From 40b8d020ec853ebcac5abc5293bd44651772bc51 Mon Sep 17 00:00:00 2001 From: jeff-zucker Date: Sat, 12 Dec 2020 22:02:30 -0800 Subject: [PATCH 01/11] first refactor --- .gitignore | 2 + bundles/Dropbox-sdk.js.map | 1 - bundles/Dropbox-sdk.min.js | 1 - bundles/browserfs.min.js | 15 - bundles/browserfs.min.js.map | 1 - bundles/utils.js | 26 - how-to-test.md | 46 -- jest.config.js | 185 ------ package-lock.json | 616 ++++++++++++------ package.json | 7 +- {src => plugins/solid-rest-bfs}/browserFS.js | 0 plugins/solid-rest-file/package.json | 12 + .../solid-rest-file/src/index.js | 23 +- plugins/solid-rest-mem/package.json | 12 + .../solid-rest-mem/src/index.js | 17 +- src/actions.js | 29 + src/container.js | 40 ++ src/error.js | 30 + src/item.js | 30 + src/request.js | 44 ++ src/response.js | 83 +++ src/rest.js | 513 +++------------ src/utils.js | 130 ++++ tests/all.js | 34 +- 24 files changed, 960 insertions(+), 937 deletions(-) delete mode 100644 bundles/Dropbox-sdk.js.map delete mode 100644 bundles/Dropbox-sdk.min.js delete mode 100644 bundles/browserfs.min.js delete mode 100644 bundles/browserfs.min.js.map delete mode 100644 bundles/utils.js delete mode 100644 how-to-test.md delete mode 100644 jest.config.js rename {src => plugins/solid-rest-bfs}/browserFS.js (100%) create mode 100644 plugins/solid-rest-file/package.json rename src/file.js => plugins/solid-rest-file/src/index.js (91%) create mode 100644 plugins/solid-rest-mem/package.json rename src/localStorage.js => plugins/solid-rest-mem/src/index.js (94%) create mode 100644 src/actions.js create mode 100644 src/container.js create mode 100644 src/error.js create mode 100644 src/item.js create mode 100644 src/request.js create mode 100644 src/response.js create mode 100644 src/utils.js diff --git a/.gitignore b/.gitignore index cad124b..419f783 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,7 @@ *~ #* +*# +.#* drafts node_modules dist diff --git a/bundles/Dropbox-sdk.js.map b/bundles/Dropbox-sdk.js.map deleted file mode 100644 index 8db0a55..0000000 --- a/bundles/Dropbox-sdk.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"Dropbox-sdk.js","sources":["../src/routes.js","../src/constants.js","../src/utils.js","../src/download-request.js","../src/upload-request.js","../node_modules/base64-js/index.js","../node_modules/ieee754/index.js","../node_modules/buffer/index.js","../src/rpc-request.js","../src/dropbox-base.js","../src/dropbox.js","../src/routes-team.js","../src/team/dropbox-team.js","../src/index.js"],"sourcesContent":["// Auto-generated by Stone, do not modify.\nvar routes = {};\n\n/**\n * Creates an OAuth 2.0 access token from the supplied OAuth 1.0 access token.\n * @function Dropbox#authTokenFromOauth1\n * @arg {AuthTokenFromOAuth1Arg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.authTokenFromOauth1 = function (arg) {\n return this.request('auth/token/from_oauth1', arg, 'app', 'api', 'rpc');\n};\n\n/**\n * Disables the access token used to authenticate the call.\n * @function Dropbox#authTokenRevoke\n * @arg {void} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.authTokenRevoke = function (arg) {\n return this.request('auth/token/revoke', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Removes all manually added contacts. You'll still keep contacts who are on\n * your team or who you imported. New contacts will be added when you share.\n * @function Dropbox#contactsDeleteManualContacts\n * @arg {void} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.contactsDeleteManualContacts = function (arg) {\n return this.request('contacts/delete_manual_contacts', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Removes manually added contacts from the given list.\n * @function Dropbox#contactsDeleteManualContactsBatch\n * @arg {ContactsDeleteManualContactsArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.contactsDeleteManualContactsBatch = function (arg) {\n return this.request('contacts/delete_manual_contacts_batch', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Add property groups to a Dropbox file. See templates/add_for_user or\n * templates/add_for_team to create new templates.\n * @function Dropbox#filePropertiesPropertiesAdd\n * @arg {FilePropertiesAddPropertiesArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.filePropertiesPropertiesAdd = function (arg) {\n return this.request('file_properties/properties/add', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Overwrite property groups associated with a file. This endpoint should be\n * used instead of properties/update when property groups are being updated via\n * a \"snapshot\" instead of via a \"delta\". In other words, this endpoint will\n * delete all omitted fields from a property group, whereas properties/update\n * will only delete fields that are explicitly marked for deletion.\n * @function Dropbox#filePropertiesPropertiesOverwrite\n * @arg {FilePropertiesOverwritePropertyGroupArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.filePropertiesPropertiesOverwrite = function (arg) {\n return this.request('file_properties/properties/overwrite', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Permanently removes the specified property group from the file. To remove\n * specific property field key value pairs, see properties/update. To update a\n * template, see templates/update_for_user or templates/update_for_team. To\n * remove a template, see templates/remove_for_user or\n * templates/remove_for_team.\n * @function Dropbox#filePropertiesPropertiesRemove\n * @arg {FilePropertiesRemovePropertiesArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.filePropertiesPropertiesRemove = function (arg) {\n return this.request('file_properties/properties/remove', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Search across property templates for particular property field values.\n * @function Dropbox#filePropertiesPropertiesSearch\n * @arg {FilePropertiesPropertiesSearchArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.filePropertiesPropertiesSearch = function (arg) {\n return this.request('file_properties/properties/search', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Once a cursor has been retrieved from properties/search, use this to paginate\n * through all search results.\n * @function Dropbox#filePropertiesPropertiesSearchContinue\n * @arg {FilePropertiesPropertiesSearchContinueArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.filePropertiesPropertiesSearchContinue = function (arg) {\n return this.request('file_properties/properties/search/continue', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Add, update or remove properties associated with the supplied file and\n * templates. This endpoint should be used instead of properties/overwrite when\n * property groups are being updated via a \"delta\" instead of via a \"snapshot\" .\n * In other words, this endpoint will not delete any omitted fields from a\n * property group, whereas properties/overwrite will delete any fields that are\n * omitted from a property group.\n * @function Dropbox#filePropertiesPropertiesUpdate\n * @arg {FilePropertiesUpdatePropertiesArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.filePropertiesPropertiesUpdate = function (arg) {\n return this.request('file_properties/properties/update', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Add a template associated with a team. See properties/add to add properties\n * to a file or folder. Note: this endpoint will create team-owned templates.\n * @function Dropbox#filePropertiesTemplatesAddForTeam\n * @arg {FilePropertiesAddTemplateArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.filePropertiesTemplatesAddForTeam = function (arg) {\n return this.request('file_properties/templates/add_for_team', arg, 'team', 'api', 'rpc');\n};\n\n/**\n * Add a template associated with a user. See properties/add to add properties\n * to a file. This endpoint can't be called on a team member or admin's behalf.\n * @function Dropbox#filePropertiesTemplatesAddForUser\n * @arg {FilePropertiesAddTemplateArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.filePropertiesTemplatesAddForUser = function (arg) {\n return this.request('file_properties/templates/add_for_user', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Get the schema for a specified template.\n * @function Dropbox#filePropertiesTemplatesGetForTeam\n * @arg {FilePropertiesGetTemplateArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.filePropertiesTemplatesGetForTeam = function (arg) {\n return this.request('file_properties/templates/get_for_team', arg, 'team', 'api', 'rpc');\n};\n\n/**\n * Get the schema for a specified template. This endpoint can't be called on a\n * team member or admin's behalf.\n * @function Dropbox#filePropertiesTemplatesGetForUser\n * @arg {FilePropertiesGetTemplateArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.filePropertiesTemplatesGetForUser = function (arg) {\n return this.request('file_properties/templates/get_for_user', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Get the template identifiers for a team. To get the schema of each template\n * use templates/get_for_team.\n * @function Dropbox#filePropertiesTemplatesListForTeam\n * @arg {void} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.filePropertiesTemplatesListForTeam = function (arg) {\n return this.request('file_properties/templates/list_for_team', arg, 'team', 'api', 'rpc');\n};\n\n/**\n * Get the template identifiers for a team. To get the schema of each template\n * use templates/get_for_user. This endpoint can't be called on a team member or\n * admin's behalf.\n * @function Dropbox#filePropertiesTemplatesListForUser\n * @arg {void} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.filePropertiesTemplatesListForUser = function (arg) {\n return this.request('file_properties/templates/list_for_user', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Permanently removes the specified template created from\n * templates/add_for_user. All properties associated with the template will also\n * be removed. This action cannot be undone.\n * @function Dropbox#filePropertiesTemplatesRemoveForTeam\n * @arg {FilePropertiesRemoveTemplateArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.filePropertiesTemplatesRemoveForTeam = function (arg) {\n return this.request('file_properties/templates/remove_for_team', arg, 'team', 'api', 'rpc');\n};\n\n/**\n * Permanently removes the specified template created from\n * templates/add_for_user. All properties associated with the template will also\n * be removed. This action cannot be undone.\n * @function Dropbox#filePropertiesTemplatesRemoveForUser\n * @arg {FilePropertiesRemoveTemplateArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.filePropertiesTemplatesRemoveForUser = function (arg) {\n return this.request('file_properties/templates/remove_for_user', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Update a template associated with a team. This route can update the template\n * name, the template description and add optional properties to templates.\n * @function Dropbox#filePropertiesTemplatesUpdateForTeam\n * @arg {FilePropertiesUpdateTemplateArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.filePropertiesTemplatesUpdateForTeam = function (arg) {\n return this.request('file_properties/templates/update_for_team', arg, 'team', 'api', 'rpc');\n};\n\n/**\n * Update a template associated with a user. This route can update the template\n * name, the template description and add optional properties to templates. This\n * endpoint can't be called on a team member or admin's behalf.\n * @function Dropbox#filePropertiesTemplatesUpdateForUser\n * @arg {FilePropertiesUpdateTemplateArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.filePropertiesTemplatesUpdateForUser = function (arg) {\n return this.request('file_properties/templates/update_for_user', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Returns the total number of file requests owned by this user. Includes both\n * open and closed file requests.\n * @function Dropbox#fileRequestsCount\n * @arg {void} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.fileRequestsCount = function (arg) {\n return this.request('file_requests/count', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Creates a file request for this user.\n * @function Dropbox#fileRequestsCreate\n * @arg {FileRequestsCreateFileRequestArgs} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.fileRequestsCreate = function (arg) {\n return this.request('file_requests/create', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Delete a batch of closed file requests.\n * @function Dropbox#fileRequestsDelete\n * @arg {FileRequestsDeleteFileRequestArgs} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.fileRequestsDelete = function (arg) {\n return this.request('file_requests/delete', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Delete all closed file requests owned by this user.\n * @function Dropbox#fileRequestsDeleteAllClosed\n * @arg {void} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.fileRequestsDeleteAllClosed = function (arg) {\n return this.request('file_requests/delete_all_closed', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Returns the specified file request.\n * @function Dropbox#fileRequestsGet\n * @arg {FileRequestsGetFileRequestArgs} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.fileRequestsGet = function (arg) {\n return this.request('file_requests/get', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Returns a list of file requests owned by this user. For apps with the app\n * folder permission, this will only return file requests with destinations in\n * the app folder.\n * @function Dropbox#fileRequestsListV2\n * @arg {FileRequestsListFileRequestsArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.fileRequestsListV2 = function (arg) {\n return this.request('file_requests/list_v2', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Returns a list of file requests owned by this user. For apps with the app\n * folder permission, this will only return file requests with destinations in\n * the app folder.\n * @function Dropbox#fileRequestsList\n * @arg {void} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.fileRequestsList = function (arg) {\n return this.request('file_requests/list', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Once a cursor has been retrieved from list_v2, use this to paginate through\n * all file requests. The cursor must come from a previous call to list_v2 or\n * list/continue.\n * @function Dropbox#fileRequestsListContinue\n * @arg {FileRequestsListFileRequestsContinueArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.fileRequestsListContinue = function (arg) {\n return this.request('file_requests/list/continue', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Update a file request.\n * @function Dropbox#fileRequestsUpdate\n * @arg {FileRequestsUpdateFileRequestArgs} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.fileRequestsUpdate = function (arg) {\n return this.request('file_requests/update', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Returns the metadata for a file or folder. This is an alpha endpoint\n * compatible with the properties API. Note: Metadata for the root folder is\n * unsupported.\n * @function Dropbox#filesAlphaGetMetadata\n * @deprecated\n * @arg {FilesAlphaGetMetadataArg} arg - The request parameters.\n * @returns {Promise.<(FilesFileMetadata|FilesFolderMetadata|FilesDeletedMetadata), Error.>}\n */\nroutes.filesAlphaGetMetadata = function (arg) {\n return this.request('files/alpha/get_metadata', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Create a new file with the contents provided in the request. Note that this\n * endpoint is part of the properties API alpha and is slightly different from\n * upload. Do not use this to upload a file larger than 150 MB. Instead, create\n * an upload session with upload_session/start.\n * @function Dropbox#filesAlphaUpload\n * @deprecated\n * @arg {FilesCommitInfoWithProperties} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.filesAlphaUpload = function (arg) {\n return this.request('files/alpha/upload', arg, 'user', 'content', 'upload');\n};\n\n/**\n * Copy a file or folder to a different location in the user's Dropbox. If the\n * source path is a folder all its contents will be copied.\n * @function Dropbox#filesCopyV2\n * @arg {FilesRelocationArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.filesCopyV2 = function (arg) {\n return this.request('files/copy_v2', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Copy a file or folder to a different location in the user's Dropbox. If the\n * source path is a folder all its contents will be copied.\n * @function Dropbox#filesCopy\n * @deprecated\n * @arg {FilesRelocationArg} arg - The request parameters.\n * @returns {Promise.<(FilesFileMetadata|FilesFolderMetadata|FilesDeletedMetadata), Error.>}\n */\nroutes.filesCopy = function (arg) {\n return this.request('files/copy', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Copy multiple files or folders to different locations at once in the user's\n * Dropbox. This route will replace copy_batch. The main difference is this\n * route will return status for each entry, while copy_batch raises failure if\n * any entry fails. This route will either finish synchronously, or return a job\n * ID and do the async copy job in background. Please use copy_batch/check_v2 to\n * check the job status.\n * @function Dropbox#filesCopyBatchV2\n * @arg {Object} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.filesCopyBatchV2 = function (arg) {\n return this.request('files/copy_batch_v2', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Copy multiple files or folders to different locations at once in the user's\n * Dropbox. If RelocationBatchArg.allow_shared_folder is false, this route is\n * atomic. If one entry fails, the whole transaction will abort. If\n * RelocationBatchArg.allow_shared_folder is true, atomicity is not guaranteed,\n * but it allows you to copy the contents of shared folders to new locations.\n * This route will return job ID immediately and do the async copy job in\n * background. Please use copy_batch/check to check the job status.\n * @function Dropbox#filesCopyBatch\n * @deprecated\n * @arg {FilesRelocationBatchArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.filesCopyBatch = function (arg) {\n return this.request('files/copy_batch', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Returns the status of an asynchronous job for copy_batch_v2. It returns list\n * of results for each entry.\n * @function Dropbox#filesCopyBatchCheckV2\n * @arg {AsyncPollArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.filesCopyBatchCheckV2 = function (arg) {\n return this.request('files/copy_batch/check_v2', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Returns the status of an asynchronous job for copy_batch. If success, it\n * returns list of results for each entry.\n * @function Dropbox#filesCopyBatchCheck\n * @deprecated\n * @arg {AsyncPollArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.filesCopyBatchCheck = function (arg) {\n return this.request('files/copy_batch/check', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Get a copy reference to a file or folder. This reference string can be used\n * to save that file or folder to another user's Dropbox by passing it to\n * copy_reference/save.\n * @function Dropbox#filesCopyReferenceGet\n * @arg {FilesGetCopyReferenceArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.filesCopyReferenceGet = function (arg) {\n return this.request('files/copy_reference/get', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Save a copy reference returned by copy_reference/get to the user's Dropbox.\n * @function Dropbox#filesCopyReferenceSave\n * @arg {FilesSaveCopyReferenceArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.filesCopyReferenceSave = function (arg) {\n return this.request('files/copy_reference/save', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Create a folder at a given path.\n * @function Dropbox#filesCreateFolderV2\n * @arg {FilesCreateFolderArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.filesCreateFolderV2 = function (arg) {\n return this.request('files/create_folder_v2', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Create a folder at a given path.\n * @function Dropbox#filesCreateFolder\n * @deprecated\n * @arg {FilesCreateFolderArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.filesCreateFolder = function (arg) {\n return this.request('files/create_folder', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Create multiple folders at once. This route is asynchronous for large\n * batches, which returns a job ID immediately and runs the create folder batch\n * asynchronously. Otherwise, creates the folders and returns the result\n * synchronously for smaller inputs. You can force asynchronous behaviour by\n * using the CreateFolderBatchArg.force_async flag. Use\n * create_folder_batch/check to check the job status.\n * @function Dropbox#filesCreateFolderBatch\n * @arg {FilesCreateFolderBatchArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.filesCreateFolderBatch = function (arg) {\n return this.request('files/create_folder_batch', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Returns the status of an asynchronous job for create_folder_batch. If\n * success, it returns list of result for each entry.\n * @function Dropbox#filesCreateFolderBatchCheck\n * @arg {AsyncPollArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.filesCreateFolderBatchCheck = function (arg) {\n return this.request('files/create_folder_batch/check', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Delete the file or folder at a given path. If the path is a folder, all its\n * contents will be deleted too. A successful response indicates that the file\n * or folder was deleted. The returned metadata will be the corresponding\n * FileMetadata or FolderMetadata for the item at time of deletion, and not a\n * DeletedMetadata object.\n * @function Dropbox#filesDeleteV2\n * @arg {FilesDeleteArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.filesDeleteV2 = function (arg) {\n return this.request('files/delete_v2', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Delete the file or folder at a given path. If the path is a folder, all its\n * contents will be deleted too. A successful response indicates that the file\n * or folder was deleted. The returned metadata will be the corresponding\n * FileMetadata or FolderMetadata for the item at time of deletion, and not a\n * DeletedMetadata object.\n * @function Dropbox#filesDelete\n * @deprecated\n * @arg {FilesDeleteArg} arg - The request parameters.\n * @returns {Promise.<(FilesFileMetadata|FilesFolderMetadata|FilesDeletedMetadata), Error.>}\n */\nroutes.filesDelete = function (arg) {\n return this.request('files/delete', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Delete multiple files/folders at once. This route is asynchronous, which\n * returns a job ID immediately and runs the delete batch asynchronously. Use\n * delete_batch/check to check the job status.\n * @function Dropbox#filesDeleteBatch\n * @arg {FilesDeleteBatchArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.filesDeleteBatch = function (arg) {\n return this.request('files/delete_batch', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Returns the status of an asynchronous job for delete_batch. If success, it\n * returns list of result for each entry.\n * @function Dropbox#filesDeleteBatchCheck\n * @arg {AsyncPollArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.filesDeleteBatchCheck = function (arg) {\n return this.request('files/delete_batch/check', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Download a file from a user's Dropbox.\n * @function Dropbox#filesDownload\n * @arg {FilesDownloadArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.filesDownload = function (arg) {\n return this.request('files/download', arg, 'user', 'content', 'download');\n};\n\n/**\n * Download a folder from the user's Dropbox, as a zip file. The folder must be\n * less than 20 GB in size and have fewer than 10,000 total files. The input\n * cannot be a single file. Any single file must be less than 4GB in size.\n * @function Dropbox#filesDownloadZip\n * @arg {FilesDownloadZipArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.filesDownloadZip = function (arg) {\n return this.request('files/download_zip', arg, 'user', 'content', 'download');\n};\n\n/**\n * Export a file from a user's Dropbox. This route only supports exporting files\n * that cannot be downloaded directly and whose ExportResult.file_metadata has\n * ExportInfo.export_as populated.\n * @function Dropbox#filesExport\n * @arg {FilesExportArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.filesExport = function (arg) {\n return this.request('files/export', arg, 'user', 'content', 'download');\n};\n\n/**\n * Returns the metadata for a file or folder. Note: Metadata for the root folder\n * is unsupported.\n * @function Dropbox#filesGetMetadata\n * @arg {FilesGetMetadataArg} arg - The request parameters.\n * @returns {Promise.<(FilesFileMetadata|FilesFolderMetadata|FilesDeletedMetadata), Error.>}\n */\nroutes.filesGetMetadata = function (arg) {\n return this.request('files/get_metadata', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Get a preview for a file. Currently, PDF previews are generated for files\n * with the following extensions: .ai, .doc, .docm, .docx, .eps, .gdoc,\n * .gslides, .odp, .odt, .pps, .ppsm, .ppsx, .ppt, .pptm, .pptx, .rtf. HTML\n * previews are generated for files with the following extensions: .csv, .ods,\n * .xls, .xlsm, .gsheet, .xlsx. Other formats will return an unsupported\n * extension error.\n * @function Dropbox#filesGetPreview\n * @arg {FilesPreviewArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.filesGetPreview = function (arg) {\n return this.request('files/get_preview', arg, 'user', 'content', 'download');\n};\n\n/**\n * Get a temporary link to stream content of a file. This link will expire in\n * four hours and afterwards you will get 410 Gone. This URL should not be used\n * to display content directly in the browser. The Content-Type of the link is\n * determined automatically by the file's mime type.\n * @function Dropbox#filesGetTemporaryLink\n * @arg {FilesGetTemporaryLinkArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.filesGetTemporaryLink = function (arg) {\n return this.request('files/get_temporary_link', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Get a one-time use temporary upload link to upload a file to a Dropbox\n * location. This endpoint acts as a delayed upload. The returned temporary\n * upload link may be used to make a POST request with the data to be uploaded.\n * The upload will then be perfomed with the CommitInfo previously provided to\n * get_temporary_upload_link but evaluated only upon consumption. Hence, errors\n * stemming from invalid CommitInfo with respect to the state of the user's\n * Dropbox will only be communicated at consumption time. Additionally, these\n * errors are surfaced as generic HTTP 409 Conflict responses, potentially\n * hiding issue details. The maximum temporary upload link duration is 4 hours.\n * Upon consumption or expiration, a new link will have to be generated.\n * Multiple links may exist for a specific upload path at any given time. The\n * POST request on the temporary upload link must have its Content-Type set to\n * \"application/octet-stream\". Example temporary upload link consumption\n * request: curl -X POST\n * https://dl.dropboxusercontent.com/apitul/1/bNi2uIYF51cVBND --header\n * \"Content-Type: application/octet-stream\" --data-binary @local_file.txt A\n * successful temporary upload link consumption request returns the content hash\n * of the uploaded data in JSON format. Example succesful temporary upload link\n * consumption response: {\"content-hash\":\n * \"599d71033d700ac892a0e48fa61b125d2f5994\"} An unsuccessful temporary upload\n * link consumption request returns any of the following status codes: HTTP 400\n * Bad Request: Content-Type is not one of application/octet-stream and\n * text/plain or request is invalid. HTTP 409 Conflict: The temporary upload\n * link does not exist or is currently unavailable, the upload failed, or\n * another error happened. HTTP 410 Gone: The temporary upload link is expired\n * or consumed. Example unsuccessful temporary upload link consumption\n * response: Temporary upload link has been recently consumed.\n * @function Dropbox#filesGetTemporaryUploadLink\n * @arg {FilesGetTemporaryUploadLinkArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.filesGetTemporaryUploadLink = function (arg) {\n return this.request('files/get_temporary_upload_link', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Get a thumbnail for an image. This method currently supports files with the\n * following file extensions: jpg, jpeg, png, tiff, tif, gif and bmp. Photos\n * that are larger than 20MB in size won't be converted to a thumbnail.\n * @function Dropbox#filesGetThumbnail\n * @arg {FilesThumbnailArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.filesGetThumbnail = function (arg) {\n return this.request('files/get_thumbnail', arg, 'user', 'content', 'download');\n};\n\n/**\n * Get thumbnails for a list of images. We allow up to 25 thumbnails in a single\n * batch. This method currently supports files with the following file\n * extensions: jpg, jpeg, png, tiff, tif, gif and bmp. Photos that are larger\n * than 20MB in size won't be converted to a thumbnail.\n * @function Dropbox#filesGetThumbnailBatch\n * @arg {FilesGetThumbnailBatchArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.filesGetThumbnailBatch = function (arg) {\n return this.request('files/get_thumbnail_batch', arg, 'user', 'content', 'rpc');\n};\n\n/**\n * Starts returning the contents of a folder. If the result's\n * ListFolderResult.has_more field is true, call list_folder/continue with the\n * returned ListFolderResult.cursor to retrieve more entries. If you're using\n * ListFolderArg.recursive set to true to keep a local cache of the contents of\n * a Dropbox account, iterate through each entry in order and process them as\n * follows to keep your local state in sync: For each FileMetadata, store the\n * new entry at the given path in your local state. If the required parent\n * folders don't exist yet, create them. If there's already something else at\n * the given path, replace it and remove all its children. For each\n * FolderMetadata, store the new entry at the given path in your local state. If\n * the required parent folders don't exist yet, create them. If there's already\n * something else at the given path, replace it but leave the children as they\n * are. Check the new entry's FolderSharingInfo.read_only and set all its\n * children's read-only statuses to match. For each DeletedMetadata, if your\n * local state has something at the given path, remove it and all its children.\n * If there's nothing at the given path, ignore this entry. Note:\n * auth.RateLimitError may be returned if multiple list_folder or\n * list_folder/continue calls with same parameters are made simultaneously by\n * same API app for same user. If your app implements retry logic, please hold\n * off the retry until the previous request finishes.\n * @function Dropbox#filesListFolder\n * @arg {FilesListFolderArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.filesListFolder = function (arg) {\n return this.request('files/list_folder', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Once a cursor has been retrieved from list_folder, use this to paginate\n * through all files and retrieve updates to the folder, following the same\n * rules as documented for list_folder.\n * @function Dropbox#filesListFolderContinue\n * @arg {FilesListFolderContinueArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.filesListFolderContinue = function (arg) {\n return this.request('files/list_folder/continue', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * A way to quickly get a cursor for the folder's state. Unlike list_folder,\n * list_folder/get_latest_cursor doesn't return any entries. This endpoint is\n * for app which only needs to know about new files and modifications and\n * doesn't need to know about files that already exist in Dropbox.\n * @function Dropbox#filesListFolderGetLatestCursor\n * @arg {FilesListFolderArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.filesListFolderGetLatestCursor = function (arg) {\n return this.request('files/list_folder/get_latest_cursor', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * A longpoll endpoint to wait for changes on an account. In conjunction with\n * list_folder/continue, this call gives you a low-latency way to monitor an\n * account for file changes. The connection will block until there are changes\n * available or a timeout occurs. This endpoint is useful mostly for client-side\n * apps. If you're looking for server-side notifications, check out our webhooks\n * documentation https://www.dropbox.com/developers/reference/webhooks.\n * @function Dropbox#filesListFolderLongpoll\n * @arg {FilesListFolderLongpollArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.filesListFolderLongpoll = function (arg) {\n return this.request('files/list_folder/longpoll', arg, 'noauth', 'notify', 'rpc');\n};\n\n/**\n * Returns revisions for files based on a file path or a file id. The file path\n * or file id is identified from the latest file entry at the given file path or\n * id. This end point allows your app to query either by file path or file id by\n * setting the mode parameter appropriately. In the ListRevisionsMode.path\n * (default) mode, all revisions at the same file path as the latest file entry\n * are returned. If revisions with the same file id are desired, then mode must\n * be set to ListRevisionsMode.id. The ListRevisionsMode.id mode is useful to\n * retrieve revisions for a given file across moves or renames.\n * @function Dropbox#filesListRevisions\n * @arg {FilesListRevisionsArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.filesListRevisions = function (arg) {\n return this.request('files/list_revisions', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Move a file or folder to a different location in the user's Dropbox. If the\n * source path is a folder all its contents will be moved.\n * @function Dropbox#filesMoveV2\n * @arg {FilesRelocationArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.filesMoveV2 = function (arg) {\n return this.request('files/move_v2', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Move a file or folder to a different location in the user's Dropbox. If the\n * source path is a folder all its contents will be moved.\n * @function Dropbox#filesMove\n * @deprecated\n * @arg {FilesRelocationArg} arg - The request parameters.\n * @returns {Promise.<(FilesFileMetadata|FilesFolderMetadata|FilesDeletedMetadata), Error.>}\n */\nroutes.filesMove = function (arg) {\n return this.request('files/move', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Move multiple files or folders to different locations at once in the user's\n * Dropbox. This route will replace move_batch. The main difference is this\n * route will return status for each entry, while move_batch raises failure if\n * any entry fails. This route will either finish synchronously, or return a job\n * ID and do the async move job in background. Please use move_batch/check_v2 to\n * check the job status.\n * @function Dropbox#filesMoveBatchV2\n * @arg {FilesMoveBatchArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.filesMoveBatchV2 = function (arg) {\n return this.request('files/move_batch_v2', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Move multiple files or folders to different locations at once in the user's\n * Dropbox. This route is 'all or nothing', which means if one entry fails, the\n * whole transaction will abort. This route will return job ID immediately and\n * do the async moving job in background. Please use move_batch/check to check\n * the job status.\n * @function Dropbox#filesMoveBatch\n * @arg {FilesRelocationBatchArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.filesMoveBatch = function (arg) {\n return this.request('files/move_batch', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Returns the status of an asynchronous job for move_batch_v2. It returns list\n * of results for each entry.\n * @function Dropbox#filesMoveBatchCheckV2\n * @arg {AsyncPollArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.filesMoveBatchCheckV2 = function (arg) {\n return this.request('files/move_batch/check_v2', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Returns the status of an asynchronous job for move_batch. If success, it\n * returns list of results for each entry.\n * @function Dropbox#filesMoveBatchCheck\n * @arg {AsyncPollArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.filesMoveBatchCheck = function (arg) {\n return this.request('files/move_batch/check', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Permanently delete the file or folder at a given path (see\n * https://www.dropbox.com/en/help/40). Note: This endpoint is only available\n * for Dropbox Business apps.\n * @function Dropbox#filesPermanentlyDelete\n * @arg {FilesDeleteArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.filesPermanentlyDelete = function (arg) {\n return this.request('files/permanently_delete', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * @function Dropbox#filesPropertiesAdd\n * @deprecated\n * @arg {FilePropertiesAddPropertiesArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.filesPropertiesAdd = function (arg) {\n return this.request('files/properties/add', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * @function Dropbox#filesPropertiesOverwrite\n * @deprecated\n * @arg {FilePropertiesOverwritePropertyGroupArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.filesPropertiesOverwrite = function (arg) {\n return this.request('files/properties/overwrite', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * @function Dropbox#filesPropertiesRemove\n * @deprecated\n * @arg {FilePropertiesRemovePropertiesArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.filesPropertiesRemove = function (arg) {\n return this.request('files/properties/remove', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * @function Dropbox#filesPropertiesTemplateGet\n * @deprecated\n * @arg {FilePropertiesGetTemplateArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.filesPropertiesTemplateGet = function (arg) {\n return this.request('files/properties/template/get', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * @function Dropbox#filesPropertiesTemplateList\n * @deprecated\n * @arg {void} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.filesPropertiesTemplateList = function (arg) {\n return this.request('files/properties/template/list', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * @function Dropbox#filesPropertiesUpdate\n * @deprecated\n * @arg {FilePropertiesUpdatePropertiesArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.filesPropertiesUpdate = function (arg) {\n return this.request('files/properties/update', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Restore a specific revision of a file to the given path.\n * @function Dropbox#filesRestore\n * @arg {FilesRestoreArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.filesRestore = function (arg) {\n return this.request('files/restore', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Save the data from a specified URL into a file in user's Dropbox. Note that\n * the transfer from the URL must complete within 5 minutes, or the operation\n * will time out and the job will fail. If the given path already exists, the\n * file will be renamed to avoid the conflict (e.g. myfile (1).txt).\n * @function Dropbox#filesSaveUrl\n * @arg {FilesSaveUrlArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.filesSaveUrl = function (arg) {\n return this.request('files/save_url', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Check the status of a save_url job.\n * @function Dropbox#filesSaveUrlCheckJobStatus\n * @arg {AsyncPollArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.filesSaveUrlCheckJobStatus = function (arg) {\n return this.request('files/save_url/check_job_status', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Searches for files and folders. Note: Recent changes may not immediately be\n * reflected in search results due to a short delay in indexing.\n * @function Dropbox#filesSearch\n * @arg {FilesSearchArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.filesSearch = function (arg) {\n return this.request('files/search', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Create a new file with the contents provided in the request. Do not use this\n * to upload a file larger than 150 MB. Instead, create an upload session with\n * upload_session/start. Calls to this endpoint will count as data transport\n * calls for any Dropbox Business teams with a limit on the number of data\n * transport calls allowed per month. For more information, see the Data\n * transport limit page\n * https://www.dropbox.com/developers/reference/data-transport-limit.\n * @function Dropbox#filesUpload\n * @arg {FilesCommitInfo} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.filesUpload = function (arg) {\n return this.request('files/upload', arg, 'user', 'content', 'upload');\n};\n\n/**\n * Append more data to an upload session. When the parameter close is set, this\n * call will close the session. A single request should not upload more than 150\n * MB. The maximum size of a file one can upload to an upload session is 350 GB.\n * Calls to this endpoint will count as data transport calls for any Dropbox\n * Business teams with a limit on the number of data transport calls allowed per\n * month. For more information, see the Data transport limit page\n * https://www.dropbox.com/developers/reference/data-transport-limit.\n * @function Dropbox#filesUploadSessionAppendV2\n * @arg {FilesUploadSessionAppendArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.filesUploadSessionAppendV2 = function (arg) {\n return this.request('files/upload_session/append_v2', arg, 'user', 'content', 'upload');\n};\n\n/**\n * Append more data to an upload session. A single request should not upload\n * more than 150 MB. The maximum size of a file one can upload to an upload\n * session is 350 GB. Calls to this endpoint will count as data transport calls\n * for any Dropbox Business teams with a limit on the number of data transport\n * calls allowed per month. For more information, see the Data transport limit\n * page https://www.dropbox.com/developers/reference/data-transport-limit.\n * @function Dropbox#filesUploadSessionAppend\n * @deprecated\n * @arg {FilesUploadSessionCursor} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.filesUploadSessionAppend = function (arg) {\n return this.request('files/upload_session/append', arg, 'user', 'content', 'upload');\n};\n\n/**\n * Finish an upload session and save the uploaded data to the given file path. A\n * single request should not upload more than 150 MB. The maximum size of a file\n * one can upload to an upload session is 350 GB. Calls to this endpoint will\n * count as data transport calls for any Dropbox Business teams with a limit on\n * the number of data transport calls allowed per month. For more information,\n * see the Data transport limit page\n * https://www.dropbox.com/developers/reference/data-transport-limit.\n * @function Dropbox#filesUploadSessionFinish\n * @arg {FilesUploadSessionFinishArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.filesUploadSessionFinish = function (arg) {\n return this.request('files/upload_session/finish', arg, 'user', 'content', 'upload');\n};\n\n/**\n * This route helps you commit many files at once into a user's Dropbox. Use\n * upload_session/start and upload_session/append_v2 to upload file contents. We\n * recommend uploading many files in parallel to increase throughput. Once the\n * file contents have been uploaded, rather than calling upload_session/finish,\n * use this route to finish all your upload sessions in a single request.\n * UploadSessionStartArg.close or UploadSessionAppendArg.close needs to be true\n * for the last upload_session/start or upload_session/append_v2 call. The\n * maximum size of a file one can upload to an upload session is 350 GB. This\n * route will return a job_id immediately and do the async commit job in\n * background. Use upload_session/finish_batch/check to check the job status.\n * For the same account, this route should be executed serially. That means you\n * should not start the next job before current job finishes. We allow up to\n * 1000 entries in a single request. Calls to this endpoint will count as data\n * transport calls for any Dropbox Business teams with a limit on the number of\n * data transport calls allowed per month. For more information, see the Data\n * transport limit page\n * https://www.dropbox.com/developers/reference/data-transport-limit.\n * @function Dropbox#filesUploadSessionFinishBatch\n * @arg {FilesUploadSessionFinishBatchArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.filesUploadSessionFinishBatch = function (arg) {\n return this.request('files/upload_session/finish_batch', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Returns the status of an asynchronous job for upload_session/finish_batch. If\n * success, it returns list of result for each entry.\n * @function Dropbox#filesUploadSessionFinishBatchCheck\n * @arg {AsyncPollArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.filesUploadSessionFinishBatchCheck = function (arg) {\n return this.request('files/upload_session/finish_batch/check', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Upload sessions allow you to upload a single file in one or more requests,\n * for example where the size of the file is greater than 150 MB. This call\n * starts a new upload session with the given data. You can then use\n * upload_session/append_v2 to add more data and upload_session/finish to save\n * all the data to a file in Dropbox. A single request should not upload more\n * than 150 MB. The maximum size of a file one can upload to an upload session\n * is 350 GB. An upload session can be used for a maximum of 48 hours.\n * Attempting to use an UploadSessionStartResult.session_id with\n * upload_session/append_v2 or upload_session/finish more than 48 hours after\n * its creation will return a UploadSessionLookupError.not_found. Calls to this\n * endpoint will count as data transport calls for any Dropbox Business teams\n * with a limit on the number of data transport calls allowed per month. For\n * more information, see the Data transport limit page\n * https://www.dropbox.com/developers/reference/data-transport-limit.\n * @function Dropbox#filesUploadSessionStart\n * @arg {FilesUploadSessionStartArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.filesUploadSessionStart = function (arg) {\n return this.request('files/upload_session/start', arg, 'user', 'content', 'upload');\n};\n\n/**\n * Marks the given Paper doc as archived. Note: This action can be performed or\n * undone by anyone with edit permissions to the doc.\n * @function Dropbox#paperDocsArchive\n * @arg {PaperRefPaperDoc} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.paperDocsArchive = function (arg) {\n return this.request('paper/docs/archive', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Creates a new Paper doc with the provided content.\n * @function Dropbox#paperDocsCreate\n * @arg {PaperPaperDocCreateArgs} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.paperDocsCreate = function (arg) {\n return this.request('paper/docs/create', arg, 'user', 'api', 'upload');\n};\n\n/**\n * Exports and downloads Paper doc either as HTML or markdown.\n * @function Dropbox#paperDocsDownload\n * @arg {PaperPaperDocExport} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.paperDocsDownload = function (arg) {\n return this.request('paper/docs/download', arg, 'user', 'api', 'download');\n};\n\n/**\n * Lists the users who are explicitly invited to the Paper folder in which the\n * Paper doc is contained. For private folders all users (including owner)\n * shared on the folder are listed and for team folders all non-team users\n * shared on the folder are returned.\n * @function Dropbox#paperDocsFolderUsersList\n * @arg {PaperListUsersOnFolderArgs} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.paperDocsFolderUsersList = function (arg) {\n return this.request('paper/docs/folder_users/list', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Once a cursor has been retrieved from docs/folder_users/list, use this to\n * paginate through all users on the Paper folder.\n * @function Dropbox#paperDocsFolderUsersListContinue\n * @arg {PaperListUsersOnFolderContinueArgs} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.paperDocsFolderUsersListContinue = function (arg) {\n return this.request('paper/docs/folder_users/list/continue', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Retrieves folder information for the given Paper doc. This includes: -\n * folder sharing policy; permissions for subfolders are set by the top-level\n * folder. - full 'filepath', i.e. the list of folders (both folderId and\n * folderName) from the root folder to the folder directly containing the\n * Paper doc. Note: If the Paper doc is not in any folder (aka unfiled) the\n * response will be empty.\n * @function Dropbox#paperDocsGetFolderInfo\n * @arg {PaperRefPaperDoc} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.paperDocsGetFolderInfo = function (arg) {\n return this.request('paper/docs/get_folder_info', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Return the list of all Paper docs according to the argument specifications.\n * To iterate over through the full pagination, pass the cursor to\n * docs/list/continue.\n * @function Dropbox#paperDocsList\n * @arg {PaperListPaperDocsArgs} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.paperDocsList = function (arg) {\n return this.request('paper/docs/list', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Once a cursor has been retrieved from docs/list, use this to paginate through\n * all Paper doc.\n * @function Dropbox#paperDocsListContinue\n * @arg {PaperListPaperDocsContinueArgs} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.paperDocsListContinue = function (arg) {\n return this.request('paper/docs/list/continue', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Permanently deletes the given Paper doc. This operation is final as the doc\n * cannot be recovered. Note: This action can be performed only by the doc\n * owner.\n * @function Dropbox#paperDocsPermanentlyDelete\n * @arg {PaperRefPaperDoc} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.paperDocsPermanentlyDelete = function (arg) {\n return this.request('paper/docs/permanently_delete', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Gets the default sharing policy for the given Paper doc.\n * @function Dropbox#paperDocsSharingPolicyGet\n * @arg {PaperRefPaperDoc} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.paperDocsSharingPolicyGet = function (arg) {\n return this.request('paper/docs/sharing_policy/get', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Sets the default sharing policy for the given Paper doc. The default\n * 'team_sharing_policy' can be changed only by teams, omit this field for\n * personal accounts. Note: 'public_sharing_policy' cannot be set to the value\n * 'disabled' because this setting can be changed only via the team admin\n * console.\n * @function Dropbox#paperDocsSharingPolicySet\n * @arg {PaperPaperDocSharingPolicy} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.paperDocsSharingPolicySet = function (arg) {\n return this.request('paper/docs/sharing_policy/set', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Updates an existing Paper doc with the provided content.\n * @function Dropbox#paperDocsUpdate\n * @arg {PaperPaperDocUpdateArgs} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.paperDocsUpdate = function (arg) {\n return this.request('paper/docs/update', arg, 'user', 'api', 'upload');\n};\n\n/**\n * Allows an owner or editor to add users to a Paper doc or change their\n * permissions using their email address or Dropbox account ID. Note: The Doc\n * owner's permissions cannot be changed.\n * @function Dropbox#paperDocsUsersAdd\n * @arg {PaperAddPaperDocUser} arg - The request parameters.\n * @returns {Promise., Error.>}\n */\nroutes.paperDocsUsersAdd = function (arg) {\n return this.request('paper/docs/users/add', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Lists all users who visited the Paper doc or users with explicit access. This\n * call excludes users who have been removed. The list is sorted by the date of\n * the visit or the share date. The list will include both users, the explicitly\n * shared ones as well as those who came in using the Paper url link.\n * @function Dropbox#paperDocsUsersList\n * @arg {PaperListUsersOnPaperDocArgs} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.paperDocsUsersList = function (arg) {\n return this.request('paper/docs/users/list', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Once a cursor has been retrieved from docs/users/list, use this to paginate\n * through all users on the Paper doc.\n * @function Dropbox#paperDocsUsersListContinue\n * @arg {PaperListUsersOnPaperDocContinueArgs} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.paperDocsUsersListContinue = function (arg) {\n return this.request('paper/docs/users/list/continue', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Allows an owner or editor to remove users from a Paper doc using their email\n * address or Dropbox account ID. Note: Doc owner cannot be removed.\n * @function Dropbox#paperDocsUsersRemove\n * @arg {PaperRemovePaperDocUser} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.paperDocsUsersRemove = function (arg) {\n return this.request('paper/docs/users/remove', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Adds specified members to a file.\n * @function Dropbox#sharingAddFileMember\n * @arg {SharingAddFileMemberArgs} arg - The request parameters.\n * @returns {Promise., Error.>}\n */\nroutes.sharingAddFileMember = function (arg) {\n return this.request('sharing/add_file_member', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Allows an owner or editor (if the ACL update policy allows) of a shared\n * folder to add another member. For the new member to get access to all the\n * functionality for this folder, you will need to call mount_folder on their\n * behalf.\n * @function Dropbox#sharingAddFolderMember\n * @arg {SharingAddFolderMemberArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.sharingAddFolderMember = function (arg) {\n return this.request('sharing/add_folder_member', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Identical to update_file_member but with less information returned.\n * @function Dropbox#sharingChangeFileMemberAccess\n * @deprecated\n * @arg {SharingChangeFileMemberAccessArgs} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.sharingChangeFileMemberAccess = function (arg) {\n return this.request('sharing/change_file_member_access', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Returns the status of an asynchronous job.\n * @function Dropbox#sharingCheckJobStatus\n * @arg {AsyncPollArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.sharingCheckJobStatus = function (arg) {\n return this.request('sharing/check_job_status', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Returns the status of an asynchronous job for sharing a folder.\n * @function Dropbox#sharingCheckRemoveMemberJobStatus\n * @arg {AsyncPollArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.sharingCheckRemoveMemberJobStatus = function (arg) {\n return this.request('sharing/check_remove_member_job_status', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Returns the status of an asynchronous job for sharing a folder.\n * @function Dropbox#sharingCheckShareJobStatus\n * @arg {AsyncPollArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.sharingCheckShareJobStatus = function (arg) {\n return this.request('sharing/check_share_job_status', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Create a shared link. If a shared link already exists for the given path,\n * that link is returned. Note that in the returned PathLinkMetadata, the\n * PathLinkMetadata.url field is the shortened URL if\n * CreateSharedLinkArg.short_url argument is set to true. Previously, it was\n * technically possible to break a shared link by moving or renaming the\n * corresponding file or folder. In the future, this will no longer be the case,\n * so your app shouldn't rely on this behavior. Instead, if your app needs to\n * revoke a shared link, use revoke_shared_link.\n * @function Dropbox#sharingCreateSharedLink\n * @deprecated\n * @arg {SharingCreateSharedLinkArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.sharingCreateSharedLink = function (arg) {\n return this.request('sharing/create_shared_link', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Create a shared link with custom settings. If no settings are given then the\n * default visibility is RequestedVisibility.public (The resolved visibility,\n * though, may depend on other aspects such as team and shared folder settings).\n * @function Dropbox#sharingCreateSharedLinkWithSettings\n * @arg {SharingCreateSharedLinkWithSettingsArg} arg - The request parameters.\n * @returns {Promise.<(SharingFileLinkMetadata|SharingFolderLinkMetadata|SharingSharedLinkMetadata), Error.>}\n */\nroutes.sharingCreateSharedLinkWithSettings = function (arg) {\n return this.request('sharing/create_shared_link_with_settings', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Returns shared file metadata.\n * @function Dropbox#sharingGetFileMetadata\n * @arg {SharingGetFileMetadataArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.sharingGetFileMetadata = function (arg) {\n return this.request('sharing/get_file_metadata', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Returns shared file metadata.\n * @function Dropbox#sharingGetFileMetadataBatch\n * @arg {SharingGetFileMetadataBatchArg} arg - The request parameters.\n * @returns {Promise., Error.>}\n */\nroutes.sharingGetFileMetadataBatch = function (arg) {\n return this.request('sharing/get_file_metadata/batch', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Returns shared folder metadata by its folder ID.\n * @function Dropbox#sharingGetFolderMetadata\n * @arg {SharingGetMetadataArgs} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.sharingGetFolderMetadata = function (arg) {\n return this.request('sharing/get_folder_metadata', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Download the shared link's file from a user's Dropbox.\n * @function Dropbox#sharingGetSharedLinkFile\n * @arg {Object} arg - The request parameters.\n * @returns {Promise.<(SharingFileLinkMetadata|SharingFolderLinkMetadata|SharingSharedLinkMetadata), Error.>}\n */\nroutes.sharingGetSharedLinkFile = function (arg) {\n return this.request('sharing/get_shared_link_file', arg, 'user', 'content', 'download');\n};\n\n/**\n * Get the shared link's metadata.\n * @function Dropbox#sharingGetSharedLinkMetadata\n * @arg {SharingGetSharedLinkMetadataArg} arg - The request parameters.\n * @returns {Promise.<(SharingFileLinkMetadata|SharingFolderLinkMetadata|SharingSharedLinkMetadata), Error.>}\n */\nroutes.sharingGetSharedLinkMetadata = function (arg) {\n return this.request('sharing/get_shared_link_metadata', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Returns a list of LinkMetadata objects for this user, including collection\n * links. If no path is given, returns a list of all shared links for the\n * current user, including collection links, up to a maximum of 1000 links. If a\n * non-empty path is given, returns a list of all shared links that allow access\n * to the given path. Collection links are never returned in this case. Note\n * that the url field in the response is never the shortened URL.\n * @function Dropbox#sharingGetSharedLinks\n * @deprecated\n * @arg {SharingGetSharedLinksArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.sharingGetSharedLinks = function (arg) {\n return this.request('sharing/get_shared_links', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Use to obtain the members who have been invited to a file, both inherited and\n * uninherited members.\n * @function Dropbox#sharingListFileMembers\n * @arg {SharingListFileMembersArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.sharingListFileMembers = function (arg) {\n return this.request('sharing/list_file_members', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Get members of multiple files at once. The arguments to this route are more\n * limited, and the limit on query result size per file is more strict. To\n * customize the results more, use the individual file endpoint. Inherited users\n * and groups are not included in the result, and permissions are not returned\n * for this endpoint.\n * @function Dropbox#sharingListFileMembersBatch\n * @arg {SharingListFileMembersBatchArg} arg - The request parameters.\n * @returns {Promise., Error.>}\n */\nroutes.sharingListFileMembersBatch = function (arg) {\n return this.request('sharing/list_file_members/batch', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Once a cursor has been retrieved from list_file_members or\n * list_file_members/batch, use this to paginate through all shared file\n * members.\n * @function Dropbox#sharingListFileMembersContinue\n * @arg {SharingListFileMembersContinueArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.sharingListFileMembersContinue = function (arg) {\n return this.request('sharing/list_file_members/continue', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Returns shared folder membership by its folder ID.\n * @function Dropbox#sharingListFolderMembers\n * @arg {SharingListFolderMembersArgs} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.sharingListFolderMembers = function (arg) {\n return this.request('sharing/list_folder_members', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Once a cursor has been retrieved from list_folder_members, use this to\n * paginate through all shared folder members.\n * @function Dropbox#sharingListFolderMembersContinue\n * @arg {SharingListFolderMembersContinueArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.sharingListFolderMembersContinue = function (arg) {\n return this.request('sharing/list_folder_members/continue', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Return the list of all shared folders the current user has access to.\n * @function Dropbox#sharingListFolders\n * @arg {SharingListFoldersArgs} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.sharingListFolders = function (arg) {\n return this.request('sharing/list_folders', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Once a cursor has been retrieved from list_folders, use this to paginate\n * through all shared folders. The cursor must come from a previous call to\n * list_folders or list_folders/continue.\n * @function Dropbox#sharingListFoldersContinue\n * @arg {SharingListFoldersContinueArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.sharingListFoldersContinue = function (arg) {\n return this.request('sharing/list_folders/continue', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Return the list of all shared folders the current user can mount or unmount.\n * @function Dropbox#sharingListMountableFolders\n * @arg {SharingListFoldersArgs} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.sharingListMountableFolders = function (arg) {\n return this.request('sharing/list_mountable_folders', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Once a cursor has been retrieved from list_mountable_folders, use this to\n * paginate through all mountable shared folders. The cursor must come from a\n * previous call to list_mountable_folders or list_mountable_folders/continue.\n * @function Dropbox#sharingListMountableFoldersContinue\n * @arg {SharingListFoldersContinueArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.sharingListMountableFoldersContinue = function (arg) {\n return this.request('sharing/list_mountable_folders/continue', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Returns a list of all files shared with current user. Does not include files\n * the user has received via shared folders, and does not include unclaimed\n * invitations.\n * @function Dropbox#sharingListReceivedFiles\n * @arg {SharingListFilesArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.sharingListReceivedFiles = function (arg) {\n return this.request('sharing/list_received_files', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Get more results with a cursor from list_received_files.\n * @function Dropbox#sharingListReceivedFilesContinue\n * @arg {SharingListFilesContinueArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.sharingListReceivedFilesContinue = function (arg) {\n return this.request('sharing/list_received_files/continue', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * List shared links of this user. If no path is given, returns a list of all\n * shared links for the current user. If a non-empty path is given, returns a\n * list of all shared links that allow access to the given path - direct links\n * to the given path and links to parent folders of the given path. Links to\n * parent folders can be suppressed by setting direct_only to true.\n * @function Dropbox#sharingListSharedLinks\n * @arg {SharingListSharedLinksArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.sharingListSharedLinks = function (arg) {\n return this.request('sharing/list_shared_links', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Modify the shared link's settings. If the requested visibility conflict with\n * the shared links policy of the team or the shared folder (in case the linked\n * file is part of a shared folder) then the LinkPermissions.resolved_visibility\n * of the returned SharedLinkMetadata will reflect the actual visibility of the\n * shared link and the LinkPermissions.requested_visibility will reflect the\n * requested visibility.\n * @function Dropbox#sharingModifySharedLinkSettings\n * @arg {SharingModifySharedLinkSettingsArgs} arg - The request parameters.\n * @returns {Promise.<(SharingFileLinkMetadata|SharingFolderLinkMetadata|SharingSharedLinkMetadata), Error.>}\n */\nroutes.sharingModifySharedLinkSettings = function (arg) {\n return this.request('sharing/modify_shared_link_settings', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * The current user mounts the designated folder. Mount a shared folder for a\n * user after they have been added as a member. Once mounted, the shared folder\n * will appear in their Dropbox.\n * @function Dropbox#sharingMountFolder\n * @arg {SharingMountFolderArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.sharingMountFolder = function (arg) {\n return this.request('sharing/mount_folder', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * The current user relinquishes their membership in the designated file. Note\n * that the current user may still have inherited access to this file through\n * the parent folder.\n * @function Dropbox#sharingRelinquishFileMembership\n * @arg {SharingRelinquishFileMembershipArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.sharingRelinquishFileMembership = function (arg) {\n return this.request('sharing/relinquish_file_membership', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * The current user relinquishes their membership in the designated shared\n * folder and will no longer have access to the folder. A folder owner cannot\n * relinquish membership in their own folder. This will run synchronously if\n * leave_a_copy is false, and asynchronously if leave_a_copy is true.\n * @function Dropbox#sharingRelinquishFolderMembership\n * @arg {SharingRelinquishFolderMembershipArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.sharingRelinquishFolderMembership = function (arg) {\n return this.request('sharing/relinquish_folder_membership', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Identical to remove_file_member_2 but with less information returned.\n * @function Dropbox#sharingRemoveFileMember\n * @deprecated\n * @arg {SharingRemoveFileMemberArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.sharingRemoveFileMember = function (arg) {\n return this.request('sharing/remove_file_member', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Removes a specified member from the file.\n * @function Dropbox#sharingRemoveFileMember2\n * @arg {SharingRemoveFileMemberArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.sharingRemoveFileMember2 = function (arg) {\n return this.request('sharing/remove_file_member_2', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Allows an owner or editor (if the ACL update policy allows) of a shared\n * folder to remove another member.\n * @function Dropbox#sharingRemoveFolderMember\n * @arg {SharingRemoveFolderMemberArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.sharingRemoveFolderMember = function (arg) {\n return this.request('sharing/remove_folder_member', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Revoke a shared link. Note that even after revoking a shared link to a file,\n * the file may be accessible if there are shared links leading to any of the\n * file parent folders. To list all shared links that enable access to a\n * specific file, you can use the list_shared_links with the file as the\n * ListSharedLinksArg.path argument.\n * @function Dropbox#sharingRevokeSharedLink\n * @arg {SharingRevokeSharedLinkArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.sharingRevokeSharedLink = function (arg) {\n return this.request('sharing/revoke_shared_link', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Change the inheritance policy of an existing Shared Folder. Only permitted\n * for shared folders in a shared team root. If a ShareFolderLaunch.async_job_id\n * is returned, you'll need to call check_share_job_status until the action\n * completes to get the metadata for the folder.\n * @function Dropbox#sharingSetAccessInheritance\n * @arg {SharingSetAccessInheritanceArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.sharingSetAccessInheritance = function (arg) {\n return this.request('sharing/set_access_inheritance', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Share a folder with collaborators. Most sharing will be completed\n * synchronously. Large folders will be completed asynchronously. To make\n * testing the async case repeatable, set `ShareFolderArg.force_async`. If a\n * ShareFolderLaunch.async_job_id is returned, you'll need to call\n * check_share_job_status until the action completes to get the metadata for the\n * folder.\n * @function Dropbox#sharingShareFolder\n * @arg {SharingShareFolderArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.sharingShareFolder = function (arg) {\n return this.request('sharing/share_folder', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Transfer ownership of a shared folder to a member of the shared folder. User\n * must have AccessLevel.owner access to the shared folder to perform a\n * transfer.\n * @function Dropbox#sharingTransferFolder\n * @arg {SharingTransferFolderArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.sharingTransferFolder = function (arg) {\n return this.request('sharing/transfer_folder', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * The current user unmounts the designated folder. They can re-mount the folder\n * at a later time using mount_folder.\n * @function Dropbox#sharingUnmountFolder\n * @arg {SharingUnmountFolderArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.sharingUnmountFolder = function (arg) {\n return this.request('sharing/unmount_folder', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Remove all members from this file. Does not remove inherited members.\n * @function Dropbox#sharingUnshareFile\n * @arg {SharingUnshareFileArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.sharingUnshareFile = function (arg) {\n return this.request('sharing/unshare_file', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Allows a shared folder owner to unshare the folder. You'll need to call\n * check_job_status to determine if the action has completed successfully.\n * @function Dropbox#sharingUnshareFolder\n * @arg {SharingUnshareFolderArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.sharingUnshareFolder = function (arg) {\n return this.request('sharing/unshare_folder', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Changes a member's access on a shared file.\n * @function Dropbox#sharingUpdateFileMember\n * @arg {SharingUpdateFileMemberArgs} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.sharingUpdateFileMember = function (arg) {\n return this.request('sharing/update_file_member', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Allows an owner or editor of a shared folder to update another member's\n * permissions.\n * @function Dropbox#sharingUpdateFolderMember\n * @arg {SharingUpdateFolderMemberArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.sharingUpdateFolderMember = function (arg) {\n return this.request('sharing/update_folder_member', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Update the sharing policies for a shared folder. User must have\n * AccessLevel.owner access to the shared folder to update its policies.\n * @function Dropbox#sharingUpdateFolderPolicy\n * @arg {SharingUpdateFolderPolicyArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.sharingUpdateFolderPolicy = function (arg) {\n return this.request('sharing/update_folder_policy', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Retrieves team events. Events have a lifespan of two years. Events older than\n * two years will not be returned. Many attributes note 'may be missing due to\n * historical data gap'. Note that the file_operations category and & analogous\n * paper events are not available on all Dropbox Business plans\n * /business/plans-comparison. Use features/get_values\n * /developers/documentation/http/teams#team-features-get_values to check for\n * this feature. Permission : Team Auditing.\n * @function Dropbox#teamLogGetEvents\n * @arg {TeamLogGetTeamEventsArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.teamLogGetEvents = function (arg) {\n return this.request('team_log/get_events', arg, 'team', 'api', 'rpc');\n};\n\n/**\n * Once a cursor has been retrieved from get_events, use this to paginate\n * through all events. Permission : Team Auditing.\n * @function Dropbox#teamLogGetEventsContinue\n * @arg {TeamLogGetTeamEventsContinueArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.teamLogGetEventsContinue = function (arg) {\n return this.request('team_log/get_events/continue', arg, 'team', 'api', 'rpc');\n};\n\n/**\n * Get information about a user's account.\n * @function Dropbox#usersGetAccount\n * @arg {UsersGetAccountArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.usersGetAccount = function (arg) {\n return this.request('users/get_account', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Get information about multiple user accounts. At most 300 accounts may be\n * queried per request.\n * @function Dropbox#usersGetAccountBatch\n * @arg {UsersGetAccountBatchArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.usersGetAccountBatch = function (arg) {\n return this.request('users/get_account_batch', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Get information about the current user's account.\n * @function Dropbox#usersGetCurrentAccount\n * @arg {void} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.usersGetCurrentAccount = function (arg) {\n return this.request('users/get_current_account', arg, 'user', 'api', 'rpc');\n};\n\n/**\n * Get the space usage information for the current user's account.\n * @function Dropbox#usersGetSpaceUsage\n * @arg {void} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.usersGetSpaceUsage = function (arg) {\n return this.request('users/get_space_usage', arg, 'user', 'api', 'rpc');\n};\n\nexport { routes };\n","export const RPC = 'rpc';\nexport const UPLOAD = 'upload';\nexport const DOWNLOAD = 'download';\n","function getSafeUnicode(c) {\n const unicode = `000${c.charCodeAt(0).toString(16)}`.slice(-4);\n return `\\\\u${unicode}`;\n}\n\n\n/* global WorkerGlobalScope */\nexport function isWindowOrWorker() {\n return (\n (\n typeof WorkerGlobalScope !== 'undefined' &&\n self instanceof WorkerGlobalScope\n )\n ||\n (\n typeof module === 'undefined' ||\n typeof window !== 'undefined'\n )\n );\n}\n\nexport function getBaseURL(host) {\n return `https://${host}.dropboxapi.com/2/`;\n}\n\n// source https://www.dropboxforum.com/t5/API-support/HTTP-header-quot-Dropbox-API-Arg-quot-could-not-decode-input-as/m-p/173823/highlight/true#M6786\nexport function httpHeaderSafeJson(args) {\n return JSON.stringify(args).replace(/[\\u007f-\\uffff]/g, getSafeUnicode);\n}\n","import { getBaseURL, httpHeaderSafeJson, isWindowOrWorker } from './utils';\n\nfunction getDataFromConsumer(res) {\n if (!res.ok) {\n return res.text();\n }\n\n return (isWindowOrWorker()) ? res.blob() : res.buffer();\n}\n\nfunction responseHandler(res, data) {\n if (!res.ok) {\n // eslint-disable-next-line no-throw-literal\n throw {\n error: data,\n response: res,\n status: res.status,\n };\n }\n\n const result = JSON.parse(res.headers.get('dropbox-api-result'));\n\n if (isWindowOrWorker()) {\n result.fileBlob = data;\n } else {\n result.fileBinary = data;\n }\n\n return result;\n}\n\nexport function downloadRequest(fetch) {\n return function downloadRequestWithFetch(path, args, auth, host, accessToken, options) {\n if (auth !== 'user') {\n throw new Error(`Unexpected auth type: ${auth}`);\n }\n\n const fetchOptions = {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${accessToken}`,\n 'Dropbox-API-Arg': httpHeaderSafeJson(args),\n },\n };\n\n if (options) {\n if (options.selectUser) {\n fetchOptions.headers['Dropbox-API-Select-User'] = options.selectUser;\n }\n if (options.selectAdmin) {\n fetchOptions.headers['Dropbox-API-Select-Admin'] = options.selectAdmin;\n }\n if (options.pathRoot) {\n fetchOptions.headers['Dropbox-API-Path-Root'] = options.pathRoot;\n }\n }\n\n\n return fetch(getBaseURL(host) + path, fetchOptions)\n .then(res => getDataFromConsumer(res).then(data => [res, data]))\n .then(([res, data]) => responseHandler(res, data));\n };\n}\n","import { getBaseURL, httpHeaderSafeJson } from './utils';\n\nfunction parseBodyToType(res) {\n const clone = res.clone();\n return new Promise((resolve) => {\n res.json()\n .then(data => resolve(data))\n .catch(() => clone.text().then(data => resolve(data)));\n }).then(data => [res, data]);\n}\n\nexport function uploadRequest(fetch) {\n return function uploadRequestWithFetch(path, args, auth, host, accessToken, options) {\n if (auth !== 'user') {\n throw new Error(`Unexpected auth type: ${auth}`);\n }\n\n const { contents } = args;\n delete args.contents;\n\n const fetchOptions = {\n body: contents,\n method: 'POST',\n headers: {\n Authorization: `Bearer ${accessToken}`,\n 'Content-Type': 'application/octet-stream',\n 'Dropbox-API-Arg': httpHeaderSafeJson(args),\n },\n };\n\n if (options) {\n if (options.selectUser) {\n fetchOptions.headers['Dropbox-API-Select-User'] = options.selectUser;\n }\n if (options.selectAdmin) {\n fetchOptions.headers['Dropbox-API-Select-Admin'] = options.selectAdmin;\n }\n if (options.pathRoot) {\n fetchOptions.headers['Dropbox-API-Path-Root'] = options.pathRoot;\n }\n }\n\n return fetch(getBaseURL(host) + path, fetchOptions)\n .then(res => parseBodyToType(res))\n .then(([res, data]) => {\n // maintaining existing API for error codes not equal to 200 range\n if (!res.ok) {\n // eslint-disable-next-line no-throw-literal\n throw {\n error: data,\n response: res,\n status: res.status,\n };\n }\n\n return data;\n });\n };\n}\n","'use strict'\n\nexports.byteLength = byteLength\nexports.toByteArray = toByteArray\nexports.fromByteArray = fromByteArray\n\nvar lookup = []\nvar revLookup = []\nvar Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array\n\nvar code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'\nfor (var i = 0, len = code.length; i < len; ++i) {\n lookup[i] = code[i]\n revLookup[code.charCodeAt(i)] = i\n}\n\nrevLookup['-'.charCodeAt(0)] = 62\nrevLookup['_'.charCodeAt(0)] = 63\n\nfunction placeHoldersCount (b64) {\n var len = b64.length\n if (len % 4 > 0) {\n throw new Error('Invalid string. Length must be a multiple of 4')\n }\n\n // the number of equal signs (place holders)\n // if there are two placeholders, than the two characters before it\n // represent one byte\n // if there is only one, then the three characters before it represent 2 bytes\n // this is just a cheap hack to not do indexOf twice\n return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0\n}\n\nfunction byteLength (b64) {\n // base64 is 4/3 + up to two characters of the original data\n return (b64.length * 3 / 4) - placeHoldersCount(b64)\n}\n\nfunction toByteArray (b64) {\n var i, l, tmp, placeHolders, arr\n var len = b64.length\n placeHolders = placeHoldersCount(b64)\n\n arr = new Arr((len * 3 / 4) - placeHolders)\n\n // if there are placeholders, only get up to the last complete 4 chars\n l = placeHolders > 0 ? len - 4 : len\n\n var L = 0\n\n for (i = 0; i < l; i += 4) {\n tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]\n arr[L++] = (tmp >> 16) & 0xFF\n arr[L++] = (tmp >> 8) & 0xFF\n arr[L++] = tmp & 0xFF\n }\n\n if (placeHolders === 2) {\n tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4)\n arr[L++] = tmp & 0xFF\n } else if (placeHolders === 1) {\n tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2)\n arr[L++] = (tmp >> 8) & 0xFF\n arr[L++] = tmp & 0xFF\n }\n\n return arr\n}\n\nfunction tripletToBase64 (num) {\n return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]\n}\n\nfunction encodeChunk (uint8, start, end) {\n var tmp\n var output = []\n for (var i = start; i < end; i += 3) {\n tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])\n output.push(tripletToBase64(tmp))\n }\n return output.join('')\n}\n\nfunction fromByteArray (uint8) {\n var tmp\n var len = uint8.length\n var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes\n var output = ''\n var parts = []\n var maxChunkLength = 16383 // must be multiple of 3\n\n // go through the array every three bytes, we'll deal with trailing stuff later\n for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {\n parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))\n }\n\n // pad the end with zeros, but make sure to not forget the extra bytes\n if (extraBytes === 1) {\n tmp = uint8[len - 1]\n output += lookup[tmp >> 2]\n output += lookup[(tmp << 4) & 0x3F]\n output += '=='\n } else if (extraBytes === 2) {\n tmp = (uint8[len - 2] << 8) + (uint8[len - 1])\n output += lookup[tmp >> 10]\n output += lookup[(tmp >> 4) & 0x3F]\n output += lookup[(tmp << 2) & 0x3F]\n output += '='\n }\n\n parts.push(output)\n\n return parts.join('')\n}\n","exports.read = function (buffer, offset, isLE, mLen, nBytes) {\n var e, m\n var eLen = nBytes * 8 - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var nBits = -7\n var i = isLE ? (nBytes - 1) : 0\n var d = isLE ? -1 : 1\n var s = buffer[offset + i]\n\n i += d\n\n e = s & ((1 << (-nBits)) - 1)\n s >>= (-nBits)\n nBits += eLen\n for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}\n\n m = e & ((1 << (-nBits)) - 1)\n e >>= (-nBits)\n nBits += mLen\n for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}\n\n if (e === 0) {\n e = 1 - eBias\n } else if (e === eMax) {\n return m ? NaN : ((s ? -1 : 1) * Infinity)\n } else {\n m = m + Math.pow(2, mLen)\n e = e - eBias\n }\n return (s ? -1 : 1) * m * Math.pow(2, e - mLen)\n}\n\nexports.write = function (buffer, value, offset, isLE, mLen, nBytes) {\n var e, m, c\n var eLen = nBytes * 8 - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)\n var i = isLE ? 0 : (nBytes - 1)\n var d = isLE ? 1 : -1\n var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0\n\n value = Math.abs(value)\n\n if (isNaN(value) || value === Infinity) {\n m = isNaN(value) ? 1 : 0\n e = eMax\n } else {\n e = Math.floor(Math.log(value) / Math.LN2)\n if (value * (c = Math.pow(2, -e)) < 1) {\n e--\n c *= 2\n }\n if (e + eBias >= 1) {\n value += rt / c\n } else {\n value += rt * Math.pow(2, 1 - eBias)\n }\n if (value * c >= 2) {\n e++\n c /= 2\n }\n\n if (e + eBias >= eMax) {\n m = 0\n e = eMax\n } else if (e + eBias >= 1) {\n m = (value * c - 1) * Math.pow(2, mLen)\n e = e + eBias\n } else {\n m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)\n e = 0\n }\n }\n\n for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}\n\n e = (e << mLen) | m\n eLen += mLen\n for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}\n\n buffer[offset + i - d] |= s * 128\n}\n","/*!\n * The buffer module from node.js, for the browser.\n *\n * @author Feross Aboukhadijeh \n * @license MIT\n */\n/* eslint-disable no-proto */\n\n'use strict'\n\nvar base64 = require('base64-js')\nvar ieee754 = require('ieee754')\n\nexports.Buffer = Buffer\nexports.SlowBuffer = SlowBuffer\nexports.INSPECT_MAX_BYTES = 50\n\nvar K_MAX_LENGTH = 0x7fffffff\nexports.kMaxLength = K_MAX_LENGTH\n\n/**\n * If `Buffer.TYPED_ARRAY_SUPPORT`:\n * === true Use Uint8Array implementation (fastest)\n * === false Print warning and recommend using `buffer` v4.x which has an Object\n * implementation (most compatible, even IE6)\n *\n * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,\n * Opera 11.6+, iOS 4.2+.\n *\n * We report that the browser does not support typed arrays if the are not subclassable\n * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`\n * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support\n * for __proto__ and has a buggy typed array implementation.\n */\nBuffer.TYPED_ARRAY_SUPPORT = typedArraySupport()\n\nif (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&\n typeof console.error === 'function') {\n console.error(\n 'This browser lacks typed array (Uint8Array) support which is required by ' +\n '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'\n )\n}\n\nfunction typedArraySupport () {\n // Can typed array instances can be augmented?\n try {\n var arr = new Uint8Array(1)\n arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}\n return arr.foo() === 42\n } catch (e) {\n return false\n }\n}\n\nfunction createBuffer (length) {\n if (length > K_MAX_LENGTH) {\n throw new RangeError('Invalid typed array length')\n }\n // Return an augmented `Uint8Array` instance\n var buf = new Uint8Array(length)\n buf.__proto__ = Buffer.prototype\n return buf\n}\n\n/**\n * The Buffer constructor returns instances of `Uint8Array` that have their\n * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of\n * `Uint8Array`, so the returned instances will have all the node `Buffer` methods\n * and the `Uint8Array` methods. Square bracket notation works as expected -- it\n * returns a single octet.\n *\n * The `Uint8Array` prototype remains unmodified.\n */\n\nfunction Buffer (arg, encodingOrOffset, length) {\n // Common case.\n if (typeof arg === 'number') {\n if (typeof encodingOrOffset === 'string') {\n throw new Error(\n 'If encoding is specified then the first argument must be a string'\n )\n }\n return allocUnsafe(arg)\n }\n return from(arg, encodingOrOffset, length)\n}\n\n// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97\nif (typeof Symbol !== 'undefined' && Symbol.species &&\n Buffer[Symbol.species] === Buffer) {\n Object.defineProperty(Buffer, Symbol.species, {\n value: null,\n configurable: true,\n enumerable: false,\n writable: false\n })\n}\n\nBuffer.poolSize = 8192 // not used by this implementation\n\nfunction from (value, encodingOrOffset, length) {\n if (typeof value === 'number') {\n throw new TypeError('\"value\" argument must not be a number')\n }\n\n if (isArrayBuffer(value)) {\n return fromArrayBuffer(value, encodingOrOffset, length)\n }\n\n if (typeof value === 'string') {\n return fromString(value, encodingOrOffset)\n }\n\n return fromObject(value)\n}\n\n/**\n * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError\n * if value is a number.\n * Buffer.from(str[, encoding])\n * Buffer.from(array)\n * Buffer.from(buffer)\n * Buffer.from(arrayBuffer[, byteOffset[, length]])\n **/\nBuffer.from = function (value, encodingOrOffset, length) {\n return from(value, encodingOrOffset, length)\n}\n\n// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:\n// https://github.com/feross/buffer/pull/148\nBuffer.prototype.__proto__ = Uint8Array.prototype\nBuffer.__proto__ = Uint8Array\n\nfunction assertSize (size) {\n if (typeof size !== 'number') {\n throw new TypeError('\"size\" argument must be a number')\n } else if (size < 0) {\n throw new RangeError('\"size\" argument must not be negative')\n }\n}\n\nfunction alloc (size, fill, encoding) {\n assertSize(size)\n if (size <= 0) {\n return createBuffer(size)\n }\n if (fill !== undefined) {\n // Only pay attention to encoding if it's a string. This\n // prevents accidentally sending in a number that would\n // be interpretted as a start offset.\n return typeof encoding === 'string'\n ? createBuffer(size).fill(fill, encoding)\n : createBuffer(size).fill(fill)\n }\n return createBuffer(size)\n}\n\n/**\n * Creates a new filled Buffer instance.\n * alloc(size[, fill[, encoding]])\n **/\nBuffer.alloc = function (size, fill, encoding) {\n return alloc(size, fill, encoding)\n}\n\nfunction allocUnsafe (size) {\n assertSize(size)\n return createBuffer(size < 0 ? 0 : checked(size) | 0)\n}\n\n/**\n * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.\n * */\nBuffer.allocUnsafe = function (size) {\n return allocUnsafe(size)\n}\n/**\n * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.\n */\nBuffer.allocUnsafeSlow = function (size) {\n return allocUnsafe(size)\n}\n\nfunction fromString (string, encoding) {\n if (typeof encoding !== 'string' || encoding === '') {\n encoding = 'utf8'\n }\n\n if (!Buffer.isEncoding(encoding)) {\n throw new TypeError('\"encoding\" must be a valid string encoding')\n }\n\n var length = byteLength(string, encoding) | 0\n var buf = createBuffer(length)\n\n var actual = buf.write(string, encoding)\n\n if (actual !== length) {\n // Writing a hex string, for example, that contains invalid characters will\n // cause everything after the first invalid character to be ignored. (e.g.\n // 'abxxcd' will be treated as 'ab')\n buf = buf.slice(0, actual)\n }\n\n return buf\n}\n\nfunction fromArrayLike (array) {\n var length = array.length < 0 ? 0 : checked(array.length) | 0\n var buf = createBuffer(length)\n for (var i = 0; i < length; i += 1) {\n buf[i] = array[i] & 255\n }\n return buf\n}\n\nfunction fromArrayBuffer (array, byteOffset, length) {\n if (byteOffset < 0 || array.byteLength < byteOffset) {\n throw new RangeError('\\'offset\\' is out of bounds')\n }\n\n if (array.byteLength < byteOffset + (length || 0)) {\n throw new RangeError('\\'length\\' is out of bounds')\n }\n\n var buf\n if (byteOffset === undefined && length === undefined) {\n buf = new Uint8Array(array)\n } else if (length === undefined) {\n buf = new Uint8Array(array, byteOffset)\n } else {\n buf = new Uint8Array(array, byteOffset, length)\n }\n\n // Return an augmented `Uint8Array` instance\n buf.__proto__ = Buffer.prototype\n return buf\n}\n\nfunction fromObject (obj) {\n if (Buffer.isBuffer(obj)) {\n var len = checked(obj.length) | 0\n var buf = createBuffer(len)\n\n if (buf.length === 0) {\n return buf\n }\n\n obj.copy(buf, 0, 0, len)\n return buf\n }\n\n if (obj) {\n if (isArrayBufferView(obj) || 'length' in obj) {\n if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {\n return createBuffer(0)\n }\n return fromArrayLike(obj)\n }\n\n if (obj.type === 'Buffer' && Array.isArray(obj.data)) {\n return fromArrayLike(obj.data)\n }\n }\n\n throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')\n}\n\nfunction checked (length) {\n // Note: cannot use `length < K_MAX_LENGTH` here because that fails when\n // length is NaN (which is otherwise coerced to zero.)\n if (length >= K_MAX_LENGTH) {\n throw new RangeError('Attempt to allocate Buffer larger than maximum ' +\n 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')\n }\n return length | 0\n}\n\nfunction SlowBuffer (length) {\n if (+length != length) { // eslint-disable-line eqeqeq\n length = 0\n }\n return Buffer.alloc(+length)\n}\n\nBuffer.isBuffer = function isBuffer (b) {\n return b != null && b._isBuffer === true\n}\n\nBuffer.compare = function compare (a, b) {\n if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {\n throw new TypeError('Arguments must be Buffers')\n }\n\n if (a === b) return 0\n\n var x = a.length\n var y = b.length\n\n for (var i = 0, len = Math.min(x, y); i < len; ++i) {\n if (a[i] !== b[i]) {\n x = a[i]\n y = b[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\nBuffer.isEncoding = function isEncoding (encoding) {\n switch (String(encoding).toLowerCase()) {\n case 'hex':\n case 'utf8':\n case 'utf-8':\n case 'ascii':\n case 'latin1':\n case 'binary':\n case 'base64':\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return true\n default:\n return false\n }\n}\n\nBuffer.concat = function concat (list, length) {\n if (!Array.isArray(list)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n }\n\n if (list.length === 0) {\n return Buffer.alloc(0)\n }\n\n var i\n if (length === undefined) {\n length = 0\n for (i = 0; i < list.length; ++i) {\n length += list[i].length\n }\n }\n\n var buffer = Buffer.allocUnsafe(length)\n var pos = 0\n for (i = 0; i < list.length; ++i) {\n var buf = list[i]\n if (!Buffer.isBuffer(buf)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n }\n buf.copy(buffer, pos)\n pos += buf.length\n }\n return buffer\n}\n\nfunction byteLength (string, encoding) {\n if (Buffer.isBuffer(string)) {\n return string.length\n }\n if (isArrayBufferView(string) || isArrayBuffer(string)) {\n return string.byteLength\n }\n if (typeof string !== 'string') {\n string = '' + string\n }\n\n var len = string.length\n if (len === 0) return 0\n\n // Use a for loop to avoid recursion\n var loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'ascii':\n case 'latin1':\n case 'binary':\n return len\n case 'utf8':\n case 'utf-8':\n case undefined:\n return utf8ToBytes(string).length\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return len * 2\n case 'hex':\n return len >>> 1\n case 'base64':\n return base64ToBytes(string).length\n default:\n if (loweredCase) return utf8ToBytes(string).length // assume utf8\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\nBuffer.byteLength = byteLength\n\nfunction slowToString (encoding, start, end) {\n var loweredCase = false\n\n // No need to verify that \"this.length <= MAX_UINT32\" since it's a read-only\n // property of a typed array.\n\n // This behaves neither like String nor Uint8Array in that we set start/end\n // to their upper/lower bounds if the value passed is out of range.\n // undefined is handled specially as per ECMA-262 6th Edition,\n // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.\n if (start === undefined || start < 0) {\n start = 0\n }\n // Return early if start > this.length. Done here to prevent potential uint32\n // coercion fail below.\n if (start > this.length) {\n return ''\n }\n\n if (end === undefined || end > this.length) {\n end = this.length\n }\n\n if (end <= 0) {\n return ''\n }\n\n // Force coersion to uint32. This will also coerce falsey/NaN values to 0.\n end >>>= 0\n start >>>= 0\n\n if (end <= start) {\n return ''\n }\n\n if (!encoding) encoding = 'utf8'\n\n while (true) {\n switch (encoding) {\n case 'hex':\n return hexSlice(this, start, end)\n\n case 'utf8':\n case 'utf-8':\n return utf8Slice(this, start, end)\n\n case 'ascii':\n return asciiSlice(this, start, end)\n\n case 'latin1':\n case 'binary':\n return latin1Slice(this, start, end)\n\n case 'base64':\n return base64Slice(this, start, end)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return utf16leSlice(this, start, end)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = (encoding + '').toLowerCase()\n loweredCase = true\n }\n }\n}\n\n// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)\n// to detect a Buffer instance. It's not possible to use `instanceof Buffer`\n// reliably in a browserify context because there could be multiple different\n// copies of the 'buffer' package in use. This method works even for Buffer\n// instances that were created from another copy of the `buffer` package.\n// See: https://github.com/feross/buffer/issues/154\nBuffer.prototype._isBuffer = true\n\nfunction swap (b, n, m) {\n var i = b[n]\n b[n] = b[m]\n b[m] = i\n}\n\nBuffer.prototype.swap16 = function swap16 () {\n var len = this.length\n if (len % 2 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 16-bits')\n }\n for (var i = 0; i < len; i += 2) {\n swap(this, i, i + 1)\n }\n return this\n}\n\nBuffer.prototype.swap32 = function swap32 () {\n var len = this.length\n if (len % 4 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 32-bits')\n }\n for (var i = 0; i < len; i += 4) {\n swap(this, i, i + 3)\n swap(this, i + 1, i + 2)\n }\n return this\n}\n\nBuffer.prototype.swap64 = function swap64 () {\n var len = this.length\n if (len % 8 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 64-bits')\n }\n for (var i = 0; i < len; i += 8) {\n swap(this, i, i + 7)\n swap(this, i + 1, i + 6)\n swap(this, i + 2, i + 5)\n swap(this, i + 3, i + 4)\n }\n return this\n}\n\nBuffer.prototype.toString = function toString () {\n var length = this.length\n if (length === 0) return ''\n if (arguments.length === 0) return utf8Slice(this, 0, length)\n return slowToString.apply(this, arguments)\n}\n\nBuffer.prototype.equals = function equals (b) {\n if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')\n if (this === b) return true\n return Buffer.compare(this, b) === 0\n}\n\nBuffer.prototype.inspect = function inspect () {\n var str = ''\n var max = exports.INSPECT_MAX_BYTES\n if (this.length > 0) {\n str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')\n if (this.length > max) str += ' ... '\n }\n return ''\n}\n\nBuffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {\n if (!Buffer.isBuffer(target)) {\n throw new TypeError('Argument must be a Buffer')\n }\n\n if (start === undefined) {\n start = 0\n }\n if (end === undefined) {\n end = target ? target.length : 0\n }\n if (thisStart === undefined) {\n thisStart = 0\n }\n if (thisEnd === undefined) {\n thisEnd = this.length\n }\n\n if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {\n throw new RangeError('out of range index')\n }\n\n if (thisStart >= thisEnd && start >= end) {\n return 0\n }\n if (thisStart >= thisEnd) {\n return -1\n }\n if (start >= end) {\n return 1\n }\n\n start >>>= 0\n end >>>= 0\n thisStart >>>= 0\n thisEnd >>>= 0\n\n if (this === target) return 0\n\n var x = thisEnd - thisStart\n var y = end - start\n var len = Math.min(x, y)\n\n var thisCopy = this.slice(thisStart, thisEnd)\n var targetCopy = target.slice(start, end)\n\n for (var i = 0; i < len; ++i) {\n if (thisCopy[i] !== targetCopy[i]) {\n x = thisCopy[i]\n y = targetCopy[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\n// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,\n// OR the last index of `val` in `buffer` at offset <= `byteOffset`.\n//\n// Arguments:\n// - buffer - a Buffer to search\n// - val - a string, Buffer, or number\n// - byteOffset - an index into `buffer`; will be clamped to an int32\n// - encoding - an optional encoding, relevant is val is a string\n// - dir - true for indexOf, false for lastIndexOf\nfunction bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {\n // Empty buffer means no match\n if (buffer.length === 0) return -1\n\n // Normalize byteOffset\n if (typeof byteOffset === 'string') {\n encoding = byteOffset\n byteOffset = 0\n } else if (byteOffset > 0x7fffffff) {\n byteOffset = 0x7fffffff\n } else if (byteOffset < -0x80000000) {\n byteOffset = -0x80000000\n }\n byteOffset = +byteOffset // Coerce to Number.\n if (numberIsNaN(byteOffset)) {\n // byteOffset: it it's undefined, null, NaN, \"foo\", etc, search whole buffer\n byteOffset = dir ? 0 : (buffer.length - 1)\n }\n\n // Normalize byteOffset: negative offsets start from the end of the buffer\n if (byteOffset < 0) byteOffset = buffer.length + byteOffset\n if (byteOffset >= buffer.length) {\n if (dir) return -1\n else byteOffset = buffer.length - 1\n } else if (byteOffset < 0) {\n if (dir) byteOffset = 0\n else return -1\n }\n\n // Normalize val\n if (typeof val === 'string') {\n val = Buffer.from(val, encoding)\n }\n\n // Finally, search either indexOf (if dir is true) or lastIndexOf\n if (Buffer.isBuffer(val)) {\n // Special case: looking for empty string/buffer always fails\n if (val.length === 0) {\n return -1\n }\n return arrayIndexOf(buffer, val, byteOffset, encoding, dir)\n } else if (typeof val === 'number') {\n val = val & 0xFF // Search for a byte value [0-255]\n if (typeof Uint8Array.prototype.indexOf === 'function') {\n if (dir) {\n return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)\n } else {\n return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)\n }\n }\n return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)\n }\n\n throw new TypeError('val must be string, number or Buffer')\n}\n\nfunction arrayIndexOf (arr, val, byteOffset, encoding, dir) {\n var indexSize = 1\n var arrLength = arr.length\n var valLength = val.length\n\n if (encoding !== undefined) {\n encoding = String(encoding).toLowerCase()\n if (encoding === 'ucs2' || encoding === 'ucs-2' ||\n encoding === 'utf16le' || encoding === 'utf-16le') {\n if (arr.length < 2 || val.length < 2) {\n return -1\n }\n indexSize = 2\n arrLength /= 2\n valLength /= 2\n byteOffset /= 2\n }\n }\n\n function read (buf, i) {\n if (indexSize === 1) {\n return buf[i]\n } else {\n return buf.readUInt16BE(i * indexSize)\n }\n }\n\n var i\n if (dir) {\n var foundIndex = -1\n for (i = byteOffset; i < arrLength; i++) {\n if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {\n if (foundIndex === -1) foundIndex = i\n if (i - foundIndex + 1 === valLength) return foundIndex * indexSize\n } else {\n if (foundIndex !== -1) i -= i - foundIndex\n foundIndex = -1\n }\n }\n } else {\n if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength\n for (i = byteOffset; i >= 0; i--) {\n var found = true\n for (var j = 0; j < valLength; j++) {\n if (read(arr, i + j) !== read(val, j)) {\n found = false\n break\n }\n }\n if (found) return i\n }\n }\n\n return -1\n}\n\nBuffer.prototype.includes = function includes (val, byteOffset, encoding) {\n return this.indexOf(val, byteOffset, encoding) !== -1\n}\n\nBuffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, true)\n}\n\nBuffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, false)\n}\n\nfunction hexWrite (buf, string, offset, length) {\n offset = Number(offset) || 0\n var remaining = buf.length - offset\n if (!length) {\n length = remaining\n } else {\n length = Number(length)\n if (length > remaining) {\n length = remaining\n }\n }\n\n // must be an even number of digits\n var strLen = string.length\n if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')\n\n if (length > strLen / 2) {\n length = strLen / 2\n }\n for (var i = 0; i < length; ++i) {\n var parsed = parseInt(string.substr(i * 2, 2), 16)\n if (numberIsNaN(parsed)) return i\n buf[offset + i] = parsed\n }\n return i\n}\n\nfunction utf8Write (buf, string, offset, length) {\n return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nfunction asciiWrite (buf, string, offset, length) {\n return blitBuffer(asciiToBytes(string), buf, offset, length)\n}\n\nfunction latin1Write (buf, string, offset, length) {\n return asciiWrite(buf, string, offset, length)\n}\n\nfunction base64Write (buf, string, offset, length) {\n return blitBuffer(base64ToBytes(string), buf, offset, length)\n}\n\nfunction ucs2Write (buf, string, offset, length) {\n return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nBuffer.prototype.write = function write (string, offset, length, encoding) {\n // Buffer#write(string)\n if (offset === undefined) {\n encoding = 'utf8'\n length = this.length\n offset = 0\n // Buffer#write(string, encoding)\n } else if (length === undefined && typeof offset === 'string') {\n encoding = offset\n length = this.length\n offset = 0\n // Buffer#write(string, offset[, length][, encoding])\n } else if (isFinite(offset)) {\n offset = offset >>> 0\n if (isFinite(length)) {\n length = length >>> 0\n if (encoding === undefined) encoding = 'utf8'\n } else {\n encoding = length\n length = undefined\n }\n } else {\n throw new Error(\n 'Buffer.write(string, encoding, offset[, length]) is no longer supported'\n )\n }\n\n var remaining = this.length - offset\n if (length === undefined || length > remaining) length = remaining\n\n if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {\n throw new RangeError('Attempt to write outside buffer bounds')\n }\n\n if (!encoding) encoding = 'utf8'\n\n var loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'hex':\n return hexWrite(this, string, offset, length)\n\n case 'utf8':\n case 'utf-8':\n return utf8Write(this, string, offset, length)\n\n case 'ascii':\n return asciiWrite(this, string, offset, length)\n\n case 'latin1':\n case 'binary':\n return latin1Write(this, string, offset, length)\n\n case 'base64':\n // Warning: maxLength not taken into account in base64Write\n return base64Write(this, string, offset, length)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return ucs2Write(this, string, offset, length)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\n\nBuffer.prototype.toJSON = function toJSON () {\n return {\n type: 'Buffer',\n data: Array.prototype.slice.call(this._arr || this, 0)\n }\n}\n\nfunction base64Slice (buf, start, end) {\n if (start === 0 && end === buf.length) {\n return base64.fromByteArray(buf)\n } else {\n return base64.fromByteArray(buf.slice(start, end))\n }\n}\n\nfunction utf8Slice (buf, start, end) {\n end = Math.min(buf.length, end)\n var res = []\n\n var i = start\n while (i < end) {\n var firstByte = buf[i]\n var codePoint = null\n var bytesPerSequence = (firstByte > 0xEF) ? 4\n : (firstByte > 0xDF) ? 3\n : (firstByte > 0xBF) ? 2\n : 1\n\n if (i + bytesPerSequence <= end) {\n var secondByte, thirdByte, fourthByte, tempCodePoint\n\n switch (bytesPerSequence) {\n case 1:\n if (firstByte < 0x80) {\n codePoint = firstByte\n }\n break\n case 2:\n secondByte = buf[i + 1]\n if ((secondByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)\n if (tempCodePoint > 0x7F) {\n codePoint = tempCodePoint\n }\n }\n break\n case 3:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)\n if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {\n codePoint = tempCodePoint\n }\n }\n break\n case 4:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n fourthByte = buf[i + 3]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)\n if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {\n codePoint = tempCodePoint\n }\n }\n }\n }\n\n if (codePoint === null) {\n // we did not generate a valid codePoint so insert a\n // replacement char (U+FFFD) and advance only 1 byte\n codePoint = 0xFFFD\n bytesPerSequence = 1\n } else if (codePoint > 0xFFFF) {\n // encode to utf16 (surrogate pair dance)\n codePoint -= 0x10000\n res.push(codePoint >>> 10 & 0x3FF | 0xD800)\n codePoint = 0xDC00 | codePoint & 0x3FF\n }\n\n res.push(codePoint)\n i += bytesPerSequence\n }\n\n return decodeCodePointsArray(res)\n}\n\n// Based on http://stackoverflow.com/a/22747272/680742, the browser with\n// the lowest limit is Chrome, with 0x10000 args.\n// We go 1 magnitude less, for safety\nvar MAX_ARGUMENTS_LENGTH = 0x1000\n\nfunction decodeCodePointsArray (codePoints) {\n var len = codePoints.length\n if (len <= MAX_ARGUMENTS_LENGTH) {\n return String.fromCharCode.apply(String, codePoints) // avoid extra slice()\n }\n\n // Decode in chunks to avoid \"call stack size exceeded\".\n var res = ''\n var i = 0\n while (i < len) {\n res += String.fromCharCode.apply(\n String,\n codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)\n )\n }\n return res\n}\n\nfunction asciiSlice (buf, start, end) {\n var ret = ''\n end = Math.min(buf.length, end)\n\n for (var i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i] & 0x7F)\n }\n return ret\n}\n\nfunction latin1Slice (buf, start, end) {\n var ret = ''\n end = Math.min(buf.length, end)\n\n for (var i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i])\n }\n return ret\n}\n\nfunction hexSlice (buf, start, end) {\n var len = buf.length\n\n if (!start || start < 0) start = 0\n if (!end || end < 0 || end > len) end = len\n\n var out = ''\n for (var i = start; i < end; ++i) {\n out += toHex(buf[i])\n }\n return out\n}\n\nfunction utf16leSlice (buf, start, end) {\n var bytes = buf.slice(start, end)\n var res = ''\n for (var i = 0; i < bytes.length; i += 2) {\n res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))\n }\n return res\n}\n\nBuffer.prototype.slice = function slice (start, end) {\n var len = this.length\n start = ~~start\n end = end === undefined ? len : ~~end\n\n if (start < 0) {\n start += len\n if (start < 0) start = 0\n } else if (start > len) {\n start = len\n }\n\n if (end < 0) {\n end += len\n if (end < 0) end = 0\n } else if (end > len) {\n end = len\n }\n\n if (end < start) end = start\n\n var newBuf = this.subarray(start, end)\n // Return an augmented `Uint8Array` instance\n newBuf.__proto__ = Buffer.prototype\n return newBuf\n}\n\n/*\n * Need to make sure that buffer isn't trying to write out of bounds.\n */\nfunction checkOffset (offset, ext, length) {\n if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')\n if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')\n}\n\nBuffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var val = this[offset]\n var mul = 1\n var i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) {\n checkOffset(offset, byteLength, this.length)\n }\n\n var val = this[offset + --byteLength]\n var mul = 1\n while (byteLength > 0 && (mul *= 0x100)) {\n val += this[offset + --byteLength] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 1, this.length)\n return this[offset]\n}\n\nBuffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n return this[offset] | (this[offset + 1] << 8)\n}\n\nBuffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n return (this[offset] << 8) | this[offset + 1]\n}\n\nBuffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return ((this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16)) +\n (this[offset + 3] * 0x1000000)\n}\n\nBuffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] * 0x1000000) +\n ((this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n this[offset + 3])\n}\n\nBuffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var val = this[offset]\n var mul = 1\n var i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var i = byteLength\n var mul = 1\n var val = this[offset + --i]\n while (i > 0 && (mul *= 0x100)) {\n val += this[offset + --i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readInt8 = function readInt8 (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 1, this.length)\n if (!(this[offset] & 0x80)) return (this[offset])\n return ((0xff - this[offset] + 1) * -1)\n}\n\nBuffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n var val = this[offset] | (this[offset + 1] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n var val = this[offset + 1] | (this[offset] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16) |\n (this[offset + 3] << 24)\n}\n\nBuffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] << 24) |\n (this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n (this[offset + 3])\n}\n\nBuffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, true, 23, 4)\n}\n\nBuffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, false, 23, 4)\n}\n\nBuffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, true, 52, 8)\n}\n\nBuffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, false, 52, 8)\n}\n\nfunction checkInt (buf, value, offset, ext, max, min) {\n if (!Buffer.isBuffer(buf)) throw new TypeError('\"buffer\" argument must be a Buffer instance')\n if (value > max || value < min) throw new RangeError('\"value\" argument is out of bounds')\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n}\n\nBuffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) {\n var maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n var mul = 1\n var i = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) {\n var maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n var i = byteLength - 1\n var mul = 1\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nBuffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n return offset + 2\n}\n\nBuffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n return offset + 2\n}\n\nBuffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n this[offset + 3] = (value >>> 24)\n this[offset + 2] = (value >>> 16)\n this[offset + 1] = (value >>> 8)\n this[offset] = (value & 0xff)\n return offset + 4\n}\n\nBuffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n return offset + 4\n}\n\nBuffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n var limit = Math.pow(2, (8 * byteLength) - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n var i = 0\n var mul = 1\n var sub = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n var limit = Math.pow(2, (8 * byteLength) - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n var i = byteLength - 1\n var mul = 1\n var sub = 0\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)\n if (value < 0) value = 0xff + value + 1\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nBuffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n return offset + 2\n}\n\nBuffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n return offset + 2\n}\n\nBuffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n this[offset + 2] = (value >>> 16)\n this[offset + 3] = (value >>> 24)\n return offset + 4\n}\n\nBuffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n if (value < 0) value = 0xffffffff + value + 1\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n return offset + 4\n}\n\nfunction checkIEEE754 (buf, value, offset, ext, max, min) {\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n if (offset < 0) throw new RangeError('Index out of range')\n}\n\nfunction writeFloat (buf, value, offset, littleEndian, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)\n }\n ieee754.write(buf, value, offset, littleEndian, 23, 4)\n return offset + 4\n}\n\nBuffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {\n return writeFloat(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {\n return writeFloat(this, value, offset, false, noAssert)\n}\n\nfunction writeDouble (buf, value, offset, littleEndian, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)\n }\n ieee754.write(buf, value, offset, littleEndian, 52, 8)\n return offset + 8\n}\n\nBuffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {\n return writeDouble(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {\n return writeDouble(this, value, offset, false, noAssert)\n}\n\n// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)\nBuffer.prototype.copy = function copy (target, targetStart, start, end) {\n if (!start) start = 0\n if (!end && end !== 0) end = this.length\n if (targetStart >= target.length) targetStart = target.length\n if (!targetStart) targetStart = 0\n if (end > 0 && end < start) end = start\n\n // Copy 0 bytes; we're done\n if (end === start) return 0\n if (target.length === 0 || this.length === 0) return 0\n\n // Fatal error conditions\n if (targetStart < 0) {\n throw new RangeError('targetStart out of bounds')\n }\n if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')\n if (end < 0) throw new RangeError('sourceEnd out of bounds')\n\n // Are we oob?\n if (end > this.length) end = this.length\n if (target.length - targetStart < end - start) {\n end = target.length - targetStart + start\n }\n\n var len = end - start\n var i\n\n if (this === target && start < targetStart && targetStart < end) {\n // descending copy from end\n for (i = len - 1; i >= 0; --i) {\n target[i + targetStart] = this[i + start]\n }\n } else if (len < 1000) {\n // ascending copy from start\n for (i = 0; i < len; ++i) {\n target[i + targetStart] = this[i + start]\n }\n } else {\n Uint8Array.prototype.set.call(\n target,\n this.subarray(start, start + len),\n targetStart\n )\n }\n\n return len\n}\n\n// Usage:\n// buffer.fill(number[, offset[, end]])\n// buffer.fill(buffer[, offset[, end]])\n// buffer.fill(string[, offset[, end]][, encoding])\nBuffer.prototype.fill = function fill (val, start, end, encoding) {\n // Handle string cases:\n if (typeof val === 'string') {\n if (typeof start === 'string') {\n encoding = start\n start = 0\n end = this.length\n } else if (typeof end === 'string') {\n encoding = end\n end = this.length\n }\n if (val.length === 1) {\n var code = val.charCodeAt(0)\n if (code < 256) {\n val = code\n }\n }\n if (encoding !== undefined && typeof encoding !== 'string') {\n throw new TypeError('encoding must be a string')\n }\n if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {\n throw new TypeError('Unknown encoding: ' + encoding)\n }\n } else if (typeof val === 'number') {\n val = val & 255\n }\n\n // Invalid ranges are not set to a default, so can range check early.\n if (start < 0 || this.length < start || this.length < end) {\n throw new RangeError('Out of range index')\n }\n\n if (end <= start) {\n return this\n }\n\n start = start >>> 0\n end = end === undefined ? this.length : end >>> 0\n\n if (!val) val = 0\n\n var i\n if (typeof val === 'number') {\n for (i = start; i < end; ++i) {\n this[i] = val\n }\n } else {\n var bytes = Buffer.isBuffer(val)\n ? val\n : new Buffer(val, encoding)\n var len = bytes.length\n for (i = 0; i < end - start; ++i) {\n this[i + start] = bytes[i % len]\n }\n }\n\n return this\n}\n\n// HELPER FUNCTIONS\n// ================\n\nvar INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g\n\nfunction base64clean (str) {\n // Node strips out invalid characters like \\n and \\t from the string, base64-js does not\n str = str.trim().replace(INVALID_BASE64_RE, '')\n // Node converts strings with length < 2 to ''\n if (str.length < 2) return ''\n // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not\n while (str.length % 4 !== 0) {\n str = str + '='\n }\n return str\n}\n\nfunction toHex (n) {\n if (n < 16) return '0' + n.toString(16)\n return n.toString(16)\n}\n\nfunction utf8ToBytes (string, units) {\n units = units || Infinity\n var codePoint\n var length = string.length\n var leadSurrogate = null\n var bytes = []\n\n for (var i = 0; i < length; ++i) {\n codePoint = string.charCodeAt(i)\n\n // is surrogate component\n if (codePoint > 0xD7FF && codePoint < 0xE000) {\n // last char was a lead\n if (!leadSurrogate) {\n // no lead yet\n if (codePoint > 0xDBFF) {\n // unexpected trail\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n } else if (i + 1 === length) {\n // unpaired lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n }\n\n // valid lead\n leadSurrogate = codePoint\n\n continue\n }\n\n // 2 leads in a row\n if (codePoint < 0xDC00) {\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n leadSurrogate = codePoint\n continue\n }\n\n // valid surrogate pair\n codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000\n } else if (leadSurrogate) {\n // valid bmp char, but last char was a lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n }\n\n leadSurrogate = null\n\n // encode utf8\n if (codePoint < 0x80) {\n if ((units -= 1) < 0) break\n bytes.push(codePoint)\n } else if (codePoint < 0x800) {\n if ((units -= 2) < 0) break\n bytes.push(\n codePoint >> 0x6 | 0xC0,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x10000) {\n if ((units -= 3) < 0) break\n bytes.push(\n codePoint >> 0xC | 0xE0,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x110000) {\n if ((units -= 4) < 0) break\n bytes.push(\n codePoint >> 0x12 | 0xF0,\n codePoint >> 0xC & 0x3F | 0x80,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else {\n throw new Error('Invalid code point')\n }\n }\n\n return bytes\n}\n\nfunction asciiToBytes (str) {\n var byteArray = []\n for (var i = 0; i < str.length; ++i) {\n // Node's code seems to be doing this and not & 0x7F..\n byteArray.push(str.charCodeAt(i) & 0xFF)\n }\n return byteArray\n}\n\nfunction utf16leToBytes (str, units) {\n var c, hi, lo\n var byteArray = []\n for (var i = 0; i < str.length; ++i) {\n if ((units -= 2) < 0) break\n\n c = str.charCodeAt(i)\n hi = c >> 8\n lo = c % 256\n byteArray.push(lo)\n byteArray.push(hi)\n }\n\n return byteArray\n}\n\nfunction base64ToBytes (str) {\n return base64.toByteArray(base64clean(str))\n}\n\nfunction blitBuffer (src, dst, offset, length) {\n for (var i = 0; i < length; ++i) {\n if ((i + offset >= dst.length) || (i >= src.length)) break\n dst[i + offset] = src[i]\n }\n return i\n}\n\n// ArrayBuffers from another context (i.e. an iframe) do not pass the `instanceof` check\n// but they should be treated as valid. See: https://github.com/feross/buffer/issues/166\nfunction isArrayBuffer (obj) {\n return obj instanceof ArrayBuffer ||\n (obj != null && obj.constructor != null && obj.constructor.name === 'ArrayBuffer' &&\n typeof obj.byteLength === 'number')\n}\n\n// Node 0.10 supports `ArrayBuffer` but lacks `ArrayBuffer.isView`\nfunction isArrayBufferView (obj) {\n return (typeof ArrayBuffer.isView === 'function') && ArrayBuffer.isView(obj)\n}\n\nfunction numberIsNaN (obj) {\n return obj !== obj // eslint-disable-line no-self-compare\n}\n","import { Buffer } from 'buffer/';\nimport { getBaseURL } from './utils';\n\nfunction parseBodyToType(res) {\n if (res.headers.get('Content-Type') === 'application/json') {\n return res.json().then(data => [res, data]);\n }\n return res.text().then(data => [res, data]);\n}\n\nexport function rpcRequest(fetch) {\n return function rpcRequestWithFetch(path, body, auth, host, accessToken, options) {\n const fetchOptions = {\n method: 'POST',\n body: (body) ? JSON.stringify(body) : null,\n };\n const headers = {};\n if (body) {\n headers['Content-Type'] = 'application/json';\n }\n let authHeader = '';\n\n switch (auth) {\n case 'app':\n if (!options.clientId || !options.clientSecret) {\n throw new Error('A client id and secret is required for this function');\n }\n authHeader = new Buffer(`${options.clientId}:${options.clientSecret}`).toString('base64');\n headers.Authorization = `Basic ${authHeader}`;\n break;\n case 'team':\n case 'user':\n headers.Authorization = `Bearer ${accessToken}`;\n break;\n case 'noauth':\n break;\n default:\n throw new Error(`Unhandled auth type: ${auth}`);\n }\n\n if (options) {\n if (options.selectUser) {\n headers['Dropbox-API-Select-User'] = options.selectUser;\n }\n if (options.selectAdmin) {\n headers['Dropbox-API-Select-Admin'] = options.selectAdmin;\n }\n if (options.pathRoot) {\n headers['Dropbox-API-Path-Root'] = options.pathRoot;\n }\n }\n\n fetchOptions.headers = headers;\n return fetch(getBaseURL(host) + path, fetchOptions)\n .then(res => parseBodyToType(res))\n .then(([res, data]) => {\n // maintaining existing API for error codes not equal to 200 range\n if (!res.ok) {\n // eslint-disable-next-line no-throw-literal\n throw {\n error: data,\n response: res,\n status: res.status,\n };\n }\n\n return data;\n });\n };\n}\n","import { UPLOAD, DOWNLOAD, RPC } from './constants';\nimport { downloadRequest } from './download-request';\nimport { uploadRequest } from './upload-request';\nimport { rpcRequest } from './rpc-request';\n\n/* eslint-disable */\n// Polyfill object.assign for legacy browsers\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign\nif (typeof Object.assign !== 'function') {\n (function () {\n Object.assign = function (target) {\n 'use strict';\n var output;\n var index;\n var source;\n var nextKey;\n if (target === undefined || target === null) {\n throw new TypeError('Cannot convert undefined or null to object');\n }\n\n output = Object(target);\n for (index = 1; index < arguments.length; index++) {\n source = arguments[index];\n if (source !== undefined && source !== null) {\n for (nextKey in source) {\n if (source.hasOwnProperty(nextKey)) {\n output[nextKey] = source[nextKey];\n }\n }\n }\n }\n return output;\n };\n }());\n}\n\n// Polyfill Array.includes for legacy browsers\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes\n// https://tc39.github.io/ecma262/#sec-array.prototype.includes\nif (!Array.prototype.includes) {\n Object.defineProperty(Array.prototype, 'includes', {\n value: function(searchElement, fromIndex) {\n\n if (this == null) {\n throw new TypeError('\"this\" is null or not defined');\n }\n\n // 1. Let O be ? ToObject(this value).\n var o = Object(this);\n\n // 2. Let len be ? ToLength(? Get(O, \"length\")).\n var len = o.length >>> 0;\n\n // 3. If len is 0, return false.\n if (len === 0) {\n return false;\n }\n\n // 4. Let n be ? ToInteger(fromIndex).\n // (If fromIndex is undefined, this step produces the value 0.)\n var n = fromIndex | 0;\n\n // 5. If n ≥ 0, then\n // a. Let k be n.\n // 6. Else n < 0,\n // a. Let k be len + n.\n // b. If k < 0, let k be 0.\n var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);\n\n function sameValueZero(x, y) {\n return x === y || (typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y));\n }\n\n // 7. Repeat, while k < len\n while (k < len) {\n // a. Let elementK be the result of ? Get(O, ! ToString(k)).\n // b. If SameValueZero(searchElement, elementK) is true, return true.\n if (sameValueZero(o[k], searchElement)) {\n return true;\n }\n // c. Increase k by 1.\n k++;\n }\n\n // 8. Return false\n return false;\n }\n });\n}\n/* eslint-enable */\n\n/**\n * @private\n * @class DropboxBase\n * @classdesc The main Dropbox SDK class. This contains the methods that are\n * shared between Dropbox and DropboxTeam classes. It is marked as private so\n * that it doesn't show up in the docs because it is never used directly.\n * @arg {Object} options\n * @arg {Function} [options.fetch] - fetch library for making requests.\n * @arg {String} [options.accessToken] - An access token for making authenticated\n * requests.\n * @arg {String} [options.clientId] - The client id for your app. Used to create\n * authentication URL.\n * @arg {String} [options.clientSecret] - The client secret for your app.\n * @arg {Number} [options.selectUser] - User that the team access token would like\n * to act as.\n * @arg {String} [options.selectAdmin] - Team admin that the team access token would like\n * to act as.\n * @arg {String} [options.pathRoot] - root pass to access other namespaces\n * Use to access team folders for example\n */\n\nfunction parseBodyToType(res) {\n const clone = res.clone();\n return new Promise((resolve) => {\n res.json()\n .then(data => resolve(data))\n .catch(() => clone.text().then(data => resolve(data)));\n }).then(data => [res, data]);\n}\n\nexport class DropboxBase {\n constructor(options) {\n options = options || {};\n this.accessToken = options.accessToken;\n this.clientId = options.clientId;\n this.clientSecret = options.clientSecret;\n this.selectUser = options.selectUser;\n this.selectAdmin = options.selectAdmin;\n this.fetch = options.fetch || fetch;\n this.pathRoot = options.pathRoot;\n if (!options.fetch) { console.warn('Global fetch is deprecated and will be unsupported in a future version. Please pass fetch function as option when instantiating dropbox instance: new Dropbox({fetch})'); } // eslint-disable-line no-console\n }\n\n /**\n * Set the access token used to authenticate requests to the API.\n * @arg {String} accessToken - An access token\n * @returns {undefined}\n */\n setAccessToken(accessToken) {\n this.accessToken = accessToken;\n }\n\n /**\n * Get the access token\n * @returns {String} Access token\n */\n getAccessToken() {\n return this.accessToken;\n }\n\n /**\n * Set the client id, which is used to help gain an access token.\n * @arg {String} clientId - Your apps client id\n * @returns {undefined}\n */\n setClientId(clientId) {\n this.clientId = clientId;\n }\n\n /**\n * Get the client id\n * @returns {String} Client id\n */\n getClientId() {\n return this.clientId;\n }\n\n /**\n * Set the client secret\n * @arg {String} clientSecret - Your app's client secret\n * @returns {undefined}\n */\n setClientSecret(clientSecret) {\n this.clientSecret = clientSecret;\n }\n\n /**\n * Get the client secret\n * @returns {String} Client secret\n */\n getClientSecret() {\n return this.clientSecret;\n }\n\n /**\n * Get a URL that can be used to authenticate users for the Dropbox API.\n * @arg {String} redirectUri - A URL to redirect the user to after\n * authenticating. This must be added to your app through the admin interface.\n * @arg {String} [state] - State that will be returned in the redirect URL to help\n * prevent cross site scripting attacks.\n * @arg {String} [authType] - auth type, defaults to 'token', other option is 'code'\n * @returns {String} Url to send user to for Dropbox API authentication\n */\n getAuthenticationUrl(redirectUri, state, authType = 'token') {\n const clientId = this.getClientId();\n const baseUrl = 'https://www.dropbox.com/oauth2/authorize';\n\n if (!clientId) {\n throw new Error('A client id is required. You can set the client id using .setClientId().');\n }\n if (authType !== 'code' && !redirectUri) {\n throw new Error('A redirect uri is required.');\n }\n if (!['code', 'token'].includes(authType)) {\n throw new Error('Authorization type must be code or token');\n }\n\n let authUrl;\n if (authType === 'code') {\n authUrl = `${baseUrl}?response_type=code&client_id=${clientId}`;\n } else {\n authUrl = `${baseUrl}?response_type=token&client_id=${clientId}`;\n }\n\n if (redirectUri) {\n authUrl += `&redirect_uri=${redirectUri}`;\n }\n if (state) {\n authUrl += `&state=${state}`;\n }\n return authUrl;\n }\n\n /**\n * Get an OAuth2 access token from an OAuth2 Code.\n * @arg {String} redirectUri - A URL to redirect the user to after\n * authenticating. This must be added to your app through the admin interface.\n * @arg {String} code - An OAuth2 code.\n */\n getAccessTokenFromCode(redirectUri, code) {\n const clientId = this.getClientId();\n const clientSecret = this.getClientSecret();\n\n if (!clientId) {\n throw new Error('A client id is required. You can set the client id using .setClientId().');\n }\n if (!clientSecret) {\n throw new Error('A client secret is required. You can set the client id using .setClientSecret().');\n }\n const path = `https://api.dropboxapi.com/oauth2/token?code=${code}&\\\ngrant_type=authorization_code&redirect_uri=${redirectUri}&\\\nclient_id=${clientId}&client_secret=${clientSecret}`;\n\n const fetchOptions = {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded',\n },\n };\n\n return this.fetch(path, fetchOptions)\n .then(res => parseBodyToType(res))\n .then(([res, data]) => {\n // maintaining existing API for error codes not equal to 200 range\n if (!res.ok) {\n // eslint-disable-next-line no-throw-literal\n throw {\n error: data,\n response: res,\n status: res.status,\n };\n }\n return data.access_token;\n });\n }\n\n /**\n * Called when the authentication succeed\n * @callback successCallback\n * @param {string} access_token The application's access token\n */\n\n /**\n * Called when the authentication failed.\n * @callback errorCallback\n */\n\n\n /**\n * An authentication process that works with cordova applications.\n * @param {successCallback} successCallback\n * @param {errorCallback} errorCallback\n */\n authenticateWithCordova(successCallback, errorCallback) {\n const redirectUrl = 'https://www.dropbox.com/1/oauth2/redirect_receiver';\n const url = this.getAuthenticationUrl(redirectUrl);\n\n let removed = false;\n const browser = window.open(url, '_blank');\n\n function onLoadError(event) {\n if (event.code !== -999) { // Workaround to fix wrong behavior on cordova-plugin-inappbrowser\n // Try to avoid a browser crash on browser.close().\n window.setTimeout(() => { browser.close(); }, 10);\n errorCallback();\n }\n }\n\n function onLoadStop(event) {\n const errorLabel = '&error=';\n const errorIndex = event.url.indexOf(errorLabel);\n\n if (errorIndex > -1) {\n // Try to avoid a browser crash on browser.close().\n window.setTimeout(() => { browser.close(); }, 10);\n errorCallback();\n } else {\n const tokenLabel = '#access_token=';\n let tokenIndex = event.url.indexOf(tokenLabel);\n const tokenTypeIndex = event.url.indexOf('&token_type=');\n if (tokenIndex > -1) {\n tokenIndex += tokenLabel.length;\n // Try to avoid a browser crash on browser.close().\n window.setTimeout(() => { browser.close(); }, 10);\n\n const accessToken = event.url.substring(tokenIndex, tokenTypeIndex);\n successCallback(accessToken);\n }\n }\n }\n\n function onExit() {\n if (removed) {\n return;\n }\n browser.removeEventListener('loaderror', onLoadError);\n browser.removeEventListener('loadstop', onLoadStop);\n browser.removeEventListener('exit', onExit);\n removed = true;\n }\n\n browser.addEventListener('loaderror', onLoadError);\n browser.addEventListener('loadstop', onLoadStop);\n browser.addEventListener('exit', onExit);\n }\n\n request(path, args, auth, host, style) {\n let request = null;\n switch (style) {\n case RPC:\n request = this.getRpcRequest();\n break;\n case DOWNLOAD:\n request = this.getDownloadRequest();\n break;\n case UPLOAD:\n request = this.getUploadRequest();\n break;\n default:\n throw new Error(`Invalid request style: ${style}`);\n }\n const options = {\n selectUser: this.selectUser,\n selectAdmin: this.selectAdmin,\n clientId: this.getClientId(),\n clientSecret: this.getClientSecret(),\n pathRoot: this.pathRoot,\n };\n return request(path, args, auth, host, this.getAccessToken(), options);\n }\n\n setRpcRequest(newRpcRequest) {\n this.rpcRequest = newRpcRequest;\n }\n\n getRpcRequest() {\n if (this.rpcRequest === undefined) {\n this.rpcRequest = rpcRequest(this.fetch);\n }\n return this.rpcRequest;\n }\n\n setDownloadRequest(newDownloadRequest) {\n this.downloadRequest = newDownloadRequest;\n }\n\n getDownloadRequest() {\n if (this.downloadRequest === undefined) {\n this.downloadRequest = downloadRequest(this.fetch);\n }\n return this.downloadRequest;\n }\n\n setUploadRequest(newUploadRequest) {\n this.uploadRequest = newUploadRequest;\n }\n\n getUploadRequest() {\n if (this.uploadRequest === undefined) {\n this.uploadRequest = uploadRequest(this.fetch);\n }\n return this.uploadRequest;\n }\n\n}\n","import { routes } from './routes';\nimport { DropboxBase } from './dropbox-base';\n\n/**\n * @class Dropbox\n * @extends DropboxBase\n * @classdesc The Dropbox SDK class that provides methods to read, write and\n * create files or folders in a user's Dropbox.\n * @arg {Object} options\n * @arg {Function} [options.fetch] - fetch library for making requests.\n * @arg {String} [options.accessToken] - An access token for making authenticated\n * requests.\n * @arg {String} [options.clientId] - The client id for your app. Used to create\n * authentication URL.\n * @arg {String} [options.selectUser] - Select user is only used by DropboxTeam.\n * It specifies which user the team access token should be acting as.\n * @arg {String} [options.pathRoot] - root pass to access other namespaces\n * Use to access team folders for example\n */\nexport class Dropbox extends DropboxBase {\n\n constructor(options) {\n super(options);\n Object.assign(this, routes);\n }\n\n filesGetSharedLinkFile(arg) {\n return this.request('sharing/get_shared_link_file', arg, 'api', 'download');\n }\n}\n","// Auto-generated by Stone, do not modify.\nvar routes = {};\n\n/**\n * List all device sessions of a team's member.\n * @function DropboxTeam#teamDevicesListMemberDevices\n * @arg {TeamListMemberDevicesArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.teamDevicesListMemberDevices = function (arg) {\n return this.request('team/devices/list_member_devices', arg, 'team', 'api', 'rpc');\n};\n\n/**\n * List all device sessions of a team. Permission : Team member file access.\n * @function DropboxTeam#teamDevicesListMembersDevices\n * @arg {TeamListMembersDevicesArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.teamDevicesListMembersDevices = function (arg) {\n return this.request('team/devices/list_members_devices', arg, 'team', 'api', 'rpc');\n};\n\n/**\n * List all device sessions of a team. Permission : Team member file access.\n * @function DropboxTeam#teamDevicesListTeamDevices\n * @deprecated\n * @arg {TeamListTeamDevicesArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.teamDevicesListTeamDevices = function (arg) {\n return this.request('team/devices/list_team_devices', arg, 'team', 'api', 'rpc');\n};\n\n/**\n * Revoke a device session of a team's member.\n * @function DropboxTeam#teamDevicesRevokeDeviceSession\n * @arg {TeamRevokeDeviceSessionArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.teamDevicesRevokeDeviceSession = function (arg) {\n return this.request('team/devices/revoke_device_session', arg, 'team', 'api', 'rpc');\n};\n\n/**\n * Revoke a list of device sessions of team members.\n * @function DropboxTeam#teamDevicesRevokeDeviceSessionBatch\n * @arg {TeamRevokeDeviceSessionBatchArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.teamDevicesRevokeDeviceSessionBatch = function (arg) {\n return this.request('team/devices/revoke_device_session_batch', arg, 'team', 'api', 'rpc');\n};\n\n/**\n * Get the values for one or more featues. This route allows you to check your\n * account's capability for what feature you can access or what value you have\n * for certain features. Permission : Team information.\n * @function DropboxTeam#teamFeaturesGetValues\n * @arg {TeamFeaturesGetValuesBatchArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.teamFeaturesGetValues = function (arg) {\n return this.request('team/features/get_values', arg, 'team', 'api', 'rpc');\n};\n\n/**\n * Retrieves information about a team.\n * @function DropboxTeam#teamGetInfo\n * @arg {void} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.teamGetInfo = function (arg) {\n return this.request('team/get_info', arg, 'team', 'api', 'rpc');\n};\n\n/**\n * Creates a new, empty group, with a requested name. Permission : Team member\n * management.\n * @function DropboxTeam#teamGroupsCreate\n * @arg {TeamGroupCreateArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.teamGroupsCreate = function (arg) {\n return this.request('team/groups/create', arg, 'team', 'api', 'rpc');\n};\n\n/**\n * Deletes a group. The group is deleted immediately. However the revoking of\n * group-owned resources may take additional time. Use the groups/job_status/get\n * to determine whether this process has completed. Permission : Team member\n * management.\n * @function DropboxTeam#teamGroupsDelete\n * @arg {TeamGroupSelector} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.teamGroupsDelete = function (arg) {\n return this.request('team/groups/delete', arg, 'team', 'api', 'rpc');\n};\n\n/**\n * Retrieves information about one or more groups. Note that the optional field\n * GroupFullInfo.members is not returned for system-managed groups. Permission :\n * Team Information.\n * @function DropboxTeam#teamGroupsGetInfo\n * @arg {TeamGroupsSelector} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.teamGroupsGetInfo = function (arg) {\n return this.request('team/groups/get_info', arg, 'team', 'api', 'rpc');\n};\n\n/**\n * Once an async_job_id is returned from groups/delete, groups/members/add , or\n * groups/members/remove use this method to poll the status of granting/revoking\n * group members' access to group-owned resources. Permission : Team member\n * management.\n * @function DropboxTeam#teamGroupsJobStatusGet\n * @arg {AsyncPollArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.teamGroupsJobStatusGet = function (arg) {\n return this.request('team/groups/job_status/get', arg, 'team', 'api', 'rpc');\n};\n\n/**\n * Lists groups on a team. Permission : Team Information.\n * @function DropboxTeam#teamGroupsList\n * @arg {TeamGroupsListArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.teamGroupsList = function (arg) {\n return this.request('team/groups/list', arg, 'team', 'api', 'rpc');\n};\n\n/**\n * Once a cursor has been retrieved from groups/list, use this to paginate\n * through all groups. Permission : Team Information.\n * @function DropboxTeam#teamGroupsListContinue\n * @arg {TeamGroupsListContinueArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.teamGroupsListContinue = function (arg) {\n return this.request('team/groups/list/continue', arg, 'team', 'api', 'rpc');\n};\n\n/**\n * Adds members to a group. The members are added immediately. However the\n * granting of group-owned resources may take additional time. Use the\n * groups/job_status/get to determine whether this process has completed.\n * Permission : Team member management.\n * @function DropboxTeam#teamGroupsMembersAdd\n * @arg {TeamGroupMembersAddArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.teamGroupsMembersAdd = function (arg) {\n return this.request('team/groups/members/add', arg, 'team', 'api', 'rpc');\n};\n\n/**\n * Lists members of a group. Permission : Team Information.\n * @function DropboxTeam#teamGroupsMembersList\n * @arg {TeamGroupsMembersListArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.teamGroupsMembersList = function (arg) {\n return this.request('team/groups/members/list', arg, 'team', 'api', 'rpc');\n};\n\n/**\n * Once a cursor has been retrieved from groups/members/list, use this to\n * paginate through all members of the group. Permission : Team information.\n * @function DropboxTeam#teamGroupsMembersListContinue\n * @arg {TeamGroupsMembersListContinueArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.teamGroupsMembersListContinue = function (arg) {\n return this.request('team/groups/members/list/continue', arg, 'team', 'api', 'rpc');\n};\n\n/**\n * Removes members from a group. The members are removed immediately. However\n * the revoking of group-owned resources may take additional time. Use the\n * groups/job_status/get to determine whether this process has completed. This\n * method permits removing the only owner of a group, even in cases where this\n * is not possible via the web client. Permission : Team member management.\n * @function DropboxTeam#teamGroupsMembersRemove\n * @arg {TeamGroupMembersRemoveArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.teamGroupsMembersRemove = function (arg) {\n return this.request('team/groups/members/remove', arg, 'team', 'api', 'rpc');\n};\n\n/**\n * Sets a member's access type in a group. Permission : Team member management.\n * @function DropboxTeam#teamGroupsMembersSetAccessType\n * @arg {TeamGroupMembersSetAccessTypeArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.teamGroupsMembersSetAccessType = function (arg) {\n return this.request('team/groups/members/set_access_type', arg, 'team', 'api', 'rpc');\n};\n\n/**\n * Updates a group's name and/or external ID. Permission : Team member\n * management.\n * @function DropboxTeam#teamGroupsUpdate\n * @arg {TeamGroupUpdateArgs} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.teamGroupsUpdate = function (arg) {\n return this.request('team/groups/update', arg, 'team', 'api', 'rpc');\n};\n\n/**\n * List all linked applications of the team member. Note, this endpoint does not\n * list any team-linked applications.\n * @function DropboxTeam#teamLinkedAppsListMemberLinkedApps\n * @arg {TeamListMemberAppsArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.teamLinkedAppsListMemberLinkedApps = function (arg) {\n return this.request('team/linked_apps/list_member_linked_apps', arg, 'team', 'api', 'rpc');\n};\n\n/**\n * List all applications linked to the team members' accounts. Note, this\n * endpoint does not list any team-linked applications.\n * @function DropboxTeam#teamLinkedAppsListMembersLinkedApps\n * @arg {TeamListMembersAppsArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.teamLinkedAppsListMembersLinkedApps = function (arg) {\n return this.request('team/linked_apps/list_members_linked_apps', arg, 'team', 'api', 'rpc');\n};\n\n/**\n * List all applications linked to the team members' accounts. Note, this\n * endpoint doesn't list any team-linked applications.\n * @function DropboxTeam#teamLinkedAppsListTeamLinkedApps\n * @deprecated\n * @arg {TeamListTeamAppsArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.teamLinkedAppsListTeamLinkedApps = function (arg) {\n return this.request('team/linked_apps/list_team_linked_apps', arg, 'team', 'api', 'rpc');\n};\n\n/**\n * Revoke a linked application of the team member.\n * @function DropboxTeam#teamLinkedAppsRevokeLinkedApp\n * @arg {TeamRevokeLinkedApiAppArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.teamLinkedAppsRevokeLinkedApp = function (arg) {\n return this.request('team/linked_apps/revoke_linked_app', arg, 'team', 'api', 'rpc');\n};\n\n/**\n * Revoke a list of linked applications of the team members.\n * @function DropboxTeam#teamLinkedAppsRevokeLinkedAppBatch\n * @arg {TeamRevokeLinkedApiAppBatchArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.teamLinkedAppsRevokeLinkedAppBatch = function (arg) {\n return this.request('team/linked_apps/revoke_linked_app_batch', arg, 'team', 'api', 'rpc');\n};\n\n/**\n * Add users to member space limits excluded users list.\n * @function DropboxTeam#teamMemberSpaceLimitsExcludedUsersAdd\n * @arg {TeamExcludedUsersUpdateArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.teamMemberSpaceLimitsExcludedUsersAdd = function (arg) {\n return this.request('team/member_space_limits/excluded_users/add', arg, 'team', 'api', 'rpc');\n};\n\n/**\n * List member space limits excluded users.\n * @function DropboxTeam#teamMemberSpaceLimitsExcludedUsersList\n * @arg {TeamExcludedUsersListArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.teamMemberSpaceLimitsExcludedUsersList = function (arg) {\n return this.request('team/member_space_limits/excluded_users/list', arg, 'team', 'api', 'rpc');\n};\n\n/**\n * Continue listing member space limits excluded users.\n * @function DropboxTeam#teamMemberSpaceLimitsExcludedUsersListContinue\n * @arg {TeamExcludedUsersListContinueArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.teamMemberSpaceLimitsExcludedUsersListContinue = function (arg) {\n return this.request('team/member_space_limits/excluded_users/list/continue', arg, 'team', 'api', 'rpc');\n};\n\n/**\n * Remove users from member space limits excluded users list.\n * @function DropboxTeam#teamMemberSpaceLimitsExcludedUsersRemove\n * @arg {TeamExcludedUsersUpdateArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.teamMemberSpaceLimitsExcludedUsersRemove = function (arg) {\n return this.request('team/member_space_limits/excluded_users/remove', arg, 'team', 'api', 'rpc');\n};\n\n/**\n * Get users custom quota. Returns none as the custom quota if none was set. A\n * maximum of 1000 members can be specified in a single call.\n * @function DropboxTeam#teamMemberSpaceLimitsGetCustomQuota\n * @arg {TeamCustomQuotaUsersArg} arg - The request parameters.\n * @returns {Promise., Error.>}\n */\nroutes.teamMemberSpaceLimitsGetCustomQuota = function (arg) {\n return this.request('team/member_space_limits/get_custom_quota', arg, 'team', 'api', 'rpc');\n};\n\n/**\n * Remove users custom quota. A maximum of 1000 members can be specified in a\n * single call.\n * @function DropboxTeam#teamMemberSpaceLimitsRemoveCustomQuota\n * @arg {TeamCustomQuotaUsersArg} arg - The request parameters.\n * @returns {Promise., Error.>}\n */\nroutes.teamMemberSpaceLimitsRemoveCustomQuota = function (arg) {\n return this.request('team/member_space_limits/remove_custom_quota', arg, 'team', 'api', 'rpc');\n};\n\n/**\n * Set users custom quota. Custom quota has to be at least 15GB. A maximum of\n * 1000 members can be specified in a single call.\n * @function DropboxTeam#teamMemberSpaceLimitsSetCustomQuota\n * @arg {TeamSetCustomQuotaArg} arg - The request parameters.\n * @returns {Promise., Error.>}\n */\nroutes.teamMemberSpaceLimitsSetCustomQuota = function (arg) {\n return this.request('team/member_space_limits/set_custom_quota', arg, 'team', 'api', 'rpc');\n};\n\n/**\n * Adds members to a team. Permission : Team member management A maximum of 20\n * members can be specified in a single call. If no Dropbox account exists with\n * the email address specified, a new Dropbox account will be created with the\n * given email address, and that account will be invited to the team. If a\n * personal Dropbox account exists with the email address specified in the call,\n * this call will create a placeholder Dropbox account for the user on the team\n * and send an email inviting the user to migrate their existing personal\n * account onto the team. Team member management apps are required to set an\n * initial given_name and surname for a user to use in the team invitation and\n * for 'Perform as team member' actions taken on the user before they become\n * 'active'.\n * @function DropboxTeam#teamMembersAdd\n * @arg {TeamMembersAddArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.teamMembersAdd = function (arg) {\n return this.request('team/members/add', arg, 'team', 'api', 'rpc');\n};\n\n/**\n * Once an async_job_id is returned from members/add , use this to poll the\n * status of the asynchronous request. Permission : Team member management.\n * @function DropboxTeam#teamMembersAddJobStatusGet\n * @arg {AsyncPollArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.teamMembersAddJobStatusGet = function (arg) {\n return this.request('team/members/add/job_status/get', arg, 'team', 'api', 'rpc');\n};\n\n/**\n * Returns information about multiple team members. Permission : Team\n * information This endpoint will return MembersGetInfoItem.id_not_found, for\n * IDs (or emails) that cannot be matched to a valid team member.\n * @function DropboxTeam#teamMembersGetInfo\n * @arg {TeamMembersGetInfoArgs} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.teamMembersGetInfo = function (arg) {\n return this.request('team/members/get_info', arg, 'team', 'api', 'rpc');\n};\n\n/**\n * Lists members of a team. Permission : Team information.\n * @function DropboxTeam#teamMembersList\n * @arg {TeamMembersListArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.teamMembersList = function (arg) {\n return this.request('team/members/list', arg, 'team', 'api', 'rpc');\n};\n\n/**\n * Once a cursor has been retrieved from members/list, use this to paginate\n * through all team members. Permission : Team information.\n * @function DropboxTeam#teamMembersListContinue\n * @arg {TeamMembersListContinueArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.teamMembersListContinue = function (arg) {\n return this.request('team/members/list/continue', arg, 'team', 'api', 'rpc');\n};\n\n/**\n * Moves removed member's files to a different member. This endpoint initiates\n * an asynchronous job. To obtain the final result of the job, the client should\n * periodically poll members/move_former_member_files/job_status/check.\n * Permission : Team member management.\n * @function DropboxTeam#teamMembersMoveFormerMemberFiles\n * @arg {TeamMembersDataTransferArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.teamMembersMoveFormerMemberFiles = function (arg) {\n return this.request('team/members/move_former_member_files', arg, 'team', 'api', 'rpc');\n};\n\n/**\n * Once an async_job_id is returned from members/move_former_member_files , use\n * this to poll the status of the asynchronous request. Permission : Team member\n * management.\n * @function DropboxTeam#teamMembersMoveFormerMemberFilesJobStatusCheck\n * @arg {AsyncPollArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.teamMembersMoveFormerMemberFilesJobStatusCheck = function (arg) {\n return this.request('team/members/move_former_member_files/job_status/check', arg, 'team', 'api', 'rpc');\n};\n\n/**\n * Recover a deleted member. Permission : Team member management Exactly one of\n * team_member_id, email, or external_id must be provided to identify the user\n * account.\n * @function DropboxTeam#teamMembersRecover\n * @arg {TeamMembersRecoverArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.teamMembersRecover = function (arg) {\n return this.request('team/members/recover', arg, 'team', 'api', 'rpc');\n};\n\n/**\n * Removes a member from a team. Permission : Team member management Exactly one\n * of team_member_id, email, or external_id must be provided to identify the\n * user account. Accounts can be recovered via members/recover for a 7 day\n * period or until the account has been permanently deleted or transferred to\n * another account (whichever comes first). Calling members/add while a user is\n * still recoverable on your team will return with\n * MemberAddResult.user_already_on_team. Accounts can have their files\n * transferred via the admin console for a limited time, based on the version\n * history length associated with the team (120 days for most teams). This\n * endpoint may initiate an asynchronous job. To obtain the final result of the\n * job, the client should periodically poll members/remove/job_status/get.\n * @function DropboxTeam#teamMembersRemove\n * @arg {TeamMembersRemoveArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.teamMembersRemove = function (arg) {\n return this.request('team/members/remove', arg, 'team', 'api', 'rpc');\n};\n\n/**\n * Once an async_job_id is returned from members/remove , use this to poll the\n * status of the asynchronous request. Permission : Team member management.\n * @function DropboxTeam#teamMembersRemoveJobStatusGet\n * @arg {AsyncPollArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.teamMembersRemoveJobStatusGet = function (arg) {\n return this.request('team/members/remove/job_status/get', arg, 'team', 'api', 'rpc');\n};\n\n/**\n * Sends welcome email to pending team member. Permission : Team member\n * management Exactly one of team_member_id, email, or external_id must be\n * provided to identify the user account. No-op if team member is not pending.\n * @function DropboxTeam#teamMembersSendWelcomeEmail\n * @arg {TeamUserSelectorArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.teamMembersSendWelcomeEmail = function (arg) {\n return this.request('team/members/send_welcome_email', arg, 'team', 'api', 'rpc');\n};\n\n/**\n * Updates a team member's permissions. Permission : Team member management.\n * @function DropboxTeam#teamMembersSetAdminPermissions\n * @arg {TeamMembersSetPermissionsArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.teamMembersSetAdminPermissions = function (arg) {\n return this.request('team/members/set_admin_permissions', arg, 'team', 'api', 'rpc');\n};\n\n/**\n * Updates a team member's profile. Permission : Team member management.\n * @function DropboxTeam#teamMembersSetProfile\n * @arg {TeamMembersSetProfileArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.teamMembersSetProfile = function (arg) {\n return this.request('team/members/set_profile', arg, 'team', 'api', 'rpc');\n};\n\n/**\n * Suspend a member from a team. Permission : Team member management Exactly one\n * of team_member_id, email, or external_id must be provided to identify the\n * user account.\n * @function DropboxTeam#teamMembersSuspend\n * @arg {TeamMembersDeactivateArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.teamMembersSuspend = function (arg) {\n return this.request('team/members/suspend', arg, 'team', 'api', 'rpc');\n};\n\n/**\n * Unsuspend a member from a team. Permission : Team member management Exactly\n * one of team_member_id, email, or external_id must be provided to identify the\n * user account.\n * @function DropboxTeam#teamMembersUnsuspend\n * @arg {TeamMembersUnsuspendArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.teamMembersUnsuspend = function (arg) {\n return this.request('team/members/unsuspend', arg, 'team', 'api', 'rpc');\n};\n\n/**\n * Returns a list of all team-accessible namespaces. This list includes team\n * folders, shared folders containing team members, team members' home\n * namespaces, and team members' app folders. Home namespaces and app folders\n * are always owned by this team or members of the team, but shared folders may\n * be owned by other users or other teams. Duplicates may occur in the list.\n * @function DropboxTeam#teamNamespacesList\n * @arg {TeamTeamNamespacesListArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.teamNamespacesList = function (arg) {\n return this.request('team/namespaces/list', arg, 'team', 'api', 'rpc');\n};\n\n/**\n * Once a cursor has been retrieved from namespaces/list, use this to paginate\n * through all team-accessible namespaces. Duplicates may occur in the list.\n * @function DropboxTeam#teamNamespacesListContinue\n * @arg {TeamTeamNamespacesListContinueArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.teamNamespacesListContinue = function (arg) {\n return this.request('team/namespaces/list/continue', arg, 'team', 'api', 'rpc');\n};\n\n/**\n * Permission : Team member file access.\n * @function DropboxTeam#teamPropertiesTemplateAdd\n * @deprecated\n * @arg {FilePropertiesAddTemplateArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.teamPropertiesTemplateAdd = function (arg) {\n return this.request('team/properties/template/add', arg, 'team', 'api', 'rpc');\n};\n\n/**\n * Permission : Team member file access.\n * @function DropboxTeam#teamPropertiesTemplateGet\n * @deprecated\n * @arg {FilePropertiesGetTemplateArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.teamPropertiesTemplateGet = function (arg) {\n return this.request('team/properties/template/get', arg, 'team', 'api', 'rpc');\n};\n\n/**\n * Permission : Team member file access.\n * @function DropboxTeam#teamPropertiesTemplateList\n * @deprecated\n * @arg {void} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.teamPropertiesTemplateList = function (arg) {\n return this.request('team/properties/template/list', arg, 'team', 'api', 'rpc');\n};\n\n/**\n * Permission : Team member file access.\n * @function DropboxTeam#teamPropertiesTemplateUpdate\n * @deprecated\n * @arg {FilePropertiesUpdateTemplateArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.teamPropertiesTemplateUpdate = function (arg) {\n return this.request('team/properties/template/update', arg, 'team', 'api', 'rpc');\n};\n\n/**\n * Retrieves reporting data about a team's user activity.\n * @function DropboxTeam#teamReportsGetActivity\n * @arg {TeamDateRange} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.teamReportsGetActivity = function (arg) {\n return this.request('team/reports/get_activity', arg, 'team', 'api', 'rpc');\n};\n\n/**\n * Retrieves reporting data about a team's linked devices.\n * @function DropboxTeam#teamReportsGetDevices\n * @arg {TeamDateRange} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.teamReportsGetDevices = function (arg) {\n return this.request('team/reports/get_devices', arg, 'team', 'api', 'rpc');\n};\n\n/**\n * Retrieves reporting data about a team's membership.\n * @function DropboxTeam#teamReportsGetMembership\n * @arg {TeamDateRange} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.teamReportsGetMembership = function (arg) {\n return this.request('team/reports/get_membership', arg, 'team', 'api', 'rpc');\n};\n\n/**\n * Retrieves reporting data about a team's storage usage.\n * @function DropboxTeam#teamReportsGetStorage\n * @arg {TeamDateRange} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.teamReportsGetStorage = function (arg) {\n return this.request('team/reports/get_storage', arg, 'team', 'api', 'rpc');\n};\n\n/**\n * Sets an archived team folder's status to active. Permission : Team member\n * file access.\n * @function DropboxTeam#teamTeamFolderActivate\n * @arg {TeamTeamFolderIdArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.teamTeamFolderActivate = function (arg) {\n return this.request('team/team_folder/activate', arg, 'team', 'api', 'rpc');\n};\n\n/**\n * Sets an active team folder's status to archived and removes all folder and\n * file members. Permission : Team member file access.\n * @function DropboxTeam#teamTeamFolderArchive\n * @arg {TeamTeamFolderArchiveArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.teamTeamFolderArchive = function (arg) {\n return this.request('team/team_folder/archive', arg, 'team', 'api', 'rpc');\n};\n\n/**\n * Returns the status of an asynchronous job for archiving a team folder.\n * Permission : Team member file access.\n * @function DropboxTeam#teamTeamFolderArchiveCheck\n * @arg {AsyncPollArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.teamTeamFolderArchiveCheck = function (arg) {\n return this.request('team/team_folder/archive/check', arg, 'team', 'api', 'rpc');\n};\n\n/**\n * Creates a new, active, team folder with no members. Permission : Team member\n * file access.\n * @function DropboxTeam#teamTeamFolderCreate\n * @arg {TeamTeamFolderCreateArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.teamTeamFolderCreate = function (arg) {\n return this.request('team/team_folder/create', arg, 'team', 'api', 'rpc');\n};\n\n/**\n * Retrieves metadata for team folders. Permission : Team member file access.\n * @function DropboxTeam#teamTeamFolderGetInfo\n * @arg {TeamTeamFolderIdListArg} arg - The request parameters.\n * @returns {Promise., Error.>}\n */\nroutes.teamTeamFolderGetInfo = function (arg) {\n return this.request('team/team_folder/get_info', arg, 'team', 'api', 'rpc');\n};\n\n/**\n * Lists all team folders. Permission : Team member file access.\n * @function DropboxTeam#teamTeamFolderList\n * @arg {TeamTeamFolderListArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.teamTeamFolderList = function (arg) {\n return this.request('team/team_folder/list', arg, 'team', 'api', 'rpc');\n};\n\n/**\n * Once a cursor has been retrieved from team_folder/list, use this to paginate\n * through all team folders. Permission : Team member file access.\n * @function DropboxTeam#teamTeamFolderListContinue\n * @arg {TeamTeamFolderListContinueArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.teamTeamFolderListContinue = function (arg) {\n return this.request('team/team_folder/list/continue', arg, 'team', 'api', 'rpc');\n};\n\n/**\n * Permanently deletes an archived team folder. Permission : Team member file\n * access.\n * @function DropboxTeam#teamTeamFolderPermanentlyDelete\n * @arg {TeamTeamFolderIdArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.teamTeamFolderPermanentlyDelete = function (arg) {\n return this.request('team/team_folder/permanently_delete', arg, 'team', 'api', 'rpc');\n};\n\n/**\n * Changes an active team folder's name. Permission : Team member file access.\n * @function DropboxTeam#teamTeamFolderRename\n * @arg {TeamTeamFolderRenameArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.teamTeamFolderRename = function (arg) {\n return this.request('team/team_folder/rename', arg, 'team', 'api', 'rpc');\n};\n\n/**\n * Updates the sync settings on a team folder or its contents. Use of this\n * endpoint requires that the team has team selective sync enabled.\n * @function DropboxTeam#teamTeamFolderUpdateSyncSettings\n * @arg {TeamTeamFolderUpdateSyncSettingsArg} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.teamTeamFolderUpdateSyncSettings = function (arg) {\n return this.request('team/team_folder/update_sync_settings', arg, 'team', 'api', 'rpc');\n};\n\n/**\n * Returns the member profile of the admin who generated the team access token\n * used to make the call.\n * @function DropboxTeam#teamTokenGetAuthenticatedAdmin\n * @arg {void} arg - The request parameters.\n * @returns {Promise.>}\n */\nroutes.teamTokenGetAuthenticatedAdmin = function (arg) {\n return this.request('team/token/get_authenticated_admin', arg, 'team', 'api', 'rpc');\n};\n\nexport { routes };\n","import { Dropbox } from '../dropbox';\nimport { DropboxBase } from '../dropbox-base';\nimport { routes } from '../routes-team';\n\n/**\n * @class DropboxTeam\n * @extends DropboxBase\n * @classdesc The Dropbox SDK class that provides access to team endpoints.\n * @arg {Object} options\n * @arg {String} [options.accessToken] - An access token for making authenticated\n * requests.\n * @arg {String} [options.clientId] - The client id for your app. Used to create\n * authentication URL.\n */\nexport class DropboxTeam extends DropboxBase {\n\n constructor(options) {\n super(options);\n Object.assign(this, routes);\n }\n\n /**\n * Returns an instance of Dropbox that can make calls to user api endpoints on\n * behalf of the passed user id, using the team access token.\n * @arg {String} userId - The user id to use the Dropbox class as\n * @returns {Dropbox} An instance of Dropbox used to make calls to user api\n * endpoints\n */\n actAsUser(userId) {\n return new Dropbox({\n accessToken: this.accessToken,\n clientId: this.clientId,\n selectUser: userId,\n });\n }\n}\n","const dropbox = require('./dropbox');\nconst dropboxTeam = require('./team/dropbox-team.js');\n\nmodule.exports = {\n Dropbox: dropbox.Dropbox,\n DropboxTeam: dropboxTeam.DropboxTeam,\n};\n"],"names":["routes","authTokenFromOauth1","arg","request","authTokenRevoke","contactsDeleteManualContacts","contactsDeleteManualContactsBatch","filePropertiesPropertiesAdd","filePropertiesPropertiesOverwrite","filePropertiesPropertiesRemove","filePropertiesPropertiesSearch","filePropertiesPropertiesSearchContinue","filePropertiesPropertiesUpdate","filePropertiesTemplatesAddForTeam","filePropertiesTemplatesAddForUser","filePropertiesTemplatesGetForTeam","filePropertiesTemplatesGetForUser","filePropertiesTemplatesListForTeam","filePropertiesTemplatesListForUser","filePropertiesTemplatesRemoveForTeam","filePropertiesTemplatesRemoveForUser","filePropertiesTemplatesUpdateForTeam","filePropertiesTemplatesUpdateForUser","fileRequestsCount","fileRequestsCreate","fileRequestsDelete","fileRequestsDeleteAllClosed","fileRequestsGet","fileRequestsListV2","fileRequestsList","fileRequestsListContinue","fileRequestsUpdate","filesAlphaGetMetadata","filesAlphaUpload","filesCopyV2","filesCopy","filesCopyBatchV2","filesCopyBatch","filesCopyBatchCheckV2","filesCopyBatchCheck","filesCopyReferenceGet","filesCopyReferenceSave","filesCreateFolderV2","filesCreateFolder","filesCreateFolderBatch","filesCreateFolderBatchCheck","filesDeleteV2","filesDelete","filesDeleteBatch","filesDeleteBatchCheck","filesDownload","filesDownloadZip","filesExport","filesGetMetadata","filesGetPreview","filesGetTemporaryLink","filesGetTemporaryUploadLink","filesGetThumbnail","filesGetThumbnailBatch","filesListFolder","filesListFolderContinue","filesListFolderGetLatestCursor","filesListFolderLongpoll","filesListRevisions","filesMoveV2","filesMove","filesMoveBatchV2","filesMoveBatch","filesMoveBatchCheckV2","filesMoveBatchCheck","filesPermanentlyDelete","filesPropertiesAdd","filesPropertiesOverwrite","filesPropertiesRemove","filesPropertiesTemplateGet","filesPropertiesTemplateList","filesPropertiesUpdate","filesRestore","filesSaveUrl","filesSaveUrlCheckJobStatus","filesSearch","filesUpload","filesUploadSessionAppendV2","filesUploadSessionAppend","filesUploadSessionFinish","filesUploadSessionFinishBatch","filesUploadSessionFinishBatchCheck","filesUploadSessionStart","paperDocsArchive","paperDocsCreate","paperDocsDownload","paperDocsFolderUsersList","paperDocsFolderUsersListContinue","paperDocsGetFolderInfo","paperDocsList","paperDocsListContinue","paperDocsPermanentlyDelete","paperDocsSharingPolicyGet","paperDocsSharingPolicySet","paperDocsUpdate","paperDocsUsersAdd","paperDocsUsersList","paperDocsUsersListContinue","paperDocsUsersRemove","sharingAddFileMember","sharingAddFolderMember","sharingChangeFileMemberAccess","sharingCheckJobStatus","sharingCheckRemoveMemberJobStatus","sharingCheckShareJobStatus","sharingCreateSharedLink","sharingCreateSharedLinkWithSettings","sharingGetFileMetadata","sharingGetFileMetadataBatch","sharingGetFolderMetadata","sharingGetSharedLinkFile","sharingGetSharedLinkMetadata","sharingGetSharedLinks","sharingListFileMembers","sharingListFileMembersBatch","sharingListFileMembersContinue","sharingListFolderMembers","sharingListFolderMembersContinue","sharingListFolders","sharingListFoldersContinue","sharingListMountableFolders","sharingListMountableFoldersContinue","sharingListReceivedFiles","sharingListReceivedFilesContinue","sharingListSharedLinks","sharingModifySharedLinkSettings","sharingMountFolder","sharingRelinquishFileMembership","sharingRelinquishFolderMembership","sharingRemoveFileMember","sharingRemoveFileMember2","sharingRemoveFolderMember","sharingRevokeSharedLink","sharingSetAccessInheritance","sharingShareFolder","sharingTransferFolder","sharingUnmountFolder","sharingUnshareFile","sharingUnshareFolder","sharingUpdateFileMember","sharingUpdateFolderMember","sharingUpdateFolderPolicy","teamLogGetEvents","teamLogGetEventsContinue","usersGetAccount","usersGetAccountBatch","usersGetCurrentAccount","usersGetSpaceUsage","RPC","UPLOAD","DOWNLOAD","getSafeUnicode","c","unicode","charCodeAt","toString","slice","isWindowOrWorker","WorkerGlobalScope","self","module","window","getBaseURL","host","httpHeaderSafeJson","args","JSON","stringify","replace","getDataFromConsumer","res","ok","text","blob","buffer","responseHandler","data","status","result","parse","headers","get","fileBlob","fileBinary","downloadRequest","fetch","downloadRequestWithFetch","path","auth","accessToken","options","Error","fetchOptions","selectUser","selectAdmin","pathRoot","then","parseBodyToType","clone","Promise","resolve","json","catch","uploadRequest","uploadRequestWithFetch","contents","base64","rpcRequest","rpcRequestWithFetch","body","authHeader","clientId","clientSecret","Buffer","Authorization","Object","assign","target","output","index","source","nextKey","undefined","TypeError","arguments","length","hasOwnProperty","Array","prototype","includes","defineProperty","searchElement","fromIndex","o","len","n","k","Math","max","abs","sameValueZero","x","y","isNaN","DropboxBase","warn","redirectUri","state","authType","getClientId","baseUrl","authUrl","code","getClientSecret","access_token","successCallback","errorCallback","redirectUrl","url","getAuthenticationUrl","removed","browser","open","onLoadError","event","setTimeout","close","onLoadStop","errorLabel","errorIndex","indexOf","tokenLabel","tokenIndex","tokenTypeIndex","substring","onExit","removeEventListener","addEventListener","style","getRpcRequest","getDownloadRequest","getUploadRequest","getAccessToken","newRpcRequest","newDownloadRequest","newUploadRequest","Dropbox","teamDevicesListMemberDevices","teamDevicesListMembersDevices","teamDevicesListTeamDevices","teamDevicesRevokeDeviceSession","teamDevicesRevokeDeviceSessionBatch","teamFeaturesGetValues","teamGetInfo","teamGroupsCreate","teamGroupsDelete","teamGroupsGetInfo","teamGroupsJobStatusGet","teamGroupsList","teamGroupsListContinue","teamGroupsMembersAdd","teamGroupsMembersList","teamGroupsMembersListContinue","teamGroupsMembersRemove","teamGroupsMembersSetAccessType","teamGroupsUpdate","teamLinkedAppsListMemberLinkedApps","teamLinkedAppsListMembersLinkedApps","teamLinkedAppsListTeamLinkedApps","teamLinkedAppsRevokeLinkedApp","teamLinkedAppsRevokeLinkedAppBatch","teamMemberSpaceLimitsExcludedUsersAdd","teamMemberSpaceLimitsExcludedUsersList","teamMemberSpaceLimitsExcludedUsersListContinue","teamMemberSpaceLimitsExcludedUsersRemove","teamMemberSpaceLimitsGetCustomQuota","teamMemberSpaceLimitsRemoveCustomQuota","teamMemberSpaceLimitsSetCustomQuota","teamMembersAdd","teamMembersAddJobStatusGet","teamMembersGetInfo","teamMembersList","teamMembersListContinue","teamMembersMoveFormerMemberFiles","teamMembersMoveFormerMemberFilesJobStatusCheck","teamMembersRecover","teamMembersRemove","teamMembersRemoveJobStatusGet","teamMembersSendWelcomeEmail","teamMembersSetAdminPermissions","teamMembersSetProfile","teamMembersSuspend","teamMembersUnsuspend","teamNamespacesList","teamNamespacesListContinue","teamPropertiesTemplateAdd","teamPropertiesTemplateGet","teamPropertiesTemplateList","teamPropertiesTemplateUpdate","teamReportsGetActivity","teamReportsGetDevices","teamReportsGetMembership","teamReportsGetStorage","teamTeamFolderActivate","teamTeamFolderArchive","teamTeamFolderArchiveCheck","teamTeamFolderCreate","teamTeamFolderGetInfo","teamTeamFolderList","teamTeamFolderListContinue","teamTeamFolderPermanentlyDelete","teamTeamFolderRename","teamTeamFolderUpdateSyncSettings","teamTokenGetAuthenticatedAdmin","DropboxTeam","userId","dropbox","dropboxTeam"],"mappings":";;;;;;AAAA;AACA,IAAIA,SAAS,EAAb;;;;;;;;AAQAA,OAAOC,mBAAP,GAA6B,UAAUC,GAAV,EAAe;SACnC,KAAKC,OAAL,CAAa,wBAAb,EAAuCD,GAAvC,EAA4C,KAA5C,EAAmD,KAAnD,EAA0D,KAA1D,CAAP;CADF;;;;;;;;AAUAF,OAAOI,eAAP,GAAyB,UAAUF,GAAV,EAAe;SAC/B,KAAKC,OAAL,CAAa,mBAAb,EAAkCD,GAAlC,EAAuC,MAAvC,EAA+C,KAA/C,EAAsD,KAAtD,CAAP;CADF;;;;;;;;;AAWAF,OAAOK,4BAAP,GAAsC,UAAUH,GAAV,EAAe;SAC5C,KAAKC,OAAL,CAAa,iCAAb,EAAgDD,GAAhD,EAAqD,MAArD,EAA6D,KAA7D,EAAoE,KAApE,CAAP;CADF;;;;;;;;AAUAF,OAAOM,iCAAP,GAA2C,UAAUJ,GAAV,EAAe;SACjD,KAAKC,OAAL,CAAa,uCAAb,EAAsDD,GAAtD,EAA2D,MAA3D,EAAmE,KAAnE,EAA0E,KAA1E,CAAP;CADF;;;;;;;;;AAWAF,OAAOO,2BAAP,GAAqC,UAAUL,GAAV,EAAe;SAC3C,KAAKC,OAAL,CAAa,gCAAb,EAA+CD,GAA/C,EAAoD,MAApD,EAA4D,KAA5D,EAAmE,KAAnE,CAAP;CADF;;;;;;;;;;;;AAcAF,OAAOQ,iCAAP,GAA2C,UAAUN,GAAV,EAAe;SACjD,KAAKC,OAAL,CAAa,sCAAb,EAAqDD,GAArD,EAA0D,MAA1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P,GAA0C,UAAUnW,GAAV,EAAe;SAChD,KAAKC,OAAL,CAAa,uCAAb,EAAsDD,GAAtD,EAA2D,MAA3D,EAAmE,KAAnE,EAA0E,KAA1E,CAAP;CADF;;;;;;;;;AAWAF,SAAOsW,8BAAP,GAAwC,UAAUpW,GAAV,EAAe;SAC9C,KAAKC,OAAL,CAAa,oCAAb,EAAmDD,GAAnD,EAAwD,MAAxD,EAAgE,KAAhE,EAAuE,KAAvE,CAAP;CADF,CAIA;;ACjvBA;;;;;;;;;;AAUA,IAAaqW,WAAb;;;uBAEcpK,OAAZ,EAAqB;;;yHACbA,OADa;;WAEZ0B,MAAP,QAAoB7N,QAApB;;;;;;;;;;;;;;;8BAUQwW,MAdZ,EAcoB;aACT,IAAIrE,OAAJ,CAAY;qBACJ,KAAKjG,WADD;kBAEP,KAAKsB,QAFE;oBAGLgJ;OAHP,CAAP;;;;EAf6B/G,WAAjC;;;;;;;;ACXA,UAAiB;WACNgH,QAAQtE,OADF;eAEFuE,YAAYH;CAF3B;;;;"} \ No newline at end of file diff --git a/bundles/Dropbox-sdk.min.js b/bundles/Dropbox-sdk.min.js deleted file mode 100644 index 26f13f1..0000000 --- a/bundles/Dropbox-sdk.min.js +++ /dev/null @@ -1 +0,0 @@ -!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):e.Dropbox=t()}(this,function(){"use strict";function e(){return"undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope||"undefined"==typeof module||"undefined"!=typeof window}function t(e){return"https://"+e+".dropboxapi.com/2/"}function r(e){return JSON.stringify(e).replace(/[\u007f-\uffff]/g,function(e){return"\\u"+("000"+e.charCodeAt(0).toString(16)).slice(-4)})}function n(e){var t=e.length;if(t%4>0)throw Error("Invalid string. Length must be a multiple of 4");return"="===e[t-2]?2:"="===e[t-1]?1:0}var i={};i.authTokenFromOauth1=function(e){return this.request("auth/token/from_oauth1",e,"app","api","rpc")},i.authTokenRevoke=function(e){return this.request("auth/token/revoke",e,"user","api","rpc")},i.contactsDeleteManualContacts=function(e){return this.request("contacts/delete_manual_contacts",e,"user","api","rpc")},i.contactsDeleteManualContactsBatch=function(e){return this.request("contacts/delete_manual_contacts_batch",e,"user","api","rpc")},i.filePropertiesPropertiesAdd=function(e){return this.request("file_properties/properties/add",e,"user","api","rpc")},i.filePropertiesPropertiesOverwrite=function(e){return this.request("file_properties/properties/overwrite",e,"user","api","rpc")},i.filePropertiesPropertiesRemove=function(e){return this.request("file_properties/properties/remove",e,"user","api","rpc")},i.filePropertiesPropertiesSearch=function(e){return this.request("file_properties/properties/search",e,"user","api","rpc")},i.filePropertiesPropertiesSearchContinue=function(e){return this.request("file_properties/properties/search/continue",e,"user","api","rpc")},i.filePropertiesPropertiesUpdate=function(e){return this.request("file_properties/properties/update",e,"user","api","rpc")},i.filePropertiesTemplatesAddForTeam=function(e){return this.request("file_properties/templates/add_for_team",e,"team","api","rpc")},i.filePropertiesTemplatesAddForUser=function(e){return this.request("file_properties/templates/add_for_user",e,"user","api","rpc")},i.filePropertiesTemplatesGetForTeam=function(e){return this.request("file_properties/templates/get_for_team",e,"team","api","rpc")},i.filePropertiesTemplatesGetForUser=function(e){return this.request("file_properties/templates/get_for_user",e,"user","api","rpc")},i.filePropertiesTemplatesListForTeam=function(e){return this.request("file_properties/templates/list_for_team",e,"team","api","rpc")},i.filePropertiesTemplatesListForUser=function(e){return this.request("file_properties/templates/list_for_user",e,"user","api","rpc")},i.filePropertiesTemplatesRemoveForTeam=function(e){return this.request("file_properties/templates/remove_for_team",e,"team","api","rpc")},i.filePropertiesTemplatesRemoveForUser=function(e){return this.request("file_properties/templates/remove_for_user",e,"user","api","rpc")},i.filePropertiesTemplatesUpdateForTeam=function(e){return this.request("file_properties/templates/update_for_team",e,"team","api","rpc")},i.filePropertiesTemplatesUpdateForUser=function(e){return this.request("file_properties/templates/update_for_user",e,"user","api","rpc")},i.fileRequestsCount=function(e){return this.request("file_requests/count",e,"user","api","rpc")},i.fileRequestsCreate=function(e){return this.request("file_requests/create",e,"user","api","rpc")},i.fileRequestsDelete=function(e){return this.request("file_requests/delete",e,"user","api","rpc")},i.fileRequestsDeleteAllClosed=function(e){return this.request("file_requests/delete_all_closed",e,"user","api","rpc")},i.fileRequestsGet=function(e){return this.request("file_requests/get",e,"user","api","rpc")},i.fileRequestsListV2=function(e){return this.request("file_requests/list_v2",e,"user","api","rpc")},i.fileRequestsList=function(e){return this.request("file_requests/list",e,"user","api","rpc")},i.fileRequestsListContinue=function(e){return this.request("file_requests/list/continue",e,"user","api","rpc")},i.fileRequestsUpdate=function(e){return this.request("file_requests/update",e,"user","api","rpc")},i.filesAlphaGetMetadata=function(e){return this.request("files/alpha/get_metadata",e,"user","api","rpc")},i.filesAlphaUpload=function(e){return this.request("files/alpha/upload",e,"user","content","upload")},i.filesCopyV2=function(e){return this.request("files/copy_v2",e,"user","api","rpc")},i.filesCopy=function(e){return this.request("files/copy",e,"user","api","rpc")},i.filesCopyBatchV2=function(e){return this.request("files/copy_batch_v2",e,"user","api","rpc")},i.filesCopyBatch=function(e){return this.request("files/copy_batch",e,"user","api","rpc")},i.filesCopyBatchCheckV2=function(e){return this.request("files/copy_batch/check_v2",e,"user","api","rpc")},i.filesCopyBatchCheck=function(e){return this.request("files/copy_batch/check",e,"user","api","rpc")},i.filesCopyReferenceGet=function(e){return this.request("files/copy_reference/get",e,"user","api","rpc")},i.filesCopyReferenceSave=function(e){return this.request("files/copy_reference/save",e,"user","api","rpc")},i.filesCreateFolderV2=function(e){return this.request("files/create_folder_v2",e,"user","api","rpc")},i.filesCreateFolder=function(e){return this.request("files/create_folder",e,"user","api","rpc")},i.filesCreateFolderBatch=function(e){return this.request("files/create_folder_batch",e,"user","api","rpc")},i.filesCreateFolderBatchCheck=function(e){return this.request("files/create_folder_batch/check",e,"user","api","rpc")},i.filesDeleteV2=function(e){return this.request("files/delete_v2",e,"user","api","rpc")},i.filesDelete=function(e){return this.request("files/delete",e,"user","api","rpc")},i.filesDeleteBatch=function(e){return this.request("files/delete_batch",e,"user","api","rpc")},i.filesDeleteBatchCheck=function(e){return this.request("files/delete_batch/check",e,"user","api","rpc")},i.filesDownload=function(e){return this.request("files/download",e,"user","content","download")},i.filesDownloadZip=function(e){return this.request("files/download_zip",e,"user","content","download")},i.filesExport=function(e){return this.request("files/export",e,"user","content","download")},i.filesGetMetadata=function(e){return this.request("files/get_metadata",e,"user","api","rpc")},i.filesGetPreview=function(e){return this.request("files/get_preview",e,"user","content","download")},i.filesGetTemporaryLink=function(e){return this.request("files/get_temporary_link",e,"user","api","rpc")},i.filesGetTemporaryUploadLink=function(e){return this.request("files/get_temporary_upload_link",e,"user","api","rpc")},i.filesGetThumbnail=function(e){return this.request("files/get_thumbnail",e,"user","content","download")},i.filesGetThumbnailBatch=function(e){return this.request("files/get_thumbnail_batch",e,"user","content","rpc")},i.filesListFolder=function(e){return this.request("files/list_folder",e,"user","api","rpc")},i.filesListFolderContinue=function(e){return this.request("files/list_folder/continue",e,"user","api","rpc")},i.filesListFolderGetLatestCursor=function(e){return this.request("files/list_folder/get_latest_cursor",e,"user","api","rpc")},i.filesListFolderLongpoll=function(e){return this.request("files/list_folder/longpoll",e,"noauth","notify","rpc")},i.filesListRevisions=function(e){return this.request("files/list_revisions",e,"user","api","rpc")},i.filesMoveV2=function(e){return this.request("files/move_v2",e,"user","api","rpc")},i.filesMove=function(e){return this.request("files/move",e,"user","api","rpc")},i.filesMoveBatchV2=function(e){return this.request("files/move_batch_v2",e,"user","api","rpc")},i.filesMoveBatch=function(e){return this.request("files/move_batch",e,"user","api","rpc")},i.filesMoveBatchCheckV2=function(e){return this.request("files/move_batch/check_v2",e,"user","api","rpc")},i.filesMoveBatchCheck=function(e){return this.request("files/move_batch/check",e,"user","api","rpc")},i.filesPermanentlyDelete=function(e){return this.request("files/permanently_delete",e,"user","api","rpc")},i.filesPropertiesAdd=function(e){return this.request("files/properties/add",e,"user","api","rpc")},i.filesPropertiesOverwrite=function(e){return this.request("files/properties/overwrite",e,"user","api","rpc")},i.filesPropertiesRemove=function(e){return this.request("files/properties/remove",e,"user","api","rpc")},i.filesPropertiesTemplateGet=function(e){return this.request("files/properties/template/get",e,"user","api","rpc")},i.filesPropertiesTemplateList=function(e){return this.request("files/properties/template/list",e,"user","api","rpc")},i.filesPropertiesUpdate=function(e){return this.request("files/properties/update",e,"user","api","rpc")},i.filesRestore=function(e){return this.request("files/restore",e,"user","api","rpc")},i.filesSaveUrl=function(e){return this.request("files/save_url",e,"user","api","rpc")},i.filesSaveUrlCheckJobStatus=function(e){return this.request("files/save_url/check_job_status",e,"user","api","rpc")},i.filesSearch=function(e){return this.request("files/search",e,"user","api","rpc")},i.filesUpload=function(e){return this.request("files/upload",e,"user","content","upload")},i.filesUploadSessionAppendV2=function(e){return this.request("files/upload_session/append_v2",e,"user","content","upload")},i.filesUploadSessionAppend=function(e){return this.request("files/upload_session/append",e,"user","content","upload")},i.filesUploadSessionFinish=function(e){return this.request("files/upload_session/finish",e,"user","content","upload")},i.filesUploadSessionFinishBatch=function(e){return this.request("files/upload_session/finish_batch",e,"user","api","rpc")},i.filesUploadSessionFinishBatchCheck=function(e){return this.request("files/upload_session/finish_batch/check",e,"user","api","rpc")},i.filesUploadSessionStart=function(e){return this.request("files/upload_session/start",e,"user","content","upload")},i.paperDocsArchive=function(e){return this.request("paper/docs/archive",e,"user","api","rpc")},i.paperDocsCreate=function(e){return this.request("paper/docs/create",e,"user","api","upload")},i.paperDocsDownload=function(e){return this.request("paper/docs/download",e,"user","api","download")},i.paperDocsFolderUsersList=function(e){return this.request("paper/docs/folder_users/list",e,"user","api","rpc")},i.paperDocsFolderUsersListContinue=function(e){return this.request("paper/docs/folder_users/list/continue",e,"user","api","rpc")},i.paperDocsGetFolderInfo=function(e){return this.request("paper/docs/get_folder_info",e,"user","api","rpc")},i.paperDocsList=function(e){return this.request("paper/docs/list",e,"user","api","rpc")},i.paperDocsListContinue=function(e){return this.request("paper/docs/list/continue",e,"user","api","rpc")},i.paperDocsPermanentlyDelete=function(e){return this.request("paper/docs/permanently_delete",e,"user","api","rpc")},i.paperDocsSharingPolicyGet=function(e){return this.request("paper/docs/sharing_policy/get",e,"user","api","rpc")},i.paperDocsSharingPolicySet=function(e){return this.request("paper/docs/sharing_policy/set",e,"user","api","rpc")},i.paperDocsUpdate=function(e){return this.request("paper/docs/update",e,"user","api","upload")},i.paperDocsUsersAdd=function(e){return this.request("paper/docs/users/add",e,"user","api","rpc")},i.paperDocsUsersList=function(e){return this.request("paper/docs/users/list",e,"user","api","rpc")},i.paperDocsUsersListContinue=function(e){return this.request("paper/docs/users/list/continue",e,"user","api","rpc")},i.paperDocsUsersRemove=function(e){return this.request("paper/docs/users/remove",e,"user","api","rpc")},i.sharingAddFileMember=function(e){return this.request("sharing/add_file_member",e,"user","api","rpc")},i.sharingAddFolderMember=function(e){return this.request("sharing/add_folder_member",e,"user","api","rpc")},i.sharingChangeFileMemberAccess=function(e){return this.request("sharing/change_file_member_access",e,"user","api","rpc")},i.sharingCheckJobStatus=function(e){return this.request("sharing/check_job_status",e,"user","api","rpc")},i.sharingCheckRemoveMemberJobStatus=function(e){return this.request("sharing/check_remove_member_job_status",e,"user","api","rpc")},i.sharingCheckShareJobStatus=function(e){return this.request("sharing/check_share_job_status",e,"user","api","rpc")},i.sharingCreateSharedLink=function(e){return this.request("sharing/create_shared_link",e,"user","api","rpc")},i.sharingCreateSharedLinkWithSettings=function(e){return this.request("sharing/create_shared_link_with_settings",e,"user","api","rpc")},i.sharingGetFileMetadata=function(e){return this.request("sharing/get_file_metadata",e,"user","api","rpc")},i.sharingGetFileMetadataBatch=function(e){return this.request("sharing/get_file_metadata/batch",e,"user","api","rpc")},i.sharingGetFolderMetadata=function(e){return this.request("sharing/get_folder_metadata",e,"user","api","rpc")},i.sharingGetSharedLinkFile=function(e){return this.request("sharing/get_shared_link_file",e,"user","content","download")},i.sharingGetSharedLinkMetadata=function(e){return this.request("sharing/get_shared_link_metadata",e,"user","api","rpc")},i.sharingGetSharedLinks=function(e){return this.request("sharing/get_shared_links",e,"user","api","rpc")},i.sharingListFileMembers=function(e){return this.request("sharing/list_file_members",e,"user","api","rpc")},i.sharingListFileMembersBatch=function(e){return this.request("sharing/list_file_members/batch",e,"user","api","rpc")},i.sharingListFileMembersContinue=function(e){return this.request("sharing/list_file_members/continue",e,"user","api","rpc")},i.sharingListFolderMembers=function(e){return this.request("sharing/list_folder_members",e,"user","api","rpc")},i.sharingListFolderMembersContinue=function(e){return this.request("sharing/list_folder_members/continue",e,"user","api","rpc")},i.sharingListFolders=function(e){return this.request("sharing/list_folders",e,"user","api","rpc")},i.sharingListFoldersContinue=function(e){return this.request("sharing/list_folders/continue",e,"user","api","rpc")},i.sharingListMountableFolders=function(e){return this.request("sharing/list_mountable_folders",e,"user","api","rpc")},i.sharingListMountableFoldersContinue=function(e){return this.request("sharing/list_mountable_folders/continue",e,"user","api","rpc")},i.sharingListReceivedFiles=function(e){return this.request("sharing/list_received_files",e,"user","api","rpc")},i.sharingListReceivedFilesContinue=function(e){return this.request("sharing/list_received_files/continue",e,"user","api","rpc")},i.sharingListSharedLinks=function(e){return this.request("sharing/list_shared_links",e,"user","api","rpc")},i.sharingModifySharedLinkSettings=function(e){return this.request("sharing/modify_shared_link_settings",e,"user","api","rpc")},i.sharingMountFolder=function(e){return this.request("sharing/mount_folder",e,"user","api","rpc")},i.sharingRelinquishFileMembership=function(e){return this.request("sharing/relinquish_file_membership",e,"user","api","rpc")},i.sharingRelinquishFolderMembership=function(e){return this.request("sharing/relinquish_folder_membership",e,"user","api","rpc")},i.sharingRemoveFileMember=function(e){return this.request("sharing/remove_file_member",e,"user","api","rpc")},i.sharingRemoveFileMember2=function(e){return this.request("sharing/remove_file_member_2",e,"user","api","rpc")},i.sharingRemoveFolderMember=function(e){return this.request("sharing/remove_folder_member",e,"user","api","rpc")},i.sharingRevokeSharedLink=function(e){return this.request("sharing/revoke_shared_link",e,"user","api","rpc")},i.sharingSetAccessInheritance=function(e){return this.request("sharing/set_access_inheritance",e,"user","api","rpc")},i.sharingShareFolder=function(e){return this.request("sharing/share_folder",e,"user","api","rpc")},i.sharingTransferFolder=function(e){return this.request("sharing/transfer_folder",e,"user","api","rpc")},i.sharingUnmountFolder=function(e){return this.request("sharing/unmount_folder",e,"user","api","rpc")},i.sharingUnshareFile=function(e){return this.request("sharing/unshare_file",e,"user","api","rpc")},i.sharingUnshareFolder=function(e){return this.request("sharing/unshare_folder",e,"user","api","rpc")},i.sharingUpdateFileMember=function(e){return this.request("sharing/update_file_member",e,"user","api","rpc")},i.sharingUpdateFolderMember=function(e){return this.request("sharing/update_folder_member",e,"user","api","rpc")},i.sharingUpdateFolderPolicy=function(e){return this.request("sharing/update_folder_policy",e,"user","api","rpc")},i.teamLogGetEvents=function(e){return this.request("team_log/get_events",e,"team","api","rpc")},i.teamLogGetEventsContinue=function(e){return this.request("team_log/get_events/continue",e,"team","api","rpc")},i.usersGetAccount=function(e){return this.request("users/get_account",e,"user","api","rpc")},i.usersGetAccountBatch=function(e){return this.request("users/get_account_batch",e,"user","api","rpc")},i.usersGetCurrentAccount=function(e){return this.request("users/get_current_account",e,"user","api","rpc")},i.usersGetSpaceUsage=function(e){return this.request("users/get_space_usage",e,"user","api","rpc")};for(var s=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},o=function(){function e(e,t){for(var r=0;t.length>r;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),u=function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)},a=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t},c=function(){return function(e,t){if(Array.isArray(e))return e;if(Symbol.iterator in Object(e))return function(e,t){var r=[],n=!0,i=!1,s=void 0;try{for(var o,u=e[Symbol.iterator]();!(n=(o=u.next()).done)&&(r.push(o.value),!t||r.length!==t);n=!0);}catch(e){i=!0,s=e}finally{try{!n&&u.return&&u.return()}finally{if(i)throw s}}return r}(e,t);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),p=function(e){return 3*e.length/4-n(e)},f=function(e){var t,r,i,s,o,u=e.length;s=n(e),o=new d(3*u/4-s),r=s>0?u-4:u;var a=0;for(t=0;r>t;t+=4)i=m[e.charCodeAt(t)]<<18|m[e.charCodeAt(t+1)]<<12|m[e.charCodeAt(t+2)]<<6|m[e.charCodeAt(t+3)],o[a++]=i>>16&255,o[a++]=i>>8&255,o[a++]=255&i;return 2===s?(i=m[e.charCodeAt(t)]<<2|m[e.charCodeAt(t+1)]>>4,o[a++]=255&i):1===s&&(i=m[e.charCodeAt(t)]<<10|m[e.charCodeAt(t+1)]<<4|m[e.charCodeAt(t+2)]>>2,o[a++]=i>>8&255,o[a++]=255&i),o},h=function(e){for(var t,r=e.length,n=r%3,i="",s=[],o=0,u=r-n;u>o;o+=16383)s.push(function(e,t,r){for(var n=[],i=t;r>i;i+=3)n.push(function(e){return l[e>>18&63]+l[e>>12&63]+l[e>>6&63]+l[63&e]}((e[i]<<16)+(e[i+1]<<8)+e[i+2]));return n.join("")}(e,o,o+16383>u?u:o+16383));return 1===n?(i+=l[(t=e[r-1])>>2],i+=l[t<<4&63],i+="=="):2===n&&(i+=l[(t=(e[r-2]<<8)+e[r-1])>>10],i+=l[t>>4&63],i+=l[t<<2&63],i+="="),s.push(i),s.join("")},l=[],m=[],d="undefined"!=typeof Uint8Array?Uint8Array:Array,g="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",_=0;64>_;++_)l[_]=g[_],m[g.charCodeAt(_)]=_;m[45]=62,m[95]=63;var b={byteLength:p,toByteArray:f,fromByteArray:h},v={read:function(e,t,r,n,i){var s,o,u=8*i-n-1,a=(1<>1,p=-7,f=r?i-1:0,h=r?-1:1,l=e[t+f];for(f+=h,s=l&(1<<-p)-1,l>>=-p,p+=u;p>0;s=256*s+e[t+f],f+=h,p-=8);for(o=s&(1<<-p)-1,s>>=-p,p+=n;p>0;o=256*o+e[t+f],f+=h,p-=8);if(0===s)s=1-c;else{if(s===a)return o?NaN:1/0*(l?-1:1);o+=Math.pow(2,n),s-=c}return(l?-1:1)*o*Math.pow(2,s-n)},write:function(e,t,r,n,i,s){var o,u,a,c=8*s-i-1,p=(1<>1,h=23===i?5.960464477539062e-8:0,l=n?0:s-1,m=n?1:-1,d=0>t||0===t&&0>1/t?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(u=isNaN(t)?1:0,o=p):(o=Math.floor(Math.log(t)/Math.LN2),1>t*(a=Math.pow(2,-o))&&(o--,a*=2),2>(t+=1>o+f?h*Math.pow(2,1-f):h/a)*a||(o++,a/=2),p>o+f?1>o+f?(u=t*Math.pow(2,f-1)*Math.pow(2,i),o=0):(u=(t*a-1)*Math.pow(2,i),o+=f):(u=0,o=p));i>=8;e[r+l]=255&u,l+=m,u/=256,i-=8);for(o=o<0;e[r+l]=255&o,l+=m,o/=256,c-=8);e[r+l-m]|=128*d}},y=function(e,t){return t={exports:{}},e(t,t.exports),t.exports}(function(e,t){function r(e){if(e>C)throw new RangeError("Invalid typed array length");var t=new Uint8Array(e);return t.__proto__=n.prototype,t}function n(e,t,r){if("number"==typeof e){if("string"==typeof t)throw Error("If encoding is specified then the first argument must be a string");return o(e)}return i(e,t,r)}function i(e,t,i){if("number"==typeof e)throw new TypeError('"value" argument must not be a number');return L(e)?function(e,t,r){if(0>t||t>e.byteLength)throw new RangeError("'offset' is out of bounds");if(t+(r||0)>e.byteLength)throw new RangeError("'length' is out of bounds");var i;i=void 0===t&&void 0===r?new Uint8Array(e):void 0===r?new Uint8Array(e,t):new Uint8Array(e,t,r);return i.__proto__=n.prototype,i}(e,t,i):"string"==typeof e?function(e,t){"string"==typeof t&&""!==t||(t="utf8");if(!n.isEncoding(t))throw new TypeError('"encoding" must be a valid string encoding');var i=0|c(e,t),s=r(i),o=s.write(e,t);o!==i&&(s=s.slice(0,o));return s}(e,t):function(e){if(n.isBuffer(e)){var t=0|a(e.length),i=r(t);return 0===i.length?i:(e.copy(i,0,0,t),i)}if(e){if(S(e)||"length"in e)return"number"!=typeof e.length||E(e.length)?r(0):u(e);if("Buffer"===e.type&&Array.isArray(e.data))return u(e.data)}throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")}(e)}function s(e){if("number"!=typeof e)throw new TypeError('"size" argument must be a number');if(0>e)throw new RangeError('"size" argument must not be negative')}function o(e){return s(e),r(0>e?0:0|a(e))}function u(e){for(var t=0>e.length?0:0|a(e.length),n=r(t),i=0;t>i;i+=1)n[i]=255&e[i];return n}function a(e){if(e>=C)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+C.toString(16)+" bytes");return 0|e}function c(e,t){if(n.isBuffer(e))return e.length;if(S(e)||L(e))return e.byteLength;"string"!=typeof e&&(e=""+e);var r=e.length;if(0===r)return 0;for(var i=!1;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":case void 0:return w(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return k(e).length;default:if(i)return w(e).length;t=(""+t).toLowerCase(),i=!0}}function p(e,t,r){var n=e[t];e[t]=e[r],e[r]=n}function f(e,t,r,i,s){if(0===e.length)return-1;if("string"==typeof r?(i=r,r=0):r>2147483647?r=2147483647:-2147483648>r&&(r=-2147483648),r=+r,E(r)&&(r=s?0:e.length-1),0>r&&(r=e.length+r),e.length>r){if(0>r){if(!s)return-1;r=0}}else{if(s)return-1;r=e.length-1}if("string"==typeof t&&(t=n.from(t,i)),n.isBuffer(t))return 0===t.length?-1:h(e,t,r,i,s);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?s?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):h(e,[t],r,i,s);throw new TypeError("val must be string, number or Buffer")}function h(e,t,r,n,i){function s(e,t){return 1===o?e[t]:e.readUInt16BE(t*o)}var o=1,u=e.length,a=t.length;if(void 0!==n&&("ucs2"===(n=(n+"").toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(2>e.length||2>t.length)return-1;o=2,u/=2,a/=2,r/=2}var c;if(i){var p=-1;for(c=r;u>c;c++)if(s(e,c)===s(t,-1===p?0:c-p)){if(-1===p&&(p=c),c-p+1===a)return p*o}else-1!==p&&(c-=c-p),p=-1}else for(r+a>u&&(r=u-a),c=r;c>=0;c--){for(var f=!0,h=0;a>h;h++)if(s(e,c+h)!==s(t,h)){f=!1;break}if(f)return c}return-1}function l(e,t,r,n){return A(function(e){for(var t=[],r=0;e.length>r;++r)t.push(255&e.charCodeAt(r));return t}(t),e,r,n)}function m(e,t,r){r=Math.min(e.length,r);for(var n=[],i=t;r>i;){var s=e[i],o=null,u=s>239?4:s>223?3:s>191?2:1;if(r>=i+u){var a,c,p,f;switch(u){case 1:128>s&&(o=s);break;case 2:128==(192&(a=e[i+1]))&&(f=(31&s)<<6|63&a)>127&&(o=f);break;case 3:c=e[i+2],128==(192&(a=e[i+1]))&&128==(192&c)&&(f=(15&s)<<12|(63&a)<<6|63&c)>2047&&(55296>f||f>57343)&&(o=f);break;case 4:c=e[i+2],p=e[i+3],128==(192&(a=e[i+1]))&&128==(192&c)&&128==(192&p)&&(f=(15&s)<<18|(63&a)<<12|(63&c)<<6|63&p)>65535&&1114112>f&&(o=f)}}null===o?(o=65533,u=1):o>65535&&(n.push((o-=65536)>>>10&1023|55296),o=56320|1023&o),n.push(o),i+=u}return function(e){var t=e.length;if(R>=t)return String.fromCharCode.apply(String,e);var r="",n=0;for(;t>n;)r+=String.fromCharCode.apply(String,e.slice(n,n+=R));return r}(n)}function d(e,t,r){if(e%1!=0||0>e)throw new RangeError("offset is not uint");if(e+t>r)throw new RangeError("Trying to access beyond buffer length")}function g(e,t,r,i,s,o){if(!n.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>s||o>t)throw new RangeError('"value" argument is out of bounds');if(r+i>e.length)throw new RangeError("Index out of range")}function _(e,t,r,n,i,s){if(r+n>e.length)throw new RangeError("Index out of range");if(0>r)throw new RangeError("Index out of range")}function y(e,t,r,n,i){return t=+t,r>>>=0,i||_(e,0,r,4),v.write(e,t,r,n,23,4),r+4}function q(e,t,r,n,i){return t=+t,r>>>=0,i||_(e,0,r,8),v.write(e,t,r,n,52,8),r+8}function w(e,t){t=t||1/0;for(var r,n=e.length,i=null,s=[],o=0;n>o;++o){if((r=e.charCodeAt(o))>55295&&57344>r){if(!i){if(r>56319){(t-=3)>-1&&s.push(239,191,189);continue}if(o+1===n){(t-=3)>-1&&s.push(239,191,189);continue}i=r;continue}if(56320>r){(t-=3)>-1&&s.push(239,191,189),i=r;continue}r=65536+(i-55296<<10|r-56320)}else i&&(t-=3)>-1&&s.push(239,191,189);if(i=null,128>r){if(0>(t-=1))break;s.push(r)}else if(2048>r){if(0>(t-=2))break;s.push(r>>6|192,63&r|128)}else if(65536>r){if(0>(t-=3))break;s.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(r>=1114112)throw Error("Invalid code point");if(0>(t-=4))break;s.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return s}function k(e){return b.toByteArray(function(e){if(2>(e=e.trim().replace(U,"")).length)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function A(e,t,r,n){for(var i=0;n>i&&(i+r0&&void 0!==t?"string"==typeof n?r(e).fill(t,n):r(e).fill(t):r(e)}(e,t,n)},n.allocUnsafe=function(e){return o(e)},n.allocUnsafeSlow=function(e){return o(e)},n.isBuffer=function(e){return null!=e&&!0===e._isBuffer},n.compare=function(e,t){if(!n.isBuffer(e)||!n.isBuffer(t))throw new TypeError("Arguments must be Buffers");if(e===t)return 0;for(var r=e.length,i=t.length,s=0,o=Math.min(r,i);o>s;++s)if(e[s]!==t[s]){r=e[s],i=t[s];break}return i>r?-1:r>i?1:0},n.isEncoding=function(e){switch((e+"").toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},n.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return n.alloc(0);var r;if(void 0===t)for(t=0,r=0;e.length>r;++r)t+=e[r].length;var i=n.allocUnsafe(t),s=0;for(r=0;e.length>r;++r){var o=e[r];if(!n.isBuffer(o))throw new TypeError('"list" argument must be an Array of Buffers');o.copy(i,s),s+=o.length}return i},n.byteLength=c,n.prototype._isBuffer=!0,n.prototype.swap16=function(){var e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var t=0;e>t;t+=2)p(this,t,t+1);return this},n.prototype.swap32=function(){var e=this.length;if(e%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var t=0;e>t;t+=4)p(this,t,t+3),p(this,t+1,t+2);return this},n.prototype.swap64=function(){var e=this.length;if(e%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var t=0;e>t;t+=8)p(this,t,t+7),p(this,t+1,t+6),p(this,t+2,t+5),p(this,t+3,t+4);return this},n.prototype.toString=function(){var e=this.length;return 0===e?"":0===arguments.length?m(this,0,e):function(e,t,r){var n=!1;if((void 0===t||0>t)&&(t=0),t>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),0>=r)return"";if(r>>>=0,(t>>>=0)>=r)return"";for(e||(e="utf8");;)switch(e){case"hex":return function(e,t,r){var n=e.length;t&&t>=0||(t=0),(!r||0>r||r>n)&&(r=n);for(var i="",s=t;r>s;++s)i+=function(e){return 16>e?"0"+e.toString(16):e.toString(16)}(e[s]);return i}(this,t,r);case"utf8":case"utf-8":return m(this,t,r);case"ascii":return function(e,t,r){var n="";r=Math.min(e.length,r);for(var i=t;r>i;++i)n+=String.fromCharCode(127&e[i]);return n}(this,t,r);case"latin1":case"binary":return function(e,t,r){var n="";r=Math.min(e.length,r);for(var i=t;r>i;++i)n+=String.fromCharCode(e[i]);return n}(this,t,r);case"base64":return function(e,t,r){return b.fromByteArray(0===t&&r===e.length?e:e.slice(t,r))}(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return function(e,t,r){for(var n=e.slice(t,r),i="",s=0;n.length>s;s+=2)i+=String.fromCharCode(n[s]+256*n[s+1]);return i}(this,t,r);default:if(n)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),n=!0}}.apply(this,arguments)},n.prototype.equals=function(e){if(!n.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===n.compare(this,e)},n.prototype.inspect=function(){var e="",r=t.INSPECT_MAX_BYTES;return this.length>0&&(e=this.toString("hex",0,r).match(/.{2}/g).join(" "),this.length>r&&(e+=" ... ")),""},n.prototype.compare=function(e,t,r,i,s){if(!n.isBuffer(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===r&&(r=e?e.length:0),void 0===i&&(i=0),void 0===s&&(s=this.length),0>t||r>e.length||0>i||s>this.length)throw new RangeError("out of range index");if(i>=s&&t>=r)return 0;if(i>=s)return-1;if(t>=r)return 1;if(t>>>=0,r>>>=0,i>>>=0,s>>>=0,this===e)return 0;for(var o=s-i,u=r-t,a=Math.min(o,u),c=this.slice(i,s),p=e.slice(t,r),f=0;a>f;++f)if(c[f]!==p[f]){o=c[f],u=p[f];break}return u>o?-1:o>u?1:0},n.prototype.includes=function(e,t,r){return-1!==this.indexOf(e,t,r)},n.prototype.indexOf=function(e,t,r){return f(this,e,t,r,!0)},n.prototype.lastIndexOf=function(e,t,r){return f(this,e,t,r,!1)},n.prototype.write=function(e,t,r,n){if(void 0===t)n="utf8",r=this.length,t=0;else if(void 0===r&&"string"==typeof t)n=t,r=this.length,t=0;else{if(!isFinite(t))throw Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t>>>=0,isFinite(r)?(r>>>=0,void 0===n&&(n="utf8")):(n=r,r=void 0)}var i=this.length-t;if((void 0===r||r>i)&&(r=i),e.length>0&&(0>r||0>t)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var s=!1;;)switch(n){case"hex":return function(e,t,r,n){var i=e.length-(r=+r||0);n?(n=+n)>i&&(n=i):n=i;var s=t.length;if(s%2!=0)throw new TypeError("Invalid hex string");n>s/2&&(n=s/2);for(var o=0;n>o;++o){var u=parseInt(t.substr(2*o,2),16);if(E(u))return o;e[r+o]=u}return o}(this,e,t,r);case"utf8":case"utf-8":return function(e,t,r,n){return A(w(t,e.length-r),e,r,n)}(this,e,t,r);case"ascii":return l(this,e,t,r);case"latin1":case"binary":return function(e,t,r,n){return l(e,t,r,n)}(this,e,t,r);case"base64":return function(e,t,r,n){return A(k(t),e,r,n)}(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return function(e,t,r,n){return A(function(e,t){for(var r,n,i=[],s=0;e.length>s&&(t-=2)>=0;++s)r=e.charCodeAt(s),n=r>>8,i.push(r%256),i.push(n);return i}(t,e.length-r),e,r,n)}(this,e,t,r);default:if(s)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),s=!0}},n.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var R=4096;n.prototype.slice=function(e,t){var r=this.length;e=~~e,t=void 0===t?r:~~t,0>e?0>(e+=r)&&(e=0):e>r&&(e=r),0>t?0>(t+=r)&&(t=0):t>r&&(t=r),e>t&&(t=e);var i=this.subarray(e,t);return i.__proto__=n.prototype,i},n.prototype.readUIntLE=function(e,t,r){e>>>=0,t>>>=0,r||d(e,t,this.length);for(var n=this[e],i=1,s=0;++s>>=0,t>>>=0,r||d(e,t,this.length);for(var n=this[e+--t],i=1;t>0&&(i*=256);)n+=this[e+--t]*i;return n},n.prototype.readUInt8=function(e,t){return e>>>=0,t||d(e,1,this.length),this[e]},n.prototype.readUInt16LE=function(e,t){return e>>>=0,t||d(e,2,this.length),this[e]|this[e+1]<<8},n.prototype.readUInt16BE=function(e,t){return e>>>=0,t||d(e,2,this.length),this[e]<<8|this[e+1]},n.prototype.readUInt32LE=function(e,t){return e>>>=0,t||d(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},n.prototype.readUInt32BE=function(e,t){return e>>>=0,t||d(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},n.prototype.readIntLE=function(e,t,r){e>>>=0,t>>>=0,r||d(e,t,this.length);for(var n=this[e],i=1,s=0;++sn||(n-=Math.pow(2,8*t)),n},n.prototype.readIntBE=function(e,t,r){e>>>=0,t>>>=0,r||d(e,t,this.length);for(var n=t,i=1,s=this[e+--n];n>0&&(i*=256);)s+=this[e+--n]*i;return(i*=128)>s||(s-=Math.pow(2,8*t)),s},n.prototype.readInt8=function(e,t){return e>>>=0,t||d(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},n.prototype.readInt16LE=function(e,t){e>>>=0,t||d(e,2,this.length);var r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},n.prototype.readInt16BE=function(e,t){e>>>=0,t||d(e,2,this.length);var r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},n.prototype.readInt32LE=function(e,t){return e>>>=0,t||d(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},n.prototype.readInt32BE=function(e,t){return e>>>=0,t||d(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},n.prototype.readFloatLE=function(e,t){return e>>>=0,t||d(e,4,this.length),v.read(this,e,!0,23,4)},n.prototype.readFloatBE=function(e,t){return e>>>=0,t||d(e,4,this.length),v.read(this,e,!1,23,4)},n.prototype.readDoubleLE=function(e,t){return e>>>=0,t||d(e,8,this.length),v.read(this,e,!0,52,8)},n.prototype.readDoubleBE=function(e,t){return e>>>=0,t||d(e,8,this.length),v.read(this,e,!1,52,8)},n.prototype.writeUIntLE=function(e,t,r,n){if(e=+e,t>>>=0,r>>>=0,!n){g(this,e,t,r,Math.pow(2,8*r)-1,0)}var i=1,s=0;for(this[t]=255&e;++s>>=0,r>>>=0,!n){g(this,e,t,r,Math.pow(2,8*r)-1,0)}var i=r-1,s=1;for(this[t+i]=255&e;--i>=0&&(s*=256);)this[t+i]=e/s&255;return t+r},n.prototype.writeUInt8=function(e,t,r){return e=+e,t>>>=0,r||g(this,e,t,1,255,0),this[t]=255&e,t+1},n.prototype.writeUInt16LE=function(e,t,r){return e=+e,t>>>=0,r||g(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},n.prototype.writeUInt16BE=function(e,t,r){return e=+e,t>>>=0,r||g(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},n.prototype.writeUInt32LE=function(e,t,r){return e=+e,t>>>=0,r||g(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},n.prototype.writeUInt32BE=function(e,t,r){return e=+e,t>>>=0,r||g(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},n.prototype.writeIntLE=function(e,t,r,n){if(e=+e,t>>>=0,!n){var i=Math.pow(2,8*r-1);g(this,e,t,r,i-1,-i)}var s=0,o=1,u=0;for(this[t]=255&e;++se&&0===u&&0!==this[t+s-1]&&(u=1),this[t+s]=(e/o>>0)-u&255;return t+r},n.prototype.writeIntBE=function(e,t,r,n){if(e=+e,t>>>=0,!n){var i=Math.pow(2,8*r-1);g(this,e,t,r,i-1,-i)}var s=r-1,o=1,u=0;for(this[t+s]=255&e;--s>=0&&(o*=256);)0>e&&0===u&&0!==this[t+s+1]&&(u=1),this[t+s]=(e/o>>0)-u&255;return t+r},n.prototype.writeInt8=function(e,t,r){return e=+e,t>>>=0,r||g(this,e,t,1,127,-128),0>e&&(e=255+e+1),this[t]=255&e,t+1},n.prototype.writeInt16LE=function(e,t,r){return e=+e,t>>>=0,r||g(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},n.prototype.writeInt16BE=function(e,t,r){return e=+e,t>>>=0,r||g(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},n.prototype.writeInt32LE=function(e,t,r){return e=+e,t>>>=0,r||g(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},n.prototype.writeInt32BE=function(e,t,r){return e=+e,t>>>=0,r||g(this,e,t,4,2147483647,-2147483648),0>e&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},n.prototype.writeFloatLE=function(e,t,r){return y(this,e,t,!0,r)},n.prototype.writeFloatBE=function(e,t,r){return y(this,e,t,!1,r)},n.prototype.writeDoubleLE=function(e,t,r){return q(this,e,t,!0,r)},n.prototype.writeDoubleBE=function(e,t,r){return q(this,e,t,!1,r)},n.prototype.copy=function(e,t,r,n){if(r||(r=0),n||0===n||(n=this.length),e.length>t||(t=e.length),t||(t=0),n>0&&r>n&&(n=r),n===r)return 0;if(0===e.length||0===this.length)return 0;if(0>t)throw new RangeError("targetStart out of bounds");if(0>r||r>=this.length)throw new RangeError("sourceStart out of bounds");if(0>n)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),n-r>e.length-t&&(n=e.length-t+r);var i,s=n-r;if(this===e&&t>r&&n>t)for(i=s-1;i>=0;--i)e[i+t]=this[i+r];else if(1e3>s)for(i=0;s>i;++i)e[i+t]=this[i+r];else Uint8Array.prototype.set.call(e,this.subarray(r,r+s),t);return s},n.prototype.fill=function(e,t,r,i){if("string"==typeof e){if("string"==typeof t?(i=t,t=0,r=this.length):"string"==typeof r&&(i=r,r=this.length),1===e.length){var s=e.charCodeAt(0);256>s&&(e=s)}if(void 0!==i&&"string"!=typeof i)throw new TypeError("encoding must be a string");if("string"==typeof i&&!n.isEncoding(i))throw new TypeError("Unknown encoding: "+i)}else"number"==typeof e&&(e&=255);if(0>t||t>this.length||r>this.length)throw new RangeError("Out of range index");if(t>=r)return this;t>>>=0,r=void 0===r?this.length:r>>>0,e||(e=0);var o;if("number"==typeof e)for(o=t;r>o;++o)this[o]=e;else{var u=n.isBuffer(e)?e:new n(e,i),a=u.length;for(o=0;r-t>o;++o)this[o+t]=u[o%a]}return this};var U=/[^+/0-9A-Za-z-_]/g}).Buffer;"function"!=typeof Object.assign&&(Object.assign=function(e){var t,r,n,i;if(void 0===e||null===e)throw new TypeError("Cannot convert undefined or null to object");for(t=Object(e),r=1;arguments.length>r;r++)if(void 0!==(n=arguments[r])&&null!==n)for(i in n)n.hasOwnProperty(i)&&(t[i]=n[i]);return t}),Array.prototype.includes||Object.defineProperty(Array.prototype,"includes",{value:function(e,t){if(null==this)throw new TypeError('"this" is null or not defined');var r=Object(this),n=r.length>>>0;if(0===n)return!1;for(var i=0|t,s=Math.max(0>i?n-Math.abs(i):i,0);n>s;){if(function(e,t){return e===t||"number"==typeof e&&"number"==typeof t&&isNaN(e)&&isNaN(t)}(r[s],e))return!0;s++}return!1}});var q=function(){function n(e){s(this,n),this.accessToken=(e=e||{}).accessToken,this.clientId=e.clientId,this.clientSecret=e.clientSecret,this.selectUser=e.selectUser,this.selectAdmin=e.selectAdmin,this.fetch=e.fetch||fetch,this.pathRoot=e.pathRoot,e.fetch||console.warn("Global fetch is deprecated and will be unsupported in a future version. Please pass fetch function as option when instantiating dropbox instance: new Dropbox({fetch})")}return o(n,[{key:"setAccessToken",value:function(e){this.accessToken=e}},{key:"getAccessToken",value:function(){return this.accessToken}},{key:"setClientId",value:function(e){this.clientId=e}},{key:"getClientId",value:function(){return this.clientId}},{key:"setClientSecret",value:function(e){this.clientSecret=e}},{key:"getClientSecret",value:function(){return this.clientSecret}},{key:"getAuthenticationUrl",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"token",n=this.getClientId(),i="https://www.dropbox.com/oauth2/authorize";if(!n)throw Error("A client id is required. You can set the client id using .setClientId().");if("code"!==r&&!e)throw Error("A redirect uri is required.");if(!["code","token"].includes(r))throw Error("Authorization type must be code or token");var s=void 0;return s="code"===r?i+"?response_type=code&client_id="+n:i+"?response_type=token&client_id="+n,e&&(s+="&redirect_uri="+e),t&&(s+="&state="+t),s}},{key:"getAccessTokenFromCode",value:function(e,t){var r=this.getClientId(),n=this.getClientSecret();if(!r)throw Error("A client id is required. You can set the client id using .setClientId().");if(!n)throw Error("A client secret is required. You can set the client id using .setClientSecret().");return this.fetch("https://api.dropboxapi.com/oauth2/token?code="+t+"&grant_type=authorization_code&redirect_uri="+e+"&client_id="+r+"&client_secret="+n,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"}}).then(function(e){return function(e){var t=e.clone();return new Promise(function(r){e.json().then(function(e){return r(e)}).catch(function(){return t.text().then(function(e){return r(e)})})}).then(function(t){return[e,t]})}(e)}).then(function(e){var t=c(e,2),r=t[0],n=t[1];if(!r.ok)throw{error:n,response:r,status:r.status};return n.access_token})}},{key:"authenticateWithCordova",value:function(e,t){function r(e){-999!==e.code&&(window.setTimeout(function(){u.close()},10),t())}function n(r){if(r.url.indexOf("&error=")>-1)window.setTimeout(function(){u.close()},10),t();else{var n=r.url.indexOf("#access_token="),i=r.url.indexOf("&token_type=");if(n>-1){n+=14,window.setTimeout(function(){u.close()},10);var s=r.url.substring(n,i);e(s)}}}function i(){o||(u.removeEventListener("loaderror",r),u.removeEventListener("loadstop",n),u.removeEventListener("exit",i),o=!0)}var s=this.getAuthenticationUrl("https://www.dropbox.com/1/oauth2/redirect_receiver"),o=!1,u=window.open(s,"_blank");u.addEventListener("loaderror",r),u.addEventListener("loadstop",n),u.addEventListener("exit",i)}},{key:"request",value:function(e,t,r,n,i){var s=null;switch(i){case"rpc":s=this.getRpcRequest();break;case"download":s=this.getDownloadRequest();break;case"upload":s=this.getUploadRequest();break;default:throw Error("Invalid request style: "+i)}var o={selectUser:this.selectUser,selectAdmin:this.selectAdmin,clientId:this.getClientId(),clientSecret:this.getClientSecret(),pathRoot:this.pathRoot};return s(e,t,r,n,this.getAccessToken(),o)}},{key:"setRpcRequest",value:function(e){this.rpcRequest=e}},{key:"getRpcRequest",value:function(){return void 0===this.rpcRequest&&(this.rpcRequest=function(e){return function(r,n,i,s,o,u){var a={method:"POST",body:n?JSON.stringify(n):null},p={};n&&(p["Content-Type"]="application/json");var f="";switch(i){case"app":if(!u.clientId||!u.clientSecret)throw Error("A client id and secret is required for this function");f=new y(u.clientId+":"+u.clientSecret).toString("base64"),p.Authorization="Basic "+f;break;case"team":case"user":p.Authorization="Bearer "+o;break;case"noauth":break;default:throw Error("Unhandled auth type: "+i)}return u&&(u.selectUser&&(p["Dropbox-API-Select-User"]=u.selectUser),u.selectAdmin&&(p["Dropbox-API-Select-Admin"]=u.selectAdmin),u.pathRoot&&(p["Dropbox-API-Path-Root"]=u.pathRoot)),a.headers=p,e(t(s)+r,a).then(function(e){return function(e){return"application/json"===e.headers.get("Content-Type")?e.json().then(function(t){return[e,t]}):e.text().then(function(t){return[e,t]})}(e)}).then(function(e){var t=c(e,2),r=t[0],n=t[1];if(!r.ok)throw{error:n,response:r,status:r.status};return n})}}(this.fetch)),this.rpcRequest}},{key:"setDownloadRequest",value:function(e){this.downloadRequest=e}},{key:"getDownloadRequest",value:function(){return void 0===this.downloadRequest&&(this.downloadRequest=function(n){return function(i,s,o,u,a,p){if("user"!==o)throw Error("Unexpected auth type: "+o);var f={method:"POST",headers:{Authorization:"Bearer "+a,"Dropbox-API-Arg":r(s)}};return p&&(p.selectUser&&(f.headers["Dropbox-API-Select-User"]=p.selectUser),p.selectAdmin&&(f.headers["Dropbox-API-Select-Admin"]=p.selectAdmin),p.pathRoot&&(f.headers["Dropbox-API-Path-Root"]=p.pathRoot)),n(t(u)+i,f).then(function(t){return function(t){return t.ok?e()?t.blob():t.buffer():t.text()}(t).then(function(e){return[t,e]})}).then(function(t){var r=c(t,2);return function(t,r){if(!t.ok)throw{error:r,response:t,status:t.status};var n=JSON.parse(t.headers.get("dropbox-api-result"));return e()?n.fileBlob=r:n.fileBinary=r,n}(r[0],r[1])})}}(this.fetch)),this.downloadRequest}},{key:"setUploadRequest",value:function(e){this.uploadRequest=e}},{key:"getUploadRequest",value:function(){return void 0===this.uploadRequest&&(this.uploadRequest=function(e){return function(n,i,s,o,u,a){if("user"!==s)throw Error("Unexpected auth type: "+s);var p=i.contents;delete i.contents;var f={body:p,method:"POST",headers:{Authorization:"Bearer "+u,"Content-Type":"application/octet-stream","Dropbox-API-Arg":r(i)}};return a&&(a.selectUser&&(f.headers["Dropbox-API-Select-User"]=a.selectUser),a.selectAdmin&&(f.headers["Dropbox-API-Select-Admin"]=a.selectAdmin),a.pathRoot&&(f.headers["Dropbox-API-Path-Root"]=a.pathRoot)),e(t(o)+n,f).then(function(e){return function(e){var t=e.clone();return new Promise(function(r){e.json().then(function(e){return r(e)}).catch(function(){return t.text().then(function(e){return r(e)})})}).then(function(t){return[e,t]})}(e)}).then(function(e){var t=c(e,2),r=t[0],n=t[1];if(!r.ok)throw{error:n,response:r,status:r.status};return n})}}(this.fetch)),this.uploadRequest}}]),n}(),w=function(e){function t(e){s(this,t);var r=a(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return Object.assign(r,i),r}return u(t,q),o(t,[{key:"filesGetSharedLinkFile",value:function(e){return this.request("sharing/get_shared_link_file",e,"api","download")}}]),t}(),k=Object.freeze({Dropbox:w}),A={};A.teamDevicesListMemberDevices=function(e){return this.request("team/devices/list_member_devices",e,"team","api","rpc")},A.teamDevicesListMembersDevices=function(e){return this.request("team/devices/list_members_devices",e,"team","api","rpc")},A.teamDevicesListTeamDevices=function(e){return this.request("team/devices/list_team_devices",e,"team","api","rpc")},A.teamDevicesRevokeDeviceSession=function(e){return this.request("team/devices/revoke_device_session",e,"team","api","rpc")},A.teamDevicesRevokeDeviceSessionBatch=function(e){return this.request("team/devices/revoke_device_session_batch",e,"team","api","rpc")},A.teamFeaturesGetValues=function(e){return this.request("team/features/get_values",e,"team","api","rpc")},A.teamGetInfo=function(e){return this.request("team/get_info",e,"team","api","rpc")},A.teamGroupsCreate=function(e){return this.request("team/groups/create",e,"team","api","rpc")},A.teamGroupsDelete=function(e){return this.request("team/groups/delete",e,"team","api","rpc")},A.teamGroupsGetInfo=function(e){return this.request("team/groups/get_info",e,"team","api","rpc")},A.teamGroupsJobStatusGet=function(e){return this.request("team/groups/job_status/get",e,"team","api","rpc")},A.teamGroupsList=function(e){return this.request("team/groups/list",e,"team","api","rpc")},A.teamGroupsListContinue=function(e){return this.request("team/groups/list/continue",e,"team","api","rpc")},A.teamGroupsMembersAdd=function(e){return this.request("team/groups/members/add",e,"team","api","rpc")},A.teamGroupsMembersList=function(e){return this.request("team/groups/members/list",e,"team","api","rpc")},A.teamGroupsMembersListContinue=function(e){return this.request("team/groups/members/list/continue",e,"team","api","rpc")},A.teamGroupsMembersRemove=function(e){return this.request("team/groups/members/remove",e,"team","api","rpc")},A.teamGroupsMembersSetAccessType=function(e){return this.request("team/groups/members/set_access_type",e,"team","api","rpc")},A.teamGroupsUpdate=function(e){return this.request("team/groups/update",e,"team","api","rpc")},A.teamLinkedAppsListMemberLinkedApps=function(e){return this.request("team/linked_apps/list_member_linked_apps",e,"team","api","rpc")},A.teamLinkedAppsListMembersLinkedApps=function(e){return this.request("team/linked_apps/list_members_linked_apps",e,"team","api","rpc")},A.teamLinkedAppsListTeamLinkedApps=function(e){return this.request("team/linked_apps/list_team_linked_apps",e,"team","api","rpc")},A.teamLinkedAppsRevokeLinkedApp=function(e){return this.request("team/linked_apps/revoke_linked_app",e,"team","api","rpc")},A.teamLinkedAppsRevokeLinkedAppBatch=function(e){return this.request("team/linked_apps/revoke_linked_app_batch",e,"team","api","rpc")},A.teamMemberSpaceLimitsExcludedUsersAdd=function(e){return this.request("team/member_space_limits/excluded_users/add",e,"team","api","rpc")},A.teamMemberSpaceLimitsExcludedUsersList=function(e){return this.request("team/member_space_limits/excluded_users/list",e,"team","api","rpc")},A.teamMemberSpaceLimitsExcludedUsersListContinue=function(e){return this.request("team/member_space_limits/excluded_users/list/continue",e,"team","api","rpc")},A.teamMemberSpaceLimitsExcludedUsersRemove=function(e){return this.request("team/member_space_limits/excluded_users/remove",e,"team","api","rpc")},A.teamMemberSpaceLimitsGetCustomQuota=function(e){return this.request("team/member_space_limits/get_custom_quota",e,"team","api","rpc")},A.teamMemberSpaceLimitsRemoveCustomQuota=function(e){return this.request("team/member_space_limits/remove_custom_quota",e,"team","api","rpc")},A.teamMemberSpaceLimitsSetCustomQuota=function(e){return this.request("team/member_space_limits/set_custom_quota",e,"team","api","rpc")},A.teamMembersAdd=function(e){return this.request("team/members/add",e,"team","api","rpc")},A.teamMembersAddJobStatusGet=function(e){return this.request("team/members/add/job_status/get",e,"team","api","rpc")},A.teamMembersGetInfo=function(e){return this.request("team/members/get_info",e,"team","api","rpc")},A.teamMembersList=function(e){return this.request("team/members/list",e,"team","api","rpc")},A.teamMembersListContinue=function(e){return this.request("team/members/list/continue",e,"team","api","rpc")},A.teamMembersMoveFormerMemberFiles=function(e){return this.request("team/members/move_former_member_files",e,"team","api","rpc")},A.teamMembersMoveFormerMemberFilesJobStatusCheck=function(e){return this.request("team/members/move_former_member_files/job_status/check",e,"team","api","rpc")},A.teamMembersRecover=function(e){return this.request("team/members/recover",e,"team","api","rpc")},A.teamMembersRemove=function(e){return this.request("team/members/remove",e,"team","api","rpc")},A.teamMembersRemoveJobStatusGet=function(e){return this.request("team/members/remove/job_status/get",e,"team","api","rpc")},A.teamMembersSendWelcomeEmail=function(e){return this.request("team/members/send_welcome_email",e,"team","api","rpc")},A.teamMembersSetAdminPermissions=function(e){return this.request("team/members/set_admin_permissions",e,"team","api","rpc")},A.teamMembersSetProfile=function(e){return this.request("team/members/set_profile",e,"team","api","rpc")},A.teamMembersSuspend=function(e){return this.request("team/members/suspend",e,"team","api","rpc")},A.teamMembersUnsuspend=function(e){return this.request("team/members/unsuspend",e,"team","api","rpc")},A.teamNamespacesList=function(e){return this.request("team/namespaces/list",e,"team","api","rpc")},A.teamNamespacesListContinue=function(e){return this.request("team/namespaces/list/continue",e,"team","api","rpc")},A.teamPropertiesTemplateAdd=function(e){return this.request("team/properties/template/add",e,"team","api","rpc")},A.teamPropertiesTemplateGet=function(e){return this.request("team/properties/template/get",e,"team","api","rpc")},A.teamPropertiesTemplateList=function(e){return this.request("team/properties/template/list",e,"team","api","rpc")},A.teamPropertiesTemplateUpdate=function(e){return this.request("team/properties/template/update",e,"team","api","rpc")},A.teamReportsGetActivity=function(e){return this.request("team/reports/get_activity",e,"team","api","rpc")},A.teamReportsGetDevices=function(e){return this.request("team/reports/get_devices",e,"team","api","rpc")},A.teamReportsGetMembership=function(e){return this.request("team/reports/get_membership",e,"team","api","rpc")},A.teamReportsGetStorage=function(e){return this.request("team/reports/get_storage",e,"team","api","rpc")},A.teamTeamFolderActivate=function(e){return this.request("team/team_folder/activate",e,"team","api","rpc")},A.teamTeamFolderArchive=function(e){return this.request("team/team_folder/archive",e,"team","api","rpc")},A.teamTeamFolderArchiveCheck=function(e){return this.request("team/team_folder/archive/check",e,"team","api","rpc")},A.teamTeamFolderCreate=function(e){return this.request("team/team_folder/create",e,"team","api","rpc")},A.teamTeamFolderGetInfo=function(e){return this.request("team/team_folder/get_info",e,"team","api","rpc")},A.teamTeamFolderList=function(e){return this.request("team/team_folder/list",e,"team","api","rpc")},A.teamTeamFolderListContinue=function(e){return this.request("team/team_folder/list/continue",e,"team","api","rpc")},A.teamTeamFolderPermanentlyDelete=function(e){return this.request("team/team_folder/permanently_delete",e,"team","api","rpc")},A.teamTeamFolderRename=function(e){return this.request("team/team_folder/rename",e,"team","api","rpc")},A.teamTeamFolderUpdateSyncSettings=function(e){return this.request("team/team_folder/update_sync_settings",e,"team","api","rpc")},A.teamTokenGetAuthenticatedAdmin=function(e){return this.request("team/token/get_authenticated_admin",e,"team","api","rpc")};var L=function(e){function t(e){s(this,t);var r=a(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return Object.assign(r,A),r}return u(t,q),o(t,[{key:"actAsUser",value:function(e){return new w({accessToken:this.accessToken,clientId:this.clientId,selectUser:e})}}]),t}(),S=Object.freeze({DropboxTeam:L});return{Dropbox:k.Dropbox,DropboxTeam:S.DropboxTeam}}); diff --git a/bundles/browserfs.min.js b/bundles/browserfs.min.js deleted file mode 100644 index 673df5e..0000000 --- a/bundles/browserfs.min.js +++ /dev/null @@ -1,15 +0,0 @@ -!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.BrowserFS=e():t.BrowserFS=e()}(this,function(){return function(t){function e(r){if(n[r])return n[r].exports;var i=n[r]={exports:{},id:r,loaded:!1};return t[r].call(i.exports,i,i.exports,e),i.loaded=!0,i.exports}var n={};return e.m=t,e.c=n,e.p="",e(0)}([function(t,e,n){(function(t,r,i,o){"use strict";function s(t){if(t)return t;throw new Fe(be.EIO,"Initialize BrowserFS with a file system using BrowserFS.initialize(filesystem)")}function a(t,e){switch(typeof t){case"number":return t;case"string":var n=parseInt(t,8);return isNaN(n)?e:n;default:return e}}function c(t){if(t instanceof Date)return t;if("number"==typeof t)return new Date(1e3*t);throw new Fe(be.EINVAL,"Invalid time.")}function u(t){if(t.indexOf("\0")>=0)throw new Fe(be.EINVAL,"Path must be a string without null bytes.");if(""===t)throw new Fe(be.EINVAL,"Path must not be empty.");return ke.resolve(t)}function f(t,e,n,r){switch(typeof t){case"object":return{encoding:"undefined"!=typeof t.encoding?t.encoding:e,flag:"undefined"!=typeof t.flag?t.flag:n,mode:a(t.mode,r)};case"string":return{encoding:t,flag:n,mode:r};default:return{encoding:e,flag:n,mode:r}}}function h(){}function p(t,e,n,r,i){return tn?n+1:t+1:r===i?e:e+1}function l(t,e){if(t===e)return 0;if(t.length>e.length){var n=t;t=e,e=n}for(var r=t.length,i=e.length;r>0&&t.charCodeAt(r-1)===e.charCodeAt(i-1);)r--,i--;for(var o=0;ob?b+1:I+1:S===s[r+k]?u:u+1,u=I}}return b}function d(t,e,n){t&&console.warn("["+e+"] Direct file system constructor usage is deprecated for this file system, and will be removed in the next major version. Please use the '"+e+".Create("+JSON.stringify(n)+", callback)' method instead. See https://github.com/jvilk/BrowserFS/issues/176 for more details.")}function y(){throw new Error("BFS has reached an impossible code path; please file a bug.")}function g(t,e,n){n.existsSync(t)||(g(ke.dirname(t),e,n),n.mkdirSync(t,e))}function v(t){var e=m(t),n=e.byteOffset,r=e.byteLength;return 0===n&&r===e.buffer.byteLength?e.buffer:e.buffer.slice(n,n+r)}function m(t){return t instanceof Uint8Array?t:new Uint8Array(t)}function _(e){return e instanceof t?e:e instanceof Uint8Array?w(e):t.from(e)}function w(e){return e instanceof t?e:0===e.byteOffset&&e.byteLength===e.buffer.byteLength?E(e.buffer):t.from(e.buffer,e.byteOffset,e.byteLength)}function E(e){return t.from(e)}function b(t,e,n){if(void 0===e&&(e=0),void 0===n&&(n=t.length),e<0||n<0||n>t.length||e>n)throw new TypeError("Invalid slice bounds on buffer of length "+t.length+": ["+e+", "+n+"]");if(0===t.length)return S();var r=m(t),i=t[0],o=(i+1)%255;return t[0]=o,r[0]===o?(r[0]=i,w(r.slice(e,n))):(t[0]=i,w(r.subarray(e,n)))}function S(){return je?je:je=t.alloc(0)}function k(e,n){t.isBuffer(e)?n():n(new Fe(be.EINVAL,"option must be a Buffer."))}function I(t,e,n){function r(t){a||(t&&(a=!0,n(t)),s--,0===s&&c&&n())}var i=t.Options,o=t.Name,s=0,a=!1,c=!1,u=function(t){if(i.hasOwnProperty(t)){var c=i[t],u=e[t];if(void 0===u||null===u){if(!c.optional){var f=Object.keys(e).filter(function(t){return!(t in i)}).map(function(e){return{str:e,distance:l(t,e)}}).filter(function(t){return t.distance<5}).sort(function(t,e){return t.distance-e.distance});return a?{}:(a=!0,{v:n(new Fe(be.EINVAL,"["+o+"] Required option '"+t+"' not provided."+(f.length>0?" You provided unrecognized option '"+f[0].str+"'; perhaps you meant to type '"+t+"'.":"")+"\nOption description: "+c.description))})}}else{var h=!1;if(h=Array.isArray(c.type)?c.type.indexOf(typeof u)!==-1:typeof u===c.type,!h)return a?{}:(a=!0,{v:n(new Fe(be.EINVAL,"["+o+"] Value provided for option "+t+" is not the proper type. Expected "+(Array.isArray(c.type)?"one of {"+c.type.join(", ")+"}":c.type)+", but received "+typeof u+"\nOption description: "+c.description))});c.validator&&(s++,c.validator(u,r))}}};for(var f in i){var h=u(f);if(h)return h.v}c=!0,0!==s||a||n()}function O(t,e,n){switch(n.length){case 0:return t.call(e);case 1:return t.call(e,n[0]);case 2:return t.call(e,n[0],n[1]);case 3:return t.call(e,n[0],n[1],n[2])}return t.apply(e,n)}function F(t,e,n){return e=Ge(void 0===e?t.length-1:e,0),function(){for(var r=arguments,i=-1,o=Ge(r.length-e,0),s=Array(o);++i-1&&t%1==0&&t<=vn}function U(t){return null!=t&&C(t.length)&&!P(t)}function M(){}function j(t){return function(){if(null!==t){var e=t;t=null,e.apply(this,arguments)}}}function B(t,e){for(var n=-1,r=Array(t);++n-1&&t%1==0&&t0?"/"+i.join("/"):e)}function St(t,e){if(null!==e&&"object"==typeof e){var n=e,r=n.path;r&&(r="/"+ke.relative(t,r),n.message=n.message.replace(n.path,r),n.path=r)}return e}function kt(t,e){return"function"==typeof e?function(n){arguments.length>0&&(arguments[0]=St(t,n)),e.apply(null,arguments)}:e}function It(t,e,n){return"Sync"!==t.slice(t.length-4)?function(){return arguments.length>0&&(e&&(arguments[0]=ke.join(this._folder,arguments[0])),n&&(arguments[1]=ke.join(this._folder,arguments[1])),arguments[arguments.length-1]=kt(this._folder,arguments[arguments.length-1])),this._wrapped[t].apply(this._wrapped,arguments)}:function(){try{return e&&(arguments[0]=ke.join(this._folder,arguments[0])),n&&(arguments[1]=ke.join(this._folder,arguments[1])),this._wrapped[t].apply(this._wrapped,arguments)}catch(t){throw St(this._folder,t)}}}function Ot(t){return t.isDirectory}function Ft(t,e,n,r){if("undefined"!=typeof navigator.webkitPersistentStorage)switch(t){case ti.PERSISTENT:navigator.webkitPersistentStorage.requestQuota(e,n,r);break;case ti.TEMPORARY:navigator.webkitTemporaryStorage.requestQuota(e,n,r);break;default:r(new TypeError("Invalid storage type: "+t))}else ti.webkitStorageInfo.requestQuota(t,e,n,r)}function Nt(t){return Array.prototype.slice.call(t||[],0)}function Rt(t,e,n){switch(t.name){case"PathExistsError":return Fe.EEXIST(e);case"QuotaExceededError":return Fe.FileError(be.ENOSPC,e);case"NotFoundError":return Fe.ENOENT(e);case"SecurityError":return Fe.FileError(be.EACCES,e);case"InvalidModificationError":return Fe.FileError(be.EPERM,e);case"TypeMismatchError":return Fe.FileError(n?be.ENOTDIR:be.EISDIR,e);case"EncodingError":case"InvalidStateError":case"NoModificationAllowedError":default:return Fe.FileError(be.EINVAL,e)}}function Lt(){return si?si:si=t.from("{}")}function Tt(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){var e=16*Math.random()|0,n="x"===t?e:3&e|8;return n.toString(16)})}function xt(t,e){return!t||(e(t),!1)}function At(t,e,n){return!t||(e.abort(function(){n(t)}),!1)}function Dt(t,e){switch(void 0===e&&(e=t.toString()),t.name){case"NotFoundError":return new Fe(be.ENOENT,e);case"QuotaExceededError":return new Fe(be.ENOSPC,e);default:return new Fe(be.EIO,e)}}function Pt(t,e,n){return void 0===e&&(e=be.EIO),void 0===n&&(n=null),function(r){r.preventDefault(),t(new Fe(e,null!==n?n:void 0))}}function Ct(t,e,n){return e?function(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];var r=e[0],i=this._getFs(r);e[0]=i.path;try{return i.fs[t].apply(i.fs,e)}catch(t){throw this.standardizeError(t,i.path,r),t}}:function(){for(var e=this,n=[],r=arguments.length;r--;)n[r]=arguments[r];var i=n[0],o=this._getFs(i);if(n[0]=o.path,"function"==typeof n[n.length-1]){var s=n[n.length-1];n[n.length-1]=function(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];t.length>0&&t[0]instanceof Fe&&e.standardizeError(t[0],o.path,i),s.apply(null,t)}}return o.fs[t].apply(o.fs,n)}}function Ut(t){return 146|t}function Mt(t){return Re.getFileFlag(t)}function jt(t){return{type:Wi.API_ERROR,errorData:Yt(t.writeToBuffer())}}function Bt(t){return Fe.fromBuffer(Xt(t.errorData))}function zt(t){return{type:Wi.ERROR,name:t.name,message:t.message,stack:t.stack}}function qt(t){var e=ti[t.name];"function"!=typeof e&&(e=Error);var n=new e(t.message);return n.stack=t.stack,n}function Vt(t){return{type:Wi.STATS,statsData:Yt(t.toBuffer())}}function Wt(t){return Te.fromBuffer(Xt(t.statsData))}function Ht(t){return{type:Wi.FILEFLAG,flagStr:t.getFlagString()}}function Zt(t){return Re.getFileFlag(t.flagStr)}function Yt(t){return v(t)}function Xt(t){return E(t)}function Kt(t){return{type:Wi.BUFFER,data:Yt(t)}}function Jt(t){return Xt(t.data)}function Gt(t){return t&&"object"==typeof t&&t.hasOwnProperty("browserfsMessage")&&t.browserfsMessage}function Qt(t){return t&&"object"==typeof t&&t.hasOwnProperty("browserfsMessage")&&t.browserfsMessage}function $t(e,n,r){var i=new XMLHttpRequest;i.open("GET",e,!0);var o=!0;switch(n){case"buffer":i.responseType="arraybuffer";break;case"json":try{i.responseType="json",o="json"===i.responseType}catch(t){o=!1}break;default:return r(new Fe(be.EINVAL,"Invalid download type: "+n))}i.onreadystatechange=function(e){if(4===i.readyState){if(200!==i.status)return r(new Fe(i.status,"XHR error."));switch(n){case"buffer":return r(null,i.response?t.from(i.response):S());case"json":return o?r(null,i.response):r(null,JSON.parse(i.responseText))}}},i.send()}function te(e,n){var r=new XMLHttpRequest;r.open("GET",e,!1);var i=null,o=null;if(r.overrideMimeType("text/plain; charset=x-user-defined"),r.onreadystatechange=function(e){if(4===r.readyState){if(200!==r.status)return void(o=new Fe(r.status,"XHR error."));switch(n){case"buffer":var s=r.responseText;i=t.alloc(s.length);for(var a=0;a>5&15)-1,i=(e>>9)+1980,o=31&t,s=t>>5&63,a=t>>11;return new Date(i,r,n,a,s,o)}function ue(t,e,n,r){return 0===r?"":e?t.toString("utf8",n,n+r):eo.byte2str(t.slice(n,n+r))}function fe(t,e,n){return t.toString("ascii",e,e+n).trim()}function he(t,e,n){if(1===n)return String.fromCharCode(t[e]);for(var r=Math.floor(n/2),i=new Array(r),o=0;othis._buffer.length){var n=t.alloc(e-this._buffer.length,0);return this.writeSync(n,0,n.length,this._buffer.length),void(this._flag.isSynchronous()&&Pe.getRootFS().supportsSynch()&&this.syncSync())}this._stat.size=e;var r=t.alloc(e);this._buffer.copy(r,0,0,e),this._buffer=r,this._flag.isSynchronous()&&Pe.getRootFS().supportsSynch()&&this.syncSync()},n.prototype.write=function(t,e,n,r,i){try{i(null,this.writeSync(t,e,n,r),t)}catch(t){i(t)}},n.prototype.writeSync=function(e,n,r,i){if(this._dirty=!0,void 0!==i&&null!==i||(i=this.getPos()),!this._flag.isWriteable())throw new Fe(be.EPERM,"File not opened with a writeable mode.");var o=i+r;if(o>this._stat.size&&(this._stat.size=o,o>this._buffer.length)){var s=t.alloc(o);this._buffer.copy(s),this._buffer=s}var a=e.copy(this._buffer,i,n,n+r);return this._stat.mtime=new Date,this._flag.isSynchronous()?(this.syncSync(),a):(this.setPos(i+a),a)},n.prototype.read=function(t,e,n,r,i){try{i(null,this.readSync(t,e,n,r),t)}catch(t){i(t)}},n.prototype.readSync=function(t,e,n,r){if(!this._flag.isReadable())throw new Fe(be.EPERM,"File not opened with a readable mode.");void 0!==r&&null!==r||(r=this.getPos());var i=r+n;i>this._stat.size&&(n=this._stat.size-r);var o=this._buffer.copy(t,e,r,r+n);return this._stat.atime=new Date,this._pos=r+n,o},n.prototype.chmod=function(t,e){try{this.chmodSync(t),e()}catch(t){e(t)}},n.prototype.chmodSync=function(t){if(!this._fs.supportsProps())throw new Fe(be.ENOTSUP);this._dirty=!0,this._stat.chmod(t),this.syncSync()},n.prototype.isDirty=function(){return this._dirty},n.prototype.resetDirty=function(){this._dirty=!1},n}(Ze),Xe=function(t){function e(e,n,r,i,o){t.call(this,e,n,r,i,o)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.sync=function(t){t()},e.prototype.syncSync=function(){},e.prototype.close=function(t){t()},e.prototype.closeSync=function(){},e}(Ye),Ke=function(t){function e(e,n,r,i,o){t.call(this,e,n,r,i,o)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.syncSync=function(){this.isDirty()&&(this._fs._syncSync(this),this.resetDirty())},e.prototype.closeSync=function(){this.syncSync()},e}(Ye),Je=function(t){function e(n,r,i){if(void 0===i&&(i=!0),t.call(this),this._queue=[],this._queueRunning=!1,this._isInitialized=!1,this._initializeCallbacks=[],this._sync=n,this._async=r,!n.supportsSynch())throw new Error("The first argument to AsyncMirror needs to be a synchronous file system.");d(i,e.Name,{sync:"sync file system instance",async:"async file system instance"})}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.Create=function(t,n){try{var r=new e(t.sync,t.async,!1);r.initialize(function(t){t?n(t):n(null,r)},!1)}catch(t){n(t)}},e.isAvailable=function(){return!0},e.prototype.getName=function(){return e.Name},e.prototype._syncSync=function(t){this._sync.writeFileSync(t.getPath(),t.getBuffer(),null,Re.getFileFlag("w"),t.getStats().mode),this.enqueueOp({apiMethod:"writeFile",arguments:[t.getPath(),t.getBuffer(),null,t.getFlag(),t.getStats().mode]})},e.prototype.initialize=function(t,e){var n=this;void 0===e&&(e=!0),e&&console.warn("[AsyncMirror] AsyncMirror.initialize() is deprecated and will be removed in the next major version. Please use 'AsyncMirror.Create({ sync: (sync file system instance), async: (async file system instance)}, cb)' to create and initialize AsyncMirror instances.");var r=this._initializeCallbacks,i=function(t){n._isInitialized=!t,n._initializeCallbacks=[],r.forEach(function(e){return e(t)})};if(this._isInitialized)t();else if(1===r.push(t)){var o=function(t,e,r){"/"!==t&&n._sync.mkdirSync(t,e),n._async.readdir(t,function(e,n){function i(e){e?r(e):o0){var r=e._queue.shift(),i=r.arguments;i.push(n),e._async[r.apiMethod].apply(e._async,i)}else e._queueRunning=!1};n()}},e}(He);Je.Name="AsyncMirror",Je.Options={sync:{type:"object",description:"The synchronous file system to mirror the asynchronous file system to."},async:{type:"object",description:"The asynchronous file system to mirror."}};var Ge=Math.max,Qe=function(t){return R(function(e){var n=e.pop();t.call(this,e,n)})},$e="object"==typeof r&&r&&r.Object===Object&&r,tn="object"==typeof self&&self&&self.Object===Object&&self,en=$e||tn||Function("return this")(),nn=en.Symbol,rn=Object.prototype,on=rn.hasOwnProperty,sn=rn.toString,an=nn?nn.toStringTag:void 0,cn=Object.prototype,un=cn.toString,fn="[object Null]",hn="[object Undefined]",pn=nn?nn.toStringTag:void 0,ln="[object AsyncFunction]",dn="[object Function]",yn="[object GeneratorFunction]",gn="[object Proxy]",vn=9007199254740991,mn={},_n="function"==typeof Symbol&&Symbol.iterator,wn=function(t){return _n&&t[_n]&&t[_n]()},En="[object Arguments]",bn=Object.prototype,Sn=bn.hasOwnProperty,kn=bn.propertyIsEnumerable,In=q(function(){return arguments}())?q:function(t){return z(t)&&Sn.call(t,"callee")&&!kn.call(t,"callee")},On=Array.isArray,Fn="object"==typeof e&&e&&!e.nodeType&&e,Nn=Fn&&"object"==typeof i&&i&&!i.nodeType&&i,Rn=Nn&&Nn.exports===Fn,Ln=Rn?en.Buffer:void 0,Tn=Ln?Ln.isBuffer:void 0,xn=Tn||V,An=9007199254740991,Dn=/^(?:0|[1-9]\d*)$/,Pn="[object Arguments]",Cn="[object Array]",Un="[object Boolean]",Mn="[object Date]",jn="[object Error]",Bn="[object Function]",zn="[object Map]",qn="[object Number]",Vn="[object Object]",Wn="[object RegExp]",Hn="[object Set]",Zn="[object String]",Yn="[object WeakMap]",Xn="[object ArrayBuffer]",Kn="[object DataView]",Jn="[object Float32Array]",Gn="[object Float64Array]",Qn="[object Int8Array]",$n="[object Int16Array]",tr="[object Int32Array]",er="[object Uint8Array]",nr="[object Uint8ClampedArray]",rr="[object Uint16Array]",ir="[object Uint32Array]",or={};or[Jn]=or[Gn]=or[Qn]=or[$n]=or[tr]=or[er]=or[nr]=or[rr]=or[ir]=!0,or[Pn]=or[Cn]=or[Xn]=or[Un]=or[Kn]=or[Mn]=or[jn]=or[Bn]=or[zn]=or[qn]=or[Vn]=or[Wn]=or[Hn]=or[Zn]=or[Yn]=!1;var sr="object"==typeof e&&e&&!e.nodeType&&e,ar=sr&&"object"==typeof i&&i&&!i.nodeType&&i,cr=ar&&ar.exports===sr,ur=cr&&$e.process,fr=function(){try{return ur&&ur.binding&&ur.binding("util")}catch(t){}}(),hr=fr&&fr.isTypedArray,pr=hr?Z(hr):H,lr=Object.prototype,dr=lr.hasOwnProperty,yr=Object.prototype,gr=K(Object.keys,Object),vr=Object.prototype,mr=vr.hasOwnProperty,_r=ot(it,1/0),wr=function(t,e,n){var r=U(t)?st:_r;r(t,e,n)},Er=at(ct);L(Er);var br=ut(ct),Sr=ot(br,1);L(Sr),R(function(t,e){return R(function(n){return t.apply(null,e.concat(n))})});var kr,Ir=(ht(),"\\ud800-\\udfff"),Or="\\u0300-\\u036f",Fr="\\ufe20-\\ufe2f",Nr="\\u20d0-\\u20ff",Rr=Or+Fr+Nr,Lr="\\ufe0e\\ufe0f",Tr="["+Ir+"]",xr="["+Rr+"]",Ar="\\ud83c[\\udffb-\\udfff]",Dr="(?:"+xr+"|"+Ar+")",Pr="[^"+Ir+"]",Cr="(?:\\ud83c[\\udde6-\\uddff]){2}",Ur="[\\ud800-\\udbff][\\udc00-\\udfff]",Mr="\\u200d",jr=Dr+"?",Br="["+Lr+"]?",zr=("(?:"+Mr+"(?:"+[Pr,Cr,Ur].join("|")+")"+Br+jr+")*","(?:"+[Pr+xr+"?",xr,Cr,Ur,Tr].join("|")+")","function"==typeof setImmediate&&setImmediate),qr="object"==typeof o&&"function"==typeof o.nextTick;kr=zr?setImmediate:qr?o.nextTick:pt,lt(kr);var Vr=ot(it,1),Wr=R(function(t){return R(function(e){var n=this,r=e[e.length-1];"function"==typeof r?e.pop():r=M,dt(t,e,function(t,e,r){e.apply(n,t.concat(R(function(t,e){r(t,e)})))},function(t,e){r.apply(n,[t].concat(e))})})});R(function(t){return Wr.apply(null,t.reverse())}),R(function(t){var e=[null].concat(t);return Qe(function(t,n){return n.apply(this,e)})}),yt("dir"),yt("log");var Hr;Hr=qr?o.nextTick:zr?setImmediate:pt,lt(Hr);var Zr,Yr=(Math.ceil,Math.max,function(t){this._cache={},this._client=t});Yr.prototype.readdir=function(t,e){var n=this,r=this.getCachedDirInfo(t);this._wrap(function(e){null!==r&&r.contents?n._client.readdir(t,{contentHash:r.stat.contentHash},e):n._client.readdir(t,e)},function(i,o,s,a){i?i.status===Dropbox.ApiError.NO_CONTENT&&null!==r?e(null,r.contents.slice(0)):e(i):(n.updateCachedDirInfo(t,s,o.slice(0)),a.forEach(function(e){n.updateCachedInfo(ke.join(t,e.name),e)}),e(null,o))})},Yr.prototype.remove=function(t,e){var n=this;this._wrap(function(e){n._client.remove(t,e)},function(r,i){r||n.updateCachedInfo(t,i),e(r)})},Yr.prototype.move=function(t,e,n){var r=this;this._wrap(function(n){r._client.move(t,e,n)},function(i,o){i||(r.deleteCachedInfo(t),r.updateCachedInfo(e,o)),n(i)})},Yr.prototype.stat=function(t,e){var n=this;this._wrap(function(e){n._client.stat(t,e)},function(r,i){r||n.updateCachedInfo(t,i),e(r,i)})},Yr.prototype.readFile=function(t,e){var n=this,r=this.getCachedFileInfo(t);null!==r&&null!==r.contents?this.stat(t,function(i,o){i?e(i):o.contentHash===r.stat.contentHash?e(i,r.contents.slice(0),r.stat):n.readFile(t,e)}):this._wrap(function(e){n._client.readFile(t,{arrayBuffer:!0},e)},function(r,i,o){r||n.updateCachedInfo(t,o,i.slice(0)),e(r,i,o)})},Yr.prototype.writeFile=function(t,e,n){var r=this;this._wrap(function(n){r._client.writeFile(t,e,n)},function(i,o){i||r.updateCachedInfo(t,o,e.slice(0)),n(i,o)})},Yr.prototype.mkdir=function(t,e){var n=this;this._wrap(function(e){n._client.mkdir(t,e)},function(r,i){r||n.updateCachedInfo(t,i,[]),e(r)})},Yr.prototype._wrap=function(t,e){var n=0,r=function(i){var o=2;if(i&&3>++n)switch(i.status){case Dropbox.ApiError.SERVER_ERROR:case Dropbox.ApiError.NETWORK_ERROR:case Dropbox.ApiError.RATE_LIMITED:setTimeout(function(){t(r)},1e3*o);break;default:e.apply(null,arguments)}else e.apply(null,arguments)};t(r)},Yr.prototype.getCachedInfo=function(t){return this._cache[t.toLowerCase()]},Yr.prototype.putCachedInfo=function(t,e){this._cache[t.toLowerCase()]=e},Yr.prototype.deleteCachedInfo=function(t){delete this._cache[t.toLowerCase()]},Yr.prototype.getCachedDirInfo=function(t){var e=this.getCachedInfo(t);return wt(e)?e:null},Yr.prototype.getCachedFileInfo=function(t){var e=this.getCachedInfo(t);return _t(e)?e:null},Yr.prototype.updateCachedDirInfo=function(t,e,n){void 0===n&&(n=null);var r=this.getCachedInfo(t);null===e.contentHash||void 0!==r&&r.stat.contentHash===e.contentHash||this.putCachedInfo(t,{stat:e,contents:n})},Yr.prototype.updateCachedFileInfo=function(t,e,n){void 0===n&&(n=null);var r=this.getCachedInfo(t);null===e.versionTag||void 0!==r&&r.stat.versionTag===e.versionTag||this.putCachedInfo(t,{stat:e,contents:n})},Yr.prototype.updateCachedInfo=function(t,e,n){void 0===n&&(n=null),e.isFile&&Et(n)?this.updateCachedFileInfo(t,e,n):e.isFolder&&Array.isArray(n)&&this.updateCachedDirInfo(t,e,n)};var Xr=function(t){function e(e,n,r,i,o){t.call(this,e,n,r,i,o)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.sync=function(t){var e=this;if(this.isDirty()){var n=this.getBuffer(),r=v(n);this._fs._writeFileStrict(this.getPath(),r,function(n){n||e.resetDirty(),t(n)})}else t()},e.prototype.close=function(t){this.sync(t)},e}(Ye),Kr=function(t){function e(n,r){void 0===r&&(r=!0),t.call(this),this._client=new Yr(n),d(r,e.Name,{client:"authenticated dropbox client instance"}),mt()}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.Create=function(t,n){n(null,new e(t.client,!1))},e.isAvailable=function(){return"undefined"!=typeof Dropbox},e.prototype.getName=function(){return e.Name},e.prototype.isReadOnly=function(){return!1},e.prototype.supportsSymlinks=function(){return!1},e.prototype.supportsProps=function(){return!1},e.prototype.supportsSynch=function(){return!1},e.prototype.empty=function(t){var e=this;this._client.readdir("/",function(n,r){if(n)t(e.convert(n,"/"));else{var i=function(t,n){var r=ke.join("/",t);e._client.remove(r,function(t){n(t?e.convert(t,r):null)})},o=function(e){e?t(e):t()};vt(r,i,o)}})},e.prototype.rename=function(t,e,n){var r=this;this._client.move(t,e,function(i){i?r._client.stat(e,function(o,s){if(o||s.isFolder){var a=i.response.error.indexOf(t)>-1?t:e; -n(r.convert(i,a))}else r._client.remove(e,function(i){i?n(r.convert(i,e)):r.rename(t,e,n)})}):n()})},e.prototype.stat=function(t,e,n){var r=this;this._client.stat(t,function(e,i){if(e)n(r.convert(e,t));else{if(!i||!i.isRemoved){var o=new Te(r._statType(i),i.size);return n(null,o)}n(Fe.FileError(be.ENOENT,t))}})},e.prototype.open=function(t,e,n,r){var i=this;this._client.readFile(t,function(n,o,s){if(!n){var a;a=null===o?S():E(o);var c=i._makeFile(t,e,s,a);return r(null,c)}if(e.isReadable())r(i.convert(n,t));else switch(n.status){case Dropbox.ApiError.NOT_FOUND:var u=new ArrayBuffer(0);return i._writeFileStrict(t,u,function(n,o){if(n)r(n);else{var s=i._makeFile(t,e,o,E(u));r(null,s)}});default:return r(i.convert(n,t))}})},e.prototype._writeFileStrict=function(t,e,n){var r=this,i=ke.dirname(t);this.stat(i,!1,function(o,s){o?n(Fe.FileError(be.ENOENT,i)):r._client.writeFile(t,e,function(e,i){e?n(r.convert(e,t)):n(null,i)})})},e.prototype._statType=function(t){return t.isFile?Le.FILE:Le.DIRECTORY},e.prototype._makeFile=function(t,e,n,r){var i=this._statType(n),o=new Te(i,n.size);return new Xr(this,t,e,o,r)},e.prototype._remove=function(t,e,n){var r=this;this._client.stat(t,function(i,o){i?e(r.convert(i,t)):o.isFile&&!n?e(Fe.FileError(be.ENOTDIR,t)):!o.isFile&&n?e(Fe.FileError(be.EISDIR,t)):r._client.remove(t,function(n){e(n?r.convert(n,t):null)})})},e.prototype.unlink=function(t,e){this._remove(t,e,!0)},e.prototype.rmdir=function(t,e){this._remove(t,e,!1)},e.prototype.mkdir=function(t,e,n){var r=this,i=ke.dirname(t);this._client.stat(i,function(e,o){e?n(r.convert(e,i)):r._client.mkdir(t,function(e){n(e?Fe.FileError(be.EEXIST,t):null)})})},e.prototype.readdir=function(t,e){var n=this;this._client.readdir(t,function(t,r){return t?e(n.convert(t)):e(null,r)})},e.prototype.convert=function(t,e){void 0===e&&(e=null);var n=Zr[t.status];return void 0===n&&(n=be.EIO),e?Fe.FileError(n,e):new Fe(n)},e}(We);Kr.Name="Dropbox",Kr.Options={client:{type:"object",description:"An *authenticated* Dropbox client. Must be from the 0.10 JS SDK.",validator:function(t,e){t.isAuthenticated&&t.isAuthenticated()?e():e(new Fe(be.EINVAL,"'client' option must be an authenticated Dropbox client from the v0.10 JS SDK."))}}};var Jr=function(t){function e(e,n,r,i){t.call(this),this._fs=e,this._FS=n,this._path=r,this._stream=i}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.getPos=function(){},e.prototype.close=function(t){var e=null;try{this.closeSync()}catch(t){e=t}finally{t(e)}},e.prototype.closeSync=function(){try{this._FS.close(this._stream)}catch(t){throw bt(t,this._path)}},e.prototype.stat=function(t){try{t(null,this.statSync())}catch(e){t(e)}},e.prototype.statSync=function(){try{return this._fs.statSync(this._path,!1)}catch(t){throw bt(t,this._path)}},e.prototype.truncate=function(t,e){var n=null;try{this.truncateSync(t)}catch(t){n=t}finally{e(n)}},e.prototype.truncateSync=function(t){try{this._FS.ftruncate(this._stream.fd,t)}catch(t){throw bt(t,this._path)}},e.prototype.write=function(t,e,n,r,i){try{i(null,this.writeSync(t,e,n,r),t)}catch(t){i(t)}},e.prototype.writeSync=function(t,e,n,r){try{var i=m(t),o=null===r?void 0:r;return this._FS.write(this._stream,i,e,n,o)}catch(t){throw bt(t,this._path)}},e.prototype.read=function(t,e,n,r,i){try{i(null,this.readSync(t,e,n,r),t)}catch(t){i(t)}},e.prototype.readSync=function(t,e,n,r){try{var i=m(t),o=null===r?void 0:r;return this._FS.read(this._stream,i,e,n,o)}catch(t){throw bt(t,this._path)}},e.prototype.sync=function(t){t()},e.prototype.syncSync=function(){},e.prototype.chown=function(t,e,n){var r=null;try{this.chownSync(t,e)}catch(t){r=t}finally{n(r)}},e.prototype.chownSync=function(t,e){try{this._FS.fchown(this._stream.fd,t,e)}catch(t){throw bt(t,this._path)}},e.prototype.chmod=function(t,e){var n=null;try{this.chmodSync(t)}catch(t){n=t}finally{e(n)}},e.prototype.chmodSync=function(t){try{this._FS.fchmod(this._stream.fd,t)}catch(t){throw bt(t,this._path)}},e.prototype.utimes=function(t,e,n){var r=null;try{this.utimesSync(t,e)}catch(t){r=t}finally{n(r)}},e.prototype.utimesSync=function(t,e){this._fs.utimesSync(this._path,t,e)},e}(Ze),Gr=function(e){function n(t){e.call(this),this._FS=t}return e&&(n.__proto__=e),n.prototype=Object.create(e&&e.prototype),n.prototype.constructor=n,n.Create=function(t,e){e(null,new n(t.FS))},n.isAvailable=function(){return!0},n.prototype.getName=function(){return this._FS.DB_NAME()},n.prototype.isReadOnly=function(){return!1},n.prototype.supportsLinks=function(){return!0},n.prototype.supportsProps=function(){return!0},n.prototype.supportsSynch=function(){return!0},n.prototype.renameSync=function(t,e){try{this._FS.rename(t,e)}catch(n){throw n.errno===be.ENOENT?bt(n,this.existsSync(t)?e:t):bt(n)}},n.prototype.statSync=function(t,e){try{var n=e?this._FS.lstat(t):this._FS.stat(t),r=this.modeToFileType(n.mode);return new Te(r,n.size,n.mode,n.atime,n.mtime,n.ctime)}catch(e){throw bt(e,t)}},n.prototype.openSync=function(t,e,n){try{var r=this._FS.open(t,e.getFlagString(),n);if(this._FS.isDir(r.node.mode))throw this._FS.close(r),Fe.EISDIR(t);return new Jr(this,this._FS,t,r)}catch(e){throw bt(e,t)}},n.prototype.unlinkSync=function(t){try{this._FS.unlink(t)}catch(e){throw bt(e,t)}},n.prototype.rmdirSync=function(t){try{this._FS.rmdir(t)}catch(e){throw bt(e,t)}},n.prototype.mkdirSync=function(t,e){try{this._FS.mkdir(t,e)}catch(e){throw bt(e,t)}},n.prototype.readdirSync=function(t){try{return this._FS.readdir(t).filter(function(t){return"."!==t&&".."!==t})}catch(e){throw bt(e,t)}},n.prototype.truncateSync=function(t,e){try{this._FS.truncate(t,e)}catch(e){throw bt(e,t)}},n.prototype.readFileSync=function(t,e,n){try{var r=this._FS.readFile(t,{flags:n.getFlagString()}),i=w(r);return e?i.toString(e):i}catch(e){throw bt(e,t)}},n.prototype.writeFileSync=function(e,n,r,i,o){try{r&&(n=t.from(n,r));var s=m(n);this._FS.writeFile(e,s,{flags:i.getFlagString(),encoding:"binary"}),this._FS.chmod(e,o)}catch(t){throw bt(t,e)}},n.prototype.chmodSync=function(t,e,n){try{e?this._FS.lchmod(t,n):this._FS.chmod(t,n)}catch(e){throw bt(e,t)}},n.prototype.chownSync=function(t,e,n,r){try{e?this._FS.lchown(t,n,r):this._FS.chown(t,n,r)}catch(e){throw bt(e,t)}},n.prototype.symlinkSync=function(t,e,n){try{this._FS.symlink(t,e)}catch(t){throw bt(t)}},n.prototype.readlinkSync=function(t){try{return this._FS.readlink(t)}catch(e){throw bt(e,t)}},n.prototype.utimesSync=function(t,e,n){try{this._FS.utime(t,e.getTime(),n.getTime())}catch(e){throw bt(e,t)}},n.prototype.modeToFileType=function(t){if(this._FS.isDir(t))return Le.DIRECTORY;if(this._FS.isFile(t))return Le.FILE;if(this._FS.isLink(t))return Le.SYMLINK;throw Fe.EPERM("Invalid mode: "+t)},n}(He);Gr.Name="EmscriptenFileSystem",Gr.Options={FS:{type:"object",description:"The Emscripten file system to use (the `FS` variable)"}};var Qr=function(t){function e(e,n){t.call(this),this._folder=e,this._wrapped=n}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.Create=function(t,n){n(null,new e(t.folder,t.wrapped))},e.isAvailable=function(){return!0},e.prototype.initialize=function(t){var e=this;this._wrapped.exists(this._folder,function(n){n?t():e._wrapped.isReadOnly()?t(Fe.ENOENT(e._folder)):e._wrapped.mkdir(e._folder,511,t)})},e.prototype.getName=function(){return this._wrapped.getName()},e.prototype.isReadOnly=function(){return this._wrapped.isReadOnly()},e.prototype.supportsProps=function(){return this._wrapped.supportsProps()},e.prototype.supportsSynch=function(){return this._wrapped.supportsSynch()},e.prototype.supportsLinks=function(){return!1},e}(We);Qr.Name="FolderAdapter",Qr.Options={folder:{type:"string",description:"The folder to use as the root directory"},wrapped:{type:"object",description:"The file system to wrap"}},["diskSpace","stat","statSync","open","openSync","unlink","unlinkSync","rmdir","rmdirSync","mkdir","mkdirSync","readdir","readdirSync","exists","existsSync","realpath","realpathSync","truncate","truncateSync","readFile","readFileSync","writeFile","writeFileSync","appendFile","appendFileSync","chmod","chmodSync","chown","chownSync","utimes","utimesSync","readlink","readlinkSync"].forEach(function(t){Qr.prototype[t]=It(t,!0,!1)}),["rename","renameSync","link","linkSync","symlink","symlinkSync"].forEach(function(t){Qr.prototype[t]=It(t,!0,!0)});var $r;$r="undefined"!=typeof window?window:"undefined"!=typeof self?self:r;var ti=$r,ei=ti.webkitRequestFileSystem||ti.requestFileSystem||null,ni=function(t){function e(e,n,r,i,o,s){t.call(this,e,r,i,o,s),this._entry=n}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.sync=function(t){var e=this;return this.isDirty()?void this._entry.createWriter(function(n){var r=e.getBuffer(),i=new Blob([v(r)]),o=i.size;n.onwriteend=function(r){n.onwriteend=null,n.onerror=null,n.truncate(o),e.resetDirty(),t()},n.onerror=function(n){t(Rt(n,e.getPath(),!1))},n.write(i)}):t()},e.prototype.close=function(t){this.sync(t)},e}(Ye),ri=function(t){function e(n,r,i){void 0===n&&(n=5),void 0===r&&(r=ti.PERSISTENT),void 0===i&&(i=!0),t.call(this),this.size=1048576*n,this.type=r,d(i,e.Name,{size:n,type:r})}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.Create=function(t,n){var r=new e(t.size,t.type,!1);r.allocate(function(t){return t?n(t):n(null,r)},!1)},e.isAvailable=function(){return!!ei},e.prototype.getName=function(){return e.Name},e.prototype.isReadOnly=function(){return!1},e.prototype.supportsSymlinks=function(){return!1},e.prototype.supportsProps=function(){return!1},e.prototype.supportsSynch=function(){return!1},e.prototype.allocate=function(t,e){var n=this;void 0===t&&(t=function(){}),void 0===e&&(e=!0),e&&console.warn("[HTML5FS] HTML5FS.allocate() is deprecated and will be removed in the next major release. Please use 'HTML5FS.Create({type: "+this.type+", size: "+this.size+"}, cb)' to create and allocate HTML5FS instances.");var r=function(e){n.fs=e,t()},i=function(e){t(Rt(e,"/",!0))};this.type===ti.PERSISTENT?Ft(this.type,this.size,function(t){ei(n.type,t,r,i)},i):ei(this.type,this.size,r,i)},e.prototype.empty=function(t){this._readdir("/",function(e,n){if(e)console.error("Failed to empty FS"),t(e);else{var r=function(n){e?(console.error("Failed to empty FS"),t(e)):t()},i=function(t,e){var n=function(){e()},r=function(n){e(Rt(n,t.fullPath,!t.isDirectory))};Ot(t)?t.removeRecursively(n,r):t.remove(n,r)};vt(n,i,r)}})},e.prototype.rename=function(t,e,n){var r=this,i=2,o=0,s=this.fs.root,a=t,c=function(t){--i<=0&&n(Rt(t,a,!1))},u=function(i){return 2===++o?n(new Fe(be.EINVAL,"Something was identified as both a file and a directory. This should never happen.")):t===e?n():(a=ke.dirname(e),void s.getDirectory(a,{},function(o){a=ke.basename(e),i.moveTo(o,a,function(t){n()},function(o){i.isDirectory?(a=e,r.unlink(e,function(i){i?c(o):r.rename(t,e,n)})):c(o)})},c))};s.getFile(t,{},u,c),s.getDirectory(t,{},u,c)},e.prototype.stat=function(t,e,n){var r=this,i={create:!1},o=function(t){var e=function(t){var e=new Te(Le.FILE,t.size);n(null,e)};t.file(e,a)},s=function(t){var e=4096,r=new Te(Le.DIRECTORY,e);n(null,r)},a=function(e){n(Rt(e,t,!1))},c=function(){r.fs.root.getDirectory(t,i,s,a)};this.fs.root.getFile(t,i,o,c)},e.prototype.open=function(t,e,n,r){var i=this,o=function(n){r("InvalidModificationError"===n.name&&e.isExclusive()?Fe.EEXIST(t):Rt(n,t,!1))};this.fs.root.getFile(t,{create:e.pathNotExistsAction()===Oe.CREATE_FILE,exclusive:e.isExclusive()},function(n){n.file(function(s){var a=new FileReader;a.onloadend=function(o){var c=i._makeFile(t,n,e,s,a.result);r(null,c)},a.onerror=function(t){o(a.error)},a.readAsArrayBuffer(s)},o)},o)},e.prototype.unlink=function(t,e){this._remove(t,e,!0)},e.prototype.rmdir=function(t,e){var n=this;this.readdir(t,function(r,i){r?e(r):i.length>0?e(Fe.ENOTEMPTY(t)):n._remove(t,e,!1)})},e.prototype.mkdir=function(t,e,n){var r={create:!0,exclusive:!0},i=function(t){n()},o=function(e){n(Rt(e,t,!0))};this.fs.root.getDirectory(t,r,i,o)},e.prototype.readdir=function(t,e){this._readdir(t,function(t,n){if(!n)return e(t);for(var r=[],i=0,o=n;i0)throw Fe.ENOTEMPTY(t);this.removeEntry(t,!0)},n.prototype.mkdirSync=function(e,n){var r=this.store.beginTransaction("readwrite"),i=t.from("{}");this.commitNewFile(r,e,Le.DIRECTORY,n,i)},n.prototype.readdirSync=function(t){var e=this.store.beginTransaction("readonly");return Object.keys(this.getDirListing(e,t,this.findINode(e,t)))},n.prototype._syncSync=function(t,e,n){var r=this.store.beginTransaction("readwrite"),i=this._findINode(r,ke.dirname(t),ke.basename(t)),o=this.getINode(r,t,i),s=o.update(n);try{r.put(o.id,e,!0),s&&r.put(i,o.toBuffer(),!0)}catch(t){throw r.abort(),t}r.commit()},n.prototype.makeRootDirectory=function(){var t=this.store.beginTransaction("readwrite");if(void 0===t.get(oi)){var e=(new Date).getTime(),n=new ii(Tt(),4096,511|Le.DIRECTORY,e,e,e);t.put(n.id,Lt(),!1),t.put(oi,n.toBuffer(),!1),t.commit()}},n.prototype._findINode=function(t,e,n){var r=this,i=function(i){var o=r.getDirListing(t,e,i);if(o[n])return o[n];throw Fe.ENOENT(ke.resolve(e,n))};return"/"===e?""===n?oi:i(this.getINode(t,e,oi)):i(this.getINode(t,e+ke.sep+n,this._findINode(t,ke.dirname(e),ke.basename(e))))},n.prototype.findINode=function(t,e){return this.getINode(t,e,this._findINode(t,ke.dirname(e),ke.basename(e)))},n.prototype.getINode=function(t,e,n){var r=t.get(n);if(void 0===r)throw Fe.ENOENT(e);return ii.fromBuffer(r)},n.prototype.getDirListing=function(t,e,n){if(!n.isDirectory())throw Fe.ENOTDIR(e);var r=t.get(n.id);if(void 0===r)throw Fe.ENOENT(e);return JSON.parse(r.toString())},n.prototype.addNewNode=function(t,e){for(var n,r=0;r<5;)try{return n=Tt(),t.put(n,e,!1),n}catch(t){}throw new Fe(be.EIO,"Unable to commit data to key-value store.")},n.prototype.commitNewFile=function(e,n,r,i,o){var s=ke.dirname(n),a=ke.basename(n),c=this.findINode(e,s),u=this.getDirListing(e,s,c),f=(new Date).getTime();if("/"===n)throw Fe.EEXIST(n);if(u[a])throw Fe.EEXIST(n);var h;try{var p=this.addNewNode(e,o);h=new ii(p,o.length,i|r,f,f,f);var l=this.addNewNode(e,h.toBuffer());u[a]=l,e.put(c.id,t.from(JSON.stringify(u)),!0)}catch(t){throw e.abort(),t}return e.commit(),h},n.prototype.removeEntry=function(e,n){var r=this.store.beginTransaction("readwrite"),i=ke.dirname(e),o=this.findINode(r,i),s=this.getDirListing(r,i,o),a=ke.basename(e);if(!s[a])throw Fe.ENOENT(e);var c=s[a];delete s[a];var u=this.getINode(r,e,c);if(!n&&u.isDirectory())throw Fe.EISDIR(e);if(n&&!u.isDirectory())throw Fe.ENOTDIR(e);try{r.del(u.id),r.del(c),r.put(o.id,t.from(JSON.stringify(s)),!0)}catch(t){throw r.abort(),t}r.commit()},n}(He),fi=function(t){function e(e,n,r,i,o){t.call(this,e,n,r,i,o)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.sync=function(t){var e=this;this.isDirty()?this._fs._sync(this.getPath(),this.getBuffer(),this.getStats(),function(n){n||e.resetDirty(),t(n)}):t()},e.prototype.close=function(t){this.sync(t)},e}(Ye),hi=function(e){function n(){e.apply(this,arguments)}return e&&(n.__proto__=e),n.prototype=Object.create(e&&e.prototype),n.prototype.constructor=n,n.isAvailable=function(){return!0},n.prototype.init=function(t,e){this.store=t,this.makeRootDirectory(e)},n.prototype.getName=function(){return this.store.name()},n.prototype.isReadOnly=function(){return!1},n.prototype.supportsSymlinks=function(){return!1},n.prototype.supportsProps=function(){return!1},n.prototype.supportsSynch=function(){return!1},n.prototype.empty=function(t){var e=this;this.store.clear(function(n){xt(n,t)&&e.makeRootDirectory(t)})},n.prototype.rename=function(e,n,r){var i=this,o=this.store.beginTransaction("readwrite"),s=ke.dirname(e),a=ke.basename(e),c=ke.dirname(n),u=ke.basename(n),f={},h={},p=!1;if(0===(c+"/").indexOf(e+"/"))return r(new Fe(be.EBUSY,s));var l=function(){if(!p&&h.hasOwnProperty(s)&&h.hasOwnProperty(c)){var l=h[s],d=f[s],y=h[c],g=f[c];if(l[a]){var v=l[a];delete l[a];var m=function(){y[u]=v,o.put(d.id,t.from(JSON.stringify(l)),!0,function(e){At(e,o,r)&&(s===c?o.commit(r):o.put(g.id,t.from(JSON.stringify(y)),!0,function(t){At(t,o,r)&&o.commit(r)}))})};y[u]?i.getINode(o,n,y[u],function(t,e){At(t,o,r)&&(e.isFile()?o.del(e.id,function(t){At(t,o,r)&&o.del(y[u],function(t){At(t,o,r)&&m()})}):o.abort(function(t){r(Fe.EPERM(n))}))}):m()}else r(Fe.ENOENT(e))}},d=function(t){i.findINodeAndDirListing(o,t,function(e,n,i){e?p||(p=!0,o.abort(function(){r(e)})):(f[t]=n,h[t]=i,l())})};d(s),s!==c&&d(c)},n.prototype.stat=function(t,e,n){var r=this.store.beginTransaction("readonly");this.findINode(r,t,function(t,e){xt(t,n)&&n(null,e.toStats())})},n.prototype.createFile=function(t,e,n,r){var i=this,o=this.store.beginTransaction("readwrite"),s=S();this.commitNewFile(o,t,Le.FILE,n,s,function(n,o){xt(n,r)&&r(null,new fi(i,t,e,o.toStats(),s))})},n.prototype.openFile=function(t,e,n){var r=this,i=this.store.beginTransaction("readonly");this.findINode(i,t,function(o,s){xt(o,n)&&i.get(s.id,function(i,o){xt(i,n)&&(void 0===o?n(Fe.ENOENT(t)):n(null,new fi(r,t,e,s.toStats(),o)))})})},n.prototype.unlink=function(t,e){this.removeEntry(t,!1,e)},n.prototype.rmdir=function(t,e){var n=this;this.readdir(t,function(r,i){r?e(r):i.length>0?e(Fe.ENOTEMPTY(t)):n.removeEntry(t,!0,e)})},n.prototype.mkdir=function(e,n,r){var i=this.store.beginTransaction("readwrite"),o=t.from("{}");this.commitNewFile(i,e,Le.DIRECTORY,n,o,r)},n.prototype.readdir=function(t,e){var n=this,r=this.store.beginTransaction("readonly");this.findINode(r,t,function(i,o){xt(i,e)&&n.getDirListing(r,t,o,function(t,n){xt(t,e)&&e(null,Object.keys(n))})})},n.prototype._sync=function(t,e,n,r){var i=this,o=this.store.beginTransaction("readwrite");this._findINode(o,ke.dirname(t),ke.basename(t),function(s,a){At(s,o,r)&&i.getINode(o,t,a,function(t,i){if(At(t,o,r)){var s=i.update(n);o.put(i.id,e,!0,function(t){At(t,o,r)&&(s?o.put(a,i.toBuffer(),!0,function(t){At(t,o,r)&&o.commit(r)}):o.commit(r))})}})})},n.prototype.makeRootDirectory=function(t){var e=this.store.beginTransaction("readwrite");e.get(oi,function(n,r){if(n||void 0===r){var i=(new Date).getTime(),o=new ii(Tt(),4096,511|Le.DIRECTORY,i,i,i);e.put(o.id,Lt(),!1,function(n){At(n,e,t)&&e.put(oi,o.toBuffer(),!1,function(n){n?e.abort(function(){t(n)}):e.commit(t)})})}else e.commit(t)})},n.prototype._findINode=function(t,e,n,r){var i=this,o=function(t,i,o){t?r(t):o[n]?r(null,o[n]):r(Fe.ENOENT(ke.resolve(e,n)))};"/"===e?""===n?r(null,oi):this.getINode(t,e,oi,function(n,s){xt(n,r)&&i.getDirListing(t,e,s,function(t,e){o(t,s,e)})}):this.findINodeAndDirListing(t,e,o)},n.prototype.findINode=function(t,e,n){var r=this;this._findINode(t,ke.dirname(e),ke.basename(e),function(i,o){xt(i,n)&&r.getINode(t,e,o,n)})},n.prototype.getINode=function(t,e,n,r){t.get(n,function(t,n){xt(t,r)&&(void 0===n?r(Fe.ENOENT(e)):r(null,ii.fromBuffer(n)))})},n.prototype.getDirListing=function(t,e,n,r){n.isDirectory()?t.get(n.id,function(t,n){if(xt(t,r))try{r(null,JSON.parse(n.toString()))}catch(t){r(Fe.ENOENT(e))}}):r(Fe.ENOTDIR(e))},n.prototype.findINodeAndDirListing=function(t,e,n){var r=this;this.findINode(t,e,function(i,o){xt(i,n)&&r.getDirListing(t,e,o,function(t,e){xt(t,n)&&n(null,o,e)})})},n.prototype.addNewNode=function(t,e,n){var r,i=0,o=function(){5===++i?n(new Fe(be.EIO,"Unable to commit data to key-value store.")):(r=Tt(),t.put(r,e,!1,function(t,e){t||!e?o():n(null,r)}))};o()},n.prototype.commitNewFile=function(e,n,r,i,o,s){var a=this,c=ke.dirname(n),u=ke.basename(n),f=(new Date).getTime();return"/"===n?s(Fe.EEXIST(n)):void this.findINodeAndDirListing(e,c,function(c,h,p){At(c,e,s)&&(p[u]?e.abort(function(){s(Fe.EEXIST(n))}):a.addNewNode(e,o,function(n,c){if(At(n,e,s)){var l=new ii(c,o.length,i|r,f,f,f);a.addNewNode(e,l.toBuffer(),function(n,r){At(n,e,s)&&(p[u]=r,e.put(h.id,t.from(JSON.stringify(p)),!0,function(t){At(t,e,s)&&e.commit(function(t){At(t,e,s)&&s(null,l)})}))})}}))})},n.prototype.removeEntry=function(e,n,r){var i=this,o=this.store.beginTransaction("readwrite"),s=ke.dirname(e),a=ke.basename(e);this.findINodeAndDirListing(o,s,function(s,c,u){if(At(s,o,r))if(u[a]){var f=u[a];delete u[a],i.getINode(o,e,f,function(i,s){At(i,o,r)&&(!n&&s.isDirectory()?o.abort(function(){r(Fe.EISDIR(e))}):n&&!s.isDirectory()?o.abort(function(){r(Fe.ENOTDIR(e))}):o.del(s.id,function(e){At(e,o,r)&&o.del(f,function(e){At(e,o,r)&&o.put(c.id,t.from(JSON.stringify(u)),!0,function(t){At(t,o,r)&&o.commit(r)})})}))})}else o.abort(function(){r(Fe.ENOENT(e))})})},n}(We),pi=function(){this.store={}};pi.prototype.name=function(){return li.Name},pi.prototype.clear=function(){this.store={}},pi.prototype.beginTransaction=function(t){return new ai(this)},pi.prototype.get=function(t){return this.store[t]},pi.prototype.put=function(t,e,n){return!(!n&&this.store.hasOwnProperty(t))&&(this.store[t]=e,!0)},pi.prototype.del=function(t){delete this.store[t]};var li=function(t){function e(){t.call(this,{store:new pi})}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.Create=function(t,n){n(null,new e)},e}(ui);li.Name="InMemory",li.Options={};var di=ti.indexedDB||ti.mozIndexedDB||ti.webkitIndexedDB||ti.msIndexedDB,yi=function(t,e){this.tx=t,this.store=e};yi.prototype.get=function(t,e){try{var n=this.store.get(t);n.onerror=Pt(e),n.onsuccess=function(t){var n=t.target.result;void 0===n?e(null,n):e(null,E(n))}}catch(t){e(Dt(t))}};var gi=function(t){function e(e,n){t.call(this,e,n)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.put=function(t,e,n,r){try{var i,o=v(e);i=n?this.store.put(o,t):this.store.add(o,t),i.onerror=Pt(r),i.onsuccess=function(t){r(null,!0)}}catch(t){r(Dt(t))}},e.prototype.del=function(t,e){try{var n=this.store.delete(t);n.onerror=Pt(e),n.onsuccess=function(t){e()}}catch(t){e(Dt(t))}},e.prototype.commit=function(t){setTimeout(t,0)},e.prototype.abort=function(t){var e=null;try{this.tx.abort()}catch(t){e=Dt(t)}finally{t(e)}},e}(yi),vi=function(t,e){var n=this;void 0===e&&(e="browserfs"),this.storeName=e;var r=di.open(this.storeName,1);r.onupgradeneeded=function(t){var e=t.target.result;e.objectStoreNames.contains(n.storeName)&&e.deleteObjectStore(n.storeName),e.createObjectStore(n.storeName)},r.onsuccess=function(e){n.db=e.target.result,t(null,n)},r.onerror=Pt(t,be.EACCES)};vi.prototype.name=function(){return mi.Name+" - "+this.storeName},vi.prototype.clear=function(t){try{var e=this.db.transaction(this.storeName,"readwrite"),n=e.objectStore(this.storeName),r=n.clear();r.onsuccess=function(e){setTimeout(t,0)},r.onerror=Pt(t)}catch(e){t(Dt(e))}},vi.prototype.beginTransaction=function(t){void 0===t&&(t="readonly");var e=this.db.transaction(this.storeName,t),n=e.objectStore(this.storeName);if("readwrite"===t)return new gi(e,n);if("readonly"===t)return new yi(e,n);throw new Fe(be.EINVAL,"Invalid transaction type.")};var mi=function(t){function e(n,r,i){var o=this;void 0===i&&(i=!0),t.call(this),this.store=new vi(function(t){t?n(t):o.init(o.store,function(t){n(t,o)})},r),d(i,e.Name,{storeName:r})}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.Create=function(t,n){new e(n,t.storeName,!1)},e.isAvailable=function(){try{return"undefined"!=typeof di&&null!==di.open("__browserfs_test__")}catch(t){return!1}},e}(hi);mi.Name="IndexedDB",mi.Options={storeName:{type:"string",optional:!0,description:"The name of this file system. You can have multiple IndexedDB file systems operating at once, but each must have a different name."}};var _i,wi=!1;try{ti.localStorage.setItem("__test__",String.fromCharCode(55296)),wi=ti.localStorage.getItem("__test__")===String.fromCharCode(55296)}catch(t){wi=!1}_i=wi?"binary_string":"binary_string_ie",t.isEncoding(_i)||(_i="base64");var Ei=function(){};Ei.prototype.name=function(){return bi.Name},Ei.prototype.clear=function(){ti.localStorage.clear()},Ei.prototype.beginTransaction=function(t){return new ai(this)},Ei.prototype.get=function(e){try{var n=ti.localStorage.getItem(e);if(null!==n)return t.from(n,_i)}catch(t){}},Ei.prototype.put=function(t,e,n){try{return!(!n&&null!==ti.localStorage.getItem(t))&&(ti.localStorage.setItem(t,e.toString(_i)),!0)}catch(t){throw new Fe(be.ENOSPC,"LocalStorage is full.")}},Ei.prototype.del=function(t){try{ti.localStorage.removeItem(t)}catch(e){throw new Fe(be.EIO,"Unable to delete key "+t+": "+e)}};var bi=function(t){function e(){t.call(this,{store:new Ei})}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.Create=function(t,n){n(null,new e)},e.isAvailable=function(){return"undefined"!=typeof ti.localStorage},e}(ui);bi.Name="LocalStorage",bi.Options={};var Si=function(t){function e(){t.call(this),this.mountList=[],this.mntMap={},this.rootFs=new li}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.Create=function(t,n){var r=new e;Object.keys(t).forEach(function(e){r.mount(e,t[e])}),n(null,r)},e.isAvailable=function(){return!0},e.prototype.mount=function(t,e){if("/"!==t[0]&&(t="/"+t),t=ke.resolve(t),this.mntMap[t])throw new Fe(be.EINVAL,"Mount point "+t+" is already taken.");g(t,511,this.rootFs),this.mntMap[t]=e,this.mountList.push(t),this.mountList=this.mountList.sort(function(t,e){return e.length-t.length})},e.prototype.umount=function(t){var e=this;if("/"!==t[0]&&(t="/"+t),t=ke.resolve(t),!this.mntMap[t])throw new Fe(be.EINVAL,"Mount point "+t+" is already unmounted.");for(delete this.mntMap[t],this.mountList.splice(this.mountList.indexOf(t),1);"/"!==t&&0===e.rootFs.readdirSync(t).length;)e.rootFs.rmdirSync(t),t=ke.dirname(t)},e.prototype._getFs=function(t){for(var e=this,n=this.mountList,r=n.length,i=0;i1?o.length:0),""===t&&(t="/"),{fs:e.mntMap[o],path:t}}return{fs:this.rootFs,path:t}},e.prototype.getName=function(){return e.Name},e.prototype.diskSpace=function(t,e){e(0,0)},e.prototype.isReadOnly=function(){return!1},e.prototype.supportsLinks=function(){return!1},e.prototype.supportsProps=function(){return!1},e.prototype.supportsSynch=function(){return!0},e.prototype.standardizeError=function(t,e,n){var r=t.message.indexOf(e);return r!==-1&&(t.message=t.message.substr(0,r)+n+t.message.substr(r+e.length),t.path=n),t},e.prototype.rename=function(t,e,n){var r=this,i=this._getFs(t),o=this._getFs(e);return i.fs===o.fs?i.fs.rename(i.path,o.path,function(s){s&&r.standardizeError(r.standardizeError(s,i.path,t),o.path,e),n(s)}):Pe.readFile(t,function(r,i){return r?n(r):void Pe.writeFile(e,i,function(e){return e?n(e):void Pe.unlink(t,n)})})},e.prototype.renameSync=function(t,e){var n=this._getFs(t),r=this._getFs(e);if(n.fs===r.fs)try{return n.fs.renameSync(n.path,r.path)}catch(i){ -throw this.standardizeError(this.standardizeError(i,n.path,t),r.path,e),i}var i=Pe.readFileSync(t);return Pe.writeFileSync(e,i),Pe.unlinkSync(t)},e.prototype.readdirSync=function(t){var e=this._getFs(t),n=null;if(e.fs!==this.rootFs)try{n=this.rootFs.readdirSync(t)}catch(t){}try{var r=e.fs.readdirSync(e.path);return null===n?r:r.concat(n.filter(function(t){return r.indexOf(t)===-1}))}catch(r){if(null===n)throw this.standardizeError(r,e.path,t);return n}},e.prototype.readdir=function(t,e){var n=this,r=this._getFs(t);r.fs.readdir(r.path,function(i,o){if(r.fs!==n.rootFs)try{var s=n.rootFs.readdirSync(t);o=o?o.concat(s.filter(function(t){return o.indexOf(t)===-1})):s}catch(o){if(i)return e(n.standardizeError(i,r.path,t))}else if(i)return e(n.standardizeError(i,r.path,t));e(null,o)})},e.prototype.rmdirSync=function(t){var e=this._getFs(t);if(this._containsMountPt(t))throw Fe.ENOTEMPTY(t);try{e.fs.rmdirSync(e.path)}catch(n){throw this.standardizeError(n,e.path,t)}},e.prototype.rmdir=function(t,e){var n=this,r=this._getFs(t);this._containsMountPt(t)?e(Fe.ENOTEMPTY(t)):r.fs.rmdir(r.path,function(i){e(i?n.standardizeError(i,r.path,t):null)})},e.prototype._containsMountPt=function(t){for(var e=this.mountList,n=e.length,r=0;r=t.length&&i.slice(0,t.length)===t)return!0}return!1},e}(We);Si.Name="MountableFileSystem",Si.Options={};for(var ki=[["exists","unlink","readlink"],["stat","mkdir","realpath","truncate"],["open","readFile","chmod","utimes"],["chown"],["writeFile","appendFile"]],Ii=0;Ii0)){var e=xi.shift();return e()}};Ti.addEventListener?Ti.addEventListener("message",Pi,!0):Ti.attachEvent("onmessage",Pi)}else if(Ti.MessageChannel){var Ci=new Ti.MessageChannel;Ci.port1.onmessage=function(t){if(xi.length>0)return xi.shift()()},Li=function(t){xi.push(t),Ci.port2.postMessage("")}}else Li=function(t){return setTimeout(t,0)}}var Ui=Li,Mi=function(){this._locked=!1,this._waiters=[]};Mi.prototype.lock=function(t){return this._locked?void this._waiters.push(t):(this._locked=!0,void t())},Mi.prototype.unlock=function(){if(!this._locked)throw new Error("unlock of a non-locked mutex");var t=this._waiters.shift();return t?void Ui(t):void(this._locked=!1)},Mi.prototype.tryLock=function(){return!this._locked&&(this._locked=!0,!0)},Mi.prototype.isLocked=function(){return this._locked};var ji=function(t){this._fs=t,this._mu=new Mi};ji.prototype.getName=function(){return"LockedFS<"+this._fs.getName()+">"},ji.prototype.getFSUnlocked=function(){return this._fs},ji.prototype.initialize=function(t){this._fs.initialize(t)},ji.prototype.diskSpace=function(t,e){this._fs.diskSpace(t,e)},ji.prototype.isReadOnly=function(){return this._fs.isReadOnly()},ji.prototype.supportsLinks=function(){return this._fs.supportsLinks()},ji.prototype.supportsProps=function(){return this._fs.supportsProps()},ji.prototype.supportsSynch=function(){return this._fs.supportsSynch()},ji.prototype.rename=function(t,e,n){var r=this;this._mu.lock(function(){r._fs.rename(t,e,function(t){r._mu.unlock(),n(t)})})},ji.prototype.renameSync=function(t,e){if(this._mu.isLocked())throw new Error("invalid sync call");return this._fs.renameSync(t,e)},ji.prototype.stat=function(t,e,n){var r=this;this._mu.lock(function(){r._fs.stat(t,e,function(t,e){r._mu.unlock(),n(t,e)})})},ji.prototype.statSync=function(t,e){if(this._mu.isLocked())throw new Error("invalid sync call");return this._fs.statSync(t,e)},ji.prototype.open=function(t,e,n,r){var i=this;this._mu.lock(function(){i._fs.open(t,e,n,function(t,e){i._mu.unlock(),r(t,e)})})},ji.prototype.openSync=function(t,e,n){if(this._mu.isLocked())throw new Error("invalid sync call");return this._fs.openSync(t,e,n)},ji.prototype.unlink=function(t,e){var n=this;this._mu.lock(function(){n._fs.unlink(t,function(t){n._mu.unlock(),e(t)})})},ji.prototype.unlinkSync=function(t){if(this._mu.isLocked())throw new Error("invalid sync call");return this._fs.unlinkSync(t)},ji.prototype.rmdir=function(t,e){var n=this;this._mu.lock(function(){n._fs.rmdir(t,function(t){n._mu.unlock(),e(t)})})},ji.prototype.rmdirSync=function(t){if(this._mu.isLocked())throw new Error("invalid sync call");return this._fs.rmdirSync(t)},ji.prototype.mkdir=function(t,e,n){var r=this;this._mu.lock(function(){r._fs.mkdir(t,e,function(t){r._mu.unlock(),n(t)})})},ji.prototype.mkdirSync=function(t,e){if(this._mu.isLocked())throw new Error("invalid sync call");return this._fs.mkdirSync(t,e)},ji.prototype.readdir=function(t,e){var n=this;this._mu.lock(function(){n._fs.readdir(t,function(t,r){n._mu.unlock(),e(t,r)})})},ji.prototype.readdirSync=function(t){if(this._mu.isLocked())throw new Error("invalid sync call");return this._fs.readdirSync(t)},ji.prototype.exists=function(t,e){var n=this;this._mu.lock(function(){n._fs.exists(t,function(t){n._mu.unlock(),e(t)})})},ji.prototype.existsSync=function(t){if(this._mu.isLocked())throw new Error("invalid sync call");return this._fs.existsSync(t)},ji.prototype.realpath=function(t,e,n){var r=this;this._mu.lock(function(){r._fs.realpath(t,e,function(t,e){r._mu.unlock(),n(t,e)})})},ji.prototype.realpathSync=function(t,e){if(this._mu.isLocked())throw new Error("invalid sync call");return this._fs.realpathSync(t,e)},ji.prototype.truncate=function(t,e,n){var r=this;this._mu.lock(function(){r._fs.truncate(t,e,function(t){r._mu.unlock(),n(t)})})},ji.prototype.truncateSync=function(t,e){if(this._mu.isLocked())throw new Error("invalid sync call");return this._fs.truncateSync(t,e)},ji.prototype.readFile=function(t,e,n,r){var i=this;this._mu.lock(function(){i._fs.readFile(t,e,n,function(t,e){i._mu.unlock(),r(t,e)})})},ji.prototype.readFileSync=function(t,e,n){if(this._mu.isLocked())throw new Error("invalid sync call");return this._fs.readFileSync(t,e,n)},ji.prototype.writeFile=function(t,e,n,r,i,o){var s=this;this._mu.lock(function(){s._fs.writeFile(t,e,n,r,i,function(t){s._mu.unlock(),o(t)})})},ji.prototype.writeFileSync=function(t,e,n,r,i){if(this._mu.isLocked())throw new Error("invalid sync call");return this._fs.writeFileSync(t,e,n,r,i)},ji.prototype.appendFile=function(t,e,n,r,i,o){var s=this;this._mu.lock(function(){s._fs.appendFile(t,e,n,r,i,function(t){s._mu.unlock(),o(t)})})},ji.prototype.appendFileSync=function(t,e,n,r,i){if(this._mu.isLocked())throw new Error("invalid sync call");return this._fs.appendFileSync(t,e,n,r,i)},ji.prototype.chmod=function(t,e,n,r){var i=this;this._mu.lock(function(){i._fs.chmod(t,e,n,function(t){i._mu.unlock(),r(t)})})},ji.prototype.chmodSync=function(t,e,n){if(this._mu.isLocked())throw new Error("invalid sync call");return this._fs.chmodSync(t,e,n)},ji.prototype.chown=function(t,e,n,r,i){var o=this;this._mu.lock(function(){o._fs.chown(t,e,n,r,function(t){o._mu.unlock(),i(t)})})},ji.prototype.chownSync=function(t,e,n,r){if(this._mu.isLocked())throw new Error("invalid sync call");return this._fs.chownSync(t,e,n,r)},ji.prototype.utimes=function(t,e,n,r){var i=this;this._mu.lock(function(){i._fs.utimes(t,e,n,function(t){i._mu.unlock(),r(t)})})},ji.prototype.utimesSync=function(t,e,n){if(this._mu.isLocked())throw new Error("invalid sync call");return this._fs.utimesSync(t,e,n)},ji.prototype.link=function(t,e,n){var r=this;this._mu.lock(function(){r._fs.link(t,e,function(t){r._mu.unlock(),n(t)})})},ji.prototype.linkSync=function(t,e){if(this._mu.isLocked())throw new Error("invalid sync call");return this._fs.linkSync(t,e)},ji.prototype.symlink=function(t,e,n,r){var i=this;this._mu.lock(function(){i._fs.symlink(t,e,n,function(t){i._mu.unlock(),r(t)})})},ji.prototype.symlinkSync=function(t,e,n){if(this._mu.isLocked())throw new Error("invalid sync call");return this._fs.symlinkSync(t,e,n)},ji.prototype.readlink=function(t,e){var n=this;this._mu.lock(function(){n._fs.readlink(t,function(t,r){n._mu.unlock(),e(t,r)})})},ji.prototype.readlinkSync=function(t){if(this._mu.isLocked())throw new Error("invalid sync call");return this._fs.readlinkSync(t)};var Bi="/.deletedFiles.log",zi=function(t){function e(e,n,r,i,o){t.call(this,e,n,r,i,o)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.sync=function(t){var e=this;return this.isDirty()?void this._fs._syncAsync(this,function(n){e.resetDirty(),t(n)}):void t(null)},e.prototype.syncSync=function(){this.isDirty()&&(this._fs._syncSync(this),this.resetDirty())},e.prototype.close=function(t){this.sync(t)},e.prototype.closeSync=function(){this.syncSync()},e}(Ye),qi=function(t){function e(e,n){if(t.call(this),this._isInitialized=!1,this._initializeCallbacks=[],this._deletedFiles={},this._deleteLog="",this._deleteLogUpdatePending=!1,this._deleteLogUpdateNeeded=!1,this._deleteLogError=null,this._writable=e,this._readable=n,this._writable.isReadOnly())throw new Fe(be.EINVAL,"Writable file system must be writable.")}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.isAvailable=function(){return!0},e.prototype.getOverlayedFileSystems=function(){return{readable:this._readable,writable:this._writable}},e.prototype._syncAsync=function(t,e){var n=this;this.createParentDirectoriesAsync(t.getPath(),function(r){return r?e(r):void n._writable.writeFile(t.getPath(),t.getBuffer(),null,Mt("w"),t.getStats().mode,e)})},e.prototype._syncSync=function(t){this.createParentDirectories(t.getPath()),this._writable.writeFileSync(t.getPath(),t.getBuffer(),null,Mt("w"),t.getStats().mode)},e.prototype.getName=function(){return Vi.Name},e.prototype.initialize=function(t){var e=this,n=this._initializeCallbacks,r=function(t){e._isInitialized=!t,e._initializeCallbacks=[],n.forEach(function(e){return e(t)})};return this._isInitialized?t():(n.push(t),void(1===n.length&&this._writable.readFile(Bi,"utf8",Mt("r"),function(t,n){if(t){if(t.errno!==be.ENOENT)return r(t)}else e._deleteLog=n;e._reparseDeletionLog(),r()})))},e.prototype.isReadOnly=function(){return!1},e.prototype.supportsSynch=function(){return this._readable.supportsSynch()&&this._writable.supportsSynch()},e.prototype.supportsLinks=function(){return!1},e.prototype.supportsProps=function(){return this._readable.supportsProps()&&this._writable.supportsProps()},e.prototype.getDeletionLog=function(){return this._deleteLog},e.prototype.restoreDeletionLog=function(t){this._deleteLog=t,this._reparseDeletionLog(),this.updateLog("")},e.prototype.rename=function(t,e,n){var r=this;if(this.checkInitAsync(n)&&!this.checkPathAsync(t,n)&&!this.checkPathAsync(e,n))return t===Bi||e===Bi?n(Fe.EPERM("Cannot rename deletion log.")):t===e?n():void this.stat(t,!1,function(i,o){return i?n(i):r.stat(e,!1,function(i,s){function a(r){var i=r.shift();if(!i)return n();var o=ke.resolve(t,i),s=ke.resolve(e,i);c.rename(o,s,function(t){return t?n(t):void a(r)})}var c=r,u=511;if(o.isDirectory()){if(i)return i.errno!==be.ENOENT?n(i):r._writable.exists(t,function(i){return i?r._writable.rename(t,e,n):void r._writable.mkdir(e,u,function(e){return e?n(e):void r._readable.readdir(t,function(t,e){return t?n():void a(e)})})});if(u=s.mode,!s.isDirectory())return n(Fe.ENOTDIR(e));r.readdir(e,function(i,o){return o&&o.length?n(Fe.ENOTEMPTY(e)):void r._readable.readdir(t,function(t,e){return t?n():void a(e)})})}return s&&s.isDirectory()?n(Fe.EISDIR(e)):void r.readFile(t,null,Mt("r"),function(i,s){return i?n(i):r.writeFile(e,s,null,Mt("w"),o.mode,function(e){return e?n(e):r.unlink(t,n)})})})})},e.prototype.renameSync=function(t,e){var n=this;if(this.checkInitialized(),this.checkPath(t),this.checkPath(e),t===Bi||e===Bi)throw Fe.EPERM("Cannot rename deletion log.");var r=this.statSync(t,!1);if(r.isDirectory()){if(t===e)return;var i=511;if(this.existsSync(e)){var o=this.statSync(e,!1);if(i=o.mode,!o.isDirectory())throw Fe.ENOTDIR(e);if(this.readdirSync(e).length>0)throw Fe.ENOTEMPTY(e)}this._writable.existsSync(t)?this._writable.renameSync(t,e):this._writable.existsSync(e)||this._writable.mkdirSync(e,i),this._readable.existsSync(t)&&this._readable.readdirSync(t).forEach(function(r){n.renameSync(ke.resolve(t,r),ke.resolve(e,r))})}else{if(this.existsSync(e)&&this.statSync(e,!1).isDirectory())throw Fe.EISDIR(e);this.writeFileSync(e,this.readFileSync(t,null,Mt("r")),null,Mt("w"),r.mode)}t!==e&&this.existsSync(t)&&this.unlinkSync(t)},e.prototype.stat=function(t,e,n){var r=this;this.checkInitAsync(n)&&this._writable.stat(t,e,function(i,o){i&&i.errno===be.ENOENT?(r._deletedFiles[t]&&n(Fe.ENOENT(t)),r._readable.stat(t,e,function(t,e){e&&(e=e.clone(),e.mode=Ut(e.mode)),n(t,e)})):n(i,o)})},e.prototype.statSync=function(t,e){this.checkInitialized();try{return this._writable.statSync(t,e)}catch(r){if(this._deletedFiles[t])throw Fe.ENOENT(t);var n=this._readable.statSync(t,e).clone();return n.mode=Ut(n.mode),n}},e.prototype.open=function(t,e,n,r){var i=this;this.checkInitAsync(r)&&!this.checkPathAsync(t,r)&&this.stat(t,!1,function(o,s){if(s)switch(e.pathExistsAction()){case Oe.TRUNCATE_FILE:return i.createParentDirectoriesAsync(t,function(o){return o?r(o):void i._writable.open(t,e,n,r)});case Oe.NOP:return i._writable.exists(t,function(o){o?i._writable.open(t,e,n,r):(s=s.clone(),s.mode=n,i._readable.readFile(t,null,Mt("r"),function(n,o){if(n)return r(n);s.size===-1&&(s.size=o.length);var a=new zi(i,t,e,s,o);r(null,a)}))});default:return r(Fe.EEXIST(t))}else switch(e.pathNotExistsAction()){case Oe.CREATE_FILE:return i.createParentDirectoriesAsync(t,function(o){return o?r(o):i._writable.open(t,e,n,r)});default:return r(Fe.ENOENT(t))}})},e.prototype.openSync=function(t,e,n){if(this.checkInitialized(),this.checkPath(t),t===Bi)throw Fe.EPERM("Cannot open deletion log.");if(this.existsSync(t))switch(e.pathExistsAction()){case Oe.TRUNCATE_FILE:return this.createParentDirectories(t),this._writable.openSync(t,e,n);case Oe.NOP:if(this._writable.existsSync(t))return this._writable.openSync(t,e,n);var r=this._readable.readFileSync(t,null,Mt("r")),i=this._readable.statSync(t,!1).clone();return i.mode=n,new zi(this,t,e,i,r);default:throw Fe.EEXIST(t)}else switch(e.pathNotExistsAction()){case Oe.CREATE_FILE:return this.createParentDirectories(t),this._writable.openSync(t,e,n);default:throw Fe.ENOENT(t)}},e.prototype.unlink=function(t,e){var n=this;this.checkInitAsync(e)&&!this.checkPathAsync(t,e)&&this.exists(t,function(r){return r?void n._writable.exists(t,function(r){return r?n._writable.unlink(t,function(r){return r?e(r):void n.exists(t,function(r){r&&n.deletePath(t),e(null)})}):(n.deletePath(t),void e(null))}):e(Fe.ENOENT(t))})},e.prototype.unlinkSync=function(t){if(this.checkInitialized(),this.checkPath(t),!this.existsSync(t))throw Fe.ENOENT(t);this._writable.existsSync(t)&&this._writable.unlinkSync(t),this.existsSync(t)&&this.deletePath(t)},e.prototype.rmdir=function(t,e){var n=this;if(this.checkInitAsync(e)){var r=function(){n.readdir(t,function(r,i){return r?e(r):i.length?e(Fe.ENOTEMPTY(t)):(n.deletePath(t),void e(null))})};this.exists(t,function(i){return i?void n._writable.exists(t,function(i){i?n._writable.rmdir(t,function(i){return i?e(i):void n._readable.exists(t,function(t){t?r():e()})}):r()}):e(Fe.ENOENT(t))})}},e.prototype.rmdirSync=function(t){if(this.checkInitialized(),!this.existsSync(t))throw Fe.ENOENT(t);if(this._writable.existsSync(t)&&this._writable.rmdirSync(t),this.existsSync(t)){if(this.readdirSync(t).length>0)throw Fe.ENOTEMPTY(t);this.deletePath(t)}},e.prototype.mkdir=function(t,e,n){var r=this;this.checkInitAsync(n)&&this.exists(t,function(i){return i?n(Fe.EEXIST(t)):void r.createParentDirectoriesAsync(t,function(i){return i?n(i):void r._writable.mkdir(t,e,n)})})},e.prototype.mkdirSync=function(t,e){if(this.checkInitialized(),this.existsSync(t))throw Fe.EEXIST(t);this.createParentDirectories(t),this._writable.mkdirSync(t,e)},e.prototype.readdir=function(t,e){var n=this;this.checkInitAsync(e)&&this.stat(t,!1,function(r,i){return r?e(r):i.isDirectory()?void n._writable.readdir(t,function(r,i){return r&&"ENOENT"!==r.code?e(r):(!r&&i||(i=[]),void n._readable.readdir(t,function(r,o){!r&&o||(o=[]);var s={},a=i.concat(o.filter(function(e){return!n._deletedFiles[t+"/"+e]})).filter(function(t){var e=!s[t];return s[t]=!0,e});e(null,a)}))}):e(Fe.ENOTDIR(t))})},e.prototype.readdirSync=function(t){var e=this;this.checkInitialized();var n=this.statSync(t,!1);if(!n.isDirectory())throw Fe.ENOTDIR(t);var r=[];try{r=r.concat(this._writable.readdirSync(t))}catch(t){}try{r=r.concat(this._readable.readdirSync(t).filter(function(n){return!e._deletedFiles[t+"/"+n]}))}catch(t){}var i={};return r.filter(function(t){var e=!i[t];return i[t]=!0,e})},e.prototype.exists=function(t,e){var n=this;this.checkInitialized(),this._writable.exists(t,function(r){return r?e(!0):void n._readable.exists(t,function(r){e(r&&n._deletedFiles[t]!==!0)})})},e.prototype.existsSync=function(t){return this.checkInitialized(),this._writable.existsSync(t)||this._readable.existsSync(t)&&this._deletedFiles[t]!==!0},e.prototype.chmod=function(t,e,n,r){var i=this;this.checkInitAsync(r)&&this.operateOnWritableAsync(t,function(o){return o?r(o):void i._writable.chmod(t,e,n,r)})},e.prototype.chmodSync=function(t,e,n){var r=this;this.checkInitialized(),this.operateOnWritable(t,function(){r._writable.chmodSync(t,e,n)})},e.prototype.chown=function(t,e,n,r,i){var o=this;this.checkInitAsync(i)&&this.operateOnWritableAsync(t,function(s){return s?i(s):void o._writable.chown(t,e,n,r,i)})},e.prototype.chownSync=function(t,e,n,r){var i=this;this.checkInitialized(),this.operateOnWritable(t,function(){i._writable.chownSync(t,e,n,r)})},e.prototype.utimes=function(t,e,n,r){var i=this;this.checkInitAsync(r)&&this.operateOnWritableAsync(t,function(o){return o?r(o):void i._writable.utimes(t,e,n,r)})},e.prototype.utimesSync=function(t,e,n){var r=this;this.checkInitialized(),this.operateOnWritable(t,function(){r._writable.utimesSync(t,e,n)})},e.prototype.deletePath=function(t){this._deletedFiles[t]=!0,this.updateLog("d"+t+"\n")},e.prototype.updateLog=function(t){var e=this;this._deleteLog+=t,this._deleteLogUpdatePending?this._deleteLogUpdateNeeded=!0:(this._deleteLogUpdatePending=!0,this._writable.writeFile(Bi,this._deleteLog,"utf8",Re.getFileFlag("w"),420,function(t){e._deleteLogUpdatePending=!1,t?e._deleteLogError=t:e._deleteLogUpdateNeeded&&(e._deleteLogUpdateNeeded=!1,e.updateLog(""))}))},e.prototype._reparseDeletionLog=function(){var t=this;this._deletedFiles={},this._deleteLog.split("\n").forEach(function(e){t._deletedFiles[e.slice(1)]="d"===e.slice(0,1)})},e.prototype.checkInitialized=function(){if(!this._isInitialized)throw new Fe(be.EPERM,"OverlayFS is not initialized. Please initialize OverlayFS using its initialize() method before using it.");if(null!==this._deleteLogError){var t=this._deleteLogError;throw this._deleteLogError=null,t}},e.prototype.checkInitAsync=function(t){if(!this._isInitialized)return t(new Fe(be.EPERM,"OverlayFS is not initialized. Please initialize OverlayFS using its initialize() method before using it.")),!1;if(null!==this._deleteLogError){var e=this._deleteLogError;return this._deleteLogError=null,t(e),!1}return!0},e.prototype.checkPath=function(t){if(t===Bi)throw Fe.EPERM(t)},e.prototype.checkPathAsync=function(t,e){return t===Bi&&(e(Fe.EPERM(t)),!0)},e.prototype.createParentDirectoriesAsync=function(t,e){function n(t,e){t?(o.push(i),i=ke.dirname(i),s._writable.stat(i,!1,n)):r()}function r(){if(!o.length)return e();var t=o.pop();s._readable.stat(t,!1,function(n,i){return i?void s._writable.mkdir(t,i.mode,function(t){return t?e(t):void r()}):e()})}var i=ke.dirname(t),o=[],s=this;this._writable.stat(i,!1,n)},e.prototype.createParentDirectories=function(t){for(var e=this,n=ke.dirname(t),r=[];!this._writable.existsSync(n);)r.push(n),n=ke.dirname(n);r=r.reverse(),r.forEach(function(t){e._writable.mkdirSync(t,e.statSync(t,!1).mode)})},e.prototype.operateOnWritable=function(t,e){if(!this.existsSync(t))throw Fe.ENOENT(t);this._writable.existsSync(t)||this.copyToWritable(t),e()},e.prototype.operateOnWritableAsync=function(t,e){var n=this;this.exists(t,function(r){return r?void n._writable.exists(t,function(r){return r?void e():n.copyToWritableAsync(t,e)}):e(Fe.ENOENT(t))})},e.prototype.copyToWritable=function(t){var e=this.statSync(t,!1);e.isDirectory()?this._writable.mkdirSync(t,e.mode):this.writeFileSync(t,this._readable.readFileSync(t,null,Mt("r")),null,Mt("w"),this.statSync(t,!1).mode)},e.prototype.copyToWritableAsync=function(t,e){var n=this;this.stat(t,!1,function(r,i){return r?e(r):i.isDirectory()?n._writable.mkdir(t,i.mode,e):void n._readable.readFile(t,null,Mt("r"),function(r,o){return r?e(r):void n.writeFile(t,o,null,Mt("w"),i.mode,e)})})},e}(We),Vi=function(t){function e(n,r,i){void 0===i&&(i=!0),t.call(this,new qi(n,r)),d(i,e.Name,{readable:"readable file system",writable:"writable file system"})}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.Create=function(t,n){try{var r=new e(t.writable,t.readable,!1);r.initialize(function(t){n(t,r)},!1)}catch(t){n(t)}},e.isAvailable=function(){return qi.isAvailable()},e.prototype.initialize=function(e,n){void 0===n&&(n=!0),n&&console.warn("[OverlayFS] OverlayFS.initialize() is deprecated and will be removed in the next major release. Please use 'OverlayFS.Create({readable: readable file system instance, writable: writable file system instance}, cb)' to create and initialize OverlayFS instances."),t.prototype.initialize.call(this,e)},e.prototype.getOverlayedFileSystems=function(){return t.prototype.getFSUnlocked.call(this).getOverlayedFileSystems()},e.prototype.unwrap=function(){return t.prototype.getFSUnlocked.call(this)},e}(ji);Vi.Name="OverlayFS",Vi.Options={writable:{type:"object",description:"The file system to write modified files to."},readable:{type:"object",description:"The file system that initially populates this file system."}};var Wi;!function(t){t[t.CB=0]="CB",t[t.FD=1]="FD",t[t.API_ERROR=2]="API_ERROR",t[t.STATS=3]="STATS",t[t.PROBE=4]="PROBE",t[t.FILEFLAG=5]="FILEFLAG",t[t.BUFFER=6]="BUFFER",t[t.ERROR=7]="ERROR"}(Wi||(Wi={}));var Hi=function(){this._callbacks={},this._nextId=0};Hi.prototype.toRemoteArg=function(t){var e=this._nextId++;return this._callbacks[e]=t,{type:Wi.CB,id:e}},Hi.prototype.toLocalArg=function(t){var e=this._callbacks[t];return delete this._callbacks[t],e};var Zi=function(){this._fileDescriptors={},this._nextId=0};Zi.prototype.toRemoteArg=function(e,n,r,i){var o,s,a=this._nextId++;this._fileDescriptors[a]=e,e.stat(function(c,u){c?i(c):(s=Yt(u.toBuffer()),r.isReadable()?e.read(t.alloc(u.size),0,u.size,0,function(t,e,c){t?i(t):(o=Yt(c),i(null,{type:Wi.FD,id:a,data:o,stat:s,path:n,flag:r.getFlagString()}))}):i(null,{type:Wi.FD,id:a,data:new ArrayBuffer(0),stat:s,path:n,flag:r.getFlagString()}))})},Zi.prototype.applyFdAPIRequest=function(t,e){var n=this,r=t.args[0];this._applyFdChanges(r,function(i,o){i?e(i):o[t.method](function(i){"close"===t.method&&delete n._fileDescriptors[r.id],e(i)})})},Zi.prototype._applyFdChanges=function(t,e){var n=this._fileDescriptors[t.id],r=Xt(t.data),i=Te.fromBuffer(Xt(t.stat)),o=Re.getFileFlag(t.flag);o.isWriteable()?n.write(r,0,r.length,o.isAppendable()?n.getPos():0,function(t){function s(){n.stat(function(t,r){t?e(t):r.mode!==i.mode?n.chmod(i.mode,function(t){e(t,n)}):e(t,n)})}t?e(t):o.isAppendable()?s():n.truncate(r.length,function(){s()})}):e(null,n)};var Yi=function(t){function e(e,n,r,i,o,s){t.call(this,e,n,r,i,s),this._remoteFdId=o}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.getRemoteFdId=function(){return this._remoteFdId},e.prototype.toRemoteArg=function(){return{type:Wi.FD,id:this._remoteFdId,data:Yt(this.getBuffer()),stat:Yt(this.getStats().toBuffer()),path:this.getPath(),flag:this.getFlag().getFlagString()}},e.prototype.sync=function(t){this._syncClose("sync",t)},e.prototype.close=function(t){this._syncClose("close",t)},e.prototype._syncClose=function(t,e){var n=this;this.isDirty()?this._fs.syncClose(t,this,function(t){t||n.resetDirty(),e(t)}):e()},e}(Ye),Xi=function(e){function n(t,r){var i=this;void 0===r&&(r=!0),e.call(this),this._callbackConverter=new Hi,this._isInitialized=!1,this._isReadOnly=!1,this._supportLinks=!1,this._supportProps=!1,this._worker=t,d(r,n.Name,{worker:"Web Worker instance"}),this._worker.addEventListener("message",function(t){var e=t.data;if(Qt(e)){var n,r=e.args,o=new Array(r.length);for(n=0;n0&&(u=-1,s={browserfsMessage:!0,cbId:o,args:[jt(t)]},e.postMessage(s))}var i,s,a=arguments,c=new Array(arguments.length),u=arguments.length;for(i=0;i0;){var i=void 0,o=r.pop(),s=o[0],a=o[1],c=o[2];for(var u in a)if(a.hasOwnProperty(u)){var f=a[u],h=s+"/"+u;f?(e._index[h]=i=new $i,r.push([h,f,i])):i=new Qi(new Te(Le.FILE,-1,365)),c&&(c._ls[u]=i)}}return e},Gi.prototype.fileIterator=function(t){var e=this;for(var n in e._index)if(e._index.hasOwnProperty(n))for(var r=e._index[n],i=r.getListing(),o=0,s=i;o0&&"/"!==r.charAt(r.length-1)&&(r+="/"),this.prefixUrl=r;var o=null;if("string"==typeof n){if(o=this._requestFileSync(n,"json"),!o)throw new Error("Unable to find listing at URL: ${listingUrlOrObj}")}else o=n;d(i,e.Name,{index:"string"==typeof n?n:"file index as an object",baseUrl:r}),this._index=Gi.fromListing(o)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.Create=function(t,n){void 0===t.index&&(t.index="index.json"),"string"==typeof t.index?e.FromURL(t.index,n,t.baseUrl,!1):n(null,new e(t.index,t.baseUrl,!1))},e.isAvailable=function(){return"undefined"!=typeof XMLHttpRequest&&null!==XMLHttpRequest},e.FromURL=function(t,n,r,i){void 0===r&&(r=t.slice(0,t.lastIndexOf("/")+1)),void 0===i&&(i=!0),i&&console.warn("[XmlHttpRequest] XmlHttpRequest.FromURL() is deprecated and will be removed in the next major release. Please use 'XmlHttpRequest.Create({ index: \""+t+'", baseUrl: "'+r+"\" }, cb)' instead."),Ki(t,"json",function(t,i){t?n(t):n(null,new e(i,r,!1))})},e.prototype.empty=function(){this._index.fileIterator(function(t){t.fileData=null})},e.prototype.getName=function(){return e.Name},e.prototype.diskSpace=function(t,e){e(0,0)},e.prototype.isReadOnly=function(){return!0},e.prototype.supportsLinks=function(){return!1},e.prototype.supportsProps=function(){return!1},e.prototype.supportsSynch=function(){return!0},e.prototype.preloadFile=function(t,e){var n=this._index.getInode(t);if(!oe(n))throw Fe.EISDIR(t);if(null===n)throw Fe.ENOENT(t);var r=n.getData();r.size=e.length,r.fileData=e},e.prototype.stat=function(t,e,n){var r=this._index.getInode(t);if(null===r)return n(Fe.ENOENT(t));var i;oe(r)?(i=r.getData(),i.size<0?this._requestFileSizeAsync(t,function(t,e){return t?n(t):(i.size=e,void n(null,i.clone()))}):n(null,i.clone())):se(r)?(i=r.getStats(),n(null,i)):n(Fe.FileError(be.EINVAL,t))},e.prototype.statSync=function(t,e){var n=this._index.getInode(t);if(null===n)throw Fe.ENOENT(t);var r;if(oe(n))r=n.getData(),r.size<0&&(r.size=this._requestFileSizeSync(t));else{if(!se(n))throw Fe.FileError(be.EINVAL,t);r=n.getStats()}return r},e.prototype.open=function(t,e,n,r){if(e.isWriteable())return r(new Fe(be.EPERM,t));var i=this,o=this._index.getInode(t);if(null===o)return r(Fe.ENOENT(t));if(!oe(o))return r(Fe.EISDIR(t));var s=o.getData();switch(e.pathExistsAction()){case Oe.THROW_EXCEPTION:case Oe.TRUNCATE_FILE:return r(Fe.EEXIST(t));case Oe.NOP:if(s.fileData)return r(null,new Xe(i,t,e,s.clone(),s.fileData));this._requestFileAsync(t,"buffer",function(n,o){return n?r(n):(s.size=o.length,s.fileData=o,r(null,new Xe(i,t,e,s.clone(),o)))});break;default:return r(new Fe(be.EINVAL,"Invalid FileMode object."))}},e.prototype.openSync=function(t,e,n){if(e.isWriteable())throw new Fe(be.EPERM,t);var r=this._index.getInode(t);if(null===r)throw Fe.ENOENT(t);if(!oe(r))throw Fe.EISDIR(t);var i=r.getData();switch(e.pathExistsAction()){case Oe.THROW_EXCEPTION:case Oe.TRUNCATE_FILE:throw Fe.EEXIST(t);case Oe.NOP:if(i.fileData)return new Xe(this,t,e,i.clone(),i.fileData);var o=this._requestFileSync(t,"buffer");return i.size=o.length,i.fileData=o,new Xe(this,t,e,i.clone(),o);default:throw new Fe(be.EINVAL,"Invalid FileMode object.")}},e.prototype.readdir=function(t,e){try{e(null,this.readdirSync(t))}catch(t){e(t)}},e.prototype.readdirSync=function(t){var e=this._index.getInode(t);if(null===e)throw Fe.ENOENT(t);if(se(e))return e.getListing();throw Fe.ENOTDIR(t)},e.prototype.readFile=function(t,e,n,r){var i=r;this.open(t,n,420,function(t,n){if(t)return r(t);r=function(t,e){n.close(function(n){return t||(t=n),i(t,e)})};var o=n,s=o.getBuffer();null===e?r(t,b(s)):ae(s,e,r)})},e.prototype.readFileSync=function(t,e,n){var r=this.openSync(t,n,420);try{var i=r,o=i.getBuffer();return null===e?b(o):o.toString(e)}finally{r.closeSync()}},e.prototype.getXhrPath=function(t){return"/"===t.charAt(0)&&(t=t.slice(1)),this.prefixUrl+t},e.prototype._requestFileAsync=function(t,e,n){Ki(this.getXhrPath(t),e,n)},e.prototype._requestFileSync=function(t,e){return Ji(this.getXhrPath(t),e)},e.prototype._requestFileSizeAsync=function(t,e){ie(this.getXhrPath(t),e)},e.prototype._requestFileSizeSync=function(t){return re(this.getXhrPath(t))},e}(We);to.Name="XmlHttpRequest",to.Options={index:{type:["string","object"],optional:!0,description:"URL to a file index as a JSON file or the file index object itself, generated with the make_xhrfs_index script. Defaults to `index.json`."},baseUrl:{type:"string",optional:!0,description:"Used as the URL prefix for fetched files. Default: Fetch files relative to the index."}};var eo=function(){};eo.str2byte=function(t,e){for(var n=t.length>e.length?e.length:t.length,r=0;r127){var o=eo.extendedChars.indexOf(t.charAt(r));o>-1&&(i=o+128)}e[i]=r}return n},eo.byte2str=function(t){for(var e=new Array(t.length),n=0;n127?e[n]=eo.extendedChars[r-128]:e[n]=String.fromCharCode(r)}return e.join("")},eo.byteLength=function(t){return t.length},eo.extendedChars=["Ç","ü","é","â","ä","à","å","ç","ê","ë","è","ï","î","ì","Ä","Å","É","æ","Æ","ô","ö","ò","û","ù","ÿ","Ö","Ü","ø","£","Ø","×","ƒ","á","í","ó","ú","ñ","Ñ","ª","º","¿","®","¬","½","¼","¡","«","»","_","_","_","¦","¦","Á","Â","À","©","¦","¦","+","+","¢","¥","+","+","-","-","+","-","+","ã","Ã","+","+","-","-","¦","-","+","¤","ð","Ð","Ê","Ë","È","i","Í","Î","Ï","+","+","_","_","¦","Ì","_","Ó","ß","Ô","Ò","õ","Õ","µ","þ","Þ","Ú","Û","Ù","ý","Ý","¯","´","­","±","_","¾","¶","§","÷","¸","°","¨","·","¹","³","²","_"," "];var no,ro=n(23).inflateRaw,io={};!function(t){t[t.MSDOS=0]="MSDOS",t[t.AMIGA=1]="AMIGA",t[t.OPENVMS=2]="OPENVMS",t[t.UNIX=3]="UNIX",t[t.VM_CMS=4]="VM_CMS",t[t.ATARI_ST=5]="ATARI_ST",t[t.OS2_HPFS=6]="OS2_HPFS",t[t.MAC=7]="MAC",t[t.Z_SYSTEM=8]="Z_SYSTEM",t[t.CP_M=9]="CP_M",t[t.NTFS=10]="NTFS",t[t.MVS=11]="MVS",t[t.VSE=12]="VSE",t[t.ACORN_RISC=13]="ACORN_RISC",t[t.VFAT=14]="VFAT",t[t.ALT_MVS=15]="ALT_MVS",t[t.BEOS=16]="BEOS",t[t.TANDEM=17]="TANDEM",t[t.OS_400=18]="OS_400",t[t.OSX=19]="OSX"}(no||(no={}));var oo;!function(t){t[t.STORED=0]="STORED",t[t.SHRUNK=1]="SHRUNK",t[t.REDUCED_1=2]="REDUCED_1",t[t.REDUCED_2=3]="REDUCED_2",t[t.REDUCED_3=4]="REDUCED_3",t[t.REDUCED_4=5]="REDUCED_4",t[t.IMPLODE=6]="IMPLODE",t[t.DEFLATE=8]="DEFLATE",t[t.DEFLATE64=9]="DEFLATE64",t[t.TERSE_OLD=10]="TERSE_OLD",t[t.BZIP2=12]="BZIP2",t[t.LZMA=14]="LZMA",t[t.TERSE_NEW=18]="TERSE_NEW",t[t.LZ77=19]="LZ77",t[t.WAVPACK=97]="WAVPACK",t[t.PPMD=98]="PPMD"}(oo||(oo={}));var so=function(t){if(this.data=t,67324752!==t.readUInt32LE(0))throw new Fe(be.EINVAL,"Invalid Zip file: Local file header has invalid signature: "+this.data.readUInt32LE(0))};so.prototype.versionNeeded=function(){return this.data.readUInt16LE(4)},so.prototype.flags=function(){return this.data.readUInt16LE(6)},so.prototype.compressionMethod=function(){return this.data.readUInt16LE(8)},so.prototype.lastModFileTime=function(){return ce(this.data.readUInt16LE(10),this.data.readUInt16LE(12))},so.prototype.rawLastModFileTime=function(){return this.data.readUInt32LE(10)},so.prototype.crc32=function(){return this.data.readUInt32LE(14)},so.prototype.fileNameLength=function(){return this.data.readUInt16LE(26)},so.prototype.extraFieldLength=function(){return this.data.readUInt16LE(28)},so.prototype.fileName=function(){return ue(this.data,this.useUTF8(),30,this.fileNameLength())},so.prototype.extraField=function(){var t=30+this.fileNameLength();return this.data.slice(t,t+this.extraFieldLength())},so.prototype.totalSize=function(){return 30+this.fileNameLength()+this.extraFieldLength()},so.prototype.useUTF8=function(){return 2048===(2048&this.flags())};var ao=function(t,e,n){this.header=t,this.record=e,this.data=n};ao.prototype.decompress=function(){var t=this.header.compressionMethod(),e=io[t];if(e)return e(this.data,this.record.compressedSize(),this.record.uncompressedSize(),this.record.flag());var n=oo[t];throw n||(n="Unknown: "+t),new Fe(be.EINVAL,"Invalid compression method on file '"+this.header.fileName()+"': "+n)},ao.prototype.getHeader=function(){return this.header},ao.prototype.getRecord=function(){return this.record},ao.prototype.getRawData=function(){return this.data};var co=function(t){this.data=t};co.prototype.crc32=function(){return this.data.readUInt32LE(0)},co.prototype.compressedSize=function(){return this.data.readUInt32LE(4)},co.prototype.uncompressedSize=function(){return this.data.readUInt32LE(8)};var uo=function(t){if(this.data=t,134630224!==this.data.readUInt32LE(0))throw new Fe(be.EINVAL,"Invalid archive extra data record signature: "+this.data.readUInt32LE(0))};uo.prototype.length=function(){return this.data.readUInt32LE(4)},uo.prototype.extraFieldData=function(){return this.data.slice(8,8+this.length())};var fo=function(t){if(this.data=t,84233040!==this.data.readUInt32LE(0))throw new Fe(be.EINVAL,"Invalid digital signature signature: "+this.data.readUInt32LE(0))};fo.prototype.size=function(){return this.data.readUInt16LE(4)},fo.prototype.signatureData=function(){return this.data.slice(6,6+this.size())};var ho=function(t,e){if(this.zipData=t,this.data=e,33639248!==this.data.readUInt32LE(0))throw new Fe(be.EINVAL,"Invalid Zip file: Central directory record has invalid signature: "+this.data.readUInt32LE(0));this._filename=this.produceFilename()};ho.prototype.versionMadeBy=function(){return this.data.readUInt16LE(4)},ho.prototype.versionNeeded=function(){return this.data.readUInt16LE(6)},ho.prototype.flag=function(){return this.data.readUInt16LE(8)},ho.prototype.compressionMethod=function(){return this.data.readUInt16LE(10)},ho.prototype.lastModFileTime=function(){return ce(this.data.readUInt16LE(12),this.data.readUInt16LE(14))},ho.prototype.rawLastModFileTime=function(){return this.data.readUInt32LE(12)},ho.prototype.crc32=function(){return this.data.readUInt32LE(16)},ho.prototype.compressedSize=function(){return this.data.readUInt32LE(20)},ho.prototype.uncompressedSize=function(){return this.data.readUInt32LE(24)},ho.prototype.fileNameLength=function(){return this.data.readUInt16LE(28)},ho.prototype.extraFieldLength=function(){return this.data.readUInt16LE(30)},ho.prototype.fileCommentLength=function(){return this.data.readUInt16LE(32)},ho.prototype.diskNumberStart=function(){return this.data.readUInt16LE(34)},ho.prototype.internalAttributes=function(){return this.data.readUInt16LE(36)},ho.prototype.externalAttributes=function(){return this.data.readUInt32LE(38)},ho.prototype.headerRelativeOffset=function(){return this.data.readUInt32LE(42)},ho.prototype.produceFilename=function(){var t=ue(this.data,this.useUTF8(),46,this.fileNameLength());return t.replace(/\\/g,"/")},ho.prototype.fileName=function(){return this._filename},ho.prototype.rawFileName=function(){return this.data.slice(46,46+this.fileNameLength())},ho.prototype.extraField=function(){var t=44+this.fileNameLength();return this.data.slice(t,t+this.extraFieldLength())},ho.prototype.fileComment=function(){var t=46+this.fileNameLength()+this.extraFieldLength();return ue(this.data,this.useUTF8(),t,this.fileCommentLength())},ho.prototype.rawFileComment=function(){var t=46+this.fileNameLength()+this.extraFieldLength();return this.data.slice(t,t+this.fileCommentLength())},ho.prototype.totalSize=function(){return 46+this.fileNameLength()+this.extraFieldLength()+this.fileCommentLength()},ho.prototype.isDirectory=function(){var t=this.fileName();return!!(16&this.externalAttributes())||"/"===t.charAt(t.length-1)},ho.prototype.isFile=function(){return!this.isDirectory()},ho.prototype.useUTF8=function(){return 2048===(2048&this.flag())},ho.prototype.isEncrypted=function(){return 1===(1&this.flag())},ho.prototype.getFileData=function(){var t=this.headerRelativeOffset(),e=new so(this.zipData.slice(t));return new ao(e,this,this.zipData.slice(t+e.totalSize()))},ho.prototype.getData=function(){return this.getFileData().decompress()},ho.prototype.getRawData=function(){return this.getFileData().getRawData()},ho.prototype.getStats=function(){return new Te(Le.FILE,this.uncompressedSize(),365,new Date,this.lastModFileTime())};var po=function(t){if(this.data=t,101010256!==this.data.readUInt32LE(0))throw new Fe(be.EINVAL,"Invalid Zip file: End of central directory record has invalid signature: "+this.data.readUInt32LE(0))};po.prototype.diskNumber=function(){return this.data.readUInt16LE(4)},po.prototype.cdDiskNumber=function(){return this.data.readUInt16LE(6)},po.prototype.cdDiskEntryCount=function(){return this.data.readUInt16LE(8)},po.prototype.cdTotalEntryCount=function(){return this.data.readUInt16LE(10)},po.prototype.cdSize=function(){return this.data.readUInt32LE(12)},po.prototype.cdOffset=function(){return this.data.readUInt32LE(16)},po.prototype.cdZipCommentLength=function(){return this.data.readUInt16LE(20)},po.prototype.cdZipComment=function(){return ue(this.data,!0,22,this.cdZipCommentLength())},po.prototype.rawCdZipComment=function(){return this.data.slice(22,22+this.cdZipCommentLength())};var lo=function(t,e,n,r){this.index=t,this.directoryEntries=e,this.eocd=n,this.data=r},yo=function(t){function e(n,r,i){void 0===r&&(r=""),void 0===i&&(i=!0),t.call(this),this.name=r,this._index=new Gi,this._directoryEntries=[],this._eocd=null,d(i,e.Name,{zipData:"zip data as a Buffer",name:r}),n instanceof lo?(this._index=n.index,this._directoryEntries=n.directoryEntries,this._eocd=n.eocd,this.data=n.data):(this.data=n,this.populateIndex())}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.Create=function(t,n){try{e.computeIndex(t.zipData,function(r){var i=new e(r,t.name,!1);n(null,i)},!1)}catch(t){n(t)}},e.isAvailable=function(){return!0},e.RegisterDecompressionMethod=function(t,e){io[t]=e},e.computeIndex=function(t,n,r){void 0===r&&(r=!0),r&&console.warn("[ZipFS] ZipFS.computeIndex is now deprecated, and will be removed in the next major release. Please update your code to use 'ZipFS.Create({ zipData: zip file as a Buffer}, cb)' instead.");var i=new Gi,o=e.getEOCD(t);if(o.diskNumber()!==o.cdDiskNumber())throw new Fe(be.EINVAL,"ZipFS does not support spanned zip files.");var s=o.cdOffset();if(4294967295===s)throw new Fe(be.EINVAL,"ZipFS does not support Zip64.");var a=s+o.cdSize();e.computeIndexResponsive(t,i,s,a,n,[],o)},e.getEOCD=function(t){for(var e=22,n=Math.min(e+65535,t.length-1),r=e;r-1},Eo.prototype.getRockRidgeOffset=function(){return this._rockRidgeOffset},Eo.prototype.rootCheckForRockRidge=function(t){var e=this.getDirectory(t);this._rockRidgeOffset=e.getDotEntry(t)._getRockRidgeOffset(t),this._rockRidgeOffset>-1&&(this._fileOrDir=null)},Eo.prototype.length=function(){return this._data[0]},Eo.prototype.extendedAttributeRecordLength=function(){return this._data[1]},Eo.prototype.lba=function(){return 2048*this._data.readUInt32LE(2)},Eo.prototype.dataLength=function(){return this._data.readUInt32LE(10)},Eo.prototype.recordingDate=function(){return le(this._data,18)},Eo.prototype.fileFlags=function(){return this._data[25]},Eo.prototype.fileUnitSize=function(){return this._data[26]},Eo.prototype.interleaveGapSize=function(){return this._data[27]},Eo.prototype.volumeSequenceNumber=function(){return this._data.readUInt16LE(28)},Eo.prototype.identifier=function(){return this._getString(33,this._data[32])},Eo.prototype.fileName=function(t){if(this.hasRockRidge()){var e=this._rockRidgeFilename(t);if(null!==e)return e}var n=this.identifier();if(this.isDirectory(t))return n;var r=n.indexOf(";");return r===-1?n:"."===n[r-1]?n.slice(0,r-1):n.slice(0,r)},Eo.prototype.isDirectory=function(t){var e=!!(2&this.fileFlags());return!e&&this.hasRockRidge()&&(e=this.getSUEntries(t).filter(function(t){return t instanceof Uo}).length>0),e},Eo.prototype.isSymlink=function(t){return this.hasRockRidge()&&this.getSUEntries(t).filter(function(t){return t instanceof Do}).length>0},Eo.prototype.getSymlinkPath=function(t){for(var e="",n=this.getSUEntries(t),r=this._getGetString(),i=0,o=n;i1&&"/"===e[e.length-1]?e.slice(0,e.length-1):e},Eo.prototype.getFile=function(t){if(this.isDirectory(t))throw new Error("Tried to get a File from a directory.");return null===this._fileOrDir&&(this._fileOrDir=t.slice(this.lba(),this.lba()+this.dataLength())),this._fileOrDir},Eo.prototype.getDirectory=function(t){if(!this.isDirectory(t))throw new Error("Tried to get a Directory from a file.");return null===this._fileOrDir&&(this._fileOrDir=this._constructDirectory(t)),this._fileOrDir},Eo.prototype.getSUEntries=function(t){return this._suEntries||this._constructSUEntries(t),this._suEntries},Eo.prototype._rockRidgeFilename=function(t){var e=this.getSUEntries(t).filter(function(t){return t instanceof Co});if(0===e.length||6&e[0].flags())return null;for(var n="",r=this._getGetString(),i=0,o=e;i0){var n=e[0];if(n instanceof Fo&&n.checkBytesPass())for(var r=1;r - * @license MIT - */ -"use strict";function r(){try{var t=new Uint8Array(1);return t.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===t.foo()}catch(t){return!1}}function i(e){if(e>J)throw new RangeError("Invalid typed array length");var n=new Uint8Array(e);return n.__proto__=t.prototype,n}function t(t,e,n){if("number"==typeof t){if("string"==typeof e)throw new Error("If encoding is specified then the first argument must be a string");return c(t)}return o(t,e,n)}function o(t,e,n){if("number"==typeof t)throw new TypeError('"value" argument must not be a number');return H(t)?h(t,e,n):"string"==typeof t?u(t,e):p(t)}function s(t){if("number"!=typeof t)throw new TypeError('"size" argument must be a number');if(t<0)throw new RangeError('"size" argument must not be negative')}function a(t,e,n){return s(t),t<=0?i(t):void 0!==e?"string"==typeof n?i(t).fill(e,n):i(t).fill(e):i(t)}function c(t){return s(t),i(t<0?0:0|l(t))}function u(e,n){if("string"==typeof n&&""!==n||(n="utf8"),!t.isEncoding(n))throw new TypeError('"encoding" must be a valid string encoding');var r=0|y(e,n),o=i(r),s=o.write(e,n);return s!==r&&(o=o.slice(0,s)),o}function f(t){for(var e=t.length<0?0:0|l(t.length),n=i(e),r=0;r=J)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+J.toString(16)+" bytes");return 0|t}function d(e){return+e!=e&&(e=0),t.alloc(+e)}function y(e,n){if(t.isBuffer(e))return e.length;if(Z(e)||H(e))return e.byteLength;"string"!=typeof e&&(e=""+e);var r=e.length;if(0===r)return 0;for(var i=!1;;)switch(n){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":case void 0:return B(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return V(e).length;default:if(i)return B(e).length;n=(""+n).toLowerCase(),i=!0}}function g(t,e,n){var r=!1;if((void 0===e||e<0)&&(e=0),e>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if(n>>>=0,e>>>=0,n<=e)return"";for(t||(t="utf8");;)switch(t){case"hex":return T(this,e,n);case"utf8":case"utf-8":return F(this,e,n);case"ascii":return R(this,e,n);case"latin1":case"binary":return L(this,e,n);case"base64":return O(this,e,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return x(this,e,n);default:if(r)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),r=!0}}function v(t,e,n){var r=t[e];t[e]=t[n],t[n]=r}function m(e,n,r,i,o){if(0===e.length)return-1;if("string"==typeof r?(i=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,Y(r)&&(r=o?0:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(o)return-1;r=e.length-1}else if(r<0){if(!o)return-1;r=0}if("string"==typeof n&&(n=t.from(n,i)),t.isBuffer(n))return 0===n.length?-1:_(e,n,r,i,o);if("number"==typeof n)return n&=255,"function"==typeof Uint8Array.prototype.indexOf?o?Uint8Array.prototype.indexOf.call(e,n,r):Uint8Array.prototype.lastIndexOf.call(e,n,r):_(e,[n],r,i,o);throw new TypeError("val must be string, number or Buffer")}function _(t,e,n,r,i){function o(t,e){return 1===s?t[e]:t.readUInt16BE(e*s)}var s=1,a=t.length,c=e.length;if(void 0!==r&&(r=String(r).toLowerCase(),"ucs2"===r||"ucs-2"===r||"utf16le"===r||"utf-16le"===r)){if(t.length<2||e.length<2)return-1;s=2,a/=2,c/=2,n/=2}var u;if(i){var f=-1;for(u=n;ua&&(n=a-c),u=n;u>=0;u--){for(var h=!0,p=0;pi&&(r=i)):r=i;var o=e.length;if(o%2!==0)throw new TypeError("Invalid hex string");r>o/2&&(r=o/2);for(var s=0;s239?4:o>223?3:o>191?2:1;if(i+a<=n){var c,u,f,h;switch(a){case 1:o<128&&(s=o);break;case 2:c=t[i+1],128===(192&c)&&(h=(31&o)<<6|63&c,h>127&&(s=h));break;case 3:c=t[i+1],u=t[i+2],128===(192&c)&&128===(192&u)&&(h=(15&o)<<12|(63&c)<<6|63&u,h>2047&&(h<55296||h>57343)&&(s=h));break;case 4:c=t[i+1],u=t[i+2],f=t[i+3],128===(192&c)&&128===(192&u)&&128===(192&f)&&(h=(15&o)<<18|(63&c)<<12|(63&u)<<6|63&f,h>65535&&h<1114112&&(s=h))}}null===s?(s=65533,a=1):s>65535&&(s-=65536,r.push(s>>>10&1023|55296),s=56320|1023&s),r.push(s),i+=a}return N(r)}function N(t){var e=t.length;if(e<=G)return String.fromCharCode.apply(String,t);for(var n="",r=0;rr)&&(n=r);for(var i="",o=e;on)throw new RangeError("Trying to access beyond buffer length")}function D(e,n,r,i,o,s){if(!t.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(n>o||ne.length)throw new RangeError("Index out of range")}function P(t,e,n,r,i,o){if(n+r>t.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function C(t,e,n,r,i){return e=+e,n>>>=0,i||P(t,e,n,4,3.4028234663852886e38,-3.4028234663852886e38),K.write(t,e,n,r,23,4),n+4}function U(t,e,n,r,i){return e=+e,n>>>=0,i||P(t,e,n,8,1.7976931348623157e308,-1.7976931348623157e308),K.write(t,e,n,r,52,8),n+8}function M(t){if(t=t.trim().replace(Q,""),t.length<2)return"";for(;t.length%4!==0;)t+="=";return t}function j(t){return t<16?"0"+t.toString(16):t.toString(16)}function B(t,e){e=e||1/0;for(var n,r=t.length,i=null,o=[],s=0;s55295&&n<57344){if(!i){if(n>56319){(e-=3)>-1&&o.push(239,191,189);continue}if(s+1===r){(e-=3)>-1&&o.push(239,191,189);continue}i=n;continue}if(n<56320){(e-=3)>-1&&o.push(239,191,189),i=n;continue}n=(i-55296<<10|n-56320)+65536}else i&&(e-=3)>-1&&o.push(239,191,189);if(i=null,n<128){if((e-=1)<0)break;o.push(n)}else if(n<2048){if((e-=2)<0)break;o.push(n>>6|192,63&n|128)}else if(n<65536){if((e-=3)<0)break;o.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((e-=4)<0)break;o.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return o}function z(t){for(var e=[],n=0;n>8,i=n%256,o.push(i),o.push(r);return o}function V(t){return X.toByteArray(M(t))}function W(t,e,n,r){for(var i=0;i=e.length||i>=t.length);++i)e[i+n]=t[i];return i}function H(t){return t instanceof ArrayBuffer||null!=t&&null!=t.constructor&&"ArrayBuffer"===t.constructor.name&&"number"==typeof t.byteLength}function Z(t){return"function"==typeof ArrayBuffer.isView&&ArrayBuffer.isView(t)}function Y(t){return t!==t}var X=n(18),K=n(21);e.Buffer=t,e.SlowBuffer=d,e.INSPECT_MAX_BYTES=50;var J=2147483647;e.kMaxLength=J,t.TYPED_ARRAY_SUPPORT=r(),t.TYPED_ARRAY_SUPPORT||"undefined"==typeof console||"function"!=typeof console.error||console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."),"undefined"!=typeof Symbol&&Symbol.species&&t[Symbol.species]===t&&Object.defineProperty(t,Symbol.species,{value:null,configurable:!0,enumerable:!1,writable:!1}),t.poolSize=8192,t.from=function(t,e,n){return o(t,e,n)},t.prototype.__proto__=Uint8Array.prototype,t.__proto__=Uint8Array,t.alloc=function(t,e,n){return a(t,e,n)},t.allocUnsafe=function(t){return c(t)},t.allocUnsafeSlow=function(t){return c(t)},t.isBuffer=function(t){return null!=t&&t._isBuffer===!0},t.compare=function(e,n){if(!t.isBuffer(e)||!t.isBuffer(n))throw new TypeError("Arguments must be Buffers");if(e===n)return 0;for(var r=e.length,i=n.length,o=0,s=Math.min(r,i);o0&&(t=this.toString("hex",0,n).match(/.{2}/g).join(" "),this.length>n&&(t+=" ... ")),""},t.prototype.compare=function(e,n,r,i,o){if(!t.isBuffer(e))throw new TypeError("Argument must be a Buffer");if(void 0===n&&(n=0),void 0===r&&(r=e?e.length:0),void 0===i&&(i=0),void 0===o&&(o=this.length),n<0||r>e.length||i<0||o>this.length)throw new RangeError("out of range index");if(i>=o&&n>=r)return 0;if(i>=o)return-1;if(n>=r)return 1;if(n>>>=0,r>>>=0,i>>>=0,o>>>=0,this===e)return 0;for(var s=o-i,a=r-n,c=Math.min(s,a),u=this.slice(i,o),f=e.slice(n,r),h=0;h>>=0,isFinite(n)?(n>>>=0,void 0===r&&(r="utf8")):(r=n,n=void 0)}var i=this.length-e;if((void 0===n||n>i)&&(n=i),t.length>0&&(n<0||e<0)||e>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");for(var o=!1;;)switch(r){case"hex":return w(this,t,e,n);case"utf8":case"utf-8":return E(this,t,e,n);case"ascii":return b(this,t,e,n);case"latin1":case"binary":return S(this,t,e,n);case"base64":return k(this,t,e,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return I(this,t,e,n);default:if(o)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),o=!0}},t.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var G=4096;t.prototype.slice=function(e,n){var r=this.length;e=~~e,n=void 0===n?r:~~n,e<0?(e+=r,e<0&&(e=0)):e>r&&(e=r),n<0?(n+=r,n<0&&(n=0)):n>r&&(n=r),n>>=0,e>>>=0,n||A(t,e,this.length);for(var r=this[t],i=1,o=0;++o>>=0,e>>>=0,n||A(t,e,this.length);for(var r=this[t+--e],i=1;e>0&&(i*=256);)r+=this[t+--e]*i;return r},t.prototype.readUInt8=function(t,e){return t>>>=0,e||A(t,1,this.length),this[t]},t.prototype.readUInt16LE=function(t,e){return t>>>=0,e||A(t,2,this.length),this[t]|this[t+1]<<8},t.prototype.readUInt16BE=function(t,e){return t>>>=0,e||A(t,2,this.length),this[t]<<8|this[t+1]},t.prototype.readUInt32LE=function(t,e){return t>>>=0,e||A(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},t.prototype.readUInt32BE=function(t,e){return t>>>=0,e||A(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},t.prototype.readIntLE=function(t,e,n){t>>>=0,e>>>=0,n||A(t,e,this.length);for(var r=this[t],i=1,o=0;++o=i&&(r-=Math.pow(2,8*e)),r},t.prototype.readIntBE=function(t,e,n){t>>>=0,e>>>=0,n||A(t,e,this.length);for(var r=e,i=1,o=this[t+--r];r>0&&(i*=256);)o+=this[t+--r]*i;return i*=128,o>=i&&(o-=Math.pow(2,8*e)),o},t.prototype.readInt8=function(t,e){return t>>>=0,e||A(t,1,this.length),128&this[t]?(255-this[t]+1)*-1:this[t]},t.prototype.readInt16LE=function(t,e){t>>>=0,e||A(t,2,this.length);var n=this[t]|this[t+1]<<8;return 32768&n?4294901760|n:n},t.prototype.readInt16BE=function(t,e){t>>>=0,e||A(t,2,this.length);var n=this[t+1]|this[t]<<8;return 32768&n?4294901760|n:n},t.prototype.readInt32LE=function(t,e){return t>>>=0,e||A(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},t.prototype.readInt32BE=function(t,e){return t>>>=0,e||A(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},t.prototype.readFloatLE=function(t,e){return t>>>=0,e||A(t,4,this.length),K.read(this,t,!0,23,4)},t.prototype.readFloatBE=function(t,e){return t>>>=0,e||A(t,4,this.length),K.read(this,t,!1,23,4)},t.prototype.readDoubleLE=function(t,e){return t>>>=0,e||A(t,8,this.length),K.read(this,t,!0,52,8)},t.prototype.readDoubleBE=function(t,e){return t>>>=0,e||A(t,8,this.length),K.read(this,t,!1,52,8)},t.prototype.writeUIntLE=function(t,e,n,r){if(t=+t,e>>>=0,n>>>=0,!r){var i=Math.pow(2,8*n)-1;D(this,t,e,n,i,0)}var o=1,s=0;for(this[e]=255&t;++s>>=0,n>>>=0,!r){var i=Math.pow(2,8*n)-1;D(this,t,e,n,i,0)}var o=n-1,s=1;for(this[e+o]=255&t;--o>=0&&(s*=256);)this[e+o]=t/s&255;return e+n},t.prototype.writeUInt8=function(t,e,n){return t=+t,e>>>=0,n||D(this,t,e,1,255,0),this[e]=255&t,e+1},t.prototype.writeUInt16LE=function(t,e,n){return t=+t,e>>>=0,n||D(this,t,e,2,65535,0),this[e]=255&t,this[e+1]=t>>>8,e+2},t.prototype.writeUInt16BE=function(t,e,n){return t=+t,e>>>=0,n||D(this,t,e,2,65535,0),this[e]=t>>>8,this[e+1]=255&t,e+2},t.prototype.writeUInt32LE=function(t,e,n){return t=+t,e>>>=0,n||D(this,t,e,4,4294967295,0),this[e+3]=t>>>24,this[e+2]=t>>>16,this[e+1]=t>>>8,this[e]=255&t,e+4},t.prototype.writeUInt32BE=function(t,e,n){return t=+t,e>>>=0,n||D(this,t,e,4,4294967295,0),this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t,e+4},t.prototype.writeIntLE=function(t,e,n,r){if(t=+t,e>>>=0,!r){var i=Math.pow(2,8*n-1);D(this,t,e,n,i-1,-i)}var o=0,s=1,a=0;for(this[e]=255&t;++o>0)-a&255;return e+n},t.prototype.writeIntBE=function(t,e,n,r){if(t=+t,e>>>=0,!r){var i=Math.pow(2,8*n-1);D(this,t,e,n,i-1,-i)}var o=n-1,s=1,a=0;for(this[e+o]=255&t;--o>=0&&(s*=256);)t<0&&0===a&&0!==this[e+o+1]&&(a=1),this[e+o]=(t/s>>0)-a&255;return e+n},t.prototype.writeInt8=function(t,e,n){return t=+t,e>>>=0,n||D(this,t,e,1,127,-128),t<0&&(t=255+t+1),this[e]=255&t,e+1},t.prototype.writeInt16LE=function(t,e,n){return t=+t,e>>>=0,n||D(this,t,e,2,32767,-32768),this[e]=255&t,this[e+1]=t>>>8,e+2},t.prototype.writeInt16BE=function(t,e,n){return t=+t,e>>>=0,n||D(this,t,e,2,32767,-32768),this[e]=t>>>8,this[e+1]=255&t,e+2},t.prototype.writeInt32LE=function(t,e,n){return t=+t,e>>>=0,n||D(this,t,e,4,2147483647,-2147483648),this[e]=255&t,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24,e+4},t.prototype.writeInt32BE=function(t,e,n){return t=+t,e>>>=0,n||D(this,t,e,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t,e+4},t.prototype.writeFloatLE=function(t,e,n){return C(this,t,e,!0,n)},t.prototype.writeFloatBE=function(t,e,n){return C(this,t,e,!1,n)},t.prototype.writeDoubleLE=function(t,e,n){return U(this,t,e,!0,n)},t.prototype.writeDoubleBE=function(t,e,n){return U(this,t,e,!1,n)},t.prototype.copy=function(t,e,n,r){if(n||(n=0),r||0===r||(r=this.length),e>=t.length&&(e=t.length),e||(e=0),r>0&&r=this.length)throw new RangeError("sourceStart out of bounds");if(r<0)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),t.length-e=0;--i)t[i+e]=this[i+n];else if(o<1e3)for(i=0;i>>=0,r=void 0===r?this.length:r>>>0,e||(e=0);var s;if("number"==typeof e)for(s=n;s0&&this._events[t].length>i&&(this._events[t].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[t].length),"function"==typeof console.trace&&console.trace())),this},n.prototype.on=n.prototype.addListener,n.prototype.once=function(t,e){function n(){this.removeListener(t,n),i||(i=!0,e.apply(this,arguments))}if(!r(e))throw TypeError("listener must be a function");var i=!1;return n.listener=e,this.on(t,n),this},n.prototype.removeListener=function(t,e){var n,i,s,a;if(!r(e))throw TypeError("listener must be a function");if(!this._events||!this._events[t])return this;if(n=this._events[t],s=n.length,i=-1,n===e||r(n.listener)&&n.listener===e)delete this._events[t],this._events.removeListener&&this.emit("removeListener",t,e);else if(o(n)){for(a=s;a-- >0;)if(n[a]===e||n[a].listener&&n[a].listener===e){i=a;break}if(i<0)return this;1===n.length?(n.length=0,delete this._events[t]):n.splice(i,1),this._events.removeListener&&this.emit("removeListener",t,e)}return this},n.prototype.removeAllListeners=function(t){var e,n;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[t]&&delete this._events[t],this;if(0===arguments.length){for(e in this._events)"removeListener"!==e&&this.removeAllListeners(e);return this.removeAllListeners("removeListener"),this._events={},this}if(n=this._events[t],r(n))this.removeListener(t,n);else if(n)for(;n.length;)this.removeListener(t,n[n.length-1]);return delete this._events[t],this},n.prototype.listeners=function(t){var e;return e=this._events&&this._events[t]?r(this._events[t])?[this._events[t]]:this._events[t].slice():[]},n.prototype.listenerCount=function(t){if(this._events){var e=this._events[t];if(r(e))return 1;if(e)return e.length}return 0},n.listenerCount=function(t,e){return t.listenerCount(e)}},function(t,e,n){t.exports=n(1).Buffer},function(t,e){"use strict";var n="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;e.assign=function(t){for(var e=Array.prototype.slice.call(arguments,1);e.length;){var n=e.shift();if(n){if("object"!=typeof n)throw new TypeError(n+"must be non-object");for(var r in n)n.hasOwnProperty(r)&&(t[r]=n[r])}}return t},e.shrinkBuf=function(t,e){return t.length===e?t:t.subarray?t.subarray(0,e):(t.length=e,t)};var r={arraySet:function(t,e,n,r,i){if(e.subarray&&t.subarray)return void t.set(e.subarray(n,n+r),i);for(var o=0;os)throw new RangeError("size is too large");var r=n,o=e;void 0===o&&(r=void 0,o=0);var a=new i(t);if("string"==typeof o)for(var c=new i(o,r),u=c.length,f=-1;++fs)throw new RangeError("size is too large");return new i(t)},e.from=function(e,n,r){if("function"==typeof i.from&&(!t.Uint8Array||Uint8Array.from!==i.from))return i.from(e,n,r);if("number"==typeof e)throw new TypeError('"value" argument must not be a number');if("string"==typeof e)return new i(e,n);if("undefined"!=typeof ArrayBuffer&&e instanceof ArrayBuffer){var o=n;if(1===arguments.length)return new i(e);"undefined"==typeof o&&(o=0);var s=r;if("undefined"==typeof s&&(s=e.byteLength-o),o>=e.byteLength)throw new RangeError("'offset' is out of bounds");if(s>e.byteLength-o)throw new RangeError("'length' is out of bounds");return new i(e.slice(o,o+s))}if(i.isBuffer(e)){var a=new i(e.length);return e.copy(a,0,0,e.length),a}if(e){if(Array.isArray(e)||"undefined"!=typeof ArrayBuffer&&e.buffer instanceof ArrayBuffer||"length"in e)return new i(e);if("Buffer"===e.type&&Array.isArray(e.data))return new i(e.data)}throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")},e.allocUnsafeSlow=function(t){if("function"==typeof i.allocUnsafeSlow)return i.allocUnsafeSlow(t);if("number"!=typeof t)throw new TypeError("size must be a number");if(t>=s)throw new RangeError("size is too large");return new o(t)}}).call(e,function(){return this}())},function(t,e,n){(function(e){"use strict";function n(t,n,r,i){if("function"!=typeof t)throw new TypeError('"callback" argument must be a function');var o,s,a=arguments.length;switch(a){case 0:case 1:return e.nextTick(t);case 2:return e.nextTick(function(){t.call(null,n)});case 3:return e.nextTick(function(){t.call(null,n,r)});case 4:return e.nextTick(function(){t.call(null,n,r,i)});default:for(o=new Array(a-1),s=0;s-1?setImmediate:k;s.WritableState=o;var O=n(5);O.inherits=n(4);var F,N={deprecate:n(40)};!function(){try{F=n(9)}catch(t){}finally{F||(F=n(6).EventEmitter)}}();var R=n(1).Buffer,L=n(10);O.inherits(s,F),o.prototype.getBuffer=function(){for(var t=this.bufferedRequest,e=[];t;)e.push(t),t=t.next;return e},function(){try{Object.defineProperty(o.prototype,"buffer",{get:N.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.")})}catch(t){}}();var T;"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(T=Function.prototype[Symbol.hasInstance],Object.defineProperty(s,Symbol.hasInstance,{value:function(t){return!!T.call(this,t)||t&&t._writableState instanceof o}})):T=function(t){return t instanceof this},s.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))},s.prototype.write=function(t,e,n){var i=this._writableState,o=!1,s=R.isBuffer(t);return"function"==typeof e&&(n=e,e=null),s?e="buffer":e||(e=i.defaultEncoding),"function"!=typeof n&&(n=r),i.ended?a(this,n):(s||c(this,i,t,n))&&(i.pendingcb++,o=f(this,i,s,t,e,n)),o},s.prototype.cork=function(){var t=this._writableState;t.corked++},s.prototype.uncork=function(){var t=this._writableState;t.corked&&(t.corked--,t.writing||t.corked||t.finished||t.bufferProcessing||!t.bufferedRequest||v(this,t))},s.prototype.setDefaultEncoding=function(t){if("string"==typeof t&&(t=t.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((t+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+t);return this._writableState.defaultEncoding=t,this},s.prototype._write=function(t,e,n){n(new Error("_write() is not implemented"))},s.prototype._writev=null,s.prototype.end=function(t,e,n){var r=this._writableState;"function"==typeof t?(n=t,t=null,e=null):"function"==typeof e&&(n=e,e=null),null!==t&&void 0!==t&&this.write(t,e),r.corked&&(r.corked=1,this.uncork()),r.ending||r.finished||E(this,r,n)}}).call(e,n(3))},function(t,e,n){(function(e){"use strict";function n(t){var e=r.exec(t);return e.shift(),e}var r=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/,i=function(){function t(){}return t.normalize=function(e){""===e&&(e=".");var n=e.charAt(0)===t.sep;e=t._removeDuplicateSeps(e);for(var r=e.split(t.sep),i=[],o=0;o0&&".."!==i[0])?i.pop():i.push(s))}if(!n&&i.length<2)switch(i.length){case 1:""===i[0]&&i.unshift(".");break;default:i.push(".")}return e=i.join(t.sep),n&&e.charAt(0)!==t.sep&&(e=t.sep+e),e},t.join=function(){for(var e=[],n=0;n1&&a.charAt(a.length-1)===t.sep)return a.substr(0,a.length-1);if(a.charAt(0)!==t.sep){"."!==a.charAt(0)||1!==a.length&&a.charAt(1)!==t.sep||(a=1===a.length?"":a.substr(2));var c=e.cwd();a=""!==a?this.normalize(c+("/"!==c?t.sep:"")+a):c}return a},t.relative=function(e,n){var r;e=t.resolve(e),n=t.resolve(n);var i=e.split(t.sep),o=n.split(t.sep);o.shift(),i.shift();var s=0,a=[];for(r=0;ri.length&&(s=i.length);var u="";for(r=0;r1&&u.charAt(u.length-1)===t.sep&&(u=u.substr(0,u.length-1)),u},t.dirname=function(e){e=t._removeDuplicateSeps(e);var n=e.charAt(0)===t.sep,r=e.split(t.sep);return""===r.pop()&&r.length>0&&r.pop(),r.length>1||1===r.length&&!n?r.join(t.sep):n?t.sep:"."},t.basename=function(e,n){if(void 0===n&&(n=""),""===e)return e;e=t.normalize(e);var r=e.split(t.sep),i=r[r.length-1];if(""===i&&r.length>1)return r[r.length-2];if(n.length>0){var o=i.substr(i.length-n.length);if(o===n)return i.substr(0,i.length-n.length)}return i},t.extname=function(e){e=t.normalize(e);var n=e.split(t.sep);if(e=n.pop(),""===e&&n.length>0&&(e=n.pop()),".."===e)return"";var r=e.lastIndexOf(".");return r===-1||0===r?"":e.substr(r)},t.isAbsolute=function(e){return e.length>0&&e.charAt(0)===t.sep},t._makeLong=function(t){return t},t.parse=function(t){var e=n(t);return{root:e[0],dir:e[0]+e[1].slice(0,-1),base:e[2],ext:e[3],name:e[2].slice(0,e[2].length-e[3].length)}},t.format=function(e){if(null===e||"object"!=typeof e)throw new TypeError("Parameter 'pathObject' must be an object, not "+typeof e);var n=e.root||"";if("string"!=typeof n)throw new TypeError("'pathObject.root' must be a string or undefined, not "+typeof e.root);var r=e.dir?e.dir+t.sep:"",i=e.base||"";return r+i},t._removeDuplicateSeps=function(t){return t=t.replace(this._replaceRegex,this.sep)},t.sep="/",t._replaceRegex=new RegExp("//+","g"),t.delimiter=":",t.posix=t,t.win32=t,t}();t.exports=i}).call(e,n(3))},function(t,e,n){"use strict";function r(t){return this instanceof r?void i.call(this,t):new r(t)}t.exports=r;var i=n(12),o=n(5);o.inherits=n(4),o.inherits(r,i),r.prototype._transform=function(t,e,n){n(null,t)}},function(t,e,n){(function(e){"use strict";function r(t,e,n){return"function"==typeof t.prependListener?t.prependListener(e,n):void(t._events&&t._events[e]?T(t._events[e])?t._events[e].unshift(n):t._events[e]=[n,t._events[e]]:t.on(e,n))}function i(t,e){R=R||n(2),t=t||{},this.objectMode=!!t.objectMode,e instanceof R&&(this.objectMode=this.objectMode||!!t.readableObjectMode);var r=t.highWaterMark,i=this.objectMode?16:16384;this.highWaterMark=r||0===r?r:i,this.highWaterMark=~~this.highWaterMark,this.buffer=new B,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.defaultEncoding=t.defaultEncoding||"utf8",this.ranOut=!1,this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,t.encoding&&(j||(j=n(17).StringDecoder),this.decoder=new j(t.encoding),this.encoding=t.encoding)}function o(t){return R=R||n(2),this instanceof o?(this._readableState=new i(t,this),this.readable=!0,t&&"function"==typeof t.read&&(this._read=t.read),void x.call(this)):new o(t)}function s(t,e,n,r,i){var o=f(e,n);if(o)t.emit("error",o);else if(null===n)e.reading=!1,h(t,e);else if(e.objectMode||n&&n.length>0)if(e.ended&&!i){var s=new Error("stream.push() after EOF");t.emit("error",s)}else if(e.endEmitted&&i){var c=new Error("stream.unshift() after end event");t.emit("error",c)}else{var u;!e.decoder||i||r||(n=e.decoder.write(n),u=!e.objectMode&&0===n.length),i||(e.reading=!1),u||(e.flowing&&0===e.length&&!e.sync?(t.emit("data",n),t.read(0)):(e.length+=e.objectMode?1:n.length,i?e.buffer.unshift(n):e.buffer.push(n),e.needReadable&&p(t))),d(t,e)}else i||(e.reading=!1);return a(e)}function a(t){return!t.ended&&(t.needReadable||t.length=z?t=z:(t--,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t++),t}function u(t,e){return t<=0||0===e.length&&e.ended?0:e.objectMode?1:t!==t?e.flowing&&e.length?e.buffer.head.data.length:e.length:(t>e.highWaterMark&&(e.highWaterMark=c(t)),t<=e.length?t:e.ended?e.length:(e.needReadable=!0,0))}function f(t,e){var n=null;return D.isBuffer(e)||"string"==typeof e||null===e||void 0===e||t.objectMode||(n=new TypeError("Invalid non-string/buffer chunk")),n}function h(t,e){if(!e.ended){if(e.decoder){var n=e.decoder.end();n&&n.length&&(e.buffer.push(n),e.length+=e.objectMode?1:n.length)}e.ended=!0,p(t)}}function p(t){var e=t._readableState;e.needReadable=!1,e.emittedReadable||(M("emitReadable",e.flowing),e.emittedReadable=!0,e.sync?L(l,t):l(t))}function l(t){M("emit readable"),t.emit("readable"),w(t)}function d(t,e){e.readingMore||(e.readingMore=!0,L(y,t,e))}function y(t,e){for(var n=e.length;!e.reading&&!e.flowing&&!e.ended&&e.length=e.length?(n=e.decoder?e.buffer.join(""):1===e.buffer.length?e.buffer.head.data:e.buffer.concat(e.length),e.buffer.clear()):n=b(t,e.buffer,e.decoder),n}function b(t,e,n){var r;return to.length?o.length:t;if(i+=s===o.length?o:o.slice(0,t),t-=s,0===t){s===o.length?(++r,n.next?e.head=n.next:e.head=e.tail=null):(e.head=n,n.data=o.slice(s));break}++r}return e.length-=r,i}function k(t,e){var n=P.allocUnsafe(t),r=e.head,i=1;for(r.data.copy(n),t-=r.data.length;r=r.next;){var o=r.data,s=t>o.length?o.length:t;if(o.copy(n,n.length-t,0,s),t-=s,0===t){s===o.length?(++i,r.next?e.head=r.next:e.head=e.tail=null):(e.head=r,r.data=o.slice(s));break}++i}return e.length-=i,n}function I(t){var e=t._readableState;if(e.length>0)throw new Error('"endReadable()" called on non-empty stream');e.endEmitted||(e.ended=!0,L(O,e,t))}function O(t,e){t.endEmitted||0!==t.length||(t.endEmitted=!0,e.readable=!1,e.emit("end"))}function F(t,e){for(var n=0,r=t.length;n=e.highWaterMark||e.ended))return M("read: emitReadable",e.length,e.ended),0===e.length&&e.ended?I(this):p(this),null;if(t=u(t,e),0===t&&e.ended)return 0===e.length&&I(this),null;var r=e.needReadable;M("need readable",r),(0===e.length||e.length-t0?E(t,e):null,null===i?(e.needReadable=!0,t=0):e.length-=t,0===e.length&&(e.ended||(e.needReadable=!0),n!==t&&e.ended&&I(this)),null!==i&&this.emit("data",i),i},o.prototype._read=function(t){this.emit("error",new Error("_read() is not implemented"))},o.prototype.pipe=function(t,n){function i(t){M("onunpipe"),t===p&&s()}function o(){M("onend"),t.end()}function s(){M("cleanup"),t.removeListener("close",u),t.removeListener("finish",f),t.removeListener("drain",v),t.removeListener("error",c),t.removeListener("unpipe",i),p.removeListener("end",o),p.removeListener("end",s),p.removeListener("data",a),m=!0,!l.awaitDrain||t._writableState&&!t._writableState.needDrain||v()}function a(e){M("ondata"),_=!1;var n=t.write(e);!1!==n||_||((1===l.pipesCount&&l.pipes===t||l.pipesCount>1&&N(l.pipes,t)!==-1)&&!m&&(M("false write response, pause",p._readableState.awaitDrain),p._readableState.awaitDrain++,_=!0),p.pause())}function c(e){M("onerror",e),h(),t.removeListener("error",c),0===A(t,"error")&&t.emit("error",e)}function u(){t.removeListener("finish",f),h()}function f(){M("onfinish"),t.removeListener("close",u),h()}function h(){M("unpipe"),p.unpipe(t)}var p=this,l=this._readableState;switch(l.pipesCount){case 0:l.pipes=t;break;case 1:l.pipes=[l.pipes,t];break;default:l.pipes.push(t)}l.pipesCount+=1,M("pipe count=%d opts=%j",l.pipesCount,n);var d=(!n||n.end!==!1)&&t!==e.stdout&&t!==e.stderr,y=d?o:s;l.endEmitted?L(y):p.once("end",y),t.on("unpipe",i);var v=g(p);t.on("drain",v);var m=!1,_=!1;return p.on("data",a),r(t,"error",c),t.once("close",u),t.once("finish",f),t.emit("pipe",p),l.flowing||(M("pipe resume"),p.resume()),t},o.prototype.unpipe=function(t){var e=this._readableState;if(0===e.pipesCount)return this;if(1===e.pipesCount)return t&&t!==e.pipes?this:(t||(t=e.pipes),e.pipes=null,e.pipesCount=0,e.flowing=!1,t&&t.emit("unpipe",this),this);if(!t){var n=e.pipes,r=e.pipesCount;e.pipes=null,e.pipesCount=0,e.flowing=!1;for(var i=0;i=this.charLength-this.charReceived?this.charLength-this.charReceived:t.length;if(t.copy(this.charBuffer,this.charReceived,0,n),this.charReceived+=n,this.charReceived=55296&&r<=56319)){if(this.charReceived=this.charLength=0,0===t.length)return e;break}this.charLength+=this.surrogateSize,e=""}this.detectIncompleteChar(t);var i=t.length;this.charLength&&(t.copy(this.charBuffer,0,t.length-this.charReceived,i),i-=this.charReceived),e+=t.toString(this.encoding,0,i);var i=e.length-1,r=e.charCodeAt(i);if(r>=55296&&r<=56319){var o=this.surrogateSize;return this.charLength+=o,this.charReceived+=o,this.charBuffer.copy(this.charBuffer,o,0,o),t.copy(this.charBuffer,0,0,o),e.substring(0,i)}return e},u.prototype.detectIncompleteChar=function(t){for(var e=t.length>=3?3:t.length;e>0;e--){var n=t[t.length-e];if(1==e&&n>>5==6){this.charLength=2;break}if(e<=2&&n>>4==14){this.charLength=3;break}if(e<=3&&n>>3==30){this.charLength=4;break}}this.charReceived=e},u.prototype.end=function(t){var e="";if(t&&t.length&&(e=this.write(t)),this.charReceived){var n=this.charReceived,r=this.charBuffer,i=this.encoding;e+=r.slice(0,n).toString(i)}return e}},function(t,e){"use strict";function n(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");return"="===t[e-2]?2:"="===t[e-1]?1:0}function r(t){return 3*t.length/4-n(t)}function i(t){var e,r,i,o,s,a,c=t.length;s=n(t),a=new f(3*c/4-s),i=s>0?c-4:c;var h=0;for(e=0,r=0;e>16&255,a[h++]=o>>8&255,a[h++]=255&o;return 2===s?(o=u[t.charCodeAt(e)]<<2|u[t.charCodeAt(e+1)]>>4,a[h++]=255&o):1===s&&(o=u[t.charCodeAt(e)]<<10|u[t.charCodeAt(e+1)]<<4|u[t.charCodeAt(e+2)]>>2,a[h++]=o>>8&255,a[h++]=255&o),a}function o(t){return c[t>>18&63]+c[t>>12&63]+c[t>>6&63]+c[63&t]}function s(t,e,n){for(var r,i=[],s=e;sf?f:u+a));return 1===r?(e=t[n-1],i+=c[e>>2],i+=c[e<<4&63],i+="=="):2===r&&(e=(t[n-2]<<8)+t[n-1],i+=c[e>>10],i+=c[e>>4&63],i+=c[e<<2&63],i+="="),o.push(i),o.join("")}e.byteLength=r,e.toByteArray=i,e.fromByteArray=a;for(var c=[],u=[],f="undefined"!=typeof Uint8Array?Uint8Array:Array,h="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",p=0,l=h.length;p0&&(this._waitingForWrites=this.push(this._bufferedWrites.shift()),this._waitingForWrites););},n}(i.Duplex);t.exports=o}).call(e,n(7))},function(t,e){e.read=function(t,e,n,r,i){var o,s,a=8*i-r-1,c=(1<>1,f=-7,h=n?i-1:0,p=n?-1:1,l=t[e+h];for(h+=p,o=l&(1<<-f)-1,l>>=-f,f+=a;f>0;o=256*o+t[e+h],h+=p,f-=8);for(s=o&(1<<-f)-1,o>>=-f,f+=r;f>0;s=256*s+t[e+h],h+=p,f-=8);if(0===o)o=1-u;else{if(o===c)return s?NaN:(l?-1:1)*(1/0);s+=Math.pow(2,r),o-=u}return(l?-1:1)*s*Math.pow(2,o-r)},e.write=function(t,e,n,r,i,o){var s,a,c,u=8*o-i-1,f=(1<>1,p=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,l=r?0:o-1,d=r?1:-1,y=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,s=f):(s=Math.floor(Math.log(e)/Math.LN2),e*(c=Math.pow(2,-s))<1&&(s--,c*=2),e+=s+h>=1?p/c:p*Math.pow(2,1-h),e*c>=2&&(s++,c/=2),s+h>=f?(a=0,s=f):s+h>=1?(a=(e*c-1)*Math.pow(2,i),s+=h):(a=e*Math.pow(2,h-1)*Math.pow(2,i),s=0));i>=8;t[n+l]=255&a,l+=d,a/=256,i-=8);for(s=s<0;t[n+l]=255&s,l+=d,s/=256,u-=8);t[n+l-d]|=128*y}},function(t,e){var n={}.toString;t.exports=Array.isArray||function(t){return"[object Array]"==n.call(t)}},function(t,e,n){"use strict";function r(t){if(!(this instanceof r))return new r(t);this.options=a.assign({chunkSize:16384,windowBits:0,to:""},t||{});var e=this.options;e.raw&&e.windowBits>=0&&e.windowBits<16&&(e.windowBits=-e.windowBits,0===e.windowBits&&(e.windowBits=-15)),!(e.windowBits>=0&&e.windowBits<16)||t&&t.windowBits||(e.windowBits+=32),e.windowBits>15&&e.windowBits<48&&0===(15&e.windowBits)&&(e.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new h,this.strm.avail_out=0;var n=s.inflateInit2(this.strm,e.windowBits);if(n!==u.Z_OK)throw new Error(f[n]);this.header=new p,s.inflateGetHeader(this.strm,this.header)}function i(t,e){var n=new r(e);if(n.push(t,!0),n.err)throw n.msg||f[n.err];return n.result}function o(t,e){return e=e||{},e.raw=!0,i(t,e)}var s=n(30),a=n(8),c=n(24),u=n(26),f=n(32),h=n(33),p=n(28),l=Object.prototype.toString;r.prototype.push=function(t,e){var n,r,i,o,f,h,p=this.strm,d=this.options.chunkSize,y=this.options.dictionary,g=!1;if(this.ended)return!1;r=e===~~e?e:e===!0?u.Z_FINISH:u.Z_NO_FLUSH,"string"==typeof t?p.input=c.binstring2buf(t):"[object ArrayBuffer]"===l.call(t)?p.input=new Uint8Array(t):p.input=t,p.next_in=0,p.avail_in=p.input.length;do{if(0===p.avail_out&&(p.output=new a.Buf8(d),p.next_out=0,p.avail_out=d),n=s.inflate(p,u.Z_NO_FLUSH),n===u.Z_NEED_DICT&&y&&(h="string"==typeof y?c.string2buf(y):"[object ArrayBuffer]"===l.call(y)?new Uint8Array(y):y,n=s.inflateSetDictionary(this.strm,h)),n===u.Z_BUF_ERROR&&g===!0&&(n=u.Z_OK,g=!1),n!==u.Z_STREAM_END&&n!==u.Z_OK)return this.onEnd(n),this.ended=!0,!1;p.next_out&&(0!==p.avail_out&&n!==u.Z_STREAM_END&&(0!==p.avail_in||r!==u.Z_FINISH&&r!==u.Z_SYNC_FLUSH)||("string"===this.options.to?(i=c.utf8border(p.output,p.next_out),o=p.next_out-i,f=c.buf2string(p.output,i),p.next_out=o,p.avail_out=d-o,o&&a.arraySet(p.output,p.output,i,o,0),this.onData(f)):this.onData(a.shrinkBuf(p.output,p.next_out)))),0===p.avail_in&&0===p.avail_out&&(g=!0)}while((p.avail_in>0||0===p.avail_out)&&n!==u.Z_STREAM_END);return n===u.Z_STREAM_END&&(r=u.Z_FINISH),r===u.Z_FINISH?(n=s.inflateEnd(this.strm),this.onEnd(n),this.ended=!0,n===u.Z_OK):r!==u.Z_SYNC_FLUSH||(this.onEnd(u.Z_OK),p.avail_out=0,!0)},r.prototype.onData=function(t){this.chunks.push(t)},r.prototype.onEnd=function(t){t===u.Z_OK&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=a.flattenChunks(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg},e.Inflate=r,e.inflate=i,e.inflateRaw=o,e.ungzip=i},function(t,e,n){"use strict";function r(t,e){if(e<65537&&(t.subarray&&s||!t.subarray&&o))return String.fromCharCode.apply(null,i.shrinkBuf(t,e));for(var n="",r=0;r=252?6:c>=248?5:c>=240?4:c>=224?3:c>=192?2:1;a[254]=a[254]=1,e.string2buf=function(t){var e,n,r,o,s,a=t.length,c=0;for(o=0;o>>6,e[s++]=128|63&n):n<65536?(e[s++]=224|n>>>12,e[s++]=128|n>>>6&63,e[s++]=128|63&n):(e[s++]=240|n>>>18,e[s++]=128|n>>>12&63,e[s++]=128|n>>>6&63,e[s++]=128|63&n);return e},e.buf2binstring=function(t){return r(t,t.length)},e.binstring2buf=function(t){for(var e=new i.Buf8(t.length),n=0,r=e.length;n4)u[i++]=65533,n+=s-1;else{for(o&=2===s?31:3===s?15:7;s>1&&n1?u[i++]=65533:o<65536?u[i++]=o:(o-=65536,u[i++]=55296|o>>10&1023,u[i++]=56320|1023&o)}return r(u,i)},e.utf8border=function(t,e){ -var n;for(e=e||t.length,e>t.length&&(e=t.length),n=e-1;n>=0&&128===(192&t[n]);)n--;return n<0?e:0===n?e:n+a[t[n]]>e?n:e}},function(t,e){"use strict";function n(t,e,n,r){for(var i=65535&t|0,o=t>>>16&65535|0,s=0;0!==n;){s=n>2e3?2e3:n,n-=s;do i=i+e[r++]|0,o=o+i|0;while(--s);i%=65521,o%=65521}return i|o<<16|0}t.exports=n},function(t,e){"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_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},function(t,e){"use strict";function n(){for(var t,e=[],n=0;n<256;n++){t=n;for(var r=0;r<8;r++)t=1&t?3988292384^t>>>1:t>>>1;e[n]=t}return e}function r(t,e,n,r){var o=i,s=r+n;t^=-1;for(var a=r;a>>8^o[255&(t^e[a])];return t^-1}var i=n();t.exports=r},function(t,e){"use strict";function n(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}t.exports=n},function(t,e){"use strict";var n=30,r=12;t.exports=function(t,e){var i,o,s,a,c,u,f,h,p,l,d,y,g,v,m,_,w,E,b,S,k,I,O,F,N;i=t.state,o=t.next_in,F=t.input,s=o+(t.avail_in-5),a=t.next_out,N=t.output,c=a-(e-t.avail_out),u=a+(t.avail_out-257),f=i.dmax,h=i.wsize,p=i.whave,l=i.wnext,d=i.window,y=i.hold,g=i.bits,v=i.lencode,m=i.distcode,_=(1<>>24,y>>>=b,g-=b,b=E>>>16&255,0===b)N[a++]=65535&E;else{if(!(16&b)){if(0===(64&b)){E=v[(65535&E)+(y&(1<>>=b,g-=b),g<15&&(y+=F[o++]<>>24,y>>>=b,g-=b,b=E>>>16&255,!(16&b)){if(0===(64&b)){E=m[(65535&E)+(y&(1<f){t.msg="invalid distance too far back",i.mode=n;break t}if(y>>>=b,g-=b,b=a-c,k>b){if(b=k-b,b>p&&i.sane){t.msg="invalid distance too far back",i.mode=n;break t}if(I=0,O=d,0===l){if(I+=h-b,b2;)N[a++]=O[I++],N[a++]=O[I++],N[a++]=O[I++],S-=3;S&&(N[a++]=O[I++],S>1&&(N[a++]=O[I++]))}else{I=a-k;do N[a++]=N[I++],N[a++]=N[I++],N[a++]=N[I++],S-=3;while(S>2);S&&(N[a++]=N[I++],S>1&&(N[a++]=N[I++]))}break}}break}}while(o>3,o-=S,g-=S<<3,y&=(1<>>24&255)+(t>>>8&65280)+((65280&t)<<8)+((255&t)<<24)}function i(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new m.Buf16(320),this.work=new m.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function o(t){var e;return t&&t.state?(e=t.state,t.total_in=t.total_out=e.total=0,t.msg="",e.wrap&&(t.adler=1&e.wrap),e.mode=U,e.last=0,e.havedict=0,e.dmax=32768,e.head=null,e.hold=0,e.bits=0,e.lencode=e.lendyn=new m.Buf32(yt),e.distcode=e.distdyn=new m.Buf32(gt),e.sane=1,e.back=-1,R):x}function s(t){var e;return t&&t.state?(e=t.state,e.wsize=0,e.whave=0,e.wnext=0,o(t)):x}function a(t,e){var n,r;return t&&t.state?(r=t.state,e<0?(n=0,e=-e):(n=(e>>4)+1,e<48&&(e&=15)),e&&(e<8||e>15)?x:(null!==r.window&&r.wbits!==e&&(r.window=null),r.wrap=n,r.wbits=e,s(t))):x}function c(t,e){var n,r;return t?(r=new i,t.state=r,r.window=null,n=a(t,e),n!==R&&(t.state=null),n):x}function u(t){return c(t,mt)}function f(t){if(_t){var e;for(g=new m.Buf32(512),v=new m.Buf32(32),e=0;e<144;)t.lens[e++]=8;for(;e<256;)t.lens[e++]=9;for(;e<280;)t.lens[e++]=7;for(;e<288;)t.lens[e++]=8;for(b(k,t.lens,0,288,g,0,t.work,{bits:9}),e=0;e<32;)t.lens[e++]=5;b(I,t.lens,0,32,v,0,t.work,{bits:5}),_t=!1}t.lencode=g,t.lenbits=9,t.distcode=v,t.distbits=5}function h(t,e,n,r){var i,o=t.state;return null===o.window&&(o.wsize=1<=o.wsize?(m.arraySet(o.window,e,n-o.wsize,o.wsize,0),o.wnext=0,o.whave=o.wsize):(i=o.wsize-o.wnext,i>r&&(i=r),m.arraySet(o.window,e,n-r,i,o.wnext),r-=i,r?(m.arraySet(o.window,e,n-r,r,0),o.wnext=r,o.whave=o.wsize):(o.wnext+=i,o.wnext===o.wsize&&(o.wnext=0),o.whave>>8&255,n.check=w(n.check,Ft,2,0),p=0,l=0,n.mode=M;break}if(n.flags=0,n.head&&(n.head.done=!1),!(1&n.wrap)||(((255&p)<<8)+(p>>8))%31){t.msg="incorrect header check",n.mode=pt;break}if((15&p)!==C){t.msg="unknown compression method",n.mode=pt;break}if(p>>>=4,l-=4,bt=(15&p)+8,0===n.wbits)n.wbits=bt;else if(bt>n.wbits){t.msg="invalid window size",n.mode=pt;break}n.dmax=1<>8&1),512&n.flags&&(Ft[0]=255&p,Ft[1]=p>>>8&255,n.check=w(n.check,Ft,2,0)),p=0,l=0,n.mode=j;case j:for(;l<32;){if(0===c)break t;c--,p+=i[s++]<>>8&255,Ft[2]=p>>>16&255,Ft[3]=p>>>24&255,n.check=w(n.check,Ft,4,0)),p=0,l=0,n.mode=B;case B:for(;l<16;){if(0===c)break t;c--,p+=i[s++]<>8),512&n.flags&&(Ft[0]=255&p,Ft[1]=p>>>8&255,n.check=w(n.check,Ft,2,0)),p=0,l=0,n.mode=z;case z:if(1024&n.flags){for(;l<16;){if(0===c)break t;c--,p+=i[s++]<>>8&255,n.check=w(n.check,Ft,2,0)),p=0,l=0}else n.head&&(n.head.extra=null);n.mode=q;case q:if(1024&n.flags&&(g=n.length,g>c&&(g=c),g&&(n.head&&(bt=n.head.extra_len-n.length,n.head.extra||(n.head.extra=new Array(n.head.extra_len)),m.arraySet(n.head.extra,i,s,g,bt)),512&n.flags&&(n.check=w(n.check,i,g,s)),c-=g,s+=g,n.length-=g),n.length))break t;n.length=0,n.mode=V;case V:if(2048&n.flags){if(0===c)break t;g=0;do bt=i[s+g++],n.head&&bt&&n.length<65536&&(n.head.name+=String.fromCharCode(bt));while(bt&&g>9&1,n.head.done=!0),t.adler=n.check=0,n.mode=X;break;case Z:for(;l<32;){if(0===c)break t;c--,p+=i[s++]<>>=7&l,l-=7&l,n.mode=ut;break}for(;l<3;){if(0===c)break t;c--,p+=i[s++]<>>=1,l-=1,3&p){case 0:n.mode=J;break;case 1:if(f(n),n.mode=nt,e===N){p>>>=2,l-=2;break t}break;case 2:n.mode=$;break;case 3:t.msg="invalid block type",n.mode=pt}p>>>=2,l-=2;break;case J:for(p>>>=7&l,l-=7&l;l<32;){if(0===c)break t;c--,p+=i[s++]<>>16^65535)){t.msg="invalid stored block lengths",n.mode=pt;break}if(n.length=65535&p,p=0,l=0,n.mode=G,e===N)break t;case G:n.mode=Q;case Q:if(g=n.length){if(g>c&&(g=c),g>u&&(g=u),0===g)break t;m.arraySet(o,i,s,g,a),c-=g,s+=g,u-=g,a+=g,n.length-=g;break}n.mode=X;break;case $:for(;l<14;){if(0===c)break t;c--,p+=i[s++]<>>=5,l-=5,n.ndist=(31&p)+1,p>>>=5,l-=5,n.ncode=(15&p)+4,p>>>=4,l-=4,n.nlen>286||n.ndist>30){t.msg="too many length or distance symbols",n.mode=pt;break}n.have=0,n.mode=tt;case tt:for(;n.have>>=3,l-=3}for(;n.have<19;)n.lens[Nt[n.have++]]=0;if(n.lencode=n.lendyn,n.lenbits=7,kt={bits:n.lenbits},St=b(S,n.lens,0,19,n.lencode,0,n.work,kt),n.lenbits=kt.bits,St){t.msg="invalid code lengths set",n.mode=pt;break}n.have=0,n.mode=et;case et:for(;n.have>>24,vt=Ot>>>16&255,mt=65535&Ot,!(gt<=l);){if(0===c)break t;c--,p+=i[s++]<>>=gt,l-=gt,n.lens[n.have++]=mt;else{if(16===mt){for(It=gt+2;l>>=gt,l-=gt,0===n.have){t.msg="invalid bit length repeat",n.mode=pt;break}bt=n.lens[n.have-1],g=3+(3&p),p>>>=2,l-=2}else if(17===mt){for(It=gt+3;l>>=gt,l-=gt,bt=0,g=3+(7&p),p>>>=3,l-=3}else{for(It=gt+7;l>>=gt,l-=gt,bt=0,g=11+(127&p),p>>>=7,l-=7}if(n.have+g>n.nlen+n.ndist){t.msg="invalid bit length repeat",n.mode=pt;break}for(;g--;)n.lens[n.have++]=bt}}if(n.mode===pt)break;if(0===n.lens[256]){t.msg="invalid code -- missing end-of-block",n.mode=pt;break}if(n.lenbits=9,kt={bits:n.lenbits},St=b(k,n.lens,0,n.nlen,n.lencode,0,n.work,kt),n.lenbits=kt.bits,St){t.msg="invalid literal/lengths set",n.mode=pt;break}if(n.distbits=6,n.distcode=n.distdyn,kt={bits:n.distbits},St=b(I,n.lens,n.nlen,n.ndist,n.distcode,0,n.work,kt),n.distbits=kt.bits,St){t.msg="invalid distances set",n.mode=pt;break}if(n.mode=nt,e===N)break t;case nt:n.mode=rt;case rt:if(c>=6&&u>=258){t.next_out=a,t.avail_out=u,t.next_in=s,t.avail_in=c,n.hold=p,n.bits=l,E(t,y),a=t.next_out,o=t.output,u=t.avail_out,s=t.next_in,i=t.input,c=t.avail_in,p=n.hold,l=n.bits,n.mode===X&&(n.back=-1);break}for(n.back=0;Ot=n.lencode[p&(1<>>24,vt=Ot>>>16&255,mt=65535&Ot,!(gt<=l);){if(0===c)break t;c--,p+=i[s++]<>_t)],gt=Ot>>>24,vt=Ot>>>16&255,mt=65535&Ot,!(_t+gt<=l);){if(0===c)break t;c--,p+=i[s++]<>>=_t,l-=_t,n.back+=_t}if(p>>>=gt,l-=gt,n.back+=gt,n.length=mt,0===vt){n.mode=ct;break}if(32&vt){n.back=-1,n.mode=X;break}if(64&vt){t.msg="invalid literal/length code",n.mode=pt;break}n.extra=15&vt,n.mode=it;case it:if(n.extra){for(It=n.extra;l>>=n.extra,l-=n.extra,n.back+=n.extra}n.was=n.length,n.mode=ot;case ot:for(;Ot=n.distcode[p&(1<>>24,vt=Ot>>>16&255,mt=65535&Ot,!(gt<=l);){if(0===c)break t;c--,p+=i[s++]<>_t)],gt=Ot>>>24,vt=Ot>>>16&255,mt=65535&Ot,!(_t+gt<=l);){if(0===c)break t;c--,p+=i[s++]<>>=_t,l-=_t,n.back+=_t}if(p>>>=gt,l-=gt,n.back+=gt,64&vt){t.msg="invalid distance code",n.mode=pt;break}n.offset=mt,n.extra=15&vt,n.mode=st;case st:if(n.extra){for(It=n.extra;l>>=n.extra,l-=n.extra,n.back+=n.extra}if(n.offset>n.dmax){t.msg="invalid distance too far back",n.mode=pt;break}n.mode=at;case at:if(0===u)break t;if(g=y-u,n.offset>g){if(g=n.offset-g,g>n.whave&&n.sane){t.msg="invalid distance too far back",n.mode=pt;break}g>n.wnext?(g-=n.wnext,v=n.wsize-g):v=n.wnext-g,g>n.length&&(g=n.length),yt=n.window}else yt=o,v=a-n.offset,g=n.length;g>u&&(g=u),u-=g,n.length-=g;do o[a++]=yt[v++];while(--g);0===n.length&&(n.mode=rt);break;case ct:if(0===u)break t;o[a++]=n.length,u--,n.mode=rt;break;case ut:if(n.wrap){for(;l<32;){if(0===c)break t;c--,p|=i[s++]<=1&&0===z[x];x--);if(A>x&&(A=x),0===x)return y[g++]=20971520,y[g++]=20971520,m.bits=1,0;for(T=1;T0&&(t===a||1!==x))return-1;for(q[1]=0,R=1;Ro||t===u&&U>s)return 1;for(;;){I=R-P,v[L]k?(O=V[W+v[L]],F=j[B+v[L]]):(O=96,F=0),_=1<>P)+w]=I<<24|O<<16|F|0;while(0!==w);for(_=1<>=1;if(0!==_?(M&=_-1,M+=_):M=0,L++,0===--z[R]){if(R===x)break;R=e[n+v[L]]}if(R>A&&(M&b)!==E){for(0===P&&(P=A),S+=T,D=R-P,C=1<o||t===u&&U>s)return 1;E=M&b,y[E]=A<<24|D<<16|S-g|0}}return 0!==M&&(y[S+M]=R-P<<24|64<<16|0),m.bits=A,0}},function(t,e){"use strict";t.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},function(t,e){"use strict";function n(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}t.exports=n},function(t,e,n){t.exports=n(2)},function(t,e,n){"use strict";function r(){this.head=null,this.tail=null,this.length=0}var i=(n(1).Buffer,n(10));t.exports=r,r.prototype.push=function(t){var e={data:t,next:null};this.length>0?this.tail.next=e:this.head=e,this.tail=e,++this.length},r.prototype.unshift=function(t){var e={data:t,next:this.head};0===this.length&&(this.tail=e),this.head=e,++this.length},r.prototype.shift=function(){if(0!==this.length){var t=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,t}},r.prototype.clear=function(){this.head=this.tail=null,this.length=0},r.prototype.join=function(t){if(0===this.length)return"";for(var e=this.head,n=""+e.data;e=e.next;)n+=t+e.data;return n},r.prototype.concat=function(t){if(0===this.length)return i.alloc(0);if(1===this.length)return this.head.data;for(var e=i.allocUnsafe(t>>>0),n=this.head,r=0;n;)n.data.copy(e,r),r+=n.data.length,n=n.next;return e}},function(t,e,n){t.exports=n(15)},function(t,e,n){(function(r){var i=function(){try{return n(9)}catch(t){}}();e=t.exports=n(16),e.Stream=i||e,e.Readable=e,e.Writable=n(13),e.Duplex=n(2),e.Transform=n(12),e.PassThrough=n(15),!r.browser&&"disable"===r.env.READABLE_STREAM&&i&&(t.exports=i)}).call(e,n(3))},function(t,e,n){t.exports=n(12)},function(t,e,n){t.exports=n(13)},function(t,e){(function(e){function n(t,e){function n(){if(!i){if(r("throwDeprecation"))throw new Error(e);r("traceDeprecation")?console.trace(e):console.warn(e),i=!0}return t.apply(this,arguments)}if(r("noDeprecation"))return t;var i=!1;return n}function r(t){try{if(!e.localStorage)return!1}catch(t){return!1}var n=e.localStorage[t];return null!=n&&"true"===String(n).toLowerCase()}t.exports=n}).call(e,function(){return this}())},function(t,e){t.exports=function(t){return t.webpackPolyfill||(t.deprecate=function(){},t.paths=[],t.children=[],t.webpackPolyfill=1),t}},function(t,e){}])}); -//# sourceMappingURL=browserfs.min.js.map \ No newline at end of file diff --git a/bundles/browserfs.min.js.map b/bundles/browserfs.min.js.map deleted file mode 100644 index 53e1d4a..0000000 --- a/bundles/browserfs.min.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"sources":["webpack:///webpack/universalModuleDefinition","webpack:///../build/browserfs.min.js","webpack:///webpack/bootstrap ebd3bd27baeec43b998e","webpack:///../../../../src/core/FS.ts","webpack:///../../../../src/core/levenshtein.ts","webpack:///../../../../src/core/util.ts","webpack:///../../../../~/lodash-es/_apply.js","webpack:///../../../../~/lodash-es/_overRest.js","webpack:///../../../../~/lodash-es/identity.js","webpack:///../../../../~/async-es/internal/rest.js","webpack:///../../../../~/async-es/internal/applyEach.js","webpack:///../../../../~/lodash-es/_getRawTag.js","webpack:///../../../../~/lodash-es/_objectToString.js","webpack:///../../../../~/lodash-es/_baseGetTag.js","webpack:///../../../../~/lodash-es/isObject.js","webpack:///../../../../~/lodash-es/isFunction.js","webpack:///../../../../~/lodash-es/isLength.js","webpack:///../../../../~/lodash-es/isArrayLike.js","webpack:///../../../../~/lodash-es/noop.js","webpack:///../../../../~/async-es/internal/once.js","webpack:///../../../../~/lodash-es/_baseTimes.js","webpack:///../../../../~/lodash-es/isObjectLike.js","webpack:///../../../../~/lodash-es/_baseIsArguments.js","webpack:///../../../../~/lodash-es/stubFalse.js","webpack:///../../../../~/lodash-es/_isIndex.js","webpack:///../../../../~/lodash-es/_baseIsTypedArray.js","webpack:///../../../../~/lodash-es/_baseUnary.js","webpack:///../../../../~/lodash-es/_arrayLikeKeys.js","webpack:///../../../../~/lodash-es/_isPrototype.js","webpack:///../../../../~/lodash-es/_overArg.js","webpack:///../../../../~/lodash-es/_baseKeys.js","webpack:///../../../../~/lodash-es/keys.js","webpack:///../../../../~/async-es/internal/iterator.js","webpack:///../../../../~/async-es/internal/onlyOnce.js","webpack:///../../../../~/async-es/internal/eachOfLimit.js","webpack:///../../../../~/async-es/eachOfLimit.js","webpack:///../../../../~/async-es/internal/doLimit.js","webpack:///../../../../~/async-es/eachOf.js","webpack:///../../../../~/async-es/internal/doParallel.js","webpack:///../../../../~/async-es/internal/map.js","webpack:///../../../../~/async-es/internal/doParallelLimit.js","webpack:///../../../../~/lodash-es/_arrayEach.js","webpack:///../../../../~/lodash-es/_createBaseFor.js","webpack:///../../../../~/async-es/internal/setImmediate.js","webpack:///../../../../~/async-es/reduce.js","webpack:///../../../../~/async-es/internal/consoleFunc.js","webpack:///../../../../~/async-es/internal/withoutIndex.js","webpack:///../../../../~/async-es/each.js","webpack:///../../../../src/backend/Dropbox.ts","webpack:///../../../../src/backend/Emscripten.ts","webpack:///../../../../src/backend/FolderAdapter.ts","webpack:///../../../../src/backend/HTML5FS.ts","webpack:///../../../../src/generic/key_value_filesystem.ts","webpack:///../../../../src/backend/IndexedDB.ts","webpack:///../../../../src/backend/MountableFileSystem.ts","webpack:///../../../../src/backend/OverlayFS.ts","webpack:///../../../../src/backend/WorkerFS.ts","webpack:///../../../../src/generic/xhr.ts","webpack:///../../../../src/generic/file_index.ts","webpack:///../../../../src/backend/XmlHttpRequest.ts","webpack:///../../../../src/backend/ZipFS.ts","webpack:///../../../../src/backend/IsoFS.ts","webpack:///../../../../src/core/browserfs.ts","webpack:///../../../../src/core/api_error.ts","webpack:///../../../../src/core/file_flag.ts","webpack:///../../../../src/core/node_fs_stats.ts","webpack:///../../../../src/core/node_fs.ts","webpack:///../../../../src/generic/emscripten_fs.ts","webpack:///../../../../src/core/file_system.ts","webpack:///../../../../src/core/file.ts","webpack:///../../../../src/generic/preload_file.ts","webpack:///../../../../src/backend/AsyncMirror.ts","webpack:///../../../../~/async-es/internal/initialParams.js","webpack:///../../../../~/lodash-es/_freeGlobal.js","webpack:///../../../../~/lodash-es/_root.js","webpack:///../../../../~/lodash-es/_Symbol.js","webpack:///../../../../~/async-es/internal/breakLoop.js","webpack:///../../../../~/async-es/internal/getIterator.js","webpack:///../../../../~/lodash-es/isArguments.js","webpack:///../../../../~/lodash-es/isArray.js","webpack:///../../../../~/lodash-es/isBuffer.js","webpack:///../../../../~/lodash-es/_nodeUtil.js","webpack:///../../../../~/lodash-es/isTypedArray.js","webpack:///../../../../~/lodash-es/_nativeKeys.js","webpack:///../../../../~/async-es/map.js","webpack:///../../../../~/async-es/applyEach.js","webpack:///../../../../~/async-es/mapLimit.js","webpack:///../../../../~/async-es/mapSeries.js","webpack:///../../../../~/async-es/applyEachSeries.js","webpack:///../../../../~/async-es/apply.js","webpack:///../../../../~/lodash-es/_baseFor.js","webpack:///../../../../~/lodash-es/_unicodeToArray.js","webpack:///../../../../~/async-es/eachOfSeries.js","webpack:///../../../../~/async-es/seq.js","webpack:///../../../../~/async-es/compose.js","webpack:///../../../../~/async-es/constant.js","webpack:///../../../../~/async-es/dir.js","webpack:///../../../../~/async-es/log.js","webpack:///../../../../~/async-es/nextTick.js","webpack:///../../../../~/lodash-es/_baseRange.js","webpack:///../../../../src/core/global.ts","webpack:///../../../../src/generic/inode.ts","webpack:///../../../../src/backend/InMemory.ts","webpack:///../../../../src/backend/LocalStorage.ts","webpack:///../../../../src/generic/setImmediate.ts","webpack:///../../../../src/generic/mutex.ts","webpack:///../../../../src/generic/locked_fs.ts","webpack:///../../../../src/generic/extended_ascii.ts","webpack:///../../../../src/core/backends.ts","webpack:///../../../../src/index.ts","webpack:///./~/buffer/index.js","webpack:///./~/readable-stream/lib/_stream_duplex.js","webpack:///../ts/index.ts","webpack:///./~/inherits/inherits_browser.js","webpack:///./~/core-util-is/lib/util.js","webpack:///./~/events/events.js","webpack:///./build/temp/library/webpack/BFSBuffer.js","webpack:///./~/pako/lib/utils/common.js","webpack:///./~/stream-browserify/index.js","webpack:///./~/buffer-shims/index.js","webpack:///./~/process-nextick-args/index.js","webpack:///./~/readable-stream/lib/_stream_transform.js","webpack:///./~/readable-stream/lib/_stream_writable.js","webpack:///../ts/path.ts","webpack:///./~/readable-stream/lib/_stream_passthrough.js","webpack:///./~/readable-stream/lib/_stream_readable.js","webpack:///./~/string_decoder/index.js","webpack:///./~/base64-js/index.js","webpack:///../ts/process.ts","webpack:///../ts/tty.ts","webpack:///./~/ieee754/index.js","webpack:///./~/isarray/index.js","webpack:///./~/pako/lib/inflate.js","webpack:///./~/pako/lib/utils/strings.js","webpack:///./~/pako/lib/zlib/adler32.js","webpack:///./~/pako/lib/zlib/constants.js","webpack:///./~/pako/lib/zlib/crc32.js","webpack:///./~/pako/lib/zlib/gzheader.js","webpack:///./~/pako/lib/zlib/inffast.js","webpack:///./~/pako/lib/zlib/inflate.js","webpack:///./~/pako/lib/zlib/inftrees.js","webpack:///./~/pako/lib/zlib/messages.js","webpack:///./~/pako/lib/zlib/zstream.js","webpack:///./~/readable-stream/duplex.js","webpack:///./~/readable-stream/lib/internal/streams/BufferList.js","webpack:///./~/readable-stream/passthrough.js","webpack:///./~/readable-stream/readable.js","webpack:///./~/readable-stream/transform.js","webpack:///./~/readable-stream/writable.js","webpack:///./~/util-deprecate/browser.js","webpack:///(webpack)/buildin/module.js"],"names":["root","factory","exports","module","define","amd","this","modules","__webpack_require__","moduleId","installedModules","id","loaded","call","m","c","p","Buffer","global","process","assertRoot","fs","ApiError","ErrorCode","EIO","normalizeMode","mode","def","const","trueMode","parseInt","isNaN","normalizeTime","time","Date","EINVAL","normalizePath","indexOf","path.resolve","normalizeOptions","options","defEnc","defFlag","defMode","encoding","flag","nopCb","_min","d0","d1","d2","bx","ay","levenshtein","a","b","length","tmp","let","la","lb","charCodeAt","offset","vector","Array","y","x","d3","bx0","bx1","bx2","bx3","dd","dy","deprecationMessage","print","fsName","opts","console","warn","JSON","stringify","fail","Error","mkdirpSync","existsSync","path.dirname","mkdirSync","buffer2ArrayBuffer","buff","u8","buffer2Uint8array","u8offset","byteOffset","u8Len","byteLength","buffer","slice","Uint8Array","arrayish2Buffer","arr","uint8Array2Buffer","from","arrayBuffer2Buffer","ab","copyingSlice","start","end","TypeError","emptyBuffer","s0","newS0","subarray","emptyBuff","alloc","bufferValidator","v","cb","isBuffer","checkOptions","fsType","validatorCallback","e","callbackCalled","pendingValidators","loopEnded","optsInfo","Options","Name","loop","optName","hasOwnProperty","opt","providedValue","undefined","optional","incorrectOptions","Object","keys","filter","o","map","str","distance","sort","typeMatches","isArray","type","join","validator","returned","apply","func","thisArg","args","overRest","transform","nativeMax","arguments","index","array","otherArgs","identity","value","rest","_overRest","applyEach","eachfn","fns","go","initialParams","callback","that","fn","concat","getRawTag","isOwn","symToStringTag","tag","unmasked","result","nativeObjectToString","objectToString","baseGetTag","undefinedTag","nullTag","isObject","isFunction","funcTag","genTag","asyncTag","proxyTag","isLength","MAX_SAFE_INTEGER","isArrayLike","noop","once","callFn","baseTimes","n","iteratee","isObjectLike","baseIsArguments","argsTag","stubFalse","isIndex","reIsUint","test","baseIsTypedArray","typedArrayTags","baseUnary","arrayLikeKeys","inherited","isArr","isArg","isArguments","isBuff","isType","isTypedArray","skipIndexes","String","key","push","isPrototype","Ctor","constructor","proto","prototype","objectProto","overArg","arg","baseKeys","object","nativeKeys","createArrayIterator","coll","i","len","createES2015Iterator","iterator","item","next","done","createObjectIterator","obj","okeys","getIterator","onlyOnce","_eachOfLimit","limit","iterateeCallback","err","running","breakLoop","replenish","elem","nextElem","eachOfLimit","doLimit","iterable","eachOfArrayLike","iteratorCallback","completed","doParallel","eachOf","_asyncMap","results","counter","_","doParallelLimit","arrayEach","createBaseFor","fromRight","keysFunc","props","fallback","setTimeout","wrap","defer","reduce","memo","eachOfSeries","consoleFunc","name","error","_withoutIndex","eachLimit","withoutIndex","constructErrorCodeLookup","errorCodeLookup","Dropbox","NETWORK_ERROR","INVALID_PARAM","INVALID_TOKEN","EPERM","OAUTH_ERROR","NOT_FOUND","ENOENT","INVALID_METHOD","NOT_ACCEPTABLE","CONFLICT","RATE_LIMITED","EBUSY","SERVER_ERROR","OVER_QUOTA","ENOSPC","isFileInfo","cache","stat","isFile","isDirInfo","isFolder","isArrayBuffer","convertError","path","path$$1","errno","parent","node","paths","unshift","ErrorStrings","translateError","folder","path.relative","message","replace","wrapCallback","wrapFunction","wrapFirst","wrapSecond","path.join","_folder","_wrapped","isDirectoryEntry","entry","isDirectory","_requestQuota","size","success","errorCallback","navigator","PERSISTENT","webkitPersistentStorage","requestQuota","TEMPORARY","webkitTemporaryStorage","webkitStorageInfo","_toArray","list","convertError$1","expectedDir","EEXIST","FileError","EACCES","ENOTDIR","EISDIR","getEmptyDirNode","emptyDirNode","GenerateRandomID","r","Math","random","toString","noError","noErrorTx","tx","abort","convertError$2","onErrorHandler","code","preventDefault","defineFcn","isSync","numArgs","rv","_getFs","standardizeError","this$1","makeModeWritable","0o222","getFlag","f","FileFlag","getFileFlag","apiErrorLocal2Remote","SpecialArgType","API_ERROR","errorData","bufferToTransferrableObject","writeToBuffer","apiErrorRemote2Local","fromBuffer","transferrableObjectToBuffer","errorLocal2Remote","ERROR","stack","errorRemote2Local","cnstr","statsLocal2Remote","stats","STATS","statsData","toBuffer","statsRemote2Local","Stats","fileFlagLocal2Remote","FILEFLAG","flagStr","getFlagString","fileFlagRemote2Local","remoteFlag","bufferLocal2Remote","BUFFER","data","bufferRemote2Local","buffArg","isAPIRequest","isAPIResponse","asyncDownloadFileModern","req","XMLHttpRequest","open","jsonSupported","responseType","onreadystatechange","readyState","status","response","parse","responseText","send","syncDownloadFileModern","overrideMimeType","text","syncDownloadFileIE10","getFileSize","async","getResponseHeader","getFileSizeSync","getFileSizeAsync","isFileInode","inode","isDirInode","isDir","tryToString","msdos2date","date","day","month","year","second","minute","hour","safeToString","useUTF8","ExtendedASCII","byte2str","getASCIIString","startIndex","trim","getJolietString","fromCharCode","pairs","floor","chars","pos","getDate","mon","min","sec","hundrethsSec","getShortFormDate","yearsSince1900","constructSystemUseEntry","bigData","sue","SystemUseEntry","signatureWord","CEEntry","PDEntry","SPEntry","STEntry","EREntry","ESEntry","PXEntry","PNEntry","SLEntry","NMEntry","CLEntry","PLEntry","REEntry","TFEntry","SFEntry","RREntry","constructSystemUseEntries","isoData","entries","getEntries","install","oldRequire","require","BFSRequire","registerFileSystem","Backends","BFSUtils","initialize","rootfs","configure","config","getFileSystem","finish","called","fsc","Create","Errors.ApiError","Errors.ErrorCode","waitCount","finishedIterating","k","forEach","d","defineProperty","EBADF","EFBIG","EROFS","ENOTEMPTY","ENOTSUP","ActionType","super","syscall","__proto__","create","fromJSON","json","readUInt32LE","toJSON","buffer$$1","bufferSize","bytesWritten","write","writeUInt32LE","api_error","freeze","validFlagStrs","flagCache","isReadable","isWriteable","isTruncating","isAppendable","isSynchronous","isExclusive","pathExistsAction","THROW_EXCEPTION","TRUNCATE_FILE","NOP","pathNotExistsAction","CREATE_FILE","FileType","itemType","atime","mtime","ctime","dev","ino","rdev","nlink","blksize","uid","gid","birthtime","fileData","FILE","DIRECTORY","blocks","ceil","readDoubleLE","writeDoubleLE","getTime","clone","isSymbolicLink","SYMLINK","chmod","isSocket","isBlockDevice","isCharacterDevice","isFIFO","wrapCb","FS","F_OK","R_OK","W_OK","X_OK","fdMap","nextFd","rootFS","isAvailable","_toUnixTimestamp","getRootFS","rename","oldPath","newPath","newCb","renameSync","exists","statSync","lstat","lstatSync","truncate","arg2","truncateSync","unlink","unlinkSync","file","getFdForFile","openSync","readFile","filename","readFileSync","writeFile","arg3","writeFileSync","appendFile","appendFileSync","fstat","fd","fd2file","fstatSync","close","closeFd","closeSync","ftruncate","ftruncateSync","fsync","sync","fsyncSync","syncSync","fdatasync","datasync","fdatasyncSync","datasyncSync","arg4","arg5","position","getPos","writeSync","read","bytesRead","buf","readSync","shenanigans","fchown","chown","fchownSync","chownSync","fchmod","numMode","fchmodSync","chmodSync","futimes","utimes","futimesSync","utimesSync","rmdir","rmdirSync","mkdir","readdir","readdirSync","link","srcpath","dstpath","linkSync","symlink","symlinkSync","readlink","readlinkSync","lchown","lchownSync","lchmod","lchmodSync","realpath","realpathSync","watchFile","listener","unwatchFile","watch","access","accessSync","createReadStream","createWriteStream","wrapCallbacks","cbWrapper","_fsMock","fsProto","newFs","isIE","exec","userAgent","toLowerCase","isWebWorker","window","BFSEmscriptenStreamOps","nodefs","getNodeFS","getFS","PATH","getPATH","ERRNO_CODES","getERRNO_CODES","stream","realPath","nfd","flagsToPermissionString","flags","ErrnoError","llseek","whence","BFSEmscriptenNodeOps","getattr","setattr","attr","timestamp","lookup","join2","getMode","createNode","mknod","oldNode","newDir","newName","contents","BFSEmscriptenFS","_FS","_PATH","_ERRNO_CODES","self","flagsToPermissionStringMap","0","1","2","64","65","66","129","193","514","577","578","705","706","1024","1025","1026","1089","1090","1153","1154","1217","1218","4096","4098","node_ops","stream_ops","mount","isLink","parts","reverse","parsedFlags","BaseFileSystem","supportsLinks","diskSpace","openFile","createFile","mustBeFile","parentStats","isLstat","openFileSync","createFileSync","splitPath","split","path.sep","addPaths","doesExist","er","er2","fname","oldCb","err2","isLchmod","isLchown","SynchronousFileSystem","supportsSynch","BaseFile","PreloadFile","BaseFile$$1","_fs","_path","_flag","_stat","_pos","_dirty","_buffer","getBuffer","getStats","getPath","advancePos","delta","setPos","newPos","newBuff","copy","endFp","endRead","supportsProps","isDirty","resetDirty","NoSyncFile","MirrorFile","PreloadFile$$1","_syncSync","AsyncMirror","SynchronousFileSystem$$1","deprecateMsg","_queue","_queueRunning","_isInitialized","_initializeCallbacks","_sync","_async","getName","enqueueOp","apiMethod","userCb","callbacks","copyDirectory","files","copyNextFile","copyItem","copyFile","isReadOnly","checkInitialized","op","doNextOp","shift","description","max","pop","freeGlobal","freeSelf","Function","Symbol","toStringTag","iteratorSymbol","propertyIsEnumerable","freeExports","nodeType","freeModule","moduleExports","nativeIsBuffer","arrayTag","boolTag","dateTag","errorTag","mapTag","numberTag","objectTag","regexpTag","setTag","stringTag","weakMapTag","arrayBufferTag","dataViewTag","float32Tag","float64Tag","int8Tag","int16Tag","int32Tag","uint8Tag","uint8ClampedTag","uint16Tag","uint32Tag","freeProcess","nodeUtil","binding","nodeIsTypedArray","eachOfGeneric","Infinity","eachOfImplementation","mapLimit","mapSeries","callArgs","_defer","rsAstralRange","rsComboMarksRange","reComboHalfMarksRange","rsComboSymbolsRange","rsComboRange","rsVarRange","rsAstral","rsCombo","rsFitz","rsModifier","rsNonAstral","rsRegional","rsSurrPair","rsZWJ","reOptMod","rsOptVar","hasSetImmediate","setImmediate","hasNextTick","nextTick","seq","functions","newargs","nextargs","values","ignoredArgs","CachedDropboxClient","client","_cache","_client","cacheInfo","getCachedDirInfo","_wrap","interceptCb","contentHash","filenames","folderEntries","NO_CONTENT","updateCachedDirInfo","updateCachedInfo","remove","move","src","dest","deleteCachedInfo","getCachedFileInfo","arrayBuffer","performOp","numRun","timeoutDuration","getCachedInfo","putCachedInfo","info","cachedInfo","updateCachedFileInfo","versionTag","DropboxFile","_writeFileStrict","DropboxFileSystem","BaseFileSystem$$1","supportsSymlinks","empty","mainCb","convert","deleteFile","finished","asyncEach","error2","missingPath","isRemoved","_statType","content","dbStat","_makeFile","ArrayBuffer","_remove","errorCode","isAuthenticated","EmscriptenFile","_stream","emPosition","EmscriptenFileSystem","DB_NAME","modeToFileType","utime","FolderAdapter","wrapped","toExport","global$1","_getFS","webkitRequestFileSystem","requestFileSystem","HTML5FSFile","_entry","createWriter","writer","blob","Blob","onwriteend","onerror","HTML5FS","allocate","granted","_readdir","deleteEntry","succ","fullPath","removeRecursively","semaphore","successCount","currentPath","getDirectory","parentDir","path.basename","moveTo","getFile","loadAsFile","fileFromEntry","failedToLoad","loadAsDir","dir","failedToLoadAsFile","exclusive","reader","FileReader","onloadend","event","bfsFile","ev","readAsArrayBuffer","dirEntry","createReader","readEntries","Inode","readUInt16LE","toStats","getSize","writeUInt16LE","update","hasChanged","atimeMs","mtimeMs","ctimeMs","ROOT_NODE_ID","SimpleSyncRWTransaction","store","originalData","modifiedKeys","get","val","stashOldValue","put","overwrite","markModified","del","commit","SyncKeyValueFile","SyncKeyValueFileSystem","makeRootDirectory","clear","beginTransaction","oldParent","oldName","newParent","oldDirNode","findINode","oldDirList","getDirListing","nodeId","newDirNode","newDirList","newNameNode","getINode","newFile","commitNewFile","removeEntry","fileInodeId","_findINode","fileInode","inodeChanged","currTime","dirInode","readDirectory","dirList","addNewNode","currId","retries","parentNode","dirListing","fileNode","dataId","fileNodeId","parentListing","fileName","AsyncKeyValueFile","AsyncKeyValueFileSystem","init","inodes","lists","errorOccurred","theOleSwitcharoo","oldParentList","oldParentINode","newParentList","newParentINode","fileId","completeRename","processInodeAndListings","findINodeAndDirListing","handleDirectoryListings","listing","reroll","committed","InMemoryStore","InMemoryFileSystem","SyncKeyValueFileSystem$$1","indexedDB","mozIndexedDB","webkitIndexedDB","msIndexedDB","IndexedDBROTransaction","onsuccess","target","IndexedDBRWTransaction","arraybuffer","add","_e","IndexedDBStore","storeName","openReq","onupgradeneeded","db","objectStoreNames","contains","deleteObjectStore","createObjectStore","IndexedDBFileSystem","transaction","objectStore","AsyncKeyValueFileSystem$$1","binaryEncoding","supportsBinaryString","localStorage","setItem","getItem","isEncoding","LocalStorageStore","LocalStorageFileSystem","removeItem","MountableFileSystem","mountList","mntMap","rootFs","mountPoint","umount","splice","substr","fs1rv","fs2rv","fsInfo","rv2","_containsMountPt","mountPoints","pt","fsCmdMap","cmds","i$1","fnName","bfsSetImmediate","gScope","timeouts","messageName","canUsePostMessage","importScripts","postMessage","postMessageIsAsync","oldOnMessage","onmessage","handleMessage","source","stopPropagation","cancelBubble","addEventListener","attachEvent","MessageChannel","channel","port1","port2","setImmediate$3","Mutex","_locked","_waiters","lock","unlock","tryLock","isLocked","LockedFS","_mu","getFSUnlocked","resolvedPath","linkString","deletionLogPath","OverlayFile","_syncAsync","UnlockedOverlayFS","writable","readable","_deletedFiles","_deleteLog","_deleteLogUpdatePending","_deleteLogUpdateNeeded","_deleteLogError","_writable","_readable","getOverlayedFileSystems","createParentDirectoriesAsync","createParentDirectories","OverlayFS","callbackArray","_reparseDeletionLog","getDeletionLog","restoreDeletionLog","log","updateLog","checkInitAsync","checkPathAsync","oldErr","oldStats","newErr","newStats","copyDirContents","oldFile","0o777","mkdirErr","readdirErr","checkPath","oldStat","readFileErr","writableExists","readableExists","deletePath","rmdirLower","dirStats","wFiles","rFiles","seenMap","filtered","fPath","fileP","existsWritable","existsReadable","operateOnWritableAsync","operateOnWritable","addition","0o644","statDone","toCreate","createParents","copyToWritable","copyToWritableAsync","pStats","LockedFS$$1","unwrap","CallbackArgumentConverter","_callbacks","_nextId","toRemoteArg","CB","toLocalArg","FileDescriptorArgumentConverter","_fileDescriptors","FD","applyFdAPIRequest","request","fdArg","_applyFdChanges","method","remoteFd","remoteStats","applyStatChanges","WorkerFile","remoteFdId","_remoteFdId","getRemoteFdId","_syncClose","syncClose","WorkerFS","worker","_callbackConverter","_isReadOnly","_supportLinks","_supportProps","_worker","resp","fixedArgs","_argRemote2Local","cbId","attachRemoteListener","argLocal2Remote","requestArgs","fdConverter","argRemote2Local","fixedRequestArgs","specialArg","abortAndSendError","countdown","browserfsMessage","arguments$1","fixedArg","remoteCb","probeResponse","PROBE","_argLocal2Remote","_rpc","methodName","asyncDownloadFile","syncDownloadFile","FileIndex","_index","addPath","DirInode","fromListing","idx","rootInode","queue","pwd","tree","children","FileInode","_ls","fileIterator","getListing","getData","_split_path","dirpath","itemname","addItem","addPathFast","itemNameMark","lastIndexOf","parentPath","substring","itemName","removePath","remItem","child","ls","getInode","setData","XmlHttpRequest","listingUrlOrObj","prefixUrl","charAt","_requestFileSync","baseUrl","FromURL","url","preloadFile","_requestFileSizeAsync","_requestFileSizeSync","_requestFileAsync","fdCast","fdBuff","getXhrPath","filePath","str2byte","charCode","charIdx","extendedChars","ExternalFileAttributeType","inflateRaw","decompressionMethods","CompressionMethod","FileHeader","versionNeeded","compressionMethod","lastModFileTime","rawLastModFileTime","crc32","fileNameLength","extraFieldLength","extraField","totalSize","FileData","header","record","decompress","fcn","compressedSize","uncompressedSize","getHeader","getRecord","getRawData","DataDescriptor","ArchiveExtraDataRecord","extraFieldData","DigitalSignature","signatureData","CentralDirectory","zipData","_filename","produceFilename","versionMadeBy","fileCommentLength","diskNumberStart","internalAttributes","externalAttributes","headerRelativeOffset","rawFileName","fileComment","rawFileComment","isEncrypted","getFileData","EndOfCentralDirectory","diskNumber","cdDiskNumber","cdDiskEntryCount","cdTotalEntryCount","cdSize","cdOffset","cdZipCommentLength","cdZipComment","rawCdZipComment","ZipTOC","directoryEntries","eocd","ZipFS","input","_directoryEntries","_eocd","populateIndex","computeIndex","zipTOC","RegisterDecompressionMethod","getEOCD","cdPtr","cdEnd","computeIndexResponsive","startOffset","endOffset","addToIndex","cd","cdEntries","count","getCentralDirectoryEntry","getCentralDirectoryEntryAt","RangeError","getNumberOfCentralDirectoryEntries","getEndOfCentralDirectory","cdRecord","DEFLATE","chunkSize","STORED","rockRidgeIdentifier","VolumeDescriptor","_data","standardIdentifier","version","PrimaryOrSupplementaryVolumeDescriptor","_root","systemIdentifier","_getString32","volumeIdentifier","volumeSpaceSize","volumeSetSize","volumeSequenceNumber","logicalBlockSize","pathTableSize","locationOfTypeLPathTable","locationOfOptionalTypeLPathTable","locationOfTypeMPathTable","readUInt32BE","locationOfOptionalTypeMPathTable","rootDirectoryEntry","_constructRootDirectoryRecord","rootCheckForRockRidge","volumeSetIdentifier","_getString","publisherIdentifier","dataPreparerIdentifier","applicationIdentifier","copyrightFileIdentifier","abstractFileIdentifier","bibliographicFileIdentifier","volumeCreationDate","volumeModificationDate","volumeExpirationDate","volumeEffectiveDate","fileStructureVersion","applicationUsed","reserved","PrimaryVolumeDescriptor","ISODirectoryRecord","SupplementaryVolumeDescriptor","escapeSequence","third","JolietDirectoryRecord","DirectoryRecord","rockRidgeOffset","_suEntries","_fileOrDir","_rockRidgeOffset","hasRockRidge","getRockRidgeOffset","getDotEntry","_getRockRidgeOffset","extendedAttributeRecordLength","lba","dataLength","recordingDate","fileFlags","fileUnitSize","interleaveGapSize","identifier","_rockRidgeFilename","ident","versionSeparator","getSUEntries","isSymlink","getSymlinkPath","getStr","_getGetString","components","componentRecords","list$1","component","continueFlag","_constructDirectory","_constructSUEntries","nmEntries","getString","suEntries","spEntry","checkBytesPass","extensionIdentifier","bytesSkipped","ISODirectory","JolietDirectory","readUInt16BE","signatureWordString","suVersion","_entries","continuationLba","continuationLbaOffset","continuationLength","identifierLength","descriptorLength","sourceLength","extensionVersion","extensionDescriptor","extensionSource","extensionSequence","fileLinks","devTHigh","devTLow","records","SLComponentRecord","componentLength","childDirectoryLba","parentDirectoryLba","creation","_longFormDates","modify","previousDates","backup","expiration","effective","virtualSizeHigh","virtualSizeLow","tableDepth","Directory","_fileList","_fileMap","_record","iLimit","cl","_constructDirectoryRecord","getFileList","IsoFS","vdTerminatorFound","candidateVDs","vd","_pvd","_name","_getDirectoryRecord","_getStats","newP","dirRec","Emscripten","InMemory","IndexedDB","LocalStorage","wrappedCb","normalizedCb","normalizedOpts","oneArg","EmscriptenFS","FileSystem","Errors","typedArraySupport","foo","createBuffer","K_MAX_LENGTH","encodingOrOffset","allocUnsafe","fromArrayBuffer","fromString","fromObject","assertSize","fill","checked","string","actual","fromArrayLike","isArrayBufferView","numberIsNaN","SlowBuffer","loweredCase","utf8ToBytes","base64ToBytes","slowToString","hexSlice","utf8Slice","asciiSlice","latin1Slice","base64Slice","utf16leSlice","swap","bidirectionalIndexOf","arrayIndexOf","indexSize","arrLength","valLength","foundIndex","found","j","hexWrite","Number","remaining","strLen","parsed","utf8Write","blitBuffer","asciiWrite","asciiToBytes","latin1Write","base64Write","ucs2Write","utf16leToBytes","base64","fromByteArray","res","firstByte","codePoint","bytesPerSequence","secondByte","thirdByte","fourthByte","tempCodePoint","decodeCodePointsArray","codePoints","MAX_ARGUMENTS_LENGTH","ret","out","toHex","bytes","checkOffset","ext","checkInt","checkIEEE754","writeFloat","littleEndian","noAssert","ieee754","writeDouble","base64clean","INVALID_BASE64_RE","units","leadSurrogate","byteArray","hi","lo","toByteArray","dst","isView","INSPECT_MAX_BYTES","kMaxLength","TYPED_ARRAY_SUPPORT","species","configurable","enumerable","poolSize","allocUnsafeSlow","_isBuffer","compare","swap16","swap32","swap64","equals","inspect","match","thisStart","thisEnd","thisCopy","targetCopy","includes","isFinite","_arr","newBuf","readUIntLE","mul","readUIntBE","readUInt8","readIntLE","pow","readIntBE","readInt8","readInt16LE","readInt16BE","readInt32LE","readInt32BE","readFloatLE","readFloatBE","readDoubleBE","writeUIntLE","maxBytes","writeUIntBE","writeUInt8","writeUInt16BE","writeUInt32BE","writeIntLE","sub","writeIntBE","writeInt8","writeInt16LE","writeInt16BE","writeInt32LE","writeInt32BE","writeFloatLE","writeFloatBE","writeDoubleBE","targetStart","set","Duplex","Readable","Writable","allowHalfOpen","onend","_writableState","ended","processNextTick","onEndNT","objectKeys","util","inherits","defineKey","processProxy","Process","initializeTTYs","stdin","stdout","stderr","ctor","superCtor","super_","TempCtor","isBoolean","isNull","isNullOrUndefined","isNumber","isString","isSymbol","isUndefined","isRegExp","re","isDate","isError","isPrimitive","EventEmitter","_events","_maxListeners","defaultMaxListeners","setMaxListeners","emit","handler","listeners","context","addListener","newListener","warned","trace","on","g","removeListener","fired","removeAllListeners","listenerCount","evlistener","emitter","TYPED_OK","Uint16Array","Int32Array","assign","sources","shrinkBuf","fnTyped","arraySet","src_offs","dest_offs","flattenChunks","chunks","l","chunk","fnUntyped","setTyped","Buf8","Buf16","Buf32","Stream","EE","Transform","PassThrough","pipe","ondata","pause","ondrain","resume","didOnEnd","onclose","destroy","cleanup","_isStdio","MAX_LEN","enc","_fill","fillBuf","flen","arg1","TransformState","afterTransform","needTransform","transforming","writecb","writechunk","writeencoding","ts","_transformState","rs","_readableState","reading","needReadable","highWaterMark","_read","_transform","flush","_flush","ws","_write","nop","WriteReq","WritableState","objectMode","writableObjectMode","hwm","defaultHwm","needDrain","ending","noDecode","decodeStrings","defaultEncoding","writing","corked","bufferProcessing","onwrite","writelen","bufferedRequest","lastBufferedRequest","pendingcb","prefinished","errorEmitted","bufferedRequestCount","corkedRequestsFree","CorkedRequest","realHasInstance","writev","_writev","writeAfterEnd","validChunk","state","valid","decodeChunk","bufferShim","writeOrBuffer","isBuf","last","doWrite","onwriteError","onwriteStateUpdate","needFinish","clearBuffer","asyncWrite","afterWrite","onwriteDrain","finishMaybe","holder","prefinish","need","endWritable","_this","browser","internalUtil","deprecate","current","hasInstance","cork","uncork","setDefaultEncoding","posixSplitPath","splitPathRe","normalize","absolute","sep","_removeDuplicateSeps","goodComponents","_i","processed","segment","resolve","resolved","cwd","relative","to","fromSegs","toSegs","upCount","downSegs","seg","dirname","sections","basename","lastPart","lastPartExt","extname","isAbsolute","_makeLong","allParts","base","format","pathObject","_replaceRegex","RegExp","delimiter","posix","win32","prependListener","ReadableState","readableObjectMode","BufferList","pipes","pipesCount","flowing","endEmitted","emittedReadable","readableListening","resumeScheduled","ranOut","awaitDrain","readingMore","decoder","StringDecoder","readableAddChunk","addToFront","chunkInvalid","onEofChunk","skipAdd","emitReadable","maybeReadMore","needMoreData","computeNewHighWaterMark","MAX_HWM","howMuchToRead","head","debug","emitReadable_","flow","maybeReadMore_","pipeOnDrain","EElistenerCount","nReadingNextTick","resume_","fromList","fromListPartial","hasStrings","copyFromBufferString","copyFromBuffer","nb","tail","endReadable","endReadableNT","xs","debugUtil","debuglog","isPaused","setEncoding","nOrig","doRead","pipeOpts","onunpipe","onfinish","cleanedUp","increasedAwaitDrain","unpipe","doEnd","endFn","dests","paused","events","bind","_fromList","assertEncoding","isBufferEncoding","passThroughWrite","utf16DetectIncompleteChar","charReceived","charLength","base64DetectIncompleteChar","surrogateSize","detectIncompleteChar","charBuffer","charStr","available","cr","placeHoldersCount","b64","placeHolders","Arr","L","revLookup","tripletToBase64","num","encodeChunk","uint8","output","extraBytes","maxChunkLength","len2","__dirname","__extends","__","Item","fun","run","NextTickQueue","_draining","_currentQueue","_queueIndex","_drainQueue","_cleanUpNextTick","timeout","clearTimeout","_super","startTime","now","_cwd","platform","argv","execArgv","domain","execPath","env","exitCode","_gid","_uid","versions","http_parser","v8","uv","zlib","ares","icu","openssl","target_defaults","cflags","default_configuration","defines","include_dirs","libraries","variables","clang","host_arch","node_install_npm","node_install_waf","node_prefix","node_shared_cares","node_shared_http_parser","node_shared_libuv","node_shared_zlib","node_shared_v8","node_use_dtrace","node_use_etw","node_use_openssl","node_shared_openssl","strict_aliasing","target_arch","v8_use_snapshot","v8_no_strict_aliasing","visibility","pid","title","arch","_mask","connected","chdir","uptime","exit","getgid","setgid","getuid","setuid","kill","signal","memoryUsage","rss","heapTotal","heapUsed","umask","mask","oldMask","hrtime","timeinfo","performance","secs","TTY","disconnect","isRaw","columns","rows","isTTY","_bufferedWrites","_waitingForWrites","setRawMode","changeColumns","changeRows","isatty","isLE","mLen","nBytes","eLen","eMax","eBias","nBits","s","NaN","rt","abs","LN2","Inflate","utils","windowBits","raw","msg","strm","ZStream","avail_out","zlib_inflate","inflateInit2","Z_OK","GZheader","inflateGetHeader","inflate","inflator","strings","_mode","next_out_utf8","utf8str","dict","dictionary","allowBufError","Z_FINISH","Z_NO_FLUSH","binstring2buf","next_in","avail_in","next_out","Z_NEED_DICT","string2buf","inflateSetDictionary","Z_BUF_ERROR","Z_STREAM_END","onEnd","Z_SYNC_FLUSH","utf8border","buf2string","onData","inflateEnd","ungzip","buf2binstring","STR_APPLY_UIA_OK","STR_APPLY_OK","_utf8len","q","c2","m_pos","str_len","buf_len","c_len","utf16buf","adler32","adler","s1","s2","Z_PARTIAL_FLUSH","Z_FULL_FLUSH","Z_BLOCK","Z_TREES","Z_ERRNO","Z_STREAM_ERROR","Z_DATA_ERROR","Z_NO_COMPRESSION","Z_BEST_SPEED","Z_BEST_COMPRESSION","Z_DEFAULT_COMPRESSION","Z_FILTERED","Z_HUFFMAN_ONLY","Z_RLE","Z_FIXED","Z_DEFAULT_STRATEGY","Z_BINARY","Z_TEXT","Z_UNKNOWN","Z_DEFLATED","makeTable","table","crc","t","crcTable","xflags","os","extra","extra_len","comment","hcrc","BAD","TYPE","_in","_out","beg","dmax","wsize","whave","wnext","s_window","hold","bits","lcode","dcode","lmask","dmask","here","dist","from_source","lencode","distcode","lenbits","distbits","top","dolen","dodist","sane","zswap32","InflateState","havedict","check","total","wbits","ncode","nlen","ndist","have","lens","work","lendyn","distdyn","back","was","inflateResetKeep","total_in","total_out","HEAD","ENOUGH_LENS","ENOUGH_DISTS","inflateReset","inflateReset2","inflateInit","DEF_WBITS","fixedtables","virgin","sym","lenfix","distfix","inflate_table","LENS","DISTS","updatewindow","left","here_bits","here_op","here_val","last_bits","last_op","last_val","hbuf","order","TYPEDO","inf_leave","FLAGS","DICTID","TIME","OS","EXLEN","EXTRA","NAME","COMMENT","HCRC","DICT","CHECK","LEN_","TABLE","COPY_","COPY","LENLENS","CODES","CODELENS","LEN","inflate_fast","LIT","LENEXT","DIST","DISTEXT","MATCH","LENGTH","DONE","MEM","Z_MEM_ERROR","SYNC","data_type","dictid","dictLength","MAX_WBITS","inflateInfo","MAXBITS","lbase","lext","dbase","dext","lens_index","codes","table_index","incr","low","curr","drop","used","huff","base_index","offs","extra_index","-1","-2","-3","-4","-5","-6","READABLE_STREAM","deprecated","webpackPolyfill"],"mappings":"CAAA,SAAAA,EAAAC,GACA,gBAAAC,UAAA,gBAAAC,QACAA,OAAAD,QAAAD,IACA,kBAAAG,gBAAAC,IACAD,UAAAH,GACA,gBAAAC,SACAA,QAAA,UAAAD,IAEAD,EAAA,UAAAC,KACCK,KAAA,WACD,MCAgB,UAAUC,GCN1B,QAAAC,GAAAC,GAGA,GAAAC,EAAAD,GACA,MAAAC,GAAAD,GAAAP,OAGA,IAAAC,GAAAO,EAAAD,IACAP,WACAS,GAAAF,EACAG,QAAA,EAUA,OANAL,GAAAE,GAAAI,KAAAV,EAAAD,QAAAC,IAAAD,QAAAM,GAGAL,EAAAS,QAAA,EAGAT,EAAAD,QAvBA,GAAAQ,KAqCA,OATAF,GAAAM,EAAAP,EAGAC,EAAAO,EAAAL,EAGAF,EAAAQ,EAAA,GAGAR,EAAA,KDgBM,SAASL,EAAQD,EAASM,IAEH,SAASS,EAAQC,EAAQf,EAAQgB,GAAU,YEnCxE,SAAAC,GAAo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ASL,EAAQD,EAASM,GkJnkwBhCL,EAAAD,QAAAM,EAAA,KlJ0kwBM,SAASL,EAAQD,EAASM,GmJ1kwBhCL,EAAAD,QAAAM,EAAA,KnJilwBM,SAASL,EAAQD,IAEM,SAASgB,GoJ1jwBtC,QAAA61D,GAAAlsD,EAAA27D,GAMA,QAAAsN,KACA,IAAAzkB,EAAA,CACA,GAAAxvC,EAAA,oBACA,SAAA1a,OAAAqhE,EACO3mD,GAAA,oBACP/a,QAAAwqD,MAAAkX,GAEA1hE,QAAAC,KAAAyhE,GAEAnX,GAAA,EAEA,MAAAxkD,GAAAtB,MAAAjJ,KAAAwJ,WAhBA,GAAA+V,EAAA,iBACA,MAAAhV,EAGA,IAAAwkD,IAAA,CAeA,OAAAykB,GAWA,QAAAj0D,GAAAlO,GAEA,IACA,IAAAzQ,EAAA4lC,aAAA,SACG,MAAAl2B,GACH,SAEA,GAAAqwB,GAAA//B,EAAA4lC,aAAAn1B,EACA,cAAAsvB,GACA,SAAArzB,OAAAqzB,GAAAvV,cA5DAvrB,EAAAD,QAAA62D,IpJkpwB8Bl2D,KAAKX,EAAU,WAAa,MAAOI,WAI3D,SAASH,EAAQD,GqJ3pwBvBC,EAAAD,QAAA,SAAAC,GAQA,MAPAA,GAAA4zE,kBACA5zE,EAAA42D,UAAA,aACA52D,EAAA4T,SAEA5T,EAAAoyC,YACApyC,EAAA4zE,gBAAA,GAEA5zE,IrJmqwBM,SAASA,EAAQD","file":"../build/browserfs.min.js","sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"BrowserFS\"] = factory();\n\telse\n\t\troot[\"BrowserFS\"] = factory();\n})(this, function() {\nreturn \n\n\n// WEBPACK FOOTER //\n// webpack/universalModuleDefinition","(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"BrowserFS\"] = factory();\n\telse\n\t\troot[\"BrowserFS\"] = factory();\n})(this, function() {\nreturn /******/ (function(modules) { // webpackBootstrap\n/******/ \t// The module cache\n/******/ \tvar installedModules = {};\n/******/\n/******/ \t// The require function\n/******/ \tfunction __webpack_require__(moduleId) {\n/******/\n/******/ \t\t// Check if module is in cache\n/******/ \t\tif(installedModules[moduleId])\n/******/ \t\t\treturn installedModules[moduleId].exports;\n/******/\n/******/ \t\t// Create a new module (and put it into the cache)\n/******/ \t\tvar module = installedModules[moduleId] = {\n/******/ \t\t\texports: {},\n/******/ \t\t\tid: moduleId,\n/******/ \t\t\tloaded: false\n/******/ \t\t};\n/******/\n/******/ \t\t// Execute the module function\n/******/ \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n/******/\n/******/ \t\t// Flag the module as loaded\n/******/ \t\tmodule.loaded = true;\n/******/\n/******/ \t\t// Return the exports of the module\n/******/ \t\treturn module.exports;\n/******/ \t}\n/******/\n/******/\n/******/ \t// expose the modules object (__webpack_modules__)\n/******/ \t__webpack_require__.m = modules;\n/******/\n/******/ \t// expose the module cache\n/******/ \t__webpack_require__.c = installedModules;\n/******/\n/******/ \t// __webpack_public_path__\n/******/ \t__webpack_require__.p = \"\";\n/******/\n/******/ \t// Load entry module and return exports\n/******/ \treturn __webpack_require__(0);\n/******/ })\n/************************************************************************/\n/******/ ([\n/* 0 */\n/***/ function(module, exports, __webpack_require__) {\n\n\t/* WEBPACK VAR INJECTION */(function(Buffer, global, module, process) {'use strict';\n\t\n\tObject.defineProperty(exports, '__esModule', { value: true });\n\t\n\tvar buffer = __webpack_require__(1);\n\tvar path = __webpack_require__(14);\n\t\n\t/**\n\t * Standard libc error codes. Add more to this enum and ErrorStrings as they are\n\t * needed.\n\t * @url http://www.gnu.org/software/libc/manual/html_node/Error-Codes.html\n\t */\n\t/**\n\t * Standard libc error codes. Add more to this enum and ErrorStrings as they are\n\t * needed.\n\t * @url http://www.gnu.org/software/libc/manual/html_node/Error-Codes.html\n\t */ var ErrorCode;\n\t(function (ErrorCode) {\n\t ErrorCode[ErrorCode[\"EPERM\"] = 1] = \"EPERM\";\n\t ErrorCode[ErrorCode[\"ENOENT\"] = 2] = \"ENOENT\";\n\t ErrorCode[ErrorCode[\"EIO\"] = 5] = \"EIO\";\n\t ErrorCode[ErrorCode[\"EBADF\"] = 9] = \"EBADF\";\n\t ErrorCode[ErrorCode[\"EACCES\"] = 13] = \"EACCES\";\n\t ErrorCode[ErrorCode[\"EBUSY\"] = 16] = \"EBUSY\";\n\t ErrorCode[ErrorCode[\"EEXIST\"] = 17] = \"EEXIST\";\n\t ErrorCode[ErrorCode[\"ENOTDIR\"] = 20] = \"ENOTDIR\";\n\t ErrorCode[ErrorCode[\"EISDIR\"] = 21] = \"EISDIR\";\n\t ErrorCode[ErrorCode[\"EINVAL\"] = 22] = \"EINVAL\";\n\t ErrorCode[ErrorCode[\"EFBIG\"] = 27] = \"EFBIG\";\n\t ErrorCode[ErrorCode[\"ENOSPC\"] = 28] = \"ENOSPC\";\n\t ErrorCode[ErrorCode[\"EROFS\"] = 30] = \"EROFS\";\n\t ErrorCode[ErrorCode[\"ENOTEMPTY\"] = 39] = \"ENOTEMPTY\";\n\t ErrorCode[ErrorCode[\"ENOTSUP\"] = 95] = \"ENOTSUP\";\n\t})(ErrorCode || (ErrorCode = {}));\n\t/* tslint:disable:variable-name */\n\t/**\n\t * Strings associated with each error code.\n\t * @hidden\n\t */\n\tvar ErrorStrings = {};\n\tErrorStrings[ErrorCode.EPERM] = 'Operation not permitted.';\n\tErrorStrings[ErrorCode.ENOENT] = 'No such file or directory.';\n\tErrorStrings[ErrorCode.EIO] = 'Input/output error.';\n\tErrorStrings[ErrorCode.EBADF] = 'Bad file descriptor.';\n\tErrorStrings[ErrorCode.EACCES] = 'Permission denied.';\n\tErrorStrings[ErrorCode.EBUSY] = 'Resource busy or locked.';\n\tErrorStrings[ErrorCode.EEXIST] = 'File exists.';\n\tErrorStrings[ErrorCode.ENOTDIR] = 'File is not a directory.';\n\tErrorStrings[ErrorCode.EISDIR] = 'File is a directory.';\n\tErrorStrings[ErrorCode.EINVAL] = 'Invalid argument.';\n\tErrorStrings[ErrorCode.EFBIG] = 'File is too big.';\n\tErrorStrings[ErrorCode.ENOSPC] = 'No space left on disk.';\n\tErrorStrings[ErrorCode.EROFS] = 'Cannot modify a read-only file system.';\n\tErrorStrings[ErrorCode.ENOTEMPTY] = 'Directory is not empty.';\n\tErrorStrings[ErrorCode.ENOTSUP] = 'Operation is not supported.';\n\t/* tslint:enable:variable-name */\n\t/**\n\t * Represents a BrowserFS error. Passed back to applications after a failed\n\t * call to the BrowserFS API.\n\t */\n\tvar ApiError = (function (Error) {\n\t function ApiError(type, message, path$$1) {\n\t if ( message === void 0 ) message = ErrorStrings[type];\n\t\n\t Error.call(this, message);\n\t // Unsupported.\n\t this.syscall = \"\";\n\t this.errno = type;\n\t this.code = ErrorCode[type];\n\t this.path = path$$1;\n\t this.stack = new Error().stack;\n\t this.message = \"Error: \" + (this.code) + \": \" + message + (this.path ? (\", '\" + (this.path) + \"'\") : '');\n\t }\n\t\n\t if ( Error ) ApiError.__proto__ = Error;\n\t ApiError.prototype = Object.create( Error && Error.prototype );\n\t ApiError.prototype.constructor = ApiError;\n\t ApiError.fromJSON = function fromJSON (json) {\n\t var err = new ApiError(0);\n\t err.errno = json.errno;\n\t err.code = json.code;\n\t err.path = json.path;\n\t err.stack = json.stack;\n\t err.message = json.message;\n\t return err;\n\t };\n\t /**\n\t * Creates an ApiError object from a buffer.\n\t */\n\t ApiError.fromBuffer = function fromBuffer (buffer$$1, i) {\n\t if ( i === void 0 ) i = 0;\n\t\n\t return ApiError.fromJSON(JSON.parse(buffer$$1.toString('utf8', i + 4, i + 4 + buffer$$1.readUInt32LE(i))));\n\t };\n\t ApiError.FileError = function FileError (code, p) {\n\t return new ApiError(code, ErrorStrings[code], p);\n\t };\n\t ApiError.ENOENT = function ENOENT (path$$1) {\n\t return this.FileError(ErrorCode.ENOENT, path$$1);\n\t };\n\t ApiError.EEXIST = function EEXIST (path$$1) {\n\t return this.FileError(ErrorCode.EEXIST, path$$1);\n\t };\n\t ApiError.EISDIR = function EISDIR (path$$1) {\n\t return this.FileError(ErrorCode.EISDIR, path$$1);\n\t };\n\t ApiError.ENOTDIR = function ENOTDIR (path$$1) {\n\t return this.FileError(ErrorCode.ENOTDIR, path$$1);\n\t };\n\t ApiError.EPERM = function EPERM (path$$1) {\n\t return this.FileError(ErrorCode.EPERM, path$$1);\n\t };\n\t ApiError.ENOTEMPTY = function ENOTEMPTY (path$$1) {\n\t return this.FileError(ErrorCode.ENOTEMPTY, path$$1);\n\t };\n\t /**\n\t * @return A friendly error message.\n\t */\n\t ApiError.prototype.toString = function toString () {\n\t return this.message;\n\t };\n\t ApiError.prototype.toJSON = function toJSON () {\n\t return {\n\t errno: this.errno,\n\t code: this.code,\n\t path: this.path,\n\t stack: this.stack,\n\t message: this.message\n\t };\n\t };\n\t /**\n\t * Writes the API error into a buffer.\n\t */\n\t ApiError.prototype.writeToBuffer = function writeToBuffer (buffer$$1, i) {\n\t if ( buffer$$1 === void 0 ) buffer$$1 = Buffer.alloc(this.bufferSize());\n\t if ( i === void 0 ) i = 0;\n\t\n\t var bytesWritten = buffer$$1.write(JSON.stringify(this.toJSON()), i + 4);\n\t buffer$$1.writeUInt32LE(bytesWritten, i);\n\t return buffer$$1;\n\t };\n\t /**\n\t * The size of the API error in buffer-form in bytes.\n\t */\n\t ApiError.prototype.bufferSize = function bufferSize () {\n\t // 4 bytes for string length.\n\t return 4 + Buffer.byteLength(JSON.stringify(this.toJSON()));\n\t };\n\t\n\t return ApiError;\n\t }(Error));\n\t\n\t\n\tvar api_error = Object.freeze({\n\t\tget ErrorCode () { return ErrorCode; },\n\t\tErrorStrings: ErrorStrings,\n\t\tApiError: ApiError\n\t});\n\t\n\tvar ActionType;\n\t(function (ActionType) {\n\t // Indicates that the code should not do anything.\n\t ActionType[ActionType[\"NOP\"] = 0] = \"NOP\";\n\t // Indicates that the code should throw an exception.\n\t ActionType[ActionType[\"THROW_EXCEPTION\"] = 1] = \"THROW_EXCEPTION\";\n\t // Indicates that the code should truncate the file, but only if it is a file.\n\t ActionType[ActionType[\"TRUNCATE_FILE\"] = 2] = \"TRUNCATE_FILE\";\n\t // Indicates that the code should create the file.\n\t ActionType[ActionType[\"CREATE_FILE\"] = 3] = \"CREATE_FILE\";\n\t})(ActionType || (ActionType = {}));\n\t/**\n\t * Represents one of the following file flags. A convenience object.\n\t *\n\t * * `'r'` - Open file for reading. An exception occurs if the file does not exist.\n\t * * `'r+'` - Open file for reading and writing. An exception occurs if the file does not exist.\n\t * * `'rs'` - Open file for reading in synchronous mode. Instructs the filesystem to not cache writes.\n\t * * `'rs+'` - Open file for reading and writing, and opens the file in synchronous mode.\n\t * * `'w'` - Open file for writing. The file is created (if it does not exist) or truncated (if it exists).\n\t * * `'wx'` - Like 'w' but opens the file in exclusive mode.\n\t * * `'w+'` - Open file for reading and writing. The file is created (if it does not exist) or truncated (if it exists).\n\t * * `'wx+'` - Like 'w+' but opens the file in exclusive mode.\n\t * * `'a'` - Open file for appending. The file is created if it does not exist.\n\t * * `'ax'` - Like 'a' but opens the file in exclusive mode.\n\t * * `'a+'` - Open file for reading and appending. The file is created if it does not exist.\n\t * * `'ax+'` - Like 'a+' but opens the file in exclusive mode.\n\t *\n\t * Exclusive mode ensures that the file path is newly created.\n\t */\n\tvar FileFlag = function FileFlag(flagStr) {\n\t this.flagStr = flagStr;\n\t if (FileFlag.validFlagStrs.indexOf(flagStr) < 0) {\n\t throw new ApiError(ErrorCode.EINVAL, \"Invalid flag: \" + flagStr);\n\t }\n\t};\n\t/**\n\t * Get an object representing the given file flag.\n\t * @param modeStr The string representing the flag\n\t * @return The FileFlag object representing the flag\n\t * @throw when the flag string is invalid\n\t */\n\tFileFlag.getFileFlag = function getFileFlag (flagStr) {\n\t // Check cache first.\n\t if (FileFlag.flagCache.hasOwnProperty(flagStr)) {\n\t return FileFlag.flagCache[flagStr];\n\t }\n\t return FileFlag.flagCache[flagStr] = new FileFlag(flagStr);\n\t};\n\t/**\n\t * Get the underlying flag string for this flag.\n\t */\n\tFileFlag.prototype.getFlagString = function getFlagString () {\n\t return this.flagStr;\n\t};\n\t/**\n\t * Returns true if the file is readable.\n\t */\n\tFileFlag.prototype.isReadable = function isReadable () {\n\t return this.flagStr.indexOf('r') !== -1 || this.flagStr.indexOf('+') !== -1;\n\t};\n\t/**\n\t * Returns true if the file is writeable.\n\t */\n\tFileFlag.prototype.isWriteable = function isWriteable () {\n\t return this.flagStr.indexOf('w') !== -1 || this.flagStr.indexOf('a') !== -1 || this.flagStr.indexOf('+') !== -1;\n\t};\n\t/**\n\t * Returns true if the file mode should truncate.\n\t */\n\tFileFlag.prototype.isTruncating = function isTruncating () {\n\t return this.flagStr.indexOf('w') !== -1;\n\t};\n\t/**\n\t * Returns true if the file is appendable.\n\t */\n\tFileFlag.prototype.isAppendable = function isAppendable () {\n\t return this.flagStr.indexOf('a') !== -1;\n\t};\n\t/**\n\t * Returns true if the file is open in synchronous mode.\n\t */\n\tFileFlag.prototype.isSynchronous = function isSynchronous () {\n\t return this.flagStr.indexOf('s') !== -1;\n\t};\n\t/**\n\t * Returns true if the file is open in exclusive mode.\n\t */\n\tFileFlag.prototype.isExclusive = function isExclusive () {\n\t return this.flagStr.indexOf('x') !== -1;\n\t};\n\t/**\n\t * Returns one of the static fields on this object that indicates the\n\t * appropriate response to the path existing.\n\t */\n\tFileFlag.prototype.pathExistsAction = function pathExistsAction () {\n\t if (this.isExclusive()) {\n\t return ActionType.THROW_EXCEPTION;\n\t }\n\t else if (this.isTruncating()) {\n\t return ActionType.TRUNCATE_FILE;\n\t }\n\t else {\n\t return ActionType.NOP;\n\t }\n\t};\n\t/**\n\t * Returns one of the static fields on this object that indicates the\n\t * appropriate response to the path not existing.\n\t */\n\tFileFlag.prototype.pathNotExistsAction = function pathNotExistsAction () {\n\t if ((this.isWriteable() || this.isAppendable()) && this.flagStr !== 'r+') {\n\t return ActionType.CREATE_FILE;\n\t }\n\t else {\n\t return ActionType.THROW_EXCEPTION;\n\t }\n\t};\n\t// Contains cached FileMode instances.\n\tFileFlag.flagCache = {};\n\t// Array of valid mode strings.\n\tFileFlag.validFlagStrs = ['r', 'r+', 'rs', 'rs+', 'w', 'wx', 'w+', 'wx+', 'a', 'ax', 'a+', 'ax+'];\n\t\n\t/**\n\t * Indicates the type of the given file. Applied to 'mode'.\n\t */\n\tvar FileType;\n\t(function (FileType) {\n\t FileType[FileType[\"FILE\"] = 32768] = \"FILE\";\n\t FileType[FileType[\"DIRECTORY\"] = 16384] = \"DIRECTORY\";\n\t FileType[FileType[\"SYMLINK\"] = 40960] = \"SYMLINK\";\n\t})(FileType || (FileType = {}));\n\t/**\n\t * Emulation of Node's `fs.Stats` object.\n\t *\n\t * Attribute descriptions are from `man 2 stat'\n\t * @see http://nodejs.org/api/fs.html#fs_class_fs_stats\n\t * @see http://man7.org/linux/man-pages/man2/stat.2.html\n\t */\n\tvar Stats = function Stats(itemType, size, mode, atime, mtime, ctime) {\n\t if ( atime === void 0 ) atime = new Date();\n\t if ( mtime === void 0 ) mtime = new Date();\n\t if ( ctime === void 0 ) ctime = new Date();\n\t\n\t this.size = size;\n\t this.atime = atime;\n\t this.mtime = mtime;\n\t this.ctime = ctime;\n\t /**\n\t * UNSUPPORTED ATTRIBUTES\n\t * I assume no one is going to need these details, although we could fake\n\t * appropriate values if need be.\n\t */\n\t // ID of device containing file\n\t this.dev = 0;\n\t // inode number\n\t this.ino = 0;\n\t // device ID (if special file)\n\t this.rdev = 0;\n\t // number of hard links\n\t this.nlink = 1;\n\t // blocksize for file system I/O\n\t this.blksize = 4096;\n\t // @todo Maybe support these? atm, it's a one-user filesystem.\n\t // user ID of owner\n\t this.uid = 0;\n\t // group ID of owner\n\t this.gid = 0;\n\t // time file was created (currently unsupported)\n\t this.birthtime = new Date(0);\n\t // XXX: Some file systems stash data on stats objects.\n\t this.fileData = null;\n\t if (!mode) {\n\t switch (itemType) {\n\t case FileType.FILE:\n\t this.mode = 0x1a4;\n\t break;\n\t case FileType.DIRECTORY:\n\t default:\n\t this.mode = 0x1ff;\n\t }\n\t }\n\t else {\n\t this.mode = mode;\n\t }\n\t // number of 512B blocks allocated\n\t this.blocks = Math.ceil(size / 512);\n\t // Check if mode also includes top-most bits, which indicate the file's\n\t // type.\n\t if (this.mode < 0x1000) {\n\t this.mode |= itemType;\n\t }\n\t};\n\tStats.fromBuffer = function fromBuffer (buffer$$1) {\n\t var size = buffer$$1.readUInt32LE(0), mode = buffer$$1.readUInt32LE(4), atime = buffer$$1.readDoubleLE(8), mtime = buffer$$1.readDoubleLE(16), ctime = buffer$$1.readDoubleLE(24);\n\t return new Stats(mode & 0xF000, size, mode & 0xFFF, new Date(atime), new Date(mtime), new Date(ctime));\n\t};\n\tStats.prototype.toBuffer = function toBuffer () {\n\t var buffer$$1 = Buffer.alloc(32);\n\t buffer$$1.writeUInt32LE(this.size, 0);\n\t buffer$$1.writeUInt32LE(this.mode, 4);\n\t buffer$$1.writeDoubleLE(this.atime.getTime(), 8);\n\t buffer$$1.writeDoubleLE(this.mtime.getTime(), 16);\n\t buffer$$1.writeDoubleLE(this.ctime.getTime(), 24);\n\t return buffer$$1;\n\t};\n\t/**\n\t * **Nonstandard**: Clone the stats object.\n\t * @return [BrowserFS.node.fs.Stats]\n\t */\n\tStats.prototype.clone = function clone () {\n\t return new Stats(this.mode & 0xF000, this.size, this.mode & 0xFFF, this.atime, this.mtime, this.ctime);\n\t};\n\t/**\n\t * @return [Boolean] True if this item is a file.\n\t */\n\tStats.prototype.isFile = function isFile () {\n\t return (this.mode & 0xF000) === FileType.FILE;\n\t};\n\t/**\n\t * @return [Boolean] True if this item is a directory.\n\t */\n\tStats.prototype.isDirectory = function isDirectory () {\n\t return (this.mode & 0xF000) === FileType.DIRECTORY;\n\t};\n\t/**\n\t * @return [Boolean] True if this item is a symbolic link (only valid through lstat)\n\t */\n\tStats.prototype.isSymbolicLink = function isSymbolicLink () {\n\t return (this.mode & 0xF000) === FileType.SYMLINK;\n\t};\n\t/**\n\t * Change the mode of the file. We use this helper function to prevent messing\n\t * up the type of the file, which is encoded in mode.\n\t */\n\tStats.prototype.chmod = function chmod (mode) {\n\t this.mode = (this.mode & 0xF000) | mode;\n\t};\n\t// We don't support the following types of files.\n\tStats.prototype.isSocket = function isSocket () {\n\t return false;\n\t};\n\tStats.prototype.isBlockDevice = function isBlockDevice () {\n\t return false;\n\t};\n\tStats.prototype.isCharacterDevice = function isCharacterDevice () {\n\t return false;\n\t};\n\tStats.prototype.isFIFO = function isFIFO () {\n\t return false;\n\t};\n\t\n\t/**\n\t * Wraps a callback function. Used for unit testing. Defaults to a NOP.\n\t * @hidden\n\t */\n\tvar wrapCb = function (cb, numArgs) {\n\t return cb;\n\t};\n\t/**\n\t * @hidden\n\t */\n\tfunction assertRoot(fs) {\n\t if (fs) {\n\t return fs;\n\t }\n\t throw new ApiError(ErrorCode.EIO, \"Initialize BrowserFS with a file system using BrowserFS.initialize(filesystem)\");\n\t}\n\t/**\n\t * @hidden\n\t */\n\tfunction normalizeMode(mode, def) {\n\t switch (typeof mode) {\n\t case 'number':\n\t // (path, flag, mode, cb?)\n\t return mode;\n\t case 'string':\n\t // (path, flag, modeString, cb?)\n\t var trueMode = parseInt(mode, 8);\n\t if (!isNaN(trueMode)) {\n\t return trueMode;\n\t }\n\t // Invalid string.\n\t return def;\n\t default:\n\t return def;\n\t }\n\t}\n\t/**\n\t * @hidden\n\t */\n\tfunction normalizeTime(time) {\n\t if (time instanceof Date) {\n\t return time;\n\t }\n\t else if (typeof time === 'number') {\n\t return new Date(time * 1000);\n\t }\n\t else {\n\t throw new ApiError(ErrorCode.EINVAL, \"Invalid time.\");\n\t }\n\t}\n\t/**\n\t * @hidden\n\t */\n\tfunction normalizePath(p) {\n\t // Node doesn't allow null characters in paths.\n\t if (p.indexOf('\\u0000') >= 0) {\n\t throw new ApiError(ErrorCode.EINVAL, 'Path must be a string without null bytes.');\n\t }\n\t else if (p === '') {\n\t throw new ApiError(ErrorCode.EINVAL, 'Path must not be empty.');\n\t }\n\t return path.resolve(p);\n\t}\n\t/**\n\t * @hidden\n\t */\n\tfunction normalizeOptions(options, defEnc, defFlag, defMode) {\n\t switch (typeof options) {\n\t case 'object':\n\t return {\n\t encoding: typeof options['encoding'] !== 'undefined' ? options['encoding'] : defEnc,\n\t flag: typeof options['flag'] !== 'undefined' ? options['flag'] : defFlag,\n\t mode: normalizeMode(options['mode'], defMode)\n\t };\n\t case 'string':\n\t return {\n\t encoding: options,\n\t flag: defFlag,\n\t mode: defMode\n\t };\n\t default:\n\t return {\n\t encoding: defEnc,\n\t flag: defFlag,\n\t mode: defMode\n\t };\n\t }\n\t}\n\t/**\n\t * The default callback is a NOP.\n\t * @hidden\n\t * @private\n\t */\n\tfunction nopCb() {\n\t // NOP.\n\t}\n\t/**\n\t * The node frontend to all filesystems.\n\t * This layer handles:\n\t *\n\t * * Sanity checking inputs.\n\t * * Normalizing paths.\n\t * * Resetting stack depth for asynchronous operations which may not go through\n\t * the browser by wrapping all input callbacks using `setImmediate`.\n\t * * Performing the requested operation through the filesystem or the file\n\t * descriptor, as appropriate.\n\t * * Handling optional arguments and setting default arguments.\n\t * @see http://nodejs.org/api/fs.html\n\t */\n\tvar FS = function FS() {\n\t /* tslint:enable:variable-name */\n\t this.F_OK = 0;\n\t this.R_OK = 4;\n\t this.W_OK = 2;\n\t this.X_OK = 1;\n\t this.root = null;\n\t this.fdMap = {};\n\t this.nextFd = 100;\n\t};\n\tFS.prototype.initialize = function initialize (rootFS) {\n\t if (!rootFS.constructor.isAvailable()) {\n\t throw new ApiError(ErrorCode.EINVAL, 'Tried to instantiate BrowserFS with an unavailable file system.');\n\t }\n\t return this.root = rootFS;\n\t};\n\t/**\n\t * converts Date or number to a fractional UNIX timestamp\n\t * Grabbed from NodeJS sources (lib/fs.js)\n\t */\n\tFS.prototype._toUnixTimestamp = function _toUnixTimestamp (time) {\n\t if (typeof time === 'number') {\n\t return time;\n\t }\n\t else if (time instanceof Date) {\n\t return time.getTime() / 1000;\n\t }\n\t throw new Error(\"Cannot parse time: \" + time);\n\t};\n\t/**\n\t * **NONSTANDARD**: Grab the FileSystem instance that backs this API.\n\t * @return [BrowserFS.FileSystem | null] Returns null if the file system has\n\t * not been initialized.\n\t */\n\tFS.prototype.getRootFS = function getRootFS () {\n\t if (this.root) {\n\t return this.root;\n\t }\n\t else {\n\t return null;\n\t }\n\t};\n\t// FILE OR DIRECTORY METHODS\n\t/**\n\t * Asynchronous rename. No arguments other than a possible exception are given\n\t * to the completion callback.\n\t * @param oldPath\n\t * @param newPath\n\t * @param callback\n\t */\n\tFS.prototype.rename = function rename (oldPath, newPath, cb) {\n\t if ( cb === void 0 ) cb = nopCb;\n\t\n\t var newCb = wrapCb(cb, 1);\n\t try {\n\t assertRoot(this.root).rename(normalizePath(oldPath), normalizePath(newPath), newCb);\n\t }\n\t catch (e) {\n\t newCb(e);\n\t }\n\t};\n\t/**\n\t * Synchronous rename.\n\t * @param oldPath\n\t * @param newPath\n\t */\n\tFS.prototype.renameSync = function renameSync (oldPath, newPath) {\n\t assertRoot(this.root).renameSync(normalizePath(oldPath), normalizePath(newPath));\n\t};\n\t/**\n\t * Test whether or not the given path exists by checking with the file system.\n\t * Then call the callback argument with either true or false.\n\t * @example Sample invocation\n\t * fs.exists('/etc/passwd', function (exists) {\n\t * util.debug(exists ? \"it's there\" : \"no passwd!\");\n\t * });\n\t * @param path\n\t * @param callback\n\t */\n\tFS.prototype.exists = function exists (path$$1, cb) {\n\t if ( cb === void 0 ) cb = nopCb;\n\t\n\t var newCb = wrapCb(cb, 1);\n\t try {\n\t return assertRoot(this.root).exists(normalizePath(path$$1), newCb);\n\t }\n\t catch (e) {\n\t // Doesn't return an error. If something bad happens, we assume it just\n\t // doesn't exist.\n\t return newCb(false);\n\t }\n\t};\n\t/**\n\t * Test whether or not the given path exists by checking with the file system.\n\t * @param path\n\t * @return [boolean]\n\t */\n\tFS.prototype.existsSync = function existsSync (path$$1) {\n\t try {\n\t return assertRoot(this.root).existsSync(normalizePath(path$$1));\n\t }\n\t catch (e) {\n\t // Doesn't return an error. If something bad happens, we assume it just\n\t // doesn't exist.\n\t return false;\n\t }\n\t};\n\t/**\n\t * Asynchronous `stat`.\n\t * @param path\n\t * @param callback\n\t */\n\tFS.prototype.stat = function stat (path$$1, cb) {\n\t if ( cb === void 0 ) cb = nopCb;\n\t\n\t var newCb = wrapCb(cb, 2);\n\t try {\n\t return assertRoot(this.root).stat(normalizePath(path$$1), false, newCb);\n\t }\n\t catch (e) {\n\t return newCb(e);\n\t }\n\t};\n\t/**\n\t * Synchronous `stat`.\n\t * @param path\n\t * @return [BrowserFS.node.fs.Stats]\n\t */\n\tFS.prototype.statSync = function statSync (path$$1) {\n\t return assertRoot(this.root).statSync(normalizePath(path$$1), false);\n\t};\n\t/**\n\t * Asynchronous `lstat`.\n\t * `lstat()` is identical to `stat()`, except that if path is a symbolic link,\n\t * then the link itself is stat-ed, not the file that it refers to.\n\t * @param path\n\t * @param callback\n\t */\n\tFS.prototype.lstat = function lstat (path$$1, cb) {\n\t if ( cb === void 0 ) cb = nopCb;\n\t\n\t var newCb = wrapCb(cb, 2);\n\t try {\n\t return assertRoot(this.root).stat(normalizePath(path$$1), true, newCb);\n\t }\n\t catch (e) {\n\t return newCb(e);\n\t }\n\t};\n\t/**\n\t * Synchronous `lstat`.\n\t * `lstat()` is identical to `stat()`, except that if path is a symbolic link,\n\t * then the link itself is stat-ed, not the file that it refers to.\n\t * @param path\n\t * @return [BrowserFS.node.fs.Stats]\n\t */\n\tFS.prototype.lstatSync = function lstatSync (path$$1) {\n\t return assertRoot(this.root).statSync(normalizePath(path$$1), true);\n\t};\n\tFS.prototype.truncate = function truncate (path$$1, arg2, cb) {\n\t if ( arg2 === void 0 ) arg2 = 0;\n\t if ( cb === void 0 ) cb = nopCb;\n\t\n\t var len = 0;\n\t if (typeof arg2 === 'function') {\n\t cb = arg2;\n\t }\n\t else if (typeof arg2 === 'number') {\n\t len = arg2;\n\t }\n\t var newCb = wrapCb(cb, 1);\n\t try {\n\t if (len < 0) {\n\t throw new ApiError(ErrorCode.EINVAL);\n\t }\n\t return assertRoot(this.root).truncate(normalizePath(path$$1), len, newCb);\n\t }\n\t catch (e) {\n\t return newCb(e);\n\t }\n\t};\n\t/**\n\t * Synchronous `truncate`.\n\t * @param path\n\t * @param len\n\t */\n\tFS.prototype.truncateSync = function truncateSync (path$$1, len) {\n\t if ( len === void 0 ) len = 0;\n\t\n\t if (len < 0) {\n\t throw new ApiError(ErrorCode.EINVAL);\n\t }\n\t return assertRoot(this.root).truncateSync(normalizePath(path$$1), len);\n\t};\n\t/**\n\t * Asynchronous `unlink`.\n\t * @param path\n\t * @param callback\n\t */\n\tFS.prototype.unlink = function unlink (path$$1, cb) {\n\t if ( cb === void 0 ) cb = nopCb;\n\t\n\t var newCb = wrapCb(cb, 1);\n\t try {\n\t return assertRoot(this.root).unlink(normalizePath(path$$1), newCb);\n\t }\n\t catch (e) {\n\t return newCb(e);\n\t }\n\t};\n\t/**\n\t * Synchronous `unlink`.\n\t * @param path\n\t */\n\tFS.prototype.unlinkSync = function unlinkSync (path$$1) {\n\t return assertRoot(this.root).unlinkSync(normalizePath(path$$1));\n\t};\n\tFS.prototype.open = function open (path$$1, flag, arg2, cb) {\n\t var this$1 = this;\n\t if ( cb === void 0 ) cb = nopCb;\n\t\n\t var mode = normalizeMode(arg2, 0x1a4);\n\t cb = typeof arg2 === 'function' ? arg2 : cb;\n\t var newCb = wrapCb(cb, 2);\n\t try {\n\t assertRoot(this.root).open(normalizePath(path$$1), FileFlag.getFileFlag(flag), mode, function (e, file) {\n\t if (file) {\n\t newCb(e, this$1.getFdForFile(file));\n\t }\n\t else {\n\t newCb(e);\n\t }\n\t });\n\t }\n\t catch (e) {\n\t newCb(e);\n\t }\n\t};\n\t/**\n\t * Synchronous file open.\n\t * @see http://www.manpagez.com/man/2/open/\n\t * @param path\n\t * @param flags\n\t * @param mode defaults to `0644`\n\t * @return [BrowserFS.File]\n\t */\n\tFS.prototype.openSync = function openSync (path$$1, flag, mode) {\n\t if ( mode === void 0 ) mode = 0x1a4;\n\t\n\t return this.getFdForFile(assertRoot(this.root).openSync(normalizePath(path$$1), FileFlag.getFileFlag(flag), normalizeMode(mode, 0x1a4)));\n\t};\n\tFS.prototype.readFile = function readFile (filename, arg2, cb) {\n\t if ( arg2 === void 0 ) arg2 = {};\n\t if ( cb === void 0 ) cb = nopCb;\n\t\n\t var options = normalizeOptions(arg2, null, 'r', null);\n\t cb = typeof arg2 === 'function' ? arg2 : cb;\n\t var newCb = wrapCb(cb, 2);\n\t try {\n\t var flag = FileFlag.getFileFlag(options['flag']);\n\t if (!flag.isReadable()) {\n\t return newCb(new ApiError(ErrorCode.EINVAL, 'Flag passed to readFile must allow for reading.'));\n\t }\n\t return assertRoot(this.root).readFile(normalizePath(filename), options.encoding, flag, newCb);\n\t }\n\t catch (e) {\n\t return newCb(e);\n\t }\n\t};\n\tFS.prototype.readFileSync = function readFileSync (filename, arg2) {\n\t if ( arg2 === void 0 ) arg2 = {};\n\t\n\t var options = normalizeOptions(arg2, null, 'r', null);\n\t var flag = FileFlag.getFileFlag(options.flag);\n\t if (!flag.isReadable()) {\n\t throw new ApiError(ErrorCode.EINVAL, 'Flag passed to readFile must allow for reading.');\n\t }\n\t return assertRoot(this.root).readFileSync(normalizePath(filename), options.encoding, flag);\n\t};\n\tFS.prototype.writeFile = function writeFile (filename, data, arg3, cb) {\n\t if ( arg3 === void 0 ) arg3 = {};\n\t if ( cb === void 0 ) cb = nopCb;\n\t\n\t var options = normalizeOptions(arg3, 'utf8', 'w', 0x1a4);\n\t cb = typeof arg3 === 'function' ? arg3 : cb;\n\t var newCb = wrapCb(cb, 1);\n\t try {\n\t var flag = FileFlag.getFileFlag(options.flag);\n\t if (!flag.isWriteable()) {\n\t return newCb(new ApiError(ErrorCode.EINVAL, 'Flag passed to writeFile must allow for writing.'));\n\t }\n\t return assertRoot(this.root).writeFile(normalizePath(filename), data, options.encoding, flag, options.mode, newCb);\n\t }\n\t catch (e) {\n\t return newCb(e);\n\t }\n\t};\n\tFS.prototype.writeFileSync = function writeFileSync (filename, data, arg3) {\n\t var options = normalizeOptions(arg3, 'utf8', 'w', 0x1a4);\n\t var flag = FileFlag.getFileFlag(options.flag);\n\t if (!flag.isWriteable()) {\n\t throw new ApiError(ErrorCode.EINVAL, 'Flag passed to writeFile must allow for writing.');\n\t }\n\t return assertRoot(this.root).writeFileSync(normalizePath(filename), data, options.encoding, flag, options.mode);\n\t};\n\tFS.prototype.appendFile = function appendFile (filename, data, arg3, cb) {\n\t if ( cb === void 0 ) cb = nopCb;\n\t\n\t var options = normalizeOptions(arg3, 'utf8', 'a', 0x1a4);\n\t cb = typeof arg3 === 'function' ? arg3 : cb;\n\t var newCb = wrapCb(cb, 1);\n\t try {\n\t var flag = FileFlag.getFileFlag(options.flag);\n\t if (!flag.isAppendable()) {\n\t return newCb(new ApiError(ErrorCode.EINVAL, 'Flag passed to appendFile must allow for appending.'));\n\t }\n\t assertRoot(this.root).appendFile(normalizePath(filename), data, options.encoding, flag, options.mode, newCb);\n\t }\n\t catch (e) {\n\t newCb(e);\n\t }\n\t};\n\tFS.prototype.appendFileSync = function appendFileSync (filename, data, arg3) {\n\t var options = normalizeOptions(arg3, 'utf8', 'a', 0x1a4);\n\t var flag = FileFlag.getFileFlag(options.flag);\n\t if (!flag.isAppendable()) {\n\t throw new ApiError(ErrorCode.EINVAL, 'Flag passed to appendFile must allow for appending.');\n\t }\n\t return assertRoot(this.root).appendFileSync(normalizePath(filename), data, options.encoding, flag, options.mode);\n\t};\n\t// FILE DESCRIPTOR METHODS\n\t/**\n\t * Asynchronous `fstat`.\n\t * `fstat()` is identical to `stat()`, except that the file to be stat-ed is\n\t * specified by the file descriptor `fd`.\n\t * @param fd\n\t * @param callback\n\t */\n\tFS.prototype.fstat = function fstat (fd, cb) {\n\t if ( cb === void 0 ) cb = nopCb;\n\t\n\t var newCb = wrapCb(cb, 2);\n\t try {\n\t var file = this.fd2file(fd);\n\t file.stat(newCb);\n\t }\n\t catch (e) {\n\t newCb(e);\n\t }\n\t};\n\t/**\n\t * Synchronous `fstat`.\n\t * `fstat()` is identical to `stat()`, except that the file to be stat-ed is\n\t * specified by the file descriptor `fd`.\n\t * @param fd\n\t * @return [BrowserFS.node.fs.Stats]\n\t */\n\tFS.prototype.fstatSync = function fstatSync (fd) {\n\t return this.fd2file(fd).statSync();\n\t};\n\t/**\n\t * Asynchronous close.\n\t * @param fd\n\t * @param callback\n\t */\n\tFS.prototype.close = function close (fd, cb) {\n\t var this$1 = this;\n\t if ( cb === void 0 ) cb = nopCb;\n\t\n\t var newCb = wrapCb(cb, 1);\n\t try {\n\t this.fd2file(fd).close(function (e) {\n\t if (!e) {\n\t this$1.closeFd(fd);\n\t }\n\t newCb(e);\n\t });\n\t }\n\t catch (e) {\n\t newCb(e);\n\t }\n\t};\n\t/**\n\t * Synchronous close.\n\t * @param fd\n\t */\n\tFS.prototype.closeSync = function closeSync (fd) {\n\t this.fd2file(fd).closeSync();\n\t this.closeFd(fd);\n\t};\n\tFS.prototype.ftruncate = function ftruncate (fd, arg2, cb) {\n\t if ( cb === void 0 ) cb = nopCb;\n\t\n\t var length = typeof arg2 === 'number' ? arg2 : 0;\n\t cb = typeof arg2 === 'function' ? arg2 : cb;\n\t var newCb = wrapCb(cb, 1);\n\t try {\n\t var file = this.fd2file(fd);\n\t if (length < 0) {\n\t throw new ApiError(ErrorCode.EINVAL);\n\t }\n\t file.truncate(length, newCb);\n\t }\n\t catch (e) {\n\t newCb(e);\n\t }\n\t};\n\t/**\n\t * Synchronous ftruncate.\n\t * @param fd\n\t * @param len\n\t */\n\tFS.prototype.ftruncateSync = function ftruncateSync (fd, len) {\n\t if ( len === void 0 ) len = 0;\n\t\n\t var file = this.fd2file(fd);\n\t if (len < 0) {\n\t throw new ApiError(ErrorCode.EINVAL);\n\t }\n\t file.truncateSync(len);\n\t};\n\t/**\n\t * Asynchronous fsync.\n\t * @param fd\n\t * @param callback\n\t */\n\tFS.prototype.fsync = function fsync (fd, cb) {\n\t if ( cb === void 0 ) cb = nopCb;\n\t\n\t var newCb = wrapCb(cb, 1);\n\t try {\n\t this.fd2file(fd).sync(newCb);\n\t }\n\t catch (e) {\n\t newCb(e);\n\t }\n\t};\n\t/**\n\t * Synchronous fsync.\n\t * @param fd\n\t */\n\tFS.prototype.fsyncSync = function fsyncSync (fd) {\n\t this.fd2file(fd).syncSync();\n\t};\n\t/**\n\t * Asynchronous fdatasync.\n\t * @param fd\n\t * @param callback\n\t */\n\tFS.prototype.fdatasync = function fdatasync (fd, cb) {\n\t if ( cb === void 0 ) cb = nopCb;\n\t\n\t var newCb = wrapCb(cb, 1);\n\t try {\n\t this.fd2file(fd).datasync(newCb);\n\t }\n\t catch (e) {\n\t newCb(e);\n\t }\n\t};\n\t/**\n\t * Synchronous fdatasync.\n\t * @param fd\n\t */\n\tFS.prototype.fdatasyncSync = function fdatasyncSync (fd) {\n\t this.fd2file(fd).datasyncSync();\n\t};\n\tFS.prototype.write = function write (fd, arg2, arg3, arg4, arg5, cb) {\n\t if ( cb === void 0 ) cb = nopCb;\n\t\n\t var buffer$$1, offset, length, position = null;\n\t if (typeof arg2 === 'string') {\n\t // Signature 1: (fd, string, [position?, [encoding?]], cb?)\n\t var encoding = 'utf8';\n\t switch (typeof arg3) {\n\t case 'function':\n\t // (fd, string, cb)\n\t cb = arg3;\n\t break;\n\t case 'number':\n\t // (fd, string, position, encoding?, cb?)\n\t position = arg3;\n\t encoding = typeof arg4 === 'string' ? arg4 : 'utf8';\n\t cb = typeof arg5 === 'function' ? arg5 : cb;\n\t break;\n\t default:\n\t // ...try to find the callback and get out of here!\n\t cb = typeof arg4 === 'function' ? arg4 : typeof arg5 === 'function' ? arg5 : cb;\n\t return cb(new ApiError(ErrorCode.EINVAL, 'Invalid arguments.'));\n\t }\n\t buffer$$1 = Buffer.from(arg2, encoding);\n\t offset = 0;\n\t length = buffer$$1.length;\n\t }\n\t else {\n\t // Signature 2: (fd, buffer, offset, length, position?, cb?)\n\t buffer$$1 = arg2;\n\t offset = arg3;\n\t length = arg4;\n\t position = typeof arg5 === 'number' ? arg5 : null;\n\t cb = typeof arg5 === 'function' ? arg5 : cb;\n\t }\n\t var newCb = wrapCb(cb, 3);\n\t try {\n\t var file = this.fd2file(fd);\n\t if (position === undefined || position === null) {\n\t position = file.getPos();\n\t }\n\t file.write(buffer$$1, offset, length, position, newCb);\n\t }\n\t catch (e) {\n\t newCb(e);\n\t }\n\t};\n\tFS.prototype.writeSync = function writeSync (fd, arg2, arg3, arg4, arg5) {\n\t var buffer$$1, offset = 0, length, position;\n\t if (typeof arg2 === 'string') {\n\t // Signature 1: (fd, string, [position?, [encoding?]])\n\t position = typeof arg3 === 'number' ? arg3 : null;\n\t var encoding = typeof arg4 === 'string' ? arg4 : 'utf8';\n\t offset = 0;\n\t buffer$$1 = Buffer.from(arg2, encoding);\n\t length = buffer$$1.length;\n\t }\n\t else {\n\t // Signature 2: (fd, buffer, offset, length, position?)\n\t buffer$$1 = arg2;\n\t offset = arg3;\n\t length = arg4;\n\t position = typeof arg5 === 'number' ? arg5 : null;\n\t }\n\t var file = this.fd2file(fd);\n\t if (position === undefined || position === null) {\n\t position = file.getPos();\n\t }\n\t return file.writeSync(buffer$$1, offset, length, position);\n\t};\n\tFS.prototype.read = function read (fd, arg2, arg3, arg4, arg5, cb) {\n\t if ( cb === void 0 ) cb = nopCb;\n\t\n\t var position, offset, length, buffer$$1, newCb;\n\t if (typeof arg2 === 'number') {\n\t // legacy interface\n\t // (fd, length, position, encoding, callback)\n\t length = arg2;\n\t position = arg3;\n\t var encoding = arg4;\n\t cb = typeof arg5 === 'function' ? arg5 : cb;\n\t offset = 0;\n\t buffer$$1 = Buffer.alloc(length);\n\t // XXX: Inefficient.\n\t // Wrap the cb so we shelter upper layers of the API from these\n\t // shenanigans.\n\t newCb = wrapCb(function (err, bytesRead, buf) {\n\t if (err) {\n\t return cb(err);\n\t }\n\t cb(err, buf.toString(encoding), bytesRead);\n\t }, 3);\n\t }\n\t else {\n\t buffer$$1 = arg2;\n\t offset = arg3;\n\t length = arg4;\n\t position = arg5;\n\t newCb = wrapCb(cb, 3);\n\t }\n\t try {\n\t var file = this.fd2file(fd);\n\t if (position === undefined || position === null) {\n\t position = file.getPos();\n\t }\n\t file.read(buffer$$1, offset, length, position, newCb);\n\t }\n\t catch (e) {\n\t newCb(e);\n\t }\n\t};\n\tFS.prototype.readSync = function readSync (fd, arg2, arg3, arg4, arg5) {\n\t var shenanigans = false;\n\t var buffer$$1, offset, length, position, encoding = 'utf8';\n\t if (typeof arg2 === 'number') {\n\t length = arg2;\n\t position = arg3;\n\t encoding = arg4;\n\t offset = 0;\n\t buffer$$1 = Buffer.alloc(length);\n\t shenanigans = true;\n\t }\n\t else {\n\t buffer$$1 = arg2;\n\t offset = arg3;\n\t length = arg4;\n\t position = arg5;\n\t }\n\t var file = this.fd2file(fd);\n\t if (position === undefined || position === null) {\n\t position = file.getPos();\n\t }\n\t var rv = file.readSync(buffer$$1, offset, length, position);\n\t if (!shenanigans) {\n\t return rv;\n\t }\n\t else {\n\t return [buffer$$1.toString(encoding), rv];\n\t }\n\t};\n\t/**\n\t * Asynchronous `fchown`.\n\t * @param fd\n\t * @param uid\n\t * @param gid\n\t * @param callback\n\t */\n\tFS.prototype.fchown = function fchown (fd, uid, gid, callback) {\n\t if ( callback === void 0 ) callback = nopCb;\n\t\n\t var newCb = wrapCb(callback, 1);\n\t try {\n\t this.fd2file(fd).chown(uid, gid, newCb);\n\t }\n\t catch (e) {\n\t newCb(e);\n\t }\n\t};\n\t/**\n\t * Synchronous `fchown`.\n\t * @param fd\n\t * @param uid\n\t * @param gid\n\t */\n\tFS.prototype.fchownSync = function fchownSync (fd, uid, gid) {\n\t this.fd2file(fd).chownSync(uid, gid);\n\t};\n\t/**\n\t * Asynchronous `fchmod`.\n\t * @param fd\n\t * @param mode\n\t * @param callback\n\t */\n\tFS.prototype.fchmod = function fchmod (fd, mode, cb) {\n\t var newCb = wrapCb(cb, 1);\n\t try {\n\t var numMode = typeof mode === 'string' ? parseInt(mode, 8) : mode;\n\t this.fd2file(fd).chmod(numMode, newCb);\n\t }\n\t catch (e) {\n\t newCb(e);\n\t }\n\t};\n\t/**\n\t * Synchronous `fchmod`.\n\t * @param fd\n\t * @param mode\n\t */\n\tFS.prototype.fchmodSync = function fchmodSync (fd, mode) {\n\t var numMode = typeof mode === 'string' ? parseInt(mode, 8) : mode;\n\t this.fd2file(fd).chmodSync(numMode);\n\t};\n\t/**\n\t * Change the file timestamps of a file referenced by the supplied file\n\t * descriptor.\n\t * @param fd\n\t * @param atime\n\t * @param mtime\n\t * @param callback\n\t */\n\tFS.prototype.futimes = function futimes (fd, atime, mtime, cb) {\n\t if ( cb === void 0 ) cb = nopCb;\n\t\n\t var newCb = wrapCb(cb, 1);\n\t try {\n\t var file = this.fd2file(fd);\n\t if (typeof atime === 'number') {\n\t atime = new Date(atime * 1000);\n\t }\n\t if (typeof mtime === 'number') {\n\t mtime = new Date(mtime * 1000);\n\t }\n\t file.utimes(atime, mtime, newCb);\n\t }\n\t catch (e) {\n\t newCb(e);\n\t }\n\t};\n\t/**\n\t * Change the file timestamps of a file referenced by the supplied file\n\t * descriptor.\n\t * @param fd\n\t * @param atime\n\t * @param mtime\n\t */\n\tFS.prototype.futimesSync = function futimesSync (fd, atime, mtime) {\n\t this.fd2file(fd).utimesSync(normalizeTime(atime), normalizeTime(mtime));\n\t};\n\t// DIRECTORY-ONLY METHODS\n\t/**\n\t * Asynchronous `rmdir`.\n\t * @param path\n\t * @param callback\n\t */\n\tFS.prototype.rmdir = function rmdir (path$$1, cb) {\n\t if ( cb === void 0 ) cb = nopCb;\n\t\n\t var newCb = wrapCb(cb, 1);\n\t try {\n\t path$$1 = normalizePath(path$$1);\n\t assertRoot(this.root).rmdir(path$$1, newCb);\n\t }\n\t catch (e) {\n\t newCb(e);\n\t }\n\t};\n\t/**\n\t * Synchronous `rmdir`.\n\t * @param path\n\t */\n\tFS.prototype.rmdirSync = function rmdirSync (path$$1) {\n\t path$$1 = normalizePath(path$$1);\n\t return assertRoot(this.root).rmdirSync(path$$1);\n\t};\n\t/**\n\t * Asynchronous `mkdir`.\n\t * @param path\n\t * @param mode defaults to `0777`\n\t * @param callback\n\t */\n\tFS.prototype.mkdir = function mkdir (path$$1, mode, cb) {\n\t if ( cb === void 0 ) cb = nopCb;\n\t\n\t if (typeof mode === 'function') {\n\t cb = mode;\n\t mode = 0x1ff;\n\t }\n\t var newCb = wrapCb(cb, 1);\n\t try {\n\t path$$1 = normalizePath(path$$1);\n\t assertRoot(this.root).mkdir(path$$1, mode, newCb);\n\t }\n\t catch (e) {\n\t newCb(e);\n\t }\n\t};\n\t/**\n\t * Synchronous `mkdir`.\n\t * @param path\n\t * @param mode defaults to `0777`\n\t */\n\tFS.prototype.mkdirSync = function mkdirSync (path$$1, mode) {\n\t assertRoot(this.root).mkdirSync(normalizePath(path$$1), normalizeMode(mode, 0x1ff));\n\t};\n\t/**\n\t * Asynchronous `readdir`. Reads the contents of a directory.\n\t * The callback gets two arguments `(err, files)` where `files` is an array of\n\t * the names of the files in the directory excluding `'.'` and `'..'`.\n\t * @param path\n\t * @param callback\n\t */\n\tFS.prototype.readdir = function readdir (path$$1, cb) {\n\t if ( cb === void 0 ) cb = nopCb;\n\t\n\t var newCb = wrapCb(cb, 2);\n\t try {\n\t path$$1 = normalizePath(path$$1);\n\t assertRoot(this.root).readdir(path$$1, newCb);\n\t }\n\t catch (e) {\n\t newCb(e);\n\t }\n\t};\n\t/**\n\t * Synchronous `readdir`. Reads the contents of a directory.\n\t * @param path\n\t * @return [String[]]\n\t */\n\tFS.prototype.readdirSync = function readdirSync (path$$1) {\n\t path$$1 = normalizePath(path$$1);\n\t return assertRoot(this.root).readdirSync(path$$1);\n\t};\n\t// SYMLINK METHODS\n\t/**\n\t * Asynchronous `link`.\n\t * @param srcpath\n\t * @param dstpath\n\t * @param callback\n\t */\n\tFS.prototype.link = function link (srcpath, dstpath, cb) {\n\t if ( cb === void 0 ) cb = nopCb;\n\t\n\t var newCb = wrapCb(cb, 1);\n\t try {\n\t srcpath = normalizePath(srcpath);\n\t dstpath = normalizePath(dstpath);\n\t assertRoot(this.root).link(srcpath, dstpath, newCb);\n\t }\n\t catch (e) {\n\t newCb(e);\n\t }\n\t};\n\t/**\n\t * Synchronous `link`.\n\t * @param srcpath\n\t * @param dstpath\n\t */\n\tFS.prototype.linkSync = function linkSync (srcpath, dstpath) {\n\t srcpath = normalizePath(srcpath);\n\t dstpath = normalizePath(dstpath);\n\t return assertRoot(this.root).linkSync(srcpath, dstpath);\n\t};\n\tFS.prototype.symlink = function symlink (srcpath, dstpath, arg3, cb) {\n\t if ( cb === void 0 ) cb = nopCb;\n\t\n\t var type = typeof arg3 === 'string' ? arg3 : 'file';\n\t cb = typeof arg3 === 'function' ? arg3 : cb;\n\t var newCb = wrapCb(cb, 1);\n\t try {\n\t if (type !== 'file' && type !== 'dir') {\n\t return newCb(new ApiError(ErrorCode.EINVAL, \"Invalid type: \" + type));\n\t }\n\t srcpath = normalizePath(srcpath);\n\t dstpath = normalizePath(dstpath);\n\t assertRoot(this.root).symlink(srcpath, dstpath, type, newCb);\n\t }\n\t catch (e) {\n\t newCb(e);\n\t }\n\t};\n\t/**\n\t * Synchronous `symlink`.\n\t * @param srcpath\n\t * @param dstpath\n\t * @param type can be either `'dir'` or `'file'` (default is `'file'`)\n\t */\n\tFS.prototype.symlinkSync = function symlinkSync (srcpath, dstpath, type) {\n\t if (!type) {\n\t type = 'file';\n\t }\n\t else if (type !== 'file' && type !== 'dir') {\n\t throw new ApiError(ErrorCode.EINVAL, \"Invalid type: \" + type);\n\t }\n\t srcpath = normalizePath(srcpath);\n\t dstpath = normalizePath(dstpath);\n\t return assertRoot(this.root).symlinkSync(srcpath, dstpath, type);\n\t};\n\t/**\n\t * Asynchronous readlink.\n\t * @param path\n\t * @param callback\n\t */\n\tFS.prototype.readlink = function readlink (path$$1, cb) {\n\t if ( cb === void 0 ) cb = nopCb;\n\t\n\t var newCb = wrapCb(cb, 2);\n\t try {\n\t path$$1 = normalizePath(path$$1);\n\t assertRoot(this.root).readlink(path$$1, newCb);\n\t }\n\t catch (e) {\n\t newCb(e);\n\t }\n\t};\n\t/**\n\t * Synchronous readlink.\n\t * @param path\n\t * @return [String]\n\t */\n\tFS.prototype.readlinkSync = function readlinkSync (path$$1) {\n\t path$$1 = normalizePath(path$$1);\n\t return assertRoot(this.root).readlinkSync(path$$1);\n\t};\n\t// PROPERTY OPERATIONS\n\t/**\n\t * Asynchronous `chown`.\n\t * @param path\n\t * @param uid\n\t * @param gid\n\t * @param callback\n\t */\n\tFS.prototype.chown = function chown (path$$1, uid, gid, cb) {\n\t if ( cb === void 0 ) cb = nopCb;\n\t\n\t var newCb = wrapCb(cb, 1);\n\t try {\n\t path$$1 = normalizePath(path$$1);\n\t assertRoot(this.root).chown(path$$1, false, uid, gid, newCb);\n\t }\n\t catch (e) {\n\t newCb(e);\n\t }\n\t};\n\t/**\n\t * Synchronous `chown`.\n\t * @param path\n\t * @param uid\n\t * @param gid\n\t */\n\tFS.prototype.chownSync = function chownSync (path$$1, uid, gid) {\n\t path$$1 = normalizePath(path$$1);\n\t assertRoot(this.root).chownSync(path$$1, false, uid, gid);\n\t};\n\t/**\n\t * Asynchronous `lchown`.\n\t * @param path\n\t * @param uid\n\t * @param gid\n\t * @param callback\n\t */\n\tFS.prototype.lchown = function lchown (path$$1, uid, gid, cb) {\n\t if ( cb === void 0 ) cb = nopCb;\n\t\n\t var newCb = wrapCb(cb, 1);\n\t try {\n\t path$$1 = normalizePath(path$$1);\n\t assertRoot(this.root).chown(path$$1, true, uid, gid, newCb);\n\t }\n\t catch (e) {\n\t newCb(e);\n\t }\n\t};\n\t/**\n\t * Synchronous `lchown`.\n\t * @param path\n\t * @param uid\n\t * @param gid\n\t */\n\tFS.prototype.lchownSync = function lchownSync (path$$1, uid, gid) {\n\t path$$1 = normalizePath(path$$1);\n\t assertRoot(this.root).chownSync(path$$1, true, uid, gid);\n\t};\n\t/**\n\t * Asynchronous `chmod`.\n\t * @param path\n\t * @param mode\n\t * @param callback\n\t */\n\tFS.prototype.chmod = function chmod (path$$1, mode, cb) {\n\t if ( cb === void 0 ) cb = nopCb;\n\t\n\t var newCb = wrapCb(cb, 1);\n\t try {\n\t var numMode = normalizeMode(mode, -1);\n\t if (numMode < 0) {\n\t throw new ApiError(ErrorCode.EINVAL, \"Invalid mode.\");\n\t }\n\t assertRoot(this.root).chmod(normalizePath(path$$1), false, numMode, newCb);\n\t }\n\t catch (e) {\n\t newCb(e);\n\t }\n\t};\n\t/**\n\t * Synchronous `chmod`.\n\t * @param path\n\t * @param mode\n\t */\n\tFS.prototype.chmodSync = function chmodSync (path$$1, mode) {\n\t var numMode = normalizeMode(mode, -1);\n\t if (numMode < 0) {\n\t throw new ApiError(ErrorCode.EINVAL, \"Invalid mode.\");\n\t }\n\t path$$1 = normalizePath(path$$1);\n\t assertRoot(this.root).chmodSync(path$$1, false, numMode);\n\t};\n\t/**\n\t * Asynchronous `lchmod`.\n\t * @param path\n\t * @param mode\n\t * @param callback\n\t */\n\tFS.prototype.lchmod = function lchmod (path$$1, mode, cb) {\n\t if ( cb === void 0 ) cb = nopCb;\n\t\n\t var newCb = wrapCb(cb, 1);\n\t try {\n\t var numMode = normalizeMode(mode, -1);\n\t if (numMode < 0) {\n\t throw new ApiError(ErrorCode.EINVAL, \"Invalid mode.\");\n\t }\n\t assertRoot(this.root).chmod(normalizePath(path$$1), true, numMode, newCb);\n\t }\n\t catch (e) {\n\t newCb(e);\n\t }\n\t};\n\t/**\n\t * Synchronous `lchmod`.\n\t * @param path\n\t * @param mode\n\t */\n\tFS.prototype.lchmodSync = function lchmodSync (path$$1, mode) {\n\t var numMode = normalizeMode(mode, -1);\n\t if (numMode < 1) {\n\t throw new ApiError(ErrorCode.EINVAL, \"Invalid mode.\");\n\t }\n\t assertRoot(this.root).chmodSync(normalizePath(path$$1), true, numMode);\n\t};\n\t/**\n\t * Change file timestamps of the file referenced by the supplied path.\n\t * @param path\n\t * @param atime\n\t * @param mtime\n\t * @param callback\n\t */\n\tFS.prototype.utimes = function utimes (path$$1, atime, mtime, cb) {\n\t if ( cb === void 0 ) cb = nopCb;\n\t\n\t var newCb = wrapCb(cb, 1);\n\t try {\n\t assertRoot(this.root).utimes(normalizePath(path$$1), normalizeTime(atime), normalizeTime(mtime), newCb);\n\t }\n\t catch (e) {\n\t newCb(e);\n\t }\n\t};\n\t/**\n\t * Change file timestamps of the file referenced by the supplied path.\n\t * @param path\n\t * @param atime\n\t * @param mtime\n\t */\n\tFS.prototype.utimesSync = function utimesSync (path$$1, atime, mtime) {\n\t assertRoot(this.root).utimesSync(normalizePath(path$$1), normalizeTime(atime), normalizeTime(mtime));\n\t};\n\tFS.prototype.realpath = function realpath (path$$1, arg2, cb) {\n\t if ( cb === void 0 ) cb = nopCb;\n\t\n\t var cache = typeof (arg2) === 'object' ? arg2 : {};\n\t cb = typeof (arg2) === 'function' ? arg2 : nopCb;\n\t var newCb = wrapCb(cb, 2);\n\t try {\n\t path$$1 = normalizePath(path$$1);\n\t assertRoot(this.root).realpath(path$$1, cache, newCb);\n\t }\n\t catch (e) {\n\t newCb(e);\n\t }\n\t};\n\t/**\n\t * Synchronous `realpath`.\n\t * @param path\n\t * @param cache An object literal of mapped paths that can be used to\n\t * force a specific path resolution or avoid additional `fs.stat` calls for\n\t * known real paths.\n\t * @return [String]\n\t */\n\tFS.prototype.realpathSync = function realpathSync (path$$1, cache) {\n\t if ( cache === void 0 ) cache = {};\n\t\n\t path$$1 = normalizePath(path$$1);\n\t return assertRoot(this.root).realpathSync(path$$1, cache);\n\t};\n\tFS.prototype.watchFile = function watchFile (filename, arg2, listener) {\n\t if ( listener === void 0 ) listener = nopCb;\n\t\n\t throw new ApiError(ErrorCode.ENOTSUP);\n\t};\n\tFS.prototype.unwatchFile = function unwatchFile (filename, listener) {\n\t if ( listener === void 0 ) listener = nopCb;\n\t\n\t throw new ApiError(ErrorCode.ENOTSUP);\n\t};\n\tFS.prototype.watch = function watch (filename, arg2, listener) {\n\t if ( listener === void 0 ) listener = nopCb;\n\t\n\t throw new ApiError(ErrorCode.ENOTSUP);\n\t};\n\tFS.prototype.access = function access (path$$1, arg2, cb) {\n\t if ( cb === void 0 ) cb = nopCb;\n\t\n\t throw new ApiError(ErrorCode.ENOTSUP);\n\t};\n\tFS.prototype.accessSync = function accessSync (path$$1, mode) {\n\t throw new ApiError(ErrorCode.ENOTSUP);\n\t};\n\tFS.prototype.createReadStream = function createReadStream (path$$1, options) {\n\t throw new ApiError(ErrorCode.ENOTSUP);\n\t};\n\tFS.prototype.createWriteStream = function createWriteStream (path$$1, options) {\n\t throw new ApiError(ErrorCode.ENOTSUP);\n\t};\n\t/**\n\t * For unit testing. Passes all incoming callbacks to cbWrapper for wrapping.\n\t */\n\tFS.prototype.wrapCallbacks = function wrapCallbacks (cbWrapper) {\n\t wrapCb = cbWrapper;\n\t};\n\tFS.prototype.getFdForFile = function getFdForFile (file) {\n\t var fd = this.nextFd++;\n\t this.fdMap[fd] = file;\n\t return fd;\n\t};\n\tFS.prototype.fd2file = function fd2file (fd) {\n\t var rv = this.fdMap[fd];\n\t if (rv) {\n\t return rv;\n\t }\n\t else {\n\t throw new ApiError(ErrorCode.EBADF, 'Invalid file descriptor.');\n\t }\n\t};\n\tFS.prototype.closeFd = function closeFd (fd) {\n\t delete this.fdMap[fd];\n\t};\n\t\n\t/* tslint:disable:variable-name */\n\t// Exported fs.Stats.\n\tFS.Stats = Stats;\n\t\n\t// Manually export the individual public functions of fs.\n\t// Required because some code will invoke functions off of the module.\n\t// e.g.:\n\t// let writeFile = fs.writeFile;\n\t// writeFile(...)\n\t/**\n\t * @hidden\n\t */\n\tvar fs = new FS();\n\t/**\n\t * @hidden\n\t */\n\tvar _fsMock = {};\n\t/**\n\t * @hidden\n\t */\n\tvar fsProto = FS.prototype;\n\tObject.keys(fsProto).forEach(function (key) {\n\t if (typeof fs[key] === 'function') {\n\t _fsMock[key] = function () {\n\t return fs[key].apply(fs, arguments);\n\t };\n\t }\n\t else {\n\t _fsMock[key] = fs[key];\n\t }\n\t});\n\t_fsMock['changeFSModule'] = function (newFs) {\n\t fs = newFs;\n\t};\n\t_fsMock['getFSModule'] = function () {\n\t return fs;\n\t};\n\t_fsMock['FS'] = FS;\n\t\n\t/*\n\t * Levenshtein distance, from the `js-levenshtein` NPM module.\n\t * Copied here to avoid complexity of adding another CommonJS module dependency.\n\t */\n\tfunction _min(d0, d1, d2, bx, ay) {\n\t return d0 < d1 || d2 < d1\n\t ? d0 > d2\n\t ? d2 + 1\n\t : d0 + 1\n\t : bx === ay\n\t ? d1\n\t : d1 + 1;\n\t}\n\t/**\n\t * Calculates levenshtein distance.\n\t * @param a\n\t * @param b\n\t */\n\tfunction levenshtein(a, b) {\n\t if (a === b) {\n\t return 0;\n\t }\n\t if (a.length > b.length) {\n\t var tmp = a;\n\t a = b;\n\t b = tmp;\n\t }\n\t var la = a.length;\n\t var lb = b.length;\n\t while (la > 0 && (a.charCodeAt(la - 1) === b.charCodeAt(lb - 1))) {\n\t la--;\n\t lb--;\n\t }\n\t var offset = 0;\n\t while (offset < la && (a.charCodeAt(offset) === b.charCodeAt(offset))) {\n\t offset++;\n\t }\n\t la -= offset;\n\t lb -= offset;\n\t if (la === 0 || lb === 1) {\n\t return lb;\n\t }\n\t var vector = new Array(la << 1);\n\t for (var y = 0; y < la;) {\n\t vector[la + y] = a.charCodeAt(offset + y);\n\t vector[y] = ++y;\n\t }\n\t var x;\n\t var d0;\n\t var d1;\n\t var d2;\n\t var d3;\n\t for (x = 0; (x + 3) < lb;) {\n\t var bx0 = b.charCodeAt(offset + (d0 = x));\n\t var bx1 = b.charCodeAt(offset + (d1 = x + 1));\n\t var bx2 = b.charCodeAt(offset + (d2 = x + 2));\n\t var bx3 = b.charCodeAt(offset + (d3 = x + 3));\n\t var dd$1 = (x += 4);\n\t for (var y$1 = 0; y$1 < la;) {\n\t var ay = vector[la + y$1];\n\t var dy = vector[y$1];\n\t d0 = _min(dy, d0, d1, bx0, ay);\n\t d1 = _min(d0, d1, d2, bx1, ay);\n\t d2 = _min(d1, d2, d3, bx2, ay);\n\t dd$1 = _min(d2, d3, dd$1, bx3, ay);\n\t vector[y$1++] = dd$1;\n\t d3 = d2;\n\t d2 = d1;\n\t d1 = d0;\n\t d0 = dy;\n\t }\n\t }\n\t var dd = 0;\n\t for (; x < lb;) {\n\t var bx0$1 = b.charCodeAt(offset + (d0 = x));\n\t dd = ++x;\n\t for (var y$2 = 0; y$2 < la; y$2++) {\n\t var dy$1 = vector[y$2];\n\t vector[y$2] = dd = dy$1 < d0 || dd < d0\n\t ? dy$1 > dd ? dd + 1 : dy$1 + 1\n\t : bx0$1 === vector[la + y$2]\n\t ? d0\n\t : d0 + 1;\n\t d0 = dy$1;\n\t }\n\t }\n\t return dd;\n\t}\n\t\n\tfunction deprecationMessage(print, fsName, opts) {\n\t if (print) {\n\t console.warn((\"[\" + fsName + \"] Direct file system constructor usage is deprecated for this file system, and will be removed in the next major version. Please use the '\" + fsName + \".Create(\" + (JSON.stringify(opts)) + \", callback)' method instead. See https://github.com/jvilk/BrowserFS/issues/176 for more details.\"));\n\t }\n\t}\n\t/**\n\t * Checks for any IE version, including IE11 which removed MSIE from the\n\t * userAgent string.\n\t * @hidden\n\t */\n\tvar isIE = typeof navigator !== \"undefined\" && !!(/(msie) ([\\w.]+)/.exec(navigator.userAgent.toLowerCase()) || navigator.userAgent.indexOf('Trident') !== -1);\n\t/**\n\t * Check if we're in a web worker.\n\t * @hidden\n\t */\n\tvar isWebWorker = typeof window === \"undefined\";\n\t/**\n\t * Throws an exception. Called on code paths that should be impossible.\n\t * @hidden\n\t */\n\tfunction fail() {\n\t throw new Error(\"BFS has reached an impossible code path; please file a bug.\");\n\t}\n\t/**\n\t * Synchronous recursive makedir.\n\t * @hidden\n\t */\n\tfunction mkdirpSync(p, mode, fs) {\n\t if (!fs.existsSync(p)) {\n\t mkdirpSync(path.dirname(p), mode, fs);\n\t fs.mkdirSync(p, mode);\n\t }\n\t}\n\t/**\n\t * Converts a buffer into an array buffer. Attempts to do so in a\n\t * zero-copy manner, e.g. the array references the same memory.\n\t * @hidden\n\t */\n\tfunction buffer2ArrayBuffer(buff) {\n\t var u8 = buffer2Uint8array(buff), u8offset = u8.byteOffset, u8Len = u8.byteLength;\n\t if (u8offset === 0 && u8Len === u8.buffer.byteLength) {\n\t return u8.buffer;\n\t }\n\t else {\n\t return u8.buffer.slice(u8offset, u8offset + u8Len);\n\t }\n\t}\n\t/**\n\t * Converts a buffer into a Uint8Array. Attempts to do so in a\n\t * zero-copy manner, e.g. the array references the same memory.\n\t * @hidden\n\t */\n\tfunction buffer2Uint8array(buff) {\n\t if (buff instanceof Uint8Array) {\n\t // BFS & Node v4.0 buffers *are* Uint8Arrays.\n\t return buff;\n\t }\n\t else {\n\t // Uint8Arrays can be constructed from arrayish numbers.\n\t // At this point, we assume this isn't a BFS array.\n\t return new Uint8Array(buff);\n\t }\n\t}\n\t/**\n\t * Converts the given arrayish object into a Buffer. Attempts to\n\t * be zero-copy.\n\t * @hidden\n\t */\n\tfunction arrayish2Buffer(arr) {\n\t if (arr instanceof Buffer) {\n\t return arr;\n\t }\n\t else if (arr instanceof Uint8Array) {\n\t return uint8Array2Buffer(arr);\n\t }\n\t else {\n\t return Buffer.from(arr);\n\t }\n\t}\n\t/**\n\t * Converts the given Uint8Array into a Buffer. Attempts to be zero-copy.\n\t * @hidden\n\t */\n\tfunction uint8Array2Buffer(u8) {\n\t if (u8 instanceof Buffer) {\n\t return u8;\n\t }\n\t else if (u8.byteOffset === 0 && u8.byteLength === u8.buffer.byteLength) {\n\t return arrayBuffer2Buffer(u8.buffer);\n\t }\n\t else {\n\t return Buffer.from(u8.buffer, u8.byteOffset, u8.byteLength);\n\t }\n\t}\n\t/**\n\t * Converts the given array buffer into a Buffer. Attempts to be\n\t * zero-copy.\n\t * @hidden\n\t */\n\tfunction arrayBuffer2Buffer(ab) {\n\t return Buffer.from(ab);\n\t}\n\t/**\n\t * Copies a slice of the given buffer\n\t * @hidden\n\t */\n\tfunction copyingSlice(buff, start, end) {\n\t if ( start === void 0 ) start = 0;\n\t if ( end === void 0 ) end = buff.length;\n\t\n\t if (start < 0 || end < 0 || end > buff.length || start > end) {\n\t throw new TypeError((\"Invalid slice bounds on buffer of length \" + (buff.length) + \": [\" + start + \", \" + end + \"]\"));\n\t }\n\t if (buff.length === 0) {\n\t // Avoid s0 corner case in ArrayBuffer case.\n\t return emptyBuffer();\n\t }\n\t else {\n\t var u8 = buffer2Uint8array(buff), s0 = buff[0], newS0 = (s0 + 1) % 0xFF;\n\t buff[0] = newS0;\n\t if (u8[0] === newS0) {\n\t // Same memory. Revert & copy.\n\t u8[0] = s0;\n\t return uint8Array2Buffer(u8.slice(start, end));\n\t }\n\t else {\n\t // Revert.\n\t buff[0] = s0;\n\t return uint8Array2Buffer(u8.subarray(start, end));\n\t }\n\t }\n\t}\n\t/**\n\t * @hidden\n\t */\n\tvar emptyBuff = null;\n\t/**\n\t * Returns an empty buffer.\n\t * @hidden\n\t */\n\tfunction emptyBuffer() {\n\t if (emptyBuff) {\n\t return emptyBuff;\n\t }\n\t return emptyBuff = Buffer.alloc(0);\n\t}\n\t/**\n\t * Option validator for a Buffer file system option.\n\t * @hidden\n\t */\n\tfunction bufferValidator(v, cb) {\n\t if (Buffer.isBuffer(v)) {\n\t cb();\n\t }\n\t else {\n\t cb(new ApiError(ErrorCode.EINVAL, \"option must be a Buffer.\"));\n\t }\n\t}\n\t/**\n\t * Checks that the given options object is valid for the file system options.\n\t * @hidden\n\t */\n\tfunction checkOptions(fsType, opts, cb) {\n\t var optsInfo = fsType.Options;\n\t var fsName = fsType.Name;\n\t var pendingValidators = 0;\n\t var callbackCalled = false;\n\t var loopEnded = false;\n\t function validatorCallback(e) {\n\t if (!callbackCalled) {\n\t if (e) {\n\t callbackCalled = true;\n\t cb(e);\n\t }\n\t pendingValidators--;\n\t if (pendingValidators === 0 && loopEnded) {\n\t cb();\n\t }\n\t }\n\t }\n\t // Check for required options.\n\t var loop = function ( optName ) {\n\t if (optsInfo.hasOwnProperty(optName)) {\n\t var opt = optsInfo[optName];\n\t var providedValue = opts[optName];\n\t if (providedValue === undefined || providedValue === null) {\n\t if (!opt.optional) {\n\t // Required option, not provided.\n\t // Any incorrect options provided? Which ones are close to the provided one?\n\t // (edit distance 5 === close)\n\t var incorrectOptions = Object.keys(opts).filter(function (o) { return !(o in optsInfo); }).map(function (a) {\n\t return { str: a, distance: levenshtein(optName, a) };\n\t }).filter(function (o) { return o.distance < 5; }).sort(function (a, b) { return a.distance - b.distance; });\n\t // Validators may be synchronous.\n\t if (callbackCalled) {\n\t return {};\n\t }\n\t callbackCalled = true;\n\t return { v: cb(new ApiError(ErrorCode.EINVAL, (\"[\" + fsName + \"] Required option '\" + optName + \"' not provided.\" + (incorrectOptions.length > 0 ? (\" You provided unrecognized option '\" + (incorrectOptions[0].str) + \"'; perhaps you meant to type '\" + optName + \"'.\") : '') + \"\\nOption description: \" + (opt.description)))) };\n\t }\n\t // Else: Optional option, not provided. That is OK.\n\t }\n\t else {\n\t // Option provided! Check type.\n\t var typeMatches = false;\n\t if (Array.isArray(opt.type)) {\n\t typeMatches = opt.type.indexOf(typeof (providedValue)) !== -1;\n\t }\n\t else {\n\t typeMatches = typeof (providedValue) === opt.type;\n\t }\n\t if (!typeMatches) {\n\t // Validators may be synchronous.\n\t if (callbackCalled) {\n\t return {};\n\t }\n\t callbackCalled = true;\n\t return { v: cb(new ApiError(ErrorCode.EINVAL, (\"[\" + fsName + \"] Value provided for option \" + optName + \" is not the proper type. Expected \" + (Array.isArray(opt.type) ? (\"one of {\" + (opt.type.join(\", \")) + \"}\") : opt.type) + \", but received \" + (typeof (providedValue)) + \"\\nOption description: \" + (opt.description)))) };\n\t }\n\t else if (opt.validator) {\n\t pendingValidators++;\n\t opt.validator(providedValue, validatorCallback);\n\t }\n\t // Otherwise: All good!\n\t }\n\t }\n\t };\n\t\n\t for (var optName in optsInfo) {\n\t var returned = loop( optName );\n\t\n\t if ( returned ) return returned.v;\n\t }\n\t loopEnded = true;\n\t if (pendingValidators === 0 && !callbackCalled) {\n\t cb();\n\t }\n\t}\n\t\n\t\n\tvar BFSUtils = Object.freeze({\n\t\tdeprecationMessage: deprecationMessage,\n\t\tisIE: isIE,\n\t\tisWebWorker: isWebWorker,\n\t\tfail: fail,\n\t\tmkdirpSync: mkdirpSync,\n\t\tbuffer2ArrayBuffer: buffer2ArrayBuffer,\n\t\tbuffer2Uint8array: buffer2Uint8array,\n\t\tarrayish2Buffer: arrayish2Buffer,\n\t\tuint8Array2Buffer: uint8Array2Buffer,\n\t\tarrayBuffer2Buffer: arrayBuffer2Buffer,\n\t\tcopyingSlice: copyingSlice,\n\t\temptyBuffer: emptyBuffer,\n\t\tbufferValidator: bufferValidator,\n\t\tcheckOptions: checkOptions\n\t});\n\t\n\tvar BFSEmscriptenStreamOps = function BFSEmscriptenStreamOps(fs) {\n\t this.fs = fs;\n\t this.nodefs = fs.getNodeFS();\n\t this.FS = fs.getFS();\n\t this.PATH = fs.getPATH();\n\t this.ERRNO_CODES = fs.getERRNO_CODES();\n\t};\n\tBFSEmscriptenStreamOps.prototype.open = function open (stream) {\n\t var path$$1 = this.fs.realPath(stream.node);\n\t var FS = this.FS;\n\t try {\n\t if (FS.isFile(stream.node.mode)) {\n\t stream.nfd = this.nodefs.openSync(path$$1, this.fs.flagsToPermissionString(stream.flags));\n\t }\n\t }\n\t catch (e) {\n\t if (!e.code) {\n\t throw e;\n\t }\n\t throw new FS.ErrnoError(this.ERRNO_CODES[e.code]);\n\t }\n\t};\n\tBFSEmscriptenStreamOps.prototype.close = function close (stream) {\n\t var FS = this.FS;\n\t try {\n\t if (FS.isFile(stream.node.mode) && stream.nfd) {\n\t this.nodefs.closeSync(stream.nfd);\n\t }\n\t }\n\t catch (e) {\n\t if (!e.code) {\n\t throw e;\n\t }\n\t throw new FS.ErrnoError(this.ERRNO_CODES[e.code]);\n\t }\n\t};\n\tBFSEmscriptenStreamOps.prototype.read = function read (stream, buffer$$1, offset, length, position) {\n\t // Avoid copying overhead by reading directly into buffer.\n\t try {\n\t return this.nodefs.readSync(stream.nfd, uint8Array2Buffer(buffer$$1), offset, length, position);\n\t }\n\t catch (e) {\n\t throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code]);\n\t }\n\t};\n\tBFSEmscriptenStreamOps.prototype.write = function write (stream, buffer$$1, offset, length, position) {\n\t // Avoid copying overhead.\n\t try {\n\t return this.nodefs.writeSync(stream.nfd, uint8Array2Buffer(buffer$$1), offset, length, position);\n\t }\n\t catch (e) {\n\t throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code]);\n\t }\n\t};\n\tBFSEmscriptenStreamOps.prototype.llseek = function llseek (stream, offset, whence) {\n\t var position = offset;\n\t if (whence === 1) {\n\t position += stream.position;\n\t }\n\t else if (whence === 2) {\n\t if (this.FS.isFile(stream.node.mode)) {\n\t try {\n\t var stat = this.nodefs.fstatSync(stream.nfd);\n\t position += stat.size;\n\t }\n\t catch (e) {\n\t throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code]);\n\t }\n\t }\n\t }\n\t if (position < 0) {\n\t throw new this.FS.ErrnoError(this.ERRNO_CODES.EINVAL);\n\t }\n\t stream.position = position;\n\t return position;\n\t};\n\tvar BFSEmscriptenNodeOps = function BFSEmscriptenNodeOps(fs) {\n\t this.fs = fs;\n\t this.nodefs = fs.getNodeFS();\n\t this.FS = fs.getFS();\n\t this.PATH = fs.getPATH();\n\t this.ERRNO_CODES = fs.getERRNO_CODES();\n\t};\n\tBFSEmscriptenNodeOps.prototype.getattr = function getattr (node) {\n\t var path$$1 = this.fs.realPath(node);\n\t var stat;\n\t try {\n\t stat = this.nodefs.lstatSync(path$$1);\n\t }\n\t catch (e) {\n\t if (!e.code) {\n\t throw e;\n\t }\n\t throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code]);\n\t }\n\t return {\n\t dev: stat.dev,\n\t ino: stat.ino,\n\t mode: stat.mode,\n\t nlink: stat.nlink,\n\t uid: stat.uid,\n\t gid: stat.gid,\n\t rdev: stat.rdev,\n\t size: stat.size,\n\t atime: stat.atime,\n\t mtime: stat.mtime,\n\t ctime: stat.ctime,\n\t blksize: stat.blksize,\n\t blocks: stat.blocks\n\t };\n\t};\n\tBFSEmscriptenNodeOps.prototype.setattr = function setattr (node, attr) {\n\t var path$$1 = this.fs.realPath(node);\n\t try {\n\t if (attr.mode !== undefined) {\n\t this.nodefs.chmodSync(path$$1, attr.mode);\n\t // update the common node structure mode as well\n\t node.mode = attr.mode;\n\t }\n\t if (attr.timestamp !== undefined) {\n\t var date = new Date(attr.timestamp);\n\t this.nodefs.utimesSync(path$$1, date, date);\n\t }\n\t }\n\t catch (e) {\n\t if (!e.code) {\n\t throw e;\n\t }\n\t // Ignore not supported errors. Emscripten does utimesSync when it\n\t // writes files, but never really requires the value to be set.\n\t if (e.code !== \"ENOTSUP\") {\n\t throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code]);\n\t }\n\t }\n\t if (attr.size !== undefined) {\n\t try {\n\t this.nodefs.truncateSync(path$$1, attr.size);\n\t }\n\t catch (e) {\n\t if (!e.code) {\n\t throw e;\n\t }\n\t throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code]);\n\t }\n\t }\n\t};\n\tBFSEmscriptenNodeOps.prototype.lookup = function lookup (parent, name) {\n\t var path$$1 = this.PATH.join2(this.fs.realPath(parent), name);\n\t var mode = this.fs.getMode(path$$1);\n\t return this.fs.createNode(parent, name, mode);\n\t};\n\tBFSEmscriptenNodeOps.prototype.mknod = function mknod (parent, name, mode, dev) {\n\t var node = this.fs.createNode(parent, name, mode, dev);\n\t // create the backing node for this in the fs root as well\n\t var path$$1 = this.fs.realPath(node);\n\t try {\n\t if (this.FS.isDir(node.mode)) {\n\t this.nodefs.mkdirSync(path$$1, node.mode);\n\t }\n\t else {\n\t this.nodefs.writeFileSync(path$$1, '', { mode: node.mode });\n\t }\n\t }\n\t catch (e) {\n\t if (!e.code) {\n\t throw e;\n\t }\n\t throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code]);\n\t }\n\t return node;\n\t};\n\tBFSEmscriptenNodeOps.prototype.rename = function rename (oldNode, newDir, newName) {\n\t var oldPath = this.fs.realPath(oldNode);\n\t var newPath = this.PATH.join2(this.fs.realPath(newDir), newName);\n\t try {\n\t this.nodefs.renameSync(oldPath, newPath);\n\t // This logic is missing from the original NodeFS,\n\t // causing Emscripten's filesystem to think that the old file still exists.\n\t oldNode.name = newName;\n\t oldNode.parent = newDir;\n\t }\n\t catch (e) {\n\t if (!e.code) {\n\t throw e;\n\t }\n\t throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code]);\n\t }\n\t};\n\tBFSEmscriptenNodeOps.prototype.unlink = function unlink (parent, name) {\n\t var path$$1 = this.PATH.join2(this.fs.realPath(parent), name);\n\t try {\n\t this.nodefs.unlinkSync(path$$1);\n\t }\n\t catch (e) {\n\t if (!e.code) {\n\t throw e;\n\t }\n\t throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code]);\n\t }\n\t};\n\tBFSEmscriptenNodeOps.prototype.rmdir = function rmdir (parent, name) {\n\t var path$$1 = this.PATH.join2(this.fs.realPath(parent), name);\n\t try {\n\t this.nodefs.rmdirSync(path$$1);\n\t }\n\t catch (e) {\n\t if (!e.code) {\n\t throw e;\n\t }\n\t throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code]);\n\t }\n\t};\n\tBFSEmscriptenNodeOps.prototype.readdir = function readdir (node) {\n\t var path$$1 = this.fs.realPath(node);\n\t try {\n\t // Node does not list . and .. in directory listings,\n\t // but Emscripten expects it.\n\t var contents = this.nodefs.readdirSync(path$$1);\n\t contents.push('.', '..');\n\t return contents;\n\t }\n\t catch (e) {\n\t if (!e.code) {\n\t throw e;\n\t }\n\t throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code]);\n\t }\n\t};\n\tBFSEmscriptenNodeOps.prototype.symlink = function symlink (parent, newName, oldPath) {\n\t var newPath = this.PATH.join2(this.fs.realPath(parent), newName);\n\t try {\n\t this.nodefs.symlinkSync(oldPath, newPath);\n\t }\n\t catch (e) {\n\t if (!e.code) {\n\t throw e;\n\t }\n\t throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code]);\n\t }\n\t};\n\tBFSEmscriptenNodeOps.prototype.readlink = function readlink (node) {\n\t var path$$1 = this.fs.realPath(node);\n\t try {\n\t return this.nodefs.readlinkSync(path$$1);\n\t }\n\t catch (e) {\n\t if (!e.code) {\n\t throw e;\n\t }\n\t throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code]);\n\t }\n\t};\n\tvar BFSEmscriptenFS = function BFSEmscriptenFS(_FS, _PATH, _ERRNO_CODES, nodefs) {\n\t if ( _FS === void 0 ) _FS = self['FS'];\n\t if ( _PATH === void 0 ) _PATH = self['PATH'];\n\t if ( _ERRNO_CODES === void 0 ) _ERRNO_CODES = self['ERRNO_CODES'];\n\t if ( nodefs === void 0 ) nodefs = _fsMock;\n\t\n\t // This maps the integer permission modes from http://linux.die.net/man/3/open\n\t // to node.js-specific file open permission strings at http://nodejs.org/api/fs.html#fs_fs_open_path_flags_mode_callback\n\t this.flagsToPermissionStringMap = {\n\t 0 /*O_RDONLY*/: 'r',\n\t 1 /*O_WRONLY*/: 'r+',\n\t 2 /*O_RDWR*/: 'r+',\n\t 64 /*O_CREAT*/: 'r',\n\t 65 /*O_WRONLY|O_CREAT*/: 'r+',\n\t 66 /*O_RDWR|O_CREAT*/: 'r+',\n\t 129 /*O_WRONLY|O_EXCL*/: 'rx+',\n\t 193 /*O_WRONLY|O_CREAT|O_EXCL*/: 'rx+',\n\t 514 /*O_RDWR|O_TRUNC*/: 'w+',\n\t 577 /*O_WRONLY|O_CREAT|O_TRUNC*/: 'w',\n\t 578 /*O_CREAT|O_RDWR|O_TRUNC*/: 'w+',\n\t 705 /*O_WRONLY|O_CREAT|O_EXCL|O_TRUNC*/: 'wx',\n\t 706 /*O_RDWR|O_CREAT|O_EXCL|O_TRUNC*/: 'wx+',\n\t 1024 /*O_APPEND*/: 'a',\n\t 1025 /*O_WRONLY|O_APPEND*/: 'a',\n\t 1026 /*O_RDWR|O_APPEND*/: 'a+',\n\t 1089 /*O_WRONLY|O_CREAT|O_APPEND*/: 'a',\n\t 1090 /*O_RDWR|O_CREAT|O_APPEND*/: 'a+',\n\t 1153 /*O_WRONLY|O_EXCL|O_APPEND*/: 'ax',\n\t 1154 /*O_RDWR|O_EXCL|O_APPEND*/: 'ax+',\n\t 1217 /*O_WRONLY|O_CREAT|O_EXCL|O_APPEND*/: 'ax',\n\t 1218 /*O_RDWR|O_CREAT|O_EXCL|O_APPEND*/: 'ax+',\n\t 4096 /*O_RDONLY|O_DSYNC*/: 'rs',\n\t 4098 /*O_RDWR|O_DSYNC*/: 'rs+'\n\t };\n\t this.nodefs = nodefs;\n\t this.FS = _FS;\n\t this.PATH = _PATH;\n\t this.ERRNO_CODES = _ERRNO_CODES;\n\t this.node_ops = new BFSEmscriptenNodeOps(this);\n\t this.stream_ops = new BFSEmscriptenStreamOps(this);\n\t};\n\tBFSEmscriptenFS.prototype.mount = function mount (m) {\n\t return this.createNode(null, '/', this.getMode(m.opts.root), 0);\n\t};\n\tBFSEmscriptenFS.prototype.createNode = function createNode (parent, name, mode, dev) {\n\t var FS = this.FS;\n\t if (!FS.isDir(mode) && !FS.isFile(mode) && !FS.isLink(mode)) {\n\t throw new FS.ErrnoError(this.ERRNO_CODES.EINVAL);\n\t }\n\t var node = FS.createNode(parent, name, mode);\n\t node.node_ops = this.node_ops;\n\t node.stream_ops = this.stream_ops;\n\t return node;\n\t};\n\tBFSEmscriptenFS.prototype.getMode = function getMode (path$$1) {\n\t var stat;\n\t try {\n\t stat = this.nodefs.lstatSync(path$$1);\n\t }\n\t catch (e) {\n\t if (!e.code) {\n\t throw e;\n\t }\n\t throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code]);\n\t }\n\t return stat.mode;\n\t};\n\tBFSEmscriptenFS.prototype.realPath = function realPath (node) {\n\t var parts = [];\n\t while (node.parent !== node) {\n\t parts.push(node.name);\n\t node = node.parent;\n\t }\n\t parts.push(node.mount.opts.root);\n\t parts.reverse();\n\t return this.PATH.join.apply(null, parts);\n\t};\n\tBFSEmscriptenFS.prototype.flagsToPermissionString = function flagsToPermissionString (flags) {\n\t var parsedFlags = (typeof flags === \"string\") ? parseInt(flags, 10) : flags;\n\t parsedFlags &= 0x1FFF;\n\t if (parsedFlags in this.flagsToPermissionStringMap) {\n\t return this.flagsToPermissionStringMap[parsedFlags];\n\t }\n\t else {\n\t return flags;\n\t }\n\t};\n\tBFSEmscriptenFS.prototype.getNodeFS = function getNodeFS () {\n\t return this.nodefs;\n\t};\n\tBFSEmscriptenFS.prototype.getFS = function getFS () {\n\t return this.FS;\n\t};\n\tBFSEmscriptenFS.prototype.getPATH = function getPATH () {\n\t return this.PATH;\n\t};\n\tBFSEmscriptenFS.prototype.getERRNO_CODES = function getERRNO_CODES () {\n\t return this.ERRNO_CODES;\n\t};\n\t\n\t/**\n\t * Basic filesystem class. Most filesystems should extend this class, as it\n\t * provides default implementations for a handful of methods.\n\t */\n\tvar BaseFileSystem = function BaseFileSystem () {};\n\t\n\tBaseFileSystem.prototype.supportsLinks = function supportsLinks () {\n\t return false;\n\t};\n\tBaseFileSystem.prototype.diskSpace = function diskSpace (p, cb) {\n\t cb(0, 0);\n\t};\n\t/**\n\t * Opens the file at path p with the given flag. The file must exist.\n\t * @param p The path to open.\n\t * @param flag The flag to use when opening the file.\n\t */\n\tBaseFileSystem.prototype.openFile = function openFile (p, flag, cb) {\n\t throw new ApiError(ErrorCode.ENOTSUP);\n\t};\n\t/**\n\t * Create the file at path p with the given mode. Then, open it with the given\n\t * flag.\n\t */\n\tBaseFileSystem.prototype.createFile = function createFile (p, flag, mode, cb) {\n\t throw new ApiError(ErrorCode.ENOTSUP);\n\t};\n\tBaseFileSystem.prototype.open = function open (p, flag, mode, cb) {\n\t var this$1 = this;\n\t\n\t var mustBeFile = function (e, stats) {\n\t if (e) {\n\t // File does not exist.\n\t switch (flag.pathNotExistsAction()) {\n\t case ActionType.CREATE_FILE:\n\t // Ensure parent exists.\n\t return this$1.stat(path.dirname(p), false, function (e, parentStats) {\n\t if (e) {\n\t cb(e);\n\t }\n\t else if (parentStats && !parentStats.isDirectory()) {\n\t cb(ApiError.ENOTDIR(path.dirname(p)));\n\t }\n\t else {\n\t this$1.createFile(p, flag, mode, cb);\n\t }\n\t });\n\t case ActionType.THROW_EXCEPTION:\n\t return cb(ApiError.ENOENT(p));\n\t default:\n\t return cb(new ApiError(ErrorCode.EINVAL, 'Invalid FileFlag object.'));\n\t }\n\t }\n\t else {\n\t // File exists.\n\t if (stats && stats.isDirectory()) {\n\t return cb(ApiError.EISDIR(p));\n\t }\n\t switch (flag.pathExistsAction()) {\n\t case ActionType.THROW_EXCEPTION:\n\t return cb(ApiError.EEXIST(p));\n\t case ActionType.TRUNCATE_FILE:\n\t // NOTE: In a previous implementation, we deleted the file and\n\t // re-created it. However, this created a race condition if another\n\t // asynchronous request was trying to read the file, as the file\n\t // would not exist for a small period of time.\n\t return this$1.openFile(p, flag, function (e, fd) {\n\t if (e) {\n\t cb(e);\n\t }\n\t else if (fd) {\n\t fd.truncate(0, function () {\n\t fd.sync(function () {\n\t cb(null, fd);\n\t });\n\t });\n\t }\n\t else {\n\t fail();\n\t }\n\t });\n\t case ActionType.NOP:\n\t return this$1.openFile(p, flag, cb);\n\t default:\n\t return cb(new ApiError(ErrorCode.EINVAL, 'Invalid FileFlag object.'));\n\t }\n\t }\n\t };\n\t this.stat(p, false, mustBeFile);\n\t};\n\tBaseFileSystem.prototype.rename = function rename (oldPath, newPath, cb) {\n\t cb(new ApiError(ErrorCode.ENOTSUP));\n\t};\n\tBaseFileSystem.prototype.renameSync = function renameSync (oldPath, newPath) {\n\t throw new ApiError(ErrorCode.ENOTSUP);\n\t};\n\tBaseFileSystem.prototype.stat = function stat (p, isLstat, cb) {\n\t cb(new ApiError(ErrorCode.ENOTSUP));\n\t};\n\tBaseFileSystem.prototype.statSync = function statSync (p, isLstat) {\n\t throw new ApiError(ErrorCode.ENOTSUP);\n\t};\n\t/**\n\t * Opens the file at path p with the given flag. The file must exist.\n\t * @param p The path to open.\n\t * @param flag The flag to use when opening the file.\n\t * @return A File object corresponding to the opened file.\n\t */\n\tBaseFileSystem.prototype.openFileSync = function openFileSync (p, flag, mode) {\n\t throw new ApiError(ErrorCode.ENOTSUP);\n\t};\n\t/**\n\t * Create the file at path p with the given mode. Then, open it with the given\n\t * flag.\n\t */\n\tBaseFileSystem.prototype.createFileSync = function createFileSync (p, flag, mode) {\n\t throw new ApiError(ErrorCode.ENOTSUP);\n\t};\n\tBaseFileSystem.prototype.openSync = function openSync (p, flag, mode) {\n\t // Check if the path exists, and is a file.\n\t var stats;\n\t try {\n\t stats = this.statSync(p, false);\n\t }\n\t catch (e) {\n\t // File does not exist.\n\t switch (flag.pathNotExistsAction()) {\n\t case ActionType.CREATE_FILE:\n\t // Ensure parent exists.\n\t var parentStats = this.statSync(path.dirname(p), false);\n\t if (!parentStats.isDirectory()) {\n\t throw ApiError.ENOTDIR(path.dirname(p));\n\t }\n\t return this.createFileSync(p, flag, mode);\n\t case ActionType.THROW_EXCEPTION:\n\t throw ApiError.ENOENT(p);\n\t default:\n\t throw new ApiError(ErrorCode.EINVAL, 'Invalid FileFlag object.');\n\t }\n\t }\n\t // File exists.\n\t if (stats.isDirectory()) {\n\t throw ApiError.EISDIR(p);\n\t }\n\t switch (flag.pathExistsAction()) {\n\t case ActionType.THROW_EXCEPTION:\n\t throw ApiError.EEXIST(p);\n\t case ActionType.TRUNCATE_FILE:\n\t // Delete file.\n\t this.unlinkSync(p);\n\t // Create file. Use the same mode as the old file.\n\t // Node itself modifies the ctime when this occurs, so this action\n\t // will preserve that behavior if the underlying file system\n\t // supports those properties.\n\t return this.createFileSync(p, flag, stats.mode);\n\t case ActionType.NOP:\n\t return this.openFileSync(p, flag, mode);\n\t default:\n\t throw new ApiError(ErrorCode.EINVAL, 'Invalid FileFlag object.');\n\t }\n\t};\n\tBaseFileSystem.prototype.unlink = function unlink (p, cb) {\n\t cb(new ApiError(ErrorCode.ENOTSUP));\n\t};\n\tBaseFileSystem.prototype.unlinkSync = function unlinkSync (p) {\n\t throw new ApiError(ErrorCode.ENOTSUP);\n\t};\n\tBaseFileSystem.prototype.rmdir = function rmdir (p, cb) {\n\t cb(new ApiError(ErrorCode.ENOTSUP));\n\t};\n\tBaseFileSystem.prototype.rmdirSync = function rmdirSync (p) {\n\t throw new ApiError(ErrorCode.ENOTSUP);\n\t};\n\tBaseFileSystem.prototype.mkdir = function mkdir (p, mode, cb) {\n\t cb(new ApiError(ErrorCode.ENOTSUP));\n\t};\n\tBaseFileSystem.prototype.mkdirSync = function mkdirSync (p, mode) {\n\t throw new ApiError(ErrorCode.ENOTSUP);\n\t};\n\tBaseFileSystem.prototype.readdir = function readdir (p, cb) {\n\t cb(new ApiError(ErrorCode.ENOTSUP));\n\t};\n\tBaseFileSystem.prototype.readdirSync = function readdirSync (p) {\n\t throw new ApiError(ErrorCode.ENOTSUP);\n\t};\n\tBaseFileSystem.prototype.exists = function exists (p, cb) {\n\t this.stat(p, null, function (err) {\n\t cb(!err);\n\t });\n\t};\n\tBaseFileSystem.prototype.existsSync = function existsSync (p) {\n\t try {\n\t this.statSync(p, true);\n\t return true;\n\t }\n\t catch (e) {\n\t return false;\n\t }\n\t};\n\tBaseFileSystem.prototype.realpath = function realpath (p, cache, cb) {\n\t if (this.supportsLinks()) {\n\t // The path could contain symlinks. Split up the path,\n\t // resolve any symlinks, return the resolved string.\n\t var splitPath = p.split(path.sep);\n\t // TODO: Simpler to just pass through file, find sep and such.\n\t for (var i = 0; i < splitPath.length; i++) {\n\t var addPaths = splitPath.slice(0, i + 1);\n\t splitPath[i] = path.join.apply(null, addPaths);\n\t }\n\t }\n\t else {\n\t // No symlinks. We just need to verify that it exists.\n\t this.exists(p, function (doesExist) {\n\t if (doesExist) {\n\t cb(null, p);\n\t }\n\t else {\n\t cb(ApiError.ENOENT(p));\n\t }\n\t });\n\t }\n\t};\n\tBaseFileSystem.prototype.realpathSync = function realpathSync (p, cache) {\n\t if (this.supportsLinks()) {\n\t // The path could contain symlinks. Split up the path,\n\t // resolve any symlinks, return the resolved string.\n\t var splitPath = p.split(path.sep);\n\t // TODO: Simpler to just pass through file, find sep and such.\n\t for (var i = 0; i < splitPath.length; i++) {\n\t var addPaths = splitPath.slice(0, i + 1);\n\t splitPath[i] = path.join.apply(path, addPaths);\n\t }\n\t return splitPath.join(path.sep);\n\t }\n\t else {\n\t // No symlinks. We just need to verify that it exists.\n\t if (this.existsSync(p)) {\n\t return p;\n\t }\n\t else {\n\t throw ApiError.ENOENT(p);\n\t }\n\t }\n\t};\n\tBaseFileSystem.prototype.truncate = function truncate (p, len, cb) {\n\t this.open(p, FileFlag.getFileFlag('r+'), 0x1a4, (function (er, fd) {\n\t if (er) {\n\t return cb(er);\n\t }\n\t fd.truncate(len, (function (er) {\n\t fd.close((function (er2) {\n\t cb(er || er2);\n\t }));\n\t }));\n\t }));\n\t};\n\tBaseFileSystem.prototype.truncateSync = function truncateSync (p, len) {\n\t var fd = this.openSync(p, FileFlag.getFileFlag('r+'), 0x1a4);\n\t // Need to safely close FD, regardless of whether or not truncate succeeds.\n\t try {\n\t fd.truncateSync(len);\n\t }\n\t catch (e) {\n\t throw e;\n\t }\n\t finally {\n\t fd.closeSync();\n\t }\n\t};\n\tBaseFileSystem.prototype.readFile = function readFile (fname, encoding, flag, cb) {\n\t // Wrap cb in file closing code.\n\t var oldCb = cb;\n\t // Get file.\n\t this.open(fname, flag, 0x1a4, function (err, fd) {\n\t if (err) {\n\t return cb(err);\n\t }\n\t cb = function (err, arg) {\n\t fd.close(function (err2) {\n\t if (!err) {\n\t err = err2;\n\t }\n\t return oldCb(err, arg);\n\t });\n\t };\n\t fd.stat(function (err, stat) {\n\t if (err) {\n\t return cb(err);\n\t }\n\t // Allocate buffer.\n\t var buf = Buffer.alloc(stat.size);\n\t fd.read(buf, 0, stat.size, 0, function (err) {\n\t if (err) {\n\t return cb(err);\n\t }\n\t else if (encoding === null) {\n\t return cb(err, buf);\n\t }\n\t try {\n\t cb(null, buf.toString(encoding));\n\t }\n\t catch (e) {\n\t cb(e);\n\t }\n\t });\n\t });\n\t });\n\t};\n\tBaseFileSystem.prototype.readFileSync = function readFileSync (fname, encoding, flag) {\n\t // Get file.\n\t var fd = this.openSync(fname, flag, 0x1a4);\n\t try {\n\t var stat = fd.statSync();\n\t // Allocate buffer.\n\t var buf = Buffer.alloc(stat.size);\n\t fd.readSync(buf, 0, stat.size, 0);\n\t fd.closeSync();\n\t if (encoding === null) {\n\t return buf;\n\t }\n\t return buf.toString(encoding);\n\t }\n\t finally {\n\t fd.closeSync();\n\t }\n\t};\n\tBaseFileSystem.prototype.writeFile = function writeFile (fname, data, encoding, flag, mode, cb) {\n\t // Wrap cb in file closing code.\n\t var oldCb = cb;\n\t // Get file.\n\t this.open(fname, flag, 0x1a4, function (err, fd) {\n\t if (err) {\n\t return cb(err);\n\t }\n\t cb = function (err) {\n\t fd.close(function (err2) {\n\t oldCb(err ? err : err2);\n\t });\n\t };\n\t try {\n\t if (typeof data === 'string') {\n\t data = Buffer.from(data, encoding);\n\t }\n\t }\n\t catch (e) {\n\t return cb(e);\n\t }\n\t // Write into file.\n\t fd.write(data, 0, data.length, 0, cb);\n\t });\n\t};\n\tBaseFileSystem.prototype.writeFileSync = function writeFileSync (fname, data, encoding, flag, mode) {\n\t // Get file.\n\t var fd = this.openSync(fname, flag, mode);\n\t try {\n\t if (typeof data === 'string') {\n\t data = Buffer.from(data, encoding);\n\t }\n\t // Write into file.\n\t fd.writeSync(data, 0, data.length, 0);\n\t }\n\t finally {\n\t fd.closeSync();\n\t }\n\t};\n\tBaseFileSystem.prototype.appendFile = function appendFile (fname, data, encoding, flag, mode, cb) {\n\t // Wrap cb in file closing code.\n\t var oldCb = cb;\n\t this.open(fname, flag, mode, function (err, fd) {\n\t if (err) {\n\t return cb(err);\n\t }\n\t cb = function (err) {\n\t fd.close(function (err2) {\n\t oldCb(err ? err : err2);\n\t });\n\t };\n\t if (typeof data === 'string') {\n\t data = Buffer.from(data, encoding);\n\t }\n\t fd.write(data, 0, data.length, null, cb);\n\t });\n\t};\n\tBaseFileSystem.prototype.appendFileSync = function appendFileSync (fname, data, encoding, flag, mode) {\n\t var fd = this.openSync(fname, flag, mode);\n\t try {\n\t if (typeof data === 'string') {\n\t data = Buffer.from(data, encoding);\n\t }\n\t fd.writeSync(data, 0, data.length, null);\n\t }\n\t finally {\n\t fd.closeSync();\n\t }\n\t};\n\tBaseFileSystem.prototype.chmod = function chmod (p, isLchmod, mode, cb) {\n\t cb(new ApiError(ErrorCode.ENOTSUP));\n\t};\n\tBaseFileSystem.prototype.chmodSync = function chmodSync (p, isLchmod, mode) {\n\t throw new ApiError(ErrorCode.ENOTSUP);\n\t};\n\tBaseFileSystem.prototype.chown = function chown (p, isLchown, uid, gid, cb) {\n\t cb(new ApiError(ErrorCode.ENOTSUP));\n\t};\n\tBaseFileSystem.prototype.chownSync = function chownSync (p, isLchown, uid, gid) {\n\t throw new ApiError(ErrorCode.ENOTSUP);\n\t};\n\tBaseFileSystem.prototype.utimes = function utimes (p, atime, mtime, cb) {\n\t cb(new ApiError(ErrorCode.ENOTSUP));\n\t};\n\tBaseFileSystem.prototype.utimesSync = function utimesSync (p, atime, mtime) {\n\t throw new ApiError(ErrorCode.ENOTSUP);\n\t};\n\tBaseFileSystem.prototype.link = function link (srcpath, dstpath, cb) {\n\t cb(new ApiError(ErrorCode.ENOTSUP));\n\t};\n\tBaseFileSystem.prototype.linkSync = function linkSync (srcpath, dstpath) {\n\t throw new ApiError(ErrorCode.ENOTSUP);\n\t};\n\tBaseFileSystem.prototype.symlink = function symlink (srcpath, dstpath, type, cb) {\n\t cb(new ApiError(ErrorCode.ENOTSUP));\n\t};\n\tBaseFileSystem.prototype.symlinkSync = function symlinkSync (srcpath, dstpath, type) {\n\t throw new ApiError(ErrorCode.ENOTSUP);\n\t};\n\tBaseFileSystem.prototype.readlink = function readlink (p, cb) {\n\t cb(new ApiError(ErrorCode.ENOTSUP));\n\t};\n\tBaseFileSystem.prototype.readlinkSync = function readlinkSync (p) {\n\t throw new ApiError(ErrorCode.ENOTSUP);\n\t};\n\t/**\n\t * Implements the asynchronous API in terms of the synchronous API.\n\t * @class SynchronousFileSystem\n\t */\n\tvar SynchronousFileSystem = (function (BaseFileSystem) {\n\t function SynchronousFileSystem () {\n\t BaseFileSystem.apply(this, arguments);\n\t }\n\t\n\t if ( BaseFileSystem ) SynchronousFileSystem.__proto__ = BaseFileSystem;\n\t SynchronousFileSystem.prototype = Object.create( BaseFileSystem && BaseFileSystem.prototype );\n\t SynchronousFileSystem.prototype.constructor = SynchronousFileSystem;\n\t\n\t SynchronousFileSystem.prototype.supportsSynch = function supportsSynch () {\n\t return true;\n\t };\n\t SynchronousFileSystem.prototype.rename = function rename (oldPath, newPath, cb) {\n\t try {\n\t this.renameSync(oldPath, newPath);\n\t cb();\n\t }\n\t catch (e) {\n\t cb(e);\n\t }\n\t };\n\t SynchronousFileSystem.prototype.stat = function stat (p, isLstat, cb) {\n\t try {\n\t cb(null, this.statSync(p, isLstat));\n\t }\n\t catch (e) {\n\t cb(e);\n\t }\n\t };\n\t SynchronousFileSystem.prototype.open = function open (p, flags, mode, cb) {\n\t try {\n\t cb(null, this.openSync(p, flags, mode));\n\t }\n\t catch (e) {\n\t cb(e);\n\t }\n\t };\n\t SynchronousFileSystem.prototype.unlink = function unlink (p, cb) {\n\t try {\n\t this.unlinkSync(p);\n\t cb();\n\t }\n\t catch (e) {\n\t cb(e);\n\t }\n\t };\n\t SynchronousFileSystem.prototype.rmdir = function rmdir (p, cb) {\n\t try {\n\t this.rmdirSync(p);\n\t cb();\n\t }\n\t catch (e) {\n\t cb(e);\n\t }\n\t };\n\t SynchronousFileSystem.prototype.mkdir = function mkdir (p, mode, cb) {\n\t try {\n\t this.mkdirSync(p, mode);\n\t cb();\n\t }\n\t catch (e) {\n\t cb(e);\n\t }\n\t };\n\t SynchronousFileSystem.prototype.readdir = function readdir (p, cb) {\n\t try {\n\t cb(null, this.readdirSync(p));\n\t }\n\t catch (e) {\n\t cb(e);\n\t }\n\t };\n\t SynchronousFileSystem.prototype.chmod = function chmod (p, isLchmod, mode, cb) {\n\t try {\n\t this.chmodSync(p, isLchmod, mode);\n\t cb();\n\t }\n\t catch (e) {\n\t cb(e);\n\t }\n\t };\n\t SynchronousFileSystem.prototype.chown = function chown (p, isLchown, uid, gid, cb) {\n\t try {\n\t this.chownSync(p, isLchown, uid, gid);\n\t cb();\n\t }\n\t catch (e) {\n\t cb(e);\n\t }\n\t };\n\t SynchronousFileSystem.prototype.utimes = function utimes (p, atime, mtime, cb) {\n\t try {\n\t this.utimesSync(p, atime, mtime);\n\t cb();\n\t }\n\t catch (e) {\n\t cb(e);\n\t }\n\t };\n\t SynchronousFileSystem.prototype.link = function link (srcpath, dstpath, cb) {\n\t try {\n\t this.linkSync(srcpath, dstpath);\n\t cb();\n\t }\n\t catch (e) {\n\t cb(e);\n\t }\n\t };\n\t SynchronousFileSystem.prototype.symlink = function symlink (srcpath, dstpath, type, cb) {\n\t try {\n\t this.symlinkSync(srcpath, dstpath, type);\n\t cb();\n\t }\n\t catch (e) {\n\t cb(e);\n\t }\n\t };\n\t SynchronousFileSystem.prototype.readlink = function readlink (p, cb) {\n\t try {\n\t cb(null, this.readlinkSync(p));\n\t }\n\t catch (e) {\n\t cb(e);\n\t }\n\t };\n\t\n\t return SynchronousFileSystem;\n\t}(BaseFileSystem));\n\t\n\t/**\n\t * Base class that contains shared implementations of functions for the file\n\t * object.\n\t */\n\tvar BaseFile = function BaseFile () {};\n\t\n\tBaseFile.prototype.sync = function sync (cb) {\n\t cb(new ApiError(ErrorCode.ENOTSUP));\n\t};\n\tBaseFile.prototype.syncSync = function syncSync () {\n\t throw new ApiError(ErrorCode.ENOTSUP);\n\t};\n\tBaseFile.prototype.datasync = function datasync (cb) {\n\t this.sync(cb);\n\t};\n\tBaseFile.prototype.datasyncSync = function datasyncSync () {\n\t return this.syncSync();\n\t};\n\tBaseFile.prototype.chown = function chown (uid, gid, cb) {\n\t cb(new ApiError(ErrorCode.ENOTSUP));\n\t};\n\tBaseFile.prototype.chownSync = function chownSync (uid, gid) {\n\t throw new ApiError(ErrorCode.ENOTSUP);\n\t};\n\tBaseFile.prototype.chmod = function chmod (mode, cb) {\n\t cb(new ApiError(ErrorCode.ENOTSUP));\n\t};\n\tBaseFile.prototype.chmodSync = function chmodSync (mode) {\n\t throw new ApiError(ErrorCode.ENOTSUP);\n\t};\n\tBaseFile.prototype.utimes = function utimes (atime, mtime, cb) {\n\t cb(new ApiError(ErrorCode.ENOTSUP));\n\t};\n\tBaseFile.prototype.utimesSync = function utimesSync (atime, mtime) {\n\t throw new ApiError(ErrorCode.ENOTSUP);\n\t};\n\t\n\t/**\n\t * An implementation of the File interface that operates on a file that is\n\t * completely in-memory. PreloadFiles are backed by a Buffer.\n\t *\n\t * This is also an abstract class, as it lacks an implementation of 'sync' and\n\t * 'close'. Each filesystem that wishes to use this file representation must\n\t * extend this class and implement those two methods.\n\t * @todo 'close' lever that disables functionality once closed.\n\t */\n\tvar PreloadFile = (function (BaseFile$$1) {\n\t function PreloadFile(_fs, _path, _flag, _stat, contents) {\n\t BaseFile$$1.call(this);\n\t this._pos = 0;\n\t this._dirty = false;\n\t this._fs = _fs;\n\t this._path = _path;\n\t this._flag = _flag;\n\t this._stat = _stat;\n\t if (contents) {\n\t this._buffer = contents;\n\t }\n\t else {\n\t // Empty buffer. It'll expand once we write stuff to it.\n\t this._buffer = emptyBuffer();\n\t }\n\t // Note: This invariant is *not* maintained once the file starts getting\n\t // modified.\n\t // Note: Only actually matters if file is readable, as writeable modes may\n\t // truncate/append to file.\n\t if (this._stat.size !== this._buffer.length && this._flag.isReadable()) {\n\t throw new Error((\"Invalid buffer: Buffer is \" + (this._buffer.length) + \" long, yet Stats object specifies that file is \" + (this._stat.size) + \" long.\"));\n\t }\n\t }\n\t\n\t if ( BaseFile$$1 ) PreloadFile.__proto__ = BaseFile$$1;\n\t PreloadFile.prototype = Object.create( BaseFile$$1 && BaseFile$$1.prototype );\n\t PreloadFile.prototype.constructor = PreloadFile;\n\t /**\n\t * NONSTANDARD: Get the underlying buffer for this file. !!DO NOT MUTATE!! Will mess up dirty tracking.\n\t */\n\t PreloadFile.prototype.getBuffer = function getBuffer () {\n\t return this._buffer;\n\t };\n\t /**\n\t * NONSTANDARD: Get underlying stats for this file. !!DO NOT MUTATE!!\n\t */\n\t PreloadFile.prototype.getStats = function getStats () {\n\t return this._stat;\n\t };\n\t PreloadFile.prototype.getFlag = function getFlag () {\n\t return this._flag;\n\t };\n\t /**\n\t * Get the path to this file.\n\t * @return [String] The path to the file.\n\t */\n\t PreloadFile.prototype.getPath = function getPath () {\n\t return this._path;\n\t };\n\t /**\n\t * Get the current file position.\n\t *\n\t * We emulate the following bug mentioned in the Node documentation:\n\t * > On Linux, positional writes don't work when the file is opened in append\n\t * mode. The kernel ignores the position argument and always appends the data\n\t * to the end of the file.\n\t * @return [Number] The current file position.\n\t */\n\t PreloadFile.prototype.getPos = function getPos () {\n\t if (this._flag.isAppendable()) {\n\t return this._stat.size;\n\t }\n\t return this._pos;\n\t };\n\t /**\n\t * Advance the current file position by the indicated number of positions.\n\t * @param [Number] delta\n\t */\n\t PreloadFile.prototype.advancePos = function advancePos (delta) {\n\t return this._pos += delta;\n\t };\n\t /**\n\t * Set the file position.\n\t * @param [Number] newPos\n\t */\n\t PreloadFile.prototype.setPos = function setPos (newPos) {\n\t return this._pos = newPos;\n\t };\n\t /**\n\t * **Core**: Asynchronous sync. Must be implemented by subclasses of this\n\t * class.\n\t * @param [Function(BrowserFS.ApiError)] cb\n\t */\n\t PreloadFile.prototype.sync = function sync (cb) {\n\t try {\n\t this.syncSync();\n\t cb();\n\t }\n\t catch (e) {\n\t cb(e);\n\t }\n\t };\n\t /**\n\t * **Core**: Synchronous sync.\n\t */\n\t PreloadFile.prototype.syncSync = function syncSync () {\n\t throw new ApiError(ErrorCode.ENOTSUP);\n\t };\n\t /**\n\t * **Core**: Asynchronous close. Must be implemented by subclasses of this\n\t * class.\n\t * @param [Function(BrowserFS.ApiError)] cb\n\t */\n\t PreloadFile.prototype.close = function close (cb) {\n\t try {\n\t this.closeSync();\n\t cb();\n\t }\n\t catch (e) {\n\t cb(e);\n\t }\n\t };\n\t /**\n\t * **Core**: Synchronous close.\n\t */\n\t PreloadFile.prototype.closeSync = function closeSync () {\n\t throw new ApiError(ErrorCode.ENOTSUP);\n\t };\n\t /**\n\t * Asynchronous `stat`.\n\t * @param [Function(BrowserFS.ApiError, BrowserFS.node.fs.Stats)] cb\n\t */\n\t PreloadFile.prototype.stat = function stat (cb) {\n\t try {\n\t cb(null, this._stat.clone());\n\t }\n\t catch (e) {\n\t cb(e);\n\t }\n\t };\n\t /**\n\t * Synchronous `stat`.\n\t */\n\t PreloadFile.prototype.statSync = function statSync () {\n\t return this._stat.clone();\n\t };\n\t /**\n\t * Asynchronous truncate.\n\t * @param [Number] len\n\t * @param [Function(BrowserFS.ApiError)] cb\n\t */\n\t PreloadFile.prototype.truncate = function truncate (len, cb) {\n\t try {\n\t this.truncateSync(len);\n\t if (this._flag.isSynchronous() && !_fsMock.getRootFS().supportsSynch()) {\n\t this.sync(cb);\n\t }\n\t cb();\n\t }\n\t catch (e) {\n\t return cb(e);\n\t }\n\t };\n\t /**\n\t * Synchronous truncate.\n\t * @param [Number] len\n\t */\n\t PreloadFile.prototype.truncateSync = function truncateSync (len) {\n\t this._dirty = true;\n\t if (!this._flag.isWriteable()) {\n\t throw new ApiError(ErrorCode.EPERM, 'File not opened with a writeable mode.');\n\t }\n\t this._stat.mtime = new Date();\n\t if (len > this._buffer.length) {\n\t var buf = Buffer.alloc(len - this._buffer.length, 0);\n\t // Write will set @_stat.size for us.\n\t this.writeSync(buf, 0, buf.length, this._buffer.length);\n\t if (this._flag.isSynchronous() && _fsMock.getRootFS().supportsSynch()) {\n\t this.syncSync();\n\t }\n\t return;\n\t }\n\t this._stat.size = len;\n\t // Truncate buffer to 'len'.\n\t var newBuff = Buffer.alloc(len);\n\t this._buffer.copy(newBuff, 0, 0, len);\n\t this._buffer = newBuff;\n\t if (this._flag.isSynchronous() && _fsMock.getRootFS().supportsSynch()) {\n\t this.syncSync();\n\t }\n\t };\n\t /**\n\t * Write buffer to the file.\n\t * Note that it is unsafe to use fs.write multiple times on the same file\n\t * without waiting for the callback.\n\t * @param [BrowserFS.node.Buffer] buffer Buffer containing the data to write to\n\t * the file.\n\t * @param [Number] offset Offset in the buffer to start reading data from.\n\t * @param [Number] length The amount of bytes to write to the file.\n\t * @param [Number] position Offset from the beginning of the file where this\n\t * data should be written. If position is null, the data will be written at\n\t * the current position.\n\t * @param [Function(BrowserFS.ApiError, Number, BrowserFS.node.Buffer)]\n\t * cb The number specifies the number of bytes written into the file.\n\t */\n\t PreloadFile.prototype.write = function write (buffer$$1, offset, length, position, cb) {\n\t try {\n\t cb(null, this.writeSync(buffer$$1, offset, length, position), buffer$$1);\n\t }\n\t catch (e) {\n\t cb(e);\n\t }\n\t };\n\t /**\n\t * Write buffer to the file.\n\t * Note that it is unsafe to use fs.writeSync multiple times on the same file\n\t * without waiting for the callback.\n\t * @param [BrowserFS.node.Buffer] buffer Buffer containing the data to write to\n\t * the file.\n\t * @param [Number] offset Offset in the buffer to start reading data from.\n\t * @param [Number] length The amount of bytes to write to the file.\n\t * @param [Number] position Offset from the beginning of the file where this\n\t * data should be written. If position is null, the data will be written at\n\t * the current position.\n\t * @return [Number]\n\t */\n\t PreloadFile.prototype.writeSync = function writeSync (buffer$$1, offset, length, position) {\n\t this._dirty = true;\n\t if (position === undefined || position === null) {\n\t position = this.getPos();\n\t }\n\t if (!this._flag.isWriteable()) {\n\t throw new ApiError(ErrorCode.EPERM, 'File not opened with a writeable mode.');\n\t }\n\t var endFp = position + length;\n\t if (endFp > this._stat.size) {\n\t this._stat.size = endFp;\n\t if (endFp > this._buffer.length) {\n\t // Extend the buffer!\n\t var newBuff = Buffer.alloc(endFp);\n\t this._buffer.copy(newBuff);\n\t this._buffer = newBuff;\n\t }\n\t }\n\t var len = buffer$$1.copy(this._buffer, position, offset, offset + length);\n\t this._stat.mtime = new Date();\n\t if (this._flag.isSynchronous()) {\n\t this.syncSync();\n\t return len;\n\t }\n\t this.setPos(position + len);\n\t return len;\n\t };\n\t /**\n\t * Read data from the file.\n\t * @param [BrowserFS.node.Buffer] buffer The buffer that the data will be\n\t * written to.\n\t * @param [Number] offset The offset within the buffer where writing will\n\t * start.\n\t * @param [Number] length An integer specifying the number of bytes to read.\n\t * @param [Number] position An integer specifying where to begin reading from\n\t * in the file. If position is null, data will be read from the current file\n\t * position.\n\t * @param [Function(BrowserFS.ApiError, Number, BrowserFS.node.Buffer)] cb The\n\t * number is the number of bytes read\n\t */\n\t PreloadFile.prototype.read = function read (buffer$$1, offset, length, position, cb) {\n\t try {\n\t cb(null, this.readSync(buffer$$1, offset, length, position), buffer$$1);\n\t }\n\t catch (e) {\n\t cb(e);\n\t }\n\t };\n\t /**\n\t * Read data from the file.\n\t * @param [BrowserFS.node.Buffer] buffer The buffer that the data will be\n\t * written to.\n\t * @param [Number] offset The offset within the buffer where writing will\n\t * start.\n\t * @param [Number] length An integer specifying the number of bytes to read.\n\t * @param [Number] position An integer specifying where to begin reading from\n\t * in the file. If position is null, data will be read from the current file\n\t * position.\n\t * @return [Number]\n\t */\n\t PreloadFile.prototype.readSync = function readSync (buffer$$1, offset, length, position) {\n\t if (!this._flag.isReadable()) {\n\t throw new ApiError(ErrorCode.EPERM, 'File not opened with a readable mode.');\n\t }\n\t if (position === undefined || position === null) {\n\t position = this.getPos();\n\t }\n\t var endRead = position + length;\n\t if (endRead > this._stat.size) {\n\t length = this._stat.size - position;\n\t }\n\t var rv = this._buffer.copy(buffer$$1, offset, position, position + length);\n\t this._stat.atime = new Date();\n\t this._pos = position + length;\n\t return rv;\n\t };\n\t /**\n\t * Asynchronous `fchmod`.\n\t * @param [Number|String] mode\n\t * @param [Function(BrowserFS.ApiError)] cb\n\t */\n\t PreloadFile.prototype.chmod = function chmod (mode, cb) {\n\t try {\n\t this.chmodSync(mode);\n\t cb();\n\t }\n\t catch (e) {\n\t cb(e);\n\t }\n\t };\n\t /**\n\t * Asynchronous `fchmod`.\n\t * @param [Number] mode\n\t */\n\t PreloadFile.prototype.chmodSync = function chmodSync (mode) {\n\t if (!this._fs.supportsProps()) {\n\t throw new ApiError(ErrorCode.ENOTSUP);\n\t }\n\t this._dirty = true;\n\t this._stat.chmod(mode);\n\t this.syncSync();\n\t };\n\t PreloadFile.prototype.isDirty = function isDirty () {\n\t return this._dirty;\n\t };\n\t /**\n\t * Resets the dirty bit. Should only be called after a sync has completed successfully.\n\t */\n\t PreloadFile.prototype.resetDirty = function resetDirty () {\n\t this._dirty = false;\n\t };\n\t\n\t return PreloadFile;\n\t}(BaseFile));\n\t\n\t/**\n\t * File class for the InMemory and XHR file systems.\n\t * Doesn't sync to anything, so it works nicely for memory-only files.\n\t */\n\tvar NoSyncFile = (function (PreloadFile) {\n\t function NoSyncFile(_fs, _path, _flag, _stat, contents) {\n\t PreloadFile.call(this, _fs, _path, _flag, _stat, contents);\n\t }\n\t\n\t if ( PreloadFile ) NoSyncFile.__proto__ = PreloadFile;\n\t NoSyncFile.prototype = Object.create( PreloadFile && PreloadFile.prototype );\n\t NoSyncFile.prototype.constructor = NoSyncFile;\n\t /**\n\t * Asynchronous sync. Doesn't do anything, simply calls the cb.\n\t * @param [Function(BrowserFS.ApiError)] cb\n\t */\n\t NoSyncFile.prototype.sync = function sync (cb) {\n\t cb();\n\t };\n\t /**\n\t * Synchronous sync. Doesn't do anything.\n\t */\n\t NoSyncFile.prototype.syncSync = function syncSync () {\n\t // NOP.\n\t };\n\t /**\n\t * Asynchronous close. Doesn't do anything, simply calls the cb.\n\t * @param [Function(BrowserFS.ApiError)] cb\n\t */\n\t NoSyncFile.prototype.close = function close (cb) {\n\t cb();\n\t };\n\t /**\n\t * Synchronous close. Doesn't do anything.\n\t */\n\t NoSyncFile.prototype.closeSync = function closeSync () {\n\t // NOP.\n\t };\n\t\n\t return NoSyncFile;\n\t}(PreloadFile));\n\t\n\t/**\n\t * We define our own file to interpose on syncSync() for mirroring purposes.\n\t */\n\tvar MirrorFile = (function (PreloadFile$$1) {\n\t function MirrorFile(fs, path$$1, flag, stat, data) {\n\t PreloadFile$$1.call(this, fs, path$$1, flag, stat, data);\n\t }\n\t\n\t if ( PreloadFile$$1 ) MirrorFile.__proto__ = PreloadFile$$1;\n\t MirrorFile.prototype = Object.create( PreloadFile$$1 && PreloadFile$$1.prototype );\n\t MirrorFile.prototype.constructor = MirrorFile;\n\t MirrorFile.prototype.syncSync = function syncSync () {\n\t if (this.isDirty()) {\n\t this._fs._syncSync(this);\n\t this.resetDirty();\n\t }\n\t };\n\t MirrorFile.prototype.closeSync = function closeSync () {\n\t this.syncSync();\n\t };\n\t\n\t return MirrorFile;\n\t}(PreloadFile));\n\t/**\n\t * AsyncMirrorFS mirrors a synchronous filesystem into an asynchronous filesystem\n\t * by:\n\t *\n\t * * Performing operations over the in-memory copy, while asynchronously pipelining them\n\t * to the backing store.\n\t * * During application loading, the contents of the async file system can be reloaded into\n\t * the synchronous store, if desired.\n\t *\n\t * The two stores will be kept in sync. The most common use-case is to pair a synchronous\n\t * in-memory filesystem with an asynchronous backing store.\n\t *\n\t * Example: Mirroring an IndexedDB file system to an in memory file system. Now, you can use\n\t * IndexedDB synchronously.\n\t *\n\t * ```javascript\n\t * BrowserFS.configure({\n\t * fs: \"AsyncMirror\",\n\t * options: {\n\t * sync: { fs: \"InMemory\" },\n\t * async: { fs: \"IndexedDB\" }\n\t * }\n\t * }, function(e) {\n\t * // BrowserFS is initialized and ready-to-use!\n\t * });\n\t * ```\n\t *\n\t * Or, alternatively:\n\t *\n\t * ```javascript\n\t * BrowserFS.FileSystem.IndexedDB.Create(function(e, idbfs) {\n\t * BrowserFS.FileSystem.InMemory.Create(function(e, inMemory) {\n\t * BrowserFS.FileSystem.AsyncMirror({\n\t * sync: inMemory, async: idbfs\n\t * }, function(e, mirrored) {\n\t * BrowserFS.initialize(mirrored);\n\t * });\n\t * });\n\t * });\n\t * ```\n\t */\n\tvar AsyncMirror = (function (SynchronousFileSystem$$1) {\n\t function AsyncMirror(sync, async, deprecateMsg) {\n\t if ( deprecateMsg === void 0 ) deprecateMsg = true;\n\t\n\t SynchronousFileSystem$$1.call(this);\n\t /**\n\t * Queue of pending asynchronous operations.\n\t */\n\t this._queue = [];\n\t this._queueRunning = false;\n\t this._isInitialized = false;\n\t this._initializeCallbacks = [];\n\t this._sync = sync;\n\t this._async = async;\n\t if (!sync.supportsSynch()) {\n\t throw new Error(\"The first argument to AsyncMirror needs to be a synchronous file system.\");\n\t }\n\t deprecationMessage(deprecateMsg, AsyncMirror.Name, { sync: \"sync file system instance\", async: \"async file system instance\" });\n\t }\n\t\n\t if ( SynchronousFileSystem$$1 ) AsyncMirror.__proto__ = SynchronousFileSystem$$1;\n\t AsyncMirror.prototype = Object.create( SynchronousFileSystem$$1 && SynchronousFileSystem$$1.prototype );\n\t AsyncMirror.prototype.constructor = AsyncMirror;\n\t /**\n\t * Constructs and initializes an AsyncMirror file system with the given options.\n\t */\n\t AsyncMirror.Create = function Create (opts, cb) {\n\t try {\n\t var fs = new AsyncMirror(opts.sync, opts.async, false);\n\t fs.initialize(function (e) {\n\t if (e) {\n\t cb(e);\n\t }\n\t else {\n\t cb(null, fs);\n\t }\n\t }, false);\n\t }\n\t catch (e) {\n\t cb(e);\n\t }\n\t };\n\t AsyncMirror.isAvailable = function isAvailable () {\n\t return true;\n\t };\n\t AsyncMirror.prototype.getName = function getName () {\n\t return AsyncMirror.Name;\n\t };\n\t AsyncMirror.prototype._syncSync = function _syncSync (fd) {\n\t this._sync.writeFileSync(fd.getPath(), fd.getBuffer(), null, FileFlag.getFileFlag('w'), fd.getStats().mode);\n\t this.enqueueOp({\n\t apiMethod: 'writeFile',\n\t arguments: [fd.getPath(), fd.getBuffer(), null, fd.getFlag(), fd.getStats().mode]\n\t });\n\t };\n\t /**\n\t * Called once to load up files from async storage into sync storage.\n\t */\n\t AsyncMirror.prototype.initialize = function initialize (userCb, deprecateMsg) {\n\t var this$1 = this;\n\t if ( deprecateMsg === void 0 ) deprecateMsg = true;\n\t\n\t if (deprecateMsg) {\n\t console.warn(\"[AsyncMirror] AsyncMirror.initialize() is deprecated and will be removed in the next major version. Please use 'AsyncMirror.Create({ sync: (sync file system instance), async: (async file system instance)}, cb)' to create and initialize AsyncMirror instances.\");\n\t }\n\t var callbacks = this._initializeCallbacks;\n\t var end = function (e) {\n\t this$1._isInitialized = !e;\n\t this$1._initializeCallbacks = [];\n\t callbacks.forEach(function (cb) { return cb(e); });\n\t };\n\t if (!this._isInitialized) {\n\t // First call triggers initialization, the rest wait.\n\t if (callbacks.push(userCb) === 1) {\n\t var copyDirectory = function (p, mode, cb) {\n\t if (p !== '/') {\n\t this$1._sync.mkdirSync(p, mode);\n\t }\n\t this$1._async.readdir(p, function (err, files) {\n\t var i = 0;\n\t // NOTE: This function must not be in a lexically nested statement,\n\t // such as an if or while statement. Safari refuses to run the\n\t // script since it is undefined behavior.\n\t function copyNextFile(err) {\n\t if (err) {\n\t cb(err);\n\t }\n\t else if (i < files.length) {\n\t copyItem(path.join(p, files[i]), copyNextFile);\n\t i++;\n\t }\n\t else {\n\t cb();\n\t }\n\t }\n\t if (err) {\n\t cb(err);\n\t }\n\t else {\n\t copyNextFile();\n\t }\n\t });\n\t }, copyFile = function (p, mode, cb) {\n\t this$1._async.readFile(p, null, FileFlag.getFileFlag('r'), function (err, data) {\n\t if (err) {\n\t cb(err);\n\t }\n\t else {\n\t try {\n\t this$1._sync.writeFileSync(p, data, null, FileFlag.getFileFlag('w'), mode);\n\t }\n\t catch (e) {\n\t err = e;\n\t }\n\t finally {\n\t cb(err);\n\t }\n\t }\n\t });\n\t }, copyItem = function (p, cb) {\n\t this$1._async.stat(p, false, function (err, stats) {\n\t if (err) {\n\t cb(err);\n\t }\n\t else if (stats.isDirectory()) {\n\t copyDirectory(p, stats.mode, cb);\n\t }\n\t else {\n\t copyFile(p, stats.mode, cb);\n\t }\n\t });\n\t };\n\t copyDirectory('/', 0, end);\n\t }\n\t }\n\t else {\n\t userCb();\n\t }\n\t };\n\t AsyncMirror.prototype.isReadOnly = function isReadOnly () { return false; };\n\t AsyncMirror.prototype.supportsSynch = function supportsSynch () { return true; };\n\t AsyncMirror.prototype.supportsLinks = function supportsLinks () { return false; };\n\t AsyncMirror.prototype.supportsProps = function supportsProps () { return this._sync.supportsProps() && this._async.supportsProps(); };\n\t AsyncMirror.prototype.renameSync = function renameSync (oldPath, newPath) {\n\t this.checkInitialized();\n\t this._sync.renameSync(oldPath, newPath);\n\t this.enqueueOp({\n\t apiMethod: 'rename',\n\t arguments: [oldPath, newPath]\n\t });\n\t };\n\t AsyncMirror.prototype.statSync = function statSync (p, isLstat) {\n\t this.checkInitialized();\n\t return this._sync.statSync(p, isLstat);\n\t };\n\t AsyncMirror.prototype.openSync = function openSync (p, flag, mode) {\n\t this.checkInitialized();\n\t // Sanity check: Is this open/close permitted?\n\t var fd = this._sync.openSync(p, flag, mode);\n\t fd.closeSync();\n\t return new MirrorFile(this, p, flag, this._sync.statSync(p, false), this._sync.readFileSync(p, null, FileFlag.getFileFlag('r')));\n\t };\n\t AsyncMirror.prototype.unlinkSync = function unlinkSync (p) {\n\t this.checkInitialized();\n\t this._sync.unlinkSync(p);\n\t this.enqueueOp({\n\t apiMethod: 'unlink',\n\t arguments: [p]\n\t });\n\t };\n\t AsyncMirror.prototype.rmdirSync = function rmdirSync (p) {\n\t this.checkInitialized();\n\t this._sync.rmdirSync(p);\n\t this.enqueueOp({\n\t apiMethod: 'rmdir',\n\t arguments: [p]\n\t });\n\t };\n\t AsyncMirror.prototype.mkdirSync = function mkdirSync (p, mode) {\n\t this.checkInitialized();\n\t this._sync.mkdirSync(p, mode);\n\t this.enqueueOp({\n\t apiMethod: 'mkdir',\n\t arguments: [p, mode]\n\t });\n\t };\n\t AsyncMirror.prototype.readdirSync = function readdirSync (p) {\n\t this.checkInitialized();\n\t return this._sync.readdirSync(p);\n\t };\n\t AsyncMirror.prototype.existsSync = function existsSync (p) {\n\t this.checkInitialized();\n\t return this._sync.existsSync(p);\n\t };\n\t AsyncMirror.prototype.chmodSync = function chmodSync (p, isLchmod, mode) {\n\t this.checkInitialized();\n\t this._sync.chmodSync(p, isLchmod, mode);\n\t this.enqueueOp({\n\t apiMethod: 'chmod',\n\t arguments: [p, isLchmod, mode]\n\t });\n\t };\n\t AsyncMirror.prototype.chownSync = function chownSync (p, isLchown, uid, gid) {\n\t this.checkInitialized();\n\t this._sync.chownSync(p, isLchown, uid, gid);\n\t this.enqueueOp({\n\t apiMethod: 'chown',\n\t arguments: [p, isLchown, uid, gid]\n\t });\n\t };\n\t AsyncMirror.prototype.utimesSync = function utimesSync (p, atime, mtime) {\n\t this.checkInitialized();\n\t this._sync.utimesSync(p, atime, mtime);\n\t this.enqueueOp({\n\t apiMethod: 'utimes',\n\t arguments: [p, atime, mtime]\n\t });\n\t };\n\t AsyncMirror.prototype.checkInitialized = function checkInitialized () {\n\t if (!this._isInitialized) {\n\t throw new ApiError(ErrorCode.EPERM, \"AsyncMirrorFS is not initialized. Please initialize AsyncMirrorFS using its initialize() method before using it.\");\n\t }\n\t };\n\t AsyncMirror.prototype.enqueueOp = function enqueueOp (op) {\n\t var this$1 = this;\n\t\n\t this._queue.push(op);\n\t if (!this._queueRunning) {\n\t this._queueRunning = true;\n\t var doNextOp = function (err) {\n\t if (err) {\n\t console.error((\"WARNING: File system has desynchronized. Received following error: \" + err + \"\\n$\"));\n\t }\n\t if (this$1._queue.length > 0) {\n\t var op = this$1._queue.shift(), args = op.arguments;\n\t args.push(doNextOp);\n\t this$1._async[op.apiMethod].apply(this$1._async, args);\n\t }\n\t else {\n\t this$1._queueRunning = false;\n\t }\n\t };\n\t doNextOp();\n\t }\n\t };\n\t\n\t return AsyncMirror;\n\t}(SynchronousFileSystem));\n\t\n\tAsyncMirror.Name = \"AsyncMirror\";\n\tAsyncMirror.Options = {\n\t sync: {\n\t type: \"object\",\n\t description: \"The synchronous file system to mirror the asynchronous file system to.\"\n\t },\n\t async: {\n\t type: \"object\",\n\t description: \"The asynchronous file system to mirror.\"\n\t }\n\t};\n\t\n\t/**\n\t * A faster alternative to `Function#apply`, this function invokes `func`\n\t * with the `this` binding of `thisArg` and the arguments of `args`.\n\t *\n\t * @private\n\t * @param {Function} func The function to invoke.\n\t * @param {*} thisArg The `this` binding of `func`.\n\t * @param {Array} args The arguments to invoke `func` with.\n\t * @returns {*} Returns the result of `func`.\n\t */\n\tfunction apply(func, thisArg, args) {\n\t switch (args.length) {\n\t case 0: return func.call(thisArg);\n\t case 1: return func.call(thisArg, args[0]);\n\t case 2: return func.call(thisArg, args[0], args[1]);\n\t case 3: return func.call(thisArg, args[0], args[1], args[2]);\n\t }\n\t return func.apply(thisArg, args);\n\t}\n\t\n\t/* Built-in method references for those with the same name as other `lodash` methods. */\n\tvar nativeMax = Math.max;\n\t\n\t/**\n\t * A specialized version of `baseRest` which transforms the rest array.\n\t *\n\t * @private\n\t * @param {Function} func The function to apply a rest parameter to.\n\t * @param {number} [start=func.length-1] The start position of the rest parameter.\n\t * @param {Function} transform The rest array transform.\n\t * @returns {Function} Returns the new function.\n\t */\n\tfunction overRest$1(func, start, transform) {\n\t start = nativeMax(start === undefined ? (func.length - 1) : start, 0);\n\t return function() {\n\t var args = arguments,\n\t index = -1,\n\t length = nativeMax(args.length - start, 0),\n\t array = Array(length);\n\t\n\t while (++index < length) {\n\t array[index] = args[start + index];\n\t }\n\t index = -1;\n\t var otherArgs = Array(start + 1);\n\t while (++index < start) {\n\t otherArgs[index] = args[index];\n\t }\n\t otherArgs[start] = transform(array);\n\t return apply(func, this, otherArgs);\n\t };\n\t}\n\t\n\t/**\n\t * This method returns the first argument it receives.\n\t *\n\t * @static\n\t * @since 0.1.0\n\t * @memberOf _\n\t * @category Util\n\t * @param {*} value Any value.\n\t * @returns {*} Returns `value`.\n\t * @example\n\t *\n\t * var object = { 'a': 1 };\n\t *\n\t * console.log(_.identity(object) === object);\n\t * // => true\n\t */\n\tfunction identity(value) {\n\t return value;\n\t}\n\t\n\t// Lodash rest function without function.toString()\n\t// remappings\n\tfunction rest(func, start) {\n\t return overRest$1(func, start, identity);\n\t}\n\t\n\tvar initialParams = function (fn) {\n\t return rest(function (args/*..., callback*/) {\n\t var callback = args.pop();\n\t fn.call(this, args, callback);\n\t });\n\t};\n\t\n\tfunction applyEach$1(eachfn) {\n\t return rest(function(fns, args) {\n\t var go = initialParams(function(args, callback) {\n\t var that = this;\n\t return eachfn(fns, function (fn, cb) {\n\t fn.apply(that, args.concat(cb));\n\t }, callback);\n\t });\n\t if (args.length) {\n\t return go.apply(this, args);\n\t }\n\t else {\n\t return go;\n\t }\n\t });\n\t}\n\t\n\t/** Detect free variable `global` from Node.js. */\n\tvar freeGlobal = typeof global == 'object' && global && global.Object === Object && global;\n\t\n\t/** Detect free variable `self`. */\n\tvar freeSelf = typeof self == 'object' && self && self.Object === Object && self;\n\t\n\t/** Used as a reference to the global object. */\n\tvar root = freeGlobal || freeSelf || Function('return this')();\n\t\n\t/** Built-in value references. */\n\tvar Symbol$1 = root.Symbol;\n\t\n\t/** Used for built-in method references. */\n\tvar objectProto = Object.prototype;\n\t\n\t/** Used to check objects for own properties. */\n\tvar hasOwnProperty = objectProto.hasOwnProperty;\n\t\n\t/**\n\t * Used to resolve the\n\t * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n\t * of values.\n\t */\n\tvar nativeObjectToString = objectProto.toString;\n\t\n\t/** Built-in value references. */\n\tvar symToStringTag$1 = Symbol$1 ? Symbol$1.toStringTag : undefined;\n\t\n\t/**\n\t * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.\n\t *\n\t * @private\n\t * @param {*} value The value to query.\n\t * @returns {string} Returns the raw `toStringTag`.\n\t */\n\tfunction getRawTag(value) {\n\t var isOwn = hasOwnProperty.call(value, symToStringTag$1),\n\t tag = value[symToStringTag$1];\n\t\n\t try {\n\t value[symToStringTag$1] = undefined;\n\t var unmasked = true;\n\t } catch (e) {}\n\t\n\t var result = nativeObjectToString.call(value);\n\t if (unmasked) {\n\t if (isOwn) {\n\t value[symToStringTag$1] = tag;\n\t } else {\n\t delete value[symToStringTag$1];\n\t }\n\t }\n\t return result;\n\t}\n\t\n\t/** Used for built-in method references. */\n\tvar objectProto$1 = Object.prototype;\n\t\n\t/**\n\t * Used to resolve the\n\t * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n\t * of values.\n\t */\n\tvar nativeObjectToString$1 = objectProto$1.toString;\n\t\n\t/**\n\t * Converts `value` to a string using `Object.prototype.toString`.\n\t *\n\t * @private\n\t * @param {*} value The value to convert.\n\t * @returns {string} Returns the converted string.\n\t */\n\tfunction objectToString(value) {\n\t return nativeObjectToString$1.call(value);\n\t}\n\t\n\t/** `Object#toString` result references. */\n\tvar nullTag = '[object Null]';\n\tvar undefinedTag = '[object Undefined]';\n\t\n\t/** Built-in value references. */\n\tvar symToStringTag = Symbol$1 ? Symbol$1.toStringTag : undefined;\n\t\n\t/**\n\t * The base implementation of `getTag` without fallbacks for buggy environments.\n\t *\n\t * @private\n\t * @param {*} value The value to query.\n\t * @returns {string} Returns the `toStringTag`.\n\t */\n\tfunction baseGetTag(value) {\n\t if (value == null) {\n\t return value === undefined ? undefinedTag : nullTag;\n\t }\n\t return (symToStringTag && symToStringTag in Object(value))\n\t ? getRawTag(value)\n\t : objectToString(value);\n\t}\n\t\n\t/**\n\t * Checks if `value` is the\n\t * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)\n\t * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)\n\t *\n\t * @static\n\t * @memberOf _\n\t * @since 0.1.0\n\t * @category Lang\n\t * @param {*} value The value to check.\n\t * @returns {boolean} Returns `true` if `value` is an object, else `false`.\n\t * @example\n\t *\n\t * _.isObject({});\n\t * // => true\n\t *\n\t * _.isObject([1, 2, 3]);\n\t * // => true\n\t *\n\t * _.isObject(_.noop);\n\t * // => true\n\t *\n\t * _.isObject(null);\n\t * // => false\n\t */\n\tfunction isObject(value) {\n\t var type = typeof value;\n\t return value != null && (type == 'object' || type == 'function');\n\t}\n\t\n\t/** `Object#toString` result references. */\n\tvar asyncTag = '[object AsyncFunction]';\n\tvar funcTag = '[object Function]';\n\tvar genTag = '[object GeneratorFunction]';\n\tvar proxyTag = '[object Proxy]';\n\t\n\t/**\n\t * Checks if `value` is classified as a `Function` object.\n\t *\n\t * @static\n\t * @memberOf _\n\t * @since 0.1.0\n\t * @category Lang\n\t * @param {*} value The value to check.\n\t * @returns {boolean} Returns `true` if `value` is a function, else `false`.\n\t * @example\n\t *\n\t * _.isFunction(_);\n\t * // => true\n\t *\n\t * _.isFunction(/abc/);\n\t * // => false\n\t */\n\tfunction isFunction(value) {\n\t if (!isObject(value)) {\n\t return false;\n\t }\n\t // The use of `Object#toString` avoids issues with the `typeof` operator\n\t // in Safari 9 which returns 'object' for typed arrays and other constructors.\n\t var tag = baseGetTag(value);\n\t return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;\n\t}\n\t\n\t/** Used as references for various `Number` constants. */\n\tvar MAX_SAFE_INTEGER = 9007199254740991;\n\t\n\t/**\n\t * Checks if `value` is a valid array-like length.\n\t *\n\t * **Note:** This method is loosely based on\n\t * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).\n\t *\n\t * @static\n\t * @memberOf _\n\t * @since 4.0.0\n\t * @category Lang\n\t * @param {*} value The value to check.\n\t * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.\n\t * @example\n\t *\n\t * _.isLength(3);\n\t * // => true\n\t *\n\t * _.isLength(Number.MIN_VALUE);\n\t * // => false\n\t *\n\t * _.isLength(Infinity);\n\t * // => false\n\t *\n\t * _.isLength('3');\n\t * // => false\n\t */\n\tfunction isLength(value) {\n\t return typeof value == 'number' &&\n\t value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;\n\t}\n\t\n\t/**\n\t * Checks if `value` is array-like. A value is considered array-like if it's\n\t * not a function and has a `value.length` that's an integer greater than or\n\t * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.\n\t *\n\t * @static\n\t * @memberOf _\n\t * @since 4.0.0\n\t * @category Lang\n\t * @param {*} value The value to check.\n\t * @returns {boolean} Returns `true` if `value` is array-like, else `false`.\n\t * @example\n\t *\n\t * _.isArrayLike([1, 2, 3]);\n\t * // => true\n\t *\n\t * _.isArrayLike(document.body.children);\n\t * // => true\n\t *\n\t * _.isArrayLike('abc');\n\t * // => true\n\t *\n\t * _.isArrayLike(_.noop);\n\t * // => false\n\t */\n\tfunction isArrayLike(value) {\n\t return value != null && isLength(value.length) && !isFunction(value);\n\t}\n\t\n\t// A temporary value used to identify if the loop should be broken.\n\t// See #1064, #1293\n\tvar breakLoop = {};\n\t\n\t/**\n\t * This method returns `undefined`.\n\t *\n\t * @static\n\t * @memberOf _\n\t * @since 2.3.0\n\t * @category Util\n\t * @example\n\t *\n\t * _.times(2, _.noop);\n\t * // => [undefined, undefined]\n\t */\n\tfunction noop() {\n\t // No operation performed.\n\t}\n\t\n\tfunction once(fn) {\n\t return function () {\n\t if (fn === null) { return; }\n\t var callFn = fn;\n\t fn = null;\n\t callFn.apply(this, arguments);\n\t };\n\t}\n\t\n\tvar iteratorSymbol = typeof Symbol === 'function' && Symbol.iterator;\n\t\n\tvar getIterator = function (coll) {\n\t return iteratorSymbol && coll[iteratorSymbol] && coll[iteratorSymbol]();\n\t};\n\t\n\t/**\n\t * The base implementation of `_.times` without support for iteratee shorthands\n\t * or max array length checks.\n\t *\n\t * @private\n\t * @param {number} n The number of times to invoke `iteratee`.\n\t * @param {Function} iteratee The function invoked per iteration.\n\t * @returns {Array} Returns the array of results.\n\t */\n\tfunction baseTimes(n, iteratee) {\n\t var index = -1,\n\t result = Array(n);\n\t\n\t while (++index < n) {\n\t result[index] = iteratee(index);\n\t }\n\t return result;\n\t}\n\t\n\t/**\n\t * Checks if `value` is object-like. A value is object-like if it's not `null`\n\t * and has a `typeof` result of \"object\".\n\t *\n\t * @static\n\t * @memberOf _\n\t * @since 4.0.0\n\t * @category Lang\n\t * @param {*} value The value to check.\n\t * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n\t * @example\n\t *\n\t * _.isObjectLike({});\n\t * // => true\n\t *\n\t * _.isObjectLike([1, 2, 3]);\n\t * // => true\n\t *\n\t * _.isObjectLike(_.noop);\n\t * // => false\n\t *\n\t * _.isObjectLike(null);\n\t * // => false\n\t */\n\tfunction isObjectLike(value) {\n\t return value != null && typeof value == 'object';\n\t}\n\t\n\t/** `Object#toString` result references. */\n\tvar argsTag = '[object Arguments]';\n\t\n\t/**\n\t * The base implementation of `_.isArguments`.\n\t *\n\t * @private\n\t * @param {*} value The value to check.\n\t * @returns {boolean} Returns `true` if `value` is an `arguments` object,\n\t */\n\tfunction baseIsArguments(value) {\n\t return isObjectLike(value) && baseGetTag(value) == argsTag;\n\t}\n\t\n\t/** Used for built-in method references. */\n\tvar objectProto$3 = Object.prototype;\n\t\n\t/** Used to check objects for own properties. */\n\tvar hasOwnProperty$2 = objectProto$3.hasOwnProperty;\n\t\n\t/** Built-in value references. */\n\tvar propertyIsEnumerable = objectProto$3.propertyIsEnumerable;\n\t\n\t/**\n\t * Checks if `value` is likely an `arguments` object.\n\t *\n\t * @static\n\t * @memberOf _\n\t * @since 0.1.0\n\t * @category Lang\n\t * @param {*} value The value to check.\n\t * @returns {boolean} Returns `true` if `value` is an `arguments` object,\n\t * else `false`.\n\t * @example\n\t *\n\t * _.isArguments(function() { return arguments; }());\n\t * // => true\n\t *\n\t * _.isArguments([1, 2, 3]);\n\t * // => false\n\t */\n\tvar isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {\n\t return isObjectLike(value) && hasOwnProperty$2.call(value, 'callee') &&\n\t !propertyIsEnumerable.call(value, 'callee');\n\t};\n\t\n\t/**\n\t * Checks if `value` is classified as an `Array` object.\n\t *\n\t * @static\n\t * @memberOf _\n\t * @since 0.1.0\n\t * @category Lang\n\t * @param {*} value The value to check.\n\t * @returns {boolean} Returns `true` if `value` is an array, else `false`.\n\t * @example\n\t *\n\t * _.isArray([1, 2, 3]);\n\t * // => true\n\t *\n\t * _.isArray(document.body.children);\n\t * // => false\n\t *\n\t * _.isArray('abc');\n\t * // => false\n\t *\n\t * _.isArray(_.noop);\n\t * // => false\n\t */\n\tvar isArray = Array.isArray;\n\t\n\t/**\n\t * This method returns `false`.\n\t *\n\t * @static\n\t * @memberOf _\n\t * @since 4.13.0\n\t * @category Util\n\t * @returns {boolean} Returns `false`.\n\t * @example\n\t *\n\t * _.times(2, _.stubFalse);\n\t * // => [false, false]\n\t */\n\tfunction stubFalse() {\n\t return false;\n\t}\n\t\n\t/** Detect free variable `exports`. */\n\tvar freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;\n\t\n\t/** Detect free variable `module`. */\n\tvar freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;\n\t\n\t/** Detect the popular CommonJS extension `module.exports`. */\n\tvar moduleExports = freeModule && freeModule.exports === freeExports;\n\t\n\t/** Built-in value references. */\n\tvar Buffer$1 = moduleExports ? root.Buffer : undefined;\n\t\n\t/* Built-in method references for those with the same name as other `lodash` methods. */\n\tvar nativeIsBuffer = Buffer$1 ? Buffer$1.isBuffer : undefined;\n\t\n\t/**\n\t * Checks if `value` is a buffer.\n\t *\n\t * @static\n\t * @memberOf _\n\t * @since 4.3.0\n\t * @category Lang\n\t * @param {*} value The value to check.\n\t * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.\n\t * @example\n\t *\n\t * _.isBuffer(new Buffer(2));\n\t * // => true\n\t *\n\t * _.isBuffer(new Uint8Array(2));\n\t * // => false\n\t */\n\tvar isBuffer = nativeIsBuffer || stubFalse;\n\t\n\t/** Used as references for various `Number` constants. */\n\tvar MAX_SAFE_INTEGER$1 = 9007199254740991;\n\t\n\t/** Used to detect unsigned integer values. */\n\tvar reIsUint = /^(?:0|[1-9]\\d*)$/;\n\t\n\t/**\n\t * Checks if `value` is a valid array-like index.\n\t *\n\t * @private\n\t * @param {*} value The value to check.\n\t * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.\n\t * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.\n\t */\n\tfunction isIndex(value, length) {\n\t length = length == null ? MAX_SAFE_INTEGER$1 : length;\n\t return !!length &&\n\t (typeof value == 'number' || reIsUint.test(value)) &&\n\t (value > -1 && value % 1 == 0 && value < length);\n\t}\n\t\n\t/** `Object#toString` result references. */\n\tvar argsTag$1 = '[object Arguments]';\n\tvar arrayTag = '[object Array]';\n\tvar boolTag = '[object Boolean]';\n\tvar dateTag = '[object Date]';\n\tvar errorTag = '[object Error]';\n\tvar funcTag$1 = '[object Function]';\n\tvar mapTag = '[object Map]';\n\tvar numberTag = '[object Number]';\n\tvar objectTag = '[object Object]';\n\tvar regexpTag = '[object RegExp]';\n\tvar setTag = '[object Set]';\n\tvar stringTag = '[object String]';\n\tvar weakMapTag = '[object WeakMap]';\n\t\n\tvar arrayBufferTag = '[object ArrayBuffer]';\n\tvar dataViewTag = '[object DataView]';\n\tvar float32Tag = '[object Float32Array]';\n\tvar float64Tag = '[object Float64Array]';\n\tvar int8Tag = '[object Int8Array]';\n\tvar int16Tag = '[object Int16Array]';\n\tvar int32Tag = '[object Int32Array]';\n\tvar uint8Tag = '[object Uint8Array]';\n\tvar uint8ClampedTag = '[object Uint8ClampedArray]';\n\tvar uint16Tag = '[object Uint16Array]';\n\tvar uint32Tag = '[object Uint32Array]';\n\t\n\t/** Used to identify `toStringTag` values of typed arrays. */\n\tvar typedArrayTags = {};\n\ttypedArrayTags[float32Tag] = typedArrayTags[float64Tag] =\n\ttypedArrayTags[int8Tag] = typedArrayTags[int16Tag] =\n\ttypedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =\n\ttypedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =\n\ttypedArrayTags[uint32Tag] = true;\n\ttypedArrayTags[argsTag$1] = typedArrayTags[arrayTag] =\n\ttypedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =\n\ttypedArrayTags[dataViewTag] = typedArrayTags[dateTag] =\n\ttypedArrayTags[errorTag] = typedArrayTags[funcTag$1] =\n\ttypedArrayTags[mapTag] = typedArrayTags[numberTag] =\n\ttypedArrayTags[objectTag] = typedArrayTags[regexpTag] =\n\ttypedArrayTags[setTag] = typedArrayTags[stringTag] =\n\ttypedArrayTags[weakMapTag] = false;\n\t\n\t/**\n\t * The base implementation of `_.isTypedArray` without Node.js optimizations.\n\t *\n\t * @private\n\t * @param {*} value The value to check.\n\t * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.\n\t */\n\tfunction baseIsTypedArray(value) {\n\t return isObjectLike(value) &&\n\t isLength(value.length) && !!typedArrayTags[baseGetTag(value)];\n\t}\n\t\n\t/**\n\t * The base implementation of `_.unary` without support for storing metadata.\n\t *\n\t * @private\n\t * @param {Function} func The function to cap arguments for.\n\t * @returns {Function} Returns the new capped function.\n\t */\n\tfunction baseUnary(func) {\n\t return function(value) {\n\t return func(value);\n\t };\n\t}\n\t\n\t/** Detect free variable `exports`. */\n\tvar freeExports$1 = typeof exports == 'object' && exports && !exports.nodeType && exports;\n\t\n\t/** Detect free variable `module`. */\n\tvar freeModule$1 = freeExports$1 && typeof module == 'object' && module && !module.nodeType && module;\n\t\n\t/** Detect the popular CommonJS extension `module.exports`. */\n\tvar moduleExports$1 = freeModule$1 && freeModule$1.exports === freeExports$1;\n\t\n\t/** Detect free variable `process` from Node.js. */\n\tvar freeProcess = moduleExports$1 && freeGlobal.process;\n\t\n\t/** Used to access faster Node.js helpers. */\n\tvar nodeUtil = (function() {\n\t try {\n\t return freeProcess && freeProcess.binding && freeProcess.binding('util');\n\t } catch (e) {}\n\t}());\n\t\n\t/* Node.js helper references. */\n\tvar nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;\n\t\n\t/**\n\t * Checks if `value` is classified as a typed array.\n\t *\n\t * @static\n\t * @memberOf _\n\t * @since 3.0.0\n\t * @category Lang\n\t * @param {*} value The value to check.\n\t * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.\n\t * @example\n\t *\n\t * _.isTypedArray(new Uint8Array);\n\t * // => true\n\t *\n\t * _.isTypedArray([]);\n\t * // => false\n\t */\n\tvar isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;\n\t\n\t/** Used for built-in method references. */\n\tvar objectProto$2 = Object.prototype;\n\t\n\t/** Used to check objects for own properties. */\n\tvar hasOwnProperty$1 = objectProto$2.hasOwnProperty;\n\t\n\t/**\n\t * Creates an array of the enumerable property names of the array-like `value`.\n\t *\n\t * @private\n\t * @param {*} value The value to query.\n\t * @param {boolean} inherited Specify returning inherited property names.\n\t * @returns {Array} Returns the array of property names.\n\t */\n\tfunction arrayLikeKeys(value, inherited) {\n\t var isArr = isArray(value),\n\t isArg = !isArr && isArguments(value),\n\t isBuff = !isArr && !isArg && isBuffer(value),\n\t isType = !isArr && !isArg && !isBuff && isTypedArray(value),\n\t skipIndexes = isArr || isArg || isBuff || isType,\n\t result = skipIndexes ? baseTimes(value.length, String) : [],\n\t length = result.length;\n\t\n\t for (var key in value) {\n\t if ((inherited || hasOwnProperty$1.call(value, key)) &&\n\t !(skipIndexes && (\n\t // Safari 9 has enumerable `arguments.length` in strict mode.\n\t key == 'length' ||\n\t // Node.js 0.10 has enumerable non-index properties on buffers.\n\t (isBuff && (key == 'offset' || key == 'parent')) ||\n\t // PhantomJS 2 has enumerable non-index properties on typed arrays.\n\t (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||\n\t // Skip index properties.\n\t isIndex(key, length)\n\t ))) {\n\t result.push(key);\n\t }\n\t }\n\t return result;\n\t}\n\t\n\t/** Used for built-in method references. */\n\tvar objectProto$5 = Object.prototype;\n\t\n\t/**\n\t * Checks if `value` is likely a prototype object.\n\t *\n\t * @private\n\t * @param {*} value The value to check.\n\t * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.\n\t */\n\tfunction isPrototype(value) {\n\t var Ctor = value && value.constructor,\n\t proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto$5;\n\t\n\t return value === proto;\n\t}\n\t\n\t/**\n\t * Creates a unary function that invokes `func` with its argument transformed.\n\t *\n\t * @private\n\t * @param {Function} func The function to wrap.\n\t * @param {Function} transform The argument transform.\n\t * @returns {Function} Returns the new function.\n\t */\n\tfunction overArg(func, transform) {\n\t return function(arg) {\n\t return func(transform(arg));\n\t };\n\t}\n\t\n\t/* Built-in method references for those with the same name as other `lodash` methods. */\n\tvar nativeKeys = overArg(Object.keys, Object);\n\t\n\t/** Used for built-in method references. */\n\tvar objectProto$4 = Object.prototype;\n\t\n\t/** Used to check objects for own properties. */\n\tvar hasOwnProperty$3 = objectProto$4.hasOwnProperty;\n\t\n\t/**\n\t * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.\n\t *\n\t * @private\n\t * @param {Object} object The object to query.\n\t * @returns {Array} Returns the array of property names.\n\t */\n\tfunction baseKeys(object) {\n\t if (!isPrototype(object)) {\n\t return nativeKeys(object);\n\t }\n\t var result = [];\n\t for (var key in Object(object)) {\n\t if (hasOwnProperty$3.call(object, key) && key != 'constructor') {\n\t result.push(key);\n\t }\n\t }\n\t return result;\n\t}\n\t\n\t/**\n\t * Creates an array of the own enumerable property names of `object`.\n\t *\n\t * **Note:** Non-object values are coerced to objects. See the\n\t * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)\n\t * for more details.\n\t *\n\t * @static\n\t * @since 0.1.0\n\t * @memberOf _\n\t * @category Object\n\t * @param {Object} object The object to query.\n\t * @returns {Array} Returns the array of property names.\n\t * @example\n\t *\n\t * function Foo() {\n\t * this.a = 1;\n\t * this.b = 2;\n\t * }\n\t *\n\t * Foo.prototype.c = 3;\n\t *\n\t * _.keys(new Foo);\n\t * // => ['a', 'b'] (iteration order is not guaranteed)\n\t *\n\t * _.keys('hi');\n\t * // => ['0', '1']\n\t */\n\tfunction keys(object) {\n\t return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);\n\t}\n\t\n\tfunction createArrayIterator(coll) {\n\t var i = -1;\n\t var len = coll.length;\n\t return function next() {\n\t return ++i < len ? {value: coll[i], key: i} : null;\n\t }\n\t}\n\t\n\tfunction createES2015Iterator(iterator) {\n\t var i = -1;\n\t return function next() {\n\t var item = iterator.next();\n\t if (item.done)\n\t { return null; }\n\t i++;\n\t return {value: item.value, key: i};\n\t }\n\t}\n\t\n\tfunction createObjectIterator(obj) {\n\t var okeys = keys(obj);\n\t var i = -1;\n\t var len = okeys.length;\n\t return function next() {\n\t var key = okeys[++i];\n\t return i < len ? {value: obj[key], key: key} : null;\n\t };\n\t}\n\t\n\tfunction iterator(coll) {\n\t if (isArrayLike(coll)) {\n\t return createArrayIterator(coll);\n\t }\n\t\n\t var iterator = getIterator(coll);\n\t return iterator ? createES2015Iterator(iterator) : createObjectIterator(coll);\n\t}\n\t\n\tfunction onlyOnce(fn) {\n\t return function() {\n\t if (fn === null) { throw new Error(\"Callback was already called.\"); }\n\t var callFn = fn;\n\t fn = null;\n\t callFn.apply(this, arguments);\n\t };\n\t}\n\t\n\tfunction _eachOfLimit(limit) {\n\t return function (obj, iteratee, callback) {\n\t callback = once(callback || noop);\n\t if (limit <= 0 || !obj) {\n\t return callback(null);\n\t }\n\t var nextElem = iterator(obj);\n\t var done = false;\n\t var running = 0;\n\t\n\t function iterateeCallback(err, value) {\n\t running -= 1;\n\t if (err) {\n\t done = true;\n\t callback(err);\n\t }\n\t else if (value === breakLoop || (done && running <= 0)) {\n\t done = true;\n\t return callback(null);\n\t }\n\t else {\n\t replenish();\n\t }\n\t }\n\t\n\t function replenish () {\n\t while (running < limit && !done) {\n\t var elem = nextElem();\n\t if (elem === null) {\n\t done = true;\n\t if (running <= 0) {\n\t callback(null);\n\t }\n\t return;\n\t }\n\t running += 1;\n\t iteratee(elem.value, elem.key, onlyOnce(iterateeCallback));\n\t }\n\t }\n\t\n\t replenish();\n\t };\n\t}\n\t\n\t/**\n\t * The same as [`eachOf`]{@link module:Collections.eachOf} but runs a maximum of `limit` async operations at a\n\t * time.\n\t *\n\t * @name eachOfLimit\n\t * @static\n\t * @memberOf module:Collections\n\t * @method\n\t * @see [async.eachOf]{@link module:Collections.eachOf}\n\t * @alias forEachOfLimit\n\t * @category Collection\n\t * @param {Array|Iterable|Object} coll - A collection to iterate over.\n\t * @param {number} limit - The maximum number of async operations at a time.\n\t * @param {Function} iteratee - A function to apply to each\n\t * item in `coll`. The `key` is the item's key, or index in the case of an\n\t * array. The iteratee is passed a `callback(err)` which must be called once it\n\t * has completed. If no error has occurred, the callback should be run without\n\t * arguments or with an explicit `null` argument. Invoked with\n\t * (item, key, callback).\n\t * @param {Function} [callback] - A callback which is called when all\n\t * `iteratee` functions have finished, or an error occurs. Invoked with (err).\n\t */\n\tfunction eachOfLimit(coll, limit, iteratee, callback) {\n\t _eachOfLimit(limit)(coll, iteratee, callback);\n\t}\n\t\n\tfunction doLimit(fn, limit) {\n\t return function (iterable, iteratee, callback) {\n\t return fn(iterable, limit, iteratee, callback);\n\t };\n\t}\n\t\n\t// eachOf implementation optimized for array-likes\n\tfunction eachOfArrayLike(coll, iteratee, callback) {\n\t callback = once(callback || noop);\n\t var index = 0,\n\t completed = 0,\n\t length = coll.length;\n\t if (length === 0) {\n\t callback(null);\n\t }\n\t\n\t function iteratorCallback(err, value) {\n\t if (err) {\n\t callback(err);\n\t } else if ((++completed === length) || value === breakLoop) {\n\t callback(null);\n\t }\n\t }\n\t\n\t for (; index < length; index++) {\n\t iteratee(coll[index], index, onlyOnce(iteratorCallback));\n\t }\n\t}\n\t\n\t// a generic version of eachOf which can handle array, object, and iterator cases.\n\tvar eachOfGeneric = doLimit(eachOfLimit, Infinity);\n\t\n\t/**\n\t * Like [`each`]{@link module:Collections.each}, except that it passes the key (or index) as the second argument\n\t * to the iteratee.\n\t *\n\t * @name eachOf\n\t * @static\n\t * @memberOf module:Collections\n\t * @method\n\t * @alias forEachOf\n\t * @category Collection\n\t * @see [async.each]{@link module:Collections.each}\n\t * @param {Array|Iterable|Object} coll - A collection to iterate over.\n\t * @param {Function} iteratee - A function to apply to each\n\t * item in `coll`. The `key` is the item's key, or index in the case of an\n\t * array. The iteratee is passed a `callback(err)` which must be called once it\n\t * has completed. If no error has occurred, the callback should be run without\n\t * arguments or with an explicit `null` argument. Invoked with\n\t * (item, key, callback).\n\t * @param {Function} [callback] - A callback which is called when all\n\t * `iteratee` functions have finished, or an error occurs. Invoked with (err).\n\t * @example\n\t *\n\t * var obj = {dev: \"/dev.json\", test: \"/test.json\", prod: \"/prod.json\"};\n\t * var configs = {};\n\t *\n\t * async.forEachOf(obj, function (value, key, callback) {\n\t * fs.readFile(__dirname + value, \"utf8\", function (err, data) {\n\t * if (err) return callback(err);\n\t * try {\n\t * configs[key] = JSON.parse(data);\n\t * } catch (e) {\n\t * return callback(e);\n\t * }\n\t * callback();\n\t * });\n\t * }, function (err) {\n\t * if (err) console.error(err.message);\n\t * // configs is now a map of JSON data\n\t * doSomethingWith(configs);\n\t * });\n\t */\n\tvar eachOf = function(coll, iteratee, callback) {\n\t var eachOfImplementation = isArrayLike(coll) ? eachOfArrayLike : eachOfGeneric;\n\t eachOfImplementation(coll, iteratee, callback);\n\t};\n\t\n\tfunction doParallel(fn) {\n\t return function (obj, iteratee, callback) {\n\t return fn(eachOf, obj, iteratee, callback);\n\t };\n\t}\n\t\n\tfunction _asyncMap(eachfn, arr, iteratee, callback) {\n\t callback = callback || noop;\n\t arr = arr || [];\n\t var results = [];\n\t var counter = 0;\n\t\n\t eachfn(arr, function (value, _, callback) {\n\t var index = counter++;\n\t iteratee(value, function (err, v) {\n\t results[index] = v;\n\t callback(err);\n\t });\n\t }, function (err) {\n\t callback(err, results);\n\t });\n\t}\n\t\n\t/**\n\t * Produces a new collection of values by mapping each value in `coll` through\n\t * the `iteratee` function. The `iteratee` is called with an item from `coll`\n\t * and a callback for when it has finished processing. Each of these callback\n\t * takes 2 arguments: an `error`, and the transformed item from `coll`. If\n\t * `iteratee` passes an error to its callback, the main `callback` (for the\n\t * `map` function) is immediately called with the error.\n\t *\n\t * Note, that since this function applies the `iteratee` to each item in\n\t * parallel, there is no guarantee that the `iteratee` functions will complete\n\t * in order. However, the results array will be in the same order as the\n\t * original `coll`.\n\t *\n\t * If `map` is passed an Object, the results will be an Array. The results\n\t * will roughly be in the order of the original Objects' keys (but this can\n\t * vary across JavaScript engines)\n\t *\n\t * @name map\n\t * @static\n\t * @memberOf module:Collections\n\t * @method\n\t * @category Collection\n\t * @param {Array|Iterable|Object} coll - A collection to iterate over.\n\t * @param {Function} iteratee - A function to apply to each item in `coll`.\n\t * The iteratee is passed a `callback(err, transformed)` which must be called\n\t * once it has completed with an error (which can be `null`) and a\n\t * transformed item. Invoked with (item, callback).\n\t * @param {Function} [callback] - A callback which is called when all `iteratee`\n\t * functions have finished, or an error occurs. Results is an Array of the\n\t * transformed items from the `coll`. Invoked with (err, results).\n\t * @example\n\t *\n\t * async.map(['file1','file2','file3'], fs.stat, function(err, results) {\n\t * // results is now an array of stats for each file\n\t * });\n\t */\n\tvar map = doParallel(_asyncMap);\n\t\n\t/**\n\t * Applies the provided arguments to each function in the array, calling\n\t * `callback` after all functions have completed. If you only provide the first\n\t * argument, `fns`, then it will return a function which lets you pass in the\n\t * arguments as if it were a single function call. If more arguments are\n\t * provided, `callback` is required while `args` is still optional.\n\t *\n\t * @name applyEach\n\t * @static\n\t * @memberOf module:ControlFlow\n\t * @method\n\t * @category Control Flow\n\t * @param {Array|Iterable|Object} fns - A collection of asynchronous functions\n\t * to all call with the same arguments\n\t * @param {...*} [args] - any number of separate arguments to pass to the\n\t * function.\n\t * @param {Function} [callback] - the final argument should be the callback,\n\t * called when all functions have completed processing.\n\t * @returns {Function} - If only the first argument, `fns`, is provided, it will\n\t * return a function which lets you pass in the arguments as if it were a single\n\t * function call. The signature is `(..args, callback)`. If invoked with any\n\t * arguments, `callback` is required.\n\t * @example\n\t *\n\t * async.applyEach([enableSearch, updateSchema], 'bucket', callback);\n\t *\n\t * // partial application example:\n\t * async.each(\n\t * buckets,\n\t * async.applyEach([enableSearch, updateSchema]),\n\t * callback\n\t * );\n\t */\n\tapplyEach$1(map);\n\t\n\tfunction doParallelLimit(fn) {\n\t return function (obj, limit, iteratee, callback) {\n\t return fn(_eachOfLimit(limit), obj, iteratee, callback);\n\t };\n\t}\n\t\n\t/**\n\t * The same as [`map`]{@link module:Collections.map} but runs a maximum of `limit` async operations at a time.\n\t *\n\t * @name mapLimit\n\t * @static\n\t * @memberOf module:Collections\n\t * @method\n\t * @see [async.map]{@link module:Collections.map}\n\t * @category Collection\n\t * @param {Array|Iterable|Object} coll - A collection to iterate over.\n\t * @param {number} limit - The maximum number of async operations at a time.\n\t * @param {Function} iteratee - A function to apply to each item in `coll`.\n\t * The iteratee is passed a `callback(err, transformed)` which must be called\n\t * once it has completed with an error (which can be `null`) and a transformed\n\t * item. Invoked with (item, callback).\n\t * @param {Function} [callback] - A callback which is called when all `iteratee`\n\t * functions have finished, or an error occurs. Results is an array of the\n\t * transformed items from the `coll`. Invoked with (err, results).\n\t */\n\tvar mapLimit = doParallelLimit(_asyncMap);\n\t\n\t/**\n\t * The same as [`map`]{@link module:Collections.map} but runs only a single async operation at a time.\n\t *\n\t * @name mapSeries\n\t * @static\n\t * @memberOf module:Collections\n\t * @method\n\t * @see [async.map]{@link module:Collections.map}\n\t * @category Collection\n\t * @param {Array|Iterable|Object} coll - A collection to iterate over.\n\t * @param {Function} iteratee - A function to apply to each item in `coll`.\n\t * The iteratee is passed a `callback(err, transformed)` which must be called\n\t * once it has completed with an error (which can be `null`) and a\n\t * transformed item. Invoked with (item, callback).\n\t * @param {Function} [callback] - A callback which is called when all `iteratee`\n\t * functions have finished, or an error occurs. Results is an array of the\n\t * transformed items from the `coll`. Invoked with (err, results).\n\t */\n\tvar mapSeries = doLimit(mapLimit, 1);\n\t\n\t/**\n\t * The same as [`applyEach`]{@link module:ControlFlow.applyEach} but runs only a single async operation at a time.\n\t *\n\t * @name applyEachSeries\n\t * @static\n\t * @memberOf module:ControlFlow\n\t * @method\n\t * @see [async.applyEach]{@link module:ControlFlow.applyEach}\n\t * @category Control Flow\n\t * @param {Array|Iterable|Object} fns - A collection of asynchronous functions to all\n\t * call with the same arguments\n\t * @param {...*} [args] - any number of separate arguments to pass to the\n\t * function.\n\t * @param {Function} [callback] - the final argument should be the callback,\n\t * called when all functions have completed processing.\n\t * @returns {Function} - If only the first argument is provided, it will return\n\t * a function which lets you pass in the arguments as if it were a single\n\t * function call.\n\t */\n\tapplyEach$1(mapSeries);\n\t\n\t/**\n\t * Creates a continuation function with some arguments already applied.\n\t *\n\t * Useful as a shorthand when combined with other control flow functions. Any\n\t * arguments passed to the returned function are added to the arguments\n\t * originally passed to apply.\n\t *\n\t * @name apply\n\t * @static\n\t * @memberOf module:Utils\n\t * @method\n\t * @category Util\n\t * @param {Function} function - The function you want to eventually apply all\n\t * arguments to. Invokes with (arguments...).\n\t * @param {...*} arguments... - Any number of arguments to automatically apply\n\t * when the continuation is called.\n\t * @example\n\t *\n\t * // using apply\n\t * async.parallel([\n\t * async.apply(fs.writeFile, 'testfile1', 'test1'),\n\t * async.apply(fs.writeFile, 'testfile2', 'test2')\n\t * ]);\n\t *\n\t *\n\t * // the same process without using apply\n\t * async.parallel([\n\t * function(callback) {\n\t * fs.writeFile('testfile1', 'test1', callback);\n\t * },\n\t * function(callback) {\n\t * fs.writeFile('testfile2', 'test2', callback);\n\t * }\n\t * ]);\n\t *\n\t * // It's possible to pass any number of additional arguments when calling the\n\t * // continuation:\n\t *\n\t * node> var fn = async.apply(sys.puts, 'one');\n\t * node> fn('two', 'three');\n\t * one\n\t * two\n\t * three\n\t */\n\trest(function(fn, args) {\n\t return rest(function(callArgs) {\n\t return fn.apply(null, args.concat(callArgs));\n\t });\n\t});\n\t\n\t/**\n\t * A specialized version of `_.forEach` for arrays without support for\n\t * iteratee shorthands.\n\t *\n\t * @private\n\t * @param {Array} [array] The array to iterate over.\n\t * @param {Function} iteratee The function invoked per iteration.\n\t * @returns {Array} Returns `array`.\n\t */\n\tfunction arrayEach(array, iteratee) {\n\t var index = -1,\n\t length = array == null ? 0 : array.length;\n\t\n\t while (++index < length) {\n\t if (iteratee(array[index], index, array) === false) {\n\t break;\n\t }\n\t }\n\t return array;\n\t}\n\t\n\t/**\n\t * Creates a base function for methods like `_.forIn` and `_.forOwn`.\n\t *\n\t * @private\n\t * @param {boolean} [fromRight] Specify iterating from right to left.\n\t * @returns {Function} Returns the new base function.\n\t */\n\tfunction createBaseFor(fromRight) {\n\t return function(object, iteratee, keysFunc) {\n\t var index = -1,\n\t iterable = Object(object),\n\t props = keysFunc(object),\n\t length = props.length;\n\t\n\t while (length--) {\n\t var key = props[fromRight ? length : ++index];\n\t if (iteratee(iterable[key], key, iterable) === false) {\n\t break;\n\t }\n\t }\n\t return object;\n\t };\n\t}\n\t\n\t/**\n\t * The base implementation of `baseForOwn` which iterates over `object`\n\t * properties returned by `keysFunc` and invokes `iteratee` for each property.\n\t * Iteratee functions may exit iteration early by explicitly returning `false`.\n\t *\n\t * @private\n\t * @param {Object} object The object to iterate over.\n\t * @param {Function} iteratee The function invoked per iteration.\n\t * @param {Function} keysFunc The function to get the keys of `object`.\n\t * @returns {Object} Returns `object`.\n\t */\n\tvar baseFor = createBaseFor();\n\t\n\t/**\n\t * The base implementation of `_.forOwn` without support for iteratee shorthands.\n\t *\n\t * @private\n\t * @param {Object} object The object to iterate over.\n\t * @param {Function} iteratee The function invoked per iteration.\n\t * @returns {Object} Returns `object`.\n\t */\n\tfunction baseForOwn(object, iteratee) {\n\t return object && baseFor(object, iteratee, keys);\n\t}\n\t\n\t/**\n\t * The base implementation of `_.findIndex` and `_.findLastIndex` without\n\t * support for iteratee shorthands.\n\t *\n\t * @private\n\t * @param {Array} array The array to inspect.\n\t * @param {Function} predicate The function invoked per iteration.\n\t * @param {number} fromIndex The index to search from.\n\t * @param {boolean} [fromRight] Specify iterating from right to left.\n\t * @returns {number} Returns the index of the matched value, else `-1`.\n\t */\n\tfunction baseFindIndex(array, predicate, fromIndex, fromRight) {\n\t var length = array.length,\n\t index = fromIndex + (fromRight ? 1 : -1);\n\t\n\t while ((fromRight ? index-- : ++index < length)) {\n\t if (predicate(array[index], index, array)) {\n\t return index;\n\t }\n\t }\n\t return -1;\n\t}\n\t\n\t/**\n\t * The base implementation of `_.isNaN` without support for number objects.\n\t *\n\t * @private\n\t * @param {*} value The value to check.\n\t * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.\n\t */\n\tfunction baseIsNaN(value) {\n\t return value !== value;\n\t}\n\t\n\t/**\n\t * A specialized version of `_.indexOf` which performs strict equality\n\t * comparisons of values, i.e. `===`.\n\t *\n\t * @private\n\t * @param {Array} array The array to inspect.\n\t * @param {*} value The value to search for.\n\t * @param {number} fromIndex The index to search from.\n\t * @returns {number} Returns the index of the matched value, else `-1`.\n\t */\n\tfunction strictIndexOf(array, value, fromIndex) {\n\t var index = fromIndex - 1,\n\t length = array.length;\n\t\n\t while (++index < length) {\n\t if (array[index] === value) {\n\t return index;\n\t }\n\t }\n\t return -1;\n\t}\n\t\n\t/**\n\t * The base implementation of `_.indexOf` without `fromIndex` bounds checks.\n\t *\n\t * @private\n\t * @param {Array} array The array to inspect.\n\t * @param {*} value The value to search for.\n\t * @param {number} fromIndex The index to search from.\n\t * @returns {number} Returns the index of the matched value, else `-1`.\n\t */\n\tfunction baseIndexOf(array, value, fromIndex) {\n\t return value === value\n\t ? strictIndexOf(array, value, fromIndex)\n\t : baseFindIndex(array, baseIsNaN, fromIndex);\n\t}\n\t\n\t/**\n\t * Determines the best order for running the functions in `tasks`, based on\n\t * their requirements. Each function can optionally depend on other functions\n\t * being completed first, and each function is run as soon as its requirements\n\t * are satisfied.\n\t *\n\t * If any of the functions pass an error to their callback, the `auto` sequence\n\t * will stop. Further tasks will not execute (so any other functions depending\n\t * on it will not run), and the main `callback` is immediately called with the\n\t * error.\n\t *\n\t * Functions also receive an object containing the results of functions which\n\t * have completed so far as the first argument, if they have dependencies. If a\n\t * task function has no dependencies, it will only be passed a callback.\n\t *\n\t * @name auto\n\t * @static\n\t * @memberOf module:ControlFlow\n\t * @method\n\t * @category Control Flow\n\t * @param {Object} tasks - An object. Each of its properties is either a\n\t * function or an array of requirements, with the function itself the last item\n\t * in the array. The object's key of a property serves as the name of the task\n\t * defined by that property, i.e. can be used when specifying requirements for\n\t * other tasks. The function receives one or two arguments:\n\t * * a `results` object, containing the results of the previously executed\n\t * functions, only passed if the task has any dependencies,\n\t * * a `callback(err, result)` function, which must be called when finished,\n\t * passing an `error` (which can be `null`) and the result of the function's\n\t * execution.\n\t * @param {number} [concurrency=Infinity] - An optional `integer` for\n\t * determining the maximum number of tasks that can be run in parallel. By\n\t * default, as many as possible.\n\t * @param {Function} [callback] - An optional callback which is called when all\n\t * the tasks have been completed. It receives the `err` argument if any `tasks`\n\t * pass an error to their callback. Results are always returned; however, if an\n\t * error occurs, no further `tasks` will be performed, and the results object\n\t * will only contain partial results. Invoked with (err, results).\n\t * @returns undefined\n\t * @example\n\t *\n\t * async.auto({\n\t * // this function will just be passed a callback\n\t * readData: async.apply(fs.readFile, 'data.txt', 'utf-8'),\n\t * showData: ['readData', function(results, cb) {\n\t * // results.readData is the file's contents\n\t * // ...\n\t * }]\n\t * }, callback);\n\t *\n\t * async.auto({\n\t * get_data: function(callback) {\n\t * console.log('in get_data');\n\t * // async code to get some data\n\t * callback(null, 'data', 'converted to array');\n\t * },\n\t * make_folder: function(callback) {\n\t * console.log('in make_folder');\n\t * // async code to create a directory to store a file in\n\t * // this is run at the same time as getting the data\n\t * callback(null, 'folder');\n\t * },\n\t * write_file: ['get_data', 'make_folder', function(results, callback) {\n\t * console.log('in write_file', JSON.stringify(results));\n\t * // once there is some data and the directory exists,\n\t * // write the data to a file in the directory\n\t * callback(null, 'filename');\n\t * }],\n\t * email_link: ['write_file', function(results, callback) {\n\t * console.log('in email_link', JSON.stringify(results));\n\t * // once the file is written let's email a link to it...\n\t * // results.write_file contains the filename returned by write_file.\n\t * callback(null, {'file':results.write_file, 'email':'user@example.com'});\n\t * }]\n\t * }, function(err, results) {\n\t * console.log('err = ', err);\n\t * console.log('results = ', results);\n\t * });\n\t */\n\t\n\t/**\n\t * A specialized version of `_.map` for arrays without support for iteratee\n\t * shorthands.\n\t *\n\t * @private\n\t * @param {Array} [array] The array to iterate over.\n\t * @param {Function} iteratee The function invoked per iteration.\n\t * @returns {Array} Returns the new mapped array.\n\t */\n\t\n\t/**\n\t * The base implementation of `_.slice` without an iteratee call guard.\n\t *\n\t * @private\n\t * @param {Array} array The array to slice.\n\t * @param {number} [start=0] The start position.\n\t * @param {number} [end=array.length] The end position.\n\t * @returns {Array} Returns the slice of `array`.\n\t */\n\t\n\t/**\n\t * Converts an ASCII `string` to an array.\n\t *\n\t * @private\n\t * @param {string} string The string to convert.\n\t * @returns {Array} Returns the converted array.\n\t */\n\t\n\t/** Used to compose unicode character classes. */\n\t\n\t/** Used to compose unicode character classes. */\n\tvar rsAstralRange$1 = '\\\\ud800-\\\\udfff';\n\tvar rsComboMarksRange$1 = '\\\\u0300-\\\\u036f';\n\tvar reComboHalfMarksRange$1 = '\\\\ufe20-\\\\ufe2f';\n\tvar rsComboSymbolsRange$1 = '\\\\u20d0-\\\\u20ff';\n\tvar rsComboRange$1 = rsComboMarksRange$1 + reComboHalfMarksRange$1 + rsComboSymbolsRange$1;\n\tvar rsVarRange$1 = '\\\\ufe0e\\\\ufe0f';\n\t\n\t/** Used to compose unicode capture groups. */\n\tvar rsAstral = '[' + rsAstralRange$1 + ']';\n\tvar rsCombo = '[' + rsComboRange$1 + ']';\n\tvar rsFitz = '\\\\ud83c[\\\\udffb-\\\\udfff]';\n\tvar rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')';\n\tvar rsNonAstral = '[^' + rsAstralRange$1 + ']';\n\tvar rsRegional = '(?:\\\\ud83c[\\\\udde6-\\\\uddff]){2}';\n\tvar rsSurrPair = '[\\\\ud800-\\\\udbff][\\\\udc00-\\\\udfff]';\n\tvar rsZWJ$1 = '\\\\u200d';\n\t\n\t/** Used to compose unicode regexes. */\n\tvar reOptMod = rsModifier + '?';\n\tvar rsOptVar = '[' + rsVarRange$1 + ']?';\n\tvar rsOptJoin = '(?:' + rsZWJ$1 + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*';\n\tvar rsSeq = rsOptVar + reOptMod + rsOptJoin;\n\tvar rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';\n\t\n\tvar hasSetImmediate = typeof setImmediate === 'function' && setImmediate;\n\tvar hasNextTick = typeof process === 'object' && typeof process.nextTick === 'function';\n\t\n\tfunction fallback(fn) {\n\t setTimeout(fn, 0);\n\t}\n\t\n\tfunction wrap(defer) {\n\t return rest(function (fn, args) {\n\t defer(function () {\n\t fn.apply(null, args);\n\t });\n\t });\n\t}\n\t\n\tvar _defer;\n\t\n\tif (hasSetImmediate) {\n\t _defer = setImmediate;\n\t} else if (hasNextTick) {\n\t _defer = process.nextTick;\n\t} else {\n\t _defer = fallback;\n\t}\n\t\n\twrap(_defer);\n\t\n\t// Simple doubly linked list (https://en.wikipedia.org/wiki/Doubly_linked_list) implementation\n\t// used for queues. This implementation assumes that the node provided by the user can be modified\n\t// to adjust the next and last properties. We implement only the minimal functionality\n\t// for queue support.\n\t\n\t/**\n\t * The same as [`eachOf`]{@link module:Collections.eachOf} but runs only a single async operation at a time.\n\t *\n\t * @name eachOfSeries\n\t * @static\n\t * @memberOf module:Collections\n\t * @method\n\t * @see [async.eachOf]{@link module:Collections.eachOf}\n\t * @alias forEachOfSeries\n\t * @category Collection\n\t * @param {Array|Iterable|Object} coll - A collection to iterate over.\n\t * @param {Function} iteratee - A function to apply to each item in `coll`. The\n\t * `key` is the item's key, or index in the case of an array. The iteratee is\n\t * passed a `callback(err)` which must be called once it has completed. If no\n\t * error has occurred, the callback should be run without arguments or with an\n\t * explicit `null` argument. Invoked with (item, key, callback).\n\t * @param {Function} [callback] - A callback which is called when all `iteratee`\n\t * functions have finished, or an error occurs. Invoked with (err).\n\t */\n\tvar eachOfSeries = doLimit(eachOfLimit, 1);\n\t\n\t/**\n\t * Reduces `coll` into a single value using an async `iteratee` to return each\n\t * successive step. `memo` is the initial state of the reduction. This function\n\t * only operates in series.\n\t *\n\t * For performance reasons, it may make sense to split a call to this function\n\t * into a parallel map, and then use the normal `Array.prototype.reduce` on the\n\t * results. This function is for situations where each step in the reduction\n\t * needs to be async; if you can get the data before reducing it, then it's\n\t * probably a good idea to do so.\n\t *\n\t * @name reduce\n\t * @static\n\t * @memberOf module:Collections\n\t * @method\n\t * @alias inject\n\t * @alias foldl\n\t * @category Collection\n\t * @param {Array|Iterable|Object} coll - A collection to iterate over.\n\t * @param {*} memo - The initial state of the reduction.\n\t * @param {Function} iteratee - A function applied to each item in the\n\t * array to produce the next step in the reduction. The `iteratee` is passed a\n\t * `callback(err, reduction)` which accepts an optional error as its first\n\t * argument, and the state of the reduction as the second. If an error is\n\t * passed to the callback, the reduction is stopped and the main `callback` is\n\t * immediately called with the error. Invoked with (memo, item, callback).\n\t * @param {Function} [callback] - A callback which is called after all the\n\t * `iteratee` functions have finished. Result is the reduced value. Invoked with\n\t * (err, result).\n\t * @example\n\t *\n\t * async.reduce([1,2,3], 0, function(memo, item, callback) {\n\t * // pointless async:\n\t * process.nextTick(function() {\n\t * callback(null, memo + item)\n\t * });\n\t * }, function(err, result) {\n\t * // result is now equal to the last value of memo, which is 6\n\t * });\n\t */\n\tfunction reduce(coll, memo, iteratee, callback) {\n\t callback = once(callback || noop);\n\t eachOfSeries(coll, function(x, i, callback) {\n\t iteratee(memo, x, function(err, v) {\n\t memo = v;\n\t callback(err);\n\t });\n\t }, function(err) {\n\t callback(err, memo);\n\t });\n\t}\n\t\n\t/**\n\t * Version of the compose function that is more natural to read. Each function\n\t * consumes the return value of the previous function. It is the equivalent of\n\t * [compose]{@link module:ControlFlow.compose} with the arguments reversed.\n\t *\n\t * Each function is executed with the `this` binding of the composed function.\n\t *\n\t * @name seq\n\t * @static\n\t * @memberOf module:ControlFlow\n\t * @method\n\t * @see [async.compose]{@link module:ControlFlow.compose}\n\t * @category Control Flow\n\t * @param {...Function} functions - the asynchronous functions to compose\n\t * @returns {Function} a function that composes the `functions` in order\n\t * @example\n\t *\n\t * // Requires lodash (or underscore), express3 and dresende's orm2.\n\t * // Part of an app, that fetches cats of the logged user.\n\t * // This example uses `seq` function to avoid overnesting and error\n\t * // handling clutter.\n\t * app.get('/cats', function(request, response) {\n\t * var User = request.models.User;\n\t * async.seq(\n\t * _.bind(User.get, User), // 'User.get' has signature (id, callback(err, data))\n\t * function(user, fn) {\n\t * user.getCats(fn); // 'getCats' has signature (callback(err, data))\n\t * }\n\t * )(req.session.user_id, function (err, cats) {\n\t * if (err) {\n\t * console.error(err);\n\t * response.json({ status: 'error', message: err.message });\n\t * } else {\n\t * response.json({ status: 'ok', message: 'Cats found', data: cats });\n\t * }\n\t * });\n\t * });\n\t */\n\tvar seq = rest(function seq(functions) {\n\t return rest(function(args) {\n\t var that = this;\n\t\n\t var cb = args[args.length - 1];\n\t if (typeof cb == 'function') {\n\t args.pop();\n\t } else {\n\t cb = noop;\n\t }\n\t\n\t reduce(functions, args, function(newargs, fn, cb) {\n\t fn.apply(that, newargs.concat(rest(function(err, nextargs) {\n\t cb(err, nextargs);\n\t })));\n\t },\n\t function(err, results) {\n\t cb.apply(that, [err].concat(results));\n\t });\n\t });\n\t});\n\t\n\t/**\n\t * Creates a function which is a composition of the passed asynchronous\n\t * functions. Each function consumes the return value of the function that\n\t * follows. Composing functions `f()`, `g()`, and `h()` would produce the result\n\t * of `f(g(h()))`, only this version uses callbacks to obtain the return values.\n\t *\n\t * Each function is executed with the `this` binding of the composed function.\n\t *\n\t * @name compose\n\t * @static\n\t * @memberOf module:ControlFlow\n\t * @method\n\t * @category Control Flow\n\t * @param {...Function} functions - the asynchronous functions to compose\n\t * @returns {Function} an asynchronous function that is the composed\n\t * asynchronous `functions`\n\t * @example\n\t *\n\t * function add1(n, callback) {\n\t * setTimeout(function () {\n\t * callback(null, n + 1);\n\t * }, 10);\n\t * }\n\t *\n\t * function mul3(n, callback) {\n\t * setTimeout(function () {\n\t * callback(null, n * 3);\n\t * }, 10);\n\t * }\n\t *\n\t * var add1mul3 = async.compose(mul3, add1);\n\t * add1mul3(4, function (err, result) {\n\t * // result now equals 15\n\t * });\n\t */\n\trest(function(args) {\n\t return seq.apply(null, args.reverse());\n\t});\n\t\n\t/**\n\t * Applies `iteratee` to each item in `coll`, concatenating the results. Returns\n\t * the concatenated list. The `iteratee`s are called in parallel, and the\n\t * results are concatenated as they return. There is no guarantee that the\n\t * results array will be returned in the original order of `coll` passed to the\n\t * `iteratee` function.\n\t *\n\t * @name concat\n\t * @static\n\t * @memberOf module:Collections\n\t * @method\n\t * @category Collection\n\t * @param {Array|Iterable|Object} coll - A collection to iterate over.\n\t * @param {Function} iteratee - A function to apply to each item in `coll`.\n\t * The iteratee is passed a `callback(err, results)` which must be called once\n\t * it has completed with an error (which can be `null`) and an array of results.\n\t * Invoked with (item, callback).\n\t * @param {Function} [callback(err)] - A callback which is called after all the\n\t * `iteratee` functions have finished, or an error occurs. Results is an array\n\t * containing the concatenated results of the `iteratee` function. Invoked with\n\t * (err, results).\n\t * @example\n\t *\n\t * async.concat(['dir1','dir2','dir3'], fs.readdir, function(err, files) {\n\t * // files is now a list of filenames that exist in the 3 directories\n\t * });\n\t */\n\t\n\t/**\n\t * The same as [`concat`]{@link module:Collections.concat} but runs only a single async operation at a time.\n\t *\n\t * @name concatSeries\n\t * @static\n\t * @memberOf module:Collections\n\t * @method\n\t * @see [async.concat]{@link module:Collections.concat}\n\t * @category Collection\n\t * @param {Array|Iterable|Object} coll - A collection to iterate over.\n\t * @param {Function} iteratee - A function to apply to each item in `coll`.\n\t * The iteratee is passed a `callback(err, results)` which must be called once\n\t * it has completed with an error (which can be `null`) and an array of results.\n\t * Invoked with (item, callback).\n\t * @param {Function} [callback(err)] - A callback which is called after all the\n\t * `iteratee` functions have finished, or an error occurs. Results is an array\n\t * containing the concatenated results of the `iteratee` function. Invoked with\n\t * (err, results).\n\t */\n\t\n\t/**\n\t * Returns a function that when called, calls-back with the values provided.\n\t * Useful as the first function in a [`waterfall`]{@link module:ControlFlow.waterfall}, or for plugging values in to\n\t * [`auto`]{@link module:ControlFlow.auto}.\n\t *\n\t * @name constant\n\t * @static\n\t * @memberOf module:Utils\n\t * @method\n\t * @category Util\n\t * @param {...*} arguments... - Any number of arguments to automatically invoke\n\t * callback with.\n\t * @returns {Function} Returns a function that when invoked, automatically\n\t * invokes the callback with the previous given arguments.\n\t * @example\n\t *\n\t * async.waterfall([\n\t * async.constant(42),\n\t * function (value, next) {\n\t * // value === 42\n\t * },\n\t * //...\n\t * ], callback);\n\t *\n\t * async.waterfall([\n\t * async.constant(filename, \"utf8\"),\n\t * fs.readFile,\n\t * function (fileData, next) {\n\t * //...\n\t * }\n\t * //...\n\t * ], callback);\n\t *\n\t * async.auto({\n\t * hostname: async.constant(\"https://server.net/\"),\n\t * port: findFreePort,\n\t * launchServer: [\"hostname\", \"port\", function (options, cb) {\n\t * startServer(options, cb);\n\t * }],\n\t * //...\n\t * }, callback);\n\t */\n\trest(function(values) {\n\t var args = [null].concat(values);\n\t return initialParams(function (ignoredArgs, callback) {\n\t return callback.apply(this, args);\n\t });\n\t});\n\t\n\t/**\n\t * Returns the first value in `coll` that passes an async truth test. The\n\t * `iteratee` is applied in parallel, meaning the first iteratee to return\n\t * `true` will fire the detect `callback` with that result. That means the\n\t * result might not be the first item in the original `coll` (in terms of order)\n\t * that passes the test.\n\t\n\t * If order within the original `coll` is important, then look at\n\t * [`detectSeries`]{@link module:Collections.detectSeries}.\n\t *\n\t * @name detect\n\t * @static\n\t * @memberOf module:Collections\n\t * @method\n\t * @alias find\n\t * @category Collections\n\t * @param {Array|Iterable|Object} coll - A collection to iterate over.\n\t * @param {Function} iteratee - A truth test to apply to each item in `coll`.\n\t * The iteratee is passed a `callback(err, truthValue)` which must be called\n\t * with a boolean argument once it has completed. Invoked with (item, callback).\n\t * @param {Function} [callback] - A callback which is called as soon as any\n\t * iteratee returns `true`, or after all the `iteratee` functions have finished.\n\t * Result will be the first item in the array that passes the truth test\n\t * (iteratee) or the value `undefined` if none passed. Invoked with\n\t * (err, result).\n\t * @example\n\t *\n\t * async.detect(['file1','file2','file3'], function(filePath, callback) {\n\t * fs.access(filePath, function(err) {\n\t * callback(null, !err)\n\t * });\n\t * }, function(err, result) {\n\t * // result now equals the first file in the list that exists\n\t * });\n\t */\n\t\n\t/**\n\t * The same as [`detect`]{@link module:Collections.detect} but runs a maximum of `limit` async operations at a\n\t * time.\n\t *\n\t * @name detectLimit\n\t * @static\n\t * @memberOf module:Collections\n\t * @method\n\t * @see [async.detect]{@link module:Collections.detect}\n\t * @alias findLimit\n\t * @category Collections\n\t * @param {Array|Iterable|Object} coll - A collection to iterate over.\n\t * @param {number} limit - The maximum number of async operations at a time.\n\t * @param {Function} iteratee - A truth test to apply to each item in `coll`.\n\t * The iteratee is passed a `callback(err, truthValue)` which must be called\n\t * with a boolean argument once it has completed. Invoked with (item, callback).\n\t * @param {Function} [callback] - A callback which is called as soon as any\n\t * iteratee returns `true`, or after all the `iteratee` functions have finished.\n\t * Result will be the first item in the array that passes the truth test\n\t * (iteratee) or the value `undefined` if none passed. Invoked with\n\t * (err, result).\n\t */\n\t\n\t/**\n\t * The same as [`detect`]{@link module:Collections.detect} but runs only a single async operation at a time.\n\t *\n\t * @name detectSeries\n\t * @static\n\t * @memberOf module:Collections\n\t * @method\n\t * @see [async.detect]{@link module:Collections.detect}\n\t * @alias findSeries\n\t * @category Collections\n\t * @param {Array|Iterable|Object} coll - A collection to iterate over.\n\t * @param {Function} iteratee - A truth test to apply to each item in `coll`.\n\t * The iteratee is passed a `callback(err, truthValue)` which must be called\n\t * with a boolean argument once it has completed. Invoked with (item, callback).\n\t * @param {Function} [callback] - A callback which is called as soon as any\n\t * iteratee returns `true`, or after all the `iteratee` functions have finished.\n\t * Result will be the first item in the array that passes the truth test\n\t * (iteratee) or the value `undefined` if none passed. Invoked with\n\t * (err, result).\n\t */\n\t\n\tfunction consoleFunc(name) {\n\t return rest(function (fn, args) {\n\t fn.apply(null, args.concat(rest(function (err, args) {\n\t if (typeof console === 'object') {\n\t if (err) {\n\t if (console.error) {\n\t console.error(err);\n\t }\n\t }\n\t else if (console[name]) {\n\t arrayEach(args, function (x) {\n\t console[name](x);\n\t });\n\t }\n\t }\n\t })));\n\t });\n\t}\n\t\n\t/**\n\t * Logs the result of an `async` function to the `console` using `console.dir`\n\t * to display the properties of the resulting object. Only works in Node.js or\n\t * in browsers that support `console.dir` and `console.error` (such as FF and\n\t * Chrome). If multiple arguments are returned from the async function,\n\t * `console.dir` is called on each argument in order.\n\t *\n\t * @name dir\n\t * @static\n\t * @memberOf module:Utils\n\t * @method\n\t * @category Util\n\t * @param {Function} function - The function you want to eventually apply all\n\t * arguments to.\n\t * @param {...*} arguments... - Any number of arguments to apply to the function.\n\t * @example\n\t *\n\t * // in a module\n\t * var hello = function(name, callback) {\n\t * setTimeout(function() {\n\t * callback(null, {hello: name});\n\t * }, 1000);\n\t * };\n\t *\n\t * // in the node repl\n\t * node> async.dir(hello, 'world');\n\t * {hello: 'world'}\n\t */\n\tconsoleFunc('dir');\n\t\n\tfunction _withoutIndex(iteratee) {\n\t return function (value, index, callback) {\n\t return iteratee(value, callback);\n\t };\n\t}\n\t\n\t/**\n\t * Applies the function `iteratee` to each item in `coll`, in parallel.\n\t * The `iteratee` is called with an item from the list, and a callback for when\n\t * it has finished. If the `iteratee` passes an error to its `callback`, the\n\t * main `callback` (for the `each` function) is immediately called with the\n\t * error.\n\t *\n\t * Note, that since this function applies `iteratee` to each item in parallel,\n\t * there is no guarantee that the iteratee functions will complete in order.\n\t *\n\t * @name each\n\t * @static\n\t * @memberOf module:Collections\n\t * @method\n\t * @alias forEach\n\t * @category Collection\n\t * @param {Array|Iterable|Object} coll - A collection to iterate over.\n\t * @param {Function} iteratee - A function to apply to each item\n\t * in `coll`. The iteratee is passed a `callback(err)` which must be called once\n\t * it has completed. If no error has occurred, the `callback` should be run\n\t * without arguments or with an explicit `null` argument. The array index is not\n\t * passed to the iteratee. Invoked with (item, callback). If you need the index,\n\t * use `eachOf`.\n\t * @param {Function} [callback] - A callback which is called when all\n\t * `iteratee` functions have finished, or an error occurs. Invoked with (err).\n\t * @example\n\t *\n\t * // assuming openFiles is an array of file names and saveFile is a function\n\t * // to save the modified contents of that file:\n\t *\n\t * async.each(openFiles, saveFile, function(err){\n\t * // if any of the saves produced an error, err would equal that error\n\t * });\n\t *\n\t * // assuming openFiles is an array of file names\n\t * async.each(openFiles, function(file, callback) {\n\t *\n\t * // Perform operation on file here.\n\t * console.log('Processing file ' + file);\n\t *\n\t * if( file.length > 32 ) {\n\t * console.log('This file name is too long');\n\t * callback('File name too long');\n\t * } else {\n\t * // Do work to process file here\n\t * console.log('File processed');\n\t * callback();\n\t * }\n\t * }, function(err) {\n\t * // if any of the file processing produced an error, err would equal that error\n\t * if( err ) {\n\t * // One of the iterations produced an error.\n\t * // All processing will now stop.\n\t * console.log('A file failed to process');\n\t * } else {\n\t * console.log('All files have been processed successfully');\n\t * }\n\t * });\n\t */\n\tfunction eachLimit(coll, iteratee, callback) {\n\t eachOf(coll, _withoutIndex(iteratee), callback);\n\t}\n\t\n\t/**\n\t * The same as [`each`]{@link module:Collections.each} but runs only a single async operation at a time.\n\t *\n\t * @name eachSeries\n\t * @static\n\t * @memberOf module:Collections\n\t * @method\n\t * @see [async.each]{@link module:Collections.each}\n\t * @alias forEachSeries\n\t * @category Collection\n\t * @param {Array|Iterable|Object} coll - A collection to iterate over.\n\t * @param {Function} iteratee - A function to apply to each\n\t * item in `coll`. The iteratee is passed a `callback(err)` which must be called\n\t * once it has completed. If no error has occurred, the `callback` should be run\n\t * without arguments or with an explicit `null` argument. The array index is\n\t * not passed to the iteratee. Invoked with (item, callback). If you need the\n\t * index, use `eachOfSeries`.\n\t * @param {Function} [callback] - A callback which is called when all\n\t * `iteratee` functions have finished, or an error occurs. Invoked with (err).\n\t */\n\t\n\t/**\n\t * Returns `true` if every element in `coll` satisfies an async test. If any\n\t * iteratee call returns `false`, the main `callback` is immediately called.\n\t *\n\t * @name every\n\t * @static\n\t * @memberOf module:Collections\n\t * @method\n\t * @alias all\n\t * @category Collection\n\t * @param {Array|Iterable|Object} coll - A collection to iterate over.\n\t * @param {Function} iteratee - A truth test to apply to each item in the\n\t * collection in parallel. The iteratee is passed a `callback(err, truthValue)`\n\t * which must be called with a boolean argument once it has completed. Invoked\n\t * with (item, callback).\n\t * @param {Function} [callback] - A callback which is called after all the\n\t * `iteratee` functions have finished. Result will be either `true` or `false`\n\t * depending on the values of the async tests. Invoked with (err, result).\n\t * @example\n\t *\n\t * async.every(['file1','file2','file3'], function(filePath, callback) {\n\t * fs.access(filePath, function(err) {\n\t * callback(null, !err)\n\t * });\n\t * }, function(err, result) {\n\t * // if result is true then every file exists\n\t * });\n\t */\n\t\n\t/**\n\t * The same as [`every`]{@link module:Collections.every} but runs a maximum of `limit` async operations at a time.\n\t *\n\t * @name everyLimit\n\t * @static\n\t * @memberOf module:Collections\n\t * @method\n\t * @see [async.every]{@link module:Collections.every}\n\t * @alias allLimit\n\t * @category Collection\n\t * @param {Array|Iterable|Object} coll - A collection to iterate over.\n\t * @param {number} limit - The maximum number of async operations at a time.\n\t * @param {Function} iteratee - A truth test to apply to each item in the\n\t * collection in parallel. The iteratee is passed a `callback(err, truthValue)`\n\t * which must be called with a boolean argument once it has completed. Invoked\n\t * with (item, callback).\n\t * @param {Function} [callback] - A callback which is called after all the\n\t * `iteratee` functions have finished. Result will be either `true` or `false`\n\t * depending on the values of the async tests. Invoked with (err, result).\n\t */\n\t\n\t/**\n\t * The same as [`every`]{@link module:Collections.every} but runs only a single async operation at a time.\n\t *\n\t * @name everySeries\n\t * @static\n\t * @memberOf module:Collections\n\t * @method\n\t * @see [async.every]{@link module:Collections.every}\n\t * @alias allSeries\n\t * @category Collection\n\t * @param {Array|Iterable|Object} coll - A collection to iterate over.\n\t * @param {Function} iteratee - A truth test to apply to each item in the\n\t * collection in parallel. The iteratee is passed a `callback(err, truthValue)`\n\t * which must be called with a boolean argument once it has completed. Invoked\n\t * with (item, callback).\n\t * @param {Function} [callback] - A callback which is called after all the\n\t * `iteratee` functions have finished. Result will be either `true` or `false`\n\t * depending on the values of the async tests. Invoked with (err, result).\n\t */\n\t\n\t/**\n\t * The base implementation of `_.property` without support for deep paths.\n\t *\n\t * @private\n\t * @param {string} key The key of the property to get.\n\t * @returns {Function} Returns the new accessor function.\n\t */\n\t\n\t/**\n\t * Returns a new array of all the values in `coll` which pass an async truth\n\t * test. This operation is performed in parallel, but the results array will be\n\t * in the same order as the original.\n\t *\n\t * @name filter\n\t * @static\n\t * @memberOf module:Collections\n\t * @method\n\t * @alias select\n\t * @category Collection\n\t * @param {Array|Iterable|Object} coll - A collection to iterate over.\n\t * @param {Function} iteratee - A truth test to apply to each item in `coll`.\n\t * The `iteratee` is passed a `callback(err, truthValue)`, which must be called\n\t * with a boolean argument once it has completed. Invoked with (item, callback).\n\t * @param {Function} [callback] - A callback which is called after all the\n\t * `iteratee` functions have finished. Invoked with (err, results).\n\t * @example\n\t *\n\t * async.filter(['file1','file2','file3'], function(filePath, callback) {\n\t * fs.access(filePath, function(err) {\n\t * callback(null, !err)\n\t * });\n\t * }, function(err, results) {\n\t * // results now equals an array of the existing files\n\t * });\n\t */\n\t\n\t/**\n\t * The same as [`filter`]{@link module:Collections.filter} but runs a maximum of `limit` async operations at a\n\t * time.\n\t *\n\t * @name filterLimit\n\t * @static\n\t * @memberOf module:Collections\n\t * @method\n\t * @see [async.filter]{@link module:Collections.filter}\n\t * @alias selectLimit\n\t * @category Collection\n\t * @param {Array|Iterable|Object} coll - A collection to iterate over.\n\t * @param {number} limit - The maximum number of async operations at a time.\n\t * @param {Function} iteratee - A truth test to apply to each item in `coll`.\n\t * The `iteratee` is passed a `callback(err, truthValue)`, which must be called\n\t * with a boolean argument once it has completed. Invoked with (item, callback).\n\t * @param {Function} [callback] - A callback which is called after all the\n\t * `iteratee` functions have finished. Invoked with (err, results).\n\t */\n\t\n\t/**\n\t * The same as [`filter`]{@link module:Collections.filter} but runs only a single async operation at a time.\n\t *\n\t * @name filterSeries\n\t * @static\n\t * @memberOf module:Collections\n\t * @method\n\t * @see [async.filter]{@link module:Collections.filter}\n\t * @alias selectSeries\n\t * @category Collection\n\t * @param {Array|Iterable|Object} coll - A collection to iterate over.\n\t * @param {Function} iteratee - A truth test to apply to each item in `coll`.\n\t * The `iteratee` is passed a `callback(err, truthValue)`, which must be called\n\t * with a boolean argument once it has completed. Invoked with (item, callback).\n\t * @param {Function} [callback] - A callback which is called after all the\n\t * `iteratee` functions have finished. Invoked with (err, results)\n\t */\n\t\n\t/**\n\t * Logs the result of an `async` function to the `console`. Only works in\n\t * Node.js or in browsers that support `console.log` and `console.error` (such\n\t * as FF and Chrome). If multiple arguments are returned from the async\n\t * function, `console.log` is called on each argument in order.\n\t *\n\t * @name log\n\t * @static\n\t * @memberOf module:Utils\n\t * @method\n\t * @category Util\n\t * @param {Function} function - The function you want to eventually apply all\n\t * arguments to.\n\t * @param {...*} arguments... - Any number of arguments to apply to the function.\n\t * @example\n\t *\n\t * // in a module\n\t * var hello = function(name, callback) {\n\t * setTimeout(function() {\n\t * callback(null, 'hello ' + name);\n\t * }, 1000);\n\t * };\n\t *\n\t * // in the node repl\n\t * node> async.log(hello, 'world');\n\t * 'hello world'\n\t */\n\tconsoleFunc('log');\n\t\n\t/**\n\t * A relative of [`map`]{@link module:Collections.map}, designed for use with objects.\n\t *\n\t * Produces a new Object by mapping each value of `obj` through the `iteratee`\n\t * function. The `iteratee` is called each `value` and `key` from `obj` and a\n\t * callback for when it has finished processing. Each of these callbacks takes\n\t * two arguments: an `error`, and the transformed item from `obj`. If `iteratee`\n\t * passes an error to its callback, the main `callback` (for the `mapValues`\n\t * function) is immediately called with the error.\n\t *\n\t * Note, the order of the keys in the result is not guaranteed. The keys will\n\t * be roughly in the order they complete, (but this is very engine-specific)\n\t *\n\t * @name mapValues\n\t * @static\n\t * @memberOf module:Collections\n\t * @method\n\t * @category Collection\n\t * @param {Object} obj - A collection to iterate over.\n\t * @param {Function} iteratee - A function to apply to each value and key in\n\t * `coll`. The iteratee is passed a `callback(err, transformed)` which must be\n\t * called once it has completed with an error (which can be `null`) and a\n\t * transformed value. Invoked with (value, key, callback).\n\t * @param {Function} [callback] - A callback which is called when all `iteratee`\n\t * functions have finished, or an error occurs. `result` is a new object consisting\n\t * of each key from `obj`, with each transformed value on the right-hand side.\n\t * Invoked with (err, result).\n\t * @example\n\t *\n\t * async.mapValues({\n\t * f1: 'file1',\n\t * f2: 'file2',\n\t * f3: 'file3'\n\t * }, function (file, key, callback) {\n\t * fs.stat(file, callback);\n\t * }, function(err, result) {\n\t * // result is now a map of stats for each file, e.g.\n\t * // {\n\t * // f1: [stats for file1],\n\t * // f2: [stats for file2],\n\t * // f3: [stats for file3]\n\t * // }\n\t * });\n\t */\n\t\n\t/**\n\t * The same as [`mapValues`]{@link module:Collections.mapValues} but runs only a single async operation at a time.\n\t *\n\t * @name mapValuesSeries\n\t * @static\n\t * @memberOf module:Collections\n\t * @method\n\t * @see [async.mapValues]{@link module:Collections.mapValues}\n\t * @category Collection\n\t * @param {Object} obj - A collection to iterate over.\n\t * @param {Function} iteratee - A function to apply to each value in `obj`.\n\t * The iteratee is passed a `callback(err, transformed)` which must be called\n\t * once it has completed with an error (which can be `null`) and a\n\t * transformed value. Invoked with (value, key, callback).\n\t * @param {Function} [callback] - A callback which is called when all `iteratee`\n\t * functions have finished, or an error occurs. `result` is a new object consisting\n\t * of each key from `obj`, with each transformed value on the right-hand side.\n\t * Invoked with (err, result).\n\t */\n\t\n\t/**\n\t * Calls `callback` on a later loop around the event loop. In Node.js this just\n\t * calls `setImmediate`. In the browser it will use `setImmediate` if\n\t * available, otherwise `setTimeout(callback, 0)`, which means other higher\n\t * priority events may precede the execution of `callback`.\n\t *\n\t * This is used internally for browser-compatibility purposes.\n\t *\n\t * @name nextTick\n\t * @static\n\t * @memberOf module:Utils\n\t * @method\n\t * @alias setImmediate\n\t * @category Util\n\t * @param {Function} callback - The function to call on a later loop around\n\t * the event loop. Invoked with (args...).\n\t * @param {...*} args... - any number of additional arguments to pass to the\n\t * callback on the next tick.\n\t * @example\n\t *\n\t * var call_order = [];\n\t * async.nextTick(function() {\n\t * call_order.push('two');\n\t * // call_order now equals ['one','two']\n\t * });\n\t * call_order.push('one');\n\t *\n\t * async.setImmediate(function (a, b, c) {\n\t * // a, b, and c equal 1, 2, and 3\n\t * }, 1, 2, 3);\n\t */\n\tvar _defer$1;\n\t\n\tif (hasNextTick) {\n\t _defer$1 = process.nextTick;\n\t} else if (hasSetImmediate) {\n\t _defer$1 = setImmediate;\n\t} else {\n\t _defer$1 = fallback;\n\t}\n\t\n\twrap(_defer$1);\n\t\n\t/**\n\t * Calls `callback` on a later loop around the event loop. In Node.js this just\n\t * calls `setImmediate`. In the browser it will use `setImmediate` if\n\t * available, otherwise `setTimeout(callback, 0)`, which means other higher\n\t * priority events may precede the execution of `callback`.\n\t *\n\t * This is used internally for browser-compatibility purposes.\n\t *\n\t * @name setImmediate\n\t * @static\n\t * @memberOf module:Utils\n\t * @method\n\t * @alias nextTick\n\t * @category Util\n\t * @param {Function} callback - The function to call on a later loop around\n\t * the event loop. Invoked with (args...).\n\t * @param {...*} args... - any number of additional arguments to pass to the\n\t * callback on the next tick.\n\t * @example\n\t *\n\t * var call_order = [];\n\t * async.nextTick(function() {\n\t * call_order.push('two');\n\t * // call_order now equals ['one','two']\n\t * });\n\t * call_order.push('one');\n\t *\n\t * async.setImmediate(function (a, b, c) {\n\t * // a, b, and c equal 1, 2, and 3\n\t * }, 1, 2, 3);\n\t */\n\t\n\t/**\n\t * A queue of tasks for the worker function to complete.\n\t * @typedef {Object} QueueObject\n\t * @memberOf module:ControlFlow\n\t * @property {Function} length - a function returning the number of items\n\t * waiting to be processed. Invoke with `queue.length()`.\n\t * @property {boolean} started - a boolean indicating whether or not any\n\t * items have been pushed and processed by the queue.\n\t * @property {Function} running - a function returning the number of items\n\t * currently being processed. Invoke with `queue.running()`.\n\t * @property {Function} workersList - a function returning the array of items\n\t * currently being processed. Invoke with `queue.workersList()`.\n\t * @property {Function} idle - a function returning false if there are items\n\t * waiting or being processed, or true if not. Invoke with `queue.idle()`.\n\t * @property {number} concurrency - an integer for determining how many `worker`\n\t * functions should be run in parallel. This property can be changed after a\n\t * `queue` is created to alter the concurrency on-the-fly.\n\t * @property {Function} push - add a new task to the `queue`. Calls `callback`\n\t * once the `worker` has finished processing the task. Instead of a single task,\n\t * a `tasks` array can be submitted. The respective callback is used for every\n\t * task in the list. Invoke with `queue.push(task, [callback])`,\n\t * @property {Function} unshift - add a new task to the front of the `queue`.\n\t * Invoke with `queue.unshift(task, [callback])`.\n\t * @property {Function} saturated - a callback that is called when the number of\n\t * running workers hits the `concurrency` limit, and further tasks will be\n\t * queued.\n\t * @property {Function} unsaturated - a callback that is called when the number\n\t * of running workers is less than the `concurrency` & `buffer` limits, and\n\t * further tasks will not be queued.\n\t * @property {number} buffer - A minimum threshold buffer in order to say that\n\t * the `queue` is `unsaturated`.\n\t * @property {Function} empty - a callback that is called when the last item\n\t * from the `queue` is given to a `worker`.\n\t * @property {Function} drain - a callback that is called when the last item\n\t * from the `queue` has returned from the `worker`.\n\t * @property {Function} error - a callback that is called when a task errors.\n\t * Has the signature `function(error, task)`.\n\t * @property {boolean} paused - a boolean for determining whether the queue is\n\t * in a paused state.\n\t * @property {Function} pause - a function that pauses the processing of tasks\n\t * until `resume()` is called. Invoke with `queue.pause()`.\n\t * @property {Function} resume - a function that resumes the processing of\n\t * queued tasks when the queue is paused. Invoke with `queue.resume()`.\n\t * @property {Function} kill - a function that removes the `drain` callback and\n\t * empties remaining tasks from the queue forcing it to go idle. Invoke with `queue.kill()`.\n\t */\n\t\n\t/**\n\t * Creates a `queue` object with the specified `concurrency`. Tasks added to the\n\t * `queue` are processed in parallel (up to the `concurrency` limit). If all\n\t * `worker`s are in progress, the task is queued until one becomes available.\n\t * Once a `worker` completes a `task`, that `task`'s callback is called.\n\t *\n\t * @name queue\n\t * @static\n\t * @memberOf module:ControlFlow\n\t * @method\n\t * @category Control Flow\n\t * @param {Function} worker - An asynchronous function for processing a queued\n\t * task, which must call its `callback(err)` argument when finished, with an\n\t * optional `error` as an argument. If you want to handle errors from an\n\t * individual task, pass a callback to `q.push()`. Invoked with\n\t * (task, callback).\n\t * @param {number} [concurrency=1] - An `integer` for determining how many\n\t * `worker` functions should be run in parallel. If omitted, the concurrency\n\t * defaults to `1`. If the concurrency is `0`, an error is thrown.\n\t * @returns {module:ControlFlow.QueueObject} A queue object to manage the tasks. Callbacks can\n\t * attached as certain properties to listen for specific events during the\n\t * lifecycle of the queue.\n\t * @example\n\t *\n\t * // create a queue object with concurrency 2\n\t * var q = async.queue(function(task, callback) {\n\t * console.log('hello ' + task.name);\n\t * callback();\n\t * }, 2);\n\t *\n\t * // assign a callback\n\t * q.drain = function() {\n\t * console.log('all items have been processed');\n\t * };\n\t *\n\t * // add some items to the queue\n\t * q.push({name: 'foo'}, function(err) {\n\t * console.log('finished processing foo');\n\t * });\n\t * q.push({name: 'bar'}, function (err) {\n\t * console.log('finished processing bar');\n\t * });\n\t *\n\t * // add some items to the queue (batch-wise)\n\t * q.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function(err) {\n\t * console.log('finished processing item');\n\t * });\n\t *\n\t * // add some items to the front of the queue\n\t * q.unshift({name: 'bar'}, function (err) {\n\t * console.log('finished processing bar');\n\t * });\n\t */\n\t\n\t/**\n\t * The same as [async.queue]{@link module:ControlFlow.queue} only tasks are assigned a priority and\n\t * completed in ascending priority order.\n\t *\n\t * @name priorityQueue\n\t * @static\n\t * @memberOf module:ControlFlow\n\t * @method\n\t * @see [async.queue]{@link module:ControlFlow.queue}\n\t * @category Control Flow\n\t * @param {Function} worker - An asynchronous function for processing a queued\n\t * task, which must call its `callback(err)` argument when finished, with an\n\t * optional `error` as an argument. If you want to handle errors from an\n\t * individual task, pass a callback to `q.push()`. Invoked with\n\t * (task, callback).\n\t * @param {number} concurrency - An `integer` for determining how many `worker`\n\t * functions should be run in parallel. If omitted, the concurrency defaults to\n\t * `1`. If the concurrency is `0`, an error is thrown.\n\t * @returns {module:ControlFlow.QueueObject} A priorityQueue object to manage the tasks. There are two\n\t * differences between `queue` and `priorityQueue` objects:\n\t * * `push(task, priority, [callback])` - `priority` should be a number. If an\n\t * array of `tasks` is given, all tasks will be assigned the same priority.\n\t * * The `unshift` method was removed.\n\t */\n\t\n\t/**\n\t * The opposite of [`filter`]{@link module:Collections.filter}. Removes values that pass an `async` truth test.\n\t *\n\t * @name reject\n\t * @static\n\t * @memberOf module:Collections\n\t * @method\n\t * @see [async.filter]{@link module:Collections.filter}\n\t * @category Collection\n\t * @param {Array|Iterable|Object} coll - A collection to iterate over.\n\t * @param {Function} iteratee - A truth test to apply to each item in `coll`.\n\t * The `iteratee` is passed a `callback(err, truthValue)`, which must be called\n\t * with a boolean argument once it has completed. Invoked with (item, callback).\n\t * @param {Function} [callback] - A callback which is called after all the\n\t * `iteratee` functions have finished. Invoked with (err, results).\n\t * @example\n\t *\n\t * async.reject(['file1','file2','file3'], function(filePath, callback) {\n\t * fs.access(filePath, function(err) {\n\t * callback(null, !err)\n\t * });\n\t * }, function(err, results) {\n\t * // results now equals an array of missing files\n\t * createFiles(results);\n\t * });\n\t */\n\t\n\t/**\n\t * The same as [`reject`]{@link module:Collections.reject} but runs a maximum of `limit` async operations at a\n\t * time.\n\t *\n\t * @name rejectLimit\n\t * @static\n\t * @memberOf module:Collections\n\t * @method\n\t * @see [async.reject]{@link module:Collections.reject}\n\t * @category Collection\n\t * @param {Array|Iterable|Object} coll - A collection to iterate over.\n\t * @param {number} limit - The maximum number of async operations at a time.\n\t * @param {Function} iteratee - A truth test to apply to each item in `coll`.\n\t * The `iteratee` is passed a `callback(err, truthValue)`, which must be called\n\t * with a boolean argument once it has completed. Invoked with (item, callback).\n\t * @param {Function} [callback] - A callback which is called after all the\n\t * `iteratee` functions have finished. Invoked with (err, results).\n\t */\n\t\n\t/**\n\t * The same as [`reject`]{@link module:Collections.reject} but runs only a single async operation at a time.\n\t *\n\t * @name rejectSeries\n\t * @static\n\t * @memberOf module:Collections\n\t * @method\n\t * @see [async.reject]{@link module:Collections.reject}\n\t * @category Collection\n\t * @param {Array|Iterable|Object} coll - A collection to iterate over.\n\t * @param {Function} iteratee - A truth test to apply to each item in `coll`.\n\t * The `iteratee` is passed a `callback(err, truthValue)`, which must be called\n\t * with a boolean argument once it has completed. Invoked with (item, callback).\n\t * @param {Function} [callback] - A callback which is called after all the\n\t * `iteratee` functions have finished. Invoked with (err, results).\n\t */\n\t\n\t/**\n\t * Creates a function that returns `value`.\n\t *\n\t * @static\n\t * @memberOf _\n\t * @since 2.4.0\n\t * @category Util\n\t * @param {*} value The value to return from the new function.\n\t * @returns {Function} Returns the new constant function.\n\t * @example\n\t *\n\t * var objects = _.times(2, _.constant({ 'a': 1 }));\n\t *\n\t * console.log(objects);\n\t * // => [{ 'a': 1 }, { 'a': 1 }]\n\t *\n\t * console.log(objects[0] === objects[1]);\n\t * // => true\n\t */\n\t\n\t/**\n\t * A close relative of [`retry`]{@link module:ControlFlow.retry}. This method wraps a task and makes it\n\t * retryable, rather than immediately calling it with retries.\n\t *\n\t * @name retryable\n\t * @static\n\t * @memberOf module:ControlFlow\n\t * @method\n\t * @see [async.retry]{@link module:ControlFlow.retry}\n\t * @category Control Flow\n\t * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - optional\n\t * options, exactly the same as from `retry`\n\t * @param {Function} task - the asynchronous function to wrap\n\t * @returns {Functions} The wrapped function, which when invoked, will retry on\n\t * an error, based on the parameters specified in `opts`.\n\t * @example\n\t *\n\t * async.auto({\n\t * dep1: async.retryable(3, getFromFlakyService),\n\t * process: [\"dep1\", async.retryable(3, function (results, cb) {\n\t * maybeProcessData(results.dep1, cb);\n\t * })]\n\t * }, callback);\n\t */\n\t\n\t/**\n\t * Returns `true` if at least one element in the `coll` satisfies an async test.\n\t * If any iteratee call returns `true`, the main `callback` is immediately\n\t * called.\n\t *\n\t * @name some\n\t * @static\n\t * @memberOf module:Collections\n\t * @method\n\t * @alias any\n\t * @category Collection\n\t * @param {Array|Iterable|Object} coll - A collection to iterate over.\n\t * @param {Function} iteratee - A truth test to apply to each item in the array\n\t * in parallel. The iteratee is passed a `callback(err, truthValue)` which must\n\t * be called with a boolean argument once it has completed. Invoked with\n\t * (item, callback).\n\t * @param {Function} [callback] - A callback which is called as soon as any\n\t * iteratee returns `true`, or after all the iteratee functions have finished.\n\t * Result will be either `true` or `false` depending on the values of the async\n\t * tests. Invoked with (err, result).\n\t * @example\n\t *\n\t * async.some(['file1','file2','file3'], function(filePath, callback) {\n\t * fs.access(filePath, function(err) {\n\t * callback(null, !err)\n\t * });\n\t * }, function(err, result) {\n\t * // if result is true then at least one of the files exists\n\t * });\n\t */\n\t\n\t/**\n\t * The same as [`some`]{@link module:Collections.some} but runs a maximum of `limit` async operations at a time.\n\t *\n\t * @name someLimit\n\t * @static\n\t * @memberOf module:Collections\n\t * @method\n\t * @see [async.some]{@link module:Collections.some}\n\t * @alias anyLimit\n\t * @category Collection\n\t * @param {Array|Iterable|Object} coll - A collection to iterate over.\n\t * @param {number} limit - The maximum number of async operations at a time.\n\t * @param {Function} iteratee - A truth test to apply to each item in the array\n\t * in parallel. The iteratee is passed a `callback(err, truthValue)` which must\n\t * be called with a boolean argument once it has completed. Invoked with\n\t * (item, callback).\n\t * @param {Function} [callback] - A callback which is called as soon as any\n\t * iteratee returns `true`, or after all the iteratee functions have finished.\n\t * Result will be either `true` or `false` depending on the values of the async\n\t * tests. Invoked with (err, result).\n\t */\n\t\n\t/**\n\t * The same as [`some`]{@link module:Collections.some} but runs only a single async operation at a time.\n\t *\n\t * @name someSeries\n\t * @static\n\t * @memberOf module:Collections\n\t * @method\n\t * @see [async.some]{@link module:Collections.some}\n\t * @alias anySeries\n\t * @category Collection\n\t * @param {Array|Iterable|Object} coll - A collection to iterate over.\n\t * @param {Function} iteratee - A truth test to apply to each item in the array\n\t * in parallel. The iteratee is passed a `callback(err, truthValue)` which must\n\t * be called with a boolean argument once it has completed. Invoked with\n\t * (item, callback).\n\t * @param {Function} [callback] - A callback which is called as soon as any\n\t * iteratee returns `true`, or after all the iteratee functions have finished.\n\t * Result will be either `true` or `false` depending on the values of the async\n\t * tests. Invoked with (err, result).\n\t */\n\t\n\t/* Built-in method references for those with the same name as other `lodash` methods. */\n\tvar nativeCeil = Math.ceil;\n\tvar nativeMax$1 = Math.max;\n\t\n\t/**\n\t * Calls the `iteratee` function `n` times, and accumulates results in the same\n\t * manner you would use with [map]{@link module:Collections.map}.\n\t *\n\t * @name times\n\t * @static\n\t * @memberOf module:ControlFlow\n\t * @method\n\t * @see [async.map]{@link module:Collections.map}\n\t * @category Control Flow\n\t * @param {number} n - The number of times to run the function.\n\t * @param {Function} iteratee - The function to call `n` times. Invoked with the\n\t * iteration index and a callback (n, next).\n\t * @param {Function} callback - see {@link module:Collections.map}.\n\t * @example\n\t *\n\t * // Pretend this is some complicated async factory\n\t * var createUser = function(id, callback) {\n\t * callback(null, {\n\t * id: 'user' + id\n\t * });\n\t * };\n\t *\n\t * // generate 5 users\n\t * async.times(5, function(n, next) {\n\t * createUser(n, function(err, user) {\n\t * next(err, user);\n\t * });\n\t * }, function(err, users) {\n\t * // we should now have 5 users\n\t * });\n\t */\n\t\n\t/**\n\t * The same as [times]{@link module:ControlFlow.times} but runs only a single async operation at a time.\n\t *\n\t * @name timesSeries\n\t * @static\n\t * @memberOf module:ControlFlow\n\t * @method\n\t * @see [async.times]{@link module:ControlFlow.times}\n\t * @category Control Flow\n\t * @param {number} n - The number of times to run the function.\n\t * @param {Function} iteratee - The function to call `n` times. Invoked with the\n\t * iteration index and a callback (n, next).\n\t * @param {Function} callback - see {@link module:Collections.map}.\n\t */\n\t\n\t/**\n\t * Undoes a [memoize]{@link module:Utils.memoize}d function, reverting it to the original,\n\t * unmemoized form. Handy for testing.\n\t *\n\t * @name unmemoize\n\t * @static\n\t * @memberOf module:Utils\n\t * @method\n\t * @see [async.memoize]{@link module:Utils.memoize}\n\t * @category Util\n\t * @param {Function} fn - the memoized function\n\t * @returns {Function} a function that calls the original unmemoized function\n\t */\n\t\n\t/**\n\t * Runs the `tasks` array of functions in series, each passing their results to\n\t * the next in the array. However, if any of the `tasks` pass an error to their\n\t * own callback, the next function is not executed, and the main `callback` is\n\t * immediately called with the error.\n\t *\n\t * @name waterfall\n\t * @static\n\t * @memberOf module:ControlFlow\n\t * @method\n\t * @category Control Flow\n\t * @param {Array} tasks - An array of functions to run, each function is passed\n\t * a `callback(err, result1, result2, ...)` it must call on completion. The\n\t * first argument is an error (which can be `null`) and any further arguments\n\t * will be passed as arguments in order to the next task.\n\t * @param {Function} [callback] - An optional callback to run once all the\n\t * functions have completed. This will be passed the results of the last task's\n\t * callback. Invoked with (err, [results]).\n\t * @returns undefined\n\t * @example\n\t *\n\t * async.waterfall([\n\t * function(callback) {\n\t * callback(null, 'one', 'two');\n\t * },\n\t * function(arg1, arg2, callback) {\n\t * // arg1 now equals 'one' and arg2 now equals 'two'\n\t * callback(null, 'three');\n\t * },\n\t * function(arg1, callback) {\n\t * // arg1 now equals 'three'\n\t * callback(null, 'done');\n\t * }\n\t * ], function (err, result) {\n\t * // result now equals 'done'\n\t * });\n\t *\n\t * // Or, with named functions:\n\t * async.waterfall([\n\t * myFirstFunction,\n\t * mySecondFunction,\n\t * myLastFunction,\n\t * ], function (err, result) {\n\t * // result now equals 'done'\n\t * });\n\t * function myFirstFunction(callback) {\n\t * callback(null, 'one', 'two');\n\t * }\n\t * function mySecondFunction(arg1, arg2, callback) {\n\t * // arg1 now equals 'one' and arg2 now equals 'two'\n\t * callback(null, 'three');\n\t * }\n\t * function myLastFunction(arg1, callback) {\n\t * // arg1 now equals 'three'\n\t * callback(null, 'done');\n\t * }\n\t */\n\t\n\t/**\n\t * Async is a utility module which provides straight-forward, powerful functions\n\t * for working with asynchronous JavaScript. Although originally designed for\n\t * use with [Node.js](http://nodejs.org) and installable via\n\t * `npm install --save async`, it can also be used directly in the browser.\n\t * @module async\n\t */\n\t\n\t/**\n\t * A collection of `async` functions for manipulating collections, such as\n\t * arrays and objects.\n\t * @module Collections\n\t */\n\t\n\t/**\n\t * A collection of `async` functions for controlling the flow through a script.\n\t * @module ControlFlow\n\t */\n\t\n\t /**\n\t * A collection of `async` utility functions.\n\t * @module Utils\n\t */\n\t\n\t/**\n\t * @hidden\n\t */\n\tvar errorCodeLookup;\n\t/**\n\t * Lazily construct error code lookup, since DropboxJS might be loaded *after* BrowserFS (or not at all!)\n\t * @hidden\n\t */\n\tfunction constructErrorCodeLookup() {\n\t if (errorCodeLookup) {\n\t return;\n\t }\n\t errorCodeLookup = {};\n\t // This indicates a network transmission error on modern browsers. Internet Explorer might cause this code to be reported on some API server errors.\n\t errorCodeLookup[Dropbox.ApiError.NETWORK_ERROR] = ErrorCode.EIO;\n\t // 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.\n\t // errorCodeLookup[Dropbox.ApiError.NO_CONTENT];\n\t // The error property on {Dropbox.ApiError#response} should indicate which input parameter is invalid and why.\n\t errorCodeLookup[Dropbox.ApiError.INVALID_PARAM] = ErrorCode.EINVAL;\n\t // The OAuth token used for the request will never become valid again, so the user should be re-authenticated.\n\t errorCodeLookup[Dropbox.ApiError.INVALID_TOKEN] = ErrorCode.EPERM;\n\t // This indicates a bug in dropbox.js and should never occur under normal circumstances.\n\t // ^ Actually, that's false. This occurs when you try to move folders to themselves, or move a file over another file.\n\t errorCodeLookup[Dropbox.ApiError.OAUTH_ERROR] = ErrorCode.EPERM;\n\t // 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.\n\t errorCodeLookup[Dropbox.ApiError.NOT_FOUND] = ErrorCode.ENOENT;\n\t // This indicates a bug in dropbox.js and should never occur under normal circumstances.\n\t errorCodeLookup[Dropbox.ApiError.INVALID_METHOD] = ErrorCode.EINVAL;\n\t // This happens when a Dropbox.Client#readdir or Dropbox.Client#stat call would return more than a maximum amount of directory entries.\n\t errorCodeLookup[Dropbox.ApiError.NOT_ACCEPTABLE] = ErrorCode.EINVAL;\n\t // 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.\n\t errorCodeLookup[Dropbox.ApiError.CONFLICT] = ErrorCode.EINVAL;\n\t // Status value indicating that the application is making too many requests.\n\t errorCodeLookup[Dropbox.ApiError.RATE_LIMITED] = ErrorCode.EBUSY;\n\t // The request should be retried after some time.\n\t errorCodeLookup[Dropbox.ApiError.SERVER_ERROR] = ErrorCode.EBUSY;\n\t // Status value indicating that the user's Dropbox is over its storage quota.\n\t errorCodeLookup[Dropbox.ApiError.OVER_QUOTA] = ErrorCode.ENOSPC;\n\t}\n\t/**\n\t * @hidden\n\t */\n\tfunction isFileInfo(cache) {\n\t return cache && cache.stat.isFile;\n\t}\n\t/**\n\t * @hidden\n\t */\n\tfunction isDirInfo(cache) {\n\t return cache && cache.stat.isFolder;\n\t}\n\t/**\n\t * @hidden\n\t */\n\tfunction isArrayBuffer(ab) {\n\t // Accept null / undefined, too.\n\t return ab === null || ab === undefined || (typeof (ab) === 'object' && typeof (ab['byteLength']) === 'number');\n\t}\n\t/**\n\t * Wraps a Dropbox client and caches operations.\n\t * @hidden\n\t */\n\tvar CachedDropboxClient = function CachedDropboxClient(client) {\n\t this._cache = {};\n\t this._client = client;\n\t};\n\tCachedDropboxClient.prototype.readdir = function readdir (p, cb) {\n\t var this$1 = this;\n\t\n\t var cacheInfo = this.getCachedDirInfo(p);\n\t this._wrap(function (interceptCb) {\n\t if (cacheInfo !== null && cacheInfo.contents) {\n\t this$1._client.readdir(p, {\n\t contentHash: cacheInfo.stat.contentHash\n\t }, interceptCb);\n\t }\n\t else {\n\t this$1._client.readdir(p, interceptCb);\n\t }\n\t }, function (err, filenames, stat, folderEntries) {\n\t if (err) {\n\t if (err.status === Dropbox.ApiError.NO_CONTENT && cacheInfo !== null) {\n\t cb(null, cacheInfo.contents.slice(0));\n\t }\n\t else {\n\t cb(err);\n\t }\n\t }\n\t else {\n\t this$1.updateCachedDirInfo(p, stat, filenames.slice(0));\n\t folderEntries.forEach(function (entry) {\n\t this$1.updateCachedInfo(path.join(p, entry.name), entry);\n\t });\n\t cb(null, filenames);\n\t }\n\t });\n\t};\n\tCachedDropboxClient.prototype.remove = function remove (p, cb) {\n\t var this$1 = this;\n\t\n\t this._wrap(function (interceptCb) {\n\t this$1._client.remove(p, interceptCb);\n\t }, function (err, stat) {\n\t if (!err) {\n\t this$1.updateCachedInfo(p, stat);\n\t }\n\t cb(err);\n\t });\n\t};\n\tCachedDropboxClient.prototype.move = function move (src, dest, cb) {\n\t var this$1 = this;\n\t\n\t this._wrap(function (interceptCb) {\n\t this$1._client.move(src, dest, interceptCb);\n\t }, function (err, stat) {\n\t if (!err) {\n\t this$1.deleteCachedInfo(src);\n\t this$1.updateCachedInfo(dest, stat);\n\t }\n\t cb(err);\n\t });\n\t};\n\tCachedDropboxClient.prototype.stat = function stat (p, cb) {\n\t var this$1 = this;\n\t\n\t this._wrap(function (interceptCb) {\n\t this$1._client.stat(p, interceptCb);\n\t }, function (err, stat) {\n\t if (!err) {\n\t this$1.updateCachedInfo(p, stat);\n\t }\n\t cb(err, stat);\n\t });\n\t};\n\tCachedDropboxClient.prototype.readFile = function readFile (p, cb) {\n\t var this$1 = this;\n\t\n\t var cacheInfo = this.getCachedFileInfo(p);\n\t if (cacheInfo !== null && cacheInfo.contents !== null) {\n\t // Try to use cached info; issue a stat to see if contents are up-to-date.\n\t this.stat(p, function (error, stat) {\n\t if (error) {\n\t cb(error);\n\t }\n\t else if (stat.contentHash === cacheInfo.stat.contentHash) {\n\t // No file changes.\n\t cb(error, cacheInfo.contents.slice(0), cacheInfo.stat);\n\t }\n\t else {\n\t // File changes; rerun to trigger actual readFile.\n\t this$1.readFile(p, cb);\n\t }\n\t });\n\t }\n\t else {\n\t this._wrap(function (interceptCb) {\n\t this$1._client.readFile(p, { arrayBuffer: true }, interceptCb);\n\t }, function (err, contents, stat) {\n\t if (!err) {\n\t this$1.updateCachedInfo(p, stat, contents.slice(0));\n\t }\n\t cb(err, contents, stat);\n\t });\n\t }\n\t};\n\tCachedDropboxClient.prototype.writeFile = function writeFile (p, contents, cb) {\n\t var this$1 = this;\n\t\n\t this._wrap(function (interceptCb) {\n\t this$1._client.writeFile(p, contents, interceptCb);\n\t }, function (err, stat) {\n\t if (!err) {\n\t this$1.updateCachedInfo(p, stat, contents.slice(0));\n\t }\n\t cb(err, stat);\n\t });\n\t};\n\tCachedDropboxClient.prototype.mkdir = function mkdir (p, cb) {\n\t var this$1 = this;\n\t\n\t this._wrap(function (interceptCb) {\n\t this$1._client.mkdir(p, interceptCb);\n\t }, function (err, stat) {\n\t if (!err) {\n\t this$1.updateCachedInfo(p, stat, []);\n\t }\n\t cb(err);\n\t });\n\t};\n\t/**\n\t * Wraps an operation such that we retry a failed operation 3 times.\n\t * Necessary to deal with Dropbox rate limiting.\n\t *\n\t * @param performOp Function that performs the operation. Will be called up to three times.\n\t * @param cb Called when the operation succeeds, fails in a non-temporary manner, or fails three times.\n\t */\n\tCachedDropboxClient.prototype._wrap = function _wrap (performOp, cb) {\n\t var numRun = 0;\n\t var interceptCb = function (error) {\n\t // Timeout duration, in seconds.\n\t var timeoutDuration = 2;\n\t if (error && 3 > (++numRun)) {\n\t switch (error.status) {\n\t case Dropbox.ApiError.SERVER_ERROR:\n\t case Dropbox.ApiError.NETWORK_ERROR:\n\t case Dropbox.ApiError.RATE_LIMITED:\n\t setTimeout(function () {\n\t performOp(interceptCb);\n\t }, timeoutDuration * 1000);\n\t break;\n\t default:\n\t cb.apply(null, arguments);\n\t break;\n\t }\n\t }\n\t else {\n\t cb.apply(null, arguments);\n\t }\n\t };\n\t performOp(interceptCb);\n\t};\n\tCachedDropboxClient.prototype.getCachedInfo = function getCachedInfo (p) {\n\t return this._cache[p.toLowerCase()];\n\t};\n\tCachedDropboxClient.prototype.putCachedInfo = function putCachedInfo (p, cache) {\n\t this._cache[p.toLowerCase()] = cache;\n\t};\n\tCachedDropboxClient.prototype.deleteCachedInfo = function deleteCachedInfo (p) {\n\t delete this._cache[p.toLowerCase()];\n\t};\n\tCachedDropboxClient.prototype.getCachedDirInfo = function getCachedDirInfo (p) {\n\t var info = this.getCachedInfo(p);\n\t if (isDirInfo(info)) {\n\t return info;\n\t }\n\t else {\n\t return null;\n\t }\n\t};\n\tCachedDropboxClient.prototype.getCachedFileInfo = function getCachedFileInfo (p) {\n\t var info = this.getCachedInfo(p);\n\t if (isFileInfo(info)) {\n\t return info;\n\t }\n\t else {\n\t return null;\n\t }\n\t};\n\tCachedDropboxClient.prototype.updateCachedDirInfo = function updateCachedDirInfo (p, stat, contents) {\n\t if ( contents === void 0 ) contents = null;\n\t\n\t var cachedInfo = this.getCachedInfo(p);\n\t // Dropbox uses the *contentHash* property for directories.\n\t // Ignore stat objects w/o a contentHash defined; those actually exist!!!\n\t // (Example: readdir returns an array of stat objs; stat objs for dirs in that context have no contentHash)\n\t if (stat.contentHash !== null && (cachedInfo === undefined || cachedInfo.stat.contentHash !== stat.contentHash)) {\n\t this.putCachedInfo(p, {\n\t stat: stat,\n\t contents: contents\n\t });\n\t }\n\t};\n\tCachedDropboxClient.prototype.updateCachedFileInfo = function updateCachedFileInfo (p, stat, contents) {\n\t if ( contents === void 0 ) contents = null;\n\t\n\t var cachedInfo = this.getCachedInfo(p);\n\t // Dropbox uses the *versionTag* property for files.\n\t // Ignore stat objects w/o a versionTag defined.\n\t if (stat.versionTag !== null && (cachedInfo === undefined || cachedInfo.stat.versionTag !== stat.versionTag)) {\n\t this.putCachedInfo(p, {\n\t stat: stat,\n\t contents: contents\n\t });\n\t }\n\t};\n\tCachedDropboxClient.prototype.updateCachedInfo = function updateCachedInfo (p, stat, contents) {\n\t if ( contents === void 0 ) contents = null;\n\t\n\t if (stat.isFile && isArrayBuffer(contents)) {\n\t this.updateCachedFileInfo(p, stat, contents);\n\t }\n\t else if (stat.isFolder && Array.isArray(contents)) {\n\t this.updateCachedDirInfo(p, stat, contents);\n\t }\n\t};\n\tvar DropboxFile = (function (PreloadFile$$1) {\n\t function DropboxFile(_fs, _path, _flag, _stat, contents) {\n\t PreloadFile$$1.call(this, _fs, _path, _flag, _stat, contents);\n\t }\n\t\n\t if ( PreloadFile$$1 ) DropboxFile.__proto__ = PreloadFile$$1;\n\t DropboxFile.prototype = Object.create( PreloadFile$$1 && PreloadFile$$1.prototype );\n\t DropboxFile.prototype.constructor = DropboxFile;\n\t DropboxFile.prototype.sync = function sync (cb) {\n\t var this$1 = this;\n\t\n\t if (this.isDirty()) {\n\t var buffer$$1 = this.getBuffer(), arrayBuffer = buffer2ArrayBuffer(buffer$$1);\n\t this._fs._writeFileStrict(this.getPath(), arrayBuffer, function (e) {\n\t if (!e) {\n\t this$1.resetDirty();\n\t }\n\t cb(e);\n\t });\n\t }\n\t else {\n\t cb();\n\t }\n\t };\n\t DropboxFile.prototype.close = function close (cb) {\n\t this.sync(cb);\n\t };\n\t\n\t return DropboxFile;\n\t}(PreloadFile));\n\t/**\n\t * A read/write file system backed by Dropbox cloud storage.\n\t *\n\t * Uses the Dropbox V1 API.\n\t *\n\t * NOTE: You must use the v0.10 version of the [Dropbox JavaScript SDK](https://www.npmjs.com/package/dropbox).\n\t */\n\tvar DropboxFileSystem = (function (BaseFileSystem$$1) {\n\t function DropboxFileSystem(client, deprecateMsg) {\n\t if ( deprecateMsg === void 0 ) deprecateMsg = true;\n\t\n\t BaseFileSystem$$1.call(this);\n\t this._client = new CachedDropboxClient(client);\n\t deprecationMessage(deprecateMsg, DropboxFileSystem.Name, { client: \"authenticated dropbox client instance\" });\n\t constructErrorCodeLookup();\n\t }\n\t\n\t if ( BaseFileSystem$$1 ) DropboxFileSystem.__proto__ = BaseFileSystem$$1;\n\t DropboxFileSystem.prototype = Object.create( BaseFileSystem$$1 && BaseFileSystem$$1.prototype );\n\t DropboxFileSystem.prototype.constructor = DropboxFileSystem;\n\t /**\n\t * Creates a new DropboxFileSystem instance with the given options.\n\t * Must be given an *authenticated* DropboxJS client from the old v0.10 version of the Dropbox JS SDK.\n\t */\n\t DropboxFileSystem.Create = function Create (opts, cb) {\n\t cb(null, new DropboxFileSystem(opts.client, false));\n\t };\n\t DropboxFileSystem.isAvailable = function isAvailable () {\n\t // Checks if the Dropbox library is loaded.\n\t return typeof Dropbox !== 'undefined';\n\t };\n\t DropboxFileSystem.prototype.getName = function getName () {\n\t return DropboxFileSystem.Name;\n\t };\n\t DropboxFileSystem.prototype.isReadOnly = function isReadOnly () {\n\t return false;\n\t };\n\t // Dropbox doesn't support symlinks, properties, or synchronous calls\n\t DropboxFileSystem.prototype.supportsSymlinks = function supportsSymlinks () {\n\t return false;\n\t };\n\t DropboxFileSystem.prototype.supportsProps = function supportsProps () {\n\t return false;\n\t };\n\t DropboxFileSystem.prototype.supportsSynch = function supportsSynch () {\n\t return false;\n\t };\n\t DropboxFileSystem.prototype.empty = function empty (mainCb) {\n\t var this$1 = this;\n\t\n\t this._client.readdir('/', function (error, files) {\n\t if (error) {\n\t mainCb(this$1.convert(error, '/'));\n\t }\n\t else {\n\t var deleteFile = function (file, cb) {\n\t var p = path.join('/', file);\n\t this$1._client.remove(p, function (err) {\n\t cb(err ? this$1.convert(err, p) : null);\n\t });\n\t };\n\t var finished = function (err) {\n\t if (err) {\n\t mainCb(err);\n\t }\n\t else {\n\t mainCb();\n\t }\n\t };\n\t // XXX: typing is to get around overly-restrictive ErrorCallback typing.\n\t eachLimit(files, deleteFile, finished);\n\t }\n\t });\n\t };\n\t DropboxFileSystem.prototype.rename = function rename (oldPath, newPath, cb) {\n\t var this$1 = this;\n\t\n\t this._client.move(oldPath, newPath, function (error) {\n\t if (error) {\n\t // the move is permitted if newPath is a file.\n\t // Check if this is the case, and remove if so.\n\t this$1._client.stat(newPath, function (error2, stat) {\n\t if (error2 || stat.isFolder) {\n\t var missingPath = error.response.error.indexOf(oldPath) > -1 ? oldPath : newPath;\n\t cb(this$1.convert(error, missingPath));\n\t }\n\t else {\n\t // Delete file, repeat rename.\n\t this$1._client.remove(newPath, function (error2) {\n\t if (error2) {\n\t cb(this$1.convert(error2, newPath));\n\t }\n\t else {\n\t this$1.rename(oldPath, newPath, cb);\n\t }\n\t });\n\t }\n\t });\n\t }\n\t else {\n\t cb();\n\t }\n\t });\n\t };\n\t DropboxFileSystem.prototype.stat = function stat (path$$1, isLstat, cb) {\n\t var this$1 = this;\n\t\n\t // Ignore lstat case -- Dropbox doesn't support symlinks\n\t // Stat the file\n\t this._client.stat(path$$1, function (error, stat) {\n\t if (error) {\n\t cb(this$1.convert(error, path$$1));\n\t }\n\t else if (stat && stat.isRemoved) {\n\t // Dropbox keeps track of deleted files, so if a file has existed in the\n\t // past but doesn't any longer, you wont get an error\n\t cb(ApiError.FileError(ErrorCode.ENOENT, path$$1));\n\t }\n\t else {\n\t var stats = new Stats(this$1._statType(stat), stat.size);\n\t return cb(null, stats);\n\t }\n\t });\n\t };\n\t DropboxFileSystem.prototype.open = function open (path$$1, flags, mode, cb) {\n\t var this$1 = this;\n\t\n\t // Try and get the file's contents\n\t this._client.readFile(path$$1, function (error, content, dbStat) {\n\t if (error) {\n\t // If the file's being opened for reading and doesn't exist, return an\n\t // error\n\t if (flags.isReadable()) {\n\t cb(this$1.convert(error, path$$1));\n\t }\n\t else {\n\t switch (error.status) {\n\t // If it's being opened for writing or appending, create it so that\n\t // it can be written to\n\t case Dropbox.ApiError.NOT_FOUND:\n\t var ab = new ArrayBuffer(0);\n\t return this$1._writeFileStrict(path$$1, ab, function (error2, stat) {\n\t if (error2) {\n\t cb(error2);\n\t }\n\t else {\n\t var file = this$1._makeFile(path$$1, flags, stat, arrayBuffer2Buffer(ab));\n\t cb(null, file);\n\t }\n\t });\n\t default:\n\t return cb(this$1.convert(error, path$$1));\n\t }\n\t }\n\t }\n\t else {\n\t // No error\n\t var buffer$$1;\n\t // Dropbox.js seems to set `content` to `null` rather than to an empty\n\t // buffer when reading an empty file. Not sure why this is.\n\t if (content === null) {\n\t buffer$$1 = emptyBuffer();\n\t }\n\t else {\n\t buffer$$1 = arrayBuffer2Buffer(content);\n\t }\n\t var file = this$1._makeFile(path$$1, flags, dbStat, buffer$$1);\n\t return cb(null, file);\n\t }\n\t });\n\t };\n\t DropboxFileSystem.prototype._writeFileStrict = function _writeFileStrict (p, data, cb) {\n\t var this$1 = this;\n\t\n\t var parent = path.dirname(p);\n\t this.stat(parent, false, function (error, stat) {\n\t if (error) {\n\t cb(ApiError.FileError(ErrorCode.ENOENT, parent));\n\t }\n\t else {\n\t this$1._client.writeFile(p, data, function (error2, stat) {\n\t if (error2) {\n\t cb(this$1.convert(error2, p));\n\t }\n\t else {\n\t cb(null, stat);\n\t }\n\t });\n\t }\n\t });\n\t };\n\t /**\n\t * Private\n\t * Returns a BrowserFS object representing the type of a Dropbox.js stat object\n\t */\n\t DropboxFileSystem.prototype._statType = function _statType (stat) {\n\t return stat.isFile ? FileType.FILE : FileType.DIRECTORY;\n\t };\n\t /**\n\t * Private\n\t * Returns a BrowserFS object representing a File, created from the data\n\t * returned by calls to the Dropbox API.\n\t */\n\t DropboxFileSystem.prototype._makeFile = function _makeFile (path$$1, flag, stat, buffer$$1) {\n\t var type = this._statType(stat);\n\t var stats = new Stats(type, stat.size);\n\t return new DropboxFile(this, path$$1, flag, stats, buffer$$1);\n\t };\n\t /**\n\t * Private\n\t * Delete a file or directory from Dropbox\n\t * isFile should reflect which call was made to remove the it (`unlink` or\n\t * `rmdir`). If this doesn't match what's actually at `path`, an error will be\n\t * returned\n\t */\n\t DropboxFileSystem.prototype._remove = function _remove (path$$1, cb, isFile) {\n\t var this$1 = this;\n\t\n\t this._client.stat(path$$1, function (error, stat) {\n\t if (error) {\n\t cb(this$1.convert(error, path$$1));\n\t }\n\t else {\n\t if (stat.isFile && !isFile) {\n\t cb(ApiError.FileError(ErrorCode.ENOTDIR, path$$1));\n\t }\n\t else if (!stat.isFile && isFile) {\n\t cb(ApiError.FileError(ErrorCode.EISDIR, path$$1));\n\t }\n\t else {\n\t this$1._client.remove(path$$1, function (error) {\n\t if (error) {\n\t cb(this$1.convert(error, path$$1));\n\t }\n\t else {\n\t cb(null);\n\t }\n\t });\n\t }\n\t }\n\t });\n\t };\n\t /**\n\t * Delete a file\n\t */\n\t DropboxFileSystem.prototype.unlink = function unlink (path$$1, cb) {\n\t this._remove(path$$1, cb, true);\n\t };\n\t /**\n\t * Delete a directory\n\t */\n\t DropboxFileSystem.prototype.rmdir = function rmdir (path$$1, cb) {\n\t this._remove(path$$1, cb, false);\n\t };\n\t /**\n\t * Create a directory\n\t */\n\t DropboxFileSystem.prototype.mkdir = function mkdir (p, mode, cb) {\n\t var this$1 = this;\n\t\n\t // Dropbox.js' client.mkdir() behaves like `mkdir -p`, i.e. it creates a\n\t // directory and all its ancestors if they don't exist.\n\t // Node's fs.mkdir() behaves like `mkdir`, i.e. it throws an error if an attempt\n\t // is made to create a directory without a parent.\n\t // To handle this inconsistency, a check for the existence of `path`'s parent\n\t // must be performed before it is created, and an error thrown if it does\n\t // not exist\n\t var parent = path.dirname(p);\n\t this._client.stat(parent, function (error, stat) {\n\t if (error) {\n\t cb(this$1.convert(error, parent));\n\t }\n\t else {\n\t this$1._client.mkdir(p, function (error) {\n\t if (error) {\n\t cb(ApiError.FileError(ErrorCode.EEXIST, p));\n\t }\n\t else {\n\t cb(null);\n\t }\n\t });\n\t }\n\t });\n\t };\n\t /**\n\t * Get the names of the files in a directory\n\t */\n\t DropboxFileSystem.prototype.readdir = function readdir (path$$1, cb) {\n\t var this$1 = this;\n\t\n\t this._client.readdir(path$$1, function (error, files) {\n\t if (error) {\n\t return cb(this$1.convert(error));\n\t }\n\t else {\n\t return cb(null, files);\n\t }\n\t });\n\t };\n\t /**\n\t * Converts a Dropbox-JS error into a BFS error.\n\t */\n\t DropboxFileSystem.prototype.convert = function convert (err, path$$1) {\n\t if ( path$$1 === void 0 ) path$$1 = null;\n\t\n\t var errorCode = errorCodeLookup[err.status];\n\t if (errorCode === undefined) {\n\t errorCode = ErrorCode.EIO;\n\t }\n\t if (!path$$1) {\n\t return new ApiError(errorCode);\n\t }\n\t else {\n\t return ApiError.FileError(errorCode, path$$1);\n\t }\n\t };\n\t\n\t return DropboxFileSystem;\n\t}(BaseFileSystem));\n\t\n\tDropboxFileSystem.Name = \"Dropbox\";\n\tDropboxFileSystem.Options = {\n\t client: {\n\t type: \"object\",\n\t description: \"An *authenticated* Dropbox client. Must be from the 0.10 JS SDK.\",\n\t validator: function (opt, cb) {\n\t if (opt.isAuthenticated && opt.isAuthenticated()) {\n\t cb();\n\t }\n\t else {\n\t cb(new ApiError(ErrorCode.EINVAL, \"'client' option must be an authenticated Dropbox client from the v0.10 JS SDK.\"));\n\t }\n\t }\n\t }\n\t};\n\t\n\t/**\n\t * @hidden\n\t */\n\tfunction convertError(e, path$$1) {\n\t if ( path$$1 === void 0 ) path$$1 = '';\n\t\n\t var errno = e.errno;\n\t var parent = e.node;\n\t var paths = [];\n\t while (parent) {\n\t paths.unshift(parent.name);\n\t if (parent === parent.parent) {\n\t break;\n\t }\n\t parent = parent.parent;\n\t }\n\t return new ApiError(errno, ErrorStrings[errno], paths.length > 0 ? '/' + paths.join('/') : path$$1);\n\t}\n\tvar EmscriptenFile = (function (BaseFile$$1) {\n\t function EmscriptenFile(_fs, _FS, _path, _stream) {\n\t BaseFile$$1.call(this);\n\t this._fs = _fs;\n\t this._FS = _FS;\n\t this._path = _path;\n\t this._stream = _stream;\n\t }\n\t\n\t if ( BaseFile$$1 ) EmscriptenFile.__proto__ = BaseFile$$1;\n\t EmscriptenFile.prototype = Object.create( BaseFile$$1 && BaseFile$$1.prototype );\n\t EmscriptenFile.prototype.constructor = EmscriptenFile;\n\t EmscriptenFile.prototype.getPos = function getPos () {\n\t return undefined;\n\t };\n\t EmscriptenFile.prototype.close = function close (cb) {\n\t var err = null;\n\t try {\n\t this.closeSync();\n\t }\n\t catch (e) {\n\t err = e;\n\t }\n\t finally {\n\t cb(err);\n\t }\n\t };\n\t EmscriptenFile.prototype.closeSync = function closeSync () {\n\t try {\n\t this._FS.close(this._stream);\n\t }\n\t catch (e) {\n\t throw convertError(e, this._path);\n\t }\n\t };\n\t EmscriptenFile.prototype.stat = function stat (cb) {\n\t try {\n\t cb(null, this.statSync());\n\t }\n\t catch (e) {\n\t cb(e);\n\t }\n\t };\n\t EmscriptenFile.prototype.statSync = function statSync () {\n\t try {\n\t return this._fs.statSync(this._path, false);\n\t }\n\t catch (e) {\n\t throw convertError(e, this._path);\n\t }\n\t };\n\t EmscriptenFile.prototype.truncate = function truncate (len, cb) {\n\t var err = null;\n\t try {\n\t this.truncateSync(len);\n\t }\n\t catch (e) {\n\t err = e;\n\t }\n\t finally {\n\t cb(err);\n\t }\n\t };\n\t EmscriptenFile.prototype.truncateSync = function truncateSync (len) {\n\t try {\n\t this._FS.ftruncate(this._stream.fd, len);\n\t }\n\t catch (e) {\n\t throw convertError(e, this._path);\n\t }\n\t };\n\t EmscriptenFile.prototype.write = function write (buffer$$1, offset, length, position, cb) {\n\t try {\n\t cb(null, this.writeSync(buffer$$1, offset, length, position), buffer$$1);\n\t }\n\t catch (e) {\n\t cb(e);\n\t }\n\t };\n\t EmscriptenFile.prototype.writeSync = function writeSync (buffer$$1, offset, length, position) {\n\t try {\n\t var u8 = buffer2Uint8array(buffer$$1);\n\t // Emscripten is particular about what position is set to.\n\t var emPosition = position === null ? undefined : position;\n\t return this._FS.write(this._stream, u8, offset, length, emPosition);\n\t }\n\t catch (e) {\n\t throw convertError(e, this._path);\n\t }\n\t };\n\t EmscriptenFile.prototype.read = function read (buffer$$1, offset, length, position, cb) {\n\t try {\n\t cb(null, this.readSync(buffer$$1, offset, length, position), buffer$$1);\n\t }\n\t catch (e) {\n\t cb(e);\n\t }\n\t };\n\t EmscriptenFile.prototype.readSync = function readSync (buffer$$1, offset, length, position) {\n\t try {\n\t var u8 = buffer2Uint8array(buffer$$1);\n\t // Emscripten is particular about what position is set to.\n\t var emPosition = position === null ? undefined : position;\n\t return this._FS.read(this._stream, u8, offset, length, emPosition);\n\t }\n\t catch (e) {\n\t throw convertError(e, this._path);\n\t }\n\t };\n\t EmscriptenFile.prototype.sync = function sync (cb) {\n\t // NOP.\n\t cb();\n\t };\n\t EmscriptenFile.prototype.syncSync = function syncSync () {\n\t // NOP.\n\t };\n\t EmscriptenFile.prototype.chown = function chown (uid, gid, cb) {\n\t var err = null;\n\t try {\n\t this.chownSync(uid, gid);\n\t }\n\t catch (e) {\n\t err = e;\n\t }\n\t finally {\n\t cb(err);\n\t }\n\t };\n\t EmscriptenFile.prototype.chownSync = function chownSync (uid, gid) {\n\t try {\n\t this._FS.fchown(this._stream.fd, uid, gid);\n\t }\n\t catch (e) {\n\t throw convertError(e, this._path);\n\t }\n\t };\n\t EmscriptenFile.prototype.chmod = function chmod (mode, cb) {\n\t var err = null;\n\t try {\n\t this.chmodSync(mode);\n\t }\n\t catch (e) {\n\t err = e;\n\t }\n\t finally {\n\t cb(err);\n\t }\n\t };\n\t EmscriptenFile.prototype.chmodSync = function chmodSync (mode) {\n\t try {\n\t this._FS.fchmod(this._stream.fd, mode);\n\t }\n\t catch (e) {\n\t throw convertError(e, this._path);\n\t }\n\t };\n\t EmscriptenFile.prototype.utimes = function utimes (atime, mtime, cb) {\n\t var err = null;\n\t try {\n\t this.utimesSync(atime, mtime);\n\t }\n\t catch (e) {\n\t err = e;\n\t }\n\t finally {\n\t cb(err);\n\t }\n\t };\n\t EmscriptenFile.prototype.utimesSync = function utimesSync (atime, mtime) {\n\t this._fs.utimesSync(this._path, atime, mtime);\n\t };\n\t\n\t return EmscriptenFile;\n\t}(BaseFile));\n\t/**\n\t * Mounts an Emscripten file system into the BrowserFS file system.\n\t */\n\tvar EmscriptenFileSystem = (function (SynchronousFileSystem$$1) {\n\t function EmscriptenFileSystem(_FS) {\n\t SynchronousFileSystem$$1.call(this);\n\t this._FS = _FS;\n\t }\n\t\n\t if ( SynchronousFileSystem$$1 ) EmscriptenFileSystem.__proto__ = SynchronousFileSystem$$1;\n\t EmscriptenFileSystem.prototype = Object.create( SynchronousFileSystem$$1 && SynchronousFileSystem$$1.prototype );\n\t EmscriptenFileSystem.prototype.constructor = EmscriptenFileSystem;\n\t /**\n\t * Create an EmscriptenFileSystem instance with the given options.\n\t */\n\t EmscriptenFileSystem.Create = function Create (opts, cb) {\n\t cb(null, new EmscriptenFileSystem(opts.FS));\n\t };\n\t EmscriptenFileSystem.isAvailable = function isAvailable () { return true; };\n\t EmscriptenFileSystem.prototype.getName = function getName () { return this._FS.DB_NAME(); };\n\t EmscriptenFileSystem.prototype.isReadOnly = function isReadOnly () { return false; };\n\t EmscriptenFileSystem.prototype.supportsLinks = function supportsLinks () { return true; };\n\t EmscriptenFileSystem.prototype.supportsProps = function supportsProps () { return true; };\n\t EmscriptenFileSystem.prototype.supportsSynch = function supportsSynch () { return true; };\n\t EmscriptenFileSystem.prototype.renameSync = function renameSync (oldPath, newPath) {\n\t try {\n\t this._FS.rename(oldPath, newPath);\n\t }\n\t catch (e) {\n\t if (e.errno === ErrorCode.ENOENT) {\n\t throw convertError(e, this.existsSync(oldPath) ? newPath : oldPath);\n\t }\n\t else {\n\t throw convertError(e);\n\t }\n\t }\n\t };\n\t EmscriptenFileSystem.prototype.statSync = function statSync (p, isLstat) {\n\t try {\n\t var stats = isLstat ? this._FS.lstat(p) : this._FS.stat(p);\n\t var itemType = this.modeToFileType(stats.mode);\n\t return new Stats(itemType, stats.size, stats.mode, stats.atime, stats.mtime, stats.ctime);\n\t }\n\t catch (e) {\n\t throw convertError(e, p);\n\t }\n\t };\n\t EmscriptenFileSystem.prototype.openSync = function openSync (p, flag, mode) {\n\t try {\n\t var stream = this._FS.open(p, flag.getFlagString(), mode);\n\t if (this._FS.isDir(stream.node.mode)) {\n\t this._FS.close(stream);\n\t throw ApiError.EISDIR(p);\n\t }\n\t return new EmscriptenFile(this, this._FS, p, stream);\n\t }\n\t catch (e) {\n\t throw convertError(e, p);\n\t }\n\t };\n\t EmscriptenFileSystem.prototype.unlinkSync = function unlinkSync (p) {\n\t try {\n\t this._FS.unlink(p);\n\t }\n\t catch (e) {\n\t throw convertError(e, p);\n\t }\n\t };\n\t EmscriptenFileSystem.prototype.rmdirSync = function rmdirSync (p) {\n\t try {\n\t this._FS.rmdir(p);\n\t }\n\t catch (e) {\n\t throw convertError(e, p);\n\t }\n\t };\n\t EmscriptenFileSystem.prototype.mkdirSync = function mkdirSync (p, mode) {\n\t try {\n\t this._FS.mkdir(p, mode);\n\t }\n\t catch (e) {\n\t throw convertError(e, p);\n\t }\n\t };\n\t EmscriptenFileSystem.prototype.readdirSync = function readdirSync (p) {\n\t try {\n\t // Emscripten returns items for '.' and '..'. Node does not.\n\t return this._FS.readdir(p).filter(function (p) { return p !== '.' && p !== '..'; });\n\t }\n\t catch (e) {\n\t throw convertError(e, p);\n\t }\n\t };\n\t EmscriptenFileSystem.prototype.truncateSync = function truncateSync (p, len) {\n\t try {\n\t this._FS.truncate(p, len);\n\t }\n\t catch (e) {\n\t throw convertError(e, p);\n\t }\n\t };\n\t EmscriptenFileSystem.prototype.readFileSync = function readFileSync (p, encoding, flag) {\n\t try {\n\t var data = this._FS.readFile(p, { flags: flag.getFlagString() });\n\t var buff = uint8Array2Buffer(data);\n\t if (encoding) {\n\t return buff.toString(encoding);\n\t }\n\t else {\n\t return buff;\n\t }\n\t }\n\t catch (e) {\n\t throw convertError(e, p);\n\t }\n\t };\n\t EmscriptenFileSystem.prototype.writeFileSync = function writeFileSync (p, data, encoding, flag, mode) {\n\t try {\n\t if (encoding) {\n\t data = Buffer.from(data, encoding);\n\t }\n\t var u8 = buffer2Uint8array(data);\n\t this._FS.writeFile(p, u8, { flags: flag.getFlagString(), encoding: 'binary' });\n\t this._FS.chmod(p, mode);\n\t }\n\t catch (e) {\n\t throw convertError(e, p);\n\t }\n\t };\n\t EmscriptenFileSystem.prototype.chmodSync = function chmodSync (p, isLchmod, mode) {\n\t try {\n\t isLchmod ? this._FS.lchmod(p, mode) : this._FS.chmod(p, mode);\n\t }\n\t catch (e) {\n\t throw convertError(e, p);\n\t }\n\t };\n\t EmscriptenFileSystem.prototype.chownSync = function chownSync (p, isLchown, uid, gid) {\n\t try {\n\t isLchown ? this._FS.lchown(p, uid, gid) : this._FS.chown(p, uid, gid);\n\t }\n\t catch (e) {\n\t throw convertError(e, p);\n\t }\n\t };\n\t EmscriptenFileSystem.prototype.symlinkSync = function symlinkSync (srcpath, dstpath, type) {\n\t try {\n\t this._FS.symlink(srcpath, dstpath);\n\t }\n\t catch (e) {\n\t throw convertError(e);\n\t }\n\t };\n\t EmscriptenFileSystem.prototype.readlinkSync = function readlinkSync (p) {\n\t try {\n\t return this._FS.readlink(p);\n\t }\n\t catch (e) {\n\t throw convertError(e, p);\n\t }\n\t };\n\t EmscriptenFileSystem.prototype.utimesSync = function utimesSync (p, atime, mtime) {\n\t try {\n\t this._FS.utime(p, atime.getTime(), mtime.getTime());\n\t }\n\t catch (e) {\n\t throw convertError(e, p);\n\t }\n\t };\n\t EmscriptenFileSystem.prototype.modeToFileType = function modeToFileType (mode) {\n\t if (this._FS.isDir(mode)) {\n\t return FileType.DIRECTORY;\n\t }\n\t else if (this._FS.isFile(mode)) {\n\t return FileType.FILE;\n\t }\n\t else if (this._FS.isLink(mode)) {\n\t return FileType.SYMLINK;\n\t }\n\t else {\n\t throw ApiError.EPERM((\"Invalid mode: \" + mode));\n\t }\n\t };\n\t\n\t return EmscriptenFileSystem;\n\t}(SynchronousFileSystem));\n\t\n\tEmscriptenFileSystem.Name = \"EmscriptenFileSystem\";\n\tEmscriptenFileSystem.Options = {\n\t FS: {\n\t type: \"object\",\n\t description: \"The Emscripten file system to use (the `FS` variable)\"\n\t }\n\t};\n\t\n\t/**\n\t * The FolderAdapter file system wraps a file system, and scopes all interactions to a subfolder of that file system.\n\t *\n\t * Example: Given a file system `foo` with folder `bar` and file `bar/baz`...\n\t *\n\t * ```javascript\n\t * BrowserFS.configure({\n\t * fs: \"FolderAdapter\",\n\t * options: {\n\t * folder: \"bar\",\n\t * wrapped: foo\n\t * }\n\t * }, function(e) {\n\t * var fs = BrowserFS.BFSRequire('fs');\n\t * fs.readdirSync('/'); // ['baz']\n\t * });\n\t * ```\n\t */\n\tvar FolderAdapter = (function (BaseFileSystem$$1) {\n\t function FolderAdapter(folder, wrapped) {\n\t BaseFileSystem$$1.call(this);\n\t this._folder = folder;\n\t this._wrapped = wrapped;\n\t }\n\t\n\t if ( BaseFileSystem$$1 ) FolderAdapter.__proto__ = BaseFileSystem$$1;\n\t FolderAdapter.prototype = Object.create( BaseFileSystem$$1 && BaseFileSystem$$1.prototype );\n\t FolderAdapter.prototype.constructor = FolderAdapter;\n\t /**\n\t * Creates a FolderAdapter instance with the given options.\n\t */\n\t FolderAdapter.Create = function Create (opts, cb) {\n\t cb(null, new FolderAdapter(opts.folder, opts.wrapped));\n\t };\n\t FolderAdapter.isAvailable = function isAvailable () {\n\t return true;\n\t };\n\t /**\n\t * Initialize the file system. Ensures that the wrapped file system\n\t * has the given folder.\n\t */\n\t FolderAdapter.prototype.initialize = function initialize (cb) {\n\t var this$1 = this;\n\t\n\t this._wrapped.exists(this._folder, function (exists) {\n\t if (exists) {\n\t cb();\n\t }\n\t else if (this$1._wrapped.isReadOnly()) {\n\t cb(ApiError.ENOENT(this$1._folder));\n\t }\n\t else {\n\t this$1._wrapped.mkdir(this$1._folder, 0x1ff, cb);\n\t }\n\t });\n\t };\n\t FolderAdapter.prototype.getName = function getName () { return this._wrapped.getName(); };\n\t FolderAdapter.prototype.isReadOnly = function isReadOnly () { return this._wrapped.isReadOnly(); };\n\t FolderAdapter.prototype.supportsProps = function supportsProps () { return this._wrapped.supportsProps(); };\n\t FolderAdapter.prototype.supportsSynch = function supportsSynch () { return this._wrapped.supportsSynch(); };\n\t FolderAdapter.prototype.supportsLinks = function supportsLinks () { return false; };\n\t\n\t return FolderAdapter;\n\t}(BaseFileSystem));\n\t\n\tFolderAdapter.Name = \"FolderAdapter\";\n\tFolderAdapter.Options = {\n\t folder: {\n\t type: \"string\",\n\t description: \"The folder to use as the root directory\"\n\t },\n\t wrapped: {\n\t type: \"object\",\n\t description: \"The file system to wrap\"\n\t }\n\t};\n\t/**\n\t * @hidden\n\t */\n\tfunction translateError(folder, e) {\n\t if (e !== null && typeof e === 'object') {\n\t var err = e;\n\t var p = err.path;\n\t if (p) {\n\t p = '/' + path.relative(folder, p);\n\t err.message = err.message.replace(err.path, p);\n\t err.path = p;\n\t }\n\t }\n\t return e;\n\t}\n\t/**\n\t * @hidden\n\t */\n\tfunction wrapCallback(folder, cb) {\n\t if (typeof cb === 'function') {\n\t return function (err) {\n\t if (arguments.length > 0) {\n\t arguments[0] = translateError(folder, err);\n\t }\n\t cb.apply(null, arguments);\n\t };\n\t }\n\t else {\n\t return cb;\n\t }\n\t}\n\t/**\n\t * @hidden\n\t */\n\tfunction wrapFunction(name, wrapFirst, wrapSecond) {\n\t if (name.slice(name.length - 4) !== 'Sync') {\n\t // Async function. Translate error in callback.\n\t return function () {\n\t if (arguments.length > 0) {\n\t if (wrapFirst) {\n\t arguments[0] = path.join(this._folder, arguments[0]);\n\t }\n\t if (wrapSecond) {\n\t arguments[1] = path.join(this._folder, arguments[1]);\n\t }\n\t arguments[arguments.length - 1] = wrapCallback(this._folder, arguments[arguments.length - 1]);\n\t }\n\t return this._wrapped[name].apply(this._wrapped, arguments);\n\t };\n\t }\n\t else {\n\t // Sync function. Translate error in catch.\n\t return function () {\n\t try {\n\t if (wrapFirst) {\n\t arguments[0] = path.join(this._folder, arguments[0]);\n\t }\n\t if (wrapSecond) {\n\t arguments[1] = path.join(this._folder, arguments[1]);\n\t }\n\t return this._wrapped[name].apply(this._wrapped, arguments);\n\t }\n\t catch (e) {\n\t throw translateError(this._folder, e);\n\t }\n\t };\n\t }\n\t}\n\t// First argument is a path.\n\t['diskSpace', 'stat', 'statSync', 'open', 'openSync', 'unlink', 'unlinkSync',\n\t 'rmdir', 'rmdirSync', 'mkdir', 'mkdirSync', 'readdir', 'readdirSync', 'exists',\n\t 'existsSync', 'realpath', 'realpathSync', 'truncate', 'truncateSync', 'readFile',\n\t 'readFileSync', 'writeFile', 'writeFileSync', 'appendFile', 'appendFileSync',\n\t 'chmod', 'chmodSync', 'chown', 'chownSync', 'utimes', 'utimesSync', 'readlink',\n\t 'readlinkSync'].forEach(function (name) {\n\t FolderAdapter.prototype[name] = wrapFunction(name, true, false);\n\t});\n\t// First and second arguments are paths.\n\t['rename', 'renameSync', 'link', 'linkSync', 'symlink', 'symlinkSync'].forEach(function (name) {\n\t FolderAdapter.prototype[name] = wrapFunction(name, true, true);\n\t});\n\t\n\t/**\n\t * @hidden\n\t */\n\tvar toExport;\n\tif (typeof (window) !== 'undefined') {\n\t toExport = window;\n\t}\n\telse if (typeof (self) !== 'undefined') {\n\t toExport = self;\n\t}\n\telse {\n\t toExport = global;\n\t}\n\tvar global$1 = toExport;\n\t\n\t/**\n\t * @hidden\n\t */\n\tfunction isDirectoryEntry(entry) {\n\t return entry.isDirectory;\n\t}\n\t/**\n\t * @hidden\n\t */\n\tvar _getFS = global$1.webkitRequestFileSystem || global$1.requestFileSystem || null;\n\t/**\n\t * @hidden\n\t */\n\tfunction _requestQuota(type, size, success, errorCallback) {\n\t // We cast navigator and window to '' because everything here is\n\t // nonstandard functionality, despite the fact that Chrome has the only\n\t // implementation of the HTML5FS and is likely driving the standardization\n\t // process. Thus, these objects defined off of navigator and window are not\n\t // present in the DefinitelyTyped TypeScript typings for FileSystem.\n\t if (typeof navigator['webkitPersistentStorage'] !== 'undefined') {\n\t switch (type) {\n\t case global$1.PERSISTENT:\n\t navigator.webkitPersistentStorage.requestQuota(size, success, errorCallback);\n\t break;\n\t case global$1.TEMPORARY:\n\t navigator.webkitTemporaryStorage.requestQuota(size, success, errorCallback);\n\t break;\n\t default:\n\t errorCallback(new TypeError((\"Invalid storage type: \" + type)));\n\t break;\n\t }\n\t }\n\t else {\n\t global$1.webkitStorageInfo.requestQuota(type, size, success, errorCallback);\n\t }\n\t}\n\t/**\n\t * @hidden\n\t */\n\tfunction _toArray(list) {\n\t return Array.prototype.slice.call(list || [], 0);\n\t}\n\t/**\n\t * Converts the given DOMError into an appropriate ApiError.\n\t * @url https://developer.mozilla.org/en-US/docs/Web/API/DOMError\n\t * @hidden\n\t */\n\tfunction convertError$1(err, p, expectedDir) {\n\t switch (err.name) {\n\t /* The user agent failed to create a file or directory due to the existence of a file or\n\t directory with the same path. */\n\t case \"PathExistsError\":\n\t return ApiError.EEXIST(p);\n\t /* The operation failed because it would cause the application to exceed its storage quota. */\n\t case 'QuotaExceededError':\n\t return ApiError.FileError(ErrorCode.ENOSPC, p);\n\t /* A required file or directory could not be found at the time an operation was processed. */\n\t case 'NotFoundError':\n\t return ApiError.ENOENT(p);\n\t /* This is a security error code to be used in situations not covered by any other error codes.\n\t - A required file was unsafe for access within a Web application\n\t - Too many calls are being made on filesystem resources */\n\t case 'SecurityError':\n\t return ApiError.FileError(ErrorCode.EACCES, p);\n\t /* The modification requested was illegal. Examples of invalid modifications include moving a\n\t directory into its own child, moving a file into its parent directory without changing its name,\n\t or copying a directory to a path occupied by a file. */\n\t case 'InvalidModificationError':\n\t return ApiError.FileError(ErrorCode.EPERM, p);\n\t /* The user has attempted to look up a file or directory, but the Entry found is of the wrong type\n\t [e.g. is a DirectoryEntry when the user requested a FileEntry]. */\n\t case 'TypeMismatchError':\n\t return ApiError.FileError(expectedDir ? ErrorCode.ENOTDIR : ErrorCode.EISDIR, p);\n\t /* A path or URL supplied to the API was malformed. */\n\t case \"EncodingError\":\n\t /* An operation depended on state cached in an interface object, but that state that has changed\n\t since it was read from disk. */\n\t case \"InvalidStateError\":\n\t /* The user attempted to write to a file or directory which could not be modified due to the state\n\t of the underlying filesystem. */\n\t case \"NoModificationAllowedError\":\n\t default:\n\t return ApiError.FileError(ErrorCode.EINVAL, p);\n\t }\n\t}\n\t// A note about getFile and getDirectory options:\n\t// These methods are called at numerous places in this file, and are passed\n\t// some combination of these two options:\n\t// - create: If true, the entry will be created if it doesn't exist.\n\t// If false, an error will be thrown if it doesn't exist.\n\t// - exclusive: If true, only create the entry if it doesn't already exist,\n\t// and throw an error if it does.\n\tvar HTML5FSFile = (function (PreloadFile$$1) {\n\t function HTML5FSFile(fs, entry, path$$1, flag, stat, contents) {\n\t PreloadFile$$1.call(this, fs, path$$1, flag, stat, contents);\n\t this._entry = entry;\n\t }\n\t\n\t if ( PreloadFile$$1 ) HTML5FSFile.__proto__ = PreloadFile$$1;\n\t HTML5FSFile.prototype = Object.create( PreloadFile$$1 && PreloadFile$$1.prototype );\n\t HTML5FSFile.prototype.constructor = HTML5FSFile;\n\t HTML5FSFile.prototype.sync = function sync (cb) {\n\t var this$1 = this;\n\t\n\t if (!this.isDirty()) {\n\t return cb();\n\t }\n\t this._entry.createWriter(function (writer) {\n\t var buffer$$1 = this$1.getBuffer();\n\t var blob = new Blob([buffer2ArrayBuffer(buffer$$1)]);\n\t var length = blob.size;\n\t writer.onwriteend = function (err) {\n\t writer.onwriteend = null;\n\t writer.onerror = null;\n\t writer.truncate(length);\n\t this$1.resetDirty();\n\t cb();\n\t };\n\t writer.onerror = function (err) {\n\t cb(convertError$1(err, this$1.getPath(), false));\n\t };\n\t writer.write(blob);\n\t });\n\t };\n\t HTML5FSFile.prototype.close = function close (cb) {\n\t this.sync(cb);\n\t };\n\t\n\t return HTML5FSFile;\n\t}(PreloadFile));\n\t/**\n\t * A read-write filesystem backed by the HTML5 FileSystem API.\n\t *\n\t * As the HTML5 FileSystem is only implemented in Blink, this interface is\n\t * only available in Chrome.\n\t */\n\tvar HTML5FS = (function (BaseFileSystem$$1) {\n\t function HTML5FS(size, type, deprecateMsg) {\n\t if ( size === void 0 ) size = 5;\n\t if ( type === void 0 ) type = global$1.PERSISTENT;\n\t if ( deprecateMsg === void 0 ) deprecateMsg = true;\n\t\n\t BaseFileSystem$$1.call(this);\n\t // Convert MB to bytes.\n\t this.size = 1024 * 1024 * size;\n\t this.type = type;\n\t deprecationMessage(deprecateMsg, HTML5FS.Name, { size: size, type: type });\n\t }\n\t\n\t if ( BaseFileSystem$$1 ) HTML5FS.__proto__ = BaseFileSystem$$1;\n\t HTML5FS.prototype = Object.create( BaseFileSystem$$1 && BaseFileSystem$$1.prototype );\n\t HTML5FS.prototype.constructor = HTML5FS;\n\t /**\n\t * Creates an HTML5FS instance with the given options.\n\t */\n\t HTML5FS.Create = function Create (opts, cb) {\n\t var fs = new HTML5FS(opts.size, opts.type, false);\n\t fs.allocate(function (e) { return e ? cb(e) : cb(null, fs); }, false);\n\t };\n\t HTML5FS.isAvailable = function isAvailable () {\n\t return !!_getFS;\n\t };\n\t HTML5FS.prototype.getName = function getName () {\n\t return HTML5FS.Name;\n\t };\n\t HTML5FS.prototype.isReadOnly = function isReadOnly () {\n\t return false;\n\t };\n\t HTML5FS.prototype.supportsSymlinks = function supportsSymlinks () {\n\t return false;\n\t };\n\t HTML5FS.prototype.supportsProps = function supportsProps () {\n\t return false;\n\t };\n\t HTML5FS.prototype.supportsSynch = function supportsSynch () {\n\t return false;\n\t };\n\t /**\n\t * **Deprecated. Please use Create() method instead to create and allocate an HTML5FS.**\n\t *\n\t * Requests a storage quota from the browser to back this FS.\n\t * Must be called before file system can be used!\n\t */\n\t HTML5FS.prototype.allocate = function allocate (cb, deprecateMsg) {\n\t var this$1 = this;\n\t if ( cb === void 0 ) cb = function () { };\n\t if ( deprecateMsg === void 0 ) deprecateMsg = true;\n\t\n\t if (deprecateMsg) {\n\t console.warn((\"[HTML5FS] HTML5FS.allocate() is deprecated and will be removed in the next major release. Please use 'HTML5FS.Create({type: \" + (this.type) + \", size: \" + (this.size) + \"}, cb)' to create and allocate HTML5FS instances.\"));\n\t }\n\t var success = function (fs) {\n\t this$1.fs = fs;\n\t cb();\n\t };\n\t var error = function (err) {\n\t cb(convertError$1(err, \"/\", true));\n\t };\n\t if (this.type === global$1.PERSISTENT) {\n\t _requestQuota(this.type, this.size, function (granted) {\n\t _getFS(this$1.type, granted, success, error);\n\t }, error);\n\t }\n\t else {\n\t _getFS(this.type, this.size, success, error);\n\t }\n\t };\n\t /**\n\t * Deletes everything in the FS. Used for testing.\n\t * Karma clears the storage after you quit it but not between runs of the test\n\t * suite, and the tests expect an empty FS every time.\n\t */\n\t HTML5FS.prototype.empty = function empty (mainCb) {\n\t // Get a list of all entries in the root directory to delete them\n\t this._readdir('/', function (err, entries) {\n\t if (err) {\n\t console.error('Failed to empty FS');\n\t mainCb(err);\n\t }\n\t else {\n\t // Called when every entry has been operated on\n\t var finished = function (er) {\n\t if (err) {\n\t console.error(\"Failed to empty FS\");\n\t mainCb(err);\n\t }\n\t else {\n\t mainCb();\n\t }\n\t };\n\t // Removes files and recursively removes directories\n\t var deleteEntry = function (entry, cb) {\n\t var succ = function () {\n\t cb();\n\t };\n\t var error = function (err) {\n\t cb(convertError$1(err, entry.fullPath, !entry.isDirectory));\n\t };\n\t if (isDirectoryEntry(entry)) {\n\t entry.removeRecursively(succ, error);\n\t }\n\t else {\n\t entry.remove(succ, error);\n\t }\n\t };\n\t // Loop through the entries and remove them, then call the callback\n\t // when they're all finished.\n\t eachLimit(entries, deleteEntry, finished);\n\t }\n\t });\n\t };\n\t HTML5FS.prototype.rename = function rename (oldPath, newPath, cb) {\n\t var this$1 = this;\n\t\n\t var semaphore = 2;\n\t var successCount = 0;\n\t var root = this.fs.root;\n\t var currentPath = oldPath;\n\t var error = function (err) {\n\t if (--semaphore <= 0) {\n\t cb(convertError$1(err, currentPath, false));\n\t }\n\t };\n\t var success = function (file) {\n\t if (++successCount === 2) {\n\t return cb(new ApiError(ErrorCode.EINVAL, \"Something was identified as both a file and a directory. This should never happen.\"));\n\t }\n\t // SPECIAL CASE: If newPath === oldPath, and the path exists, then\n\t // this operation trivially succeeds.\n\t if (oldPath === newPath) {\n\t return cb();\n\t }\n\t // Get the new parent directory.\n\t currentPath = path.dirname(newPath);\n\t root.getDirectory(currentPath, {}, function (parentDir) {\n\t currentPath = path.basename(newPath);\n\t file.moveTo(parentDir, currentPath, function (entry) { cb(); }, function (err) {\n\t // SPECIAL CASE: If oldPath is a directory, and newPath is a\n\t // file, rename should delete the file and perform the move.\n\t if (file.isDirectory) {\n\t currentPath = newPath;\n\t // Unlink only works on files. Try to delete newPath.\n\t this$1.unlink(newPath, function (e) {\n\t if (e) {\n\t // newPath is probably a directory.\n\t error(err);\n\t }\n\t else {\n\t // Recur, now that newPath doesn't exist.\n\t this$1.rename(oldPath, newPath, cb);\n\t }\n\t });\n\t }\n\t else {\n\t error(err);\n\t }\n\t });\n\t }, error);\n\t };\n\t // We don't know if oldPath is a *file* or a *directory*, and there's no\n\t // way to stat items. So launch both requests, see which one succeeds.\n\t root.getFile(oldPath, {}, success, error);\n\t root.getDirectory(oldPath, {}, success, error);\n\t };\n\t HTML5FS.prototype.stat = function stat (path$$1, isLstat, cb) {\n\t var this$1 = this;\n\t\n\t // Throw an error if the entry doesn't exist, because then there's nothing\n\t // to stat.\n\t var opts = {\n\t create: false\n\t };\n\t // Called when the path has been successfully loaded as a file.\n\t var loadAsFile = function (entry) {\n\t var fileFromEntry = function (file) {\n\t var stat = new Stats(FileType.FILE, file.size);\n\t cb(null, stat);\n\t };\n\t entry.file(fileFromEntry, failedToLoad);\n\t };\n\t // Called when the path has been successfully loaded as a directory.\n\t var loadAsDir = function (dir$$1) {\n\t // Directory entry size can't be determined from the HTML5 FS API, and is\n\t // implementation-dependant anyway, so a dummy value is used.\n\t var size = 4096;\n\t var stat = new Stats(FileType.DIRECTORY, size);\n\t cb(null, stat);\n\t };\n\t // Called when the path couldn't be opened as a directory or a file.\n\t var failedToLoad = function (err) {\n\t cb(convertError$1(err, path$$1, false /* Unknown / irrelevant */));\n\t };\n\t // Called when the path couldn't be opened as a file, but might still be a\n\t // directory.\n\t var failedToLoadAsFile = function () {\n\t this$1.fs.root.getDirectory(path$$1, opts, loadAsDir, failedToLoad);\n\t };\n\t // No method currently exists to determine whether a path refers to a\n\t // directory or a file, so this implementation tries both and uses the first\n\t // one that succeeds.\n\t this.fs.root.getFile(path$$1, opts, loadAsFile, failedToLoadAsFile);\n\t };\n\t HTML5FS.prototype.open = function open (p, flags, mode, cb) {\n\t var this$1 = this;\n\t\n\t // XXX: err is a DOMError\n\t var error = function (err) {\n\t if (err.name === 'InvalidModificationError' && flags.isExclusive()) {\n\t cb(ApiError.EEXIST(p));\n\t }\n\t else {\n\t cb(convertError$1(err, p, false));\n\t }\n\t };\n\t this.fs.root.getFile(p, {\n\t create: flags.pathNotExistsAction() === ActionType.CREATE_FILE,\n\t exclusive: flags.isExclusive()\n\t }, function (entry) {\n\t // Try to fetch corresponding file.\n\t entry.file(function (file) {\n\t var reader = new FileReader();\n\t reader.onloadend = function (event) {\n\t var bfsFile = this$1._makeFile(p, entry, flags, file, reader.result);\n\t cb(null, bfsFile);\n\t };\n\t reader.onerror = function (ev) {\n\t error(reader.error);\n\t };\n\t reader.readAsArrayBuffer(file);\n\t }, error);\n\t }, error);\n\t };\n\t HTML5FS.prototype.unlink = function unlink (path$$1, cb) {\n\t this._remove(path$$1, cb, true);\n\t };\n\t HTML5FS.prototype.rmdir = function rmdir (path$$1, cb) {\n\t var this$1 = this;\n\t\n\t // Check if directory is non-empty, first.\n\t this.readdir(path$$1, function (e, files) {\n\t if (e) {\n\t cb(e);\n\t }\n\t else if (files.length > 0) {\n\t cb(ApiError.ENOTEMPTY(path$$1));\n\t }\n\t else {\n\t this$1._remove(path$$1, cb, false);\n\t }\n\t });\n\t };\n\t HTML5FS.prototype.mkdir = function mkdir (path$$1, mode, cb) {\n\t // Create the directory, but throw an error if it already exists, as per\n\t // mkdir(1)\n\t var opts = {\n\t create: true,\n\t exclusive: true\n\t };\n\t var success = function (dir$$1) {\n\t cb();\n\t };\n\t var error = function (err) {\n\t cb(convertError$1(err, path$$1, true));\n\t };\n\t this.fs.root.getDirectory(path$$1, opts, success, error);\n\t };\n\t /**\n\t * Map _readdir's list of `FileEntry`s to their names and return that.\n\t */\n\t HTML5FS.prototype.readdir = function readdir (path$$1, cb) {\n\t this._readdir(path$$1, function (e, entries) {\n\t if (entries) {\n\t var rv = [];\n\t for (var i = 0, list = entries; i < list.length; i += 1) {\n\t var entry = list[i];\n\t\n\t rv.push(entry.name);\n\t }\n\t cb(null, rv);\n\t }\n\t else {\n\t return cb(e);\n\t }\n\t });\n\t };\n\t /**\n\t * Returns a BrowserFS object representing a File.\n\t */\n\t HTML5FS.prototype._makeFile = function _makeFile (path$$1, entry, flag, stat, data) {\n\t if ( data === void 0 ) data = new ArrayBuffer(0);\n\t\n\t var stats = new Stats(FileType.FILE, stat.size);\n\t var buffer$$1 = arrayBuffer2Buffer(data);\n\t return new HTML5FSFile(this, entry, path$$1, flag, stats, buffer$$1);\n\t };\n\t /**\n\t * Returns an array of `FileEntry`s. Used internally by empty and readdir.\n\t */\n\t HTML5FS.prototype._readdir = function _readdir (path$$1, cb) {\n\t var error = function (err) {\n\t cb(convertError$1(err, path$$1, true));\n\t };\n\t // Grab the requested directory.\n\t this.fs.root.getDirectory(path$$1, { create: false }, function (dirEntry) {\n\t var reader = dirEntry.createReader();\n\t var entries = [];\n\t // Call the reader.readEntries() until no more results are returned.\n\t var readEntries = function () {\n\t reader.readEntries((function (results) {\n\t if (results.length) {\n\t entries = entries.concat(_toArray(results));\n\t readEntries();\n\t }\n\t else {\n\t cb(null, entries);\n\t }\n\t }), error);\n\t };\n\t readEntries();\n\t }, error);\n\t };\n\t /**\n\t * Delete a file or directory from the file system\n\t * isFile should reflect which call was made to remove the it (`unlink` or\n\t * `rmdir`). If this doesn't match what's actually at `path`, an error will be\n\t * returned\n\t */\n\t HTML5FS.prototype._remove = function _remove (path$$1, cb, isFile) {\n\t var success = function (entry) {\n\t var succ = function () {\n\t cb();\n\t };\n\t var err = function (err) {\n\t cb(convertError$1(err, path$$1, !isFile));\n\t };\n\t entry.remove(succ, err);\n\t };\n\t var error = function (err) {\n\t cb(convertError$1(err, path$$1, !isFile));\n\t };\n\t // Deleting the entry, so don't create it\n\t var opts = {\n\t create: false\n\t };\n\t if (isFile) {\n\t this.fs.root.getFile(path$$1, opts, success, error);\n\t }\n\t else {\n\t this.fs.root.getDirectory(path$$1, opts, success, error);\n\t }\n\t };\n\t\n\t return HTML5FS;\n\t}(BaseFileSystem));\n\t\n\tHTML5FS.Name = \"HTML5FS\";\n\tHTML5FS.Options = {\n\t size: {\n\t type: \"number\",\n\t optional: true,\n\t description: \"Storage quota to request, in megabytes. Allocated value may be less. Defaults to 5.\"\n\t },\n\t type: {\n\t type: \"number\",\n\t optional: true,\n\t description: \"window.PERSISTENT or window.TEMPORARY. Defaults to PERSISTENT.\"\n\t }\n\t};\n\t\n\t/**\n\t * Generic inode definition that can easily be serialized.\n\t */\n\tvar Inode = function Inode(id, size, mode, atime, mtime, ctime) {\n\t this.id = id;\n\t this.size = size;\n\t this.mode = mode;\n\t this.atime = atime;\n\t this.mtime = mtime;\n\t this.ctime = ctime;\n\t};\n\t/**\n\t * Converts the buffer into an Inode.\n\t */\n\tInode.fromBuffer = function fromBuffer (buffer$$1) {\n\t if (buffer$$1 === undefined) {\n\t throw new Error(\"NO\");\n\t }\n\t return new Inode(buffer$$1.toString('ascii', 30), buffer$$1.readUInt32LE(0), buffer$$1.readUInt16LE(4), buffer$$1.readDoubleLE(6), buffer$$1.readDoubleLE(14), buffer$$1.readDoubleLE(22));\n\t};\n\t/**\n\t * Handy function that converts the Inode to a Node Stats object.\n\t */\n\tInode.prototype.toStats = function toStats () {\n\t return new Stats((this.mode & 0xF000) === FileType.DIRECTORY ? FileType.DIRECTORY : FileType.FILE, this.size, this.mode, new Date(this.atime), new Date(this.mtime), new Date(this.ctime));\n\t};\n\t/**\n\t * Get the size of this Inode, in bytes.\n\t */\n\tInode.prototype.getSize = function getSize () {\n\t // ASSUMPTION: ID is ASCII (1 byte per char).\n\t return 30 + this.id.length;\n\t};\n\t/**\n\t * Writes the inode into the start of the buffer.\n\t */\n\tInode.prototype.toBuffer = function toBuffer (buff) {\n\t if ( buff === void 0 ) buff = Buffer.alloc(this.getSize());\n\t\n\t buff.writeUInt32LE(this.size, 0);\n\t buff.writeUInt16LE(this.mode, 4);\n\t buff.writeDoubleLE(this.atime, 6);\n\t buff.writeDoubleLE(this.mtime, 14);\n\t buff.writeDoubleLE(this.ctime, 22);\n\t buff.write(this.id, 30, this.id.length, 'ascii');\n\t return buff;\n\t};\n\t/**\n\t * Updates the Inode using information from the stats object. Used by file\n\t * systems at sync time, e.g.:\n\t * - Program opens file and gets a File object.\n\t * - Program mutates file. File object is responsible for maintaining\n\t * metadata changes locally -- typically in a Stats object.\n\t * - Program closes file. File object's metadata changes are synced with the\n\t * file system.\n\t * @return True if any changes have occurred.\n\t */\n\tInode.prototype.update = function update (stats) {\n\t var hasChanged = false;\n\t if (this.size !== stats.size) {\n\t this.size = stats.size;\n\t hasChanged = true;\n\t }\n\t if (this.mode !== stats.mode) {\n\t this.mode = stats.mode;\n\t hasChanged = true;\n\t }\n\t var atimeMs = stats.atime.getTime();\n\t if (this.atime !== atimeMs) {\n\t this.atime = atimeMs;\n\t hasChanged = true;\n\t }\n\t var mtimeMs = stats.mtime.getTime();\n\t if (this.mtime !== mtimeMs) {\n\t this.mtime = mtimeMs;\n\t hasChanged = true;\n\t }\n\t var ctimeMs = stats.ctime.getTime();\n\t if (this.ctime !== ctimeMs) {\n\t this.ctime = ctimeMs;\n\t hasChanged = true;\n\t }\n\t return hasChanged;\n\t};\n\t// XXX: Copied from Stats. Should reconcile these two into something more\n\t// compact.\n\t/**\n\t * @return [Boolean] True if this item is a file.\n\t */\n\tInode.prototype.isFile = function isFile () {\n\t return (this.mode & 0xF000) === FileType.FILE;\n\t};\n\t/**\n\t * @return [Boolean] True if this item is a directory.\n\t */\n\tInode.prototype.isDirectory = function isDirectory () {\n\t return (this.mode & 0xF000) === FileType.DIRECTORY;\n\t};\n\t\n\t/**\n\t * @hidden\n\t */\n\tvar ROOT_NODE_ID = \"/\";\n\t/**\n\t * @hidden\n\t */\n\tvar emptyDirNode = null;\n\t/**\n\t * Returns an empty directory node.\n\t * @hidden\n\t */\n\tfunction getEmptyDirNode() {\n\t if (emptyDirNode) {\n\t return emptyDirNode;\n\t }\n\t return emptyDirNode = Buffer.from(\"{}\");\n\t}\n\t/**\n\t * Generates a random ID.\n\t * @hidden\n\t */\n\tfunction GenerateRandomID() {\n\t // From http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript\n\t return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {\n\t var r = Math.random() * 16 | 0;\n\t var v = c === 'x' ? r : (r & 0x3 | 0x8);\n\t return v.toString(16);\n\t });\n\t}\n\t/**\n\t * Helper function. Checks if 'e' is defined. If so, it triggers the callback\n\t * with 'e' and returns false. Otherwise, returns true.\n\t * @hidden\n\t */\n\tfunction noError(e, cb) {\n\t if (e) {\n\t cb(e);\n\t return false;\n\t }\n\t return true;\n\t}\n\t/**\n\t * Helper function. Checks if 'e' is defined. If so, it aborts the transaction,\n\t * triggers the callback with 'e', and returns false. Otherwise, returns true.\n\t * @hidden\n\t */\n\tfunction noErrorTx(e, tx, cb) {\n\t if (e) {\n\t tx.abort(function () {\n\t cb(e);\n\t });\n\t return false;\n\t }\n\t return true;\n\t}\n\t/**\n\t * A simple RW transaction for simple synchronous key-value stores.\n\t */\n\tvar SimpleSyncRWTransaction = function SimpleSyncRWTransaction(store) {\n\t this.store = store;\n\t /**\n\t * Stores data in the keys we modify prior to modifying them.\n\t * Allows us to roll back commits.\n\t */\n\t this.originalData = {};\n\t /**\n\t * List of keys modified in this transaction, if any.\n\t */\n\t this.modifiedKeys = [];\n\t};\n\tSimpleSyncRWTransaction.prototype.get = function get (key) {\n\t var val = this.store.get(key);\n\t this.stashOldValue(key, val);\n\t return val;\n\t};\n\tSimpleSyncRWTransaction.prototype.put = function put (key, data, overwrite) {\n\t this.markModified(key);\n\t return this.store.put(key, data, overwrite);\n\t};\n\tSimpleSyncRWTransaction.prototype.del = function del (key) {\n\t this.markModified(key);\n\t this.store.del(key);\n\t};\n\tSimpleSyncRWTransaction.prototype.commit = function commit () { };\n\tSimpleSyncRWTransaction.prototype.abort = function abort () {\n\t var this$1 = this;\n\t\n\t // Rollback old values.\n\t for (var i = 0, list = this$1.modifiedKeys; i < list.length; i += 1) {\n\t var key = list[i];\n\t\n\t var value = this$1.originalData[key];\n\t if (!value) {\n\t // Key didn't exist.\n\t this$1.store.del(key);\n\t }\n\t else {\n\t // Key existed. Store old value.\n\t this$1.store.put(key, value, true);\n\t }\n\t }\n\t};\n\t/**\n\t * Stashes given key value pair into `originalData` if it doesn't already\n\t * exist. Allows us to stash values the program is requesting anyway to\n\t * prevent needless `get` requests if the program modifies the data later\n\t * on during the transaction.\n\t */\n\tSimpleSyncRWTransaction.prototype.stashOldValue = function stashOldValue (key, value) {\n\t // Keep only the earliest value in the transaction.\n\t if (!this.originalData.hasOwnProperty(key)) {\n\t this.originalData[key] = value;\n\t }\n\t};\n\t/**\n\t * Marks the given key as modified, and stashes its value if it has not been\n\t * stashed already.\n\t */\n\tSimpleSyncRWTransaction.prototype.markModified = function markModified (key) {\n\t if (this.modifiedKeys.indexOf(key) === -1) {\n\t this.modifiedKeys.push(key);\n\t if (!this.originalData.hasOwnProperty(key)) {\n\t this.originalData[key] = this.store.get(key);\n\t }\n\t }\n\t};\n\tvar SyncKeyValueFile = (function (PreloadFile$$1) {\n\t function SyncKeyValueFile(_fs, _path, _flag, _stat, contents) {\n\t PreloadFile$$1.call(this, _fs, _path, _flag, _stat, contents);\n\t }\n\t\n\t if ( PreloadFile$$1 ) SyncKeyValueFile.__proto__ = PreloadFile$$1;\n\t SyncKeyValueFile.prototype = Object.create( PreloadFile$$1 && PreloadFile$$1.prototype );\n\t SyncKeyValueFile.prototype.constructor = SyncKeyValueFile;\n\t SyncKeyValueFile.prototype.syncSync = function syncSync () {\n\t if (this.isDirty()) {\n\t this._fs._syncSync(this.getPath(), this.getBuffer(), this.getStats());\n\t this.resetDirty();\n\t }\n\t };\n\t SyncKeyValueFile.prototype.closeSync = function closeSync () {\n\t this.syncSync();\n\t };\n\t\n\t return SyncKeyValueFile;\n\t}(PreloadFile));\n\t/**\n\t * A \"Synchronous key-value file system\". Stores data to/retrieves data from an\n\t * underlying key-value store.\n\t *\n\t * We use a unique ID for each node in the file system. The root node has a\n\t * fixed ID.\n\t * @todo Introduce Node ID caching.\n\t * @todo Check modes.\n\t */\n\tvar SyncKeyValueFileSystem = (function (SynchronousFileSystem$$1) {\n\t function SyncKeyValueFileSystem(options) {\n\t SynchronousFileSystem$$1.call(this);\n\t this.store = options.store;\n\t // INVARIANT: Ensure that the root exists.\n\t this.makeRootDirectory();\n\t }\n\t\n\t if ( SynchronousFileSystem$$1 ) SyncKeyValueFileSystem.__proto__ = SynchronousFileSystem$$1;\n\t SyncKeyValueFileSystem.prototype = Object.create( SynchronousFileSystem$$1 && SynchronousFileSystem$$1.prototype );\n\t SyncKeyValueFileSystem.prototype.constructor = SyncKeyValueFileSystem;\n\t SyncKeyValueFileSystem.isAvailable = function isAvailable () { return true; };\n\t\n\t SyncKeyValueFileSystem.prototype.getName = function getName () { return this.store.name(); };\n\t SyncKeyValueFileSystem.prototype.isReadOnly = function isReadOnly () { return false; };\n\t SyncKeyValueFileSystem.prototype.supportsSymlinks = function supportsSymlinks () { return false; };\n\t SyncKeyValueFileSystem.prototype.supportsProps = function supportsProps () { return false; };\n\t SyncKeyValueFileSystem.prototype.supportsSynch = function supportsSynch () { return true; };\n\t /**\n\t * Delete all contents stored in the file system.\n\t */\n\t SyncKeyValueFileSystem.prototype.empty = function empty () {\n\t this.store.clear();\n\t // INVARIANT: Root always exists.\n\t this.makeRootDirectory();\n\t };\n\t SyncKeyValueFileSystem.prototype.renameSync = function renameSync (oldPath, newPath) {\n\t var tx = this.store.beginTransaction('readwrite'), oldParent = path.dirname(oldPath), oldName = path.basename(oldPath), newParent = path.dirname(newPath), newName = path.basename(newPath), \n\t // Remove oldPath from parent's directory listing.\n\t oldDirNode = this.findINode(tx, oldParent), oldDirList = this.getDirListing(tx, oldParent, oldDirNode);\n\t if (!oldDirList[oldName]) {\n\t throw ApiError.ENOENT(oldPath);\n\t }\n\t var nodeId = oldDirList[oldName];\n\t delete oldDirList[oldName];\n\t // Invariant: Can't move a folder inside itself.\n\t // This funny little hack ensures that the check passes only if oldPath\n\t // is a subpath of newParent. We append '/' to avoid matching folders that\n\t // are a substring of the bottom-most folder in the path.\n\t if ((newParent + '/').indexOf(oldPath + '/') === 0) {\n\t throw new ApiError(ErrorCode.EBUSY, oldParent);\n\t }\n\t // Add newPath to parent's directory listing.\n\t var newDirNode, newDirList;\n\t if (newParent === oldParent) {\n\t // Prevent us from re-grabbing the same directory listing, which still\n\t // contains oldName.\n\t newDirNode = oldDirNode;\n\t newDirList = oldDirList;\n\t }\n\t else {\n\t newDirNode = this.findINode(tx, newParent);\n\t newDirList = this.getDirListing(tx, newParent, newDirNode);\n\t }\n\t if (newDirList[newName]) {\n\t // If it's a file, delete it.\n\t var newNameNode = this.getINode(tx, newPath, newDirList[newName]);\n\t if (newNameNode.isFile()) {\n\t try {\n\t tx.del(newNameNode.id);\n\t tx.del(newDirList[newName]);\n\t }\n\t catch (e) {\n\t tx.abort();\n\t throw e;\n\t }\n\t }\n\t else {\n\t // If it's a directory, throw a permissions error.\n\t throw ApiError.EPERM(newPath);\n\t }\n\t }\n\t newDirList[newName] = nodeId;\n\t // Commit the two changed directory listings.\n\t try {\n\t tx.put(oldDirNode.id, Buffer.from(JSON.stringify(oldDirList)), true);\n\t tx.put(newDirNode.id, Buffer.from(JSON.stringify(newDirList)), true);\n\t }\n\t catch (e) {\n\t tx.abort();\n\t throw e;\n\t }\n\t tx.commit();\n\t };\n\t SyncKeyValueFileSystem.prototype.statSync = function statSync (p, isLstat) {\n\t // Get the inode to the item, convert it into a Stats object.\n\t return this.findINode(this.store.beginTransaction('readonly'), p).toStats();\n\t };\n\t SyncKeyValueFileSystem.prototype.createFileSync = function createFileSync (p, flag, mode) {\n\t var tx = this.store.beginTransaction('readwrite'), data = emptyBuffer(), newFile = this.commitNewFile(tx, p, FileType.FILE, mode, data);\n\t // Open the file.\n\t return new SyncKeyValueFile(this, p, flag, newFile.toStats(), data);\n\t };\n\t SyncKeyValueFileSystem.prototype.openFileSync = function openFileSync (p, flag) {\n\t var tx = this.store.beginTransaction('readonly'), node = this.findINode(tx, p), data = tx.get(node.id);\n\t if (data === undefined) {\n\t throw ApiError.ENOENT(p);\n\t }\n\t return new SyncKeyValueFile(this, p, flag, node.toStats(), data);\n\t };\n\t SyncKeyValueFileSystem.prototype.unlinkSync = function unlinkSync (p) {\n\t this.removeEntry(p, false);\n\t };\n\t SyncKeyValueFileSystem.prototype.rmdirSync = function rmdirSync (p) {\n\t // Check first if directory is empty.\n\t if (this.readdirSync(p).length > 0) {\n\t throw ApiError.ENOTEMPTY(p);\n\t }\n\t else {\n\t this.removeEntry(p, true);\n\t }\n\t };\n\t SyncKeyValueFileSystem.prototype.mkdirSync = function mkdirSync (p, mode) {\n\t var tx = this.store.beginTransaction('readwrite'), data = Buffer.from('{}');\n\t this.commitNewFile(tx, p, FileType.DIRECTORY, mode, data);\n\t };\n\t SyncKeyValueFileSystem.prototype.readdirSync = function readdirSync (p) {\n\t var tx = this.store.beginTransaction('readonly');\n\t return Object.keys(this.getDirListing(tx, p, this.findINode(tx, p)));\n\t };\n\t SyncKeyValueFileSystem.prototype._syncSync = function _syncSync (p, data, stats) {\n\t // @todo Ensure mtime updates properly, and use that to determine if a data\n\t // update is required.\n\t var tx = this.store.beginTransaction('readwrite'), \n\t // We use the _findInode helper because we actually need the INode id.\n\t fileInodeId = this._findINode(tx, path.dirname(p), path.basename(p)), fileInode = this.getINode(tx, p, fileInodeId), inodeChanged = fileInode.update(stats);\n\t try {\n\t // Sync data.\n\t tx.put(fileInode.id, data, true);\n\t // Sync metadata.\n\t if (inodeChanged) {\n\t tx.put(fileInodeId, fileInode.toBuffer(), true);\n\t }\n\t }\n\t catch (e) {\n\t tx.abort();\n\t throw e;\n\t }\n\t tx.commit();\n\t };\n\t /**\n\t * Checks if the root directory exists. Creates it if it doesn't.\n\t */\n\t SyncKeyValueFileSystem.prototype.makeRootDirectory = function makeRootDirectory () {\n\t var tx = this.store.beginTransaction('readwrite');\n\t if (tx.get(ROOT_NODE_ID) === undefined) {\n\t // Create new inode.\n\t var currTime = (new Date()).getTime(), \n\t // Mode 0666\n\t dirInode = new Inode(GenerateRandomID(), 4096, 511 | FileType.DIRECTORY, currTime, currTime, currTime);\n\t // If the root doesn't exist, the first random ID shouldn't exist,\n\t // either.\n\t tx.put(dirInode.id, getEmptyDirNode(), false);\n\t tx.put(ROOT_NODE_ID, dirInode.toBuffer(), false);\n\t tx.commit();\n\t }\n\t };\n\t /**\n\t * Helper function for findINode.\n\t * @param parent The parent directory of the file we are attempting to find.\n\t * @param filename The filename of the inode we are attempting to find, minus\n\t * the parent.\n\t * @return string The ID of the file's inode in the file system.\n\t */\n\t SyncKeyValueFileSystem.prototype._findINode = function _findINode (tx, parent, filename) {\n\t var this$1 = this;\n\t\n\t var readDirectory = function (inode) {\n\t // Get the root's directory listing.\n\t var dirList = this$1.getDirListing(tx, parent, inode);\n\t // Get the file's ID.\n\t if (dirList[filename]) {\n\t return dirList[filename];\n\t }\n\t else {\n\t throw ApiError.ENOENT(path.resolve(parent, filename));\n\t }\n\t };\n\t if (parent === '/') {\n\t if (filename === '') {\n\t // BASE CASE #1: Return the root's ID.\n\t return ROOT_NODE_ID;\n\t }\n\t else {\n\t // BASE CASE #2: Find the item in the root ndoe.\n\t return readDirectory(this.getINode(tx, parent, ROOT_NODE_ID));\n\t }\n\t }\n\t else {\n\t return readDirectory(this.getINode(tx, parent + path.sep + filename, this._findINode(tx, path.dirname(parent), path.basename(parent))));\n\t }\n\t };\n\t /**\n\t * Finds the Inode of the given path.\n\t * @param p The path to look up.\n\t * @return The Inode of the path p.\n\t * @todo memoize/cache\n\t */\n\t SyncKeyValueFileSystem.prototype.findINode = function findINode (tx, p) {\n\t return this.getINode(tx, p, this._findINode(tx, path.dirname(p), path.basename(p)));\n\t };\n\t /**\n\t * Given the ID of a node, retrieves the corresponding Inode.\n\t * @param tx The transaction to use.\n\t * @param p The corresponding path to the file (used for error messages).\n\t * @param id The ID to look up.\n\t */\n\t SyncKeyValueFileSystem.prototype.getINode = function getINode (tx, p, id) {\n\t var inode = tx.get(id);\n\t if (inode === undefined) {\n\t throw ApiError.ENOENT(p);\n\t }\n\t return Inode.fromBuffer(inode);\n\t };\n\t /**\n\t * Given the Inode of a directory, retrieves the corresponding directory\n\t * listing.\n\t */\n\t SyncKeyValueFileSystem.prototype.getDirListing = function getDirListing (tx, p, inode) {\n\t if (!inode.isDirectory()) {\n\t throw ApiError.ENOTDIR(p);\n\t }\n\t var data = tx.get(inode.id);\n\t if (data === undefined) {\n\t throw ApiError.ENOENT(p);\n\t }\n\t return JSON.parse(data.toString());\n\t };\n\t /**\n\t * Creates a new node under a random ID. Retries 5 times before giving up in\n\t * the exceedingly unlikely chance that we try to reuse a random GUID.\n\t * @return The GUID that the data was stored under.\n\t */\n\t SyncKeyValueFileSystem.prototype.addNewNode = function addNewNode (tx, data) {\n\t var retries = 0;\n\t var currId;\n\t while (retries < 5) {\n\t try {\n\t currId = GenerateRandomID();\n\t tx.put(currId, data, false);\n\t return currId;\n\t }\n\t catch (e) {\n\t // Ignore and reroll.\n\t }\n\t }\n\t throw new ApiError(ErrorCode.EIO, 'Unable to commit data to key-value store.');\n\t };\n\t /**\n\t * Commits a new file (well, a FILE or a DIRECTORY) to the file system with\n\t * the given mode.\n\t * Note: This will commit the transaction.\n\t * @param p The path to the new file.\n\t * @param type The type of the new file.\n\t * @param mode The mode to create the new file with.\n\t * @param data The data to store at the file's data node.\n\t * @return The Inode for the new file.\n\t */\n\t SyncKeyValueFileSystem.prototype.commitNewFile = function commitNewFile (tx, p, type, mode, data) {\n\t var parentDir = path.dirname(p), fname = path.basename(p), parentNode = this.findINode(tx, parentDir), dirListing = this.getDirListing(tx, parentDir, parentNode), currTime = (new Date()).getTime();\n\t // Invariant: The root always exists.\n\t // If we don't check this prior to taking steps below, we will create a\n\t // file with name '' in root should p == '/'.\n\t if (p === '/') {\n\t throw ApiError.EEXIST(p);\n\t }\n\t // Check if file already exists.\n\t if (dirListing[fname]) {\n\t throw ApiError.EEXIST(p);\n\t }\n\t var fileNode;\n\t try {\n\t // Commit data.\n\t var dataId = this.addNewNode(tx, data);\n\t fileNode = new Inode(dataId, data.length, mode | type, currTime, currTime, currTime);\n\t // Commit file node.\n\t var fileNodeId = this.addNewNode(tx, fileNode.toBuffer());\n\t // Update and commit parent directory listing.\n\t dirListing[fname] = fileNodeId;\n\t tx.put(parentNode.id, Buffer.from(JSON.stringify(dirListing)), true);\n\t }\n\t catch (e) {\n\t tx.abort();\n\t throw e;\n\t }\n\t tx.commit();\n\t return fileNode;\n\t };\n\t /**\n\t * Remove all traces of the given path from the file system.\n\t * @param p The path to remove from the file system.\n\t * @param isDir Does the path belong to a directory, or a file?\n\t * @todo Update mtime.\n\t */\n\t SyncKeyValueFileSystem.prototype.removeEntry = function removeEntry (p, isDir) {\n\t var tx = this.store.beginTransaction('readwrite'), parent = path.dirname(p), parentNode = this.findINode(tx, parent), parentListing = this.getDirListing(tx, parent, parentNode), fileName = path.basename(p);\n\t if (!parentListing[fileName]) {\n\t throw ApiError.ENOENT(p);\n\t }\n\t // Remove from directory listing of parent.\n\t var fileNodeId = parentListing[fileName];\n\t delete parentListing[fileName];\n\t // Get file inode.\n\t var fileNode = this.getINode(tx, p, fileNodeId);\n\t if (!isDir && fileNode.isDirectory()) {\n\t throw ApiError.EISDIR(p);\n\t }\n\t else if (isDir && !fileNode.isDirectory()) {\n\t throw ApiError.ENOTDIR(p);\n\t }\n\t try {\n\t // Delete data.\n\t tx.del(fileNode.id);\n\t // Delete node.\n\t tx.del(fileNodeId);\n\t // Update directory listing.\n\t tx.put(parentNode.id, Buffer.from(JSON.stringify(parentListing)), true);\n\t }\n\t catch (e) {\n\t tx.abort();\n\t throw e;\n\t }\n\t // Success.\n\t tx.commit();\n\t };\n\t\n\t return SyncKeyValueFileSystem;\n\t}(SynchronousFileSystem));\n\tvar AsyncKeyValueFile = (function (PreloadFile$$1) {\n\t function AsyncKeyValueFile(_fs, _path, _flag, _stat, contents) {\n\t PreloadFile$$1.call(this, _fs, _path, _flag, _stat, contents);\n\t }\n\t\n\t if ( PreloadFile$$1 ) AsyncKeyValueFile.__proto__ = PreloadFile$$1;\n\t AsyncKeyValueFile.prototype = Object.create( PreloadFile$$1 && PreloadFile$$1.prototype );\n\t AsyncKeyValueFile.prototype.constructor = AsyncKeyValueFile;\n\t AsyncKeyValueFile.prototype.sync = function sync (cb) {\n\t var this$1 = this;\n\t\n\t if (this.isDirty()) {\n\t this._fs._sync(this.getPath(), this.getBuffer(), this.getStats(), function (e) {\n\t if (!e) {\n\t this$1.resetDirty();\n\t }\n\t cb(e);\n\t });\n\t }\n\t else {\n\t cb();\n\t }\n\t };\n\t AsyncKeyValueFile.prototype.close = function close (cb) {\n\t this.sync(cb);\n\t };\n\t\n\t return AsyncKeyValueFile;\n\t}(PreloadFile));\n\t/**\n\t * An \"Asynchronous key-value file system\". Stores data to/retrieves data from\n\t * an underlying asynchronous key-value store.\n\t */\n\tvar AsyncKeyValueFileSystem = (function (BaseFileSystem$$1) {\n\t function AsyncKeyValueFileSystem () {\n\t BaseFileSystem$$1.apply(this, arguments);\n\t }\n\t\n\t if ( BaseFileSystem$$1 ) AsyncKeyValueFileSystem.__proto__ = BaseFileSystem$$1;\n\t AsyncKeyValueFileSystem.prototype = Object.create( BaseFileSystem$$1 && BaseFileSystem$$1.prototype );\n\t AsyncKeyValueFileSystem.prototype.constructor = AsyncKeyValueFileSystem;\n\t\n\t AsyncKeyValueFileSystem.isAvailable = function isAvailable () { return true; };\n\t /**\n\t * Initializes the file system. Typically called by subclasses' async\n\t * constructors.\n\t */\n\t AsyncKeyValueFileSystem.prototype.init = function init (store, cb) {\n\t this.store = store;\n\t // INVARIANT: Ensure that the root exists.\n\t this.makeRootDirectory(cb);\n\t };\n\t AsyncKeyValueFileSystem.prototype.getName = function getName () { return this.store.name(); };\n\t AsyncKeyValueFileSystem.prototype.isReadOnly = function isReadOnly () { return false; };\n\t AsyncKeyValueFileSystem.prototype.supportsSymlinks = function supportsSymlinks () { return false; };\n\t AsyncKeyValueFileSystem.prototype.supportsProps = function supportsProps () { return false; };\n\t AsyncKeyValueFileSystem.prototype.supportsSynch = function supportsSynch () { return false; };\n\t /**\n\t * Delete all contents stored in the file system.\n\t */\n\t AsyncKeyValueFileSystem.prototype.empty = function empty (cb) {\n\t var this$1 = this;\n\t\n\t this.store.clear(function (e) {\n\t if (noError(e, cb)) {\n\t // INVARIANT: Root always exists.\n\t this$1.makeRootDirectory(cb);\n\t }\n\t });\n\t };\n\t AsyncKeyValueFileSystem.prototype.rename = function rename (oldPath, newPath, cb) {\n\t var this$1 = this;\n\t\n\t var tx = this.store.beginTransaction('readwrite');\n\t var oldParent = path.dirname(oldPath), oldName = path.basename(oldPath);\n\t var newParent = path.dirname(newPath), newName = path.basename(newPath);\n\t var inodes = {};\n\t var lists = {};\n\t var errorOccurred = false;\n\t // Invariant: Can't move a folder inside itself.\n\t // This funny little hack ensures that the check passes only if oldPath\n\t // is a subpath of newParent. We append '/' to avoid matching folders that\n\t // are a substring of the bottom-most folder in the path.\n\t if ((newParent + '/').indexOf(oldPath + '/') === 0) {\n\t return cb(new ApiError(ErrorCode.EBUSY, oldParent));\n\t }\n\t /**\n\t * Responsible for Phase 2 of the rename operation: Modifying and\n\t * committing the directory listings. Called once we have successfully\n\t * retrieved both the old and new parent's inodes and listings.\n\t */\n\t var theOleSwitcharoo = function () {\n\t // Sanity check: Ensure both paths are present, and no error has occurred.\n\t if (errorOccurred || !lists.hasOwnProperty(oldParent) || !lists.hasOwnProperty(newParent)) {\n\t return;\n\t }\n\t var oldParentList = lists[oldParent], oldParentINode = inodes[oldParent], newParentList = lists[newParent], newParentINode = inodes[newParent];\n\t // Delete file from old parent.\n\t if (!oldParentList[oldName]) {\n\t cb(ApiError.ENOENT(oldPath));\n\t }\n\t else {\n\t var fileId = oldParentList[oldName];\n\t delete oldParentList[oldName];\n\t // Finishes off the renaming process by adding the file to the new\n\t // parent.\n\t var completeRename = function () {\n\t newParentList[newName] = fileId;\n\t // Commit old parent's list.\n\t tx.put(oldParentINode.id, Buffer.from(JSON.stringify(oldParentList)), true, function (e) {\n\t if (noErrorTx(e, tx, cb)) {\n\t if (oldParent === newParent) {\n\t // DONE!\n\t tx.commit(cb);\n\t }\n\t else {\n\t // Commit new parent's list.\n\t tx.put(newParentINode.id, Buffer.from(JSON.stringify(newParentList)), true, function (e) {\n\t if (noErrorTx(e, tx, cb)) {\n\t tx.commit(cb);\n\t }\n\t });\n\t }\n\t }\n\t });\n\t };\n\t if (newParentList[newName]) {\n\t // 'newPath' already exists. Check if it's a file or a directory, and\n\t // act accordingly.\n\t this$1.getINode(tx, newPath, newParentList[newName], function (e, inode) {\n\t if (noErrorTx(e, tx, cb)) {\n\t if (inode.isFile()) {\n\t // Delete the file and continue.\n\t tx.del(inode.id, function (e) {\n\t if (noErrorTx(e, tx, cb)) {\n\t tx.del(newParentList[newName], function (e) {\n\t if (noErrorTx(e, tx, cb)) {\n\t completeRename();\n\t }\n\t });\n\t }\n\t });\n\t }\n\t else {\n\t // Can't overwrite a directory using rename.\n\t tx.abort(function (e) {\n\t cb(ApiError.EPERM(newPath));\n\t });\n\t }\n\t }\n\t });\n\t }\n\t else {\n\t completeRename();\n\t }\n\t }\n\t };\n\t /**\n\t * Grabs a path's inode and directory listing, and shoves it into the\n\t * inodes and lists hashes.\n\t */\n\t var processInodeAndListings = function (p) {\n\t this$1.findINodeAndDirListing(tx, p, function (e, node, dirList) {\n\t if (e) {\n\t if (!errorOccurred) {\n\t errorOccurred = true;\n\t tx.abort(function () {\n\t cb(e);\n\t });\n\t }\n\t // If error has occurred already, just stop here.\n\t }\n\t else {\n\t inodes[p] = node;\n\t lists[p] = dirList;\n\t theOleSwitcharoo();\n\t }\n\t });\n\t };\n\t processInodeAndListings(oldParent);\n\t if (oldParent !== newParent) {\n\t processInodeAndListings(newParent);\n\t }\n\t };\n\t AsyncKeyValueFileSystem.prototype.stat = function stat (p, isLstat, cb) {\n\t var tx = this.store.beginTransaction('readonly');\n\t this.findINode(tx, p, function (e, inode) {\n\t if (noError(e, cb)) {\n\t cb(null, inode.toStats());\n\t }\n\t });\n\t };\n\t AsyncKeyValueFileSystem.prototype.createFile = function createFile (p, flag, mode, cb) {\n\t var this$1 = this;\n\t\n\t var tx = this.store.beginTransaction('readwrite'), data = emptyBuffer();\n\t this.commitNewFile(tx, p, FileType.FILE, mode, data, function (e, newFile) {\n\t if (noError(e, cb)) {\n\t cb(null, new AsyncKeyValueFile(this$1, p, flag, newFile.toStats(), data));\n\t }\n\t });\n\t };\n\t AsyncKeyValueFileSystem.prototype.openFile = function openFile (p, flag, cb) {\n\t var this$1 = this;\n\t\n\t var tx = this.store.beginTransaction('readonly');\n\t // Step 1: Grab the file's inode.\n\t this.findINode(tx, p, function (e, inode) {\n\t if (noError(e, cb)) {\n\t // Step 2: Grab the file's data.\n\t tx.get(inode.id, function (e, data) {\n\t if (noError(e, cb)) {\n\t if (data === undefined) {\n\t cb(ApiError.ENOENT(p));\n\t }\n\t else {\n\t cb(null, new AsyncKeyValueFile(this$1, p, flag, inode.toStats(), data));\n\t }\n\t }\n\t });\n\t }\n\t });\n\t };\n\t AsyncKeyValueFileSystem.prototype.unlink = function unlink (p, cb) {\n\t this.removeEntry(p, false, cb);\n\t };\n\t AsyncKeyValueFileSystem.prototype.rmdir = function rmdir (p, cb) {\n\t var this$1 = this;\n\t\n\t // Check first if directory is empty.\n\t this.readdir(p, function (err, files) {\n\t if (err) {\n\t cb(err);\n\t }\n\t else if (files.length > 0) {\n\t cb(ApiError.ENOTEMPTY(p));\n\t }\n\t else {\n\t this$1.removeEntry(p, true, cb);\n\t }\n\t });\n\t };\n\t AsyncKeyValueFileSystem.prototype.mkdir = function mkdir (p, mode, cb) {\n\t var tx = this.store.beginTransaction('readwrite'), data = Buffer.from('{}');\n\t this.commitNewFile(tx, p, FileType.DIRECTORY, mode, data, cb);\n\t };\n\t AsyncKeyValueFileSystem.prototype.readdir = function readdir (p, cb) {\n\t var this$1 = this;\n\t\n\t var tx = this.store.beginTransaction('readonly');\n\t this.findINode(tx, p, function (e, inode) {\n\t if (noError(e, cb)) {\n\t this$1.getDirListing(tx, p, inode, function (e, dirListing) {\n\t if (noError(e, cb)) {\n\t cb(null, Object.keys(dirListing));\n\t }\n\t });\n\t }\n\t });\n\t };\n\t AsyncKeyValueFileSystem.prototype._sync = function _sync (p, data, stats, cb) {\n\t var this$1 = this;\n\t\n\t // @todo Ensure mtime updates properly, and use that to determine if a data\n\t // update is required.\n\t var tx = this.store.beginTransaction('readwrite');\n\t // Step 1: Get the file node's ID.\n\t this._findINode(tx, path.dirname(p), path.basename(p), function (e, fileInodeId) {\n\t if (noErrorTx(e, tx, cb)) {\n\t // Step 2: Get the file inode.\n\t this$1.getINode(tx, p, fileInodeId, function (e, fileInode) {\n\t if (noErrorTx(e, tx, cb)) {\n\t var inodeChanged = fileInode.update(stats);\n\t // Step 3: Sync the data.\n\t tx.put(fileInode.id, data, true, function (e) {\n\t if (noErrorTx(e, tx, cb)) {\n\t // Step 4: Sync the metadata (if it changed)!\n\t if (inodeChanged) {\n\t tx.put(fileInodeId, fileInode.toBuffer(), true, function (e) {\n\t if (noErrorTx(e, tx, cb)) {\n\t tx.commit(cb);\n\t }\n\t });\n\t }\n\t else {\n\t // No need to sync metadata; return.\n\t tx.commit(cb);\n\t }\n\t }\n\t });\n\t }\n\t });\n\t }\n\t });\n\t };\n\t /**\n\t * Checks if the root directory exists. Creates it if it doesn't.\n\t */\n\t AsyncKeyValueFileSystem.prototype.makeRootDirectory = function makeRootDirectory (cb) {\n\t var tx = this.store.beginTransaction('readwrite');\n\t tx.get(ROOT_NODE_ID, function (e, data) {\n\t if (e || data === undefined) {\n\t // Create new inode.\n\t var currTime = (new Date()).getTime(), \n\t // Mode 0666\n\t dirInode = new Inode(GenerateRandomID(), 4096, 511 | FileType.DIRECTORY, currTime, currTime, currTime);\n\t // If the root doesn't exist, the first random ID shouldn't exist,\n\t // either.\n\t tx.put(dirInode.id, getEmptyDirNode(), false, function (e) {\n\t if (noErrorTx(e, tx, cb)) {\n\t tx.put(ROOT_NODE_ID, dirInode.toBuffer(), false, function (e) {\n\t if (e) {\n\t tx.abort(function () { cb(e); });\n\t }\n\t else {\n\t tx.commit(cb);\n\t }\n\t });\n\t }\n\t });\n\t }\n\t else {\n\t // We're good.\n\t tx.commit(cb);\n\t }\n\t });\n\t };\n\t /**\n\t * Helper function for findINode.\n\t * @param parent The parent directory of the file we are attempting to find.\n\t * @param filename The filename of the inode we are attempting to find, minus\n\t * the parent.\n\t * @param cb Passed an error or the ID of the file's inode in the file system.\n\t */\n\t AsyncKeyValueFileSystem.prototype._findINode = function _findINode (tx, parent, filename, cb) {\n\t var this$1 = this;\n\t\n\t var handleDirectoryListings = function (e, inode, dirList) {\n\t if (e) {\n\t cb(e);\n\t }\n\t else if (dirList[filename]) {\n\t cb(null, dirList[filename]);\n\t }\n\t else {\n\t cb(ApiError.ENOENT(path.resolve(parent, filename)));\n\t }\n\t };\n\t if (parent === '/') {\n\t if (filename === '') {\n\t // BASE CASE #1: Return the root's ID.\n\t cb(null, ROOT_NODE_ID);\n\t }\n\t else {\n\t // BASE CASE #2: Find the item in the root node.\n\t this.getINode(tx, parent, ROOT_NODE_ID, function (e, inode) {\n\t if (noError(e, cb)) {\n\t this$1.getDirListing(tx, parent, inode, function (e, dirList) {\n\t // handle_directory_listings will handle e for us.\n\t handleDirectoryListings(e, inode, dirList);\n\t });\n\t }\n\t });\n\t }\n\t }\n\t else {\n\t // Get the parent directory's INode, and find the file in its directory\n\t // listing.\n\t this.findINodeAndDirListing(tx, parent, handleDirectoryListings);\n\t }\n\t };\n\t /**\n\t * Finds the Inode of the given path.\n\t * @param p The path to look up.\n\t * @param cb Passed an error or the Inode of the path p.\n\t * @todo memoize/cache\n\t */\n\t AsyncKeyValueFileSystem.prototype.findINode = function findINode (tx, p, cb) {\n\t var this$1 = this;\n\t\n\t this._findINode(tx, path.dirname(p), path.basename(p), function (e, id) {\n\t if (noError(e, cb)) {\n\t this$1.getINode(tx, p, id, cb);\n\t }\n\t });\n\t };\n\t /**\n\t * Given the ID of a node, retrieves the corresponding Inode.\n\t * @param tx The transaction to use.\n\t * @param p The corresponding path to the file (used for error messages).\n\t * @param id The ID to look up.\n\t * @param cb Passed an error or the inode under the given id.\n\t */\n\t AsyncKeyValueFileSystem.prototype.getINode = function getINode (tx, p, id, cb) {\n\t tx.get(id, function (e, data) {\n\t if (noError(e, cb)) {\n\t if (data === undefined) {\n\t cb(ApiError.ENOENT(p));\n\t }\n\t else {\n\t cb(null, Inode.fromBuffer(data));\n\t }\n\t }\n\t });\n\t };\n\t /**\n\t * Given the Inode of a directory, retrieves the corresponding directory\n\t * listing.\n\t */\n\t AsyncKeyValueFileSystem.prototype.getDirListing = function getDirListing (tx, p, inode, cb) {\n\t if (!inode.isDirectory()) {\n\t cb(ApiError.ENOTDIR(p));\n\t }\n\t else {\n\t tx.get(inode.id, function (e, data) {\n\t if (noError(e, cb)) {\n\t try {\n\t cb(null, JSON.parse(data.toString()));\n\t }\n\t catch (e) {\n\t // Occurs when data is undefined, or corresponds to something other\n\t // than a directory listing. The latter should never occur unless\n\t // the file system is corrupted.\n\t cb(ApiError.ENOENT(p));\n\t }\n\t }\n\t });\n\t }\n\t };\n\t /**\n\t * Given a path to a directory, retrieves the corresponding INode and\n\t * directory listing.\n\t */\n\t AsyncKeyValueFileSystem.prototype.findINodeAndDirListing = function findINodeAndDirListing (tx, p, cb) {\n\t var this$1 = this;\n\t\n\t this.findINode(tx, p, function (e, inode) {\n\t if (noError(e, cb)) {\n\t this$1.getDirListing(tx, p, inode, function (e, listing) {\n\t if (noError(e, cb)) {\n\t cb(null, inode, listing);\n\t }\n\t });\n\t }\n\t });\n\t };\n\t /**\n\t * Adds a new node under a random ID. Retries 5 times before giving up in\n\t * the exceedingly unlikely chance that we try to reuse a random GUID.\n\t * @param cb Passed an error or the GUID that the data was stored under.\n\t */\n\t AsyncKeyValueFileSystem.prototype.addNewNode = function addNewNode (tx, data, cb) {\n\t var retries = 0, currId;\n\t var reroll = function () {\n\t if (++retries === 5) {\n\t // Max retries hit. Return with an error.\n\t cb(new ApiError(ErrorCode.EIO, 'Unable to commit data to key-value store.'));\n\t }\n\t else {\n\t // Try again.\n\t currId = GenerateRandomID();\n\t tx.put(currId, data, false, function (e, committed) {\n\t if (e || !committed) {\n\t reroll();\n\t }\n\t else {\n\t // Successfully stored under 'currId'.\n\t cb(null, currId);\n\t }\n\t });\n\t }\n\t };\n\t reroll();\n\t };\n\t /**\n\t * Commits a new file (well, a FILE or a DIRECTORY) to the file system with\n\t * the given mode.\n\t * Note: This will commit the transaction.\n\t * @param p The path to the new file.\n\t * @param type The type of the new file.\n\t * @param mode The mode to create the new file with.\n\t * @param data The data to store at the file's data node.\n\t * @param cb Passed an error or the Inode for the new file.\n\t */\n\t AsyncKeyValueFileSystem.prototype.commitNewFile = function commitNewFile (tx, p, type, mode, data, cb) {\n\t var this$1 = this;\n\t\n\t var parentDir = path.dirname(p), fname = path.basename(p), currTime = (new Date()).getTime();\n\t // Invariant: The root always exists.\n\t // If we don't check this prior to taking steps below, we will create a\n\t // file with name '' in root should p == '/'.\n\t if (p === '/') {\n\t return cb(ApiError.EEXIST(p));\n\t }\n\t // Let's build a pyramid of code!\n\t // Step 1: Get the parent directory's inode and directory listing\n\t this.findINodeAndDirListing(tx, parentDir, function (e, parentNode, dirListing) {\n\t if (noErrorTx(e, tx, cb)) {\n\t if (dirListing[fname]) {\n\t // File already exists.\n\t tx.abort(function () {\n\t cb(ApiError.EEXIST(p));\n\t });\n\t }\n\t else {\n\t // Step 2: Commit data to store.\n\t this$1.addNewNode(tx, data, function (e, dataId) {\n\t if (noErrorTx(e, tx, cb)) {\n\t // Step 3: Commit the file's inode to the store.\n\t var fileInode = new Inode(dataId, data.length, mode | type, currTime, currTime, currTime);\n\t this$1.addNewNode(tx, fileInode.toBuffer(), function (e, fileInodeId) {\n\t if (noErrorTx(e, tx, cb)) {\n\t // Step 4: Update parent directory's listing.\n\t dirListing[fname] = fileInodeId;\n\t tx.put(parentNode.id, Buffer.from(JSON.stringify(dirListing)), true, function (e) {\n\t if (noErrorTx(e, tx, cb)) {\n\t // Step 5: Commit and return the new inode.\n\t tx.commit(function (e) {\n\t if (noErrorTx(e, tx, cb)) {\n\t cb(null, fileInode);\n\t }\n\t });\n\t }\n\t });\n\t }\n\t });\n\t }\n\t });\n\t }\n\t }\n\t });\n\t };\n\t /**\n\t * Remove all traces of the given path from the file system.\n\t * @param p The path to remove from the file system.\n\t * @param isDir Does the path belong to a directory, or a file?\n\t * @todo Update mtime.\n\t */\n\t AsyncKeyValueFileSystem.prototype.removeEntry = function removeEntry (p, isDir, cb) {\n\t var this$1 = this;\n\t\n\t var tx = this.store.beginTransaction('readwrite'), parent = path.dirname(p), fileName = path.basename(p);\n\t // Step 1: Get parent directory's node and directory listing.\n\t this.findINodeAndDirListing(tx, parent, function (e, parentNode, parentListing) {\n\t if (noErrorTx(e, tx, cb)) {\n\t if (!parentListing[fileName]) {\n\t tx.abort(function () {\n\t cb(ApiError.ENOENT(p));\n\t });\n\t }\n\t else {\n\t // Remove from directory listing of parent.\n\t var fileNodeId = parentListing[fileName];\n\t delete parentListing[fileName];\n\t // Step 2: Get file inode.\n\t this$1.getINode(tx, p, fileNodeId, function (e, fileNode) {\n\t if (noErrorTx(e, tx, cb)) {\n\t if (!isDir && fileNode.isDirectory()) {\n\t tx.abort(function () {\n\t cb(ApiError.EISDIR(p));\n\t });\n\t }\n\t else if (isDir && !fileNode.isDirectory()) {\n\t tx.abort(function () {\n\t cb(ApiError.ENOTDIR(p));\n\t });\n\t }\n\t else {\n\t // Step 3: Delete data.\n\t tx.del(fileNode.id, function (e) {\n\t if (noErrorTx(e, tx, cb)) {\n\t // Step 4: Delete node.\n\t tx.del(fileNodeId, function (e) {\n\t if (noErrorTx(e, tx, cb)) {\n\t // Step 5: Update directory listing.\n\t tx.put(parentNode.id, Buffer.from(JSON.stringify(parentListing)), true, function (e) {\n\t if (noErrorTx(e, tx, cb)) {\n\t tx.commit(cb);\n\t }\n\t });\n\t }\n\t });\n\t }\n\t });\n\t }\n\t }\n\t });\n\t }\n\t }\n\t });\n\t };\n\t\n\t return AsyncKeyValueFileSystem;\n\t}(BaseFileSystem));\n\t\n\t/**\n\t * A simple in-memory key-value store backed by a JavaScript object.\n\t */\n\tvar InMemoryStore = function InMemoryStore() {\n\t this.store = {};\n\t};\n\tInMemoryStore.prototype.name = function name () { return InMemoryFileSystem.Name; };\n\tInMemoryStore.prototype.clear = function clear () { this.store = {}; };\n\tInMemoryStore.prototype.beginTransaction = function beginTransaction (type) {\n\t return new SimpleSyncRWTransaction(this);\n\t};\n\tInMemoryStore.prototype.get = function get (key) {\n\t return this.store[key];\n\t};\n\tInMemoryStore.prototype.put = function put (key, data, overwrite) {\n\t if (!overwrite && this.store.hasOwnProperty(key)) {\n\t return false;\n\t }\n\t this.store[key] = data;\n\t return true;\n\t};\n\tInMemoryStore.prototype.del = function del (key) {\n\t delete this.store[key];\n\t};\n\t/**\n\t * A simple in-memory file system backed by an InMemoryStore.\n\t * Files are not persisted across page loads.\n\t */\n\tvar InMemoryFileSystem = (function (SyncKeyValueFileSystem$$1) {\n\t function InMemoryFileSystem() {\n\t SyncKeyValueFileSystem$$1.call(this, { store: new InMemoryStore() });\n\t }\n\t\n\t if ( SyncKeyValueFileSystem$$1 ) InMemoryFileSystem.__proto__ = SyncKeyValueFileSystem$$1;\n\t InMemoryFileSystem.prototype = Object.create( SyncKeyValueFileSystem$$1 && SyncKeyValueFileSystem$$1.prototype );\n\t InMemoryFileSystem.prototype.constructor = InMemoryFileSystem;\n\t /**\n\t * Creates an InMemoryFileSystem instance.\n\t */\n\t InMemoryFileSystem.Create = function Create (options, cb) {\n\t cb(null, new InMemoryFileSystem());\n\t };\n\t\n\t return InMemoryFileSystem;\n\t}(SyncKeyValueFileSystem));\n\t\n\tInMemoryFileSystem.Name = \"InMemory\";\n\tInMemoryFileSystem.Options = {};\n\t\n\t/**\n\t * Get the indexedDB constructor for the current browser.\n\t * @hidden\n\t */\n\tvar indexedDB = global$1.indexedDB ||\n\t global$1.mozIndexedDB ||\n\t global$1.webkitIndexedDB ||\n\t global$1.msIndexedDB;\n\t/**\n\t * Converts a DOMException or a DOMError from an IndexedDB event into a\n\t * standardized BrowserFS API error.\n\t * @hidden\n\t */\n\tfunction convertError$2(e, message) {\n\t if ( message === void 0 ) message = e.toString();\n\t\n\t switch (e.name) {\n\t case \"NotFoundError\":\n\t return new ApiError(ErrorCode.ENOENT, message);\n\t case \"QuotaExceededError\":\n\t return new ApiError(ErrorCode.ENOSPC, message);\n\t default:\n\t // The rest do not seem to map cleanly to standard error codes.\n\t return new ApiError(ErrorCode.EIO, message);\n\t }\n\t}\n\t/**\n\t * Produces a new onerror handler for IDB. Our errors are always fatal, so we\n\t * handle them generically: Call the user-supplied callback with a translated\n\t * version of the error, and let the error bubble up.\n\t * @hidden\n\t */\n\tfunction onErrorHandler(cb, code, message) {\n\t if ( code === void 0 ) code = ErrorCode.EIO;\n\t if ( message === void 0 ) message = null;\n\t\n\t return function (e) {\n\t // Prevent the error from canceling the transaction.\n\t e.preventDefault();\n\t cb(new ApiError(code, message !== null ? message : undefined));\n\t };\n\t}\n\t/**\n\t * @hidden\n\t */\n\tvar IndexedDBROTransaction = function IndexedDBROTransaction(tx, store) {\n\t this.tx = tx;\n\t this.store = store;\n\t};\n\tIndexedDBROTransaction.prototype.get = function get (key, cb) {\n\t try {\n\t var r = this.store.get(key);\n\t r.onerror = onErrorHandler(cb);\n\t r.onsuccess = function (event) {\n\t // IDB returns the value 'undefined' when you try to get keys that\n\t // don't exist. The caller expects this behavior.\n\t var result = event.target.result;\n\t if (result === undefined) {\n\t cb(null, result);\n\t }\n\t else {\n\t // IDB data is stored as an ArrayBuffer\n\t cb(null, arrayBuffer2Buffer(result));\n\t }\n\t };\n\t }\n\t catch (e) {\n\t cb(convertError$2(e));\n\t }\n\t};\n\t/**\n\t * @hidden\n\t */\n\tvar IndexedDBRWTransaction = (function (IndexedDBROTransaction) {\n\t function IndexedDBRWTransaction(tx, store) {\n\t IndexedDBROTransaction.call(this, tx, store);\n\t }\n\t\n\t if ( IndexedDBROTransaction ) IndexedDBRWTransaction.__proto__ = IndexedDBROTransaction;\n\t IndexedDBRWTransaction.prototype = Object.create( IndexedDBROTransaction && IndexedDBROTransaction.prototype );\n\t IndexedDBRWTransaction.prototype.constructor = IndexedDBRWTransaction;\n\t IndexedDBRWTransaction.prototype.put = function put (key, data, overwrite, cb) {\n\t try {\n\t var arraybuffer = buffer2ArrayBuffer(data);\n\t var r;\n\t if (overwrite) {\n\t r = this.store.put(arraybuffer, key);\n\t }\n\t else {\n\t // 'add' will never overwrite an existing key.\n\t r = this.store.add(arraybuffer, key);\n\t }\n\t // XXX: NEED TO RETURN FALSE WHEN ADD HAS A KEY CONFLICT. NO ERROR.\n\t r.onerror = onErrorHandler(cb);\n\t r.onsuccess = function (event) {\n\t cb(null, true);\n\t };\n\t }\n\t catch (e) {\n\t cb(convertError$2(e));\n\t }\n\t };\n\t IndexedDBRWTransaction.prototype.del = function del (key, cb) {\n\t try {\n\t // NOTE: IE8 has a bug with identifiers named 'delete' unless used as a string\n\t // like this.\n\t // http://stackoverflow.com/a/26479152\n\t var r = this.store['delete'](key);\n\t r.onerror = onErrorHandler(cb);\n\t r.onsuccess = function (event) {\n\t cb();\n\t };\n\t }\n\t catch (e) {\n\t cb(convertError$2(e));\n\t }\n\t };\n\t IndexedDBRWTransaction.prototype.commit = function commit (cb) {\n\t // Return to the event loop to commit the transaction.\n\t setTimeout(cb, 0);\n\t };\n\t IndexedDBRWTransaction.prototype.abort = function abort (cb) {\n\t var _e = null;\n\t try {\n\t this.tx.abort();\n\t }\n\t catch (e) {\n\t _e = convertError$2(e);\n\t }\n\t finally {\n\t cb(_e);\n\t }\n\t };\n\t\n\t return IndexedDBRWTransaction;\n\t}(IndexedDBROTransaction));\n\tvar IndexedDBStore = function IndexedDBStore(cb, storeName) {\n\t var this$1 = this;\n\t if ( storeName === void 0 ) storeName = 'browserfs';\n\t\n\t this.storeName = storeName;\n\t var openReq = indexedDB.open(this.storeName, 1);\n\t openReq.onupgradeneeded = function (event) {\n\t var db = event.target.result;\n\t // Huh. This should never happen; we're at version 1. Why does another\n\t // database exist?\n\t if (db.objectStoreNames.contains(this$1.storeName)) {\n\t db.deleteObjectStore(this$1.storeName);\n\t }\n\t db.createObjectStore(this$1.storeName);\n\t };\n\t openReq.onsuccess = function (event) {\n\t this$1.db = event.target.result;\n\t cb(null, this$1);\n\t };\n\t openReq.onerror = onErrorHandler(cb, ErrorCode.EACCES);\n\t};\n\tIndexedDBStore.prototype.name = function name () {\n\t return IndexedDBFileSystem.Name + \" - \" + this.storeName;\n\t};\n\tIndexedDBStore.prototype.clear = function clear (cb) {\n\t try {\n\t var tx = this.db.transaction(this.storeName, 'readwrite'), objectStore = tx.objectStore(this.storeName), r = objectStore.clear();\n\t r.onsuccess = function (event) {\n\t // Use setTimeout to commit transaction.\n\t setTimeout(cb, 0);\n\t };\n\t r.onerror = onErrorHandler(cb);\n\t }\n\t catch (e) {\n\t cb(convertError$2(e));\n\t }\n\t};\n\tIndexedDBStore.prototype.beginTransaction = function beginTransaction (type) {\n\t if ( type === void 0 ) type = 'readonly';\n\t\n\t var tx = this.db.transaction(this.storeName, type), objectStore = tx.objectStore(this.storeName);\n\t if (type === 'readwrite') {\n\t return new IndexedDBRWTransaction(tx, objectStore);\n\t }\n\t else if (type === 'readonly') {\n\t return new IndexedDBROTransaction(tx, objectStore);\n\t }\n\t else {\n\t throw new ApiError(ErrorCode.EINVAL, 'Invalid transaction type.');\n\t }\n\t};\n\t/**\n\t * A file system that uses the IndexedDB key value file system.\n\t */\n\tvar IndexedDBFileSystem = (function (AsyncKeyValueFileSystem$$1) {\n\t function IndexedDBFileSystem(cb, storeName, deprecateMsg) {\n\t var this$1 = this;\n\t if ( deprecateMsg === void 0 ) deprecateMsg = true;\n\t\n\t AsyncKeyValueFileSystem$$1.call(this);\n\t this.store = new IndexedDBStore(function (e) {\n\t if (e) {\n\t cb(e);\n\t }\n\t else {\n\t this$1.init(this$1.store, function (e) {\n\t cb(e, this$1);\n\t });\n\t }\n\t }, storeName);\n\t deprecationMessage(deprecateMsg, IndexedDBFileSystem.Name, { storeName: storeName });\n\t }\n\t\n\t if ( AsyncKeyValueFileSystem$$1 ) IndexedDBFileSystem.__proto__ = AsyncKeyValueFileSystem$$1;\n\t IndexedDBFileSystem.prototype = Object.create( AsyncKeyValueFileSystem$$1 && AsyncKeyValueFileSystem$$1.prototype );\n\t IndexedDBFileSystem.prototype.constructor = IndexedDBFileSystem;\n\t /**\n\t * Constructs an IndexedDB file system with the given options.\n\t */\n\t IndexedDBFileSystem.Create = function Create (opts, cb) {\n\t // tslint:disable-next-line:no-unused-new\n\t new IndexedDBFileSystem(cb, opts.storeName, false);\n\t // tslint:enable-next-line:no-unused-new\n\t };\n\t IndexedDBFileSystem.isAvailable = function isAvailable () {\n\t // In Safari's private browsing mode, indexedDB.open returns NULL.\n\t // In Firefox, it throws an exception.\n\t // In Chrome, it \"just works\", and clears the database when you leave the page.\n\t // Untested: Opera, IE.\n\t try {\n\t return typeof indexedDB !== 'undefined' && null !== indexedDB.open(\"__browserfs_test__\");\n\t }\n\t catch (e) {\n\t return false;\n\t }\n\t };\n\t\n\t return IndexedDBFileSystem;\n\t}(AsyncKeyValueFileSystem));\n\t\n\tIndexedDBFileSystem.Name = \"IndexedDB\";\n\tIndexedDBFileSystem.Options = {\n\t storeName: {\n\t type: \"string\",\n\t optional: true,\n\t description: \"The name of this file system. You can have multiple IndexedDB file systems operating at once, but each must have a different name.\"\n\t }\n\t};\n\t\n\t/**\n\t * Some versions of FF and all versions of IE do not support the full range of\n\t * 16-bit numbers encoded as characters, as they enforce UTF-16 restrictions.\n\t * @url http://stackoverflow.com/questions/11170716/are-there-any-characters-that-are-not-allowed-in-localstorage/11173673#11173673\n\t * @hidden\n\t */\n\tvar supportsBinaryString = false;\n\tvar binaryEncoding;\n\ttry {\n\t global$1.localStorage.setItem(\"__test__\", String.fromCharCode(0xD800));\n\t supportsBinaryString = global$1.localStorage.getItem(\"__test__\") === String.fromCharCode(0xD800);\n\t}\n\tcatch (e) {\n\t // IE throws an exception.\n\t supportsBinaryString = false;\n\t}\n\tbinaryEncoding = supportsBinaryString ? 'binary_string' : 'binary_string_ie';\n\tif (!Buffer.isEncoding(binaryEncoding)) {\n\t // Fallback for non BrowserFS implementations of buffer that lack a\n\t // binary_string format.\n\t binaryEncoding = \"base64\";\n\t}\n\t/**\n\t * A synchronous key-value store backed by localStorage.\n\t */\n\tvar LocalStorageStore = function LocalStorageStore () {};\n\t\n\tLocalStorageStore.prototype.name = function name () {\n\t return LocalStorageFileSystem.Name;\n\t};\n\tLocalStorageStore.prototype.clear = function clear () {\n\t global$1.localStorage.clear();\n\t};\n\tLocalStorageStore.prototype.beginTransaction = function beginTransaction (type) {\n\t // No need to differentiate.\n\t return new SimpleSyncRWTransaction(this);\n\t};\n\tLocalStorageStore.prototype.get = function get (key) {\n\t try {\n\t var data = global$1.localStorage.getItem(key);\n\t if (data !== null) {\n\t return Buffer.from(data, binaryEncoding);\n\t }\n\t }\n\t catch (e) {\n\t // Do nothing.\n\t }\n\t // Key doesn't exist, or a failure occurred.\n\t return undefined;\n\t};\n\tLocalStorageStore.prototype.put = function put (key, data, overwrite) {\n\t try {\n\t if (!overwrite && global$1.localStorage.getItem(key) !== null) {\n\t // Don't want to overwrite the key!\n\t return false;\n\t }\n\t global$1.localStorage.setItem(key, data.toString(binaryEncoding));\n\t return true;\n\t }\n\t catch (e) {\n\t throw new ApiError(ErrorCode.ENOSPC, \"LocalStorage is full.\");\n\t }\n\t};\n\tLocalStorageStore.prototype.del = function del (key) {\n\t try {\n\t global$1.localStorage.removeItem(key);\n\t }\n\t catch (e) {\n\t throw new ApiError(ErrorCode.EIO, \"Unable to delete key \" + key + \": \" + e);\n\t }\n\t};\n\t/**\n\t * A synchronous file system backed by localStorage. Connects our\n\t * LocalStorageStore to our SyncKeyValueFileSystem.\n\t */\n\tvar LocalStorageFileSystem = (function (SyncKeyValueFileSystem$$1) {\n\t function LocalStorageFileSystem() { SyncKeyValueFileSystem$$1.call(this, { store: new LocalStorageStore() }); }\n\t\n\t if ( SyncKeyValueFileSystem$$1 ) LocalStorageFileSystem.__proto__ = SyncKeyValueFileSystem$$1;\n\t LocalStorageFileSystem.prototype = Object.create( SyncKeyValueFileSystem$$1 && SyncKeyValueFileSystem$$1.prototype );\n\t LocalStorageFileSystem.prototype.constructor = LocalStorageFileSystem;\n\t /**\n\t * Creates a LocalStorageFileSystem instance.\n\t */\n\t LocalStorageFileSystem.Create = function Create (options, cb) {\n\t cb(null, new LocalStorageFileSystem());\n\t };\n\t LocalStorageFileSystem.isAvailable = function isAvailable () {\n\t return typeof global$1.localStorage !== 'undefined';\n\t };\n\t\n\t return LocalStorageFileSystem;\n\t}(SyncKeyValueFileSystem));\n\t\n\tLocalStorageFileSystem.Name = \"LocalStorage\";\n\tLocalStorageFileSystem.Options = {};\n\t\n\t/**\n\t * The MountableFileSystem allows you to mount multiple backend types or\n\t * multiple instantiations of the same backend into a single file system tree.\n\t * The file systems do not need to know about each other; all interactions are\n\t * automatically facilitated through this interface.\n\t *\n\t * For example, if a file system is mounted at /mnt/blah, and a request came in\n\t * for /mnt/blah/foo.txt, the file system would see a request for /foo.txt.\n\t *\n\t * You can mount file systems when you configure the file system:\n\t * ```javascript\n\t * BrowserFS.configure({\n\t * fs: \"MountableFileSystem\",\n\t * options: {\n\t * '/data': { fs: 'XmlHttpRequest', options: { index: \"http://mysite.com/files/index.json\" } },\n\t * '/home': { fs: 'LocalStorage' }\n\t * }\n\t * }, function(e) {\n\t *\n\t * });\n\t * ```\n\t *\n\t * For advanced users, you can also mount file systems *after* MFS is constructed:\n\t * ```javascript\n\t * BrowserFS.FileSystem.XmlHttpRequest.Create({\n\t * index: \"http://mysite.com/files/index.json\"\n\t * }, function(e, xhrfs) {\n\t * BrowserFS.FileSystem.MountableFileSystem.Create({\n\t * '/data': xhrfs\n\t * }, function(e, mfs) {\n\t * BrowserFS.initialize(mfs);\n\t *\n\t * // Added after-the-fact...\n\t * BrowserFS.FileSystem.LocalStorage.Create(function(e, lsfs) {\n\t * mfs.mount('/home', lsfs);\n\t * });\n\t * });\n\t * });\n\t * ```\n\t *\n\t * Since MountableFileSystem simply proxies requests to mounted file systems, it supports all of the operations that the mounted file systems support.\n\t *\n\t * With no mounted file systems, `MountableFileSystem` acts as a simple `InMemory` filesystem.\n\t */\n\tvar MountableFileSystem = (function (BaseFileSystem$$1) {\n\t function MountableFileSystem() {\n\t BaseFileSystem$$1.call(this);\n\t // Contains the list of mount points in mntMap, sorted by string length in decreasing order.\n\t // Ensures that we scan the most specific mount points for a match first, which lets us\n\t // nest mount points.\n\t this.mountList = [];\n\t this.mntMap = {};\n\t // The InMemory file system serves purely to provide directory listings for\n\t // mounted file systems.\n\t this.rootFs = new InMemoryFileSystem();\n\t }\n\t\n\t if ( BaseFileSystem$$1 ) MountableFileSystem.__proto__ = BaseFileSystem$$1;\n\t MountableFileSystem.prototype = Object.create( BaseFileSystem$$1 && BaseFileSystem$$1.prototype );\n\t MountableFileSystem.prototype.constructor = MountableFileSystem;\n\t /**\n\t * Creates a MountableFileSystem instance with the given options.\n\t */\n\t MountableFileSystem.Create = function Create (opts, cb) {\n\t var fs = new MountableFileSystem();\n\t Object.keys(opts).forEach(function (mountPoint) {\n\t fs.mount(mountPoint, opts[mountPoint]);\n\t });\n\t cb(null, fs);\n\t };\n\t MountableFileSystem.isAvailable = function isAvailable () {\n\t return true;\n\t };\n\t /**\n\t * Mounts the file system at the given mount point.\n\t */\n\t MountableFileSystem.prototype.mount = function mount (mountPoint, fs) {\n\t if (mountPoint[0] !== '/') {\n\t mountPoint = \"/\" + mountPoint;\n\t }\n\t mountPoint = path.resolve(mountPoint);\n\t if (this.mntMap[mountPoint]) {\n\t throw new ApiError(ErrorCode.EINVAL, \"Mount point \" + mountPoint + \" is already taken.\");\n\t }\n\t mkdirpSync(mountPoint, 0x1ff, this.rootFs);\n\t this.mntMap[mountPoint] = fs;\n\t this.mountList.push(mountPoint);\n\t this.mountList = this.mountList.sort(function (a, b) { return b.length - a.length; });\n\t };\n\t MountableFileSystem.prototype.umount = function umount (mountPoint) {\n\t var this$1 = this;\n\t\n\t if (mountPoint[0] !== '/') {\n\t mountPoint = \"/\" + mountPoint;\n\t }\n\t mountPoint = path.resolve(mountPoint);\n\t if (!this.mntMap[mountPoint]) {\n\t throw new ApiError(ErrorCode.EINVAL, \"Mount point \" + mountPoint + \" is already unmounted.\");\n\t }\n\t delete this.mntMap[mountPoint];\n\t this.mountList.splice(this.mountList.indexOf(mountPoint), 1);\n\t while (mountPoint !== '/') {\n\t if (this$1.rootFs.readdirSync(mountPoint).length === 0) {\n\t this$1.rootFs.rmdirSync(mountPoint);\n\t mountPoint = path.dirname(mountPoint);\n\t }\n\t else {\n\t break;\n\t }\n\t }\n\t };\n\t /**\n\t * Returns the file system that the path points to.\n\t */\n\t MountableFileSystem.prototype._getFs = function _getFs (path$$1) {\n\t var this$1 = this;\n\t\n\t var mountList = this.mountList, len = mountList.length;\n\t for (var i = 0; i < len; i++) {\n\t var mountPoint = mountList[i];\n\t // We know path is normalized, so it is a substring of the mount point.\n\t if (mountPoint.length <= path$$1.length && path$$1.indexOf(mountPoint) === 0) {\n\t path$$1 = path$$1.substr(mountPoint.length > 1 ? mountPoint.length : 0);\n\t if (path$$1 === '') {\n\t path$$1 = '/';\n\t }\n\t return { fs: this$1.mntMap[mountPoint], path: path$$1 };\n\t }\n\t }\n\t // Query our root file system.\n\t return { fs: this.rootFs, path: path$$1 };\n\t };\n\t // Global information methods\n\t MountableFileSystem.prototype.getName = function getName () {\n\t return MountableFileSystem.Name;\n\t };\n\t MountableFileSystem.prototype.diskSpace = function diskSpace (path$$1, cb) {\n\t cb(0, 0);\n\t };\n\t MountableFileSystem.prototype.isReadOnly = function isReadOnly () {\n\t return false;\n\t };\n\t MountableFileSystem.prototype.supportsLinks = function supportsLinks () {\n\t // I'm not ready for cross-FS links yet.\n\t return false;\n\t };\n\t MountableFileSystem.prototype.supportsProps = function supportsProps () {\n\t return false;\n\t };\n\t MountableFileSystem.prototype.supportsSynch = function supportsSynch () {\n\t return true;\n\t };\n\t /**\n\t * Fixes up error messages so they mention the mounted file location relative\n\t * to the MFS root, not to the particular FS's root.\n\t * Mutates the input error, and returns it.\n\t */\n\t MountableFileSystem.prototype.standardizeError = function standardizeError (err, path$$1, realPath) {\n\t var index = err.message.indexOf(path$$1);\n\t if (index !== -1) {\n\t err.message = err.message.substr(0, index) + realPath + err.message.substr(index + path$$1.length);\n\t err.path = realPath;\n\t }\n\t return err;\n\t };\n\t // The following methods involve multiple file systems, and thus have custom\n\t // logic.\n\t // Note that we go through the Node API to use its robust default argument\n\t // processing.\n\t MountableFileSystem.prototype.rename = function rename (oldPath, newPath, cb) {\n\t var this$1 = this;\n\t\n\t // Scenario 1: old and new are on same FS.\n\t var fs1rv = this._getFs(oldPath);\n\t var fs2rv = this._getFs(newPath);\n\t if (fs1rv.fs === fs2rv.fs) {\n\t return fs1rv.fs.rename(fs1rv.path, fs2rv.path, function (e) {\n\t if (e) {\n\t this$1.standardizeError(this$1.standardizeError(e, fs1rv.path, oldPath), fs2rv.path, newPath);\n\t }\n\t cb(e);\n\t });\n\t }\n\t // Scenario 2: Different file systems.\n\t // Read old file, write new file, delete old file.\n\t return _fsMock.readFile(oldPath, function (err, data) {\n\t if (err) {\n\t return cb(err);\n\t }\n\t _fsMock.writeFile(newPath, data, function (err) {\n\t if (err) {\n\t return cb(err);\n\t }\n\t _fsMock.unlink(oldPath, cb);\n\t });\n\t });\n\t };\n\t MountableFileSystem.prototype.renameSync = function renameSync (oldPath, newPath) {\n\t // Scenario 1: old and new are on same FS.\n\t var fs1rv = this._getFs(oldPath);\n\t var fs2rv = this._getFs(newPath);\n\t if (fs1rv.fs === fs2rv.fs) {\n\t try {\n\t return fs1rv.fs.renameSync(fs1rv.path, fs2rv.path);\n\t }\n\t catch (e) {\n\t this.standardizeError(this.standardizeError(e, fs1rv.path, oldPath), fs2rv.path, newPath);\n\t throw e;\n\t }\n\t }\n\t // Scenario 2: Different file systems.\n\t var data = _fsMock.readFileSync(oldPath);\n\t _fsMock.writeFileSync(newPath, data);\n\t return _fsMock.unlinkSync(oldPath);\n\t };\n\t MountableFileSystem.prototype.readdirSync = function readdirSync (p) {\n\t var fsInfo = this._getFs(p);\n\t // If null, rootfs did not have the directory\n\t // (or the target FS is the root fs).\n\t var rv = null;\n\t // Mount points are all defined in the root FS.\n\t // Ensure that we list those, too.\n\t if (fsInfo.fs !== this.rootFs) {\n\t try {\n\t rv = this.rootFs.readdirSync(p);\n\t }\n\t catch (e) {\n\t // Ignore.\n\t }\n\t }\n\t try {\n\t var rv2 = fsInfo.fs.readdirSync(fsInfo.path);\n\t if (rv === null) {\n\t return rv2;\n\t }\n\t else {\n\t // Filter out duplicates.\n\t return rv2.concat(rv.filter(function (val) { return rv2.indexOf(val) === -1; }));\n\t }\n\t }\n\t catch (e) {\n\t if (rv === null) {\n\t throw this.standardizeError(e, fsInfo.path, p);\n\t }\n\t else {\n\t // The root FS had something.\n\t return rv;\n\t }\n\t }\n\t };\n\t MountableFileSystem.prototype.readdir = function readdir (p, cb) {\n\t var this$1 = this;\n\t\n\t var fsInfo = this._getFs(p);\n\t fsInfo.fs.readdir(fsInfo.path, function (err, files) {\n\t if (fsInfo.fs !== this$1.rootFs) {\n\t try {\n\t var rv = this$1.rootFs.readdirSync(p);\n\t if (files) {\n\t // Filter out duplicates.\n\t files = files.concat(rv.filter(function (val) { return files.indexOf(val) === -1; }));\n\t }\n\t else {\n\t files = rv;\n\t }\n\t }\n\t catch (e) {\n\t // Root FS and target FS did not have directory.\n\t if (err) {\n\t return cb(this$1.standardizeError(err, fsInfo.path, p));\n\t }\n\t }\n\t }\n\t else if (err) {\n\t // Root FS and target FS are the same, and did not have directory.\n\t return cb(this$1.standardizeError(err, fsInfo.path, p));\n\t }\n\t cb(null, files);\n\t });\n\t };\n\t MountableFileSystem.prototype.rmdirSync = function rmdirSync (p) {\n\t var fsInfo = this._getFs(p);\n\t if (this._containsMountPt(p)) {\n\t throw ApiError.ENOTEMPTY(p);\n\t }\n\t else {\n\t try {\n\t fsInfo.fs.rmdirSync(fsInfo.path);\n\t }\n\t catch (e) {\n\t throw this.standardizeError(e, fsInfo.path, p);\n\t }\n\t }\n\t };\n\t MountableFileSystem.prototype.rmdir = function rmdir (p, cb) {\n\t var this$1 = this;\n\t\n\t var fsInfo = this._getFs(p);\n\t if (this._containsMountPt(p)) {\n\t cb(ApiError.ENOTEMPTY(p));\n\t }\n\t else {\n\t fsInfo.fs.rmdir(fsInfo.path, function (err) {\n\t cb(err ? this$1.standardizeError(err, fsInfo.path, p) : null);\n\t });\n\t }\n\t };\n\t /**\n\t * Returns true if the given path contains a mount point.\n\t */\n\t MountableFileSystem.prototype._containsMountPt = function _containsMountPt (p) {\n\t var mountPoints = this.mountList, len = mountPoints.length;\n\t for (var i = 0; i < len; i++) {\n\t var pt = mountPoints[i];\n\t if (pt.length >= p.length && pt.slice(0, p.length) === p) {\n\t return true;\n\t }\n\t }\n\t return false;\n\t };\n\t\n\t return MountableFileSystem;\n\t}(BaseFileSystem));\n\t\n\tMountableFileSystem.Name = \"MountableFileSystem\";\n\tMountableFileSystem.Options = {};\n\t/**\n\t * Tricky: Define all of the functions that merely forward arguments to the\n\t * relevant file system, or return/throw an error.\n\t * Take advantage of the fact that the *first* argument is always the path, and\n\t * the *last* is the callback function (if async).\n\t * @todo Can use numArgs to make proxying more efficient.\n\t * @hidden\n\t */\n\tfunction defineFcn(name, isSync, numArgs) {\n\t if (isSync) {\n\t return function () {\n\t var args = [], len = arguments.length;\n\t while ( len-- ) args[ len ] = arguments[ len ];\n\t\n\t var path$$1 = args[0];\n\t var rv = this._getFs(path$$1);\n\t args[0] = rv.path;\n\t try {\n\t return rv.fs[name].apply(rv.fs, args);\n\t }\n\t catch (e) {\n\t this.standardizeError(e, rv.path, path$$1);\n\t throw e;\n\t }\n\t };\n\t }\n\t else {\n\t return function () {\n\t var this$1 = this;\n\t var args = [], len = arguments.length;\n\t while ( len-- ) args[ len ] = arguments[ len ];\n\t\n\t var path$$1 = args[0];\n\t var rv = this._getFs(path$$1);\n\t args[0] = rv.path;\n\t if (typeof args[args.length - 1] === 'function') {\n\t var cb = args[args.length - 1];\n\t args[args.length - 1] = function () {\n\t var args = [], len = arguments.length;\n\t while ( len-- ) args[ len ] = arguments[ len ];\n\t\n\t if (args.length > 0 && args[0] instanceof ApiError) {\n\t this$1.standardizeError(args[0], rv.path, path$$1);\n\t }\n\t cb.apply(null, args);\n\t };\n\t }\n\t return rv.fs[name].apply(rv.fs, args);\n\t };\n\t }\n\t}\n\t/**\n\t * @hidden\n\t */\n\tvar fsCmdMap = [\n\t // 1 arg functions\n\t ['exists', 'unlink', 'readlink'],\n\t // 2 arg functions\n\t ['stat', 'mkdir', 'realpath', 'truncate'],\n\t // 3 arg functions\n\t ['open', 'readFile', 'chmod', 'utimes'],\n\t // 4 arg functions\n\t ['chown'],\n\t // 5 arg functions\n\t ['writeFile', 'appendFile']\n\t];\n\tfor (var i = 0; i < fsCmdMap.length; i++) {\n\t var cmds = fsCmdMap[i];\n\t for (var i$1 = 0, list = cmds; i$1 < list.length; i$1 += 1) {\n\t var fnName = list[i$1];\n\t\n\t MountableFileSystem.prototype[fnName] = defineFcn(fnName, false, i + 1);\n\t MountableFileSystem.prototype[fnName + 'Sync'] = defineFcn(fnName + 'Sync', true, i + 1);\n\t }\n\t}\n\t\n\t/**\n\t * @hidden\n\t */\n\tvar bfsSetImmediate;\n\tif (typeof (setImmediate) !== \"undefined\") {\n\t bfsSetImmediate = setImmediate;\n\t}\n\telse {\n\t var gScope = global$1;\n\t var timeouts = [];\n\t var messageName = \"zero-timeout-message\";\n\t var canUsePostMessage = function () {\n\t if (typeof gScope.importScripts !== 'undefined' || !gScope.postMessage) {\n\t return false;\n\t }\n\t var postMessageIsAsync = true;\n\t var oldOnMessage = gScope.onmessage;\n\t gScope.onmessage = function () {\n\t postMessageIsAsync = false;\n\t };\n\t gScope.postMessage('', '*');\n\t gScope.onmessage = oldOnMessage;\n\t return postMessageIsAsync;\n\t };\n\t if (canUsePostMessage()) {\n\t bfsSetImmediate = function (fn) {\n\t timeouts.push(fn);\n\t gScope.postMessage(messageName, \"*\");\n\t };\n\t var handleMessage = function (event) {\n\t if (event.source === self && event.data === messageName) {\n\t if (event.stopPropagation) {\n\t event.stopPropagation();\n\t }\n\t else {\n\t event.cancelBubble = true;\n\t }\n\t if (timeouts.length > 0) {\n\t var fn = timeouts.shift();\n\t return fn();\n\t }\n\t }\n\t };\n\t if (gScope.addEventListener) {\n\t gScope.addEventListener('message', handleMessage, true);\n\t }\n\t else {\n\t gScope.attachEvent('onmessage', handleMessage);\n\t }\n\t }\n\t else if (gScope.MessageChannel) {\n\t // WebWorker MessageChannel\n\t var channel = new gScope.MessageChannel();\n\t channel.port1.onmessage = function (event) {\n\t if (timeouts.length > 0) {\n\t return timeouts.shift()();\n\t }\n\t };\n\t bfsSetImmediate = function (fn) {\n\t timeouts.push(fn);\n\t channel.port2.postMessage('');\n\t };\n\t }\n\t else {\n\t bfsSetImmediate = function (fn) {\n\t return setTimeout(fn, 0);\n\t };\n\t }\n\t}\n\tvar setImmediate$3 = bfsSetImmediate;\n\t\n\t/**\n\t * Non-recursive mutex\n\t * @hidden\n\t */\n\tvar Mutex = function Mutex() {\n\t this._locked = false;\n\t this._waiters = [];\n\t};\n\tMutex.prototype.lock = function lock (cb) {\n\t if (this._locked) {\n\t this._waiters.push(cb);\n\t return;\n\t }\n\t this._locked = true;\n\t cb();\n\t};\n\tMutex.prototype.unlock = function unlock () {\n\t if (!this._locked) {\n\t throw new Error('unlock of a non-locked mutex');\n\t }\n\t var next = this._waiters.shift();\n\t // don't unlock - we want to queue up next for the\n\t // _end_ of the current task execution, but we don't\n\t // want it to be called inline with whatever the\n\t // current stack is. This way we still get the nice\n\t // behavior that an unlock immediately followed by a\n\t // lock won't cause starvation.\n\t if (next) {\n\t setImmediate$3(next);\n\t return;\n\t }\n\t this._locked = false;\n\t};\n\tMutex.prototype.tryLock = function tryLock () {\n\t if (this._locked) {\n\t return false;\n\t }\n\t this._locked = true;\n\t return true;\n\t};\n\tMutex.prototype.isLocked = function isLocked () {\n\t return this._locked;\n\t};\n\t\n\t/**\n\t * This class serializes access to an underlying async filesystem.\n\t * For example, on an OverlayFS instance with an async lower\n\t * directory operations like rename and rmdir may involve multiple\n\t * requests involving both the upper and lower filesystems -- they\n\t * are not executed in a single atomic step. OverlayFS uses this\n\t * LockedFS to avoid having to reason about the correctness of\n\t * multiple requests interleaving.\n\t */\n\tvar LockedFS = function LockedFS(fs) {\n\t this._fs = fs;\n\t this._mu = new Mutex();\n\t};\n\tLockedFS.prototype.getName = function getName () {\n\t return 'LockedFS<' + this._fs.getName() + '>';\n\t};\n\tLockedFS.prototype.getFSUnlocked = function getFSUnlocked () {\n\t return this._fs;\n\t};\n\tLockedFS.prototype.initialize = function initialize (cb) {\n\t // FIXME: check to see if FS supports initialization\n\t this._fs.initialize(cb);\n\t};\n\tLockedFS.prototype.diskSpace = function diskSpace (p, cb) {\n\t // FIXME: should this lock?\n\t this._fs.diskSpace(p, cb);\n\t};\n\tLockedFS.prototype.isReadOnly = function isReadOnly () {\n\t return this._fs.isReadOnly();\n\t};\n\tLockedFS.prototype.supportsLinks = function supportsLinks () {\n\t return this._fs.supportsLinks();\n\t};\n\tLockedFS.prototype.supportsProps = function supportsProps () {\n\t return this._fs.supportsProps();\n\t};\n\tLockedFS.prototype.supportsSynch = function supportsSynch () {\n\t return this._fs.supportsSynch();\n\t};\n\tLockedFS.prototype.rename = function rename (oldPath, newPath, cb) {\n\t var this$1 = this;\n\t\n\t this._mu.lock(function () {\n\t this$1._fs.rename(oldPath, newPath, function (err) {\n\t this$1._mu.unlock();\n\t cb(err);\n\t });\n\t });\n\t};\n\tLockedFS.prototype.renameSync = function renameSync (oldPath, newPath) {\n\t if (this._mu.isLocked()) {\n\t throw new Error('invalid sync call');\n\t }\n\t return this._fs.renameSync(oldPath, newPath);\n\t};\n\tLockedFS.prototype.stat = function stat (p, isLstat, cb) {\n\t var this$1 = this;\n\t\n\t this._mu.lock(function () {\n\t this$1._fs.stat(p, isLstat, function (err, stat) {\n\t this$1._mu.unlock();\n\t cb(err, stat);\n\t });\n\t });\n\t};\n\tLockedFS.prototype.statSync = function statSync (p, isLstat) {\n\t if (this._mu.isLocked()) {\n\t throw new Error('invalid sync call');\n\t }\n\t return this._fs.statSync(p, isLstat);\n\t};\n\tLockedFS.prototype.open = function open (p, flag, mode, cb) {\n\t var this$1 = this;\n\t\n\t this._mu.lock(function () {\n\t this$1._fs.open(p, flag, mode, function (err, fd) {\n\t this$1._mu.unlock();\n\t cb(err, fd);\n\t });\n\t });\n\t};\n\tLockedFS.prototype.openSync = function openSync (p, flag, mode) {\n\t if (this._mu.isLocked()) {\n\t throw new Error('invalid sync call');\n\t }\n\t return this._fs.openSync(p, flag, mode);\n\t};\n\tLockedFS.prototype.unlink = function unlink (p, cb) {\n\t var this$1 = this;\n\t\n\t this._mu.lock(function () {\n\t this$1._fs.unlink(p, function (err) {\n\t this$1._mu.unlock();\n\t cb(err);\n\t });\n\t });\n\t};\n\tLockedFS.prototype.unlinkSync = function unlinkSync (p) {\n\t if (this._mu.isLocked()) {\n\t throw new Error('invalid sync call');\n\t }\n\t return this._fs.unlinkSync(p);\n\t};\n\tLockedFS.prototype.rmdir = function rmdir (p, cb) {\n\t var this$1 = this;\n\t\n\t this._mu.lock(function () {\n\t this$1._fs.rmdir(p, function (err) {\n\t this$1._mu.unlock();\n\t cb(err);\n\t });\n\t });\n\t};\n\tLockedFS.prototype.rmdirSync = function rmdirSync (p) {\n\t if (this._mu.isLocked()) {\n\t throw new Error('invalid sync call');\n\t }\n\t return this._fs.rmdirSync(p);\n\t};\n\tLockedFS.prototype.mkdir = function mkdir (p, mode, cb) {\n\t var this$1 = this;\n\t\n\t this._mu.lock(function () {\n\t this$1._fs.mkdir(p, mode, function (err) {\n\t this$1._mu.unlock();\n\t cb(err);\n\t });\n\t });\n\t};\n\tLockedFS.prototype.mkdirSync = function mkdirSync (p, mode) {\n\t if (this._mu.isLocked()) {\n\t throw new Error('invalid sync call');\n\t }\n\t return this._fs.mkdirSync(p, mode);\n\t};\n\tLockedFS.prototype.readdir = function readdir (p, cb) {\n\t var this$1 = this;\n\t\n\t this._mu.lock(function () {\n\t this$1._fs.readdir(p, function (err, files) {\n\t this$1._mu.unlock();\n\t cb(err, files);\n\t });\n\t });\n\t};\n\tLockedFS.prototype.readdirSync = function readdirSync (p) {\n\t if (this._mu.isLocked()) {\n\t throw new Error('invalid sync call');\n\t }\n\t return this._fs.readdirSync(p);\n\t};\n\tLockedFS.prototype.exists = function exists (p, cb) {\n\t var this$1 = this;\n\t\n\t this._mu.lock(function () {\n\t this$1._fs.exists(p, function (exists) {\n\t this$1._mu.unlock();\n\t cb(exists);\n\t });\n\t });\n\t};\n\tLockedFS.prototype.existsSync = function existsSync (p) {\n\t if (this._mu.isLocked()) {\n\t throw new Error('invalid sync call');\n\t }\n\t return this._fs.existsSync(p);\n\t};\n\tLockedFS.prototype.realpath = function realpath (p, cache, cb) {\n\t var this$1 = this;\n\t\n\t this._mu.lock(function () {\n\t this$1._fs.realpath(p, cache, function (err, resolvedPath) {\n\t this$1._mu.unlock();\n\t cb(err, resolvedPath);\n\t });\n\t });\n\t};\n\tLockedFS.prototype.realpathSync = function realpathSync (p, cache) {\n\t if (this._mu.isLocked()) {\n\t throw new Error('invalid sync call');\n\t }\n\t return this._fs.realpathSync(p, cache);\n\t};\n\tLockedFS.prototype.truncate = function truncate (p, len, cb) {\n\t var this$1 = this;\n\t\n\t this._mu.lock(function () {\n\t this$1._fs.truncate(p, len, function (err) {\n\t this$1._mu.unlock();\n\t cb(err);\n\t });\n\t });\n\t};\n\tLockedFS.prototype.truncateSync = function truncateSync (p, len) {\n\t if (this._mu.isLocked()) {\n\t throw new Error('invalid sync call');\n\t }\n\t return this._fs.truncateSync(p, len);\n\t};\n\tLockedFS.prototype.readFile = function readFile (fname, encoding, flag, cb) {\n\t var this$1 = this;\n\t\n\t this._mu.lock(function () {\n\t this$1._fs.readFile(fname, encoding, flag, function (err, data) {\n\t this$1._mu.unlock();\n\t cb(err, data);\n\t });\n\t });\n\t};\n\tLockedFS.prototype.readFileSync = function readFileSync (fname, encoding, flag) {\n\t if (this._mu.isLocked()) {\n\t throw new Error('invalid sync call');\n\t }\n\t return this._fs.readFileSync(fname, encoding, flag);\n\t};\n\tLockedFS.prototype.writeFile = function writeFile (fname, data, encoding, flag, mode, cb) {\n\t var this$1 = this;\n\t\n\t this._mu.lock(function () {\n\t this$1._fs.writeFile(fname, data, encoding, flag, mode, function (err) {\n\t this$1._mu.unlock();\n\t cb(err);\n\t });\n\t });\n\t};\n\tLockedFS.prototype.writeFileSync = function writeFileSync (fname, data, encoding, flag, mode) {\n\t if (this._mu.isLocked()) {\n\t throw new Error('invalid sync call');\n\t }\n\t return this._fs.writeFileSync(fname, data, encoding, flag, mode);\n\t};\n\tLockedFS.prototype.appendFile = function appendFile (fname, data, encoding, flag, mode, cb) {\n\t var this$1 = this;\n\t\n\t this._mu.lock(function () {\n\t this$1._fs.appendFile(fname, data, encoding, flag, mode, function (err) {\n\t this$1._mu.unlock();\n\t cb(err);\n\t });\n\t });\n\t};\n\tLockedFS.prototype.appendFileSync = function appendFileSync (fname, data, encoding, flag, mode) {\n\t if (this._mu.isLocked()) {\n\t throw new Error('invalid sync call');\n\t }\n\t return this._fs.appendFileSync(fname, data, encoding, flag, mode);\n\t};\n\tLockedFS.prototype.chmod = function chmod (p, isLchmod, mode, cb) {\n\t var this$1 = this;\n\t\n\t this._mu.lock(function () {\n\t this$1._fs.chmod(p, isLchmod, mode, function (err) {\n\t this$1._mu.unlock();\n\t cb(err);\n\t });\n\t });\n\t};\n\tLockedFS.prototype.chmodSync = function chmodSync (p, isLchmod, mode) {\n\t if (this._mu.isLocked()) {\n\t throw new Error('invalid sync call');\n\t }\n\t return this._fs.chmodSync(p, isLchmod, mode);\n\t};\n\tLockedFS.prototype.chown = function chown (p, isLchown, uid, gid, cb) {\n\t var this$1 = this;\n\t\n\t this._mu.lock(function () {\n\t this$1._fs.chown(p, isLchown, uid, gid, function (err) {\n\t this$1._mu.unlock();\n\t cb(err);\n\t });\n\t });\n\t};\n\tLockedFS.prototype.chownSync = function chownSync (p, isLchown, uid, gid) {\n\t if (this._mu.isLocked()) {\n\t throw new Error('invalid sync call');\n\t }\n\t return this._fs.chownSync(p, isLchown, uid, gid);\n\t};\n\tLockedFS.prototype.utimes = function utimes (p, atime, mtime, cb) {\n\t var this$1 = this;\n\t\n\t this._mu.lock(function () {\n\t this$1._fs.utimes(p, atime, mtime, function (err) {\n\t this$1._mu.unlock();\n\t cb(err);\n\t });\n\t });\n\t};\n\tLockedFS.prototype.utimesSync = function utimesSync (p, atime, mtime) {\n\t if (this._mu.isLocked()) {\n\t throw new Error('invalid sync call');\n\t }\n\t return this._fs.utimesSync(p, atime, mtime);\n\t};\n\tLockedFS.prototype.link = function link (srcpath, dstpath, cb) {\n\t var this$1 = this;\n\t\n\t this._mu.lock(function () {\n\t this$1._fs.link(srcpath, dstpath, function (err) {\n\t this$1._mu.unlock();\n\t cb(err);\n\t });\n\t });\n\t};\n\tLockedFS.prototype.linkSync = function linkSync (srcpath, dstpath) {\n\t if (this._mu.isLocked()) {\n\t throw new Error('invalid sync call');\n\t }\n\t return this._fs.linkSync(srcpath, dstpath);\n\t};\n\tLockedFS.prototype.symlink = function symlink (srcpath, dstpath, type, cb) {\n\t var this$1 = this;\n\t\n\t this._mu.lock(function () {\n\t this$1._fs.symlink(srcpath, dstpath, type, function (err) {\n\t this$1._mu.unlock();\n\t cb(err);\n\t });\n\t });\n\t};\n\tLockedFS.prototype.symlinkSync = function symlinkSync (srcpath, dstpath, type) {\n\t if (this._mu.isLocked()) {\n\t throw new Error('invalid sync call');\n\t }\n\t return this._fs.symlinkSync(srcpath, dstpath, type);\n\t};\n\tLockedFS.prototype.readlink = function readlink (p, cb) {\n\t var this$1 = this;\n\t\n\t this._mu.lock(function () {\n\t this$1._fs.readlink(p, function (err, linkString) {\n\t this$1._mu.unlock();\n\t cb(err, linkString);\n\t });\n\t });\n\t};\n\tLockedFS.prototype.readlinkSync = function readlinkSync (p) {\n\t if (this._mu.isLocked()) {\n\t throw new Error('invalid sync call');\n\t }\n\t return this._fs.readlinkSync(p);\n\t};\n\t\n\t/**\n\t * @hidden\n\t */\n\tvar deletionLogPath = '/.deletedFiles.log';\n\t/**\n\t * Given a read-only mode, makes it writable.\n\t * @hidden\n\t */\n\tfunction makeModeWritable(mode) {\n\t return 146 | mode;\n\t}\n\t/**\n\t * @hidden\n\t */\n\tfunction getFlag(f) {\n\t return FileFlag.getFileFlag(f);\n\t}\n\t/**\n\t * Overlays a RO file to make it writable.\n\t */\n\tvar OverlayFile = (function (PreloadFile$$1) {\n\t function OverlayFile(fs, path$$1, flag, stats, data) {\n\t PreloadFile$$1.call(this, fs, path$$1, flag, stats, data);\n\t }\n\t\n\t if ( PreloadFile$$1 ) OverlayFile.__proto__ = PreloadFile$$1;\n\t OverlayFile.prototype = Object.create( PreloadFile$$1 && PreloadFile$$1.prototype );\n\t OverlayFile.prototype.constructor = OverlayFile;\n\t OverlayFile.prototype.sync = function sync (cb) {\n\t var this$1 = this;\n\t\n\t if (!this.isDirty()) {\n\t cb(null);\n\t return;\n\t }\n\t this._fs._syncAsync(this, function (err) {\n\t this$1.resetDirty();\n\t cb(err);\n\t });\n\t };\n\t OverlayFile.prototype.syncSync = function syncSync () {\n\t if (this.isDirty()) {\n\t this._fs._syncSync(this);\n\t this.resetDirty();\n\t }\n\t };\n\t OverlayFile.prototype.close = function close (cb) {\n\t this.sync(cb);\n\t };\n\t OverlayFile.prototype.closeSync = function closeSync () {\n\t this.syncSync();\n\t };\n\t\n\t return OverlayFile;\n\t}(PreloadFile));\n\t/**\n\t * *INTERNAL, DO NOT USE DIRECTLY!*\n\t *\n\t * Core OverlayFS class that contains no locking whatsoever. We wrap these objects\n\t * in a LockedFS to prevent races.\n\t */\n\tvar UnlockedOverlayFS = (function (BaseFileSystem$$1) {\n\t function UnlockedOverlayFS(writable, readable) {\n\t BaseFileSystem$$1.call(this);\n\t this._isInitialized = false;\n\t this._initializeCallbacks = [];\n\t this._deletedFiles = {};\n\t this._deleteLog = '';\n\t // If 'true', we have scheduled a delete log update.\n\t this._deleteLogUpdatePending = false;\n\t // If 'true', a delete log update is needed after the scheduled delete log\n\t // update finishes.\n\t this._deleteLogUpdateNeeded = false;\n\t // If there was an error updating the delete log...\n\t this._deleteLogError = null;\n\t this._writable = writable;\n\t this._readable = readable;\n\t if (this._writable.isReadOnly()) {\n\t throw new ApiError(ErrorCode.EINVAL, \"Writable file system must be writable.\");\n\t }\n\t }\n\t\n\t if ( BaseFileSystem$$1 ) UnlockedOverlayFS.__proto__ = BaseFileSystem$$1;\n\t UnlockedOverlayFS.prototype = Object.create( BaseFileSystem$$1 && BaseFileSystem$$1.prototype );\n\t UnlockedOverlayFS.prototype.constructor = UnlockedOverlayFS;\n\t UnlockedOverlayFS.isAvailable = function isAvailable () {\n\t return true;\n\t };\n\t UnlockedOverlayFS.prototype.getOverlayedFileSystems = function getOverlayedFileSystems () {\n\t return {\n\t readable: this._readable,\n\t writable: this._writable\n\t };\n\t };\n\t UnlockedOverlayFS.prototype._syncAsync = function _syncAsync (file, cb) {\n\t var this$1 = this;\n\t\n\t this.createParentDirectoriesAsync(file.getPath(), function (err) {\n\t if (err) {\n\t return cb(err);\n\t }\n\t this$1._writable.writeFile(file.getPath(), file.getBuffer(), null, getFlag('w'), file.getStats().mode, cb);\n\t });\n\t };\n\t UnlockedOverlayFS.prototype._syncSync = function _syncSync (file) {\n\t this.createParentDirectories(file.getPath());\n\t this._writable.writeFileSync(file.getPath(), file.getBuffer(), null, getFlag('w'), file.getStats().mode);\n\t };\n\t UnlockedOverlayFS.prototype.getName = function getName () {\n\t return OverlayFS.Name;\n\t };\n\t /**\n\t * Called once to load up metadata stored on the writable file system.\n\t */\n\t UnlockedOverlayFS.prototype.initialize = function initialize (cb) {\n\t var this$1 = this;\n\t\n\t var callbackArray = this._initializeCallbacks;\n\t var end = function (e) {\n\t this$1._isInitialized = !e;\n\t this$1._initializeCallbacks = [];\n\t callbackArray.forEach((function (cb) { return cb(e); }));\n\t };\n\t // if we're already initialized, immediately invoke the callback\n\t if (this._isInitialized) {\n\t return cb();\n\t }\n\t callbackArray.push(cb);\n\t // The first call to initialize initializes, the rest wait for it to complete.\n\t if (callbackArray.length !== 1) {\n\t return;\n\t }\n\t // Read deletion log, process into metadata.\n\t this._writable.readFile(deletionLogPath, 'utf8', getFlag('r'), function (err, data) {\n\t if (err) {\n\t // ENOENT === Newly-instantiated file system, and thus empty log.\n\t if (err.errno !== ErrorCode.ENOENT) {\n\t return end(err);\n\t }\n\t }\n\t else {\n\t this$1._deleteLog = data;\n\t }\n\t this$1._reparseDeletionLog();\n\t end();\n\t });\n\t };\n\t UnlockedOverlayFS.prototype.isReadOnly = function isReadOnly () { return false; };\n\t UnlockedOverlayFS.prototype.supportsSynch = function supportsSynch () { return this._readable.supportsSynch() && this._writable.supportsSynch(); };\n\t UnlockedOverlayFS.prototype.supportsLinks = function supportsLinks () { return false; };\n\t UnlockedOverlayFS.prototype.supportsProps = function supportsProps () { return this._readable.supportsProps() && this._writable.supportsProps(); };\n\t UnlockedOverlayFS.prototype.getDeletionLog = function getDeletionLog () {\n\t return this._deleteLog;\n\t };\n\t UnlockedOverlayFS.prototype.restoreDeletionLog = function restoreDeletionLog (log) {\n\t this._deleteLog = log;\n\t this._reparseDeletionLog();\n\t this.updateLog('');\n\t };\n\t UnlockedOverlayFS.prototype.rename = function rename (oldPath, newPath, cb) {\n\t var this$1 = this;\n\t\n\t if (!this.checkInitAsync(cb) || this.checkPathAsync(oldPath, cb) || this.checkPathAsync(newPath, cb)) {\n\t return;\n\t }\n\t if (oldPath === deletionLogPath || newPath === deletionLogPath) {\n\t return cb(ApiError.EPERM('Cannot rename deletion log.'));\n\t }\n\t // nothing to do if paths match\n\t if (oldPath === newPath) {\n\t return cb();\n\t }\n\t this.stat(oldPath, false, function (oldErr, oldStats) {\n\t if (oldErr) {\n\t return cb(oldErr);\n\t }\n\t return this$1.stat(newPath, false, function (newErr, newStats) {\n\t var self = this$1;\n\t // precondition: both oldPath and newPath exist and are dirs.\n\t // decreases: |files|\n\t // Need to move *every file/folder* currently stored on\n\t // readable to its new location on writable.\n\t function copyDirContents(files) {\n\t var file = files.shift();\n\t if (!file) {\n\t return cb();\n\t }\n\t var oldFile = path.resolve(oldPath, file);\n\t var newFile = path.resolve(newPath, file);\n\t // Recursion! Should work for any nested files / folders.\n\t self.rename(oldFile, newFile, function (err) {\n\t if (err) {\n\t return cb(err);\n\t }\n\t copyDirContents(files);\n\t });\n\t }\n\t var mode = 511;\n\t // from linux's rename(2) manpage: oldpath can specify a\n\t // directory. In this case, newpath must either not exist, or\n\t // it must specify an empty directory.\n\t if (oldStats.isDirectory()) {\n\t if (newErr) {\n\t if (newErr.errno !== ErrorCode.ENOENT) {\n\t return cb(newErr);\n\t }\n\t return this$1._writable.exists(oldPath, function (exists) {\n\t // simple case - both old and new are on the writable layer\n\t if (exists) {\n\t return this$1._writable.rename(oldPath, newPath, cb);\n\t }\n\t this$1._writable.mkdir(newPath, mode, function (mkdirErr) {\n\t if (mkdirErr) {\n\t return cb(mkdirErr);\n\t }\n\t this$1._readable.readdir(oldPath, function (err, files) {\n\t if (err) {\n\t return cb();\n\t }\n\t copyDirContents(files);\n\t });\n\t });\n\t });\n\t }\n\t mode = newStats.mode;\n\t if (!newStats.isDirectory()) {\n\t return cb(ApiError.ENOTDIR(newPath));\n\t }\n\t this$1.readdir(newPath, function (readdirErr, files) {\n\t if (files && files.length) {\n\t return cb(ApiError.ENOTEMPTY(newPath));\n\t }\n\t this$1._readable.readdir(oldPath, function (err, files) {\n\t if (err) {\n\t return cb();\n\t }\n\t copyDirContents(files);\n\t });\n\t });\n\t }\n\t if (newStats && newStats.isDirectory()) {\n\t return cb(ApiError.EISDIR(newPath));\n\t }\n\t this$1.readFile(oldPath, null, getFlag('r'), function (err, data) {\n\t if (err) {\n\t return cb(err);\n\t }\n\t return this$1.writeFile(newPath, data, null, getFlag('w'), oldStats.mode, function (err) {\n\t if (err) {\n\t return cb(err);\n\t }\n\t return this$1.unlink(oldPath, cb);\n\t });\n\t });\n\t });\n\t });\n\t };\n\t UnlockedOverlayFS.prototype.renameSync = function renameSync (oldPath, newPath) {\n\t var this$1 = this;\n\t\n\t this.checkInitialized();\n\t this.checkPath(oldPath);\n\t this.checkPath(newPath);\n\t if (oldPath === deletionLogPath || newPath === deletionLogPath) {\n\t throw ApiError.EPERM('Cannot rename deletion log.');\n\t }\n\t // Write newPath using oldPath's contents, delete oldPath.\n\t var oldStats = this.statSync(oldPath, false);\n\t if (oldStats.isDirectory()) {\n\t // Optimization: Don't bother moving if old === new.\n\t if (oldPath === newPath) {\n\t return;\n\t }\n\t var mode = 511;\n\t if (this.existsSync(newPath)) {\n\t var stats = this.statSync(newPath, false);\n\t mode = stats.mode;\n\t if (stats.isDirectory()) {\n\t if (this.readdirSync(newPath).length > 0) {\n\t throw ApiError.ENOTEMPTY(newPath);\n\t }\n\t }\n\t else {\n\t throw ApiError.ENOTDIR(newPath);\n\t }\n\t }\n\t // Take care of writable first. Move any files there, or create an empty directory\n\t // if it doesn't exist.\n\t if (this._writable.existsSync(oldPath)) {\n\t this._writable.renameSync(oldPath, newPath);\n\t }\n\t else if (!this._writable.existsSync(newPath)) {\n\t this._writable.mkdirSync(newPath, mode);\n\t }\n\t // Need to move *every file/folder* currently stored on readable to its new location\n\t // on writable.\n\t if (this._readable.existsSync(oldPath)) {\n\t this._readable.readdirSync(oldPath).forEach(function (name) {\n\t // Recursion! Should work for any nested files / folders.\n\t this$1.renameSync(path.resolve(oldPath, name), path.resolve(newPath, name));\n\t });\n\t }\n\t }\n\t else {\n\t if (this.existsSync(newPath) && this.statSync(newPath, false).isDirectory()) {\n\t throw ApiError.EISDIR(newPath);\n\t }\n\t this.writeFileSync(newPath, this.readFileSync(oldPath, null, getFlag('r')), null, getFlag('w'), oldStats.mode);\n\t }\n\t if (oldPath !== newPath && this.existsSync(oldPath)) {\n\t this.unlinkSync(oldPath);\n\t }\n\t };\n\t UnlockedOverlayFS.prototype.stat = function stat (p, isLstat, cb) {\n\t var this$1 = this;\n\t\n\t if (!this.checkInitAsync(cb)) {\n\t return;\n\t }\n\t this._writable.stat(p, isLstat, function (err, stat) {\n\t if (err && err.errno === ErrorCode.ENOENT) {\n\t if (this$1._deletedFiles[p]) {\n\t cb(ApiError.ENOENT(p));\n\t }\n\t this$1._readable.stat(p, isLstat, function (err, stat) {\n\t if (stat) {\n\t // Make the oldStat's mode writable. Preserve the topmost\n\t // part of the mode, which specifies if it is a file or a\n\t // directory.\n\t stat = stat.clone();\n\t stat.mode = makeModeWritable(stat.mode);\n\t }\n\t cb(err, stat);\n\t });\n\t }\n\t else {\n\t cb(err, stat);\n\t }\n\t });\n\t };\n\t UnlockedOverlayFS.prototype.statSync = function statSync (p, isLstat) {\n\t this.checkInitialized();\n\t try {\n\t return this._writable.statSync(p, isLstat);\n\t }\n\t catch (e) {\n\t if (this._deletedFiles[p]) {\n\t throw ApiError.ENOENT(p);\n\t }\n\t var oldStat = this._readable.statSync(p, isLstat).clone();\n\t // Make the oldStat's mode writable. Preserve the topmost part of the\n\t // mode, which specifies if it is a file or a directory.\n\t oldStat.mode = makeModeWritable(oldStat.mode);\n\t return oldStat;\n\t }\n\t };\n\t UnlockedOverlayFS.prototype.open = function open (p, flag, mode, cb) {\n\t var this$1 = this;\n\t\n\t if (!this.checkInitAsync(cb) || this.checkPathAsync(p, cb)) {\n\t return;\n\t }\n\t this.stat(p, false, function (err, stats) {\n\t if (stats) {\n\t switch (flag.pathExistsAction()) {\n\t case ActionType.TRUNCATE_FILE:\n\t return this$1.createParentDirectoriesAsync(p, function (err) {\n\t if (err) {\n\t return cb(err);\n\t }\n\t this$1._writable.open(p, flag, mode, cb);\n\t });\n\t case ActionType.NOP:\n\t return this$1._writable.exists(p, function (exists) {\n\t if (exists) {\n\t this$1._writable.open(p, flag, mode, cb);\n\t }\n\t else {\n\t // at this point we know the stats object we got is from\n\t // the readable FS.\n\t stats = stats.clone();\n\t stats.mode = mode;\n\t this$1._readable.readFile(p, null, getFlag('r'), function (readFileErr, data) {\n\t if (readFileErr) {\n\t return cb(readFileErr);\n\t }\n\t if (stats.size === -1) {\n\t stats.size = data.length;\n\t }\n\t var f = new OverlayFile(this$1, p, flag, stats, data);\n\t cb(null, f);\n\t });\n\t }\n\t });\n\t default:\n\t return cb(ApiError.EEXIST(p));\n\t }\n\t }\n\t else {\n\t switch (flag.pathNotExistsAction()) {\n\t case ActionType.CREATE_FILE:\n\t return this$1.createParentDirectoriesAsync(p, function (err) {\n\t if (err) {\n\t return cb(err);\n\t }\n\t return this$1._writable.open(p, flag, mode, cb);\n\t });\n\t default:\n\t return cb(ApiError.ENOENT(p));\n\t }\n\t }\n\t });\n\t };\n\t UnlockedOverlayFS.prototype.openSync = function openSync (p, flag, mode) {\n\t this.checkInitialized();\n\t this.checkPath(p);\n\t if (p === deletionLogPath) {\n\t throw ApiError.EPERM('Cannot open deletion log.');\n\t }\n\t if (this.existsSync(p)) {\n\t switch (flag.pathExistsAction()) {\n\t case ActionType.TRUNCATE_FILE:\n\t this.createParentDirectories(p);\n\t return this._writable.openSync(p, flag, mode);\n\t case ActionType.NOP:\n\t if (this._writable.existsSync(p)) {\n\t return this._writable.openSync(p, flag, mode);\n\t }\n\t else {\n\t // Create an OverlayFile.\n\t var buf = this._readable.readFileSync(p, null, getFlag('r'));\n\t var stats = this._readable.statSync(p, false).clone();\n\t stats.mode = mode;\n\t return new OverlayFile(this, p, flag, stats, buf);\n\t }\n\t default:\n\t throw ApiError.EEXIST(p);\n\t }\n\t }\n\t else {\n\t switch (flag.pathNotExistsAction()) {\n\t case ActionType.CREATE_FILE:\n\t this.createParentDirectories(p);\n\t return this._writable.openSync(p, flag, mode);\n\t default:\n\t throw ApiError.ENOENT(p);\n\t }\n\t }\n\t };\n\t UnlockedOverlayFS.prototype.unlink = function unlink (p, cb) {\n\t var this$1 = this;\n\t\n\t if (!this.checkInitAsync(cb) || this.checkPathAsync(p, cb)) {\n\t return;\n\t }\n\t this.exists(p, function (exists) {\n\t if (!exists) {\n\t return cb(ApiError.ENOENT(p));\n\t }\n\t this$1._writable.exists(p, function (writableExists) {\n\t if (writableExists) {\n\t return this$1._writable.unlink(p, function (err) {\n\t if (err) {\n\t return cb(err);\n\t }\n\t this$1.exists(p, function (readableExists) {\n\t if (readableExists) {\n\t this$1.deletePath(p);\n\t }\n\t cb(null);\n\t });\n\t });\n\t }\n\t else {\n\t // if this only exists on the readable FS, add it to the\n\t // delete map.\n\t this$1.deletePath(p);\n\t cb(null);\n\t }\n\t });\n\t });\n\t };\n\t UnlockedOverlayFS.prototype.unlinkSync = function unlinkSync (p) {\n\t this.checkInitialized();\n\t this.checkPath(p);\n\t if (this.existsSync(p)) {\n\t if (this._writable.existsSync(p)) {\n\t this._writable.unlinkSync(p);\n\t }\n\t // if it still exists add to the delete log\n\t if (this.existsSync(p)) {\n\t this.deletePath(p);\n\t }\n\t }\n\t else {\n\t throw ApiError.ENOENT(p);\n\t }\n\t };\n\t UnlockedOverlayFS.prototype.rmdir = function rmdir (p, cb) {\n\t var this$1 = this;\n\t\n\t if (!this.checkInitAsync(cb)) {\n\t return;\n\t }\n\t var rmdirLower = function () {\n\t this$1.readdir(p, function (err, files) {\n\t if (err) {\n\t return cb(err);\n\t }\n\t if (files.length) {\n\t return cb(ApiError.ENOTEMPTY(p));\n\t }\n\t this$1.deletePath(p);\n\t cb(null);\n\t });\n\t };\n\t this.exists(p, function (exists) {\n\t if (!exists) {\n\t return cb(ApiError.ENOENT(p));\n\t }\n\t this$1._writable.exists(p, function (writableExists) {\n\t if (writableExists) {\n\t this$1._writable.rmdir(p, function (err) {\n\t if (err) {\n\t return cb(err);\n\t }\n\t this$1._readable.exists(p, function (readableExists) {\n\t if (readableExists) {\n\t rmdirLower();\n\t }\n\t else {\n\t cb();\n\t }\n\t });\n\t });\n\t }\n\t else {\n\t rmdirLower();\n\t }\n\t });\n\t });\n\t };\n\t UnlockedOverlayFS.prototype.rmdirSync = function rmdirSync (p) {\n\t this.checkInitialized();\n\t if (this.existsSync(p)) {\n\t if (this._writable.existsSync(p)) {\n\t this._writable.rmdirSync(p);\n\t }\n\t if (this.existsSync(p)) {\n\t // Check if directory is empty.\n\t if (this.readdirSync(p).length > 0) {\n\t throw ApiError.ENOTEMPTY(p);\n\t }\n\t else {\n\t this.deletePath(p);\n\t }\n\t }\n\t }\n\t else {\n\t throw ApiError.ENOENT(p);\n\t }\n\t };\n\t UnlockedOverlayFS.prototype.mkdir = function mkdir (p, mode, cb) {\n\t var this$1 = this;\n\t\n\t if (!this.checkInitAsync(cb)) {\n\t return;\n\t }\n\t this.exists(p, function (exists) {\n\t if (exists) {\n\t return cb(ApiError.EEXIST(p));\n\t }\n\t // The below will throw should any of the parent directories\n\t // fail to exist on _writable.\n\t this$1.createParentDirectoriesAsync(p, function (err) {\n\t if (err) {\n\t return cb(err);\n\t }\n\t this$1._writable.mkdir(p, mode, cb);\n\t });\n\t });\n\t };\n\t UnlockedOverlayFS.prototype.mkdirSync = function mkdirSync (p, mode) {\n\t this.checkInitialized();\n\t if (this.existsSync(p)) {\n\t throw ApiError.EEXIST(p);\n\t }\n\t else {\n\t // The below will throw should any of the parent directories fail to exist\n\t // on _writable.\n\t this.createParentDirectories(p);\n\t this._writable.mkdirSync(p, mode);\n\t }\n\t };\n\t UnlockedOverlayFS.prototype.readdir = function readdir (p, cb) {\n\t var this$1 = this;\n\t\n\t if (!this.checkInitAsync(cb)) {\n\t return;\n\t }\n\t this.stat(p, false, function (err, dirStats) {\n\t if (err) {\n\t return cb(err);\n\t }\n\t if (!dirStats.isDirectory()) {\n\t return cb(ApiError.ENOTDIR(p));\n\t }\n\t this$1._writable.readdir(p, function (err, wFiles) {\n\t if (err && err.code !== 'ENOENT') {\n\t return cb(err);\n\t }\n\t else if (err || !wFiles) {\n\t wFiles = [];\n\t }\n\t this$1._readable.readdir(p, function (err, rFiles) {\n\t // if the directory doesn't exist on the lower FS set rFiles\n\t // here to simplify the following code.\n\t if (err || !rFiles) {\n\t rFiles = [];\n\t }\n\t // Readdir in both, check delete log on read-only file system's files, merge, return.\n\t var seenMap = {};\n\t var filtered = wFiles.concat(rFiles.filter(function (fPath) { return !this$1._deletedFiles[(p + \"/\" + fPath)]; })).filter(function (fPath) {\n\t // Remove duplicates.\n\t var result = !seenMap[fPath];\n\t seenMap[fPath] = true;\n\t return result;\n\t });\n\t cb(null, filtered);\n\t });\n\t });\n\t });\n\t };\n\t UnlockedOverlayFS.prototype.readdirSync = function readdirSync (p) {\n\t var this$1 = this;\n\t\n\t this.checkInitialized();\n\t var dirStats = this.statSync(p, false);\n\t if (!dirStats.isDirectory()) {\n\t throw ApiError.ENOTDIR(p);\n\t }\n\t // Readdir in both, check delete log on RO file system's listing, merge, return.\n\t var contents = [];\n\t try {\n\t contents = contents.concat(this._writable.readdirSync(p));\n\t }\n\t catch (e) {\n\t // NOP.\n\t }\n\t try {\n\t contents = contents.concat(this._readable.readdirSync(p).filter(function (fPath) { return !this$1._deletedFiles[(p + \"/\" + fPath)]; }));\n\t }\n\t catch (e) {\n\t // NOP.\n\t }\n\t var seenMap = {};\n\t return contents.filter(function (fileP) {\n\t var result = !seenMap[fileP];\n\t seenMap[fileP] = true;\n\t return result;\n\t });\n\t };\n\t UnlockedOverlayFS.prototype.exists = function exists (p, cb) {\n\t var this$1 = this;\n\t\n\t // Cannot pass an error back to callback, so throw an exception instead\n\t // if not initialized.\n\t this.checkInitialized();\n\t this._writable.exists(p, function (existsWritable) {\n\t if (existsWritable) {\n\t return cb(true);\n\t }\n\t this$1._readable.exists(p, function (existsReadable) {\n\t cb(existsReadable && this$1._deletedFiles[p] !== true);\n\t });\n\t });\n\t };\n\t UnlockedOverlayFS.prototype.existsSync = function existsSync (p) {\n\t this.checkInitialized();\n\t return this._writable.existsSync(p) || (this._readable.existsSync(p) && this._deletedFiles[p] !== true);\n\t };\n\t UnlockedOverlayFS.prototype.chmod = function chmod (p, isLchmod, mode, cb) {\n\t var this$1 = this;\n\t\n\t if (!this.checkInitAsync(cb)) {\n\t return;\n\t }\n\t this.operateOnWritableAsync(p, function (err) {\n\t if (err) {\n\t return cb(err);\n\t }\n\t else {\n\t this$1._writable.chmod(p, isLchmod, mode, cb);\n\t }\n\t });\n\t };\n\t UnlockedOverlayFS.prototype.chmodSync = function chmodSync (p, isLchmod, mode) {\n\t var this$1 = this;\n\t\n\t this.checkInitialized();\n\t this.operateOnWritable(p, function () {\n\t this$1._writable.chmodSync(p, isLchmod, mode);\n\t });\n\t };\n\t UnlockedOverlayFS.prototype.chown = function chown (p, isLchmod, uid, gid, cb) {\n\t var this$1 = this;\n\t\n\t if (!this.checkInitAsync(cb)) {\n\t return;\n\t }\n\t this.operateOnWritableAsync(p, function (err) {\n\t if (err) {\n\t return cb(err);\n\t }\n\t else {\n\t this$1._writable.chown(p, isLchmod, uid, gid, cb);\n\t }\n\t });\n\t };\n\t UnlockedOverlayFS.prototype.chownSync = function chownSync (p, isLchown, uid, gid) {\n\t var this$1 = this;\n\t\n\t this.checkInitialized();\n\t this.operateOnWritable(p, function () {\n\t this$1._writable.chownSync(p, isLchown, uid, gid);\n\t });\n\t };\n\t UnlockedOverlayFS.prototype.utimes = function utimes (p, atime, mtime, cb) {\n\t var this$1 = this;\n\t\n\t if (!this.checkInitAsync(cb)) {\n\t return;\n\t }\n\t this.operateOnWritableAsync(p, function (err) {\n\t if (err) {\n\t return cb(err);\n\t }\n\t else {\n\t this$1._writable.utimes(p, atime, mtime, cb);\n\t }\n\t });\n\t };\n\t UnlockedOverlayFS.prototype.utimesSync = function utimesSync (p, atime, mtime) {\n\t var this$1 = this;\n\t\n\t this.checkInitialized();\n\t this.operateOnWritable(p, function () {\n\t this$1._writable.utimesSync(p, atime, mtime);\n\t });\n\t };\n\t UnlockedOverlayFS.prototype.deletePath = function deletePath (p) {\n\t this._deletedFiles[p] = true;\n\t this.updateLog((\"d\" + p + \"\\n\"));\n\t };\n\t UnlockedOverlayFS.prototype.updateLog = function updateLog (addition) {\n\t var this$1 = this;\n\t\n\t this._deleteLog += addition;\n\t if (this._deleteLogUpdatePending) {\n\t this._deleteLogUpdateNeeded = true;\n\t }\n\t else {\n\t this._deleteLogUpdatePending = true;\n\t this._writable.writeFile(deletionLogPath, this._deleteLog, 'utf8', FileFlag.getFileFlag('w'), 420, function (e) {\n\t this$1._deleteLogUpdatePending = false;\n\t if (e) {\n\t this$1._deleteLogError = e;\n\t }\n\t else if (this$1._deleteLogUpdateNeeded) {\n\t this$1._deleteLogUpdateNeeded = false;\n\t this$1.updateLog('');\n\t }\n\t });\n\t }\n\t };\n\t UnlockedOverlayFS.prototype._reparseDeletionLog = function _reparseDeletionLog () {\n\t var this$1 = this;\n\t\n\t this._deletedFiles = {};\n\t this._deleteLog.split('\\n').forEach(function (path$$1) {\n\t // If the log entry begins w/ 'd', it's a deletion.\n\t this$1._deletedFiles[path$$1.slice(1)] = path$$1.slice(0, 1) === 'd';\n\t });\n\t };\n\t UnlockedOverlayFS.prototype.checkInitialized = function checkInitialized () {\n\t if (!this._isInitialized) {\n\t throw new ApiError(ErrorCode.EPERM, \"OverlayFS is not initialized. Please initialize OverlayFS using its initialize() method before using it.\");\n\t }\n\t else if (this._deleteLogError !== null) {\n\t var e = this._deleteLogError;\n\t this._deleteLogError = null;\n\t throw e;\n\t }\n\t };\n\t UnlockedOverlayFS.prototype.checkInitAsync = function checkInitAsync (cb) {\n\t if (!this._isInitialized) {\n\t cb(new ApiError(ErrorCode.EPERM, \"OverlayFS is not initialized. Please initialize OverlayFS using its initialize() method before using it.\"));\n\t return false;\n\t }\n\t else if (this._deleteLogError !== null) {\n\t var e = this._deleteLogError;\n\t this._deleteLogError = null;\n\t cb(e);\n\t return false;\n\t }\n\t return true;\n\t };\n\t UnlockedOverlayFS.prototype.checkPath = function checkPath (p) {\n\t if (p === deletionLogPath) {\n\t throw ApiError.EPERM(p);\n\t }\n\t };\n\t UnlockedOverlayFS.prototype.checkPathAsync = function checkPathAsync (p, cb) {\n\t if (p === deletionLogPath) {\n\t cb(ApiError.EPERM(p));\n\t return true;\n\t }\n\t return false;\n\t };\n\t UnlockedOverlayFS.prototype.createParentDirectoriesAsync = function createParentDirectoriesAsync (p, cb) {\n\t var parent = path.dirname(p);\n\t var toCreate = [];\n\t var self = this;\n\t this._writable.stat(parent, false, statDone);\n\t function statDone(err, stat) {\n\t if (err) {\n\t toCreate.push(parent);\n\t parent = path.dirname(parent);\n\t self._writable.stat(parent, false, statDone);\n\t }\n\t else {\n\t createParents();\n\t }\n\t }\n\t function createParents() {\n\t if (!toCreate.length) {\n\t return cb();\n\t }\n\t var dir = toCreate.pop();\n\t self._readable.stat(dir, false, function (err, stats) {\n\t // stop if we couldn't read the dir\n\t if (!stats) {\n\t return cb();\n\t }\n\t self._writable.mkdir(dir, stats.mode, function (err) {\n\t if (err) {\n\t return cb(err);\n\t }\n\t createParents();\n\t });\n\t });\n\t }\n\t };\n\t /**\n\t * With the given path, create the needed parent directories on the writable storage\n\t * should they not exist. Use modes from the read-only storage.\n\t */\n\t UnlockedOverlayFS.prototype.createParentDirectories = function createParentDirectories (p) {\n\t var this$1 = this;\n\t\n\t var parent = path.dirname(p), toCreate = [];\n\t while (!this._writable.existsSync(parent)) {\n\t toCreate.push(parent);\n\t parent = path.dirname(parent);\n\t }\n\t toCreate = toCreate.reverse();\n\t toCreate.forEach(function (p) {\n\t this$1._writable.mkdirSync(p, this$1.statSync(p, false).mode);\n\t });\n\t };\n\t /**\n\t * Helper function:\n\t * - Ensures p is on writable before proceeding. Throws an error if it doesn't exist.\n\t * - Calls f to perform operation on writable.\n\t */\n\t UnlockedOverlayFS.prototype.operateOnWritable = function operateOnWritable (p, f) {\n\t if (this.existsSync(p)) {\n\t if (!this._writable.existsSync(p)) {\n\t // File is on readable storage. Copy to writable storage before\n\t // changing its mode.\n\t this.copyToWritable(p);\n\t }\n\t f();\n\t }\n\t else {\n\t throw ApiError.ENOENT(p);\n\t }\n\t };\n\t UnlockedOverlayFS.prototype.operateOnWritableAsync = function operateOnWritableAsync (p, cb) {\n\t var this$1 = this;\n\t\n\t this.exists(p, function (exists) {\n\t if (!exists) {\n\t return cb(ApiError.ENOENT(p));\n\t }\n\t this$1._writable.exists(p, function (existsWritable) {\n\t if (existsWritable) {\n\t cb();\n\t }\n\t else {\n\t return this$1.copyToWritableAsync(p, cb);\n\t }\n\t });\n\t });\n\t };\n\t /**\n\t * Copy from readable to writable storage.\n\t * PRECONDITION: File does not exist on writable storage.\n\t */\n\t UnlockedOverlayFS.prototype.copyToWritable = function copyToWritable (p) {\n\t var pStats = this.statSync(p, false);\n\t if (pStats.isDirectory()) {\n\t this._writable.mkdirSync(p, pStats.mode);\n\t }\n\t else {\n\t this.writeFileSync(p, this._readable.readFileSync(p, null, getFlag('r')), null, getFlag('w'), this.statSync(p, false).mode);\n\t }\n\t };\n\t UnlockedOverlayFS.prototype.copyToWritableAsync = function copyToWritableAsync (p, cb) {\n\t var this$1 = this;\n\t\n\t this.stat(p, false, function (err, pStats) {\n\t if (err) {\n\t return cb(err);\n\t }\n\t if (pStats.isDirectory()) {\n\t return this$1._writable.mkdir(p, pStats.mode, cb);\n\t }\n\t // need to copy file.\n\t this$1._readable.readFile(p, null, getFlag('r'), function (err, data) {\n\t if (err) {\n\t return cb(err);\n\t }\n\t this$1.writeFile(p, data, null, getFlag('w'), pStats.mode, cb);\n\t });\n\t });\n\t };\n\t\n\t return UnlockedOverlayFS;\n\t}(BaseFileSystem));\n\t/**\n\t * OverlayFS makes a read-only filesystem writable by storing writes on a second,\n\t * writable file system. Deletes are persisted via metadata stored on the writable\n\t * file system.\n\t */\n\tvar OverlayFS = (function (LockedFS$$1) {\n\t function OverlayFS(writable, readable, deprecateMsg) {\n\t if ( deprecateMsg === void 0 ) deprecateMsg = true;\n\t\n\t LockedFS$$1.call(this, new UnlockedOverlayFS(writable, readable));\n\t deprecationMessage(deprecateMsg, OverlayFS.Name, { readable: \"readable file system\", writable: \"writable file system\" });\n\t }\n\t\n\t if ( LockedFS$$1 ) OverlayFS.__proto__ = LockedFS$$1;\n\t OverlayFS.prototype = Object.create( LockedFS$$1 && LockedFS$$1.prototype );\n\t OverlayFS.prototype.constructor = OverlayFS;\n\t /**\n\t * Constructs and initializes an OverlayFS instance with the given options.\n\t */\n\t OverlayFS.Create = function Create (opts, cb) {\n\t try {\n\t var fs = new OverlayFS(opts.writable, opts.readable, false);\n\t fs.initialize(function (e) {\n\t cb(e, fs);\n\t }, false);\n\t }\n\t catch (e) {\n\t cb(e);\n\t }\n\t };\n\t OverlayFS.isAvailable = function isAvailable () {\n\t return UnlockedOverlayFS.isAvailable();\n\t };\n\t /**\n\t * **Deprecated. Please use OverlayFS.Create() to construct and initialize OverlayFS instances.**\n\t */\n\t OverlayFS.prototype.initialize = function initialize (cb, deprecateMsg) {\n\t if ( deprecateMsg === void 0 ) deprecateMsg = true;\n\t\n\t if (deprecateMsg) {\n\t console.warn(\"[OverlayFS] OverlayFS.initialize() is deprecated and will be removed in the next major release. Please use 'OverlayFS.Create({readable: readable file system instance, writable: writable file system instance}, cb)' to create and initialize OverlayFS instances.\");\n\t }\n\t LockedFS$$1.prototype.initialize.call(this, cb);\n\t };\n\t OverlayFS.prototype.getOverlayedFileSystems = function getOverlayedFileSystems () {\n\t return LockedFS$$1.prototype.getFSUnlocked.call(this).getOverlayedFileSystems();\n\t };\n\t OverlayFS.prototype.unwrap = function unwrap () {\n\t return LockedFS$$1.prototype.getFSUnlocked.call(this);\n\t };\n\t\n\t return OverlayFS;\n\t}(LockedFS));\n\t\n\tOverlayFS.Name = \"OverlayFS\";\n\tOverlayFS.Options = {\n\t writable: {\n\t type: \"object\",\n\t description: \"The file system to write modified files to.\"\n\t },\n\t readable: {\n\t type: \"object\",\n\t description: \"The file system that initially populates this file system.\"\n\t }\n\t};\n\t\n\t/**\n\t * @hidden\n\t */\n\tvar SpecialArgType;\n\t(function (SpecialArgType) {\n\t // Callback\n\t SpecialArgType[SpecialArgType[\"CB\"] = 0] = \"CB\";\n\t // File descriptor\n\t SpecialArgType[SpecialArgType[\"FD\"] = 1] = \"FD\";\n\t // API error\n\t SpecialArgType[SpecialArgType[\"API_ERROR\"] = 2] = \"API_ERROR\";\n\t // Stats object\n\t SpecialArgType[SpecialArgType[\"STATS\"] = 3] = \"STATS\";\n\t // Initial probe for file system information.\n\t SpecialArgType[SpecialArgType[\"PROBE\"] = 4] = \"PROBE\";\n\t // FileFlag object.\n\t SpecialArgType[SpecialArgType[\"FILEFLAG\"] = 5] = \"FILEFLAG\";\n\t // Buffer object.\n\t SpecialArgType[SpecialArgType[\"BUFFER\"] = 6] = \"BUFFER\";\n\t // Generic Error object.\n\t SpecialArgType[SpecialArgType[\"ERROR\"] = 7] = \"ERROR\";\n\t})(SpecialArgType || (SpecialArgType = {}));\n\t/**\n\t * Converts callback arguments into ICallbackArgument objects, and back\n\t * again.\n\t * @hidden\n\t */\n\tvar CallbackArgumentConverter = function CallbackArgumentConverter() {\n\t this._callbacks = {};\n\t this._nextId = 0;\n\t};\n\tCallbackArgumentConverter.prototype.toRemoteArg = function toRemoteArg (cb) {\n\t var id = this._nextId++;\n\t this._callbacks[id] = cb;\n\t return {\n\t type: SpecialArgType.CB,\n\t id: id\n\t };\n\t};\n\tCallbackArgumentConverter.prototype.toLocalArg = function toLocalArg (id) {\n\t var cb = this._callbacks[id];\n\t delete this._callbacks[id];\n\t return cb;\n\t};\n\t/**\n\t * @hidden\n\t */\n\tvar FileDescriptorArgumentConverter = function FileDescriptorArgumentConverter() {\n\t this._fileDescriptors = {};\n\t this._nextId = 0;\n\t};\n\tFileDescriptorArgumentConverter.prototype.toRemoteArg = function toRemoteArg (fd, p, flag, cb) {\n\t var id = this._nextId++;\n\t var data;\n\t var stat;\n\t this._fileDescriptors[id] = fd;\n\t // Extract needed information asynchronously.\n\t fd.stat(function (err, stats) {\n\t if (err) {\n\t cb(err);\n\t }\n\t else {\n\t stat = bufferToTransferrableObject(stats.toBuffer());\n\t // If it's a readable flag, we need to grab contents.\n\t if (flag.isReadable()) {\n\t fd.read(Buffer.alloc(stats.size), 0, stats.size, 0, function (err, bytesRead, buff) {\n\t if (err) {\n\t cb(err);\n\t }\n\t else {\n\t data = bufferToTransferrableObject(buff);\n\t cb(null, {\n\t type: SpecialArgType.FD,\n\t id: id,\n\t data: data,\n\t stat: stat,\n\t path: p,\n\t flag: flag.getFlagString()\n\t });\n\t }\n\t });\n\t }\n\t else {\n\t // File is not readable, which means writing to it will append or\n\t // truncate/replace existing contents. Return an empty arraybuffer.\n\t cb(null, {\n\t type: SpecialArgType.FD,\n\t id: id,\n\t data: new ArrayBuffer(0),\n\t stat: stat,\n\t path: p,\n\t flag: flag.getFlagString()\n\t });\n\t }\n\t }\n\t });\n\t};\n\tFileDescriptorArgumentConverter.prototype.applyFdAPIRequest = function applyFdAPIRequest (request, cb) {\n\t var this$1 = this;\n\t\n\t var fdArg = request.args[0];\n\t this._applyFdChanges(fdArg, function (err, fd) {\n\t if (err) {\n\t cb(err);\n\t }\n\t else {\n\t // Apply method on now-changed file descriptor.\n\t fd[request.method](function (e) {\n\t if (request.method === 'close') {\n\t delete this$1._fileDescriptors[fdArg.id];\n\t }\n\t cb(e);\n\t });\n\t }\n\t });\n\t};\n\tFileDescriptorArgumentConverter.prototype._applyFdChanges = function _applyFdChanges (remoteFd, cb) {\n\t var fd = this._fileDescriptors[remoteFd.id], data = transferrableObjectToBuffer(remoteFd.data), remoteStats = Stats.fromBuffer(transferrableObjectToBuffer(remoteFd.stat));\n\t // Write data if the file is writable.\n\t var flag = FileFlag.getFileFlag(remoteFd.flag);\n\t if (flag.isWriteable()) {\n\t // Appendable: Write to end of file.\n\t // Writeable: Replace entire contents of file.\n\t fd.write(data, 0, data.length, flag.isAppendable() ? fd.getPos() : 0, function (e) {\n\t function applyStatChanges() {\n\t // Check if mode changed.\n\t fd.stat(function (e, stats) {\n\t if (e) {\n\t cb(e);\n\t }\n\t else {\n\t if (stats.mode !== remoteStats.mode) {\n\t fd.chmod(remoteStats.mode, function (e) {\n\t cb(e, fd);\n\t });\n\t }\n\t else {\n\t cb(e, fd);\n\t }\n\t }\n\t });\n\t }\n\t if (e) {\n\t cb(e);\n\t }\n\t else {\n\t // If writeable & not appendable, we need to ensure file contents are\n\t // identical to those from the remote FD. Thus, we truncate to the\n\t // length of the remote file.\n\t if (!flag.isAppendable()) {\n\t fd.truncate(data.length, function () {\n\t applyStatChanges();\n\t });\n\t }\n\t else {\n\t applyStatChanges();\n\t }\n\t }\n\t });\n\t }\n\t else {\n\t cb(null, fd);\n\t }\n\t};\n\t/**\n\t * @hidden\n\t */\n\tfunction apiErrorLocal2Remote(e) {\n\t return {\n\t type: SpecialArgType.API_ERROR,\n\t errorData: bufferToTransferrableObject(e.writeToBuffer())\n\t };\n\t}\n\t/**\n\t * @hidden\n\t */\n\tfunction apiErrorRemote2Local(e) {\n\t return ApiError.fromBuffer(transferrableObjectToBuffer(e.errorData));\n\t}\n\t/**\n\t * @hidden\n\t */\n\tfunction errorLocal2Remote(e) {\n\t return {\n\t type: SpecialArgType.ERROR,\n\t name: e.name,\n\t message: e.message,\n\t stack: e.stack\n\t };\n\t}\n\t/**\n\t * @hidden\n\t */\n\tfunction errorRemote2Local(e) {\n\t var cnstr = global$1[e.name];\n\t if (typeof (cnstr) !== 'function') {\n\t cnstr = Error;\n\t }\n\t var err = new cnstr(e.message);\n\t err.stack = e.stack;\n\t return err;\n\t}\n\t/**\n\t * @hidden\n\t */\n\tfunction statsLocal2Remote(stats) {\n\t return {\n\t type: SpecialArgType.STATS,\n\t statsData: bufferToTransferrableObject(stats.toBuffer())\n\t };\n\t}\n\t/**\n\t * @hidden\n\t */\n\tfunction statsRemote2Local(stats) {\n\t return Stats.fromBuffer(transferrableObjectToBuffer(stats.statsData));\n\t}\n\t/**\n\t * @hidden\n\t */\n\tfunction fileFlagLocal2Remote(flag) {\n\t return {\n\t type: SpecialArgType.FILEFLAG,\n\t flagStr: flag.getFlagString()\n\t };\n\t}\n\t/**\n\t * @hidden\n\t */\n\tfunction fileFlagRemote2Local(remoteFlag) {\n\t return FileFlag.getFileFlag(remoteFlag.flagStr);\n\t}\n\t/**\n\t * @hidden\n\t */\n\tfunction bufferToTransferrableObject(buff) {\n\t return buffer2ArrayBuffer(buff);\n\t}\n\t/**\n\t * @hidden\n\t */\n\tfunction transferrableObjectToBuffer(buff) {\n\t return arrayBuffer2Buffer(buff);\n\t}\n\t/**\n\t * @hidden\n\t */\n\tfunction bufferLocal2Remote(buff) {\n\t return {\n\t type: SpecialArgType.BUFFER,\n\t data: bufferToTransferrableObject(buff)\n\t };\n\t}\n\t/**\n\t * @hidden\n\t */\n\tfunction bufferRemote2Local(buffArg) {\n\t return transferrableObjectToBuffer(buffArg.data);\n\t}\n\t/**\n\t * @hidden\n\t */\n\tfunction isAPIRequest(data) {\n\t return data && typeof data === 'object' && data.hasOwnProperty('browserfsMessage') && data['browserfsMessage'];\n\t}\n\t/**\n\t * @hidden\n\t */\n\tfunction isAPIResponse(data) {\n\t return data && typeof data === 'object' && data.hasOwnProperty('browserfsMessage') && data['browserfsMessage'];\n\t}\n\t/**\n\t * Represents a remote file in a different worker/thread.\n\t */\n\tvar WorkerFile = (function (PreloadFile$$1) {\n\t function WorkerFile(_fs, _path, _flag, _stat, remoteFdId, contents) {\n\t PreloadFile$$1.call(this, _fs, _path, _flag, _stat, contents);\n\t this._remoteFdId = remoteFdId;\n\t }\n\t\n\t if ( PreloadFile$$1 ) WorkerFile.__proto__ = PreloadFile$$1;\n\t WorkerFile.prototype = Object.create( PreloadFile$$1 && PreloadFile$$1.prototype );\n\t WorkerFile.prototype.constructor = WorkerFile;\n\t WorkerFile.prototype.getRemoteFdId = function getRemoteFdId () {\n\t return this._remoteFdId;\n\t };\n\t /**\n\t * @hidden\n\t */\n\t WorkerFile.prototype.toRemoteArg = function toRemoteArg () {\n\t return {\n\t type: SpecialArgType.FD,\n\t id: this._remoteFdId,\n\t data: bufferToTransferrableObject(this.getBuffer()),\n\t stat: bufferToTransferrableObject(this.getStats().toBuffer()),\n\t path: this.getPath(),\n\t flag: this.getFlag().getFlagString()\n\t };\n\t };\n\t WorkerFile.prototype.sync = function sync (cb) {\n\t this._syncClose('sync', cb);\n\t };\n\t WorkerFile.prototype.close = function close (cb) {\n\t this._syncClose('close', cb);\n\t };\n\t WorkerFile.prototype._syncClose = function _syncClose (type, cb) {\n\t var this$1 = this;\n\t\n\t if (this.isDirty()) {\n\t this._fs.syncClose(type, this, function (e) {\n\t if (!e) {\n\t this$1.resetDirty();\n\t }\n\t cb(e);\n\t });\n\t }\n\t else {\n\t cb();\n\t }\n\t };\n\t\n\t return WorkerFile;\n\t}(PreloadFile));\n\t/**\n\t * WorkerFS lets you access a BrowserFS instance that is running in a different\n\t * JavaScript context (e.g. access BrowserFS in one of your WebWorkers, or\n\t * access BrowserFS running on the main page from a WebWorker).\n\t *\n\t * For example, to have a WebWorker access files in the main browser thread,\n\t * do the following:\n\t *\n\t * MAIN BROWSER THREAD:\n\t *\n\t * ```javascript\n\t * // Listen for remote file system requests.\n\t * BrowserFS.FileSystem.WorkerFS.attachRemoteListener(webWorkerObject);\n\t * ```\n\t *\n\t * WEBWORKER THREAD:\n\t *\n\t * ```javascript\n\t * // Set the remote file system as the root file system.\n\t * BrowserFS.configure({ fs: \"WorkerFS\", options: { worker: self }}, function(e) {\n\t * // Ready!\n\t * });\n\t * ```\n\t *\n\t * Note that synchronous operations are not permitted on the WorkerFS, regardless\n\t * of the configuration option of the remote FS.\n\t */\n\tvar WorkerFS = (function (BaseFileSystem$$1) {\n\t function WorkerFS(worker, deprecateMsg) {\n\t var this$1 = this;\n\t if ( deprecateMsg === void 0 ) deprecateMsg = true;\n\t\n\t BaseFileSystem$$1.call(this);\n\t this._callbackConverter = new CallbackArgumentConverter();\n\t this._isInitialized = false;\n\t this._isReadOnly = false;\n\t this._supportLinks = false;\n\t this._supportProps = false;\n\t this._worker = worker;\n\t deprecationMessage(deprecateMsg, WorkerFS.Name, { worker: \"Web Worker instance\" });\n\t this._worker.addEventListener('message', function (e) {\n\t var resp = e.data;\n\t if (isAPIResponse(resp)) {\n\t var i;\n\t var args = resp.args;\n\t var fixedArgs = new Array(args.length);\n\t // Dispatch event to correct id.\n\t for (i = 0; i < fixedArgs.length; i++) {\n\t fixedArgs[i] = this$1._argRemote2Local(args[i]);\n\t }\n\t this$1._callbackConverter.toLocalArg(resp.cbId).apply(null, fixedArgs);\n\t }\n\t });\n\t }\n\t\n\t if ( BaseFileSystem$$1 ) WorkerFS.__proto__ = BaseFileSystem$$1;\n\t WorkerFS.prototype = Object.create( BaseFileSystem$$1 && BaseFileSystem$$1.prototype );\n\t WorkerFS.prototype.constructor = WorkerFS;\n\t WorkerFS.Create = function Create (opts, cb) {\n\t var fs = new WorkerFS(opts.worker, false);\n\t fs.initialize(function () {\n\t cb(null, fs);\n\t });\n\t };\n\t WorkerFS.isAvailable = function isAvailable () {\n\t return typeof (importScripts) !== 'undefined' || typeof (Worker) !== 'undefined';\n\t };\n\t /**\n\t * Attaches a listener to the remote worker for file system requests.\n\t */\n\t WorkerFS.attachRemoteListener = function attachRemoteListener (worker) {\n\t var fdConverter = new FileDescriptorArgumentConverter();\n\t function argLocal2Remote(arg, requestArgs, cb) {\n\t switch (typeof arg) {\n\t case 'object':\n\t if (arg instanceof Stats) {\n\t cb(null, statsLocal2Remote(arg));\n\t }\n\t else if (arg instanceof ApiError) {\n\t cb(null, apiErrorLocal2Remote(arg));\n\t }\n\t else if (arg instanceof BaseFile) {\n\t // Pass in p and flags from original request.\n\t cb(null, fdConverter.toRemoteArg(arg, requestArgs[0], requestArgs[1], cb));\n\t }\n\t else if (arg instanceof FileFlag) {\n\t cb(null, fileFlagLocal2Remote(arg));\n\t }\n\t else if (arg instanceof Buffer) {\n\t cb(null, bufferLocal2Remote(arg));\n\t }\n\t else if (arg instanceof Error) {\n\t cb(null, errorLocal2Remote(arg));\n\t }\n\t else {\n\t cb(null, arg);\n\t }\n\t break;\n\t default:\n\t cb(null, arg);\n\t break;\n\t }\n\t }\n\t function argRemote2Local(arg, fixedRequestArgs) {\n\t if (!arg) {\n\t return arg;\n\t }\n\t switch (typeof arg) {\n\t case 'object':\n\t if (typeof arg['type'] === 'number') {\n\t var specialArg = arg;\n\t switch (specialArg.type) {\n\t case SpecialArgType.CB:\n\t var cbId = arg.id;\n\t return function () {\n\t var arguments$1 = arguments;\n\t\n\t var i;\n\t var fixedArgs = new Array(arguments.length);\n\t var message, countdown = arguments.length;\n\t function abortAndSendError(err) {\n\t if (countdown > 0) {\n\t countdown = -1;\n\t message = {\n\t browserfsMessage: true,\n\t cbId: cbId,\n\t args: [apiErrorLocal2Remote(err)]\n\t };\n\t worker.postMessage(message);\n\t }\n\t }\n\t for (i = 0; i < arguments.length; i++) {\n\t // Capture i and argument.\n\t (function (i, arg) {\n\t argLocal2Remote(arg, fixedRequestArgs, function (err, fixedArg) {\n\t fixedArgs[i] = fixedArg;\n\t if (err) {\n\t abortAndSendError(err);\n\t }\n\t else if (--countdown === 0) {\n\t message = {\n\t browserfsMessage: true,\n\t cbId: cbId,\n\t args: fixedArgs\n\t };\n\t worker.postMessage(message);\n\t }\n\t });\n\t })(i, arguments$1[i]);\n\t }\n\t if (arguments.length === 0) {\n\t message = {\n\t browserfsMessage: true,\n\t cbId: cbId,\n\t args: fixedArgs\n\t };\n\t worker.postMessage(message);\n\t }\n\t };\n\t case SpecialArgType.API_ERROR:\n\t return apiErrorRemote2Local(specialArg);\n\t case SpecialArgType.STATS:\n\t return statsRemote2Local(specialArg);\n\t case SpecialArgType.FILEFLAG:\n\t return fileFlagRemote2Local(specialArg);\n\t case SpecialArgType.BUFFER:\n\t return bufferRemote2Local(specialArg);\n\t case SpecialArgType.ERROR:\n\t return errorRemote2Local(specialArg);\n\t default:\n\t // No idea what this is.\n\t return arg;\n\t }\n\t }\n\t else {\n\t return arg;\n\t }\n\t default:\n\t return arg;\n\t }\n\t }\n\t worker.addEventListener('message', function (e) {\n\t var request = e.data;\n\t if (isAPIRequest(request)) {\n\t var args = request.args, fixedArgs = new Array(args.length);\n\t switch (request.method) {\n\t case 'close':\n\t case 'sync':\n\t (function () {\n\t // File descriptor-relative methods.\n\t var remoteCb = args[1];\n\t fdConverter.applyFdAPIRequest(request, function (err) {\n\t // Send response.\n\t var response = {\n\t browserfsMessage: true,\n\t cbId: remoteCb.id,\n\t args: err ? [apiErrorLocal2Remote(err)] : []\n\t };\n\t worker.postMessage(response);\n\t });\n\t })();\n\t break;\n\t case 'probe':\n\t (function () {\n\t var rootFs = _fsMock.getRootFS(), remoteCb = args[1], probeResponse = {\n\t type: SpecialArgType.PROBE,\n\t isReadOnly: rootFs.isReadOnly(),\n\t supportsLinks: rootFs.supportsLinks(),\n\t supportsProps: rootFs.supportsProps()\n\t }, response = {\n\t browserfsMessage: true,\n\t cbId: remoteCb.id,\n\t args: [probeResponse]\n\t };\n\t worker.postMessage(response);\n\t })();\n\t break;\n\t default:\n\t // File system methods.\n\t for (var i = 0; i < args.length; i++) {\n\t fixedArgs[i] = argRemote2Local(args[i], fixedArgs);\n\t }\n\t var rootFS = _fsMock.getRootFS();\n\t rootFS[request.method].apply(rootFS, fixedArgs);\n\t break;\n\t }\n\t }\n\t });\n\t };\n\t WorkerFS.prototype.getName = function getName () {\n\t return WorkerFS.Name;\n\t };\n\t /**\n\t * **Deprecated. Please use WorkerFS.Create() method to construct and initialize WorkerFS instances.**\n\t *\n\t * Called once both local and remote sides are set up.\n\t */\n\t WorkerFS.prototype.initialize = function initialize (cb) {\n\t var this$1 = this;\n\t\n\t if (!this._isInitialized) {\n\t var message = {\n\t browserfsMessage: true,\n\t method: 'probe',\n\t args: [this._argLocal2Remote(emptyBuffer()), this._callbackConverter.toRemoteArg(function (probeResponse) {\n\t this$1._isInitialized = true;\n\t this$1._isReadOnly = probeResponse.isReadOnly;\n\t this$1._supportLinks = probeResponse.supportsLinks;\n\t this$1._supportProps = probeResponse.supportsProps;\n\t cb();\n\t })]\n\t };\n\t this._worker.postMessage(message);\n\t }\n\t else {\n\t cb();\n\t }\n\t };\n\t WorkerFS.prototype.isReadOnly = function isReadOnly () { return this._isReadOnly; };\n\t WorkerFS.prototype.supportsSynch = function supportsSynch () { return false; };\n\t WorkerFS.prototype.supportsLinks = function supportsLinks () { return this._supportLinks; };\n\t WorkerFS.prototype.supportsProps = function supportsProps () { return this._supportProps; };\n\t WorkerFS.prototype.rename = function rename (oldPath, newPath, cb) {\n\t this._rpc('rename', arguments);\n\t };\n\t WorkerFS.prototype.stat = function stat (p, isLstat, cb) {\n\t this._rpc('stat', arguments);\n\t };\n\t WorkerFS.prototype.open = function open (p, flag, mode, cb) {\n\t this._rpc('open', arguments);\n\t };\n\t WorkerFS.prototype.unlink = function unlink (p, cb) {\n\t this._rpc('unlink', arguments);\n\t };\n\t WorkerFS.prototype.rmdir = function rmdir (p, cb) {\n\t this._rpc('rmdir', arguments);\n\t };\n\t WorkerFS.prototype.mkdir = function mkdir (p, mode, cb) {\n\t this._rpc('mkdir', arguments);\n\t };\n\t WorkerFS.prototype.readdir = function readdir (p, cb) {\n\t this._rpc('readdir', arguments);\n\t };\n\t WorkerFS.prototype.exists = function exists (p, cb) {\n\t this._rpc('exists', arguments);\n\t };\n\t WorkerFS.prototype.realpath = function realpath (p, cache, cb) {\n\t this._rpc('realpath', arguments);\n\t };\n\t WorkerFS.prototype.truncate = function truncate (p, len, cb) {\n\t this._rpc('truncate', arguments);\n\t };\n\t WorkerFS.prototype.readFile = function readFile (fname, encoding, flag, cb) {\n\t this._rpc('readFile', arguments);\n\t };\n\t WorkerFS.prototype.writeFile = function writeFile (fname, data, encoding, flag, mode, cb) {\n\t this._rpc('writeFile', arguments);\n\t };\n\t WorkerFS.prototype.appendFile = function appendFile (fname, data, encoding, flag, mode, cb) {\n\t this._rpc('appendFile', arguments);\n\t };\n\t WorkerFS.prototype.chmod = function chmod (p, isLchmod, mode, cb) {\n\t this._rpc('chmod', arguments);\n\t };\n\t WorkerFS.prototype.chown = function chown (p, isLchown, uid, gid, cb) {\n\t this._rpc('chown', arguments);\n\t };\n\t WorkerFS.prototype.utimes = function utimes (p, atime, mtime, cb) {\n\t this._rpc('utimes', arguments);\n\t };\n\t WorkerFS.prototype.link = function link (srcpath, dstpath, cb) {\n\t this._rpc('link', arguments);\n\t };\n\t WorkerFS.prototype.symlink = function symlink (srcpath, dstpath, type, cb) {\n\t this._rpc('symlink', arguments);\n\t };\n\t WorkerFS.prototype.readlink = function readlink (p, cb) {\n\t this._rpc('readlink', arguments);\n\t };\n\t WorkerFS.prototype.syncClose = function syncClose (method, fd, cb) {\n\t this._worker.postMessage({\n\t browserfsMessage: true,\n\t method: method,\n\t args: [fd.toRemoteArg(), this._callbackConverter.toRemoteArg(cb)]\n\t });\n\t };\n\t WorkerFS.prototype._argRemote2Local = function _argRemote2Local (arg) {\n\t if (!arg) {\n\t return arg;\n\t }\n\t switch (typeof arg) {\n\t case 'object':\n\t if (typeof arg['type'] === 'number') {\n\t var specialArg = arg;\n\t switch (specialArg.type) {\n\t case SpecialArgType.API_ERROR:\n\t return apiErrorRemote2Local(specialArg);\n\t case SpecialArgType.FD:\n\t var fdArg = specialArg;\n\t return new WorkerFile(this, fdArg.path, FileFlag.getFileFlag(fdArg.flag), Stats.fromBuffer(transferrableObjectToBuffer(fdArg.stat)), fdArg.id, transferrableObjectToBuffer(fdArg.data));\n\t case SpecialArgType.STATS:\n\t return statsRemote2Local(specialArg);\n\t case SpecialArgType.FILEFLAG:\n\t return fileFlagRemote2Local(specialArg);\n\t case SpecialArgType.BUFFER:\n\t return bufferRemote2Local(specialArg);\n\t case SpecialArgType.ERROR:\n\t return errorRemote2Local(specialArg);\n\t default:\n\t return arg;\n\t }\n\t }\n\t else {\n\t return arg;\n\t }\n\t default:\n\t return arg;\n\t }\n\t };\n\t WorkerFS.prototype._rpc = function _rpc (methodName, args) {\n\t var this$1 = this;\n\t\n\t var fixedArgs = new Array(args.length);\n\t for (var i = 0; i < args.length; i++) {\n\t fixedArgs[i] = this$1._argLocal2Remote(args[i]);\n\t }\n\t var message = {\n\t browserfsMessage: true,\n\t method: methodName,\n\t args: fixedArgs\n\t };\n\t this._worker.postMessage(message);\n\t };\n\t /**\n\t * Converts a local argument into a remote argument. Public so WorkerFile objects can call it.\n\t */\n\t WorkerFS.prototype._argLocal2Remote = function _argLocal2Remote (arg) {\n\t if (!arg) {\n\t return arg;\n\t }\n\t switch (typeof arg) {\n\t case \"object\":\n\t if (arg instanceof Stats) {\n\t return statsLocal2Remote(arg);\n\t }\n\t else if (arg instanceof ApiError) {\n\t return apiErrorLocal2Remote(arg);\n\t }\n\t else if (arg instanceof WorkerFile) {\n\t return arg.toRemoteArg();\n\t }\n\t else if (arg instanceof FileFlag) {\n\t return fileFlagLocal2Remote(arg);\n\t }\n\t else if (arg instanceof Buffer) {\n\t return bufferLocal2Remote(arg);\n\t }\n\t else if (arg instanceof Error) {\n\t return errorLocal2Remote(arg);\n\t }\n\t else {\n\t return \"Unknown argument\";\n\t }\n\t case \"function\":\n\t return this._callbackConverter.toRemoteArg(arg);\n\t default:\n\t return arg;\n\t }\n\t };\n\t\n\t return WorkerFS;\n\t}(BaseFileSystem));\n\t\n\tWorkerFS.Name = \"WorkerFS\";\n\tWorkerFS.Options = {\n\t worker: {\n\t type: \"object\",\n\t description: \"The target worker that you want to connect to, or the current worker if in a worker context.\",\n\t validator: function (v, cb) {\n\t // Check for a `postMessage` function.\n\t if (v['postMessage']) {\n\t cb();\n\t }\n\t else {\n\t cb(new ApiError(ErrorCode.EINVAL, \"option must be a Web Worker instance.\"));\n\t }\n\t }\n\t }\n\t};\n\t\n\t/**\n\t * Contains utility methods for performing a variety of tasks with\n\t * XmlHttpRequest across browsers.\n\t */\n\tfunction asyncDownloadFileModern(p, type, cb) {\n\t var req = new XMLHttpRequest();\n\t req.open('GET', p, true);\n\t var jsonSupported = true;\n\t switch (type) {\n\t case 'buffer':\n\t req.responseType = 'arraybuffer';\n\t break;\n\t case 'json':\n\t // Some browsers don't support the JSON response type.\n\t // They either reset responseType, or throw an exception.\n\t // @see https://github.com/Modernizr/Modernizr/blob/master/src/testXhrType.js\n\t try {\n\t req.responseType = 'json';\n\t jsonSupported = req.responseType === 'json';\n\t }\n\t catch (e) {\n\t jsonSupported = false;\n\t }\n\t break;\n\t default:\n\t return cb(new ApiError(ErrorCode.EINVAL, \"Invalid download type: \" + type));\n\t }\n\t req.onreadystatechange = function (e) {\n\t if (req.readyState === 4) {\n\t if (req.status === 200) {\n\t switch (type) {\n\t case 'buffer':\n\t // XXX: WebKit-based browsers return *null* when XHRing an empty file.\n\t return cb(null, req.response ? Buffer.from(req.response) : emptyBuffer());\n\t case 'json':\n\t if (jsonSupported) {\n\t return cb(null, req.response);\n\t }\n\t else {\n\t return cb(null, JSON.parse(req.responseText));\n\t }\n\t }\n\t }\n\t else {\n\t return cb(new ApiError(req.status, \"XHR error.\"));\n\t }\n\t }\n\t };\n\t req.send();\n\t}\n\tfunction syncDownloadFileModern(p, type) {\n\t var req = new XMLHttpRequest();\n\t req.open('GET', p, false);\n\t // On most platforms, we cannot set the responseType of synchronous downloads.\n\t // @todo Test for this; IE10 allows this, as do older versions of Chrome/FF.\n\t var data = null;\n\t var err = null;\n\t // Classic hack to download binary data as a string.\n\t req.overrideMimeType('text/plain; charset=x-user-defined');\n\t req.onreadystatechange = function (e) {\n\t if (req.readyState === 4) {\n\t if (req.status === 200) {\n\t switch (type) {\n\t case 'buffer':\n\t // Convert the text into a buffer.\n\t var text = req.responseText;\n\t data = Buffer.alloc(text.length);\n\t // Throw away the upper bits of each character.\n\t for (var i = 0; i < text.length; i++) {\n\t // This will automatically throw away the upper bit of each\n\t // character for us.\n\t data[i] = text.charCodeAt(i);\n\t }\n\t return;\n\t case 'json':\n\t data = JSON.parse(req.responseText);\n\t return;\n\t }\n\t }\n\t else {\n\t err = new ApiError(req.status, \"XHR error.\");\n\t return;\n\t }\n\t }\n\t };\n\t req.send();\n\t if (err) {\n\t throw err;\n\t }\n\t return data;\n\t}\n\tfunction syncDownloadFileIE10(p, type) {\n\t var req = new XMLHttpRequest();\n\t req.open('GET', p, false);\n\t switch (type) {\n\t case 'buffer':\n\t req.responseType = 'arraybuffer';\n\t break;\n\t case 'json':\n\t // IE10 does not support the JSON type.\n\t break;\n\t default:\n\t throw new ApiError(ErrorCode.EINVAL, \"Invalid download type: \" + type);\n\t }\n\t var data;\n\t var err;\n\t req.onreadystatechange = function (e) {\n\t if (req.readyState === 4) {\n\t if (req.status === 200) {\n\t switch (type) {\n\t case 'buffer':\n\t data = Buffer.from(req.response);\n\t break;\n\t case 'json':\n\t data = JSON.parse(req.response);\n\t break;\n\t }\n\t }\n\t else {\n\t err = new ApiError(req.status, \"XHR error.\");\n\t }\n\t }\n\t };\n\t req.send();\n\t if (err) {\n\t throw err;\n\t }\n\t return data;\n\t}\n\t/**\n\t * @hidden\n\t */\n\tfunction getFileSize(async, p, cb) {\n\t var req = new XMLHttpRequest();\n\t req.open('HEAD', p, async);\n\t req.onreadystatechange = function (e) {\n\t if (req.readyState === 4) {\n\t if (req.status === 200) {\n\t try {\n\t return cb(null, parseInt(req.getResponseHeader('Content-Length') || '-1', 10));\n\t }\n\t catch (e) {\n\t // In the event that the header isn't present or there is an error...\n\t return cb(new ApiError(ErrorCode.EIO, \"XHR HEAD error: Could not read content-length.\"));\n\t }\n\t }\n\t else {\n\t return cb(new ApiError(req.status, \"XHR HEAD error.\"));\n\t }\n\t }\n\t };\n\t req.send();\n\t}\n\t/**\n\t * Asynchronously download a file as a buffer or a JSON object.\n\t * Note that the third function signature with a non-specialized type is\n\t * invalid, but TypeScript requires it when you specialize string arguments to\n\t * constants.\n\t * @hidden\n\t */\n\tvar asyncDownloadFile = asyncDownloadFileModern;\n\t/**\n\t * Synchronously download a file as a buffer or a JSON object.\n\t * Note that the third function signature with a non-specialized type is\n\t * invalid, but TypeScript requires it when you specialize string arguments to\n\t * constants.\n\t * @hidden\n\t */\n\tvar syncDownloadFile = (isIE && typeof Blob !== 'undefined') ? syncDownloadFileIE10 : syncDownloadFileModern;\n\t/**\n\t * Synchronously retrieves the size of the given file in bytes.\n\t * @hidden\n\t */\n\tfunction getFileSizeSync(p) {\n\t var rv = -1;\n\t getFileSize(false, p, function (err, size) {\n\t if (err) {\n\t throw err;\n\t }\n\t rv = size;\n\t });\n\t return rv;\n\t}\n\t/**\n\t * Asynchronously retrieves the size of the given file in bytes.\n\t * @hidden\n\t */\n\tfunction getFileSizeAsync(p, cb) {\n\t getFileSize(true, p, cb);\n\t}\n\t\n\t/**\n\t * A simple class for storing a filesystem index. Assumes that all paths passed\n\t * to it are *absolute* paths.\n\t *\n\t * Can be used as a partial or a full index, although care must be taken if used\n\t * for the former purpose, especially when directories are concerned.\n\t */\n\tvar FileIndex = function FileIndex() {\n\t // _index is a single-level key,value store that maps *directory* paths to\n\t // DirInodes. File information is only contained in DirInodes themselves.\n\t this._index = {};\n\t // Create the root directory.\n\t this.addPath('/', new DirInode());\n\t};\n\t/**\n\t * Static method for constructing indices from a JSON listing.\n\t * @param listing Directory listing generated by tools/XHRIndexer.coffee\n\t * @return A new FileIndex object.\n\t */\n\tFileIndex.fromListing = function fromListing (listing) {\n\t var idx = new FileIndex();\n\t // Add a root DirNode.\n\t var rootInode = new DirInode();\n\t idx._index['/'] = rootInode;\n\t var queue = [['', listing, rootInode]];\n\t while (queue.length > 0) {\n\t var inode = (void 0);\n\t var next = queue.pop();\n\t var pwd = next[0];\n\t var tree = next[1];\n\t var parent = next[2];\n\t for (var node in tree) {\n\t if (tree.hasOwnProperty(node)) {\n\t var children = tree[node];\n\t var name = pwd + \"/\" + node;\n\t if (children) {\n\t idx._index[name] = inode = new DirInode();\n\t queue.push([name, children, inode]);\n\t }\n\t else {\n\t // This inode doesn't have correct size information, noted with -1.\n\t inode = new FileInode(new Stats(FileType.FILE, -1, 0x16D));\n\t }\n\t if (parent) {\n\t parent._ls[node] = inode;\n\t }\n\t }\n\t }\n\t }\n\t return idx;\n\t};\n\t/**\n\t * Runs the given function over all files in the index.\n\t */\n\tFileIndex.prototype.fileIterator = function fileIterator (cb) {\n\t var this$1 = this;\n\t\n\t for (var path$$1 in this$1._index) {\n\t if (this$1._index.hasOwnProperty(path$$1)) {\n\t var dir = this$1._index[path$$1];\n\t var files = dir.getListing();\n\t for (var i = 0, list = files; i < list.length; i += 1) {\n\t var file = list[i];\n\t\n\t var item = dir.getItem(file);\n\t if (isFileInode(item)) {\n\t cb(item.getData());\n\t }\n\t }\n\t }\n\t }\n\t};\n\t/**\n\t * Adds the given absolute path to the index if it is not already in the index.\n\t * Creates any needed parent directories.\n\t * @param path The path to add to the index.\n\t * @param inode The inode for the\n\t * path to add.\n\t * @return 'True' if it was added or already exists, 'false' if there\n\t * was an issue adding it (e.g. item in path is a file, item exists but is\n\t * different).\n\t * @todo If adding fails and implicitly creates directories, we do not clean up\n\t * the new empty directories.\n\t */\n\tFileIndex.prototype.addPath = function addPath (path$$1, inode) {\n\t if (!inode) {\n\t throw new Error('Inode must be specified');\n\t }\n\t if (path$$1[0] !== '/') {\n\t throw new Error('Path must be absolute, got: ' + path$$1);\n\t }\n\t // Check if it already exists.\n\t if (this._index.hasOwnProperty(path$$1)) {\n\t return this._index[path$$1] === inode;\n\t }\n\t var splitPath = this._split_path(path$$1);\n\t var dirpath = splitPath[0];\n\t var itemname = splitPath[1];\n\t // Try to add to its parent directory first.\n\t var parent = this._index[dirpath];\n\t if (parent === undefined && path$$1 !== '/') {\n\t // Create parent.\n\t parent = new DirInode();\n\t if (!this.addPath(dirpath, parent)) {\n\t return false;\n\t }\n\t }\n\t // Add myself to my parent.\n\t if (path$$1 !== '/') {\n\t if (!parent.addItem(itemname, inode)) {\n\t return false;\n\t }\n\t }\n\t // If I'm a directory, add myself to the index.\n\t if (isDirInode(inode)) {\n\t this._index[path$$1] = inode;\n\t }\n\t return true;\n\t};\n\t/**\n\t * Adds the given absolute path to the index if it is not already in the index.\n\t * The path is added without special treatment (no joining of adjacent separators, etc).\n\t * Creates any needed parent directories.\n\t * @param path The path to add to the index.\n\t * @param inode The inode for the\n\t * path to add.\n\t * @return 'True' if it was added or already exists, 'false' if there\n\t * was an issue adding it (e.g. item in path is a file, item exists but is\n\t * different).\n\t * @todo If adding fails and implicitly creates directories, we do not clean up\n\t * the new empty directories.\n\t */\n\tFileIndex.prototype.addPathFast = function addPathFast (path$$1, inode) {\n\t var itemNameMark = path$$1.lastIndexOf('/');\n\t var parentPath = itemNameMark === 0 ? \"/\" : path$$1.substring(0, itemNameMark);\n\t var itemName = path$$1.substring(itemNameMark + 1);\n\t // Try to add to its parent directory first.\n\t var parent = this._index[parentPath];\n\t if (parent === undefined) {\n\t // Create parent.\n\t parent = new DirInode();\n\t this.addPathFast(parentPath, parent);\n\t }\n\t if (!parent.addItem(itemName, inode)) {\n\t return false;\n\t }\n\t // If adding a directory, add to the index as well.\n\t if (inode.isDir()) {\n\t this._index[path$$1] = inode;\n\t }\n\t return true;\n\t};\n\t/**\n\t * Removes the given path. Can be a file or a directory.\n\t * @return The removed item,\n\t * or null if it did not exist.\n\t */\n\tFileIndex.prototype.removePath = function removePath (path$$1) {\n\t var this$1 = this;\n\t\n\t var splitPath = this._split_path(path$$1);\n\t var dirpath = splitPath[0];\n\t var itemname = splitPath[1];\n\t // Try to remove it from its parent directory first.\n\t var parent = this._index[dirpath];\n\t if (parent === undefined) {\n\t return null;\n\t }\n\t // Remove myself from my parent.\n\t var inode = parent.remItem(itemname);\n\t if (inode === null) {\n\t return null;\n\t }\n\t // If I'm a directory, remove myself from the index, and remove my children.\n\t if (isDirInode(inode)) {\n\t var children = inode.getListing();\n\t for (var i = 0, list = children; i < list.length; i += 1) {\n\t var child = list[i];\n\t\n\t this$1.removePath(path$$1 + '/' + child);\n\t }\n\t // Remove the directory from the index, unless it's the root.\n\t if (path$$1 !== '/') {\n\t delete this._index[path$$1];\n\t }\n\t }\n\t return inode;\n\t};\n\t/**\n\t * Retrieves the directory listing of the given path.\n\t * @return An array of files in the given path, or 'null' if it does not exist.\n\t */\n\tFileIndex.prototype.ls = function ls (path$$1) {\n\t var item = this._index[path$$1];\n\t if (item === undefined) {\n\t return null;\n\t }\n\t return item.getListing();\n\t};\n\t/**\n\t * Returns the inode of the given item.\n\t * @return Returns null if the item does not exist.\n\t */\n\tFileIndex.prototype.getInode = function getInode (path$$1) {\n\t var splitPath = this._split_path(path$$1);\n\t var dirpath = splitPath[0];\n\t var itemname = splitPath[1];\n\t // Retrieve from its parent directory.\n\t var parent = this._index[dirpath];\n\t if (parent === undefined) {\n\t return null;\n\t }\n\t // Root case\n\t if (dirpath === path$$1) {\n\t return parent;\n\t }\n\t return parent.getItem(itemname);\n\t};\n\t/**\n\t * Split into a (directory path, item name) pair\n\t */\n\tFileIndex.prototype._split_path = function _split_path (p) {\n\t var dirpath = path.dirname(p);\n\t var itemname = p.substr(dirpath.length + (dirpath === \"/\" ? 0 : 1));\n\t return [dirpath, itemname];\n\t};\n\t/**\n\t * Inode for a file. Stores an arbitrary (filesystem-specific) data payload.\n\t */\n\tvar FileInode = function FileInode(data) {\n\t this.data = data;\n\t};\n\tFileInode.prototype.isFile = function isFile () { return true; };\n\tFileInode.prototype.isDir = function isDir () { return false; };\n\tFileInode.prototype.getData = function getData () { return this.data; };\n\tFileInode.prototype.setData = function setData (data) { this.data = data; };\n\t/**\n\t * Inode for a directory. Currently only contains the directory listing.\n\t */\n\tvar DirInode = function DirInode(data) {\n\t if ( data === void 0 ) data = null;\n\t\n\t this.data = data;\n\t this._ls = {};\n\t};\n\tDirInode.prototype.isFile = function isFile () {\n\t return false;\n\t};\n\tDirInode.prototype.isDir = function isDir () {\n\t return true;\n\t};\n\tDirInode.prototype.getData = function getData () { return this.data; };\n\t/**\n\t * Return a Stats object for this inode.\n\t * @todo Should probably remove this at some point. This isn't the\n\t * responsibility of the FileIndex.\n\t */\n\tDirInode.prototype.getStats = function getStats () {\n\t return new Stats(FileType.DIRECTORY, 4096, 0x16D);\n\t};\n\t/**\n\t * Returns the directory listing for this directory. Paths in the directory are\n\t * relative to the directory's path.\n\t * @return The directory listing for this directory.\n\t */\n\tDirInode.prototype.getListing = function getListing () {\n\t return Object.keys(this._ls);\n\t};\n\t/**\n\t * Returns the inode for the indicated item, or null if it does not exist.\n\t * @param p Name of item in this directory.\n\t */\n\tDirInode.prototype.getItem = function getItem (p) {\n\t var item = this._ls[p];\n\t return item ? item : null;\n\t};\n\t/**\n\t * Add the given item to the directory listing. Note that the given inode is\n\t * not copied, and will be mutated by the DirInode if it is a DirInode.\n\t * @param p Item name to add to the directory listing.\n\t * @param inode The inode for the\n\t * item to add to the directory inode.\n\t * @return True if it was added, false if it already existed.\n\t */\n\tDirInode.prototype.addItem = function addItem (p, inode) {\n\t if (p in this._ls) {\n\t return false;\n\t }\n\t this._ls[p] = inode;\n\t return true;\n\t};\n\t/**\n\t * Removes the given item from the directory listing.\n\t * @param p Name of item to remove from the directory listing.\n\t * @return Returns the item\n\t * removed, or null if the item did not exist.\n\t */\n\tDirInode.prototype.remItem = function remItem (p) {\n\t var item = this._ls[p];\n\t if (item === undefined) {\n\t return null;\n\t }\n\t delete this._ls[p];\n\t return item;\n\t};\n\t/**\n\t * @hidden\n\t */\n\tfunction isFileInode(inode) {\n\t return !!inode && inode.isFile();\n\t}\n\t/**\n\t * @hidden\n\t */\n\tfunction isDirInode(inode) {\n\t return !!inode && inode.isDir();\n\t}\n\t\n\t/**\n\t * Try to convert the given buffer into a string, and pass it to the callback.\n\t * Optimization that removes the needed try/catch into a helper function, as\n\t * this is an uncommon case.\n\t * @hidden\n\t */\n\tfunction tryToString(buff, encoding, cb) {\n\t try {\n\t cb(null, buff.toString(encoding));\n\t }\n\t catch (e) {\n\t cb(e);\n\t }\n\t}\n\t/**\n\t * A simple filesystem backed by XMLHttpRequests. You must create a directory listing using the\n\t * `make_xhrfs_index` tool provided by BrowserFS.\n\t *\n\t * If you install BrowserFS globally with `npm i -g browserfs`, you can generate a listing by\n\t * running `make_xhrfs_index` in your terminal in the directory you would like to index:\n\t *\n\t * ```\n\t * make_xhrfs_index > index.json\n\t * ```\n\t *\n\t * Listings objects look like the following:\n\t *\n\t * ```json\n\t * {\n\t * \"home\": {\n\t * \"jvilk\": {\n\t * \"someFile.txt\": null,\n\t * \"someDir\": {\n\t * // Empty directory\n\t * }\n\t * }\n\t * }\n\t * }\n\t * ```\n\t *\n\t * *This example has the folder `/home/jvilk` with subfile `someFile.txt` and subfolder `someDir`.*\n\t */\n\tvar XmlHttpRequest = (function (BaseFileSystem$$1) {\n\t function XmlHttpRequest(listingUrlOrObj, prefixUrl, deprecateMsg) {\n\t if ( prefixUrl === void 0 ) prefixUrl = '';\n\t if ( deprecateMsg === void 0 ) deprecateMsg = true;\n\t\n\t BaseFileSystem$$1.call(this);\n\t if (!listingUrlOrObj) {\n\t listingUrlOrObj = 'index.json';\n\t }\n\t // prefix_url must end in a directory separator.\n\t if (prefixUrl.length > 0 && prefixUrl.charAt(prefixUrl.length - 1) !== '/') {\n\t prefixUrl = prefixUrl + '/';\n\t }\n\t this.prefixUrl = prefixUrl;\n\t var listing = null;\n\t if (typeof (listingUrlOrObj) === \"string\") {\n\t listing = this._requestFileSync(listingUrlOrObj, 'json');\n\t if (!listing) {\n\t throw new Error(\"Unable to find listing at URL: ${listingUrlOrObj}\");\n\t }\n\t }\n\t else {\n\t listing = listingUrlOrObj;\n\t }\n\t deprecationMessage(deprecateMsg, XmlHttpRequest.Name, { index: typeof (listingUrlOrObj) === \"string\" ? listingUrlOrObj : \"file index as an object\", baseUrl: prefixUrl });\n\t this._index = FileIndex.fromListing(listing);\n\t }\n\t\n\t if ( BaseFileSystem$$1 ) XmlHttpRequest.__proto__ = BaseFileSystem$$1;\n\t XmlHttpRequest.prototype = Object.create( BaseFileSystem$$1 && BaseFileSystem$$1.prototype );\n\t XmlHttpRequest.prototype.constructor = XmlHttpRequest;\n\t /**\n\t * Construct an XmlHttpRequest file system backend with the given options.\n\t */\n\t XmlHttpRequest.Create = function Create (opts, cb) {\n\t if (opts.index === undefined) {\n\t opts.index = \"index.json\";\n\t }\n\t if (typeof (opts.index) === \"string\") {\n\t XmlHttpRequest.FromURL(opts.index, cb, opts.baseUrl, false);\n\t }\n\t else {\n\t cb(null, new XmlHttpRequest(opts.index, opts.baseUrl, false));\n\t }\n\t };\n\t XmlHttpRequest.isAvailable = function isAvailable () {\n\t return typeof (XMLHttpRequest) !== \"undefined\" && XMLHttpRequest !== null;\n\t };\n\t /**\n\t * **Deprecated. Please use XmlHttpRequest.Create() method instead to construct XmlHttpRequest objects.**\n\t *\n\t * Constructs an XmlHttpRequest object using the directory listing at the given URL.\n\t * Uses the base URL as the URL prefix for fetched files.\n\t * @param cb Called when the file system has been instantiated, or if an error occurs.\n\t */\n\t XmlHttpRequest.FromURL = function FromURL (url, cb, baseUrl, deprecateMsg) {\n\t if ( baseUrl === void 0 ) baseUrl = url.slice(0, url.lastIndexOf('/') + 1);\n\t if ( deprecateMsg === void 0 ) deprecateMsg = true;\n\t\n\t if (deprecateMsg) {\n\t console.warn((\"[XmlHttpRequest] XmlHttpRequest.FromURL() is deprecated and will be removed in the next major release. Please use 'XmlHttpRequest.Create({ index: \\\"\" + url + \"\\\", baseUrl: \\\"\" + baseUrl + \"\\\" }, cb)' instead.\"));\n\t }\n\t asyncDownloadFile(url, \"json\", function (e, data) {\n\t if (e) {\n\t cb(e);\n\t }\n\t else {\n\t cb(null, new XmlHttpRequest(data, baseUrl, false));\n\t }\n\t });\n\t };\n\t XmlHttpRequest.prototype.empty = function empty () {\n\t this._index.fileIterator(function (file) {\n\t file.fileData = null;\n\t });\n\t };\n\t XmlHttpRequest.prototype.getName = function getName () {\n\t return XmlHttpRequest.Name;\n\t };\n\t XmlHttpRequest.prototype.diskSpace = function diskSpace (path$$1, cb) {\n\t // Read-only file system. We could calculate the total space, but that's not\n\t // important right now.\n\t cb(0, 0);\n\t };\n\t XmlHttpRequest.prototype.isReadOnly = function isReadOnly () {\n\t return true;\n\t };\n\t XmlHttpRequest.prototype.supportsLinks = function supportsLinks () {\n\t return false;\n\t };\n\t XmlHttpRequest.prototype.supportsProps = function supportsProps () {\n\t return false;\n\t };\n\t XmlHttpRequest.prototype.supportsSynch = function supportsSynch () {\n\t return true;\n\t };\n\t /**\n\t * Special XHR function: Preload the given file into the index.\n\t * @param [String] path\n\t * @param [BrowserFS.Buffer] buffer\n\t */\n\t XmlHttpRequest.prototype.preloadFile = function preloadFile (path$$1, buffer$$1) {\n\t var inode = this._index.getInode(path$$1);\n\t if (isFileInode(inode)) {\n\t if (inode === null) {\n\t throw ApiError.ENOENT(path$$1);\n\t }\n\t var stats = inode.getData();\n\t stats.size = buffer$$1.length;\n\t stats.fileData = buffer$$1;\n\t }\n\t else {\n\t throw ApiError.EISDIR(path$$1);\n\t }\n\t };\n\t XmlHttpRequest.prototype.stat = function stat (path$$1, isLstat, cb) {\n\t var inode = this._index.getInode(path$$1);\n\t if (inode === null) {\n\t return cb(ApiError.ENOENT(path$$1));\n\t }\n\t var stats;\n\t if (isFileInode(inode)) {\n\t stats = inode.getData();\n\t // At this point, a non-opened file will still have default stats from the listing.\n\t if (stats.size < 0) {\n\t this._requestFileSizeAsync(path$$1, function (e, size) {\n\t if (e) {\n\t return cb(e);\n\t }\n\t stats.size = size;\n\t cb(null, stats.clone());\n\t });\n\t }\n\t else {\n\t cb(null, stats.clone());\n\t }\n\t }\n\t else if (isDirInode(inode)) {\n\t stats = inode.getStats();\n\t cb(null, stats);\n\t }\n\t else {\n\t cb(ApiError.FileError(ErrorCode.EINVAL, path$$1));\n\t }\n\t };\n\t XmlHttpRequest.prototype.statSync = function statSync (path$$1, isLstat) {\n\t var inode = this._index.getInode(path$$1);\n\t if (inode === null) {\n\t throw ApiError.ENOENT(path$$1);\n\t }\n\t var stats;\n\t if (isFileInode(inode)) {\n\t stats = inode.getData();\n\t // At this point, a non-opened file will still have default stats from the listing.\n\t if (stats.size < 0) {\n\t stats.size = this._requestFileSizeSync(path$$1);\n\t }\n\t }\n\t else if (isDirInode(inode)) {\n\t stats = inode.getStats();\n\t }\n\t else {\n\t throw ApiError.FileError(ErrorCode.EINVAL, path$$1);\n\t }\n\t return stats;\n\t };\n\t XmlHttpRequest.prototype.open = function open (path$$1, flags, mode, cb) {\n\t // INVARIANT: You can't write to files on this file system.\n\t if (flags.isWriteable()) {\n\t return cb(new ApiError(ErrorCode.EPERM, path$$1));\n\t }\n\t var self = this;\n\t // Check if the path exists, and is a file.\n\t var inode = this._index.getInode(path$$1);\n\t if (inode === null) {\n\t return cb(ApiError.ENOENT(path$$1));\n\t }\n\t if (isFileInode(inode)) {\n\t var stats = inode.getData();\n\t switch (flags.pathExistsAction()) {\n\t case ActionType.THROW_EXCEPTION:\n\t case ActionType.TRUNCATE_FILE:\n\t return cb(ApiError.EEXIST(path$$1));\n\t case ActionType.NOP:\n\t // Use existing file contents.\n\t // XXX: Uh, this maintains the previously-used flag.\n\t if (stats.fileData) {\n\t return cb(null, new NoSyncFile(self, path$$1, flags, stats.clone(), stats.fileData));\n\t }\n\t // @todo be lazier about actually requesting the file\n\t this._requestFileAsync(path$$1, 'buffer', function (err, buffer$$1) {\n\t if (err) {\n\t return cb(err);\n\t }\n\t // we don't initially have file sizes\n\t stats.size = buffer$$1.length;\n\t stats.fileData = buffer$$1;\n\t return cb(null, new NoSyncFile(self, path$$1, flags, stats.clone(), buffer$$1));\n\t });\n\t break;\n\t default:\n\t return cb(new ApiError(ErrorCode.EINVAL, 'Invalid FileMode object.'));\n\t }\n\t }\n\t else {\n\t return cb(ApiError.EISDIR(path$$1));\n\t }\n\t };\n\t XmlHttpRequest.prototype.openSync = function openSync (path$$1, flags, mode) {\n\t // INVARIANT: You can't write to files on this file system.\n\t if (flags.isWriteable()) {\n\t throw new ApiError(ErrorCode.EPERM, path$$1);\n\t }\n\t // Check if the path exists, and is a file.\n\t var inode = this._index.getInode(path$$1);\n\t if (inode === null) {\n\t throw ApiError.ENOENT(path$$1);\n\t }\n\t if (isFileInode(inode)) {\n\t var stats = inode.getData();\n\t switch (flags.pathExistsAction()) {\n\t case ActionType.THROW_EXCEPTION:\n\t case ActionType.TRUNCATE_FILE:\n\t throw ApiError.EEXIST(path$$1);\n\t case ActionType.NOP:\n\t // Use existing file contents.\n\t // XXX: Uh, this maintains the previously-used flag.\n\t if (stats.fileData) {\n\t return new NoSyncFile(this, path$$1, flags, stats.clone(), stats.fileData);\n\t }\n\t // @todo be lazier about actually requesting the file\n\t var buffer$$1 = this._requestFileSync(path$$1, 'buffer');\n\t // we don't initially have file sizes\n\t stats.size = buffer$$1.length;\n\t stats.fileData = buffer$$1;\n\t return new NoSyncFile(this, path$$1, flags, stats.clone(), buffer$$1);\n\t default:\n\t throw new ApiError(ErrorCode.EINVAL, 'Invalid FileMode object.');\n\t }\n\t }\n\t else {\n\t throw ApiError.EISDIR(path$$1);\n\t }\n\t };\n\t XmlHttpRequest.prototype.readdir = function readdir (path$$1, cb) {\n\t try {\n\t cb(null, this.readdirSync(path$$1));\n\t }\n\t catch (e) {\n\t cb(e);\n\t }\n\t };\n\t XmlHttpRequest.prototype.readdirSync = function readdirSync (path$$1) {\n\t // Check if it exists.\n\t var inode = this._index.getInode(path$$1);\n\t if (inode === null) {\n\t throw ApiError.ENOENT(path$$1);\n\t }\n\t else if (isDirInode(inode)) {\n\t return inode.getListing();\n\t }\n\t else {\n\t throw ApiError.ENOTDIR(path$$1);\n\t }\n\t };\n\t /**\n\t * We have the entire file as a buffer; optimize readFile.\n\t */\n\t XmlHttpRequest.prototype.readFile = function readFile (fname, encoding, flag, cb) {\n\t // Wrap cb in file closing code.\n\t var oldCb = cb;\n\t // Get file.\n\t this.open(fname, flag, 0x1a4, function (err, fd) {\n\t if (err) {\n\t return cb(err);\n\t }\n\t cb = function (err, arg) {\n\t fd.close(function (err2) {\n\t if (!err) {\n\t err = err2;\n\t }\n\t return oldCb(err, arg);\n\t });\n\t };\n\t var fdCast = fd;\n\t var fdBuff = fdCast.getBuffer();\n\t if (encoding === null) {\n\t cb(err, copyingSlice(fdBuff));\n\t }\n\t else {\n\t tryToString(fdBuff, encoding, cb);\n\t }\n\t });\n\t };\n\t /**\n\t * Specially-optimized readfile.\n\t */\n\t XmlHttpRequest.prototype.readFileSync = function readFileSync (fname, encoding, flag) {\n\t // Get file.\n\t var fd = this.openSync(fname, flag, 0x1a4);\n\t try {\n\t var fdCast = fd;\n\t var fdBuff = fdCast.getBuffer();\n\t if (encoding === null) {\n\t return copyingSlice(fdBuff);\n\t }\n\t return fdBuff.toString(encoding);\n\t }\n\t finally {\n\t fd.closeSync();\n\t }\n\t };\n\t XmlHttpRequest.prototype.getXhrPath = function getXhrPath (filePath) {\n\t if (filePath.charAt(0) === '/') {\n\t filePath = filePath.slice(1);\n\t }\n\t return this.prefixUrl + filePath;\n\t };\n\t XmlHttpRequest.prototype._requestFileAsync = function _requestFileAsync (p, type, cb) {\n\t asyncDownloadFile(this.getXhrPath(p), type, cb);\n\t };\n\t XmlHttpRequest.prototype._requestFileSync = function _requestFileSync (p, type) {\n\t return syncDownloadFile(this.getXhrPath(p), type);\n\t };\n\t /**\n\t * Only requests the HEAD content, for the file size.\n\t */\n\t XmlHttpRequest.prototype._requestFileSizeAsync = function _requestFileSizeAsync (path$$1, cb) {\n\t getFileSizeAsync(this.getXhrPath(path$$1), cb);\n\t };\n\t XmlHttpRequest.prototype._requestFileSizeSync = function _requestFileSizeSync (path$$1) {\n\t return getFileSizeSync(this.getXhrPath(path$$1));\n\t };\n\t\n\t return XmlHttpRequest;\n\t}(BaseFileSystem));\n\t\n\tXmlHttpRequest.Name = \"XmlHttpRequest\";\n\tXmlHttpRequest.Options = {\n\t index: {\n\t type: [\"string\", \"object\"],\n\t optional: true,\n\t description: \"URL to a file index as a JSON file or the file index object itself, generated with the make_xhrfs_index script. Defaults to `index.json`.\"\n\t },\n\t baseUrl: {\n\t type: \"string\",\n\t optional: true,\n\t description: \"Used as the URL prefix for fetched files. Default: Fetch files relative to the index.\"\n\t }\n\t};\n\t\n\t/**\n\t * (Nonstandard) String utility function for 8-bit ASCII with the extended\n\t * character set. Unlike the ASCII above, we do not mask the high bits.\n\t *\n\t * Placed into a separate file so it can be used with other Buffer implementations.\n\t * @see http://en.wikipedia.org/wiki/Extended_ASCII\n\t */\n\t/**\n\t * (Nonstandard) String utility function for 8-bit ASCII with the extended\n\t * character set. Unlike the ASCII above, we do not mask the high bits.\n\t *\n\t * Placed into a separate file so it can be used with other Buffer implementations.\n\t * @see http://en.wikipedia.org/wiki/Extended_ASCII\n\t */ var ExtendedASCII = function ExtendedASCII () {};\n\t\n\t ExtendedASCII.str2byte = function str2byte (str, buf) {\n\t var length = str.length > buf.length ? buf.length : str.length;\n\t for (var i = 0; i < length; i++) {\n\t var charCode = str.charCodeAt(i);\n\t if (charCode > 0x7F) {\n\t // Check if extended ASCII.\n\t var charIdx = ExtendedASCII.extendedChars.indexOf(str.charAt(i));\n\t if (charIdx > -1) {\n\t charCode = charIdx + 0x80;\n\t }\n\t // Otherwise, keep it as-is.\n\t }\n\t buf[charCode] = i;\n\t }\n\t return length;\n\t};\n\tExtendedASCII.byte2str = function byte2str (buff) {\n\t var chars = new Array(buff.length);\n\t for (var i = 0; i < buff.length; i++) {\n\t var charCode = buff[i];\n\t if (charCode > 0x7F) {\n\t chars[i] = ExtendedASCII.extendedChars[charCode - 128];\n\t }\n\t else {\n\t chars[i] = String.fromCharCode(charCode);\n\t }\n\t }\n\t return chars.join('');\n\t};\n\tExtendedASCII.byteLength = function byteLength (str) { return str.length; };\n\t\n\t ExtendedASCII.extendedChars = ['\\u00C7', '\\u00FC', '\\u00E9', '\\u00E2', '\\u00E4',\n\t '\\u00E0', '\\u00E5', '\\u00E7', '\\u00EA', '\\u00EB', '\\u00E8', '\\u00EF',\n\t '\\u00EE', '\\u00EC', '\\u00C4', '\\u00C5', '\\u00C9', '\\u00E6', '\\u00C6',\n\t '\\u00F4', '\\u00F6', '\\u00F2', '\\u00FB', '\\u00F9', '\\u00FF', '\\u00D6',\n\t '\\u00DC', '\\u00F8', '\\u00A3', '\\u00D8', '\\u00D7', '\\u0192', '\\u00E1',\n\t '\\u00ED', '\\u00F3', '\\u00FA', '\\u00F1', '\\u00D1', '\\u00AA', '\\u00BA',\n\t '\\u00BF', '\\u00AE', '\\u00AC', '\\u00BD', '\\u00BC', '\\u00A1', '\\u00AB',\n\t '\\u00BB', '_', '_', '_', '\\u00A6', '\\u00A6', '\\u00C1', '\\u00C2', '\\u00C0',\n\t '\\u00A9', '\\u00A6', '\\u00A6', '+', '+', '\\u00A2', '\\u00A5', '+', '+', '-',\n\t '-', '+', '-', '+', '\\u00E3', '\\u00C3', '+', '+', '-', '-', '\\u00A6', '-',\n\t '+', '\\u00A4', '\\u00F0', '\\u00D0', '\\u00CA', '\\u00CB', '\\u00C8', 'i',\n\t '\\u00CD', '\\u00CE', '\\u00CF', '+', '+', '_', '_', '\\u00A6', '\\u00CC', '_',\n\t '\\u00D3', '\\u00DF', '\\u00D4', '\\u00D2', '\\u00F5', '\\u00D5', '\\u00B5',\n\t '\\u00FE', '\\u00DE', '\\u00DA', '\\u00DB', '\\u00D9', '\\u00FD', '\\u00DD',\n\t '\\u00AF', '\\u00B4', '\\u00AD', '\\u00B1', '_', '\\u00BE', '\\u00B6', '\\u00A7',\n\t '\\u00F7', '\\u00B8', '\\u00B0', '\\u00A8', '\\u00B7', '\\u00B9', '\\u00B3',\n\t '\\u00B2', '_', ' '];\n\t\n\t/**\n\t * @hidden\n\t */\n\tvar inflateRaw = __webpack_require__(23).inflateRaw;\n\t/**\n\t * Maps CompressionMethod => function that decompresses.\n\t * @hidden\n\t */\n\tvar decompressionMethods = {};\n\t/**\n\t * 4.4.2.2: Indicates the compatibiltiy of a file's external attributes.\n\t */\n\tvar ExternalFileAttributeType;\n\t(function (ExternalFileAttributeType) {\n\t ExternalFileAttributeType[ExternalFileAttributeType[\"MSDOS\"] = 0] = \"MSDOS\";\n\t ExternalFileAttributeType[ExternalFileAttributeType[\"AMIGA\"] = 1] = \"AMIGA\";\n\t ExternalFileAttributeType[ExternalFileAttributeType[\"OPENVMS\"] = 2] = \"OPENVMS\";\n\t ExternalFileAttributeType[ExternalFileAttributeType[\"UNIX\"] = 3] = \"UNIX\";\n\t ExternalFileAttributeType[ExternalFileAttributeType[\"VM_CMS\"] = 4] = \"VM_CMS\";\n\t ExternalFileAttributeType[ExternalFileAttributeType[\"ATARI_ST\"] = 5] = \"ATARI_ST\";\n\t ExternalFileAttributeType[ExternalFileAttributeType[\"OS2_HPFS\"] = 6] = \"OS2_HPFS\";\n\t ExternalFileAttributeType[ExternalFileAttributeType[\"MAC\"] = 7] = \"MAC\";\n\t ExternalFileAttributeType[ExternalFileAttributeType[\"Z_SYSTEM\"] = 8] = \"Z_SYSTEM\";\n\t ExternalFileAttributeType[ExternalFileAttributeType[\"CP_M\"] = 9] = \"CP_M\";\n\t ExternalFileAttributeType[ExternalFileAttributeType[\"NTFS\"] = 10] = \"NTFS\";\n\t ExternalFileAttributeType[ExternalFileAttributeType[\"MVS\"] = 11] = \"MVS\";\n\t ExternalFileAttributeType[ExternalFileAttributeType[\"VSE\"] = 12] = \"VSE\";\n\t ExternalFileAttributeType[ExternalFileAttributeType[\"ACORN_RISC\"] = 13] = \"ACORN_RISC\";\n\t ExternalFileAttributeType[ExternalFileAttributeType[\"VFAT\"] = 14] = \"VFAT\";\n\t ExternalFileAttributeType[ExternalFileAttributeType[\"ALT_MVS\"] = 15] = \"ALT_MVS\";\n\t ExternalFileAttributeType[ExternalFileAttributeType[\"BEOS\"] = 16] = \"BEOS\";\n\t ExternalFileAttributeType[ExternalFileAttributeType[\"TANDEM\"] = 17] = \"TANDEM\";\n\t ExternalFileAttributeType[ExternalFileAttributeType[\"OS_400\"] = 18] = \"OS_400\";\n\t ExternalFileAttributeType[ExternalFileAttributeType[\"OSX\"] = 19] = \"OSX\";\n\t})(ExternalFileAttributeType || (ExternalFileAttributeType = {}));\n\t/**\n\t * 4.4.5\n\t */\n\tvar CompressionMethod;\n\t(function (CompressionMethod) {\n\t CompressionMethod[CompressionMethod[\"STORED\"] = 0] = \"STORED\";\n\t CompressionMethod[CompressionMethod[\"SHRUNK\"] = 1] = \"SHRUNK\";\n\t CompressionMethod[CompressionMethod[\"REDUCED_1\"] = 2] = \"REDUCED_1\";\n\t CompressionMethod[CompressionMethod[\"REDUCED_2\"] = 3] = \"REDUCED_2\";\n\t CompressionMethod[CompressionMethod[\"REDUCED_3\"] = 4] = \"REDUCED_3\";\n\t CompressionMethod[CompressionMethod[\"REDUCED_4\"] = 5] = \"REDUCED_4\";\n\t CompressionMethod[CompressionMethod[\"IMPLODE\"] = 6] = \"IMPLODE\";\n\t CompressionMethod[CompressionMethod[\"DEFLATE\"] = 8] = \"DEFLATE\";\n\t CompressionMethod[CompressionMethod[\"DEFLATE64\"] = 9] = \"DEFLATE64\";\n\t CompressionMethod[CompressionMethod[\"TERSE_OLD\"] = 10] = \"TERSE_OLD\";\n\t CompressionMethod[CompressionMethod[\"BZIP2\"] = 12] = \"BZIP2\";\n\t CompressionMethod[CompressionMethod[\"LZMA\"] = 14] = \"LZMA\";\n\t CompressionMethod[CompressionMethod[\"TERSE_NEW\"] = 18] = \"TERSE_NEW\";\n\t CompressionMethod[CompressionMethod[\"LZ77\"] = 19] = \"LZ77\";\n\t CompressionMethod[CompressionMethod[\"WAVPACK\"] = 97] = \"WAVPACK\";\n\t CompressionMethod[CompressionMethod[\"PPMD\"] = 98] = \"PPMD\"; // PPMd version I, Rev 1\n\t})(CompressionMethod || (CompressionMethod = {}));\n\t/**\n\t * Converts the input time and date in MS-DOS format into a JavaScript Date\n\t * object.\n\t * @hidden\n\t */\n\tfunction msdos2date(time, date) {\n\t // MS-DOS Date\n\t // |0 0 0 0 0|0 0 0 0|0 0 0 0 0 0 0\n\t // D (1-31) M (1-23) Y (from 1980)\n\t var day = date & 0x1F;\n\t // JS date is 0-indexed, DOS is 1-indexed.\n\t var month = ((date >> 5) & 0xF) - 1;\n\t var year = (date >> 9) + 1980;\n\t // MS DOS Time\n\t // |0 0 0 0 0|0 0 0 0 0 0|0 0 0 0 0\n\t // Second Minute Hour\n\t var second = time & 0x1F;\n\t var minute = (time >> 5) & 0x3F;\n\t var hour = time >> 11;\n\t return new Date(year, month, day, hour, minute, second);\n\t}\n\t/**\n\t * Safely returns the string from the buffer, even if it is 0 bytes long.\n\t * (Normally, calling toString() on a buffer with start === end causes an\n\t * exception).\n\t * @hidden\n\t */\n\tfunction safeToString(buff, useUTF8, start, length) {\n\t if (length === 0) {\n\t return \"\";\n\t }\n\t else if (useUTF8) {\n\t return buff.toString('utf8', start, start + length);\n\t }\n\t else {\n\t return ExtendedASCII.byte2str(buff.slice(start, start + length));\n\t }\n\t}\n\t/*\n\t 4.3.6 Overall .ZIP file format:\n\t\n\t [local file header 1]\n\t [encryption header 1]\n\t [file data 1]\n\t [data descriptor 1]\n\t .\n\t .\n\t .\n\t [local file header n]\n\t [encryption header n]\n\t [file data n]\n\t [data descriptor n]\n\t [archive decryption header]\n\t [archive extra data record]\n\t [central directory header 1]\n\t .\n\t .\n\t .\n\t [central directory header n]\n\t [zip64 end of central directory record]\n\t [zip64 end of central directory locator]\n\t [end of central directory record]\n\t*/\n\t/**\n\t * 4.3.7 Local file header:\n\t *\n\t * local file header signature 4 bytes (0x04034b50)\n\t * version needed to extract 2 bytes\n\t * general purpose bit flag 2 bytes\n\t * compression method 2 bytes\n\t * last mod file time 2 bytes\n\t * last mod file date 2 bytes\n\t * crc-32 4 bytes\n\t * compressed size 4 bytes\n\t * uncompressed size 4 bytes\n\t * file name length 2 bytes\n\t * extra field length 2 bytes\n\t *\n\t * file name (variable size)\n\t * extra field (variable size)\n\t */\n\tvar FileHeader = function FileHeader(data) {\n\t this.data = data;\n\t if (data.readUInt32LE(0) !== 0x04034b50) {\n\t throw new ApiError(ErrorCode.EINVAL, \"Invalid Zip file: Local file header has invalid signature: \" + this.data.readUInt32LE(0));\n\t }\n\t };\n\t FileHeader.prototype.versionNeeded = function versionNeeded () { return this.data.readUInt16LE(4); };\n\t FileHeader.prototype.flags = function flags () { return this.data.readUInt16LE(6); };\n\t FileHeader.prototype.compressionMethod = function compressionMethod () { return this.data.readUInt16LE(8); };\n\t FileHeader.prototype.lastModFileTime = function lastModFileTime () {\n\t // Time and date is in MS-DOS format.\n\t return msdos2date(this.data.readUInt16LE(10), this.data.readUInt16LE(12));\n\t };\n\t FileHeader.prototype.rawLastModFileTime = function rawLastModFileTime () {\n\t return this.data.readUInt32LE(10);\n\t };\n\t FileHeader.prototype.crc32 = function crc32 () { return this.data.readUInt32LE(14); };\n\t /**\n\t * These two values are COMPLETELY USELESS.\n\t *\n\t * Section 4.4.9:\n\t *If bit 3 of the general purpose bit flag is set,\n\t *these fields are set to zero in the local header and the\n\t *correct values are put in the data descriptor and\n\t *in the central directory.\n\t *\n\t * So we'll just use the central directory's values.\n\t */\n\t // public compressedSize(): number { return this.data.readUInt32LE(18); }\n\t // public uncompressedSize(): number { return this.data.readUInt32LE(22); }\n\t FileHeader.prototype.fileNameLength = function fileNameLength () { return this.data.readUInt16LE(26); };\n\t FileHeader.prototype.extraFieldLength = function extraFieldLength () { return this.data.readUInt16LE(28); };\n\t FileHeader.prototype.fileName = function fileName () {\n\t return safeToString(this.data, this.useUTF8(), 30, this.fileNameLength());\n\t };\n\t FileHeader.prototype.extraField = function extraField () {\n\t var start = 30 + this.fileNameLength();\n\t return this.data.slice(start, start + this.extraFieldLength());\n\t };\n\t FileHeader.prototype.totalSize = function totalSize () { return 30 + this.fileNameLength() + this.extraFieldLength(); };\n\t FileHeader.prototype.useUTF8 = function useUTF8 () { return (this.flags() & 0x800) === 0x800; };\n\t/**\n\t * 4.3.8 File data\n\t *\n\t * Immediately following the local header for a file\n\t * SHOULD be placed the compressed or stored data for the file.\n\t * If the file is encrypted, the encryption header for the file\n\t * SHOULD be placed after the local header and before the file\n\t * data. The series of [local file header][encryption header]\n\t * [file data][data descriptor] repeats for each file in the\n\t * .ZIP archive.\n\t *\n\t * Zero-byte files, directories, and other file types that\n\t * contain no content MUST not include file data.\n\t */\n\tvar FileData = function FileData(header, record, data) {\n\t this.header = header;\n\t this.record = record;\n\t this.data = data;\n\t };\n\t FileData.prototype.decompress = function decompress () {\n\t // Check the compression\n\t var compressionMethod = this.header.compressionMethod();\n\t var fcn = decompressionMethods[compressionMethod];\n\t if (fcn) {\n\t return fcn(this.data, this.record.compressedSize(), this.record.uncompressedSize(), this.record.flag());\n\t }\n\t else {\n\t var name = CompressionMethod[compressionMethod];\n\t if (!name) {\n\t name = \"Unknown: \" + compressionMethod;\n\t }\n\t throw new ApiError(ErrorCode.EINVAL, (\"Invalid compression method on file '\" + (this.header.fileName()) + \"': \" + name));\n\t }\n\t };\n\t FileData.prototype.getHeader = function getHeader () {\n\t return this.header;\n\t };\n\t FileData.prototype.getRecord = function getRecord () {\n\t return this.record;\n\t };\n\t FileData.prototype.getRawData = function getRawData () {\n\t return this.data;\n\t };\n\t/**\n\t * 4.3.9 Data descriptor:\n\t *\n\t * crc-32 4 bytes\n\t * compressed size 4 bytes\n\t * uncompressed size 4 bytes\n\t */\n\tvar DataDescriptor = function DataDescriptor(data) {\n\t this.data = data;\n\t };\n\t DataDescriptor.prototype.crc32 = function crc32 () { return this.data.readUInt32LE(0); };\n\t DataDescriptor.prototype.compressedSize = function compressedSize () { return this.data.readUInt32LE(4); };\n\t DataDescriptor.prototype.uncompressedSize = function uncompressedSize () { return this.data.readUInt32LE(8); };\n\t/*\n\t` 4.3.10 Archive decryption header:\n\t\n\t 4.3.10.1 The Archive Decryption Header is introduced in version 6.2\n\t of the ZIP format specification. This record exists in support\n\t of the Central Directory Encryption Feature implemented as part of\n\t the Strong Encryption Specification as described in this document.\n\t When the Central Directory Structure is encrypted, this decryption\n\t header MUST precede the encrypted data segment.\n\t */\n\t/**\n\t * 4.3.11 Archive extra data record:\n\t *\n\t * archive extra data signature 4 bytes (0x08064b50)\n\t * extra field length 4 bytes\n\t * extra field data (variable size)\n\t *\n\t * 4.3.11.1 The Archive Extra Data Record is introduced in version 6.2\n\t * of the ZIP format specification. This record MAY be used in support\n\t * of the Central Directory Encryption Feature implemented as part of\n\t * the Strong Encryption Specification as described in this document.\n\t * When present, this record MUST immediately precede the central\n\t * directory data structure.\n\t */\n\tvar ArchiveExtraDataRecord = function ArchiveExtraDataRecord(data) {\n\t this.data = data;\n\t if (this.data.readUInt32LE(0) !== 0x08064b50) {\n\t throw new ApiError(ErrorCode.EINVAL, \"Invalid archive extra data record signature: \" + this.data.readUInt32LE(0));\n\t }\n\t };\n\t ArchiveExtraDataRecord.prototype.length = function length () { return this.data.readUInt32LE(4); };\n\t ArchiveExtraDataRecord.prototype.extraFieldData = function extraFieldData () { return this.data.slice(8, 8 + this.length()); };\n\t/**\n\t * 4.3.13 Digital signature:\n\t *\n\t * header signature 4 bytes (0x05054b50)\n\t * size of data 2 bytes\n\t * signature data (variable size)\n\t *\n\t * With the introduction of the Central Directory Encryption\n\t * feature in version 6.2 of this specification, the Central\n\t * Directory Structure MAY be stored both compressed and encrypted.\n\t * Although not required, it is assumed when encrypting the\n\t * Central Directory Structure, that it will be compressed\n\t * for greater storage efficiency. Information on the\n\t * Central Directory Encryption feature can be found in the section\n\t * describing the Strong Encryption Specification. The Digital\n\t * Signature record will be neither compressed nor encrypted.\n\t */\n\tvar DigitalSignature = function DigitalSignature(data) {\n\t this.data = data;\n\t if (this.data.readUInt32LE(0) !== 0x05054b50) {\n\t throw new ApiError(ErrorCode.EINVAL, \"Invalid digital signature signature: \" + this.data.readUInt32LE(0));\n\t }\n\t };\n\t DigitalSignature.prototype.size = function size () { return this.data.readUInt16LE(4); };\n\t DigitalSignature.prototype.signatureData = function signatureData () { return this.data.slice(6, 6 + this.size()); };\n\t/**\n\t * 4.3.12 Central directory structure:\n\t *\n\t * central file header signature 4 bytes (0x02014b50)\n\t * version made by 2 bytes\n\t * version needed to extract 2 bytes\n\t * general purpose bit flag 2 bytes\n\t * compression method 2 bytes\n\t * last mod file time 2 bytes\n\t * last mod file date 2 bytes\n\t * crc-32 4 bytes\n\t * compressed size 4 bytes\n\t * uncompressed size 4 bytes\n\t * file name length 2 bytes\n\t * extra field length 2 bytes\n\t * file comment length 2 bytes\n\t * disk number start 2 bytes\n\t * internal file attributes 2 bytes\n\t * external file attributes 4 bytes\n\t * relative offset of local header 4 bytes\n\t *\n\t * file name (variable size)\n\t * extra field (variable size)\n\t * file comment (variable size)\n\t */\n\tvar CentralDirectory = function CentralDirectory(zipData, data) {\n\t this.zipData = zipData;\n\t this.data = data;\n\t // Sanity check.\n\t if (this.data.readUInt32LE(0) !== 0x02014b50) {\n\t throw new ApiError(ErrorCode.EINVAL, (\"Invalid Zip file: Central directory record has invalid signature: \" + (this.data.readUInt32LE(0))));\n\t }\n\t this._filename = this.produceFilename();\n\t };\n\t CentralDirectory.prototype.versionMadeBy = function versionMadeBy () { return this.data.readUInt16LE(4); };\n\t CentralDirectory.prototype.versionNeeded = function versionNeeded () { return this.data.readUInt16LE(6); };\n\t CentralDirectory.prototype.flag = function flag () { return this.data.readUInt16LE(8); };\n\t CentralDirectory.prototype.compressionMethod = function compressionMethod () { return this.data.readUInt16LE(10); };\n\t CentralDirectory.prototype.lastModFileTime = function lastModFileTime () {\n\t // Time and date is in MS-DOS format.\n\t return msdos2date(this.data.readUInt16LE(12), this.data.readUInt16LE(14));\n\t };\n\t CentralDirectory.prototype.rawLastModFileTime = function rawLastModFileTime () {\n\t return this.data.readUInt32LE(12);\n\t };\n\t CentralDirectory.prototype.crc32 = function crc32 () { return this.data.readUInt32LE(16); };\n\t CentralDirectory.prototype.compressedSize = function compressedSize () { return this.data.readUInt32LE(20); };\n\t CentralDirectory.prototype.uncompressedSize = function uncompressedSize () { return this.data.readUInt32LE(24); };\n\t CentralDirectory.prototype.fileNameLength = function fileNameLength () { return this.data.readUInt16LE(28); };\n\t CentralDirectory.prototype.extraFieldLength = function extraFieldLength () { return this.data.readUInt16LE(30); };\n\t CentralDirectory.prototype.fileCommentLength = function fileCommentLength () { return this.data.readUInt16LE(32); };\n\t CentralDirectory.prototype.diskNumberStart = function diskNumberStart () { return this.data.readUInt16LE(34); };\n\t CentralDirectory.prototype.internalAttributes = function internalAttributes () { return this.data.readUInt16LE(36); };\n\t CentralDirectory.prototype.externalAttributes = function externalAttributes () { return this.data.readUInt32LE(38); };\n\t CentralDirectory.prototype.headerRelativeOffset = function headerRelativeOffset () { return this.data.readUInt32LE(42); };\n\t CentralDirectory.prototype.produceFilename = function produceFilename () {\n\t /*\n\t 4.4.17.1 claims:\n\t * All slashes are forward ('/') slashes.\n\t * Filename doesn't begin with a slash.\n\t * No drive letters or any nonsense like that.\n\t * If filename is missing, the input came from standard input.\n\t \n\t Unfortunately, this isn't true in practice. Some Windows zip utilities use\n\t a backslash here, but the correct Unix-style path in file headers.\n\t \n\t To avoid seeking all over the file to recover the known-good filenames\n\t from file headers, we simply convert '/' to '\\' here.\n\t */\n\t var fileName = safeToString(this.data, this.useUTF8(), 46, this.fileNameLength());\n\t return fileName.replace(/\\\\/g, \"/\");\n\t };\n\t CentralDirectory.prototype.fileName = function fileName () {\n\t return this._filename;\n\t };\n\t CentralDirectory.prototype.rawFileName = function rawFileName () {\n\t return this.data.slice(46, 46 + this.fileNameLength());\n\t };\n\t CentralDirectory.prototype.extraField = function extraField () {\n\t var start = 44 + this.fileNameLength();\n\t return this.data.slice(start, start + this.extraFieldLength());\n\t };\n\t CentralDirectory.prototype.fileComment = function fileComment () {\n\t var start = 46 + this.fileNameLength() + this.extraFieldLength();\n\t return safeToString(this.data, this.useUTF8(), start, this.fileCommentLength());\n\t };\n\t CentralDirectory.prototype.rawFileComment = function rawFileComment () {\n\t var start = 46 + this.fileNameLength() + this.extraFieldLength();\n\t return this.data.slice(start, start + this.fileCommentLength());\n\t };\n\t CentralDirectory.prototype.totalSize = function totalSize () {\n\t return 46 + this.fileNameLength() + this.extraFieldLength() + this.fileCommentLength();\n\t };\n\t CentralDirectory.prototype.isDirectory = function isDirectory () {\n\t // NOTE: This assumes that the zip file implementation uses the lower byte\n\t // of external attributes for DOS attributes for\n\t // backwards-compatibility. This is not mandated, but appears to be\n\t // commonplace.\n\t // According to the spec, the layout of external attributes is\n\t // platform-dependent.\n\t // If that fails, we also check if the name of the file ends in '/',\n\t // which is what Java's ZipFile implementation does.\n\t var fileName = this.fileName();\n\t return (this.externalAttributes() & 0x10 ? true : false) || (fileName.charAt(fileName.length - 1) === '/');\n\t };\n\t CentralDirectory.prototype.isFile = function isFile () { return !this.isDirectory(); };\n\t CentralDirectory.prototype.useUTF8 = function useUTF8 () { return (this.flag() & 0x800) === 0x800; };\n\t CentralDirectory.prototype.isEncrypted = function isEncrypted () { return (this.flag() & 0x1) === 0x1; };\n\t CentralDirectory.prototype.getFileData = function getFileData () {\n\t // Need to grab the header before we can figure out where the actual\n\t // compressed data starts.\n\t var start = this.headerRelativeOffset();\n\t var header = new FileHeader(this.zipData.slice(start));\n\t return new FileData(header, this, this.zipData.slice(start + header.totalSize()));\n\t };\n\t CentralDirectory.prototype.getData = function getData () {\n\t return this.getFileData().decompress();\n\t };\n\t CentralDirectory.prototype.getRawData = function getRawData () {\n\t return this.getFileData().getRawData();\n\t };\n\t CentralDirectory.prototype.getStats = function getStats () {\n\t return new Stats(FileType.FILE, this.uncompressedSize(), 0x16D, new Date(), this.lastModFileTime());\n\t };\n\t/**\n\t * 4.3.16: end of central directory record\n\t * end of central dir signature 4 bytes (0x06054b50)\n\t * number of this disk 2 bytes\n\t * number of the disk with the\n\t * start of the central directory 2 bytes\n\t * total number of entries in the\n\t * central directory on this disk 2 bytes\n\t * total number of entries in\n\t * the central directory 2 bytes\n\t * size of the central directory 4 bytes\n\t * offset of start of central\n\t * directory with respect to\n\t * the starting disk number 4 bytes\n\t * .ZIP file comment length 2 bytes\n\t * .ZIP file comment (variable size)\n\t */\n\tvar EndOfCentralDirectory = function EndOfCentralDirectory(data) {\n\t this.data = data;\n\t if (this.data.readUInt32LE(0) !== 0x06054b50) {\n\t throw new ApiError(ErrorCode.EINVAL, (\"Invalid Zip file: End of central directory record has invalid signature: \" + (this.data.readUInt32LE(0))));\n\t }\n\t };\n\t EndOfCentralDirectory.prototype.diskNumber = function diskNumber () { return this.data.readUInt16LE(4); };\n\t EndOfCentralDirectory.prototype.cdDiskNumber = function cdDiskNumber () { return this.data.readUInt16LE(6); };\n\t EndOfCentralDirectory.prototype.cdDiskEntryCount = function cdDiskEntryCount () { return this.data.readUInt16LE(8); };\n\t EndOfCentralDirectory.prototype.cdTotalEntryCount = function cdTotalEntryCount () { return this.data.readUInt16LE(10); };\n\t EndOfCentralDirectory.prototype.cdSize = function cdSize () { return this.data.readUInt32LE(12); };\n\t EndOfCentralDirectory.prototype.cdOffset = function cdOffset () { return this.data.readUInt32LE(16); };\n\t EndOfCentralDirectory.prototype.cdZipCommentLength = function cdZipCommentLength () { return this.data.readUInt16LE(20); };\n\t EndOfCentralDirectory.prototype.cdZipComment = function cdZipComment () {\n\t // Assuming UTF-8. The specification doesn't specify.\n\t return safeToString(this.data, true, 22, this.cdZipCommentLength());\n\t };\n\t EndOfCentralDirectory.prototype.rawCdZipComment = function rawCdZipComment () {\n\t return this.data.slice(22, 22 + this.cdZipCommentLength());\n\t };\n\t/**\n\t * Contains the table of contents of a Zip file.\n\t */\n\tvar ZipTOC = function ZipTOC(index, directoryEntries, eocd, data) {\n\t this.index = index;\n\t this.directoryEntries = directoryEntries;\n\t this.eocd = eocd;\n\t this.data = data;\n\t };\n\t/**\n\t * Zip file-backed filesystem\n\t * Implemented according to the standard:\n\t * http://www.pkware.com/documents/casestudies/APPNOTE.TXT\n\t *\n\t * While there are a few zip libraries for JavaScript (e.g. JSZip and zip.js),\n\t * they are not a good match for BrowserFS. In particular, these libraries\n\t * perform a lot of unneeded data copying, and eagerly decompress every file\n\t * in the zip file upon loading to check the CRC32. They also eagerly decode\n\t * strings. Furthermore, these libraries duplicate functionality already present\n\t * in BrowserFS (e.g. UTF-8 decoding and binary data manipulation).\n\t *\n\t * This filesystem takes advantage of BrowserFS's Buffer implementation, which\n\t * efficiently represents the zip file in memory (in both ArrayBuffer-enabled\n\t * browsers *and* non-ArrayBuffer browsers), and which can neatly be 'sliced'\n\t * without copying data. Each struct defined in the standard is represented with\n\t * a buffer slice pointing to an offset in the zip file, and has getters for\n\t * each field. As we anticipate that this data will not be read often, we choose\n\t * not to store each struct field in the JavaScript object; instead, to reduce\n\t * memory consumption, we retrieve it directly from the binary data each time it\n\t * is requested.\n\t *\n\t * When the filesystem is instantiated, we determine the directory structure\n\t * of the zip file as quickly as possible. We lazily decompress and check the\n\t * CRC32 of files. We do not cache decompressed files; if this is a desired\n\t * feature, it is best implemented as a generic file system wrapper that can\n\t * cache data from arbitrary file systems.\n\t *\n\t * For inflation, we use `pako`'s implementation:\n\t * https://github.com/nodeca/pako\n\t *\n\t * Current limitations:\n\t * * No encryption.\n\t * * No ZIP64 support.\n\t * * Read-only.\n\t * Write support would require that we:\n\t * - Keep track of changed/new files.\n\t * - Compress changed files, and generate appropriate metadata for each.\n\t * - Update file offsets for other files in the zip file.\n\t * - Stream it out to a location.\n\t * This isn't that bad, so we might do this at a later date.\n\t */\n\tvar ZipFS = (function (SynchronousFileSystem$$1) {\n\t function ZipFS(input, name, deprecateMsg) {\n\t if ( name === void 0 ) name = '';\n\t if ( deprecateMsg === void 0 ) deprecateMsg = true;\n\t\n\t SynchronousFileSystem$$1.call(this);\n\t this.name = name;\n\t this._index = new FileIndex();\n\t this._directoryEntries = [];\n\t this._eocd = null;\n\t deprecationMessage(deprecateMsg, ZipFS.Name, { zipData: \"zip data as a Buffer\", name: name });\n\t if (input instanceof ZipTOC) {\n\t this._index = input.index;\n\t this._directoryEntries = input.directoryEntries;\n\t this._eocd = input.eocd;\n\t this.data = input.data;\n\t }\n\t else {\n\t this.data = input;\n\t this.populateIndex();\n\t }\n\t }\n\t\n\t if ( SynchronousFileSystem$$1 ) ZipFS.__proto__ = SynchronousFileSystem$$1;\n\t ZipFS.prototype = Object.create( SynchronousFileSystem$$1 && SynchronousFileSystem$$1.prototype );\n\t ZipFS.prototype.constructor = ZipFS;\n\t /**\n\t * Constructs a ZipFS instance with the given options.\n\t */\n\t ZipFS.Create = function Create (opts, cb) {\n\t try {\n\t ZipFS.computeIndex(opts.zipData, function (zipTOC) {\n\t var fs = new ZipFS(zipTOC, opts.name, false);\n\t cb(null, fs);\n\t }, false);\n\t }\n\t catch (e) {\n\t cb(e);\n\t }\n\t };\n\t ZipFS.isAvailable = function isAvailable () { return true; };\n\t ZipFS.RegisterDecompressionMethod = function RegisterDecompressionMethod (m, fcn) {\n\t decompressionMethods[m] = fcn;\n\t };\n\t /**\n\t * **Deprecated. Please use ZipFS.Create() method instead.**\n\t */\n\t ZipFS.computeIndex = function computeIndex (data, cb, deprecateMsg) {\n\t if ( deprecateMsg === void 0 ) deprecateMsg = true;\n\t\n\t // TODO: Refactor to plumb errors through. Right now, they throw.\n\t if (deprecateMsg) {\n\t console.warn(\"[ZipFS] ZipFS.computeIndex is now deprecated, and will be removed in the next major release. Please update your code to use 'ZipFS.Create({ zipData: zip file as a Buffer}, cb)' instead.\");\n\t }\n\t var index = new FileIndex();\n\t var eocd = ZipFS.getEOCD(data);\n\t if (eocd.diskNumber() !== eocd.cdDiskNumber()) {\n\t throw new ApiError(ErrorCode.EINVAL, \"ZipFS does not support spanned zip files.\");\n\t }\n\t var cdPtr = eocd.cdOffset();\n\t if (cdPtr === 0xFFFFFFFF) {\n\t throw new ApiError(ErrorCode.EINVAL, \"ZipFS does not support Zip64.\");\n\t }\n\t var cdEnd = cdPtr + eocd.cdSize();\n\t ZipFS.computeIndexResponsive(data, index, cdPtr, cdEnd, cb, [], eocd);\n\t };\n\t /**\n\t * Locates the end of central directory record at the end of the file.\n\t * Throws an exception if it cannot be found.\n\t */\n\t ZipFS.getEOCD = function getEOCD (data) {\n\t // Unfortunately, the comment is variable size and up to 64K in size.\n\t // We assume that the magic signature does not appear in the comment, and\n\t // in the bytes between the comment and the signature. Other ZIP\n\t // implementations make this same assumption, since the alternative is to\n\t // read thread every entry in the file to get to it. :(\n\t // These are *negative* offsets from the end of the file.\n\t var startOffset = 22;\n\t var endOffset = Math.min(startOffset + 0xFFFF, data.length - 1);\n\t // There's not even a byte alignment guarantee on the comment so we need to\n\t // search byte by byte. *grumble grumble*\n\t for (var i = startOffset; i < endOffset; i++) {\n\t // Magic number: EOCD Signature\n\t if (data.readUInt32LE(data.length - i) === 0x06054b50) {\n\t return new EndOfCentralDirectory(data.slice(data.length - i));\n\t }\n\t }\n\t throw new ApiError(ErrorCode.EINVAL, \"Invalid ZIP file: Could not locate End of Central Directory signature.\");\n\t };\n\t ZipFS.addToIndex = function addToIndex (cd, index) {\n\t // Paths must be absolute, yet zip file paths are always relative to the\n\t // zip root. So we append '/' and call it a day.\n\t var filename = cd.fileName();\n\t if (filename.charAt(0) === '/') {\n\t throw new Error(\"WHY IS THIS ABSOLUTE\");\n\t }\n\t // XXX: For the file index, strip the trailing '/'.\n\t if (filename.charAt(filename.length - 1) === '/') {\n\t filename = filename.substr(0, filename.length - 1);\n\t }\n\t if (cd.isDirectory()) {\n\t index.addPathFast('/' + filename, new DirInode(cd));\n\t }\n\t else {\n\t index.addPathFast('/' + filename, new FileInode(cd));\n\t }\n\t };\n\t ZipFS.computeIndexResponsive = function computeIndexResponsive (data, index, cdPtr, cdEnd, cb, cdEntries, eocd) {\n\t if (cdPtr < cdEnd) {\n\t var count = 0;\n\t while (count++ < 200 && cdPtr < cdEnd) {\n\t var cd = new CentralDirectory(data, data.slice(cdPtr));\n\t ZipFS.addToIndex(cd, index);\n\t cdPtr += cd.totalSize();\n\t cdEntries.push(cd);\n\t }\n\t setImmediate$3(function () {\n\t ZipFS.computeIndexResponsive(data, index, cdPtr, cdEnd, cb, cdEntries, eocd);\n\t });\n\t }\n\t else {\n\t cb(new ZipTOC(index, cdEntries, eocd, data));\n\t }\n\t };\n\t ZipFS.prototype.getName = function getName () {\n\t return ZipFS.Name + (this.name !== '' ? (\" \" + (this.name)) : '');\n\t };\n\t /**\n\t * Get the CentralDirectory object for the given path.\n\t */\n\t ZipFS.prototype.getCentralDirectoryEntry = function getCentralDirectoryEntry (path$$1) {\n\t var inode = this._index.getInode(path$$1);\n\t if (inode === null) {\n\t throw ApiError.ENOENT(path$$1);\n\t }\n\t if (isFileInode(inode)) {\n\t return inode.getData();\n\t }\n\t else if (isDirInode(inode)) {\n\t return inode.getData();\n\t }\n\t else {\n\t // Should never occur.\n\t throw ApiError.EPERM((\"Invalid inode: \" + inode));\n\t }\n\t };\n\t ZipFS.prototype.getCentralDirectoryEntryAt = function getCentralDirectoryEntryAt (index) {\n\t var dirEntry = this._directoryEntries[index];\n\t if (!dirEntry) {\n\t throw new RangeError((\"Invalid directory index: \" + index + \".\"));\n\t }\n\t return dirEntry;\n\t };\n\t ZipFS.prototype.getNumberOfCentralDirectoryEntries = function getNumberOfCentralDirectoryEntries () {\n\t return this._directoryEntries.length;\n\t };\n\t ZipFS.prototype.getEndOfCentralDirectory = function getEndOfCentralDirectory () {\n\t return this._eocd;\n\t };\n\t ZipFS.prototype.diskSpace = function diskSpace (path$$1, cb) {\n\t // Read-only file system.\n\t cb(this.data.length, 0);\n\t };\n\t ZipFS.prototype.isReadOnly = function isReadOnly () {\n\t return true;\n\t };\n\t ZipFS.prototype.supportsLinks = function supportsLinks () {\n\t return false;\n\t };\n\t ZipFS.prototype.supportsProps = function supportsProps () {\n\t return false;\n\t };\n\t ZipFS.prototype.supportsSynch = function supportsSynch () {\n\t return true;\n\t };\n\t ZipFS.prototype.statSync = function statSync (path$$1, isLstat) {\n\t var inode = this._index.getInode(path$$1);\n\t if (inode === null) {\n\t throw ApiError.ENOENT(path$$1);\n\t }\n\t var stats;\n\t if (isFileInode(inode)) {\n\t stats = inode.getData().getStats();\n\t }\n\t else if (isDirInode(inode)) {\n\t stats = inode.getStats();\n\t }\n\t else {\n\t throw new ApiError(ErrorCode.EINVAL, \"Invalid inode.\");\n\t }\n\t return stats;\n\t };\n\t ZipFS.prototype.openSync = function openSync (path$$1, flags, mode) {\n\t // INVARIANT: Cannot write to RO file systems.\n\t if (flags.isWriteable()) {\n\t throw new ApiError(ErrorCode.EPERM, path$$1);\n\t }\n\t // Check if the path exists, and is a file.\n\t var inode = this._index.getInode(path$$1);\n\t if (!inode) {\n\t throw ApiError.ENOENT(path$$1);\n\t }\n\t else if (isFileInode(inode)) {\n\t var cdRecord = inode.getData();\n\t var stats = cdRecord.getStats();\n\t switch (flags.pathExistsAction()) {\n\t case ActionType.THROW_EXCEPTION:\n\t case ActionType.TRUNCATE_FILE:\n\t throw ApiError.EEXIST(path$$1);\n\t case ActionType.NOP:\n\t return new NoSyncFile(this, path$$1, flags, stats, cdRecord.getData());\n\t default:\n\t throw new ApiError(ErrorCode.EINVAL, 'Invalid FileMode object.');\n\t }\n\t }\n\t else {\n\t throw ApiError.EISDIR(path$$1);\n\t }\n\t };\n\t ZipFS.prototype.readdirSync = function readdirSync (path$$1) {\n\t // Check if it exists.\n\t var inode = this._index.getInode(path$$1);\n\t if (!inode) {\n\t throw ApiError.ENOENT(path$$1);\n\t }\n\t else if (isDirInode(inode)) {\n\t return inode.getListing();\n\t }\n\t else {\n\t throw ApiError.ENOTDIR(path$$1);\n\t }\n\t };\n\t /**\n\t * Specially-optimized readfile.\n\t */\n\t ZipFS.prototype.readFileSync = function readFileSync (fname, encoding, flag) {\n\t // Get file.\n\t var fd = this.openSync(fname, flag, 0x1a4);\n\t try {\n\t var fdCast = fd;\n\t var fdBuff = fdCast.getBuffer();\n\t if (encoding === null) {\n\t return copyingSlice(fdBuff);\n\t }\n\t return fdBuff.toString(encoding);\n\t }\n\t finally {\n\t fd.closeSync();\n\t }\n\t };\n\t ZipFS.prototype.populateIndex = function populateIndex () {\n\t var this$1 = this;\n\t\n\t var eocd = this._eocd = ZipFS.getEOCD(this.data);\n\t if (eocd.diskNumber() !== eocd.cdDiskNumber()) {\n\t throw new ApiError(ErrorCode.EINVAL, \"ZipFS does not support spanned zip files.\");\n\t }\n\t var cdPtr = eocd.cdOffset();\n\t if (cdPtr === 0xFFFFFFFF) {\n\t throw new ApiError(ErrorCode.EINVAL, \"ZipFS does not support Zip64.\");\n\t }\n\t var cdEnd = cdPtr + eocd.cdSize();\n\t while (cdPtr < cdEnd) {\n\t var cd = new CentralDirectory(this$1.data, this$1.data.slice(cdPtr));\n\t cdPtr += cd.totalSize();\n\t ZipFS.addToIndex(cd, this$1._index);\n\t this$1._directoryEntries.push(cd);\n\t }\n\t };\n\t\n\t return ZipFS;\n\t}(SynchronousFileSystem));\n\t\n\tZipFS.Name = \"ZipFS\";\n\tZipFS.Options = {\n\t zipData: {\n\t type: \"object\",\n\t description: \"The zip file as a Buffer object.\",\n\t validator: bufferValidator\n\t },\n\t name: {\n\t type: \"string\",\n\t optional: true,\n\t description: \"The name of the zip file (optional).\"\n\t }\n\t};\n\tZipFS.CompressionMethod = CompressionMethod;\n\tZipFS.RegisterDecompressionMethod(CompressionMethod.DEFLATE, function (data, compressedSize, uncompressedSize) {\n\t return arrayish2Buffer(inflateRaw(data.slice(0, compressedSize), { chunkSize: uncompressedSize }));\n\t});\n\tZipFS.RegisterDecompressionMethod(CompressionMethod.STORED, function (data, compressedSize, uncompressedSize) {\n\t return copyingSlice(data, 0, uncompressedSize);\n\t});\n\t\n\t/**\n\t * @hidden\n\t */\n\tvar rockRidgeIdentifier = \"IEEE_P1282\";\n\t/**\n\t * @hidden\n\t */\n\tfunction getASCIIString(data, startIndex, length) {\n\t return data.toString('ascii', startIndex, startIndex + length).trim();\n\t}\n\t/**\n\t * @hidden\n\t */\n\tfunction getJolietString(data, startIndex, length) {\n\t if (length === 1) {\n\t // Special: Root, parent, current directory are still a single byte.\n\t return String.fromCharCode(data[startIndex]);\n\t }\n\t // UTF16-BE, which isn't natively supported by NodeJS Buffers.\n\t // Length should be even, but pessimistically floor just in case.\n\t var pairs = Math.floor(length / 2);\n\t var chars = new Array(pairs);\n\t for (var i = 0; i < pairs; i++) {\n\t var pos = startIndex + (i << 1);\n\t chars[i] = String.fromCharCode(data[pos + 1] | (data[pos] << 8));\n\t }\n\t return chars.join('');\n\t}\n\t/**\n\t * @hidden\n\t */\n\tfunction getDate(data, startIndex) {\n\t var year = parseInt(getASCIIString(data, startIndex, 4), 10);\n\t var mon = parseInt(getASCIIString(data, startIndex + 4, 2), 10);\n\t var day = parseInt(getASCIIString(data, startIndex + 6, 2), 10);\n\t var hour = parseInt(getASCIIString(data, startIndex + 8, 2), 10);\n\t var min = parseInt(getASCIIString(data, startIndex + 10, 2), 10);\n\t var sec = parseInt(getASCIIString(data, startIndex + 12, 2), 10);\n\t var hundrethsSec = parseInt(getASCIIString(data, startIndex + 14, 2), 10);\n\t // Last is a time-zone offset, but JavaScript dates don't support time zones well.\n\t return new Date(year, mon, day, hour, min, sec, hundrethsSec * 100);\n\t}\n\t/**\n\t * @hidden\n\t */\n\tfunction getShortFormDate(data, startIndex) {\n\t var yearsSince1900 = data[startIndex];\n\t var month = data[startIndex + 1];\n\t var day = data[startIndex + 2];\n\t var hour = data[startIndex + 3];\n\t var minute = data[startIndex + 4];\n\t var second = data[startIndex + 5];\n\t // JavaScript's Date support isn't so great; ignore timezone.\n\t // const offsetFromGMT = this._data[24];\n\t return new Date(yearsSince1900, month - 1, day, hour, minute, second);\n\t}\n\t/**\n\t * @hidden\n\t */\n\tfunction constructSystemUseEntry(bigData, i) {\n\t var data = bigData.slice(i);\n\t var sue = new SystemUseEntry(data);\n\t switch (sue.signatureWord()) {\n\t case 17221 /* CE */:\n\t return new CEEntry(data);\n\t case 20548 /* PD */:\n\t return new PDEntry(data);\n\t case 21328 /* SP */:\n\t return new SPEntry(data);\n\t case 21332 /* ST */:\n\t return new STEntry(data);\n\t case 17746 /* ER */:\n\t return new EREntry(data);\n\t case 17747 /* ES */:\n\t return new ESEntry(data);\n\t case 20568 /* PX */:\n\t return new PXEntry(data);\n\t case 20558 /* PN */:\n\t return new PNEntry(data);\n\t case 21324 /* SL */:\n\t return new SLEntry(data);\n\t case 20045 /* NM */:\n\t return new NMEntry(data);\n\t case 17228 /* CL */:\n\t return new CLEntry(data);\n\t case 20556 /* PL */:\n\t return new PLEntry(data);\n\t case 21061 /* RE */:\n\t return new REEntry(data);\n\t case 21574 /* TF */:\n\t return new TFEntry(data);\n\t case 21318 /* SF */:\n\t return new SFEntry(data);\n\t case 21074 /* RR */:\n\t return new RREntry(data);\n\t default:\n\t return sue;\n\t }\n\t}\n\t/**\n\t * @hidden\n\t */\n\tfunction constructSystemUseEntries(data, i, len, isoData) {\n\t // If the remaining allocated space following the last recorded System Use Entry in a System\n\t // Use field or Continuation Area is less than four bytes long, it cannot contain a System\n\t // Use Entry and shall be ignored\n\t len = len - 4;\n\t var entries = new Array();\n\t while (i < len) {\n\t var entry = constructSystemUseEntry(data, i);\n\t var length = entry.length();\n\t if (length === 0) {\n\t // Invalid SU section; prevent infinite loop.\n\t return entries;\n\t }\n\t i += length;\n\t if (entry instanceof STEntry) {\n\t // ST indicates the end of entries.\n\t break;\n\t }\n\t if (entry instanceof CEEntry) {\n\t entries = entries.concat(entry.getEntries(isoData));\n\t }\n\t else {\n\t entries.push(entry);\n\t }\n\t }\n\t return entries;\n\t}\n\t/**\n\t * @hidden\n\t */\n\tvar VolumeDescriptor = function VolumeDescriptor(data) {\n\t this._data = data;\n\t};\n\tVolumeDescriptor.prototype.type = function type () {\n\t return this._data[0];\n\t};\n\tVolumeDescriptor.prototype.standardIdentifier = function standardIdentifier () {\n\t return getASCIIString(this._data, 1, 5);\n\t};\n\tVolumeDescriptor.prototype.version = function version () {\n\t return this._data[6];\n\t};\n\tVolumeDescriptor.prototype.data = function data () {\n\t return this._data.slice(7, 2048);\n\t};\n\t/**\n\t * @hidden\n\t */\n\tvar PrimaryOrSupplementaryVolumeDescriptor = (function (VolumeDescriptor) {\n\t function PrimaryOrSupplementaryVolumeDescriptor(data) {\n\t VolumeDescriptor.call(this, data);\n\t this._root = null;\n\t }\n\t\n\t if ( VolumeDescriptor ) PrimaryOrSupplementaryVolumeDescriptor.__proto__ = VolumeDescriptor;\n\t PrimaryOrSupplementaryVolumeDescriptor.prototype = Object.create( VolumeDescriptor && VolumeDescriptor.prototype );\n\t PrimaryOrSupplementaryVolumeDescriptor.prototype.constructor = PrimaryOrSupplementaryVolumeDescriptor;\n\t PrimaryOrSupplementaryVolumeDescriptor.prototype.systemIdentifier = function systemIdentifier () {\n\t return this._getString32(8);\n\t };\n\t PrimaryOrSupplementaryVolumeDescriptor.prototype.volumeIdentifier = function volumeIdentifier () {\n\t return this._getString32(40);\n\t };\n\t PrimaryOrSupplementaryVolumeDescriptor.prototype.volumeSpaceSize = function volumeSpaceSize () {\n\t return this._data.readUInt32LE(80);\n\t };\n\t PrimaryOrSupplementaryVolumeDescriptor.prototype.volumeSetSize = function volumeSetSize () {\n\t return this._data.readUInt16LE(120);\n\t };\n\t PrimaryOrSupplementaryVolumeDescriptor.prototype.volumeSequenceNumber = function volumeSequenceNumber () {\n\t return this._data.readUInt16LE(124);\n\t };\n\t PrimaryOrSupplementaryVolumeDescriptor.prototype.logicalBlockSize = function logicalBlockSize () {\n\t return this._data.readUInt16LE(128);\n\t };\n\t PrimaryOrSupplementaryVolumeDescriptor.prototype.pathTableSize = function pathTableSize () {\n\t return this._data.readUInt32LE(132);\n\t };\n\t PrimaryOrSupplementaryVolumeDescriptor.prototype.locationOfTypeLPathTable = function locationOfTypeLPathTable () {\n\t return this._data.readUInt32LE(140);\n\t };\n\t PrimaryOrSupplementaryVolumeDescriptor.prototype.locationOfOptionalTypeLPathTable = function locationOfOptionalTypeLPathTable () {\n\t return this._data.readUInt32LE(144);\n\t };\n\t PrimaryOrSupplementaryVolumeDescriptor.prototype.locationOfTypeMPathTable = function locationOfTypeMPathTable () {\n\t return this._data.readUInt32BE(148);\n\t };\n\t PrimaryOrSupplementaryVolumeDescriptor.prototype.locationOfOptionalTypeMPathTable = function locationOfOptionalTypeMPathTable () {\n\t return this._data.readUInt32BE(152);\n\t };\n\t PrimaryOrSupplementaryVolumeDescriptor.prototype.rootDirectoryEntry = function rootDirectoryEntry (isoData) {\n\t if (this._root === null) {\n\t this._root = this._constructRootDirectoryRecord(this._data.slice(156));\n\t this._root.rootCheckForRockRidge(isoData);\n\t }\n\t return this._root;\n\t };\n\t PrimaryOrSupplementaryVolumeDescriptor.prototype.volumeSetIdentifier = function volumeSetIdentifier () {\n\t return this._getString(190, 128);\n\t };\n\t PrimaryOrSupplementaryVolumeDescriptor.prototype.publisherIdentifier = function publisherIdentifier () {\n\t return this._getString(318, 128);\n\t };\n\t PrimaryOrSupplementaryVolumeDescriptor.prototype.dataPreparerIdentifier = function dataPreparerIdentifier () {\n\t return this._getString(446, 128);\n\t };\n\t PrimaryOrSupplementaryVolumeDescriptor.prototype.applicationIdentifier = function applicationIdentifier () {\n\t return this._getString(574, 128);\n\t };\n\t PrimaryOrSupplementaryVolumeDescriptor.prototype.copyrightFileIdentifier = function copyrightFileIdentifier () {\n\t return this._getString(702, 38);\n\t };\n\t PrimaryOrSupplementaryVolumeDescriptor.prototype.abstractFileIdentifier = function abstractFileIdentifier () {\n\t return this._getString(740, 36);\n\t };\n\t PrimaryOrSupplementaryVolumeDescriptor.prototype.bibliographicFileIdentifier = function bibliographicFileIdentifier () {\n\t return this._getString(776, 37);\n\t };\n\t PrimaryOrSupplementaryVolumeDescriptor.prototype.volumeCreationDate = function volumeCreationDate () {\n\t return getDate(this._data, 813);\n\t };\n\t PrimaryOrSupplementaryVolumeDescriptor.prototype.volumeModificationDate = function volumeModificationDate () {\n\t return getDate(this._data, 830);\n\t };\n\t PrimaryOrSupplementaryVolumeDescriptor.prototype.volumeExpirationDate = function volumeExpirationDate () {\n\t return getDate(this._data, 847);\n\t };\n\t PrimaryOrSupplementaryVolumeDescriptor.prototype.volumeEffectiveDate = function volumeEffectiveDate () {\n\t return getDate(this._data, 864);\n\t };\n\t PrimaryOrSupplementaryVolumeDescriptor.prototype.fileStructureVersion = function fileStructureVersion () {\n\t return this._data[881];\n\t };\n\t PrimaryOrSupplementaryVolumeDescriptor.prototype.applicationUsed = function applicationUsed () {\n\t return this._data.slice(883, 883 + 512);\n\t };\n\t PrimaryOrSupplementaryVolumeDescriptor.prototype.reserved = function reserved () {\n\t return this._data.slice(1395, 1395 + 653);\n\t };\n\t PrimaryOrSupplementaryVolumeDescriptor.prototype._getString32 = function _getString32 (idx) {\n\t return this._getString(idx, 32);\n\t };\n\t\n\t return PrimaryOrSupplementaryVolumeDescriptor;\n\t}(VolumeDescriptor));\n\t/**\n\t * @hidden\n\t */\n\tvar PrimaryVolumeDescriptor = (function (PrimaryOrSupplementaryVolumeDescriptor) {\n\t function PrimaryVolumeDescriptor(data) {\n\t PrimaryOrSupplementaryVolumeDescriptor.call(this, data);\n\t if (this.type() !== 1 /* PrimaryVolumeDescriptor */) {\n\t throw new ApiError(ErrorCode.EIO, \"Invalid primary volume descriptor.\");\n\t }\n\t }\n\t\n\t if ( PrimaryOrSupplementaryVolumeDescriptor ) PrimaryVolumeDescriptor.__proto__ = PrimaryOrSupplementaryVolumeDescriptor;\n\t PrimaryVolumeDescriptor.prototype = Object.create( PrimaryOrSupplementaryVolumeDescriptor && PrimaryOrSupplementaryVolumeDescriptor.prototype );\n\t PrimaryVolumeDescriptor.prototype.constructor = PrimaryVolumeDescriptor;\n\t PrimaryVolumeDescriptor.prototype.name = function name () {\n\t return \"ISO9660\";\n\t };\n\t PrimaryVolumeDescriptor.prototype._constructRootDirectoryRecord = function _constructRootDirectoryRecord (data) {\n\t return new ISODirectoryRecord(data, -1);\n\t };\n\t PrimaryVolumeDescriptor.prototype._getString = function _getString (idx, len) {\n\t return this._getString(idx, len);\n\t };\n\t\n\t return PrimaryVolumeDescriptor;\n\t}(PrimaryOrSupplementaryVolumeDescriptor));\n\t/**\n\t * @hidden\n\t */\n\tvar SupplementaryVolumeDescriptor = (function (PrimaryOrSupplementaryVolumeDescriptor) {\n\t function SupplementaryVolumeDescriptor(data) {\n\t PrimaryOrSupplementaryVolumeDescriptor.call(this, data);\n\t if (this.type() !== 2 /* SupplementaryVolumeDescriptor */) {\n\t throw new ApiError(ErrorCode.EIO, \"Invalid supplementary volume descriptor.\");\n\t }\n\t var escapeSequence = this.escapeSequence();\n\t var third = escapeSequence[2];\n\t // Third character identifies what 'level' of the UCS specification to follow.\n\t // We ignore it.\n\t if (escapeSequence[0] !== 0x25 || escapeSequence[1] !== 0x2F ||\n\t (third !== 0x40 && third !== 0x43 && third !== 0x45)) {\n\t throw new ApiError(ErrorCode.EIO, (\"Unrecognized escape sequence for SupplementaryVolumeDescriptor: \" + (escapeSequence.toString())));\n\t }\n\t }\n\t\n\t if ( PrimaryOrSupplementaryVolumeDescriptor ) SupplementaryVolumeDescriptor.__proto__ = PrimaryOrSupplementaryVolumeDescriptor;\n\t SupplementaryVolumeDescriptor.prototype = Object.create( PrimaryOrSupplementaryVolumeDescriptor && PrimaryOrSupplementaryVolumeDescriptor.prototype );\n\t SupplementaryVolumeDescriptor.prototype.constructor = SupplementaryVolumeDescriptor;\n\t SupplementaryVolumeDescriptor.prototype.name = function name () {\n\t return \"Joliet\";\n\t };\n\t SupplementaryVolumeDescriptor.prototype.escapeSequence = function escapeSequence () {\n\t return this._data.slice(88, 120);\n\t };\n\t SupplementaryVolumeDescriptor.prototype._constructRootDirectoryRecord = function _constructRootDirectoryRecord (data) {\n\t return new JolietDirectoryRecord(data, -1);\n\t };\n\t SupplementaryVolumeDescriptor.prototype._getString = function _getString (idx, len) {\n\t return getJolietString(this._data, idx, len);\n\t };\n\t\n\t return SupplementaryVolumeDescriptor;\n\t}(PrimaryOrSupplementaryVolumeDescriptor));\n\t/**\n\t * @hidden\n\t */\n\tvar DirectoryRecord = function DirectoryRecord(data, rockRidgeOffset) {\n\t this._suEntries = null;\n\t this._fileOrDir = null;\n\t this._data = data;\n\t this._rockRidgeOffset = rockRidgeOffset;\n\t};\n\tDirectoryRecord.prototype.hasRockRidge = function hasRockRidge () {\n\t return this._rockRidgeOffset > -1;\n\t};\n\tDirectoryRecord.prototype.getRockRidgeOffset = function getRockRidgeOffset () {\n\t return this._rockRidgeOffset;\n\t};\n\t/**\n\t * !!ONLY VALID ON ROOT NODE!!\n\t * Checks if Rock Ridge is enabled, and sets the offset.\n\t */\n\tDirectoryRecord.prototype.rootCheckForRockRidge = function rootCheckForRockRidge (isoData) {\n\t var dir = this.getDirectory(isoData);\n\t this._rockRidgeOffset = dir.getDotEntry(isoData)._getRockRidgeOffset(isoData);\n\t if (this._rockRidgeOffset > -1) {\n\t // Wipe out directory. Start over with RR knowledge.\n\t this._fileOrDir = null;\n\t }\n\t};\n\tDirectoryRecord.prototype.length = function length () {\n\t return this._data[0];\n\t};\n\tDirectoryRecord.prototype.extendedAttributeRecordLength = function extendedAttributeRecordLength () {\n\t return this._data[1];\n\t};\n\tDirectoryRecord.prototype.lba = function lba () {\n\t return this._data.readUInt32LE(2) * 2048;\n\t};\n\tDirectoryRecord.prototype.dataLength = function dataLength () {\n\t return this._data.readUInt32LE(10);\n\t};\n\tDirectoryRecord.prototype.recordingDate = function recordingDate () {\n\t return getShortFormDate(this._data, 18);\n\t};\n\tDirectoryRecord.prototype.fileFlags = function fileFlags () {\n\t return this._data[25];\n\t};\n\tDirectoryRecord.prototype.fileUnitSize = function fileUnitSize () {\n\t return this._data[26];\n\t};\n\tDirectoryRecord.prototype.interleaveGapSize = function interleaveGapSize () {\n\t return this._data[27];\n\t};\n\tDirectoryRecord.prototype.volumeSequenceNumber = function volumeSequenceNumber () {\n\t return this._data.readUInt16LE(28);\n\t};\n\tDirectoryRecord.prototype.identifier = function identifier () {\n\t return this._getString(33, this._data[32]);\n\t};\n\tDirectoryRecord.prototype.fileName = function fileName (isoData) {\n\t if (this.hasRockRidge()) {\n\t var fn = this._rockRidgeFilename(isoData);\n\t if (fn !== null) {\n\t return fn;\n\t }\n\t }\n\t var ident = this.identifier();\n\t if (this.isDirectory(isoData)) {\n\t return ident;\n\t }\n\t // Files:\n\t // - MUST have 0x2E (.) separating the name from the extension\n\t // - MUST have 0x3B (;) separating the file name and extension from the version\n\t // Gets expanded to two-byte char in Unicode directory records.\n\t var versionSeparator = ident.indexOf(';');\n\t if (versionSeparator === -1) {\n\t // Some Joliet filenames lack the version separator, despite the standard\n\t // specifying that it should be there.\n\t return ident;\n\t }\n\t else if (ident[versionSeparator - 1] === '.') {\n\t // Empty extension. Do not include '.' in the filename.\n\t return ident.slice(0, versionSeparator - 1);\n\t }\n\t else {\n\t // Include up to version separator.\n\t return ident.slice(0, versionSeparator);\n\t }\n\t};\n\tDirectoryRecord.prototype.isDirectory = function isDirectory (isoData) {\n\t var rv = !!(this.fileFlags() & 2 /* Directory */);\n\t // If it lacks the Directory flag, it may still be a directory if we've exceeded the directory\n\t // depth limit. Rock Ridge marks these as files and adds a special attribute.\n\t if (!rv && this.hasRockRidge()) {\n\t rv = this.getSUEntries(isoData).filter(function (e) { return e instanceof CLEntry; }).length > 0;\n\t }\n\t return rv;\n\t};\n\tDirectoryRecord.prototype.isSymlink = function isSymlink (isoData) {\n\t return this.hasRockRidge() && this.getSUEntries(isoData).filter(function (e) { return e instanceof SLEntry; }).length > 0;\n\t};\n\tDirectoryRecord.prototype.getSymlinkPath = function getSymlinkPath (isoData) {\n\t var p = \"\";\n\t var entries = this.getSUEntries(isoData);\n\t var getStr = this._getGetString();\n\t for (var i = 0, list = entries; i < list.length; i += 1) {\n\t var entry = list[i];\n\t\n\t if (entry instanceof SLEntry) {\n\t var components = entry.componentRecords();\n\t for (var i$1 = 0, list$1 = components; i$1 < list$1.length; i$1 += 1) {\n\t var component = list$1[i$1];\n\t\n\t var flags = component.flags();\n\t if (flags & 2 /* CURRENT */) {\n\t p += \"./\";\n\t }\n\t else if (flags & 4 /* PARENT */) {\n\t p += \"../\";\n\t }\n\t else if (flags & 8 /* ROOT */) {\n\t p += \"/\";\n\t }\n\t else {\n\t p += component.content(getStr);\n\t if (!(flags & 1 /* CONTINUE */)) {\n\t p += '/';\n\t }\n\t }\n\t }\n\t if (!entry.continueFlag()) {\n\t // We are done with this link.\n\t break;\n\t }\n\t }\n\t }\n\t if (p.length > 1 && p[p.length - 1] === '/') {\n\t // Trim trailing '/'.\n\t return p.slice(0, p.length - 1);\n\t }\n\t else {\n\t return p;\n\t }\n\t};\n\tDirectoryRecord.prototype.getFile = function getFile (isoData) {\n\t if (this.isDirectory(isoData)) {\n\t throw new Error(\"Tried to get a File from a directory.\");\n\t }\n\t if (this._fileOrDir === null) {\n\t this._fileOrDir = isoData.slice(this.lba(), this.lba() + this.dataLength());\n\t }\n\t return this._fileOrDir;\n\t};\n\tDirectoryRecord.prototype.getDirectory = function getDirectory (isoData) {\n\t if (!this.isDirectory(isoData)) {\n\t throw new Error(\"Tried to get a Directory from a file.\");\n\t }\n\t if (this._fileOrDir === null) {\n\t this._fileOrDir = this._constructDirectory(isoData);\n\t }\n\t return this._fileOrDir;\n\t};\n\tDirectoryRecord.prototype.getSUEntries = function getSUEntries (isoData) {\n\t if (!this._suEntries) {\n\t this._constructSUEntries(isoData);\n\t }\n\t return this._suEntries;\n\t};\n\tDirectoryRecord.prototype._rockRidgeFilename = function _rockRidgeFilename (isoData) {\n\t var nmEntries = this.getSUEntries(isoData).filter(function (e) { return e instanceof NMEntry; });\n\t if (nmEntries.length === 0 || nmEntries[0].flags() & (2 /* CURRENT */ | 4 /* PARENT */)) {\n\t return null;\n\t }\n\t var str = '';\n\t var getString = this._getGetString();\n\t for (var i = 0, list = nmEntries; i < list.length; i += 1) {\n\t var e = list[i];\n\t\n\t str += e.name(getString);\n\t if (!(e.flags() & 1 /* CONTINUE */)) {\n\t break;\n\t }\n\t }\n\t return str;\n\t};\n\tDirectoryRecord.prototype._constructSUEntries = function _constructSUEntries (isoData) {\n\t var i = 33 + this._data[32];\n\t if (i % 2 === 1) {\n\t // Skip padding field.\n\t i++;\n\t }\n\t i += this._rockRidgeOffset;\n\t this._suEntries = constructSystemUseEntries(this._data, i, this.length(), isoData);\n\t};\n\t/**\n\t * !!ONLY VALID ON FIRST ENTRY OF ROOT DIRECTORY!!\n\t * Returns -1 if rock ridge is not enabled. Otherwise, returns the offset\n\t * at which system use fields begin.\n\t */\n\tDirectoryRecord.prototype._getRockRidgeOffset = function _getRockRidgeOffset (isoData) {\n\t // In the worst case, we get some garbage SU entries.\n\t // Fudge offset to 0 before proceeding.\n\t this._rockRidgeOffset = 0;\n\t var suEntries = this.getSUEntries(isoData);\n\t if (suEntries.length > 0) {\n\t var spEntry = suEntries[0];\n\t if (spEntry instanceof SPEntry && spEntry.checkBytesPass()) {\n\t // SUSP is in use.\n\t for (var i = 1; i < suEntries.length; i++) {\n\t var entry = suEntries[i];\n\t if (entry instanceof RREntry || (entry instanceof EREntry && entry.extensionIdentifier() === rockRidgeIdentifier)) {\n\t // Rock Ridge is in use!\n\t return spEntry.bytesSkipped();\n\t }\n\t }\n\t }\n\t }\n\t // Failed.\n\t this._rockRidgeOffset = -1;\n\t return -1;\n\t};\n\t/**\n\t * @hidden\n\t */\n\tvar ISODirectoryRecord = (function (DirectoryRecord) {\n\t function ISODirectoryRecord(data, rockRidgeOffset) {\n\t DirectoryRecord.call(this, data, rockRidgeOffset);\n\t }\n\t\n\t if ( DirectoryRecord ) ISODirectoryRecord.__proto__ = DirectoryRecord;\n\t ISODirectoryRecord.prototype = Object.create( DirectoryRecord && DirectoryRecord.prototype );\n\t ISODirectoryRecord.prototype.constructor = ISODirectoryRecord;\n\t ISODirectoryRecord.prototype._getString = function _getString (i, len) {\n\t return getASCIIString(this._data, i, len);\n\t };\n\t ISODirectoryRecord.prototype._constructDirectory = function _constructDirectory (isoData) {\n\t return new ISODirectory(this, isoData);\n\t };\n\t ISODirectoryRecord.prototype._getGetString = function _getGetString () {\n\t return getASCIIString;\n\t };\n\t\n\t return ISODirectoryRecord;\n\t}(DirectoryRecord));\n\t/**\n\t * @hidden\n\t */\n\tvar JolietDirectoryRecord = (function (DirectoryRecord) {\n\t function JolietDirectoryRecord(data, rockRidgeOffset) {\n\t DirectoryRecord.call(this, data, rockRidgeOffset);\n\t }\n\t\n\t if ( DirectoryRecord ) JolietDirectoryRecord.__proto__ = DirectoryRecord;\n\t JolietDirectoryRecord.prototype = Object.create( DirectoryRecord && DirectoryRecord.prototype );\n\t JolietDirectoryRecord.prototype.constructor = JolietDirectoryRecord;\n\t JolietDirectoryRecord.prototype._getString = function _getString (i, len) {\n\t return getJolietString(this._data, i, len);\n\t };\n\t JolietDirectoryRecord.prototype._constructDirectory = function _constructDirectory (isoData) {\n\t return new JolietDirectory(this, isoData);\n\t };\n\t JolietDirectoryRecord.prototype._getGetString = function _getGetString () {\n\t return getJolietString;\n\t };\n\t\n\t return JolietDirectoryRecord;\n\t}(DirectoryRecord));\n\t/**\n\t * @hidden\n\t */\n\tvar SystemUseEntry = function SystemUseEntry(data) {\n\t this._data = data;\n\t};\n\tSystemUseEntry.prototype.signatureWord = function signatureWord () {\n\t return this._data.readUInt16BE(0);\n\t};\n\tSystemUseEntry.prototype.signatureWordString = function signatureWordString () {\n\t return getASCIIString(this._data, 0, 2);\n\t};\n\tSystemUseEntry.prototype.length = function length () {\n\t return this._data[2];\n\t};\n\tSystemUseEntry.prototype.suVersion = function suVersion () {\n\t return this._data[3];\n\t};\n\t/**\n\t * Continuation entry.\n\t * @hidden\n\t */\n\tvar CEEntry = (function (SystemUseEntry) {\n\t function CEEntry(data) {\n\t SystemUseEntry.call(this, data);\n\t this._entries = null;\n\t }\n\t\n\t if ( SystemUseEntry ) CEEntry.__proto__ = SystemUseEntry;\n\t CEEntry.prototype = Object.create( SystemUseEntry && SystemUseEntry.prototype );\n\t CEEntry.prototype.constructor = CEEntry;\n\t /**\n\t * Logical block address of the continuation area.\n\t */\n\t CEEntry.prototype.continuationLba = function continuationLba () {\n\t return this._data.readUInt32LE(4);\n\t };\n\t /**\n\t * Offset into the logical block.\n\t */\n\t CEEntry.prototype.continuationLbaOffset = function continuationLbaOffset () {\n\t return this._data.readUInt32LE(12);\n\t };\n\t /**\n\t * Length of the continuation area.\n\t */\n\t CEEntry.prototype.continuationLength = function continuationLength () {\n\t return this._data.readUInt32LE(20);\n\t };\n\t CEEntry.prototype.getEntries = function getEntries (isoData) {\n\t if (!this._entries) {\n\t var start = this.continuationLba() * 2048 + this.continuationLbaOffset();\n\t this._entries = constructSystemUseEntries(isoData, start, this.continuationLength(), isoData);\n\t }\n\t return this._entries;\n\t };\n\t\n\t return CEEntry;\n\t}(SystemUseEntry));\n\t/**\n\t * Padding entry.\n\t * @hidden\n\t */\n\tvar PDEntry = (function (SystemUseEntry) {\n\t function PDEntry(data) {\n\t SystemUseEntry.call(this, data);\n\t }\n\t\n\t if ( SystemUseEntry ) PDEntry.__proto__ = SystemUseEntry;\n\t PDEntry.prototype = Object.create( SystemUseEntry && SystemUseEntry.prototype );\n\t PDEntry.prototype.constructor = PDEntry;\n\t\n\t return PDEntry;\n\t}(SystemUseEntry));\n\t/**\n\t * Identifies that SUSP is in-use.\n\t * @hidden\n\t */\n\tvar SPEntry = (function (SystemUseEntry) {\n\t function SPEntry(data) {\n\t SystemUseEntry.call(this, data);\n\t }\n\t\n\t if ( SystemUseEntry ) SPEntry.__proto__ = SystemUseEntry;\n\t SPEntry.prototype = Object.create( SystemUseEntry && SystemUseEntry.prototype );\n\t SPEntry.prototype.constructor = SPEntry;\n\t SPEntry.prototype.checkBytesPass = function checkBytesPass () {\n\t return this._data[4] === 0xBE && this._data[5] === 0xEF;\n\t };\n\t SPEntry.prototype.bytesSkipped = function bytesSkipped () {\n\t return this._data[6];\n\t };\n\t\n\t return SPEntry;\n\t}(SystemUseEntry));\n\t/**\n\t * Identifies the end of the SUSP entries.\n\t * @hidden\n\t */\n\tvar STEntry = (function (SystemUseEntry) {\n\t function STEntry(data) {\n\t SystemUseEntry.call(this, data);\n\t }\n\t\n\t if ( SystemUseEntry ) STEntry.__proto__ = SystemUseEntry;\n\t STEntry.prototype = Object.create( SystemUseEntry && SystemUseEntry.prototype );\n\t STEntry.prototype.constructor = STEntry;\n\t\n\t return STEntry;\n\t}(SystemUseEntry));\n\t/**\n\t * Specifies system-specific extensions to SUSP.\n\t * @hidden\n\t */\n\tvar EREntry = (function (SystemUseEntry) {\n\t function EREntry(data) {\n\t SystemUseEntry.call(this, data);\n\t }\n\t\n\t if ( SystemUseEntry ) EREntry.__proto__ = SystemUseEntry;\n\t EREntry.prototype = Object.create( SystemUseEntry && SystemUseEntry.prototype );\n\t EREntry.prototype.constructor = EREntry;\n\t EREntry.prototype.identifierLength = function identifierLength () {\n\t return this._data[4];\n\t };\n\t EREntry.prototype.descriptorLength = function descriptorLength () {\n\t return this._data[5];\n\t };\n\t EREntry.prototype.sourceLength = function sourceLength () {\n\t return this._data[6];\n\t };\n\t EREntry.prototype.extensionVersion = function extensionVersion () {\n\t return this._data[7];\n\t };\n\t EREntry.prototype.extensionIdentifier = function extensionIdentifier () {\n\t return getASCIIString(this._data, 8, this.identifierLength());\n\t };\n\t EREntry.prototype.extensionDescriptor = function extensionDescriptor () {\n\t return getASCIIString(this._data, 8 + this.identifierLength(), this.descriptorLength());\n\t };\n\t EREntry.prototype.extensionSource = function extensionSource () {\n\t return getASCIIString(this._data, 8 + this.identifierLength() + this.descriptorLength(), this.sourceLength());\n\t };\n\t\n\t return EREntry;\n\t}(SystemUseEntry));\n\t/**\n\t * @hidden\n\t */\n\tvar ESEntry = (function (SystemUseEntry) {\n\t function ESEntry(data) {\n\t SystemUseEntry.call(this, data);\n\t }\n\t\n\t if ( SystemUseEntry ) ESEntry.__proto__ = SystemUseEntry;\n\t ESEntry.prototype = Object.create( SystemUseEntry && SystemUseEntry.prototype );\n\t ESEntry.prototype.constructor = ESEntry;\n\t ESEntry.prototype.extensionSequence = function extensionSequence () {\n\t return this._data[4];\n\t };\n\t\n\t return ESEntry;\n\t}(SystemUseEntry));\n\t/**\n\t * RockRidge: Marks that RockRidge is in use [deprecated]\n\t * @hidden\n\t */\n\tvar RREntry = (function (SystemUseEntry) {\n\t function RREntry(data) {\n\t SystemUseEntry.call(this, data);\n\t }\n\t\n\t if ( SystemUseEntry ) RREntry.__proto__ = SystemUseEntry;\n\t RREntry.prototype = Object.create( SystemUseEntry && SystemUseEntry.prototype );\n\t RREntry.prototype.constructor = RREntry;\n\t\n\t return RREntry;\n\t}(SystemUseEntry));\n\t/**\n\t * RockRidge: Records POSIX file attributes.\n\t * @hidden\n\t */\n\tvar PXEntry = (function (SystemUseEntry) {\n\t function PXEntry(data) {\n\t SystemUseEntry.call(this, data);\n\t }\n\t\n\t if ( SystemUseEntry ) PXEntry.__proto__ = SystemUseEntry;\n\t PXEntry.prototype = Object.create( SystemUseEntry && SystemUseEntry.prototype );\n\t PXEntry.prototype.constructor = PXEntry;\n\t PXEntry.prototype.mode = function mode () {\n\t return this._data.readUInt32LE(4);\n\t };\n\t PXEntry.prototype.fileLinks = function fileLinks () {\n\t return this._data.readUInt32LE(12);\n\t };\n\t PXEntry.prototype.uid = function uid () {\n\t return this._data.readUInt32LE(20);\n\t };\n\t PXEntry.prototype.gid = function gid () {\n\t return this._data.readUInt32LE(28);\n\t };\n\t PXEntry.prototype.inode = function inode () {\n\t return this._data.readUInt32LE(36);\n\t };\n\t\n\t return PXEntry;\n\t}(SystemUseEntry));\n\t/**\n\t * RockRidge: Records POSIX device number.\n\t * @hidden\n\t */\n\tvar PNEntry = (function (SystemUseEntry) {\n\t function PNEntry(data) {\n\t SystemUseEntry.call(this, data);\n\t }\n\t\n\t if ( SystemUseEntry ) PNEntry.__proto__ = SystemUseEntry;\n\t PNEntry.prototype = Object.create( SystemUseEntry && SystemUseEntry.prototype );\n\t PNEntry.prototype.constructor = PNEntry;\n\t PNEntry.prototype.devTHigh = function devTHigh () {\n\t return this._data.readUInt32LE(4);\n\t };\n\t PNEntry.prototype.devTLow = function devTLow () {\n\t return this._data.readUInt32LE(12);\n\t };\n\t\n\t return PNEntry;\n\t}(SystemUseEntry));\n\t/**\n\t * RockRidge: Records symbolic link\n\t * @hidden\n\t */\n\tvar SLEntry = (function (SystemUseEntry) {\n\t function SLEntry(data) {\n\t SystemUseEntry.call(this, data);\n\t }\n\t\n\t if ( SystemUseEntry ) SLEntry.__proto__ = SystemUseEntry;\n\t SLEntry.prototype = Object.create( SystemUseEntry && SystemUseEntry.prototype );\n\t SLEntry.prototype.constructor = SLEntry;\n\t SLEntry.prototype.flags = function flags () {\n\t return this._data[4];\n\t };\n\t SLEntry.prototype.continueFlag = function continueFlag () {\n\t return this.flags() & 0x1;\n\t };\n\t SLEntry.prototype.componentRecords = function componentRecords () {\n\t var this$1 = this;\n\t\n\t var records = new Array();\n\t var i = 5;\n\t while (i < this.length()) {\n\t var record = new SLComponentRecord(this$1._data.slice(i));\n\t records.push(record);\n\t i += record.length();\n\t }\n\t return records;\n\t };\n\t\n\t return SLEntry;\n\t}(SystemUseEntry));\n\t/**\n\t * @hidden\n\t */\n\tvar SLComponentRecord = function SLComponentRecord(data) {\n\t this._data = data;\n\t};\n\tSLComponentRecord.prototype.flags = function flags () {\n\t return this._data[0];\n\t};\n\tSLComponentRecord.prototype.length = function length () {\n\t return 2 + this.componentLength();\n\t};\n\tSLComponentRecord.prototype.componentLength = function componentLength () {\n\t return this._data[1];\n\t};\n\tSLComponentRecord.prototype.content = function content (getString) {\n\t return getString(this._data, 2, this.componentLength());\n\t};\n\t/**\n\t * RockRidge: Records alternate file name\n\t * @hidden\n\t */\n\tvar NMEntry = (function (SystemUseEntry) {\n\t function NMEntry(data) {\n\t SystemUseEntry.call(this, data);\n\t }\n\t\n\t if ( SystemUseEntry ) NMEntry.__proto__ = SystemUseEntry;\n\t NMEntry.prototype = Object.create( SystemUseEntry && SystemUseEntry.prototype );\n\t NMEntry.prototype.constructor = NMEntry;\n\t NMEntry.prototype.flags = function flags () {\n\t return this._data[4];\n\t };\n\t NMEntry.prototype.name = function name (getString) {\n\t return getString(this._data, 5, this.length() - 5);\n\t };\n\t\n\t return NMEntry;\n\t}(SystemUseEntry));\n\t/**\n\t * RockRidge: Records child link\n\t * @hidden\n\t */\n\tvar CLEntry = (function (SystemUseEntry) {\n\t function CLEntry(data) {\n\t SystemUseEntry.call(this, data);\n\t }\n\t\n\t if ( SystemUseEntry ) CLEntry.__proto__ = SystemUseEntry;\n\t CLEntry.prototype = Object.create( SystemUseEntry && SystemUseEntry.prototype );\n\t CLEntry.prototype.constructor = CLEntry;\n\t CLEntry.prototype.childDirectoryLba = function childDirectoryLba () {\n\t return this._data.readUInt32LE(4);\n\t };\n\t\n\t return CLEntry;\n\t}(SystemUseEntry));\n\t/**\n\t * RockRidge: Records parent link.\n\t * @hidden\n\t */\n\tvar PLEntry = (function (SystemUseEntry) {\n\t function PLEntry(data) {\n\t SystemUseEntry.call(this, data);\n\t }\n\t\n\t if ( SystemUseEntry ) PLEntry.__proto__ = SystemUseEntry;\n\t PLEntry.prototype = Object.create( SystemUseEntry && SystemUseEntry.prototype );\n\t PLEntry.prototype.constructor = PLEntry;\n\t PLEntry.prototype.parentDirectoryLba = function parentDirectoryLba () {\n\t return this._data.readUInt32LE(4);\n\t };\n\t\n\t return PLEntry;\n\t}(SystemUseEntry));\n\t/**\n\t * RockRidge: Records relocated directory.\n\t * @hidden\n\t */\n\tvar REEntry = (function (SystemUseEntry) {\n\t function REEntry(data) {\n\t SystemUseEntry.call(this, data);\n\t }\n\t\n\t if ( SystemUseEntry ) REEntry.__proto__ = SystemUseEntry;\n\t REEntry.prototype = Object.create( SystemUseEntry && SystemUseEntry.prototype );\n\t REEntry.prototype.constructor = REEntry;\n\t\n\t return REEntry;\n\t}(SystemUseEntry));\n\t/**\n\t * RockRidge: Records file timestamps\n\t * @hidden\n\t */\n\tvar TFEntry = (function (SystemUseEntry) {\n\t function TFEntry(data) {\n\t SystemUseEntry.call(this, data);\n\t }\n\t\n\t if ( SystemUseEntry ) TFEntry.__proto__ = SystemUseEntry;\n\t TFEntry.prototype = Object.create( SystemUseEntry && SystemUseEntry.prototype );\n\t TFEntry.prototype.constructor = TFEntry;\n\t TFEntry.prototype.flags = function flags () {\n\t return this._data[4];\n\t };\n\t TFEntry.prototype.creation = function creation () {\n\t if (this.flags() & 1 /* CREATION */) {\n\t if (this._longFormDates()) {\n\t return getDate(this._data, 5);\n\t }\n\t else {\n\t return getShortFormDate(this._data, 5);\n\t }\n\t }\n\t else {\n\t return null;\n\t }\n\t };\n\t TFEntry.prototype.modify = function modify () {\n\t if (this.flags() & 2 /* MODIFY */) {\n\t var previousDates = (this.flags() & 1 /* CREATION */) ? 1 : 0;\n\t if (this._longFormDates) {\n\t return getDate(this._data, 5 + (previousDates * 17));\n\t }\n\t else {\n\t return getShortFormDate(this._data, 5 + (previousDates * 7));\n\t }\n\t }\n\t else {\n\t return null;\n\t }\n\t };\n\t TFEntry.prototype.access = function access () {\n\t if (this.flags() & 4 /* ACCESS */) {\n\t var previousDates = (this.flags() & 1 /* CREATION */) ? 1 : 0;\n\t previousDates += (this.flags() & 2 /* MODIFY */) ? 1 : 0;\n\t if (this._longFormDates) {\n\t return getDate(this._data, 5 + (previousDates * 17));\n\t }\n\t else {\n\t return getShortFormDate(this._data, 5 + (previousDates * 7));\n\t }\n\t }\n\t else {\n\t return null;\n\t }\n\t };\n\t TFEntry.prototype.backup = function backup () {\n\t if (this.flags() & 16 /* BACKUP */) {\n\t var previousDates = (this.flags() & 1 /* CREATION */) ? 1 : 0;\n\t previousDates += (this.flags() & 2 /* MODIFY */) ? 1 : 0;\n\t previousDates += (this.flags() & 4 /* ACCESS */) ? 1 : 0;\n\t if (this._longFormDates) {\n\t return getDate(this._data, 5 + (previousDates * 17));\n\t }\n\t else {\n\t return getShortFormDate(this._data, 5 + (previousDates * 7));\n\t }\n\t }\n\t else {\n\t return null;\n\t }\n\t };\n\t TFEntry.prototype.expiration = function expiration () {\n\t if (this.flags() & 32 /* EXPIRATION */) {\n\t var previousDates = (this.flags() & 1 /* CREATION */) ? 1 : 0;\n\t previousDates += (this.flags() & 2 /* MODIFY */) ? 1 : 0;\n\t previousDates += (this.flags() & 4 /* ACCESS */) ? 1 : 0;\n\t previousDates += (this.flags() & 16 /* BACKUP */) ? 1 : 0;\n\t if (this._longFormDates) {\n\t return getDate(this._data, 5 + (previousDates * 17));\n\t }\n\t else {\n\t return getShortFormDate(this._data, 5 + (previousDates * 7));\n\t }\n\t }\n\t else {\n\t return null;\n\t }\n\t };\n\t TFEntry.prototype.effective = function effective () {\n\t if (this.flags() & 64 /* EFFECTIVE */) {\n\t var previousDates = (this.flags() & 1 /* CREATION */) ? 1 : 0;\n\t previousDates += (this.flags() & 2 /* MODIFY */) ? 1 : 0;\n\t previousDates += (this.flags() & 4 /* ACCESS */) ? 1 : 0;\n\t previousDates += (this.flags() & 16 /* BACKUP */) ? 1 : 0;\n\t previousDates += (this.flags() & 32 /* EXPIRATION */) ? 1 : 0;\n\t if (this._longFormDates) {\n\t return getDate(this._data, 5 + (previousDates * 17));\n\t }\n\t else {\n\t return getShortFormDate(this._data, 5 + (previousDates * 7));\n\t }\n\t }\n\t else {\n\t return null;\n\t }\n\t };\n\t TFEntry.prototype._longFormDates = function _longFormDates () {\n\t return !!(this.flags() && 128 /* LONG_FORM */);\n\t };\n\t\n\t return TFEntry;\n\t}(SystemUseEntry));\n\t/**\n\t * RockRidge: File data in sparse format.\n\t * @hidden\n\t */\n\tvar SFEntry = (function (SystemUseEntry) {\n\t function SFEntry(data) {\n\t SystemUseEntry.call(this, data);\n\t }\n\t\n\t if ( SystemUseEntry ) SFEntry.__proto__ = SystemUseEntry;\n\t SFEntry.prototype = Object.create( SystemUseEntry && SystemUseEntry.prototype );\n\t SFEntry.prototype.constructor = SFEntry;\n\t SFEntry.prototype.virtualSizeHigh = function virtualSizeHigh () {\n\t return this._data.readUInt32LE(4);\n\t };\n\t SFEntry.prototype.virtualSizeLow = function virtualSizeLow () {\n\t return this._data.readUInt32LE(12);\n\t };\n\t SFEntry.prototype.tableDepth = function tableDepth () {\n\t return this._data[20];\n\t };\n\t\n\t return SFEntry;\n\t}(SystemUseEntry));\n\t/**\n\t * @hidden\n\t */\n\tvar Directory = function Directory(record, isoData) {\n\t var this$1 = this;\n\t\n\t this._fileList = [];\n\t this._fileMap = {};\n\t this._record = record;\n\t var i = record.lba();\n\t var iLimit = i + record.dataLength();\n\t if (!(record.fileFlags() & 2 /* Directory */)) {\n\t // Must have a CL entry.\n\t var cl = record.getSUEntries(isoData).filter(function (e) { return e instanceof CLEntry; })[0];\n\t i = cl.childDirectoryLba() * 2048;\n\t iLimit = Infinity;\n\t }\n\t while (i < iLimit) {\n\t var len = isoData[i];\n\t // Zero-padding between sectors.\n\t // TODO: Could optimize this to seek to nearest-sector upon\n\t // seeing a 0.\n\t if (len === 0) {\n\t i++;\n\t continue;\n\t }\n\t var r = this$1._constructDirectoryRecord(isoData.slice(i));\n\t var fname = r.fileName(isoData);\n\t // Skip '.' and '..' entries.\n\t if (fname !== '\\u0000' && fname !== '\\u0001') {\n\t // Skip relocated entries.\n\t if (!r.hasRockRidge() || r.getSUEntries(isoData).filter(function (e) { return e instanceof REEntry; }).length === 0) {\n\t this$1._fileMap[fname] = r;\n\t this$1._fileList.push(fname);\n\t }\n\t }\n\t else if (iLimit === Infinity) {\n\t // First entry contains needed data.\n\t iLimit = i + r.dataLength();\n\t }\n\t i += r.length();\n\t }\n\t};\n\t/**\n\t * Get the record with the given name.\n\t * Returns undefined if not present.\n\t */\n\tDirectory.prototype.getRecord = function getRecord (name) {\n\t return this._fileMap[name];\n\t};\n\tDirectory.prototype.getFileList = function getFileList () {\n\t return this._fileList;\n\t};\n\tDirectory.prototype.getDotEntry = function getDotEntry (isoData) {\n\t return this._constructDirectoryRecord(isoData.slice(this._record.lba()));\n\t};\n\t/**\n\t * @hidden\n\t */\n\tvar ISODirectory = (function (Directory) {\n\t function ISODirectory(record, isoData) {\n\t Directory.call(this, record, isoData);\n\t }\n\t\n\t if ( Directory ) ISODirectory.__proto__ = Directory;\n\t ISODirectory.prototype = Object.create( Directory && Directory.prototype );\n\t ISODirectory.prototype.constructor = ISODirectory;\n\t ISODirectory.prototype._constructDirectoryRecord = function _constructDirectoryRecord (data) {\n\t return new ISODirectoryRecord(data, this._record.getRockRidgeOffset());\n\t };\n\t\n\t return ISODirectory;\n\t}(Directory));\n\t/**\n\t * @hidden\n\t */\n\tvar JolietDirectory = (function (Directory) {\n\t function JolietDirectory(record, isoData) {\n\t Directory.call(this, record, isoData);\n\t }\n\t\n\t if ( Directory ) JolietDirectory.__proto__ = Directory;\n\t JolietDirectory.prototype = Object.create( Directory && Directory.prototype );\n\t JolietDirectory.prototype.constructor = JolietDirectory;\n\t JolietDirectory.prototype._constructDirectoryRecord = function _constructDirectoryRecord (data) {\n\t return new JolietDirectoryRecord(data, this._record.getRockRidgeOffset());\n\t };\n\t\n\t return JolietDirectory;\n\t}(Directory));\n\t/**\n\t * Mounts an ISO file as a read-only file system.\n\t *\n\t * Supports:\n\t * * Vanilla ISO9660 ISOs\n\t * * Microsoft Joliet and Rock Ridge extensions to the ISO9660 standard\n\t */\n\tvar IsoFS = (function (SynchronousFileSystem$$1) {\n\t function IsoFS(data, name, deprecateMsg) {\n\t var this$1 = this;\n\t if ( name === void 0 ) name = \"\";\n\t if ( deprecateMsg === void 0 ) deprecateMsg = true;\n\t\n\t SynchronousFileSystem$$1.call(this);\n\t this._data = data;\n\t deprecationMessage(deprecateMsg, IsoFS.Name, { data: \"ISO data as a Buffer\", name: name });\n\t // Skip first 16 sectors.\n\t var vdTerminatorFound = false;\n\t var i = 16 * 2048;\n\t var candidateVDs = new Array();\n\t while (!vdTerminatorFound) {\n\t var slice = data.slice(i);\n\t var vd = new VolumeDescriptor(slice);\n\t switch (vd.type()) {\n\t case 1 /* PrimaryVolumeDescriptor */:\n\t candidateVDs.push(new PrimaryVolumeDescriptor(slice));\n\t break;\n\t case 2 /* SupplementaryVolumeDescriptor */:\n\t candidateVDs.push(new SupplementaryVolumeDescriptor(slice));\n\t break;\n\t case 255 /* VolumeDescriptorSetTerminator */:\n\t vdTerminatorFound = true;\n\t break;\n\t }\n\t i += 2048;\n\t }\n\t if (candidateVDs.length === 0) {\n\t throw new ApiError(ErrorCode.EIO, \"Unable to find a suitable volume descriptor.\");\n\t }\n\t candidateVDs.forEach(function (v) {\n\t // Take an SVD over a PVD.\n\t if (!this$1._pvd || this$1._pvd.type() !== 2 /* SupplementaryVolumeDescriptor */) {\n\t this$1._pvd = v;\n\t }\n\t });\n\t this._root = this._pvd.rootDirectoryEntry(data);\n\t this._name = name;\n\t }\n\t\n\t if ( SynchronousFileSystem$$1 ) IsoFS.__proto__ = SynchronousFileSystem$$1;\n\t IsoFS.prototype = Object.create( SynchronousFileSystem$$1 && SynchronousFileSystem$$1.prototype );\n\t IsoFS.prototype.constructor = IsoFS;\n\t /**\n\t * Creates an IsoFS instance with the given options.\n\t */\n\t IsoFS.Create = function Create (opts, cb) {\n\t var fs;\n\t var e;\n\t try {\n\t fs = new IsoFS(opts.data, opts.name, false);\n\t }\n\t catch (e) {\n\t e = e;\n\t }\n\t finally {\n\t cb(e, fs);\n\t }\n\t };\n\t IsoFS.isAvailable = function isAvailable () {\n\t return true;\n\t };\n\t IsoFS.prototype.getName = function getName () {\n\t var name = \"IsoFS\" + (this._name) + (this._pvd ? (\"-\" + (this._pvd.name())) : '');\n\t if (this._root && this._root.hasRockRidge()) {\n\t name += \"-RockRidge\";\n\t }\n\t return name;\n\t };\n\t IsoFS.prototype.diskSpace = function diskSpace (path$$1, cb) {\n\t // Read-only file system.\n\t cb(this._data.length, 0);\n\t };\n\t IsoFS.prototype.isReadOnly = function isReadOnly () {\n\t return true;\n\t };\n\t IsoFS.prototype.supportsLinks = function supportsLinks () {\n\t return false;\n\t };\n\t IsoFS.prototype.supportsProps = function supportsProps () {\n\t return false;\n\t };\n\t IsoFS.prototype.supportsSynch = function supportsSynch () {\n\t return true;\n\t };\n\t IsoFS.prototype.statSync = function statSync (p, isLstat) {\n\t var record = this._getDirectoryRecord(p);\n\t if (record === null) {\n\t throw ApiError.ENOENT(p);\n\t }\n\t return this._getStats(p, record);\n\t };\n\t IsoFS.prototype.openSync = function openSync (p, flags, mode) {\n\t // INVARIANT: Cannot write to RO file systems.\n\t if (flags.isWriteable()) {\n\t throw new ApiError(ErrorCode.EPERM, p);\n\t }\n\t // Check if the path exists, and is a file.\n\t var record = this._getDirectoryRecord(p);\n\t if (!record) {\n\t throw ApiError.ENOENT(p);\n\t }\n\t else if (record.isSymlink(this._data)) {\n\t return this.openSync(path.resolve(p, record.getSymlinkPath(this._data)), flags, mode);\n\t }\n\t else if (!record.isDirectory(this._data)) {\n\t var data = record.getFile(this._data);\n\t var stats = this._getStats(p, record);\n\t switch (flags.pathExistsAction()) {\n\t case ActionType.THROW_EXCEPTION:\n\t case ActionType.TRUNCATE_FILE:\n\t throw ApiError.EEXIST(p);\n\t case ActionType.NOP:\n\t return new NoSyncFile(this, p, flags, stats, data);\n\t default:\n\t throw new ApiError(ErrorCode.EINVAL, 'Invalid FileMode object.');\n\t }\n\t }\n\t else {\n\t throw ApiError.EISDIR(p);\n\t }\n\t };\n\t IsoFS.prototype.readdirSync = function readdirSync (path$$1) {\n\t // Check if it exists.\n\t var record = this._getDirectoryRecord(path$$1);\n\t if (!record) {\n\t throw ApiError.ENOENT(path$$1);\n\t }\n\t else if (record.isDirectory(this._data)) {\n\t return record.getDirectory(this._data).getFileList().slice(0);\n\t }\n\t else {\n\t throw ApiError.ENOTDIR(path$$1);\n\t }\n\t };\n\t /**\n\t * Specially-optimized readfile.\n\t */\n\t IsoFS.prototype.readFileSync = function readFileSync (fname, encoding, flag) {\n\t // Get file.\n\t var fd = this.openSync(fname, flag, 0x1a4);\n\t try {\n\t var fdCast = fd;\n\t var fdBuff = fdCast.getBuffer();\n\t if (encoding === null) {\n\t return copyingSlice(fdBuff);\n\t }\n\t return fdBuff.toString(encoding);\n\t }\n\t finally {\n\t fd.closeSync();\n\t }\n\t };\n\t IsoFS.prototype._getDirectoryRecord = function _getDirectoryRecord (path$$1) {\n\t var this$1 = this;\n\t\n\t // Special case.\n\t if (path$$1 === '/') {\n\t return this._root;\n\t }\n\t var components = path$$1.split('/').slice(1);\n\t var dir = this._root;\n\t for (var i = 0, list = components; i < list.length; i += 1) {\n\t var component = list[i];\n\t\n\t if (dir.isDirectory(this$1._data)) {\n\t dir = dir.getDirectory(this$1._data).getRecord(component);\n\t if (!dir) {\n\t return null;\n\t }\n\t }\n\t else {\n\t return null;\n\t }\n\t }\n\t return dir;\n\t };\n\t IsoFS.prototype._getStats = function _getStats (p, record) {\n\t if (record.isSymlink(this._data)) {\n\t var newP = path.resolve(p, record.getSymlinkPath(this._data));\n\t var dirRec = this._getDirectoryRecord(newP);\n\t if (!dirRec) {\n\t return null;\n\t }\n\t return this._getStats(newP, dirRec);\n\t }\n\t else {\n\t var len = record.dataLength();\n\t var mode = 0x16D;\n\t var date = record.recordingDate();\n\t var atime = date;\n\t var mtime = date;\n\t var ctime = date;\n\t if (record.hasRockRidge()) {\n\t var entries = record.getSUEntries(this._data);\n\t for (var i = 0, list = entries; i < list.length; i += 1) {\n\t var entry = list[i];\n\t\n\t if (entry instanceof PXEntry) {\n\t mode = entry.mode();\n\t }\n\t else if (entry instanceof TFEntry) {\n\t var flags = entry.flags();\n\t if (flags & 4 /* ACCESS */) {\n\t atime = entry.access();\n\t }\n\t if (flags & 2 /* MODIFY */) {\n\t mtime = entry.modify();\n\t }\n\t if (flags & 1 /* CREATION */) {\n\t ctime = entry.creation();\n\t }\n\t }\n\t }\n\t }\n\t // Mask out writeable flags. This is a RO file system.\n\t mode = mode & 0x16D;\n\t return new Stats(record.isDirectory(this._data) ? FileType.DIRECTORY : FileType.FILE, len, mode, atime, mtime, ctime);\n\t }\n\t };\n\t\n\t return IsoFS;\n\t}(SynchronousFileSystem));\n\t\n\tIsoFS.Name = \"IsoFS\";\n\tIsoFS.Options = {\n\t data: {\n\t type: \"object\",\n\t description: \"The ISO file in a buffer\",\n\t validator: bufferValidator\n\t }\n\t};\n\t\n\t// Monkey-patch `Create` functions to check options before file system initialization.\n\t[AsyncMirror, DropboxFileSystem, EmscriptenFileSystem, FolderAdapter, HTML5FS, InMemoryFileSystem, IndexedDBFileSystem, IsoFS, LocalStorageFileSystem, MountableFileSystem, OverlayFS, WorkerFS, XmlHttpRequest, ZipFS].forEach(function (fsType) {\n\t var create = fsType.Create;\n\t fsType.Create = function (opts, cb) {\n\t var oneArg = typeof (opts) === \"function\";\n\t var normalizedCb = oneArg ? opts : cb;\n\t var normalizedOpts = oneArg ? {} : opts;\n\t function wrappedCb(e) {\n\t if (e) {\n\t normalizedCb(e);\n\t }\n\t else {\n\t create.call(fsType, normalizedOpts, normalizedCb);\n\t }\n\t }\n\t checkOptions(fsType, normalizedOpts, wrappedCb);\n\t };\n\t});\n\t/**\n\t * @hidden\n\t */\n\tvar Backends = { AsyncMirror: AsyncMirror, Dropbox: DropboxFileSystem, Emscripten: EmscriptenFileSystem, FolderAdapter: FolderAdapter, HTML5FS: HTML5FS, InMemory: InMemoryFileSystem, IndexedDB: IndexedDBFileSystem, IsoFS: IsoFS, LocalStorage: LocalStorageFileSystem, MountableFileSystem: MountableFileSystem, OverlayFS: OverlayFS, WorkerFS: WorkerFS, XmlHttpRequest: XmlHttpRequest, ZipFS: ZipFS };\n\t\n\t/**\n\t * BrowserFS's main module. This is exposed in the browser via the BrowserFS global.\n\t * Due to limitations in typedoc, we document these functions in ./typedoc.ts.\n\t */\n\tif (process['initializeTTYs']) {\n\t process['initializeTTYs']();\n\t}\n\t/**\n\t * Installs BFSRequire as global `require`, a Node Buffer polyfill as the global `Buffer` variable,\n\t * and a Node process polyfill as the global `process` variable.\n\t */\n\tfunction install(obj) {\n\t obj.Buffer = Buffer;\n\t obj.process = process;\n\t var oldRequire = obj.require ? obj.require : null;\n\t // Monkey-patch require for Node-style code.\n\t obj.require = function (arg) {\n\t var rv = BFSRequire(arg);\n\t if (!rv) {\n\t return oldRequire.apply(null, Array.prototype.slice.call(arguments, 0));\n\t }\n\t else {\n\t return rv;\n\t }\n\t };\n\t}\n\t/**\n\t * @hidden\n\t */\n\tfunction registerFileSystem(name, fs) {\n\t Backends[name] = fs;\n\t}\n\tfunction BFSRequire(module) {\n\t switch (module) {\n\t case 'fs':\n\t return _fsMock;\n\t case 'path':\n\t return path;\n\t case 'buffer':\n\t // The 'buffer' module has 'Buffer' as a property.\n\t return buffer;\n\t case 'process':\n\t return process;\n\t case 'bfs_utils':\n\t return BFSUtils;\n\t default:\n\t return Backends[module];\n\t }\n\t}\n\t/**\n\t * Initializes BrowserFS with the given root file system.\n\t */\n\tfunction initialize(rootfs) {\n\t return _fsMock.initialize(rootfs);\n\t}\n\t/**\n\t * Creates a file system with the given configuration, and initializes BrowserFS with it.\n\t * See the FileSystemConfiguration type for more info on the configuration object.\n\t */\n\tfunction configure(config, cb) {\n\t getFileSystem(config, function (e, fs) {\n\t if (fs) {\n\t initialize(fs);\n\t cb();\n\t }\n\t else {\n\t cb(e);\n\t }\n\t });\n\t}\n\t/**\n\t * Retrieve a file system with the given configuration.\n\t * @param config A FileSystemConfiguration object. See FileSystemConfiguration for details.\n\t * @param cb Called when the file system is constructed, or when an error occurs.\n\t */\n\tfunction getFileSystem(config, cb) {\n\t var fsName = config['fs'];\n\t if (!fsName) {\n\t return cb(new ApiError(ErrorCode.EPERM, 'Missing \"fs\" property on configuration object.'));\n\t }\n\t var options = config['options'];\n\t var waitCount = 0;\n\t var called = false;\n\t function finish() {\n\t if (!called) {\n\t called = true;\n\t var fsc = Backends[fsName];\n\t if (!fsc) {\n\t cb(new ApiError(ErrorCode.EPERM, (\"File system \" + fsName + \" is not available in BrowserFS.\")));\n\t }\n\t else {\n\t fsc.Create(options, cb);\n\t }\n\t }\n\t }\n\t if (options !== null && typeof (options) === \"object\") {\n\t var finishedIterating = false;\n\t var props = Object.keys(options).filter(function (k) { return k !== 'fs'; });\n\t // Check recursively if other fields have 'fs' properties.\n\t props.forEach(function (p) {\n\t var d = options[p];\n\t if (d !== null && typeof (d) === \"object\" && d['fs']) {\n\t waitCount++;\n\t getFileSystem(d, function (e, fs) {\n\t waitCount--;\n\t if (e) {\n\t if (called) {\n\t return;\n\t }\n\t called = true;\n\t cb(e);\n\t }\n\t else {\n\t options[p] = fs;\n\t if (waitCount === 0 && finishedIterating) {\n\t finish();\n\t }\n\t }\n\t });\n\t }\n\t });\n\t finishedIterating = true;\n\t }\n\t if (waitCount === 0) {\n\t finish();\n\t }\n\t}\n\t\n\t/**\n\t * BrowserFS's main entry point.\n\t * It installs all of the needed polyfills, and requires() the main module.\n\t */\n\t// IE substr does not support negative indices\n\tif ('ab'.substr(-1) !== 'b') {\n\t String.prototype.substr = function (substr) {\n\t return function (start, length) {\n\t // did we get a negative start, calculate how much it is from the\n\t // beginning of the string\n\t if (start < 0) {\n\t start = this.length + start;\n\t }\n\t // call the original function\n\t return substr.call(this, start, length);\n\t };\n\t }(String.prototype.substr);\n\t}\n\t// Polyfill for Uint8Array.prototype.slice.\n\t// Safari and some other browsers do not define it.\n\tif (typeof (ArrayBuffer) !== 'undefined' && typeof (Uint8Array) !== 'undefined') {\n\t if (!Uint8Array.prototype['slice']) {\n\t Uint8Array.prototype.slice = function (start, end) {\n\t if ( start === void 0 ) start = 0;\n\t if ( end === void 0 ) end = this.length;\n\t\n\t var self = this;\n\t if (start < 0) {\n\t start = this.length + start;\n\t if (start < 0) {\n\t start = 0;\n\t }\n\t }\n\t if (end < 0) {\n\t end = this.length + end;\n\t if (end < 0) {\n\t end = 0;\n\t }\n\t }\n\t if (end < start) {\n\t end = start;\n\t }\n\t return new Uint8Array(self.buffer, self.byteOffset + start, end - start);\n\t };\n\t }\n\t}\n\t\n\texports.install = install;\n\texports.registerFileSystem = registerFileSystem;\n\texports.BFSRequire = BFSRequire;\n\texports.initialize = initialize;\n\texports.configure = configure;\n\texports.getFileSystem = getFileSystem;\n\texports.EmscriptenFS = BFSEmscriptenFS;\n\texports.FileSystem = Backends;\n\texports.Errors = api_error;\n\texports.setImmediate = setImmediate$3;\n\t\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7), (function() { return this; }()), __webpack_require__(41)(module), __webpack_require__(3)))\n\n/***/ },\n/* 1 */\n/***/ function(module, exports, __webpack_require__) {\n\n\t/* WEBPACK VAR INJECTION */(function(Buffer) {/*!\n\t * The buffer module from node.js, for the browser.\n\t *\n\t * @author Feross Aboukhadijeh \n\t * @license MIT\n\t */\n\t/* eslint-disable no-proto */\n\t\n\t'use strict'\n\t\n\tvar base64 = __webpack_require__(18)\n\tvar ieee754 = __webpack_require__(21)\n\t\n\texports.Buffer = Buffer\n\texports.SlowBuffer = SlowBuffer\n\texports.INSPECT_MAX_BYTES = 50\n\t\n\tvar K_MAX_LENGTH = 0x7fffffff\n\texports.kMaxLength = K_MAX_LENGTH\n\t\n\t/**\n\t * If `Buffer.TYPED_ARRAY_SUPPORT`:\n\t * === true Use Uint8Array implementation (fastest)\n\t * === false Print warning and recommend using `buffer` v4.x which has an Object\n\t * implementation (most compatible, even IE6)\n\t *\n\t * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,\n\t * Opera 11.6+, iOS 4.2+.\n\t *\n\t * We report that the browser does not support typed arrays if the are not subclassable\n\t * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`\n\t * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support\n\t * for __proto__ and has a buggy typed array implementation.\n\t */\n\tBuffer.TYPED_ARRAY_SUPPORT = typedArraySupport()\n\t\n\tif (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&\n\t typeof console.error === 'function') {\n\t console.error(\n\t 'This browser lacks typed array (Uint8Array) support which is required by ' +\n\t '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'\n\t )\n\t}\n\t\n\tfunction typedArraySupport () {\n\t // Can typed array instances can be augmented?\n\t try {\n\t var arr = new Uint8Array(1)\n\t arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}\n\t return arr.foo() === 42\n\t } catch (e) {\n\t return false\n\t }\n\t}\n\t\n\tfunction createBuffer (length) {\n\t if (length > K_MAX_LENGTH) {\n\t throw new RangeError('Invalid typed array length')\n\t }\n\t // Return an augmented `Uint8Array` instance\n\t var buf = new Uint8Array(length)\n\t buf.__proto__ = Buffer.prototype\n\t return buf\n\t}\n\t\n\t/**\n\t * The Buffer constructor returns instances of `Uint8Array` that have their\n\t * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of\n\t * `Uint8Array`, so the returned instances will have all the node `Buffer` methods\n\t * and the `Uint8Array` methods. Square bracket notation works as expected -- it\n\t * returns a single octet.\n\t *\n\t * The `Uint8Array` prototype remains unmodified.\n\t */\n\t\n\tfunction Buffer (arg, encodingOrOffset, length) {\n\t // Common case.\n\t if (typeof arg === 'number') {\n\t if (typeof encodingOrOffset === 'string') {\n\t throw new Error(\n\t 'If encoding is specified then the first argument must be a string'\n\t )\n\t }\n\t return allocUnsafe(arg)\n\t }\n\t return from(arg, encodingOrOffset, length)\n\t}\n\t\n\t// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97\n\tif (typeof Symbol !== 'undefined' && Symbol.species &&\n\t Buffer[Symbol.species] === Buffer) {\n\t Object.defineProperty(Buffer, Symbol.species, {\n\t value: null,\n\t configurable: true,\n\t enumerable: false,\n\t writable: false\n\t })\n\t}\n\t\n\tBuffer.poolSize = 8192 // not used by this implementation\n\t\n\tfunction from (value, encodingOrOffset, length) {\n\t if (typeof value === 'number') {\n\t throw new TypeError('\"value\" argument must not be a number')\n\t }\n\t\n\t if (isArrayBuffer(value)) {\n\t return fromArrayBuffer(value, encodingOrOffset, length)\n\t }\n\t\n\t if (typeof value === 'string') {\n\t return fromString(value, encodingOrOffset)\n\t }\n\t\n\t return fromObject(value)\n\t}\n\t\n\t/**\n\t * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError\n\t * if value is a number.\n\t * Buffer.from(str[, encoding])\n\t * Buffer.from(array)\n\t * Buffer.from(buffer)\n\t * Buffer.from(arrayBuffer[, byteOffset[, length]])\n\t **/\n\tBuffer.from = function (value, encodingOrOffset, length) {\n\t return from(value, encodingOrOffset, length)\n\t}\n\t\n\t// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:\n\t// https://github.com/feross/buffer/pull/148\n\tBuffer.prototype.__proto__ = Uint8Array.prototype\n\tBuffer.__proto__ = Uint8Array\n\t\n\tfunction assertSize (size) {\n\t if (typeof size !== 'number') {\n\t throw new TypeError('\"size\" argument must be a number')\n\t } else if (size < 0) {\n\t throw new RangeError('\"size\" argument must not be negative')\n\t }\n\t}\n\t\n\tfunction alloc (size, fill, encoding) {\n\t assertSize(size)\n\t if (size <= 0) {\n\t return createBuffer(size)\n\t }\n\t if (fill !== undefined) {\n\t // Only pay attention to encoding if it's a string. This\n\t // prevents accidentally sending in a number that would\n\t // be interpretted as a start offset.\n\t return typeof encoding === 'string'\n\t ? createBuffer(size).fill(fill, encoding)\n\t : createBuffer(size).fill(fill)\n\t }\n\t return createBuffer(size)\n\t}\n\t\n\t/**\n\t * Creates a new filled Buffer instance.\n\t * alloc(size[, fill[, encoding]])\n\t **/\n\tBuffer.alloc = function (size, fill, encoding) {\n\t return alloc(size, fill, encoding)\n\t}\n\t\n\tfunction allocUnsafe (size) {\n\t assertSize(size)\n\t return createBuffer(size < 0 ? 0 : checked(size) | 0)\n\t}\n\t\n\t/**\n\t * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.\n\t * */\n\tBuffer.allocUnsafe = function (size) {\n\t return allocUnsafe(size)\n\t}\n\t/**\n\t * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.\n\t */\n\tBuffer.allocUnsafeSlow = function (size) {\n\t return allocUnsafe(size)\n\t}\n\t\n\tfunction fromString (string, encoding) {\n\t if (typeof encoding !== 'string' || encoding === '') {\n\t encoding = 'utf8'\n\t }\n\t\n\t if (!Buffer.isEncoding(encoding)) {\n\t throw new TypeError('\"encoding\" must be a valid string encoding')\n\t }\n\t\n\t var length = byteLength(string, encoding) | 0\n\t var buf = createBuffer(length)\n\t\n\t var actual = buf.write(string, encoding)\n\t\n\t if (actual !== length) {\n\t // Writing a hex string, for example, that contains invalid characters will\n\t // cause everything after the first invalid character to be ignored. (e.g.\n\t // 'abxxcd' will be treated as 'ab')\n\t buf = buf.slice(0, actual)\n\t }\n\t\n\t return buf\n\t}\n\t\n\tfunction fromArrayLike (array) {\n\t var length = array.length < 0 ? 0 : checked(array.length) | 0\n\t var buf = createBuffer(length)\n\t for (var i = 0; i < length; i += 1) {\n\t buf[i] = array[i] & 255\n\t }\n\t return buf\n\t}\n\t\n\tfunction fromArrayBuffer (array, byteOffset, length) {\n\t if (byteOffset < 0 || array.byteLength < byteOffset) {\n\t throw new RangeError('\\'offset\\' is out of bounds')\n\t }\n\t\n\t if (array.byteLength < byteOffset + (length || 0)) {\n\t throw new RangeError('\\'length\\' is out of bounds')\n\t }\n\t\n\t var buf\n\t if (byteOffset === undefined && length === undefined) {\n\t buf = new Uint8Array(array)\n\t } else if (length === undefined) {\n\t buf = new Uint8Array(array, byteOffset)\n\t } else {\n\t buf = new Uint8Array(array, byteOffset, length)\n\t }\n\t\n\t // Return an augmented `Uint8Array` instance\n\t buf.__proto__ = Buffer.prototype\n\t return buf\n\t}\n\t\n\tfunction fromObject (obj) {\n\t if (Buffer.isBuffer(obj)) {\n\t var len = checked(obj.length) | 0\n\t var buf = createBuffer(len)\n\t\n\t if (buf.length === 0) {\n\t return buf\n\t }\n\t\n\t obj.copy(buf, 0, 0, len)\n\t return buf\n\t }\n\t\n\t if (obj) {\n\t if (isArrayBufferView(obj) || 'length' in obj) {\n\t if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {\n\t return createBuffer(0)\n\t }\n\t return fromArrayLike(obj)\n\t }\n\t\n\t if (obj.type === 'Buffer' && Array.isArray(obj.data)) {\n\t return fromArrayLike(obj.data)\n\t }\n\t }\n\t\n\t throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')\n\t}\n\t\n\tfunction checked (length) {\n\t // Note: cannot use `length < K_MAX_LENGTH` here because that fails when\n\t // length is NaN (which is otherwise coerced to zero.)\n\t if (length >= K_MAX_LENGTH) {\n\t throw new RangeError('Attempt to allocate Buffer larger than maximum ' +\n\t 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')\n\t }\n\t return length | 0\n\t}\n\t\n\tfunction SlowBuffer (length) {\n\t if (+length != length) { // eslint-disable-line eqeqeq\n\t length = 0\n\t }\n\t return Buffer.alloc(+length)\n\t}\n\t\n\tBuffer.isBuffer = function isBuffer (b) {\n\t return b != null && b._isBuffer === true\n\t}\n\t\n\tBuffer.compare = function compare (a, b) {\n\t if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {\n\t throw new TypeError('Arguments must be Buffers')\n\t }\n\t\n\t if (a === b) return 0\n\t\n\t var x = a.length\n\t var y = b.length\n\t\n\t for (var i = 0, len = Math.min(x, y); i < len; ++i) {\n\t if (a[i] !== b[i]) {\n\t x = a[i]\n\t y = b[i]\n\t break\n\t }\n\t }\n\t\n\t if (x < y) return -1\n\t if (y < x) return 1\n\t return 0\n\t}\n\t\n\tBuffer.isEncoding = function isEncoding (encoding) {\n\t switch (String(encoding).toLowerCase()) {\n\t case 'hex':\n\t case 'utf8':\n\t case 'utf-8':\n\t case 'ascii':\n\t case 'latin1':\n\t case 'binary':\n\t case 'base64':\n\t case 'ucs2':\n\t case 'ucs-2':\n\t case 'utf16le':\n\t case 'utf-16le':\n\t return true\n\t default:\n\t return false\n\t }\n\t}\n\t\n\tBuffer.concat = function concat (list, length) {\n\t if (!Array.isArray(list)) {\n\t throw new TypeError('\"list\" argument must be an Array of Buffers')\n\t }\n\t\n\t if (list.length === 0) {\n\t return Buffer.alloc(0)\n\t }\n\t\n\t var i\n\t if (length === undefined) {\n\t length = 0\n\t for (i = 0; i < list.length; ++i) {\n\t length += list[i].length\n\t }\n\t }\n\t\n\t var buffer = Buffer.allocUnsafe(length)\n\t var pos = 0\n\t for (i = 0; i < list.length; ++i) {\n\t var buf = list[i]\n\t if (!Buffer.isBuffer(buf)) {\n\t throw new TypeError('\"list\" argument must be an Array of Buffers')\n\t }\n\t buf.copy(buffer, pos)\n\t pos += buf.length\n\t }\n\t return buffer\n\t}\n\t\n\tfunction byteLength (string, encoding) {\n\t if (Buffer.isBuffer(string)) {\n\t return string.length\n\t }\n\t if (isArrayBufferView(string) || isArrayBuffer(string)) {\n\t return string.byteLength\n\t }\n\t if (typeof string !== 'string') {\n\t string = '' + string\n\t }\n\t\n\t var len = string.length\n\t if (len === 0) return 0\n\t\n\t // Use a for loop to avoid recursion\n\t var loweredCase = false\n\t for (;;) {\n\t switch (encoding) {\n\t case 'ascii':\n\t case 'latin1':\n\t case 'binary':\n\t return len\n\t case 'utf8':\n\t case 'utf-8':\n\t case undefined:\n\t return utf8ToBytes(string).length\n\t case 'ucs2':\n\t case 'ucs-2':\n\t case 'utf16le':\n\t case 'utf-16le':\n\t return len * 2\n\t case 'hex':\n\t return len >>> 1\n\t case 'base64':\n\t return base64ToBytes(string).length\n\t default:\n\t if (loweredCase) return utf8ToBytes(string).length // assume utf8\n\t encoding = ('' + encoding).toLowerCase()\n\t loweredCase = true\n\t }\n\t }\n\t}\n\tBuffer.byteLength = byteLength\n\t\n\tfunction slowToString (encoding, start, end) {\n\t var loweredCase = false\n\t\n\t // No need to verify that \"this.length <= MAX_UINT32\" since it's a read-only\n\t // property of a typed array.\n\t\n\t // This behaves neither like String nor Uint8Array in that we set start/end\n\t // to their upper/lower bounds if the value passed is out of range.\n\t // undefined is handled specially as per ECMA-262 6th Edition,\n\t // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.\n\t if (start === undefined || start < 0) {\n\t start = 0\n\t }\n\t // Return early if start > this.length. Done here to prevent potential uint32\n\t // coercion fail below.\n\t if (start > this.length) {\n\t return ''\n\t }\n\t\n\t if (end === undefined || end > this.length) {\n\t end = this.length\n\t }\n\t\n\t if (end <= 0) {\n\t return ''\n\t }\n\t\n\t // Force coersion to uint32. This will also coerce falsey/NaN values to 0.\n\t end >>>= 0\n\t start >>>= 0\n\t\n\t if (end <= start) {\n\t return ''\n\t }\n\t\n\t if (!encoding) encoding = 'utf8'\n\t\n\t while (true) {\n\t switch (encoding) {\n\t case 'hex':\n\t return hexSlice(this, start, end)\n\t\n\t case 'utf8':\n\t case 'utf-8':\n\t return utf8Slice(this, start, end)\n\t\n\t case 'ascii':\n\t return asciiSlice(this, start, end)\n\t\n\t case 'latin1':\n\t case 'binary':\n\t return latin1Slice(this, start, end)\n\t\n\t case 'base64':\n\t return base64Slice(this, start, end)\n\t\n\t case 'ucs2':\n\t case 'ucs-2':\n\t case 'utf16le':\n\t case 'utf-16le':\n\t return utf16leSlice(this, start, end)\n\t\n\t default:\n\t if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n\t encoding = (encoding + '').toLowerCase()\n\t loweredCase = true\n\t }\n\t }\n\t}\n\t\n\t// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)\n\t// to detect a Buffer instance. It's not possible to use `instanceof Buffer`\n\t// reliably in a browserify context because there could be multiple different\n\t// copies of the 'buffer' package in use. This method works even for Buffer\n\t// instances that were created from another copy of the `buffer` package.\n\t// See: https://github.com/feross/buffer/issues/154\n\tBuffer.prototype._isBuffer = true\n\t\n\tfunction swap (b, n, m) {\n\t var i = b[n]\n\t b[n] = b[m]\n\t b[m] = i\n\t}\n\t\n\tBuffer.prototype.swap16 = function swap16 () {\n\t var len = this.length\n\t if (len % 2 !== 0) {\n\t throw new RangeError('Buffer size must be a multiple of 16-bits')\n\t }\n\t for (var i = 0; i < len; i += 2) {\n\t swap(this, i, i + 1)\n\t }\n\t return this\n\t}\n\t\n\tBuffer.prototype.swap32 = function swap32 () {\n\t var len = this.length\n\t if (len % 4 !== 0) {\n\t throw new RangeError('Buffer size must be a multiple of 32-bits')\n\t }\n\t for (var i = 0; i < len; i += 4) {\n\t swap(this, i, i + 3)\n\t swap(this, i + 1, i + 2)\n\t }\n\t return this\n\t}\n\t\n\tBuffer.prototype.swap64 = function swap64 () {\n\t var len = this.length\n\t if (len % 8 !== 0) {\n\t throw new RangeError('Buffer size must be a multiple of 64-bits')\n\t }\n\t for (var i = 0; i < len; i += 8) {\n\t swap(this, i, i + 7)\n\t swap(this, i + 1, i + 6)\n\t swap(this, i + 2, i + 5)\n\t swap(this, i + 3, i + 4)\n\t }\n\t return this\n\t}\n\t\n\tBuffer.prototype.toString = function toString () {\n\t var length = this.length\n\t if (length === 0) return ''\n\t if (arguments.length === 0) return utf8Slice(this, 0, length)\n\t return slowToString.apply(this, arguments)\n\t}\n\t\n\tBuffer.prototype.equals = function equals (b) {\n\t if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')\n\t if (this === b) return true\n\t return Buffer.compare(this, b) === 0\n\t}\n\t\n\tBuffer.prototype.inspect = function inspect () {\n\t var str = ''\n\t var max = exports.INSPECT_MAX_BYTES\n\t if (this.length > 0) {\n\t str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')\n\t if (this.length > max) str += ' ... '\n\t }\n\t return ''\n\t}\n\t\n\tBuffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {\n\t if (!Buffer.isBuffer(target)) {\n\t throw new TypeError('Argument must be a Buffer')\n\t }\n\t\n\t if (start === undefined) {\n\t start = 0\n\t }\n\t if (end === undefined) {\n\t end = target ? target.length : 0\n\t }\n\t if (thisStart === undefined) {\n\t thisStart = 0\n\t }\n\t if (thisEnd === undefined) {\n\t thisEnd = this.length\n\t }\n\t\n\t if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {\n\t throw new RangeError('out of range index')\n\t }\n\t\n\t if (thisStart >= thisEnd && start >= end) {\n\t return 0\n\t }\n\t if (thisStart >= thisEnd) {\n\t return -1\n\t }\n\t if (start >= end) {\n\t return 1\n\t }\n\t\n\t start >>>= 0\n\t end >>>= 0\n\t thisStart >>>= 0\n\t thisEnd >>>= 0\n\t\n\t if (this === target) return 0\n\t\n\t var x = thisEnd - thisStart\n\t var y = end - start\n\t var len = Math.min(x, y)\n\t\n\t var thisCopy = this.slice(thisStart, thisEnd)\n\t var targetCopy = target.slice(start, end)\n\t\n\t for (var i = 0; i < len; ++i) {\n\t if (thisCopy[i] !== targetCopy[i]) {\n\t x = thisCopy[i]\n\t y = targetCopy[i]\n\t break\n\t }\n\t }\n\t\n\t if (x < y) return -1\n\t if (y < x) return 1\n\t return 0\n\t}\n\t\n\t// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,\n\t// OR the last index of `val` in `buffer` at offset <= `byteOffset`.\n\t//\n\t// Arguments:\n\t// - buffer - a Buffer to search\n\t// - val - a string, Buffer, or number\n\t// - byteOffset - an index into `buffer`; will be clamped to an int32\n\t// - encoding - an optional encoding, relevant is val is a string\n\t// - dir - true for indexOf, false for lastIndexOf\n\tfunction bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {\n\t // Empty buffer means no match\n\t if (buffer.length === 0) return -1\n\t\n\t // Normalize byteOffset\n\t if (typeof byteOffset === 'string') {\n\t encoding = byteOffset\n\t byteOffset = 0\n\t } else if (byteOffset > 0x7fffffff) {\n\t byteOffset = 0x7fffffff\n\t } else if (byteOffset < -0x80000000) {\n\t byteOffset = -0x80000000\n\t }\n\t byteOffset = +byteOffset // Coerce to Number.\n\t if (numberIsNaN(byteOffset)) {\n\t // byteOffset: it it's undefined, null, NaN, \"foo\", etc, search whole buffer\n\t byteOffset = dir ? 0 : (buffer.length - 1)\n\t }\n\t\n\t // Normalize byteOffset: negative offsets start from the end of the buffer\n\t if (byteOffset < 0) byteOffset = buffer.length + byteOffset\n\t if (byteOffset >= buffer.length) {\n\t if (dir) return -1\n\t else byteOffset = buffer.length - 1\n\t } else if (byteOffset < 0) {\n\t if (dir) byteOffset = 0\n\t else return -1\n\t }\n\t\n\t // Normalize val\n\t if (typeof val === 'string') {\n\t val = Buffer.from(val, encoding)\n\t }\n\t\n\t // Finally, search either indexOf (if dir is true) or lastIndexOf\n\t if (Buffer.isBuffer(val)) {\n\t // Special case: looking for empty string/buffer always fails\n\t if (val.length === 0) {\n\t return -1\n\t }\n\t return arrayIndexOf(buffer, val, byteOffset, encoding, dir)\n\t } else if (typeof val === 'number') {\n\t val = val & 0xFF // Search for a byte value [0-255]\n\t if (typeof Uint8Array.prototype.indexOf === 'function') {\n\t if (dir) {\n\t return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)\n\t } else {\n\t return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)\n\t }\n\t }\n\t return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)\n\t }\n\t\n\t throw new TypeError('val must be string, number or Buffer')\n\t}\n\t\n\tfunction arrayIndexOf (arr, val, byteOffset, encoding, dir) {\n\t var indexSize = 1\n\t var arrLength = arr.length\n\t var valLength = val.length\n\t\n\t if (encoding !== undefined) {\n\t encoding = String(encoding).toLowerCase()\n\t if (encoding === 'ucs2' || encoding === 'ucs-2' ||\n\t encoding === 'utf16le' || encoding === 'utf-16le') {\n\t if (arr.length < 2 || val.length < 2) {\n\t return -1\n\t }\n\t indexSize = 2\n\t arrLength /= 2\n\t valLength /= 2\n\t byteOffset /= 2\n\t }\n\t }\n\t\n\t function read (buf, i) {\n\t if (indexSize === 1) {\n\t return buf[i]\n\t } else {\n\t return buf.readUInt16BE(i * indexSize)\n\t }\n\t }\n\t\n\t var i\n\t if (dir) {\n\t var foundIndex = -1\n\t for (i = byteOffset; i < arrLength; i++) {\n\t if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {\n\t if (foundIndex === -1) foundIndex = i\n\t if (i - foundIndex + 1 === valLength) return foundIndex * indexSize\n\t } else {\n\t if (foundIndex !== -1) i -= i - foundIndex\n\t foundIndex = -1\n\t }\n\t }\n\t } else {\n\t if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength\n\t for (i = byteOffset; i >= 0; i--) {\n\t var found = true\n\t for (var j = 0; j < valLength; j++) {\n\t if (read(arr, i + j) !== read(val, j)) {\n\t found = false\n\t break\n\t }\n\t }\n\t if (found) return i\n\t }\n\t }\n\t\n\t return -1\n\t}\n\t\n\tBuffer.prototype.includes = function includes (val, byteOffset, encoding) {\n\t return this.indexOf(val, byteOffset, encoding) !== -1\n\t}\n\t\n\tBuffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {\n\t return bidirectionalIndexOf(this, val, byteOffset, encoding, true)\n\t}\n\t\n\tBuffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {\n\t return bidirectionalIndexOf(this, val, byteOffset, encoding, false)\n\t}\n\t\n\tfunction hexWrite (buf, string, offset, length) {\n\t offset = Number(offset) || 0\n\t var remaining = buf.length - offset\n\t if (!length) {\n\t length = remaining\n\t } else {\n\t length = Number(length)\n\t if (length > remaining) {\n\t length = remaining\n\t }\n\t }\n\t\n\t // must be an even number of digits\n\t var strLen = string.length\n\t if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')\n\t\n\t if (length > strLen / 2) {\n\t length = strLen / 2\n\t }\n\t for (var i = 0; i < length; ++i) {\n\t var parsed = parseInt(string.substr(i * 2, 2), 16)\n\t if (numberIsNaN(parsed)) return i\n\t buf[offset + i] = parsed\n\t }\n\t return i\n\t}\n\t\n\tfunction utf8Write (buf, string, offset, length) {\n\t return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)\n\t}\n\t\n\tfunction asciiWrite (buf, string, offset, length) {\n\t return blitBuffer(asciiToBytes(string), buf, offset, length)\n\t}\n\t\n\tfunction latin1Write (buf, string, offset, length) {\n\t return asciiWrite(buf, string, offset, length)\n\t}\n\t\n\tfunction base64Write (buf, string, offset, length) {\n\t return blitBuffer(base64ToBytes(string), buf, offset, length)\n\t}\n\t\n\tfunction ucs2Write (buf, string, offset, length) {\n\t return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)\n\t}\n\t\n\tBuffer.prototype.write = function write (string, offset, length, encoding) {\n\t // Buffer#write(string)\n\t if (offset === undefined) {\n\t encoding = 'utf8'\n\t length = this.length\n\t offset = 0\n\t // Buffer#write(string, encoding)\n\t } else if (length === undefined && typeof offset === 'string') {\n\t encoding = offset\n\t length = this.length\n\t offset = 0\n\t // Buffer#write(string, offset[, length][, encoding])\n\t } else if (isFinite(offset)) {\n\t offset = offset >>> 0\n\t if (isFinite(length)) {\n\t length = length >>> 0\n\t if (encoding === undefined) encoding = 'utf8'\n\t } else {\n\t encoding = length\n\t length = undefined\n\t }\n\t } else {\n\t throw new Error(\n\t 'Buffer.write(string, encoding, offset[, length]) is no longer supported'\n\t )\n\t }\n\t\n\t var remaining = this.length - offset\n\t if (length === undefined || length > remaining) length = remaining\n\t\n\t if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {\n\t throw new RangeError('Attempt to write outside buffer bounds')\n\t }\n\t\n\t if (!encoding) encoding = 'utf8'\n\t\n\t var loweredCase = false\n\t for (;;) {\n\t switch (encoding) {\n\t case 'hex':\n\t return hexWrite(this, string, offset, length)\n\t\n\t case 'utf8':\n\t case 'utf-8':\n\t return utf8Write(this, string, offset, length)\n\t\n\t case 'ascii':\n\t return asciiWrite(this, string, offset, length)\n\t\n\t case 'latin1':\n\t case 'binary':\n\t return latin1Write(this, string, offset, length)\n\t\n\t case 'base64':\n\t // Warning: maxLength not taken into account in base64Write\n\t return base64Write(this, string, offset, length)\n\t\n\t case 'ucs2':\n\t case 'ucs-2':\n\t case 'utf16le':\n\t case 'utf-16le':\n\t return ucs2Write(this, string, offset, length)\n\t\n\t default:\n\t if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n\t encoding = ('' + encoding).toLowerCase()\n\t loweredCase = true\n\t }\n\t }\n\t}\n\t\n\tBuffer.prototype.toJSON = function toJSON () {\n\t return {\n\t type: 'Buffer',\n\t data: Array.prototype.slice.call(this._arr || this, 0)\n\t }\n\t}\n\t\n\tfunction base64Slice (buf, start, end) {\n\t if (start === 0 && end === buf.length) {\n\t return base64.fromByteArray(buf)\n\t } else {\n\t return base64.fromByteArray(buf.slice(start, end))\n\t }\n\t}\n\t\n\tfunction utf8Slice (buf, start, end) {\n\t end = Math.min(buf.length, end)\n\t var res = []\n\t\n\t var i = start\n\t while (i < end) {\n\t var firstByte = buf[i]\n\t var codePoint = null\n\t var bytesPerSequence = (firstByte > 0xEF) ? 4\n\t : (firstByte > 0xDF) ? 3\n\t : (firstByte > 0xBF) ? 2\n\t : 1\n\t\n\t if (i + bytesPerSequence <= end) {\n\t var secondByte, thirdByte, fourthByte, tempCodePoint\n\t\n\t switch (bytesPerSequence) {\n\t case 1:\n\t if (firstByte < 0x80) {\n\t codePoint = firstByte\n\t }\n\t break\n\t case 2:\n\t secondByte = buf[i + 1]\n\t if ((secondByte & 0xC0) === 0x80) {\n\t tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)\n\t if (tempCodePoint > 0x7F) {\n\t codePoint = tempCodePoint\n\t }\n\t }\n\t break\n\t case 3:\n\t secondByte = buf[i + 1]\n\t thirdByte = buf[i + 2]\n\t if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {\n\t tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)\n\t if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {\n\t codePoint = tempCodePoint\n\t }\n\t }\n\t break\n\t case 4:\n\t secondByte = buf[i + 1]\n\t thirdByte = buf[i + 2]\n\t fourthByte = buf[i + 3]\n\t if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {\n\t tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)\n\t if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {\n\t codePoint = tempCodePoint\n\t }\n\t }\n\t }\n\t }\n\t\n\t if (codePoint === null) {\n\t // we did not generate a valid codePoint so insert a\n\t // replacement char (U+FFFD) and advance only 1 byte\n\t codePoint = 0xFFFD\n\t bytesPerSequence = 1\n\t } else if (codePoint > 0xFFFF) {\n\t // encode to utf16 (surrogate pair dance)\n\t codePoint -= 0x10000\n\t res.push(codePoint >>> 10 & 0x3FF | 0xD800)\n\t codePoint = 0xDC00 | codePoint & 0x3FF\n\t }\n\t\n\t res.push(codePoint)\n\t i += bytesPerSequence\n\t }\n\t\n\t return decodeCodePointsArray(res)\n\t}\n\t\n\t// Based on http://stackoverflow.com/a/22747272/680742, the browser with\n\t// the lowest limit is Chrome, with 0x10000 args.\n\t// We go 1 magnitude less, for safety\n\tvar MAX_ARGUMENTS_LENGTH = 0x1000\n\t\n\tfunction decodeCodePointsArray (codePoints) {\n\t var len = codePoints.length\n\t if (len <= MAX_ARGUMENTS_LENGTH) {\n\t return String.fromCharCode.apply(String, codePoints) // avoid extra slice()\n\t }\n\t\n\t // Decode in chunks to avoid \"call stack size exceeded\".\n\t var res = ''\n\t var i = 0\n\t while (i < len) {\n\t res += String.fromCharCode.apply(\n\t String,\n\t codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)\n\t )\n\t }\n\t return res\n\t}\n\t\n\tfunction asciiSlice (buf, start, end) {\n\t var ret = ''\n\t end = Math.min(buf.length, end)\n\t\n\t for (var i = start; i < end; ++i) {\n\t ret += String.fromCharCode(buf[i] & 0x7F)\n\t }\n\t return ret\n\t}\n\t\n\tfunction latin1Slice (buf, start, end) {\n\t var ret = ''\n\t end = Math.min(buf.length, end)\n\t\n\t for (var i = start; i < end; ++i) {\n\t ret += String.fromCharCode(buf[i])\n\t }\n\t return ret\n\t}\n\t\n\tfunction hexSlice (buf, start, end) {\n\t var len = buf.length\n\t\n\t if (!start || start < 0) start = 0\n\t if (!end || end < 0 || end > len) end = len\n\t\n\t var out = ''\n\t for (var i = start; i < end; ++i) {\n\t out += toHex(buf[i])\n\t }\n\t return out\n\t}\n\t\n\tfunction utf16leSlice (buf, start, end) {\n\t var bytes = buf.slice(start, end)\n\t var res = ''\n\t for (var i = 0; i < bytes.length; i += 2) {\n\t res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))\n\t }\n\t return res\n\t}\n\t\n\tBuffer.prototype.slice = function slice (start, end) {\n\t var len = this.length\n\t start = ~~start\n\t end = end === undefined ? len : ~~end\n\t\n\t if (start < 0) {\n\t start += len\n\t if (start < 0) start = 0\n\t } else if (start > len) {\n\t start = len\n\t }\n\t\n\t if (end < 0) {\n\t end += len\n\t if (end < 0) end = 0\n\t } else if (end > len) {\n\t end = len\n\t }\n\t\n\t if (end < start) end = start\n\t\n\t var newBuf = this.subarray(start, end)\n\t // Return an augmented `Uint8Array` instance\n\t newBuf.__proto__ = Buffer.prototype\n\t return newBuf\n\t}\n\t\n\t/*\n\t * Need to make sure that buffer isn't trying to write out of bounds.\n\t */\n\tfunction checkOffset (offset, ext, length) {\n\t if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')\n\t if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')\n\t}\n\t\n\tBuffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {\n\t offset = offset >>> 0\n\t byteLength = byteLength >>> 0\n\t if (!noAssert) checkOffset(offset, byteLength, this.length)\n\t\n\t var val = this[offset]\n\t var mul = 1\n\t var i = 0\n\t while (++i < byteLength && (mul *= 0x100)) {\n\t val += this[offset + i] * mul\n\t }\n\t\n\t return val\n\t}\n\t\n\tBuffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {\n\t offset = offset >>> 0\n\t byteLength = byteLength >>> 0\n\t if (!noAssert) {\n\t checkOffset(offset, byteLength, this.length)\n\t }\n\t\n\t var val = this[offset + --byteLength]\n\t var mul = 1\n\t while (byteLength > 0 && (mul *= 0x100)) {\n\t val += this[offset + --byteLength] * mul\n\t }\n\t\n\t return val\n\t}\n\t\n\tBuffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {\n\t offset = offset >>> 0\n\t if (!noAssert) checkOffset(offset, 1, this.length)\n\t return this[offset]\n\t}\n\t\n\tBuffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {\n\t offset = offset >>> 0\n\t if (!noAssert) checkOffset(offset, 2, this.length)\n\t return this[offset] | (this[offset + 1] << 8)\n\t}\n\t\n\tBuffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {\n\t offset = offset >>> 0\n\t if (!noAssert) checkOffset(offset, 2, this.length)\n\t return (this[offset] << 8) | this[offset + 1]\n\t}\n\t\n\tBuffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {\n\t offset = offset >>> 0\n\t if (!noAssert) checkOffset(offset, 4, this.length)\n\t\n\t return ((this[offset]) |\n\t (this[offset + 1] << 8) |\n\t (this[offset + 2] << 16)) +\n\t (this[offset + 3] * 0x1000000)\n\t}\n\t\n\tBuffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {\n\t offset = offset >>> 0\n\t if (!noAssert) checkOffset(offset, 4, this.length)\n\t\n\t return (this[offset] * 0x1000000) +\n\t ((this[offset + 1] << 16) |\n\t (this[offset + 2] << 8) |\n\t this[offset + 3])\n\t}\n\t\n\tBuffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {\n\t offset = offset >>> 0\n\t byteLength = byteLength >>> 0\n\t if (!noAssert) checkOffset(offset, byteLength, this.length)\n\t\n\t var val = this[offset]\n\t var mul = 1\n\t var i = 0\n\t while (++i < byteLength && (mul *= 0x100)) {\n\t val += this[offset + i] * mul\n\t }\n\t mul *= 0x80\n\t\n\t if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\t\n\t return val\n\t}\n\t\n\tBuffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {\n\t offset = offset >>> 0\n\t byteLength = byteLength >>> 0\n\t if (!noAssert) checkOffset(offset, byteLength, this.length)\n\t\n\t var i = byteLength\n\t var mul = 1\n\t var val = this[offset + --i]\n\t while (i > 0 && (mul *= 0x100)) {\n\t val += this[offset + --i] * mul\n\t }\n\t mul *= 0x80\n\t\n\t if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\t\n\t return val\n\t}\n\t\n\tBuffer.prototype.readInt8 = function readInt8 (offset, noAssert) {\n\t offset = offset >>> 0\n\t if (!noAssert) checkOffset(offset, 1, this.length)\n\t if (!(this[offset] & 0x80)) return (this[offset])\n\t return ((0xff - this[offset] + 1) * -1)\n\t}\n\t\n\tBuffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {\n\t offset = offset >>> 0\n\t if (!noAssert) checkOffset(offset, 2, this.length)\n\t var val = this[offset] | (this[offset + 1] << 8)\n\t return (val & 0x8000) ? val | 0xFFFF0000 : val\n\t}\n\t\n\tBuffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {\n\t offset = offset >>> 0\n\t if (!noAssert) checkOffset(offset, 2, this.length)\n\t var val = this[offset + 1] | (this[offset] << 8)\n\t return (val & 0x8000) ? val | 0xFFFF0000 : val\n\t}\n\t\n\tBuffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {\n\t offset = offset >>> 0\n\t if (!noAssert) checkOffset(offset, 4, this.length)\n\t\n\t return (this[offset]) |\n\t (this[offset + 1] << 8) |\n\t (this[offset + 2] << 16) |\n\t (this[offset + 3] << 24)\n\t}\n\t\n\tBuffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {\n\t offset = offset >>> 0\n\t if (!noAssert) checkOffset(offset, 4, this.length)\n\t\n\t return (this[offset] << 24) |\n\t (this[offset + 1] << 16) |\n\t (this[offset + 2] << 8) |\n\t (this[offset + 3])\n\t}\n\t\n\tBuffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {\n\t offset = offset >>> 0\n\t if (!noAssert) checkOffset(offset, 4, this.length)\n\t return ieee754.read(this, offset, true, 23, 4)\n\t}\n\t\n\tBuffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {\n\t offset = offset >>> 0\n\t if (!noAssert) checkOffset(offset, 4, this.length)\n\t return ieee754.read(this, offset, false, 23, 4)\n\t}\n\t\n\tBuffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {\n\t offset = offset >>> 0\n\t if (!noAssert) checkOffset(offset, 8, this.length)\n\t return ieee754.read(this, offset, true, 52, 8)\n\t}\n\t\n\tBuffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {\n\t offset = offset >>> 0\n\t if (!noAssert) checkOffset(offset, 8, this.length)\n\t return ieee754.read(this, offset, false, 52, 8)\n\t}\n\t\n\tfunction checkInt (buf, value, offset, ext, max, min) {\n\t if (!Buffer.isBuffer(buf)) throw new TypeError('\"buffer\" argument must be a Buffer instance')\n\t if (value > max || value < min) throw new RangeError('\"value\" argument is out of bounds')\n\t if (offset + ext > buf.length) throw new RangeError('Index out of range')\n\t}\n\t\n\tBuffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {\n\t value = +value\n\t offset = offset >>> 0\n\t byteLength = byteLength >>> 0\n\t if (!noAssert) {\n\t var maxBytes = Math.pow(2, 8 * byteLength) - 1\n\t checkInt(this, value, offset, byteLength, maxBytes, 0)\n\t }\n\t\n\t var mul = 1\n\t var i = 0\n\t this[offset] = value & 0xFF\n\t while (++i < byteLength && (mul *= 0x100)) {\n\t this[offset + i] = (value / mul) & 0xFF\n\t }\n\t\n\t return offset + byteLength\n\t}\n\t\n\tBuffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {\n\t value = +value\n\t offset = offset >>> 0\n\t byteLength = byteLength >>> 0\n\t if (!noAssert) {\n\t var maxBytes = Math.pow(2, 8 * byteLength) - 1\n\t checkInt(this, value, offset, byteLength, maxBytes, 0)\n\t }\n\t\n\t var i = byteLength - 1\n\t var mul = 1\n\t this[offset + i] = value & 0xFF\n\t while (--i >= 0 && (mul *= 0x100)) {\n\t this[offset + i] = (value / mul) & 0xFF\n\t }\n\t\n\t return offset + byteLength\n\t}\n\t\n\tBuffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {\n\t value = +value\n\t offset = offset >>> 0\n\t if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)\n\t this[offset] = (value & 0xff)\n\t return offset + 1\n\t}\n\t\n\tBuffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {\n\t value = +value\n\t offset = offset >>> 0\n\t if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n\t this[offset] = (value & 0xff)\n\t this[offset + 1] = (value >>> 8)\n\t return offset + 2\n\t}\n\t\n\tBuffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {\n\t value = +value\n\t offset = offset >>> 0\n\t if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n\t this[offset] = (value >>> 8)\n\t this[offset + 1] = (value & 0xff)\n\t return offset + 2\n\t}\n\t\n\tBuffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {\n\t value = +value\n\t offset = offset >>> 0\n\t if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n\t this[offset + 3] = (value >>> 24)\n\t this[offset + 2] = (value >>> 16)\n\t this[offset + 1] = (value >>> 8)\n\t this[offset] = (value & 0xff)\n\t return offset + 4\n\t}\n\t\n\tBuffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {\n\t value = +value\n\t offset = offset >>> 0\n\t if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n\t this[offset] = (value >>> 24)\n\t this[offset + 1] = (value >>> 16)\n\t this[offset + 2] = (value >>> 8)\n\t this[offset + 3] = (value & 0xff)\n\t return offset + 4\n\t}\n\t\n\tBuffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {\n\t value = +value\n\t offset = offset >>> 0\n\t if (!noAssert) {\n\t var limit = Math.pow(2, (8 * byteLength) - 1)\n\t\n\t checkInt(this, value, offset, byteLength, limit - 1, -limit)\n\t }\n\t\n\t var i = 0\n\t var mul = 1\n\t var sub = 0\n\t this[offset] = value & 0xFF\n\t while (++i < byteLength && (mul *= 0x100)) {\n\t if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {\n\t sub = 1\n\t }\n\t this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n\t }\n\t\n\t return offset + byteLength\n\t}\n\t\n\tBuffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {\n\t value = +value\n\t offset = offset >>> 0\n\t if (!noAssert) {\n\t var limit = Math.pow(2, (8 * byteLength) - 1)\n\t\n\t checkInt(this, value, offset, byteLength, limit - 1, -limit)\n\t }\n\t\n\t var i = byteLength - 1\n\t var mul = 1\n\t var sub = 0\n\t this[offset + i] = value & 0xFF\n\t while (--i >= 0 && (mul *= 0x100)) {\n\t if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {\n\t sub = 1\n\t }\n\t this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n\t }\n\t\n\t return offset + byteLength\n\t}\n\t\n\tBuffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {\n\t value = +value\n\t offset = offset >>> 0\n\t if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)\n\t if (value < 0) value = 0xff + value + 1\n\t this[offset] = (value & 0xff)\n\t return offset + 1\n\t}\n\t\n\tBuffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {\n\t value = +value\n\t offset = offset >>> 0\n\t if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n\t this[offset] = (value & 0xff)\n\t this[offset + 1] = (value >>> 8)\n\t return offset + 2\n\t}\n\t\n\tBuffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {\n\t value = +value\n\t offset = offset >>> 0\n\t if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n\t this[offset] = (value >>> 8)\n\t this[offset + 1] = (value & 0xff)\n\t return offset + 2\n\t}\n\t\n\tBuffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {\n\t value = +value\n\t offset = offset >>> 0\n\t if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n\t this[offset] = (value & 0xff)\n\t this[offset + 1] = (value >>> 8)\n\t this[offset + 2] = (value >>> 16)\n\t this[offset + 3] = (value >>> 24)\n\t return offset + 4\n\t}\n\t\n\tBuffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {\n\t value = +value\n\t offset = offset >>> 0\n\t if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n\t if (value < 0) value = 0xffffffff + value + 1\n\t this[offset] = (value >>> 24)\n\t this[offset + 1] = (value >>> 16)\n\t this[offset + 2] = (value >>> 8)\n\t this[offset + 3] = (value & 0xff)\n\t return offset + 4\n\t}\n\t\n\tfunction checkIEEE754 (buf, value, offset, ext, max, min) {\n\t if (offset + ext > buf.length) throw new RangeError('Index out of range')\n\t if (offset < 0) throw new RangeError('Index out of range')\n\t}\n\t\n\tfunction writeFloat (buf, value, offset, littleEndian, noAssert) {\n\t value = +value\n\t offset = offset >>> 0\n\t if (!noAssert) {\n\t checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)\n\t }\n\t ieee754.write(buf, value, offset, littleEndian, 23, 4)\n\t return offset + 4\n\t}\n\t\n\tBuffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {\n\t return writeFloat(this, value, offset, true, noAssert)\n\t}\n\t\n\tBuffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {\n\t return writeFloat(this, value, offset, false, noAssert)\n\t}\n\t\n\tfunction writeDouble (buf, value, offset, littleEndian, noAssert) {\n\t value = +value\n\t offset = offset >>> 0\n\t if (!noAssert) {\n\t checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)\n\t }\n\t ieee754.write(buf, value, offset, littleEndian, 52, 8)\n\t return offset + 8\n\t}\n\t\n\tBuffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {\n\t return writeDouble(this, value, offset, true, noAssert)\n\t}\n\t\n\tBuffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {\n\t return writeDouble(this, value, offset, false, noAssert)\n\t}\n\t\n\t// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)\n\tBuffer.prototype.copy = function copy (target, targetStart, start, end) {\n\t if (!start) start = 0\n\t if (!end && end !== 0) end = this.length\n\t if (targetStart >= target.length) targetStart = target.length\n\t if (!targetStart) targetStart = 0\n\t if (end > 0 && end < start) end = start\n\t\n\t // Copy 0 bytes; we're done\n\t if (end === start) return 0\n\t if (target.length === 0 || this.length === 0) return 0\n\t\n\t // Fatal error conditions\n\t if (targetStart < 0) {\n\t throw new RangeError('targetStart out of bounds')\n\t }\n\t if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')\n\t if (end < 0) throw new RangeError('sourceEnd out of bounds')\n\t\n\t // Are we oob?\n\t if (end > this.length) end = this.length\n\t if (target.length - targetStart < end - start) {\n\t end = target.length - targetStart + start\n\t }\n\t\n\t var len = end - start\n\t var i\n\t\n\t if (this === target && start < targetStart && targetStart < end) {\n\t // descending copy from end\n\t for (i = len - 1; i >= 0; --i) {\n\t target[i + targetStart] = this[i + start]\n\t }\n\t } else if (len < 1000) {\n\t // ascending copy from start\n\t for (i = 0; i < len; ++i) {\n\t target[i + targetStart] = this[i + start]\n\t }\n\t } else {\n\t Uint8Array.prototype.set.call(\n\t target,\n\t this.subarray(start, start + len),\n\t targetStart\n\t )\n\t }\n\t\n\t return len\n\t}\n\t\n\t// Usage:\n\t// buffer.fill(number[, offset[, end]])\n\t// buffer.fill(buffer[, offset[, end]])\n\t// buffer.fill(string[, offset[, end]][, encoding])\n\tBuffer.prototype.fill = function fill (val, start, end, encoding) {\n\t // Handle string cases:\n\t if (typeof val === 'string') {\n\t if (typeof start === 'string') {\n\t encoding = start\n\t start = 0\n\t end = this.length\n\t } else if (typeof end === 'string') {\n\t encoding = end\n\t end = this.length\n\t }\n\t if (val.length === 1) {\n\t var code = val.charCodeAt(0)\n\t if (code < 256) {\n\t val = code\n\t }\n\t }\n\t if (encoding !== undefined && typeof encoding !== 'string') {\n\t throw new TypeError('encoding must be a string')\n\t }\n\t if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {\n\t throw new TypeError('Unknown encoding: ' + encoding)\n\t }\n\t } else if (typeof val === 'number') {\n\t val = val & 255\n\t }\n\t\n\t // Invalid ranges are not set to a default, so can range check early.\n\t if (start < 0 || this.length < start || this.length < end) {\n\t throw new RangeError('Out of range index')\n\t }\n\t\n\t if (end <= start) {\n\t return this\n\t }\n\t\n\t start = start >>> 0\n\t end = end === undefined ? this.length : end >>> 0\n\t\n\t if (!val) val = 0\n\t\n\t var i\n\t if (typeof val === 'number') {\n\t for (i = start; i < end; ++i) {\n\t this[i] = val\n\t }\n\t } else {\n\t var bytes = Buffer.isBuffer(val)\n\t ? val\n\t : new Buffer(val, encoding)\n\t var len = bytes.length\n\t for (i = 0; i < end - start; ++i) {\n\t this[i + start] = bytes[i % len]\n\t }\n\t }\n\t\n\t return this\n\t}\n\t\n\t// HELPER FUNCTIONS\n\t// ================\n\t\n\tvar INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g\n\t\n\tfunction base64clean (str) {\n\t // Node strips out invalid characters like \\n and \\t from the string, base64-js does not\n\t str = str.trim().replace(INVALID_BASE64_RE, '')\n\t // Node converts strings with length < 2 to ''\n\t if (str.length < 2) return ''\n\t // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not\n\t while (str.length % 4 !== 0) {\n\t str = str + '='\n\t }\n\t return str\n\t}\n\t\n\tfunction toHex (n) {\n\t if (n < 16) return '0' + n.toString(16)\n\t return n.toString(16)\n\t}\n\t\n\tfunction utf8ToBytes (string, units) {\n\t units = units || Infinity\n\t var codePoint\n\t var length = string.length\n\t var leadSurrogate = null\n\t var bytes = []\n\t\n\t for (var i = 0; i < length; ++i) {\n\t codePoint = string.charCodeAt(i)\n\t\n\t // is surrogate component\n\t if (codePoint > 0xD7FF && codePoint < 0xE000) {\n\t // last char was a lead\n\t if (!leadSurrogate) {\n\t // no lead yet\n\t if (codePoint > 0xDBFF) {\n\t // unexpected trail\n\t if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n\t continue\n\t } else if (i + 1 === length) {\n\t // unpaired lead\n\t if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n\t continue\n\t }\n\t\n\t // valid lead\n\t leadSurrogate = codePoint\n\t\n\t continue\n\t }\n\t\n\t // 2 leads in a row\n\t if (codePoint < 0xDC00) {\n\t if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n\t leadSurrogate = codePoint\n\t continue\n\t }\n\t\n\t // valid surrogate pair\n\t codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000\n\t } else if (leadSurrogate) {\n\t // valid bmp char, but last char was a lead\n\t if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n\t }\n\t\n\t leadSurrogate = null\n\t\n\t // encode utf8\n\t if (codePoint < 0x80) {\n\t if ((units -= 1) < 0) break\n\t bytes.push(codePoint)\n\t } else if (codePoint < 0x800) {\n\t if ((units -= 2) < 0) break\n\t bytes.push(\n\t codePoint >> 0x6 | 0xC0,\n\t codePoint & 0x3F | 0x80\n\t )\n\t } else if (codePoint < 0x10000) {\n\t if ((units -= 3) < 0) break\n\t bytes.push(\n\t codePoint >> 0xC | 0xE0,\n\t codePoint >> 0x6 & 0x3F | 0x80,\n\t codePoint & 0x3F | 0x80\n\t )\n\t } else if (codePoint < 0x110000) {\n\t if ((units -= 4) < 0) break\n\t bytes.push(\n\t codePoint >> 0x12 | 0xF0,\n\t codePoint >> 0xC & 0x3F | 0x80,\n\t codePoint >> 0x6 & 0x3F | 0x80,\n\t codePoint & 0x3F | 0x80\n\t )\n\t } else {\n\t throw new Error('Invalid code point')\n\t }\n\t }\n\t\n\t return bytes\n\t}\n\t\n\tfunction asciiToBytes (str) {\n\t var byteArray = []\n\t for (var i = 0; i < str.length; ++i) {\n\t // Node's code seems to be doing this and not & 0x7F..\n\t byteArray.push(str.charCodeAt(i) & 0xFF)\n\t }\n\t return byteArray\n\t}\n\t\n\tfunction utf16leToBytes (str, units) {\n\t var c, hi, lo\n\t var byteArray = []\n\t for (var i = 0; i < str.length; ++i) {\n\t if ((units -= 2) < 0) break\n\t\n\t c = str.charCodeAt(i)\n\t hi = c >> 8\n\t lo = c % 256\n\t byteArray.push(lo)\n\t byteArray.push(hi)\n\t }\n\t\n\t return byteArray\n\t}\n\t\n\tfunction base64ToBytes (str) {\n\t return base64.toByteArray(base64clean(str))\n\t}\n\t\n\tfunction blitBuffer (src, dst, offset, length) {\n\t for (var i = 0; i < length; ++i) {\n\t if ((i + offset >= dst.length) || (i >= src.length)) break\n\t dst[i + offset] = src[i]\n\t }\n\t return i\n\t}\n\t\n\t// ArrayBuffers from another context (i.e. an iframe) do not pass the `instanceof` check\n\t// but they should be treated as valid. See: https://github.com/feross/buffer/issues/166\n\tfunction isArrayBuffer (obj) {\n\t return obj instanceof ArrayBuffer ||\n\t (obj != null && obj.constructor != null && obj.constructor.name === 'ArrayBuffer' &&\n\t typeof obj.byteLength === 'number')\n\t}\n\t\n\t// Node 0.10 supports `ArrayBuffer` but lacks `ArrayBuffer.isView`\n\tfunction isArrayBufferView (obj) {\n\t return (typeof ArrayBuffer.isView === 'function') && ArrayBuffer.isView(obj)\n\t}\n\t\n\tfunction numberIsNaN (obj) {\n\t return obj !== obj // eslint-disable-line no-self-compare\n\t}\n\t\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7)))\n\n/***/ },\n/* 2 */\n/***/ function(module, exports, __webpack_require__) {\n\n\t// a duplex stream is just a stream that is both readable and writable.\n\t// Since JS doesn't have multiple prototypal inheritance, this class\n\t// prototypally inherits from Readable, and then parasitically from\n\t// Writable.\n\t\n\t'use strict';\n\t\n\t/**/\n\t\n\tvar objectKeys = Object.keys || function (obj) {\n\t var keys = [];\n\t for (var key in obj) {\n\t keys.push(key);\n\t }return keys;\n\t};\n\t/**/\n\t\n\tmodule.exports = Duplex;\n\t\n\t/**/\n\tvar processNextTick = __webpack_require__(11);\n\t/**/\n\t\n\t/**/\n\tvar util = __webpack_require__(5);\n\tutil.inherits = __webpack_require__(4);\n\t/**/\n\t\n\tvar Readable = __webpack_require__(16);\n\tvar Writable = __webpack_require__(13);\n\t\n\tutil.inherits(Duplex, Readable);\n\t\n\tvar keys = objectKeys(Writable.prototype);\n\tfor (var v = 0; v < keys.length; v++) {\n\t var method = keys[v];\n\t if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];\n\t}\n\t\n\tfunction Duplex(options) {\n\t if (!(this instanceof Duplex)) return new Duplex(options);\n\t\n\t Readable.call(this, options);\n\t Writable.call(this, options);\n\t\n\t if (options && options.readable === false) this.readable = false;\n\t\n\t if (options && options.writable === false) this.writable = false;\n\t\n\t this.allowHalfOpen = true;\n\t if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;\n\t\n\t this.once('end', onend);\n\t}\n\t\n\t// the no-half-open enforcer\n\tfunction onend() {\n\t // if we allow half-open state, or if the writable side ended,\n\t // then we're ok.\n\t if (this.allowHalfOpen || this._writableState.ended) return;\n\t\n\t // no more data can be written.\n\t // But allow more writes to happen in this tick.\n\t processNextTick(onEndNT, this);\n\t}\n\t\n\tfunction onEndNT(self) {\n\t self.end();\n\t}\n\t\n\tfunction forEach(xs, f) {\n\t for (var i = 0, l = xs.length; i < l; i++) {\n\t f(xs[i], i);\n\t }\n\t}\n\n/***/ },\n/* 3 */\n/***/ function(module, exports, __webpack_require__) {\n\n\t\"use strict\";\n\tvar Process = __webpack_require__(19);\n\tvar process = new Process(), processProxy = {};\n\tfunction defineKey(key) {\n\t if (processProxy[key]) {\n\t // Probably a builtin Object property we don't care about.\n\t return;\n\t }\n\t if (typeof process[key] === 'function') {\n\t processProxy[key] = function () {\n\t return process[key].apply(process, arguments);\n\t };\n\t }\n\t else {\n\t processProxy[key] = process[key];\n\t }\n\t}\n\tfor (var key in process) {\n\t // Don't check if process.hasOwnProperty; we want to also expose objects\n\t // up the prototype hierarchy.\n\t defineKey(key);\n\t}\n\t// Special key: Ensure we update public-facing values of stdin/stdout/stderr.\n\tprocessProxy.initializeTTYs = function () {\n\t if (process.stdin === null) {\n\t process.initializeTTYs();\n\t processProxy.stdin = process.stdin;\n\t processProxy.stdout = process.stdout;\n\t processProxy.stderr = process.stderr;\n\t }\n\t};\n\tprocess.nextTick(function () {\n\t processProxy.initializeTTYs();\n\t});\n\tmodule.exports = processProxy;\n\n\n/***/ },\n/* 4 */\n/***/ function(module, exports) {\n\n\tif (typeof Object.create === 'function') {\n\t // implementation from standard node.js 'util' module\n\t module.exports = function inherits(ctor, superCtor) {\n\t ctor.super_ = superCtor\n\t ctor.prototype = Object.create(superCtor.prototype, {\n\t constructor: {\n\t value: ctor,\n\t enumerable: false,\n\t writable: true,\n\t configurable: true\n\t }\n\t });\n\t };\n\t} else {\n\t // old school shim for old browsers\n\t module.exports = function inherits(ctor, superCtor) {\n\t ctor.super_ = superCtor\n\t var TempCtor = function () {}\n\t TempCtor.prototype = superCtor.prototype\n\t ctor.prototype = new TempCtor()\n\t ctor.prototype.constructor = ctor\n\t }\n\t}\n\n\n/***/ },\n/* 5 */\n/***/ function(module, exports, __webpack_require__) {\n\n\t/* WEBPACK VAR INJECTION */(function(Buffer) {// Copyright Joyent, Inc. and other Node contributors.\n\t//\n\t// Permission is hereby granted, free of charge, to any person obtaining a\n\t// copy of this software and associated documentation files (the\n\t// \"Software\"), to deal in the Software without restriction, including\n\t// without limitation the rights to use, copy, modify, merge, publish,\n\t// distribute, sublicense, and/or sell copies of the Software, and to permit\n\t// persons to whom the Software is furnished to do so, subject to the\n\t// following conditions:\n\t//\n\t// The above copyright notice and this permission notice shall be included\n\t// in all copies or substantial portions of the Software.\n\t//\n\t// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n\t// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n\t// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n\t// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n\t// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n\t// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n\t// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\t\n\t// NOTE: These type checking functions intentionally don't use `instanceof`\n\t// because it is fragile and can be easily faked with `Object.create()`.\n\t\n\tfunction isArray(arg) {\n\t if (Array.isArray) {\n\t return Array.isArray(arg);\n\t }\n\t return objectToString(arg) === '[object Array]';\n\t}\n\texports.isArray = isArray;\n\t\n\tfunction isBoolean(arg) {\n\t return typeof arg === 'boolean';\n\t}\n\texports.isBoolean = isBoolean;\n\t\n\tfunction isNull(arg) {\n\t return arg === null;\n\t}\n\texports.isNull = isNull;\n\t\n\tfunction isNullOrUndefined(arg) {\n\t return arg == null;\n\t}\n\texports.isNullOrUndefined = isNullOrUndefined;\n\t\n\tfunction isNumber(arg) {\n\t return typeof arg === 'number';\n\t}\n\texports.isNumber = isNumber;\n\t\n\tfunction isString(arg) {\n\t return typeof arg === 'string';\n\t}\n\texports.isString = isString;\n\t\n\tfunction isSymbol(arg) {\n\t return typeof arg === 'symbol';\n\t}\n\texports.isSymbol = isSymbol;\n\t\n\tfunction isUndefined(arg) {\n\t return arg === void 0;\n\t}\n\texports.isUndefined = isUndefined;\n\t\n\tfunction isRegExp(re) {\n\t return objectToString(re) === '[object RegExp]';\n\t}\n\texports.isRegExp = isRegExp;\n\t\n\tfunction isObject(arg) {\n\t return typeof arg === 'object' && arg !== null;\n\t}\n\texports.isObject = isObject;\n\t\n\tfunction isDate(d) {\n\t return objectToString(d) === '[object Date]';\n\t}\n\texports.isDate = isDate;\n\t\n\tfunction isError(e) {\n\t return (objectToString(e) === '[object Error]' || e instanceof Error);\n\t}\n\texports.isError = isError;\n\t\n\tfunction isFunction(arg) {\n\t return typeof arg === 'function';\n\t}\n\texports.isFunction = isFunction;\n\t\n\tfunction isPrimitive(arg) {\n\t return arg === null ||\n\t typeof arg === 'boolean' ||\n\t typeof arg === 'number' ||\n\t typeof arg === 'string' ||\n\t typeof arg === 'symbol' || // ES6 symbol\n\t typeof arg === 'undefined';\n\t}\n\texports.isPrimitive = isPrimitive;\n\t\n\texports.isBuffer = Buffer.isBuffer;\n\t\n\tfunction objectToString(o) {\n\t return Object.prototype.toString.call(o);\n\t}\n\t\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7)))\n\n/***/ },\n/* 6 */\n/***/ function(module, exports) {\n\n\t// Copyright Joyent, Inc. and other Node contributors.\n\t//\n\t// Permission is hereby granted, free of charge, to any person obtaining a\n\t// copy of this software and associated documentation files (the\n\t// \"Software\"), to deal in the Software without restriction, including\n\t// without limitation the rights to use, copy, modify, merge, publish,\n\t// distribute, sublicense, and/or sell copies of the Software, and to permit\n\t// persons to whom the Software is furnished to do so, subject to the\n\t// following conditions:\n\t//\n\t// The above copyright notice and this permission notice shall be included\n\t// in all copies or substantial portions of the Software.\n\t//\n\t// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n\t// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n\t// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n\t// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n\t// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n\t// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n\t// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\t\n\tfunction EventEmitter() {\n\t this._events = this._events || {};\n\t this._maxListeners = this._maxListeners || undefined;\n\t}\n\tmodule.exports = EventEmitter;\n\t\n\t// Backwards-compat with node 0.10.x\n\tEventEmitter.EventEmitter = EventEmitter;\n\t\n\tEventEmitter.prototype._events = undefined;\n\tEventEmitter.prototype._maxListeners = undefined;\n\t\n\t// By default EventEmitters will print a warning if more than 10 listeners are\n\t// added to it. This is a useful default which helps finding memory leaks.\n\tEventEmitter.defaultMaxListeners = 10;\n\t\n\t// Obviously not all Emitters should be limited to 10. This function allows\n\t// that to be increased. Set to zero for unlimited.\n\tEventEmitter.prototype.setMaxListeners = function(n) {\n\t if (!isNumber(n) || n < 0 || isNaN(n))\n\t throw TypeError('n must be a positive number');\n\t this._maxListeners = n;\n\t return this;\n\t};\n\t\n\tEventEmitter.prototype.emit = function(type) {\n\t var er, handler, len, args, i, listeners;\n\t\n\t if (!this._events)\n\t this._events = {};\n\t\n\t // If there is no 'error' event listener then throw.\n\t if (type === 'error') {\n\t if (!this._events.error ||\n\t (isObject(this._events.error) && !this._events.error.length)) {\n\t er = arguments[1];\n\t if (er instanceof Error) {\n\t throw er; // Unhandled 'error' event\n\t } else {\n\t // At least give some kind of context to the user\n\t var err = new Error('Uncaught, unspecified \"error\" event. (' + er + ')');\n\t err.context = er;\n\t throw err;\n\t }\n\t }\n\t }\n\t\n\t handler = this._events[type];\n\t\n\t if (isUndefined(handler))\n\t return false;\n\t\n\t if (isFunction(handler)) {\n\t switch (arguments.length) {\n\t // fast cases\n\t case 1:\n\t handler.call(this);\n\t break;\n\t case 2:\n\t handler.call(this, arguments[1]);\n\t break;\n\t case 3:\n\t handler.call(this, arguments[1], arguments[2]);\n\t break;\n\t // slower\n\t default:\n\t args = Array.prototype.slice.call(arguments, 1);\n\t handler.apply(this, args);\n\t }\n\t } else if (isObject(handler)) {\n\t args = Array.prototype.slice.call(arguments, 1);\n\t listeners = handler.slice();\n\t len = listeners.length;\n\t for (i = 0; i < len; i++)\n\t listeners[i].apply(this, args);\n\t }\n\t\n\t return true;\n\t};\n\t\n\tEventEmitter.prototype.addListener = function(type, listener) {\n\t var m;\n\t\n\t if (!isFunction(listener))\n\t throw TypeError('listener must be a function');\n\t\n\t if (!this._events)\n\t this._events = {};\n\t\n\t // To avoid recursion in the case that type === \"newListener\"! Before\n\t // adding it to the listeners, first emit \"newListener\".\n\t if (this._events.newListener)\n\t this.emit('newListener', type,\n\t isFunction(listener.listener) ?\n\t listener.listener : listener);\n\t\n\t if (!this._events[type])\n\t // Optimize the case of one listener. Don't need the extra array object.\n\t this._events[type] = listener;\n\t else if (isObject(this._events[type]))\n\t // If we've already got an array, just append.\n\t this._events[type].push(listener);\n\t else\n\t // Adding the second element, need to change to array.\n\t this._events[type] = [this._events[type], listener];\n\t\n\t // Check for listener leak\n\t if (isObject(this._events[type]) && !this._events[type].warned) {\n\t if (!isUndefined(this._maxListeners)) {\n\t m = this._maxListeners;\n\t } else {\n\t m = EventEmitter.defaultMaxListeners;\n\t }\n\t\n\t if (m && m > 0 && this._events[type].length > m) {\n\t this._events[type].warned = true;\n\t console.error('(node) warning: possible EventEmitter memory ' +\n\t 'leak detected. %d listeners added. ' +\n\t 'Use emitter.setMaxListeners() to increase limit.',\n\t this._events[type].length);\n\t if (typeof console.trace === 'function') {\n\t // not supported in IE 10\n\t console.trace();\n\t }\n\t }\n\t }\n\t\n\t return this;\n\t};\n\t\n\tEventEmitter.prototype.on = EventEmitter.prototype.addListener;\n\t\n\tEventEmitter.prototype.once = function(type, listener) {\n\t if (!isFunction(listener))\n\t throw TypeError('listener must be a function');\n\t\n\t var fired = false;\n\t\n\t function g() {\n\t this.removeListener(type, g);\n\t\n\t if (!fired) {\n\t fired = true;\n\t listener.apply(this, arguments);\n\t }\n\t }\n\t\n\t g.listener = listener;\n\t this.on(type, g);\n\t\n\t return this;\n\t};\n\t\n\t// emits a 'removeListener' event iff the listener was removed\n\tEventEmitter.prototype.removeListener = function(type, listener) {\n\t var list, position, length, i;\n\t\n\t if (!isFunction(listener))\n\t throw TypeError('listener must be a function');\n\t\n\t if (!this._events || !this._events[type])\n\t return this;\n\t\n\t list = this._events[type];\n\t length = list.length;\n\t position = -1;\n\t\n\t if (list === listener ||\n\t (isFunction(list.listener) && list.listener === listener)) {\n\t delete this._events[type];\n\t if (this._events.removeListener)\n\t this.emit('removeListener', type, listener);\n\t\n\t } else if (isObject(list)) {\n\t for (i = length; i-- > 0;) {\n\t if (list[i] === listener ||\n\t (list[i].listener && list[i].listener === listener)) {\n\t position = i;\n\t break;\n\t }\n\t }\n\t\n\t if (position < 0)\n\t return this;\n\t\n\t if (list.length === 1) {\n\t list.length = 0;\n\t delete this._events[type];\n\t } else {\n\t list.splice(position, 1);\n\t }\n\t\n\t if (this._events.removeListener)\n\t this.emit('removeListener', type, listener);\n\t }\n\t\n\t return this;\n\t};\n\t\n\tEventEmitter.prototype.removeAllListeners = function(type) {\n\t var key, listeners;\n\t\n\t if (!this._events)\n\t return this;\n\t\n\t // not listening for removeListener, no need to emit\n\t if (!this._events.removeListener) {\n\t if (arguments.length === 0)\n\t this._events = {};\n\t else if (this._events[type])\n\t delete this._events[type];\n\t return this;\n\t }\n\t\n\t // emit removeListener for all listeners on all events\n\t if (arguments.length === 0) {\n\t for (key in this._events) {\n\t if (key === 'removeListener') continue;\n\t this.removeAllListeners(key);\n\t }\n\t this.removeAllListeners('removeListener');\n\t this._events = {};\n\t return this;\n\t }\n\t\n\t listeners = this._events[type];\n\t\n\t if (isFunction(listeners)) {\n\t this.removeListener(type, listeners);\n\t } else if (listeners) {\n\t // LIFO order\n\t while (listeners.length)\n\t this.removeListener(type, listeners[listeners.length - 1]);\n\t }\n\t delete this._events[type];\n\t\n\t return this;\n\t};\n\t\n\tEventEmitter.prototype.listeners = function(type) {\n\t var ret;\n\t if (!this._events || !this._events[type])\n\t ret = [];\n\t else if (isFunction(this._events[type]))\n\t ret = [this._events[type]];\n\t else\n\t ret = this._events[type].slice();\n\t return ret;\n\t};\n\t\n\tEventEmitter.prototype.listenerCount = function(type) {\n\t if (this._events) {\n\t var evlistener = this._events[type];\n\t\n\t if (isFunction(evlistener))\n\t return 1;\n\t else if (evlistener)\n\t return evlistener.length;\n\t }\n\t return 0;\n\t};\n\t\n\tEventEmitter.listenerCount = function(emitter, type) {\n\t return emitter.listenerCount(type);\n\t};\n\t\n\tfunction isFunction(arg) {\n\t return typeof arg === 'function';\n\t}\n\t\n\tfunction isNumber(arg) {\n\t return typeof arg === 'number';\n\t}\n\t\n\tfunction isObject(arg) {\n\t return typeof arg === 'object' && arg !== null;\n\t}\n\t\n\tfunction isUndefined(arg) {\n\t return arg === void 0;\n\t}\n\n\n/***/ },\n/* 7 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tmodule.exports = __webpack_require__(1).Buffer;\n\n\n/***/ },\n/* 8 */\n/***/ function(module, exports) {\n\n\t'use strict';\n\t\n\t\n\tvar TYPED_OK = (typeof Uint8Array !== 'undefined') &&\n\t (typeof Uint16Array !== 'undefined') &&\n\t (typeof Int32Array !== 'undefined');\n\t\n\t\n\texports.assign = function (obj /*from1, from2, from3, ...*/) {\n\t var sources = Array.prototype.slice.call(arguments, 1);\n\t while (sources.length) {\n\t var source = sources.shift();\n\t if (!source) { continue; }\n\t\n\t if (typeof source !== 'object') {\n\t throw new TypeError(source + 'must be non-object');\n\t }\n\t\n\t for (var p in source) {\n\t if (source.hasOwnProperty(p)) {\n\t obj[p] = source[p];\n\t }\n\t }\n\t }\n\t\n\t return obj;\n\t};\n\t\n\t\n\t// reduce buffer size, avoiding mem copy\n\texports.shrinkBuf = function (buf, size) {\n\t if (buf.length === size) { return buf; }\n\t if (buf.subarray) { return buf.subarray(0, size); }\n\t buf.length = size;\n\t return buf;\n\t};\n\t\n\t\n\tvar fnTyped = {\n\t arraySet: function (dest, src, src_offs, len, dest_offs) {\n\t if (src.subarray && dest.subarray) {\n\t dest.set(src.subarray(src_offs, src_offs + len), dest_offs);\n\t return;\n\t }\n\t // Fallback to ordinary array\n\t for (var i = 0; i < len; i++) {\n\t dest[dest_offs + i] = src[src_offs + i];\n\t }\n\t },\n\t // Join array of chunks to single array.\n\t flattenChunks: function (chunks) {\n\t var i, l, len, pos, chunk, result;\n\t\n\t // calculate data length\n\t len = 0;\n\t for (i = 0, l = chunks.length; i < l; i++) {\n\t len += chunks[i].length;\n\t }\n\t\n\t // join chunks\n\t result = new Uint8Array(len);\n\t pos = 0;\n\t for (i = 0, l = chunks.length; i < l; i++) {\n\t chunk = chunks[i];\n\t result.set(chunk, pos);\n\t pos += chunk.length;\n\t }\n\t\n\t return result;\n\t }\n\t};\n\t\n\tvar fnUntyped = {\n\t arraySet: function (dest, src, src_offs, len, dest_offs) {\n\t for (var i = 0; i < len; i++) {\n\t dest[dest_offs + i] = src[src_offs + i];\n\t }\n\t },\n\t // Join array of chunks to single array.\n\t flattenChunks: function (chunks) {\n\t return [].concat.apply([], chunks);\n\t }\n\t};\n\t\n\t\n\t// Enable/Disable typed arrays use, for testing\n\t//\n\texports.setTyped = function (on) {\n\t if (on) {\n\t exports.Buf8 = Uint8Array;\n\t exports.Buf16 = Uint16Array;\n\t exports.Buf32 = Int32Array;\n\t exports.assign(exports, fnTyped);\n\t } else {\n\t exports.Buf8 = Array;\n\t exports.Buf16 = Array;\n\t exports.Buf32 = Array;\n\t exports.assign(exports, fnUntyped);\n\t }\n\t};\n\t\n\texports.setTyped(TYPED_OK);\n\n\n/***/ },\n/* 9 */\n/***/ function(module, exports, __webpack_require__) {\n\n\t// Copyright Joyent, Inc. and other Node contributors.\n\t//\n\t// Permission is hereby granted, free of charge, to any person obtaining a\n\t// copy of this software and associated documentation files (the\n\t// \"Software\"), to deal in the Software without restriction, including\n\t// without limitation the rights to use, copy, modify, merge, publish,\n\t// distribute, sublicense, and/or sell copies of the Software, and to permit\n\t// persons to whom the Software is furnished to do so, subject to the\n\t// following conditions:\n\t//\n\t// The above copyright notice and this permission notice shall be included\n\t// in all copies or substantial portions of the Software.\n\t//\n\t// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n\t// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n\t// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n\t// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n\t// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n\t// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n\t// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\t\n\tmodule.exports = Stream;\n\t\n\tvar EE = __webpack_require__(6).EventEmitter;\n\tvar inherits = __webpack_require__(4);\n\t\n\tinherits(Stream, EE);\n\tStream.Readable = __webpack_require__(37);\n\tStream.Writable = __webpack_require__(39);\n\tStream.Duplex = __webpack_require__(34);\n\tStream.Transform = __webpack_require__(38);\n\tStream.PassThrough = __webpack_require__(36);\n\t\n\t// Backwards-compat with node 0.4.x\n\tStream.Stream = Stream;\n\t\n\t\n\t\n\t// old-style streams. Note that the pipe method (the only relevant\n\t// part of this class) is overridden in the Readable class.\n\t\n\tfunction Stream() {\n\t EE.call(this);\n\t}\n\t\n\tStream.prototype.pipe = function(dest, options) {\n\t var source = this;\n\t\n\t function ondata(chunk) {\n\t if (dest.writable) {\n\t if (false === dest.write(chunk) && source.pause) {\n\t source.pause();\n\t }\n\t }\n\t }\n\t\n\t source.on('data', ondata);\n\t\n\t function ondrain() {\n\t if (source.readable && source.resume) {\n\t source.resume();\n\t }\n\t }\n\t\n\t dest.on('drain', ondrain);\n\t\n\t // If the 'end' option is not supplied, dest.end() will be called when\n\t // source gets the 'end' or 'close' events. Only dest.end() once.\n\t if (!dest._isStdio && (!options || options.end !== false)) {\n\t source.on('end', onend);\n\t source.on('close', onclose);\n\t }\n\t\n\t var didOnEnd = false;\n\t function onend() {\n\t if (didOnEnd) return;\n\t didOnEnd = true;\n\t\n\t dest.end();\n\t }\n\t\n\t\n\t function onclose() {\n\t if (didOnEnd) return;\n\t didOnEnd = true;\n\t\n\t if (typeof dest.destroy === 'function') dest.destroy();\n\t }\n\t\n\t // don't leave dangling pipes when there are errors.\n\t function onerror(er) {\n\t cleanup();\n\t if (EE.listenerCount(this, 'error') === 0) {\n\t throw er; // Unhandled stream error in pipe.\n\t }\n\t }\n\t\n\t source.on('error', onerror);\n\t dest.on('error', onerror);\n\t\n\t // remove all the event listeners that were added.\n\t function cleanup() {\n\t source.removeListener('data', ondata);\n\t dest.removeListener('drain', ondrain);\n\t\n\t source.removeListener('end', onend);\n\t source.removeListener('close', onclose);\n\t\n\t source.removeListener('error', onerror);\n\t dest.removeListener('error', onerror);\n\t\n\t source.removeListener('end', cleanup);\n\t source.removeListener('close', cleanup);\n\t\n\t dest.removeListener('close', cleanup);\n\t }\n\t\n\t source.on('end', cleanup);\n\t source.on('close', cleanup);\n\t\n\t dest.on('close', cleanup);\n\t\n\t dest.emit('pipe', source);\n\t\n\t // Allow for unix-like usage: A.pipe(B).pipe(C)\n\t return dest;\n\t};\n\n\n/***/ },\n/* 10 */\n/***/ function(module, exports, __webpack_require__) {\n\n\t/* WEBPACK VAR INJECTION */(function(global) {'use strict';\n\t\n\tvar buffer = __webpack_require__(1);\n\tvar Buffer = buffer.Buffer;\n\tvar SlowBuffer = buffer.SlowBuffer;\n\tvar MAX_LEN = buffer.kMaxLength || 2147483647;\n\texports.alloc = function alloc(size, fill, encoding) {\n\t if (typeof Buffer.alloc === 'function') {\n\t return Buffer.alloc(size, fill, encoding);\n\t }\n\t if (typeof encoding === 'number') {\n\t throw new TypeError('encoding must not be number');\n\t }\n\t if (typeof size !== 'number') {\n\t throw new TypeError('size must be a number');\n\t }\n\t if (size > MAX_LEN) {\n\t throw new RangeError('size is too large');\n\t }\n\t var enc = encoding;\n\t var _fill = fill;\n\t if (_fill === undefined) {\n\t enc = undefined;\n\t _fill = 0;\n\t }\n\t var buf = new Buffer(size);\n\t if (typeof _fill === 'string') {\n\t var fillBuf = new Buffer(_fill, enc);\n\t var flen = fillBuf.length;\n\t var i = -1;\n\t while (++i < size) {\n\t buf[i] = fillBuf[i % flen];\n\t }\n\t } else {\n\t buf.fill(_fill);\n\t }\n\t return buf;\n\t}\n\texports.allocUnsafe = function allocUnsafe(size) {\n\t if (typeof Buffer.allocUnsafe === 'function') {\n\t return Buffer.allocUnsafe(size);\n\t }\n\t if (typeof size !== 'number') {\n\t throw new TypeError('size must be a number');\n\t }\n\t if (size > MAX_LEN) {\n\t throw new RangeError('size is too large');\n\t }\n\t return new Buffer(size);\n\t}\n\texports.from = function from(value, encodingOrOffset, length) {\n\t if (typeof Buffer.from === 'function' && (!global.Uint8Array || Uint8Array.from !== Buffer.from)) {\n\t return Buffer.from(value, encodingOrOffset, length);\n\t }\n\t if (typeof value === 'number') {\n\t throw new TypeError('\"value\" argument must not be a number');\n\t }\n\t if (typeof value === 'string') {\n\t return new Buffer(value, encodingOrOffset);\n\t }\n\t if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {\n\t var offset = encodingOrOffset;\n\t if (arguments.length === 1) {\n\t return new Buffer(value);\n\t }\n\t if (typeof offset === 'undefined') {\n\t offset = 0;\n\t }\n\t var len = length;\n\t if (typeof len === 'undefined') {\n\t len = value.byteLength - offset;\n\t }\n\t if (offset >= value.byteLength) {\n\t throw new RangeError('\\'offset\\' is out of bounds');\n\t }\n\t if (len > value.byteLength - offset) {\n\t throw new RangeError('\\'length\\' is out of bounds');\n\t }\n\t return new Buffer(value.slice(offset, offset + len));\n\t }\n\t if (Buffer.isBuffer(value)) {\n\t var out = new Buffer(value.length);\n\t value.copy(out, 0, 0, value.length);\n\t return out;\n\t }\n\t if (value) {\n\t if (Array.isArray(value) || (typeof ArrayBuffer !== 'undefined' && value.buffer instanceof ArrayBuffer) || 'length' in value) {\n\t return new Buffer(value);\n\t }\n\t if (value.type === 'Buffer' && Array.isArray(value.data)) {\n\t return new Buffer(value.data);\n\t }\n\t }\n\t\n\t throw new TypeError('First argument must be a string, Buffer, ' + 'ArrayBuffer, Array, or array-like object.');\n\t}\n\texports.allocUnsafeSlow = function allocUnsafeSlow(size) {\n\t if (typeof Buffer.allocUnsafeSlow === 'function') {\n\t return Buffer.allocUnsafeSlow(size);\n\t }\n\t if (typeof size !== 'number') {\n\t throw new TypeError('size must be a number');\n\t }\n\t if (size >= MAX_LEN) {\n\t throw new RangeError('size is too large');\n\t }\n\t return new SlowBuffer(size);\n\t}\n\t\n\t/* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }())))\n\n/***/ },\n/* 11 */\n/***/ function(module, exports, __webpack_require__) {\n\n\t/* WEBPACK VAR INJECTION */(function(process) {'use strict';\n\t\n\tif (!process.version ||\n\t process.version.indexOf('v0.') === 0 ||\n\t process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {\n\t module.exports = nextTick;\n\t} else {\n\t module.exports = process.nextTick;\n\t}\n\t\n\tfunction nextTick(fn, arg1, arg2, arg3) {\n\t if (typeof fn !== 'function') {\n\t throw new TypeError('\"callback\" argument must be a function');\n\t }\n\t var len = arguments.length;\n\t var args, i;\n\t switch (len) {\n\t case 0:\n\t case 1:\n\t return process.nextTick(fn);\n\t case 2:\n\t return process.nextTick(function afterTickOne() {\n\t fn.call(null, arg1);\n\t });\n\t case 3:\n\t return process.nextTick(function afterTickTwo() {\n\t fn.call(null, arg1, arg2);\n\t });\n\t case 4:\n\t return process.nextTick(function afterTickThree() {\n\t fn.call(null, arg1, arg2, arg3);\n\t });\n\t default:\n\t args = new Array(len - 1);\n\t i = 0;\n\t while (i < args.length) {\n\t args[i++] = arguments[i];\n\t }\n\t return process.nextTick(function afterTick() {\n\t fn.apply(null, args);\n\t });\n\t }\n\t}\n\t\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))\n\n/***/ },\n/* 12 */\n/***/ function(module, exports, __webpack_require__) {\n\n\t// a transform stream is a readable/writable stream where you do\n\t// something with the data. Sometimes it's called a \"filter\",\n\t// but that's not a great name for it, since that implies a thing where\n\t// some bits pass through, and others are simply ignored. (That would\n\t// be a valid example of a transform, of course.)\n\t//\n\t// While the output is causally related to the input, it's not a\n\t// necessarily symmetric or synchronous transformation. For example,\n\t// a zlib stream might take multiple plain-text writes(), and then\n\t// emit a single compressed chunk some time in the future.\n\t//\n\t// Here's how this works:\n\t//\n\t// The Transform stream has all the aspects of the readable and writable\n\t// stream classes. When you write(chunk), that calls _write(chunk,cb)\n\t// internally, and returns false if there's a lot of pending writes\n\t// buffered up. When you call read(), that calls _read(n) until\n\t// there's enough pending readable data buffered up.\n\t//\n\t// In a transform stream, the written data is placed in a buffer. When\n\t// _read(n) is called, it transforms the queued up data, calling the\n\t// buffered _write cb's as it consumes chunks. If consuming a single\n\t// written chunk would result in multiple output chunks, then the first\n\t// outputted bit calls the readcb, and subsequent chunks just go into\n\t// the read buffer, and will cause it to emit 'readable' if necessary.\n\t//\n\t// This way, back-pressure is actually determined by the reading side,\n\t// since _read has to be called to start processing a new chunk. However,\n\t// a pathological inflate type of transform can cause excessive buffering\n\t// here. For example, imagine a stream where every byte of input is\n\t// interpreted as an integer from 0-255, and then results in that many\n\t// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in\n\t// 1kb of data being output. In this case, you could write a very small\n\t// amount of input, and end up with a very large amount of output. In\n\t// such a pathological inflating mechanism, there'd be no way to tell\n\t// the system to stop doing the transform. A single 4MB write could\n\t// cause the system to run out of memory.\n\t//\n\t// However, even in such a pathological case, only a single written chunk\n\t// would be consumed, and then the rest would wait (un-transformed) until\n\t// the results of the previous transformed chunk were consumed.\n\t\n\t'use strict';\n\t\n\tmodule.exports = Transform;\n\t\n\tvar Duplex = __webpack_require__(2);\n\t\n\t/**/\n\tvar util = __webpack_require__(5);\n\tutil.inherits = __webpack_require__(4);\n\t/**/\n\t\n\tutil.inherits(Transform, Duplex);\n\t\n\tfunction TransformState(stream) {\n\t this.afterTransform = function (er, data) {\n\t return afterTransform(stream, er, data);\n\t };\n\t\n\t this.needTransform = false;\n\t this.transforming = false;\n\t this.writecb = null;\n\t this.writechunk = null;\n\t this.writeencoding = null;\n\t}\n\t\n\tfunction afterTransform(stream, er, data) {\n\t var ts = stream._transformState;\n\t ts.transforming = false;\n\t\n\t var cb = ts.writecb;\n\t\n\t if (!cb) return stream.emit('error', new Error('no writecb in Transform class'));\n\t\n\t ts.writechunk = null;\n\t ts.writecb = null;\n\t\n\t if (data !== null && data !== undefined) stream.push(data);\n\t\n\t cb(er);\n\t\n\t var rs = stream._readableState;\n\t rs.reading = false;\n\t if (rs.needReadable || rs.length < rs.highWaterMark) {\n\t stream._read(rs.highWaterMark);\n\t }\n\t}\n\t\n\tfunction Transform(options) {\n\t if (!(this instanceof Transform)) return new Transform(options);\n\t\n\t Duplex.call(this, options);\n\t\n\t this._transformState = new TransformState(this);\n\t\n\t var stream = this;\n\t\n\t // start out asking for a readable event once data is transformed.\n\t this._readableState.needReadable = true;\n\t\n\t // we have implemented the _read method, and done the other things\n\t // that Readable wants before the first _read call, so unset the\n\t // sync guard flag.\n\t this._readableState.sync = false;\n\t\n\t if (options) {\n\t if (typeof options.transform === 'function') this._transform = options.transform;\n\t\n\t if (typeof options.flush === 'function') this._flush = options.flush;\n\t }\n\t\n\t // When the writable side finishes, then flush out anything remaining.\n\t this.once('prefinish', function () {\n\t if (typeof this._flush === 'function') this._flush(function (er, data) {\n\t done(stream, er, data);\n\t });else done(stream);\n\t });\n\t}\n\t\n\tTransform.prototype.push = function (chunk, encoding) {\n\t this._transformState.needTransform = false;\n\t return Duplex.prototype.push.call(this, chunk, encoding);\n\t};\n\t\n\t// This is the part where you do stuff!\n\t// override this function in implementation classes.\n\t// 'chunk' is an input chunk.\n\t//\n\t// Call `push(newChunk)` to pass along transformed output\n\t// to the readable side. You may call 'push' zero or more times.\n\t//\n\t// Call `cb(err)` when you are done with this chunk. If you pass\n\t// an error, then that'll put the hurt on the whole operation. If you\n\t// never call cb(), then you'll never get another chunk.\n\tTransform.prototype._transform = function (chunk, encoding, cb) {\n\t throw new Error('_transform() is not implemented');\n\t};\n\t\n\tTransform.prototype._write = function (chunk, encoding, cb) {\n\t var ts = this._transformState;\n\t ts.writecb = cb;\n\t ts.writechunk = chunk;\n\t ts.writeencoding = encoding;\n\t if (!ts.transforming) {\n\t var rs = this._readableState;\n\t if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);\n\t }\n\t};\n\t\n\t// Doesn't matter what the args are here.\n\t// _transform does all the work.\n\t// That we got here means that the readable side wants more data.\n\tTransform.prototype._read = function (n) {\n\t var ts = this._transformState;\n\t\n\t if (ts.writechunk !== null && ts.writecb && !ts.transforming) {\n\t ts.transforming = true;\n\t this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);\n\t } else {\n\t // mark that we need a transform, so that any data that comes in\n\t // will get processed, now that we've asked for it.\n\t ts.needTransform = true;\n\t }\n\t};\n\t\n\tfunction done(stream, er, data) {\n\t if (er) return stream.emit('error', er);\n\t\n\t if (data !== null && data !== undefined) stream.push(data);\n\t\n\t // if there's nothing in the write buffer, then that means\n\t // that nothing more will ever be provided\n\t var ws = stream._writableState;\n\t var ts = stream._transformState;\n\t\n\t if (ws.length) throw new Error('Calling transform done when ws.length != 0');\n\t\n\t if (ts.transforming) throw new Error('Calling transform done when still transforming');\n\t\n\t return stream.push(null);\n\t}\n\n/***/ },\n/* 13 */\n/***/ function(module, exports, __webpack_require__) {\n\n\t/* WEBPACK VAR INJECTION */(function(process) {// A bit simpler than readable streams.\n\t// Implement an async ._write(chunk, encoding, cb), and it'll handle all\n\t// the drain event emission and buffering.\n\t\n\t'use strict';\n\t\n\tmodule.exports = Writable;\n\t\n\t/**/\n\tvar processNextTick = __webpack_require__(11);\n\t/**/\n\t\n\t/**/\n\tvar asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : processNextTick;\n\t/**/\n\t\n\t/**/\n\tvar Duplex;\n\t/**/\n\t\n\tWritable.WritableState = WritableState;\n\t\n\t/**/\n\tvar util = __webpack_require__(5);\n\tutil.inherits = __webpack_require__(4);\n\t/**/\n\t\n\t/**/\n\tvar internalUtil = {\n\t deprecate: __webpack_require__(40)\n\t};\n\t/**/\n\t\n\t/**/\n\tvar Stream;\n\t(function () {\n\t try {\n\t Stream = __webpack_require__(9);\n\t } catch (_) {} finally {\n\t if (!Stream) Stream = __webpack_require__(6).EventEmitter;\n\t }\n\t})();\n\t/**/\n\t\n\tvar Buffer = __webpack_require__(1).Buffer;\n\t/**/\n\tvar bufferShim = __webpack_require__(10);\n\t/**/\n\t\n\tutil.inherits(Writable, Stream);\n\t\n\tfunction nop() {}\n\t\n\tfunction WriteReq(chunk, encoding, cb) {\n\t this.chunk = chunk;\n\t this.encoding = encoding;\n\t this.callback = cb;\n\t this.next = null;\n\t}\n\t\n\tfunction WritableState(options, stream) {\n\t Duplex = Duplex || __webpack_require__(2);\n\t\n\t options = options || {};\n\t\n\t // object stream flag to indicate whether or not this stream\n\t // contains buffers or objects.\n\t this.objectMode = !!options.objectMode;\n\t\n\t if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode;\n\t\n\t // the point at which write() starts returning false\n\t // Note: 0 is a valid value, means that we always return false if\n\t // the entire buffer is not flushed immediately on write()\n\t var hwm = options.highWaterMark;\n\t var defaultHwm = this.objectMode ? 16 : 16 * 1024;\n\t this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm;\n\t\n\t // cast to ints.\n\t this.highWaterMark = ~~this.highWaterMark;\n\t\n\t // drain event flag.\n\t this.needDrain = false;\n\t // at the start of calling end()\n\t this.ending = false;\n\t // when end() has been called, and returned\n\t this.ended = false;\n\t // when 'finish' is emitted\n\t this.finished = false;\n\t\n\t // should we decode strings into buffers before passing to _write?\n\t // this is here so that some node-core streams can optimize string\n\t // handling at a lower level.\n\t var noDecode = options.decodeStrings === false;\n\t this.decodeStrings = !noDecode;\n\t\n\t // Crypto is kind of old and crusty. Historically, its default string\n\t // encoding is 'binary' so we have to make this configurable.\n\t // Everything else in the universe uses 'utf8', though.\n\t this.defaultEncoding = options.defaultEncoding || 'utf8';\n\t\n\t // not an actual buffer we keep track of, but a measurement\n\t // of how much we're waiting to get pushed to some underlying\n\t // socket or file.\n\t this.length = 0;\n\t\n\t // a flag to see when we're in the middle of a write.\n\t this.writing = false;\n\t\n\t // when true all writes will be buffered until .uncork() call\n\t this.corked = 0;\n\t\n\t // a flag to be able to tell if the onwrite cb is called immediately,\n\t // or on a later tick. We set this to true at first, because any\n\t // actions that shouldn't happen until \"later\" should generally also\n\t // not happen before the first write call.\n\t this.sync = true;\n\t\n\t // a flag to know if we're processing previously buffered items, which\n\t // may call the _write() callback in the same tick, so that we don't\n\t // end up in an overlapped onwrite situation.\n\t this.bufferProcessing = false;\n\t\n\t // the callback that's passed to _write(chunk,cb)\n\t this.onwrite = function (er) {\n\t onwrite(stream, er);\n\t };\n\t\n\t // the callback that the user supplies to write(chunk,encoding,cb)\n\t this.writecb = null;\n\t\n\t // the amount that is being written when _write is called.\n\t this.writelen = 0;\n\t\n\t this.bufferedRequest = null;\n\t this.lastBufferedRequest = null;\n\t\n\t // number of pending user-supplied write callbacks\n\t // this must be 0 before 'finish' can be emitted\n\t this.pendingcb = 0;\n\t\n\t // emit prefinish if the only thing we're waiting for is _write cbs\n\t // This is relevant for synchronous Transform streams\n\t this.prefinished = false;\n\t\n\t // True if the error was already emitted and should not be thrown again\n\t this.errorEmitted = false;\n\t\n\t // count buffered requests\n\t this.bufferedRequestCount = 0;\n\t\n\t // allocate the first CorkedRequest, there is always\n\t // one allocated and free to use, and we maintain at most two\n\t this.corkedRequestsFree = new CorkedRequest(this);\n\t}\n\t\n\tWritableState.prototype.getBuffer = function getBuffer() {\n\t var current = this.bufferedRequest;\n\t var out = [];\n\t while (current) {\n\t out.push(current);\n\t current = current.next;\n\t }\n\t return out;\n\t};\n\t\n\t(function () {\n\t try {\n\t Object.defineProperty(WritableState.prototype, 'buffer', {\n\t get: internalUtil.deprecate(function () {\n\t return this.getBuffer();\n\t }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.')\n\t });\n\t } catch (_) {}\n\t})();\n\t\n\t// Test _writableState for inheritance to account for Duplex streams,\n\t// whose prototype chain only points to Readable.\n\tvar realHasInstance;\n\tif (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {\n\t realHasInstance = Function.prototype[Symbol.hasInstance];\n\t Object.defineProperty(Writable, Symbol.hasInstance, {\n\t value: function (object) {\n\t if (realHasInstance.call(this, object)) return true;\n\t\n\t return object && object._writableState instanceof WritableState;\n\t }\n\t });\n\t} else {\n\t realHasInstance = function (object) {\n\t return object instanceof this;\n\t };\n\t}\n\t\n\tfunction Writable(options) {\n\t Duplex = Duplex || __webpack_require__(2);\n\t\n\t // Writable ctor is applied to Duplexes, too.\n\t // `realHasInstance` is necessary because using plain `instanceof`\n\t // would return false, as no `_writableState` property is attached.\n\t\n\t // Trying to use the custom `instanceof` for Writable here will also break the\n\t // Node.js LazyTransform implementation, which has a non-trivial getter for\n\t // `_writableState` that would lead to infinite recursion.\n\t if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {\n\t return new Writable(options);\n\t }\n\t\n\t this._writableState = new WritableState(options, this);\n\t\n\t // legacy.\n\t this.writable = true;\n\t\n\t if (options) {\n\t if (typeof options.write === 'function') this._write = options.write;\n\t\n\t if (typeof options.writev === 'function') this._writev = options.writev;\n\t }\n\t\n\t Stream.call(this);\n\t}\n\t\n\t// Otherwise people can pipe Writable streams, which is just wrong.\n\tWritable.prototype.pipe = function () {\n\t this.emit('error', new Error('Cannot pipe, not readable'));\n\t};\n\t\n\tfunction writeAfterEnd(stream, cb) {\n\t var er = new Error('write after end');\n\t // TODO: defer error events consistently everywhere, not just the cb\n\t stream.emit('error', er);\n\t processNextTick(cb, er);\n\t}\n\t\n\t// Checks that a user-supplied chunk is valid, especially for the particular\n\t// mode the stream is in. Currently this means that `null` is never accepted\n\t// and undefined/non-string values are only allowed in object mode.\n\tfunction validChunk(stream, state, chunk, cb) {\n\t var valid = true;\n\t var er = false;\n\t\n\t if (chunk === null) {\n\t er = new TypeError('May not write null values to stream');\n\t } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {\n\t er = new TypeError('Invalid non-string/buffer chunk');\n\t }\n\t if (er) {\n\t stream.emit('error', er);\n\t processNextTick(cb, er);\n\t valid = false;\n\t }\n\t return valid;\n\t}\n\t\n\tWritable.prototype.write = function (chunk, encoding, cb) {\n\t var state = this._writableState;\n\t var ret = false;\n\t var isBuf = Buffer.isBuffer(chunk);\n\t\n\t if (typeof encoding === 'function') {\n\t cb = encoding;\n\t encoding = null;\n\t }\n\t\n\t if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;\n\t\n\t if (typeof cb !== 'function') cb = nop;\n\t\n\t if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {\n\t state.pendingcb++;\n\t ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);\n\t }\n\t\n\t return ret;\n\t};\n\t\n\tWritable.prototype.cork = function () {\n\t var state = this._writableState;\n\t\n\t state.corked++;\n\t};\n\t\n\tWritable.prototype.uncork = function () {\n\t var state = this._writableState;\n\t\n\t if (state.corked) {\n\t state.corked--;\n\t\n\t if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);\n\t }\n\t};\n\t\n\tWritable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {\n\t // node::ParseEncoding() requires lower case.\n\t if (typeof encoding === 'string') encoding = encoding.toLowerCase();\n\t if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding);\n\t this._writableState.defaultEncoding = encoding;\n\t return this;\n\t};\n\t\n\tfunction decodeChunk(state, chunk, encoding) {\n\t if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {\n\t chunk = bufferShim.from(chunk, encoding);\n\t }\n\t return chunk;\n\t}\n\t\n\t// if we're already writing something, then just put this\n\t// in the queue, and wait our turn. Otherwise, call _write\n\t// If we return false, then we need a drain event, so set that flag.\n\tfunction writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {\n\t if (!isBuf) {\n\t chunk = decodeChunk(state, chunk, encoding);\n\t if (Buffer.isBuffer(chunk)) encoding = 'buffer';\n\t }\n\t var len = state.objectMode ? 1 : chunk.length;\n\t\n\t state.length += len;\n\t\n\t var ret = state.length < state.highWaterMark;\n\t // we must ensure that previous needDrain will not be reset to false.\n\t if (!ret) state.needDrain = true;\n\t\n\t if (state.writing || state.corked) {\n\t var last = state.lastBufferedRequest;\n\t state.lastBufferedRequest = new WriteReq(chunk, encoding, cb);\n\t if (last) {\n\t last.next = state.lastBufferedRequest;\n\t } else {\n\t state.bufferedRequest = state.lastBufferedRequest;\n\t }\n\t state.bufferedRequestCount += 1;\n\t } else {\n\t doWrite(stream, state, false, len, chunk, encoding, cb);\n\t }\n\t\n\t return ret;\n\t}\n\t\n\tfunction doWrite(stream, state, writev, len, chunk, encoding, cb) {\n\t state.writelen = len;\n\t state.writecb = cb;\n\t state.writing = true;\n\t state.sync = true;\n\t if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);\n\t state.sync = false;\n\t}\n\t\n\tfunction onwriteError(stream, state, sync, er, cb) {\n\t --state.pendingcb;\n\t if (sync) processNextTick(cb, er);else cb(er);\n\t\n\t stream._writableState.errorEmitted = true;\n\t stream.emit('error', er);\n\t}\n\t\n\tfunction onwriteStateUpdate(state) {\n\t state.writing = false;\n\t state.writecb = null;\n\t state.length -= state.writelen;\n\t state.writelen = 0;\n\t}\n\t\n\tfunction onwrite(stream, er) {\n\t var state = stream._writableState;\n\t var sync = state.sync;\n\t var cb = state.writecb;\n\t\n\t onwriteStateUpdate(state);\n\t\n\t if (er) onwriteError(stream, state, sync, er, cb);else {\n\t // Check if we're actually ready to finish, but don't emit yet\n\t var finished = needFinish(state);\n\t\n\t if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {\n\t clearBuffer(stream, state);\n\t }\n\t\n\t if (sync) {\n\t /**/\n\t asyncWrite(afterWrite, stream, state, finished, cb);\n\t /**/\n\t } else {\n\t afterWrite(stream, state, finished, cb);\n\t }\n\t }\n\t}\n\t\n\tfunction afterWrite(stream, state, finished, cb) {\n\t if (!finished) onwriteDrain(stream, state);\n\t state.pendingcb--;\n\t cb();\n\t finishMaybe(stream, state);\n\t}\n\t\n\t// Must force callback to be called on nextTick, so that we don't\n\t// emit 'drain' before the write() consumer gets the 'false' return\n\t// value, and has a chance to attach a 'drain' listener.\n\tfunction onwriteDrain(stream, state) {\n\t if (state.length === 0 && state.needDrain) {\n\t state.needDrain = false;\n\t stream.emit('drain');\n\t }\n\t}\n\t\n\t// if there's something in the buffer waiting, then process it\n\tfunction clearBuffer(stream, state) {\n\t state.bufferProcessing = true;\n\t var entry = state.bufferedRequest;\n\t\n\t if (stream._writev && entry && entry.next) {\n\t // Fast case, write everything using _writev()\n\t var l = state.bufferedRequestCount;\n\t var buffer = new Array(l);\n\t var holder = state.corkedRequestsFree;\n\t holder.entry = entry;\n\t\n\t var count = 0;\n\t while (entry) {\n\t buffer[count] = entry;\n\t entry = entry.next;\n\t count += 1;\n\t }\n\t\n\t doWrite(stream, state, true, state.length, buffer, '', holder.finish);\n\t\n\t // doWrite is almost always async, defer these to save a bit of time\n\t // as the hot path ends with doWrite\n\t state.pendingcb++;\n\t state.lastBufferedRequest = null;\n\t if (holder.next) {\n\t state.corkedRequestsFree = holder.next;\n\t holder.next = null;\n\t } else {\n\t state.corkedRequestsFree = new CorkedRequest(state);\n\t }\n\t } else {\n\t // Slow case, write chunks one-by-one\n\t while (entry) {\n\t var chunk = entry.chunk;\n\t var encoding = entry.encoding;\n\t var cb = entry.callback;\n\t var len = state.objectMode ? 1 : chunk.length;\n\t\n\t doWrite(stream, state, false, len, chunk, encoding, cb);\n\t entry = entry.next;\n\t // if we didn't call the onwrite immediately, then\n\t // it means that we need to wait until it does.\n\t // also, that means that the chunk and cb are currently\n\t // being processed, so move the buffer counter past them.\n\t if (state.writing) {\n\t break;\n\t }\n\t }\n\t\n\t if (entry === null) state.lastBufferedRequest = null;\n\t }\n\t\n\t state.bufferedRequestCount = 0;\n\t state.bufferedRequest = entry;\n\t state.bufferProcessing = false;\n\t}\n\t\n\tWritable.prototype._write = function (chunk, encoding, cb) {\n\t cb(new Error('_write() is not implemented'));\n\t};\n\t\n\tWritable.prototype._writev = null;\n\t\n\tWritable.prototype.end = function (chunk, encoding, cb) {\n\t var state = this._writableState;\n\t\n\t if (typeof chunk === 'function') {\n\t cb = chunk;\n\t chunk = null;\n\t encoding = null;\n\t } else if (typeof encoding === 'function') {\n\t cb = encoding;\n\t encoding = null;\n\t }\n\t\n\t if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);\n\t\n\t // .end() fully uncorks\n\t if (state.corked) {\n\t state.corked = 1;\n\t this.uncork();\n\t }\n\t\n\t // ignore unnecessary end() calls.\n\t if (!state.ending && !state.finished) endWritable(this, state, cb);\n\t};\n\t\n\tfunction needFinish(state) {\n\t return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;\n\t}\n\t\n\tfunction prefinish(stream, state) {\n\t if (!state.prefinished) {\n\t state.prefinished = true;\n\t stream.emit('prefinish');\n\t }\n\t}\n\t\n\tfunction finishMaybe(stream, state) {\n\t var need = needFinish(state);\n\t if (need) {\n\t if (state.pendingcb === 0) {\n\t prefinish(stream, state);\n\t state.finished = true;\n\t stream.emit('finish');\n\t } else {\n\t prefinish(stream, state);\n\t }\n\t }\n\t return need;\n\t}\n\t\n\tfunction endWritable(stream, state, cb) {\n\t state.ending = true;\n\t finishMaybe(stream, state);\n\t if (cb) {\n\t if (state.finished) processNextTick(cb);else stream.once('finish', cb);\n\t }\n\t state.ended = true;\n\t stream.writable = false;\n\t}\n\t\n\t// It seems a linked list but it is not\n\t// there will be only 2 of these for each stream\n\tfunction CorkedRequest(state) {\n\t var _this = this;\n\t\n\t this.next = null;\n\t this.entry = null;\n\t this.finish = function (err) {\n\t var entry = _this.entry;\n\t _this.entry = null;\n\t while (entry) {\n\t var cb = entry.callback;\n\t state.pendingcb--;\n\t cb(err);\n\t entry = entry.next;\n\t }\n\t if (state.corkedRequestsFree) {\n\t state.corkedRequestsFree.next = _this;\n\t } else {\n\t state.corkedRequestsFree = _this;\n\t }\n\t };\n\t}\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))\n\n/***/ },\n/* 14 */\n/***/ function(module, exports, __webpack_require__) {\n\n\t/* WEBPACK VAR INJECTION */(function(process) {\"use strict\";\n\t// Split a filename into [root, dir, basename, ext], unix version\n\t// 'root' is just a slash, or nothing.\n\tvar splitPathRe = /^(\\/?|)([\\s\\S]*?)((?:\\.{1,2}|[^\\/]+?|)(\\.[^.\\/]*|))(?:[\\/]*)$/;\n\tfunction posixSplitPath(filename) {\n\t var out = splitPathRe.exec(filename);\n\t out.shift();\n\t return out;\n\t}\n\t/**\n\t * Emulates Node's `path` module. This module contains utilities for handling and\n\t * transforming file paths. **All** of these methods perform only string\n\t * transformations. The file system is not consulted to check whether paths are\n\t * valid.\n\t * @see http://nodejs.org/api/path.html\n\t * @class\n\t */\n\tvar path = (function () {\n\t function path() {\n\t }\n\t /**\n\t * Normalize a string path, taking care of '..' and '.' parts.\n\t *\n\t * 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\t * @example Usage example\n\t * path.normalize('/foo/bar//baz/asdf/quux/..')\n\t * // returns\n\t * '/foo/bar/baz/asdf'\n\t * @param [String] p The path to normalize.\n\t * @return [String]\n\t */\n\t path.normalize = function (p) {\n\t // Special case: '' -> '.'\n\t if (p === '') {\n\t p = '.';\n\t }\n\t // It's very important to know if the path is relative or not, since it\n\t // changes how we process .. and reconstruct the split string.\n\t var absolute = p.charAt(0) === path.sep;\n\t // Remove repeated //s\n\t p = path._removeDuplicateSeps(p);\n\t // Try to remove as many '../' as possible, and remove '.' completely.\n\t var components = p.split(path.sep);\n\t var goodComponents = [];\n\t for (var idx = 0; idx < components.length; idx++) {\n\t var c = components[idx];\n\t if (c === '.') {\n\t continue;\n\t }\n\t else if (c === '..' && (absolute || (!absolute && goodComponents.length > 0 && goodComponents[0] !== '..'))) {\n\t // In the absolute case: Path is relative to root, so we may pop even if\n\t // goodComponents is empty (e.g. /../ => /)\n\t // In the relative case: We're getting rid of a directory that preceded\n\t // it (e.g. /foo/../bar -> /bar)\n\t goodComponents.pop();\n\t }\n\t else {\n\t goodComponents.push(c);\n\t }\n\t }\n\t // Add in '.' when it's a relative path with no other nonempty components.\n\t // Possible results: '.' and './' (input: [''] or [])\n\t // @todo Can probably simplify this logic.\n\t if (!absolute && goodComponents.length < 2) {\n\t switch (goodComponents.length) {\n\t case 1:\n\t if (goodComponents[0] === '') {\n\t goodComponents.unshift('.');\n\t }\n\t break;\n\t default:\n\t goodComponents.push('.');\n\t }\n\t }\n\t p = goodComponents.join(path.sep);\n\t if (absolute && p.charAt(0) !== path.sep) {\n\t p = path.sep + p;\n\t }\n\t return p;\n\t };\n\t /**\n\t * Join all arguments together and normalize the resulting path.\n\t *\n\t * Arguments must be strings.\n\t * @example Usage\n\t * path.join('/foo', 'bar', 'baz/asdf', 'quux', '..')\n\t * // returns\n\t * '/foo/bar/baz/asdf'\n\t *\n\t * path.join('foo', {}, 'bar')\n\t * // throws exception\n\t * TypeError: Arguments to path.join must be strings\n\t * @param [String,...] paths Each component of the path\n\t * @return [String]\n\t */\n\t path.join = function () {\n\t var paths = [];\n\t for (var _i = 0; _i < arguments.length; _i++) {\n\t paths[_i - 0] = arguments[_i];\n\t }\n\t // Required: Prune any non-strings from the path. I also prune empty segments\n\t // so we can do a simple join of the array.\n\t var processed = [];\n\t for (var i = 0; i < paths.length; i++) {\n\t var segment = paths[i];\n\t if (typeof segment !== 'string') {\n\t throw new TypeError(\"Invalid argument type to path.join: \" + (typeof segment));\n\t }\n\t else if (segment !== '') {\n\t processed.push(segment);\n\t }\n\t }\n\t return path.normalize(processed.join(path.sep));\n\t };\n\t /**\n\t * Resolves to to an absolute path.\n\t *\n\t * If to isn't already absolute from arguments are prepended in right to left\n\t * order, until an absolute path is found. If after using all from paths still\n\t * no absolute path is found, the current working directory is used as well.\n\t * The resulting path is normalized, and trailing slashes are removed unless\n\t * the path gets resolved to the root directory. Non-string arguments are\n\t * ignored.\n\t *\n\t * Another way to think of it is as a sequence of cd commands in a shell.\n\t *\n\t * path.resolve('foo/bar', '/tmp/file/', '..', 'a/../subfile')\n\t *\n\t * Is similar to:\n\t *\n\t * cd foo/bar\n\t * cd /tmp/file/\n\t * cd ..\n\t * cd a/../subfile\n\t * pwd\n\t *\n\t * The difference is that the different paths don't need to exist and may also\n\t * be files.\n\t * @example Usage example\n\t * path.resolve('/foo/bar', './baz')\n\t * // returns\n\t * '/foo/bar/baz'\n\t *\n\t * path.resolve('/foo/bar', '/tmp/file/')\n\t * // returns\n\t * '/tmp/file'\n\t *\n\t * path.resolve('wwwroot', 'static_files/png/', '../gif/image.gif')\n\t * // if currently in /home/myself/node, it returns\n\t * '/home/myself/node/wwwroot/static_files/gif/image.gif'\n\t * @param [String,...] paths\n\t * @return [String]\n\t */\n\t path.resolve = function () {\n\t var paths = [];\n\t for (var _i = 0; _i < arguments.length; _i++) {\n\t paths[_i - 0] = arguments[_i];\n\t }\n\t // Monitor for invalid paths, throw out empty paths, and look for the *last*\n\t // absolute path that we see.\n\t var processed = [];\n\t for (var i = 0; i < paths.length; i++) {\n\t var p = paths[i];\n\t if (typeof p !== 'string') {\n\t throw new TypeError(\"Invalid argument type to path.join: \" + (typeof p));\n\t }\n\t else if (p !== '') {\n\t // Remove anything that has occurred before this absolute path, as it\n\t // doesn't matter.\n\t if (p.charAt(0) === path.sep) {\n\t processed = [];\n\t }\n\t processed.push(p);\n\t }\n\t }\n\t // Special: Remove trailing slash unless it's the root\n\t var resolved = path.normalize(processed.join(path.sep));\n\t if (resolved.length > 1 && resolved.charAt(resolved.length - 1) === path.sep) {\n\t return resolved.substr(0, resolved.length - 1);\n\t }\n\t // Special: If it doesn't start with '/', it's relative and we need to append\n\t // the current directory.\n\t if (resolved.charAt(0) !== path.sep) {\n\t // Remove ./, since we're going to append the current directory.\n\t if (resolved.charAt(0) === '.' && (resolved.length === 1 || resolved.charAt(1) === path.sep)) {\n\t resolved = resolved.length === 1 ? '' : resolved.substr(2);\n\t }\n\t // Append the current directory, which *must* be an absolute path.\n\t var cwd = process.cwd();\n\t if (resolved !== '') {\n\t // cwd will never end in a /... unless it's the root.\n\t resolved = this.normalize(cwd + (cwd !== '/' ? path.sep : '') + resolved);\n\t }\n\t else {\n\t resolved = cwd;\n\t }\n\t }\n\t return resolved;\n\t };\n\t /**\n\t * Solve the relative path from from to to.\n\t *\n\t * At times we have two absolute paths, and we need to derive the relative path\n\t * from one to the other. This is actually the reverse transform of\n\t * path.resolve, which means we see that:\n\t *\n\t * path.resolve(from, path.relative(from, to)) == path.resolve(to)\n\t *\n\t * @example Usage example\n\t * path.relative('C:\\\\orandea\\\\test\\\\aaa', 'C:\\\\orandea\\\\impl\\\\bbb')\n\t * // returns\n\t * '..\\\\..\\\\impl\\\\bbb'\n\t *\n\t * path.relative('/data/orandea/test/aaa', '/data/orandea/impl/bbb')\n\t * // returns\n\t * '../../impl/bbb'\n\t * @param [String] from\n\t * @param [String] to\n\t * @return [String]\n\t */\n\t path.relative = function (from, to) {\n\t var i;\n\t // Alright. Let's resolve these two to absolute paths and remove any\n\t // weirdness.\n\t from = path.resolve(from);\n\t to = path.resolve(to);\n\t var fromSegs = from.split(path.sep);\n\t var toSegs = to.split(path.sep);\n\t // Remove the first segment on both, as it's '' (both are absolute paths)\n\t toSegs.shift();\n\t fromSegs.shift();\n\t // There are two segments to this path:\n\t // * Going *up* the directory hierarchy with '..'\n\t // * Going *down* the directory hierarchy with foo/baz/bat.\n\t var upCount = 0;\n\t var downSegs = [];\n\t // Figure out how many things in 'from' are shared with 'to'.\n\t for (i = 0; i < fromSegs.length; i++) {\n\t var seg = fromSegs[i];\n\t if (seg === toSegs[i]) {\n\t continue;\n\t }\n\t // The rest of 'from', including the current element, indicates how many\n\t // directories we need to go up.\n\t upCount = fromSegs.length - i;\n\t break;\n\t }\n\t // The rest of 'to' indicates where we need to change to. We place this\n\t // outside of the loop, as toSegs.length may be greater than fromSegs.length.\n\t downSegs = toSegs.slice(i);\n\t // Special case: If 'from' is '/'\n\t if (fromSegs.length === 1 && fromSegs[0] === '') {\n\t upCount = 0;\n\t }\n\t // upCount can't be greater than the number of fromSegs\n\t // (cd .. from / is still /)\n\t if (upCount > fromSegs.length) {\n\t upCount = fromSegs.length;\n\t }\n\t // Create the final string!\n\t var rv = '';\n\t for (i = 0; i < upCount; i++) {\n\t rv += '../';\n\t }\n\t rv += downSegs.join(path.sep);\n\t // Special case: Remove trailing '/'. Happens if it's all up and no down.\n\t if (rv.length > 1 && rv.charAt(rv.length - 1) === path.sep) {\n\t rv = rv.substr(0, rv.length - 1);\n\t }\n\t return rv;\n\t };\n\t /**\n\t * Return the directory name of a path. Similar to the Unix `dirname` command.\n\t *\n\t * Note that BrowserFS does not validate if the path is actually a valid\n\t * directory.\n\t * @example Usage example\n\t * path.dirname('/foo/bar/baz/asdf/quux')\n\t * // returns\n\t * '/foo/bar/baz/asdf'\n\t * @param [String] p The path to get the directory name of.\n\t * @return [String]\n\t */\n\t path.dirname = function (p) {\n\t // We get rid of //, but we don't modify anything else (e.g. any extraneous .\n\t // and ../ are kept intact)\n\t p = path._removeDuplicateSeps(p);\n\t var absolute = p.charAt(0) === path.sep;\n\t var sections = p.split(path.sep);\n\t // Do 1 if it's /foo/bar, 2 if it's /foo/bar/\n\t if (sections.pop() === '' && sections.length > 0) {\n\t sections.pop();\n\t }\n\t // # of sections needs to be > 1 if absolute, since the first section is '' for '/'.\n\t // If not absolute, the first section is the first part of the path, and is OK\n\t // to return.\n\t if (sections.length > 1 || (sections.length === 1 && !absolute)) {\n\t return sections.join(path.sep);\n\t }\n\t else if (absolute) {\n\t return path.sep;\n\t }\n\t else {\n\t return '.';\n\t }\n\t };\n\t /**\n\t * Return the last portion of a path. Similar to the Unix basename command.\n\t * @example Usage example\n\t * path.basename('/foo/bar/baz/asdf/quux.html')\n\t * // returns\n\t * 'quux.html'\n\t *\n\t * path.basename('/foo/bar/baz/asdf/quux.html', '.html')\n\t * // returns\n\t * 'quux'\n\t * @param [String] p\n\t * @param [String?] ext\n\t * @return [String]\n\t */\n\t path.basename = function (p, ext) {\n\t if (ext === void 0) { ext = \"\"; }\n\t // Special case: Normalize will modify this to '.'\n\t if (p === '') {\n\t return p;\n\t }\n\t // Normalize the string first to remove any weirdness.\n\t p = path.normalize(p);\n\t // Get the last part of the string.\n\t var sections = p.split(path.sep);\n\t var lastPart = sections[sections.length - 1];\n\t // Special case: If it's empty, then we have a string like so: foo/\n\t // Meaning, 'foo' is guaranteed to be a directory.\n\t if (lastPart === '' && sections.length > 1) {\n\t return sections[sections.length - 2];\n\t }\n\t // Remove the extension, if need be.\n\t if (ext.length > 0) {\n\t var lastPartExt = lastPart.substr(lastPart.length - ext.length);\n\t if (lastPartExt === ext) {\n\t return lastPart.substr(0, lastPart.length - ext.length);\n\t }\n\t }\n\t return lastPart;\n\t };\n\t /**\n\t * Return the extension of the path, from the last '.' to end of string in the\n\t * last portion of the path. If there is no '.' in the last portion of the path\n\t * or the first character of it is '.', then it returns an empty string.\n\t * @example Usage example\n\t * path.extname('index.html')\n\t * // returns\n\t * '.html'\n\t *\n\t * path.extname('index.')\n\t * // returns\n\t * '.'\n\t *\n\t * path.extname('index')\n\t * // returns\n\t * ''\n\t * @param [String] p\n\t * @return [String]\n\t */\n\t path.extname = function (p) {\n\t p = path.normalize(p);\n\t var sections = p.split(path.sep);\n\t p = sections.pop();\n\t // Special case: foo/file.ext/ should return '.ext'\n\t if (p === '' && sections.length > 0) {\n\t p = sections.pop();\n\t }\n\t if (p === '..') {\n\t return '';\n\t }\n\t var i = p.lastIndexOf('.');\n\t if (i === -1 || i === 0) {\n\t return '';\n\t }\n\t return p.substr(i);\n\t };\n\t /**\n\t * Checks if the given path is an absolute path.\n\t *\n\t * Despite not being documented, this is a tested part of Node's path API.\n\t * @param [String] p\n\t * @return [Boolean] True if the path appears to be an absolute path.\n\t */\n\t path.isAbsolute = function (p) {\n\t return p.length > 0 && p.charAt(0) === path.sep;\n\t };\n\t /**\n\t * Unknown. Undocumented.\n\t */\n\t path._makeLong = function (p) {\n\t return p;\n\t };\n\t /**\n\t * Returns an object from a path string.\n\t */\n\t path.parse = function (p) {\n\t var allParts = posixSplitPath(p);\n\t return {\n\t root: allParts[0],\n\t dir: allParts[0] + allParts[1].slice(0, -1),\n\t base: allParts[2],\n\t ext: allParts[3],\n\t name: allParts[2].slice(0, allParts[2].length - allParts[3].length)\n\t };\n\t };\n\t path.format = function (pathObject) {\n\t if (pathObject === null || typeof pathObject !== 'object') {\n\t throw new TypeError(\"Parameter 'pathObject' must be an object, not \" + typeof pathObject);\n\t }\n\t var root = pathObject.root || '';\n\t if (typeof root !== 'string') {\n\t throw new TypeError(\"'pathObject.root' must be a string or undefined, not \" +\n\t typeof pathObject.root);\n\t }\n\t var dir = pathObject.dir ? pathObject.dir + path.sep : '';\n\t var base = pathObject.base || '';\n\t return dir + base;\n\t };\n\t path._removeDuplicateSeps = function (p) {\n\t p = p.replace(this._replaceRegex, this.sep);\n\t return p;\n\t };\n\t // The platform-specific file separator. BrowserFS uses `/`.\n\t path.sep = '/';\n\t path._replaceRegex = new RegExp(\"//+\", 'g');\n\t // The platform-specific path delimiter. BrowserFS uses `:`.\n\t path.delimiter = ':';\n\t path.posix = path;\n\t // XXX: Typing hack. We don't actually support win32.\n\t path.win32 = path;\n\t return path;\n\t}());\n\tvar _ = path;\n\tmodule.exports = path;\n\t\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))\n\n/***/ },\n/* 15 */\n/***/ function(module, exports, __webpack_require__) {\n\n\t// a passthrough stream.\n\t// basically just the most minimal sort of Transform stream.\n\t// Every written chunk gets output as-is.\n\t\n\t'use strict';\n\t\n\tmodule.exports = PassThrough;\n\t\n\tvar Transform = __webpack_require__(12);\n\t\n\t/**/\n\tvar util = __webpack_require__(5);\n\tutil.inherits = __webpack_require__(4);\n\t/**/\n\t\n\tutil.inherits(PassThrough, Transform);\n\t\n\tfunction PassThrough(options) {\n\t if (!(this instanceof PassThrough)) return new PassThrough(options);\n\t\n\t Transform.call(this, options);\n\t}\n\t\n\tPassThrough.prototype._transform = function (chunk, encoding, cb) {\n\t cb(null, chunk);\n\t};\n\n/***/ },\n/* 16 */\n/***/ function(module, exports, __webpack_require__) {\n\n\t/* WEBPACK VAR INJECTION */(function(process) {'use strict';\n\t\n\tmodule.exports = Readable;\n\t\n\t/**/\n\tvar processNextTick = __webpack_require__(11);\n\t/**/\n\t\n\t/**/\n\tvar isArray = __webpack_require__(22);\n\t/**/\n\t\n\t/**/\n\tvar Duplex;\n\t/**/\n\t\n\tReadable.ReadableState = ReadableState;\n\t\n\t/**/\n\tvar EE = __webpack_require__(6).EventEmitter;\n\t\n\tvar EElistenerCount = function (emitter, type) {\n\t return emitter.listeners(type).length;\n\t};\n\t/**/\n\t\n\t/**/\n\tvar Stream;\n\t(function () {\n\t try {\n\t Stream = __webpack_require__(9);\n\t } catch (_) {} finally {\n\t if (!Stream) Stream = __webpack_require__(6).EventEmitter;\n\t }\n\t})();\n\t/**/\n\t\n\tvar Buffer = __webpack_require__(1).Buffer;\n\t/**/\n\tvar bufferShim = __webpack_require__(10);\n\t/**/\n\t\n\t/**/\n\tvar util = __webpack_require__(5);\n\tutil.inherits = __webpack_require__(4);\n\t/**/\n\t\n\t/**/\n\tvar debugUtil = __webpack_require__(42);\n\tvar debug = void 0;\n\tif (debugUtil && debugUtil.debuglog) {\n\t debug = debugUtil.debuglog('stream');\n\t} else {\n\t debug = function () {};\n\t}\n\t/**/\n\t\n\tvar BufferList = __webpack_require__(35);\n\tvar StringDecoder;\n\t\n\tutil.inherits(Readable, Stream);\n\t\n\tfunction prependListener(emitter, event, fn) {\n\t // Sadly this is not cacheable as some libraries bundle their own\n\t // event emitter implementation with them.\n\t if (typeof emitter.prependListener === 'function') {\n\t return emitter.prependListener(event, fn);\n\t } else {\n\t // This is a hack to make sure that our error handler is attached before any\n\t // userland ones. NEVER DO THIS. This is here only because this code needs\n\t // to continue to work with older versions of Node.js that do not include\n\t // the prependListener() method. The goal is to eventually remove this hack.\n\t if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];\n\t }\n\t}\n\t\n\tfunction ReadableState(options, stream) {\n\t Duplex = Duplex || __webpack_require__(2);\n\t\n\t options = options || {};\n\t\n\t // object stream flag. Used to make read(n) ignore n and to\n\t // make all the buffer merging and length checks go away\n\t this.objectMode = !!options.objectMode;\n\t\n\t if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode;\n\t\n\t // the point at which it stops calling _read() to fill the buffer\n\t // Note: 0 is a valid value, means \"don't call _read preemptively ever\"\n\t var hwm = options.highWaterMark;\n\t var defaultHwm = this.objectMode ? 16 : 16 * 1024;\n\t this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm;\n\t\n\t // cast to ints.\n\t this.highWaterMark = ~~this.highWaterMark;\n\t\n\t // A linked list is used to store data chunks instead of an array because the\n\t // linked list can remove elements from the beginning faster than\n\t // array.shift()\n\t this.buffer = new BufferList();\n\t this.length = 0;\n\t this.pipes = null;\n\t this.pipesCount = 0;\n\t this.flowing = null;\n\t this.ended = false;\n\t this.endEmitted = false;\n\t this.reading = false;\n\t\n\t // a flag to be able to tell if the onwrite cb is called immediately,\n\t // or on a later tick. We set this to true at first, because any\n\t // actions that shouldn't happen until \"later\" should generally also\n\t // not happen before the first write call.\n\t this.sync = true;\n\t\n\t // whenever we return null, then we set a flag to say\n\t // that we're awaiting a 'readable' event emission.\n\t this.needReadable = false;\n\t this.emittedReadable = false;\n\t this.readableListening = false;\n\t this.resumeScheduled = false;\n\t\n\t // Crypto is kind of old and crusty. Historically, its default string\n\t // encoding is 'binary' so we have to make this configurable.\n\t // Everything else in the universe uses 'utf8', though.\n\t this.defaultEncoding = options.defaultEncoding || 'utf8';\n\t\n\t // when piping, we only care about 'readable' events that happen\n\t // after read()ing all the bytes and not getting any pushback.\n\t this.ranOut = false;\n\t\n\t // the number of writers that are awaiting a drain event in .pipe()s\n\t this.awaitDrain = 0;\n\t\n\t // if true, a maybeReadMore has been scheduled\n\t this.readingMore = false;\n\t\n\t this.decoder = null;\n\t this.encoding = null;\n\t if (options.encoding) {\n\t if (!StringDecoder) StringDecoder = __webpack_require__(17).StringDecoder;\n\t this.decoder = new StringDecoder(options.encoding);\n\t this.encoding = options.encoding;\n\t }\n\t}\n\t\n\tfunction Readable(options) {\n\t Duplex = Duplex || __webpack_require__(2);\n\t\n\t if (!(this instanceof Readable)) return new Readable(options);\n\t\n\t this._readableState = new ReadableState(options, this);\n\t\n\t // legacy\n\t this.readable = true;\n\t\n\t if (options && typeof options.read === 'function') this._read = options.read;\n\t\n\t Stream.call(this);\n\t}\n\t\n\t// Manually shove something into the read() buffer.\n\t// This returns true if the highWaterMark has not been hit yet,\n\t// similar to how Writable.write() returns true if you should\n\t// write() some more.\n\tReadable.prototype.push = function (chunk, encoding) {\n\t var state = this._readableState;\n\t\n\t if (!state.objectMode && typeof chunk === 'string') {\n\t encoding = encoding || state.defaultEncoding;\n\t if (encoding !== state.encoding) {\n\t chunk = bufferShim.from(chunk, encoding);\n\t encoding = '';\n\t }\n\t }\n\t\n\t return readableAddChunk(this, state, chunk, encoding, false);\n\t};\n\t\n\t// Unshift should *always* be something directly out of read()\n\tReadable.prototype.unshift = function (chunk) {\n\t var state = this._readableState;\n\t return readableAddChunk(this, state, chunk, '', true);\n\t};\n\t\n\tReadable.prototype.isPaused = function () {\n\t return this._readableState.flowing === false;\n\t};\n\t\n\tfunction readableAddChunk(stream, state, chunk, encoding, addToFront) {\n\t var er = chunkInvalid(state, chunk);\n\t if (er) {\n\t stream.emit('error', er);\n\t } else if (chunk === null) {\n\t state.reading = false;\n\t onEofChunk(stream, state);\n\t } else if (state.objectMode || chunk && chunk.length > 0) {\n\t if (state.ended && !addToFront) {\n\t var e = new Error('stream.push() after EOF');\n\t stream.emit('error', e);\n\t } else if (state.endEmitted && addToFront) {\n\t var _e = new Error('stream.unshift() after end event');\n\t stream.emit('error', _e);\n\t } else {\n\t var skipAdd;\n\t if (state.decoder && !addToFront && !encoding) {\n\t chunk = state.decoder.write(chunk);\n\t skipAdd = !state.objectMode && chunk.length === 0;\n\t }\n\t\n\t if (!addToFront) state.reading = false;\n\t\n\t // Don't add to the buffer if we've decoded to an empty string chunk and\n\t // we're not in object mode\n\t if (!skipAdd) {\n\t // if we want the data now, just emit it.\n\t if (state.flowing && state.length === 0 && !state.sync) {\n\t stream.emit('data', chunk);\n\t stream.read(0);\n\t } else {\n\t // update the buffer info.\n\t state.length += state.objectMode ? 1 : chunk.length;\n\t if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);\n\t\n\t if (state.needReadable) emitReadable(stream);\n\t }\n\t }\n\t\n\t maybeReadMore(stream, state);\n\t }\n\t } else if (!addToFront) {\n\t state.reading = false;\n\t }\n\t\n\t return needMoreData(state);\n\t}\n\t\n\t// if it's past the high water mark, we can push in some more.\n\t// Also, if we have no data yet, we can stand some\n\t// more bytes. This is to work around cases where hwm=0,\n\t// such as the repl. Also, if the push() triggered a\n\t// readable event, and the user called read(largeNumber) such that\n\t// needReadable was set, then we ought to push more, so that another\n\t// 'readable' event will be triggered.\n\tfunction needMoreData(state) {\n\t return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);\n\t}\n\t\n\t// backwards compatibility.\n\tReadable.prototype.setEncoding = function (enc) {\n\t if (!StringDecoder) StringDecoder = __webpack_require__(17).StringDecoder;\n\t this._readableState.decoder = new StringDecoder(enc);\n\t this._readableState.encoding = enc;\n\t return this;\n\t};\n\t\n\t// Don't raise the hwm > 8MB\n\tvar MAX_HWM = 0x800000;\n\tfunction computeNewHighWaterMark(n) {\n\t if (n >= MAX_HWM) {\n\t n = MAX_HWM;\n\t } else {\n\t // Get the next highest power of 2 to prevent increasing hwm excessively in\n\t // tiny amounts\n\t n--;\n\t n |= n >>> 1;\n\t n |= n >>> 2;\n\t n |= n >>> 4;\n\t n |= n >>> 8;\n\t n |= n >>> 16;\n\t n++;\n\t }\n\t return n;\n\t}\n\t\n\t// This function is designed to be inlinable, so please take care when making\n\t// changes to the function body.\n\tfunction howMuchToRead(n, state) {\n\t if (n <= 0 || state.length === 0 && state.ended) return 0;\n\t if (state.objectMode) return 1;\n\t if (n !== n) {\n\t // Only flow one buffer at a time\n\t if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;\n\t }\n\t // If we're asking for more than the current hwm, then raise the hwm.\n\t if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);\n\t if (n <= state.length) return n;\n\t // Don't have enough\n\t if (!state.ended) {\n\t state.needReadable = true;\n\t return 0;\n\t }\n\t return state.length;\n\t}\n\t\n\t// you can override either this method, or the async _read(n) below.\n\tReadable.prototype.read = function (n) {\n\t debug('read', n);\n\t n = parseInt(n, 10);\n\t var state = this._readableState;\n\t var nOrig = n;\n\t\n\t if (n !== 0) state.emittedReadable = false;\n\t\n\t // if we're doing read(0) to trigger a readable event, but we\n\t // already have a bunch of data in the buffer, then just trigger\n\t // the 'readable' event and move on.\n\t if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {\n\t debug('read: emitReadable', state.length, state.ended);\n\t if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);\n\t return null;\n\t }\n\t\n\t n = howMuchToRead(n, state);\n\t\n\t // if we've ended, and we're now clear, then finish it up.\n\t if (n === 0 && state.ended) {\n\t if (state.length === 0) endReadable(this);\n\t return null;\n\t }\n\t\n\t // All the actual chunk generation logic needs to be\n\t // *below* the call to _read. The reason is that in certain\n\t // synthetic stream cases, such as passthrough streams, _read\n\t // may be a completely synchronous operation which may change\n\t // the state of the read buffer, providing enough data when\n\t // before there was *not* enough.\n\t //\n\t // So, the steps are:\n\t // 1. Figure out what the state of things will be after we do\n\t // a read from the buffer.\n\t //\n\t // 2. If that resulting state will trigger a _read, then call _read.\n\t // Note that this may be asynchronous, or synchronous. Yes, it is\n\t // deeply ugly to write APIs this way, but that still doesn't mean\n\t // that the Readable class should behave improperly, as streams are\n\t // designed to be sync/async agnostic.\n\t // Take note if the _read call is sync or async (ie, if the read call\n\t // has returned yet), so that we know whether or not it's safe to emit\n\t // 'readable' etc.\n\t //\n\t // 3. Actually pull the requested chunks out of the buffer and return.\n\t\n\t // if we need a readable event, then we need to do some reading.\n\t var doRead = state.needReadable;\n\t debug('need readable', doRead);\n\t\n\t // if we currently have less than the highWaterMark, then also read some\n\t if (state.length === 0 || state.length - n < state.highWaterMark) {\n\t doRead = true;\n\t debug('length less than watermark', doRead);\n\t }\n\t\n\t // however, if we've ended, then there's no point, and if we're already\n\t // reading, then it's unnecessary.\n\t if (state.ended || state.reading) {\n\t doRead = false;\n\t debug('reading or ended', doRead);\n\t } else if (doRead) {\n\t debug('do read');\n\t state.reading = true;\n\t state.sync = true;\n\t // if the length is currently zero, then we *need* a readable event.\n\t if (state.length === 0) state.needReadable = true;\n\t // call internal read method\n\t this._read(state.highWaterMark);\n\t state.sync = false;\n\t // If _read pushed data synchronously, then `reading` will be false,\n\t // and we need to re-evaluate how much data we can return to the user.\n\t if (!state.reading) n = howMuchToRead(nOrig, state);\n\t }\n\t\n\t var ret;\n\t if (n > 0) ret = fromList(n, state);else ret = null;\n\t\n\t if (ret === null) {\n\t state.needReadable = true;\n\t n = 0;\n\t } else {\n\t state.length -= n;\n\t }\n\t\n\t if (state.length === 0) {\n\t // If we have nothing in the buffer, then we want to know\n\t // as soon as we *do* get something into the buffer.\n\t if (!state.ended) state.needReadable = true;\n\t\n\t // If we tried to read() past the EOF, then emit end on the next tick.\n\t if (nOrig !== n && state.ended) endReadable(this);\n\t }\n\t\n\t if (ret !== null) this.emit('data', ret);\n\t\n\t return ret;\n\t};\n\t\n\tfunction chunkInvalid(state, chunk) {\n\t var er = null;\n\t if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) {\n\t er = new TypeError('Invalid non-string/buffer chunk');\n\t }\n\t return er;\n\t}\n\t\n\tfunction onEofChunk(stream, state) {\n\t if (state.ended) return;\n\t if (state.decoder) {\n\t var chunk = state.decoder.end();\n\t if (chunk && chunk.length) {\n\t state.buffer.push(chunk);\n\t state.length += state.objectMode ? 1 : chunk.length;\n\t }\n\t }\n\t state.ended = true;\n\t\n\t // emit 'readable' now to make sure it gets picked up.\n\t emitReadable(stream);\n\t}\n\t\n\t// Don't emit readable right away in sync mode, because this can trigger\n\t// another read() call => stack overflow. This way, it might trigger\n\t// a nextTick recursion warning, but that's not so bad.\n\tfunction emitReadable(stream) {\n\t var state = stream._readableState;\n\t state.needReadable = false;\n\t if (!state.emittedReadable) {\n\t debug('emitReadable', state.flowing);\n\t state.emittedReadable = true;\n\t if (state.sync) processNextTick(emitReadable_, stream);else emitReadable_(stream);\n\t }\n\t}\n\t\n\tfunction emitReadable_(stream) {\n\t debug('emit readable');\n\t stream.emit('readable');\n\t flow(stream);\n\t}\n\t\n\t// at this point, the user has presumably seen the 'readable' event,\n\t// and called read() to consume some data. that may have triggered\n\t// in turn another _read(n) call, in which case reading = true if\n\t// it's in progress.\n\t// However, if we're not ended, or reading, and the length < hwm,\n\t// then go ahead and try to read some more preemptively.\n\tfunction maybeReadMore(stream, state) {\n\t if (!state.readingMore) {\n\t state.readingMore = true;\n\t processNextTick(maybeReadMore_, stream, state);\n\t }\n\t}\n\t\n\tfunction maybeReadMore_(stream, state) {\n\t var len = state.length;\n\t while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {\n\t debug('maybeReadMore read 0');\n\t stream.read(0);\n\t if (len === state.length)\n\t // didn't get any data, stop spinning.\n\t break;else len = state.length;\n\t }\n\t state.readingMore = false;\n\t}\n\t\n\t// abstract method. to be overridden in specific implementation classes.\n\t// call cb(er, data) where data is <= n in length.\n\t// for virtual (non-string, non-buffer) streams, \"length\" is somewhat\n\t// arbitrary, and perhaps not very meaningful.\n\tReadable.prototype._read = function (n) {\n\t this.emit('error', new Error('_read() is not implemented'));\n\t};\n\t\n\tReadable.prototype.pipe = function (dest, pipeOpts) {\n\t var src = this;\n\t var state = this._readableState;\n\t\n\t switch (state.pipesCount) {\n\t case 0:\n\t state.pipes = dest;\n\t break;\n\t case 1:\n\t state.pipes = [state.pipes, dest];\n\t break;\n\t default:\n\t state.pipes.push(dest);\n\t break;\n\t }\n\t state.pipesCount += 1;\n\t debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);\n\t\n\t var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;\n\t\n\t var endFn = doEnd ? onend : cleanup;\n\t if (state.endEmitted) processNextTick(endFn);else src.once('end', endFn);\n\t\n\t dest.on('unpipe', onunpipe);\n\t function onunpipe(readable) {\n\t debug('onunpipe');\n\t if (readable === src) {\n\t cleanup();\n\t }\n\t }\n\t\n\t function onend() {\n\t debug('onend');\n\t dest.end();\n\t }\n\t\n\t // when the dest drains, it reduces the awaitDrain counter\n\t // on the source. This would be more elegant with a .once()\n\t // handler in flow(), but adding and removing repeatedly is\n\t // too slow.\n\t var ondrain = pipeOnDrain(src);\n\t dest.on('drain', ondrain);\n\t\n\t var cleanedUp = false;\n\t function cleanup() {\n\t debug('cleanup');\n\t // cleanup event handlers once the pipe is broken\n\t dest.removeListener('close', onclose);\n\t dest.removeListener('finish', onfinish);\n\t dest.removeListener('drain', ondrain);\n\t dest.removeListener('error', onerror);\n\t dest.removeListener('unpipe', onunpipe);\n\t src.removeListener('end', onend);\n\t src.removeListener('end', cleanup);\n\t src.removeListener('data', ondata);\n\t\n\t cleanedUp = true;\n\t\n\t // if the reader is waiting for a drain event from this\n\t // specific writer, then it would cause it to never start\n\t // flowing again.\n\t // So, if this is awaiting a drain, then we just call it now.\n\t // If we don't know, then assume that we are waiting for one.\n\t if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();\n\t }\n\t\n\t // If the user pushes more data while we're writing to dest then we'll end up\n\t // in ondata again. However, we only want to increase awaitDrain once because\n\t // dest will only emit one 'drain' event for the multiple writes.\n\t // => Introduce a guard on increasing awaitDrain.\n\t var increasedAwaitDrain = false;\n\t src.on('data', ondata);\n\t function ondata(chunk) {\n\t debug('ondata');\n\t increasedAwaitDrain = false;\n\t var ret = dest.write(chunk);\n\t if (false === ret && !increasedAwaitDrain) {\n\t // If the user unpiped during `dest.write()`, it is possible\n\t // to get stuck in a permanently paused state if that write\n\t // also returned false.\n\t // => Check whether `dest` is still a piping destination.\n\t if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {\n\t debug('false write response, pause', src._readableState.awaitDrain);\n\t src._readableState.awaitDrain++;\n\t increasedAwaitDrain = true;\n\t }\n\t src.pause();\n\t }\n\t }\n\t\n\t // if the dest has an error, then stop piping into it.\n\t // however, don't suppress the throwing behavior for this.\n\t function onerror(er) {\n\t debug('onerror', er);\n\t unpipe();\n\t dest.removeListener('error', onerror);\n\t if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);\n\t }\n\t\n\t // Make sure our error handler is attached before userland ones.\n\t prependListener(dest, 'error', onerror);\n\t\n\t // Both close and finish should trigger unpipe, but only once.\n\t function onclose() {\n\t dest.removeListener('finish', onfinish);\n\t unpipe();\n\t }\n\t dest.once('close', onclose);\n\t function onfinish() {\n\t debug('onfinish');\n\t dest.removeListener('close', onclose);\n\t unpipe();\n\t }\n\t dest.once('finish', onfinish);\n\t\n\t function unpipe() {\n\t debug('unpipe');\n\t src.unpipe(dest);\n\t }\n\t\n\t // tell the dest that it's being piped to\n\t dest.emit('pipe', src);\n\t\n\t // start the flow if it hasn't been started already.\n\t if (!state.flowing) {\n\t debug('pipe resume');\n\t src.resume();\n\t }\n\t\n\t return dest;\n\t};\n\t\n\tfunction pipeOnDrain(src) {\n\t return function () {\n\t var state = src._readableState;\n\t debug('pipeOnDrain', state.awaitDrain);\n\t if (state.awaitDrain) state.awaitDrain--;\n\t if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {\n\t state.flowing = true;\n\t flow(src);\n\t }\n\t };\n\t}\n\t\n\tReadable.prototype.unpipe = function (dest) {\n\t var state = this._readableState;\n\t\n\t // if we're not piping anywhere, then do nothing.\n\t if (state.pipesCount === 0) return this;\n\t\n\t // just one destination. most common case.\n\t if (state.pipesCount === 1) {\n\t // passed in one, but it's not the right one.\n\t if (dest && dest !== state.pipes) return this;\n\t\n\t if (!dest) dest = state.pipes;\n\t\n\t // got a match.\n\t state.pipes = null;\n\t state.pipesCount = 0;\n\t state.flowing = false;\n\t if (dest) dest.emit('unpipe', this);\n\t return this;\n\t }\n\t\n\t // slow case. multiple pipe destinations.\n\t\n\t if (!dest) {\n\t // remove all.\n\t var dests = state.pipes;\n\t var len = state.pipesCount;\n\t state.pipes = null;\n\t state.pipesCount = 0;\n\t state.flowing = false;\n\t\n\t for (var i = 0; i < len; i++) {\n\t dests[i].emit('unpipe', this);\n\t }return this;\n\t }\n\t\n\t // try to find the right one.\n\t var index = indexOf(state.pipes, dest);\n\t if (index === -1) return this;\n\t\n\t state.pipes.splice(index, 1);\n\t state.pipesCount -= 1;\n\t if (state.pipesCount === 1) state.pipes = state.pipes[0];\n\t\n\t dest.emit('unpipe', this);\n\t\n\t return this;\n\t};\n\t\n\t// set up data events if they are asked for\n\t// Ensure readable listeners eventually get something\n\tReadable.prototype.on = function (ev, fn) {\n\t var res = Stream.prototype.on.call(this, ev, fn);\n\t\n\t if (ev === 'data') {\n\t // Start flowing on next tick if stream isn't explicitly paused\n\t if (this._readableState.flowing !== false) this.resume();\n\t } else if (ev === 'readable') {\n\t var state = this._readableState;\n\t if (!state.endEmitted && !state.readableListening) {\n\t state.readableListening = state.needReadable = true;\n\t state.emittedReadable = false;\n\t if (!state.reading) {\n\t processNextTick(nReadingNextTick, this);\n\t } else if (state.length) {\n\t emitReadable(this, state);\n\t }\n\t }\n\t }\n\t\n\t return res;\n\t};\n\tReadable.prototype.addListener = Readable.prototype.on;\n\t\n\tfunction nReadingNextTick(self) {\n\t debug('readable nexttick read 0');\n\t self.read(0);\n\t}\n\t\n\t// pause() and resume() are remnants of the legacy readable stream API\n\t// If the user uses them, then switch into old mode.\n\tReadable.prototype.resume = function () {\n\t var state = this._readableState;\n\t if (!state.flowing) {\n\t debug('resume');\n\t state.flowing = true;\n\t resume(this, state);\n\t }\n\t return this;\n\t};\n\t\n\tfunction resume(stream, state) {\n\t if (!state.resumeScheduled) {\n\t state.resumeScheduled = true;\n\t processNextTick(resume_, stream, state);\n\t }\n\t}\n\t\n\tfunction resume_(stream, state) {\n\t if (!state.reading) {\n\t debug('resume read 0');\n\t stream.read(0);\n\t }\n\t\n\t state.resumeScheduled = false;\n\t state.awaitDrain = 0;\n\t stream.emit('resume');\n\t flow(stream);\n\t if (state.flowing && !state.reading) stream.read(0);\n\t}\n\t\n\tReadable.prototype.pause = function () {\n\t debug('call pause flowing=%j', this._readableState.flowing);\n\t if (false !== this._readableState.flowing) {\n\t debug('pause');\n\t this._readableState.flowing = false;\n\t this.emit('pause');\n\t }\n\t return this;\n\t};\n\t\n\tfunction flow(stream) {\n\t var state = stream._readableState;\n\t debug('flow', state.flowing);\n\t while (state.flowing && stream.read() !== null) {}\n\t}\n\t\n\t// wrap an old-style stream as the async data source.\n\t// This is *not* part of the readable stream interface.\n\t// It is an ugly unfortunate mess of history.\n\tReadable.prototype.wrap = function (stream) {\n\t var state = this._readableState;\n\t var paused = false;\n\t\n\t var self = this;\n\t stream.on('end', function () {\n\t debug('wrapped end');\n\t if (state.decoder && !state.ended) {\n\t var chunk = state.decoder.end();\n\t if (chunk && chunk.length) self.push(chunk);\n\t }\n\t\n\t self.push(null);\n\t });\n\t\n\t stream.on('data', function (chunk) {\n\t debug('wrapped data');\n\t if (state.decoder) chunk = state.decoder.write(chunk);\n\t\n\t // don't skip over falsy values in objectMode\n\t if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;\n\t\n\t var ret = self.push(chunk);\n\t if (!ret) {\n\t paused = true;\n\t stream.pause();\n\t }\n\t });\n\t\n\t // proxy all the other methods.\n\t // important when wrapping filters and duplexes.\n\t for (var i in stream) {\n\t if (this[i] === undefined && typeof stream[i] === 'function') {\n\t this[i] = function (method) {\n\t return function () {\n\t return stream[method].apply(stream, arguments);\n\t };\n\t }(i);\n\t }\n\t }\n\t\n\t // proxy certain important events.\n\t var events = ['error', 'close', 'destroy', 'pause', 'resume'];\n\t forEach(events, function (ev) {\n\t stream.on(ev, self.emit.bind(self, ev));\n\t });\n\t\n\t // when we try to consume some more bytes, simply unpause the\n\t // underlying stream.\n\t self._read = function (n) {\n\t debug('wrapped _read', n);\n\t if (paused) {\n\t paused = false;\n\t stream.resume();\n\t }\n\t };\n\t\n\t return self;\n\t};\n\t\n\t// exposed for testing purposes only.\n\tReadable._fromList = fromList;\n\t\n\t// Pluck off n bytes from an array of buffers.\n\t// Length is the combined lengths of all the buffers in the list.\n\t// This function is designed to be inlinable, so please take care when making\n\t// changes to the function body.\n\tfunction fromList(n, state) {\n\t // nothing buffered\n\t if (state.length === 0) return null;\n\t\n\t var ret;\n\t if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {\n\t // read it all, truncate the list\n\t if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length);\n\t state.buffer.clear();\n\t } else {\n\t // read part of list\n\t ret = fromListPartial(n, state.buffer, state.decoder);\n\t }\n\t\n\t return ret;\n\t}\n\t\n\t// Extracts only enough buffered data to satisfy the amount requested.\n\t// This function is designed to be inlinable, so please take care when making\n\t// changes to the function body.\n\tfunction fromListPartial(n, list, hasStrings) {\n\t var ret;\n\t if (n < list.head.data.length) {\n\t // slice is the same for buffers and strings\n\t ret = list.head.data.slice(0, n);\n\t list.head.data = list.head.data.slice(n);\n\t } else if (n === list.head.data.length) {\n\t // first chunk is a perfect match\n\t ret = list.shift();\n\t } else {\n\t // result spans more than one buffer\n\t ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);\n\t }\n\t return ret;\n\t}\n\t\n\t// Copies a specified amount of characters from the list of buffered data\n\t// chunks.\n\t// This function is designed to be inlinable, so please take care when making\n\t// changes to the function body.\n\tfunction copyFromBufferString(n, list) {\n\t var p = list.head;\n\t var c = 1;\n\t var ret = p.data;\n\t n -= ret.length;\n\t while (p = p.next) {\n\t var str = p.data;\n\t var nb = n > str.length ? str.length : n;\n\t if (nb === str.length) ret += str;else ret += str.slice(0, n);\n\t n -= nb;\n\t if (n === 0) {\n\t if (nb === str.length) {\n\t ++c;\n\t if (p.next) list.head = p.next;else list.head = list.tail = null;\n\t } else {\n\t list.head = p;\n\t p.data = str.slice(nb);\n\t }\n\t break;\n\t }\n\t ++c;\n\t }\n\t list.length -= c;\n\t return ret;\n\t}\n\t\n\t// Copies a specified amount of bytes from the list of buffered data chunks.\n\t// This function is designed to be inlinable, so please take care when making\n\t// changes to the function body.\n\tfunction copyFromBuffer(n, list) {\n\t var ret = bufferShim.allocUnsafe(n);\n\t var p = list.head;\n\t var c = 1;\n\t p.data.copy(ret);\n\t n -= p.data.length;\n\t while (p = p.next) {\n\t var buf = p.data;\n\t var nb = n > buf.length ? buf.length : n;\n\t buf.copy(ret, ret.length - n, 0, nb);\n\t n -= nb;\n\t if (n === 0) {\n\t if (nb === buf.length) {\n\t ++c;\n\t if (p.next) list.head = p.next;else list.head = list.tail = null;\n\t } else {\n\t list.head = p;\n\t p.data = buf.slice(nb);\n\t }\n\t break;\n\t }\n\t ++c;\n\t }\n\t list.length -= c;\n\t return ret;\n\t}\n\t\n\tfunction endReadable(stream) {\n\t var state = stream._readableState;\n\t\n\t // If we get here before consuming all the bytes, then that is a\n\t // bug in node. Should never happen.\n\t if (state.length > 0) throw new Error('\"endReadable()\" called on non-empty stream');\n\t\n\t if (!state.endEmitted) {\n\t state.ended = true;\n\t processNextTick(endReadableNT, state, stream);\n\t }\n\t}\n\t\n\tfunction endReadableNT(state, stream) {\n\t // Check that we didn't get one last unshift.\n\t if (!state.endEmitted && state.length === 0) {\n\t state.endEmitted = true;\n\t stream.readable = false;\n\t stream.emit('end');\n\t }\n\t}\n\t\n\tfunction forEach(xs, f) {\n\t for (var i = 0, l = xs.length; i < l; i++) {\n\t f(xs[i], i);\n\t }\n\t}\n\t\n\tfunction indexOf(xs, x) {\n\t for (var i = 0, l = xs.length; i < l; i++) {\n\t if (xs[i] === x) return i;\n\t }\n\t return -1;\n\t}\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))\n\n/***/ },\n/* 17 */\n/***/ function(module, exports, __webpack_require__) {\n\n\t// Copyright Joyent, Inc. and other Node contributors.\n\t//\n\t// Permission is hereby granted, free of charge, to any person obtaining a\n\t// copy of this software and associated documentation files (the\n\t// \"Software\"), to deal in the Software without restriction, including\n\t// without limitation the rights to use, copy, modify, merge, publish,\n\t// distribute, sublicense, and/or sell copies of the Software, and to permit\n\t// persons to whom the Software is furnished to do so, subject to the\n\t// following conditions:\n\t//\n\t// The above copyright notice and this permission notice shall be included\n\t// in all copies or substantial portions of the Software.\n\t//\n\t// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n\t// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n\t// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n\t// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n\t// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n\t// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n\t// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\t\n\tvar Buffer = __webpack_require__(1).Buffer;\n\t\n\tvar isBufferEncoding = Buffer.isEncoding\n\t || function(encoding) {\n\t switch (encoding && encoding.toLowerCase()) {\n\t 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\t default: return false;\n\t }\n\t }\n\t\n\t\n\tfunction assertEncoding(encoding) {\n\t if (encoding && !isBufferEncoding(encoding)) {\n\t throw new Error('Unknown encoding: ' + encoding);\n\t }\n\t}\n\t\n\t// StringDecoder provides an interface for efficiently splitting a series of\n\t// buffers into a series of JS strings without breaking apart multi-byte\n\t// characters. CESU-8 is handled as part of the UTF-8 encoding.\n\t//\n\t// @TODO Handling all encodings inside a single object makes it very difficult\n\t// to reason about this code, so it should be split up in the future.\n\t// @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code\n\t// points as used by CESU-8.\n\tvar StringDecoder = exports.StringDecoder = function(encoding) {\n\t this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, '');\n\t assertEncoding(encoding);\n\t switch (this.encoding) {\n\t case 'utf8':\n\t // CESU-8 represents each of Surrogate Pair by 3-bytes\n\t this.surrogateSize = 3;\n\t break;\n\t case 'ucs2':\n\t case 'utf16le':\n\t // UTF-16 represents each of Surrogate Pair by 2-bytes\n\t this.surrogateSize = 2;\n\t this.detectIncompleteChar = utf16DetectIncompleteChar;\n\t break;\n\t case 'base64':\n\t // Base-64 stores 3 bytes in 4 chars, and pads the remainder.\n\t this.surrogateSize = 3;\n\t this.detectIncompleteChar = base64DetectIncompleteChar;\n\t break;\n\t default:\n\t this.write = passThroughWrite;\n\t return;\n\t }\n\t\n\t // Enough space to store all bytes of a single character. UTF-8 needs 4\n\t // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate).\n\t this.charBuffer = new Buffer(6);\n\t // Number of bytes received for the current incomplete multi-byte character.\n\t this.charReceived = 0;\n\t // Number of bytes expected for the current incomplete multi-byte character.\n\t this.charLength = 0;\n\t};\n\t\n\t\n\t// write decodes the given buffer and returns it as JS string that is\n\t// guaranteed to not contain any partial multi-byte characters. Any partial\n\t// character found at the end of the buffer is buffered up, and will be\n\t// returned when calling write again with the remaining bytes.\n\t//\n\t// Note: Converting a Buffer containing an orphan surrogate to a String\n\t// currently works, but converting a String to a Buffer (via `new Buffer`, or\n\t// Buffer#write) will replace incomplete surrogates with the unicode\n\t// replacement character. See https://codereview.chromium.org/121173009/ .\n\tStringDecoder.prototype.write = function(buffer) {\n\t var charStr = '';\n\t // if our last write ended with an incomplete multibyte character\n\t while (this.charLength) {\n\t // determine how many remaining bytes this buffer has to offer for this char\n\t var available = (buffer.length >= this.charLength - this.charReceived) ?\n\t this.charLength - this.charReceived :\n\t buffer.length;\n\t\n\t // add the new bytes to the char buffer\n\t buffer.copy(this.charBuffer, this.charReceived, 0, available);\n\t this.charReceived += available;\n\t\n\t if (this.charReceived < this.charLength) {\n\t // still not enough chars in this buffer? wait for more ...\n\t return '';\n\t }\n\t\n\t // remove bytes belonging to the current character from the buffer\n\t buffer = buffer.slice(available, buffer.length);\n\t\n\t // get the character that was split\n\t charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding);\n\t\n\t // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character\n\t var charCode = charStr.charCodeAt(charStr.length - 1);\n\t if (charCode >= 0xD800 && charCode <= 0xDBFF) {\n\t this.charLength += this.surrogateSize;\n\t charStr = '';\n\t continue;\n\t }\n\t this.charReceived = this.charLength = 0;\n\t\n\t // if there are no more bytes in this buffer, just emit our char\n\t if (buffer.length === 0) {\n\t return charStr;\n\t }\n\t break;\n\t }\n\t\n\t // determine and set charLength / charReceived\n\t this.detectIncompleteChar(buffer);\n\t\n\t var end = buffer.length;\n\t if (this.charLength) {\n\t // buffer the incomplete character bytes we got\n\t buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end);\n\t end -= this.charReceived;\n\t }\n\t\n\t charStr += buffer.toString(this.encoding, 0, end);\n\t\n\t var end = charStr.length - 1;\n\t var charCode = charStr.charCodeAt(end);\n\t // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character\n\t if (charCode >= 0xD800 && charCode <= 0xDBFF) {\n\t var size = this.surrogateSize;\n\t this.charLength += size;\n\t this.charReceived += size;\n\t this.charBuffer.copy(this.charBuffer, size, 0, size);\n\t buffer.copy(this.charBuffer, 0, 0, size);\n\t return charStr.substring(0, end);\n\t }\n\t\n\t // or just emit the charStr\n\t return charStr;\n\t};\n\t\n\t// detectIncompleteChar determines if there is an incomplete UTF-8 character at\n\t// the end of the given buffer. If so, it sets this.charLength to the byte\n\t// length that character, and sets this.charReceived to the number of bytes\n\t// that are available for this character.\n\tStringDecoder.prototype.detectIncompleteChar = function(buffer) {\n\t // determine how many bytes we have to check at the end of this buffer\n\t var i = (buffer.length >= 3) ? 3 : buffer.length;\n\t\n\t // Figure out if one of the last i bytes of our buffer announces an\n\t // incomplete char.\n\t for (; i > 0; i--) {\n\t var c = buffer[buffer.length - i];\n\t\n\t // See http://en.wikipedia.org/wiki/UTF-8#Description\n\t\n\t // 110XXXXX\n\t if (i == 1 && c >> 5 == 0x06) {\n\t this.charLength = 2;\n\t break;\n\t }\n\t\n\t // 1110XXXX\n\t if (i <= 2 && c >> 4 == 0x0E) {\n\t this.charLength = 3;\n\t break;\n\t }\n\t\n\t // 11110XXX\n\t if (i <= 3 && c >> 3 == 0x1E) {\n\t this.charLength = 4;\n\t break;\n\t }\n\t }\n\t this.charReceived = i;\n\t};\n\t\n\tStringDecoder.prototype.end = function(buffer) {\n\t var res = '';\n\t if (buffer && buffer.length)\n\t res = this.write(buffer);\n\t\n\t if (this.charReceived) {\n\t var cr = this.charReceived;\n\t var buf = this.charBuffer;\n\t var enc = this.encoding;\n\t res += buf.slice(0, cr).toString(enc);\n\t }\n\t\n\t return res;\n\t};\n\t\n\tfunction passThroughWrite(buffer) {\n\t return buffer.toString(this.encoding);\n\t}\n\t\n\tfunction utf16DetectIncompleteChar(buffer) {\n\t this.charReceived = buffer.length % 2;\n\t this.charLength = this.charReceived ? 2 : 0;\n\t}\n\t\n\tfunction base64DetectIncompleteChar(buffer) {\n\t this.charReceived = buffer.length % 3;\n\t this.charLength = this.charReceived ? 3 : 0;\n\t}\n\n\n/***/ },\n/* 18 */\n/***/ function(module, exports) {\n\n\t'use strict'\n\t\n\texports.byteLength = byteLength\n\texports.toByteArray = toByteArray\n\texports.fromByteArray = fromByteArray\n\t\n\tvar lookup = []\n\tvar revLookup = []\n\tvar Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array\n\t\n\tvar code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'\n\tfor (var i = 0, len = code.length; i < len; ++i) {\n\t lookup[i] = code[i]\n\t revLookup[code.charCodeAt(i)] = i\n\t}\n\t\n\trevLookup['-'.charCodeAt(0)] = 62\n\trevLookup['_'.charCodeAt(0)] = 63\n\t\n\tfunction placeHoldersCount (b64) {\n\t var len = b64.length\n\t if (len % 4 > 0) {\n\t throw new Error('Invalid string. Length must be a multiple of 4')\n\t }\n\t\n\t // the number of equal signs (place holders)\n\t // if there are two placeholders, than the two characters before it\n\t // represent one byte\n\t // if there is only one, then the three characters before it represent 2 bytes\n\t // this is just a cheap hack to not do indexOf twice\n\t return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0\n\t}\n\t\n\tfunction byteLength (b64) {\n\t // base64 is 4/3 + up to two characters of the original data\n\t return b64.length * 3 / 4 - placeHoldersCount(b64)\n\t}\n\t\n\tfunction toByteArray (b64) {\n\t var i, j, l, tmp, placeHolders, arr\n\t var len = b64.length\n\t placeHolders = placeHoldersCount(b64)\n\t\n\t arr = new Arr(len * 3 / 4 - placeHolders)\n\t\n\t // if there are placeholders, only get up to the last complete 4 chars\n\t l = placeHolders > 0 ? len - 4 : len\n\t\n\t var L = 0\n\t\n\t for (i = 0, j = 0; i < l; i += 4, j += 3) {\n\t tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]\n\t arr[L++] = (tmp >> 16) & 0xFF\n\t arr[L++] = (tmp >> 8) & 0xFF\n\t arr[L++] = tmp & 0xFF\n\t }\n\t\n\t if (placeHolders === 2) {\n\t tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4)\n\t arr[L++] = tmp & 0xFF\n\t } else if (placeHolders === 1) {\n\t tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2)\n\t arr[L++] = (tmp >> 8) & 0xFF\n\t arr[L++] = tmp & 0xFF\n\t }\n\t\n\t return arr\n\t}\n\t\n\tfunction tripletToBase64 (num) {\n\t return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]\n\t}\n\t\n\tfunction encodeChunk (uint8, start, end) {\n\t var tmp\n\t var output = []\n\t for (var i = start; i < end; i += 3) {\n\t tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])\n\t output.push(tripletToBase64(tmp))\n\t }\n\t return output.join('')\n\t}\n\t\n\tfunction fromByteArray (uint8) {\n\t var tmp\n\t var len = uint8.length\n\t var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes\n\t var output = ''\n\t var parts = []\n\t var maxChunkLength = 16383 // must be multiple of 3\n\t\n\t // go through the array every three bytes, we'll deal with trailing stuff later\n\t for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {\n\t parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))\n\t }\n\t\n\t // pad the end with zeros, but make sure to not forget the extra bytes\n\t if (extraBytes === 1) {\n\t tmp = uint8[len - 1]\n\t output += lookup[tmp >> 2]\n\t output += lookup[(tmp << 4) & 0x3F]\n\t output += '=='\n\t } else if (extraBytes === 2) {\n\t tmp = (uint8[len - 2] << 8) + (uint8[len - 1])\n\t output += lookup[tmp >> 10]\n\t output += lookup[(tmp >> 4) & 0x3F]\n\t output += lookup[(tmp << 2) & 0x3F]\n\t output += '='\n\t }\n\t\n\t parts.push(output)\n\t\n\t return parts.join('')\n\t}\n\n\n/***/ },\n/* 19 */\n/***/ function(module, exports, __webpack_require__) {\n\n\t/* WEBPACK VAR INJECTION */(function(__dirname) {\"use strict\";\n\tvar __extends = (this && this.__extends) || function (d, b) {\n\t for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];\n\t function __() { this.constructor = d; }\n\t d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n\t};\n\tvar events = __webpack_require__(6);\n\t// Path depends on process. Avoid a circular reference by dynamically including path when we need it.\n\tvar path = null;\n\tvar Item = (function () {\n\t function Item(fun, array) {\n\t this.fun = fun;\n\t this.array = array;\n\t }\n\t Item.prototype.run = function () {\n\t this.fun.apply(null, this.array);\n\t };\n\t return Item;\n\t}());\n\t/**\n\t * Contains a queue of Items for process.nextTick.\n\t * Inspired by node-process: https://github.com/defunctzombie/node-process\n\t */\n\tvar NextTickQueue = (function () {\n\t function NextTickQueue() {\n\t this._queue = [];\n\t this._draining = false;\n\t // Used/assigned by the drainQueue function.\n\t this._currentQueue = null;\n\t this._queueIndex = -1;\n\t }\n\t NextTickQueue.prototype.push = function (item) {\n\t var _this = this;\n\t if (this._queue.push(item) === 1 && !this._draining) {\n\t setTimeout(function () { return _this._drainQueue(); }, 0);\n\t }\n\t };\n\t NextTickQueue.prototype._cleanUpNextTick = function () {\n\t this._draining = false;\n\t if (this._currentQueue && this._currentQueue.length) {\n\t this._queue = this._currentQueue.concat(this._queue);\n\t }\n\t else {\n\t this._queueIndex = -1;\n\t }\n\t if (this._queue.length) {\n\t this._drainQueue();\n\t }\n\t };\n\t NextTickQueue.prototype._drainQueue = function () {\n\t var _this = this;\n\t if (this._draining) {\n\t return;\n\t }\n\t // If an Item throws an unhandled exception, this function will clean things up.\n\t var timeout = setTimeout(function () { return _this._cleanUpNextTick(); });\n\t this._draining = true;\n\t var len = this._queue.length;\n\t while (len) {\n\t this._currentQueue = this._queue;\n\t this._queue = [];\n\t while (++this._queueIndex < len) {\n\t if (this._currentQueue) {\n\t this._currentQueue[this._queueIndex].run();\n\t }\n\t }\n\t this._queueIndex = -1;\n\t len = this._queue.length;\n\t }\n\t this._currentQueue = null;\n\t this._draining = false;\n\t clearTimeout(timeout);\n\t };\n\t return NextTickQueue;\n\t}());\n\t/**\n\t * Partial implementation of Node's `process` module.\n\t * We implement the portions that are relevant for the filesystem.\n\t * @see http://nodejs.org/api/process.html\n\t * @class\n\t */\n\tvar Process = (function (_super) {\n\t __extends(Process, _super);\n\t function Process() {\n\t _super.apply(this, arguments);\n\t this.startTime = Date.now();\n\t this._cwd = '/';\n\t /**\n\t * Returns what platform you are running on.\n\t * @return [String]\n\t */\n\t this.platform = 'browser';\n\t this.argv = [];\n\t this.execArgv = [];\n\t this.stdout = null;\n\t this.stderr = null;\n\t this.stdin = null;\n\t this.domain = null;\n\t this._queue = new NextTickQueue();\n\t this.execPath = __dirname;\n\t this.env = {};\n\t this.exitCode = 0;\n\t this._gid = 1;\n\t this._uid = 1;\n\t this.version = 'v5.0';\n\t this.versions = {\n\t http_parser: '0.0',\n\t node: '5.0',\n\t v8: '0.0',\n\t uv: '0.0',\n\t zlib: '0.0',\n\t ares: '0.0',\n\t icu: '0.0',\n\t modules: '0',\n\t openssl: '0.0'\n\t };\n\t this.config = {\n\t target_defaults: { cflags: [],\n\t default_configuration: 'Release',\n\t defines: [],\n\t include_dirs: [],\n\t libraries: [] },\n\t variables: { clang: 0,\n\t host_arch: 'x32',\n\t node_install_npm: false,\n\t node_install_waf: false,\n\t node_prefix: '',\n\t node_shared_cares: false,\n\t node_shared_http_parser: false,\n\t node_shared_libuv: false,\n\t node_shared_zlib: false,\n\t node_shared_v8: false,\n\t node_use_dtrace: false,\n\t node_use_etw: false,\n\t node_use_openssl: false,\n\t node_shared_openssl: false,\n\t strict_aliasing: false,\n\t target_arch: 'x32',\n\t v8_use_snapshot: false,\n\t v8_no_strict_aliasing: 0,\n\t visibility: '' } };\n\t this.pid = (Math.random() * 1000) | 0;\n\t this.title = 'node';\n\t this.arch = 'x32';\n\t this._mask = 18;\n\t // Undefined in main thread. Worker-only.\n\t this.connected = undefined;\n\t }\n\t /**\n\t * Changes the current working directory.\n\t *\n\t * **Note**: BrowserFS does not validate that the directory actually exists.\n\t *\n\t * @example Usage example\n\t * console.log('Starting directory: ' + process.cwd());\n\t * process.chdir('/tmp');\n\t * console.log('New directory: ' + process.cwd());\n\t * @param [String] dir The directory to change to.\n\t */\n\t Process.prototype.chdir = function (dir) {\n\t // XXX: Circular dependency hack.\n\t if (path === null) {\n\t path = __webpack_require__(14);\n\t }\n\t this._cwd = path.resolve(dir);\n\t };\n\t /**\n\t * Returns the current working directory.\n\t * @example Usage example\n\t * console.log('Current directory: ' + process.cwd());\n\t * @return [String] The current working directory.\n\t */\n\t Process.prototype.cwd = function () {\n\t return this._cwd;\n\t };\n\t /**\n\t * Number of seconds BrowserFS has been running.\n\t * @return [Number]\n\t */\n\t Process.prototype.uptime = function () {\n\t return ((Date.now() - this.startTime) / 1000) | 0;\n\t };\n\t Process.prototype.nextTick = function (fun) {\n\t var args = [];\n\t for (var _i = 1; _i < arguments.length; _i++) {\n\t args[_i - 1] = arguments[_i];\n\t }\n\t this._queue.push(new Item(fun, args));\n\t };\n\t Process.prototype.abort = function () {\n\t this.emit('abort');\n\t };\n\t Process.prototype.exit = function (code) {\n\t this.exitCode = code;\n\t this.emit('exit', [code]);\n\t };\n\t Process.prototype.getgid = function () {\n\t return this._gid;\n\t };\n\t Process.prototype.setgid = function (gid) {\n\t if (typeof gid === 'number') {\n\t this._gid = gid;\n\t }\n\t else {\n\t this._gid = 1;\n\t }\n\t };\n\t Process.prototype.getuid = function () {\n\t return this._uid;\n\t };\n\t Process.prototype.setuid = function (uid) {\n\t if (typeof uid === 'number') {\n\t this._uid = uid;\n\t }\n\t else {\n\t this._uid = 1;\n\t }\n\t };\n\t Process.prototype.kill = function (pid, signal) {\n\t this.emit('kill', [pid, signal]);\n\t };\n\t Process.prototype.memoryUsage = function () {\n\t return { rss: 0, heapTotal: 0, heapUsed: 0 };\n\t };\n\t Process.prototype.umask = function (mask) {\n\t if (mask === void 0) { mask = this._mask; }\n\t var oldMask = this._mask;\n\t this._mask = mask;\n\t this.emit('umask', [mask]);\n\t return oldMask;\n\t };\n\t Process.prototype.hrtime = function () {\n\t var timeinfo;\n\t if (typeof performance !== 'undefined') {\n\t timeinfo = performance.now();\n\t }\n\t else if (Date['now']) {\n\t timeinfo = Date.now();\n\t }\n\t else {\n\t timeinfo = (new Date()).getTime();\n\t }\n\t var secs = (timeinfo / 1000) | 0;\n\t timeinfo -= secs * 1000;\n\t timeinfo = (timeinfo * 1000000) | 0;\n\t return [secs, timeinfo];\n\t };\n\t /**\n\t * [BFS only] Initialize the TTY devices.\n\t */\n\t Process.prototype.initializeTTYs = function () {\n\t // Guard against multiple invocations.\n\t if (this.stdout === null) {\n\t var TTY = __webpack_require__(20);\n\t this.stdout = new TTY();\n\t this.stderr = new TTY();\n\t this.stdin = new TTY();\n\t }\n\t };\n\t /**\n\t * Worker-only function; irrelevant here.\n\t */\n\t Process.prototype.disconnect = function () {\n\t };\n\t return Process;\n\t}(events.EventEmitter));\n\tmodule.exports = Process;\n\t\n\t/* WEBPACK VAR INJECTION */}.call(exports, \"/\"))\n\n/***/ },\n/* 20 */\n/***/ function(module, exports, __webpack_require__) {\n\n\t/* WEBPACK VAR INJECTION */(function(Buffer) {\"use strict\";\n\tvar __extends = (this && this.__extends) || function (d, b) {\n\t for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];\n\t function __() { this.constructor = d; }\n\t d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n\t};\n\tvar stream = __webpack_require__(9);\n\tvar TTY = (function (_super) {\n\t __extends(TTY, _super);\n\t function TTY() {\n\t _super.call(this);\n\t this.isRaw = false;\n\t this.columns = 80;\n\t this.rows = 120;\n\t this.isTTY = true;\n\t this._bufferedWrites = [];\n\t this._waitingForWrites = false;\n\t }\n\t /**\n\t * Toggle raw mode.\n\t */\n\t TTY.prototype.setRawMode = function (mode) {\n\t if (this.isRaw !== mode) {\n\t this.isRaw = mode;\n\t // [BFS] TTY implementations can use this to change their event emitting\n\t // patterns.\n\t this.emit('modeChange');\n\t }\n\t };\n\t /**\n\t * [BFS] Update the number of columns available on the terminal.\n\t */\n\t TTY.prototype.changeColumns = function (columns) {\n\t if (columns !== this.columns) {\n\t this.columns = columns;\n\t // Resize event.\n\t this.emit('resize');\n\t }\n\t };\n\t /**\n\t * [BFS] Update the number of rows available on the terminal.\n\t */\n\t TTY.prototype.changeRows = function (rows) {\n\t if (rows !== this.rows) {\n\t this.rows = rows;\n\t // Resize event.\n\t this.emit('resize');\n\t }\n\t };\n\t /**\n\t * Returns 'true' if the given object is a TTY.\n\t */\n\t TTY.isatty = function (fd) {\n\t return fd && fd instanceof TTY;\n\t };\n\t TTY.prototype._write = function (chunk, encoding, cb) {\n\t var error;\n\t try {\n\t var data;\n\t if (typeof (chunk) === 'string') {\n\t data = new Buffer(chunk, encoding);\n\t }\n\t else {\n\t data = chunk;\n\t }\n\t this._bufferedWrites.push(data);\n\t if (this._waitingForWrites) {\n\t this._read(1024);\n\t }\n\t }\n\t catch (e) {\n\t error = e;\n\t }\n\t finally {\n\t cb(error);\n\t }\n\t };\n\t TTY.prototype._read = function (size) {\n\t // Size is advisory -- we can ignore it.\n\t if (this._bufferedWrites.length === 0) {\n\t this._waitingForWrites = true;\n\t }\n\t else {\n\t while (this._bufferedWrites.length > 0) {\n\t this._waitingForWrites = this.push(this._bufferedWrites.shift());\n\t if (!this._waitingForWrites) {\n\t break;\n\t }\n\t }\n\t }\n\t };\n\t return TTY;\n\t}(stream.Duplex));\n\tmodule.exports = TTY;\n\t\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7)))\n\n/***/ },\n/* 21 */\n/***/ function(module, exports) {\n\n\texports.read = function (buffer, offset, isLE, mLen, nBytes) {\n\t var e, m\n\t var eLen = nBytes * 8 - mLen - 1\n\t var eMax = (1 << eLen) - 1\n\t var eBias = eMax >> 1\n\t var nBits = -7\n\t var i = isLE ? (nBytes - 1) : 0\n\t var d = isLE ? -1 : 1\n\t var s = buffer[offset + i]\n\t\n\t i += d\n\t\n\t e = s & ((1 << (-nBits)) - 1)\n\t s >>= (-nBits)\n\t nBits += eLen\n\t for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}\n\t\n\t m = e & ((1 << (-nBits)) - 1)\n\t e >>= (-nBits)\n\t nBits += mLen\n\t for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}\n\t\n\t if (e === 0) {\n\t e = 1 - eBias\n\t } else if (e === eMax) {\n\t return m ? NaN : ((s ? -1 : 1) * Infinity)\n\t } else {\n\t m = m + Math.pow(2, mLen)\n\t e = e - eBias\n\t }\n\t return (s ? -1 : 1) * m * Math.pow(2, e - mLen)\n\t}\n\t\n\texports.write = function (buffer, value, offset, isLE, mLen, nBytes) {\n\t var e, m, c\n\t var eLen = nBytes * 8 - mLen - 1\n\t var eMax = (1 << eLen) - 1\n\t var eBias = eMax >> 1\n\t var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)\n\t var i = isLE ? 0 : (nBytes - 1)\n\t var d = isLE ? 1 : -1\n\t var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0\n\t\n\t value = Math.abs(value)\n\t\n\t if (isNaN(value) || value === Infinity) {\n\t m = isNaN(value) ? 1 : 0\n\t e = eMax\n\t } else {\n\t e = Math.floor(Math.log(value) / Math.LN2)\n\t if (value * (c = Math.pow(2, -e)) < 1) {\n\t e--\n\t c *= 2\n\t }\n\t if (e + eBias >= 1) {\n\t value += rt / c\n\t } else {\n\t value += rt * Math.pow(2, 1 - eBias)\n\t }\n\t if (value * c >= 2) {\n\t e++\n\t c /= 2\n\t }\n\t\n\t if (e + eBias >= eMax) {\n\t m = 0\n\t e = eMax\n\t } else if (e + eBias >= 1) {\n\t m = (value * c - 1) * Math.pow(2, mLen)\n\t e = e + eBias\n\t } else {\n\t m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)\n\t e = 0\n\t }\n\t }\n\t\n\t for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}\n\t\n\t e = (e << mLen) | m\n\t eLen += mLen\n\t for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}\n\t\n\t buffer[offset + i - d] |= s * 128\n\t}\n\n\n/***/ },\n/* 22 */\n/***/ function(module, exports) {\n\n\tvar toString = {}.toString;\n\t\n\tmodule.exports = Array.isArray || function (arr) {\n\t return toString.call(arr) == '[object Array]';\n\t};\n\n\n/***/ },\n/* 23 */\n/***/ function(module, exports, __webpack_require__) {\n\n\t'use strict';\n\t\n\t\n\tvar zlib_inflate = __webpack_require__(30);\n\tvar utils = __webpack_require__(8);\n\tvar strings = __webpack_require__(24);\n\tvar c = __webpack_require__(26);\n\tvar msg = __webpack_require__(32);\n\tvar ZStream = __webpack_require__(33);\n\tvar GZheader = __webpack_require__(28);\n\t\n\tvar toString = Object.prototype.toString;\n\t\n\t/**\n\t * class Inflate\n\t *\n\t * Generic JS-style wrapper for zlib calls. If you don't need\n\t * streaming behaviour - use more simple functions: [[inflate]]\n\t * and [[inflateRaw]].\n\t **/\n\t\n\t/* internal\n\t * inflate.chunks -> Array\n\t *\n\t * Chunks of output data, if [[Inflate#onData]] not overriden.\n\t **/\n\t\n\t/**\n\t * Inflate.result -> Uint8Array|Array|String\n\t *\n\t * Uncompressed result, generated by default [[Inflate#onData]]\n\t * and [[Inflate#onEnd]] handlers. Filled after you push last chunk\n\t * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you\n\t * push a chunk with explicit flush (call [[Inflate#push]] with\n\t * `Z_SYNC_FLUSH` param).\n\t **/\n\t\n\t/**\n\t * Inflate.err -> Number\n\t *\n\t * Error code after inflate finished. 0 (Z_OK) on success.\n\t * Should be checked if broken data possible.\n\t **/\n\t\n\t/**\n\t * Inflate.msg -> String\n\t *\n\t * Error message, if [[Inflate.err]] != 0\n\t **/\n\t\n\t\n\t/**\n\t * new Inflate(options)\n\t * - options (Object): zlib inflate options.\n\t *\n\t * Creates new inflator instance with specified params. Throws exception\n\t * on bad params. Supported options:\n\t *\n\t * - `windowBits`\n\t * - `dictionary`\n\t *\n\t * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n\t * for more information on these.\n\t *\n\t * Additional options, for internal needs:\n\t *\n\t * - `chunkSize` - size of generated data chunks (16K by default)\n\t * - `raw` (Boolean) - do raw inflate\n\t * - `to` (String) - if equal to 'string', then result will be converted\n\t * from utf8 to utf16 (javascript) string. When string output requested,\n\t * chunk length can differ from `chunkSize`, depending on content.\n\t *\n\t * By default, when no options set, autodetect deflate/gzip data format via\n\t * wrapper header.\n\t *\n\t * ##### Example:\n\t *\n\t * ```javascript\n\t * var pako = require('pako')\n\t * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])\n\t * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);\n\t *\n\t * var inflate = new pako.Inflate({ level: 3});\n\t *\n\t * inflate.push(chunk1, false);\n\t * inflate.push(chunk2, true); // true -> last chunk\n\t *\n\t * if (inflate.err) { throw new Error(inflate.err); }\n\t *\n\t * console.log(inflate.result);\n\t * ```\n\t **/\n\tfunction Inflate(options) {\n\t if (!(this instanceof Inflate)) return new Inflate(options);\n\t\n\t this.options = utils.assign({\n\t chunkSize: 16384,\n\t windowBits: 0,\n\t to: ''\n\t }, options || {});\n\t\n\t var opt = this.options;\n\t\n\t // Force window size for `raw` data, if not set directly,\n\t // because we have no header for autodetect.\n\t if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {\n\t opt.windowBits = -opt.windowBits;\n\t if (opt.windowBits === 0) { opt.windowBits = -15; }\n\t }\n\t\n\t // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate\n\t if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&\n\t !(options && options.windowBits)) {\n\t opt.windowBits += 32;\n\t }\n\t\n\t // Gzip header has no info about windows size, we can do autodetect only\n\t // for deflate. So, if window size not set, force it to max when gzip possible\n\t if ((opt.windowBits > 15) && (opt.windowBits < 48)) {\n\t // bit 3 (16) -> gzipped data\n\t // bit 4 (32) -> autodetect gzip/deflate\n\t if ((opt.windowBits & 15) === 0) {\n\t opt.windowBits |= 15;\n\t }\n\t }\n\t\n\t this.err = 0; // error code, if happens (0 = Z_OK)\n\t this.msg = ''; // error message\n\t this.ended = false; // used to avoid multiple onEnd() calls\n\t this.chunks = []; // chunks of compressed data\n\t\n\t this.strm = new ZStream();\n\t this.strm.avail_out = 0;\n\t\n\t var status = zlib_inflate.inflateInit2(\n\t this.strm,\n\t opt.windowBits\n\t );\n\t\n\t if (status !== c.Z_OK) {\n\t throw new Error(msg[status]);\n\t }\n\t\n\t this.header = new GZheader();\n\t\n\t zlib_inflate.inflateGetHeader(this.strm, this.header);\n\t}\n\t\n\t/**\n\t * Inflate#push(data[, mode]) -> Boolean\n\t * - data (Uint8Array|Array|ArrayBuffer|String): input data\n\t * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.\n\t * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.\n\t *\n\t * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with\n\t * new output chunks. Returns `true` on success. The last data block must have\n\t * mode Z_FINISH (or `true`). That will flush internal pending buffers and call\n\t * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you\n\t * can use mode Z_SYNC_FLUSH, keeping the decompression context.\n\t *\n\t * On fail call [[Inflate#onEnd]] with error code and return false.\n\t *\n\t * We strongly recommend to use `Uint8Array` on input for best speed (output\n\t * format is detected automatically). Also, don't skip last param and always\n\t * use the same type in your code (boolean or number). That will improve JS speed.\n\t *\n\t * For regular `Array`-s make sure all elements are [0..255].\n\t *\n\t * ##### Example\n\t *\n\t * ```javascript\n\t * push(chunk, false); // push one of data chunks\n\t * ...\n\t * push(chunk, true); // push last chunk\n\t * ```\n\t **/\n\tInflate.prototype.push = function (data, mode) {\n\t var strm = this.strm;\n\t var chunkSize = this.options.chunkSize;\n\t var dictionary = this.options.dictionary;\n\t var status, _mode;\n\t var next_out_utf8, tail, utf8str;\n\t var dict;\n\t\n\t // Flag to properly process Z_BUF_ERROR on testing inflate call\n\t // when we check that all output data was flushed.\n\t var allowBufError = false;\n\t\n\t if (this.ended) { return false; }\n\t _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);\n\t\n\t // Convert data if needed\n\t if (typeof data === 'string') {\n\t // Only binary strings can be decompressed on practice\n\t strm.input = strings.binstring2buf(data);\n\t } else if (toString.call(data) === '[object ArrayBuffer]') {\n\t strm.input = new Uint8Array(data);\n\t } else {\n\t strm.input = data;\n\t }\n\t\n\t strm.next_in = 0;\n\t strm.avail_in = strm.input.length;\n\t\n\t do {\n\t if (strm.avail_out === 0) {\n\t strm.output = new utils.Buf8(chunkSize);\n\t strm.next_out = 0;\n\t strm.avail_out = chunkSize;\n\t }\n\t\n\t status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */\n\t\n\t if (status === c.Z_NEED_DICT && dictionary) {\n\t // Convert data if needed\n\t if (typeof dictionary === 'string') {\n\t dict = strings.string2buf(dictionary);\n\t } else if (toString.call(dictionary) === '[object ArrayBuffer]') {\n\t dict = new Uint8Array(dictionary);\n\t } else {\n\t dict = dictionary;\n\t }\n\t\n\t status = zlib_inflate.inflateSetDictionary(this.strm, dict);\n\t\n\t }\n\t\n\t if (status === c.Z_BUF_ERROR && allowBufError === true) {\n\t status = c.Z_OK;\n\t allowBufError = false;\n\t }\n\t\n\t if (status !== c.Z_STREAM_END && status !== c.Z_OK) {\n\t this.onEnd(status);\n\t this.ended = true;\n\t return false;\n\t }\n\t\n\t if (strm.next_out) {\n\t if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {\n\t\n\t if (this.options.to === 'string') {\n\t\n\t next_out_utf8 = strings.utf8border(strm.output, strm.next_out);\n\t\n\t tail = strm.next_out - next_out_utf8;\n\t utf8str = strings.buf2string(strm.output, next_out_utf8);\n\t\n\t // move tail\n\t strm.next_out = tail;\n\t strm.avail_out = chunkSize - tail;\n\t if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }\n\t\n\t this.onData(utf8str);\n\t\n\t } else {\n\t this.onData(utils.shrinkBuf(strm.output, strm.next_out));\n\t }\n\t }\n\t }\n\t\n\t // When no more input data, we should check that internal inflate buffers\n\t // are flushed. The only way to do it when avail_out = 0 - run one more\n\t // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.\n\t // Here we set flag to process this error properly.\n\t //\n\t // NOTE. Deflate does not return error in this case and does not needs such\n\t // logic.\n\t if (strm.avail_in === 0 && strm.avail_out === 0) {\n\t allowBufError = true;\n\t }\n\t\n\t } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END);\n\t\n\t if (status === c.Z_STREAM_END) {\n\t _mode = c.Z_FINISH;\n\t }\n\t\n\t // Finalize on the last chunk.\n\t if (_mode === c.Z_FINISH) {\n\t status = zlib_inflate.inflateEnd(this.strm);\n\t this.onEnd(status);\n\t this.ended = true;\n\t return status === c.Z_OK;\n\t }\n\t\n\t // callback interim results if Z_SYNC_FLUSH.\n\t if (_mode === c.Z_SYNC_FLUSH) {\n\t this.onEnd(c.Z_OK);\n\t strm.avail_out = 0;\n\t return true;\n\t }\n\t\n\t return true;\n\t};\n\t\n\t\n\t/**\n\t * Inflate#onData(chunk) -> Void\n\t * - chunk (Uint8Array|Array|String): ouput data. Type of array depends\n\t * on js engine support. When string output requested, each chunk\n\t * will be string.\n\t *\n\t * By default, stores data blocks in `chunks[]` property and glue\n\t * those in `onEnd`. Override this handler, if you need another behaviour.\n\t **/\n\tInflate.prototype.onData = function (chunk) {\n\t this.chunks.push(chunk);\n\t};\n\t\n\t\n\t/**\n\t * Inflate#onEnd(status) -> Void\n\t * - status (Number): inflate status. 0 (Z_OK) on success,\n\t * other if not.\n\t *\n\t * Called either after you tell inflate that the input stream is\n\t * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)\n\t * or if an error happened. By default - join collected chunks,\n\t * free memory and fill `results` / `err` properties.\n\t **/\n\tInflate.prototype.onEnd = function (status) {\n\t // On success - join\n\t if (status === c.Z_OK) {\n\t if (this.options.to === 'string') {\n\t // Glue & convert here, until we teach pako to send\n\t // utf8 alligned strings to onData\n\t this.result = this.chunks.join('');\n\t } else {\n\t this.result = utils.flattenChunks(this.chunks);\n\t }\n\t }\n\t this.chunks = [];\n\t this.err = status;\n\t this.msg = this.strm.msg;\n\t};\n\t\n\t\n\t/**\n\t * inflate(data[, options]) -> Uint8Array|Array|String\n\t * - data (Uint8Array|Array|String): input data to decompress.\n\t * - options (Object): zlib inflate options.\n\t *\n\t * Decompress `data` with inflate/ungzip and `options`. Autodetect\n\t * format via wrapper header by default. That's why we don't provide\n\t * separate `ungzip` method.\n\t *\n\t * Supported options are:\n\t *\n\t * - windowBits\n\t *\n\t * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n\t * for more information.\n\t *\n\t * Sugar (options):\n\t *\n\t * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify\n\t * negative windowBits implicitly.\n\t * - `to` (String) - if equal to 'string', then result will be converted\n\t * from utf8 to utf16 (javascript) string. When string output requested,\n\t * chunk length can differ from `chunkSize`, depending on content.\n\t *\n\t *\n\t * ##### Example:\n\t *\n\t * ```javascript\n\t * var pako = require('pako')\n\t * , input = pako.deflate([1,2,3,4,5,6,7,8,9])\n\t * , output;\n\t *\n\t * try {\n\t * output = pako.inflate(input);\n\t * } catch (err)\n\t * console.log(err);\n\t * }\n\t * ```\n\t **/\n\tfunction inflate(input, options) {\n\t var inflator = new Inflate(options);\n\t\n\t inflator.push(input, true);\n\t\n\t // That will never happens, if you don't cheat with options :)\n\t if (inflator.err) { throw inflator.msg || msg[inflator.err]; }\n\t\n\t return inflator.result;\n\t}\n\t\n\t\n\t/**\n\t * inflateRaw(data[, options]) -> Uint8Array|Array|String\n\t * - data (Uint8Array|Array|String): input data to decompress.\n\t * - options (Object): zlib inflate options.\n\t *\n\t * The same as [[inflate]], but creates raw data, without wrapper\n\t * (header and adler32 crc).\n\t **/\n\tfunction inflateRaw(input, options) {\n\t options = options || {};\n\t options.raw = true;\n\t return inflate(input, options);\n\t}\n\t\n\t\n\t/**\n\t * ungzip(data[, options]) -> Uint8Array|Array|String\n\t * - data (Uint8Array|Array|String): input data to decompress.\n\t * - options (Object): zlib inflate options.\n\t *\n\t * Just shortcut to [[inflate]], because it autodetects format\n\t * by header.content. Done for convenience.\n\t **/\n\t\n\t\n\texports.Inflate = Inflate;\n\texports.inflate = inflate;\n\texports.inflateRaw = inflateRaw;\n\texports.ungzip = inflate;\n\n\n/***/ },\n/* 24 */\n/***/ function(module, exports, __webpack_require__) {\n\n\t// String encode/decode helpers\n\t'use strict';\n\t\n\t\n\tvar utils = __webpack_require__(8);\n\t\n\t\n\t// Quick check if we can use fast array to bin string conversion\n\t//\n\t// - apply(Array) can fail on Android 2.2\n\t// - apply(Uint8Array) can fail on iOS 5.1 Safary\n\t//\n\tvar STR_APPLY_OK = true;\n\tvar STR_APPLY_UIA_OK = true;\n\t\n\ttry { String.fromCharCode.apply(null, [ 0 ]); } catch (__) { STR_APPLY_OK = false; }\n\ttry { String.fromCharCode.apply(null, new Uint8Array(1)); } catch (__) { STR_APPLY_UIA_OK = false; }\n\t\n\t\n\t// Table with utf8 lengths (calculated by first byte of sequence)\n\t// Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,\n\t// because max possible codepoint is 0x10ffff\n\tvar _utf8len = new utils.Buf8(256);\n\tfor (var q = 0; q < 256; q++) {\n\t _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);\n\t}\n\t_utf8len[254] = _utf8len[254] = 1; // Invalid sequence start\n\t\n\t\n\t// convert string to array (typed, when possible)\n\texports.string2buf = function (str) {\n\t var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;\n\t\n\t // count binary size\n\t for (m_pos = 0; m_pos < str_len; m_pos++) {\n\t c = str.charCodeAt(m_pos);\n\t if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {\n\t c2 = str.charCodeAt(m_pos + 1);\n\t if ((c2 & 0xfc00) === 0xdc00) {\n\t c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);\n\t m_pos++;\n\t }\n\t }\n\t buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;\n\t }\n\t\n\t // allocate buffer\n\t buf = new utils.Buf8(buf_len);\n\t\n\t // convert\n\t for (i = 0, m_pos = 0; i < buf_len; m_pos++) {\n\t c = str.charCodeAt(m_pos);\n\t if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {\n\t c2 = str.charCodeAt(m_pos + 1);\n\t if ((c2 & 0xfc00) === 0xdc00) {\n\t c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);\n\t m_pos++;\n\t }\n\t }\n\t if (c < 0x80) {\n\t /* one byte */\n\t buf[i++] = c;\n\t } else if (c < 0x800) {\n\t /* two bytes */\n\t buf[i++] = 0xC0 | (c >>> 6);\n\t buf[i++] = 0x80 | (c & 0x3f);\n\t } else if (c < 0x10000) {\n\t /* three bytes */\n\t buf[i++] = 0xE0 | (c >>> 12);\n\t buf[i++] = 0x80 | (c >>> 6 & 0x3f);\n\t buf[i++] = 0x80 | (c & 0x3f);\n\t } else {\n\t /* four bytes */\n\t buf[i++] = 0xf0 | (c >>> 18);\n\t buf[i++] = 0x80 | (c >>> 12 & 0x3f);\n\t buf[i++] = 0x80 | (c >>> 6 & 0x3f);\n\t buf[i++] = 0x80 | (c & 0x3f);\n\t }\n\t }\n\t\n\t return buf;\n\t};\n\t\n\t// Helper (used in 2 places)\n\tfunction buf2binstring(buf, len) {\n\t // use fallback for big arrays to avoid stack overflow\n\t if (len < 65537) {\n\t if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {\n\t return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));\n\t }\n\t }\n\t\n\t var result = '';\n\t for (var i = 0; i < len; i++) {\n\t result += String.fromCharCode(buf[i]);\n\t }\n\t return result;\n\t}\n\t\n\t\n\t// Convert byte array to binary string\n\texports.buf2binstring = function (buf) {\n\t return buf2binstring(buf, buf.length);\n\t};\n\t\n\t\n\t// Convert binary string (typed, when possible)\n\texports.binstring2buf = function (str) {\n\t var buf = new utils.Buf8(str.length);\n\t for (var i = 0, len = buf.length; i < len; i++) {\n\t buf[i] = str.charCodeAt(i);\n\t }\n\t return buf;\n\t};\n\t\n\t\n\t// convert array to string\n\texports.buf2string = function (buf, max) {\n\t var i, out, c, c_len;\n\t var len = max || buf.length;\n\t\n\t // Reserve max possible length (2 words per char)\n\t // NB: by unknown reasons, Array is significantly faster for\n\t // String.fromCharCode.apply than Uint16Array.\n\t var utf16buf = new Array(len * 2);\n\t\n\t for (out = 0, i = 0; i < len;) {\n\t c = buf[i++];\n\t // quick process ascii\n\t if (c < 0x80) { utf16buf[out++] = c; continue; }\n\t\n\t c_len = _utf8len[c];\n\t // skip 5 & 6 byte codes\n\t if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len - 1; continue; }\n\t\n\t // apply mask on first byte\n\t c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;\n\t // join the rest\n\t while (c_len > 1 && i < len) {\n\t c = (c << 6) | (buf[i++] & 0x3f);\n\t c_len--;\n\t }\n\t\n\t // terminated by end of string?\n\t if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }\n\t\n\t if (c < 0x10000) {\n\t utf16buf[out++] = c;\n\t } else {\n\t c -= 0x10000;\n\t utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);\n\t utf16buf[out++] = 0xdc00 | (c & 0x3ff);\n\t }\n\t }\n\t\n\t return buf2binstring(utf16buf, out);\n\t};\n\t\n\t\n\t// Calculate max possible position in utf8 buffer,\n\t// that will not break sequence. If that's not possible\n\t// - (very small limits) return max size as is.\n\t//\n\t// buf[] - utf8 bytes array\n\t// max - length limit (mandatory);\n\texports.utf8border = function (buf, max) {\n\t var pos;\n\t\n\t max = max || buf.length;\n\t if (max > buf.length) { max = buf.length; }\n\t\n\t // go back from last position, until start of sequence found\n\t pos = max - 1;\n\t while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }\n\t\n\t // Fuckup - very small and broken sequence,\n\t // return max, because we should return something anyway.\n\t if (pos < 0) { return max; }\n\t\n\t // If we came to start of buffer - that means vuffer is too small,\n\t // return max too.\n\t if (pos === 0) { return max; }\n\t\n\t return (pos + _utf8len[buf[pos]] > max) ? pos : max;\n\t};\n\n\n/***/ },\n/* 25 */\n/***/ function(module, exports) {\n\n\t'use strict';\n\t\n\t// Note: adler32 takes 12% for level 0 and 2% for level 6.\n\t// It doesn't worth to make additional optimizationa as in original.\n\t// Small size is preferable.\n\t\n\tfunction adler32(adler, buf, len, pos) {\n\t var s1 = (adler & 0xffff) |0,\n\t s2 = ((adler >>> 16) & 0xffff) |0,\n\t n = 0;\n\t\n\t while (len !== 0) {\n\t // Set limit ~ twice less than 5552, to keep\n\t // s2 in 31-bits, because we force signed ints.\n\t // in other case %= will fail.\n\t n = len > 2000 ? 2000 : len;\n\t len -= n;\n\t\n\t do {\n\t s1 = (s1 + buf[pos++]) |0;\n\t s2 = (s2 + s1) |0;\n\t } while (--n);\n\t\n\t s1 %= 65521;\n\t s2 %= 65521;\n\t }\n\t\n\t return (s1 | (s2 << 16)) |0;\n\t}\n\t\n\t\n\tmodule.exports = adler32;\n\n\n/***/ },\n/* 26 */\n/***/ function(module, exports) {\n\n\t'use strict';\n\t\n\t\n\tmodule.exports = {\n\t\n\t /* Allowed flush values; see deflate() and inflate() below for details */\n\t Z_NO_FLUSH: 0,\n\t Z_PARTIAL_FLUSH: 1,\n\t Z_SYNC_FLUSH: 2,\n\t Z_FULL_FLUSH: 3,\n\t Z_FINISH: 4,\n\t Z_BLOCK: 5,\n\t Z_TREES: 6,\n\t\n\t /* Return codes for the compression/decompression functions. Negative values\n\t * are errors, positive values are used for special but normal events.\n\t */\n\t Z_OK: 0,\n\t Z_STREAM_END: 1,\n\t Z_NEED_DICT: 2,\n\t Z_ERRNO: -1,\n\t Z_STREAM_ERROR: -2,\n\t Z_DATA_ERROR: -3,\n\t //Z_MEM_ERROR: -4,\n\t Z_BUF_ERROR: -5,\n\t //Z_VERSION_ERROR: -6,\n\t\n\t /* compression levels */\n\t Z_NO_COMPRESSION: 0,\n\t Z_BEST_SPEED: 1,\n\t Z_BEST_COMPRESSION: 9,\n\t Z_DEFAULT_COMPRESSION: -1,\n\t\n\t\n\t Z_FILTERED: 1,\n\t Z_HUFFMAN_ONLY: 2,\n\t Z_RLE: 3,\n\t Z_FIXED: 4,\n\t Z_DEFAULT_STRATEGY: 0,\n\t\n\t /* Possible values of the data_type field (though see inflate()) */\n\t Z_BINARY: 0,\n\t Z_TEXT: 1,\n\t //Z_ASCII: 1, // = Z_TEXT (deprecated)\n\t Z_UNKNOWN: 2,\n\t\n\t /* The deflate compression method */\n\t Z_DEFLATED: 8\n\t //Z_NULL: null // Use -1 or null inline, depending on var type\n\t};\n\n\n/***/ },\n/* 27 */\n/***/ function(module, exports) {\n\n\t'use strict';\n\t\n\t// Note: we can't get significant speed boost here.\n\t// So write code to minimize size - no pregenerated tables\n\t// and array tools dependencies.\n\t\n\t\n\t// Use ordinary array, since untyped makes no boost here\n\tfunction makeTable() {\n\t var c, table = [];\n\t\n\t for (var n = 0; n < 256; n++) {\n\t c = n;\n\t for (var k = 0; k < 8; k++) {\n\t c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));\n\t }\n\t table[n] = c;\n\t }\n\t\n\t return table;\n\t}\n\t\n\t// Create table on load. Just 255 signed longs. Not a problem.\n\tvar crcTable = makeTable();\n\t\n\t\n\tfunction crc32(crc, buf, len, pos) {\n\t var t = crcTable,\n\t end = pos + len;\n\t\n\t crc ^= -1;\n\t\n\t for (var i = pos; i < end; i++) {\n\t crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];\n\t }\n\t\n\t return (crc ^ (-1)); // >>> 0;\n\t}\n\t\n\t\n\tmodule.exports = crc32;\n\n\n/***/ },\n/* 28 */\n/***/ function(module, exports) {\n\n\t'use strict';\n\t\n\t\n\tfunction GZheader() {\n\t /* true if compressed data believed to be text */\n\t this.text = 0;\n\t /* modification time */\n\t this.time = 0;\n\t /* extra flags (not used when writing a gzip file) */\n\t this.xflags = 0;\n\t /* operating system */\n\t this.os = 0;\n\t /* pointer to extra field or Z_NULL if none */\n\t this.extra = null;\n\t /* extra field length (valid if extra != Z_NULL) */\n\t this.extra_len = 0; // Actually, we don't need it in JS,\n\t // but leave for few code modifications\n\t\n\t //\n\t // Setup limits is not necessary because in js we should not preallocate memory\n\t // for inflate use constant limit in 65536 bytes\n\t //\n\t\n\t /* space at extra (only when reading header) */\n\t // this.extra_max = 0;\n\t /* pointer to zero-terminated file name or Z_NULL */\n\t this.name = '';\n\t /* space at name (only when reading header) */\n\t // this.name_max = 0;\n\t /* pointer to zero-terminated comment or Z_NULL */\n\t this.comment = '';\n\t /* space at comment (only when reading header) */\n\t // this.comm_max = 0;\n\t /* true if there was or will be a header crc */\n\t this.hcrc = 0;\n\t /* true when done reading gzip header (not used when writing a gzip file) */\n\t this.done = false;\n\t}\n\t\n\tmodule.exports = GZheader;\n\n\n/***/ },\n/* 29 */\n/***/ function(module, exports) {\n\n\t'use strict';\n\t\n\t// See state defs from inflate.js\n\tvar BAD = 30; /* got a data error -- remain here until reset */\n\tvar TYPE = 12; /* i: waiting for type bits, including last-flag bit */\n\t\n\t/*\n\t Decode literal, length, and distance codes and write out the resulting\n\t literal and match bytes until either not enough input or output is\n\t available, an end-of-block is encountered, or a data error is encountered.\n\t When large enough input and output buffers are supplied to inflate(), for\n\t example, a 16K input buffer and a 64K output buffer, more than 95% of the\n\t inflate execution time is spent in this routine.\n\t\n\t Entry assumptions:\n\t\n\t state.mode === LEN\n\t strm.avail_in >= 6\n\t strm.avail_out >= 258\n\t start >= strm.avail_out\n\t state.bits < 8\n\t\n\t On return, state.mode is one of:\n\t\n\t LEN -- ran out of enough output space or enough available input\n\t TYPE -- reached end of block code, inflate() to interpret next block\n\t BAD -- error in block data\n\t\n\t Notes:\n\t\n\t - The maximum input bits used by a length/distance pair is 15 bits for the\n\t length code, 5 bits for the length extra, 15 bits for the distance code,\n\t and 13 bits for the distance extra. This totals 48 bits, or six bytes.\n\t Therefore if strm.avail_in >= 6, then there is enough input to avoid\n\t checking for available input while decoding.\n\t\n\t - The maximum bytes that a single length/distance pair can output is 258\n\t bytes, which is the maximum length that can be coded. inflate_fast()\n\t requires strm.avail_out >= 258 for each loop to avoid checking for\n\t output space.\n\t */\n\tmodule.exports = function inflate_fast(strm, start) {\n\t var state;\n\t var _in; /* local strm.input */\n\t var last; /* have enough input while in < last */\n\t var _out; /* local strm.output */\n\t var beg; /* inflate()'s initial strm.output */\n\t var end; /* while out < end, enough space available */\n\t//#ifdef INFLATE_STRICT\n\t var dmax; /* maximum distance from zlib header */\n\t//#endif\n\t var wsize; /* window size or zero if not using window */\n\t var whave; /* valid bytes in the window */\n\t var wnext; /* window write index */\n\t // Use `s_window` instead `window`, avoid conflict with instrumentation tools\n\t var s_window; /* allocated sliding window, if wsize != 0 */\n\t var hold; /* local strm.hold */\n\t var bits; /* local strm.bits */\n\t var lcode; /* local strm.lencode */\n\t var dcode; /* local strm.distcode */\n\t var lmask; /* mask for first level of length codes */\n\t var dmask; /* mask for first level of distance codes */\n\t var here; /* retrieved table entry */\n\t var op; /* code bits, operation, extra bits, or */\n\t /* window position, window bytes to copy */\n\t var len; /* match length, unused bytes */\n\t var dist; /* match distance */\n\t var from; /* where to copy match from */\n\t var from_source;\n\t\n\t\n\t var input, output; // JS specific, because we have no pointers\n\t\n\t /* copy state to local variables */\n\t state = strm.state;\n\t //here = state.here;\n\t _in = strm.next_in;\n\t input = strm.input;\n\t last = _in + (strm.avail_in - 5);\n\t _out = strm.next_out;\n\t output = strm.output;\n\t beg = _out - (start - strm.avail_out);\n\t end = _out + (strm.avail_out - 257);\n\t//#ifdef INFLATE_STRICT\n\t dmax = state.dmax;\n\t//#endif\n\t wsize = state.wsize;\n\t whave = state.whave;\n\t wnext = state.wnext;\n\t s_window = state.window;\n\t hold = state.hold;\n\t bits = state.bits;\n\t lcode = state.lencode;\n\t dcode = state.distcode;\n\t lmask = (1 << state.lenbits) - 1;\n\t dmask = (1 << state.distbits) - 1;\n\t\n\t\n\t /* decode literals and length/distances until end-of-block or not enough\n\t input data or output space */\n\t\n\t top:\n\t do {\n\t if (bits < 15) {\n\t hold += input[_in++] << bits;\n\t bits += 8;\n\t hold += input[_in++] << bits;\n\t bits += 8;\n\t }\n\t\n\t here = lcode[hold & lmask];\n\t\n\t dolen:\n\t for (;;) { // Goto emulation\n\t op = here >>> 24/*here.bits*/;\n\t hold >>>= op;\n\t bits -= op;\n\t op = (here >>> 16) & 0xff/*here.op*/;\n\t if (op === 0) { /* literal */\n\t //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?\n\t // \"inflate: literal '%c'\\n\" :\n\t // \"inflate: literal 0x%02x\\n\", here.val));\n\t output[_out++] = here & 0xffff/*here.val*/;\n\t }\n\t else if (op & 16) { /* length base */\n\t len = here & 0xffff/*here.val*/;\n\t op &= 15; /* number of extra bits */\n\t if (op) {\n\t if (bits < op) {\n\t hold += input[_in++] << bits;\n\t bits += 8;\n\t }\n\t len += hold & ((1 << op) - 1);\n\t hold >>>= op;\n\t bits -= op;\n\t }\n\t //Tracevv((stderr, \"inflate: length %u\\n\", len));\n\t if (bits < 15) {\n\t hold += input[_in++] << bits;\n\t bits += 8;\n\t hold += input[_in++] << bits;\n\t bits += 8;\n\t }\n\t here = dcode[hold & dmask];\n\t\n\t dodist:\n\t for (;;) { // goto emulation\n\t op = here >>> 24/*here.bits*/;\n\t hold >>>= op;\n\t bits -= op;\n\t op = (here >>> 16) & 0xff/*here.op*/;\n\t\n\t if (op & 16) { /* distance base */\n\t dist = here & 0xffff/*here.val*/;\n\t op &= 15; /* number of extra bits */\n\t if (bits < op) {\n\t hold += input[_in++] << bits;\n\t bits += 8;\n\t if (bits < op) {\n\t hold += input[_in++] << bits;\n\t bits += 8;\n\t }\n\t }\n\t dist += hold & ((1 << op) - 1);\n\t//#ifdef INFLATE_STRICT\n\t if (dist > dmax) {\n\t strm.msg = 'invalid distance too far back';\n\t state.mode = BAD;\n\t break top;\n\t }\n\t//#endif\n\t hold >>>= op;\n\t bits -= op;\n\t //Tracevv((stderr, \"inflate: distance %u\\n\", dist));\n\t op = _out - beg; /* max distance in output */\n\t if (dist > op) { /* see if copy from window */\n\t op = dist - op; /* distance back in window */\n\t if (op > whave) {\n\t if (state.sane) {\n\t strm.msg = 'invalid distance too far back';\n\t state.mode = BAD;\n\t break top;\n\t }\n\t\n\t// (!) This block is disabled in zlib defailts,\n\t// don't enable it for binary compatibility\n\t//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR\n\t// if (len <= op - whave) {\n\t// do {\n\t// output[_out++] = 0;\n\t// } while (--len);\n\t// continue top;\n\t// }\n\t// len -= op - whave;\n\t// do {\n\t// output[_out++] = 0;\n\t// } while (--op > whave);\n\t// if (op === 0) {\n\t// from = _out - dist;\n\t// do {\n\t// output[_out++] = output[from++];\n\t// } while (--len);\n\t// continue top;\n\t// }\n\t//#endif\n\t }\n\t from = 0; // window index\n\t from_source = s_window;\n\t if (wnext === 0) { /* very common case */\n\t from += wsize - op;\n\t if (op < len) { /* some from window */\n\t len -= op;\n\t do {\n\t output[_out++] = s_window[from++];\n\t } while (--op);\n\t from = _out - dist; /* rest from output */\n\t from_source = output;\n\t }\n\t }\n\t else if (wnext < op) { /* wrap around window */\n\t from += wsize + wnext - op;\n\t op -= wnext;\n\t if (op < len) { /* some from end of window */\n\t len -= op;\n\t do {\n\t output[_out++] = s_window[from++];\n\t } while (--op);\n\t from = 0;\n\t if (wnext < len) { /* some from start of window */\n\t op = wnext;\n\t len -= op;\n\t do {\n\t output[_out++] = s_window[from++];\n\t } while (--op);\n\t from = _out - dist; /* rest from output */\n\t from_source = output;\n\t }\n\t }\n\t }\n\t else { /* contiguous in window */\n\t from += wnext - op;\n\t if (op < len) { /* some from window */\n\t len -= op;\n\t do {\n\t output[_out++] = s_window[from++];\n\t } while (--op);\n\t from = _out - dist; /* rest from output */\n\t from_source = output;\n\t }\n\t }\n\t while (len > 2) {\n\t output[_out++] = from_source[from++];\n\t output[_out++] = from_source[from++];\n\t output[_out++] = from_source[from++];\n\t len -= 3;\n\t }\n\t if (len) {\n\t output[_out++] = from_source[from++];\n\t if (len > 1) {\n\t output[_out++] = from_source[from++];\n\t }\n\t }\n\t }\n\t else {\n\t from = _out - dist; /* copy direct from output */\n\t do { /* minimum length is three */\n\t output[_out++] = output[from++];\n\t output[_out++] = output[from++];\n\t output[_out++] = output[from++];\n\t len -= 3;\n\t } while (len > 2);\n\t if (len) {\n\t output[_out++] = output[from++];\n\t if (len > 1) {\n\t output[_out++] = output[from++];\n\t }\n\t }\n\t }\n\t }\n\t else if ((op & 64) === 0) { /* 2nd level distance code */\n\t here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];\n\t continue dodist;\n\t }\n\t else {\n\t strm.msg = 'invalid distance code';\n\t state.mode = BAD;\n\t break top;\n\t }\n\t\n\t break; // need to emulate goto via \"continue\"\n\t }\n\t }\n\t else if ((op & 64) === 0) { /* 2nd level length code */\n\t here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];\n\t continue dolen;\n\t }\n\t else if (op & 32) { /* end-of-block */\n\t //Tracevv((stderr, \"inflate: end of block\\n\"));\n\t state.mode = TYPE;\n\t break top;\n\t }\n\t else {\n\t strm.msg = 'invalid literal/length code';\n\t state.mode = BAD;\n\t break top;\n\t }\n\t\n\t break; // need to emulate goto via \"continue\"\n\t }\n\t } while (_in < last && _out < end);\n\t\n\t /* return unused bytes (on entry, bits < 8, so in won't go too far back) */\n\t len = bits >> 3;\n\t _in -= len;\n\t bits -= len << 3;\n\t hold &= (1 << bits) - 1;\n\t\n\t /* update state and return */\n\t strm.next_in = _in;\n\t strm.next_out = _out;\n\t strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));\n\t strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));\n\t state.hold = hold;\n\t state.bits = bits;\n\t return;\n\t};\n\n\n/***/ },\n/* 30 */\n/***/ function(module, exports, __webpack_require__) {\n\n\t'use strict';\n\t\n\t\n\tvar utils = __webpack_require__(8);\n\tvar adler32 = __webpack_require__(25);\n\tvar crc32 = __webpack_require__(27);\n\tvar inflate_fast = __webpack_require__(29);\n\tvar inflate_table = __webpack_require__(31);\n\t\n\tvar CODES = 0;\n\tvar LENS = 1;\n\tvar DISTS = 2;\n\t\n\t/* Public constants ==========================================================*/\n\t/* ===========================================================================*/\n\t\n\t\n\t/* Allowed flush values; see deflate() and inflate() below for details */\n\t//var Z_NO_FLUSH = 0;\n\t//var Z_PARTIAL_FLUSH = 1;\n\t//var Z_SYNC_FLUSH = 2;\n\t//var Z_FULL_FLUSH = 3;\n\tvar Z_FINISH = 4;\n\tvar Z_BLOCK = 5;\n\tvar Z_TREES = 6;\n\t\n\t\n\t/* Return codes for the compression/decompression functions. Negative values\n\t * are errors, positive values are used for special but normal events.\n\t */\n\tvar Z_OK = 0;\n\tvar Z_STREAM_END = 1;\n\tvar Z_NEED_DICT = 2;\n\t//var Z_ERRNO = -1;\n\tvar Z_STREAM_ERROR = -2;\n\tvar Z_DATA_ERROR = -3;\n\tvar Z_MEM_ERROR = -4;\n\tvar Z_BUF_ERROR = -5;\n\t//var Z_VERSION_ERROR = -6;\n\t\n\t/* The deflate compression method */\n\tvar Z_DEFLATED = 8;\n\t\n\t\n\t/* STATES ====================================================================*/\n\t/* ===========================================================================*/\n\t\n\t\n\tvar HEAD = 1; /* i: waiting for magic header */\n\tvar FLAGS = 2; /* i: waiting for method and flags (gzip) */\n\tvar TIME = 3; /* i: waiting for modification time (gzip) */\n\tvar OS = 4; /* i: waiting for extra flags and operating system (gzip) */\n\tvar EXLEN = 5; /* i: waiting for extra length (gzip) */\n\tvar EXTRA = 6; /* i: waiting for extra bytes (gzip) */\n\tvar NAME = 7; /* i: waiting for end of file name (gzip) */\n\tvar COMMENT = 8; /* i: waiting for end of comment (gzip) */\n\tvar HCRC = 9; /* i: waiting for header crc (gzip) */\n\tvar DICTID = 10; /* i: waiting for dictionary check value */\n\tvar DICT = 11; /* waiting for inflateSetDictionary() call */\n\tvar TYPE = 12; /* i: waiting for type bits, including last-flag bit */\n\tvar TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */\n\tvar STORED = 14; /* i: waiting for stored size (length and complement) */\n\tvar COPY_ = 15; /* i/o: same as COPY below, but only first time in */\n\tvar COPY = 16; /* i/o: waiting for input or output to copy stored block */\n\tvar TABLE = 17; /* i: waiting for dynamic block table lengths */\n\tvar LENLENS = 18; /* i: waiting for code length code lengths */\n\tvar CODELENS = 19; /* i: waiting for length/lit and distance code lengths */\n\tvar LEN_ = 20; /* i: same as LEN below, but only first time in */\n\tvar LEN = 21; /* i: waiting for length/lit/eob code */\n\tvar LENEXT = 22; /* i: waiting for length extra bits */\n\tvar DIST = 23; /* i: waiting for distance code */\n\tvar DISTEXT = 24; /* i: waiting for distance extra bits */\n\tvar MATCH = 25; /* o: waiting for output space to copy string */\n\tvar LIT = 26; /* o: waiting for output space to write literal */\n\tvar CHECK = 27; /* i: waiting for 32-bit check value */\n\tvar LENGTH = 28; /* i: waiting for 32-bit length (gzip) */\n\tvar DONE = 29; /* finished check, done -- remain here until reset */\n\tvar BAD = 30; /* got a data error -- remain here until reset */\n\tvar MEM = 31; /* got an inflate() memory error -- remain here until reset */\n\tvar SYNC = 32; /* looking for synchronization bytes to restart inflate() */\n\t\n\t/* ===========================================================================*/\n\t\n\t\n\t\n\tvar ENOUGH_LENS = 852;\n\tvar ENOUGH_DISTS = 592;\n\t//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);\n\t\n\tvar MAX_WBITS = 15;\n\t/* 32K LZ77 window */\n\tvar DEF_WBITS = MAX_WBITS;\n\t\n\t\n\tfunction zswap32(q) {\n\t return (((q >>> 24) & 0xff) +\n\t ((q >>> 8) & 0xff00) +\n\t ((q & 0xff00) << 8) +\n\t ((q & 0xff) << 24));\n\t}\n\t\n\t\n\tfunction InflateState() {\n\t this.mode = 0; /* current inflate mode */\n\t this.last = false; /* true if processing last block */\n\t this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */\n\t this.havedict = false; /* true if dictionary provided */\n\t this.flags = 0; /* gzip header method and flags (0 if zlib) */\n\t this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */\n\t this.check = 0; /* protected copy of check value */\n\t this.total = 0; /* protected copy of output count */\n\t // TODO: may be {}\n\t this.head = null; /* where to save gzip header information */\n\t\n\t /* sliding window */\n\t this.wbits = 0; /* log base 2 of requested window size */\n\t this.wsize = 0; /* window size or zero if not using window */\n\t this.whave = 0; /* valid bytes in the window */\n\t this.wnext = 0; /* window write index */\n\t this.window = null; /* allocated sliding window, if needed */\n\t\n\t /* bit accumulator */\n\t this.hold = 0; /* input bit accumulator */\n\t this.bits = 0; /* number of bits in \"in\" */\n\t\n\t /* for string and stored block copying */\n\t this.length = 0; /* literal or length of data to copy */\n\t this.offset = 0; /* distance back to copy string from */\n\t\n\t /* for table and code decoding */\n\t this.extra = 0; /* extra bits needed */\n\t\n\t /* fixed and dynamic code tables */\n\t this.lencode = null; /* starting table for length/literal codes */\n\t this.distcode = null; /* starting table for distance codes */\n\t this.lenbits = 0; /* index bits for lencode */\n\t this.distbits = 0; /* index bits for distcode */\n\t\n\t /* dynamic table building */\n\t this.ncode = 0; /* number of code length code lengths */\n\t this.nlen = 0; /* number of length code lengths */\n\t this.ndist = 0; /* number of distance code lengths */\n\t this.have = 0; /* number of code lengths in lens[] */\n\t this.next = null; /* next available space in codes[] */\n\t\n\t this.lens = new utils.Buf16(320); /* temporary storage for code lengths */\n\t this.work = new utils.Buf16(288); /* work area for code table building */\n\t\n\t /*\n\t because we don't have pointers in js, we use lencode and distcode directly\n\t as buffers so we don't need codes\n\t */\n\t //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */\n\t this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */\n\t this.distdyn = null; /* dynamic table for distance codes (JS specific) */\n\t this.sane = 0; /* if false, allow invalid distance too far */\n\t this.back = 0; /* bits back of last unprocessed length/lit */\n\t this.was = 0; /* initial length of match */\n\t}\n\t\n\tfunction inflateResetKeep(strm) {\n\t var state;\n\t\n\t if (!strm || !strm.state) { return Z_STREAM_ERROR; }\n\t state = strm.state;\n\t strm.total_in = strm.total_out = state.total = 0;\n\t strm.msg = ''; /*Z_NULL*/\n\t if (state.wrap) { /* to support ill-conceived Java test suite */\n\t strm.adler = state.wrap & 1;\n\t }\n\t state.mode = HEAD;\n\t state.last = 0;\n\t state.havedict = 0;\n\t state.dmax = 32768;\n\t state.head = null/*Z_NULL*/;\n\t state.hold = 0;\n\t state.bits = 0;\n\t //state.lencode = state.distcode = state.next = state.codes;\n\t state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);\n\t state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);\n\t\n\t state.sane = 1;\n\t state.back = -1;\n\t //Tracev((stderr, \"inflate: reset\\n\"));\n\t return Z_OK;\n\t}\n\t\n\tfunction inflateReset(strm) {\n\t var state;\n\t\n\t if (!strm || !strm.state) { return Z_STREAM_ERROR; }\n\t state = strm.state;\n\t state.wsize = 0;\n\t state.whave = 0;\n\t state.wnext = 0;\n\t return inflateResetKeep(strm);\n\t\n\t}\n\t\n\tfunction inflateReset2(strm, windowBits) {\n\t var wrap;\n\t var state;\n\t\n\t /* get the state */\n\t if (!strm || !strm.state) { return Z_STREAM_ERROR; }\n\t state = strm.state;\n\t\n\t /* extract wrap request from windowBits parameter */\n\t if (windowBits < 0) {\n\t wrap = 0;\n\t windowBits = -windowBits;\n\t }\n\t else {\n\t wrap = (windowBits >> 4) + 1;\n\t if (windowBits < 48) {\n\t windowBits &= 15;\n\t }\n\t }\n\t\n\t /* set number of window bits, free window if different */\n\t if (windowBits && (windowBits < 8 || windowBits > 15)) {\n\t return Z_STREAM_ERROR;\n\t }\n\t if (state.window !== null && state.wbits !== windowBits) {\n\t state.window = null;\n\t }\n\t\n\t /* update state and reset the rest of it */\n\t state.wrap = wrap;\n\t state.wbits = windowBits;\n\t return inflateReset(strm);\n\t}\n\t\n\tfunction inflateInit2(strm, windowBits) {\n\t var ret;\n\t var state;\n\t\n\t if (!strm) { return Z_STREAM_ERROR; }\n\t //strm.msg = Z_NULL; /* in case we return an error */\n\t\n\t state = new InflateState();\n\t\n\t //if (state === Z_NULL) return Z_MEM_ERROR;\n\t //Tracev((stderr, \"inflate: allocated\\n\"));\n\t strm.state = state;\n\t state.window = null/*Z_NULL*/;\n\t ret = inflateReset2(strm, windowBits);\n\t if (ret !== Z_OK) {\n\t strm.state = null/*Z_NULL*/;\n\t }\n\t return ret;\n\t}\n\t\n\tfunction inflateInit(strm) {\n\t return inflateInit2(strm, DEF_WBITS);\n\t}\n\t\n\t\n\t/*\n\t Return state with length and distance decoding tables and index sizes set to\n\t fixed code decoding. Normally this returns fixed tables from inffixed.h.\n\t If BUILDFIXED is defined, then instead this routine builds the tables the\n\t first time it's called, and returns those tables the first time and\n\t thereafter. This reduces the size of the code by about 2K bytes, in\n\t exchange for a little execution time. However, BUILDFIXED should not be\n\t used for threaded applications, since the rewriting of the tables and virgin\n\t may not be thread-safe.\n\t */\n\tvar virgin = true;\n\t\n\tvar lenfix, distfix; // We have no pointers in JS, so keep tables separate\n\t\n\tfunction fixedtables(state) {\n\t /* build fixed huffman tables if first call (may not be thread safe) */\n\t if (virgin) {\n\t var sym;\n\t\n\t lenfix = new utils.Buf32(512);\n\t distfix = new utils.Buf32(32);\n\t\n\t /* literal/length table */\n\t sym = 0;\n\t while (sym < 144) { state.lens[sym++] = 8; }\n\t while (sym < 256) { state.lens[sym++] = 9; }\n\t while (sym < 280) { state.lens[sym++] = 7; }\n\t while (sym < 288) { state.lens[sym++] = 8; }\n\t\n\t inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 });\n\t\n\t /* distance table */\n\t sym = 0;\n\t while (sym < 32) { state.lens[sym++] = 5; }\n\t\n\t inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 });\n\t\n\t /* do this just once */\n\t virgin = false;\n\t }\n\t\n\t state.lencode = lenfix;\n\t state.lenbits = 9;\n\t state.distcode = distfix;\n\t state.distbits = 5;\n\t}\n\t\n\t\n\t/*\n\t Update the window with the last wsize (normally 32K) bytes written before\n\t returning. If window does not exist yet, create it. This is only called\n\t when a window is already in use, or when output has been written during this\n\t inflate call, but the end of the deflate stream has not been reached yet.\n\t It is also called to create a window for dictionary data when a dictionary\n\t is loaded.\n\t\n\t Providing output buffers larger than 32K to inflate() should provide a speed\n\t advantage, since only the last 32K of output is copied to the sliding window\n\t upon return from inflate(), and since all distances after the first 32K of\n\t output will fall in the output data, making match copies simpler and faster.\n\t The advantage may be dependent on the size of the processor's data caches.\n\t */\n\tfunction updatewindow(strm, src, end, copy) {\n\t var dist;\n\t var state = strm.state;\n\t\n\t /* if it hasn't been done already, allocate space for the window */\n\t if (state.window === null) {\n\t state.wsize = 1 << state.wbits;\n\t state.wnext = 0;\n\t state.whave = 0;\n\t\n\t state.window = new utils.Buf8(state.wsize);\n\t }\n\t\n\t /* copy state->wsize or less output bytes into the circular window */\n\t if (copy >= state.wsize) {\n\t utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n\t state.wnext = 0;\n\t state.whave = state.wsize;\n\t }\n\t else {\n\t dist = state.wsize - state.wnext;\n\t if (dist > copy) {\n\t dist = copy;\n\t }\n\t //zmemcpy(state->window + state->wnext, end - copy, dist);\n\t utils.arraySet(state.window, src, end - copy, dist, state.wnext);\n\t copy -= dist;\n\t if (copy) {\n\t //zmemcpy(state->window, end - copy, copy);\n\t utils.arraySet(state.window, src, end - copy, copy, 0);\n\t state.wnext = copy;\n\t state.whave = state.wsize;\n\t }\n\t else {\n\t state.wnext += dist;\n\t if (state.wnext === state.wsize) { state.wnext = 0; }\n\t if (state.whave < state.wsize) { state.whave += dist; }\n\t }\n\t }\n\t return 0;\n\t}\n\t\n\tfunction inflate(strm, flush) {\n\t var state;\n\t var input, output; // input/output buffers\n\t var next; /* next input INDEX */\n\t var put; /* next output INDEX */\n\t var have, left; /* available input and output */\n\t var hold; /* bit buffer */\n\t var bits; /* bits in bit buffer */\n\t var _in, _out; /* save starting available input and output */\n\t var copy; /* number of stored or match bytes to copy */\n\t var from; /* where to copy match bytes from */\n\t var from_source;\n\t var here = 0; /* current decoding table entry */\n\t var here_bits, here_op, here_val; // paked \"here\" denormalized (JS specific)\n\t //var last; /* parent table entry */\n\t var last_bits, last_op, last_val; // paked \"last\" denormalized (JS specific)\n\t var len; /* length to copy for repeats, bits to drop */\n\t var ret; /* return code */\n\t var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */\n\t var opts;\n\t\n\t var n; // temporary var for NEED_BITS\n\t\n\t var order = /* permutation of code lengths */\n\t [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ];\n\t\n\t\n\t if (!strm || !strm.state || !strm.output ||\n\t (!strm.input && strm.avail_in !== 0)) {\n\t return Z_STREAM_ERROR;\n\t }\n\t\n\t state = strm.state;\n\t if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */\n\t\n\t\n\t //--- LOAD() ---\n\t put = strm.next_out;\n\t output = strm.output;\n\t left = strm.avail_out;\n\t next = strm.next_in;\n\t input = strm.input;\n\t have = strm.avail_in;\n\t hold = state.hold;\n\t bits = state.bits;\n\t //---\n\t\n\t _in = have;\n\t _out = left;\n\t ret = Z_OK;\n\t\n\t inf_leave: // goto emulation\n\t for (;;) {\n\t switch (state.mode) {\n\t case HEAD:\n\t if (state.wrap === 0) {\n\t state.mode = TYPEDO;\n\t break;\n\t }\n\t //=== NEEDBITS(16);\n\t while (bits < 16) {\n\t if (have === 0) { break inf_leave; }\n\t have--;\n\t hold += input[next++] << bits;\n\t bits += 8;\n\t }\n\t //===//\n\t if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */\n\t state.check = 0/*crc32(0L, Z_NULL, 0)*/;\n\t //=== CRC2(state.check, hold);\n\t hbuf[0] = hold & 0xff;\n\t hbuf[1] = (hold >>> 8) & 0xff;\n\t state.check = crc32(state.check, hbuf, 2, 0);\n\t //===//\n\t\n\t //=== INITBITS();\n\t hold = 0;\n\t bits = 0;\n\t //===//\n\t state.mode = FLAGS;\n\t break;\n\t }\n\t state.flags = 0; /* expect zlib header */\n\t if (state.head) {\n\t state.head.done = false;\n\t }\n\t if (!(state.wrap & 1) || /* check if zlib header allowed */\n\t (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {\n\t strm.msg = 'incorrect header check';\n\t state.mode = BAD;\n\t break;\n\t }\n\t if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {\n\t strm.msg = 'unknown compression method';\n\t state.mode = BAD;\n\t break;\n\t }\n\t //--- DROPBITS(4) ---//\n\t hold >>>= 4;\n\t bits -= 4;\n\t //---//\n\t len = (hold & 0x0f)/*BITS(4)*/ + 8;\n\t if (state.wbits === 0) {\n\t state.wbits = len;\n\t }\n\t else if (len > state.wbits) {\n\t strm.msg = 'invalid window size';\n\t state.mode = BAD;\n\t break;\n\t }\n\t state.dmax = 1 << len;\n\t //Tracev((stderr, \"inflate: zlib header ok\\n\"));\n\t strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;\n\t state.mode = hold & 0x200 ? DICTID : TYPE;\n\t //=== INITBITS();\n\t hold = 0;\n\t bits = 0;\n\t //===//\n\t break;\n\t case FLAGS:\n\t //=== NEEDBITS(16); */\n\t while (bits < 16) {\n\t if (have === 0) { break inf_leave; }\n\t have--;\n\t hold += input[next++] << bits;\n\t bits += 8;\n\t }\n\t //===//\n\t state.flags = hold;\n\t if ((state.flags & 0xff) !== Z_DEFLATED) {\n\t strm.msg = 'unknown compression method';\n\t state.mode = BAD;\n\t break;\n\t }\n\t if (state.flags & 0xe000) {\n\t strm.msg = 'unknown header flags set';\n\t state.mode = BAD;\n\t break;\n\t }\n\t if (state.head) {\n\t state.head.text = ((hold >> 8) & 1);\n\t }\n\t if (state.flags & 0x0200) {\n\t //=== CRC2(state.check, hold);\n\t hbuf[0] = hold & 0xff;\n\t hbuf[1] = (hold >>> 8) & 0xff;\n\t state.check = crc32(state.check, hbuf, 2, 0);\n\t //===//\n\t }\n\t //=== INITBITS();\n\t hold = 0;\n\t bits = 0;\n\t //===//\n\t state.mode = TIME;\n\t /* falls through */\n\t case TIME:\n\t //=== NEEDBITS(32); */\n\t while (bits < 32) {\n\t if (have === 0) { break inf_leave; }\n\t have--;\n\t hold += input[next++] << bits;\n\t bits += 8;\n\t }\n\t //===//\n\t if (state.head) {\n\t state.head.time = hold;\n\t }\n\t if (state.flags & 0x0200) {\n\t //=== CRC4(state.check, hold)\n\t hbuf[0] = hold & 0xff;\n\t hbuf[1] = (hold >>> 8) & 0xff;\n\t hbuf[2] = (hold >>> 16) & 0xff;\n\t hbuf[3] = (hold >>> 24) & 0xff;\n\t state.check = crc32(state.check, hbuf, 4, 0);\n\t //===\n\t }\n\t //=== INITBITS();\n\t hold = 0;\n\t bits = 0;\n\t //===//\n\t state.mode = OS;\n\t /* falls through */\n\t case OS:\n\t //=== NEEDBITS(16); */\n\t while (bits < 16) {\n\t if (have === 0) { break inf_leave; }\n\t have--;\n\t hold += input[next++] << bits;\n\t bits += 8;\n\t }\n\t //===//\n\t if (state.head) {\n\t state.head.xflags = (hold & 0xff);\n\t state.head.os = (hold >> 8);\n\t }\n\t if (state.flags & 0x0200) {\n\t //=== CRC2(state.check, hold);\n\t hbuf[0] = hold & 0xff;\n\t hbuf[1] = (hold >>> 8) & 0xff;\n\t state.check = crc32(state.check, hbuf, 2, 0);\n\t //===//\n\t }\n\t //=== INITBITS();\n\t hold = 0;\n\t bits = 0;\n\t //===//\n\t state.mode = EXLEN;\n\t /* falls through */\n\t case EXLEN:\n\t if (state.flags & 0x0400) {\n\t //=== NEEDBITS(16); */\n\t while (bits < 16) {\n\t if (have === 0) { break inf_leave; }\n\t have--;\n\t hold += input[next++] << bits;\n\t bits += 8;\n\t }\n\t //===//\n\t state.length = hold;\n\t if (state.head) {\n\t state.head.extra_len = hold;\n\t }\n\t if (state.flags & 0x0200) {\n\t //=== CRC2(state.check, hold);\n\t hbuf[0] = hold & 0xff;\n\t hbuf[1] = (hold >>> 8) & 0xff;\n\t state.check = crc32(state.check, hbuf, 2, 0);\n\t //===//\n\t }\n\t //=== INITBITS();\n\t hold = 0;\n\t bits = 0;\n\t //===//\n\t }\n\t else if (state.head) {\n\t state.head.extra = null/*Z_NULL*/;\n\t }\n\t state.mode = EXTRA;\n\t /* falls through */\n\t case EXTRA:\n\t if (state.flags & 0x0400) {\n\t copy = state.length;\n\t if (copy > have) { copy = have; }\n\t if (copy) {\n\t if (state.head) {\n\t len = state.head.extra_len - state.length;\n\t if (!state.head.extra) {\n\t // Use untyped array for more conveniend processing later\n\t state.head.extra = new Array(state.head.extra_len);\n\t }\n\t utils.arraySet(\n\t state.head.extra,\n\t input,\n\t next,\n\t // extra field is limited to 65536 bytes\n\t // - no need for additional size check\n\t copy,\n\t /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/\n\t len\n\t );\n\t //zmemcpy(state.head.extra + len, next,\n\t // len + copy > state.head.extra_max ?\n\t // state.head.extra_max - len : copy);\n\t }\n\t if (state.flags & 0x0200) {\n\t state.check = crc32(state.check, input, copy, next);\n\t }\n\t have -= copy;\n\t next += copy;\n\t state.length -= copy;\n\t }\n\t if (state.length) { break inf_leave; }\n\t }\n\t state.length = 0;\n\t state.mode = NAME;\n\t /* falls through */\n\t case NAME:\n\t if (state.flags & 0x0800) {\n\t if (have === 0) { break inf_leave; }\n\t copy = 0;\n\t do {\n\t // TODO: 2 or 1 bytes?\n\t len = input[next + copy++];\n\t /* use constant limit because in js we should not preallocate memory */\n\t if (state.head && len &&\n\t (state.length < 65536 /*state.head.name_max*/)) {\n\t state.head.name += String.fromCharCode(len);\n\t }\n\t } while (len && copy < have);\n\t\n\t if (state.flags & 0x0200) {\n\t state.check = crc32(state.check, input, copy, next);\n\t }\n\t have -= copy;\n\t next += copy;\n\t if (len) { break inf_leave; }\n\t }\n\t else if (state.head) {\n\t state.head.name = null;\n\t }\n\t state.length = 0;\n\t state.mode = COMMENT;\n\t /* falls through */\n\t case COMMENT:\n\t if (state.flags & 0x1000) {\n\t if (have === 0) { break inf_leave; }\n\t copy = 0;\n\t do {\n\t len = input[next + copy++];\n\t /* use constant limit because in js we should not preallocate memory */\n\t if (state.head && len &&\n\t (state.length < 65536 /*state.head.comm_max*/)) {\n\t state.head.comment += String.fromCharCode(len);\n\t }\n\t } while (len && copy < have);\n\t if (state.flags & 0x0200) {\n\t state.check = crc32(state.check, input, copy, next);\n\t }\n\t have -= copy;\n\t next += copy;\n\t if (len) { break inf_leave; }\n\t }\n\t else if (state.head) {\n\t state.head.comment = null;\n\t }\n\t state.mode = HCRC;\n\t /* falls through */\n\t case HCRC:\n\t if (state.flags & 0x0200) {\n\t //=== NEEDBITS(16); */\n\t while (bits < 16) {\n\t if (have === 0) { break inf_leave; }\n\t have--;\n\t hold += input[next++] << bits;\n\t bits += 8;\n\t }\n\t //===//\n\t if (hold !== (state.check & 0xffff)) {\n\t strm.msg = 'header crc mismatch';\n\t state.mode = BAD;\n\t break;\n\t }\n\t //=== INITBITS();\n\t hold = 0;\n\t bits = 0;\n\t //===//\n\t }\n\t if (state.head) {\n\t state.head.hcrc = ((state.flags >> 9) & 1);\n\t state.head.done = true;\n\t }\n\t strm.adler = state.check = 0;\n\t state.mode = TYPE;\n\t break;\n\t case DICTID:\n\t //=== NEEDBITS(32); */\n\t while (bits < 32) {\n\t if (have === 0) { break inf_leave; }\n\t have--;\n\t hold += input[next++] << bits;\n\t bits += 8;\n\t }\n\t //===//\n\t strm.adler = state.check = zswap32(hold);\n\t //=== INITBITS();\n\t hold = 0;\n\t bits = 0;\n\t //===//\n\t state.mode = DICT;\n\t /* falls through */\n\t case DICT:\n\t if (state.havedict === 0) {\n\t //--- RESTORE() ---\n\t strm.next_out = put;\n\t strm.avail_out = left;\n\t strm.next_in = next;\n\t strm.avail_in = have;\n\t state.hold = hold;\n\t state.bits = bits;\n\t //---\n\t return Z_NEED_DICT;\n\t }\n\t strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;\n\t state.mode = TYPE;\n\t /* falls through */\n\t case TYPE:\n\t if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }\n\t /* falls through */\n\t case TYPEDO:\n\t if (state.last) {\n\t //--- BYTEBITS() ---//\n\t hold >>>= bits & 7;\n\t bits -= bits & 7;\n\t //---//\n\t state.mode = CHECK;\n\t break;\n\t }\n\t //=== NEEDBITS(3); */\n\t while (bits < 3) {\n\t if (have === 0) { break inf_leave; }\n\t have--;\n\t hold += input[next++] << bits;\n\t bits += 8;\n\t }\n\t //===//\n\t state.last = (hold & 0x01)/*BITS(1)*/;\n\t //--- DROPBITS(1) ---//\n\t hold >>>= 1;\n\t bits -= 1;\n\t //---//\n\t\n\t switch ((hold & 0x03)/*BITS(2)*/) {\n\t case 0: /* stored block */\n\t //Tracev((stderr, \"inflate: stored block%s\\n\",\n\t // state.last ? \" (last)\" : \"\"));\n\t state.mode = STORED;\n\t break;\n\t case 1: /* fixed block */\n\t fixedtables(state);\n\t //Tracev((stderr, \"inflate: fixed codes block%s\\n\",\n\t // state.last ? \" (last)\" : \"\"));\n\t state.mode = LEN_; /* decode codes */\n\t if (flush === Z_TREES) {\n\t //--- DROPBITS(2) ---//\n\t hold >>>= 2;\n\t bits -= 2;\n\t //---//\n\t break inf_leave;\n\t }\n\t break;\n\t case 2: /* dynamic block */\n\t //Tracev((stderr, \"inflate: dynamic codes block%s\\n\",\n\t // state.last ? \" (last)\" : \"\"));\n\t state.mode = TABLE;\n\t break;\n\t case 3:\n\t strm.msg = 'invalid block type';\n\t state.mode = BAD;\n\t }\n\t //--- DROPBITS(2) ---//\n\t hold >>>= 2;\n\t bits -= 2;\n\t //---//\n\t break;\n\t case STORED:\n\t //--- BYTEBITS() ---// /* go to byte boundary */\n\t hold >>>= bits & 7;\n\t bits -= bits & 7;\n\t //---//\n\t //=== NEEDBITS(32); */\n\t while (bits < 32) {\n\t if (have === 0) { break inf_leave; }\n\t have--;\n\t hold += input[next++] << bits;\n\t bits += 8;\n\t }\n\t //===//\n\t if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {\n\t strm.msg = 'invalid stored block lengths';\n\t state.mode = BAD;\n\t break;\n\t }\n\t state.length = hold & 0xffff;\n\t //Tracev((stderr, \"inflate: stored length %u\\n\",\n\t // state.length));\n\t //=== INITBITS();\n\t hold = 0;\n\t bits = 0;\n\t //===//\n\t state.mode = COPY_;\n\t if (flush === Z_TREES) { break inf_leave; }\n\t /* falls through */\n\t case COPY_:\n\t state.mode = COPY;\n\t /* falls through */\n\t case COPY:\n\t copy = state.length;\n\t if (copy) {\n\t if (copy > have) { copy = have; }\n\t if (copy > left) { copy = left; }\n\t if (copy === 0) { break inf_leave; }\n\t //--- zmemcpy(put, next, copy); ---\n\t utils.arraySet(output, input, next, copy, put);\n\t //---//\n\t have -= copy;\n\t next += copy;\n\t left -= copy;\n\t put += copy;\n\t state.length -= copy;\n\t break;\n\t }\n\t //Tracev((stderr, \"inflate: stored end\\n\"));\n\t state.mode = TYPE;\n\t break;\n\t case TABLE:\n\t //=== NEEDBITS(14); */\n\t while (bits < 14) {\n\t if (have === 0) { break inf_leave; }\n\t have--;\n\t hold += input[next++] << bits;\n\t bits += 8;\n\t }\n\t //===//\n\t state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;\n\t //--- DROPBITS(5) ---//\n\t hold >>>= 5;\n\t bits -= 5;\n\t //---//\n\t state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;\n\t //--- DROPBITS(5) ---//\n\t hold >>>= 5;\n\t bits -= 5;\n\t //---//\n\t state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;\n\t //--- DROPBITS(4) ---//\n\t hold >>>= 4;\n\t bits -= 4;\n\t //---//\n\t//#ifndef PKZIP_BUG_WORKAROUND\n\t if (state.nlen > 286 || state.ndist > 30) {\n\t strm.msg = 'too many length or distance symbols';\n\t state.mode = BAD;\n\t break;\n\t }\n\t//#endif\n\t //Tracev((stderr, \"inflate: table sizes ok\\n\"));\n\t state.have = 0;\n\t state.mode = LENLENS;\n\t /* falls through */\n\t case LENLENS:\n\t while (state.have < state.ncode) {\n\t //=== NEEDBITS(3);\n\t while (bits < 3) {\n\t if (have === 0) { break inf_leave; }\n\t have--;\n\t hold += input[next++] << bits;\n\t bits += 8;\n\t }\n\t //===//\n\t state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);\n\t //--- DROPBITS(3) ---//\n\t hold >>>= 3;\n\t bits -= 3;\n\t //---//\n\t }\n\t while (state.have < 19) {\n\t state.lens[order[state.have++]] = 0;\n\t }\n\t // We have separate tables & no pointers. 2 commented lines below not needed.\n\t //state.next = state.codes;\n\t //state.lencode = state.next;\n\t // Switch to use dynamic table\n\t state.lencode = state.lendyn;\n\t state.lenbits = 7;\n\t\n\t opts = { bits: state.lenbits };\n\t ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);\n\t state.lenbits = opts.bits;\n\t\n\t if (ret) {\n\t strm.msg = 'invalid code lengths set';\n\t state.mode = BAD;\n\t break;\n\t }\n\t //Tracev((stderr, \"inflate: code lengths ok\\n\"));\n\t state.have = 0;\n\t state.mode = CODELENS;\n\t /* falls through */\n\t case CODELENS:\n\t while (state.have < state.nlen + state.ndist) {\n\t for (;;) {\n\t here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/\n\t here_bits = here >>> 24;\n\t here_op = (here >>> 16) & 0xff;\n\t here_val = here & 0xffff;\n\t\n\t if ((here_bits) <= bits) { break; }\n\t //--- PULLBYTE() ---//\n\t if (have === 0) { break inf_leave; }\n\t have--;\n\t hold += input[next++] << bits;\n\t bits += 8;\n\t //---//\n\t }\n\t if (here_val < 16) {\n\t //--- DROPBITS(here.bits) ---//\n\t hold >>>= here_bits;\n\t bits -= here_bits;\n\t //---//\n\t state.lens[state.have++] = here_val;\n\t }\n\t else {\n\t if (here_val === 16) {\n\t //=== NEEDBITS(here.bits + 2);\n\t n = here_bits + 2;\n\t while (bits < n) {\n\t if (have === 0) { break inf_leave; }\n\t have--;\n\t hold += input[next++] << bits;\n\t bits += 8;\n\t }\n\t //===//\n\t //--- DROPBITS(here.bits) ---//\n\t hold >>>= here_bits;\n\t bits -= here_bits;\n\t //---//\n\t if (state.have === 0) {\n\t strm.msg = 'invalid bit length repeat';\n\t state.mode = BAD;\n\t break;\n\t }\n\t len = state.lens[state.have - 1];\n\t copy = 3 + (hold & 0x03);//BITS(2);\n\t //--- DROPBITS(2) ---//\n\t hold >>>= 2;\n\t bits -= 2;\n\t //---//\n\t }\n\t else if (here_val === 17) {\n\t //=== NEEDBITS(here.bits + 3);\n\t n = here_bits + 3;\n\t while (bits < n) {\n\t if (have === 0) { break inf_leave; }\n\t have--;\n\t hold += input[next++] << bits;\n\t bits += 8;\n\t }\n\t //===//\n\t //--- DROPBITS(here.bits) ---//\n\t hold >>>= here_bits;\n\t bits -= here_bits;\n\t //---//\n\t len = 0;\n\t copy = 3 + (hold & 0x07);//BITS(3);\n\t //--- DROPBITS(3) ---//\n\t hold >>>= 3;\n\t bits -= 3;\n\t //---//\n\t }\n\t else {\n\t //=== NEEDBITS(here.bits + 7);\n\t n = here_bits + 7;\n\t while (bits < n) {\n\t if (have === 0) { break inf_leave; }\n\t have--;\n\t hold += input[next++] << bits;\n\t bits += 8;\n\t }\n\t //===//\n\t //--- DROPBITS(here.bits) ---//\n\t hold >>>= here_bits;\n\t bits -= here_bits;\n\t //---//\n\t len = 0;\n\t copy = 11 + (hold & 0x7f);//BITS(7);\n\t //--- DROPBITS(7) ---//\n\t hold >>>= 7;\n\t bits -= 7;\n\t //---//\n\t }\n\t if (state.have + copy > state.nlen + state.ndist) {\n\t strm.msg = 'invalid bit length repeat';\n\t state.mode = BAD;\n\t break;\n\t }\n\t while (copy--) {\n\t state.lens[state.have++] = len;\n\t }\n\t }\n\t }\n\t\n\t /* handle error breaks in while */\n\t if (state.mode === BAD) { break; }\n\t\n\t /* check for end-of-block code (better have one) */\n\t if (state.lens[256] === 0) {\n\t strm.msg = 'invalid code -- missing end-of-block';\n\t state.mode = BAD;\n\t break;\n\t }\n\t\n\t /* build code tables -- note: do not change the lenbits or distbits\n\t values here (9 and 6) without reading the comments in inftrees.h\n\t concerning the ENOUGH constants, which depend on those values */\n\t state.lenbits = 9;\n\t\n\t opts = { bits: state.lenbits };\n\t ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);\n\t // We have separate tables & no pointers. 2 commented lines below not needed.\n\t // state.next_index = opts.table_index;\n\t state.lenbits = opts.bits;\n\t // state.lencode = state.next;\n\t\n\t if (ret) {\n\t strm.msg = 'invalid literal/lengths set';\n\t state.mode = BAD;\n\t break;\n\t }\n\t\n\t state.distbits = 6;\n\t //state.distcode.copy(state.codes);\n\t // Switch to use dynamic table\n\t state.distcode = state.distdyn;\n\t opts = { bits: state.distbits };\n\t ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);\n\t // We have separate tables & no pointers. 2 commented lines below not needed.\n\t // state.next_index = opts.table_index;\n\t state.distbits = opts.bits;\n\t // state.distcode = state.next;\n\t\n\t if (ret) {\n\t strm.msg = 'invalid distances set';\n\t state.mode = BAD;\n\t break;\n\t }\n\t //Tracev((stderr, 'inflate: codes ok\\n'));\n\t state.mode = LEN_;\n\t if (flush === Z_TREES) { break inf_leave; }\n\t /* falls through */\n\t case LEN_:\n\t state.mode = LEN;\n\t /* falls through */\n\t case LEN:\n\t if (have >= 6 && left >= 258) {\n\t //--- RESTORE() ---\n\t strm.next_out = put;\n\t strm.avail_out = left;\n\t strm.next_in = next;\n\t strm.avail_in = have;\n\t state.hold = hold;\n\t state.bits = bits;\n\t //---\n\t inflate_fast(strm, _out);\n\t //--- LOAD() ---\n\t put = strm.next_out;\n\t output = strm.output;\n\t left = strm.avail_out;\n\t next = strm.next_in;\n\t input = strm.input;\n\t have = strm.avail_in;\n\t hold = state.hold;\n\t bits = state.bits;\n\t //---\n\t\n\t if (state.mode === TYPE) {\n\t state.back = -1;\n\t }\n\t break;\n\t }\n\t state.back = 0;\n\t for (;;) {\n\t here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/\n\t here_bits = here >>> 24;\n\t here_op = (here >>> 16) & 0xff;\n\t here_val = here & 0xffff;\n\t\n\t if (here_bits <= bits) { break; }\n\t //--- PULLBYTE() ---//\n\t if (have === 0) { break inf_leave; }\n\t have--;\n\t hold += input[next++] << bits;\n\t bits += 8;\n\t //---//\n\t }\n\t if (here_op && (here_op & 0xf0) === 0) {\n\t last_bits = here_bits;\n\t last_op = here_op;\n\t last_val = here_val;\n\t for (;;) {\n\t here = state.lencode[last_val +\n\t ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];\n\t here_bits = here >>> 24;\n\t here_op = (here >>> 16) & 0xff;\n\t here_val = here & 0xffff;\n\t\n\t if ((last_bits + here_bits) <= bits) { break; }\n\t //--- PULLBYTE() ---//\n\t if (have === 0) { break inf_leave; }\n\t have--;\n\t hold += input[next++] << bits;\n\t bits += 8;\n\t //---//\n\t }\n\t //--- DROPBITS(last.bits) ---//\n\t hold >>>= last_bits;\n\t bits -= last_bits;\n\t //---//\n\t state.back += last_bits;\n\t }\n\t //--- DROPBITS(here.bits) ---//\n\t hold >>>= here_bits;\n\t bits -= here_bits;\n\t //---//\n\t state.back += here_bits;\n\t state.length = here_val;\n\t if (here_op === 0) {\n\t //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?\n\t // \"inflate: literal '%c'\\n\" :\n\t // \"inflate: literal 0x%02x\\n\", here.val));\n\t state.mode = LIT;\n\t break;\n\t }\n\t if (here_op & 32) {\n\t //Tracevv((stderr, \"inflate: end of block\\n\"));\n\t state.back = -1;\n\t state.mode = TYPE;\n\t break;\n\t }\n\t if (here_op & 64) {\n\t strm.msg = 'invalid literal/length code';\n\t state.mode = BAD;\n\t break;\n\t }\n\t state.extra = here_op & 15;\n\t state.mode = LENEXT;\n\t /* falls through */\n\t case LENEXT:\n\t if (state.extra) {\n\t //=== NEEDBITS(state.extra);\n\t n = state.extra;\n\t while (bits < n) {\n\t if (have === 0) { break inf_leave; }\n\t have--;\n\t hold += input[next++] << bits;\n\t bits += 8;\n\t }\n\t //===//\n\t state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;\n\t //--- DROPBITS(state.extra) ---//\n\t hold >>>= state.extra;\n\t bits -= state.extra;\n\t //---//\n\t state.back += state.extra;\n\t }\n\t //Tracevv((stderr, \"inflate: length %u\\n\", state.length));\n\t state.was = state.length;\n\t state.mode = DIST;\n\t /* falls through */\n\t case DIST:\n\t for (;;) {\n\t here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/\n\t here_bits = here >>> 24;\n\t here_op = (here >>> 16) & 0xff;\n\t here_val = here & 0xffff;\n\t\n\t if ((here_bits) <= bits) { break; }\n\t //--- PULLBYTE() ---//\n\t if (have === 0) { break inf_leave; }\n\t have--;\n\t hold += input[next++] << bits;\n\t bits += 8;\n\t //---//\n\t }\n\t if ((here_op & 0xf0) === 0) {\n\t last_bits = here_bits;\n\t last_op = here_op;\n\t last_val = here_val;\n\t for (;;) {\n\t here = state.distcode[last_val +\n\t ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];\n\t here_bits = here >>> 24;\n\t here_op = (here >>> 16) & 0xff;\n\t here_val = here & 0xffff;\n\t\n\t if ((last_bits + here_bits) <= bits) { break; }\n\t //--- PULLBYTE() ---//\n\t if (have === 0) { break inf_leave; }\n\t have--;\n\t hold += input[next++] << bits;\n\t bits += 8;\n\t //---//\n\t }\n\t //--- DROPBITS(last.bits) ---//\n\t hold >>>= last_bits;\n\t bits -= last_bits;\n\t //---//\n\t state.back += last_bits;\n\t }\n\t //--- DROPBITS(here.bits) ---//\n\t hold >>>= here_bits;\n\t bits -= here_bits;\n\t //---//\n\t state.back += here_bits;\n\t if (here_op & 64) {\n\t strm.msg = 'invalid distance code';\n\t state.mode = BAD;\n\t break;\n\t }\n\t state.offset = here_val;\n\t state.extra = (here_op) & 15;\n\t state.mode = DISTEXT;\n\t /* falls through */\n\t case DISTEXT:\n\t if (state.extra) {\n\t //=== NEEDBITS(state.extra);\n\t n = state.extra;\n\t while (bits < n) {\n\t if (have === 0) { break inf_leave; }\n\t have--;\n\t hold += input[next++] << bits;\n\t bits += 8;\n\t }\n\t //===//\n\t state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;\n\t //--- DROPBITS(state.extra) ---//\n\t hold >>>= state.extra;\n\t bits -= state.extra;\n\t //---//\n\t state.back += state.extra;\n\t }\n\t//#ifdef INFLATE_STRICT\n\t if (state.offset > state.dmax) {\n\t strm.msg = 'invalid distance too far back';\n\t state.mode = BAD;\n\t break;\n\t }\n\t//#endif\n\t //Tracevv((stderr, \"inflate: distance %u\\n\", state.offset));\n\t state.mode = MATCH;\n\t /* falls through */\n\t case MATCH:\n\t if (left === 0) { break inf_leave; }\n\t copy = _out - left;\n\t if (state.offset > copy) { /* copy from window */\n\t copy = state.offset - copy;\n\t if (copy > state.whave) {\n\t if (state.sane) {\n\t strm.msg = 'invalid distance too far back';\n\t state.mode = BAD;\n\t break;\n\t }\n\t// (!) This block is disabled in zlib defailts,\n\t// don't enable it for binary compatibility\n\t//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR\n\t// Trace((stderr, \"inflate.c too far\\n\"));\n\t// copy -= state.whave;\n\t// if (copy > state.length) { copy = state.length; }\n\t// if (copy > left) { copy = left; }\n\t// left -= copy;\n\t// state.length -= copy;\n\t// do {\n\t// output[put++] = 0;\n\t// } while (--copy);\n\t// if (state.length === 0) { state.mode = LEN; }\n\t// break;\n\t//#endif\n\t }\n\t if (copy > state.wnext) {\n\t copy -= state.wnext;\n\t from = state.wsize - copy;\n\t }\n\t else {\n\t from = state.wnext - copy;\n\t }\n\t if (copy > state.length) { copy = state.length; }\n\t from_source = state.window;\n\t }\n\t else { /* copy from output */\n\t from_source = output;\n\t from = put - state.offset;\n\t copy = state.length;\n\t }\n\t if (copy > left) { copy = left; }\n\t left -= copy;\n\t state.length -= copy;\n\t do {\n\t output[put++] = from_source[from++];\n\t } while (--copy);\n\t if (state.length === 0) { state.mode = LEN; }\n\t break;\n\t case LIT:\n\t if (left === 0) { break inf_leave; }\n\t output[put++] = state.length;\n\t left--;\n\t state.mode = LEN;\n\t break;\n\t case CHECK:\n\t if (state.wrap) {\n\t //=== NEEDBITS(32);\n\t while (bits < 32) {\n\t if (have === 0) { break inf_leave; }\n\t have--;\n\t // Use '|' insdead of '+' to make sure that result is signed\n\t hold |= input[next++] << bits;\n\t bits += 8;\n\t }\n\t //===//\n\t _out -= left;\n\t strm.total_out += _out;\n\t state.total += _out;\n\t if (_out) {\n\t strm.adler = state.check =\n\t /*UPDATE(state.check, put - _out, _out);*/\n\t (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));\n\t\n\t }\n\t _out = left;\n\t // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too\n\t if ((state.flags ? hold : zswap32(hold)) !== state.check) {\n\t strm.msg = 'incorrect data check';\n\t state.mode = BAD;\n\t break;\n\t }\n\t //=== INITBITS();\n\t hold = 0;\n\t bits = 0;\n\t //===//\n\t //Tracev((stderr, \"inflate: check matches trailer\\n\"));\n\t }\n\t state.mode = LENGTH;\n\t /* falls through */\n\t case LENGTH:\n\t if (state.wrap && state.flags) {\n\t //=== NEEDBITS(32);\n\t while (bits < 32) {\n\t if (have === 0) { break inf_leave; }\n\t have--;\n\t hold += input[next++] << bits;\n\t bits += 8;\n\t }\n\t //===//\n\t if (hold !== (state.total & 0xffffffff)) {\n\t strm.msg = 'incorrect length check';\n\t state.mode = BAD;\n\t break;\n\t }\n\t //=== INITBITS();\n\t hold = 0;\n\t bits = 0;\n\t //===//\n\t //Tracev((stderr, \"inflate: length matches trailer\\n\"));\n\t }\n\t state.mode = DONE;\n\t /* falls through */\n\t case DONE:\n\t ret = Z_STREAM_END;\n\t break inf_leave;\n\t case BAD:\n\t ret = Z_DATA_ERROR;\n\t break inf_leave;\n\t case MEM:\n\t return Z_MEM_ERROR;\n\t case SYNC:\n\t /* falls through */\n\t default:\n\t return Z_STREAM_ERROR;\n\t }\n\t }\n\t\n\t // inf_leave <- here is real place for \"goto inf_leave\", emulated via \"break inf_leave\"\n\t\n\t /*\n\t Return from inflate(), updating the total counts and the check value.\n\t If there was no progress during the inflate() call, return a buffer\n\t error. Call updatewindow() to create and/or update the window state.\n\t Note: a memory error from inflate() is non-recoverable.\n\t */\n\t\n\t //--- RESTORE() ---\n\t strm.next_out = put;\n\t strm.avail_out = left;\n\t strm.next_in = next;\n\t strm.avail_in = have;\n\t state.hold = hold;\n\t state.bits = bits;\n\t //---\n\t\n\t if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&\n\t (state.mode < CHECK || flush !== Z_FINISH))) {\n\t if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {\n\t state.mode = MEM;\n\t return Z_MEM_ERROR;\n\t }\n\t }\n\t _in -= strm.avail_in;\n\t _out -= strm.avail_out;\n\t strm.total_in += _in;\n\t strm.total_out += _out;\n\t state.total += _out;\n\t if (state.wrap && _out) {\n\t strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/\n\t (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));\n\t }\n\t strm.data_type = state.bits + (state.last ? 64 : 0) +\n\t (state.mode === TYPE ? 128 : 0) +\n\t (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);\n\t if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {\n\t ret = Z_BUF_ERROR;\n\t }\n\t return ret;\n\t}\n\t\n\tfunction inflateEnd(strm) {\n\t\n\t if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {\n\t return Z_STREAM_ERROR;\n\t }\n\t\n\t var state = strm.state;\n\t if (state.window) {\n\t state.window = null;\n\t }\n\t strm.state = null;\n\t return Z_OK;\n\t}\n\t\n\tfunction inflateGetHeader(strm, head) {\n\t var state;\n\t\n\t /* check state */\n\t if (!strm || !strm.state) { return Z_STREAM_ERROR; }\n\t state = strm.state;\n\t if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }\n\t\n\t /* save header structure */\n\t state.head = head;\n\t head.done = false;\n\t return Z_OK;\n\t}\n\t\n\tfunction inflateSetDictionary(strm, dictionary) {\n\t var dictLength = dictionary.length;\n\t\n\t var state;\n\t var dictid;\n\t var ret;\n\t\n\t /* check state */\n\t if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; }\n\t state = strm.state;\n\t\n\t if (state.wrap !== 0 && state.mode !== DICT) {\n\t return Z_STREAM_ERROR;\n\t }\n\t\n\t /* check for correct dictionary identifier */\n\t if (state.mode === DICT) {\n\t dictid = 1; /* adler32(0, null, 0)*/\n\t /* dictid = adler32(dictid, dictionary, dictLength); */\n\t dictid = adler32(dictid, dictionary, dictLength, 0);\n\t if (dictid !== state.check) {\n\t return Z_DATA_ERROR;\n\t }\n\t }\n\t /* copy dictionary to window using updatewindow(), which will amend the\n\t existing dictionary if appropriate */\n\t ret = updatewindow(strm, dictionary, dictLength, dictLength);\n\t if (ret) {\n\t state.mode = MEM;\n\t return Z_MEM_ERROR;\n\t }\n\t state.havedict = 1;\n\t // Tracev((stderr, \"inflate: dictionary set\\n\"));\n\t return Z_OK;\n\t}\n\t\n\texports.inflateReset = inflateReset;\n\texports.inflateReset2 = inflateReset2;\n\texports.inflateResetKeep = inflateResetKeep;\n\texports.inflateInit = inflateInit;\n\texports.inflateInit2 = inflateInit2;\n\texports.inflate = inflate;\n\texports.inflateEnd = inflateEnd;\n\texports.inflateGetHeader = inflateGetHeader;\n\texports.inflateSetDictionary = inflateSetDictionary;\n\texports.inflateInfo = 'pako inflate (from Nodeca project)';\n\t\n\t/* Not implemented\n\texports.inflateCopy = inflateCopy;\n\texports.inflateGetDictionary = inflateGetDictionary;\n\texports.inflateMark = inflateMark;\n\texports.inflatePrime = inflatePrime;\n\texports.inflateSync = inflateSync;\n\texports.inflateSyncPoint = inflateSyncPoint;\n\texports.inflateUndermine = inflateUndermine;\n\t*/\n\n\n/***/ },\n/* 31 */\n/***/ function(module, exports, __webpack_require__) {\n\n\t'use strict';\n\t\n\t\n\tvar utils = __webpack_require__(8);\n\t\n\tvar MAXBITS = 15;\n\tvar ENOUGH_LENS = 852;\n\tvar ENOUGH_DISTS = 592;\n\t//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);\n\t\n\tvar CODES = 0;\n\tvar LENS = 1;\n\tvar DISTS = 2;\n\t\n\tvar lbase = [ /* Length codes 257..285 base */\n\t 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,\n\t 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0\n\t];\n\t\n\tvar lext = [ /* Length codes 257..285 extra */\n\t 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,\n\t 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78\n\t];\n\t\n\tvar dbase = [ /* Distance codes 0..29 base */\n\t 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,\n\t 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,\n\t 8193, 12289, 16385, 24577, 0, 0\n\t];\n\t\n\tvar dext = [ /* Distance codes 0..29 extra */\n\t 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,\n\t 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,\n\t 28, 28, 29, 29, 64, 64\n\t];\n\t\n\tmodule.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)\n\t{\n\t var bits = opts.bits;\n\t //here = opts.here; /* table entry for duplication */\n\t\n\t var len = 0; /* a code's length in bits */\n\t var sym = 0; /* index of code symbols */\n\t var min = 0, max = 0; /* minimum and maximum code lengths */\n\t var root = 0; /* number of index bits for root table */\n\t var curr = 0; /* number of index bits for current table */\n\t var drop = 0; /* code bits to drop for sub-table */\n\t var left = 0; /* number of prefix codes available */\n\t var used = 0; /* code entries in table used */\n\t var huff = 0; /* Huffman code */\n\t var incr; /* for incrementing code, index */\n\t var fill; /* index for replicating entries */\n\t var low; /* low bits for current root entry */\n\t var mask; /* mask for low root bits */\n\t var next; /* next available space in table */\n\t var base = null; /* base value table to use */\n\t var base_index = 0;\n\t// var shoextra; /* extra bits table to use */\n\t var end; /* use base and extra for symbol > end */\n\t var count = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */\n\t var offs = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */\n\t var extra = null;\n\t var extra_index = 0;\n\t\n\t var here_bits, here_op, here_val;\n\t\n\t /*\n\t Process a set of code lengths to create a canonical Huffman code. The\n\t code lengths are lens[0..codes-1]. Each length corresponds to the\n\t symbols 0..codes-1. The Huffman code is generated by first sorting the\n\t symbols by length from short to long, and retaining the symbol order\n\t for codes with equal lengths. Then the code starts with all zero bits\n\t for the first code of the shortest length, and the codes are integer\n\t increments for the same length, and zeros are appended as the length\n\t increases. For the deflate format, these bits are stored backwards\n\t from their more natural integer increment ordering, and so when the\n\t decoding tables are built in the large loop below, the integer codes\n\t are incremented backwards.\n\t\n\t This routine assumes, but does not check, that all of the entries in\n\t lens[] are in the range 0..MAXBITS. The caller must assure this.\n\t 1..MAXBITS is interpreted as that code length. zero means that that\n\t symbol does not occur in this code.\n\t\n\t The codes are sorted by computing a count of codes for each length,\n\t creating from that a table of starting indices for each length in the\n\t sorted table, and then entering the symbols in order in the sorted\n\t table. The sorted table is work[], with that space being provided by\n\t the caller.\n\t\n\t The length counts are used for other purposes as well, i.e. finding\n\t the minimum and maximum length codes, determining if there are any\n\t codes at all, checking for a valid set of lengths, and looking ahead\n\t at length counts to determine sub-table sizes when building the\n\t decoding tables.\n\t */\n\t\n\t /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */\n\t for (len = 0; len <= MAXBITS; len++) {\n\t count[len] = 0;\n\t }\n\t for (sym = 0; sym < codes; sym++) {\n\t count[lens[lens_index + sym]]++;\n\t }\n\t\n\t /* bound code lengths, force root to be within code lengths */\n\t root = bits;\n\t for (max = MAXBITS; max >= 1; max--) {\n\t if (count[max] !== 0) { break; }\n\t }\n\t if (root > max) {\n\t root = max;\n\t }\n\t if (max === 0) { /* no symbols to code at all */\n\t //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */\n\t //table.bits[opts.table_index] = 1; //here.bits = (var char)1;\n\t //table.val[opts.table_index++] = 0; //here.val = (var short)0;\n\t table[table_index++] = (1 << 24) | (64 << 16) | 0;\n\t\n\t\n\t //table.op[opts.table_index] = 64;\n\t //table.bits[opts.table_index] = 1;\n\t //table.val[opts.table_index++] = 0;\n\t table[table_index++] = (1 << 24) | (64 << 16) | 0;\n\t\n\t opts.bits = 1;\n\t return 0; /* no symbols, but wait for decoding to report error */\n\t }\n\t for (min = 1; min < max; min++) {\n\t if (count[min] !== 0) { break; }\n\t }\n\t if (root < min) {\n\t root = min;\n\t }\n\t\n\t /* check for an over-subscribed or incomplete set of lengths */\n\t left = 1;\n\t for (len = 1; len <= MAXBITS; len++) {\n\t left <<= 1;\n\t left -= count[len];\n\t if (left < 0) {\n\t return -1;\n\t } /* over-subscribed */\n\t }\n\t if (left > 0 && (type === CODES || max !== 1)) {\n\t return -1; /* incomplete set */\n\t }\n\t\n\t /* generate offsets into symbol table for each length for sorting */\n\t offs[1] = 0;\n\t for (len = 1; len < MAXBITS; len++) {\n\t offs[len + 1] = offs[len] + count[len];\n\t }\n\t\n\t /* sort symbols by length, by symbol order within each length */\n\t for (sym = 0; sym < codes; sym++) {\n\t if (lens[lens_index + sym] !== 0) {\n\t work[offs[lens[lens_index + sym]]++] = sym;\n\t }\n\t }\n\t\n\t /*\n\t Create and fill in decoding tables. In this loop, the table being\n\t filled is at next and has curr index bits. The code being used is huff\n\t with length len. That code is converted to an index by dropping drop\n\t bits off of the bottom. For codes where len is less than drop + curr,\n\t those top drop + curr - len bits are incremented through all values to\n\t fill the table with replicated entries.\n\t\n\t root is the number of index bits for the root table. When len exceeds\n\t root, sub-tables are created pointed to by the root entry with an index\n\t of the low root bits of huff. This is saved in low to check for when a\n\t new sub-table should be started. drop is zero when the root table is\n\t being filled, and drop is root when sub-tables are being filled.\n\t\n\t When a new sub-table is needed, it is necessary to look ahead in the\n\t code lengths to determine what size sub-table is needed. The length\n\t counts are used for this, and so count[] is decremented as codes are\n\t entered in the tables.\n\t\n\t used keeps track of how many table entries have been allocated from the\n\t provided *table space. It is checked for LENS and DIST tables against\n\t the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in\n\t the initial root table size constants. See the comments in inftrees.h\n\t for more information.\n\t\n\t sym increments through all symbols, and the loop terminates when\n\t all codes of length max, i.e. all codes, have been processed. This\n\t routine permits incomplete codes, so another loop after this one fills\n\t in the rest of the decoding tables with invalid code markers.\n\t */\n\t\n\t /* set up for code type */\n\t // poor man optimization - use if-else instead of switch,\n\t // to avoid deopts in old v8\n\t if (type === CODES) {\n\t base = extra = work; /* dummy value--not used */\n\t end = 19;\n\t\n\t } else if (type === LENS) {\n\t base = lbase;\n\t base_index -= 257;\n\t extra = lext;\n\t extra_index -= 257;\n\t end = 256;\n\t\n\t } else { /* DISTS */\n\t base = dbase;\n\t extra = dext;\n\t end = -1;\n\t }\n\t\n\t /* initialize opts for loop */\n\t huff = 0; /* starting code */\n\t sym = 0; /* starting code symbol */\n\t len = min; /* starting code length */\n\t next = table_index; /* current table to fill in */\n\t curr = root; /* current table index bits */\n\t drop = 0; /* current bits to drop from code for index */\n\t low = -1; /* trigger new sub-table when len > root */\n\t used = 1 << root; /* use root table entries */\n\t mask = used - 1; /* mask for comparing low */\n\t\n\t /* check available table space */\n\t if ((type === LENS && used > ENOUGH_LENS) ||\n\t (type === DISTS && used > ENOUGH_DISTS)) {\n\t return 1;\n\t }\n\t\n\t /* process all codes and make table entries */\n\t for (;;) {\n\t /* create table entry */\n\t here_bits = len - drop;\n\t if (work[sym] < end) {\n\t here_op = 0;\n\t here_val = work[sym];\n\t }\n\t else if (work[sym] > end) {\n\t here_op = extra[extra_index + work[sym]];\n\t here_val = base[base_index + work[sym]];\n\t }\n\t else {\n\t here_op = 32 + 64; /* end of block */\n\t here_val = 0;\n\t }\n\t\n\t /* replicate for those indices with low len bits equal to huff */\n\t incr = 1 << (len - drop);\n\t fill = 1 << curr;\n\t min = fill; /* save offset to next table */\n\t do {\n\t fill -= incr;\n\t table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;\n\t } while (fill !== 0);\n\t\n\t /* backwards increment the len-bit code huff */\n\t incr = 1 << (len - 1);\n\t while (huff & incr) {\n\t incr >>= 1;\n\t }\n\t if (incr !== 0) {\n\t huff &= incr - 1;\n\t huff += incr;\n\t } else {\n\t huff = 0;\n\t }\n\t\n\t /* go to next symbol, update count, len */\n\t sym++;\n\t if (--count[len] === 0) {\n\t if (len === max) { break; }\n\t len = lens[lens_index + work[sym]];\n\t }\n\t\n\t /* create new sub-table if needed */\n\t if (len > root && (huff & mask) !== low) {\n\t /* if first time, transition to sub-tables */\n\t if (drop === 0) {\n\t drop = root;\n\t }\n\t\n\t /* increment past last table */\n\t next += min; /* here min is 1 << curr */\n\t\n\t /* determine length of next table */\n\t curr = len - drop;\n\t left = 1 << curr;\n\t while (curr + drop < max) {\n\t left -= count[curr + drop];\n\t if (left <= 0) { break; }\n\t curr++;\n\t left <<= 1;\n\t }\n\t\n\t /* check for enough space */\n\t used += 1 << curr;\n\t if ((type === LENS && used > ENOUGH_LENS) ||\n\t (type === DISTS && used > ENOUGH_DISTS)) {\n\t return 1;\n\t }\n\t\n\t /* point entry in root table to sub-table */\n\t low = huff & mask;\n\t /*table.op[low] = curr;\n\t table.bits[low] = root;\n\t table.val[low] = next - opts.table_index;*/\n\t table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;\n\t }\n\t }\n\t\n\t /* fill in remaining table entry if code is incomplete (guaranteed to have\n\t at most one remaining entry, since if the code is incomplete, the\n\t maximum code length that was allowed to get this far is one bit) */\n\t if (huff !== 0) {\n\t //table.op[next + huff] = 64; /* invalid code marker */\n\t //table.bits[next + huff] = len - drop;\n\t //table.val[next + huff] = 0;\n\t table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;\n\t }\n\t\n\t /* set return parameters */\n\t //opts.table_index += used;\n\t opts.bits = root;\n\t return 0;\n\t};\n\n\n/***/ },\n/* 32 */\n/***/ function(module, exports) {\n\n\t'use strict';\n\t\n\tmodule.exports = {\n\t 2: 'need dictionary', /* Z_NEED_DICT 2 */\n\t 1: 'stream end', /* Z_STREAM_END 1 */\n\t 0: '', /* Z_OK 0 */\n\t '-1': 'file error', /* Z_ERRNO (-1) */\n\t '-2': 'stream error', /* Z_STREAM_ERROR (-2) */\n\t '-3': 'data error', /* Z_DATA_ERROR (-3) */\n\t '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */\n\t '-5': 'buffer error', /* Z_BUF_ERROR (-5) */\n\t '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */\n\t};\n\n\n/***/ },\n/* 33 */\n/***/ function(module, exports) {\n\n\t'use strict';\n\t\n\t\n\tfunction ZStream() {\n\t /* next input byte */\n\t this.input = null; // JS specific, because we have no pointers\n\t this.next_in = 0;\n\t /* number of bytes available at input */\n\t this.avail_in = 0;\n\t /* total number of input bytes read so far */\n\t this.total_in = 0;\n\t /* next output byte should be put there */\n\t this.output = null; // JS specific, because we have no pointers\n\t this.next_out = 0;\n\t /* remaining free space at output */\n\t this.avail_out = 0;\n\t /* total number of bytes output so far */\n\t this.total_out = 0;\n\t /* last error message, NULL if no error */\n\t this.msg = ''/*Z_NULL*/;\n\t /* not visible by applications */\n\t this.state = null;\n\t /* best guess about the data type: binary or text */\n\t this.data_type = 2/*Z_UNKNOWN*/;\n\t /* adler32 value of the uncompressed data */\n\t this.adler = 0;\n\t}\n\t\n\tmodule.exports = ZStream;\n\n\n/***/ },\n/* 34 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tmodule.exports = __webpack_require__(2)\n\n\n/***/ },\n/* 35 */\n/***/ function(module, exports, __webpack_require__) {\n\n\t'use strict';\n\t\n\tvar Buffer = __webpack_require__(1).Buffer;\n\t/**/\n\tvar bufferShim = __webpack_require__(10);\n\t/**/\n\t\n\tmodule.exports = BufferList;\n\t\n\tfunction BufferList() {\n\t this.head = null;\n\t this.tail = null;\n\t this.length = 0;\n\t}\n\t\n\tBufferList.prototype.push = function (v) {\n\t var entry = { data: v, next: null };\n\t if (this.length > 0) this.tail.next = entry;else this.head = entry;\n\t this.tail = entry;\n\t ++this.length;\n\t};\n\t\n\tBufferList.prototype.unshift = function (v) {\n\t var entry = { data: v, next: this.head };\n\t if (this.length === 0) this.tail = entry;\n\t this.head = entry;\n\t ++this.length;\n\t};\n\t\n\tBufferList.prototype.shift = function () {\n\t if (this.length === 0) return;\n\t var ret = this.head.data;\n\t if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;\n\t --this.length;\n\t return ret;\n\t};\n\t\n\tBufferList.prototype.clear = function () {\n\t this.head = this.tail = null;\n\t this.length = 0;\n\t};\n\t\n\tBufferList.prototype.join = function (s) {\n\t if (this.length === 0) return '';\n\t var p = this.head;\n\t var ret = '' + p.data;\n\t while (p = p.next) {\n\t ret += s + p.data;\n\t }return ret;\n\t};\n\t\n\tBufferList.prototype.concat = function (n) {\n\t if (this.length === 0) return bufferShim.alloc(0);\n\t if (this.length === 1) return this.head.data;\n\t var ret = bufferShim.allocUnsafe(n >>> 0);\n\t var p = this.head;\n\t var i = 0;\n\t while (p) {\n\t p.data.copy(ret, i);\n\t i += p.data.length;\n\t p = p.next;\n\t }\n\t return ret;\n\t};\n\n/***/ },\n/* 36 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tmodule.exports = __webpack_require__(15)\n\n\n/***/ },\n/* 37 */\n/***/ function(module, exports, __webpack_require__) {\n\n\t/* WEBPACK VAR INJECTION */(function(process) {var Stream = (function (){\n\t try {\n\t return __webpack_require__(9); // hack to fix a circular dependency issue when used with browserify\n\t } catch(_){}\n\t}());\n\texports = module.exports = __webpack_require__(16);\n\texports.Stream = Stream || exports;\n\texports.Readable = exports;\n\texports.Writable = __webpack_require__(13);\n\texports.Duplex = __webpack_require__(2);\n\texports.Transform = __webpack_require__(12);\n\texports.PassThrough = __webpack_require__(15);\n\t\n\tif (!process.browser && process.env.READABLE_STREAM === 'disable' && Stream) {\n\t module.exports = Stream;\n\t}\n\t\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))\n\n/***/ },\n/* 38 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tmodule.exports = __webpack_require__(12)\n\n\n/***/ },\n/* 39 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tmodule.exports = __webpack_require__(13)\n\n\n/***/ },\n/* 40 */\n/***/ function(module, exports) {\n\n\t/* WEBPACK VAR INJECTION */(function(global) {\n\t/**\n\t * Module exports.\n\t */\n\t\n\tmodule.exports = deprecate;\n\t\n\t/**\n\t * Mark that a method should not be used.\n\t * Returns a modified function which warns once by default.\n\t *\n\t * If `localStorage.noDeprecation = true` is set, then it is a no-op.\n\t *\n\t * If `localStorage.throwDeprecation = true` is set, then deprecated functions\n\t * will throw an Error when invoked.\n\t *\n\t * If `localStorage.traceDeprecation = true` is set, then deprecated functions\n\t * will invoke `console.trace()` instead of `console.error()`.\n\t *\n\t * @param {Function} fn - the function to deprecate\n\t * @param {String} msg - the string to print to the console when `fn` is invoked\n\t * @returns {Function} a new \"deprecated\" version of `fn`\n\t * @api public\n\t */\n\t\n\tfunction deprecate (fn, msg) {\n\t if (config('noDeprecation')) {\n\t return fn;\n\t }\n\t\n\t var warned = false;\n\t function deprecated() {\n\t if (!warned) {\n\t if (config('throwDeprecation')) {\n\t throw new Error(msg);\n\t } else if (config('traceDeprecation')) {\n\t console.trace(msg);\n\t } else {\n\t console.warn(msg);\n\t }\n\t warned = true;\n\t }\n\t return fn.apply(this, arguments);\n\t }\n\t\n\t return deprecated;\n\t}\n\t\n\t/**\n\t * Checks `localStorage` for boolean values for the given `name`.\n\t *\n\t * @param {String} name\n\t * @returns {Boolean}\n\t * @api private\n\t */\n\t\n\tfunction config (name) {\n\t // accessing global.localStorage can trigger a DOMException in sandboxed iframes\n\t try {\n\t if (!global.localStorage) return false;\n\t } catch (_) {\n\t return false;\n\t }\n\t var val = global.localStorage[name];\n\t if (null == val) return false;\n\t return String(val).toLowerCase() === 'true';\n\t}\n\t\n\t/* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }())))\n\n/***/ },\n/* 41 */\n/***/ function(module, exports) {\n\n\tmodule.exports = function(module) {\r\n\t\tif(!module.webpackPolyfill) {\r\n\t\t\tmodule.deprecate = function() {};\r\n\t\t\tmodule.paths = [];\r\n\t\t\t// module.parent = undefined by default\r\n\t\t\tmodule.children = [];\r\n\t\t\tmodule.webpackPolyfill = 1;\r\n\t\t}\r\n\t\treturn module;\r\n\t}\r\n\n\n/***/ },\n/* 42 */\n/***/ function(module, exports) {\n\n\t/* (ignored) */\n\n/***/ }\n/******/ ])\n});\n;\n\n\n// WEBPACK FOOTER //\n// ../build/browserfs.min.js"," \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId])\n \t\t\treturn installedModules[moduleId].exports;\n\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\texports: {},\n \t\t\tid: moduleId,\n \t\t\tloaded: false\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.loaded = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(0);\n\n\n\n// WEBPACK FOOTER //\n// webpack/bootstrap ebd3bd27baeec43b998e","import {File} from './file';\nimport {ApiError, ErrorCode} from './api_error';\nimport {FileSystem, BFSOneArgCallback, BFSCallback, BFSThreeArgCallback} from './file_system';\nimport {FileFlag} from './file_flag';\nimport * as path from 'path';\nimport Stats from './node_fs_stats';\n\n// Typing info only.\nimport * as _fs from 'fs';\n\n/**\n * Wraps a callback function. Used for unit testing. Defaults to a NOP.\n * @hidden\n */\nlet wrapCb = function(cb: T, numArgs: number): T {\n return cb;\n};\n\n/**\n * @hidden\n */\nfunction assertRoot(fs?: FileSystem | null): FileSystem {\n if (fs) {\n return fs;\n }\n throw new ApiError(ErrorCode.EIO, `Initialize BrowserFS with a file system using BrowserFS.initialize(filesystem)`);\n}\n\n/**\n * @hidden\n */\nfunction normalizeMode(mode: number | string | null | undefined, def: number): number {\n switch (typeof mode) {\n case 'number':\n // (path, flag, mode, cb?)\n return mode;\n case 'string':\n // (path, flag, modeString, cb?)\n const trueMode = parseInt( mode, 8);\n if (!isNaN(trueMode)) {\n return trueMode;\n }\n // Invalid string.\n return def;\n default:\n return def;\n }\n}\n\n/**\n * @hidden\n */\nfunction normalizeTime(time: number | Date): Date {\n if (time instanceof Date) {\n return time;\n } else if (typeof time === 'number') {\n return new Date(time * 1000);\n } else {\n throw new ApiError(ErrorCode.EINVAL, `Invalid time.`);\n }\n}\n\n/**\n * @hidden\n */\nfunction normalizePath(p: string): string {\n // Node doesn't allow null characters in paths.\n if (p.indexOf('\\u0000') >= 0) {\n throw new ApiError(ErrorCode.EINVAL, 'Path must be a string without null bytes.');\n } else if (p === '') {\n throw new ApiError(ErrorCode.EINVAL, 'Path must not be empty.');\n }\n return path.resolve(p);\n}\n\n/**\n * @hidden\n */\nfunction normalizeOptions(options: any, defEnc: string | null, defFlag: string, defMode: number | null): {encoding: string; flag: string; mode: number} {\n switch (typeof options) {\n case 'object':\n return {\n encoding: typeof options['encoding'] !== 'undefined' ? options['encoding'] : defEnc,\n flag: typeof options['flag'] !== 'undefined' ? options['flag'] : defFlag,\n mode: normalizeMode(options['mode'], defMode!)\n };\n case 'string':\n return {\n encoding: options,\n flag: defFlag,\n mode: defMode!\n };\n default:\n return {\n encoding: defEnc!,\n flag: defFlag,\n mode: defMode!\n };\n }\n}\n\n/**\n * The default callback is a NOP.\n * @hidden\n * @private\n */\nfunction nopCb() {\n // NOP.\n}\n\n/**\n * The node frontend to all filesystems.\n * This layer handles:\n *\n * * Sanity checking inputs.\n * * Normalizing paths.\n * * Resetting stack depth for asynchronous operations which may not go through\n * the browser by wrapping all input callbacks using `setImmediate`.\n * * Performing the requested operation through the filesystem or the file\n * descriptor, as appropriate.\n * * Handling optional arguments and setting default arguments.\n * @see http://nodejs.org/api/fs.html\n */\nexport default class FS {\n /* tslint:disable:variable-name */\n // Exported fs.Stats.\n public static Stats = Stats;\n /* tslint:enable:variable-name */\n\n public F_OK: number = 0;\n public R_OK: number = 4;\n public W_OK: number = 2;\n public X_OK: number = 1;\n\n private root: FileSystem | null = null;\n private fdMap: {[fd: number]: File} = {};\n private nextFd = 100;\n\n public initialize(rootFS: FileSystem): FileSystem {\n if (!( rootFS).constructor.isAvailable()) {\n throw new ApiError(ErrorCode.EINVAL, 'Tried to instantiate BrowserFS with an unavailable file system.');\n }\n return this.root = rootFS;\n }\n\n /**\n * converts Date or number to a fractional UNIX timestamp\n * Grabbed from NodeJS sources (lib/fs.js)\n */\n public _toUnixTimestamp(time: Date | number): number {\n if (typeof time === 'number') {\n return time;\n } else if (time instanceof Date) {\n return time.getTime() / 1000;\n }\n throw new Error(\"Cannot parse time: \" + time);\n }\n\n /**\n * **NONSTANDARD**: Grab the FileSystem instance that backs this API.\n * @return [BrowserFS.FileSystem | null] Returns null if the file system has\n * not been initialized.\n */\n public getRootFS(): FileSystem | null {\n if (this.root) {\n return this.root;\n } else {\n return null;\n }\n }\n\n // FILE OR DIRECTORY METHODS\n\n /**\n * Asynchronous rename. No arguments other than a possible exception are given\n * to the completion callback.\n * @param oldPath\n * @param newPath\n * @param callback\n */\n public rename(oldPath: string, newPath: string, cb: BFSOneArgCallback = nopCb): void {\n const newCb = wrapCb(cb, 1);\n try {\n assertRoot(this.root).rename(normalizePath(oldPath), normalizePath(newPath), newCb);\n } catch (e) {\n newCb(e);\n }\n }\n\n /**\n * Synchronous rename.\n * @param oldPath\n * @param newPath\n */\n public renameSync(oldPath: string, newPath: string): void {\n assertRoot(this.root).renameSync(normalizePath(oldPath), normalizePath(newPath));\n }\n\n /**\n * Test whether or not the given path exists by checking with the file system.\n * Then call the callback argument with either true or false.\n * @example Sample invocation\n * fs.exists('/etc/passwd', function (exists) {\n * util.debug(exists ? \"it's there\" : \"no passwd!\");\n * });\n * @param path\n * @param callback\n */\n public exists(path: string, cb: (exists: boolean) => any = nopCb): void {\n const newCb = wrapCb(cb, 1);\n try {\n return assertRoot(this.root).exists(normalizePath(path), newCb);\n } catch (e) {\n // Doesn't return an error. If something bad happens, we assume it just\n // doesn't exist.\n return newCb(false);\n }\n }\n\n /**\n * Test whether or not the given path exists by checking with the file system.\n * @param path\n * @return [boolean]\n */\n public existsSync(path: string): boolean {\n try {\n return assertRoot(this.root).existsSync(normalizePath(path));\n } catch (e) {\n // Doesn't return an error. If something bad happens, we assume it just\n // doesn't exist.\n return false;\n }\n }\n\n /**\n * Asynchronous `stat`.\n * @param path\n * @param callback\n */\n public stat(path: string, cb: BFSCallback = nopCb): void {\n const newCb = wrapCb(cb, 2);\n try {\n return assertRoot(this.root).stat(normalizePath(path), false, newCb);\n } catch (e) {\n return newCb(e);\n }\n }\n\n /**\n * Synchronous `stat`.\n * @param path\n * @return [BrowserFS.node.fs.Stats]\n */\n public statSync(path: string): Stats {\n return assertRoot(this.root).statSync(normalizePath(path), false);\n }\n\n /**\n * Asynchronous `lstat`.\n * `lstat()` is identical to `stat()`, except that if path is a symbolic link,\n * then the link itself is stat-ed, not the file that it refers to.\n * @param path\n * @param callback\n */\n public lstat(path: string, cb: BFSCallback = nopCb): void {\n const newCb = wrapCb(cb, 2);\n try {\n return assertRoot(this.root).stat(normalizePath(path), true, newCb);\n } catch (e) {\n return newCb(e);\n }\n }\n\n /**\n * Synchronous `lstat`.\n * `lstat()` is identical to `stat()`, except that if path is a symbolic link,\n * then the link itself is stat-ed, not the file that it refers to.\n * @param path\n * @return [BrowserFS.node.fs.Stats]\n */\n public lstatSync(path: string): Stats {\n return assertRoot(this.root).statSync(normalizePath(path), true);\n }\n\n // FILE-ONLY METHODS\n\n /**\n * Asynchronous `truncate`.\n * @param path\n * @param len\n * @param callback\n */\n public truncate(path: string, cb?: BFSOneArgCallback): void;\n public truncate(path: string, len: number, cb?: BFSOneArgCallback): void;\n public truncate(path: string, arg2: any = 0, cb: BFSOneArgCallback = nopCb): void {\n let len = 0;\n if (typeof arg2 === 'function') {\n cb = arg2;\n } else if (typeof arg2 === 'number') {\n len = arg2;\n }\n\n const newCb = wrapCb(cb, 1);\n try {\n if (len < 0) {\n throw new ApiError(ErrorCode.EINVAL);\n }\n return assertRoot(this.root).truncate(normalizePath(path), len, newCb);\n } catch (e) {\n return newCb(e);\n }\n }\n\n /**\n * Synchronous `truncate`.\n * @param path\n * @param len\n */\n public truncateSync(path: string, len: number = 0): void {\n if (len < 0) {\n throw new ApiError(ErrorCode.EINVAL);\n }\n return assertRoot(this.root).truncateSync(normalizePath(path), len);\n }\n\n /**\n * Asynchronous `unlink`.\n * @param path\n * @param callback\n */\n public unlink(path: string, cb: BFSOneArgCallback = nopCb): void {\n const newCb = wrapCb(cb, 1);\n try {\n return assertRoot(this.root).unlink(normalizePath(path), newCb);\n } catch (e) {\n return newCb(e);\n }\n }\n\n /**\n * Synchronous `unlink`.\n * @param path\n */\n public unlinkSync(path: string): void {\n return assertRoot(this.root).unlinkSync(normalizePath(path));\n }\n\n /**\n * Asynchronous file open.\n * Exclusive mode ensures that path is newly created.\n *\n * `flags` can be:\n *\n * * `'r'` - Open file for reading. An exception occurs if the file does not exist.\n * * `'r+'` - Open file for reading and writing. An exception occurs if the file does not exist.\n * * `'rs'` - Open file for reading in synchronous mode. Instructs the filesystem to not cache writes.\n * * `'rs+'` - Open file for reading and writing, and opens the file in synchronous mode.\n * * `'w'` - Open file for writing. The file is created (if it does not exist) or truncated (if it exists).\n * * `'wx'` - Like 'w' but opens the file in exclusive mode.\n * * `'w+'` - Open file for reading and writing. The file is created (if it does not exist) or truncated (if it exists).\n * * `'wx+'` - Like 'w+' but opens the file in exclusive mode.\n * * `'a'` - Open file for appending. The file is created if it does not exist.\n * * `'ax'` - Like 'a' but opens the file in exclusive mode.\n * * `'a+'` - Open file for reading and appending. The file is created if it does not exist.\n * * `'ax+'` - Like 'a+' but opens the file in exclusive mode.\n *\n * @see http://www.manpagez.com/man/2/open/\n * @param path\n * @param flags\n * @param mode defaults to `0644`\n * @param callback\n */\n public open(path: string, flag: string, cb?: BFSCallback): void;\n public open(path: string, flag: string, mode: number|string, cb?: BFSCallback): void;\n public open(path: string, flag: string, arg2?: any, cb: BFSCallback = nopCb): void {\n const mode = normalizeMode(arg2, 0x1a4);\n cb = typeof arg2 === 'function' ? arg2 : cb;\n const newCb = wrapCb(cb, 2);\n try {\n assertRoot(this.root).open(normalizePath(path), FileFlag.getFileFlag(flag), mode, (e: ApiError, file?: File) => {\n if (file) {\n newCb(e, this.getFdForFile(file));\n } else {\n newCb(e);\n }\n });\n } catch (e) {\n newCb(e);\n }\n }\n\n /**\n * Synchronous file open.\n * @see http://www.manpagez.com/man/2/open/\n * @param path\n * @param flags\n * @param mode defaults to `0644`\n * @return [BrowserFS.File]\n */\n public openSync(path: string, flag: string, mode: number|string = 0x1a4): number {\n return this.getFdForFile(\n assertRoot(this.root).openSync(normalizePath(path), FileFlag.getFileFlag(flag), normalizeMode(mode, 0x1a4)));\n }\n\n /**\n * Asynchronously reads the entire contents of a file.\n * @example Usage example\n * fs.readFile('/etc/passwd', function (err, data) {\n * if (err) throw err;\n * console.log(data);\n * });\n * @param filename\n * @param options\n * @option options [String] encoding The string encoding for the file contents. Defaults to `null`.\n * @option options [String] flag Defaults to `'r'`.\n * @param callback If no encoding is specified, then the raw buffer is returned.\n */\n public readFile(filename: string, cb: BFSCallback): void;\n public readFile(filename: string, options: { flag?: string; }, callback: BFSCallback): void;\n public readFile(filename: string, options: { encoding: string; flag?: string; }, callback: BFSCallback): void;\n public readFile(filename: string, encoding: string, cb?: BFSCallback): void;\n public readFile(filename: string, arg2: any = {}, cb: BFSCallback = nopCb ) {\n const options = normalizeOptions(arg2, null, 'r', null);\n cb = typeof arg2 === 'function' ? arg2 : cb;\n const newCb = wrapCb(cb, 2);\n try {\n const flag = FileFlag.getFileFlag(options['flag']);\n if (!flag.isReadable()) {\n return newCb(new ApiError(ErrorCode.EINVAL, 'Flag passed to readFile must allow for reading.'));\n }\n return assertRoot(this.root).readFile(normalizePath(filename), options.encoding, flag, newCb);\n } catch (e) {\n return newCb(e);\n }\n }\n\n /**\n * Synchronously reads the entire contents of a file.\n * @param filename\n * @param options\n * @option options [String] encoding The string encoding for the file contents. Defaults to `null`.\n * @option options [String] flag Defaults to `'r'`.\n * @return [String | BrowserFS.node.Buffer]\n */\n public readFileSync(filename: string, options?: { flag?: string; }): Buffer;\n public readFileSync(filename: string, options: { encoding: string; flag?: string; }): string;\n public readFileSync(filename: string, encoding: string): string;\n public readFileSync(filename: string, arg2: any = {}): any {\n const options = normalizeOptions(arg2, null, 'r', null);\n const flag = FileFlag.getFileFlag(options.flag);\n if (!flag.isReadable()) {\n throw new ApiError(ErrorCode.EINVAL, 'Flag passed to readFile must allow for reading.');\n }\n return assertRoot(this.root).readFileSync(normalizePath(filename), options.encoding, flag);\n }\n\n /**\n * Asynchronously writes data to a file, replacing the file if it already\n * exists.\n *\n * The encoding option is ignored if data is a buffer.\n *\n * @example Usage example\n * fs.writeFile('message.txt', 'Hello Node', function (err) {\n * if (err) throw err;\n * console.log('It\\'s saved!');\n * });\n * @param filename\n * @param data\n * @param options\n * @option options [String] encoding Defaults to `'utf8'`.\n * @option options [Number] mode Defaults to `0644`.\n * @option options [String] flag Defaults to `'w'`.\n * @param callback\n */\n public writeFile(filename: string, data: any, cb?: BFSOneArgCallback): void;\n public writeFile(filename: string, data: any, encoding?: string, cb?: BFSOneArgCallback): void;\n public writeFile(filename: string, data: any, options?: { encoding?: string; mode?: string | number; flag?: string; }, cb?: BFSOneArgCallback): void;\n public writeFile(filename: string, data: any, arg3: any = {}, cb: BFSOneArgCallback = nopCb): void {\n const options = normalizeOptions(arg3, 'utf8', 'w', 0x1a4);\n cb = typeof arg3 === 'function' ? arg3 : cb;\n const newCb = wrapCb(cb, 1);\n try {\n const flag = FileFlag.getFileFlag(options.flag);\n if (!flag.isWriteable()) {\n return newCb(new ApiError(ErrorCode.EINVAL, 'Flag passed to writeFile must allow for writing.'));\n }\n return assertRoot(this.root).writeFile(normalizePath(filename), data, options.encoding, flag, options.mode, newCb);\n } catch (e) {\n return newCb(e);\n }\n }\n\n /**\n * Synchronously writes data to a file, replacing the file if it already\n * exists.\n *\n * The encoding option is ignored if data is a buffer.\n * @param filename\n * @param data\n * @param options\n * @option options [String] encoding Defaults to `'utf8'`.\n * @option options [Number] mode Defaults to `0644`.\n * @option options [String] flag Defaults to `'w'`.\n */\n public writeFileSync(filename: string, data: any, options?: { encoding?: string; mode?: number | string; flag?: string; }): void;\n public writeFileSync(filename: string, data: any, encoding?: string): void;\n public writeFileSync(filename: string, data: any, arg3?: any): void {\n const options = normalizeOptions(arg3, 'utf8', 'w', 0x1a4);\n const flag = FileFlag.getFileFlag(options.flag);\n if (!flag.isWriteable()) {\n throw new ApiError(ErrorCode.EINVAL, 'Flag passed to writeFile must allow for writing.');\n }\n return assertRoot(this.root).writeFileSync(normalizePath(filename), data, options.encoding, flag, options.mode);\n }\n\n /**\n * Asynchronously append data to a file, creating the file if it not yet\n * exists.\n *\n * @example Usage example\n * fs.appendFile('message.txt', 'data to append', function (err) {\n * if (err) throw err;\n * console.log('The \"data to append\" was appended to file!');\n * });\n * @param filename\n * @param data\n * @param options\n * @option options [String] encoding Defaults to `'utf8'`.\n * @option options [Number] mode Defaults to `0644`.\n * @option options [String] flag Defaults to `'a'`.\n * @param callback\n */\n public appendFile(filename: string, data: any, cb?: BFSOneArgCallback): void;\n public appendFile(filename: string, data: any, options?: { encoding?: string; mode?: number|string; flag?: string; }, cb?: BFSOneArgCallback): void;\n public appendFile(filename: string, data: any, encoding?: string, cb?: BFSOneArgCallback): void;\n public appendFile(filename: string, data: any, arg3?: any, cb: BFSOneArgCallback = nopCb): void {\n const options = normalizeOptions(arg3, 'utf8', 'a', 0x1a4);\n cb = typeof arg3 === 'function' ? arg3 : cb;\n const newCb = wrapCb(cb, 1);\n try {\n const flag = FileFlag.getFileFlag(options.flag);\n if (!flag.isAppendable()) {\n return newCb(new ApiError(ErrorCode.EINVAL, 'Flag passed to appendFile must allow for appending.'));\n }\n assertRoot(this.root).appendFile(normalizePath(filename), data, options.encoding, flag, options.mode, newCb);\n } catch (e) {\n newCb(e);\n }\n }\n\n /**\n * Asynchronously append data to a file, creating the file if it not yet\n * exists.\n *\n * @example Usage example\n * fs.appendFile('message.txt', 'data to append', function (err) {\n * if (err) throw err;\n * console.log('The \"data to append\" was appended to file!');\n * });\n * @param filename\n * @param data\n * @param options\n * @option options [String] encoding Defaults to `'utf8'`.\n * @option options [Number] mode Defaults to `0644`.\n * @option options [String] flag Defaults to `'a'`.\n */\n public appendFileSync(filename: string, data: any, options?: { encoding?: string; mode?: number | string; flag?: string; }): void;\n public appendFileSync(filename: string, data: any, encoding?: string): void;\n public appendFileSync(filename: string, data: any, arg3?: any): void {\n const options = normalizeOptions(arg3, 'utf8', 'a', 0x1a4);\n const flag = FileFlag.getFileFlag(options.flag);\n if (!flag.isAppendable()) {\n throw new ApiError(ErrorCode.EINVAL, 'Flag passed to appendFile must allow for appending.');\n }\n return assertRoot(this.root).appendFileSync(normalizePath(filename), data, options.encoding, flag, options.mode);\n }\n\n // FILE DESCRIPTOR METHODS\n\n /**\n * Asynchronous `fstat`.\n * `fstat()` is identical to `stat()`, except that the file to be stat-ed is\n * specified by the file descriptor `fd`.\n * @param fd\n * @param callback\n */\n public fstat(fd: number, cb: BFSCallback = nopCb): void {\n const newCb = wrapCb(cb, 2);\n try {\n const file = this.fd2file(fd);\n file.stat(newCb);\n } catch (e) {\n newCb(e);\n }\n }\n\n /**\n * Synchronous `fstat`.\n * `fstat()` is identical to `stat()`, except that the file to be stat-ed is\n * specified by the file descriptor `fd`.\n * @param fd\n * @return [BrowserFS.node.fs.Stats]\n */\n public fstatSync(fd: number): Stats {\n return this.fd2file(fd).statSync();\n }\n\n /**\n * Asynchronous close.\n * @param fd\n * @param callback\n */\n public close(fd: number, cb: BFSOneArgCallback = nopCb): void {\n const newCb = wrapCb(cb, 1);\n try {\n this.fd2file(fd).close((e: ApiError) => {\n if (!e) {\n this.closeFd(fd);\n }\n newCb(e);\n });\n } catch (e) {\n newCb(e);\n }\n }\n\n /**\n * Synchronous close.\n * @param fd\n */\n public closeSync(fd: number): void {\n this.fd2file(fd).closeSync();\n this.closeFd(fd);\n }\n\n /**\n * Asynchronous ftruncate.\n * @param fd\n * @param len\n * @param callback\n */\n public ftruncate(fd: number, cb?: BFSOneArgCallback): void;\n public ftruncate(fd: number, len?: number, cb?: BFSOneArgCallback): void;\n public ftruncate(fd: number, arg2?: any, cb: BFSOneArgCallback = nopCb): void {\n const length = typeof arg2 === 'number' ? arg2 : 0;\n cb = typeof arg2 === 'function' ? arg2 : cb;\n const newCb = wrapCb(cb, 1);\n try {\n const file = this.fd2file(fd);\n if (length < 0) {\n throw new ApiError(ErrorCode.EINVAL);\n }\n file.truncate(length, newCb);\n } catch (e) {\n newCb(e);\n }\n }\n\n /**\n * Synchronous ftruncate.\n * @param fd\n * @param len\n */\n public ftruncateSync(fd: number, len: number = 0): void {\n const file = this.fd2file(fd);\n if (len < 0) {\n throw new ApiError(ErrorCode.EINVAL);\n }\n file.truncateSync(len);\n }\n\n /**\n * Asynchronous fsync.\n * @param fd\n * @param callback\n */\n public fsync(fd: number, cb: BFSOneArgCallback = nopCb): void {\n const newCb = wrapCb(cb, 1);\n try {\n this.fd2file(fd).sync(newCb);\n } catch (e) {\n newCb(e);\n }\n }\n\n /**\n * Synchronous fsync.\n * @param fd\n */\n public fsyncSync(fd: number): void {\n this.fd2file(fd).syncSync();\n }\n\n /**\n * Asynchronous fdatasync.\n * @param fd\n * @param callback\n */\n public fdatasync(fd: number, cb: BFSOneArgCallback = nopCb): void {\n const newCb = wrapCb(cb, 1);\n try {\n this.fd2file(fd).datasync(newCb);\n } catch (e) {\n newCb(e);\n }\n }\n\n /**\n * Synchronous fdatasync.\n * @param fd\n */\n public fdatasyncSync(fd: number): void {\n this.fd2file(fd).datasyncSync();\n }\n\n /**\n * Write buffer to the file specified by `fd`.\n * Note that it is unsafe to use fs.write multiple times on the same file\n * without waiting for the callback.\n * @param fd\n * @param buffer Buffer containing the data to write to\n * the file.\n * @param offset Offset in the buffer to start reading data from.\n * @param length The amount of bytes to write to the file.\n * @param position Offset from the beginning of the file where this\n * data should be written. If position is null, the data will be written at\n * the current position.\n * @param callback The number specifies the number of bytes written into the file.\n */\n public write(fd: number, buffer: Buffer, offset: number, length: number, cb?: BFSThreeArgCallback): void;\n public write(fd: number, buffer: Buffer, offset: number, length: number, position: number | null, cb?: BFSThreeArgCallback): void;\n public write(fd: number, data: any, cb?: BFSThreeArgCallback): void;\n public write(fd: number, data: any, position: number | null, cb?: BFSThreeArgCallback): void;\n public write(fd: number, data: any, position: number | null, encoding: string, cb?: BFSThreeArgCallback): void;\n public write(fd: number, arg2: any, arg3?: any, arg4?: any, arg5?: any, cb: BFSThreeArgCallback = nopCb): void {\n let buffer: Buffer, offset: number, length: number, position: number | null = null;\n if (typeof arg2 === 'string') {\n // Signature 1: (fd, string, [position?, [encoding?]], cb?)\n let encoding = 'utf8';\n switch (typeof arg3) {\n case 'function':\n // (fd, string, cb)\n cb = arg3;\n break;\n case 'number':\n // (fd, string, position, encoding?, cb?)\n position = arg3;\n encoding = typeof arg4 === 'string' ? arg4 : 'utf8';\n cb = typeof arg5 === 'function' ? arg5 : cb;\n break;\n default:\n // ...try to find the callback and get out of here!\n cb = typeof arg4 === 'function' ? arg4 : typeof arg5 === 'function' ? arg5 : cb;\n return cb(new ApiError(ErrorCode.EINVAL, 'Invalid arguments.'));\n }\n buffer = Buffer.from(arg2, encoding);\n offset = 0;\n length = buffer.length;\n } else {\n // Signature 2: (fd, buffer, offset, length, position?, cb?)\n buffer = arg2;\n offset = arg3;\n length = arg4;\n position = typeof arg5 === 'number' ? arg5 : null;\n cb = typeof arg5 === 'function' ? arg5 : cb;\n }\n\n const newCb = wrapCb(cb, 3);\n try {\n const file = this.fd2file(fd);\n if (position === undefined || position === null) {\n position = file.getPos()!;\n }\n file.write(buffer, offset, length, position, newCb);\n } catch (e) {\n newCb(e);\n }\n }\n\n /**\n * Write buffer to the file specified by `fd`.\n * Note that it is unsafe to use fs.write multiple times on the same file\n * without waiting for it to return.\n * @param fd\n * @param buffer Buffer containing the data to write to\n * the file.\n * @param offset Offset in the buffer to start reading data from.\n * @param length The amount of bytes to write to the file.\n * @param position Offset from the beginning of the file where this\n * data should be written. If position is null, the data will be written at\n * the current position.\n */\n public writeSync(fd: number, buffer: Buffer, offset: number, length: number, position?: number | null): number;\n public writeSync(fd: number, data: string, position?: number | null, encoding?: string): number;\n public writeSync(fd: number, arg2: any, arg3?: any, arg4?: any, arg5?: any): number {\n let buffer: Buffer, offset: number = 0, length: number, position: number | null;\n if (typeof arg2 === 'string') {\n // Signature 1: (fd, string, [position?, [encoding?]])\n position = typeof arg3 === 'number' ? arg3 : null;\n const encoding = typeof arg4 === 'string' ? arg4 : 'utf8';\n offset = 0;\n buffer = Buffer.from(arg2, encoding);\n length = buffer.length;\n } else {\n // Signature 2: (fd, buffer, offset, length, position?)\n buffer = arg2;\n offset = arg3;\n length = arg4;\n position = typeof arg5 === 'number' ? arg5 : null;\n }\n\n const file = this.fd2file(fd);\n if (position === undefined || position === null) {\n position = file.getPos()!;\n }\n return file.writeSync(buffer, offset, length, position);\n }\n\n /**\n * Read data from the file specified by `fd`.\n * @param buffer The buffer that the data will be\n * written to.\n * @param offset The offset within the buffer where writing will\n * start.\n * @param length An integer specifying the number of bytes to read.\n * @param position An integer specifying where to begin reading from\n * in the file. If position is null, data will be read from the current file\n * position.\n * @param callback The number is the number of bytes read\n */\n public read(fd: number, length: number, position: number | null, encoding: string, cb?: BFSThreeArgCallback): void;\n public read(fd: number, buffer: Buffer, offset: number, length: number, position: number | null, cb?: BFSThreeArgCallback): void;\n public read(fd: number, arg2: any, arg3: any, arg4: any, arg5?: any, cb: BFSThreeArgCallback | BFSThreeArgCallback = nopCb): void {\n let position: number | null, offset: number, length: number, buffer: Buffer, newCb: BFSThreeArgCallback;\n if (typeof arg2 === 'number') {\n // legacy interface\n // (fd, length, position, encoding, callback)\n length = arg2;\n position = arg3;\n const encoding = arg4;\n cb = typeof arg5 === 'function' ? arg5 : cb;\n offset = 0;\n buffer = Buffer.alloc(length);\n // XXX: Inefficient.\n // Wrap the cb so we shelter upper layers of the API from these\n // shenanigans.\n newCb = wrapCb((err?: ApiError | null, bytesRead?: number, buf?: Buffer) => {\n if (err) {\n return ( cb)(err);\n }\n (> cb)(err, buf!.toString(encoding), bytesRead!);\n }, 3);\n } else {\n buffer = arg2;\n offset = arg3;\n length = arg4;\n position = arg5;\n newCb = wrapCb(> cb, 3);\n }\n\n try {\n const file = this.fd2file(fd);\n if (position === undefined || position === null) {\n position = file.getPos()!;\n }\n file.read(buffer, offset, length, position, newCb);\n } catch (e) {\n newCb(e);\n }\n }\n\n /**\n * Read data from the file specified by `fd`.\n * @param fd\n * @param buffer The buffer that the data will be\n * written to.\n * @param offset The offset within the buffer where writing will\n * start.\n * @param length An integer specifying the number of bytes to read.\n * @param position An integer specifying where to begin reading from\n * in the file. If position is null, data will be read from the current file\n * position.\n * @return [Number]\n */\n public readSync(fd: number, length: number, position: number, encoding: string): string;\n public readSync(fd: number, buffer: Buffer, offset: number, length: number, position: number): number;\n public readSync(fd: number, arg2: any, arg3: any, arg4: any, arg5?: any): any {\n let shenanigans = false;\n let buffer: Buffer, offset: number, length: number, position: number, encoding: string = 'utf8';\n if (typeof arg2 === 'number') {\n length = arg2;\n position = arg3;\n encoding = arg4;\n offset = 0;\n buffer = Buffer.alloc(length);\n shenanigans = true;\n } else {\n buffer = arg2;\n offset = arg3;\n length = arg4;\n position = arg5;\n }\n const file = this.fd2file(fd);\n if (position === undefined || position === null) {\n position = file.getPos()!;\n }\n\n const rv = file.readSync(buffer, offset, length, position);\n if (!shenanigans) {\n return rv;\n } else {\n return [buffer.toString(encoding), rv];\n }\n }\n\n /**\n * Asynchronous `fchown`.\n * @param fd\n * @param uid\n * @param gid\n * @param callback\n */\n public fchown(fd: number, uid: number, gid: number, callback: BFSOneArgCallback = nopCb): void {\n const newCb = wrapCb(callback, 1);\n try {\n this.fd2file(fd).chown(uid, gid, newCb);\n } catch (e) {\n newCb(e);\n }\n }\n\n /**\n * Synchronous `fchown`.\n * @param fd\n * @param uid\n * @param gid\n */\n public fchownSync(fd: number, uid: number, gid: number): void {\n this.fd2file(fd).chownSync(uid, gid);\n }\n\n /**\n * Asynchronous `fchmod`.\n * @param fd\n * @param mode\n * @param callback\n */\n public fchmod(fd: number, mode: string | number, cb: BFSOneArgCallback): void {\n const newCb = wrapCb(cb, 1);\n try {\n const numMode = typeof mode === 'string' ? parseInt(mode, 8) : mode;\n this.fd2file(fd).chmod(numMode, newCb);\n } catch (e) {\n newCb(e);\n }\n }\n\n /**\n * Synchronous `fchmod`.\n * @param fd\n * @param mode\n */\n public fchmodSync(fd: number, mode: number | string): void {\n const numMode = typeof mode === 'string' ? parseInt(mode, 8) : mode;\n this.fd2file(fd).chmodSync(numMode);\n }\n\n /**\n * Change the file timestamps of a file referenced by the supplied file\n * descriptor.\n * @param fd\n * @param atime\n * @param mtime\n * @param callback\n */\n public futimes(fd: number, atime: number | Date, mtime: number | Date, cb: BFSOneArgCallback = nopCb): void {\n const newCb = wrapCb(cb, 1);\n try {\n const file = this.fd2file(fd);\n if (typeof atime === 'number') {\n atime = new Date(atime * 1000);\n }\n if (typeof mtime === 'number') {\n mtime = new Date(mtime * 1000);\n }\n file.utimes(atime, mtime, newCb);\n } catch (e) {\n newCb(e);\n }\n }\n\n /**\n * Change the file timestamps of a file referenced by the supplied file\n * descriptor.\n * @param fd\n * @param atime\n * @param mtime\n */\n public futimesSync(fd: number, atime: number | Date, mtime: number | Date): void {\n this.fd2file(fd).utimesSync(normalizeTime(atime), normalizeTime(mtime));\n }\n\n // DIRECTORY-ONLY METHODS\n\n /**\n * Asynchronous `rmdir`.\n * @param path\n * @param callback\n */\n public rmdir(path: string, cb: BFSOneArgCallback = nopCb): void {\n const newCb = wrapCb(cb, 1);\n try {\n path = normalizePath(path);\n assertRoot(this.root).rmdir(path, newCb);\n } catch (e) {\n newCb(e);\n }\n }\n\n /**\n * Synchronous `rmdir`.\n * @param path\n */\n public rmdirSync(path: string): void {\n path = normalizePath(path);\n return assertRoot(this.root).rmdirSync(path);\n }\n\n /**\n * Asynchronous `mkdir`.\n * @param path\n * @param mode defaults to `0777`\n * @param callback\n */\n public mkdir(path: string, mode?: any, cb: BFSOneArgCallback = nopCb): void {\n if (typeof mode === 'function') {\n cb = mode;\n mode = 0x1ff;\n }\n const newCb = wrapCb(cb, 1);\n try {\n path = normalizePath(path);\n assertRoot(this.root).mkdir(path, mode, newCb);\n } catch (e) {\n newCb(e);\n }\n }\n\n /**\n * Synchronous `mkdir`.\n * @param path\n * @param mode defaults to `0777`\n */\n public mkdirSync(path: string, mode?: number | string): void {\n assertRoot(this.root).mkdirSync(normalizePath(path), normalizeMode(mode, 0x1ff));\n }\n\n /**\n * Asynchronous `readdir`. Reads the contents of a directory.\n * The callback gets two arguments `(err, files)` where `files` is an array of\n * the names of the files in the directory excluding `'.'` and `'..'`.\n * @param path\n * @param callback\n */\n public readdir(path: string, cb: BFSCallback = nopCb): void {\n const newCb = <(err: ApiError, files?: string[]) => void> wrapCb(cb, 2);\n try {\n path = normalizePath(path);\n assertRoot(this.root).readdir(path, newCb);\n } catch (e) {\n newCb(e);\n }\n }\n\n /**\n * Synchronous `readdir`. Reads the contents of a directory.\n * @param path\n * @return [String[]]\n */\n public readdirSync(path: string): string[] {\n path = normalizePath(path);\n return assertRoot(this.root).readdirSync(path);\n }\n\n // SYMLINK METHODS\n\n /**\n * Asynchronous `link`.\n * @param srcpath\n * @param dstpath\n * @param callback\n */\n public link(srcpath: string, dstpath: string, cb: BFSOneArgCallback = nopCb): void {\n const newCb = wrapCb(cb, 1);\n try {\n srcpath = normalizePath(srcpath);\n dstpath = normalizePath(dstpath);\n assertRoot(this.root).link(srcpath, dstpath, newCb);\n } catch (e) {\n newCb(e);\n }\n }\n\n /**\n * Synchronous `link`.\n * @param srcpath\n * @param dstpath\n */\n public linkSync(srcpath: string, dstpath: string): void {\n srcpath = normalizePath(srcpath);\n dstpath = normalizePath(dstpath);\n return assertRoot(this.root).linkSync(srcpath, dstpath);\n }\n\n /**\n * Asynchronous `symlink`.\n * @param srcpath\n * @param dstpath\n * @param type can be either `'dir'` or `'file'` (default is `'file'`)\n * @param callback\n */\n public symlink(srcpath: string, dstpath: string, cb?: BFSOneArgCallback): void;\n public symlink(srcpath: string, dstpath: string, type?: string, cb?: BFSOneArgCallback): void;\n public symlink(srcpath: string, dstpath: string, arg3?: any, cb: BFSOneArgCallback = nopCb): void {\n const type = typeof arg3 === 'string' ? arg3 : 'file';\n cb = typeof arg3 === 'function' ? arg3 : cb;\n const newCb = wrapCb(cb, 1);\n try {\n if (type !== 'file' && type !== 'dir') {\n return newCb(new ApiError(ErrorCode.EINVAL, \"Invalid type: \" + type));\n }\n srcpath = normalizePath(srcpath);\n dstpath = normalizePath(dstpath);\n assertRoot(this.root).symlink(srcpath, dstpath, type, newCb);\n } catch (e) {\n newCb(e);\n }\n }\n\n /**\n * Synchronous `symlink`.\n * @param srcpath\n * @param dstpath\n * @param type can be either `'dir'` or `'file'` (default is `'file'`)\n */\n public symlinkSync(srcpath: string, dstpath: string, type?: string): void {\n if (!type) {\n type = 'file';\n } else if (type !== 'file' && type !== 'dir') {\n throw new ApiError(ErrorCode.EINVAL, \"Invalid type: \" + type);\n }\n srcpath = normalizePath(srcpath);\n dstpath = normalizePath(dstpath);\n return assertRoot(this.root).symlinkSync(srcpath, dstpath, type);\n }\n\n /**\n * Asynchronous readlink.\n * @param path\n * @param callback\n */\n public readlink(path: string, cb: BFSCallback = nopCb): void {\n const newCb = wrapCb(cb, 2);\n try {\n path = normalizePath(path);\n assertRoot(this.root).readlink(path, newCb);\n } catch (e) {\n newCb(e);\n }\n }\n\n /**\n * Synchronous readlink.\n * @param path\n * @return [String]\n */\n public readlinkSync(path: string): string {\n path = normalizePath(path);\n return assertRoot(this.root).readlinkSync(path);\n }\n\n // PROPERTY OPERATIONS\n\n /**\n * Asynchronous `chown`.\n * @param path\n * @param uid\n * @param gid\n * @param callback\n */\n public chown(path: string, uid: number, gid: number, cb: BFSOneArgCallback = nopCb): void {\n const newCb = wrapCb(cb, 1);\n try {\n path = normalizePath(path);\n assertRoot(this.root).chown(path, false, uid, gid, newCb);\n } catch (e) {\n newCb(e);\n }\n }\n\n /**\n * Synchronous `chown`.\n * @param path\n * @param uid\n * @param gid\n */\n public chownSync(path: string, uid: number, gid: number): void {\n path = normalizePath(path);\n assertRoot(this.root).chownSync(path, false, uid, gid);\n }\n\n /**\n * Asynchronous `lchown`.\n * @param path\n * @param uid\n * @param gid\n * @param callback\n */\n public lchown(path: string, uid: number, gid: number, cb: BFSOneArgCallback = nopCb): void {\n const newCb = wrapCb(cb, 1);\n try {\n path = normalizePath(path);\n assertRoot(this.root).chown(path, true, uid, gid, newCb);\n } catch (e) {\n newCb(e);\n }\n }\n\n /**\n * Synchronous `lchown`.\n * @param path\n * @param uid\n * @param gid\n */\n public lchownSync(path: string, uid: number, gid: number): void {\n path = normalizePath(path);\n assertRoot(this.root).chownSync(path, true, uid, gid);\n }\n\n /**\n * Asynchronous `chmod`.\n * @param path\n * @param mode\n * @param callback\n */\n public chmod(path: string, mode: number | string, cb: BFSOneArgCallback = nopCb): void {\n const newCb = wrapCb(cb, 1);\n try {\n const numMode = normalizeMode(mode, -1);\n if (numMode < 0) {\n throw new ApiError(ErrorCode.EINVAL, `Invalid mode.`);\n }\n assertRoot(this.root).chmod(normalizePath(path), false, numMode, newCb);\n } catch (e) {\n newCb(e);\n }\n }\n\n /**\n * Synchronous `chmod`.\n * @param path\n * @param mode\n */\n public chmodSync(path: string, mode: string | number): void {\n const numMode = normalizeMode(mode, -1);\n if (numMode < 0) {\n throw new ApiError(ErrorCode.EINVAL, `Invalid mode.`);\n }\n path = normalizePath(path);\n assertRoot(this.root).chmodSync(path, false, numMode);\n }\n\n /**\n * Asynchronous `lchmod`.\n * @param path\n * @param mode\n * @param callback\n */\n public lchmod(path: string, mode: number | string, cb: BFSOneArgCallback = nopCb): void {\n const newCb = wrapCb(cb, 1);\n try {\n const numMode = normalizeMode(mode, -1);\n if (numMode < 0) {\n throw new ApiError(ErrorCode.EINVAL, `Invalid mode.`);\n }\n assertRoot(this.root).chmod(normalizePath(path), true, numMode, newCb);\n } catch (e) {\n newCb(e);\n }\n }\n\n /**\n * Synchronous `lchmod`.\n * @param path\n * @param mode\n */\n public lchmodSync(path: string, mode: number | string): void {\n const numMode = normalizeMode(mode, -1);\n if (numMode < 1) {\n throw new ApiError(ErrorCode.EINVAL, `Invalid mode.`);\n }\n assertRoot(this.root).chmodSync(normalizePath(path), true, numMode);\n }\n\n /**\n * Change file timestamps of the file referenced by the supplied path.\n * @param path\n * @param atime\n * @param mtime\n * @param callback\n */\n public utimes(path: string, atime: number | Date, mtime: number | Date, cb: BFSOneArgCallback = nopCb): void {\n const newCb = wrapCb(cb, 1);\n try {\n assertRoot(this.root).utimes(normalizePath(path), normalizeTime(atime), normalizeTime(mtime), newCb);\n } catch (e) {\n newCb(e);\n }\n }\n\n /**\n * Change file timestamps of the file referenced by the supplied path.\n * @param path\n * @param atime\n * @param mtime\n */\n public utimesSync(path: string, atime: number | Date, mtime: number | Date): void {\n assertRoot(this.root).utimesSync(normalizePath(path), normalizeTime(atime), normalizeTime(mtime));\n }\n\n /**\n * Asynchronous `realpath`. The callback gets two arguments\n * `(err, resolvedPath)`. May use `process.cwd` to resolve relative paths.\n *\n * @example Usage example\n * let cache = {'/etc':'/private/etc'};\n * fs.realpath('/etc/passwd', cache, function (err, resolvedPath) {\n * if (err) throw err;\n * console.log(resolvedPath);\n * });\n *\n * @param path\n * @param cache An object literal of mapped paths that can be used to\n * force a specific path resolution or avoid additional `fs.stat` calls for\n * known real paths.\n * @param callback\n */\n public realpath(path: string, cb?: BFSCallback): void;\n public realpath(path: string, cache: {[path: string]: string}, cb: BFSCallback): void;\n public realpath(path: string, arg2?: any, cb: BFSCallback = nopCb): void {\n const cache = typeof(arg2) === 'object' ? arg2 : {};\n cb = typeof(arg2) === 'function' ? arg2 : nopCb;\n const newCb = <(err: ApiError, resolvedPath?: string) => any> wrapCb(cb, 2);\n try {\n path = normalizePath(path);\n assertRoot(this.root).realpath(path, cache, newCb);\n } catch (e) {\n newCb(e);\n }\n }\n\n /**\n * Synchronous `realpath`.\n * @param path\n * @param cache An object literal of mapped paths that can be used to\n * force a specific path resolution or avoid additional `fs.stat` calls for\n * known real paths.\n * @return [String]\n */\n public realpathSync(path: string, cache: {[path: string]: string} = {}): string {\n path = normalizePath(path);\n return assertRoot(this.root).realpathSync(path, cache);\n }\n\n public watchFile(filename: string, listener: (curr: Stats, prev: Stats) => void): void;\n public watchFile(filename: string, options: { persistent?: boolean; interval?: number; }, listener: (curr: Stats, prev: Stats) => void): void;\n public watchFile(filename: string, arg2: any, listener: (curr: Stats, prev: Stats) => void = nopCb): void {\n throw new ApiError(ErrorCode.ENOTSUP);\n }\n\n public unwatchFile(filename: string, listener: (curr: Stats, prev: Stats) => void = nopCb): void {\n throw new ApiError(ErrorCode.ENOTSUP);\n }\n\n public watch(filename: string, listener?: (event: string, filename: string) => any): _fs.FSWatcher;\n public watch(filename: string, options: { persistent?: boolean; }, listener?: (event: string, filename: string) => any): _fs.FSWatcher;\n public watch(filename: string, arg2: any, listener: (event: string, filename: string) => any = nopCb): _fs.FSWatcher {\n throw new ApiError(ErrorCode.ENOTSUP);\n }\n\n public access(path: string, callback: (err: ApiError) => void): void;\n public access(path: string, mode: number, callback: (err: ApiError) => void): void;\n public access(path: string, arg2: any, cb: (e: ApiError) => void = nopCb): void {\n throw new ApiError(ErrorCode.ENOTSUP);\n }\n\n public accessSync(path: string, mode?: number): void {\n throw new ApiError(ErrorCode.ENOTSUP);\n }\n\n public createReadStream(path: string, options?: {\n flags?: string;\n encoding?: string;\n fd?: number;\n mode?: number;\n autoClose?: boolean;\n }): _fs.ReadStream {\n throw new ApiError(ErrorCode.ENOTSUP);\n }\n\n public createWriteStream(path: string, options?: {\n flags?: string;\n encoding?: string;\n fd?: number;\n mode?: number;\n }): _fs.WriteStream {\n throw new ApiError(ErrorCode.ENOTSUP);\n }\n\n /**\n * For unit testing. Passes all incoming callbacks to cbWrapper for wrapping.\n */\n public wrapCallbacks(cbWrapper: (cb: Function, args: number) => Function) {\n wrapCb = cbWrapper;\n }\n\n private getFdForFile(file: File): number {\n const fd = this.nextFd++;\n this.fdMap[fd] = file;\n return fd;\n }\n private fd2file(fd: number): File {\n const rv = this.fdMap[fd];\n if (rv) {\n return rv;\n } else {\n throw new ApiError(ErrorCode.EBADF, 'Invalid file descriptor.');\n }\n }\n private closeFd(fd: number): void {\n delete this.fdMap[fd];\n }\n}\n\nexport interface FSModule extends FS {\n /**\n * The FS constructor.\n */\n FS: typeof FS;\n /**\n * Retrieve the FS object backing the fs module.\n */\n getFSModule(): FS;\n /**\n * Set the FS object backing the fs module.\n */\n changeFSModule(newFs: FS): void;\n}\n\n\n\n// WEBPACK FOOTER //\n// ../../../../src/core/FS.ts","/*\n * Levenshtein distance, from the `js-levenshtein` NPM module.\n * Copied here to avoid complexity of adding another CommonJS module dependency.\n */\n\nfunction _min(d0: number, d1: number, d2: number, bx: number, ay: number): number {\n return d0 < d1 || d2 < d1\n ? d0 > d2\n ? d2 + 1\n : d0 + 1\n : bx === ay\n ? d1\n : d1 + 1;\n}\n\n/**\n * Calculates levenshtein distance.\n * @param a\n * @param b\n */\nexport default function levenshtein(a: string, b: string): number {\n if (a === b) {\n return 0;\n }\n\n if (a.length > b.length) {\n const tmp = a;\n a = b;\n b = tmp;\n }\n\n let la = a.length;\n let lb = b.length;\n\n while (la > 0 && (a.charCodeAt(la - 1) === b.charCodeAt(lb - 1))) {\n la--;\n lb--;\n }\n\n let offset = 0;\n\n while (offset < la && (a.charCodeAt(offset) === b.charCodeAt(offset))) {\n offset++;\n }\n\n la -= offset;\n lb -= offset;\n\n if (la === 0 || lb === 1) {\n return lb;\n }\n\n const vector = new Array(la << 1);\n\n for (let y = 0; y < la; ) {\n vector[la + y] = a.charCodeAt(offset + y);\n vector[y] = ++y;\n }\n\n let x: number;\n let d0: number;\n let d1: number;\n let d2: number;\n let d3: number;\n for (x = 0; (x + 3) < lb; ) {\n const bx0 = b.charCodeAt(offset + (d0 = x));\n const bx1 = b.charCodeAt(offset + (d1 = x + 1));\n const bx2 = b.charCodeAt(offset + (d2 = x + 2));\n const bx3 = b.charCodeAt(offset + (d3 = x + 3));\n let dd = (x += 4);\n for (let y = 0; y < la; ) {\n const ay = vector[la + y];\n const dy = vector[y];\n d0 = _min(dy, d0, d1, bx0, ay);\n d1 = _min(d0, d1, d2, bx1, ay);\n d2 = _min(d1, d2, d3, bx2, ay);\n dd = _min(d2, d3, dd, bx3, ay);\n vector[y++] = dd;\n d3 = d2;\n d2 = d1;\n d1 = d0;\n d0 = dy;\n }\n }\n\n let dd: number = 0;\n for (; x < lb; ) {\n const bx0 = b.charCodeAt(offset + (d0 = x));\n dd = ++x;\n for (let y = 0; y < la; y++) {\n const dy = vector[y];\n vector[y] = dd = dy < d0 || dd < d0\n ? dy > dd ? dd + 1 : dy + 1\n : bx0 === vector[la + y]\n ? d0\n : d0 + 1;\n d0 = dy;\n }\n }\n\n return dd;\n}\n\n\n\n// WEBPACK FOOTER //\n// ../../../../src/core/levenshtein.ts","/**\n * Grab bag of utility functions used across the code.\n */\nimport {FileSystem, BFSOneArgCallback, FileSystemConstructor} from './file_system';\nimport {ErrorCode, ApiError} from './api_error';\nimport levenshtein from './levenshtein';\nimport * as path from 'path';\n\nexport function deprecationMessage(print: boolean, fsName: string, opts: any): void {\n if (print) {\n console.warn(`[${fsName}] Direct file system constructor usage is deprecated for this file system, and will be removed in the next major version. Please use the '${fsName}.Create(${JSON.stringify(opts)}, callback)' method instead. See https://github.com/jvilk/BrowserFS/issues/176 for more details.`);\n }\n}\n\n/**\n * Checks for any IE version, including IE11 which removed MSIE from the\n * userAgent string.\n * @hidden\n */\nexport const isIE: boolean = typeof navigator !== \"undefined\" && !!(/(msie) ([\\w.]+)/.exec(navigator.userAgent.toLowerCase()) || navigator.userAgent.indexOf('Trident') !== -1);\n\n/**\n * Check if we're in a web worker.\n * @hidden\n */\nexport const isWebWorker: boolean = typeof window === \"undefined\";\n\n/**\n * @hidden\n */\nexport interface Arrayish {\n [idx: number]: T;\n length: number;\n}\n\n/**\n * Throws an exception. Called on code paths that should be impossible.\n * @hidden\n */\nexport function fail() {\n throw new Error(\"BFS has reached an impossible code path; please file a bug.\");\n}\n\n/**\n * Synchronous recursive makedir.\n * @hidden\n */\nexport function mkdirpSync(p: string, mode: number, fs: FileSystem): void {\n if (!fs.existsSync(p)) {\n mkdirpSync(path.dirname(p), mode, fs);\n fs.mkdirSync(p, mode);\n }\n}\n\n/**\n * Converts a buffer into an array buffer. Attempts to do so in a\n * zero-copy manner, e.g. the array references the same memory.\n * @hidden\n */\nexport function buffer2ArrayBuffer(buff: Buffer): ArrayBuffer {\n const u8 = buffer2Uint8array(buff),\n u8offset = u8.byteOffset,\n u8Len = u8.byteLength;\n if (u8offset === 0 && u8Len === u8.buffer.byteLength) {\n return u8.buffer;\n } else {\n return u8.buffer.slice(u8offset, u8offset + u8Len);\n }\n}\n\n/**\n * Converts a buffer into a Uint8Array. Attempts to do so in a\n * zero-copy manner, e.g. the array references the same memory.\n * @hidden\n */\nexport function buffer2Uint8array(buff: Buffer): Uint8Array {\n if (buff instanceof Uint8Array) {\n // BFS & Node v4.0 buffers *are* Uint8Arrays.\n return buff;\n } else {\n // Uint8Arrays can be constructed from arrayish numbers.\n // At this point, we assume this isn't a BFS array.\n return new Uint8Array(buff);\n }\n}\n\n/**\n * Converts the given arrayish object into a Buffer. Attempts to\n * be zero-copy.\n * @hidden\n */\nexport function arrayish2Buffer(arr: Arrayish): Buffer {\n if (arr instanceof Buffer) {\n return arr;\n } else if (arr instanceof Uint8Array) {\n return uint8Array2Buffer(arr);\n } else {\n return Buffer.from( arr);\n }\n}\n\n/**\n * Converts the given Uint8Array into a Buffer. Attempts to be zero-copy.\n * @hidden\n */\nexport function uint8Array2Buffer(u8: Uint8Array): Buffer {\n if (u8 instanceof Buffer) {\n return u8;\n } else if (u8.byteOffset === 0 && u8.byteLength === u8.buffer.byteLength) {\n return arrayBuffer2Buffer(u8.buffer);\n } else {\n return Buffer.from(u8.buffer, u8.byteOffset, u8.byteLength);\n }\n}\n\n/**\n * Converts the given array buffer into a Buffer. Attempts to be\n * zero-copy.\n * @hidden\n */\nexport function arrayBuffer2Buffer(ab: ArrayBuffer): Buffer {\n return Buffer.from(ab);\n}\n\n/**\n * Copies a slice of the given buffer\n * @hidden\n */\nexport function copyingSlice(buff: Buffer, start: number = 0, end = buff.length): Buffer {\n if (start < 0 || end < 0 || end > buff.length || start > end) {\n throw new TypeError(`Invalid slice bounds on buffer of length ${buff.length}: [${start}, ${end}]`);\n }\n if (buff.length === 0) {\n // Avoid s0 corner case in ArrayBuffer case.\n return emptyBuffer();\n } else {\n const u8 = buffer2Uint8array(buff),\n s0 = buff[0],\n newS0 = (s0 + 1) % 0xFF;\n\n buff[0] = newS0;\n if (u8[0] === newS0) {\n // Same memory. Revert & copy.\n u8[0] = s0;\n return uint8Array2Buffer(u8.slice(start, end));\n } else {\n // Revert.\n buff[0] = s0;\n return uint8Array2Buffer(u8.subarray(start, end));\n }\n }\n}\n\n/**\n * @hidden\n */\nlet emptyBuff: Buffer | null = null;\n/**\n * Returns an empty buffer.\n * @hidden\n */\nexport function emptyBuffer(): Buffer {\n if (emptyBuff) {\n return emptyBuff;\n }\n return emptyBuff = Buffer.alloc(0);\n}\n\n/**\n * Option validator for a Buffer file system option.\n * @hidden\n */\nexport function bufferValidator(v: object, cb: BFSOneArgCallback): void {\n if (Buffer.isBuffer(v)) {\n cb();\n } else {\n cb(new ApiError(ErrorCode.EINVAL, `option must be a Buffer.`));\n }\n}\n\n/**\n * Checks that the given options object is valid for the file system options.\n * @hidden\n */\nexport function checkOptions(fsType: FileSystemConstructor, opts: any, cb: BFSOneArgCallback): void {\n const optsInfo = fsType.Options;\n const fsName = fsType.Name;\n\n let pendingValidators = 0;\n let callbackCalled = false;\n let loopEnded = false;\n function validatorCallback(e?: ApiError): void {\n if (!callbackCalled) {\n if (e) {\n callbackCalled = true;\n cb(e);\n }\n pendingValidators--;\n if (pendingValidators === 0 && loopEnded) {\n cb();\n }\n }\n }\n\n // Check for required options.\n for (const optName in optsInfo) {\n if (optsInfo.hasOwnProperty(optName)) {\n const opt = optsInfo[optName];\n const providedValue = opts[optName];\n\n if (providedValue === undefined || providedValue === null) {\n if (!opt.optional) {\n // Required option, not provided.\n // Any incorrect options provided? Which ones are close to the provided one?\n // (edit distance 5 === close)\n const incorrectOptions = Object.keys(opts).filter((o) => !(o in optsInfo)).map((a: string) => {\n return {str: a, distance: levenshtein(optName, a)};\n }).filter((o) => o.distance < 5).sort((a, b) => a.distance - b.distance);\n // Validators may be synchronous.\n if (callbackCalled) {\n return;\n }\n callbackCalled = true;\n return cb(new ApiError(ErrorCode.EINVAL, `[${fsName}] Required option '${optName}' not provided.${incorrectOptions.length > 0 ? ` You provided unrecognized option '${incorrectOptions[0].str}'; perhaps you meant to type '${optName}'.` : ''}\\nOption description: ${opt.description}`));\n }\n // Else: Optional option, not provided. That is OK.\n } else {\n // Option provided! Check type.\n let typeMatches = false;\n if (Array.isArray(opt.type)) {\n typeMatches = opt.type.indexOf(typeof(providedValue)) !== -1;\n } else {\n typeMatches = typeof(providedValue) === opt.type;\n }\n if (!typeMatches) {\n // Validators may be synchronous.\n if (callbackCalled) {\n return;\n }\n callbackCalled = true;\n return cb(new ApiError(ErrorCode.EINVAL, `[${fsName}] Value provided for option ${optName} is not the proper type. Expected ${Array.isArray(opt.type) ? `one of {${opt.type.join(\", \")}}` : opt.type}, but received ${typeof(providedValue)}\\nOption description: ${opt.description}`));\n } else if (opt.validator) {\n pendingValidators++;\n opt.validator(providedValue, validatorCallback);\n }\n // Otherwise: All good!\n }\n }\n }\n loopEnded = true;\n if (pendingValidators === 0 && !callbackCalled) {\n cb();\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ../../../../src/core/util.ts","/**\n * A faster alternative to `Function#apply`, this function invokes `func`\n * with the `this` binding of `thisArg` and the arguments of `args`.\n *\n * @private\n * @param {Function} func The function to invoke.\n * @param {*} thisArg The `this` binding of `func`.\n * @param {Array} args The arguments to invoke `func` with.\n * @returns {*} Returns the result of `func`.\n */\nfunction apply(func, thisArg, args) {\n switch (args.length) {\n case 0: return func.call(thisArg);\n case 1: return func.call(thisArg, args[0]);\n case 2: return func.call(thisArg, args[0], args[1]);\n case 3: return func.call(thisArg, args[0], args[1], args[2]);\n }\n return func.apply(thisArg, args);\n}\n\nexport default apply;\n\n\n\n// WEBPACK FOOTER //\n// ../../../../~/lodash-es/_apply.js","import apply from './_apply.js';\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeMax = Math.max;\n\n/**\n * A specialized version of `baseRest` which transforms the rest array.\n *\n * @private\n * @param {Function} func The function to apply a rest parameter to.\n * @param {number} [start=func.length-1] The start position of the rest parameter.\n * @param {Function} transform The rest array transform.\n * @returns {Function} Returns the new function.\n */\nfunction overRest(func, start, transform) {\n start = nativeMax(start === undefined ? (func.length - 1) : start, 0);\n return function() {\n var args = arguments,\n index = -1,\n length = nativeMax(args.length - start, 0),\n array = Array(length);\n\n while (++index < length) {\n array[index] = args[start + index];\n }\n index = -1;\n var otherArgs = Array(start + 1);\n while (++index < start) {\n otherArgs[index] = args[index];\n }\n otherArgs[start] = transform(array);\n return apply(func, this, otherArgs);\n };\n}\n\nexport default overRest;\n\n\n\n// WEBPACK FOOTER //\n// ../../../../~/lodash-es/_overRest.js","/**\n * This method returns the first argument it receives.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Util\n * @param {*} value Any value.\n * @returns {*} Returns `value`.\n * @example\n *\n * var object = { 'a': 1 };\n *\n * console.log(_.identity(object) === object);\n * // => true\n */\nfunction identity(value) {\n return value;\n}\n\nexport default identity;\n\n\n\n// WEBPACK FOOTER //\n// ../../../../~/lodash-es/identity.js","import _overRest from 'lodash-es/_overRest';\nimport identity from 'lodash-es/identity';\n\n// Lodash rest function without function.toString()\n// remappings\nexport default function rest(func, start) {\n return _overRest(func, start, identity);\n}\n\n\n\n// WEBPACK FOOTER //\n// ../../../../~/async-es/internal/rest.js","import rest from './rest';\nimport initialParams from './initialParams';\n\nexport default function applyEach(eachfn) {\n return rest(function(fns, args) {\n var go = initialParams(function(args, callback) {\n var that = this;\n return eachfn(fns, function (fn, cb) {\n fn.apply(that, args.concat(cb));\n }, callback);\n });\n if (args.length) {\n return go.apply(this, args);\n }\n else {\n return go;\n }\n });\n}\n\n\n\n// WEBPACK FOOTER //\n// ../../../../~/async-es/internal/applyEach.js","import Symbol from './_Symbol.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar nativeObjectToString = objectProto.toString;\n\n/** Built-in value references. */\nvar symToStringTag = Symbol ? Symbol.toStringTag : undefined;\n\n/**\n * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the raw `toStringTag`.\n */\nfunction getRawTag(value) {\n var isOwn = hasOwnProperty.call(value, symToStringTag),\n tag = value[symToStringTag];\n\n try {\n value[symToStringTag] = undefined;\n var unmasked = true;\n } catch (e) {}\n\n var result = nativeObjectToString.call(value);\n if (unmasked) {\n if (isOwn) {\n value[symToStringTag] = tag;\n } else {\n delete value[symToStringTag];\n }\n }\n return result;\n}\n\nexport default getRawTag;\n\n\n\n// WEBPACK FOOTER //\n// ../../../../~/lodash-es/_getRawTag.js","/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar nativeObjectToString = objectProto.toString;\n\n/**\n * Converts `value` to a string using `Object.prototype.toString`.\n *\n * @private\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n */\nfunction objectToString(value) {\n return nativeObjectToString.call(value);\n}\n\nexport default objectToString;\n\n\n\n// WEBPACK FOOTER //\n// ../../../../~/lodash-es/_objectToString.js","import Symbol from './_Symbol.js';\nimport getRawTag from './_getRawTag.js';\nimport objectToString from './_objectToString.js';\n\n/** `Object#toString` result references. */\nvar nullTag = '[object Null]',\n undefinedTag = '[object Undefined]';\n\n/** Built-in value references. */\nvar symToStringTag = Symbol ? Symbol.toStringTag : undefined;\n\n/**\n * The base implementation of `getTag` without fallbacks for buggy environments.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\nfunction baseGetTag(value) {\n if (value == null) {\n return value === undefined ? undefinedTag : nullTag;\n }\n return (symToStringTag && symToStringTag in Object(value))\n ? getRawTag(value)\n : objectToString(value);\n}\n\nexport default baseGetTag;\n\n\n\n// WEBPACK FOOTER //\n// ../../../../~/lodash-es/_baseGetTag.js","/**\n * Checks if `value` is the\n * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)\n * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an object, else `false`.\n * @example\n *\n * _.isObject({});\n * // => true\n *\n * _.isObject([1, 2, 3]);\n * // => true\n *\n * _.isObject(_.noop);\n * // => true\n *\n * _.isObject(null);\n * // => false\n */\nfunction isObject(value) {\n var type = typeof value;\n return value != null && (type == 'object' || type == 'function');\n}\n\nexport default isObject;\n\n\n\n// WEBPACK FOOTER //\n// ../../../../~/lodash-es/isObject.js","import baseGetTag from './_baseGetTag.js';\nimport isObject from './isObject.js';\n\n/** `Object#toString` result references. */\nvar asyncTag = '[object AsyncFunction]',\n funcTag = '[object Function]',\n genTag = '[object GeneratorFunction]',\n proxyTag = '[object Proxy]';\n\n/**\n * Checks if `value` is classified as a `Function` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a function, else `false`.\n * @example\n *\n * _.isFunction(_);\n * // => true\n *\n * _.isFunction(/abc/);\n * // => false\n */\nfunction isFunction(value) {\n if (!isObject(value)) {\n return false;\n }\n // The use of `Object#toString` avoids issues with the `typeof` operator\n // in Safari 9 which returns 'object' for typed arrays and other constructors.\n var tag = baseGetTag(value);\n return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;\n}\n\nexport default isFunction;\n\n\n\n// WEBPACK FOOTER //\n// ../../../../~/lodash-es/isFunction.js","/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/**\n * Checks if `value` is a valid array-like length.\n *\n * **Note:** This method is loosely based on\n * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.\n * @example\n *\n * _.isLength(3);\n * // => true\n *\n * _.isLength(Number.MIN_VALUE);\n * // => false\n *\n * _.isLength(Infinity);\n * // => false\n *\n * _.isLength('3');\n * // => false\n */\nfunction isLength(value) {\n return typeof value == 'number' &&\n value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;\n}\n\nexport default isLength;\n\n\n\n// WEBPACK FOOTER //\n// ../../../../~/lodash-es/isLength.js","import isFunction from './isFunction.js';\nimport isLength from './isLength.js';\n\n/**\n * Checks if `value` is array-like. A value is considered array-like if it's\n * not a function and has a `value.length` that's an integer greater than or\n * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is array-like, else `false`.\n * @example\n *\n * _.isArrayLike([1, 2, 3]);\n * // => true\n *\n * _.isArrayLike(document.body.children);\n * // => true\n *\n * _.isArrayLike('abc');\n * // => true\n *\n * _.isArrayLike(_.noop);\n * // => false\n */\nfunction isArrayLike(value) {\n return value != null && isLength(value.length) && !isFunction(value);\n}\n\nexport default isArrayLike;\n\n\n\n// WEBPACK FOOTER //\n// ../../../../~/lodash-es/isArrayLike.js","/**\n * This method returns `undefined`.\n *\n * @static\n * @memberOf _\n * @since 2.3.0\n * @category Util\n * @example\n *\n * _.times(2, _.noop);\n * // => [undefined, undefined]\n */\nfunction noop() {\n // No operation performed.\n}\n\nexport default noop;\n\n\n\n// WEBPACK FOOTER //\n// ../../../../~/lodash-es/noop.js","export default function once(fn) {\n return function () {\n if (fn === null) return;\n var callFn = fn;\n fn = null;\n callFn.apply(this, arguments);\n };\n}\n\n\n\n// WEBPACK FOOTER //\n// ../../../../~/async-es/internal/once.js","/**\n * The base implementation of `_.times` without support for iteratee shorthands\n * or max array length checks.\n *\n * @private\n * @param {number} n The number of times to invoke `iteratee`.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the array of results.\n */\nfunction baseTimes(n, iteratee) {\n var index = -1,\n result = Array(n);\n\n while (++index < n) {\n result[index] = iteratee(index);\n }\n return result;\n}\n\nexport default baseTimes;\n\n\n\n// WEBPACK FOOTER //\n// ../../../../~/lodash-es/_baseTimes.js","/**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\nfunction isObjectLike(value) {\n return value != null && typeof value == 'object';\n}\n\nexport default isObjectLike;\n\n\n\n// WEBPACK FOOTER //\n// ../../../../~/lodash-es/isObjectLike.js","import baseGetTag from './_baseGetTag.js';\nimport isObjectLike from './isObjectLike.js';\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]';\n\n/**\n * The base implementation of `_.isArguments`.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an `arguments` object,\n */\nfunction baseIsArguments(value) {\n return isObjectLike(value) && baseGetTag(value) == argsTag;\n}\n\nexport default baseIsArguments;\n\n\n\n// WEBPACK FOOTER //\n// ../../../../~/lodash-es/_baseIsArguments.js","/**\n * This method returns `false`.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {boolean} Returns `false`.\n * @example\n *\n * _.times(2, _.stubFalse);\n * // => [false, false]\n */\nfunction stubFalse() {\n return false;\n}\n\nexport default stubFalse;\n\n\n\n// WEBPACK FOOTER //\n// ../../../../~/lodash-es/stubFalse.js","/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/** Used to detect unsigned integer values. */\nvar reIsUint = /^(?:0|[1-9]\\d*)$/;\n\n/**\n * Checks if `value` is a valid array-like index.\n *\n * @private\n * @param {*} value The value to check.\n * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.\n * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.\n */\nfunction isIndex(value, length) {\n length = length == null ? MAX_SAFE_INTEGER : length;\n return !!length &&\n (typeof value == 'number' || reIsUint.test(value)) &&\n (value > -1 && value % 1 == 0 && value < length);\n}\n\nexport default isIndex;\n\n\n\n// WEBPACK FOOTER //\n// ../../../../~/lodash-es/_isIndex.js","import baseGetTag from './_baseGetTag.js';\nimport isLength from './isLength.js';\nimport isObjectLike from './isObjectLike.js';\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]',\n arrayTag = '[object Array]',\n boolTag = '[object Boolean]',\n dateTag = '[object Date]',\n errorTag = '[object Error]',\n funcTag = '[object Function]',\n mapTag = '[object Map]',\n numberTag = '[object Number]',\n objectTag = '[object Object]',\n regexpTag = '[object RegExp]',\n setTag = '[object Set]',\n stringTag = '[object String]',\n weakMapTag = '[object WeakMap]';\n\nvar arrayBufferTag = '[object ArrayBuffer]',\n dataViewTag = '[object DataView]',\n float32Tag = '[object Float32Array]',\n float64Tag = '[object Float64Array]',\n int8Tag = '[object Int8Array]',\n int16Tag = '[object Int16Array]',\n int32Tag = '[object Int32Array]',\n uint8Tag = '[object Uint8Array]',\n uint8ClampedTag = '[object Uint8ClampedArray]',\n uint16Tag = '[object Uint16Array]',\n uint32Tag = '[object Uint32Array]';\n\n/** Used to identify `toStringTag` values of typed arrays. */\nvar typedArrayTags = {};\ntypedArrayTags[float32Tag] = typedArrayTags[float64Tag] =\ntypedArrayTags[int8Tag] = typedArrayTags[int16Tag] =\ntypedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =\ntypedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =\ntypedArrayTags[uint32Tag] = true;\ntypedArrayTags[argsTag] = typedArrayTags[arrayTag] =\ntypedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =\ntypedArrayTags[dataViewTag] = typedArrayTags[dateTag] =\ntypedArrayTags[errorTag] = typedArrayTags[funcTag] =\ntypedArrayTags[mapTag] = typedArrayTags[numberTag] =\ntypedArrayTags[objectTag] = typedArrayTags[regexpTag] =\ntypedArrayTags[setTag] = typedArrayTags[stringTag] =\ntypedArrayTags[weakMapTag] = false;\n\n/**\n * The base implementation of `_.isTypedArray` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.\n */\nfunction baseIsTypedArray(value) {\n return isObjectLike(value) &&\n isLength(value.length) && !!typedArrayTags[baseGetTag(value)];\n}\n\nexport default baseIsTypedArray;\n\n\n\n// WEBPACK FOOTER //\n// ../../../../~/lodash-es/_baseIsTypedArray.js","/**\n * The base implementation of `_.unary` without support for storing metadata.\n *\n * @private\n * @param {Function} func The function to cap arguments for.\n * @returns {Function} Returns the new capped function.\n */\nfunction baseUnary(func) {\n return function(value) {\n return func(value);\n };\n}\n\nexport default baseUnary;\n\n\n\n// WEBPACK FOOTER //\n// ../../../../~/lodash-es/_baseUnary.js","import baseTimes from './_baseTimes.js';\nimport isArguments from './isArguments.js';\nimport isArray from './isArray.js';\nimport isBuffer from './isBuffer.js';\nimport isIndex from './_isIndex.js';\nimport isTypedArray from './isTypedArray.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Creates an array of the enumerable property names of the array-like `value`.\n *\n * @private\n * @param {*} value The value to query.\n * @param {boolean} inherited Specify returning inherited property names.\n * @returns {Array} Returns the array of property names.\n */\nfunction arrayLikeKeys(value, inherited) {\n var isArr = isArray(value),\n isArg = !isArr && isArguments(value),\n isBuff = !isArr && !isArg && isBuffer(value),\n isType = !isArr && !isArg && !isBuff && isTypedArray(value),\n skipIndexes = isArr || isArg || isBuff || isType,\n result = skipIndexes ? baseTimes(value.length, String) : [],\n length = result.length;\n\n for (var key in value) {\n if ((inherited || hasOwnProperty.call(value, key)) &&\n !(skipIndexes && (\n // Safari 9 has enumerable `arguments.length` in strict mode.\n key == 'length' ||\n // Node.js 0.10 has enumerable non-index properties on buffers.\n (isBuff && (key == 'offset' || key == 'parent')) ||\n // PhantomJS 2 has enumerable non-index properties on typed arrays.\n (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||\n // Skip index properties.\n isIndex(key, length)\n ))) {\n result.push(key);\n }\n }\n return result;\n}\n\nexport default arrayLikeKeys;\n\n\n\n// WEBPACK FOOTER //\n// ../../../../~/lodash-es/_arrayLikeKeys.js","/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Checks if `value` is likely a prototype object.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.\n */\nfunction isPrototype(value) {\n var Ctor = value && value.constructor,\n proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;\n\n return value === proto;\n}\n\nexport default isPrototype;\n\n\n\n// WEBPACK FOOTER //\n// ../../../../~/lodash-es/_isPrototype.js","/**\n * Creates a unary function that invokes `func` with its argument transformed.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {Function} transform The argument transform.\n * @returns {Function} Returns the new function.\n */\nfunction overArg(func, transform) {\n return function(arg) {\n return func(transform(arg));\n };\n}\n\nexport default overArg;\n\n\n\n// WEBPACK FOOTER //\n// ../../../../~/lodash-es/_overArg.js","import isPrototype from './_isPrototype.js';\nimport nativeKeys from './_nativeKeys.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\nfunction baseKeys(object) {\n if (!isPrototype(object)) {\n return nativeKeys(object);\n }\n var result = [];\n for (var key in Object(object)) {\n if (hasOwnProperty.call(object, key) && key != 'constructor') {\n result.push(key);\n }\n }\n return result;\n}\n\nexport default baseKeys;\n\n\n\n// WEBPACK FOOTER //\n// ../../../../~/lodash-es/_baseKeys.js","import arrayLikeKeys from './_arrayLikeKeys.js';\nimport baseKeys from './_baseKeys.js';\nimport isArrayLike from './isArrayLike.js';\n\n/**\n * Creates an array of the own enumerable property names of `object`.\n *\n * **Note:** Non-object values are coerced to objects. See the\n * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)\n * for more details.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.keys(new Foo);\n * // => ['a', 'b'] (iteration order is not guaranteed)\n *\n * _.keys('hi');\n * // => ['0', '1']\n */\nfunction keys(object) {\n return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);\n}\n\nexport default keys;\n\n\n\n// WEBPACK FOOTER //\n// ../../../../~/lodash-es/keys.js","import isArrayLike from 'lodash-es/isArrayLike';\nimport getIterator from './getIterator';\nimport keys from 'lodash-es/keys';\n\nfunction createArrayIterator(coll) {\n var i = -1;\n var len = coll.length;\n return function next() {\n return ++i < len ? {value: coll[i], key: i} : null;\n }\n}\n\nfunction createES2015Iterator(iterator) {\n var i = -1;\n return function next() {\n var item = iterator.next();\n if (item.done)\n return null;\n i++;\n return {value: item.value, key: i};\n }\n}\n\nfunction createObjectIterator(obj) {\n var okeys = keys(obj);\n var i = -1;\n var len = okeys.length;\n return function next() {\n var key = okeys[++i];\n return i < len ? {value: obj[key], key: key} : null;\n };\n}\n\nexport default function iterator(coll) {\n if (isArrayLike(coll)) {\n return createArrayIterator(coll);\n }\n\n var iterator = getIterator(coll);\n return iterator ? createES2015Iterator(iterator) : createObjectIterator(coll);\n}\n\n\n\n// WEBPACK FOOTER //\n// ../../../../~/async-es/internal/iterator.js","export default function onlyOnce(fn) {\n return function() {\n if (fn === null) throw new Error(\"Callback was already called.\");\n var callFn = fn;\n fn = null;\n callFn.apply(this, arguments);\n };\n}\n\n\n\n// WEBPACK FOOTER //\n// ../../../../~/async-es/internal/onlyOnce.js","import noop from 'lodash-es/noop';\nimport once from './once';\n\nimport iterator from './iterator';\nimport onlyOnce from './onlyOnce';\n\nimport breakLoop from './breakLoop';\n\nexport default function _eachOfLimit(limit) {\n return function (obj, iteratee, callback) {\n callback = once(callback || noop);\n if (limit <= 0 || !obj) {\n return callback(null);\n }\n var nextElem = iterator(obj);\n var done = false;\n var running = 0;\n\n function iterateeCallback(err, value) {\n running -= 1;\n if (err) {\n done = true;\n callback(err);\n }\n else if (value === breakLoop || (done && running <= 0)) {\n done = true;\n return callback(null);\n }\n else {\n replenish();\n }\n }\n\n function replenish () {\n while (running < limit && !done) {\n var elem = nextElem();\n if (elem === null) {\n done = true;\n if (running <= 0) {\n callback(null);\n }\n return;\n }\n running += 1;\n iteratee(elem.value, elem.key, onlyOnce(iterateeCallback));\n }\n }\n\n replenish();\n };\n}\n\n\n\n// WEBPACK FOOTER //\n// ../../../../~/async-es/internal/eachOfLimit.js","import _eachOfLimit from './internal/eachOfLimit';\n\n/**\n * The same as [`eachOf`]{@link module:Collections.eachOf} but runs a maximum of `limit` async operations at a\n * time.\n *\n * @name eachOfLimit\n * @static\n * @memberOf module:Collections\n * @method\n * @see [async.eachOf]{@link module:Collections.eachOf}\n * @alias forEachOfLimit\n * @category Collection\n * @param {Array|Iterable|Object} coll - A collection to iterate over.\n * @param {number} limit - The maximum number of async operations at a time.\n * @param {Function} iteratee - A function to apply to each\n * item in `coll`. The `key` is the item's key, or index in the case of an\n * array. The iteratee is passed a `callback(err)` which must be called once it\n * has completed. If no error has occurred, the callback should be run without\n * arguments or with an explicit `null` argument. Invoked with\n * (item, key, callback).\n * @param {Function} [callback] - A callback which is called when all\n * `iteratee` functions have finished, or an error occurs. Invoked with (err).\n */\nexport default function eachOfLimit(coll, limit, iteratee, callback) {\n _eachOfLimit(limit)(coll, iteratee, callback);\n}\n\n\n\n// WEBPACK FOOTER //\n// ../../../../~/async-es/eachOfLimit.js","export default function doLimit(fn, limit) {\n return function (iterable, iteratee, callback) {\n return fn(iterable, limit, iteratee, callback);\n };\n}\n\n\n\n// WEBPACK FOOTER //\n// ../../../../~/async-es/internal/doLimit.js","import isArrayLike from 'lodash-es/isArrayLike';\n\nimport breakLoop from './internal/breakLoop';\nimport eachOfLimit from './eachOfLimit';\nimport doLimit from './internal/doLimit';\nimport noop from 'lodash-es/noop';\nimport once from './internal/once';\nimport onlyOnce from './internal/onlyOnce';\n\n// eachOf implementation optimized for array-likes\nfunction eachOfArrayLike(coll, iteratee, callback) {\n callback = once(callback || noop);\n var index = 0,\n completed = 0,\n length = coll.length;\n if (length === 0) {\n callback(null);\n }\n\n function iteratorCallback(err, value) {\n if (err) {\n callback(err);\n } else if ((++completed === length) || value === breakLoop) {\n callback(null);\n }\n }\n\n for (; index < length; index++) {\n iteratee(coll[index], index, onlyOnce(iteratorCallback));\n }\n}\n\n// a generic version of eachOf which can handle array, object, and iterator cases.\nvar eachOfGeneric = doLimit(eachOfLimit, Infinity);\n\n/**\n * Like [`each`]{@link module:Collections.each}, except that it passes the key (or index) as the second argument\n * to the iteratee.\n *\n * @name eachOf\n * @static\n * @memberOf module:Collections\n * @method\n * @alias forEachOf\n * @category Collection\n * @see [async.each]{@link module:Collections.each}\n * @param {Array|Iterable|Object} coll - A collection to iterate over.\n * @param {Function} iteratee - A function to apply to each\n * item in `coll`. The `key` is the item's key, or index in the case of an\n * array. The iteratee is passed a `callback(err)` which must be called once it\n * has completed. If no error has occurred, the callback should be run without\n * arguments or with an explicit `null` argument. Invoked with\n * (item, key, callback).\n * @param {Function} [callback] - A callback which is called when all\n * `iteratee` functions have finished, or an error occurs. Invoked with (err).\n * @example\n *\n * var obj = {dev: \"/dev.json\", test: \"/test.json\", prod: \"/prod.json\"};\n * var configs = {};\n *\n * async.forEachOf(obj, function (value, key, callback) {\n * fs.readFile(__dirname + value, \"utf8\", function (err, data) {\n * if (err) return callback(err);\n * try {\n * configs[key] = JSON.parse(data);\n * } catch (e) {\n * return callback(e);\n * }\n * callback();\n * });\n * }, function (err) {\n * if (err) console.error(err.message);\n * // configs is now a map of JSON data\n * doSomethingWith(configs);\n * });\n */\nexport default function(coll, iteratee, callback) {\n var eachOfImplementation = isArrayLike(coll) ? eachOfArrayLike : eachOfGeneric;\n eachOfImplementation(coll, iteratee, callback);\n}\n\n\n\n// WEBPACK FOOTER //\n// ../../../../~/async-es/eachOf.js","import eachOf from '../eachOf';\n\nexport default function doParallel(fn) {\n return function (obj, iteratee, callback) {\n return fn(eachOf, obj, iteratee, callback);\n };\n}\n\n\n\n// WEBPACK FOOTER //\n// ../../../../~/async-es/internal/doParallel.js","import noop from 'lodash-es/noop';\n\nexport default function _asyncMap(eachfn, arr, iteratee, callback) {\n callback = callback || noop;\n arr = arr || [];\n var results = [];\n var counter = 0;\n\n eachfn(arr, function (value, _, callback) {\n var index = counter++;\n iteratee(value, function (err, v) {\n results[index] = v;\n callback(err);\n });\n }, function (err) {\n callback(err, results);\n });\n}\n\n\n\n// WEBPACK FOOTER //\n// ../../../../~/async-es/internal/map.js","import eachOfLimit from './eachOfLimit';\n\nexport default function doParallelLimit(fn) {\n return function (obj, limit, iteratee, callback) {\n return fn(eachOfLimit(limit), obj, iteratee, callback);\n };\n}\n\n\n\n// WEBPACK FOOTER //\n// ../../../../~/async-es/internal/doParallelLimit.js","/**\n * A specialized version of `_.forEach` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns `array`.\n */\nfunction arrayEach(array, iteratee) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (iteratee(array[index], index, array) === false) {\n break;\n }\n }\n return array;\n}\n\nexport default arrayEach;\n\n\n\n// WEBPACK FOOTER //\n// ../../../../~/lodash-es/_arrayEach.js","/**\n * Creates a base function for methods like `_.forIn` and `_.forOwn`.\n *\n * @private\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {Function} Returns the new base function.\n */\nfunction createBaseFor(fromRight) {\n return function(object, iteratee, keysFunc) {\n var index = -1,\n iterable = Object(object),\n props = keysFunc(object),\n length = props.length;\n\n while (length--) {\n var key = props[fromRight ? length : ++index];\n if (iteratee(iterable[key], key, iterable) === false) {\n break;\n }\n }\n return object;\n };\n}\n\nexport default createBaseFor;\n\n\n\n// WEBPACK FOOTER //\n// ../../../../~/lodash-es/_createBaseFor.js","'use strict';\n\nimport rest from './rest';\n\nexport var hasSetImmediate = typeof setImmediate === 'function' && setImmediate;\nexport var hasNextTick = typeof process === 'object' && typeof process.nextTick === 'function';\n\nexport function fallback(fn) {\n setTimeout(fn, 0);\n}\n\nexport function wrap(defer) {\n return rest(function (fn, args) {\n defer(function () {\n fn.apply(null, args);\n });\n });\n}\n\nvar _defer;\n\nif (hasSetImmediate) {\n _defer = setImmediate;\n} else if (hasNextTick) {\n _defer = process.nextTick;\n} else {\n _defer = fallback;\n}\n\nexport default wrap(_defer);\n\n\n\n// WEBPACK FOOTER //\n// ../../../../~/async-es/internal/setImmediate.js","import eachOfSeries from './eachOfSeries';\nimport noop from 'lodash-es/noop';\nimport once from './internal/once';\n\n/**\n * Reduces `coll` into a single value using an async `iteratee` to return each\n * successive step. `memo` is the initial state of the reduction. This function\n * only operates in series.\n *\n * For performance reasons, it may make sense to split a call to this function\n * into a parallel map, and then use the normal `Array.prototype.reduce` on the\n * results. This function is for situations where each step in the reduction\n * needs to be async; if you can get the data before reducing it, then it's\n * probably a good idea to do so.\n *\n * @name reduce\n * @static\n * @memberOf module:Collections\n * @method\n * @alias inject\n * @alias foldl\n * @category Collection\n * @param {Array|Iterable|Object} coll - A collection to iterate over.\n * @param {*} memo - The initial state of the reduction.\n * @param {Function} iteratee - A function applied to each item in the\n * array to produce the next step in the reduction. The `iteratee` is passed a\n * `callback(err, reduction)` which accepts an optional error as its first\n * argument, and the state of the reduction as the second. If an error is\n * passed to the callback, the reduction is stopped and the main `callback` is\n * immediately called with the error. Invoked with (memo, item, callback).\n * @param {Function} [callback] - A callback which is called after all the\n * `iteratee` functions have finished. Result is the reduced value. Invoked with\n * (err, result).\n * @example\n *\n * async.reduce([1,2,3], 0, function(memo, item, callback) {\n * // pointless async:\n * process.nextTick(function() {\n * callback(null, memo + item)\n * });\n * }, function(err, result) {\n * // result is now equal to the last value of memo, which is 6\n * });\n */\nexport default function reduce(coll, memo, iteratee, callback) {\n callback = once(callback || noop);\n eachOfSeries(coll, function(x, i, callback) {\n iteratee(memo, x, function(err, v) {\n memo = v;\n callback(err);\n });\n }, function(err) {\n callback(err, memo);\n });\n}\n\n\n\n// WEBPACK FOOTER //\n// ../../../../~/async-es/reduce.js","import arrayEach from 'lodash-es/_arrayEach';\nimport rest from './rest';\n\nexport default function consoleFunc(name) {\n return rest(function (fn, args) {\n fn.apply(null, args.concat(rest(function (err, args) {\n if (typeof console === 'object') {\n if (err) {\n if (console.error) {\n console.error(err);\n }\n }\n else if (console[name]) {\n arrayEach(args, function (x) {\n console[name](x);\n });\n }\n }\n })));\n });\n}\n\n\n\n// WEBPACK FOOTER //\n// ../../../../~/async-es/internal/consoleFunc.js","export default function _withoutIndex(iteratee) {\n return function (value, index, callback) {\n return iteratee(value, callback);\n };\n}\n\n\n\n// WEBPACK FOOTER //\n// ../../../../~/async-es/internal/withoutIndex.js","import eachOf from './eachOf';\nimport withoutIndex from './internal/withoutIndex';\n\n/**\n * Applies the function `iteratee` to each item in `coll`, in parallel.\n * The `iteratee` is called with an item from the list, and a callback for when\n * it has finished. If the `iteratee` passes an error to its `callback`, the\n * main `callback` (for the `each` function) is immediately called with the\n * error.\n *\n * Note, that since this function applies `iteratee` to each item in parallel,\n * there is no guarantee that the iteratee functions will complete in order.\n *\n * @name each\n * @static\n * @memberOf module:Collections\n * @method\n * @alias forEach\n * @category Collection\n * @param {Array|Iterable|Object} coll - A collection to iterate over.\n * @param {Function} iteratee - A function to apply to each item\n * in `coll`. The iteratee is passed a `callback(err)` which must be called once\n * it has completed. If no error has occurred, the `callback` should be run\n * without arguments or with an explicit `null` argument. The array index is not\n * passed to the iteratee. Invoked with (item, callback). If you need the index,\n * use `eachOf`.\n * @param {Function} [callback] - A callback which is called when all\n * `iteratee` functions have finished, or an error occurs. Invoked with (err).\n * @example\n *\n * // assuming openFiles is an array of file names and saveFile is a function\n * // to save the modified contents of that file:\n *\n * async.each(openFiles, saveFile, function(err){\n * // if any of the saves produced an error, err would equal that error\n * });\n *\n * // assuming openFiles is an array of file names\n * async.each(openFiles, function(file, callback) {\n *\n * // Perform operation on file here.\n * console.log('Processing file ' + file);\n *\n * if( file.length > 32 ) {\n * console.log('This file name is too long');\n * callback('File name too long');\n * } else {\n * // Do work to process file here\n * console.log('File processed');\n * callback();\n * }\n * }, function(err) {\n * // if any of the file processing produced an error, err would equal that error\n * if( err ) {\n * // One of the iterations produced an error.\n * // All processing will now stop.\n * console.log('A file failed to process');\n * } else {\n * console.log('All files have been processed successfully');\n * }\n * });\n */\nexport default function eachLimit(coll, iteratee, callback) {\n eachOf(coll, withoutIndex(iteratee), callback);\n}\n\n\n\n// WEBPACK FOOTER //\n// ../../../../~/async-es/each.js","import PreloadFile from '../generic/preload_file';\nimport {BaseFileSystem, FileSystem, BFSOneArgCallback, BFSCallback, FileSystemOptions} from '../core/file_system';\nimport {FileFlag} from '../core/file_flag';\nimport {default as Stats, FileType} from '../core/node_fs_stats';\nimport {ApiError, ErrorCode} from '../core/api_error';\nimport {File} from '../core/file';\nimport {each as asyncEach} from 'async';\nimport * as path from 'path';\nimport {arrayBuffer2Buffer, buffer2ArrayBuffer, emptyBuffer, deprecationMessage} from '../core/util';\n\n/**\n * @hidden\n */\nlet errorCodeLookup: {[dropboxErrorCode: number]: ErrorCode};\n/**\n * Lazily construct error code lookup, since DropboxJS might be loaded *after* BrowserFS (or not at all!)\n * @hidden\n */\nfunction constructErrorCodeLookup() {\n if (errorCodeLookup) {\n return;\n }\n errorCodeLookup = {};\n // This indicates a network transmission error on modern browsers. Internet Explorer might cause this code to be reported on some API server errors.\n errorCodeLookup[Dropbox.ApiError.NETWORK_ERROR] = ErrorCode.EIO;\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.\n // errorCodeLookup[Dropbox.ApiError.NO_CONTENT];\n // The error property on {Dropbox.ApiError#response} should indicate which input parameter is invalid and why.\n errorCodeLookup[Dropbox.ApiError.INVALID_PARAM] = ErrorCode.EINVAL;\n // The OAuth token used for the request will never become valid again, so the user should be re-authenticated.\n errorCodeLookup[Dropbox.ApiError.INVALID_TOKEN] = ErrorCode.EPERM;\n // This indicates a bug in dropbox.js and should never occur under normal circumstances.\n // ^ Actually, that's false. This occurs when you try to move folders to themselves, or move a file over another file.\n errorCodeLookup[Dropbox.ApiError.OAUTH_ERROR] = ErrorCode.EPERM;\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.\n errorCodeLookup[Dropbox.ApiError.NOT_FOUND] = ErrorCode.ENOENT;\n // This indicates a bug in dropbox.js and should never occur under normal circumstances.\n errorCodeLookup[Dropbox.ApiError.INVALID_METHOD] = ErrorCode.EINVAL;\n // This happens when a Dropbox.Client#readdir or Dropbox.Client#stat call would return more than a maximum amount of directory entries.\n errorCodeLookup[Dropbox.ApiError.NOT_ACCEPTABLE] = ErrorCode.EINVAL;\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.\n errorCodeLookup[Dropbox.ApiError.CONFLICT] = ErrorCode.EINVAL;\n // Status value indicating that the application is making too many requests.\n errorCodeLookup[Dropbox.ApiError.RATE_LIMITED] = ErrorCode.EBUSY;\n // The request should be retried after some time.\n errorCodeLookup[Dropbox.ApiError.SERVER_ERROR] = ErrorCode.EBUSY;\n // Status value indicating that the user's Dropbox is over its storage quota.\n errorCodeLookup[Dropbox.ApiError.OVER_QUOTA] = ErrorCode.ENOSPC;\n}\n\n/**\n * @hidden\n */\ninterface ICachedPathInfo {\n stat: Dropbox.File.Stat;\n}\n\n/**\n * @hidden\n */\ninterface ICachedFileInfo extends ICachedPathInfo {\n contents: ArrayBuffer;\n}\n\n/**\n * @hidden\n */\nfunction isFileInfo(cache: ICachedPathInfo): cache is ICachedFileInfo {\n return cache && cache.stat.isFile;\n}\n\n/**\n * @hidden\n */\ninterface ICachedDirInfo extends ICachedPathInfo {\n contents: string[];\n}\n\n/**\n * @hidden\n */\nfunction isDirInfo(cache: ICachedPathInfo): cache is ICachedDirInfo {\n return cache && cache.stat.isFolder;\n}\n\n/**\n * @hidden\n */\nfunction isArrayBuffer(ab: any): ab is ArrayBuffer {\n // Accept null / undefined, too.\n return ab === null || ab === undefined || (typeof(ab) === 'object' && typeof(ab['byteLength']) === 'number');\n}\n\n/**\n * Wraps a Dropbox client and caches operations.\n * @hidden\n */\nclass CachedDropboxClient {\n private _cache: {[path: string]: ICachedPathInfo} = {};\n private _client: Dropbox.Client;\n\n constructor(client: Dropbox.Client) {\n this._client = client;\n }\n\n public readdir(p: string, cb: (error: Dropbox.ApiError | null, contents?: string[]) => void): void {\n const cacheInfo = this.getCachedDirInfo(p);\n\n this._wrap((interceptCb) => {\n if (cacheInfo !== null && cacheInfo.contents) {\n this._client.readdir(p, {\n contentHash: cacheInfo.stat.contentHash\n }, interceptCb);\n } else {\n this._client.readdir(p, interceptCb);\n }\n }, (err: Dropbox.ApiError, filenames: string[], stat: Dropbox.File.Stat, folderEntries: Dropbox.File.Stat[]) => {\n if (err) {\n if (err.status === Dropbox.ApiError.NO_CONTENT && cacheInfo !== null) {\n cb(null, cacheInfo.contents.slice(0));\n } else {\n cb(err);\n }\n } else {\n this.updateCachedDirInfo(p, stat, filenames.slice(0));\n folderEntries.forEach((entry) => {\n this.updateCachedInfo(path.join(p, entry.name), entry);\n });\n cb(null, filenames);\n }\n });\n }\n\n public remove(p: string, cb: (error?: Dropbox.ApiError | null) => void): void {\n this._wrap((interceptCb) => {\n this._client.remove(p, interceptCb);\n }, (err: Dropbox.ApiError, stat?: Dropbox.File.Stat) => {\n if (!err) {\n this.updateCachedInfo(p, stat!);\n }\n cb(err);\n });\n }\n\n public move(src: string, dest: string, cb: (error?: Dropbox.ApiError) => void): void {\n this._wrap((interceptCb) => {\n this._client.move(src, dest, interceptCb);\n }, (err: Dropbox.ApiError, stat: Dropbox.File.Stat) => {\n if (!err) {\n this.deleteCachedInfo(src);\n this.updateCachedInfo(dest, stat);\n }\n cb(err);\n });\n }\n\n public stat(p: string, cb: (error: Dropbox.ApiError, stat?: Dropbox.File.Stat) => void): void {\n this._wrap((interceptCb) => {\n this._client.stat(p, interceptCb);\n }, (err: Dropbox.ApiError, stat: Dropbox.File.Stat) => {\n if (!err) {\n this.updateCachedInfo(p, stat);\n }\n cb(err, stat);\n });\n }\n\n public readFile(p: string, cb: (error: Dropbox.ApiError, file?: ArrayBuffer, stat?: Dropbox.File.Stat) => void): void {\n const cacheInfo = this.getCachedFileInfo(p);\n if (cacheInfo !== null && cacheInfo.contents !== null) {\n // Try to use cached info; issue a stat to see if contents are up-to-date.\n this.stat(p, (error, stat?) => {\n if (error) {\n cb(error);\n } else if (stat!.contentHash === cacheInfo!.stat.contentHash) {\n // No file changes.\n cb(error, cacheInfo!.contents.slice(0), cacheInfo!.stat);\n } else {\n // File changes; rerun to trigger actual readFile.\n this.readFile(p, cb);\n }\n });\n } else {\n this._wrap((interceptCb) => {\n this._client.readFile(p, { arrayBuffer: true }, interceptCb);\n }, (err: Dropbox.ApiError, contents: any, stat: Dropbox.File.Stat) => {\n if (!err) {\n this.updateCachedInfo(p, stat, contents.slice(0));\n }\n cb(err, contents, stat);\n });\n }\n }\n\n public writeFile(p: string, contents: ArrayBuffer, cb: (error: Dropbox.ApiError, stat?: Dropbox.File.Stat) => void): void {\n this._wrap((interceptCb) => {\n this._client.writeFile(p, contents, interceptCb);\n }, (err: Dropbox.ApiError, stat: Dropbox.File.Stat) => {\n if (!err) {\n this.updateCachedInfo(p, stat, contents.slice(0));\n }\n cb(err, stat);\n });\n }\n\n public mkdir(p: string, cb: (error?: Dropbox.ApiError) => void): void {\n this._wrap((interceptCb) => {\n this._client.mkdir(p, interceptCb);\n }, (err: Dropbox.ApiError, stat: Dropbox.File.Stat) => {\n if (!err) {\n this.updateCachedInfo(p, stat, []);\n }\n cb(err);\n });\n }\n\n /**\n * Wraps an operation such that we retry a failed operation 3 times.\n * Necessary to deal with Dropbox rate limiting.\n *\n * @param performOp Function that performs the operation. Will be called up to three times.\n * @param cb Called when the operation succeeds, fails in a non-temporary manner, or fails three times.\n */\n private _wrap(performOp: (interceptCb: (error: Dropbox.ApiError) => void) => void, cb: Function): void {\n let numRun = 0;\n const interceptCb = function(error: Dropbox.ApiError): void {\n // Timeout duration, in seconds.\n const timeoutDuration: number = 2;\n if (error && 3 > (++numRun)) {\n switch (error.status) {\n case Dropbox.ApiError.SERVER_ERROR:\n case Dropbox.ApiError.NETWORK_ERROR:\n case Dropbox.ApiError.RATE_LIMITED:\n setTimeout(() => {\n performOp(interceptCb);\n }, timeoutDuration * 1000);\n break;\n default:\n cb.apply(null, arguments);\n break;\n }\n } else {\n cb.apply(null, arguments);\n }\n };\n\n performOp(interceptCb);\n }\n\n private getCachedInfo(p: string): ICachedPathInfo {\n return this._cache[p.toLowerCase()];\n }\n\n private putCachedInfo(p: string, cache: ICachedPathInfo): void {\n this._cache[p.toLowerCase()] = cache;\n }\n\n private deleteCachedInfo(p: string): void {\n delete this._cache[p.toLowerCase()];\n }\n\n private getCachedDirInfo(p: string): ICachedDirInfo | null {\n const info = this.getCachedInfo(p);\n if (isDirInfo(info)) {\n return info;\n } else {\n return null;\n }\n }\n\n private getCachedFileInfo(p: string): ICachedFileInfo | null {\n const info = this.getCachedInfo(p);\n if (isFileInfo(info)) {\n return info;\n } else {\n return null;\n }\n }\n\n private updateCachedDirInfo(p: string, stat: Dropbox.File.Stat, contents: string[] | null = null): void {\n const cachedInfo = this.getCachedInfo(p);\n // Dropbox uses the *contentHash* property for directories.\n // Ignore stat objects w/o a contentHash defined; those actually exist!!!\n // (Example: readdir returns an array of stat objs; stat objs for dirs in that context have no contentHash)\n if (stat.contentHash !== null && (cachedInfo === undefined || cachedInfo.stat.contentHash !== stat.contentHash)) {\n this.putCachedInfo(p, {\n stat: stat,\n contents: contents\n });\n }\n }\n\n private updateCachedFileInfo(p: string, stat: Dropbox.File.Stat, contents: ArrayBuffer | null = null): void {\n const cachedInfo = this.getCachedInfo(p);\n // Dropbox uses the *versionTag* property for files.\n // Ignore stat objects w/o a versionTag defined.\n if (stat.versionTag !== null && (cachedInfo === undefined || cachedInfo.stat.versionTag !== stat.versionTag)) {\n this.putCachedInfo(p, {\n stat: stat,\n contents: contents\n });\n }\n }\n\n private updateCachedInfo(p: string, stat: Dropbox.File.Stat, contents: ArrayBuffer | string[] | null = null): void {\n if (stat.isFile && isArrayBuffer(contents)) {\n this.updateCachedFileInfo(p, stat, contents);\n } else if (stat.isFolder && Array.isArray(contents)) {\n this.updateCachedDirInfo(p, stat, contents);\n }\n }\n}\n\nexport class DropboxFile extends PreloadFile implements File {\n constructor(_fs: DropboxFileSystem, _path: string, _flag: FileFlag, _stat: Stats, contents?: Buffer) {\n super(_fs, _path, _flag, _stat, contents);\n }\n\n public sync(cb: BFSOneArgCallback): void {\n if (this.isDirty()) {\n const buffer = this.getBuffer(),\n arrayBuffer = buffer2ArrayBuffer(buffer);\n this._fs._writeFileStrict(this.getPath(), arrayBuffer, (e?: ApiError) => {\n if (!e) {\n this.resetDirty();\n }\n cb(e);\n });\n } else {\n cb();\n }\n }\n\n public close(cb: BFSOneArgCallback): void {\n this.sync(cb);\n }\n}\n\n/**\n * Options for the Dropbox file system.\n */\nexport interface DropboxFileSystemOptions {\n // An *authenticated* Dropbox client. Must be from the 0.10 JS SDK.\n client: Dropbox.Client;\n}\n\n/**\n * A read/write file system backed by Dropbox cloud storage.\n *\n * Uses the Dropbox V1 API.\n *\n * NOTE: You must use the v0.10 version of the [Dropbox JavaScript SDK](https://www.npmjs.com/package/dropbox).\n */\nexport default class DropboxFileSystem extends BaseFileSystem implements FileSystem {\n public static readonly Name = \"Dropbox\";\n\n public static readonly Options: FileSystemOptions = {\n client: {\n type: \"object\",\n description: \"An *authenticated* Dropbox client. Must be from the 0.10 JS SDK.\",\n validator: (opt: Dropbox.Client, cb: BFSOneArgCallback): void => {\n if (opt.isAuthenticated && opt.isAuthenticated()) {\n cb();\n } else {\n cb(new ApiError(ErrorCode.EINVAL, `'client' option must be an authenticated Dropbox client from the v0.10 JS SDK.`));\n }\n }\n }\n };\n\n /**\n * Creates a new DropboxFileSystem instance with the given options.\n * Must be given an *authenticated* DropboxJS client from the old v0.10 version of the Dropbox JS SDK.\n */\n public static Create(opts: DropboxFileSystemOptions, cb: BFSCallback): void {\n cb(null, new DropboxFileSystem(opts.client, false));\n }\n\n public static isAvailable(): boolean {\n // Checks if the Dropbox library is loaded.\n return typeof Dropbox !== 'undefined';\n }\n\n // The Dropbox client.\n private _client: CachedDropboxClient;\n\n /**\n * **Deprecated. Please use Dropbox.Create() method instead.**\n *\n * Constructs a Dropbox-backed file system using the *authenticated* DropboxJS client.\n *\n * Note that you must use the old v0.10 version of the Dropbox JavaScript SDK.\n */\n constructor(client: Dropbox.Client, deprecateMsg = true) {\n super();\n this._client = new CachedDropboxClient(client);\n deprecationMessage(deprecateMsg, DropboxFileSystem.Name, { client: \"authenticated dropbox client instance\" });\n constructErrorCodeLookup();\n }\n\n public getName(): string {\n return DropboxFileSystem.Name;\n }\n\n public isReadOnly(): boolean {\n return false;\n }\n\n // Dropbox doesn't support symlinks, properties, or synchronous calls\n\n public supportsSymlinks(): boolean {\n return false;\n }\n\n public supportsProps(): boolean {\n return false;\n }\n\n public supportsSynch(): boolean {\n return false;\n }\n\n public empty(mainCb: BFSOneArgCallback): void {\n this._client.readdir('/', (error, files) => {\n if (error) {\n mainCb(this.convert(error, '/'));\n } else {\n const deleteFile = (file: string, cb: BFSOneArgCallback) => {\n const p = path.join('/', file);\n this._client.remove(p, (err) => {\n cb(err ? this.convert(err, p) : null);\n });\n };\n const finished = (err?: ApiError) => {\n if (err) {\n mainCb(err);\n } else {\n mainCb();\n }\n };\n // XXX: typing is to get around overly-restrictive ErrorCallback typing.\n asyncEach(files!, deleteFile, finished);\n }\n });\n }\n\n public rename(oldPath: string, newPath: string, cb: BFSOneArgCallback): void {\n this._client.move(oldPath, newPath, (error) => {\n if (error) {\n // the move is permitted if newPath is a file.\n // Check if this is the case, and remove if so.\n this._client.stat(newPath, (error2, stat) => {\n if (error2 || stat!.isFolder) {\n const missingPath = ( error.response).error.indexOf(oldPath) > -1 ? oldPath : newPath;\n cb(this.convert(error, missingPath));\n } else {\n // Delete file, repeat rename.\n this._client.remove(newPath, (error2) => {\n if (error2) {\n cb(this.convert(error2, newPath));\n } else {\n this.rename(oldPath, newPath, cb);\n }\n });\n }\n });\n } else {\n cb();\n }\n });\n }\n\n public stat(path: string, isLstat: boolean, cb: BFSCallback): void {\n // Ignore lstat case -- Dropbox doesn't support symlinks\n // Stat the file\n this._client.stat(path, (error, stat) => {\n if (error) {\n cb(this.convert(error, path));\n } else if (stat && stat.isRemoved) {\n // Dropbox keeps track of deleted files, so if a file has existed in the\n // past but doesn't any longer, you wont get an error\n cb(ApiError.FileError(ErrorCode.ENOENT, path));\n } else {\n const stats = new Stats(this._statType(stat!), stat!.size);\n return cb(null, stats);\n }\n });\n }\n\n public open(path: string, flags: FileFlag, mode: number, cb: BFSCallback): void {\n // Try and get the file's contents\n this._client.readFile(path, (error, content, dbStat) => {\n if (error) {\n // If the file's being opened for reading and doesn't exist, return an\n // error\n if (flags.isReadable()) {\n cb(this.convert(error, path));\n } else {\n switch (error.status) {\n // If it's being opened for writing or appending, create it so that\n // it can be written to\n case Dropbox.ApiError.NOT_FOUND:\n const ab = new ArrayBuffer(0);\n return this._writeFileStrict(path, ab, (error2: ApiError, stat?: Dropbox.File.Stat) => {\n if (error2) {\n cb(error2);\n } else {\n const file = this._makeFile(path, flags, stat!, arrayBuffer2Buffer(ab));\n cb(null, file);\n }\n });\n default:\n return cb(this.convert(error, path));\n }\n }\n } else {\n // No error\n let buffer: Buffer;\n // Dropbox.js seems to set `content` to `null` rather than to an empty\n // buffer when reading an empty file. Not sure why this is.\n if (content === null) {\n buffer = emptyBuffer();\n } else {\n buffer = arrayBuffer2Buffer(content!);\n }\n const file = this._makeFile(path, flags, dbStat!, buffer);\n return cb(null, file);\n }\n });\n }\n\n public _writeFileStrict(p: string, data: ArrayBuffer, cb: BFSCallback): void {\n const parent = path.dirname(p);\n this.stat(parent, false, (error: ApiError, stat?: Stats): void => {\n if (error) {\n cb(ApiError.FileError(ErrorCode.ENOENT, parent));\n } else {\n this._client.writeFile(p, data, (error2, stat) => {\n if (error2) {\n cb(this.convert(error2, p));\n } else {\n cb(null, stat);\n }\n });\n }\n });\n }\n\n /**\n * Private\n * Returns a BrowserFS object representing the type of a Dropbox.js stat object\n */\n public _statType(stat: Dropbox.File.Stat): FileType {\n return stat.isFile ? FileType.FILE : FileType.DIRECTORY;\n }\n\n /**\n * Private\n * Returns a BrowserFS object representing a File, created from the data\n * returned by calls to the Dropbox API.\n */\n public _makeFile(path: string, flag: FileFlag, stat: Dropbox.File.Stat, buffer: Buffer): DropboxFile {\n const type = this._statType(stat);\n const stats = new Stats(type, stat.size);\n return new DropboxFile(this, path, flag, stats, buffer);\n }\n\n /**\n * Private\n * Delete a file or directory from Dropbox\n * isFile should reflect which call was made to remove the it (`unlink` or\n * `rmdir`). If this doesn't match what's actually at `path`, an error will be\n * returned\n */\n public _remove(path: string, cb: BFSOneArgCallback, isFile: boolean): void {\n this._client.stat(path, (error, stat) => {\n if (error) {\n cb(this.convert(error, path));\n } else {\n if (stat!.isFile && !isFile) {\n cb(ApiError.FileError(ErrorCode.ENOTDIR, path));\n } else if (!stat!.isFile && isFile) {\n cb(ApiError.FileError(ErrorCode.EISDIR, path));\n } else {\n this._client.remove(path, (error) => {\n if (error) {\n cb(this.convert(error, path));\n } else {\n cb(null);\n }\n });\n }\n }\n });\n }\n\n /**\n * Delete a file\n */\n public unlink(path: string, cb: BFSOneArgCallback): void {\n this._remove(path, cb, true);\n }\n\n /**\n * Delete a directory\n */\n public rmdir(path: string, cb: BFSOneArgCallback): void {\n this._remove(path, cb, false);\n }\n\n /**\n * Create a directory\n */\n public mkdir(p: string, mode: number, cb: BFSOneArgCallback): void {\n // Dropbox.js' client.mkdir() behaves like `mkdir -p`, i.e. it creates a\n // directory and all its ancestors if they don't exist.\n // Node's fs.mkdir() behaves like `mkdir`, i.e. it throws an error if an attempt\n // is made to create a directory without a parent.\n // To handle this inconsistency, a check for the existence of `path`'s parent\n // must be performed before it is created, and an error thrown if it does\n // not exist\n const parent = path.dirname(p);\n this._client.stat(parent, (error, stat) => {\n if (error) {\n cb(this.convert(error, parent));\n } else {\n this._client.mkdir(p, (error) => {\n if (error) {\n cb(ApiError.FileError(ErrorCode.EEXIST, p));\n } else {\n cb(null);\n }\n });\n }\n });\n }\n\n /**\n * Get the names of the files in a directory\n */\n public readdir(path: string, cb: BFSCallback): void {\n this._client.readdir(path, (error, files) => {\n if (error) {\n return cb(this.convert(error));\n } else {\n return cb(null, files);\n }\n });\n }\n\n /**\n * Converts a Dropbox-JS error into a BFS error.\n */\n public convert(err: Dropbox.ApiError, path: string | null = null): ApiError {\n let errorCode = errorCodeLookup[err.status];\n if (errorCode === undefined) {\n errorCode = ErrorCode.EIO;\n }\n\n if (!path) {\n return new ApiError(errorCode);\n } else {\n return ApiError.FileError(errorCode, path);\n }\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ../../../../src/backend/Dropbox.ts","import {SynchronousFileSystem, BFSOneArgCallback, BFSCallback, BFSThreeArgCallback, FileSystemOptions} from '../core/file_system';\nimport {default as Stats, FileType} from '../core/node_fs_stats';\nimport {FileFlag} from '../core/file_flag';\nimport {BaseFile, File} from '../core/file';\nimport {uint8Array2Buffer, buffer2Uint8array} from '../core/util';\nimport {ApiError, ErrorCode, ErrorStrings} from '../core/api_error';\nimport {EmscriptenFSNode} from '../generic/emscripten_fs';\n\n/**\n * @hidden\n */\ninterface EmscriptenError {\n node: EmscriptenFSNode;\n errno: number;\n}\n\n/**\n * @hidden\n */\nfunction convertError(e: EmscriptenError, path: string = ''): ApiError {\n const errno = e.errno;\n let parent = e.node;\n const paths: string[] = [];\n while (parent) {\n paths.unshift(parent.name);\n if (parent === parent.parent) {\n break;\n }\n parent = parent.parent;\n }\n return new ApiError(errno, ErrorStrings[errno], paths.length > 0 ? '/' + paths.join('/') : path);\n}\n\nexport class EmscriptenFile extends BaseFile implements File {\n constructor(\n private _fs: EmscriptenFileSystem,\n private _FS: any,\n private _path: string,\n private _stream: any) {\n super();\n }\n public getPos(): number | undefined {\n return undefined;\n }\n public close(cb: BFSOneArgCallback): void {\n let err: ApiError | null = null;\n try {\n this.closeSync();\n } catch (e) {\n err = e;\n } finally {\n cb(err);\n }\n }\n public closeSync(): void {\n try {\n this._FS.close(this._stream);\n } catch (e) {\n throw convertError(e, this._path);\n }\n }\n public stat(cb: BFSCallback): void {\n try {\n cb(null, this.statSync());\n } catch (e) {\n cb(e);\n }\n }\n public statSync(): Stats {\n try {\n return this._fs.statSync(this._path, false);\n } catch (e) {\n throw convertError(e, this._path);\n }\n }\n public truncate(len: number, cb: BFSOneArgCallback): void {\n let err: ApiError | null = null;\n try {\n this.truncateSync(len);\n } catch (e) {\n err = e;\n } finally {\n cb(err);\n }\n }\n public truncateSync(len: number): void {\n try {\n this._FS.ftruncate(this._stream.fd, len);\n } catch (e) {\n throw convertError(e, this._path);\n }\n }\n public write(buffer: NodeBuffer, offset: number, length: number, position: number, cb: BFSThreeArgCallback): void {\n try {\n cb(null, this.writeSync(buffer, offset, length, position), buffer);\n } catch (e) {\n cb(e);\n }\n }\n public writeSync(buffer: NodeBuffer, offset: number, length: number, position: number | null): number {\n try {\n const u8 = buffer2Uint8array(buffer);\n // Emscripten is particular about what position is set to.\n const emPosition = position === null ? undefined : position;\n return this._FS.write(this._stream, u8, offset, length, emPosition);\n } catch (e) {\n throw convertError(e, this._path);\n }\n }\n public read(buffer: NodeBuffer, offset: number, length: number, position: number, cb: BFSThreeArgCallback): void {\n try {\n cb(null, this.readSync(buffer, offset, length, position), buffer);\n } catch (e) {\n cb(e);\n }\n }\n public readSync(buffer: NodeBuffer, offset: number, length: number, position: number | null): number {\n try {\n const u8 = buffer2Uint8array(buffer);\n // Emscripten is particular about what position is set to.\n const emPosition = position === null ? undefined : position;\n return this._FS.read(this._stream, u8, offset, length, emPosition);\n } catch (e) {\n throw convertError(e, this._path);\n }\n }\n public sync(cb: BFSOneArgCallback): void {\n // NOP.\n cb();\n }\n public syncSync(): void {\n // NOP.\n }\n public chown(uid: number, gid: number, cb: BFSOneArgCallback): void {\n let err: ApiError | null = null;\n try {\n this.chownSync(uid, gid);\n } catch (e) {\n err = e;\n } finally {\n cb(err);\n }\n }\n public chownSync(uid: number, gid: number): void {\n try {\n this._FS.fchown(this._stream.fd, uid, gid);\n } catch (e) {\n throw convertError(e, this._path);\n }\n }\n public chmod(mode: number, cb: BFSOneArgCallback): void {\n let err: ApiError | null = null;\n try {\n this.chmodSync(mode);\n } catch (e) {\n err = e;\n } finally {\n cb(err);\n }\n }\n public chmodSync(mode: number): void {\n try {\n this._FS.fchmod(this._stream.fd, mode);\n } catch (e) {\n throw convertError(e, this._path);\n }\n }\n public utimes(atime: Date, mtime: Date, cb: BFSOneArgCallback): void {\n let err: ApiError | null = null;\n try {\n this.utimesSync(atime, mtime);\n } catch (e) {\n err = e;\n } finally {\n cb(err);\n }\n }\n public utimesSync(atime: Date, mtime: Date): void {\n this._fs.utimesSync(this._path, atime, mtime);\n }\n}\n\n/**\n * Configuration options for Emscripten file systems.\n */\nexport interface EmscriptenFileSystemOptions {\n // The Emscripten file system to use (`FS`)\n FS: any;\n}\n\n/**\n * Mounts an Emscripten file system into the BrowserFS file system.\n */\nexport default class EmscriptenFileSystem extends SynchronousFileSystem {\n public static readonly Name = \"EmscriptenFileSystem\";\n\n public static readonly Options: FileSystemOptions = {\n FS: {\n type: \"object\",\n description: \"The Emscripten file system to use (the `FS` variable)\"\n }\n };\n\n /**\n * Create an EmscriptenFileSystem instance with the given options.\n */\n public static Create(opts: EmscriptenFileSystemOptions, cb: BFSCallback): void {\n cb(null, new EmscriptenFileSystem(opts.FS));\n }\n public static isAvailable(): boolean { return true; }\n\n private _FS: any;\n\n /**\n * Creates a BrowserFS file system for the given Emscripten file system.\n * @param _FS The Emscripten file system (`FS`).\n */\n constructor(_FS: any) {\n super();\n this._FS = _FS;\n }\n public getName(): string { return this._FS.DB_NAME(); }\n public isReadOnly(): boolean { return false; }\n public supportsLinks(): boolean { return true; }\n public supportsProps(): boolean { return true; }\n public supportsSynch(): boolean { return true; }\n\n public renameSync(oldPath: string, newPath: string): void {\n try {\n this._FS.rename(oldPath, newPath);\n } catch (e) {\n if (e.errno === ErrorCode.ENOENT) {\n throw convertError(e, this.existsSync(oldPath) ? newPath : oldPath);\n } else {\n throw convertError(e);\n }\n }\n }\n\n public statSync(p: string, isLstat: boolean): Stats {\n try {\n const stats = isLstat ? this._FS.lstat(p) : this._FS.stat(p);\n const itemType = this.modeToFileType(stats.mode);\n return new Stats(\n itemType,\n stats.size,\n stats.mode,\n stats.atime,\n stats.mtime,\n stats.ctime\n );\n } catch (e) {\n throw convertError(e, p);\n }\n }\n\n public openSync(p: string, flag: FileFlag, mode: number): EmscriptenFile {\n try {\n const stream = this._FS.open(p, flag.getFlagString(), mode);\n if (this._FS.isDir(stream.node.mode)) {\n this._FS.close(stream);\n throw ApiError.EISDIR(p);\n }\n return new EmscriptenFile(this, this._FS, p, stream);\n } catch (e) {\n throw convertError(e, p);\n }\n }\n\n public unlinkSync(p: string): void {\n try {\n this._FS.unlink(p);\n } catch (e) {\n throw convertError(e, p);\n }\n }\n\n public rmdirSync(p: string): void {\n try {\n this._FS.rmdir(p);\n } catch (e) {\n throw convertError(e, p);\n }\n }\n\n public mkdirSync(p: string, mode: number): void {\n try {\n this._FS.mkdir(p, mode);\n } catch (e) {\n throw convertError(e, p);\n }\n }\n\n public readdirSync(p: string): string[] {\n try {\n // Emscripten returns items for '.' and '..'. Node does not.\n return this._FS.readdir(p).filter((p: string) => p !== '.' && p !== '..');\n } catch (e) {\n throw convertError(e, p);\n }\n }\n\n public truncateSync(p: string, len: number): void {\n try {\n this._FS.truncate(p, len);\n } catch (e) {\n throw convertError(e, p);\n }\n }\n\n public readFileSync(p: string, encoding: string, flag: FileFlag): any {\n try {\n const data: Uint8Array = this._FS.readFile(p, { flags: flag.getFlagString() });\n const buff = uint8Array2Buffer(data);\n if (encoding) {\n return buff.toString(encoding);\n } else {\n return buff;\n }\n } catch (e) {\n throw convertError(e, p);\n }\n }\n\n public writeFileSync(p: string, data: any, encoding: string, flag: FileFlag, mode: number): void {\n try {\n if (encoding) {\n data = Buffer.from(data, encoding);\n }\n const u8 = buffer2Uint8array(data);\n this._FS.writeFile(p, u8, { flags: flag.getFlagString(), encoding: 'binary' });\n this._FS.chmod(p, mode);\n } catch (e) {\n throw convertError(e, p);\n }\n }\n\n public chmodSync(p: string, isLchmod: boolean, mode: number) {\n try {\n isLchmod ? this._FS.lchmod(p, mode) : this._FS.chmod(p, mode);\n } catch (e) {\n throw convertError(e, p);\n }\n }\n\n public chownSync(p: string, isLchown: boolean, uid: number, gid: number): void {\n try {\n isLchown ? this._FS.lchown(p, uid, gid) : this._FS.chown(p, uid, gid);\n } catch (e) {\n throw convertError(e, p);\n }\n }\n\n public symlinkSync(srcpath: string, dstpath: string, type: string): void {\n try {\n this._FS.symlink(srcpath, dstpath);\n } catch (e) {\n throw convertError(e);\n }\n }\n\n public readlinkSync(p: string): string {\n try {\n return this._FS.readlink(p);\n } catch (e) {\n throw convertError(e, p);\n }\n }\n\n public utimesSync(p: string, atime: Date, mtime: Date): void {\n try {\n this._FS.utime(p, atime.getTime(), mtime.getTime());\n } catch (e) {\n throw convertError(e, p);\n }\n }\n\n private modeToFileType(mode: number): FileType {\n if (this._FS.isDir(mode)) {\n return FileType.DIRECTORY;\n } else if (this._FS.isFile(mode)) {\n return FileType.FILE;\n } else if (this._FS.isLink(mode)) {\n return FileType.SYMLINK;\n } else {\n throw ApiError.EPERM(`Invalid mode: ${mode}`);\n }\n }\n\n}\n\n\n\n// WEBPACK FOOTER //\n// ../../../../src/backend/Emscripten.ts","import {BaseFileSystem, FileSystem, BFSCallback, FileSystemOptions} from '../core/file_system';\nimport * as path from 'path';\nimport {ApiError} from '../core/api_error';\n\n/**\n * Configuration options for a FolderAdapter file system.\n */\nexport interface FolderAdapterOptions {\n // The folder to use as the root directory.\n folder: string;\n // The file system to wrap.\n wrapped: FileSystem;\n}\n\n/**\n * The FolderAdapter file system wraps a file system, and scopes all interactions to a subfolder of that file system.\n *\n * Example: Given a file system `foo` with folder `bar` and file `bar/baz`...\n *\n * ```javascript\n * BrowserFS.configure({\n * fs: \"FolderAdapter\",\n * options: {\n * folder: \"bar\",\n * wrapped: foo\n * }\n * }, function(e) {\n * var fs = BrowserFS.BFSRequire('fs');\n * fs.readdirSync('/'); // ['baz']\n * });\n * ```\n */\nexport default class FolderAdapter extends BaseFileSystem implements FileSystem {\n public static readonly Name = \"FolderAdapter\";\n\n public static readonly Options: FileSystemOptions = {\n folder: {\n type: \"string\",\n description: \"The folder to use as the root directory\"\n },\n wrapped: {\n type: \"object\",\n description: \"The file system to wrap\"\n }\n };\n\n /**\n * Creates a FolderAdapter instance with the given options.\n */\n public static Create(opts: FolderAdapterOptions, cb: BFSCallback): void {\n cb(null, new FolderAdapter(opts.folder, opts.wrapped));\n }\n public static isAvailable(): boolean {\n return true;\n }\n\n public _wrapped: FileSystem;\n public _folder: string;\n /**\n * Wraps a file system, and uses the given folder as its root.\n *\n * @param folder The folder to use as the root directory.\n * @param wrapped The file system to wrap.\n */\n constructor(folder: string, wrapped: FileSystem) {\n super();\n this._folder = folder;\n this._wrapped = wrapped;\n }\n\n /**\n * Initialize the file system. Ensures that the wrapped file system\n * has the given folder.\n */\n public initialize(cb: (e?: ApiError) => void) {\n this._wrapped.exists(this._folder, (exists: boolean) => {\n if (exists) {\n cb();\n } else if (this._wrapped.isReadOnly()) {\n cb(ApiError.ENOENT(this._folder));\n } else {\n this._wrapped.mkdir(this._folder, 0x1ff, cb);\n }\n });\n }\n\n public getName(): string { return this._wrapped.getName(); }\n public isReadOnly(): boolean { return this._wrapped.isReadOnly(); }\n public supportsProps(): boolean { return this._wrapped.supportsProps(); }\n public supportsSynch(): boolean { return this._wrapped.supportsSynch(); }\n public supportsLinks(): boolean { return false; }\n}\n\n/**\n * @hidden\n */\nfunction translateError(folder: string, e: any): any {\n if (e !== null && typeof e === 'object') {\n const err = e;\n let p = err.path;\n if (p) {\n p = '/' + path.relative(folder, p);\n err.message = err.message.replace(err.path!, p);\n err.path = p;\n }\n }\n return e;\n}\n\n/**\n * @hidden\n */\nfunction wrapCallback(folder: string, cb: any): any {\n if (typeof cb === 'function') {\n return function(err: ApiError) {\n if (arguments.length > 0) {\n arguments[0] = translateError(folder, err);\n }\n ( cb).apply(null, arguments);\n };\n } else {\n return cb;\n }\n}\n\n/**\n * @hidden\n */\nfunction wrapFunction(name: string, wrapFirst: boolean, wrapSecond: boolean): Function {\n if (name.slice(name.length - 4) !== 'Sync') {\n // Async function. Translate error in callback.\n return function(this: FolderAdapter) {\n if (arguments.length > 0) {\n if (wrapFirst) {\n arguments[0] = path.join(this._folder, arguments[0]);\n }\n if (wrapSecond) {\n arguments[1] = path.join(this._folder, arguments[1]);\n }\n arguments[arguments.length - 1] = wrapCallback(this._folder, arguments[arguments.length - 1]);\n }\n return ( this._wrapped)[name].apply(this._wrapped, arguments);\n };\n } else {\n // Sync function. Translate error in catch.\n return function(this: FolderAdapter) {\n try {\n if (wrapFirst) {\n arguments[0] = path.join(this._folder, arguments[0]);\n }\n if (wrapSecond) {\n arguments[1] = path.join(this._folder, arguments[1]);\n }\n return ( this._wrapped)[name].apply(this._wrapped, arguments);\n } catch (e) {\n throw translateError(this._folder, e);\n }\n };\n }\n}\n\n// First argument is a path.\n['diskSpace', 'stat', 'statSync', 'open', 'openSync', 'unlink', 'unlinkSync',\n 'rmdir', 'rmdirSync', 'mkdir', 'mkdirSync', 'readdir', 'readdirSync', 'exists',\n 'existsSync', 'realpath', 'realpathSync', 'truncate', 'truncateSync', 'readFile',\n 'readFileSync', 'writeFile', 'writeFileSync', 'appendFile', 'appendFileSync',\n 'chmod', 'chmodSync', 'chown', 'chownSync', 'utimes', 'utimesSync', 'readlink',\n 'readlinkSync'].forEach((name: string) => {\n ( FolderAdapter.prototype)[name] = wrapFunction(name, true, false);\n});\n\n// First and second arguments are paths.\n['rename', 'renameSync', 'link', 'linkSync', 'symlink', 'symlinkSync'].forEach((name: string) => {\n ( FolderAdapter.prototype)[name] = wrapFunction(name, true, true);\n});\n\n\n\n// WEBPACK FOOTER //\n// ../../../../src/backend/FolderAdapter.ts","import PreloadFile from '../generic/preload_file';\nimport {BaseFileSystem, FileSystem as IFileSystem, BFSOneArgCallback, BFSCallback, FileSystemOptions} from '../core/file_system';\nimport {ApiError, ErrorCode} from '../core/api_error';\nimport {FileFlag, ActionType} from '../core/file_flag';\nimport {default as Stats, FileType} from '../core/node_fs_stats';\nimport {File as IFile} from '../core/file';\nimport * as path from 'path';\nimport global from '../core/global';\nimport {each as asyncEach} from 'async';\nimport {buffer2ArrayBuffer, arrayBuffer2Buffer, deprecationMessage} from '../core/util';\n\n/**\n * @hidden\n */\nfunction isDirectoryEntry(entry: Entry): entry is DirectoryEntry {\n return entry.isDirectory;\n}\n\n/**\n * @hidden\n */\nconst _getFS: (type: number, size: number, successCallback: FileSystemCallback, errorCallback?: ErrorCallback) => void = global.webkitRequestFileSystem || global.requestFileSystem || null;\n\n/**\n * @hidden\n */\nfunction _requestQuota(type: number, size: number, success: (size: number) => void, errorCallback: ErrorCallback) {\n // We cast navigator and window to '' because everything here is\n // nonstandard functionality, despite the fact that Chrome has the only\n // implementation of the HTML5FS and is likely driving the standardization\n // process. Thus, these objects defined off of navigator and window are not\n // present in the DefinitelyTyped TypeScript typings for FileSystem.\n if (typeof ( navigator)['webkitPersistentStorage'] !== 'undefined') {\n switch (type) {\n case global.PERSISTENT:\n ( navigator).webkitPersistentStorage.requestQuota(size, success, errorCallback);\n break;\n case global.TEMPORARY:\n ( navigator).webkitTemporaryStorage.requestQuota(size, success, errorCallback);\n break;\n default:\n errorCallback(new TypeError(`Invalid storage type: ${type}`));\n break;\n }\n } else {\n ( global).webkitStorageInfo.requestQuota(type, size, success, errorCallback);\n }\n}\n\n/**\n * @hidden\n */\nfunction _toArray(list?: any[]): any[] {\n return Array.prototype.slice.call(list || [], 0);\n}\n\n/**\n * Converts the given DOMError into an appropriate ApiError.\n * @url https://developer.mozilla.org/en-US/docs/Web/API/DOMError\n * @hidden\n */\nfunction convertError(err: DOMError, p: string, expectedDir: boolean): ApiError {\n switch (err.name) {\n /* The user agent failed to create a file or directory due to the existence of a file or\n directory with the same path. */\n case \"PathExistsError\":\n return ApiError.EEXIST(p);\n /* The operation failed because it would cause the application to exceed its storage quota. */\n case 'QuotaExceededError':\n return ApiError.FileError(ErrorCode.ENOSPC, p);\n /* A required file or directory could not be found at the time an operation was processed. */\n case 'NotFoundError':\n return ApiError.ENOENT(p);\n /* This is a security error code to be used in situations not covered by any other error codes.\n - A required file was unsafe for access within a Web application\n - Too many calls are being made on filesystem resources */\n case 'SecurityError':\n return ApiError.FileError(ErrorCode.EACCES, p);\n /* The modification requested was illegal. Examples of invalid modifications include moving a\n directory into its own child, moving a file into its parent directory without changing its name,\n or copying a directory to a path occupied by a file. */\n case 'InvalidModificationError':\n return ApiError.FileError(ErrorCode.EPERM, p);\n /* The user has attempted to look up a file or directory, but the Entry found is of the wrong type\n [e.g. is a DirectoryEntry when the user requested a FileEntry]. */\n case 'TypeMismatchError':\n return ApiError.FileError(expectedDir ? ErrorCode.ENOTDIR : ErrorCode.EISDIR, p);\n /* A path or URL supplied to the API was malformed. */\n case \"EncodingError\":\n /* An operation depended on state cached in an interface object, but that state that has changed\n since it was read from disk. */\n case \"InvalidStateError\":\n /* The user attempted to write to a file or directory which could not be modified due to the state\n of the underlying filesystem. */\n case \"NoModificationAllowedError\":\n default:\n return ApiError.FileError(ErrorCode.EINVAL, p);\n }\n}\n\n// A note about getFile and getDirectory options:\n// These methods are called at numerous places in this file, and are passed\n// some combination of these two options:\n// - create: If true, the entry will be created if it doesn't exist.\n// If false, an error will be thrown if it doesn't exist.\n// - exclusive: If true, only create the entry if it doesn't already exist,\n// and throw an error if it does.\n\nexport class HTML5FSFile extends PreloadFile implements IFile {\n private _entry: FileEntry;\n\n constructor(fs: HTML5FS, entry: FileEntry, path: string, flag: FileFlag, stat: Stats, contents?: Buffer) {\n super(fs, path, flag, stat, contents);\n this._entry = entry;\n }\n\n public sync(cb: BFSOneArgCallback): void {\n if (!this.isDirty()) {\n return cb();\n }\n\n this._entry.createWriter((writer) => {\n const buffer = this.getBuffer();\n const blob = new Blob([buffer2ArrayBuffer(buffer)]);\n const length = blob.size;\n writer.onwriteend = (err?: any) => {\n writer.onwriteend = null;\n writer.onerror = null;\n writer.truncate(length);\n this.resetDirty();\n cb();\n };\n writer.onerror = (err: any) => {\n cb(convertError(err, this.getPath(), false));\n };\n writer.write(blob);\n });\n }\n\n public close(cb: BFSOneArgCallback): void {\n this.sync(cb);\n }\n}\n\nexport interface HTML5FSOptions {\n // storage quota to request, in megabytes. Allocated value may be less.\n size?: number;\n // window.PERSISTENT or window.TEMPORARY. Defaults to PERSISTENT.\n type?: number;\n}\n\n/**\n * A read-write filesystem backed by the HTML5 FileSystem API.\n *\n * As the HTML5 FileSystem is only implemented in Blink, this interface is\n * only available in Chrome.\n */\nexport default class HTML5FS extends BaseFileSystem implements IFileSystem {\n public static readonly Name = \"HTML5FS\";\n\n public static readonly Options: FileSystemOptions = {\n size: {\n type: \"number\",\n optional: true,\n description: \"Storage quota to request, in megabytes. Allocated value may be less. Defaults to 5.\"\n },\n type: {\n type: \"number\",\n optional: true,\n description: \"window.PERSISTENT or window.TEMPORARY. Defaults to PERSISTENT.\"\n }\n };\n\n /**\n * Creates an HTML5FS instance with the given options.\n */\n public static Create(opts: HTML5FSOptions, cb: BFSCallback): void {\n const fs = new HTML5FS(opts.size, opts.type, false);\n fs.allocate((e) => e ? cb(e) : cb(null, fs), false);\n }\n public static isAvailable(): boolean {\n return !!_getFS;\n }\n\n // HTML5File reaches into HTML5FS. :/\n public fs: FileSystem;\n private size: number;\n private type: number;\n /**\n * **Deprecated. Please use HTML5FS.Create() method instead.**\n *\n * Creates a new HTML5 FileSystem-backed BrowserFS file system of the given size\n * and storage type.\n *\n * **IMPORTANT**: You must call `allocate` on the resulting object before the file system\n * can be used.\n *\n * @param size storage quota to request, in megabytes. Allocated value may be less.\n * @param type window.PERSISTENT or window.TEMPORARY. Defaults to PERSISTENT.\n */\n constructor(size: number = 5, type: number = global.PERSISTENT, deprecateMsg = true) {\n super();\n // Convert MB to bytes.\n this.size = 1024 * 1024 * size;\n this.type = type;\n deprecationMessage(deprecateMsg, HTML5FS.Name, {size: size, type: type});\n }\n\n public getName(): string {\n return HTML5FS.Name;\n }\n\n public isReadOnly(): boolean {\n return false;\n }\n\n public supportsSymlinks(): boolean {\n return false;\n }\n\n public supportsProps(): boolean {\n return false;\n }\n\n public supportsSynch(): boolean {\n return false;\n }\n\n /**\n * **Deprecated. Please use Create() method instead to create and allocate an HTML5FS.**\n *\n * Requests a storage quota from the browser to back this FS.\n * Must be called before file system can be used!\n */\n public allocate(cb: BFSOneArgCallback = () => {/*nop*/}, deprecateMsg = true): void {\n if (deprecateMsg) {\n console.warn(`[HTML5FS] HTML5FS.allocate() is deprecated and will be removed in the next major release. Please use 'HTML5FS.Create({type: ${this.type}, size: ${this.size}}, cb)' to create and allocate HTML5FS instances.`);\n }\n const success = (fs: FileSystem): void => {\n this.fs = fs;\n cb();\n };\n const error = (err: DOMException): void => {\n cb(convertError(err, \"/\", true));\n };\n if (this.type === global.PERSISTENT) {\n _requestQuota(this.type, this.size, (granted: number) => {\n _getFS(this.type, granted, success, error);\n }, error);\n } else {\n _getFS(this.type, this.size, success, error);\n }\n }\n\n /**\n * Deletes everything in the FS. Used for testing.\n * Karma clears the storage after you quit it but not between runs of the test\n * suite, and the tests expect an empty FS every time.\n */\n public empty(mainCb: BFSOneArgCallback): void {\n // Get a list of all entries in the root directory to delete them\n this._readdir('/', (err: ApiError, entries?: Entry[]): void => {\n if (err) {\n console.error('Failed to empty FS');\n mainCb(err);\n } else {\n // Called when every entry has been operated on\n const finished = (er: any): void => {\n if (err) {\n console.error(\"Failed to empty FS\");\n mainCb(err);\n } else {\n mainCb();\n }\n };\n // Removes files and recursively removes directories\n const deleteEntry = (entry: Entry, cb: (e?: any) => void): void => {\n const succ = () => {\n cb();\n };\n const error = (err: DOMException) => {\n cb(convertError(err, entry.fullPath, !entry.isDirectory));\n };\n if (isDirectoryEntry(entry)) {\n entry.removeRecursively(succ, error);\n } else {\n entry.remove(succ, error);\n }\n };\n // Loop through the entries and remove them, then call the callback\n // when they're all finished.\n asyncEach(entries!, deleteEntry, finished);\n }\n });\n }\n\n public rename(oldPath: string, newPath: string, cb: BFSOneArgCallback): void {\n let semaphore: number = 2;\n let successCount: number = 0;\n const root: DirectoryEntry = this.fs.root;\n let currentPath: string = oldPath;\n const error = (err: DOMException): void => {\n if (--semaphore <= 0) {\n cb(convertError(err, currentPath, false));\n }\n };\n const success = (file: Entry): void => {\n if (++successCount === 2) {\n return cb(new ApiError(ErrorCode.EINVAL, \"Something was identified as both a file and a directory. This should never happen.\"));\n }\n\n // SPECIAL CASE: If newPath === oldPath, and the path exists, then\n // this operation trivially succeeds.\n if (oldPath === newPath) {\n return cb();\n }\n\n // Get the new parent directory.\n currentPath = path.dirname(newPath);\n root.getDirectory(currentPath, {}, (parentDir: DirectoryEntry): void => {\n currentPath = path.basename(newPath);\n file.moveTo(parentDir, currentPath, (entry: Entry): void => { cb(); }, (err: DOMException): void => {\n // SPECIAL CASE: If oldPath is a directory, and newPath is a\n // file, rename should delete the file and perform the move.\n if (file.isDirectory) {\n currentPath = newPath;\n // Unlink only works on files. Try to delete newPath.\n this.unlink(newPath, (e?): void => {\n if (e) {\n // newPath is probably a directory.\n error(err);\n } else {\n // Recur, now that newPath doesn't exist.\n this.rename(oldPath, newPath, cb);\n }\n });\n } else {\n error(err);\n }\n });\n }, error);\n };\n\n // We don't know if oldPath is a *file* or a *directory*, and there's no\n // way to stat items. So launch both requests, see which one succeeds.\n root.getFile(oldPath, {}, success, error);\n root.getDirectory(oldPath, {}, success, error);\n }\n\n public stat(path: string, isLstat: boolean, cb: BFSCallback): void {\n // Throw an error if the entry doesn't exist, because then there's nothing\n // to stat.\n const opts = {\n create: false\n };\n // Called when the path has been successfully loaded as a file.\n const loadAsFile = (entry: FileEntry): void => {\n const fileFromEntry = (file: File): void => {\n const stat = new Stats(FileType.FILE, file.size);\n cb(null, stat);\n };\n entry.file(fileFromEntry, failedToLoad);\n };\n // Called when the path has been successfully loaded as a directory.\n const loadAsDir = (dir: DirectoryEntry): void => {\n // Directory entry size can't be determined from the HTML5 FS API, and is\n // implementation-dependant anyway, so a dummy value is used.\n const size = 4096;\n const stat = new Stats(FileType.DIRECTORY, size);\n cb(null, stat);\n };\n // Called when the path couldn't be opened as a directory or a file.\n const failedToLoad = (err: DOMException): void => {\n cb(convertError(err, path, false /* Unknown / irrelevant */));\n };\n // Called when the path couldn't be opened as a file, but might still be a\n // directory.\n const failedToLoadAsFile = (): void => {\n this.fs.root.getDirectory(path, opts, loadAsDir, failedToLoad);\n };\n // No method currently exists to determine whether a path refers to a\n // directory or a file, so this implementation tries both and uses the first\n // one that succeeds.\n this.fs.root.getFile(path, opts, loadAsFile, failedToLoadAsFile);\n }\n\n public open(p: string, flags: FileFlag, mode: number, cb: BFSCallback): void {\n // XXX: err is a DOMError\n const error = (err: any): void => {\n if (err.name === 'InvalidModificationError' && flags.isExclusive()) {\n cb(ApiError.EEXIST(p));\n } else {\n cb(convertError(err, p, false));\n }\n };\n\n this.fs.root.getFile(p, {\n create: flags.pathNotExistsAction() === ActionType.CREATE_FILE,\n exclusive: flags.isExclusive()\n }, (entry: FileEntry): void => {\n // Try to fetch corresponding file.\n entry.file((file: File): void => {\n const reader = new FileReader();\n reader.onloadend = (event: Event): void => {\n const bfsFile = this._makeFile(p, entry, flags, file, reader.result);\n cb(null, bfsFile);\n };\n reader.onerror = (ev: Event) => {\n error(reader.error);\n };\n reader.readAsArrayBuffer(file);\n }, error);\n }, error);\n }\n\n public unlink(path: string, cb: BFSOneArgCallback): void {\n this._remove(path, cb, true);\n }\n\n public rmdir(path: string, cb: BFSOneArgCallback): void {\n // Check if directory is non-empty, first.\n this.readdir(path, (e, files?) => {\n if (e) {\n cb(e);\n } else if (files!.length > 0) {\n cb(ApiError.ENOTEMPTY(path));\n } else {\n this._remove(path, cb, false);\n }\n });\n }\n\n public mkdir(path: string, mode: number, cb: BFSOneArgCallback): void {\n // Create the directory, but throw an error if it already exists, as per\n // mkdir(1)\n const opts = {\n create: true,\n exclusive: true\n };\n const success = (dir: DirectoryEntry): void => {\n cb();\n };\n const error = (err: DOMException): void => {\n cb(convertError(err, path, true));\n };\n this.fs.root.getDirectory(path, opts, success, error);\n }\n\n /**\n * Map _readdir's list of `FileEntry`s to their names and return that.\n */\n public readdir(path: string, cb: BFSCallback): void {\n this._readdir(path, (e: ApiError, entries?: Entry[]): void => {\n if (entries) {\n const rv: string[] = [];\n for (const entry of entries) {\n rv.push(entry.name);\n }\n cb(null, rv);\n } else {\n return cb(e);\n }\n });\n }\n\n /**\n * Returns a BrowserFS object representing a File.\n */\n private _makeFile(path: string, entry: FileEntry, flag: FileFlag, stat: File, data: ArrayBuffer = new ArrayBuffer(0)): HTML5FSFile {\n const stats = new Stats(FileType.FILE, stat.size);\n const buffer = arrayBuffer2Buffer(data);\n return new HTML5FSFile(this, entry, path, flag, stats, buffer);\n }\n\n /**\n * Returns an array of `FileEntry`s. Used internally by empty and readdir.\n */\n private _readdir(path: string, cb: BFSCallback): void {\n const error = (err: DOMException): void => {\n cb(convertError(err, path, true));\n };\n // Grab the requested directory.\n this.fs.root.getDirectory(path, { create: false }, (dirEntry: DirectoryEntry) => {\n const reader = dirEntry.createReader();\n let entries: Entry[] = [];\n\n // Call the reader.readEntries() until no more results are returned.\n const readEntries = () => {\n reader.readEntries(((results) => {\n if (results.length) {\n entries = entries.concat(_toArray(results));\n readEntries();\n } else {\n cb(null, entries);\n }\n }), error);\n };\n readEntries();\n }, error);\n }\n\n /**\n * Delete a file or directory from the file system\n * isFile should reflect which call was made to remove the it (`unlink` or\n * `rmdir`). If this doesn't match what's actually at `path`, an error will be\n * returned\n */\n private _remove(path: string, cb: BFSOneArgCallback, isFile: boolean): void {\n const success = (entry: Entry): void => {\n const succ = () => {\n cb();\n };\n const err = (err: DOMException) => {\n cb(convertError(err, path, !isFile));\n };\n entry.remove(succ, err);\n };\n const error = (err: DOMException): void => {\n cb(convertError(err, path, !isFile));\n };\n // Deleting the entry, so don't create it\n const opts = {\n create: false\n };\n\n if (isFile) {\n this.fs.root.getFile(path, opts, success, error);\n } else {\n this.fs.root.getDirectory(path, opts, success, error);\n }\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ../../../../src/backend/HTML5FS.ts","import {BaseFileSystem, SynchronousFileSystem, BFSOneArgCallback, BFSCallback, BFSThreeArgCallback} from '../core/file_system';\nimport {ApiError, ErrorCode} from '../core/api_error';\nimport {default as Stats, FileType} from '../core/node_fs_stats';\nimport {File} from '../core/file';\nimport {FileFlag} from '../core/file_flag';\nimport * as path from 'path';\nimport Inode from '../generic/inode';\nimport PreloadFile from '../generic/preload_file';\nimport {emptyBuffer} from '../core/util';\n/**\n * @hidden\n */\nconst ROOT_NODE_ID: string = \"/\";\n/**\n * @hidden\n */\nlet emptyDirNode: Buffer | null = null;\n/**\n * Returns an empty directory node.\n * @hidden\n */\nfunction getEmptyDirNode(): Buffer {\n if (emptyDirNode) {\n return emptyDirNode;\n }\n return emptyDirNode = Buffer.from(\"{}\");\n}\n\n/**\n * Generates a random ID.\n * @hidden\n */\nfunction GenerateRandomID(): string {\n // From http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {\n const r = Math.random() * 16 | 0;\n const v = c === 'x' ? r : (r & 0x3 | 0x8);\n return v.toString(16);\n });\n}\n\n/**\n * Helper function. Checks if 'e' is defined. If so, it triggers the callback\n * with 'e' and returns false. Otherwise, returns true.\n * @hidden\n */\nfunction noError(e: ApiError | undefined | null, cb: (e: ApiError) => void): boolean {\n if (e) {\n cb(e);\n return false;\n }\n return true;\n}\n\n/**\n * Helper function. Checks if 'e' is defined. If so, it aborts the transaction,\n * triggers the callback with 'e', and returns false. Otherwise, returns true.\n * @hidden\n */\nfunction noErrorTx(e: ApiError | undefined | null, tx: AsyncKeyValueRWTransaction, cb: (e: ApiError) => void): boolean {\n if (e) {\n tx.abort(() => {\n cb(e);\n });\n return false;\n }\n return true;\n}\n\n/**\n * Represents a *synchronous* key-value store.\n */\nexport interface SyncKeyValueStore {\n /**\n * The name of the key-value store.\n */\n name(): string;\n /**\n * Empties the key-value store completely.\n */\n clear(): void;\n /**\n * Begins a new read-only transaction.\n */\n beginTransaction(type: \"readonly\"): SyncKeyValueROTransaction;\n /**\n * Begins a new read-write transaction.\n */\n beginTransaction(type: \"readwrite\"): SyncKeyValueRWTransaction;\n beginTransaction(type: string): SyncKeyValueROTransaction;\n}\n\n/**\n * A read-only transaction for a synchronous key value store.\n */\nexport interface SyncKeyValueROTransaction {\n /**\n * Retrieves the data at the given key. Throws an ApiError if an error occurs\n * or if the key does not exist.\n * @param key The key to look under for data.\n * @return The data stored under the key, or undefined if not present.\n */\n get(key: string): Buffer | undefined;\n}\n\n/**\n * A read-write transaction for a synchronous key value store.\n */\nexport interface SyncKeyValueRWTransaction extends SyncKeyValueROTransaction {\n /**\n * Adds the data to the store under the given key.\n * @param key The key to add the data under.\n * @param data The data to add to the store.\n * @param overwrite If 'true', overwrite any existing data. If 'false',\n * avoids storing the data if the key exists.\n * @return True if storage succeeded, false otherwise.\n */\n put(key: string, data: Buffer, overwrite: boolean): boolean;\n /**\n * Deletes the data at the given key.\n * @param key The key to delete from the store.\n */\n del(key: string): void;\n /**\n * Commits the transaction.\n */\n commit(): void;\n /**\n * Aborts and rolls back the transaction.\n */\n abort(): void;\n}\n\n/**\n * An interface for simple synchronous key-value stores that don't have special\n * support for transactions and such.\n */\nexport interface SimpleSyncStore {\n get(key: string): Buffer | undefined;\n put(key: string, data: Buffer, overwrite: boolean): boolean;\n del(key: string): void;\n}\n\n/**\n * A simple RW transaction for simple synchronous key-value stores.\n */\nexport class SimpleSyncRWTransaction implements SyncKeyValueRWTransaction {\n /**\n * Stores data in the keys we modify prior to modifying them.\n * Allows us to roll back commits.\n */\n private originalData: { [key: string]: Buffer | undefined } = {};\n /**\n * List of keys modified in this transaction, if any.\n */\n private modifiedKeys: string[] = [];\n\n constructor(private store: SimpleSyncStore) { }\n\n public get(key: string): Buffer | undefined {\n const val = this.store.get(key);\n this.stashOldValue(key, val);\n return val;\n }\n\n public put(key: string, data: Buffer, overwrite: boolean): boolean {\n this.markModified(key);\n return this.store.put(key, data, overwrite);\n }\n\n public del(key: string): void {\n this.markModified(key);\n this.store.del(key);\n }\n\n public commit(): void {/* NOP */}\n\n public abort(): void {\n // Rollback old values.\n for (const key of this.modifiedKeys) {\n const value = this.originalData[key];\n if (!value) {\n // Key didn't exist.\n this.store.del(key);\n } else {\n // Key existed. Store old value.\n this.store.put(key, value, true);\n }\n }\n }\n\n /**\n * Stashes given key value pair into `originalData` if it doesn't already\n * exist. Allows us to stash values the program is requesting anyway to\n * prevent needless `get` requests if the program modifies the data later\n * on during the transaction.\n */\n private stashOldValue(key: string, value: Buffer | undefined) {\n // Keep only the earliest value in the transaction.\n if (!this.originalData.hasOwnProperty(key)) {\n this.originalData[key] = value;\n }\n }\n\n /**\n * Marks the given key as modified, and stashes its value if it has not been\n * stashed already.\n */\n private markModified(key: string) {\n if (this.modifiedKeys.indexOf(key) === -1) {\n this.modifiedKeys.push(key);\n if (!this.originalData.hasOwnProperty(key)) {\n this.originalData[key] = this.store.get(key);\n }\n }\n }\n}\n\nexport interface SyncKeyValueFileSystemOptions {\n /**\n * The actual key-value store to read from/write to.\n */\n store: SyncKeyValueStore;\n /**\n * Should the file system support properties (mtime/atime/ctime/chmod/etc)?\n * Enabling this slightly increases the storage space per file, and adds\n * atime updates every time a file is accessed, mtime updates every time\n * a file is modified, and permission checks on every operation.\n *\n * Defaults to *false*.\n */\n // supportProps?: boolean;\n /**\n * Should the file system support links?\n */\n // supportLinks?: boolean;\n}\n\nexport class SyncKeyValueFile extends PreloadFile implements File {\n constructor(_fs: SyncKeyValueFileSystem, _path: string, _flag: FileFlag, _stat: Stats, contents?: Buffer) {\n super(_fs, _path, _flag, _stat, contents);\n }\n\n public syncSync(): void {\n if (this.isDirty()) {\n this._fs._syncSync(this.getPath(), this.getBuffer(), this.getStats());\n this.resetDirty();\n }\n }\n\n public closeSync(): void {\n this.syncSync();\n }\n}\n\n/**\n * A \"Synchronous key-value file system\". Stores data to/retrieves data from an\n * underlying key-value store.\n *\n * We use a unique ID for each node in the file system. The root node has a\n * fixed ID.\n * @todo Introduce Node ID caching.\n * @todo Check modes.\n */\nexport class SyncKeyValueFileSystem extends SynchronousFileSystem {\n public static isAvailable(): boolean { return true; }\n\n private store: SyncKeyValueStore;\n\n constructor(options: SyncKeyValueFileSystemOptions) {\n super();\n this.store = options.store;\n // INVARIANT: Ensure that the root exists.\n this.makeRootDirectory();\n }\n\n public getName(): string { return this.store.name(); }\n public isReadOnly(): boolean { return false; }\n public supportsSymlinks(): boolean { return false; }\n public supportsProps(): boolean { return false; }\n public supportsSynch(): boolean { return true; }\n\n /**\n * Delete all contents stored in the file system.\n */\n public empty(): void {\n this.store.clear();\n // INVARIANT: Root always exists.\n this.makeRootDirectory();\n }\n\n public renameSync(oldPath: string, newPath: string): void {\n const tx = this.store.beginTransaction('readwrite'),\n oldParent = path.dirname(oldPath), oldName = path.basename(oldPath),\n newParent = path.dirname(newPath), newName = path.basename(newPath),\n // Remove oldPath from parent's directory listing.\n oldDirNode = this.findINode(tx, oldParent),\n oldDirList = this.getDirListing(tx, oldParent, oldDirNode);\n\n if (!oldDirList[oldName]) {\n throw ApiError.ENOENT(oldPath);\n }\n const nodeId: string = oldDirList[oldName];\n delete oldDirList[oldName];\n\n // Invariant: Can't move a folder inside itself.\n // This funny little hack ensures that the check passes only if oldPath\n // is a subpath of newParent. We append '/' to avoid matching folders that\n // are a substring of the bottom-most folder in the path.\n if ((newParent + '/').indexOf(oldPath + '/') === 0) {\n throw new ApiError(ErrorCode.EBUSY, oldParent);\n }\n\n // Add newPath to parent's directory listing.\n let newDirNode: Inode, newDirList: typeof oldDirList;\n if (newParent === oldParent) {\n // Prevent us from re-grabbing the same directory listing, which still\n // contains oldName.\n newDirNode = oldDirNode;\n newDirList = oldDirList;\n } else {\n newDirNode = this.findINode(tx, newParent);\n newDirList = this.getDirListing(tx, newParent, newDirNode);\n }\n\n if (newDirList[newName]) {\n // If it's a file, delete it.\n const newNameNode = this.getINode(tx, newPath, newDirList[newName]);\n if (newNameNode.isFile()) {\n try {\n tx.del(newNameNode.id);\n tx.del(newDirList[newName]);\n } catch (e) {\n tx.abort();\n throw e;\n }\n } else {\n // If it's a directory, throw a permissions error.\n throw ApiError.EPERM(newPath);\n }\n }\n newDirList[newName] = nodeId;\n\n // Commit the two changed directory listings.\n try {\n tx.put(oldDirNode.id, Buffer.from(JSON.stringify(oldDirList)), true);\n tx.put(newDirNode.id, Buffer.from(JSON.stringify(newDirList)), true);\n } catch (e) {\n tx.abort();\n throw e;\n }\n\n tx.commit();\n }\n\n public statSync(p: string, isLstat: boolean): Stats {\n // Get the inode to the item, convert it into a Stats object.\n return this.findINode(this.store.beginTransaction('readonly'), p).toStats();\n }\n\n public createFileSync(p: string, flag: FileFlag, mode: number): File {\n const tx = this.store.beginTransaction('readwrite'),\n data = emptyBuffer(),\n newFile = this.commitNewFile(tx, p, FileType.FILE, mode, data);\n // Open the file.\n return new SyncKeyValueFile(this, p, flag, newFile.toStats(), data);\n }\n\n public openFileSync(p: string, flag: FileFlag): File {\n const tx = this.store.beginTransaction('readonly'),\n node = this.findINode(tx, p),\n data = tx.get(node.id);\n if (data === undefined) {\n throw ApiError.ENOENT(p);\n }\n return new SyncKeyValueFile(this, p, flag, node.toStats(), data);\n }\n\n public unlinkSync(p: string): void {\n this.removeEntry(p, false);\n }\n\n public rmdirSync(p: string): void {\n // Check first if directory is empty.\n if (this.readdirSync(p).length > 0) {\n throw ApiError.ENOTEMPTY(p);\n } else {\n this.removeEntry(p, true);\n }\n }\n\n public mkdirSync(p: string, mode: number): void {\n const tx = this.store.beginTransaction('readwrite'),\n data = Buffer.from('{}');\n this.commitNewFile(tx, p, FileType.DIRECTORY, mode, data);\n }\n\n public readdirSync(p: string): string[] {\n const tx = this.store.beginTransaction('readonly');\n return Object.keys(this.getDirListing(tx, p, this.findINode(tx, p)));\n }\n\n public _syncSync(p: string, data: Buffer, stats: Stats): void {\n // @todo Ensure mtime updates properly, and use that to determine if a data\n // update is required.\n const tx = this.store.beginTransaction('readwrite'),\n // We use the _findInode helper because we actually need the INode id.\n fileInodeId = this._findINode(tx, path.dirname(p), path.basename(p)),\n fileInode = this.getINode(tx, p, fileInodeId),\n inodeChanged = fileInode.update(stats);\n\n try {\n // Sync data.\n tx.put(fileInode.id, data, true);\n // Sync metadata.\n if (inodeChanged) {\n tx.put(fileInodeId, fileInode.toBuffer(), true);\n }\n } catch (e) {\n tx.abort();\n throw e;\n }\n tx.commit();\n }\n\n /**\n * Checks if the root directory exists. Creates it if it doesn't.\n */\n private makeRootDirectory() {\n const tx = this.store.beginTransaction('readwrite');\n if (tx.get(ROOT_NODE_ID) === undefined) {\n // Create new inode.\n const currTime = (new Date()).getTime(),\n // Mode 0666\n dirInode = new Inode(GenerateRandomID(), 4096, 511 | FileType.DIRECTORY, currTime, currTime, currTime);\n // If the root doesn't exist, the first random ID shouldn't exist,\n // either.\n tx.put(dirInode.id, getEmptyDirNode(), false);\n tx.put(ROOT_NODE_ID, dirInode.toBuffer(), false);\n tx.commit();\n }\n }\n\n /**\n * Helper function for findINode.\n * @param parent The parent directory of the file we are attempting to find.\n * @param filename The filename of the inode we are attempting to find, minus\n * the parent.\n * @return string The ID of the file's inode in the file system.\n */\n private _findINode(tx: SyncKeyValueROTransaction, parent: string, filename: string): string {\n const readDirectory = (inode: Inode): string => {\n // Get the root's directory listing.\n const dirList = this.getDirListing(tx, parent, inode);\n // Get the file's ID.\n if (dirList[filename]) {\n return dirList[filename];\n } else {\n throw ApiError.ENOENT(path.resolve(parent, filename));\n }\n };\n if (parent === '/') {\n if (filename === '') {\n // BASE CASE #1: Return the root's ID.\n return ROOT_NODE_ID;\n } else {\n // BASE CASE #2: Find the item in the root ndoe.\n return readDirectory(this.getINode(tx, parent, ROOT_NODE_ID));\n }\n } else {\n return readDirectory(this.getINode(tx, parent + path.sep + filename,\n this._findINode(tx, path.dirname(parent), path.basename(parent))));\n }\n }\n\n /**\n * Finds the Inode of the given path.\n * @param p The path to look up.\n * @return The Inode of the path p.\n * @todo memoize/cache\n */\n private findINode(tx: SyncKeyValueROTransaction, p: string): Inode {\n return this.getINode(tx, p, this._findINode(tx, path.dirname(p), path.basename(p)));\n }\n\n /**\n * Given the ID of a node, retrieves the corresponding Inode.\n * @param tx The transaction to use.\n * @param p The corresponding path to the file (used for error messages).\n * @param id The ID to look up.\n */\n private getINode(tx: SyncKeyValueROTransaction, p: string, id: string): Inode {\n const inode = tx.get(id);\n if (inode === undefined) {\n throw ApiError.ENOENT(p);\n }\n return Inode.fromBuffer(inode);\n }\n\n /**\n * Given the Inode of a directory, retrieves the corresponding directory\n * listing.\n */\n private getDirListing(tx: SyncKeyValueROTransaction, p: string, inode: Inode): { [fileName: string]: string } {\n if (!inode.isDirectory()) {\n throw ApiError.ENOTDIR(p);\n }\n const data = tx.get(inode.id);\n if (data === undefined) {\n throw ApiError.ENOENT(p);\n }\n return JSON.parse(data.toString());\n }\n\n /**\n * Creates a new node under a random ID. Retries 5 times before giving up in\n * the exceedingly unlikely chance that we try to reuse a random GUID.\n * @return The GUID that the data was stored under.\n */\n private addNewNode(tx: SyncKeyValueRWTransaction, data: Buffer): string {\n const retries = 0;\n let currId: string;\n while (retries < 5) {\n try {\n currId = GenerateRandomID();\n tx.put(currId, data, false);\n return currId;\n } catch (e) {\n // Ignore and reroll.\n }\n }\n throw new ApiError(ErrorCode.EIO, 'Unable to commit data to key-value store.');\n }\n\n /**\n * Commits a new file (well, a FILE or a DIRECTORY) to the file system with\n * the given mode.\n * Note: This will commit the transaction.\n * @param p The path to the new file.\n * @param type The type of the new file.\n * @param mode The mode to create the new file with.\n * @param data The data to store at the file's data node.\n * @return The Inode for the new file.\n */\n private commitNewFile(tx: SyncKeyValueRWTransaction, p: string, type: FileType, mode: number, data: Buffer): Inode {\n const parentDir = path.dirname(p),\n fname = path.basename(p),\n parentNode = this.findINode(tx, parentDir),\n dirListing = this.getDirListing(tx, parentDir, parentNode),\n currTime = (new Date()).getTime();\n\n // Invariant: The root always exists.\n // If we don't check this prior to taking steps below, we will create a\n // file with name '' in root should p == '/'.\n if (p === '/') {\n throw ApiError.EEXIST(p);\n }\n\n // Check if file already exists.\n if (dirListing[fname]) {\n throw ApiError.EEXIST(p);\n }\n\n let fileNode: Inode;\n try {\n // Commit data.\n const dataId = this.addNewNode(tx, data);\n fileNode = new Inode(dataId, data.length, mode | type, currTime, currTime, currTime);\n // Commit file node.\n const fileNodeId = this.addNewNode(tx, fileNode.toBuffer());\n // Update and commit parent directory listing.\n dirListing[fname] = fileNodeId;\n tx.put(parentNode.id, Buffer.from(JSON.stringify(dirListing)), true);\n } catch (e) {\n tx.abort();\n throw e;\n }\n tx.commit();\n return fileNode;\n }\n\n /**\n * Remove all traces of the given path from the file system.\n * @param p The path to remove from the file system.\n * @param isDir Does the path belong to a directory, or a file?\n * @todo Update mtime.\n */\n private removeEntry(p: string, isDir: boolean): void {\n const tx = this.store.beginTransaction('readwrite'),\n parent: string = path.dirname(p),\n parentNode = this.findINode(tx, parent),\n parentListing = this.getDirListing(tx, parent, parentNode),\n fileName: string = path.basename(p);\n\n if (!parentListing[fileName]) {\n throw ApiError.ENOENT(p);\n }\n\n // Remove from directory listing of parent.\n const fileNodeId = parentListing[fileName];\n delete parentListing[fileName];\n\n // Get file inode.\n const fileNode = this.getINode(tx, p, fileNodeId);\n if (!isDir && fileNode.isDirectory()) {\n throw ApiError.EISDIR(p);\n } else if (isDir && !fileNode.isDirectory()) {\n throw ApiError.ENOTDIR(p);\n }\n\n try {\n // Delete data.\n tx.del(fileNode.id);\n // Delete node.\n tx.del(fileNodeId);\n // Update directory listing.\n tx.put(parentNode.id, Buffer.from(JSON.stringify(parentListing)), true);\n } catch (e) {\n tx.abort();\n throw e;\n }\n // Success.\n tx.commit();\n }\n}\n\n/**\n * Represents an *asynchronous* key-value store.\n */\nexport interface AsyncKeyValueStore {\n /**\n * The name of the key-value store.\n */\n name(): string;\n /**\n * Empties the key-value store completely.\n */\n clear(cb: BFSOneArgCallback): void;\n /**\n * Begins a read-write transaction.\n */\n beginTransaction(type: 'readwrite'): AsyncKeyValueRWTransaction;\n /**\n * Begins a read-only transaction.\n */\n beginTransaction(type: 'readonly'): AsyncKeyValueROTransaction;\n beginTransaction(type: string): AsyncKeyValueROTransaction;\n}\n\n/**\n * Represents an asynchronous read-only transaction.\n */\nexport interface AsyncKeyValueROTransaction {\n /**\n * Retrieves the data at the given key.\n * @param key The key to look under for data.\n */\n get(key: string, cb: BFSCallback): void;\n}\n\n/**\n * Represents an asynchronous read-write transaction.\n */\nexport interface AsyncKeyValueRWTransaction extends AsyncKeyValueROTransaction {\n /**\n * Adds the data to the store under the given key. Overwrites any existing\n * data.\n * @param key The key to add the data under.\n * @param data The data to add to the store.\n * @param overwrite If 'true', overwrite any existing data. If 'false',\n * avoids writing the data if the key exists.\n * @param cb Triggered with an error and whether or not the value was\n * committed.\n */\n put(key: string, data: Buffer, overwrite: boolean, cb: (e: ApiError,\n committed?: boolean) => void): void;\n /**\n * Deletes the data at the given key.\n * @param key The key to delete from the store.\n */\n del(key: string, cb: BFSOneArgCallback): void;\n /**\n * Commits the transaction.\n */\n commit(cb: BFSOneArgCallback): void;\n /**\n * Aborts and rolls back the transaction.\n */\n abort(cb: BFSOneArgCallback): void;\n}\n\nexport class AsyncKeyValueFile extends PreloadFile implements File {\n constructor(_fs: AsyncKeyValueFileSystem, _path: string, _flag: FileFlag, _stat: Stats, contents?: Buffer) {\n super(_fs, _path, _flag, _stat, contents);\n }\n\n public sync(cb: BFSOneArgCallback): void {\n if (this.isDirty()) {\n this._fs._sync(this.getPath(), this.getBuffer(), this.getStats(), (e?: ApiError) => {\n if (!e) {\n this.resetDirty();\n }\n cb(e);\n });\n } else {\n cb();\n }\n }\n\n public close(cb: BFSOneArgCallback): void {\n this.sync(cb);\n }\n}\n\n/**\n * An \"Asynchronous key-value file system\". Stores data to/retrieves data from\n * an underlying asynchronous key-value store.\n */\nexport class AsyncKeyValueFileSystem extends BaseFileSystem {\n public static isAvailable(): boolean { return true; }\n\n protected store: AsyncKeyValueStore;\n\n /**\n * Initializes the file system. Typically called by subclasses' async\n * constructors.\n */\n public init(store: AsyncKeyValueStore, cb: BFSOneArgCallback) {\n this.store = store;\n // INVARIANT: Ensure that the root exists.\n this.makeRootDirectory(cb);\n }\n public getName(): string { return this.store.name(); }\n public isReadOnly(): boolean { return false; }\n public supportsSymlinks(): boolean { return false; }\n public supportsProps(): boolean { return false; }\n public supportsSynch(): boolean { return false; }\n\n /**\n * Delete all contents stored in the file system.\n */\n public empty(cb: BFSOneArgCallback): void {\n this.store.clear((e?) => {\n if (noError(e, cb)) {\n // INVARIANT: Root always exists.\n this.makeRootDirectory(cb);\n }\n });\n }\n\n public rename(oldPath: string, newPath: string, cb: BFSOneArgCallback): void {\n const tx = this.store.beginTransaction('readwrite');\n const oldParent = path.dirname(oldPath), oldName = path.basename(oldPath);\n const newParent = path.dirname(newPath), newName = path.basename(newPath);\n const inodes: { [path: string]: Inode } = {};\n const lists: {\n [path: string]: { [file: string]: string }\n } = {};\n let errorOccurred: boolean = false;\n\n // Invariant: Can't move a folder inside itself.\n // This funny little hack ensures that the check passes only if oldPath\n // is a subpath of newParent. We append '/' to avoid matching folders that\n // are a substring of the bottom-most folder in the path.\n if ((newParent + '/').indexOf(oldPath + '/') === 0) {\n return cb(new ApiError(ErrorCode.EBUSY, oldParent));\n }\n\n /**\n * Responsible for Phase 2 of the rename operation: Modifying and\n * committing the directory listings. Called once we have successfully\n * retrieved both the old and new parent's inodes and listings.\n */\n const theOleSwitcharoo = (): void => {\n // Sanity check: Ensure both paths are present, and no error has occurred.\n if (errorOccurred || !lists.hasOwnProperty(oldParent) || !lists.hasOwnProperty(newParent)) {\n return;\n }\n const oldParentList = lists[oldParent], oldParentINode = inodes[oldParent],\n newParentList = lists[newParent], newParentINode = inodes[newParent];\n\n // Delete file from old parent.\n if (!oldParentList[oldName]) {\n cb(ApiError.ENOENT(oldPath));\n } else {\n const fileId = oldParentList[oldName];\n delete oldParentList[oldName];\n\n // Finishes off the renaming process by adding the file to the new\n // parent.\n const completeRename = () => {\n newParentList[newName] = fileId;\n // Commit old parent's list.\n tx.put(oldParentINode.id, Buffer.from(JSON.stringify(oldParentList)), true, (e: ApiError) => {\n if (noErrorTx(e, tx, cb)) {\n if (oldParent === newParent) {\n // DONE!\n tx.commit(cb);\n } else {\n // Commit new parent's list.\n tx.put(newParentINode.id, Buffer.from(JSON.stringify(newParentList)), true, (e: ApiError) => {\n if (noErrorTx(e, tx, cb)) {\n tx.commit(cb);\n }\n });\n }\n }\n });\n };\n\n if (newParentList[newName]) {\n // 'newPath' already exists. Check if it's a file or a directory, and\n // act accordingly.\n this.getINode(tx, newPath, newParentList[newName], (e: ApiError, inode?: Inode) => {\n if (noErrorTx(e, tx, cb)) {\n if (inode!.isFile()) {\n // Delete the file and continue.\n tx.del(inode!.id, (e?: ApiError) => {\n if (noErrorTx(e, tx, cb)) {\n tx.del(newParentList[newName], (e?: ApiError) => {\n if (noErrorTx(e, tx, cb)) {\n completeRename();\n }\n });\n }\n });\n } else {\n // Can't overwrite a directory using rename.\n tx.abort((e?) => {\n cb(ApiError.EPERM(newPath));\n });\n }\n }\n });\n } else {\n completeRename();\n }\n }\n };\n\n /**\n * Grabs a path's inode and directory listing, and shoves it into the\n * inodes and lists hashes.\n */\n const processInodeAndListings = (p: string): void => {\n this.findINodeAndDirListing(tx, p, (e?: ApiError | null, node?: Inode, dirList?: {[name: string]: string}): void => {\n if (e) {\n if (!errorOccurred) {\n errorOccurred = true;\n tx.abort(() => {\n cb(e);\n });\n }\n // If error has occurred already, just stop here.\n } else {\n inodes[p] = node!;\n lists[p] = dirList!;\n theOleSwitcharoo();\n }\n });\n };\n\n processInodeAndListings(oldParent);\n if (oldParent !== newParent) {\n processInodeAndListings(newParent);\n }\n }\n\n public stat(p: string, isLstat: boolean, cb: BFSCallback): void {\n const tx = this.store.beginTransaction('readonly');\n this.findINode(tx, p, (e: ApiError, inode?: Inode): void => {\n if (noError(e, cb)) {\n cb(null, inode!.toStats());\n }\n });\n }\n\n public createFile(p: string, flag: FileFlag, mode: number, cb: BFSCallback): void {\n const tx = this.store.beginTransaction('readwrite'),\n data = emptyBuffer();\n\n this.commitNewFile(tx, p, FileType.FILE, mode, data, (e: ApiError, newFile?: Inode): void => {\n if (noError(e, cb)) {\n cb(null, new AsyncKeyValueFile(this, p, flag, newFile!.toStats(), data));\n }\n });\n }\n\n public openFile(p: string, flag: FileFlag, cb: BFSCallback): void {\n const tx = this.store.beginTransaction('readonly');\n // Step 1: Grab the file's inode.\n this.findINode(tx, p, (e: ApiError, inode?: Inode) => {\n if (noError(e, cb)) {\n // Step 2: Grab the file's data.\n tx.get(inode!.id, (e: ApiError, data?: Buffer): void => {\n if (noError(e, cb)) {\n if (data === undefined) {\n cb(ApiError.ENOENT(p));\n } else {\n cb(null, new AsyncKeyValueFile(this, p, flag, inode!.toStats(), data));\n }\n }\n });\n }\n });\n }\n\n public unlink(p: string, cb: BFSOneArgCallback): void {\n this.removeEntry(p, false, cb);\n }\n\n public rmdir(p: string, cb: BFSOneArgCallback): void {\n // Check first if directory is empty.\n this.readdir(p, (err, files?) => {\n if (err) {\n cb(err);\n } else if (files!.length > 0) {\n cb(ApiError.ENOTEMPTY(p));\n } else {\n this.removeEntry(p, true, cb);\n }\n });\n }\n\n public mkdir(p: string, mode: number, cb: BFSOneArgCallback): void {\n const tx = this.store.beginTransaction('readwrite'),\n data = Buffer.from('{}');\n this.commitNewFile(tx, p, FileType.DIRECTORY, mode, data, cb);\n }\n\n public readdir(p: string, cb: BFSCallback): void {\n const tx = this.store.beginTransaction('readonly');\n this.findINode(tx, p, (e: ApiError, inode?: Inode) => {\n if (noError(e, cb)) {\n this.getDirListing(tx, p, inode!, (e: ApiError, dirListing?: {[name: string]: string}) => {\n if (noError(e, cb)) {\n cb(null, Object.keys(dirListing));\n }\n });\n }\n });\n }\n\n public _sync(p: string, data: Buffer, stats: Stats, cb: BFSOneArgCallback): void {\n // @todo Ensure mtime updates properly, and use that to determine if a data\n // update is required.\n const tx = this.store.beginTransaction('readwrite');\n // Step 1: Get the file node's ID.\n this._findINode(tx, path.dirname(p), path.basename(p), (e: ApiError, fileInodeId?: string): void => {\n if (noErrorTx(e, tx, cb)) {\n // Step 2: Get the file inode.\n this.getINode(tx, p, fileInodeId!, (e: ApiError, fileInode?: Inode): void => {\n if (noErrorTx(e, tx, cb)) {\n const inodeChanged: boolean = fileInode!.update(stats);\n // Step 3: Sync the data.\n tx.put(fileInode!.id, data, true, (e: ApiError): void => {\n if (noErrorTx(e, tx, cb)) {\n // Step 4: Sync the metadata (if it changed)!\n if (inodeChanged) {\n tx.put(fileInodeId!, fileInode!.toBuffer(), true, (e: ApiError): void => {\n if (noErrorTx(e, tx, cb)) {\n tx.commit(cb);\n }\n });\n } else {\n // No need to sync metadata; return.\n tx.commit(cb);\n }\n }\n });\n }\n });\n }\n });\n }\n\n /**\n * Checks if the root directory exists. Creates it if it doesn't.\n */\n private makeRootDirectory(cb: BFSOneArgCallback) {\n const tx = this.store.beginTransaction('readwrite');\n tx.get(ROOT_NODE_ID, (e: ApiError, data?: Buffer) => {\n if (e || data === undefined) {\n // Create new inode.\n const currTime = (new Date()).getTime(),\n // Mode 0666\n dirInode = new Inode(GenerateRandomID(), 4096, 511 | FileType.DIRECTORY, currTime, currTime, currTime);\n // If the root doesn't exist, the first random ID shouldn't exist,\n // either.\n tx.put(dirInode.id, getEmptyDirNode(), false, (e?: ApiError) => {\n if (noErrorTx(e, tx, cb)) {\n tx.put(ROOT_NODE_ID, dirInode.toBuffer(), false, (e?: ApiError) => {\n if (e) {\n tx.abort(() => { cb(e); });\n } else {\n tx.commit(cb);\n }\n });\n }\n });\n } else {\n // We're good.\n tx.commit(cb);\n }\n });\n }\n\n /**\n * Helper function for findINode.\n * @param parent The parent directory of the file we are attempting to find.\n * @param filename The filename of the inode we are attempting to find, minus\n * the parent.\n * @param cb Passed an error or the ID of the file's inode in the file system.\n */\n private _findINode(tx: AsyncKeyValueROTransaction, parent: string, filename: string, cb: BFSCallback): void {\n const handleDirectoryListings = (e?: ApiError | null, inode?: Inode, dirList?: {[name: string]: string}): void => {\n if (e) {\n cb(e);\n } else if (dirList![filename]) {\n cb(null, dirList![filename]);\n } else {\n cb(ApiError.ENOENT(path.resolve(parent, filename)));\n }\n };\n\n if (parent === '/') {\n if (filename === '') {\n // BASE CASE #1: Return the root's ID.\n cb(null, ROOT_NODE_ID);\n } else {\n // BASE CASE #2: Find the item in the root node.\n this.getINode(tx, parent, ROOT_NODE_ID, (e: ApiError, inode?: Inode): void => {\n if (noError(e, cb)) {\n this.getDirListing(tx, parent, inode!, (e: ApiError, dirList?: {[name: string]: string}): void => {\n // handle_directory_listings will handle e for us.\n handleDirectoryListings(e, inode, dirList);\n });\n }\n });\n }\n } else {\n // Get the parent directory's INode, and find the file in its directory\n // listing.\n this.findINodeAndDirListing(tx, parent, handleDirectoryListings);\n }\n }\n\n /**\n * Finds the Inode of the given path.\n * @param p The path to look up.\n * @param cb Passed an error or the Inode of the path p.\n * @todo memoize/cache\n */\n private findINode(tx: AsyncKeyValueROTransaction, p: string, cb: BFSCallback): void {\n this._findINode(tx, path.dirname(p), path.basename(p), (e: ApiError, id?: string): void => {\n if (noError(e, cb)) {\n this.getINode(tx, p, id!, cb);\n }\n });\n }\n\n /**\n * Given the ID of a node, retrieves the corresponding Inode.\n * @param tx The transaction to use.\n * @param p The corresponding path to the file (used for error messages).\n * @param id The ID to look up.\n * @param cb Passed an error or the inode under the given id.\n */\n private getINode(tx: AsyncKeyValueROTransaction, p: string, id: string, cb: BFSCallback): void {\n tx.get(id, (e: ApiError, data?: Buffer): void => {\n if (noError(e, cb)) {\n if (data === undefined) {\n cb(ApiError.ENOENT(p));\n } else {\n cb(null, Inode.fromBuffer(data));\n }\n }\n });\n }\n\n /**\n * Given the Inode of a directory, retrieves the corresponding directory\n * listing.\n */\n private getDirListing(tx: AsyncKeyValueROTransaction, p: string, inode: Inode, cb: BFSCallback<{ [fileName: string]: string }>): void {\n if (!inode.isDirectory()) {\n cb(ApiError.ENOTDIR(p));\n } else {\n tx.get(inode.id, (e: ApiError, data?: Buffer): void => {\n if (noError(e, cb)) {\n try {\n cb(null, JSON.parse(data!.toString()));\n } catch (e) {\n // Occurs when data is undefined, or corresponds to something other\n // than a directory listing. The latter should never occur unless\n // the file system is corrupted.\n cb(ApiError.ENOENT(p));\n }\n }\n });\n }\n }\n\n /**\n * Given a path to a directory, retrieves the corresponding INode and\n * directory listing.\n */\n private findINodeAndDirListing(tx: AsyncKeyValueROTransaction, p: string, cb: BFSThreeArgCallback): void {\n this.findINode(tx, p, (e: ApiError, inode?: Inode): void => {\n if (noError(e, cb)) {\n this.getDirListing(tx, p, inode!, (e, listing?) => {\n if (noError(e, cb)) {\n cb(null, inode!, listing!);\n }\n });\n }\n });\n }\n\n /**\n * Adds a new node under a random ID. Retries 5 times before giving up in\n * the exceedingly unlikely chance that we try to reuse a random GUID.\n * @param cb Passed an error or the GUID that the data was stored under.\n */\n private addNewNode(tx: AsyncKeyValueRWTransaction, data: Buffer, cb: BFSCallback): void {\n let retries = 0, currId: string;\n const reroll = () => {\n if (++retries === 5) {\n // Max retries hit. Return with an error.\n cb(new ApiError(ErrorCode.EIO, 'Unable to commit data to key-value store.'));\n } else {\n // Try again.\n currId = GenerateRandomID();\n tx.put(currId, data, false, (e: ApiError, committed?: boolean) => {\n if (e || !committed) {\n reroll();\n } else {\n // Successfully stored under 'currId'.\n cb(null, currId);\n }\n });\n }\n };\n reroll();\n }\n\n /**\n * Commits a new file (well, a FILE or a DIRECTORY) to the file system with\n * the given mode.\n * Note: This will commit the transaction.\n * @param p The path to the new file.\n * @param type The type of the new file.\n * @param mode The mode to create the new file with.\n * @param data The data to store at the file's data node.\n * @param cb Passed an error or the Inode for the new file.\n */\n private commitNewFile(tx: AsyncKeyValueRWTransaction, p: string, type: FileType, mode: number, data: Buffer, cb: BFSCallback): void {\n const parentDir = path.dirname(p),\n fname = path.basename(p),\n currTime = (new Date()).getTime();\n\n // Invariant: The root always exists.\n // If we don't check this prior to taking steps below, we will create a\n // file with name '' in root should p == '/'.\n if (p === '/') {\n return cb(ApiError.EEXIST(p));\n }\n\n // Let's build a pyramid of code!\n\n // Step 1: Get the parent directory's inode and directory listing\n this.findINodeAndDirListing(tx, parentDir, (e?: ApiError | null, parentNode?: Inode, dirListing?: {[name: string]: string}): void => {\n if (noErrorTx(e, tx, cb)) {\n if (dirListing![fname]) {\n // File already exists.\n tx.abort(() => {\n cb(ApiError.EEXIST(p));\n });\n } else {\n // Step 2: Commit data to store.\n this.addNewNode(tx, data, (e: ApiError, dataId?: string): void => {\n if (noErrorTx(e, tx, cb)) {\n // Step 3: Commit the file's inode to the store.\n const fileInode = new Inode(dataId!, data.length, mode | type, currTime, currTime, currTime);\n this.addNewNode(tx, fileInode.toBuffer(), (e: ApiError, fileInodeId?: string): void => {\n if (noErrorTx(e, tx, cb)) {\n // Step 4: Update parent directory's listing.\n dirListing![fname] = fileInodeId!;\n tx.put(parentNode!.id, Buffer.from(JSON.stringify(dirListing)), true, (e: ApiError): void => {\n if (noErrorTx(e, tx, cb)) {\n // Step 5: Commit and return the new inode.\n tx.commit((e?: ApiError): void => {\n if (noErrorTx(e, tx, cb)) {\n cb(null, fileInode);\n }\n });\n }\n });\n }\n });\n }\n });\n }\n }\n });\n }\n\n /**\n * Remove all traces of the given path from the file system.\n * @param p The path to remove from the file system.\n * @param isDir Does the path belong to a directory, or a file?\n * @todo Update mtime.\n */\n private removeEntry(p: string, isDir: boolean, cb: BFSOneArgCallback): void {\n const tx = this.store.beginTransaction('readwrite'),\n parent: string = path.dirname(p), fileName: string = path.basename(p);\n // Step 1: Get parent directory's node and directory listing.\n this.findINodeAndDirListing(tx, parent, (e?: ApiError | null, parentNode?: Inode, parentListing?: {[name: string]: string}): void => {\n if (noErrorTx(e, tx, cb)) {\n if (!parentListing![fileName]) {\n tx.abort(() => {\n cb(ApiError.ENOENT(p));\n });\n } else {\n // Remove from directory listing of parent.\n const fileNodeId = parentListing![fileName];\n delete parentListing![fileName];\n // Step 2: Get file inode.\n this.getINode(tx, p, fileNodeId, (e: ApiError, fileNode?: Inode): void => {\n if (noErrorTx(e, tx, cb)) {\n if (!isDir && fileNode!.isDirectory()) {\n tx.abort(() => {\n cb(ApiError.EISDIR(p));\n });\n } else if (isDir && !fileNode!.isDirectory()) {\n tx.abort(() => {\n cb(ApiError.ENOTDIR(p));\n });\n } else {\n // Step 3: Delete data.\n tx.del(fileNode!.id, (e?: ApiError): void => {\n if (noErrorTx(e, tx, cb)) {\n // Step 4: Delete node.\n tx.del(fileNodeId, (e?: ApiError): void => {\n if (noErrorTx(e, tx, cb)) {\n // Step 5: Update directory listing.\n tx.put(parentNode!.id, Buffer.from(JSON.stringify(parentListing)), true, (e: ApiError): void => {\n if (noErrorTx(e, tx, cb)) {\n tx.commit(cb);\n }\n });\n }\n });\n }\n });\n }\n }\n });\n }\n }\n });\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ../../../../src/generic/key_value_filesystem.ts","import {BFSOneArgCallback, BFSCallback, FileSystemOptions} from '../core/file_system';\nimport {AsyncKeyValueROTransaction, AsyncKeyValueRWTransaction, AsyncKeyValueStore, AsyncKeyValueFileSystem} from '../generic/key_value_filesystem';\nimport {ApiError, ErrorCode} from '../core/api_error';\nimport global from '../core/global';\nimport {arrayBuffer2Buffer, buffer2ArrayBuffer, deprecationMessage} from '../core/util';\n/**\n * Get the indexedDB constructor for the current browser.\n * @hidden\n */\nconst indexedDB: IDBFactory = global.indexedDB ||\n ( global).mozIndexedDB ||\n ( global).webkitIndexedDB ||\n global.msIndexedDB;\n\n/**\n * Converts a DOMException or a DOMError from an IndexedDB event into a\n * standardized BrowserFS API error.\n * @hidden\n */\nfunction convertError(e: {name: string}, message: string = e.toString()): ApiError {\n switch (e.name) {\n case \"NotFoundError\":\n return new ApiError(ErrorCode.ENOENT, message);\n case \"QuotaExceededError\":\n return new ApiError(ErrorCode.ENOSPC, message);\n default:\n // The rest do not seem to map cleanly to standard error codes.\n return new ApiError(ErrorCode.EIO, message);\n }\n}\n\n/**\n * Produces a new onerror handler for IDB. Our errors are always fatal, so we\n * handle them generically: Call the user-supplied callback with a translated\n * version of the error, and let the error bubble up.\n * @hidden\n */\nfunction onErrorHandler(cb: (e: ApiError) => void, code: ErrorCode = ErrorCode.EIO, message: string | null = null): (e?: any) => void {\n return function(e?: any): void {\n // Prevent the error from canceling the transaction.\n e.preventDefault();\n cb(new ApiError(code, message !== null ? message : undefined));\n };\n}\n\n/**\n * @hidden\n */\nexport class IndexedDBROTransaction implements AsyncKeyValueROTransaction {\n constructor(public tx: IDBTransaction, public store: IDBObjectStore) { }\n\n public get(key: string, cb: BFSCallback): void {\n try {\n const r: IDBRequest = this.store.get(key);\n r.onerror = onErrorHandler(cb);\n r.onsuccess = (event) => {\n // IDB returns the value 'undefined' when you try to get keys that\n // don't exist. The caller expects this behavior.\n const result: any = ( event.target).result;\n if (result === undefined) {\n cb(null, result);\n } else {\n // IDB data is stored as an ArrayBuffer\n cb(null, arrayBuffer2Buffer(result));\n }\n };\n } catch (e) {\n cb(convertError(e));\n }\n }\n}\n\n/**\n * @hidden\n */\nexport class IndexedDBRWTransaction extends IndexedDBROTransaction implements AsyncKeyValueRWTransaction, AsyncKeyValueROTransaction {\n constructor(tx: IDBTransaction, store: IDBObjectStore) {\n super(tx, store);\n }\n\n public put(key: string, data: Buffer, overwrite: boolean, cb: BFSCallback): void {\n try {\n const arraybuffer = buffer2ArrayBuffer(data);\n let r: IDBRequest;\n if (overwrite) {\n r = this.store.put(arraybuffer, key);\n } else {\n // 'add' will never overwrite an existing key.\n r = this.store.add(arraybuffer, key);\n }\n // XXX: NEED TO RETURN FALSE WHEN ADD HAS A KEY CONFLICT. NO ERROR.\n r.onerror = onErrorHandler(cb);\n r.onsuccess = (event) => {\n cb(null, true);\n };\n } catch (e) {\n cb(convertError(e));\n }\n }\n\n public del(key: string, cb: BFSOneArgCallback): void {\n try {\n // NOTE: IE8 has a bug with identifiers named 'delete' unless used as a string\n // like this.\n // http://stackoverflow.com/a/26479152\n const r: IDBRequest = this.store['delete'](key);\n r.onerror = onErrorHandler(cb);\n r.onsuccess = (event) => {\n cb();\n };\n } catch (e) {\n cb(convertError(e));\n }\n }\n\n public commit(cb: BFSOneArgCallback): void {\n // Return to the event loop to commit the transaction.\n setTimeout(cb, 0);\n }\n\n public abort(cb: BFSOneArgCallback): void {\n let _e: ApiError | null = null;\n try {\n this.tx.abort();\n } catch (e) {\n _e = convertError(e);\n } finally {\n cb(_e);\n }\n }\n}\n\nexport class IndexedDBStore implements AsyncKeyValueStore {\n private db: IDBDatabase;\n\n constructor(cb: BFSCallback, private storeName: string = 'browserfs') {\n const openReq: IDBOpenDBRequest = indexedDB.open(this.storeName, 1);\n\n openReq.onupgradeneeded = (event) => {\n const db: IDBDatabase = ( event.target).result;\n // Huh. This should never happen; we're at version 1. Why does another\n // database exist?\n if (db.objectStoreNames.contains(this.storeName)) {\n db.deleteObjectStore(this.storeName);\n }\n db.createObjectStore(this.storeName);\n };\n\n openReq.onsuccess = (event) => {\n this.db = ( event.target).result;\n cb(null, this);\n };\n\n openReq.onerror = onErrorHandler(cb, ErrorCode.EACCES);\n }\n\n public name(): string {\n return IndexedDBFileSystem.Name + \" - \" + this.storeName;\n }\n\n public clear(cb: BFSOneArgCallback): void {\n try {\n const tx = this.db.transaction(this.storeName, 'readwrite'),\n objectStore = tx.objectStore(this.storeName),\n r: IDBRequest = objectStore.clear();\n r.onsuccess = (event) => {\n // Use setTimeout to commit transaction.\n setTimeout(cb, 0);\n };\n r.onerror = onErrorHandler(cb);\n } catch (e) {\n cb(convertError(e));\n }\n }\n\n public beginTransaction(type: 'readonly'): AsyncKeyValueROTransaction;\n public beginTransaction(type: 'readwrite'): AsyncKeyValueRWTransaction;\n public beginTransaction(type: string = 'readonly'): AsyncKeyValueROTransaction {\n const tx = this.db.transaction(this.storeName, type),\n objectStore = tx.objectStore(this.storeName);\n if (type === 'readwrite') {\n return new IndexedDBRWTransaction(tx, objectStore);\n } else if (type === 'readonly') {\n return new IndexedDBROTransaction(tx, objectStore);\n } else {\n throw new ApiError(ErrorCode.EINVAL, 'Invalid transaction type.');\n }\n }\n}\n\n/**\n * Configuration options for the IndexedDB file system.\n */\nexport interface IndexedDBFileSystemOptions {\n // The name of this file system. You can have multiple IndexedDB file systems operating\n // at once, but each must have a different name.\n storeName?: string;\n}\n\n/**\n * A file system that uses the IndexedDB key value file system.\n */\nexport default class IndexedDBFileSystem extends AsyncKeyValueFileSystem {\n public static readonly Name = \"IndexedDB\";\n\n public static readonly Options: FileSystemOptions = {\n storeName: {\n type: \"string\",\n optional: true,\n description: \"The name of this file system. You can have multiple IndexedDB file systems operating at once, but each must have a different name.\"\n }\n };\n\n /**\n * Constructs an IndexedDB file system with the given options.\n */\n public static Create(opts: IndexedDBFileSystemOptions, cb: BFSCallback): void {\n // tslint:disable-next-line:no-unused-new\n new IndexedDBFileSystem(cb, opts.storeName, false);\n // tslint:enable-next-line:no-unused-new\n }\n public static isAvailable(): boolean {\n // In Safari's private browsing mode, indexedDB.open returns NULL.\n // In Firefox, it throws an exception.\n // In Chrome, it \"just works\", and clears the database when you leave the page.\n // Untested: Opera, IE.\n try {\n return typeof indexedDB !== 'undefined' && null !== indexedDB.open(\"__browserfs_test__\");\n } catch (e) {\n return false;\n }\n }\n /**\n * **Deprecated. Use IndexedDB.Create() method instead.**\n *\n * Constructs an IndexedDB file system.\n * @param cb Called once the database is instantiated and ready for use.\n * Passes an error if there was an issue instantiating the database.\n * @param storeName The name of this file system. You can have\n * multiple IndexedDB file systems operating at once, but each must have\n * a different name.\n */\n constructor(cb: BFSCallback, storeName?: string, deprecateMsg: boolean = true) {\n super();\n this.store = new IndexedDBStore((e): void => {\n if (e) {\n cb(e);\n } else {\n this.init(this.store, (e?) => {\n cb(e, this);\n });\n }\n }, storeName);\n deprecationMessage(deprecateMsg, IndexedDBFileSystem.Name, {storeName: storeName});\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ../../../../src/backend/IndexedDB.ts","import {FileSystem, BaseFileSystem, BFSOneArgCallback, BFSCallback, FileSystemOptions} from '../core/file_system';\nimport InMemoryFileSystem from './InMemory';\nimport {ApiError, ErrorCode} from '../core/api_error';\nimport fs from '../core/node_fs';\nimport * as path from 'path';\nimport {mkdirpSync} from '../core/util';\n\n/**\n * Configuration options for the MountableFileSystem backend.\n */\nexport interface MountableFileSystemOptions {\n // Locations of mount points. Can be empty.\n [mountPoint: string]: FileSystem;\n}\n\n/**\n * The MountableFileSystem allows you to mount multiple backend types or\n * multiple instantiations of the same backend into a single file system tree.\n * The file systems do not need to know about each other; all interactions are\n * automatically facilitated through this interface.\n *\n * For example, if a file system is mounted at /mnt/blah, and a request came in\n * for /mnt/blah/foo.txt, the file system would see a request for /foo.txt.\n *\n * You can mount file systems when you configure the file system:\n * ```javascript\n * BrowserFS.configure({\n * fs: \"MountableFileSystem\",\n * options: {\n * '/data': { fs: 'XmlHttpRequest', options: { index: \"http://mysite.com/files/index.json\" } },\n * '/home': { fs: 'LocalStorage' }\n * }\n * }, function(e) {\n *\n * });\n * ```\n *\n * For advanced users, you can also mount file systems *after* MFS is constructed:\n * ```javascript\n * BrowserFS.FileSystem.XmlHttpRequest.Create({\n * index: \"http://mysite.com/files/index.json\"\n * }, function(e, xhrfs) {\n * BrowserFS.FileSystem.MountableFileSystem.Create({\n * '/data': xhrfs\n * }, function(e, mfs) {\n * BrowserFS.initialize(mfs);\n *\n * // Added after-the-fact...\n * BrowserFS.FileSystem.LocalStorage.Create(function(e, lsfs) {\n * mfs.mount('/home', lsfs);\n * });\n * });\n * });\n * ```\n *\n * Since MountableFileSystem simply proxies requests to mounted file systems, it supports all of the operations that the mounted file systems support.\n *\n * With no mounted file systems, `MountableFileSystem` acts as a simple `InMemory` filesystem.\n */\nexport default class MountableFileSystem extends BaseFileSystem implements FileSystem {\n public static readonly Name = \"MountableFileSystem\";\n\n public static readonly Options: FileSystemOptions = {};\n\n /**\n * Creates a MountableFileSystem instance with the given options.\n */\n public static Create(opts: MountableFileSystemOptions, cb: BFSCallback): void {\n const fs = new MountableFileSystem();\n Object.keys(opts).forEach((mountPoint) => {\n fs.mount(mountPoint, opts[mountPoint]);\n });\n cb(null, fs);\n }\n public static isAvailable(): boolean {\n return true;\n }\n\n private mntMap: {[path: string]: FileSystem};\n // Contains the list of mount points in mntMap, sorted by string length in decreasing order.\n // Ensures that we scan the most specific mount points for a match first, which lets us\n // nest mount points.\n private mountList: string[] = [];\n private rootFs: FileSystem;\n\n /**\n * Creates a new, empty MountableFileSystem.\n */\n constructor() {\n super();\n this.mntMap = {};\n // The InMemory file system serves purely to provide directory listings for\n // mounted file systems.\n this.rootFs = new InMemoryFileSystem();\n }\n\n /**\n * Mounts the file system at the given mount point.\n */\n public mount(mountPoint: string, fs: FileSystem): void {\n if (mountPoint[0] !== '/') {\n mountPoint = `/${mountPoint}`;\n }\n mountPoint = path.resolve(mountPoint);\n if (this.mntMap[mountPoint]) {\n throw new ApiError(ErrorCode.EINVAL, \"Mount point \" + mountPoint + \" is already taken.\");\n }\n mkdirpSync(mountPoint, 0x1ff, this.rootFs);\n this.mntMap[mountPoint] = fs;\n this.mountList.push(mountPoint);\n this.mountList = this.mountList.sort((a, b) => b.length - a.length);\n }\n\n public umount(mountPoint: string): void {\n if (mountPoint[0] !== '/') {\n mountPoint = `/${mountPoint}`;\n }\n mountPoint = path.resolve(mountPoint);\n if (!this.mntMap[mountPoint]) {\n throw new ApiError(ErrorCode.EINVAL, \"Mount point \" + mountPoint + \" is already unmounted.\");\n }\n delete this.mntMap[mountPoint];\n this.mountList.splice(this.mountList.indexOf(mountPoint), 1);\n\n while (mountPoint !== '/') {\n if (this.rootFs.readdirSync(mountPoint).length === 0) {\n this.rootFs.rmdirSync(mountPoint);\n mountPoint = path.dirname(mountPoint);\n } else {\n break;\n }\n }\n }\n\n /**\n * Returns the file system that the path points to.\n */\n public _getFs(path: string): {fs: FileSystem; path: string} {\n const mountList = this.mountList, len = mountList.length;\n for (let i = 0; i < len; i++) {\n const mountPoint = mountList[i];\n // We know path is normalized, so it is a substring of the mount point.\n if (mountPoint.length <= path.length && path.indexOf(mountPoint) === 0) {\n path = path.substr(mountPoint.length > 1 ? mountPoint.length : 0);\n if (path === '') {\n path = '/';\n }\n return {fs: this.mntMap[mountPoint], path: path};\n }\n }\n // Query our root file system.\n return {fs: this.rootFs, path: path};\n }\n\n // Global information methods\n\n public getName(): string {\n return MountableFileSystem.Name;\n }\n\n public diskSpace(path: string, cb: (total: number, free: number) => void): void {\n cb(0, 0);\n }\n\n public isReadOnly(): boolean {\n return false;\n }\n\n public supportsLinks(): boolean {\n // I'm not ready for cross-FS links yet.\n return false;\n }\n\n public supportsProps(): boolean {\n return false;\n }\n\n public supportsSynch(): boolean {\n return true;\n }\n\n /**\n * Fixes up error messages so they mention the mounted file location relative\n * to the MFS root, not to the particular FS's root.\n * Mutates the input error, and returns it.\n */\n public standardizeError(err: ApiError, path: string, realPath: string): ApiError {\n const index = err.message.indexOf(path);\n if (index !== -1) {\n err.message = err.message.substr(0, index) + realPath + err.message.substr(index + path.length);\n err.path = realPath;\n }\n return err;\n }\n\n // The following methods involve multiple file systems, and thus have custom\n // logic.\n // Note that we go through the Node API to use its robust default argument\n // processing.\n\n public rename(oldPath: string, newPath: string, cb: BFSOneArgCallback): void {\n // Scenario 1: old and new are on same FS.\n const fs1rv = this._getFs(oldPath);\n const fs2rv = this._getFs(newPath);\n if (fs1rv.fs === fs2rv.fs) {\n return fs1rv.fs.rename(fs1rv.path, fs2rv.path, (e?: ApiError) => {\n if (e) {\n this.standardizeError(this.standardizeError(e, fs1rv.path, oldPath), fs2rv.path, newPath);\n }\n cb(e);\n });\n }\n\n // Scenario 2: Different file systems.\n // Read old file, write new file, delete old file.\n return fs.readFile(oldPath, function(err: ApiError, data?: any) {\n if (err) {\n return cb(err);\n }\n fs.writeFile(newPath, data, function(err: ApiError) {\n if (err) {\n return cb(err);\n }\n fs.unlink(oldPath, cb);\n });\n });\n }\n\n public renameSync(oldPath: string, newPath: string): void {\n // Scenario 1: old and new are on same FS.\n const fs1rv = this._getFs(oldPath);\n const fs2rv = this._getFs(newPath);\n if (fs1rv.fs === fs2rv.fs) {\n try {\n return fs1rv.fs.renameSync(fs1rv.path, fs2rv.path);\n } catch (e) {\n this.standardizeError(this.standardizeError(e, fs1rv.path, oldPath), fs2rv.path, newPath);\n throw e;\n }\n }\n // Scenario 2: Different file systems.\n const data = fs.readFileSync(oldPath);\n fs.writeFileSync(newPath, data);\n return fs.unlinkSync(oldPath);\n }\n\n public readdirSync(p: string): string[] {\n const fsInfo = this._getFs(p);\n\n // If null, rootfs did not have the directory\n // (or the target FS is the root fs).\n let rv: string[] | null = null;\n // Mount points are all defined in the root FS.\n // Ensure that we list those, too.\n if (fsInfo.fs !== this.rootFs) {\n try {\n rv = this.rootFs.readdirSync(p);\n } catch (e) {\n // Ignore.\n }\n }\n\n try {\n const rv2 = fsInfo.fs.readdirSync(fsInfo.path);\n if (rv === null) {\n return rv2;\n } else {\n // Filter out duplicates.\n return rv2.concat(rv.filter((val) => rv2.indexOf(val) === -1));\n }\n } catch (e) {\n if (rv === null) {\n throw this.standardizeError(e, fsInfo.path, p);\n } else {\n // The root FS had something.\n return rv;\n }\n }\n }\n\n public readdir(p: string, cb: BFSCallback): void {\n const fsInfo = this._getFs(p);\n fsInfo.fs.readdir(fsInfo.path, (err, files) => {\n if (fsInfo.fs !== this.rootFs) {\n try {\n const rv = this.rootFs.readdirSync(p);\n if (files) {\n // Filter out duplicates.\n files = files.concat(rv.filter((val) => files!.indexOf(val) === -1));\n } else {\n files = rv;\n }\n } catch (e) {\n // Root FS and target FS did not have directory.\n if (err) {\n return cb(this.standardizeError(err, fsInfo.path, p));\n }\n }\n } else if (err) {\n // Root FS and target FS are the same, and did not have directory.\n return cb(this.standardizeError(err, fsInfo.path, p));\n }\n\n cb(null, files);\n });\n }\n\n public rmdirSync(p: string): void {\n const fsInfo = this._getFs(p);\n if (this._containsMountPt(p)) {\n throw ApiError.ENOTEMPTY(p);\n } else {\n try {\n fsInfo.fs.rmdirSync(fsInfo.path);\n } catch (e) {\n throw this.standardizeError(e, fsInfo.path, p);\n }\n }\n }\n\n public rmdir(p: string, cb: BFSOneArgCallback): void {\n const fsInfo = this._getFs(p);\n if (this._containsMountPt(p)) {\n cb(ApiError.ENOTEMPTY(p));\n } else {\n fsInfo.fs.rmdir(fsInfo.path, (err?) => {\n cb(err ? this.standardizeError(err, fsInfo.path, p) : null);\n });\n }\n }\n\n /**\n * Returns true if the given path contains a mount point.\n */\n private _containsMountPt(p: string): boolean {\n const mountPoints = this.mountList, len = mountPoints.length;\n for (let i = 0; i < len; i++) {\n const pt = mountPoints[i];\n if (pt.length >= p.length && pt.slice(0, p.length) === p) {\n return true;\n }\n }\n return false;\n }\n}\n\n/**\n * Tricky: Define all of the functions that merely forward arguments to the\n * relevant file system, or return/throw an error.\n * Take advantage of the fact that the *first* argument is always the path, and\n * the *last* is the callback function (if async).\n * @todo Can use numArgs to make proxying more efficient.\n * @hidden\n */\nfunction defineFcn(name: string, isSync: boolean, numArgs: number): (...args: any[]) => any {\n if (isSync) {\n return function(this: MountableFileSystem, ...args: any[]) {\n const path = args[0];\n const rv = this._getFs(path);\n args[0] = rv.path;\n try {\n return ( rv.fs)[name].apply(rv.fs, args);\n } catch (e) {\n this.standardizeError(e, rv.path, path);\n throw e;\n }\n };\n } else {\n return function(this: MountableFileSystem, ...args: any[]) {\n const path = args[0];\n const rv = this._getFs(path);\n args[0] = rv.path;\n if (typeof args[args.length - 1] === 'function') {\n const cb = args[args.length - 1];\n args[args.length - 1] = (...args: any[]) => {\n if (args.length > 0 && args[0] instanceof ApiError) {\n this.standardizeError(args[0], rv.path, path);\n }\n cb.apply(null, args);\n };\n }\n return ( rv.fs)[name].apply(rv.fs, args);\n };\n }\n}\n\n/**\n * @hidden\n */\nconst fsCmdMap = [\n // 1 arg functions\n ['exists', 'unlink', 'readlink'],\n // 2 arg functions\n ['stat', 'mkdir', 'realpath', 'truncate'],\n // 3 arg functions\n ['open', 'readFile', 'chmod', 'utimes'],\n // 4 arg functions\n ['chown'],\n // 5 arg functions\n ['writeFile', 'appendFile']];\n\nfor (let i = 0; i < fsCmdMap.length; i++) {\n const cmds = fsCmdMap[i];\n for (const fnName of cmds) {\n ( MountableFileSystem.prototype)[fnName] = defineFcn(fnName, false, i + 1);\n ( MountableFileSystem.prototype)[fnName + 'Sync'] = defineFcn(fnName + 'Sync', true, i + 1);\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ../../../../src/backend/MountableFileSystem.ts","import {FileSystem, BaseFileSystem, BFSOneArgCallback, BFSCallback, FileSystemOptions} from '../core/file_system';\nimport {ApiError, ErrorCode} from '../core/api_error';\nimport {FileFlag, ActionType} from '../core/file_flag';\nimport {File} from '../core/file';\nimport {deprecationMessage} from '../core/util';\nimport {default as Stats} from '../core/node_fs_stats';\nimport PreloadFile from '../generic/preload_file';\nimport LockedFS from '../generic/locked_fs';\nimport * as path from 'path';\n/**\n * @hidden\n */\nconst deletionLogPath = '/.deletedFiles.log';\n\n/**\n * Given a read-only mode, makes it writable.\n * @hidden\n */\nfunction makeModeWritable(mode: number): number {\n return 0o222 | mode;\n}\n\n/**\n * @hidden\n */\nfunction getFlag(f: string): FileFlag {\n return FileFlag.getFileFlag(f);\n}\n\n/**\n * Overlays a RO file to make it writable.\n */\nclass OverlayFile extends PreloadFile implements File {\n constructor(fs: UnlockedOverlayFS, path: string, flag: FileFlag, stats: Stats, data: Buffer) {\n super(fs, path, flag, stats, data);\n }\n\n public sync(cb: BFSOneArgCallback): void {\n if (!this.isDirty()) {\n cb(null);\n return;\n }\n\n this._fs._syncAsync(this, (err: ApiError) => {\n this.resetDirty();\n cb(err);\n });\n }\n\n public syncSync(): void {\n if (this.isDirty()) {\n this._fs._syncSync(this);\n this.resetDirty();\n }\n }\n\n public close(cb: BFSOneArgCallback): void {\n this.sync(cb);\n }\n\n public closeSync(): void {\n this.syncSync();\n }\n}\n\n/**\n * *INTERNAL, DO NOT USE DIRECTLY!*\n *\n * Core OverlayFS class that contains no locking whatsoever. We wrap these objects\n * in a LockedFS to prevent races.\n */\nexport class UnlockedOverlayFS extends BaseFileSystem implements FileSystem {\n public static isAvailable(): boolean {\n return true;\n }\n\n private _writable: FileSystem;\n private _readable: FileSystem;\n private _isInitialized: boolean = false;\n private _initializeCallbacks: (BFSOneArgCallback)[] = [];\n private _deletedFiles: {[path: string]: boolean} = {};\n private _deleteLog: string = '';\n // If 'true', we have scheduled a delete log update.\n private _deleteLogUpdatePending: boolean = false;\n // If 'true', a delete log update is needed after the scheduled delete log\n // update finishes.\n private _deleteLogUpdateNeeded: boolean = false;\n // If there was an error updating the delete log...\n private _deleteLogError: ApiError | null = null;\n\n constructor(writable: FileSystem, readable: FileSystem) {\n super();\n this._writable = writable;\n this._readable = readable;\n if (this._writable.isReadOnly()) {\n throw new ApiError(ErrorCode.EINVAL, \"Writable file system must be writable.\");\n }\n }\n\n public getOverlayedFileSystems(): { readable: FileSystem; writable: FileSystem; } {\n return {\n readable: this._readable,\n writable: this._writable\n };\n }\n\n public _syncAsync(file: PreloadFile, cb: BFSOneArgCallback): void {\n this.createParentDirectoriesAsync(file.getPath(), (err?: ApiError) => {\n if (err) {\n return cb(err);\n }\n this._writable.writeFile(file.getPath(), file.getBuffer(), null, getFlag('w'), file.getStats().mode, cb);\n });\n }\n\n public _syncSync(file: PreloadFile): void {\n this.createParentDirectories(file.getPath());\n this._writable.writeFileSync(file.getPath(), file.getBuffer(), null, getFlag('w'), file.getStats().mode);\n }\n\n public getName() {\n return OverlayFS.Name;\n }\n\n /**\n * Called once to load up metadata stored on the writable file system.\n */\n public initialize(cb: BFSOneArgCallback): void {\n const callbackArray = this._initializeCallbacks;\n\n const end = (e?: ApiError): void => {\n this._isInitialized = !e;\n this._initializeCallbacks = [];\n callbackArray.forEach(((cb) => cb(e)));\n };\n\n // if we're already initialized, immediately invoke the callback\n if (this._isInitialized) {\n return cb();\n }\n\n callbackArray.push(cb);\n // The first call to initialize initializes, the rest wait for it to complete.\n if (callbackArray.length !== 1) {\n return;\n }\n\n // Read deletion log, process into metadata.\n this._writable.readFile(deletionLogPath, 'utf8', getFlag('r'), (err: ApiError, data?: string) => {\n if (err) {\n // ENOENT === Newly-instantiated file system, and thus empty log.\n if (err.errno !== ErrorCode.ENOENT) {\n return end(err);\n }\n } else {\n this._deleteLog = data!;\n }\n this._reparseDeletionLog();\n end();\n });\n }\n\n public isReadOnly(): boolean { return false; }\n public supportsSynch(): boolean { return this._readable.supportsSynch() && this._writable.supportsSynch(); }\n public supportsLinks(): boolean { return false; }\n public supportsProps(): boolean { return this._readable.supportsProps() && this._writable.supportsProps(); }\n\n public getDeletionLog(): string {\n return this._deleteLog;\n }\n\n public restoreDeletionLog(log: string): void {\n this._deleteLog = log;\n this._reparseDeletionLog();\n this.updateLog('');\n }\n\n public rename(oldPath: string, newPath: string, cb: BFSOneArgCallback): void {\n if (!this.checkInitAsync(cb) || this.checkPathAsync(oldPath, cb) || this.checkPathAsync(newPath, cb)) {\n return;\n }\n\n if (oldPath === deletionLogPath || newPath === deletionLogPath) {\n return cb(ApiError.EPERM('Cannot rename deletion log.'));\n }\n\n // nothing to do if paths match\n if (oldPath === newPath) {\n return cb();\n }\n\n this.stat(oldPath, false, (oldErr: ApiError, oldStats?: Stats) => {\n if (oldErr) {\n return cb(oldErr);\n }\n\n return this.stat(newPath, false, (newErr: ApiError, newStats?: Stats) => {\n const self = this;\n // precondition: both oldPath and newPath exist and are dirs.\n // decreases: |files|\n // Need to move *every file/folder* currently stored on\n // readable to its new location on writable.\n function copyDirContents(files: string[]): void {\n const file = files.shift();\n if (!file) {\n return cb();\n }\n\n const oldFile = path.resolve(oldPath, file);\n const newFile = path.resolve(newPath, file);\n\n // Recursion! Should work for any nested files / folders.\n self.rename(oldFile, newFile, (err?: ApiError) => {\n if (err) {\n return cb(err);\n }\n copyDirContents(files);\n });\n }\n\n let mode = 0o777;\n\n // from linux's rename(2) manpage: oldpath can specify a\n // directory. In this case, newpath must either not exist, or\n // it must specify an empty directory.\n if (oldStats!.isDirectory()) {\n if (newErr) {\n if (newErr.errno !== ErrorCode.ENOENT) {\n return cb(newErr);\n }\n\n return this._writable.exists(oldPath, (exists: boolean) => {\n // simple case - both old and new are on the writable layer\n if (exists) {\n return this._writable.rename(oldPath, newPath, cb);\n }\n\n this._writable.mkdir(newPath, mode, (mkdirErr?: ApiError) => {\n if (mkdirErr) {\n return cb(mkdirErr);\n }\n\n this._readable.readdir(oldPath, (err: ApiError, files?: string[]) => {\n if (err) {\n return cb();\n }\n copyDirContents(files!);\n });\n });\n });\n }\n\n mode = newStats!.mode;\n if (!newStats!.isDirectory()) {\n return cb(ApiError.ENOTDIR(newPath));\n }\n\n this.readdir(newPath, (readdirErr: ApiError, files?: string[]) => {\n if (files && files.length) {\n return cb(ApiError.ENOTEMPTY(newPath));\n }\n\n this._readable.readdir(oldPath, (err: ApiError, files?: string[]) => {\n if (err) {\n return cb();\n }\n copyDirContents(files!);\n });\n });\n }\n\n if (newStats && newStats.isDirectory()) {\n return cb(ApiError.EISDIR(newPath));\n }\n\n this.readFile(oldPath, null, getFlag('r'), (err: ApiError, data?: any) => {\n if (err) {\n return cb(err);\n }\n\n return this.writeFile(newPath, data, null, getFlag('w'), oldStats!.mode, (err: ApiError) => {\n if (err) {\n return cb(err);\n }\n return this.unlink(oldPath, cb);\n });\n });\n });\n });\n }\n\n public renameSync(oldPath: string, newPath: string): void {\n this.checkInitialized();\n this.checkPath(oldPath);\n this.checkPath(newPath);\n if (oldPath === deletionLogPath || newPath === deletionLogPath) {\n throw ApiError.EPERM('Cannot rename deletion log.');\n }\n // Write newPath using oldPath's contents, delete oldPath.\n const oldStats = this.statSync(oldPath, false);\n if (oldStats.isDirectory()) {\n // Optimization: Don't bother moving if old === new.\n if (oldPath === newPath) {\n return;\n }\n\n let mode = 0o777;\n if (this.existsSync(newPath)) {\n const stats = this.statSync(newPath, false);\n mode = stats.mode;\n if (stats.isDirectory()) {\n if (this.readdirSync(newPath).length > 0) {\n throw ApiError.ENOTEMPTY(newPath);\n }\n } else {\n throw ApiError.ENOTDIR(newPath);\n }\n }\n\n // Take care of writable first. Move any files there, or create an empty directory\n // if it doesn't exist.\n if (this._writable.existsSync(oldPath)) {\n this._writable.renameSync(oldPath, newPath);\n } else if (!this._writable.existsSync(newPath)) {\n this._writable.mkdirSync(newPath, mode);\n }\n\n // Need to move *every file/folder* currently stored on readable to its new location\n // on writable.\n if (this._readable.existsSync(oldPath)) {\n this._readable.readdirSync(oldPath).forEach((name) => {\n // Recursion! Should work for any nested files / folders.\n this.renameSync(path.resolve(oldPath, name), path.resolve(newPath, name));\n });\n }\n } else {\n if (this.existsSync(newPath) && this.statSync(newPath, false).isDirectory()) {\n throw ApiError.EISDIR(newPath);\n }\n\n this.writeFileSync(newPath,\n this.readFileSync(oldPath, null, getFlag('r')), null, getFlag('w'), oldStats.mode);\n }\n\n if (oldPath !== newPath && this.existsSync(oldPath)) {\n this.unlinkSync(oldPath);\n }\n }\n\n public stat(p: string, isLstat: boolean, cb: BFSCallback): void {\n if (!this.checkInitAsync(cb)) {\n return;\n }\n this._writable.stat(p, isLstat, (err: ApiError, stat?: Stats) => {\n if (err && err.errno === ErrorCode.ENOENT) {\n if (this._deletedFiles[p]) {\n cb(ApiError.ENOENT(p));\n }\n this._readable.stat(p, isLstat, (err: ApiError, stat?: Stats) => {\n if (stat) {\n // Make the oldStat's mode writable. Preserve the topmost\n // part of the mode, which specifies if it is a file or a\n // directory.\n stat = stat.clone();\n stat.mode = makeModeWritable(stat.mode);\n }\n cb(err, stat);\n });\n } else {\n cb(err, stat);\n }\n });\n }\n\n public statSync(p: string, isLstat: boolean): Stats {\n this.checkInitialized();\n try {\n return this._writable.statSync(p, isLstat);\n } catch (e) {\n if (this._deletedFiles[p]) {\n throw ApiError.ENOENT(p);\n }\n const oldStat = this._readable.statSync(p, isLstat).clone();\n // Make the oldStat's mode writable. Preserve the topmost part of the\n // mode, which specifies if it is a file or a directory.\n oldStat.mode = makeModeWritable(oldStat.mode);\n return oldStat;\n }\n }\n\n public open(p: string, flag: FileFlag, mode: number, cb: BFSCallback): void {\n if (!this.checkInitAsync(cb) || this.checkPathAsync(p, cb)) {\n return;\n }\n this.stat(p, false, (err: ApiError, stats?: Stats) => {\n if (stats) {\n switch (flag.pathExistsAction()) {\n case ActionType.TRUNCATE_FILE:\n return this.createParentDirectoriesAsync(p, (err?: ApiError) => {\n if (err) {\n return cb(err);\n }\n this._writable.open(p, flag, mode, cb);\n });\n case ActionType.NOP:\n return this._writable.exists(p, (exists: boolean) => {\n if (exists) {\n this._writable.open(p, flag, mode, cb);\n } else {\n // at this point we know the stats object we got is from\n // the readable FS.\n stats = stats!.clone();\n stats.mode = mode;\n this._readable.readFile(p, null, getFlag('r'), (readFileErr: ApiError, data?: any) => {\n if (readFileErr) {\n return cb(readFileErr);\n }\n if (stats!.size === -1) {\n stats!.size = data.length;\n }\n const f = new OverlayFile(this, p, flag, stats!, data);\n cb(null, f);\n });\n }\n });\n default:\n return cb(ApiError.EEXIST(p));\n }\n } else {\n switch (flag.pathNotExistsAction()) {\n case ActionType.CREATE_FILE:\n return this.createParentDirectoriesAsync(p, (err?: ApiError) => {\n if (err) {\n return cb(err);\n }\n return this._writable.open(p, flag, mode, cb);\n });\n default:\n return cb(ApiError.ENOENT(p));\n }\n }\n });\n }\n\n public openSync(p: string, flag: FileFlag, mode: number): File {\n this.checkInitialized();\n this.checkPath(p);\n if (p === deletionLogPath) {\n throw ApiError.EPERM('Cannot open deletion log.');\n }\n if (this.existsSync(p)) {\n switch (flag.pathExistsAction()) {\n case ActionType.TRUNCATE_FILE:\n this.createParentDirectories(p);\n return this._writable.openSync(p, flag, mode);\n case ActionType.NOP:\n if (this._writable.existsSync(p)) {\n return this._writable.openSync(p, flag, mode);\n } else {\n // Create an OverlayFile.\n const buf = this._readable.readFileSync(p, null, getFlag('r'));\n const stats = this._readable.statSync(p, false).clone();\n stats.mode = mode;\n return new OverlayFile(this, p, flag, stats, buf);\n }\n default:\n throw ApiError.EEXIST(p);\n }\n } else {\n switch (flag.pathNotExistsAction()) {\n case ActionType.CREATE_FILE:\n this.createParentDirectories(p);\n return this._writable.openSync(p, flag, mode);\n default:\n throw ApiError.ENOENT(p);\n }\n }\n }\n\n public unlink(p: string, cb: BFSOneArgCallback): void {\n if (!this.checkInitAsync(cb) || this.checkPathAsync(p, cb)) {\n return;\n }\n this.exists(p, (exists: boolean) => {\n if (!exists) {\n return cb(ApiError.ENOENT(p));\n }\n\n this._writable.exists(p, (writableExists: boolean) => {\n if (writableExists) {\n return this._writable.unlink(p, (err: ApiError) => {\n if (err) {\n return cb(err);\n }\n\n this.exists(p, (readableExists: boolean) => {\n if (readableExists) {\n this.deletePath(p);\n }\n cb(null);\n });\n });\n } else {\n // if this only exists on the readable FS, add it to the\n // delete map.\n this.deletePath(p);\n cb(null);\n }\n });\n });\n }\n\n public unlinkSync(p: string): void {\n this.checkInitialized();\n this.checkPath(p);\n if (this.existsSync(p)) {\n if (this._writable.existsSync(p)) {\n this._writable.unlinkSync(p);\n }\n\n // if it still exists add to the delete log\n if (this.existsSync(p)) {\n this.deletePath(p);\n }\n } else {\n throw ApiError.ENOENT(p);\n }\n }\n\n public rmdir(p: string, cb: BFSOneArgCallback): void {\n if (!this.checkInitAsync(cb)) {\n return;\n }\n\n const rmdirLower = (): void => {\n this.readdir(p, (err: ApiError, files: string[]): void => {\n if (err) {\n return cb(err);\n }\n\n if (files.length) {\n return cb(ApiError.ENOTEMPTY(p));\n }\n\n this.deletePath(p);\n cb(null);\n });\n };\n\n this.exists(p, (exists: boolean) => {\n if (!exists) {\n return cb(ApiError.ENOENT(p));\n }\n\n this._writable.exists(p, (writableExists: boolean) => {\n if (writableExists) {\n this._writable.rmdir(p, (err: ApiError) => {\n if (err) {\n return cb(err);\n }\n\n this._readable.exists(p, (readableExists: boolean) => {\n if (readableExists) {\n rmdirLower();\n } else {\n cb();\n }\n });\n });\n } else {\n rmdirLower();\n }\n });\n });\n }\n\n public rmdirSync(p: string): void {\n this.checkInitialized();\n if (this.existsSync(p)) {\n if (this._writable.existsSync(p)) {\n this._writable.rmdirSync(p);\n }\n if (this.existsSync(p)) {\n // Check if directory is empty.\n if (this.readdirSync(p).length > 0) {\n throw ApiError.ENOTEMPTY(p);\n } else {\n this.deletePath(p);\n }\n }\n } else {\n throw ApiError.ENOENT(p);\n }\n }\n\n public mkdir(p: string, mode: number, cb: BFSCallback): void {\n if (!this.checkInitAsync(cb)) {\n return;\n }\n this.exists(p, (exists: boolean) => {\n if (exists) {\n return cb(ApiError.EEXIST(p));\n }\n\n // The below will throw should any of the parent directories\n // fail to exist on _writable.\n this.createParentDirectoriesAsync(p, (err: ApiError) => {\n if (err) {\n return cb(err);\n }\n this._writable.mkdir(p, mode, cb);\n });\n });\n }\n\n public mkdirSync(p: string, mode: number): void {\n this.checkInitialized();\n if (this.existsSync(p)) {\n throw ApiError.EEXIST(p);\n } else {\n // The below will throw should any of the parent directories fail to exist\n // on _writable.\n this.createParentDirectories(p);\n this._writable.mkdirSync(p, mode);\n }\n }\n\n public readdir(p: string, cb: BFSCallback): void {\n if (!this.checkInitAsync(cb)) {\n return;\n }\n this.stat(p, false, (err: ApiError, dirStats?: Stats) => {\n if (err) {\n return cb(err);\n }\n\n if (!dirStats!.isDirectory()) {\n return cb(ApiError.ENOTDIR(p));\n }\n\n this._writable.readdir(p, (err: ApiError, wFiles: string[]) => {\n if (err && err.code !== 'ENOENT') {\n return cb(err);\n } else if (err || !wFiles) {\n wFiles = [];\n }\n\n this._readable.readdir(p, (err: ApiError, rFiles: string[]) => {\n // if the directory doesn't exist on the lower FS set rFiles\n // here to simplify the following code.\n if (err || !rFiles) {\n rFiles = [];\n }\n\n // Readdir in both, check delete log on read-only file system's files, merge, return.\n const seenMap: {[name: string]: boolean} = {};\n const filtered: string[] = wFiles.concat(rFiles.filter((fPath: string) =>\n !this._deletedFiles[`${p}/${fPath}`]\n )).filter((fPath: string) => {\n // Remove duplicates.\n const result = !seenMap[fPath];\n seenMap[fPath] = true;\n return result;\n });\n cb(null, filtered);\n });\n });\n });\n }\n\n public readdirSync(p: string): string[] {\n this.checkInitialized();\n const dirStats = this.statSync(p, false);\n if (!dirStats.isDirectory()) {\n throw ApiError.ENOTDIR(p);\n }\n\n // Readdir in both, check delete log on RO file system's listing, merge, return.\n let contents: string[] = [];\n try {\n contents = contents.concat(this._writable.readdirSync(p));\n } catch (e) {\n // NOP.\n }\n try {\n contents = contents.concat(this._readable.readdirSync(p).filter((fPath: string) =>\n !this._deletedFiles[`${p}/${fPath}`]\n ));\n } catch (e) {\n // NOP.\n }\n const seenMap: {[name: string]: boolean} = {};\n return contents.filter((fileP: string) => {\n const result = !seenMap[fileP];\n seenMap[fileP] = true;\n return result;\n });\n }\n\n public exists(p: string, cb: (exists: boolean) => void): void {\n // Cannot pass an error back to callback, so throw an exception instead\n // if not initialized.\n this.checkInitialized();\n this._writable.exists(p, (existsWritable: boolean) => {\n if (existsWritable) {\n return cb(true);\n }\n\n this._readable.exists(p, (existsReadable: boolean) => {\n cb(existsReadable && this._deletedFiles[p] !== true);\n });\n });\n }\n\n public existsSync(p: string): boolean {\n this.checkInitialized();\n return this._writable.existsSync(p) || (this._readable.existsSync(p) && this._deletedFiles[p] !== true);\n }\n\n public chmod(p: string, isLchmod: boolean, mode: number, cb: BFSOneArgCallback): void {\n if (!this.checkInitAsync(cb)) {\n return;\n }\n this.operateOnWritableAsync(p, (err?: ApiError) => {\n if (err) {\n return cb(err);\n } else {\n this._writable.chmod(p, isLchmod, mode, cb);\n }\n });\n }\n\n public chmodSync(p: string, isLchmod: boolean, mode: number): void {\n this.checkInitialized();\n this.operateOnWritable(p, () => {\n this._writable.chmodSync(p, isLchmod, mode);\n });\n }\n\n public chown(p: string, isLchmod: boolean, uid: number, gid: number, cb: BFSOneArgCallback): void {\n if (!this.checkInitAsync(cb)) {\n return;\n }\n this.operateOnWritableAsync(p, (err?: ApiError) => {\n if (err) {\n return cb(err);\n } else {\n this._writable.chown(p, isLchmod, uid, gid, cb);\n }\n });\n }\n\n public chownSync(p: string, isLchown: boolean, uid: number, gid: number): void {\n this.checkInitialized();\n this.operateOnWritable(p, () => {\n this._writable.chownSync(p, isLchown, uid, gid);\n });\n }\n\n public utimes(p: string, atime: Date, mtime: Date, cb: BFSOneArgCallback): void {\n if (!this.checkInitAsync(cb)) {\n return;\n }\n this.operateOnWritableAsync(p, (err?: ApiError) => {\n if (err) {\n return cb(err);\n } else {\n this._writable.utimes(p, atime, mtime, cb);\n }\n });\n }\n\n public utimesSync(p: string, atime: Date, mtime: Date): void {\n this.checkInitialized();\n this.operateOnWritable(p, () => {\n this._writable.utimesSync(p, atime, mtime);\n });\n }\n\n private deletePath(p: string): void {\n this._deletedFiles[p] = true;\n this.updateLog(`d${p}\\n`);\n }\n\n private updateLog(addition: string) {\n this._deleteLog += addition;\n if (this._deleteLogUpdatePending) {\n this._deleteLogUpdateNeeded = true;\n } else {\n this._deleteLogUpdatePending = true;\n this._writable.writeFile(deletionLogPath, this._deleteLog, 'utf8', FileFlag.getFileFlag('w'), 0o644, (e) => {\n this._deleteLogUpdatePending = false;\n if (e) {\n this._deleteLogError = e;\n } else if (this._deleteLogUpdateNeeded) {\n this._deleteLogUpdateNeeded = false;\n this.updateLog('');\n }\n });\n }\n }\n\n private _reparseDeletionLog(): void {\n this._deletedFiles = {};\n this._deleteLog.split('\\n').forEach((path: string) => {\n // If the log entry begins w/ 'd', it's a deletion.\n this._deletedFiles[path.slice(1)] = path.slice(0, 1) === 'd';\n });\n }\n\n private checkInitialized(): void {\n if (!this._isInitialized) {\n throw new ApiError(ErrorCode.EPERM, \"OverlayFS is not initialized. Please initialize OverlayFS using its initialize() method before using it.\");\n } else if (this._deleteLogError !== null) {\n const e = this._deleteLogError;\n this._deleteLogError = null;\n throw e;\n }\n }\n\n private checkInitAsync(cb: BFSOneArgCallback): boolean {\n if (!this._isInitialized) {\n cb(new ApiError(ErrorCode.EPERM, \"OverlayFS is not initialized. Please initialize OverlayFS using its initialize() method before using it.\"));\n return false;\n } else if (this._deleteLogError !== null) {\n const e = this._deleteLogError;\n this._deleteLogError = null;\n cb(e);\n return false;\n }\n return true;\n }\n\n private checkPath(p: string): void {\n if (p === deletionLogPath) {\n throw ApiError.EPERM(p);\n }\n }\n\n private checkPathAsync(p: string, cb: BFSOneArgCallback): boolean {\n if (p === deletionLogPath) {\n cb(ApiError.EPERM(p));\n return true;\n }\n return false;\n }\n\n private createParentDirectoriesAsync(p: string, cb: BFSOneArgCallback): void {\n let parent = path.dirname(p);\n const toCreate: string[] = [];\n const self = this;\n\n this._writable.stat(parent, false, statDone);\n function statDone(err: ApiError, stat?: Stats): void {\n if (err) {\n toCreate.push(parent);\n parent = path.dirname(parent);\n self._writable.stat(parent, false, statDone);\n } else {\n createParents();\n }\n }\n\n function createParents(): void {\n if (!toCreate.length) {\n return cb();\n }\n\n const dir = toCreate.pop();\n self._readable.stat(dir!, false, (err: ApiError, stats?: Stats) => {\n // stop if we couldn't read the dir\n if (!stats) {\n return cb();\n }\n\n self._writable.mkdir(dir!, stats.mode, (err?: ApiError) => {\n if (err) {\n return cb(err);\n }\n createParents();\n });\n });\n }\n }\n\n /**\n * With the given path, create the needed parent directories on the writable storage\n * should they not exist. Use modes from the read-only storage.\n */\n private createParentDirectories(p: string): void {\n let parent = path.dirname(p), toCreate: string[] = [];\n while (!this._writable.existsSync(parent)) {\n toCreate.push(parent);\n parent = path.dirname(parent);\n }\n toCreate = toCreate.reverse();\n\n toCreate.forEach((p: string) => {\n this._writable.mkdirSync(p, this.statSync(p, false).mode);\n });\n }\n\n /**\n * Helper function:\n * - Ensures p is on writable before proceeding. Throws an error if it doesn't exist.\n * - Calls f to perform operation on writable.\n */\n private operateOnWritable(p: string, f: () => void): void {\n if (this.existsSync(p)) {\n if (!this._writable.existsSync(p)) {\n // File is on readable storage. Copy to writable storage before\n // changing its mode.\n this.copyToWritable(p);\n }\n f();\n } else {\n throw ApiError.ENOENT(p);\n }\n }\n\n private operateOnWritableAsync(p: string, cb: BFSOneArgCallback): void {\n this.exists(p, (exists: boolean) => {\n if (!exists) {\n return cb(ApiError.ENOENT(p));\n }\n\n this._writable.exists(p, (existsWritable: boolean) => {\n if (existsWritable) {\n cb();\n } else {\n return this.copyToWritableAsync(p, cb);\n }\n });\n });\n }\n\n /**\n * Copy from readable to writable storage.\n * PRECONDITION: File does not exist on writable storage.\n */\n private copyToWritable(p: string): void {\n const pStats = this.statSync(p, false);\n if (pStats.isDirectory()) {\n this._writable.mkdirSync(p, pStats.mode);\n } else {\n this.writeFileSync(p,\n this._readable.readFileSync(p, null, getFlag('r')), null,\n getFlag('w'), this.statSync(p, false).mode);\n }\n }\n\n private copyToWritableAsync(p: string, cb: BFSOneArgCallback): void {\n this.stat(p, false, (err: ApiError, pStats?: Stats) => {\n if (err) {\n return cb(err);\n }\n\n if (pStats!.isDirectory()) {\n return this._writable.mkdir(p, pStats!.mode, cb);\n }\n\n // need to copy file.\n this._readable.readFile(p, null, getFlag('r'), (err: ApiError, data?: Buffer) => {\n if (err) {\n return cb(err);\n }\n\n this.writeFile(p, data, null, getFlag('w'), pStats!.mode, cb);\n });\n });\n }\n}\n\n/**\n * Configuration options for OverlayFS instances.\n */\nexport interface OverlayFSOptions {\n // The file system to write modified files to.\n writable: FileSystem;\n // The file system that initially populates this file system.\n readable: FileSystem;\n}\n\n/**\n * OverlayFS makes a read-only filesystem writable by storing writes on a second,\n * writable file system. Deletes are persisted via metadata stored on the writable\n * file system.\n */\nexport default class OverlayFS extends LockedFS {\n public static readonly Name = \"OverlayFS\";\n\n public static readonly Options: FileSystemOptions = {\n writable: {\n type: \"object\",\n description: \"The file system to write modified files to.\"\n },\n readable: {\n type: \"object\",\n description: \"The file system that initially populates this file system.\"\n }\n };\n\n /**\n * Constructs and initializes an OverlayFS instance with the given options.\n */\n public static Create(opts: OverlayFSOptions, cb: BFSCallback): void {\n try {\n const fs = new OverlayFS(opts.writable, opts.readable, false);\n fs.initialize((e?) => {\n cb(e, fs);\n }, false);\n } catch (e) {\n cb(e);\n }\n }\n public static isAvailable(): boolean {\n return UnlockedOverlayFS.isAvailable();\n }\n\n /**\n * **Deprecated. Please use OverlayFS.Create() method instead.**\n * @param writable The file system to write modified files to.\n * @param readable The file system that initially populates this file system.\n */\n constructor(writable: FileSystem, readable: FileSystem, deprecateMsg = true) {\n super(new UnlockedOverlayFS(writable, readable));\n deprecationMessage(deprecateMsg, OverlayFS.Name, {readable: \"readable file system\", writable: \"writable file system\"});\n }\n\n /**\n * **Deprecated. Please use OverlayFS.Create() to construct and initialize OverlayFS instances.**\n */\n public initialize(cb: BFSOneArgCallback, deprecateMsg = true): void {\n if (deprecateMsg) {\n console.warn(`[OverlayFS] OverlayFS.initialize() is deprecated and will be removed in the next major release. Please use 'OverlayFS.Create({readable: readable file system instance, writable: writable file system instance}, cb)' to create and initialize OverlayFS instances.`);\n }\n super.initialize(cb);\n }\n\n public getOverlayedFileSystems(): { readable: FileSystem; writable: FileSystem; } {\n return super.getFSUnlocked().getOverlayedFileSystems();\n }\n\n public unwrap(): UnlockedOverlayFS {\n return super.getFSUnlocked();\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ../../../../src/backend/OverlayFS.ts","import {BaseFileSystem, FileSystem, BFSOneArgCallback, BFSCallback, FileSystemOptions} from '../core/file_system';\nimport {ApiError, ErrorCode} from '../core/api_error';\nimport {FileFlag} from '../core/file_flag';\nimport {buffer2ArrayBuffer, arrayBuffer2Buffer, emptyBuffer, deprecationMessage} from '../core/util';\nimport {File, BaseFile} from '../core/file';\nimport {default as Stats} from '../core/node_fs_stats';\nimport PreloadFile from '../generic/preload_file';\nimport global from '../core/global';\nimport fs from '../core/node_fs';\n\n/**\n * @hidden\n */\ndeclare const importScripts: Function;\n\n/**\n * @hidden\n */\ninterface IBrowserFSMessage {\n browserfsMessage: boolean;\n}\n\n/**\n * @hidden\n */\nenum SpecialArgType {\n // Callback\n CB,\n // File descriptor\n FD,\n // API error\n API_ERROR,\n // Stats object\n STATS,\n // Initial probe for file system information.\n PROBE,\n // FileFlag object.\n FILEFLAG,\n // Buffer object.\n BUFFER,\n // Generic Error object.\n ERROR\n}\n\n/**\n * @hidden\n */\ninterface ISpecialArgument {\n type: SpecialArgType;\n}\n\n/**\n * @hidden\n */\ninterface IProbeResponse extends ISpecialArgument {\n isReadOnly: boolean;\n supportsLinks: boolean;\n supportsProps: boolean;\n}\n\n/**\n * @hidden\n */\ninterface ICallbackArgument extends ISpecialArgument {\n // The callback ID.\n id: number;\n}\n\n/**\n * Converts callback arguments into ICallbackArgument objects, and back\n * again.\n * @hidden\n */\nclass CallbackArgumentConverter {\n private _callbacks: { [id: number]: Function } = {};\n private _nextId: number = 0;\n\n public toRemoteArg(cb: Function): ICallbackArgument {\n const id = this._nextId++;\n this._callbacks[id] = cb;\n return {\n type: SpecialArgType.CB,\n id: id\n };\n }\n\n public toLocalArg(id: number): Function {\n const cb = this._callbacks[id];\n delete this._callbacks[id];\n return cb;\n }\n}\n\n/**\n * @hidden\n */\ninterface IFileDescriptorArgument extends ISpecialArgument {\n // The file descriptor's id on the remote side.\n id: number;\n // The entire file's data, as an array buffer.\n data: ArrayBuffer;\n // The file's stat object, as an array buffer.\n stat: ArrayBuffer;\n // The path to the file.\n path: string;\n // The flag of the open file descriptor.\n flag: string;\n}\n\n/**\n * @hidden\n */\nclass FileDescriptorArgumentConverter {\n private _fileDescriptors: { [id: number]: File } = {};\n private _nextId: number = 0;\n\n public toRemoteArg(fd: File, p: string, flag: FileFlag, cb: BFSCallback): void {\n const id = this._nextId++;\n let data: ArrayBuffer;\n let stat: ArrayBuffer;\n this._fileDescriptors[id] = fd;\n\n // Extract needed information asynchronously.\n fd.stat((err, stats) => {\n if (err) {\n cb(err);\n } else {\n stat = bufferToTransferrableObject(stats!.toBuffer());\n // If it's a readable flag, we need to grab contents.\n if (flag.isReadable()) {\n fd.read(Buffer.alloc(stats!.size), 0, stats!.size, 0, (err?: ApiError | null, bytesRead?: number, buff?: Buffer) => {\n if (err) {\n cb(err);\n } else {\n data = bufferToTransferrableObject(buff!);\n cb(null, {\n type: SpecialArgType.FD,\n id: id,\n data: data,\n stat: stat,\n path: p,\n flag: flag.getFlagString()\n });\n }\n });\n } else {\n // File is not readable, which means writing to it will append or\n // truncate/replace existing contents. Return an empty arraybuffer.\n cb(null, {\n type: SpecialArgType.FD,\n id: id,\n data: new ArrayBuffer(0),\n stat: stat,\n path: p,\n flag: flag.getFlagString()\n });\n }\n }\n });\n }\n\n public applyFdAPIRequest(request: IAPIRequest, cb: BFSOneArgCallback): void {\n const fdArg = request.args[0];\n this._applyFdChanges(fdArg, (err, fd?) => {\n if (err) {\n cb(err);\n } else {\n // Apply method on now-changed file descriptor.\n ( fd)[request.method]((e?: ApiError) => {\n if (request.method === 'close') {\n delete this._fileDescriptors[fdArg.id];\n }\n cb(e);\n });\n }\n });\n }\n\n private _applyFdChanges(remoteFd: IFileDescriptorArgument, cb: BFSCallback): void {\n const fd = this._fileDescriptors[remoteFd.id],\n data = transferrableObjectToBuffer(remoteFd.data),\n remoteStats = Stats.fromBuffer(transferrableObjectToBuffer(remoteFd.stat));\n\n // Write data if the file is writable.\n const flag = FileFlag.getFileFlag(remoteFd.flag);\n if (flag.isWriteable()) {\n // Appendable: Write to end of file.\n // Writeable: Replace entire contents of file.\n fd.write(data, 0, data.length, flag.isAppendable() ? fd.getPos()! : 0, (e?: ApiError | null) => {\n function applyStatChanges() {\n // Check if mode changed.\n fd.stat((e, stats?) => {\n if (e) {\n cb(e);\n } else {\n if (stats!.mode !== remoteStats.mode) {\n fd.chmod(remoteStats.mode, (e: any) => {\n cb(e, fd);\n });\n } else {\n cb(e, fd);\n }\n }\n });\n }\n if (e) {\n cb(e);\n } else {\n // If writeable & not appendable, we need to ensure file contents are\n // identical to those from the remote FD. Thus, we truncate to the\n // length of the remote file.\n if (!flag.isAppendable()) {\n fd.truncate(data.length, () => {\n applyStatChanges();\n });\n } else {\n applyStatChanges();\n }\n }\n });\n } else {\n cb(null, fd);\n }\n }\n}\n\n/**\n * @hidden\n */\ninterface IAPIErrorArgument extends ISpecialArgument {\n // The error object, as an array buffer.\n errorData: ArrayBuffer;\n}\n\n/**\n * @hidden\n */\nfunction apiErrorLocal2Remote(e: ApiError): IAPIErrorArgument {\n return {\n type: SpecialArgType.API_ERROR,\n errorData: bufferToTransferrableObject(e.writeToBuffer())\n };\n}\n\n/**\n * @hidden\n */\nfunction apiErrorRemote2Local(e: IAPIErrorArgument): ApiError {\n return ApiError.fromBuffer(transferrableObjectToBuffer(e.errorData));\n}\n\n/**\n * @hidden\n */\ninterface IErrorArgument extends ISpecialArgument {\n // The name of the error (e.g. 'TypeError').\n name: string;\n // The message associated with the error.\n message: string;\n // The stack associated with the error.\n stack: string;\n}\n\n/**\n * @hidden\n */\nfunction errorLocal2Remote(e: Error): IErrorArgument {\n return {\n type: SpecialArgType.ERROR,\n name: e.name,\n message: e.message,\n stack: e.stack!\n };\n}\n\n/**\n * @hidden\n */\nfunction errorRemote2Local(e: IErrorArgument): Error {\n let cnstr: {\n new (msg: string): Error;\n } = global[e.name];\n if (typeof(cnstr) !== 'function') {\n cnstr = Error;\n }\n const err = new cnstr(e.message);\n err.stack = e.stack;\n return err;\n}\n\n/**\n * @hidden\n */\ninterface IStatsArgument extends ISpecialArgument {\n // The stats object as an array buffer.\n statsData: ArrayBuffer;\n}\n\n/**\n * @hidden\n */\nfunction statsLocal2Remote(stats: Stats): IStatsArgument {\n return {\n type: SpecialArgType.STATS,\n statsData: bufferToTransferrableObject(stats.toBuffer())\n };\n}\n\n/**\n * @hidden\n */\nfunction statsRemote2Local(stats: IStatsArgument): Stats {\n return Stats.fromBuffer(transferrableObjectToBuffer(stats.statsData));\n}\n\n/**\n * @hidden\n */\ninterface IFileFlagArgument extends ISpecialArgument {\n flagStr: string;\n}\n\n/**\n * @hidden\n */\nfunction fileFlagLocal2Remote(flag: FileFlag): IFileFlagArgument {\n return {\n type: SpecialArgType.FILEFLAG,\n flagStr: flag.getFlagString()\n };\n}\n\n/**\n * @hidden\n */\nfunction fileFlagRemote2Local(remoteFlag: IFileFlagArgument): FileFlag {\n return FileFlag.getFileFlag(remoteFlag.flagStr);\n}\n\n/**\n * @hidden\n */\ninterface IBufferArgument extends ISpecialArgument {\n data: ArrayBuffer;\n}\n\n/**\n * @hidden\n */\nfunction bufferToTransferrableObject(buff: Buffer): ArrayBuffer {\n return buffer2ArrayBuffer(buff);\n}\n\n/**\n * @hidden\n */\nfunction transferrableObjectToBuffer(buff: ArrayBuffer): Buffer {\n return arrayBuffer2Buffer(buff);\n}\n\n/**\n * @hidden\n */\nfunction bufferLocal2Remote(buff: Buffer): IBufferArgument {\n return {\n type: SpecialArgType.BUFFER,\n data: bufferToTransferrableObject(buff)\n };\n}\n\n/**\n * @hidden\n */\nfunction bufferRemote2Local(buffArg: IBufferArgument): Buffer {\n return transferrableObjectToBuffer(buffArg.data);\n}\n\n/**\n * @hidden\n */\ninterface IAPIRequest extends IBrowserFSMessage {\n method: string;\n args: Array;\n}\n\n/**\n * @hidden\n */\nfunction isAPIRequest(data: any): data is IAPIRequest {\n return data && typeof data === 'object' && data.hasOwnProperty('browserfsMessage') && data['browserfsMessage'];\n}\n\n/**\n * @hidden\n */\ninterface IAPIResponse extends IBrowserFSMessage {\n cbId: number;\n args: Array;\n}\n\n/**\n * @hidden\n */\nfunction isAPIResponse(data: any): data is IAPIResponse {\n return data && typeof data === 'object' && data.hasOwnProperty('browserfsMessage') && data['browserfsMessage'];\n}\n\n/**\n * Represents a remote file in a different worker/thread.\n */\nclass WorkerFile extends PreloadFile {\n private _remoteFdId: number;\n\n constructor(_fs: WorkerFS, _path: string, _flag: FileFlag, _stat: Stats, remoteFdId: number, contents?: Buffer) {\n super(_fs, _path, _flag, _stat, contents);\n this._remoteFdId = remoteFdId;\n }\n\n public getRemoteFdId() {\n return this._remoteFdId;\n }\n\n /**\n * @hidden\n */\n public toRemoteArg(): IFileDescriptorArgument {\n return {\n type: SpecialArgType.FD,\n id: this._remoteFdId,\n data: bufferToTransferrableObject(this.getBuffer()),\n stat: bufferToTransferrableObject(this.getStats().toBuffer()),\n path: this.getPath(),\n flag: this.getFlag().getFlagString()\n };\n }\n\n public sync(cb: BFSOneArgCallback): void {\n this._syncClose('sync', cb);\n }\n\n public close(cb: BFSOneArgCallback): void {\n this._syncClose('close', cb);\n }\n\n private _syncClose(type: string, cb: BFSOneArgCallback): void {\n if (this.isDirty()) {\n ( this._fs).syncClose(type, this, (e?: ApiError) => {\n if (!e) {\n this.resetDirty();\n }\n cb(e);\n });\n } else {\n cb();\n }\n }\n}\n\nexport interface WorkerFSOptions {\n // The target worker that you want to connect to, or the current worker if in a worker context.\n worker: Worker;\n}\n\n/**\n * WorkerFS lets you access a BrowserFS instance that is running in a different\n * JavaScript context (e.g. access BrowserFS in one of your WebWorkers, or\n * access BrowserFS running on the main page from a WebWorker).\n *\n * For example, to have a WebWorker access files in the main browser thread,\n * do the following:\n *\n * MAIN BROWSER THREAD:\n *\n * ```javascript\n * // Listen for remote file system requests.\n * BrowserFS.FileSystem.WorkerFS.attachRemoteListener(webWorkerObject);\n * ```\n *\n * WEBWORKER THREAD:\n *\n * ```javascript\n * // Set the remote file system as the root file system.\n * BrowserFS.configure({ fs: \"WorkerFS\", options: { worker: self }}, function(e) {\n * // Ready!\n * });\n * ```\n *\n * Note that synchronous operations are not permitted on the WorkerFS, regardless\n * of the configuration option of the remote FS.\n */\nexport default class WorkerFS extends BaseFileSystem implements FileSystem {\n public static readonly Name = \"WorkerFS\";\n\n public static readonly Options: FileSystemOptions = {\n worker: {\n type: \"object\",\n description: \"The target worker that you want to connect to, or the current worker if in a worker context.\",\n validator: function(v: object, cb: BFSOneArgCallback): void {\n // Check for a `postMessage` function.\n if (( v)['postMessage']) {\n cb();\n } else {\n cb(new ApiError(ErrorCode.EINVAL, `option must be a Web Worker instance.`));\n }\n }\n }\n };\n\n public static Create(opts: WorkerFSOptions, cb: BFSCallback): void {\n const fs = new WorkerFS(opts.worker, false);\n fs.initialize(() => {\n cb(null, fs);\n });\n }\n public static isAvailable(): boolean {\n return typeof(importScripts) !== 'undefined' || typeof(Worker) !== 'undefined';\n }\n\n /**\n * Attaches a listener to the remote worker for file system requests.\n */\n public static attachRemoteListener(worker: Worker) {\n const fdConverter = new FileDescriptorArgumentConverter();\n\n function argLocal2Remote(arg: any, requestArgs: any[], cb: BFSCallback): void {\n switch (typeof arg) {\n case 'object':\n if (arg instanceof Stats) {\n cb(null, statsLocal2Remote(arg));\n } else if (arg instanceof ApiError) {\n cb(null, apiErrorLocal2Remote(arg));\n } else if (arg instanceof BaseFile) {\n // Pass in p and flags from original request.\n cb(null, fdConverter.toRemoteArg( arg, requestArgs[0], requestArgs[1], cb));\n } else if (arg instanceof FileFlag) {\n cb(null, fileFlagLocal2Remote(arg));\n } else if (arg instanceof Buffer) {\n cb(null, bufferLocal2Remote(arg));\n } else if (arg instanceof Error) {\n cb(null, errorLocal2Remote(arg));\n } else {\n cb(null, arg);\n }\n break;\n default:\n cb(null, arg);\n break;\n }\n }\n\n function argRemote2Local(arg: any, fixedRequestArgs: any[]): any {\n if (!arg) {\n return arg;\n }\n switch (typeof arg) {\n case 'object':\n if (typeof arg['type'] === 'number') {\n const specialArg = arg;\n switch (specialArg.type) {\n case SpecialArgType.CB:\n const cbId = ( arg).id;\n return function() {\n let i: number;\n const fixedArgs = new Array(arguments.length);\n let message: IAPIResponse,\n countdown = arguments.length;\n\n function abortAndSendError(err: ApiError) {\n if (countdown > 0) {\n countdown = -1;\n message = {\n browserfsMessage: true,\n cbId: cbId,\n args: [apiErrorLocal2Remote(err)]\n };\n worker.postMessage(message);\n }\n }\n\n for (i = 0; i < arguments.length; i++) {\n // Capture i and argument.\n ((i: number, arg: any) => {\n argLocal2Remote(arg, fixedRequestArgs, (err, fixedArg?) => {\n fixedArgs[i] = fixedArg;\n if (err) {\n abortAndSendError(err);\n } else if (--countdown === 0) {\n message = {\n browserfsMessage: true,\n cbId: cbId,\n args: fixedArgs\n };\n worker.postMessage(message);\n }\n });\n })(i, arguments[i]);\n }\n\n if (arguments.length === 0) {\n message = {\n browserfsMessage: true,\n cbId: cbId,\n args: fixedArgs\n };\n worker.postMessage(message);\n }\n\n };\n case SpecialArgType.API_ERROR:\n return apiErrorRemote2Local( specialArg);\n case SpecialArgType.STATS:\n return statsRemote2Local( specialArg);\n case SpecialArgType.FILEFLAG:\n return fileFlagRemote2Local( specialArg);\n case SpecialArgType.BUFFER:\n return bufferRemote2Local( specialArg);\n case SpecialArgType.ERROR:\n return errorRemote2Local( specialArg);\n default:\n // No idea what this is.\n return arg;\n }\n } else {\n return arg;\n }\n default:\n return arg;\n }\n }\n\n worker.addEventListener('message', (e: MessageEvent) => {\n const request: object = e.data;\n if (isAPIRequest(request)) {\n const args = request.args,\n fixedArgs = new Array(args.length);\n\n switch (request.method) {\n case 'close':\n case 'sync':\n (() => {\n // File descriptor-relative methods.\n const remoteCb = args[1];\n fdConverter.applyFdAPIRequest(request, (err?: ApiError) => {\n // Send response.\n const response: IAPIResponse = {\n browserfsMessage: true,\n cbId: remoteCb.id,\n args: err ? [apiErrorLocal2Remote(err)] : []\n };\n worker.postMessage(response);\n });\n })();\n break;\n case 'probe':\n (() => {\n const rootFs = fs.getRootFS(),\n remoteCb = args[1],\n probeResponse: IProbeResponse = {\n type: SpecialArgType.PROBE,\n isReadOnly: rootFs.isReadOnly(),\n supportsLinks: rootFs.supportsLinks(),\n supportsProps: rootFs.supportsProps()\n },\n response: IAPIResponse = {\n browserfsMessage: true,\n cbId: remoteCb.id,\n args: [probeResponse]\n };\n\n worker.postMessage(response);\n })();\n break;\n default:\n // File system methods.\n for (let i = 0; i < args.length; i++) {\n fixedArgs[i] = argRemote2Local(args[i], fixedArgs);\n }\n const rootFS = fs.getRootFS();\n ( ( rootFS)[request.method]).apply(rootFS, fixedArgs);\n break;\n }\n }\n });\n }\n\n private _worker: Worker;\n private _callbackConverter = new CallbackArgumentConverter();\n\n private _isInitialized: boolean = false;\n private _isReadOnly: boolean = false;\n private _supportLinks: boolean = false;\n private _supportProps: boolean = false;\n\n /**\n * **Deprecated. Please use WorkerFS.Create() method instead.**\n *\n * Constructs a new WorkerFS instance that connects with BrowserFS running on\n * the specified worker.\n */\n constructor(worker: Worker, deprecateMsg = true) {\n super();\n this._worker = worker;\n deprecationMessage(deprecateMsg, WorkerFS.Name, {worker: \"Web Worker instance\"});\n this._worker.addEventListener('message', (e: MessageEvent) => {\n const resp: object = e.data;\n if (isAPIResponse(resp)) {\n let i: number;\n const args = resp.args;\n const fixedArgs = new Array(args.length);\n // Dispatch event to correct id.\n for (i = 0; i < fixedArgs.length; i++) {\n fixedArgs[i] = this._argRemote2Local(args[i]);\n }\n this._callbackConverter.toLocalArg(resp.cbId).apply(null, fixedArgs);\n }\n });\n }\n\n public getName(): string {\n return WorkerFS.Name;\n }\n\n /**\n * **Deprecated. Please use WorkerFS.Create() method to construct and initialize WorkerFS instances.**\n *\n * Called once both local and remote sides are set up.\n */\n public initialize(cb: () => void): void {\n if (!this._isInitialized) {\n const message: IAPIRequest = {\n browserfsMessage: true,\n method: 'probe',\n args: [this._argLocal2Remote(emptyBuffer()), this._callbackConverter.toRemoteArg((probeResponse: IProbeResponse) => {\n this._isInitialized = true;\n this._isReadOnly = probeResponse.isReadOnly;\n this._supportLinks = probeResponse.supportsLinks;\n this._supportProps = probeResponse.supportsProps;\n cb();\n })]\n };\n this._worker.postMessage(message);\n } else {\n cb();\n }\n }\n\n public isReadOnly(): boolean { return this._isReadOnly; }\n public supportsSynch(): boolean { return false; }\n public supportsLinks(): boolean { return this._supportLinks; }\n public supportsProps(): boolean { return this._supportProps; }\n\n public rename(oldPath: string, newPath: string, cb: BFSOneArgCallback): void {\n this._rpc('rename', arguments);\n }\n public stat(p: string, isLstat: boolean, cb: BFSCallback): void {\n this._rpc('stat', arguments);\n }\n public open(p: string, flag: FileFlag, mode: number, cb: BFSCallback): void {\n this._rpc('open', arguments);\n }\n public unlink(p: string, cb: Function): void {\n this._rpc('unlink', arguments);\n }\n public rmdir(p: string, cb: Function): void {\n this._rpc('rmdir', arguments);\n }\n public mkdir(p: string, mode: number, cb: Function): void {\n this._rpc('mkdir', arguments);\n }\n public readdir(p: string, cb: BFSCallback): void {\n this._rpc('readdir', arguments);\n }\n public exists(p: string, cb: (exists: boolean) => void): void {\n this._rpc('exists', arguments);\n }\n public realpath(p: string, cache: { [path: string]: string }, cb: BFSCallback): void {\n this._rpc('realpath', arguments);\n }\n public truncate(p: string, len: number, cb: Function): void {\n this._rpc('truncate', arguments);\n }\n public readFile(fname: string, encoding: string, flag: FileFlag, cb: BFSCallback): void {\n this._rpc('readFile', arguments);\n }\n public writeFile(fname: string, data: any, encoding: string, flag: FileFlag, mode: number, cb: BFSOneArgCallback): void {\n this._rpc('writeFile', arguments);\n }\n public appendFile(fname: string, data: any, encoding: string, flag: FileFlag, mode: number, cb: BFSOneArgCallback): void {\n this._rpc('appendFile', arguments);\n }\n public chmod(p: string, isLchmod: boolean, mode: number, cb: Function): void {\n this._rpc('chmod', arguments);\n }\n public chown(p: string, isLchown: boolean, uid: number, gid: number, cb: Function): void {\n this._rpc('chown', arguments);\n }\n public utimes(p: string, atime: Date, mtime: Date, cb: Function): void {\n this._rpc('utimes', arguments);\n }\n public link(srcpath: string, dstpath: string, cb: Function): void {\n this._rpc('link', arguments);\n }\n public symlink(srcpath: string, dstpath: string, type: string, cb: Function): void {\n this._rpc('symlink', arguments);\n }\n public readlink(p: string, cb: Function): void {\n this._rpc('readlink', arguments);\n }\n\n public syncClose(method: string, fd: File, cb: BFSOneArgCallback): void {\n this._worker.postMessage( {\n browserfsMessage: true,\n method: method,\n args: [( fd).toRemoteArg(), this._callbackConverter.toRemoteArg(cb)]\n });\n }\n\n private _argRemote2Local(arg: any): any {\n if (!arg) {\n return arg;\n }\n switch (typeof arg) {\n case 'object':\n if (typeof arg['type'] === 'number') {\n const specialArg = arg;\n switch (specialArg.type) {\n case SpecialArgType.API_ERROR:\n return apiErrorRemote2Local( specialArg);\n case SpecialArgType.FD:\n const fdArg = specialArg;\n return new WorkerFile(this, fdArg.path, FileFlag.getFileFlag(fdArg.flag), Stats.fromBuffer(transferrableObjectToBuffer(fdArg.stat)), fdArg.id, transferrableObjectToBuffer(fdArg.data));\n case SpecialArgType.STATS:\n return statsRemote2Local( specialArg);\n case SpecialArgType.FILEFLAG:\n return fileFlagRemote2Local( specialArg);\n case SpecialArgType.BUFFER:\n return bufferRemote2Local( specialArg);\n case SpecialArgType.ERROR:\n return errorRemote2Local( specialArg);\n default:\n return arg;\n }\n } else {\n return arg;\n }\n default:\n return arg;\n }\n }\n\n private _rpc(methodName: string, args: IArguments) {\n const fixedArgs = new Array(args.length);\n for (let i = 0; i < args.length; i++) {\n fixedArgs[i] = this._argLocal2Remote(args[i]);\n }\n const message: IAPIRequest = {\n browserfsMessage: true,\n method: methodName,\n args: fixedArgs\n };\n this._worker.postMessage(message);\n }\n\n /**\n * Converts a local argument into a remote argument. Public so WorkerFile objects can call it.\n */\n private _argLocal2Remote(arg: any): any {\n if (!arg) {\n return arg;\n }\n switch (typeof arg) {\n case \"object\":\n if (arg instanceof Stats) {\n return statsLocal2Remote(arg);\n } else if (arg instanceof ApiError) {\n return apiErrorLocal2Remote(arg);\n } else if (arg instanceof WorkerFile) {\n return ( arg).toRemoteArg();\n } else if (arg instanceof FileFlag) {\n return fileFlagLocal2Remote(arg);\n } else if (arg instanceof Buffer) {\n return bufferLocal2Remote(arg);\n } else if (arg instanceof Error) {\n return errorLocal2Remote(arg);\n } else {\n return \"Unknown argument\";\n }\n case \"function\":\n return this._callbackConverter.toRemoteArg(arg);\n default:\n return arg;\n }\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ../../../../src/backend/WorkerFS.ts","/**\n * Contains utility methods for performing a variety of tasks with\n * XmlHttpRequest across browsers.\n */\n\nimport {isIE, emptyBuffer} from '../core/util';\nimport {ApiError, ErrorCode} from '../core/api_error';\nimport {BFSCallback} from '../core/file_system';\n\n/**\n * @hidden\n */\nfunction asyncDownloadFileModern(p: string, type: 'buffer', cb: BFSCallback): void;\nfunction asyncDownloadFileModern(p: string, type: 'json', cb: BFSCallback): void;\nfunction asyncDownloadFileModern(p: string, type: string, cb: BFSCallback): void;\nfunction asyncDownloadFileModern(p: string, type: string, cb: BFSCallback): void {\n const req = new XMLHttpRequest();\n req.open('GET', p, true);\n let jsonSupported = true;\n switch (type) {\n case 'buffer':\n req.responseType = 'arraybuffer';\n break;\n case 'json':\n // Some browsers don't support the JSON response type.\n // They either reset responseType, or throw an exception.\n // @see https://github.com/Modernizr/Modernizr/blob/master/src/testXhrType.js\n try {\n req.responseType = 'json';\n jsonSupported = req.responseType === 'json';\n } catch (e) {\n jsonSupported = false;\n }\n break;\n default:\n return cb(new ApiError(ErrorCode.EINVAL, \"Invalid download type: \" + type));\n }\n req.onreadystatechange = function(e) {\n if (req.readyState === 4) {\n if (req.status === 200) {\n switch (type) {\n case 'buffer':\n // XXX: WebKit-based browsers return *null* when XHRing an empty file.\n return cb(null, req.response ? Buffer.from(req.response) : emptyBuffer());\n case 'json':\n if (jsonSupported) {\n return cb(null, req.response);\n } else {\n return cb(null, JSON.parse(req.responseText));\n }\n }\n } else {\n return cb(new ApiError(req.status, \"XHR error.\"));\n }\n }\n };\n req.send();\n}\n\n/**\n * @hidden\n */\nfunction syncDownloadFileModern(p: string, type: 'buffer'): Buffer;\nfunction syncDownloadFileModern(p: string, type: 'json'): any;\nfunction syncDownloadFileModern(p: string, type: string): any;\nfunction syncDownloadFileModern(p: string, type: string): any {\n const req = new XMLHttpRequest();\n req.open('GET', p, false);\n\n // On most platforms, we cannot set the responseType of synchronous downloads.\n // @todo Test for this; IE10 allows this, as do older versions of Chrome/FF.\n let data: any = null;\n let err: any = null;\n // Classic hack to download binary data as a string.\n req.overrideMimeType('text/plain; charset=x-user-defined');\n req.onreadystatechange = function(e) {\n if (req.readyState === 4) {\n if (req.status === 200) {\n switch (type) {\n case 'buffer':\n // Convert the text into a buffer.\n const text = req.responseText;\n data = Buffer.alloc(text.length);\n // Throw away the upper bits of each character.\n for (let i = 0; i < text.length; i++) {\n // This will automatically throw away the upper bit of each\n // character for us.\n data[i] = text.charCodeAt(i);\n }\n return;\n case 'json':\n data = JSON.parse(req.responseText);\n return;\n }\n } else {\n err = new ApiError(req.status, \"XHR error.\");\n return;\n }\n }\n };\n req.send();\n if (err) {\n throw err;\n }\n return data;\n}\n\n/**\n * IE10 allows us to perform synchronous binary file downloads.\n * @todo Feature detect this, as older versions of FF/Chrome do too!\n * @hidden\n */\nfunction syncDownloadFileIE10(p: string, type: 'buffer'): Buffer;\nfunction syncDownloadFileIE10(p: string, type: 'json'): any;\nfunction syncDownloadFileIE10(p: string, type: string): any;\nfunction syncDownloadFileIE10(p: string, type: string): any {\n const req = new XMLHttpRequest();\n req.open('GET', p, false);\n switch (type) {\n case 'buffer':\n req.responseType = 'arraybuffer';\n break;\n case 'json':\n // IE10 does not support the JSON type.\n break;\n default:\n throw new ApiError(ErrorCode.EINVAL, \"Invalid download type: \" + type);\n }\n let data: any;\n let err: any;\n req.onreadystatechange = function(e) {\n if (req.readyState === 4) {\n if (req.status === 200) {\n switch (type) {\n case 'buffer':\n data = Buffer.from(req.response);\n break;\n case 'json':\n data = JSON.parse(req.response);\n break;\n }\n } else {\n err = new ApiError(req.status, \"XHR error.\");\n }\n }\n };\n req.send();\n if (err) {\n throw err;\n }\n return data;\n}\n\n/**\n * @hidden\n */\nfunction getFileSize(async: boolean, p: string, cb: BFSCallback): void {\n const req = new XMLHttpRequest();\n req.open('HEAD', p, async);\n req.onreadystatechange = function(e) {\n if (req.readyState === 4) {\n if (req.status === 200) {\n try {\n return cb(null, parseInt(req.getResponseHeader('Content-Length') || '-1', 10));\n } catch (e) {\n // In the event that the header isn't present or there is an error...\n return cb(new ApiError(ErrorCode.EIO, \"XHR HEAD error: Could not read content-length.\"));\n }\n } else {\n return cb(new ApiError(req.status, \"XHR HEAD error.\"));\n }\n }\n };\n req.send();\n}\n\n/**\n * Asynchronously download a file as a buffer or a JSON object.\n * Note that the third function signature with a non-specialized type is\n * invalid, but TypeScript requires it when you specialize string arguments to\n * constants.\n * @hidden\n */\nexport let asyncDownloadFile: {\n (p: string, type: 'buffer', cb: BFSCallback): void;\n (p: string, type: 'json', cb: BFSCallback): void;\n (p: string, type: string, cb: BFSCallback): void;\n} = asyncDownloadFileModern;\n\n/**\n * Synchronously download a file as a buffer or a JSON object.\n * Note that the third function signature with a non-specialized type is\n * invalid, but TypeScript requires it when you specialize string arguments to\n * constants.\n * @hidden\n */\nexport let syncDownloadFile: {\n (p: string, type: 'buffer'): Buffer;\n (p: string, type: 'json'): any;\n (p: string, type: string): any;\n} = (isIE && typeof Blob !== 'undefined') ? syncDownloadFileIE10 : syncDownloadFileModern;\n\n/**\n * Synchronously retrieves the size of the given file in bytes.\n * @hidden\n */\nexport function getFileSizeSync(p: string): number {\n let rv: number = -1;\n getFileSize(false, p, function(err: ApiError, size?: number) {\n if (err) {\n throw err;\n }\n rv = size!;\n });\n return rv;\n}\n\n/**\n * Asynchronously retrieves the size of the given file in bytes.\n * @hidden\n */\nexport function getFileSizeAsync(p: string, cb: (err: ApiError, size?: number) => void): void {\n getFileSize(true, p, cb);\n}\n\n\n\n// WEBPACK FOOTER //\n// ../../../../src/generic/xhr.ts","import {default as Stats, FileType} from '../core/node_fs_stats';\nimport * as path from 'path';\n\n/**\n * A simple class for storing a filesystem index. Assumes that all paths passed\n * to it are *absolute* paths.\n *\n * Can be used as a partial or a full index, although care must be taken if used\n * for the former purpose, especially when directories are concerned.\n */\nexport class FileIndex {\n /**\n * Static method for constructing indices from a JSON listing.\n * @param listing Directory listing generated by tools/XHRIndexer.coffee\n * @return A new FileIndex object.\n */\n public static fromListing(listing: any): FileIndex {\n const idx = new FileIndex();\n // Add a root DirNode.\n const rootInode = new DirInode();\n idx._index['/'] = rootInode;\n const queue = [['', listing, rootInode]];\n while (queue.length > 0) {\n let inode: Inode;\n const next = queue.pop();\n const pwd = next![0];\n const tree = next![1];\n const parent = next![2];\n for (const node in tree) {\n if (tree.hasOwnProperty(node)) {\n const children = tree[node];\n const name = `${pwd}/${node}`;\n if (children) {\n idx._index[name] = inode = new DirInode();\n queue.push([name, children, inode]);\n } else {\n // This inode doesn't have correct size information, noted with -1.\n inode = new FileInode(new Stats(FileType.FILE, -1, 0x16D));\n }\n if (parent) {\n parent._ls[node] = inode;\n }\n }\n }\n }\n return idx;\n }\n\n // Maps directory paths to directory inodes, which contain files.\n private _index: {[path: string]: DirInode };\n\n /**\n * Constructs a new FileIndex.\n */\n constructor() {\n // _index is a single-level key,value store that maps *directory* paths to\n // DirInodes. File information is only contained in DirInodes themselves.\n this._index = {};\n // Create the root directory.\n this.addPath('/', new DirInode());\n }\n\n /**\n * Runs the given function over all files in the index.\n */\n public fileIterator(cb: (file: T | null) => void): void {\n for (const path in this._index) {\n if (this._index.hasOwnProperty(path)) {\n const dir = this._index[path];\n const files = dir.getListing();\n for (const file of files) {\n const item = dir.getItem(file);\n if (isFileInode(item)) {\n cb(item.getData());\n }\n }\n }\n }\n }\n\n /**\n * Adds the given absolute path to the index if it is not already in the index.\n * Creates any needed parent directories.\n * @param path The path to add to the index.\n * @param inode The inode for the\n * path to add.\n * @return 'True' if it was added or already exists, 'false' if there\n * was an issue adding it (e.g. item in path is a file, item exists but is\n * different).\n * @todo If adding fails and implicitly creates directories, we do not clean up\n * the new empty directories.\n */\n public addPath(path: string, inode: Inode): boolean {\n if (!inode) {\n throw new Error('Inode must be specified');\n }\n if (path[0] !== '/') {\n throw new Error('Path must be absolute, got: ' + path);\n }\n\n // Check if it already exists.\n if (this._index.hasOwnProperty(path)) {\n return this._index[path] === inode;\n }\n\n const splitPath = this._split_path(path);\n const dirpath = splitPath[0];\n const itemname = splitPath[1];\n // Try to add to its parent directory first.\n let parent = this._index[dirpath];\n if (parent === undefined && path !== '/') {\n // Create parent.\n parent = new DirInode();\n if (!this.addPath(dirpath, parent)) {\n return false;\n }\n }\n // Add myself to my parent.\n if (path !== '/') {\n if (!parent.addItem(itemname, inode)) {\n return false;\n }\n }\n // If I'm a directory, add myself to the index.\n if (isDirInode(inode)) {\n this._index[path] = inode;\n }\n return true;\n }\n\n /**\n * Adds the given absolute path to the index if it is not already in the index.\n * The path is added without special treatment (no joining of adjacent separators, etc).\n * Creates any needed parent directories.\n * @param path The path to add to the index.\n * @param inode The inode for the\n * path to add.\n * @return 'True' if it was added or already exists, 'false' if there\n * was an issue adding it (e.g. item in path is a file, item exists but is\n * different).\n * @todo If adding fails and implicitly creates directories, we do not clean up\n * the new empty directories.\n */\n public addPathFast(path: string, inode: Inode): boolean {\n const itemNameMark = path.lastIndexOf('/');\n const parentPath = itemNameMark === 0 ? \"/\" : path.substring(0, itemNameMark);\n const itemName = path.substring(itemNameMark + 1);\n\n // Try to add to its parent directory first.\n let parent = this._index[parentPath];\n if (parent === undefined) {\n // Create parent.\n parent = new DirInode();\n this.addPathFast(parentPath, parent);\n }\n\n if (!parent.addItem(itemName, inode)) {\n return false;\n }\n\n // If adding a directory, add to the index as well.\n if (inode.isDir()) {\n this._index[path] = > inode;\n }\n return true;\n }\n\n /**\n * Removes the given path. Can be a file or a directory.\n * @return The removed item,\n * or null if it did not exist.\n */\n public removePath(path: string): Inode | null {\n const splitPath = this._split_path(path);\n const dirpath = splitPath[0];\n const itemname = splitPath[1];\n\n // Try to remove it from its parent directory first.\n const parent = this._index[dirpath];\n if (parent === undefined) {\n return null;\n }\n // Remove myself from my parent.\n const inode = parent.remItem(itemname);\n if (inode === null) {\n return null;\n }\n // If I'm a directory, remove myself from the index, and remove my children.\n if (isDirInode(inode)) {\n const children = inode.getListing();\n for (const child of children) {\n this.removePath(path + '/' + child);\n }\n\n // Remove the directory from the index, unless it's the root.\n if (path !== '/') {\n delete this._index[path];\n }\n }\n return inode;\n }\n\n /**\n * Retrieves the directory listing of the given path.\n * @return An array of files in the given path, or 'null' if it does not exist.\n */\n public ls(path: string): string[] | null {\n const item = this._index[path];\n if (item === undefined) {\n return null;\n }\n return item.getListing();\n }\n\n /**\n * Returns the inode of the given item.\n * @return Returns null if the item does not exist.\n */\n public getInode(path: string): Inode | null {\n const splitPath = this._split_path(path);\n const dirpath = splitPath[0];\n const itemname = splitPath[1];\n // Retrieve from its parent directory.\n const parent = this._index[dirpath];\n if (parent === undefined) {\n return null;\n }\n // Root case\n if (dirpath === path) {\n return parent;\n }\n return parent.getItem(itemname);\n }\n\n /**\n * Split into a (directory path, item name) pair\n */\n private _split_path(p: string): string[] {\n const dirpath = path.dirname(p);\n const itemname = p.substr(dirpath.length + (dirpath === \"/\" ? 0 : 1));\n return [dirpath, itemname];\n }\n}\n\n/**\n * Generic interface for file/directory inodes.\n * Note that Stats objects are what we use for file inodes.\n */\nexport interface Inode {\n // Is this an inode for a file?\n isFile(): boolean;\n // Is this an inode for a directory?\n isDir(): boolean;\n}\n\n/**\n * Inode for a file. Stores an arbitrary (filesystem-specific) data payload.\n */\nexport class FileInode implements Inode {\n constructor(private data: T) { }\n public isFile(): boolean { return true; }\n public isDir(): boolean { return false; }\n public getData(): T { return this.data; }\n public setData(data: T): void { this.data = data; }\n}\n\n/**\n * Inode for a directory. Currently only contains the directory listing.\n */\nexport class DirInode implements Inode {\n private _ls: {[path: string]: Inode} = {};\n /**\n * Constructs an inode for a directory.\n */\n constructor(private data: T | null = null) {}\n public isFile(): boolean {\n return false;\n }\n public isDir(): boolean {\n return true;\n }\n public getData(): T | null { return this.data; }\n\n /**\n * Return a Stats object for this inode.\n * @todo Should probably remove this at some point. This isn't the\n * responsibility of the FileIndex.\n */\n public getStats(): Stats {\n return new Stats(FileType.DIRECTORY, 4096, 0x16D);\n }\n /**\n * Returns the directory listing for this directory. Paths in the directory are\n * relative to the directory's path.\n * @return The directory listing for this directory.\n */\n public getListing(): string[] {\n return Object.keys(this._ls);\n }\n /**\n * Returns the inode for the indicated item, or null if it does not exist.\n * @param p Name of item in this directory.\n */\n public getItem(p: string): Inode | null {\n const item = this._ls[p];\n return item ? item : null;\n }\n /**\n * Add the given item to the directory listing. Note that the given inode is\n * not copied, and will be mutated by the DirInode if it is a DirInode.\n * @param p Item name to add to the directory listing.\n * @param inode The inode for the\n * item to add to the directory inode.\n * @return True if it was added, false if it already existed.\n */\n public addItem(p: string, inode: Inode): boolean {\n if (p in this._ls) {\n return false;\n }\n this._ls[p] = inode;\n return true;\n }\n /**\n * Removes the given item from the directory listing.\n * @param p Name of item to remove from the directory listing.\n * @return Returns the item\n * removed, or null if the item did not exist.\n */\n public remItem(p: string): Inode | null {\n const item = this._ls[p];\n if (item === undefined) {\n return null;\n }\n delete this._ls[p];\n return item;\n }\n}\n\n/**\n * @hidden\n */\nexport function isFileInode(inode: Inode | null): inode is FileInode {\n return !!inode && inode.isFile();\n}\n\n/**\n * @hidden\n */\nexport function isDirInode(inode: Inode | null): inode is DirInode {\n return !!inode && inode.isDir();\n}\n\n\n\n// WEBPACK FOOTER //\n// ../../../../src/generic/file_index.ts","import {BaseFileSystem, FileSystem, BFSCallback, FileSystemOptions} from '../core/file_system';\nimport {ApiError, ErrorCode} from '../core/api_error';\nimport {FileFlag, ActionType} from '../core/file_flag';\nimport {copyingSlice, deprecationMessage} from '../core/util';\nimport {File} from '../core/file';\nimport Stats from '../core/node_fs_stats';\nimport {NoSyncFile} from '../generic/preload_file';\nimport {asyncDownloadFile, syncDownloadFile, getFileSizeAsync, getFileSizeSync} from '../generic/xhr';\nimport {FileIndex, isFileInode, isDirInode} from '../generic/file_index';\n\n/**\n * Try to convert the given buffer into a string, and pass it to the callback.\n * Optimization that removes the needed try/catch into a helper function, as\n * this is an uncommon case.\n * @hidden\n */\nfunction tryToString(buff: Buffer, encoding: string, cb: BFSCallback) {\n try {\n cb(null, buff.toString(encoding));\n } catch (e) {\n cb(e);\n }\n}\n\n/**\n * Configuration options for an XmlHttpRequest file system.\n */\nexport interface XmlHttpRequestOptions {\n // URL to a file index as a JSON file or the file index object itself, generated with the make_xhrfs_index script.\n // Defaults to `index.json`.\n index?: string | object;\n // Used as the URL prefix for fetched files.\n // Default: Fetch files relative to the index.\n baseUrl?: string;\n}\n\n/**\n * A simple filesystem backed by XMLHttpRequests. You must create a directory listing using the\n * `make_xhrfs_index` tool provided by BrowserFS.\n *\n * If you install BrowserFS globally with `npm i -g browserfs`, you can generate a listing by\n * running `make_xhrfs_index` in your terminal in the directory you would like to index:\n *\n * ```\n * make_xhrfs_index > index.json\n * ```\n *\n * Listings objects look like the following:\n *\n * ```json\n * {\n * \"home\": {\n * \"jvilk\": {\n * \"someFile.txt\": null,\n * \"someDir\": {\n * // Empty directory\n * }\n * }\n * }\n * }\n * ```\n *\n * *This example has the folder `/home/jvilk` with subfile `someFile.txt` and subfolder `someDir`.*\n */\nexport default class XmlHttpRequest extends BaseFileSystem implements FileSystem {\n public static readonly Name = \"XmlHttpRequest\";\n\n public static readonly Options: FileSystemOptions = {\n index: {\n type: [\"string\", \"object\"],\n optional: true,\n description: \"URL to a file index as a JSON file or the file index object itself, generated with the make_xhrfs_index script. Defaults to `index.json`.\"\n },\n baseUrl: {\n type: \"string\",\n optional: true,\n description: \"Used as the URL prefix for fetched files. Default: Fetch files relative to the index.\"\n }\n };\n\n /**\n * Construct an XmlHttpRequest file system backend with the given options.\n */\n public static Create(opts: XmlHttpRequestOptions, cb: BFSCallback): void {\n if (opts.index === undefined) {\n opts.index = `index.json`;\n }\n if (typeof(opts.index) === \"string\") {\n XmlHttpRequest.FromURL(opts.index, cb, opts.baseUrl, false);\n } else {\n cb(null, new XmlHttpRequest(opts.index, opts.baseUrl, false));\n }\n }\n public static isAvailable(): boolean {\n return typeof(XMLHttpRequest) !== \"undefined\" && XMLHttpRequest !== null;\n }\n /**\n * **Deprecated. Please use XmlHttpRequest.Create() method instead to construct XmlHttpRequest objects.**\n *\n * Constructs an XmlHttpRequest object using the directory listing at the given URL.\n * Uses the base URL as the URL prefix for fetched files.\n * @param cb Called when the file system has been instantiated, or if an error occurs.\n */\n public static FromURL(url: string, cb: BFSCallback, baseUrl = url.slice(0, url.lastIndexOf('/') + 1), deprecateMsg = true): void {\n if (deprecateMsg) {\n console.warn(`[XmlHttpRequest] XmlHttpRequest.FromURL() is deprecated and will be removed in the next major release. Please use 'XmlHttpRequest.Create({ index: \"${url}\", baseUrl: \"${baseUrl}\" }, cb)' instead.`);\n }\n asyncDownloadFile(url, \"json\", (e, data?) => {\n if (e) {\n cb(e);\n } else {\n cb(null, new XmlHttpRequest(data, baseUrl, false));\n }\n });\n }\n\n public readonly prefixUrl: string;\n private _index: FileIndex<{}>;\n /**\n * **Deprecated. Please use XmlHttpRequest.Create() method instead to construct XmlHttpRequest objects.**\n *\n * Constructs the file system. You must provide the directory listing as a JSON object\n * produced by the `make_xhrfs_index` script.\n *\n * **DEPRECATED:** You may pass a URL to the file index to the constructor, which will fetch the file index\n * *synchronously* and may freeze up the web page. This behavior will be removed in the next major version\n * of BrowserFS.\n *\n * @param listingUrlOrObj index object or the path to the JSON file index generated by\n * `make_xhrfs_index`.\n * @param prefixUrl URL that is prepended to any file locations in the file index. e.g. if `prefixUrl = 'data/`, and the user wants to open the file `/foo.txt`,\n * the file system will fetch file `data/foo.txt`. The browser will access the file relative to the currrent webpage\n * URL.\n */\n constructor(listingUrlOrObj: string | object, prefixUrl: string = '', deprecateMsg = true) {\n super();\n if (!listingUrlOrObj) {\n listingUrlOrObj = 'index.json';\n }\n // prefix_url must end in a directory separator.\n if (prefixUrl.length > 0 && prefixUrl.charAt(prefixUrl.length - 1) !== '/') {\n prefixUrl = prefixUrl + '/';\n }\n this.prefixUrl = prefixUrl;\n\n let listing: object | null = null;\n if (typeof(listingUrlOrObj) === \"string\") {\n listing = this._requestFileSync( listingUrlOrObj, 'json');\n if (!listing) {\n throw new Error(\"Unable to find listing at URL: ${listingUrlOrObj}\");\n }\n } else {\n listing = listingUrlOrObj;\n }\n deprecationMessage(deprecateMsg, XmlHttpRequest.Name, { index: typeof(listingUrlOrObj) === \"string\" ? listingUrlOrObj : \"file index as an object\", baseUrl: prefixUrl});\n\n this._index = FileIndex.fromListing(listing);\n }\n\n public empty(): void {\n this._index.fileIterator(function(file: Stats) {\n file.fileData = null;\n });\n }\n\n public getName(): string {\n return XmlHttpRequest.Name;\n }\n\n public diskSpace(path: string, cb: (total: number, free: number) => void): void {\n // Read-only file system. We could calculate the total space, but that's not\n // important right now.\n cb(0, 0);\n }\n\n public isReadOnly(): boolean {\n return true;\n }\n\n public supportsLinks(): boolean {\n return false;\n }\n\n public supportsProps(): boolean {\n return false;\n }\n\n public supportsSynch(): boolean {\n return true;\n }\n\n /**\n * Special XHR function: Preload the given file into the index.\n * @param [String] path\n * @param [BrowserFS.Buffer] buffer\n */\n public preloadFile(path: string, buffer: Buffer): void {\n const inode = this._index.getInode(path);\n if (isFileInode(inode)) {\n if (inode === null) {\n throw ApiError.ENOENT(path);\n }\n const stats = inode.getData();\n stats.size = buffer.length;\n stats.fileData = buffer;\n } else {\n throw ApiError.EISDIR(path);\n }\n }\n\n public stat(path: string, isLstat: boolean, cb: BFSCallback): void {\n const inode = this._index.getInode(path);\n if (inode === null) {\n return cb(ApiError.ENOENT(path));\n }\n let stats: Stats;\n if (isFileInode(inode)) {\n stats = inode.getData();\n // At this point, a non-opened file will still have default stats from the listing.\n if (stats.size < 0) {\n this._requestFileSizeAsync(path, function(e: ApiError, size?: number) {\n if (e) {\n return cb(e);\n }\n stats.size = size!;\n cb(null, stats.clone());\n });\n } else {\n cb(null, stats.clone());\n }\n } else if (isDirInode(inode)) {\n stats = inode.getStats();\n cb(null, stats);\n } else {\n cb(ApiError.FileError(ErrorCode.EINVAL, path));\n }\n }\n\n public statSync(path: string, isLstat: boolean): Stats {\n const inode = this._index.getInode(path);\n if (inode === null) {\n throw ApiError.ENOENT(path);\n }\n let stats: Stats;\n if (isFileInode(inode)) {\n stats = inode.getData();\n // At this point, a non-opened file will still have default stats from the listing.\n if (stats.size < 0) {\n stats.size = this._requestFileSizeSync(path);\n }\n } else if (isDirInode(inode)) {\n stats = inode.getStats();\n } else {\n throw ApiError.FileError(ErrorCode.EINVAL, path);\n }\n return stats;\n }\n\n public open(path: string, flags: FileFlag, mode: number, cb: BFSCallback): void {\n // INVARIANT: You can't write to files on this file system.\n if (flags.isWriteable()) {\n return cb(new ApiError(ErrorCode.EPERM, path));\n }\n const self = this;\n // Check if the path exists, and is a file.\n const inode = this._index.getInode(path);\n if (inode === null) {\n return cb(ApiError.ENOENT(path));\n }\n if (isFileInode(inode)) {\n const stats = inode.getData();\n switch (flags.pathExistsAction()) {\n case ActionType.THROW_EXCEPTION:\n case ActionType.TRUNCATE_FILE:\n return cb(ApiError.EEXIST(path));\n case ActionType.NOP:\n // Use existing file contents.\n // XXX: Uh, this maintains the previously-used flag.\n if (stats.fileData) {\n return cb(null, new NoSyncFile(self, path, flags, stats.clone(), stats.fileData));\n }\n // @todo be lazier about actually requesting the file\n this._requestFileAsync(path, 'buffer', function(err: ApiError, buffer?: Buffer) {\n if (err) {\n return cb(err);\n }\n // we don't initially have file sizes\n stats.size = buffer!.length;\n stats.fileData = buffer!;\n return cb(null, new NoSyncFile(self, path, flags, stats.clone(), buffer));\n });\n break;\n default:\n return cb(new ApiError(ErrorCode.EINVAL, 'Invalid FileMode object.'));\n }\n } else {\n return cb(ApiError.EISDIR(path));\n }\n }\n\n public openSync(path: string, flags: FileFlag, mode: number): File {\n // INVARIANT: You can't write to files on this file system.\n if (flags.isWriteable()) {\n throw new ApiError(ErrorCode.EPERM, path);\n }\n // Check if the path exists, and is a file.\n const inode = this._index.getInode(path);\n if (inode === null) {\n throw ApiError.ENOENT(path);\n }\n if (isFileInode(inode)) {\n const stats = inode.getData();\n switch (flags.pathExistsAction()) {\n case ActionType.THROW_EXCEPTION:\n case ActionType.TRUNCATE_FILE:\n throw ApiError.EEXIST(path);\n case ActionType.NOP:\n // Use existing file contents.\n // XXX: Uh, this maintains the previously-used flag.\n if (stats.fileData) {\n return new NoSyncFile(this, path, flags, stats.clone(), stats.fileData);\n }\n // @todo be lazier about actually requesting the file\n const buffer = this._requestFileSync(path, 'buffer');\n // we don't initially have file sizes\n stats.size = buffer.length;\n stats.fileData = buffer;\n return new NoSyncFile(this, path, flags, stats.clone(), buffer);\n default:\n throw new ApiError(ErrorCode.EINVAL, 'Invalid FileMode object.');\n }\n } else {\n throw ApiError.EISDIR(path);\n }\n }\n\n public readdir(path: string, cb: BFSCallback): void {\n try {\n cb(null, this.readdirSync(path));\n } catch (e) {\n cb(e);\n }\n }\n\n public readdirSync(path: string): string[] {\n // Check if it exists.\n const inode = this._index.getInode(path);\n if (inode === null) {\n throw ApiError.ENOENT(path);\n } else if (isDirInode(inode)) {\n return inode.getListing();\n } else {\n throw ApiError.ENOTDIR(path);\n }\n }\n\n /**\n * We have the entire file as a buffer; optimize readFile.\n */\n public readFile(fname: string, encoding: string, flag: FileFlag, cb: BFSCallback): void {\n // Wrap cb in file closing code.\n const oldCb = cb;\n // Get file.\n this.open(fname, flag, 0x1a4, function(err: ApiError, fd?: File) {\n if (err) {\n return cb(err);\n }\n cb = function(err: ApiError, arg?: Buffer) {\n fd!.close(function(err2: any) {\n if (!err) {\n err = err2;\n }\n return oldCb(err, arg);\n });\n };\n const fdCast = > fd;\n const fdBuff = fdCast.getBuffer();\n if (encoding === null) {\n cb(err, copyingSlice(fdBuff));\n } else {\n tryToString(fdBuff, encoding, cb);\n }\n });\n }\n\n /**\n * Specially-optimized readfile.\n */\n public readFileSync(fname: string, encoding: string, flag: FileFlag): any {\n // Get file.\n const fd = this.openSync(fname, flag, 0x1a4);\n try {\n const fdCast = > fd;\n const fdBuff = fdCast.getBuffer();\n if (encoding === null) {\n return copyingSlice(fdBuff);\n }\n return fdBuff.toString(encoding);\n } finally {\n fd.closeSync();\n }\n }\n\n private getXhrPath(filePath: string): string {\n if (filePath.charAt(0) === '/') {\n filePath = filePath.slice(1);\n }\n return this.prefixUrl + filePath;\n }\n\n /**\n * Asynchronously download the given file.\n */\n private _requestFileAsync(p: string, type: 'buffer', cb: BFSCallback): void;\n private _requestFileAsync(p: string, type: 'json', cb: BFSCallback): void;\n private _requestFileAsync(p: string, type: string, cb: BFSCallback): void;\n private _requestFileAsync(p: string, type: string, cb: BFSCallback): void {\n asyncDownloadFile(this.getXhrPath(p), type, cb);\n }\n\n /**\n * Synchronously download the given file.\n */\n private _requestFileSync(p: string, type: 'buffer'): Buffer;\n private _requestFileSync(p: string, type: 'json'): any;\n private _requestFileSync(p: string, type: string): any;\n private _requestFileSync(p: string, type: string): any {\n return syncDownloadFile(this.getXhrPath(p), type);\n }\n\n /**\n * Only requests the HEAD content, for the file size.\n */\n private _requestFileSizeAsync(path: string, cb: BFSCallback): void {\n getFileSizeAsync(this.getXhrPath(path), cb);\n }\n private _requestFileSizeSync(path: string): number {\n return getFileSizeSync(this.getXhrPath(path));\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ../../../../src/backend/XmlHttpRequest.ts","import {ApiError, ErrorCode} from '../core/api_error';\nimport {default as Stats, FileType} from '../core/node_fs_stats';\nimport {SynchronousFileSystem, FileSystem, BFSCallback, FileSystemOptions} from '../core/file_system';\nimport {File} from '../core/file';\nimport {FileFlag, ActionType} from '../core/file_flag';\nimport {NoSyncFile} from '../generic/preload_file';\nimport {Arrayish, arrayish2Buffer, copyingSlice, deprecationMessage, bufferValidator} from '../core/util';\nimport ExtendedASCII from '../generic/extended_ascii';\nimport setImmediate from '../generic/setImmediate';\n/**\n * @hidden\n */\nconst inflateRaw:\n (data: Arrayish, options?: {\n chunkSize: number;\n }) => Arrayish = require('pako/lib/inflate').inflateRaw;\nimport {FileIndex, DirInode, FileInode, isDirInode, isFileInode} from '../generic/file_index';\n\n/**\n * Maps CompressionMethod => function that decompresses.\n * @hidden\n */\nconst decompressionMethods: {[method: number]: (data: Buffer, compressedSize: number, uncompressedSize: number, flags: number) => Buffer} = {};\n\n/**\n * 4.4.2.2: Indicates the compatibiltiy of a file's external attributes.\n */\nexport enum ExternalFileAttributeType {\n MSDOS = 0, AMIGA = 1, OPENVMS = 2, UNIX = 3, VM_CMS = 4, ATARI_ST = 5,\n OS2_HPFS = 6, MAC = 7, Z_SYSTEM = 8, CP_M = 9, NTFS = 10, MVS = 11, VSE = 12,\n ACORN_RISC = 13, VFAT = 14, ALT_MVS = 15, BEOS = 16, TANDEM = 17, OS_400 = 18,\n OSX = 19\n}\n\n/**\n * 4.4.5\n */\nexport enum CompressionMethod {\n STORED = 0, // The file is stored (no compression)\n SHRUNK = 1, // The file is Shrunk\n REDUCED_1 = 2, // The file is Reduced with compression factor 1\n REDUCED_2 = 3, // The file is Reduced with compression factor 2\n REDUCED_3 = 4, // The file is Reduced with compression factor 3\n REDUCED_4 = 5, // The file is Reduced with compression factor 4\n IMPLODE = 6, // The file is Imploded\n DEFLATE = 8, // The file is Deflated\n DEFLATE64 = 9, // Enhanced Deflating using Deflate64(tm)\n TERSE_OLD = 10, // PKWARE Data Compression Library Imploding (old IBM TERSE)\n BZIP2 = 12, // File is compressed using BZIP2 algorithm\n LZMA = 14, // LZMA (EFS)\n TERSE_NEW = 18, // File is compressed using IBM TERSE (new)\n LZ77 = 19, // IBM LZ77 z Architecture (PFS)\n WAVPACK = 97, // WavPack compressed data\n PPMD = 98 // PPMd version I, Rev 1\n}\n\n/**\n * Converts the input time and date in MS-DOS format into a JavaScript Date\n * object.\n * @hidden\n */\nfunction msdos2date(time: number, date: number): Date {\n // MS-DOS Date\n // |0 0 0 0 0|0 0 0 0|0 0 0 0 0 0 0\n // D (1-31) M (1-23) Y (from 1980)\n const day = date & 0x1F;\n // JS date is 0-indexed, DOS is 1-indexed.\n const month = ((date >> 5) & 0xF) - 1;\n const year = (date >> 9) + 1980;\n // MS DOS Time\n // |0 0 0 0 0|0 0 0 0 0 0|0 0 0 0 0\n // Second Minute Hour\n const second = time & 0x1F;\n const minute = (time >> 5) & 0x3F;\n const hour = time >> 11;\n return new Date(year, month, day, hour, minute, second);\n}\n\n/**\n * Safely returns the string from the buffer, even if it is 0 bytes long.\n * (Normally, calling toString() on a buffer with start === end causes an\n * exception).\n * @hidden\n */\nfunction safeToString(buff: Buffer, useUTF8: boolean, start: number, length: number): string {\n if (length === 0) {\n return \"\";\n } else if (useUTF8) {\n return buff.toString('utf8', start, start + length);\n } else {\n return ExtendedASCII.byte2str(buff.slice(start, start + length));\n }\n}\n\n/*\n 4.3.6 Overall .ZIP file format:\n\n [local file header 1]\n [encryption header 1]\n [file data 1]\n [data descriptor 1]\n .\n .\n .\n [local file header n]\n [encryption header n]\n [file data n]\n [data descriptor n]\n [archive decryption header]\n [archive extra data record]\n [central directory header 1]\n .\n .\n .\n [central directory header n]\n [zip64 end of central directory record]\n [zip64 end of central directory locator]\n [end of central directory record]\n*/\n\n/**\n * 4.3.7 Local file header:\n *\n * local file header signature 4 bytes (0x04034b50)\n * version needed to extract 2 bytes\n * general purpose bit flag 2 bytes\n * compression method 2 bytes\n * last mod file time 2 bytes\n * last mod file date 2 bytes\n * crc-32 4 bytes\n * compressed size 4 bytes\n * uncompressed size 4 bytes\n * file name length 2 bytes\n * extra field length 2 bytes\n *\n * file name (variable size)\n * extra field (variable size)\n */\nexport class FileHeader {\n constructor(private data: Buffer) {\n if (data.readUInt32LE(0) !== 0x04034b50) {\n throw new ApiError(ErrorCode.EINVAL, \"Invalid Zip file: Local file header has invalid signature: \" + this.data.readUInt32LE(0));\n }\n }\n public versionNeeded(): number { return this.data.readUInt16LE(4); }\n public flags(): number { return this.data.readUInt16LE(6); }\n public compressionMethod(): CompressionMethod { return this.data.readUInt16LE(8); }\n public lastModFileTime(): Date {\n // Time and date is in MS-DOS format.\n return msdos2date(this.data.readUInt16LE(10), this.data.readUInt16LE(12));\n }\n public rawLastModFileTime(): number {\n return this.data.readUInt32LE(10);\n }\n public crc32(): number { return this.data.readUInt32LE(14); }\n /**\n * These two values are COMPLETELY USELESS.\n *\n * Section 4.4.9:\n * If bit 3 of the general purpose bit flag is set,\n * these fields are set to zero in the local header and the\n * correct values are put in the data descriptor and\n * in the central directory.\n *\n * So we'll just use the central directory's values.\n */\n // public compressedSize(): number { return this.data.readUInt32LE(18); }\n // public uncompressedSize(): number { return this.data.readUInt32LE(22); }\n public fileNameLength(): number { return this.data.readUInt16LE(26); }\n public extraFieldLength(): number { return this.data.readUInt16LE(28); }\n public fileName(): string {\n return safeToString(this.data, this.useUTF8(), 30, this.fileNameLength());\n }\n public extraField(): Buffer {\n const start = 30 + this.fileNameLength();\n return this.data.slice(start, start + this.extraFieldLength());\n }\n public totalSize(): number { return 30 + this.fileNameLength() + this.extraFieldLength(); }\n public useUTF8(): boolean { return (this.flags() & 0x800) === 0x800; }\n}\n\n/**\n * 4.3.8 File data\n *\n * Immediately following the local header for a file\n * SHOULD be placed the compressed or stored data for the file.\n * If the file is encrypted, the encryption header for the file\n * SHOULD be placed after the local header and before the file\n * data. The series of [local file header][encryption header]\n * [file data][data descriptor] repeats for each file in the\n * .ZIP archive.\n *\n * Zero-byte files, directories, and other file types that\n * contain no content MUST not include file data.\n */\nexport class FileData {\n constructor(private header: FileHeader, private record: CentralDirectory, private data: Buffer) {}\n public decompress(): Buffer {\n // Check the compression\n const compressionMethod: CompressionMethod = this.header.compressionMethod();\n const fcn = decompressionMethods[compressionMethod];\n if (fcn) {\n return fcn(this.data, this.record.compressedSize(), this.record.uncompressedSize(), this.record.flag());\n } else {\n let name: string = CompressionMethod[compressionMethod];\n if (!name) {\n name = `Unknown: ${compressionMethod}`;\n }\n throw new ApiError(ErrorCode.EINVAL, `Invalid compression method on file '${this.header.fileName()}': ${name}`);\n }\n }\n public getHeader(): FileHeader {\n return this.header;\n }\n public getRecord(): CentralDirectory {\n return this.record;\n }\n public getRawData(): Buffer {\n return this.data;\n }\n}\n\n/**\n * 4.3.9 Data descriptor:\n *\n * crc-32 4 bytes\n * compressed size 4 bytes\n * uncompressed size 4 bytes\n */\nexport class DataDescriptor {\n constructor(private data: Buffer) {}\n public crc32(): number { return this.data.readUInt32LE(0); }\n public compressedSize(): number { return this.data.readUInt32LE(4); }\n public uncompressedSize(): number { return this.data.readUInt32LE(8); }\n}\n\n/*\n` 4.3.10 Archive decryption header:\n\n 4.3.10.1 The Archive Decryption Header is introduced in version 6.2\n of the ZIP format specification. This record exists in support\n of the Central Directory Encryption Feature implemented as part of\n the Strong Encryption Specification as described in this document.\n When the Central Directory Structure is encrypted, this decryption\n header MUST precede the encrypted data segment.\n */\n/**\n * 4.3.11 Archive extra data record:\n *\n * archive extra data signature 4 bytes (0x08064b50)\n * extra field length 4 bytes\n * extra field data (variable size)\n *\n * 4.3.11.1 The Archive Extra Data Record is introduced in version 6.2\n * of the ZIP format specification. This record MAY be used in support\n * of the Central Directory Encryption Feature implemented as part of\n * the Strong Encryption Specification as described in this document.\n * When present, this record MUST immediately precede the central\n * directory data structure.\n */\nexport class ArchiveExtraDataRecord {\n constructor(private data: Buffer) {\n if (this.data.readUInt32LE(0) !== 0x08064b50) {\n throw new ApiError(ErrorCode.EINVAL, \"Invalid archive extra data record signature: \" + this.data.readUInt32LE(0));\n }\n }\n public length(): number { return this.data.readUInt32LE(4); }\n public extraFieldData(): Buffer { return this.data.slice(8, 8 + this.length()); }\n}\n\n/**\n * 4.3.13 Digital signature:\n *\n * header signature 4 bytes (0x05054b50)\n * size of data 2 bytes\n * signature data (variable size)\n *\n * With the introduction of the Central Directory Encryption\n * feature in version 6.2 of this specification, the Central\n * Directory Structure MAY be stored both compressed and encrypted.\n * Although not required, it is assumed when encrypting the\n * Central Directory Structure, that it will be compressed\n * for greater storage efficiency. Information on the\n * Central Directory Encryption feature can be found in the section\n * describing the Strong Encryption Specification. The Digital\n * Signature record will be neither compressed nor encrypted.\n */\nexport class DigitalSignature {\n constructor(private data: Buffer) {\n if (this.data.readUInt32LE(0) !== 0x05054b50) {\n throw new ApiError(ErrorCode.EINVAL, \"Invalid digital signature signature: \" + this.data.readUInt32LE(0));\n }\n }\n public size(): number { return this.data.readUInt16LE(4); }\n public signatureData(): Buffer { return this.data.slice(6, 6 + this.size()); }\n}\n\n/**\n * 4.3.12 Central directory structure:\n *\n * central file header signature 4 bytes (0x02014b50)\n * version made by 2 bytes\n * version needed to extract 2 bytes\n * general purpose bit flag 2 bytes\n * compression method 2 bytes\n * last mod file time 2 bytes\n * last mod file date 2 bytes\n * crc-32 4 bytes\n * compressed size 4 bytes\n * uncompressed size 4 bytes\n * file name length 2 bytes\n * extra field length 2 bytes\n * file comment length 2 bytes\n * disk number start 2 bytes\n * internal file attributes 2 bytes\n * external file attributes 4 bytes\n * relative offset of local header 4 bytes\n *\n * file name (variable size)\n * extra field (variable size)\n * file comment (variable size)\n */\nexport class CentralDirectory {\n // Optimization: The filename is frequently read, so stash it here.\n private _filename: string;\n constructor(private zipData: Buffer, private data: Buffer) {\n // Sanity check.\n if (this.data.readUInt32LE(0) !== 0x02014b50) {\n throw new ApiError(ErrorCode.EINVAL, `Invalid Zip file: Central directory record has invalid signature: ${this.data.readUInt32LE(0)}`);\n }\n this._filename = this.produceFilename();\n }\n public versionMadeBy(): number { return this.data.readUInt16LE(4); }\n public versionNeeded(): number { return this.data.readUInt16LE(6); }\n public flag(): number { return this.data.readUInt16LE(8); }\n public compressionMethod(): CompressionMethod { return this.data.readUInt16LE(10); }\n public lastModFileTime(): Date {\n // Time and date is in MS-DOS format.\n return msdos2date(this.data.readUInt16LE(12), this.data.readUInt16LE(14));\n }\n public rawLastModFileTime(): number {\n return this.data.readUInt32LE(12);\n }\n public crc32(): number { return this.data.readUInt32LE(16); }\n public compressedSize(): number { return this.data.readUInt32LE(20); }\n public uncompressedSize(): number { return this.data.readUInt32LE(24); }\n public fileNameLength(): number { return this.data.readUInt16LE(28); }\n public extraFieldLength(): number { return this.data.readUInt16LE(30); }\n public fileCommentLength(): number { return this.data.readUInt16LE(32); }\n public diskNumberStart(): number { return this.data.readUInt16LE(34); }\n public internalAttributes(): number { return this.data.readUInt16LE(36); }\n public externalAttributes(): number { return this.data.readUInt32LE(38); }\n public headerRelativeOffset(): number { return this.data.readUInt32LE(42); }\n public produceFilename(): string {\n /*\n 4.4.17.1 claims:\n * All slashes are forward ('/') slashes.\n * Filename doesn't begin with a slash.\n * No drive letters or any nonsense like that.\n * If filename is missing, the input came from standard input.\n\n Unfortunately, this isn't true in practice. Some Windows zip utilities use\n a backslash here, but the correct Unix-style path in file headers.\n\n To avoid seeking all over the file to recover the known-good filenames\n from file headers, we simply convert '/' to '\\' here.\n */\n const fileName: string = safeToString(this.data, this.useUTF8(), 46, this.fileNameLength());\n return fileName.replace(/\\\\/g, \"/\");\n }\n public fileName(): string {\n return this._filename;\n }\n public rawFileName(): Buffer {\n return this.data.slice(46, 46 + this.fileNameLength());\n }\n public extraField(): Buffer {\n const start = 44 + this.fileNameLength();\n return this.data.slice(start, start + this.extraFieldLength());\n }\n public fileComment(): string {\n const start = 46 + this.fileNameLength() + this.extraFieldLength();\n return safeToString(this.data, this.useUTF8(), start, this.fileCommentLength());\n }\n public rawFileComment(): Buffer {\n const start = 46 + this.fileNameLength() + this.extraFieldLength();\n return this.data.slice(start, start + this.fileCommentLength());\n }\n public totalSize(): number {\n return 46 + this.fileNameLength() + this.extraFieldLength() + this.fileCommentLength();\n }\n public isDirectory(): boolean {\n // NOTE: This assumes that the zip file implementation uses the lower byte\n // of external attributes for DOS attributes for\n // backwards-compatibility. This is not mandated, but appears to be\n // commonplace.\n // According to the spec, the layout of external attributes is\n // platform-dependent.\n // If that fails, we also check if the name of the file ends in '/',\n // which is what Java's ZipFile implementation does.\n const fileName = this.fileName();\n return (this.externalAttributes() & 0x10 ? true : false) || (fileName.charAt(fileName.length - 1) === '/');\n }\n public isFile(): boolean { return !this.isDirectory(); }\n public useUTF8(): boolean { return (this.flag() & 0x800) === 0x800; }\n public isEncrypted(): boolean { return (this.flag() & 0x1) === 0x1; }\n public getFileData(): FileData {\n // Need to grab the header before we can figure out where the actual\n // compressed data starts.\n const start = this.headerRelativeOffset();\n const header = new FileHeader(this.zipData.slice(start));\n return new FileData(header, this, this.zipData.slice(start + header.totalSize()));\n }\n public getData(): Buffer {\n return this.getFileData().decompress();\n }\n public getRawData(): Buffer {\n return this.getFileData().getRawData();\n }\n public getStats(): Stats {\n return new Stats(FileType.FILE, this.uncompressedSize(), 0x16D, new Date(), this.lastModFileTime());\n }\n}\n\n/**\n * 4.3.16: end of central directory record\n * end of central dir signature 4 bytes (0x06054b50)\n * number of this disk 2 bytes\n * number of the disk with the\n * start of the central directory 2 bytes\n * total number of entries in the\n * central directory on this disk 2 bytes\n * total number of entries in\n * the central directory 2 bytes\n * size of the central directory 4 bytes\n * offset of start of central\n * directory with respect to\n * the starting disk number 4 bytes\n * .ZIP file comment length 2 bytes\n * .ZIP file comment (variable size)\n */\nexport class EndOfCentralDirectory {\n constructor(private data: Buffer) {\n if (this.data.readUInt32LE(0) !== 0x06054b50) {\n throw new ApiError(ErrorCode.EINVAL, `Invalid Zip file: End of central directory record has invalid signature: ${this.data.readUInt32LE(0)}`);\n }\n }\n public diskNumber(): number { return this.data.readUInt16LE(4); }\n public cdDiskNumber(): number { return this.data.readUInt16LE(6); }\n public cdDiskEntryCount(): number { return this.data.readUInt16LE(8); }\n public cdTotalEntryCount(): number { return this.data.readUInt16LE(10); }\n public cdSize(): number { return this.data.readUInt32LE(12); }\n public cdOffset(): number { return this.data.readUInt32LE(16); }\n public cdZipCommentLength(): number { return this.data.readUInt16LE(20); }\n public cdZipComment(): string {\n // Assuming UTF-8. The specification doesn't specify.\n return safeToString(this.data, true, 22, this.cdZipCommentLength());\n }\n public rawCdZipComment(): Buffer {\n return this.data.slice(22, 22 + this.cdZipCommentLength());\n }\n}\n\n/**\n * Contains the table of contents of a Zip file.\n */\nexport class ZipTOC {\n constructor(public index: FileIndex, public directoryEntries: CentralDirectory[], public eocd: EndOfCentralDirectory, public data: Buffer) {\n }\n}\n\n/**\n * Configuration options for a ZipFS file system.\n */\nexport interface ZipFSOptions {\n // The zip file as a binary buffer.\n zipData: Buffer;\n // The name of the zip file (optional).\n name?: string;\n}\n\n/**\n * Zip file-backed filesystem\n * Implemented according to the standard:\n * http://www.pkware.com/documents/casestudies/APPNOTE.TXT\n *\n * While there are a few zip libraries for JavaScript (e.g. JSZip and zip.js),\n * they are not a good match for BrowserFS. In particular, these libraries\n * perform a lot of unneeded data copying, and eagerly decompress every file\n * in the zip file upon loading to check the CRC32. They also eagerly decode\n * strings. Furthermore, these libraries duplicate functionality already present\n * in BrowserFS (e.g. UTF-8 decoding and binary data manipulation).\n *\n * This filesystem takes advantage of BrowserFS's Buffer implementation, which\n * efficiently represents the zip file in memory (in both ArrayBuffer-enabled\n * browsers *and* non-ArrayBuffer browsers), and which can neatly be 'sliced'\n * without copying data. Each struct defined in the standard is represented with\n * a buffer slice pointing to an offset in the zip file, and has getters for\n * each field. As we anticipate that this data will not be read often, we choose\n * not to store each struct field in the JavaScript object; instead, to reduce\n * memory consumption, we retrieve it directly from the binary data each time it\n * is requested.\n *\n * When the filesystem is instantiated, we determine the directory structure\n * of the zip file as quickly as possible. We lazily decompress and check the\n * CRC32 of files. We do not cache decompressed files; if this is a desired\n * feature, it is best implemented as a generic file system wrapper that can\n * cache data from arbitrary file systems.\n *\n * For inflation, we use `pako`'s implementation:\n * https://github.com/nodeca/pako\n *\n * Current limitations:\n * * No encryption.\n * * No ZIP64 support.\n * * Read-only.\n * Write support would require that we:\n * - Keep track of changed/new files.\n * - Compress changed files, and generate appropriate metadata for each.\n * - Update file offsets for other files in the zip file.\n * - Stream it out to a location.\n * This isn't that bad, so we might do this at a later date.\n */\nexport default class ZipFS extends SynchronousFileSystem implements FileSystem {\n public static readonly Name = \"ZipFS\";\n\n public static readonly Options: FileSystemOptions = {\n zipData: {\n type: \"object\",\n description: \"The zip file as a Buffer object.\",\n validator: bufferValidator\n },\n name: {\n type: \"string\",\n optional: true,\n description: \"The name of the zip file (optional).\"\n }\n };\n\n public static readonly CompressionMethod = CompressionMethod;\n\n /**\n * Constructs a ZipFS instance with the given options.\n */\n public static Create(opts: ZipFSOptions, cb: BFSCallback): void {\n try {\n ZipFS.computeIndex(opts.zipData, (zipTOC) => {\n const fs = new ZipFS(zipTOC, opts.name, false);\n cb(null, fs);\n }, false);\n } catch (e) {\n cb(e);\n }\n }\n\n public static isAvailable(): boolean { return true; }\n\n public static RegisterDecompressionMethod(m: CompressionMethod, fcn: (data: Buffer, compressedSize: number, uncompressedSize: number, flags: number) => Buffer): void {\n decompressionMethods[m] = fcn;\n }\n\n /**\n * **Deprecated. Please use ZipFS.Create() method instead.**\n */\n public static computeIndex(data: Buffer, cb: (zipTOC: ZipTOC) => void, deprecateMsg = true) {\n // TODO: Refactor to plumb errors through. Right now, they throw.\n if (deprecateMsg) {\n console.warn(`[ZipFS] ZipFS.computeIndex is now deprecated, and will be removed in the next major release. Please update your code to use 'ZipFS.Create({ zipData: zip file as a Buffer}, cb)' instead.`);\n }\n const index: FileIndex = new FileIndex();\n const eocd: EndOfCentralDirectory = ZipFS.getEOCD(data);\n if (eocd.diskNumber() !== eocd.cdDiskNumber()) {\n throw new ApiError(ErrorCode.EINVAL, \"ZipFS does not support spanned zip files.\");\n }\n\n const cdPtr = eocd.cdOffset();\n if (cdPtr === 0xFFFFFFFF) {\n throw new ApiError(ErrorCode.EINVAL, \"ZipFS does not support Zip64.\");\n }\n const cdEnd = cdPtr + eocd.cdSize();\n ZipFS.computeIndexResponsive(data, index, cdPtr, cdEnd, cb, [], eocd);\n }\n\n /**\n * Locates the end of central directory record at the end of the file.\n * Throws an exception if it cannot be found.\n */\n private static getEOCD(data: Buffer): EndOfCentralDirectory {\n // Unfortunately, the comment is variable size and up to 64K in size.\n // We assume that the magic signature does not appear in the comment, and\n // in the bytes between the comment and the signature. Other ZIP\n // implementations make this same assumption, since the alternative is to\n // read thread every entry in the file to get to it. :(\n // These are *negative* offsets from the end of the file.\n const startOffset = 22;\n const endOffset = Math.min(startOffset + 0xFFFF, data.length - 1);\n // There's not even a byte alignment guarantee on the comment so we need to\n // search byte by byte. *grumble grumble*\n for (let i = startOffset; i < endOffset; i++) {\n // Magic number: EOCD Signature\n if (data.readUInt32LE(data.length - i) === 0x06054b50) {\n return new EndOfCentralDirectory(data.slice(data.length - i));\n }\n }\n throw new ApiError(ErrorCode.EINVAL, \"Invalid ZIP file: Could not locate End of Central Directory signature.\");\n }\n\n private static addToIndex(cd: CentralDirectory, index: FileIndex) {\n // Paths must be absolute, yet zip file paths are always relative to the\n // zip root. So we append '/' and call it a day.\n let filename = cd.fileName();\n if (filename.charAt(0) === '/') {\n throw new Error(\"WHY IS THIS ABSOLUTE\");\n }\n // XXX: For the file index, strip the trailing '/'.\n if (filename.charAt(filename.length - 1) === '/') {\n filename = filename.substr(0, filename.length - 1);\n }\n\n if (cd.isDirectory()) {\n index.addPathFast('/' + filename, new DirInode(cd));\n } else {\n index.addPathFast('/' + filename, new FileInode(cd));\n }\n }\n\n private static computeIndexResponsive(data: Buffer, index: FileIndex, cdPtr: number, cdEnd: number, cb: (zipTOC: ZipTOC) => void, cdEntries: CentralDirectory[], eocd: EndOfCentralDirectory) {\n if (cdPtr < cdEnd) {\n let count = 0;\n while (count++ < 200 && cdPtr < cdEnd) {\n const cd: CentralDirectory = new CentralDirectory(data, data.slice(cdPtr));\n ZipFS.addToIndex(cd, index);\n cdPtr += cd.totalSize();\n cdEntries.push(cd);\n }\n setImmediate(() => {\n ZipFS.computeIndexResponsive(data, index, cdPtr, cdEnd, cb, cdEntries, eocd);\n });\n } else {\n cb(new ZipTOC(index, cdEntries, eocd, data));\n }\n }\n\n private _index: FileIndex = new FileIndex();\n private _directoryEntries: CentralDirectory[] = [];\n private _eocd: EndOfCentralDirectory | null = null;\n private data: Buffer;\n\n /**\n * **Deprecated. Please use ZipFS.Create() method to construct ZipFS objects.**\n */\n constructor(input: Buffer | ZipTOC, private name: string = '', deprecateMsg = true) {\n super();\n deprecationMessage(deprecateMsg, ZipFS.Name, {zipData: \"zip data as a Buffer\", name: name});\n if (input instanceof ZipTOC) {\n this._index = input.index;\n this._directoryEntries = input.directoryEntries;\n this._eocd = input.eocd;\n this.data = input.data;\n } else {\n this.data = input as Buffer;\n this.populateIndex();\n }\n }\n\n public getName(): string {\n return ZipFS.Name + (this.name !== '' ? ` ${this.name}` : '');\n }\n\n /**\n * Get the CentralDirectory object for the given path.\n */\n public getCentralDirectoryEntry(path: string): CentralDirectory {\n const inode = this._index.getInode(path);\n if (inode === null) {\n throw ApiError.ENOENT(path);\n }\n if (isFileInode(inode)) {\n return inode.getData();\n } else if (isDirInode(inode)) {\n return inode.getData()!;\n } else {\n // Should never occur.\n throw ApiError.EPERM(`Invalid inode: ${inode}`);\n }\n }\n\n public getCentralDirectoryEntryAt(index: number): CentralDirectory {\n const dirEntry = this._directoryEntries[index];\n if (!dirEntry) {\n throw new RangeError(`Invalid directory index: ${index}.`);\n }\n return dirEntry;\n }\n\n public getNumberOfCentralDirectoryEntries(): number {\n return this._directoryEntries.length;\n }\n\n public getEndOfCentralDirectory(): EndOfCentralDirectory | null {\n return this._eocd;\n }\n\n public diskSpace(path: string, cb: (total: number, free: number) => void): void {\n // Read-only file system.\n cb(this.data.length, 0);\n }\n\n public isReadOnly(): boolean {\n return true;\n }\n\n public supportsLinks(): boolean {\n return false;\n }\n\n public supportsProps(): boolean {\n return false;\n }\n\n public supportsSynch(): boolean {\n return true;\n }\n\n public statSync(path: string, isLstat: boolean): Stats {\n const inode = this._index.getInode(path);\n if (inode === null) {\n throw ApiError.ENOENT(path);\n }\n let stats: Stats;\n if (isFileInode(inode)) {\n stats = inode.getData().getStats();\n } else if (isDirInode(inode)) {\n stats = inode.getStats();\n } else {\n throw new ApiError(ErrorCode.EINVAL, \"Invalid inode.\");\n }\n return stats;\n }\n\n public openSync(path: string, flags: FileFlag, mode: number): File {\n // INVARIANT: Cannot write to RO file systems.\n if (flags.isWriteable()) {\n throw new ApiError(ErrorCode.EPERM, path);\n }\n // Check if the path exists, and is a file.\n const inode = this._index.getInode(path);\n if (!inode) {\n throw ApiError.ENOENT(path);\n } else if (isFileInode(inode)) {\n const cdRecord = inode.getData();\n const stats = cdRecord.getStats();\n switch (flags.pathExistsAction()) {\n case ActionType.THROW_EXCEPTION:\n case ActionType.TRUNCATE_FILE:\n throw ApiError.EEXIST(path);\n case ActionType.NOP:\n return new NoSyncFile(this, path, flags, stats, cdRecord.getData());\n default:\n throw new ApiError(ErrorCode.EINVAL, 'Invalid FileMode object.');\n }\n } else {\n throw ApiError.EISDIR(path);\n }\n }\n\n public readdirSync(path: string): string[] {\n // Check if it exists.\n const inode = this._index.getInode(path);\n if (!inode) {\n throw ApiError.ENOENT(path);\n } else if (isDirInode(inode)) {\n return inode.getListing();\n } else {\n throw ApiError.ENOTDIR(path);\n }\n }\n\n /**\n * Specially-optimized readfile.\n */\n public readFileSync(fname: string, encoding: string, flag: FileFlag): any {\n // Get file.\n const fd = this.openSync(fname, flag, 0x1a4);\n try {\n const fdCast = > fd;\n const fdBuff = fdCast.getBuffer();\n if (encoding === null) {\n return copyingSlice(fdBuff);\n }\n return fdBuff.toString(encoding);\n } finally {\n fd.closeSync();\n }\n }\n\n private populateIndex() {\n const eocd: EndOfCentralDirectory = this._eocd = ZipFS.getEOCD(this.data);\n if (eocd.diskNumber() !== eocd.cdDiskNumber()) {\n throw new ApiError(ErrorCode.EINVAL, \"ZipFS does not support spanned zip files.\");\n }\n\n let cdPtr = eocd.cdOffset();\n if (cdPtr === 0xFFFFFFFF) {\n throw new ApiError(ErrorCode.EINVAL, \"ZipFS does not support Zip64.\");\n }\n const cdEnd = cdPtr + eocd.cdSize();\n while (cdPtr < cdEnd) {\n const cd: CentralDirectory = new CentralDirectory(this.data, this.data.slice(cdPtr));\n cdPtr += cd.totalSize();\n ZipFS.addToIndex(cd, this._index);\n this._directoryEntries.push(cd);\n }\n }\n}\n\nZipFS.RegisterDecompressionMethod(CompressionMethod.DEFLATE, (data, compressedSize, uncompressedSize) => {\n return arrayish2Buffer(inflateRaw(\n data.slice(0, compressedSize),\n { chunkSize: uncompressedSize }\n ));\n});\n\nZipFS.RegisterDecompressionMethod(CompressionMethod.STORED, (data, compressedSize, uncompressedSize) => {\n return copyingSlice(data, 0, uncompressedSize);\n});\n\n\n\n// WEBPACK FOOTER //\n// ../../../../src/backend/ZipFS.ts","import {ApiError, ErrorCode} from '../core/api_error';\nimport {default as Stats, FileType} from '../core/node_fs_stats';\nimport {SynchronousFileSystem, FileSystem, BFSCallback, FileSystemOptions} from '../core/file_system';\nimport {File} from '../core/file';\nimport {FileFlag, ActionType} from '../core/file_flag';\nimport {NoSyncFile} from '../generic/preload_file';\nimport {copyingSlice, deprecationMessage, bufferValidator} from '../core/util';\nimport * as path from 'path';\n\n/**\n * @hidden\n */\nconst rockRidgeIdentifier = \"IEEE_P1282\";\n/**\n * @hidden\n */\nconst enum VolumeDescriptorTypeCode {\n BootRecord = 0,\n PrimaryVolumeDescriptor = 1,\n SupplementaryVolumeDescriptor = 2,\n VolumePartitionDescriptor = 3,\n VolumeDescriptorSetTerminator = 255\n}\n\n/**\n * @hidden\n */\ntype TGetString = (d: Buffer, i: number, len: number) => string;\n\n/**\n * @hidden\n */\nfunction getASCIIString(data: Buffer, startIndex: number, length: number) {\n return data.toString('ascii', startIndex, startIndex + length).trim();\n}\n\n/**\n * @hidden\n */\nfunction getJolietString(data: Buffer, startIndex: number, length: number): string {\n if (length === 1) {\n // Special: Root, parent, current directory are still a single byte.\n return String.fromCharCode(data[startIndex]);\n }\n // UTF16-BE, which isn't natively supported by NodeJS Buffers.\n // Length should be even, but pessimistically floor just in case.\n const pairs = Math.floor(length / 2);\n const chars = new Array(pairs);\n for (let i = 0; i < pairs; i++) {\n const pos = startIndex + (i << 1);\n chars[i] = String.fromCharCode(data[pos + 1] | (data[pos] << 8));\n }\n return chars.join('');\n}\n\n/**\n * @hidden\n */\nfunction getDate(data: Buffer, startIndex: number): Date {\n const year = parseInt(getASCIIString(data, startIndex, 4), 10);\n const mon = parseInt(getASCIIString(data, startIndex + 4, 2), 10);\n const day = parseInt(getASCIIString(data, startIndex + 6, 2), 10);\n const hour = parseInt(getASCIIString(data, startIndex + 8, 2), 10);\n const min = parseInt(getASCIIString(data, startIndex + 10, 2), 10);\n const sec = parseInt(getASCIIString(data, startIndex + 12, 2), 10);\n const hundrethsSec = parseInt(getASCIIString(data, startIndex + 14, 2), 10);\n // Last is a time-zone offset, but JavaScript dates don't support time zones well.\n return new Date(year, mon, day, hour, min, sec, hundrethsSec * 100);\n}\n\n/**\n * @hidden\n */\nfunction getShortFormDate(data: Buffer, startIndex: number): Date {\n const yearsSince1900 = data[startIndex];\n const month = data[startIndex + 1];\n const day = data[startIndex + 2];\n const hour = data[startIndex + 3];\n const minute = data[startIndex + 4];\n const second = data[startIndex + 5];\n // JavaScript's Date support isn't so great; ignore timezone.\n // const offsetFromGMT = this._data[24];\n return new Date(yearsSince1900, month - 1, day, hour, minute, second);\n}\n\n/**\n * @hidden\n */\nfunction constructSystemUseEntry(bigData: Buffer, i: number): SystemUseEntry {\n const data = bigData.slice(i);\n const sue = new SystemUseEntry(data);\n switch (sue.signatureWord()) {\n case SystemUseEntrySignatures.CE:\n return new CEEntry(data);\n case SystemUseEntrySignatures.PD:\n return new PDEntry(data);\n case SystemUseEntrySignatures.SP:\n return new SPEntry(data);\n case SystemUseEntrySignatures.ST:\n return new STEntry(data);\n case SystemUseEntrySignatures.ER:\n return new EREntry(data);\n case SystemUseEntrySignatures.ES:\n return new ESEntry(data);\n case SystemUseEntrySignatures.PX:\n return new PXEntry(data);\n case SystemUseEntrySignatures.PN:\n return new PNEntry(data);\n case SystemUseEntrySignatures.SL:\n return new SLEntry(data);\n case SystemUseEntrySignatures.NM:\n return new NMEntry(data);\n case SystemUseEntrySignatures.CL:\n return new CLEntry(data);\n case SystemUseEntrySignatures.PL:\n return new PLEntry(data);\n case SystemUseEntrySignatures.RE:\n return new REEntry(data);\n case SystemUseEntrySignatures.TF:\n return new TFEntry(data);\n case SystemUseEntrySignatures.SF:\n return new SFEntry(data);\n case SystemUseEntrySignatures.RR:\n return new RREntry(data);\n default:\n return sue;\n }\n}\n\n/**\n * @hidden\n */\nfunction constructSystemUseEntries(data: Buffer, i: number, len: number, isoData: Buffer): SystemUseEntry[] {\n // If the remaining allocated space following the last recorded System Use Entry in a System\n // Use field or Continuation Area is less than four bytes long, it cannot contain a System\n // Use Entry and shall be ignored\n len = len - 4;\n let entries = new Array();\n while (i < len) {\n const entry = constructSystemUseEntry(data, i);\n const length = entry.length();\n if (length === 0) {\n // Invalid SU section; prevent infinite loop.\n return entries;\n }\n i += length;\n if (entry instanceof STEntry) {\n // ST indicates the end of entries.\n break;\n }\n if (entry instanceof CEEntry) {\n entries = entries.concat(entry.getEntries(isoData));\n } else {\n entries.push(entry);\n }\n }\n return entries;\n}\n\n/**\n * @hidden\n */\nclass VolumeDescriptor {\n protected _data: Buffer;\n constructor(data: Buffer) {\n this._data = data;\n }\n public type(): VolumeDescriptorTypeCode {\n return this._data[0];\n }\n public standardIdentifier(): string {\n return getASCIIString(this._data, 1, 5);\n }\n public version(): number {\n return this._data[6];\n }\n public data(): Buffer {\n return this._data.slice(7, 2048);\n }\n}\n\n/**\n * @hidden\n */\nabstract class PrimaryOrSupplementaryVolumeDescriptor extends VolumeDescriptor {\n private _root: DirectoryRecord | null = null;\n constructor(data: Buffer) {\n super(data);\n }\n public systemIdentifier(): string {\n return this._getString32(8);\n }\n public volumeIdentifier(): string {\n return this._getString32(40);\n }\n public volumeSpaceSize(): number {\n return this._data.readUInt32LE(80);\n }\n public volumeSetSize(): number {\n return this._data.readUInt16LE(120);\n }\n public volumeSequenceNumber(): number {\n return this._data.readUInt16LE(124);\n }\n public logicalBlockSize(): number {\n return this._data.readUInt16LE(128);\n }\n public pathTableSize(): number {\n return this._data.readUInt32LE(132);\n }\n public locationOfTypeLPathTable(): number {\n return this._data.readUInt32LE(140);\n }\n public locationOfOptionalTypeLPathTable(): number {\n return this._data.readUInt32LE(144);\n }\n public locationOfTypeMPathTable(): number {\n return this._data.readUInt32BE(148);\n }\n public locationOfOptionalTypeMPathTable(): number {\n return this._data.readUInt32BE(152);\n }\n public rootDirectoryEntry(isoData: Buffer): DirectoryRecord {\n if (this._root === null) {\n this._root = this._constructRootDirectoryRecord(this._data.slice(156));\n this._root.rootCheckForRockRidge(isoData);\n }\n return this._root;\n }\n public volumeSetIdentifier(): string {\n return this._getString(190, 128);\n }\n public publisherIdentifier(): string {\n return this._getString(318, 128);\n }\n public dataPreparerIdentifier(): string {\n return this._getString(446, 128);\n }\n public applicationIdentifier(): string {\n return this._getString(574, 128);\n }\n public copyrightFileIdentifier(): string {\n return this._getString(702, 38);\n }\n public abstractFileIdentifier(): string {\n return this._getString(740, 36);\n }\n public bibliographicFileIdentifier(): string {\n return this._getString(776, 37);\n }\n public volumeCreationDate(): Date {\n return getDate(this._data, 813);\n }\n public volumeModificationDate(): Date {\n return getDate(this._data, 830);\n }\n public volumeExpirationDate(): Date {\n return getDate(this._data, 847);\n }\n public volumeEffectiveDate(): Date {\n return getDate(this._data, 864);\n }\n public fileStructureVersion(): number {\n return this._data[881];\n }\n public applicationUsed(): Buffer {\n return this._data.slice(883, 883 + 512);\n }\n public reserved(): Buffer {\n return this._data.slice(1395, 1395 + 653);\n }\n public abstract name(): string;\n protected abstract _constructRootDirectoryRecord(data: Buffer): DirectoryRecord;\n protected abstract _getString(idx: number, len: number): string;\n protected _getString32(idx: number): string {\n return this._getString(idx, 32);\n }\n}\n\n/**\n * @hidden\n */\nclass PrimaryVolumeDescriptor extends PrimaryOrSupplementaryVolumeDescriptor {\n constructor(data: Buffer) {\n super(data);\n if (this.type() !== VolumeDescriptorTypeCode.PrimaryVolumeDescriptor) {\n throw new ApiError(ErrorCode.EIO, `Invalid primary volume descriptor.`);\n }\n }\n public name() {\n return \"ISO9660\";\n }\n protected _constructRootDirectoryRecord(data: Buffer): DirectoryRecord {\n return new ISODirectoryRecord(data, -1);\n }\n protected _getString(idx: number, len: number): string {\n return this._getString(idx, len);\n }\n}\n\n/**\n * @hidden\n */\nclass SupplementaryVolumeDescriptor extends PrimaryOrSupplementaryVolumeDescriptor {\n constructor(data: Buffer) {\n super(data);\n if (this.type() !== VolumeDescriptorTypeCode.SupplementaryVolumeDescriptor) {\n throw new ApiError(ErrorCode.EIO, `Invalid supplementary volume descriptor.`);\n }\n const escapeSequence = this.escapeSequence();\n const third = escapeSequence[2];\n // Third character identifies what 'level' of the UCS specification to follow.\n // We ignore it.\n if (escapeSequence[0] !== 0x25 || escapeSequence[1] !== 0x2F ||\n (third !== 0x40 && third !== 0x43 && third !== 0x45)) {\n throw new ApiError(ErrorCode.EIO, `Unrecognized escape sequence for SupplementaryVolumeDescriptor: ${escapeSequence.toString()}`);\n }\n }\n public name() {\n return \"Joliet\";\n }\n public escapeSequence(): Buffer {\n return this._data.slice(88, 120);\n }\n protected _constructRootDirectoryRecord(data: Buffer): DirectoryRecord {\n return new JolietDirectoryRecord(data, -1);\n }\n protected _getString(idx: number, len: number): string {\n return getJolietString(this._data, idx, len);\n }\n}\n\n/**\n * @hidden\n */\nconst enum FileFlags {\n Hidden = 1,\n Directory = 1 << 1,\n AssociatedFile = 1 << 2,\n EARContainsInfo = 1 << 3,\n EARContainsPerms = 1 << 4,\n FinalDirectoryRecordForFile = 1 << 5\n}\n\n/**\n * @hidden\n */\nabstract class DirectoryRecord {\n protected _data: Buffer;\n // Offset at which system use entries begin. Set to -1 if not enabled.\n protected _rockRidgeOffset: number;\n protected _suEntries: SystemUseEntry[] | null = null;\n private _fileOrDir: Buffer | Directory | null = null;\n constructor(data: Buffer, rockRidgeOffset: number) {\n this._data = data;\n this._rockRidgeOffset = rockRidgeOffset;\n }\n public hasRockRidge(): boolean {\n return this._rockRidgeOffset > -1;\n }\n public getRockRidgeOffset(): number {\n return this._rockRidgeOffset;\n }\n /**\n * !!ONLY VALID ON ROOT NODE!!\n * Checks if Rock Ridge is enabled, and sets the offset.\n */\n public rootCheckForRockRidge(isoData: Buffer): void {\n const dir = this.getDirectory(isoData);\n this._rockRidgeOffset = dir.getDotEntry(isoData)._getRockRidgeOffset(isoData);\n if (this._rockRidgeOffset > -1) {\n // Wipe out directory. Start over with RR knowledge.\n this._fileOrDir = null;\n }\n }\n public length(): number {\n return this._data[0];\n }\n public extendedAttributeRecordLength(): number {\n return this._data[1];\n }\n public lba(): number {\n return this._data.readUInt32LE(2) * 2048;\n }\n public dataLength(): number {\n return this._data.readUInt32LE(10);\n }\n public recordingDate(): Date {\n return getShortFormDate(this._data, 18);\n }\n public fileFlags(): number {\n return this._data[25];\n }\n public fileUnitSize(): number {\n return this._data[26];\n }\n public interleaveGapSize(): number {\n return this._data[27];\n }\n public volumeSequenceNumber(): number {\n return this._data.readUInt16LE(28);\n }\n public identifier(): string {\n return this._getString(33, this._data[32]);\n }\n public fileName(isoData: Buffer): string {\n if (this.hasRockRidge()) {\n const fn = this._rockRidgeFilename(isoData);\n if (fn !== null) {\n return fn;\n }\n }\n const ident = this.identifier();\n if (this.isDirectory(isoData)) {\n return ident;\n }\n // Files:\n // - MUST have 0x2E (.) separating the name from the extension\n // - MUST have 0x3B (;) separating the file name and extension from the version\n // Gets expanded to two-byte char in Unicode directory records.\n const versionSeparator = ident.indexOf(';');\n if (versionSeparator === -1) {\n // Some Joliet filenames lack the version separator, despite the standard\n // specifying that it should be there.\n return ident;\n } else if (ident[versionSeparator - 1] === '.') {\n // Empty extension. Do not include '.' in the filename.\n return ident.slice(0, versionSeparator - 1);\n } else {\n // Include up to version separator.\n return ident.slice(0, versionSeparator);\n }\n }\n public isDirectory(isoData: Buffer): boolean {\n let rv = !!(this.fileFlags() & FileFlags.Directory);\n // If it lacks the Directory flag, it may still be a directory if we've exceeded the directory\n // depth limit. Rock Ridge marks these as files and adds a special attribute.\n if (!rv && this.hasRockRidge()) {\n rv = this.getSUEntries(isoData).filter((e) => e instanceof CLEntry).length > 0;\n }\n return rv;\n }\n public isSymlink(isoData: Buffer): boolean {\n return this.hasRockRidge() && this.getSUEntries(isoData).filter((e) => e instanceof SLEntry).length > 0;\n }\n public getSymlinkPath(isoData: Buffer): string {\n let p = \"\";\n const entries = this.getSUEntries(isoData);\n const getStr = this._getGetString();\n for (const entry of entries) {\n if (entry instanceof SLEntry) {\n const components = entry.componentRecords();\n for (const component of components) {\n const flags = component.flags();\n if (flags & SLComponentFlags.CURRENT) {\n p += \"./\";\n } else if (flags & SLComponentFlags.PARENT) {\n p += \"../\";\n } else if (flags & SLComponentFlags.ROOT) {\n p += \"/\";\n } else {\n p += component.content(getStr);\n if (!(flags & SLComponentFlags.CONTINUE)) {\n p += '/';\n }\n }\n }\n if (!entry.continueFlag()) {\n // We are done with this link.\n break;\n }\n }\n }\n if (p.length > 1 && p[p.length - 1] === '/') {\n // Trim trailing '/'.\n return p.slice(0, p.length - 1);\n } else {\n return p;\n }\n }\n public getFile(isoData: Buffer): Buffer {\n if (this.isDirectory(isoData)) {\n throw new Error(`Tried to get a File from a directory.`);\n }\n if (this._fileOrDir === null) {\n this._fileOrDir = isoData.slice(this.lba(), this.lba() + this.dataLength());\n }\n return this._fileOrDir;\n }\n public getDirectory(isoData: Buffer): Directory {\n if (!this.isDirectory(isoData)) {\n throw new Error(`Tried to get a Directory from a file.`);\n }\n if (this._fileOrDir === null) {\n this._fileOrDir = this._constructDirectory(isoData);\n }\n return > this._fileOrDir;\n }\n public getSUEntries(isoData: Buffer): SystemUseEntry[] {\n if (!this._suEntries) {\n this._constructSUEntries(isoData);\n }\n return this._suEntries!;\n }\n protected abstract _getString(i: number, len: number): string;\n protected abstract _getGetString(): TGetString;\n protected abstract _constructDirectory(isoData: Buffer): Directory;\n protected _rockRidgeFilename(isoData: Buffer): string | null {\n const nmEntries = this.getSUEntries(isoData).filter((e) => e instanceof NMEntry);\n if (nmEntries.length === 0 || nmEntries[0].flags() & (NMFlags.CURRENT | NMFlags.PARENT)) {\n return null;\n }\n let str = '';\n const getString = this._getGetString();\n for (const e of nmEntries) {\n str += e.name(getString);\n if (!(e.flags() & NMFlags.CONTINUE)) {\n break;\n }\n }\n return str;\n }\n private _constructSUEntries(isoData: Buffer): void {\n let i = 33 + this._data[32];\n if (i % 2 === 1) {\n // Skip padding field.\n i++;\n }\n i += this._rockRidgeOffset;\n this._suEntries = constructSystemUseEntries(this._data, i, this.length(), isoData);\n }\n /**\n * !!ONLY VALID ON FIRST ENTRY OF ROOT DIRECTORY!!\n * Returns -1 if rock ridge is not enabled. Otherwise, returns the offset\n * at which system use fields begin.\n */\n private _getRockRidgeOffset(isoData: Buffer): number {\n // In the worst case, we get some garbage SU entries.\n // Fudge offset to 0 before proceeding.\n this._rockRidgeOffset = 0;\n const suEntries = this.getSUEntries(isoData);\n if (suEntries.length > 0) {\n const spEntry = suEntries[0];\n if (spEntry instanceof SPEntry && spEntry.checkBytesPass()) {\n // SUSP is in use.\n for (let i = 1; i < suEntries.length; i++) {\n const entry = suEntries[i];\n if (entry instanceof RREntry || (entry instanceof EREntry && entry.extensionIdentifier() === rockRidgeIdentifier)) {\n // Rock Ridge is in use!\n return spEntry.bytesSkipped();\n }\n }\n }\n }\n // Failed.\n this._rockRidgeOffset = -1;\n return -1;\n }\n}\n\n/**\n * @hidden\n */\nclass ISODirectoryRecord extends DirectoryRecord {\n constructor(data: Buffer, rockRidgeOffset: number) {\n super(data, rockRidgeOffset);\n }\n protected _getString(i: number, len: number): string {\n return getASCIIString(this._data, i, len);\n }\n protected _constructDirectory(isoData: Buffer): Directory {\n return new ISODirectory(this, isoData);\n }\n protected _getGetString(): TGetString {\n return getASCIIString;\n }\n}\n\n/**\n * @hidden\n */\nclass JolietDirectoryRecord extends DirectoryRecord {\n constructor(data: Buffer, rockRidgeOffset: number) {\n super(data, rockRidgeOffset);\n }\n protected _getString(i: number, len: number): string {\n return getJolietString(this._data, i, len);\n }\n protected _constructDirectory(isoData: Buffer): Directory {\n return new JolietDirectory(this, isoData);\n }\n protected _getGetString(): TGetString {\n return getJolietString;\n }\n}\n\n/**\n * @hidden\n */\nconst enum SystemUseEntrySignatures {\n CE = 0x4345,\n PD = 0x5044,\n SP = 0x5350,\n ST = 0x5354,\n ER = 0x4552,\n ES = 0x4553,\n PX = 0x5058,\n PN = 0x504E,\n SL = 0x534C,\n NM = 0x4E4D,\n CL = 0x434C,\n PL = 0x504C,\n RE = 0x5245,\n TF = 0x5446,\n SF = 0x5346,\n RR = 0x5252\n}\n\n/**\n * @hidden\n */\nclass SystemUseEntry {\n protected _data: Buffer;\n constructor(data: Buffer) {\n this._data = data;\n }\n public signatureWord(): SystemUseEntrySignatures {\n return this._data.readUInt16BE(0);\n }\n public signatureWordString(): string {\n return getASCIIString(this._data, 0, 2);\n }\n public length(): number {\n return this._data[2];\n }\n public suVersion(): number {\n return this._data[3];\n }\n}\n\n/**\n * Continuation entry.\n * @hidden\n */\nclass CEEntry extends SystemUseEntry {\n private _entries: SystemUseEntry[] | null = null;\n constructor(data: Buffer) {\n super(data);\n }\n /**\n * Logical block address of the continuation area.\n */\n public continuationLba(): number {\n return this._data.readUInt32LE(4);\n }\n /**\n * Offset into the logical block.\n */\n public continuationLbaOffset(): number {\n return this._data.readUInt32LE(12);\n }\n /**\n * Length of the continuation area.\n */\n public continuationLength(): number {\n return this._data.readUInt32LE(20);\n }\n public getEntries(isoData: Buffer): SystemUseEntry[] {\n if (!this._entries) {\n const start = this.continuationLba() * 2048 + this.continuationLbaOffset();\n this._entries = constructSystemUseEntries(isoData, start, this.continuationLength(), isoData);\n }\n return this._entries;\n }\n}\n\n/**\n * Padding entry.\n * @hidden\n */\nclass PDEntry extends SystemUseEntry {\n constructor(data: Buffer) {\n super(data);\n }\n}\n\n/**\n * Identifies that SUSP is in-use.\n * @hidden\n */\nclass SPEntry extends SystemUseEntry {\n constructor(data: Buffer) {\n super(data);\n }\n public checkBytesPass(): boolean {\n return this._data[4] === 0xBE && this._data[5] === 0xEF;\n }\n public bytesSkipped(): number {\n return this._data[6];\n }\n}\n\n/**\n * Identifies the end of the SUSP entries.\n * @hidden\n */\nclass STEntry extends SystemUseEntry {\n constructor(data: Buffer) {\n super(data);\n }\n}\n\n/**\n * Specifies system-specific extensions to SUSP.\n * @hidden\n */\nclass EREntry extends SystemUseEntry {\n constructor(data: Buffer) {\n super(data);\n }\n public identifierLength(): number {\n return this._data[4];\n }\n public descriptorLength(): number {\n return this._data[5];\n }\n public sourceLength(): number {\n return this._data[6];\n }\n public extensionVersion(): number {\n return this._data[7];\n }\n public extensionIdentifier(): string {\n return getASCIIString(this._data, 8, this.identifierLength());\n }\n public extensionDescriptor(): string {\n return getASCIIString(this._data, 8 + this.identifierLength(), this.descriptorLength());\n }\n public extensionSource(): string {\n return getASCIIString(this._data, 8 + this.identifierLength() + this.descriptorLength(), this.sourceLength());\n }\n}\n\n/**\n * @hidden\n */\nclass ESEntry extends SystemUseEntry {\n constructor(data: Buffer) {\n super(data);\n }\n public extensionSequence(): number {\n return this._data[4];\n }\n}\n\n/**\n * RockRidge: Marks that RockRidge is in use [deprecated]\n * @hidden\n */\nclass RREntry extends SystemUseEntry {\n constructor(data: Buffer) {\n super(data);\n }\n}\n\n/**\n * RockRidge: Records POSIX file attributes.\n * @hidden\n */\nclass PXEntry extends SystemUseEntry {\n constructor(data: Buffer) {\n super(data);\n }\n public mode(): number {\n return this._data.readUInt32LE(4);\n }\n public fileLinks(): number {\n return this._data.readUInt32LE(12);\n }\n public uid(): number {\n return this._data.readUInt32LE(20);\n }\n public gid(): number {\n return this._data.readUInt32LE(28);\n }\n public inode(): number {\n return this._data.readUInt32LE(36);\n }\n}\n\n/**\n * RockRidge: Records POSIX device number.\n * @hidden\n */\nclass PNEntry extends SystemUseEntry {\n constructor(data: Buffer) {\n super(data);\n }\n public devTHigh(): number {\n return this._data.readUInt32LE(4);\n }\n public devTLow(): number {\n return this._data.readUInt32LE(12);\n }\n}\n\n/**\n * RockRidge: Records symbolic link\n * @hidden\n */\nclass SLEntry extends SystemUseEntry {\n constructor(data: Buffer) {\n super(data);\n }\n public flags(): number {\n return this._data[4];\n }\n public continueFlag(): number {\n return this.flags() & 0x1;\n }\n public componentRecords(): SLComponentRecord[] {\n const records = new Array();\n let i = 5;\n while (i < this.length()) {\n const record = new SLComponentRecord(this._data.slice(i));\n records.push(record);\n i += record.length();\n }\n return records;\n }\n}\n\n/**\n * @hidden\n */\nconst enum SLComponentFlags {\n CONTINUE = 1,\n CURRENT = 1 << 1,\n PARENT = 1 << 2,\n ROOT = 1 << 3\n}\n\n/**\n * @hidden\n */\nclass SLComponentRecord {\n private _data: Buffer;\n constructor(data: Buffer) {\n this._data = data;\n }\n public flags(): SLComponentFlags {\n return this._data[0];\n }\n public length(): number {\n return 2 + this.componentLength();\n }\n public componentLength(): number {\n return this._data[1];\n }\n public content(getString: TGetString): string {\n return getString(this._data, 2, this.componentLength());\n }\n}\n\n/**\n * @hidden\n */\nconst enum NMFlags {\n CONTINUE = 1,\n CURRENT = 1 << 1,\n PARENT = 1 << 2\n}\n\n/**\n * RockRidge: Records alternate file name\n * @hidden\n */\nclass NMEntry extends SystemUseEntry {\n constructor(data: Buffer) {\n super(data);\n }\n public flags(): NMFlags {\n return this._data[4];\n }\n public name(getString: TGetString): string {\n return getString(this._data, 5, this.length() - 5);\n }\n}\n\n/**\n * RockRidge: Records child link\n * @hidden\n */\nclass CLEntry extends SystemUseEntry {\n constructor(data: Buffer) {\n super(data);\n }\n public childDirectoryLba(): number {\n return this._data.readUInt32LE(4);\n }\n}\n\n/**\n * RockRidge: Records parent link.\n * @hidden\n */\nclass PLEntry extends SystemUseEntry {\n constructor(data: Buffer) {\n super(data);\n }\n public parentDirectoryLba(): number {\n return this._data.readUInt32LE(4);\n }\n}\n\n/**\n * RockRidge: Records relocated directory.\n * @hidden\n */\nclass REEntry extends SystemUseEntry {\n constructor(data: Buffer) {\n super(data);\n }\n}\n\n/**\n * @hidden\n */\nconst enum TFFlags {\n CREATION = 1,\n MODIFY = 1 << 1,\n ACCESS = 1 << 2,\n ATTRIBUTES = 1 << 3,\n BACKUP = 1 << 4,\n EXPIRATION = 1 << 5,\n EFFECTIVE = 1 << 6,\n LONG_FORM = 1 << 7\n}\n\n/**\n * RockRidge: Records file timestamps\n * @hidden\n */\nclass TFEntry extends SystemUseEntry {\n constructor(data: Buffer) {\n super(data);\n }\n public flags(): number {\n return this._data[4];\n }\n public creation(): Date | null {\n if (this.flags() & TFFlags.CREATION) {\n if (this._longFormDates()) {\n return getDate(this._data, 5);\n } else {\n return getShortFormDate(this._data, 5);\n }\n } else {\n return null;\n }\n }\n public modify(): Date | null {\n if (this.flags() & TFFlags.MODIFY) {\n const previousDates = (this.flags() & TFFlags.CREATION) ? 1 : 0;\n if (this._longFormDates) {\n return getDate(this._data, 5 + (previousDates * 17));\n } else {\n return getShortFormDate(this._data, 5 + (previousDates * 7));\n }\n } else {\n return null;\n }\n }\n public access(): Date | null {\n if (this.flags() & TFFlags.ACCESS) {\n let previousDates = (this.flags() & TFFlags.CREATION) ? 1 : 0;\n previousDates += (this.flags() & TFFlags.MODIFY) ? 1 : 0;\n if (this._longFormDates) {\n return getDate(this._data, 5 + (previousDates * 17));\n } else {\n return getShortFormDate(this._data, 5 + (previousDates * 7));\n }\n } else {\n return null;\n }\n }\n public backup(): Date | null {\n if (this.flags() & TFFlags.BACKUP) {\n let previousDates = (this.flags() & TFFlags.CREATION) ? 1 : 0;\n previousDates += (this.flags() & TFFlags.MODIFY) ? 1 : 0;\n previousDates += (this.flags() & TFFlags.ACCESS) ? 1 : 0;\n if (this._longFormDates) {\n return getDate(this._data, 5 + (previousDates * 17));\n } else {\n return getShortFormDate(this._data, 5 + (previousDates * 7));\n }\n } else {\n return null;\n }\n }\n public expiration(): Date | null {\n if (this.flags() & TFFlags.EXPIRATION) {\n let previousDates = (this.flags() & TFFlags.CREATION) ? 1 : 0;\n previousDates += (this.flags() & TFFlags.MODIFY) ? 1 : 0;\n previousDates += (this.flags() & TFFlags.ACCESS) ? 1 : 0;\n previousDates += (this.flags() & TFFlags.BACKUP) ? 1 : 0;\n if (this._longFormDates) {\n return getDate(this._data, 5 + (previousDates * 17));\n } else {\n return getShortFormDate(this._data, 5 + (previousDates * 7));\n }\n } else {\n return null;\n }\n }\n public effective(): Date | null {\n if (this.flags() & TFFlags.EFFECTIVE) {\n let previousDates = (this.flags() & TFFlags.CREATION) ? 1 : 0;\n previousDates += (this.flags() & TFFlags.MODIFY) ? 1 : 0;\n previousDates += (this.flags() & TFFlags.ACCESS) ? 1 : 0;\n previousDates += (this.flags() & TFFlags.BACKUP) ? 1 : 0;\n previousDates += (this.flags() & TFFlags.EXPIRATION) ? 1 : 0;\n if (this._longFormDates) {\n return getDate(this._data, 5 + (previousDates * 17));\n } else {\n return getShortFormDate(this._data, 5 + (previousDates * 7));\n }\n } else {\n return null;\n }\n }\n private _longFormDates(): boolean {\n return !!(this.flags() && TFFlags.LONG_FORM);\n }\n}\n\n/**\n * RockRidge: File data in sparse format.\n * @hidden\n */\nclass SFEntry extends SystemUseEntry {\n constructor(data: Buffer) {\n super(data);\n }\n public virtualSizeHigh(): number {\n return this._data.readUInt32LE(4);\n }\n public virtualSizeLow(): number {\n return this._data.readUInt32LE(12);\n }\n public tableDepth(): number {\n return this._data[20];\n }\n}\n\n/**\n * @hidden\n */\nabstract class Directory {\n protected _record: T;\n private _fileList: string[] = [];\n private _fileMap: {[name: string]: T} = {};\n constructor(record: T, isoData: Buffer) {\n this._record = record;\n let i = record.lba();\n let iLimit = i + record.dataLength();\n if (!(record.fileFlags() & FileFlags.Directory)) {\n // Must have a CL entry.\n const cl = record.getSUEntries(isoData).filter((e) => e instanceof CLEntry)[0];\n i = cl.childDirectoryLba() * 2048;\n iLimit = Infinity;\n }\n\n while (i < iLimit) {\n const len = isoData[i];\n // Zero-padding between sectors.\n // TODO: Could optimize this to seek to nearest-sector upon\n // seeing a 0.\n if (len === 0) {\n i++;\n continue;\n }\n const r = this._constructDirectoryRecord(isoData.slice(i));\n const fname = r.fileName(isoData);\n // Skip '.' and '..' entries.\n if (fname !== '\\u0000' && fname !== '\\u0001') {\n // Skip relocated entries.\n if (!r.hasRockRidge() || r.getSUEntries(isoData).filter((e) => e instanceof REEntry).length === 0) {\n this._fileMap[fname] = r;\n this._fileList.push(fname);\n }\n } else if (iLimit === Infinity) {\n // First entry contains needed data.\n iLimit = i + r.dataLength();\n }\n i += r.length();\n }\n }\n /**\n * Get the record with the given name.\n * Returns undefined if not present.\n */\n public getRecord(name: string): DirectoryRecord {\n return this._fileMap[name];\n }\n public getFileList(): string[] {\n return this._fileList;\n }\n public getDotEntry(isoData: Buffer): T {\n return this._constructDirectoryRecord(isoData.slice(this._record.lba()));\n }\n protected abstract _constructDirectoryRecord(data: Buffer): T;\n}\n\n/**\n * @hidden\n */\nclass ISODirectory extends Directory {\n constructor(record: ISODirectoryRecord, isoData: Buffer) {\n super(record, isoData);\n }\n protected _constructDirectoryRecord(data: Buffer): ISODirectoryRecord {\n return new ISODirectoryRecord(data, this._record.getRockRidgeOffset());\n }\n}\n\n/**\n * @hidden\n */\nclass JolietDirectory extends Directory {\n constructor(record: JolietDirectoryRecord, isoData: Buffer) {\n super(record, isoData);\n }\n protected _constructDirectoryRecord(data: Buffer): JolietDirectoryRecord {\n return new JolietDirectoryRecord(data, this._record.getRockRidgeOffset());\n }\n}\n\n/**\n * Options for IsoFS file system instances.\n */\nexport interface IsoFSOptions {\n // The ISO file in a buffer.\n data: Buffer;\n // The name of the ISO (optional; used for debug messages / identification via getName()).\n name?: string;\n}\n\n/**\n * Mounts an ISO file as a read-only file system.\n *\n * Supports:\n * * Vanilla ISO9660 ISOs\n * * Microsoft Joliet and Rock Ridge extensions to the ISO9660 standard\n */\nexport default class IsoFS extends SynchronousFileSystem implements FileSystem {\n public static readonly Name = \"IsoFS\";\n\n public static readonly Options: FileSystemOptions = {\n data: {\n type: \"object\",\n description: \"The ISO file in a buffer\",\n validator: bufferValidator\n }\n };\n\n /**\n * Creates an IsoFS instance with the given options.\n */\n public static Create(opts: IsoFSOptions, cb: BFSCallback): void {\n let fs: IsoFS | undefined;\n let e: ApiError | undefined;\n try {\n fs = new IsoFS(opts.data, opts.name, false);\n } catch (e) {\n e = e;\n } finally {\n cb(e, fs);\n }\n }\n public static isAvailable(): boolean {\n return true;\n }\n\n private _data: Buffer;\n private _pvd: PrimaryOrSupplementaryVolumeDescriptor;\n private _root: DirectoryRecord;\n private _name: string;\n\n /**\n * **Deprecated. Please use IsoFS.Create() method instead.**\n *\n * Constructs a read-only file system from the given ISO.\n * @param data The ISO file in a buffer.\n * @param name The name of the ISO (optional; used for debug messages / identification via getName()).\n */\n constructor(data: Buffer, name: string = \"\", deprecateMsg = true) {\n super();\n this._data = data;\n deprecationMessage(deprecateMsg, IsoFS.Name, {data: \"ISO data as a Buffer\", name: name});\n // Skip first 16 sectors.\n let vdTerminatorFound = false;\n let i = 16 * 2048;\n const candidateVDs = new Array();\n while (!vdTerminatorFound) {\n const slice = data.slice(i);\n const vd = new VolumeDescriptor(slice);\n switch (vd.type()) {\n case VolumeDescriptorTypeCode.PrimaryVolumeDescriptor:\n candidateVDs.push(new PrimaryVolumeDescriptor(slice));\n break;\n case VolumeDescriptorTypeCode.SupplementaryVolumeDescriptor:\n candidateVDs.push(new SupplementaryVolumeDescriptor(slice));\n break;\n case VolumeDescriptorTypeCode.VolumeDescriptorSetTerminator:\n vdTerminatorFound = true;\n break;\n }\n i += 2048;\n }\n if (candidateVDs.length === 0) {\n throw new ApiError(ErrorCode.EIO, `Unable to find a suitable volume descriptor.`);\n }\n candidateVDs.forEach((v) => {\n // Take an SVD over a PVD.\n if (!this._pvd || this._pvd.type() !== VolumeDescriptorTypeCode.SupplementaryVolumeDescriptor) {\n this._pvd = v;\n }\n });\n this._root = this._pvd.rootDirectoryEntry(data);\n this._name = name;\n }\n\n public getName(): string {\n let name = `IsoFS${this._name}${this._pvd ? `-${this._pvd.name()}` : ''}`;\n if (this._root && this._root.hasRockRidge()) {\n name += `-RockRidge`;\n }\n return name;\n }\n\n public diskSpace(path: string, cb: (total: number, free: number) => void): void {\n // Read-only file system.\n cb(this._data.length, 0);\n }\n\n public isReadOnly(): boolean {\n return true;\n }\n\n public supportsLinks(): boolean {\n return false;\n }\n\n public supportsProps(): boolean {\n return false;\n }\n\n public supportsSynch(): boolean {\n return true;\n }\n\n public statSync(p: string, isLstat: boolean): Stats {\n const record = this._getDirectoryRecord(p);\n if (record === null) {\n throw ApiError.ENOENT(p);\n }\n return this._getStats(p, record)!;\n }\n\n public openSync(p: string, flags: FileFlag, mode: number): File {\n // INVARIANT: Cannot write to RO file systems.\n if (flags.isWriteable()) {\n throw new ApiError(ErrorCode.EPERM, p);\n }\n // Check if the path exists, and is a file.\n const record = this._getDirectoryRecord(p);\n if (!record) {\n throw ApiError.ENOENT(p);\n } else if (record.isSymlink(this._data)) {\n return this.openSync(path.resolve(p, record.getSymlinkPath(this._data)), flags, mode);\n } else if (!record.isDirectory(this._data)) {\n const data = record.getFile(this._data);\n const stats = this._getStats(p, record)!;\n switch (flags.pathExistsAction()) {\n case ActionType.THROW_EXCEPTION:\n case ActionType.TRUNCATE_FILE:\n throw ApiError.EEXIST(p);\n case ActionType.NOP:\n return new NoSyncFile(this, p, flags, stats, data);\n default:\n throw new ApiError(ErrorCode.EINVAL, 'Invalid FileMode object.');\n }\n } else {\n throw ApiError.EISDIR(p);\n }\n }\n\n public readdirSync(path: string): string[] {\n // Check if it exists.\n const record = this._getDirectoryRecord(path);\n if (!record) {\n throw ApiError.ENOENT(path);\n } else if (record.isDirectory(this._data)) {\n return record.getDirectory(this._data).getFileList().slice(0);\n } else {\n throw ApiError.ENOTDIR(path);\n }\n }\n\n /**\n * Specially-optimized readfile.\n */\n public readFileSync(fname: string, encoding: string, flag: FileFlag): any {\n // Get file.\n const fd = this.openSync(fname, flag, 0x1a4);\n try {\n const fdCast = > fd;\n const fdBuff = fdCast.getBuffer();\n if (encoding === null) {\n return copyingSlice(fdBuff);\n }\n return fdBuff.toString(encoding);\n } finally {\n fd.closeSync();\n }\n }\n\n private _getDirectoryRecord(path: string): DirectoryRecord | null {\n // Special case.\n if (path === '/') {\n return this._root;\n }\n const components = path.split('/').slice(1);\n let dir = this._root;\n for (const component of components) {\n if (dir.isDirectory(this._data)) {\n dir = dir.getDirectory(this._data).getRecord(component);\n if (!dir) {\n return null;\n }\n } else {\n return null;\n }\n }\n return dir;\n }\n\n private _getStats(p: string, record: DirectoryRecord): Stats | null {\n if (record.isSymlink(this._data)) {\n const newP = path.resolve(p, record.getSymlinkPath(this._data));\n const dirRec = this._getDirectoryRecord(newP);\n if (!dirRec) {\n return null;\n }\n return this._getStats(newP, dirRec);\n } else {\n const len = record.dataLength();\n let mode = 0x16D;\n const date = record.recordingDate();\n let atime = date;\n let mtime = date;\n let ctime = date;\n if (record.hasRockRidge()) {\n const entries = record.getSUEntries(this._data);\n for (const entry of entries) {\n if (entry instanceof PXEntry) {\n mode = entry.mode();\n } else if (entry instanceof TFEntry) {\n const flags = entry.flags();\n if (flags & TFFlags.ACCESS) {\n atime = entry.access()!;\n }\n if (flags & TFFlags.MODIFY) {\n mtime = entry.modify()!;\n }\n if (flags & TFFlags.CREATION) {\n ctime = entry.creation()!;\n }\n }\n }\n }\n // Mask out writeable flags. This is a RO file system.\n mode = mode & 0x16D;\n return new Stats(record.isDirectory(this._data) ? FileType.DIRECTORY : FileType.FILE, len, mode, atime, mtime, ctime);\n }\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ../../../../src/backend/IsoFS.ts","/**\n * BrowserFS's main module. This is exposed in the browser via the BrowserFS global.\n * Due to limitations in typedoc, we document these functions in ./typedoc.ts.\n */\n\nimport * as buffer from 'buffer';\nimport fs from './node_fs';\nimport * as path from 'path';\nimport {FileSystemConstructor, FileSystem, BFSOneArgCallback, BFSCallback} from './file_system';\nimport EmscriptenFS from '../generic/emscripten_fs';\nimport Backends from './backends';\nimport * as BFSUtils from './util';\nimport * as Errors from './api_error';\nimport setImmediate from '../generic/setImmediate';\n\nif (( process)['initializeTTYs']) {\n ( process)['initializeTTYs']();\n}\n\n/**\n * Installs BFSRequire as global `require`, a Node Buffer polyfill as the global `Buffer` variable,\n * and a Node process polyfill as the global `process` variable.\n */\nexport function install(obj: any) {\n obj.Buffer = Buffer;\n obj.process = process;\n const oldRequire = obj.require ? obj.require : null;\n // Monkey-patch require for Node-style code.\n obj.require = function(arg: string) {\n const rv = BFSRequire(arg);\n if (!rv) {\n return oldRequire.apply(null, Array.prototype.slice.call(arguments, 0));\n } else {\n return rv;\n }\n };\n}\n\n/**\n * @hidden\n */\nexport function registerFileSystem(name: string, fs: FileSystemConstructor) {\n ( Backends)[name] = fs;\n}\n\n/**\n * Polyfill for CommonJS `require()`. For example, can call `BFSRequire('fs')` to get a 'fs' module polyfill.\n */\nexport function BFSRequire(module: 'fs'): typeof fs;\nexport function BFSRequire(module: 'path'): typeof path;\nexport function BFSRequire(module: 'buffer'): typeof buffer;\nexport function BFSRequire(module: 'process'): typeof process;\nexport function BFSRequire(module: 'bfs_utils'): typeof BFSUtils;\nexport function BFSRequire(module: string): any;\nexport function BFSRequire(module: string): any {\n switch (module) {\n case 'fs':\n return fs;\n case 'path':\n return path;\n case 'buffer':\n // The 'buffer' module has 'Buffer' as a property.\n return buffer;\n case 'process':\n return process;\n case 'bfs_utils':\n return BFSUtils;\n default:\n return ( Backends)[module];\n }\n}\n\n/**\n * Initializes BrowserFS with the given root file system.\n */\nexport function initialize(rootfs: FileSystem) {\n return fs.initialize(rootfs);\n}\n\n/**\n * Creates a file system with the given configuration, and initializes BrowserFS with it.\n * See the FileSystemConfiguration type for more info on the configuration object.\n */\nexport function configure(config: FileSystemConfiguration, cb: BFSOneArgCallback): void {\n getFileSystem(config, (e, fs?) => {\n if (fs) {\n initialize(fs);\n cb();\n } else {\n cb(e);\n }\n });\n}\n\n/**\n * Specifies a file system backend type and its options.\n *\n * Individual options can recursively contain FileSystemConfiguration objects for\n * option values that require file systems.\n *\n * For example, to mirror Dropbox to LocalStorage with AsyncMirror, use the following\n * object:\n *\n * ```javascript\n * var config = {\n * fs: \"AsyncMirror\",\n * options: {\n * sync: {fs: \"LocalStorage\"},\n * async: {fs: \"Dropbox\", options: {client: anAuthenticatedDropboxSDKClient }}\n * }\n * };\n * ```\n *\n * The option object for each file system corresponds to that file system's option object passed to its `Create()` method.\n */\nexport interface FileSystemConfiguration {\n fs: string;\n options: any;\n}\n\n/**\n * Retrieve a file system with the given configuration.\n * @param config A FileSystemConfiguration object. See FileSystemConfiguration for details.\n * @param cb Called when the file system is constructed, or when an error occurs.\n */\nexport function getFileSystem(config: FileSystemConfiguration, cb: BFSCallback): void {\n const fsName = config['fs'];\n if (!fsName) {\n return cb(new Errors.ApiError(Errors.ErrorCode.EPERM, 'Missing \"fs\" property on configuration object.'));\n }\n const options = config['options'];\n let waitCount = 0;\n let called = false;\n function finish() {\n if (!called) {\n called = true;\n const fsc = ( Backends)[fsName];\n if (!fsc) {\n cb(new Errors.ApiError(Errors.ErrorCode.EPERM, `File system ${fsName} is not available in BrowserFS.`));\n } else {\n fsc.Create(options, cb);\n }\n }\n }\n\n if (options !== null && typeof(options) === \"object\") {\n let finishedIterating = false;\n const props = Object.keys(options).filter((k) => k !== 'fs');\n\n // Check recursively if other fields have 'fs' properties.\n props.forEach((p) => {\n const d = options[p];\n if (d !== null && typeof(d) === \"object\" && d['fs']) {\n waitCount++;\n getFileSystem(d, function(e, fs?) {\n waitCount--;\n if (e) {\n if (called) {\n return;\n }\n called = true;\n cb(e);\n } else {\n options[p] = fs;\n if (waitCount === 0 && finishedIterating) {\n finish();\n }\n }\n });\n }\n });\n finishedIterating = true;\n }\n if (waitCount === 0) {\n finish();\n }\n}\n\nexport {EmscriptenFS, Backends as FileSystem, Errors, setImmediate};\n\n\n\n// WEBPACK FOOTER //\n// ../../../../src/core/browserfs.ts","/**\n * Standard libc error codes. Add more to this enum and ErrorStrings as they are\n * needed.\n * @url http://www.gnu.org/software/libc/manual/html_node/Error-Codes.html\n */\nexport enum ErrorCode {\n EPERM = 1,\n ENOENT = 2,\n EIO = 5,\n EBADF = 9,\n EACCES = 13,\n EBUSY = 16,\n EEXIST = 17,\n ENOTDIR = 20,\n EISDIR = 21,\n EINVAL = 22,\n EFBIG = 27,\n ENOSPC = 28,\n EROFS = 30,\n ENOTEMPTY = 39,\n ENOTSUP = 95,\n}\n/* tslint:disable:variable-name */\n/**\n * Strings associated with each error code.\n * @hidden\n */\nexport const ErrorStrings: {[code: string]: string; [code: number]: string; } = {};\nErrorStrings[ErrorCode.EPERM] = 'Operation not permitted.';\nErrorStrings[ErrorCode.ENOENT] = 'No such file or directory.';\nErrorStrings[ErrorCode.EIO] = 'Input/output error.';\nErrorStrings[ErrorCode.EBADF] = 'Bad file descriptor.';\nErrorStrings[ErrorCode.EACCES] = 'Permission denied.';\nErrorStrings[ErrorCode.EBUSY] = 'Resource busy or locked.';\nErrorStrings[ErrorCode.EEXIST] = 'File exists.';\nErrorStrings[ErrorCode.ENOTDIR] = 'File is not a directory.';\nErrorStrings[ErrorCode.EISDIR] = 'File is a directory.';\nErrorStrings[ErrorCode.EINVAL] = 'Invalid argument.';\nErrorStrings[ErrorCode.EFBIG] = 'File is too big.';\nErrorStrings[ErrorCode.ENOSPC] = 'No space left on disk.';\nErrorStrings[ErrorCode.EROFS] = 'Cannot modify a read-only file system.';\nErrorStrings[ErrorCode.ENOTEMPTY] = 'Directory is not empty.';\nErrorStrings[ErrorCode.ENOTSUP] = 'Operation is not supported.';\n/* tslint:enable:variable-name */\n\n/**\n * Represents a BrowserFS error. Passed back to applications after a failed\n * call to the BrowserFS API.\n */\nexport class ApiError extends Error implements NodeJS.ErrnoException {\n public static fromJSON(json: any): ApiError {\n const err = new ApiError(0);\n err.errno = json.errno;\n err.code = json.code;\n err.path = json.path;\n err.stack = json.stack;\n err.message = json.message;\n return err;\n }\n\n /**\n * Creates an ApiError object from a buffer.\n */\n public static fromBuffer(buffer: Buffer, i: number = 0): ApiError {\n return ApiError.fromJSON(JSON.parse(buffer.toString('utf8', i + 4, i + 4 + buffer.readUInt32LE(i))));\n }\n\n public static FileError(code: ErrorCode, p: string): ApiError {\n return new ApiError(code, ErrorStrings[code], p);\n }\n public static ENOENT(path: string): ApiError {\n return this.FileError(ErrorCode.ENOENT, path);\n }\n\n public static EEXIST(path: string): ApiError {\n return this.FileError(ErrorCode.EEXIST, path);\n }\n\n public static EISDIR(path: string): ApiError {\n return this.FileError(ErrorCode.EISDIR, path);\n }\n\n public static ENOTDIR(path: string): ApiError {\n return this.FileError(ErrorCode.ENOTDIR, path);\n }\n\n public static EPERM(path: string): ApiError {\n return this.FileError(ErrorCode.EPERM, path);\n }\n\n public static ENOTEMPTY(path: string): ApiError {\n return this.FileError(ErrorCode.ENOTEMPTY, path);\n }\n\n public errno: ErrorCode;\n public code: string;\n public path: string | undefined;\n // Unsupported.\n public syscall: string = \"\";\n public stack: string | undefined;\n\n /**\n * Represents a BrowserFS error. Passed back to applications after a failed\n * call to the BrowserFS API.\n *\n * Error codes mirror those returned by regular Unix file operations, which is\n * what Node returns.\n * @constructor ApiError\n * @param type The type of the error.\n * @param [message] A descriptive error message.\n */\n constructor(type: ErrorCode, message: string = ErrorStrings[type], path?: string) {\n super(message);\n this.errno = type;\n this.code = ErrorCode[type];\n this.path = path;\n this.stack = new Error().stack;\n this.message = `Error: ${this.code}: ${message}${this.path ? `, '${this.path}'` : ''}`;\n }\n\n /**\n * @return A friendly error message.\n */\n public toString(): string {\n return this.message;\n }\n\n public toJSON(): any {\n return {\n errno: this.errno,\n code: this.code,\n path: this.path,\n stack: this.stack,\n message: this.message\n };\n }\n\n /**\n * Writes the API error into a buffer.\n */\n public writeToBuffer(buffer: Buffer = Buffer.alloc(this.bufferSize()), i: number = 0): Buffer {\n const bytesWritten = buffer.write(JSON.stringify(this.toJSON()), i + 4);\n buffer.writeUInt32LE(bytesWritten, i);\n return buffer;\n }\n\n /**\n * The size of the API error in buffer-form in bytes.\n */\n public bufferSize(): number {\n // 4 bytes for string length.\n return 4 + Buffer.byteLength(JSON.stringify(this.toJSON()));\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ../../../../src/core/api_error.ts","import {ErrorCode, ApiError} from './api_error';\n\nexport enum ActionType {\n // Indicates that the code should not do anything.\n NOP = 0,\n // Indicates that the code should throw an exception.\n THROW_EXCEPTION = 1,\n // Indicates that the code should truncate the file, but only if it is a file.\n TRUNCATE_FILE = 2,\n // Indicates that the code should create the file.\n CREATE_FILE = 3\n}\n\n/**\n * Represents one of the following file flags. A convenience object.\n *\n * * `'r'` - Open file for reading. An exception occurs if the file does not exist.\n * * `'r+'` - Open file for reading and writing. An exception occurs if the file does not exist.\n * * `'rs'` - Open file for reading in synchronous mode. Instructs the filesystem to not cache writes.\n * * `'rs+'` - Open file for reading and writing, and opens the file in synchronous mode.\n * * `'w'` - Open file for writing. The file is created (if it does not exist) or truncated (if it exists).\n * * `'wx'` - Like 'w' but opens the file in exclusive mode.\n * * `'w+'` - Open file for reading and writing. The file is created (if it does not exist) or truncated (if it exists).\n * * `'wx+'` - Like 'w+' but opens the file in exclusive mode.\n * * `'a'` - Open file for appending. The file is created if it does not exist.\n * * `'ax'` - Like 'a' but opens the file in exclusive mode.\n * * `'a+'` - Open file for reading and appending. The file is created if it does not exist.\n * * `'ax+'` - Like 'a+' but opens the file in exclusive mode.\n *\n * Exclusive mode ensures that the file path is newly created.\n */\nexport class FileFlag {\n // Contains cached FileMode instances.\n private static flagCache: { [mode: string]: FileFlag } = {};\n // Array of valid mode strings.\n private static validFlagStrs = ['r', 'r+', 'rs', 'rs+', 'w', 'wx', 'w+', 'wx+', 'a', 'ax', 'a+', 'ax+'];\n\n /**\n * Get an object representing the given file flag.\n * @param modeStr The string representing the flag\n * @return The FileFlag object representing the flag\n * @throw when the flag string is invalid\n */\n public static getFileFlag(flagStr: string): FileFlag {\n // Check cache first.\n if (FileFlag.flagCache.hasOwnProperty(flagStr)) {\n return FileFlag.flagCache[flagStr];\n }\n return FileFlag.flagCache[flagStr] = new FileFlag(flagStr);\n }\n\n private flagStr: string;\n /**\n * This should never be called directly.\n * @param modeStr The string representing the mode\n * @throw when the mode string is invalid\n */\n constructor(flagStr: string) {\n this.flagStr = flagStr;\n if (FileFlag.validFlagStrs.indexOf(flagStr) < 0) {\n throw new ApiError(ErrorCode.EINVAL, \"Invalid flag: \" + flagStr);\n }\n }\n\n /**\n * Get the underlying flag string for this flag.\n */\n public getFlagString(): string {\n return this.flagStr;\n }\n\n /**\n * Returns true if the file is readable.\n */\n public isReadable(): boolean {\n return this.flagStr.indexOf('r') !== -1 || this.flagStr.indexOf('+') !== -1;\n }\n /**\n * Returns true if the file is writeable.\n */\n public isWriteable(): boolean {\n return this.flagStr.indexOf('w') !== -1 || this.flagStr.indexOf('a') !== -1 || this.flagStr.indexOf('+') !== -1;\n }\n /**\n * Returns true if the file mode should truncate.\n */\n public isTruncating(): boolean {\n return this.flagStr.indexOf('w') !== -1;\n }\n /**\n * Returns true if the file is appendable.\n */\n public isAppendable(): boolean {\n return this.flagStr.indexOf('a') !== -1;\n }\n /**\n * Returns true if the file is open in synchronous mode.\n */\n public isSynchronous(): boolean {\n return this.flagStr.indexOf('s') !== -1;\n }\n /**\n * Returns true if the file is open in exclusive mode.\n */\n public isExclusive(): boolean {\n return this.flagStr.indexOf('x') !== -1;\n }\n /**\n * Returns one of the static fields on this object that indicates the\n * appropriate response to the path existing.\n */\n public pathExistsAction(): ActionType {\n if (this.isExclusive()) {\n return ActionType.THROW_EXCEPTION;\n } else if (this.isTruncating()) {\n return ActionType.TRUNCATE_FILE;\n } else {\n return ActionType.NOP;\n }\n }\n /**\n * Returns one of the static fields on this object that indicates the\n * appropriate response to the path not existing.\n */\n public pathNotExistsAction(): ActionType {\n if ((this.isWriteable() || this.isAppendable()) && this.flagStr !== 'r+') {\n return ActionType.CREATE_FILE;\n } else {\n return ActionType.THROW_EXCEPTION;\n }\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ../../../../src/core/file_flag.ts","import * as fs from 'fs';\n\n/**\n * Indicates the type of the given file. Applied to 'mode'.\n */\nexport enum FileType {\n FILE = 0x8000,\n DIRECTORY = 0x4000,\n SYMLINK = 0xA000\n}\n\n/**\n * Emulation of Node's `fs.Stats` object.\n *\n * Attribute descriptions are from `man 2 stat'\n * @see http://nodejs.org/api/fs.html#fs_class_fs_stats\n * @see http://man7.org/linux/man-pages/man2/stat.2.html\n */\nexport default class Stats implements fs.Stats {\n public static fromBuffer(buffer: Buffer): Stats {\n const size = buffer.readUInt32LE(0),\n mode = buffer.readUInt32LE(4),\n atime = buffer.readDoubleLE(8),\n mtime = buffer.readDoubleLE(16),\n ctime = buffer.readDoubleLE(24);\n\n return new Stats(mode & 0xF000, size, mode & 0xFFF, new Date(atime), new Date(mtime), new Date(ctime));\n }\n\n public blocks: number;\n public mode: number;\n /**\n * UNSUPPORTED ATTRIBUTES\n * I assume no one is going to need these details, although we could fake\n * appropriate values if need be.\n */\n // ID of device containing file\n public dev: number = 0;\n // inode number\n public ino: number = 0;\n // device ID (if special file)\n public rdev: number = 0;\n // number of hard links\n public nlink: number = 1;\n // blocksize for file system I/O\n public blksize: number = 4096;\n // @todo Maybe support these? atm, it's a one-user filesystem.\n // user ID of owner\n public uid: number = 0;\n // group ID of owner\n public gid: number = 0;\n // time file was created (currently unsupported)\n public birthtime: Date = new Date(0);\n // XXX: Some file systems stash data on stats objects.\n public fileData: Buffer | null= null;\n\n /**\n * Provides information about a particular entry in the file system.\n * @param [Number] item_type type of the item (FILE, DIRECTORY, SYMLINK, or SOCKET)\n * @param [Number] size Size of the item in bytes. For directories/symlinks,\n * this is normally the size of the struct that represents the item.\n * @param [Number] mode Unix-style file mode (e.g. 0o644)\n * @param [Date?] atime time of last access\n * @param [Date?] mtime time of last modification\n * @param [Date?] ctime time of creation\n */\n constructor(\n itemType: FileType,\n public size: number,\n mode?: number,\n public atime: Date = new Date(),\n public mtime: Date = new Date(),\n public ctime: Date = new Date()) {\n if (!mode) {\n switch (itemType) {\n case FileType.FILE:\n this.mode = 0x1a4;\n break;\n case FileType.DIRECTORY:\n default:\n this.mode = 0x1ff;\n }\n } else {\n this.mode = mode;\n }\n // number of 512B blocks allocated\n this.blocks = Math.ceil(size / 512);\n // Check if mode also includes top-most bits, which indicate the file's\n // type.\n if (this.mode < 0x1000) {\n this.mode |= itemType;\n }\n }\n\n public toBuffer(): Buffer {\n const buffer = Buffer.alloc(32);\n buffer.writeUInt32LE(this.size, 0);\n buffer.writeUInt32LE(this.mode, 4);\n buffer.writeDoubleLE(this.atime.getTime(), 8);\n buffer.writeDoubleLE(this.mtime.getTime(), 16);\n buffer.writeDoubleLE(this.ctime.getTime(), 24);\n return buffer;\n }\n\n /**\n * **Nonstandard**: Clone the stats object.\n * @return [BrowserFS.node.fs.Stats]\n */\n public clone(): Stats {\n return new Stats(this.mode & 0xF000, this.size, this.mode & 0xFFF, this.atime, this.mtime, this.ctime);\n }\n\n /**\n * @return [Boolean] True if this item is a file.\n */\n public isFile(): boolean {\n return (this.mode & 0xF000) === FileType.FILE;\n }\n\n /**\n * @return [Boolean] True if this item is a directory.\n */\n public isDirectory(): boolean {\n return (this.mode & 0xF000) === FileType.DIRECTORY;\n }\n\n /**\n * @return [Boolean] True if this item is a symbolic link (only valid through lstat)\n */\n public isSymbolicLink(): boolean {\n return (this.mode & 0xF000) === FileType.SYMLINK;\n }\n\n /**\n * Change the mode of the file. We use this helper function to prevent messing\n * up the type of the file, which is encoded in mode.\n */\n public chmod(mode: number): void {\n this.mode = (this.mode & 0xF000) | mode;\n }\n\n // We don't support the following types of files.\n\n public isSocket(): boolean {\n return false;\n }\n\n public isBlockDevice(): boolean {\n return false;\n }\n\n public isCharacterDevice(): boolean {\n return false;\n }\n\n public isFIFO(): boolean {\n return false;\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ../../../../src/core/node_fs_stats.ts","import {default as FS, FSModule} from './FS';\n\n// Manually export the individual public functions of fs.\n// Required because some code will invoke functions off of the module.\n// e.g.:\n// let writeFile = fs.writeFile;\n// writeFile(...)\n\n/**\n * @hidden\n */\nlet fs: any = new FS();\n/**\n * @hidden\n */\nconst _fsMock: FSModule = {};\n/**\n * @hidden\n */\nconst fsProto = FS.prototype;\nObject.keys(fsProto).forEach((key) => {\n if (typeof fs[key] === 'function') {\n ( _fsMock)[key] = function() {\n return ( fs[key]).apply(fs, arguments);\n };\n } else {\n ( _fsMock)[key] = fs[key];\n }\n});\n\n_fsMock['changeFSModule'] = function(newFs: FS): void {\n fs = newFs;\n};\n_fsMock['getFSModule'] = function(): FS {\n return fs;\n};\n_fsMock['FS'] = FS;\n\nexport default _fsMock;\n\n\n\n// WEBPACK FOOTER //\n// ../../../../src/core/node_fs.ts","/**\n * Defines an Emscripten file system object for use in the Emscripten virtual\n * filesystem. Allows you to use synchronous BrowserFS file systems from within\n * Emscripten.\n *\n * You can construct a BFSEmscriptenFS, mount it using its mount command,\n * and then mount it into Emscripten.\n *\n * Adapted from Emscripten's NodeFS:\n * https://raw.github.com/kripken/emscripten/master/src/library_nodefs.js\n */\nimport FS from '../core/FS';\nimport fs from '../core/node_fs';\nimport NodeStats from '../core/node_fs_stats';\nimport {uint8Array2Buffer} from '../core/util';\n\nexport interface Stats {\n dev: number;\n ino: number;\n mode: number;\n nlink: number;\n uid: number;\n gid: number;\n rdev: number;\n size: number;\n blksize: number;\n blocks: number;\n atime: Date;\n mtime: Date;\n ctime: Date;\n timestamp?: number;\n}\n\nexport interface EmscriptenFSNode {\n name: string;\n mode: number;\n parent: EmscriptenFSNode;\n mount: {opts: {root: string}};\n stream_ops: EmscriptenStreamOps;\n node_ops: EmscriptenNodeOps;\n}\n\nexport interface EmscriptenStream {\n node: EmscriptenFSNode;\n nfd: any;\n flags: string;\n position: number;\n}\n\nexport interface EmscriptenNodeOps {\n getattr(node: EmscriptenFSNode): Stats;\n setattr(node: EmscriptenFSNode, attr: Stats): void;\n lookup(parent: EmscriptenFSNode, name: string): EmscriptenFSNode;\n mknod(parent: EmscriptenFSNode, name: string, mode: number, dev: any): EmscriptenFSNode;\n rename(oldNode: EmscriptenFSNode, newDir: EmscriptenFSNode, newName: string): void;\n unlink(parent: EmscriptenFSNode, name: string): void;\n rmdir(parent: EmscriptenFSNode, name: string): void;\n readdir(node: EmscriptenFSNode): string[];\n symlink(parent: EmscriptenFSNode, newName: string, oldPath: string): void;\n readlink(node: EmscriptenFSNode): string;\n}\n\nexport interface EmscriptenStreamOps {\n open(stream: EmscriptenStream): void;\n close(stream: EmscriptenStream): void;\n read(stream: EmscriptenStream, buffer: Uint8Array, offset: number, length: number, position: number): number;\n write(stream: EmscriptenStream, buffer: Uint8Array, offset: number, length: number, position: number): number;\n llseek(stream: EmscriptenStream, offset: number, whence: number): number;\n}\n\nexport interface EmscriptenFS {\n node_ops: EmscriptenNodeOps;\n stream_ops: EmscriptenStreamOps;\n mount(mount: {opts: {root: string}}): EmscriptenFSNode;\n createNode(parent: EmscriptenFSNode, name: string, mode: number, dev?: any): EmscriptenFSNode;\n getMode(path: string): number;\n realPath(node: EmscriptenFSNode): string;\n}\n\nclass BFSEmscriptenStreamOps implements EmscriptenStreamOps {\n private FS: any;\n private PATH: any;\n private ERRNO_CODES: any;\n private nodefs: FS;\n\n constructor(private fs: BFSEmscriptenFS) {\n this.nodefs = fs.getNodeFS();\n this.FS = fs.getFS();\n this.PATH = fs.getPATH();\n this.ERRNO_CODES = fs.getERRNO_CODES();\n }\n\n public open(stream: EmscriptenStream): void {\n const path = this.fs.realPath(stream.node);\n const FS = this.FS;\n try {\n if (FS.isFile(stream.node.mode)) {\n stream.nfd = this.nodefs.openSync(path, this.fs.flagsToPermissionString(stream.flags));\n }\n } catch (e) {\n if (!e.code) {\n throw e;\n }\n throw new FS.ErrnoError(this.ERRNO_CODES[e.code]);\n }\n }\n\n public close(stream: EmscriptenStream): void {\n const FS = this.FS;\n try {\n if (FS.isFile(stream.node.mode) && stream.nfd) {\n this.nodefs.closeSync(stream.nfd);\n }\n } catch (e) {\n if (!e.code) {\n throw e;\n }\n throw new FS.ErrnoError(this.ERRNO_CODES[e.code]);\n }\n }\n\n public read(stream: EmscriptenStream, buffer: Uint8Array, offset: number, length: number, position: number): number {\n // Avoid copying overhead by reading directly into buffer.\n try {\n return this.nodefs.readSync(stream.nfd, uint8Array2Buffer(buffer), offset, length, position);\n } catch (e) {\n throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code]);\n }\n }\n\n public write(stream: EmscriptenStream, buffer: Uint8Array, offset: number, length: number, position: number): number {\n // Avoid copying overhead.\n try {\n return this.nodefs.writeSync(stream.nfd, uint8Array2Buffer(buffer), offset, length, position);\n } catch (e) {\n throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code]);\n }\n }\n\n public llseek(stream: EmscriptenStream, offset: number, whence: number): number {\n let position = offset;\n if (whence === 1) { // SEEK_CUR.\n position += stream.position;\n } else if (whence === 2) { // SEEK_END.\n if (this.FS.isFile(stream.node.mode)) {\n try {\n const stat = this.nodefs.fstatSync(stream.nfd);\n position += stat.size;\n } catch (e) {\n throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code]);\n }\n }\n }\n\n if (position < 0) {\n throw new this.FS.ErrnoError(this.ERRNO_CODES.EINVAL);\n }\n\n stream.position = position;\n return position;\n }\n}\n\nclass BFSEmscriptenNodeOps implements EmscriptenNodeOps {\n private FS: any;\n private PATH: any;\n private ERRNO_CODES: any;\n private nodefs: FS;\n\n constructor(private fs: BFSEmscriptenFS) {\n this.nodefs = fs.getNodeFS();\n this.FS = fs.getFS();\n this.PATH = fs.getPATH();\n this.ERRNO_CODES = fs.getERRNO_CODES();\n }\n\n public getattr(node: EmscriptenFSNode): Stats {\n const path = this.fs.realPath(node);\n let stat: NodeStats;\n try {\n stat = this.nodefs.lstatSync(path);\n } catch (e) {\n if (!e.code) {\n throw e;\n }\n throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code]);\n }\n return {\n dev: stat.dev,\n ino: stat.ino,\n mode: stat.mode,\n nlink: stat.nlink,\n uid: stat.uid,\n gid: stat.gid,\n rdev: stat.rdev,\n size: stat.size,\n atime: stat.atime,\n mtime: stat.mtime,\n ctime: stat.ctime,\n blksize: stat.blksize,\n blocks: stat.blocks\n };\n }\n\n public setattr(node: EmscriptenFSNode, attr: Stats): void {\n const path = this.fs.realPath(node);\n try {\n if (attr.mode !== undefined) {\n this.nodefs.chmodSync(path, attr.mode);\n // update the common node structure mode as well\n node.mode = attr.mode;\n }\n if (attr.timestamp !== undefined) {\n const date = new Date(attr.timestamp);\n this.nodefs.utimesSync(path, date, date);\n }\n } catch (e) {\n if (!e.code) {\n throw e;\n }\n // Ignore not supported errors. Emscripten does utimesSync when it\n // writes files, but never really requires the value to be set.\n if (e.code !== \"ENOTSUP\") {\n throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code]);\n }\n }\n if (attr.size !== undefined) {\n try {\n this.nodefs.truncateSync(path, attr.size);\n } catch (e) {\n if (!e.code) {\n throw e;\n }\n throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code]);\n }\n }\n }\n\n public lookup(parent: EmscriptenFSNode, name: string): EmscriptenFSNode {\n const path = this.PATH.join2(this.fs.realPath(parent), name);\n const mode = this.fs.getMode(path);\n return this.fs.createNode(parent, name, mode);\n }\n\n public mknod(parent: EmscriptenFSNode, name: string, mode: number, dev: any): EmscriptenFSNode {\n const node = this.fs.createNode(parent, name, mode, dev);\n // create the backing node for this in the fs root as well\n const path = this.fs.realPath(node);\n try {\n if (this.FS.isDir(node.mode)) {\n this.nodefs.mkdirSync(path, node.mode);\n } else {\n this.nodefs.writeFileSync(path, '', { mode: node.mode });\n }\n } catch (e) {\n if (!e.code) {\n throw e;\n }\n throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code]);\n }\n return node;\n }\n\n public rename(oldNode: EmscriptenFSNode, newDir: EmscriptenFSNode, newName: string): void {\n const oldPath = this.fs.realPath(oldNode);\n const newPath = this.PATH.join2(this.fs.realPath(newDir), newName);\n try {\n this.nodefs.renameSync(oldPath, newPath);\n // This logic is missing from the original NodeFS,\n // causing Emscripten's filesystem to think that the old file still exists.\n oldNode.name = newName;\n oldNode.parent = newDir;\n } catch (e) {\n if (!e.code) {\n throw e;\n }\n throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code]);\n }\n }\n\n public unlink(parent: EmscriptenFSNode, name: string): void {\n const path = this.PATH.join2(this.fs.realPath(parent), name);\n try {\n this.nodefs.unlinkSync(path);\n } catch (e) {\n if (!e.code) {\n throw e;\n }\n throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code]);\n }\n }\n\n public rmdir(parent: EmscriptenFSNode, name: string) {\n const path = this.PATH.join2(this.fs.realPath(parent), name);\n try {\n this.nodefs.rmdirSync(path);\n } catch (e) {\n if (!e.code) {\n throw e;\n }\n throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code]);\n }\n }\n\n public readdir(node: EmscriptenFSNode): string[] {\n const path = this.fs.realPath(node);\n try {\n // Node does not list . and .. in directory listings,\n // but Emscripten expects it.\n const contents = this.nodefs.readdirSync(path);\n contents.push('.', '..');\n return contents;\n } catch (e) {\n if (!e.code) {\n throw e;\n }\n throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code]);\n }\n }\n\n public symlink(parent: EmscriptenFSNode, newName: string, oldPath: string): void {\n const newPath = this.PATH.join2(this.fs.realPath(parent), newName);\n try {\n this.nodefs.symlinkSync(oldPath, newPath);\n } catch (e) {\n if (!e.code) {\n throw e;\n }\n throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code]);\n }\n }\n\n public readlink(node: EmscriptenFSNode): string {\n const path = this.fs.realPath(node);\n try {\n return this.nodefs.readlinkSync(path);\n } catch (e) {\n if (!e.code) {\n throw e;\n }\n throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code]);\n }\n }\n}\n\nexport default class BFSEmscriptenFS implements EmscriptenFS {\n // This maps the integer permission modes from http://linux.die.net/man/3/open\n // to node.js-specific file open permission strings at http://nodejs.org/api/fs.html#fs_fs_open_path_flags_mode_callback\n public flagsToPermissionStringMap = {\n 0/*O_RDONLY*/: 'r',\n 1/*O_WRONLY*/: 'r+',\n 2/*O_RDWR*/: 'r+',\n 64/*O_CREAT*/: 'r',\n 65/*O_WRONLY|O_CREAT*/: 'r+',\n 66/*O_RDWR|O_CREAT*/: 'r+',\n 129/*O_WRONLY|O_EXCL*/: 'rx+',\n 193/*O_WRONLY|O_CREAT|O_EXCL*/: 'rx+',\n 514/*O_RDWR|O_TRUNC*/: 'w+',\n 577/*O_WRONLY|O_CREAT|O_TRUNC*/: 'w',\n 578/*O_CREAT|O_RDWR|O_TRUNC*/: 'w+',\n 705/*O_WRONLY|O_CREAT|O_EXCL|O_TRUNC*/: 'wx',\n 706/*O_RDWR|O_CREAT|O_EXCL|O_TRUNC*/: 'wx+',\n 1024/*O_APPEND*/: 'a',\n 1025/*O_WRONLY|O_APPEND*/: 'a',\n 1026/*O_RDWR|O_APPEND*/: 'a+',\n 1089/*O_WRONLY|O_CREAT|O_APPEND*/: 'a',\n 1090/*O_RDWR|O_CREAT|O_APPEND*/: 'a+',\n 1153/*O_WRONLY|O_EXCL|O_APPEND*/: 'ax',\n 1154/*O_RDWR|O_EXCL|O_APPEND*/: 'ax+',\n 1217/*O_WRONLY|O_CREAT|O_EXCL|O_APPEND*/: 'ax',\n 1218/*O_RDWR|O_CREAT|O_EXCL|O_APPEND*/: 'ax+',\n 4096/*O_RDONLY|O_DSYNC*/: 'rs',\n 4098/*O_RDWR|O_DSYNC*/: 'rs+'\n };\n /* tslint:disable:variable-name */\n public node_ops: EmscriptenNodeOps;\n public stream_ops: EmscriptenStreamOps;\n /* tslint:enable:variable-name */\n\n private FS: any;\n private PATH: any;\n private ERRNO_CODES: any;\n private nodefs: FS;\n constructor(_FS = ( self)['FS'], _PATH = ( self)['PATH'], _ERRNO_CODES = ( self)['ERRNO_CODES'], nodefs: FS = fs) {\n this.nodefs = nodefs;\n this.FS = _FS;\n this.PATH = _PATH;\n this.ERRNO_CODES = _ERRNO_CODES;\n this.node_ops = new BFSEmscriptenNodeOps(this);\n this.stream_ops = new BFSEmscriptenStreamOps(this);\n }\n\n public mount(m: {opts: {root: string}}): EmscriptenFSNode {\n return this.createNode(null, '/', this.getMode(m.opts.root), 0);\n }\n\n public createNode(parent: EmscriptenFSNode | null, name: string, mode: number, dev?: any): EmscriptenFSNode {\n const FS = this.FS;\n if (!FS.isDir(mode) && !FS.isFile(mode) && !FS.isLink(mode)) {\n throw new FS.ErrnoError(this.ERRNO_CODES.EINVAL);\n }\n const node = FS.createNode(parent, name, mode);\n node.node_ops = this.node_ops;\n node.stream_ops = this.stream_ops;\n return node;\n }\n\n public getMode(path: string): number {\n let stat: NodeStats;\n try {\n stat = this.nodefs.lstatSync(path);\n } catch (e) {\n if (!e.code) {\n throw e;\n }\n throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code]);\n }\n return stat.mode;\n }\n\n public realPath(node: EmscriptenFSNode): string {\n const parts: string[] = [];\n while (node.parent !== node) {\n parts.push(node.name);\n node = node.parent;\n }\n parts.push(node.mount.opts.root);\n parts.reverse();\n return this.PATH.join.apply(null, parts);\n }\n\n public flagsToPermissionString(flags: string | number): string {\n let parsedFlags = (typeof flags === \"string\") ? parseInt(flags, 10) : flags;\n parsedFlags &= 0x1FFF;\n if (parsedFlags in this.flagsToPermissionStringMap) {\n return ( this.flagsToPermissionStringMap)[parsedFlags];\n } else {\n return flags;\n }\n }\n\n public getNodeFS() {\n return this.nodefs;\n }\n\n public getFS() {\n return this.FS;\n }\n\n public getPATH() {\n return this.PATH;\n }\n\n public getERRNO_CODES() {\n return this.ERRNO_CODES;\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ../../../../src/generic/emscripten_fs.ts","import {ApiError, ErrorCode} from './api_error';\nimport Stats from './node_fs_stats';\nimport {File} from './file';\nimport {FileFlag, ActionType} from './file_flag';\nimport * as path from 'path';\nimport {fail} from './util';\n\nexport type BFSOneArgCallback = (e?: ApiError | null) => any;\nexport type BFSCallback = (e: ApiError | null | undefined, rv?: T) => any;\nexport type BFSThreeArgCallback =\n (e: ApiError | null | undefined, arg1?: T, arg2?: U) => any;\n\n/**\n * Interface for a filesystem. **All** BrowserFS FileSystems should implement\n * this interface.\n *\n * Below, we denote each API method as **Core**, **Supplemental**, or\n * **Optional**.\n *\n * ### Core Methods\n *\n * **Core** API methods *need* to be implemented for basic read/write\n * functionality.\n *\n * Note that read-only FileSystems can choose to not implement core methods\n * that mutate files or metadata. The default implementation will pass a\n * NOT_SUPPORTED error to the callback.\n *\n * ### Supplemental Methods\n *\n * **Supplemental** API methods do not need to be implemented by a filesystem.\n * The default implementation implements all of the supplemental API methods in\n * terms of the **core** API methods.\n *\n * Note that a file system may choose to implement supplemental methods for\n * efficiency reasons.\n *\n * The code for some supplemental methods was adapted directly from NodeJS's\n * fs.js source code.\n *\n * ### Optional Methods\n *\n * **Optional** API methods provide functionality that may not be available in\n * all filesystems. For example, all symlink/hardlink-related API methods fall\n * under this category.\n *\n * The default implementation will pass a NOT_SUPPORTED error to the callback.\n *\n * ### Argument Assumptions\n *\n * You can assume the following about arguments passed to each API method:\n *\n * * **Every path is an absolute path.** Meaning, `.`, `..`, and other items\n * are resolved into an absolute form.\n * * **All arguments are present.** Any optional arguments at the Node API level\n * have been passed in with their default values.\n * * **The callback will reset the stack depth.** When your filesystem calls the\n * callback with the requested information, it will use `setImmediate` to\n * reset the JavaScript stack depth before calling the user-supplied callback.\n */\nexport interface FileSystem {\n /**\n * **Optional**: Returns the name of the file system.\n */\n getName(): string;\n /**\n * **Optional**: Passes the following information to the callback:\n *\n * * Total number of bytes available on this file system.\n * * number of free bytes available on this file system.\n *\n * @todo This info is not available through the Node API. Perhaps we could do a\n * polyfill of diskspace.js, or add a new Node API function.\n * @param path The path to the location that is being queried. Only\n * useful for filesystems that support mount points.\n */\n diskSpace(p: string, cb: (total: number, free: number) => any): void;\n /**\n * **Core**: Is this filesystem read-only?\n * @return True if this FileSystem is inherently read-only.\n */\n isReadOnly(): boolean;\n /**\n * **Core**: Does the filesystem support optional symlink/hardlink-related\n * commands?\n * @return True if the FileSystem supports the optional\n * symlink/hardlink-related commands.\n */\n supportsLinks(): boolean;\n /**\n * **Core**: Does the filesystem support optional property-related commands?\n * @return True if the FileSystem supports the optional\n * property-related commands (permissions, utimes, etc).\n */\n supportsProps(): boolean;\n /**\n * **Core**: Does the filesystem support the optional synchronous interface?\n * @return True if the FileSystem supports synchronous operations.\n */\n supportsSynch(): boolean;\n // **CORE API METHODS**\n // File or directory operations\n /**\n * **Core**: Asynchronous rename. No arguments other than a possible exception\n * are given to the completion callback.\n */\n rename(oldPath: string, newPath: string, cb: BFSOneArgCallback): void;\n /**\n * **Core**: Synchronous rename.\n */\n renameSync(oldPath: string, newPath: string): void;\n /**\n * **Core**: Asynchronous `stat` or `lstat`.\n * @param isLstat True if this is `lstat`, false if this is regular\n * `stat`.\n */\n stat(p: string, isLstat: boolean | null, cb: BFSCallback): void;\n /**\n * **Core**: Synchronous `stat` or `lstat`.\n * @param isLstat True if this is `lstat`, false if this is regular\n * `stat`.\n */\n statSync(p: string, isLstat: boolean | null): Stats;\n // File operations\n /**\n * **Core**: Asynchronous file open.\n * @see http://www.manpagez.com/man/2/open/\n * @param flags Handles the complexity of the various file\n * modes. See its API for more details.\n * @param mode Mode to use to open the file. Can be ignored if the\n * filesystem doesn't support permissions.\n */\n open(p: string, flag: FileFlag, mode: number, cb: BFSCallback): void;\n /**\n * **Core**: Synchronous file open.\n * @see http://www.manpagez.com/man/2/open/\n * @param flags Handles the complexity of the various file\n * modes. See its API for more details.\n * @param mode Mode to use to open the file. Can be ignored if the\n * filesystem doesn't support permissions.\n */\n openSync(p: string, flag: FileFlag, mode: number): File;\n /**\n * **Core**: Asynchronous `unlink`.\n */\n unlink(p: string, cb: BFSOneArgCallback): void;\n /**\n * **Core**: Synchronous `unlink`.\n */\n unlinkSync(p: string): void;\n // Directory operations\n /**\n * **Core**: Asynchronous `rmdir`.\n */\n rmdir(p: string, cb: BFSOneArgCallback): void;\n /**\n * **Core**: Synchronous `rmdir`.\n */\n rmdirSync(p: string): void;\n /**\n * **Core**: Asynchronous `mkdir`.\n * @param mode Mode to make the directory using. Can be ignored if\n * the filesystem doesn't support permissions.\n */\n mkdir(p: string, mode: number, cb: BFSOneArgCallback): void;\n /**\n * **Core**: Synchronous `mkdir`.\n * @param mode Mode to make the directory using. Can be ignored if\n * the filesystem doesn't support permissions.\n */\n mkdirSync(p: string, mode: number): void;\n /**\n * **Core**: Asynchronous `readdir`. Reads the contents of a directory.\n *\n * The callback gets two arguments `(err, files)` where `files` is an array of\n * the names of the files in the directory excluding `'.'` and `'..'`.\n */\n readdir(p: string, cb: BFSCallback): void;\n /**\n * **Core**: Synchronous `readdir`. Reads the contents of a directory.\n */\n readdirSync(p: string): string[];\n // **SUPPLEMENTAL INTERFACE METHODS**\n // File or directory operations\n /**\n * **Supplemental**: Test whether or not the given path exists by checking with\n * the file system. Then call the callback argument with either true or false.\n */\n exists(p: string, cb: (exists: boolean) => void): void;\n /**\n * **Supplemental**: Test whether or not the given path exists by checking with\n * the file system.\n */\n existsSync(p: string): boolean;\n /**\n * **Supplemental**: Asynchronous `realpath`. The callback gets two arguments\n * `(err, resolvedPath)`.\n *\n * Note that the Node API will resolve `path` to an absolute path.\n * @param cache An object literal of mapped paths that can be used to\n * force a specific path resolution or avoid additional `fs.stat` calls for\n * known real paths. If not supplied by the user, it'll be an empty object.\n */\n realpath(p: string, cache: {[path: string]: string}, cb: BFSCallback): void;\n /**\n * **Supplemental**: Synchronous `realpath`.\n *\n * Note that the Node API will resolve `path` to an absolute path.\n * @param cache An object literal of mapped paths that can be used to\n * force a specific path resolution or avoid additional `fs.stat` calls for\n * known real paths. If not supplied by the user, it'll be an empty object.\n */\n realpathSync(p: string, cache: {[path: string]: string}): string;\n // File operations\n /**\n * **Supplemental**: Asynchronous `truncate`.\n */\n truncate(p: string, len: number, cb: BFSOneArgCallback): void;\n /**\n * **Supplemental**: Synchronous `truncate`.\n */\n truncateSync(p: string, len: number): void;\n /**\n * **Supplemental**: Asynchronously reads the entire contents of a file.\n * @param encoding If non-null, the file's contents should be decoded\n * into a string using that encoding. Otherwise, if encoding is null, fetch\n * the file's contents as a Buffer.\n * @param cb If no encoding is specified, then the raw buffer is returned.\n */\n readFile(fname: string, encoding: string | null, flag: FileFlag, cb: BFSCallback): void;\n /**\n * **Supplemental**: Synchronously reads the entire contents of a file.\n * @param encoding If non-null, the file's contents should be decoded\n * into a string using that encoding. Otherwise, if encoding is null, fetch\n * the file's contents as a Buffer.\n */\n readFileSync(fname: string, encoding: string | null, flag: FileFlag): any;\n /**\n * **Supplemental**: Asynchronously writes data to a file, replacing the file\n * if it already exists.\n *\n * The encoding option is ignored if data is a buffer.\n */\n writeFile(fname: string, data: any, encoding: string | null, flag: FileFlag, mode: number, cb: BFSOneArgCallback): void;\n /**\n * **Supplemental**: Synchronously writes data to a file, replacing the file\n * if it already exists.\n *\n * The encoding option is ignored if data is a buffer.\n */\n writeFileSync(fname: string, data: string | Buffer, encoding: string | null, flag: FileFlag, mode: number): void;\n /**\n * **Supplemental**: Asynchronously append data to a file, creating the file if\n * it not yet exists.\n */\n appendFile(fname: string, data: string | Buffer, encoding: string | null, flag: FileFlag, mode: number, cb: BFSOneArgCallback): void;\n /**\n * **Supplemental**: Synchronously append data to a file, creating the file if\n * it not yet exists.\n */\n appendFileSync(fname: string, data: string | Buffer, encoding: string | null, flag: FileFlag, mode: number): void;\n // **OPTIONAL INTERFACE METHODS**\n // Property operations\n // This isn't always possible on some filesystem types (e.g. Dropbox).\n /**\n * **Optional**: Asynchronous `chmod` or `lchmod`.\n * @param isLchmod `True` if `lchmod`, false if `chmod`. Has no\n * bearing on result if links aren't supported.\n */\n chmod(p: string, isLchmod: boolean, mode: number, cb: BFSOneArgCallback): void;\n /**\n * **Optional**: Synchronous `chmod` or `lchmod`.\n * @param isLchmod `True` if `lchmod`, false if `chmod`. Has no\n * bearing on result if links aren't supported.\n */\n chmodSync(p: string, isLchmod: boolean, mode: number): void;\n /**\n * **Optional**: Asynchronous `chown` or `lchown`.\n * @param isLchown `True` if `lchown`, false if `chown`. Has no\n * bearing on result if links aren't supported.\n */\n chown(p: string, isLchown: boolean, uid: number, gid: number, cb: BFSOneArgCallback): void;\n /**\n * **Optional**: Synchronous `chown` or `lchown`.\n * @param isLchown `True` if `lchown`, false if `chown`. Has no\n * bearing on result if links aren't supported.\n */\n chownSync(p: string, isLchown: boolean, uid: number, gid: number): void;\n /**\n * **Optional**: Change file timestamps of the file referenced by the supplied\n * path.\n */\n utimes(p: string, atime: Date, mtime: Date, cb: BFSOneArgCallback): void;\n /**\n * **Optional**: Change file timestamps of the file referenced by the supplied\n * path.\n */\n utimesSync(p: string, atime: Date, mtime: Date): void;\n // Symlink operations\n // Symlinks aren't always supported.\n /**\n * **Optional**: Asynchronous `link`.\n */\n link(srcpath: string, dstpath: string, cb: BFSOneArgCallback): void;\n /**\n * **Optional**: Synchronous `link`.\n */\n linkSync(srcpath: string, dstpath: string): void;\n /**\n * **Optional**: Asynchronous `symlink`.\n * @param type can be either `'dir'` or `'file'`\n */\n symlink(srcpath: string, dstpath: string, type: string, cb: BFSOneArgCallback): void;\n /**\n * **Optional**: Synchronous `symlink`.\n * @param type can be either `'dir'` or `'file'`\n */\n symlinkSync(srcpath: string, dstpath: string, type: string): void;\n /**\n * **Optional**: Asynchronous readlink.\n */\n readlink(p: string, cb: BFSCallback): void;\n /**\n * **Optional**: Synchronous readlink.\n */\n readlinkSync(p: string): string;\n}\n\n/**\n * Describes a file system option.\n */\nexport interface FileSystemOption {\n // The basic JavaScript type(s) for this option.\n type: string | string[];\n // Whether or not the option is optional (e.g., can be set to null or undefined).\n // Defaults to `false`.\n optional?: boolean;\n // Description of the option. Used in error messages and documentation.\n description: string;\n // A custom validation function to check if the option is valid.\n // Calls the callback with an error object on an error.\n // (Can call callback synchronously.)\n // Defaults to `(opt, cb) => cb()`.\n validator?(opt: T, cb: BFSOneArgCallback): void;\n}\n\n/**\n * Describes all of the options available in a file system.\n */\nexport interface FileSystemOptions {\n [name: string]: FileSystemOption;\n}\n\n/**\n * Contains typings for static functions on the file system constructor.\n */\nexport interface FileSystemConstructor {\n /**\n * **Core**: Name to identify this particular file system.\n */\n Name: string;\n /**\n * **Core**: Describes all of the options available for this file system.\n */\n Options: FileSystemOptions;\n /**\n * **Core**: Creates a file system of this given type with the given\n * options.\n */\n Create(options: object, cb: BFSCallback): void;\n /**\n * **Core**: Returns 'true' if this filesystem is available in the current\n * environment. For example, a `localStorage`-backed filesystem will return\n * 'false' if the browser does not support that API.\n *\n * Defaults to 'false', as the FileSystem base class isn't usable alone.\n */\n isAvailable(): boolean;\n}\n\n/**\n * Basic filesystem class. Most filesystems should extend this class, as it\n * provides default implementations for a handful of methods.\n */\nexport class BaseFileSystem {\n public supportsLinks(): boolean {\n return false;\n }\n public diskSpace(p: string, cb: (total: number, free: number) => any): void {\n cb(0, 0);\n }\n /**\n * Opens the file at path p with the given flag. The file must exist.\n * @param p The path to open.\n * @param flag The flag to use when opening the file.\n */\n public openFile(p: string, flag: FileFlag, cb: BFSCallback): void {\n throw new ApiError(ErrorCode.ENOTSUP);\n }\n /**\n * Create the file at path p with the given mode. Then, open it with the given\n * flag.\n */\n public createFile(p: string, flag: FileFlag, mode: number, cb: BFSCallback): void {\n throw new ApiError(ErrorCode.ENOTSUP);\n }\n public open(p: string, flag: FileFlag, mode: number, cb: BFSCallback): void {\n const mustBeFile = (e: ApiError, stats?: Stats): void => {\n if (e) {\n // File does not exist.\n switch (flag.pathNotExistsAction()) {\n case ActionType.CREATE_FILE:\n // Ensure parent exists.\n return this.stat(path.dirname(p), false, (e: ApiError, parentStats?: Stats) => {\n if (e) {\n cb(e);\n } else if (parentStats && !parentStats.isDirectory()) {\n cb(ApiError.ENOTDIR(path.dirname(p)));\n } else {\n this.createFile(p, flag, mode, cb);\n }\n });\n case ActionType.THROW_EXCEPTION:\n return cb(ApiError.ENOENT(p));\n default:\n return cb(new ApiError(ErrorCode.EINVAL, 'Invalid FileFlag object.'));\n }\n } else {\n // File exists.\n if (stats && stats.isDirectory()) {\n return cb(ApiError.EISDIR(p));\n }\n switch (flag.pathExistsAction()) {\n case ActionType.THROW_EXCEPTION:\n return cb(ApiError.EEXIST(p));\n case ActionType.TRUNCATE_FILE:\n // NOTE: In a previous implementation, we deleted the file and\n // re-created it. However, this created a race condition if another\n // asynchronous request was trying to read the file, as the file\n // would not exist for a small period of time.\n return this.openFile(p, flag, (e: ApiError, fd?: File): void => {\n if (e) {\n cb(e);\n } else if (fd) {\n fd.truncate(0, () => {\n fd.sync(() => {\n cb(null, fd);\n });\n });\n } else {\n fail();\n }\n });\n case ActionType.NOP:\n return this.openFile(p, flag, cb);\n default:\n return cb(new ApiError(ErrorCode.EINVAL, 'Invalid FileFlag object.'));\n }\n }\n };\n this.stat(p, false, mustBeFile);\n }\n public rename(oldPath: string, newPath: string, cb: BFSOneArgCallback): void {\n cb(new ApiError(ErrorCode.ENOTSUP));\n }\n public renameSync(oldPath: string, newPath: string): void {\n throw new ApiError(ErrorCode.ENOTSUP);\n }\n public stat(p: string, isLstat: boolean | null, cb: BFSCallback): void {\n cb(new ApiError(ErrorCode.ENOTSUP));\n }\n public statSync(p: string, isLstat: boolean | null): Stats {\n throw new ApiError(ErrorCode.ENOTSUP);\n }\n /**\n * Opens the file at path p with the given flag. The file must exist.\n * @param p The path to open.\n * @param flag The flag to use when opening the file.\n * @return A File object corresponding to the opened file.\n */\n public openFileSync(p: string, flag: FileFlag, mode: number): File {\n throw new ApiError(ErrorCode.ENOTSUP);\n }\n /**\n * Create the file at path p with the given mode. Then, open it with the given\n * flag.\n */\n public createFileSync(p: string, flag: FileFlag, mode: number): File {\n throw new ApiError(ErrorCode.ENOTSUP);\n }\n public openSync(p: string, flag: FileFlag, mode: number): File {\n // Check if the path exists, and is a file.\n let stats: Stats;\n try {\n stats = this.statSync(p, false);\n } catch (e) {\n // File does not exist.\n switch (flag.pathNotExistsAction()) {\n case ActionType.CREATE_FILE:\n // Ensure parent exists.\n const parentStats = this.statSync(path.dirname(p), false);\n if (!parentStats.isDirectory()) {\n throw ApiError.ENOTDIR(path.dirname(p));\n }\n return this.createFileSync(p, flag, mode);\n case ActionType.THROW_EXCEPTION:\n throw ApiError.ENOENT(p);\n default:\n throw new ApiError(ErrorCode.EINVAL, 'Invalid FileFlag object.');\n }\n }\n\n // File exists.\n if (stats.isDirectory()) {\n throw ApiError.EISDIR(p);\n }\n switch (flag.pathExistsAction()) {\n case ActionType.THROW_EXCEPTION:\n throw ApiError.EEXIST(p);\n case ActionType.TRUNCATE_FILE:\n // Delete file.\n this.unlinkSync(p);\n // Create file. Use the same mode as the old file.\n // Node itself modifies the ctime when this occurs, so this action\n // will preserve that behavior if the underlying file system\n // supports those properties.\n return this.createFileSync(p, flag, stats.mode);\n case ActionType.NOP:\n return this.openFileSync(p, flag, mode);\n default:\n throw new ApiError(ErrorCode.EINVAL, 'Invalid FileFlag object.');\n }\n }\n public unlink(p: string, cb: BFSOneArgCallback): void {\n cb(new ApiError(ErrorCode.ENOTSUP));\n }\n public unlinkSync(p: string): void {\n throw new ApiError(ErrorCode.ENOTSUP);\n }\n public rmdir(p: string, cb: BFSOneArgCallback): void {\n cb(new ApiError(ErrorCode.ENOTSUP));\n }\n public rmdirSync(p: string): void {\n throw new ApiError(ErrorCode.ENOTSUP);\n }\n public mkdir(p: string, mode: number, cb: BFSOneArgCallback): void {\n cb(new ApiError(ErrorCode.ENOTSUP));\n }\n public mkdirSync(p: string, mode: number): void {\n throw new ApiError(ErrorCode.ENOTSUP);\n }\n public readdir(p: string, cb: BFSCallback): void {\n cb(new ApiError(ErrorCode.ENOTSUP));\n }\n public readdirSync(p: string): string[] {\n throw new ApiError(ErrorCode.ENOTSUP);\n }\n public exists(p: string, cb: (exists: boolean) => void): void {\n this.stat(p, null, function(err) {\n cb(!err);\n });\n }\n public existsSync(p: string): boolean {\n try {\n this.statSync(p, true);\n return true;\n } catch (e) {\n return false;\n }\n }\n public realpath(p: string, cache: {[path: string]: string}, cb: BFSCallback): void {\n if (this.supportsLinks()) {\n // The path could contain symlinks. Split up the path,\n // resolve any symlinks, return the resolved string.\n const splitPath = p.split(path.sep);\n // TODO: Simpler to just pass through file, find sep and such.\n for (let i = 0; i < splitPath.length; i++) {\n const addPaths = splitPath.slice(0, i + 1);\n splitPath[i] = path.join.apply(null, addPaths);\n }\n } else {\n // No symlinks. We just need to verify that it exists.\n this.exists(p, function(doesExist) {\n if (doesExist) {\n cb(null, p);\n } else {\n cb(ApiError.ENOENT(p));\n }\n });\n }\n }\n public realpathSync(p: string, cache: {[path: string]: string}): string {\n if (this.supportsLinks()) {\n // The path could contain symlinks. Split up the path,\n // resolve any symlinks, return the resolved string.\n const splitPath = p.split(path.sep);\n // TODO: Simpler to just pass through file, find sep and such.\n for (let i = 0; i < splitPath.length; i++) {\n const addPaths = splitPath.slice(0, i + 1);\n splitPath[i] = path.join.apply(path, addPaths);\n }\n return splitPath.join(path.sep);\n } else {\n // No symlinks. We just need to verify that it exists.\n if (this.existsSync(p)) {\n return p;\n } else {\n throw ApiError.ENOENT(p);\n }\n }\n }\n public truncate(p: string, len: number, cb: BFSOneArgCallback): void {\n this.open(p, FileFlag.getFileFlag('r+'), 0x1a4, (function(er: ApiError, fd?: File) {\n if (er) {\n return cb(er);\n }\n fd!.truncate(len, (function(er: any) {\n fd!.close((function(er2: any) {\n cb(er || er2);\n }));\n }));\n }));\n }\n public truncateSync(p: string, len: number): void {\n const fd = this.openSync(p, FileFlag.getFileFlag('r+'), 0x1a4);\n // Need to safely close FD, regardless of whether or not truncate succeeds.\n try {\n fd.truncateSync(len);\n } catch (e) {\n throw e;\n } finally {\n fd.closeSync();\n }\n }\n public readFile(fname: string, encoding: string | null, flag: FileFlag, cb: BFSCallback): void {\n // Wrap cb in file closing code.\n const oldCb = cb;\n // Get file.\n this.open(fname, flag, 0x1a4, (err, fd) => {\n if (err) {\n return cb(err);\n }\n cb = function(err?: ApiError | null, arg?: string | Buffer) {\n fd!.close(function(err2: any) {\n if (!err) {\n err = err2;\n }\n return oldCb(err, arg);\n });\n };\n fd!.stat((err, stat?) => {\n if (err) {\n return cb(err);\n }\n // Allocate buffer.\n const buf = Buffer.alloc(stat!.size);\n fd!.read(buf, 0, stat!.size, 0, (err?: ApiError | null) => {\n if (err) {\n return cb(err);\n } else if (encoding === null) {\n return cb(err, buf);\n }\n try {\n cb(null, buf.toString(encoding));\n } catch (e) {\n cb(e);\n }\n });\n });\n });\n }\n public readFileSync(fname: string, encoding: string | null, flag: FileFlag): any {\n // Get file.\n const fd = this.openSync(fname, flag, 0x1a4);\n try {\n const stat = fd.statSync();\n // Allocate buffer.\n const buf = Buffer.alloc(stat.size);\n fd.readSync(buf, 0, stat.size, 0);\n fd.closeSync();\n if (encoding === null) {\n return buf;\n }\n return buf.toString(encoding);\n } finally {\n fd.closeSync();\n }\n }\n public writeFile(fname: string, data: any, encoding: string | null, flag: FileFlag, mode: number, cb: BFSOneArgCallback): void {\n // Wrap cb in file closing code.\n const oldCb = cb;\n // Get file.\n this.open(fname, flag, 0x1a4, function(err: ApiError, fd?: File) {\n if (err) {\n return cb(err);\n }\n cb = function(err: ApiError) {\n fd!.close(function(err2: any) {\n oldCb(err ? err : err2);\n });\n };\n\n try {\n if (typeof data === 'string') {\n data = Buffer.from(data, encoding!);\n }\n } catch (e) {\n return cb(e);\n }\n // Write into file.\n fd!.write(data, 0, data.length, 0, cb);\n });\n }\n public writeFileSync(fname: string, data: any, encoding: string | null, flag: FileFlag, mode: number): void {\n // Get file.\n const fd = this.openSync(fname, flag, mode);\n try {\n if (typeof data === 'string') {\n data = Buffer.from(data, encoding!);\n }\n // Write into file.\n fd.writeSync(data, 0, data.length, 0);\n } finally {\n fd.closeSync();\n }\n }\n public appendFile(fname: string, data: any, encoding: string | null, flag: FileFlag, mode: number, cb: BFSOneArgCallback): void {\n // Wrap cb in file closing code.\n const oldCb = cb;\n this.open(fname, flag, mode, function(err: ApiError, fd?: File) {\n if (err) {\n return cb(err);\n }\n cb = function(err: ApiError) {\n fd!.close(function(err2: any) {\n oldCb(err ? err : err2);\n });\n };\n if (typeof data === 'string') {\n data = Buffer.from(data, encoding!);\n }\n fd!.write(data, 0, data.length, null, cb);\n });\n }\n public appendFileSync(fname: string, data: any, encoding: string | null, flag: FileFlag, mode: number): void {\n const fd = this.openSync(fname, flag, mode);\n try {\n if (typeof data === 'string') {\n data = Buffer.from(data, encoding!);\n }\n fd.writeSync(data, 0, data.length, null);\n } finally {\n fd.closeSync();\n }\n }\n public chmod(p: string, isLchmod: boolean, mode: number, cb: BFSOneArgCallback): void {\n cb(new ApiError(ErrorCode.ENOTSUP));\n }\n public chmodSync(p: string, isLchmod: boolean, mode: number) {\n throw new ApiError(ErrorCode.ENOTSUP);\n }\n public chown(p: string, isLchown: boolean, uid: number, gid: number, cb: BFSOneArgCallback): void {\n cb(new ApiError(ErrorCode.ENOTSUP));\n }\n public chownSync(p: string, isLchown: boolean, uid: number, gid: number): void {\n throw new ApiError(ErrorCode.ENOTSUP);\n }\n public utimes(p: string, atime: Date, mtime: Date, cb: BFSOneArgCallback): void {\n cb(new ApiError(ErrorCode.ENOTSUP));\n }\n public utimesSync(p: string, atime: Date, mtime: Date): void {\n throw new ApiError(ErrorCode.ENOTSUP);\n }\n public link(srcpath: string, dstpath: string, cb: BFSOneArgCallback): void {\n cb(new ApiError(ErrorCode.ENOTSUP));\n }\n public linkSync(srcpath: string, dstpath: string): void {\n throw new ApiError(ErrorCode.ENOTSUP);\n }\n public symlink(srcpath: string, dstpath: string, type: string, cb: BFSOneArgCallback): void {\n cb(new ApiError(ErrorCode.ENOTSUP));\n }\n public symlinkSync(srcpath: string, dstpath: string, type: string): void {\n throw new ApiError(ErrorCode.ENOTSUP);\n }\n public readlink(p: string, cb: BFSOneArgCallback): void {\n cb(new ApiError(ErrorCode.ENOTSUP));\n }\n public readlinkSync(p: string): string {\n throw new ApiError(ErrorCode.ENOTSUP);\n }\n}\n\n/**\n * Implements the asynchronous API in terms of the synchronous API.\n * @class SynchronousFileSystem\n */\nexport class SynchronousFileSystem extends BaseFileSystem {\n public supportsSynch(): boolean {\n return true;\n }\n\n public rename(oldPath: string, newPath: string, cb: BFSOneArgCallback): void {\n try {\n this.renameSync(oldPath, newPath);\n cb();\n } catch (e) {\n cb(e);\n }\n }\n\n public stat(p: string, isLstat: boolean | null, cb: BFSCallback): void {\n try {\n cb(null, this.statSync(p, isLstat));\n } catch (e) {\n cb(e);\n }\n }\n\n public open(p: string, flags: FileFlag, mode: number, cb: BFSCallback): void {\n try {\n cb(null, this.openSync(p, flags, mode));\n } catch (e) {\n cb(e);\n }\n }\n\n public unlink(p: string, cb: BFSOneArgCallback): void {\n try {\n this.unlinkSync(p);\n cb();\n } catch (e) {\n cb(e);\n }\n }\n\n public rmdir(p: string, cb: BFSOneArgCallback): void {\n try {\n this.rmdirSync(p);\n cb();\n } catch (e) {\n cb(e);\n }\n }\n\n public mkdir(p: string, mode: number, cb: BFSOneArgCallback): void {\n try {\n this.mkdirSync(p, mode);\n cb();\n } catch (e) {\n cb(e);\n }\n }\n\n public readdir(p: string, cb: BFSCallback): void {\n try {\n cb(null, this.readdirSync(p));\n } catch (e) {\n cb(e);\n }\n }\n\n public chmod(p: string, isLchmod: boolean, mode: number, cb: BFSOneArgCallback): void {\n try {\n this.chmodSync(p, isLchmod, mode);\n cb();\n } catch (e) {\n cb(e);\n }\n }\n\n public chown(p: string, isLchown: boolean, uid: number, gid: number, cb: BFSOneArgCallback): void {\n try {\n this.chownSync(p, isLchown, uid, gid);\n cb();\n } catch (e) {\n cb(e);\n }\n }\n\n public utimes(p: string, atime: Date, mtime: Date, cb: BFSOneArgCallback): void {\n try {\n this.utimesSync(p, atime, mtime);\n cb();\n } catch (e) {\n cb(e);\n }\n }\n\n public link(srcpath: string, dstpath: string, cb: BFSOneArgCallback): void {\n try {\n this.linkSync(srcpath, dstpath);\n cb();\n } catch (e) {\n cb(e);\n }\n }\n\n public symlink(srcpath: string, dstpath: string, type: string, cb: BFSOneArgCallback): void {\n try {\n this.symlinkSync(srcpath, dstpath, type);\n cb();\n } catch (e) {\n cb(e);\n }\n }\n\n public readlink(p: string, cb: BFSCallback): void {\n try {\n cb(null, this.readlinkSync(p));\n } catch (e) {\n cb(e);\n }\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ../../../../src/core/file_system.ts","import {ApiError, ErrorCode} from './api_error';\nimport Stats from './node_fs_stats';\nimport {BFSCallback, BFSOneArgCallback, BFSThreeArgCallback} from './file_system';\n\nexport interface File {\n /**\n * **Core**: Get the current file position.\n */\n getPos(): number | undefined;\n /**\n * **Core**: Asynchronous `stat`.\n */\n stat(cb: BFSCallback): void;\n /**\n * **Core**: Synchronous `stat`.\n */\n statSync(): Stats;\n /**\n * **Core**: Asynchronous close.\n */\n close(cb: BFSOneArgCallback): void;\n /**\n * **Core**: Synchronous close.\n */\n closeSync(): void;\n /**\n * **Core**: Asynchronous truncate.\n */\n truncate(len: number, cb: BFSOneArgCallback): void;\n /**\n * **Core**: Synchronous truncate.\n */\n truncateSync(len: number): void;\n /**\n * **Core**: Asynchronous sync.\n */\n sync(cb: BFSOneArgCallback): void;\n /**\n * **Core**: Synchronous sync.\n */\n syncSync(): void;\n /**\n * **Core**: Write buffer to the file.\n * Note that it is unsafe to use fs.write multiple times on the same file\n * without waiting for the callback.\n * @param buffer Buffer containing the data to write to\n * the file.\n * @param offset Offset in the buffer to start reading data from.\n * @param length The amount of bytes to write to the file.\n * @param position Offset from the beginning of the file where this\n * data should be written. If position is null, the data will be written at\n * the current position.\n * @param cb The number specifies the number of bytes written into the file.\n */\n write(buffer: Buffer, offset: number, length: number, position: number | null, cb: BFSThreeArgCallback): void;\n /**\n * **Core**: Write buffer to the file.\n * Note that it is unsafe to use fs.writeSync multiple times on the same file\n * without waiting for it to return.\n * @param buffer Buffer containing the data to write to\n * the file.\n * @param offset Offset in the buffer to start reading data from.\n * @param length The amount of bytes to write to the file.\n * @param position Offset from the beginning of the file where this\n * data should be written. If position is null, the data will be written at\n * the current position.\n */\n writeSync(buffer: Buffer, offset: number, length: number, position: number | null): number;\n /**\n * **Core**: Read data from the file.\n * @param buffer The buffer that the data will be\n * written to.\n * @param offset The offset within the buffer where writing will\n * start.\n * @param length An integer specifying the number of bytes to read.\n * @param position An integer specifying where to begin reading from\n * in the file. If position is null, data will be read from the current file\n * position.\n * @param cb The number is the number of bytes read\n */\n read(buffer: Buffer, offset: number, length: number, position: number | null, cb: BFSThreeArgCallback): void;\n /**\n * **Core**: Read data from the file.\n * @param buffer The buffer that the data will be written to.\n * @param offset The offset within the buffer where writing will start.\n * @param length An integer specifying the number of bytes to read.\n * @param position An integer specifying where to begin reading from\n * in the file. If position is null, data will be read from the current file\n * position.\n */\n readSync(buffer: Buffer, offset: number, length: number, position: number): number;\n /**\n * **Supplementary**: Asynchronous `datasync`.\n *\n * Default implementation maps to `sync`.\n */\n datasync(cb: BFSOneArgCallback): void;\n /**\n * **Supplementary**: Synchronous `datasync`.\n *\n * Default implementation maps to `syncSync`.\n */\n datasyncSync(): void;\n /**\n * **Optional**: Asynchronous `chown`.\n */\n chown(uid: number, gid: number, cb: BFSOneArgCallback): void;\n /**\n * **Optional**: Synchronous `chown`.\n */\n chownSync(uid: number, gid: number): void;\n /**\n * **Optional**: Asynchronous `fchmod`.\n */\n chmod(mode: number, cb: BFSOneArgCallback): void;\n /**\n * **Optional**: Synchronous `fchmod`.\n */\n chmodSync(mode: number): void;\n /**\n * **Optional**: Change the file timestamps of the file.\n */\n utimes(atime: Date, mtime: Date, cb: BFSOneArgCallback): void;\n /**\n * **Optional**: Change the file timestamps of the file.\n */\n utimesSync(atime: Date, mtime: Date): void;\n}\n\n/**\n * Base class that contains shared implementations of functions for the file\n * object.\n */\nexport class BaseFile {\n public sync(cb: BFSOneArgCallback): void {\n cb(new ApiError(ErrorCode.ENOTSUP));\n }\n public syncSync(): void {\n throw new ApiError(ErrorCode.ENOTSUP);\n }\n public datasync(cb: BFSOneArgCallback): void {\n this.sync(cb);\n }\n public datasyncSync(): void {\n return this.syncSync();\n }\n public chown(uid: number, gid: number, cb: BFSOneArgCallback): void {\n cb(new ApiError(ErrorCode.ENOTSUP));\n }\n public chownSync(uid: number, gid: number): void {\n throw new ApiError(ErrorCode.ENOTSUP);\n }\n public chmod(mode: number, cb: BFSOneArgCallback): void {\n cb(new ApiError(ErrorCode.ENOTSUP));\n }\n public chmodSync(mode: number): void {\n throw new ApiError(ErrorCode.ENOTSUP);\n }\n public utimes(atime: Date, mtime: Date, cb: BFSOneArgCallback): void {\n cb(new ApiError(ErrorCode.ENOTSUP));\n }\n public utimesSync(atime: Date, mtime: Date): void {\n throw new ApiError(ErrorCode.ENOTSUP);\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ../../../../src/core/file.ts","import {BaseFile, File} from '../core/file';\nimport {FileSystem, BFSOneArgCallback, BFSCallback, BFSThreeArgCallback} from '../core/file_system';\nimport Stats from '../core/node_fs_stats';\nimport {FileFlag} from '../core/file_flag';\nimport {ApiError, ErrorCode} from '../core/api_error';\nimport fs from '../core/node_fs';\nimport {emptyBuffer} from '../core/util';\n\n/**\n * An implementation of the File interface that operates on a file that is\n * completely in-memory. PreloadFiles are backed by a Buffer.\n *\n * This is also an abstract class, as it lacks an implementation of 'sync' and\n * 'close'. Each filesystem that wishes to use this file representation must\n * extend this class and implement those two methods.\n * @todo 'close' lever that disables functionality once closed.\n */\nexport default class PreloadFile extends BaseFile {\n protected _fs: T;\n private _pos: number = 0;\n private _path: string;\n private _stat: Stats;\n private _flag: FileFlag;\n private _buffer: Buffer;\n private _dirty: boolean = false;\n /**\n * Creates a file with the given path and, optionally, the given contents. Note\n * that, if contents is specified, it will be mutated by the file!\n * @param _fs The file system that created the file.\n * @param _path\n * @param _mode The mode that the file was opened using.\n * Dictates permissions and where the file pointer starts.\n * @param _stat The stats object for the given file.\n * PreloadFile will mutate this object. Note that this object must contain\n * the appropriate mode that the file was opened as.\n * @param contents A buffer containing the entire\n * contents of the file. PreloadFile will mutate this buffer. If not\n * specified, we assume it is a new file.\n */\n constructor(_fs: T, _path: string, _flag: FileFlag, _stat: Stats, contents?: Buffer) {\n super();\n this._fs = _fs;\n this._path = _path;\n this._flag = _flag;\n this._stat = _stat;\n if (contents) {\n this._buffer = contents;\n } else {\n // Empty buffer. It'll expand once we write stuff to it.\n this._buffer = emptyBuffer();\n }\n // Note: This invariant is *not* maintained once the file starts getting\n // modified.\n // Note: Only actually matters if file is readable, as writeable modes may\n // truncate/append to file.\n if (this._stat.size !== this._buffer.length && this._flag.isReadable()) {\n throw new Error(`Invalid buffer: Buffer is ${this._buffer.length} long, yet Stats object specifies that file is ${this._stat.size} long.`);\n }\n }\n\n /**\n * NONSTANDARD: Get the underlying buffer for this file. !!DO NOT MUTATE!! Will mess up dirty tracking.\n */\n public getBuffer(): Buffer {\n return this._buffer;\n }\n\n /**\n * NONSTANDARD: Get underlying stats for this file. !!DO NOT MUTATE!!\n */\n public getStats(): Stats {\n return this._stat;\n }\n\n public getFlag(): FileFlag {\n return this._flag;\n }\n\n /**\n * Get the path to this file.\n * @return [String] The path to the file.\n */\n public getPath(): string {\n return this._path;\n }\n\n /**\n * Get the current file position.\n *\n * We emulate the following bug mentioned in the Node documentation:\n * > On Linux, positional writes don't work when the file is opened in append\n * mode. The kernel ignores the position argument and always appends the data\n * to the end of the file.\n * @return [Number] The current file position.\n */\n public getPos(): number {\n if (this._flag.isAppendable()) {\n return this._stat.size;\n }\n return this._pos;\n }\n\n /**\n * Advance the current file position by the indicated number of positions.\n * @param [Number] delta\n */\n public advancePos(delta: number): number {\n return this._pos += delta;\n }\n\n /**\n * Set the file position.\n * @param [Number] newPos\n */\n public setPos(newPos: number): number {\n return this._pos = newPos;\n }\n\n /**\n * **Core**: Asynchronous sync. Must be implemented by subclasses of this\n * class.\n * @param [Function(BrowserFS.ApiError)] cb\n */\n public sync(cb: BFSOneArgCallback): void {\n try {\n this.syncSync();\n cb();\n } catch (e) {\n cb(e);\n }\n }\n\n /**\n * **Core**: Synchronous sync.\n */\n public syncSync(): void {\n throw new ApiError(ErrorCode.ENOTSUP);\n }\n\n /**\n * **Core**: Asynchronous close. Must be implemented by subclasses of this\n * class.\n * @param [Function(BrowserFS.ApiError)] cb\n */\n public close(cb: BFSOneArgCallback): void {\n try {\n this.closeSync();\n cb();\n } catch (e) {\n cb(e);\n }\n }\n\n /**\n * **Core**: Synchronous close.\n */\n public closeSync(): void {\n throw new ApiError(ErrorCode.ENOTSUP);\n }\n\n /**\n * Asynchronous `stat`.\n * @param [Function(BrowserFS.ApiError, BrowserFS.node.fs.Stats)] cb\n */\n public stat(cb: BFSCallback): void {\n try {\n cb(null, this._stat.clone());\n } catch (e) {\n cb(e);\n }\n }\n\n /**\n * Synchronous `stat`.\n */\n public statSync(): Stats {\n return this._stat.clone();\n }\n\n /**\n * Asynchronous truncate.\n * @param [Number] len\n * @param [Function(BrowserFS.ApiError)] cb\n */\n public truncate(len: number, cb: BFSOneArgCallback): void {\n try {\n this.truncateSync(len);\n if (this._flag.isSynchronous() && !fs.getRootFS()!.supportsSynch()) {\n this.sync(cb);\n }\n cb();\n } catch (e) {\n return cb(e);\n }\n }\n\n /**\n * Synchronous truncate.\n * @param [Number] len\n */\n public truncateSync(len: number): void {\n this._dirty = true;\n if (!this._flag.isWriteable()) {\n throw new ApiError(ErrorCode.EPERM, 'File not opened with a writeable mode.');\n }\n this._stat.mtime = new Date();\n if (len > this._buffer.length) {\n const buf = Buffer.alloc(len - this._buffer.length, 0);\n // Write will set @_stat.size for us.\n this.writeSync(buf, 0, buf.length, this._buffer.length);\n if (this._flag.isSynchronous() && fs.getRootFS()!.supportsSynch()) {\n this.syncSync();\n }\n return;\n }\n this._stat.size = len;\n // Truncate buffer to 'len'.\n const newBuff = Buffer.alloc(len);\n this._buffer.copy(newBuff, 0, 0, len);\n this._buffer = newBuff;\n if (this._flag.isSynchronous() && fs.getRootFS()!.supportsSynch()) {\n this.syncSync();\n }\n }\n\n /**\n * Write buffer to the file.\n * Note that it is unsafe to use fs.write multiple times on the same file\n * without waiting for the callback.\n * @param [BrowserFS.node.Buffer] buffer Buffer containing the data to write to\n * the file.\n * @param [Number] offset Offset in the buffer to start reading data from.\n * @param [Number] length The amount of bytes to write to the file.\n * @param [Number] position Offset from the beginning of the file where this\n * data should be written. If position is null, the data will be written at\n * the current position.\n * @param [Function(BrowserFS.ApiError, Number, BrowserFS.node.Buffer)]\n * cb The number specifies the number of bytes written into the file.\n */\n public write(buffer: Buffer, offset: number, length: number, position: number, cb: BFSThreeArgCallback): void {\n try {\n cb(null, this.writeSync(buffer, offset, length, position), buffer);\n } catch (e) {\n cb(e);\n }\n }\n\n /**\n * Write buffer to the file.\n * Note that it is unsafe to use fs.writeSync multiple times on the same file\n * without waiting for the callback.\n * @param [BrowserFS.node.Buffer] buffer Buffer containing the data to write to\n * the file.\n * @param [Number] offset Offset in the buffer to start reading data from.\n * @param [Number] length The amount of bytes to write to the file.\n * @param [Number] position Offset from the beginning of the file where this\n * data should be written. If position is null, the data will be written at\n * the current position.\n * @return [Number]\n */\n public writeSync(buffer: Buffer, offset: number, length: number, position: number): number {\n this._dirty = true;\n if (position === undefined || position === null) {\n position = this.getPos();\n }\n if (!this._flag.isWriteable()) {\n throw new ApiError(ErrorCode.EPERM, 'File not opened with a writeable mode.');\n }\n const endFp = position + length;\n if (endFp > this._stat.size) {\n this._stat.size = endFp;\n if (endFp > this._buffer.length) {\n // Extend the buffer!\n const newBuff = Buffer.alloc(endFp);\n this._buffer.copy(newBuff);\n this._buffer = newBuff;\n }\n }\n const len = buffer.copy(this._buffer, position, offset, offset + length);\n this._stat.mtime = new Date();\n if (this._flag.isSynchronous()) {\n this.syncSync();\n return len;\n }\n this.setPos(position + len);\n return len;\n }\n\n /**\n * Read data from the file.\n * @param [BrowserFS.node.Buffer] buffer The buffer that the data will be\n * written to.\n * @param [Number] offset The offset within the buffer where writing will\n * start.\n * @param [Number] length An integer specifying the number of bytes to read.\n * @param [Number] position An integer specifying where to begin reading from\n * in the file. If position is null, data will be read from the current file\n * position.\n * @param [Function(BrowserFS.ApiError, Number, BrowserFS.node.Buffer)] cb The\n * number is the number of bytes read\n */\n public read(buffer: Buffer, offset: number, length: number, position: number, cb: BFSThreeArgCallback): void {\n try {\n cb(null, this.readSync(buffer, offset, length, position), buffer);\n } catch (e) {\n cb(e);\n }\n }\n\n /**\n * Read data from the file.\n * @param [BrowserFS.node.Buffer] buffer The buffer that the data will be\n * written to.\n * @param [Number] offset The offset within the buffer where writing will\n * start.\n * @param [Number] length An integer specifying the number of bytes to read.\n * @param [Number] position An integer specifying where to begin reading from\n * in the file. If position is null, data will be read from the current file\n * position.\n * @return [Number]\n */\n public readSync(buffer: Buffer, offset: number, length: number, position: number): number {\n if (!this._flag.isReadable()) {\n throw new ApiError(ErrorCode.EPERM, 'File not opened with a readable mode.');\n }\n if (position === undefined || position === null) {\n position = this.getPos();\n }\n const endRead = position + length;\n if (endRead > this._stat.size) {\n length = this._stat.size - position;\n }\n const rv = this._buffer.copy(buffer, offset, position, position + length);\n this._stat.atime = new Date();\n this._pos = position + length;\n return rv;\n }\n\n /**\n * Asynchronous `fchmod`.\n * @param [Number|String] mode\n * @param [Function(BrowserFS.ApiError)] cb\n */\n public chmod(mode: number, cb: BFSOneArgCallback): void {\n try {\n this.chmodSync(mode);\n cb();\n } catch (e) {\n cb(e);\n }\n }\n\n /**\n * Asynchronous `fchmod`.\n * @param [Number] mode\n */\n public chmodSync(mode: number): void {\n if (!this._fs.supportsProps()) {\n throw new ApiError(ErrorCode.ENOTSUP);\n }\n this._dirty = true;\n this._stat.chmod(mode);\n this.syncSync();\n }\n\n protected isDirty(): boolean {\n return this._dirty;\n }\n\n /**\n * Resets the dirty bit. Should only be called after a sync has completed successfully.\n */\n protected resetDirty() {\n this._dirty = false;\n }\n}\n\n/**\n * File class for the InMemory and XHR file systems.\n * Doesn't sync to anything, so it works nicely for memory-only files.\n */\nexport class NoSyncFile extends PreloadFile implements File {\n constructor(_fs: T, _path: string, _flag: FileFlag, _stat: Stats, contents?: Buffer) {\n super(_fs, _path, _flag, _stat, contents);\n }\n /**\n * Asynchronous sync. Doesn't do anything, simply calls the cb.\n * @param [Function(BrowserFS.ApiError)] cb\n */\n public sync(cb: BFSOneArgCallback): void {\n cb();\n }\n /**\n * Synchronous sync. Doesn't do anything.\n */\n public syncSync(): void {\n // NOP.\n }\n /**\n * Asynchronous close. Doesn't do anything, simply calls the cb.\n * @param [Function(BrowserFS.ApiError)] cb\n */\n public close(cb: BFSOneArgCallback): void {\n cb();\n }\n /**\n * Synchronous close. Doesn't do anything.\n */\n public closeSync(): void {\n // NOP.\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ../../../../src/generic/preload_file.ts","import {FileSystem, SynchronousFileSystem, BFSOneArgCallback, BFSCallback, FileSystemOptions} from '../core/file_system';\nimport {ApiError, ErrorCode} from '../core/api_error';\nimport {FileFlag} from '../core/file_flag';\nimport {File} from '../core/file';\nimport Stats from '../core/node_fs_stats';\nimport PreloadFile from '../generic/preload_file';\nimport {deprecationMessage} from '../core/util';\nimport * as path from 'path';\n\n/**\n * @hidden\n */\ninterface IAsyncOperation {\n apiMethod: string;\n arguments: any[];\n}\n\n/**\n * We define our own file to interpose on syncSync() for mirroring purposes.\n */\nclass MirrorFile extends PreloadFile implements File {\n constructor(fs: AsyncMirror, path: string, flag: FileFlag, stat: Stats, data: Buffer) {\n super(fs, path, flag, stat, data);\n }\n\n public syncSync(): void {\n if (this.isDirty()) {\n this._fs._syncSync(this);\n this.resetDirty();\n }\n }\n\n public closeSync(): void {\n this.syncSync();\n }\n}\n\n/**\n * Configuration options for the AsyncMirror file system.\n */\nexport interface AsyncMirrorOptions {\n // The synchronous file system to mirror the asynchronous file system to.\n sync: FileSystem;\n // The asynchronous file system to mirror.\n async: FileSystem;\n}\n\n/**\n * AsyncMirrorFS mirrors a synchronous filesystem into an asynchronous filesystem\n * by:\n *\n * * Performing operations over the in-memory copy, while asynchronously pipelining them\n * to the backing store.\n * * During application loading, the contents of the async file system can be reloaded into\n * the synchronous store, if desired.\n *\n * The two stores will be kept in sync. The most common use-case is to pair a synchronous\n * in-memory filesystem with an asynchronous backing store.\n *\n * Example: Mirroring an IndexedDB file system to an in memory file system. Now, you can use\n * IndexedDB synchronously.\n *\n * ```javascript\n * BrowserFS.configure({\n * fs: \"AsyncMirror\",\n * options: {\n * sync: { fs: \"InMemory\" },\n * async: { fs: \"IndexedDB\" }\n * }\n * }, function(e) {\n * // BrowserFS is initialized and ready-to-use!\n * });\n * ```\n *\n * Or, alternatively:\n *\n * ```javascript\n * BrowserFS.FileSystem.IndexedDB.Create(function(e, idbfs) {\n * BrowserFS.FileSystem.InMemory.Create(function(e, inMemory) {\n * BrowserFS.FileSystem.AsyncMirror({\n * sync: inMemory, async: idbfs\n * }, function(e, mirrored) {\n * BrowserFS.initialize(mirrored);\n * });\n * });\n * });\n * ```\n */\nexport default class AsyncMirror extends SynchronousFileSystem implements FileSystem {\n public static readonly Name = \"AsyncMirror\";\n\n public static readonly Options: FileSystemOptions = {\n sync: {\n type: \"object\",\n description: \"The synchronous file system to mirror the asynchronous file system to.\"\n },\n async: {\n type: \"object\",\n description: \"The asynchronous file system to mirror.\"\n }\n };\n\n /**\n * Constructs and initializes an AsyncMirror file system with the given options.\n */\n public static Create(opts: AsyncMirrorOptions, cb: BFSCallback): void {\n try {\n const fs = new AsyncMirror(opts.sync, opts.async, false);\n fs.initialize((e?) => {\n if (e) {\n cb(e);\n } else {\n cb(null, fs);\n }\n }, false);\n } catch (e) {\n cb(e);\n }\n }\n\n public static isAvailable(): boolean {\n return true;\n }\n\n /**\n * Queue of pending asynchronous operations.\n */\n private _queue: IAsyncOperation[] = [];\n private _queueRunning: boolean = false;\n private _sync: FileSystem;\n private _async: FileSystem;\n private _isInitialized: boolean = false;\n private _initializeCallbacks: ((e?: ApiError) => void)[] = [];\n\n /**\n * **Deprecated; use AsyncMirror.Create() method instead.**\n *\n * Mirrors the synchronous file system into the asynchronous file system.\n *\n * **IMPORTANT**: You must call `initialize` on the file system before it can be used.\n * @param sync The synchronous file system to mirror the asynchronous file system to.\n * @param async The asynchronous file system to mirror.\n */\n constructor(sync: FileSystem, async: FileSystem, deprecateMsg = true) {\n super();\n this._sync = sync;\n this._async = async;\n if (!sync.supportsSynch()) {\n throw new Error(\"The first argument to AsyncMirror needs to be a synchronous file system.\");\n }\n deprecationMessage(deprecateMsg, AsyncMirror.Name, { sync: \"sync file system instance\", async: \"async file system instance\"});\n }\n\n public getName(): string {\n return AsyncMirror.Name;\n }\n\n public _syncSync(fd: PreloadFile) {\n this._sync.writeFileSync(fd.getPath(), fd.getBuffer(), null, FileFlag.getFileFlag('w'), fd.getStats().mode);\n this.enqueueOp({\n apiMethod: 'writeFile',\n arguments: [fd.getPath(), fd.getBuffer(), null, fd.getFlag(), fd.getStats().mode]\n });\n }\n\n /**\n * Called once to load up files from async storage into sync storage.\n */\n public initialize(userCb: BFSOneArgCallback, deprecateMsg = true): void {\n if (deprecateMsg) {\n console.warn(`[AsyncMirror] AsyncMirror.initialize() is deprecated and will be removed in the next major version. Please use 'AsyncMirror.Create({ sync: (sync file system instance), async: (async file system instance)}, cb)' to create and initialize AsyncMirror instances.`);\n }\n const callbacks = this._initializeCallbacks;\n\n const end = (e?: ApiError): void => {\n this._isInitialized = !e;\n this._initializeCallbacks = [];\n callbacks.forEach((cb) => cb(e));\n };\n\n if (!this._isInitialized) {\n // First call triggers initialization, the rest wait.\n if (callbacks.push(userCb) === 1) {\n const copyDirectory = (p: string, mode: number, cb: BFSOneArgCallback) => {\n if (p !== '/') {\n this._sync.mkdirSync(p, mode);\n }\n this._async.readdir(p, (err, files) => {\n let i = 0;\n // NOTE: This function must not be in a lexically nested statement,\n // such as an if or while statement. Safari refuses to run the\n // script since it is undefined behavior.\n function copyNextFile(err?: ApiError) {\n if (err) {\n cb(err);\n } else if (i < files!.length) {\n copyItem(path.join(p, files![i]), copyNextFile);\n i++;\n } else {\n cb();\n }\n }\n if (err) {\n cb(err);\n } else {\n copyNextFile();\n }\n });\n }, copyFile = (p: string, mode: number, cb: BFSOneArgCallback) => {\n this._async.readFile(p, null, FileFlag.getFileFlag('r'), (err, data) => {\n if (err) {\n cb(err);\n } else {\n try {\n this._sync.writeFileSync(p, data!, null, FileFlag.getFileFlag('w'), mode);\n } catch (e) {\n err = e;\n } finally {\n cb(err);\n }\n }\n });\n }, copyItem = (p: string, cb: BFSOneArgCallback) => {\n this._async.stat(p, false, (err, stats) => {\n if (err) {\n cb(err);\n } else if (stats!.isDirectory()) {\n copyDirectory(p, stats!.mode, cb);\n } else {\n copyFile(p, stats!.mode, cb);\n }\n });\n };\n copyDirectory('/', 0, end);\n }\n } else {\n userCb();\n }\n }\n\n public isReadOnly(): boolean { return false; }\n public supportsSynch(): boolean { return true; }\n public supportsLinks(): boolean { return false; }\n public supportsProps(): boolean { return this._sync.supportsProps() && this._async.supportsProps(); }\n\n public renameSync(oldPath: string, newPath: string): void {\n this.checkInitialized();\n this._sync.renameSync(oldPath, newPath);\n this.enqueueOp({\n apiMethod: 'rename',\n arguments: [oldPath, newPath]\n });\n }\n\n public statSync(p: string, isLstat: boolean): Stats {\n this.checkInitialized();\n return this._sync.statSync(p, isLstat);\n }\n\n public openSync(p: string, flag: FileFlag, mode: number): File {\n this.checkInitialized();\n // Sanity check: Is this open/close permitted?\n const fd = this._sync.openSync(p, flag, mode);\n fd.closeSync();\n return new MirrorFile(this, p, flag, this._sync.statSync(p, false), this._sync.readFileSync(p, null, FileFlag.getFileFlag('r')));\n }\n\n public unlinkSync(p: string): void {\n this.checkInitialized();\n this._sync.unlinkSync(p);\n this.enqueueOp({\n apiMethod: 'unlink',\n arguments: [p]\n });\n }\n\n public rmdirSync(p: string): void {\n this.checkInitialized();\n this._sync.rmdirSync(p);\n this.enqueueOp({\n apiMethod: 'rmdir',\n arguments: [p]\n });\n }\n\n public mkdirSync(p: string, mode: number): void {\n this.checkInitialized();\n this._sync.mkdirSync(p, mode);\n this.enqueueOp({\n apiMethod: 'mkdir',\n arguments: [p, mode]\n });\n }\n\n public readdirSync(p: string): string[] {\n this.checkInitialized();\n return this._sync.readdirSync(p);\n }\n\n public existsSync(p: string): boolean {\n this.checkInitialized();\n return this._sync.existsSync(p);\n }\n\n public chmodSync(p: string, isLchmod: boolean, mode: number): void {\n this.checkInitialized();\n this._sync.chmodSync(p, isLchmod, mode);\n this.enqueueOp({\n apiMethod: 'chmod',\n arguments: [p, isLchmod, mode]\n });\n }\n\n public chownSync(p: string, isLchown: boolean, uid: number, gid: number): void {\n this.checkInitialized();\n this._sync.chownSync(p, isLchown, uid, gid);\n this.enqueueOp({\n apiMethod: 'chown',\n arguments: [p, isLchown, uid, gid]\n });\n }\n\n public utimesSync(p: string, atime: Date, mtime: Date): void {\n this.checkInitialized();\n this._sync.utimesSync(p, atime, mtime);\n this.enqueueOp({\n apiMethod: 'utimes',\n arguments: [p, atime, mtime]\n });\n }\n\n private checkInitialized(): void {\n if (!this._isInitialized) {\n throw new ApiError(ErrorCode.EPERM, \"AsyncMirrorFS is not initialized. Please initialize AsyncMirrorFS using its initialize() method before using it.\");\n }\n }\n\n private enqueueOp(op: IAsyncOperation) {\n this._queue.push(op);\n if (!this._queueRunning) {\n this._queueRunning = true;\n const doNextOp = (err?: ApiError) => {\n if (err) {\n console.error(`WARNING: File system has desynchronized. Received following error: ${err}\\n$`);\n }\n if (this._queue.length > 0) {\n const op = this._queue.shift()!,\n args = op.arguments;\n args.push(doNextOp);\n ( ( this._async)[op.apiMethod]).apply(this._async, args);\n } else {\n this._queueRunning = false;\n }\n };\n doNextOp();\n }\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ../../../../src/backend/AsyncMirror.ts","import rest from './rest';\n\nexport default function (fn) {\n return rest(function (args/*..., callback*/) {\n var callback = args.pop();\n fn.call(this, args, callback);\n });\n}\n\n\n\n// WEBPACK FOOTER //\n// ../../../../~/async-es/internal/initialParams.js","/** Detect free variable `global` from Node.js. */\nvar freeGlobal = typeof global == 'object' && global && global.Object === Object && global;\n\nexport default freeGlobal;\n\n\n\n// WEBPACK FOOTER //\n// ../../../../~/lodash-es/_freeGlobal.js","import freeGlobal from './_freeGlobal.js';\n\n/** Detect free variable `self`. */\nvar freeSelf = typeof self == 'object' && self && self.Object === Object && self;\n\n/** Used as a reference to the global object. */\nvar root = freeGlobal || freeSelf || Function('return this')();\n\nexport default root;\n\n\n\n// WEBPACK FOOTER //\n// ../../../../~/lodash-es/_root.js","import root from './_root.js';\n\n/** Built-in value references. */\nvar Symbol = root.Symbol;\n\nexport default Symbol;\n\n\n\n// WEBPACK FOOTER //\n// ../../../../~/lodash-es/_Symbol.js","// A temporary value used to identify if the loop should be broken.\n// See #1064, #1293\nexport default {};\n\n\n// WEBPACK FOOTER //\n// ../../../../~/async-es/internal/breakLoop.js","var iteratorSymbol = typeof Symbol === 'function' && Symbol.iterator;\n\nexport default function (coll) {\n return iteratorSymbol && coll[iteratorSymbol] && coll[iteratorSymbol]();\n}\n\n\n\n// WEBPACK FOOTER //\n// ../../../../~/async-es/internal/getIterator.js","import baseIsArguments from './_baseIsArguments.js';\nimport isObjectLike from './isObjectLike.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/** Built-in value references. */\nvar propertyIsEnumerable = objectProto.propertyIsEnumerable;\n\n/**\n * Checks if `value` is likely an `arguments` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an `arguments` object,\n * else `false`.\n * @example\n *\n * _.isArguments(function() { return arguments; }());\n * // => true\n *\n * _.isArguments([1, 2, 3]);\n * // => false\n */\nvar isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {\n return isObjectLike(value) && hasOwnProperty.call(value, 'callee') &&\n !propertyIsEnumerable.call(value, 'callee');\n};\n\nexport default isArguments;\n\n\n\n// WEBPACK FOOTER //\n// ../../../../~/lodash-es/isArguments.js","/**\n * Checks if `value` is classified as an `Array` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array, else `false`.\n * @example\n *\n * _.isArray([1, 2, 3]);\n * // => true\n *\n * _.isArray(document.body.children);\n * // => false\n *\n * _.isArray('abc');\n * // => false\n *\n * _.isArray(_.noop);\n * // => false\n */\nvar isArray = Array.isArray;\n\nexport default isArray;\n\n\n\n// WEBPACK FOOTER //\n// ../../../../~/lodash-es/isArray.js","import root from './_root.js';\nimport stubFalse from './stubFalse.js';\n\n/** Detect free variable `exports`. */\nvar freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;\n\n/** Detect free variable `module`. */\nvar freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;\n\n/** Detect the popular CommonJS extension `module.exports`. */\nvar moduleExports = freeModule && freeModule.exports === freeExports;\n\n/** Built-in value references. */\nvar Buffer = moduleExports ? root.Buffer : undefined;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;\n\n/**\n * Checks if `value` is a buffer.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.\n * @example\n *\n * _.isBuffer(new Buffer(2));\n * // => true\n *\n * _.isBuffer(new Uint8Array(2));\n * // => false\n */\nvar isBuffer = nativeIsBuffer || stubFalse;\n\nexport default isBuffer;\n\n\n\n// WEBPACK FOOTER //\n// ../../../../~/lodash-es/isBuffer.js","import freeGlobal from './_freeGlobal.js';\n\n/** Detect free variable `exports`. */\nvar freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;\n\n/** Detect free variable `module`. */\nvar freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;\n\n/** Detect the popular CommonJS extension `module.exports`. */\nvar moduleExports = freeModule && freeModule.exports === freeExports;\n\n/** Detect free variable `process` from Node.js. */\nvar freeProcess = moduleExports && freeGlobal.process;\n\n/** Used to access faster Node.js helpers. */\nvar nodeUtil = (function() {\n try {\n return freeProcess && freeProcess.binding && freeProcess.binding('util');\n } catch (e) {}\n}());\n\nexport default nodeUtil;\n\n\n\n// WEBPACK FOOTER //\n// ../../../../~/lodash-es/_nodeUtil.js","import baseIsTypedArray from './_baseIsTypedArray.js';\nimport baseUnary from './_baseUnary.js';\nimport nodeUtil from './_nodeUtil.js';\n\n/* Node.js helper references. */\nvar nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;\n\n/**\n * Checks if `value` is classified as a typed array.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.\n * @example\n *\n * _.isTypedArray(new Uint8Array);\n * // => true\n *\n * _.isTypedArray([]);\n * // => false\n */\nvar isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;\n\nexport default isTypedArray;\n\n\n\n// WEBPACK FOOTER //\n// ../../../../~/lodash-es/isTypedArray.js","import overArg from './_overArg.js';\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeKeys = overArg(Object.keys, Object);\n\nexport default nativeKeys;\n\n\n\n// WEBPACK FOOTER //\n// ../../../../~/lodash-es/_nativeKeys.js","import doParallel from './internal/doParallel';\nimport map from './internal/map';\n\n/**\n * Produces a new collection of values by mapping each value in `coll` through\n * the `iteratee` function. The `iteratee` is called with an item from `coll`\n * and a callback for when it has finished processing. Each of these callback\n * takes 2 arguments: an `error`, and the transformed item from `coll`. If\n * `iteratee` passes an error to its callback, the main `callback` (for the\n * `map` function) is immediately called with the error.\n *\n * Note, that since this function applies the `iteratee` to each item in\n * parallel, there is no guarantee that the `iteratee` functions will complete\n * in order. However, the results array will be in the same order as the\n * original `coll`.\n *\n * If `map` is passed an Object, the results will be an Array. The results\n * will roughly be in the order of the original Objects' keys (but this can\n * vary across JavaScript engines)\n *\n * @name map\n * @static\n * @memberOf module:Collections\n * @method\n * @category Collection\n * @param {Array|Iterable|Object} coll - A collection to iterate over.\n * @param {Function} iteratee - A function to apply to each item in `coll`.\n * The iteratee is passed a `callback(err, transformed)` which must be called\n * once it has completed with an error (which can be `null`) and a\n * transformed item. Invoked with (item, callback).\n * @param {Function} [callback] - A callback which is called when all `iteratee`\n * functions have finished, or an error occurs. Results is an Array of the\n * transformed items from the `coll`. Invoked with (err, results).\n * @example\n *\n * async.map(['file1','file2','file3'], fs.stat, function(err, results) {\n * // results is now an array of stats for each file\n * });\n */\nexport default doParallel(map);\n\n\n\n// WEBPACK FOOTER //\n// ../../../../~/async-es/map.js","import applyEach from './internal/applyEach';\nimport map from './map';\n\n/**\n * Applies the provided arguments to each function in the array, calling\n * `callback` after all functions have completed. If you only provide the first\n * argument, `fns`, then it will return a function which lets you pass in the\n * arguments as if it were a single function call. If more arguments are\n * provided, `callback` is required while `args` is still optional.\n *\n * @name applyEach\n * @static\n * @memberOf module:ControlFlow\n * @method\n * @category Control Flow\n * @param {Array|Iterable|Object} fns - A collection of asynchronous functions\n * to all call with the same arguments\n * @param {...*} [args] - any number of separate arguments to pass to the\n * function.\n * @param {Function} [callback] - the final argument should be the callback,\n * called when all functions have completed processing.\n * @returns {Function} - If only the first argument, `fns`, is provided, it will\n * return a function which lets you pass in the arguments as if it were a single\n * function call. The signature is `(..args, callback)`. If invoked with any\n * arguments, `callback` is required.\n * @example\n *\n * async.applyEach([enableSearch, updateSchema], 'bucket', callback);\n *\n * // partial application example:\n * async.each(\n * buckets,\n * async.applyEach([enableSearch, updateSchema]),\n * callback\n * );\n */\nexport default applyEach(map);\n\n\n\n// WEBPACK FOOTER //\n// ../../../../~/async-es/applyEach.js","import doParallelLimit from './internal/doParallelLimit';\nimport map from './internal/map';\n\n/**\n * The same as [`map`]{@link module:Collections.map} but runs a maximum of `limit` async operations at a time.\n *\n * @name mapLimit\n * @static\n * @memberOf module:Collections\n * @method\n * @see [async.map]{@link module:Collections.map}\n * @category Collection\n * @param {Array|Iterable|Object} coll - A collection to iterate over.\n * @param {number} limit - The maximum number of async operations at a time.\n * @param {Function} iteratee - A function to apply to each item in `coll`.\n * The iteratee is passed a `callback(err, transformed)` which must be called\n * once it has completed with an error (which can be `null`) and a transformed\n * item. Invoked with (item, callback).\n * @param {Function} [callback] - A callback which is called when all `iteratee`\n * functions have finished, or an error occurs. Results is an array of the\n * transformed items from the `coll`. Invoked with (err, results).\n */\nexport default doParallelLimit(map);\n\n\n\n// WEBPACK FOOTER //\n// ../../../../~/async-es/mapLimit.js","import mapLimit from './mapLimit';\nimport doLimit from './internal/doLimit';\n\n/**\n * The same as [`map`]{@link module:Collections.map} but runs only a single async operation at a time.\n *\n * @name mapSeries\n * @static\n * @memberOf module:Collections\n * @method\n * @see [async.map]{@link module:Collections.map}\n * @category Collection\n * @param {Array|Iterable|Object} coll - A collection to iterate over.\n * @param {Function} iteratee - A function to apply to each item in `coll`.\n * The iteratee is passed a `callback(err, transformed)` which must be called\n * once it has completed with an error (which can be `null`) and a\n * transformed item. Invoked with (item, callback).\n * @param {Function} [callback] - A callback which is called when all `iteratee`\n * functions have finished, or an error occurs. Results is an array of the\n * transformed items from the `coll`. Invoked with (err, results).\n */\nexport default doLimit(mapLimit, 1);\n\n\n\n// WEBPACK FOOTER //\n// ../../../../~/async-es/mapSeries.js","import applyEach from './internal/applyEach';\nimport mapSeries from './mapSeries';\n\n/**\n * The same as [`applyEach`]{@link module:ControlFlow.applyEach} but runs only a single async operation at a time.\n *\n * @name applyEachSeries\n * @static\n * @memberOf module:ControlFlow\n * @method\n * @see [async.applyEach]{@link module:ControlFlow.applyEach}\n * @category Control Flow\n * @param {Array|Iterable|Object} fns - A collection of asynchronous functions to all\n * call with the same arguments\n * @param {...*} [args] - any number of separate arguments to pass to the\n * function.\n * @param {Function} [callback] - the final argument should be the callback,\n * called when all functions have completed processing.\n * @returns {Function} - If only the first argument is provided, it will return\n * a function which lets you pass in the arguments as if it were a single\n * function call.\n */\nexport default applyEach(mapSeries);\n\n\n\n// WEBPACK FOOTER //\n// ../../../../~/async-es/applyEachSeries.js","import rest from './internal/rest';\n\n/**\n * Creates a continuation function with some arguments already applied.\n *\n * Useful as a shorthand when combined with other control flow functions. Any\n * arguments passed to the returned function are added to the arguments\n * originally passed to apply.\n *\n * @name apply\n * @static\n * @memberOf module:Utils\n * @method\n * @category Util\n * @param {Function} function - The function you want to eventually apply all\n * arguments to. Invokes with (arguments...).\n * @param {...*} arguments... - Any number of arguments to automatically apply\n * when the continuation is called.\n * @example\n *\n * // using apply\n * async.parallel([\n * async.apply(fs.writeFile, 'testfile1', 'test1'),\n * async.apply(fs.writeFile, 'testfile2', 'test2')\n * ]);\n *\n *\n * // the same process without using apply\n * async.parallel([\n * function(callback) {\n * fs.writeFile('testfile1', 'test1', callback);\n * },\n * function(callback) {\n * fs.writeFile('testfile2', 'test2', callback);\n * }\n * ]);\n *\n * // It's possible to pass any number of additional arguments when calling the\n * // continuation:\n *\n * node> var fn = async.apply(sys.puts, 'one');\n * node> fn('two', 'three');\n * one\n * two\n * three\n */\nexport default rest(function(fn, args) {\n return rest(function(callArgs) {\n return fn.apply(null, args.concat(callArgs));\n });\n});\n\n\n\n// WEBPACK FOOTER //\n// ../../../../~/async-es/apply.js","import createBaseFor from './_createBaseFor.js';\n\n/**\n * The base implementation of `baseForOwn` which iterates over `object`\n * properties returned by `keysFunc` and invokes `iteratee` for each property.\n * Iteratee functions may exit iteration early by explicitly returning `false`.\n *\n * @private\n * @param {Object} object The object to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @param {Function} keysFunc The function to get the keys of `object`.\n * @returns {Object} Returns `object`.\n */\nvar baseFor = createBaseFor();\n\nexport default baseFor;\n\n\n\n// WEBPACK FOOTER //\n// ../../../../~/lodash-es/_baseFor.js","/** Used to compose unicode character classes. */\nvar rsAstralRange = '\\\\ud800-\\\\udfff',\n rsComboMarksRange = '\\\\u0300-\\\\u036f',\n reComboHalfMarksRange = '\\\\ufe20-\\\\ufe2f',\n rsComboSymbolsRange = '\\\\u20d0-\\\\u20ff',\n rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,\n rsVarRange = '\\\\ufe0e\\\\ufe0f';\n\n/** Used to compose unicode capture groups. */\nvar rsAstral = '[' + rsAstralRange + ']',\n rsCombo = '[' + rsComboRange + ']',\n rsFitz = '\\\\ud83c[\\\\udffb-\\\\udfff]',\n rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',\n rsNonAstral = '[^' + rsAstralRange + ']',\n rsRegional = '(?:\\\\ud83c[\\\\udde6-\\\\uddff]){2}',\n rsSurrPair = '[\\\\ud800-\\\\udbff][\\\\udc00-\\\\udfff]',\n rsZWJ = '\\\\u200d';\n\n/** Used to compose unicode regexes. */\nvar reOptMod = rsModifier + '?',\n rsOptVar = '[' + rsVarRange + ']?',\n rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',\n rsSeq = rsOptVar + reOptMod + rsOptJoin,\n rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';\n\n/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */\nvar reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');\n\n/**\n * Converts a Unicode `string` to an array.\n *\n * @private\n * @param {string} string The string to convert.\n * @returns {Array} Returns the converted array.\n */\nfunction unicodeToArray(string) {\n return string.match(reUnicode) || [];\n}\n\nexport default unicodeToArray;\n\n\n\n// WEBPACK FOOTER //\n// ../../../../~/lodash-es/_unicodeToArray.js","import eachOfLimit from './eachOfLimit';\nimport doLimit from './internal/doLimit';\n\n/**\n * The same as [`eachOf`]{@link module:Collections.eachOf} but runs only a single async operation at a time.\n *\n * @name eachOfSeries\n * @static\n * @memberOf module:Collections\n * @method\n * @see [async.eachOf]{@link module:Collections.eachOf}\n * @alias forEachOfSeries\n * @category Collection\n * @param {Array|Iterable|Object} coll - A collection to iterate over.\n * @param {Function} iteratee - A function to apply to each item in `coll`. The\n * `key` is the item's key, or index in the case of an array. The iteratee is\n * passed a `callback(err)` which must be called once it has completed. If no\n * error has occurred, the callback should be run without arguments or with an\n * explicit `null` argument. Invoked with (item, key, callback).\n * @param {Function} [callback] - A callback which is called when all `iteratee`\n * functions have finished, or an error occurs. Invoked with (err).\n */\nexport default doLimit(eachOfLimit, 1);\n\n\n\n// WEBPACK FOOTER //\n// ../../../../~/async-es/eachOfSeries.js","import noop from 'lodash-es/noop';\nimport rest from './internal/rest';\nimport reduce from './reduce';\n\n/**\n * Version of the compose function that is more natural to read. Each function\n * consumes the return value of the previous function. It is the equivalent of\n * [compose]{@link module:ControlFlow.compose} with the arguments reversed.\n *\n * Each function is executed with the `this` binding of the composed function.\n *\n * @name seq\n * @static\n * @memberOf module:ControlFlow\n * @method\n * @see [async.compose]{@link module:ControlFlow.compose}\n * @category Control Flow\n * @param {...Function} functions - the asynchronous functions to compose\n * @returns {Function} a function that composes the `functions` in order\n * @example\n *\n * // Requires lodash (or underscore), express3 and dresende's orm2.\n * // Part of an app, that fetches cats of the logged user.\n * // This example uses `seq` function to avoid overnesting and error\n * // handling clutter.\n * app.get('/cats', function(request, response) {\n * var User = request.models.User;\n * async.seq(\n * _.bind(User.get, User), // 'User.get' has signature (id, callback(err, data))\n * function(user, fn) {\n * user.getCats(fn); // 'getCats' has signature (callback(err, data))\n * }\n * )(req.session.user_id, function (err, cats) {\n * if (err) {\n * console.error(err);\n * response.json({ status: 'error', message: err.message });\n * } else {\n * response.json({ status: 'ok', message: 'Cats found', data: cats });\n * }\n * });\n * });\n */\nexport default rest(function seq(functions) {\n return rest(function(args) {\n var that = this;\n\n var cb = args[args.length - 1];\n if (typeof cb == 'function') {\n args.pop();\n } else {\n cb = noop;\n }\n\n reduce(functions, args, function(newargs, fn, cb) {\n fn.apply(that, newargs.concat(rest(function(err, nextargs) {\n cb(err, nextargs);\n })));\n },\n function(err, results) {\n cb.apply(that, [err].concat(results));\n });\n });\n})\n\n\n\n// WEBPACK FOOTER //\n// ../../../../~/async-es/seq.js","import seq from './seq';\nimport rest from './internal/rest';\n\n/**\n * Creates a function which is a composition of the passed asynchronous\n * functions. Each function consumes the return value of the function that\n * follows. Composing functions `f()`, `g()`, and `h()` would produce the result\n * of `f(g(h()))`, only this version uses callbacks to obtain the return values.\n *\n * Each function is executed with the `this` binding of the composed function.\n *\n * @name compose\n * @static\n * @memberOf module:ControlFlow\n * @method\n * @category Control Flow\n * @param {...Function} functions - the asynchronous functions to compose\n * @returns {Function} an asynchronous function that is the composed\n * asynchronous `functions`\n * @example\n *\n * function add1(n, callback) {\n * setTimeout(function () {\n * callback(null, n + 1);\n * }, 10);\n * }\n *\n * function mul3(n, callback) {\n * setTimeout(function () {\n * callback(null, n * 3);\n * }, 10);\n * }\n *\n * var add1mul3 = async.compose(mul3, add1);\n * add1mul3(4, function (err, result) {\n * // result now equals 15\n * });\n */\nexport default rest(function(args) {\n return seq.apply(null, args.reverse());\n});\n\n\n\n// WEBPACK FOOTER //\n// ../../../../~/async-es/compose.js","import rest from './internal/rest';\nimport initialParams from './internal/initialParams';\n\n/**\n * Returns a function that when called, calls-back with the values provided.\n * Useful as the first function in a [`waterfall`]{@link module:ControlFlow.waterfall}, or for plugging values in to\n * [`auto`]{@link module:ControlFlow.auto}.\n *\n * @name constant\n * @static\n * @memberOf module:Utils\n * @method\n * @category Util\n * @param {...*} arguments... - Any number of arguments to automatically invoke\n * callback with.\n * @returns {Function} Returns a function that when invoked, automatically\n * invokes the callback with the previous given arguments.\n * @example\n *\n * async.waterfall([\n * async.constant(42),\n * function (value, next) {\n * // value === 42\n * },\n * //...\n * ], callback);\n *\n * async.waterfall([\n * async.constant(filename, \"utf8\"),\n * fs.readFile,\n * function (fileData, next) {\n * //...\n * }\n * //...\n * ], callback);\n *\n * async.auto({\n * hostname: async.constant(\"https://server.net/\"),\n * port: findFreePort,\n * launchServer: [\"hostname\", \"port\", function (options, cb) {\n * startServer(options, cb);\n * }],\n * //...\n * }, callback);\n */\nexport default rest(function(values) {\n var args = [null].concat(values);\n return initialParams(function (ignoredArgs, callback) {\n return callback.apply(this, args);\n });\n});\n\n\n\n// WEBPACK FOOTER //\n// ../../../../~/async-es/constant.js","import consoleFunc from './internal/consoleFunc';\n\n/**\n * Logs the result of an `async` function to the `console` using `console.dir`\n * to display the properties of the resulting object. Only works in Node.js or\n * in browsers that support `console.dir` and `console.error` (such as FF and\n * Chrome). If multiple arguments are returned from the async function,\n * `console.dir` is called on each argument in order.\n *\n * @name dir\n * @static\n * @memberOf module:Utils\n * @method\n * @category Util\n * @param {Function} function - The function you want to eventually apply all\n * arguments to.\n * @param {...*} arguments... - Any number of arguments to apply to the function.\n * @example\n *\n * // in a module\n * var hello = function(name, callback) {\n * setTimeout(function() {\n * callback(null, {hello: name});\n * }, 1000);\n * };\n *\n * // in the node repl\n * node> async.dir(hello, 'world');\n * {hello: 'world'}\n */\nexport default consoleFunc('dir');\n\n\n\n// WEBPACK FOOTER //\n// ../../../../~/async-es/dir.js","import consoleFunc from './internal/consoleFunc';\n\n/**\n * Logs the result of an `async` function to the `console`. Only works in\n * Node.js or in browsers that support `console.log` and `console.error` (such\n * as FF and Chrome). If multiple arguments are returned from the async\n * function, `console.log` is called on each argument in order.\n *\n * @name log\n * @static\n * @memberOf module:Utils\n * @method\n * @category Util\n * @param {Function} function - The function you want to eventually apply all\n * arguments to.\n * @param {...*} arguments... - Any number of arguments to apply to the function.\n * @example\n *\n * // in a module\n * var hello = function(name, callback) {\n * setTimeout(function() {\n * callback(null, 'hello ' + name);\n * }, 1000);\n * };\n *\n * // in the node repl\n * node> async.log(hello, 'world');\n * 'hello world'\n */\nexport default consoleFunc('log');\n\n\n\n// WEBPACK FOOTER //\n// ../../../../~/async-es/log.js","'use strict';\n\nimport { hasNextTick, hasSetImmediate, fallback, wrap } from './internal/setImmediate';\n\n/**\n * Calls `callback` on a later loop around the event loop. In Node.js this just\n * calls `setImmediate`. In the browser it will use `setImmediate` if\n * available, otherwise `setTimeout(callback, 0)`, which means other higher\n * priority events may precede the execution of `callback`.\n *\n * This is used internally for browser-compatibility purposes.\n *\n * @name nextTick\n * @static\n * @memberOf module:Utils\n * @method\n * @alias setImmediate\n * @category Util\n * @param {Function} callback - The function to call on a later loop around\n * the event loop. Invoked with (args...).\n * @param {...*} args... - any number of additional arguments to pass to the\n * callback on the next tick.\n * @example\n *\n * var call_order = [];\n * async.nextTick(function() {\n * call_order.push('two');\n * // call_order now equals ['one','two']\n * });\n * call_order.push('one');\n *\n * async.setImmediate(function (a, b, c) {\n * // a, b, and c equal 1, 2, and 3\n * }, 1, 2, 3);\n */\nvar _defer;\n\nif (hasNextTick) {\n _defer = process.nextTick;\n} else if (hasSetImmediate) {\n _defer = setImmediate;\n} else {\n _defer = fallback;\n}\n\nexport default wrap(_defer);\n\n\n\n// WEBPACK FOOTER //\n// ../../../../~/async-es/nextTick.js","/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeCeil = Math.ceil,\n nativeMax = Math.max;\n\n/**\n * The base implementation of `_.range` and `_.rangeRight` which doesn't\n * coerce arguments.\n *\n * @private\n * @param {number} start The start of the range.\n * @param {number} end The end of the range.\n * @param {number} step The value to increment or decrement by.\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {Array} Returns the range of numbers.\n */\nfunction baseRange(start, end, step, fromRight) {\n var index = -1,\n length = nativeMax(nativeCeil((end - start) / (step || 1)), 0),\n result = Array(length);\n\n while (length--) {\n result[fromRight ? length : ++index] = start;\n start += step;\n }\n return result;\n}\n\nexport default baseRange;\n\n\n\n// WEBPACK FOOTER //\n// ../../../../~/lodash-es/_baseRange.js","/**\n * Exports the global scope variable.\n * In the main browser thread, this is \"window\".\n * In a WebWorker, this is \"self\".\n * In Node, this is \"global\".\n * @hidden\n * @private\n */\ndeclare var global: any;\n/**\n * @hidden\n */\nlet toExport: any;\nif (typeof(window) !== 'undefined') {\n toExport = window;\n} else if (typeof(self) !== 'undefined') {\n toExport = self;\n} else {\n toExport = global;\n}\nexport default toExport;\n\n\n\n// WEBPACK FOOTER //\n// ../../../../src/core/global.ts","import {default as Stats, FileType} from '../core/node_fs_stats';\n\n/**\n * Generic inode definition that can easily be serialized.\n */\nexport default class Inode {\n /**\n * Converts the buffer into an Inode.\n */\n public static fromBuffer(buffer: Buffer): Inode {\n if (buffer === undefined) {\n throw new Error(\"NO\");\n }\n return new Inode(buffer.toString('ascii', 30),\n buffer.readUInt32LE(0),\n buffer.readUInt16LE(4),\n buffer.readDoubleLE(6),\n buffer.readDoubleLE(14),\n buffer.readDoubleLE(22)\n );\n }\n\n constructor(public id: string,\n public size: number,\n public mode: number,\n public atime: number,\n public mtime: number,\n public ctime: number) { }\n\n /**\n * Handy function that converts the Inode to a Node Stats object.\n */\n public toStats(): Stats {\n return new Stats(\n (this.mode & 0xF000) === FileType.DIRECTORY ? FileType.DIRECTORY : FileType.FILE,\n this.size, this.mode, new Date(this.atime), new Date(this.mtime), new Date(this.ctime));\n }\n\n /**\n * Get the size of this Inode, in bytes.\n */\n public getSize(): number {\n // ASSUMPTION: ID is ASCII (1 byte per char).\n return 30 + this.id.length;\n }\n\n /**\n * Writes the inode into the start of the buffer.\n */\n public toBuffer(buff: Buffer = Buffer.alloc(this.getSize())): Buffer {\n buff.writeUInt32LE(this.size, 0);\n buff.writeUInt16LE(this.mode, 4);\n buff.writeDoubleLE(this.atime, 6);\n buff.writeDoubleLE(this.mtime, 14);\n buff.writeDoubleLE(this.ctime, 22);\n buff.write(this.id, 30, this.id.length, 'ascii');\n return buff;\n }\n\n /**\n * Updates the Inode using information from the stats object. Used by file\n * systems at sync time, e.g.:\n * - Program opens file and gets a File object.\n * - Program mutates file. File object is responsible for maintaining\n * metadata changes locally -- typically in a Stats object.\n * - Program closes file. File object's metadata changes are synced with the\n * file system.\n * @return True if any changes have occurred.\n */\n public update(stats: Stats): boolean {\n let hasChanged = false;\n if (this.size !== stats.size) {\n this.size = stats.size;\n hasChanged = true;\n }\n\n if (this.mode !== stats.mode) {\n this.mode = stats.mode;\n hasChanged = true;\n }\n\n const atimeMs = stats.atime.getTime();\n if (this.atime !== atimeMs) {\n this.atime = atimeMs;\n hasChanged = true;\n }\n\n const mtimeMs = stats.mtime.getTime();\n if (this.mtime !== mtimeMs) {\n this.mtime = mtimeMs;\n hasChanged = true;\n }\n\n const ctimeMs = stats.ctime.getTime();\n if (this.ctime !== ctimeMs) {\n this.ctime = ctimeMs;\n hasChanged = true;\n }\n\n return hasChanged;\n }\n\n // XXX: Copied from Stats. Should reconcile these two into something more\n // compact.\n\n /**\n * @return [Boolean] True if this item is a file.\n */\n public isFile(): boolean {\n return (this.mode & 0xF000) === FileType.FILE;\n }\n\n /**\n * @return [Boolean] True if this item is a directory.\n */\n public isDirectory(): boolean {\n return (this.mode & 0xF000) === FileType.DIRECTORY;\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ../../../../src/generic/inode.ts","import {BFSCallback, FileSystemOptions} from '../core/file_system';\nimport {SyncKeyValueStore, SimpleSyncStore, SimpleSyncRWTransaction, SyncKeyValueRWTransaction, SyncKeyValueFileSystem} from '../generic/key_value_filesystem';\n\n/**\n * A simple in-memory key-value store backed by a JavaScript object.\n */\nexport class InMemoryStore implements SyncKeyValueStore, SimpleSyncStore {\n private store: { [key: string]: Buffer } = {};\n\n public name() { return InMemoryFileSystem.Name; }\n public clear() { this.store = {}; }\n\n public beginTransaction(type: string): SyncKeyValueRWTransaction {\n return new SimpleSyncRWTransaction(this);\n }\n\n public get(key: string): Buffer {\n return this.store[key];\n }\n\n public put(key: string, data: Buffer, overwrite: boolean): boolean {\n if (!overwrite && this.store.hasOwnProperty(key)) {\n return false;\n }\n this.store[key] = data;\n return true;\n }\n\n public del(key: string): void {\n delete this.store[key];\n }\n}\n\n/**\n * A simple in-memory file system backed by an InMemoryStore.\n * Files are not persisted across page loads.\n */\nexport default class InMemoryFileSystem extends SyncKeyValueFileSystem {\n public static readonly Name = \"InMemory\";\n\n public static readonly Options: FileSystemOptions = {};\n\n /**\n * Creates an InMemoryFileSystem instance.\n */\n public static Create(options: any, cb: BFSCallback): void {\n cb(null, new InMemoryFileSystem());\n }\n constructor() {\n super({ store: new InMemoryStore() });\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ../../../../src/backend/InMemory.ts","import {BFSCallback, FileSystemOptions} from '../core/file_system';\nimport {SyncKeyValueStore, SimpleSyncStore, SyncKeyValueFileSystem, SimpleSyncRWTransaction, SyncKeyValueRWTransaction} from '../generic/key_value_filesystem';\nimport {ApiError, ErrorCode} from '../core/api_error';\nimport global from '../core/global';\n\n/**\n * Some versions of FF and all versions of IE do not support the full range of\n * 16-bit numbers encoded as characters, as they enforce UTF-16 restrictions.\n * @url http://stackoverflow.com/questions/11170716/are-there-any-characters-that-are-not-allowed-in-localstorage/11173673#11173673\n * @hidden\n */\nlet supportsBinaryString: boolean = false,\n binaryEncoding: string;\ntry {\n global.localStorage.setItem(\"__test__\", String.fromCharCode(0xD800));\n supportsBinaryString = global.localStorage.getItem(\"__test__\") === String.fromCharCode(0xD800);\n} catch (e) {\n // IE throws an exception.\n supportsBinaryString = false;\n}\nbinaryEncoding = supportsBinaryString ? 'binary_string' : 'binary_string_ie';\nif (!Buffer.isEncoding(binaryEncoding)) {\n // Fallback for non BrowserFS implementations of buffer that lack a\n // binary_string format.\n binaryEncoding = \"base64\";\n}\n\n/**\n * A synchronous key-value store backed by localStorage.\n */\nexport class LocalStorageStore implements SyncKeyValueStore, SimpleSyncStore {\n public name(): string {\n return LocalStorageFileSystem.Name;\n }\n\n public clear(): void {\n global.localStorage.clear();\n }\n\n public beginTransaction(type: string): SyncKeyValueRWTransaction {\n // No need to differentiate.\n return new SimpleSyncRWTransaction(this);\n }\n\n public get(key: string): Buffer | undefined {\n try {\n const data = global.localStorage.getItem(key);\n if (data !== null) {\n return Buffer.from(data, binaryEncoding);\n }\n } catch (e) {\n // Do nothing.\n }\n // Key doesn't exist, or a failure occurred.\n return undefined;\n }\n\n public put(key: string, data: Buffer, overwrite: boolean): boolean {\n try {\n if (!overwrite && global.localStorage.getItem(key) !== null) {\n // Don't want to overwrite the key!\n return false;\n }\n global.localStorage.setItem(key, data.toString(binaryEncoding));\n return true;\n } catch (e) {\n throw new ApiError(ErrorCode.ENOSPC, \"LocalStorage is full.\");\n }\n }\n\n public del(key: string): void {\n try {\n global.localStorage.removeItem(key);\n } catch (e) {\n throw new ApiError(ErrorCode.EIO, \"Unable to delete key \" + key + \": \" + e);\n }\n }\n}\n\n/**\n * A synchronous file system backed by localStorage. Connects our\n * LocalStorageStore to our SyncKeyValueFileSystem.\n */\nexport default class LocalStorageFileSystem extends SyncKeyValueFileSystem {\n public static readonly Name = \"LocalStorage\";\n\n public static readonly Options: FileSystemOptions = {};\n\n /**\n * Creates a LocalStorageFileSystem instance.\n */\n public static Create(options: any, cb: BFSCallback): void {\n cb(null, new LocalStorageFileSystem());\n }\n public static isAvailable(): boolean {\n return typeof global.localStorage !== 'undefined';\n }\n /**\n * Creates a new LocalStorage file system using the contents of `localStorage`.\n */\n constructor() { super({ store: new LocalStorageStore() }); }\n}\n\n\n\n// WEBPACK FOOTER //\n// ../../../../src/backend/LocalStorage.ts","import global from '../core/global';\n\n/**\n * @hidden\n */\nlet bfsSetImmediate: (cb: Function) => any;\nif (typeof(setImmediate) !== \"undefined\") {\n bfsSetImmediate = setImmediate;\n} else {\n const gScope = global;\n const timeouts: (() => void)[] = [];\n const messageName = \"zero-timeout-message\";\n const canUsePostMessage = function() {\n if (typeof gScope.importScripts !== 'undefined' || !gScope.postMessage) {\n return false;\n }\n let postMessageIsAsync = true;\n const oldOnMessage = gScope.onmessage;\n gScope.onmessage = function() {\n postMessageIsAsync = false;\n };\n gScope.postMessage('', '*');\n gScope.onmessage = oldOnMessage;\n return postMessageIsAsync;\n };\n if (canUsePostMessage()) {\n bfsSetImmediate = function(fn: () => void) {\n timeouts.push(fn);\n gScope.postMessage(messageName, \"*\");\n };\n const handleMessage = function(event: MessageEvent) {\n if (event.source === self && event.data === messageName) {\n if (event.stopPropagation) {\n event.stopPropagation();\n } else {\n event.cancelBubble = true;\n }\n if (timeouts.length > 0) {\n const fn = timeouts.shift()!;\n return fn();\n }\n }\n };\n if (gScope.addEventListener) {\n gScope.addEventListener('message', handleMessage, true);\n } else {\n gScope.attachEvent('onmessage', handleMessage);\n }\n } else if (gScope.MessageChannel) {\n // WebWorker MessageChannel\n const channel = new gScope.MessageChannel();\n channel.port1.onmessage = (event: any) => {\n if (timeouts.length > 0) {\n return timeouts.shift()!();\n }\n };\n bfsSetImmediate = (fn: () => void) => {\n timeouts.push(fn);\n channel.port2.postMessage('');\n };\n } else {\n bfsSetImmediate = function(fn: () => void) {\n return setTimeout(fn, 0);\n };\n }\n}\n\nexport default bfsSetImmediate;\n\n\n\n// WEBPACK FOOTER //\n// ../../../../src/generic/setImmediate.ts","import setImmediate from '../generic/setImmediate';\n\n/**\n * Non-recursive mutex\n * @hidden\n */\nexport default class Mutex {\n private _locked: boolean = false;\n private _waiters: Function[] = [];\n\n public lock(cb: Function): void {\n if (this._locked) {\n this._waiters.push(cb);\n return;\n }\n this._locked = true;\n cb();\n }\n\n public unlock(): void {\n if (!this._locked) {\n throw new Error('unlock of a non-locked mutex');\n }\n\n const next = this._waiters.shift();\n // don't unlock - we want to queue up next for the\n // _end_ of the current task execution, but we don't\n // want it to be called inline with whatever the\n // current stack is. This way we still get the nice\n // behavior that an unlock immediately followed by a\n // lock won't cause starvation.\n if (next) {\n setImmediate(next);\n return;\n }\n\n this._locked = false;\n }\n\n public tryLock(): boolean {\n if (this._locked) {\n return false;\n }\n\n this._locked = true;\n return true;\n }\n\n public isLocked(): boolean {\n return this._locked;\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ../../../../src/generic/mutex.ts","import Mutex from './mutex';\nimport {FileSystem, BFSOneArgCallback, BFSCallback} from '../core/file_system';\nimport {ApiError} from '../core/api_error';\nimport {FileFlag} from '../core/file_flag';\nimport {default as Stats} from '../core/node_fs_stats';\nimport {File} from '../core/file';\n\n/**\n * This class serializes access to an underlying async filesystem.\n * For example, on an OverlayFS instance with an async lower\n * directory operations like rename and rmdir may involve multiple\n * requests involving both the upper and lower filesystems -- they\n * are not executed in a single atomic step. OverlayFS uses this\n * LockedFS to avoid having to reason about the correctness of\n * multiple requests interleaving.\n */\nexport default class LockedFS implements FileSystem {\n private _fs: T;\n private _mu: Mutex;\n\n constructor(fs: T) {\n this._fs = fs;\n this._mu = new Mutex();\n }\n\n public getName(): string {\n return 'LockedFS<' + this._fs.getName() + '>';\n }\n\n public getFSUnlocked(): T {\n return this._fs;\n }\n\n public initialize(cb: BFSOneArgCallback): void {\n // FIXME: check to see if FS supports initialization\n ( this._fs).initialize(cb);\n }\n\n public diskSpace(p: string, cb: (total: number, free: number) => any): void {\n // FIXME: should this lock?\n this._fs.diskSpace(p, cb);\n }\n\n public isReadOnly(): boolean {\n return this._fs.isReadOnly();\n }\n\n public supportsLinks(): boolean {\n return this._fs.supportsLinks();\n }\n\n public supportsProps(): boolean {\n return this._fs.supportsProps();\n }\n\n public supportsSynch(): boolean {\n return this._fs.supportsSynch();\n }\n\n public rename(oldPath: string, newPath: string, cb: BFSOneArgCallback): void {\n this._mu.lock(() => {\n this._fs.rename(oldPath, newPath, (err?: ApiError) => {\n this._mu.unlock();\n cb(err);\n });\n });\n }\n\n public renameSync(oldPath: string, newPath: string): void {\n if (this._mu.isLocked()) {\n throw new Error('invalid sync call');\n }\n return this._fs.renameSync(oldPath, newPath);\n }\n\n public stat(p: string, isLstat: boolean, cb: BFSCallback): void {\n this._mu.lock(() => {\n this._fs.stat(p, isLstat, (err?: ApiError, stat?: Stats) => {\n this._mu.unlock();\n cb(err, stat);\n });\n });\n }\n\n public statSync(p: string, isLstat: boolean): Stats {\n if (this._mu.isLocked()) {\n throw new Error('invalid sync call');\n }\n return this._fs.statSync(p, isLstat);\n }\n\n public open(p: string, flag: FileFlag, mode: number, cb: BFSCallback): void {\n this._mu.lock(() => {\n this._fs.open(p, flag, mode, (err?: ApiError, fd?: File) => {\n this._mu.unlock();\n cb(err, fd);\n });\n });\n }\n\n public openSync(p: string, flag: FileFlag, mode: number): File {\n if (this._mu.isLocked()) {\n throw new Error('invalid sync call');\n }\n return this._fs.openSync(p, flag, mode);\n }\n\n public unlink(p: string, cb: BFSOneArgCallback): void {\n this._mu.lock(() => {\n this._fs.unlink(p, (err?: ApiError) => {\n this._mu.unlock();\n cb(err);\n });\n });\n }\n\n public unlinkSync(p: string): void {\n if (this._mu.isLocked()) {\n throw new Error('invalid sync call');\n }\n return this._fs.unlinkSync(p);\n }\n\n public rmdir(p: string, cb: BFSOneArgCallback): void {\n this._mu.lock(() => {\n this._fs.rmdir(p, (err?: ApiError) => {\n this._mu.unlock();\n cb(err);\n });\n });\n }\n\n public rmdirSync(p: string): void {\n if (this._mu.isLocked()) {\n throw new Error('invalid sync call');\n }\n return this._fs.rmdirSync(p);\n }\n\n public mkdir(p: string, mode: number, cb: BFSOneArgCallback): void {\n this._mu.lock(() => {\n this._fs.mkdir(p, mode, (err?: ApiError) => {\n this._mu.unlock();\n cb(err);\n });\n });\n }\n\n public mkdirSync(p: string, mode: number): void {\n if (this._mu.isLocked()) {\n throw new Error('invalid sync call');\n }\n return this._fs.mkdirSync(p, mode);\n }\n\n public readdir(p: string, cb: BFSCallback): void {\n this._mu.lock(() => {\n this._fs.readdir(p, (err?: ApiError, files?: string[]) => {\n this._mu.unlock();\n cb(err, files);\n });\n });\n }\n\n public readdirSync(p: string): string[] {\n if (this._mu.isLocked()) {\n throw new Error('invalid sync call');\n }\n return this._fs.readdirSync(p);\n }\n\n public exists(p: string, cb: (exists: boolean) => void): void {\n this._mu.lock(() => {\n this._fs.exists(p, (exists: boolean) => {\n this._mu.unlock();\n cb(exists);\n });\n });\n }\n\n public existsSync(p: string): boolean {\n if (this._mu.isLocked()) {\n throw new Error('invalid sync call');\n }\n return this._fs.existsSync(p);\n }\n\n public realpath(p: string, cache: {[path: string]: string}, cb: BFSCallback): void {\n this._mu.lock(() => {\n this._fs.realpath(p, cache, (err?: ApiError, resolvedPath?: string) => {\n this._mu.unlock();\n cb(err, resolvedPath);\n });\n });\n }\n\n public realpathSync(p: string, cache: {[path: string]: string}): string {\n if (this._mu.isLocked()) {\n throw new Error('invalid sync call');\n }\n return this._fs.realpathSync(p, cache);\n }\n\n public truncate(p: string, len: number, cb: BFSOneArgCallback): void {\n this._mu.lock(() => {\n this._fs.truncate(p, len, (err?: ApiError) => {\n this._mu.unlock();\n cb(err);\n });\n });\n }\n\n public truncateSync(p: string, len: number): void {\n if (this._mu.isLocked()) {\n throw new Error('invalid sync call');\n }\n return this._fs.truncateSync(p, len);\n }\n\n public readFile(fname: string, encoding: string, flag: FileFlag, cb: BFSCallback): void {\n this._mu.lock(() => {\n this._fs.readFile(fname, encoding, flag, (err?: ApiError, data?: any) => {\n this._mu.unlock();\n cb(err, data);\n });\n });\n }\n\n public readFileSync(fname: string, encoding: string, flag: FileFlag): any {\n if (this._mu.isLocked()) {\n throw new Error('invalid sync call');\n }\n return this._fs.readFileSync(fname, encoding, flag);\n }\n\n public writeFile(fname: string, data: any, encoding: string, flag: FileFlag, mode: number, cb: BFSOneArgCallback): void {\n this._mu.lock(() => {\n this._fs.writeFile(fname, data, encoding, flag, mode, (err?: ApiError) => {\n this._mu.unlock();\n cb(err);\n });\n });\n }\n\n public writeFileSync(fname: string, data: any, encoding: string, flag: FileFlag, mode: number): void {\n if (this._mu.isLocked()) {\n throw new Error('invalid sync call');\n }\n return this._fs.writeFileSync(fname, data, encoding, flag, mode);\n }\n\n public appendFile(fname: string, data: any, encoding: string, flag: FileFlag, mode: number, cb: BFSOneArgCallback): void {\n this._mu.lock(() => {\n this._fs.appendFile(fname, data, encoding, flag, mode, (err?: ApiError) => {\n this._mu.unlock();\n cb(err);\n });\n });\n }\n\n public appendFileSync(fname: string, data: any, encoding: string, flag: FileFlag, mode: number): void {\n if (this._mu.isLocked()) {\n throw new Error('invalid sync call');\n }\n return this._fs.appendFileSync(fname, data, encoding, flag, mode);\n }\n\n public chmod(p: string, isLchmod: boolean, mode: number, cb: BFSOneArgCallback): void {\n this._mu.lock(() => {\n this._fs.chmod(p, isLchmod, mode, (err?: ApiError) => {\n this._mu.unlock();\n cb(err);\n });\n });\n }\n\n public chmodSync(p: string, isLchmod: boolean, mode: number): void {\n if (this._mu.isLocked()) {\n throw new Error('invalid sync call');\n }\n return this._fs.chmodSync(p, isLchmod, mode);\n }\n\n public chown(p: string, isLchown: boolean, uid: number, gid: number, cb: BFSOneArgCallback): void {\n this._mu.lock(() => {\n this._fs.chown(p, isLchown, uid, gid, (err?: ApiError) => {\n this._mu.unlock();\n cb(err);\n });\n });\n }\n\n public chownSync(p: string, isLchown: boolean, uid: number, gid: number): void {\n if (this._mu.isLocked()) {\n throw new Error('invalid sync call');\n }\n return this._fs.chownSync(p, isLchown, uid, gid);\n }\n\n public utimes(p: string, atime: Date, mtime: Date, cb: BFSOneArgCallback): void {\n this._mu.lock(() => {\n this._fs.utimes(p, atime, mtime, (err?: ApiError) => {\n this._mu.unlock();\n cb(err);\n });\n });\n }\n\n public utimesSync(p: string, atime: Date, mtime: Date): void {\n if (this._mu.isLocked()) {\n throw new Error('invalid sync call');\n }\n return this._fs.utimesSync(p, atime, mtime);\n }\n\n public link(srcpath: string, dstpath: string, cb: BFSOneArgCallback): void {\n this._mu.lock(() => {\n this._fs.link(srcpath, dstpath, (err?: ApiError) => {\n this._mu.unlock();\n cb(err);\n });\n });\n }\n\n public linkSync(srcpath: string, dstpath: string): void {\n if (this._mu.isLocked()) {\n throw new Error('invalid sync call');\n }\n return this._fs.linkSync(srcpath, dstpath);\n }\n\n public symlink(srcpath: string, dstpath: string, type: string, cb: BFSOneArgCallback): void {\n this._mu.lock(() => {\n this._fs.symlink(srcpath, dstpath, type, (err?: ApiError) => {\n this._mu.unlock();\n cb(err);\n });\n });\n }\n\n public symlinkSync(srcpath: string, dstpath: string, type: string): void {\n if (this._mu.isLocked()) {\n throw new Error('invalid sync call');\n }\n return this._fs.symlinkSync(srcpath, dstpath, type);\n }\n\n public readlink(p: string, cb: BFSCallback): void {\n this._mu.lock(() => {\n this._fs.readlink(p, (err?: ApiError, linkString?: string) => {\n this._mu.unlock();\n cb(err, linkString);\n });\n });\n }\n\n public readlinkSync(p: string): string {\n if (this._mu.isLocked()) {\n throw new Error('invalid sync call');\n }\n return this._fs.readlinkSync(p);\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ../../../../src/generic/locked_fs.ts","/**\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: Buffer): number {\n const length = str.length > buf.length ? buf.length : str.length;\n for (let i = 0; i < length; i++) {\n let charCode = str.charCodeAt(i);\n if (charCode > 0x7F) {\n // Check if extended ASCII.\n const 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[charCode] = i;\n }\n return length;\n }\n\n public static byte2str(buff: Buffer): string {\n const chars = new Array(buff.length);\n for (let i = 0; i < buff.length; i++) {\n const charCode = buff[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\n\n\n// WEBPACK FOOTER //\n// ../../../../src/generic/extended_ascii.ts","import {FileSystemConstructor, BFSCallback, FileSystem} from './file_system';\nimport {ApiError} from './api_error';\nimport {checkOptions} from './util';\nimport AsyncMirror from '../backend/AsyncMirror';\nimport Dropbox from '../backend/Dropbox';\nimport Emscripten from '../backend/Emscripten';\nimport FolderAdapter from '../backend/FolderAdapter';\nimport HTML5FS from '../backend/HTML5FS';\nimport InMemory from '../backend/InMemory';\nimport IndexedDB from '../backend/IndexedDB';\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';\nimport IsoFS from '../backend/IsoFS';\n\n// Monkey-patch `Create` functions to check options before file system initialization.\n[AsyncMirror, Dropbox, Emscripten, FolderAdapter, HTML5FS, InMemory, IndexedDB, IsoFS, LocalStorage, MountableFileSystem, OverlayFS, WorkerFS, XmlHttpRequest, ZipFS].forEach((fsType: FileSystemConstructor) => {\n const create = fsType.Create;\n fsType.Create = function(opts?: any, cb?: BFSCallback): void {\n const oneArg = typeof(opts) === \"function\";\n const normalizedCb = oneArg ? opts : cb;\n const normalizedOpts = oneArg ? {} : opts;\n\n function wrappedCb(e?: ApiError): void {\n if (e) {\n normalizedCb(e);\n } else {\n create.call(fsType, normalizedOpts, normalizedCb);\n }\n }\n\n checkOptions(fsType, normalizedOpts, wrappedCb);\n };\n});\n\n/**\n * @hidden\n */\nconst Backends = { AsyncMirror, Dropbox, Emscripten, FolderAdapter, HTML5FS, InMemory, IndexedDB, IsoFS, LocalStorage, MountableFileSystem, OverlayFS, WorkerFS, XmlHttpRequest, ZipFS };\n// Make sure all backends cast to FileSystemConstructor (for type checking)\nconst _: {[name: string]: FileSystemConstructor} = Backends;\n// tslint:disable-next-line:no-unused-expression\n_;\n// tslint:enable-next-line:no-unused-expression\nexport default Backends;\n\n\n\n// WEBPACK FOOTER //\n// ../../../../src/core/backends.ts","/**\n * BrowserFS's main entry point.\n * It installs all of the needed polyfills, and requires() the main module.\n */\n\n// IE substr does not support negative indices\nif ('ab'.substr(-1) !== 'b') {\n String.prototype.substr = function(substr: (start: number, length?: number) => string) {\n return function(this: string, start: number, length?: number): string {\n // did we get a negative start, calculate how much it is from the\n // beginning of the string\n if (start < 0) {\n start = this.length + start;\n }\n // call the original function\n return substr.call(this, start, length);\n };\n }(String.prototype.substr);\n}\n\n// Polyfill for Uint8Array.prototype.slice.\n// Safari and some other browsers do not define it.\nif (typeof(ArrayBuffer) !== 'undefined' && typeof(Uint8Array) !== 'undefined') {\n if (!Uint8Array.prototype['slice']) {\n Uint8Array.prototype.slice = function(this: Uint8Array, start: number = 0, end: number = this.length): Uint8Array {\n const self: Uint8Array = this;\n if (start < 0) {\n start = this.length + start;\n if (start < 0) {\n start = 0;\n }\n }\n if (end < 0) {\n end = this.length + end;\n if (end < 0) {\n end = 0;\n }\n }\n if (end < start) {\n end = start;\n }\n return new Uint8Array(self.buffer, self.byteOffset + start, end - start);\n };\n }\n}\n\nexport * from './core/browserfs';\n\n\n\n// WEBPACK FOOTER //\n// ../../../../src/index.ts","/*!\n * The buffer module from node.js, for the browser.\n *\n * @author Feross Aboukhadijeh \n * @license MIT\n */\n/* eslint-disable no-proto */\n\n'use strict'\n\nvar base64 = require('base64-js')\nvar ieee754 = require('ieee754')\n\nexports.Buffer = Buffer\nexports.SlowBuffer = SlowBuffer\nexports.INSPECT_MAX_BYTES = 50\n\nvar K_MAX_LENGTH = 0x7fffffff\nexports.kMaxLength = K_MAX_LENGTH\n\n/**\n * If `Buffer.TYPED_ARRAY_SUPPORT`:\n * === true Use Uint8Array implementation (fastest)\n * === false Print warning and recommend using `buffer` v4.x which has an Object\n * implementation (most compatible, even IE6)\n *\n * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,\n * Opera 11.6+, iOS 4.2+.\n *\n * We report that the browser does not support typed arrays if the are not subclassable\n * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`\n * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support\n * for __proto__ and has a buggy typed array implementation.\n */\nBuffer.TYPED_ARRAY_SUPPORT = typedArraySupport()\n\nif (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&\n typeof console.error === 'function') {\n console.error(\n 'This browser lacks typed array (Uint8Array) support which is required by ' +\n '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'\n )\n}\n\nfunction typedArraySupport () {\n // Can typed array instances can be augmented?\n try {\n var arr = new Uint8Array(1)\n arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}\n return arr.foo() === 42\n } catch (e) {\n return false\n }\n}\n\nfunction createBuffer (length) {\n if (length > K_MAX_LENGTH) {\n throw new RangeError('Invalid typed array length')\n }\n // Return an augmented `Uint8Array` instance\n var buf = new Uint8Array(length)\n buf.__proto__ = Buffer.prototype\n return buf\n}\n\n/**\n * The Buffer constructor returns instances of `Uint8Array` that have their\n * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of\n * `Uint8Array`, so the returned instances will have all the node `Buffer` methods\n * and the `Uint8Array` methods. Square bracket notation works as expected -- it\n * returns a single octet.\n *\n * The `Uint8Array` prototype remains unmodified.\n */\n\nfunction Buffer (arg, encodingOrOffset, length) {\n // Common case.\n if (typeof arg === 'number') {\n if (typeof encodingOrOffset === 'string') {\n throw new Error(\n 'If encoding is specified then the first argument must be a string'\n )\n }\n return allocUnsafe(arg)\n }\n return from(arg, encodingOrOffset, length)\n}\n\n// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97\nif (typeof Symbol !== 'undefined' && Symbol.species &&\n Buffer[Symbol.species] === Buffer) {\n Object.defineProperty(Buffer, Symbol.species, {\n value: null,\n configurable: true,\n enumerable: false,\n writable: false\n })\n}\n\nBuffer.poolSize = 8192 // not used by this implementation\n\nfunction from (value, encodingOrOffset, length) {\n if (typeof value === 'number') {\n throw new TypeError('\"value\" argument must not be a number')\n }\n\n if (isArrayBuffer(value)) {\n return fromArrayBuffer(value, encodingOrOffset, length)\n }\n\n if (typeof value === 'string') {\n return fromString(value, encodingOrOffset)\n }\n\n return fromObject(value)\n}\n\n/**\n * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError\n * if value is a number.\n * Buffer.from(str[, encoding])\n * Buffer.from(array)\n * Buffer.from(buffer)\n * Buffer.from(arrayBuffer[, byteOffset[, length]])\n **/\nBuffer.from = function (value, encodingOrOffset, length) {\n return from(value, encodingOrOffset, length)\n}\n\n// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:\n// https://github.com/feross/buffer/pull/148\nBuffer.prototype.__proto__ = Uint8Array.prototype\nBuffer.__proto__ = Uint8Array\n\nfunction assertSize (size) {\n if (typeof size !== 'number') {\n throw new TypeError('\"size\" argument must be a number')\n } else if (size < 0) {\n throw new RangeError('\"size\" argument must not be negative')\n }\n}\n\nfunction alloc (size, fill, encoding) {\n assertSize(size)\n if (size <= 0) {\n return createBuffer(size)\n }\n if (fill !== undefined) {\n // Only pay attention to encoding if it's a string. This\n // prevents accidentally sending in a number that would\n // be interpretted as a start offset.\n return typeof encoding === 'string'\n ? createBuffer(size).fill(fill, encoding)\n : createBuffer(size).fill(fill)\n }\n return createBuffer(size)\n}\n\n/**\n * Creates a new filled Buffer instance.\n * alloc(size[, fill[, encoding]])\n **/\nBuffer.alloc = function (size, fill, encoding) {\n return alloc(size, fill, encoding)\n}\n\nfunction allocUnsafe (size) {\n assertSize(size)\n return createBuffer(size < 0 ? 0 : checked(size) | 0)\n}\n\n/**\n * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.\n * */\nBuffer.allocUnsafe = function (size) {\n return allocUnsafe(size)\n}\n/**\n * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.\n */\nBuffer.allocUnsafeSlow = function (size) {\n return allocUnsafe(size)\n}\n\nfunction fromString (string, encoding) {\n if (typeof encoding !== 'string' || encoding === '') {\n encoding = 'utf8'\n }\n\n if (!Buffer.isEncoding(encoding)) {\n throw new TypeError('\"encoding\" must be a valid string encoding')\n }\n\n var length = byteLength(string, encoding) | 0\n var buf = createBuffer(length)\n\n var actual = buf.write(string, encoding)\n\n if (actual !== length) {\n // Writing a hex string, for example, that contains invalid characters will\n // cause everything after the first invalid character to be ignored. (e.g.\n // 'abxxcd' will be treated as 'ab')\n buf = buf.slice(0, actual)\n }\n\n return buf\n}\n\nfunction fromArrayLike (array) {\n var length = array.length < 0 ? 0 : checked(array.length) | 0\n var buf = createBuffer(length)\n for (var i = 0; i < length; i += 1) {\n buf[i] = array[i] & 255\n }\n return buf\n}\n\nfunction fromArrayBuffer (array, byteOffset, length) {\n if (byteOffset < 0 || array.byteLength < byteOffset) {\n throw new RangeError('\\'offset\\' is out of bounds')\n }\n\n if (array.byteLength < byteOffset + (length || 0)) {\n throw new RangeError('\\'length\\' is out of bounds')\n }\n\n var buf\n if (byteOffset === undefined && length === undefined) {\n buf = new Uint8Array(array)\n } else if (length === undefined) {\n buf = new Uint8Array(array, byteOffset)\n } else {\n buf = new Uint8Array(array, byteOffset, length)\n }\n\n // Return an augmented `Uint8Array` instance\n buf.__proto__ = Buffer.prototype\n return buf\n}\n\nfunction fromObject (obj) {\n if (Buffer.isBuffer(obj)) {\n var len = checked(obj.length) | 0\n var buf = createBuffer(len)\n\n if (buf.length === 0) {\n return buf\n }\n\n obj.copy(buf, 0, 0, len)\n return buf\n }\n\n if (obj) {\n if (isArrayBufferView(obj) || 'length' in obj) {\n if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {\n return createBuffer(0)\n }\n return fromArrayLike(obj)\n }\n\n if (obj.type === 'Buffer' && Array.isArray(obj.data)) {\n return fromArrayLike(obj.data)\n }\n }\n\n throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')\n}\n\nfunction checked (length) {\n // Note: cannot use `length < K_MAX_LENGTH` here because that fails when\n // length is NaN (which is otherwise coerced to zero.)\n if (length >= K_MAX_LENGTH) {\n throw new RangeError('Attempt to allocate Buffer larger than maximum ' +\n 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')\n }\n return length | 0\n}\n\nfunction SlowBuffer (length) {\n if (+length != length) { // eslint-disable-line eqeqeq\n length = 0\n }\n return Buffer.alloc(+length)\n}\n\nBuffer.isBuffer = function isBuffer (b) {\n return b != null && b._isBuffer === true\n}\n\nBuffer.compare = function compare (a, b) {\n if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {\n throw new TypeError('Arguments must be Buffers')\n }\n\n if (a === b) return 0\n\n var x = a.length\n var y = b.length\n\n for (var i = 0, len = Math.min(x, y); i < len; ++i) {\n if (a[i] !== b[i]) {\n x = a[i]\n y = b[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\nBuffer.isEncoding = function isEncoding (encoding) {\n switch (String(encoding).toLowerCase()) {\n case 'hex':\n case 'utf8':\n case 'utf-8':\n case 'ascii':\n case 'latin1':\n case 'binary':\n case 'base64':\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return true\n default:\n return false\n }\n}\n\nBuffer.concat = function concat (list, length) {\n if (!Array.isArray(list)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n }\n\n if (list.length === 0) {\n return Buffer.alloc(0)\n }\n\n var i\n if (length === undefined) {\n length = 0\n for (i = 0; i < list.length; ++i) {\n length += list[i].length\n }\n }\n\n var buffer = Buffer.allocUnsafe(length)\n var pos = 0\n for (i = 0; i < list.length; ++i) {\n var buf = list[i]\n if (!Buffer.isBuffer(buf)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n }\n buf.copy(buffer, pos)\n pos += buf.length\n }\n return buffer\n}\n\nfunction byteLength (string, encoding) {\n if (Buffer.isBuffer(string)) {\n return string.length\n }\n if (isArrayBufferView(string) || isArrayBuffer(string)) {\n return string.byteLength\n }\n if (typeof string !== 'string') {\n string = '' + string\n }\n\n var len = string.length\n if (len === 0) return 0\n\n // Use a for loop to avoid recursion\n var loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'ascii':\n case 'latin1':\n case 'binary':\n return len\n case 'utf8':\n case 'utf-8':\n case undefined:\n return utf8ToBytes(string).length\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return len * 2\n case 'hex':\n return len >>> 1\n case 'base64':\n return base64ToBytes(string).length\n default:\n if (loweredCase) return utf8ToBytes(string).length // assume utf8\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\nBuffer.byteLength = byteLength\n\nfunction slowToString (encoding, start, end) {\n var loweredCase = false\n\n // No need to verify that \"this.length <= MAX_UINT32\" since it's a read-only\n // property of a typed array.\n\n // This behaves neither like String nor Uint8Array in that we set start/end\n // to their upper/lower bounds if the value passed is out of range.\n // undefined is handled specially as per ECMA-262 6th Edition,\n // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.\n if (start === undefined || start < 0) {\n start = 0\n }\n // Return early if start > this.length. Done here to prevent potential uint32\n // coercion fail below.\n if (start > this.length) {\n return ''\n }\n\n if (end === undefined || end > this.length) {\n end = this.length\n }\n\n if (end <= 0) {\n return ''\n }\n\n // Force coersion to uint32. This will also coerce falsey/NaN values to 0.\n end >>>= 0\n start >>>= 0\n\n if (end <= start) {\n return ''\n }\n\n if (!encoding) encoding = 'utf8'\n\n while (true) {\n switch (encoding) {\n case 'hex':\n return hexSlice(this, start, end)\n\n case 'utf8':\n case 'utf-8':\n return utf8Slice(this, start, end)\n\n case 'ascii':\n return asciiSlice(this, start, end)\n\n case 'latin1':\n case 'binary':\n return latin1Slice(this, start, end)\n\n case 'base64':\n return base64Slice(this, start, end)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return utf16leSlice(this, start, end)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = (encoding + '').toLowerCase()\n loweredCase = true\n }\n }\n}\n\n// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)\n// to detect a Buffer instance. It's not possible to use `instanceof Buffer`\n// reliably in a browserify context because there could be multiple different\n// copies of the 'buffer' package in use. This method works even for Buffer\n// instances that were created from another copy of the `buffer` package.\n// See: https://github.com/feross/buffer/issues/154\nBuffer.prototype._isBuffer = true\n\nfunction swap (b, n, m) {\n var i = b[n]\n b[n] = b[m]\n b[m] = i\n}\n\nBuffer.prototype.swap16 = function swap16 () {\n var len = this.length\n if (len % 2 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 16-bits')\n }\n for (var i = 0; i < len; i += 2) {\n swap(this, i, i + 1)\n }\n return this\n}\n\nBuffer.prototype.swap32 = function swap32 () {\n var len = this.length\n if (len % 4 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 32-bits')\n }\n for (var i = 0; i < len; i += 4) {\n swap(this, i, i + 3)\n swap(this, i + 1, i + 2)\n }\n return this\n}\n\nBuffer.prototype.swap64 = function swap64 () {\n var len = this.length\n if (len % 8 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 64-bits')\n }\n for (var i = 0; i < len; i += 8) {\n swap(this, i, i + 7)\n swap(this, i + 1, i + 6)\n swap(this, i + 2, i + 5)\n swap(this, i + 3, i + 4)\n }\n return this\n}\n\nBuffer.prototype.toString = function toString () {\n var length = this.length\n if (length === 0) return ''\n if (arguments.length === 0) return utf8Slice(this, 0, length)\n return slowToString.apply(this, arguments)\n}\n\nBuffer.prototype.equals = function equals (b) {\n if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')\n if (this === b) return true\n return Buffer.compare(this, b) === 0\n}\n\nBuffer.prototype.inspect = function inspect () {\n var str = ''\n var max = exports.INSPECT_MAX_BYTES\n if (this.length > 0) {\n str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')\n if (this.length > max) str += ' ... '\n }\n return ''\n}\n\nBuffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {\n if (!Buffer.isBuffer(target)) {\n throw new TypeError('Argument must be a Buffer')\n }\n\n if (start === undefined) {\n start = 0\n }\n if (end === undefined) {\n end = target ? target.length : 0\n }\n if (thisStart === undefined) {\n thisStart = 0\n }\n if (thisEnd === undefined) {\n thisEnd = this.length\n }\n\n if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {\n throw new RangeError('out of range index')\n }\n\n if (thisStart >= thisEnd && start >= end) {\n return 0\n }\n if (thisStart >= thisEnd) {\n return -1\n }\n if (start >= end) {\n return 1\n }\n\n start >>>= 0\n end >>>= 0\n thisStart >>>= 0\n thisEnd >>>= 0\n\n if (this === target) return 0\n\n var x = thisEnd - thisStart\n var y = end - start\n var len = Math.min(x, y)\n\n var thisCopy = this.slice(thisStart, thisEnd)\n var targetCopy = target.slice(start, end)\n\n for (var i = 0; i < len; ++i) {\n if (thisCopy[i] !== targetCopy[i]) {\n x = thisCopy[i]\n y = targetCopy[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\n// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,\n// OR the last index of `val` in `buffer` at offset <= `byteOffset`.\n//\n// Arguments:\n// - buffer - a Buffer to search\n// - val - a string, Buffer, or number\n// - byteOffset - an index into `buffer`; will be clamped to an int32\n// - encoding - an optional encoding, relevant is val is a string\n// - dir - true for indexOf, false for lastIndexOf\nfunction bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {\n // Empty buffer means no match\n if (buffer.length === 0) return -1\n\n // Normalize byteOffset\n if (typeof byteOffset === 'string') {\n encoding = byteOffset\n byteOffset = 0\n } else if (byteOffset > 0x7fffffff) {\n byteOffset = 0x7fffffff\n } else if (byteOffset < -0x80000000) {\n byteOffset = -0x80000000\n }\n byteOffset = +byteOffset // Coerce to Number.\n if (numberIsNaN(byteOffset)) {\n // byteOffset: it it's undefined, null, NaN, \"foo\", etc, search whole buffer\n byteOffset = dir ? 0 : (buffer.length - 1)\n }\n\n // Normalize byteOffset: negative offsets start from the end of the buffer\n if (byteOffset < 0) byteOffset = buffer.length + byteOffset\n if (byteOffset >= buffer.length) {\n if (dir) return -1\n else byteOffset = buffer.length - 1\n } else if (byteOffset < 0) {\n if (dir) byteOffset = 0\n else return -1\n }\n\n // Normalize val\n if (typeof val === 'string') {\n val = Buffer.from(val, encoding)\n }\n\n // Finally, search either indexOf (if dir is true) or lastIndexOf\n if (Buffer.isBuffer(val)) {\n // Special case: looking for empty string/buffer always fails\n if (val.length === 0) {\n return -1\n }\n return arrayIndexOf(buffer, val, byteOffset, encoding, dir)\n } else if (typeof val === 'number') {\n val = val & 0xFF // Search for a byte value [0-255]\n if (typeof Uint8Array.prototype.indexOf === 'function') {\n if (dir) {\n return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)\n } else {\n return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)\n }\n }\n return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)\n }\n\n throw new TypeError('val must be string, number or Buffer')\n}\n\nfunction arrayIndexOf (arr, val, byteOffset, encoding, dir) {\n var indexSize = 1\n var arrLength = arr.length\n var valLength = val.length\n\n if (encoding !== undefined) {\n encoding = String(encoding).toLowerCase()\n if (encoding === 'ucs2' || encoding === 'ucs-2' ||\n encoding === 'utf16le' || encoding === 'utf-16le') {\n if (arr.length < 2 || val.length < 2) {\n return -1\n }\n indexSize = 2\n arrLength /= 2\n valLength /= 2\n byteOffset /= 2\n }\n }\n\n function read (buf, i) {\n if (indexSize === 1) {\n return buf[i]\n } else {\n return buf.readUInt16BE(i * indexSize)\n }\n }\n\n var i\n if (dir) {\n var foundIndex = -1\n for (i = byteOffset; i < arrLength; i++) {\n if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {\n if (foundIndex === -1) foundIndex = i\n if (i - foundIndex + 1 === valLength) return foundIndex * indexSize\n } else {\n if (foundIndex !== -1) i -= i - foundIndex\n foundIndex = -1\n }\n }\n } else {\n if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength\n for (i = byteOffset; i >= 0; i--) {\n var found = true\n for (var j = 0; j < valLength; j++) {\n if (read(arr, i + j) !== read(val, j)) {\n found = false\n break\n }\n }\n if (found) return i\n }\n }\n\n return -1\n}\n\nBuffer.prototype.includes = function includes (val, byteOffset, encoding) {\n return this.indexOf(val, byteOffset, encoding) !== -1\n}\n\nBuffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, true)\n}\n\nBuffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, false)\n}\n\nfunction hexWrite (buf, string, offset, length) {\n offset = Number(offset) || 0\n var remaining = buf.length - offset\n if (!length) {\n length = remaining\n } else {\n length = Number(length)\n if (length > remaining) {\n length = remaining\n }\n }\n\n // must be an even number of digits\n var strLen = string.length\n if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')\n\n if (length > strLen / 2) {\n length = strLen / 2\n }\n for (var i = 0; i < length; ++i) {\n var parsed = parseInt(string.substr(i * 2, 2), 16)\n if (numberIsNaN(parsed)) return i\n buf[offset + i] = parsed\n }\n return i\n}\n\nfunction utf8Write (buf, string, offset, length) {\n return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nfunction asciiWrite (buf, string, offset, length) {\n return blitBuffer(asciiToBytes(string), buf, offset, length)\n}\n\nfunction latin1Write (buf, string, offset, length) {\n return asciiWrite(buf, string, offset, length)\n}\n\nfunction base64Write (buf, string, offset, length) {\n return blitBuffer(base64ToBytes(string), buf, offset, length)\n}\n\nfunction ucs2Write (buf, string, offset, length) {\n return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nBuffer.prototype.write = function write (string, offset, length, encoding) {\n // Buffer#write(string)\n if (offset === undefined) {\n encoding = 'utf8'\n length = this.length\n offset = 0\n // Buffer#write(string, encoding)\n } else if (length === undefined && typeof offset === 'string') {\n encoding = offset\n length = this.length\n offset = 0\n // Buffer#write(string, offset[, length][, encoding])\n } else if (isFinite(offset)) {\n offset = offset >>> 0\n if (isFinite(length)) {\n length = length >>> 0\n if (encoding === undefined) encoding = 'utf8'\n } else {\n encoding = length\n length = undefined\n }\n } else {\n throw new Error(\n 'Buffer.write(string, encoding, offset[, length]) is no longer supported'\n )\n }\n\n var remaining = this.length - offset\n if (length === undefined || length > remaining) length = remaining\n\n if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {\n throw new RangeError('Attempt to write outside buffer bounds')\n }\n\n if (!encoding) encoding = 'utf8'\n\n var loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'hex':\n return hexWrite(this, string, offset, length)\n\n case 'utf8':\n case 'utf-8':\n return utf8Write(this, string, offset, length)\n\n case 'ascii':\n return asciiWrite(this, string, offset, length)\n\n case 'latin1':\n case 'binary':\n return latin1Write(this, string, offset, length)\n\n case 'base64':\n // Warning: maxLength not taken into account in base64Write\n return base64Write(this, string, offset, length)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return ucs2Write(this, string, offset, length)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\n\nBuffer.prototype.toJSON = function toJSON () {\n return {\n type: 'Buffer',\n data: Array.prototype.slice.call(this._arr || this, 0)\n }\n}\n\nfunction base64Slice (buf, start, end) {\n if (start === 0 && end === buf.length) {\n return base64.fromByteArray(buf)\n } else {\n return base64.fromByteArray(buf.slice(start, end))\n }\n}\n\nfunction utf8Slice (buf, start, end) {\n end = Math.min(buf.length, end)\n var res = []\n\n var i = start\n while (i < end) {\n var firstByte = buf[i]\n var codePoint = null\n var bytesPerSequence = (firstByte > 0xEF) ? 4\n : (firstByte > 0xDF) ? 3\n : (firstByte > 0xBF) ? 2\n : 1\n\n if (i + bytesPerSequence <= end) {\n var secondByte, thirdByte, fourthByte, tempCodePoint\n\n switch (bytesPerSequence) {\n case 1:\n if (firstByte < 0x80) {\n codePoint = firstByte\n }\n break\n case 2:\n secondByte = buf[i + 1]\n if ((secondByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)\n if (tempCodePoint > 0x7F) {\n codePoint = tempCodePoint\n }\n }\n break\n case 3:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)\n if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {\n codePoint = tempCodePoint\n }\n }\n break\n case 4:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n fourthByte = buf[i + 3]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)\n if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {\n codePoint = tempCodePoint\n }\n }\n }\n }\n\n if (codePoint === null) {\n // we did not generate a valid codePoint so insert a\n // replacement char (U+FFFD) and advance only 1 byte\n codePoint = 0xFFFD\n bytesPerSequence = 1\n } else if (codePoint > 0xFFFF) {\n // encode to utf16 (surrogate pair dance)\n codePoint -= 0x10000\n res.push(codePoint >>> 10 & 0x3FF | 0xD800)\n codePoint = 0xDC00 | codePoint & 0x3FF\n }\n\n res.push(codePoint)\n i += bytesPerSequence\n }\n\n return decodeCodePointsArray(res)\n}\n\n// Based on http://stackoverflow.com/a/22747272/680742, the browser with\n// the lowest limit is Chrome, with 0x10000 args.\n// We go 1 magnitude less, for safety\nvar MAX_ARGUMENTS_LENGTH = 0x1000\n\nfunction decodeCodePointsArray (codePoints) {\n var len = codePoints.length\n if (len <= MAX_ARGUMENTS_LENGTH) {\n return String.fromCharCode.apply(String, codePoints) // avoid extra slice()\n }\n\n // Decode in chunks to avoid \"call stack size exceeded\".\n var res = ''\n var i = 0\n while (i < len) {\n res += String.fromCharCode.apply(\n String,\n codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)\n )\n }\n return res\n}\n\nfunction asciiSlice (buf, start, end) {\n var ret = ''\n end = Math.min(buf.length, end)\n\n for (var i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i] & 0x7F)\n }\n return ret\n}\n\nfunction latin1Slice (buf, start, end) {\n var ret = ''\n end = Math.min(buf.length, end)\n\n for (var i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i])\n }\n return ret\n}\n\nfunction hexSlice (buf, start, end) {\n var len = buf.length\n\n if (!start || start < 0) start = 0\n if (!end || end < 0 || end > len) end = len\n\n var out = ''\n for (var i = start; i < end; ++i) {\n out += toHex(buf[i])\n }\n return out\n}\n\nfunction utf16leSlice (buf, start, end) {\n var bytes = buf.slice(start, end)\n var res = ''\n for (var i = 0; i < bytes.length; i += 2) {\n res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))\n }\n return res\n}\n\nBuffer.prototype.slice = function slice (start, end) {\n var len = this.length\n start = ~~start\n end = end === undefined ? len : ~~end\n\n if (start < 0) {\n start += len\n if (start < 0) start = 0\n } else if (start > len) {\n start = len\n }\n\n if (end < 0) {\n end += len\n if (end < 0) end = 0\n } else if (end > len) {\n end = len\n }\n\n if (end < start) end = start\n\n var newBuf = this.subarray(start, end)\n // Return an augmented `Uint8Array` instance\n newBuf.__proto__ = Buffer.prototype\n return newBuf\n}\n\n/*\n * Need to make sure that buffer isn't trying to write out of bounds.\n */\nfunction checkOffset (offset, ext, length) {\n if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')\n if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')\n}\n\nBuffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var val = this[offset]\n var mul = 1\n var i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) {\n checkOffset(offset, byteLength, this.length)\n }\n\n var val = this[offset + --byteLength]\n var mul = 1\n while (byteLength > 0 && (mul *= 0x100)) {\n val += this[offset + --byteLength] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 1, this.length)\n return this[offset]\n}\n\nBuffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n return this[offset] | (this[offset + 1] << 8)\n}\n\nBuffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n return (this[offset] << 8) | this[offset + 1]\n}\n\nBuffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return ((this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16)) +\n (this[offset + 3] * 0x1000000)\n}\n\nBuffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] * 0x1000000) +\n ((this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n this[offset + 3])\n}\n\nBuffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var val = this[offset]\n var mul = 1\n var i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var i = byteLength\n var mul = 1\n var val = this[offset + --i]\n while (i > 0 && (mul *= 0x100)) {\n val += this[offset + --i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readInt8 = function readInt8 (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 1, this.length)\n if (!(this[offset] & 0x80)) return (this[offset])\n return ((0xff - this[offset] + 1) * -1)\n}\n\nBuffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n var val = this[offset] | (this[offset + 1] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n var val = this[offset + 1] | (this[offset] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16) |\n (this[offset + 3] << 24)\n}\n\nBuffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] << 24) |\n (this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n (this[offset + 3])\n}\n\nBuffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, true, 23, 4)\n}\n\nBuffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, false, 23, 4)\n}\n\nBuffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, true, 52, 8)\n}\n\nBuffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, false, 52, 8)\n}\n\nfunction checkInt (buf, value, offset, ext, max, min) {\n if (!Buffer.isBuffer(buf)) throw new TypeError('\"buffer\" argument must be a Buffer instance')\n if (value > max || value < min) throw new RangeError('\"value\" argument is out of bounds')\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n}\n\nBuffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) {\n var maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n var mul = 1\n var i = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) {\n var maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n var i = byteLength - 1\n var mul = 1\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nBuffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n return offset + 2\n}\n\nBuffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n return offset + 2\n}\n\nBuffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n this[offset + 3] = (value >>> 24)\n this[offset + 2] = (value >>> 16)\n this[offset + 1] = (value >>> 8)\n this[offset] = (value & 0xff)\n return offset + 4\n}\n\nBuffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n return offset + 4\n}\n\nBuffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n var limit = Math.pow(2, (8 * byteLength) - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n var i = 0\n var mul = 1\n var sub = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n var limit = Math.pow(2, (8 * byteLength) - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n var i = byteLength - 1\n var mul = 1\n var sub = 0\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)\n if (value < 0) value = 0xff + value + 1\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nBuffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n return offset + 2\n}\n\nBuffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n return offset + 2\n}\n\nBuffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n this[offset + 2] = (value >>> 16)\n this[offset + 3] = (value >>> 24)\n return offset + 4\n}\n\nBuffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n if (value < 0) value = 0xffffffff + value + 1\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n return offset + 4\n}\n\nfunction checkIEEE754 (buf, value, offset, ext, max, min) {\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n if (offset < 0) throw new RangeError('Index out of range')\n}\n\nfunction writeFloat (buf, value, offset, littleEndian, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)\n }\n ieee754.write(buf, value, offset, littleEndian, 23, 4)\n return offset + 4\n}\n\nBuffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {\n return writeFloat(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {\n return writeFloat(this, value, offset, false, noAssert)\n}\n\nfunction writeDouble (buf, value, offset, littleEndian, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)\n }\n ieee754.write(buf, value, offset, littleEndian, 52, 8)\n return offset + 8\n}\n\nBuffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {\n return writeDouble(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {\n return writeDouble(this, value, offset, false, noAssert)\n}\n\n// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)\nBuffer.prototype.copy = function copy (target, targetStart, start, end) {\n if (!start) start = 0\n if (!end && end !== 0) end = this.length\n if (targetStart >= target.length) targetStart = target.length\n if (!targetStart) targetStart = 0\n if (end > 0 && end < start) end = start\n\n // Copy 0 bytes; we're done\n if (end === start) return 0\n if (target.length === 0 || this.length === 0) return 0\n\n // Fatal error conditions\n if (targetStart < 0) {\n throw new RangeError('targetStart out of bounds')\n }\n if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')\n if (end < 0) throw new RangeError('sourceEnd out of bounds')\n\n // Are we oob?\n if (end > this.length) end = this.length\n if (target.length - targetStart < end - start) {\n end = target.length - targetStart + start\n }\n\n var len = end - start\n var i\n\n if (this === target && start < targetStart && targetStart < end) {\n // descending copy from end\n for (i = len - 1; i >= 0; --i) {\n target[i + targetStart] = this[i + start]\n }\n } else if (len < 1000) {\n // ascending copy from start\n for (i = 0; i < len; ++i) {\n target[i + targetStart] = this[i + start]\n }\n } else {\n Uint8Array.prototype.set.call(\n target,\n this.subarray(start, start + len),\n targetStart\n )\n }\n\n return len\n}\n\n// Usage:\n// buffer.fill(number[, offset[, end]])\n// buffer.fill(buffer[, offset[, end]])\n// buffer.fill(string[, offset[, end]][, encoding])\nBuffer.prototype.fill = function fill (val, start, end, encoding) {\n // Handle string cases:\n if (typeof val === 'string') {\n if (typeof start === 'string') {\n encoding = start\n start = 0\n end = this.length\n } else if (typeof end === 'string') {\n encoding = end\n end = this.length\n }\n if (val.length === 1) {\n var code = val.charCodeAt(0)\n if (code < 256) {\n val = code\n }\n }\n if (encoding !== undefined && typeof encoding !== 'string') {\n throw new TypeError('encoding must be a string')\n }\n if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {\n throw new TypeError('Unknown encoding: ' + encoding)\n }\n } else if (typeof val === 'number') {\n val = val & 255\n }\n\n // Invalid ranges are not set to a default, so can range check early.\n if (start < 0 || this.length < start || this.length < end) {\n throw new RangeError('Out of range index')\n }\n\n if (end <= start) {\n return this\n }\n\n start = start >>> 0\n end = end === undefined ? this.length : end >>> 0\n\n if (!val) val = 0\n\n var i\n if (typeof val === 'number') {\n for (i = start; i < end; ++i) {\n this[i] = val\n }\n } else {\n var bytes = Buffer.isBuffer(val)\n ? val\n : new Buffer(val, encoding)\n var len = bytes.length\n for (i = 0; i < end - start; ++i) {\n this[i + start] = bytes[i % len]\n }\n }\n\n return this\n}\n\n// HELPER FUNCTIONS\n// ================\n\nvar INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g\n\nfunction base64clean (str) {\n // Node strips out invalid characters like \\n and \\t from the string, base64-js does not\n str = str.trim().replace(INVALID_BASE64_RE, '')\n // Node converts strings with length < 2 to ''\n if (str.length < 2) return ''\n // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not\n while (str.length % 4 !== 0) {\n str = str + '='\n }\n return str\n}\n\nfunction toHex (n) {\n if (n < 16) return '0' + n.toString(16)\n return n.toString(16)\n}\n\nfunction utf8ToBytes (string, units) {\n units = units || Infinity\n var codePoint\n var length = string.length\n var leadSurrogate = null\n var bytes = []\n\n for (var i = 0; i < length; ++i) {\n codePoint = string.charCodeAt(i)\n\n // is surrogate component\n if (codePoint > 0xD7FF && codePoint < 0xE000) {\n // last char was a lead\n if (!leadSurrogate) {\n // no lead yet\n if (codePoint > 0xDBFF) {\n // unexpected trail\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n } else if (i + 1 === length) {\n // unpaired lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n }\n\n // valid lead\n leadSurrogate = codePoint\n\n continue\n }\n\n // 2 leads in a row\n if (codePoint < 0xDC00) {\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n leadSurrogate = codePoint\n continue\n }\n\n // valid surrogate pair\n codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000\n } else if (leadSurrogate) {\n // valid bmp char, but last char was a lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n }\n\n leadSurrogate = null\n\n // encode utf8\n if (codePoint < 0x80) {\n if ((units -= 1) < 0) break\n bytes.push(codePoint)\n } else if (codePoint < 0x800) {\n if ((units -= 2) < 0) break\n bytes.push(\n codePoint >> 0x6 | 0xC0,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x10000) {\n if ((units -= 3) < 0) break\n bytes.push(\n codePoint >> 0xC | 0xE0,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x110000) {\n if ((units -= 4) < 0) break\n bytes.push(\n codePoint >> 0x12 | 0xF0,\n codePoint >> 0xC & 0x3F | 0x80,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else {\n throw new Error('Invalid code point')\n }\n }\n\n return bytes\n}\n\nfunction asciiToBytes (str) {\n var byteArray = []\n for (var i = 0; i < str.length; ++i) {\n // Node's code seems to be doing this and not & 0x7F..\n byteArray.push(str.charCodeAt(i) & 0xFF)\n }\n return byteArray\n}\n\nfunction utf16leToBytes (str, units) {\n var c, hi, lo\n var byteArray = []\n for (var i = 0; i < str.length; ++i) {\n if ((units -= 2) < 0) break\n\n c = str.charCodeAt(i)\n hi = c >> 8\n lo = c % 256\n byteArray.push(lo)\n byteArray.push(hi)\n }\n\n return byteArray\n}\n\nfunction base64ToBytes (str) {\n return base64.toByteArray(base64clean(str))\n}\n\nfunction blitBuffer (src, dst, offset, length) {\n for (var i = 0; i < length; ++i) {\n if ((i + offset >= dst.length) || (i >= src.length)) break\n dst[i + offset] = src[i]\n }\n return i\n}\n\n// ArrayBuffers from another context (i.e. an iframe) do not pass the `instanceof` check\n// but they should be treated as valid. See: https://github.com/feross/buffer/issues/166\nfunction isArrayBuffer (obj) {\n return obj instanceof ArrayBuffer ||\n (obj != null && obj.constructor != null && obj.constructor.name === 'ArrayBuffer' &&\n typeof obj.byteLength === 'number')\n}\n\n// Node 0.10 supports `ArrayBuffer` but lacks `ArrayBuffer.isView`\nfunction isArrayBufferView (obj) {\n return (typeof ArrayBuffer.isView === 'function') && ArrayBuffer.isView(obj)\n}\n\nfunction numberIsNaN (obj) {\n return obj !== obj // eslint-disable-line no-self-compare\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/buffer/index.js\n// module id = 1\n// module chunks = 0","// 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/**/\n\nvar objectKeys = Object.keys || function (obj) {\n var keys = [];\n for (var key in obj) {\n keys.push(key);\n }return keys;\n};\n/**/\n\nmodule.exports = Duplex;\n\n/**/\nvar processNextTick = require('process-nextick-args');\n/**/\n\n/**/\nvar util = require('core-util-is');\nutil.inherits = require('inherits');\n/**/\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]) Duplex.prototype[method] = Writable.prototype[method];\n}\n\nfunction Duplex(options) {\n if (!(this instanceof Duplex)) return new Duplex(options);\n\n Readable.call(this, options);\n Writable.call(this, options);\n\n if (options && options.readable === false) this.readable = false;\n\n if (options && options.writable === false) this.writable = false;\n\n this.allowHalfOpen = true;\n if (options && options.allowHalfOpen === false) 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) 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\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/readable-stream/lib/_stream_duplex.js\n// module id = 2\n// module chunks = 0","import Process = require('./process');\nimport TTD = require('./tty');\n\nvar process = new Process(),\n processProxy: Process = {};\n\nfunction defineKey(key: string) {\n if (( processProxy)[key]) {\n // Probably a builtin Object property we don't care about.\n return;\n }\n if (typeof ( process)[key] === 'function') {\n ( processProxy)[key] = function() {\n return ( ( process)[key]).apply(process, arguments);\n };\n } else {\n ( processProxy)[key] = ( 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\n\n\n// WEBPACK FOOTER //\n// ../ts/index.ts","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\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/inherits/inherits_browser.js\n// module id = 4\n// module chunks = 0","// 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\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/core-util-is/lib/util.js\n// module id = 5\n// module chunks = 0","// 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 } else {\n // At least give some kind of context to the user\n var err = new Error('Uncaught, unspecified \"error\" event. (' + er + ')');\n err.context = er;\n throw err;\n }\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._events[type].push(listener);\n else\n // Adding the second element, need to change to array.\n this._events[type] = [this._events[type], listener];\n\n // Check for listener leak\n if (isObject(this._events[type]) && !this._events[type].warned) {\n if (!isUndefined(this._maxListeners)) {\n m = this._maxListeners;\n } else {\n m = EventEmitter.defaultMaxListeners;\n }\n\n if (m && m > 0 && this._events[type].length > m) {\n this._events[type].warned = true;\n console.error('(node) warning: possible EventEmitter memory ' +\n 'leak detected. %d listeners added. ' +\n 'Use emitter.setMaxListeners() to increase limit.',\n this._events[type].length);\n if (typeof console.trace === 'function') {\n // not supported in IE 10\n console.trace();\n }\n }\n }\n\n return this;\n};\n\nEventEmitter.prototype.on = EventEmitter.prototype.addListener;\n\nEventEmitter.prototype.once = function(type, listener) {\n if (!isFunction(listener))\n throw TypeError('listener must be a function');\n\n var fired = false;\n\n function g() {\n this.removeListener(type, g);\n\n if (!fired) {\n fired = true;\n listener.apply(this, arguments);\n }\n }\n\n g.listener = listener;\n this.on(type, g);\n\n return this;\n};\n\n// emits a 'removeListener' event iff the listener was removed\nEventEmitter.prototype.removeListener = function(type, listener) {\n var list, position, length, i;\n\n if (!isFunction(listener))\n throw TypeError('listener must be a function');\n\n if (!this._events || !this._events[type])\n return this;\n\n list = this._events[type];\n length = list.length;\n position = -1;\n\n if (list === listener ||\n (isFunction(list.listener) && list.listener === listener)) {\n delete this._events[type];\n if (this._events.removeListener)\n this.emit('removeListener', type, listener);\n\n } else if (isObject(list)) {\n for (i = length; i-- > 0;) {\n if (list[i] === listener ||\n (list[i].listener && list[i].listener === listener)) {\n position = i;\n break;\n }\n }\n\n if (position < 0)\n return this;\n\n if (list.length === 1) {\n list.length = 0;\n delete this._events[type];\n } else {\n list.splice(position, 1);\n }\n\n if (this._events.removeListener)\n this.emit('removeListener', type, listener);\n }\n\n return this;\n};\n\nEventEmitter.prototype.removeAllListeners = function(type) {\n var key, listeners;\n\n if (!this._events)\n return this;\n\n // not listening for removeListener, no need to emit\n if (!this._events.removeListener) {\n if (arguments.length === 0)\n this._events = {};\n else if (this._events[type])\n delete this._events[type];\n return this;\n }\n\n // emit removeListener for all listeners on all events\n if (arguments.length === 0) {\n for (key in this._events) {\n if (key === 'removeListener') continue;\n this.removeAllListeners(key);\n }\n this.removeAllListeners('removeListener');\n this._events = {};\n return this;\n }\n\n listeners = this._events[type];\n\n if (isFunction(listeners)) {\n this.removeListener(type, listeners);\n } else if (listeners) {\n // LIFO order\n while (listeners.length)\n this.removeListener(type, listeners[listeners.length - 1]);\n }\n delete this._events[type];\n\n return this;\n};\n\nEventEmitter.prototype.listeners = function(type) {\n var ret;\n if (!this._events || !this._events[type])\n ret = [];\n else if (isFunction(this._events[type]))\n ret = [this._events[type]];\n else\n ret = this._events[type].slice();\n return ret;\n};\n\nEventEmitter.prototype.listenerCount = function(type) {\n if (this._events) {\n var evlistener = this._events[type];\n\n if (isFunction(evlistener))\n return 1;\n else if (evlistener)\n return evlistener.length;\n }\n return 0;\n};\n\nEventEmitter.listenerCount = function(emitter, type) {\n return emitter.listenerCount(type);\n};\n\nfunction isFunction(arg) {\n return typeof arg === 'function';\n}\n\nfunction isNumber(arg) {\n return typeof arg === 'number';\n}\n\nfunction isObject(arg) {\n return typeof arg === 'object' && arg !== null;\n}\n\nfunction isUndefined(arg) {\n return arg === void 0;\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/events/events.js\n// module id = 6\n// module chunks = 0","module.exports = require('buffer').Buffer;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./build/temp/library/webpack/BFSBuffer.js\n// module id = 7\n// module chunks = 0","'use strict';\n\n\nvar TYPED_OK = (typeof Uint8Array !== 'undefined') &&\n (typeof Uint16Array !== 'undefined') &&\n (typeof Int32Array !== 'undefined');\n\n\nexports.assign = function (obj /*from1, from2, from3, ...*/) {\n var sources = Array.prototype.slice.call(arguments, 1);\n while (sources.length) {\n var source = sources.shift();\n if (!source) { continue; }\n\n if (typeof source !== 'object') {\n throw new TypeError(source + 'must be non-object');\n }\n\n for (var p in source) {\n if (source.hasOwnProperty(p)) {\n obj[p] = source[p];\n }\n }\n }\n\n return obj;\n};\n\n\n// reduce buffer size, avoiding mem copy\nexports.shrinkBuf = function (buf, size) {\n if (buf.length === size) { return buf; }\n if (buf.subarray) { return buf.subarray(0, size); }\n buf.length = size;\n return buf;\n};\n\n\nvar fnTyped = {\n arraySet: function (dest, src, src_offs, len, dest_offs) {\n if (src.subarray && dest.subarray) {\n dest.set(src.subarray(src_offs, src_offs + len), dest_offs);\n return;\n }\n // Fallback to ordinary array\n for (var i = 0; i < len; i++) {\n dest[dest_offs + i] = src[src_offs + i];\n }\n },\n // Join array of chunks to single array.\n flattenChunks: function (chunks) {\n var i, l, len, pos, chunk, result;\n\n // calculate data length\n len = 0;\n for (i = 0, l = chunks.length; i < l; i++) {\n len += chunks[i].length;\n }\n\n // join chunks\n result = new Uint8Array(len);\n pos = 0;\n for (i = 0, l = chunks.length; i < l; i++) {\n chunk = chunks[i];\n result.set(chunk, pos);\n pos += chunk.length;\n }\n\n return result;\n }\n};\n\nvar fnUntyped = {\n arraySet: function (dest, src, src_offs, len, dest_offs) {\n for (var i = 0; i < len; i++) {\n dest[dest_offs + i] = src[src_offs + i];\n }\n },\n // Join array of chunks to single array.\n flattenChunks: function (chunks) {\n return [].concat.apply([], chunks);\n }\n};\n\n\n// Enable/Disable typed arrays use, for testing\n//\nexports.setTyped = function (on) {\n if (on) {\n exports.Buf8 = Uint8Array;\n exports.Buf16 = Uint16Array;\n exports.Buf32 = Int32Array;\n exports.assign(exports, fnTyped);\n } else {\n exports.Buf8 = Array;\n exports.Buf16 = Array;\n exports.Buf32 = Array;\n exports.assign(exports, fnUntyped);\n }\n};\n\nexports.setTyped(TYPED_OK);\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/pako/lib/utils/common.js\n// module id = 8\n// module chunks = 0","// 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\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/stream-browserify/index.js\n// module id = 9\n// module chunks = 0","'use strict';\n\nvar buffer = require('buffer');\nvar Buffer = buffer.Buffer;\nvar SlowBuffer = buffer.SlowBuffer;\nvar MAX_LEN = buffer.kMaxLength || 2147483647;\nexports.alloc = function alloc(size, fill, encoding) {\n if (typeof Buffer.alloc === 'function') {\n return Buffer.alloc(size, fill, encoding);\n }\n if (typeof encoding === 'number') {\n throw new TypeError('encoding must not be number');\n }\n if (typeof size !== 'number') {\n throw new TypeError('size must be a number');\n }\n if (size > MAX_LEN) {\n throw new RangeError('size is too large');\n }\n var enc = encoding;\n var _fill = fill;\n if (_fill === undefined) {\n enc = undefined;\n _fill = 0;\n }\n var buf = new Buffer(size);\n if (typeof _fill === 'string') {\n var fillBuf = new Buffer(_fill, enc);\n var flen = fillBuf.length;\n var i = -1;\n while (++i < size) {\n buf[i] = fillBuf[i % flen];\n }\n } else {\n buf.fill(_fill);\n }\n return buf;\n}\nexports.allocUnsafe = function allocUnsafe(size) {\n if (typeof Buffer.allocUnsafe === 'function') {\n return Buffer.allocUnsafe(size);\n }\n if (typeof size !== 'number') {\n throw new TypeError('size must be a number');\n }\n if (size > MAX_LEN) {\n throw new RangeError('size is too large');\n }\n return new Buffer(size);\n}\nexports.from = function from(value, encodingOrOffset, length) {\n if (typeof Buffer.from === 'function' && (!global.Uint8Array || Uint8Array.from !== Buffer.from)) {\n return Buffer.from(value, encodingOrOffset, length);\n }\n if (typeof value === 'number') {\n throw new TypeError('\"value\" argument must not be a number');\n }\n if (typeof value === 'string') {\n return new Buffer(value, encodingOrOffset);\n }\n if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {\n var offset = encodingOrOffset;\n if (arguments.length === 1) {\n return new Buffer(value);\n }\n if (typeof offset === 'undefined') {\n offset = 0;\n }\n var len = length;\n if (typeof len === 'undefined') {\n len = value.byteLength - offset;\n }\n if (offset >= value.byteLength) {\n throw new RangeError('\\'offset\\' is out of bounds');\n }\n if (len > value.byteLength - offset) {\n throw new RangeError('\\'length\\' is out of bounds');\n }\n return new Buffer(value.slice(offset, offset + len));\n }\n if (Buffer.isBuffer(value)) {\n var out = new Buffer(value.length);\n value.copy(out, 0, 0, value.length);\n return out;\n }\n if (value) {\n if (Array.isArray(value) || (typeof ArrayBuffer !== 'undefined' && value.buffer instanceof ArrayBuffer) || 'length' in value) {\n return new Buffer(value);\n }\n if (value.type === 'Buffer' && Array.isArray(value.data)) {\n return new Buffer(value.data);\n }\n }\n\n throw new TypeError('First argument must be a string, Buffer, ' + 'ArrayBuffer, Array, or array-like object.');\n}\nexports.allocUnsafeSlow = function allocUnsafeSlow(size) {\n if (typeof Buffer.allocUnsafeSlow === 'function') {\n return Buffer.allocUnsafeSlow(size);\n }\n if (typeof size !== 'number') {\n throw new TypeError('size must be a number');\n }\n if (size >= MAX_LEN) {\n throw new RangeError('size is too large');\n }\n return new SlowBuffer(size);\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/buffer-shims/index.js\n// module id = 10\n// module chunks = 0","'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, arg1, arg2, arg3) {\n if (typeof fn !== 'function') {\n throw new TypeError('\"callback\" argument must be a function');\n }\n var len = arguments.length;\n var args, i;\n switch (len) {\n case 0:\n case 1:\n return process.nextTick(fn);\n case 2:\n return process.nextTick(function afterTickOne() {\n fn.call(null, arg1);\n });\n case 3:\n return process.nextTick(function afterTickTwo() {\n fn.call(null, arg1, arg2);\n });\n case 4:\n return process.nextTick(function afterTickThree() {\n fn.call(null, arg1, arg2, arg3);\n });\n default:\n args = new Array(len - 1);\n i = 0;\n while (i < args.length) {\n args[i++] = arguments[i];\n }\n return process.nextTick(function afterTick() {\n fn.apply(null, args);\n });\n }\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/process-nextick-args/index.js\n// module id = 11\n// module chunks = 0","// 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/**/\nvar util = require('core-util-is');\nutil.inherits = require('inherits');\n/**/\n\nutil.inherits(Transform, Duplex);\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 this.writeencoding = 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) 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) stream.push(data);\n\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\nfunction Transform(options) {\n if (!(this instanceof Transform)) return new Transform(options);\n\n Duplex.call(this, options);\n\n this._transformState = new TransformState(this);\n\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 === 'function') this._transform = options.transform;\n\n if (typeof options.flush === 'function') this._flush = options.flush;\n }\n\n // When the writable side finishes, then flush out anything remaining.\n this.once('prefinish', function () {\n if (typeof this._flush === 'function') this._flush(function (er, data) {\n done(stream, er, data);\n });else done(stream);\n });\n}\n\nTransform.prototype.push = function (chunk, encoding) {\n this._transformState.needTransform = false;\n return Duplex.prototype.push.call(this, chunk, encoding);\n};\n\n// This is the part where you do stuff!\n// override this function in implementation classes.\n// 'chunk' is an input chunk.\n//\n// Call `push(newChunk)` to pass along transformed output\n// to the readable side. You may call 'push' zero or more times.\n//\n// Call `cb(err)` when you are done with this chunk. If you pass\n// an error, then that'll put the hurt on the whole operation. If you\n// never call cb(), then you'll never get another chunk.\nTransform.prototype._transform = function (chunk, encoding, cb) {\n throw new Error('_transform() is not implemented');\n};\n\nTransform.prototype._write = function (chunk, encoding, cb) {\n var ts = this._transformState;\n ts.writecb = cb;\n ts.writechunk = chunk;\n ts.writeencoding = encoding;\n if (!ts.transforming) {\n var rs = this._readableState;\n if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);\n }\n};\n\n// Doesn't matter what the args are here.\n// _transform does all the work.\n// That we got here means that the readable side wants more data.\nTransform.prototype._read = function (n) {\n var ts = this._transformState;\n\n if (ts.writechunk !== null && ts.writecb && !ts.transforming) {\n ts.transforming = true;\n this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);\n } else {\n // mark that we need a transform, so that any data that comes in\n // will get processed, now that we've asked for it.\n ts.needTransform = true;\n }\n};\n\nfunction done(stream, er, data) {\n if (er) return stream.emit('error', er);\n\n if (data !== null && data !== undefined) stream.push(data);\n\n // if there's nothing in the write buffer, then that means\n // that nothing more will ever be provided\n var ws = stream._writableState;\n var ts = stream._transformState;\n\n if (ws.length) throw new Error('Calling transform done when ws.length != 0');\n\n if (ts.transforming) throw new Error('Calling transform done when still transforming');\n\n return stream.push(null);\n}\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/readable-stream/lib/_stream_transform.js\n// module id = 12\n// module chunks = 0","// 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/**/\nvar processNextTick = require('process-nextick-args');\n/**/\n\n/**/\nvar asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : processNextTick;\n/**/\n\n/**/\nvar Duplex;\n/**/\n\nWritable.WritableState = WritableState;\n\n/**/\nvar util = require('core-util-is');\nutil.inherits = require('inherits');\n/**/\n\n/**/\nvar internalUtil = {\n deprecate: require('util-deprecate')\n};\n/**/\n\n/**/\nvar Stream;\n(function () {\n try {\n Stream = require('st' + 'ream');\n } catch (_) {} finally {\n if (!Stream) Stream = require('events').EventEmitter;\n }\n})();\n/**/\n\nvar Buffer = require('buffer').Buffer;\n/**/\nvar bufferShim = require('buffer-shims');\n/**/\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\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) 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 // drain event flag.\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 relevant for synchronous Transform streams\n this.prefinished = false;\n\n // True if the error was already emitted and should not be thrown again\n this.errorEmitted = false;\n\n // count buffered requests\n this.bufferedRequestCount = 0;\n\n // allocate the first CorkedRequest, there is always\n // one allocated and free to use, and we maintain at most two\n this.corkedRequestsFree = new CorkedRequest(this);\n}\n\nWritableState.prototype.getBuffer = function getBuffer() {\n var current = this.bufferedRequest;\n var out = [];\n while (current) {\n out.push(current);\n current = current.next;\n }\n return out;\n};\n\n(function () {\n try {\n Object.defineProperty(WritableState.prototype, 'buffer', {\n get: internalUtil.deprecate(function () {\n return this.getBuffer();\n }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.')\n });\n } catch (_) {}\n})();\n\n// Test _writableState for inheritance to account for Duplex streams,\n// whose prototype chain only points to Readable.\nvar realHasInstance;\nif (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {\n realHasInstance = Function.prototype[Symbol.hasInstance];\n Object.defineProperty(Writable, Symbol.hasInstance, {\n value: function (object) {\n if (realHasInstance.call(this, object)) return true;\n\n return object && object._writableState instanceof WritableState;\n }\n });\n} else {\n realHasInstance = function (object) {\n return object instanceof this;\n };\n}\n\nfunction Writable(options) {\n Duplex = Duplex || require('./_stream_duplex');\n\n // Writable ctor is applied to Duplexes, too.\n // `realHasInstance` is necessary because using plain `instanceof`\n // would return false, as no `_writableState` property is attached.\n\n // Trying to use the custom `instanceof` for Writable here will also break the\n // Node.js LazyTransform implementation, which has a non-trivial getter for\n // `_writableState` that would lead to infinite recursion.\n if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {\n return new Writable(options);\n }\n\n this._writableState = new WritableState(options, this);\n\n // legacy.\n this.writable = true;\n\n if (options) {\n if (typeof options.write === 'function') this._write = options.write;\n\n if (typeof options.writev === 'function') this._writev = options.writev;\n }\n\n Stream.call(this);\n}\n\n// Otherwise people can pipe Writable streams, which is just wrong.\nWritable.prototype.pipe = function () {\n this.emit('error', new Error('Cannot pipe, not readable'));\n};\n\nfunction writeAfterEnd(stream, cb) {\n var er = new Error('write after end');\n // TODO: defer error events consistently everywhere, not just the cb\n stream.emit('error', er);\n processNextTick(cb, er);\n}\n\n// Checks that a user-supplied chunk is valid, especially for the particular\n// mode the stream is in. Currently this means that `null` is never accepted\n// and undefined/non-string values are only allowed in object mode.\nfunction validChunk(stream, state, chunk, cb) {\n var valid = true;\n var er = false;\n\n if (chunk === null) {\n er = new TypeError('May not write null values to stream');\n } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {\n er = new TypeError('Invalid non-string/buffer chunk');\n }\n if (er) {\n stream.emit('error', er);\n processNextTick(cb, er);\n valid = false;\n }\n return valid;\n}\n\nWritable.prototype.write = function (chunk, encoding, cb) {\n var state = this._writableState;\n var ret = false;\n var isBuf = Buffer.isBuffer(chunk);\n\n if (typeof encoding === 'function') {\n cb = encoding;\n encoding = null;\n }\n\n if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;\n\n if (typeof cb !== 'function') cb = nop;\n\n if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {\n state.pendingcb++;\n ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);\n }\n\n return ret;\n};\n\nWritable.prototype.cork = function () {\n var state = this._writableState;\n\n state.corked++;\n};\n\nWritable.prototype.uncork = function () {\n var state = this._writableState;\n\n if (state.corked) {\n state.corked--;\n\n if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);\n }\n};\n\nWritable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {\n // node::ParseEncoding() requires lower case.\n if (typeof encoding === 'string') encoding = encoding.toLowerCase();\n if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding);\n this._writableState.defaultEncoding = encoding;\n return this;\n};\n\nfunction decodeChunk(state, chunk, encoding) {\n if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {\n chunk = bufferShim.from(chunk, encoding);\n }\n return chunk;\n}\n\n// if we're already writing something, then just put this\n// in the queue, and wait our turn. Otherwise, call _write\n// If we return false, then we need a drain event, so set that flag.\nfunction writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {\n if (!isBuf) {\n chunk = decodeChunk(state, chunk, encoding);\n if (Buffer.isBuffer(chunk)) encoding = 'buffer';\n }\n var len = state.objectMode ? 1 : chunk.length;\n\n state.length += len;\n\n var ret = state.length < state.highWaterMark;\n // we must ensure that previous needDrain will not be reset to false.\n if (!ret) state.needDrain = true;\n\n if (state.writing || state.corked) {\n var last = state.lastBufferedRequest;\n state.lastBufferedRequest = new WriteReq(chunk, encoding, cb);\n if (last) {\n last.next = state.lastBufferedRequest;\n } else {\n state.bufferedRequest = state.lastBufferedRequest;\n }\n state.bufferedRequestCount += 1;\n } else {\n doWrite(stream, state, false, len, chunk, encoding, cb);\n }\n\n return ret;\n}\n\nfunction doWrite(stream, state, writev, len, chunk, encoding, cb) {\n state.writelen = len;\n state.writecb = cb;\n state.writing = true;\n state.sync = true;\n if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);\n state.sync = false;\n}\n\nfunction onwriteError(stream, state, sync, er, cb) {\n --state.pendingcb;\n if (sync) processNextTick(cb, er);else cb(er);\n\n stream._writableState.errorEmitted = true;\n stream.emit('error', er);\n}\n\nfunction onwriteStateUpdate(state) {\n state.writing = false;\n state.writecb = null;\n state.length -= state.writelen;\n state.writelen = 0;\n}\n\nfunction onwrite(stream, er) {\n var state = stream._writableState;\n var sync = state.sync;\n var cb = state.writecb;\n\n onwriteStateUpdate(state);\n\n if (er) onwriteError(stream, state, sync, er, cb);else {\n // Check if we're actually ready to finish, but don't emit yet\n var finished = needFinish(state);\n\n if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {\n clearBuffer(stream, state);\n }\n\n if (sync) {\n /**/\n asyncWrite(afterWrite, stream, state, finished, cb);\n /**/\n } else {\n afterWrite(stream, state, finished, cb);\n }\n }\n}\n\nfunction afterWrite(stream, state, finished, cb) {\n if (!finished) onwriteDrain(stream, state);\n state.pendingcb--;\n cb();\n finishMaybe(stream, state);\n}\n\n// Must force callback to be called on nextTick, so that we don't\n// emit 'drain' before the write() consumer gets the 'false' return\n// value, and has a chance to attach a 'drain' listener.\nfunction onwriteDrain(stream, state) {\n if (state.length === 0 && state.needDrain) {\n state.needDrain = false;\n stream.emit('drain');\n }\n}\n\n// if there's something in the buffer waiting, then process it\nfunction clearBuffer(stream, state) {\n state.bufferProcessing = true;\n var entry = state.bufferedRequest;\n\n if (stream._writev && entry && entry.next) {\n // Fast case, write everything using _writev()\n var l = state.bufferedRequestCount;\n var buffer = new Array(l);\n var holder = state.corkedRequestsFree;\n holder.entry = entry;\n\n var count = 0;\n while (entry) {\n buffer[count] = entry;\n entry = entry.next;\n count += 1;\n }\n\n doWrite(stream, state, true, state.length, buffer, '', holder.finish);\n\n // doWrite is almost always async, defer these to save a bit of time\n // as the hot path ends with doWrite\n state.pendingcb++;\n state.lastBufferedRequest = null;\n if (holder.next) {\n state.corkedRequestsFree = holder.next;\n holder.next = null;\n } else {\n state.corkedRequestsFree = new CorkedRequest(state);\n }\n } else {\n // Slow case, write chunks one-by-one\n while (entry) {\n var chunk = entry.chunk;\n var encoding = entry.encoding;\n var cb = entry.callback;\n var len = state.objectMode ? 1 : chunk.length;\n\n doWrite(stream, state, false, len, chunk, encoding, cb);\n entry = entry.next;\n // if we didn't call the onwrite immediately, then\n // it means that we need to wait until it does.\n // also, that means that the chunk and cb are currently\n // being processed, so move the buffer counter past them.\n if (state.writing) {\n break;\n }\n }\n\n if (entry === null) state.lastBufferedRequest = null;\n }\n\n state.bufferedRequestCount = 0;\n state.bufferedRequest = entry;\n state.bufferProcessing = false;\n}\n\nWritable.prototype._write = function (chunk, encoding, cb) {\n cb(new Error('_write() is not implemented'));\n};\n\nWritable.prototype._writev = null;\n\nWritable.prototype.end = function (chunk, encoding, cb) {\n var state = this._writableState;\n\n if (typeof chunk === 'function') {\n cb = chunk;\n chunk = null;\n encoding = null;\n } else if (typeof encoding === 'function') {\n cb = encoding;\n encoding = null;\n }\n\n if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);\n\n // .end() fully uncorks\n if (state.corked) {\n state.corked = 1;\n this.uncork();\n }\n\n // ignore unnecessary end() calls.\n if (!state.ending && !state.finished) endWritable(this, state, cb);\n};\n\nfunction needFinish(state) {\n return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;\n}\n\nfunction prefinish(stream, state) {\n if (!state.prefinished) {\n state.prefinished = true;\n stream.emit('prefinish');\n }\n}\n\nfunction finishMaybe(stream, state) {\n var need = needFinish(state);\n if (need) {\n if (state.pendingcb === 0) {\n prefinish(stream, state);\n state.finished = true;\n stream.emit('finish');\n } else {\n prefinish(stream, state);\n }\n }\n return need;\n}\n\nfunction endWritable(stream, state, cb) {\n state.ending = true;\n finishMaybe(stream, state);\n if (cb) {\n if (state.finished) processNextTick(cb);else stream.once('finish', cb);\n }\n state.ended = true;\n stream.writable = false;\n}\n\n// It seems a linked list but it is not\n// there will be only 2 of these for each stream\nfunction CorkedRequest(state) {\n var _this = this;\n\n this.next = null;\n this.entry = null;\n this.finish = function (err) {\n var entry = _this.entry;\n _this.entry = null;\n while (entry) {\n var cb = entry.callback;\n state.pendingcb--;\n cb(err);\n entry = entry.next;\n }\n if (state.corkedRequestsFree) {\n state.corkedRequestsFree.next = _this;\n } else {\n state.corkedRequestsFree = _this;\n }\n };\n}\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/readable-stream/lib/_stream_writable.js\n// module id = 13\n// module chunks = 0","// 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 right to left\n * order, until an absolute path is found. If after using all from paths still\n * no absolute path is found, the current working directory is used as well.\n * The resulting path is normalized, and trailing slashes are removed unless\n * the path gets resolved to the root directory. Non-string arguments are\n * ignored.\n *\n * Another way to think of it is as a sequence of cd commands in a shell.\n *\n * path.resolve('foo/bar', '/tmp/file/', '..', 'a/../subfile')\n *\n * Is similar to:\n *\n * cd foo/bar\n * cd /tmp/file/\n * cd ..\n * cd a/../subfile\n * pwd\n *\n * The difference is that the different paths don't need to exist and may also\n * be files.\n * @example Usage example\n * path.resolve('/foo/bar', './baz')\n * // returns\n * '/foo/bar/baz'\n *\n * path.resolve('/foo/bar', '/tmp/file/')\n * // returns\n * '/tmp/file'\n *\n * path.resolve('wwwroot', 'static_files/png/', '../gif/image.gif')\n * // if currently in /home/myself/node, it returns\n * '/home/myself/node/wwwroot/static_files/gif/image.gif'\n * @param [String,...] paths\n * @return [String]\n */\n public static resolve(...paths: string[]): string {\n // Monitor for invalid paths, throw out empty paths, and look for the *last*\n // absolute path that we see.\n var processed: string[] = [];\n for (var i = 0; i < paths.length; i++) {\n var p = paths[i];\n if (typeof p !== 'string') {\n throw new TypeError(\"Invalid argument type to path.join: \" + (typeof p));\n } else if (p !== '') {\n // Remove anything that has occurred before this absolute path, as it\n // doesn't matter.\n if (p.charAt(0) === path.sep) {\n processed = [];\n }\n processed.push(p);\n }\n }\n // Special: Remove trailing slash unless it's the root\n var resolved = path.normalize(processed.join(path.sep));\n if (resolved.length > 1 && resolved.charAt(resolved.length - 1) === path.sep) {\n return resolved.substr(0, resolved.length - 1);\n }\n // Special: If it doesn't start with '/', it's relative and we need to append\n // the current directory.\n if (resolved.charAt(0) !== path.sep) {\n // Remove ./, since we're going to append the current directory.\n if (resolved.charAt(0) === '.' && (resolved.length === 1 || resolved.charAt(1) === path.sep)) {\n resolved = resolved.length === 1 ? '' : resolved.substr(2);\n }\n // Append the current directory, which *must* be an absolute path.\n var cwd = process.cwd();\n if (resolved !== '') {\n // cwd will never end in a /... unless it's the root.\n resolved = this.normalize(cwd + (cwd !== '/' ? path.sep : '') + resolved);\n } else {\n resolved = cwd;\n }\n }\n return resolved;\n }\n\n /**\n * Solve the relative path from from to to.\n *\n * At times we have two absolute paths, and we need to derive the relative path\n * from one to the other. This is actually the reverse transform of\n * path.resolve, which means we see that:\n *\n * path.resolve(from, path.relative(from, to)) == path.resolve(to)\n *\n * @example Usage example\n * path.relative('C:\\\\orandea\\\\test\\\\aaa', 'C:\\\\orandea\\\\impl\\\\bbb')\n * // returns\n * '..\\\\..\\\\impl\\\\bbb'\n *\n * path.relative('/data/orandea/test/aaa', '/data/orandea/impl/bbb')\n * // returns\n * '../../impl/bbb'\n * @param [String] from\n * @param [String] to\n * @return [String]\n */\n public static relative(from: string, to: string): string {\n var i: number;\n // Alright. Let's resolve these two to absolute paths and remove any\n // weirdness.\n from = path.resolve(from);\n to = path.resolve(to);\n var fromSegs = from.split(path.sep);\n var toSegs = to.split(path.sep);\n // Remove the first segment on both, as it's '' (both are absolute paths)\n toSegs.shift();\n fromSegs.shift();\n // There are two segments to this path:\n // * Going *up* the directory hierarchy with '..'\n // * Going *down* the directory hierarchy with foo/baz/bat.\n var upCount = 0;\n var downSegs: string[] = [];\n // Figure out how many things in 'from' are shared with 'to'.\n for (i = 0; i < fromSegs.length; i++) {\n var seg = fromSegs[i];\n if (seg === toSegs[i]) {\n continue;\n }\n // The rest of 'from', including the current element, indicates how many\n // directories we need to go up.\n upCount = fromSegs.length - i;\n break;\n }\n // The rest of 'to' indicates where we need to change to. We place this\n // outside of the loop, as toSegs.length may be greater than fromSegs.length.\n downSegs = toSegs.slice(i);\n // Special case: If 'from' is '/'\n if (fromSegs.length === 1 && fromSegs[0] === '') {\n upCount = 0;\n }\n // upCount can't be greater than the number of fromSegs\n // (cd .. from / is still /)\n if (upCount > fromSegs.length) {\n upCount = fromSegs.length;\n }\n // Create the final string!\n var rv = '';\n for (i = 0; i < upCount; i++) {\n rv += '../';\n }\n rv += downSegs.join(path.sep);\n // Special case: Remove trailing '/'. Happens if it's all up and no down.\n if (rv.length > 1 && rv.charAt(rv.length - 1) === path.sep) {\n rv = rv.substr(0, rv.length - 1);\n }\n return rv;\n }\n\n /**\n * Return the directory name of a path. Similar to the Unix `dirname` command.\n *\n * Note that BrowserFS does not validate if the path is actually a valid\n * directory.\n * @example Usage example\n * path.dirname('/foo/bar/baz/asdf/quux')\n * // returns\n * '/foo/bar/baz/asdf'\n * @param [String] p The path to get the directory name of.\n * @return [String]\n */\n public static dirname(p: string): string {\n // We get rid of //, but we don't modify anything else (e.g. any extraneous .\n // and ../ are kept intact)\n p = path._removeDuplicateSeps(p);\n var absolute = p.charAt(0) === path.sep;\n var sections = p.split(path.sep);\n // Do 1 if it's /foo/bar, 2 if it's /foo/bar/\n if (sections.pop() === '' && sections.length > 0) {\n sections.pop();\n }\n // # of sections needs to be > 1 if absolute, since the first section is '' for '/'.\n // If not absolute, the first section is the first part of the path, and is OK\n // to return.\n if (sections.length > 1 || (sections.length === 1 && !absolute)) {\n return sections.join(path.sep);\n } else if (absolute) {\n return path.sep;\n } else {\n return '.';\n }\n }\n\n /**\n * Return the last portion of a path. Similar to the Unix basename command.\n * @example Usage example\n * path.basename('/foo/bar/baz/asdf/quux.html')\n * // returns\n * 'quux.html'\n *\n * path.basename('/foo/bar/baz/asdf/quux.html', '.html')\n * // returns\n * 'quux'\n * @param [String] p\n * @param [String?] ext\n * @return [String]\n */\n public static basename(p: string, ext: string = \"\"): string {\n // Special case: Normalize will modify this to '.'\n if (p === '') {\n return p;\n }\n // Normalize the string first to remove any weirdness.\n p = path.normalize(p);\n // Get the last part of the string.\n var sections = p.split(path.sep);\n var lastPart = sections[sections.length - 1];\n // Special case: If it's empty, then we have a string like so: foo/\n // Meaning, 'foo' is guaranteed to be a directory.\n if (lastPart === '' && sections.length > 1) {\n return sections[sections.length - 2];\n }\n // Remove the extension, if need be.\n if (ext.length > 0) {\n var lastPartExt = lastPart.substr(lastPart.length - ext.length);\n if (lastPartExt === ext) {\n return lastPart.substr(0, lastPart.length - ext.length);\n }\n }\n return lastPart;\n }\n\n /**\n * Return the extension of the path, from the last '.' to end of string in the\n * last portion of the path. If there is no '.' in the last portion of the path\n * or the first character of it is '.', then it returns an empty string.\n * @example Usage example\n * path.extname('index.html')\n * // returns\n * '.html'\n *\n * path.extname('index.')\n * // returns\n * '.'\n *\n * path.extname('index')\n * // returns\n * ''\n * @param [String] p\n * @return [String]\n */\n public static extname(p: string): string {\n p = path.normalize(p);\n var sections = p.split(path.sep);\n p = sections.pop();\n // Special case: foo/file.ext/ should return '.ext'\n if (p === '' && sections.length > 0) {\n p = sections.pop();\n }\n if (p === '..') {\n return '';\n }\n var i = p.lastIndexOf('.');\n if (i === -1 || i === 0) {\n return '';\n }\n return p.substr(i);\n }\n\n /**\n * Checks if the given path is an absolute path.\n *\n * Despite not being documented, this is a tested part of Node's path API.\n * @param [String] p\n * @return [Boolean] True if the path appears to be an absolute path.\n */\n public static isAbsolute(p: string): boolean {\n return p.length > 0 && p.charAt(0) === path.sep;\n }\n\n /**\n * Unknown. Undocumented.\n */\n public static _makeLong(p: string): string {\n return p;\n }\n\n /**\n * Returns an object from a path string.\n */\n public static parse(p: string): _path.ParsedPath {\n var allParts = posixSplitPath(p);\n return {\n root: allParts[0],\n dir: allParts[0] + allParts[1].slice(0, -1),\n base: allParts[2],\n ext: allParts[3],\n name: allParts[2].slice(0, allParts[2].length - allParts[3].length)\n };\n }\n\n public static format(pathObject: _path.ParsedPath): string {\n if (pathObject === null || typeof pathObject !== 'object') {\n throw new TypeError(`Parameter 'pathObject' must be an object, not ${typeof pathObject}`);\n }\n\n var root = pathObject.root || '';\n\n if (typeof root !== 'string') {\n throw new TypeError(\n \"'pathObject.root' must be a string or undefined, not \" +\n typeof pathObject.root\n );\n }\n\n var dir = pathObject.dir ? pathObject.dir + path.sep : '';\n var base = pathObject.base || '';\n return dir + base;\n }\n\n // The platform-specific file separator. BrowserFS uses `/`.\n public static sep: string = '/';\n\n private static _replaceRegex = new RegExp(\"//+\", 'g');\n\n private static _removeDuplicateSeps(p: string): string {\n p = p.replace(this._replaceRegex, this.sep);\n return p;\n }\n\n // The platform-specific path delimiter. BrowserFS uses `:`.\n public static delimiter = ':';\n\n public static posix = path;\n // XXX: Typing hack. We don't actually support win32.\n public static win32 = path;\n}\n\nvar _: typeof _path = path;\n\nexport = path;\n\n\n\n// WEBPACK FOOTER //\n// ../ts/path.ts","// 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/**/\nvar util = require('core-util-is');\nutil.inherits = require('inherits');\n/**/\n\nutil.inherits(PassThrough, Transform);\n\nfunction PassThrough(options) {\n if (!(this instanceof PassThrough)) 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\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/readable-stream/lib/_stream_passthrough.js\n// module id = 15\n// module chunks = 0","'use strict';\n\nmodule.exports = Readable;\n\n/**/\nvar processNextTick = require('process-nextick-args');\n/**/\n\n/**/\nvar isArray = require('isarray');\n/**/\n\n/**/\nvar Duplex;\n/**/\n\nReadable.ReadableState = ReadableState;\n\n/**/\nvar EE = require('events').EventEmitter;\n\nvar EElistenerCount = function (emitter, type) {\n return emitter.listeners(type).length;\n};\n/**/\n\n/**/\nvar Stream;\n(function () {\n try {\n Stream = require('st' + 'ream');\n } catch (_) {} finally {\n if (!Stream) Stream = require('events').EventEmitter;\n }\n})();\n/**/\n\nvar Buffer = require('buffer').Buffer;\n/**/\nvar bufferShim = require('buffer-shims');\n/**/\n\n/**/\nvar util = require('core-util-is');\nutil.inherits = require('inherits');\n/**/\n\n/**/\nvar debugUtil = require('util');\nvar debug = void 0;\nif (debugUtil && debugUtil.debuglog) {\n debug = debugUtil.debuglog('stream');\n} else {\n debug = function () {};\n}\n/**/\n\nvar BufferList = require('./internal/streams/BufferList');\nvar StringDecoder;\n\nutil.inherits(Readable, Stream);\n\nfunction prependListener(emitter, event, fn) {\n // Sadly this is not cacheable as some libraries bundle their own\n // event emitter implementation with them.\n if (typeof emitter.prependListener === 'function') {\n return emitter.prependListener(event, fn);\n } else {\n // This is a hack to make sure that our error handler is attached before any\n // userland ones. NEVER DO THIS. This is here only because this code needs\n // to continue to work with older versions of Node.js that do not include\n // the prependListener() method. The goal is to eventually remove this hack.\n if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];\n }\n}\n\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) 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 // A linked list is used to store data chunks instead of an array because the\n // linked list can remove elements from the beginning faster than\n // array.shift()\n this.buffer = new BufferList();\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 this.resumeScheduled = 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) StringDecoder = require('string_decoder/').StringDecoder;\n this.decoder = new StringDecoder(options.encoding);\n this.encoding = options.encoding;\n }\n}\n\nfunction Readable(options) {\n Duplex = Duplex || require('./_stream_duplex');\n\n if (!(this instanceof Readable)) 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') 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.prototype.push = function (chunk, encoding) {\n var state = this._readableState;\n\n if (!state.objectMode && typeof chunk === 'string') {\n encoding = encoding || state.defaultEncoding;\n if (encoding !== state.encoding) {\n chunk = bufferShim.from(chunk, encoding);\n encoding = '';\n }\n }\n\n return readableAddChunk(this, state, chunk, encoding, false);\n};\n\n// Unshift should *always* be something directly out of read()\nReadable.prototype.unshift = function (chunk) {\n var state = this._readableState;\n return readableAddChunk(this, state, chunk, '', true);\n};\n\nReadable.prototype.isPaused = function () {\n return this._readableState.flowing === false;\n};\n\nfunction readableAddChunk(stream, state, chunk, encoding, addToFront) {\n var er = chunkInvalid(state, chunk);\n if (er) {\n stream.emit('error', er);\n } else if (chunk === null) {\n state.reading = false;\n onEofChunk(stream, state);\n } else if (state.objectMode || chunk && chunk.length > 0) {\n if (state.ended && !addToFront) {\n var e = new Error('stream.push() after EOF');\n stream.emit('error', e);\n } else if (state.endEmitted && addToFront) {\n var _e = new Error('stream.unshift() after end event');\n stream.emit('error', _e);\n } else {\n var skipAdd;\n if (state.decoder && !addToFront && !encoding) {\n chunk = state.decoder.write(chunk);\n skipAdd = !state.objectMode && chunk.length === 0;\n }\n\n if (!addToFront) state.reading = false;\n\n // Don't add to the buffer if we've decoded to an empty string chunk and\n // we're not in object mode\n if (!skipAdd) {\n // if we want the data now, just emit it.\n if (state.flowing && state.length === 0 && !state.sync) {\n stream.emit('data', chunk);\n stream.read(0);\n } else {\n // update the buffer info.\n state.length += state.objectMode ? 1 : chunk.length;\n if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);\n\n if (state.needReadable) emitReadable(stream);\n }\n }\n\n maybeReadMore(stream, state);\n }\n } else if (!addToFront) {\n state.reading = false;\n }\n\n return needMoreData(state);\n}\n\n// if it's past the high water mark, we can push in some more.\n// Also, if we have no data yet, we can stand some\n// more bytes. This is to work around cases where hwm=0,\n// such as the repl. Also, if the push() triggered a\n// readable event, and the user called read(largeNumber) such that\n// needReadable was set, then we ought to push more, so that another\n// 'readable' event will be triggered.\nfunction needMoreData(state) {\n return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);\n}\n\n// backwards compatibility.\nReadable.prototype.setEncoding = function (enc) {\n if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;\n this._readableState.decoder = new StringDecoder(enc);\n this._readableState.encoding = enc;\n return this;\n};\n\n// Don't raise the hwm > 8MB\nvar MAX_HWM = 0x800000;\nfunction computeNewHighWaterMark(n) {\n if (n >= MAX_HWM) {\n n = MAX_HWM;\n } else {\n // Get the next highest power of 2 to prevent increasing hwm excessively in\n // tiny amounts\n n--;\n n |= n >>> 1;\n n |= n >>> 2;\n n |= n >>> 4;\n n |= n >>> 8;\n n |= n >>> 16;\n n++;\n }\n return n;\n}\n\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction howMuchToRead(n, state) {\n if (n <= 0 || state.length === 0 && state.ended) return 0;\n if (state.objectMode) return 1;\n if (n !== n) {\n // Only flow one buffer at a time\n if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;\n }\n // If we're asking for more than the current hwm, then raise the hwm.\n if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);\n if (n <= state.length) return n;\n // Don't have enough\n if (!state.ended) {\n state.needReadable = true;\n return 0;\n }\n return state.length;\n}\n\n// you can override either this method, or the async _read(n) below.\nReadable.prototype.read = function (n) {\n debug('read', n);\n n = parseInt(n, 10);\n var state = this._readableState;\n var nOrig = n;\n\n if (n !== 0) state.emittedReadable = false;\n\n // if we're doing read(0) to trigger a readable event, but we\n // already have a bunch of data in the buffer, then just trigger\n // the 'readable' event and move on.\n if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {\n debug('read: emitReadable', state.length, state.ended);\n if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);\n return null;\n }\n\n n = howMuchToRead(n, state);\n\n // if we've ended, and we're now clear, then finish it up.\n if (n === 0 && state.ended) {\n if (state.length === 0) endReadable(this);\n return null;\n }\n\n // All the actual chunk generation logic needs to be\n // *below* the call to _read. The reason is that in certain\n // synthetic stream cases, such as passthrough streams, _read\n // may be a completely synchronous operation which may change\n // the state of the read buffer, providing enough data when\n // before there was *not* enough.\n //\n // So, the steps are:\n // 1. Figure out what the state of things will be after we do\n // a read from the buffer.\n //\n // 2. If that resulting state will trigger a _read, then call _read.\n // Note that this may be asynchronous, or synchronous. Yes, it is\n // deeply ugly to write APIs this way, but that still doesn't mean\n // that the Readable class should behave improperly, as streams are\n // designed to be sync/async agnostic.\n // Take note if the _read call is sync or async (ie, if the read call\n // has returned yet), so that we know whether or not it's safe to emit\n // 'readable' etc.\n //\n // 3. Actually pull the requested chunks out of the buffer and return.\n\n // if we need a readable event, then we need to do some reading.\n var doRead = state.needReadable;\n debug('need readable', doRead);\n\n // if we currently have less than the highWaterMark, then also read some\n if (state.length === 0 || state.length - n < state.highWaterMark) {\n doRead = true;\n debug('length less than watermark', doRead);\n }\n\n // however, if we've ended, then there's no point, and if we're already\n // reading, then it's unnecessary.\n if (state.ended || state.reading) {\n doRead = false;\n debug('reading or ended', doRead);\n } else if (doRead) {\n debug('do read');\n state.reading = true;\n state.sync = true;\n // if the length is currently zero, then we *need* a readable event.\n if (state.length === 0) state.needReadable = true;\n // call internal read method\n this._read(state.highWaterMark);\n state.sync = false;\n // If _read pushed data synchronously, then `reading` will be false,\n // and we need to re-evaluate how much data we can return to the user.\n if (!state.reading) n = howMuchToRead(nOrig, state);\n }\n\n var ret;\n if (n > 0) ret = fromList(n, state);else ret = null;\n\n if (ret === null) {\n state.needReadable = true;\n n = 0;\n } else {\n state.length -= n;\n }\n\n if (state.length === 0) {\n // If we have nothing in the buffer, then we want to know\n // as soon as we *do* get something into the buffer.\n if (!state.ended) state.needReadable = true;\n\n // If we tried to read() past the EOF, then emit end on the next tick.\n if (nOrig !== n && state.ended) endReadable(this);\n }\n\n if (ret !== null) this.emit('data', ret);\n\n return ret;\n};\n\nfunction chunkInvalid(state, chunk) {\n var er = null;\n if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) {\n er = new TypeError('Invalid non-string/buffer chunk');\n }\n return er;\n}\n\nfunction onEofChunk(stream, state) {\n if (state.ended) return;\n if (state.decoder) {\n var chunk = state.decoder.end();\n if (chunk && chunk.length) {\n state.buffer.push(chunk);\n state.length += state.objectMode ? 1 : chunk.length;\n }\n }\n state.ended = true;\n\n // emit 'readable' now to make sure it gets picked up.\n emitReadable(stream);\n}\n\n// Don't emit readable right away in sync mode, because this can trigger\n// another read() call => stack overflow. This way, it might trigger\n// a nextTick recursion warning, but that's not so bad.\nfunction emitReadable(stream) {\n var state = stream._readableState;\n state.needReadable = false;\n if (!state.emittedReadable) {\n debug('emitReadable', state.flowing);\n state.emittedReadable = true;\n if (state.sync) processNextTick(emitReadable_, stream);else emitReadable_(stream);\n }\n}\n\nfunction emitReadable_(stream) {\n debug('emit readable');\n stream.emit('readable');\n flow(stream);\n}\n\n// at this point, the user has presumably seen the 'readable' event,\n// and called read() to consume some data. that may have triggered\n// in turn another _read(n) call, in which case reading = true if\n// it's in progress.\n// However, if we're not ended, or reading, and the length < hwm,\n// then go ahead and try to read some more preemptively.\nfunction maybeReadMore(stream, state) {\n if (!state.readingMore) {\n state.readingMore = true;\n processNextTick(maybeReadMore_, stream, state);\n }\n}\n\nfunction maybeReadMore_(stream, state) {\n var len = state.length;\n while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {\n debug('maybeReadMore read 0');\n stream.read(0);\n if (len === state.length)\n // didn't get any data, stop spinning.\n break;else len = state.length;\n }\n state.readingMore = false;\n}\n\n// abstract method. to be overridden in specific implementation classes.\n// call cb(er, data) where data is <= n in length.\n// for virtual (non-string, non-buffer) streams, \"length\" is somewhat\n// arbitrary, and perhaps not very meaningful.\nReadable.prototype._read = function (n) {\n this.emit('error', new Error('_read() is not implemented'));\n};\n\nReadable.prototype.pipe = function (dest, pipeOpts) {\n var src = this;\n var state = this._readableState;\n\n switch (state.pipesCount) {\n case 0:\n state.pipes = dest;\n break;\n case 1:\n state.pipes = [state.pipes, dest];\n break;\n default:\n state.pipes.push(dest);\n break;\n }\n state.pipesCount += 1;\n debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);\n\n var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;\n\n var endFn = doEnd ? onend : cleanup;\n if (state.endEmitted) processNextTick(endFn);else src.once('end', endFn);\n\n dest.on('unpipe', onunpipe);\n function onunpipe(readable) {\n debug('onunpipe');\n if (readable === src) {\n cleanup();\n }\n }\n\n function onend() {\n debug('onend');\n dest.end();\n }\n\n // when the dest drains, it reduces the awaitDrain counter\n // on the source. This would be more elegant with a .once()\n // handler in flow(), but adding and removing repeatedly is\n // too slow.\n var ondrain = pipeOnDrain(src);\n dest.on('drain', ondrain);\n\n var cleanedUp = false;\n function cleanup() {\n debug('cleanup');\n // cleanup event handlers once the pipe is broken\n dest.removeListener('close', onclose);\n dest.removeListener('finish', onfinish);\n dest.removeListener('drain', ondrain);\n dest.removeListener('error', onerror);\n dest.removeListener('unpipe', onunpipe);\n src.removeListener('end', onend);\n src.removeListener('end', cleanup);\n src.removeListener('data', ondata);\n\n cleanedUp = true;\n\n // if the reader is waiting for a drain event from this\n // specific writer, then it would cause it to never start\n // flowing again.\n // So, if this is awaiting a drain, then we just call it now.\n // If we don't know, then assume that we are waiting for one.\n if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();\n }\n\n // If the user pushes more data while we're writing to dest then we'll end up\n // in ondata again. However, we only want to increase awaitDrain once because\n // dest will only emit one 'drain' event for the multiple writes.\n // => Introduce a guard on increasing awaitDrain.\n var increasedAwaitDrain = false;\n src.on('data', ondata);\n function ondata(chunk) {\n debug('ondata');\n increasedAwaitDrain = false;\n var ret = dest.write(chunk);\n if (false === ret && !increasedAwaitDrain) {\n // If the user unpiped during `dest.write()`, it is possible\n // to get stuck in a permanently paused state if that write\n // also returned false.\n // => Check whether `dest` is still a piping destination.\n if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {\n debug('false write response, pause', src._readableState.awaitDrain);\n src._readableState.awaitDrain++;\n increasedAwaitDrain = true;\n }\n src.pause();\n }\n }\n\n // if the dest has an error, then stop piping into it.\n // however, don't suppress the throwing behavior for this.\n function onerror(er) {\n debug('onerror', er);\n unpipe();\n dest.removeListener('error', onerror);\n if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);\n }\n\n // Make sure our error handler is attached before userland ones.\n prependListener(dest, 'error', onerror);\n\n // Both close and finish should trigger unpipe, but only once.\n function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }\n dest.once('close', onclose);\n function onfinish() {\n debug('onfinish');\n dest.removeListener('close', onclose);\n unpipe();\n }\n dest.once('finish', onfinish);\n\n function unpipe() {\n debug('unpipe');\n src.unpipe(dest);\n }\n\n // tell the dest that it's being piped to\n dest.emit('pipe', src);\n\n // start the flow if it hasn't been started already.\n if (!state.flowing) {\n debug('pipe resume');\n src.resume();\n }\n\n return dest;\n};\n\nfunction pipeOnDrain(src) {\n return function () {\n var state = src._readableState;\n debug('pipeOnDrain', state.awaitDrain);\n if (state.awaitDrain) state.awaitDrain--;\n if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {\n state.flowing = true;\n flow(src);\n }\n };\n}\n\nReadable.prototype.unpipe = function (dest) {\n var state = this._readableState;\n\n // if we're not piping anywhere, then do nothing.\n if (state.pipesCount === 0) return this;\n\n // just one destination. most common case.\n if (state.pipesCount === 1) {\n // passed in one, but it's not the right one.\n if (dest && dest !== state.pipes) return this;\n\n if (!dest) dest = state.pipes;\n\n // got a match.\n state.pipes = null;\n state.pipesCount = 0;\n state.flowing = false;\n if (dest) dest.emit('unpipe', this);\n return this;\n }\n\n // slow case. multiple pipe destinations.\n\n if (!dest) {\n // remove all.\n var dests = state.pipes;\n var len = state.pipesCount;\n state.pipes = null;\n state.pipesCount = 0;\n state.flowing = false;\n\n for (var i = 0; i < len; i++) {\n dests[i].emit('unpipe', this);\n }return this;\n }\n\n // try to find the right one.\n var index = indexOf(state.pipes, dest);\n if (index === -1) return this;\n\n state.pipes.splice(index, 1);\n state.pipesCount -= 1;\n if (state.pipesCount === 1) state.pipes = state.pipes[0];\n\n dest.emit('unpipe', this);\n\n return this;\n};\n\n// set up data events if they are asked for\n// Ensure readable listeners eventually get something\nReadable.prototype.on = function (ev, fn) {\n var res = Stream.prototype.on.call(this, ev, fn);\n\n if (ev === 'data') {\n // Start flowing on next tick if stream isn't explicitly paused\n if (this._readableState.flowing !== false) this.resume();\n } else if (ev === 'readable') {\n var state = this._readableState;\n if (!state.endEmitted && !state.readableListening) {\n state.readableListening = state.needReadable = true;\n state.emittedReadable = false;\n if (!state.reading) {\n processNextTick(nReadingNextTick, this);\n } else if (state.length) {\n emitReadable(this, state);\n }\n }\n }\n\n return res;\n};\nReadable.prototype.addListener = Readable.prototype.on;\n\nfunction nReadingNextTick(self) {\n debug('readable nexttick read 0');\n self.read(0);\n}\n\n// pause() and resume() are remnants of the legacy readable stream API\n// If the user uses them, then switch into old mode.\nReadable.prototype.resume = function () {\n var state = this._readableState;\n if (!state.flowing) {\n debug('resume');\n state.flowing = true;\n resume(this, state);\n }\n return this;\n};\n\nfunction resume(stream, state) {\n if (!state.resumeScheduled) {\n state.resumeScheduled = true;\n processNextTick(resume_, stream, state);\n }\n}\n\nfunction resume_(stream, state) {\n if (!state.reading) {\n debug('resume read 0');\n stream.read(0);\n }\n\n state.resumeScheduled = false;\n state.awaitDrain = 0;\n stream.emit('resume');\n flow(stream);\n if (state.flowing && !state.reading) stream.read(0);\n}\n\nReadable.prototype.pause = function () {\n debug('call pause flowing=%j', this._readableState.flowing);\n if (false !== this._readableState.flowing) {\n debug('pause');\n this._readableState.flowing = false;\n this.emit('pause');\n }\n return this;\n};\n\nfunction flow(stream) {\n var state = stream._readableState;\n debug('flow', state.flowing);\n while (state.flowing && stream.read() !== null) {}\n}\n\n// wrap an old-style stream as the async data source.\n// This is *not* part of the readable stream interface.\n// It is an ugly unfortunate mess of history.\nReadable.prototype.wrap = function (stream) {\n var state = this._readableState;\n var paused = false;\n\n var self = this;\n stream.on('end', function () {\n debug('wrapped end');\n if (state.decoder && !state.ended) {\n var chunk = state.decoder.end();\n if (chunk && chunk.length) self.push(chunk);\n }\n\n self.push(null);\n });\n\n stream.on('data', function (chunk) {\n debug('wrapped data');\n if (state.decoder) chunk = state.decoder.write(chunk);\n\n // don't skip over falsy values in objectMode\n if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;\n\n var ret = self.push(chunk);\n if (!ret) {\n paused = true;\n stream.pause();\n }\n });\n\n // proxy all the other methods.\n // important when wrapping filters and duplexes.\n for (var i in stream) {\n if (this[i] === undefined && typeof stream[i] === 'function') {\n this[i] = function (method) {\n return function () {\n return stream[method].apply(stream, arguments);\n };\n }(i);\n }\n }\n\n // proxy certain important events.\n var events = ['error', 'close', 'destroy', 'pause', 'resume'];\n forEach(events, function (ev) {\n stream.on(ev, self.emit.bind(self, ev));\n });\n\n // when we try to consume some more bytes, simply unpause the\n // underlying stream.\n self._read = function (n) {\n debug('wrapped _read', n);\n if (paused) {\n paused = false;\n stream.resume();\n }\n };\n\n return self;\n};\n\n// exposed for testing purposes only.\nReadable._fromList = fromList;\n\n// Pluck off n bytes from an array of buffers.\n// Length is the combined lengths of all the buffers in the list.\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction fromList(n, state) {\n // nothing buffered\n if (state.length === 0) return null;\n\n var ret;\n if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {\n // read it all, truncate the list\n if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length);\n state.buffer.clear();\n } else {\n // read part of list\n ret = fromListPartial(n, state.buffer, state.decoder);\n }\n\n return ret;\n}\n\n// Extracts only enough buffered data to satisfy the amount requested.\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction fromListPartial(n, list, hasStrings) {\n var ret;\n if (n < list.head.data.length) {\n // slice is the same for buffers and strings\n ret = list.head.data.slice(0, n);\n list.head.data = list.head.data.slice(n);\n } else if (n === list.head.data.length) {\n // first chunk is a perfect match\n ret = list.shift();\n } else {\n // result spans more than one buffer\n ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);\n }\n return ret;\n}\n\n// Copies a specified amount of characters from the list of buffered data\n// chunks.\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction copyFromBufferString(n, list) {\n var p = list.head;\n var c = 1;\n var ret = p.data;\n n -= ret.length;\n while (p = p.next) {\n var str = p.data;\n var nb = n > str.length ? str.length : n;\n if (nb === str.length) ret += str;else ret += str.slice(0, n);\n n -= nb;\n if (n === 0) {\n if (nb === str.length) {\n ++c;\n if (p.next) list.head = p.next;else list.head = list.tail = null;\n } else {\n list.head = p;\n p.data = str.slice(nb);\n }\n break;\n }\n ++c;\n }\n list.length -= c;\n return ret;\n}\n\n// Copies a specified amount of bytes from the list of buffered data chunks.\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction copyFromBuffer(n, list) {\n var ret = bufferShim.allocUnsafe(n);\n var p = list.head;\n var c = 1;\n p.data.copy(ret);\n n -= p.data.length;\n while (p = p.next) {\n var buf = p.data;\n var nb = n > buf.length ? buf.length : n;\n buf.copy(ret, ret.length - n, 0, nb);\n n -= nb;\n if (n === 0) {\n if (nb === buf.length) {\n ++c;\n if (p.next) list.head = p.next;else list.head = list.tail = null;\n } else {\n list.head = p;\n p.data = buf.slice(nb);\n }\n break;\n }\n ++c;\n }\n list.length -= c;\n return ret;\n}\n\nfunction endReadable(stream) {\n var state = stream._readableState;\n\n // If we get here before consuming all the bytes, then that is a\n // bug in node. Should never happen.\n if (state.length > 0) throw new Error('\"endReadable()\" called on non-empty stream');\n\n if (!state.endEmitted) {\n state.ended = true;\n processNextTick(endReadableNT, state, stream);\n }\n}\n\nfunction endReadableNT(state, stream) {\n // Check that we didn't get one last unshift.\n if (!state.endEmitted && state.length === 0) {\n state.endEmitted = true;\n stream.readable = false;\n stream.emit('end');\n }\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\nfunction indexOf(xs, x) {\n for (var i = 0, l = xs.length; i < l; i++) {\n if (xs[i] === x) return i;\n }\n return -1;\n}\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/readable-stream/lib/_stream_readable.js\n// module id = 16\n// module chunks = 0","// 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 incomplete multibyte character\n while (this.charLength) {\n // determine how many remaining bytes this buffer has to offer for this char\n var available = (buffer.length >= this.charLength - this.charReceived) ?\n this.charLength - this.charReceived :\n buffer.length;\n\n // add the new bytes to the char buffer\n buffer.copy(this.charBuffer, this.charReceived, 0, available);\n this.charReceived += available;\n\n if (this.charReceived < this.charLength) {\n // still not enough chars in this buffer? wait for more ...\n return '';\n }\n\n // remove bytes belonging to the current character from the buffer\n buffer = buffer.slice(available, buffer.length);\n\n // get the character that was split\n charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding);\n\n // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character\n var charCode = charStr.charCodeAt(charStr.length - 1);\n if (charCode >= 0xD800 && charCode <= 0xDBFF) {\n this.charLength += this.surrogateSize;\n charStr = '';\n continue;\n }\n this.charReceived = this.charLength = 0;\n\n // if there are no more bytes in this buffer, just emit our char\n if (buffer.length === 0) {\n return charStr;\n }\n break;\n }\n\n // determine and set charLength / charReceived\n this.detectIncompleteChar(buffer);\n\n var end = buffer.length;\n if (this.charLength) {\n // buffer the incomplete character bytes we got\n buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end);\n end -= this.charReceived;\n }\n\n charStr += buffer.toString(this.encoding, 0, end);\n\n var end = charStr.length - 1;\n var charCode = charStr.charCodeAt(end);\n // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character\n if (charCode >= 0xD800 && charCode <= 0xDBFF) {\n var size = this.surrogateSize;\n this.charLength += size;\n this.charReceived += size;\n this.charBuffer.copy(this.charBuffer, size, 0, size);\n buffer.copy(this.charBuffer, 0, 0, size);\n return charStr.substring(0, end);\n }\n\n // or just emit the charStr\n return charStr;\n};\n\n// detectIncompleteChar determines if there is an incomplete UTF-8 character at\n// the end of the given buffer. If so, it sets this.charLength to the byte\n// length that character, and sets this.charReceived to the number of bytes\n// that are available for this character.\nStringDecoder.prototype.detectIncompleteChar = function(buffer) {\n // determine how many bytes we have to check at the end of this buffer\n var i = (buffer.length >= 3) ? 3 : buffer.length;\n\n // Figure out if one of the last i bytes of our buffer announces an\n // incomplete char.\n for (; i > 0; i--) {\n var c = buffer[buffer.length - i];\n\n // See http://en.wikipedia.org/wiki/UTF-8#Description\n\n // 110XXXXX\n if (i == 1 && c >> 5 == 0x06) {\n this.charLength = 2;\n break;\n }\n\n // 1110XXXX\n if (i <= 2 && c >> 4 == 0x0E) {\n this.charLength = 3;\n break;\n }\n\n // 11110XXX\n if (i <= 3 && c >> 3 == 0x1E) {\n this.charLength = 4;\n break;\n }\n }\n this.charReceived = i;\n};\n\nStringDecoder.prototype.end = function(buffer) {\n var res = '';\n if (buffer && buffer.length)\n res = this.write(buffer);\n\n if (this.charReceived) {\n var cr = this.charReceived;\n var buf = this.charBuffer;\n var enc = this.encoding;\n res += buf.slice(0, cr).toString(enc);\n }\n\n return res;\n};\n\nfunction passThroughWrite(buffer) {\n return buffer.toString(this.encoding);\n}\n\nfunction utf16DetectIncompleteChar(buffer) {\n this.charReceived = buffer.length % 2;\n this.charLength = this.charReceived ? 2 : 0;\n}\n\nfunction base64DetectIncompleteChar(buffer) {\n this.charReceived = buffer.length % 3;\n this.charLength = this.charReceived ? 3 : 0;\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/string_decoder/index.js\n// module id = 17\n// module chunks = 0","'use strict'\n\nexports.byteLength = byteLength\nexports.toByteArray = toByteArray\nexports.fromByteArray = fromByteArray\n\nvar lookup = []\nvar revLookup = []\nvar Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array\n\nvar code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'\nfor (var i = 0, len = code.length; i < len; ++i) {\n lookup[i] = code[i]\n revLookup[code.charCodeAt(i)] = i\n}\n\nrevLookup['-'.charCodeAt(0)] = 62\nrevLookup['_'.charCodeAt(0)] = 63\n\nfunction placeHoldersCount (b64) {\n var len = b64.length\n if (len % 4 > 0) {\n throw new Error('Invalid string. Length must be a multiple of 4')\n }\n\n // the number of equal signs (place holders)\n // if there are two placeholders, than the two characters before it\n // represent one byte\n // if there is only one, then the three characters before it represent 2 bytes\n // this is just a cheap hack to not do indexOf twice\n return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0\n}\n\nfunction byteLength (b64) {\n // base64 is 4/3 + up to two characters of the original data\n return b64.length * 3 / 4 - placeHoldersCount(b64)\n}\n\nfunction toByteArray (b64) {\n var i, j, l, tmp, placeHolders, arr\n var len = b64.length\n placeHolders = placeHoldersCount(b64)\n\n arr = new Arr(len * 3 / 4 - placeHolders)\n\n // if there are placeholders, only get up to the last complete 4 chars\n l = placeHolders > 0 ? len - 4 : len\n\n var L = 0\n\n for (i = 0, j = 0; i < l; i += 4, j += 3) {\n tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]\n arr[L++] = (tmp >> 16) & 0xFF\n arr[L++] = (tmp >> 8) & 0xFF\n arr[L++] = tmp & 0xFF\n }\n\n if (placeHolders === 2) {\n tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4)\n arr[L++] = tmp & 0xFF\n } else if (placeHolders === 1) {\n tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2)\n arr[L++] = (tmp >> 8) & 0xFF\n arr[L++] = tmp & 0xFF\n }\n\n return arr\n}\n\nfunction tripletToBase64 (num) {\n return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]\n}\n\nfunction encodeChunk (uint8, start, end) {\n var tmp\n var output = []\n for (var i = start; i < end; i += 3) {\n tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])\n output.push(tripletToBase64(tmp))\n }\n return output.join('')\n}\n\nfunction fromByteArray (uint8) {\n var tmp\n var len = uint8.length\n var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes\n var output = ''\n var parts = []\n var maxChunkLength = 16383 // must be multiple of 3\n\n // go through the array every three bytes, we'll deal with trailing stuff later\n for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {\n parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))\n }\n\n // pad the end with zeros, but make sure to not forget the extra bytes\n if (extraBytes === 1) {\n tmp = uint8[len - 1]\n output += lookup[tmp >> 2]\n output += lookup[(tmp << 4) & 0x3F]\n output += '=='\n } else if (extraBytes === 2) {\n tmp = (uint8[len - 2] << 8) + (uint8[len - 1])\n output += lookup[tmp >> 10]\n output += lookup[(tmp >> 4) & 0x3F]\n output += lookup[(tmp << 2) & 0x3F]\n output += '='\n }\n\n parts.push(output)\n\n return parts.join('')\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/base64-js/index.js\n// module id = 18\n// module chunks = 0","// 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 execArgv: string[] = [];\n public stdout: _TTY = null;\n public stderr: _TTY = null;\n public stdin: _TTY = null;\n public domain: NodeJS.Domain = 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 public exitCode: number = 0;\n public exit(code: number): void {\n this.exitCode = code;\n this.emit('exit', [code]);\n }\n\n private _gid: number = 1;\n public getgid(): number {\n return this._gid;\n }\n public setgid(gid: number | string): void {\n if (typeof gid === 'number') {\n this._gid = gid;\n } else {\n this._gid = 1;\n }\n }\n\n private _uid: number = 1;\n public getuid(): number {\n return this._uid;\n }\n public setuid(uid: number | string): void {\n if (typeof uid === 'number') {\n this._uid = uid;\n } else {\n this._uid = 1;\n }\n }\n\n public version: string = 'v5.0';\n\n public versions = {\n http_parser: '0.0',\n node: '5.0',\n v8: '0.0',\n uv: '0.0',\n zlib: '0.0',\n ares: '0.0',\n icu: '0.0',\n modules: '0',\n openssl: '0.0'\n };\n\n public config = {\n target_defaults:\n { cflags: [],\n default_configuration: 'Release',\n defines: [],\n include_dirs: [],\n libraries: [] },\n variables:\n { clang: 0,\n host_arch: 'x32',\n node_install_npm: false,\n node_install_waf: false,\n node_prefix: '',\n node_shared_cares: false,\n node_shared_http_parser: false,\n node_shared_libuv: false,\n node_shared_zlib: false,\n node_shared_v8: false,\n node_use_dtrace: false,\n node_use_etw: false,\n node_use_openssl: false,\n node_shared_openssl: false,\n strict_aliasing: false,\n target_arch: 'x32',\n v8_use_snapshot: false,\n v8_no_strict_aliasing: 0,\n visibility: '' } };\n\n public kill(pid: number, signal?: string): void {\n this.emit('kill', [pid, signal]);\n }\n\n public pid = (Math.random()*1000)|0;\n\n public title = 'node';\n public arch = 'x32';\n public memoryUsage(): {rss: number; heapTotal: number; heapUsed: number;} {\n return { rss: 0, heapTotal: 0, heapUsed: 0 }\n }\n\n private _mask = 18;\n public umask(mask: number = this._mask): number {\n let oldMask = this._mask;\n this._mask = mask;\n this.emit('umask', [mask]);\n return oldMask;\n }\n\n public hrtime(): [number, number] {\n let timeinfo: number;\n if (typeof performance !== 'undefined') {\n timeinfo = performance.now();\n } else if (Date['now']) {\n timeinfo = Date.now();\n } else {\n timeinfo = (new Date()).getTime();\n }\n let secs = (timeinfo / 1000)|0;\n timeinfo -= secs * 1000;\n timeinfo = (timeinfo * 1000000)|0;\n return [secs, timeinfo];\n }\n\n /**\n * [BFS only] Initialize the TTY devices.\n */\n public initializeTTYs(): void {\n // Guard against multiple invocations.\n if (this.stdout === null) {\n let TTY: typeof _TTY = require('./tty');\n this.stdout = new TTY();\n this.stderr = new TTY();\n this.stdin = new TTY();\n }\n }\n\n /**\n * Worker-only function; irrelevant here.\n */\n public disconnect(): void {\n\n }\n // Undefined in main thread. Worker-only.\n public connected: boolean = undefined;\n}\n\nexport = Process;\n\n\n// WEBPACK FOOTER //\n// ../ts/process.ts","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\n\n\n// WEBPACK FOOTER //\n// ../ts/tty.ts","exports.read = function (buffer, offset, isLE, mLen, nBytes) {\n var e, m\n var eLen = nBytes * 8 - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var nBits = -7\n var i = isLE ? (nBytes - 1) : 0\n var d = isLE ? -1 : 1\n var s = buffer[offset + i]\n\n i += d\n\n e = s & ((1 << (-nBits)) - 1)\n s >>= (-nBits)\n nBits += eLen\n for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}\n\n m = e & ((1 << (-nBits)) - 1)\n e >>= (-nBits)\n nBits += mLen\n for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}\n\n if (e === 0) {\n e = 1 - eBias\n } else if (e === eMax) {\n return m ? NaN : ((s ? -1 : 1) * Infinity)\n } else {\n m = m + Math.pow(2, mLen)\n e = e - eBias\n }\n return (s ? -1 : 1) * m * Math.pow(2, e - mLen)\n}\n\nexports.write = function (buffer, value, offset, isLE, mLen, nBytes) {\n var e, m, c\n var eLen = nBytes * 8 - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)\n var i = isLE ? 0 : (nBytes - 1)\n var d = isLE ? 1 : -1\n var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0\n\n value = Math.abs(value)\n\n if (isNaN(value) || value === Infinity) {\n m = isNaN(value) ? 1 : 0\n e = eMax\n } else {\n e = Math.floor(Math.log(value) / Math.LN2)\n if (value * (c = Math.pow(2, -e)) < 1) {\n e--\n c *= 2\n }\n if (e + eBias >= 1) {\n value += rt / c\n } else {\n value += rt * Math.pow(2, 1 - eBias)\n }\n if (value * c >= 2) {\n e++\n c /= 2\n }\n\n if (e + eBias >= eMax) {\n m = 0\n e = eMax\n } else if (e + eBias >= 1) {\n m = (value * c - 1) * Math.pow(2, mLen)\n e = e + eBias\n } else {\n m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)\n e = 0\n }\n }\n\n for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}\n\n e = (e << mLen) | m\n eLen += mLen\n for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}\n\n buffer[offset + i - d] |= s * 128\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ieee754/index.js\n// module id = 21\n// module chunks = 0","var toString = {}.toString;\n\nmodule.exports = Array.isArray || function (arr) {\n return toString.call(arr) == '[object Array]';\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/isarray/index.js\n// module id = 22\n// module chunks = 0","'use strict';\n\n\nvar zlib_inflate = require('./zlib/inflate');\nvar utils = require('./utils/common');\nvar strings = require('./utils/strings');\nvar c = require('./zlib/constants');\nvar msg = require('./zlib/messages');\nvar ZStream = require('./zlib/zstream');\nvar GZheader = require('./zlib/gzheader');\n\nvar toString = Object.prototype.toString;\n\n/**\n * class Inflate\n *\n * Generic JS-style wrapper for zlib calls. If you don't need\n * streaming behaviour - use more simple functions: [[inflate]]\n * and [[inflateRaw]].\n **/\n\n/* internal\n * inflate.chunks -> Array\n *\n * Chunks of output data, if [[Inflate#onData]] not overriden.\n **/\n\n/**\n * Inflate.result -> Uint8Array|Array|String\n *\n * Uncompressed result, generated by default [[Inflate#onData]]\n * and [[Inflate#onEnd]] handlers. Filled after you push last chunk\n * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you\n * push a chunk with explicit flush (call [[Inflate#push]] with\n * `Z_SYNC_FLUSH` param).\n **/\n\n/**\n * Inflate.err -> Number\n *\n * Error code after inflate finished. 0 (Z_OK) on success.\n * Should be checked if broken data possible.\n **/\n\n/**\n * Inflate.msg -> String\n *\n * Error message, if [[Inflate.err]] != 0\n **/\n\n\n/**\n * new Inflate(options)\n * - options (Object): zlib inflate options.\n *\n * Creates new inflator instance with specified params. Throws exception\n * on bad params. Supported options:\n *\n * - `windowBits`\n * - `dictionary`\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information on these.\n *\n * Additional options, for internal needs:\n *\n * - `chunkSize` - size of generated data chunks (16K by default)\n * - `raw` (Boolean) - do raw inflate\n * - `to` (String) - if equal to 'string', then result will be converted\n * from utf8 to utf16 (javascript) string. When string output requested,\n * chunk length can differ from `chunkSize`, depending on content.\n *\n * By default, when no options set, autodetect deflate/gzip data format via\n * wrapper header.\n *\n * ##### Example:\n *\n * ```javascript\n * var pako = require('pako')\n * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])\n * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);\n *\n * var inflate = new pako.Inflate({ level: 3});\n *\n * inflate.push(chunk1, false);\n * inflate.push(chunk2, true); // true -> last chunk\n *\n * if (inflate.err) { throw new Error(inflate.err); }\n *\n * console.log(inflate.result);\n * ```\n **/\nfunction Inflate(options) {\n if (!(this instanceof Inflate)) return new Inflate(options);\n\n this.options = utils.assign({\n chunkSize: 16384,\n windowBits: 0,\n to: ''\n }, options || {});\n\n var opt = this.options;\n\n // Force window size for `raw` data, if not set directly,\n // because we have no header for autodetect.\n if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {\n opt.windowBits = -opt.windowBits;\n if (opt.windowBits === 0) { opt.windowBits = -15; }\n }\n\n // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate\n if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&\n !(options && options.windowBits)) {\n opt.windowBits += 32;\n }\n\n // Gzip header has no info about windows size, we can do autodetect only\n // for deflate. So, if window size not set, force it to max when gzip possible\n if ((opt.windowBits > 15) && (opt.windowBits < 48)) {\n // bit 3 (16) -> gzipped data\n // bit 4 (32) -> autodetect gzip/deflate\n if ((opt.windowBits & 15) === 0) {\n opt.windowBits |= 15;\n }\n }\n\n this.err = 0; // error code, if happens (0 = Z_OK)\n this.msg = ''; // error message\n this.ended = false; // used to avoid multiple onEnd() calls\n this.chunks = []; // chunks of compressed data\n\n this.strm = new ZStream();\n this.strm.avail_out = 0;\n\n var status = zlib_inflate.inflateInit2(\n this.strm,\n opt.windowBits\n );\n\n if (status !== c.Z_OK) {\n throw new Error(msg[status]);\n }\n\n this.header = new GZheader();\n\n zlib_inflate.inflateGetHeader(this.strm, this.header);\n}\n\n/**\n * Inflate#push(data[, mode]) -> Boolean\n * - data (Uint8Array|Array|ArrayBuffer|String): input data\n * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.\n * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.\n *\n * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with\n * new output chunks. Returns `true` on success. The last data block must have\n * mode Z_FINISH (or `true`). That will flush internal pending buffers and call\n * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you\n * can use mode Z_SYNC_FLUSH, keeping the decompression context.\n *\n * On fail call [[Inflate#onEnd]] with error code and return false.\n *\n * We strongly recommend to use `Uint8Array` on input for best speed (output\n * format is detected automatically). Also, don't skip last param and always\n * use the same type in your code (boolean or number). That will improve JS speed.\n *\n * For regular `Array`-s make sure all elements are [0..255].\n *\n * ##### Example\n *\n * ```javascript\n * push(chunk, false); // push one of data chunks\n * ...\n * push(chunk, true); // push last chunk\n * ```\n **/\nInflate.prototype.push = function (data, mode) {\n var strm = this.strm;\n var chunkSize = this.options.chunkSize;\n var dictionary = this.options.dictionary;\n var status, _mode;\n var next_out_utf8, tail, utf8str;\n var dict;\n\n // Flag to properly process Z_BUF_ERROR on testing inflate call\n // when we check that all output data was flushed.\n var allowBufError = false;\n\n if (this.ended) { return false; }\n _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);\n\n // Convert data if needed\n if (typeof data === 'string') {\n // Only binary strings can be decompressed on practice\n strm.input = strings.binstring2buf(data);\n } else if (toString.call(data) === '[object ArrayBuffer]') {\n strm.input = new Uint8Array(data);\n } else {\n strm.input = data;\n }\n\n strm.next_in = 0;\n strm.avail_in = strm.input.length;\n\n do {\n if (strm.avail_out === 0) {\n strm.output = new utils.Buf8(chunkSize);\n strm.next_out = 0;\n strm.avail_out = chunkSize;\n }\n\n status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */\n\n if (status === c.Z_NEED_DICT && dictionary) {\n // Convert data if needed\n if (typeof dictionary === 'string') {\n dict = strings.string2buf(dictionary);\n } else if (toString.call(dictionary) === '[object ArrayBuffer]') {\n dict = new Uint8Array(dictionary);\n } else {\n dict = dictionary;\n }\n\n status = zlib_inflate.inflateSetDictionary(this.strm, dict);\n\n }\n\n if (status === c.Z_BUF_ERROR && allowBufError === true) {\n status = c.Z_OK;\n allowBufError = false;\n }\n\n if (status !== c.Z_STREAM_END && status !== c.Z_OK) {\n this.onEnd(status);\n this.ended = true;\n return false;\n }\n\n if (strm.next_out) {\n if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {\n\n if (this.options.to === 'string') {\n\n next_out_utf8 = strings.utf8border(strm.output, strm.next_out);\n\n tail = strm.next_out - next_out_utf8;\n utf8str = strings.buf2string(strm.output, next_out_utf8);\n\n // move tail\n strm.next_out = tail;\n strm.avail_out = chunkSize - tail;\n if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }\n\n this.onData(utf8str);\n\n } else {\n this.onData(utils.shrinkBuf(strm.output, strm.next_out));\n }\n }\n }\n\n // When no more input data, we should check that internal inflate buffers\n // are flushed. The only way to do it when avail_out = 0 - run one more\n // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.\n // Here we set flag to process this error properly.\n //\n // NOTE. Deflate does not return error in this case and does not needs such\n // logic.\n if (strm.avail_in === 0 && strm.avail_out === 0) {\n allowBufError = true;\n }\n\n } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END);\n\n if (status === c.Z_STREAM_END) {\n _mode = c.Z_FINISH;\n }\n\n // Finalize on the last chunk.\n if (_mode === c.Z_FINISH) {\n status = zlib_inflate.inflateEnd(this.strm);\n this.onEnd(status);\n this.ended = true;\n return status === c.Z_OK;\n }\n\n // callback interim results if Z_SYNC_FLUSH.\n if (_mode === c.Z_SYNC_FLUSH) {\n this.onEnd(c.Z_OK);\n strm.avail_out = 0;\n return true;\n }\n\n return true;\n};\n\n\n/**\n * Inflate#onData(chunk) -> Void\n * - chunk (Uint8Array|Array|String): ouput data. Type of array depends\n * on js engine support. When string output requested, each chunk\n * will be string.\n *\n * By default, stores data blocks in `chunks[]` property and glue\n * those in `onEnd`. Override this handler, if you need another behaviour.\n **/\nInflate.prototype.onData = function (chunk) {\n this.chunks.push(chunk);\n};\n\n\n/**\n * Inflate#onEnd(status) -> Void\n * - status (Number): inflate status. 0 (Z_OK) on success,\n * other if not.\n *\n * Called either after you tell inflate that the input stream is\n * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)\n * or if an error happened. By default - join collected chunks,\n * free memory and fill `results` / `err` properties.\n **/\nInflate.prototype.onEnd = function (status) {\n // On success - join\n if (status === c.Z_OK) {\n if (this.options.to === 'string') {\n // Glue & convert here, until we teach pako to send\n // utf8 alligned strings to onData\n this.result = this.chunks.join('');\n } else {\n this.result = utils.flattenChunks(this.chunks);\n }\n }\n this.chunks = [];\n this.err = status;\n this.msg = this.strm.msg;\n};\n\n\n/**\n * inflate(data[, options]) -> Uint8Array|Array|String\n * - data (Uint8Array|Array|String): input data to decompress.\n * - options (Object): zlib inflate options.\n *\n * Decompress `data` with inflate/ungzip and `options`. Autodetect\n * format via wrapper header by default. That's why we don't provide\n * separate `ungzip` method.\n *\n * Supported options are:\n *\n * - windowBits\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information.\n *\n * Sugar (options):\n *\n * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify\n * negative windowBits implicitly.\n * - `to` (String) - if equal to 'string', then result will be converted\n * from utf8 to utf16 (javascript) string. When string output requested,\n * chunk length can differ from `chunkSize`, depending on content.\n *\n *\n * ##### Example:\n *\n * ```javascript\n * var pako = require('pako')\n * , input = pako.deflate([1,2,3,4,5,6,7,8,9])\n * , output;\n *\n * try {\n * output = pako.inflate(input);\n * } catch (err)\n * console.log(err);\n * }\n * ```\n **/\nfunction inflate(input, options) {\n var inflator = new Inflate(options);\n\n inflator.push(input, true);\n\n // That will never happens, if you don't cheat with options :)\n if (inflator.err) { throw inflator.msg || msg[inflator.err]; }\n\n return inflator.result;\n}\n\n\n/**\n * inflateRaw(data[, options]) -> Uint8Array|Array|String\n * - data (Uint8Array|Array|String): input data to decompress.\n * - options (Object): zlib inflate options.\n *\n * The same as [[inflate]], but creates raw data, without wrapper\n * (header and adler32 crc).\n **/\nfunction inflateRaw(input, options) {\n options = options || {};\n options.raw = true;\n return inflate(input, options);\n}\n\n\n/**\n * ungzip(data[, options]) -> Uint8Array|Array|String\n * - data (Uint8Array|Array|String): input data to decompress.\n * - options (Object): zlib inflate options.\n *\n * Just shortcut to [[inflate]], because it autodetects format\n * by header.content. Done for convenience.\n **/\n\n\nexports.Inflate = Inflate;\nexports.inflate = inflate;\nexports.inflateRaw = inflateRaw;\nexports.ungzip = inflate;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/pako/lib/inflate.js\n// module id = 23\n// module chunks = 0","// String encode/decode helpers\n'use strict';\n\n\nvar utils = require('./common');\n\n\n// Quick check if we can use fast array to bin string conversion\n//\n// - apply(Array) can fail on Android 2.2\n// - apply(Uint8Array) can fail on iOS 5.1 Safary\n//\nvar STR_APPLY_OK = true;\nvar STR_APPLY_UIA_OK = true;\n\ntry { String.fromCharCode.apply(null, [ 0 ]); } catch (__) { STR_APPLY_OK = false; }\ntry { String.fromCharCode.apply(null, new Uint8Array(1)); } catch (__) { STR_APPLY_UIA_OK = false; }\n\n\n// Table with utf8 lengths (calculated by first byte of sequence)\n// Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,\n// because max possible codepoint is 0x10ffff\nvar _utf8len = new utils.Buf8(256);\nfor (var q = 0; q < 256; q++) {\n _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);\n}\n_utf8len[254] = _utf8len[254] = 1; // Invalid sequence start\n\n\n// convert string to array (typed, when possible)\nexports.string2buf = function (str) {\n var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;\n\n // count binary size\n for (m_pos = 0; m_pos < str_len; m_pos++) {\n c = str.charCodeAt(m_pos);\n if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {\n c2 = str.charCodeAt(m_pos + 1);\n if ((c2 & 0xfc00) === 0xdc00) {\n c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);\n m_pos++;\n }\n }\n buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;\n }\n\n // allocate buffer\n buf = new utils.Buf8(buf_len);\n\n // convert\n for (i = 0, m_pos = 0; i < buf_len; m_pos++) {\n c = str.charCodeAt(m_pos);\n if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {\n c2 = str.charCodeAt(m_pos + 1);\n if ((c2 & 0xfc00) === 0xdc00) {\n c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);\n m_pos++;\n }\n }\n if (c < 0x80) {\n /* one byte */\n buf[i++] = c;\n } else if (c < 0x800) {\n /* two bytes */\n buf[i++] = 0xC0 | (c >>> 6);\n buf[i++] = 0x80 | (c & 0x3f);\n } else if (c < 0x10000) {\n /* three bytes */\n buf[i++] = 0xE0 | (c >>> 12);\n buf[i++] = 0x80 | (c >>> 6 & 0x3f);\n buf[i++] = 0x80 | (c & 0x3f);\n } else {\n /* four bytes */\n buf[i++] = 0xf0 | (c >>> 18);\n buf[i++] = 0x80 | (c >>> 12 & 0x3f);\n buf[i++] = 0x80 | (c >>> 6 & 0x3f);\n buf[i++] = 0x80 | (c & 0x3f);\n }\n }\n\n return buf;\n};\n\n// Helper (used in 2 places)\nfunction buf2binstring(buf, len) {\n // use fallback for big arrays to avoid stack overflow\n if (len < 65537) {\n if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {\n return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));\n }\n }\n\n var result = '';\n for (var i = 0; i < len; i++) {\n result += String.fromCharCode(buf[i]);\n }\n return result;\n}\n\n\n// Convert byte array to binary string\nexports.buf2binstring = function (buf) {\n return buf2binstring(buf, buf.length);\n};\n\n\n// Convert binary string (typed, when possible)\nexports.binstring2buf = function (str) {\n var buf = new utils.Buf8(str.length);\n for (var i = 0, len = buf.length; i < len; i++) {\n buf[i] = str.charCodeAt(i);\n }\n return buf;\n};\n\n\n// convert array to string\nexports.buf2string = function (buf, max) {\n var i, out, c, c_len;\n var len = max || buf.length;\n\n // Reserve max possible length (2 words per char)\n // NB: by unknown reasons, Array is significantly faster for\n // String.fromCharCode.apply than Uint16Array.\n var utf16buf = new Array(len * 2);\n\n for (out = 0, i = 0; i < len;) {\n c = buf[i++];\n // quick process ascii\n if (c < 0x80) { utf16buf[out++] = c; continue; }\n\n c_len = _utf8len[c];\n // skip 5 & 6 byte codes\n if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len - 1; continue; }\n\n // apply mask on first byte\n c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;\n // join the rest\n while (c_len > 1 && i < len) {\n c = (c << 6) | (buf[i++] & 0x3f);\n c_len--;\n }\n\n // terminated by end of string?\n if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }\n\n if (c < 0x10000) {\n utf16buf[out++] = c;\n } else {\n c -= 0x10000;\n utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);\n utf16buf[out++] = 0xdc00 | (c & 0x3ff);\n }\n }\n\n return buf2binstring(utf16buf, out);\n};\n\n\n// Calculate max possible position in utf8 buffer,\n// that will not break sequence. If that's not possible\n// - (very small limits) return max size as is.\n//\n// buf[] - utf8 bytes array\n// max - length limit (mandatory);\nexports.utf8border = function (buf, max) {\n var pos;\n\n max = max || buf.length;\n if (max > buf.length) { max = buf.length; }\n\n // go back from last position, until start of sequence found\n pos = max - 1;\n while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }\n\n // Fuckup - very small and broken sequence,\n // return max, because we should return something anyway.\n if (pos < 0) { return max; }\n\n // If we came to start of buffer - that means vuffer is too small,\n // return max too.\n if (pos === 0) { return max; }\n\n return (pos + _utf8len[buf[pos]] > max) ? pos : max;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/pako/lib/utils/strings.js\n// module id = 24\n// module chunks = 0","'use strict';\n\n// Note: adler32 takes 12% for level 0 and 2% for level 6.\n// It doesn't worth to make additional optimizationa as in original.\n// Small size is preferable.\n\nfunction adler32(adler, buf, len, pos) {\n var s1 = (adler & 0xffff) |0,\n s2 = ((adler >>> 16) & 0xffff) |0,\n n = 0;\n\n while (len !== 0) {\n // Set limit ~ twice less than 5552, to keep\n // s2 in 31-bits, because we force signed ints.\n // in other case %= will fail.\n n = len > 2000 ? 2000 : len;\n len -= n;\n\n do {\n s1 = (s1 + buf[pos++]) |0;\n s2 = (s2 + s1) |0;\n } while (--n);\n\n s1 %= 65521;\n s2 %= 65521;\n }\n\n return (s1 | (s2 << 16)) |0;\n}\n\n\nmodule.exports = adler32;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/pako/lib/zlib/adler32.js\n// module id = 25\n// module chunks = 0","'use strict';\n\n\nmodule.exports = {\n\n /* Allowed flush values; see deflate() and inflate() below for details */\n Z_NO_FLUSH: 0,\n Z_PARTIAL_FLUSH: 1,\n Z_SYNC_FLUSH: 2,\n Z_FULL_FLUSH: 3,\n Z_FINISH: 4,\n Z_BLOCK: 5,\n Z_TREES: 6,\n\n /* Return codes for the compression/decompression functions. Negative values\n * are errors, positive values are used for special but normal events.\n */\n Z_OK: 0,\n Z_STREAM_END: 1,\n Z_NEED_DICT: 2,\n Z_ERRNO: -1,\n Z_STREAM_ERROR: -2,\n Z_DATA_ERROR: -3,\n //Z_MEM_ERROR: -4,\n Z_BUF_ERROR: -5,\n //Z_VERSION_ERROR: -6,\n\n /* compression levels */\n Z_NO_COMPRESSION: 0,\n Z_BEST_SPEED: 1,\n Z_BEST_COMPRESSION: 9,\n Z_DEFAULT_COMPRESSION: -1,\n\n\n Z_FILTERED: 1,\n Z_HUFFMAN_ONLY: 2,\n Z_RLE: 3,\n Z_FIXED: 4,\n Z_DEFAULT_STRATEGY: 0,\n\n /* Possible values of the data_type field (though see inflate()) */\n Z_BINARY: 0,\n Z_TEXT: 1,\n //Z_ASCII: 1, // = Z_TEXT (deprecated)\n Z_UNKNOWN: 2,\n\n /* The deflate compression method */\n Z_DEFLATED: 8\n //Z_NULL: null // Use -1 or null inline, depending on var type\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/pako/lib/zlib/constants.js\n// module id = 26\n// module chunks = 0","'use strict';\n\n// Note: we can't get significant speed boost here.\n// So write code to minimize size - no pregenerated tables\n// and array tools dependencies.\n\n\n// Use ordinary array, since untyped makes no boost here\nfunction makeTable() {\n var c, table = [];\n\n for (var n = 0; n < 256; n++) {\n c = n;\n for (var k = 0; k < 8; k++) {\n c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));\n }\n table[n] = c;\n }\n\n return table;\n}\n\n// Create table on load. Just 255 signed longs. Not a problem.\nvar crcTable = makeTable();\n\n\nfunction crc32(crc, buf, len, pos) {\n var t = crcTable,\n end = pos + len;\n\n crc ^= -1;\n\n for (var i = pos; i < end; i++) {\n crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];\n }\n\n return (crc ^ (-1)); // >>> 0;\n}\n\n\nmodule.exports = crc32;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/pako/lib/zlib/crc32.js\n// module id = 27\n// module chunks = 0","'use strict';\n\n\nfunction GZheader() {\n /* true if compressed data believed to be text */\n this.text = 0;\n /* modification time */\n this.time = 0;\n /* extra flags (not used when writing a gzip file) */\n this.xflags = 0;\n /* operating system */\n this.os = 0;\n /* pointer to extra field or Z_NULL if none */\n this.extra = null;\n /* extra field length (valid if extra != Z_NULL) */\n this.extra_len = 0; // Actually, we don't need it in JS,\n // but leave for few code modifications\n\n //\n // Setup limits is not necessary because in js we should not preallocate memory\n // for inflate use constant limit in 65536 bytes\n //\n\n /* space at extra (only when reading header) */\n // this.extra_max = 0;\n /* pointer to zero-terminated file name or Z_NULL */\n this.name = '';\n /* space at name (only when reading header) */\n // this.name_max = 0;\n /* pointer to zero-terminated comment or Z_NULL */\n this.comment = '';\n /* space at comment (only when reading header) */\n // this.comm_max = 0;\n /* true if there was or will be a header crc */\n this.hcrc = 0;\n /* true when done reading gzip header (not used when writing a gzip file) */\n this.done = false;\n}\n\nmodule.exports = GZheader;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/pako/lib/zlib/gzheader.js\n// module id = 28\n// module chunks = 0","'use strict';\n\n// See state defs from inflate.js\nvar BAD = 30; /* got a data error -- remain here until reset */\nvar TYPE = 12; /* i: waiting for type bits, including last-flag bit */\n\n/*\n Decode literal, length, and distance codes and write out the resulting\n literal and match bytes until either not enough input or output is\n available, an end-of-block is encountered, or a data error is encountered.\n When large enough input and output buffers are supplied to inflate(), for\n example, a 16K input buffer and a 64K output buffer, more than 95% of the\n inflate execution time is spent in this routine.\n\n Entry assumptions:\n\n state.mode === LEN\n strm.avail_in >= 6\n strm.avail_out >= 258\n start >= strm.avail_out\n state.bits < 8\n\n On return, state.mode is one of:\n\n LEN -- ran out of enough output space or enough available input\n TYPE -- reached end of block code, inflate() to interpret next block\n BAD -- error in block data\n\n Notes:\n\n - The maximum input bits used by a length/distance pair is 15 bits for the\n length code, 5 bits for the length extra, 15 bits for the distance code,\n and 13 bits for the distance extra. This totals 48 bits, or six bytes.\n Therefore if strm.avail_in >= 6, then there is enough input to avoid\n checking for available input while decoding.\n\n - The maximum bytes that a single length/distance pair can output is 258\n bytes, which is the maximum length that can be coded. inflate_fast()\n requires strm.avail_out >= 258 for each loop to avoid checking for\n output space.\n */\nmodule.exports = function inflate_fast(strm, start) {\n var state;\n var _in; /* local strm.input */\n var last; /* have enough input while in < last */\n var _out; /* local strm.output */\n var beg; /* inflate()'s initial strm.output */\n var end; /* while out < end, enough space available */\n//#ifdef INFLATE_STRICT\n var dmax; /* maximum distance from zlib header */\n//#endif\n var wsize; /* window size or zero if not using window */\n var whave; /* valid bytes in the window */\n var wnext; /* window write index */\n // Use `s_window` instead `window`, avoid conflict with instrumentation tools\n var s_window; /* allocated sliding window, if wsize != 0 */\n var hold; /* local strm.hold */\n var bits; /* local strm.bits */\n var lcode; /* local strm.lencode */\n var dcode; /* local strm.distcode */\n var lmask; /* mask for first level of length codes */\n var dmask; /* mask for first level of distance codes */\n var here; /* retrieved table entry */\n var op; /* code bits, operation, extra bits, or */\n /* window position, window bytes to copy */\n var len; /* match length, unused bytes */\n var dist; /* match distance */\n var from; /* where to copy match from */\n var from_source;\n\n\n var input, output; // JS specific, because we have no pointers\n\n /* copy state to local variables */\n state = strm.state;\n //here = state.here;\n _in = strm.next_in;\n input = strm.input;\n last = _in + (strm.avail_in - 5);\n _out = strm.next_out;\n output = strm.output;\n beg = _out - (start - strm.avail_out);\n end = _out + (strm.avail_out - 257);\n//#ifdef INFLATE_STRICT\n dmax = state.dmax;\n//#endif\n wsize = state.wsize;\n whave = state.whave;\n wnext = state.wnext;\n s_window = state.window;\n hold = state.hold;\n bits = state.bits;\n lcode = state.lencode;\n dcode = state.distcode;\n lmask = (1 << state.lenbits) - 1;\n dmask = (1 << state.distbits) - 1;\n\n\n /* decode literals and length/distances until end-of-block or not enough\n input data or output space */\n\n top:\n do {\n if (bits < 15) {\n hold += input[_in++] << bits;\n bits += 8;\n hold += input[_in++] << bits;\n bits += 8;\n }\n\n here = lcode[hold & lmask];\n\n dolen:\n for (;;) { // Goto emulation\n op = here >>> 24/*here.bits*/;\n hold >>>= op;\n bits -= op;\n op = (here >>> 16) & 0xff/*here.op*/;\n if (op === 0) { /* literal */\n //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?\n // \"inflate: literal '%c'\\n\" :\n // \"inflate: literal 0x%02x\\n\", here.val));\n output[_out++] = here & 0xffff/*here.val*/;\n }\n else if (op & 16) { /* length base */\n len = here & 0xffff/*here.val*/;\n op &= 15; /* number of extra bits */\n if (op) {\n if (bits < op) {\n hold += input[_in++] << bits;\n bits += 8;\n }\n len += hold & ((1 << op) - 1);\n hold >>>= op;\n bits -= op;\n }\n //Tracevv((stderr, \"inflate: length %u\\n\", len));\n if (bits < 15) {\n hold += input[_in++] << bits;\n bits += 8;\n hold += input[_in++] << bits;\n bits += 8;\n }\n here = dcode[hold & dmask];\n\n dodist:\n for (;;) { // goto emulation\n op = here >>> 24/*here.bits*/;\n hold >>>= op;\n bits -= op;\n op = (here >>> 16) & 0xff/*here.op*/;\n\n if (op & 16) { /* distance base */\n dist = here & 0xffff/*here.val*/;\n op &= 15; /* number of extra bits */\n if (bits < op) {\n hold += input[_in++] << bits;\n bits += 8;\n if (bits < op) {\n hold += input[_in++] << bits;\n bits += 8;\n }\n }\n dist += hold & ((1 << op) - 1);\n//#ifdef INFLATE_STRICT\n if (dist > dmax) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD;\n break top;\n }\n//#endif\n hold >>>= op;\n bits -= op;\n //Tracevv((stderr, \"inflate: distance %u\\n\", dist));\n op = _out - beg; /* max distance in output */\n if (dist > op) { /* see if copy from window */\n op = dist - op; /* distance back in window */\n if (op > whave) {\n if (state.sane) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD;\n break top;\n }\n\n// (!) This block is disabled in zlib defailts,\n// don't enable it for binary compatibility\n//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR\n// if (len <= op - whave) {\n// do {\n// output[_out++] = 0;\n// } while (--len);\n// continue top;\n// }\n// len -= op - whave;\n// do {\n// output[_out++] = 0;\n// } while (--op > whave);\n// if (op === 0) {\n// from = _out - dist;\n// do {\n// output[_out++] = output[from++];\n// } while (--len);\n// continue top;\n// }\n//#endif\n }\n from = 0; // window index\n from_source = s_window;\n if (wnext === 0) { /* very common case */\n from += wsize - op;\n if (op < len) { /* some from window */\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = _out - dist; /* rest from output */\n from_source = output;\n }\n }\n else if (wnext < op) { /* wrap around window */\n from += wsize + wnext - op;\n op -= wnext;\n if (op < len) { /* some from end of window */\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = 0;\n if (wnext < len) { /* some from start of window */\n op = wnext;\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = _out - dist; /* rest from output */\n from_source = output;\n }\n }\n }\n else { /* contiguous in window */\n from += wnext - op;\n if (op < len) { /* some from window */\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = _out - dist; /* rest from output */\n from_source = output;\n }\n }\n while (len > 2) {\n output[_out++] = from_source[from++];\n output[_out++] = from_source[from++];\n output[_out++] = from_source[from++];\n len -= 3;\n }\n if (len) {\n output[_out++] = from_source[from++];\n if (len > 1) {\n output[_out++] = from_source[from++];\n }\n }\n }\n else {\n from = _out - dist; /* copy direct from output */\n do { /* minimum length is three */\n output[_out++] = output[from++];\n output[_out++] = output[from++];\n output[_out++] = output[from++];\n len -= 3;\n } while (len > 2);\n if (len) {\n output[_out++] = output[from++];\n if (len > 1) {\n output[_out++] = output[from++];\n }\n }\n }\n }\n else if ((op & 64) === 0) { /* 2nd level distance code */\n here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];\n continue dodist;\n }\n else {\n strm.msg = 'invalid distance code';\n state.mode = BAD;\n break top;\n }\n\n break; // need to emulate goto via \"continue\"\n }\n }\n else if ((op & 64) === 0) { /* 2nd level length code */\n here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];\n continue dolen;\n }\n else if (op & 32) { /* end-of-block */\n //Tracevv((stderr, \"inflate: end of block\\n\"));\n state.mode = TYPE;\n break top;\n }\n else {\n strm.msg = 'invalid literal/length code';\n state.mode = BAD;\n break top;\n }\n\n break; // need to emulate goto via \"continue\"\n }\n } while (_in < last && _out < end);\n\n /* return unused bytes (on entry, bits < 8, so in won't go too far back) */\n len = bits >> 3;\n _in -= len;\n bits -= len << 3;\n hold &= (1 << bits) - 1;\n\n /* update state and return */\n strm.next_in = _in;\n strm.next_out = _out;\n strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));\n strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));\n state.hold = hold;\n state.bits = bits;\n return;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/pako/lib/zlib/inffast.js\n// module id = 29\n// module chunks = 0","'use strict';\n\n\nvar utils = require('../utils/common');\nvar adler32 = require('./adler32');\nvar crc32 = require('./crc32');\nvar inflate_fast = require('./inffast');\nvar inflate_table = require('./inftrees');\n\nvar CODES = 0;\nvar LENS = 1;\nvar DISTS = 2;\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\n\n/* Allowed flush values; see deflate() and inflate() below for details */\n//var Z_NO_FLUSH = 0;\n//var Z_PARTIAL_FLUSH = 1;\n//var Z_SYNC_FLUSH = 2;\n//var Z_FULL_FLUSH = 3;\nvar Z_FINISH = 4;\nvar Z_BLOCK = 5;\nvar Z_TREES = 6;\n\n\n/* Return codes for the compression/decompression functions. Negative values\n * are errors, positive values are used for special but normal events.\n */\nvar Z_OK = 0;\nvar Z_STREAM_END = 1;\nvar Z_NEED_DICT = 2;\n//var Z_ERRNO = -1;\nvar Z_STREAM_ERROR = -2;\nvar Z_DATA_ERROR = -3;\nvar Z_MEM_ERROR = -4;\nvar Z_BUF_ERROR = -5;\n//var Z_VERSION_ERROR = -6;\n\n/* The deflate compression method */\nvar Z_DEFLATED = 8;\n\n\n/* STATES ====================================================================*/\n/* ===========================================================================*/\n\n\nvar HEAD = 1; /* i: waiting for magic header */\nvar FLAGS = 2; /* i: waiting for method and flags (gzip) */\nvar TIME = 3; /* i: waiting for modification time (gzip) */\nvar OS = 4; /* i: waiting for extra flags and operating system (gzip) */\nvar EXLEN = 5; /* i: waiting for extra length (gzip) */\nvar EXTRA = 6; /* i: waiting for extra bytes (gzip) */\nvar NAME = 7; /* i: waiting for end of file name (gzip) */\nvar COMMENT = 8; /* i: waiting for end of comment (gzip) */\nvar HCRC = 9; /* i: waiting for header crc (gzip) */\nvar DICTID = 10; /* i: waiting for dictionary check value */\nvar DICT = 11; /* waiting for inflateSetDictionary() call */\nvar TYPE = 12; /* i: waiting for type bits, including last-flag bit */\nvar TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */\nvar STORED = 14; /* i: waiting for stored size (length and complement) */\nvar COPY_ = 15; /* i/o: same as COPY below, but only first time in */\nvar COPY = 16; /* i/o: waiting for input or output to copy stored block */\nvar TABLE = 17; /* i: waiting for dynamic block table lengths */\nvar LENLENS = 18; /* i: waiting for code length code lengths */\nvar CODELENS = 19; /* i: waiting for length/lit and distance code lengths */\nvar LEN_ = 20; /* i: same as LEN below, but only first time in */\nvar LEN = 21; /* i: waiting for length/lit/eob code */\nvar LENEXT = 22; /* i: waiting for length extra bits */\nvar DIST = 23; /* i: waiting for distance code */\nvar DISTEXT = 24; /* i: waiting for distance extra bits */\nvar MATCH = 25; /* o: waiting for output space to copy string */\nvar LIT = 26; /* o: waiting for output space to write literal */\nvar CHECK = 27; /* i: waiting for 32-bit check value */\nvar LENGTH = 28; /* i: waiting for 32-bit length (gzip) */\nvar DONE = 29; /* finished check, done -- remain here until reset */\nvar BAD = 30; /* got a data error -- remain here until reset */\nvar MEM = 31; /* got an inflate() memory error -- remain here until reset */\nvar SYNC = 32; /* looking for synchronization bytes to restart inflate() */\n\n/* ===========================================================================*/\n\n\n\nvar ENOUGH_LENS = 852;\nvar ENOUGH_DISTS = 592;\n//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);\n\nvar MAX_WBITS = 15;\n/* 32K LZ77 window */\nvar DEF_WBITS = MAX_WBITS;\n\n\nfunction zswap32(q) {\n return (((q >>> 24) & 0xff) +\n ((q >>> 8) & 0xff00) +\n ((q & 0xff00) << 8) +\n ((q & 0xff) << 24));\n}\n\n\nfunction InflateState() {\n this.mode = 0; /* current inflate mode */\n this.last = false; /* true if processing last block */\n this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */\n this.havedict = false; /* true if dictionary provided */\n this.flags = 0; /* gzip header method and flags (0 if zlib) */\n this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */\n this.check = 0; /* protected copy of check value */\n this.total = 0; /* protected copy of output count */\n // TODO: may be {}\n this.head = null; /* where to save gzip header information */\n\n /* sliding window */\n this.wbits = 0; /* log base 2 of requested window size */\n this.wsize = 0; /* window size or zero if not using window */\n this.whave = 0; /* valid bytes in the window */\n this.wnext = 0; /* window write index */\n this.window = null; /* allocated sliding window, if needed */\n\n /* bit accumulator */\n this.hold = 0; /* input bit accumulator */\n this.bits = 0; /* number of bits in \"in\" */\n\n /* for string and stored block copying */\n this.length = 0; /* literal or length of data to copy */\n this.offset = 0; /* distance back to copy string from */\n\n /* for table and code decoding */\n this.extra = 0; /* extra bits needed */\n\n /* fixed and dynamic code tables */\n this.lencode = null; /* starting table for length/literal codes */\n this.distcode = null; /* starting table for distance codes */\n this.lenbits = 0; /* index bits for lencode */\n this.distbits = 0; /* index bits for distcode */\n\n /* dynamic table building */\n this.ncode = 0; /* number of code length code lengths */\n this.nlen = 0; /* number of length code lengths */\n this.ndist = 0; /* number of distance code lengths */\n this.have = 0; /* number of code lengths in lens[] */\n this.next = null; /* next available space in codes[] */\n\n this.lens = new utils.Buf16(320); /* temporary storage for code lengths */\n this.work = new utils.Buf16(288); /* work area for code table building */\n\n /*\n because we don't have pointers in js, we use lencode and distcode directly\n as buffers so we don't need codes\n */\n //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */\n this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */\n this.distdyn = null; /* dynamic table for distance codes (JS specific) */\n this.sane = 0; /* if false, allow invalid distance too far */\n this.back = 0; /* bits back of last unprocessed length/lit */\n this.was = 0; /* initial length of match */\n}\n\nfunction inflateResetKeep(strm) {\n var state;\n\n if (!strm || !strm.state) { return Z_STREAM_ERROR; }\n state = strm.state;\n strm.total_in = strm.total_out = state.total = 0;\n strm.msg = ''; /*Z_NULL*/\n if (state.wrap) { /* to support ill-conceived Java test suite */\n strm.adler = state.wrap & 1;\n }\n state.mode = HEAD;\n state.last = 0;\n state.havedict = 0;\n state.dmax = 32768;\n state.head = null/*Z_NULL*/;\n state.hold = 0;\n state.bits = 0;\n //state.lencode = state.distcode = state.next = state.codes;\n state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);\n state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);\n\n state.sane = 1;\n state.back = -1;\n //Tracev((stderr, \"inflate: reset\\n\"));\n return Z_OK;\n}\n\nfunction inflateReset(strm) {\n var state;\n\n if (!strm || !strm.state) { return Z_STREAM_ERROR; }\n state = strm.state;\n state.wsize = 0;\n state.whave = 0;\n state.wnext = 0;\n return inflateResetKeep(strm);\n\n}\n\nfunction inflateReset2(strm, windowBits) {\n var wrap;\n var state;\n\n /* get the state */\n if (!strm || !strm.state) { return Z_STREAM_ERROR; }\n state = strm.state;\n\n /* extract wrap request from windowBits parameter */\n if (windowBits < 0) {\n wrap = 0;\n windowBits = -windowBits;\n }\n else {\n wrap = (windowBits >> 4) + 1;\n if (windowBits < 48) {\n windowBits &= 15;\n }\n }\n\n /* set number of window bits, free window if different */\n if (windowBits && (windowBits < 8 || windowBits > 15)) {\n return Z_STREAM_ERROR;\n }\n if (state.window !== null && state.wbits !== windowBits) {\n state.window = null;\n }\n\n /* update state and reset the rest of it */\n state.wrap = wrap;\n state.wbits = windowBits;\n return inflateReset(strm);\n}\n\nfunction inflateInit2(strm, windowBits) {\n var ret;\n var state;\n\n if (!strm) { return Z_STREAM_ERROR; }\n //strm.msg = Z_NULL; /* in case we return an error */\n\n state = new InflateState();\n\n //if (state === Z_NULL) return Z_MEM_ERROR;\n //Tracev((stderr, \"inflate: allocated\\n\"));\n strm.state = state;\n state.window = null/*Z_NULL*/;\n ret = inflateReset2(strm, windowBits);\n if (ret !== Z_OK) {\n strm.state = null/*Z_NULL*/;\n }\n return ret;\n}\n\nfunction inflateInit(strm) {\n return inflateInit2(strm, DEF_WBITS);\n}\n\n\n/*\n Return state with length and distance decoding tables and index sizes set to\n fixed code decoding. Normally this returns fixed tables from inffixed.h.\n If BUILDFIXED is defined, then instead this routine builds the tables the\n first time it's called, and returns those tables the first time and\n thereafter. This reduces the size of the code by about 2K bytes, in\n exchange for a little execution time. However, BUILDFIXED should not be\n used for threaded applications, since the rewriting of the tables and virgin\n may not be thread-safe.\n */\nvar virgin = true;\n\nvar lenfix, distfix; // We have no pointers in JS, so keep tables separate\n\nfunction fixedtables(state) {\n /* build fixed huffman tables if first call (may not be thread safe) */\n if (virgin) {\n var sym;\n\n lenfix = new utils.Buf32(512);\n distfix = new utils.Buf32(32);\n\n /* literal/length table */\n sym = 0;\n while (sym < 144) { state.lens[sym++] = 8; }\n while (sym < 256) { state.lens[sym++] = 9; }\n while (sym < 280) { state.lens[sym++] = 7; }\n while (sym < 288) { state.lens[sym++] = 8; }\n\n inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 });\n\n /* distance table */\n sym = 0;\n while (sym < 32) { state.lens[sym++] = 5; }\n\n inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 });\n\n /* do this just once */\n virgin = false;\n }\n\n state.lencode = lenfix;\n state.lenbits = 9;\n state.distcode = distfix;\n state.distbits = 5;\n}\n\n\n/*\n Update the window with the last wsize (normally 32K) bytes written before\n returning. If window does not exist yet, create it. This is only called\n when a window is already in use, or when output has been written during this\n inflate call, but the end of the deflate stream has not been reached yet.\n It is also called to create a window for dictionary data when a dictionary\n is loaded.\n\n Providing output buffers larger than 32K to inflate() should provide a speed\n advantage, since only the last 32K of output is copied to the sliding window\n upon return from inflate(), and since all distances after the first 32K of\n output will fall in the output data, making match copies simpler and faster.\n The advantage may be dependent on the size of the processor's data caches.\n */\nfunction updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}\n\nfunction inflate(strm, flush) {\n var state;\n var input, output; // input/output buffers\n var next; /* next input INDEX */\n var put; /* next output INDEX */\n var have, left; /* available input and output */\n var hold; /* bit buffer */\n var bits; /* bits in bit buffer */\n var _in, _out; /* save starting available input and output */\n var copy; /* number of stored or match bytes to copy */\n var from; /* where to copy match bytes from */\n var from_source;\n var here = 0; /* current decoding table entry */\n var here_bits, here_op, here_val; // paked \"here\" denormalized (JS specific)\n //var last; /* parent table entry */\n var last_bits, last_op, last_val; // paked \"last\" denormalized (JS specific)\n var len; /* length to copy for repeats, bits to drop */\n var ret; /* return code */\n var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */\n var opts;\n\n var n; // temporary var for NEED_BITS\n\n var order = /* permutation of code lengths */\n [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ];\n\n\n if (!strm || !strm.state || !strm.output ||\n (!strm.input && strm.avail_in !== 0)) {\n return Z_STREAM_ERROR;\n }\n\n state = strm.state;\n if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */\n\n\n //--- LOAD() ---\n put = strm.next_out;\n output = strm.output;\n left = strm.avail_out;\n next = strm.next_in;\n input = strm.input;\n have = strm.avail_in;\n hold = state.hold;\n bits = state.bits;\n //---\n\n _in = have;\n _out = left;\n ret = Z_OK;\n\n inf_leave: // goto emulation\n for (;;) {\n switch (state.mode) {\n case HEAD:\n if (state.wrap === 0) {\n state.mode = TYPEDO;\n break;\n }\n //=== NEEDBITS(16);\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */\n state.check = 0/*crc32(0L, Z_NULL, 0)*/;\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32(state.check, hbuf, 2, 0);\n //===//\n\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = FLAGS;\n break;\n }\n state.flags = 0; /* expect zlib header */\n if (state.head) {\n state.head.done = false;\n }\n if (!(state.wrap & 1) || /* check if zlib header allowed */\n (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {\n strm.msg = 'incorrect header check';\n state.mode = BAD;\n break;\n }\n if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {\n strm.msg = 'unknown compression method';\n state.mode = BAD;\n break;\n }\n //--- DROPBITS(4) ---//\n hold >>>= 4;\n bits -= 4;\n //---//\n len = (hold & 0x0f)/*BITS(4)*/ + 8;\n if (state.wbits === 0) {\n state.wbits = len;\n }\n else if (len > state.wbits) {\n strm.msg = 'invalid window size';\n state.mode = BAD;\n break;\n }\n state.dmax = 1 << len;\n //Tracev((stderr, \"inflate: zlib header ok\\n\"));\n strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;\n state.mode = hold & 0x200 ? DICTID : TYPE;\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n break;\n case FLAGS:\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.flags = hold;\n if ((state.flags & 0xff) !== Z_DEFLATED) {\n strm.msg = 'unknown compression method';\n state.mode = BAD;\n break;\n }\n if (state.flags & 0xe000) {\n strm.msg = 'unknown header flags set';\n state.mode = BAD;\n break;\n }\n if (state.head) {\n state.head.text = ((hold >> 8) & 1);\n }\n if (state.flags & 0x0200) {\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32(state.check, hbuf, 2, 0);\n //===//\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = TIME;\n /* falls through */\n case TIME:\n //=== NEEDBITS(32); */\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (state.head) {\n state.head.time = hold;\n }\n if (state.flags & 0x0200) {\n //=== CRC4(state.check, hold)\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n hbuf[2] = (hold >>> 16) & 0xff;\n hbuf[3] = (hold >>> 24) & 0xff;\n state.check = crc32(state.check, hbuf, 4, 0);\n //===\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = OS;\n /* falls through */\n case OS:\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (state.head) {\n state.head.xflags = (hold & 0xff);\n state.head.os = (hold >> 8);\n }\n if (state.flags & 0x0200) {\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32(state.check, hbuf, 2, 0);\n //===//\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = EXLEN;\n /* falls through */\n case EXLEN:\n if (state.flags & 0x0400) {\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.length = hold;\n if (state.head) {\n state.head.extra_len = hold;\n }\n if (state.flags & 0x0200) {\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32(state.check, hbuf, 2, 0);\n //===//\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n }\n else if (state.head) {\n state.head.extra = null/*Z_NULL*/;\n }\n state.mode = EXTRA;\n /* falls through */\n case EXTRA:\n if (state.flags & 0x0400) {\n copy = state.length;\n if (copy > have) { copy = have; }\n if (copy) {\n if (state.head) {\n len = state.head.extra_len - state.length;\n if (!state.head.extra) {\n // Use untyped array for more conveniend processing later\n state.head.extra = new Array(state.head.extra_len);\n }\n utils.arraySet(\n state.head.extra,\n input,\n next,\n // extra field is limited to 65536 bytes\n // - no need for additional size check\n copy,\n /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/\n len\n );\n //zmemcpy(state.head.extra + len, next,\n // len + copy > state.head.extra_max ?\n // state.head.extra_max - len : copy);\n }\n if (state.flags & 0x0200) {\n state.check = crc32(state.check, input, copy, next);\n }\n have -= copy;\n next += copy;\n state.length -= copy;\n }\n if (state.length) { break inf_leave; }\n }\n state.length = 0;\n state.mode = NAME;\n /* falls through */\n case NAME:\n if (state.flags & 0x0800) {\n if (have === 0) { break inf_leave; }\n copy = 0;\n do {\n // TODO: 2 or 1 bytes?\n len = input[next + copy++];\n /* use constant limit because in js we should not preallocate memory */\n if (state.head && len &&\n (state.length < 65536 /*state.head.name_max*/)) {\n state.head.name += String.fromCharCode(len);\n }\n } while (len && copy < have);\n\n if (state.flags & 0x0200) {\n state.check = crc32(state.check, input, copy, next);\n }\n have -= copy;\n next += copy;\n if (len) { break inf_leave; }\n }\n else if (state.head) {\n state.head.name = null;\n }\n state.length = 0;\n state.mode = COMMENT;\n /* falls through */\n case COMMENT:\n if (state.flags & 0x1000) {\n if (have === 0) { break inf_leave; }\n copy = 0;\n do {\n len = input[next + copy++];\n /* use constant limit because in js we should not preallocate memory */\n if (state.head && len &&\n (state.length < 65536 /*state.head.comm_max*/)) {\n state.head.comment += String.fromCharCode(len);\n }\n } while (len && copy < have);\n if (state.flags & 0x0200) {\n state.check = crc32(state.check, input, copy, next);\n }\n have -= copy;\n next += copy;\n if (len) { break inf_leave; }\n }\n else if (state.head) {\n state.head.comment = null;\n }\n state.mode = HCRC;\n /* falls through */\n case HCRC:\n if (state.flags & 0x0200) {\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (hold !== (state.check & 0xffff)) {\n strm.msg = 'header crc mismatch';\n state.mode = BAD;\n break;\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n }\n if (state.head) {\n state.head.hcrc = ((state.flags >> 9) & 1);\n state.head.done = true;\n }\n strm.adler = state.check = 0;\n state.mode = TYPE;\n break;\n case DICTID:\n //=== NEEDBITS(32); */\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n strm.adler = state.check = zswap32(hold);\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = DICT;\n /* falls through */\n case DICT:\n if (state.havedict === 0) {\n //--- RESTORE() ---\n strm.next_out = put;\n strm.avail_out = left;\n strm.next_in = next;\n strm.avail_in = have;\n state.hold = hold;\n state.bits = bits;\n //---\n return Z_NEED_DICT;\n }\n strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;\n state.mode = TYPE;\n /* falls through */\n case TYPE:\n if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }\n /* falls through */\n case TYPEDO:\n if (state.last) {\n //--- BYTEBITS() ---//\n hold >>>= bits & 7;\n bits -= bits & 7;\n //---//\n state.mode = CHECK;\n break;\n }\n //=== NEEDBITS(3); */\n while (bits < 3) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.last = (hold & 0x01)/*BITS(1)*/;\n //--- DROPBITS(1) ---//\n hold >>>= 1;\n bits -= 1;\n //---//\n\n switch ((hold & 0x03)/*BITS(2)*/) {\n case 0: /* stored block */\n //Tracev((stderr, \"inflate: stored block%s\\n\",\n // state.last ? \" (last)\" : \"\"));\n state.mode = STORED;\n break;\n case 1: /* fixed block */\n fixedtables(state);\n //Tracev((stderr, \"inflate: fixed codes block%s\\n\",\n // state.last ? \" (last)\" : \"\"));\n state.mode = LEN_; /* decode codes */\n if (flush === Z_TREES) {\n //--- DROPBITS(2) ---//\n hold >>>= 2;\n bits -= 2;\n //---//\n break inf_leave;\n }\n break;\n case 2: /* dynamic block */\n //Tracev((stderr, \"inflate: dynamic codes block%s\\n\",\n // state.last ? \" (last)\" : \"\"));\n state.mode = TABLE;\n break;\n case 3:\n strm.msg = 'invalid block type';\n state.mode = BAD;\n }\n //--- DROPBITS(2) ---//\n hold >>>= 2;\n bits -= 2;\n //---//\n break;\n case STORED:\n //--- BYTEBITS() ---// /* go to byte boundary */\n hold >>>= bits & 7;\n bits -= bits & 7;\n //---//\n //=== NEEDBITS(32); */\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {\n strm.msg = 'invalid stored block lengths';\n state.mode = BAD;\n break;\n }\n state.length = hold & 0xffff;\n //Tracev((stderr, \"inflate: stored length %u\\n\",\n // state.length));\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = COPY_;\n if (flush === Z_TREES) { break inf_leave; }\n /* falls through */\n case COPY_:\n state.mode = COPY;\n /* falls through */\n case COPY:\n copy = state.length;\n if (copy) {\n if (copy > have) { copy = have; }\n if (copy > left) { copy = left; }\n if (copy === 0) { break inf_leave; }\n //--- zmemcpy(put, next, copy); ---\n utils.arraySet(output, input, next, copy, put);\n //---//\n have -= copy;\n next += copy;\n left -= copy;\n put += copy;\n state.length -= copy;\n break;\n }\n //Tracev((stderr, \"inflate: stored end\\n\"));\n state.mode = TYPE;\n break;\n case TABLE:\n //=== NEEDBITS(14); */\n while (bits < 14) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;\n //--- DROPBITS(5) ---//\n hold >>>= 5;\n bits -= 5;\n //---//\n state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;\n //--- DROPBITS(5) ---//\n hold >>>= 5;\n bits -= 5;\n //---//\n state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;\n //--- DROPBITS(4) ---//\n hold >>>= 4;\n bits -= 4;\n //---//\n//#ifndef PKZIP_BUG_WORKAROUND\n if (state.nlen > 286 || state.ndist > 30) {\n strm.msg = 'too many length or distance symbols';\n state.mode = BAD;\n break;\n }\n//#endif\n //Tracev((stderr, \"inflate: table sizes ok\\n\"));\n state.have = 0;\n state.mode = LENLENS;\n /* falls through */\n case LENLENS:\n while (state.have < state.ncode) {\n //=== NEEDBITS(3);\n while (bits < 3) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);\n //--- DROPBITS(3) ---//\n hold >>>= 3;\n bits -= 3;\n //---//\n }\n while (state.have < 19) {\n state.lens[order[state.have++]] = 0;\n }\n // We have separate tables & no pointers. 2 commented lines below not needed.\n //state.next = state.codes;\n //state.lencode = state.next;\n // Switch to use dynamic table\n state.lencode = state.lendyn;\n state.lenbits = 7;\n\n opts = { bits: state.lenbits };\n ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);\n state.lenbits = opts.bits;\n\n if (ret) {\n strm.msg = 'invalid code lengths set';\n state.mode = BAD;\n break;\n }\n //Tracev((stderr, \"inflate: code lengths ok\\n\"));\n state.have = 0;\n state.mode = CODELENS;\n /* falls through */\n case CODELENS:\n while (state.have < state.nlen + state.ndist) {\n for (;;) {\n here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n if (here_val < 16) {\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n state.lens[state.have++] = here_val;\n }\n else {\n if (here_val === 16) {\n //=== NEEDBITS(here.bits + 2);\n n = here_bits + 2;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n if (state.have === 0) {\n strm.msg = 'invalid bit length repeat';\n state.mode = BAD;\n break;\n }\n len = state.lens[state.have - 1];\n copy = 3 + (hold & 0x03);//BITS(2);\n //--- DROPBITS(2) ---//\n hold >>>= 2;\n bits -= 2;\n //---//\n }\n else if (here_val === 17) {\n //=== NEEDBITS(here.bits + 3);\n n = here_bits + 3;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n len = 0;\n copy = 3 + (hold & 0x07);//BITS(3);\n //--- DROPBITS(3) ---//\n hold >>>= 3;\n bits -= 3;\n //---//\n }\n else {\n //=== NEEDBITS(here.bits + 7);\n n = here_bits + 7;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n len = 0;\n copy = 11 + (hold & 0x7f);//BITS(7);\n //--- DROPBITS(7) ---//\n hold >>>= 7;\n bits -= 7;\n //---//\n }\n if (state.have + copy > state.nlen + state.ndist) {\n strm.msg = 'invalid bit length repeat';\n state.mode = BAD;\n break;\n }\n while (copy--) {\n state.lens[state.have++] = len;\n }\n }\n }\n\n /* handle error breaks in while */\n if (state.mode === BAD) { break; }\n\n /* check for end-of-block code (better have one) */\n if (state.lens[256] === 0) {\n strm.msg = 'invalid code -- missing end-of-block';\n state.mode = BAD;\n break;\n }\n\n /* build code tables -- note: do not change the lenbits or distbits\n values here (9 and 6) without reading the comments in inftrees.h\n concerning the ENOUGH constants, which depend on those values */\n state.lenbits = 9;\n\n opts = { bits: state.lenbits };\n ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);\n // We have separate tables & no pointers. 2 commented lines below not needed.\n // state.next_index = opts.table_index;\n state.lenbits = opts.bits;\n // state.lencode = state.next;\n\n if (ret) {\n strm.msg = 'invalid literal/lengths set';\n state.mode = BAD;\n break;\n }\n\n state.distbits = 6;\n //state.distcode.copy(state.codes);\n // Switch to use dynamic table\n state.distcode = state.distdyn;\n opts = { bits: state.distbits };\n ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);\n // We have separate tables & no pointers. 2 commented lines below not needed.\n // state.next_index = opts.table_index;\n state.distbits = opts.bits;\n // state.distcode = state.next;\n\n if (ret) {\n strm.msg = 'invalid distances set';\n state.mode = BAD;\n break;\n }\n //Tracev((stderr, 'inflate: codes ok\\n'));\n state.mode = LEN_;\n if (flush === Z_TREES) { break inf_leave; }\n /* falls through */\n case LEN_:\n state.mode = LEN;\n /* falls through */\n case LEN:\n if (have >= 6 && left >= 258) {\n //--- RESTORE() ---\n strm.next_out = put;\n strm.avail_out = left;\n strm.next_in = next;\n strm.avail_in = have;\n state.hold = hold;\n state.bits = bits;\n //---\n inflate_fast(strm, _out);\n //--- LOAD() ---\n put = strm.next_out;\n output = strm.output;\n left = strm.avail_out;\n next = strm.next_in;\n input = strm.input;\n have = strm.avail_in;\n hold = state.hold;\n bits = state.bits;\n //---\n\n if (state.mode === TYPE) {\n state.back = -1;\n }\n break;\n }\n state.back = 0;\n for (;;) {\n here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if (here_bits <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n if (here_op && (here_op & 0xf0) === 0) {\n last_bits = here_bits;\n last_op = here_op;\n last_val = here_val;\n for (;;) {\n here = state.lencode[last_val +\n ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((last_bits + here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n //--- DROPBITS(last.bits) ---//\n hold >>>= last_bits;\n bits -= last_bits;\n //---//\n state.back += last_bits;\n }\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n state.back += here_bits;\n state.length = here_val;\n if (here_op === 0) {\n //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?\n // \"inflate: literal '%c'\\n\" :\n // \"inflate: literal 0x%02x\\n\", here.val));\n state.mode = LIT;\n break;\n }\n if (here_op & 32) {\n //Tracevv((stderr, \"inflate: end of block\\n\"));\n state.back = -1;\n state.mode = TYPE;\n break;\n }\n if (here_op & 64) {\n strm.msg = 'invalid literal/length code';\n state.mode = BAD;\n break;\n }\n state.extra = here_op & 15;\n state.mode = LENEXT;\n /* falls through */\n case LENEXT:\n if (state.extra) {\n //=== NEEDBITS(state.extra);\n n = state.extra;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;\n //--- DROPBITS(state.extra) ---//\n hold >>>= state.extra;\n bits -= state.extra;\n //---//\n state.back += state.extra;\n }\n //Tracevv((stderr, \"inflate: length %u\\n\", state.length));\n state.was = state.length;\n state.mode = DIST;\n /* falls through */\n case DIST:\n for (;;) {\n here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n if ((here_op & 0xf0) === 0) {\n last_bits = here_bits;\n last_op = here_op;\n last_val = here_val;\n for (;;) {\n here = state.distcode[last_val +\n ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((last_bits + here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n //--- DROPBITS(last.bits) ---//\n hold >>>= last_bits;\n bits -= last_bits;\n //---//\n state.back += last_bits;\n }\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n state.back += here_bits;\n if (here_op & 64) {\n strm.msg = 'invalid distance code';\n state.mode = BAD;\n break;\n }\n state.offset = here_val;\n state.extra = (here_op) & 15;\n state.mode = DISTEXT;\n /* falls through */\n case DISTEXT:\n if (state.extra) {\n //=== NEEDBITS(state.extra);\n n = state.extra;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;\n //--- DROPBITS(state.extra) ---//\n hold >>>= state.extra;\n bits -= state.extra;\n //---//\n state.back += state.extra;\n }\n//#ifdef INFLATE_STRICT\n if (state.offset > state.dmax) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD;\n break;\n }\n//#endif\n //Tracevv((stderr, \"inflate: distance %u\\n\", state.offset));\n state.mode = MATCH;\n /* falls through */\n case MATCH:\n if (left === 0) { break inf_leave; }\n copy = _out - left;\n if (state.offset > copy) { /* copy from window */\n copy = state.offset - copy;\n if (copy > state.whave) {\n if (state.sane) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD;\n break;\n }\n// (!) This block is disabled in zlib defailts,\n// don't enable it for binary compatibility\n//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR\n// Trace((stderr, \"inflate.c too far\\n\"));\n// copy -= state.whave;\n// if (copy > state.length) { copy = state.length; }\n// if (copy > left) { copy = left; }\n// left -= copy;\n// state.length -= copy;\n// do {\n// output[put++] = 0;\n// } while (--copy);\n// if (state.length === 0) { state.mode = LEN; }\n// break;\n//#endif\n }\n if (copy > state.wnext) {\n copy -= state.wnext;\n from = state.wsize - copy;\n }\n else {\n from = state.wnext - copy;\n }\n if (copy > state.length) { copy = state.length; }\n from_source = state.window;\n }\n else { /* copy from output */\n from_source = output;\n from = put - state.offset;\n copy = state.length;\n }\n if (copy > left) { copy = left; }\n left -= copy;\n state.length -= copy;\n do {\n output[put++] = from_source[from++];\n } while (--copy);\n if (state.length === 0) { state.mode = LEN; }\n break;\n case LIT:\n if (left === 0) { break inf_leave; }\n output[put++] = state.length;\n left--;\n state.mode = LEN;\n break;\n case CHECK:\n if (state.wrap) {\n //=== NEEDBITS(32);\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n // Use '|' insdead of '+' to make sure that result is signed\n hold |= input[next++] << bits;\n bits += 8;\n }\n //===//\n _out -= left;\n strm.total_out += _out;\n state.total += _out;\n if (_out) {\n strm.adler = state.check =\n /*UPDATE(state.check, put - _out, _out);*/\n (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));\n\n }\n _out = left;\n // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too\n if ((state.flags ? hold : zswap32(hold)) !== state.check) {\n strm.msg = 'incorrect data check';\n state.mode = BAD;\n break;\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n //Tracev((stderr, \"inflate: check matches trailer\\n\"));\n }\n state.mode = LENGTH;\n /* falls through */\n case LENGTH:\n if (state.wrap && state.flags) {\n //=== NEEDBITS(32);\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (hold !== (state.total & 0xffffffff)) {\n strm.msg = 'incorrect length check';\n state.mode = BAD;\n break;\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n //Tracev((stderr, \"inflate: length matches trailer\\n\"));\n }\n state.mode = DONE;\n /* falls through */\n case DONE:\n ret = Z_STREAM_END;\n break inf_leave;\n case BAD:\n ret = Z_DATA_ERROR;\n break inf_leave;\n case MEM:\n return Z_MEM_ERROR;\n case SYNC:\n /* falls through */\n default:\n return Z_STREAM_ERROR;\n }\n }\n\n // inf_leave <- here is real place for \"goto inf_leave\", emulated via \"break inf_leave\"\n\n /*\n Return from inflate(), updating the total counts and the check value.\n If there was no progress during the inflate() call, return a buffer\n error. Call updatewindow() to create and/or update the window state.\n Note: a memory error from inflate() is non-recoverable.\n */\n\n //--- RESTORE() ---\n strm.next_out = put;\n strm.avail_out = left;\n strm.next_in = next;\n strm.avail_in = have;\n state.hold = hold;\n state.bits = bits;\n //---\n\n if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&\n (state.mode < CHECK || flush !== Z_FINISH))) {\n if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {\n state.mode = MEM;\n return Z_MEM_ERROR;\n }\n }\n _in -= strm.avail_in;\n _out -= strm.avail_out;\n strm.total_in += _in;\n strm.total_out += _out;\n state.total += _out;\n if (state.wrap && _out) {\n strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/\n (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));\n }\n strm.data_type = state.bits + (state.last ? 64 : 0) +\n (state.mode === TYPE ? 128 : 0) +\n (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);\n if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {\n ret = Z_BUF_ERROR;\n }\n return ret;\n}\n\nfunction inflateEnd(strm) {\n\n if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {\n return Z_STREAM_ERROR;\n }\n\n var state = strm.state;\n if (state.window) {\n state.window = null;\n }\n strm.state = null;\n return Z_OK;\n}\n\nfunction inflateGetHeader(strm, head) {\n var state;\n\n /* check state */\n if (!strm || !strm.state) { return Z_STREAM_ERROR; }\n state = strm.state;\n if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }\n\n /* save header structure */\n state.head = head;\n head.done = false;\n return Z_OK;\n}\n\nfunction inflateSetDictionary(strm, dictionary) {\n var dictLength = dictionary.length;\n\n var state;\n var dictid;\n var ret;\n\n /* check state */\n if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; }\n state = strm.state;\n\n if (state.wrap !== 0 && state.mode !== DICT) {\n return Z_STREAM_ERROR;\n }\n\n /* check for correct dictionary identifier */\n if (state.mode === DICT) {\n dictid = 1; /* adler32(0, null, 0)*/\n /* dictid = adler32(dictid, dictionary, dictLength); */\n dictid = adler32(dictid, dictionary, dictLength, 0);\n if (dictid !== state.check) {\n return Z_DATA_ERROR;\n }\n }\n /* copy dictionary to window using updatewindow(), which will amend the\n existing dictionary if appropriate */\n ret = updatewindow(strm, dictionary, dictLength, dictLength);\n if (ret) {\n state.mode = MEM;\n return Z_MEM_ERROR;\n }\n state.havedict = 1;\n // Tracev((stderr, \"inflate: dictionary set\\n\"));\n return Z_OK;\n}\n\nexports.inflateReset = inflateReset;\nexports.inflateReset2 = inflateReset2;\nexports.inflateResetKeep = inflateResetKeep;\nexports.inflateInit = inflateInit;\nexports.inflateInit2 = inflateInit2;\nexports.inflate = inflate;\nexports.inflateEnd = inflateEnd;\nexports.inflateGetHeader = inflateGetHeader;\nexports.inflateSetDictionary = inflateSetDictionary;\nexports.inflateInfo = 'pako inflate (from Nodeca project)';\n\n/* Not implemented\nexports.inflateCopy = inflateCopy;\nexports.inflateGetDictionary = inflateGetDictionary;\nexports.inflateMark = inflateMark;\nexports.inflatePrime = inflatePrime;\nexports.inflateSync = inflateSync;\nexports.inflateSyncPoint = inflateSyncPoint;\nexports.inflateUndermine = inflateUndermine;\n*/\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/pako/lib/zlib/inflate.js\n// module id = 30\n// module chunks = 0","'use strict';\n\n\nvar utils = require('../utils/common');\n\nvar MAXBITS = 15;\nvar ENOUGH_LENS = 852;\nvar ENOUGH_DISTS = 592;\n//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);\n\nvar CODES = 0;\nvar LENS = 1;\nvar DISTS = 2;\n\nvar lbase = [ /* Length codes 257..285 base */\n 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,\n 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0\n];\n\nvar lext = [ /* Length codes 257..285 extra */\n 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,\n 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78\n];\n\nvar dbase = [ /* Distance codes 0..29 base */\n 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,\n 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,\n 8193, 12289, 16385, 24577, 0, 0\n];\n\nvar dext = [ /* Distance codes 0..29 extra */\n 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,\n 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,\n 28, 28, 29, 29, 64, 64\n];\n\nmodule.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)\n{\n var bits = opts.bits;\n //here = opts.here; /* table entry for duplication */\n\n var len = 0; /* a code's length in bits */\n var sym = 0; /* index of code symbols */\n var min = 0, max = 0; /* minimum and maximum code lengths */\n var root = 0; /* number of index bits for root table */\n var curr = 0; /* number of index bits for current table */\n var drop = 0; /* code bits to drop for sub-table */\n var left = 0; /* number of prefix codes available */\n var used = 0; /* code entries in table used */\n var huff = 0; /* Huffman code */\n var incr; /* for incrementing code, index */\n var fill; /* index for replicating entries */\n var low; /* low bits for current root entry */\n var mask; /* mask for low root bits */\n var next; /* next available space in table */\n var base = null; /* base value table to use */\n var base_index = 0;\n// var shoextra; /* extra bits table to use */\n var end; /* use base and extra for symbol > end */\n var count = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */\n var offs = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */\n var extra = null;\n var extra_index = 0;\n\n var here_bits, here_op, here_val;\n\n /*\n Process a set of code lengths to create a canonical Huffman code. The\n code lengths are lens[0..codes-1]. Each length corresponds to the\n symbols 0..codes-1. The Huffman code is generated by first sorting the\n symbols by length from short to long, and retaining the symbol order\n for codes with equal lengths. Then the code starts with all zero bits\n for the first code of the shortest length, and the codes are integer\n increments for the same length, and zeros are appended as the length\n increases. For the deflate format, these bits are stored backwards\n from their more natural integer increment ordering, and so when the\n decoding tables are built in the large loop below, the integer codes\n are incremented backwards.\n\n This routine assumes, but does not check, that all of the entries in\n lens[] are in the range 0..MAXBITS. The caller must assure this.\n 1..MAXBITS is interpreted as that code length. zero means that that\n symbol does not occur in this code.\n\n The codes are sorted by computing a count of codes for each length,\n creating from that a table of starting indices for each length in the\n sorted table, and then entering the symbols in order in the sorted\n table. The sorted table is work[], with that space being provided by\n the caller.\n\n The length counts are used for other purposes as well, i.e. finding\n the minimum and maximum length codes, determining if there are any\n codes at all, checking for a valid set of lengths, and looking ahead\n at length counts to determine sub-table sizes when building the\n decoding tables.\n */\n\n /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */\n for (len = 0; len <= MAXBITS; len++) {\n count[len] = 0;\n }\n for (sym = 0; sym < codes; sym++) {\n count[lens[lens_index + sym]]++;\n }\n\n /* bound code lengths, force root to be within code lengths */\n root = bits;\n for (max = MAXBITS; max >= 1; max--) {\n if (count[max] !== 0) { break; }\n }\n if (root > max) {\n root = max;\n }\n if (max === 0) { /* no symbols to code at all */\n //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */\n //table.bits[opts.table_index] = 1; //here.bits = (var char)1;\n //table.val[opts.table_index++] = 0; //here.val = (var short)0;\n table[table_index++] = (1 << 24) | (64 << 16) | 0;\n\n\n //table.op[opts.table_index] = 64;\n //table.bits[opts.table_index] = 1;\n //table.val[opts.table_index++] = 0;\n table[table_index++] = (1 << 24) | (64 << 16) | 0;\n\n opts.bits = 1;\n return 0; /* no symbols, but wait for decoding to report error */\n }\n for (min = 1; min < max; min++) {\n if (count[min] !== 0) { break; }\n }\n if (root < min) {\n root = min;\n }\n\n /* check for an over-subscribed or incomplete set of lengths */\n left = 1;\n for (len = 1; len <= MAXBITS; len++) {\n left <<= 1;\n left -= count[len];\n if (left < 0) {\n return -1;\n } /* over-subscribed */\n }\n if (left > 0 && (type === CODES || max !== 1)) {\n return -1; /* incomplete set */\n }\n\n /* generate offsets into symbol table for each length for sorting */\n offs[1] = 0;\n for (len = 1; len < MAXBITS; len++) {\n offs[len + 1] = offs[len] + count[len];\n }\n\n /* sort symbols by length, by symbol order within each length */\n for (sym = 0; sym < codes; sym++) {\n if (lens[lens_index + sym] !== 0) {\n work[offs[lens[lens_index + sym]]++] = sym;\n }\n }\n\n /*\n Create and fill in decoding tables. In this loop, the table being\n filled is at next and has curr index bits. The code being used is huff\n with length len. That code is converted to an index by dropping drop\n bits off of the bottom. For codes where len is less than drop + curr,\n those top drop + curr - len bits are incremented through all values to\n fill the table with replicated entries.\n\n root is the number of index bits for the root table. When len exceeds\n root, sub-tables are created pointed to by the root entry with an index\n of the low root bits of huff. This is saved in low to check for when a\n new sub-table should be started. drop is zero when the root table is\n being filled, and drop is root when sub-tables are being filled.\n\n When a new sub-table is needed, it is necessary to look ahead in the\n code lengths to determine what size sub-table is needed. The length\n counts are used for this, and so count[] is decremented as codes are\n entered in the tables.\n\n used keeps track of how many table entries have been allocated from the\n provided *table space. It is checked for LENS and DIST tables against\n the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in\n the initial root table size constants. See the comments in inftrees.h\n for more information.\n\n sym increments through all symbols, and the loop terminates when\n all codes of length max, i.e. all codes, have been processed. This\n routine permits incomplete codes, so another loop after this one fills\n in the rest of the decoding tables with invalid code markers.\n */\n\n /* set up for code type */\n // poor man optimization - use if-else instead of switch,\n // to avoid deopts in old v8\n if (type === CODES) {\n base = extra = work; /* dummy value--not used */\n end = 19;\n\n } else if (type === LENS) {\n base = lbase;\n base_index -= 257;\n extra = lext;\n extra_index -= 257;\n end = 256;\n\n } else { /* DISTS */\n base = dbase;\n extra = dext;\n end = -1;\n }\n\n /* initialize opts for loop */\n huff = 0; /* starting code */\n sym = 0; /* starting code symbol */\n len = min; /* starting code length */\n next = table_index; /* current table to fill in */\n curr = root; /* current table index bits */\n drop = 0; /* current bits to drop from code for index */\n low = -1; /* trigger new sub-table when len > root */\n used = 1 << root; /* use root table entries */\n mask = used - 1; /* mask for comparing low */\n\n /* check available table space */\n if ((type === LENS && used > ENOUGH_LENS) ||\n (type === DISTS && used > ENOUGH_DISTS)) {\n return 1;\n }\n\n /* process all codes and make table entries */\n for (;;) {\n /* create table entry */\n here_bits = len - drop;\n if (work[sym] < end) {\n here_op = 0;\n here_val = work[sym];\n }\n else if (work[sym] > end) {\n here_op = extra[extra_index + work[sym]];\n here_val = base[base_index + work[sym]];\n }\n else {\n here_op = 32 + 64; /* end of block */\n here_val = 0;\n }\n\n /* replicate for those indices with low len bits equal to huff */\n incr = 1 << (len - drop);\n fill = 1 << curr;\n min = fill; /* save offset to next table */\n do {\n fill -= incr;\n table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;\n } while (fill !== 0);\n\n /* backwards increment the len-bit code huff */\n incr = 1 << (len - 1);\n while (huff & incr) {\n incr >>= 1;\n }\n if (incr !== 0) {\n huff &= incr - 1;\n huff += incr;\n } else {\n huff = 0;\n }\n\n /* go to next symbol, update count, len */\n sym++;\n if (--count[len] === 0) {\n if (len === max) { break; }\n len = lens[lens_index + work[sym]];\n }\n\n /* create new sub-table if needed */\n if (len > root && (huff & mask) !== low) {\n /* if first time, transition to sub-tables */\n if (drop === 0) {\n drop = root;\n }\n\n /* increment past last table */\n next += min; /* here min is 1 << curr */\n\n /* determine length of next table */\n curr = len - drop;\n left = 1 << curr;\n while (curr + drop < max) {\n left -= count[curr + drop];\n if (left <= 0) { break; }\n curr++;\n left <<= 1;\n }\n\n /* check for enough space */\n used += 1 << curr;\n if ((type === LENS && used > ENOUGH_LENS) ||\n (type === DISTS && used > ENOUGH_DISTS)) {\n return 1;\n }\n\n /* point entry in root table to sub-table */\n low = huff & mask;\n /*table.op[low] = curr;\n table.bits[low] = root;\n table.val[low] = next - opts.table_index;*/\n table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;\n }\n }\n\n /* fill in remaining table entry if code is incomplete (guaranteed to have\n at most one remaining entry, since if the code is incomplete, the\n maximum code length that was allowed to get this far is one bit) */\n if (huff !== 0) {\n //table.op[next + huff] = 64; /* invalid code marker */\n //table.bits[next + huff] = len - drop;\n //table.val[next + huff] = 0;\n table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;\n }\n\n /* set return parameters */\n //opts.table_index += used;\n opts.bits = root;\n return 0;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/pako/lib/zlib/inftrees.js\n// module id = 31\n// module chunks = 0","'use strict';\n\nmodule.exports = {\n 2: 'need dictionary', /* Z_NEED_DICT 2 */\n 1: 'stream end', /* Z_STREAM_END 1 */\n 0: '', /* Z_OK 0 */\n '-1': 'file error', /* Z_ERRNO (-1) */\n '-2': 'stream error', /* Z_STREAM_ERROR (-2) */\n '-3': 'data error', /* Z_DATA_ERROR (-3) */\n '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */\n '-5': 'buffer error', /* Z_BUF_ERROR (-5) */\n '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/pako/lib/zlib/messages.js\n// module id = 32\n// module chunks = 0","'use strict';\n\n\nfunction ZStream() {\n /* next input byte */\n this.input = null; // JS specific, because we have no pointers\n this.next_in = 0;\n /* number of bytes available at input */\n this.avail_in = 0;\n /* total number of input bytes read so far */\n this.total_in = 0;\n /* next output byte should be put there */\n this.output = null; // JS specific, because we have no pointers\n this.next_out = 0;\n /* remaining free space at output */\n this.avail_out = 0;\n /* total number of bytes output so far */\n this.total_out = 0;\n /* last error message, NULL if no error */\n this.msg = ''/*Z_NULL*/;\n /* not visible by applications */\n this.state = null;\n /* best guess about the data type: binary or text */\n this.data_type = 2/*Z_UNKNOWN*/;\n /* adler32 value of the uncompressed data */\n this.adler = 0;\n}\n\nmodule.exports = ZStream;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/pako/lib/zlib/zstream.js\n// module id = 33\n// module chunks = 0","module.exports = require(\"./lib/_stream_duplex.js\")\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/readable-stream/duplex.js\n// module id = 34\n// module chunks = 0","'use strict';\n\nvar Buffer = require('buffer').Buffer;\n/**/\nvar bufferShim = require('buffer-shims');\n/**/\n\nmodule.exports = BufferList;\n\nfunction BufferList() {\n this.head = null;\n this.tail = null;\n this.length = 0;\n}\n\nBufferList.prototype.push = function (v) {\n var entry = { data: v, next: null };\n if (this.length > 0) this.tail.next = entry;else this.head = entry;\n this.tail = entry;\n ++this.length;\n};\n\nBufferList.prototype.unshift = function (v) {\n var entry = { data: v, next: this.head };\n if (this.length === 0) this.tail = entry;\n this.head = entry;\n ++this.length;\n};\n\nBufferList.prototype.shift = function () {\n if (this.length === 0) return;\n var ret = this.head.data;\n if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;\n --this.length;\n return ret;\n};\n\nBufferList.prototype.clear = function () {\n this.head = this.tail = null;\n this.length = 0;\n};\n\nBufferList.prototype.join = function (s) {\n if (this.length === 0) return '';\n var p = this.head;\n var ret = '' + p.data;\n while (p = p.next) {\n ret += s + p.data;\n }return ret;\n};\n\nBufferList.prototype.concat = function (n) {\n if (this.length === 0) return bufferShim.alloc(0);\n if (this.length === 1) return this.head.data;\n var ret = bufferShim.allocUnsafe(n >>> 0);\n var p = this.head;\n var i = 0;\n while (p) {\n p.data.copy(ret, i);\n i += p.data.length;\n p = p.next;\n }\n return ret;\n};\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/readable-stream/lib/internal/streams/BufferList.js\n// module id = 35\n// module chunks = 0","module.exports = require(\"./lib/_stream_passthrough.js\")\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/readable-stream/passthrough.js\n// module id = 36\n// module chunks = 0","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\nif (!process.browser && process.env.READABLE_STREAM === 'disable' && Stream) {\n module.exports = Stream;\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/readable-stream/readable.js\n// module id = 37\n// module chunks = 0","module.exports = require(\"./lib/_stream_transform.js\")\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/readable-stream/transform.js\n// module id = 38\n// module chunks = 0","module.exports = require(\"./lib/_stream_writable.js\")\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/readable-stream/writable.js\n// module id = 39\n// module chunks = 0","\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\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/util-deprecate/browser.js\n// module id = 40\n// module chunks = 0","module.exports = function(module) {\r\n\tif(!module.webpackPolyfill) {\r\n\t\tmodule.deprecate = function() {};\r\n\t\tmodule.paths = [];\r\n\t\t// module.parent = undefined by default\r\n\t\tmodule.children = [];\r\n\t\tmodule.webpackPolyfill = 1;\r\n\t}\r\n\treturn module;\r\n}\r\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// (webpack)/buildin/module.js\n// module id = 41\n// module chunks = 0"],"sourceRoot":""} \ No newline at end of file diff --git a/bundles/utils.js b/bundles/utils.js deleted file mode 100644 index 3bd2986..0000000 --- a/bundles/utils.js +++ /dev/null @@ -1,26 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.isWindowOrWorker = isWindowOrWorker; -exports.getBaseURL = getBaseURL; -exports.httpHeaderSafeJson = httpHeaderSafeJson; -function getSafeUnicode(c) { - var unicode = ('000' + c.charCodeAt(0).toString(16)).slice(-4); - return '\\u' + unicode; -} - -/* global WorkerGlobalScope */ -function isWindowOrWorker() { - return typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope || typeof module === 'undefined' || typeof window !== 'undefined'; -} - -function getBaseURL(host) { - return 'https://' + host + '.dropboxapi.com/2/'; -} - -// source https://www.dropboxforum.com/t5/API-support/HTTP-header-quot-Dropbox-API-Arg-quot-could-not-decode-input-as/m-p/173823/highlight/true#M6786 -function httpHeaderSafeJson(args) { - return JSON.stringify(args).replace(/[\u007f-\uffff]/g, getSafeUnicode); -} \ No newline at end of file diff --git a/how-to-test.md b/how-to-test.md deleted file mode 100644 index 52267bc..0000000 --- a/how-to-test.md +++ /dev/null @@ -1,46 +0,0 @@ -# Testing solid-rest-file - -## Requirements - - * **Time** half an hour - * **Skills** ability to use a command-line (terminal) program - * **Software** any version of nodejs - -## How to run the test - - 1. In your browser, go to [solid-rest-file](https://github.com/jeff-zucker/solid-rest-file) - - 2. Click on **clone or download** (green button in upper right) - - 3. Download the zip file (or if you know git, clone the repo and skip to step #6) - - 4. In your terminal, change to the locations of the downloaded zip - - 5. Unzip the file solid-rest-file-master.zip - - 6. Change directory into the solid-rest-file-master - - 7. Enter the command: npm install - - 8. Enter the command: node tests/all - -## How to report the results - - -Send an email to me at dubzed@gmail.com. which includes: - - * the name and version of your operating system (e.g Linux Mint 18.3, Mac, Windows) - * whether it's ok to contact you with questions - * the results of the tests as shown below - -The expected result is a long list of the word "ok". If that's what you -see, report the results as "all tests passed". Otherwise, please take a -screenshot and attach it to the email, or cut and paste the results into -the email or simply manually copy the results into the email. - -## Questions or problems? - -Go to [the Solid app-development chat room](https://gitter.im/solid/app-development) -and ping @jeff-zucker and I'll respond as soon as I can. I'm on the U.S. west coast, -so usually availble 8am to 11pm Pacific Daylight Time which is 5pm through 8am Central -European Time. diff --git a/jest.config.js b/jest.config.js deleted file mode 100644 index ac52a32..0000000 --- a/jest.config.js +++ /dev/null @@ -1,185 +0,0 @@ -// For a detailed explanation regarding each configuration property, visit: -// https://jestjs.io/docs/en/configuration.html - -module.exports = { - // All imported modules in your tests should be mocked automatically - // automock: false, - - // Stop running tests after `n` failures - // bail: 0, - - // Respect "browser" field in package.json when resolving modules - // browser: false, - - // The directory where Jest should store its cached dependency information - // cacheDirectory: "/tmp/jest_rs", - - // Automatically clear mock calls and instances between every test - // clearMocks: false, - - // Indicates whether the coverage information should be collected while executing the test - // collectCoverage: false, - - // An array of glob patterns indicating a set of files for which coverage information should be collected - // collectCoverageFrom: null, - - // The directory where Jest should output its coverage files - // coverageDirectory: null, - - // An array of regexp pattern strings used to skip coverage collection - // coveragePathIgnorePatterns: [ - // "/node_modules/" - // ], - - // A list of reporter names that Jest uses when writing coverage reports - // coverageReporters: [ - // "json", - // "text", - // "lcov", - // "clover" - // ], - - // An object that configures minimum threshold enforcement for coverage results - // coverageThreshold: null, - - // A path to a custom dependency extractor - // dependencyExtractor: null, - - // Make calling deprecated APIs throw helpful error messages - // errorOnDeprecated: false, - - // Force coverage collection from ignored files using an array of glob patterns - // forceCoverageMatch: [], - - // A path to a module which exports an async function that is triggered once before all test suites - // globalSetup: null, - - // A path to a module which exports an async function that is triggered once after all test suites - // globalTeardown: null, - - // A set of global variables that need to be available in all test environments - // globals: {}, - - // An array of directory names to be searched recursively up from the requiring module's location - // moduleDirectories: [ - // "node_modules" - // ], - - // An array of file extensions your modules use - // moduleFileExtensions: [ - // "js", - // "json", - // "jsx", - // "ts", - // "tsx", - // "node" - // ], - - // A map from regular expressions to module names that allow to stub out resources with a single module - // moduleNameMapper: {}, - - // An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader - // modulePathIgnorePatterns: [], - - // Activates notifications for test results - // notify: false, - - // An enum that specifies notification mode. Requires { notify: true } - // notifyMode: "failure-change", - - // A preset that is used as a base for Jest's configuration - // preset: null, - - // Run tests from one or more projects - // projects: null, - - // Use this configuration option to add custom reporters to Jest - // reporters: undefined, - - // Automatically reset mock state between every test - // resetMocks: false, - - // Reset the module registry before running each individual test - // resetModules: false, - - // A path to a custom resolver - // resolver: null, - - // Automatically restore mock state between every test - // restoreMocks: false, - - // The root directory that Jest should scan for tests and modules within - // rootDir: null, - - // A list of paths to directories that Jest should use to search for files in - // roots: [ - // "" - // ], - - // Allows you to use a custom runner instead of Jest's default test runner - // runner: "jest-runner", - - // The paths to modules that run some code to configure or set up the testing environment before each test - // setupFiles: [], - - // A list of paths to modules that run some code to configure or set up the testing framework before each test - // setupFilesAfterEnv: [], - - // A list of paths to snapshot serializer modules Jest should use for snapshot testing - // snapshotSerializers: [], - - // The test environment that will be used for testing - testEnvironment: "node", - - // Options that will be passed to the testEnvironment - // testEnvironmentOptions: {}, - - // Adds a location field to test results - // testLocationInResults: false, - - // The glob patterns Jest uses to detect test files - // testMatch: [ - // "**/__tests__/**/*.[jt]s?(x)", - // "**/?(*.)+(spec|test).[tj]s?(x)" - // ], - - // An array of regexp pattern strings that are matched against all test paths, matched tests are skipped - // testPathIgnorePatterns: [ - // "/node_modules/" - // ], - - // The regexp pattern or array of patterns that Jest uses to detect test files - // testRegex: [], - - // This option allows the use of a custom results processor - // testResultsProcessor: null, - - // This option allows use of a custom test runner - // testRunner: "jasmine2", - - // This option sets the URL for the jsdom environment. It is reflected in properties such as location.href - // testURL: "http://localhost", - - // Setting this value to "fake" allows the use of fake timers for functions such as "setTimeout" - // timers: "real", - - // A map from regular expressions to paths to transformers - // transform: null, - - // An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation - // transformIgnorePatterns: [ - // "/node_modules/" - // ], - - // An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them - // unmockedModulePathPatterns: undefined, - - // Indicates whether each individual test should be reported during the run - // verbose: null, - - // An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode - // watchPathIgnorePatterns: [], - - // Whether to use watchman for file crawling - // watchman: true, -}; diff --git a/package-lock.json b/package-lock.json index 9f321bb..cdcfa21 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,6 +1,6 @@ { "name": "solid-rest", - "version": "1.3.1", + "version": "1.4.0", "lockfileVersion": 1, "requires": true, "dependencies": { @@ -405,11 +405,6 @@ "integrity": "sha1-x57Zf380y48robyXkLzDZkdLS3k=", "dev": true }, - "at-least-node": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/at-least-node/-/at-least-node-1.0.0.tgz", - "integrity": "sha512-+q/t7Ekv1EDY2l6Gda6LLiX14rU9TV20Wa3ofeQmwPFZbOMo9DXrLbOjFaaclkXKWidIaopwAObQDqwWtGUjqg==" - }, "atob": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/atob/-/atob-2.1.2.tgz", @@ -464,14 +459,6 @@ "private": "^0.1.8", "slash": "^1.0.0", "source-map": "^0.5.7" - }, - "dependencies": { - "json5": { - "version": "0.5.1", - "resolved": "https://registry.npmjs.org/json5/-/json5-0.5.1.tgz", - "integrity": "sha1-Hq3nrMASA0rYTiOWdn6tn6VJWCE=", - "dev": true - } } }, "babel-generator": { @@ -1194,17 +1181,6 @@ "lodash": "^4.17.4", "mkdirp": "^0.5.1", "source-map-support": "^0.4.15" - }, - "dependencies": { - "source-map-support": { - "version": "0.4.18", - "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.4.18.tgz", - "integrity": "sha512-try0/JqxPLF9nOjvSta7tVondkP5dwgyLDjVoyMDlmjugT2lRZ1OfsrYTkCd2hkDnJTKRbO/Rl3orm8vlsUzbA==", - "dev": true, - "requires": { - "source-map": "^0.5.6" - } - } } }, "babel-runtime": { @@ -1354,16 +1330,6 @@ "dev": true, "optional": true }, - "bindings": { - "version": "1.5.0", - "resolved": "https://registry.npmjs.org/bindings/-/bindings-1.5.0.tgz", - "integrity": "sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ==", - "dev": true, - "optional": true, - "requires": { - "file-uri-to-path": "1.0.0" - } - }, "bluebird": { "version": "3.7.2", "resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.7.2.tgz", @@ -1485,17 +1451,6 @@ "safe-buffer": "^5.2.0" }, "dependencies": { - "readable-stream": { - "version": "3.6.0", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.0.tgz", - "integrity": "sha512-BViHy7LKeTz4oNnkcLJ+lVSL6vpiFeX6/d3oSH8zCW7UxP2onchk+vTGB143xuFjHS3deTgkKoXXymXqymiIdA==", - "dev": true, - "requires": { - "inherits": "^2.0.3", - "string_decoder": "^1.1.1", - "util-deprecate": "^1.0.1" - } - }, "safe-buffer": { "version": "5.2.1", "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", @@ -1527,7 +1482,8 @@ "buffer-from": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.1.tgz", - "integrity": "sha512-MQcXEUbCKtEo7bhqEs6560Hyd4XaovZlO/k9V3hjVUF/zwW7KBVdSK4gIt/bzwS9MbR5qob+F5jusZsb0YQK2A==" + "integrity": "sha512-MQcXEUbCKtEo7bhqEs6560Hyd4XaovZlO/k9V3hjVUF/zwW7KBVdSK4gIt/bzwS9MbR5qob+F5jusZsb0YQK2A==", + "dev": true }, "buffer-xor": { "version": "1.0.3", @@ -1839,24 +1795,39 @@ "dev": true }, "concat-stream": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-2.0.0.tgz", - "integrity": "sha512-MWufYdFw53ccGjCA+Ol7XJYpAlW6/prSMzuPOTRnJGcGzuhLn4Scrz7qf6o8bROZ514ltazcIFJZevcfbo0x7A==", + "version": "1.6.2", + "resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-1.6.2.tgz", + "integrity": "sha512-27HBghJxjiZtIk3Ycvn/4kbJk/1uZuJFfuPEns6LaEvpvG1f0hTea8lilrouyo9mVc2GWdcEZ8OLoGmSADlrCw==", + "dev": true, "requires": { "buffer-from": "^1.0.0", "inherits": "^2.0.3", - "readable-stream": "^3.0.2", + "readable-stream": "^2.2.2", "typedarray": "^0.0.6" }, "dependencies": { "readable-stream": { - "version": "3.6.0", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.0.tgz", - "integrity": "sha512-BViHy7LKeTz4oNnkcLJ+lVSL6vpiFeX6/d3oSH8zCW7UxP2onchk+vTGB143xuFjHS3deTgkKoXXymXqymiIdA==", + "version": "2.3.7", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.7.tgz", + "integrity": "sha512-Ebho8K4jIbHAxnuxi7o42OrZgF/ZTNcsZj6nRKyUmkhLFq8CHItp/fy6hQZuZmP/n3yZ9VBUbp4zz/mX8hmYPw==", + "dev": true, "requires": { - "inherits": "^2.0.3", - "string_decoder": "^1.1.1", - "util-deprecate": "^1.0.1" + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "string_decoder": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "dev": true, + "requires": { + "safe-buffer": "~5.1.0" } } } @@ -2154,6 +2125,32 @@ "inherits": "^2.0.1", "readable-stream": "^2.0.0", "stream-shift": "^1.0.0" + }, + "dependencies": { + "readable-stream": { + "version": "2.3.7", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.7.tgz", + "integrity": "sha512-Ebho8K4jIbHAxnuxi7o42OrZgF/ZTNcsZj6nRKyUmkhLFq8CHItp/fy6hQZuZmP/n3yZ9VBUbp4zz/mX8hmYPw==", + "dev": true, + "requires": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "string_decoder": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "dev": true, + "requires": { + "safe-buffer": "~5.1.0" + } + } } }, "ecc-jsbn": { @@ -2224,6 +2221,30 @@ "errno": "^0.1.3", "readable-stream": "^2.0.1" } + }, + "readable-stream": { + "version": "2.3.7", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.7.tgz", + "integrity": "sha512-Ebho8K4jIbHAxnuxi7o42OrZgF/ZTNcsZj6nRKyUmkhLFq8CHItp/fy6hQZuZmP/n3yZ9VBUbp4zz/mX8hmYPw==", + "dev": true, + "requires": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "string_decoder": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "dev": true, + "requires": { + "safe-buffer": "~5.1.0" + } } } }, @@ -2511,13 +2532,6 @@ "integrity": "sha512-0btnI/H8f2pavGMN8w40mlSKOfTK2SVJmBfBeVIj3kNw0swwgzyRq0d5TJVOwodFmtvpPeWPN/MCcfuWF0Ezbw==", "dev": true }, - "file-uri-to-path": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/file-uri-to-path/-/file-uri-to-path-1.0.0.tgz", - "integrity": "sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw==", - "dev": true, - "optional": true - }, "fill-range": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-4.0.0.tgz", @@ -2569,6 +2583,32 @@ "requires": { "inherits": "^2.0.3", "readable-stream": "^2.3.6" + }, + "dependencies": { + "readable-stream": { + "version": "2.3.7", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.7.tgz", + "integrity": "sha512-Ebho8K4jIbHAxnuxi7o42OrZgF/ZTNcsZj6nRKyUmkhLFq8CHItp/fy6hQZuZmP/n3yZ9VBUbp4zz/mX8hmYPw==", + "dev": true, + "requires": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "string_decoder": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "dev": true, + "requires": { + "safe-buffer": "~5.1.0" + } + } } }, "for-in": { @@ -2611,17 +2651,32 @@ "requires": { "inherits": "^2.0.1", "readable-stream": "^2.0.0" - } - }, - "fs-extra": { - "version": "9.0.1", - "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-9.0.1.tgz", - "integrity": "sha512-h2iAoN838FqAFJY2/qVpzFXy+EBxfVE220PalAqQLDVsFOHLJrZvut5puAbCdNv6WJk+B8ihI+k0c7JK5erwqQ==", - "requires": { - "at-least-node": "^1.0.0", - "graceful-fs": "^4.2.0", - "jsonfile": "^6.0.1", - "universalify": "^1.0.0" + }, + "dependencies": { + "readable-stream": { + "version": "2.3.7", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.7.tgz", + "integrity": "sha512-Ebho8K4jIbHAxnuxi7o42OrZgF/ZTNcsZj6nRKyUmkhLFq8CHItp/fy6hQZuZmP/n3yZ9VBUbp4zz/mX8hmYPw==", + "dev": true, + "requires": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "string_decoder": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "dev": true, + "requires": { + "safe-buffer": "~5.1.0" + } + } } }, "fs-write-stream-atomic": { @@ -2634,6 +2689,32 @@ "iferr": "^0.1.5", "imurmurhash": "^0.1.4", "readable-stream": "1 || 2" + }, + "dependencies": { + "readable-stream": { + "version": "2.3.7", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.7.tgz", + "integrity": "sha512-Ebho8K4jIbHAxnuxi7o42OrZgF/ZTNcsZj6nRKyUmkhLFq8CHItp/fy6hQZuZmP/n3yZ9VBUbp4zz/mX8hmYPw==", + "dev": true, + "requires": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "string_decoder": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "dev": true, + "requires": { + "safe-buffer": "~5.1.0" + } + } } }, "fs.realpath": { @@ -2723,7 +2804,8 @@ "graceful-fs": { "version": "4.2.4", "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.4.tgz", - "integrity": "sha512-WjKPNJF79dtJAVniUlGGWHYGz2jWxT6VhN/4m1NdkbZ2nOsEF+cI1Edgql5zCRhs/VsQYRvrXctxktVXZUkixw==" + "integrity": "sha512-WjKPNJF79dtJAVniUlGGWHYGz2jWxT6VhN/4m1NdkbZ2nOsEF+cI1Edgql5zCRhs/VsQYRvrXctxktVXZUkixw==", + "dev": true }, "har-schema": { "version": "2.0.0", @@ -2814,17 +2896,6 @@ "safe-buffer": "^5.2.0" }, "dependencies": { - "readable-stream": { - "version": "3.6.0", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.0.tgz", - "integrity": "sha512-BViHy7LKeTz4oNnkcLJ+lVSL6vpiFeX6/d3oSH8zCW7UxP2onchk+vTGB143xuFjHS3deTgkKoXXymXqymiIdA==", - "dev": true, - "requires": { - "inherits": "^2.0.3", - "string_decoder": "^1.1.1", - "util-deprecate": "^1.0.1" - } - }, "safe-buffer": { "version": "5.2.1", "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", @@ -2979,7 +3050,8 @@ "inherits": { "version": "2.0.4", "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", - "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "dev": true }, "interpret": { "version": "2.2.0", @@ -3122,9 +3194,9 @@ } }, "is-negative-zero": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/is-negative-zero/-/is-negative-zero-2.0.0.tgz", - "integrity": "sha1-lVOxIbD6wohp2p7UWeIMdUN4hGE=", + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/is-negative-zero/-/is-negative-zero-2.0.1.tgz", + "integrity": "sha512-2z6JzQvZRa9A2Y7xC6dQQm4FSTSTNWjKIYYTt4246eMTJmIo0Q+ZyOsU66X8lxK1AbB92dFeglPLrhwpeRKO6w==", "dev": true }, "is-number": { @@ -3265,29 +3337,10 @@ "dev": true }, "json5": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/json5/-/json5-1.0.1.tgz", - "integrity": "sha512-aKS4WQjPenRxiQsC93MNfjx+nbF4PAdYzmd/1JIj8HYzqfbu86beTuNgXDzPknWk0n0uARlyewZo4s++ES36Ow==", - "dev": true, - "requires": { - "minimist": "^1.2.0" - } - }, - "jsonfile": { - "version": "6.1.0", - "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.1.0.tgz", - "integrity": "sha512-5dgndWOriYSm5cnYaJNhalLNDKOqFwyDB/rr1E9ZsGciGvKPs8R2xYGCacuf3z6K1YKDz182fd+fY3cn3pMqXQ==", - "requires": { - "graceful-fs": "^4.1.6", - "universalify": "^2.0.0" - }, - "dependencies": { - "universalify": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.0.tgz", - "integrity": "sha512-hAZsKq7Yy11Zu1DE0OzWjw7nnLZmJZYTDZZyEFHZdUhV8FkH5MCfoU1XMaxXovpyW5nq5scPqq0ZDP9Zyl04oQ==" - } - } + "version": "0.5.1", + "resolved": "https://registry.npmjs.org/json5/-/json5-0.5.1.tgz", + "integrity": "sha1-Hq3nrMASA0rYTiOWdn6tn6VJWCE=", + "dev": true }, "jsonld": { "version": "3.2.0", @@ -3304,12 +3357,6 @@ "xmldom": "0.1.19" }, "dependencies": { - "semver": { - "version": "6.3.0", - "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", - "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", - "dev": true - }, "xmldom": { "version": "0.1.19", "resolved": "https://registry.npmjs.org/xmldom/-/xmldom-0.1.19.tgz", @@ -3357,6 +3404,17 @@ "big.js": "^5.2.2", "emojis-list": "^3.0.0", "json5": "^1.0.1" + }, + "dependencies": { + "json5": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/json5/-/json5-1.0.1.tgz", + "integrity": "sha512-aKS4WQjPenRxiQsC93MNfjx+nbF4PAdYzmd/1JIj8HYzqfbu86beTuNgXDzPknWk0n0uARlyewZo4s++ES36Ow==", + "dev": true, + "requires": { + "minimist": "^1.2.0" + } + } } }, "locate-path": { @@ -3401,6 +3459,14 @@ "requires": { "pify": "^4.0.1", "semver": "^5.6.0" + }, + "dependencies": { + "semver": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz", + "integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==", + "dev": true + } } }, "map-cache": { @@ -3437,6 +3503,32 @@ "requires": { "errno": "^0.1.3", "readable-stream": "^2.0.1" + }, + "dependencies": { + "readable-stream": { + "version": "2.3.7", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.7.tgz", + "integrity": "sha512-Ebho8K4jIbHAxnuxi7o42OrZgF/ZTNcsZj6nRKyUmkhLFq8CHItp/fy6hQZuZmP/n3yZ9VBUbp4zz/mX8hmYPw==", + "dev": true, + "requires": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "string_decoder": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "dev": true, + "requires": { + "safe-buffer": "~5.1.0" + } + } } }, "merge-stream": { @@ -3546,20 +3638,6 @@ "pumpify": "^1.3.3", "stream-each": "^1.1.0", "through2": "^2.0.0" - }, - "dependencies": { - "concat-stream": { - "version": "1.6.2", - "resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-1.6.2.tgz", - "integrity": "sha512-27HBghJxjiZtIk3Ycvn/4kbJk/1uZuJFfuPEns6LaEvpvG1f0hTea8lilrouyo9mVc2GWdcEZ8OLoGmSADlrCw==", - "dev": true, - "requires": { - "buffer-from": "^1.0.0", - "inherits": "^2.0.3", - "readable-stream": "^2.2.2", - "typedarray": "^0.0.6" - } - } } }, "mixin-deep": { @@ -3631,28 +3709,8 @@ "requires": { "queue-microtask": "^1.1.2", "readable-stream": "^3.6.0" - }, - "dependencies": { - "readable-stream": { - "version": "3.6.0", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.0.tgz", - "integrity": "sha512-BViHy7LKeTz4oNnkcLJ+lVSL6vpiFeX6/d3oSH8zCW7UxP2onchk+vTGB143xuFjHS3deTgkKoXXymXqymiIdA==", - "dev": true, - "requires": { - "inherits": "^2.0.3", - "string_decoder": "^1.1.1", - "util-deprecate": "^1.0.1" - } - } } }, - "nan": { - "version": "2.14.2", - "resolved": "https://registry.npmjs.org/nan/-/nan-2.14.2.tgz", - "integrity": "sha512-M2ufzIiINKCuDfBSAUr1vWQ+vuVcA9kqx8JJUsbQi6yf1uGRyb7HfpdfUr5qLXf3B/t8dPvcjhKMmlfnP47EzQ==", - "dev": true, - "optional": true - }, "nanomatch": { "version": "1.2.13", "resolved": "https://registry.npmjs.org/nanomatch/-/nanomatch-1.2.13.tgz", @@ -3725,6 +3783,32 @@ "resolved": "https://registry.npmjs.org/punycode/-/punycode-1.4.1.tgz", "integrity": "sha1-wNWmOycYgArY4esPpSachN1BhF4=", "dev": true + }, + "readable-stream": { + "version": "2.3.7", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.7.tgz", + "integrity": "sha512-Ebho8K4jIbHAxnuxi7o42OrZgF/ZTNcsZj6nRKyUmkhLFq8CHItp/fy6hQZuZmP/n3yZ9VBUbp4zz/mX8hmYPw==", + "dev": true, + "requires": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + }, + "dependencies": { + "string_decoder": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "dev": true, + "requires": { + "safe-buffer": "~5.1.0" + } + } + } } } }, @@ -3916,6 +4000,32 @@ "cyclist": "^1.0.1", "inherits": "^2.0.3", "readable-stream": "^2.1.5" + }, + "dependencies": { + "readable-stream": { + "version": "2.3.7", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.7.tgz", + "integrity": "sha512-Ebho8K4jIbHAxnuxi7o42OrZgF/ZTNcsZj6nRKyUmkhLFq8CHItp/fy6hQZuZmP/n3yZ9VBUbp4zz/mX8hmYPw==", + "dev": true, + "requires": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "string_decoder": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "dev": true, + "requires": { + "safe-buffer": "~5.1.0" + } + } } }, "parse-asn1": { @@ -4169,14 +4279,6 @@ "requires": { "node-forge": "^0.10.0", "semver": "^6.3.0" - }, - "dependencies": { - "semver": { - "version": "6.3.0", - "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", - "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", - "dev": true - } } }, "rdflib": { @@ -4194,18 +4296,14 @@ } }, "readable-stream": { - "version": "2.3.7", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.7.tgz", - "integrity": "sha512-Ebho8K4jIbHAxnuxi7o42OrZgF/ZTNcsZj6nRKyUmkhLFq8CHItp/fy6hQZuZmP/n3yZ9VBUbp4zz/mX8hmYPw==", + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.0.tgz", + "integrity": "sha512-BViHy7LKeTz4oNnkcLJ+lVSL6vpiFeX6/d3oSH8zCW7UxP2onchk+vTGB143xuFjHS3deTgkKoXXymXqymiIdA==", "dev": true, "requires": { - "core-util-is": "~1.0.0", - "inherits": "~2.0.3", - "isarray": "~1.0.0", - "process-nextick-args": "~2.0.0", - "safe-buffer": "~5.1.1", - "string_decoder": "~1.1.1", - "util-deprecate": "~1.0.1" + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" } }, "readdirp": { @@ -4432,7 +4530,8 @@ "safe-buffer": { "version": "5.1.2", "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", - "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==" + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", + "dev": true }, "safe-regex": { "version": "1.1.0", @@ -4461,9 +4560,9 @@ } }, "semver": { - "version": "5.7.1", - "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz", - "integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==", + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", + "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", "dev": true }, "serialize-javascript": { @@ -4674,21 +4773,12 @@ } }, "source-map-support": { - "version": "0.5.19", - "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.19.tgz", - "integrity": "sha512-Wonm7zOCIJzBGQdB+thsPar0kYuCIzYvxZwlBa87yi/Mdjv7Tip2cyVbLj5o0cFPN4EVkuTwb3GDDyUx2DGnGw==", + "version": "0.4.18", + "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.4.18.tgz", + "integrity": "sha512-try0/JqxPLF9nOjvSta7tVondkP5dwgyLDjVoyMDlmjugT2lRZ1OfsrYTkCd2hkDnJTKRbO/Rl3orm8vlsUzbA==", "dev": true, "requires": { - "buffer-from": "^1.0.0", - "source-map": "^0.6.0" - }, - "dependencies": { - "source-map": { - "version": "0.6.1", - "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", - "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", - "dev": true - } + "source-map": "^0.5.6" } }, "source-map-url": { @@ -4761,6 +4851,32 @@ "requires": { "inherits": "~2.0.1", "readable-stream": "^2.0.2" + }, + "dependencies": { + "readable-stream": { + "version": "2.3.7", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.7.tgz", + "integrity": "sha512-Ebho8K4jIbHAxnuxi7o42OrZgF/ZTNcsZj6nRKyUmkhLFq8CHItp/fy6hQZuZmP/n3yZ9VBUbp4zz/mX8hmYPw==", + "dev": true, + "requires": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "string_decoder": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "dev": true, + "requires": { + "safe-buffer": "~5.1.0" + } + } } }, "stream-each": { @@ -4784,6 +4900,32 @@ "readable-stream": "^2.3.6", "to-arraybuffer": "^1.0.0", "xtend": "^4.0.0" + }, + "dependencies": { + "readable-stream": { + "version": "2.3.7", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.7.tgz", + "integrity": "sha512-Ebho8K4jIbHAxnuxi7o42OrZgF/ZTNcsZj6nRKyUmkhLFq8CHItp/fy6hQZuZmP/n3yZ9VBUbp4zz/mX8hmYPw==", + "dev": true, + "requires": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "string_decoder": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "dev": true, + "requires": { + "safe-buffer": "~5.1.0" + } + } } }, "stream-shift": { @@ -4813,11 +4955,20 @@ } }, "string_decoder": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", - "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", + "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", + "dev": true, "requires": { - "safe-buffer": "~5.1.0" + "safe-buffer": "~5.2.0" + }, + "dependencies": { + "safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "dev": true + } } }, "strip-ansi": { @@ -4875,6 +5026,16 @@ "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", "dev": true + }, + "source-map-support": { + "version": "0.5.19", + "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.19.tgz", + "integrity": "sha512-Wonm7zOCIJzBGQdB+thsPar0kYuCIzYvxZwlBa87yi/Mdjv7Tip2cyVbLj5o0cFPN4EVkuTwb3GDDyUx2DGnGw==", + "dev": true, + "requires": { + "buffer-from": "^1.0.0", + "source-map": "^0.6.0" + } } } }, @@ -4911,6 +5072,32 @@ "requires": { "readable-stream": "~2.3.6", "xtend": "~4.0.1" + }, + "dependencies": { + "readable-stream": { + "version": "2.3.7", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.7.tgz", + "integrity": "sha512-Ebho8K4jIbHAxnuxi7o42OrZgF/ZTNcsZj6nRKyUmkhLFq8CHItp/fy6hQZuZmP/n3yZ9VBUbp4zz/mX8hmYPw==", + "dev": true, + "requires": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "string_decoder": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "dev": true, + "requires": { + "safe-buffer": "~5.1.0" + } + } } }, "timers-browserify": { @@ -5022,7 +5209,8 @@ "typedarray": { "version": "0.0.6", "resolved": "https://registry.npmjs.org/typedarray/-/typedarray-0.0.6.tgz", - "integrity": "sha1-hnrHTjhkGHsdPUfZlqeOxciDB3c=" + "integrity": "sha1-hnrHTjhkGHsdPUfZlqeOxciDB3c=", + "dev": true }, "typical": { "version": "5.2.0", @@ -5060,11 +5248,6 @@ "imurmurhash": "^0.1.4" } }, - "universalify": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/universalify/-/universalify-1.0.0.tgz", - "integrity": "sha512-rb6X1W158d7pRQBg5gkR8uPaSfiids68LTJQYOtEUhoJUWBdaQHsuT/EUduxXYxcrt4r5PJ4fuHW1MHT6p0qug==" - }, "unset-value": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/unset-value/-/unset-value-1.0.0.tgz", @@ -5171,7 +5354,8 @@ "util-deprecate": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", - "integrity": "sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8=" + "integrity": "sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8=", + "dev": true }, "uuid": { "version": "8.3.1", @@ -5279,11 +5463,7 @@ "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-1.2.13.tgz", "integrity": "sha512-oWb1Z6mkHIskLzEJ/XWX0srkpkTQ7vaopMQkyaEIoq0fmtFVxOthb8cCxeT+p3ynTdkk/RZwbgG4brR5BeWECw==", "dev": true, - "optional": true, - "requires": { - "bindings": "^1.5.0", - "nan": "^2.12.1" - } + "optional": true }, "glob-parent": { "version": "3.1.0", @@ -5318,6 +5498,22 @@ "binary-extensions": "^1.0.0" } }, + "readable-stream": { + "version": "2.3.7", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.7.tgz", + "integrity": "sha512-Ebho8K4jIbHAxnuxi7o42OrZgF/ZTNcsZj6nRKyUmkhLFq8CHItp/fy6hQZuZmP/n3yZ9VBUbp4zz/mX8hmYPw==", + "dev": true, + "optional": true, + "requires": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, "readdirp": { "version": "2.2.1", "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-2.2.1.tgz", @@ -5329,6 +5525,16 @@ "micromatch": "^3.1.10", "readable-stream": "^2.0.2" } + }, + "string_decoder": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "dev": true, + "optional": true, + "requires": { + "safe-buffer": "~5.1.0" + } } } }, diff --git a/package.json b/package.json index 9007894..9e571bd 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "solid-rest", - "version": "1.3.1", + "version": "1.4.0", "author": "Jeff Zucker", "license": "MIT", "description": "treat any storage as a mini Solid server", @@ -30,15 +30,10 @@ }, "homepage": "https://github.com/jeff-zucker/solid-rest#readme", "dependencies": { - "concat-stream": "2.0.0", "cross-fetch": "3.0.6", - "fs-extra": "9.0.1", "mime-types": "2.1.27", "uuid": "8.3.1" }, - "peerDependencies": { - "browserfs": "1.4.3" - }, "devDependencies": { "babel-core": "6.26.3", "babel-preset-es2015": "6.24.1", diff --git a/src/browserFS.js b/plugins/solid-rest-bfs/browserFS.js similarity index 100% rename from src/browserFS.js rename to plugins/solid-rest-bfs/browserFS.js diff --git a/plugins/solid-rest-file/package.json b/plugins/solid-rest-file/package.json new file mode 100644 index 0000000..b9c08ad --- /dev/null +++ b/plugins/solid-rest-file/package.json @@ -0,0 +1,12 @@ +{ + "name": "solid-rest-file", + "version": "1.2.0", + "description": "", + "main": "src/index.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "keywords": [], + "author": "", + "license": "ISC" +} diff --git a/src/file.js b/plugins/solid-rest-file/src/index.js similarity index 91% rename from src/file.js rename to plugins/solid-rest-file/src/index.js index 42e0801..a3d1f76 100644 --- a/src/file.js +++ b/plugins/solid-rest-file/src/index.js @@ -6,7 +6,7 @@ const fs = require("fs-extra"); class SolidFileStorage { constructor() { this.prefix = "file" - this.name = "solid-rest-file-storage-1.0.0" + this.name = "solid-rest-file-1.0.0" } _makeStream(text){ @@ -32,10 +32,12 @@ class SolidFileStorage { return text(stream).then(text => JSON.parse(text)) } -async getObjectType(fn,options){ +async getObjectType(fn,request){ + request = request.request || request; + fn = fn.replace( request.protocol+'//','') let stat; try { stat = fs.lstatSync(fn); } - catch(err){ } + catch(err){} let read=true,write=true; if( stat ) { try { @@ -48,12 +50,19 @@ async getObjectType(fn,options){ catch(e){write=false} } let mode = { - read: (read), - write: (write) + read: read, + write: write, + append: write, } let type = ( stat && stat.isDirectory()) ? "Container" : "Resource"; if(!stat && fn.endsWith('/')) type = "Container" - return Promise.resolve( [type,stat,mode] ) + stat = stat ? true : false + let item = { + mode : mode, + exists : stat, + isContainer : type==="Container" ? true : false, + } + return Promise.resolve( [type,stat,mode,item] ) } async getResource(pathname,options,objectType){ @@ -171,7 +180,7 @@ postContainer(fn,options){ } async makeContainers(pathname, options){ const foldername = path.dirname(pathname) - const [type, exists] = await this.getObjectType(foldername); + const [type, exists] = await this.getObjectType(foldername,options.request); if (!exists) { try { fs.mkdirpSync(foldername); diff --git a/plugins/solid-rest-mem/package.json b/plugins/solid-rest-mem/package.json new file mode 100644 index 0000000..5e58c5f --- /dev/null +++ b/plugins/solid-rest-mem/package.json @@ -0,0 +1,12 @@ +{ + "name": "solid-rest-mem", + "version": "1.0.0", + "description": "", + "main": "src/index.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "keywords": [], + "author": "", + "license": "MIT" +} diff --git a/src/localStorage.js b/plugins/solid-rest-mem/src/index.js similarity index 94% rename from src/localStorage.js rename to plugins/solid-rest-mem/src/index.js index 0244612..0141b8b 100644 --- a/src/localStorage.js +++ b/plugins/solid-rest-mem/src/index.js @@ -2,10 +2,10 @@ constructor should define the pacakage's name by default this will be added to the x-powered-by header of all responses */ -class SolidLocalStorage { +class SolidMemStorage { constructor() { - this.prefix = "ls" - this.name = "solid-rest-localStorage-1.0.0" + this.prefix = "mem" + this.name = "solid-rest-mem-1.0.0" localStorage.setItem( "/", " " ); } @@ -26,7 +26,14 @@ async getObjectType(pathname,options){ if(type==="Container" && item.startsWith(pathname)){ exists=true; break } if(item === pathname){ exists=true; break } } - return [type,exists] + let mode = {read:true,write:true,append:true} + let item = { + pathname : pathname, + mode : mode, + exists : exists, + isContainer : type==="Containter", + } + return [type,exists,mode,item] } /* @@ -186,5 +193,5 @@ if(typeof window==="undefined") { removeItem : (key) => { delete localStorage[key] }, setItem : (key,val) => { localStorage[key]=val }, } - module.exports = SolidLocalStorage + module.exports = SolidMemStorage } diff --git a/src/actions.js b/src/actions.js new file mode 100644 index 0000000..c4ad3e4 --- /dev/null +++ b/src/actions.js @@ -0,0 +1,29 @@ +import u from './utils.js'; +import {containerAsturtle} from './container.js'; + +async function GET(pathname,options,storage){ + if( options.item.isContainer ){ + let files = await storage.getContainer(pathname,options) + return await containerAsturtle(pathname,options,files,storage) + } + else { + return await storage.getResource(pathname,options) + } +} + +async function DELETE(pathname,options,storage){ + const links = await u.getLinks(pathname, options,storage); + if (links.length) + links.map( async (link) => { + await storage.deleteResource(link,options) + }) + if (options.item.isContainer) + return await storage.deleteContainer(pathname,options) + else + return await storage.deleteResource(pathname,options) +} + +export default { + DELETE, + GET, +} diff --git a/src/container.js b/src/container.js new file mode 100644 index 0000000..190ec2d --- /dev/null +++ b/src/container.js @@ -0,0 +1,40 @@ +import u from './utils.js'; + +export async function containerAsturtle( pathname, options, contentsArray, storage ){ + const pathSep = u.pathSep( options.item.pathHandler ); + if(typeof storage.container2turtle != "undefined") + return storage.container2turtle(pathname,options,contentsArray) + let filenames=contentsArray.filter( item => { + if(!item.endsWith('.acl') && !item.endsWith('.meta')){ return item } + }) + + // cxRes + if ( !pathname.endsWith(pathSep) ) pathname += pathSep + // if (!pathname.endsWith("/")) pathname += "/" + + let str2 = "" + let str = "@prefix : <#>. @prefix ldp: .\n" + + "<> a ldp:BasicContainer, ldp:Container" + if(filenames.length){ + str = str + "; ldp:contains\n"; + for(var i=0;i,\n` + + let ctype = u.getContentType(u.getExtension(fn,options),'Resource') + ctype = ctype.replace(/;.*/,'') + ftype = ftype==="Container" ? "ldp:Container; a ldp:BasicContainer" : "ldp:Resource" + str2 = str2 + `<${fn}> a ${ftype}.\n` + str2 = str2 + `<${fn}> a .\n` + // str2 = str2 + `<${fn}> :type "${ctype}".\n` + } + str = str.replace(/,\n$/,"") + } + str = str + `.\n` + str2 + // str = _makeStream(str); + return ([200,str]) + } + diff --git a/src/error.js b/src/error.js new file mode 100644 index 0000000..07f2ba3 --- /dev/null +++ b/src/error.js @@ -0,0 +1,30 @@ +import u from './utils.js'; + +export function checkRestErrors( options, request, item ){ + if( !request.url) return(400); + if( request.slug.endsWith('/') ) return(400); + if( request.method==='DELETE' && item.containerNotEmpty ) return(409); + if( u.isAuxResource(options) && request.method==="POST") return(405); + const methods = { + DELETE : { mustPrexist:1, requiresWrite:1 }, + POST : { mustPrexist:1, requiresAppend:1, requiresContentType:1 }, + GET : { mustPrexist:1, requiresRead:1 }, + HEAD : { mustPrexist:1, requiresRead:1 }, + OPTIONS : { mustPrexist:1, requiresRead:1 }, + PUT : { requiresWrite:1, requiresContentType:1 }, + PATCH : { requiresWrite:1, requiresContentType:1 }, + } + const method = methods[request.method]; + if( !method ) return(409); + if( method.mustPrexist && !item.exists ) return(404); + if( (method.requiresRead && !item.mode.read) + || (method.requiresWrite && !item.mode.write ) + || (method.requiresAppend && !item.mode.append ) + ) return (401); + if( method.requiresContentType && !request.headers['content-type'] ) + return (400); + if ( (request.method==='PUT'||request.method==='PATCH') && item.isContainer ) + return(405) +} +// ENDS + diff --git a/src/item.js b/src/item.js new file mode 100644 index 0000000..46deb1e --- /dev/null +++ b/src/item.js @@ -0,0 +1,30 @@ +import Url from "url"; +import u from './utils.js'; + +export async function getItem(uri,request,storage){ + const [objectType,objectExists,mode,item] = + await storage.getObjectType(uri,request) + item.mode = item.mode ? item.mode : {read:true,append:true,write:true}; + let pathHandler,url; + if (request.protocol.startsWith('file')) { + url = Url.format(request.url) + item.rest_prefix = 'file' + // item.pathname = Url.fileURLToPath(url) + item.pathHandler = 'default' + } + else { + url = decodeURIComponent(uri) + // item.pathname = Url.parse(url).pathname + item.rest_prefix=uri.replace(request.protocol+'//','').replace(/\/.*$/,'') + item.pathHandler = 'posix' + } + item.pathname = uri.replace(request.protocol+'//','') + if( request.method==='DELETE' && item.isContainer){ + let files = await storage.getContainer(item.pathname); + files = files.filter(file => !u.isLink(file,{item:{pathHandler:item.pathHandler}})) + if (files.length) item.containerNotEmpty = true; + } + + return item; +} + diff --git a/src/request.js b/src/request.js new file mode 100644 index 0000000..e3314df --- /dev/null +++ b/src/request.js @@ -0,0 +1,44 @@ +const URL = require("url").URL; + +export function getRequest(uri,options){ + const request = normalizeRequestKeys(options) + request.headers = normalizeRequestKeys(request.headers) + request.method = normalizeRequestMethod(request.method) + request.slug = request.headers.slug || request.slug || ""; + request.body = request.body || ""; + if( !validUrl(uri) ){ + request.url = null; + } + else{ + request.url = uri; + const url = new URL(uri) + request.protocol = url.protocol + } + return request; +} + +/* lowercase all request keys e.g. Method -> method +* lowercase all request.header keys e.g. Content-Type -> content-type +*/ +function normalizeRequestKeys(opts){ + let newOpts = {}; + for(var o in opts){ + newOpts[o.toLowerCase()] = opts[o]; + } + return newOpts; +} + +const validUrl = (s) => { + try { + new URL(s); + return true; + } catch (err) { return false; } +}; + +/* uppercase all request methods e.g. get -> GET +* default method = GET +*/ +function normalizeRequestMethod(method){ + return method ? method.toUpperCase() : 'GET'; +} + diff --git a/src/response.js b/src/response.js new file mode 100644 index 0000000..bab9cc8 --- /dev/null +++ b/src/response.js @@ -0,0 +1,83 @@ + /* DEFAULT HEADER + link created using .meta and .acl appended to uri + content-type assigned by mime-types.lookup + date from nodejs Date + */ + +import u from './utils.js'; + +export default function getResponseHeader( + pathname,options,headersFromPlugin,name,item,request +){ + const fn = u.basename(pathname,item.pathHandler) + let headers = headersFromPlugin; + + headers.location = headers.url = headers.location + || request.url.href + + headers.date = headers.date + || new Date(Date.now()).toISOString() + + headers.allow = headers.allow + || createAllowHeader(options.patch,item.mode) + + let wacAllow = headers['wac-allow'] + || createWacHeader(item.mode) + if( wacAllow ) headers['wac-allow'] = wacAllow; + + headers['x-powered-by'] = headers['x-powered-by'] || + name + + options.item = item; + options.request = request; + const ext = u.getExtension(pathname,options) + + headers['content-type'] + = headers['content-type'] + || u.getContentType(ext,item.isContainer==='Container'?"Container":"Resource") + if(!headers['content-type']){ + delete headers['content-type'] + } + if(options.patch) { + headers['ms-author-via']=["SPARQL"]; + headers['accept-patch']=['application/sparql-update']; + } + headers.link = headers.link; + if( !headers.link ) { + if( ext === '.acl' ) { + headers.link = + `; rel="type"` + } + else if( ext === '.meta' ) { + headers.link = + `<${fn}.acl>; rel="acl",` + +`; rel="type"` + } + else if ( item.isContainer ) { + headers.link = + `<.meta>; rel="describedBy", <.acl>; rel="acl",` + +`; rel="type",` + +`; rel="type"` + } + else { + headers.link = + `<${fn}.meta>; rel="describedBy", <${fn}.acl>; rel="acl",` + +`; rel="type"` + } + } + return headers + } // end of getHeaders() + + function createWacHeader( mode ){ + if(!mode.read && !mode.write) return null; + if(mode.read && !mode.write) return `user="read",public="read"` + if(!mode.read && mode.write) return `user="append write control",public=""` + return `user="read write append control",public="read"` + } + + function createAllowHeader( patch, mode ){ + return 'OPTIONS,HEAD' + + (mode.read ?',GET' : '') + + (mode.write ?',POST,PUT,DELETE' : '') + + (mode.write && patch ?',PATCH' : '') + } diff --git a/src/rest.js b/src/rest.js index 5cac922..533e1f3 100644 --- a/src/rest.js +++ b/src/rest.js @@ -1,237 +1,91 @@ "use strict"; -const Url = require('url') -const libPath = require("path"); const { Response } = require('cross-fetch') -const crossFetch = require('cross-fetch') -const { v1: uuidv1 } = require('uuid') -const contentTypeLookup = require('mime-types').contentType + const RestPatch = require('./rest-patch') -const pod = require('./createServerlessPod.js') +import u from './utils.js'; +import actions from './actions.js'; +import getResponseHeader from './response.js'; +import {checkRestErrors} from './error.js'; +import {getRequest} from './request.js'; +import {getItem} from './item.js'; -const linkExt = ['.acl', '.meta'] -const linksExt = linkExt.concat('.meta.acl') -let patch; +let patch,pathname,pathSep,request,item; class SolidRest { constructor( options ) { - this.version = "1.2.9"; - let handlers; - if(typeof options === "object"){ - if( Object.keys(options)[0] === "0" ) { - handlers = options // ARRAY - options = {} - } - else { - handlers = options.handlers || null - } - } - else { - options = {} + options = options || {} + if(!options.plugin) { + console.log(`You must specify a plugin storage handler!`); + process.exit(1); } + this.storage = options.plugin; let $rdf = (options.parser) ? options.parser : (typeof window !="undefined" && window.$rdf) ? window.$rdf : (typeof global !="undefined" && global.$rdf) ? global.$rdf : null; - patch = ($rdf) ? new RestPatch($rdf) : null; - this.storageHandlers = {} - if( !handlers ) { - if( typeof window ==="undefined") { - let File = require('./file.js'); - let Mem = require('./localStorage.js'); - handlers = [ new File(), new Mem() ] - } - else { - try { - let Bfs = require('./browserFS.js'); - handlers = [ new Bfs() ] - } - catch{(e)=>{alert(e)}} - } - } - handlers.forEach( handler => { -// console.log(` -// Installing Rest Handler ${handler.name} using prefix ${handler.prefix} -// `) - this.storageHandlers[handler.prefix] = handler - }) - // return this.addFetch(auth,sessionId) -} - -/* auth can be solid-auth-cli or solid-client-authn, or (default) cross-fetch - rest attaches itself to auth's fetch such that htpp* requests are - handled by the auth's fetch and others are handled by rest -*/ -addFetch( auth,sessionId ) { - let self = this - auth = auth || crossFetch - if(typeof auth.Session === 'function'){ - auth = new auth.Session( - { - clientAuthentication : - auth.getClientAuthenticationWithDependencies({}) - }, - sessionId - ); - } - let originalFetch = auth.fetch - auth.fetch = (uri,options) => { - if(uri.startsWith('http') ){ - return originalFetch(uri,options) - } - else { - return self.fetch(uri,options) - } - } - return auth + patch = options.patch = ($rdf) ? new RestPatch($rdf) : null; } - async createServerlessPod( base ){ - console.log(`Creating pod at <${base}>`); - base = base.replace(/\/$/,''); - await this.makeResource( base,"/.acl", pod.acl_content ); - await this.makeResource( base,"/profile/card", pod.profile_content ); - await this.makeResource( base,"/settings/prefs.ttl", pod.prefs_content ); - await this.makeResource(base,"/settings/privateTypeIndex.ttl",pod.private_content ); - await this.makeResource( base,"/settings/publicTypeIndex.ttl", pod.public_content ); - await this.makeResource( base,"/private/.meta", "" ); - await this.makeResource( base,"/.well-known/.meta", "" ); - await this.makeResource( base,"/public/.meta", "" ); - await this.makeResource( base,"/inbox/.meta", "" ); - } - async makeResource( base, path, content ){ - let url = base + path - console.log ( " creating " + path ) - await this.fetch( url, { - method:"PUT", - body:content, - headers:{"content-type":"text/turtle"} - }) - } - - -storage(options){ - const prefix = (typeof options==="string") ? options : options.rest_prefix - if(!this.storageHandlers[prefix]) throw "Did not recognize prefix "+prefix - return this.storageHandlers[prefix] +async createServerlessPod ( base ){ + return u.createServerlessPod( base ); } async itemExists(pathname,options){ - return (await this.storage(options).getObjectType(pathname, options))[1] + return (await this.storage.getObjectType(pathname, options),request)[1] } - async fetch(uri, options = {}) { let self = this - options = _normalizeOptions(options) - options.headers = _normalizeOptions(options.headers) - const url = new URL(uri) - options.scheme = url.protocol - let pathname, path - /* mungedPath = USE default path() for file and posix.path for others) - */ - if (options.scheme.startsWith('file')) { - options.url = Url.format(url) - pathname = Url.fileURLToPath(options.url) - options.rest_prefix = 'file' - path = libPath - } - else { - options.url = decodeURIComponent(uri) - pathname = Url.parse(options.url).pathname - options.rest_prefix=uri.replace(options.scheme+'//','').replace(/\/.*$/,'') - path = libPath.posix - } - options.mungedPath = path || libPath - /**/ - - if(!self.storage){ - if(self.storageHandlers) { - self.storage=()=>{return self.storageHandlers[prefix]} - } - else { - self.storage=()=>{return self.storageHandlers[options.rest_prefix]} - } - } - - const [objectType,objectExists,mode] = - await self.storage(options).getObjectType(pathname,options) + request = options = getRequest(uri,options); + item = await getItem(uri,request,this.storage); + + options.request = request; + options.item = item; + if (item.isContainer && !uri.endsWith('/')) options.url = `${options.url}/` + pathname = item.pathname + pathSep = u.pathSep( item.pathHandler ); + options.url = request.url; + options.rest_prefix = item.rest_prefix; +const objectType = item.isContainer ? "Container" : "Resource"; +const objectExists = item.exists; +const mode = item.mode; options.objectType = objectType options.objectExists = objectExists options.objectMode = mode ? mode : {read:true,write:true}; - const notFoundMessage = '404 Not Found' - if (objectType === "Container" && !options.url.endsWith('/')) options.url = `${options.url}/` - const resOptions = Object.assign({}, options) - resOptions.headers = {} + const resOptions = {headers:{}}; + let restError = checkRestErrors(options,request,item); + if( restError ) return _response( null, {}, restError ); - /* GET - */ if (options.method === 'GET') { - if(!objectExists) return _response("", resOptions, 404) - if(!options.objectMode.read) return _response("", resOptions, 401) - if( objectType==="Container"){ - let contents = await self.storage(options).getContainer(pathname,options) - const [status, turtleContents, headers] = await _container2turtle(pathname,options,contents) - Object.assign(resOptions.headers, headers) - - return _response(turtleContents, resOptions, status) - } - else if( objectType==="Resource" ){ - const [status, contents, headers] = await self.storage(options).getResource(pathname,options) - Object.assign(resOptions.headers, headers) - - return _response(contents, resOptions, status) - } - } - /* HEAD & OPTIONS // TBD : Should these be the same? - */ - if (options.method === 'HEAD' || options.method === 'OPTIONS' ) { - if(!objectExists) return _response(null, resOptions, 404) - else return _response(null, resOptions, 200) + return makeResponse( resOptions, + await actions.GET(pathname,options,this.storage) + ); } - if( options.method === 'DELETE' - || options.method === 'PUT' - || options.method === 'POST' - || options.method === 'PATCH' - ){ - if(objectExists && !options.objectMode.write) - return _response("", resOptions, 401) + if (options.method === 'HEAD' || options.method === 'OPTIONS' ) { + return _response(null, resOptions, 200) } - /* DELETE - */ if( options.method==="DELETE" ){ - if(!objectExists) return _response(notFoundMessage, resOptions, 404) - if( objectType==="Container" ){ - const [status, , headers] = await _deleteContainer(pathname,options) - Object.assign(resOptions.headers, headers) - - return _response(null, resOptions, status) - } - else if (objectType === 'Resource' ) { - const [status, , headers] = await _deleteResource(pathname,options) - Object.assign(resOptions.headers, headers) - - return _response(null, resOptions, status) - } - else { - } + return makeResponse( resOptions, + await actions.DELETE(pathname,options,this.storage) + ); } + /* POST */ if( options.method==="POST"){ - if( !objectExists ) return _response(notFoundMessage, resOptions, 404) - let link = options.headers.Link || options.headers.link + let link = options.headers.link let slug = options.headers.Slug || options.headers.slug || options.slug if(slug.match(/\//)) return _response(null, resOptions, 400) if( link && link.match("Container") ) { options.resourceType="Container" - slug = await _getAvailableUrl(pathname, slug, options) // jz add - pathname = _mungePath(pathname, slug, options) - const [status, , headers] = await self.storage(options).postContainer(pathname,options) + slug = await u.getAvailableUrl(pathname, slug, options,this.storage) // jz add + pathname = u.mungePath(pathname, slug, options) + const [status, , headers] = await self.storage.postContainer(pathname,options) // Object.assign(resOptions.headers, { location: mapPathToUrl(pathname, options) + '/' }) Object.assign(resOptions.headers, { location: pathname + '/' }) Object.assign(resOptions.headers, headers) @@ -239,11 +93,10 @@ async fetch(uri, options = {}) { } else if( link && link.match("Resource")){ options.resourceType="Resource" - slug = await _getAvailableUrl(pathname, slug, options) - pathname = _mungePath(pathname, slug, options) - if (isLink(pathname, options)) return _response(null, resOptions, 405) - const [status, , headers] = await self.storage(options).putResource( pathname, options) -// Object.assign(resOptions.headers, { location: mapPathToUrl(pathname, options) }) + slug = await u.getAvailableUrl(pathname, slug, options,this.storage) + pathname = u.mungePath(pathname, slug, options) + if (u.isLink(pathname, options)) return _response(null, resOptions, 405) + const [status, , headers] = await self.storage.putResource( pathname, options) Object.assign(resOptions.headers, { location: pathname }) Object.assign(resOptions.headers, headers) return _response(null, resOptions, status) @@ -253,12 +106,11 @@ async fetch(uri, options = {}) { /* PUT */ if (options.method === 'PUT' ) { - if(objectType==="Container") return _response(null, resOptions, 409) - const [status, undefined, headers] = await self.storage(options).makeContainers(pathname,options) + const [status, undefined, headers] = await self.storage.makeContainers(pathname,options) Object.assign(resOptions.headers, headers) if(status !== 200 && status !== 201) return _response(null, resOptions, status) - const [putStatus, , putHeaders] = await self.storage(options).putResource(pathname, options) + const [putStatus, , putHeaders] = await self.storage.putResource(pathname, options) Object.assign(resOptions.headers, putHeaders) // Note: The headers from makeContainers are also returned here @@ -273,14 +125,14 @@ async fetch(uri, options = {}) { return _response( null, resOptions, 405); } - // check pathname and 'text/turtle'. TODO see if NSS allows other RDF - if(objectType==="Container") return _response(null, resOptions, 409) + // check pathname and 'text/turtle'. TODO see if NSS allows other RD + let content = '' if (objectExists) { - const [status, contents, headers] = await self.storage(options).getResource(pathname,options) + const [status, contents, headers] = await self.storage.getResource(pathname,options) content = typeof contents === 'string' ? contents : contents.toString() } - const contentType = _getContentType(_getExtension(pathname, options)) + const contentType = u.getContentType(u.getExtension(pathname, options)) if (contentType !== 'text/turtle') return _response('500 '+ pathname + ' is not a "text/turtle" file', resOptions, 500) // patch content @@ -293,12 +145,12 @@ async fetch(uri, options = {}) { // PUT content to file if (!objectExists) { - const [status, undefined, headers] = await self.storage(options).makeContainers(pathname,options) + const [status, undefined, headers] = await self.storage.makeContainers(pathname,options) // TODO add patchHeaders('MS-Author-Via', 'SPARQL') Object.assign(resOptions.headers, headers) if(status !== 200 && status !== 201) return _response(null, resOptions, status) } - const [putStatus, , putHeaders] = await self.storage(options).putResource(pathname, options) + const [putStatus, , putHeaders] = await self.storage.putResource(pathname, options) //Object.assign(resOptions.headers, putHeaders) // Note: The headers from makeContainers are also returned here @@ -309,237 +161,40 @@ async fetch(uri, options = {}) { return _response(null, resOptions, 405) } - /** - * @param {RequestInfo} body - * @param {RequestInit} options - * @param {Number} status - Overrules options.status - */ - function _response(body, options, status = options.status) { - options.status = status - // if (body) options.statusText = body - options.headers = Object.assign(_getHeaders(pathname, options), options.headers) - return new Response(body, options) - } - - async function _container2turtle( pathname, options, contentsArray ){ - if(typeof self.storage(options).container2turtle != "undefined") - return self.storage(options).container2turtle(pathname,options,contentsArray) - let filenames=contentsArray.filter( item => { - if(!item.endsWith('.acl') && !item.endsWith('.meta')){ return item } - }) - - // cxRes - if ( !pathname.endsWith(options.mungedPath.sep) ) pathname += options.mungedPath.sep - // if (!pathname.endsWith("/")) pathname += "/" - - let str2 = "" - let str = "@prefix : <#>. @prefix ldp: .\n" - + "<> a ldp:BasicContainer, ldp:Container" - if(filenames.length){ - str = str + "; ldp:contains\n"; - for(var i=0;i,\n` - - let ctype = _getContentType(_getExtension(fn,options),'Resource') - ctype = ctype.replace(/;.*/,'') - ftype = ftype==="Container" ? "ldp:Container; a ldp:BasicContainer" : "ldp:Resource" - str2 = str2 + `<${fn}> a ${ftype}.\n` - str2 = str2 + `<${fn}> a .\n` - // str2 = str2 + `<${fn}> :type "${ctype}".\n` - } - str = str.replace(/,\n$/,"") - } - str = str + `.\n` + str2 - // str = _makeStream(str); - return ([200,str]) + function makeResponse(resOptions,response){ + // combine the standard headers with ones returned from the action if any + // respons = [status,body,headers] + Object.assign(resOptions.headers, response[2]) + return _response( response[1], resOptions, response[0] ); } - /* treats filename ".acl" and ".meta" as extensions - */ - function _getExtension(pathname,options) { - let ext = ( options.mungedPath.basename(pathname).startsWith('.') ) - ? options.mungedPath.basename(pathname) - : options.mungedPath.extname(pathname) - return ext - } - function _getContentType(ext,type) { - if( !ext - || ext==='.ttl' - || ext==='.acl' - || ext==='.meta' - || type==="Container" - ) { - return 'text/turtle' - } - else { - let ctype = contentTypeLookup(ext) - return( ctype ? ctype : 'text/turtle' ) + /** + * @param {RequestInfo} body + * @param {RequestInit} options + * @param {Number} status - Overrules options.status + */ + function _response(body, options, status = options.status) { + options.status = status; + let headersFromPlugin = + typeof self.storage.getHeaders != "undefined" + ? self.storage.getHeaders(pathname,options,item,request) + : {} + let name = self.storage.name + options.headers = Object.assign( + getResponseHeader( + pathname,options,headersFromPlugin,name,item,request + ), + options.headers + ) + return new Response(body, options) } - } - function isLink(pathname,options) { - return linkExt.find(ext => _getExtension(pathname,options) === ext) - } - - /* DEFAULT HEADER - link created using .meta and .acl appended to uri - content-type assigned by mime-types.lookup - date from nodejs Date - */ - function _getHeaders(pathname,options){ - - const fn = options.mungedPath.basename(pathname) - let headers = (typeof self.storage(options).getHeaders != "undefined") - ? self.storage(options).getHeaders(pathname,options) - : {} - - headers.location = headers.url = headers.location - || options.url - - headers.date = headers.date - || new Date(Date.now()).toISOString() - headers.allow = headers.allow - || _createAllowHeader(patch,options.objectMode) - let wacAllow = headers['wac-allow'] - || _createWacHeader(options.objectMode) - if( wacAllow ) headers['wac-allow'] = wacAllow; - - headers['x-powered-by'] = headers['x-powered-by'] || - self.storage(options).name - - const ext = _getExtension(pathname,options) - - headers['content-type'] - = headers['content-type'] - || _getContentType(ext,options.objectType) - if(!headers['content-type']){ - delete headers['content-type'] - } - if(patch) { - headers['ms-author-via']=["SPARQL"]; - headers['accept-patch']=['application/sparql-update']; - } - headers.link = headers.link; - if( !headers.link ) { - if( ext === '.acl' ) { - headers.link = - `; rel="type"` - } - else if( ext === '.meta' ) { - headers.link = - `<${fn}.acl>; rel="acl",` - +`; rel="type"` - } - else if (options.objectType==='Container') { - headers.link = - `<.meta>; rel="describedBy", <.acl>; rel="acl",` - +`; rel="type",` - +`; rel="type"` - } - else { - headers.link = - `<${fn}.meta>; rel="describedBy", <${fn}.acl>; rel="acl",` - +`; rel="type"` - } - } - return headers - } // end of getHeaders() - function _createWacHeader( mode ){ - if(!mode.read && !mode.write) return null; - if(mode.read && !mode.write) return `user="read",public="read"` - if(!mode.read && mode.write) return `user="append write control",public=""` - return `user="read write append control",public="read"` - } - function _createAllowHeader( patch, mode ){ - return 'OPTIONS,HEAD' - + (mode.read ?',GET' : '') - + (mode.write ?',POST,PUT,DELETE' : '') - + (mode.write && patch ?',PATCH' : '') - } - -async function _deleteContainer(pathname,options){ - let files = await self.storage(options).getContainer(pathname, options) - files = files.filter(file => !isLink(file,options)) // linkExt.find(ext => _getExtension(file,options) === ext)) - if (files.length) return [409] - const links = await getLinks(pathname, options) - if (links.length) links.map(async link => await self.storage(options).deleteResource(link,options)) - return await self.storage(options).deleteContainer(pathname,options) -} - -/* - _deleteResource(pathname,options) - * deletes a resource with links -*/ -async function _deleteResource(pathname,options){ - const links = await getLinks(pathname, options) - if (links.length) links.map(async link => await self.storage(options).deleteResource(link,options)) - return await self.storage(options).deleteResource(pathname,options) -} - -/** - * getLinks for item - * @param {*} pathname - * @param {*} options - */ -async function getLinks (pathname, options) { - let linksExists = linksExt.filter(async ext => await self.storage(options).getObjectType(pathname + ext)[1]) - const links = linksExists.map( ext => pathname + ext) - return links -} - -async function _getAvailableUrl (pathname, slug = uuidv1(), options) { - let requestUrl = _mungePath(pathname, slug, options) - if(options.resourceType==='Container' && !requestUrl.endsWith(options.mungedPath.sep)) requestUrl = requestUrl + options.mungedPath.sep - let urlExists = (await self.storage(options).getObjectType(requestUrl, options))[1] - if (urlExists) { slug = `${uuidv1()}-${slug}` } - return slug -} - -function _mungePath(pathname, slug, options) { - pathname = options.mungedPath.join(pathname, slug); - if (pathname.includes('\\')) pathname = pathname.replace(/\\/g, '/'); - return pathname; -} - -/** Normalize content-type/Content-type and method/Method - */ -function _normalizeOptions(opts){ - let newOpts = {}; - for(var o in opts){ - newOpts[o.toLowerCase()] = opts[o]; - } - newOpts.method = newOpts.method ? newOpts.method.toUpperCase() : 'GET'; - return newOpts; -} - - } // end of fetch() + } // end of fetch() } // end of SolidRest() module.exports = exports = SolidRest module.exports.SolidRest = SolidRest -/* END */ - - -/* -required - getObjectType - getResouce - getContainer - putResource - postResource - postContainer - deleteResource - deleteContainer - makeContainers -optional - getHeaders - text - json -*/ +// THE END diff --git a/src/utils.js b/src/utils.js new file mode 100644 index 0000000..174fd1a --- /dev/null +++ b/src/utils.js @@ -0,0 +1,130 @@ +import libPath from "path"; +import {contentType as contentTypeLookup} from 'mime-types' +const { v1: uuidv1 } = require('uuid') +import pod from './createServerlessPod.js'; + +const linkExt = ['.acl', '.meta'] +const linksExt = linkExt.concat('.meta.acl') + + async function createServerlessPod( base ){ + console.log(`Creating pod at <${base}>`); + base = base.replace(/\/$/,''); + await _makeResource( base,"/.acl", pod.acl_content ); + await _makeResource( base,"/profile/card", pod.profile_content ); + await _makeResource( base,"/settings/prefs.ttl", pod.prefs_content ); + await _makeResource(base,"/settings/privateTypeIndex.ttl",pod.private_content ); + await _.makeResource( base,"/settings/publicTypeIndex.ttl", pod.public_content ); + await _.makeResource( base,"/private/.meta", "" ); + await _.makeResource( base,"/.well-known/.meta", "" ); + await _.makeResource( base,"/public/.meta", "" ); + await _.makeResource( base,"/inbox/.meta", "" ); + } + async function _makeResource( base, path, content ){ + let url = base + path + console.log ( " creating " + path ) + await this.fetch( url, { + method:"PUT", + body:content, + headers:{"content-type":"text/turtle"} + }) + } + +function pathSep(type){ + if(type==='posix') return libPath.posix.sep + else return libPath.sep +} +function basename(path,type){ + if(type==='posix') return libPath.posix.basename(path); + else return libPath.basename(path); +} + +function mungePath(pathname, slug, options) { + pathname = options.item.pathHandler==='posix' + ? libPath.posix.join(pathname, slug) + : libPath.join(pathname, slug); + if (pathname.includes('\\')) pathname = pathname.replace(/\\/g, '/'); + return pathname; +} + + /* treats filename ".acl" and ".meta" as extensions + */ + function getExtension(pathname,options) { + let ext = ( basename(pathname,options.item.pathHandler).startsWith('.') ) + ? basename(pathname,options.item.pathHandler) + : options.item.pathHandler==='posix' + ? libPath.posix.extname(pathname) + : libPath.extname(pathname) + return ext + } + + function getContentType(ext,type) { + if( !ext + || ext==='.ttl' + || ext==='.acl' + || ext==='.meta' + || type==="Container" + ) { + return 'text/turtle' + } + else { + let ctype = contentTypeLookup(ext) + return( ctype ? ctype : 'text/turtle' ) + } + } + + function isAuxResource(o) { + return linkExt.find(ext => + getExtension( o.item.pathname,o ) === ext + ) + } + async function getAuxResources (pathname, options,storage) { + let linksExists = linksExt.filter(async ext => + await storage.getObjectType(pathname + ext,options.request)[1] + ) + const links = linksExists.map( ext => pathname + ext) + return links || []; + } + +// TBD : remove getLinks and isLink, replace in code with isAuxResource, etc. + + function isLink(pathname,options) { + return linkExt.find(ext => getExtension(pathname,options) === ext) + } + +/** + * getLinks for item + * @param {*} pathname + * @param {*} options + */ +async function getLinks (pathname, options,storage) { + let linksExists = linksExt.filter(async ext => + await storage.getObjectType(pathname + ext,options.request)[1] + ) + const links = linksExists.map( ext => pathname + ext) + return links +} + + +/* getAvailableUrl - generate random prefix for POST file names +*/ +async function getAvailableUrl (pathname, slug = uuidv1(), options,storage) { + let requestUrl = mungePath(pathname, slug, options) + if(options.resourceType==='Container' && !requestUrl.endsWith(pathSep(options.item.pathHandler))) requestUrl = requestUrl + pathSep(options.item.pathHandler) + let urlExists = (await storage.getObjectType(requestUrl, options,options.request))[1] + if (urlExists) { slug = `${uuidv1()}-${slug}` } + return slug +} + +export default { + createServerlessPod, + mungePath, + getExtension, + getContentType, + isAuxResource, isLink, + getAuxResources, getLinks, + getAvailableUrl, + linkExt, + linksExt, + pathSep, + basename, +} diff --git a/tests/all.js b/tests/all.js index e2bfb81..382835e 100644 --- a/tests/all.js +++ b/tests/all.js @@ -5,33 +5,46 @@ // //const SolidNodeClient = require('../').SolidNodeClient //const client = new SolidNodeClient() -const SolidRest = require('../') - // global.$rdf = require('rdflib') // const client = new SolidRest() const $rdf = require('rdflib'); -const client = new SolidRest({ parser:$rdf }) + +const SolidRest = require('../') +const SolidRestFile = require('../plugins/solid-rest-file'); +const SolidRestMem = require('../plugins/solid-rest-mem'); + +function getRestClient(protocol,parser){ + const plugin = protocol.startsWith('file') ? new SolidRestFile() + : protocol.startsWith('mem') ? new SolidRestMem() + : protocol.startsWith('ssh') ? new SolidRestSsh() : null; + return new SolidRest({ + plugin : plugin, + parser : parser, + }); +} +let client; /** Silence rdflib chatty information about patch * Send console.log() to a logfile * Send console.error(), console.warn() and untrapped errors to screen */ +/* const fs = require('fs'); const logfile = `${process.cwd()}/log.txt`; console.log = function(msg) { fs.appendFileSync(logfile,msg.toString()) } process.on('uncaughtException', function(err) { console.error((err && err.stack) ? err.stack : err); }); - +*/ const libUrl = require('url') let [tests,fails,passes,res] = [0,0,0] let allfails = 0 async function main(){ - await run("app:") await run("file:") +// await run("mem:") // await run("https:") if(allfails>0){ process.exit(1) @@ -43,9 +56,10 @@ async function main(){ main() async function getConfig(scheme){ + client = getRestClient(scheme,$rdf); let host = scheme; - if(scheme==="app:"){ - scheme = "app://ls" // = protocol + if(scheme==="mem:"){ + scheme = "mem://" // = protocol host = scheme; } @@ -203,8 +217,8 @@ async function run(scheme){ let res let res1 - if(scheme==="app:") cfg.base += "/" - try {res=await PUT(cfg.dummy)}catch{} + if(scheme==="mem:") cfg.base += "/" + try {res=await PUT(cfg.dummy)}catch(e){console.log(e)} console.warn(`\nTesting ${cfg.base} ...`) @@ -247,7 +261,7 @@ async function run(scheme){ /** PUT */ res = await PUT( cfg.folder1 ) - ok( "409 put container (method not allowed)", res.status==409,res) + ok( "405 put container (method not allowed)", res.status==405,res) res = await PUT( cfg.file1,cfg.text ) ok( "201 put resource", res.status==201,res) From ce560b27965498bccf58a219d78a4d1e5ab304bd Mon Sep 17 00:00:00 2001 From: jeff-zucker Date: Sun, 13 Dec 2020 21:44:00 -0800 Subject: [PATCH 02/11] second refactor --- package.json | 2 +- plugins/solid-rest-file/src/index.js | 50 +++++----- src/actions.js | 29 ------ src/error.js | 30 ------ src/{request.js => examineRequest.js} | 0 src/{item.js => examineRequestedItem.js} | 24 +++-- src/handleRequest.js | 52 ++++++++++ src/{response.js => handleResponse.js} | 42 ++++---- src/{rest.js => index.js} | 121 ++++++++++++++--------- src/performRequestedMethod.js | 68 +++++++++++++ src/{ => utils}/container.js | 14 +-- src/{ => utils}/createServerlessPod.js | 0 src/{ => utils}/rest-patch.js | 0 src/{ => utils}/utils.js | 36 +------ test.txt | 1 + tests/jz.js | 88 +++++++++++++++++ 16 files changed, 356 insertions(+), 201 deletions(-) delete mode 100644 src/actions.js delete mode 100644 src/error.js rename src/{request.js => examineRequest.js} (100%) rename src/{item.js => examineRequestedItem.js} (51%) create mode 100644 src/handleRequest.js rename src/{response.js => handleResponse.js} (69%) rename src/{rest.js => index.js} (71%) create mode 100644 src/performRequestedMethod.js rename src/{ => utils}/container.js (71%) rename src/{ => utils}/createServerlessPod.js (100%) rename src/{ => utils}/rest-patch.js (100%) rename src/{ => utils}/utils.js (75%) create mode 100644 test.txt create mode 100644 tests/jz.js diff --git a/package.json b/package.json index 9e571bd..c581078 100644 --- a/package.json +++ b/package.json @@ -4,7 +4,7 @@ "author": "Jeff Zucker", "license": "MIT", "description": "treat any storage as a mini Solid server", - "main": "./src/rest.js", + "main": "./src/index.js", "browser": "./dist/browser/solid-rest.js", "scripts": { "test": "node tests/all", diff --git a/plugins/solid-rest-file/src/index.js b/plugins/solid-rest-file/src/index.js index a3d1f76..a26584e 100644 --- a/plugins/solid-rest-file/src/index.js +++ b/plugins/solid-rest-file/src/index.js @@ -88,52 +88,51 @@ async putResource(pathname,options){ }) } */ -async putResource(pathname,options){ +async putResource(pathname,request,item){ let successCode = 201; - let failureCode = - ( options.method==="PUT" && options.objectType==="Container" ) - ? 409 : 500 + let failureCode = 500; return new Promise(async (resolve) => { let writeIt=false - if(failureCode===409) return resolve( [failureCode] ) - if(typeof options.body==="undefined") options.body = "" - if(typeof options.body==="string"){ + if(typeof request.body==="undefined") request.body = "" + if(typeof request.body==="string"){ writeIt=true } - else if(options.body.stream){ - options.body = await options.body.stream() - options.body = await options.body.read() + else if(request.body.stream){ + request.body = await request.body.stream() + request.body = await request.body.read() writeIt=true } - else if(options.body.text){ - options.body = await options.body.text() + else if(request.body.text){ + request.body = await request.body.text() writeIt=true } if(writeIt){ try { - await fs.writeFileSync(pathname,options.body) + await fs.writeFileSync(pathname,request.body) return resolve([successCode]) } catch(e){ console.log(e); return resolve([failureCode])} } - if(!options.body.pipe && typeof FileReader !="undefined"){ + if(!request.body.pipe && typeof FileReader !="undefined"){ var fileReader = new FileReader(); fileReader.onload = function() { fs.writeFileSync(pathname, Buffer.from( new Uint8Array(this.result)) ) } - fileReader.onloadend = () => {return resolve([successCode])} + fileReader.onloadend = () => { + return resolve([successCode]) + } fileReader.onerror = (err) => { console.log(err); return resolve([failureCode]) } - fileReader.readAsArrayBuffer(options.body); + fileReader.readAsArrayBuffer(request.body); } else { - options.body = options.body || "" - options.body = this._makeStream( options.body ); - options.body.pipe(fs.createWriteStream(pathname)).on('finish',()=>{ + request.body = request.body || "" + request.body = this._makeStream( request.body ); + request.body.pipe(fs.createWriteStream(pathname)).on('finish',()=>{ return resolve( [successCode] ) }).on('error', (err) => { console.log(err) @@ -178,21 +177,20 @@ postContainer(fn,options){ }); }); } -async makeContainers(pathname, options){ +async makeContainers(pathname){ const foldername = path.dirname(pathname) - const [type, exists] = await this.getObjectType(foldername,options.request); - if (!exists) { + if (!fs.existsSync(foldername)) { try { fs.mkdirpSync(foldername); - return Promise.resolve([201]) + return Promise.resolve(true) } catch { - return Promise.resolve([500]) + return Promise.resolve(false) } } - return Promise.resolve([200]) + return Promise.resolve(true) } -async getContainer(pathname,options) { +async getContainer(pathname) { return await fs.readdirSync(pathname) } diff --git a/src/actions.js b/src/actions.js deleted file mode 100644 index c4ad3e4..0000000 --- a/src/actions.js +++ /dev/null @@ -1,29 +0,0 @@ -import u from './utils.js'; -import {containerAsturtle} from './container.js'; - -async function GET(pathname,options,storage){ - if( options.item.isContainer ){ - let files = await storage.getContainer(pathname,options) - return await containerAsturtle(pathname,options,files,storage) - } - else { - return await storage.getResource(pathname,options) - } -} - -async function DELETE(pathname,options,storage){ - const links = await u.getLinks(pathname, options,storage); - if (links.length) - links.map( async (link) => { - await storage.deleteResource(link,options) - }) - if (options.item.isContainer) - return await storage.deleteContainer(pathname,options) - else - return await storage.deleteResource(pathname,options) -} - -export default { - DELETE, - GET, -} diff --git a/src/error.js b/src/error.js deleted file mode 100644 index 07f2ba3..0000000 --- a/src/error.js +++ /dev/null @@ -1,30 +0,0 @@ -import u from './utils.js'; - -export function checkRestErrors( options, request, item ){ - if( !request.url) return(400); - if( request.slug.endsWith('/') ) return(400); - if( request.method==='DELETE' && item.containerNotEmpty ) return(409); - if( u.isAuxResource(options) && request.method==="POST") return(405); - const methods = { - DELETE : { mustPrexist:1, requiresWrite:1 }, - POST : { mustPrexist:1, requiresAppend:1, requiresContentType:1 }, - GET : { mustPrexist:1, requiresRead:1 }, - HEAD : { mustPrexist:1, requiresRead:1 }, - OPTIONS : { mustPrexist:1, requiresRead:1 }, - PUT : { requiresWrite:1, requiresContentType:1 }, - PATCH : { requiresWrite:1, requiresContentType:1 }, - } - const method = methods[request.method]; - if( !method ) return(409); - if( method.mustPrexist && !item.exists ) return(404); - if( (method.requiresRead && !item.mode.read) - || (method.requiresWrite && !item.mode.write ) - || (method.requiresAppend && !item.mode.append ) - ) return (401); - if( method.requiresContentType && !request.headers['content-type'] ) - return (400); - if ( (request.method==='PUT'||request.method==='PATCH') && item.isContainer ) - return(405) -} -// ENDS - diff --git a/src/request.js b/src/examineRequest.js similarity index 100% rename from src/request.js rename to src/examineRequest.js diff --git a/src/item.js b/src/examineRequestedItem.js similarity index 51% rename from src/item.js rename to src/examineRequestedItem.js index 46deb1e..98458c0 100644 --- a/src/item.js +++ b/src/examineRequestedItem.js @@ -1,30 +1,42 @@ +import libPath from "path"; import Url from "url"; -import u from './utils.js'; export async function getItem(uri,request,storage){ const [objectType,objectExists,mode,item] = - await storage.getObjectType(uri,request) + await this.storage.getObjectType(uri,request) item.mode = item.mode ? item.mode : {read:true,append:true,write:true}; let pathHandler,url; if (request.protocol.startsWith('file')) { url = Url.format(request.url) item.rest_prefix = 'file' // item.pathname = Url.fileURLToPath(url) - item.pathHandler = 'default' + pathHandler = libPath; } else { url = decodeURIComponent(uri) // item.pathname = Url.parse(url).pathname item.rest_prefix=uri.replace(request.protocol+'//','').replace(/\/.*$/,'') - item.pathHandler = 'posix' + pathHandler = libPath.posix } + // item.pathname = url.replace(request.protocol+'//','') ??? item.pathname = uri.replace(request.protocol+'//','') if( request.method==='DELETE' && item.isContainer){ let files = await storage.getContainer(item.pathname); - files = files.filter(file => !u.isLink(file,{item:{pathHandler:item.pathHandler}})) + files = files.filter(file => !this.isLink(file,{item:{pathHandler:item.pathHandler}})) if (files.length) item.containerNotEmpty = true; } + this.getExtension = (path)=>{ + path = path || this.item.pathname; + return ( path.startsWith('.') && !( (path.match(/\./g)||[]).length > 1 ) + ?path :pathHandler.extname(path) ) + }; + this.pathSep = pathHandler.sep; + this.basename = pathHandler.extname + this.mungePath = (pathname, slug, options)=>{ + pathname = pathHandler.join(pathname, slug) + if (pathname.includes('\\')) pathname = pathname.replace(/\\/g, '/'); + return pathname; + } return item; } - diff --git a/src/handleRequest.js b/src/handleRequest.js new file mode 100644 index 0000000..2526da9 --- /dev/null +++ b/src/handleRequest.js @@ -0,0 +1,52 @@ +import {getItem} from './examineRequestedItem.js'; +import {getRequest} from './examineRequest.js'; + +const methods = { + DELETE : { mustPrexist:1, requiresWrite:1 }, + POST : { mustPrexist:1, requiresAppend:1, requiresContentType:1 }, + GET : { mustPrexist:1, requiresRead:1 }, + HEAD : { mustPrexist:1, requiresRead:1 }, + OPTIONS : { mustPrexist:1, requiresRead:1 }, + PUT : { requiresWrite:1, requiresContentType:1 }, + PATCH : { requiresWrite:1, requiresContentType:1 }, +} + +export async function handleRequest( uri, originalRequest ){ + const request = this.request = await this.getRequest( uri, originalRequest ); + if( !request.url || !request.method ) return 400; + if( request.slug.endsWith('/') ) return 400; + if( request.originMismatch ) return 403; + if( request.method==='PATCH' && !request.validPatchContent ) return 400; + const item = this.item = await this.getItem( uri, request ); + if( this.isAuxResource() ){ + request.method.requiresControl = true; + if( request.method==="POST" ) return 405; + } + if( request.method==='DELETE' && item.containerNotEmpty ) return 409; + if( request.method==='PATCH' && !item.canBePatched ) return 405; + if( item.mode.control ) item.mode.write=true; + if( item.mode.write ) item.mode.append=true; + const method = methods[request.method]; + if( !method ) return 409; + if( method.mustPrexist && !item.exists ) return 404; + if( (method.requiresRead && !item.mode.read) + || (method.requiresAppend && !item.mode.append ) + || (method.requiresWrite && !item.mode.write ) + || (method.requiresControl && !item.mode.control ) + ) return 401; + if( method.requiresContentType && !request.headers['content-type'] ) + return 400; + if ( request.method==='PUT'||request.method==='PATCH'){ + if( item.isContainer ) return 405; + let okDir = await this.perform('CREATE_INTERMEDIATE_CONTAINERS'); + if( !okDir ) return 500; + } + if( request.method==='DELETE' ){ + let okDel = await this.perform('DELETE_AUX_RESOURCES'); + if( !okDel ) return 500; + } + let successfulRequest = await this.perform(request.method); + return successfulRequest ? successfulRequest : 500; +} +// ENDS + diff --git a/src/response.js b/src/handleResponse.js similarity index 69% rename from src/response.js rename to src/handleResponse.js index bab9cc8..1130dc7 100644 --- a/src/response.js +++ b/src/handleResponse.js @@ -1,25 +1,28 @@ - /* DEFAULT HEADER - link created using .meta and .acl appended to uri - content-type assigned by mime-types.lookup - date from nodejs Date - */ +const { Response } = require('cross-fetch') -import u from './utils.js'; - -export default function getResponseHeader( - pathname,options,headersFromPlugin,name,item,request -){ - const fn = u.basename(pathname,item.pathHandler) - let headers = headersFromPlugin; +export async function handleResponse(response){ + const pathname = this.item.pathname; + const status = response[0]; + const body = response[1]; + let headers = response[2] || {}; + const headersFromPlugin = + typeof this.storage.getHeaders != "undefined" + ? this.storage.getHeaders(pathname) + : {} + let name = this.storage.name + const item = this.item; + const request = this.request; + const fn = this.basename(pathname,item.pathHandler) + Object.assign(headers,headersFromPlugin); headers.location = headers.url = headers.location - || request.url.href + || request.url headers.date = headers.date || new Date(Date.now()).toISOString() headers.allow = headers.allow - || createAllowHeader(options.patch,item.mode) + || createAllowHeader(this.canPatch,this.item.mode) let wacAllow = headers['wac-allow'] || createWacHeader(item.mode) @@ -27,18 +30,18 @@ export default function getResponseHeader( headers['x-powered-by'] = headers['x-powered-by'] || name - + const options = {}; options.item = item; options.request = request; - const ext = u.getExtension(pathname,options) + const ext = this.getExtension(pathname) headers['content-type'] = headers['content-type'] - || u.getContentType(ext,item.isContainer==='Container'?"Container":"Resource") + || this.getContentType(ext,item.isContainer==='Container'?"Container":"Resource") if(!headers['content-type']){ delete headers['content-type'] } - if(options.patch) { + if(this.canPatch) { headers['ms-author-via']=["SPARQL"]; headers['accept-patch']=['application/sparql-update']; } @@ -65,7 +68,8 @@ export default function getResponseHeader( +`; rel="type"` } } - return headers + headers.status = status; + return new Response(body, headers) } // end of getHeaders() function createWacHeader( mode ){ diff --git a/src/rest.js b/src/index.js similarity index 71% rename from src/rest.js rename to src/index.js index 533e1f3..a249236 100644 --- a/src/rest.js +++ b/src/index.js @@ -1,17 +1,27 @@ "use strict"; -const { Response } = require('cross-fetch') -const RestPatch = require('./rest-patch') -import u from './utils.js'; -import actions from './actions.js'; -import getResponseHeader from './response.js'; -import {checkRestErrors} from './error.js'; -import {getRequest} from './request.js'; -import {getItem} from './item.js'; +import {getRequest} from './examineRequest.js'; +import {getItem} from './examineRequestedItem.js'; +import {handleRequest} from './handleRequest.js'; +import perform from './performRequestedMethod.js'; +import {handleResponse} from './handleResponse.js'; + +import { + createServerlessPod, + getContentType, + isAuxResource, isLink, + getAuxResources, getLinks, + getAvailableUrl, + linkExt, + linksExt, +} from './utils/utils.js'; +import containerAsTurtle from './utils/container.js'; +const RestPatch = require('./utils/rest-patch') + let patch,pathname,pathSep,request,item; -class SolidRest { +export default class SolidRest { constructor( options ) { options = options || {} @@ -20,11 +30,29 @@ constructor( options ) { process.exit(1); } this.storage = options.plugin; + this.handleRequest = handleRequest.bind(this); + this.handleResponse = handleResponse.bind(this); + this.getItem = getItem.bind(this); + this.getRequest = getRequest.bind(this); + this.perform = perform.bind(this); + this.isAuxResource = isAuxResource.bind(this); + this.getAuxResources = getAuxResources.bind(this); + this.getContentType = getContentType.bind(this); + this.getAvailableUrl = getAvailableUrl.bind(this); + this.containerAsTurtle = containerAsTurtle.bind(this); +/* + createServerlessPod, + isLink, + getLinks, + linkExt, + linksExt, +*/ let $rdf = (options.parser) ? options.parser : (typeof window !="undefined" && window.$rdf) ? window.$rdf : (typeof global !="undefined" && global.$rdf) ? global.$rdf : null; patch = options.patch = ($rdf) ? new RestPatch($rdf) : null; + this.os = { canPatch : patch ? true :false }; } async createServerlessPod ( base ){ @@ -36,38 +64,9 @@ async itemExists(pathname,options){ } async fetch(uri, options = {}) { - let self = this - request = options = getRequest(uri,options); - item = await getItem(uri,request,this.storage); - - options.request = request; - options.item = item; - if (item.isContainer && !uri.endsWith('/')) options.url = `${options.url}/` - pathname = item.pathname - pathSep = u.pathSep( item.pathHandler ); - options.url = request.url; - options.rest_prefix = item.rest_prefix; -const objectType = item.isContainer ? "Container" : "Resource"; -const objectExists = item.exists; -const mode = item.mode; - options.objectType = objectType - options.objectExists = objectExists - options.objectMode = mode ? mode : {read:true,write:true}; - - const resOptions = {headers:{}}; - - let restError = checkRestErrors(options,request,item); - if( restError ) return _response( null, {}, restError ); - - if (options.method === 'GET') { - return makeResponse( resOptions, - await actions.GET(pathname,options,this.storage) - ); - } - - if (options.method === 'HEAD' || options.method === 'OPTIONS' ) { - return _response(null, resOptions, 200) - } + let request = await this.handleRequest(uri,options); + return await this.handleResponse(request); +/* if( options.method==="DELETE" ){ return makeResponse( resOptions, @@ -75,8 +74,8 @@ const mode = item.mode; ); } - /* POST - */ + // POST + if( options.method==="POST"){ let link = options.headers.link let slug = options.headers.Slug || options.headers.slug || options.slug @@ -103,8 +102,8 @@ const mode = item.mode; } } - /* PUT - */ + // PUT + if (options.method === 'PUT' ) { const [status, undefined, headers] = await self.storage.makeContainers(pathname,options) Object.assign(resOptions.headers, headers) @@ -116,8 +115,8 @@ const mode = item.mode; return _response(null, resOptions, putStatus) } - /* PATCH - */ + // PATCH + if (options.method === 'PATCH' ) { if(!patch){ @@ -161,6 +160,29 @@ const mode = item.mode; return _response(null, resOptions, 405) } + function handleResponse(response){ + // combine the standard headers with ones returned from the action if any + // respons = [status,body,headers] +// Object.assign(resOptions.headers, response[2]) +// return _response( response[1], resOptions, response[0] ); + let status = response[0]; + let body = response[1]; + let headers = response[2]; + options.status = status; + let headersFromPlugin = + typeof this.storage.getHeaders != "undefined" + ? this.storage.getHeaders(pathname,options,item,request) + : {} + let name = self.storage.name + headers = Object.assign( + getResponseHeader( + pathname,options,headersFromPlugin,name,item,request + ), + options.headers + ) + return new Response(body, options) + } +*/ function makeResponse(resOptions,response){ // combine the standard headers with ones returned from the action if any // respons = [status,body,headers] @@ -194,7 +216,8 @@ const mode = item.mode; } // end of SolidRest() -module.exports = exports = SolidRest -module.exports.SolidRest = SolidRest +// module.exports = exports = SolidRest +// module.exports.SolidRest = SolidRest + // THE END diff --git a/src/performRequestedMethod.js b/src/performRequestedMethod.js new file mode 100644 index 0000000..7479438 --- /dev/null +++ b/src/performRequestedMethod.js @@ -0,0 +1,68 @@ +export default async function perform(method,pathname){ + pathname = pathname || this.item.pathname; + let res; + switch( method || this.request.method ) { + case 'GET': + if( this.item.isContainer ){ + let files = await this.storage.getContainer(pathname) + return await this.containerAsTurtle(pathname,files) + } + else { + return await this.storage.getResource(pathname) + } + break; + case 'PUT': + res = await this.storage.putResource(pathname,this.request,this.item) + return(res) + break; + case 'CREATE_INTERMEDIATE_CONTAINERS': + res = await this.storage.makeContainers(pathname) + return(res) + //return await this.storage.makeContainers(pathname) + break; + default: + + } +} +/* + async GET(pathname,options,storage){ + if( options.item.isContainer ){ + let files = await storage.getContainer(pathname,options) + return await containerAsturtle(pathname,options,files,storage) + } + else { + return await storage.getResource(pathname,options) + } + } + + async DELETE(pathname,options,storage){ + const links = await this.getLinks(pathname, options,storage); + if (links.length) + links.map( async (link) => { + await storage.deleteResource(link,options) + }) + if (options.item.isContainer) + return await storage.deleteContainer(pathname,options) + else + return await storage.deleteResource(pathname,options) + } + + async PUT(pathname,options,storage){ +return(777); + } + async POST(pathname,options,storage){ +return(777); + } + async PATCH(pathname,options,storage){ +return(777); + } + async HEAD(pathname,options,storage){ +return(777); + } + async OPTIONS(pathname,options,storage){ +return(777); + } + +} + +*/ diff --git a/src/container.js b/src/utils/container.js similarity index 71% rename from src/container.js rename to src/utils/container.js index 190ec2d..168c8a0 100644 --- a/src/container.js +++ b/src/utils/container.js @@ -1,9 +1,9 @@ -import u from './utils.js'; -export async function containerAsturtle( pathname, options, contentsArray, storage ){ - const pathSep = u.pathSep( options.item.pathHandler ); - if(typeof storage.container2turtle != "undefined") - return storage.container2turtle(pathname,options,contentsArray) + +export default async function containerAsTurtle( pathname, contentsArray ){ + const pathSep = this.pathSep; + if(typeof this.storage.container2turtle != "undefined") + return this.storage.container2turtle(pathname,contentsArray) let filenames=contentsArray.filter( item => { if(!item.endsWith('.acl') && !item.endsWith('.meta')){ return item } }) @@ -20,11 +20,11 @@ export async function containerAsturtle( pathname, options, contentsArray, stora for(var i=0;i,\n` - let ctype = u.getContentType(u.getExtension(fn,options),'Resource') + let ctype = this.getContentType(this.getExtension(fn),'Resource') ctype = ctype.replace(/;.*/,'') ftype = ftype==="Container" ? "ldp:Container; a ldp:BasicContainer" : "ldp:Resource" str2 = str2 + `<${fn}> a ${ftype}.\n` diff --git a/src/createServerlessPod.js b/src/utils/createServerlessPod.js similarity index 100% rename from src/createServerlessPod.js rename to src/utils/createServerlessPod.js diff --git a/src/rest-patch.js b/src/utils/rest-patch.js similarity index 100% rename from src/rest-patch.js rename to src/utils/rest-patch.js diff --git a/src/utils.js b/src/utils/utils.js similarity index 75% rename from src/utils.js rename to src/utils/utils.js index 174fd1a..dcc0ce5 100644 --- a/src/utils.js +++ b/src/utils/utils.js @@ -29,34 +29,6 @@ const linksExt = linkExt.concat('.meta.acl') }) } -function pathSep(type){ - if(type==='posix') return libPath.posix.sep - else return libPath.sep -} -function basename(path,type){ - if(type==='posix') return libPath.posix.basename(path); - else return libPath.basename(path); -} - -function mungePath(pathname, slug, options) { - pathname = options.item.pathHandler==='posix' - ? libPath.posix.join(pathname, slug) - : libPath.join(pathname, slug); - if (pathname.includes('\\')) pathname = pathname.replace(/\\/g, '/'); - return pathname; -} - - /* treats filename ".acl" and ".meta" as extensions - */ - function getExtension(pathname,options) { - let ext = ( basename(pathname,options.item.pathHandler).startsWith('.') ) - ? basename(pathname,options.item.pathHandler) - : options.item.pathHandler==='posix' - ? libPath.posix.extname(pathname) - : libPath.extname(pathname) - return ext - } - function getContentType(ext,type) { if( !ext || ext==='.ttl' @@ -74,7 +46,7 @@ function mungePath(pathname, slug, options) { function isAuxResource(o) { return linkExt.find(ext => - getExtension( o.item.pathname,o ) === ext + this.getExtension( o ) === ext ) } async function getAuxResources (pathname, options,storage) { @@ -115,16 +87,12 @@ async function getAvailableUrl (pathname, slug = uuidv1(), options,storage) { return slug } -export default { +export { createServerlessPod, - mungePath, - getExtension, getContentType, isAuxResource, isLink, getAuxResources, getLinks, getAvailableUrl, linkExt, linksExt, - pathSep, - basename, } diff --git a/test.txt b/test.txt new file mode 100644 index 0000000..95d09f2 --- /dev/null +++ b/test.txt @@ -0,0 +1 @@ +hello world \ No newline at end of file diff --git a/tests/jz.js b/tests/jz.js new file mode 100644 index 0000000..182df92 --- /dev/null +++ b/tests/jz.js @@ -0,0 +1,88 @@ +import SolidRest from '../'; +import SolidRestFile from '../plugins/solid-rest-file'; +import SolidRestMem from '../plugins/solid-rest-mem'; + +let [tests,fails,passes,res] = [0,0,0] +let allfails = 0 + +let client = getRestClient('file'); + +const cfg = { + base : `file://${process.cwd()}/`, + file : `file://${process.cwd()}/test.txt`, + text : "hello world", +} + +async function test(){ + + res = await GET( cfg.base ) + ok("200 get container",res.status==200, res) + + res = await PUT( cfg.file,cfg.text ) + ok( "201 put resource", res.status==201,res) + + res = await GET( cfg.file ) + ok("200 get resource",res.status==200 && await res.text()===cfg.text, res) + +} +test(); + +function getRestClient(protocol,parser){ + const plugin = protocol.startsWith('file') ? new SolidRestFile() + : protocol.startsWith('mem') ? new SolidRestMem() + : protocol.startsWith('ssh') ? new SolidRestSsh() : null; + return new SolidRest({ + plugin : plugin, + parser : parser, + }); +} +async function GET(url){ + return await client.fetch( url, {method:"GET"} ) +} +async function HEAD(url){ + return await client.fetch( url, {method:"HEAD"} ) +} +async function PUT(url,text){ + return await client.fetch( url, {method:"PUT",body:text,headers:{"content-type":"text/plain"}} ) +} +async function PATCH(url, patchContent, patchContentType){ + return await client.fetch(url, { + method: 'PATCH', + body:patchContent, + headers:{ + 'Content-Type': patchContentType, + link: '; rel="type"' + }, + relative: true + }) +} +async function DELETE(url){ + return await client.fetch( url, {method:"DELETE"} ) +} +async function POST(parent,item,content,link){ + return await client.fetch( parent,{ + method:"POST", + headers:{slug:item,link:link,"content-type":"text/turtle"}, + body:content + }) +} +async function postFile(parent,file,content){ + let link = '; rel="type"' + return POST(parent,file,content,link) +} +async function postFolder(parent,folder){ + let link ='; rel="type"' + return POST(parent,folder,'',link) +} + +/* ============================================== */ + +function ok( label, success,res ){ + tests = tests + 1; + if(success) passes = passes + 1 + else fails = fails+1 + let msg = success ? "ok " : "FAIL " + console.warn( " " + msg + label) + if(!success && res ) console.warn(res.status,res.statusText) + return success +} From d0bbcee89a4bbc3b2e236722544a96edc40e7a13 Mon Sep 17 00:00:00 2001 From: jeff-zucker Date: Tue, 15 Dec 2020 09:53:46 -0800 Subject: [PATCH 03/11] 32 out of 33! --- package.json | 2 +- plugins/solid-rest-file/src/index.js | 75 ++++----- src/examineRequestedItem.js | 8 +- src/handleRequest.js | 47 +++--- src/handleResponse.js | 50 ++++-- src/index.js | 233 +++++---------------------- src/performRequestedMethod.js | 172 ++++++++++++-------- src/utils/rest-patch.js | 17 +- src/utils/utils.js | 24 ++- tests/all.js | 69 ++++---- tests/shouldFail.js | 89 ++++++++++ tests/shouldSucceed.js | 129 +++++++++++++++ 12 files changed, 524 insertions(+), 391 deletions(-) create mode 100644 tests/shouldFail.js create mode 100644 tests/shouldSucceed.js diff --git a/package.json b/package.json index c581078..a1b6c47 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "solid-rest", - "version": "1.4.0", + "version": "2.0.0", "author": "Jeff Zucker", "license": "MIT", "description": "treat any storage as a mini Solid server", diff --git a/plugins/solid-rest-file/src/index.js b/plugins/solid-rest-file/src/index.js index a26584e..cfa8bf6 100644 --- a/plugins/solid-rest-file/src/index.js +++ b/plugins/solid-rest-file/src/index.js @@ -1,6 +1,6 @@ const concatStream = require('concat-stream') const Readable = require('stream').Readable -const path = require("path"); +const libPath = require("path"); const fs = require("fs-extra"); class SolidFileStorage { @@ -32,8 +32,11 @@ class SolidFileStorage { return text(stream).then(text => JSON.parse(text)) } + async itemExists(path){ + return fs.existsSync(path); + } + async getObjectType(fn,request){ - request = request.request || request; fn = fn.replace( request.protocol+'//','') let stat; try { stat = fs.lstatSync(fn); } @@ -56,10 +59,10 @@ async getObjectType(fn,request){ } let type = ( stat && stat.isDirectory()) ? "Container" : "Resource"; if(!stat && fn.endsWith('/')) type = "Container" - stat = stat ? true : false + let exists = await this.itemExists(fn); let item = { mode : mode, - exists : stat, + exists : exists, isContainer : type==="Container" ? true : false, } return Promise.resolve( [type,stat,mode,item] ) @@ -74,46 +77,32 @@ async getResource(pathname,options,objectType){ ] } -/* -async putResource(pathname,options){ - return new Promise((resolve) => { - options.body = this._makeStream( options.body ); - options.body.pipe(fs.createWriteStream(pathname)).on('finish',()=>{ - resolve( [201] ) - }).on('error', (err) => { - if(options.method==="PUT" && options.objectType==="Container") - resolve( [405] ) - resolve( [500] ) - }) - }) -} -*/ -async putResource(pathname,request,item){ - let successCode = 201; - let failureCode = 500; +async putResource(pathname,content){ + let successCode = [200]; + let failureCode = [500]; return new Promise(async (resolve) => { let writeIt=false - if(typeof request.body==="undefined") request.body = "" - if(typeof request.body==="string"){ + if(typeof content==="undefined") content = "" + if(typeof content==="string"){ writeIt=true } - else if(request.body.stream){ - request.body = await request.body.stream() - request.body = await request.body.read() + else if(content.stream){ + content = await content.stream() + content = await content.read() writeIt=true } - else if(request.body.text){ - request.body = await request.body.text() + else if(content.text){ + content = await content.text() writeIt=true } if(writeIt){ try { - await fs.writeFileSync(pathname,request.body) + await fs.writeFileSync(pathname,content) return resolve([successCode]) } catch(e){ console.log(e); return resolve([failureCode])} } - if(!request.body.pipe && typeof FileReader !="undefined"){ + if(!content.pipe && typeof FileReader !="undefined"){ var fileReader = new FileReader(); fileReader.onload = function() { fs.writeFileSync(pathname, Buffer.from( @@ -127,12 +116,12 @@ async putResource(pathname,request,item){ console.log(err); return resolve([failureCode]) } - fileReader.readAsArrayBuffer(request.body); + fileReader.readAsArrayBuffer(content); } else { - request.body = request.body || "" - request.body = this._makeStream( request.body ); - request.body.pipe(fs.createWriteStream(pathname)).on('finish',()=>{ + content = content || "" + content = this._makeStream( content ); + content.pipe(fs.createWriteStream(pathname)).on('finish',()=>{ return resolve( [successCode] ) }).on('error', (err) => { console.log(err) @@ -144,41 +133,41 @@ async putResource(pathname,request,item){ async deleteResource(fn){ return new Promise(function(resolve) { fs.unlink( fn, function(err) { - if(err) resolve( [409] ); + if(err) resolve( false ); else resolve( [200] ); }); }); } deleteContainer(fn) { - return new Promise(function(resolve) { - fs.rmdir( fn, function(err) { + return new Promise(async function(resolve) { + await fs.rmdir( fn, function(err) { if(err) { - resolve( [409] ); + resolve( false ); } else { resolve( [200] ); } }); }); } -postContainer(fn,options){ +async postContainer(fn,options){ fn = fn.replace(/\/$/,''); return new Promise(function(resolve) { if(fs.existsSync(fn)){ - return resolve( [201] ) + return resolve( [200] ) } fs.mkdirp( fn, {}, (err) => { if(err) { - return resolve( [500] ) + return resolve( false ) } else { - return resolve( [201] ) + return resolve( [200] ) } }); }); } async makeContainers(pathname){ - const foldername = path.dirname(pathname) + const foldername = libPath.dirname(pathname) if (!fs.existsSync(foldername)) { try { fs.mkdirpSync(foldername); diff --git a/src/examineRequestedItem.js b/src/examineRequestedItem.js index 98458c0..a95ce42 100644 --- a/src/examineRequestedItem.js +++ b/src/examineRequestedItem.js @@ -1,9 +1,9 @@ import libPath from "path"; import Url from "url"; -export async function getItem(uri,request,storage){ +export async function getItem(uri,request){ const [objectType,objectExists,mode,item] = - await this.storage.getObjectType(uri,request) + await this.perform('GET_ITEM_INFO',uri,request) item.mode = item.mode ? item.mode : {read:true,append:true,write:true}; let pathHandler,url; if (request.protocol.startsWith('file')) { @@ -21,8 +21,8 @@ export async function getItem(uri,request,storage){ // item.pathname = url.replace(request.protocol+'//','') ??? item.pathname = uri.replace(request.protocol+'//','') if( request.method==='DELETE' && item.isContainer){ - let files = await storage.getContainer(item.pathname); - files = files.filter(file => !this.isLink(file,{item:{pathHandler:item.pathHandler}})) + let files = await this.perform('GET_FILES',item.pathname); + files = files.filter(file => !this.isAuxResource(file)) if (files.length) item.containerNotEmpty = true; } diff --git a/src/handleRequest.js b/src/handleRequest.js index 2526da9..ab81fd4 100644 --- a/src/handleRequest.js +++ b/src/handleRequest.js @@ -1,34 +1,33 @@ -import {getItem} from './examineRequestedItem.js'; -import {getRequest} from './examineRequest.js'; - const methods = { - DELETE : { mustPrexist:1, requiresWrite:1 }, - POST : { mustPrexist:1, requiresAppend:1, requiresContentType:1 }, - GET : { mustPrexist:1, requiresRead:1 }, - HEAD : { mustPrexist:1, requiresRead:1 }, - OPTIONS : { mustPrexist:1, requiresRead:1 }, + DELETE : { mustExist:1, requiresWrite:1 }, + POST : { mustExist:1, requiresAppend:1, requiresContentType:1 }, + GET : { mustExist:1, requiresRead:1 }, + HEAD : { mustExist:1, requiresRead:1 }, + OPTIONS : { mustExist:1, requiresRead:1 }, PUT : { requiresWrite:1, requiresContentType:1 }, PATCH : { requiresWrite:1, requiresContentType:1 }, } - export async function handleRequest( uri, originalRequest ){ const request = this.request = await this.getRequest( uri, originalRequest ); if( !request.url || !request.method ) return 400; if( request.slug.endsWith('/') ) return 400; if( request.originMismatch ) return 403; - if( request.method==='PATCH' && !request.validPatchContent ) return 400; + if( request.invalidPatchContent ) return 400; + if( request.unsupportedAcceptFormat ) return 405; + if( request.method==='POST' && !request.headers.link ) return 400; const item = this.item = await this.getItem( uri, request ); - if( this.isAuxResource() ){ - request.method.requiresControl = true; + if( item.folderFileConfusion ) return 400; // can't have both /foo and /foo/ + if( item.isAuxResource ){ + if( item.isAcl ) request.method.requiresControl = true; if( request.method==="POST" ) return 405; } if( request.method==='DELETE' && item.containerNotEmpty ) return 409; - if( request.method==='PATCH' && !item.canBePatched ) return 405; - if( item.mode.control ) item.mode.write=true; - if( item.mode.write ) item.mode.append=true; + if( request.method==='PATCH' && !this.patch ) return 405; + if( item.mode.control ) item.mode.write=true; // does control imply read? + if( item.mode.write ) item.mode.append=true; // does write imply read? const method = methods[request.method]; if( !method ) return 409; - if( method.mustPrexist && !item.exists ) return 404; + if( method.mustExist && !item.exists ) return 404; if( (method.requiresRead && !item.mode.read) || (method.requiresAppend && !item.mode.append ) || (method.requiresWrite && !item.mode.write ) @@ -36,17 +35,25 @@ export async function handleRequest( uri, originalRequest ){ ) return 401; if( method.requiresContentType && !request.headers['content-type'] ) return 400; + if ( request.method==='POST' ){ + this.item.pathname = await this.generateRandomSlug( + this.item.pathname, this.request.slug + ) +} if ( request.method==='PUT'||request.method==='PATCH'){ if( item.isContainer ) return 405; let okDir = await this.perform('CREATE_INTERMEDIATE_CONTAINERS'); if( !okDir ) return 500; } if( request.method==='DELETE' ){ - let okDel = await this.perform('DELETE_AUX_RESOURCES'); - if( !okDel ) return 500; + let del = await this.perform('DELETE_AUX_RESOURCES'); + if( !del ) return 500; + if( this.isAccessError(del) ) return 401; } - let successfulRequest = await this.perform(request.method); - return successfulRequest ? successfulRequest : 500; + let response = await this.perform(request.method); + if( !response ) return 500; + if( this.isPatchConflictError(response) ) return 400; + return response; } // ENDS diff --git a/src/handleResponse.js b/src/handleResponse.js index 1130dc7..dca8164 100644 --- a/src/handleResponse.js +++ b/src/handleResponse.js @@ -1,28 +1,31 @@ -const { Response } = require('cross-fetch') +//import { Response,Headers } from 'cross-fetch'; +import { Response,Headers } from 'node-fetch'; export async function handleResponse(response){ const pathname = this.item.pathname; - const status = response[0]; - const body = response[1]; + const isError = typeof response==='number'; + response = isError ? [response] : response; + let status = response[0]; + let body = response[1] || ""; let headers = response[2] || {}; - const headersFromPlugin = - typeof this.storage.getHeaders != "undefined" - ? this.storage.getHeaders(pathname) - : {} - let name = this.storage.name +// const headersFromPlugin = this.perform('STORAGE_HEADER_METHOD'); +// if(this.request.method==="PATCH" && status>399 && body){ headers.statusText=body;body=""; } + let name = this.perform('STORAGE_NAME'); const item = this.item; const request = this.request; const fn = this.basename(pathname,item.pathHandler) - Object.assign(headers,headersFromPlugin); +// Object.assign(headers,headersFromPlugin); - headers.location = headers.url = headers.location - || request.url +// headers.location = headers.url = headers.location || this.response.headers.location + + if(this.response && this.response.headers) + headers.location = this.response.headers.location headers.date = headers.date || new Date(Date.now()).toISOString() headers.allow = headers.allow - || createAllowHeader(this.canPatch,this.item.mode) + || createAllowHeader(this.patch,this.item.mode) let wacAllow = headers['wac-allow'] || createWacHeader(item.mode) @@ -41,7 +44,11 @@ export async function handleResponse(response){ if(!headers['content-type']){ delete headers['content-type'] } - if(this.canPatch) { + else { + headers['content-type'] = headers['content-type'].replace(/;.*/,''); + } + + if(this.patch) { headers['ms-author-via']=["SPARQL"]; headers['accept-patch']=['application/sparql-update']; } @@ -68,8 +75,21 @@ export async function handleResponse(response){ +`; rel="type"` } } - headers.status = status; - return new Response(body, headers) + headers.status = parseInt(status) || 500; +for(var k in headers) { + if(typeof headers[k]==='undefined') delete headers[k]; +} +// console.log('handleResponse1',headers) + + headers = (isError || this.request.method==='PATCH') ? headers : {headers:headers} + + let resp + try{ + resp = new Response(body, headers) + } catch(e){console.log(e)} +// for(var h of resp.headers.entries()){console.log(1,h)}; +//console.log('handleResponse2',resp) + return resp } // end of getHeaders() function createWacHeader( mode ){ diff --git a/src/index.js b/src/index.js index a249236..1c8d8db 100644 --- a/src/index.js +++ b/src/index.js @@ -1,5 +1,3 @@ -"use strict"; - import {getRequest} from './examineRequest.js'; import {getItem} from './examineRequestedItem.js'; import {handleRequest} from './handleRequest.js'; @@ -9,215 +7,60 @@ import {handleResponse} from './handleResponse.js'; import { createServerlessPod, getContentType, - isAuxResource, isLink, - getAuxResources, getLinks, - getAvailableUrl, - linkExt, - linksExt, + isAuxResource, + getAuxResources, + generateRandomSlug, } from './utils/utils.js'; import containerAsTurtle from './utils/container.js'; -const RestPatch = require('./utils/rest-patch') - - -let patch,pathname,pathSep,request,item; +import RestPatch from './utils/rest-patch'; export default class SolidRest { -constructor( options ) { - options = options || {} - if(!options.plugin) { - console.log(`You must specify a plugin storage handler!`); - process.exit(1); - } - this.storage = options.plugin; - this.handleRequest = handleRequest.bind(this); - this.handleResponse = handleResponse.bind(this); - this.getItem = getItem.bind(this); - this.getRequest = getRequest.bind(this); - this.perform = perform.bind(this); - this.isAuxResource = isAuxResource.bind(this); - this.getAuxResources = getAuxResources.bind(this); - this.getContentType = getContentType.bind(this); - this.getAvailableUrl = getAvailableUrl.bind(this); - this.containerAsTurtle = containerAsTurtle.bind(this); -/* - createServerlessPod, - isLink, - getLinks, - linkExt, - linksExt, -*/ - let $rdf = (options.parser) ? options.parser - : (typeof window !="undefined" && window.$rdf) ? window.$rdf - : (typeof global !="undefined" && global.$rdf) ? global.$rdf - : null; - patch = options.patch = ($rdf) ? new RestPatch($rdf) : null; - this.os = { canPatch : patch ? true :false }; -} - -async createServerlessPod ( base ){ - return u.createServerlessPod( base ); -} + constructor( options ) { -async itemExists(pathname,options){ - return (await this.storage.getObjectType(pathname, options),request)[1] -} + options = options || {} + if(!options.plugin) { + console.log(`You must specify a plugin storage handler!`); + process.exit(1); + } -async fetch(uri, options = {}) { - let request = await this.handleRequest(uri,options); - return await this.handleResponse(request); -/* + this.storage = options.plugin; + this.handleRequest = handleRequest.bind(this); + this.handleResponse = handleResponse.bind(this); + this.getItem = getItem.bind(this); + this.getRequest = getRequest.bind(this); + this.perform = perform.bind(this); + this.isAuxResource = isAuxResource.bind(this); + this.getAuxResources = getAuxResources.bind(this); + this.getContentType = getContentType.bind(this); + this.generateRandomSlug = generateRandomSlug.bind(this); + this.createServerlessPod = createServerlessPod.bind(this); + this.containerAsTurtle = containerAsTurtle.bind(this); + + let $rdf = (options.parser) ? options.parser + : (typeof window !="undefined" && window.$rdf) ? window.$rdf + : (typeof global !="undefined" && global.$rdf) ? global.$rdf + : null; + this.patch = options.patch = ($rdf) ? new RestPatch($rdf) : null; - if( options.method==="DELETE" ){ - return makeResponse( resOptions, - await actions.DELETE(pathname,options,this.storage) - ); } - // POST - - if( options.method==="POST"){ - let link = options.headers.link - let slug = options.headers.Slug || options.headers.slug || options.slug - if(slug.match(/\//)) return _response(null, resOptions, 400) - if( link && link.match("Container") ) { - options.resourceType="Container" - slug = await u.getAvailableUrl(pathname, slug, options,this.storage) // jz add - pathname = u.mungePath(pathname, slug, options) - const [status, , headers] = await self.storage.postContainer(pathname,options) -// Object.assign(resOptions.headers, { location: mapPathToUrl(pathname, options) + '/' }) - Object.assign(resOptions.headers, { location: pathname + '/' }) - Object.assign(resOptions.headers, headers) - return _response(null, resOptions, status) - } - else if( link && link.match("Resource")){ - options.resourceType="Resource" - slug = await u.getAvailableUrl(pathname, slug, options,this.storage) - pathname = u.mungePath(pathname, slug, options) - if (u.isLink(pathname, options)) return _response(null, resOptions, 405) - const [status, , headers] = await self.storage.putResource( pathname, options) - Object.assign(resOptions.headers, { location: pathname }) - Object.assign(resOptions.headers, headers) - return _response(null, resOptions, status) - } - + async fetch( uri, options = {} ) { + let request = await this.handleRequest(uri,options); + return await this.handleResponse(request); } - // PUT - - if (options.method === 'PUT' ) { - const [status, undefined, headers] = await self.storage.makeContainers(pathname,options) - Object.assign(resOptions.headers, headers) - if(status !== 200 && status !== 201) return _response(null, resOptions, status) - const [putStatus, , putHeaders] = await self.storage.putResource(pathname, options) - - Object.assign(resOptions.headers, putHeaders) // Note: The headers from makeContainers are also returned here - - return _response(null, resOptions, putStatus) + async itemExists(pathname){ + return await this.perform('ITEM_EXISTS',pathname); } - // PATCH - - if (options.method === 'PATCH' ) { - - if(!patch){ - console.log( 'TO USE PATCH, YOU MUST IMPORT rdflib IN YOUR MAIN SCRIPT AND SET global.$rdf = $rdf'); - return _response( null, resOptions, 405); - } - // check pathname and 'text/turtle'. TODO see if NSS allows other RD - - let content = '' - if (objectExists) { - const [status, contents, headers] = await self.storage.getResource(pathname,options) - content = typeof contents === 'string' ? contents : contents.toString() - } - const contentType = u.getContentType(u.getExtension(pathname, options)) - if (contentType !== 'text/turtle') return _response('500 '+ pathname + ' is not a "text/turtle" file', resOptions, 500) - - // patch content - try { - const [patchStatus, resContent] = await patch.patchContent(content, contentType, options) - if ( patchStatus !== 200) return _response(resContent, resOptions, patchStatus) - options.body = resContent - options.headers['content-type'] = contentType - } catch (e) { throw _response(e, resOptions, parseInt(e)) } - - // PUT content to file - if (!objectExists) { - const [status, undefined, headers] = await self.storage.makeContainers(pathname,options) - // TODO add patchHeaders('MS-Author-Via', 'SPARQL') - Object.assign(resOptions.headers, headers) - if(status !== 200 && status !== 201) return _response(null, resOptions, status) - } - const [putStatus, , putHeaders] = await self.storage.putResource(pathname, options) - - //Object.assign(resOptions.headers, putHeaders) // Note: The headers from makeContainers are also returned here - - let returnStatus = (putStatus === 201) ? 200 : putStatus - return _response(null, resOptions, returnStatus) - } - else { - return _response(null, resOptions, 405) + isPatchConflictError(response){ + if(response===400) return true; } - function handleResponse(response){ - // combine the standard headers with ones returned from the action if any - // respons = [status,body,headers] -// Object.assign(resOptions.headers, response[2]) -// return _response( response[1], resOptions, response[0] ); - let status = response[0]; - let body = response[1]; - let headers = response[2]; - options.status = status; - let headersFromPlugin = - typeof this.storage.getHeaders != "undefined" - ? this.storage.getHeaders(pathname,options,item,request) - : {} - let name = self.storage.name - headers = Object.assign( - getResponseHeader( - pathname,options,headersFromPlugin,name,item,request - ), - options.headers - ) - return new Response(body, options) - } -*/ - function makeResponse(resOptions,response){ - // combine the standard headers with ones returned from the action if any - // respons = [status,body,headers] - Object.assign(resOptions.headers, response[2]) - return _response( response[1], resOptions, response[0] ); + isAccessError(response){ + if(response===401) return true; } - /** - * @param {RequestInfo} body - * @param {RequestInit} options - * @param {Number} status - Overrules options.status - */ - function _response(body, options, status = options.status) { - options.status = status; - let headersFromPlugin = - typeof self.storage.getHeaders != "undefined" - ? self.storage.getHeaders(pathname,options,item,request) - : {} - let name = self.storage.name - options.headers = Object.assign( - getResponseHeader( - pathname,options,headersFromPlugin,name,item,request - ), - options.headers - ) - return new Response(body, options) - } - - - } // end of fetch() - -} // end of SolidRest() - -// module.exports = exports = SolidRest -// module.exports.SolidRest = SolidRest - - +} // THE END diff --git a/src/performRequestedMethod.js b/src/performRequestedMethod.js index 7479438..2d0c2e9 100644 --- a/src/performRequestedMethod.js +++ b/src/performRequestedMethod.js @@ -1,68 +1,114 @@ -export default async function perform(method,pathname){ - pathname = pathname || this.item.pathname; - let res; - switch( method || this.request.method ) { - case 'GET': - if( this.item.isContainer ){ - let files = await this.storage.getContainer(pathname) - return await this.containerAsTurtle(pathname,files) - } - else { - return await this.storage.getResource(pathname) - } - break; - case 'PUT': - res = await this.storage.putResource(pathname,this.request,this.item) - return(res) - break; - case 'CREATE_INTERMEDIATE_CONTAINERS': - res = await this.storage.makeContainers(pathname) - return(res) - //return await this.storage.makeContainers(pathname) - break; - default: - - } -} /* - async GET(pathname,options,storage){ - if( options.item.isContainer ){ - let files = await storage.getContainer(pathname,options) - return await containerAsturtle(pathname,options,files,storage) - } - else { - return await storage.getResource(pathname,options) - } - } + All calls to the storage plugin happen here. Calls include + * Solid-rest verbs (GET_ITEM_INFO), etc. + * Rest verbs (GET,etc.) - async DELETE(pathname,options,storage){ - const links = await this.getLinks(pathname, options,storage); - if (links.length) - links.map( async (link) => { - await storage.deleteResource(link,options) - }) - if (options.item.isContainer) - return await storage.deleteContainer(pathname,options) - else - return await storage.deleteResource(pathname,options) - } +The **request** object is created in examineRequest.js. It is a munged version of the request recieved with keys, headers, and method names normalized. + +The **item** object is created in examineRequestedItem.js. It contains all information about an item including its type, mode, and other details returned from the storage plugin's item_info method. + +The **headers** object - async PUT(pathname,options,storage){ -return(777); - } - async POST(pathname,options,storage){ -return(777); - } - async PATCH(pathname,options,storage){ -return(777); - } - async HEAD(pathname,options,storage){ -return(777); - } - async OPTIONS(pathname,options,storage){ -return(777); - } - -} */ + +export default async function perform(method,pathname,arg){ + method = method || this.request.method; + pathname = pathname || this.item.pathname; + let res; + this.response = this.response || {headers:{}}; + switch( method ) { + + case 'STORAGE_NAME': + return this.storage.name; + break; + + case 'ITEM_EXISTS': + return await this.storage.itemExists(pathname); + break; + + case 'GET_ITEM_INFO': + return await this.storage.getObjectType(pathname,arg) + break; + + case 'GET_FILES': + return await this.storage.getContainer(pathname) + break; + + case 'DELETE_AUX_RESOURCES': + const links = await this.getAuxResources(pathname) || []; + try { + links.map( async (link) => { await this.storage.deleteResource(link) }) + } + catch(e){ console.log(e); return null; } + return 200; + break; + + case 'CREATE_INTERMEDIATE_CONTAINERS': + return await this.storage.makeContainers(pathname); + break; + + case 'GET': + if( this.item.isContainer ){ + let files = await this.storage.getContainer(pathname) + return await this.containerAsTurtle(pathname,files) + } + else { + return await this.storage.getResource(pathname) + } + break; + + case 'OPTIONS': + case 'HEAD': + return [200]; + break; + + case 'PUT': + return await this.storage.putResource(pathname,this.request.body); + break; + + case 'DELETE': + if (this.item.isContainer) + return await this.storage.deleteContainer(pathname) + else + return await this.storage.deleteResource(pathname) + break; + + case 'POST': + if( this.request.headers.link.match("Container") ){ + this.response.headers.location = pathname + '/'; + return await this.storage.postContainer(pathname,this.request) + } + else { + this.response.headers.location = pathname; + return await this.storage.putResource(pathname,this.request.body) + } + break; + + case 'PATCH': + let [getStatus,oldContent,h] = await this.storage.getResource(pathname) + if(getStatus !== 200) return [getStatus] + oldContent = typeof oldContent === 'string' + ? oldContent : oldContent.toString() + const contentType = this.getContentType( this.getExtension(pathname) ); + if (contentType !== 'text/turtle') + return [400,"Can not patch : ${pathname} is not a text/turtle file"]; + let newContent; + try { + const [patchStatus, newContent] = await this.patch.patchContent( + oldContent, contentType, this.request + ) + if ( patchStatus !== 200 ) return [ patchStatus, newContent ] + } catch (e) { return [parseInt(e),e] } + const status = await this.storage.makeContainers(pathname); + if(!status) return [500] + this.request.body = newContent + const [putStatus,,putHeaders] = await this.storage.putResource( + pathname, this.request.body + ); + console.log(newContent) + return [putStatus,newContent]; + break; + + } +} diff --git a/src/utils/rest-patch.js b/src/utils/rest-patch.js index f6c070f..1a39c32 100644 --- a/src/utils/rest-patch.js +++ b/src/utils/rest-patch.js @@ -1,5 +1,5 @@ let $rdf; -//const crypto = require('crypto') TODO may be +//import crypto from 'crypto' TODO may be const PATCH_NS = 'http://www.w3.org/ns/solid/terms#' const PREFIXES = `PREFIX solid: <${PATCH_NS}>\n` @@ -10,21 +10,21 @@ const PATCH_PARSERS = { 'text/n3': parsePatchN3 } -class RestPatch { +export default class RestPatch { constructor(passedRDF){ $rdf = passedRDF; } - async patchContent (content, contentType, options) { - const url = options.url + async patchContent (content, contentType, request) { + const url = request.url; const resource = { contentType: contentType, - url: url } - // Obtain details of the patch document + url: url + } const patch = { - text: options.body.toString(), - contentType: options.headers['content-type'] // normalized to lowercase + text: request.body.toString(), + contentType: request.headers['content-type'] } const parsePatch = PATCH_PARSERS[patch.contentType] if (!parsePatch) { @@ -129,4 +129,3 @@ function queryForFirstResult(store, sparql) { }) } -module.exports = exports = RestPatch diff --git a/src/utils/utils.js b/src/utils/utils.js index dcc0ce5..1f9b4d6 100644 --- a/src/utils/utils.js +++ b/src/utils/utils.js @@ -1,6 +1,7 @@ import libPath from "path"; import {contentType as contentTypeLookup} from 'mime-types' -const { v1: uuidv1 } = require('uuid') +import { v1 as uuidv1 } from 'uuid' +//const { v1: uuidv1 } = require('uuid') import pod from './createServerlessPod.js'; const linkExt = ['.acl', '.meta'] @@ -51,7 +52,7 @@ const linksExt = linkExt.concat('.meta.acl') } async function getAuxResources (pathname, options,storage) { let linksExists = linksExt.filter(async ext => - await storage.getObjectType(pathname + ext,options.request)[1] + await this.storage.itemExists(pathname + ext) ) const links = linksExists.map( ext => pathname + ext) return links || []; @@ -60,7 +61,7 @@ const linksExt = linkExt.concat('.meta.acl') // TBD : remove getLinks and isLink, replace in code with isAuxResource, etc. function isLink(pathname,options) { - return linkExt.find(ext => getExtension(pathname,options) === ext) + return linkExt.find(ext => this.getExtension(pathname,options) === ext) } /** @@ -76,15 +77,12 @@ async function getLinks (pathname, options,storage) { return links } - -/* getAvailableUrl - generate random prefix for POST file names -*/ -async function getAvailableUrl (pathname, slug = uuidv1(), options,storage) { - let requestUrl = mungePath(pathname, slug, options) - if(options.resourceType==='Container' && !requestUrl.endsWith(pathSep(options.item.pathHandler))) requestUrl = requestUrl + pathSep(options.item.pathHandler) - let urlExists = (await storage.getObjectType(requestUrl, options,options.request))[1] - if (urlExists) { slug = `${uuidv1()}-${slug}` } - return slug +async function generateRandomSlug (pathname, slug = uuidv1()) { + let requestUrl = this.mungePath(pathname, slug) + if( this.item.isContainer && !this.request.url.endsWith(this.pathSep) ) + requestUrl = requestUrl + this.pathSep + if( await this.storage.itemExists(requestUrl) ){ slug=`${uuidv1()}-${slug}` } + return this.mungePath(pathname, slug) } export { @@ -92,7 +90,7 @@ export { getContentType, isAuxResource, isLink, getAuxResources, getLinks, - getAvailableUrl, + generateRandomSlug, linkExt, linksExt, } diff --git a/tests/all.js b/tests/all.js index 382835e..71f560d 100644 --- a/tests/all.js +++ b/tests/all.js @@ -1,6 +1,3 @@ -"use strict"; - - // SAME TEST SHOULD WORK FOR solid-rest AND solid-node-client // //const SolidNodeClient = require('../').SolidNodeClient @@ -10,9 +7,9 @@ // const client = new SolidRest() const $rdf = require('rdflib'); -const SolidRest = require('../') -const SolidRestFile = require('../plugins/solid-rest-file'); -const SolidRestMem = require('../plugins/solid-rest-mem'); +import SolidRest from '../'; +import SolidRestFile from '../plugins/solid-rest-file'; +import SolidRestMem from '../plugins/solid-rest-mem'; function getRestClient(protocol,parser){ const plugin = protocol.startsWith('file') ? new SolidRestFile() @@ -23,7 +20,7 @@ function getRestClient(protocol,parser){ parser : parser, }); } -let client; +let client,slug,cSlug; /** Silence rdflib chatty information about patch * Send console.log() to a logfile @@ -209,6 +206,10 @@ const resPatchN3_2 = [`@prefix : <#>. return(cfg) } +const check = { + headers:1, + patch:1, +} async function run(scheme){ @@ -222,27 +223,28 @@ async function run(scheme){ console.warn(`\nTesting ${cfg.base} ...`) - /** POST */ + /// POST res = await postFolder( cfg.base,cfg.c1name ) ok( "400 post container with trailing slash on slug", res.status==400,res) cfg.c1name = cfg.c1name.replace(/\/$/,'') res = await postFolder( cfg.base,cfg.c1name ) - ok( "201 post container", res.status==201,res) + ok( "201 post container", res.status==201 || res.status==200,res) +if(check.headers){ let loc = res.headers.get('location') ok( "post container returns location header",loc.match(`${cfg.c1name}/`)) res = await postFolder( cfg.base,cfg.c1name ) - let cSlug = res.headers.get('location') + cSlug = res.headers.get('location') ok( "post container returns location header (new slug generated)", cfg.folder1!=cSlug && cSlug.match('-'+cfg.c1name)) res = await postFolder( cfg.missingFolder,cfg.c2name ) ok( "404 post container, parent not found", res.status==404,res) res = await postFile( cfg.folder1,cfg.r1name,cfg.text ) - ok( "201 post resource", res.status==201,res) + ok( "200 post resource", res.status==200,res) loc = res.headers.get('location') ok( "post resource returns location header", (cfg.folder1+cfg.r1name).match(loc), loc) @@ -252,40 +254,41 @@ async function run(scheme){ // ok( "405 post aux resource", res.status==405,res) res = await postFile( cfg.folder1,cfg.r1name,cfg.txt ) - ok( "201 post resource, resource found", res.status==201, res ) - let slug = res.headers.get('location') + ok( "200 post resource, resource found", res.status==200, res ) + slug = res.headers.get('location') || ""; ok( "post resource returns location (new slug generated)", slug !== cfg.r1name && slug.endsWith('-test1.ttl'),res) +} res = await postFile( cfg.missingFolder,cfg.file2 ) ok( "404 post resource, parent not found", res.status==404,res) - /** PUT */ + // PUT res = await PUT( cfg.folder1 ) ok( "405 put container (method not allowed)", res.status==405,res) res = await PUT( cfg.file1,cfg.text ) - ok( "201 put resource", res.status==201,res) + ok( "200 put resource", res.status==200,res) res = await PUT( cfg.file1,cfg.text ) - ok( "201 put resource, resource found", res.status==201,res) + ok( "200 put resource, resource found", res.status==200,res) res = await PUT( cfg.deepR,cfg.text ) - ok("201 put resource, parent not found (recursive creation)",res.status==201, res) + ok("200 put resource, parent not found (recursive creation)",res.status==200, res) res = await PUT( cfg.folder2meta,cfg.text ) - ok("201 put container acl",res.status==201, res) + ok("200 put container acl",res.status==200, res) res = await PUT( cfg.deepRacl,cfg.text ) - ok("201 put resource acl",res.status==201, res) + ok("200 put resource acl",res.status==200, res) - /** HEAD */ + // HEAD res = await HEAD( cfg.deepR ) ok("200 head",res.status==200 && res.headers.get("allow"),res ) res = await HEAD( cfg.missingFolder ) ok("404 head resource, not found",res.status==404,res ) - /** GET */ + // GET res = await GET( cfg.missingFolder ) ok("404 get container, not found",res.status==404,res ) @@ -296,7 +299,8 @@ async function run(scheme){ let type = res.headers.get("content-type") ok("200 get container",res.status==200 && type==="text/turtle",res) - /** PATCH */ +if( check.patch ){ + // PATCH res = await PATCH( cfg.file1,cfg.patchSparql, 'fake-contentType') ok("415 patch wrong patch contentType",res.status==415, res) @@ -315,12 +319,13 @@ async function run(scheme){ //console.warn(res1.statusText.toString()) ok("200 patch n3 insert",res.status==200 && testPatch(res1, cfg.resPatchN3_1), res1) +/* NOT WORKING ! res = await PATCH( cfg.file1,cfg.patchN3_3, 'text/n3' ) res1 = await GET( cfg.file1 ) - //console.warn(res1.statusText.toString()) ok("200 patch n3 delete, insert, where",res.status==200 && testPatch(res1, cfg.resPatchN3_2), res1) - - /** DELETE */ +*/ +} + // DELETE res = await DELETE( cfg.file1 ) // delete r1.name ok("200 delete resource",res.status==200,res) @@ -333,21 +338,28 @@ async function run(scheme){ res = await DELETE( cfg.folder2meta) ok("200 delete folder with meta", res.status===200, res) +if(check.headers && typeof slug !='undefined'){ res = await DELETE( cfg.host + slug ) ok("200 delete resource",res.status==200,res) +} - /** Cleaning */ + // Cleaning res = await DELETE( cfg.base+'/dummy.txt' ) res = await DELETE( cfg.base+'dummy.txt' ) res = await DELETE( cfg.folder2 ) res = await DELETE( cfg.folder1 ) - res = await DELETE( cfg.host + cSlug ) + + if(check.headers && typeof cSlug!='undefined'){ + res = await DELETE( cfg.host + cSlug ) + } + cfg.base = cfg.base.endsWith("/") ? cfg.base : cfg.base+"/" res = await DELETE( cfg.base ) ok("200 delete container",res.status==200,res) - console.warn(`${passes}/${tests} tests passed, ${fails} failed\n`) + let skipped = 33 - passes - fails; + console.warn(`${passes}/33 tests passed, ${fails} failed, ${skipped} skipped\n`) allfails = allfails + fails } /* =========================================================== */ @@ -406,5 +418,6 @@ function ok( label, success,res ){ async function testPatch (res, resPatch) { let content = await res.text(); +// if(!content) console.log("No body from PATCH",resPatch); return resPatch.find(string => string === content) } diff --git a/tests/shouldFail.js b/tests/shouldFail.js new file mode 100644 index 0000000..894b21c --- /dev/null +++ b/tests/shouldFail.js @@ -0,0 +1,89 @@ +import SolidRest from '../'; +import SolidRestFile from '../plugins/solid-rest-file'; +import SolidRestMem from '../plugins/solid-rest-mem'; + +let [tests,fails,passes,res] = [0,0,0] +let allfails = 0 + +let client = getRestClient('file'); + +const cfg = { + base : `file://${process.cwd()}/`, + folder1 : `test-folder`, + file1 : `test1.txt`, + folder2 : `file://${process.cwd()}/test-folder/subFolder/`, + file2 : `file://${process.cwd()}/test-folder/subFolder/test2.txt`, + text : "hello world", +} + +async function test(){ + +console.log('not found'); + res = await HEAD( 'file:///noshuchthing/' ) + ok( "get 404 on container not found", res.status==404,res) + + res = await HEAD( 'file:///noshuchthing.txt' ) + ok( "get 404 on resource not found", res.status==404,res) + +} +test(); + +function getRestClient(protocol,parser){ + const plugin = protocol.startsWith('file') ? new SolidRestFile() + : protocol.startsWith('mem') ? new SolidRestMem() + : protocol.startsWith('ssh') ? new SolidRestSsh() : null; + return new SolidRest({ + plugin : plugin, + parser : parser, + }); +} +async function GET(url){ + return await client.fetch( url, {method:"GET"} ) +} +async function HEAD(url){ + return await client.fetch( url, {method:"HEAD"} ) +} +async function PUT(url,text){ + return await client.fetch( url, {method:"PUT",body:text,headers:{"content-type":"text/plain"}} ) +} +async function PATCH(url, patchContent, patchContentType){ + return await client.fetch(url, { + method: 'PATCH', + body:patchContent, + headers:{ + 'Content-Type': patchContentType, + link: '; rel="type"' + }, + relative: true + }) +} +async function DELETE(url){ + return await client.fetch( url, {method:"DELETE"} ) +} +async function POST(parent,item,content,link,ctype){ + return await client.fetch( parent,{ + method:"POST", + headers:{slug:item,link:link,"content-type":ctype}, + body:content + }) +} +async function postFile(parent,file,content){ + let link = '; rel="type"' + return POST(parent,file,content,link,'text/plain') +} +async function postFolder(parent,folder){ + let link ='; rel="type"' + return POST(parent,folder,'',link,"text/turtle") +} + +/* ============================================== */ + +function ok( label, success,res ){ + tests = tests + 1; + if(success) passes = passes + 1 + else fails = fails+1 + let msg = success ? "can " : "CAN NOT " + console.warn( " " + msg + label) + if(!success && res ) console.warn(res.status,res.statusText) + return success +} diff --git a/tests/shouldSucceed.js b/tests/shouldSucceed.js new file mode 100644 index 0000000..5511f24 --- /dev/null +++ b/tests/shouldSucceed.js @@ -0,0 +1,129 @@ +import SolidRest from '../'; +import SolidRestFile from '../plugins/solid-rest-file'; +import SolidRestMem from '../plugins/solid-rest-mem'; + +let [tests,fails,passes,res] = [0,0,0] +let allfails = 0 + +let client = getRestClient('file'); + +const cfg = { + base : `file://${process.cwd()}/`, + folder1 : `test-folder`, + file1 : `test1.txt`, + folder2 : `file://${process.cwd()}/test-folder/subFolder/`, + file2 : `file://${process.cwd()}/test-folder/subFolder/test2.txt`, + text : "hello world", +} + +async function test(){ + +console.log('headers'); + res = await HEAD( cfg.base ) + ok( "get content-type header", res.status==200 && res.headers.get('content-type')==='text/turtle',res) + ok("get wac-allow header",res.headers.get('wac-allow').match('write'), res) + + res = await postFolder( cfg.base, cfg.folder1 ) + cfg.folder1 = cfg.base+cfg.folder1+'/'; + ok("get location header",cfg.folder1.match(res.headers.get('location')), res) + +console.log('post'); + ok("post container",res.status==200, res) + + res = await postFile( cfg.folder1, cfg.file1, cfg.text ) + ok( "post resource", res.status==200,res) + cfg.file1 = cfg.folder1+'/'+cfg.file1; + + +console.log('get'); + res = await GET( cfg.folder1 ) + ok("get container",res.status==200, res) + + + res = await GET( cfg.file1 ) + let content = await res.text(); + ok("get resource",res.status==200 && content===cfg.text, res) + +console.log('put'); + res = await PUT( cfg.file2, cfg.text ) + ok( "put resource", res.status==200,res) + +console.log('head'); + res = await HEAD( cfg.base ) + ok( "head container", res.status==200 && res.headers.get('content-type')==='text/turtle',res) + + res = await HEAD( cfg.file1 ) + ok( "head resource", res.status==200 && res.headers.get('content-type')==='text/plain',res) + +console.log('delete'); + res = await DELETE( cfg.file1 ) + res = await DELETE( cfg.file2 ) + ok( "delete resource", res.status==200,res) + + res = await DELETE( cfg.folder2 ) + res = await DELETE( cfg.folder1 ) + res = await GET( cfg.folder1 ) + ok( "delete container", res.status==404,res) + +} +test(); + +function getRestClient(protocol,parser){ + const plugin = protocol.startsWith('file') ? new SolidRestFile() + : protocol.startsWith('mem') ? new SolidRestMem() + : protocol.startsWith('ssh') ? new SolidRestSsh() : null; + return new SolidRest({ + plugin : plugin, + parser : parser, + }); +} +async function GET(url){ + return await client.fetch( url, {method:"GET"} ) +} +async function HEAD(url){ + return await client.fetch( url, {method:"HEAD"} ) +} +async function PUT(url,text){ + return await client.fetch( url, {method:"PUT",body:text,headers:{"content-type":"text/plain"}} ) +} +async function PATCH(url, patchContent, patchContentType){ + return await client.fetch(url, { + method: 'PATCH', + body:patchContent, + headers:{ + 'Content-Type': patchContentType, + link: '; rel="type"' + }, + relative: true + }) +} +async function DELETE(url){ + return await client.fetch( url, {method:"DELETE"} ) +} +async function POST(parent,item,content,link,ctype){ + return await client.fetch( parent,{ + method:"POST", + headers:{slug:item,link:link,"content-type":ctype}, + body:content + }) +} +async function postFile(parent,file,content){ + let link = '; rel="type"' + return POST(parent,file,content,link,'text/plain') +} +async function postFolder(parent,folder){ + let link ='; rel="type"' + return POST(parent,folder,'',link,"text/turtle") +} + +/* ============================================== */ + +function ok( label, success,res ){ + tests = tests + 1; + if(success) passes = passes + 1 + else fails = fails+1 + let msg = success ? "can " : "CAN NOT " + console.warn( " " + msg + label) + if(!success && res ) console.warn(res.status,res.statusText) + return success +} From b0bb5ad64c5dc3a04daed8ca6c37466dadd7980f Mon Sep 17 00:00:00 2001 From: jeff-zucker Date: Tue, 15 Dec 2020 11:44:41 -0800 Subject: [PATCH 04/11] more goodies --- plugins/solid-rest-file/src/index.js | 22 +++++++++------ src/examineRequestedItem.js | 30 +++++++++++++++++---- src/handleRequest.js | 25 ++++++++++++----- src/performRequestedMethod.js | 19 +++---------- src/utils/container.js | 5 ++-- src/utils/utils.js | 40 ++++++++-------------------- 6 files changed, 74 insertions(+), 67 deletions(-) diff --git a/plugins/solid-rest-file/src/index.js b/plugins/solid-rest-file/src/index.js index cfa8bf6..a7285ac 100644 --- a/plugins/solid-rest-file/src/index.js +++ b/plugins/solid-rest-file/src/index.js @@ -35,14 +35,21 @@ class SolidFileStorage { async itemExists(path){ return fs.existsSync(path); } - -async getObjectType(fn,request){ - fn = fn.replace( request.protocol+'//','') + async itemType(path,wantFull){ let stat; try { stat = fs.lstatSync(fn); } catch(err){} + if( !stat ) return null; + return stat && stat.isDirectory() ? "Container" : "Resource"; + } + +async getObjectType(fn,request){ + fn = fn.replace( request.protocol+'//','') + let type = await this.itemType(fn,'want_full'); + let exists = await this.itemExists(fn); + if(!type && fn.endsWith('/')) type = "Container" let read=true,write=true; - if( stat ) { + if( exists ) { try { fs.accessSync(fn,fs.constants.R_OK); } @@ -56,16 +63,15 @@ async getObjectType(fn,request){ read: read, write: write, append: write, + control: write, } - let type = ( stat && stat.isDirectory()) ? "Container" : "Resource"; - if(!stat && fn.endsWith('/')) type = "Container" - let exists = await this.itemExists(fn); let item = { mode : mode, exists : exists, isContainer : type==="Container" ? true : false, } - return Promise.resolve( [type,stat,mode,item] ) +// return Promise.resolve( [type,stat,mode,item] ) + return Promise.resolve( item ) } async getResource(pathname,options,objectType){ diff --git a/src/examineRequestedItem.js b/src/examineRequestedItem.js index a95ce42..f28465b 100644 --- a/src/examineRequestedItem.js +++ b/src/examineRequestedItem.js @@ -2,20 +2,17 @@ import libPath from "path"; import Url from "url"; export async function getItem(uri,request){ - const [objectType,objectExists,mode,item] = - await this.perform('GET_ITEM_INFO',uri,request) + const item = await this.perform('GET_ITEM_INFO',uri,request) item.mode = item.mode ? item.mode : {read:true,append:true,write:true}; let pathHandler,url; if (request.protocol.startsWith('file')) { url = Url.format(request.url) - item.rest_prefix = 'file' // item.pathname = Url.fileURLToPath(url) pathHandler = libPath; } else { url = decodeURIComponent(uri) // item.pathname = Url.parse(url).pathname - item.rest_prefix=uri.replace(request.protocol+'//','').replace(/\/.*$/,'') pathHandler = libPath.posix } // item.pathname = url.replace(request.protocol+'//','') ??? @@ -23,7 +20,7 @@ export async function getItem(uri,request){ if( request.method==='DELETE' && item.isContainer){ let files = await this.perform('GET_FILES',item.pathname); files = files.filter(file => !this.isAuxResource(file)) - if (files.length) item.containerNotEmpty = true; + item.containedFiles = files.length; } this.getExtension = (path)=>{ @@ -38,5 +35,28 @@ export async function getItem(uri,request){ if (pathname.includes('\\')) pathname = pathname.replace(/\\/g, '/'); return pathname; } + item.extension = this.getExtension(item.pathname); + item.contentType = this.getContentType(item.extension); + item.patchOnNonTurtle = request.method==='PATCH' && !item.contentType.match('text/turtle'); + item.isAcl = this.extension==='.acl'; + item.folderFileConfusion = false; // TBD + item.isAuxResource = false; // TBD + item.isAcl = false; // TBD return item; } +/* +item = { + mode: { read: true, write: true, append: true, control: true }, + exists: true, + isContainer: true, + pathname: '/home/jeff/Dropbox/Web/solid/solid-rest/2.0.0/test-folder/', + containedFiles: 0, + extension: '', + contentType: 'text/turtle', + patchOnNonTurtle: false, + isAcl: false, + folderFileConfusion: false, + isAuxResource: false +} + +*/ diff --git a/src/handleRequest.js b/src/handleRequest.js index ab81fd4..87b79ae 100644 --- a/src/handleRequest.js +++ b/src/handleRequest.js @@ -8,21 +8,27 @@ const methods = { PATCH : { requiresWrite:1, requiresContentType:1 }, } export async function handleRequest( uri, originalRequest ){ + + // Errors we find in the request + // const request = this.request = await this.getRequest( uri, originalRequest ); if( !request.url || !request.method ) return 400; if( request.slug.endsWith('/') ) return 400; if( request.originMismatch ) return 403; - if( request.invalidPatchContent ) return 400; if( request.unsupportedAcceptFormat ) return 405; + if( request.method==='PATCH' && !this.patch ) return 405; if( request.method==='POST' && !request.headers.link ) return 400; + + // Errors we find by comparing the request & the itemRequested + // const item = this.item = await this.getItem( uri, request ); if( item.folderFileConfusion ) return 400; // can't have both /foo and /foo/ + if( item.patchOnNonRdf ) return 400; if( item.isAuxResource ){ if( item.isAcl ) request.method.requiresControl = true; if( request.method==="POST" ) return 405; } - if( request.method==='DELETE' && item.containerNotEmpty ) return 409; - if( request.method==='PATCH' && !this.patch ) return 405; + if( request.method==='DELETE' && item.containedFiles ) return 409; if( item.mode.control ) item.mode.write=true; // does control imply read? if( item.mode.write ) item.mode.append=true; // does write imply read? const method = methods[request.method]; @@ -38,8 +44,11 @@ export async function handleRequest( uri, originalRequest ){ if ( request.method==='POST' ){ this.item.pathname = await this.generateRandomSlug( this.item.pathname, this.request.slug - ) -} + ) + } + + // Errors from carrying out the request + // if ( request.method==='PUT'||request.method==='PATCH'){ if( item.isContainer ) return 405; let okDir = await this.perform('CREATE_INTERMEDIATE_CONTAINERS'); @@ -48,12 +57,14 @@ export async function handleRequest( uri, originalRequest ){ if( request.method==='DELETE' ){ let del = await this.perform('DELETE_AUX_RESOURCES'); if( !del ) return 500; - if( this.isAccessError(del) ) return 401; } let response = await this.perform(request.method); if( !response ) return 500; - if( this.isPatchConflictError(response) ) return 400; + + // SUCCESS !!! + // return response; + } // ENDS diff --git a/src/performRequestedMethod.js b/src/performRequestedMethod.js index 2d0c2e9..21545e1 100644 --- a/src/performRequestedMethod.js +++ b/src/performRequestedMethod.js @@ -1,17 +1,3 @@ -/* - All calls to the storage plugin happen here. Calls include - * Solid-rest verbs (GET_ITEM_INFO), etc. - * Rest verbs (GET,etc.) - -The **request** object is created in examineRequest.js. It is a munged version of the request recieved with keys, headers, and method names normalized. - -The **item** object is created in examineRequestedItem.js. It contains all information about an item including its type, mode, and other details returned from the storage plugin's item_info method. - -The **headers** object - - -*/ - export default async function perform(method,pathname,arg){ method = method || this.request.method; pathname = pathname || this.item.pathname; @@ -27,6 +13,10 @@ export default async function perform(method,pathname,arg){ return await this.storage.itemExists(pathname); break; + case 'ITEM_TYPE': // Container/Resource + return await this.storage.itemType(pathname); + break; + case 'GET_ITEM_INFO': return await this.storage.getObjectType(pathname,arg) break; @@ -106,7 +96,6 @@ export default async function perform(method,pathname,arg){ const [putStatus,,putHeaders] = await this.storage.putResource( pathname, this.request.body ); - console.log(newContent) return [putStatus,newContent]; break; diff --git a/src/utils/container.js b/src/utils/container.js index 168c8a0..41efc27 100644 --- a/src/utils/container.js +++ b/src/utils/container.js @@ -2,8 +2,6 @@ export default async function containerAsTurtle( pathname, contentsArray ){ const pathSep = this.pathSep; - if(typeof this.storage.container2turtle != "undefined") - return this.storage.container2turtle(pathname,contentsArray) let filenames=contentsArray.filter( item => { if(!item.endsWith('.acl') && !item.endsWith('.meta')){ return item } }) @@ -20,7 +18,8 @@ export default async function containerAsTurtle( pathname, contentsArray ){ for(var i=0;i,\n` diff --git a/src/utils/utils.js b/src/utils/utils.js index 1f9b4d6..34c7fa5 100644 --- a/src/utils/utils.js +++ b/src/utils/utils.js @@ -50,46 +50,28 @@ const linksExt = linkExt.concat('.meta.acl') this.getExtension( o ) === ext ) } - async function getAuxResources (pathname, options,storage) { + async function getAuxResources (pathname) { let linksExists = linksExt.filter(async ext => - await this.storage.itemExists(pathname + ext) + await this.perform('ITEM_EXISTS',pathname + ext) ) const links = linksExists.map( ext => pathname + ext) return links || []; } -// TBD : remove getLinks and isLink, replace in code with isAuxResource, etc. - - function isLink(pathname,options) { - return linkExt.find(ext => this.getExtension(pathname,options) === ext) + async function generateRandomSlug (pathname, slug = uuidv1()) { + let requestUrl = this.mungePath(pathname, slug) + if( this.item.isContainer && !this.request.url.endsWith(this.pathSep) ) + requestUrl = requestUrl + this.pathSep + if( await this.perform('ITEM_EXISTS',requestUrl) ) + { slug=`${uuidv1()}-${slug}` } + return this.mungePath(pathname, slug) } -/** - * getLinks for item - * @param {*} pathname - * @param {*} options - */ -async function getLinks (pathname, options,storage) { - let linksExists = linksExt.filter(async ext => - await storage.getObjectType(pathname + ext,options.request)[1] - ) - const links = linksExists.map( ext => pathname + ext) - return links -} - -async function generateRandomSlug (pathname, slug = uuidv1()) { - let requestUrl = this.mungePath(pathname, slug) - if( this.item.isContainer && !this.request.url.endsWith(this.pathSep) ) - requestUrl = requestUrl + this.pathSep - if( await this.storage.itemExists(requestUrl) ){ slug=`${uuidv1()}-${slug}` } - return this.mungePath(pathname, slug) -} - export { createServerlessPod, getContentType, - isAuxResource, isLink, - getAuxResources, getLinks, + isAuxResource, + getAuxResources, generateRandomSlug, linkExt, linksExt, From 989ca635c7fa2f57111e4884ba307617dc5f5fc6 Mon Sep 17 00:00:00 2001 From: jeff-zucker Date: Tue, 15 Dec 2020 19:52:30 -0800 Subject: [PATCH 05/11] almost there --- plugins/solid-rest-file/src/index.js | 138 +++++++++++++++------------ src/handleResponse.js | 55 ++++++++--- src/index.js | 5 + src/performRequestedMethod.js | 36 ++++--- tests/all.js | 6 +- tests/shouldSucceed.js | 2 + 6 files changed, 150 insertions(+), 92 deletions(-) diff --git a/plugins/solid-rest-file/src/index.js b/plugins/solid-rest-file/src/index.js index a7285ac..915625c 100644 --- a/plugins/solid-rest-file/src/index.js +++ b/plugins/solid-rest-file/src/index.js @@ -2,50 +2,46 @@ const concatStream = require('concat-stream') const Readable = require('stream').Readable const libPath = require("path"); const fs = require("fs-extra"); +const mime = require('mime-types') -class SolidFileStorage { +export default class SolidFileStorage { + + /** + * file system backend for Solid-Rest + * @constructor + * @return {prefix:"file",name:"solid-rest-file-version"} + */ constructor() { this.prefix = "file" - this.name = "solid-rest-file-1.0.0" + this.name = "solid-rest-file-2.0.0" } - _makeStream(text){ - if (typeof text === 'object' && typeof text.stream === 'function') { - return text.stream() - } - let s = new Readable - s.push(text) - s.push(null) - return s; - } - async text (stream) { - return new Promise((resolve, reject) => { - stream = stream || "" - if(typeof stream === "string") return resolve(stream); - stream.pipe(concatStream({ - encoding: 'string' - }, resolve())).catch(e=>{console.log(e); reject()}) - stream.on('error', reject()) - }) -} - async json (stream) { - return text(stream).then(text => JSON.parse(text)) -} - + /** + * check if file exists + * @param {filePath:string} + * @return {boolean} + */ async itemExists(path){ - return fs.existsSync(path); + return await fs.existsSync(path); } + + /** + * check if thing is Container or Resource + * @param {filePath:string} + * @return {null|"Container"|"Resource"} + */ async itemType(path,wantFull){ let stat; - try { stat = fs.lstatSync(fn); } + try { stat = await fs.lstatSync(fn); } catch(err){} if( !stat ) return null; return stat && stat.isDirectory() ? "Container" : "Resource"; } -async getObjectType(fn,request){ - fn = fn.replace( request.protocol+'//','') - let type = await this.itemType(fn,'want_full'); +async getItemInfo(fn,request){ + fn = fn.replace( /^file:\/\//,'') + let mimetype = mime.lookup(fn); // mimetype from ext + let type = await this.itemType(fn); // Container/Resource let exists = await this.itemExists(fn); if(!type && fn.endsWith('/')) type = "Container" let read=true,write=true; @@ -69,23 +65,29 @@ async getObjectType(fn,request){ mode : mode, exists : exists, isContainer : type==="Container" ? true : false, + mimetype : mimetype, } -// return Promise.resolve( [type,stat,mode,item] ) return Promise.resolve( item ) } -async getResource(pathname,options,objectType){ - // const bodyData = await fs.createReadStream(pathname) - const bodyData = await fs.readFile(pathname) - return [ - 200, - bodyData - ] -} + /** + * check if thing is Container or Resource + * @param filePath:string + * @return { status:number, body?:string, header?:object } + */ + async getResource(pathname){ + let mimetype = mime.lookup(pathname); + let bodyData; + try { + bodyData = await fs.readFile(pathname,mime.charset(mimetype)) + } + catch(e) { return false } + return bodyData + } async putResource(pathname,content){ - let successCode = [200]; - let failureCode = [500]; + let successCode = true; + let failureCode = false; return new Promise(async (resolve) => { let writeIt=false if(typeof content==="undefined") content = "" @@ -104,9 +106,9 @@ async putResource(pathname,content){ if(writeIt){ try { await fs.writeFileSync(pathname,content) - return resolve([successCode]) + return resolve(successCode) } - catch(e){ console.log(e); return resolve([failureCode])} + catch(e){ console.log(e); return resolve(failureCode)} } if(!content.pipe && typeof FileReader !="undefined"){ var fileReader = new FileReader(); @@ -116,11 +118,11 @@ async putResource(pathname,content){ ) } fileReader.onloadend = () => { - return resolve([successCode]) + return resolve(successCode) } fileReader.onerror = (err) => { console.log(err); - return resolve([failureCode]) + return resolve(failureCode) } fileReader.readAsArrayBuffer(content); } @@ -128,19 +130,20 @@ async putResource(pathname,content){ content = content || "" content = this._makeStream( content ); content.pipe(fs.createWriteStream(pathname)).on('finish',()=>{ - return resolve( [successCode] ) + return resolve( successCode ) }).on('error', (err) => { console.log(err) - return resolve( [failureCode] ) + return resolve( failureCode ) }) } }) } + async deleteResource(fn){ return new Promise(function(resolve) { fs.unlink( fn, function(err) { if(err) resolve( false ); - else resolve( [200] ); + else resolve( true ); }); }); } @@ -151,27 +154,28 @@ deleteContainer(fn) { if(err) { resolve( false ); } else { - resolve( [200] ); + resolve( true ); } }); }); } -async postContainer(fn,options){ +async postContainer(fn){ fn = fn.replace(/\/$/,''); return new Promise(function(resolve) { if(fs.existsSync(fn)){ - return resolve( [200] ) + return resolve( true ) } fs.mkdirp( fn, {}, (err) => { if(err) { return resolve( false ) } else { - return resolve( [200] ) + return resolve( true ) } }); }); } +// return true on success async makeContainers(pathname){ const foldername = libPath.dirname(pathname) if (!fs.existsSync(foldername)) { @@ -185,9 +189,26 @@ async makeContainers(pathname){ } return Promise.resolve(true) } -async getContainer(pathname) { - return await fs.readdirSync(pathname) -} + + // returns an array of files or false + async getContainer(pathname) { + let files + try { + files = await fs.readdirSync(pathname) + } + catch(e) { return false } + return files; + } + + _makeStream(text){ + if (typeof text === 'object' && typeof text.stream === 'function') { + return text.stream() + } + let s = new Readable + s.push(text) + s.push(null) + return s; + } } @@ -205,12 +226,5 @@ function getParent(url) { return url.substring(0, url.lastIndexOf('/')) + '/' } -module.exports = SolidFileStorage -/* - linux - /home/travis/build/jeff-zucker/solid-rest/test-folder/rest/deep-folder - osx - /Users/travis/build/jeff-zucker/solid-rest/test-folder/rest/deep-folder -*/ diff --git a/src/handleResponse.js b/src/handleResponse.js index dca8164..73f5f8f 100644 --- a/src/handleResponse.js +++ b/src/handleResponse.js @@ -1,20 +1,37 @@ -//import { Response,Headers } from 'cross-fetch'; -import { Response,Headers } from 'node-fetch'; +import { Response,Headers } from 'cross-fetch'; +//import { Response,Headers } from 'node-fetch'; export async function handleResponse(response){ + let wrapHeaders = true; // feed {headers} instead of headers to Response + let finalResponse = { body:"",headers:{} }; + if(typeof response==='object' && response[0]){ + finalResponse.headers.status = response[0]; + finalResponse.body = response[1] || ""; + } + else if(typeof response==='number'){ + wrapHeaders = false; + finalResponse.headers.status=response; // from handleRequest + } + else if(typeof response==='boolean'){ + finalResponse.headers.status = response ? 200 : 500; + } + else if(typeof response==='string'){ + finalResponse.headers.status = 200; + finalResponse.body = response; + } + else if(typeof response==='object'){ + wrapHeaders = false; + finalResponse = response; + } +// console.log(finalResponse) const pathname = this.item.pathname; - const isError = typeof response==='number'; - response = isError ? [response] : response; - let status = response[0]; - let body = response[1] || ""; - let headers = response[2] || {}; -// const headersFromPlugin = this.perform('STORAGE_HEADER_METHOD'); -// if(this.request.method==="PATCH" && status>399 && body){ headers.statusText=body;body=""; } - let name = this.perform('STORAGE_NAME'); + let name = await this.perform('STORAGE_NAME'); const item = this.item; const request = this.request; const fn = this.basename(pathname,item.pathHandler) -// Object.assign(headers,headersFromPlugin); + + + let headers = {}; // our constructed headers // headers.location = headers.url = headers.location || this.response.headers.location @@ -75,17 +92,25 @@ export async function handleResponse(response){ +`; rel="type"` } } - headers.status = parseInt(status) || 500; + for(var k in headers) { if(typeof headers[k]==='undefined') delete headers[k]; } -// console.log('handleResponse1',headers) - headers = (isError || this.request.method==='PATCH') ? headers : {headers:headers} + + // merge headers created above with headers from response, prefer response + Object.assign( headers, finalResponse.headers ); + +//headers = typeof response==='number' || this.request.method==='PATCH' ? headers : {headers} + +headers = wrapHeaders ? {headers} : headers; + +//console.log(headers); + let resp try{ - resp = new Response(body, headers) + resp = new Response( finalResponse.body, headers) } catch(e){console.log(e)} // for(var h of resp.headers.entries()){console.log(1,h)}; //console.log('handleResponse2',resp) diff --git a/src/index.js b/src/index.js index 1c8d8db..d337fef 100644 --- a/src/index.js +++ b/src/index.js @@ -48,6 +48,11 @@ export default class SolidRest { async fetch( uri, options = {} ) { let request = await this.handleRequest(uri,options); return await this.handleResponse(request); +/* + for(var r of [4,"foo",true,false,{body:"x",headers:{status:66}}]){ + await this.handleResponse(r); + } +*/ } async itemExists(pathname){ diff --git a/src/performRequestedMethod.js b/src/performRequestedMethod.js index 21545e1..10d0cbf 100644 --- a/src/performRequestedMethod.js +++ b/src/performRequestedMethod.js @@ -18,7 +18,7 @@ export default async function perform(method,pathname,arg){ break; case 'GET_ITEM_INFO': - return await this.storage.getObjectType(pathname,arg) + return await this.storage.getItemInfo(pathname,arg) break; case 'GET_FILES': @@ -76,28 +76,40 @@ export default async function perform(method,pathname,arg){ break; case 'PATCH': - let [getStatus,oldContent,h] = await this.storage.getResource(pathname) - if(getStatus !== 200) return [getStatus] + // 415 patchOnNonTurtle is handled already in handleRequest.js + let oldContent = await this.storage.getResource(pathname) + oldContent = oldContent && oldContent.body ? oldContent.body : oldContent + if(!oldContent) return false; oldContent = typeof oldContent === 'string' ? oldContent : oldContent.toString() - const contentType = this.getContentType( this.getExtension(pathname) ); - if (contentType !== 'text/turtle') - return [400,"Can not patch : ${pathname} is not a text/turtle file"]; + const contentType=await this.getContentType(this.getExtension(pathname)); let newContent; try { const [patchStatus, newContent] = await this.patch.patchContent( oldContent, contentType, this.request ) - if ( patchStatus !== 200 ) return [ patchStatus, newContent ] - } catch (e) { return [parseInt(e),e] } + if ( patchStatus !== 200 ) { + return { headers: { + status:patchStatus + }}; + } + } catch (e) { + return { headers: { + status:parseInt(e), + statusText:e + }}; + } const status = await this.storage.makeContainers(pathname); - if(!status) return [500] - this.request.body = newContent - const [putStatus,,putHeaders] = await this.storage.putResource( + if(!status) return false; + let putStatus = await this.storage.putResource( pathname, this.request.body ); - return [putStatus,newContent]; + putStatus = putStatus && putStatus.body ? putStatus.body : putStatus + return putStatus break; } + } +// ENDS + diff --git a/tests/all.js b/tests/all.js index 71f560d..f24649b 100644 --- a/tests/all.js +++ b/tests/all.js @@ -314,12 +314,12 @@ if( check.patch ){ res1 = await GET( cfg.file1 ) ok("200 patch sparql insert, delete to existing resource",res.status==200 && testPatch(res1, cfg.resPatchSparql), res1) +/* DROPPING SUPPORT FOR N3 res = await PATCH( cfg.file1,cfg.patchN3_1, 'text/n3' ) res1 = await GET( cfg.file1 ) //console.warn(res1.statusText.toString()) ok("200 patch n3 insert",res.status==200 && testPatch(res1, cfg.resPatchN3_1), res1) -/* NOT WORKING ! res = await PATCH( cfg.file1,cfg.patchN3_3, 'text/n3' ) res1 = await GET( cfg.file1 ) ok("200 patch n3 delete, insert, where",res.status==200 && testPatch(res1, cfg.resPatchN3_2), res1) @@ -358,8 +358,8 @@ if(check.headers && typeof slug !='undefined'){ res = await DELETE( cfg.base ) ok("200 delete container",res.status==200,res) - let skipped = 33 - passes - fails; - console.warn(`${passes}/33 tests passed, ${fails} failed, ${skipped} skipped\n`) + let skipped = 31 - passes - fails; + console.warn(`${passes}/31 tests passed, ${fails} failed, ${skipped} skipped\n`) allfails = allfails + fails } /* =========================================================== */ diff --git a/tests/shouldSucceed.js b/tests/shouldSucceed.js index 5511f24..22feaaa 100644 --- a/tests/shouldSucceed.js +++ b/tests/shouldSucceed.js @@ -62,6 +62,8 @@ console.log('delete'); res = await DELETE( cfg.folder2 ) res = await DELETE( cfg.folder1 ) + + cfg.folder1 = cfg.base+cfg.folder1+'/'; res = await GET( cfg.folder1 ) ok( "delete container", res.status==404,res) From 7cfb0423a6baa881fbd009e8796160913c785b19 Mon Sep 17 00:00:00 2001 From: jeff-zucker Date: Tue, 15 Dec 2020 20:36:28 -0800 Subject: [PATCH 06/11] everything excet n3/text patch --- plugin-template.js | 241 +++++++++++++++++++++++++++ plugins/solid-rest-file/src/index.js | 208 ++++++++++++++--------- src/performRequestedMethod.js | 2 +- 3 files changed, 369 insertions(+), 82 deletions(-) create mode 100644 plugin-template.js diff --git a/plugin-template.js b/plugin-template.js new file mode 100644 index 0000000..deca475 --- /dev/null +++ b/plugin-template.js @@ -0,0 +1,241 @@ + +export default class SolidYOURBACKENDStorage { + + /** + * file system backend for Solid-Rest + * @constructor + * @return {prefix:"file",name:"solid-rest-file-version"} + */ + constructor() { + this.prefix = "YOUR PROTOCOL PREFIX" + this.name = "solid-rest-YOUR_PROTOCOL_PREFIX-YOUR-VERSION" + } + + /** + * check if file exists + * @param filePath + * @return {boolean} + */ + async itemExists(path){ + } + + /** + * check if thing is Container or Resource + * @param filePath + * @return "Container" | "Resource" | null + */ + async itemType(path,wantFull){ + } + + /** + * examine a requested item + * @param filePath, request object + * @return item object + * item = { + * mode : { read:1,append:1,write:1,control:1 } + * exists : await this.itemExists(), + * isContainer : await this.getType()==="Container" ? true : false, + * } + * Note : mode is optional, only provide if you can check permissions + */ + async getItemInfo(fn,request){ + } + + /** + * read a file + * @param filePath + * @return on success : body | Response object + * @return on failure false | Response object + */ + async getResource(pathname){ + let bodyData; + try { + bodyData = await // ... + } + catch(e) { return false } + return bodyData + } + + /** + * write a file + * @param filePath, content + * @return true | Response object on success + * @return false | Response object on failure + */ + async putResource(pathname,content){ + let successCode = true; + let failureCode = false; + return new Promise(async (resolve) => { + let writeIt=false + if(typeof content==="undefined") content = "" + if(typeof content==="string"){ + writeIt=true + } + else if(content.stream){ + content = await content.stream() + content = await content.read() + writeIt=true + } + else if(content.text){ + content = await content.text() + writeIt=true + } + if(writeIt){ + try { + await fs.writeFileSync(pathname,content) + return resolve(successCode) + } + catch(e){ console.log(e); return resolve(failureCode)} + } + if(!content.pipe && typeof FileReader !="undefined"){ + var fileReader = new FileReader(); + fileReader.onload = function() { + fs.writeFileSync(pathname, Buffer.from( + new Uint8Array(this.result)) + ) + } + fileReader.onloadend = () => { + return resolve(successCode) + } + fileReader.onerror = (err) => { + console.log(err); + return resolve(failureCode) + } + fileReader.readAsArrayBuffer(content); + } + else { + content = content || "" + content = this._makeStream( content ); + content.pipe(fs.createWriteStream(pathname)).on('finish',()=>{ + return resolve( successCode ) + }).on('error', (err) => { + console.log(err) + return resolve( failureCode ) + }) + } + }) + } + + /** + * delete file + * @param filePath + * @return true on success, false on failure + */ + async deleteResource(fn){ + return new Promise(function(resolve) { + fs.unlink( fn, function(err) { + if(err) resolve( false ); + else resolve( true ); + }); + }); + } + + /** + * delete folder + * @param filePath + * @return true on success, false on failure + */ + deleteContainer(fn) { + return new Promise(async function(resolve) { + await fs.rmdir( fn, function(err) { + if(err) { + resolve( false ); + } else { + resolve( true ); + } + }); + }); + } + + /** + * create folder + * @param filePath + * @return true on success, false on failure + */ + async postContainer(fn){ + fn = fn.replace(/\/$/,''); + return new Promise(function(resolve) { + if(fs.existsSync(fn)){ + return resolve( true ) + } + fs.mkdirp( fn, {}, (err) => { + if(err) { + return resolve( false ) + } + else { + return resolve( true ) + } + }); + }); + } + + /** + * create parent and intermediate folders + * @param filePath + * @return true on success, false on failure + */ + async makeContainers(pathname){ + const foldername = libPath.dirname(pathname) + if (!fs.existsSync(foldername)) { + try { + fs.mkdirpSync(foldername); + return Promise.resolve(true) + } + catch { + return Promise.resolve(false) + } + } + return Promise.resolve(true) + } + + /** + * read a folder + * @param filePath + * @return on success : a possibly empty array of child fileNames (not paths) + * @return on failure : false + */ + async getContainer(pathname) { + let files + try { + files = await fs.readdirSync(pathname) + } + catch(e) { return false } + return files; + } + + + /** + * creates a ReadableStream + * @param content as text or streamable object + * @return on success : a ReadableStream + * @return on failure : false + */ + _makeStream(text){ + if (typeof text === 'object' && typeof text.stream === 'function') { + return text.stream() + } + let s = new Readable + s.push(text) + s.push(null) + return s; + } + +} // end of SolidRestFile + + /** + * return parent url with / at the end. + * If no parent exists return null + * @param {string} url + * @returns {string|null} + */ + function getParent(url) { + while (url.endsWith('/')) + url = url.slice(0, -1) + if (!url.includes('/')) + return null + return url.substring(0, url.lastIndexOf('/')) + '/' + } + +// ENDS + + diff --git a/plugins/solid-rest-file/src/index.js b/plugins/solid-rest-file/src/index.js index 915625c..04d0203 100644 --- a/plugins/solid-rest-file/src/index.js +++ b/plugins/solid-rest-file/src/index.js @@ -1,35 +1,35 @@ -const concatStream = require('concat-stream') -const Readable = require('stream').Readable -const libPath = require("path"); -const fs = require("fs-extra"); -const mime = require('mime-types') +import concatStream from "concat-stream"; +import {Readable} from "stream"; +import libPath from "path"; +import fs from "fs-extra"; +import mime from "mime-types"; export default class SolidFileStorage { - /** - * file system backend for Solid-Rest - * @constructor - * @return {prefix:"file",name:"solid-rest-file-version"} - */ + /** + * file system backend for Solid-Rest + * @constructor + * @return {prefix:"file",name:"solid-rest-file-version"} + */ constructor() { this.prefix = "file" this.name = "solid-rest-file-2.0.0" } - /** - * check if file exists - * @param {filePath:string} - * @return {boolean} - */ + /** + * check if file exists + * @param filePath + * @return {boolean} + */ async itemExists(path){ return await fs.existsSync(path); } - /** - * check if thing is Container or Resource - * @param {filePath:string} - * @return {null|"Container"|"Resource"} - */ + /** + * check if thing is Container or Resource + * @param filePath + * @return "Container" | "Resource" | null + */ async itemType(path,wantFull){ let stat; try { stat = await fs.lstatSync(fn); } @@ -38,7 +38,12 @@ export default class SolidFileStorage { return stat && stat.isDirectory() ? "Container" : "Resource"; } -async getItemInfo(fn,request){ + /** + * examine a requested item + * @param filePath, request object + * @return item object + */ + async getItemInfo(fn,request){ fn = fn.replace( /^file:\/\//,'') let mimetype = mime.lookup(fn); // mimetype from ext let type = await this.itemType(fn); // Container/Resource @@ -68,13 +73,14 @@ async getItemInfo(fn,request){ mimetype : mimetype, } return Promise.resolve( item ) -} + } - /** - * check if thing is Container or Resource - * @param filePath:string - * @return { status:number, body?:string, header?:object } - */ + /** + * read a file + * @param filePath + * @return on success : body | Response object + * @return on failure false | Response object + */ async getResource(pathname){ let mimetype = mime.lookup(pathname); let bodyData; @@ -85,7 +91,13 @@ async getItemInfo(fn,request){ return bodyData } -async putResource(pathname,content){ + /** + * write a file + * @param filePath, content + * @return true | Response object on success + * @return false | Response object on failure + */ + async putResource(pathname,content){ let successCode = true; let failureCode = false; return new Promise(async (resolve) => { @@ -137,19 +149,29 @@ async putResource(pathname,content){ }) } }) -} + } -async deleteResource(fn){ + /** + * delete file + * @param filePath + * @return true on success, false on failure + */ + async deleteResource(fn){ return new Promise(function(resolve) { - fs.unlink( fn, function(err) { - if(err) resolve( false ); - else resolve( true ); - }); + fs.unlink( fn, function(err) { + if(err) resolve( false ); + else resolve( true ); + }); }); -} + } -deleteContainer(fn) { - return new Promise(async function(resolve) { + /** + * delete folder + * @param filePath + * @return true on success, false on failure + */ + deleteContainer(fn) { + return new Promise(async function(resolve) { await fs.rmdir( fn, function(err) { if(err) { resolve( false ); @@ -158,39 +180,55 @@ deleteContainer(fn) { } }); }); -} -async postContainer(fn){ - fn = fn.replace(/\/$/,''); - return new Promise(function(resolve) { - if(fs.existsSync(fn)){ - return resolve( true ) - } - fs.mkdirp( fn, {}, (err) => { - if(err) { - return resolve( false ) - } - else { + } + + /** + * create folder + * @param filePath + * @return true on success, false on failure + */ + async postContainer(fn){ + fn = fn.replace(/\/$/,''); + return new Promise(function(resolve) { + if(fs.existsSync(fn)){ return resolve( true ) } + fs.mkdirp( fn, {}, (err) => { + if(err) { + return resolve( false ) + } + else { + return resolve( true ) + } + }); }); - }); -} -// return true on success -async makeContainers(pathname){ - const foldername = libPath.dirname(pathname) - if (!fs.existsSync(foldername)) { - try { - fs.mkdirpSync(foldername); - return Promise.resolve(true) - } - catch { - return Promise.resolve(false) + } + + /** + * create parent and intermediate folders + * @param filePath + * @return true on success, false on failure + */ + async makeContainers(pathname){ + const foldername = libPath.dirname(pathname) + if (!fs.existsSync(foldername)) { + try { + fs.mkdirpSync(foldername); + return Promise.resolve(true) + } + catch { + return Promise.resolve(false) + } } + return Promise.resolve(true) } - return Promise.resolve(true) -} - // returns an array of files or false + /** + * read a folder + * @param filePath + * @return on success : a possibly empty array of child fileNames (not paths) + * @return on failure : false + */ async getContainer(pathname) { let files try { @@ -200,6 +238,13 @@ async makeContainers(pathname){ return files; } + + /** + * creates a ReadableStream + * @param content as text or streamable object + * @return on success : a ReadableStream + * @return on failure : false + */ _makeStream(text){ if (typeof text === 'object' && typeof text.stream === 'function') { return text.stream() @@ -208,23 +253,24 @@ async makeContainers(pathname){ s.push(text) s.push(null) return s; - } - -} - -/** - * return parent url with / at the end. - * If no parent exists return null - * @param {string} url - * @returns {string|null} - */ -function getParent(url) { - while (url.endsWith('/')) - url = url.slice(0, -1) - if (!url.includes('/')) - return null - return url.substring(0, url.lastIndexOf('/')) + '/' -} + } + +} // end of SolidRestFile + + /** + * return parent url with / at the end. + * If no parent exists return null + * @param {string} url + * @returns {string|null} + */ + function getParent(url) { + while (url.endsWith('/')) + url = url.slice(0, -1) + if (!url.includes('/')) + return null + return url.substring(0, url.lastIndexOf('/')) + '/' + } +// ENDS diff --git a/src/performRequestedMethod.js b/src/performRequestedMethod.js index 10d0cbf..6d445b4 100644 --- a/src/performRequestedMethod.js +++ b/src/performRequestedMethod.js @@ -82,7 +82,7 @@ export default async function perform(method,pathname,arg){ if(!oldContent) return false; oldContent = typeof oldContent === 'string' ? oldContent : oldContent.toString() - const contentType=await this.getContentType(this.getExtension(pathname)); + const contentType=this.item.contentType; let newContent; try { const [patchStatus, newContent] = await this.patch.patchContent( From eac64c2a28d21b55ecbdf41e68a8ba9db699733a Mon Sep 17 00:00:00 2001 From: jeff-zucker Date: Wed, 16 Dec 2020 12:09:49 -0800 Subject: [PATCH 07/11] cleanup handleResponse --- src/handleResponse.js | 169 +++++++++++++++++----------------- src/performRequestedMethod.js | 2 +- src/utils/container.js | 8 +- 3 files changed, 88 insertions(+), 91 deletions(-) diff --git a/src/handleResponse.js b/src/handleResponse.js index 73f5f8f..bc095b8 100644 --- a/src/handleResponse.js +++ b/src/handleResponse.js @@ -1,16 +1,20 @@ import { Response,Headers } from 'cross-fetch'; -//import { Response,Headers } from 'node-fetch'; export async function handleResponse(response){ - let wrapHeaders = true; // feed {headers} instead of headers to Response - let finalResponse = { body:"",headers:{} }; - if(typeof response==='object' && response[0]){ - finalResponse.headers.status = response[0]; - finalResponse.body = response[1] || ""; - } - else if(typeof response==='number'){ + + let wrapHeaders = true; // {headers} instead of headers for Response + + let finalResponse = { body:"",headers:{} }; // headers from response + + /* We parse the response depending on its type + * number : plugins may send a simple status code + * boolean : or send true on success, false on failure + * object : or send a header and optional body + * string : or, for get requests, send the content + */ + if(typeof response==='number'){ wrapHeaders = false; - finalResponse.headers.status=response; // from handleRequest + finalResponse.headers.status=response; } else if(typeof response==='boolean'){ finalResponse.headers.status = response ? 200 : 500; @@ -23,99 +27,62 @@ export async function handleResponse(response){ wrapHeaders = false; finalResponse = response; } -// console.log(finalResponse) - const pathname = this.item.pathname; - let name = await this.perform('STORAGE_NAME'); - const item = this.item; - const request = this.request; - const fn = this.basename(pathname,item.pathHandler) - - let headers = {}; // our constructed headers + // now we create headers + // if the response already has some of them, those will replace our + // constructed ones later -// headers.location = headers.url = headers.location || this.response.headers.location + let headers = {}; - if(this.response && this.response.headers) - headers.location = this.response.headers.location + const pathname = this.item.pathname; + const item = this.item; + const request = this.request; + const fn = this.basename(pathname,item.pathHandler) - headers.date = headers.date - || new Date(Date.now()).toISOString() + // CONTENT-TYPE + headers['content-type'] = this.item.contentType; - headers.allow = headers.allow - || createAllowHeader(this.patch,this.item.mode) + // LINK + headers.link = headers.link || createLinkHeader(this.item); - let wacAllow = headers['wac-allow'] - || createWacHeader(item.mode) - if( wacAllow ) headers['wac-allow'] = wacAllow; + // ALLOW + headers.allow = createAllowHeader(this.patch,this.item.mode) - headers['x-powered-by'] = headers['x-powered-by'] || - name - const options = {}; - options.item = item; - options.request = request; - const ext = this.getExtension(pathname) + // WAC-ALLOW + headers['wac-allow'] = createWacHeader(this.item.mode) - headers['content-type'] - = headers['content-type'] - || this.getContentType(ext,item.isContainer==='Container'?"Container":"Resource") - if(!headers['content-type']){ - delete headers['content-type'] - } - else { - headers['content-type'] = headers['content-type'].replace(/;.*/,''); - } - - if(this.patch) { - headers['ms-author-via']=["SPARQL"]; - headers['accept-patch']=['application/sparql-update']; - } - headers.link = headers.link; - if( !headers.link ) { - if( ext === '.acl' ) { - headers.link = - `; rel="type"` - } - else if( ext === '.meta' ) { - headers.link = - `<${fn}.acl>; rel="acl",` - +`; rel="type"` - } - else if ( item.isContainer ) { - headers.link = - `<.meta>; rel="describedBy", <.acl>; rel="acl",` - +`; rel="type",` - +`; rel="type"` - } - else { - headers.link = - `<${fn}.meta>; rel="describedBy", <${fn}.acl>; rel="acl",` - +`; rel="type"` - } - } + // DATE + headers.date = headers.date || new Date(Date.now()).toISOString() -for(var k in headers) { - if(typeof headers[k]==='undefined') delete headers[k]; -} + // X-POWERED-BY + headers['x-powered-by'] = headers['x-powered-by'] + || await this.perform('STORAGE_NAME'); + // LOCATION (we pre-populated this in performRequestedMethod.js) + if(this.response && this.response.headers) + headers.location = this.response.headers.location - // merge headers created above with headers from response, prefer response - Object.assign( headers, finalResponse.headers ); + // ACCEPT-PATCH & MS-AUTHOR-VIA + if(this.patch) { + headers['accept-patch']=['application/sparql-update']; + headers['ms-author-via']=["SPARQL"]; + } -//headers = typeof response==='number' || this.request.method==='PATCH' ? headers : {headers} + // Now we merge headers we created with response headers, prefering response + Object.assign( headers, finalResponse.headers ); -headers = wrapHeaders ? {headers} : headers; + // Now we create & return the Response object + headers = wrapHeaders ? {headers} : headers; + let responseObject; + try{ + responseObject = new Response( finalResponse.body, headers) + } catch(e){console.log(e)} + return responseObject; -//console.log(headers); +} // end of handleResponse method - let resp - try{ - resp = new Response( finalResponse.body, headers) - } catch(e){console.log(e)} -// for(var h of resp.headers.entries()){console.log(1,h)}; -//console.log('handleResponse2',resp) - return resp - } // end of getHeaders() +// Utility methods for creating headers function createWacHeader( mode ){ if(!mode.read && !mode.write) return null; @@ -130,3 +97,33 @@ headers = wrapHeaders ? {headers} : headers; + (mode.write ?',POST,PUT,DELETE' : '') + (mode.write && patch ?',PATCH' : '') } + + function createLinkHeader(item) { + let ext = item.extension; + let isContainer = item.isContainer; + let link; + + if( ext === '.acl' ) // .acl not controlledBy or describedBy anything + return `; rel="type"` + + else if( ext === '.meta' ) { + return + `<${fn}.acl>; rel="acl",` // .meta controlledBy .meta.acl + +`; rel="type"` + } + + else if ( isContainer ) { + return + `<.meta>; rel="describedBy", <.acl>; rel="acl",` + +`; rel="type",` + +`; rel="type"` + +`; rel="type"` + } + else { + return + `<${fn}.meta>; rel="describedBy", <${fn}.acl>; rel="acl",` + +`; rel="type"` + } + } + +// THE END! diff --git a/src/performRequestedMethod.js b/src/performRequestedMethod.js index 6d445b4..805a866 100644 --- a/src/performRequestedMethod.js +++ b/src/performRequestedMethod.js @@ -50,7 +50,7 @@ export default async function perform(method,pathname,arg){ case 'OPTIONS': case 'HEAD': - return [200]; + return true; break; case 'PUT': diff --git a/src/utils/container.js b/src/utils/container.js index 41efc27..ff75c8c 100644 --- a/src/utils/container.js +++ b/src/utils/container.js @@ -16,16 +16,16 @@ export default async function containerAsTurtle( pathname, contentsArray ){ if(filenames.length){ str = str + "; ldp:contains\n"; for(var i=0;i,\n` let ctype = this.getContentType(this.getExtension(fn),'Resource') ctype = ctype.replace(/;.*/,'') - ftype = ftype==="Container" ? "ldp:Container; a ldp:BasicContainer" : "ldp:Resource" + ftype = ftype==="Container" + ? "ldp:Container; a ldp:BasicContainer; a ldp:Resource" + : "ldp:Resource" str2 = str2 + `<${fn}> a ${ftype}.\n` str2 = str2 + `<${fn}> a .\n` // str2 = str2 + `<${fn}> :type "${ctype}".\n` @@ -34,6 +34,6 @@ export default async function containerAsTurtle( pathname, contentsArray ){ } str = str + `.\n` + str2 // str = _makeStream(str); - return ([200,str]) + return (str) } From 83e9cae982e6d172df7ddd321129c22e527387eb Mon Sep 17 00:00:00 2001 From: jeff-zucker Date: Fri, 18 Dec 2020 20:19:14 -0800 Subject: [PATCH 08/11] Solid-Rest-Server! --- developer-notes.md | 28 + filemap.txt | 37 + package.json | 1 + plugins/solid-rest-file/package.json | 1 + plugins/solid-rest-file/src/index.js | 64 +- server/data-kitchen.md | 22 + server/myPod/.acl | 23 + server/myPod/.well-known/.meta | 0 server/myPod/data-kitchen.html | 78 + server/myPod/favicon.ico | Bin 0 -> 4286 bytes server/myPod/inbox/.meta | 0 server/myPod/mashlib.html | 144 + server/myPod/org.html | 121 + server/myPod/private/.meta | 0 server/myPod/profile/card.ttl | 32 + server/myPod/public/.meta | 0 server/myPod/scripts/mashlib/browse.html | 70 + server/myPod/scripts/mashlib/databrowser.html | 3 + server/myPod/scripts/mashlib/mash.css | 354 + server/myPod/scripts/mashlib/mash.css.map | 1 + server/myPod/scripts/mashlib/mashlib.js | 143859 +++++++++++++++ server/myPod/scripts/mashlib/mashlib.js.map | 1 + server/myPod/scripts/mashlib/mashlib.min.js | 149 + .../myPod/scripts/mashlib/mashlib.min.js.map | 1 + server/myPod/settings/prefs.ttl | 13 + server/myPod/settings/privateTypeIndex.ttl | 5 + server/myPod/settings/publicTypeIndex.ttl | 12 + server/package-lock.json | 3477 + server/package.json | 18 + server/src/databrowser.html | 121 + server/src/index.js | 82 + src/examineRequest.js | 6 +- src/examineRequestedItem.js | 16 +- src/handleRequest.js | 14 +- src/handleResponse.js | 38 +- src/index.js | 12 +- src/performRequestedMethod.js | 31 +- src/utils/container.js | 2 +- src/utils/createServerlessPod.js | 10 +- src/utils/utils.js | 38 +- tests/all.js | 12 +- 41 files changed, 148812 insertions(+), 84 deletions(-) create mode 100644 developer-notes.md create mode 100644 filemap.txt create mode 100644 server/data-kitchen.md create mode 100644 server/myPod/.acl create mode 100644 server/myPod/.well-known/.meta create mode 100644 server/myPod/data-kitchen.html create mode 100644 server/myPod/favicon.ico create mode 100644 server/myPod/inbox/.meta create mode 100644 server/myPod/mashlib.html create mode 100644 server/myPod/org.html create mode 100644 server/myPod/private/.meta create mode 100644 server/myPod/profile/card.ttl create mode 100644 server/myPod/public/.meta create mode 100644 server/myPod/scripts/mashlib/browse.html create mode 100644 server/myPod/scripts/mashlib/databrowser.html create mode 100644 server/myPod/scripts/mashlib/mash.css create mode 100644 server/myPod/scripts/mashlib/mash.css.map create mode 100644 server/myPod/scripts/mashlib/mashlib.js create mode 100644 server/myPod/scripts/mashlib/mashlib.js.map create mode 100644 server/myPod/scripts/mashlib/mashlib.min.js create mode 100644 server/myPod/scripts/mashlib/mashlib.min.js.map create mode 100644 server/myPod/settings/prefs.ttl create mode 100644 server/myPod/settings/privateTypeIndex.ttl create mode 100644 server/myPod/settings/publicTypeIndex.ttl create mode 100644 server/package-lock.json create mode 100644 server/package.json create mode 100644 server/src/databrowser.html create mode 100644 server/src/index.js diff --git a/developer-notes.md b/developer-notes.md new file mode 100644 index 0000000..13f7661 --- /dev/null +++ b/developer-notes.md @@ -0,0 +1,28 @@ +### A sample SolidRest.request Object + request: { + method: 'DELETE', + headers: {}, + slug: '', + body: '', + url: 'file:///home/jeff/Dropbox/Web/solid/solid-rest/2.0.0/test-folder/', + protocol: 'file:' + }, + response: { + headers: { + location: '/home/jeff/Dropbox/Web/solid/solid-rest/2.0.0/test-folder/rest/e63cabb0-4071-11eb-8a41-4f858c3eae9f-test1.ttl' + } + }, + item: { + mode: { read: true, write: true, append: true, control: true }, + exists: true, + isContainer: true, + mimetype: false, + pathname: '/home/jeff/Dropbox/Web/solid/solid-rest/2.0.0/test-folder/', + containedFiles: 0, + extension: '', + contentType: 'text/turtle', + patchOnNonTurtle: false, + isAcl: false, + folderFileConfusion: false, + isAuxResource: false + } diff --git a/filemap.txt b/filemap.txt new file mode 100644 index 0000000..851b8c4 --- /dev/null +++ b/filemap.txt @@ -0,0 +1,37 @@ +solid-rest/ + README.md + Plugin-Developer.md + tests/ + all.js + shouldSucceed.js + shouldFail.js + src/ + index.js + handleRequest.js + examineRequest.js + examineRequestedItem.js + performRequestedMethod.js + handleResponse.js + utils/ + performPatch.js + containerToTurtle.js + utils.js + createServerlessPod.js + plugins/ + solid-rest-file/ + README.md + src/ + index.js + solid-rest-mem/ + README.md + src/ + index.js + solid-rest-ssh/ + README.md + src/ + index.js + solid-rest-browser/ + README.md + src/ + index.js + diff --git a/package.json b/package.json index a1b6c47..3c6e00c 100644 --- a/package.json +++ b/package.json @@ -2,6 +2,7 @@ "name": "solid-rest", "version": "2.0.0", "author": "Jeff Zucker", + "type":"module", "license": "MIT", "description": "treat any storage as a mini Solid server", "main": "./src/index.js", diff --git a/plugins/solid-rest-file/package.json b/plugins/solid-rest-file/package.json index b9c08ad..d8d8e7d 100644 --- a/plugins/solid-rest-file/package.json +++ b/plugins/solid-rest-file/package.json @@ -1,6 +1,7 @@ { "name": "solid-rest-file", "version": "1.2.0", + "type":"module", "description": "", "main": "src/index.js", "scripts": { diff --git a/plugins/solid-rest-file/src/index.js b/plugins/solid-rest-file/src/index.js index 04d0203..cfb5360 100644 --- a/plugins/solid-rest-file/src/index.js +++ b/plugins/solid-rest-file/src/index.js @@ -5,7 +5,6 @@ import fs from "fs-extra"; import mime from "mime-types"; export default class SolidFileStorage { - /** * file system backend for Solid-Rest * @constructor @@ -30,12 +29,38 @@ export default class SolidFileStorage { * @param filePath * @return "Container" | "Resource" | null */ - async itemType(path,wantFull){ + async itemType(path){ let stat; - try { stat = await fs.lstatSync(fn); } + try { stat = await fs.lstatSync(path); } catch(err){} if( !stat ) return null; - return stat && stat.isDirectory() ? "Container" : "Resource"; + if( stat.isSymbolicLink() ) return null; + if( stat.isDirectory() ) return "Container"; + if( stat.isFile() ) return "Resource"; + return null; + } + + /** + * read a folder + * @param filePath + * @return on success : a possibly empty array of child fileNames (not paths) + * @return on failure : false + */ + async getContainer(pathname) { + let files; + let newFiles = []; + let newFolders = []; + try { + files = await fs.readdirSync(pathname) + for(var f in files){ + let ftype = await this.itemType(pathname+files[f]); + if( ftype==="Resource" ) newFiles.push(files[f]); + if( ftype==="Container" ) newFolders.push(files[f]); + } + } + catch(e) { console.log(e); return false } + newFiles = newFiles.concat(newFolders); + return newFiles; } /** @@ -67,6 +92,8 @@ export default class SolidFileStorage { control: write, } let item = { + fileName : fn, + extension : mime.extension(fn), mode : mode, exists : exists, isContainer : type==="Container" ? true : false, @@ -82,12 +109,13 @@ export default class SolidFileStorage { * @return on failure false | Response object */ async getResource(pathname){ - let mimetype = mime.lookup(pathname); - let bodyData; - try { - bodyData = await fs.readFile(pathname,mime.charset(mimetype)) + let ctype,encoding,bodyData; + try{ + ctype = mime.contentType(pathname); + encoding = ctype.match(/text|application/) ? "string" : null; + bodyData = encoding ? await fs.readFile(pathname,encoding) :await fs.readFile(pathname); } - catch(e) { return false } + catch(e) { console.log("Error"+e); return false } return bodyData } @@ -97,7 +125,7 @@ export default class SolidFileStorage { * @return true | Response object on success * @return false | Response object on failure */ - async putResource(pathname,content){ + async putResource(pathname,content,ctype){ let successCode = true; let failureCode = false; return new Promise(async (resolve) => { @@ -223,22 +251,6 @@ export default class SolidFileStorage { return Promise.resolve(true) } - /** - * read a folder - * @param filePath - * @return on success : a possibly empty array of child fileNames (not paths) - * @return on failure : false - */ - async getContainer(pathname) { - let files - try { - files = await fs.readdirSync(pathname) - } - catch(e) { return false } - return files; - } - - /** * creates a ReadableStream * @param content as text or streamable object diff --git a/server/data-kitchen.md b/server/data-kitchen.md new file mode 100644 index 0000000..78d28af --- /dev/null +++ b/server/data-kitchen.md @@ -0,0 +1,22 @@ + +Data-Kitchen-Browser-Edition + * does not use electron, works in any browser + * handles authenticated fetch to pods on ESS, CSS, NSS + * does not dissconnect on page refresh + * handles file: protocol - access any local file via the Databrowser. + * handles ssh: protocol - access any file on an ssh host via the Databrowser. + * works using Solid-Rest as a proxy server + +Welcome to the Data Kitchen - where you can cook with all your data, no matter where or how it is stored. Data Kitchen gives you access to three kinds of Solid spaces : + + * pods on Solid Servers + * files in your local file system + * files in the cloud + +All these spaces are under *your* control, are accessed through the Databrowser, may be both read and written. + +Connect to as many information spaces as you'd like. These spaces may be a pod on a Solid Server, your local file system, or a file system on a cloud server your have access to. + + Information spaces : + * my local file system + * add an information space diff --git a/server/myPod/.acl b/server/myPod/.acl new file mode 100644 index 0000000..d3c491d --- /dev/null +++ b/server/myPod/.acl @@ -0,0 +1,23 @@ +@prefix acl: . +@prefix foaf: . + +# The homepage is readable by the public +<#public> + a acl:Authorization; + acl:agentClass foaf:Agent; + acl:accessTo <./>; + acl:mode acl:Read. + +# The owner has full access to every resource in their pod. +# Other agents have no access rights, +# unless specifically authorized in other .acl resources. +<#owner> + a acl:Authorization; + acl:agent <./profile/card#me>; + # Set the access to the root storage folder itself + acl:accessTo <./>; + # All resources will inherit this authorization, by default + acl:default <./>; + # The owner has all of the access modes allowed + acl:mode + acl:Read, acl:Write, acl:Control. diff --git a/server/myPod/.well-known/.meta b/server/myPod/.well-known/.meta new file mode 100644 index 0000000..e69de29 diff --git a/server/myPod/data-kitchen.html b/server/myPod/data-kitchen.html new file mode 100644 index 0000000..a0d2ad9 --- /dev/null +++ b/server/myPod/data-kitchen.html @@ -0,0 +1,78 @@ + + + Data Kitchen + + + + + + + + + + + + + + diff --git a/server/myPod/favicon.ico b/server/myPod/favicon.ico new file mode 100644 index 0000000000000000000000000000000000000000..764acb2052a2af5542ac41f436ad5106ad109fa4 GIT binary patch literal 4286 zcmeH}u}%U(5Qc}!QYu?1eGBge>@6?$_7)~yjGeKvw7A5|*zgD>hK?9wL6n39A_*}> zf&~d+fN_4plD%X1SU94E9QoP1o!R+j_I4MDGV;mg2;cOOCE6pR1Cex*Cqn=965ICL z&cLcOz(?o4C@(5F3cmiT9FxDq2}Hc60#i)aK4E4>-8I?B8DrPpbuu@OEMLV>YQ-08uCDV@yN%s!Ho01@M(l&nu8EJBOV^_KEbKSTsfk~y zR2VYZkh5OH>^@jhdrtfo_FKIEUa!ZcQpw7;)Q@}+J7>#5Y@x`MceL;LiifWaW8Gj| zYF9C=`|%gp(;O1&S2>#7bal^TCh$Y+9Bhb|3$P5HHdahQg-;NaVidCGGfQBA95o$)&Kwi literal 0 HcmV?d00001 diff --git a/server/myPod/inbox/.meta b/server/myPod/inbox/.meta new file mode 100644 index 0000000..e69de29 diff --git a/server/myPod/mashlib.html b/server/myPod/mashlib.html new file mode 100644 index 0000000..2413167 --- /dev/null +++ b/server/myPod/mashlib.html @@ -0,0 +1,144 @@ + + + + + + + + + + + + + + + +
+ File Path : + + +
+ + +
+
+
+ + + + + diff --git a/server/myPod/org.html b/server/myPod/org.html new file mode 100644 index 0000000..ba6ec26 --- /dev/null +++ b/server/myPod/org.html @@ -0,0 +1,121 @@ + + + + + + + + + + + + + +
+Data Kitchen : + + + + +
+ + + + + + +
+
URI:
+
+ + + + + diff --git a/server/myPod/private/.meta b/server/myPod/private/.meta new file mode 100644 index 0000000..e69de29 diff --git a/server/myPod/profile/card.ttl b/server/myPod/profile/card.ttl new file mode 100644 index 0000000..e60723f --- /dev/null +++ b/server/myPod/profile/card.ttl @@ -0,0 +1,32 @@ +@prefix : <#>. +@prefix jef: <../>. +@prefix ldp: . +@prefix inbox: <../inbox/>. +@prefix pro: <./>. +@prefix ter: . +@prefix foaf: . +@prefix pim: . +@prefix n2: . +@prefix n3: . +@prefix vcard: . +@prefix sch: . +@prefix n1: . + +pro:card a foaf:PersonalProfileDocument; foaf:maker :me; foaf:primaryTopic :me. + +:me + a sch:Person, foaf:Person; + vcard:fn "Local Solid User"; + vcard:role "software developer"; + n1:trustedApp + [ + n1:mode n1:Append, n1:Control, n1:Read, n1:Write; + n1:origin + ]; + ldp:inbox inbox:; + pim:preferencesFile <../settings/prefs.ttl>; + pim:storage jef:; + ter:account jef:; + ter:privateTypeIndex <../settings/privateTypeIndex.ttl>; + ter:publicTypeIndex <../settings/publicTypeIndex.ttl>; + foaf:name "Local Solid User". diff --git a/server/myPod/public/.meta b/server/myPod/public/.meta new file mode 100644 index 0000000..e69de29 diff --git a/server/myPod/scripts/mashlib/browse.html b/server/myPod/scripts/mashlib/browse.html new file mode 100644 index 0000000..a0a8237 --- /dev/null +++ b/server/myPod/scripts/mashlib/browse.html @@ -0,0 +1,70 @@ + + + + + + + + + + + + Data browser + + + + + + +
+
URI:
+
+ + + + + diff --git a/server/myPod/scripts/mashlib/databrowser.html b/server/myPod/scripts/mashlib/databrowser.html new file mode 100644 index 0000000..757d6b5 --- /dev/null +++ b/server/myPod/scripts/mashlib/databrowser.html @@ -0,0 +1,3 @@ +Solid Data Browser
\ No newline at end of file diff --git a/server/myPod/scripts/mashlib/mash.css b/server/myPod/scripts/mashlib/mash.css new file mode 100644 index 0000000..73e4c45 --- /dev/null +++ b/server/myPod/scripts/mashlib/mash.css @@ -0,0 +1,354 @@ +/*! normalize.css v8.0.1 | MIT License | github.com/necolas/normalize.css */ + +/* Document + ========================================================================== */ + +/** + * 1. Correct the line height in all browsers. + * 2. Prevent adjustments of font size after orientation changes in iOS. + */ + +html { + line-height: 1.15; /* 1 */ + -webkit-text-size-adjust: 100%; /* 2 */ +} + +/* Sections + ========================================================================== */ + +/** + * Remove the margin in all browsers. + */ + +body { + margin: 0; +} + +/** + * Render the `main` element consistently in IE. + */ + +main { + display: block; +} + +/** + * Correct the font size and margin on `h1` elements within `section` and + * `article` contexts in Chrome, Firefox, and Safari. + */ + +h1 { + font-size: 2em; + margin: 0.67em 0; +} + +/* Grouping content + ========================================================================== */ + +/** + * 1. Add the correct box sizing in Firefox. + * 2. Show the overflow in Edge and IE. + */ + +hr { + box-sizing: content-box; /* 1 */ + height: 0; /* 1 */ + overflow: visible; /* 2 */ +} + +/** + * 1. Correct the inheritance and scaling of font size in all browsers. + * 2. Correct the odd `em` font sizing in all browsers. + */ + +pre { + font-family: monospace, monospace; /* 1 */ + font-size: 1em; /* 2 */ +} + +/* Text-level semantics + ========================================================================== */ + +/** + * Remove the gray background on active links in IE 10. + */ + +a { + background-color: transparent; +} + +/** + * 1. Remove the bottom border in Chrome 57- + * 2. Add the correct text decoration in Chrome, Edge, IE, Opera, and Safari. + */ + +abbr[title] { + border-bottom: none; /* 1 */ + text-decoration: underline; /* 2 */ + text-decoration: underline dotted; /* 2 */ +} + +/** + * Add the correct font weight in Chrome, Edge, and Safari. + */ + +b, +strong { + font-weight: bolder; +} + +/** + * 1. Correct the inheritance and scaling of font size in all browsers. + * 2. Correct the odd `em` font sizing in all browsers. + */ + +code, +kbd, +samp { + font-family: monospace, monospace; /* 1 */ + font-size: 1em; /* 2 */ +} + +/** + * Add the correct font size in all browsers. + */ + +small { + font-size: 80%; +} + +/** + * Prevent `sub` and `sup` elements from affecting the line height in + * all browsers. + */ + +sub, +sup { + font-size: 75%; + line-height: 0; + position: relative; + vertical-align: baseline; +} + +sub { + bottom: -0.25em; +} + +sup { + top: -0.5em; +} + +/* Embedded content + ========================================================================== */ + +/** + * Remove the border on images inside links in IE 10. + */ + +img { + border-style: none; +} + +/* Forms + ========================================================================== */ + +/** + * 1. Change the font styles in all browsers. + * 2. Remove the margin in Firefox and Safari. + */ + +button, +input, +optgroup, +select, +textarea { + font-family: inherit; /* 1 */ + font-size: 100%; /* 1 */ + line-height: 1.15; /* 1 */ + margin: 0; /* 2 */ +} + +/** + * Show the overflow in IE. + * 1. Show the overflow in Edge. + */ + +button, +input { /* 1 */ + overflow: visible; +} + +/** + * Remove the inheritance of text transform in Edge, Firefox, and IE. + * 1. Remove the inheritance of text transform in Firefox. + */ + +button, +select { /* 1 */ + text-transform: none; +} + +/** + * Correct the inability to style clickable types in iOS and Safari. + */ + +button, +[type="button"], +[type="reset"], +[type="submit"] { + -webkit-appearance: button; +} + +/** + * Remove the inner border and padding in Firefox. + */ + +button::-moz-focus-inner, +[type="button"]::-moz-focus-inner, +[type="reset"]::-moz-focus-inner, +[type="submit"]::-moz-focus-inner { + border-style: none; + padding: 0; +} + +/** + * Restore the focus styles unset by the previous rule. + */ + +button:-moz-focusring, +[type="button"]:-moz-focusring, +[type="reset"]:-moz-focusring, +[type="submit"]:-moz-focusring { + outline: 1px dotted ButtonText; +} + +/** + * Correct the padding in Firefox. + */ + +fieldset { + padding: 0.35em 0.75em 0.625em; +} + +/** + * 1. Correct the text wrapping in Edge and IE. + * 2. Correct the color inheritance from `fieldset` elements in IE. + * 3. Remove the padding so developers are not caught out when they zero out + * `fieldset` elements in all browsers. + */ + +legend { + box-sizing: border-box; /* 1 */ + color: inherit; /* 2 */ + display: table; /* 1 */ + max-width: 100%; /* 1 */ + padding: 0; /* 3 */ + white-space: normal; /* 1 */ +} + +/** + * Add the correct vertical alignment in Chrome, Firefox, and Opera. + */ + +progress { + vertical-align: baseline; +} + +/** + * Remove the default vertical scrollbar in IE 10+. + */ + +textarea { + overflow: auto; +} + +/** + * 1. Add the correct box sizing in IE 10. + * 2. Remove the padding in IE 10. + */ + +[type="checkbox"], +[type="radio"] { + box-sizing: border-box; /* 1 */ + padding: 0; /* 2 */ +} + +/** + * Correct the cursor style of increment and decrement buttons in Chrome. + */ + +[type="number"]::-webkit-inner-spin-button, +[type="number"]::-webkit-outer-spin-button { + height: auto; +} + +/** + * 1. Correct the odd appearance in Chrome and Safari. + * 2. Correct the outline style in Safari. + */ + +[type="search"] { + -webkit-appearance: textfield; /* 1 */ + outline-offset: -2px; /* 2 */ +} + +/** + * Remove the inner padding in Chrome and Safari on macOS. + */ + +[type="search"]::-webkit-search-decoration { + -webkit-appearance: none; +} + +/** + * 1. Correct the inability to style clickable types in iOS and Safari. + * 2. Change font properties to `inherit` in Safari. + */ + +::-webkit-file-upload-button { + -webkit-appearance: button; /* 1 */ + font: inherit; /* 2 */ +} + +/* Interactive + ========================================================================== */ + +/* + * Add the correct display in Edge, IE 10+, and Firefox. + */ + +details { + display: block; +} + +/* + * Add the correct display in all browsers. + */ + +summary { + display: list-item; +} + +/* Misc + ========================================================================== */ + +/** + * Add the correct display in IE 10+. + */ + +template { + display: none; +} + +/** + * Add the correct display in IE 10. + */ + +[hidden] { + display: none; +} + +img[title="Hide details."]{float:left}body{background-color:white;font-family:sans-serif}.warning{color:red}.selected{background-color:#8F3}.licOkay{background-color:#dfd}strong{font-size:120%;color:#333}div.Outliner{margin-top:2em;padding:0.8em}form#TabulateForm{padding:0.8em}div#addViewForm{padding:0.8em}iframe{background:white}img.pic{max-height:20em}.fetched{background-color:#eeffee}.requested{background-color:yellow}.failed{color:red;background-color:white}.unparseable{background-color:#ffcc00}pre#status{font-size:100%}div.container{border-top:solid 5px black;border-left:solid 5px black;border-bottom:solid 5px black;border-right:solid 5px black;margin-top:0.5em;margin-bottom:0.5em;border-radius:0.75em}div.justification{font-size:100%;padding:0 5px;width:80%;background-color:white;margin-top:0.5em;margin-bottom:0.5em}div.description{font-size:120%;border-top:solid 1px yellow;border-left:solid 1px yellow;border-bottom:solid 1px yellow;border-right:solid 1px yellow;padding:15px;width:100%;background-color:#ffffdd;margin-top:0.5em;margin-bottom:0.5em;margin-left:0.5em;margin-right:0.5em;border-radius:0.75em;position:relative;left:0%}div.premises{font-size:100%;border-top:solid 1px #3399ff;border-left:solid 1px #3399ff;border-bottom:solid 1px #3399ff;border-right:solid 1px #3399ff;padding:0.5px;width:100%;background-color:#ccccff;margin-top:0.5em;margin-bottom:0.5em;margin-left:0.5em;margin-right:0.5em;border-radius:0.75em;position:relative;left:0%}div.socialPane{border-top:solid 1px #777;border-bottom:solid 1px #777;padding-top:0.5em;padding-bottom:0.5em;margin:0}img.foafPic{width:100%;border:none;margin:0;padding:0}div.mildNotice{border:dashed 0.1em #777;margin:1em;padding:1em;width:80%;background-color:#ffe}.friendBox{border-top:solid 0.01em #ccc;margin:0;padding:0.3em}.friendBoxBig{height:20em;border-top:solid 0.01em #202}.socialPane a{color:#3B5998;text-decoration:none;font-weight:bold}.socialPane a:link{color:#3B5998;text-decoration:none;font-weight:bold}.socialPane a:visited{color:#3B5998;text-decoration:none;font-weight:bold}.socialPane a:hover{color:#3B5998;text-decoration:underline;font-weight:bold}.socialPane a:active{color:#888;text-decoration:none}img.foafThumb{height:3em;border:0px;margin:0.1em;padding:0.1em;vertical-align:middle}.friendBox .confirmed{font-weight:bold}table.inputForm{font-size:100%}.mainBlock{background:#fff;color:#000;float:left;width:46%;margin:0;border-left:1px solid #ccc;border-right:1px solid #ccc;border-bottom:1px solid #ccc;padding:0}.navBlock{background-color:#eee;float:left;width:25%;border:0;padding:0.5em;margin:0}.navBlock .navSection{border:solid 0.05em gray;padding:0.5em;border-radius:0.5em}div.socialPane h2{color:#202}div.socialPane h3{color:#202}div.social_linkButton{width:80%;background-color:#fff;border:solid 0.05em #ccc;margin-top:0.1em;margin-bottom:0.1em;padding:0.1em;text-align:center}.answer{font-style:italic;color:#00c;text-decoration:underline}.tip{font-style:normal;color:#333;margin:1em}.task{font-style:normal;color:#333;margin:1em;background-color:#ffe;padding:1em;border-radius:1em}.success{background-color:#efe}.failure{background-color:white;border:0.5em red}div.unknown{display:none}div.yes>div.negative{display:none}div.no>div.affirmative{display:none}div.exceptionPane pre{background-color:#fee}.categoryPane a{color:#3B5998;text-decoration:none;font-weight:bold}.categoryPane a:link{color:#3B5998;text-decoration:none;font-weight:bold}.categoryPane a:visited{color:#3B5998;text-decoration:none;font-weight:bold}.categoryPane a:hover{color:#3B5998;text-decoration:underline;font-weight:bold}.categoryPane a:active{color:#888;text-decoration:none}.categoryBottomClass{background-color:#efe;border:0.1em solid green}.categoryTable{padding-left:2em}.categoryPane{background-color:#f8fff8;padding:0.5em;border-width:0.1em;border-color:#777777;border-radius:1em}.categoryPane a.categoryWhy{color:#ddd}.categoryPane a.categoryWhy:link{color:#ddd;text-decoration:none;font-weight:bold}.categoryPane a.categoryWhy:visited{color:#ddd;text-decoration:none;font-weight:bold}.categoryPane a.categoryWhy:hover{color:#3B5998;text-decoration:underline;font-weight:bold}.categoryPane a.categoryWhy:active{color:#ddd;text-decoration:none}.categoryPane a.categoryWhy{color:grey}.pubsPane{background-color:#F2F6DA;border-width:0.1em;border-color:#777777;border-radius:1em;padding:1em;text-decoration:none;font-weight:bold}.pubsPane h2{margin:0;padding:0}.pubsPane form{padding-left:1em}.pubsRow{margin:0.5em 3em 0.5em 0em;clear:both}.pubsRow input{float:right;width:20em;height:1em}#inpid_book_description{float:right;height:8em;width:17em}.pubsRow button{float:left;height:2em;padding:0.5em;margin:0.5em}.hideit{display:none}.submitRow{clear:both;height:5em}.submitRow button{width:7em;height:100%}#buttonid{display:none}#buttonid.active{display:inline}.CVclass{background-color:LightSkyBlue}div.dataContentPane{border-top:solid 1px black;border-left:solid 1px black;border-bottom:solid 1px #777;border-right:solid 1px #777;padding:0.5em;margin-top:0.5em;margin-bottom:0.5em}.nestedFormula{border-top:solid 1px black;border-left:solid 1px black;border-bottom:solid 1px #777;border-right:solid 1px #777;padding:0.5em;border-radius:0.5em}div.dataContentPane td{padding-left:0.2em;padding-top:0.1em;padding-right:0.2em;padding-bottom:0.05em;vertical-align:top}div.dataContentPane tr{margin-bottom:0.6em;padding-top:1em;padding-bottom:1em}.dataContentPane a{color:#3B5998;text-decoration:none;font-weight:bold}.dataContentPane a:link{color:#3B5998;text-decoration:none;font-weight:bold}.dataContentPane a:visited{color:#3B5998;text-decoration:none;font-weight:bold}.dataContentPane a:hover{color:#3B5998;text-decoration:underline;font-weight:bold}.dataContentPane a:active{color:#888;text-decoration:none}.dataContentPane.embeddedText{white-space:pre-wrap}div.dataContentPane td.pred{min-width:12em}div.dataContentPane td.pred a{color:#444}div.n3Pane{padding:1em;border-top:solid 1px black;border-left:solid 1px black;border-bottom:solid 1px #777;border-right:solid 1px #777;color:#004}.imageView{border:1em white;margin:1em}.n3Pane pre{font-size:120%}.RDFXMLPane pre{font-size:120%}div.RDFXMLPane{padding:1em;border-top:solid 2px black;border-left:solid 2px black;border-bottom:solid 2px #777;border-right:solid 2px #777;color:#440}img.hideTillHover{visibility:hidden}img.hideTillHover:hover{visibility:visible}.hideTillHover img{visibility:hidden}.hideTillHover:hover img{visibility:visible}.hideTillHover a{visibility:hidden}.hideTillHover:hover a{visibility:visible}.hoverControl .hoverControlHide{visibility:hidden}.hoverControl:hover .hoverControlHide{visibility:visible}img.outlineImage{max-height:20em;max-width:30em}img.phoneIcon{border:0;margin-left:1em}table#sources{width:100%}table{border-spacing:0}table{margin:0em}td{font-size:100%;border-left:none;border-top:none;border-right:none;border-bottom:none;margin:0.2em;vertical-align:top}td.pred{padding-left:0.5em}table.results{width:100%}table.results td{font-size:100%;background-color:#fff;border-left:none;border-top:none;border-right:none;border-bottom:none;margin:0.1em;border-right:solid #777 0.1em;border-bottom:solid #777 0.1em;vertical-align:top}table.results th{font-size:100%;background-color:#ddf;border-left:none;border-top:none;border-right:solid #777 0.1em;border-bottom:solid #777 0.1em;margin:0.3em;padding-top:0.5em;padding-right:0.5em;border-right:solid #777 0.1em;border-bottom:solid #777 0.1em;vertical-align:top}.collapse{display:none}.expand{display:block}.nrml{color:black}.info{color:black}.warn{color:black;background-color:#ffd}.eror{color:black;background-color:#fdd}.mesg{color:green}.dbug{color:black;background-color:#ddf}.sortheader{color:black;text-decoration:none;position:relative;border:none}.colclose{float:right;color:#aaa}.sortarrow{float:left;color:#aaa;border:none}table.viewTable{padding:0;margin:0;border-style:none;border-width:0;height:40em;width:100%;border-spacing:0}div.viewTabs{background-color:#fff;padding:0}div.viewWindows{width:100%;height:100%;overflow:auto;margin:0em;padding:0em;border-right:solid #aaa 0.1em;border-left:solid #aaa 0.1em;border-bottom:solid #aaa 0.1em;background-color:#ccc}div.querySelect{background-color:#ccc;width:100%;height:100%;border-left:solid #aaa 0.1em;border-bottom:solid #aaa 0.1em;overflow:auto;margin:0em;padding:0em}td.viewTableData{padding:0em;margin:0em;height:100%;width:80%}td.queryTableData{padding:0em;margin:0em;border-width:0em;height:100%;width:20%;border-style:none}table.viewTable tr{height:100%;margin:0em;padding:0em;border-style:none}a{color:#3B5998;text-decoration:none;cursor:pointer}a.inactive{background-color:#eee;border-right:solid #ddd 0.1em;border-top:solid #aaa 0.1em;border-left:solid #aaa 0.1em;padding-top:0.3em;padding-left:0.8em;padding-right:0.8em;padding-bottom:0em;margin-right:0.1em;color:#99f;text-decoration:none}a.active{background-color:#ccc;border-right:solid #ddd 0.1em;border-top:solid #aaa 0.1em;border-left:solid #aaa 0.1em;padding-top:0.3em;padding-left:0.8em;padding-right:0.8em;padding-bottom:0em;margin-right:0.1em;color:#22f;text-decoration:none}input.tabQueryName{border:solid #aaa 0.1em;width:100%;padding:0em}input.delQueryButton{border:none;color:#c00;background-color:#ccc;cursor:pointer;padding:0em}td.checkboxTD{padding-right:0.5em}.sourceHighlight{background-color:yellow}#MenuBar{padding:0.5em;position:fixed;top:0;bottom:auto;left:0;right:0;background-color:#eee;border:0.1em solid #aaa}#TabulatorStatusWidget{position:fixed;top:0;bottom:auto;left:auto;right:0}div.mapKeyDiv{position:relative;float:right;margin:0.3em;color:#777;background:#fff;border:solid #777 0.1em;padding:0.1em}span.closeQuerySpan{float:right;text-align:right;height:0.1em;overflow:visible}span.openQuerySpan{float:left;overflow:visible;height:0em;text-align:left;position:relative;top:0em;z-index:1}input.textinput{width:100%;border:none;font-size:95%;padding:0em;margin:0}textarea.textinput{border:none}.pendingedit{color:#bbb}td.undetermined{color:gray;font-style:italic}td.undetermined table{color:black;font-style:normal}.outlineMenu{position:absolute;height:10em;background:#FFFFFF none repeat scroll 0%;overflow-x:hidden;overflow-y:auto;border:1px solid}.outlineMenu table{cursor:default;width:100%;text-align:left;padding:5px 5px}.outlineMenu div{overflow:auto;white-space:nowrap}.outlineMenu td{color:#654d6c}.outlineMenu .activeItem{background:#D1C6DA}.outlineMenu input{margin:0.2em}div.bottom-border{border:.2em solid transparent;width:100%}div.bottom-border-active{cursor:copy;border:.2em solid;border-color:#ffa600}.deleteIcon{margin-left:0.1em}.deleteCol{float:right;display:inline}.suggestion_list{background:white;border:1px solid;padding:4px}.suggestion_list ul{padding:0;margin:0;list-style-type:none}.suggestion_list a{text-decoration:none;color:navy}.suggestion_list .selected{background:navy;color:white}.suggestion_list .selected a{color:white}#autosuggest{display:none}div.PhotoContentPane{float:left;width:900px;border:1px solid #AAAAAA;padding:10px}div.PhotoListPanel{float:left;padding:5px;border:1px solid #AAAAAA;width:540px;min-height:300px}div.PhotoInfoPanel{float:left;padding:10px;border:1px solid #AAAAAA;width:300px;text-align:center;margin:0px 0px 10px 10px}div.TagMenu{float:left;padding:10px;border:1px solid #AAAAAA;width:300px;margin:0px 0px 0px 10px;text-align:justify}.tagItem{float:left;padding:2px;margin:2px;cursor:pointer}.tagItem_h{float:left;padding:2px;margin:1px;border:1px solid #DDBB99;background-color:#DDEEFF;cursor:pointer}div.photoItem{float:left;width:100%}div.photoFrame{border-right:1px solid #AAAAAA;width:260px;padding:10px;margin:10px 10px 10px 10px;text-align:center;float:left}img.photoThumbnail{border:1px solid #CCCCCC;margin:auto auto auto auto}.photoListTags{width:200px;margin-top:10px;padding-top:10px;float:left}.photoList_tag{background:transparent url("https://solid.github.io/solid-ui/src/originalIcons/tag_tiny.png") 0px 1px no-repeat;padding:1px 0px 1px 18px;margin-left:5px}.TagMenu_tag{background:transparent url("https://solid.github.io/solid-ui/src/originalIcons/tag_tiny.png") 0px 1px no-repeat;padding:1px 0px 1px 18px;margin-left:5px}div.photoImportContentPane{float:left;padding:0px;width:930px;border:1px solid #AAAAAA;padding:10px}.photoImportTitle{font-size:16px;font-weight:bold}.photoItemPanel{width:260px;height:300px;float:left;padding:10px;border:1px solid #AAAAAA;margin:0px 10px 10px 0px}.photoControlImg{border:0px;cursor:pointer}.photoControlImgInactive{opacity:.5;border:0px}#photoPageInfo{font-family:Arial;font-size:14px;font-weight:bold}.controls{clear:both;text-align:right;margin:15px 15px 0px 0px}.controlButton{margin:0px 0px 0px 10px}div.TagPane{min-width:500px;border:1px solid #AAAAAA;padding:10px}div.TagSemanticsPanel{margin:5px 0px 20px 0px}div.TagSemanticsTable{width:100%;font-family:Arial;font-size:12px}div.AddTagSemantics{margin:50px 0px 10px 0px}.controlSelect{margin:5px;font-family:Arial;font-size:12px}.tagURIInput{margin:5px;font-family:Arial;font-size:12px;width:300px}div.TagPane hr{border:1px solid #AAAAAA}.tableViewPane table th{background-color:#eee;color:black}.tableViewPane table th a{color:#555}.tableViewPane table .selectors td{background-color:#ccc}.tableViewPane table td{border-bottom:1px solid black;border-right:1px solid black}.tableViewPane .toolbar td{border:none}.tableViewPane .sparqlButton{width:16px;height:16px;border:1px solid black}.tableViewPane .sparqlDialog{position:fixed;top:40px;left:100px;width:600px;background:white;border:1px solid black;padding:5px}.tableViewPane .sparqlDialog textarea{width:590px;height:250px}.tableViewPane a{color:#3B5998;text-decoration:none;font-weight:bold}.tableViewPane a:link{color:#3B5998;text-decoration:none;font-weight:bold}.tableViewPane a:visited{color:#3B5998;text-decoration:none;font-weight:bold}.tableViewPane a:hover{color:#3B5998;text-decoration:underline;font-weight:bold}.tableViewPane a:active{color:#888;text-decoration:none}.tableViewPane tr{border-color:#444;padding-left:0.3em;padding-right:0.3em}.inquiry{padding-left:0.2em;color:red;font-family:Arial;font-weight:bold}.formPane a{color:#3B5998;text-decoration:none}.formPane a:link{color:#3B5998;text-decoration:none}.formPane a:visited{color:#3B5998;text-decoration:none}.formPane a:hover{color:#3B5998;font-weight:bold}.formPane a:active{color:#888;text-decoration:none}.footer{border-top:solid 1px rgba(0,0,0,0.2);font-size:0.9em;padding:0.5em 1.5em}.header-banner{box-shadow:0px 1px 4px rgba(0,0,0,0.2);-webkit-box-shadow:0px 1px 4px rgba(0,0,0,0.2);-moz-box-shadow:0px 1px 4px rgba(0,0,0,0.2);-o-box-shadow:0px 1px 4px rgba(0,0,0,0.2);display:flex;padding:0 1.5em;margin-bottom:4px}.header-banner__icon{height:60px;width:66px;width:65.59006px}.header-banner__login{margin-left:auto}.header-banner__login input{margin:0.75em 0 0.75em 0.5em !important;padding:0.5em !important}.header-banner__link{display:block}.header-banner__user-menu{border-left:solid 1px rgba(0,0,0,0.2);margin-left:auto}.header-user-menu__button,.header-user-menu__link{background:none;border:0;color:black;cursor:pointer;display:block;font-family:Arial;font-size:1em;text-align:left;padding:1em;width:100%}.header-user-menu__button:focus,.header-user-menu__button:hover,.header-user-menu__link:focus,.header-user-menu__link:hover{background-color:#eee}.header-user-menu__list{list-style:none;margin:0;padding:0}.header-user-menu__list-item{border-bottom:solid 1px rgba(0,0,0,0.2)}.header-user-menu__list-item:last-child{border:0}.header-user-menu__navigation-menu{background:white;border:solid 1px rgba(0,0,0,0.2);border-right:0;position:absolute;right:0;top:60px;width:200px;z-index:1}.header-user-menu__navigation-menu[aria-hidden='true']{display:none}.header-user-menu__photo{border-radius:50%;background-position:center;background-repeat:no-repeat;background-size:cover;margin:5px;height:50px;width:50px}.header-user-menu__trigger{background:none;border:0;cursor:pointer;width:60px;height:60px}.header-user-menu__trigger img{border-radius:50%;height:56px;width:56px}html,body{height:100%}.db-layout{display:flex;flex-direction:column}.db-layout__content{flex:1 0 auto}.db-layout__footer,.db-layout__header{flex-shrink:0}body{font-family:sans-serif}strong{font-weight:bold} + + +/*# sourceMappingURL=mash.css.map*/ \ No newline at end of file diff --git a/server/myPod/scripts/mashlib/mash.css.map b/server/myPod/scripts/mashlib/mash.css.map new file mode 100644 index 0000000..7c87b70 --- /dev/null +++ b/server/myPod/scripts/mashlib/mash.css.map @@ -0,0 +1 @@ +{"version":3,"sources":["webpack://Mashlib/./node_modules/normalize.css/normalize.css","webpack://Mashlib/./src/styles/common.scss","webpack://Mashlib/./src/styles/footer.scss","webpack://Mashlib/./src/styles/_colors.scss","webpack://Mashlib/./src/styles/_mixin.scss","webpack://Mashlib/./src/styles/header.scss","webpack://Mashlib/./src/styles/layout.scss","webpack://Mashlib/./src/styles/index.scss"],"names":[],"mappings":"AAAA,2EAA2E;;AAE3E;+EAC+E;;AAE/E;;;EAGE;;AAEF;EACE,iBAAiB,EAAE,MAAM;EACzB,8BAA8B,EAAE,MAAM;AACxC;;AAEA;+EAC+E;;AAE/E;;EAEE;;AAEF;EACE,SAAS;AACX;;AAEA;;EAEE;;AAEF;EACE,cAAc;AAChB;;AAEA;;;EAGE;;AAEF;EACE,cAAc;EACd,gBAAgB;AAClB;;AAEA;+EAC+E;;AAE/E;;;EAGE;;AAEF;EACE,uBAAuB,EAAE,MAAM;EAC/B,SAAS,EAAE,MAAM;EACjB,iBAAiB,EAAE,MAAM;AAC3B;;AAEA;;;EAGE;;AA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AAe,CACf,UAjGY,CAkGZ,WAlGY,CA6Fb,+BAOG,iBAAkB,CAClB,WAAwB,CACxB,UAAuB,CACxB,UCrGH,WAAY,CACb,WAGC,YAAa,CACb,qBAAsB,CAEtB,oBACE,aAAc,CACf,sCAIC,aAAc,CCNlB,KACE,sBAAuB,CACxB,OAGC,gBAAiB","file":"mash.css","sourcesContent":["/*! normalize.css v8.0.1 | MIT License | github.com/necolas/normalize.css */\n\n/* Document\n ========================================================================== */\n\n/**\n * 1. Correct the line height in all browsers.\n * 2. Prevent adjustments of font size after orientation changes in iOS.\n */\n\nhtml {\n line-height: 1.15; /* 1 */\n -webkit-text-size-adjust: 100%; /* 2 */\n}\n\n/* Sections\n ========================================================================== */\n\n/**\n * Remove the margin in all browsers.\n */\n\nbody {\n margin: 0;\n}\n\n/**\n * Render the `main` element consistently in IE.\n */\n\nmain {\n display: block;\n}\n\n/**\n * Correct the font size and margin on `h1` elements within `section` and\n * `article` contexts in Chrome, Firefox, and Safari.\n */\n\nh1 {\n font-size: 2em;\n margin: 0.67em 0;\n}\n\n/* Grouping content\n ========================================================================== */\n\n/**\n * 1. Add the correct box sizing in Firefox.\n * 2. Show the overflow in Edge and IE.\n */\n\nhr {\n box-sizing: content-box; /* 1 */\n height: 0; /* 1 */\n overflow: visible; /* 2 */\n}\n\n/**\n * 1. Correct the inheritance and scaling of font size in all browsers.\n * 2. Correct the odd `em` font sizing in all browsers.\n */\n\npre {\n font-family: monospace, monospace; /* 1 */\n font-size: 1em; /* 2 */\n}\n\n/* Text-level semantics\n ========================================================================== */\n\n/**\n * Remove the gray background on active links in IE 10.\n */\n\na {\n background-color: transparent;\n}\n\n/**\n * 1. Remove the bottom border in Chrome 57-\n * 2. Add the correct text decoration in Chrome, Edge, IE, Opera, and Safari.\n */\n\nabbr[title] {\n border-bottom: none; /* 1 */\n text-decoration: underline; /* 2 */\n text-decoration: underline dotted; /* 2 */\n}\n\n/**\n * Add the correct font weight in Chrome, Edge, and Safari.\n */\n\nb,\nstrong {\n font-weight: bolder;\n}\n\n/**\n * 1. Correct the inheritance and scaling of font size in all browsers.\n * 2. Correct the odd `em` font sizing in all browsers.\n */\n\ncode,\nkbd,\nsamp {\n font-family: monospace, monospace; /* 1 */\n font-size: 1em; /* 2 */\n}\n\n/**\n * Add the correct font size in all browsers.\n */\n\nsmall {\n font-size: 80%;\n}\n\n/**\n * Prevent `sub` and `sup` elements from affecting the line height in\n * all browsers.\n */\n\nsub,\nsup {\n font-size: 75%;\n line-height: 0;\n position: relative;\n vertical-align: baseline;\n}\n\nsub {\n bottom: -0.25em;\n}\n\nsup {\n top: -0.5em;\n}\n\n/* Embedded content\n ========================================================================== */\n\n/**\n * Remove the border on images inside links in IE 10.\n */\n\nimg {\n border-style: none;\n}\n\n/* Forms\n ========================================================================== */\n\n/**\n * 1. Change the font styles in all browsers.\n * 2. Remove the margin in Firefox and Safari.\n */\n\nbutton,\ninput,\noptgroup,\nselect,\ntextarea {\n font-family: inherit; /* 1 */\n font-size: 100%; /* 1 */\n line-height: 1.15; /* 1 */\n margin: 0; /* 2 */\n}\n\n/**\n * Show the overflow in IE.\n * 1. Show the overflow in Edge.\n */\n\nbutton,\ninput { /* 1 */\n overflow: visible;\n}\n\n/**\n * Remove the inheritance of text transform in Edge, Firefox, and IE.\n * 1. Remove the inheritance of text transform in Firefox.\n */\n\nbutton,\nselect { /* 1 */\n text-transform: none;\n}\n\n/**\n * Correct the inability to style clickable types in iOS and Safari.\n */\n\nbutton,\n[type=\"button\"],\n[type=\"reset\"],\n[type=\"submit\"] {\n -webkit-appearance: button;\n}\n\n/**\n * Remove the inner border and padding in Firefox.\n */\n\nbutton::-moz-focus-inner,\n[type=\"button\"]::-moz-focus-inner,\n[type=\"reset\"]::-moz-focus-inner,\n[type=\"submit\"]::-moz-focus-inner {\n border-style: none;\n padding: 0;\n}\n\n/**\n * Restore the focus styles unset by the previous rule.\n */\n\nbutton:-moz-focusring,\n[type=\"button\"]:-moz-focusring,\n[type=\"reset\"]:-moz-focusring,\n[type=\"submit\"]:-moz-focusring {\n outline: 1px dotted ButtonText;\n}\n\n/**\n * Correct the padding in Firefox.\n */\n\nfieldset {\n padding: 0.35em 0.75em 0.625em;\n}\n\n/**\n * 1. Correct the text wrapping in Edge and IE.\n * 2. Correct the color inheritance from `fieldset` elements in IE.\n * 3. Remove the padding so developers are not caught out when they zero out\n * `fieldset` elements in all browsers.\n */\n\nlegend {\n box-sizing: border-box; /* 1 */\n color: inherit; /* 2 */\n display: table; /* 1 */\n max-width: 100%; /* 1 */\n padding: 0; /* 3 */\n white-space: normal; /* 1 */\n}\n\n/**\n * Add the correct vertical alignment in Chrome, Firefox, and Opera.\n */\n\nprogress {\n vertical-align: baseline;\n}\n\n/**\n * Remove the default vertical scrollbar in IE 10+.\n */\n\ntextarea {\n overflow: auto;\n}\n\n/**\n * 1. Add the correct box sizing in IE 10.\n * 2. Remove the padding in IE 10.\n */\n\n[type=\"checkbox\"],\n[type=\"radio\"] {\n box-sizing: border-box; /* 1 */\n padding: 0; /* 2 */\n}\n\n/**\n * Correct the cursor style of increment and decrement buttons in Chrome.\n */\n\n[type=\"number\"]::-webkit-inner-spin-button,\n[type=\"number\"]::-webkit-outer-spin-button {\n height: auto;\n}\n\n/**\n * 1. Correct the odd appearance in Chrome and Safari.\n * 2. Correct the outline style in Safari.\n */\n\n[type=\"search\"] {\n -webkit-appearance: textfield; /* 1 */\n outline-offset: -2px; /* 2 */\n}\n\n/**\n * Remove the inner padding in Chrome and Safari on macOS.\n */\n\n[type=\"search\"]::-webkit-search-decoration {\n -webkit-appearance: none;\n}\n\n/**\n * 1. Correct the inability to style clickable types in iOS and Safari.\n * 2. Change font properties to `inherit` in Safari.\n */\n\n::-webkit-file-upload-button {\n -webkit-appearance: button; /* 1 */\n font: inherit; /* 2 */\n}\n\n/* Interactive\n ========================================================================== */\n\n/*\n * Add the correct display in Edge, IE 10+, and Firefox.\n */\n\ndetails {\n display: block;\n}\n\n/*\n * Add the correct display in all browsers.\n */\n\nsummary {\n display: list-item;\n}\n\n/* Misc\n ========================================================================== */\n\n/**\n * Add the correct display in IE 10+.\n */\n\ntemplate {\n display: none;\n}\n\n/**\n * Add the correct display in IE 10.\n */\n\n[hidden] {\n display: none;\n}\n","/* Some common style for the Solid Data Browser\n**\n**\n** Do NOT use physical measures, but font-relative measures.\n** 2006-10-21 timbl converted px to em at approx 1em = 12px\n**\n*/\n\n/* If you need style in a pane, insert it in the dom (2016)*/\n\n/* I couldn't find the code for the collapse image. this is a quick work around\nto make the collapsing easier to use ( the triangles dont jump 20 pixels). ~cm2\n*/\nimg[title=\"Hide details.\"]{\n float:left;\n}\nbody {background-color: white ; font-family: sans-serif} /* was: font-size: 80%; */\n\n.warning { color: red; }\n.selected {background-color: #8F3}\n\n.licOkay {background-color: #dfd}\n\n/*\n** other potential colors for CC:\n** #C4FF55. \"faded\" version of CC\n** #486d00, actual CC\n** #ccff99, mit page color\n*/\n\nstrong { font-size: 120%; color: #333 }\ndiv.Outliner { margin-top: 2em; padding: 0.8em; }\nform#TabulateForm { padding: 0.8em }\ndiv#addViewForm { padding: 0.8em }\niframe { background: white }\n\n/* Map */\n\nimg.pic { max-height: 20em }\n\n/* Sources */\n\n.fetched { background-color: #eeffee }\n.requested { background-color: yellow }\n.failed { color: red; background-color: white }\n.unparseable { background-color: #ffcc00; }\n\npre#status { font-size: 100% }\n\n/* Panes */\n/*\ntd.internal { }\n\n/* Moved into code:\ndiv.internalPane { background-color: #ddddff; padding: 0.5em;\n border-radius: 1em; border-radius: .4em; }\n\ndiv.instancePane {\n border-top: solid 1px #777; border-bottom: solid 1px #777;\n margin-top: 0.5em; margin-bottom: 0.5em }\n*/\n/* ***************** For the Justification UI Panes **********/\n\ndiv.container {\n border-top: solid 5px black;\n border-left: solid 5px black;\n border-bottom: solid 5px black;\n border-right: solid 5px black;\n margin-top: 0.5em;\n margin-bottom: 0.5em;\n border-radius: 0.75em;\n}\n/*\ndiv.nonCompliantPane {\n border-top: solid 1px red;\n border-left: solid 1px red;\n border-bottom: solid 1px red;\n border-right: solid 1px red;\n padding: 0.5em;\n background-color: #fbf0f7;\n margin-top: 0.5em; margin-bottom: 0.5em;\n border-radius: 1em;\n}\n\ndiv.compliantPane {\n border-top: solid 1px green;\n border-left: solid 1px green;\n border-bottom: solid 1px green;\n border-right: solid 1px green;\n padding: 0.5em;\n background-color: #def8e0;\n margin-top: 0.5em; margin-bottom: 0.5em;\n border-radius: 1em;\n}\n*/\ndiv.justification {\n font-size: 100%;\n padding: 0 5px;\n width: 80%; /* @@ Don't use pixels -- use em */\n background-color: white;\n margin-top: 0.5em; margin-bottom: 0.5em;\n}\n\n\ndiv.description {\n font-size: 120%;\n border-top: solid 1px yellow;\n border-left: solid 1px yellow;\n border-bottom: solid 1px yellow;\n border-right: solid 1px yellow;\n padding: 15px;\n width: 100%;\n background-color: #ffffdd;\n margin-top: 0.5em;\n margin-bottom: 0.5em;\n margin-left: 0.5em;\n margin-right: 0.5em;\n border-radius: 0.75em;\n position:relative;\n left:0%\n}\n\ndiv.premises {\n font-size: 100%;\n border-top: solid 1px #3399ff;\n border-left: solid 1px #3399ff;\n border-bottom: solid 1px #3399ff;\n border-right: solid 1px #3399ff;\n padding: 0.5px;\n width: 100%;\n background-color: #ccccff;\n margin-top: 0.5em;\n margin-bottom: 0.5em;\n margin-left: 0.5em;\n margin-right: 0.5em;\n border-radius: 0.75em;\n position:relative;\n left:0% /*May be we could shift the left margin a bit?*/\n}\n\n/* ***************** Social Pane **********/\n\ndiv.socialPane {\n border-top: solid 1px #777; border-bottom: solid 1px #777;\n padding-top: 0.5em; padding-bottom: 0.5em;\n margin: 0 }\n\nimg.foafPic { width: 100% ; border: none; margin: 0; padding: 0;\n /*float:right; */}\n\n\ndiv.mildNotice {\n border: dashed 0.1em #777; margin: 1em; padding: 1em;\n width: 80%; /* float: right; */\n background-color: #ffe; }\n\n.friendBox { /* height: 4em; */ border-top: solid 0.01em #ccc; margin: 0; padding: 0.3em;\n /* float: left; */}\n.friendBoxBig { height: 20em; border-top: solid 0.01em #202; /* float: left; */}\n\n.socialPane a { color: #3B5998; text-decoration: none; font-weight: bold}\n.socialPane a:link { color: #3B5998; text-decoration: none; font-weight: bold}\n.socialPane a:visited { color: #3B5998; text-decoration: none; font-weight: bold}\n.socialPane a:hover { color: #3B5998; text-decoration: underline; font-weight: bold}\n.socialPane a:active { color: #888; text-decoration: none; }\n\nimg.foafThumb { height: 3em ; border: 0px; margin: 0.1em; padding: 0.1em;\n vertical-align: middle;\n} /* Thumbnail of a fiend etc */\n\n.friendBox .confirmed { font-weight: bold; }\n\ntable.inputForm { font-size: 100% }\n\n.mainBlock {\n background: #fff;\n color: #000;\n float: left;\n width: 46%;\n margin: 0;\n border-left: 1px solid #ccc;\n border-right: 1px solid #ccc;\n border-bottom: 1px solid #ccc;\n padding: 0;\n}\n\n.navBlock {\n background-color: #eee;\n float: left;\n width: 25%;\n border: 0;\n padding: 0.5em;\n margin: 0;\n}\n\n.navBlock .navSection {\n border: solid 0.05em gray;\n padding: 0.5em;\n border-radius: 0.5em; /* CSS3: border-radius: .4em; */\n}\n\ndiv.socialPane h2 { color: #202 }\ndiv.socialPane h3 { color: #202 }\n\ndiv.social_linkButton {\n width: 80%;\n background-color: #fff;\n border: solid 0.05em #ccc;\n margin-top: 0.1em; margin-bottom: 0.1em;\n padding: 0.1em;\n text-align: center;\n}\n\n/* For question-and-answer stuff for new web id but quite reusable.\n*/\n.answer { font-style: italic; color: #00c; text-decoration: underline; }\n.tip { font-style: normal; color: #333; margin: 1em;}\n.task { font-style: normal; color: #333; margin: 1em;\n background-color: #ffe; padding: 1em;\n border-radius: 1em; /* CSS3: border-radius: 1em; */\n}\n.success {background-color: #efe }\n.failure {background-color: white ; border: 0.5em red}\ndiv.unknown { display:none }\ndiv.yes > div.negative { display: none }\ndiv.no > div.affirmative { display: none }\n\n/******************* Exception Pane ********\n**\n** A pane created when the loading of a pane\n** throws an exception\n**/\n\ndiv.exceptionPane pre { background-color: #fee; }\n\n\n\n/******************* Category Pane *********/\n\n.categoryPane a { color: #3B5998; text-decoration: none; font-weight: bold}\n.categoryPane a:link { color: #3B5998; text-decoration: none; font-weight: bold}\n.categoryPane a:visited { color: #3B5998; text-decoration: none; font-weight: bold}\n.categoryPane a:hover { color: #3B5998; text-decoration: underline; font-weight: bold}\n.categoryPane a:active { color: #888; text-decoration: none; }\n\n.categoryBottomClass { background-color: #efe ; border: 0.1em solid green }\n\n.categoryTable { padding-left: 2em;}\n.categoryPane { background-color: #f8fff8; padding: 0.5em;\n border-width: 0.1em; border-color: #777777;\n border-radius: 1em; /* CSS3: border-radius: .4em; */ }\n\n.categoryPane a.categoryWhy { color: #ddd}\n.categoryPane a.categoryWhy:link { color: #ddd; text-decoration: none; font-weight: bold}\n.categoryPane a.categoryWhy:visited { color: #ddd; text-decoration: none; font-weight: bold}\n.categoryPane a.categoryWhy:hover { color: #3B5998; text-decoration: underline; font-weight: bold}\n.categoryPane a.categoryWhy:active { color: #ddd; text-decoration: none; }\n\n.categoryPane a.categoryWhy { color:grey }\n/* a.categoryWhy:hover { color: #3B5998 } */\n\n\n/******************* PubsPane *********/\n\n.pubsPane {\n background-color: #F2F6DA;\n border-width: 0.1em;\n border-color: #777777;\n border-radius: 1em; /* CSS3: border-radius: .4em; */\n padding: 1em;\n\n text-decoration: none;\n font-weight: bold;\n}\n\n.pubsPane h2 {\n margin: 0;\n padding: 0;\n}\n\n.pubsPane form {\n padding-left: 1em;\n}\n\n/*Clear both - start things on individula lines */\n.pubsRow {\n margin: 0.5em 3em 0.5em 0em;\n clear: both;\n}\n\n/*inputs float right to line up */\n.pubsRow input {\n float: right;\n width: 20em;\n height: 1em;\n}\n#inpid_book_description {\n float: right;\n height: 8em;\n width: 17em;\n}\n\n.pubsRow button {\n float: left;\n height: 2em;\n padding: 0.5em;\n margin: 0.5em;\n}\n\n.hideit\n{\n display: none;\n}\n\n.active {\n /* display: visible; */\n}\n\n.submitRow {\n clear: both;\n height: 5em;\n}\n\n.submitRow button {\n width: 7em;\n height: 100%;\n}\n\n#buttonid {\n display: none;\n}\n\n#buttonid.active{\n display: inline;\n}\n\n\n\n\n/******************* CV Pane *****************/\n\n.CVclass {\n background-color: LightSkyBlue;\n}\n\n/******************* Data Content Pane *****************/\n\ndiv.dataContentPane {\n border-top: solid 1px black;\n border-left: solid 1px black;\n border-bottom: solid 1px #777;\n border-right: solid 1px #777;\n padding: 0.5em; /* color: #404; */\n margin-top: 0.5em; margin-bottom: 0.5em;\n}\n\n.nestedFormula {\n border-top: solid 1px black;\n border-left: solid 1px black;\n border-bottom: solid 1px #777;\n border-right: solid 1px #777;\n padding: 0.5em;\n border-radius: 0.5em;\n}\n\ndiv.dataContentPane td {\n padding-left: 0.2em;\n padding-top: 0.1em;\n padding-right: 0.2em;\n padding-bottom: 0.05em;\n /*\t vertical-align: middle; /*@@ Lalana's request*/\n vertical-align: top; /*@@ Tims's request*/\n /* With middel, you can't tell what is with what */\n /* background-color: white; */\n}\n\ndiv.dataContentPane tr {\n margin-bottom: 0.6em;\n padding-top: 1em;\n padding-bottom: 1em;\n\n}\n\n.dataContentPane a { color: #3B5998; text-decoration: none; font-weight: bold}\n.dataContentPane a:link { color: #3B5998; text-decoration: none; font-weight: bold}\n.dataContentPane a:visited { color: #3B5998; text-decoration: none; font-weight: bold}\n.dataContentPane a:hover { color: #3B5998; text-decoration: underline; font-weight: bold}\n.dataContentPane a:active { color: #888; text-decoration: none; }\n\n.dataContentPane.embeddedText { white-space: pre-wrap;}\n.dataContentPane.embeddedXHTML {}\n\n/* div.dataContentPane a { text-decoration: none; color: #006} /* Only very slightly blue */\ndiv.dataContentPane td.pred { min-width: 12em } /* Keep aligned with others better */\ndiv.dataContentPane td.pred a { color: #444 } /* Greyish as form field names have less info value */\n\n/* .collectionAsTables {border-right: green 1px; margin: 0.2em;} */\n\n\n\ndiv.n3Pane {\n padding: 1em;\n border-top: solid 1px black;\n border-left: solid 1px black;\n border-bottom: solid 1px #777;\n border-right: solid 1px #777;\n color: #004;\n}\n\n.imageView { border: 1em white; margin: 1em; }\n\n.n3Pane pre { font-size: 120%; }\ndiv.n3Pane { }\n\n.RDFXMLPane pre { font-size: 120%; }\ndiv.RDFXMLPane { }\n\ndiv.RDFXMLPane {\n padding: 1em;\n border-top: solid 2px black;\n border-left: solid 2px black;\n border-bottom: solid 2px #777;\n border-right: solid 2px #777;\n color: #440;\n}\n\n/* Generic things useful anywhere */\n\n\nimg.hideTillHover {\n visibility:hidden;\n}\nimg.hideTillHover:hover {\n visibility:visible;\n}\n.hideTillHover img{\n visibility:hidden;\n}\n.hideTillHover:hover img {\n visibility:visible;\n}\n.hideTillHover a{\n visibility:hidden;\n}\n.hideTillHover:hover a {\n visibility:visible;\n}\n.hoverControl .hoverControlHide{\n visibility:hidden;\n}\n.hoverControl:hover .hoverControlHide {\n visibility:visible;\n}\n\n\n/* Pane icons: */\n\n/*\n.hoverControl .paneShown{ border-radius: 0.5em;\n border-top: solid #222 1px;\n border-left: solid #222 0.1em; border-bottom: solid #eee 0.1em;\n border-right: solid #eee 0.1em;\n margin-left: 1em; padding: 3px;\n background-color: #ffd;\n visibility: hidden;}\n\n.hoverControl:hover .paneShown{ border-radius: 0.5em;\n border-top: solid #222 1px;\n border-left: solid #222 0.1em; border-bottom: solid #eee 0.1em;\n border-right: solid #eee 0.1em;\n margin-left: 1em; padding: 3px;\n background-color: #ffd;\n visibility:visible; }\n\n.paneHidden { border-radius: 0.5em; margin-left: 1em; padding: 3px}\n\n.hoverControl .paneHidden { border-radius: 0.5em; margin-left: 1em; padding: 3px; visibility:hidden;}\n.hoverControl:hover .paneHidden { border-radius: 0.5em; margin-left: 1em; padding: 3px; visibility:visible; }\n*/\n\n\n\n/* outline object view */\nimg.outlineImage { max-height: 20em; max-width: 30em } /* save vertical space */\n/* Compare facebook which only limits width -> lots of tall images! */\n\nimg.phoneIcon { border: 0; margin-left: 1em}\n\ntable#sources { width: 100% }\n\ntable { border-spacing: 0}\n\ntable { margin: 0em }\n\ntd { font-size: 100%;\n border-left: none;\n border-top: none;\n border-right: none;\n border-bottom: none;\n margin: 0.2em;\n /* border-right: solid purple 0.1em ;\n border-bottom: solid purple 0.1em;\n */\n vertical-align: top;\n /* display: compact; Causes console errors in ffox */\n}\n\ntd.pred { padding-left: 0.5em }\n/*td.optButton { display: none }\ntr[parentOfSelected] > td.pred td.optButton { display: block }\n*/\n\ntable.results { width: 100% }\n\ntable.results td { font-size: 100%;\n background-color:#fff;\n border-left: none;\n border-top: none;\n border-right: none;\n border-bottom: none;\n margin: 0.1em;\n border-right: solid #777 0.1em ;\n border-bottom: solid #777 0.1em;\n\n vertical-align: top }\n\n\ntable.results th { font-size: 100%;\n background-color: #ddf;\n border-left: none;\n border-top: none;\n border-right: solid #777 0.1em;\n border-bottom: solid #777 0.1em;\n margin: 0.3em;\n padding-top: 0.5em; padding-right: 0.5em;\n border-right: solid #777 0.1em ;\n border-bottom: solid #777 0.1em;\n\n vertical-align: top }\n\n/* Hide sections of the display.\nCollpase not actually in CSS1 except for table row and col.\nSupposed to leave layoutunchanged. So we float it too. */\n\n.collapse { display: none }\n.expand { display: block }\n\n/* log classes */\n.nrml { color: black; }\n.info { color: black; }\n.warn { color: black; background-color: #ffd; }\n.eror { color: black; background-color: #fdd; }\n.mesg { color: green; }\n.dbug { color: black; background-color: #ddf;} /* Blue */\n\n/* Try to get the icons to flush right in the cell */\n\n.sortheader {\n color: black;\n text-decoration: none;\n position: relative;\n border:none; /* Jim's commented out */\n}\n\n.colclose { float: right; color: #aaa } /* Should be 67% transp black */\n.sortarrow { float: left; color: #aaa; border: none;}\n\n\n/* CSS Stuff for tabbed Views.. */\ntable.viewTable {\n padding: 0;\n margin: 0;\n border-style: none;\n border-width: 0;\n height: 40em;\n width: 100%;\n border-spacing: 0;\n}\n\ndiv.viewTabs {\n background-color: #fff;\n padding:0;\n}\n\ndiv.viewWindows {\n width: 100%;\n height:100%;\n overflow: auto;\n margin: 0em;\n padding:0em;\n border-right: solid #aaa 0.1em; /* was 2px */\n border-left: solid #aaa 0.1em;\n border-bottom: solid #aaa 0.1em;\n background-color: #ccc;\n}\n\ndiv.querySelect {\n background-color: #ccc;\n width:100%;\n height:100%;\n border-left: solid #aaa 0.1em;\n border-bottom: solid #aaa 0.1em;\n overflow:auto;\n margin: 0em;\n padding:0em;\n}\n\ntd.viewTableData {\n padding: 0em;\n margin: 0em;\n height:100%;\n width:80%;\n}\n\ntd.queryTableData {\n padding: 0em;\n margin: 0em;\n border-width: 0em;\n height:100%;\n width:20%;\n border-style:none;\n}\n\ntable.viewTable tr {\n height: 100%;\n margin: 0em;\n padding: 0em;\n border-style:none;\n}\n\n\na {\n color: #3B5998;\n text-decoration: none;\n cursor: pointer;\n}\na.inactive{\n background-color: #eee;\n border-right:solid #ddd 0.1em;\n border-top:solid #aaa 0.1em;\n border-left:solid #aaa 0.1em;\n padding-top: 0.3em;\n padding-left: 0.8em;\n padding-right: 0.8em;\n padding-bottom: 0em;\n margin-right: 0.1em;\n color: #99f;\n text-decoration:none;\n}\n\na.active{\n background-color: #ccc;\n border-right:solid #ddd 0.1em;\n border-top:solid #aaa 0.1em;\n border-left:solid #aaa 0.1em;\n padding-top: 0.3em;\n padding-left: 0.8em;\n padding-right: 0.8em;\n padding-bottom:0em;\n margin-right:0.1em;\n color: #22f;\n text-decoration:none;\n}\n\ninput.tabQueryName {\n border: solid #aaa 0.1em;\n width:100%;\n padding:0em;\n}\n\ninput.delQueryButton {\n border:none;\n color:#c00;\n background-color:#ccc;\n cursor:pointer;\n padding:0em;\n}\n\ntd.checkboxTD {\n padding-right:0.5em;\n}\n\n.sourceHighlight {\n background-color:yellow;\n}\n\n#MenuBar {\n padding: 0.5em;\n position: fixed;\n top: 0;\n bottom: auto;\n left: 0;\n right: 0;\n background-color: #eee;\n border: 0.1em solid #aaa;\n}\n\n#TabulatorStatusWidget {\n position: fixed;\n top: 0;\n bottom: auto;\n left: auto;\n right: 0;\n}\n\ndiv.mapKeyDiv {\n position:relative;\n float:right;\n margin: 0.3em;\n color: #777;\n background:#fff;\n border:solid #777 0.1em;\n padding:0.1em;\n}\n\nspan.closeQuerySpan {\n float:right;\n text-align:right;\n height: 0.1em;\n overflow:visible;\n}\n\nspan.openQuerySpan {\n float:left;\n overflow:visible;\n height:0em;\n text-align:left;\n position:relative;\n top:0em;\n z-index:1;\n}\n\ninput.textinput{\n width: 100%;\n border: none;\n font-size:95%;\n padding: 0em;\n margin: 0;\n}\n\ntextarea.textinput{\n border: none;\n}\n\n.pendingedit {\n color: #bbb;\n}\n\ntd.undetermined{\n color: gray;\n font-style: italic;\n}\n\n/*revert back*/\ntd.undetermined table{\n color: black;\n font-style: normal;\n}\n\n/*color style from http://developer.yahoo.com/yui/docs/module_menu.html*/\n.outlineMenu{\n position:absolute;\n /*width:10em;*/\n height:10em; /* Jim's commented out */\n background: #FFFFFF none repeat scroll 0%;\n overflow-x: hidden;\n overflow-y: auto;\n border: 1px solid;\n /*padding:.2em;*/\n}\n.outlineMenu table{cursor:default;width:100%;text-align:left;padding:5px 5px;}\n.outlineMenu div{/*width:6em;*/ overflow:auto; white-space:nowrap;}\n.outlineMenu td{color:#654d6c;}\n.outlineMenu .activeItem{background: #D1C6DA;} /* @@ Jim's: #f4e8fc; */\n.outlineMenu input{margin: 0.2em;}\n\ndiv.bottom-border{\n border: .2em solid transparent;\n width: 100%;\n}\n\ndiv.bottom-border-active{\n cursor: copy;\n border: .2em solid;\n border-color: rgb(100%,65%,0%);\n}\n\n/* The thing below was for the kenny's orange bar*/\n/* @@@ This is not specific enough\ntd{\n margin: 0;\n padding: 0;\n}\n*/\n\n.deleteIcon {\n margin-left: 0.1em;\n}\n\n.deleteCol {\n float: right;\n display: inline;\n}\n\n.suggestion_list\n{\n background: white;\n border: 1px solid;\n padding: 4px;\n}\n\n.suggestion_list ul\n{\n padding: 0;\n margin: 0;\n list-style-type: none;\n}\n\n.suggestion_list a\n{\n text-decoration: none;\n color: navy;\n}\n\n.suggestion_list .selected\n{\n background: navy;\n color: white;\n}\n\n.suggestion_list .selected a\n{\n color: white;\n}\n\n#autosuggest\n{\n display: none;\n}\n\n\n\n/*\nStart of styles for the photoPane, by albert08@csail.mit.edu\n*/\ndiv.PhotoContentPane {\n float: left;\n width: 900px;\n border: 1px solid #AAAAAA;\n padding: 10px;\n}\ndiv.PhotoListPanel {\n float: left;\n padding: 5px ;\n border: 1px solid #AAAAAA;\n width: 540px;\n min-height: 300px;\n}\ndiv.PhotoInfoPanel {\n float: left;\n padding: 10px;\n border: 1px solid #AAAAAA;\n width: 300px;\n text-align: center;\n margin: 0px 0px 10px 10px;\n}\ndiv.TagMenu {\n float: left;\n padding: 10px;\n border: 1px solid #AAAAAA;\n width: 300px;\n margin: 0px 0px 0px 10px;\n text-align: justify;\n}\n.tagItem {\n float: left;\n padding: 2px;\n margin: 2px;\n cursor:pointer;\n}\n.tagItem_h {\n float: left;\n padding: 2px;\n margin: 1px;\n border: 1px solid #DDBB99;\n background-color: #DDEEFF;\n cursor:pointer;\n}\ndiv.photoItem {\n float: left;\n width: 100%;\n}\ndiv.photoFrame {\n border-right: 1px solid #AAAAAA;\n width: 260px;\n padding: 10px;\n margin: 10px 10px 10px 10px;\n text-align: center;\n float: left;\n}\nimg.photoThumbnail {\n border: 1px solid #CCCCCC;\n margin: auto auto auto auto;\n}\n.photoListTags {\n width:200px;\n margin-top: 10px;\n padding-top: 10px;\n float: left;\n}\n.photoList_tag {\n background: transparent url(\"https://solid.github.io/solid-ui/src/originalIcons/tag_tiny.png\") 0px 1px no-repeat;\n padding: 1px 0px 1px 18px;\n margin-left: 5px;\n}\n.TagMenu_tag {\n background: transparent url(\"https://solid.github.io/solid-ui/src/originalIcons/tag_tiny.png\") 0px 1px no-repeat;\n padding: 1px 0px 1px 18px;\n margin-left: 5px;\n}\ndiv.photoImportContentPane {\n float: left;\n padding: 0px;\n width: 930px;\n border: 1px solid #AAAAAA;\n padding: 10px;\n}\n.photoImportTitle {\n font-size: 16px;\n font-weight: bold;\n}\n.photoItemPanel {\n width: 260px;\n height: 300px;\n float: left;\n padding: 10px;\n border: 1px solid #AAAAAA;\n margin: 0px 10px 10px 0px;\n}\n.photoControlImg {\n border: 0px;\n cursor: pointer;\n}\n.photoControlImgInactive {\n opacity: .5;\n border: 0px;\n}\n#photoPageInfo {\n font-family: Arial;\n font-size: 14px;\n font-weight: bold;\n}\n.controls {\n clear: both;\n text-align: right;\n margin: 15px 15px 0px 0px;\n}\n.controlButton {\n margin: 0px 0px 0px 10px;\n}\ndiv.TagPane {\n min-width: 500px;\n border: 1px solid #AAAAAA;\n padding: 10px;\n}\ndiv.TagSemanticsPanel {\n margin: 5px 0px 20px 0px;\n}\ndiv.TagSemanticsTable {\n width: 100%;\n font-family: Arial;\n font-size: 12px;\n}\ndiv.AddTagSemantics {\n margin: 50px 0px 10px 0px;\n}\n.controlSelect {\n margin: 5px;\n font-family: Arial;\n font-size: 12px;\n}\n.tagURIInput {\n margin: 5px;\n font-family: Arial;\n font-size: 12px;\n width: 300px;\n}\ndiv.TagPane hr{\n border: 1px solid #AAAAAA;\n}\n/*\nEnd of styles for the photoPane\n*/\n\n/*\nStyles for tableViewPane\n*/\n\n.tableViewPane table th {\n background-color: #eee;\n color: black;\n}\n\n.tableViewPane table th a {\n color: #555;\n}\n\n.tableViewPane table .selectors td {\n background-color: #ccc;\n}\n\n.tableViewPane table td {\n border-bottom: 1px solid black;\n border-right: 1px solid black;\n}\n\n.tableViewPane .toolbar td {\n border: none;\n}\n\n.tableViewPane .sparqlButton {\n width: 16px;\n height: 16px;\n border: 1px solid black;\n}\n\n.tableViewPane .sparqlDialog {\n position: fixed;\n top: 40px;\n left: 100px;\n width: 600px;\n background: white;\n border: 1px solid black;\n padding: 5px;\n}\n\n.tableViewPane .sparqlDialog textarea {\n width: 590px;\n height: 250px;\n}\n\n/* These should be the same as with hthe dataContentPane */\n.tableViewPane a { color: #3B5998; text-decoration: none; font-weight: bold}\n.tableViewPane a:link { color: #3B5998; text-decoration: none; font-weight: bold}\n.tableViewPane a:visited { color: #3B5998; text-decoration: none; font-weight: bold}\n.tableViewPane a:hover { color: #3B5998; text-decoration: underline; font-weight: bold}\n.tableViewPane a:active { color: #888; text-decoration: none; }\n\n.tableViewPane tr {border-color: #444; padding-left: 0.3em; padding-right: 0.3em }\n\n\n\n/*The 'display explanation' feature*/\n.inquiry {\n padding-left: 0.2em;\n color: red;\n font-family: Arial;\n font-weight: bold;\n}\n\n/*\nEnd of styles for tableViewPane\n*/\n\n\n\n/* Styles for FORM PANE\n**\n** Colors from data cotent pane\n*/\n\n.formPane a { color: #3B5998; text-decoration: none; }\n.formPane a:link { color: #3B5998; text-decoration: none; }\n.formPane a:visited { color: #3B5998; text-decoration: none; }\n.formPane a:hover { color: #3B5998; font-weight: bold} /* was text-decoration: underline; */\n.formPane a:active { color: #888; text-decoration: none; }\n\n/* ends */\n",".footer {\n border-top: solid 1px $divider-color;\n font-size: 0.9em;\n padding: 0.5em 1.5em;\n}\n","$divider-color: rgba(0, 0, 0, 0.2);\n","@mixin box-shadow($x-axis: 0, $y-axis: 1px, $blur: 4px, $color: $default) {\n box-shadow: $x-axis $y-axis $blur $color;\n -webkit-box-shadow: $x-axis $y-axis $blur $color;\n -moz-box-shadow: $x-axis $y-axis $blur $color;\n -o-box-shadow: $x-axis $y-axis $blur $color;\n}","$icon-size: 60px;\n\n.header-banner {\n @include box-shadow(0px, 1px, 4px, $divider-color);\n display: flex;\n padding: 0 1.5em;\n margin-bottom: 4px;\n\n &__icon {\n height: $icon-size;\n width: round($icon-size * 352 / 322);\n width: $icon-size * 352 / 322;\n }\n\n &__login {\n margin-left: auto;\n input {\n // hacks to override the default style of login and signup button from solid-ui\n margin: 0.75em 0 0.75em 0.5em !important;\n padding: 0.5em !important;\n }\n }\n\n &__link {\n display: block;\n }\n\n &__user-menu {\n border-left: solid 1px $divider-color;\n margin-left: auto;\n }\n}\n\n.header-user-menu {\n &__button,\n &__link {\n background: none;\n border: 0;\n color: black;\n cursor: pointer;\n display: block;\n font-family: Arial;\n font-size: 1em;\n text-align: left;\n padding: 1em;\n width: 100%;\n &:focus,\n &:hover {\n background-color: #eee;\n }\n }\n\n &__list {\n list-style: none;\n margin: 0;\n padding: 0;\n }\n\n &__list-item {\n border-bottom: solid 1px $divider-color;\n\n &:last-child {\n border: 0;\n }\n }\n\n &__navigation-menu {\n background: white;\n border: solid 1px $divider-color;\n border-right: 0;\n position: absolute;\n right: 0;\n top: $icon-size;\n width: 200px;\n z-index: 1; // Adding this to make sure that user menu is presented above items with position: relative\n\n &[aria-hidden='true'] {\n display: none;\n }\n }\n\n &__photo {\n $image-margin: 5px;\n $image-size: $icon-size - $image-margin * 2;\n border-radius: 50%;\n background-position: center;\n background-repeat: no-repeat;\n background-size: cover;\n margin: $image-margin;\n height: $image-size;\n width: $image-size;\n }\n\n &__trigger {\n background: none;\n border: 0;\n cursor: pointer;\n width: $icon-size;\n height: $icon-size;\n img {\n border-radius: 50%;\n height: $icon-size - 4px;\n width: $icon-size - 4px;\n }\n }\n}\n","html,\nbody {\n height: 100%;\n}\n\n.db-layout {\n display: flex;\n flex-direction: column;\n\n &__content {\n flex: 1 0 auto;\n }\n\n &__footer,\n &__header {\n flex-shrink: 0;\n }\n}\n","@import \"colors\";\n@import \"mixin\";\n@import \"~normalize.css/normalize.css\";\n\n@import \"common\";\n@import \"footer\";\n@import \"header\";\n@import \"layout\";\n\nbody {\n font-family: sans-serif;\n}\n\nstrong {\n font-weight: bold;\n}\n"],"sourceRoot":""} \ No newline at end of file diff --git a/server/myPod/scripts/mashlib/mashlib.js b/server/myPod/scripts/mashlib/mashlib.js new file mode 100644 index 0000000..9325647 --- /dev/null +++ b/server/myPod/scripts/mashlib/mashlib.js @@ -0,0 +1,143859 @@ +(function webpackUniversalModuleDefinition(root, factory) { + if(typeof exports === 'object' && typeof module === 'object') + module.exports = factory(require("window")); + else if(typeof define === 'function' && define.amd) + define(["window"], factory); + else if(typeof exports === 'object') + exports["Mashlib"] = factory(require("window")); + else + root["Mashlib"] = factory(root["window"]); +})(window, function(__WEBPACK_EXTERNAL_MODULE_xmldom__) { +return /******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) { +/******/ return installedModules[moduleId].exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ i: moduleId, +/******/ l: false, +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); +/******/ +/******/ // Flag the module as loaded +/******/ module.l = true; +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/******/ +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; +/******/ +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; +/******/ +/******/ // define getter function for harmony exports +/******/ __webpack_require__.d = function(exports, name, getter) { +/******/ if(!__webpack_require__.o(exports, name)) { +/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); +/******/ } +/******/ }; +/******/ +/******/ // define __esModule on exports +/******/ __webpack_require__.r = function(exports) { +/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { +/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); +/******/ } +/******/ Object.defineProperty(exports, '__esModule', { value: true }); +/******/ }; +/******/ +/******/ // create a fake namespace object +/******/ // mode & 1: value is a module id, require it +/******/ // mode & 2: merge all properties of value into the ns +/******/ // mode & 4: return value when already ns object +/******/ // mode & 8|1: behave like require +/******/ __webpack_require__.t = function(value, mode) { +/******/ if(mode & 1) value = __webpack_require__(value); +/******/ if(mode & 8) return value; +/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; +/******/ var ns = Object.create(null); +/******/ __webpack_require__.r(ns); +/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); +/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); +/******/ return ns; +/******/ }; +/******/ +/******/ // getDefaultExport function for compatibility with non-harmony modules +/******/ __webpack_require__.n = function(module) { +/******/ var getter = module && module.__esModule ? +/******/ function getDefault() { return module['default']; } : +/******/ function getModuleExports() { return module; }; +/******/ __webpack_require__.d(getter, 'a', getter); +/******/ return getter; +/******/ }; +/******/ +/******/ // Object.prototype.hasOwnProperty.call +/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; +/******/ +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = "/"; +/******/ +/******/ +/******/ // Load entry module and return exports +/******/ return __webpack_require__(__webpack_require__.s = 0); +/******/ }) +/************************************************************************/ +/******/ ({ + +/***/ "./node_modules/@babel/runtime/helpers/arrayLikeToArray.js": +/*!*****************************************************************!*\ + !*** ./node_modules/@babel/runtime/helpers/arrayLikeToArray.js ***! + \*****************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports) { + +function _arrayLikeToArray(arr, len) { + if (len == null || len > arr.length) len = arr.length; + + for (var i = 0, arr2 = new Array(len); i < len; i++) { + arr2[i] = arr[i]; + } + + return arr2; +} + +module.exports = _arrayLikeToArray; + +/***/ }), + +/***/ "./node_modules/@babel/runtime/helpers/arrayWithHoles.js": +/*!***************************************************************!*\ + !*** ./node_modules/@babel/runtime/helpers/arrayWithHoles.js ***! + \***************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports) { + +function _arrayWithHoles(arr) { + if (Array.isArray(arr)) return arr; +} + +module.exports = _arrayWithHoles; + +/***/ }), + +/***/ "./node_modules/@babel/runtime/helpers/assertThisInitialized.js": +/*!**********************************************************************!*\ + !*** ./node_modules/@babel/runtime/helpers/assertThisInitialized.js ***! + \**********************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports) { + +function _assertThisInitialized(self) { + if (self === void 0) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + + return self; +} + +module.exports = _assertThisInitialized; + +/***/ }), + +/***/ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js": +/*!*****************************************************************!*\ + !*** ./node_modules/@babel/runtime/helpers/asyncToGenerator.js ***! + \*****************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports) { + +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { + try { + var info = gen[key](arg); + var value = info.value; + } catch (error) { + reject(error); + return; + } + + if (info.done) { + resolve(value); + } else { + Promise.resolve(value).then(_next, _throw); + } +} + +function _asyncToGenerator(fn) { + return function () { + var self = this, + args = arguments; + return new Promise(function (resolve, reject) { + var gen = fn.apply(self, args); + + function _next(value) { + asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); + } + + function _throw(err) { + asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); + } + + _next(undefined); + }); + }; +} + +module.exports = _asyncToGenerator; + +/***/ }), + +/***/ "./node_modules/@babel/runtime/helpers/classCallCheck.js": +/*!***************************************************************!*\ + !*** ./node_modules/@babel/runtime/helpers/classCallCheck.js ***! + \***************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports) { + +function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } +} + +module.exports = _classCallCheck; + +/***/ }), + +/***/ "./node_modules/@babel/runtime/helpers/construct.js": +/*!**********************************************************!*\ + !*** ./node_modules/@babel/runtime/helpers/construct.js ***! + \**********************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +var setPrototypeOf = __webpack_require__(/*! ./setPrototypeOf */ "./node_modules/@babel/runtime/helpers/setPrototypeOf.js"); + +var isNativeReflectConstruct = __webpack_require__(/*! ./isNativeReflectConstruct */ "./node_modules/@babel/runtime/helpers/isNativeReflectConstruct.js"); + +function _construct(Parent, args, Class) { + if (isNativeReflectConstruct()) { + module.exports = _construct = Reflect.construct; + } else { + module.exports = _construct = function _construct(Parent, args, Class) { + var a = [null]; + a.push.apply(a, args); + var Constructor = Function.bind.apply(Parent, a); + var instance = new Constructor(); + if (Class) setPrototypeOf(instance, Class.prototype); + return instance; + }; + } + + return _construct.apply(null, arguments); +} + +module.exports = _construct; + +/***/ }), + +/***/ "./node_modules/@babel/runtime/helpers/createClass.js": +/*!************************************************************!*\ + !*** ./node_modules/@babel/runtime/helpers/createClass.js ***! + \************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports) { + +function _defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ("value" in descriptor) descriptor.writable = true; + Object.defineProperty(target, descriptor.key, descriptor); + } +} + +function _createClass(Constructor, protoProps, staticProps) { + if (protoProps) _defineProperties(Constructor.prototype, protoProps); + if (staticProps) _defineProperties(Constructor, staticProps); + return Constructor; +} + +module.exports = _createClass; + +/***/ }), + +/***/ "./node_modules/@babel/runtime/helpers/defineProperty.js": +/*!***************************************************************!*\ + !*** ./node_modules/@babel/runtime/helpers/defineProperty.js ***! + \***************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports) { + +function _defineProperty(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; + } + + return obj; +} + +module.exports = _defineProperty; + +/***/ }), + +/***/ "./node_modules/@babel/runtime/helpers/esm/arrayLikeToArray.js": +/*!*********************************************************************!*\ + !*** ./node_modules/@babel/runtime/helpers/esm/arrayLikeToArray.js ***! + \*********************************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return _arrayLikeToArray; }); +function _arrayLikeToArray(arr, len) { + if (len == null || len > arr.length) len = arr.length; + + for (var i = 0, arr2 = new Array(len); i < len; i++) { + arr2[i] = arr[i]; + } + + return arr2; +} + +/***/ }), + +/***/ "./node_modules/@babel/runtime/helpers/esm/arrayWithoutHoles.js": +/*!**********************************************************************!*\ + !*** ./node_modules/@babel/runtime/helpers/esm/arrayWithoutHoles.js ***! + \**********************************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return _arrayWithoutHoles; }); +/* harmony import */ var _babel_runtime_helpers_esm_arrayLikeToArray__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/esm/arrayLikeToArray */ "./node_modules/@babel/runtime/helpers/esm/arrayLikeToArray.js"); + +function _arrayWithoutHoles(arr) { + if (Array.isArray(arr)) return Object(_babel_runtime_helpers_esm_arrayLikeToArray__WEBPACK_IMPORTED_MODULE_0__["default"])(arr); +} + +/***/ }), + +/***/ "./node_modules/@babel/runtime/helpers/esm/assertThisInitialized.js": +/*!**************************************************************************!*\ + !*** ./node_modules/@babel/runtime/helpers/esm/assertThisInitialized.js ***! + \**************************************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return _assertThisInitialized; }); +function _assertThisInitialized(self) { + if (self === void 0) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + + return self; +} + +/***/ }), + +/***/ "./node_modules/@babel/runtime/helpers/esm/createClass.js": +/*!****************************************************************!*\ + !*** ./node_modules/@babel/runtime/helpers/esm/createClass.js ***! + \****************************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return _createClass; }); +function _defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ("value" in descriptor) descriptor.writable = true; + Object.defineProperty(target, descriptor.key, descriptor); + } +} + +function _createClass(Constructor, protoProps, staticProps) { + if (protoProps) _defineProperties(Constructor.prototype, protoProps); + if (staticProps) _defineProperties(Constructor, staticProps); + return Constructor; +} + +/***/ }), + +/***/ "./node_modules/@babel/runtime/helpers/esm/extends.js": +/*!************************************************************!*\ + !*** ./node_modules/@babel/runtime/helpers/esm/extends.js ***! + \************************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return _extends; }); +function _extends() { + _extends = Object.assign || function (target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i]; + + for (var key in source) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + target[key] = source[key]; + } + } + } + + return target; + }; + + return _extends.apply(this, arguments); +} + +/***/ }), + +/***/ "./node_modules/@babel/runtime/helpers/esm/inheritsLoose.js": +/*!******************************************************************!*\ + !*** ./node_modules/@babel/runtime/helpers/esm/inheritsLoose.js ***! + \******************************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return _inheritsLoose; }); +function _inheritsLoose(subClass, superClass) { + subClass.prototype = Object.create(superClass.prototype); + subClass.prototype.constructor = subClass; + subClass.__proto__ = superClass; +} + +/***/ }), + +/***/ "./node_modules/@babel/runtime/helpers/esm/iterableToArray.js": +/*!********************************************************************!*\ + !*** ./node_modules/@babel/runtime/helpers/esm/iterableToArray.js ***! + \********************************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return _iterableToArray; }); +function _iterableToArray(iter) { + if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); +} + +/***/ }), + +/***/ "./node_modules/@babel/runtime/helpers/esm/nonIterableSpread.js": +/*!**********************************************************************!*\ + !*** ./node_modules/@babel/runtime/helpers/esm/nonIterableSpread.js ***! + \**********************************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return _nonIterableSpread; }); +function _nonIterableSpread() { + throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); +} + +/***/ }), + +/***/ "./node_modules/@babel/runtime/helpers/esm/objectWithoutPropertiesLoose.js": +/*!*********************************************************************************!*\ + !*** ./node_modules/@babel/runtime/helpers/esm/objectWithoutPropertiesLoose.js ***! + \*********************************************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return _objectWithoutPropertiesLoose; }); +function _objectWithoutPropertiesLoose(source, excluded) { + if (source == null) return {}; + var target = {}; + var sourceKeys = Object.keys(source); + var key, i; + + for (i = 0; i < sourceKeys.length; i++) { + key = sourceKeys[i]; + if (excluded.indexOf(key) >= 0) continue; + target[key] = source[key]; + } + + return target; +} + +/***/ }), + +/***/ "./node_modules/@babel/runtime/helpers/esm/toConsumableArray.js": +/*!**********************************************************************!*\ + !*** ./node_modules/@babel/runtime/helpers/esm/toConsumableArray.js ***! + \**********************************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return _toConsumableArray; }); +/* harmony import */ var _babel_runtime_helpers_esm_arrayWithoutHoles__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/esm/arrayWithoutHoles */ "./node_modules/@babel/runtime/helpers/esm/arrayWithoutHoles.js"); +/* harmony import */ var _babel_runtime_helpers_esm_iterableToArray__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/esm/iterableToArray */ "./node_modules/@babel/runtime/helpers/esm/iterableToArray.js"); +/* harmony import */ var _babel_runtime_helpers_esm_unsupportedIterableToArray__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/esm/unsupportedIterableToArray */ "./node_modules/@babel/runtime/helpers/esm/unsupportedIterableToArray.js"); +/* harmony import */ var _babel_runtime_helpers_esm_nonIterableSpread__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/esm/nonIterableSpread */ "./node_modules/@babel/runtime/helpers/esm/nonIterableSpread.js"); + + + + +function _toConsumableArray(arr) { + return Object(_babel_runtime_helpers_esm_arrayWithoutHoles__WEBPACK_IMPORTED_MODULE_0__["default"])(arr) || Object(_babel_runtime_helpers_esm_iterableToArray__WEBPACK_IMPORTED_MODULE_1__["default"])(arr) || Object(_babel_runtime_helpers_esm_unsupportedIterableToArray__WEBPACK_IMPORTED_MODULE_2__["default"])(arr) || Object(_babel_runtime_helpers_esm_nonIterableSpread__WEBPACK_IMPORTED_MODULE_3__["default"])(); +} + +/***/ }), + +/***/ "./node_modules/@babel/runtime/helpers/esm/unsupportedIterableToArray.js": +/*!*******************************************************************************!*\ + !*** ./node_modules/@babel/runtime/helpers/esm/unsupportedIterableToArray.js ***! + \*******************************************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return _unsupportedIterableToArray; }); +/* harmony import */ var _babel_runtime_helpers_esm_arrayLikeToArray__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/esm/arrayLikeToArray */ "./node_modules/@babel/runtime/helpers/esm/arrayLikeToArray.js"); + +function _unsupportedIterableToArray(o, minLen) { + if (!o) return; + if (typeof o === "string") return Object(_babel_runtime_helpers_esm_arrayLikeToArray__WEBPACK_IMPORTED_MODULE_0__["default"])(o, minLen); + var n = Object.prototype.toString.call(o).slice(8, -1); + if (n === "Object" && o.constructor) n = o.constructor.name; + if (n === "Map" || n === "Set") return Array.from(o); + if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return Object(_babel_runtime_helpers_esm_arrayLikeToArray__WEBPACK_IMPORTED_MODULE_0__["default"])(o, minLen); +} + +/***/ }), + +/***/ "./node_modules/@babel/runtime/helpers/getPrototypeOf.js": +/*!***************************************************************!*\ + !*** ./node_modules/@babel/runtime/helpers/getPrototypeOf.js ***! + \***************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports) { + +function _getPrototypeOf(o) { + module.exports = _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { + return o.__proto__ || Object.getPrototypeOf(o); + }; + return _getPrototypeOf(o); +} + +module.exports = _getPrototypeOf; + +/***/ }), + +/***/ "./node_modules/@babel/runtime/helpers/inherits.js": +/*!*********************************************************!*\ + !*** ./node_modules/@babel/runtime/helpers/inherits.js ***! + \*********************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +var setPrototypeOf = __webpack_require__(/*! ./setPrototypeOf */ "./node_modules/@babel/runtime/helpers/setPrototypeOf.js"); + +function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError("Super expression must either be null or a function"); + } + + subClass.prototype = Object.create(superClass && superClass.prototype, { + constructor: { + value: subClass, + writable: true, + configurable: true + } + }); + if (superClass) setPrototypeOf(subClass, superClass); +} + +module.exports = _inherits; + +/***/ }), + +/***/ "./node_modules/@babel/runtime/helpers/interopRequireDefault.js": +/*!**********************************************************************!*\ + !*** ./node_modules/@babel/runtime/helpers/interopRequireDefault.js ***! + \**********************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports) { + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + "default": obj + }; +} + +module.exports = _interopRequireDefault; + +/***/ }), + +/***/ "./node_modules/@babel/runtime/helpers/interopRequireWildcard.js": +/*!***********************************************************************!*\ + !*** ./node_modules/@babel/runtime/helpers/interopRequireWildcard.js ***! + \***********************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "./node_modules/@babel/runtime/helpers/typeof.js"); + +function _getRequireWildcardCache() { + if (typeof WeakMap !== "function") return null; + var cache = new WeakMap(); + + _getRequireWildcardCache = function _getRequireWildcardCache() { + return cache; + }; + + return cache; +} + +function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } + + if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { + return { + "default": obj + }; + } + + var cache = _getRequireWildcardCache(); + + if (cache && cache.has(obj)) { + return cache.get(obj); + } + + var newObj = {}; + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; + + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; + + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + + newObj["default"] = obj; + + if (cache) { + cache.set(obj, newObj); + } + + return newObj; +} + +module.exports = _interopRequireWildcard; + +/***/ }), + +/***/ "./node_modules/@babel/runtime/helpers/isNativeFunction.js": +/*!*****************************************************************!*\ + !*** ./node_modules/@babel/runtime/helpers/isNativeFunction.js ***! + \*****************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports) { + +function _isNativeFunction(fn) { + return Function.toString.call(fn).indexOf("[native code]") !== -1; +} + +module.exports = _isNativeFunction; + +/***/ }), + +/***/ "./node_modules/@babel/runtime/helpers/isNativeReflectConstruct.js": +/*!*************************************************************************!*\ + !*** ./node_modules/@babel/runtime/helpers/isNativeReflectConstruct.js ***! + \*************************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports) { + +function _isNativeReflectConstruct() { + if (typeof Reflect === "undefined" || !Reflect.construct) return false; + if (Reflect.construct.sham) return false; + if (typeof Proxy === "function") return true; + + try { + Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); + return true; + } catch (e) { + return false; + } +} + +module.exports = _isNativeReflectConstruct; + +/***/ }), + +/***/ "./node_modules/@babel/runtime/helpers/iterableToArrayLimit.js": +/*!*********************************************************************!*\ + !*** ./node_modules/@babel/runtime/helpers/iterableToArrayLimit.js ***! + \*********************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports) { + +function _iterableToArrayLimit(arr, i) { + if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; + var _arr = []; + var _n = true; + var _d = false; + var _e = undefined; + + try { + for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { + _arr.push(_s.value); + + if (i && _arr.length === i) break; + } + } catch (err) { + _d = true; + _e = err; + } finally { + try { + if (!_n && _i["return"] != null) _i["return"](); + } finally { + if (_d) throw _e; + } + } + + return _arr; +} + +module.exports = _iterableToArrayLimit; + +/***/ }), + +/***/ "./node_modules/@babel/runtime/helpers/nonIterableRest.js": +/*!****************************************************************!*\ + !*** ./node_modules/@babel/runtime/helpers/nonIterableRest.js ***! + \****************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports) { + +function _nonIterableRest() { + throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); +} + +module.exports = _nonIterableRest; + +/***/ }), + +/***/ "./node_modules/@babel/runtime/helpers/possibleConstructorReturn.js": +/*!**************************************************************************!*\ + !*** ./node_modules/@babel/runtime/helpers/possibleConstructorReturn.js ***! + \**************************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "./node_modules/@babel/runtime/helpers/typeof.js"); + +var assertThisInitialized = __webpack_require__(/*! ./assertThisInitialized */ "./node_modules/@babel/runtime/helpers/assertThisInitialized.js"); + +function _possibleConstructorReturn(self, call) { + if (call && (_typeof(call) === "object" || typeof call === "function")) { + return call; + } + + return assertThisInitialized(self); +} + +module.exports = _possibleConstructorReturn; + +/***/ }), + +/***/ "./node_modules/@babel/runtime/helpers/setPrototypeOf.js": +/*!***************************************************************!*\ + !*** ./node_modules/@babel/runtime/helpers/setPrototypeOf.js ***! + \***************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports) { + +function _setPrototypeOf(o, p) { + module.exports = _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { + o.__proto__ = p; + return o; + }; + + return _setPrototypeOf(o, p); +} + +module.exports = _setPrototypeOf; + +/***/ }), + +/***/ "./node_modules/@babel/runtime/helpers/slicedToArray.js": +/*!**************************************************************!*\ + !*** ./node_modules/@babel/runtime/helpers/slicedToArray.js ***! + \**************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +var arrayWithHoles = __webpack_require__(/*! ./arrayWithHoles */ "./node_modules/@babel/runtime/helpers/arrayWithHoles.js"); + +var iterableToArrayLimit = __webpack_require__(/*! ./iterableToArrayLimit */ "./node_modules/@babel/runtime/helpers/iterableToArrayLimit.js"); + +var unsupportedIterableToArray = __webpack_require__(/*! ./unsupportedIterableToArray */ "./node_modules/@babel/runtime/helpers/unsupportedIterableToArray.js"); + +var nonIterableRest = __webpack_require__(/*! ./nonIterableRest */ "./node_modules/@babel/runtime/helpers/nonIterableRest.js"); + +function _slicedToArray(arr, i) { + return arrayWithHoles(arr) || iterableToArrayLimit(arr, i) || unsupportedIterableToArray(arr, i) || nonIterableRest(); +} + +module.exports = _slicedToArray; + +/***/ }), + +/***/ "./node_modules/@babel/runtime/helpers/taggedTemplateLiteral.js": +/*!**********************************************************************!*\ + !*** ./node_modules/@babel/runtime/helpers/taggedTemplateLiteral.js ***! + \**********************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports) { + +function _taggedTemplateLiteral(strings, raw) { + if (!raw) { + raw = strings.slice(0); + } + + return Object.freeze(Object.defineProperties(strings, { + raw: { + value: Object.freeze(raw) + } + })); +} + +module.exports = _taggedTemplateLiteral; + +/***/ }), + +/***/ "./node_modules/@babel/runtime/helpers/typeof.js": +/*!*******************************************************!*\ + !*** ./node_modules/@babel/runtime/helpers/typeof.js ***! + \*******************************************************/ +/*! no static exports found */ +/***/ (function(module, exports) { + +function _typeof(obj) { + "@babel/helpers - typeof"; + + if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { + module.exports = _typeof = function _typeof(obj) { + return typeof obj; + }; + } else { + module.exports = _typeof = function _typeof(obj) { + return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; + }; + } + + return _typeof(obj); +} + +module.exports = _typeof; + +/***/ }), + +/***/ "./node_modules/@babel/runtime/helpers/unsupportedIterableToArray.js": +/*!***************************************************************************!*\ + !*** ./node_modules/@babel/runtime/helpers/unsupportedIterableToArray.js ***! + \***************************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +var arrayLikeToArray = __webpack_require__(/*! ./arrayLikeToArray */ "./node_modules/@babel/runtime/helpers/arrayLikeToArray.js"); + +function _unsupportedIterableToArray(o, minLen) { + if (!o) return; + if (typeof o === "string") return arrayLikeToArray(o, minLen); + var n = Object.prototype.toString.call(o).slice(8, -1); + if (n === "Object" && o.constructor) n = o.constructor.name; + if (n === "Map" || n === "Set") return Array.from(o); + if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return arrayLikeToArray(o, minLen); +} + +module.exports = _unsupportedIterableToArray; + +/***/ }), + +/***/ "./node_modules/@babel/runtime/helpers/wrapNativeSuper.js": +/*!****************************************************************!*\ + !*** ./node_modules/@babel/runtime/helpers/wrapNativeSuper.js ***! + \****************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +var getPrototypeOf = __webpack_require__(/*! ./getPrototypeOf */ "./node_modules/@babel/runtime/helpers/getPrototypeOf.js"); + +var setPrototypeOf = __webpack_require__(/*! ./setPrototypeOf */ "./node_modules/@babel/runtime/helpers/setPrototypeOf.js"); + +var isNativeFunction = __webpack_require__(/*! ./isNativeFunction */ "./node_modules/@babel/runtime/helpers/isNativeFunction.js"); + +var construct = __webpack_require__(/*! ./construct */ "./node_modules/@babel/runtime/helpers/construct.js"); + +function _wrapNativeSuper(Class) { + var _cache = typeof Map === "function" ? new Map() : undefined; + + module.exports = _wrapNativeSuper = function _wrapNativeSuper(Class) { + if (Class === null || !isNativeFunction(Class)) return Class; + + if (typeof Class !== "function") { + throw new TypeError("Super expression must either be null or a function"); + } + + if (typeof _cache !== "undefined") { + if (_cache.has(Class)) return _cache.get(Class); + + _cache.set(Class, Wrapper); + } + + function Wrapper() { + return construct(Class, arguments, getPrototypeOf(this).constructor); + } + + Wrapper.prototype = Object.create(Class.prototype, { + constructor: { + value: Wrapper, + enumerable: false, + writable: true, + configurable: true + } + }); + return setPrototypeOf(Wrapper, Class); + }; + + return _wrapNativeSuper(Class); +} + +module.exports = _wrapNativeSuper; + +/***/ }), + +/***/ "./node_modules/@babel/runtime/regenerator/index.js": +/*!**********************************************************!*\ + !*** ./node_modules/@babel/runtime/regenerator/index.js ***! + \**********************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +module.exports = __webpack_require__(/*! regenerator-runtime */ "./node_modules/regenerator-runtime/runtime.js"); + + +/***/ }), + +/***/ "./node_modules/@emotion/is-prop-valid/dist/is-prop-valid.browser.esm.js": +/*!*******************************************************************************!*\ + !*** ./node_modules/@emotion/is-prop-valid/dist/is-prop-valid.browser.esm.js ***! + \*******************************************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _emotion_memoize__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @emotion/memoize */ "./node_modules/@emotion/memoize/dist/memoize.browser.esm.js"); + + +var reactPropsRegex = /^((children|dangerouslySetInnerHTML|key|ref|autoFocus|defaultValue|defaultChecked|innerHTML|suppressContentEditableWarning|suppressHydrationWarning|valueLink|accept|acceptCharset|accessKey|action|allow|allowUserMedia|allowPaymentRequest|allowFullScreen|allowTransparency|alt|async|autoComplete|autoPlay|capture|cellPadding|cellSpacing|challenge|charSet|checked|cite|classID|className|cols|colSpan|content|contentEditable|contextMenu|controls|controlsList|coords|crossOrigin|data|dateTime|default|defer|dir|disabled|download|draggable|encType|form|formAction|formEncType|formMethod|formNoValidate|formTarget|frameBorder|headers|height|hidden|high|href|hrefLang|htmlFor|httpEquiv|id|inputMode|integrity|is|keyParams|keyType|kind|label|lang|list|loop|low|marginHeight|marginWidth|max|maxLength|media|mediaGroup|method|min|minLength|multiple|muted|name|nonce|noValidate|open|optimum|pattern|placeholder|playsInline|poster|preload|profile|radioGroup|readOnly|referrerPolicy|rel|required|reversed|role|rows|rowSpan|sandbox|scope|scoped|scrolling|seamless|selected|shape|size|sizes|slot|span|spellCheck|src|srcDoc|srcLang|srcSet|start|step|style|summary|tabIndex|target|title|type|useMap|value|width|wmode|wrap|about|datatype|inlist|prefix|property|resource|typeof|vocab|autoCapitalize|autoCorrect|autoSave|color|itemProp|itemScope|itemType|itemID|itemRef|results|security|unselectable|accentHeight|accumulate|additive|alignmentBaseline|allowReorder|alphabetic|amplitude|arabicForm|ascent|attributeName|attributeType|autoReverse|azimuth|baseFrequency|baselineShift|baseProfile|bbox|begin|bias|by|calcMode|capHeight|clip|clipPathUnits|clipPath|clipRule|colorInterpolation|colorInterpolationFilters|colorProfile|colorRendering|contentScriptType|contentStyleType|cursor|cx|cy|d|decelerate|descent|diffuseConstant|direction|display|divisor|dominantBaseline|dur|dx|dy|edgeMode|elevation|enableBackground|end|exponent|externalResourcesRequired|fill|fillOpacity|fillRule|filter|filterRes|filterUnits|floodColor|floodOpacity|focusable|fontFamily|fontSize|fontSizeAdjust|fontStretch|fontStyle|fontVariant|fontWeight|format|from|fr|fx|fy|g1|g2|glyphName|glyphOrientationHorizontal|glyphOrientationVertical|glyphRef|gradientTransform|gradientUnits|hanging|horizAdvX|horizOriginX|ideographic|imageRendering|in|in2|intercept|k|k1|k2|k3|k4|kernelMatrix|kernelUnitLength|kerning|keyPoints|keySplines|keyTimes|lengthAdjust|letterSpacing|lightingColor|limitingConeAngle|local|markerEnd|markerMid|markerStart|markerHeight|markerUnits|markerWidth|mask|maskContentUnits|maskUnits|mathematical|mode|numOctaves|offset|opacity|operator|order|orient|orientation|origin|overflow|overlinePosition|overlineThickness|panose1|paintOrder|pathLength|patternContentUnits|patternTransform|patternUnits|pointerEvents|points|pointsAtX|pointsAtY|pointsAtZ|preserveAlpha|preserveAspectRatio|primitiveUnits|r|radius|refX|refY|renderingIntent|repeatCount|repeatDur|requiredExtensions|requiredFeatures|restart|result|rotate|rx|ry|scale|seed|shapeRendering|slope|spacing|specularConstant|specularExponent|speed|spreadMethod|startOffset|stdDeviation|stemh|stemv|stitchTiles|stopColor|stopOpacity|strikethroughPosition|strikethroughThickness|string|stroke|strokeDasharray|strokeDashoffset|strokeLinecap|strokeLinejoin|strokeMiterlimit|strokeOpacity|strokeWidth|surfaceScale|systemLanguage|tableValues|targetX|targetY|textAnchor|textDecoration|textRendering|textLength|to|transform|u1|u2|underlinePosition|underlineThickness|unicode|unicodeBidi|unicodeRange|unitsPerEm|vAlphabetic|vHanging|vIdeographic|vMathematical|values|vectorEffect|version|vertAdvY|vertOriginX|vertOriginY|viewBox|viewTarget|visibility|widths|wordSpacing|writingMode|x|xHeight|x1|x2|xChannelSelector|xlinkActuate|xlinkArcrole|xlinkHref|xlinkRole|xlinkShow|xlinkTitle|xlinkType|xmlBase|xmlns|xmlnsXlink|xmlLang|xmlSpace|y|y1|y2|yChannelSelector|z|zoomAndPan|for|class|autofocus)|(([Dd][Aa][Tt][Aa]|[Aa][Rr][Ii][Aa]|x)-.*))$/; // https://esbench.com/bench/5bfee68a4cd7e6009ef61d23 + +var index = Object(_emotion_memoize__WEBPACK_IMPORTED_MODULE_0__["default"])(function (prop) { + return reactPropsRegex.test(prop) || prop.charCodeAt(0) === 111 + /* o */ + && prop.charCodeAt(1) === 110 + /* n */ + && prop.charCodeAt(2) < 91; +} +/* Z+1 */ +); + +/* harmony default export */ __webpack_exports__["default"] = (index); + + +/***/ }), + +/***/ "./node_modules/@emotion/memoize/dist/memoize.browser.esm.js": +/*!*******************************************************************!*\ + !*** ./node_modules/@emotion/memoize/dist/memoize.browser.esm.js ***! + \*******************************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +function memoize(fn) { + var cache = {}; + return function (arg) { + if (cache[arg] === undefined) cache[arg] = fn(arg); + return cache[arg]; + }; +} + +/* harmony default export */ __webpack_exports__["default"] = (memoize); + + +/***/ }), + +/***/ "./node_modules/@solid/better-simple-slideshow/js/better-simple-slideshow.js": +/*!***********************************************************************************!*\ + !*** ./node_modules/@solid/better-simple-slideshow/js/better-simple-slideshow.js ***! + \***********************************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + + +var makeBSS = function (el, options) { + if (typeof document === 'undefined') { + var document = options.dom; + } + var $slideshows = document.querySelectorAll(el), // a collection of all of the slideshow + $slideshow = {}, + Slideshow = { + init: function (el, options) { + this.counter = 0; // to keep track of current slide + this.el = el; // current slideshow container + this.$items = el.querySelectorAll('figure'); // a collection of all of the slides, caching for performance + this.numItems = this.$items.length; // total number of slides + options = options || {}; // if options object not passed in, then set to empty object + options.auto = options.auto || false; // if options.auto object not passed in, then set to false + this.opts = { + auto: (typeof options.auto === "undefined") ? false : options.auto, + speed: (typeof options.auto.speed === "undefined") ? 1500 : options.auto.speed, + pauseOnHover: (typeof options.auto.pauseOnHover === "undefined") ? false : options.auto.pauseOnHover, + fullScreen: (typeof options.fullScreen === "undefined") ? false : options.fullScreen, + swipe: (typeof options.swipe === "undefined") ? false : options.swipe + }; + + this.$items[0].classList.add('bss-show'); // add show class to first figure + this.injectControls(el); + this.addEventListeners(el); + if (this.opts.auto) { + this.autoCycle(this.el, this.opts.speed, this.opts.pauseOnHover); + } + if (this.opts.fullScreen) { + this.addFullScreen(this.el); + } + if (this.opts.swipe) { + this.addSwipe(this.el); + } + }, + showCurrent: function (i) { + // increment or decrement this.counter depending on whether i === 1 or i === -1 + if (i > 0) { + this.counter = (this.counter + 1 === this.numItems) ? 0 : this.counter + 1; + } else { + this.counter = (this.counter - 1 < 0) ? this.numItems - 1 : this.counter - 1; + } + + // remove .show from whichever element currently has it + // http://stackoverflow.com/a/16053538/2006057 + [].forEach.call(this.$items, function (el) { + el.classList.remove('bss-show'); + }); + + // add .show to the one item that's supposed to have it + this.$items[this.counter].classList.add('bss-show'); + }, + injectControls: function (el) { + // build and inject prev/next controls + // first create all the new elements + var spanPrev = document.createElement("span"), + spanNext = document.createElement("span"), + docFrag = document.createDocumentFragment(); + + // add classes + spanPrev.classList.add('bss-prev'); + spanNext.classList.add('bss-next'); + + // add contents + spanPrev.innerHTML = '«'; + spanNext.innerHTML = '»'; + + // append elements to fragment, then append fragment to DOM + docFrag.appendChild(spanPrev); + docFrag.appendChild(spanNext); + el.appendChild(docFrag); + }, + addEventListeners: function (el) { + var that = this; + el.querySelector('.bss-next').addEventListener('click', function () { + that.showCurrent(1); // increment & show + }, false); + + el.querySelector('.bss-prev').addEventListener('click', function () { + that.showCurrent(-1); // decrement & show + }, false); + + el.onkeydown = function (e) { + e = e || window.event; + if (e.keyCode === 37) { + that.showCurrent(-1); // decrement & show + } else if (e.keyCode === 39) { + that.showCurrent(1); // increment & show + } + }; + }, + autoCycle: function (el, speed, pauseOnHover) { + var that = this, + interval = window.setInterval(function () { + that.showCurrent(1); // increment & show + }, speed); + + if (pauseOnHover) { + el.addEventListener('mouseover', function () { + interval = clearInterval(interval); + }, false); + el.addEventListener('mouseout', function () { + interval = window.setInterval(function () { + that.showCurrent(1); // increment & show + }, speed); + }, false); + } // end pauseonhover + + }, + addFullScreen: function(el){ + var that = this, + fsControl = document.createElement("span"); + + fsControl.classList.add('bss-fullscreen'); + el.appendChild(fsControl); + el.querySelector('.bss-fullscreen').addEventListener('click', function () { + that.toggleFullScreen(el); + }, false); + }, + addSwipe: function(el){ + var that = this, + ht = new Hammer(el); + ht.on('swiperight', function(e) { + that.showCurrent(-1); // decrement & show + }); + ht.on('swipeleft', function(e) { + that.showCurrent(1); // increment & show + }); + }, + toggleFullScreen: function(el){ + // https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Using_full_screen_mode + if (!document.fullscreenElement && // alternative standard method + !document.mozFullScreenElement && !document.webkitFullscreenElement && + !document.msFullscreenElement ) { // current working methods + if (document.documentElement.requestFullscreen) { + el.requestFullscreen(); + } else if (document.documentElement.msRequestFullscreen) { + el.msRequestFullscreen(); + } else if (document.documentElement.mozRequestFullScreen) { + el.mozRequestFullScreen(); + } else if (document.documentElement.webkitRequestFullscreen) { + el.webkitRequestFullscreen(el.ALLOW_KEYBOARD_INPUT); + } + } else { + if (document.exitFullscreen) { + document.exitFullscreen(); + } else if (document.msExitFullscreen) { + document.msExitFullscreen(); + } else if (document.mozCancelFullScreen) { + document.mozCancelFullScreen(); + } else if (document.webkitExitFullscreen) { + document.webkitExitFullscreen(); + } + } + } // end toggleFullScreen + + }; // end Slideshow object ..... + + // make instances of Slideshow as needed + [].forEach.call($slideshows, function (el) { + $slideshow = Object.create(Slideshow); + $slideshow.init(el, options); + }); +}; + +if ( true && module.exports) { + module.exports = makeBSS +} + + +/***/ }), + +/***/ "./node_modules/activitystreams-pane/lib/Pane.js": +/*!*******************************************************!*\ + !*** ./node_modules/activitystreams-pane/lib/Pane.js ***! + \*******************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __assign = (this && this.__assign) || function () { + __assign = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Pane = void 0; +var React = __webpack_require__(/*! react */ "./node_modules/react/index.js"); +var note_1 = __webpack_require__(/*! ./note */ "./node_modules/activitystreams-pane/lib/note/index.js"); +exports.Pane = function (_a) { + var subject = _a.subject, context = _a.context; + var store = context.session.store; + var note = note_1.useNote(subject, store); + return React.createElement(note_1.NoteCard, __assign({}, note)); +}; +//# sourceMappingURL=Pane.js.map + +/***/ }), + +/***/ "./node_modules/activitystreams-pane/lib/dom.js": +/*!******************************************************!*\ + !*** ./node_modules/activitystreams-pane/lib/dom.js ***! + \******************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createElement = void 0; +var react_dom_1 = __webpack_require__(/*! react-dom */ "./node_modules/react-dom/index.js"); +function createElement(jsx) { + var element = document.createElement("div"); + element.style.padding = "1em"; + react_dom_1.render(jsx, element); + return element; +} +exports.createElement = createElement; +//# sourceMappingURL=dom.js.map + +/***/ }), + +/***/ "./node_modules/activitystreams-pane/lib/index.js": +/*!********************************************************!*\ + !*** ./node_modules/activitystreams-pane/lib/index.js ***! + \********************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +var React = __webpack_require__(/*! react */ "./node_modules/react/index.js"); +var solid_ui_1 = __webpack_require__(/*! solid-ui */ "./node_modules/solid-ui/lib/index.js"); +var dom_1 = __webpack_require__(/*! ./dom */ "./node_modules/activitystreams-pane/lib/dom.js"); +var Pane_1 = __webpack_require__(/*! ./Pane */ "./node_modules/activitystreams-pane/lib/Pane.js"); +var thisPane = { + global: false, + icon: solid_ui_1.icons.iconBase + "noun_15695.svg", + name: "activitystreams", + label: function (subject, context) { + var t = context.session.store.findTypeURIs(subject); + if (t[solid_ui_1.ns.as("Note").uri]) { + return "Note"; + } + return null; + }, + render: function (subject, context) { + return dom_1.createElement(React.createElement(Pane_1.Pane, { subject: subject, context: context })); + }, +}; +exports.default = thisPane; +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ "./node_modules/activitystreams-pane/lib/note/AttributionTag.js": +/*!**********************************************************************!*\ + !*** ./node_modules/activitystreams-pane/lib/note/AttributionTag.js ***! + \**********************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __assign = (this && this.__assign) || function () { + __assign = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AttributionTag = void 0; +var React = __webpack_require__(/*! react */ "./node_modules/react/index.js"); +var types_1 = __webpack_require__(/*! ./types */ "./node_modules/activitystreams-pane/lib/note/types.js"); +exports.AttributionTag = function (_a) { + var to = _a.to; + if (types_1.isLinkAttribution(to)) { + return React.createElement("a", { href: to.uri }, to.uri); + } + else if (types_1.isPersonAttribution(to)) { + return React.createElement(PersonAttributionTag, __assign({}, to)); + } + else { + return null; + } +}; +var PersonAttributionTag = function (_a) { + var webId = _a.webId, name = _a.name, imageSrc = _a.imageSrc; + return (React.createElement(React.Fragment, null, + imageSrc && React.createElement("img", { height: "47", width: "47", alt: name, src: imageSrc }), + React.createElement("a", { href: webId }, name))); +}; +//# sourceMappingURL=AttributionTag.js.map + +/***/ }), + +/***/ "./node_modules/activitystreams-pane/lib/note/FormattedDate.js": +/*!*********************************************************************!*\ + !*** ./node_modules/activitystreams-pane/lib/note/FormattedDate.js ***! + \*********************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +exports.FormattedDate = void 0; +var React = __webpack_require__(/*! react */ "./node_modules/react/index.js"); +var timeago_js_1 = __webpack_require__(/*! timeago.js */ "./node_modules/timeago.js/esm/index.js"); +var twoDigitsDateTime = { + year: "numeric", + month: "2-digit", + day: "2-digit", + hour: "2-digit", + minute: "2-digit", +}; +exports.FormattedDate = function (_a) { + var value = _a.value, className = _a.className; + if (!value) + return null; + var formatted = value.toLocaleDateString(undefined, twoDigitsDateTime); + var relative = timeago_js_1.format(value); + return (React.createElement("p", { className: className }, + relative, + " \u00B7 ", + formatted)); +}; +//# sourceMappingURL=FormattedDate.js.map + +/***/ }), + +/***/ "./node_modules/activitystreams-pane/lib/note/NoteCard.js": +/*!****************************************************************!*\ + !*** ./node_modules/activitystreams-pane/lib/note/NoteCard.js ***! + \****************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +exports.NoteCard = void 0; +var React = __webpack_require__(/*! react */ "./node_modules/react/index.js"); +var react_jss_1 = __webpack_require__(/*! react-jss */ "./node_modules/react-jss/dist/react-jss.esm.js"); +var FormattedDate_1 = __webpack_require__(/*! ./FormattedDate */ "./node_modules/activitystreams-pane/lib/note/FormattedDate.js"); +var AttributionTag_1 = __webpack_require__(/*! ./AttributionTag */ "./node_modules/activitystreams-pane/lib/note/AttributionTag.js"); +var useStyles = react_jss_1.createUseStyles({ + card: { + fontFamily: "sans-serif", + display: "flex", + flexWrap: "wrap", + borderRadius: "4px", + flexDirection: "column", + justifyContent: "center", + padding: "1em", + boxShadow: "0 1px 5px rgba(0,0,0,0.2)", + transition: "all .25s ease-in-out", + maxWidth: 632, + }, + content: { + fontSize: "larger", + }, + date: { + color: "rgb(0, 0, 0, 60%)", + }, + attribution: { + display: "flex", + alignItems: "center", + fontWeight: "bold", + "& a": { + color: "black", + textDecoration: "none", + }, + "& a:hover": { + textDecoration: "underline", + }, + "& img": { + marginRight: 5, + width: 47, + borderRadius: 5, + }, + }, +}); +exports.NoteCard = function (_a) { + var content = _a.content, published = _a.published, attributedTo = _a.attributedTo; + var classes = useStyles(); + return (React.createElement("div", { className: classes.card }, + React.createElement("div", { className: classes.attribution }, + React.createElement(AttributionTag_1.AttributionTag, { to: attributedTo })), + React.createElement("p", { className: classes.content }, content), + React.createElement(FormattedDate_1.FormattedDate, { className: classes.date, value: published }))); +}; +//# sourceMappingURL=NoteCard.js.map + +/***/ }), + +/***/ "./node_modules/activitystreams-pane/lib/note/index.js": +/*!*************************************************************!*\ + !*** ./node_modules/activitystreams-pane/lib/note/index.js ***! + \*************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +exports.useNote = exports.NoteCard = void 0; +var NoteCard_1 = __webpack_require__(/*! ./NoteCard */ "./node_modules/activitystreams-pane/lib/note/NoteCard.js"); +Object.defineProperty(exports, "NoteCard", { enumerable: true, get: function () { return NoteCard_1.NoteCard; } }); +var useNote_1 = __webpack_require__(/*! ./useNote */ "./node_modules/activitystreams-pane/lib/note/useNote.js"); +Object.defineProperty(exports, "useNote", { enumerable: true, get: function () { return useNote_1.useNote; } }); +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ "./node_modules/activitystreams-pane/lib/note/store/attribution.js": +/*!*************************************************************************!*\ + !*** ./node_modules/activitystreams-pane/lib/note/store/attribution.js ***! + \*************************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __generator = (this && this.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.fetchAttribution = exports.readAttribution = void 0; +var solid_ui_1 = __webpack_require__(/*! solid-ui */ "./node_modules/solid-ui/lib/index.js"); +var rdflib_1 = __webpack_require__(/*! rdflib */ "./node_modules/rdflib/esm/index.js"); +/** + * Constructs an attribution object for the node the subject is attributed to. + */ +function readAttribution(subject, store) { + var attributedTo = store.any(subject, solid_ui_1.ns.as("attributedTo")); + return read(attributedTo, store); +} +exports.readAttribution = readAttribution; +function containsPersonType(types) { + var as = solid_ui_1.ns.as("Person").uri; + var foaf = solid_ui_1.ns.foaf("Person").uri; + var vcard = solid_ui_1.ns.vcard("Individual").uri; + var schema = solid_ui_1.ns.schema("Person").uri; + return types[as] || types[foaf] || types[vcard] || types[schema]; +} +/** + * Constructs an attribution object for the given node with data read from the store + */ +function read(attributedTo, store) { + if (attributedTo instanceof rdflib_1.NamedNode) { + var types = store.findTypeURIs(attributedTo); + if (containsPersonType(types)) { + return readPerson(store, attributedTo); + } + else { + return { + discriminator: "LinkAttribution", + uri: attributedTo.uri, + }; + } + } + return { + discriminator: "NoAttribution", + }; +} +function readPerson(store, attributedTo) { + var name = store.anyValue(attributedTo, solid_ui_1.ns.as("name")) || + store.anyValue(attributedTo, solid_ui_1.ns.foaf("name")) || + store.anyValue(attributedTo, solid_ui_1.ns.vcard("fn")) || + store.anyValue(attributedTo, solid_ui_1.ns.schema("name")) || + ""; + var imageSrc = readImageSrc(store, attributedTo); + return { + discriminator: "PersonAttribution", + webId: attributedTo.uri, + name: name, + imageSrc: imageSrc, + }; +} +function readImageSrc(store, attributedTo) { + var image = store.anyValue(attributedTo, solid_ui_1.ns.as("image")); + if (image) { + return store.anyValue(rdflib_1.sym(image), solid_ui_1.ns.as("url")) || undefined; + } + return (store.anyValue(attributedTo, solid_ui_1.ns.foaf("img")) || + store.anyValue(attributedTo, solid_ui_1.ns.vcard("hasPhoto")) || + undefined); +} +/** + * Fetches the given attribution uri and returns an updated attribution with data from the fetched resource + */ +function fetchAttribution(attribution, store) { + return __awaiter(this, void 0, void 0, function () { + var attributionNode; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + attributionNode = rdflib_1.sym(attribution.uri); + return [4 /*yield*/, store.fetcher.load(attributionNode)]; + case 1: + _a.sent(); + return [2 /*return*/, read(attributionNode, store)]; + } + }); + }); +} +exports.fetchAttribution = fetchAttribution; +//# sourceMappingURL=attribution.js.map + +/***/ }), + +/***/ "./node_modules/activitystreams-pane/lib/note/store/note.js": +/*!******************************************************************!*\ + !*** ./node_modules/activitystreams-pane/lib/note/store/note.js ***! + \******************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +exports.read = void 0; +var solid_ui_1 = __webpack_require__(/*! solid-ui */ "./node_modules/solid-ui/lib/index.js"); +var attribution_1 = __webpack_require__(/*! ./attribution */ "./node_modules/activitystreams-pane/lib/note/store/attribution.js"); +function read(subject, store) { + var content = store.any(subject, solid_ui_1.ns.as("content")); + var published = store.any(subject, solid_ui_1.ns.as("published")); + var attributedTo = attribution_1.readAttribution(subject, store); + if (!content) { + return null; + } + return { + content: content.value, + published: published && new Date(published.value), + attributedTo: attributedTo, + }; +} +exports.read = read; +//# sourceMappingURL=note.js.map + +/***/ }), + +/***/ "./node_modules/activitystreams-pane/lib/note/types.js": +/*!*************************************************************!*\ + !*** ./node_modules/activitystreams-pane/lib/note/types.js ***! + \*************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isPersonAttribution = exports.isLinkAttribution = void 0; +function isLinkAttribution(attribution) { + return attribution.discriminator === "LinkAttribution"; +} +exports.isLinkAttribution = isLinkAttribution; +function isPersonAttribution(attribution) { + return attribution.discriminator === "PersonAttribution"; +} +exports.isPersonAttribution = isPersonAttribution; +//# sourceMappingURL=types.js.map + +/***/ }), + +/***/ "./node_modules/activitystreams-pane/lib/note/useNote.js": +/*!***************************************************************!*\ + !*** ./node_modules/activitystreams-pane/lib/note/useNote.js ***! + \***************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __assign = (this && this.__assign) || function () { + __assign = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __generator = (this && this.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.useNote = void 0; +var note_1 = __webpack_require__(/*! ./store/note */ "./node_modules/activitystreams-pane/lib/note/store/note.js"); +var types_1 = __webpack_require__(/*! ./types */ "./node_modules/activitystreams-pane/lib/note/types.js"); +var react_1 = __webpack_require__(/*! react */ "./node_modules/react/index.js"); +var attribution_1 = __webpack_require__(/*! ./store/attribution */ "./node_modules/activitystreams-pane/lib/note/store/attribution.js"); +exports.useNote = function (subject, store) { + var _a = react_1.useState(note_1.read(subject, store)), note = _a[0], setNote = _a[1]; + react_1.useEffect(function () { + function fetch() { + return __awaiter(this, void 0, void 0, function () { + var attribution; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + if (!types_1.isLinkAttribution(note.attributedTo)) return [3 /*break*/, 2]; + return [4 /*yield*/, attribution_1.fetchAttribution(note.attributedTo, store)]; + case 1: + attribution = _a.sent(); + setNote(__assign(__assign({}, note), { attributedTo: attribution })); + _a.label = 2; + case 2: return [2 /*return*/]; + } + }); + }); + } + fetch(); + }, []); + return note; +}; +//# sourceMappingURL=useNote.js.map + +/***/ }), + +/***/ "./node_modules/async/dist/async.mjs": +/*!*******************************************!*\ + !*** ./node_modules/async/dist/async.mjs ***! + \*******************************************/ +/*! exports provided: default, apply, applyEach, applyEachSeries, asyncify, auto, autoInject, cargo, cargoQueue, compose, concat, concatLimit, concatSeries, constant, detect, detectLimit, detectSeries, dir, doUntil, doWhilst, each, eachLimit, eachOf, eachOfLimit, eachOfSeries, eachSeries, ensureAsync, every, everyLimit, everySeries, filter, filterLimit, filterSeries, forever, groupBy, groupByLimit, groupBySeries, log, map, mapLimit, mapSeries, mapValues, mapValuesLimit, mapValuesSeries, memoize, nextTick, parallel, parallelLimit, priorityQueue, queue, race, reduce, reduceRight, reflect, reflectAll, reject, rejectLimit, rejectSeries, retry, retryable, seq, series, setImmediate, some, someLimit, someSeries, sortBy, timeout, times, timesLimit, timesSeries, transform, tryEach, unmemoize, until, waterfall, whilst, all, allLimit, allSeries, any, anyLimit, anySeries, find, findLimit, findSeries, flatMap, flatMapLimit, flatMapSeries, forEach, forEachSeries, forEachLimit, forEachOf, forEachOfSeries, forEachOfLimit, inject, foldl, foldr, select, selectLimit, selectSeries, wrapSync, during, doDuring */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "apply", function() { return apply; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "applyEach", function() { return applyEach$1; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "applyEachSeries", function() { return applyEachSeries; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "asyncify", function() { return asyncify; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "auto", function() { return auto; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "autoInject", function() { return autoInject; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "cargo", function() { return cargo; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "cargoQueue", function() { return cargo$1; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "compose", function() { return compose; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "concat", function() { return concat$1; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "concatLimit", function() { return concatLimit$1; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "concatSeries", function() { return concatSeries$1; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "constant", function() { return constant; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "detect", function() { return detect$1; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "detectLimit", function() { return detectLimit$1; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "detectSeries", function() { return detectSeries$1; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "dir", function() { return dir; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "doUntil", function() { return doUntil; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "doWhilst", function() { return doWhilst$1; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "each", function() { return each; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "eachLimit", function() { return eachLimit$2; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "eachOf", function() { return eachOf$1; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "eachOfLimit", function() { return eachOfLimit$2; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "eachOfSeries", function() { return eachOfSeries$1; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "eachSeries", function() { return eachSeries$1; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ensureAsync", function() { return ensureAsync; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "every", function() { return every$1; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "everyLimit", function() { return everyLimit$1; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "everySeries", function() { return everySeries$1; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "filter", function() { return filter$1; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "filterLimit", function() { return filterLimit$1; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "filterSeries", function() { return filterSeries$1; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "forever", function() { return forever$1; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "groupBy", function() { return groupBy; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "groupByLimit", function() { return groupByLimit$1; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "groupBySeries", function() { return groupBySeries; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "log", function() { return log; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "map", function() { return map$1; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mapLimit", function() { return mapLimit$1; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mapSeries", function() { return mapSeries$1; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mapValues", function() { return mapValues; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mapValuesLimit", function() { return mapValuesLimit$1; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mapValuesSeries", function() { return mapValuesSeries; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "memoize", function() { return memoize; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "nextTick", function() { return nextTick; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parallel", function() { return parallel; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parallelLimit", function() { return parallelLimit; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "priorityQueue", function() { return priorityQueue; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "queue", function() { return queue$1; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "race", function() { return race$1; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "reduce", function() { return reduce$1; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "reduceRight", function() { return reduceRight; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "reflect", function() { return reflect; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "reflectAll", function() { return reflectAll; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "reject", function() { return reject$2; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "rejectLimit", function() { return rejectLimit$1; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "rejectSeries", function() { return rejectSeries$1; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "retry", function() { return retry; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "retryable", function() { return retryable; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "seq", function() { return seq; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "series", function() { return series; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setImmediate", function() { return setImmediate$1; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "some", function() { return some$1; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "someLimit", function() { return someLimit$1; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "someSeries", function() { return someSeries$1; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sortBy", function() { return sortBy$1; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "timeout", function() { return timeout; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "times", function() { return times; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "timesLimit", function() { return timesLimit; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "timesSeries", function() { return timesSeries; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "transform", function() { return transform; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "tryEach", function() { return tryEach$1; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "unmemoize", function() { return unmemoize; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "until", function() { return until; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "waterfall", function() { return waterfall$1; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "whilst", function() { return whilst$1; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "all", function() { return every$1; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "allLimit", function() { return everyLimit$1; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "allSeries", function() { return everySeries$1; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "any", function() { return some$1; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "anyLimit", function() { return someLimit$1; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "anySeries", function() { return someSeries$1; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "find", function() { return detect$1; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findLimit", function() { return detectLimit$1; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findSeries", function() { return detectSeries$1; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "flatMap", function() { return concat$1; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "flatMapLimit", function() { return concatLimit$1; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "flatMapSeries", function() { return concatSeries$1; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "forEach", function() { return each; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "forEachSeries", function() { return eachSeries$1; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "forEachLimit", function() { return eachLimit$2; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "forEachOf", function() { return eachOf$1; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "forEachOfSeries", function() { return eachOfSeries$1; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "forEachOfLimit", function() { return eachOfLimit$2; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "inject", function() { return reduce$1; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "foldl", function() { return reduce$1; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "foldr", function() { return reduceRight; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "select", function() { return filter$1; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "selectLimit", function() { return filterLimit$1; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "selectSeries", function() { return filterSeries$1; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "wrapSync", function() { return asyncify; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "during", function() { return whilst$1; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "doDuring", function() { return doWhilst$1; }); +/** + * Creates a continuation function with some arguments already applied. + * + * Useful as a shorthand when combined with other control flow functions. Any + * arguments passed to the returned function are added to the arguments + * originally passed to apply. + * + * @name apply + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {Function} fn - The function you want to eventually apply all + * arguments to. Invokes with (arguments...). + * @param {...*} arguments... - Any number of arguments to automatically apply + * when the continuation is called. + * @returns {Function} the partially-applied function + * @example + * + * // using apply + * async.parallel([ + * async.apply(fs.writeFile, 'testfile1', 'test1'), + * async.apply(fs.writeFile, 'testfile2', 'test2') + * ]); + * + * + * // the same process without using apply + * async.parallel([ + * function(callback) { + * fs.writeFile('testfile1', 'test1', callback); + * }, + * function(callback) { + * fs.writeFile('testfile2', 'test2', callback); + * } + * ]); + * + * // It's possible to pass any number of additional arguments when calling the + * // continuation: + * + * node> var fn = async.apply(sys.puts, 'one'); + * node> fn('two', 'three'); + * one + * two + * three + */ +function apply(fn, ...args) { + return (...callArgs) => fn(...args,...callArgs); +} + +function initialParams (fn) { + return function (...args/*, callback*/) { + var callback = args.pop(); + return fn.call(this, args, callback); + }; +} + +/* istanbul ignore file */ + +var hasSetImmediate = typeof setImmediate === 'function' && setImmediate; +var hasNextTick = typeof process === 'object' && typeof process.nextTick === 'function'; + +function fallback(fn) { + setTimeout(fn, 0); +} + +function wrap(defer) { + return (fn, ...args) => defer(() => fn(...args)); +} + +var _defer; + +if (hasSetImmediate) { + _defer = setImmediate; +} else if (hasNextTick) { + _defer = process.nextTick; +} else { + _defer = fallback; +} + +var setImmediate$1 = wrap(_defer); + +/** + * Take a sync function and make it async, passing its return value to a + * callback. This is useful for plugging sync functions into a waterfall, + * series, or other async functions. Any arguments passed to the generated + * function will be passed to the wrapped function (except for the final + * callback argument). Errors thrown will be passed to the callback. + * + * If the function passed to `asyncify` returns a Promise, that promises's + * resolved/rejected state will be used to call the callback, rather than simply + * the synchronous return value. + * + * This also means you can asyncify ES2017 `async` functions. + * + * @name asyncify + * @static + * @memberOf module:Utils + * @method + * @alias wrapSync + * @category Util + * @param {Function} func - The synchronous function, or Promise-returning + * function to convert to an {@link AsyncFunction}. + * @returns {AsyncFunction} An asynchronous wrapper of the `func`. To be + * invoked with `(args..., callback)`. + * @example + * + * // passing a regular synchronous function + * async.waterfall([ + * async.apply(fs.readFile, filename, "utf8"), + * async.asyncify(JSON.parse), + * function (data, next) { + * // data is the result of parsing the text. + * // If there was a parsing error, it would have been caught. + * } + * ], callback); + * + * // passing a function returning a promise + * async.waterfall([ + * async.apply(fs.readFile, filename, "utf8"), + * async.asyncify(function (contents) { + * return db.model.create(contents); + * }), + * function (model, next) { + * // `model` is the instantiated model object. + * // If there was an error, this function would be skipped. + * } + * ], callback); + * + * // es2017 example, though `asyncify` is not needed if your JS environment + * // supports async functions out of the box + * var q = async.queue(async.asyncify(async function(file) { + * var intermediateStep = await processFile(file); + * return await somePromise(intermediateStep) + * })); + * + * q.push(files); + */ +function asyncify(func) { + if (isAsync(func)) { + return function (...args/*, callback*/) { + const callback = args.pop(); + const promise = func.apply(this, args); + return handlePromise(promise, callback) + } + } + + return initialParams(function (args, callback) { + var result; + try { + result = func.apply(this, args); + } catch (e) { + return callback(e); + } + // if result is Promise object + if (result && typeof result.then === 'function') { + return handlePromise(result, callback) + } else { + callback(null, result); + } + }); +} + +function handlePromise(promise, callback) { + return promise.then(value => { + invokeCallback(callback, null, value); + }, err => { + invokeCallback(callback, err && err.message ? err : new Error(err)); + }); +} + +function invokeCallback(callback, error, value) { + try { + callback(error, value); + } catch (err) { + setImmediate$1(e => { throw e }, err); + } +} + +function isAsync(fn) { + return fn[Symbol.toStringTag] === 'AsyncFunction'; +} + +function isAsyncGenerator(fn) { + return fn[Symbol.toStringTag] === 'AsyncGenerator'; +} + +function isAsyncIterable(obj) { + return typeof obj[Symbol.asyncIterator] === 'function'; +} + +function wrapAsync(asyncFn) { + if (typeof asyncFn !== 'function') throw new Error('expected a function') + return isAsync(asyncFn) ? asyncify(asyncFn) : asyncFn; +} + +// conditionally promisify a function. +// only return a promise if a callback is omitted +function awaitify (asyncFn, arity = asyncFn.length) { + if (!arity) throw new Error('arity is undefined') + function awaitable (...args) { + if (typeof args[arity - 1] === 'function') { + return asyncFn.apply(this, args) + } + + return new Promise((resolve, reject) => { + args[arity - 1] = (err, ...cbArgs) => { + if (err) return reject(err) + resolve(cbArgs.length > 1 ? cbArgs : cbArgs[0]); + }; + asyncFn.apply(this, args); + }) + } + + return awaitable +} + +function applyEach (eachfn) { + return function applyEach(fns, ...callArgs) { + const go = awaitify(function (callback) { + var that = this; + return eachfn(fns, (fn, cb) => { + wrapAsync(fn).apply(that, callArgs.concat(cb)); + }, callback); + }); + return go; + }; +} + +function _asyncMap(eachfn, arr, iteratee, callback) { + arr = arr || []; + var results = []; + var counter = 0; + var _iteratee = wrapAsync(iteratee); + + return eachfn(arr, (value, _, iterCb) => { + var index = counter++; + _iteratee(value, (err, v) => { + results[index] = v; + iterCb(err); + }); + }, err => { + callback(err, results); + }); +} + +function isArrayLike(value) { + return value && + typeof value.length === 'number' && + value.length >= 0 && + value.length % 1 === 0; +} + +// A temporary value used to identify if the loop should be broken. +// See #1064, #1293 +const breakLoop = {}; + +function once(fn) { + function wrapper (...args) { + if (fn === null) return; + var callFn = fn; + fn = null; + callFn.apply(this, args); + } + Object.assign(wrapper, fn); + return wrapper +} + +function getIterator (coll) { + return coll[Symbol.iterator] && coll[Symbol.iterator](); +} + +function createArrayIterator(coll) { + var i = -1; + var len = coll.length; + return function next() { + return ++i < len ? {value: coll[i], key: i} : null; + } +} + +function createES2015Iterator(iterator) { + var i = -1; + return function next() { + var item = iterator.next(); + if (item.done) + return null; + i++; + return {value: item.value, key: i}; + } +} + +function createObjectIterator(obj) { + var okeys = obj ? Object.keys(obj) : []; + var i = -1; + var len = okeys.length; + return function next() { + var key = okeys[++i]; + return i < len ? {value: obj[key], key} : null; + }; +} + +function createIterator(coll) { + if (isArrayLike(coll)) { + return createArrayIterator(coll); + } + + var iterator = getIterator(coll); + return iterator ? createES2015Iterator(iterator) : createObjectIterator(coll); +} + +function onlyOnce(fn) { + return function (...args) { + if (fn === null) throw new Error("Callback was already called."); + var callFn = fn; + fn = null; + callFn.apply(this, args); + }; +} + +// for async generators +function asyncEachOfLimit(generator, limit, iteratee, callback) { + let done = false; + let canceled = false; + let awaiting = false; + let running = 0; + let idx = 0; + + function replenish() { + //console.log('replenish') + if (running >= limit || awaiting || done) return + //console.log('replenish awaiting') + awaiting = true; + generator.next().then(({value, done: iterDone}) => { + //console.log('got value', value) + if (canceled || done) return + awaiting = false; + if (iterDone) { + done = true; + if (running <= 0) { + //console.log('done nextCb') + callback(null); + } + return; + } + running++; + iteratee(value, idx, iterateeCallback); + idx++; + replenish(); + }).catch(handleError); + } + + function iterateeCallback(err, result) { + //console.log('iterateeCallback') + running -= 1; + if (canceled) return + if (err) return handleError(err) + + if (err === false) { + done = true; + canceled = true; + return + } + + if (result === breakLoop || (done && running <= 0)) { + done = true; + //console.log('done iterCb') + return callback(null); + } + replenish(); + } + + function handleError(err) { + if (canceled) return + awaiting = false; + done = true; + callback(err); + } + + replenish(); +} + +var eachOfLimit = (limit) => { + return (obj, iteratee, callback) => { + callback = once(callback); + if (limit <= 0) { + throw new RangeError('concurrency limit cannot be less than 1') + } + if (!obj) { + return callback(null); + } + if (isAsyncGenerator(obj)) { + return asyncEachOfLimit(obj, limit, iteratee, callback) + } + if (isAsyncIterable(obj)) { + return asyncEachOfLimit(obj[Symbol.asyncIterator](), limit, iteratee, callback) + } + var nextElem = createIterator(obj); + var done = false; + var canceled = false; + var running = 0; + var looping = false; + + function iterateeCallback(err, value) { + if (canceled) return + running -= 1; + if (err) { + done = true; + callback(err); + } + else if (err === false) { + done = true; + canceled = true; + } + else if (value === breakLoop || (done && running <= 0)) { + done = true; + return callback(null); + } + else if (!looping) { + replenish(); + } + } + + function replenish () { + looping = true; + while (running < limit && !done) { + var elem = nextElem(); + if (elem === null) { + done = true; + if (running <= 0) { + callback(null); + } + return; + } + running += 1; + iteratee(elem.value, elem.key, onlyOnce(iterateeCallback)); + } + looping = false; + } + + replenish(); + }; +}; + +/** + * The same as [`eachOf`]{@link module:Collections.eachOf} but runs a maximum of `limit` async operations at a + * time. + * + * @name eachOfLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.eachOf]{@link module:Collections.eachOf} + * @alias forEachOfLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each + * item in `coll`. The `key` is the item's key, or index in the case of an + * array. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ +function eachOfLimit$1(coll, limit, iteratee, callback) { + return eachOfLimit(limit)(coll, wrapAsync(iteratee), callback); +} + +var eachOfLimit$2 = awaitify(eachOfLimit$1, 4); + +// eachOf implementation optimized for array-likes +function eachOfArrayLike(coll, iteratee, callback) { + callback = once(callback); + var index = 0, + completed = 0, + {length} = coll, + canceled = false; + if (length === 0) { + callback(null); + } + + function iteratorCallback(err, value) { + if (err === false) { + canceled = true; + } + if (canceled === true) return + if (err) { + callback(err); + } else if ((++completed === length) || value === breakLoop) { + callback(null); + } + } + + for (; index < length; index++) { + iteratee(coll[index], index, onlyOnce(iteratorCallback)); + } +} + +// a generic version of eachOf which can handle array, object, and iterator cases. +function eachOfGeneric (coll, iteratee, callback) { + return eachOfLimit$2(coll, Infinity, iteratee, callback); +} + +/** + * Like [`each`]{@link module:Collections.each}, except that it passes the key (or index) as the second argument + * to the iteratee. + * + * @name eachOf + * @static + * @memberOf module:Collections + * @method + * @alias forEachOf + * @category Collection + * @see [async.each]{@link module:Collections.each} + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each + * item in `coll`. + * The `key` is the item's key, or index in the case of an array. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * var obj = {dev: "/dev.json", test: "/test.json", prod: "/prod.json"}; + * var configs = {}; + * + * async.forEachOf(obj, function (value, key, callback) { + * fs.readFile(__dirname + value, "utf8", function (err, data) { + * if (err) return callback(err); + * try { + * configs[key] = JSON.parse(data); + * } catch (e) { + * return callback(e); + * } + * callback(); + * }); + * }, function (err) { + * if (err) console.error(err.message); + * // configs is now a map of JSON data + * doSomethingWith(configs); + * }); + */ +function eachOf(coll, iteratee, callback) { + var eachOfImplementation = isArrayLike(coll) ? eachOfArrayLike : eachOfGeneric; + return eachOfImplementation(coll, wrapAsync(iteratee), callback); +} + +var eachOf$1 = awaitify(eachOf, 3); + +/** + * Produces a new collection of values by mapping each value in `coll` through + * the `iteratee` function. The `iteratee` is called with an item from `coll` + * and a callback for when it has finished processing. Each of these callback + * takes 2 arguments: an `error`, and the transformed item from `coll`. If + * `iteratee` passes an error to its callback, the main `callback` (for the + * `map` function) is immediately called with the error. + * + * Note, that since this function applies the `iteratee` to each item in + * parallel, there is no guarantee that the `iteratee` functions will complete + * in order. However, the results array will be in the same order as the + * original `coll`. + * + * If `map` is passed an Object, the results will be an Array. The results + * will roughly be in the order of the original Objects' keys (but this can + * vary across JavaScript engines). + * + * @name map + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with the transformed item. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Results is an Array of the + * transformed items from the `coll`. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + * @example + * + * async.map(['file1','file2','file3'], fs.stat, function(err, results) { + * // results is now an array of stats for each file + * }); + */ +function map (coll, iteratee, callback) { + return _asyncMap(eachOf$1, coll, iteratee, callback) +} +var map$1 = awaitify(map, 3); + +/** + * Applies the provided arguments to each function in the array, calling + * `callback` after all functions have completed. If you only provide the first + * argument, `fns`, then it will return a function which lets you pass in the + * arguments as if it were a single function call. If more arguments are + * provided, `callback` is required while `args` is still optional. The results + * for each of the applied async functions are passed to the final callback + * as an array. + * + * @name applyEach + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} fns - A collection of {@link AsyncFunction}s + * to all call with the same arguments + * @param {...*} [args] - any number of separate arguments to pass to the + * function. + * @param {Function} [callback] - the final argument should be the callback, + * called when all functions have completed processing. + * @returns {AsyncFunction} - Returns a function that takes no args other than + * an optional callback, that is the result of applying the `args` to each + * of the functions. + * @example + * + * const appliedFn = async.applyEach([enableSearch, updateSchema], 'bucket') + * + * appliedFn((err, results) => { + * // results[0] is the results for `enableSearch` + * // results[1] is the results for `updateSchema` + * }); + * + * // partial application example: + * async.each( + * buckets, + * async (bucket) => async.applyEach([enableSearch, updateSchema], bucket)(), + * callback + * ); + */ +var applyEach$1 = applyEach(map$1); + +/** + * The same as [`eachOf`]{@link module:Collections.eachOf} but runs only a single async operation at a time. + * + * @name eachOfSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.eachOf]{@link module:Collections.eachOf} + * @alias forEachOfSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ +function eachOfSeries(coll, iteratee, callback) { + return eachOfLimit$2(coll, 1, iteratee, callback) +} +var eachOfSeries$1 = awaitify(eachOfSeries, 3); + +/** + * The same as [`map`]{@link module:Collections.map} but runs only a single async operation at a time. + * + * @name mapSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.map]{@link module:Collections.map} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with the transformed item. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Results is an array of the + * transformed items from the `coll`. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + */ +function mapSeries (coll, iteratee, callback) { + return _asyncMap(eachOfSeries$1, coll, iteratee, callback) +} +var mapSeries$1 = awaitify(mapSeries, 3); + +/** + * The same as [`applyEach`]{@link module:ControlFlow.applyEach} but runs only a single async operation at a time. + * + * @name applyEachSeries + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.applyEach]{@link module:ControlFlow.applyEach} + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} fns - A collection of {@link AsyncFunction}s to all + * call with the same arguments + * @param {...*} [args] - any number of separate arguments to pass to the + * function. + * @param {Function} [callback] - the final argument should be the callback, + * called when all functions have completed processing. + * @returns {AsyncFunction} - A function, that when called, is the result of + * appling the `args` to the list of functions. It takes no args, other than + * a callback. + */ +var applyEachSeries = applyEach(mapSeries$1); + +const PROMISE_SYMBOL = Symbol('promiseCallback'); + +function promiseCallback () { + let resolve, reject; + function callback (err, ...args) { + if (err) return reject(err) + resolve(args.length > 1 ? args : args[0]); + } + + callback[PROMISE_SYMBOL] = new Promise((res, rej) => { + resolve = res, + reject = rej; + }); + + return callback +} + +/** + * Determines the best order for running the {@link AsyncFunction}s in `tasks`, based on + * their requirements. Each function can optionally depend on other functions + * being completed first, and each function is run as soon as its requirements + * are satisfied. + * + * If any of the {@link AsyncFunction}s pass an error to their callback, the `auto` sequence + * will stop. Further tasks will not execute (so any other functions depending + * on it will not run), and the main `callback` is immediately called with the + * error. + * + * {@link AsyncFunction}s also receive an object containing the results of functions which + * have completed so far as the first argument, if they have dependencies. If a + * task function has no dependencies, it will only be passed a callback. + * + * @name auto + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Object} tasks - An object. Each of its properties is either a + * function or an array of requirements, with the {@link AsyncFunction} itself the last item + * in the array. The object's key of a property serves as the name of the task + * defined by that property, i.e. can be used when specifying requirements for + * other tasks. The function receives one or two arguments: + * * a `results` object, containing the results of the previously executed + * functions, only passed if the task has any dependencies, + * * a `callback(err, result)` function, which must be called when finished, + * passing an `error` (which can be `null`) and the result of the function's + * execution. + * @param {number} [concurrency=Infinity] - An optional `integer` for + * determining the maximum number of tasks that can be run in parallel. By + * default, as many as possible. + * @param {Function} [callback] - An optional callback which is called when all + * the tasks have been completed. It receives the `err` argument if any `tasks` + * pass an error to their callback. Results are always returned; however, if an + * error occurs, no further `tasks` will be performed, and the results object + * will only contain partial results. Invoked with (err, results). + * @returns {Promise} a promise, if a callback is not passed + * @example + * + * async.auto({ + * // this function will just be passed a callback + * readData: async.apply(fs.readFile, 'data.txt', 'utf-8'), + * showData: ['readData', function(results, cb) { + * // results.readData is the file's contents + * // ... + * }] + * }, callback); + * + * async.auto({ + * get_data: function(callback) { + * console.log('in get_data'); + * // async code to get some data + * callback(null, 'data', 'converted to array'); + * }, + * make_folder: function(callback) { + * console.log('in make_folder'); + * // async code to create a directory to store a file in + * // this is run at the same time as getting the data + * callback(null, 'folder'); + * }, + * write_file: ['get_data', 'make_folder', function(results, callback) { + * console.log('in write_file', JSON.stringify(results)); + * // once there is some data and the directory exists, + * // write the data to a file in the directory + * callback(null, 'filename'); + * }], + * email_link: ['write_file', function(results, callback) { + * console.log('in email_link', JSON.stringify(results)); + * // once the file is written let's email a link to it... + * // results.write_file contains the filename returned by write_file. + * callback(null, {'file':results.write_file, 'email':'user@example.com'}); + * }] + * }, function(err, results) { + * console.log('err = ', err); + * console.log('results = ', results); + * }); + */ +function auto(tasks, concurrency, callback) { + if (typeof concurrency !== 'number') { + // concurrency is optional, shift the args. + callback = concurrency; + concurrency = null; + } + callback = once(callback || promiseCallback()); + var numTasks = Object.keys(tasks).length; + if (!numTasks) { + return callback(null); + } + if (!concurrency) { + concurrency = numTasks; + } + + var results = {}; + var runningTasks = 0; + var canceled = false; + var hasError = false; + + var listeners = Object.create(null); + + var readyTasks = []; + + // for cycle detection: + var readyToCheck = []; // tasks that have been identified as reachable + // without the possibility of returning to an ancestor task + var uncheckedDependencies = {}; + + Object.keys(tasks).forEach(key => { + var task = tasks[key]; + if (!Array.isArray(task)) { + // no dependencies + enqueueTask(key, [task]); + readyToCheck.push(key); + return; + } + + var dependencies = task.slice(0, task.length - 1); + var remainingDependencies = dependencies.length; + if (remainingDependencies === 0) { + enqueueTask(key, task); + readyToCheck.push(key); + return; + } + uncheckedDependencies[key] = remainingDependencies; + + dependencies.forEach(dependencyName => { + if (!tasks[dependencyName]) { + throw new Error('async.auto task `' + key + + '` has a non-existent dependency `' + + dependencyName + '` in ' + + dependencies.join(', ')); + } + addListener(dependencyName, () => { + remainingDependencies--; + if (remainingDependencies === 0) { + enqueueTask(key, task); + } + }); + }); + }); + + checkForDeadlocks(); + processQueue(); + + function enqueueTask(key, task) { + readyTasks.push(() => runTask(key, task)); + } + + function processQueue() { + if (canceled) return + if (readyTasks.length === 0 && runningTasks === 0) { + return callback(null, results); + } + while(readyTasks.length && runningTasks < concurrency) { + var run = readyTasks.shift(); + run(); + } + + } + + function addListener(taskName, fn) { + var taskListeners = listeners[taskName]; + if (!taskListeners) { + taskListeners = listeners[taskName] = []; + } + + taskListeners.push(fn); + } + + function taskComplete(taskName) { + var taskListeners = listeners[taskName] || []; + taskListeners.forEach(fn => fn()); + processQueue(); + } + + + function runTask(key, task) { + if (hasError) return; + + var taskCallback = onlyOnce((err, ...result) => { + runningTasks--; + if (err === false) { + canceled = true; + return + } + if (result.length < 2) { + [result] = result; + } + if (err) { + var safeResults = {}; + Object.keys(results).forEach(rkey => { + safeResults[rkey] = results[rkey]; + }); + safeResults[key] = result; + hasError = true; + listeners = Object.create(null); + if (canceled) return + callback(err, safeResults); + } else { + results[key] = result; + taskComplete(key); + } + }); + + runningTasks++; + var taskFn = wrapAsync(task[task.length - 1]); + if (task.length > 1) { + taskFn(results, taskCallback); + } else { + taskFn(taskCallback); + } + } + + function checkForDeadlocks() { + // Kahn's algorithm + // https://en.wikipedia.org/wiki/Topological_sorting#Kahn.27s_algorithm + // http://connalle.blogspot.com/2013/10/topological-sortingkahn-algorithm.html + var currentTask; + var counter = 0; + while (readyToCheck.length) { + currentTask = readyToCheck.pop(); + counter++; + getDependents(currentTask).forEach(dependent => { + if (--uncheckedDependencies[dependent] === 0) { + readyToCheck.push(dependent); + } + }); + } + + if (counter !== numTasks) { + throw new Error( + 'async.auto cannot execute tasks due to a recursive dependency' + ); + } + } + + function getDependents(taskName) { + var result = []; + Object.keys(tasks).forEach(key => { + const task = tasks[key]; + if (Array.isArray(task) && task.indexOf(taskName) >= 0) { + result.push(key); + } + }); + return result; + } + + return callback[PROMISE_SYMBOL] +} + +var FN_ARGS = /^(?:async\s+)?(?:function)?\s*\w*\s*\(\s*([^)]+)\s*\)(?:\s*{)/; +var ARROW_FN_ARGS = /^(?:async\s+)?\(?\s*([^)=]+)\s*\)?(?:\s*=>)/; +var FN_ARG_SPLIT = /,/; +var FN_ARG = /(=.+)?(\s*)$/; +var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg; + +function parseParams(func) { + const src = func.toString().replace(STRIP_COMMENTS, ''); + let match = src.match(FN_ARGS); + if (!match) { + match = src.match(ARROW_FN_ARGS); + } + if (!match) throw new Error('could not parse args in autoInject\nSource:\n' + src) + let [, args] = match; + return args + .replace(/\s/g, '') + .split(FN_ARG_SPLIT) + .map((arg) => arg.replace(FN_ARG, '').trim()); +} + +/** + * A dependency-injected version of the [async.auto]{@link module:ControlFlow.auto} function. Dependent + * tasks are specified as parameters to the function, after the usual callback + * parameter, with the parameter names matching the names of the tasks it + * depends on. This can provide even more readable task graphs which can be + * easier to maintain. + * + * If a final callback is specified, the task results are similarly injected, + * specified as named parameters after the initial error parameter. + * + * The autoInject function is purely syntactic sugar and its semantics are + * otherwise equivalent to [async.auto]{@link module:ControlFlow.auto}. + * + * @name autoInject + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.auto]{@link module:ControlFlow.auto} + * @category Control Flow + * @param {Object} tasks - An object, each of whose properties is an {@link AsyncFunction} of + * the form 'func([dependencies...], callback). The object's key of a property + * serves as the name of the task defined by that property, i.e. can be used + * when specifying requirements for other tasks. + * * The `callback` parameter is a `callback(err, result)` which must be called + * when finished, passing an `error` (which can be `null`) and the result of + * the function's execution. The remaining parameters name other tasks on + * which the task is dependent, and the results from those tasks are the + * arguments of those parameters. + * @param {Function} [callback] - An optional callback which is called when all + * the tasks have been completed. It receives the `err` argument if any `tasks` + * pass an error to their callback, and a `results` object with any completed + * task results, similar to `auto`. + * @returns {Promise} a promise, if no callback is passed + * @example + * + * // The example from `auto` can be rewritten as follows: + * async.autoInject({ + * get_data: function(callback) { + * // async code to get some data + * callback(null, 'data', 'converted to array'); + * }, + * make_folder: function(callback) { + * // async code to create a directory to store a file in + * // this is run at the same time as getting the data + * callback(null, 'folder'); + * }, + * write_file: function(get_data, make_folder, callback) { + * // once there is some data and the directory exists, + * // write the data to a file in the directory + * callback(null, 'filename'); + * }, + * email_link: function(write_file, callback) { + * // once the file is written let's email a link to it... + * // write_file contains the filename returned by write_file. + * callback(null, {'file':write_file, 'email':'user@example.com'}); + * } + * }, function(err, results) { + * console.log('err = ', err); + * console.log('email_link = ', results.email_link); + * }); + * + * // If you are using a JS minifier that mangles parameter names, `autoInject` + * // will not work with plain functions, since the parameter names will be + * // collapsed to a single letter identifier. To work around this, you can + * // explicitly specify the names of the parameters your task function needs + * // in an array, similar to Angular.js dependency injection. + * + * // This still has an advantage over plain `auto`, since the results a task + * // depends on are still spread into arguments. + * async.autoInject({ + * //... + * write_file: ['get_data', 'make_folder', function(get_data, make_folder, callback) { + * callback(null, 'filename'); + * }], + * email_link: ['write_file', function(write_file, callback) { + * callback(null, {'file':write_file, 'email':'user@example.com'}); + * }] + * //... + * }, function(err, results) { + * console.log('err = ', err); + * console.log('email_link = ', results.email_link); + * }); + */ +function autoInject(tasks, callback) { + var newTasks = {}; + + Object.keys(tasks).forEach(key => { + var taskFn = tasks[key]; + var params; + var fnIsAsync = isAsync(taskFn); + var hasNoDeps = + (!fnIsAsync && taskFn.length === 1) || + (fnIsAsync && taskFn.length === 0); + + if (Array.isArray(taskFn)) { + params = [...taskFn]; + taskFn = params.pop(); + + newTasks[key] = params.concat(params.length > 0 ? newTask : taskFn); + } else if (hasNoDeps) { + // no dependencies, use the function as-is + newTasks[key] = taskFn; + } else { + params = parseParams(taskFn); + if ((taskFn.length === 0 && !fnIsAsync) && params.length === 0) { + throw new Error("autoInject task functions require explicit parameters."); + } + + // remove callback param + if (!fnIsAsync) params.pop(); + + newTasks[key] = params.concat(newTask); + } + + function newTask(results, taskCb) { + var newArgs = params.map(name => results[name]); + newArgs.push(taskCb); + wrapAsync(taskFn)(...newArgs); + } + }); + + return auto(newTasks, callback); +} + +// Simple doubly linked list (https://en.wikipedia.org/wiki/Doubly_linked_list) implementation +// used for queues. This implementation assumes that the node provided by the user can be modified +// to adjust the next and last properties. We implement only the minimal functionality +// for queue support. +class DLL { + constructor() { + this.head = this.tail = null; + this.length = 0; + } + + removeLink(node) { + if (node.prev) node.prev.next = node.next; + else this.head = node.next; + if (node.next) node.next.prev = node.prev; + else this.tail = node.prev; + + node.prev = node.next = null; + this.length -= 1; + return node; + } + + empty () { + while(this.head) this.shift(); + return this; + } + + insertAfter(node, newNode) { + newNode.prev = node; + newNode.next = node.next; + if (node.next) node.next.prev = newNode; + else this.tail = newNode; + node.next = newNode; + this.length += 1; + } + + insertBefore(node, newNode) { + newNode.prev = node.prev; + newNode.next = node; + if (node.prev) node.prev.next = newNode; + else this.head = newNode; + node.prev = newNode; + this.length += 1; + } + + unshift(node) { + if (this.head) this.insertBefore(this.head, node); + else setInitial(this, node); + } + + push(node) { + if (this.tail) this.insertAfter(this.tail, node); + else setInitial(this, node); + } + + shift() { + return this.head && this.removeLink(this.head); + } + + pop() { + return this.tail && this.removeLink(this.tail); + } + + toArray() { + return [...this] + } + + *[Symbol.iterator] () { + var cur = this.head; + while (cur) { + yield cur.data; + cur = cur.next; + } + } + + remove (testFn) { + var curr = this.head; + while(curr) { + var {next} = curr; + if (testFn(curr)) { + this.removeLink(curr); + } + curr = next; + } + return this; + } +} + +function setInitial(dll, node) { + dll.length = 1; + dll.head = dll.tail = node; +} + +function queue(worker, concurrency, payload) { + if (concurrency == null) { + concurrency = 1; + } + else if(concurrency === 0) { + throw new RangeError('Concurrency must not be zero'); + } + + var _worker = wrapAsync(worker); + var numRunning = 0; + var workersList = []; + const events = { + error: [], + drain: [], + saturated: [], + unsaturated: [], + empty: [] + }; + + function on (event, handler) { + events[event].push(handler); + } + + function once (event, handler) { + const handleAndRemove = (...args) => { + off(event, handleAndRemove); + handler(...args); + }; + events[event].push(handleAndRemove); + } + + function off (event, handler) { + if (!event) return Object.keys(events).forEach(ev => events[ev] = []) + if (!handler) return events[event] = [] + events[event] = events[event].filter(ev => ev !== handler); + } + + function trigger (event, ...args) { + events[event].forEach(handler => handler(...args)); + } + + var processingScheduled = false; + function _insert(data, insertAtFront, rejectOnError, callback) { + if (callback != null && typeof callback !== 'function') { + throw new Error('task callback must be a function'); + } + q.started = true; + + var res, rej; + function promiseCallback (err, ...args) { + // we don't care about the error, let the global error handler + // deal with it + if (err) return rejectOnError ? rej(err) : res() + if (args.length <= 1) return res(args[0]) + res(args); + } + + var item = { + data, + callback: rejectOnError ? + promiseCallback : + (callback || promiseCallback) + }; + + if (insertAtFront) { + q._tasks.unshift(item); + } else { + q._tasks.push(item); + } + + if (!processingScheduled) { + processingScheduled = true; + setImmediate$1(() => { + processingScheduled = false; + q.process(); + }); + } + + if (rejectOnError || !callback) { + return new Promise((resolve, reject) => { + res = resolve; + rej = reject; + }) + } + } + + function _createCB(tasks) { + return function (err, ...args) { + numRunning -= 1; + + for (var i = 0, l = tasks.length; i < l; i++) { + var task = tasks[i]; + + var index = workersList.indexOf(task); + if (index === 0) { + workersList.shift(); + } else if (index > 0) { + workersList.splice(index, 1); + } + + task.callback(err, ...args); + + if (err != null) { + trigger('error', err, task.data); + } + } + + if (numRunning <= (q.concurrency - q.buffer) ) { + trigger('unsaturated'); + } + + if (q.idle()) { + trigger('drain'); + } + q.process(); + }; + } + + function _maybeDrain(data) { + if (data.length === 0 && q.idle()) { + // call drain immediately if there are no tasks + setImmediate$1(() => trigger('drain')); + return true + } + return false + } + + const eventMethod = (name) => (handler) => { + if (!handler) { + return new Promise((resolve, reject) => { + once(name, (err, data) => { + if (err) return reject(err) + resolve(data); + }); + }) + } + off(name); + on(name, handler); + + }; + + var isProcessing = false; + var q = { + _tasks: new DLL(), + *[Symbol.iterator] () { + yield* q._tasks[Symbol.iterator](); + }, + concurrency, + payload, + buffer: concurrency / 4, + started: false, + paused: false, + push (data, callback) { + if (Array.isArray(data)) { + if (_maybeDrain(data)) return + return data.map(datum => _insert(datum, false, false, callback)) + } + return _insert(data, false, false, callback); + }, + pushAsync (data, callback) { + if (Array.isArray(data)) { + if (_maybeDrain(data)) return + return data.map(datum => _insert(datum, false, true, callback)) + } + return _insert(data, false, true, callback); + }, + kill () { + off(); + q._tasks.empty(); + }, + unshift (data, callback) { + if (Array.isArray(data)) { + if (_maybeDrain(data)) return + return data.map(datum => _insert(datum, true, false, callback)) + } + return _insert(data, true, false, callback); + }, + unshiftAsync (data, callback) { + if (Array.isArray(data)) { + if (_maybeDrain(data)) return + return data.map(datum => _insert(datum, true, true, callback)) + } + return _insert(data, true, true, callback); + }, + remove (testFn) { + q._tasks.remove(testFn); + }, + process () { + // Avoid trying to start too many processing operations. This can occur + // when callbacks resolve synchronously (#1267). + if (isProcessing) { + return; + } + isProcessing = true; + while(!q.paused && numRunning < q.concurrency && q._tasks.length){ + var tasks = [], data = []; + var l = q._tasks.length; + if (q.payload) l = Math.min(l, q.payload); + for (var i = 0; i < l; i++) { + var node = q._tasks.shift(); + tasks.push(node); + workersList.push(node); + data.push(node.data); + } + + numRunning += 1; + + if (q._tasks.length === 0) { + trigger('empty'); + } + + if (numRunning === q.concurrency) { + trigger('saturated'); + } + + var cb = onlyOnce(_createCB(tasks)); + _worker(data, cb); + } + isProcessing = false; + }, + length () { + return q._tasks.length; + }, + running () { + return numRunning; + }, + workersList () { + return workersList; + }, + idle() { + return q._tasks.length + numRunning === 0; + }, + pause () { + q.paused = true; + }, + resume () { + if (q.paused === false) { return; } + q.paused = false; + setImmediate$1(q.process); + } + }; + // define these as fixed properties, so people get useful errors when updating + Object.defineProperties(q, { + saturated: { + writable: false, + value: eventMethod('saturated') + }, + unsaturated: { + writable: false, + value: eventMethod('unsaturated') + }, + empty: { + writable: false, + value: eventMethod('empty') + }, + drain: { + writable: false, + value: eventMethod('drain') + }, + error: { + writable: false, + value: eventMethod('error') + }, + }); + return q; +} + +/** + * Creates a `cargo` object with the specified payload. Tasks added to the + * cargo will be processed altogether (up to the `payload` limit). If the + * `worker` is in progress, the task is queued until it becomes available. Once + * the `worker` has completed some tasks, each callback of those tasks is + * called. Check out [these](https://camo.githubusercontent.com/6bbd36f4cf5b35a0f11a96dcd2e97711ffc2fb37/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130382f62626330636662302d356632392d313165322d393734662d3333393763363464633835382e676966) [animations](https://camo.githubusercontent.com/f4810e00e1c5f5f8addbe3e9f49064fd5d102699/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130312f38346339323036362d356632392d313165322d383134662d3964336430323431336266642e676966) + * for how `cargo` and `queue` work. + * + * While [`queue`]{@link module:ControlFlow.queue} passes only one task to one of a group of workers + * at a time, cargo passes an array of tasks to a single worker, repeating + * when the worker is finished. + * + * @name cargo + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.queue]{@link module:ControlFlow.queue} + * @category Control Flow + * @param {AsyncFunction} worker - An asynchronous function for processing an array + * of queued tasks. Invoked with `(tasks, callback)`. + * @param {number} [payload=Infinity] - An optional `integer` for determining + * how many tasks should be processed per round; if omitted, the default is + * unlimited. + * @returns {module:ControlFlow.QueueObject} A cargo object to manage the tasks. Callbacks can + * attached as certain properties to listen for specific events during the + * lifecycle of the cargo and inner queue. + * @example + * + * // create a cargo object with payload 2 + * var cargo = async.cargo(function(tasks, callback) { + * for (var i=0; i { + _iteratee(memo, x, (err, v) => { + memo = v; + iterCb(err); + }); + }, err => callback(err, memo)); +} +var reduce$1 = awaitify(reduce, 4); + +/** + * Version of the compose function that is more natural to read. Each function + * consumes the return value of the previous function. It is the equivalent of + * [compose]{@link module:ControlFlow.compose} with the arguments reversed. + * + * Each function is executed with the `this` binding of the composed function. + * + * @name seq + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.compose]{@link module:ControlFlow.compose} + * @category Control Flow + * @param {...AsyncFunction} functions - the asynchronous functions to compose + * @returns {Function} a function that composes the `functions` in order + * @example + * + * // Requires lodash (or underscore), express3 and dresende's orm2. + * // Part of an app, that fetches cats of the logged user. + * // This example uses `seq` function to avoid overnesting and error + * // handling clutter. + * app.get('/cats', function(request, response) { + * var User = request.models.User; + * async.seq( + * _.bind(User.get, User), // 'User.get' has signature (id, callback(err, data)) + * function(user, fn) { + * user.getCats(fn); // 'getCats' has signature (callback(err, data)) + * } + * )(req.session.user_id, function (err, cats) { + * if (err) { + * console.error(err); + * response.json({ status: 'error', message: err.message }); + * } else { + * response.json({ status: 'ok', message: 'Cats found', data: cats }); + * } + * }); + * }); + */ +function seq(...functions) { + var _functions = functions.map(wrapAsync); + return function (...args) { + var that = this; + + var cb = args[args.length - 1]; + if (typeof cb == 'function') { + args.pop(); + } else { + cb = promiseCallback(); + } + + reduce$1(_functions, args, (newargs, fn, iterCb) => { + fn.apply(that, newargs.concat((err, ...nextargs) => { + iterCb(err, nextargs); + })); + }, + (err, results) => cb(err, ...results)); + + return cb[PROMISE_SYMBOL] + }; +} + +/** + * Creates a function which is a composition of the passed asynchronous + * functions. Each function consumes the return value of the function that + * follows. Composing functions `f()`, `g()`, and `h()` would produce the result + * of `f(g(h()))`, only this version uses callbacks to obtain the return values. + * + * If the last argument to the composed function is not a function, a promise + * is returned when you call it. + * + * Each function is executed with the `this` binding of the composed function. + * + * @name compose + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {...AsyncFunction} functions - the asynchronous functions to compose + * @returns {Function} an asynchronous function that is the composed + * asynchronous `functions` + * @example + * + * function add1(n, callback) { + * setTimeout(function () { + * callback(null, n + 1); + * }, 10); + * } + * + * function mul3(n, callback) { + * setTimeout(function () { + * callback(null, n * 3); + * }, 10); + * } + * + * var add1mul3 = async.compose(mul3, add1); + * add1mul3(4, function (err, result) { + * // result now equals 15 + * }); + */ +function compose(...args) { + return seq(...args.reverse()); +} + +/** + * The same as [`map`]{@link module:Collections.map} but runs a maximum of `limit` async operations at a time. + * + * @name mapLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.map]{@link module:Collections.map} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with the transformed item. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Results is an array of the + * transformed items from the `coll`. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + */ +function mapLimit (coll, limit, iteratee, callback) { + return _asyncMap(eachOfLimit(limit), coll, iteratee, callback) +} +var mapLimit$1 = awaitify(mapLimit, 4); + +/** + * The same as [`concat`]{@link module:Collections.concat} but runs a maximum of `limit` async operations at a time. + * + * @name concatLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.concat]{@link module:Collections.concat} + * @category Collection + * @alias flatMapLimit + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`, + * which should use an array as its result. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is an array + * containing the concatenated results of the `iteratee` function. Invoked with + * (err, results). + * @returns A Promise, if no callback is passed + */ +function concatLimit(coll, limit, iteratee, callback) { + var _iteratee = wrapAsync(iteratee); + return mapLimit$1(coll, limit, (val, iterCb) => { + _iteratee(val, (err, ...args) => { + if (err) return iterCb(err); + return iterCb(err, args); + }); + }, (err, mapResults) => { + var result = []; + for (var i = 0; i < mapResults.length; i++) { + if (mapResults[i]) { + result = result.concat(...mapResults[i]); + } + } + + return callback(err, result); + }); +} +var concatLimit$1 = awaitify(concatLimit, 4); + +/** + * Applies `iteratee` to each item in `coll`, concatenating the results. Returns + * the concatenated list. The `iteratee`s are called in parallel, and the + * results are concatenated as they return. The results array will be returned in + * the original order of `coll` passed to the `iteratee` function. + * + * @name concat + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @alias flatMap + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`, + * which should use an array as its result. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is an array + * containing the concatenated results of the `iteratee` function. Invoked with + * (err, results). + * @returns A Promise, if no callback is passed + * @example + * + * async.concat(['dir1','dir2','dir3'], fs.readdir, function(err, files) { + * // files is now a list of filenames that exist in the 3 directories + * }); + */ +function concat(coll, iteratee, callback) { + return concatLimit$1(coll, Infinity, iteratee, callback) +} +var concat$1 = awaitify(concat, 3); + +/** + * The same as [`concat`]{@link module:Collections.concat} but runs only a single async operation at a time. + * + * @name concatSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.concat]{@link module:Collections.concat} + * @category Collection + * @alias flatMapSeries + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`. + * The iteratee should complete with an array an array of results. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is an array + * containing the concatenated results of the `iteratee` function. Invoked with + * (err, results). + * @returns A Promise, if no callback is passed + */ +function concatSeries(coll, iteratee, callback) { + return concatLimit$1(coll, 1, iteratee, callback) +} +var concatSeries$1 = awaitify(concatSeries, 3); + +/** + * Returns a function that when called, calls-back with the values provided. + * Useful as the first function in a [`waterfall`]{@link module:ControlFlow.waterfall}, or for plugging values in to + * [`auto`]{@link module:ControlFlow.auto}. + * + * @name constant + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {...*} arguments... - Any number of arguments to automatically invoke + * callback with. + * @returns {AsyncFunction} Returns a function that when invoked, automatically + * invokes the callback with the previous given arguments. + * @example + * + * async.waterfall([ + * async.constant(42), + * function (value, next) { + * // value === 42 + * }, + * //... + * ], callback); + * + * async.waterfall([ + * async.constant(filename, "utf8"), + * fs.readFile, + * function (fileData, next) { + * //... + * } + * //... + * ], callback); + * + * async.auto({ + * hostname: async.constant("https://server.net/"), + * port: findFreePort, + * launchServer: ["hostname", "port", function (options, cb) { + * startServer(options, cb); + * }], + * //... + * }, callback); + */ +function constant(...args) { + return function (...ignoredArgs/*, callback*/) { + var callback = ignoredArgs.pop(); + return callback(null, ...args); + }; +} + +function _createTester(check, getResult) { + return (eachfn, arr, _iteratee, cb) => { + var testPassed = false; + var testResult; + const iteratee = wrapAsync(_iteratee); + eachfn(arr, (value, _, callback) => { + iteratee(value, (err, result) => { + if (err || err === false) return callback(err); + + if (check(result) && !testResult) { + testPassed = true; + testResult = getResult(true, value); + return callback(null, breakLoop); + } + callback(); + }); + }, err => { + if (err) return cb(err); + cb(null, testPassed ? testResult : getResult(false)); + }); + }; +} + +/** + * Returns the first value in `coll` that passes an async truth test. The + * `iteratee` is applied in parallel, meaning the first iteratee to return + * `true` will fire the detect `callback` with that result. That means the + * result might not be the first item in the original `coll` (in terms of order) + * that passes the test. + + * If order within the original `coll` is important, then look at + * [`detectSeries`]{@link module:Collections.detectSeries}. + * + * @name detect + * @static + * @memberOf module:Collections + * @method + * @alias find + * @category Collections + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. + * The iteratee must complete with a boolean value as its result. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the `iteratee` functions have finished. + * Result will be the first item in the array that passes the truth test + * (iteratee) or the value `undefined` if none passed. Invoked with + * (err, result). + * @returns A Promise, if no callback is passed + * @example + * + * async.detect(['file1','file2','file3'], function(filePath, callback) { + * fs.access(filePath, function(err) { + * callback(null, !err) + * }); + * }, function(err, result) { + * // result now equals the first file in the list that exists + * }); + */ +function detect(coll, iteratee, callback) { + return _createTester(bool => bool, (res, item) => item)(eachOf$1, coll, iteratee, callback) +} +var detect$1 = awaitify(detect, 3); + +/** + * The same as [`detect`]{@link module:Collections.detect} but runs a maximum of `limit` async operations at a + * time. + * + * @name detectLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.detect]{@link module:Collections.detect} + * @alias findLimit + * @category Collections + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. + * The iteratee must complete with a boolean value as its result. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the `iteratee` functions have finished. + * Result will be the first item in the array that passes the truth test + * (iteratee) or the value `undefined` if none passed. Invoked with + * (err, result). + * @returns a Promise if no callback is passed + */ +function detectLimit(coll, limit, iteratee, callback) { + return _createTester(bool => bool, (res, item) => item)(eachOfLimit(limit), coll, iteratee, callback) +} +var detectLimit$1 = awaitify(detectLimit, 4); + +/** + * The same as [`detect`]{@link module:Collections.detect} but runs only a single async operation at a time. + * + * @name detectSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.detect]{@link module:Collections.detect} + * @alias findSeries + * @category Collections + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. + * The iteratee must complete with a boolean value as its result. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the `iteratee` functions have finished. + * Result will be the first item in the array that passes the truth test + * (iteratee) or the value `undefined` if none passed. Invoked with + * (err, result). + * @returns a Promise if no callback is passed + */ +function detectSeries(coll, iteratee, callback) { + return _createTester(bool => bool, (res, item) => item)(eachOfLimit(1), coll, iteratee, callback) +} + +var detectSeries$1 = awaitify(detectSeries, 3); + +function consoleFunc(name) { + return (fn, ...args) => wrapAsync(fn)(...args, (err, ...resultArgs) => { + if (typeof console === 'object') { + if (err) { + if (console.error) { + console.error(err); + } + } else if (console[name]) { + resultArgs.forEach(x => console[name](x)); + } + } + }) +} + +/** + * Logs the result of an [`async` function]{@link AsyncFunction} to the + * `console` using `console.dir` to display the properties of the resulting object. + * Only works in Node.js or in browsers that support `console.dir` and + * `console.error` (such as FF and Chrome). + * If multiple arguments are returned from the async function, + * `console.dir` is called on each argument in order. + * + * @name dir + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} function - The function you want to eventually apply + * all arguments to. + * @param {...*} arguments... - Any number of arguments to apply to the function. + * @example + * + * // in a module + * var hello = function(name, callback) { + * setTimeout(function() { + * callback(null, {hello: name}); + * }, 1000); + * }; + * + * // in the node repl + * node> async.dir(hello, 'world'); + * {hello: 'world'} + */ +var dir = consoleFunc('dir'); + +/** + * The post-check version of [`whilst`]{@link module:ControlFlow.whilst}. To reflect the difference in + * the order of operations, the arguments `test` and `iteratee` are switched. + * + * `doWhilst` is to `whilst` as `do while` is to `while` in plain JavaScript. + * + * @name doWhilst + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.whilst]{@link module:ControlFlow.whilst} + * @category Control Flow + * @param {AsyncFunction} iteratee - A function which is called each time `test` + * passes. Invoked with (callback). + * @param {AsyncFunction} test - asynchronous truth test to perform after each + * execution of `iteratee`. Invoked with (...args, callback), where `...args` are the + * non-error args from the previous callback of `iteratee`. + * @param {Function} [callback] - A callback which is called after the test + * function has failed and repeated execution of `iteratee` has stopped. + * `callback` will be passed an error and any arguments passed to the final + * `iteratee`'s callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if no callback is passed + */ +function doWhilst(iteratee, test, callback) { + callback = onlyOnce(callback); + var _fn = wrapAsync(iteratee); + var _test = wrapAsync(test); + var results; + + function next(err, ...args) { + if (err) return callback(err); + if (err === false) return; + results = args; + _test(...args, check); + } + + function check(err, truth) { + if (err) return callback(err); + if (err === false) return; + if (!truth) return callback(null, ...results); + _fn(next); + } + + return check(null, true); +} + +var doWhilst$1 = awaitify(doWhilst, 3); + +/** + * Like ['doWhilst']{@link module:ControlFlow.doWhilst}, except the `test` is inverted. Note the + * argument ordering differs from `until`. + * + * @name doUntil + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.doWhilst]{@link module:ControlFlow.doWhilst} + * @category Control Flow + * @param {AsyncFunction} iteratee - An async function which is called each time + * `test` fails. Invoked with (callback). + * @param {AsyncFunction} test - asynchronous truth test to perform after each + * execution of `iteratee`. Invoked with (...args, callback), where `...args` are the + * non-error args from the previous callback of `iteratee` + * @param {Function} [callback] - A callback which is called after the test + * function has passed and repeated execution of `iteratee` has stopped. `callback` + * will be passed an error and any arguments passed to the final `iteratee`'s + * callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if no callback is passed + */ +function doUntil(iteratee, test, callback) { + const _test = wrapAsync(test); + return doWhilst$1(iteratee, (...args) => { + const cb = args.pop(); + _test(...args, (err, truth) => cb (err, !truth)); + }, callback); +} + +function _withoutIndex(iteratee) { + return (value, index, callback) => iteratee(value, callback); +} + +/** + * Applies the function `iteratee` to each item in `coll`, in parallel. + * The `iteratee` is called with an item from the list, and a callback for when + * it has finished. If the `iteratee` passes an error to its `callback`, the + * main `callback` (for the `each` function) is immediately called with the + * error. + * + * Note, that since this function applies `iteratee` to each item in parallel, + * there is no guarantee that the iteratee functions will complete in order. + * + * @name each + * @static + * @memberOf module:Collections + * @method + * @alias forEach + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to + * each item in `coll`. Invoked with (item, callback). + * The array index is not passed to the iteratee. + * If you need the index, use `eachOf`. + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * // assuming openFiles is an array of file names and saveFile is a function + * // to save the modified contents of that file: + * + * async.each(openFiles, saveFile, function(err){ + * // if any of the saves produced an error, err would equal that error + * }); + * + * // assuming openFiles is an array of file names + * async.each(openFiles, function(file, callback) { + * + * // Perform operation on file here. + * console.log('Processing file ' + file); + * + * if( file.length > 32 ) { + * console.log('This file name is too long'); + * callback('File name too long'); + * } else { + * // Do work to process file here + * console.log('File processed'); + * callback(); + * } + * }, function(err) { + * // if any of the file processing produced an error, err would equal that error + * if( err ) { + * // One of the iterations produced an error. + * // All processing will now stop. + * console.log('A file failed to process'); + * } else { + * console.log('All files have been processed successfully'); + * } + * }); + */ +function eachLimit(coll, iteratee, callback) { + return eachOf$1(coll, _withoutIndex(wrapAsync(iteratee)), callback); +} + +var each = awaitify(eachLimit, 3); + +/** + * The same as [`each`]{@link module:Collections.each} but runs a maximum of `limit` async operations at a time. + * + * @name eachLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.each]{@link module:Collections.each} + * @alias forEachLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The array index is not passed to the iteratee. + * If you need the index, use `eachOfLimit`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ +function eachLimit$1(coll, limit, iteratee, callback) { + return eachOfLimit(limit)(coll, _withoutIndex(wrapAsync(iteratee)), callback); +} +var eachLimit$2 = awaitify(eachLimit$1, 4); + +/** + * The same as [`each`]{@link module:Collections.each} but runs only a single async operation at a time. + * + * Note, that unlike [`each`]{@link module:Collections.each}, this function applies iteratee to each item + * in series and therefore the iteratee functions will complete in order. + + * @name eachSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.each]{@link module:Collections.each} + * @alias forEachSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each + * item in `coll`. + * The array index is not passed to the iteratee. + * If you need the index, use `eachOfSeries`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ +function eachSeries(coll, iteratee, callback) { + return eachLimit$2(coll, 1, iteratee, callback) +} +var eachSeries$1 = awaitify(eachSeries, 3); + +/** + * Wrap an async function and ensure it calls its callback on a later tick of + * the event loop. If the function already calls its callback on a next tick, + * no extra deferral is added. This is useful for preventing stack overflows + * (`RangeError: Maximum call stack size exceeded`) and generally keeping + * [Zalgo](http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony) + * contained. ES2017 `async` functions are returned as-is -- they are immune + * to Zalgo's corrupting influences, as they always resolve on a later tick. + * + * @name ensureAsync + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} fn - an async function, one that expects a node-style + * callback as its last argument. + * @returns {AsyncFunction} Returns a wrapped function with the exact same call + * signature as the function passed in. + * @example + * + * function sometimesAsync(arg, callback) { + * if (cache[arg]) { + * return callback(null, cache[arg]); // this would be synchronous!! + * } else { + * doSomeIO(arg, callback); // this IO would be asynchronous + * } + * } + * + * // this has a risk of stack overflows if many results are cached in a row + * async.mapSeries(args, sometimesAsync, done); + * + * // this will defer sometimesAsync's callback if necessary, + * // preventing stack overflows + * async.mapSeries(args, async.ensureAsync(sometimesAsync), done); + */ +function ensureAsync(fn) { + if (isAsync(fn)) return fn; + return function (...args/*, callback*/) { + var callback = args.pop(); + var sync = true; + args.push((...innerArgs) => { + if (sync) { + setImmediate$1(() => callback(...innerArgs)); + } else { + callback(...innerArgs); + } + }); + fn.apply(this, args); + sync = false; + }; +} + +/** + * Returns `true` if every element in `coll` satisfies an async test. If any + * iteratee call returns `false`, the main `callback` is immediately called. + * + * @name every + * @static + * @memberOf module:Collections + * @method + * @alias all + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collection in parallel. + * The iteratee must complete with a boolean result value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result will be either `true` or `false` + * depending on the values of the async tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + * @example + * + * async.every(['file1','file2','file3'], function(filePath, callback) { + * fs.access(filePath, function(err) { + * callback(null, !err) + * }); + * }, function(err, result) { + * // if result is true then every file exists + * }); + */ +function every(coll, iteratee, callback) { + return _createTester(bool => !bool, res => !res)(eachOf$1, coll, iteratee, callback) +} +var every$1 = awaitify(every, 3); + +/** + * The same as [`every`]{@link module:Collections.every} but runs a maximum of `limit` async operations at a time. + * + * @name everyLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.every]{@link module:Collections.every} + * @alias allLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collection in parallel. + * The iteratee must complete with a boolean result value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result will be either `true` or `false` + * depending on the values of the async tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ +function everyLimit(coll, limit, iteratee, callback) { + return _createTester(bool => !bool, res => !res)(eachOfLimit(limit), coll, iteratee, callback) +} +var everyLimit$1 = awaitify(everyLimit, 4); + +/** + * The same as [`every`]{@link module:Collections.every} but runs only a single async operation at a time. + * + * @name everySeries + * @static + * @memberOf module:Collections + * @method + * @see [async.every]{@link module:Collections.every} + * @alias allSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collection in series. + * The iteratee must complete with a boolean result value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result will be either `true` or `false` + * depending on the values of the async tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ +function everySeries(coll, iteratee, callback) { + return _createTester(bool => !bool, res => !res)(eachOfSeries$1, coll, iteratee, callback) +} +var everySeries$1 = awaitify(everySeries, 3); + +function filterArray(eachfn, arr, iteratee, callback) { + var truthValues = new Array(arr.length); + eachfn(arr, (x, index, iterCb) => { + iteratee(x, (err, v) => { + truthValues[index] = !!v; + iterCb(err); + }); + }, err => { + if (err) return callback(err); + var results = []; + for (var i = 0; i < arr.length; i++) { + if (truthValues[i]) results.push(arr[i]); + } + callback(null, results); + }); +} + +function filterGeneric(eachfn, coll, iteratee, callback) { + var results = []; + eachfn(coll, (x, index, iterCb) => { + iteratee(x, (err, v) => { + if (err) return iterCb(err); + if (v) { + results.push({index, value: x}); + } + iterCb(err); + }); + }, err => { + if (err) return callback(err); + callback(null, results + .sort((a, b) => a.index - b.index) + .map(v => v.value)); + }); +} + +function _filter(eachfn, coll, iteratee, callback) { + var filter = isArrayLike(coll) ? filterArray : filterGeneric; + return filter(eachfn, coll, wrapAsync(iteratee), callback); +} + +/** + * Returns a new array of all the values in `coll` which pass an async truth + * test. This operation is performed in parallel, but the results array will be + * in the same order as the original. + * + * @name filter + * @static + * @memberOf module:Collections + * @method + * @alias select + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - A truth test to apply to each item in `coll`. + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called + * with a boolean argument once it has completed. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback provided + * @example + * + * async.filter(['file1','file2','file3'], function(filePath, callback) { + * fs.access(filePath, function(err) { + * callback(null, !err) + * }); + * }, function(err, results) { + * // results now equals an array of the existing files + * }); + */ +function filter (coll, iteratee, callback) { + return _filter(eachOf$1, coll, iteratee, callback) +} +var filter$1 = awaitify(filter, 3); + +/** + * The same as [`filter`]{@link module:Collections.filter} but runs a maximum of `limit` async operations at a + * time. + * + * @name filterLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.filter]{@link module:Collections.filter} + * @alias selectLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {Function} iteratee - A truth test to apply to each item in `coll`. + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called + * with a boolean argument once it has completed. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback provided + */ +function filterLimit (coll, limit, iteratee, callback) { + return _filter(eachOfLimit(limit), coll, iteratee, callback) +} +var filterLimit$1 = awaitify(filterLimit, 4); + +/** + * The same as [`filter`]{@link module:Collections.filter} but runs only a single async operation at a time. + * + * @name filterSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.filter]{@link module:Collections.filter} + * @alias selectSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - A truth test to apply to each item in `coll`. + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called + * with a boolean argument once it has completed. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results) + * @returns {Promise} a promise, if no callback provided + */ +function filterSeries (coll, iteratee, callback) { + return _filter(eachOfSeries$1, coll, iteratee, callback) +} +var filterSeries$1 = awaitify(filterSeries, 3); + +/** + * Calls the asynchronous function `fn` with a callback parameter that allows it + * to call itself again, in series, indefinitely. + + * If an error is passed to the callback then `errback` is called with the + * error, and execution stops, otherwise it will never be called. + * + * @name forever + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {AsyncFunction} fn - an async function to call repeatedly. + * Invoked with (next). + * @param {Function} [errback] - when `fn` passes an error to it's callback, + * this function will be called, and execution stops. Invoked with (err). + * @returns {Promise} a promise that rejects if an error occurs and an errback + * is not passed + * @example + * + * async.forever( + * function(next) { + * // next is suitable for passing to things that need a callback(err [, whatever]); + * // it will result in this function being called again. + * }, + * function(err) { + * // if next is called with a value in its first parameter, it will appear + * // in here as 'err', and execution will stop. + * } + * ); + */ +function forever(fn, errback) { + var done = onlyOnce(errback); + var task = wrapAsync(ensureAsync(fn)); + + function next(err) { + if (err) return done(err); + if (err === false) return; + task(next); + } + return next(); +} +var forever$1 = awaitify(forever, 2); + +/** + * The same as [`groupBy`]{@link module:Collections.groupBy} but runs a maximum of `limit` async operations at a time. + * + * @name groupByLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.groupBy]{@link module:Collections.groupBy} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a `key` to group the value under. + * Invoked with (value, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Result is an `Object` whoses + * properties are arrays of values which returned the corresponding key. + * @returns {Promise} a promise, if no callback is passed + */ +function groupByLimit(coll, limit, iteratee, callback) { + var _iteratee = wrapAsync(iteratee); + return mapLimit$1(coll, limit, (val, iterCb) => { + _iteratee(val, (err, key) => { + if (err) return iterCb(err); + return iterCb(err, {key, val}); + }); + }, (err, mapResults) => { + var result = {}; + // from MDN, handle object having an `hasOwnProperty` prop + var {hasOwnProperty} = Object.prototype; + + for (var i = 0; i < mapResults.length; i++) { + if (mapResults[i]) { + var {key} = mapResults[i]; + var {val} = mapResults[i]; + + if (hasOwnProperty.call(result, key)) { + result[key].push(val); + } else { + result[key] = [val]; + } + } + } + + return callback(err, result); + }); +} + +var groupByLimit$1 = awaitify(groupByLimit, 4); + +/** + * Returns a new object, where each value corresponds to an array of items, from + * `coll`, that returned the corresponding key. That is, the keys of the object + * correspond to the values passed to the `iteratee` callback. + * + * Note: Since this function applies the `iteratee` to each item in parallel, + * there is no guarantee that the `iteratee` functions will complete in order. + * However, the values for each key in the `result` will be in the same order as + * the original `coll`. For Objects, the values will roughly be in the order of + * the original Objects' keys (but this can vary across JavaScript engines). + * + * @name groupBy + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a `key` to group the value under. + * Invoked with (value, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Result is an `Object` whoses + * properties are arrays of values which returned the corresponding key. + * @returns {Promise} a promise, if no callback is passed + * @example + * + * async.groupBy(['userId1', 'userId2', 'userId3'], function(userId, callback) { + * db.findById(userId, function(err, user) { + * if (err) return callback(err); + * return callback(null, user.age); + * }); + * }, function(err, result) { + * // result is object containing the userIds grouped by age + * // e.g. { 30: ['userId1', 'userId3'], 42: ['userId2']}; + * }); + */ +function groupBy (coll, iteratee, callback) { + return groupByLimit$1(coll, Infinity, iteratee, callback) +} + +/** + * The same as [`groupBy`]{@link module:Collections.groupBy} but runs only a single async operation at a time. + * + * @name groupBySeries + * @static + * @memberOf module:Collections + * @method + * @see [async.groupBy]{@link module:Collections.groupBy} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a `key` to group the value under. + * Invoked with (value, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Result is an `Object` whoses + * properties are arrays of values which returned the corresponding key. + * @returns {Promise} a promise, if no callback is passed + */ +function groupBySeries (coll, iteratee, callback) { + return groupByLimit$1(coll, 1, iteratee, callback) +} + +/** + * Logs the result of an `async` function to the `console`. Only works in + * Node.js or in browsers that support `console.log` and `console.error` (such + * as FF and Chrome). If multiple arguments are returned from the async + * function, `console.log` is called on each argument in order. + * + * @name log + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} function - The function you want to eventually apply + * all arguments to. + * @param {...*} arguments... - Any number of arguments to apply to the function. + * @example + * + * // in a module + * var hello = function(name, callback) { + * setTimeout(function() { + * callback(null, 'hello ' + name); + * }, 1000); + * }; + * + * // in the node repl + * node> async.log(hello, 'world'); + * 'hello world' + */ +var log = consoleFunc('log'); + +/** + * The same as [`mapValues`]{@link module:Collections.mapValues} but runs a maximum of `limit` async operations at a + * time. + * + * @name mapValuesLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.mapValues]{@link module:Collections.mapValues} + * @category Collection + * @param {Object} obj - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - A function to apply to each value and key + * in `coll`. + * The iteratee should complete with the transformed value as its result. + * Invoked with (value, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. `result` is a new object consisting + * of each key from `obj`, with each transformed value on the right-hand side. + * Invoked with (err, result). + * @returns {Promise} a promise, if no callback is passed + */ +function mapValuesLimit(obj, limit, iteratee, callback) { + callback = once(callback); + var newObj = {}; + var _iteratee = wrapAsync(iteratee); + return eachOfLimit(limit)(obj, (val, key, next) => { + _iteratee(val, key, (err, result) => { + if (err) return next(err); + newObj[key] = result; + next(err); + }); + }, err => callback(err, newObj)); +} + +var mapValuesLimit$1 = awaitify(mapValuesLimit, 4); + +/** + * A relative of [`map`]{@link module:Collections.map}, designed for use with objects. + * + * Produces a new Object by mapping each value of `obj` through the `iteratee` + * function. The `iteratee` is called each `value` and `key` from `obj` and a + * callback for when it has finished processing. Each of these callbacks takes + * two arguments: an `error`, and the transformed item from `obj`. If `iteratee` + * passes an error to its callback, the main `callback` (for the `mapValues` + * function) is immediately called with the error. + * + * Note, the order of the keys in the result is not guaranteed. The keys will + * be roughly in the order they complete, (but this is very engine-specific) + * + * @name mapValues + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Object} obj - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each value and key + * in `coll`. + * The iteratee should complete with the transformed value as its result. + * Invoked with (value, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. `result` is a new object consisting + * of each key from `obj`, with each transformed value on the right-hand side. + * Invoked with (err, result). + * @returns {Promise} a promise, if no callback is passed + * @example + * + * async.mapValues({ + * f1: 'file1', + * f2: 'file2', + * f3: 'file3' + * }, function (file, key, callback) { + * fs.stat(file, callback); + * }, function(err, result) { + * // result is now a map of stats for each file, e.g. + * // { + * // f1: [stats for file1], + * // f2: [stats for file2], + * // f3: [stats for file3] + * // } + * }); + */ +function mapValues(obj, iteratee, callback) { + return mapValuesLimit$1(obj, Infinity, iteratee, callback) +} + +/** + * The same as [`mapValues`]{@link module:Collections.mapValues} but runs only a single async operation at a time. + * + * @name mapValuesSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.mapValues]{@link module:Collections.mapValues} + * @category Collection + * @param {Object} obj - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each value and key + * in `coll`. + * The iteratee should complete with the transformed value as its result. + * Invoked with (value, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. `result` is a new object consisting + * of each key from `obj`, with each transformed value on the right-hand side. + * Invoked with (err, result). + * @returns {Promise} a promise, if no callback is passed + */ +function mapValuesSeries(obj, iteratee, callback) { + return mapValuesLimit$1(obj, 1, iteratee, callback) +} + +/** + * Caches the results of an async function. When creating a hash to store + * function results against, the callback is omitted from the hash and an + * optional hash function can be used. + * + * **Note: if the async function errs, the result will not be cached and + * subsequent calls will call the wrapped function.** + * + * If no hash function is specified, the first argument is used as a hash key, + * which may work reasonably if it is a string or a data type that converts to a + * distinct string. Note that objects and arrays will not behave reasonably. + * Neither will cases where the other arguments are significant. In such cases, + * specify your own hash function. + * + * The cache of results is exposed as the `memo` property of the function + * returned by `memoize`. + * + * @name memoize + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} fn - The async function to proxy and cache results from. + * @param {Function} hasher - An optional function for generating a custom hash + * for storing results. It has all the arguments applied to it apart from the + * callback, and must be synchronous. + * @returns {AsyncFunction} a memoized version of `fn` + * @example + * + * var slow_fn = function(name, callback) { + * // do something + * callback(null, result); + * }; + * var fn = async.memoize(slow_fn); + * + * // fn can now be used as if it were slow_fn + * fn('some name', function() { + * // callback + * }); + */ +function memoize(fn, hasher = v => v) { + var memo = Object.create(null); + var queues = Object.create(null); + var _fn = wrapAsync(fn); + var memoized = initialParams((args, callback) => { + var key = hasher(...args); + if (key in memo) { + setImmediate$1(() => callback(null, ...memo[key])); + } else if (key in queues) { + queues[key].push(callback); + } else { + queues[key] = [callback]; + _fn(...args, (err, ...resultArgs) => { + // #1465 don't memoize if an error occurred + if (!err) { + memo[key] = resultArgs; + } + var q = queues[key]; + delete queues[key]; + for (var i = 0, l = q.length; i < l; i++) { + q[i](err, ...resultArgs); + } + }); + } + }); + memoized.memo = memo; + memoized.unmemoized = fn; + return memoized; +} + +/** + * Calls `callback` on a later loop around the event loop. In Node.js this just + * calls `process.nextTick`. In the browser it will use `setImmediate` if + * available, otherwise `setTimeout(callback, 0)`, which means other higher + * priority events may precede the execution of `callback`. + * + * This is used internally for browser-compatibility purposes. + * + * @name nextTick + * @static + * @memberOf module:Utils + * @method + * @see [async.setImmediate]{@link module:Utils.setImmediate} + * @category Util + * @param {Function} callback - The function to call on a later loop around + * the event loop. Invoked with (args...). + * @param {...*} args... - any number of additional arguments to pass to the + * callback on the next tick. + * @example + * + * var call_order = []; + * async.nextTick(function() { + * call_order.push('two'); + * // call_order now equals ['one','two'] + * }); + * call_order.push('one'); + * + * async.setImmediate(function (a, b, c) { + * // a, b, and c equal 1, 2, and 3 + * }, 1, 2, 3); + */ +var _defer$1; + +if (hasNextTick) { + _defer$1 = process.nextTick; +} else if (hasSetImmediate) { + _defer$1 = setImmediate; +} else { + _defer$1 = fallback; +} + +var nextTick = wrap(_defer$1); + +var _parallel = awaitify((eachfn, tasks, callback) => { + var results = isArrayLike(tasks) ? [] : {}; + + eachfn(tasks, (task, key, taskCb) => { + wrapAsync(task)((err, ...result) => { + if (result.length < 2) { + [result] = result; + } + results[key] = result; + taskCb(err); + }); + }, err => callback(err, results)); +}, 3); + +/** + * Run the `tasks` collection of functions in parallel, without waiting until + * the previous function has completed. If any of the functions pass an error to + * its callback, the main `callback` is immediately called with the value of the + * error. Once the `tasks` have completed, the results are passed to the final + * `callback` as an array. + * + * **Note:** `parallel` is about kicking-off I/O tasks in parallel, not about + * parallel execution of code. If your tasks do not use any timers or perform + * any I/O, they will actually be executed in series. Any synchronous setup + * sections for each task will happen one after the other. JavaScript remains + * single-threaded. + * + * **Hint:** Use [`reflect`]{@link module:Utils.reflect} to continue the + * execution of other tasks when a task fails. + * + * It is also possible to use an object instead of an array. Each property will + * be run as a function and the results will be passed to the final `callback` + * as an object instead of an array. This can be a more readable way of handling + * results from {@link async.parallel}. + * + * @name parallel + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection of + * [async functions]{@link AsyncFunction} to run. + * Each async function can complete with any number of optional `result` values. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed successfully. This function gets a results array + * (or object) containing all the result arguments passed to the task callbacks. + * Invoked with (err, results). + * @returns {Promise} a promise, if a callback is not passed + * + * @example + * async.parallel([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ], + * // optional callback + * function(err, results) { + * // the results array will equal ['one','two'] even though + * // the second function had a shorter timeout. + * }); + * + * // an example using an object instead of an array + * async.parallel({ + * one: function(callback) { + * setTimeout(function() { + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * callback(null, 2); + * }, 100); + * } + * }, function(err, results) { + * // results is now equals to: {one: 1, two: 2} + * }); + */ +function parallel(tasks, callback) { + return _parallel(eachOf$1, tasks, callback); +} + +/** + * The same as [`parallel`]{@link module:ControlFlow.parallel} but runs a maximum of `limit` async operations at a + * time. + * + * @name parallelLimit + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.parallel]{@link module:ControlFlow.parallel} + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection of + * [async functions]{@link AsyncFunction} to run. + * Each async function can complete with any number of optional `result` values. + * @param {number} limit - The maximum number of async operations at a time. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed successfully. This function gets a results array + * (or object) containing all the result arguments passed to the task callbacks. + * Invoked with (err, results). + * @returns {Promise} a promise, if a callback is not passed + */ +function parallelLimit(tasks, limit, callback) { + return _parallel(eachOfLimit(limit), tasks, callback); +} + +/** + * A queue of tasks for the worker function to complete. + * @typedef {Iterable} QueueObject + * @memberOf module:ControlFlow + * @property {Function} length - a function returning the number of items + * waiting to be processed. Invoke with `queue.length()`. + * @property {boolean} started - a boolean indicating whether or not any + * items have been pushed and processed by the queue. + * @property {Function} running - a function returning the number of items + * currently being processed. Invoke with `queue.running()`. + * @property {Function} workersList - a function returning the array of items + * currently being processed. Invoke with `queue.workersList()`. + * @property {Function} idle - a function returning false if there are items + * waiting or being processed, or true if not. Invoke with `queue.idle()`. + * @property {number} concurrency - an integer for determining how many `worker` + * functions should be run in parallel. This property can be changed after a + * `queue` is created to alter the concurrency on-the-fly. + * @property {number} payload - an integer that specifies how many items are + * passed to the worker function at a time. only applies if this is a + * [cargo]{@link module:ControlFlow.cargo} object + * @property {AsyncFunction} push - add a new task to the `queue`. Calls `callback` + * once the `worker` has finished processing the task. Instead of a single task, + * a `tasks` array can be submitted. The respective callback is used for every + * task in the list. Invoke with `queue.push(task, [callback])`, + * @property {AsyncFunction} unshift - add a new task to the front of the `queue`. + * Invoke with `queue.unshift(task, [callback])`. + * @property {AsyncFunction} pushAsync - the same as `q.push`, except this returns + * a promise that rejects if an error occurs. + * @property {AsyncFunction} unshirtAsync - the same as `q.unshift`, except this returns + * a promise that rejects if an error occurs. + * @property {Function} remove - remove items from the queue that match a test + * function. The test function will be passed an object with a `data` property, + * and a `priority` property, if this is a + * [priorityQueue]{@link module:ControlFlow.priorityQueue} object. + * Invoked with `queue.remove(testFn)`, where `testFn` is of the form + * `function ({data, priority}) {}` and returns a Boolean. + * @property {Function} saturated - a function that sets a callback that is + * called when the number of running workers hits the `concurrency` limit, and + * further tasks will be queued. If the callback is omitted, `q.saturated()` + * returns a promise for the next occurrence. + * @property {Function} unsaturated - a function that sets a callback that is + * called when the number of running workers is less than the `concurrency` & + * `buffer` limits, and further tasks will not be queued. If the callback is + * omitted, `q.unsaturated()` returns a promise for the next occurrence. + * @property {number} buffer - A minimum threshold buffer in order to say that + * the `queue` is `unsaturated`. + * @property {Function} empty - a function that sets a callback that is called + * when the last item from the `queue` is given to a `worker`. If the callback + * is omitted, `q.empty()` returns a promise for the next occurrence. + * @property {Function} drain - a function that sets a callback that is called + * when the last item from the `queue` has returned from the `worker`. If the + * callback is omitted, `q.drain()` returns a promise for the next occurrence. + * @property {Function} error - a function that sets a callback that is called + * when a task errors. Has the signature `function(error, task)`. If the + * callback is omitted, `error()` returns a promise that rejects on the next + * error. + * @property {boolean} paused - a boolean for determining whether the queue is + * in a paused state. + * @property {Function} pause - a function that pauses the processing of tasks + * until `resume()` is called. Invoke with `queue.pause()`. + * @property {Function} resume - a function that resumes the processing of + * queued tasks when the queue is paused. Invoke with `queue.resume()`. + * @property {Function} kill - a function that removes the `drain` callback and + * empties remaining tasks from the queue forcing it to go idle. No more tasks + * should be pushed to the queue after calling this function. Invoke with `queue.kill()`. + * + * @example + * const q = aync.queue(worker, 2) + * q.push(item1) + * q.push(item2) + * q.push(item3) + * // queues are iterable, spread into an array to inspect + * const items = [...q] // [item1, item2, item3] + * // or use for of + * for (let item of q) { + * console.log(item) + * } + * + * q.drain(() => { + * console.log('all done') + * }) + * // or + * await q.drain() + */ + +/** + * Creates a `queue` object with the specified `concurrency`. Tasks added to the + * `queue` are processed in parallel (up to the `concurrency` limit). If all + * `worker`s are in progress, the task is queued until one becomes available. + * Once a `worker` completes a `task`, that `task`'s callback is called. + * + * @name queue + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {AsyncFunction} worker - An async function for processing a queued task. + * If you want to handle errors from an individual task, pass a callback to + * `q.push()`. Invoked with (task, callback). + * @param {number} [concurrency=1] - An `integer` for determining how many + * `worker` functions should be run in parallel. If omitted, the concurrency + * defaults to `1`. If the concurrency is `0`, an error is thrown. + * @returns {module:ControlFlow.QueueObject} A queue object to manage the tasks. Callbacks can be + * attached as certain properties to listen for specific events during the + * lifecycle of the queue. + * @example + * + * // create a queue object with concurrency 2 + * var q = async.queue(function(task, callback) { + * console.log('hello ' + task.name); + * callback(); + * }, 2); + * + * // assign a callback + * q.drain(function() { + * console.log('all items have been processed'); + * }); + * // or await the end + * await q.drain() + * + * // assign an error callback + * q.error(function(err, task) { + * console.error('task experienced an error'); + * }); + * + * // add some items to the queue + * q.push({name: 'foo'}, function(err) { + * console.log('finished processing foo'); + * }); + * // callback is optional + * q.push({name: 'bar'}); + * + * // add some items to the queue (batch-wise) + * q.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function(err) { + * console.log('finished processing item'); + * }); + * + * // add some items to the front of the queue + * q.unshift({name: 'bar'}, function (err) { + * console.log('finished processing bar'); + * }); + */ +function queue$1 (worker, concurrency) { + var _worker = wrapAsync(worker); + return queue((items, cb) => { + _worker(items[0], cb); + }, concurrency, 1); +} + +// Binary min-heap implementation used for priority queue. +// Implementation is stable, i.e. push time is considered for equal priorities +class Heap { + constructor() { + this.heap = []; + this.pushCount = Number.MIN_SAFE_INTEGER; + } + + get length() { + return this.heap.length; + } + + empty () { + this.heap = []; + return this; + } + + percUp(index) { + let p; + + while (index > 0 && smaller(this.heap[index], this.heap[p=parent(index)])) { + let t = this.heap[index]; + this.heap[index] = this.heap[p]; + this.heap[p] = t; + + index = p; + } + } + + percDown(index) { + let l; + + while ((l=leftChi(index)) < this.heap.length) { + if (l+1 < this.heap.length && smaller(this.heap[l+1], this.heap[l])) { + l = l+1; + } + + if (smaller(this.heap[index], this.heap[l])) { + break; + } + + let t = this.heap[index]; + this.heap[index] = this.heap[l]; + this.heap[l] = t; + + index = l; + } + } + + push(node) { + node.pushCount = ++this.pushCount; + this.heap.push(node); + this.percUp(this.heap.length-1); + } + + unshift(node) { + return this.heap.push(node); + } + + shift() { + let [top] = this.heap; + + this.heap[0] = this.heap[this.heap.length-1]; + this.heap.pop(); + this.percDown(0); + + return top; + } + + toArray() { + return [...this]; + } + + *[Symbol.iterator] () { + for (let i = 0; i < this.heap.length; i++) { + yield this.heap[i].data; + } + } + + remove (testFn) { + let j = 0; + for (let i = 0; i < this.heap.length; i++) { + if (!testFn(this.heap[i])) { + this.heap[j] = this.heap[i]; + j++; + } + } + + this.heap.splice(j); + + for (let i = parent(this.heap.length-1); i >= 0; i--) { + this.percDown(i); + } + + return this; + } +} + +function leftChi(i) { + return (i<<1)+1; +} + +function parent(i) { + return ((i+1)>>1)-1; +} + +function smaller(x, y) { + if (x.priority !== y.priority) { + return x.priority < y.priority; + } + else { + return x.pushCount < y.pushCount; + } +} + +/** + * The same as [async.queue]{@link module:ControlFlow.queue} only tasks are assigned a priority and + * completed in ascending priority order. + * + * @name priorityQueue + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.queue]{@link module:ControlFlow.queue} + * @category Control Flow + * @param {AsyncFunction} worker - An async function for processing a queued task. + * If you want to handle errors from an individual task, pass a callback to + * `q.push()`. + * Invoked with (task, callback). + * @param {number} concurrency - An `integer` for determining how many `worker` + * functions should be run in parallel. If omitted, the concurrency defaults to + * `1`. If the concurrency is `0`, an error is thrown. + * @returns {module:ControlFlow.QueueObject} A priorityQueue object to manage the tasks. There are two + * differences between `queue` and `priorityQueue` objects: + * * `push(task, priority, [callback])` - `priority` should be a number. If an + * array of `tasks` is given, all tasks will be assigned the same priority. + * * The `unshift` method was removed. + */ +function priorityQueue(worker, concurrency) { + // Start with a normal queue + var q = queue$1(worker, concurrency); + + q._tasks = new Heap(); + + // Override push to accept second parameter representing priority + q.push = function(data, priority = 0, callback = () => {}) { + if (typeof callback !== 'function') { + throw new Error('task callback must be a function'); + } + q.started = true; + if (!Array.isArray(data)) { + data = [data]; + } + if (data.length === 0 && q.idle()) { + // call drain immediately if there are no tasks + return setImmediate$1(() => q.drain()); + } + + for (var i = 0, l = data.length; i < l; i++) { + var item = { + data: data[i], + priority, + callback + }; + + q._tasks.push(item); + } + + setImmediate$1(q.process); + }; + + // Remove unshift function + delete q.unshift; + + return q; +} + +/** + * Runs the `tasks` array of functions in parallel, without waiting until the + * previous function has completed. Once any of the `tasks` complete or pass an + * error to its callback, the main `callback` is immediately called. It's + * equivalent to `Promise.race()`. + * + * @name race + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array} tasks - An array containing [async functions]{@link AsyncFunction} + * to run. Each function can complete with an optional `result` value. + * @param {Function} callback - A callback to run once any of the functions have + * completed. This function gets an error or result from the first function that + * completed. Invoked with (err, result). + * @returns undefined + * @example + * + * async.race([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ], + * // main callback + * function(err, result) { + * // the result will be equal to 'two' as it finishes earlier + * }); + */ +function race(tasks, callback) { + callback = once(callback); + if (!Array.isArray(tasks)) return callback(new TypeError('First argument to race must be an array of functions')); + if (!tasks.length) return callback(); + for (var i = 0, l = tasks.length; i < l; i++) { + wrapAsync(tasks[i])(callback); + } +} + +var race$1 = awaitify(race, 2); + +/** + * Same as [`reduce`]{@link module:Collections.reduce}, only operates on `array` in reverse order. + * + * @name reduceRight + * @static + * @memberOf module:Collections + * @method + * @see [async.reduce]{@link module:Collections.reduce} + * @alias foldr + * @category Collection + * @param {Array} array - A collection to iterate over. + * @param {*} memo - The initial state of the reduction. + * @param {AsyncFunction} iteratee - A function applied to each item in the + * array to produce the next step in the reduction. + * The `iteratee` should complete with the next state of the reduction. + * If the iteratee complete with an error, the reduction is stopped and the + * main `callback` is immediately called with the error. + * Invoked with (memo, item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result is the reduced value. Invoked with + * (err, result). + * @returns {Promise} a promise, if no callback is passed + */ +function reduceRight (array, memo, iteratee, callback) { + var reversed = [...array].reverse(); + return reduce$1(reversed, memo, iteratee, callback); +} + +/** + * Wraps the async function in another function that always completes with a + * result object, even when it errors. + * + * The result object has either the property `error` or `value`. + * + * @name reflect + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} fn - The async function you want to wrap + * @returns {Function} - A function that always passes null to it's callback as + * the error. The second argument to the callback will be an `object` with + * either an `error` or a `value` property. + * @example + * + * async.parallel([ + * async.reflect(function(callback) { + * // do some stuff ... + * callback(null, 'one'); + * }), + * async.reflect(function(callback) { + * // do some more stuff but error ... + * callback('bad stuff happened'); + * }), + * async.reflect(function(callback) { + * // do some more stuff ... + * callback(null, 'two'); + * }) + * ], + * // optional callback + * function(err, results) { + * // values + * // results[0].value = 'one' + * // results[1].error = 'bad stuff happened' + * // results[2].value = 'two' + * }); + */ +function reflect(fn) { + var _fn = wrapAsync(fn); + return initialParams(function reflectOn(args, reflectCallback) { + args.push((error, ...cbArgs) => { + let retVal = {}; + if (error) { + retVal.error = error; + } + if (cbArgs.length > 0){ + var value = cbArgs; + if (cbArgs.length <= 1) { + [value] = cbArgs; + } + retVal.value = value; + } + reflectCallback(null, retVal); + }); + + return _fn.apply(this, args); + }); +} + +/** + * A helper function that wraps an array or an object of functions with `reflect`. + * + * @name reflectAll + * @static + * @memberOf module:Utils + * @method + * @see [async.reflect]{@link module:Utils.reflect} + * @category Util + * @param {Array|Object|Iterable} tasks - The collection of + * [async functions]{@link AsyncFunction} to wrap in `async.reflect`. + * @returns {Array} Returns an array of async functions, each wrapped in + * `async.reflect` + * @example + * + * let tasks = [ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * // do some more stuff but error ... + * callback(new Error('bad stuff happened')); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ]; + * + * async.parallel(async.reflectAll(tasks), + * // optional callback + * function(err, results) { + * // values + * // results[0].value = 'one' + * // results[1].error = Error('bad stuff happened') + * // results[2].value = 'two' + * }); + * + * // an example using an object instead of an array + * let tasks = { + * one: function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * two: function(callback) { + * callback('two'); + * }, + * three: function(callback) { + * setTimeout(function() { + * callback(null, 'three'); + * }, 100); + * } + * }; + * + * async.parallel(async.reflectAll(tasks), + * // optional callback + * function(err, results) { + * // values + * // results.one.value = 'one' + * // results.two.error = 'two' + * // results.three.value = 'three' + * }); + */ +function reflectAll(tasks) { + var results; + if (Array.isArray(tasks)) { + results = tasks.map(reflect); + } else { + results = {}; + Object.keys(tasks).forEach(key => { + results[key] = reflect.call(this, tasks[key]); + }); + } + return results; +} + +function reject(eachfn, arr, _iteratee, callback) { + const iteratee = wrapAsync(_iteratee); + return _filter(eachfn, arr, (value, cb) => { + iteratee(value, (err, v) => { + cb(err, !v); + }); + }, callback); +} + +/** + * The opposite of [`filter`]{@link module:Collections.filter}. Removes values that pass an `async` truth test. + * + * @name reject + * @static + * @memberOf module:Collections + * @method + * @see [async.filter]{@link module:Collections.filter} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - An async truth test to apply to each item in + * `coll`. + * The should complete with a boolean value as its `result`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + * @example + * + * async.reject(['file1','file2','file3'], function(filePath, callback) { + * fs.access(filePath, function(err) { + * callback(null, !err) + * }); + * }, function(err, results) { + * // results now equals an array of missing files + * createFiles(results); + * }); + */ +function reject$1 (coll, iteratee, callback) { + return reject(eachOf$1, coll, iteratee, callback) +} +var reject$2 = awaitify(reject$1, 3); + +/** + * The same as [`reject`]{@link module:Collections.reject} but runs a maximum of `limit` async operations at a + * time. + * + * @name rejectLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.reject]{@link module:Collections.reject} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {Function} iteratee - An async truth test to apply to each item in + * `coll`. + * The should complete with a boolean value as its `result`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + */ +function rejectLimit (coll, limit, iteratee, callback) { + return reject(eachOfLimit(limit), coll, iteratee, callback) +} +var rejectLimit$1 = awaitify(rejectLimit, 4); + +/** + * The same as [`reject`]{@link module:Collections.reject} but runs only a single async operation at a time. + * + * @name rejectSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.reject]{@link module:Collections.reject} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - An async truth test to apply to each item in + * `coll`. + * The should complete with a boolean value as its `result`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + */ +function rejectSeries (coll, iteratee, callback) { + return reject(eachOfSeries$1, coll, iteratee, callback) +} +var rejectSeries$1 = awaitify(rejectSeries, 3); + +function constant$1(value) { + return function () { + return value; + } +} + +/** + * Attempts to get a successful response from `task` no more than `times` times + * before returning an error. If the task is successful, the `callback` will be + * passed the result of the successful task. If all attempts fail, the callback + * will be passed the error and result (if any) of the final attempt. + * + * @name retry + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @see [async.retryable]{@link module:ControlFlow.retryable} + * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - Can be either an + * object with `times` and `interval` or a number. + * * `times` - The number of attempts to make before giving up. The default + * is `5`. + * * `interval` - The time to wait between retries, in milliseconds. The + * default is `0`. The interval may also be specified as a function of the + * retry count (see example). + * * `errorFilter` - An optional synchronous function that is invoked on + * erroneous result. If it returns `true` the retry attempts will continue; + * if the function returns `false` the retry flow is aborted with the current + * attempt's error and result being returned to the final callback. + * Invoked with (err). + * * If `opts` is a number, the number specifies the number of times to retry, + * with the default interval of `0`. + * @param {AsyncFunction} task - An async function to retry. + * Invoked with (callback). + * @param {Function} [callback] - An optional callback which is called when the + * task has succeeded, or after the final failed attempt. It receives the `err` + * and `result` arguments of the last attempt at completing the `task`. Invoked + * with (err, results). + * @returns {Promise} a promise if no callback provided + * + * @example + * + * // The `retry` function can be used as a stand-alone control flow by passing + * // a callback, as shown below: + * + * // try calling apiMethod 3 times + * async.retry(3, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod 3 times, waiting 200 ms between each retry + * async.retry({times: 3, interval: 200}, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod 10 times with exponential backoff + * // (i.e. intervals of 100, 200, 400, 800, 1600, ... milliseconds) + * async.retry({ + * times: 10, + * interval: function(retryCount) { + * return 50 * Math.pow(2, retryCount); + * } + * }, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod the default 5 times no delay between each retry + * async.retry(apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod only when error condition satisfies, all other + * // errors will abort the retry control flow and return to final callback + * async.retry({ + * errorFilter: function(err) { + * return err.message === 'Temporary error'; // only retry on a specific error + * } + * }, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // to retry individual methods that are not as reliable within other + * // control flow functions, use the `retryable` wrapper: + * async.auto({ + * users: api.getUsers.bind(api), + * payments: async.retryable(3, api.getPayments.bind(api)) + * }, function(err, results) { + * // do something with the results + * }); + * + */ +const DEFAULT_TIMES = 5; +const DEFAULT_INTERVAL = 0; + +function retry(opts, task, callback) { + var options = { + times: DEFAULT_TIMES, + intervalFunc: constant$1(DEFAULT_INTERVAL) + }; + + if (arguments.length < 3 && typeof opts === 'function') { + callback = task || promiseCallback(); + task = opts; + } else { + parseTimes(options, opts); + callback = callback || promiseCallback(); + } + + if (typeof task !== 'function') { + throw new Error("Invalid arguments for async.retry"); + } + + var _task = wrapAsync(task); + + var attempt = 1; + function retryAttempt() { + _task((err, ...args) => { + if (err === false) return + if (err && attempt++ < options.times && + (typeof options.errorFilter != 'function' || + options.errorFilter(err))) { + setTimeout(retryAttempt, options.intervalFunc(attempt - 1)); + } else { + callback(err, ...args); + } + }); + } + + retryAttempt(); + return callback[PROMISE_SYMBOL] +} + +function parseTimes(acc, t) { + if (typeof t === 'object') { + acc.times = +t.times || DEFAULT_TIMES; + + acc.intervalFunc = typeof t.interval === 'function' ? + t.interval : + constant$1(+t.interval || DEFAULT_INTERVAL); + + acc.errorFilter = t.errorFilter; + } else if (typeof t === 'number' || typeof t === 'string') { + acc.times = +t || DEFAULT_TIMES; + } else { + throw new Error("Invalid arguments for async.retry"); + } +} + +/** + * A close relative of [`retry`]{@link module:ControlFlow.retry}. This method + * wraps a task and makes it retryable, rather than immediately calling it + * with retries. + * + * @name retryable + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.retry]{@link module:ControlFlow.retry} + * @category Control Flow + * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - optional + * options, exactly the same as from `retry`, except for a `opts.arity` that + * is the arity of the `task` function, defaulting to `task.length` + * @param {AsyncFunction} task - the asynchronous function to wrap. + * This function will be passed any arguments passed to the returned wrapper. + * Invoked with (...args, callback). + * @returns {AsyncFunction} The wrapped function, which when invoked, will + * retry on an error, based on the parameters specified in `opts`. + * This function will accept the same parameters as `task`. + * @example + * + * async.auto({ + * dep1: async.retryable(3, getFromFlakyService), + * process: ["dep1", async.retryable(3, function (results, cb) { + * maybeProcessData(results.dep1, cb); + * })] + * }, callback); + */ +function retryable (opts, task) { + if (!task) { + task = opts; + opts = null; + } + let arity = (opts && opts.arity) || task.length; + if (isAsync(task)) { + arity += 1; + } + var _task = wrapAsync(task); + return initialParams((args, callback) => { + if (args.length < arity - 1 || callback == null) { + args.push(callback); + callback = promiseCallback(); + } + function taskFn(cb) { + _task(...args, cb); + } + + if (opts) retry(opts, taskFn, callback); + else retry(taskFn, callback); + + return callback[PROMISE_SYMBOL] + }); +} + +/** + * Run the functions in the `tasks` collection in series, each one running once + * the previous function has completed. If any functions in the series pass an + * error to its callback, no more functions are run, and `callback` is + * immediately called with the value of the error. Otherwise, `callback` + * receives an array of results when `tasks` have completed. + * + * It is also possible to use an object instead of an array. Each property will + * be run as a function, and the results will be passed to the final `callback` + * as an object instead of an array. This can be a more readable way of handling + * results from {@link async.series}. + * + * **Note** that while many implementations preserve the order of object + * properties, the [ECMAScript Language Specification](http://www.ecma-international.org/ecma-262/5.1/#sec-8.6) + * explicitly states that + * + * > The mechanics and order of enumerating the properties is not specified. + * + * So if you rely on the order in which your series of functions are executed, + * and want this to work on all platforms, consider using an array. + * + * @name series + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection containing + * [async functions]{@link AsyncFunction} to run in series. + * Each function can complete with any number of optional `result` values. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed. This function gets a results array (or object) + * containing all the result arguments passed to the `task` callbacks. Invoked + * with (err, result). + * @return {Promise} a promise, if no callback is passed + * @example + * async.series([ + * function(callback) { + * // do some stuff ... + * callback(null, 'one'); + * }, + * function(callback) { + * // do some more stuff ... + * callback(null, 'two'); + * } + * ], + * // optional callback + * function(err, results) { + * // results is now equal to ['one', 'two'] + * }); + * + * async.series({ + * one: function(callback) { + * setTimeout(function() { + * callback(null, 1); + * }, 200); + * }, + * two: function(callback){ + * setTimeout(function() { + * callback(null, 2); + * }, 100); + * } + * }, function(err, results) { + * // results is now equal to: {one: 1, two: 2} + * }); + */ +function series(tasks, callback) { + return _parallel(eachOfSeries$1, tasks, callback); +} + +/** + * Returns `true` if at least one element in the `coll` satisfies an async test. + * If any iteratee call returns `true`, the main `callback` is immediately + * called. + * + * @name some + * @static + * @memberOf module:Collections + * @method + * @alias any + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collections in parallel. + * The iteratee should complete with a boolean `result` value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the iteratee functions have finished. + * Result will be either `true` or `false` depending on the values of the async + * tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + * @example + * + * async.some(['file1','file2','file3'], function(filePath, callback) { + * fs.access(filePath, function(err) { + * callback(null, !err) + * }); + * }, function(err, result) { + * // if result is true then at least one of the files exists + * }); + */ +function some(coll, iteratee, callback) { + return _createTester(Boolean, res => res)(eachOf$1, coll, iteratee, callback) +} +var some$1 = awaitify(some, 3); + +/** + * The same as [`some`]{@link module:Collections.some} but runs a maximum of `limit` async operations at a time. + * + * @name someLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.some]{@link module:Collections.some} + * @alias anyLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collections in parallel. + * The iteratee should complete with a boolean `result` value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the iteratee functions have finished. + * Result will be either `true` or `false` depending on the values of the async + * tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ +function someLimit(coll, limit, iteratee, callback) { + return _createTester(Boolean, res => res)(eachOfLimit(limit), coll, iteratee, callback) +} +var someLimit$1 = awaitify(someLimit, 4); + +/** + * The same as [`some`]{@link module:Collections.some} but runs only a single async operation at a time. + * + * @name someSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.some]{@link module:Collections.some} + * @alias anySeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collections in series. + * The iteratee should complete with a boolean `result` value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the iteratee functions have finished. + * Result will be either `true` or `false` depending on the values of the async + * tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ +function someSeries(coll, iteratee, callback) { + return _createTester(Boolean, res => res)(eachOfSeries$1, coll, iteratee, callback) +} +var someSeries$1 = awaitify(someSeries, 3); + +/** + * Sorts a list by the results of running each `coll` value through an async + * `iteratee`. + * + * @name sortBy + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a value to use as the sort criteria as + * its `result`. + * Invoked with (item, callback). + * @param {Function} callback - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is the items + * from the original `coll` sorted by the values returned by the `iteratee` + * calls. Invoked with (err, results). + * @returns {Promise} a promise, if no callback passed + * @example + * + * async.sortBy(['file1','file2','file3'], function(file, callback) { + * fs.stat(file, function(err, stats) { + * callback(err, stats.mtime); + * }); + * }, function(err, results) { + * // results is now the original array of files sorted by + * // modified date + * }); + * + * // By modifying the callback parameter the + * // sorting order can be influenced: + * + * // ascending order + * async.sortBy([1,9,3,5], function(x, callback) { + * callback(null, x); + * }, function(err,result) { + * // result callback + * }); + * + * // descending order + * async.sortBy([1,9,3,5], function(x, callback) { + * callback(null, x*-1); //<- x*-1 instead of x, turns the order around + * }, function(err,result) { + * // result callback + * }); + */ +function sortBy (coll, iteratee, callback) { + var _iteratee = wrapAsync(iteratee); + return map$1(coll, (x, iterCb) => { + _iteratee(x, (err, criteria) => { + if (err) return iterCb(err); + iterCb(err, {value: x, criteria}); + }); + }, (err, results) => { + if (err) return callback(err); + callback(null, results.sort(comparator).map(v => v.value)); + }); + + function comparator(left, right) { + var a = left.criteria, b = right.criteria; + return a < b ? -1 : a > b ? 1 : 0; + } +} +var sortBy$1 = awaitify(sortBy, 3); + +/** + * Sets a time limit on an asynchronous function. If the function does not call + * its callback within the specified milliseconds, it will be called with a + * timeout error. The code property for the error object will be `'ETIMEDOUT'`. + * + * @name timeout + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} asyncFn - The async function to limit in time. + * @param {number} milliseconds - The specified time limit. + * @param {*} [info] - Any variable you want attached (`string`, `object`, etc) + * to timeout Error for more information.. + * @returns {AsyncFunction} Returns a wrapped function that can be used with any + * of the control flow functions. + * Invoke this function with the same parameters as you would `asyncFunc`. + * @example + * + * function myFunction(foo, callback) { + * doAsyncTask(foo, function(err, data) { + * // handle errors + * if (err) return callback(err); + * + * // do some stuff ... + * + * // return processed data + * return callback(null, data); + * }); + * } + * + * var wrapped = async.timeout(myFunction, 1000); + * + * // call `wrapped` as you would `myFunction` + * wrapped({ bar: 'bar' }, function(err, data) { + * // if `myFunction` takes < 1000 ms to execute, `err` + * // and `data` will have their expected values + * + * // else `err` will be an Error with the code 'ETIMEDOUT' + * }); + */ +function timeout(asyncFn, milliseconds, info) { + var fn = wrapAsync(asyncFn); + + return initialParams((args, callback) => { + var timedOut = false; + var timer; + + function timeoutCallback() { + var name = asyncFn.name || 'anonymous'; + var error = new Error('Callback function "' + name + '" timed out.'); + error.code = 'ETIMEDOUT'; + if (info) { + error.info = info; + } + timedOut = true; + callback(error); + } + + args.push((...cbArgs) => { + if (!timedOut) { + callback(...cbArgs); + clearTimeout(timer); + } + }); + + // setup timer and call original function + timer = setTimeout(timeoutCallback, milliseconds); + fn(...args); + }); +} + +function range(size) { + var result = Array(size); + while (size--) { + result[size] = size; + } + return result; +} + +/** + * The same as [times]{@link module:ControlFlow.times} but runs a maximum of `limit` async operations at a + * time. + * + * @name timesLimit + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.times]{@link module:ControlFlow.times} + * @category Control Flow + * @param {number} count - The number of times to run the function. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - The async function to call `n` times. + * Invoked with the iteration index and a callback: (n, next). + * @param {Function} callback - see [async.map]{@link module:Collections.map}. + * @returns {Promise} a promise, if no callback is provided + */ +function timesLimit(count, limit, iteratee, callback) { + var _iteratee = wrapAsync(iteratee); + return mapLimit$1(range(count), limit, _iteratee, callback); +} + +/** + * Calls the `iteratee` function `n` times, and accumulates results in the same + * manner you would use with [map]{@link module:Collections.map}. + * + * @name times + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.map]{@link module:Collections.map} + * @category Control Flow + * @param {number} n - The number of times to run the function. + * @param {AsyncFunction} iteratee - The async function to call `n` times. + * Invoked with the iteration index and a callback: (n, next). + * @param {Function} callback - see {@link module:Collections.map}. + * @returns {Promise} a promise, if no callback is provided + * @example + * + * // Pretend this is some complicated async factory + * var createUser = function(id, callback) { + * callback(null, { + * id: 'user' + id + * }); + * }; + * + * // generate 5 users + * async.times(5, function(n, next) { + * createUser(n, function(err, user) { + * next(err, user); + * }); + * }, function(err, users) { + * // we should now have 5 users + * }); + */ +function times (n, iteratee, callback) { + return timesLimit(n, Infinity, iteratee, callback) +} + +/** + * The same as [times]{@link module:ControlFlow.times} but runs only a single async operation at a time. + * + * @name timesSeries + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.times]{@link module:ControlFlow.times} + * @category Control Flow + * @param {number} n - The number of times to run the function. + * @param {AsyncFunction} iteratee - The async function to call `n` times. + * Invoked with the iteration index and a callback: (n, next). + * @param {Function} callback - see {@link module:Collections.map}. + * @returns {Promise} a promise, if no callback is provided + */ +function timesSeries (n, iteratee, callback) { + return timesLimit(n, 1, iteratee, callback) +} + +/** + * A relative of `reduce`. Takes an Object or Array, and iterates over each + * element in parallel, each step potentially mutating an `accumulator` value. + * The type of the accumulator defaults to the type of collection passed in. + * + * @name transform + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {*} [accumulator] - The initial state of the transform. If omitted, + * it will default to an empty Object or Array, depending on the type of `coll` + * @param {AsyncFunction} iteratee - A function applied to each item in the + * collection that potentially modifies the accumulator. + * Invoked with (accumulator, item, key, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result is the transformed accumulator. + * Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + * @example + * + * async.transform([1,2,3], function(acc, item, index, callback) { + * // pointless async: + * process.nextTick(function() { + * acc[index] = item * 2 + * callback(null) + * }); + * }, function(err, result) { + * // result is now equal to [2, 4, 6] + * }); + * + * @example + * + * async.transform({a: 1, b: 2, c: 3}, function (obj, val, key, callback) { + * setImmediate(function () { + * obj[key] = val * 2; + * callback(); + * }) + * }, function (err, result) { + * // result is equal to {a: 2, b: 4, c: 6} + * }) + */ +function transform (coll, accumulator, iteratee, callback) { + if (arguments.length <= 3 && typeof accumulator === 'function') { + callback = iteratee; + iteratee = accumulator; + accumulator = Array.isArray(coll) ? [] : {}; + } + callback = once(callback || promiseCallback()); + var _iteratee = wrapAsync(iteratee); + + eachOf$1(coll, (v, k, cb) => { + _iteratee(accumulator, v, k, cb); + }, err => callback(err, accumulator)); + return callback[PROMISE_SYMBOL] +} + +/** + * It runs each task in series but stops whenever any of the functions were + * successful. If one of the tasks were successful, the `callback` will be + * passed the result of the successful task. If all tasks fail, the callback + * will be passed the error and result (if any) of the final attempt. + * + * @name tryEach + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection containing functions to + * run, each function is passed a `callback(err, result)` it must call on + * completion with an error `err` (which can be `null`) and an optional `result` + * value. + * @param {Function} [callback] - An optional callback which is called when one + * of the tasks has succeeded, or all have failed. It receives the `err` and + * `result` arguments of the last attempt at completing the `task`. Invoked with + * (err, results). + * @returns {Promise} a promise, if no callback is passed + * @example + * async.tryEach([ + * function getDataFromFirstWebsite(callback) { + * // Try getting the data from the first website + * callback(err, data); + * }, + * function getDataFromSecondWebsite(callback) { + * // First website failed, + * // Try getting the data from the backup website + * callback(err, data); + * } + * ], + * // optional callback + * function(err, results) { + * Now do something with the data. + * }); + * + */ +function tryEach(tasks, callback) { + var error = null; + var result; + return eachSeries$1(tasks, (task, taskCb) => { + wrapAsync(task)((err, ...args) => { + if (err === false) return taskCb(err); + + if (args.length < 2) { + [result] = args; + } else { + result = args; + } + error = err; + taskCb(err ? null : {}); + }); + }, () => callback(error, result)); +} + +var tryEach$1 = awaitify(tryEach); + +/** + * Undoes a [memoize]{@link module:Utils.memoize}d function, reverting it to the original, + * unmemoized form. Handy for testing. + * + * @name unmemoize + * @static + * @memberOf module:Utils + * @method + * @see [async.memoize]{@link module:Utils.memoize} + * @category Util + * @param {AsyncFunction} fn - the memoized function + * @returns {AsyncFunction} a function that calls the original unmemoized function + */ +function unmemoize(fn) { + return (...args) => { + return (fn.unmemoized || fn)(...args); + }; +} + +/** + * Repeatedly call `iteratee`, while `test` returns `true`. Calls `callback` when + * stopped, or an error occurs. + * + * @name whilst + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {AsyncFunction} test - asynchronous truth test to perform before each + * execution of `iteratee`. Invoked with (). + * @param {AsyncFunction} iteratee - An async function which is called each time + * `test` passes. Invoked with (callback). + * @param {Function} [callback] - A callback which is called after the test + * function has failed and repeated execution of `iteratee` has stopped. `callback` + * will be passed an error and any arguments passed to the final `iteratee`'s + * callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if no callback is passed + * @example + * + * var count = 0; + * async.whilst( + * function test(cb) { cb(null, count < 5); }, + * function iter(callback) { + * count++; + * setTimeout(function() { + * callback(null, count); + * }, 1000); + * }, + * function (err, n) { + * // 5 seconds have passed, n = 5 + * } + * ); + */ +function whilst(test, iteratee, callback) { + callback = onlyOnce(callback); + var _fn = wrapAsync(iteratee); + var _test = wrapAsync(test); + var results = []; + + function next(err, ...rest) { + if (err) return callback(err); + results = rest; + if (err === false) return; + _test(check); + } + + function check(err, truth) { + if (err) return callback(err); + if (err === false) return; + if (!truth) return callback(null, ...results); + _fn(next); + } + + return _test(check); +} +var whilst$1 = awaitify(whilst, 3); + +/** + * Repeatedly call `iteratee` until `test` returns `true`. Calls `callback` when + * stopped, or an error occurs. `callback` will be passed an error and any + * arguments passed to the final `iteratee`'s callback. + * + * The inverse of [whilst]{@link module:ControlFlow.whilst}. + * + * @name until + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.whilst]{@link module:ControlFlow.whilst} + * @category Control Flow + * @param {AsyncFunction} test - asynchronous truth test to perform before each + * execution of `iteratee`. Invoked with (callback). + * @param {AsyncFunction} iteratee - An async function which is called each time + * `test` fails. Invoked with (callback). + * @param {Function} [callback] - A callback which is called after the test + * function has passed and repeated execution of `iteratee` has stopped. `callback` + * will be passed an error and any arguments passed to the final `iteratee`'s + * callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if a callback is not passed + * + * @example + * const results = [] + * let finished = false + * async.until(function test(page, cb) { + * cb(null, finished) + * }, function iter(next) { + * fetchPage(url, (err, body) => { + * if (err) return next(err) + * results = results.concat(body.objects) + * finished = !!body.next + * next(err) + * }) + * }, function done (err) { + * // all pages have been fetched + * }) + */ +function until(test, iteratee, callback) { + const _test = wrapAsync(test); + return whilst$1((cb) => _test((err, truth) => cb (err, !truth)), iteratee, callback); +} + +/** + * Runs the `tasks` array of functions in series, each passing their results to + * the next in the array. However, if any of the `tasks` pass an error to their + * own callback, the next function is not executed, and the main `callback` is + * immediately called with the error. + * + * @name waterfall + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array} tasks - An array of [async functions]{@link AsyncFunction} + * to run. + * Each function should complete with any number of `result` values. + * The `result` values will be passed as arguments, in order, to the next task. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed. This will be passed the results of the last task's + * callback. Invoked with (err, [results]). + * @returns undefined + * @example + * + * async.waterfall([ + * function(callback) { + * callback(null, 'one', 'two'); + * }, + * function(arg1, arg2, callback) { + * // arg1 now equals 'one' and arg2 now equals 'two' + * callback(null, 'three'); + * }, + * function(arg1, callback) { + * // arg1 now equals 'three' + * callback(null, 'done'); + * } + * ], function (err, result) { + * // result now equals 'done' + * }); + * + * // Or, with named functions: + * async.waterfall([ + * myFirstFunction, + * mySecondFunction, + * myLastFunction, + * ], function (err, result) { + * // result now equals 'done' + * }); + * function myFirstFunction(callback) { + * callback(null, 'one', 'two'); + * } + * function mySecondFunction(arg1, arg2, callback) { + * // arg1 now equals 'one' and arg2 now equals 'two' + * callback(null, 'three'); + * } + * function myLastFunction(arg1, callback) { + * // arg1 now equals 'three' + * callback(null, 'done'); + * } + */ +function waterfall (tasks, callback) { + callback = once(callback); + if (!Array.isArray(tasks)) return callback(new Error('First argument to waterfall must be an array of functions')); + if (!tasks.length) return callback(); + var taskIndex = 0; + + function nextTask(args) { + var task = wrapAsync(tasks[taskIndex++]); + task(...args, onlyOnce(next)); + } + + function next(err, ...args) { + if (err === false) return + if (err || taskIndex === tasks.length) { + return callback(err, ...args); + } + nextTask(args); + } + + nextTask([]); +} + +var waterfall$1 = awaitify(waterfall); + +/** + * An "async function" in the context of Async is an asynchronous function with + * a variable number of parameters, with the final parameter being a callback. + * (`function (arg1, arg2, ..., callback) {}`) + * The final callback is of the form `callback(err, results...)`, which must be + * called once the function is completed. The callback should be called with a + * Error as its first argument to signal that an error occurred. + * Otherwise, if no error occurred, it should be called with `null` as the first + * argument, and any additional `result` arguments that may apply, to signal + * successful completion. + * The callback must be called exactly once, ideally on a later tick of the + * JavaScript event loop. + * + * This type of function is also referred to as a "Node-style async function", + * or a "continuation passing-style function" (CPS). Most of the methods of this + * library are themselves CPS/Node-style async functions, or functions that + * return CPS/Node-style async functions. + * + * Wherever we accept a Node-style async function, we also directly accept an + * [ES2017 `async` function]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function}. + * In this case, the `async` function will not be passed a final callback + * argument, and any thrown error will be used as the `err` argument of the + * implicit callback, and the return value will be used as the `result` value. + * (i.e. a `rejected` of the returned Promise becomes the `err` callback + * argument, and a `resolved` value becomes the `result`.) + * + * Note, due to JavaScript limitations, we can only detect native `async` + * functions and not transpilied implementations. + * Your environment must have `async`/`await` support for this to work. + * (e.g. Node > v7.6, or a recent version of a modern browser). + * If you are using `async` functions through a transpiler (e.g. Babel), you + * must still wrap the function with [asyncify]{@link module:Utils.asyncify}, + * because the `async function` will be compiled to an ordinary function that + * returns a promise. + * + * @typedef {Function} AsyncFunction + * @static + */ + +var index = { + apply, + applyEach: applyEach$1, + applyEachSeries, + asyncify, + auto, + autoInject, + cargo, + cargoQueue: cargo$1, + compose, + concat: concat$1, + concatLimit: concatLimit$1, + concatSeries: concatSeries$1, + constant, + detect: detect$1, + detectLimit: detectLimit$1, + detectSeries: detectSeries$1, + dir, + doUntil, + doWhilst: doWhilst$1, + each, + eachLimit: eachLimit$2, + eachOf: eachOf$1, + eachOfLimit: eachOfLimit$2, + eachOfSeries: eachOfSeries$1, + eachSeries: eachSeries$1, + ensureAsync, + every: every$1, + everyLimit: everyLimit$1, + everySeries: everySeries$1, + filter: filter$1, + filterLimit: filterLimit$1, + filterSeries: filterSeries$1, + forever: forever$1, + groupBy, + groupByLimit: groupByLimit$1, + groupBySeries, + log, + map: map$1, + mapLimit: mapLimit$1, + mapSeries: mapSeries$1, + mapValues, + mapValuesLimit: mapValuesLimit$1, + mapValuesSeries, + memoize, + nextTick, + parallel, + parallelLimit, + priorityQueue, + queue: queue$1, + race: race$1, + reduce: reduce$1, + reduceRight, + reflect, + reflectAll, + reject: reject$2, + rejectLimit: rejectLimit$1, + rejectSeries: rejectSeries$1, + retry, + retryable, + seq, + series, + setImmediate: setImmediate$1, + some: some$1, + someLimit: someLimit$1, + someSeries: someSeries$1, + sortBy: sortBy$1, + timeout, + times, + timesLimit, + timesSeries, + transform, + tryEach: tryEach$1, + unmemoize, + until, + waterfall: waterfall$1, + whilst: whilst$1, + + // aliases + all: every$1, + allLimit: everyLimit$1, + allSeries: everySeries$1, + any: some$1, + anyLimit: someLimit$1, + anySeries: someSeries$1, + find: detect$1, + findLimit: detectLimit$1, + findSeries: detectSeries$1, + flatMap: concat$1, + flatMapLimit: concatLimit$1, + flatMapSeries: concatSeries$1, + forEach: each, + forEachSeries: eachSeries$1, + forEachLimit: eachLimit$2, + forEachOf: eachOf$1, + forEachOfSeries: eachOfSeries$1, + forEachOfLimit: eachOfLimit$2, + inject: reduce$1, + foldl: reduce$1, + foldr: reduceRight, + select: filter$1, + selectLimit: filterLimit$1, + selectSeries: filterSeries$1, + wrapSync: asyncify, + during: whilst$1, + doDuring: doWhilst$1 +}; + +/* harmony default export */ __webpack_exports__["default"] = (index); + + + +/***/ }), + +/***/ "./node_modules/base64-js/index.js": +/*!*****************************************!*\ + !*** ./node_modules/base64-js/index.js ***! + \*****************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +exports.byteLength = byteLength +exports.toByteArray = toByteArray +exports.fromByteArray = fromByteArray + +var lookup = [] +var revLookup = [] +var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array + +var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' +for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i] + revLookup[code.charCodeAt(i)] = i +} + +// Support decoding URL-safe base64 strings, as Node.js does. +// See: https://en.wikipedia.org/wiki/Base64#URL_applications +revLookup['-'.charCodeAt(0)] = 62 +revLookup['_'.charCodeAt(0)] = 63 + +function getLens (b64) { + var len = b64.length + + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // Trim off extra bytes after placeholder bytes are found + // See: https://github.com/beatgammit/base64-js/issues/42 + var validLen = b64.indexOf('=') + if (validLen === -1) validLen = len + + var placeHoldersLen = validLen === len + ? 0 + : 4 - (validLen % 4) + + return [validLen, placeHoldersLen] +} + +// base64 is 4/3 + up to two characters of the original data +function byteLength (b64) { + var lens = getLens(b64) + var validLen = lens[0] + var placeHoldersLen = lens[1] + return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen +} + +function _byteLength (b64, validLen, placeHoldersLen) { + return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen +} + +function toByteArray (b64) { + var tmp + var lens = getLens(b64) + var validLen = lens[0] + var placeHoldersLen = lens[1] + + var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)) + + var curByte = 0 + + // if there are placeholders, only get up to the last complete 4 chars + var len = placeHoldersLen > 0 + ? validLen - 4 + : validLen + + var i + for (i = 0; i < len; i += 4) { + tmp = + (revLookup[b64.charCodeAt(i)] << 18) | + (revLookup[b64.charCodeAt(i + 1)] << 12) | + (revLookup[b64.charCodeAt(i + 2)] << 6) | + revLookup[b64.charCodeAt(i + 3)] + arr[curByte++] = (tmp >> 16) & 0xFF + arr[curByte++] = (tmp >> 8) & 0xFF + arr[curByte++] = tmp & 0xFF + } + + if (placeHoldersLen === 2) { + tmp = + (revLookup[b64.charCodeAt(i)] << 2) | + (revLookup[b64.charCodeAt(i + 1)] >> 4) + arr[curByte++] = tmp & 0xFF + } + + if (placeHoldersLen === 1) { + tmp = + (revLookup[b64.charCodeAt(i)] << 10) | + (revLookup[b64.charCodeAt(i + 1)] << 4) | + (revLookup[b64.charCodeAt(i + 2)] >> 2) + arr[curByte++] = (tmp >> 8) & 0xFF + arr[curByte++] = tmp & 0xFF + } + + return arr +} + +function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + + lookup[num >> 12 & 0x3F] + + lookup[num >> 6 & 0x3F] + + lookup[num & 0x3F] +} + +function encodeChunk (uint8, start, end) { + var tmp + var output = [] + for (var i = start; i < end; i += 3) { + tmp = + ((uint8[i] << 16) & 0xFF0000) + + ((uint8[i + 1] << 8) & 0xFF00) + + (uint8[i + 2] & 0xFF) + output.push(tripletToBase64(tmp)) + } + return output.join('') +} + +function fromByteArray (uint8) { + var tmp + var len = uint8.length + var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes + var parts = [] + var maxChunkLength = 16383 // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1] + parts.push( + lookup[tmp >> 2] + + lookup[(tmp << 4) & 0x3F] + + '==' + ) + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + uint8[len - 1] + parts.push( + lookup[tmp >> 10] + + lookup[(tmp >> 4) & 0x3F] + + lookup[(tmp << 2) & 0x3F] + + '=' + ) + } + + return parts.join('') +} + + +/***/ }), + +/***/ "./node_modules/canonicalize/lib/canonicalize.js": +/*!*******************************************************!*\ + !*** ./node_modules/canonicalize/lib/canonicalize.js ***! + \*******************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* jshint esversion: 6 */ +/* jslint node: true */ + + +module.exports = function serialize (object) { + if (object === null || typeof object !== 'object' || object.toJSON != null) { + return JSON.stringify(object); + } + + if (Array.isArray(object)) { + return '[' + object.reduce((t, cv, ci) => { + const comma = ci === 0 ? '' : ','; + const value = cv === undefined || typeof cv === 'symbol' ? null : cv; + return t + comma + serialize(value); + }, '') + ']'; + } + + return '{' + Object.keys(object).sort().reduce((t, cv, ci) => { + if (object[cv] === undefined || + typeof object[cv] === 'symbol') { + return t; + } + const comma = t.length === 0 ? '' : ','; + return t + comma + serialize(cv) + ':' + serialize(object[cv]); + }, '') + '}'; +}; + + +/***/ }), + +/***/ "./node_modules/chat-pane/lib/create.js": +/*!**********************************************!*\ + !*** ./node_modules/chat-pane/lib/create.js ***! + \**********************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.findChat = findChat; +exports.getChat = getChat; + +var _solidUi = __webpack_require__(/*! solid-ui */ "./node_modules/solid-ui/lib/index.js"); + +var _rdflib = __webpack_require__(/*! rdflib */ "./node_modules/rdflib/esm/index.js"); + +var _longChatPane = _interopRequireWildcard(__webpack_require__(/*! ./longChatPane */ "./node_modules/chat-pane/lib/longChatPane.js")); + +function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; } + +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } + +function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } + +function getMe() { + return _getMe.apply(this, arguments); +} + +function _getMe() { + _getMe = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() { + var me; + return regeneratorRuntime.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + me = _solidUi.authn.currentUser(); + + if (!(me === null)) { + _context.next = 3; + break; + } + + throw new Error('Current user not found! Not logged in?'); + + case 3: + _context.next = 5; + return _solidUi.store.fetcher.load(me.doc()); + + case 5: + return _context.abrupt("return", me); + + case 6: + case "end": + return _context.stop(); + } + } + }, _callee); + })); + return _getMe.apply(this, arguments); +} + +function getPodRoot(_x) { + return _getPodRoot.apply(this, arguments); +} + +function _getPodRoot() { + _getPodRoot = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(me) { + var podRoot; + return regeneratorRuntime.wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + podRoot = _solidUi.store.any(me, _solidUi.ns.space('storage'), undefined, me.doc()); + + if (podRoot) { + _context2.next = 3; + break; + } + + throw new Error('Current user pod root not found!'); + + case 3: + return _context2.abrupt("return", podRoot); + + case 4: + case "end": + return _context2.stop(); + } + } + }, _callee2); + })); + return _getPodRoot.apply(this, arguments); +} + +function sendInvite(_x2, _x3) { + return _sendInvite.apply(this, arguments); +} + +function _sendInvite() { + _sendInvite = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3(invitee, chatThing) { + var inviteeInbox, inviteBody, inviteResponse, locationStr; + return regeneratorRuntime.wrap(function _callee3$(_context3) { + while (1) { + switch (_context3.prev = _context3.next) { + case 0: + _context3.next = 2; + return _solidUi.store.fetcher.load(invitee.doc()); + + case 2: + inviteeInbox = _solidUi.store.any(invitee, _solidUi.ns.ldp('inbox'), undefined, invitee.doc()); + + if (inviteeInbox) { + _context3.next = 5; + break; + } + + throw new Error("Invitee inbox not found! ".concat(invitee.value)); + + case 5: + inviteBody = "\n<> a ;\n".concat(_solidUi.ns.rdf('seeAlso'), " <").concat(chatThing.value, "> . \n "); + _context3.next = 8; + return _solidUi.store.fetcher.webOperation('POST', inviteeInbox.value, { + data: inviteBody, + contentType: 'text/turtle' + }); + + case 8: + inviteResponse = _context3.sent; + locationStr = inviteResponse.headers.get('location'); + + if (locationStr) { + _context3.next = 12; + break; + } + + throw new Error("Invite sending returned a ".concat(inviteResponse.status)); + + case 12: + case "end": + return _context3.stop(); + } + } + }, _callee3); + })); + return _sendInvite.apply(this, arguments); +} + +function determineChatContainer(invitee, podRoot) { + // Create chat + // See https://gitter.im/solid/chat-app?at=5f3c800f855be416a23ae74a + var chatContainerStr = new URL("IndividualChats/".concat(new URL(invitee.value).host, "/"), podRoot.value).toString(); + return new _rdflib.NamedNode(chatContainerStr); +} + +function createChatThing(_x4, _x5) { + return _createChatThing.apply(this, arguments); +} + +function _createChatThing() { + _createChatThing = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee4(chatContainer, me) { + var created; + return regeneratorRuntime.wrap(function _callee4$(_context4) { + while (1) { + switch (_context4.prev = _context4.next) { + case 0: + _context4.next = 2; + return _longChatPane["default"].mintNew({ + session: { + store: _solidUi.store + } + }, { + me: me, + newBase: chatContainer.value + }); + + case 2: + created = _context4.sent; + return _context4.abrupt("return", created.newInstance); + + case 4: + case "end": + return _context4.stop(); + } + } + }, _callee4); + })); + return _createChatThing.apply(this, arguments); +} + +function setAcl(_x6, _x7, _x8) { + return _setAcl.apply(this, arguments); +} + +function _setAcl() { + _setAcl = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee5(chatContainer, me, invitee) { + var chatAclDoc, aclBody, aclResponse; + return regeneratorRuntime.wrap(function _callee5$(_context5) { + while (1) { + switch (_context5.prev = _context5.next) { + case 0: + _context5.next = 2; + return _solidUi.store.fetcher.load(chatContainer); + + case 2: + // FIXME: check the Why value on this quad: + chatAclDoc = _solidUi.store.any(chatContainer, new _rdflib.NamedNode('http://www.iana.org/assignments/link-relations/acl')); + + if (chatAclDoc) { + _context5.next = 5; + break; + } + + throw new Error('Chat ACL doc not found!'); + + case 5: + aclBody = "\n@prefix acl: .\n<#owner>\n a acl:Authorization;\n acl:agent <".concat(me.value, ">;\n acl:accessTo <.>;\n acl:default <.>;\n acl:mode\n acl:Read, acl:Write, acl:Control.\n<#invitee>\n a acl:Authorization;\n acl:agent <").concat(invitee.value, ">;\n acl:accessTo <.>;\n acl:default <.>;\n acl:mode\n acl:Read, acl:Append.\n"); + _context5.next = 8; + return _solidUi.store.fetcher.webOperation('PUT', chatAclDoc.value, { + data: aclBody, + contentType: 'text/turtle' + }); + + case 8: + aclResponse = _context5.sent; + + case 9: + case "end": + return _context5.stop(); + } + } + }, _callee5); + })); + return _setAcl.apply(this, arguments); +} + +function addToPrivateTypeIndex(_x9, _x10) { + return _addToPrivateTypeIndex.apply(this, arguments); +} + +function _addToPrivateTypeIndex() { + _addToPrivateTypeIndex = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee6(chatThing, me) { + var privateTypeIndex, reg, ins; + return regeneratorRuntime.wrap(function _callee6$(_context6) { + while (1) { + switch (_context6.prev = _context6.next) { + case 0: + // Add to private type index + privateTypeIndex = _solidUi.store.any(me, _solidUi.ns.solid('privateTypeIndex')); + + if (privateTypeIndex) { + _context6.next = 3; + break; + } + + throw new Error('Private type index not found!'); + + case 3: + _context6.next = 5; + return _solidUi.store.fetcher.load(privateTypeIndex); + + case 5: + reg = _solidUi.widgets.newThing(privateTypeIndex); + ins = [(0, _rdflib.st)(reg, _solidUi.ns.rdf('type'), _solidUi.ns.solid('TypeRegistration'), privateTypeIndex.doc()), (0, _rdflib.st)(reg, _solidUi.ns.solid('forClass'), _solidUi.ns.meeting('LongChat'), privateTypeIndex.doc()), (0, _rdflib.st)(reg, _solidUi.ns.solid('instance'), chatThing, privateTypeIndex.doc())]; + _context6.next = 9; + return new Promise(function (resolve, reject) { + _solidUi.store.updater.update([], ins, function (_uri, ok, errm) { + if (!ok) { + reject(new Error(errm)); + } else { + resolve(); + } + }); + }); + + case 9: + case "end": + return _context6.stop(); + } + } + }, _callee6); + })); + return _addToPrivateTypeIndex.apply(this, arguments); +} + +function findChat(_x11) { + return _findChat.apply(this, arguments); +} + +function _findChat() { + _findChat = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee7(invitee) { + var me, podRoot, chatContainer, exists; + return regeneratorRuntime.wrap(function _callee7$(_context7) { + while (1) { + switch (_context7.prev = _context7.next) { + case 0: + _context7.next = 2; + return getMe(); + + case 2: + me = _context7.sent; + _context7.next = 5; + return getPodRoot(me); + + case 5: + podRoot = _context7.sent; + chatContainer = determineChatContainer(invitee, podRoot); + exists = true; + _context7.prev = 8; + _context7.next = 11; + return _solidUi.store.fetcher.load(new _rdflib.NamedNode(chatContainer.value + _longChatPane.CHAT_LOCATION_IN_CONTAINER)); + + case 11: + _context7.next = 16; + break; + + case 13: + _context7.prev = 13; + _context7.t0 = _context7["catch"](8); + exists = false; + + case 16: + return _context7.abrupt("return", { + me: me, + chatContainer: chatContainer, + exists: exists + }); + + case 17: + case "end": + return _context7.stop(); + } + } + }, _callee7, null, [[8, 13]]); + })); + return _findChat.apply(this, arguments); +} + +function getChat(_x12) { + return _getChat.apply(this, arguments); +} + +function _getChat() { + _getChat = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee8(invitee) { + var createIfMissing, + _yield$findChat, + me, + chatContainer, + exists, + chatThing, + _args8 = arguments; + + return regeneratorRuntime.wrap(function _callee8$(_context8) { + while (1) { + switch (_context8.prev = _context8.next) { + case 0: + createIfMissing = _args8.length > 1 && _args8[1] !== undefined ? _args8[1] : true; + _context8.next = 3; + return findChat(invitee); + + case 3: + _yield$findChat = _context8.sent; + me = _yield$findChat.me; + chatContainer = _yield$findChat.chatContainer; + exists = _yield$findChat.exists; + + if (!exists) { + _context8.next = 9; + break; + } + + return _context8.abrupt("return", new _rdflib.NamedNode(chatContainer.value + _longChatPane.CHAT_LOCATION_IN_CONTAINER)); + + case 9: + if (!createIfMissing) { + _context8.next = 20; + break; + } + + _context8.next = 12; + return createChatThing(chatContainer, me); + + case 12: + chatThing = _context8.sent; + _context8.next = 15; + return sendInvite(invitee, chatThing); + + case 15: + _context8.next = 17; + return setAcl(chatContainer, me, invitee); + + case 17: + _context8.next = 19; + return addToPrivateTypeIndex(chatThing, me); + + case 19: + return _context8.abrupt("return", chatThing); + + case 20: + case "end": + return _context8.stop(); + } + } + }, _callee8); + })); + return _getChat.apply(this, arguments); +} +//# sourceMappingURL=create.js.map + +/***/ }), + +/***/ "./node_modules/chat-pane/lib/longChatPane.js": +/*!****************************************************!*\ + !*** ./node_modules/chat-pane/lib/longChatPane.js ***! + \****************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } + +function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } + +/* Long Chat Pane + ** + ** A long chat consists a of a series of chat files saved by date. + */ +var UI = __webpack_require__(/*! solid-ui */ "./node_modules/solid-ui/lib/index.js"); + +var ns = UI.ns; + +var $rdf = __webpack_require__(/*! rdflib */ "./node_modules/rdflib/esm/index.js"); + +var mainClass = ns.meeting('LongChat'); // @@ something from SIOC? + +var CHAT_LOCATION_IN_CONTAINER = 'index.ttl#this'; // const menuIcon = 'noun_897914.svg' + +var SPANNER_ICON = 'noun_344563.svg'; +module.exports = { + CHAT_LOCATION_IN_CONTAINER: CHAT_LOCATION_IN_CONTAINER, + // noun_704.svg Canoe noun_346319.svg = 1 Chat noun_1689339.svg = three chat + icon: UI.icons.iconBase + 'noun_1689339.svg', + name: 'long chat', + label: function label(subject, context) { + var kb = context.session.store; + + if (kb.holds(subject, ns.rdf('type'), ns.meeting('LongChat'))) { + // subject is the object + return 'Chat channnel'; + } // Looks like a message -- might not havre any class declared + + + if (kb.any(subject, ns.sioc('content')) && kb.any(subject, ns.dct('created'))) { + return 'message'; + } + + return null; // Suppress pane otherwise + }, + mintClass: mainClass, + mintNew: function mintNew(context, newPaneOptions) { + var kb = context.session.store; + var updater = kb.updater; + + if (newPaneOptions.me && !newPaneOptions.me.uri) { + throw new Error('chat mintNew: Invalid userid ' + newPaneOptions.me); + } + + var newInstance = newPaneOptions.newInstance = newPaneOptions.newInstance || kb.sym(newPaneOptions.newBase + CHAT_LOCATION_IN_CONTAINER); + var newChatDoc = newInstance.doc(); + kb.add(newInstance, ns.rdf('type'), ns.meeting('LongChat'), newChatDoc); + kb.add(newInstance, ns.dc('title'), 'Chat channel', newChatDoc); + kb.add(newInstance, ns.dc('created'), new Date(), newChatDoc); + + if (newPaneOptions.me) { + kb.add(newInstance, ns.dc('author'), newPaneOptions.me, newChatDoc); + } + + return new Promise(function (resolve, reject) { + updater.put(newChatDoc, kb.statementsMatching(undefined, undefined, undefined, newChatDoc), 'text/turtle', function (uri2, ok, message) { + if (ok) { + resolve(newPaneOptions); + } else { + reject(new Error('FAILED to save new chat channel at: ' + uri2 + ' : ' + message)); + } + }); + }); + }, + render: function render(subject, context, paneOptions) { + var dom = context.dom; + var kb = context.session.store; + /* Preferences + ** + ** Things like whether to color text by author webid, to expand image URLs inline, + ** expanded inline image height. ... + ** In general, preferences can be set per user, per user/app combo, per instance, + ** and per instance/user combo. Per instance? not sure about unless it is valuable + ** for everyone to be seeing the same thing. + */ + // const DCT = $rdf.Namespace('http://purl.org/dc/terms/') + + var preferencesFormText = "\n\n @prefix rdf: .\n @prefix solid: .\n @prefix ui: .\n @prefix : <#>.\n\n :this\n \"Chat preferences\" ;\n a ui:Form ;\n ui:part :colorizeByAuthor, :expandImagesInline, :newestFirst, :inlineImageHeightEms;\n ui:parts ( :colorizeByAuthor :expandImagesInline :newestFirst :inlineImageHeightEms ).\n\n:colorizeByAuthor a ui:TristateField; ui:property solid:colorizeByAuthor;\n ui:label \"Color user input by user\".\n:expandImagesInline a ui:TristateField; ui:property solid:expandImagesInline;\n ui:label \"Expand image URLs inline\".\n:newestFirst a ui:TristateField; ui:property solid:newestFirst;\n ui:label \"Newest messages at the top\".\n\n:inlineImageHeightEms a ui:IntegerField; ui:property solid:inlineImageHeightEms;\n ui:label \"Inline image height (lines)\".\n\n"; + var preferencesForm = kb.sym('https://solid.github.io/solid-panes/longCharPane/preferencesForm.ttl#this'); + var preferencesFormDoc = preferencesForm.doc(); + + if (!kb.holds(undefined, undefined, undefined, preferencesFormDoc)) { + // If not loaded already + $rdf.parse(preferencesFormText, kb, preferencesFormDoc.uri, 'text/turtle'); // Load form directly + } + + var preferenceProperties = kb.statementsMatching(null, ns.ui.property, null, preferencesFormDoc).map(function (st) { + return st.object; + }); // Settings Menu + // + // Build a menu a the side (@@ reactive: on top?) + + var menuArea; + + function menuHandler(_x) { + return _menuHandler.apply(this, arguments); + } // menuHandler + // People + // + + /* Build a particpants a the side + * (@@ reactive: on top?) + */ + + + function _menuHandler() { + _menuHandler = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(_event) { + var menuTable, registrationArea, statusArea, me; + return regeneratorRuntime.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + if (menuArea) { + _context.next = 15; + break; + } + + // Expand + menuArea = paneRight.appendChild(dom.createElement('div')); // @@ style below fix .. just make it onviious while testing + + menuArea.style = 'border-radius: 1em; border: 0.1em solid purple; padding: 0.5em; margin-left: 1em;' + 'resize: horizontal; overflow:scroll; min-width: 25em;'; + menuArea.style.maxHeight = triptychHeight; + menuTable = menuArea.appendChild(dom.createElement('table')); + registrationArea = menuTable.appendChild(dom.createElement('tr')); + statusArea = menuTable.appendChild(dom.createElement('tr')); + me = UI.authn.currentUser(); + + if (!me) { + _context.next = 13; + break; + } + + _context.next = 11; + return UI.authn.registrationControl({ + noun: 'chat room', + me: me, + statusArea: statusArea, + div: registrationArea, + dom: dom + }, chatChannel, mainClass); + + case 11: + console.log('Registration control finsished.'); + menuArea.appendChild(UI.preferences.renderPreferencesForm(chatChannel, mainClass, preferencesForm, { + noun: 'chat room', + me: me, + statusArea: statusArea, + div: menuArea, + dom: dom, + kb: kb + })); + + case 13: + _context.next = 17; + break; + + case 15: + // Close menu (hide or delete??) + menuArea.parentNode.removeChild(menuArea); + menuArea = null; + + case 17: + case "end": + return _context.stop(); + } + } + }, _callee); + })); + return _menuHandler.apply(this, arguments); + } + + var participantsArea; + + function particpantsHandler(_event) { + if (!participantsArea) { + // Expand + participantsArea = paneLeft.appendChild(dom.createElement('div')); + participantsArea.style = 'border-radius: 1em; border: 0.1em solid purple; padding: 0.5em; margin-right: 1em;' + ' resize: horizontal; overflow:scroll; min-width: 20em;'; + participantsArea.style.maxHeight = triptychHeight; // Record my participation and display participants + + var me = UI.authn.currentUser(); + if (!me) alert('Should be logeed in for partipants panel'); + UI.pad.manageParticipation(dom, participantsArea, chatChannel.doc(), chatChannel, me, {}); + } else { + // Close particpants (hide or delete??) + participantsArea.parentNode.removeChild(participantsArea); + participantsArea = null; + } + } // particpantsHandler + + + var chatChannel = subject; + var selectedMessage = null; + + if (kb.holds(subject, ns.rdf('type'), ns.meeting('LongChat'))) { + // subject is the chatChannel + console.log('Chat channnel'); // Looks like a message -- might not havre any class declared + } else if (kb.any(subject, ns.sioc('content')) && kb.any(subject, ns.dct('created'))) { + console.log('message'); + selectedMessage = subject; + chatChannel = kb.any(null, ns.wf('message'), selectedMessage); + if (!chatChannel) throw new Error('Message has no link to chatChannel'); + } + + var div = dom.createElement('div'); // Three large colons for particpant, chat, settings + + var triptychHeight = '30cm'; // @@ need to be able to set to window! + + var triptych = div.appendChild(dom.createElement('table')); + triptych.style.maxHeight = '12"'; // Screen max + + var paneRow = triptych.appendChild(dom.createElement('tr')); + var paneLeft = paneRow.appendChild(dom.createElement('td')); + var paneMiddle = paneRow.appendChild(dom.createElement('td')); + var paneRight = paneRow.appendChild(dom.createElement('td')); + var paneBottom = triptych.appendChild(dom.createElement('tr')); + paneBottom.appendChild(dom.createElement('td')); + var buttonCell = paneBottom.appendChild(dom.createElement('td')); + paneBottom.appendChild(dom.createElement('td')); // Button to bring up particpants drawer on left + + var particpantsIcon = 'noun_339237.svg'; + var particpantsButton = UI.widgets.button(dom, UI.icons.iconBase + particpantsIcon, 'particpants ...'); // wider var + + buttonCell.appendChild(particpantsButton); + particpantsButton.addEventListener('click', particpantsHandler); + var menuButton = UI.widgets.button(dom, UI.icons.iconBase + SPANNER_ICON, 'Menu ...'); // wider var + + buttonCell.appendChild(menuButton); + menuButton.style["float"] = 'right'; + menuButton.addEventListener('click', menuHandler); + div.setAttribute('class', 'chatPane'); + var options = { + infinite: true + }; // was: menuHandler: menuHandler + + var participantsHandlerContext = { + noun: 'chat room', + div: div, + dom: dom + }; + participantsHandlerContext.me = UI.authn.currentUser(); // If already logged on + + UI.preferences.getPreferencesForClass(chatChannel, mainClass, preferenceProperties, participantsHandlerContext).then(function (prefMap) { + for (var propuri in prefMap) { + options[propuri.split('#')[1]] = prefMap[propuri]; + } + + if (selectedMessage) { + options.selectedMessage = selectedMessage; + } + + if (paneOptions.solo) { + // This is the top pane, title, scrollbar etc are ours + options.solo = true; + } + + var chatControl = UI.infiniteMessageArea(dom, kb, chatChannel, options); + chatControl.style.resize = 'both'; + chatControl.style.overflow = 'auto'; + chatControl.style.maxHeight = triptychHeight; + paneMiddle.appendChild(chatControl); + }, function (err) { + return UI.widgets.complain(participantsHandlerContext, err); + }); + return div; + } +}; +//# sourceMappingURL=longChatPane.js.map + +/***/ }), + +/***/ "./node_modules/chat-pane/lib/main.js": +/*!********************************************!*\ + !*** ./node_modules/chat-pane/lib/main.js ***! + \********************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +module.exports = { + shortChatPane: __webpack_require__(/*! ./shortChatPane */ "./node_modules/chat-pane/lib/shortChatPane.js"), + longChatPane: __webpack_require__(/*! ./longChatPane */ "./node_modules/chat-pane/lib/longChatPane.js"), + getChat: __webpack_require__(/*! ./create */ "./node_modules/chat-pane/lib/create.js").getChat +}; +//# sourceMappingURL=main.js.map + +/***/ }), + +/***/ "./node_modules/chat-pane/lib/shortChatPane.js": +/*!*****************************************************!*\ + !*** ./node_modules/chat-pane/lib/shortChatPane.js ***! + \*****************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +/* Chat Pane + ** + ** Plan is to support a finte number of chat graph shapes + ** and investigate the interop between them. + */ + +/* global $rdf */ +var UI = __webpack_require__(/*! solid-ui */ "./node_modules/solid-ui/lib/index.js"); + +var ns = UI.ns; +module.exports = { + icon: UI.icons.iconBase + 'noun_346319.svg', + name: 'chat', + + /* + * As part of the work on merging the existing chat views (aka panes) into one view + * https://github.com/solid/chat-pane/issues/17 + * we want to dis-incentivize the use of Small Chat until we've gotten the work done + * by making it difficult to create new data resources that uses the Small Chat view + * but we still want existing resources to be viewed by the Small Chat view + */ + audience: [ns.solid('PowerUser')], + + /* AN RRSAgent IRC log: + + a foaf:ChatChannel + foaf:chatEventList + [ rdf:_100 + <#T19-10-58> + rdf:_101 + <#T19-10-58-1> + rdf:_102 + .. + <#T19-28-47-1> + dc:creator + [ a wn:Person; foaf:nick "timbl" ] + dc:date + "2016-03-15T19:28:47Z" + dc:description + "timbl has joined &mit" + a foaf:chatEvent. + */ + label: function label(subject, context) { + var kb = context.session.store; + var n = kb.each(subject, ns.wf('message')).length; + if (n > 0) return 'Chat (' + n + ')'; // Show how many in hover text + + if (kb.holds(subject, ns.rdf('type'), ns.meeting('Chat'))) { + // subject is the file + return 'Meeting chat'; + } + + if (kb.holds(undefined, ns.rdf('type'), ns.foaf('ChatChannel'), subject)) { + // subject is the file + return 'IRC log'; // contains anything of this type + } + + return null; // Suppress pane otherwise + }, + mintClass: ns.meeting('Chat'), + mintNew: function mintNew(context, newPaneOptions) { + var kb = context.session.store; + var updater = kb.updater; + + if (newPaneOptions.me && !newPaneOptions.me.uri) { + throw new Error('chat mintNew: Invalid userid ' + newPaneOptions.me); + } + + var newInstance = newPaneOptions.newInstance = newPaneOptions.newInstance || kb.sym(newPaneOptions.newBase + 'index.ttl#this'); + var newChatDoc = newInstance.doc(); + kb.add(newInstance, ns.rdf('type'), ns.meeting('Chat'), newChatDoc); + kb.add(newInstance, ns.dc('title'), 'Chat', newChatDoc); + kb.add(newInstance, ns.dc('created'), new Date(), newChatDoc); + + if (newPaneOptions.me) { + kb.add(newInstance, ns.dc('author'), newPaneOptions.me, newChatDoc); + } + + return new Promise(function (resolve, reject) { + updater.put(newChatDoc, kb.statementsMatching(undefined, undefined, undefined, newChatDoc), 'text/turtle', function (uri2, ok, message) { + if (ok) { + resolve(newPaneOptions); + } else { + reject(new Error('FAILED to save new tool at: ' + uri2 + ' : ' + message)); + } + }); + }); + }, + render: function render(subject, context) { + var kb = context.session.store; + var dom = context.dom; + + var complain = function complain(message, color) { + var pre = dom.createElement('pre'); + pre.setAttribute('style', 'background-color: ' + color || false); + div.appendChild(pre); + pre.appendChild(dom.createTextNode(message)); + }; + + var div = dom.createElement('div'); + div.setAttribute('class', 'chatPane'); + var options = {}; // Like newestFirst + + var messageStore; + + if (kb.holds(subject, ns.rdf('type'), ns.meeting('Chat'))) { + // subject may be the file + messageStore = subject.doc(); + } else if (kb.any(subject, UI.ns.wf('message'))) { + messageStore = UI.store.any(subject, UI.ns.wf('message')).doc(); + } else if (kb.holds(undefined, ns.rdf('type'), ns.foaf('ChatChannel'), subject) || kb.holds(subject, ns.rdf('type'), ns.foaf('ChatChannel'))) { + // subject is the file + var ircLogQuery = function ircLogQuery() { + var query = new $rdf.Query('IRC log entries'); + var v = []; + var vv = ['chan', 'msg', 'date', 'list', 'pred', 'creator', 'content']; + vv.map(function (x) { + query.vars.push(v[x] = $rdf.variable(x)); + }); + query.pat.add(v.chan, ns.foaf('chatEventList'), v.list); // chatEventList + + query.pat.add(v.list, v.pred, v.msg); // + + query.pat.add(v.msg, ns.dc('date'), v.date); + query.pat.add(v.msg, ns.dc('creator'), v.creator); + query.pat.add(v.msg, ns.dc('description'), v.content); + return query; + }; + + messageStore = subject.doc(); + options.query = ircLogQuery(); + } else { + complain('Unknown chat type'); + } // var context = {dom, div} + // UI.authn.logIn(context).then( context => { // The widget itself sees to login + + + div.appendChild(UI.messageArea(dom, kb, subject, messageStore, options)); + kb.updater.addDownstreamChangeListener(messageStore, function () { + UI.widgets.refreshTree(div); + }); // Live update + // }) + + return div; + } +}; +//# sourceMappingURL=shortChatPane.js.map + +/***/ }), + +/***/ "./node_modules/contacts-pane/contactLogic.js": +/*!****************************************************!*\ + !*** ./node_modules/contacts-pane/contactLogic.js ***! + \****************************************************/ +/*! exports provided: updateMany, saveNewContact, sanitizeToAlpha, saveNewGroup, addPersonToGroup */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "updateMany", function() { return updateMany; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "saveNewContact", function() { return saveNewContact; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sanitizeToAlpha", function() { return sanitizeToAlpha; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "saveNewGroup", function() { return saveNewGroup; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "addPersonToGroup", function() { return addPersonToGroup; }); +/* harmony import */ var solid_ui__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! solid-ui */ "./node_modules/solid-ui/lib/index.js"); +/* harmony import */ var solid_ui__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(solid_ui__WEBPACK_IMPORTED_MODULE_0__); +// Logic for solid contacts + + + +const ns = solid_ui__WEBPACK_IMPORTED_MODULE_0__["ns"] +const $rdf = solid_ui__WEBPACK_IMPORTED_MODULE_0__["rdf"] +const utils = solid_ui__WEBPACK_IMPORTED_MODULE_0__["utils"] +const kb = solid_ui__WEBPACK_IMPORTED_MODULE_0__["store"] +const updater = kb.updater + +/** Perform updates on more than one document @@ Move to rdflib! +*/ +async function updateMany (deletions, insertions) { + const docs = deletions.concat(insertions).map(st => st.why) + const uniqueDocs = Array.from(new Set(docs)) + const updates = uniqueDocs.map(doc => + kb.updater.update(deletions.filter(st => st.why.sameTerm(doc)), + insertions.filter(st => st.why.sameTerm(doc)))) + return Promise.all(updates) +} + +/** Add a new person to the web data +* +* adds them to the given groups as well. +* @returns {NamedNode} the person +*/ +async function saveNewContact (book, name, selectedGroups) { + const nameEmailIndex = kb.any(book, ns.vcard('nameEmailIndex')) + + const uuid = utils.genUuid() + const person = kb.sym( + book.dir().uri + 'Person/' + uuid + '/index.ttl#this' + ) + const doc = person.doc() + + // Set of statements to different files + const agenda = [ + // Patch the main index to add the person + $rdf.st(person, ns.vcard('inAddressBook'), book, nameEmailIndex), // The people index + $rdf.st(person, ns.vcard('fn'), name, nameEmailIndex), + // The new person file + $rdf.st(person, ns.vcard('fn'), name, doc), + $rdf.st(person, ns.rdf('type'), ns.vcard('Individual'), doc), + + $rdf.st(doc, ns.dct('created'), new Date(), doc) // Note when created - useful for triaging later + // Note this is propert of the file -- not when the person was created! + ] + + for (const gu in selectedGroups) { + const g = kb.sym(gu) + const gd = g.doc() + agenda.push( + $rdf.st(g, ns.vcard('hasMember'), person, gd), + $rdf.st(person, ns.vcard('fn'), name, gd) + ) + } + + try { + await updateMany([], agenda) // @@ in future, updater.updateMany + } catch (e) { + console.log("Error: can't update " + person + ' as new contact:' + e) + throw new Error('Updating new contact: ' + e) + } + return person +} + +function sanitizeToAlpha (name) { // https://mathiasbynens.be/notes/es6-unicode-regex + const n2 = name.replace(/\W/gu, '_') // Anything which is not a unicode word characeter + return n2.replace(/_+/g, '_') // https://www.regular-expressions.info/shorthand.html +} + +/** Write new group to web + * Creates an empty new group file and adds it to the index + * @returns group +*/ +async function saveNewGroup (book, name) { + const gix = kb.any(book, ns.vcard('groupIndex')) + + const gname = sanitizeToAlpha(name) + const group = kb.sym(book.dir().uri + 'Group/' + gname + '.ttl#this') + const doc = group.doc() + console.log(' New group will be: ' + group + '\n') + try { + await kb.fetcher.load(gix) + } catch (err) { + throw new Error('Error loading group index!' + gix.uri + ': ' + err) + } + if (kb.holds(book, ns.vcard('includesGroup'), group, gix)) { + return group // Already exists + } + const insertTriples = [ + $rdf.st(book, ns.vcard('includesGroup'), group, gix), + $rdf.st(group, ns.rdf('type'), ns.vcard('Group'), gix), + $rdf.st(group, ns.vcard('fn'), name, gix) + ] + try { + await updater.update([], insertTriples) + } catch (e) { + throw new Error('Could not update group index ' + e) // fail + } + + const triples = [ + $rdf.st(book, ns.vcard('includesGroup'), group, doc), // Pointer back to book + $rdf.st(group, ns.rdf('type'), ns.vcard('Group'), doc), + $rdf.st(group, ns.vcard('fn'), name, doc) + ] + try { + await updater.update([], triples) + } catch (err) { + throw new Error('Could not update group file: ' + err) // fail + } + return group +} + +async function addPersonToGroup (thing, group) { + const toBeFetched = [thing.doc(), group.doc()] + try { + await kb.fetcher.load(toBeFetched) + } catch (e) { + throw new Error('addPersonToGroup: ' + e) + } + + const types = kb.findTypeURIs(thing) + for (const ty in types) { + console.log(' drop object type includes: ' + ty) // @@ Allow email addresses and phone numbers to be dropped? + } + if (!(ns.vcard('Individual').uri in types || + ns.vcard('Organization').uri in types)) { + return alert(`Can't add ${thing} to a group: it has to be an individual or another group.`) + } + const pname = kb.any(thing, ns.vcard('fn')) + const gname = kb.any(group, ns.vcard('fn')) + if (!pname) { return alert('No vcard name known for ' + thing) } + const already = kb.holds(group, ns.vcard('hasMember'), thing, group.doc()) + if (already) { + return alert( + 'ALREADY added ' + pname + ' to group ' + gname + ) + } + const message = 'Add ' + pname + ' to group ' + gname + '?' + if (!confirm(message)) return + const ins = [ + $rdf.st(group, ns.vcard('hasMember'), thing, group.doc()), + $rdf.st(thing, ns.vcard('fn'), pname, group.doc()) + ] + try { + await updater.update([], ins) + } catch (e) { + throw new Error(`Error adding ${pname} to group ${gname}:` + e) + } + return thing +} + + +/***/ }), + +/***/ "./node_modules/contacts-pane/contactsPane.js": +/*!****************************************************!*\ + !*** ./node_modules/contacts-pane/contactsPane.js ***! + \****************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var solid_ui__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! solid-ui */ "./node_modules/solid-ui/lib/index.js"); +/* harmony import */ var solid_ui__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(solid_ui__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _toolsPane__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./toolsPane */ "./node_modules/contacts-pane/toolsPane.js"); +/* harmony import */ var _mintNewAddressBook__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./mintNewAddressBook */ "./node_modules/contacts-pane/mintNewAddressBook.js"); +/* harmony import */ var _individual__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./individual */ "./node_modules/contacts-pane/individual.js"); +/* harmony import */ var _contactLogic__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./contactLogic */ "./node_modules/contacts-pane/contactLogic.js"); +/* Contact AddressBook Pane +** +** This outline pane allows a user to interact with an contact, +to change its state according to an ontology, comment on it, etc. +** +** See also things like +** http://www.w3.org/TR/vcard-rdf/ +** http://tools.ietf.org/html/rfc6350 +** http://www.iana.org/assignments/vcard-elements/vcard-elements.xhtml +** +** Feross "Standard" style note: Callback functions should not be called "callback" +** or the "standard" linter will complain if the first param is not a node.js error code. (2018-01) +** Hence "callbackFunction" +*/ +/* global alert, confirm */ + + + + + + + +// const $rdf = UI.rdf +const ns = solid_ui__WEBPACK_IMPORTED_MODULE_0__["ns"] +const utils = solid_ui__WEBPACK_IMPORTED_MODULE_0__["utils"] + +/* harmony default export */ __webpack_exports__["default"] = ({ + icon: solid_ui__WEBPACK_IMPORTED_MODULE_0__["icons"].iconBase + 'noun_99101.svg', // changed from embedded icon 2016-05-01 + + name: 'contact', + + // Does the subject deserve an contact pane? + label: function (subject, context) { + const t = context.session.store.findTypeURIs(subject) + if (t[ns.vcard('Individual').uri]) return 'Contact' + if (t[ns.vcard('Organization').uri]) return 'contact' + if (t[ns.foaf('Person').uri]) return 'Person' + if (t[ns.schema('Person').uri]) return 'Person' + if (t[ns.vcard('Group').uri]) return 'Group' + if (t[ns.vcard('AddressBook').uri]) return 'Address book' + return null // No under other circumstances + }, + + mintClass: solid_ui__WEBPACK_IMPORTED_MODULE_0__["ns"].vcard('AddressBook'), + + mintNew: _mintNewAddressBook__WEBPACK_IMPORTED_MODULE_2__["mintNewAddressBook"], // Make a new address book + + // Render the pane + render: function (subject, dataBrowserContext, paneOptions = {}) { + const thisPane = this + + // stick functions here + function complain (message) { + console.log('contactsPane: ' + message) + div.appendChild(solid_ui__WEBPACK_IMPORTED_MODULE_0__["widgets"].errorMessageBlock(dom, message, 'pink')) + } + function complainIfBad (ok, body) { + if (!ok) { + complain('Error: ' + body) + } + } + + // Reproduction: Spawn a new instance of this app + function newAddressBookButton (thisAddressBook) { + return solid_ui__WEBPACK_IMPORTED_MODULE_0__["authn"].newAppInstance( + dom, + { noun: 'address book', appPathSegment: 'contactorator.timbl.com' }, + function (ws, newBase) { + thisPane.clone(thisAddressBook, newBase, { // @@ clone is not a thing - use mintNew + me: me, + div: div, + dom: dom + }) + } + ) + } // newAddressBookButton + + const dom = dataBrowserContext.dom + const kb = dataBrowserContext.session.store + const div = dom.createElement('div') + const me = solid_ui__WEBPACK_IMPORTED_MODULE_0__["authn"].currentUser() // If already logged on + + solid_ui__WEBPACK_IMPORTED_MODULE_0__["aclControl"].preventBrowserDropEvents(dom) // protect drag and drop + + div.setAttribute('class', 'contactPane') + + asyncRender().then( + () => console.log('contctsPane Rendered ' + subject), + err => complain('' + err)) + return div + + // Async part of render. Maybe API will later allow render to be async + async function asyncRender () { + const updater = kb.updater + solid_ui__WEBPACK_IMPORTED_MODULE_0__["aclControl"].preventBrowserDropEvents(dom) + + const t = kb.findTypeURIs(subject) + + let me = solid_ui__WEBPACK_IMPORTED_MODULE_0__["authn"].currentUser() + + const context = { + target: subject, + me: me, + noun: 'address book', + div: div, + dom: dom + } // missing: statusRegion + + // Render a 3-column browser for an address book or a group + function renderThreeColumnBrowser (books, context, options) { + kb.fetcher + .load(books) + .then(function (_xhr) { + renderThreeColumnBrowser2(books, context, options) + }) + .catch(function (err) { + complain(err) + }) + } + function renderThreeColumnBrowser2 (books, context, options) { + const classLabel = utils.label(ns.vcard('AddressBook')) + // const IndividualClassLabel = utils.label(ns.vcard('Individual')) + + let book = books[0] // for now + const groupIndex = kb.any(book, ns.vcard('groupIndex')) + let selectedGroups = {} + let selectedPeople = {} // Actually prob max 1 + + const target = options.foreignGroup || book + + let title = + kb.any(target, ns.dc('title')) || kb.any(target, ns.vcard('fn')) + if (paneOptions.solo && title && typeof document !== 'undefined') { + document.title = title.value // @@ only when the outermmost pane + } + title = title ? title.value : classLabel + + // The book could be the main subject, or linked from a group we are dealing with + function findBookFromGroups (book) { + if (book) { + return book + } + let g + for (const gu in selectedGroups) { + g = kb.sym(gu) + const b = kb.any(undefined, ns.vcard('includesGroup'), g) + if (b) return b + } + throw new Error( + 'findBookFromGroups: Cant find address book which this group is part of' + ) + } + + // Write a new contact to the web + + // organization-name is a hack for Mac records with no FN which is mandatory. + function nameFor (x) { + const name = + kb.any(x, ns.vcard('fn')) || + kb.any(x, ns.foaf('name')) || + kb.any(x, ns.vcard('organization-name')) + return name ? name.value : '???' + } + + function filterName (name) { + const filter = searchInput.value.trim().toLowerCase() + if (filter.length === 0) return true + const parts = filter.split(' ') // Each name part must be somewhere + for (let j = 0; j < parts.length; j++) { + const word = parts[j] + if (name.toLowerCase().indexOf(word) < 0) return false + } + return true + } + + function selectPerson (person) { + cardMain.innerHTML = 'loading...' + selectedPeople = {} + selectedPeople[person.uri] = true + refreshFilteredPeople() // Color to remember which one you picked + const local = book ? localNode(person) : person + kb.fetcher.nowOrWhenFetched(local.doc(), undefined, function ( + ok, + message + ) { + cardMain.innerHTML = '' + if (!ok) { + return complainIfBad( + ok, + "Can't load card: " + local + ': ' + message + ) + } + // console.log("Loaded card " + local + '\n') + cardMain.appendChild(renderPane(dom, local, 'contact')) + cardMain.appendChild(dom.createElement('br')) + + cardMain.appendChild(solid_ui__WEBPACK_IMPORTED_MODULE_0__["widgets"].linkIcon(dom, local)) // hoverHide + + // Add in a delete button to delete from AB + const deleteButton = solid_ui__WEBPACK_IMPORTED_MODULE_0__["widgets"].deleteButtonWithCheck( + dom, + cardMain, + 'contact', + function () { + const container = person.dir() // ASSUMPTION THAT CARD IS IN ITS OWN DIRECTORY + // function warn (message) { return UI.widgets.errorMessageBlock(dom, message, 'straw') } + alert('Conatiner to delete is ' + container) + const pname = kb.any(person, ns.vcard('fn')) + + if ( + confirm( + 'Delete contact ' + pname + ' completely?? ' + container + ) + ) { + console.log('Deleting a contact ' + pname) + deleteThing(person) + // - delete the references to it in group files and save them background + // - delete the reference in people.ttl and save it back + deleteRecursive(kb, container).then(_res => { + refreshNames() // Doesn't work + cardMain.innerHTML = 'Contact Data Deleted.' + }) + } + } + ) + deleteButton.style = 'height: 2em;' + }) + } + + function refreshFilteredPeople (active) { + let count = 0 + let lastRow = null + for (let i = 0; i < peopleMainTable.children.length; i++) { + const row = peopleMainTable.children[i] + const matches = filterName(nameFor(row.subject)) + if (matches) { + count++ + lastRow = row + } + row.setAttribute( + 'style', + matches + ? selectedPeople[row.subject.uri] + ? 'background-color: #cce;' + : '' + : 'display: none;' + ) + } + if (count === 1 && active) { + const unique = lastRow.subject + // selectedPeople = { } + // selectedPeople[unique.uri] = true + // lastRow.setAttribute('style', 'background-color: #cce;') + selectPerson(unique) + } + } + + function selectAllGroups ( + selectedGroups, + groupsMainTable, + callbackFunction + ) { + function fetchGroupAndSelct (group, groupRow) { + groupRow.setAttribute('style', 'background-color: #ffe;') + kb.fetcher.nowOrWhenFetched(group.doc(), undefined, function ( + ok, + message + ) { + if (!ok) { + const msg = "Can't load group file: " + group + ': ' + message + badness.push(msg) + return complainIfBad(ok, msg) + } + groupRow.setAttribute('style', 'background-color: #cce;') + selectedGroups[group.uri] = true + refreshGroupsSelected() + refreshNames() // @@ every time?? + todo -= 1 + if (!todo) { + if (callbackFunction) { callbackFunction(badness.length === 0, badness) } + } + }) + } + let todo = groupsMainTable.children.length + var badness = [] /* eslint-disable-line no-var */ + for (let k = 0; k < groupsMainTable.children.length; k++) { + const groupRow = groupsMainTable.children[k] + const group = groupRow.subject + fetchGroupAndSelct(group, groupRow) + } // for each row + } + + function groupsInOrder () { + let sortMe = [] + if (options.foreignGroup) { + sortMe.push([ + '', + kb.any(options.foreignGroup, ns.vcard('fn')), + options.foreignGroup + ]) + } + if (book) { + books.forEach(function (book) { + const gs = book ? kb.each(book, ns.vcard('includesGroup'), null, groupIndex) : [] + const gs2 = gs.map(function (g) { + return [book, kb.any(g, ns.vcard('fn')), g] + }) + sortMe = sortMe.concat(gs2) + }) + sortMe.sort() + } + return sortMe.map(tuple => tuple[2]) + } + + function renderPane (dom, subject, paneName) { + const p = dataBrowserContext.session.paneRegistry.byName(paneName) + const d = p.render(subject, dataBrowserContext) + d.setAttribute( + 'style', + 'border: 0.1em solid #444; border-radius: 0.5em' + ) + return d + } + + function compareForSort (self, other) { + let s = nameFor(self) + let o = nameFor(other) + if (s && o) { + s = s.toLowerCase() + o = o.toLowerCase() + if (s > o) return 1 + if (s < o) return -1 + } + if (self.uri > other.uri) return 1 + if (self.uri < other.uri) return -1 + return 0 + } + + // In a LDP work, deletes the whole document describing a thing + // plus patch out ALL mentiosn of it! Use with care! + // beware of other dta picked up from other places being smushed + // together and then deleted. + + function deleteThing (x) { + console.log('deleteThing: ' + x) + const ds = kb + .statementsMatching(x) + .concat(kb.statementsMatching(undefined, undefined, x)) + const targets = {} + ds.forEach(function (st) { + targets[st.why.uri] = st + }) + const agenda = [] // sets of statements of same document to delete + for (const target in targets) { + agenda.push( + ds.filter(function (st) { + return st.why.uri === target + }) + ) + console.log( + ' Deleting ' + + agenda[agenda.length - 1].length + + ' triples from ' + + target + ) + } + function nextOne () { + if (agenda.length > 0) { + updater.update(agenda.shift(), [], function (uri, ok, body) { + if (!ok) { + complain('Error deleting all trace of: ' + x + ': ' + body) + return + } + nextOne() + }) + } else { + console.log('Deleting resoure ' + x.doc()) + kb.fetcher + .delete(x.doc()) + .then(function () { + console.log('Delete thing ' + x + ': complete.') + }) + .catch(function (e) { + complain('Error deleting thing ' + x + ': ' + e) + }) + } + } + nextOne() + } + + // For deleting an addressbook sub-folder eg person - use with care! + // @@ move to solid-logic + function deleteRecursive (kb, folder) { + return new Promise(function (resolve) { + kb.fetcher.load(folder).then(function () { + const promises = kb.each(folder, ns.ldp('contains')).map(file => { + if (kb.holds(file, ns.rdf('type'), ns.ldp('BasicContainer'))) { + return deleteRecursive(kb, file) + } else { + console.log('deleteRecirsive file: ' + file) + if (!confirm(' Really DELETE File ' + file)) { + throw new Error('User aborted delete file') + } + return kb.fetcher.webOperation('DELETE', file.uri) + } + }) + console.log('deleteRecirsive folder: ' + folder) + if (!confirm(' Really DELETE folder ' + folder)) { + throw new Error('User aborted delete file') + } + promises.push(kb.fetcher.webOperation('DELETE', folder.uri)) + Promise.all(promises).then(_res => { + resolve() + }) + }) + }) + } + + function localNode (person, _div) { + const aliases = kb.allAliases(person) + const prefix = book.dir().uri + for (let i = 0; i < aliases.length; i++) { + if (aliases[i].uri.slice(0, prefix.length) === prefix) { + return aliases[i] + } + } + throw new Error('No local URI for ' + person) + } + + /** Refresh the list of names + */ + function refreshNames () { + function setPersonListener (personRow, person) { + personRow.addEventListener('click', function (event) { + event.preventDefault() + selectPerson(person) + }) + } + + let cards = [] + for (const u in selectedGroups) { + if (selectedGroups[u]) { + const a = kb.each(kb.sym(u), ns.vcard('hasMember')) + cards = cards.concat(a) + } + } + cards.sort(compareForSort) // @@ sort by name not UID later + for (let k = 0; k < cards.length - 1;) { + if (cards[k].uri === cards[k + 1].uri) { + cards.splice(k, 1) // Eliminate duplicates from more than one group + } else { + k++ + } + } + + peopleHeader.textContent = + cards.length > 5 ? '' + cards.length + ' contacts' : 'contact' + + function renderNameInGroupList (person) { + const personRow = dom.createElement('tr') + const personLeft = personRow.appendChild(dom.createElement('td')) + // const personRight = personRow.appendChild(dom.createElement('td')) + personLeft.setAttribute('style', dataCellStyle) + personRow.subject = person + const name = nameFor(person) + personLeft.textContent = name + personRow.subject = person + solid_ui__WEBPACK_IMPORTED_MODULE_0__["widgets"].makeDraggable(personRow, person) + + setPersonListener(personRow, person) + return personRow + } + + utils.syncTableToArrayReOrdered(peopleMainTable, cards, renderNameInGroupList) + refreshFilteredPeople() + } // refreshNames + + function refreshThingsSelected (table, selectionArray) { + for (let i = 0; i < table.children.length; i++) { + const row = table.children[i] + if (row.subject) { + row.setAttribute( + 'style', + selectionArray[row.subject.uri] ? 'background-color: #cce;' : '' + ) + } + } + } + + function refreshGroupsSelected () { + return refreshThingsSelected(groupsMainTable, selectedGroups) + } + + // Check every group is in the list and add it if not. + + function syncGroupTable () { + function renderGroupRow (group) { + // Is something is dropped on a group, add people to group + async function handleURIsDroppedOnGroup (uris) { + uris.forEach(function (u) { + console.log('Dropped on group: ' + u) + const thing = kb.sym(u) + try { + Object(_contactLogic__WEBPACK_IMPORTED_MODULE_4__["addPersonToGroup"])(thing, group) + } catch (e) { + complain(e) + } + refreshNames() + }) + } + function groupRowClickListener (event) { + event.preventDefault() + const groupList = kb.sym(group.uri.split('#')[0]) + if (!event.metaKey) { + selectedGroups = {} // If Command key pressed, accumulate multiple + } + selectedGroups[group.uri] = !selectedGroups[group.uri] + refreshGroupsSelected() + peopleMainTable.innerHTML = '' // clear in case refreshNames doesn't work for unknown reason + + kb.fetcher.nowOrWhenFetched( + groupList.uri, + undefined, + function (ok, message) { + if (!ok) { + return complainIfBad( + ok, + "Can't load group file: " + groupList + ': ' + message + ) + } + refreshNames() + + if (!event.metaKey) { + // If only one group has been selected, show ACL + cardMain.innerHTML = '' + let visible = false + const aclControl = solid_ui__WEBPACK_IMPORTED_MODULE_0__["aclControl"].ACLControlBox5( + group, + dataBrowserContext, + 'group', + kb, + function (ok, body, response) { + if (!ok) { + if (response && response.status && response.status === 403) { + cardMain.innerHTML = 'No control access.' + } else { + cardMain.innerHTML = 'Failed to load access control: ' + body + } + } + } + ) + const sharingButton = cardMain.appendChild( + dom.createElement('button') + ) + sharingButton.style.cssText = + 'padding: 1em; margin: 1em' + const img = sharingButton.appendChild( + dom.createElement('img') + ) + img.style.cssText = 'width: 1.5em; height: 1.5em' + img.setAttribute( + 'src', + solid_ui__WEBPACK_IMPORTED_MODULE_0__["icons"].iconBase + 'noun_123691.svg' + ) + sharingButton.addEventListener('click', function () { + visible = !visible + if (visible) { + cardMain.appendChild(aclControl) + } else { + cardMain.removeChild(aclControl) + } + }) + } + } + ) + } + + // Body of renderGroupRow + const name = kb.any(group, ns.vcard('fn')) + const groupRow = dom.createElement('tr') + groupRow.subject = group + solid_ui__WEBPACK_IMPORTED_MODULE_0__["widgets"].makeDraggable(groupRow, group) + + groupRow.setAttribute('style', dataCellStyle) + groupRow.textContent = name + + solid_ui__WEBPACK_IMPORTED_MODULE_0__["widgets"].makeDropTarget(groupRow, handleURIsDroppedOnGroup) + solid_ui__WEBPACK_IMPORTED_MODULE_0__["widgets"].deleteButtonWithCheck( + dom, + groupRow, + 'group ' + name, + function () { + deleteThing(group) + syncGroupTable() + } + ) + groupRow.addEventListener('click', groupRowClickListener, true) + return groupRow + } // renderGroupRow + + const groups = groupsInOrder() + utils.syncTableToArrayReOrdered(groupsMainTable, groups, renderGroupRow) + refreshGroupsSelected() + } // syncGroupTable + + // Click on New Group button + async function newGroupClickHandler (_event) { + cardMain.innerHTML = '' + const groupIndex = kb.any(book, ns.vcard('groupIndex')) + try { + await fetch.load(groupIndex) + } catch (e) { + console.log('Error: Group index NOT loaded:' + e + '\n') + } + console.log(' Group index has been loaded\n') + + const name = await solid_ui__WEBPACK_IMPORTED_MODULE_0__["widgets"].askName( + dom, kb, cardMain, solid_ui__WEBPACK_IMPORTED_MODULE_0__["ns"].foaf('name'), ns.vcard('Group'), 'group') + if (!name) return // cancelled by user + let group + try { + group = await Object(_contactLogic__WEBPACK_IMPORTED_MODULE_4__["saveNewGroup"])(book, name) + } catch (err) { + console.log("Error: can't save new group:" + err) + cardMain.innerHTML = 'Failed to save group' + err + return + } + selectedGroups = {} + selectedGroups[group.uri] = true + syncGroupTable() // Refresh list of groups + + cardMain.innerHTML = '' + cardMain.appendChild(solid_ui__WEBPACK_IMPORTED_MODULE_0__["aclControl"].ACLControlBox5( + group.doc(), dataBrowserContext, 'group', kb, + function (ok, body) { + if (!ok) { + cardMain.innerHTML = + 'Group sharing setup failed: ' + body + } + })) + } // newGroupClickHandler + + async function newContactClickHandler (_event) { + cardMain.innerHTML = '' + const ourBook = findBookFromGroups(book) + try { + await kb.fetcher.load(ourBook) + } catch (err) { + throw new Error("Book won't load:" + ourBook) + } + + const nameEmailIndex = kb.any(ourBook, ns.vcard('nameEmailIndex')) + if (!nameEmailIndex) throw new Error('Wot no nameEmailIndex?') + await kb.fetcher.load(nameEmailIndex) + console.log('Name index loaded async' + nameEmailIndex) + + const name = await solid_ui__WEBPACK_IMPORTED_MODULE_0__["widgets"] + .askName(dom, kb, cardMain, solid_ui__WEBPACK_IMPORTED_MODULE_0__["ns"].foaf('name'), ns.vcard('Individual'), 'person') + + if (!name) return // cancelled by user + cardMain.innerHTML = 'indexing...' + book = findBookFromGroups(book) + let person + try { + person = await Object(_contactLogic__WEBPACK_IMPORTED_MODULE_4__["saveNewContact"])(book, name, selectedGroups) + } catch (err) { + const msg = "Error: can't save new contact: " + err + console.log(msg) + alert(msg) + } + + selectedPeople = {} + selectedPeople[person.uri] = true + refreshNames() // Add name to list of group + cardMain.innerHTML = '' // Clear 'indexing' + cardMain.appendChild(renderPane(dom, person, 'contact')) + } + + // //////////////////////////// Three-column Contact Browser - Body + // ////////////////// Body of 3-column browser + + const bookTable = dom.createElement('table') + bookTable.setAttribute( + 'style', + 'border-collapse: collapse; margin-right: 0; max-height: 9in;' + ) + div.appendChild(bookTable) + /* + bookTable.innerHTML = ` + + + + + + + + + + + + ` + */ + const bookHeader = bookTable.appendChild(dom.createElement('tr')) + const bookMain = bookTable.appendChild(dom.createElement('tr')) + const bookFooter = bookTable.appendChild(dom.createElement('tr')) + + const groupsHeader = bookHeader.appendChild(dom.createElement('td')) + const peopleHeader = bookHeader.appendChild(dom.createElement('td')) + const cardHeader = bookHeader.appendChild(dom.createElement('td')) + + const groupsMain = bookMain.appendChild(dom.createElement('td')) + const groupsMainTable = groupsMain.appendChild(dom.createElement('table')) + const peopleMain = bookMain.appendChild(dom.createElement('td')) + const peopleMainTable = peopleMain.appendChild(dom.createElement('table')) + + const groupsFooter = bookFooter.appendChild(dom.createElement('td')) + const peopleFooter = bookFooter.appendChild(dom.createElement('td')) + const cardFooter = bookFooter.appendChild(dom.createElement('td')) + + cardHeader.appendChild(dom.createElement('div')) // searchDiv + // searchDiv.setAttribute('style', 'border: 0.1em solid #888; border-radius: 0.5em') + const searchInput = cardHeader.appendChild(dom.createElement('input')) + searchInput.setAttribute('type', 'text') + searchInput.setAttribute( + 'style', + 'border: 0.1em solid #444; border-radius: 0.5em; width: 100%; font-size: 100%; padding: 0.1em 0.6em' + ) + + searchInput.addEventListener('input', function (_event) { + refreshFilteredPeople(true) // Active: select person if just one left + }) + + const cardMain = bookMain.appendChild(dom.createElement('td')) + cardMain.setAttribute('style', 'margin: 0;') // fill space available + const dataCellStyle = 'padding: 0.1em;' + + groupsHeader.textContent = 'groups' + groupsHeader.setAttribute( + 'style', + 'min-width: 10em; padding-bottom 0.2em;' + ) + + function setGroupListVisibility (visible) { + const vis = visible ? '' : 'display: none;' + groupsHeader.setAttribute( + 'style', + 'min-width: 10em; padding-bottom 0.2em;' + vis + ) + const hfstyle = 'padding: 0.1em;' + groupsMain.setAttribute('style', hfstyle + vis) + groupsFooter.setAttribute('style', hfstyle + vis) + } + setGroupListVisibility(true) + + if (options.foreignGroup) { + selectedGroups[options.foreignGroup.uri] = true + } + if (book) { + const allGroups = groupsHeader.appendChild(dom.createElement('button')) + allGroups.textContent = 'All' + const style = 'margin-left: 1em; font-size: 100%;' + allGroups.setAttribute('style', style) + allGroups.addEventListener('click', function (_event) { + allGroups.state = allGroups.state ? 0 : 1 + peopleMainTable.innerHTML = '' // clear in case refreshNames doesn't work for unknown reason + if (allGroups.state) { + allGroups.setAttribute('style', style + 'background-color: #ff8;') + selectAllGroups(selectedGroups, groupsMainTable, function ( + ok, + message + ) { + if (!ok) return complain(message) + allGroups.setAttribute( + 'style', + style + 'background-color: black; color: white' + ) + refreshGroupsSelected() + }) + } else { + allGroups.setAttribute('style', style + 'background-color: #cfc;') // pale green hint groups loaded + selectedGroups = {} + refreshGroupsSelected() + } + }) // on button click + kb.fetcher.nowOrWhenFetched(groupIndex.uri, book, function (ok, body) { + if (!ok) return console.log('Cannot load group index: ' + body) + syncGroupTable() + refreshNames() + }) + } else { + syncGroupTable() + refreshNames() + console.log('No book, only one group -> hide list of groups') + setGroupListVisibility(false) // If no books involved, hide group list + } // if not book + + peopleHeader.textContent = 'name' + peopleHeader.setAttribute('style', 'min-width: 18em;') + peopleMain.setAttribute('style', 'overflow:scroll;') + + // New Contact button + const newContactButton = dom.createElement('button') + const container = dom.createElement('div') + newContactButton.setAttribute('type', 'button') + + if (!me) newContactButton.setAttribute('disabled', 'true') + + solid_ui__WEBPACK_IMPORTED_MODULE_0__["authn"].checkUser().then(webId => { + if (webId) { + me = webId + newContactButton.removeAttribute('disabled') + } + }) + + container.appendChild(newContactButton) + newContactButton.innerHTML = 'New Contact' // + IndividualClassLabel + peopleFooter.appendChild(container) + + newContactButton.addEventListener('click', newContactClickHandler, false) + + // New Group button + if (book) { + const newGroupButton = groupsFooter.appendChild( + dom.createElement('button') + ) + newGroupButton.setAttribute('type', 'button') + newGroupButton.innerHTML = 'New Group' // + IndividualClassLabel + newGroupButton.addEventListener( + 'click', newGroupClickHandler, + false + ) + + // Tools button + const toolsButton = cardFooter.appendChild(dom.createElement('button')) + toolsButton.setAttribute('type', 'button') + toolsButton.innerHTML = 'Tools' + toolsButton.addEventListener('click', function (_event) { + cardMain.innerHTML = '' + cardMain.appendChild( + Object(_toolsPane__WEBPACK_IMPORTED_MODULE_1__["toolsPane"])( + selectAllGroups, + selectedGroups, + groupsMainTable, + book, + dataBrowserContext, + me + ) + ) + }) + } // if book + + cardFooter.appendChild(newAddressBookButton(book)) + + // }) + + div.appendChild(dom.createElement('hr')) + // div.appendChild(newAddressBookButton(book)) // later + // end of AddressBook instance + } // renderThreeColumnBrowser + + // /////////////////////////////////////////////////////////////////////////////////// + + // Render a single contact Individual + + if ( + t[ns.vcard('Individual').uri] || + t[ns.vcard('Organization').uri] || + t[ns.foaf('Person').uri] || + t[ns.schema('Person').uri] + ) { + Object(_individual__WEBPACK_IMPORTED_MODULE_3__["renderIndividual"])(dom, div, subject, dataBrowserContext).then(() => console.log('(individual rendered)')) + + // Render a Group instance + } else if (t[ns.vcard('Group').uri]) { + // If we have a main address book, then render this group as a guest group within it + solid_ui__WEBPACK_IMPORTED_MODULE_0__["authn"] + .findAppInstances(context, ns.vcard('AddressBook')) + .then(function (context) { + const addressBooks = context.instances + const options = { foreignGroup: subject } + if (addressBooks.length > 0) { + // const book = addressBooks[0] + renderThreeColumnBrowser(addressBooks, context, options) + } else { + renderThreeColumnBrowser([], context, options) + // @@ button to Make a new addressBook + } + }) + .catch(function (e) { + solid_ui__WEBPACK_IMPORTED_MODULE_0__["widgets"].complain(context, e) + }) + + // Render a AddressBook instance + } else if (t[ns.vcard('AddressBook').uri]) { + renderThreeColumnBrowser([subject], context, {}) + } else { + console.log( + 'Error: Contact pane: No evidence that ' + + subject + + ' is anything to do with contacts.' + ) + } + + me = solid_ui__WEBPACK_IMPORTED_MODULE_0__["authn"].currentUser() + if (!me) { + console.log( + '(You do not have your Web Id set. Sign in or sign up to make changes.)' + ) + solid_ui__WEBPACK_IMPORTED_MODULE_0__["authn"].logInLoadProfile(context).then( + context => { + console.log('Logged in as ' + context.me) + me = context.me + }, + err => { + div.appendChild(solid_ui__WEBPACK_IMPORTED_MODULE_0__["widgets"].errorMessageBlock(err)) + } + ) + } else { + // console.log("(Your webid is "+ me +")") + } + + // /////////////// Fix user when testing on a plane + + if ( + typeof document !== 'undefined' && + document.location && + ('' + document.location).slice(0, 16) === 'http://localhost' + ) { + me = kb.any(subject, solid_ui__WEBPACK_IMPORTED_MODULE_0__["ns"].acl('owner')) // when testing on plane with no webid + console.log('Assuming user is ' + me) + } + return div + } // asyncRender + } // render function +}); // pane object +// ends + + +/***/ }), + +/***/ "./node_modules/contacts-pane/groupMembershipControl.js": +/*!**************************************************************!*\ + !*** ./node_modules/contacts-pane/groupMembershipControl.js ***! + \**************************************************************/ +/*! exports provided: renderGroupMemberships */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "renderGroupMemberships", function() { return renderGroupMemberships; }); +/* harmony import */ var solid_ui__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! solid-ui */ "./node_modules/solid-ui/lib/index.js"); +/* harmony import */ var solid_ui__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(solid_ui__WEBPACK_IMPORTED_MODULE_0__); + +// Render a control to record the group memberships we have for this agent + + +const $rdf = solid_ui__WEBPACK_IMPORTED_MODULE_0__["rdf"] +const ns = solid_ui__WEBPACK_IMPORTED_MODULE_0__["ns"] +// const buttons = UI.buttonsn no +// const widgets = UI.widgets +const utils = solid_ui__WEBPACK_IMPORTED_MODULE_0__["utils"] +const kb = solid_ui__WEBPACK_IMPORTED_MODULE_0__["store"] +// const style = UI.style + +// Groups the person is a member of + +async function renderGroupMemberships (person, context) { + // Remove a person from a group + function removeFromGroup (thing, group) { + const pname = kb.any(thing, ns.vcard('fn')) + const gname = kb.any(group, ns.vcard('fn')) + const groups = kb.each(null, ns.vcard('hasMember'), thing) + if (groups.length < 2) { + alert( + 'Must be a member of at least one group. Add to another group first.' + ) + return + } + const message = 'Remove ' + pname + ' from group ' + gname + '?' + if (confirm(message)) { + const del = [ + $rdf.st(group, ns.vcard('hasMember'), thing, group.doc()), + $rdf.st(thing, ns.vcard('fn'), pname, group.doc()) + ] + kb.updater.update(del, [], function (uri, ok, err) { + if (!ok) { + const message = 'Error removing member from group ' + group + ': ' + err + groupList.parentNode.appendChild(solid_ui__WEBPACK_IMPORTED_MODULE_0__["widgets"].errorMessageBlock(dom, message, 'pink')) + return + } + console.log('Removed ' + pname + ' from group ' + gname) + syncGroupList() + }) + } + } + function newRowForGroup (group) { + const options = { + deleteFunction: function () { + removeFromGroup(person, group) + }, + noun: 'membership' + } + const tr = solid_ui__WEBPACK_IMPORTED_MODULE_0__["widgets"].personTR(dom, null, group, options) + return tr + } + + function syncGroupList () { + const groups = kb.each(null, ns.vcard('hasMember'), person) + utils.syncTableToArray(groupList, groups, newRowForGroup) + } + + const { dom } = context + const groupList = dom.createElement('table') + groupList.refresh = syncGroupList + syncGroupList() + return groupList +} + + +/***/ }), + +/***/ "./node_modules/contacts-pane/individual.js": +/*!**************************************************!*\ + !*** ./node_modules/contacts-pane/individual.js ***! + \**************************************************/ +/*! exports provided: renderIndividual */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "renderIndividual", function() { return renderIndividual; }); +/* harmony import */ var solid_ui__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! solid-ui */ "./node_modules/solid-ui/lib/index.js"); +/* harmony import */ var solid_ui__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(solid_ui__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _mugshotGallery__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./mugshotGallery */ "./node_modules/contacts-pane/mugshotGallery.js"); +/* harmony import */ var _webidControl__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./webidControl */ "./node_modules/contacts-pane/webidControl.js"); +/* harmony import */ var _groupMembershipControl_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./groupMembershipControl.js */ "./node_modules/contacts-pane/groupMembershipControl.js"); +/* harmony import */ var _individualForm__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./individualForm */ "./node_modules/contacts-pane/individualForm.js"); +/* harmony import */ var _vcard_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./vcard.js */ "./node_modules/contacts-pane/vcard.js"); + + + + + + + +const $rdf = solid_ui__WEBPACK_IMPORTED_MODULE_0__["rdf"] +const ns = solid_ui__WEBPACK_IMPORTED_MODULE_0__["ns"] +// const utils = UI.utils +const kb = solid_ui__WEBPACK_IMPORTED_MODULE_0__["store"] + +// Render Individual card + +async function renderIndividual (dom, div, subject, dataBrowserContext) { + // //////////////////// DRAG and Drop for mugshot image + + function complain (message) { + console.log(message) + div.appendChild(solid_ui__WEBPACK_IMPORTED_MODULE_0__["widgets"].errorMessageBlock(dom, message, 'pink')) + } + + function spacer () { + div + .appendChild(dom.createElement('div')) + .setAttribute('style', 'height: 1em') + } + function complainIfBad (ok, body) { + if (!ok) { + complain('Error: ' + body) + } + } + + function setPaneStyle () { + const types = kb.findTypeURIs(subject) + let mystyle = 'padding: 0.5em 1.5em 1em 1.5em; ' + let backgroundColor = null + for (const uri in types) { + backgroundColor = kb.anyValue( + kb.sym(uri), + ns.solid('profileHighlightColor') + ) + if (backgroundColor) break + } + // allow the parent element to define background by default + backgroundColor = backgroundColor || 'transparent' + mystyle += 'background-color: ' + backgroundColor + '; ' + div.setAttribute('style', mystyle) + } + + /// /////////////////////////// + + // Background metadata for this pane we bundle with the JS + const individualForm = kb.sym( + 'https://solid.github.io/solid-panes/contact/individualForm.ttl#form1' + ) + const individualFormDoc = individualForm.doc() + if (!kb.holds(undefined, undefined, undefined, individualFormDoc)) { + // If not loaded already + // var individualFormText = require('./individualForm.js') + $rdf.parse(_individualForm__WEBPACK_IMPORTED_MODULE_4__["default"], kb, individualFormDoc.uri, 'text/turtle') // Load form directly + } + const vcardOnt = solid_ui__WEBPACK_IMPORTED_MODULE_0__["ns"].vcard('Type').doc() + if (!kb.holds(undefined, undefined, undefined, vcardOnt)) { + // If not loaded already + $rdf.parse(_vcard_js__WEBPACK_IMPORTED_MODULE_5__["default"], kb, vcardOnt.uri, 'text/turtle') // Load ontology directly + } + + try { + await kb.fetcher.load(subject.doc()) + } catch (err) { + complain('Error: Failed to load contact card: ' + err) + } // end of try catch on load + + setPaneStyle() + + solid_ui__WEBPACK_IMPORTED_MODULE_0__["authn"].checkUser() // kick off async operation @@@ use async version + + div.appendChild(Object(_mugshotGallery__WEBPACK_IMPORTED_MODULE_1__["renderMugshotGallery"])(dom, subject)) + + solid_ui__WEBPACK_IMPORTED_MODULE_0__["widgets"].appendForm( + dom, + div, + {}, + subject, + individualForm, + subject.doc(), + complainIfBad + ) + + spacer() + + div.appendChild(await Object(_groupMembershipControl_js__WEBPACK_IMPORTED_MODULE_3__["renderGroupMemberships"])(subject, dataBrowserContext)) + + spacer() + + // Allow to attach documents etc to the contact card + + const editable = kb.updater.editable(subject.doc().uri, kb) + solid_ui__WEBPACK_IMPORTED_MODULE_0__["widgets"].attachmentList(dom, subject, div, { + modify: editable + // promptIcon: UI.icons.iconBase + 'noun_681601.svg', + // predicate: UI.ns.vcard('url') // @@@@@@@@@ ,--- no, the vcard ontology structure uses a bnode. + }) + + spacer() + + div.appendChild(await Object(_webidControl__WEBPACK_IMPORTED_MODULE_2__["renderWedidControl"])(subject, dataBrowserContext)) + + // div.appendChild(dom.createElement('hr')) +} // renderIndividual + + +/***/ }), + +/***/ "./node_modules/contacts-pane/individualForm.js": +/*!******************************************************!*\ + !*** ./node_modules/contacts-pane/individualForm.js ***! + \******************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony default export */ __webpack_exports__["default"] = (` +@prefix rdf: . +@prefix ui: . +@prefix : <#>. + + + ui:creationForm <#form1> . + + +<#form1> + "Contact Details" ; + a ui:Form ; + ui:part + <#fullNameField>, <#roleField>, <#fullNameFieldC>, <#addressesComment>, <#addresses>, + <#emailComment>, <#eMails>, + <#telephoneComment>, <#telephones>, <#noteComment>, <#noteField> ; + ui:parts ( + <#fullNameField> <#roleField> <#fullNameFieldC> + <#addressesComment> <#addresses> + <#emailComment> <#eMails> + <#telephoneComment> <#telephones> <#noteComment> <#noteField> ) . + + <#fullNameField> + a ; + ui:label "Name"; + "128" ; + ; + "40" . + + <#roleField> + a ; + "128" ; + ; + "40" . + + <#fullNameFieldC> + a ; + "128" ; + ; + "40" . + + +<#addressesComment> + a ; + "Address" . + + +<#addresses> + "Address details" ; + a ; + <#oneAddress> ; + . + +<#oneAddress> + a ; + ( <#id1409437207443> <#id1409437292400> <#id1409437421996> <#id1409437467649> <#id1409437569420> <#id1409437646712> ). + +<#id1409437207443> + a ; + "128" ; + ; + "40" . + +<#id1409437292400> + a ; + "128" ; + ; + "40" . + +<#id1409437421996> + a ; + "25" ; + ; + "25" . + +<#id1409437467649> + a ; + "128" ; + ; + "40" . + +<#id1409437569420> + a ; + "128" ; + ; + "40" . + +<#id1409437646712> + a ; + rdf:Class ; + . + + +############################## + +<#emailComment> + a ; + "Email" . + + +<#eMails> + a ; + <#oneEMail> ; + . + +<#oneEMail> + a ; + <#emailValue>, <#emailType> . + +<#emailValue> + a ; ui:label "email"; + ; + "50" . + +<#emailType> + a ; + "0" ; + ; + ; + . + +############################## + +<#telephoneComment> + a ; + "Phones" . + + +<#telephones> + a ; + <#onetelephone> ; + . + +<#onetelephone> + a ; + <#telephoneValue>, <#telephoneType> . + +<#telephoneValue> + a ; + ; + "50" . + +<#telephoneType> + a ; + "0" ; + ; + ; + . + +############################## + +<#noteComment> + a ; + "General Notes" . + +<#noteField> + a ; + . +`); + + +/***/ }), + +/***/ "./node_modules/contacts-pane/mintNewAddressBook.js": +/*!**********************************************************!*\ + !*** ./node_modules/contacts-pane/mintNewAddressBook.js ***! + \**********************************************************/ +/*! exports provided: mintNewAddressBook */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mintNewAddressBook", function() { return mintNewAddressBook; }); +const UI = __webpack_require__(/*! solid-ui */ "./node_modules/solid-ui/lib/index.js") + +// const mime = require('mime-types') +// const toolsPane0 = require('./toolsPane') +// const toolsPane = toolsPane0.toolsPane + +const $rdf = UI.rdf +// const ns = UI.ns +// const utils = UI.utils + +// Mint a new address book + +function mintNewAddressBook (dataBrowserContext, context) { + return new Promise(function (resolve, reject) { + UI.authn.logInLoadProfile(context).then( + context => { + // 20180713 + console.log('Logged in as ' + context.me) + const me = context.me + + const dom = context.dom + const div = context.div + const kb = dataBrowserContext.session.store + const ns = UI.ns + const newBase = context.newBase || context.newInstance.dir().uri + const instanceClass = context.instanceClass || ns.vcard('AddressBook') + + if (instanceClass.sameTerm(ns.vcard('Group'))) { + // Make a group not an address book + const g = + context.newInstance || kb.sym(context.newBase + 'index.ttl#this') + const doc = g.doc() + kb.add(g, ns.rdf('type'), ns.vcard('Group'), doc) + kb.add( + g, + ns.vcard('fn'), + context.instanceName || 'untitled group', + doc + ) // @@ write doc back + kb.fetcher + .putBack(doc, { contentType: 'text/turtle' }) + .then(function (_xhr) { + resolve(context) + }) + .catch(function (err) { + reject( + new Error('Error creating document for new group ' + err) + ) + }) + return + } + const appInstanceNoun = 'address book' + + function complain (message) { + div.appendChild(UI.widgets.errorMessageBlock(dom, message, 'pink')) + } + + let bookContents = `@prefix vcard: . + @prefix ab: . + @prefix dc: . + @prefix xsd: . + + <#this> a vcard:AddressBook; + dc:title "New address Book"; + vcard:nameEmailIndex ; + vcard:groupIndex . +` + + bookContents += + '<#this> <' + + me.uri + + '>.\n\n' + + const newAppInstance = kb.sym(newBase + 'index.ttl#this') + + const toBeWritten = [ + { + to: 'index.ttl', + content: bookContents, + contentType: 'text/turtle' + }, + { to: 'groups.ttl', content: '', contentType: 'text/turtle' }, + { to: 'people.ttl', content: '', contentType: 'text/turtle' }, + { to: '', existing: true, aclOptions: { defaultForNew: true } } + ] + + // @@ Ask user abut ACLs? + + // + // @@ Add header to PUT If-None-Match: * to prevent overwrite + // + + function claimSuccess (newAppInstance, appInstanceNoun) { + // @@ delete or grey other stuff + console.log(`New ${appInstanceNoun} created at ${newAppInstance}`) + const p = div.appendChild(dom.createElement('p')) + p.setAttribute('style', 'font-size: 140%;') + p.innerHTML = + "Your new " + + appInstanceNoun + + ' is ready. ' + + "

Go to new " + + appInstanceNoun + + '' + const newContext = Object.assign( + { newInstance: newAppInstance }, + context + ) + resolve(newContext) + } + + function doNextTask () { + function checkOKSetACL (uri, ok) { + if (!ok) { + complain('Error writing new file ' + task.to) + return reject(new Error('Error writing new file ' + task.to)) + } + + UI.authn + .setACLUserPublic(dest, me, aclOptions) + .then(() => doNextTask()) + .catch(err => { + const message = + 'Error setting access permissions for ' + + task.to + + ' : ' + + err.message + complain(message) + return reject(new Error(message)) + }) + } + + if (toBeWritten.length === 0) { + claimSuccess(newAppInstance, appInstanceNoun) + } else { + var task = toBeWritten.shift() /* eslint-disable-line no-var */ + console.log('Creating new file ' + task.to + ' in new instance ') + var dest = $rdf.uri.join(task.to, newBase) /* eslint-disable-line no-var */ + var aclOptions = task.aclOptions || {} /* eslint-disable-line no-var */ + + if ('content' in task) { + kb.fetcher + .webOperation('PUT', dest, { + data: task.content, + saveMetadata: true, + contentType: task.contentType + }) + .then(() => checkOKSetACL(dest, true)) + } else if ('existing' in task) { + checkOKSetACL(dest, true) + } else { + reject(new Error('copy not expected buiding new app!!')) + // const from = task.from || task.to // default source to be same as dest + // UI.widgets.webCopy(base + from, dest, task.contentType, checkOKSetACL) + } + } + } + doNextTask() + }, + err => { + // log in then + context.div.appendChild(UI.widgets.errorMessageBlock(err)) + } + ) + }) +} + + +/***/ }), + +/***/ "./node_modules/contacts-pane/mugshotGallery.js": +/*!******************************************************!*\ + !*** ./node_modules/contacts-pane/mugshotGallery.js ***! + \******************************************************/ +/*! exports provided: renderMugshotGallery */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "renderMugshotGallery", function() { return renderMugshotGallery; }); +/* harmony import */ var solid_ui__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! solid-ui */ "./node_modules/solid-ui/lib/index.js"); +/* harmony import */ var solid_ui__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(solid_ui__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var mime_types__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! mime-types */ "./node_modules/mime-types/index.js"); +/* harmony import */ var mime_types__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(mime_types__WEBPACK_IMPORTED_MODULE_1__); + + + +const $rdf = solid_ui__WEBPACK_IMPORTED_MODULE_0__["rdf"] +const ns = solid_ui__WEBPACK_IMPORTED_MODULE_0__["ns"] +const utils = solid_ui__WEBPACK_IMPORTED_MODULE_0__["utils"] +const kb = solid_ui__WEBPACK_IMPORTED_MODULE_0__["store"] + +/* Mugshot Gallery +* +* A widget for managing a set of images. +* Make this a form field? +*/ +function renderMugshotGallery (dom, subject) { + function complain (message) { + console.log(message) + galleryDiv.appendChild(solid_ui__WEBPACK_IMPORTED_MODULE_0__["widgets"].errorMessageBlock(dom, message, 'pink')) + } + + async function linkToPicture (subject, pic, remove) { + const link = [ + $rdf.st(subject, ns.vcard('hasPhoto'), pic, subject.doc()) + ] + try { + if (remove) { + await kb.updater.update(link, []) + } else { + await kb.updater.update([], link) + } + } catch (err) { + const msg = ' Write back image link FAIL ' + pic + ', Error: ' + err + console.log(msg) + alert(msg) + } + } + + function handleDroppedThing (thing) { + kb.fetcher.nowOrWhenFetched(thing.doc(), function (ok, mess) { + if (!ok) { + console.log('Error looking up dropped thing ' + thing + ': ' + mess) + } else { + const types = kb.findTypeURIs(thing) + for (const ty in types) { + console.log(' drop object type includes: ' + ty) // @@ Allow email addresses and phone numbers to be dropped? + } + console.log('Default: assume web page ' + thing) // icon was: UI.icons.iconBase + 'noun_25830.svg' + kb.add(subject, ns.wf('attachment'), thing, subject.doc()) + // @@ refresh UI + } + }) + } + + function uploadFileToContact (filename, contentType, data) { + // const fileExtension = filename.split('.').pop() // .toLowerCase() + const extension = mime_types__WEBPACK_IMPORTED_MODULE_1__["extension"](contentType) + if (contentType !== mime_types__WEBPACK_IMPORTED_MODULE_1__["lookup"](filename)) { + filename += '_.' + extension + console.log('MIME TYPE MISMATCH -- adding extension: ' + filename) + } + let prefix, predicate + const isImage = contentType.startsWith('image') + if (isImage) { + prefix = 'image_' + predicate = ns.vcard('hasPhoto') + } else { + prefix = 'attachment_' + predicate = ns.wf('attachment') + } + + let n, pic + for (n = 0; ; n++) { + // Check filename is not used or invent new one + pic = kb.sym(subject.dir().uri + filename) + if (!kb.holds(subject, ns.vcard('hasPhoto'), pic)) { + break + } + filename = prefix + n + '.' + extension + } + console.log( + 'Putting ' + + data.byteLength + + ' bytes of ' + + contentType + + ' to ' + + pic + ) + kb.fetcher + .webOperation('PUT', pic.uri, { + data: data, + contentType: contentType + }) + .then(function (response) { + if (!response.ok) { + complain('Error uploading ' + pic + ':' + response.status) + return + } + console.log(' Upload: put OK: ' + pic) + kb.add(subject, predicate, pic, subject.doc()) + kb.fetcher + .putBack(subject.doc(), { contentType: 'text/turtle' }) + .then( + function (_response) { + if (isImage) { + mugshotDiv.refresh() + } + }, + function (err) { + console.log( + ' Write back image link FAIL ' + pic + ', Error: ' + err + ) + } + ) + }) + } + + // When a set of URIs are dropped on + function handleURIsDroppedOnMugshot (uris) { + uris.forEach(function (u) { + const thing = $rdf.sym(u) // Attachment needs text label to disinguish I think not icon. + console.log('Dropped on mugshot thing ' + thing) // icon was: UI.icons.iconBase + 'noun_25830.svg' + if (u.startsWith('http') && u.indexOf('#') < 0) { + // Plain document + // Take a copy of a photo on the web: + const options = { withCredentials: false, credentials: 'omit' } + kb.fetcher.webOperation('GET', thing.uri, options).then( + result => { + const contentType = result.headers.get('Content-Type') + // let data = result.responseText + let pathEnd = thing.uri.split('/').slice(-1)[0] // last segment as putative filename + pathEnd = pathEnd.split('?')[0] // chop off any query params + result.arrayBuffer().then(function (data) { + // read text stream + if (!result.ok) { + complain('Error downloading ' + thing + ':' + result.status) + return + } + uploadFileToContact(pathEnd, contentType, data) + }) + }, + err => { + complain( + `WebOp (fetch) error trying to read picture ${thing} on web: ${err}` + ) + } + ) + return + } else { + console.log( + 'Not a web document URI, cannot copy as picture: ' + thing + ) + } + handleDroppedThing(thing) + }) + } + + // Drop an image file to set up the mugshot + function droppedFileHandler (files) { + for (let i = 0; i < files.length; i++) { + const f = files[i] + console.log( + ' contacts: Filename: ' + + f.name + + ', type: ' + + (f.type || 'n/a') + + ' size: ' + + f.size + + ' bytes, last modified: ' + + (f.lastModifiedDate + ? f.lastModifiedDate.toLocaleDateString() + : 'n/a') + ) // See e.g. https://www.html5rocks.com/en/tutorials/file/dndfiles/ + + // @@ Add: progress bar(s) + const reader = new FileReader() + reader.onload = (function (theFile) { + return function (e) { + const data = e.target.result + console.log(' File read byteLength : ' + data.byteLength) + const filename = encodeURIComponent(theFile.name) + const contentType = theFile.type + uploadFileToContact(filename, contentType, data) + } + })(f) + reader.readAsArrayBuffer(f) + } + } + + function elementForImage (image) { + const img = dom.createElement('img') + img.setAttribute( + 'style', + 'max-height: 10em; border-radius: 1em; margin: 0.7em;' + ) + solid_ui__WEBPACK_IMPORTED_MODULE_0__["widgets"].makeDropTarget( + img, + handleURIsDroppedOnMugshot, + droppedFileHandler + ) + if (image) { + img.setAttribute('src', image.uri) + solid_ui__WEBPACK_IMPORTED_MODULE_0__["widgets"].makeDraggable(img, image) + } + return img + } + + function syncMugshots () { + let images = kb.each(subject, ns.vcard('hasPhoto')) // Priviledge vcard ones + images.sort() // arbitrary consistency + images = images.slice(0, 5) // max number for the space + if (images.length === 0) { + mugshotDiv.innerHTML = '' // strictly, don't remove it if already there + if (editable) { + mugshotDiv.appendChild(placeholder) // A head image to drop pictures on + } // otherwise leave gallery empty .. nothing to see here folks + } else { + utils.syncTableToArray(mugshotDiv, images, elementForImage) + } + } + + // Good URI for a Camera picture + function getImageDoc () { + const imageDoc = kb.sym( + subject.dir().uri + 'Image_' + Date.now() + '.png' + ) + return imageDoc + } + // Store picture + async function tookPicture (imageDoc) { + if (imageDoc) { + await linkToPicture(subject, imageDoc) + syncMugshots() + } + } + + function trashCan () { + const button = solid_ui__WEBPACK_IMPORTED_MODULE_0__["widgets"].button( + dom, + solid_ui__WEBPACK_IMPORTED_MODULE_0__["icons"].iconBase + 'noun_925021.svg', + 'Drag here to delete' + ) + async function droppedURIHandler (uris) { + const images = kb + .each(subject, ns.vcard('hasPhoto')) + .map(x => x.uri) + for (const uri of uris) { + if (!images.includes(uri)) { + alert('Only drop images in this contact onto this trash can.') + return + } + if (confirm(`Permanently DELETE image ${uri} completely?`)) { + console.log('Unlinking image file ' + uri) + await linkToPicture(subject, kb.sym(uri), true) + try { + console.log('Deleting image file ' + uri) + await kb.fetcher.webOperation('DELETE', uri) + } catch (err) { + alert('Unable to delete picture! ' + err) + } + } + } + syncMugshots() + } + solid_ui__WEBPACK_IMPORTED_MODULE_0__["widgets"].makeDropTarget(button, droppedURIHandler, null) + return button + } + + function renderImageTools () { + const imageToolTable = dom.createElement('table') + const row = imageToolTable.appendChild(dom.createElement('tr')) + const left = row.appendChild(dom.createElement('td')) + const middle = row.appendChild(dom.createElement('td')) + const right = row.appendChild(dom.createElement('td')) + + left.appendChild( + solid_ui__WEBPACK_IMPORTED_MODULE_0__["media"].cameraButton(dom, kb, getImageDoc, tookPicture) + ) // 20190812 + try { + middle.appendChild( + solid_ui__WEBPACK_IMPORTED_MODULE_0__["widgets"].fileUploadButtonDiv(dom, droppedFileHandler) + ) + } catch (e) { + console.log('ignore fileUploadButtonDiv error for now', e) + } + right.appendChild(trashCan()) + return imageToolTable + } + + // Body of renderMugshotGallery + + const editable = kb.updater.editable(subject.doc().uri, kb) + const galleryDiv = dom.createElement('div') + const mugshotDiv = galleryDiv.appendChild(dom.createElement('div')) + const placeholder = elementForImage() + solid_ui__WEBPACK_IMPORTED_MODULE_0__["widgets"].setImage(placeholder, subject) // Fallback icon or get from web + syncMugshots() + mugshotDiv.refresh = syncMugshots + if (editable) { + galleryDiv.appendChild(renderImageTools()) + } + return galleryDiv +} + + +/***/ }), + +/***/ "./node_modules/contacts-pane/toolsPane.js": +/*!*************************************************!*\ + !*** ./node_modules/contacts-pane/toolsPane.js ***! + \*************************************************/ +/*! exports provided: toolsPane */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toolsPane", function() { return toolsPane; }); +/* harmony import */ var solid_ui__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! solid-ui */ "./node_modules/solid-ui/lib/index.js"); +/* harmony import */ var solid_ui__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(solid_ui__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _contactLogic__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./contactLogic */ "./node_modules/contacts-pane/contactLogic.js"); +// The tools pane is for managing and debugging and maintaining solid contacts databases +// +/* global confirm, $rdf */ + + + +function toolsPane ( + selectAllGroups, + selectedGroups, + groupsMainTable, + book, + dataBrowserContext, + me +) { + const dom = dataBrowserContext.dom + const kb = solid_ui__WEBPACK_IMPORTED_MODULE_0__["store"] + const ns = solid_ui__WEBPACK_IMPORTED_MODULE_0__["ns"] + const VCARD = ns.vcard + + const buttonStyle = 'font-size: 100%; margin: 0.8em; padding:0.5em;' + const pane = dom.createElement('div') + const table = pane.appendChild(dom.createElement('table')) + table.setAttribute( + 'style', + 'font-size:120%; margin: 1em; border: 0.1em #ccc ;' + ) + const headerRow = table.appendChild(dom.createElement('tr')) + headerRow.textContent = solid_ui__WEBPACK_IMPORTED_MODULE_0__["utils"].label(book) + ' - tools' + headerRow.setAttribute( + 'style', + 'min-width: 20em; padding: 1em; font-size: 150%; border-bottom: 0.1em solid red; margin-bottom: 2em;' + ) + + const statusRow = table.appendChild(dom.createElement('tr')) + const statusBlock = statusRow.appendChild(dom.createElement('div')) + statusBlock.setAttribute('style', 'padding: 2em;') + const MainRow = table.appendChild(dom.createElement('tr')) + const box = MainRow.appendChild(dom.createElement('table')) + table.appendChild(dom.createElement('tr')) // bottomRow + + const context = { + target: book, + me: me, + noun: 'address book', + div: pane, + dom: dom, + statusRegion: statusBlock + } + + function complain (message) { + console.log(message) + statusBlock.appendChild(solid_ui__WEBPACK_IMPORTED_MODULE_0__["widgets"].errorMessageBlock(dom, message, 'pink')) + } + + // Body of main pane function + async function main () { + box.appendChild( + solid_ui__WEBPACK_IMPORTED_MODULE_0__["aclControl"].ACLControlBox5( + book.dir(), + dataBrowserContext, + 'book', + kb, + function (ok, body) { + if (!ok) box.innerHTML = 'ACL control box Failed: ' + body + } + ) + ) + + // + try { + await solid_ui__WEBPACK_IMPORTED_MODULE_0__["authn"].registrationControl(context, book, ns.vcard('AddressBook')) + } catch (e) { + solid_ui__WEBPACK_IMPORTED_MODULE_0__["widgets"].complain(context, 'registrationControl: ' + e) + } + console.log('Registration control finished.') + + // Output stats in line mode form + const logSpace = MainRow.appendChild(dom.createElement('pre')) + function log (message) { + console.log(message) + logSpace.textContent += message + '\n' + } + + function stats () { + const totalCards = kb.each(undefined, VCARD('inAddressBook'), book).length + log('' + totalCards + ' cards loaded. ') + const groups = kb.each(book, VCARD('includesGroup')) + log('' + groups.length + ' total groups. ') + const gg = [] + for (const g in selectedGroups) { + gg.push(g) + } + log('' + gg.length + ' selected groups. ') + } + + async function loadIndexHandler (_event) { + loadIndexButton.setAttribute('style', 'background-color: #ffc;') + const nameEmailIndex = kb.any(book, ns.vcard('nameEmailIndex')) + try { + await kb.fetcher.load(nameEmailIndex) + } catch (e) { + loadIndexButton.setAttribute('style', 'background-color: #fcc;') + log('Error: People index has NOT been loaded' + e + '\n') + } + loadIndexButton.setAttribute('style', 'background-color: #cfc;') + log(' People index has been loaded\n') + } // loadIndexHandler + const loadIndexButton = pane.appendChild(dom.createElement('button')) + loadIndexButton.textContent = 'Load main index' + loadIndexButton.style.cssText = buttonStyle + loadIndexButton.addEventListener('click', loadIndexHandler) + + const statButton = pane.appendChild(dom.createElement('button')) + statButton.textContent = 'Statistics' + statButton.style.cssText = buttonStyle + statButton.addEventListener('click', stats) + + const checkAccessButton = pane.appendChild(dom.createElement('button')) + checkAccessButton.textContent = + 'Check individual card access of selected groups' + checkAccessButton.style.cssText = buttonStyle + async function checkAcces (_event) { + function doCard (card) { + solid_ui__WEBPACK_IMPORTED_MODULE_0__["widgets"].fixIndividualCardACL(card, log, function (ok, message) { + if (ok) { + log('Success for ' + solid_ui__WEBPACK_IMPORTED_MODULE_0__["utils"].label(card)) + } else { + log('Failure for ' + solid_ui__WEBPACK_IMPORTED_MODULE_0__["utils"].label(card) + ': ' + message) + } + }) + } + const gg = [] + for (const g in selectedGroups) { + gg.push(g) + } + + for (let i = 0; i < gg.length; i++) { + const g = kb.sym(gg[i]) + const a = kb.each(g, ns.vcard('hasMember')) + log(solid_ui__WEBPACK_IMPORTED_MODULE_0__["utils"].label(g) + ': ' + a.length + ' members') + for (let j = 0; j < a.length; j++) { + const card = a[j] + log(solid_ui__WEBPACK_IMPORTED_MODULE_0__["utils"].label(card)) + doCard(card) + } + } + } + checkAccessButton.addEventListener('click', checkAcces) + + // /////////////////////////////////////////////////////////////////////////// + // + // DUPLICATES CHECK + const checkDuplicates = pane.appendChild(dom.createElement('button')) + checkDuplicates.textContent = 'Find duplicate cards' + checkDuplicates.style.cssText = buttonStyle + checkDuplicates.addEventListener('click', function (_event) { + const stats = {} // global god context + + stats.book = book + stats.nameEmailIndex = kb.any(book, ns.vcard('nameEmailIndex')) + log('Loading name index...') + + solid_ui__WEBPACK_IMPORTED_MODULE_0__["store"].fetcher.nowOrWhenFetched( + stats.nameEmailIndex, + undefined, + function (_ok, _message) { + log('Loaded name index.') + + stats.cards = [] + stats.duplicates = [] + stats.definitive = [] + stats.nameless = [] + + stats.exactDuplicates = [] + stats.nameOnlyDuplicates = [] + + stats.uniquesSet = [] + stats.groupProblems = [] + + // Erase one card and all its files -> (err) + // + /* + function eraseOne (card) { + return new Promise(function (resolve, reject) { + function removeFromMainIndex () { + var indexBit = kb.connectedStatements(card, stats.nameEmailIndex) + log('Bits of the name index file:' + indexBit) + log('Patching main index file...') + kb.updater.update(indexBit, [], function (uri, ok, body) { + if (ok) { + log('Success') + resolve(null) + } else { + log('Error patching index file! ' + body) + reject('Error patching index file! ' + body) + } + }) + } + var filesToDelete = [ card.doc() ] + var photos = kb.each(card, ns.vcard('hasPhoto')) // could be > 1 + if (photos.length) { + filesToDelete = filesToDelete.concat(photos) + } + filesToDelete.push(card.dir()) // the folder last + log('Files to delete: ' + filesToDelete) + if (!confirm('DELETE card ' + card.dir() + ' for "' + kb.any(card, VCARD('fn')) + '", with ' + kb.each(card).length + 'statements?')) { + return resolve('Cancelled by user') + } + + function deleteNextFile () { + var resource = filesToDelete.shift() + if (!resource) { + log('All deleted') + removeFromMainIndex() + resolve() + } + log('Deleting ... ' + resource) + kb.fetcher.delete(resource) + .then(function () { + log('Deleted ok: ' + resource) + deleteNextFile() + }) + .catch(function (e) { + var err = '*** ERROR deleting ' + resource + ': ' + e + log(err) + if (confirm('Patch out index file for card ' + card.dir() + ' EVEN THOUGH card DELETE errors?')) { + removeFromMainIndex() + } else { + reject(err) + } + }) + } + deleteNextFile() + }) // Promise + } // erase one + */ + // Check actual records to see which are exact matches - slow + stats.nameDupLog = kb.sym(book.dir().uri + 'dedup-nameDupLog.ttl') + stats.exactDupLog = kb.sym(book.dir().uri + 'dedup-exactDupLog.ttl') + /* + function checkOne (card) { + return new Promise(function (resolve, reject) { + var name = kb.anyValue(card, ns.vcard('fn')) + var other = stats.definitive[name] + kb.fetcher.load([card, other]).then(function (xhrs) { + var exclude = {} + exclude[ns.vcard('hasUID').uri] = true + exclude[ns.dc('created').uri] = true + exclude[ns.dc('modified').uri] = true + function filtered (x) { + return kb.statementsMatching(null, null, null, x.doc()).filter(function (st) { + return !exclude[st.predicate.uri] + }) + } + var desc = filtered(card) + var desc2 = filtered(other) + // var desc = connectedStatements(card, card.doc(), exclude) + // var desc2 = connectedStatements(other, other.doc(), exclude) + if (desc.length !== desc2.length) { + log('CARDS to NOT match lengths ') + stats.nameOnlyDuplicates.push(card) + return resolve(false) + } + if (!desc.length) { + log('@@@@@@ Zero length ') + stats.nameOnlyDuplicates.push(card) + return resolve(false) + } + // //////// Compare the two + // Cheat: serialize and compare + // var cardText = $rdf.serialize(card.doc(), kb, card.doc().uri, 'text/turtle') + // var otherText = $rdf.serialize(other.doc(), kb, other.doc().uri, 'text/turtle') + var cardText = (new $rdf.Serializer(kb)).setBase(card.doc().uri).statementsToN3(desc) + var otherText = (new $rdf.Serializer(kb)).setBase(other.doc().uri).statementsToN3(desc2) + // + // log('Name: ' + name + ', statements: ' + desc.length) + // log('___________________________________________') + // log('KEEPING: ' + other.doc() + '\n' + cardText) + // log('___________________________________________') + // log('DELETING: '+ card.doc() + '\n' + otherText) + // log('___________________________________________') + // + if (cardText !== otherText) { + log('Texts differ') + stats.nameOnlyDuplicates.push(card) + return resolve(false) + } + var cardGroups = kb.each(null, ns.vcard('hasMember'), card) + var otherGroups = kb.each(null, ns.vcard('hasMember'), other) + for (var j = 0; j < cardGroups.length; j++) { + var found = false + for (var k = 0; k < otherGroups.length; k++) { + if (otherGroups[k].sameTerm(cardGroups[j])) { found = true } + } + if (!found) { + log('This one groups: ' + cardGroups) + log('Other one groups: ' + otherGroups) + log('Cant delete this one because it has a group, ' + cardGroups[j] + ', which the other does not.') + stats.nameOnlyDuplicates.push(card) + return resolve(false) + } + } + console.log('Group check done -- exact duplicate: ' + card) + stats.exactDuplicates.push(card) + resolve(true) + }).catch(function (e) { + log('Cant load a card! ' + [card, other] + ': ' + e) + stats.nameOnlyDuplicates.push(card) + resolve(false) + // if (confirm('Patch out index file for card ' + card.dir() + ' EVEN THOUGH card READ errors?')){ + // removeFromMainIndex() + // } + }) + }) + } // checkOne + */ + stats.nameOnlyErrors = [] + stats.nameLessZeroData = [] + stats.nameLessIndex = [] + stats.namelessUniques = [] + stats.nameOnlyDuplicatesGroupDiff = [] + + function checkOneNameless (card) { + return new Promise(function (resolve) { + kb.fetcher + .load(card) + .then(function (_xhr) { + log(' Nameless check ' + card) + const exclude = {} + exclude[ns.vcard('hasUID').uri] = true + exclude[ns.dc('created').uri] = true + exclude[ns.dc('modified').uri] = true + function filtered (x) { + return kb + .statementsMatching(null, null, null, x.doc()) + .filter(function (st) { + return !exclude[st.predicate.uri] + }) + } + + const desc = filtered(card) + // var desc = connectedStatements(card, card.doc(), exclude) + // var desc2 = connectedStatements(other, other.doc(), exclude) + if (!desc.length) { + log(' Zero length ' + card) + stats.nameLessZeroData.push(card) + return resolve(false) + } + // Compare the two + // Cheat: serialize and compare + // var cardText = $rdf.serialize(card.doc(), kb, card.doc().uri, 'text/turtle') + // var otherText = $rdf.serialize(other.doc(), kb, other.doc().uri, 'text/turtle') + const cardText = new $rdf.Serializer(kb) + .setBase(card.doc().uri) + .statementsToN3(desc) + const other = stats.nameLessIndex[cardText] + if (other) { + log(' Matches with ' + other) + const cardGroups = kb.each(null, ns.vcard('hasMember'), card) + const otherGroups = kb.each(null, ns.vcard('hasMember'), other) + for (let j = 0; j < cardGroups.length; j++) { + let found = false + for (let k = 0; k < otherGroups.length; k++) { + if (otherGroups[k].sameTerm(cardGroups[j])) found = true + } + if (!found) { + log('This one groups: ' + cardGroups) + log('Other one groups: ' + otherGroups) + log( + 'Cant skip this one because it has a group, ' + + cardGroups[j] + + ', which the other does not.' + ) + stats.nameOnlyDuplicatesGroupDiff.push(card) + return resolve(false) + } + } + console.log('Group check done -- exact duplicate: ' + card) + } else { + log('First nameless like: ' + card.doc()) + log('___________________________________________') + log(cardText) + log('___________________________________________') + stats.nameLessIndex[cardText] = card + stats.namelessUniques.push(card) + } + resolve(true) + }) + .catch(function (e) { + log('Cant load a nameless card!: ' + e) + stats.nameOnlyErrors.push(card) + resolve(false) + }) + }) + } // checkOneNameless + + function checkAllNameless () { + stats.namelessToCheck = + stats.namelessToCheck || stats.nameless.slice() + log('Nameless check left: ' + stats.namelessToCheck.length) + return new Promise(function (resolve) { + const x = stats.namelessToCheck.shift() + if (!x) { + log('namelessUniques: ' + stats.namelessUniques.length) + log('namelessUniques: ' + stats.namelessUniques) + if (stats.namelessUniques.length > 0 && + confirm( + 'Add all ' + + stats.namelessUniques.length + + ' nameless cards to the rescued set?' + ) + ) { + stats.uniques = stats.uniques.concat(stats.namelessUniques) + for (let k = 0; k < stats.namelessUniques.length; k++) { + stats.uniqueSet[stats.namelessUniques[k].uri] = true + } + } + return resolve(true) + } + checkOneNameless(x).then(function (exact) { + log(' Nameless check returns ' + exact) + checkAllNameless() // loop + }) + }) + } + + function checkGroupMembers () { + return new Promise(function (resolve) { + // var inUniques = 0 + log('Groups loaded') + for (let i = 0; i < stats.uniques.length; i++) { + stats.uniquesSet[stats.uniques[i].uri] = true + } + stats.groupMembers = kb + .statementsMatching(null, ns.vcard('hasMember')) + .map(st => st.object) + log(' Naive group members ' + stats.groupMembers.length) + stats.groupMemberSet = [] + for (let j = 0; j < stats.groupMembers.length; j++) { + stats.groupMemberSet[stats.groupMembers[j].uri] = + stats.groupMembers[j] + } + stats.groupMembers2 = [] + for (const g in stats.groupMemberSet) { + stats.groupMembers2.push(stats.groupMemberSet[g]) + } + log(' Compact group members ' + stats.groupMembers2.length) + + if ( + $rdf.keepThisCodeForLaterButDisableFerossConstantConditionPolice + ) { + // Don't inspect as seems groups membership is complete + for (let i = 0; i < stats.groupMembers.length; i++) { + const card = stats.groupMembers[i] + if (stats.uniquesSet[card.uri]) { + // inUniques += 1 + } else { + log(' Not in uniques: ' + card) + stats.groupProblems.push(card) + if (stats.duplicateSet[card.uri]) { + log(' ** IN duplicates alas:' + card) + } else { + log(' **** WTF?') + } + } + } + log('Problem cards: ' + stats.groupProblems.length) + } // if + resolve(true) + }) + } // checkGroupMembers + + function scanForDuplicates () { + return new Promise(function (resolve) { + stats.cards = kb.each(undefined, VCARD('inAddressBook'), stats.book) + log('' + stats.cards.length + ' total cards') + + let c, card, name + for (c = 0; c < stats.cards.length; c++) { + card = stats.cards[c] + name = kb.anyValue(card, ns.vcard('fn')) + if (!name) { + stats.nameless.push(card) + continue + } + if (stats.definitive[name] === card) { + // pass + } else if (stats.definitive[name]) { + const n = stats.duplicates.length + if (n < 100 || (n < 1000 && n % 10 === 0) || n % 100 === 0) { + // log('' + n + ') Possible duplicate ' + card + ' of: ' + definitive[name]) + } + stats.duplicates.push(card) + } else { + stats.definitive[name] = card + } + } + + stats.duplicateSet = [] + for (let i = 0; i < stats.duplicates.length; i++) { + stats.duplicateSet[stats.duplicates[i].uri] = stats.duplicates[i] + } + stats.namelessSet = [] + for (let i = 0; i < stats.nameless.length; i++) { + stats.namelessSet[stats.nameless[i].uri] = stats.nameless[i] + } + stats.uniques = [] + stats.uniqueSet = [] + for (let i = 0; i < stats.cards.length; i++) { + const uri = stats.cards[i].uri + if (!stats.duplicateSet[uri] && !stats.namelessSet[uri]) { + stats.uniques.push(stats.cards[i]) + stats.uniqueSet[uri] = stats.cards[i] + } + } + log('Uniques: ' + stats.uniques.length) + + log('' + stats.nameless.length + ' nameless cards.') + log( + '' + + stats.duplicates.length + + ' name-duplicate cards, leaving ' + + (stats.cards.length - stats.duplicates.length) + ) + resolve(true) + }) + } + + // Save a new clean version + function saveCleanPeople () { + let cleanPeople + + return Promise.resolve() + .then(() => { + cleanPeople = kb.sym(stats.book.dir().uri + 'clean-people.ttl') + let sts = [] + for (let i = 0; i < stats.uniques.length; i++) { + sts = sts.concat( + kb.connectedStatements(stats.uniques[i], stats.nameEmailIndex) + ) + } + const sz = new $rdf.Serializer(kb).setBase(stats.nameEmailIndex.uri) + log('Serializing index of uniques...') + const data = sz.statementsToN3(sts) + + return kb.fetcher.webOperation('PUT', cleanPeople, { + data: data, + contentType: 'text/turtle' + }) + }) + .then(function () { + log('Done uniques log ' + cleanPeople) + return true + }) + .catch(function (e) { + log('Error saving uniques: ' + e) + }) + } + + function saveCleanGroup (g) { + let cleanGroup + + return Promise.resolve() + .then(() => { + const s = g.uri.replace('/Group/', '/NewGroup/') + cleanGroup = kb.sym(s) + let sts = [] + for (let i = 0; i < stats.uniques.length; i++) { + sts = sts.concat( + kb.connectedStatements(stats.uniques[i], g.doc()) + ) + } + const sz = new $rdf.Serializer(kb).setBase(g.uri) + log(' Regenerating group of uniques...' + cleanGroup) + const data = sz.statementsToN3(sts) + + return kb.fetcher.webOperation('PUT', cleanGroup, { data }) + }) + .then(() => { + log(' Done uniques group ' + cleanGroup) + return true + }) + .catch(e => { + log('Error saving : ' + e) + }) + } + + function saveAllGroups () { + log('Saving ALL GROUPS') + return Promise.all(stats.groupObjects.map(saveCleanGroup)) + } + + const getAndSortGroups = function () { + let groups = [] + if (stats.book) { + const books = [stats.book] + books.forEach(function (book) { + const gs = book ? kb.each(book, ns.vcard('includesGroup')) : [] + const gs2 = gs.map(function (g) { + return [book, kb.any(g, ns.vcard('fn')), g] + }) + groups = groups.concat(gs2) + }) + groups.sort() + } + return groups + } + const groups = getAndSortGroups() // Needed? + + stats.groupObjects = groups.map(gstr => gstr[2]) + log('Loading ' + stats.groupObjects.length + ' groups... ') + kb.fetcher + .load(stats.groupObjects) + .then(scanForDuplicates) + .then(checkGroupMembers) + .then(checkAllNameless) + .then((resolve, reject) => { + if (confirm('Write new clean versions?')) { + resolve(true) + } else { + reject() + } + }) + .then(saveCleanPeople) + .then(saveAllGroups) + .then(function () { + log('Done!') + }) + } + ) + }) + + async function fixGroupless (book) { + const groupless = await getGroupless(book) + if (groupless.length === 0) { + log('No groupless cards found.') + return + } + const groupOfUngrouped = await Object(_contactLogic__WEBPACK_IMPORTED_MODULE_1__["saveNewGroup"])(book, 'ZSortThese') + if (confirm(`Add the ${groupless.length} cards without groups to a ZSortThese group?`)) { + for (const person of groupless) { + log(' adding ' + person) + await Object(_contactLogic__WEBPACK_IMPORTED_MODULE_1__["addPersonToGroup"])(person, groupOfUngrouped) + } + } + log('People moved to group.') + } + + async function getGroupless (book) { + const groupIndex = kb.any(book, ns.vcard('groupIndex')) + const nameEmailIndex = kb.any(book, ns.vcard('nameEmailIndex')) + try { + await kb.fetcher.load([nameEmailIndex, groupIndex]) + const groups = kb.each(book, ns.vcard('includesGroup')) + await kb.fetcher.load(groups) + } catch (e) { + complain('Error loading stuff:' + e) + } + + const reverseIndex = {} + const groupless = [] + const groups = kb.each(book, VCARD('includesGroup')) + + log('' + groups.length + ' total groups. ') + + for (let i = 0; i < groups.length; i++) { + const g = groups[i] + const a = kb.each(g, ns.vcard('hasMember')) + log(solid_ui__WEBPACK_IMPORTED_MODULE_0__["utils"].label(g) + ': ' + a.length + ' members') + for (let j = 0; j < a.length; j++) { + kb.allAliases(a[j]).forEach(function (y) { + reverseIndex[y.uri] = g + }) + } + } + + const cards = kb.each(undefined, VCARD('inAddressBook'), book) + log('' + cards.length + ' total cards') + for (let c = 0; c < cards.length; c++) { + if (!reverseIndex[cards[c].uri]) { + groupless.push(cards[c]) + log(' groupless ' + solid_ui__WEBPACK_IMPORTED_MODULE_0__["utils"].label(cards[c])) + } + } + log('' + groupless.length + ' groupless cards.') + return groupless + } + + const checkGroupless = pane.appendChild(dom.createElement('button')) + checkGroupless.style.cssText = buttonStyle + checkGroupless.textContent = 'Find individuals with no group' + checkGroupless.addEventListener('click', function (_event) { + log('Loading groups...') + selectAllGroups(selectedGroups, groupsMainTable, async function (ok, message) { + if (!ok) { + log('Load all groups: failed: ' + message) + return + } + + const nameEmailIndex = kb.any(book, ns.vcard('nameEmailIndex')) + try { + await kb.fetcher.load(nameEmailIndex) + } catch (e) { + complain(e) + } + log('Loaded groups and name index.') + getGroupless(book) + log('Groupless list finished..') + }) // select all groups then + }) + + const fixGrouplessButton = pane.appendChild(dom.createElement('button')) + fixGrouplessButton.style.cssText = buttonStyle + fixGrouplessButton.textContent = 'Put all individuals with no group in a new group' + fixGrouplessButton.addEventListener('click', _event => fixGroupless(book)) + } // main + main() + return pane +} // toolsPane + +// ends + + +/***/ }), + +/***/ "./node_modules/contacts-pane/vcard.js": +/*!*********************************************!*\ + !*** ./node_modules/contacts-pane/vcard.js ***! + \*********************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony default export */ __webpack_exports__["default"] = (` +@prefix : . +@prefix owl: . +@prefix rdf: . +@prefix rdfs: . +@prefix xml: . +@prefix xsd: . + +:Acquaintance a owl:Class ; + rdfs:label "Acquaintance"@en ; + rdfs:isDefinedBy ; + rdfs:subClassOf :RelatedType . + +:Agent a owl:Class ; + rdfs:label "Agent"@en ; + rdfs:isDefinedBy ; + rdfs:subClassOf :RelatedType . + +:BBS a owl:Class ; + rdfs:label "BBS"@en ; + rdfs:comment "This class is deprecated"@en ; + rdfs:isDefinedBy ; + rdfs:subClassOf :TelephoneType ; + owl:deprecated true . + +:Car a owl:Class ; + rdfs:label "Car"@en ; + rdfs:comment "This class is deprecated"@en ; + rdfs:isDefinedBy ; + rdfs:subClassOf :TelephoneType ; + owl:deprecated true . + +:Cell a owl:Class ; + rdfs:label "Cell"@en ; + rdfs:comment "Also called mobile telephone"@en ; + rdfs:isDefinedBy ; + rdfs:subClassOf :TelephoneType . + +:Child a owl:Class ; + rdfs:label "Child"@en ; + rdfs:isDefinedBy ; + rdfs:subClassOf :RelatedType . + +:Colleague a owl:Class ; + rdfs:label "Colleague"@en ; + rdfs:isDefinedBy ; + rdfs:subClassOf :RelatedType . + +:Contact a owl:Class ; + rdfs:label "Contact"@en ; + rdfs:isDefinedBy ; + rdfs:subClassOf :RelatedType . + +:Coresident a owl:Class ; + rdfs:label "Coresident"@en ; + rdfs:isDefinedBy ; + rdfs:subClassOf :RelatedType . + +:Coworker a owl:Class ; + rdfs:label "Coworker"@en ; + rdfs:isDefinedBy ; + rdfs:subClassOf :RelatedType . + +:Crush a owl:Class ; + rdfs:label "Crush"@en ; + rdfs:isDefinedBy ; + rdfs:subClassOf :RelatedType . + +:Date a owl:Class ; + rdfs:label "Date"@en ; + rdfs:isDefinedBy ; + rdfs:subClassOf :RelatedType . + +:Dom a owl:Class ; + rdfs:label "Dom"@en ; + rdfs:comment "This class is deprecated"@en ; + rdfs:isDefinedBy ; + rdfs:subClassOf :Type ; + owl:deprecated true . + +:Emergency a owl:Class ; + rdfs:label "Emergency"@en ; + rdfs:isDefinedBy ; + rdfs:subClassOf :RelatedType . + +:Fax a owl:Class ; + rdfs:label "Fax"@en ; + rdfs:isDefinedBy ; + rdfs:subClassOf :TelephoneType . + +:Female a owl:Class ; + rdfs:label "Female"@en ; + rdfs:isDefinedBy ; + rdfs:subClassOf :Gender . + +:Friend a owl:Class ; + rdfs:label "Friend"@en ; + rdfs:isDefinedBy ; + rdfs:subClassOf :RelatedType . + +:Home a owl:Class ; + rdfs:label "Home"@en ; + rdfs:comment "This implies that the property is related to an individual's personal life"@en ; + rdfs:isDefinedBy ; + rdfs:subClassOf :Type . + +:ISDN a owl:Class ; + rdfs:label "ISDN"@en ; + rdfs:comment "This class is deprecated"@en ; + rdfs:isDefinedBy ; + rdfs:subClassOf :Type ; + owl:deprecated true . + +:Internet a owl:Class ; + rdfs:label "Internet"@en ; + rdfs:comment "This class is deprecated"@en ; + rdfs:isDefinedBy ; + rdfs:subClassOf :Type ; + owl:deprecated true . + +:Intl a owl:Class ; + rdfs:label "Intl"@en ; + rdfs:comment "This class is deprecated"@en ; + rdfs:isDefinedBy ; + rdfs:subClassOf :Type ; + owl:deprecated true . + +:Kin a owl:Class ; + rdfs:label "Kin"@en ; + rdfs:isDefinedBy ; + rdfs:subClassOf :RelatedType . + +:Label a owl:Class ; + rdfs:label "Label"@en ; + rdfs:comment "This class is deprecated"@en ; + rdfs:isDefinedBy ; + rdfs:subClassOf :Type ; + owl:deprecated true . + +:Male a owl:Class ; + rdfs:label "Male"@en ; + rdfs:isDefinedBy ; + rdfs:subClassOf :Gender . + +:Me a owl:Class ; + rdfs:label "Me"@en ; + rdfs:isDefinedBy ; + rdfs:subClassOf :RelatedType . + +:Met a owl:Class ; + rdfs:label "Met"@en ; + rdfs:isDefinedBy ; + rdfs:subClassOf :RelatedType . + +:Modem a owl:Class ; + rdfs:label "Modem"@en ; + rdfs:comment "This class is deprecated"@en ; + rdfs:isDefinedBy ; + rdfs:subClassOf :TelephoneType ; + owl:deprecated true . + +:Msg a owl:Class ; + rdfs:label "Msg"@en ; + rdfs:comment "This class is deprecated"@en ; + rdfs:isDefinedBy ; + rdfs:subClassOf :TelephoneType ; + owl:deprecated true . + +:Muse a owl:Class ; + rdfs:label "Muse"@en ; + rdfs:isDefinedBy ; + rdfs:subClassOf :RelatedType . + +:Neighbor a owl:Class ; + rdfs:label "Neighbor"@en ; + rdfs:isDefinedBy ; + rdfs:subClassOf :RelatedType . + +:None a owl:Class ; + rdfs:label "None"@en ; + rdfs:isDefinedBy ; + rdfs:subClassOf :Gender . + +:Other a owl:Class ; + rdfs:label "Other"@en ; + rdfs:isDefinedBy ; + rdfs:subClassOf :Gender . + +:PCS a owl:Class ; + rdfs:label "PCS"@en ; + rdfs:comment "This class is deprecated"@en ; + rdfs:isDefinedBy ; + rdfs:subClassOf :TelephoneType ; + owl:deprecated true . + +:Pager a owl:Class ; + rdfs:label "Pager"@en ; + rdfs:isDefinedBy ; + rdfs:subClassOf :TelephoneType . + +:Parcel a owl:Class ; + rdfs:label "Parcel"@en ; + rdfs:comment "This class is deprecated"@en ; + rdfs:isDefinedBy ; + rdfs:subClassOf :Type ; + owl:deprecated true . + +:Parent a owl:Class ; + rdfs:label "Parent"@en ; + rdfs:isDefinedBy ; + rdfs:subClassOf :RelatedType . + +:Postal a owl:Class ; + rdfs:label "Postal"@en ; + rdfs:comment "This class is deprecated"@en ; + rdfs:isDefinedBy ; + rdfs:subClassOf :Type ; + owl:deprecated true . + +:Pref a owl:Class ; + rdfs:label "Pref"@en ; + rdfs:comment "This class is deprecated"@en ; + rdfs:isDefinedBy ; + rdfs:subClassOf :Type ; + owl:deprecated true . + +:Sibling a owl:Class ; + rdfs:label "Sibling"@en ; + rdfs:isDefinedBy ; + rdfs:subClassOf :RelatedType . + +:Spouse a owl:Class ; + rdfs:label "Spouse"@en ; + rdfs:isDefinedBy ; + rdfs:subClassOf :RelatedType . + +:Sweetheart a owl:Class ; + rdfs:label "Sweetheart"@en ; + rdfs:isDefinedBy ; + rdfs:subClassOf :RelatedType . + +:Tel a owl:Class ; + rdfs:label "Tel"@en ; + rdfs:comment "This class is deprecated. Use the hasTelephone object property."@en ; + rdfs:isDefinedBy ; + owl:deprecated true . + +:Text a owl:Class ; + rdfs:label "Text"@en ; + rdfs:comment "Also called sms telephone"@en ; + rdfs:isDefinedBy ; + rdfs:subClassOf :TelephoneType . + +:TextPhone a owl:Class ; + rdfs:label "Text phone"@en ; + rdfs:isDefinedBy ; + rdfs:subClassOf :TelephoneType . + +:Unknown a owl:Class ; + rdfs:label "Unknown"@en ; + rdfs:isDefinedBy ; + rdfs:subClassOf :Gender . + +:Video a owl:Class ; + rdfs:label "Video"@en ; + rdfs:isDefinedBy ; + rdfs:subClassOf :TelephoneType . + +:Voice a owl:Class ; + rdfs:label "Voice"@en ; + rdfs:isDefinedBy ; + rdfs:subClassOf :TelephoneType . + +:Work a owl:Class ; + rdfs:label "Work"@en ; + rdfs:comment "This implies that the property is related to an individual's work place"@en ; + rdfs:isDefinedBy ; + rdfs:subClassOf :Type . + +:X400 a owl:Class ; + rdfs:label "X400"@en ; + rdfs:comment "This class is deprecated"@en ; + rdfs:isDefinedBy ; + rdfs:subClassOf :Type ; + owl:deprecated true . + +:adr a owl:ObjectProperty ; + rdfs:label "address"@en ; + rdfs:comment "This object property has been mapped"@en ; + rdfs:isDefinedBy ; + owl:equivalentProperty :hasAddress . + +:agent a owl:ObjectProperty ; + rdfs:label "agent"@en ; + rdfs:comment "This object property has been deprecated"@en ; + rdfs:isDefinedBy ; + owl:deprecated true . + +:anniversary a owl:DatatypeProperty ; + rdfs:label "anniversary"@en ; + rdfs:comment "The date of marriage, or equivalent, of the object"@en ; + rdfs:isDefinedBy ; + rdfs:range [ a rdfs:Datatype ; + owl:unionOf ( xsd:dateTime xsd:gYear ) ] . + +:bday a owl:DatatypeProperty ; + rdfs:label "birth date"@en ; + rdfs:comment "To specify the birth date of the object"@en ; + rdfs:isDefinedBy ; + rdfs:range [ a rdfs:Datatype ; + owl:unionOf ( xsd:dateTime xsd:dateTimeStamp xsd:gYear ) ] . + +:category a owl:DatatypeProperty ; + rdfs:label "category"@en ; + rdfs:comment "The category information about the object, also known as tags"@en ; + rdfs:isDefinedBy ; + rdfs:range xsd:string . + +:class a owl:DatatypeProperty ; + rdfs:label "class"@en ; + rdfs:comment "This data property has been deprecated"@en ; + rdfs:isDefinedBy ; + owl:deprecated true . + +:email a owl:ObjectProperty ; + rdfs:label "email"@en ; + rdfs:comment "This object property has been mapped"@en ; + rdfs:isDefinedBy ; + owl:equivalentProperty :hasEmail . + +:extended-address a owl:DatatypeProperty ; + rdfs:label "extended address"@en ; + rdfs:comment "This data property has been deprecated"@en ; + rdfs:isDefinedBy ; + owl:deprecated true . + +:geo a owl:ObjectProperty ; + rdfs:label "geo"@en ; + rdfs:comment "This object property has been mapped"@en ; + rdfs:isDefinedBy ; + owl:equivalentProperty :hasGeo . + +:hasAdditionalName a owl:ObjectProperty ; + rdfs:label "has additional name"@en ; + rdfs:comment "Used to support property parameters for the additional name data property"@en ; + rdfs:isDefinedBy . + +:hasCalendarBusy a owl:ObjectProperty ; + rdfs:label "has calendar busy"@en ; + rdfs:comment "To specify the busy time associated with the object. (Was called FBURL in RFC6350)"@en ; + rdfs:isDefinedBy . + +:hasCalendarLink a owl:ObjectProperty ; + rdfs:label "has calendar link"@en ; + rdfs:comment "To specify the calendar associated with the object. (Was called CALURI in RFC6350)"@en ; + rdfs:isDefinedBy . + +:hasCalendarRequest a owl:ObjectProperty ; + rdfs:label "has calendar request"@en ; + rdfs:comment "To specify the calendar user address to which a scheduling request be sent for the object. (Was called CALADRURI in RFC6350)"@en ; + rdfs:isDefinedBy . + +:hasCategory a owl:ObjectProperty ; + rdfs:label "has category"@en ; + rdfs:comment "Used to support property parameters for the category data property"@en ; + rdfs:isDefinedBy . + +:hasCountryName a owl:ObjectProperty ; + rdfs:label "has country name"@en ; + rdfs:comment "Used to support property parameters for the country name data property"@en ; + rdfs:isDefinedBy . + +:hasFN a owl:ObjectProperty ; + rdfs:label "has formatted name"@en ; + rdfs:comment "Used to support property parameters for the formatted name data property"@en ; + rdfs:isDefinedBy . + +:hasFamilyName a owl:ObjectProperty ; + rdfs:label "has family name"@en ; + rdfs:comment "Used to support property parameters for the family name data property"@en ; + rdfs:isDefinedBy . + +:hasGender a owl:ObjectProperty ; + rdfs:label "has gender"@en ; + rdfs:comment "To specify the sex or gender identity of the object. URIs are recommended to enable interoperable sex and gender codes to be used."@en ; + rdfs:isDefinedBy . + +:hasGivenName a owl:ObjectProperty ; + rdfs:label "has given name"@en ; + rdfs:comment "Used to support property parameters for the given name data property"@en ; + rdfs:isDefinedBy . + +:hasHonorificPrefix a owl:ObjectProperty ; + rdfs:label "has honorific prefix"@en ; + rdfs:comment "Used to support property parameters for the honorific prefix data property"@en ; + rdfs:isDefinedBy . + +:hasHonorificSuffix a owl:ObjectProperty ; + rdfs:label "has honorific suffix"@en ; + rdfs:comment "Used to support property parameters for the honorific suffix data property"@en ; + rdfs:isDefinedBy . + +:hasInstantMessage a owl:ObjectProperty ; + rdfs:label "has messaging"@en ; + rdfs:comment "To specify the instant messaging and presence protocol communications with the object. (Was called IMPP in RFC6350)"@en ; + rdfs:isDefinedBy . + +:hasLanguage a owl:ObjectProperty ; + rdfs:label "has language"@en ; + rdfs:comment "Used to support property parameters for the language data property"@en ; + rdfs:isDefinedBy . + +:hasLocality a owl:ObjectProperty ; + rdfs:label "has locality"@en ; + rdfs:comment "Used to support property parameters for the locality data property"@en ; + rdfs:isDefinedBy . + +:hasNickname a owl:ObjectProperty ; + rdfs:label "has nickname"@en ; + rdfs:comment "Used to support property parameters for the nickname data property"@en ; + rdfs:isDefinedBy ; + rdfs:seeAlso :nickname . + +:hasNote a owl:ObjectProperty ; + rdfs:label "has note"@en ; + rdfs:comment "Used to support property parameters for the note data property"@en ; + rdfs:isDefinedBy . + +:hasOrganizationName a owl:ObjectProperty ; + rdfs:label "has organization name"@en ; + rdfs:comment "Used to support property parameters for the organization name data property"@en ; + rdfs:isDefinedBy . + +:hasOrganizationUnit a owl:ObjectProperty ; + rdfs:label "has organization unit name"@en ; + rdfs:comment "Used to support property parameters for the organization unit name data property"@en ; + rdfs:isDefinedBy . + +:hasPostalCode a owl:ObjectProperty ; + rdfs:label "has postal code"@en ; + rdfs:comment "Used to support property parameters for the postal code data property"@en ; + rdfs:isDefinedBy . + +:hasRegion a owl:ObjectProperty ; + rdfs:label "has region"@en ; + rdfs:comment "Used to support property parameters for the region data property"@en ; + rdfs:isDefinedBy . + +:hasRelated a owl:ObjectProperty ; + rdfs:label "has related"@en ; + rdfs:comment "To specify a relationship between another entity and the entity represented by this object"@en ; + rdfs:isDefinedBy . + +:hasRole a owl:ObjectProperty ; + rdfs:label "has role"@en ; + rdfs:comment "Used to support property parameters for the role data property"@en ; + rdfs:isDefinedBy . + +:hasSource a owl:ObjectProperty ; + rdfs:label "has source"@en ; + rdfs:comment "To identify the source of directory information of the object"@en ; + rdfs:isDefinedBy . + +:hasStreetAddress a owl:ObjectProperty ; + rdfs:label "has street address"@en ; + rdfs:comment "Used to support property parameters for the street address data property"@en ; + rdfs:isDefinedBy . + +:hasTitle a owl:ObjectProperty ; + rdfs:label "has title"@en ; + rdfs:comment "Used to support property parameters for the title data property"@en ; + rdfs:isDefinedBy . + +:hasUID a owl:ObjectProperty ; + rdfs:label "has uid"@en ; + rdfs:comment "To specify a value that represents a globally unique identifier corresponding to the object"@en ; + rdfs:isDefinedBy . + +:hasValue a owl:ObjectProperty ; + rdfs:label "has value"@en ; + rdfs:comment "Used to indicate the resource value of an object property that requires property parameters"@en ; + rdfs:isDefinedBy . + +:label a owl:DatatypeProperty ; + rdfs:label "label"@en ; + rdfs:comment "This data property has been deprecated"@en ; + rdfs:isDefinedBy ; + owl:deprecated true . + +:language a owl:DatatypeProperty ; + rdfs:label "language"@en ; + rdfs:comment "To specify the language that may be used for contacting the object. May also be used as a property parameter."@en ; + rdfs:isDefinedBy . + +:latitude a owl:DatatypeProperty ; + rdfs:label "latitude"@en ; + rdfs:comment "This data property has been deprecated. See hasGeo"@en ; + rdfs:isDefinedBy ; + owl:deprecated true . + +:longitude a owl:DatatypeProperty ; + rdfs:label "longitude"@en ; + rdfs:comment "This data property has been deprecated. See hasGeo"@en ; + rdfs:isDefinedBy ; + owl:deprecated true . + +:mailer a owl:DatatypeProperty ; + rdfs:label "mailer"@en ; + rdfs:comment "This data property has been deprecated"@en ; + rdfs:isDefinedBy ; + owl:deprecated true . + +:note a owl:DatatypeProperty ; + rdfs:label "note"@en ; + rdfs:comment "A note associated with the object"@en ; + rdfs:isDefinedBy ; + rdfs:range xsd:string . + +:org a owl:ObjectProperty ; + rdfs:label "organization"@en ; + rdfs:comment "This object property has been mapped. Use the organization-name data property."@en ; + rdfs:isDefinedBy ; + owl:equivalentProperty :organization-name . + +:organization-unit a owl:DatatypeProperty ; + rdfs:label "organizational unit name"@en ; + rdfs:comment "To specify the organizational unit name associated with the object"@en ; + rdfs:isDefinedBy ; + rdfs:range xsd:string ; + rdfs:subPropertyOf :organization-name . + +:post-office-box a owl:DatatypeProperty ; + rdfs:label "post office box"@en ; + rdfs:comment "This data property has been deprecated"@en ; + rdfs:isDefinedBy ; + owl:deprecated true . + +:prodid a owl:DatatypeProperty ; + rdfs:label "product id"@en ; + rdfs:comment "To specify the identifier for the product that created the object"@en ; + rdfs:isDefinedBy ; + rdfs:range xsd:string . + +:rev a owl:DatatypeProperty ; + rdfs:label "revision"@en ; + rdfs:comment "To specify revision information about the object"@en ; + rdfs:isDefinedBy ; + rdfs:range xsd:dateTime . + +:role a owl:DatatypeProperty ; + rdfs:label "role"@en ; + rdfs:comment "To specify the function or part played in a particular situation by the object"@en ; + rdfs:isDefinedBy ; + rdfs:range xsd:string . + +:sort-string a owl:DatatypeProperty ; + rdfs:label "sort as"@en ; + rdfs:comment "To specify the string to be used for national-language-specific sorting. Used as a property parameter only."@en ; + rdfs:isDefinedBy ; + rdfs:range xsd:string . + +:title a owl:DatatypeProperty ; + rdfs:label "title"@en ; + rdfs:comment "To specify the position or job of the object"@en ; + rdfs:isDefinedBy ; + rdfs:range xsd:string . + +:tz a owl:DatatypeProperty ; + rdfs:label "time zone"@en ; + rdfs:comment "To indicate time zone information that is specific to the object. May also be used as a property parameter."@en ; + rdfs:isDefinedBy ; + rdfs:range xsd:string . + +:value a owl:DatatypeProperty ; + rdfs:label "value"@en ; + rdfs:comment "Used to indicate the literal value of a data property that requires property parameters"@en ; + rdfs:isDefinedBy . + +:Address a owl:Class ; + rdfs:label "Address"@en ; + rdfs:comment "To specify the components of the delivery address for the object"@en ; + rdfs:isDefinedBy ; + owl:equivalentClass [ a owl:Class ; + owl:unionOf ( [ a owl:Class ; + owl:intersectionOf ( [ a owl:Restriction ; + owl:onProperty :country-name ; + owl:someValuesFrom xsd:string ] [ a owl:Restriction ; + owl:maxCardinality "1"^^xsd:nonNegativeInteger ; + owl:onProperty :country-name ] ) ] [ a owl:Class ; + owl:intersectionOf ( [ a owl:Restriction ; + owl:onProperty :locality ; + owl:someValuesFrom xsd:string ] [ a owl:Restriction ; + owl:maxCardinality "1"^^xsd:nonNegativeInteger ; + owl:onProperty :locality ] ) ] [ a owl:Class ; + owl:intersectionOf ( [ a owl:Restriction ; + owl:onProperty :postal-code ; + owl:someValuesFrom xsd:string ] [ a owl:Restriction ; + owl:maxCardinality "1"^^xsd:nonNegativeInteger ; + owl:onProperty :postal-code ] ) ] [ a owl:Class ; + owl:intersectionOf ( [ a owl:Restriction ; + owl:onProperty :region ; + owl:someValuesFrom xsd:string ] [ a owl:Restriction ; + owl:maxCardinality "1"^^xsd:nonNegativeInteger ; + owl:onProperty :region ] ) ] [ a owl:Class ; + owl:intersectionOf ( [ a owl:Restriction ; + owl:onProperty :street-address ; + owl:someValuesFrom xsd:string ] [ a owl:Restriction ; + owl:maxCardinality "1"^^xsd:nonNegativeInteger ; + owl:onProperty :street-address ] ) ] ) ] . + +:Email a owl:Class ; + rdfs:label "Email"@en ; + rdfs:comment "To specify the electronic mail address for communication with the object the vCard represents. Use the hasEmail object property."@en ; + rdfs:isDefinedBy ; + owl:deprecated true . + +:Group a owl:Class ; + rdfs:label "Group"@en ; + rdfs:comment "Object representing a group of persons or entities. A group object will usually contain hasMember properties to specify the members of the group."@en ; + rdfs:isDefinedBy ; + rdfs:subClassOf :Kind ; + owl:disjointWith :Individual, + :Location, + :Organization ; + owl:equivalentClass [ a owl:Class ; + owl:intersectionOf ( [ a owl:Restriction ; + owl:onProperty :hasMember ; + owl:someValuesFrom :Kind ] [ a owl:Restriction ; + owl:minQualifiedCardinality "1"^^xsd:nonNegativeInteger ; + owl:onClass :Kind ; + owl:onProperty :hasMember ] ) ] . + +:Individual a owl:Class ; + rdfs:label "Individual"@en ; + rdfs:comment "An object representing a single person or entity"@en ; + rdfs:isDefinedBy ; + rdfs:subClassOf :Kind ; + owl:disjointWith :Location, + :Organization . + +:Name a owl:Class ; + rdfs:label "Name"@en ; + rdfs:comment "To specify the components of the name of the object"@en ; + rdfs:isDefinedBy ; + owl:equivalentClass [ a owl:Class ; + owl:unionOf ( [ a owl:Class ; + owl:intersectionOf ( [ a owl:Restriction ; + owl:onProperty :additional-name ; + owl:someValuesFrom xsd:string ] [ a owl:Restriction ; + owl:minCardinality "0"^^xsd:nonNegativeInteger ; + owl:onProperty :additional-name ] ) ] [ a owl:Class ; + owl:intersectionOf ( [ a owl:Restriction ; + owl:onProperty :family-name ; + owl:someValuesFrom xsd:string ] [ a owl:Restriction ; + owl:maxCardinality "1"^^xsd:nonNegativeInteger ; + owl:onProperty :family-name ] ) ] [ a owl:Class ; + owl:intersectionOf ( [ a owl:Restriction ; + owl:onProperty :given-name ; + owl:someValuesFrom xsd:string ] [ a owl:Restriction ; + owl:maxCardinality "1"^^xsd:nonNegativeInteger ; + owl:onProperty :given-name ] ) ] [ a owl:Class ; + owl:intersectionOf ( [ a owl:Restriction ; + owl:onProperty :honorific-prefix ; + owl:someValuesFrom xsd:string ] [ a owl:Restriction ; + owl:minCardinality "0"^^xsd:nonNegativeInteger ; + owl:onProperty :honorific-prefix ] ) ] [ a owl:Class ; + owl:intersectionOf ( [ a owl:Restriction ; + owl:onProperty :honorific-suffix ; + owl:someValuesFrom xsd:string ] [ a owl:Restriction ; + owl:minCardinality "0"^^xsd:nonNegativeInteger ; + owl:onProperty :honorific-suffix ] ) ] ) ] . + +:VCard a owl:Class ; + rdfs:label "VCard"@en ; + rdfs:comment "The vCard class is equivalent to the new Kind class, which is the parent for the four explicit types of vCards (Individual, Organization, Location, Group)"@en ; + rdfs:isDefinedBy ; + owl:equivalentClass :Kind . + +:fn a owl:DatatypeProperty ; + rdfs:label "formatted name"@en ; + rdfs:comment "The formatted text corresponding to the name of the object"@en ; + rdfs:isDefinedBy ; + rdfs:range xsd:string . + +:hasAddress a owl:ObjectProperty ; + rdfs:label "has address"@en ; + rdfs:comment "To specify the components of the delivery address for the object"@en ; + rdfs:isDefinedBy ; + rdfs:range :Address . + +:hasEmail a owl:ObjectProperty ; + rdfs:label "has email"@en ; + rdfs:comment "To specify the electronic mail address for communication with the object"@en ; + rdfs:isDefinedBy ; + rdfs:range :Email . + +:hasGeo a owl:ObjectProperty ; + rdfs:label "has geo"@en ; + rdfs:comment "To specify information related to the global positioning of the object. May also be used as a property parameter."@en ; + rdfs:isDefinedBy . + +:hasKey a owl:ObjectProperty ; + rdfs:label "has key"@en ; + rdfs:comment "To specify a public key or authentication certificate associated with the object"@en ; + rdfs:isDefinedBy ; + owl:equivalentProperty :key . + +:hasLogo a owl:ObjectProperty ; + rdfs:label "has logo"@en ; + rdfs:comment "To specify a graphic image of a logo associated with the object "@en ; + rdfs:isDefinedBy ; + owl:equivalentProperty :logo . + +:hasName a owl:ObjectProperty ; + rdfs:label "has name"@en ; + rdfs:comment "To specify the components of the name of the object"@en ; + rdfs:isDefinedBy ; + rdfs:range :Name ; + owl:equivalentProperty :n . + +:hasPhoto a owl:ObjectProperty ; + rdfs:label "has photo"@en ; + rdfs:comment "To specify an image or photograph information that annotates some aspect of the object"@en ; + rdfs:isDefinedBy ; + owl:equivalentProperty :photo . + +:hasSound a owl:ObjectProperty ; + rdfs:label "has sound"@en ; + rdfs:comment "To specify a digital sound content information that annotates some aspect of the object"@en ; + rdfs:isDefinedBy ; + owl:equivalentProperty :sound . + +:hasTelephone a owl:ObjectProperty ; + rdfs:label "has telephone"@en ; + rdfs:comment "To specify the telephone number for telephony communication with the object"@en ; + rdfs:isDefinedBy ; + owl:equivalentProperty :tel . + +:hasURL a owl:ObjectProperty ; + rdfs:label "has url"@en ; + rdfs:comment "To specify a uniform resource locator associated with the object"@en ; + rdfs:isDefinedBy ; + owl:equivalentProperty :url . + +:key a owl:ObjectProperty ; + rdfs:label "key"@en ; + rdfs:comment "This object property has been mapped"@en ; + rdfs:isDefinedBy ; + owl:equivalentProperty :hasKey . + +:logo a owl:ObjectProperty ; + rdfs:label "logo"@en ; + rdfs:comment "This object property has been mapped"@en ; + rdfs:isDefinedBy ; + owl:equivalentProperty :hasLogo . + +:n a owl:ObjectProperty ; + rdfs:label "name"@en ; + rdfs:comment "This object property has been mapped"@en ; + rdfs:isDefinedBy ; + owl:equivalentProperty :hasName . + +:nickname a owl:DatatypeProperty ; + rdfs:label "nickname"@en ; + rdfs:comment "The nick name associated with the object"@en ; + rdfs:isDefinedBy ; + rdfs:range xsd:string . + +:photo a owl:ObjectProperty ; + rdfs:label "photo"@en ; + rdfs:comment "This object property has been mapped"@en ; + rdfs:isDefinedBy ; + owl:equivalentProperty :hasPhoto . + +:sound a owl:ObjectProperty ; + rdfs:label "sound"@en ; + rdfs:comment "This object property has been mapped"@en ; + rdfs:isDefinedBy ; + owl:equivalentProperty :hasSound . + +:tel a owl:ObjectProperty ; + rdfs:label "telephone"@en ; + rdfs:comment "This object property has been mapped"@en ; + rdfs:isDefinedBy ; + owl:equivalentProperty :hasTelephone . + +:url a owl:ObjectProperty ; + rdfs:label "url"@en ; + rdfs:comment "This object property has been mapped"@en ; + rdfs:isDefinedBy ; + owl:equivalentProperty :hasURL . + +:Location a owl:Class ; + rdfs:label "Location"@en ; + rdfs:comment "An object representing a named geographical place"@en ; + rdfs:isDefinedBy ; + rdfs:subClassOf :Kind ; + owl:disjointWith :Organization . + +:additional-name a owl:DatatypeProperty ; + rdfs:label "additional name"@en ; + rdfs:comment "The additional name associated with the object"@en ; + rdfs:isDefinedBy ; + rdfs:range xsd:string . + +:country-name a owl:DatatypeProperty ; + rdfs:label "country name"@en ; + rdfs:comment "The country name associated with the address of the object"@en ; + rdfs:isDefinedBy ; + rdfs:range xsd:string . + +:family-name a owl:DatatypeProperty ; + rdfs:label "family name"@en ; + rdfs:comment "The family name associated with the object"@en ; + rdfs:isDefinedBy ; + rdfs:range xsd:string . + +:given-name a owl:DatatypeProperty ; + rdfs:label "given name"@en ; + rdfs:comment "The given name associated with the object"@en ; + rdfs:isDefinedBy ; + rdfs:range xsd:string . + +:hasMember a owl:ObjectProperty ; + rdfs:label "has member"@en ; + rdfs:comment "To include a member in the group this object represents. (This property can only be used by Group individuals)"@en ; + rdfs:domain :Group ; + rdfs:isDefinedBy ; + rdfs:range :Kind . + +:honorific-prefix a owl:DatatypeProperty ; + rdfs:label "honorific prefix"@en ; + rdfs:comment "The honorific prefix of the name associated with the object"@en ; + rdfs:isDefinedBy ; + rdfs:range xsd:string . + +:honorific-suffix a owl:DatatypeProperty ; + rdfs:label "honorific suffix"@en ; + rdfs:comment "The honorific suffix of the name associated with the object"@en ; + rdfs:isDefinedBy ; + rdfs:range xsd:string . + +:locality a owl:DatatypeProperty ; + rdfs:label "locality"@en ; + rdfs:comment "The locality (e.g. city or town) associated with the address of the object"@en ; + rdfs:isDefinedBy ; + rdfs:range xsd:string . + +:organization-name a owl:DatatypeProperty ; + rdfs:label "organization name"@en ; + rdfs:comment "To specify the organizational name associated with the object"@en ; + rdfs:isDefinedBy ; + rdfs:range xsd:string . + +:postal-code a owl:DatatypeProperty ; + rdfs:label "postal code"@en ; + rdfs:comment "The postal code associated with the address of the object"@en ; + rdfs:isDefinedBy ; + rdfs:range xsd:string . + +:region a owl:DatatypeProperty ; + rdfs:label "region"@en ; + rdfs:comment "The region (e.g. state or province) associated with the address of the object"@en ; + rdfs:isDefinedBy ; + rdfs:range xsd:string . + +:street-address a owl:DatatypeProperty ; + rdfs:label "street address"@en ; + rdfs:comment "The street address associated with the address of the object"@en ; + rdfs:isDefinedBy ; + rdfs:range xsd:string . + +:Organization a owl:Class ; + rdfs:label "Organization"@en ; + rdfs:comment """An object representing an organization. An organization is a single entity, and might represent a business or government, a department or division within a business or government, a club, an association, or the like. +"""@en ; + rdfs:isDefinedBy ; + rdfs:subClassOf :Kind . + +:Gender a owl:Class ; + rdfs:label "Gender"@en ; + rdfs:comment "Used for gender codes. The URI of the gender code must be used as the value for Gender."@en ; + rdfs:isDefinedBy . + +:Kind a owl:Class ; + rdfs:label "Kind"@en ; + rdfs:comment "The parent class for all objects"@en ; + rdfs:isDefinedBy ; + owl:equivalentClass [ a owl:Restriction ; + owl:minQualifiedCardinality "1"^^xsd:nonNegativeInteger ; + owl:onDataRange xsd:string ; + owl:onProperty :fn ], + :VCard . + +:Type a owl:Class ; + rdfs:label "Type"@en ; + rdfs:comment "Used for type codes. The URI of the type code must be used as the value for Type."@en ; + rdfs:isDefinedBy . + +:TelephoneType a owl:Class ; + rdfs:label "Phone"@en ; + rdfs:comment "Used for telephone type codes. The URI of the telephone type code must be used as the value for the Telephone Type."@en ; + rdfs:isDefinedBy . + +:RelatedType a owl:Class ; + rdfs:label "Relation Type"@en ; + rdfs:comment "Used for relation type codes. The URI of the relation type code must be used as the value for the Relation Type."@en ; + rdfs:isDefinedBy . + + a owl:Ontology ; + rdfs:label "Ontology for vCard"@en ; + rdfs:comment "Ontology for vCard based on RFC6350"@en ; + owl:versionInfo "Final"@en . + + +`); + + +/***/ }), + +/***/ "./node_modules/contacts-pane/webidControl.js": +/*!****************************************************!*\ + !*** ./node_modules/contacts-pane/webidControl.js ***! + \****************************************************/ +/*! exports provided: addWebIDToContacts, removeWebIDFromContacts, renderWedidControl */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "addWebIDToContacts", function() { return addWebIDToContacts; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "removeWebIDFromContacts", function() { return removeWebIDFromContacts; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "renderWedidControl", function() { return renderWedidControl; }); +/* harmony import */ var solid_ui__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! solid-ui */ "./node_modules/solid-ui/lib/index.js"); +/* harmony import */ var solid_ui__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(solid_ui__WEBPACK_IMPORTED_MODULE_0__); +// Render a control to record the webids we have for this agent +/* eslint-disable multiline-ternary */ + + +const $rdf = solid_ui__WEBPACK_IMPORTED_MODULE_0__["rdf"] +const ns = solid_ui__WEBPACK_IMPORTED_MODULE_0__["ns"] +// const buttons = UI.buttonsn no +const widgets = solid_ui__WEBPACK_IMPORTED_MODULE_0__["widgets"] +const utils = solid_ui__WEBPACK_IMPORTED_MODULE_0__["utils"] +const kb = solid_ui__WEBPACK_IMPORTED_MODULE_0__["store"] +const style = solid_ui__WEBPACK_IMPORTED_MODULE_0__["style"] + +const WEBID_NOUN = 'Solid ID' + +const GREEN_PLUS = solid_ui__WEBPACK_IMPORTED_MODULE_0__["icons"].iconBase + 'noun_34653_green.svg' +const DOWN_ARROW = solid_ui__WEBPACK_IMPORTED_MODULE_0__["icons"].iconBase + 'noun_1369241.svg' +const UP_ARROW = solid_ui__WEBPACK_IMPORTED_MODULE_0__["icons"].iconBase + 'noun_1369237.svg' + +const webidPanelBackgroundColor = '#ffe6ff' + +// Logic +async function addWebIDToContacts (person, webid, context) { + if (!webid.startsWith('https:')) { /// @@ well we will have other protcols like DID + throw new Error('Does not look like a webid, must start with https:') + } + console.log(`Adding to ${person} a ${WEBID_NOUN}: ${webid}.`) + const kb = context.kb + const vcardURLThing = kb.bnode() + const insertables = [ + $rdf.st(person, ns.vcard('url'), vcardURLThing, person.doc()), + $rdf.st(vcardURLThing, ns.rdf('type'), ns.vcard('WebID'), person.doc()), + $rdf.st(vcardURLThing, ns.vcard('value'), webid, person.doc()) + ] + await kb.updater.update([], insertables) +} + +async function removeWebIDFromContacts (person, webid, context) { + const { kb } = context + console.log(`Removing from ${person} their ${WEBID_NOUN}: ${webid}.`) + const existing = kb.each(person, ns.vcard('url'), null, person.doc()) + .filter(urlObject => kb.holds(urlObject, ns.rdf('type'), ns.vcard('WebID'), person.doc())) + .filter(urlObject => kb.holds(urlObject, ns.vcard('value'), webid, person.doc())) + if (!existing.length) { + throw new Error(`Person ${person} does not have ${WEBID_NOUN} ${webid}.`) + } + const vcardURLThing = existing[0] + const deletables = [ + $rdf.st(person, ns.vcard('url'), vcardURLThing, person.doc()), + $rdf.st(vcardURLThing, ns.rdf('type'), ns.vcard('WebID'), person.doc()), + $rdf.st(vcardURLThing, ns.vcard('value'), webid, person.doc()) + ] + await kb.updater.update(deletables, []) +} + +// The control rendered by this module +async function renderWedidControl (person, dataBrowserContext) { + // IDs which are as WebId in VCARD data + // like :me vcard:hasURL [ a vcard:WebId; vcard:value ] + // + function vcardWebIDs (person) { + return kb.each(person, ns.vcard('url'), null, person.doc()) + .filter(urlObject => kb.holds(urlObject, ns.rdf('type'), ns.vcard('WebID'), person.doc())) + .map(urlObject => kb.any(urlObject, ns.vcard('value'), null, person.doc())) + .filter(x => !!x) // remove nulls + } + + function _getAliases (person) { + return kb.allAliases(person) // All the terms linked by sameAs + .filter(x => !x.sameTerm(person)) // Except this one + } + + // Trace things the same as this - other IDs for same thing + // returns as array of node + function getSameAs (thing, doc) { // Should this recurse? + const found = new Set() + const agenda = new Set([thing.uri]) + + while (agenda.size) { + const uri = Array.from(agenda)[0] // clumsy + agenda.delete(uri) + if (found.has(uri)) continue + found.add(uri) + const node = kb.sym(uri) + const left = kb.each(node, ns.owl('sameAs'), null, doc) + const right = kb.each(null, ns.owl('sameAs'), node, doc) + left.concat(right).forEach(next => { + // if (found.has(next)) return + console.log(' sameAs: found ' + next) + agenda.add(next.uri) + }) + } + found.delete(thing.uri) // don't want the one we knew about + return Array.from(found).map(uri => kb.sym(uri)) // return as array of nodes + } + + function renderNewRow (webidObject) { + const webid = new $rdf.Literal(webidObject.uri) + async function deleteFunction () { + try { + await removeWebIDFromContacts(person, webid, { kb }) + } catch (err) { + div.appendChild(widgets.errorMessageBlock(dom, err)) + } + await refreshWebIDTable() + } + const delFunParam = editable ? deleteFunction : null + const title = webidObject.uri.split('/')[2] // domain name + const image = widgets.faviconOrDefault(dom, webidObject.site()) // image just for domain + const options = { deleteFunction: delFunParam, draggable: true, title, image } + + const row = widgets.personTR(dom, solid_ui__WEBPACK_IMPORTED_MODULE_0__["ns"].foaf('knows'), webidObject, options) + // const row = UI.widgets.personTR(dom, UI.ns.foaf('knows'), webidObject, options) + row.children[1].textConent = title // @@ will be overwritten + row.style.backgroundColor = webidPanelBackgroundColor + row.style.padding = '0.2em' + + return row + } + function _renderNewRow2 (x) { // alternative + const tr = table.appendChild(dom.createElement('tr')) + tr.setAttribute('style', 'margin-top: 0.1em solid #ccc;') + const nameTD = tr.appendChild(dom.createElement('td')) + const formTD = tr.appendChild(dom.createElement('td')) + nameTD.textContent = x.uri.split('/')[2] // domain part + kb.fetcher // Load the profile + .load(x.doc()) + .then(function (_xhr) { + nameTD.textContent = + x.uri.split('/')[2] + + ' (' + + kb.statementsMatching( + undefined, + undefined, + undefined, + x.doc() + ).length + + ')' + }) + .catch(function (e) { + formTD.appendChild(solid_ui__WEBPACK_IMPORTED_MODULE_0__["widgets"].errorMessageBlock(dom, e, 'pink')) + }) + return tr + } + + function renderPane (dom, subject, paneName) { + const p = dataBrowserContext.session.paneRegistry.byName(paneName) + const d = p.render(subject, dataBrowserContext) // @@@ change some bits of context! + d.setAttribute( + 'style', + 'border: 0.1em solid #444; border-radius: 0.5em' + ) + return d + } + + function getPersonas () { + const lits = vcardWebIDs(person).concat(getSameAs(person, person.doc())) + const strings = new Set(lits.map(lit => lit.value)) // remove dups + const personas = [...strings].map(uri => kb.sym(uri)) // The UI tables do better with Named Nodes than Literals + personas.sort() // for repeatability + personas.filter(x => !x.sameTerm(person)) + return personas + } + function renderPersona (persona) { + function profileOpenHandler (_event) { + profileIsVisible = !profileIsVisible + main.style.visibility = profileIsVisible ? 'visible' : 'collapse' + openButton.children[0].src = profileIsVisible ? UP_ARROW : DOWN_ARROW // @@ fragile + } + + const div = dom.createElement('div') + const nav = div.appendChild(dom.createElement('nav')) + nav.style = 'width: 100%; height: 4em; background-color: #eee;' + const title = persona.uri // .split('/')[2] // domain name + let main + + const header = nav.appendChild(dom.createElement('span')) + header.textContent = title + let profileIsVisible = false + + const openButton = nav.appendChild(widgets.button(dom, DOWN_ARROW, 'View', profileOpenHandler)) + openButton.style.align = 'right' + kb.fetcher.load(persona).then(_resp => { + try { + main = div.appendChild(renderPane(dom, persona, 'profile')) + main.style.visibility = 'collapse' + } catch (err) { + main = widgets.errorMessageBlock(dom, `Error loading persona ${persona}: ${err}`) + } + }, err => { + main = widgets.errorMessageBlock(dom, `Problem displaying persona ${persona}: ${err}`) + }) + return div + } // renderPersona + + async function refreshWebIDTable () { + const personas = getPersonas() + console.log('WebId personas: ' + person + ' -> ' + personas.map(p => p.uri).join(',\n ')) + prompt.style.visibility = personas.length ? 'collapse' : 'visible' + utils.syncTableToArrayReOrdered(table, personas, renderNewRow) + utils.syncTableToArrayReOrdered(profileArea, personas, renderPersona) + } + async function greenButtonHandler (_event) { + const webid = await solid_ui__WEBPACK_IMPORTED_MODULE_0__["widgets"].askName(dom, solid_ui__WEBPACK_IMPORTED_MODULE_0__["store"], div, solid_ui__WEBPACK_IMPORTED_MODULE_0__["ns"].vcard('url'), null, WEBID_NOUN) + try { + await addWebIDToContacts(person, webid, { kb: kb }) + } catch (err) { + div.appendChild(widgets.errorMessageBlock(dom, err)) + } + await refreshWebIDTable() + } + + async function droppedURIHandler (uris) { + for (const webid of uris) { + try { + await addWebIDToContacts(person, webid, { kb: kb }) + } catch (err) { + div.appendChild(widgets.errorMessageBlock(dom, err)) + } + } + await refreshWebIDTable() + } + + const { dom } = dataBrowserContext + const editable = kb.updater.editable(person.doc().uri, kb) + const div = dom.createElement('div') + div.style = 'border-radius:0.3em; border: 0.1em solid #888; padding: 0.8em;' + + if (getPersonas().length === 0 && !editable) { + div.style.visibility = 'collapse' + return div // No point listing an empty list you can't change + } + + const h4 = div.appendChild(dom.createElement('h4')) + h4.textContent = WEBID_NOUN + h4.style = style.formHeadingStyle + h4.style.color = style.highlightColor + + const prompt = div.appendChild(dom.createElement('p')) + prompt.style = style.commentStyle + prompt.textContent = `If you know someone's ${WEBID_NOUN}, you can do more stuff with them. + To record their ${WEBID_NOUN}, drag it onto the plus, or click the plus + to bring up a selector.` + const table = div.appendChild(dom.createElement('table')) + if (editable) { + const plus = div.appendChild(widgets.button(dom, GREEN_PLUS, WEBID_NOUN, greenButtonHandler)) + solid_ui__WEBPACK_IMPORTED_MODULE_0__["widgets"].makeDropTarget(plus, droppedURIHandler, null) + } + const profileArea = div.appendChild(dom.createElement('div')) + await refreshWebIDTable() + + return div +} + + +/***/ }), + +/***/ "./node_modules/cross-fetch/dist/browser-ponyfill.js": +/*!***********************************************************!*\ + !*** ./node_modules/cross-fetch/dist/browser-ponyfill.js ***! + \***********************************************************/ +/*! no static exports found */ +/***/ (function(module, exports) { + +var __self__ = (function (root) { +function F() { +this.fetch = false; +this.DOMException = root.DOMException +} +F.prototype = root; +return new F(); +})(typeof self !== 'undefined' ? self : this); +(function(self) { + +var irrelevant = (function (exports) { + + var support = { + searchParams: 'URLSearchParams' in self, + iterable: 'Symbol' in self && 'iterator' in Symbol, + blob: + 'FileReader' in self && + 'Blob' in self && + (function() { + try { + new Blob(); + return true + } catch (e) { + return false + } + })(), + formData: 'FormData' in self, + arrayBuffer: 'ArrayBuffer' in self + }; + + function isDataView(obj) { + return obj && DataView.prototype.isPrototypeOf(obj) + } + + if (support.arrayBuffer) { + var viewClasses = [ + '[object Int8Array]', + '[object Uint8Array]', + '[object Uint8ClampedArray]', + '[object Int16Array]', + '[object Uint16Array]', + '[object Int32Array]', + '[object Uint32Array]', + '[object Float32Array]', + '[object Float64Array]' + ]; + + var isArrayBufferView = + ArrayBuffer.isView || + function(obj) { + return obj && viewClasses.indexOf(Object.prototype.toString.call(obj)) > -1 + }; + } + + function normalizeName(name) { + if (typeof name !== 'string') { + name = String(name); + } + if (/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(name)) { + throw new TypeError('Invalid character in header field name') + } + return name.toLowerCase() + } + + function normalizeValue(value) { + if (typeof value !== 'string') { + value = String(value); + } + return value + } + + // Build a destructive iterator for the value list + function iteratorFor(items) { + var iterator = { + next: function() { + var value = items.shift(); + return {done: value === undefined, value: value} + } + }; + + if (support.iterable) { + iterator[Symbol.iterator] = function() { + return iterator + }; + } + + return iterator + } + + function Headers(headers) { + this.map = {}; + + if (headers instanceof Headers) { + headers.forEach(function(value, name) { + this.append(name, value); + }, this); + } else if (Array.isArray(headers)) { + headers.forEach(function(header) { + this.append(header[0], header[1]); + }, this); + } else if (headers) { + Object.getOwnPropertyNames(headers).forEach(function(name) { + this.append(name, headers[name]); + }, this); + } + } + + Headers.prototype.append = function(name, value) { + name = normalizeName(name); + value = normalizeValue(value); + var oldValue = this.map[name]; + this.map[name] = oldValue ? oldValue + ', ' + value : value; + }; + + Headers.prototype['delete'] = function(name) { + delete this.map[normalizeName(name)]; + }; + + Headers.prototype.get = function(name) { + name = normalizeName(name); + return this.has(name) ? this.map[name] : null + }; + + Headers.prototype.has = function(name) { + return this.map.hasOwnProperty(normalizeName(name)) + }; + + Headers.prototype.set = function(name, value) { + this.map[normalizeName(name)] = normalizeValue(value); + }; + + Headers.prototype.forEach = function(callback, thisArg) { + for (var name in this.map) { + if (this.map.hasOwnProperty(name)) { + callback.call(thisArg, this.map[name], name, this); + } + } + }; + + Headers.prototype.keys = function() { + var items = []; + this.forEach(function(value, name) { + items.push(name); + }); + return iteratorFor(items) + }; + + Headers.prototype.values = function() { + var items = []; + this.forEach(function(value) { + items.push(value); + }); + return iteratorFor(items) + }; + + Headers.prototype.entries = function() { + var items = []; + this.forEach(function(value, name) { + items.push([name, value]); + }); + return iteratorFor(items) + }; + + if (support.iterable) { + Headers.prototype[Symbol.iterator] = Headers.prototype.entries; + } + + function consumed(body) { + if (body.bodyUsed) { + return Promise.reject(new TypeError('Already read')) + } + body.bodyUsed = true; + } + + function fileReaderReady(reader) { + return new Promise(function(resolve, reject) { + reader.onload = function() { + resolve(reader.result); + }; + reader.onerror = function() { + reject(reader.error); + }; + }) + } + + function readBlobAsArrayBuffer(blob) { + var reader = new FileReader(); + var promise = fileReaderReady(reader); + reader.readAsArrayBuffer(blob); + return promise + } + + function readBlobAsText(blob) { + var reader = new FileReader(); + var promise = fileReaderReady(reader); + reader.readAsText(blob); + return promise + } + + function readArrayBufferAsText(buf) { + var view = new Uint8Array(buf); + var chars = new Array(view.length); + + for (var i = 0; i < view.length; i++) { + chars[i] = String.fromCharCode(view[i]); + } + return chars.join('') + } + + function bufferClone(buf) { + if (buf.slice) { + return buf.slice(0) + } else { + var view = new Uint8Array(buf.byteLength); + view.set(new Uint8Array(buf)); + return view.buffer + } + } + + function Body() { + this.bodyUsed = false; + + this._initBody = function(body) { + this._bodyInit = body; + if (!body) { + this._bodyText = ''; + } else if (typeof body === 'string') { + this._bodyText = body; + } else if (support.blob && Blob.prototype.isPrototypeOf(body)) { + this._bodyBlob = body; + } else if (support.formData && FormData.prototype.isPrototypeOf(body)) { + this._bodyFormData = body; + } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) { + this._bodyText = body.toString(); + } else if (support.arrayBuffer && support.blob && isDataView(body)) { + this._bodyArrayBuffer = bufferClone(body.buffer); + // IE 10-11 can't handle a DataView body. + this._bodyInit = new Blob([this._bodyArrayBuffer]); + } else if (support.arrayBuffer && (ArrayBuffer.prototype.isPrototypeOf(body) || isArrayBufferView(body))) { + this._bodyArrayBuffer = bufferClone(body); + } else { + this._bodyText = body = Object.prototype.toString.call(body); + } + + if (!this.headers.get('content-type')) { + if (typeof body === 'string') { + this.headers.set('content-type', 'text/plain;charset=UTF-8'); + } else if (this._bodyBlob && this._bodyBlob.type) { + this.headers.set('content-type', this._bodyBlob.type); + } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) { + this.headers.set('content-type', 'application/x-www-form-urlencoded;charset=UTF-8'); + } + } + }; + + if (support.blob) { + this.blob = function() { + var rejected = consumed(this); + if (rejected) { + return rejected + } + + if (this._bodyBlob) { + return Promise.resolve(this._bodyBlob) + } else if (this._bodyArrayBuffer) { + return Promise.resolve(new Blob([this._bodyArrayBuffer])) + } else if (this._bodyFormData) { + throw new Error('could not read FormData body as blob') + } else { + return Promise.resolve(new Blob([this._bodyText])) + } + }; + + this.arrayBuffer = function() { + if (this._bodyArrayBuffer) { + return consumed(this) || Promise.resolve(this._bodyArrayBuffer) + } else { + return this.blob().then(readBlobAsArrayBuffer) + } + }; + } + + this.text = function() { + var rejected = consumed(this); + if (rejected) { + return rejected + } + + if (this._bodyBlob) { + return readBlobAsText(this._bodyBlob) + } else if (this._bodyArrayBuffer) { + return Promise.resolve(readArrayBufferAsText(this._bodyArrayBuffer)) + } else if (this._bodyFormData) { + throw new Error('could not read FormData body as text') + } else { + return Promise.resolve(this._bodyText) + } + }; + + if (support.formData) { + this.formData = function() { + return this.text().then(decode) + }; + } + + this.json = function() { + return this.text().then(JSON.parse) + }; + + return this + } + + // HTTP methods whose capitalization should be normalized + var methods = ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT']; + + function normalizeMethod(method) { + var upcased = method.toUpperCase(); + return methods.indexOf(upcased) > -1 ? upcased : method + } + + function Request(input, options) { + options = options || {}; + var body = options.body; + + if (input instanceof Request) { + if (input.bodyUsed) { + throw new TypeError('Already read') + } + this.url = input.url; + this.credentials = input.credentials; + if (!options.headers) { + this.headers = new Headers(input.headers); + } + this.method = input.method; + this.mode = input.mode; + this.signal = input.signal; + if (!body && input._bodyInit != null) { + body = input._bodyInit; + input.bodyUsed = true; + } + } else { + this.url = String(input); + } + + this.credentials = options.credentials || this.credentials || 'same-origin'; + if (options.headers || !this.headers) { + this.headers = new Headers(options.headers); + } + this.method = normalizeMethod(options.method || this.method || 'GET'); + this.mode = options.mode || this.mode || null; + this.signal = options.signal || this.signal; + this.referrer = null; + + if ((this.method === 'GET' || this.method === 'HEAD') && body) { + throw new TypeError('Body not allowed for GET or HEAD requests') + } + this._initBody(body); + } + + Request.prototype.clone = function() { + return new Request(this, {body: this._bodyInit}) + }; + + function decode(body) { + var form = new FormData(); + body + .trim() + .split('&') + .forEach(function(bytes) { + if (bytes) { + var split = bytes.split('='); + var name = split.shift().replace(/\+/g, ' '); + var value = split.join('=').replace(/\+/g, ' '); + form.append(decodeURIComponent(name), decodeURIComponent(value)); + } + }); + return form + } + + function parseHeaders(rawHeaders) { + var headers = new Headers(); + // Replace instances of \r\n and \n followed by at least one space or horizontal tab with a space + // https://tools.ietf.org/html/rfc7230#section-3.2 + var preProcessedHeaders = rawHeaders.replace(/\r?\n[\t ]+/g, ' '); + preProcessedHeaders.split(/\r?\n/).forEach(function(line) { + var parts = line.split(':'); + var key = parts.shift().trim(); + if (key) { + var value = parts.join(':').trim(); + headers.append(key, value); + } + }); + return headers + } + + Body.call(Request.prototype); + + function Response(bodyInit, options) { + if (!options) { + options = {}; + } + + this.type = 'default'; + this.status = options.status === undefined ? 200 : options.status; + this.ok = this.status >= 200 && this.status < 300; + this.statusText = 'statusText' in options ? options.statusText : 'OK'; + this.headers = new Headers(options.headers); + this.url = options.url || ''; + this._initBody(bodyInit); + } + + Body.call(Response.prototype); + + Response.prototype.clone = function() { + return new Response(this._bodyInit, { + status: this.status, + statusText: this.statusText, + headers: new Headers(this.headers), + url: this.url + }) + }; + + Response.error = function() { + var response = new Response(null, {status: 0, statusText: ''}); + response.type = 'error'; + return response + }; + + var redirectStatuses = [301, 302, 303, 307, 308]; + + Response.redirect = function(url, status) { + if (redirectStatuses.indexOf(status) === -1) { + throw new RangeError('Invalid status code') + } + + return new Response(null, {status: status, headers: {location: url}}) + }; + + exports.DOMException = self.DOMException; + try { + new exports.DOMException(); + } catch (err) { + exports.DOMException = function(message, name) { + this.message = message; + this.name = name; + var error = Error(message); + this.stack = error.stack; + }; + exports.DOMException.prototype = Object.create(Error.prototype); + exports.DOMException.prototype.constructor = exports.DOMException; + } + + function fetch(input, init) { + return new Promise(function(resolve, reject) { + var request = new Request(input, init); + + if (request.signal && request.signal.aborted) { + return reject(new exports.DOMException('Aborted', 'AbortError')) + } + + var xhr = new XMLHttpRequest(); + + function abortXhr() { + xhr.abort(); + } + + xhr.onload = function() { + var options = { + status: xhr.status, + statusText: xhr.statusText, + headers: parseHeaders(xhr.getAllResponseHeaders() || '') + }; + options.url = 'responseURL' in xhr ? xhr.responseURL : options.headers.get('X-Request-URL'); + var body = 'response' in xhr ? xhr.response : xhr.responseText; + resolve(new Response(body, options)); + }; + + xhr.onerror = function() { + reject(new TypeError('Network request failed')); + }; + + xhr.ontimeout = function() { + reject(new TypeError('Network request failed')); + }; + + xhr.onabort = function() { + reject(new exports.DOMException('Aborted', 'AbortError')); + }; + + xhr.open(request.method, request.url, true); + + if (request.credentials === 'include') { + xhr.withCredentials = true; + } else if (request.credentials === 'omit') { + xhr.withCredentials = false; + } + + if ('responseType' in xhr && support.blob) { + xhr.responseType = 'blob'; + } + + request.headers.forEach(function(value, name) { + xhr.setRequestHeader(name, value); + }); + + if (request.signal) { + request.signal.addEventListener('abort', abortXhr); + + xhr.onreadystatechange = function() { + // DONE (success or failure) + if (xhr.readyState === 4) { + request.signal.removeEventListener('abort', abortXhr); + } + }; + } + + xhr.send(typeof request._bodyInit === 'undefined' ? null : request._bodyInit); + }) + } + + fetch.polyfill = true; + + if (!self.fetch) { + self.fetch = fetch; + self.Headers = Headers; + self.Request = Request; + self.Response = Response; + } + + exports.Headers = Headers; + exports.Request = Request; + exports.Response = Response; + exports.fetch = fetch; + + return exports; + +}({})); +})(__self__); +delete __self__.fetch.polyfill +exports = __self__.fetch // To enable: import fetch from 'cross-fetch' +exports.default = __self__.fetch // For TypeScript consumers without esModuleInterop. +exports.fetch = __self__.fetch // To enable: import {fetch} from 'cross-fetch' +exports.Headers = __self__.Headers +exports.Request = __self__.Request +exports.Response = __self__.Response +module.exports = exports + + +/***/ }), + +/***/ "./node_modules/css-jss/dist/css-jss.esm.js": +/*!**************************************************!*\ + !*** ./node_modules/css-jss/dist/css-jss.esm.js ***! + \**************************************************/ +/*! exports provided: default, create */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "create", function() { return createCss; }); +/* harmony import */ var jss__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! jss */ "./node_modules/jss/dist/jss.esm.js"); +/* harmony import */ var jss_preset_default__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! jss-preset-default */ "./node_modules/jss-preset-default/dist/jss-preset-default.esm.js"); + + + +// I have been trying to benchmark and I have seen a slow down after about 10k rules. +// Since we are in a single sheet mode, user shouldn't care about this. +var MAX_RULES_PER_SHEET = 10000; +var defaultJss = Object(jss__WEBPACK_IMPORTED_MODULE_0__["create"])(Object(jss_preset_default__WEBPACK_IMPORTED_MODULE_1__["default"])()); + +var createCss = function createCss(jss) { + if (jss === void 0) { + jss = defaultJss; + } + + var cache = new Map(); + var ruleIndex = 0; + var sheet; + + var getSheet = function getSheet() { + if (!sheet || sheet.rules.index.length > MAX_RULES_PER_SHEET) { + sheet = jss.createStyleSheet().attach(); + } + + return sheet; + }; + + function css() { + // eslint-disable-next-line prefer-rest-params + var args = arguments; // We can avoid the need for stringification with a babel plugin, + // which could generate a hash at build time and add it to the object. + + var argsStr = JSON.stringify(args); + var cached = cache.get(argsStr); + if (cached) return cached.className; + var flatArgs = []; // Flatten arguments which can be + // - style objects + // - array of style objects + // - arrays of style objects + + for (var argIndex in args) { + var arg = args[argIndex]; + + if (!Array.isArray(arg)) { + flatArgs.push(arg); + continue; + } + + for (var innerArgIndex = 0; innerArgIndex < arg.length; innerArgIndex++) { + flatArgs.push(arg[innerArgIndex]); + } + } + + var mergedStyle = {}; + var labels = []; + + for (var i = 0; i < flatArgs.length; i++) { + var style = flatArgs[i]; + if (!style) continue; + var styleObject = style; // It can be a class name that css() has previously generated. + + if (typeof style === 'string') { + // eslint-disable-next-line no-shadow + var _cached = cache.get(style); + + if (_cached) { + // eslint-disable-next-line prefer-spread + if (_cached.labels.length) labels.push.apply(labels, _cached.labels); + styleObject = _cached.style; + } + } + + if (styleObject.label && labels.indexOf(styleObject.label) === -1) labels.push(styleObject.label); + Object.assign(mergedStyle, styleObject); + } + + delete mergedStyle.label; + var label = labels.length === 0 ? 'css' : labels.join('-'); + var key = label + "-" + ruleIndex++; + getSheet().addRule(key, mergedStyle); + var className = getSheet().classes[key]; + var cacheValue = { + style: mergedStyle, + labels: labels, + className: className + }; + cache.set(argsStr, cacheValue); + cache.set(className, cacheValue); + return className; + } // For testing only. + + + css.getSheet = getSheet; + return css; +}; + +var css = createCss(); + +/* harmony default export */ __webpack_exports__["default"] = (css); + + + +/***/ }), + +/***/ "./node_modules/css-vendor/dist/css-vendor.esm.js": +/*!********************************************************!*\ + !*** ./node_modules/css-vendor/dist/css-vendor.esm.js ***! + \********************************************************/ +/*! exports provided: prefix, supportedKeyframes, supportedProperty, supportedValue */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "prefix", function() { return prefix; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "supportedKeyframes", function() { return supportedKeyframes; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "supportedProperty", function() { return supportedProperty; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "supportedValue", function() { return supportedValue; }); +/* harmony import */ var is_in_browser__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! is-in-browser */ "./node_modules/is-in-browser/dist/module.js"); +/* harmony import */ var _babel_runtime_helpers_esm_toConsumableArray__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/esm/toConsumableArray */ "./node_modules/@babel/runtime/helpers/esm/toConsumableArray.js"); + + + +// Export javascript style and css style vendor prefixes. +var js = ''; +var css = ''; +var vendor = ''; +var browser = ''; +var isTouch = is_in_browser__WEBPACK_IMPORTED_MODULE_0__["default"] && 'ontouchstart' in document.documentElement; // We should not do anything if required serverside. + +if (is_in_browser__WEBPACK_IMPORTED_MODULE_0__["default"]) { + // Order matters. We need to check Webkit the last one because + // other vendors use to add Webkit prefixes to some properties + var jsCssMap = { + Moz: '-moz-', + ms: '-ms-', + O: '-o-', + Webkit: '-webkit-' + }; + + var _document$createEleme = document.createElement('p'), + style = _document$createEleme.style; + + var testProp = 'Transform'; + + for (var key in jsCssMap) { + if (key + testProp in style) { + js = key; + css = jsCssMap[key]; + break; + } + } // Correctly detect the Edge browser. + + + if (js === 'Webkit' && 'msHyphens' in style) { + js = 'ms'; + css = jsCssMap.ms; + browser = 'edge'; + } // Correctly detect the Safari browser. + + + if (js === 'Webkit' && '-apple-trailing-word' in style) { + vendor = 'apple'; + } +} +/** + * Vendor prefix string for the current browser. + * + * @type {{js: String, css: String, vendor: String, browser: String}} + * @api public + */ + + +var prefix = { + js: js, + css: css, + vendor: vendor, + browser: browser, + isTouch: isTouch +}; + +/** + * Test if a keyframe at-rule should be prefixed or not + * + * @param {String} vendor prefix string for the current browser. + * @return {String} + * @api public + */ + +function supportedKeyframes(key) { + // Keyframes is already prefixed. e.g. key = '@-webkit-keyframes a' + if (key[1] === '-') return key; // No need to prefix IE/Edge. Older browsers will ignore unsupported rules. + // https://caniuse.com/#search=keyframes + + if (prefix.js === 'ms') return key; + return "@" + prefix.css + "keyframes" + key.substr(10); +} + +// https://caniuse.com/#search=appearance + +var appearence = { + noPrefill: ['appearance'], + supportedProperty: function supportedProperty(prop) { + if (prop !== 'appearance') return false; + if (prefix.js === 'ms') return "-webkit-" + prop; + return prefix.css + prop; + } +}; + +// https://caniuse.com/#search=color-adjust + +var colorAdjust = { + noPrefill: ['color-adjust'], + supportedProperty: function supportedProperty(prop) { + if (prop !== 'color-adjust') return false; + if (prefix.js === 'Webkit') return prefix.css + "print-" + prop; + return prop; + } +}; + +var regExp = /[-\s]+(.)?/g; +/** + * Replaces the letter with the capital letter + * + * @param {String} match + * @param {String} c + * @return {String} + * @api private + */ + +function toUpper(match, c) { + return c ? c.toUpperCase() : ''; +} +/** + * Convert dash separated strings to camel-cased. + * + * @param {String} str + * @return {String} + * @api private + */ + + +function camelize(str) { + return str.replace(regExp, toUpper); +} + +/** + * Convert dash separated strings to pascal cased. + * + * @param {String} str + * @return {String} + * @api private + */ + +function pascalize(str) { + return camelize("-" + str); +} + +// but we can use a longhand property instead. +// https://caniuse.com/#search=mask + +var mask = { + noPrefill: ['mask'], + supportedProperty: function supportedProperty(prop, style) { + if (!/^mask/.test(prop)) return false; + + if (prefix.js === 'Webkit') { + var longhand = 'mask-image'; + + if (camelize(longhand) in style) { + return prop; + } + + if (prefix.js + pascalize(longhand) in style) { + return prefix.css + prop; + } + } + + return prop; + } +}; + +// https://caniuse.com/#search=text-orientation + +var textOrientation = { + noPrefill: ['text-orientation'], + supportedProperty: function supportedProperty(prop) { + if (prop !== 'text-orientation') return false; + + if (prefix.vendor === 'apple' && !prefix.isTouch) { + return prefix.css + prop; + } + + return prop; + } +}; + +// https://caniuse.com/#search=transform + +var transform = { + noPrefill: ['transform'], + supportedProperty: function supportedProperty(prop, style, options) { + if (prop !== 'transform') return false; + + if (options.transform) { + return prop; + } + + return prefix.css + prop; + } +}; + +// https://caniuse.com/#search=transition + +var transition = { + noPrefill: ['transition'], + supportedProperty: function supportedProperty(prop, style, options) { + if (prop !== 'transition') return false; + + if (options.transition) { + return prop; + } + + return prefix.css + prop; + } +}; + +// https://caniuse.com/#search=writing-mode + +var writingMode = { + noPrefill: ['writing-mode'], + supportedProperty: function supportedProperty(prop) { + if (prop !== 'writing-mode') return false; + + if (prefix.js === 'Webkit' || prefix.js === 'ms' && prefix.browser !== 'edge') { + return prefix.css + prop; + } + + return prop; + } +}; + +// https://caniuse.com/#search=user-select + +var userSelect = { + noPrefill: ['user-select'], + supportedProperty: function supportedProperty(prop) { + if (prop !== 'user-select') return false; + + if (prefix.js === 'Moz' || prefix.js === 'ms' || prefix.vendor === 'apple') { + return prefix.css + prop; + } + + return prop; + } +}; + +// https://caniuse.com/#search=multicolumn +// https://github.com/postcss/autoprefixer/issues/491 +// https://github.com/postcss/autoprefixer/issues/177 + +var breakPropsOld = { + supportedProperty: function supportedProperty(prop, style) { + if (!/^break-/.test(prop)) return false; + + if (prefix.js === 'Webkit') { + var jsProp = "WebkitColumn" + pascalize(prop); + return jsProp in style ? prefix.css + "column-" + prop : false; + } + + if (prefix.js === 'Moz') { + var _jsProp = "page" + pascalize(prop); + + return _jsProp in style ? "page-" + prop : false; + } + + return false; + } +}; + +// See https://github.com/postcss/autoprefixer/issues/324. + +var inlineLogicalOld = { + supportedProperty: function supportedProperty(prop, style) { + if (!/^(border|margin|padding)-inline/.test(prop)) return false; + if (prefix.js === 'Moz') return prop; + var newProp = prop.replace('-inline', ''); + return prefix.js + pascalize(newProp) in style ? prefix.css + newProp : false; + } +}; + +// Camelization is required because we can't test using. +// CSS syntax for e.g. in FF. + +var unprefixed = { + supportedProperty: function supportedProperty(prop, style) { + return camelize(prop) in style ? prop : false; + } +}; + +var prefixed = { + supportedProperty: function supportedProperty(prop, style) { + var pascalized = pascalize(prop); // Return custom CSS variable without prefixing. + + if (prop[0] === '-') return prop; // Return already prefixed value without prefixing. + + if (prop[0] === '-' && prop[1] === '-') return prop; + if (prefix.js + pascalized in style) return prefix.css + prop; // Try webkit fallback. + + if (prefix.js !== 'Webkit' && "Webkit" + pascalized in style) return "-webkit-" + prop; + return false; + } +}; + +// https://caniuse.com/#search=scroll-snap + +var scrollSnap = { + supportedProperty: function supportedProperty(prop) { + if (prop.substring(0, 11) !== 'scroll-snap') return false; + + if (prefix.js === 'ms') { + return "" + prefix.css + prop; + } + + return prop; + } +}; + +// https://caniuse.com/#search=overscroll-behavior + +var overscrollBehavior = { + supportedProperty: function supportedProperty(prop) { + if (prop !== 'overscroll-behavior') return false; + + if (prefix.js === 'ms') { + return prefix.css + "scroll-chaining"; + } + + return prop; + } +}; + +var propMap = { + 'flex-grow': 'flex-positive', + 'flex-shrink': 'flex-negative', + 'flex-basis': 'flex-preferred-size', + 'justify-content': 'flex-pack', + order: 'flex-order', + 'align-items': 'flex-align', + 'align-content': 'flex-line-pack' // 'align-self' is handled by 'align-self' plugin. + +}; // Support old flex spec from 2012. + +var flex2012 = { + supportedProperty: function supportedProperty(prop, style) { + var newProp = propMap[prop]; + if (!newProp) return false; + return prefix.js + pascalize(newProp) in style ? prefix.css + newProp : false; + } +}; + +var propMap$1 = { + flex: 'box-flex', + 'flex-grow': 'box-flex', + 'flex-direction': ['box-orient', 'box-direction'], + order: 'box-ordinal-group', + 'align-items': 'box-align', + 'flex-flow': ['box-orient', 'box-direction'], + 'justify-content': 'box-pack' +}; +var propKeys = Object.keys(propMap$1); + +var prefixCss = function prefixCss(p) { + return prefix.css + p; +}; // Support old flex spec from 2009. + + +var flex2009 = { + supportedProperty: function supportedProperty(prop, style, _ref) { + var multiple = _ref.multiple; + + if (propKeys.indexOf(prop) > -1) { + var newProp = propMap$1[prop]; + + if (!Array.isArray(newProp)) { + return prefix.js + pascalize(newProp) in style ? prefix.css + newProp : false; + } + + if (!multiple) return false; + + for (var i = 0; i < newProp.length; i++) { + if (!(prefix.js + pascalize(newProp[0]) in style)) { + return false; + } + } + + return newProp.map(prefixCss); + } + + return false; + } +}; + +// plugins = [ +// ...plugins, +// breakPropsOld, +// inlineLogicalOld, +// unprefixed, +// prefixed, +// scrollSnap, +// flex2012, +// flex2009 +// ] +// Plugins without 'noPrefill' value, going last. +// 'flex-*' plugins should be at the bottom. +// 'flex2009' going after 'flex2012'. +// 'prefixed' going after 'unprefixed' + +var plugins = [appearence, colorAdjust, mask, textOrientation, transform, transition, writingMode, userSelect, breakPropsOld, inlineLogicalOld, unprefixed, prefixed, scrollSnap, overscrollBehavior, flex2012, flex2009]; +var propertyDetectors = plugins.filter(function (p) { + return p.supportedProperty; +}).map(function (p) { + return p.supportedProperty; +}); +var noPrefill = plugins.filter(function (p) { + return p.noPrefill; +}).reduce(function (a, p) { + a.push.apply(a, Object(_babel_runtime_helpers_esm_toConsumableArray__WEBPACK_IMPORTED_MODULE_1__["default"])(p.noPrefill)); + return a; +}, []); + +var el; +var cache = {}; + +if (is_in_browser__WEBPACK_IMPORTED_MODULE_0__["default"]) { + el = document.createElement('p'); // We test every property on vendor prefix requirement. + // Once tested, result is cached. It gives us up to 70% perf boost. + // http://jsperf.com/element-style-object-access-vs-plain-object + // + // Prefill cache with known css properties to reduce amount of + // properties we need to feature test at runtime. + // http://davidwalsh.name/vendor-prefix + + var computed = window.getComputedStyle(document.documentElement, ''); + + for (var key$1 in computed) { + // eslint-disable-next-line no-restricted-globals + if (!isNaN(key$1)) cache[computed[key$1]] = computed[key$1]; + } // Properties that cannot be correctly detected using the + // cache prefill method. + + + noPrefill.forEach(function (x) { + return delete cache[x]; + }); +} +/** + * Test if a property is supported, returns supported property with vendor + * prefix if required. Returns `false` if not supported. + * + * @param {String} prop dash separated + * @param {Object} [options] + * @return {String|Boolean} + * @api public + */ + + +function supportedProperty(prop, options) { + if (options === void 0) { + options = {}; + } + + // For server-side rendering. + if (!el) return prop; // Remove cache for benchmark tests or return property from the cache. + + if ( true && cache[prop] != null) { + return cache[prop]; + } // Check if 'transition' or 'transform' natively supported in browser. + + + if (prop === 'transition' || prop === 'transform') { + options[prop] = prop in el.style; + } // Find a plugin for current prefix property. + + + for (var i = 0; i < propertyDetectors.length; i++) { + cache[prop] = propertyDetectors[i](prop, el.style, options); // Break loop, if value found. + + if (cache[prop]) break; + } // Reset styles for current property. + // Firefox can even throw an error for invalid properties, e.g., "0". + + + try { + el.style[prop] = ''; + } catch (err) { + return false; + } + + return cache[prop]; +} + +var cache$1 = {}; +var transitionProperties = { + transition: 1, + 'transition-property': 1, + '-webkit-transition': 1, + '-webkit-transition-property': 1 +}; +var transPropsRegExp = /(^\s*[\w-]+)|, (\s*[\w-]+)(?![^()]*\))/g; +var el$1; +/** + * Returns prefixed value transition/transform if needed. + * + * @param {String} match + * @param {String} p1 + * @param {String} p2 + * @return {String} + * @api private + */ + +function prefixTransitionCallback(match, p1, p2) { + if (p1 === 'var') return 'var'; + if (p1 === 'all') return 'all'; + if (p2 === 'all') return ', all'; + var prefixedValue = p1 ? supportedProperty(p1) : ", " + supportedProperty(p2); + if (!prefixedValue) return p1 || p2; + return prefixedValue; +} + +if (is_in_browser__WEBPACK_IMPORTED_MODULE_0__["default"]) el$1 = document.createElement('p'); +/** + * Returns prefixed value if needed. Returns `false` if value is not supported. + * + * @param {String} property + * @param {String} value + * @return {String|Boolean} + * @api public + */ + +function supportedValue(property, value) { + // For server-side rendering. + var prefixedValue = value; + if (!el$1 || property === 'content') return value; // It is a string or a number as a string like '1'. + // We want only prefixable values here. + // eslint-disable-next-line no-restricted-globals + + if (typeof prefixedValue !== 'string' || !isNaN(parseInt(prefixedValue, 10))) { + return prefixedValue; + } // Create cache key for current value. + + + var cacheKey = property + prefixedValue; // Remove cache for benchmark tests or return value from cache. + + if ( true && cache$1[cacheKey] != null) { + return cache$1[cacheKey]; + } // IE can even throw an error in some cases, for e.g. style.content = 'bar'. + + + try { + // Test value as it is. + el$1.style[property] = prefixedValue; + } catch (err) { + // Return false if value not supported. + cache$1[cacheKey] = false; + return false; + } // If 'transition' or 'transition-property' property. + + + if (transitionProperties[property]) { + prefixedValue = prefixedValue.replace(transPropsRegExp, prefixTransitionCallback); + } else if (el$1.style[property] === '') { + // Value with a vendor prefix. + prefixedValue = prefix.css + prefixedValue; // Hardcode test to convert "flex" to "-ms-flexbox" for IE10. + + if (prefixedValue === '-ms-flex') el$1.style[property] = '-ms-flexbox'; // Test prefixed value. + + el$1.style[property] = prefixedValue; // Return false if value not supported. + + if (el$1.style[property] === '') { + cache$1[cacheKey] = false; + return false; + } + } // Reset styles for current property. + + + el$1.style[property] = ''; // Write current value to cache. + + cache$1[cacheKey] = prefixedValue; + return cache$1[cacheKey]; +} + + + + +/***/ }), + +/***/ "./node_modules/escape-html/index.js": +/*!*******************************************!*\ + !*** ./node_modules/escape-html/index.js ***! + \*******************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/*! + * escape-html + * Copyright(c) 2012-2013 TJ Holowaychuk + * Copyright(c) 2015 Andreas Lubbe + * Copyright(c) 2015 Tiancheng "Timothy" Gu + * MIT Licensed + */ + + + +/** + * Module variables. + * @private + */ + +var matchHtmlRegExp = /["'&<>]/; + +/** + * Module exports. + * @public + */ + +module.exports = escapeHtml; + +/** + * Escape special characters in the given string of html. + * + * @param {string} string The string to escape for inserting into HTML + * @return {string} + * @public + */ + +function escapeHtml(string) { + var str = '' + string; + var match = matchHtmlRegExp.exec(str); + + if (!match) { + return str; + } + + var escape; + var html = ''; + var index = 0; + var lastIndex = 0; + + for (index = match.index; index < str.length; index++) { + switch (str.charCodeAt(index)) { + case 34: // " + escape = '"'; + break; + case 38: // & + escape = '&'; + break; + case 39: // ' + escape = '''; + break; + case 60: // < + escape = '<'; + break; + case 62: // > + escape = '>'; + break; + default: + continue; + } + + if (lastIndex !== index) { + html += str.substring(lastIndex, index); + } + + lastIndex = index + 1; + html += escape; + } + + return lastIndex !== index + ? html + str.substring(lastIndex, index) + : html; +} + + +/***/ }), + +/***/ "./node_modules/events/events.js": +/*!***************************************!*\ + !*** ./node_modules/events/events.js ***! + \***************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + +var R = typeof Reflect === 'object' ? Reflect : null +var ReflectApply = R && typeof R.apply === 'function' + ? R.apply + : function ReflectApply(target, receiver, args) { + return Function.prototype.apply.call(target, receiver, args); + } + +var ReflectOwnKeys +if (R && typeof R.ownKeys === 'function') { + ReflectOwnKeys = R.ownKeys +} else if (Object.getOwnPropertySymbols) { + ReflectOwnKeys = function ReflectOwnKeys(target) { + return Object.getOwnPropertyNames(target) + .concat(Object.getOwnPropertySymbols(target)); + }; +} else { + ReflectOwnKeys = function ReflectOwnKeys(target) { + return Object.getOwnPropertyNames(target); + }; +} + +function ProcessEmitWarning(warning) { + if (console && console.warn) console.warn(warning); +} + +var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) { + return value !== value; +} + +function EventEmitter() { + EventEmitter.init.call(this); +} +module.exports = EventEmitter; +module.exports.once = once; + +// Backwards-compat with node 0.10.x +EventEmitter.EventEmitter = EventEmitter; + +EventEmitter.prototype._events = undefined; +EventEmitter.prototype._eventsCount = 0; +EventEmitter.prototype._maxListeners = undefined; + +// By default EventEmitters will print a warning if more than 10 listeners are +// added to it. This is a useful default which helps finding memory leaks. +var defaultMaxListeners = 10; + +function checkListener(listener) { + if (typeof listener !== 'function') { + throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); + } +} + +Object.defineProperty(EventEmitter, 'defaultMaxListeners', { + enumerable: true, + get: function() { + return defaultMaxListeners; + }, + set: function(arg) { + if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) { + throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.'); + } + defaultMaxListeners = arg; + } +}); + +EventEmitter.init = function() { + + if (this._events === undefined || + this._events === Object.getPrototypeOf(this)._events) { + this._events = Object.create(null); + this._eventsCount = 0; + } + + this._maxListeners = this._maxListeners || undefined; +}; + +// Obviously not all Emitters should be limited to 10. This function allows +// that to be increased. Set to zero for unlimited. +EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { + if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) { + throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.'); + } + this._maxListeners = n; + return this; +}; + +function _getMaxListeners(that) { + if (that._maxListeners === undefined) + return EventEmitter.defaultMaxListeners; + return that._maxListeners; +} + +EventEmitter.prototype.getMaxListeners = function getMaxListeners() { + return _getMaxListeners(this); +}; + +EventEmitter.prototype.emit = function emit(type) { + var args = []; + for (var i = 1; i < arguments.length; i++) args.push(arguments[i]); + var doError = (type === 'error'); + + var events = this._events; + if (events !== undefined) + doError = (doError && events.error === undefined); + else if (!doError) + return false; + + // If there is no 'error' event listener then throw. + if (doError) { + var er; + if (args.length > 0) + er = args[0]; + if (er instanceof Error) { + // Note: The comments on the `throw` lines are intentional, they show + // up in Node's output if this results in an unhandled exception. + throw er; // Unhandled 'error' event + } + // At least give some kind of context to the user + var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : '')); + err.context = er; + throw err; // Unhandled 'error' event + } + + var handler = events[type]; + + if (handler === undefined) + return false; + + if (typeof handler === 'function') { + ReflectApply(handler, this, args); + } else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + ReflectApply(listeners[i], this, args); + } + + return true; +}; + +function _addListener(target, type, listener, prepend) { + var m; + var events; + var existing; + + checkListener(listener); + + events = target._events; + if (events === undefined) { + events = target._events = Object.create(null); + target._eventsCount = 0; + } else { + // To avoid recursion in the case that type === "newListener"! Before + // adding it to the listeners, first emit "newListener". + if (events.newListener !== undefined) { + target.emit('newListener', type, + listener.listener ? listener.listener : listener); + + // Re-assign `events` because a newListener handler could have caused the + // this._events to be assigned to a new object + events = target._events; + } + existing = events[type]; + } + + if (existing === undefined) { + // Optimize the case of one listener. Don't need the extra array object. + existing = events[type] = listener; + ++target._eventsCount; + } else { + if (typeof existing === 'function') { + // Adding the second element, need to change to array. + existing = events[type] = + prepend ? [listener, existing] : [existing, listener]; + // If we've already got an array, just append. + } else if (prepend) { + existing.unshift(listener); + } else { + existing.push(listener); + } + + // Check for listener leak + m = _getMaxListeners(target); + if (m > 0 && existing.length > m && !existing.warned) { + existing.warned = true; + // No error code for this since it is a Warning + // eslint-disable-next-line no-restricted-syntax + var w = new Error('Possible EventEmitter memory leak detected. ' + + existing.length + ' ' + String(type) + ' listeners ' + + 'added. Use emitter.setMaxListeners() to ' + + 'increase limit'); + w.name = 'MaxListenersExceededWarning'; + w.emitter = target; + w.type = type; + w.count = existing.length; + ProcessEmitWarning(w); + } + } + + return target; +} + +EventEmitter.prototype.addListener = function addListener(type, listener) { + return _addListener(this, type, listener, false); +}; + +EventEmitter.prototype.on = EventEmitter.prototype.addListener; + +EventEmitter.prototype.prependListener = + function prependListener(type, listener) { + return _addListener(this, type, listener, true); + }; + +function onceWrapper() { + if (!this.fired) { + this.target.removeListener(this.type, this.wrapFn); + this.fired = true; + if (arguments.length === 0) + return this.listener.call(this.target); + return this.listener.apply(this.target, arguments); + } +} + +function _onceWrap(target, type, listener) { + var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener }; + var wrapped = onceWrapper.bind(state); + wrapped.listener = listener; + state.wrapFn = wrapped; + return wrapped; +} + +EventEmitter.prototype.once = function once(type, listener) { + checkListener(listener); + this.on(type, _onceWrap(this, type, listener)); + return this; +}; + +EventEmitter.prototype.prependOnceListener = + function prependOnceListener(type, listener) { + checkListener(listener); + this.prependListener(type, _onceWrap(this, type, listener)); + return this; + }; + +// Emits a 'removeListener' event if and only if the listener was removed. +EventEmitter.prototype.removeListener = + function removeListener(type, listener) { + var list, events, position, i, originalListener; + + checkListener(listener); + + events = this._events; + if (events === undefined) + return this; + + list = events[type]; + if (list === undefined) + return this; + + if (list === listener || list.listener === listener) { + if (--this._eventsCount === 0) + this._events = Object.create(null); + else { + delete events[type]; + if (events.removeListener) + this.emit('removeListener', type, list.listener || listener); + } + } else if (typeof list !== 'function') { + position = -1; + + for (i = list.length - 1; i >= 0; i--) { + if (list[i] === listener || list[i].listener === listener) { + originalListener = list[i].listener; + position = i; + break; + } + } + + if (position < 0) + return this; + + if (position === 0) + list.shift(); + else { + spliceOne(list, position); + } + + if (list.length === 1) + events[type] = list[0]; + + if (events.removeListener !== undefined) + this.emit('removeListener', type, originalListener || listener); + } + + return this; + }; + +EventEmitter.prototype.off = EventEmitter.prototype.removeListener; + +EventEmitter.prototype.removeAllListeners = + function removeAllListeners(type) { + var listeners, events, i; + + events = this._events; + if (events === undefined) + return this; + + // not listening for removeListener, no need to emit + if (events.removeListener === undefined) { + if (arguments.length === 0) { + this._events = Object.create(null); + this._eventsCount = 0; + } else if (events[type] !== undefined) { + if (--this._eventsCount === 0) + this._events = Object.create(null); + else + delete events[type]; + } + return this; + } + + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + var keys = Object.keys(events); + var key; + for (i = 0; i < keys.length; ++i) { + key = keys[i]; + if (key === 'removeListener') continue; + this.removeAllListeners(key); + } + this.removeAllListeners('removeListener'); + this._events = Object.create(null); + this._eventsCount = 0; + return this; + } + + listeners = events[type]; + + if (typeof listeners === 'function') { + this.removeListener(type, listeners); + } else if (listeners !== undefined) { + // LIFO order + for (i = listeners.length - 1; i >= 0; i--) { + this.removeListener(type, listeners[i]); + } + } + + return this; + }; + +function _listeners(target, type, unwrap) { + var events = target._events; + + if (events === undefined) + return []; + + var evlistener = events[type]; + if (evlistener === undefined) + return []; + + if (typeof evlistener === 'function') + return unwrap ? [evlistener.listener || evlistener] : [evlistener]; + + return unwrap ? + unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length); +} + +EventEmitter.prototype.listeners = function listeners(type) { + return _listeners(this, type, true); +}; + +EventEmitter.prototype.rawListeners = function rawListeners(type) { + return _listeners(this, type, false); +}; + +EventEmitter.listenerCount = function(emitter, type) { + if (typeof emitter.listenerCount === 'function') { + return emitter.listenerCount(type); + } else { + return listenerCount.call(emitter, type); + } +}; + +EventEmitter.prototype.listenerCount = listenerCount; +function listenerCount(type) { + var events = this._events; + + if (events !== undefined) { + var evlistener = events[type]; + + if (typeof evlistener === 'function') { + return 1; + } else if (evlistener !== undefined) { + return evlistener.length; + } + } + + return 0; +} + +EventEmitter.prototype.eventNames = function eventNames() { + return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : []; +}; + +function arrayClone(arr, n) { + var copy = new Array(n); + for (var i = 0; i < n; ++i) + copy[i] = arr[i]; + return copy; +} + +function spliceOne(list, index) { + for (; index + 1 < list.length; index++) + list[index] = list[index + 1]; + list.pop(); +} + +function unwrapListeners(arr) { + var ret = new Array(arr.length); + for (var i = 0; i < ret.length; ++i) { + ret[i] = arr[i].listener || arr[i]; + } + return ret; +} + +function once(emitter, name) { + return new Promise(function (resolve, reject) { + function eventListener() { + if (errorListener !== undefined) { + emitter.removeListener('error', errorListener); + } + resolve([].slice.call(arguments)); + }; + var errorListener; + + // Adding an error listener is not optional because + // if an error is thrown on an event emitter we cannot + // guarantee that the actual event we are waiting will + // be fired. The result could be a silent way to create + // memory or file descriptor leaks, which is something + // we should avoid. + if (name !== 'error') { + errorListener = function errorListener(err) { + emitter.removeListener(name, eventListener); + reject(err); + }; + + emitter.once('error', errorListener); + } + + emitter.once(name, eventListener); + }); +} + + +/***/ }), + +/***/ "./node_modules/folder-pane/folderPane.js": +/*!************************************************!*\ + !*** ./node_modules/folder-pane/folderPane.js ***! + \************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +/* Folder pane + ** + ** This outline pane lists the members of a folder + */ + +var UI = __webpack_require__(/*! solid-ui */ "./node_modules/solid-ui/lib/index.js") +var ns = UI.ns + +module.exports = { + icon: UI.icons.iconBase + 'noun_973694_expanded.svg', + + name: 'folder', + + // Create a new folder in a Solid system, + mintNew: function (context, newPaneOptions) { + var kb = context.session.store + var newInstance = + newPaneOptions.newInstance || kb.sym(newPaneOptions.newBase) + var u = newInstance.uri + if (u.endsWith('/')) { + u = u.slice(0, -1) // chop off trailer + } // { throw new Error('URI of new folder must end in "/" :' + u) } + newPaneOptions.newInstance = kb.sym(u + '/') + + // @@@@ kludge until we can get the solid-client version working + // Force the folder by saving a dummy file inside it + return kb.fetcher + .webOperation('PUT', newInstance.uri + '.dummy') + .then(function () { + console.log('New folder created: ' + newInstance.uri) + + return kb.fetcher.delete(newInstance.uri + '.dummy') + }) + .then(function () { + console.log('Dummy file deleted : ' + newInstance.uri + '.dummy') + /* + return kb.fetcher.createContainer(parentURI, folderName) // Not BOTH ways + }) + .then(function () { +*/ + console.log('New container created: ' + newInstance.uri) + return newPaneOptions + }) + }, + + label: function (subject, context) { + var kb = context.session.store + var n = kb.each(subject, ns.ldp('contains')).length + if (n > 0) { + return 'Contents (' + n + ')' // Show how many in hover text + } + if (kb.holds(subject, ns.rdf('type'), ns.ldp('Container'))) { + // It is declared as being a container + return 'Container (0)' + } + return null // Suppress pane otherwise + }, + + // Render a file folder in a LDP/solid system + + render: function (subject, context) { + var dom = context.dom + var outliner = context.getOutliner(dom) + var kb = context.session.store + var mainTable // This is a live synced table + /* + var complain = function complain (message, color) { + var pre = dom.createElement('pre') + console.log(message) + pre.setAttribute('style', 'background-color: ' + color || '#eed' + ';') + div.appendChild(pre) + pre.appendChild(dom.createTextNode(message)) + } +*/ + var div = dom.createElement('div') + div.setAttribute('class', 'instancePane') + div.setAttribute( + 'style', + ' border-top: solid 1px #777; border-bottom: solid 1px #777; margin-top: 0.5em; margin-bottom: 0.5em ' + ) + + // If this is an LDP container just list the directory + + var noHiddenFiles = function (obj) { + // @@ This hiddenness should actually be server defined + var pathEnd = obj.uri.slice(obj.dir().uri.length) + return !( + pathEnd.startsWith('.') || + pathEnd.endsWith('.acl') || + pathEnd.endsWith('~') + ) + } + const thisDir = subject.uri.endsWith('/') ? subject.uri : subject.uri + '/' + const indexThing = kb.sym(thisDir + 'index.ttl#this') + if (kb.holds(subject, ns.ldp('contains'), indexThing.doc())) { + console.log( + 'View of folder with be view of indexThing. Loading ' + indexThing + ) + const packageDiv = div.appendChild(dom.createElement('div')) + packageDiv.style.cssText = 'border-top: 0.2em solid #ccc;' // Separate folder views above from package views below + kb.fetcher.load(indexThing.doc()).then(function () { + mainTable = packageDiv.appendChild(dom.createElement('table')) + context + .getOutliner(dom) + .GotoSubject(indexThing, true, undefined, false, undefined, mainTable) + }) + + return div + } else { + mainTable = div.appendChild(dom.createElement('table')) + var refresh = function () { + var objs = kb.each(subject, ns.ldp('contains')).filter(noHiddenFiles) + objs = objs.map(obj => [UI.utils.label(obj).toLowerCase(), obj]) + objs.sort() // Sort by label case-insensitive + objs = objs.map(pair => pair[1]) + UI.utils.syncTableToArray(mainTable, objs, function (obj) { + const st = kb.statementsMatching(subject, ns.ldp('contains'), obj)[0] + const defaultpropview = outliner.VIEWAS_boring_default + const tr = outliner.propertyTR(dom, st, false) + tr.firstChild.textContent = '' // Was initialized to 'Contains' + tr.firstChild.style.cssText += 'min-width: 3em;' + tr.appendChild( + outliner.outlineObjectTD(obj, defaultpropview, undefined, st) + ) + // UI.widgets.makeDraggable(tr, obj) + return tr + }) + } + mainTable.refresh = refresh + refresh() + } + + // Allow user to create new things within the folder + var creationDiv = div.appendChild(dom.createElement('div')) + var me = UI.authn.currentUser() + var creationContext = { + folder: subject, + div: creationDiv, + dom: dom, + statusArea: creationDiv, + me: me + } + creationContext.refreshTarget = mainTable + UI.authn + .filterAvailablePanes(context.session.paneRegistry.list) + .then(function (relevantPanes) { + UI.create.newThingUI(creationContext, context, relevantPanes) // Have to pass panes down newUI + + UI.aclControl.preventBrowserDropEvents(dom) + + const explictDropIcon = false + var target + if (explictDropIcon) { + const iconStyleFound = creationDiv.firstChild.style.cssText + target = creationDiv.insertBefore( + dom.createElement('img'), + creationDiv.firstChild + ) + target.style.cssText = iconStyleFound + target.setAttribute('src', UI.icons.iconBase + 'noun_748003.svg') + target.setAttribute('style', 'width: 2em; height: 2em') // Safari says target.style is read-only + } else { + target = creationDiv.firstChild // Overload drop target semantics onto the plus sign + } + + // /////////// Allow new file to be Uploaded + UI.widgets.makeDropTarget(target, null, droppedFileHandler) + }) + + return div + + function droppedFileHandler (files) { + UI.widgets.uploadFiles( + kb.fetcher, + files, + subject.uri, + subject.uri, + function (file, uri) { + // A file has been uploaded + const destination = kb.sym(uri) + console.log(' Upload: put OK: ' + destination) + kb.add(subject, ns.ldp('contains'), destination, subject.doc()) + mainTable.refresh() + } + ) + } + } +} +// ends + + +/***/ }), + +/***/ "./node_modules/hoist-non-react-statics/dist/hoist-non-react-statics.cjs.js": +/*!**********************************************************************************!*\ + !*** ./node_modules/hoist-non-react-statics/dist/hoist-non-react-statics.cjs.js ***! + \**********************************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var reactIs = __webpack_require__(/*! react-is */ "./node_modules/react-is/index.js"); + +/** + * Copyright 2015, Yahoo! Inc. + * Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. + */ +var REACT_STATICS = { + childContextTypes: true, + contextType: true, + contextTypes: true, + defaultProps: true, + displayName: true, + getDefaultProps: true, + getDerivedStateFromError: true, + getDerivedStateFromProps: true, + mixins: true, + propTypes: true, + type: true +}; +var KNOWN_STATICS = { + name: true, + length: true, + prototype: true, + caller: true, + callee: true, + arguments: true, + arity: true +}; +var FORWARD_REF_STATICS = { + '$$typeof': true, + render: true, + defaultProps: true, + displayName: true, + propTypes: true +}; +var MEMO_STATICS = { + '$$typeof': true, + compare: true, + defaultProps: true, + displayName: true, + propTypes: true, + type: true +}; +var TYPE_STATICS = {}; +TYPE_STATICS[reactIs.ForwardRef] = FORWARD_REF_STATICS; +TYPE_STATICS[reactIs.Memo] = MEMO_STATICS; + +function getStatics(component) { + // React v16.11 and below + if (reactIs.isMemo(component)) { + return MEMO_STATICS; + } // React v16.12 and above + + + return TYPE_STATICS[component['$$typeof']] || REACT_STATICS; +} + +var defineProperty = Object.defineProperty; +var getOwnPropertyNames = Object.getOwnPropertyNames; +var getOwnPropertySymbols = Object.getOwnPropertySymbols; +var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; +var getPrototypeOf = Object.getPrototypeOf; +var objectPrototype = Object.prototype; +function hoistNonReactStatics(targetComponent, sourceComponent, blacklist) { + if (typeof sourceComponent !== 'string') { + // don't hoist over string (html) components + if (objectPrototype) { + var inheritedComponent = getPrototypeOf(sourceComponent); + + if (inheritedComponent && inheritedComponent !== objectPrototype) { + hoistNonReactStatics(targetComponent, inheritedComponent, blacklist); + } + } + + var keys = getOwnPropertyNames(sourceComponent); + + if (getOwnPropertySymbols) { + keys = keys.concat(getOwnPropertySymbols(sourceComponent)); + } + + var targetStatics = getStatics(targetComponent); + var sourceStatics = getStatics(sourceComponent); + + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + + if (!KNOWN_STATICS[key] && !(blacklist && blacklist[key]) && !(sourceStatics && sourceStatics[key]) && !(targetStatics && targetStatics[key])) { + var descriptor = getOwnPropertyDescriptor(sourceComponent, key); + + try { + // Avoid failures from read-only properties + defineProperty(targetComponent, key, descriptor); + } catch (e) {} + } + } + } + + return targetComponent; +} + +module.exports = hoistNonReactStatics; + + +/***/ }), + +/***/ "./node_modules/hyphenate-style-name/index.js": +/*!****************************************************!*\ + !*** ./node_modules/hyphenate-style-name/index.js ***! + \****************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* eslint-disable no-var, prefer-template */ +var uppercasePattern = /[A-Z]/g +var msPattern = /^ms-/ +var cache = {} + +function toHyphenLower(match) { + return '-' + match.toLowerCase() +} + +function hyphenateStyleName(name) { + if (cache.hasOwnProperty(name)) { + return cache[name] + } + + var hName = name.replace(uppercasePattern, toHyphenLower) + return (cache[name] = msPattern.test(hName) ? '-' + hName : hName) +} + +/* harmony default export */ __webpack_exports__["default"] = (hyphenateStyleName); + + +/***/ }), + +/***/ "./node_modules/ieee754/index.js": +/*!***************************************!*\ + !*** ./node_modules/ieee754/index.js ***! + \***************************************/ +/*! no static exports found */ +/***/ (function(module, exports) { + +/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ +exports.read = function (buffer, offset, isLE, mLen, nBytes) { + var e, m + var eLen = (nBytes * 8) - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var nBits = -7 + var i = isLE ? (nBytes - 1) : 0 + var d = isLE ? -1 : 1 + var s = buffer[offset + i] + + i += d + + e = s & ((1 << (-nBits)) - 1) + s >>= (-nBits) + nBits += eLen + for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1) + e >>= (-nBits) + nBits += mLen + for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen) + e = e - eBias + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) +} + +exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c + var eLen = (nBytes * 8) - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) + var i = isLE ? 0 : (nBytes - 1) + var d = isLE ? 1 : -1 + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 + + value = Math.abs(value) + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0 + e = eMax + } else { + e = Math.floor(Math.log(value) / Math.LN2) + if (value * (c = Math.pow(2, -e)) < 1) { + e-- + c *= 2 + } + if (e + eBias >= 1) { + value += rt / c + } else { + value += rt * Math.pow(2, 1 - eBias) + } + if (value * c >= 2) { + e++ + c /= 2 + } + + if (e + eBias >= eMax) { + m = 0 + e = eMax + } else if (e + eBias >= 1) { + m = ((value * c) - 1) * Math.pow(2, mLen) + e = e + eBias + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) + e = 0 + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m + eLen += mLen + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128 +} + + +/***/ }), + +/***/ "./node_modules/inherits/inherits_browser.js": +/*!***************************************************!*\ + !*** ./node_modules/inherits/inherits_browser.js ***! + \***************************************************/ +/*! no static exports found */ +/***/ (function(module, exports) { + +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }) + } + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } + } +} + + +/***/ }), + +/***/ "./node_modules/is-in-browser/dist/module.js": +/*!***************************************************!*\ + !*** ./node_modules/is-in-browser/dist/module.js ***! + \***************************************************/ +/*! exports provided: isBrowser, default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isBrowser", function() { return isBrowser; }); +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + +var isBrowser = (typeof window === "undefined" ? "undefined" : _typeof(window)) === "object" && (typeof document === "undefined" ? "undefined" : _typeof(document)) === 'object' && document.nodeType === 9; + +/* harmony default export */ __webpack_exports__["default"] = (isBrowser); + + +/***/ }), + +/***/ "./node_modules/isarray/index.js": +/*!***************************************!*\ + !*** ./node_modules/isarray/index.js ***! + \***************************************/ +/*! no static exports found */ +/***/ (function(module, exports) { + +var toString = {}.toString; + +module.exports = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; +}; + + +/***/ }), + +/***/ "./node_modules/issue-pane/board.js": +/*!******************************************!*\ + !*** ./node_modules/issue-pane/board.js ***! + \******************************************/ +/*! exports provided: board */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "board", function() { return board; }); +/* harmony import */ var solid_ui__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! solid-ui */ "./node_modules/solid-ui/lib/index.js"); +/* harmony import */ var solid_ui__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(solid_ui__WEBPACK_IMPORTED_MODULE_0__); +/** A Board of vertical columns + * + * Like a github "project", or a kanbam board, a board allows + * you to triage stuff into simple cateories. + * + * if an object is added in a refresh, then a new column should be added if needed + * if its value is previously unseen + * (Should the coluimn order be defined by user or caller?) + * + * @returns dom:Element +*/ + + +const kb = solid_ui__WEBPACK_IMPORTED_MODULE_0__["store"] +const ns = solid_ui__WEBPACK_IMPORTED_MODULE_0__["ns"] +const $rdf = solid_ui__WEBPACK_IMPORTED_MODULE_0__["rdf"] + +function board (dom, columnValues, renderItem, options) { + const board = dom.createElement('div') + board.style = 'width: 100%;' + board.style.margin = '1em' + const table = board.appendChild(dom.createElement('table')) + table.style = 'width: 100%;' + table.style.borderCollapse = 'collapse' + + const headerRow = table.appendChild(dom.createElement('tr')) + const mainRow = table.appendChild(dom.createElement('tr')) + columnValues.forEach(x => { + const cell = headerRow.appendChild(dom.createElement('th')) + cell.textContent = solid_ui__WEBPACK_IMPORTED_MODULE_0__["utils"].label(x, true) // Initial capital + cell.subject = x + cell.style = 'margin: 0.3em; padding: 0.5em 1em; font-treatment: bold; font-size: 120%;' + + const column = mainRow.appendChild(dom.createElement('td')) + column.subject = x + column.style = 'border: 0.01em solid white; padding: 0.1em;' // display: flex; flex-direction: column; align-items: center; + + function droppedURIHandler (uris) { + uris.forEach(function (u) { + console.log('Dropped on column: ' + u) + const item = kb.sym(u) + options.columnDropHandler(item, x) + }) + } + + if (options.columnDropHandler) { + solid_ui__WEBPACK_IMPORTED_MODULE_0__["widgets"].makeDropTarget(column, droppedURIHandler) + } + }) + + /* Each item on the board + * normally App will override this + */ + function defaultRenderItem (item, category) { + const card = dom.createElement('div') + const table = card.appendChild(dom.createElement('table')) + const classes = kb.each(item, ns.rdf('type')) + const catColors = classes.map(cat => kb.any(cat, ns.ui('backgroundColor'))).filter(c => c) + + table.appendChild(solid_ui__WEBPACK_IMPORTED_MODULE_0__["widgets"].personTR(dom, null, item)) + table.subject = item + table.style = 'margin: 1em;' // @@ use style.js + const backgroundColor = catColors[0] || kb.any(category, ns.ui('backgroundColor')) + card.style.backgroundColor = backgroundColor ? backgroundColor.value : '#fff' + return card + } + + function sortedBy (values, predicate, defaultSortValue, reverse) { + const toBeSorted = values.map(x => [kb.any(x, predicate) || defaultSortValue, x]) + toBeSorted.sort() + if (reverse) toBeSorted.reverse() // @@ check + return toBeSorted.map(pair => pair[1]) + } + board.refresh = function () { + const now = new $rdf.Literal(new Date()) + const actualRenderItem = renderItem || options.renderItem || defaultRenderItem + function localRenderItem (subject) { + const ele = actualRenderItem(subject) + solid_ui__WEBPACK_IMPORTED_MODULE_0__["widgets"].makeDraggable(ele, subject) + ele.subject = subject + return ele + } + for (let col = mainRow.firstChild; col; col = col.nextSibling) { + const category = col.subject + let items = kb.each(null, ns.rdf('type'), category) + const sortBy = options.sortBy || ns.dct('created') + if (options.filter) { + items = items.filter(options.filter) + } + const sortedItems = sortedBy(items, sortBy, now, true) + solid_ui__WEBPACK_IMPORTED_MODULE_0__["utils"].syncTableToArrayReOrdered(col, sortedItems, localRenderItem) + } + } + + // kb.query(query, addCellFromBindings, undefined, whenDone) // Populate the board + board.refresh() + return board +} + + +/***/ }), + +/***/ "./node_modules/issue-pane/issue.js": +/*!******************************************!*\ + !*** ./node_modules/issue-pane/issue.js ***! + \******************************************/ +/*! exports provided: getState, renderIssueCard, exposeOverlay, renderIssue */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getState", function() { return getState; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "renderIssueCard", function() { return renderIssueCard; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "exposeOverlay", function() { return exposeOverlay; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "renderIssue", function() { return renderIssue; }); +/* harmony import */ var solid_ui__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! solid-ui */ "./node_modules/solid-ui/lib/index.js"); +/* harmony import */ var solid_ui__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(solid_ui__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _newIssue__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./newIssue */ "./node_modules/issue-pane/newIssue.js"); +// All the UI for a single issue, without store load or listening for changes +// + + + +const $rdf = solid_ui__WEBPACK_IMPORTED_MODULE_0__["rdf"] +const kb = solid_ui__WEBPACK_IMPORTED_MODULE_0__["store"] + +const SET_MODIFIED_DATES = false + +function complain (message, context) { + console.warn(message) + context.paneDiv.appendChild(solid_ui__WEBPACK_IMPORTED_MODULE_0__["widgets"].errorMessageBlock(context.dom, message)) +} + +function getState (issue, classification) { + const tracker = kb.the(issue, solid_ui__WEBPACK_IMPORTED_MODULE_0__["ns"].wf('tracker'), null, issue.doc()) + const states = kb.any(tracker, solid_ui__WEBPACK_IMPORTED_MODULE_0__["ns"].wf('issueClass')) + classification = classification || states + const types = kb.each(issue, solid_ui__WEBPACK_IMPORTED_MODULE_0__["ns"].rdf('type')) + .filter(ty => kb.holds(ty, solid_ui__WEBPACK_IMPORTED_MODULE_0__["ns"].rdfs('subClassOf'), classification)) + if (types.length !== 1) { + // const initialState = kb.any(tracker, ns.wf('initialState')) No do NOT default + // if (initialState) return initialState + throw new Error('Issue must have one type as state: ' + types.length) + } + return types[0] +} + +function renderIssueCard (issue, context) { + function getBackgroundColor () { + const classes = kb.each(issue, solid_ui__WEBPACK_IMPORTED_MODULE_0__["ns"].rdf('type')) // @@ pick cats in order then state + const catColors = classes.map(cat => kb.any(cat, solid_ui__WEBPACK_IMPORTED_MODULE_0__["ns"].ui('backgroundColor'))).filter(c => !!c) + + if (catColors.length) return catColors[0].value // pick first one + return null + } + function refresh () { + const backgroundColor = getBackgroundColor() || 'white' + card.style.backgroundColor = backgroundColor + editButton.style.backgroundColor = backgroundColor // Override white from style sheet + } + const dom = context.dom + const uncategorized = !getBackgroundColor() // This is a suspect issue. Prompt to delete it + + const card = dom.createElement('div') + const table = card.appendChild(dom.createElement('table')) + table.style.width = '100%' + const options = { draggable: false } // Let the baord make th ewhole card draggable + table.appendChild(solid_ui__WEBPACK_IMPORTED_MODULE_0__["widgets"].personTR(dom, null, issue, options)) + table.subject = issue + card.style = 'border-radius: 0.4em; border: 0.05em solid grey; margin: 0.3em;' + + const img = card.firstChild.firstChild.firstChild.firstChild // div/table/tr/td/img + img.setAttribute('src', solid_ui__WEBPACK_IMPORTED_MODULE_0__["icons"].iconBase + 'noun_Danger_1259514.svg') // override + // Add a button for viewing the whole issue in overlay + const buttonsCell = card.firstChild.firstChild.children[2] // right hand part of card + const editButton = solid_ui__WEBPACK_IMPORTED_MODULE_0__["widgets"].button(dom, solid_ui__WEBPACK_IMPORTED_MODULE_0__["icons"].iconBase + 'noun_253504.svg', 'edit', async _event => { + exposeOverlay(issue, context) + }) + const editButtonImage = editButton.firstChild + editButtonImage.style.width = editButtonImage.style.height = '1.5em' + buttonsCell.appendChild(editButton) + + // If uncategorized, shortcut to delete issue + if (uncategorized) { + const deleteButton = solid_ui__WEBPACK_IMPORTED_MODULE_0__["widgets"].deleteButtonWithCheck(dom, buttonsCell, 'issue', async function () { // noun? + try { + await kb.updater.update(kb.connectedStatements(issue)) + } catch (err) { + complain(`Unable to delete issue: ${err}`, context) + } + console.log('User deleted issue ' + issue) + card.parentNode.removeChild(card) // refresh doesn't work yet because it is not passed though tabs so short cut + solid_ui__WEBPACK_IMPORTED_MODULE_0__["widgets"].refreshTree(context.paneDiv) // Should delete the card if nec when tabs pass it though + // complain('DELETED OK', context) + }) + buttonsCell.appendChild(deleteButton) + } + card.style.maxWidth = '24em' // @@ User adjustable?? + card.refresh = refresh + refresh() + return card +} + +function exposeOverlay (subject, context) { + function hideOverlay () { + overlay.innerHTML = '' // clear overlay + overlay.style.visibility = 'hidden' + } + const overlay = context.overlay + overlay.innerHTML = '' // clear existing + const button = overlay.appendChild( + solid_ui__WEBPACK_IMPORTED_MODULE_0__["widgets"].button(context.dom, solid_ui__WEBPACK_IMPORTED_MODULE_0__["icons"].iconBase + 'noun_1180156.svg', 'close', hideOverlay)) + button.style.float = 'right' + button.style.margin = '0.7em' + delete button.style.backgroundColor // do not want white + overlay.style.visibility = 'visible' + overlay.appendChild(renderIssue(subject, context)) + overlay.firstChild.style.overflow = 'auto' // was scroll +} + +function renderIssue (issue, context) { + // Don't bother changing the last modified dates of things: save time + function setModifiedDate (subj, kb, doc) { + if (SET_MODIFIED_DATES) { + if (!getOption(tracker, 'trackLastModified')) return + let deletions = kb.statementsMatching(issue, solid_ui__WEBPACK_IMPORTED_MODULE_0__["ns"].dct('modified')) + deletions = deletions.concat( + kb.statementsMatching(issue, solid_ui__WEBPACK_IMPORTED_MODULE_0__["ns"].wf('modifiedBy')) + ) + const insertions = [$rdf.st(issue, solid_ui__WEBPACK_IMPORTED_MODULE_0__["ns"].dct('modified'), new Date(), doc)] + if (me) insertions.push($rdf.st(issue, solid_ui__WEBPACK_IMPORTED_MODULE_0__["ns"].wf('modifiedBy'), me, doc)) + kb.updater.update(deletions, insertions, function (_uri, _ok, _body) {}) + } + } + + function say (message, style) { + const pre = dom.createElement('pre') + pre.setAttribute('style', style || 'color: grey') + issueDiv.appendChild(pre) + pre.appendChild(dom.createTextNode(message)) + return pre + } + + const timestring = function () { + const now = new Date() + return '' + now.getTime() + // http://www.w3schools.com/jsref/jsref_obj_date.asp + } + + function complain (message) { + console.warn(message) + issueDiv.appendChild(solid_ui__WEBPACK_IMPORTED_MODULE_0__["widgets"].errorMessageBlock(dom, message)) + } + + function complainIfBad (ok, body) { + if (!ok) { + complain( + 'Sorry, failed to save your change:\n' + body, + 'background-color: pink;', context + ) + } + } + function getOption (tracker, option) { + // eg 'allowSubIssues' + const opt = kb.any(tracker, solid_ui__WEBPACK_IMPORTED_MODULE_0__["ns"].ui(option)) + return !!(opt && opt.value) + } + + function setPaneStyle () { + const types = kb.findTypeURIs(issue) + let mystyle = 'padding: 0.5em 1.5em 1em 1.5em; ' + let backgroundColor = null + for (const uri in types) { + backgroundColor = kb.any( + kb.sym(uri), + kb.sym('http://www.w3.org/ns/ui#backgroundColor') + ) + if (backgroundColor) break + } + backgroundColor = backgroundColor ? backgroundColor.value : '#eee' // default grey + mystyle += 'background-color: ' + backgroundColor + '; ' + issueDiv.setAttribute('style', mystyle) + } + + const dom = context.dom + const tracker = kb.the(issue, solid_ui__WEBPACK_IMPORTED_MODULE_0__["ns"].wf('tracker'), null, issue.doc()) + if (!tracker) throw new Error('No tracker') + const stateStore = kb.any(tracker, solid_ui__WEBPACK_IMPORTED_MODULE_0__["ns"].wf('stateStore')) + const store = issue.doc() + + const issueDiv = dom.createElement('div') + var me = solid_ui__WEBPACK_IMPORTED_MODULE_0__["authn"].currentUser() + + setPaneStyle() + + solid_ui__WEBPACK_IMPORTED_MODULE_0__["authn"].checkUser() // kick off async operation + + const states = kb.any(tracker, solid_ui__WEBPACK_IMPORTED_MODULE_0__["ns"].wf('issueClass')) + if (!states) { throw new Error('This tracker ' + tracker + ' has no issueClass') } + const select = solid_ui__WEBPACK_IMPORTED_MODULE_0__["widgets"].makeSelectForCategory( + dom, + kb, + issue, + states, + stateStore, + function (ok, body) { + if (ok) { + setModifiedDate(store, kb, store) + solid_ui__WEBPACK_IMPORTED_MODULE_0__["widgets"].refreshTree(issueDiv) + } else { + console.log('Failed to change state:\n' + body) + } + } + ) + issueDiv.appendChild(select) + + const cats = kb.each(tracker, solid_ui__WEBPACK_IMPORTED_MODULE_0__["ns"].wf('issueCategory')) // zero or more + for (let i = 0; i < cats.length; i++) { + issueDiv.appendChild( + solid_ui__WEBPACK_IMPORTED_MODULE_0__["widgets"].makeSelectForCategory( + dom, + kb, + issue, + cats[i], + stateStore, + function (ok, body) { + if (ok) { + setModifiedDate(store, kb, store) + solid_ui__WEBPACK_IMPORTED_MODULE_0__["widgets"].refreshTree(issueDiv) + } else { + console.log('Failed to change category:\n' + body) + } + } + ) + ) + } + + // For when issue is the main solo subject, include link to tracker itself. + const a = dom.createElement('a') + a.setAttribute('href', tracker.uri) + a.setAttribute('style', 'float:right') + issueDiv.appendChild(a).textContent = solid_ui__WEBPACK_IMPORTED_MODULE_0__["utils"].label(tracker) + a.addEventListener('click', solid_ui__WEBPACK_IMPORTED_MODULE_0__["widgets"].openHrefInOutlineMode, true) + + // Main Form for Title, description only + const coreIssueFormText = ` + @prefix : . + @prefix core: . + @prefix dc: . + @prefix wf: . + + core:coreIsueForm a :Form; + "Core issue data"; + :parts ( + core:titleField + core:descriptionField ) . + + core:descriptionField a :MultiLineTextField; + :label "Description"; + :property wf:description; + :size "40" . + + core:titleField a :SingleLineTextField; + :label "Title"; + :maxLength "128"; + :property dc:title; # @@ Should move to dct or schema + :size "40" . + + wf:Task :creationForm core:coreIsueForm . +` + const CORE_ISSUE_FORM = solid_ui__WEBPACK_IMPORTED_MODULE_0__["ns"].wf('coreIsueForm') + $rdf.parse(coreIssueFormText, kb, CORE_ISSUE_FORM.doc().uri, 'text/turtle') + solid_ui__WEBPACK_IMPORTED_MODULE_0__["widgets"].appendForm( + dom, + issueDiv, + {}, + issue, + CORE_ISSUE_FORM, + stateStore, + complainIfBad + ) + + // Descriptions can be long and are stored local to the issue + /* + issueDiv.appendChild( + widgets.makeDescription( + dom, + kb, + issue, + ns.wf('description'), + store, + function (ok, body) { + if (ok) setModifiedDate(store, kb, store) + else console.log('Failed to change description:\n' + body) + } + ) + ) */ + + // Assigned to whom? + + const assignments = kb.statementsMatching(issue, solid_ui__WEBPACK_IMPORTED_MODULE_0__["ns"].wf('assignee')) + if (assignments.length > 1) { + say('Weird, was assigned to more than one person. Fixing ..') + const deletions = assignments.slice(1) + kb.updater.update(deletions, [], function (uri, ok, body) { + if (ok) { + say('Now fixed.') + } else { + complain('Fixed failed: ' + body, context) + } + }) + } + + // Who could be assigned to this? + // Anyone assigned to any issue we know about + + async function getPossibleAssignees () { + let devs = [] + const devGroups = kb.each(issue, solid_ui__WEBPACK_IMPORTED_MODULE_0__["ns"].wf('assigneeGroup')) + for (let i = 0; i < devGroups.length; i++) { + const group = devGroups[i] + await kb.fetcher.load() + devs = devs.concat(kb.each(group, solid_ui__WEBPACK_IMPORTED_MODULE_0__["ns"].vcard('member'))) + } + // Anyone who is a developer of any project which uses this tracker + const proj = kb.any(null, solid_ui__WEBPACK_IMPORTED_MODULE_0__["ns"].doap('bug-database'), tracker) // What project? + if (proj) { + await kb.fetcher.load(proj) + devs = devs.concat(kb.each(proj, solid_ui__WEBPACK_IMPORTED_MODULE_0__["ns"].doap('developer'))) + } + return devs + } + + // Super issues first - like parent directories .. maybe use breadcrums from?? @@ + function renderSubIssue (issue) { + const options = { link: false } + return solid_ui__WEBPACK_IMPORTED_MODULE_0__["widgets"].personTR(dom, solid_ui__WEBPACK_IMPORTED_MODULE_0__["ns"].wf('dependent'), issue, options) + } + + getPossibleAssignees().then(devs => { + if (devs.length) { + devs.forEach(function (person) { + kb.fetcher.lookUpThing(person) + }) // best effort async for names etc + const opts = { + // 'mint': '** Add new person **', + nullLabel: '(unassigned)' + /* 'mintStatementsFun': function (newDev) { + var sts = [ $rdf.st(newDev, ns.rdf('type'), ns.foaf('Person')) ] + if (proj) sts.push($rdf.st(proj, ns.doap('developer'), newDev)) + return sts + } + */ + } + issueDiv.appendChild( + solid_ui__WEBPACK_IMPORTED_MODULE_0__["widgets"].makeSelectForOptions( + dom, + kb, + issue, + solid_ui__WEBPACK_IMPORTED_MODULE_0__["ns"].wf('assignee'), + devs, + opts, + store, + function (ok, body) { + if (ok) setModifiedDate(store, kb, store) + else console.log('Failed to change assignee:\n' + body) + } + ) + ) + } + }) + + /* The trees of super issues and subissues + */ + let subIssuePanel + if (getOption(tracker, 'allowSubIssues')) { + if (!subIssuePanel) { + subIssuePanel = issueDiv.appendChild(dom.createElement('div')) + subIssuePanel.style = 'margin: 1em; padding: 1em;' + } + + subIssuePanel.appendChild(dom.createElement('h4')).textContent = 'Super Issues' + const listOfSupers = subIssuePanel.appendChild(dom.createElement('div')) + listOfSupers.refresh = function () { + solid_ui__WEBPACK_IMPORTED_MODULE_0__["utils"].syncTableToArrayReOrdered(listOfSupers, kb.each(null, solid_ui__WEBPACK_IMPORTED_MODULE_0__["ns"].wf('dependent'), issue), renderSubIssue) + } + listOfSupers.refresh() + + // Sub issues + subIssuePanel.appendChild(dom.createElement('h4')).textContent = 'Sub Issues' + const listOfSubs = subIssuePanel.appendChild(dom.createElement('div')) + listOfSubs.refresh = function () { + solid_ui__WEBPACK_IMPORTED_MODULE_0__["utils"].syncTableToArrayReOrdered(listOfSubs, kb.each(issue, solid_ui__WEBPACK_IMPORTED_MODULE_0__["ns"].wf('dependent')), renderSubIssue) + } + listOfSubs.refresh() + + const b = dom.createElement('button') + b.setAttribute('type', 'button') + subIssuePanel.appendChild(b) + const classLabel = solid_ui__WEBPACK_IMPORTED_MODULE_0__["utils"].label(states) + b.innerHTML = 'New sub ' + classLabel + b.setAttribute('style', 'float: right; margin: 0.5em 1em;') + b.addEventListener( + 'click', + function (_event) { + subIssuePanel.insertBefore(Object(_newIssue__WEBPACK_IMPORTED_MODULE_1__["newIssueForm"])(dom, kb, tracker, issue, listOfSubs.refresh), b.nextSibling) // Pop form just after button + }, + false + ) + } + + issueDiv.appendChild(dom.createElement('br')) + + // Extras are stored centrally to the tracker + const extrasForm = kb.any(tracker, solid_ui__WEBPACK_IMPORTED_MODULE_0__["ns"].wf('extrasEntryForm')) + if (extrasForm) { + solid_ui__WEBPACK_IMPORTED_MODULE_0__["widgets"].appendForm( + dom, + issueDiv, + {}, + issue, + extrasForm, + stateStore, + complainIfBad + ) + } + + // Comment/discussion area + + const spacer = issueDiv.appendChild(dom.createElement('tr')) + spacer.setAttribute('style', 'height: 1em') // spacer and placeHolder + + const template = kb.anyValue(tracker, solid_ui__WEBPACK_IMPORTED_MODULE_0__["ns"].wf('issueURITemplate')) + /* + var chatDocURITemplate = kb.anyValue(tracker, ns.wf('chatDocURITemplate')) // relaive to issue + var chat + if (chatDocURITemplate) { + let template = $rdf.uri.join(chatDocURITemplate, issue.uri) // Template is relative to issue + chat = kb.sym(expandTemplate(template)) + } else + */ + let messageStore + if (template) { + messageStore = issue.doc() // for now. Could go deeper + } else { + messageStore = kb.any(tracker, solid_ui__WEBPACK_IMPORTED_MODULE_0__["ns"].wf('messageStore')) + if (!messageStore) messageStore = kb.any(tracker, solid_ui__WEBPACK_IMPORTED_MODULE_0__["ns"].wf('stateStore')) + kb.sym(messageStore.uri + '#' + 'Chat' + timestring()) // var chat = + } + + kb.fetcher.nowOrWhenFetched(messageStore, function (ok, body, _xhr) { + if (!ok) { + const er = dom.createElement('p') + er.textContent = body // @@ use nice error message + issueDiv.insertBefore(er, spacer) + } else { + const discussion = Object(solid_ui__WEBPACK_IMPORTED_MODULE_0__["messageArea"])(dom, kb, issue, messageStore) + issueDiv.insertBefore(discussion, spacer) + } + }) + + // Draggable attachment list + const attachmentHint = issueDiv.appendChild(dom.createElement('div')) + attachmentHint.innerHTML = `

Attachments

+

Drag files, emails, + web pages onto the paper clip, or click the file upload button.

` + let uploadFolderURI + if (issue.uri.endsWith('/index.ttl#this')) { // This has a whole folder to itself + uploadFolderURI = issue.uri.slice(0, 14) + 'Files/' // back to slash + } else { // like state.ttl#Iss1587852322438 + uploadFolderURI = issue.dir().uri + 'Files/' + issue.uri.split('#')[1] + '/' // New folder for issue in file with others + } + solid_ui__WEBPACK_IMPORTED_MODULE_0__["widgets"].attachmentList(dom, issue, issueDiv, { + doc: stateStore, + promptIcon: solid_ui__WEBPACK_IMPORTED_MODULE_0__["icons"].iconBase + 'noun_25830.svg', + uploadFolder: kb.sym(uploadFolderURI), // Allow local files to be uploaded + predicate: solid_ui__WEBPACK_IMPORTED_MODULE_0__["ns"].wf('attachment') + }) + + // Delete button to delete the issue + const deleteButton = solid_ui__WEBPACK_IMPORTED_MODULE_0__["widgets"].deleteButtonWithCheck(dom, issueDiv, 'issue', async function () { + try { + await kb.updater.update(kb.connectedStatements(issue)) + } catch (err) { + complain(`Unable to delete issue: ${err}`, context) + } + // @@ refreshTree + complain('DELETED OK', context) + issueDiv.style.backgroundColor = '#eee' + issueDiv.style.fontColor = 'orange' + }) + deleteButton.style.float = 'right' + + // Refresh button + const refreshButton = dom.createElement('button') + refreshButton.textContent = 'refresh messages' + refreshButton.addEventListener( + 'click', + async function (_event) { + try { + await kb.fetcher.load(messageStore, { force: true, clearPreviousData: true }) + } catch (err) { + alert(err) + return + } + solid_ui__WEBPACK_IMPORTED_MODULE_0__["widgets"].refreshTree(issueDiv) + }, + false + ) + refreshButton.setAttribute('style', solid_ui__WEBPACK_IMPORTED_MODULE_0__["style"].button) + issueDiv.appendChild(refreshButton) + return issueDiv +} // renderIssue + + +/***/ }), + +/***/ "./node_modules/issue-pane/issuePane.js": +/*!**********************************************!*\ + !*** ./node_modules/issue-pane/issuePane.js ***! + \**********************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var solid_ui__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! solid-ui */ "./node_modules/solid-ui/lib/index.js"); +/* harmony import */ var solid_ui__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(solid_ui__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _board__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./board */ "./node_modules/issue-pane/board.js"); +/* harmony import */ var _issue__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./issue */ "./node_modules/issue-pane/issue.js"); +/* harmony import */ var _newTracker__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./newTracker */ "./node_modules/issue-pane/newTracker.js"); +/* harmony import */ var _newIssue__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./newIssue */ "./node_modules/issue-pane/newIssue.js"); +/* harmony import */ var _trackerSettingsForm_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./trackerSettingsForm.js */ "./node_modules/issue-pane/trackerSettingsForm.js"); +/* Issue Tracker Pane + ** + ** This solid view allows a user to interact with an issue tracker, or individual issue, + ** to change its state according to an ontology, comment on it, etc. + ** + */ + + + // @@ will later be in solid-UI + + + + +// import { trackerInstancesFormText } from './trackerInstancesForm.js' + +const $rdf = solid_ui__WEBPACK_IMPORTED_MODULE_0__["rdf"] +const ns = solid_ui__WEBPACK_IMPORTED_MODULE_0__["ns"] +const kb = solid_ui__WEBPACK_IMPORTED_MODULE_0__["store"] +const widgets = solid_ui__WEBPACK_IMPORTED_MODULE_0__["widgets"] + +// const MY_TRACKERS_ICON = UI.icons.iconBase + 'noun_Document_998605.svg' +// const TRACKER_ICON = UI.icons.iconBase + 'noun_list_638112' +// const TASK_ICON = UI.icons.iconBase + 'noun_17020.svg' + +const OVERFLOW_STYLE = 'position: fixed; top: 1.51em; right: 2em; left: 2em; bottom:1.5em; border: 0.1em grey; overflow: scroll;' +/* harmony default export */ __webpack_exports__["default"] = ({ + icon: solid_ui__WEBPACK_IMPORTED_MODULE_0__["icons"].iconBase + 'noun_122196.svg', // was: js/panes/issue/tbl-bug-22.png + // noun_list_638112 is a checklist document + // noun_Document_998605.svg is a stack of twpo checklists + // noun_97839.svg is a ladybug + // noun_122196.svg is a clipboard with a check list on it + // noun_17020.svg is a single check box + name: 'issue', + + audience: [], // Anyone. was [ns.solid('PowerUser')] + + // Does the subject deserve an issue pane? + label: function (subject, _context) { + const t = kb.findTypeURIs(subject) + if ( + t['http://www.w3.org/2005/01/wf/flow#Task'] || + kb.holds(subject, solid_ui__WEBPACK_IMPORTED_MODULE_0__["ns"].wf('tracker')) + ) { return 'issue' } // in case ontology not available + if (t['http://www.w3.org/2005/01/wf/flow#Tracker']) return 'tracker' + // Later: Person. For a list of things assigned to them, + // open bugs on projects they are developer on, etc + return null // No under other circumstances (while testing at least!) + }, + + mintClass: ns.wf('Tracker'), + + mintNew: async function (context, options) { + /** Perform updates on more than one document @@ Move to rdflib! + */ + async function updateMany (deletions, insertions) { + const docs = deletions.concat(insertions).map(st => st.why) + const uniqueDocs = Array.from(new Set(docs)) + const updates = uniqueDocs.map(doc => + kb.updater.update(deletions.filter(st => st.why.sameTerm(doc)), + insertions.filter(st => st.why.sameTerm(doc)))) + return Promise.all(updates) + } + + var kb = context.session.store + const ns = solid_ui__WEBPACK_IMPORTED_MODULE_0__["ns"] + let stateStore + if (options.newInstance) { + stateStore = kb.sym(options.newInstance.doc().uri + '_state.ttl') + } else { + options.newInstance = kb.sym(options.newBase + 'index.ttl#this') + stateStore = kb.sym(options.newBase + 'state.ttl') + } + const tracker = options.newInstance + const appDoc = tracker.doc() + + const me = solid_ui__WEBPACK_IMPORTED_MODULE_0__["authn"].currentUser() + if (me) { + kb.add(tracker, ns.dc('author'), me, appDoc) + } + + kb.add(tracker, ns.rdf('type'), ns.wf('Tracker'), appDoc) + kb.add(tracker, ns.dc('created'), new Date(), appDoc) + + // @@ to do --- adk user what sort of tracker they want + + kb.add(tracker, ns.wf('issueClass'), ns.wf('Task'), appDoc) // @@ ask user + kb.add(tracker, ns.wf('initialState'), ns.wf('Open'), appDoc) + kb.add(tracker, ns.wf('stateStore'), stateStore, appDoc) + kb.add(tracker, ns.wf('assigneeClass'), ns.foaf('Person'), appDoc) // @@ set to people in the meeting? + + kb.add(tracker, ns.wf('stateStore'), stateStore, stateStore) // Back Link + + const ins = kb.statementsMatching(undefined, undefined, undefined, appDoc).concat(kb.statementsMatching(undefined, undefined, undefined, stateStore)) + try { + await updateMany([], ins) + } catch (err) { + return solid_ui__WEBPACK_IMPORTED_MODULE_0__["widgets"].complain(context, 'Error writing tracker configuration: ' + err) + } + /* + try { + await kb.updater.updateMany([], kb.statementsMatching(undefined, undefined, undefined, stateStore)) + } catch (err) { + return UI.widgets.complain(context, 'Error writing tracker state file: ' + err) + } +*/ + const dom = context.dom + const div = options.div + + const notice = div.appendChild(dom.createElement('div')) + notice.innerHTML = `

Success

+

Your new tracker has been made. + Use the settings tab to configure it. +

+ ` + // console.log('New tracker created ' + tracker) + // alert('New tracker created') + return options + }, + + render: function (subject, context) { + const dom = context.dom + + const paneDiv = dom.createElement('div') + context.paneDiv = paneDiv + paneDiv.setAttribute('class', 'issuePane') + + function complain (message) { + console.warn(message) + paneDiv.appendChild(solid_ui__WEBPACK_IMPORTED_MODULE_0__["widgets"].errorMessageBlock(dom, message)) + } + + function complainIfBad (ok, message) { + if (!ok) { + complain(message) + } + } + + /** Infer subclass from disjoint Union + ** + ** This is would not be needed if our quey language + ** allowed is to query ardf Collection membership. + */ + async function fixSubClasses (kb, tracker) { + async function checkOneSuperclass (klass) { + const collection = kb.any(klass, ns.owl('disjointUnionOf'), null, doc) + if (!collection) throw new Error(`Classification ${klass} has no disjointUnionOf`) + if (!collection.elements) throw new Error(`Classification ${klass} has no array`) + const needed = new Set(collection.elements.map(x => x.uri)) + const existing = new Set(kb.each(null, ns.rdfs('subClassOf'), klass, doc) + .map(x => x.uri)) + for (const sub of existing) { + if (!needed.has(sub)) { + deletables.push($rdf.st(kb.sym(sub), ns.rdfs('subClassOf'), klass, doc)) + } + } + for (const sub of needed) { + if (!existing.has(sub)) { + insertables.push($rdf.st(kb.sym(sub), ns.rdfs('subClassOf'), klass, doc)) + } + } + } + const doc = tracker.doc() + const states = kb.any(tracker, ns.wf('issueClass')) + const cats = kb.each(tracker, ns.wf('issueCategory')) + var insertables = [] + var deletables = [] + cats.push(states) + for (const klass of cats) { + await checkOneSuperclass(klass) + } + const damage = insertables.length + deletables.length + if (damage) { + alert(`Internal error: s${damage} subclasses inconsistences!`) + /* + if (confirm(`Fix ${damage} inconsistent subclasses in tracker config?`)) { + await kb.updater.update(deletables, insertables) + */ + } + } + + /** /////////////////////////// Board + */ + function renderBoard (tracker, klass) { + const states = kb.any(tracker, ns.wf('issueClass')) + klass = klass || states // default to states + const doingStates = klass.sameTerm(states) + + // These are states we will show by default: the open issues. + const stateArray = kb.any(klass, ns.owl('disjointUnionOf')) + if (!stateArray) { + return complain(`Configuration error: state ${states} does not have substates`) + } + let columnValues = stateArray.elements + if (doingStates && columnValues.length > 2 // and there are more than two + ) { // strip out closed states + columnValues = columnValues.filter(state => kb.holds(state, ns.rdfs('subClassOf'), ns.wf('Open')) || state.sameTerm(ns.wf('Open'))) + } + + async function columnDropHandler (issue, newState) { + const currentState = Object(_issue__WEBPACK_IMPORTED_MODULE_2__["getState"])(issue, klass) + const tracker = kb.the(issue, ns.wf('tracker'), null, issue.doc()) + const stateStore = kb.any(tracker, ns.wf('stateStore')) + + if (newState.sameTerm(currentState)) { + // alert('Same state ' + UI.utils.label(currentState)) // @@ remove + return + } + try { + await kb.updater.update( + [$rdf.st(issue, ns.rdf('type'), currentState, stateStore)], + [$rdf.st(issue, ns.rdf('type'), newState, stateStore)]) + } catch (err) { + solid_ui__WEBPACK_IMPORTED_MODULE_0__["widgets"].complain(context, 'Unable to change issue state: ' + err) + } + boardDiv.refresh() // reorganize board to match the new reality + } + + function isOpen (issue) { + const types = kb.findTypeURIs(issue) + return !!types[ns.wf('Open').uri] + } + + const options = { columnDropHandler, filter: doingStates ? null : isOpen } + options.sortBy = ns.dct('created') + options.sortReverse = true + function localRenderIssueCard (issue) { + return Object(_issue__WEBPACK_IMPORTED_MODULE_2__["renderIssueCard"])(issue, context) + } + // const columnValues = states // @@ optionally selected states would work + const boardDiv = Object(_board__WEBPACK_IMPORTED_MODULE_1__["board"])(dom, columnValues, localRenderIssueCard, options) + return boardDiv + } + + /** ////////////// Table + */ + function tableRefreshButton (stateStore, tableDiv) { + const refreshButton = widgets.button(dom, solid_ui__WEBPACK_IMPORTED_MODULE_0__["icons"].iconBase + 'noun_479395.svg', + 'refresh table', async _event => { + try { + await kb.fetcher.load(stateStore, { force: true, clearPreviousData: true }) + } catch (err) { + alert(err) + return + } + solid_ui__WEBPACK_IMPORTED_MODULE_0__["widgets"].refreshTree(tableDiv) + }) + return refreshButton + } + + function renderTable (tracker) { + function newOptionalClause () { + const clause = new $rdf.IndexedFormula() + query.pat.optional.push(clause) + return clause + } + const states = kb.any(subject, ns.wf('issueClass')) + const cats = kb.each(tracker, ns.wf('issueCategory')) // zero or more + const vars = ['issue', 'state', 'created'] + var query = new $rdf.Query(solid_ui__WEBPACK_IMPORTED_MODULE_0__["utils"].label(subject)) + for (let i = 0; i < cats.length; i++) { + vars.push('_cat_' + i) + } + const v = {} // The RDF variable objects for each variable name + vars.forEach(function (x) { + query.vars.push((v[x] = $rdf.variable(x))) + }) + query.pat.add(v.issue, ns.wf('tracker'), tracker) + // query.pat.add(v['issue'], ns.dc('title'), v['title']) + query.pat.add(v.issue, ns.dct('created'), v.created) + query.pat.add(v.issue, ns.rdf('type'), v.state) + query.pat.add(v.state, ns.rdfs('subClassOf'), states) + + query.pat.optional = [] + + for (let i = 0; i < cats.length; i++) { + const clause = newOptionalClause() + clause.add(v.issue, ns.rdf('type'), v['_cat_' + i]) + clause.add(v['_cat_' + i], ns.rdfs('subClassOf'), cats[i]) + } + + const propertyList = kb.any(tracker, ns.wf('propertyList')) // List of extra properties + if (propertyList) { + const properties = propertyList.elements + for (let p = 0; p < properties.length; p++) { + const prop = properties[p] + let vname = '_prop_' + p + if (prop.uri.indexOf('#') >= 0) { + vname = prop.uri.split('#')[1] + } + const oneOpt = newOptionalClause() + query.vars.push((v[vname] = $rdf.variable(vname))) + oneOpt.add(v.issue, prop, v[vname]) + } + } + + const selectedStates = {} + const possible = kb.each(undefined, ns.rdfs('subClassOf'), states) + possible.forEach(function (s) { + if ( + kb.holds(s, ns.rdfs('subClassOf'), ns.wf('Open')) || + s.sameTerm(ns.wf('Open')) + ) { + selectedStates[s.uri] = true + // console.log('on '+s.uri); // @@ + } + }) + + function exposeThisOverlay (href) { + const subject = $rdf.sym(href) + Object(_issue__WEBPACK_IMPORTED_MODULE_2__["exposeOverlay"])(subject, context) + } + + const tableDiv = solid_ui__WEBPACK_IMPORTED_MODULE_0__["table"](dom, { + query: query, + keyVariable: '?issue', // Charactersic of row + sortBy: '?created', // By default, sort by date + sortReverse: true, // most recent at the top + hints: { + '?issue': { linkFunction: exposeThisOverlay, label: 'Title' }, + '?created': { cellFormat: 'shortDate' }, + '?state': { initialSelection: selectedStates, label: 'Status' } + } + }) + const stateStore = kb.any(subject, ns.wf('stateStore')) + tableDiv.appendChild(tableRefreshButton(stateStore, tableDiv)) + return tableDiv + } + + // Allow user to create new things within the folder + function renderCreationControl (refreshTarget) { + const creationDiv = dom.createElement('div') + const me = solid_ui__WEBPACK_IMPORTED_MODULE_0__["authn"].currentUser() + const creationContext = { + // folder: subject, + div: creationDiv, + dom: dom, + noun: 'tracker', + statusArea: creationDiv, + me: me, + refreshTarget: refreshTarget + } + const issuePane = context.session.paneRegistry.byName('issue') + const relevantPanes = [issuePane] + solid_ui__WEBPACK_IMPORTED_MODULE_0__["create"].newThingUI(creationContext, context, relevantPanes) // Have to pass panes down newUI + return creationDiv + } + + function renderInstances (theClass) { + const instancesDiv = dom.createElement('div') + const context = { dom, div: instancesDiv, noun: 'tracker' } + solid_ui__WEBPACK_IMPORTED_MODULE_0__["authn"].registrationList(context, { public: true, private: true, type: theClass }).then(_context2 => { + instancesDiv.appendChild(renderCreationControl(instancesDiv)) + /* // keep this code in case we need a form + const InstancesForm = ns.wf('TrackerInstancesForm') + const text = trackerInstancesFormText + $rdf.parse(text, kb, InstancesForm.doc().uri, 'text/turtle') + widgets.appendForm(dom, instancesDiv, {}, tracker, InstancesForm, + tracker.doc(), complainIfBad) + */ + }) + return instancesDiv + } + function renderSettings (tracker) { + const settingsDiv = dom.createElement('div') + // A registration control allows the to record this tracker in their type index + const context = { dom, div: settingsDiv, noun: 'tracker' } + solid_ui__WEBPACK_IMPORTED_MODULE_0__["authn"].registrationControl(context, tracker, ns.wf('Tracker')).then(_context2 => { + const settingsForm = ns.wf('TrackerSettingsForm') + const text = _trackerSettingsForm_js__WEBPACK_IMPORTED_MODULE_5__["trackerSettingsFormText"] + $rdf.parse(text, kb, settingsForm.doc().uri, 'text/turtle') + widgets.appendForm(dom, settingsDiv, {}, tracker, settingsForm, + tracker.doc(), complainIfBad) + }) + return settingsDiv + } + + function renderTabsTableAndBoard () { + function renderMain (ele, object) { + ele.innerHTML = '' // Clear out "loading message" + if (object.sameTerm(boardView)) { + ele.appendChild(renderBoard(tracker)) + } else if (object.sameTerm(tableView)) { + ele.appendChild(renderTable(tracker)) + } else if (object.sameTerm(settingsView)) { + ele.appendChild(renderSettings(tracker)) + } else if (object.sameTerm(instancesView)) { + ele.appendChild(renderInstances(ns.wf('Tracker'))) + } else if ((kb.holds(tracker, ns.wf('issueCategory'), object)) || + (kb.holds(tracker, ns.wf('issueClass'), object))) { + ele.appendChild(renderBoard(tracker, object)) + } else { + throw new Error('Unexpected tab type: ' + object) + } + } + const states = kb.any(tracker, ns.wf('issueClass')) + const items = [instancesView, tableView, states] + .concat(kb.each(tracker, ns.wf('issueCategory'))) + items.push(settingsView) + const selectedTab = tableView + const options = { renderMain, items, selectedTab } + + // Add stuff to the ontologies which we believe but they don't say + const doc = instancesView.doc() + kb.add(instancesView, ns.rdfs('label'), 'My Trackers', doc) // @@ squatting on wf ns + kb.add(settingsView, ns.rdfs('label'), 'Settings', doc) // @@ squatting on wf ns + kb.add(states, ns.rdfs('label'), 'By State', doc) // @@ squatting on wf ns + + const tabs = solid_ui__WEBPACK_IMPORTED_MODULE_0__["tabs"].tabWidget(options) + return tabs + } + + async function renderTracker () { + function showNewIssue (issue) { + solid_ui__WEBPACK_IMPORTED_MODULE_0__["widgets"].refreshTree(paneDiv) + Object(_issue__WEBPACK_IMPORTED_MODULE_2__["exposeOverlay"])(issue, context) + b.disabled = false // https://stackoverflow.com/questions/41176582/enable-disable-a-button-in-pure-javascript + } + tracker = subject + + try { + await fixSubClasses(kb, tracker) + } catch (err) { + console.log('@@@ Error fixing subclasses in config: ' + err) + } + + const states = kb.any(subject, ns.wf('issueClass')) + if (!states) throw new Error('This tracker has no issueClass') + const stateStore = kb.any(subject, ns.wf('stateStore')) + if (!stateStore) throw new Error('This tracker has no stateStore') + + solid_ui__WEBPACK_IMPORTED_MODULE_0__["authn"].checkUser() // kick off async operation + + const h = dom.createElement('h2') + h.setAttribute('style', 'font-size: 150%') + paneDiv.appendChild(h) + const classLabel = solid_ui__WEBPACK_IMPORTED_MODULE_0__["utils"].label(states) + h.appendChild(dom.createTextNode(classLabel + ' list')) // Use class label @@I18n + + // New Issue button + var b = dom.createElement('button') + const container = dom.createElement('div') + b.setAttribute('type', 'button') + b.setAttribute('style', 'padding: 0.3em; font-size: 100%; margin: 0.5em;') + container.appendChild(b) + paneDiv.appendChild(container) + const img = dom.createElement('img') + img.setAttribute('src', solid_ui__WEBPACK_IMPORTED_MODULE_0__["icons"].iconBase + 'noun_19460_green.svg') + img.setAttribute('style', 'width: 1em; height: 1em; margin: 0.2em;') + b.appendChild(img) + const span = dom.createElement('span') + span.innerHTML = 'New ' + classLabel + b.appendChild(span) + b.addEventListener( + 'click', + function (_event) { + b.disabled = true + container.appendChild(Object(_newIssue__WEBPACK_IMPORTED_MODULE_4__["newIssueForm"])(dom, kb, tracker, null, showNewIssue)) + }, + false + ) + + // Table of issues - when we have the main issue list + // We also need the ontology loaded + // + context.session.store.fetcher + .load([stateStore]) + .then(function (_xhrs) { + const tableDiv = renderTabsTableAndBoard(tracker) + // const tableDiv = renderTable(tracker) // was + paneDiv.appendChild(tableDiv) + + if (tableDiv.refresh) { + // Refresh function + } else { + console.log('No table refresh function?!') + } + paneDiv.appendChild(Object(_newTracker__WEBPACK_IMPORTED_MODULE_3__["newTrackerButton"])(subject)) + updater.addDownstreamChangeListener(stateStore, tableDiv.refresh) // Live update + }) + .catch(function (err) { + return console.log('Cannot load state store: ' + err) + }) + // end of Tracker instance + } // render tracker + + /* Render tabs with both views + */ + const boardView = ns.wf('BoardView') + const tableView = ns.wf('TableView') + const settingsView = ns.wf('SettingsView') + const instancesView = ns.wf('InstancesView') + + const updater = kb.updater + const t = kb.findTypeURIs(subject) + let tracker + + // Whatever we are rendering, lets load the ontology + const flowOntology = solid_ui__WEBPACK_IMPORTED_MODULE_0__["ns"].wf('').doc() + if (!kb.holds(undefined, undefined, undefined, flowOntology)) { + // If not loaded already + $rdf.parse(__webpack_require__(/*! ./wf.js */ "./node_modules/issue-pane/wf.js"), kb, flowOntology.uri, 'text/turtle') // Load ontology directly + } + const userInterfaceOntology = solid_ui__WEBPACK_IMPORTED_MODULE_0__["ns"].ui('').doc() + if (!kb.holds(undefined, undefined, undefined, userInterfaceOntology)) { + // If not loaded already + $rdf.parse(__webpack_require__(/*! ./ui.js */ "./node_modules/issue-pane/ui.js"), kb, userInterfaceOntology.uri, 'text/turtle') // Load ontology directly + } + + // Render a single issue + if ( + t['http://www.w3.org/2005/01/wf/flow#Task'] || + kb.holds(subject, solid_ui__WEBPACK_IMPORTED_MODULE_0__["ns"].wf('tracker')) + ) { + tracker = kb.any(subject, ns.wf('tracker')) + if (!tracker) throw new Error('This issue ' + subject + 'has no tracker') + + // Much data is in the tracker instance, so wait for the data from it + + context.session.store.fetcher + .load(tracker.doc()) + .then(function (_xhrs) { + const stateStore = kb.any(tracker, ns.wf('stateStore')) + context.session.store.fetcher.nowOrWhenFetched( + stateStore, + subject, + function drawIssuePane2 (ok, body) { + if (!ok) { + return console.log( + 'Failed to load state ' + stateStore + ' ' + body + ) + } + paneDiv.appendChild(Object(_issue__WEBPACK_IMPORTED_MODULE_2__["renderIssue"])(subject, context)) + updater.addDownstreamChangeListener(stateStore, function () { + solid_ui__WEBPACK_IMPORTED_MODULE_0__["widgets"].refreshTree(paneDiv) + }) // Live update + } + ) + }) + .catch(err => { + const msg = 'Failed to load config ' + tracker.doc() + ' ' + err + return complain(msg) + }) + context.session.store.fetcher.nowOrWhenFetched( + tracker.doc(), + subject, + function drawIssuePane1 (ok, body) { + if (!ok) { + return console.log( + 'Failed to load config ' + tracker.doc() + ' ' + body + ) + } + } + ) // End nowOrWhenFetched tracker + + // ///////////////////////////////////////////////////////// + // + // Render a Tracker instance + // + } else if (t['http://www.w3.org/2005/01/wf/flow#Tracker']) { + renderTracker().then(() => console.log('Tracker rendered')) + } else { + console.log( + 'Error: Issue pane: No evidence that ' + + subject + + ' is either a bug or a tracker.' + ) + } + + let loginOutButton + const overlay = paneDiv.appendChild(dom.createElement('div')) + context.overlay = overlay + overlay.style = OVERFLOW_STYLE + overlay.style.visibility = 'hidden' + + // var overlayPane = null // overlay.appendChild(dom.createElement('div')) // avoid stomping on style by pane + + solid_ui__WEBPACK_IMPORTED_MODULE_0__["authn"].checkUser().then(webId => { + if (webId) { + console.log('Web ID set already: ' + webId) + context.me = webId + // @@ enable things + return + } + + loginOutButton = solid_ui__WEBPACK_IMPORTED_MODULE_0__["authn"].loginStatusBox(dom, webIdUri => { + if (webIdUri) { + context.me = kb.sym(webIdUri) + console.log('Web ID set from login button: ' + webIdUri) + paneDiv.removeChild(loginOutButton) + // enable things + } else { + context.me = null + } + }) + + loginOutButton.setAttribute('style', 'margin: 0.5em 1em;') + paneDiv.appendChild(loginOutButton) + if (!context.statusArea) { + context.statusArea = paneDiv.appendChild(dom.createElement('div')) + } + }) + + return paneDiv + } +}); + +// ends + + +/***/ }), + +/***/ "./node_modules/issue-pane/newIssue.js": +/*!*********************************************!*\ + !*** ./node_modules/issue-pane/newIssue.js ***! + \*********************************************/ +/*! exports provided: newIssueForm */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "newIssueForm", function() { return newIssueForm; }); +/* harmony import */ var solid_ui__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! solid-ui */ "./node_modules/solid-ui/lib/index.js"); +/* harmony import */ var solid_ui__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(solid_ui__WEBPACK_IMPORTED_MODULE_0__); +// Form to collect data about a New Issue +// + + +const $rdf = solid_ui__WEBPACK_IMPORTED_MODULE_0__["rdf"] +const ns = solid_ui__WEBPACK_IMPORTED_MODULE_0__["ns"] + +function newIssueForm (dom, kb, tracker, superIssue, showNewIssue) { + const form = dom.createElement('div') // form is broken as HTML behaviour can resurface on js error + const stateStore = kb.any(tracker, ns.wf('stateStore')) + + const timestring = function () { + const now = new Date() + return '' + now.getTime() + // http://www.w3schools.com/jsref/jsref_obj_date.asp + } + + const sendNewIssue = function () { + titlefield.setAttribute('class', 'pendingedit') + titlefield.disabled = true + const sts = [] + let issue + + const expandTemplate = function (template) { + const now = new $rdf.Literal(new Date()) + const nnnn = '' + new Date().getTime() + const YYYY = now.value.slice(0, 4) + const MM = now.value.slice(5, 7) + const DD = now.value.slice(8, 10) + return template + .replace('{N}', nnnn) + .replace('{YYYY}', YYYY) + .replace('{MM}', MM) + .replace('{DD}', DD) + } + // Where to store the new issue? + let template = kb.anyValue(tracker, ns.wf('issueURITemplate')) + let issueDoc + if (template) { + // Does each issue do in its own file? + template = $rdf.uri.join(template, stateStore.uri) // Template is relative + issue = kb.sym(expandTemplate(template)) + } else { + issue = kb.sym(stateStore.uri + '#' + 'Iss' + timestring()) + } + // eslint-disable-next-line prefer-const + issueDoc = issue.doc() + + // Basic 9 core predicates are stored in the main stateStore + + const title = kb.literal(titlefield.value) + sts.push(new $rdf.Statement(issue, ns.wf('tracker'), tracker, stateStore)) + sts.push(new $rdf.Statement(issue, ns.dc('title'), title, stateStore)) + sts.push( + new $rdf.Statement(issue, ns.dct('created'), new Date(), stateStore) + ) + const initialStates = kb.each(tracker, ns.wf('initialState')) + if (initialStates.length === 0) { console.log('This tracker has no initialState') } + for (let i = 0; i < initialStates.length; i++) { + sts.push( + new $rdf.Statement( + issue, + ns.rdf('type'), + initialStates[i], + stateStore + ) + ) + } + if (superIssue) { + sts.push( + new $rdf.Statement(superIssue, ns.wf('dependent'), issue, stateStore) + ) + } + + // Other things are stores in the individual + if (template) { + sts.push(new $rdf.Statement(issue, ns.wf('tracker'), tracker, issueDoc)) + sts.push( + new $rdf.Statement(issue, ns.rdfs('seeAlso'), stateStore, issueDoc) + ) + } + + const sendComplete = function (uri, success, body) { + if (!success) { + console.log("Error: can't save new issue:" + body) + } else { + form.parentNode.removeChild(form) + showNewIssue(issue) + } + } + kb.updater.update([], sts, sendComplete) + } + + const states = kb.any(tracker, ns.wf('issueClass')) + const classLabel = solid_ui__WEBPACK_IMPORTED_MODULE_0__["utils"].label(states) + form.innerHTML = + '

Add new ' + + (superIssue ? 'sub ' : '') + + classLabel + + '

Title of new ' + + classLabel + + ':

' + var titlefield = dom.createElement('input') + titlefield.setAttribute('type', 'text') + titlefield.setAttribute( + 'style', + 'margin: 0.5em; font-size: 100%; padding: 0.3em;' + ) + titlefield.setAttribute('size', '100') + titlefield.setAttribute('maxLength', '2048') // No arbitrary limits + titlefield.select() // focus next user input + titlefield.addEventListener( + 'keyup', + function (e) { + if (e.keyCode === 13) { + sendNewIssue() + } + }, + false + ) + form.appendChild(titlefield) + return form +} + + +/***/ }), + +/***/ "./node_modules/issue-pane/newTracker.js": +/*!***********************************************!*\ + !*** ./node_modules/issue-pane/newTracker.js ***! + \***********************************************/ +/*! exports provided: newTrackerButton */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "newTrackerButton", function() { return newTrackerButton; }); +/* harmony import */ var solid_ui__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! solid-ui */ "./node_modules/solid-ui/lib/index.js"); +/* harmony import */ var solid_ui__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(solid_ui__WEBPACK_IMPORTED_MODULE_0__); + + +const $rdf = solid_ui__WEBPACK_IMPORTED_MODULE_0__["rdf"] +const ns = solid_ui__WEBPACK_IMPORTED_MODULE_0__["ns"] +const kb = solid_ui__WEBPACK_IMPORTED_MODULE_0__["store"] +const updater = kb.updater + +/* Button for making a whole new tracker +** This is the least tesetd part of the tracker system at the moment. +*/ +function newTrackerButton (thisTracker, context) { + function timestring () { + const now = new Date() + return '' + now.getTime() + // http://www.w3schools.com/jsref/jsref_obj_date.asp + } + + // const dom = context.dom + const button = solid_ui__WEBPACK_IMPORTED_MODULE_0__["authn"].newAppInstance(context.dom, { noun: 'tracker' }, function ( + ws, + base + ) { + const appPathSegment = 'issuetracker.w3.org' // how to allocate this string and connect to + // console.log("Ready to make new instance at "+ws) + const sp = solid_ui__WEBPACK_IMPORTED_MODULE_0__["ns"].space + const kb = context.session.store + + if (!base) { + base = kb.any(ws, sp('uriPrefix')).value + if (base.slice(-1) !== '/') { + $rdf.log.error( + appPathSegment + ': No / at end of uriPrefix ' + base + ) + base = base + '/' + } + base += appPathSegment + '/' + timestring() + '/' // unique id + if (!confirm('Make new tracker at ' + base + '?')) { + return + } + } + + const stateStore = kb.any(thisTracker, ns.wf('stateStore')) + const newStore = kb.sym(base + 'store.ttl') + + const here = thisTracker.doc() + + const oldBase = here.uri.slice(0, here.uri.lastIndexOf('/') + 1) + + var morph = function (x) { + // Move any URIs in this space into that space + if (x.elements !== undefined) return x.elements.map(morph) // Morph within lists + if (x.uri === undefined) return x + let u = x.uri + if (u === stateStore.uri) return newStore // special case + if (u.slice(0, oldBase.length) === oldBase) { + u = base + u.slice(oldBase.length) + $rdf.log.debug(' Map ' + x.uri + ' to ' + u) + } + return kb.sym(u) + } + const there = morph(here) + const newTracker = morph(thisTracker) + + const myConfig = kb.statementsMatching( + undefined, + undefined, + undefined, + here + ) + for (let i = 0; i < myConfig.length; i++) { + const st = myConfig[i] + kb.add( + morph(st.subject), + morph(st.predicate), + morph(st.object), + there + ) + } + + // Keep a paper trail @@ Revisit when we have non-public ones @@ Privacy + // + kb.add(newTracker, solid_ui__WEBPACK_IMPORTED_MODULE_0__["ns"].space('inspiration'), thisTracker, stateStore) + + kb.add(newTracker, solid_ui__WEBPACK_IMPORTED_MODULE_0__["ns"].space('inspiration'), thisTracker, there) + + // $rdf.log.debug("\n Ready to put " + kb.statementsMatching(undefined, undefined, undefined, there)); //@@ + + updater.put( + there, + kb.statementsMatching(undefined, undefined, undefined, there), + 'text/turtle', + function (uri2, ok, message) { + if (ok) { + updater.put(newStore, [], 'text/turtle', function ( + uri3, + ok, + message + ) { + if (ok) { + console.info( + 'Ok The tracker created OK at: ' + + newTracker.uri + + '\nMake a note of it, bookmark it. ' + ) + } else { + console.log( + 'FAILED to set up new store at: ' + + newStore.uri + + ' : ' + + message + ) + } + }) + } else { + console.log( + 'FAILED to save new tracker at: ' + there.uri + ' : ' + message + ) + } + } + ) + + // Created new data files. + // @@ Now create initial files - html skin, (Copy of mashlib, css?) + // @@ Now create form to edit configuation parameters + // @@ Optionally link new instance to list of instances -- both ways? and to child/parent? + // @@ Set up access control for new config and store. + }) // callback to newAppInstance + + button.setAttribute('style', 'margin: 0.5em 1em;') + return button +} // newTrackerButton + + +/***/ }), + +/***/ "./node_modules/issue-pane/trackerSettingsForm.js": +/*!********************************************************!*\ + !*** ./node_modules/issue-pane/trackerSettingsForm.js ***! + \********************************************************/ +/*! exports provided: trackerSettingsFormText */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "trackerSettingsFormText", function() { return trackerSettingsFormText; }); +const trackerSettingsFormText = ` +@prefix : . +@prefix core: . +@prefix dct: . +@prefix owl: . +@prefix rdfs: . +@prefix ui: . +@prefix vcard: . +@prefix wf: . + + core:TrackerSettingsForm a :Form; + "Tracker Configuration Form"; + :parts ( + + [ a ui:Heading; ui:contents "About the tracker"@en ] + + [ a :SingleLineTextField; + :label "Title of issue tracker"; + :maxLength "128"; + :property dct:title; + :size "40" ] + + [ a :MultiLineTextField; :label "Description"; :property wf:description; :size "40" ] + + [ a ui:Choice; ui:canMintNew true; ui:use core:SuperClassForm; ui:follow true; + ui:property wf:issueClass; + ui:label "What states can an issue be in?"; + ui:from rdfs:Class; + ui:default wf:Task ] + + [ a ui:Comment; ui:contents """You can optionally sort issues using (one or more) classification systems"""@en ] + + + [ a ui:Choice; ui:canMintNew true; ui:use core:ClassificationForm; + ui:property wf:issueCategory; ui:label "Sort them into which category?"; ui:from rdfs:Class ] + + [ a :BooleanField; + :label "Allow issues to have sub-issues"; + :property wf:allowSubIssues; + :default false ] + + [ a ui:Heading; ui:contents "Table view:"@en ] + + [ a ui:Comment; ui:contents "Any extra properties to include?"@en ] + + + [a ui:Multiple; ui:property wf:propertyList; ui:ordered true; ui:part core:PropertyForm; ui:follow true ] + + [ a ui:Heading; ui:contents "Details of issues"@en ] + + # Use a people picker ideally + [ a ui:Choice; ui:canMintNew true; ui:use core:GroupForm; + ui:property wf:assigneeGroup; + ui:label "Assign issues to people from which group?"; + ui:from vcard:Group; + ] + + # Optionally one form for extras + + [ a ui:Choice; ui:canMintNew true; ui:use ui:FormForm; + ui:property wf:extrasEntryForm; + ui:label "Other things to save about each issue?"; + ui:from ui:Form; + ] + + + ) . + + # Form for the superclass of all states + # @@ also We must require each state class to be stated to be a subclass of EITHER Open OR Closed. + core:SuperClassForm a ui:Form; dct:title "Form for managing states"; + ui:parts ( + [ a :SingleLineTextField; + :label "Name of set of states"; + :defualt "States"; + :maxLength "128"; + :property rdfs:label; + :size "40" ] + [a ui:Multiple; ui:property owl:disjointUnionOf; ui:ordered true; ui:part core:StateForm ] + # [ a ui:Multiple; ui:property rdfs:subClassOf; ui:reverse true; ui:part core:StateForm ] + ) . + + core:StateForm a ui:Form; dct:title "Form for one state"; + ui:parts ( + [ a :SingleLineTextField; + :label "Name of state"; + :maxLength "128"; + :property rdfs:label; + :size "40" ] + [ a :ColorField; :label "Background color"; :property :backgroundColor ] + # @@ add icon for state + + ). + + + # Form for Classification + + core:ClassificationForm a ui:Form; dct:title "Form for a classification by categpry"; + ui:parts ( + [ a :SingleLineTextField; + :label "Name of classification:"; + :maxLength "128"; + :property rdfs:label; + :size "40" ] + [a ui:Multiple; ui:property owl:disjointUnionOf; ui:ordered true; ui:part core:CategoryForm ] + ) . + + core:CategoryForm a ui:Form; dct:title "Form for a category"; + ui:parts ( + [ a :SingleLineTextField; + :label "Name of category"; + :maxLength "128"; + :property rdfs:label; + :size "40" ] + [ a :ColorField; :label "Background color"; :property :backgroundColor ] + + ). + + core:PropertyForm a ui:Form; ui:parts ( # Internded for raed only only marking the + [ a :SingleLineTextField; + :label "(property name)"; + :maxLength "128"; + :property rdfs:label; + :size "40" ] + ). + + + # Other ontology stuff we are otherwis missing + + # we can usde ui:label to give a decent abel when the ontology uses a really bad one + rdfs:subClassOf ui:label "super class" . + # We can also add a specific nice label for the inverse + [] owl:inverse rdfs:subClassOf; rdfs:label "sub class" . + owl:disjointUnionOf ui:label "option" . + + # Form for new group + + + core:GroupForm a ui:Form; dct:title "Form for new contacts group"; ui:parts ( + [ a :SingleLineTextField; + :label "Name of new group"; + :maxLength "128"; + :property vcard:fn; + :size "60" ] + + [ a ui:Heading; ui:contents "Members of group"@en ] + + [ a ui:Multiple; ui:label "contacts in group"; ui:property vcard:member; ui:part core:PersonForm ] + + ). + + core:PersonForm a ui:Form; dct:title "New contact details form"; ui:parts ( + + [ a :NamedNodeURIField; ui:label "Solid ID"; ui:property owl:sameAs; ui:size 60 ] + + [ a :SingleLineTextField; + :label "Name of contact"; + :maxLength "128"; + :property vcard:fn; + :size "60" ] + + [ a ui:PhoneField; :label "Phone"; :property vcard:phone; ] # @@ check property] + + [ a :EmailField; :label "Email"; :property vcard:email ] # @@ check property + + ). + +# classificattion owl:disjointUnionOf () + wf:Tracker :creationForm core:SettingsForm . +` + + +/***/ }), + +/***/ "./node_modules/issue-pane/ui.js": +/*!***************************************!*\ + !*** ./node_modules/issue-pane/ui.js ***! + \***************************************/ +/*! no static exports found */ +/***/ (function(module, exports) { + +module.exports = ` +# Ontology for user interface hints and forms +# +# See also related: the Fresnel language +# +@prefix contact: . +@prefix dc: . +@prefix doc: . +@prefix foaf: . +@prefix owl: . +@prefix r: . +@prefix s: . +@prefix tt: . +@prefix ui: . +@prefix : . +@prefix wf: . +@prefix xsd: . + +@keywords is, of, a. + +<> dc:title "An ontology for User Interface description, Hints and Forms."; + dc:description """The User Interface ontology allows the definition + of forms for processing RDF model data, and include a bootstrap form for + editing forms. It allows user interface hints such as background colors, + can be associated with objects and classes. + """; + dc:created 2010-08-07; + dc:license ; + dc:modified """$Date: 2020/03/22 16:53:21 $"""; + dc:author . + +style a r:Property, owl:DatatypeProperty; + s:label "style"; + prompt "CSS style"; + s:comment """Must be a valid CSS style string such as one could put in + an HTML style attribute. Depending on the user interface system, this can + by given to individuals, classes or properties. It is up to a user interface + which wants to draw on them to pick how it uses styles from which parts + of the data it has. For example, the style of a class may be picked + to distinguish information about things in that class.""". + +backgroundColor a r:Property, owl:DatatypeProperty; + s:label "background color"@en; + s:range ui:Color; + s:comment """Must be a valid CSS color string such as one could put in + an HTML style attribute. This should be in the #xxxxxx form, + (with 6 digits of hex) so that it + can work with Graphviz.""". + +backgroundImage a r:Property, owl:DatatypeProperty; + s:label "background image"@en; + s:comment """URI or base64 representation of an image""". + +color a r:Property, owl:DatatypeProperty; + s:label "color"@en; + s:range ui:Color; + s:comment """Must be a valid CSS color string such as one could put in + an HTML style attribute. This should be in the #xxxxxx form, + (with 6 digits of hex) so that it + can work with Graphviz.""". + + + +sortPriority a r:Property, owl:DatatypeProperty; + s:label "sort priority"; + s:range xsd:integer; + s:comment """When individuals or classes must be sorted, then + if they are given different values of sortPriority a user agent can + use this as a hint to how to present information.""". + +sortBy a r:Property; + s:label "sort by"; + s:domain s:Class; + s:range r:Property; + s:comment """A property which typically is used to sort + members of a given class.""". + +seqeunce a r:Property; + s:label "sequence number"; + s:range xsd:integer; + s:comment """The sequence in which this item is arranged with repect to other parts.""". + +initialProperties a r:Property; + s:label "initial properties"; + s:domain s:Class; + s:range r:List; # List of r:Property + s:comment """A really simple way of enabling user interfaces to + create new information about a class of things is to make a define of properties + to be specified when a information about a new item + ("New item" here means an item which the system + does not have prvious information about yet, + not an items which has just been created, + like new friend as opposed to new baby)"""; + prompt "Properties to be specified for new ones". + +tableProperties a r:Property; + s:domain s:Class; + s:label "table properties"; + s:range r:List; # List of r:Property + s:comment """This is a crude way of specifying a table-based + view for objects of this class."""; + prompt "Properties to be given in a default table view". + +prompt a r:Property; + s:label "user prompt"; + s:comment """A string for the UI to use if the user needs a longer + prompts than just a field name, the rdfs:label. """; + ui:prompt "A longer prompt for a user inputting this property". + + +# A Taxonomy of Field types + +ui:Form owl:disjointUnionOf ( ui:ValueField ui:Group ui:Choice ui:Classifier ui:Options ui:Multiple ui:Heading ui:Comment); + s:comment """A form can be any type of single field, or typically a Group of several fields, + including interspersed headings and comments. """. +ui:Single owl:disjointUnionOf ( ui:ValueField ui:Group ui:Choice ui:Classifier ui:Options ui:Heading ui:Comment). +ui:ValueField owl:disjointUnionOf ( ui:TextField ui:NumericField ui:ColorField ui:DateField ui:DateTimeField ui:PhoneField ui:EmailField). +ui:NumericField owl:disjointUnionOf (ui:BooleanField ui:TriStateField ui:IntegerField ui:DecimalField ui:FloatField). +# ui:Multiple owl:disjointUnionOf ( ui:ZeroOrMore ui:OneOrMore ). +ui:TextField owl:disjointUnionOf (ui:SingleLineTextField ui:MultiLineTextField). + +ui:Form a s:Class; is s:subClassOf of ui:ValueField, ui:Group, ui:Choice, ui:Heading, ui:Comment, ui:Classifier, ui:Options, ui:Multiple. +ui:Single a s:Class; is s:subClassOf of ui:ValueField, ui:Group, ui:Choice, ui:Heading, ui:Comment, ui:Classifier, ui:Options. +ui:ValueField a s:Class; is s:subClassOf of ui:TextField, ui:NumericField, ui:ColorField, ui:DateField, ui:DateTimeField, ui:PhoneField, ui:EmailField. +ui:NumericField a s:Class; is s:subClassOf of ui:BooleanField, ui:TriStateField, ui:IntegerField, ui:DecimalField, ui:FloatField. +ui:TextField a s:Class; is s:subClassOf of ui:SingleLineTextField, ui:MultiLineTextField. + +ui:Classifier a s:Class; s:label "classifier"; + s:comment """A classifier allows the user to select the type of an object. + The possible types must be subclasses of some overall class, the "category". + (Ideally, the superclass is also set up as the disjoint union of the subclasses, + if they are disjoint.) + + The form normally stores the resulting classes using an rdf:type triple, + but a different predicate can be used if required, so the classifier field + needs is 'property' defined too. + + If the subclass selected itself is has subclasses defined, the user can + recursively select from them in turn, as many levels as needed.""". + +ui:property a r:Property; s:domain ui:Form; s:range r:Property; + s:label "property to be stored"@en; + s:comment """Many fields prompt for information about a given property of the subject. + When field is filled in, this gives which property is written into the data.""". + +ui:category a r:Property; s:domain ui:Classifier; s:range s:Class; + s:label "overall superclass"@en; + s:comment """The superclass subclasses of which will be selected.""". + +ui:dependingOn a r:Property; s:domain ui:Options; s:range r:Property; + s:label "depending on"@en; + s:comment """Many fields prompt for information about a given property of the subject""". + +ui:for a r:Property; s:label "for"@en; s:comment "The value for which this case is selected.". +ui:use a r:Property; s:range ui:Form. + +ui:part a r:Property; s:label "part"@en ; s:domain ui:Form; s:range ui:Form. # Used for Multiple field - the subform for each item +ui:parts a r:Property; s:label "parts"@en ; s:domain ui:Form; s:range r:Collection. # (of Forms) The ordered set of fields in a group +ui:ordered e r:Property; s:label "ordered"; s:range xsd:Boolean . # Could be useful for all kinds of things in future so not restricted to Multiple + +ui:from a r:Property; s:domain ui:Choice; s:range r:Class; + s:label "from"; ui:prompt "from what class". + +ui:size a r:Property; s:domain ui:ValueField; s:range xsd:integer; + s:label "size of field"; + ui:prompt "size of field in characters". + +ui:maxLength a r:Property; s:domain ui:TextField; s:range xsd:integer; + s:label "max length of value". + +ui:minValue a r:Property; s:domain ui:ValueField; s:label "min". # @@ range? +ui:maxValue a r:Property; s:domain ui:ValueField; s:label "max". + + ui:creationForm a r:Property; s:domain s:Class; s:range ui:Form; + s:label "creation form"; + s:comment """A form which may be used to collect information about a + hitherto locally undocumented instance instance of this class.""". + + ui:annotationForm a r:Property; s:domain s:Class; s:range ui:Form; + s:label "annotation form"; + s:comment """A form which may be used to add more infromation to an +instance of this class which we know something about. Anything from +adding just add one more fact, to adding a whole lot of information about a specific +facet of the thing. +""". + + +############################################# +# +# Form for editing Forms +# + +FormForm a ui:Form; + dc:title "Form for editing Forms"; + is ui:creationForm of Form; + a ui:Group; ui:parts (FF1 FF2 FF3 FieldList) . + + FF1 ui:sequence 1; a ui:Heading; ui:contents "Edit Form"@en . + FF2 ui:sequence 2; a ui:SingleLineTextField; ui:property dc:title; ui:size 60 . + FF3 ui:sequence 3; a ui:Comment; ui:contents + """To add a field to the form, press the plus at the bottom, + and then select what sort of field you want."""@en; ui:style "background-color: #ffe;" . + + FieldList ui:sequence 10; a ui:Multiple; ui:ordered true; ui:property ui:parts; ui:part FieldForm . + +FieldForm a ui:Group; + dc:title "Form for selecting a type of field"; + ui:parts ( + + [ ui:sequence 1; a ui:Classifier; ui:property r:type; ui:category ui:Form] + + [ a ui:Options; ui:sequence 2; ui:dependingOn r:type; + + ui:case [ ui:for ui:TextField; ui:use [a ui:Group; ui:parts ( + [ a ui:Choice; ui:canMintNew true; ui:property ui:property; ui:label "property"; ui:from owl:DatatypeProperty] # @@@ Needs inference on current web + [ a ui:IntegerField; ui:property ui:size; ui:label "field size"; ui:min 1; ui:max 4096] + [ a ui:IntegerField; ui:property ui:maxLength; ui:label "Max. length of string"; ui:min 1] + )]]; + + ui:case [ ui:for ui:IntegerField; ui:use [a ui:Group; ui:parts ( + [ ui:sequence 1; a ui:Choice; ui:canMintNew true; ui:property ui:property; ui:label "property"; ui:from owl:DatatypeProperty] + [ ui:sequence 2; a ui:IntegerField; ui:property ui:min; ui:label "minimum value"] + [ ui:sequence 3; a ui:IntegerField; ui:property ui:max; ui:label "maximum value"] ) ]]; + + ui:case [ ui:for ui:DecimalField; ui:use [a ui:Group; ui:parts ( + [ ui:sequence 1; a ui:Choice; ui:canMintNew true; ui:property ui:property; ui:label "property"; ui:from owl:DatatypeProperty] + [ ui:sequence 2; a ui:DecimalField; ui:property ui:min; ui:label "minimum value"] + [ ui:sequence 3; a ui:DecimalField; ui:property ui:max; ui:label "maximum value"] ) ]]; + + ui:case [ ui:for ui:FloatField; ui:use [a ui:Group; ui:parts ( + [ ui:sequence 1; a ui:Choice; ui:canMintNew true; ui:property ui:property; ui:label "property"; ui:from owl:DatatypeProperty] + [ ui:sequence 2; a ui:FloatField; ui:property ui:min; ui:label "minimum value"] + [ ui:sequence 3; a ui:FloatField; ui:property ui:max; ui:label "maximum value"] ) ]]; + + ui:case [ ui:for ui:ColorField; ui:use [a ui:Group; ui:parts ( + [ ui:sequence 1; a ui:Choice; ui:canMintNew true; ui:property ui:property; ui:label "property"; ui:from owl:DatatypeProperty] ) + ]]; + + ui:case [ ui:for ui:DateField; ui:use [a ui:Group; ui:parts ( + [ ui:sequence 1; a ui:Choice; ui:canMintNew true; ui:property ui:property; ui:label "property"; ui:from owl:DatatypeProperty] + [ ui:sequence 2; a ui:DateField; ui:property ui:min; ui:label "min"] + [ ui:sequence 3; a ui:DateField; ui:property ui:max ; ui:label "max"] + ) ]]; + + ui:case [ ui:for ui:DateTimeField; ui:use [a ui:Group; ui:parts ( + [ ui:sequence 1; a ui:Choice; ui:canMintNew true; ui:property ui:property; ui:label "property"; ui:from owl:DatatypeProperty] + [ ui:sequence 2; a ui:DateTimeField; ui:property ui:min; ui:label "min"] + [ ui:sequence 3; a ui:DateTimeField; ui:property ui:max ; ui:label "max"] + ) ]]; + + ui:case [ ui:for ui:EmailField; ui:use [a ui:Group; ui:parts ( + [ ui:sequence 1; a ui:Choice; ui:canMintNew true; ui:property ui:property; ui:label "property"; ui:from owl:ObjectProperty] + ) ]]; + + ui:case [ ui:for ui:PhoneField; ui:use [a ui:Group; ui:parts ( + [ ui:sequence 1; a ui:Choice; ui:canMintNew true; ui:property ui:property; ui:label "property"; ui:from owl:ObjectProperty] + )]]; + + ui:case [ ui:for ui:Group; ui:use FieldList]; + + ui:case [ ui:for ui:Options; ui:use [a ui:Group; ui:parts ( + [ ui:sequence 1; a ui:Choice; ui:canMintNew true; ui:property ui:dependingOn; ui:label "depending on"; ui:from r:Property; ui:default r:type] + [ ui:sequence 2; a ui:Multiple; ui:property ui:case; ui:part CaseForm] + ) ]]; + + ui:case [ ui:for ui:Choice; ui:use [a ui:Group; ui:parts ( + [ ui:sequence 1; a ui:Choice; ui:canMintNew true; ui:property ui:property; ui:label "property"; + ui:canMintNew true; ui:from owl:ObjectProperty] + [ ui:sequence 2; a ui:Choice; ui:canMintNew true; ui:property ui:from; ui:label "destination class"; + ui:from s:Class; ui:canMintNew true; ] + [ ui:sequence 3; a ui:BooleanField; ui:property ui:canMintNew; # No class form yet + ui:label "user can add new"] + [ ui:sequence 4; a ui:Choice; ui:canMintNew true; ui:property ui:use; ui:label "Nested Form (if any)"; + ui:from ui:Form; ui:optional true; ui:use FormForm] # @@ optional + + ) ]]; + + ui:case [ ui:for ui:Classifier; ui:use [a ui:Group; ui:parts ( + [ ui:sequence 2; a ui:Comment; ui:contents """A classifier allows the user to which classes the item belongs to, given a common superclass of the allowed classes. Give the superclass here:""" ] + + [ ui:sequence 4; a ui:Choice; ui:canMintNew true; ui:property ui:category; ui:label "superclass"; ui:from s:Class] + + [ ui:sequence 6; a ui:Comment; ui:contents """(When the choice is made normally the item is given a rdf:type. Set this to rdf:type unless you want the form to set a different property.)""" ] + + [ ui:sequence 8; a ui:Choice; ui:canMintNew true; ui:property ui:property; + ui:label "property"; ui:from owl:ObjectProperty; ui:default r:type] # @@ restriction + + ) ]]; + + ui:case [ ui:for ui:Multiple; ui:use [a ui:Group; ui:parts ( + [ui:sequence 0; a ui:BooleanField; ui:property ui:ordered; ui:label "ordered"] # If this an ordered array or an unordered set? + [ui:sequence 0; a ui:IntegerField; ui:property ui:min; ui:label "minimum number"] # If this an ordered array or an unordered set? + [ui:sequence 1; a ui:Choice; ui:canMintNew true; ui:property ui:property; ui:label "property"; ui:from r:Property] + [ui:sequence 2; a ui:Choice; ui:canMintNew true; ui:property ui:part; ui:from ui:Form; ui:use FieldForm] # Form for details of the field part of the multiple + ) ]]; + + ui:case [ ui:for ui:Heading; ui:use [a ui:SingleLineTextField; ui:property ui:contents]]; + + ui:case [ ui:for ui:Comment; ui:use [a ui:MultiLineTextField; ui:property ui:contents]] + ]). + + +CaseForm a ui:Group; + dc:title "Form for a conditional case in a form"; + ui:parts ( + [ ui:sequence 1; a ui:Choice; ui:canMintNew true; ui:property ui:for; ui:label "when it is"; ui:canMintNew true; ui:from s:Class] + [ui:sequence 2; a ui:Choice; ui:canMintNew true; ui:property ui:use; ui:from ui:Form; ui:canMintNew true; ui:use FieldForm] ). # Form for details of the field part of the multiple + +# ENDS +` + + +/***/ }), + +/***/ "./node_modules/issue-pane/wf.js": +/*!***************************************!*\ + !*** ./node_modules/issue-pane/wf.js ***! + \***************************************/ +/*! no static exports found */ +/***/ (function(module, exports) { + +module.exports = ` +# Issue tracking - Workflow application definition ontology +# +# Finite state automaton ontology +# +# See requirements for tracking tools http://www.w3.org/2005/01/06-tool-req.html +# +@keywords a, is, of. + +@prefix : . +@prefix wf: . + +@prefix rdf: . +@prefix s: . +@prefix owl: . +@prefix xsd: . + +@prefix doc: . +@prefix log: . +@prefix foaf: . +@prefix contact: . +@prefix doap: . +@prefix dc: . +@prefix dct: . +@prefix ui: . + +<> dc:title "Issue Tracking Ontology"; + + dct:creator ; + + s:comment """This ontology defines a very general class (Task) + which can used for any kind of bug tracking, issue tracking, + to-do-list management, action items, goal dependency, and so on. + It captures the state of a task as a subclass, so that + subsumption can be used. + It captures a discussion thread about a task. + It captures subtasks structure if necessary. + A "Tracker" defines actual set of states, categories, etc., + which a task can be in. The data about the tracker + guides the software managing the task. + + There is some workflow modeling finite state machine + terms which are optional for more complex definition + of the transitions allowed. + """. + +Task a s:Class; + s:label "task"@en; owl:disjointUnionOf (Open Closed); + s:comment """Something to be done in a wide sense, + an agenda item at a meeting is one example, but any + issue, task, action item, goal, product, deliverable, milestone, can such a thing. + The requirement for this framework was that it would allow + one to customize ontologies for things such as agenda items, + action items, working group issues with a spec, w3c Last Call issues, + software bugs and administrative requests. + In π-calculus, a process. + Make your type of issue a subclass of Task. + """. + +Open a s:Class; s:subClassOf Task; + s:label "open"@en, "ouvert"@fr; + ui:backgroundColor "#d6f5d6"; # green like github for some reason + s:comment """A task which needs attention. The very crude states of Open and Closed all + interoperability between different systems if the states for a given + application are made subclasses of either Open or Closed. This allows + tasks from different systems to be mixed and treated together with + limited but valuable functionality. + """. + +Closed a s:Class; s:subClassOf Task; + s:label "closed"@en, "fermé"@fr; + ui:backgroundColor "#f5d6d6"; # pink + s:comment """A task which does not need attention. It may be closed because + has been abandoned or completed, for example. + """. + + + ActionItem a s:Class; + s:subClassOf Task; + s:label "action item"@en; owl:disjointUnionOf (Open Closed); + s:comment """An obligation taken on by a person, typically at a meeting. + """. + + +description a rdf:Property; + s:label "description"; + s:comment """The description, definition, + or abstract. Information explaining what this is. + Not arbitrary comment about anything, only about the subject. + (Use this property for anything. There is no domain restriction.).""". + +dependent a rdf:Property; + s:label "how"; owl:inverseOf [ s:label "why"]; + s:domain Task; s:range Task; + s:comment """Another task upon which this depends, in the sense that + this task cannot be completed without that task being done. + You can't use this for dependencies on anything other than other tasks. + (Note the US spelling of the URI. In the UK, a dependant is a something + which is dependent on somehing else.)""". + +assignee a rdf:Property; + s:label "assigned to"; owl:inverseOf [s:label "assignment"]; +# s:domain Task; + s:range foaf:Agent; + s:comment """The person or group to whom this has been assigned.""". + +# use dct:modified +#modified a rdf:Property; +# s:label "last changed". + +modifiedBy a rdf:Property; + s:range foaf:Agent; + s:label "changed by". + +# use dct:created instead +#created a rdf:Property; +# s:range xsd:dateTime; +# +# Use foaf:maker instead +#creator a rdf:Property; +# s:range foaf:Agent; +# s:label "changed by". + +subscriber a rdf:Property; + s:label "subscriber"; + s:range foaf:Agent. + + +################## Products +# +# +# History: The Tracker system included a cocept of a product, +# such that an action could be associated with *either* an issue *or* a product. +# Noah Mendelsohn for the TAG needed to be able make +# and to give products: Goals, scuuess criteria, +# deliverables with dates, schedules, TAG members assigned, related issues. +# + + +Product a s:Class; s:subClassOf Task; + s:label "product"; + s:comment """A product is a task which monitors something + which must be produced.""". + +deliverable a rdf:Property; s:subPropertyOf dependent; + s:range Product; + s:label "deliverable"@en; + s:comment """Something which must be delivered to accomplish this""". + +goalDescription a rdf:Property, owl:DatatypeProperty; + s:domain Task; s:range xsd:string; + s:label "goals"; + s:comment """A textual description of the goals of this product, etc.""". + +successCriteria a rdf:Property, owl:DatatypeProperty; + s:domain Task; s:range xsd:string; + s:label "success criteria"; + s:comment """A textual description of the successs critera. + How when we know this is done?""". + +dateDue a rdf:Property, owl:DatatypeProperty; + s:domain Task; s:range xsd:date; + s:label "due"@en; + s:comment """The date this task is due. + """. + +################## Attachments + +attachment a rdf:Property; + s:label "attachment"; + s:comment """Something related is attached for information.""". + +screenShot a rdf:Property; s:subPropertyOf attachment; + s:label "screen shot"@en; + s:comment """An image taken by capturing the state of a + computer screen, for example to demonstrate a problem""". + +testData a rdf:Property; s:subPropertyOf attachment; + s:label "test data"@en; + s:comment """A file which can be used as inpiut to a test + or to demonstrate a problem. """. + + +terminalOutput a rdf:Property; s:subPropertyOf attachment; + s:label "terminal output"@en; + s:comment """A file showing user interaction from a + text terminal or console etc. """. + + +message a rdf:Property; s:subPropertyOf attachment; + s:label "message"@en; + s:comment """A message about this. Attached for information.""". + + +Message a s:Class; s:label "message"@en. +recipent a rdf:Property; s:label "to"; s:domain Message; s:range foaf:Agent. +sender a rdf:Property; s:label "from"; s:domain Message; s:range foaf:Agent. + +############################# A Tracker connects and manages issues + +tracker a rdf:Property; + s:label "tracker"; + owl:inverseOf [ s:label "issue"]; + s:domain Task; + s:range Tracker. + +Tracker a s:Class; + s:label "tracker"; + s:comment """A set of issues and + the constraints on how they evolve. + To use this ontology, craete a new tracker. + Copy an existing one or make up your own.""". + +issueClass a rdf:Property; + s:label "all issues must be in"; + s:domain Tracker; + s:range s:Class, State; + s:comment """The class of issues which are allowed in this tracker. + This is essemtial to the operation of the tracker, + as it defines which states an issue can be in. + (The issueClass must be a disjointUnionOf the state classes)""". + +issueCategory a rdf:Property; + s:label "issue category"; + s:domain Tracker; + s:range s:Class; + s:comment """Issues may be categorized according to the + subclasses of this class""". + +stateStore a rdf:Property; + s:label "state store"; + s:domain Tracker; + s:range doc:Document; + s:comment """A read-write document. + The state of the issues is modified here. + When you set up a trcaker, thgis must be set to point + to a writeble data resource on the web.""". + +transactionStore + a rdf:Property; + s:label "transaction store"; + s:domain Tracker; + s:range doc:Document; + s:comment """An appendable document. Transactions and messsages + can be written into here""". + +asigneeClass + a rdf:Property; + s:label "assignees must be"; + s:domain Tracker; + s:range s:Class; # Subclass of foaf:Agent + s:comment """When an issue is assigned, the assignee must be from this class""". + +initialState + a rdf:Property; + s:label "initial state"@en; + s:label "état initial"@fr; + s:domain Tracker; + s:range State; + s:comment """The initial state for a new issue""". + +# Use this to link a project to a tracker +doap:bug-database owl:inverseOf [ s:label "project"@en ]. + + + + +############################################################ +# +# Finite state machines +# +Change a s:Class; + s:label "change"; + s:comment """The universal class of things which +change the state of a task. +Included now: Creation, Transition. (Maybe in the future +more π-calculus constructions such as splitting & merging tasks, +and import/export of obligations to a foreign opaque system.) +""". + +Transition a s:Class; s:subClassOf Change; + s:label "transition"; + s:comment """A transition is a change of state of +a task. Typical properties include date and/or source +(a document causing the transition), and a final state.""". + +Creation a s:Class; s:subClassOf Change; + s:label "creation"; + s:comment """A creation is a change from existence +to non-existence +a task. Typical properties include date and/or source +(a document causing the transition), and a final state.""". + + +date s:range DateTime. + +final a rdf:Property; + s:label "to"; + s:domain Transition; + s:range State. + +task a rdf:Property; + s:range Task; + s:label "task". + +requires a rdf:Property; + s:label "requires"; + s:domain Transition; + s:range rdf:List; # Of properties for validation + s:comment """To be a valid transition, + a necessary (but not necessarily sufficuent) condition + is that there be recorded these properties for the record""". + +affects a rdf:Property; + s:label "affects"; + s:domain doc:Work; + s:range Task. + + +# { ?x a Transition; task ?t; source ?doc } => { ?doc affects ?t }. + + +creates a rdf:Property; + s:label "creates"; + s:domain doc:Work; + s:range Task. + + +allowedTransitions a rdf:Property; + s:domain State; + s:range rdf:List; # @@@ of Action + s:label "allowed transitions"; + s:comment """The state machine is defined + by these lists of transition allowed for each issue. + (An interesting option in the Web is to make an allowed transition + to a state in soemone else's ontology, which in turn allows + transitions into many ontologies. So a finite state maxchine + may become very large. In practice this means that a task handed + off to another organization may be processed on all kinds of ways.)""". + +# { ?x a TerminalState} => { ?x allowedTransitions () }. + +final a rdf:Property; + s:label "to"; + s:range State. + +issue a rdf:Property; + s:label "issue"; + s:comment + """A transition changes the state of the given issue.""". + +source a rdf:Property; + s:label "source"; + s:comment """The source of a transition is + the document by which it happened"""; + s:range doc:Work. +TerminalState a s:Class; + s:subClassOf State; + s:label "terminal state"; + s:comment """A state from which there are no transitions.""". + +NonTerminalState a s:Class; + s:label "non-terminal state"; + owl:disjointWith TerminalState; + s:comment """A state from which there are transitions.""". + +###################################################### + +#ends +` + + +/***/ }), + +/***/ "./node_modules/jsonld/lib/ContextResolver.js": +/*!****************************************************!*\ + !*** ./node_modules/jsonld/lib/ContextResolver.js ***! + \****************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* + * Copyright (c) 2019 Digital Bazaar, Inc. All rights reserved. + */ + + +const { + isArray: _isArray, + isObject: _isObject, + isString: _isString, +} = __webpack_require__(/*! ./types */ "./node_modules/jsonld/lib/types.js"); +const { + asArray: _asArray +} = __webpack_require__(/*! ./util */ "./node_modules/jsonld/lib/util.js"); +const {prependBase} = __webpack_require__(/*! ./url */ "./node_modules/jsonld/lib/url.js"); +const JsonLdError = __webpack_require__(/*! ./JsonLdError */ "./node_modules/jsonld/lib/JsonLdError.js"); +const ResolvedContext = __webpack_require__(/*! ./ResolvedContext */ "./node_modules/jsonld/lib/ResolvedContext.js"); + +const MAX_CONTEXT_URLS = 10; + +module.exports = class ContextResolver { + /** + * Creates a ContextResolver. + * + * @param sharedCache a shared LRU cache with `get` and `set` APIs. + */ + constructor({sharedCache}) { + this.perOpCache = new Map(); + this.sharedCache = sharedCache; + } + + async resolve({ + activeCtx, context, documentLoader, base, cycles = new Set() + }) { + // process `@context` + if(context && _isObject(context) && context['@context']) { + context = context['@context']; + } + + // context is one or more contexts + context = _asArray(context); + + // resolve each context in the array + const allResolved = []; + for(const ctx of context) { + if(_isString(ctx)) { + // see if `ctx` has been resolved before... + let resolved = this._get(ctx); + if(!resolved) { + // not resolved yet, resolve + resolved = await this._resolveRemoteContext( + {activeCtx, url: ctx, documentLoader, base, cycles}); + } + + // add to output and continue + if(_isArray(resolved)) { + allResolved.push(...resolved); + } else { + allResolved.push(resolved); + } + continue; + } + if(ctx === null) { + // handle `null` context, nothing to cache + allResolved.push(new ResolvedContext({document: null})); + continue; + } + if(!_isObject(ctx)) { + _throwInvalidLocalContext(context); + } + // context is an object, get/create `ResolvedContext` for it + const key = JSON.stringify(ctx); + let resolved = this._get(key); + if(!resolved) { + // create a new static `ResolvedContext` and cache it + resolved = new ResolvedContext({document: ctx}); + this._cacheResolvedContext({key, resolved, tag: 'static'}); + } + allResolved.push(resolved); + } + + return allResolved; + } + + _get(key) { + // get key from per operation cache; no `tag` is used with this cache so + // any retrieved context will always be the same during a single operation + let resolved = this.perOpCache.get(key); + if(!resolved) { + // see if the shared cache has a `static` entry for this URL + const tagMap = this.sharedCache.get(key); + if(tagMap) { + resolved = tagMap.get('static'); + if(resolved) { + this.perOpCache.set(key, resolved); + } + } + } + return resolved; + } + + _cacheResolvedContext({key, resolved, tag}) { + this.perOpCache.set(key, resolved); + if(tag !== undefined) { + let tagMap = this.sharedCache.get(key); + if(!tagMap) { + tagMap = new Map(); + this.sharedCache.set(key, tagMap); + } + tagMap.set(tag, resolved); + } + return resolved; + } + + async _resolveRemoteContext({activeCtx, url, documentLoader, base, cycles}) { + // resolve relative URL and fetch context + url = prependBase(base, url); + const {context, remoteDoc} = await this._fetchContext( + {activeCtx, url, documentLoader, cycles}); + + // update base according to remote document and resolve any relative URLs + base = remoteDoc.documentUrl || url; + _resolveContextUrls({context, base}); + + // resolve, cache, and return context + const resolved = await this.resolve( + {activeCtx, context, documentLoader, base, cycles}); + this._cacheResolvedContext({key: url, resolved, tag: remoteDoc.tag}); + return resolved; + } + + async _fetchContext({activeCtx, url, documentLoader, cycles}) { + // check for max context URLs fetched during a resolve operation + if(cycles.size > MAX_CONTEXT_URLS) { + throw new JsonLdError( + 'Maximum number of @context URLs exceeded.', + 'jsonld.ContextUrlError', + { + code: activeCtx.processingMode === 'json-ld-1.0' ? + 'loading remote context failed' : + 'context overflow', + max: MAX_CONTEXT_URLS + }); + } + + // check for context URL cycle + // shortcut to avoid extra work that would eventually hit the max above + if(cycles.has(url)) { + throw new JsonLdError( + 'Cyclical @context URLs detected.', + 'jsonld.ContextUrlError', + { + code: activeCtx.processingMode === 'json-ld-1.0' ? + 'recursive context inclusion' : + 'context overflow', + url + }); + } + + // track cycles + cycles.add(url); + + let context; + let remoteDoc; + + try { + remoteDoc = await documentLoader(url); + context = remoteDoc.document || null; + // parse string context as JSON + if(_isString(context)) { + context = JSON.parse(context); + } + } catch(e) { + throw new JsonLdError( + 'Dereferencing a URL did not result in a valid JSON-LD object. ' + + 'Possible causes are an inaccessible URL perhaps due to ' + + 'a same-origin policy (ensure the server uses CORS if you are ' + + 'using client-side JavaScript), too many redirects, a ' + + 'non-JSON response, or more than one HTTP Link Header was ' + + 'provided for a remote context.', + 'jsonld.InvalidUrl', + {code: 'loading remote context failed', url, cause: e}); + } + + // ensure ctx is an object + if(!_isObject(context)) { + throw new JsonLdError( + 'Dereferencing a URL did not result in a JSON object. The ' + + 'response was valid JSON, but it was not a JSON object.', + 'jsonld.InvalidUrl', {code: 'invalid remote context', url}); + } + + // use empty context if no @context key is present + if(!('@context' in context)) { + context = {'@context': {}}; + } else { + context = {'@context': context['@context']}; + } + + // append @context URL to context if given + if(remoteDoc.contextUrl) { + if(!_isArray(context['@context'])) { + context['@context'] = [context['@context']]; + } + context['@context'].push(remoteDoc.contextUrl); + } + + return {context, remoteDoc}; + } +}; + +function _throwInvalidLocalContext(ctx) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; @context must be an object.', + 'jsonld.SyntaxError', { + code: 'invalid local context', context: ctx + }); +} + +/** + * Resolve all relative `@context` URLs in the given context by inline + * replacing them with absolute URLs. + * + * @param context the context. + * @param base the base IRI to use to resolve relative IRIs. + */ +function _resolveContextUrls({context, base}) { + if(!context) { + return; + } + + const ctx = context['@context']; + + if(_isString(ctx)) { + context['@context'] = prependBase(base, ctx); + return; + } + + if(_isArray(ctx)) { + for(let i = 0; i < ctx.length; ++i) { + const element = ctx[i]; + if(_isString(element)) { + ctx[i] = prependBase(base, element); + continue; + } + if(_isObject(element)) { + _resolveContextUrls({context: {'@context': element}, base}); + } + } + return; + } + + if(!_isObject(ctx)) { + // no @context URLs can be found in non-object + return; + } + + // ctx is an object, resolve any context URLs in terms + for(const term in ctx) { + _resolveContextUrls({context: ctx[term], base}); + } +} + + +/***/ }), + +/***/ "./node_modules/jsonld/lib/JsonLdError.js": +/*!************************************************!*\ + !*** ./node_modules/jsonld/lib/JsonLdError.js ***! + \************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* + * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved. + */ + + +module.exports = class JsonLdError extends Error { + /** + * Creates a JSON-LD Error. + * + * @param msg the error message. + * @param type the error type. + * @param details the error details. + */ + constructor( + message = 'An unspecified JSON-LD error occurred.', + name = 'jsonld.Error', + details = {}) { + super(message); + this.name = name; + this.message = message; + this.details = details; + } +}; + + +/***/ }), + +/***/ "./node_modules/jsonld/lib/JsonLdProcessor.js": +/*!****************************************************!*\ + !*** ./node_modules/jsonld/lib/JsonLdProcessor.js ***! + \****************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* + * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved. + */ + + +module.exports = jsonld => { + class JsonLdProcessor { + toString() { + return '[object JsonLdProcessor]'; + } + } + Object.defineProperty(JsonLdProcessor, 'prototype', { + writable: false, + enumerable: false + }); + Object.defineProperty(JsonLdProcessor.prototype, 'constructor', { + writable: true, + enumerable: false, + configurable: true, + value: JsonLdProcessor + }); + + // The Web IDL test harness will check the number of parameters defined in + // the functions below. The number of parameters must exactly match the + // required (non-optional) parameters of the JsonLdProcessor interface as + // defined here: + // https://www.w3.org/TR/json-ld-api/#the-jsonldprocessor-interface + + JsonLdProcessor.compact = function(input, ctx) { + if(arguments.length < 2) { + return Promise.reject( + new TypeError('Could not compact, too few arguments.')); + } + return jsonld.compact(input, ctx); + }; + JsonLdProcessor.expand = function(input) { + if(arguments.length < 1) { + return Promise.reject( + new TypeError('Could not expand, too few arguments.')); + } + return jsonld.expand(input); + }; + JsonLdProcessor.flatten = function(input) { + if(arguments.length < 1) { + return Promise.reject( + new TypeError('Could not flatten, too few arguments.')); + } + return jsonld.flatten(input); + }; + + return JsonLdProcessor; +}; + + +/***/ }), + +/***/ "./node_modules/jsonld/lib/NQuads.js": +/*!*******************************************!*\ + !*** ./node_modules/jsonld/lib/NQuads.js ***! + \*******************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* + * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved. + */ + + +// TODO: move `NQuads` to its own package +module.exports = __webpack_require__(/*! rdf-canonize */ "./node_modules/rdf-canonize/lib/index.js").NQuads; + + +/***/ }), + +/***/ "./node_modules/jsonld/lib/Rdfa.js": +/*!*****************************************!*\ + !*** ./node_modules/jsonld/lib/Rdfa.js ***! + \*****************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* + * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved. + */ +/* global Node, XMLSerializer */ + + +const { + RDF_LANGSTRING, + RDF_PLAIN_LITERAL, + RDF_OBJECT, + RDF_XML_LITERAL, + XSD_STRING, +} = __webpack_require__(/*! ./constants */ "./node_modules/jsonld/lib/constants.js"); + +let _Node; +if(typeof Node !== 'undefined') { + _Node = Node; +} else { + _Node = { + ELEMENT_NODE: 1, + ATTRIBUTE_NODE: 2, + TEXT_NODE: 3, + CDATA_SECTION_NODE: 4, + ENTITY_REFERENCE_NODE: 5, + ENTITY_NODE: 6, + PROCESSING_INSTRUCTION_NODE: 7, + COMMENT_NODE: 8, + DOCUMENT_NODE: 9, + DOCUMENT_TYPE_NODE: 10, + DOCUMENT_FRAGMENT_NODE: 11, + NOTATION_NODE: 12 + }; +} + +module.exports = class Rdfa { + /** + * Parses the RDF dataset found via the data object from the RDFa API. + * + * @param data the RDFa API data object. + * + * @return the RDF dataset. + */ + parse(data) { + const dataset = {}; + dataset['@default'] = []; + + const subjects = data.getSubjects(); + for(let si = 0; si < subjects.length; ++si) { + const subject = subjects[si]; + if(subject === null) { + continue; + } + + // get all related triples + const triples = data.getSubjectTriples(subject); + if(triples === null) { + continue; + } + const predicates = triples.predicates; + for(const predicate in predicates) { + // iterate over objects + const objects = predicates[predicate].objects; + for(let oi = 0; oi < objects.length; ++oi) { + const object = objects[oi]; + + // create RDF triple + const triple = {}; + + // add subject + if(subject.indexOf('_:') === 0) { + triple.subject = {type: 'blank node', value: subject}; + } else { + triple.subject = {type: 'IRI', value: subject}; + } + + // add predicate + if(predicate.indexOf('_:') === 0) { + triple.predicate = {type: 'blank node', value: predicate}; + } else { + triple.predicate = {type: 'IRI', value: predicate}; + } + + // serialize XML literal + let value = object.value; + if(object.type === RDF_XML_LITERAL) { + // initialize XMLSerializer + const XMLSerializer = getXMLSerializerClass(); + const serializer = new XMLSerializer(); + value = ''; + for(let x = 0; x < object.value.length; x++) { + if(object.value[x].nodeType === _Node.ELEMENT_NODE) { + value += serializer.serializeToString(object.value[x]); + } else if(object.value[x].nodeType === _Node.TEXT_NODE) { + value += object.value[x].nodeValue; + } + } + } + + // add object + triple.object = {}; + + // object is an IRI + if(object.type === RDF_OBJECT) { + if(object.value.indexOf('_:') === 0) { + triple.object.type = 'blank node'; + } else { + triple.object.type = 'IRI'; + } + } else { + // object is a literal + triple.object.type = 'literal'; + if(object.type === RDF_PLAIN_LITERAL) { + if(object.language) { + triple.object.datatype = RDF_LANGSTRING; + triple.object.language = object.language; + } else { + triple.object.datatype = XSD_STRING; + } + } else { + triple.object.datatype = object.type; + } + } + triple.object.value = value; + + // add triple to dataset in default graph + dataset['@default'].push(triple); + } + } + } + + return dataset; + } +}; + +function getXMLSerializerClass() { + if(typeof XMLSerializer === 'undefined') { + return __webpack_require__(/*! xmldom */ "xmldom").XMLSerializer; + } + return XMLSerializer; +} + + +/***/ }), + +/***/ "./node_modules/jsonld/lib/RequestQueue.js": +/*!*************************************************!*\ + !*** ./node_modules/jsonld/lib/RequestQueue.js ***! + \*************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* + * Copyright (c) 2017-2019 Digital Bazaar, Inc. All rights reserved. + */ + + +module.exports = class RequestQueue { + /** + * Creates a simple queue for requesting documents. + */ + constructor() { + this._requests = {}; + } + + wrapLoader(loader) { + const self = this; + self._loader = loader; + return function(/* url */) { + return self.add.apply(self, arguments); + }; + } + + async add(url) { + let promise = this._requests[url]; + if(promise) { + // URL already queued, wait for it to load + return Promise.resolve(promise); + } + + // queue URL and load it + promise = this._requests[url] = this._loader(url); + + try { + return await promise; + } finally { + delete this._requests[url]; + } + } +}; + + +/***/ }), + +/***/ "./node_modules/jsonld/lib/ResolvedContext.js": +/*!****************************************************!*\ + !*** ./node_modules/jsonld/lib/ResolvedContext.js ***! + \****************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* + * Copyright (c) 2019 Digital Bazaar, Inc. All rights reserved. + */ + + +const LRU = __webpack_require__(/*! lru-cache */ "./node_modules/lru-cache/index.js"); + +const MAX_ACTIVE_CONTEXTS = 10; + +module.exports = class ResolvedContext { + /** + * Creates a ResolvedContext. + * + * @param document the context document. + */ + constructor({document}) { + this.document = document; + // TODO: enable customization of processed context cache + // TODO: limit based on size of processed contexts vs. number of them + this.cache = new LRU({max: MAX_ACTIVE_CONTEXTS}); + } + + getProcessed(activeCtx) { + return this.cache.get(activeCtx); + } + + setProcessed(activeCtx, processedCtx) { + this.cache.set(activeCtx, processedCtx); + } +}; + + +/***/ }), + +/***/ "./node_modules/jsonld/lib/compact.js": +/*!********************************************!*\ + !*** ./node_modules/jsonld/lib/compact.js ***! + \********************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* + * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved. + */ + + +const JsonLdError = __webpack_require__(/*! ./JsonLdError */ "./node_modules/jsonld/lib/JsonLdError.js"); + +const { + isArray: _isArray, + isObject: _isObject, + isString: _isString, + isUndefined: _isUndefined +} = __webpack_require__(/*! ./types */ "./node_modules/jsonld/lib/types.js"); + +const { + isList: _isList, + isValue: _isValue, + isGraph: _isGraph, + isSimpleGraph: _isSimpleGraph, + isSubjectReference: _isSubjectReference +} = __webpack_require__(/*! ./graphTypes */ "./node_modules/jsonld/lib/graphTypes.js"); + +const { + expandIri: _expandIri, + getContextValue: _getContextValue, + isKeyword: _isKeyword, + process: _processContext, + processingMode: _processingMode +} = __webpack_require__(/*! ./context */ "./node_modules/jsonld/lib/context.js"); + +const { + removeBase: _removeBase, + prependBase: _prependBase +} = __webpack_require__(/*! ./url */ "./node_modules/jsonld/lib/url.js"); + +const { + addValue: _addValue, + asArray: _asArray, + compareShortestLeast: _compareShortestLeast +} = __webpack_require__(/*! ./util */ "./node_modules/jsonld/lib/util.js"); + +const api = {}; +module.exports = api; + +/** + * Recursively compacts an element using the given active context. All values + * must be in expanded form before this method is called. + * + * @param activeCtx the active context to use. + * @param activeProperty the compacted property associated with the element + * to compact, null for none. + * @param element the element to compact. + * @param options the compaction options. + * @param compactionMap the compaction map to use. + * + * @return a promise that resolves to the compacted value. + */ +api.compact = async ({ + activeCtx, + activeProperty = null, + element, + options = {}, + compactionMap = () => undefined +}) => { + // recursively compact array + if(_isArray(element)) { + let rval = []; + for(let i = 0; i < element.length; ++i) { + // compact, dropping any null values unless custom mapped + let compacted = await api.compact({ + activeCtx, + activeProperty, + element: element[i], + options, + compactionMap + }); + if(compacted === null) { + compacted = await compactionMap({ + unmappedValue: element[i], + activeCtx, + activeProperty, + parent: element, + index: i, + options + }); + if(compacted === undefined) { + continue; + } + } + rval.push(compacted); + } + if(options.compactArrays && rval.length === 1) { + // use single element if no container is specified + const container = _getContextValue( + activeCtx, activeProperty, '@container') || []; + if(container.length === 0) { + rval = rval[0]; + } + } + return rval; + } + + // use any scoped context on activeProperty + const ctx = _getContextValue(activeCtx, activeProperty, '@context'); + if(!_isUndefined(ctx)) { + activeCtx = await _processContext({ + activeCtx, + localCtx: ctx, + propagate: true, + overrideProtected: true, + options + }); + } + + // recursively compact object + if(_isObject(element)) { + if(options.link && '@id' in element && + options.link.hasOwnProperty(element['@id'])) { + // check for a linked element to reuse + const linked = options.link[element['@id']]; + for(let i = 0; i < linked.length; ++i) { + if(linked[i].expanded === element) { + return linked[i].compacted; + } + } + } + + // do value compaction on @values and subject references + if(_isValue(element) || _isSubjectReference(element)) { + const rval = + api.compactValue({activeCtx, activeProperty, value: element, options}); + if(options.link && _isSubjectReference(element)) { + // store linked element + if(!(options.link.hasOwnProperty(element['@id']))) { + options.link[element['@id']] = []; + } + options.link[element['@id']].push({expanded: element, compacted: rval}); + } + return rval; + } + + // if expanded property is @list and we're contained within a list + // container, recursively compact this item to an array + if(_isList(element)) { + const container = _getContextValue( + activeCtx, activeProperty, '@container') || []; + if(container.includes('@list')) { + return api.compact({ + activeCtx, + activeProperty, + element: element['@list'], + options, + compactionMap + }); + } + } + + // FIXME: avoid misuse of active property as an expanded property? + const insideReverse = (activeProperty === '@reverse'); + + const rval = {}; + + // original context before applying property-scoped and local contexts + const inputCtx = activeCtx; + + // revert to previous context, if there is one, + // and element is not a value object or a node reference + if(!_isValue(element) && !_isSubjectReference(element)) { + activeCtx = activeCtx.revertToPreviousContext(); + } + + // apply property-scoped context after reverting term-scoped context + const propertyScopedCtx = + _getContextValue(inputCtx, activeProperty, '@context'); + if(!_isUndefined(propertyScopedCtx)) { + activeCtx = await _processContext({ + activeCtx, + localCtx: propertyScopedCtx, + propagate: true, + overrideProtected: true, + options + }); + } + + if(options.link && '@id' in element) { + // store linked element + if(!options.link.hasOwnProperty(element['@id'])) { + options.link[element['@id']] = []; + } + options.link[element['@id']].push({expanded: element, compacted: rval}); + } + + // apply any context defined on an alias of @type + // if key is @type and any compacted value is a term having a local + // context, overlay that context + let types = element['@type'] || []; + if(types.length > 1) { + types = Array.from(types).sort(); + } + // find all type-scoped contexts based on current context, prior to + // updating it + const typeContext = activeCtx; + for(const type of types) { + const compactedType = api.compactIri( + {activeCtx: typeContext, iri: type, relativeTo: {vocab: true}}); + + // Use any type-scoped context defined on this value + const ctx = _getContextValue(inputCtx, compactedType, '@context'); + if(!_isUndefined(ctx)) { + activeCtx = await _processContext({ + activeCtx, + localCtx: ctx, + options, + propagate: false + }); + } + } + + // process element keys in order + const keys = Object.keys(element).sort(); + for(const expandedProperty of keys) { + const expandedValue = element[expandedProperty]; + + // compact @id + if(expandedProperty === '@id') { + let compactedValue = _asArray(expandedValue).map( + expandedIri => api.compactIri({ + activeCtx, + iri: expandedIri, + relativeTo: {vocab: false}, + base: options.base + })); + if(compactedValue.length === 1) { + compactedValue = compactedValue[0]; + } + + // use keyword alias and add value + const alias = api.compactIri( + {activeCtx, iri: '@id', relativeTo: {vocab: true}}); + + rval[alias] = compactedValue; + continue; + } + + // compact @type(s) + if(expandedProperty === '@type') { + // resolve type values against previous context + let compactedValue = _asArray(expandedValue).map( + expandedIri => api.compactIri({ + activeCtx: inputCtx, + iri: expandedIri, + relativeTo: {vocab: true} + })); + if(compactedValue.length === 1) { + compactedValue = compactedValue[0]; + } + + // use keyword alias and add value + const alias = api.compactIri( + {activeCtx, iri: '@type', relativeTo: {vocab: true}}); + const container = _getContextValue( + activeCtx, alias, '@container') || []; + + // treat as array for @type if @container includes @set + const typeAsSet = + container.includes('@set') && + _processingMode(activeCtx, 1.1); + const isArray = + typeAsSet || (_isArray(compactedValue) && expandedValue.length === 0); + _addValue(rval, alias, compactedValue, {propertyIsArray: isArray}); + continue; + } + + // handle @reverse + if(expandedProperty === '@reverse') { + // recursively compact expanded value + const compactedValue = await api.compact({ + activeCtx, + activeProperty: '@reverse', + element: expandedValue, + options, + compactionMap + }); + + // handle double-reversed properties + for(const compactedProperty in compactedValue) { + if(activeCtx.mappings.has(compactedProperty) && + activeCtx.mappings.get(compactedProperty).reverse) { + const value = compactedValue[compactedProperty]; + const container = _getContextValue( + activeCtx, compactedProperty, '@container') || []; + const useArray = ( + container.includes('@set') || !options.compactArrays); + _addValue( + rval, compactedProperty, value, {propertyIsArray: useArray}); + delete compactedValue[compactedProperty]; + } + } + + if(Object.keys(compactedValue).length > 0) { + // use keyword alias and add value + const alias = api.compactIri({ + activeCtx, + iri: expandedProperty, + relativeTo: {vocab: true} + }); + _addValue(rval, alias, compactedValue); + } + + continue; + } + + if(expandedProperty === '@preserve') { + // compact using activeProperty + const compactedValue = await api.compact({ + activeCtx, + activeProperty, + element: expandedValue, + options, + compactionMap + }); + + if(!(_isArray(compactedValue) && compactedValue.length === 0)) { + _addValue(rval, expandedProperty, compactedValue); + } + continue; + } + + // handle @index property + if(expandedProperty === '@index') { + // drop @index if inside an @index container + const container = _getContextValue( + activeCtx, activeProperty, '@container') || []; + if(container.includes('@index')) { + continue; + } + + // use keyword alias and add value + const alias = api.compactIri({ + activeCtx, + iri: expandedProperty, + relativeTo: {vocab: true} + }); + _addValue(rval, alias, expandedValue); + continue; + } + + // skip array processing for keywords that aren't + // @graph, @list, or @included + if(expandedProperty !== '@graph' && expandedProperty !== '@list' && + expandedProperty !== '@included' && + _isKeyword(expandedProperty)) { + // use keyword alias and add value as is + const alias = api.compactIri({ + activeCtx, + iri: expandedProperty, + relativeTo: {vocab: true} + }); + _addValue(rval, alias, expandedValue); + continue; + } + + // Note: expanded value must be an array due to expansion algorithm. + if(!_isArray(expandedValue)) { + throw new JsonLdError( + 'JSON-LD expansion error; expanded value must be an array.', + 'jsonld.SyntaxError'); + } + + // preserve empty arrays + if(expandedValue.length === 0) { + const itemActiveProperty = api.compactIri({ + activeCtx, + iri: expandedProperty, + value: expandedValue, + relativeTo: {vocab: true}, + reverse: insideReverse + }); + const nestProperty = activeCtx.mappings.has(itemActiveProperty) ? + activeCtx.mappings.get(itemActiveProperty)['@nest'] : null; + let nestResult = rval; + if(nestProperty) { + _checkNestProperty(activeCtx, nestProperty, options); + if(!_isObject(rval[nestProperty])) { + rval[nestProperty] = {}; + } + nestResult = rval[nestProperty]; + } + _addValue( + nestResult, itemActiveProperty, expandedValue, { + propertyIsArray: true + }); + } + + // recusively process array values + for(const expandedItem of expandedValue) { + // compact property and get container type + const itemActiveProperty = api.compactIri({ + activeCtx, + iri: expandedProperty, + value: expandedItem, + relativeTo: {vocab: true}, + reverse: insideReverse + }); + + // if itemActiveProperty is a @nest property, add values to nestResult, + // otherwise rval + const nestProperty = activeCtx.mappings.has(itemActiveProperty) ? + activeCtx.mappings.get(itemActiveProperty)['@nest'] : null; + let nestResult = rval; + if(nestProperty) { + _checkNestProperty(activeCtx, nestProperty, options); + if(!_isObject(rval[nestProperty])) { + rval[nestProperty] = {}; + } + nestResult = rval[nestProperty]; + } + + const container = _getContextValue( + activeCtx, itemActiveProperty, '@container') || []; + + // get simple @graph or @list value if appropriate + const isGraph = _isGraph(expandedItem); + const isList = _isList(expandedItem); + let inner; + if(isList) { + inner = expandedItem['@list']; + } else if(isGraph) { + inner = expandedItem['@graph']; + } + + // recursively compact expanded item + let compactedItem = await api.compact({ + activeCtx, + activeProperty: itemActiveProperty, + element: (isList || isGraph) ? inner : expandedItem, + options, + compactionMap + }); + + // handle @list + if(isList) { + // ensure @list value is an array + if(!_isArray(compactedItem)) { + compactedItem = [compactedItem]; + } + + if(!container.includes('@list')) { + // wrap using @list alias + compactedItem = { + [api.compactIri({ + activeCtx, + iri: '@list', + relativeTo: {vocab: true} + })]: compactedItem + }; + + // include @index from expanded @list, if any + if('@index' in expandedItem) { + compactedItem[api.compactIri({ + activeCtx, + iri: '@index', + relativeTo: {vocab: true} + })] = expandedItem['@index']; + } + } else { + _addValue(nestResult, itemActiveProperty, compactedItem, { + valueIsArray: true, + allowDuplicate: true + }); + continue; + } + } + + // Graph object compaction cases + if(isGraph) { + if(container.includes('@graph') && (container.includes('@id') || + container.includes('@index') && _isSimpleGraph(expandedItem))) { + // get or create the map object + let mapObject; + if(nestResult.hasOwnProperty(itemActiveProperty)) { + mapObject = nestResult[itemActiveProperty]; + } else { + nestResult[itemActiveProperty] = mapObject = {}; + } + + // index on @id or @index or alias of @none + const key = (container.includes('@id') ? + expandedItem['@id'] : expandedItem['@index']) || + api.compactIri({activeCtx, iri: '@none', + relativeTo: {vocab: true}}); + // add compactedItem to map, using value of `@id` or a new blank + // node identifier + + _addValue( + mapObject, key, compactedItem, { + propertyIsArray: + (!options.compactArrays || container.includes('@set')) + }); + } else if(container.includes('@graph') && + _isSimpleGraph(expandedItem)) { + // container includes @graph but not @id or @index and value is a + // simple graph object add compact value + // if compactedItem contains multiple values, it is wrapped in + // `@included` + if(_isArray(compactedItem) && compactedItem.length > 1) { + compactedItem = {'@included': compactedItem}; + } + _addValue( + nestResult, itemActiveProperty, compactedItem, { + propertyIsArray: + (!options.compactArrays || container.includes('@set')) + }); + } else { + // wrap using @graph alias, remove array if only one item and + // compactArrays not set + if(_isArray(compactedItem) && compactedItem.length === 1 && + options.compactArrays) { + compactedItem = compactedItem[0]; + } + compactedItem = { + [api.compactIri({ + activeCtx, + iri: '@graph', + relativeTo: {vocab: true} + })]: compactedItem + }; + + // include @id from expanded graph, if any + if('@id' in expandedItem) { + compactedItem[api.compactIri({ + activeCtx, + iri: '@id', + relativeTo: {vocab: true} + })] = expandedItem['@id']; + } + + // include @index from expanded graph, if any + if('@index' in expandedItem) { + compactedItem[api.compactIri({ + activeCtx, + iri: '@index', + relativeTo: {vocab: true} + })] = expandedItem['@index']; + } + _addValue( + nestResult, itemActiveProperty, compactedItem, { + propertyIsArray: + (!options.compactArrays || container.includes('@set')) + }); + } + } else if(container.includes('@language') || + container.includes('@index') || container.includes('@id') || + container.includes('@type')) { + // handle language and index maps + // get or create the map object + let mapObject; + if(nestResult.hasOwnProperty(itemActiveProperty)) { + mapObject = nestResult[itemActiveProperty]; + } else { + nestResult[itemActiveProperty] = mapObject = {}; + } + + let key; + if(container.includes('@language')) { + // if container is a language map, simplify compacted value to + // a simple string + if(_isValue(compactedItem)) { + compactedItem = compactedItem['@value']; + } + key = expandedItem['@language']; + } else if(container.includes('@index')) { + const indexKey = _getContextValue( + activeCtx, itemActiveProperty, '@index') || '@index'; + const containerKey = api.compactIri( + {activeCtx, iri: indexKey, relativeTo: {vocab: true}}); + if(indexKey === '@index') { + key = expandedItem['@index']; + delete compactedItem[containerKey]; + } else { + let others; + [key, ...others] = _asArray(compactedItem[indexKey] || []); + if(!_isString(key)) { + // Will use @none if it isn't a string. + key = null; + } else { + switch(others.length) { + case 0: + delete compactedItem[indexKey]; + break; + case 1: + compactedItem[indexKey] = others[0]; + break; + default: + compactedItem[indexKey] = others; + break; + } + } + } + } else if(container.includes('@id')) { + const idKey = api.compactIri({activeCtx, iri: '@id', + relativeTo: {vocab: true}}); + key = compactedItem[idKey]; + delete compactedItem[idKey]; + } else if(container.includes('@type')) { + const typeKey = api.compactIri({ + activeCtx, + iri: '@type', + relativeTo: {vocab: true} + }); + let types; + [key, ...types] = _asArray(compactedItem[typeKey] || []); + switch(types.length) { + case 0: + delete compactedItem[typeKey]; + break; + case 1: + compactedItem[typeKey] = types[0]; + break; + default: + compactedItem[typeKey] = types; + break; + } + + // If compactedItem contains a single entry + // whose key maps to @id, recompact without @type + if(Object.keys(compactedItem).length === 1 && + '@id' in expandedItem) { + compactedItem = await api.compact({ + activeCtx, + activeProperty: itemActiveProperty, + element: {'@id': expandedItem['@id']}, + options, + compactionMap + }); + } + } + + // if compacting this value which has no key, index on @none + if(!key) { + key = api.compactIri({activeCtx, iri: '@none', + relativeTo: {vocab: true}}); + } + // add compact value to map object using key from expanded value + // based on the container type + _addValue( + mapObject, key, compactedItem, { + propertyIsArray: container.includes('@set') + }); + } else { + // use an array if: compactArrays flag is false, + // @container is @set or @list , value is an empty + // array, or key is @graph + const isArray = (!options.compactArrays || + container.includes('@set') || container.includes('@list') || + (_isArray(compactedItem) && compactedItem.length === 0) || + expandedProperty === '@list' || expandedProperty === '@graph'); + + // add compact value + _addValue( + nestResult, itemActiveProperty, compactedItem, + {propertyIsArray: isArray}); + } + } + } + + return rval; + } + + // only primitives remain which are already compact + return element; +}; + +/** + * Compacts an IRI or keyword into a term or prefix if it can be. If the + * IRI has an associated value it may be passed. + * + * @param activeCtx the active context to use. + * @param iri the IRI to compact. + * @param value the value to check or null. + * @param relativeTo options for how to compact IRIs: + * vocab: true to split after @vocab, false not to. + * @param reverse true if a reverse property is being compacted, false if not. + * @param base the absolute URL to use for compacting document-relative IRIs. + * + * @return the compacted term, prefix, keyword alias, or the original IRI. + */ +api.compactIri = ({ + activeCtx, + iri, + value = null, + relativeTo = {vocab: false}, + reverse = false, + base = null +}) => { + // can't compact null + if(iri === null) { + return iri; + } + + // if context is from a property term scoped context composed with a + // type-scoped context, then use the previous context instead + if(activeCtx.isPropertyTermScoped && activeCtx.previousContext) { + activeCtx = activeCtx.previousContext; + } + + const inverseCtx = activeCtx.getInverse(); + + // if term is a keyword, it may be compacted to a simple alias + if(_isKeyword(iri) && + iri in inverseCtx && + '@none' in inverseCtx[iri] && + '@type' in inverseCtx[iri]['@none'] && + '@none' in inverseCtx[iri]['@none']['@type']) { + return inverseCtx[iri]['@none']['@type']['@none']; + } + + // use inverse context to pick a term if iri is relative to vocab + if(relativeTo.vocab && iri in inverseCtx) { + const defaultLanguage = activeCtx['@language'] || '@none'; + + // prefer @index if available in value + const containers = []; + if(_isObject(value) && '@index' in value && !('@graph' in value)) { + containers.push('@index', '@index@set'); + } + + // if value is a preserve object, use its value + if(_isObject(value) && '@preserve' in value) { + value = value['@preserve'][0]; + } + + // prefer most specific container including @graph, prefering @set + // variations + if(_isGraph(value)) { + // favor indexmap if the graph is indexed + if('@index' in value) { + containers.push( + '@graph@index', '@graph@index@set', '@index', '@index@set'); + } + // favor idmap if the graph is has an @id + if('@id' in value) { + containers.push( + '@graph@id', '@graph@id@set'); + } + containers.push('@graph', '@graph@set', '@set'); + // allow indexmap if the graph is not indexed + if(!('@index' in value)) { + containers.push( + '@graph@index', '@graph@index@set', '@index', '@index@set'); + } + // allow idmap if the graph does not have an @id + if(!('@id' in value)) { + containers.push('@graph@id', '@graph@id@set'); + } + } else if(_isObject(value) && !_isValue(value)) { + containers.push('@id', '@id@set', '@type', '@set@type'); + } + + // defaults for term selection based on type/language + let typeOrLanguage = '@language'; + let typeOrLanguageValue = '@null'; + + if(reverse) { + typeOrLanguage = '@type'; + typeOrLanguageValue = '@reverse'; + containers.push('@set'); + } else if(_isList(value)) { + // choose the most specific term that works for all elements in @list + // only select @list containers if @index is NOT in value + if(!('@index' in value)) { + containers.push('@list'); + } + const list = value['@list']; + if(list.length === 0) { + // any empty list can be matched against any term that uses the + // @list container regardless of @type or @language + typeOrLanguage = '@any'; + typeOrLanguageValue = '@none'; + } else { + let commonLanguage = (list.length === 0) ? defaultLanguage : null; + let commonType = null; + for(let i = 0; i < list.length; ++i) { + const item = list[i]; + let itemLanguage = '@none'; + let itemType = '@none'; + if(_isValue(item)) { + if('@direction' in item) { + const lang = (item['@language'] || '').toLowerCase(); + const dir = item['@direction']; + itemLanguage = `${lang}_${dir}`; + } else if('@language' in item) { + itemLanguage = item['@language'].toLowerCase(); + } else if('@type' in item) { + itemType = item['@type']; + } else { + // plain literal + itemLanguage = '@null'; + } + } else { + itemType = '@id'; + } + if(commonLanguage === null) { + commonLanguage = itemLanguage; + } else if(itemLanguage !== commonLanguage && _isValue(item)) { + commonLanguage = '@none'; + } + if(commonType === null) { + commonType = itemType; + } else if(itemType !== commonType) { + commonType = '@none'; + } + // there are different languages and types in the list, so choose + // the most generic term, no need to keep iterating the list + if(commonLanguage === '@none' && commonType === '@none') { + break; + } + } + commonLanguage = commonLanguage || '@none'; + commonType = commonType || '@none'; + if(commonType !== '@none') { + typeOrLanguage = '@type'; + typeOrLanguageValue = commonType; + } else { + typeOrLanguageValue = commonLanguage; + } + } + } else { + if(_isValue(value)) { + if('@language' in value && !('@index' in value)) { + containers.push('@language', '@language@set'); + typeOrLanguageValue = value['@language']; + const dir = value['@direction']; + if(dir) { + typeOrLanguageValue = `${typeOrLanguageValue}_${dir}`; + } + } else if('@direction' in value && !('@index' in value)) { + typeOrLanguageValue = `_${value['@direction']}`; + } else if('@type' in value) { + typeOrLanguage = '@type'; + typeOrLanguageValue = value['@type']; + } + } else { + typeOrLanguage = '@type'; + typeOrLanguageValue = '@id'; + } + containers.push('@set'); + } + + // do term selection + containers.push('@none'); + + // an index map can be used to index values using @none, so add as a low + // priority + if(_isObject(value) && !('@index' in value)) { + // allow indexing even if no @index present + containers.push('@index', '@index@set'); + } + + // values without type or language can use @language map + if(_isValue(value) && Object.keys(value).length === 1) { + // allow indexing even if no @index present + containers.push('@language', '@language@set'); + } + + const term = _selectTerm( + activeCtx, iri, value, containers, typeOrLanguage, typeOrLanguageValue); + if(term !== null) { + return term; + } + } + + // no term match, use @vocab if available + if(relativeTo.vocab) { + if('@vocab' in activeCtx) { + // determine if vocab is a prefix of the iri + const vocab = activeCtx['@vocab']; + if(iri.indexOf(vocab) === 0 && iri !== vocab) { + // use suffix as relative iri if it is not a term in the active context + const suffix = iri.substr(vocab.length); + if(!activeCtx.mappings.has(suffix)) { + return suffix; + } + } + } + } + + // no term or @vocab match, check for possible CURIEs + let choice = null; + // TODO: make FastCurieMap a class with a method to do this lookup + const partialMatches = []; + let iriMap = activeCtx.fastCurieMap; + // check for partial matches of against `iri`, which means look until + // iri.length - 1, not full length + const maxPartialLength = iri.length - 1; + for(let i = 0; i < maxPartialLength && iri[i] in iriMap; ++i) { + iriMap = iriMap[iri[i]]; + if('' in iriMap) { + partialMatches.push(iriMap[''][0]); + } + } + // check partial matches in reverse order to prefer longest ones first + for(let i = partialMatches.length - 1; i >= 0; --i) { + const entry = partialMatches[i]; + const terms = entry.terms; + for(const term of terms) { + // a CURIE is usable if: + // 1. it has no mapping, OR + // 2. value is null, which means we're not compacting an @value, AND + // the mapping matches the IRI + const curie = term + ':' + iri.substr(entry.iri.length); + const isUsableCurie = (activeCtx.mappings.get(term)._prefix && + (!activeCtx.mappings.has(curie) || + (value === null && activeCtx.mappings.get(curie)['@id'] === iri))); + + // select curie if it is shorter or the same length but lexicographically + // less than the current choice + if(isUsableCurie && (choice === null || + _compareShortestLeast(curie, choice) < 0)) { + choice = curie; + } + } + } + + // return chosen curie + if(choice !== null) { + return choice; + } + + // If iri could be confused with a compact IRI using a term in this context, + // signal an error + for(const [term, td] of activeCtx.mappings) { + if(td && td._prefix && iri.startsWith(term + ':')) { + throw new JsonLdError( + `Absolute IRI "${iri}" confused with prefix "${term}".`, + 'jsonld.SyntaxError', + {code: 'IRI confused with prefix', context: activeCtx}); + } + } + + // compact IRI relative to base + if(!relativeTo.vocab) { + if('@base' in activeCtx) { + if(!activeCtx['@base']) { + // The None case preserves rval as potentially relative + return iri; + } else { + return _removeBase(_prependBase(base, activeCtx['@base']), iri); + } + } else { + return _removeBase(base, iri); + } + } + + // return IRI as is + return iri; +}; + +/** + * Performs value compaction on an object with '@value' or '@id' as the only + * property. + * + * @param activeCtx the active context. + * @param activeProperty the active property that points to the value. + * @param value the value to compact. + * @param {Object} [options] - processing options. + * + * @return the compaction result. + */ +api.compactValue = ({activeCtx, activeProperty, value, options}) => { + // value is a @value + if(_isValue(value)) { + // get context rules + const type = _getContextValue(activeCtx, activeProperty, '@type'); + const language = _getContextValue(activeCtx, activeProperty, '@language'); + const direction = _getContextValue(activeCtx, activeProperty, '@direction'); + const container = + _getContextValue(activeCtx, activeProperty, '@container') || []; + + // whether or not the value has an @index that must be preserved + const preserveIndex = '@index' in value && !container.includes('@index'); + + // if there's no @index to preserve ... + if(!preserveIndex && type !== '@none') { + // matching @type or @language specified in context, compact value + if(value['@type'] === type) { + return value['@value']; + } + if('@language' in value && value['@language'] === language && + '@direction' in value && value['@direction'] === direction) { + return value['@value']; + } + if('@language' in value && value['@language'] === language) { + return value['@value']; + } + if('@direction' in value && value['@direction'] === direction) { + return value['@value']; + } + } + + // return just the value of @value if all are true: + // 1. @value is the only key or @index isn't being preserved + // 2. there is no default language or @value is not a string or + // the key has a mapping with a null @language + const keyCount = Object.keys(value).length; + const isValueOnlyKey = (keyCount === 1 || + (keyCount === 2 && '@index' in value && !preserveIndex)); + const hasDefaultLanguage = ('@language' in activeCtx); + const isValueString = _isString(value['@value']); + const hasNullMapping = (activeCtx.mappings.has(activeProperty) && + activeCtx.mappings.get(activeProperty)['@language'] === null); + if(isValueOnlyKey && + type !== '@none' && + (!hasDefaultLanguage || !isValueString || hasNullMapping)) { + return value['@value']; + } + + const rval = {}; + + // preserve @index + if(preserveIndex) { + rval[api.compactIri({ + activeCtx, + iri: '@index', + relativeTo: {vocab: true} + })] = value['@index']; + } + + if('@type' in value) { + // compact @type IRI + rval[api.compactIri({ + activeCtx, + iri: '@type', + relativeTo: {vocab: true} + })] = api.compactIri( + {activeCtx, iri: value['@type'], relativeTo: {vocab: true}}); + } else if('@language' in value) { + // alias @language + rval[api.compactIri({ + activeCtx, + iri: '@language', + relativeTo: {vocab: true} + })] = value['@language']; + } + + if('@direction' in value) { + // alias @direction + rval[api.compactIri({ + activeCtx, + iri: '@direction', + relativeTo: {vocab: true} + })] = value['@direction']; + } + + // alias @value + rval[api.compactIri({ + activeCtx, + iri: '@value', + relativeTo: {vocab: true} + })] = value['@value']; + + return rval; + } + + // value is a subject reference + const expandedProperty = _expandIri(activeCtx, activeProperty, {vocab: true}, + options); + const type = _getContextValue(activeCtx, activeProperty, '@type'); + const compacted = api.compactIri({ + activeCtx, + iri: value['@id'], + relativeTo: {vocab: type === '@vocab'}, + base: options.base}); + + // compact to scalar + if(type === '@id' || type === '@vocab' || expandedProperty === '@graph') { + return compacted; + } + + return { + [api.compactIri({ + activeCtx, + iri: '@id', + relativeTo: {vocab: true} + })]: compacted + }; +}; + +/** + * Picks the preferred compaction term from the given inverse context entry. + * + * @param activeCtx the active context. + * @param iri the IRI to pick the term for. + * @param value the value to pick the term for. + * @param containers the preferred containers. + * @param typeOrLanguage either '@type' or '@language'. + * @param typeOrLanguageValue the preferred value for '@type' or '@language'. + * + * @return the preferred term. + */ +function _selectTerm( + activeCtx, iri, value, containers, typeOrLanguage, typeOrLanguageValue) { + if(typeOrLanguageValue === null) { + typeOrLanguageValue = '@null'; + } + + // preferences for the value of @type or @language + const prefs = []; + + // determine prefs for @id based on whether or not value compacts to a term + if((typeOrLanguageValue === '@id' || typeOrLanguageValue === '@reverse') && + _isObject(value) && '@id' in value) { + // prefer @reverse first + if(typeOrLanguageValue === '@reverse') { + prefs.push('@reverse'); + } + // try to compact value to a term + const term = api.compactIri( + {activeCtx, iri: value['@id'], relativeTo: {vocab: true}}); + if(activeCtx.mappings.has(term) && + activeCtx.mappings.get(term) && + activeCtx.mappings.get(term)['@id'] === value['@id']) { + // prefer @vocab + prefs.push.apply(prefs, ['@vocab', '@id']); + } else { + // prefer @id + prefs.push.apply(prefs, ['@id', '@vocab']); + } + } else { + prefs.push(typeOrLanguageValue); + + // consider direction only + const langDir = prefs.find(el => el.includes('_')); + if(langDir) { + // consider _dir portion + prefs.push(langDir.replace(/^[^_]+_/, '_')); + } + } + prefs.push('@none'); + + const containerMap = activeCtx.inverse[iri]; + for(const container of containers) { + // if container not available in the map, continue + if(!(container in containerMap)) { + continue; + } + + const typeOrLanguageValueMap = containerMap[container][typeOrLanguage]; + for(const pref of prefs) { + // if type/language option not available in the map, continue + if(!(pref in typeOrLanguageValueMap)) { + continue; + } + + // select term + return typeOrLanguageValueMap[pref]; + } + } + + return null; +} + +/** + * The value of `@nest` in the term definition must either be `@nest`, or a term + * which resolves to `@nest`. + * + * @param activeCtx the active context. + * @param nestProperty a term in the active context or `@nest`. + * @param {Object} [options] - processing options. + */ +function _checkNestProperty(activeCtx, nestProperty, options) { + if(_expandIri(activeCtx, nestProperty, {vocab: true}, options) !== '@nest') { + throw new JsonLdError( + 'JSON-LD compact error; nested property must have an @nest value ' + + 'resolving to @nest.', + 'jsonld.SyntaxError', {code: 'invalid @nest value'}); + } +} + + +/***/ }), + +/***/ "./node_modules/jsonld/lib/constants.js": +/*!**********************************************!*\ + !*** ./node_modules/jsonld/lib/constants.js ***! + \**********************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* + * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved. + */ + + +const RDF = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'; +const XSD = 'http://www.w3.org/2001/XMLSchema#'; + +module.exports = { + // TODO: Deprecated and will be removed later. Use LINK_HEADER_CONTEXT. + LINK_HEADER_REL: 'http://www.w3.org/ns/json-ld#context', + + LINK_HEADER_CONTEXT: 'http://www.w3.org/ns/json-ld#context', + + RDF, + RDF_LIST: RDF + 'List', + RDF_FIRST: RDF + 'first', + RDF_REST: RDF + 'rest', + RDF_NIL: RDF + 'nil', + RDF_TYPE: RDF + 'type', + RDF_PLAIN_LITERAL: RDF + 'PlainLiteral', + RDF_XML_LITERAL: RDF + 'XMLLiteral', + RDF_JSON_LITERAL: RDF + 'JSON', + RDF_OBJECT: RDF + 'object', + RDF_LANGSTRING: RDF + 'langString', + + XSD, + XSD_BOOLEAN: XSD + 'boolean', + XSD_DOUBLE: XSD + 'double', + XSD_INTEGER: XSD + 'integer', + XSD_STRING: XSD + 'string', +}; + + +/***/ }), + +/***/ "./node_modules/jsonld/lib/context.js": +/*!********************************************!*\ + !*** ./node_modules/jsonld/lib/context.js ***! + \********************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* + * Copyright (c) 2017-2019 Digital Bazaar, Inc. All rights reserved. + */ + + +const util = __webpack_require__(/*! ./util */ "./node_modules/jsonld/lib/util.js"); +const JsonLdError = __webpack_require__(/*! ./JsonLdError */ "./node_modules/jsonld/lib/JsonLdError.js"); + +const { + isArray: _isArray, + isObject: _isObject, + isString: _isString, + isUndefined: _isUndefined +} = __webpack_require__(/*! ./types */ "./node_modules/jsonld/lib/types.js"); + +const { + isAbsolute: _isAbsoluteIri, + isRelative: _isRelativeIri, + prependBase, + parse: parseUrl +} = __webpack_require__(/*! ./url */ "./node_modules/jsonld/lib/url.js"); + +const { + asArray: _asArray, + compareShortestLeast: _compareShortestLeast +} = __webpack_require__(/*! ./util */ "./node_modules/jsonld/lib/util.js"); + +const INITIAL_CONTEXT_CACHE = new Map(); +const INITIAL_CONTEXT_CACHE_MAX_SIZE = 10000; +const KEYWORD_PATTERN = /^@[a-zA-Z]+$/; + +const api = {}; +module.exports = api; + +/** + * Processes a local context and returns a new active context. + * + * @param activeCtx the current active context. + * @param localCtx the local context to process. + * @param options the context processing options. + * @param propagate `true` if `false`, retains any previously defined term, + * which can be rolled back when the descending into a new node object. + * @param overrideProtected `false` allows protected terms to be modified. + * + * @return a Promise that resolves to the new active context. + */ +api.process = async ({ + activeCtx, localCtx, options, + propagate = true, + overrideProtected = false, + cycles = new Set() +}) => { + // normalize local context to an array of @context objects + if(_isObject(localCtx) && '@context' in localCtx && + _isArray(localCtx['@context'])) { + localCtx = localCtx['@context']; + } + const ctxs = _asArray(localCtx); + + // no contexts in array, return current active context w/o changes + if(ctxs.length === 0) { + return activeCtx; + } + + // resolve contexts + const resolved = await options.contextResolver.resolve({ + activeCtx, + context: localCtx, + documentLoader: options.documentLoader, + base: options.base + }); + + // override propagate if first resolved context has `@propagate` + if(_isObject(resolved[0].document) && + typeof resolved[0].document['@propagate'] === 'boolean') { + // retrieve early, error checking done later + propagate = resolved[0].document['@propagate']; + } + + // process each context in order, update active context + // on each iteration to ensure proper caching + let rval = activeCtx; + + // track the previous context + // if not propagating, make sure rval has a previous context + if(!propagate && !rval.previousContext) { + // clone `rval` context before updating + rval = rval.clone(); + rval.previousContext = activeCtx; + } + + for(const resolvedContext of resolved) { + let {document: ctx} = resolvedContext; + + // update active context to one computed from last iteration + activeCtx = rval; + + // reset to initial context + if(ctx === null) { + // We can't nullify if there are protected terms and we're + // not allowing overrides (e.g. processing a property term scoped context) + if(!overrideProtected && + Object.keys(activeCtx.protected).length !== 0) { + const protectedMode = (options && options.protectedMode) || 'error'; + if(protectedMode === 'error') { + throw new JsonLdError( + 'Tried to nullify a context with protected terms outside of ' + + 'a term definition.', + 'jsonld.SyntaxError', + {code: 'invalid context nullification'}); + } else if(protectedMode === 'warn') { + // FIXME: remove logging and use a handler + console.warn('WARNING: invalid context nullification'); + + // get processed context from cache if available + const processed = resolvedContext.getProcessed(activeCtx); + if(processed) { + rval = activeCtx = processed; + continue; + } + + const oldActiveCtx = activeCtx; + // copy all protected term definitions to fresh initial context + rval = activeCtx = api.getInitialContext(options).clone(); + for(const [term, _protected] of + Object.entries(oldActiveCtx.protected)) { + if(_protected) { + activeCtx.mappings[term] = + util.clone(oldActiveCtx.mappings[term]); + } + } + activeCtx.protected = util.clone(oldActiveCtx.protected); + + // cache processed result + resolvedContext.setProcessed(oldActiveCtx, rval); + continue; + } + throw new JsonLdError( + 'Invalid protectedMode.', + 'jsonld.SyntaxError', + {code: 'invalid protected mode', context: localCtx, protectedMode}); + } + rval = activeCtx = api.getInitialContext(options).clone(); + continue; + } + + // get processed context from cache if available + const processed = resolvedContext.getProcessed(activeCtx); + if(processed) { + rval = activeCtx = processed; + continue; + } + + // dereference @context key if present + if(_isObject(ctx) && '@context' in ctx) { + ctx = ctx['@context']; + } + + // context must be an object by now, all URLs retrieved before this call + if(!_isObject(ctx)) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; @context must be an object.', + 'jsonld.SyntaxError', {code: 'invalid local context', context: ctx}); + } + + // TODO: there is likely a `previousContext` cloning optimization that + // could be applied here (no need to copy it under certain conditions) + + // clone context before updating it + rval = rval.clone(); + + // define context mappings for keys in local context + const defined = new Map(); + + // handle @version + if('@version' in ctx) { + if(ctx['@version'] !== 1.1) { + throw new JsonLdError( + 'Unsupported JSON-LD version: ' + ctx['@version'], + 'jsonld.UnsupportedVersion', + {code: 'invalid @version value', context: ctx}); + } + if(activeCtx.processingMode && + activeCtx.processingMode === 'json-ld-1.0') { + throw new JsonLdError( + '@version: ' + ctx['@version'] + ' not compatible with ' + + activeCtx.processingMode, + 'jsonld.ProcessingModeConflict', + {code: 'processing mode conflict', context: ctx}); + } + rval.processingMode = 'json-ld-1.1'; + rval['@version'] = ctx['@version']; + defined.set('@version', true); + } + + // if not set explicitly, set processingMode to "json-ld-1.1" + rval.processingMode = + rval.processingMode || activeCtx.processingMode; + + // handle @base + if('@base' in ctx) { + let base = ctx['@base']; + + if(base === null || _isAbsoluteIri(base)) { + // no action + } else if(_isRelativeIri(base)) { + base = prependBase(rval['@base'], base); + } else { + throw new JsonLdError( + 'Invalid JSON-LD syntax; the value of "@base" in a ' + + '@context must be an absolute IRI, a relative IRI, or null.', + 'jsonld.SyntaxError', {code: 'invalid base IRI', context: ctx}); + } + + rval['@base'] = base; + defined.set('@base', true); + } + + // handle @vocab + if('@vocab' in ctx) { + const value = ctx['@vocab']; + if(value === null) { + delete rval['@vocab']; + } else if(!_isString(value)) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; the value of "@vocab" in a ' + + '@context must be a string or null.', + 'jsonld.SyntaxError', {code: 'invalid vocab mapping', context: ctx}); + } else if(!_isAbsoluteIri(value) && api.processingMode(rval, 1.0)) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; the value of "@vocab" in a ' + + '@context must be an absolute IRI.', + 'jsonld.SyntaxError', {code: 'invalid vocab mapping', context: ctx}); + } else { + rval['@vocab'] = _expandIri(rval, value, {vocab: true, base: true}, + undefined, undefined, options); + } + defined.set('@vocab', true); + } + + // handle @language + if('@language' in ctx) { + const value = ctx['@language']; + if(value === null) { + delete rval['@language']; + } else if(!_isString(value)) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; the value of "@language" in a ' + + '@context must be a string or null.', + 'jsonld.SyntaxError', + {code: 'invalid default language', context: ctx}); + } else { + rval['@language'] = value.toLowerCase(); + } + defined.set('@language', true); + } + + // handle @direction + if('@direction' in ctx) { + const value = ctx['@direction']; + if(activeCtx.processingMode === 'json-ld-1.0') { + throw new JsonLdError( + 'Invalid JSON-LD syntax; @direction not compatible with ' + + activeCtx.processingMode, + 'jsonld.SyntaxError', + {code: 'invalid context member', context: ctx}); + } + if(value === null) { + delete rval['@direction']; + } else if(value !== 'ltr' && value !== 'rtl') { + throw new JsonLdError( + 'Invalid JSON-LD syntax; the value of "@direction" in a ' + + '@context must be null, "ltr", or "rtl".', + 'jsonld.SyntaxError', + {code: 'invalid base direction', context: ctx}); + } else { + rval['@direction'] = value; + } + defined.set('@direction', true); + } + + // handle @propagate + // note: we've already extracted it, here we just do error checking + if('@propagate' in ctx) { + const value = ctx['@propagate']; + if(activeCtx.processingMode === 'json-ld-1.0') { + throw new JsonLdError( + 'Invalid JSON-LD syntax; @propagate not compatible with ' + + activeCtx.processingMode, + 'jsonld.SyntaxError', + {code: 'invalid context entry', context: ctx}); + } + if(typeof value !== 'boolean') { + throw new JsonLdError( + 'Invalid JSON-LD syntax; @propagate value must be a boolean.', + 'jsonld.SyntaxError', + {code: 'invalid @propagate value', context: localCtx}); + } + defined.set('@propagate', true); + } + + // handle @import + if('@import' in ctx) { + const value = ctx['@import']; + if(activeCtx.processingMode === 'json-ld-1.0') { + throw new JsonLdError( + 'Invalid JSON-LD syntax; @import not compatible with ' + + activeCtx.processingMode, + 'jsonld.SyntaxError', + {code: 'invalid context entry', context: ctx}); + } + if(!_isString(value)) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; @import must be a string.', + 'jsonld.SyntaxError', + {code: 'invalid @import value', context: localCtx}); + } + + // resolve contexts + const resolvedImport = await options.contextResolver.resolve({ + activeCtx, + context: value, + documentLoader: options.documentLoader, + base: options.base + }); + if(resolvedImport.length !== 1) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; @import must reference a single context.', + 'jsonld.SyntaxError', + {code: 'invalid remote context', context: localCtx}); + } + const processedImport = resolvedImport[0].getProcessed(activeCtx); + if(processedImport) { + // Note: if the same context were used in this active context + // as a reference context, then processed_input might not + // be a dict. + ctx = processedImport; + } else { + const importCtx = resolvedImport[0].document; + if('@import' in importCtx) { + throw new JsonLdError( + 'Invalid JSON-LD syntax: ' + + 'imported context must not include @import.', + 'jsonld.SyntaxError', + {code: 'invalid context entry', context: localCtx}); + } + + // merge ctx into importCtx and replace rval with the result + for(const key in importCtx) { + if(!ctx.hasOwnProperty(key)) { + ctx[key] = importCtx[key]; + } + } + + // Note: this could potenially conflict if the import + // were used in the same active context as a referenced + // context and an import. In this case, we + // could override the cached result, but seems unlikely. + resolvedImport[0].setProcessed(activeCtx, ctx); + } + + defined.set('@import', true); + } + + // handle @protected; determine whether this sub-context is declaring + // all its terms to be "protected" (exceptions can be made on a + // per-definition basis) + defined.set('@protected', ctx['@protected'] || false); + + // process all other keys + for(const key in ctx) { + api.createTermDefinition({ + activeCtx: rval, + localCtx: ctx, + term: key, + defined, + options, + overrideProtected + }); + + if(_isObject(ctx[key]) && '@context' in ctx[key]) { + const keyCtx = ctx[key]['@context']; + let process = true; + if(_isString(keyCtx)) { + const url = prependBase(options.base, keyCtx); + // track processed contexts to avoid scoped context recursion + if(cycles.has(url)) { + process = false; + } else { + cycles.add(url); + } + } + // parse context to validate + if(process) { + try { + await api.process({ + activeCtx: rval.clone(), + localCtx: ctx[key]['@context'], + overrideProtected: true, + options, + cycles + }); + } catch(e) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; invalid scoped context.', + 'jsonld.SyntaxError', + { + code: 'invalid scoped context', + context: ctx[key]['@context'], + term: key + }); + } + } + } + } + + // cache processed result + resolvedContext.setProcessed(activeCtx, rval); + } + + return rval; +}; + +/** + * Creates a term definition during context processing. + * + * @param activeCtx the current active context. + * @param localCtx the local context being processed. + * @param term the term in the local context to define the mapping for. + * @param defined a map of defining/defined keys to detect cycles and prevent + * double definitions. + * @param {Object} [options] - creation options. + * @param {string} [options.protectedMode="error"] - "error" to throw error + * on `@protected` constraint violation, "warn" to allow violations and + * signal a warning. + * @param overrideProtected `false` allows protected terms to be modified. + */ +api.createTermDefinition = ({ + activeCtx, + localCtx, + term, + defined, + options, + overrideProtected = false, +}) => { + if(defined.has(term)) { + // term already defined + if(defined.get(term)) { + return; + } + // cycle detected + throw new JsonLdError( + 'Cyclical context definition detected.', + 'jsonld.CyclicalContext', + {code: 'cyclic IRI mapping', context: localCtx, term}); + } + + // now defining term + defined.set(term, false); + + // get context term value + let value; + if(localCtx.hasOwnProperty(term)) { + value = localCtx[term]; + } + + if(term === '@type' && + _isObject(value) && + (value['@container'] || '@set') === '@set' && + api.processingMode(activeCtx, 1.1)) { + + const validKeys = ['@container', '@id', '@protected']; + const keys = Object.keys(value); + if(keys.length === 0 || keys.some(k => !validKeys.includes(k))) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; keywords cannot be overridden.', + 'jsonld.SyntaxError', + {code: 'keyword redefinition', context: localCtx, term}); + } + } else if(api.isKeyword(term)) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; keywords cannot be overridden.', + 'jsonld.SyntaxError', + {code: 'keyword redefinition', context: localCtx, term}); + } else if(term.match(KEYWORD_PATTERN)) { + // FIXME: remove logging and use a handler + console.warn('WARNING: terms beginning with "@" are reserved' + + ' for future use and ignored', {term}); + return; + } else if(term === '') { + throw new JsonLdError( + 'Invalid JSON-LD syntax; a term cannot be an empty string.', + 'jsonld.SyntaxError', + {code: 'invalid term definition', context: localCtx}); + } + + // keep reference to previous mapping for potential `@protected` check + const previousMapping = activeCtx.mappings.get(term); + + // remove old mapping + if(activeCtx.mappings.has(term)) { + activeCtx.mappings.delete(term); + } + + // convert short-hand value to object w/@id + let simpleTerm = false; + if(_isString(value) || value === null) { + simpleTerm = true; + value = {'@id': value}; + } + + if(!_isObject(value)) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; @context term values must be ' + + 'strings or objects.', + 'jsonld.SyntaxError', + {code: 'invalid term definition', context: localCtx}); + } + + // create new mapping + const mapping = {}; + activeCtx.mappings.set(term, mapping); + mapping.reverse = false; + + // make sure term definition only has expected keywords + const validKeys = ['@container', '@id', '@language', '@reverse', '@type']; + + // JSON-LD 1.1 support + if(api.processingMode(activeCtx, 1.1)) { + validKeys.push( + '@context', '@direction', '@index', '@nest', '@prefix', '@protected'); + } + + for(const kw in value) { + if(!validKeys.includes(kw)) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; a term definition must not contain ' + kw, + 'jsonld.SyntaxError', + {code: 'invalid term definition', context: localCtx}); + } + } + + // always compute whether term has a colon as an optimization for + // _compactIri + const colon = term.indexOf(':'); + mapping._termHasColon = (colon > 0); + + if('@reverse' in value) { + if('@id' in value) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; a @reverse term definition must not ' + + 'contain @id.', 'jsonld.SyntaxError', + {code: 'invalid reverse property', context: localCtx}); + } + if('@nest' in value) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; a @reverse term definition must not ' + + 'contain @nest.', 'jsonld.SyntaxError', + {code: 'invalid reverse property', context: localCtx}); + } + const reverse = value['@reverse']; + if(!_isString(reverse)) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; a @context @reverse value must be a string.', + 'jsonld.SyntaxError', {code: 'invalid IRI mapping', context: localCtx}); + } + + if(!api.isKeyword(reverse) && reverse.match(KEYWORD_PATTERN)) { + // FIXME: remove logging and use a handler + console.warn('WARNING: values beginning with "@" are reserved' + + ' for future use and ignored', {reverse}); + if(previousMapping) { + activeCtx.mappings.set(term, previousMapping); + } else { + activeCtx.mappings.delete(term); + } + return; + } + + // expand and add @id mapping + const id = _expandIri( + activeCtx, reverse, {vocab: true, base: false}, localCtx, defined, + options); + if(!_isAbsoluteIri(id)) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; a @context @reverse value must be an ' + + 'absolute IRI or a blank node identifier.', + 'jsonld.SyntaxError', {code: 'invalid IRI mapping', context: localCtx}); + } + + mapping['@id'] = id; + mapping.reverse = true; + } else if('@id' in value) { + let id = value['@id']; + if(id && !_isString(id)) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; a @context @id value must be an array ' + + 'of strings or a string.', + 'jsonld.SyntaxError', {code: 'invalid IRI mapping', context: localCtx}); + } + if(id === null) { + // reserve a null term, which may be protected + mapping['@id'] = null; + } else if(!api.isKeyword(id) && id.match(KEYWORD_PATTERN)) { + // FIXME: remove logging and use a handler + console.warn('WARNING: values beginning with "@" are reserved' + + ' for future use and ignored', {id}); + if(previousMapping) { + activeCtx.mappings.set(term, previousMapping); + } else { + activeCtx.mappings.delete(term); + } + return; + } else if(id !== term) { + // expand and add @id mapping + id = _expandIri( + activeCtx, id, {vocab: true, base: false}, localCtx, defined, options); + if(!_isAbsoluteIri(id) && !api.isKeyword(id)) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; a @context @id value must be an ' + + 'absolute IRI, a blank node identifier, or a keyword.', + 'jsonld.SyntaxError', + {code: 'invalid IRI mapping', context: localCtx}); + } + + // if term has the form of an IRI it must map the same + if(term.match(/(?::[^:])|\//)) { + const termDefined = new Map(defined).set(term, true); + const termIri = _expandIri( + activeCtx, term, {vocab: true, base: false}, + localCtx, termDefined, options); + if(termIri !== id) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; term in form of IRI must ' + + 'expand to definition.', + 'jsonld.SyntaxError', + {code: 'invalid IRI mapping', context: localCtx}); + } + } + + mapping['@id'] = id; + // indicate if this term may be used as a compact IRI prefix + mapping._prefix = (simpleTerm && + !mapping._termHasColon && + id.match(/[:\/\?#\[\]@]$/)); + } + } + + if(!('@id' in mapping)) { + // see if the term has a prefix + if(mapping._termHasColon) { + const prefix = term.substr(0, colon); + if(localCtx.hasOwnProperty(prefix)) { + // define parent prefix + api.createTermDefinition({ + activeCtx, localCtx, term: prefix, defined, options + }); + } + + if(activeCtx.mappings.has(prefix)) { + // set @id based on prefix parent + const suffix = term.substr(colon + 1); + mapping['@id'] = activeCtx.mappings.get(prefix)['@id'] + suffix; + } else { + // term is an absolute IRI + mapping['@id'] = term; + } + } else if(term === '@type') { + // Special case, were we've previously determined that container is @set + mapping['@id'] = term; + } else { + // non-IRIs *must* define @ids if @vocab is not available + if(!('@vocab' in activeCtx)) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; @context terms must define an @id.', + 'jsonld.SyntaxError', + {code: 'invalid IRI mapping', context: localCtx, term}); + } + // prepend vocab to term + mapping['@id'] = activeCtx['@vocab'] + term; + } + } + + // Handle term protection + if(value['@protected'] === true || + (defined.get('@protected') === true && value['@protected'] !== false)) { + activeCtx.protected[term] = true; + mapping.protected = true; + } + + // IRI mapping now defined + defined.set(term, true); + + if('@type' in value) { + let type = value['@type']; + if(!_isString(type)) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; an @context @type value must be a string.', + 'jsonld.SyntaxError', + {code: 'invalid type mapping', context: localCtx}); + } + + if((type === '@json' || type === '@none')) { + if(api.processingMode(activeCtx, 1.0)) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; an @context @type value must not be ' + + `"${type}" in JSON-LD 1.0 mode.`, + 'jsonld.SyntaxError', + {code: 'invalid type mapping', context: localCtx}); + } + } else if(type !== '@id' && type !== '@vocab') { + // expand @type to full IRI + type = _expandIri( + activeCtx, type, {vocab: true, base: false}, localCtx, defined, + options); + if(!_isAbsoluteIri(type)) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; an @context @type value must be an ' + + 'absolute IRI.', + 'jsonld.SyntaxError', + {code: 'invalid type mapping', context: localCtx}); + } + if(type.indexOf('_:') === 0) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; an @context @type value must be an IRI, ' + + 'not a blank node identifier.', + 'jsonld.SyntaxError', + {code: 'invalid type mapping', context: localCtx}); + } + } + + // add @type to mapping + mapping['@type'] = type; + } + + if('@container' in value) { + // normalize container to an array form + const container = _isString(value['@container']) ? + [value['@container']] : (value['@container'] || []); + const validContainers = ['@list', '@set', '@index', '@language']; + let isValid = true; + const hasSet = container.includes('@set'); + + // JSON-LD 1.1 support + if(api.processingMode(activeCtx, 1.1)) { + validContainers.push('@graph', '@id', '@type'); + + // check container length + if(container.includes('@list')) { + if(container.length !== 1) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; @context @container with @list must ' + + 'have no other values', + 'jsonld.SyntaxError', + {code: 'invalid container mapping', context: localCtx}); + } + } else if(container.includes('@graph')) { + if(container.some(key => + key !== '@graph' && key !== '@id' && key !== '@index' && + key !== '@set')) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; @context @container with @graph must ' + + 'have no other values other than @id, @index, and @set', + 'jsonld.SyntaxError', + {code: 'invalid container mapping', context: localCtx}); + } + } else { + // otherwise, container may also include @set + isValid &= container.length <= (hasSet ? 2 : 1); + } + + if(container.includes('@type')) { + // If mapping does not have an @type, + // set it to @id + mapping['@type'] = mapping['@type'] || '@id'; + + // type mapping must be either @id or @vocab + if(!['@id', '@vocab'].includes(mapping['@type'])) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; container: @type requires @type to be ' + + '@id or @vocab.', + 'jsonld.SyntaxError', + {code: 'invalid type mapping', context: localCtx}); + } + } + } else { + // in JSON-LD 1.0, container must not be an array (it must be a string, + // which is one of the validContainers) + isValid &= !_isArray(value['@container']); + + // check container length + isValid &= container.length <= 1; + } + + // check against valid containers + isValid &= container.every(c => validContainers.includes(c)); + + // @set not allowed with @list + isValid &= !(hasSet && container.includes('@list')); + + if(!isValid) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; @context @container value must be ' + + 'one of the following: ' + validContainers.join(', '), + 'jsonld.SyntaxError', + {code: 'invalid container mapping', context: localCtx}); + } + + if(mapping.reverse && + !container.every(c => ['@index', '@set'].includes(c))) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; @context @container value for a @reverse ' + + 'type definition must be @index or @set.', 'jsonld.SyntaxError', + {code: 'invalid reverse property', context: localCtx}); + } + + // add @container to mapping + mapping['@container'] = container; + } + + // property indexing + if('@index' in value) { + if(!('@container' in value) || !mapping['@container'].includes('@index')) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; @index without @index in @container: ' + + `"${value['@index']}" on term "${term}".`, 'jsonld.SyntaxError', + {code: 'invalid term definition', context: localCtx}); + } + if(!_isString(value['@index']) || value['@index'].indexOf('@') === 0) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; @index must expand to an IRI: ' + + `"${value['@index']}" on term "${term}".`, 'jsonld.SyntaxError', + {code: 'invalid term definition', context: localCtx}); + } + mapping['@index'] = value['@index']; + } + + // scoped contexts + if('@context' in value) { + mapping['@context'] = value['@context']; + } + + if('@language' in value && !('@type' in value)) { + let language = value['@language']; + if(language !== null && !_isString(language)) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; @context @language value must be ' + + 'a string or null.', 'jsonld.SyntaxError', + {code: 'invalid language mapping', context: localCtx}); + } + + // add @language to mapping + if(language !== null) { + language = language.toLowerCase(); + } + mapping['@language'] = language; + } + + // term may be used as a prefix + if('@prefix' in value) { + if(term.match(/:|\//)) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; @context @prefix used on a compact IRI term', + 'jsonld.SyntaxError', + {code: 'invalid term definition', context: localCtx}); + } + if(api.isKeyword(mapping['@id'])) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; keywords may not be used as prefixes', + 'jsonld.SyntaxError', + {code: 'invalid term definition', context: localCtx}); + } + if(typeof value['@prefix'] === 'boolean') { + mapping._prefix = value['@prefix'] === true; + } else { + throw new JsonLdError( + 'Invalid JSON-LD syntax; @context value for @prefix must be boolean', + 'jsonld.SyntaxError', + {code: 'invalid @prefix value', context: localCtx}); + } + } + + if('@direction' in value) { + const direction = value['@direction']; + if(direction !== null && direction !== 'ltr' && direction !== 'rtl') { + throw new JsonLdError( + 'Invalid JSON-LD syntax; @direction value must be ' + + 'null, "ltr", or "rtl".', + 'jsonld.SyntaxError', + {code: 'invalid base direction', context: localCtx}); + } + mapping['@direction'] = direction; + } + + if('@nest' in value) { + const nest = value['@nest']; + if(!_isString(nest) || (nest !== '@nest' && nest.indexOf('@') === 0)) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; @context @nest value must be ' + + 'a string which is not a keyword other than @nest.', + 'jsonld.SyntaxError', + {code: 'invalid @nest value', context: localCtx}); + } + mapping['@nest'] = nest; + } + + // disallow aliasing @context and @preserve + const id = mapping['@id']; + if(id === '@context' || id === '@preserve') { + throw new JsonLdError( + 'Invalid JSON-LD syntax; @context and @preserve cannot be aliased.', + 'jsonld.SyntaxError', {code: 'invalid keyword alias', context: localCtx}); + } + + // Check for overriding protected terms + if(previousMapping && previousMapping.protected && !overrideProtected) { + // force new term to continue to be protected and see if the mappings would + // be equal + activeCtx.protected[term] = true; + mapping.protected = true; + if(!_deepCompare(previousMapping, mapping)) { + const protectedMode = (options && options.protectedMode) || 'error'; + if(protectedMode === 'error') { + throw new JsonLdError( + 'Invalid JSON-LD syntax; tried to redefine a protected term.', + 'jsonld.SyntaxError', + {code: 'protected term redefinition', context: localCtx, term}); + } else if(protectedMode === 'warn') { + // FIXME: remove logging and use a handler + console.warn('WARNING: protected term redefinition', {term}); + return; + } + throw new JsonLdError( + 'Invalid protectedMode.', + 'jsonld.SyntaxError', + {code: 'invalid protected mode', context: localCtx, term, + protectedMode}); + } + } +}; + +/** + * Expands a string to a full IRI. The string may be a term, a prefix, a + * relative IRI, or an absolute IRI. The associated absolute IRI will be + * returned. + * + * @param activeCtx the current active context. + * @param value the string to expand. + * @param relativeTo options for how to resolve relative IRIs: + * base: true to resolve against the base IRI, false not to. + * vocab: true to concatenate after @vocab, false not to. + * @param {Object} [options] - processing options. + * + * @return the expanded value. + */ +api.expandIri = (activeCtx, value, relativeTo, options) => { + return _expandIri(activeCtx, value, relativeTo, undefined, undefined, + options); +}; + +/** + * Expands a string to a full IRI. The string may be a term, a prefix, a + * relative IRI, or an absolute IRI. The associated absolute IRI will be + * returned. + * + * @param activeCtx the current active context. + * @param value the string to expand. + * @param relativeTo options for how to resolve relative IRIs: + * base: true to resolve against the base IRI, false not to. + * vocab: true to concatenate after @vocab, false not to. + * @param localCtx the local context being processed (only given if called + * during context processing). + * @param defined a map for tracking cycles in context definitions (only given + * if called during context processing). + * @param {Object} [options] - processing options. + * + * @return the expanded value. + */ +function _expandIri(activeCtx, value, relativeTo, localCtx, defined, options) { + // already expanded + if(value === null || !_isString(value) || api.isKeyword(value)) { + return value; + } + + // ignore non-keyword things that look like a keyword + if(value.match(KEYWORD_PATTERN)) { + return null; + } + + // define term dependency if not defined + if(localCtx && localCtx.hasOwnProperty(value) && + defined.get(value) !== true) { + api.createTermDefinition({ + activeCtx, localCtx, term: value, defined, options + }); + } + + relativeTo = relativeTo || {}; + if(relativeTo.vocab) { + const mapping = activeCtx.mappings.get(value); + + // value is explicitly ignored with a null mapping + if(mapping === null) { + return null; + } + + if(_isObject(mapping) && '@id' in mapping) { + // value is a term + return mapping['@id']; + } + } + + // split value into prefix:suffix + const colon = value.indexOf(':'); + if(colon > 0) { + const prefix = value.substr(0, colon); + const suffix = value.substr(colon + 1); + + // do not expand blank nodes (prefix of '_') or already-absolute + // IRIs (suffix of '//') + if(prefix === '_' || suffix.indexOf('//') === 0) { + return value; + } + + // prefix dependency not defined, define it + if(localCtx && localCtx.hasOwnProperty(prefix)) { + api.createTermDefinition({ + activeCtx, localCtx, term: prefix, defined, options + }); + } + + // use mapping if prefix is defined + const mapping = activeCtx.mappings.get(prefix); + if(mapping && mapping._prefix) { + return mapping['@id'] + suffix; + } + + // already absolute IRI + if(_isAbsoluteIri(value)) { + return value; + } + } + + // prepend vocab + if(relativeTo.vocab && '@vocab' in activeCtx) { + return activeCtx['@vocab'] + value; + } + + // prepend base + if(relativeTo.base && '@base' in activeCtx) { + if(activeCtx['@base']) { + // The null case preserves value as potentially relative + return prependBase(prependBase(options.base, activeCtx['@base']), value); + } + } else if(relativeTo.base) { + return prependBase(options.base, value); + } + + return value; +} + +/** + * Gets the initial context. + * + * @param options the options to use: + * [base] the document base IRI. + * + * @return the initial context. + */ +api.getInitialContext = options => { + const key = JSON.stringify({processingMode: options.processingMode}); + const cached = INITIAL_CONTEXT_CACHE.get(key); + if(cached) { + return cached; + } + + const initialContext = { + processingMode: options.processingMode, + mappings: new Map(), + inverse: null, + getInverse: _createInverseContext, + clone: _cloneActiveContext, + revertToPreviousContext: _revertToPreviousContext, + protected: {} + }; + // TODO: consider using LRU cache instead + if(INITIAL_CONTEXT_CACHE.size === INITIAL_CONTEXT_CACHE_MAX_SIZE) { + // clear whole cache -- assumes scenario where the cache fills means + // the cache isn't being used very efficiently anyway + INITIAL_CONTEXT_CACHE.clear(); + } + INITIAL_CONTEXT_CACHE.set(key, initialContext); + return initialContext; + + /** + * Generates an inverse context for use in the compaction algorithm, if + * not already generated for the given active context. + * + * @return the inverse context. + */ + function _createInverseContext() { + const activeCtx = this; + + // lazily create inverse + if(activeCtx.inverse) { + return activeCtx.inverse; + } + const inverse = activeCtx.inverse = {}; + + // variables for building fast CURIE map + const fastCurieMap = activeCtx.fastCurieMap = {}; + const irisToTerms = {}; + + // handle default language + const defaultLanguage = (activeCtx['@language'] || '@none').toLowerCase(); + + // handle default direction + const defaultDirection = activeCtx['@direction']; + + // create term selections for each mapping in the context, ordered by + // shortest and then lexicographically least + const mappings = activeCtx.mappings; + const terms = [...mappings.keys()].sort(_compareShortestLeast); + for(const term of terms) { + const mapping = mappings.get(term); + if(mapping === null) { + continue; + } + + let container = mapping['@container'] || '@none'; + container = [].concat(container).sort().join(''); + + if(mapping['@id'] === null) { + continue; + } + // iterate over every IRI in the mapping + const ids = _asArray(mapping['@id']); + for(const iri of ids) { + let entry = inverse[iri]; + const isKeyword = api.isKeyword(iri); + + if(!entry) { + // initialize entry + inverse[iri] = entry = {}; + + if(!isKeyword && !mapping._termHasColon) { + // init IRI to term map and fast CURIE prefixes + irisToTerms[iri] = [term]; + const fastCurieEntry = {iri, terms: irisToTerms[iri]}; + if(iri[0] in fastCurieMap) { + fastCurieMap[iri[0]].push(fastCurieEntry); + } else { + fastCurieMap[iri[0]] = [fastCurieEntry]; + } + } + } else if(!isKeyword && !mapping._termHasColon) { + // add IRI to term match + irisToTerms[iri].push(term); + } + + // add new entry + if(!entry[container]) { + entry[container] = { + '@language': {}, + '@type': {}, + '@any': {} + }; + } + entry = entry[container]; + _addPreferredTerm(term, entry['@any'], '@none'); + + if(mapping.reverse) { + // term is preferred for values using @reverse + _addPreferredTerm(term, entry['@type'], '@reverse'); + } else if(mapping['@type'] === '@none') { + _addPreferredTerm(term, entry['@any'], '@none'); + _addPreferredTerm(term, entry['@language'], '@none'); + _addPreferredTerm(term, entry['@type'], '@none'); + } else if('@type' in mapping) { + // term is preferred for values using specific type + _addPreferredTerm(term, entry['@type'], mapping['@type']); + } else if('@language' in mapping && '@direction' in mapping) { + // term is preferred for values using specific language and direction + const language = mapping['@language']; + const direction = mapping['@direction']; + if(language && direction) { + _addPreferredTerm(term, entry['@language'], + `${language}_${direction}`.toLowerCase()); + } else if(language) { + _addPreferredTerm(term, entry['@language'], language.toLowerCase()); + } else if(direction) { + _addPreferredTerm(term, entry['@language'], `_${direction}`); + } else { + _addPreferredTerm(term, entry['@language'], '@null'); + } + } else if('@language' in mapping) { + _addPreferredTerm(term, entry['@language'], + (mapping['@language'] || '@null').toLowerCase()); + } else if('@direction' in mapping) { + if(mapping['@direction']) { + _addPreferredTerm(term, entry['@language'], + `_${mapping['@direction']}`); + } else { + _addPreferredTerm(term, entry['@language'], '@none'); + } + } else if(defaultDirection) { + _addPreferredTerm(term, entry['@language'], `_${defaultDirection}`); + _addPreferredTerm(term, entry['@language'], '@none'); + _addPreferredTerm(term, entry['@type'], '@none'); + } else { + // add entries for no type and no language + _addPreferredTerm(term, entry['@language'], defaultLanguage); + _addPreferredTerm(term, entry['@language'], '@none'); + _addPreferredTerm(term, entry['@type'], '@none'); + } + } + } + + // build fast CURIE map + for(const key in fastCurieMap) { + _buildIriMap(fastCurieMap, key, 1); + } + + return inverse; + } + + /** + * Runs a recursive algorithm to build a lookup map for quickly finding + * potential CURIEs. + * + * @param iriMap the map to build. + * @param key the current key in the map to work on. + * @param idx the index into the IRI to compare. + */ + function _buildIriMap(iriMap, key, idx) { + const entries = iriMap[key]; + const next = iriMap[key] = {}; + + let iri; + let letter; + for(const entry of entries) { + iri = entry.iri; + if(idx >= iri.length) { + letter = ''; + } else { + letter = iri[idx]; + } + if(letter in next) { + next[letter].push(entry); + } else { + next[letter] = [entry]; + } + } + + for(const key in next) { + if(key === '') { + continue; + } + _buildIriMap(next, key, idx + 1); + } + } + + /** + * Adds the term for the given entry if not already added. + * + * @param term the term to add. + * @param entry the inverse context typeOrLanguage entry to add to. + * @param typeOrLanguageValue the key in the entry to add to. + */ + function _addPreferredTerm(term, entry, typeOrLanguageValue) { + if(!entry.hasOwnProperty(typeOrLanguageValue)) { + entry[typeOrLanguageValue] = term; + } + } + + /** + * Clones an active context, creating a child active context. + * + * @return a clone (child) of the active context. + */ + function _cloneActiveContext() { + const child = {}; + child.mappings = util.clone(this.mappings); + child.clone = this.clone; + child.inverse = null; + child.getInverse = this.getInverse; + child.protected = util.clone(this.protected); + if(this.previousContext) { + child.previousContext = this.previousContext.clone(); + } + child.revertToPreviousContext = this.revertToPreviousContext; + if('@base' in this) { + child['@base'] = this['@base']; + } + if('@language' in this) { + child['@language'] = this['@language']; + } + if('@vocab' in this) { + child['@vocab'] = this['@vocab']; + } + return child; + } + + /** + * Reverts any type-scoped context in this active context to the previous + * context. + */ + function _revertToPreviousContext() { + if(!this.previousContext) { + return this; + } + return this.previousContext.clone(); + } +}; + +/** + * Gets the value for the given active context key and type, null if none is + * set or undefined if none is set and type is '@context'. + * + * @param ctx the active context. + * @param key the context key. + * @param [type] the type of value to get (eg: '@id', '@type'), if not + * specified gets the entire entry for a key, null if not found. + * + * @return the value, null, or undefined. + */ +api.getContextValue = (ctx, key, type) => { + // invalid key + if(key === null) { + if(type === '@context') { + return undefined; + } + return null; + } + + // get specific entry information + if(ctx.mappings.has(key)) { + const entry = ctx.mappings.get(key); + + if(_isUndefined(type)) { + // return whole entry + return entry; + } + if(entry.hasOwnProperty(type)) { + // return entry value for type + return entry[type]; + } + } + + // get default language + if(type === '@language' && type in ctx) { + return ctx[type]; + } + + // get default direction + if(type === '@direction' && type in ctx) { + return ctx[type]; + } + + if(type === '@context') { + return undefined; + } + return null; +}; + +/** + * Processing Mode check. + * + * @param activeCtx the current active context. + * @param version the string or numeric version to check. + * + * @return boolean. + */ +api.processingMode = (activeCtx, version) => { + if(version.toString() >= '1.1') { + return !activeCtx.processingMode || + activeCtx.processingMode >= 'json-ld-' + version.toString(); + } else { + return activeCtx.processingMode === 'json-ld-1.0'; + } +}; + +/** + * Returns whether or not the given value is a keyword. + * + * @param v the value to check. + * + * @return true if the value is a keyword, false if not. + */ +api.isKeyword = v => { + if(!_isString(v) || v[0] !== '@') { + return false; + } + switch(v) { + case '@base': + case '@container': + case '@context': + case '@default': + case '@direction': + case '@embed': + case '@explicit': + case '@graph': + case '@id': + case '@included': + case '@index': + case '@json': + case '@language': + case '@list': + case '@nest': + case '@none': + case '@omitDefault': + case '@prefix': + case '@preserve': + case '@protected': + case '@requireAll': + case '@reverse': + case '@set': + case '@type': + case '@value': + case '@version': + case '@vocab': + return true; + } + return false; +}; + +function _deepCompare(x1, x2) { + // compare `null` or primitive types directly + if((!(x1 && typeof x1 === 'object')) || + (!(x2 && typeof x2 === 'object'))) { + return x1 === x2; + } + // x1 and x2 are objects (also potentially arrays) + const x1Array = Array.isArray(x1); + if(x1Array !== Array.isArray(x2)) { + return false; + } + if(x1Array) { + if(x1.length !== x2.length) { + return false; + } + for(let i = 0; i < x1.length; ++i) { + if(!_deepCompare(x1[i], x2[i])) { + return false; + } + } + return true; + } + // x1 and x2 are non-array objects + const k1s = Object.keys(x1); + const k2s = Object.keys(x2); + if(k1s.length !== k2s.length) { + return false; + } + for(const k1 in x1) { + let v1 = x1[k1]; + let v2 = x2[k1]; + // special case: `@container` can be in any order + if(k1 === '@container') { + if(Array.isArray(v1) && Array.isArray(v2)) { + v1 = v1.slice().sort(); + v2 = v2.slice().sort(); + } + } + if(!_deepCompare(v1, v2)) { + return false; + } + } + return true; +} + + +/***/ }), + +/***/ "./node_modules/jsonld/lib/documentLoaders/node.js": +/*!*********************************************************!*\ + !*** ./node_modules/jsonld/lib/documentLoaders/node.js ***! + \*********************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* + * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved. + */ + + +const {parseLinkHeader, buildHeaders} = __webpack_require__(/*! ../util */ "./node_modules/jsonld/lib/util.js"); +const {LINK_HEADER_CONTEXT} = __webpack_require__(/*! ../constants */ "./node_modules/jsonld/lib/constants.js"); +const JsonLdError = __webpack_require__(/*! ../JsonLdError */ "./node_modules/jsonld/lib/JsonLdError.js"); +const RequestQueue = __webpack_require__(/*! ../RequestQueue */ "./node_modules/jsonld/lib/RequestQueue.js"); +const {prependBase} = __webpack_require__(/*! ../url */ "./node_modules/jsonld/lib/url.js"); + +/** + * Creates a built-in node document loader. + * + * @param options the options to use: + * secure: require all URLs to use HTTPS. + * strictSSL: true to require SSL certificates to be valid, + * false not to (default: true). + * maxRedirects: the maximum number of redirects to permit, none by + * default. + * request: the object which will make the request, default is + * provided by `https://www.npmjs.com/package/request`. + * headers: an object (map) of headers which will be passed as request + * headers for the requested document. Accept is not allowed. + * + * @return the node document loader. + */ +module.exports = ({ + secure, + strictSSL = true, + maxRedirects = -1, + request, + headers = {} +} = {strictSSL: true, maxRedirects: -1, headers: {}}) => { + headers = buildHeaders(headers); + // TODO: use `axios` + request = request || __webpack_require__(/*! request */ 2); + const http = __webpack_require__(/*! http */ 3); + + const queue = new RequestQueue(); + return queue.wrapLoader(function(url) { + return loadDocument(url, []); + }); + + async function loadDocument(url, redirects) { + if(url.indexOf('http:') !== 0 && url.indexOf('https:') !== 0) { + throw new JsonLdError( + 'URL could not be dereferenced; only "http" and "https" URLs are ' + + 'supported.', + 'jsonld.InvalidUrl', {code: 'loading document failed', url}); + } + if(secure && url.indexOf('https') !== 0) { + throw new JsonLdError( + 'URL could not be dereferenced; secure mode is enabled and ' + + 'the URL\'s scheme is not "https".', + 'jsonld.InvalidUrl', {code: 'loading document failed', url}); + } + // TODO: disable cache until HTTP caching implemented + let doc = null;//cache.get(url); + if(doc !== null) { + return doc; + } + + let result; + let alternate = null; + try { + result = await _request(request, { + url, + headers, + strictSSL, + followRedirect: false + }); + } catch(e) { + throw new JsonLdError( + 'URL could not be dereferenced, an error occurred.', + 'jsonld.LoadDocumentError', + {code: 'loading document failed', url, cause: e}); + } + + const {res, body} = result; + + doc = {contextUrl: null, documentUrl: url, document: body || null}; + + // handle error + const statusText = http.STATUS_CODES[res.statusCode]; + if(res.statusCode >= 400) { + throw new JsonLdError( + `URL "${url}" could not be dereferenced: ${statusText}`, + 'jsonld.InvalidUrl', { + code: 'loading document failed', + url, + httpStatusCode: res.statusCode + }); + } + + // handle Link Header + if(res.headers.link && + res.headers['content-type'] !== 'application/ld+json') { + // only 1 related link header permitted + const linkHeaders = parseLinkHeader(res.headers.link); + const linkedContext = linkHeaders[LINK_HEADER_CONTEXT]; + if(Array.isArray(linkedContext)) { + throw new JsonLdError( + 'URL could not be dereferenced, it has more than one associated ' + + 'HTTP Link Header.', + 'jsonld.InvalidUrl', + {code: 'multiple context link headers', url}); + } + if(linkedContext) { + doc.contextUrl = linkedContext.target; + } + + // "alternate" link header is a redirect + alternate = linkHeaders['alternate']; + if(alternate && + alternate.type == 'application/ld+json' && + !(res.headers['content-type'] || '') + .match(/^application\/(\w*\+)?json$/)) { + res.headers.location = prependBase(url, alternate.target); + } + } + + // handle redirect + if((alternate || + res.statusCode >= 300 && res.statusCode < 400) && res.headers.location) { + if(redirects.length === maxRedirects) { + throw new JsonLdError( + 'URL could not be dereferenced; there were too many redirects.', + 'jsonld.TooManyRedirects', { + code: 'loading document failed', + url, + httpStatusCode: res.statusCode, + redirects + }); + } + if(redirects.indexOf(url) !== -1) { + throw new JsonLdError( + 'URL could not be dereferenced; infinite redirection was detected.', + 'jsonld.InfiniteRedirectDetected', { + code: 'recursive context inclusion', + url, + httpStatusCode: res.statusCode, + redirects + }); + } + redirects.push(url); + return loadDocument(res.headers.location, redirects); + } + + // cache for each redirected URL + redirects.push(url); + // TODO: disable cache until HTTP caching implemented + /* + for(let i = 0; i < redirects.length; ++i) { + cache.set( + redirects[i], + {contextUrl: null, documentUrl: redirects[i], document: body}); + } + */ + + return doc; + } +}; + +function _request(request, options) { + return new Promise((resolve, reject) => { + request(options, (err, res, body) => { + if(err) { + reject(err); + } else { + resolve({res, body}); + } + }); + }); +} + + +/***/ }), + +/***/ "./node_modules/jsonld/lib/documentLoaders/xhr.js": +/*!********************************************************!*\ + !*** ./node_modules/jsonld/lib/documentLoaders/xhr.js ***! + \********************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* + * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved. + */ + + +const {parseLinkHeader, buildHeaders} = __webpack_require__(/*! ../util */ "./node_modules/jsonld/lib/util.js"); +const {LINK_HEADER_CONTEXT} = __webpack_require__(/*! ../constants */ "./node_modules/jsonld/lib/constants.js"); +const JsonLdError = __webpack_require__(/*! ../JsonLdError */ "./node_modules/jsonld/lib/JsonLdError.js"); +const RequestQueue = __webpack_require__(/*! ../RequestQueue */ "./node_modules/jsonld/lib/RequestQueue.js"); +const {prependBase} = __webpack_require__(/*! ../url */ "./node_modules/jsonld/lib/url.js"); + +const REGEX_LINK_HEADER = /(^|(\r\n))link:/i; + +/** + * Creates a built-in XMLHttpRequest document loader. + * + * @param options the options to use: + * secure: require all URLs to use HTTPS. + * headers: an object (map) of headers which will be passed as request + * headers for the requested document. Accept is not allowed. + * [xhr]: the XMLHttpRequest API to use. + * + * @return the XMLHttpRequest document loader. + */ +module.exports = ({ + secure, + headers = {}, + xhr +} = {headers: {}}) => { + headers = buildHeaders(headers); + const queue = new RequestQueue(); + return queue.wrapLoader(loader); + + async function loader(url) { + if(url.indexOf('http:') !== 0 && url.indexOf('https:') !== 0) { + throw new JsonLdError( + 'URL could not be dereferenced; only "http" and "https" URLs are ' + + 'supported.', + 'jsonld.InvalidUrl', {code: 'loading document failed', url}); + } + if(secure && url.indexOf('https') !== 0) { + throw new JsonLdError( + 'URL could not be dereferenced; secure mode is enabled and ' + + 'the URL\'s scheme is not "https".', + 'jsonld.InvalidUrl', {code: 'loading document failed', url}); + } + + let req; + try { + req = await _get(xhr, url, headers); + } catch(e) { + throw new JsonLdError( + 'URL could not be dereferenced, an error occurred.', + 'jsonld.LoadDocumentError', + {code: 'loading document failed', url, cause: e}); + } + + if(req.status >= 400) { + throw new JsonLdError( + 'URL could not be dereferenced: ' + req.statusText, + 'jsonld.LoadDocumentError', { + code: 'loading document failed', + url, + httpStatusCode: req.status + }); + } + + let doc = {contextUrl: null, documentUrl: url, document: req.response}; + let alternate = null; + + // handle Link Header (avoid unsafe header warning by existence testing) + const contentType = req.getResponseHeader('Content-Type'); + let linkHeader; + if(REGEX_LINK_HEADER.test(req.getAllResponseHeaders())) { + linkHeader = req.getResponseHeader('Link'); + } + if(linkHeader && contentType !== 'application/ld+json') { + // only 1 related link header permitted + const linkHeaders = parseLinkHeader(linkHeader); + const linkedContext = linkHeaders[LINK_HEADER_CONTEXT]; + if(Array.isArray(linkedContext)) { + throw new JsonLdError( + 'URL could not be dereferenced, it has more than one ' + + 'associated HTTP Link Header.', + 'jsonld.InvalidUrl', + {code: 'multiple context link headers', url}); + } + if(linkedContext) { + doc.contextUrl = linkedContext.target; + } + + // "alternate" link header is a redirect + alternate = linkHeaders['alternate']; + if(alternate && + alternate.type == 'application/ld+json' && + !(contentType || '').match(/^application\/(\w*\+)?json$/)) { + doc = await loader(prependBase(url, alternate.target)); + } + } + + return doc; + } +}; + +function _get(xhr, url, headers) { + xhr = xhr || XMLHttpRequest; + const req = new xhr(); + return new Promise((resolve, reject) => { + req.onload = () => resolve(req); + req.onerror = err => reject(err); + req.open('GET', url, true); + for(const k in headers) { + req.setRequestHeader(k, headers[k]); + } + req.send(); + }); +} + + +/***/ }), + +/***/ "./node_modules/jsonld/lib/expand.js": +/*!*******************************************!*\ + !*** ./node_modules/jsonld/lib/expand.js ***! + \*******************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* + * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved. + */ + + +const JsonLdError = __webpack_require__(/*! ./JsonLdError */ "./node_modules/jsonld/lib/JsonLdError.js"); + +const { + isArray: _isArray, + isObject: _isObject, + isEmptyObject: _isEmptyObject, + isString: _isString, + isUndefined: _isUndefined +} = __webpack_require__(/*! ./types */ "./node_modules/jsonld/lib/types.js"); + +const { + isList: _isList, + isValue: _isValue, + isGraph: _isGraph, + isSubject: _isSubject +} = __webpack_require__(/*! ./graphTypes */ "./node_modules/jsonld/lib/graphTypes.js"); + +const { + expandIri: _expandIri, + getContextValue: _getContextValue, + isKeyword: _isKeyword, + process: _processContext, + processingMode: _processingMode +} = __webpack_require__(/*! ./context */ "./node_modules/jsonld/lib/context.js"); + +const { + isAbsolute: _isAbsoluteIri +} = __webpack_require__(/*! ./url */ "./node_modules/jsonld/lib/url.js"); + +const { + addValue: _addValue, + asArray: _asArray, + getValues: _getValues, + validateTypeValue: _validateTypeValue +} = __webpack_require__(/*! ./util */ "./node_modules/jsonld/lib/util.js"); + +const api = {}; +module.exports = api; +const REGEX_BCP47 = /^[a-zA-Z]{1,8}(-[a-zA-Z0-9]{1,8})*$/; + +/** + * Recursively expands an element using the given context. Any context in + * the element will be removed. All context URLs must have been retrieved + * before calling this method. + * + * @param activeCtx the context to use. + * @param activeProperty the property for the element, null for none. + * @param element the element to expand. + * @param options the expansion options. + * @param insideList true if the element is a list, false if not. + * @param insideIndex true if the element is inside an index container, + * false if not. + * @param typeScopedContext an optional type-scoped active context for + * expanding values of nodes that were expressed according to + * a type-scoped context. + * @param expansionMap(info) a function that can be used to custom map + * unmappable values (or to throw an error when they are detected); + * if this function returns `undefined` then the default behavior + * will be used. + * + * @return a Promise that resolves to the expanded value. + */ +api.expand = async ({ + activeCtx, + activeProperty = null, + element, + options = {}, + insideList = false, + insideIndex = false, + typeScopedContext = null, + expansionMap = () => undefined +}) => { + // nothing to expand + if(element === null || element === undefined) { + return null; + } + + // disable framing if activeProperty is @default + if(activeProperty === '@default') { + options = Object.assign({}, options, {isFrame: false}); + } + + if(!_isArray(element) && !_isObject(element)) { + // drop free-floating scalars that are not in lists unless custom mapped + if(!insideList && (activeProperty === null || + _expandIri(activeCtx, activeProperty, {vocab: true}, + options) === '@graph')) { + const mapped = await expansionMap({ + unmappedValue: element, + activeCtx, + activeProperty, + options, + insideList + }); + if(mapped === undefined) { + return null; + } + return mapped; + } + + // expand element according to value expansion rules + return _expandValue({activeCtx, activeProperty, value: element, options}); + } + + // recursively expand array + if(_isArray(element)) { + let rval = []; + const container = _getContextValue( + activeCtx, activeProperty, '@container') || []; + insideList = insideList || container.includes('@list'); + for(let i = 0; i < element.length; ++i) { + // expand element + let e = await api.expand({ + activeCtx, + activeProperty, + element: element[i], + options, + expansionMap, + insideIndex, + typeScopedContext + }); + if(insideList && _isArray(e)) { + e = {'@list': e}; + } + + if(e === null) { + e = await expansionMap({ + unmappedValue: element[i], + activeCtx, + activeProperty, + parent: element, + index: i, + options, + expandedParent: rval, + insideList + }); + if(e === undefined) { + continue; + } + } + + if(_isArray(e)) { + rval = rval.concat(e); + } else { + rval.push(e); + } + } + return rval; + } + + // recursively expand object: + + // first, expand the active property + const expandedActiveProperty = _expandIri( + activeCtx, activeProperty, {vocab: true}, options); + + // Get any property-scoped context for activeProperty + const propertyScopedCtx = + _getContextValue(activeCtx, activeProperty, '@context'); + + // second, determine if any type-scoped context should be reverted; it + // should only be reverted when the following are all true: + // 1. `element` is not a value or subject reference + // 2. `insideIndex` is false + typeScopedContext = typeScopedContext || + (activeCtx.previousContext ? activeCtx : null); + let keys = Object.keys(element).sort(); + let mustRevert = !insideIndex; + if(mustRevert && typeScopedContext && keys.length <= 2 && + !keys.includes('@context')) { + for(const key of keys) { + const expandedProperty = _expandIri( + typeScopedContext, key, {vocab: true}, options); + if(expandedProperty === '@value') { + // value found, ensure type-scoped context is used to expand it + mustRevert = false; + activeCtx = typeScopedContext; + break; + } + if(expandedProperty === '@id' && keys.length === 1) { + // subject reference found, do not revert + mustRevert = false; + break; + } + } + } + + if(mustRevert) { + // revert type scoped context + activeCtx = activeCtx.revertToPreviousContext(); + } + + // apply property-scoped context after reverting term-scoped context + if(!_isUndefined(propertyScopedCtx)) { + activeCtx = await _processContext({ + activeCtx, + localCtx: propertyScopedCtx, + propagate: true, + overrideProtected: true, + options + }); + } + + // if element has a context, process it + if('@context' in element) { + activeCtx = await _processContext( + {activeCtx, localCtx: element['@context'], options}); + } + + // set the type-scoped context to the context on input, for use later + typeScopedContext = activeCtx; + + // Remember the first key found expanding to @type + let typeKey = null; + + // look for scoped contexts on `@type` + for(const key of keys) { + const expandedProperty = _expandIri(activeCtx, key, {vocab: true}, options); + if(expandedProperty === '@type') { + // set scoped contexts from @type + // avoid sorting if possible + typeKey = typeKey || key; + const value = element[key]; + const types = + Array.isArray(value) ? + (value.length > 1 ? value.slice().sort() : value) : [value]; + for(const type of types) { + const ctx = _getContextValue(typeScopedContext, type, '@context'); + if(!_isUndefined(ctx)) { + activeCtx = await _processContext({ + activeCtx, + localCtx: ctx, + options, + propagate: false + }); + } + } + } + } + + // process each key and value in element, ignoring @nest content + let rval = {}; + await _expandObject({ + activeCtx, + activeProperty, + expandedActiveProperty, + element, + expandedParent: rval, + options, + insideList, + typeKey, + typeScopedContext, + expansionMap}); + + // get property count on expanded output + keys = Object.keys(rval); + let count = keys.length; + + if('@value' in rval) { + // @value must only have @language or @type + if('@type' in rval && ('@language' in rval || '@direction' in rval)) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; an element containing "@value" may not ' + + 'contain both "@type" and either "@language" or "@direction".', + 'jsonld.SyntaxError', {code: 'invalid value object', element: rval}); + } + let validCount = count - 1; + if('@type' in rval) { + validCount -= 1; + } + if('@index' in rval) { + validCount -= 1; + } + if('@language' in rval) { + validCount -= 1; + } + if('@direction' in rval) { + validCount -= 1; + } + if(validCount !== 0) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; an element containing "@value" may only ' + + 'have an "@index" property and either "@type" ' + + 'or either or both "@language" or "@direction".', + 'jsonld.SyntaxError', {code: 'invalid value object', element: rval}); + } + const values = rval['@value'] === null ? [] : _asArray(rval['@value']); + const types = _getValues(rval, '@type'); + + // drop null @values unless custom mapped + if(_processingMode(activeCtx, 1.1) && types.includes('@json') && + types.length === 1) { + // Any value of @value is okay if @type: @json + } else if(values.length === 0) { + const mapped = await expansionMap({ + unmappedValue: rval, + activeCtx, + activeProperty, + element, + options, + insideList + }); + if(mapped !== undefined) { + rval = mapped; + } else { + rval = null; + } + } else if(!values.every(v => (_isString(v) || _isEmptyObject(v))) && + '@language' in rval) { + // if @language is present, @value must be a string + throw new JsonLdError( + 'Invalid JSON-LD syntax; only strings may be language-tagged.', + 'jsonld.SyntaxError', + {code: 'invalid language-tagged value', element: rval}); + } else if(!types.every(t => + (_isAbsoluteIri(t) && !(_isString(t) && t.indexOf('_:') === 0) || + _isEmptyObject(t)))) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; an element containing "@value" and "@type" ' + + 'must have an absolute IRI for the value of "@type".', + 'jsonld.SyntaxError', {code: 'invalid typed value', element: rval}); + } + } else if('@type' in rval && !_isArray(rval['@type'])) { + // convert @type to an array + rval['@type'] = [rval['@type']]; + } else if('@set' in rval || '@list' in rval) { + // handle @set and @list + if(count > 1 && !(count === 2 && '@index' in rval)) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; if an element has the property "@set" ' + + 'or "@list", then it can have at most one other property that is ' + + '"@index".', 'jsonld.SyntaxError', + {code: 'invalid set or list object', element: rval}); + } + // optimize away @set + if('@set' in rval) { + rval = rval['@set']; + keys = Object.keys(rval); + count = keys.length; + } + } else if(count === 1 && '@language' in rval) { + // drop objects with only @language unless custom mapped + const mapped = await expansionMap(rval, { + unmappedValue: rval, + activeCtx, + activeProperty, + element, + options, + insideList + }); + if(mapped !== undefined) { + rval = mapped; + } else { + rval = null; + } + } + + // drop certain top-level objects that do not occur in lists, unless custom + // mapped + if(_isObject(rval) && + !options.keepFreeFloatingNodes && !insideList && + (activeProperty === null || expandedActiveProperty === '@graph')) { + // drop empty object, top-level @value/@list, or object with only @id + if(count === 0 || '@value' in rval || '@list' in rval || + (count === 1 && '@id' in rval)) { + const mapped = await expansionMap({ + unmappedValue: rval, + activeCtx, + activeProperty, + element, + options, + insideList + }); + if(mapped !== undefined) { + rval = mapped; + } else { + rval = null; + } + } + } + + return rval; +}; + +/** + * Expand each key and value of element adding to result + * + * @param activeCtx the context to use. + * @param activeProperty the property for the element. + * @param expandedActiveProperty the expansion of activeProperty + * @param element the element to expand. + * @param expandedParent the expanded result into which to add values. + * @param options the expansion options. + * @param insideList true if the element is a list, false if not. + * @param typeKey first key found expanding to @type. + * @param typeScopedContext the context before reverting. + * @param expansionMap(info) a function that can be used to custom map + * unmappable values (or to throw an error when they are detected); + * if this function returns `undefined` then the default behavior + * will be used. + */ +async function _expandObject({ + activeCtx, + activeProperty, + expandedActiveProperty, + element, + expandedParent, + options = {}, + insideList, + typeKey, + typeScopedContext, + expansionMap +}) { + const keys = Object.keys(element).sort(); + const nests = []; + let unexpandedValue; + + // Figure out if this is the type for a JSON literal + const isJsonType = element[typeKey] && + _expandIri(activeCtx, + (_isArray(element[typeKey]) ? element[typeKey][0] : element[typeKey]), + {vocab: true}, options) === '@json'; + + for(const key of keys) { + let value = element[key]; + let expandedValue; + + // skip @context + if(key === '@context') { + continue; + } + + // expand property + let expandedProperty = _expandIri(activeCtx, key, {vocab: true}, options); + + // drop non-absolute IRI keys that aren't keywords unless custom mapped + if(expandedProperty === null || + !(_isAbsoluteIri(expandedProperty) || _isKeyword(expandedProperty))) { + // TODO: use `await` to support async + expandedProperty = expansionMap({ + unmappedProperty: key, + activeCtx, + activeProperty, + parent: element, + options, + insideList, + value, + expandedParent + }); + if(expandedProperty === undefined) { + continue; + } + } + + if(_isKeyword(expandedProperty)) { + if(expandedActiveProperty === '@reverse') { + throw new JsonLdError( + 'Invalid JSON-LD syntax; a keyword cannot be used as a @reverse ' + + 'property.', 'jsonld.SyntaxError', + {code: 'invalid reverse property map', value}); + } + if(expandedProperty in expandedParent && + expandedProperty !== '@included' && + expandedProperty !== '@type') { + throw new JsonLdError( + 'Invalid JSON-LD syntax; colliding keywords detected.', + 'jsonld.SyntaxError', + {code: 'colliding keywords', keyword: expandedProperty}); + } + } + + // syntax error if @id is not a string + if(expandedProperty === '@id') { + if(!_isString(value)) { + if(!options.isFrame) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; "@id" value must a string.', + 'jsonld.SyntaxError', {code: 'invalid @id value', value}); + } + if(_isObject(value)) { + // empty object is a wildcard + if(!_isEmptyObject(value)) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; "@id" value an empty object or array ' + + 'of strings, if framing', + 'jsonld.SyntaxError', {code: 'invalid @id value', value}); + } + } else if(_isArray(value)) { + if(!value.every(v => _isString(v))) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; "@id" value an empty object or array ' + + 'of strings, if framing', + 'jsonld.SyntaxError', {code: 'invalid @id value', value}); + } + } else { + throw new JsonLdError( + 'Invalid JSON-LD syntax; "@id" value an empty object or array ' + + 'of strings, if framing', + 'jsonld.SyntaxError', {code: 'invalid @id value', value}); + } + } + + _addValue( + expandedParent, '@id', + _asArray(value).map(v => + _isString(v) ? _expandIri(activeCtx, v, {base: true}, options) : v), + {propertyIsArray: options.isFrame}); + continue; + } + + if(expandedProperty === '@type') { + // if framing, can be a default object, but need to expand + // key to determine that + if(_isObject(value)) { + value = Object.fromEntries(Object.entries(value).map(([k, v]) => [ + _expandIri(typeScopedContext, k, {vocab: true}), + _asArray(v).map(vv => + _expandIri(typeScopedContext, vv, {base: true, vocab: true}) + ) + ])); + } + _validateTypeValue(value, options.isFrame); + _addValue( + expandedParent, '@type', + _asArray(value).map(v => + _isString(v) ? + _expandIri(typeScopedContext, v, + {base: true, vocab: true}, options) : v), + {propertyIsArray: options.isFrame}); + continue; + } + + // Included blocks are treated as an array of separate object nodes sharing + // the same referencing active_property. + // For 1.0, it is skipped as are other unknown keywords + if(expandedProperty === '@included' && _processingMode(activeCtx, 1.1)) { + const includedResult = _asArray(await api.expand({ + activeCtx, + activeProperty, + element: value, + options, + expansionMap + })); + + // Expanded values must be node objects + if(!includedResult.every(v => _isSubject(v))) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; ' + + 'values of @included must expand to node objects.', + 'jsonld.SyntaxError', {code: 'invalid @included value', value}); + } + + _addValue( + expandedParent, '@included', includedResult, {propertyIsArray: true}); + continue; + } + + // @graph must be an array or an object + if(expandedProperty === '@graph' && + !(_isObject(value) || _isArray(value))) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; "@graph" value must not be an ' + + 'object or an array.', + 'jsonld.SyntaxError', {code: 'invalid @graph value', value}); + } + + if(expandedProperty === '@value') { + // capture value for later + // "colliding keywords" check prevents this from being set twice + unexpandedValue = value; + if(isJsonType && _processingMode(activeCtx, 1.1)) { + // no coercion to array, and retain all values + expandedParent['@value'] = value; + } else { + _addValue( + expandedParent, '@value', value, {propertyIsArray: options.isFrame}); + } + continue; + } + + // @language must be a string + // it should match BCP47 + if(expandedProperty === '@language') { + if(value === null) { + // drop null @language values, they expand as if they didn't exist + continue; + } + if(!_isString(value) && !options.isFrame) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; "@language" value must be a string.', + 'jsonld.SyntaxError', + {code: 'invalid language-tagged string', value}); + } + // ensure language value is lowercase + value = _asArray(value).map(v => _isString(v) ? v.toLowerCase() : v); + + // ensure language tag matches BCP47 + for(const lang of value) { + if(_isString(lang) && !lang.match(REGEX_BCP47)) { + console.warn(`@language must be valid BCP47: ${lang}`); + } + } + + _addValue( + expandedParent, '@language', value, {propertyIsArray: options.isFrame}); + continue; + } + + // @direction must be "ltr" or "rtl" + if(expandedProperty === '@direction') { + if(!_isString(value) && !options.isFrame) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; "@direction" value must be a string.', + 'jsonld.SyntaxError', + {code: 'invalid base direction', value}); + } + + value = _asArray(value); + + // ensure direction is "ltr" or "rtl" + for(const dir of value) { + if(_isString(dir) && dir !== 'ltr' && dir !== 'rtl') { + throw new JsonLdError( + 'Invalid JSON-LD syntax; "@direction" must be "ltr" or "rtl".', + 'jsonld.SyntaxError', + {code: 'invalid base direction', value}); + } + } + + _addValue( + expandedParent, '@direction', value, + {propertyIsArray: options.isFrame}); + continue; + } + + // @index must be a string + if(expandedProperty === '@index') { + if(!_isString(value)) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; "@index" value must be a string.', + 'jsonld.SyntaxError', + {code: 'invalid @index value', value}); + } + _addValue(expandedParent, '@index', value); + continue; + } + + // @reverse must be an object + if(expandedProperty === '@reverse') { + if(!_isObject(value)) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; "@reverse" value must be an object.', + 'jsonld.SyntaxError', {code: 'invalid @reverse value', value}); + } + + expandedValue = await api.expand({ + activeCtx, + activeProperty: + '@reverse', + element: value, + options, + expansionMap + }); + // properties double-reversed + if('@reverse' in expandedValue) { + for(const property in expandedValue['@reverse']) { + _addValue( + expandedParent, property, expandedValue['@reverse'][property], + {propertyIsArray: true}); + } + } + + // FIXME: can this be merged with code below to simplify? + // merge in all reversed properties + let reverseMap = expandedParent['@reverse'] || null; + for(const property in expandedValue) { + if(property === '@reverse') { + continue; + } + if(reverseMap === null) { + reverseMap = expandedParent['@reverse'] = {}; + } + _addValue(reverseMap, property, [], {propertyIsArray: true}); + const items = expandedValue[property]; + for(let ii = 0; ii < items.length; ++ii) { + const item = items[ii]; + if(_isValue(item) || _isList(item)) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; "@reverse" value must not be a ' + + '@value or an @list.', 'jsonld.SyntaxError', + {code: 'invalid reverse property value', value: expandedValue}); + } + _addValue(reverseMap, property, item, {propertyIsArray: true}); + } + } + + continue; + } + + // nested keys + if(expandedProperty === '@nest') { + nests.push(key); + continue; + } + + // use potential scoped context for key + let termCtx = activeCtx; + const ctx = _getContextValue(activeCtx, key, '@context'); + if(!_isUndefined(ctx)) { + termCtx = await _processContext({ + activeCtx, + localCtx: ctx, + propagate: true, + overrideProtected: true, + options + }); + } + + const container = _getContextValue(termCtx, key, '@container') || []; + + if(container.includes('@language') && _isObject(value)) { + const direction = _getContextValue(termCtx, key, '@direction'); + // handle language map container (skip if value is not an object) + expandedValue = _expandLanguageMap(termCtx, value, direction, options); + } else if(container.includes('@index') && _isObject(value)) { + // handle index container (skip if value is not an object) + const asGraph = container.includes('@graph'); + const indexKey = _getContextValue(termCtx, key, '@index') || '@index'; + const propertyIndex = indexKey !== '@index' && + _expandIri(activeCtx, indexKey, {vocab: true}, options); + + expandedValue = await _expandIndexMap({ + activeCtx: termCtx, + options, + activeProperty: key, + value, + expansionMap, + asGraph, + indexKey, + propertyIndex + }); + } else if(container.includes('@id') && _isObject(value)) { + // handle id container (skip if value is not an object) + const asGraph = container.includes('@graph'); + expandedValue = await _expandIndexMap({ + activeCtx: termCtx, + options, + activeProperty: key, + value, + expansionMap, + asGraph, + indexKey: '@id' + }); + } else if(container.includes('@type') && _isObject(value)) { + // handle type container (skip if value is not an object) + expandedValue = await _expandIndexMap({ + // since container is `@type`, revert type scoped context when expanding + activeCtx: termCtx.revertToPreviousContext(), + options, + activeProperty: key, + value, + expansionMap, + asGraph: false, + indexKey: '@type' + }); + } else { + // recurse into @list or @set + const isList = (expandedProperty === '@list'); + if(isList || expandedProperty === '@set') { + let nextActiveProperty = activeProperty; + if(isList && expandedActiveProperty === '@graph') { + nextActiveProperty = null; + } + expandedValue = await api.expand({ + activeCtx: termCtx, + activeProperty: nextActiveProperty, + element: value, + options, + insideList: isList, + expansionMap + }); + } else if( + _getContextValue(activeCtx, key, '@type') === '@json') { + expandedValue = { + '@type': '@json', + '@value': value + }; + } else { + // recursively expand value with key as new active property + expandedValue = await api.expand({ + activeCtx: termCtx, + activeProperty: key, + element: value, + options, + insideList: false, + expansionMap + }); + } + } + + // drop null values if property is not @value + if(expandedValue === null && expandedProperty !== '@value') { + // TODO: use `await` to support async + expandedValue = expansionMap({ + unmappedValue: value, + expandedProperty, + activeCtx: termCtx, + activeProperty, + parent: element, + options, + insideList, + key, + expandedParent + }); + if(expandedValue === undefined) { + continue; + } + } + + // convert expanded value to @list if container specifies it + if(expandedProperty !== '@list' && !_isList(expandedValue) && + container.includes('@list')) { + // ensure expanded value in @list is an array + expandedValue = {'@list': _asArray(expandedValue)}; + } + + // convert expanded value to @graph if container specifies it + // and value is not, itself, a graph + // index cases handled above + if(container.includes('@graph') && + !container.some(key => key === '@id' || key === '@index')) { + // ensure expanded values are arrays + expandedValue = _asArray(expandedValue) + .map(v => ({'@graph': _asArray(v)})); + } + + // FIXME: can this be merged with code above to simplify? + // merge in reverse properties + if(termCtx.mappings.has(key) && termCtx.mappings.get(key).reverse) { + const reverseMap = + expandedParent['@reverse'] = expandedParent['@reverse'] || {}; + expandedValue = _asArray(expandedValue); + for(let ii = 0; ii < expandedValue.length; ++ii) { + const item = expandedValue[ii]; + if(_isValue(item) || _isList(item)) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; "@reverse" value must not be a ' + + '@value or an @list.', 'jsonld.SyntaxError', + {code: 'invalid reverse property value', value: expandedValue}); + } + _addValue(reverseMap, expandedProperty, item, {propertyIsArray: true}); + } + continue; + } + + // add value for property + // special keywords handled above + _addValue(expandedParent, expandedProperty, expandedValue, { + propertyIsArray: true + }); + } + + // @value must not be an object or an array (unless framing) or if @type is + // @json + if('@value' in expandedParent) { + if(expandedParent['@type'] === '@json' && _processingMode(activeCtx, 1.1)) { + // allow any value, to be verified when the object is fully expanded and + // the @type is @json. + } else if((_isObject(unexpandedValue) || _isArray(unexpandedValue)) && + !options.isFrame) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; "@value" value must not be an ' + + 'object or an array.', + 'jsonld.SyntaxError', + {code: 'invalid value object value', value: unexpandedValue}); + } + } + + // expand each nested key + for(const key of nests) { + const nestedValues = _isArray(element[key]) ? element[key] : [element[key]]; + for(const nv of nestedValues) { + if(!_isObject(nv) || Object.keys(nv).some(k => + _expandIri(activeCtx, k, {vocab: true}, options) === '@value')) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; nested value must be a node object.', + 'jsonld.SyntaxError', + {code: 'invalid @nest value', value: nv}); + } + await _expandObject({ + activeCtx, + activeProperty, + expandedActiveProperty, + element: nv, + expandedParent, + options, + insideList, + typeScopedContext, + typeKey, + expansionMap}); + } + } +} + +/** + * Expands the given value by using the coercion and keyword rules in the + * given context. + * + * @param activeCtx the active context to use. + * @param activeProperty the active property the value is associated with. + * @param value the value to expand. + * @param {Object} [options] - processing options. + * + * @return the expanded value. + */ +function _expandValue({activeCtx, activeProperty, value, options}) { + // nothing to expand + if(value === null || value === undefined) { + return null; + } + + // special-case expand @id and @type (skips '@id' expansion) + const expandedProperty = _expandIri( + activeCtx, activeProperty, {vocab: true}, options); + if(expandedProperty === '@id') { + return _expandIri(activeCtx, value, {base: true}, options); + } else if(expandedProperty === '@type') { + return _expandIri(activeCtx, value, {vocab: true, base: true}, options); + } + + // get type definition from context + const type = _getContextValue(activeCtx, activeProperty, '@type'); + + // do @id expansion (automatic for @graph) + if((type === '@id' || expandedProperty === '@graph') && _isString(value)) { + return {'@id': _expandIri(activeCtx, value, {base: true}, options)}; + } + // do @id expansion w/vocab + if(type === '@vocab' && _isString(value)) { + return { + '@id': _expandIri(activeCtx, value, {vocab: true, base: true}, options) + }; + } + + // do not expand keyword values + if(_isKeyword(expandedProperty)) { + return value; + } + + const rval = {}; + + if(type && !['@id', '@vocab', '@none'].includes(type)) { + // other type + rval['@type'] = type; + } else if(_isString(value)) { + // check for language tagging for strings + const language = _getContextValue(activeCtx, activeProperty, '@language'); + if(language !== null) { + rval['@language'] = language; + } + const direction = _getContextValue(activeCtx, activeProperty, '@direction'); + if(direction !== null) { + rval['@direction'] = direction; + } + } + // do conversion of values that aren't basic JSON types to strings + if(!['boolean', 'number', 'string'].includes(typeof value)) { + value = value.toString(); + } + rval['@value'] = value; + + return rval; +} + +/** + * Expands a language map. + * + * @param activeCtx the active context to use. + * @param languageMap the language map to expand. + * @param direction the direction to apply to values. + * @param {Object} [options] - processing options. + * + * @return the expanded language map. + */ +function _expandLanguageMap(activeCtx, languageMap, direction, options) { + const rval = []; + const keys = Object.keys(languageMap).sort(); + for(const key of keys) { + const expandedKey = _expandIri(activeCtx, key, {vocab: true}, options); + let val = languageMap[key]; + if(!_isArray(val)) { + val = [val]; + } + for(const item of val) { + if(item === null) { + // null values are allowed (8.5) but ignored (3.1) + continue; + } + if(!_isString(item)) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; language map values must be strings.', + 'jsonld.SyntaxError', + {code: 'invalid language map value', languageMap}); + } + const val = {'@value': item}; + if(expandedKey !== '@none') { + val['@language'] = key.toLowerCase(); + } + if(direction) { + val['@direction'] = direction; + } + rval.push(val); + } + } + return rval; +} + +async function _expandIndexMap( + {activeCtx, options, activeProperty, value, expansionMap, asGraph, + indexKey, propertyIndex}) { + const rval = []; + const keys = Object.keys(value).sort(); + const isTypeIndex = indexKey === '@type'; + for(let key of keys) { + // if indexKey is @type, there may be a context defined for it + if(isTypeIndex) { + const ctx = _getContextValue(activeCtx, key, '@context'); + if(!_isUndefined(ctx)) { + activeCtx = await _processContext({ + activeCtx, + localCtx: ctx, + propagate: false, + options + }); + } + } + + let val = value[key]; + if(!_isArray(val)) { + val = [val]; + } + + val = await api.expand({ + activeCtx, + activeProperty, + element: val, + options, + insideList: false, + insideIndex: true, + expansionMap + }); + + // expand for @type, but also for @none + let expandedKey; + if(propertyIndex) { + if(key === '@none') { + expandedKey = '@none'; + } else { + expandedKey = _expandValue( + {activeCtx, activeProperty: indexKey, value: key, options}); + } + } else { + expandedKey = _expandIri(activeCtx, key, {vocab: true}, options); + } + + if(indexKey === '@id') { + // expand document relative + key = _expandIri(activeCtx, key, {base: true}, options); + } else if(isTypeIndex) { + key = expandedKey; + } + + for(let item of val) { + // If this is also a @graph container, turn items into graphs + if(asGraph && !_isGraph(item)) { + item = {'@graph': [item]}; + } + if(indexKey === '@type') { + if(expandedKey === '@none') { + // ignore @none + } else if(item['@type']) { + item['@type'] = [key].concat(item['@type']); + } else { + item['@type'] = [key]; + } + } else if(_isValue(item) && + !['@language', '@type', '@index'].includes(indexKey)) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; Attempt to add illegal key to value ' + + `object: "${indexKey}".`, + 'jsonld.SyntaxError', + {code: 'invalid value object', value: item}); + } else if(propertyIndex) { + // index is a property to be expanded, and values interpreted for that + // property + if(expandedKey !== '@none') { + // expand key as a value + _addValue(item, propertyIndex, expandedKey, { + propertyIsArray: true, + prependValue: true + }); + } + } else if(expandedKey !== '@none' && !(indexKey in item)) { + item[indexKey] = key; + } + rval.push(item); + } + } + return rval; +} + + +/***/ }), + +/***/ "./node_modules/jsonld/lib/flatten.js": +/*!********************************************!*\ + !*** ./node_modules/jsonld/lib/flatten.js ***! + \********************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* + * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved. + */ + + +const { + isSubjectReference: _isSubjectReference +} = __webpack_require__(/*! ./graphTypes */ "./node_modules/jsonld/lib/graphTypes.js"); + +const { + createMergedNodeMap: _createMergedNodeMap +} = __webpack_require__(/*! ./nodeMap */ "./node_modules/jsonld/lib/nodeMap.js"); + +const api = {}; +module.exports = api; + +/** + * Performs JSON-LD flattening. + * + * @param input the expanded JSON-LD to flatten. + * + * @return the flattened output. + */ +api.flatten = input => { + const defaultGraph = _createMergedNodeMap(input); + + // produce flattened output + const flattened = []; + const keys = Object.keys(defaultGraph).sort(); + for(let ki = 0; ki < keys.length; ++ki) { + const node = defaultGraph[keys[ki]]; + // only add full subjects to top-level + if(!_isSubjectReference(node)) { + flattened.push(node); + } + } + return flattened; +}; + + +/***/ }), + +/***/ "./node_modules/jsonld/lib/frame.js": +/*!******************************************!*\ + !*** ./node_modules/jsonld/lib/frame.js ***! + \******************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* + * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved. + */ + + +const {isKeyword} = __webpack_require__(/*! ./context */ "./node_modules/jsonld/lib/context.js"); +const graphTypes = __webpack_require__(/*! ./graphTypes */ "./node_modules/jsonld/lib/graphTypes.js"); +const types = __webpack_require__(/*! ./types */ "./node_modules/jsonld/lib/types.js"); +const util = __webpack_require__(/*! ./util */ "./node_modules/jsonld/lib/util.js"); +const url = __webpack_require__(/*! ./url */ "./node_modules/jsonld/lib/url.js"); +const JsonLdError = __webpack_require__(/*! ./JsonLdError */ "./node_modules/jsonld/lib/JsonLdError.js"); +const { + createNodeMap: _createNodeMap, + mergeNodeMapGraphs: _mergeNodeMapGraphs +} = __webpack_require__(/*! ./nodeMap */ "./node_modules/jsonld/lib/nodeMap.js"); + +const api = {}; +module.exports = api; + +/** + * Performs JSON-LD `merged` framing. + * + * @param input the expanded JSON-LD to frame. + * @param frame the expanded JSON-LD frame to use. + * @param options the framing options. + * + * @return the framed output. + */ +api.frameMergedOrDefault = (input, frame, options) => { + // create framing state + const state = { + options, + embedded: false, + graph: '@default', + graphMap: {'@default': {}}, + subjectStack: [], + link: {}, + bnodeMap: {} + }; + + // produce a map of all graphs and name each bnode + // FIXME: currently uses subjects from @merged graph only + const issuer = new util.IdentifierIssuer('_:b'); + _createNodeMap(input, state.graphMap, '@default', issuer); + if(options.merged) { + state.graphMap['@merged'] = _mergeNodeMapGraphs(state.graphMap); + state.graph = '@merged'; + } + state.subjects = state.graphMap[state.graph]; + + // frame the subjects + const framed = []; + api.frame(state, Object.keys(state.subjects).sort(), frame, framed); + + // If pruning blank nodes, find those to prune + if(options.pruneBlankNodeIdentifiers) { + // remove all blank nodes appearing only once, done in compaction + options.bnodesToClear = + Object.keys(state.bnodeMap).filter(id => state.bnodeMap[id].length === 1); + } + + // remove @preserve from results + options.link = {}; + return _cleanupPreserve(framed, options); +}; + +/** + * Frames subjects according to the given frame. + * + * @param state the current framing state. + * @param subjects the subjects to filter. + * @param frame the frame. + * @param parent the parent subject or top-level array. + * @param property the parent property, initialized to null. + */ +api.frame = (state, subjects, frame, parent, property = null) => { + // validate the frame + _validateFrame(frame); + frame = frame[0]; + + // get flags for current frame + const options = state.options; + const flags = { + embed: _getFrameFlag(frame, options, 'embed'), + explicit: _getFrameFlag(frame, options, 'explicit'), + requireAll: _getFrameFlag(frame, options, 'requireAll') + }; + + // get link for current graph + if(!state.link.hasOwnProperty(state.graph)) { + state.link[state.graph] = {}; + } + const link = state.link[state.graph]; + + // filter out subjects that match the frame + const matches = _filterSubjects(state, subjects, frame, flags); + + // add matches to output + const ids = Object.keys(matches).sort(); + for(const id of ids) { + const subject = matches[id]; + + /* Note: In order to treat each top-level match as a compartmentalized + result, clear the unique embedded subjects map when the property is null, + which only occurs at the top-level. */ + if(property === null) { + state.uniqueEmbeds = {[state.graph]: {}}; + } else { + state.uniqueEmbeds[state.graph] = state.uniqueEmbeds[state.graph] || {}; + } + + if(flags.embed === '@link' && id in link) { + // TODO: may want to also match an existing linked subject against + // the current frame ... so different frames could produce different + // subjects that are only shared in-memory when the frames are the same + + // add existing linked subject + _addFrameOutput(parent, property, link[id]); + continue; + } + + // start output for subject + const output = {'@id': id}; + if(id.indexOf('_:') === 0) { + util.addValue(state.bnodeMap, id, output, {propertyIsArray: true}); + } + link[id] = output; + + // validate @embed + if((flags.embed === '@first' || flags.embed === '@last') && state.is11) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; invalid value of @embed.', + 'jsonld.SyntaxError', {code: 'invalid @embed value', frame}); + } + + if(!state.embedded && state.uniqueEmbeds[state.graph].hasOwnProperty(id)) { + // skip adding this node object to the top level, as it was + // already included in another node object + continue; + } + + // if embed is @never or if a circular reference would be created by an + // embed, the subject cannot be embedded, just add the reference; + // note that a circular reference won't occur when the embed flag is + // `@link` as the above check will short-circuit before reaching this point + if(state.embedded && + (flags.embed === '@never' || + _createsCircularReference(subject, state.graph, state.subjectStack))) { + _addFrameOutput(parent, property, output); + continue; + } + + // if only the first (or once) should be embedded + if(state.embedded && + (flags.embed == '@first' || flags.embed == '@once') && + state.uniqueEmbeds[state.graph].hasOwnProperty(id)) { + _addFrameOutput(parent, property, output); + continue; + } + + // if only the last match should be embedded + if(flags.embed === '@last') { + // remove any existing embed + if(id in state.uniqueEmbeds[state.graph]) { + _removeEmbed(state, id); + } + } + + state.uniqueEmbeds[state.graph][id] = {parent, property}; + + // push matching subject onto stack to enable circular embed checks + state.subjectStack.push({subject, graph: state.graph}); + + // subject is also the name of a graph + if(id in state.graphMap) { + let recurse = false; + let subframe = null; + if(!('@graph' in frame)) { + recurse = state.graph !== '@merged'; + subframe = {}; + } else { + subframe = frame['@graph'][0]; + recurse = !(id === '@merged' || id === '@default'); + if(!types.isObject(subframe)) { + subframe = {}; + } + } + + if(recurse) { + // recurse into graph + api.frame( + {...state, graph: id, embedded: false}, + Object.keys(state.graphMap[id]).sort(), [subframe], output, '@graph'); + } + } + + // if frame has @included, recurse over its sub-frame + if('@included' in frame) { + api.frame( + {...state, embedded: false}, + subjects, frame['@included'], output, '@included'); + } + + // iterate over subject properties + for(const prop of Object.keys(subject).sort()) { + // copy keywords to output + if(isKeyword(prop)) { + output[prop] = util.clone(subject[prop]); + + if(prop === '@type') { + // count bnode values of @type + for(const type of subject['@type']) { + if(type.indexOf('_:') === 0) { + util.addValue( + state.bnodeMap, type, output, {propertyIsArray: true}); + } + } + } + continue; + } + + // explicit is on and property isn't in the frame, skip processing + if(flags.explicit && !(prop in frame)) { + continue; + } + + // add objects + for(const o of subject[prop]) { + const subframe = (prop in frame ? + frame[prop] : _createImplicitFrame(flags)); + + // recurse into list + if(graphTypes.isList(o)) { + const subframe = + (frame[prop] && frame[prop][0] && frame[prop][0]['@list']) ? + frame[prop][0]['@list'] : + _createImplicitFrame(flags); + + // add empty list + const list = {'@list': []}; + _addFrameOutput(output, prop, list); + + // add list objects + const src = o['@list']; + for(const oo of src) { + if(graphTypes.isSubjectReference(oo)) { + // recurse into subject reference + api.frame( + {...state, embedded: true}, + [oo['@id']], subframe, list, '@list'); + } else { + // include other values automatically + _addFrameOutput(list, '@list', util.clone(oo)); + } + } + } else if(graphTypes.isSubjectReference(o)) { + // recurse into subject reference + api.frame( + {...state, embedded: true}, + [o['@id']], subframe, output, prop); + } else if(_valueMatch(subframe[0], o)) { + // include other values, if they match + _addFrameOutput(output, prop, util.clone(o)); + } + } + } + + // handle defaults + for(const prop of Object.keys(frame).sort()) { + // skip keywords + if(prop === '@type') { + if(!types.isObject(frame[prop][0]) || + !('@default' in frame[prop][0])) { + continue; + } + // allow through default types + } else if(isKeyword(prop)) { + continue; + } + + // if omit default is off, then include default values for properties + // that appear in the next frame but are not in the matching subject + const next = frame[prop][0] || {}; + const omitDefaultOn = _getFrameFlag(next, options, 'omitDefault'); + if(!omitDefaultOn && !(prop in output)) { + let preserve = '@null'; + if('@default' in next) { + preserve = util.clone(next['@default']); + } + if(!types.isArray(preserve)) { + preserve = [preserve]; + } + output[prop] = [{'@preserve': preserve}]; + } + } + + // if embed reverse values by finding nodes having this subject as a value + // of the associated property + for(const reverseProp of Object.keys(frame['@reverse'] || {}).sort()) { + const subframe = frame['@reverse'][reverseProp]; + for(const subject of Object.keys(state.subjects)) { + const nodeValues = + util.getValues(state.subjects[subject], reverseProp); + if(nodeValues.some(v => v['@id'] === id)) { + // node has property referencing this subject, recurse + output['@reverse'] = output['@reverse'] || {}; + util.addValue( + output['@reverse'], reverseProp, [], {propertyIsArray: true}); + api.frame( + {...state, embedded: true}, + [subject], subframe, output['@reverse'][reverseProp], + property); + } + } + } + + // add output to parent + _addFrameOutput(parent, property, output); + + // pop matching subject from circular ref-checking stack + state.subjectStack.pop(); + } +}; + +/** + * Replace `@null` with `null`, removing it from arrays. + * + * @param input the framed, compacted output. + * @param options the framing options used. + * + * @return the resulting output. + */ +api.cleanupNull = (input, options) => { + // recurse through arrays + if(types.isArray(input)) { + const noNulls = input.map(v => api.cleanupNull(v, options)); + return noNulls.filter(v => v); // removes nulls from array + } + + if(input === '@null') { + return null; + } + + if(types.isObject(input)) { + // handle in-memory linked nodes + if('@id' in input) { + const id = input['@id']; + if(options.link.hasOwnProperty(id)) { + const idx = options.link[id].indexOf(input); + if(idx !== -1) { + // already visited + return options.link[id][idx]; + } + // prevent circular visitation + options.link[id].push(input); + } else { + // prevent circular visitation + options.link[id] = [input]; + } + } + + for(const key in input) { + input[key] = api.cleanupNull(input[key], options); + } + } + return input; +}; + +/** + * Creates an implicit frame when recursing through subject matches. If + * a frame doesn't have an explicit frame for a particular property, then + * a wildcard child frame will be created that uses the same flags that the + * parent frame used. + * + * @param flags the current framing flags. + * + * @return the implicit frame. + */ +function _createImplicitFrame(flags) { + const frame = {}; + for(const key in flags) { + if(flags[key] !== undefined) { + frame['@' + key] = [flags[key]]; + } + } + return [frame]; +} + +/** + * Checks the current subject stack to see if embedding the given subject + * would cause a circular reference. + * + * @param subjectToEmbed the subject to embed. + * @param graph the graph the subject to embed is in. + * @param subjectStack the current stack of subjects. + * + * @return true if a circular reference would be created, false if not. + */ +function _createsCircularReference(subjectToEmbed, graph, subjectStack) { + for(let i = subjectStack.length - 1; i >= 0; --i) { + const subject = subjectStack[i]; + if(subject.graph === graph && + subject.subject['@id'] === subjectToEmbed['@id']) { + return true; + } + } + return false; +} + +/** + * Gets the frame flag value for the given flag name. + * + * @param frame the frame. + * @param options the framing options. + * @param name the flag name. + * + * @return the flag value. + */ +function _getFrameFlag(frame, options, name) { + const flag = '@' + name; + let rval = (flag in frame ? frame[flag][0] : options[name]); + if(name === 'embed') { + // default is "@last" + // backwards-compatibility support for "embed" maps: + // true => "@last" + // false => "@never" + if(rval === true) { + rval = '@once'; + } else if(rval === false) { + rval = '@never'; + } else if(rval !== '@always' && rval !== '@never' && rval !== '@link' && + rval !== '@first' && rval !== '@last' && rval !== '@once') { + throw new JsonLdError( + 'Invalid JSON-LD syntax; invalid value of @embed.', + 'jsonld.SyntaxError', {code: 'invalid @embed value', frame}); + } + } + return rval; +} + +/** + * Validates a JSON-LD frame, throwing an exception if the frame is invalid. + * + * @param frame the frame to validate. + */ +function _validateFrame(frame) { + if(!types.isArray(frame) || frame.length !== 1 || !types.isObject(frame[0])) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; a JSON-LD frame must be a single object.', + 'jsonld.SyntaxError', {frame}); + } + + if('@id' in frame[0]) { + for(const id of util.asArray(frame[0]['@id'])) { + // @id must be wildcard or an IRI + if(!(types.isObject(id) || url.isAbsolute(id)) || + (types.isString(id) && id.indexOf('_:') === 0)) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; invalid @id in frame.', + 'jsonld.SyntaxError', {code: 'invalid frame', frame}); + } + } + } + + if('@type' in frame[0]) { + for(const type of util.asArray(frame[0]['@type'])) { + // @id must be wildcard or an IRI + if(!(types.isObject(type) || url.isAbsolute(type)) || + (types.isString(type) && type.indexOf('_:') === 0)) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; invalid @type in frame.', + 'jsonld.SyntaxError', {code: 'invalid frame', frame}); + } + } + } +} + +/** + * Returns a map of all of the subjects that match a parsed frame. + * + * @param state the current framing state. + * @param subjects the set of subjects to filter. + * @param frame the parsed frame. + * @param flags the frame flags. + * + * @return all of the matched subjects. + */ +function _filterSubjects(state, subjects, frame, flags) { + // filter subjects in @id order + const rval = {}; + for(const id of subjects) { + const subject = state.graphMap[state.graph][id]; + if(_filterSubject(state, subject, frame, flags)) { + rval[id] = subject; + } + } + return rval; +} + +/** + * Returns true if the given subject matches the given frame. + * + * Matches either based on explicit type inclusion where the node has any + * type listed in the frame. If the frame has empty types defined matches + * nodes not having a @type. If the frame has a type of {} defined matches + * nodes having any type defined. + * + * Otherwise, does duck typing, where the node must have all of the + * properties defined in the frame. + * + * @param state the current framing state. + * @param subject the subject to check. + * @param frame the frame to check. + * @param flags the frame flags. + * + * @return true if the subject matches, false if not. + */ +function _filterSubject(state, subject, frame, flags) { + // check ducktype + let wildcard = true; + let matchesSome = false; + + for(const key in frame) { + let matchThis = false; + const nodeValues = util.getValues(subject, key); + const isEmpty = util.getValues(frame, key).length === 0; + + if(key === '@id') { + // match on no @id or any matching @id, including wildcard + if(types.isEmptyObject(frame['@id'][0] || {})) { + matchThis = true; + } else if(frame['@id'].length >= 0) { + matchThis = frame['@id'].includes(nodeValues[0]); + } + if(!flags.requireAll) { + return matchThis; + } + } else if(key === '@type') { + // check @type (object value means 'any' type, + // fall through to ducktyping) + wildcard = false; + if(isEmpty) { + if(nodeValues.length > 0) { + // don't match on no @type + return false; + } + matchThis = true; + } else if(frame['@type'].length === 1 && + types.isEmptyObject(frame['@type'][0])) { + // match on wildcard @type if there is a type + matchThis = nodeValues.length > 0; + } else { + // match on a specific @type + for(const type of frame['@type']) { + if(types.isObject(type) && '@default' in type) { + // match on default object + matchThis = true; + } else { + matchThis = matchThis || nodeValues.some(tt => tt === type); + } + } + } + if(!flags.requireAll) { + return matchThis; + } + } else if(isKeyword(key)) { + continue; + } else { + // Force a copy of this frame entry so it can be manipulated + const thisFrame = util.getValues(frame, key)[0]; + let hasDefault = false; + if(thisFrame) { + _validateFrame([thisFrame]); + hasDefault = '@default' in thisFrame; + } + + // no longer a wildcard pattern if frame has any non-keyword properties + wildcard = false; + + // skip, but allow match if node has no value for property, and frame has + // a default value + if(nodeValues.length === 0 && hasDefault) { + continue; + } + + // if frame value is empty, don't match if subject has any value + if(nodeValues.length > 0 && isEmpty) { + return false; + } + + if(thisFrame === undefined) { + // node does not match if values is not empty and the value of property + // in frame is match none. + if(nodeValues.length > 0) { + return false; + } + matchThis = true; + } else { + if(graphTypes.isList(thisFrame)) { + const listValue = thisFrame['@list'][0]; + if(graphTypes.isList(nodeValues[0])) { + const nodeListValues = nodeValues[0]['@list']; + + if(graphTypes.isValue(listValue)) { + // match on any matching value + matchThis = nodeListValues.some(lv => _valueMatch(listValue, lv)); + } else if(graphTypes.isSubject(listValue) || + graphTypes.isSubjectReference(listValue)) { + matchThis = nodeListValues.some(lv => _nodeMatch( + state, listValue, lv, flags)); + } + } + } else if(graphTypes.isValue(thisFrame)) { + matchThis = nodeValues.some(nv => _valueMatch(thisFrame, nv)); + } else if(graphTypes.isSubjectReference(thisFrame)) { + matchThis = + nodeValues.some(nv => _nodeMatch(state, thisFrame, nv, flags)); + } else if(types.isObject(thisFrame)) { + matchThis = nodeValues.length > 0; + } else { + matchThis = false; + } + } + } + + // all non-defaulted values must match if requireAll is set + if(!matchThis && flags.requireAll) { + return false; + } + + matchesSome = matchesSome || matchThis; + } + + // return true if wildcard or subject matches some properties + return wildcard || matchesSome; +} + +/** + * Removes an existing embed. + * + * @param state the current framing state. + * @param id the @id of the embed to remove. + */ +function _removeEmbed(state, id) { + // get existing embed + const embeds = state.uniqueEmbeds[state.graph]; + const embed = embeds[id]; + const parent = embed.parent; + const property = embed.property; + + // create reference to replace embed + const subject = {'@id': id}; + + // remove existing embed + if(types.isArray(parent)) { + // replace subject with reference + for(let i = 0; i < parent.length; ++i) { + if(util.compareValues(parent[i], subject)) { + parent[i] = subject; + break; + } + } + } else { + // replace subject with reference + const useArray = types.isArray(parent[property]); + util.removeValue(parent, property, subject, {propertyIsArray: useArray}); + util.addValue(parent, property, subject, {propertyIsArray: useArray}); + } + + // recursively remove dependent dangling embeds + const removeDependents = id => { + // get embed keys as a separate array to enable deleting keys in map + const ids = Object.keys(embeds); + for(const next of ids) { + if(next in embeds && types.isObject(embeds[next].parent) && + embeds[next].parent['@id'] === id) { + delete embeds[next]; + removeDependents(next); + } + } + }; + removeDependents(id); +} + +/** + * Removes the @preserve keywords from expanded result of framing. + * + * @param input the framed, framed output. + * @param options the framing options used. + * + * @return the resulting output. + */ +function _cleanupPreserve(input, options) { + // recurse through arrays + if(types.isArray(input)) { + return input.map(value => _cleanupPreserve(value, options)); + } + + if(types.isObject(input)) { + // remove @preserve + if('@preserve' in input) { + return input['@preserve'][0]; + } + + // skip @values + if(graphTypes.isValue(input)) { + return input; + } + + // recurse through @lists + if(graphTypes.isList(input)) { + input['@list'] = _cleanupPreserve(input['@list'], options); + return input; + } + + // handle in-memory linked nodes + if('@id' in input) { + const id = input['@id']; + if(options.link.hasOwnProperty(id)) { + const idx = options.link[id].indexOf(input); + if(idx !== -1) { + // already visited + return options.link[id][idx]; + } + // prevent circular visitation + options.link[id].push(input); + } else { + // prevent circular visitation + options.link[id] = [input]; + } + } + + // recurse through properties + for(const prop in input) { + // potentially remove the id, if it is an unreference bnode + if(prop === '@id' && options.bnodesToClear.includes(input[prop])) { + delete input['@id']; + continue; + } + + input[prop] = _cleanupPreserve(input[prop], options); + } + } + return input; +} + +/** + * Adds framing output to the given parent. + * + * @param parent the parent to add to. + * @param property the parent property. + * @param output the output to add. + */ +function _addFrameOutput(parent, property, output) { + if(types.isObject(parent)) { + util.addValue(parent, property, output, {propertyIsArray: true}); + } else { + parent.push(output); + } +} + +/** + * Node matches if it is a node, and matches the pattern as a frame. + * + * @param state the current framing state. + * @param pattern used to match value + * @param value to check + * @param flags the frame flags. + */ +function _nodeMatch(state, pattern, value, flags) { + if(!('@id' in value)) { + return false; + } + const nodeObject = state.subjects[value['@id']]; + return nodeObject && _filterSubject(state, nodeObject, pattern, flags); +} + +/** + * Value matches if it is a value and matches the value pattern + * + * * `pattern` is empty + * * @values are the same, or `pattern[@value]` is a wildcard, and + * * @types are the same or `value[@type]` is not null + * and `pattern[@type]` is `{}`, or `value[@type]` is null + * and `pattern[@type]` is null or `[]`, and + * * @languages are the same or `value[@language]` is not null + * and `pattern[@language]` is `{}`, or `value[@language]` is null + * and `pattern[@language]` is null or `[]`. + * + * @param pattern used to match value + * @param value to check + */ +function _valueMatch(pattern, value) { + const v1 = value['@value']; + const t1 = value['@type']; + const l1 = value['@language']; + const v2 = pattern['@value'] ? + (types.isArray(pattern['@value']) ? + pattern['@value'] : [pattern['@value']]) : + []; + const t2 = pattern['@type'] ? + (types.isArray(pattern['@type']) ? + pattern['@type'] : [pattern['@type']]) : + []; + const l2 = pattern['@language'] ? + (types.isArray(pattern['@language']) ? + pattern['@language'] : [pattern['@language']]) : + []; + + if(v2.length === 0 && t2.length === 0 && l2.length === 0) { + return true; + } + if(!(v2.includes(v1) || types.isEmptyObject(v2[0]))) { + return false; + } + if(!(!t1 && t2.length === 0 || t2.includes(t1) || t1 && + types.isEmptyObject(t2[0]))) { + return false; + } + if(!(!l1 && l2.length === 0 || l2.includes(l1) || l1 && + types.isEmptyObject(l2[0]))) { + return false; + } + return true; +} + + +/***/ }), + +/***/ "./node_modules/jsonld/lib/fromRdf.js": +/*!********************************************!*\ + !*** ./node_modules/jsonld/lib/fromRdf.js ***! + \********************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* + * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved. + */ + + +const JsonLdError = __webpack_require__(/*! ./JsonLdError */ "./node_modules/jsonld/lib/JsonLdError.js"); +const graphTypes = __webpack_require__(/*! ./graphTypes */ "./node_modules/jsonld/lib/graphTypes.js"); +const types = __webpack_require__(/*! ./types */ "./node_modules/jsonld/lib/types.js"); +const util = __webpack_require__(/*! ./util */ "./node_modules/jsonld/lib/util.js"); + +// constants +const { + // RDF, + RDF_LIST, + RDF_FIRST, + RDF_REST, + RDF_NIL, + RDF_TYPE, + // RDF_PLAIN_LITERAL, + // RDF_XML_LITERAL, + RDF_JSON_LITERAL, + // RDF_OBJECT, + // RDF_LANGSTRING, + + // XSD, + XSD_BOOLEAN, + XSD_DOUBLE, + XSD_INTEGER, + XSD_STRING, +} = __webpack_require__(/*! ./constants */ "./node_modules/jsonld/lib/constants.js"); + +const REGEX_BCP47 = /^[a-zA-Z]{1,8}(-[a-zA-Z0-9]{1,8})*$/; + +const api = {}; +module.exports = api; + +/** + * Converts an RDF dataset to JSON-LD. + * + * @param dataset the RDF dataset. + * @param options the RDF serialization options. + * + * @return a Promise that resolves to the JSON-LD output. + */ +api.fromRDF = async ( + dataset, + { + useRdfType = false, + useNativeTypes = false, + rdfDirection = null + } +) => { + const defaultGraph = {}; + const graphMap = {'@default': defaultGraph}; + const referencedOnce = {}; + + for(const quad of dataset) { + // TODO: change 'name' to 'graph' + const name = (quad.graph.termType === 'DefaultGraph') ? + '@default' : quad.graph.value; + if(!(name in graphMap)) { + graphMap[name] = {}; + } + if(name !== '@default' && !(name in defaultGraph)) { + defaultGraph[name] = {'@id': name}; + } + + const nodeMap = graphMap[name]; + + // get subject, predicate, object + const s = quad.subject.value; + const p = quad.predicate.value; + const o = quad.object; + + if(!(s in nodeMap)) { + nodeMap[s] = {'@id': s}; + } + const node = nodeMap[s]; + + const objectIsNode = o.termType.endsWith('Node'); + if(objectIsNode && !(o.value in nodeMap)) { + nodeMap[o.value] = {'@id': o.value}; + } + + if(p === RDF_TYPE && !useRdfType && objectIsNode) { + util.addValue(node, '@type', o.value, {propertyIsArray: true}); + continue; + } + + const value = _RDFToObject(o, useNativeTypes, rdfDirection); + util.addValue(node, p, value, {propertyIsArray: true}); + + // object may be an RDF list/partial list node but we can't know easily + // until all triples are read + if(objectIsNode) { + if(o.value === RDF_NIL) { + // track rdf:nil uniquely per graph + const object = nodeMap[o.value]; + if(!('usages' in object)) { + object.usages = []; + } + object.usages.push({ + node, + property: p, + value + }); + } else if(o.value in referencedOnce) { + // object referenced more than once + referencedOnce[o.value] = false; + } else { + // keep track of single reference + referencedOnce[o.value] = { + node, + property: p, + value + }; + } + } + } + + /* + for(let name in dataset) { + const graph = dataset[name]; + if(!(name in graphMap)) { + graphMap[name] = {}; + } + if(name !== '@default' && !(name in defaultGraph)) { + defaultGraph[name] = {'@id': name}; + } + const nodeMap = graphMap[name]; + for(let ti = 0; ti < graph.length; ++ti) { + const triple = graph[ti]; + + // get subject, predicate, object + const s = triple.subject.value; + const p = triple.predicate.value; + const o = triple.object; + + if(!(s in nodeMap)) { + nodeMap[s] = {'@id': s}; + } + const node = nodeMap[s]; + + const objectIsId = (o.type === 'IRI' || o.type === 'blank node'); + if(objectIsId && !(o.value in nodeMap)) { + nodeMap[o.value] = {'@id': o.value}; + } + + if(p === RDF_TYPE && !useRdfType && objectIsId) { + util.addValue(node, '@type', o.value, {propertyIsArray: true}); + continue; + } + + const value = _RDFToObject(o, useNativeTypes); + util.addValue(node, p, value, {propertyIsArray: true}); + + // object may be an RDF list/partial list node but we can't know easily + // until all triples are read + if(objectIsId) { + if(o.value === RDF_NIL) { + // track rdf:nil uniquely per graph + const object = nodeMap[o.value]; + if(!('usages' in object)) { + object.usages = []; + } + object.usages.push({ + node: node, + property: p, + value: value + }); + } else if(o.value in referencedOnce) { + // object referenced more than once + referencedOnce[o.value] = false; + } else { + // keep track of single reference + referencedOnce[o.value] = { + node: node, + property: p, + value: value + }; + } + } + } + }*/ + + // convert linked lists to @list arrays + for(const name in graphMap) { + const graphObject = graphMap[name]; + + // no @lists to be converted, continue + if(!(RDF_NIL in graphObject)) { + continue; + } + + // iterate backwards through each RDF list + const nil = graphObject[RDF_NIL]; + if(!nil.usages) { + continue; + } + for(let usage of nil.usages) { + let node = usage.node; + let property = usage.property; + let head = usage.value; + const list = []; + const listNodes = []; + + // ensure node is a well-formed list node; it must: + // 1. Be referenced only once. + // 2. Have an array for rdf:first that has 1 item. + // 3. Have an array for rdf:rest that has 1 item. + // 4. Have no keys other than: @id, rdf:first, rdf:rest, and, + // optionally, @type where the value is rdf:List. + let nodeKeyCount = Object.keys(node).length; + while(property === RDF_REST && + types.isObject(referencedOnce[node['@id']]) && + types.isArray(node[RDF_FIRST]) && node[RDF_FIRST].length === 1 && + types.isArray(node[RDF_REST]) && node[RDF_REST].length === 1 && + (nodeKeyCount === 3 || + (nodeKeyCount === 4 && types.isArray(node['@type']) && + node['@type'].length === 1 && node['@type'][0] === RDF_LIST))) { + list.push(node[RDF_FIRST][0]); + listNodes.push(node['@id']); + + // get next node, moving backwards through list + usage = referencedOnce[node['@id']]; + node = usage.node; + property = usage.property; + head = usage.value; + nodeKeyCount = Object.keys(node).length; + + // if node is not a blank node, then list head found + if(!graphTypes.isBlankNode(node)) { + break; + } + } + + // transform list into @list object + delete head['@id']; + head['@list'] = list.reverse(); + for(const listNode of listNodes) { + delete graphObject[listNode]; + } + } + + delete nil.usages; + } + + const result = []; + const subjects = Object.keys(defaultGraph).sort(); + for(const subject of subjects) { + const node = defaultGraph[subject]; + if(subject in graphMap) { + const graph = node['@graph'] = []; + const graphObject = graphMap[subject]; + const graphSubjects = Object.keys(graphObject).sort(); + for(const graphSubject of graphSubjects) { + const node = graphObject[graphSubject]; + // only add full subjects to top-level + if(!graphTypes.isSubjectReference(node)) { + graph.push(node); + } + } + } + // only add full subjects to top-level + if(!graphTypes.isSubjectReference(node)) { + result.push(node); + } + } + + return result; +}; + +/** + * Converts an RDF triple object to a JSON-LD object. + * + * @param o the RDF triple object to convert. + * @param useNativeTypes true to output native types, false not to. + * + * @return the JSON-LD object. + */ +function _RDFToObject(o, useNativeTypes, rdfDirection) { + // convert NamedNode/BlankNode object to JSON-LD + if(o.termType.endsWith('Node')) { + return {'@id': o.value}; + } + + // convert literal to JSON-LD + const rval = {'@value': o.value}; + + // add language + if(o.language) { + rval['@language'] = o.language; + } else { + let type = o.datatype.value; + if(!type) { + type = XSD_STRING; + } + if(type === RDF_JSON_LITERAL) { + type = '@json'; + try { + rval['@value'] = JSON.parse(rval['@value']); + } catch(e) { + throw new JsonLdError( + 'JSON literal could not be parsed.', + 'jsonld.InvalidJsonLiteral', + {code: 'invalid JSON literal', value: rval['@value'], cause: e}); + } + } + // use native types for certain xsd types + if(useNativeTypes) { + if(type === XSD_BOOLEAN) { + if(rval['@value'] === 'true') { + rval['@value'] = true; + } else if(rval['@value'] === 'false') { + rval['@value'] = false; + } + } else if(types.isNumeric(rval['@value'])) { + if(type === XSD_INTEGER) { + const i = parseInt(rval['@value'], 10); + if(i.toFixed(0) === rval['@value']) { + rval['@value'] = i; + } + } else if(type === XSD_DOUBLE) { + rval['@value'] = parseFloat(rval['@value']); + } + } + // do not add native type + if(![XSD_BOOLEAN, XSD_INTEGER, XSD_DOUBLE, XSD_STRING].includes(type)) { + rval['@type'] = type; + } + } else if(rdfDirection === 'i18n-datatype' && + type.startsWith('https://www.w3.org/ns/i18n#')) { + const [, language, direction] = type.split(/[#_]/); + if(language.length > 0) { + rval['@language'] = language; + if(!language.match(REGEX_BCP47)) { + console.warn(`@language must be valid BCP47: ${language}`); + } + } + rval['@direction'] = direction; + } else if(type !== XSD_STRING) { + rval['@type'] = type; + } + } + + return rval; +} + + +/***/ }), + +/***/ "./node_modules/jsonld/lib/graphTypes.js": +/*!***********************************************!*\ + !*** ./node_modules/jsonld/lib/graphTypes.js ***! + \***********************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* + * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved. + */ + + +const types = __webpack_require__(/*! ./types */ "./node_modules/jsonld/lib/types.js"); + +const api = {}; +module.exports = api; + +/** + * Returns true if the given value is a subject with properties. + * + * @param v the value to check. + * + * @return true if the value is a subject with properties, false if not. + */ +api.isSubject = v => { + // Note: A value is a subject if all of these hold true: + // 1. It is an Object. + // 2. It is not a @value, @set, or @list. + // 3. It has more than 1 key OR any existing key is not @id. + if(types.isObject(v) && + !(('@value' in v) || ('@set' in v) || ('@list' in v))) { + const keyCount = Object.keys(v).length; + return (keyCount > 1 || !('@id' in v)); + } + return false; +}; + +/** + * Returns true if the given value is a subject reference. + * + * @param v the value to check. + * + * @return true if the value is a subject reference, false if not. + */ +api.isSubjectReference = v => + // Note: A value is a subject reference if all of these hold true: + // 1. It is an Object. + // 2. It has a single key: @id. + (types.isObject(v) && Object.keys(v).length === 1 && ('@id' in v)); + +/** + * Returns true if the given value is a @value. + * + * @param v the value to check. + * + * @return true if the value is a @value, false if not. + */ +api.isValue = v => + // Note: A value is a @value if all of these hold true: + // 1. It is an Object. + // 2. It has the @value property. + types.isObject(v) && ('@value' in v); + +/** + * Returns true if the given value is a @list. + * + * @param v the value to check. + * + * @return true if the value is a @list, false if not. + */ +api.isList = v => + // Note: A value is a @list if all of these hold true: + // 1. It is an Object. + // 2. It has the @list property. + types.isObject(v) && ('@list' in v); + +/** + * Returns true if the given value is a @graph. + * + * @return true if the value is a @graph, false if not. + */ +api.isGraph = v => { + // Note: A value is a graph if all of these hold true: + // 1. It is an object. + // 2. It has an `@graph` key. + // 3. It may have '@id' or '@index' + return types.isObject(v) && + '@graph' in v && + Object.keys(v) + .filter(key => key !== '@id' && key !== '@index').length === 1; +}; + +/** + * Returns true if the given value is a simple @graph. + * + * @return true if the value is a simple @graph, false if not. + */ +api.isSimpleGraph = v => { + // Note: A value is a simple graph if all of these hold true: + // 1. It is an object. + // 2. It has an `@graph` key. + // 3. It has only 1 key or 2 keys where one of them is `@index`. + return api.isGraph(v) && !('@id' in v); +}; + +/** + * Returns true if the given value is a blank node. + * + * @param v the value to check. + * + * @return true if the value is a blank node, false if not. + */ +api.isBlankNode = v => { + // Note: A value is a blank node if all of these hold true: + // 1. It is an Object. + // 2. If it has an @id key its value begins with '_:'. + // 3. It has no keys OR is not a @value, @set, or @list. + if(types.isObject(v)) { + if('@id' in v) { + return (v['@id'].indexOf('_:') === 0); + } + return (Object.keys(v).length === 0 || + !(('@value' in v) || ('@set' in v) || ('@list' in v))); + } + return false; +}; + + +/***/ }), + +/***/ "./node_modules/jsonld/lib/jsonld.js": +/*!*******************************************!*\ + !*** ./node_modules/jsonld/lib/jsonld.js ***! + \*******************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +/* WEBPACK VAR INJECTION */(function(process, global) {/** + * A JavaScript implementation of the JSON-LD API. + * + * @author Dave Longley + * + * @license BSD 3-Clause License + * Copyright (c) 2011-2019 Digital Bazaar, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * Neither the name of the Digital Bazaar, Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A + * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED + * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +const canonize = __webpack_require__(/*! rdf-canonize */ "./node_modules/rdf-canonize/lib/index.js"); +const util = __webpack_require__(/*! ./util */ "./node_modules/jsonld/lib/util.js"); +const ContextResolver = __webpack_require__(/*! ./ContextResolver */ "./node_modules/jsonld/lib/ContextResolver.js"); +const IdentifierIssuer = util.IdentifierIssuer; +const JsonLdError = __webpack_require__(/*! ./JsonLdError */ "./node_modules/jsonld/lib/JsonLdError.js"); +const LRU = __webpack_require__(/*! lru-cache */ "./node_modules/lru-cache/index.js"); +const NQuads = __webpack_require__(/*! ./NQuads */ "./node_modules/jsonld/lib/NQuads.js"); +const Rdfa = __webpack_require__(/*! ./Rdfa */ "./node_modules/jsonld/lib/Rdfa.js"); + +const {expand: _expand} = __webpack_require__(/*! ./expand */ "./node_modules/jsonld/lib/expand.js"); +const {flatten: _flatten} = __webpack_require__(/*! ./flatten */ "./node_modules/jsonld/lib/flatten.js"); +const {fromRDF: _fromRDF} = __webpack_require__(/*! ./fromRdf */ "./node_modules/jsonld/lib/fromRdf.js"); +const {toRDF: _toRDF} = __webpack_require__(/*! ./toRdf */ "./node_modules/jsonld/lib/toRdf.js"); + +const { + frameMergedOrDefault: _frameMergedOrDefault, + cleanupNull: _cleanupNull +} = __webpack_require__(/*! ./frame */ "./node_modules/jsonld/lib/frame.js"); + +const { + isArray: _isArray, + isObject: _isObject, + isString: _isString +} = __webpack_require__(/*! ./types */ "./node_modules/jsonld/lib/types.js"); + +const { + isSubjectReference: _isSubjectReference, +} = __webpack_require__(/*! ./graphTypes */ "./node_modules/jsonld/lib/graphTypes.js"); + +const { + expandIri: _expandIri, + getInitialContext: _getInitialContext, + process: _processContext, + processingMode: _processingMode +} = __webpack_require__(/*! ./context */ "./node_modules/jsonld/lib/context.js"); + +const { + compact: _compact, + compactIri: _compactIri +} = __webpack_require__(/*! ./compact */ "./node_modules/jsonld/lib/compact.js"); + +const { + createNodeMap: _createNodeMap, + createMergedNodeMap: _createMergedNodeMap, + mergeNodeMaps: _mergeNodeMaps +} = __webpack_require__(/*! ./nodeMap */ "./node_modules/jsonld/lib/nodeMap.js"); + +// determine if in-browser or using Node.js +const _nodejs = ( + typeof process !== 'undefined' && process.versions && process.versions.node); +const _browser = !_nodejs && + (typeof window !== 'undefined' || typeof self !== 'undefined'); + +/* eslint-disable indent */ +// attaches jsonld API to the given object +const wrapper = function(jsonld) { + +/** Registered RDF dataset parsers hashed by content-type. */ +const _rdfParsers = {}; + +// resolved context cache +// TODO: consider basing max on context size rather than number +const RESOLVED_CONTEXT_CACHE_MAX_SIZE = 100; +const _resolvedContextCache = new LRU({max: RESOLVED_CONTEXT_CACHE_MAX_SIZE}); + +/* Core API */ + +/** + * Performs JSON-LD compaction. + * + * @param input the JSON-LD input to compact. + * @param ctx the context to compact with. + * @param [options] options to use: + * [base] the base IRI to use. + * [compactArrays] true to compact arrays to single values when + * appropriate, false not to (default: true). + * [compactToRelative] true to compact IRIs to be relative to document + * base, false to keep absolute (default: true) + * [graph] true to always output a top-level graph (default: false). + * [expandContext] a context to expand with. + * [skipExpansion] true to assume the input is expanded and skip + * expansion, false not to, defaults to false. + * [documentLoader(url, options)] the document loader. + * [expansionMap(info)] a function that can be used to custom map + * unmappable values (or to throw an error when they are detected); + * if this function returns `undefined` then the default behavior + * will be used. + * [framing] true if compaction is occuring during a framing operation. + * [compactionMap(info)] a function that can be used to custom map + * unmappable values (or to throw an error when they are detected); + * if this function returns `undefined` then the default behavior + * will be used. + * [contextResolver] internal use only. + * + * @return a Promise that resolves to the compacted output. + */ +jsonld.compact = async function(input, ctx, options) { + if(arguments.length < 2) { + throw new TypeError('Could not compact, too few arguments.'); + } + + if(ctx === null) { + throw new JsonLdError( + 'The compaction context must not be null.', + 'jsonld.CompactError', {code: 'invalid local context'}); + } + + // nothing to compact + if(input === null) { + return null; + } + + // set default options + options = _setDefaults(options, { + base: _isString(input) ? input : '', + compactArrays: true, + compactToRelative: true, + graph: false, + skipExpansion: false, + link: false, + issuer: new IdentifierIssuer('_:b'), + contextResolver: new ContextResolver( + {sharedCache: _resolvedContextCache}) + }); + if(options.link) { + // force skip expansion when linking, "link" is not part of the public + // API, it should only be called from framing + options.skipExpansion = true; + } + if(!options.compactToRelative) { + delete options.base; + } + + // expand input + let expanded; + if(options.skipExpansion) { + expanded = input; + } else { + expanded = await jsonld.expand(input, options); + } + + // process context + const activeCtx = await jsonld.processContext( + _getInitialContext(options), ctx, options); + + // do compaction + let compacted = await _compact({ + activeCtx, + element: expanded, + options, + compactionMap: options.compactionMap + }); + + // perform clean up + if(options.compactArrays && !options.graph && _isArray(compacted)) { + if(compacted.length === 1) { + // simplify to a single item + compacted = compacted[0]; + } else if(compacted.length === 0) { + // simplify to an empty object + compacted = {}; + } + } else if(options.graph && _isObject(compacted)) { + // always use array if graph option is on + compacted = [compacted]; + } + + // follow @context key + if(_isObject(ctx) && '@context' in ctx) { + ctx = ctx['@context']; + } + + // build output context + ctx = util.clone(ctx); + if(!_isArray(ctx)) { + ctx = [ctx]; + } + // remove empty contexts + const tmp = ctx; + ctx = []; + for(let i = 0; i < tmp.length; ++i) { + if(!_isObject(tmp[i]) || Object.keys(tmp[i]).length > 0) { + ctx.push(tmp[i]); + } + } + + // remove array if only one context + const hasContext = (ctx.length > 0); + if(ctx.length === 1) { + ctx = ctx[0]; + } + + // add context and/or @graph + if(_isArray(compacted)) { + // use '@graph' keyword + const graphAlias = _compactIri({ + activeCtx, iri: '@graph', relativeTo: {vocab: true} + }); + const graph = compacted; + compacted = {}; + if(hasContext) { + compacted['@context'] = ctx; + } + compacted[graphAlias] = graph; + } else if(_isObject(compacted) && hasContext) { + // reorder keys so @context is first + const graph = compacted; + compacted = {'@context': ctx}; + for(const key in graph) { + compacted[key] = graph[key]; + } + } + + return compacted; +}; + +/** + * Performs JSON-LD expansion. + * + * @param input the JSON-LD input to expand. + * @param [options] the options to use: + * [base] the base IRI to use. + * [expandContext] a context to expand with. + * [keepFreeFloatingNodes] true to keep free-floating nodes, + * false not to, defaults to false. + * [documentLoader(url, options)] the document loader. + * [expansionMap(info)] a function that can be used to custom map + * unmappable values (or to throw an error when they are detected); + * if this function returns `undefined` then the default behavior + * will be used. + * [contextResolver] internal use only. + * + * @return a Promise that resolves to the expanded output. + */ +jsonld.expand = async function(input, options) { + if(arguments.length < 1) { + throw new TypeError('Could not expand, too few arguments.'); + } + + // set default options + options = _setDefaults(options, { + keepFreeFloatingNodes: false, + contextResolver: new ContextResolver( + {sharedCache: _resolvedContextCache}) + }); + if(options.expansionMap === false) { + options.expansionMap = undefined; + } + + // build set of objects that may have @contexts to resolve + const toResolve = {}; + + // build set of contexts to process prior to expansion + const contextsToProcess = []; + + // if an `expandContext` has been given ensure it gets resolved + if('expandContext' in options) { + const expandContext = util.clone(options.expandContext); + if(_isObject(expandContext) && '@context' in expandContext) { + toResolve.expandContext = expandContext; + } else { + toResolve.expandContext = {'@context': expandContext}; + } + contextsToProcess.push(toResolve.expandContext); + } + + // if input is a string, attempt to dereference remote document + let defaultBase; + if(!_isString(input)) { + // input is not a URL, do not need to retrieve it first + toResolve.input = util.clone(input); + } else { + // load remote doc + const remoteDoc = await jsonld.get(input, options); + defaultBase = remoteDoc.documentUrl; + toResolve.input = remoteDoc.document; + if(remoteDoc.contextUrl) { + // context included in HTTP link header and must be resolved + toResolve.remoteContext = {'@context': remoteDoc.contextUrl}; + contextsToProcess.push(toResolve.remoteContext); + } + } + + // set default base + if(!('base' in options)) { + options.base = defaultBase || ''; + } + + // process any additional contexts + let activeCtx = _getInitialContext(options); + for(const localCtx of contextsToProcess) { + activeCtx = await _processContext({activeCtx, localCtx, options}); + } + + // expand resolved input + let expanded = await _expand({ + activeCtx, + element: toResolve.input, + options, + expansionMap: options.expansionMap + }); + + // optimize away @graph with no other properties + if(_isObject(expanded) && ('@graph' in expanded) && + Object.keys(expanded).length === 1) { + expanded = expanded['@graph']; + } else if(expanded === null) { + expanded = []; + } + + // normalize to an array + if(!_isArray(expanded)) { + expanded = [expanded]; + } + + return expanded; +}; + +/** + * Performs JSON-LD flattening. + * + * @param input the JSON-LD to flatten. + * @param ctx the context to use to compact the flattened output, or null. + * @param [options] the options to use: + * [base] the base IRI to use. + * [expandContext] a context to expand with. + * [documentLoader(url, options)] the document loader. + * [contextResolver] internal use only. + * + * @return a Promise that resolves to the flattened output. + */ +jsonld.flatten = async function(input, ctx, options) { + if(arguments.length < 1) { + return new TypeError('Could not flatten, too few arguments.'); + } + + if(typeof ctx === 'function') { + ctx = null; + } else { + ctx = ctx || null; + } + + // set default options + options = _setDefaults(options, { + base: _isString(input) ? input : '', + contextResolver: new ContextResolver( + {sharedCache: _resolvedContextCache}) + }); + + // expand input + const expanded = await jsonld.expand(input, options); + + // do flattening + const flattened = _flatten(expanded); + + if(ctx === null) { + // no compaction required + return flattened; + } + + // compact result (force @graph option to true, skip expansion) + options.graph = true; + options.skipExpansion = true; + const compacted = await jsonld.compact(flattened, ctx, options); + + return compacted; +}; + +/** + * Performs JSON-LD framing. + * + * @param input the JSON-LD input to frame. + * @param frame the JSON-LD frame to use. + * @param [options] the framing options. + * [base] the base IRI to use. + * [expandContext] a context to expand with. + * [embed] default @embed flag: '@last', '@always', '@never', '@link' + * (default: '@last'). + * [explicit] default @explicit flag (default: false). + * [requireAll] default @requireAll flag (default: true). + * [omitDefault] default @omitDefault flag (default: false). + * [documentLoader(url, options)] the document loader. + * [contextResolver] internal use only. + * + * @return a Promise that resolves to the framed output. + */ +jsonld.frame = async function(input, frame, options) { + if(arguments.length < 2) { + throw new TypeError('Could not frame, too few arguments.'); + } + + // set default options + options = _setDefaults(options, { + base: _isString(input) ? input : '', + embed: '@once', + explicit: false, + requireAll: false, + omitDefault: false, + bnodesToClear: [], + contextResolver: new ContextResolver( + {sharedCache: _resolvedContextCache}) + }); + + // if frame is a string, attempt to dereference remote document + if(_isString(frame)) { + // load remote doc + const remoteDoc = await jsonld.get(frame, options); + frame = remoteDoc.document; + + if(remoteDoc.contextUrl) { + // inject link header @context into frame + let ctx = frame['@context']; + if(!ctx) { + ctx = remoteDoc.contextUrl; + } else if(_isArray(ctx)) { + ctx.push(remoteDoc.contextUrl); + } else { + ctx = [ctx, remoteDoc.contextUrl]; + } + frame['@context'] = ctx; + } + } + + const frameContext = frame ? frame['@context'] || {} : {}; + + // process context + const activeCtx = await jsonld.processContext( + _getInitialContext(options), frameContext, options); + + // mode specific defaults + if(!options.hasOwnProperty('omitGraph')) { + options.omitGraph = _processingMode(activeCtx, 1.1); + } + if(!options.hasOwnProperty('pruneBlankNodeIdentifiers')) { + options.pruneBlankNodeIdentifiers = _processingMode(activeCtx, 1.1); + } + + // expand input + const expanded = await jsonld.expand(input, options); + + // expand frame + const opts = {...options}; + opts.isFrame = true; + opts.keepFreeFloatingNodes = true; + const expandedFrame = await jsonld.expand(frame, opts); + + // if the unexpanded frame includes a key expanding to @graph, frame the + // default graph, otherwise, the merged graph + const frameKeys = Object.keys(frame) + .map(key => _expandIri(activeCtx, key, {vocab: true})); + opts.merged = !frameKeys.includes('@graph'); + opts.is11 = _processingMode(activeCtx, 1.1); + + // do framing + const framed = _frameMergedOrDefault(expanded, expandedFrame, opts); + + opts.graph = !options.omitGraph; + opts.skipExpansion = true; + opts.link = {}; + opts.framing = true; + let compacted = await jsonld.compact(framed, frameContext, opts); + + // replace @null with null, compacting arrays + opts.link = {}; + compacted = _cleanupNull(compacted, opts); + + return compacted; +}; + +/** + * **Experimental** + * + * Links a JSON-LD document's nodes in memory. + * + * @param input the JSON-LD document to link. + * @param [ctx] the JSON-LD context to apply. + * @param [options] the options to use: + * [base] the base IRI to use. + * [expandContext] a context to expand with. + * [documentLoader(url, options)] the document loader. + * [contextResolver] internal use only. + * + * @return a Promise that resolves to the linked output. + */ +jsonld.link = async function(input, ctx, options) { + // API matches running frame with a wildcard frame and embed: '@link' + // get arguments + const frame = {}; + if(ctx) { + frame['@context'] = ctx; + } + frame['@embed'] = '@link'; + return jsonld.frame(input, frame, options); +}; + +/** + * Performs RDF dataset normalization on the given input. The input is JSON-LD + * unless the 'inputFormat' option is used. The output is an RDF dataset + * unless the 'format' option is used. + * + * @param input the input to normalize as JSON-LD or as a format specified by + * the 'inputFormat' option. + * @param [options] the options to use: + * [algorithm] the normalization algorithm to use, `URDNA2015` or + * `URGNA2012` (default: `URDNA2015`). + * [base] the base IRI to use. + * [expandContext] a context to expand with. + * [skipExpansion] true to assume the input is expanded and skip + * expansion, false not to, defaults to false. + * [inputFormat] the format if input is not JSON-LD: + * 'application/n-quads' for N-Quads. + * [format] the format if output is a string: + * 'application/n-quads' for N-Quads. + * [documentLoader(url, options)] the document loader. + * [useNative] true to use a native canonize algorithm + * [contextResolver] internal use only. + * + * @return a Promise that resolves to the normalized output. + */ +jsonld.normalize = jsonld.canonize = async function(input, options) { + if(arguments.length < 1) { + throw new TypeError('Could not canonize, too few arguments.'); + } + + // set default options + options = _setDefaults(options, { + base: _isString(input) ? input : '', + algorithm: 'URDNA2015', + skipExpansion: false, + contextResolver: new ContextResolver( + {sharedCache: _resolvedContextCache}) + }); + if('inputFormat' in options) { + if(options.inputFormat !== 'application/n-quads' && + options.inputFormat !== 'application/nquads') { + throw new JsonLdError( + 'Unknown canonicalization input format.', + 'jsonld.CanonizeError'); + } + // TODO: `await` for async parsers + const parsedInput = NQuads.parse(input); + + // do canonicalization + return canonize.canonize(parsedInput, options); + } + + // convert to RDF dataset then do normalization + const opts = {...options}; + delete opts.format; + opts.produceGeneralizedRdf = false; + const dataset = await jsonld.toRDF(input, opts); + + // do canonicalization + return canonize.canonize(dataset, options); +}; + +/** + * Converts an RDF dataset to JSON-LD. + * + * @param dataset a serialized string of RDF in a format specified by the + * format option or an RDF dataset to convert. + * @param [options] the options to use: + * [format] the format if dataset param must first be parsed: + * 'application/n-quads' for N-Quads (default). + * [rdfParser] a custom RDF-parser to use to parse the dataset. + * [useRdfType] true to use rdf:type, false to use @type + * (default: false). + * [useNativeTypes] true to convert XSD types into native types + * (boolean, integer, double), false not to (default: false). + * + * @return a Promise that resolves to the JSON-LD document. + */ +jsonld.fromRDF = async function(dataset, options) { + if(arguments.length < 1) { + throw new TypeError('Could not convert from RDF, too few arguments.'); + } + + // set default options + options = _setDefaults(options, { + format: _isString(dataset) ? 'application/n-quads' : undefined + }); + + const {format} = options; + let {rdfParser} = options; + + // handle special format + if(format) { + // check supported formats + rdfParser = rdfParser || _rdfParsers[format]; + if(!rdfParser) { + throw new JsonLdError( + 'Unknown input format.', + 'jsonld.UnknownFormat', {format}); + } + } else { + // no-op parser, assume dataset already parsed + rdfParser = () => dataset; + } + + // rdfParser must be synchronous or return a promise, no callback support + const parsedDataset = await rdfParser(dataset); + return _fromRDF(parsedDataset, options); +}; + +/** + * Outputs the RDF dataset found in the given JSON-LD object. + * + * @param input the JSON-LD input. + * @param [options] the options to use: + * [base] the base IRI to use. + * [expandContext] a context to expand with. + * [skipExpansion] true to assume the input is expanded and skip + * expansion, false not to, defaults to false. + * [format] the format to use to output a string: + * 'application/n-quads' for N-Quads. + * [produceGeneralizedRdf] true to output generalized RDF, false + * to produce only standard RDF (default: false). + * [documentLoader(url, options)] the document loader. + * [contextResolver] internal use only. + * + * @return a Promise that resolves to the RDF dataset. + */ +jsonld.toRDF = async function(input, options) { + if(arguments.length < 1) { + throw new TypeError('Could not convert to RDF, too few arguments.'); + } + + // set default options + options = _setDefaults(options, { + base: _isString(input) ? input : '', + skipExpansion: false, + contextResolver: new ContextResolver( + {sharedCache: _resolvedContextCache}) + }); + + // TODO: support toRDF custom map? + let expanded; + if(options.skipExpansion) { + expanded = input; + } else { + // expand input + expanded = await jsonld.expand(input, options); + } + + // output RDF dataset + const dataset = _toRDF(expanded, options); + if(options.format) { + if(options.format === 'application/n-quads' || + options.format === 'application/nquads') { + return await NQuads.serialize(dataset); + } + throw new JsonLdError( + 'Unknown output format.', + 'jsonld.UnknownFormat', {format: options.format}); + } + + return dataset; +}; + +/** + * **Experimental** + * + * Recursively flattens the nodes in the given JSON-LD input into a merged + * map of node ID => node. All graphs will be merged into the default graph. + * + * @param input the JSON-LD input. + * @param [options] the options to use: + * [base] the base IRI to use. + * [expandContext] a context to expand with. + * [issuer] a jsonld.IdentifierIssuer to use to label blank nodes. + * [documentLoader(url, options)] the document loader. + * [contextResolver] internal use only. + * + * @return a Promise that resolves to the merged node map. + */ +jsonld.createNodeMap = async function(input, options) { + if(arguments.length < 1) { + throw new TypeError('Could not create node map, too few arguments.'); + } + + // set default options + options = _setDefaults(options, { + base: _isString(input) ? input : '', + contextResolver: new ContextResolver( + {sharedCache: _resolvedContextCache}) + }); + + // expand input + const expanded = await jsonld.expand(input, options); + + return _createMergedNodeMap(expanded, options); +}; + +/** + * **Experimental** + * + * Merges two or more JSON-LD documents into a single flattened document. + * + * @param docs the JSON-LD documents to merge together. + * @param ctx the context to use to compact the merged result, or null. + * @param [options] the options to use: + * [base] the base IRI to use. + * [expandContext] a context to expand with. + * [issuer] a jsonld.IdentifierIssuer to use to label blank nodes. + * [mergeNodes] true to merge properties for nodes with the same ID, + * false to ignore new properties for nodes with the same ID once + * the ID has been defined; note that this may not prevent merging + * new properties where a node is in the `object` position + * (default: true). + * [documentLoader(url, options)] the document loader. + * [contextResolver] internal use only. + * + * @return a Promise that resolves to the merged output. + */ +jsonld.merge = async function(docs, ctx, options) { + if(arguments.length < 1) { + throw new TypeError('Could not merge, too few arguments.'); + } + if(!_isArray(docs)) { + throw new TypeError('Could not merge, "docs" must be an array.'); + } + + if(typeof ctx === 'function') { + ctx = null; + } else { + ctx = ctx || null; + } + + // set default options + options = _setDefaults(options, { + contextResolver: new ContextResolver( + {sharedCache: _resolvedContextCache}) + }); + + // expand all documents + const expanded = await Promise.all(docs.map(doc => { + const opts = {...options}; + return jsonld.expand(doc, opts); + })); + + let mergeNodes = true; + if('mergeNodes' in options) { + mergeNodes = options.mergeNodes; + } + + const issuer = options.issuer || new IdentifierIssuer('_:b'); + const graphs = {'@default': {}}; + + for(let i = 0; i < expanded.length; ++i) { + // uniquely relabel blank nodes + const doc = util.relabelBlankNodes(expanded[i], { + issuer: new IdentifierIssuer('_:b' + i + '-') + }); + + // add nodes to the shared node map graphs if merging nodes, to a + // separate graph set if not + const _graphs = (mergeNodes || i === 0) ? graphs : {'@default': {}}; + _createNodeMap(doc, _graphs, '@default', issuer); + + if(_graphs !== graphs) { + // merge document graphs but don't merge existing nodes + for(const graphName in _graphs) { + const _nodeMap = _graphs[graphName]; + if(!(graphName in graphs)) { + graphs[graphName] = _nodeMap; + continue; + } + const nodeMap = graphs[graphName]; + for(const key in _nodeMap) { + if(!(key in nodeMap)) { + nodeMap[key] = _nodeMap[key]; + } + } + } + } + } + + // add all non-default graphs to default graph + const defaultGraph = _mergeNodeMaps(graphs); + + // produce flattened output + const flattened = []; + const keys = Object.keys(defaultGraph).sort(); + for(let ki = 0; ki < keys.length; ++ki) { + const node = defaultGraph[keys[ki]]; + // only add full subjects to top-level + if(!_isSubjectReference(node)) { + flattened.push(node); + } + } + + if(ctx === null) { + return flattened; + } + + // compact result (force @graph option to true, skip expansion) + options.graph = true; + options.skipExpansion = true; + const compacted = await jsonld.compact(flattened, ctx, options); + + return compacted; +}; + +/** + * The default document loader for external documents. + * + * @param url the URL to load. + * + * @return a promise that resolves to the remote document. + */ +Object.defineProperty(jsonld, 'documentLoader', { + get: () => jsonld._documentLoader, + set: v => jsonld._documentLoader = v +}); +// default document loader not implemented +jsonld.documentLoader = async url => { + throw new JsonLdError( + 'Could not retrieve a JSON-LD document from the URL. URL ' + + 'dereferencing not implemented.', 'jsonld.LoadDocumentError', + {code: 'loading document failed', url}); +}; + +/** + * Gets a remote JSON-LD document using the default document loader or + * one given in the passed options. + * + * @param url the URL to fetch. + * @param [options] the options to use: + * [documentLoader] the document loader to use. + * + * @return a Promise that resolves to the retrieved remote document. + */ +jsonld.get = async function(url, options) { + let load; + if(typeof options.documentLoader === 'function') { + load = options.documentLoader; + } else { + load = jsonld.documentLoader; + } + + const remoteDoc = await load(url); + + try { + if(!remoteDoc.document) { + throw new JsonLdError( + 'No remote document found at the given URL.', + 'jsonld.NullRemoteDocument'); + } + if(_isString(remoteDoc.document)) { + remoteDoc.document = JSON.parse(remoteDoc.document); + } + } catch(e) { + throw new JsonLdError( + 'Could not retrieve a JSON-LD document from the URL.', + 'jsonld.LoadDocumentError', { + code: 'loading document failed', + cause: e, + remoteDoc + }); + } + + return remoteDoc; +}; + +/** + * Processes a local context, resolving any URLs as necessary, and returns a + * new active context. + * + * @param activeCtx the current active context. + * @param localCtx the local context to process. + * @param [options] the options to use: + * [documentLoader(url, options)] the document loader. + * [contextResolver] internal use only. + * + * @return a Promise that resolves to the new active context. + */ +jsonld.processContext = async function( + activeCtx, localCtx, options) { + // set default options + options = _setDefaults(options, { + base: '', + contextResolver: new ContextResolver( + {sharedCache: _resolvedContextCache}) + }); + + // return initial context early for null context + if(localCtx === null) { + return _getInitialContext(options); + } + + // get URLs in localCtx + localCtx = util.clone(localCtx); + if(!(_isObject(localCtx) && '@context' in localCtx)) { + localCtx = {'@context': localCtx}; + } + + return _processContext({activeCtx, localCtx, options}); +}; + +// backwards compatibility +jsonld.getContextValue = __webpack_require__(/*! ./context */ "./node_modules/jsonld/lib/context.js").getContextValue; + +/** + * Document loaders. + */ +jsonld.documentLoaders = {}; +jsonld.documentLoaders.node = __webpack_require__(/*! ./documentLoaders/node */ "./node_modules/jsonld/lib/documentLoaders/node.js"); +jsonld.documentLoaders.xhr = __webpack_require__(/*! ./documentLoaders/xhr */ "./node_modules/jsonld/lib/documentLoaders/xhr.js"); + +/** + * Assigns the default document loader for external document URLs to a built-in + * default. Supported types currently include: 'xhr' and 'node'. + * + * @param type the type to set. + * @param [params] the parameters required to use the document loader. + */ +jsonld.useDocumentLoader = function(type) { + if(!(type in jsonld.documentLoaders)) { + throw new JsonLdError( + 'Unknown document loader type: "' + type + '"', + 'jsonld.UnknownDocumentLoader', + {type}); + } + + // set document loader + jsonld.documentLoader = jsonld.documentLoaders[type].apply( + jsonld, Array.prototype.slice.call(arguments, 1)); +}; + +/** + * Registers an RDF dataset parser by content-type, for use with + * jsonld.fromRDF. An RDF dataset parser will always be given one parameter, + * a string of input. An RDF dataset parser can be synchronous or + * asynchronous (by returning a promise). + * + * @param contentType the content-type for the parser. + * @param parser(input) the parser function (takes a string as a parameter + * and either returns an RDF dataset or a Promise that resolves to one. + */ +jsonld.registerRDFParser = function(contentType, parser) { + _rdfParsers[contentType] = parser; +}; + +/** + * Unregisters an RDF dataset parser by content-type. + * + * @param contentType the content-type for the parser. + */ +jsonld.unregisterRDFParser = function(contentType) { + delete _rdfParsers[contentType]; +}; + +// register the N-Quads RDF parser +jsonld.registerRDFParser('application/n-quads', NQuads.parse); +jsonld.registerRDFParser('application/nquads', NQuads.parse); + +// register the RDFa API RDF parser +jsonld.registerRDFParser('rdfa-api', Rdfa.parse); + +/* URL API */ +jsonld.url = __webpack_require__(/*! ./url */ "./node_modules/jsonld/lib/url.js"); + +/* Utility API */ +jsonld.util = util; +// backwards compatibility +Object.assign(jsonld, util); + +// reexpose API as jsonld.promises for backwards compatability +jsonld.promises = jsonld; + +// backwards compatibility +jsonld.RequestQueue = __webpack_require__(/*! ./RequestQueue */ "./node_modules/jsonld/lib/RequestQueue.js"); + +/* WebIDL API */ +jsonld.JsonLdProcessor = __webpack_require__(/*! ./JsonLdProcessor */ "./node_modules/jsonld/lib/JsonLdProcessor.js")(jsonld); + +// setup browser global JsonLdProcessor +if(_browser && typeof global.JsonLdProcessor === 'undefined') { + Object.defineProperty(global, 'JsonLdProcessor', { + writable: true, + enumerable: false, + configurable: true, + value: jsonld.JsonLdProcessor + }); +} + +// set platform-specific defaults/APIs +if(_nodejs) { + // use node document loader by default + jsonld.useDocumentLoader('node'); +} else if(typeof XMLHttpRequest !== 'undefined') { + // use xhr document loader by default + jsonld.useDocumentLoader('xhr'); +} + +function _setDefaults(options, { + documentLoader = jsonld.documentLoader, + ...defaults +}) { + return Object.assign({}, {documentLoader}, defaults, options); +} + +// end of jsonld API `wrapper` factory +return jsonld; +}; + +// external APIs: + +// used to generate a new jsonld API instance +const factory = function() { + return wrapper(function() { + return factory(); + }); +}; + +// wrap the main jsonld API instance +wrapper(factory); +// export API +module.exports = factory; + +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../process/browser.js */ "./node_modules/process/browser.js"), __webpack_require__(/*! ./../../webpack/buildin/global.js */ "./node_modules/webpack/buildin/global.js"))) + +/***/ }), + +/***/ "./node_modules/jsonld/lib/nodeMap.js": +/*!********************************************!*\ + !*** ./node_modules/jsonld/lib/nodeMap.js ***! + \********************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* + * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved. + */ + + +const {isKeyword} = __webpack_require__(/*! ./context */ "./node_modules/jsonld/lib/context.js"); +const graphTypes = __webpack_require__(/*! ./graphTypes */ "./node_modules/jsonld/lib/graphTypes.js"); +const types = __webpack_require__(/*! ./types */ "./node_modules/jsonld/lib/types.js"); +const util = __webpack_require__(/*! ./util */ "./node_modules/jsonld/lib/util.js"); +const JsonLdError = __webpack_require__(/*! ./JsonLdError */ "./node_modules/jsonld/lib/JsonLdError.js"); + +const api = {}; +module.exports = api; + +/** + * Creates a merged JSON-LD node map (node ID => node). + * + * @param input the expanded JSON-LD to create a node map of. + * @param [options] the options to use: + * [issuer] a jsonld.IdentifierIssuer to use to label blank nodes. + * + * @return the node map. + */ +api.createMergedNodeMap = (input, options) => { + options = options || {}; + + // produce a map of all subjects and name each bnode + const issuer = options.issuer || new util.IdentifierIssuer('_:b'); + const graphs = {'@default': {}}; + api.createNodeMap(input, graphs, '@default', issuer); + + // add all non-default graphs to default graph + return api.mergeNodeMaps(graphs); +}; + +/** + * Recursively flattens the subjects in the given JSON-LD expanded input + * into a node map. + * + * @param input the JSON-LD expanded input. + * @param graphs a map of graph name to subject map. + * @param graph the name of the current graph. + * @param issuer the blank node identifier issuer. + * @param name the name assigned to the current input if it is a bnode. + * @param list the list to append to, null for none. + */ +api.createNodeMap = (input, graphs, graph, issuer, name, list) => { + // recurse through array + if(types.isArray(input)) { + for(const node of input) { + api.createNodeMap(node, graphs, graph, issuer, undefined, list); + } + return; + } + + // add non-object to list + if(!types.isObject(input)) { + if(list) { + list.push(input); + } + return; + } + + // add values to list + if(graphTypes.isValue(input)) { + if('@type' in input) { + let type = input['@type']; + // rename @type blank node + if(type.indexOf('_:') === 0) { + input['@type'] = type = issuer.getId(type); + } + } + if(list) { + list.push(input); + } + return; + } else if(list && graphTypes.isList(input)) { + const _list = []; + api.createNodeMap(input['@list'], graphs, graph, issuer, name, _list); + list.push({'@list': _list}); + return; + } + + // Note: At this point, input must be a subject. + + // spec requires @type to be named first, so assign names early + if('@type' in input) { + const types = input['@type']; + for(const type of types) { + if(type.indexOf('_:') === 0) { + issuer.getId(type); + } + } + } + + // get name for subject + if(types.isUndefined(name)) { + name = graphTypes.isBlankNode(input) ? + issuer.getId(input['@id']) : input['@id']; + } + + // add subject reference to list + if(list) { + list.push({'@id': name}); + } + + // create new subject or merge into existing one + const subjects = graphs[graph]; + const subject = subjects[name] = subjects[name] || {}; + subject['@id'] = name; + const properties = Object.keys(input).sort(); + for(let property of properties) { + // skip @id + if(property === '@id') { + continue; + } + + // handle reverse properties + if(property === '@reverse') { + const referencedNode = {'@id': name}; + const reverseMap = input['@reverse']; + for(const reverseProperty in reverseMap) { + const items = reverseMap[reverseProperty]; + for(const item of items) { + let itemName = item['@id']; + if(graphTypes.isBlankNode(item)) { + itemName = issuer.getId(itemName); + } + api.createNodeMap(item, graphs, graph, issuer, itemName); + util.addValue( + subjects[itemName], reverseProperty, referencedNode, + {propertyIsArray: true, allowDuplicate: false}); + } + } + continue; + } + + // recurse into graph + if(property === '@graph') { + // add graph subjects map entry + if(!(name in graphs)) { + graphs[name] = {}; + } + api.createNodeMap(input[property], graphs, name, issuer); + continue; + } + + // recurse into included + if(property === '@included') { + api.createNodeMap(input[property], graphs, graph, issuer); + continue; + } + + // copy non-@type keywords + if(property !== '@type' && isKeyword(property)) { + if(property === '@index' && property in subject && + (input[property] !== subject[property] || + input[property]['@id'] !== subject[property]['@id'])) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; conflicting @index property detected.', + 'jsonld.SyntaxError', + {code: 'conflicting indexes', subject}); + } + subject[property] = input[property]; + continue; + } + + // iterate over objects + const objects = input[property]; + + // if property is a bnode, assign it a new id + if(property.indexOf('_:') === 0) { + property = issuer.getId(property); + } + + // ensure property is added for empty arrays + if(objects.length === 0) { + util.addValue(subject, property, [], {propertyIsArray: true}); + continue; + } + for(let o of objects) { + if(property === '@type') { + // rename @type blank nodes + o = (o.indexOf('_:') === 0) ? issuer.getId(o) : o; + } + + // handle embedded subject or subject reference + if(graphTypes.isSubject(o) || graphTypes.isSubjectReference(o)) { + // skip null @id + if('@id' in o && !o['@id']) { + continue; + } + + // relabel blank node @id + const id = graphTypes.isBlankNode(o) ? + issuer.getId(o['@id']) : o['@id']; + + // add reference and recurse + util.addValue( + subject, property, {'@id': id}, + {propertyIsArray: true, allowDuplicate: false}); + api.createNodeMap(o, graphs, graph, issuer, id); + } else if(graphTypes.isValue(o)) { + util.addValue( + subject, property, o, + {propertyIsArray: true, allowDuplicate: false}); + } else if(graphTypes.isList(o)) { + // handle @list + const _list = []; + api.createNodeMap(o['@list'], graphs, graph, issuer, name, _list); + o = {'@list': _list}; + util.addValue( + subject, property, o, + {propertyIsArray: true, allowDuplicate: false}); + } else { + // handle @value + api.createNodeMap(o, graphs, graph, issuer, name); + util.addValue( + subject, property, o, {propertyIsArray: true, allowDuplicate: false}); + } + } + } +}; + +/** + * Merge separate named graphs into a single merged graph including + * all nodes from the default graph and named graphs. + * + * @param graphs a map of graph name to subject map. + * + * @return the merged graph map. + */ +api.mergeNodeMapGraphs = graphs => { + const merged = {}; + for(const name of Object.keys(graphs).sort()) { + for(const id of Object.keys(graphs[name]).sort()) { + const node = graphs[name][id]; + if(!(id in merged)) { + merged[id] = {'@id': id}; + } + const mergedNode = merged[id]; + + for(const property of Object.keys(node).sort()) { + if(isKeyword(property) && property !== '@type') { + // copy keywords + mergedNode[property] = util.clone(node[property]); + } else { + // merge objects + for(const value of node[property]) { + util.addValue( + mergedNode, property, util.clone(value), + {propertyIsArray: true, allowDuplicate: false}); + } + } + } + } + } + + return merged; +}; + +api.mergeNodeMaps = graphs => { + // add all non-default graphs to default graph + const defaultGraph = graphs['@default']; + const graphNames = Object.keys(graphs).sort(); + for(const graphName of graphNames) { + if(graphName === '@default') { + continue; + } + const nodeMap = graphs[graphName]; + let subject = defaultGraph[graphName]; + if(!subject) { + defaultGraph[graphName] = subject = { + '@id': graphName, + '@graph': [] + }; + } else if(!('@graph' in subject)) { + subject['@graph'] = []; + } + const graph = subject['@graph']; + for(const id of Object.keys(nodeMap).sort()) { + const node = nodeMap[id]; + // only add full subjects + if(!graphTypes.isSubjectReference(node)) { + graph.push(node); + } + } + } + return defaultGraph; +}; + + +/***/ }), + +/***/ "./node_modules/jsonld/lib/toRdf.js": +/*!******************************************!*\ + !*** ./node_modules/jsonld/lib/toRdf.js ***! + \******************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* + * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved. + */ + + +const {createNodeMap} = __webpack_require__(/*! ./nodeMap */ "./node_modules/jsonld/lib/nodeMap.js"); +const {isKeyword} = __webpack_require__(/*! ./context */ "./node_modules/jsonld/lib/context.js"); +const graphTypes = __webpack_require__(/*! ./graphTypes */ "./node_modules/jsonld/lib/graphTypes.js"); +const jsonCanonicalize = __webpack_require__(/*! canonicalize */ "./node_modules/canonicalize/lib/canonicalize.js"); +const types = __webpack_require__(/*! ./types */ "./node_modules/jsonld/lib/types.js"); +const util = __webpack_require__(/*! ./util */ "./node_modules/jsonld/lib/util.js"); + +const { + // RDF, + // RDF_LIST, + RDF_FIRST, + RDF_REST, + RDF_NIL, + RDF_TYPE, + // RDF_PLAIN_LITERAL, + // RDF_XML_LITERAL, + RDF_JSON_LITERAL, + // RDF_OBJECT, + RDF_LANGSTRING, + + // XSD, + XSD_BOOLEAN, + XSD_DOUBLE, + XSD_INTEGER, + XSD_STRING, +} = __webpack_require__(/*! ./constants */ "./node_modules/jsonld/lib/constants.js"); + +const { + isAbsolute: _isAbsoluteIri +} = __webpack_require__(/*! ./url */ "./node_modules/jsonld/lib/url.js"); + +const api = {}; +module.exports = api; + +/** + * Outputs an RDF dataset for the expanded JSON-LD input. + * + * @param input the expanded JSON-LD input. + * @param options the RDF serialization options. + * + * @return the RDF dataset. + */ +api.toRDF = (input, options) => { + // create node map for default graph (and any named graphs) + const issuer = new util.IdentifierIssuer('_:b'); + const nodeMap = {'@default': {}}; + createNodeMap(input, nodeMap, '@default', issuer); + + const dataset = []; + const graphNames = Object.keys(nodeMap).sort(); + for(const graphName of graphNames) { + let graphTerm; + if(graphName === '@default') { + graphTerm = {termType: 'DefaultGraph', value: ''}; + } else if(_isAbsoluteIri(graphName)) { + if(graphName.startsWith('_:')) { + graphTerm = {termType: 'BlankNode'}; + } else { + graphTerm = {termType: 'NamedNode'}; + } + graphTerm.value = graphName; + } else { + // skip relative IRIs (not valid RDF) + continue; + } + _graphToRDF(dataset, nodeMap[graphName], graphTerm, issuer, options); + } + + return dataset; +}; + +/** + * Adds RDF quads for a particular graph to the given dataset. + * + * @param dataset the dataset to append RDF quads to. + * @param graph the graph to create RDF quads for. + * @param graphTerm the graph term for each quad. + * @param issuer a IdentifierIssuer for assigning blank node names. + * @param options the RDF serialization options. + * + * @return the array of RDF triples for the given graph. + */ +function _graphToRDF(dataset, graph, graphTerm, issuer, options) { + const ids = Object.keys(graph).sort(); + for(const id of ids) { + const node = graph[id]; + const properties = Object.keys(node).sort(); + for(let property of properties) { + const items = node[property]; + if(property === '@type') { + property = RDF_TYPE; + } else if(isKeyword(property)) { + continue; + } + + for(const item of items) { + // RDF subject + const subject = { + termType: id.startsWith('_:') ? 'BlankNode' : 'NamedNode', + value: id + }; + + // skip relative IRI subjects (not valid RDF) + if(!_isAbsoluteIri(id)) { + continue; + } + + // RDF predicate + const predicate = { + termType: property.startsWith('_:') ? 'BlankNode' : 'NamedNode', + value: property + }; + + // skip relative IRI predicates (not valid RDF) + if(!_isAbsoluteIri(property)) { + continue; + } + + // skip blank node predicates unless producing generalized RDF + if(predicate.termType === 'BlankNode' && + !options.produceGeneralizedRdf) { + continue; + } + + // convert list, value or node object to triple + const object = + _objectToRDF(item, issuer, dataset, graphTerm, options.rdfDirection); + // skip null objects (they are relative IRIs) + if(object) { + dataset.push({ + subject, + predicate, + object, + graph: graphTerm + }); + } + } + } + } +} + +/** + * Converts a @list value into linked list of blank node RDF quads + * (an RDF collection). + * + * @param list the @list value. + * @param issuer a IdentifierIssuer for assigning blank node names. + * @param dataset the array of quads to append to. + * @param graphTerm the graph term for each quad. + * + * @return the head of the list. + */ +function _listToRDF(list, issuer, dataset, graphTerm, rdfDirection) { + const first = {termType: 'NamedNode', value: RDF_FIRST}; + const rest = {termType: 'NamedNode', value: RDF_REST}; + const nil = {termType: 'NamedNode', value: RDF_NIL}; + + const last = list.pop(); + // Result is the head of the list + const result = last ? {termType: 'BlankNode', value: issuer.getId()} : nil; + let subject = result; + + for(const item of list) { + const object = _objectToRDF(item, issuer, dataset, graphTerm, rdfDirection); + const next = {termType: 'BlankNode', value: issuer.getId()}; + dataset.push({ + subject, + predicate: first, + object, + graph: graphTerm + }); + dataset.push({ + subject, + predicate: rest, + object: next, + graph: graphTerm + }); + subject = next; + } + + // Tail of list + if(last) { + const object = _objectToRDF(last, issuer, dataset, graphTerm, rdfDirection); + dataset.push({ + subject, + predicate: first, + object, + graph: graphTerm + }); + dataset.push({ + subject, + predicate: rest, + object: nil, + graph: graphTerm + }); + } + + return result; +} + +/** + * Converts a JSON-LD value object to an RDF literal or a JSON-LD string, + * node object to an RDF resource, or adds a list. + * + * @param item the JSON-LD value or node object. + * @param issuer a IdentifierIssuer for assigning blank node names. + * @param dataset the dataset to append RDF quads to. + * @param graphTerm the graph term for each quad. + * + * @return the RDF literal or RDF resource. + */ +function _objectToRDF(item, issuer, dataset, graphTerm, rdfDirection) { + const object = {}; + + // convert value object to RDF + if(graphTypes.isValue(item)) { + object.termType = 'Literal'; + object.value = undefined; + object.datatype = { + termType: 'NamedNode' + }; + let value = item['@value']; + const datatype = item['@type'] || null; + + // convert to XSD/JSON datatypes as appropriate + if(datatype === '@json') { + object.value = jsonCanonicalize(value); + object.datatype.value = RDF_JSON_LITERAL; + } else if(types.isBoolean(value)) { + object.value = value.toString(); + object.datatype.value = datatype || XSD_BOOLEAN; + } else if(types.isDouble(value) || datatype === XSD_DOUBLE) { + if(!types.isDouble(value)) { + value = parseFloat(value); + } + // canonical double representation + object.value = value.toExponential(15).replace(/(\d)0*e\+?/, '$1E'); + object.datatype.value = datatype || XSD_DOUBLE; + } else if(types.isNumber(value)) { + object.value = value.toFixed(0); + object.datatype.value = datatype || XSD_INTEGER; + } else if(rdfDirection === 'i18n-datatype' && + '@direction' in item) { + const datatype = 'https://www.w3.org/ns/i18n#' + + (item['@language'] || '') + + `_${item['@direction']}`; + object.datatype.value = datatype; + object.value = value; + } else if('@language' in item) { + object.value = value; + object.datatype.value = datatype || RDF_LANGSTRING; + object.language = item['@language']; + } else { + object.value = value; + object.datatype.value = datatype || XSD_STRING; + } + } else if(graphTypes.isList(item)) { + const _list = + _listToRDF(item['@list'], issuer, dataset, graphTerm, rdfDirection); + object.termType = _list.termType; + object.value = _list.value; + } else { + // convert string/node object to RDF + const id = types.isObject(item) ? item['@id'] : item; + object.termType = id.startsWith('_:') ? 'BlankNode' : 'NamedNode'; + object.value = id; + } + + // skip relative IRIs, not valid RDF + if(object.termType === 'NamedNode' && !_isAbsoluteIri(object.value)) { + return null; + } + + return object; +} + + +/***/ }), + +/***/ "./node_modules/jsonld/lib/types.js": +/*!******************************************!*\ + !*** ./node_modules/jsonld/lib/types.js ***! + \******************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* + * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved. + */ + + +const api = {}; +module.exports = api; + +/** + * Returns true if the given value is an Array. + * + * @param v the value to check. + * + * @return true if the value is an Array, false if not. + */ +api.isArray = Array.isArray; + +/** + * Returns true if the given value is a Boolean. + * + * @param v the value to check. + * + * @return true if the value is a Boolean, false if not. + */ +api.isBoolean = v => (typeof v === 'boolean' || + Object.prototype.toString.call(v) === '[object Boolean]'); + +/** + * Returns true if the given value is a double. + * + * @param v the value to check. + * + * @return true if the value is a double, false if not. + */ +api.isDouble = v => api.isNumber(v) && + (String(v).indexOf('.') !== -1 || Math.abs(v) >= 1e21); + +/** + * Returns true if the given value is an empty Object. + * + * @param v the value to check. + * + * @return true if the value is an empty Object, false if not. + */ +api.isEmptyObject = v => api.isObject(v) && Object.keys(v).length === 0; + +/** + * Returns true if the given value is a Number. + * + * @param v the value to check. + * + * @return true if the value is a Number, false if not. + */ +api.isNumber = v => (typeof v === 'number' || + Object.prototype.toString.call(v) === '[object Number]'); + +/** + * Returns true if the given value is numeric. + * + * @param v the value to check. + * + * @return true if the value is numeric, false if not. + */ +api.isNumeric = v => !isNaN(parseFloat(v)) && isFinite(v); + +/** + * Returns true if the given value is an Object. + * + * @param v the value to check. + * + * @return true if the value is an Object, false if not. + */ +api.isObject = v => Object.prototype.toString.call(v) === '[object Object]'; + +/** + * Returns true if the given value is a String. + * + * @param v the value to check. + * + * @return true if the value is a String, false if not. + */ +api.isString = v => (typeof v === 'string' || + Object.prototype.toString.call(v) === '[object String]'); + +/** + * Returns true if the given value is undefined. + * + * @param v the value to check. + * + * @return true if the value is undefined, false if not. + */ +api.isUndefined = v => typeof v === 'undefined'; + + +/***/ }), + +/***/ "./node_modules/jsonld/lib/url.js": +/*!****************************************!*\ + !*** ./node_modules/jsonld/lib/url.js ***! + \****************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* + * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved. + */ + + +const types = __webpack_require__(/*! ./types */ "./node_modules/jsonld/lib/types.js"); + +const api = {}; +module.exports = api; + +// define URL parser +// parseUri 1.2.2 +// (c) Steven Levithan +// MIT License +// with local jsonld.js modifications +api.parsers = { + simple: { + // RFC 3986 basic parts + keys: [ + 'href', 'scheme', 'authority', 'path', 'query', 'fragment' + ], + /* eslint-disable-next-line max-len */ + regex: /^(?:([^:\/?#]+):)?(?:\/\/([^\/?#]*))?([^?#]*)(?:\?([^#]*))?(?:#(.*))?/ + }, + full: { + keys: [ + 'href', 'protocol', 'scheme', 'authority', 'auth', 'user', 'password', + 'hostname', 'port', 'path', 'directory', 'file', 'query', 'fragment' + ], + /* eslint-disable-next-line max-len */ + regex: /^(([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?(?:(((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/ + } +}; +api.parse = (str, parser) => { + const parsed = {}; + const o = api.parsers[parser || 'full']; + const m = o.regex.exec(str); + let i = o.keys.length; + while(i--) { + parsed[o.keys[i]] = (m[i] === undefined) ? null : m[i]; + } + + // remove default ports in found in URLs + if((parsed.scheme === 'https' && parsed.port === '443') || + (parsed.scheme === 'http' && parsed.port === '80')) { + parsed.href = parsed.href.replace(':' + parsed.port, ''); + parsed.authority = parsed.authority.replace(':' + parsed.port, ''); + parsed.port = null; + } + + parsed.normalizedPath = api.removeDotSegments(parsed.path); + return parsed; +}; + +/** + * Prepends a base IRI to the given relative IRI. + * + * @param base the base IRI. + * @param iri the relative IRI. + * + * @return the absolute IRI. + */ +api.prependBase = (base, iri) => { + // skip IRI processing + if(base === null) { + return iri; + } + // already an absolute IRI + if(api.isAbsolute(iri)) { + return iri; + } + + // parse base if it is a string + if(!base || types.isString(base)) { + base = api.parse(base || ''); + } + + // parse given IRI + const rel = api.parse(iri); + + // per RFC3986 5.2.2 + const transform = { + protocol: base.protocol || '' + }; + + if(rel.authority !== null) { + transform.authority = rel.authority; + transform.path = rel.path; + transform.query = rel.query; + } else { + transform.authority = base.authority; + + if(rel.path === '') { + transform.path = base.path; + if(rel.query !== null) { + transform.query = rel.query; + } else { + transform.query = base.query; + } + } else { + if(rel.path.indexOf('/') === 0) { + // IRI represents an absolute path + transform.path = rel.path; + } else { + // merge paths + let path = base.path; + + // append relative path to the end of the last directory from base + path = path.substr(0, path.lastIndexOf('/') + 1); + if((path.length > 0 || base.authority) && path.substr(-1) !== '/') { + path += '/'; + } + path += rel.path; + + transform.path = path; + } + transform.query = rel.query; + } + } + + if(rel.path !== '') { + // remove slashes and dots in path + transform.path = api.removeDotSegments(transform.path); + } + + // construct URL + let rval = transform.protocol; + if(transform.authority !== null) { + rval += '//' + transform.authority; + } + rval += transform.path; + if(transform.query !== null) { + rval += '?' + transform.query; + } + if(rel.fragment !== null) { + rval += '#' + rel.fragment; + } + + // handle empty base + if(rval === '') { + rval = './'; + } + + return rval; +}; + +/** + * Removes a base IRI from the given absolute IRI. + * + * @param base the base IRI. + * @param iri the absolute IRI. + * + * @return the relative IRI if relative to base, otherwise the absolute IRI. + */ +api.removeBase = (base, iri) => { + // skip IRI processing + if(base === null) { + return iri; + } + + if(!base || types.isString(base)) { + base = api.parse(base || ''); + } + + // establish base root + let root = ''; + if(base.href !== '') { + root += (base.protocol || '') + '//' + (base.authority || ''); + } else if(iri.indexOf('//')) { + // support network-path reference with empty base + root += '//'; + } + + // IRI not relative to base + if(iri.indexOf(root) !== 0) { + return iri; + } + + // remove root from IRI and parse remainder + const rel = api.parse(iri.substr(root.length)); + + // remove path segments that match (do not remove last segment unless there + // is a hash or query) + const baseSegments = base.normalizedPath.split('/'); + const iriSegments = rel.normalizedPath.split('/'); + const last = (rel.fragment || rel.query) ? 0 : 1; + while(baseSegments.length > 0 && iriSegments.length > last) { + if(baseSegments[0] !== iriSegments[0]) { + break; + } + baseSegments.shift(); + iriSegments.shift(); + } + + // use '../' for each non-matching base segment + let rval = ''; + if(baseSegments.length > 0) { + // don't count the last segment (if it ends with '/' last path doesn't + // count and if it doesn't end with '/' it isn't a path) + baseSegments.pop(); + for(let i = 0; i < baseSegments.length; ++i) { + rval += '../'; + } + } + + // prepend remaining segments + rval += iriSegments.join('/'); + + // add query and hash + if(rel.query !== null) { + rval += '?' + rel.query; + } + if(rel.fragment !== null) { + rval += '#' + rel.fragment; + } + + // handle empty base + if(rval === '') { + rval = './'; + } + + return rval; +}; + +/** + * Removes dot segments from a URL path. + * + * @param path the path to remove dot segments from. + */ +api.removeDotSegments = path => { + // RFC 3986 5.2.4 (reworked) + + // empty path shortcut + if(path.length === 0) { + return ''; + } + + const input = path.split('/'); + const output = []; + + while(input.length > 0) { + const next = input.shift(); + const done = input.length === 0; + + if(next === '.') { + if(done) { + // ensure output has trailing / + output.push(''); + } + continue; + } + + if(next === '..') { + output.pop(); + if(done) { + // ensure output has trailing / + output.push(''); + } + continue; + } + + output.push(next); + } + + // if path was absolute, ensure output has leading / + if(path[0] === '/' && output.length > 0 && output[0] !== '') { + output.unshift(''); + } + if(output.length === 1 && output[0] === '') { + return '/'; + } + + return output.join('/'); +}; + +// TODO: time better isAbsolute/isRelative checks using full regexes: +// http://jmrware.com/articles/2009/uri_regexp/URI_regex.html + +// regex to check for absolute IRI (starting scheme and ':') or blank node IRI +const isAbsoluteRegex = /^([A-Za-z][A-Za-z0-9+-.]*|_):[^\s]*$/; + +/** + * Returns true if the given value is an absolute IRI or blank node IRI, false + * if not. + * Note: This weak check only checks for a correct starting scheme. + * + * @param v the value to check. + * + * @return true if the value is an absolute IRI, false if not. + */ +api.isAbsolute = v => types.isString(v) && isAbsoluteRegex.test(v); + +/** + * Returns true if the given value is a relative IRI, false if not. + * Note: this is a weak check. + * + * @param v the value to check. + * + * @return true if the value is a relative IRI, false if not. + */ +api.isRelative = v => types.isString(v); + + +/***/ }), + +/***/ "./node_modules/jsonld/lib/util.js": +/*!*****************************************!*\ + !*** ./node_modules/jsonld/lib/util.js ***! + \*****************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* + * Copyright (c) 2017-2019 Digital Bazaar, Inc. All rights reserved. + */ + + +const graphTypes = __webpack_require__(/*! ./graphTypes */ "./node_modules/jsonld/lib/graphTypes.js"); +const types = __webpack_require__(/*! ./types */ "./node_modules/jsonld/lib/types.js"); +// TODO: move `IdentifierIssuer` to its own package +const IdentifierIssuer = __webpack_require__(/*! rdf-canonize */ "./node_modules/rdf-canonize/lib/index.js").IdentifierIssuer; +const JsonLdError = __webpack_require__(/*! ./JsonLdError */ "./node_modules/jsonld/lib/JsonLdError.js"); + +// constants +const REGEX_LINK_HEADERS = /(?:<[^>]*?>|"[^"]*?"|[^,])+/g; +const REGEX_LINK_HEADER = /\s*<([^>]*?)>\s*(?:;\s*(.*))?/; +const REGEX_LINK_HEADER_PARAMS = + /(.*?)=(?:(?:"([^"]*?)")|([^"]*?))\s*(?:(?:;\s*)|$)/g; + +const DEFAULTS = { + headers: { + accept: 'application/ld+json, application/json' + } +}; + +const api = {}; +module.exports = api; +api.IdentifierIssuer = IdentifierIssuer; + +/** + * Clones an object, array, Map, Set, or string/number. If a typed JavaScript + * object is given, such as a Date, it will be converted to a string. + * + * @param value the value to clone. + * + * @return the cloned value. + */ +api.clone = function(value) { + if(value && typeof value === 'object') { + let rval; + if(types.isArray(value)) { + rval = []; + for(let i = 0; i < value.length; ++i) { + rval[i] = api.clone(value[i]); + } + } else if(value instanceof Map) { + rval = new Map(); + for(const [k, v] of value) { + rval.set(k, api.clone(v)); + } + } else if(value instanceof Set) { + rval = new Set(); + for(const v of value) { + rval.add(api.clone(v)); + } + } else if(types.isObject(value)) { + rval = {}; + for(const key in value) { + rval[key] = api.clone(value[key]); + } + } else { + rval = value.toString(); + } + return rval; + } + return value; +}; + +/** + * Ensure a value is an array. If the value is an array, it is returned. + * Otherwise, it is wrapped in an array. + * + * @param value the value to return as an array. + * + * @return the value as an array. + */ +api.asArray = function(value) { + return Array.isArray(value) ? value : [value]; +}; + +/** + * Builds an HTTP headers object for making a JSON-LD request from custom + * headers and asserts the `accept` header isn't overridden. + * + * @param headers an object of headers with keys as header names and values + * as header values. + * + * @return an object of headers with a valid `accept` header. + */ +api.buildHeaders = (headers = {}) => { + const hasAccept = Object.keys(headers).some( + h => h.toLowerCase() === 'accept'); + + if(hasAccept) { + throw new RangeError( + 'Accept header may not be specified; only "' + + DEFAULTS.headers.accept + '" is supported.'); + } + + return Object.assign({Accept: DEFAULTS.headers.accept}, headers); +}; + +/** + * Parses a link header. The results will be key'd by the value of "rel". + * + * Link: ; + * rel="http://www.w3.org/ns/json-ld#context"; type="application/ld+json" + * + * Parses as: { + * 'http://www.w3.org/ns/json-ld#context': { + * target: http://json-ld.org/contexts/person.jsonld, + * type: 'application/ld+json' + * } + * } + * + * If there is more than one "rel" with the same IRI, then entries in the + * resulting map for that "rel" will be arrays. + * + * @param header the link header to parse. + */ +api.parseLinkHeader = header => { + const rval = {}; + // split on unbracketed/unquoted commas + const entries = header.match(REGEX_LINK_HEADERS); + for(let i = 0; i < entries.length; ++i) { + let match = entries[i].match(REGEX_LINK_HEADER); + if(!match) { + continue; + } + const result = {target: match[1]}; + const params = match[2]; + while((match = REGEX_LINK_HEADER_PARAMS.exec(params))) { + result[match[1]] = (match[2] === undefined) ? match[3] : match[2]; + } + const rel = result['rel'] || ''; + if(Array.isArray(rval[rel])) { + rval[rel].push(result); + } else if(rval.hasOwnProperty(rel)) { + rval[rel] = [rval[rel], result]; + } else { + rval[rel] = result; + } + } + return rval; +}; + +/** + * Throws an exception if the given value is not a valid @type value. + * + * @param v the value to check. + */ +api.validateTypeValue = (v, isFrame) => { + if(types.isString(v)) { + return; + } + + if(types.isArray(v) && v.every(vv => types.isString(vv))) { + return; + } + if(isFrame && types.isObject(v)) { + switch(Object.keys(v).length) { + case 0: + // empty object is wildcard + return; + case 1: + // default entry is all strings + if('@default' in v && + api.asArray(v['@default']).every(vv => types.isString(vv))) { + return; + } + } + } + + throw new JsonLdError( + 'Invalid JSON-LD syntax; "@type" value must a string, an array of ' + + 'strings, an empty object, ' + + 'or a default object.', 'jsonld.SyntaxError', + {code: 'invalid type value', value: v}); +}; + +/** + * Returns true if the given subject has the given property. + * + * @param subject the subject to check. + * @param property the property to look for. + * + * @return true if the subject has the given property, false if not. + */ +api.hasProperty = (subject, property) => { + if(subject.hasOwnProperty(property)) { + const value = subject[property]; + return (!types.isArray(value) || value.length > 0); + } + return false; +}; + +/** + * Determines if the given value is a property of the given subject. + * + * @param subject the subject to check. + * @param property the property to check. + * @param value the value to check. + * + * @return true if the value exists, false if not. + */ +api.hasValue = (subject, property, value) => { + if(api.hasProperty(subject, property)) { + let val = subject[property]; + const isList = graphTypes.isList(val); + if(types.isArray(val) || isList) { + if(isList) { + val = val['@list']; + } + for(let i = 0; i < val.length; ++i) { + if(api.compareValues(value, val[i])) { + return true; + } + } + } else if(!types.isArray(value)) { + // avoid matching the set of values with an array value parameter + return api.compareValues(value, val); + } + } + return false; +}; + +/** + * Adds a value to a subject. If the value is an array, all values in the + * array will be added. + * + * @param subject the subject to add the value to. + * @param property the property that relates the value to the subject. + * @param value the value to add. + * @param [options] the options to use: + * [propertyIsArray] true if the property is always an array, false + * if not (default: false). + * [valueIsArray] true if the value to be added should be preserved as + * an array (lists) (default: false). + * [allowDuplicate] true to allow duplicates, false not to (uses a + * simple shallow comparison of subject ID or value) (default: true). + * [prependValue] false to prepend value to any existing values. + * (default: false) + */ +api.addValue = (subject, property, value, options) => { + options = options || {}; + if(!('propertyIsArray' in options)) { + options.propertyIsArray = false; + } + if(!('valueIsArray' in options)) { + options.valueIsArray = false; + } + if(!('allowDuplicate' in options)) { + options.allowDuplicate = true; + } + if(!('prependValue' in options)) { + options.prependValue = false; + } + + if(options.valueIsArray) { + subject[property] = value; + } else if(types.isArray(value)) { + if(value.length === 0 && options.propertyIsArray && + !subject.hasOwnProperty(property)) { + subject[property] = []; + } + if(options.prependValue) { + value = value.concat(subject[property]); + subject[property] = []; + } + for(let i = 0; i < value.length; ++i) { + api.addValue(subject, property, value[i], options); + } + } else if(subject.hasOwnProperty(property)) { + // check if subject already has value if duplicates not allowed + const hasValue = (!options.allowDuplicate && + api.hasValue(subject, property, value)); + + // make property an array if value not present or always an array + if(!types.isArray(subject[property]) && + (!hasValue || options.propertyIsArray)) { + subject[property] = [subject[property]]; + } + + // add new value + if(!hasValue) { + if(options.prependValue) { + subject[property].unshift(value); + } else { + subject[property].push(value); + } + } + } else { + // add new value as set or single value + subject[property] = options.propertyIsArray ? [value] : value; + } +}; + +/** + * Gets all of the values for a subject's property as an array. + * + * @param subject the subject. + * @param property the property. + * + * @return all of the values for a subject's property as an array. + */ +api.getValues = (subject, property) => [].concat(subject[property] || []); + +/** + * Removes a property from a subject. + * + * @param subject the subject. + * @param property the property. + */ +api.removeProperty = (subject, property) => { + delete subject[property]; +}; + +/** + * Removes a value from a subject. + * + * @param subject the subject. + * @param property the property that relates the value to the subject. + * @param value the value to remove. + * @param [options] the options to use: + * [propertyIsArray] true if the property is always an array, false + * if not (default: false). + */ +api.removeValue = (subject, property, value, options) => { + options = options || {}; + if(!('propertyIsArray' in options)) { + options.propertyIsArray = false; + } + + // filter out value + const values = api.getValues(subject, property).filter( + e => !api.compareValues(e, value)); + + if(values.length === 0) { + api.removeProperty(subject, property); + } else if(values.length === 1 && !options.propertyIsArray) { + subject[property] = values[0]; + } else { + subject[property] = values; + } +}; + +/** + * Relabels all blank nodes in the given JSON-LD input. + * + * @param input the JSON-LD input. + * @param [options] the options to use: + * [issuer] an IdentifierIssuer to use to label blank nodes. + */ +api.relabelBlankNodes = (input, options) => { + options = options || {}; + const issuer = options.issuer || new IdentifierIssuer('_:b'); + return _labelBlankNodes(issuer, input); +}; + +/** + * Compares two JSON-LD values for equality. Two JSON-LD values will be + * considered equal if: + * + * 1. They are both primitives of the same type and value. + * 2. They are both @values with the same @value, @type, @language, + * and @index, OR + * 3. They both have @ids they are the same. + * + * @param v1 the first value. + * @param v2 the second value. + * + * @return true if v1 and v2 are considered equal, false if not. + */ +api.compareValues = (v1, v2) => { + // 1. equal primitives + if(v1 === v2) { + return true; + } + + // 2. equal @values + if(graphTypes.isValue(v1) && graphTypes.isValue(v2) && + v1['@value'] === v2['@value'] && + v1['@type'] === v2['@type'] && + v1['@language'] === v2['@language'] && + v1['@index'] === v2['@index']) { + return true; + } + + // 3. equal @ids + if(types.isObject(v1) && + ('@id' in v1) && + types.isObject(v2) && + ('@id' in v2)) { + return v1['@id'] === v2['@id']; + } + + return false; +}; + +/** + * Compares two strings first based on length and then lexicographically. + * + * @param a the first string. + * @param b the second string. + * + * @return -1 if a < b, 1 if a > b, 0 if a === b. + */ +api.compareShortestLeast = (a, b) => { + if(a.length < b.length) { + return -1; + } + if(b.length < a.length) { + return 1; + } + if(a === b) { + return 0; + } + return (a < b) ? -1 : 1; +}; + +/** + * Labels the blank nodes in the given value using the given IdentifierIssuer. + * + * @param issuer the IdentifierIssuer to use. + * @param element the element with blank nodes to rename. + * + * @return the element. + */ +function _labelBlankNodes(issuer, element) { + if(types.isArray(element)) { + for(let i = 0; i < element.length; ++i) { + element[i] = _labelBlankNodes(issuer, element[i]); + } + } else if(graphTypes.isList(element)) { + element['@list'] = _labelBlankNodes(issuer, element['@list']); + } else if(types.isObject(element)) { + // relabel blank node + if(graphTypes.isBlankNode(element)) { + element['@id'] = issuer.getId(element['@id']); + } + + // recursively apply to all keys + const keys = Object.keys(element).sort(); + for(let ki = 0; ki < keys.length; ++ki) { + const key = keys[ki]; + if(key !== '@id') { + element[key] = _labelBlankNodes(issuer, element[key]); + } + } + } + + return element; +} + + +/***/ }), + +/***/ "./node_modules/jss-plugin-camel-case/dist/jss-plugin-camel-case.esm.js": +/*!******************************************************************************!*\ + !*** ./node_modules/jss-plugin-camel-case/dist/jss-plugin-camel-case.esm.js ***! + \******************************************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var hyphenate_style_name__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! hyphenate-style-name */ "./node_modules/hyphenate-style-name/index.js"); + + +/** + * Convert camel cased property names to dash separated. + * + * @param {Object} style + * @return {Object} + */ + +function convertCase(style) { + var converted = {}; + + for (var prop in style) { + var key = prop.indexOf('--') === 0 ? prop : Object(hyphenate_style_name__WEBPACK_IMPORTED_MODULE_0__["default"])(prop); + converted[key] = style[prop]; + } + + if (style.fallbacks) { + if (Array.isArray(style.fallbacks)) converted.fallbacks = style.fallbacks.map(convertCase);else converted.fallbacks = convertCase(style.fallbacks); + } + + return converted; +} +/** + * Allow camel cased property names by converting them back to dasherized. + * + * @param {Rule} rule + */ + + +function camelCase() { + function onProcessStyle(style) { + if (Array.isArray(style)) { + // Handle rules like @font-face, which can have multiple styles in an array + for (var index = 0; index < style.length; index++) { + style[index] = convertCase(style[index]); + } + + return style; + } + + return convertCase(style); + } + + function onChangeValue(value, prop, rule) { + if (prop.indexOf('--') === 0) { + return value; + } + + var hyphenatedProp = Object(hyphenate_style_name__WEBPACK_IMPORTED_MODULE_0__["default"])(prop); // There was no camel case in place + + if (prop === hyphenatedProp) return value; + rule.prop(hyphenatedProp, value); // Core will ignore that property value we set the proper one above. + + return null; + } + + return { + onProcessStyle: onProcessStyle, + onChangeValue: onChangeValue + }; +} + +/* harmony default export */ __webpack_exports__["default"] = (camelCase); + + +/***/ }), + +/***/ "./node_modules/jss-plugin-compose/dist/jss-plugin-compose.esm.js": +/*!************************************************************************!*\ + !*** ./node_modules/jss-plugin-compose/dist/jss-plugin-compose.esm.js ***! + \************************************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var tiny_warning__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tiny-warning */ "./node_modules/tiny-warning/dist/tiny-warning.esm.js"); + + +/** + * Set selector. + * + * @param {Object} original rule + * @param {String} className class string + * @return {Boolean} flag, indicating function was successfull or not + */ +function registerClass(rule, className) { + // Skip falsy values + if (!className) return true; // Support array of class names `{composes: ['foo', 'bar']}` + + if (Array.isArray(className)) { + for (var index = 0; index < className.length; index++) { + var isSetted = registerClass(rule, className[index]); + if (!isSetted) return false; + } + + return true; + } // Support space separated class names `{composes: 'foo bar'}` + + + if (className.indexOf(' ') > -1) { + return registerClass(rule, className.split(' ')); + } + + var _ref = rule.options, + parent = _ref.parent; // It is a ref to a local rule. + + if (className[0] === '$') { + var refRule = parent.getRule(className.substr(1)); + + if (!refRule) { + true ? Object(tiny_warning__WEBPACK_IMPORTED_MODULE_0__["default"])(false, "[JSS] Referenced rule is not defined. \n" + rule.toString()) : undefined; + return false; + } + + if (refRule === rule) { + true ? Object(tiny_warning__WEBPACK_IMPORTED_MODULE_0__["default"])(false, "[JSS] Cyclic composition detected. \n" + rule.toString()) : undefined; + return false; + } + + parent.classes[rule.key] += " " + parent.classes[refRule.key]; + return true; + } + + parent.classes[rule.key] += " " + className; + return true; +} +/** + * Convert compose property to additional class, remove property from original styles. + * + * @param {Rule} rule + * @api public + */ + + +function jssCompose() { + function onProcessStyle(style, rule) { + if (!('composes' in style)) return style; + registerClass(rule, style.composes); // Remove composes property to prevent infinite loop. + + delete style.composes; + return style; + } + + return { + onProcessStyle: onProcessStyle + }; +} + +/* harmony default export */ __webpack_exports__["default"] = (jssCompose); + + +/***/ }), + +/***/ "./node_modules/jss-plugin-default-unit/dist/jss-plugin-default-unit.esm.js": +/*!**********************************************************************************!*\ + !*** ./node_modules/jss-plugin-default-unit/dist/jss-plugin-default-unit.esm.js ***! + \**********************************************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var jss__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! jss */ "./node_modules/jss/dist/jss.esm.js"); + + +var px = jss__WEBPACK_IMPORTED_MODULE_0__["hasCSSTOMSupport"] && CSS ? CSS.px : 'px'; +var ms = jss__WEBPACK_IMPORTED_MODULE_0__["hasCSSTOMSupport"] && CSS ? CSS.ms : 'ms'; +var percent = jss__WEBPACK_IMPORTED_MODULE_0__["hasCSSTOMSupport"] && CSS ? CSS.percent : '%'; +/** + * Generated jss-plugin-default-unit CSS property units + * + * @type object + */ + +var defaultUnits = { + // Animation properties + 'animation-delay': ms, + 'animation-duration': ms, + // Background properties + 'background-position': px, + 'background-position-x': px, + 'background-position-y': px, + 'background-size': px, + // Border Properties + border: px, + 'border-bottom': px, + 'border-bottom-left-radius': px, + 'border-bottom-right-radius': px, + 'border-bottom-width': px, + 'border-left': px, + 'border-left-width': px, + 'border-radius': px, + 'border-right': px, + 'border-right-width': px, + 'border-top': px, + 'border-top-left-radius': px, + 'border-top-right-radius': px, + 'border-top-width': px, + 'border-width': px, + 'border-block': px, + 'border-block-end': px, + 'border-block-end-width': px, + 'border-block-start': px, + 'border-block-start-width': px, + 'border-block-width': px, + 'border-inline': px, + 'border-inline-end': px, + 'border-inline-end-width': px, + 'border-inline-start': px, + 'border-inline-start-width': px, + 'border-inline-width': px, + 'border-start-start-radius': px, + 'border-start-end-radius': px, + 'border-end-start-radius': px, + 'border-end-end-radius': px, + // Margin properties + margin: px, + 'margin-bottom': px, + 'margin-left': px, + 'margin-right': px, + 'margin-top': px, + 'margin-block': px, + 'margin-block-end': px, + 'margin-block-start': px, + 'margin-inline': px, + 'margin-inline-end': px, + 'margin-inline-start': px, + // Padding properties + padding: px, + 'padding-bottom': px, + 'padding-left': px, + 'padding-right': px, + 'padding-top': px, + 'padding-block': px, + 'padding-block-end': px, + 'padding-block-start': px, + 'padding-inline': px, + 'padding-inline-end': px, + 'padding-inline-start': px, + // Mask properties + 'mask-position-x': px, + 'mask-position-y': px, + 'mask-size': px, + // Width and height properties + height: px, + width: px, + 'min-height': px, + 'max-height': px, + 'min-width': px, + 'max-width': px, + // Position properties + bottom: px, + left: px, + top: px, + right: px, + inset: px, + 'inset-block': px, + 'inset-block-end': px, + 'inset-block-start': px, + 'inset-inline': px, + 'inset-inline-end': px, + 'inset-inline-start': px, + // Shadow properties + 'box-shadow': px, + 'text-shadow': px, + // Column properties + 'column-gap': px, + 'column-rule': px, + 'column-rule-width': px, + 'column-width': px, + // Font and text properties + 'font-size': px, + 'font-size-delta': px, + 'letter-spacing': px, + 'text-indent': px, + 'text-stroke': px, + 'text-stroke-width': px, + 'word-spacing': px, + // Motion properties + motion: px, + 'motion-offset': px, + // Outline properties + outline: px, + 'outline-offset': px, + 'outline-width': px, + // Perspective properties + perspective: px, + 'perspective-origin-x': percent, + 'perspective-origin-y': percent, + // Transform properties + 'transform-origin': percent, + 'transform-origin-x': percent, + 'transform-origin-y': percent, + 'transform-origin-z': percent, + // Transition properties + 'transition-delay': ms, + 'transition-duration': ms, + // Alignment properties + 'vertical-align': px, + 'flex-basis': px, + // Some random properties + 'shape-margin': px, + size: px, + gap: px, + // Grid properties + grid: px, + 'grid-gap': px, + 'grid-row-gap': px, + 'grid-column-gap': px, + 'grid-template-rows': px, + 'grid-template-columns': px, + 'grid-auto-rows': px, + 'grid-auto-columns': px, + // Not existing properties. + // Used to avoid issues with jss-plugin-expand integration. + 'box-shadow-x': px, + 'box-shadow-y': px, + 'box-shadow-blur': px, + 'box-shadow-spread': px, + 'font-line-height': px, + 'text-shadow-x': px, + 'text-shadow-y': px, + 'text-shadow-blur': px +}; + +/** + * Clones the object and adds a camel cased property version. + */ +function addCamelCasedVersion(obj) { + var regExp = /(-[a-z])/g; + + var replace = function replace(str) { + return str[1].toUpperCase(); + }; + + var newObj = {}; + + for (var _key in obj) { + newObj[_key] = obj[_key]; + newObj[_key.replace(regExp, replace)] = obj[_key]; + } + + return newObj; +} + +var units = addCamelCasedVersion(defaultUnits); +/** + * Recursive deep style passing function + */ + +function iterate(prop, value, options) { + if (value == null) return value; + + if (Array.isArray(value)) { + for (var i = 0; i < value.length; i++) { + value[i] = iterate(prop, value[i], options); + } + } else if (typeof value === 'object') { + if (prop === 'fallbacks') { + for (var innerProp in value) { + value[innerProp] = iterate(innerProp, value[innerProp], options); + } + } else { + for (var _innerProp in value) { + value[_innerProp] = iterate(prop + "-" + _innerProp, value[_innerProp], options); + } + } + } else if (typeof value === 'number') { + var unit = options[prop] || units[prop]; // Add the unit if available, except for the special case of 0px. + + if (unit && !(value === 0 && unit === px)) { + return typeof unit === 'function' ? unit(value).toString() : "" + value + unit; + } + + return value.toString(); + } + + return value; +} +/** + * Add unit to numeric values. + */ + + +function defaultUnit(options) { + if (options === void 0) { + options = {}; + } + + var camelCasedOptions = addCamelCasedVersion(options); + + function onProcessStyle(style, rule) { + if (rule.type !== 'style') return style; + + for (var prop in style) { + style[prop] = iterate(prop, style[prop], camelCasedOptions); + } + + return style; + } + + function onChangeValue(value, prop) { + return iterate(prop, value, camelCasedOptions); + } + + return { + onProcessStyle: onProcessStyle, + onChangeValue: onChangeValue + }; +} + +/* harmony default export */ __webpack_exports__["default"] = (defaultUnit); + + +/***/ }), + +/***/ "./node_modules/jss-plugin-expand/dist/jss-plugin-expand.esm.js": +/*!**********************************************************************!*\ + !*** ./node_modules/jss-plugin-expand/dist/jss-plugin-expand.esm.js ***! + \**********************************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/** + * A scheme for converting properties from array to regular style. + * All properties listed below will be transformed to a string separated by space. + */ +var propArray = { + 'background-size': true, + 'background-position': true, + border: true, + 'border-bottom': true, + 'border-left': true, + 'border-top': true, + 'border-right': true, + 'border-radius': true, + 'border-image': true, + 'border-width': true, + 'border-style': true, + 'border-color': true, + 'box-shadow': true, + flex: true, + margin: true, + padding: true, + outline: true, + 'transform-origin': true, + transform: true, + transition: true + /** + * A scheme for converting arrays to regular styles inside of objects. + * For e.g.: "{position: [0, 0]}" => "background-position: 0 0;". + */ + +}; +var propArrayInObj = { + position: true, + // background-position + size: true // background-size + + /** + * A scheme for parsing and building correct styles from passed objects. + */ + +}; +var propObj = { + padding: { + top: 0, + right: 0, + bottom: 0, + left: 0 + }, + margin: { + top: 0, + right: 0, + bottom: 0, + left: 0 + }, + background: { + attachment: null, + color: null, + image: null, + position: null, + repeat: null + }, + border: { + width: null, + style: null, + color: null + }, + 'border-top': { + width: null, + style: null, + color: null + }, + 'border-right': { + width: null, + style: null, + color: null + }, + 'border-bottom': { + width: null, + style: null, + color: null + }, + 'border-left': { + width: null, + style: null, + color: null + }, + outline: { + width: null, + style: null, + color: null + }, + 'list-style': { + type: null, + position: null, + image: null + }, + transition: { + property: null, + duration: null, + 'timing-function': null, + timingFunction: null, + // Needed for avoiding comilation issues with jss-plugin-camel-case + delay: null + }, + animation: { + name: null, + duration: null, + 'timing-function': null, + timingFunction: null, + // Needed to avoid compilation issues with jss-plugin-camel-case + delay: null, + 'iteration-count': null, + iterationCount: null, + // Needed to avoid compilation issues with jss-plugin-camel-case + direction: null, + 'fill-mode': null, + fillMode: null, + // Needed to avoid compilation issues with jss-plugin-camel-case + 'play-state': null, + playState: null // Needed to avoid compilation issues with jss-plugin-camel-case + + }, + 'box-shadow': { + x: 0, + y: 0, + blur: 0, + spread: 0, + color: null, + inset: null + }, + 'text-shadow': { + x: 0, + y: 0, + blur: null, + color: null + } + /** + * A scheme for converting non-standart properties inside object. + * For e.g.: include 'border-radius' property inside 'border' object. + */ + +}; +var customPropObj = { + border: { + radius: 'border-radius', + image: 'border-image', + width: 'border-width', + style: 'border-style', + color: 'border-color' + }, + 'border-bottom': { + width: 'border-bottom-width', + style: 'border-bottom-style', + color: 'border-bottom-color' + }, + 'border-top': { + width: 'border-top-width', + style: 'border-top-style', + color: 'border-top-color' + }, + 'border-left': { + width: 'border-left-width', + style: 'border-left-style', + color: 'border-left-color' + }, + 'border-right': { + width: 'border-right-width', + style: 'border-right-style', + color: 'border-right-color' + }, + background: { + size: 'background-size', + image: 'background-image' + }, + font: { + style: 'font-style', + variant: 'font-variant', + weight: 'font-weight', + stretch: 'font-stretch', + size: 'font-size', + family: 'font-family', + lineHeight: 'line-height', + // Needed to avoid compilation issues with jss-plugin-camel-case + 'line-height': 'line-height' + }, + flex: { + grow: 'flex-grow', + basis: 'flex-basis', + direction: 'flex-direction', + wrap: 'flex-wrap', + flow: 'flex-flow', + shrink: 'flex-shrink' + }, + align: { + self: 'align-self', + items: 'align-items', + content: 'align-content' + }, + grid: { + 'template-columns': 'grid-template-columns', + templateColumns: 'grid-template-columns', + 'template-rows': 'grid-template-rows', + templateRows: 'grid-template-rows', + 'template-areas': 'grid-template-areas', + templateAreas: 'grid-template-areas', + template: 'grid-template', + 'auto-columns': 'grid-auto-columns', + autoColumns: 'grid-auto-columns', + 'auto-rows': 'grid-auto-rows', + autoRows: 'grid-auto-rows', + 'auto-flow': 'grid-auto-flow', + autoFlow: 'grid-auto-flow', + row: 'grid-row', + column: 'grid-column', + 'row-start': 'grid-row-start', + rowStart: 'grid-row-start', + 'row-end': 'grid-row-end', + rowEnd: 'grid-row-end', + 'column-start': 'grid-column-start', + columnStart: 'grid-column-start', + 'column-end': 'grid-column-end', + columnEnd: 'grid-column-end', + area: 'grid-area', + gap: 'grid-gap', + 'row-gap': 'grid-row-gap', + rowGap: 'grid-row-gap', + 'column-gap': 'grid-column-gap', + columnGap: 'grid-column-gap' + } +}; + +/* eslint-disable no-use-before-define */ + +/** + * Map values by given prop. + * + * @param {Array} array of values + * @param {String} original property + * @param {String} original rule + * @return {String} mapped values + */ +function mapValuesByProp(value, prop, rule) { + return value.map(function (item) { + return objectToArray(item, prop, rule, false, true); + }); +} +/** + * Convert array to nested array, if needed + */ + + +function processArray(value, prop, scheme, rule) { + if (scheme[prop] == null) return value; + if (value.length === 0) return []; + if (Array.isArray(value[0])) return processArray(value[0], prop, scheme, rule); + + if (typeof value[0] === 'object') { + return mapValuesByProp(value, prop, rule); + } + + return [value]; +} +/** + * Convert object to array. + */ + + +function objectToArray(value, prop, rule, isFallback, isInArray) { + if (!(propObj[prop] || customPropObj[prop])) return []; + var result = []; // Check if exists any non-standard property + + if (customPropObj[prop]) { + // eslint-disable-next-line no-param-reassign + value = customPropsToStyle(value, rule, customPropObj[prop], isFallback); + } // Pass throught all standart props + + + if (Object.keys(value).length) { + for (var baseProp in propObj[prop]) { + if (value[baseProp]) { + if (Array.isArray(value[baseProp])) { + result.push(propArrayInObj[baseProp] === null ? value[baseProp] : value[baseProp].join(' ')); + } else result.push(value[baseProp]); + + continue; + } // Add default value from props config. + + + if (propObj[prop][baseProp] != null) { + result.push(propObj[prop][baseProp]); + } + } + } + + if (!result.length || isInArray) return result; + return [result]; +} +/** + * Convert custom properties values to styles adding them to rule directly + */ + + +function customPropsToStyle(value, rule, customProps, isFallback) { + for (var prop in customProps) { + var propName = customProps[prop]; // If current property doesn't exist already in rule - add new one + + if (typeof value[prop] !== 'undefined' && (isFallback || !rule.prop(propName))) { + var _styleDetector; + + var appendedValue = styleDetector((_styleDetector = {}, _styleDetector[propName] = value[prop], _styleDetector), rule)[propName]; // Add style directly in rule + + if (isFallback) rule.style.fallbacks[propName] = appendedValue;else rule.style[propName] = appendedValue; + } // Delete converted property to avoid double converting + + + delete value[prop]; + } + + return value; +} +/** + * Detect if a style needs to be converted. + */ + + +function styleDetector(style, rule, isFallback) { + for (var prop in style) { + var value = style[prop]; + + if (Array.isArray(value)) { + // Check double arrays to avoid recursion. + if (!Array.isArray(value[0])) { + if (prop === 'fallbacks') { + for (var index = 0; index < style.fallbacks.length; index++) { + style.fallbacks[index] = styleDetector(style.fallbacks[index], rule, true); + } + + continue; + } + + style[prop] = processArray(value, prop, propArray, rule); // Avoid creating properties with empty values + + if (!style[prop].length) delete style[prop]; + } + } else if (typeof value === 'object') { + if (prop === 'fallbacks') { + style.fallbacks = styleDetector(style.fallbacks, rule, true); + continue; + } + + style[prop] = objectToArray(value, prop, rule, isFallback); // Avoid creating properties with empty values + + if (!style[prop].length) delete style[prop]; + } // Maybe a computed value resulting in an empty string + else if (style[prop] === '') delete style[prop]; + } + + return style; +} +/** + * Adds possibility to write expanded styles. + */ + + +function jssExpand() { + function onProcessStyle(style, rule) { + if (!style || rule.type !== 'style') return style; + + if (Array.isArray(style)) { + // Pass rules one by one and reformat them + for (var index = 0; index < style.length; index++) { + style[index] = styleDetector(style[index], rule); + } + + return style; + } + + return styleDetector(style, rule); + } + + return { + onProcessStyle: onProcessStyle + }; +} + +/* harmony default export */ __webpack_exports__["default"] = (jssExpand); + + +/***/ }), + +/***/ "./node_modules/jss-plugin-extend/dist/jss-plugin-extend.esm.js": +/*!**********************************************************************!*\ + !*** ./node_modules/jss-plugin-extend/dist/jss-plugin-extend.esm.js ***! + \**********************************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/esm/extends */ "./node_modules/@babel/runtime/helpers/esm/extends.js"); +/* harmony import */ var tiny_warning__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! tiny-warning */ "./node_modules/tiny-warning/dist/tiny-warning.esm.js"); + + + +var isObject = function isObject(obj) { + return obj && typeof obj === 'object' && !Array.isArray(obj); +}; + +var valueNs = "extendCurrValue" + Date.now(); + +function mergeExtend(style, rule, sheet, newStyle) { + var extendType = typeof style.extend; // Extend using a rule name. + + if (extendType === 'string') { + if (!sheet) return; + var refRule = sheet.getRule(style.extend); + if (!refRule) return; + + if (refRule === rule) { + true ? Object(tiny_warning__WEBPACK_IMPORTED_MODULE_1__["default"])(false, "[JSS] A rule tries to extend itself \n" + rule.toString()) : undefined; + return; + } + + var parent = refRule.options.parent; + + if (parent) { + var originalStyle = parent.rules.raw[style.extend]; + extend(originalStyle, rule, sheet, newStyle); + } + + return; + } // Extend using an array. + + + if (Array.isArray(style.extend)) { + for (var index = 0; index < style.extend.length; index++) { + var singleExtend = style.extend[index]; + var singleStyle = typeof singleExtend === 'string' ? Object(_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_0__["default"])({}, style, { + extend: singleExtend + }) : style.extend[index]; + extend(singleStyle, rule, sheet, newStyle); + } + + return; + } // Extend is a style object. + + + for (var prop in style.extend) { + if (prop === 'extend') { + extend(style.extend.extend, rule, sheet, newStyle); + continue; + } + + if (isObject(style.extend[prop])) { + if (!(prop in newStyle)) newStyle[prop] = {}; + extend(style.extend[prop], rule, sheet, newStyle[prop]); + continue; + } + + newStyle[prop] = style.extend[prop]; + } +} + +function mergeRest(style, rule, sheet, newStyle) { + // Copy base style. + for (var prop in style) { + if (prop === 'extend') continue; + + if (isObject(newStyle[prop]) && isObject(style[prop])) { + extend(style[prop], rule, sheet, newStyle[prop]); + continue; + } + + if (isObject(style[prop])) { + newStyle[prop] = extend(style[prop], rule, sheet); + continue; + } + + newStyle[prop] = style[prop]; + } +} +/** + * Recursively extend styles. + */ + + +function extend(style, rule, sheet, newStyle) { + if (newStyle === void 0) { + newStyle = {}; + } + + mergeExtend(style, rule, sheet, newStyle); + mergeRest(style, rule, sheet, newStyle); + return newStyle; +} +/** + * Handle `extend` property. + * + * @param {Rule} rule + * @api public + */ + + +function jssExtend() { + function onProcessStyle(style, rule, sheet) { + if ('extend' in style) return extend(style, rule, sheet); + return style; + } + + function onChangeValue(value, prop, rule) { + if (prop !== 'extend') return value; // Value is empty, remove properties set previously. + + if (value == null || value === false) { + // $FlowFixMe[prop-missing] + for (var key in rule[valueNs]) { + rule.prop(key, null); + } // $FlowFixMe[prop-missing] Flow complains because there is no indexer property in StyleRule + + + rule[valueNs] = null; + return null; + } + + if (typeof value === 'object') { + // $FlowFixMe[invalid-in-rhs] This will be an object + for (var _key in value) { + // $FlowFixMe[incompatible-use] This will be an object + rule.prop(_key, value[_key]); + } // $FlowFixMe[prop-missing] Flow complains because there is no indexer property in StyleRule + + + rule[valueNs] = value; + } // Make sure we don't set the value in the core. + + + return null; + } + + return { + onProcessStyle: onProcessStyle, + onChangeValue: onChangeValue + }; +} + +/* harmony default export */ __webpack_exports__["default"] = (jssExtend); + + +/***/ }), + +/***/ "./node_modules/jss-plugin-global/dist/jss-plugin-global.esm.js": +/*!**********************************************************************!*\ + !*** ./node_modules/jss-plugin-global/dist/jss-plugin-global.esm.js ***! + \**********************************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/esm/extends */ "./node_modules/@babel/runtime/helpers/esm/extends.js"); +/* harmony import */ var jss__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! jss */ "./node_modules/jss/dist/jss.esm.js"); + + + +var at = '@global'; +var atPrefix = '@global '; + +var GlobalContainerRule = +/*#__PURE__*/ +function () { + function GlobalContainerRule(key, styles, options) { + this.type = 'global'; + this.at = at; + this.rules = void 0; + this.options = void 0; + this.key = void 0; + this.isProcessed = false; + this.key = key; + this.options = options; + this.rules = new jss__WEBPACK_IMPORTED_MODULE_1__["RuleList"](Object(_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_0__["default"])({}, options, { + parent: this + })); + + for (var selector in styles) { + this.rules.add(selector, styles[selector]); + } + + this.rules.process(); + } + /** + * Get a rule. + */ + + + var _proto = GlobalContainerRule.prototype; + + _proto.getRule = function getRule(name) { + return this.rules.get(name); + } + /** + * Create and register rule, run plugins. + */ + ; + + _proto.addRule = function addRule(name, style, options) { + var rule = this.rules.add(name, style, options); + if (rule) this.options.jss.plugins.onProcessRule(rule); + return rule; + } + /** + * Get index of a rule. + */ + ; + + _proto.indexOf = function indexOf(rule) { + return this.rules.indexOf(rule); + } + /** + * Generates a CSS string. + */ + ; + + _proto.toString = function toString() { + return this.rules.toString(); + }; + + return GlobalContainerRule; +}(); + +var GlobalPrefixedRule = +/*#__PURE__*/ +function () { + function GlobalPrefixedRule(key, style, options) { + this.type = 'global'; + this.at = at; + this.options = void 0; + this.rule = void 0; + this.isProcessed = false; + this.key = void 0; + this.key = key; + this.options = options; + var selector = key.substr(atPrefix.length); + this.rule = options.jss.createRule(selector, style, Object(_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_0__["default"])({}, options, { + parent: this + })); + } + + var _proto2 = GlobalPrefixedRule.prototype; + + _proto2.toString = function toString(options) { + return this.rule ? this.rule.toString(options) : ''; + }; + + return GlobalPrefixedRule; +}(); + +var separatorRegExp = /\s*,\s*/g; + +function addScope(selector, scope) { + var parts = selector.split(separatorRegExp); + var scoped = ''; + + for (var i = 0; i < parts.length; i++) { + scoped += scope + " " + parts[i].trim(); + if (parts[i + 1]) scoped += ', '; + } + + return scoped; +} + +function handleNestedGlobalContainerRule(rule, sheet) { + var options = rule.options, + style = rule.style; + var rules = style ? style[at] : null; + if (!rules) return; + + for (var name in rules) { + sheet.addRule(name, rules[name], Object(_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_0__["default"])({}, options, { + selector: addScope(name, rule.selector) + })); + } + + delete style[at]; +} + +function handlePrefixedGlobalRule(rule, sheet) { + var options = rule.options, + style = rule.style; + + for (var prop in style) { + if (prop[0] !== '@' || prop.substr(0, at.length) !== at) continue; + var selector = addScope(prop.substr(at.length), rule.selector); + sheet.addRule(selector, style[prop], Object(_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_0__["default"])({}, options, { + selector: selector + })); + delete style[prop]; + } +} +/** + * Convert nested rules to separate, remove them from original styles. + * + * @param {Rule} rule + * @api public + */ + + +function jssGlobal() { + function onCreateRule(name, styles, options) { + if (!name) return null; + + if (name === at) { + return new GlobalContainerRule(name, styles, options); + } + + if (name[0] === '@' && name.substr(0, atPrefix.length) === atPrefix) { + return new GlobalPrefixedRule(name, styles, options); + } + + var parent = options.parent; + + if (parent) { + if (parent.type === 'global' || parent.options.parent && parent.options.parent.type === 'global') { + options.scoped = false; + } + } + + if (options.scoped === false) { + options.selector = name; + } + + return null; + } + + function onProcessRule(rule, sheet) { + if (rule.type !== 'style' || !sheet) return; + handleNestedGlobalContainerRule(rule, sheet); + handlePrefixedGlobalRule(rule, sheet); + } + + return { + onCreateRule: onCreateRule, + onProcessRule: onProcessRule + }; +} + +/* harmony default export */ __webpack_exports__["default"] = (jssGlobal); + + +/***/ }), + +/***/ "./node_modules/jss-plugin-nested/dist/jss-plugin-nested.esm.js": +/*!**********************************************************************!*\ + !*** ./node_modules/jss-plugin-nested/dist/jss-plugin-nested.esm.js ***! + \**********************************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/esm/extends */ "./node_modules/@babel/runtime/helpers/esm/extends.js"); +/* harmony import */ var tiny_warning__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! tiny-warning */ "./node_modules/tiny-warning/dist/tiny-warning.esm.js"); + + + +var separatorRegExp = /\s*,\s*/g; +var parentRegExp = /&/g; +var refRegExp = /\$([\w-]+)/g; +/** + * Convert nested rules to separate, remove them from original styles. + * + * @param {Rule} rule + * @api public + */ + +function jssNested() { + // Get a function to be used for $ref replacement. + function getReplaceRef(container, sheet) { + return function (match, key) { + var rule = container.getRule(key) || sheet && sheet.getRule(key); + + if (rule) { + rule = rule; + return rule.selector; + } + + true ? Object(tiny_warning__WEBPACK_IMPORTED_MODULE_1__["default"])(false, "[JSS] Could not find the referenced rule \"" + key + "\" in \"" + (container.options.meta || container.toString()) + "\".") : undefined; + return key; + }; + } + + function replaceParentRefs(nestedProp, parentProp) { + var parentSelectors = parentProp.split(separatorRegExp); + var nestedSelectors = nestedProp.split(separatorRegExp); + var result = ''; + + for (var i = 0; i < parentSelectors.length; i++) { + var parent = parentSelectors[i]; + + for (var j = 0; j < nestedSelectors.length; j++) { + var nested = nestedSelectors[j]; + if (result) result += ', '; // Replace all & by the parent or prefix & with the parent. + + result += nested.indexOf('&') !== -1 ? nested.replace(parentRegExp, parent) : parent + " " + nested; + } + } + + return result; + } + + function getOptions(rule, container, prevOptions) { + // Options has been already created, now we only increase index. + if (prevOptions) return Object(_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_0__["default"])({}, prevOptions, { + index: prevOptions.index + 1 // $FlowFixMe[prop-missing] + + }); + var nestingLevel = rule.options.nestingLevel; + nestingLevel = nestingLevel === undefined ? 1 : nestingLevel + 1; + + var options = Object(_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_0__["default"])({}, rule.options, { + nestingLevel: nestingLevel, + index: container.indexOf(rule) + 1 // We don't need the parent name to be set options for chlid. + + }); + + delete options.name; + return options; + } + + function onProcessStyle(style, rule, sheet) { + if (rule.type !== 'style') return style; + var styleRule = rule; + var container = styleRule.options.parent; + var options; + var replaceRef; + + for (var prop in style) { + var isNested = prop.indexOf('&') !== -1; + var isNestedConditional = prop[0] === '@'; + if (!isNested && !isNestedConditional) continue; + options = getOptions(styleRule, container, options); + + if (isNested) { + var selector = replaceParentRefs(prop, styleRule.selector); // Lazily create the ref replacer function just once for + // all nested rules within the sheet. + + if (!replaceRef) replaceRef = getReplaceRef(container, sheet); // Replace all $refs. + + selector = selector.replace(refRegExp, replaceRef); + container.addRule(selector, style[prop], Object(_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_0__["default"])({}, options, { + selector: selector + })); + } else if (isNestedConditional) { + // Place conditional right after the parent rule to ensure right ordering. + container.addRule(prop, {}, options) // Flow expects more options but they aren't required + // And flow doesn't know this will always be a StyleRule which has the addRule method + // $FlowFixMe[incompatible-use] + // $FlowFixMe[prop-missing] + .addRule(styleRule.key, style[prop], { + selector: styleRule.selector + }); + } + + delete style[prop]; + } + + return style; + } + + return { + onProcessStyle: onProcessStyle + }; +} + +/* harmony default export */ __webpack_exports__["default"] = (jssNested); + + +/***/ }), + +/***/ "./node_modules/jss-plugin-props-sort/dist/jss-plugin-props-sort.esm.js": +/*!******************************************************************************!*\ + !*** ./node_modules/jss-plugin-props-sort/dist/jss-plugin-props-sort.esm.js ***! + \******************************************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/** + * Sort props by length. + */ +function jssPropsSort() { + var sort = function sort(prop0, prop1) { + if (prop0.length === prop1.length) { + return prop0 > prop1 ? 1 : -1; + } + + return prop0.length - prop1.length; + }; + + return { + onProcessStyle: function onProcessStyle(style, rule) { + if (rule.type !== 'style') return style; + var newStyle = {}; + var props = Object.keys(style).sort(sort); + + for (var i = 0; i < props.length; i++) { + newStyle[props[i]] = style[props[i]]; + } + + return newStyle; + } + }; +} + +/* harmony default export */ __webpack_exports__["default"] = (jssPropsSort); + + +/***/ }), + +/***/ "./node_modules/jss-plugin-rule-value-function/dist/jss-plugin-rule-value-function.esm.js": +/*!************************************************************************************************!*\ + !*** ./node_modules/jss-plugin-rule-value-function/dist/jss-plugin-rule-value-function.esm.js ***! + \************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var tiny_warning__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tiny-warning */ "./node_modules/tiny-warning/dist/tiny-warning.esm.js"); +/* harmony import */ var jss__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! jss */ "./node_modules/jss/dist/jss.esm.js"); + + + +var now = Date.now(); +var fnValuesNs = "fnValues" + now; +var fnRuleNs = "fnStyle" + ++now; + +var functionPlugin = function functionPlugin() { + return { + onCreateRule: function onCreateRule(name, decl, options) { + if (typeof decl !== 'function') return null; + var rule = Object(jss__WEBPACK_IMPORTED_MODULE_1__["createRule"])(name, {}, options); + rule[fnRuleNs] = decl; + return rule; + }, + onProcessStyle: function onProcessStyle(style, rule) { + // We need to extract function values from the declaration, so that we can keep core unaware of them. + // We need to do that only once. + // We don't need to extract functions on each style update, since this can happen only once. + // We don't support function values inside of function rules. + if (fnValuesNs in rule || fnRuleNs in rule) return style; + var fnValues = {}; + + for (var prop in style) { + var value = style[prop]; + if (typeof value !== 'function') continue; + delete style[prop]; + fnValues[prop] = value; + } // $FlowFixMe[prop-missing] + + + rule[fnValuesNs] = fnValues; + return style; + }, + onUpdate: function onUpdate(data, rule, sheet, options) { + var styleRule = rule; // $FlowFixMe[prop-missing] + + var fnRule = styleRule[fnRuleNs]; // If we have a style function, the entire rule is dynamic and style object + // will be returned from that function. + + if (fnRule) { + // Empty object will remove all currently defined props + // in case function rule returns a falsy value. + styleRule.style = fnRule(data) || {}; + + if (true) { + for (var prop in styleRule.style) { + if (typeof styleRule.style[prop] === 'function') { + true ? Object(tiny_warning__WEBPACK_IMPORTED_MODULE_0__["default"])(false, '[JSS] Function values inside function rules are not supported.') : undefined; + break; + } + } + } + } // $FlowFixMe[prop-missing] + + + var fnValues = styleRule[fnValuesNs]; // If we have a fn values map, it is a rule with function values. + + if (fnValues) { + for (var _prop in fnValues) { + styleRule.prop(_prop, fnValues[_prop](data), options); + } + } + } + }; +}; + +/* harmony default export */ __webpack_exports__["default"] = (functionPlugin); + + +/***/ }), + +/***/ "./node_modules/jss-plugin-rule-value-observable/dist/jss-plugin-rule-value-observable.esm.js": +/*!****************************************************************************************************!*\ + !*** ./node_modules/jss-plugin-rule-value-observable/dist/jss-plugin-rule-value-observable.esm.js ***! + \****************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var symbol_observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! symbol-observable */ "./node_modules/symbol-observable/es/index.js"); +/* harmony import */ var jss__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! jss */ "./node_modules/jss/dist/jss.esm.js"); + + + +var isObservable = function isObservable(value) { + return value && value[symbol_observable__WEBPACK_IMPORTED_MODULE_0__["default"]] && value === value[symbol_observable__WEBPACK_IMPORTED_MODULE_0__["default"]](); +}; + +var observablePlugin = function observablePlugin(updateOptions) { + return { + onCreateRule: function onCreateRule(name, decl, options) { + if (!isObservable(decl)) return null; // Cast `decl` to `Observable`, since it passed the type guard. + + var style$ = decl; + var rule = Object(jss__WEBPACK_IMPORTED_MODULE_1__["createRule"])(name, {}, options); // TODO + // Call `stream.subscribe()` returns a subscription, which should be explicitly + // unsubscribed from when we know this sheet is no longer needed. + + style$.subscribe(function (style) { + for (var prop in style) { + rule.prop(prop, style[prop], updateOptions); + } + }); + return rule; + }, + onProcessRule: function onProcessRule(rule) { + if (rule && rule.type !== 'style') return; + var styleRule = rule; + var style = styleRule.style; + + var _loop = function _loop(prop) { + var value = style[prop]; + if (!isObservable(value)) return "continue"; + delete style[prop]; + value.subscribe({ + next: function next(nextValue) { + styleRule.prop(prop, nextValue, updateOptions); + } + }); + }; + + for (var prop in style) { + var _ret = _loop(prop); + + if (_ret === "continue") continue; + } + } + }; +}; + +/* harmony default export */ __webpack_exports__["default"] = (observablePlugin); + + +/***/ }), + +/***/ "./node_modules/jss-plugin-template/dist/jss-plugin-template.esm.js": +/*!**************************************************************************!*\ + !*** ./node_modules/jss-plugin-template/dist/jss-plugin-template.esm.js ***! + \**************************************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var tiny_warning__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tiny-warning */ "./node_modules/tiny-warning/dist/tiny-warning.esm.js"); + + +var semiWithNl = /;\n/; + +/** + * Naive CSS parser. + * - Supports only rule body (no selectors) + * - Requires semicolon and new line after the value (except of last line) + * - No nested rules support + */ +var parse = function parse(cssText) { + var style = {}; + var split = cssText.split(semiWithNl); + + for (var i = 0; i < split.length; i++) { + var decl = (split[i] || '').trim(); + if (!decl) continue; + var colonIndex = decl.indexOf(':'); + + if (colonIndex === -1) { + true ? Object(tiny_warning__WEBPACK_IMPORTED_MODULE_0__["default"])(false, "[JSS] Malformed CSS string \"" + decl + "\"") : undefined; + continue; + } + + var prop = decl.substr(0, colonIndex).trim(); + var value = decl.substr(colonIndex + 1).trim(); + style[prop] = value; + } + + return style; +}; + +var onProcessRule = function onProcessRule(rule) { + if (typeof rule.style === 'string') { + // $FlowFixMe[prop-missing] We can safely assume that rule has the style property + rule.style = parse(rule.style); + } +}; + +function templatePlugin() { + return { + onProcessRule: onProcessRule + }; +} + +/* harmony default export */ __webpack_exports__["default"] = (templatePlugin); + + +/***/ }), + +/***/ "./node_modules/jss-plugin-vendor-prefixer/dist/jss-plugin-vendor-prefixer.esm.js": +/*!****************************************************************************************!*\ + !*** ./node_modules/jss-plugin-vendor-prefixer/dist/jss-plugin-vendor-prefixer.esm.js ***! + \****************************************************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var css_vendor__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! css-vendor */ "./node_modules/css-vendor/dist/css-vendor.esm.js"); +/* harmony import */ var jss__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! jss */ "./node_modules/jss/dist/jss.esm.js"); + + + +/** + * Add vendor prefix to a property name when needed. + * + * @api public + */ + +function jssVendorPrefixer() { + function onProcessRule(rule) { + if (rule.type === 'keyframes') { + var atRule = rule; + atRule.at = Object(css_vendor__WEBPACK_IMPORTED_MODULE_0__["supportedKeyframes"])(atRule.at); + } + } + + function prefixStyle(style) { + for (var prop in style) { + var value = style[prop]; + + if (prop === 'fallbacks' && Array.isArray(value)) { + style[prop] = value.map(prefixStyle); + continue; + } + + var changeProp = false; + var supportedProp = Object(css_vendor__WEBPACK_IMPORTED_MODULE_0__["supportedProperty"])(prop); + if (supportedProp && supportedProp !== prop) changeProp = true; + var changeValue = false; + var supportedValue$1 = Object(css_vendor__WEBPACK_IMPORTED_MODULE_0__["supportedValue"])(supportedProp, Object(jss__WEBPACK_IMPORTED_MODULE_1__["toCssValue"])(value)); + if (supportedValue$1 && supportedValue$1 !== value) changeValue = true; + + if (changeProp || changeValue) { + if (changeProp) delete style[prop]; + style[supportedProp || prop] = supportedValue$1 || value; + } + } + + return style; + } + + function onProcessStyle(style, rule) { + if (rule.type !== 'style') return style; + return prefixStyle(style); + } + + function onChangeValue(value, prop) { + return Object(css_vendor__WEBPACK_IMPORTED_MODULE_0__["supportedValue"])(prop, Object(jss__WEBPACK_IMPORTED_MODULE_1__["toCssValue"])(value)) || value; + } + + return { + onProcessRule: onProcessRule, + onProcessStyle: onProcessStyle, + onChangeValue: onChangeValue + }; +} + +/* harmony default export */ __webpack_exports__["default"] = (jssVendorPrefixer); + + +/***/ }), + +/***/ "./node_modules/jss-preset-default/dist/jss-preset-default.esm.js": +/*!************************************************************************!*\ + !*** ./node_modules/jss-preset-default/dist/jss-preset-default.esm.js ***! + \************************************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var jss_plugin_rule_value_function__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! jss-plugin-rule-value-function */ "./node_modules/jss-plugin-rule-value-function/dist/jss-plugin-rule-value-function.esm.js"); +/* harmony import */ var jss_plugin_rule_value_observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! jss-plugin-rule-value-observable */ "./node_modules/jss-plugin-rule-value-observable/dist/jss-plugin-rule-value-observable.esm.js"); +/* harmony import */ var jss_plugin_template__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! jss-plugin-template */ "./node_modules/jss-plugin-template/dist/jss-plugin-template.esm.js"); +/* harmony import */ var jss_plugin_global__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! jss-plugin-global */ "./node_modules/jss-plugin-global/dist/jss-plugin-global.esm.js"); +/* harmony import */ var jss_plugin_extend__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! jss-plugin-extend */ "./node_modules/jss-plugin-extend/dist/jss-plugin-extend.esm.js"); +/* harmony import */ var jss_plugin_nested__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! jss-plugin-nested */ "./node_modules/jss-plugin-nested/dist/jss-plugin-nested.esm.js"); +/* harmony import */ var jss_plugin_compose__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! jss-plugin-compose */ "./node_modules/jss-plugin-compose/dist/jss-plugin-compose.esm.js"); +/* harmony import */ var jss_plugin_camel_case__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! jss-plugin-camel-case */ "./node_modules/jss-plugin-camel-case/dist/jss-plugin-camel-case.esm.js"); +/* harmony import */ var jss_plugin_default_unit__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! jss-plugin-default-unit */ "./node_modules/jss-plugin-default-unit/dist/jss-plugin-default-unit.esm.js"); +/* harmony import */ var jss_plugin_expand__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! jss-plugin-expand */ "./node_modules/jss-plugin-expand/dist/jss-plugin-expand.esm.js"); +/* harmony import */ var jss_plugin_vendor_prefixer__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! jss-plugin-vendor-prefixer */ "./node_modules/jss-plugin-vendor-prefixer/dist/jss-plugin-vendor-prefixer.esm.js"); +/* harmony import */ var jss_plugin_props_sort__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! jss-plugin-props-sort */ "./node_modules/jss-plugin-props-sort/dist/jss-plugin-props-sort.esm.js"); + + + + + + + + + + + + + +var create = function create(options) { + if (options === void 0) { + options = {}; + } + + return { + plugins: [Object(jss_plugin_rule_value_function__WEBPACK_IMPORTED_MODULE_0__["default"])(), Object(jss_plugin_rule_value_observable__WEBPACK_IMPORTED_MODULE_1__["default"])(options.observable), Object(jss_plugin_template__WEBPACK_IMPORTED_MODULE_2__["default"])(), Object(jss_plugin_global__WEBPACK_IMPORTED_MODULE_3__["default"])(), Object(jss_plugin_extend__WEBPACK_IMPORTED_MODULE_4__["default"])(), Object(jss_plugin_nested__WEBPACK_IMPORTED_MODULE_5__["default"])(), Object(jss_plugin_compose__WEBPACK_IMPORTED_MODULE_6__["default"])(), Object(jss_plugin_camel_case__WEBPACK_IMPORTED_MODULE_7__["default"])(), Object(jss_plugin_default_unit__WEBPACK_IMPORTED_MODULE_8__["default"])(options.defaultUnit), Object(jss_plugin_expand__WEBPACK_IMPORTED_MODULE_9__["default"])(), Object(jss_plugin_vendor_prefixer__WEBPACK_IMPORTED_MODULE_10__["default"])(), Object(jss_plugin_props_sort__WEBPACK_IMPORTED_MODULE_11__["default"])()] + }; +}; + +/* harmony default export */ __webpack_exports__["default"] = (create); + + +/***/ }), + +/***/ "./node_modules/jss/dist/jss.esm.js": +/*!******************************************!*\ + !*** ./node_modules/jss/dist/jss.esm.js ***! + \******************************************/ +/*! exports provided: default, RuleList, SheetsManager, SheetsRegistry, create, createGenerateId, createRule, getDynamicStyles, hasCSSTOMSupport, sheets, toCssValue */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RuleList", function() { return RuleList; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SheetsManager", function() { return SheetsManager; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SheetsRegistry", function() { return SheetsRegistry; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "create", function() { return create; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createGenerateId", function() { return createGenerateId; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createRule", function() { return createRule; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getDynamicStyles", function() { return getDynamicStyles; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hasCSSTOMSupport", function() { return hasCSSTOMSupport; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sheets", function() { return registry; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toCssValue", function() { return toCssValue; }); +/* harmony import */ var _babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/esm/extends */ "./node_modules/@babel/runtime/helpers/esm/extends.js"); +/* harmony import */ var is_in_browser__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! is-in-browser */ "./node_modules/is-in-browser/dist/module.js"); +/* harmony import */ var tiny_warning__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! tiny-warning */ "./node_modules/tiny-warning/dist/tiny-warning.esm.js"); +/* harmony import */ var _babel_runtime_helpers_esm_createClass__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/esm/createClass */ "./node_modules/@babel/runtime/helpers/esm/createClass.js"); +/* harmony import */ var _babel_runtime_helpers_esm_inheritsLoose__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/esm/inheritsLoose */ "./node_modules/@babel/runtime/helpers/esm/inheritsLoose.js"); +/* harmony import */ var _babel_runtime_helpers_esm_assertThisInitialized__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @babel/runtime/helpers/esm/assertThisInitialized */ "./node_modules/@babel/runtime/helpers/esm/assertThisInitialized.js"); +/* harmony import */ var _babel_runtime_helpers_esm_objectWithoutPropertiesLoose__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @babel/runtime/helpers/esm/objectWithoutPropertiesLoose */ "./node_modules/@babel/runtime/helpers/esm/objectWithoutPropertiesLoose.js"); + + + + + + + + +var plainObjectConstrurctor = {}.constructor; +function cloneStyle(style) { + if (style == null || typeof style !== 'object') return style; + if (Array.isArray(style)) return style.map(cloneStyle); + if (style.constructor !== plainObjectConstrurctor) return style; + var newStyle = {}; + + for (var name in style) { + newStyle[name] = cloneStyle(style[name]); + } + + return newStyle; +} + +/** + * Create a rule instance. + */ + +function createRule(name, decl, options) { + if (name === void 0) { + name = 'unnamed'; + } + + var jss = options.jss; + var declCopy = cloneStyle(decl); + var rule = jss.plugins.onCreateRule(name, declCopy, options); + if (rule) return rule; // It is an at-rule and it has no instance. + + if (name[0] === '@') { + true ? Object(tiny_warning__WEBPACK_IMPORTED_MODULE_2__["default"])(false, "[JSS] Unknown rule " + name) : undefined; + } + + return null; +} + +var join = function join(value, by) { + var result = ''; + + for (var i = 0; i < value.length; i++) { + // Remove !important from the value, it will be readded later. + if (value[i] === '!important') break; + if (result) result += by; + result += value[i]; + } + + return result; +}; + +/** + * Converts array values to string. + * + * `margin: [['5px', '10px']]` > `margin: 5px 10px;` + * `border: ['1px', '2px']` > `border: 1px, 2px;` + * `margin: [['5px', '10px'], '!important']` > `margin: 5px 10px !important;` + * `color: ['red', !important]` > `color: red !important;` + */ +var toCssValue = function toCssValue(value, ignoreImportant) { + if (ignoreImportant === void 0) { + ignoreImportant = false; + } + + if (!Array.isArray(value)) return value; + var cssValue = ''; // Support space separated values via `[['5px', '10px']]`. + + if (Array.isArray(value[0])) { + for (var i = 0; i < value.length; i++) { + if (value[i] === '!important') break; + if (cssValue) cssValue += ', '; + cssValue += join(value[i], ' '); + } + } else cssValue = join(value, ', '); // Add !important, because it was ignored. + + + if (!ignoreImportant && value[value.length - 1] === '!important') { + cssValue += ' !important'; + } + + return cssValue; +}; + +/** + * Indent a string. + * http://jsperf.com/array-join-vs-for + */ +function indentStr(str, indent) { + var result = ''; + + for (var index = 0; index < indent; index++) { + result += ' '; + } + + return result + str; +} +/** + * Converts a Rule to CSS string. + */ + + +function toCss(selector, style, options) { + if (options === void 0) { + options = {}; + } + + var result = ''; + if (!style) return result; + var _options = options, + _options$indent = _options.indent, + indent = _options$indent === void 0 ? 0 : _options$indent; + var fallbacks = style.fallbacks; + if (selector) indent++; // Apply fallbacks first. + + if (fallbacks) { + // Array syntax {fallbacks: [{prop: value}]} + if (Array.isArray(fallbacks)) { + for (var index = 0; index < fallbacks.length; index++) { + var fallback = fallbacks[index]; + + for (var prop in fallback) { + var value = fallback[prop]; + + if (value != null) { + if (result) result += '\n'; + result += "" + indentStr(prop + ": " + toCssValue(value) + ";", indent); + } + } + } + } else { + // Object syntax {fallbacks: {prop: value}} + for (var _prop in fallbacks) { + var _value = fallbacks[_prop]; + + if (_value != null) { + if (result) result += '\n'; + result += "" + indentStr(_prop + ": " + toCssValue(_value) + ";", indent); + } + } + } + } + + for (var _prop2 in style) { + var _value2 = style[_prop2]; + + if (_value2 != null && _prop2 !== 'fallbacks') { + if (result) result += '\n'; + result += "" + indentStr(_prop2 + ": " + toCssValue(_value2) + ";", indent); + } + } // Allow empty style in this case, because properties will be added dynamically. + + + if (!result && !options.allowEmpty) return result; // When rule is being stringified before selector was defined. + + if (!selector) return result; + indent--; + if (result) result = "\n" + result + "\n"; + return indentStr(selector + " {" + result, indent) + indentStr('}', indent); +} + +var escapeRegex = /([[\].#*$><+~=|^:(),"'`\s])/g; +var nativeEscape = typeof CSS !== 'undefined' && CSS.escape; +var escape = (function (str) { + return nativeEscape ? nativeEscape(str) : str.replace(escapeRegex, '\\$1'); +}); + +var BaseStyleRule = +/*#__PURE__*/ +function () { + function BaseStyleRule(key, style, options) { + this.type = 'style'; + this.key = void 0; + this.isProcessed = false; + this.style = void 0; + this.renderer = void 0; + this.renderable = void 0; + this.options = void 0; + var sheet = options.sheet, + Renderer = options.Renderer; + this.key = key; + this.options = options; + this.style = style; + if (sheet) this.renderer = sheet.renderer;else if (Renderer) this.renderer = new Renderer(); + } + /** + * Get or set a style property. + */ + + + var _proto = BaseStyleRule.prototype; + + _proto.prop = function prop(name, value, options) { + // It's a getter. + if (value === undefined) return this.style[name]; // Don't do anything if the value has not changed. + + var force = options ? options.force : false; + if (!force && this.style[name] === value) return this; + var newValue = value; + + if (!options || options.process !== false) { + newValue = this.options.jss.plugins.onChangeValue(value, name, this); + } + + var isEmpty = newValue == null || newValue === false; + var isDefined = name in this.style; // Value is empty and wasn't defined before. + + if (isEmpty && !isDefined && !force) return this; // We are going to remove this value. + + var remove = isEmpty && isDefined; + if (remove) delete this.style[name];else this.style[name] = newValue; // Renderable is defined if StyleSheet option `link` is true. + + if (this.renderable && this.renderer) { + if (remove) this.renderer.removeProperty(this.renderable, name);else this.renderer.setProperty(this.renderable, name, newValue); + return this; + } + + var sheet = this.options.sheet; + + if (sheet && sheet.attached) { + true ? Object(tiny_warning__WEBPACK_IMPORTED_MODULE_2__["default"])(false, '[JSS] Rule is not linked. Missing sheet option "link: true".') : undefined; + } + + return this; + }; + + return BaseStyleRule; +}(); +var StyleRule = +/*#__PURE__*/ +function (_BaseStyleRule) { + Object(_babel_runtime_helpers_esm_inheritsLoose__WEBPACK_IMPORTED_MODULE_4__["default"])(StyleRule, _BaseStyleRule); + + function StyleRule(key, style, options) { + var _this; + + _this = _BaseStyleRule.call(this, key, style, options) || this; + _this.selectorText = void 0; + _this.id = void 0; + _this.renderable = void 0; + var selector = options.selector, + scoped = options.scoped, + sheet = options.sheet, + generateId = options.generateId; + + if (selector) { + _this.selectorText = selector; + } else if (scoped !== false) { + _this.id = generateId(Object(_babel_runtime_helpers_esm_assertThisInitialized__WEBPACK_IMPORTED_MODULE_5__["default"])(Object(_babel_runtime_helpers_esm_assertThisInitialized__WEBPACK_IMPORTED_MODULE_5__["default"])(_this)), sheet); + _this.selectorText = "." + escape(_this.id); + } + + return _this; + } + /** + * Set selector string. + * Attention: use this with caution. Most browsers didn't implement + * selectorText setter, so this may result in rerendering of entire Style Sheet. + */ + + + var _proto2 = StyleRule.prototype; + + /** + * Apply rule to an element inline. + */ + _proto2.applyTo = function applyTo(renderable) { + var renderer = this.renderer; + + if (renderer) { + var json = this.toJSON(); + + for (var prop in json) { + renderer.setProperty(renderable, prop, json[prop]); + } + } + + return this; + } + /** + * Returns JSON representation of the rule. + * Fallbacks are not supported. + * Useful for inline styles. + */ + ; + + _proto2.toJSON = function toJSON() { + var json = {}; + + for (var prop in this.style) { + var value = this.style[prop]; + if (typeof value !== 'object') json[prop] = value;else if (Array.isArray(value)) json[prop] = toCssValue(value); + } + + return json; + } + /** + * Generates a CSS string. + */ + ; + + _proto2.toString = function toString(options) { + var sheet = this.options.sheet; + var link = sheet ? sheet.options.link : false; + var opts = link ? Object(_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_0__["default"])({}, options, { + allowEmpty: true + }) : options; + return toCss(this.selectorText, this.style, opts); + }; + + Object(_babel_runtime_helpers_esm_createClass__WEBPACK_IMPORTED_MODULE_3__["default"])(StyleRule, [{ + key: "selector", + set: function set(selector) { + if (selector === this.selectorText) return; + this.selectorText = selector; + var renderer = this.renderer, + renderable = this.renderable; + if (!renderable || !renderer) return; + var hasChanged = renderer.setSelector(renderable, selector); // If selector setter is not implemented, rerender the rule. + + if (!hasChanged) { + renderer.replaceRule(renderable, this); + } + } + /** + * Get selector string. + */ + , + get: function get() { + return this.selectorText; + } + }]); + + return StyleRule; +}(BaseStyleRule); +var pluginStyleRule = { + onCreateRule: function onCreateRule(name, style, options) { + if (name[0] === '@' || options.parent && options.parent.type === 'keyframes') { + return null; + } + + return new StyleRule(name, style, options); + } +}; + +var defaultToStringOptions = { + indent: 1, + children: true +}; +var atRegExp = /@([\w-]+)/; +/** + * Conditional rule for @media, @supports + */ + +var ConditionalRule = +/*#__PURE__*/ +function () { + function ConditionalRule(key, styles, options) { + this.type = 'conditional'; + this.at = void 0; + this.key = void 0; + this.query = void 0; + this.rules = void 0; + this.options = void 0; + this.isProcessed = false; + this.renderable = void 0; + this.key = key; + var atMatch = key.match(atRegExp); + this.at = atMatch ? atMatch[1] : 'unknown'; // Key might contain a unique suffix in case the `name` passed by user was duplicate. + + this.query = options.name || "@" + this.at; + this.options = options; + this.rules = new RuleList(Object(_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_0__["default"])({}, options, { + parent: this + })); + + for (var name in styles) { + this.rules.add(name, styles[name]); + } + + this.rules.process(); + } + /** + * Get a rule. + */ + + + var _proto = ConditionalRule.prototype; + + _proto.getRule = function getRule(name) { + return this.rules.get(name); + } + /** + * Get index of a rule. + */ + ; + + _proto.indexOf = function indexOf(rule) { + return this.rules.indexOf(rule); + } + /** + * Create and register rule, run plugins. + */ + ; + + _proto.addRule = function addRule(name, style, options) { + var rule = this.rules.add(name, style, options); + if (!rule) return null; + this.options.jss.plugins.onProcessRule(rule); + return rule; + } + /** + * Generates a CSS string. + */ + ; + + _proto.toString = function toString(options) { + if (options === void 0) { + options = defaultToStringOptions; + } + + if (options.indent == null) options.indent = defaultToStringOptions.indent; + if (options.children == null) options.children = defaultToStringOptions.children; + + if (options.children === false) { + return this.query + " {}"; + } + + var children = this.rules.toString(options); + return children ? this.query + " {\n" + children + "\n}" : ''; + }; + + return ConditionalRule; +}(); +var keyRegExp = /@media|@supports\s+/; +var pluginConditionalRule = { + onCreateRule: function onCreateRule(key, styles, options) { + return keyRegExp.test(key) ? new ConditionalRule(key, styles, options) : null; + } +}; + +var defaultToStringOptions$1 = { + indent: 1, + children: true +}; +var nameRegExp = /@keyframes\s+([\w-]+)/; +/** + * Rule for @keyframes + */ + +var KeyframesRule = +/*#__PURE__*/ +function () { + function KeyframesRule(key, frames, options) { + this.type = 'keyframes'; + this.at = '@keyframes'; + this.key = void 0; + this.name = void 0; + this.id = void 0; + this.rules = void 0; + this.options = void 0; + this.isProcessed = false; + this.renderable = void 0; + var nameMatch = key.match(nameRegExp); + + if (nameMatch && nameMatch[1]) { + this.name = nameMatch[1]; + } else { + this.name = 'noname'; + true ? Object(tiny_warning__WEBPACK_IMPORTED_MODULE_2__["default"])(false, "[JSS] Bad keyframes name " + key) : undefined; + } + + this.key = this.type + "-" + this.name; + this.options = options; + var scoped = options.scoped, + sheet = options.sheet, + generateId = options.generateId; + this.id = scoped === false ? this.name : escape(generateId(this, sheet)); + this.rules = new RuleList(Object(_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_0__["default"])({}, options, { + parent: this + })); + + for (var name in frames) { + this.rules.add(name, frames[name], Object(_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_0__["default"])({}, options, { + parent: this + })); + } + + this.rules.process(); + } + /** + * Generates a CSS string. + */ + + + var _proto = KeyframesRule.prototype; + + _proto.toString = function toString(options) { + if (options === void 0) { + options = defaultToStringOptions$1; + } + + if (options.indent == null) options.indent = defaultToStringOptions$1.indent; + if (options.children == null) options.children = defaultToStringOptions$1.children; + + if (options.children === false) { + return this.at + " " + this.id + " {}"; + } + + var children = this.rules.toString(options); + if (children) children = "\n" + children + "\n"; + return this.at + " " + this.id + " {" + children + "}"; + }; + + return KeyframesRule; +}(); +var keyRegExp$1 = /@keyframes\s+/; +var refRegExp = /\$([\w-]+)/g; + +var findReferencedKeyframe = function findReferencedKeyframe(val, keyframes) { + if (typeof val === 'string') { + return val.replace(refRegExp, function (match, name) { + if (name in keyframes) { + return keyframes[name]; + } + + true ? Object(tiny_warning__WEBPACK_IMPORTED_MODULE_2__["default"])(false, "[JSS] Referenced keyframes rule \"" + name + "\" is not defined.") : undefined; + return match; + }); + } + + return val; +}; +/** + * Replace the reference for a animation name. + */ + + +var replaceRef = function replaceRef(style, prop, keyframes) { + var value = style[prop]; + var refKeyframe = findReferencedKeyframe(value, keyframes); + + if (refKeyframe !== value) { + style[prop] = refKeyframe; + } +}; + +var plugin = { + onCreateRule: function onCreateRule(key, frames, options) { + return typeof key === 'string' && keyRegExp$1.test(key) ? new KeyframesRule(key, frames, options) : null; + }, + // Animation name ref replacer. + onProcessStyle: function onProcessStyle(style, rule, sheet) { + if (rule.type !== 'style' || !sheet) return style; + if ('animation-name' in style) replaceRef(style, 'animation-name', sheet.keyframes); + if ('animation' in style) replaceRef(style, 'animation', sheet.keyframes); + return style; + }, + onChangeValue: function onChangeValue(val, prop, rule) { + var sheet = rule.options.sheet; + + if (!sheet) { + return val; + } + + switch (prop) { + case 'animation': + return findReferencedKeyframe(val, sheet.keyframes); + + case 'animation-name': + return findReferencedKeyframe(val, sheet.keyframes); + + default: + return val; + } + } +}; + +var KeyframeRule = +/*#__PURE__*/ +function (_BaseStyleRule) { + Object(_babel_runtime_helpers_esm_inheritsLoose__WEBPACK_IMPORTED_MODULE_4__["default"])(KeyframeRule, _BaseStyleRule); + + function KeyframeRule() { + var _this; + + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + _this = _BaseStyleRule.call.apply(_BaseStyleRule, [this].concat(args)) || this; + _this.renderable = void 0; + return _this; + } + + var _proto = KeyframeRule.prototype; + + /** + * Generates a CSS string. + */ + _proto.toString = function toString(options) { + var sheet = this.options.sheet; + var link = sheet ? sheet.options.link : false; + var opts = link ? Object(_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_0__["default"])({}, options, { + allowEmpty: true + }) : options; + return toCss(this.key, this.style, opts); + }; + + return KeyframeRule; +}(BaseStyleRule); +var pluginKeyframeRule = { + onCreateRule: function onCreateRule(key, style, options) { + if (options.parent && options.parent.type === 'keyframes') { + return new KeyframeRule(key, style, options); + } + + return null; + } +}; + +var FontFaceRule = +/*#__PURE__*/ +function () { + function FontFaceRule(key, style, options) { + this.type = 'font-face'; + this.at = '@font-face'; + this.key = void 0; + this.style = void 0; + this.options = void 0; + this.isProcessed = false; + this.renderable = void 0; + this.key = key; + this.style = style; + this.options = options; + } + /** + * Generates a CSS string. + */ + + + var _proto = FontFaceRule.prototype; + + _proto.toString = function toString(options) { + if (Array.isArray(this.style)) { + var str = ''; + + for (var index = 0; index < this.style.length; index++) { + str += toCss(this.at, this.style[index]); + if (this.style[index + 1]) str += '\n'; + } + + return str; + } + + return toCss(this.at, this.style, options); + }; + + return FontFaceRule; +}(); +var keyRegExp$2 = /@font-face/; +var pluginFontFaceRule = { + onCreateRule: function onCreateRule(key, style, options) { + return keyRegExp$2.test(key) ? new FontFaceRule(key, style, options) : null; + } +}; + +var ViewportRule = +/*#__PURE__*/ +function () { + function ViewportRule(key, style, options) { + this.type = 'viewport'; + this.at = '@viewport'; + this.key = void 0; + this.style = void 0; + this.options = void 0; + this.isProcessed = false; + this.renderable = void 0; + this.key = key; + this.style = style; + this.options = options; + } + /** + * Generates a CSS string. + */ + + + var _proto = ViewportRule.prototype; + + _proto.toString = function toString(options) { + return toCss(this.key, this.style, options); + }; + + return ViewportRule; +}(); +var pluginViewportRule = { + onCreateRule: function onCreateRule(key, style, options) { + return key === '@viewport' || key === '@-ms-viewport' ? new ViewportRule(key, style, options) : null; + } +}; + +var SimpleRule = +/*#__PURE__*/ +function () { + function SimpleRule(key, value, options) { + this.type = 'simple'; + this.key = void 0; + this.value = void 0; + this.options = void 0; + this.isProcessed = false; + this.renderable = void 0; + this.key = key; + this.value = value; + this.options = options; + } + /** + * Generates a CSS string. + */ + // eslint-disable-next-line no-unused-vars + + + var _proto = SimpleRule.prototype; + + _proto.toString = function toString(options) { + if (Array.isArray(this.value)) { + var str = ''; + + for (var index = 0; index < this.value.length; index++) { + str += this.key + " " + this.value[index] + ";"; + if (this.value[index + 1]) str += '\n'; + } + + return str; + } + + return this.key + " " + this.value + ";"; + }; + + return SimpleRule; +}(); +var keysMap = { + '@charset': true, + '@import': true, + '@namespace': true +}; +var pluginSimpleRule = { + onCreateRule: function onCreateRule(key, value, options) { + return key in keysMap ? new SimpleRule(key, value, options) : null; + } +}; + +var plugins = [pluginStyleRule, pluginConditionalRule, plugin, pluginKeyframeRule, pluginFontFaceRule, pluginViewportRule, pluginSimpleRule]; + +var defaultUpdateOptions = { + process: true +}; +var forceUpdateOptions = { + force: true, + process: true + /** + * Contains rules objects and allows adding/removing etc. + * Is used for e.g. by `StyleSheet` or `ConditionalRule`. + */ + +}; + +var RuleList = +/*#__PURE__*/ +function () { + // Rules registry for access by .get() method. + // It contains the same rule registered by name and by selector. + // Original styles object. + // Used to ensure correct rules order. + function RuleList(options) { + this.map = {}; + this.raw = {}; + this.index = []; + this.counter = 0; + this.options = void 0; + this.classes = void 0; + this.keyframes = void 0; + this.options = options; + this.classes = options.classes; + this.keyframes = options.keyframes; + } + /** + * Create and register rule. + * + * Will not render after Style Sheet was rendered the first time. + */ + + + var _proto = RuleList.prototype; + + _proto.add = function add(name, decl, ruleOptions) { + var _this$options = this.options, + parent = _this$options.parent, + sheet = _this$options.sheet, + jss = _this$options.jss, + Renderer = _this$options.Renderer, + generateId = _this$options.generateId, + scoped = _this$options.scoped; + + var options = Object(_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_0__["default"])({ + classes: this.classes, + parent: parent, + sheet: sheet, + jss: jss, + Renderer: Renderer, + generateId: generateId, + scoped: scoped, + name: name, + keyframes: this.keyframes, + selector: undefined + }, ruleOptions); // When user uses .createStyleSheet(), duplicate names are not possible, but + // `sheet.addRule()` opens the door for any duplicate rule name. When this happens + // we need to make the key unique within this RuleList instance scope. + + + var key = name; + + if (name in this.raw) { + key = name + "-d" + this.counter++; + } // We need to save the original decl before creating the rule + // because cache plugin needs to use it as a key to return a cached rule. + + + this.raw[key] = decl; + + if (key in this.classes) { + // E.g. rules inside of @media container + options.selector = "." + escape(this.classes[key]); + } + + var rule = createRule(key, decl, options); + if (!rule) return null; + this.register(rule); + var index = options.index === undefined ? this.index.length : options.index; + this.index.splice(index, 0, rule); + return rule; + } + /** + * Get a rule. + */ + ; + + _proto.get = function get(name) { + return this.map[name]; + } + /** + * Delete a rule. + */ + ; + + _proto.remove = function remove(rule) { + this.unregister(rule); + delete this.raw[rule.key]; + this.index.splice(this.index.indexOf(rule), 1); + } + /** + * Get index of a rule. + */ + ; + + _proto.indexOf = function indexOf(rule) { + return this.index.indexOf(rule); + } + /** + * Run `onProcessRule()` plugins on every rule. + */ + ; + + _proto.process = function process() { + var plugins = this.options.jss.plugins; // We need to clone array because if we modify the index somewhere else during a loop + // we end up with very hard-to-track-down side effects. + + this.index.slice(0).forEach(plugins.onProcessRule, plugins); + } + /** + * Register a rule in `.map`, `.classes` and `.keyframes` maps. + */ + ; + + _proto.register = function register(rule) { + this.map[rule.key] = rule; + + if (rule instanceof StyleRule) { + this.map[rule.selector] = rule; + if (rule.id) this.classes[rule.key] = rule.id; + } else if (rule instanceof KeyframesRule && this.keyframes) { + this.keyframes[rule.name] = rule.id; + } + } + /** + * Unregister a rule. + */ + ; + + _proto.unregister = function unregister(rule) { + delete this.map[rule.key]; + + if (rule instanceof StyleRule) { + delete this.map[rule.selector]; + delete this.classes[rule.key]; + } else if (rule instanceof KeyframesRule) { + delete this.keyframes[rule.name]; + } + } + /** + * Update the function values with a new data. + */ + ; + + _proto.update = function update() { + var name; + var data; + var options; + + if (typeof (arguments.length <= 0 ? undefined : arguments[0]) === 'string') { + name = arguments.length <= 0 ? undefined : arguments[0]; // $FlowFixMe[invalid-tuple-index] + + data = arguments.length <= 1 ? undefined : arguments[1]; // $FlowFixMe[invalid-tuple-index] + + options = arguments.length <= 2 ? undefined : arguments[2]; + } else { + data = arguments.length <= 0 ? undefined : arguments[0]; // $FlowFixMe[invalid-tuple-index] + + options = arguments.length <= 1 ? undefined : arguments[1]; + name = null; + } + + if (name) { + this.updateOne(this.map[name], data, options); + } else { + for (var index = 0; index < this.index.length; index++) { + this.updateOne(this.index[index], data, options); + } + } + } + /** + * Execute plugins, update rule props. + */ + ; + + _proto.updateOne = function updateOne(rule, data, options) { + if (options === void 0) { + options = defaultUpdateOptions; + } + + var _this$options2 = this.options, + plugins = _this$options2.jss.plugins, + sheet = _this$options2.sheet; // It is a rules container like for e.g. ConditionalRule. + + if (rule.rules instanceof RuleList) { + rule.rules.update(data, options); + return; + } + + var styleRule = rule; + var style = styleRule.style; + plugins.onUpdate(data, rule, sheet, options); // We rely on a new `style` ref in case it was mutated during onUpdate hook. + + if (options.process && style && style !== styleRule.style) { + // We need to run the plugins in case new `style` relies on syntax plugins. + plugins.onProcessStyle(styleRule.style, styleRule, sheet); // Update and add props. + + for (var prop in styleRule.style) { + var nextValue = styleRule.style[prop]; + var prevValue = style[prop]; // We need to use `force: true` because `rule.style` has been updated during onUpdate hook, so `rule.prop()` will not update the CSSOM rule. + // We do this comparison to avoid unneeded `rule.prop()` calls, since we have the old `style` object here. + + if (nextValue !== prevValue) { + styleRule.prop(prop, nextValue, forceUpdateOptions); + } + } // Remove props. + + + for (var _prop in style) { + var _nextValue = styleRule.style[_prop]; + var _prevValue = style[_prop]; // We need to use `force: true` because `rule.style` has been updated during onUpdate hook, so `rule.prop()` will not update the CSSOM rule. + // We do this comparison to avoid unneeded `rule.prop()` calls, since we have the old `style` object here. + + if (_nextValue == null && _nextValue !== _prevValue) { + styleRule.prop(_prop, null, forceUpdateOptions); + } + } + } + } + /** + * Convert rules to a CSS string. + */ + ; + + _proto.toString = function toString(options) { + var str = ''; + var sheet = this.options.sheet; + var link = sheet ? sheet.options.link : false; + + for (var index = 0; index < this.index.length; index++) { + var rule = this.index[index]; + var css = rule.toString(options); // No need to render an empty rule. + + if (!css && !link) continue; + if (str) str += '\n'; + str += css; + } + + return str; + }; + + return RuleList; +}(); + +var StyleSheet = +/*#__PURE__*/ +function () { + function StyleSheet(styles, options) { + this.options = void 0; + this.deployed = void 0; + this.attached = void 0; + this.rules = void 0; + this.renderer = void 0; + this.classes = void 0; + this.keyframes = void 0; + this.queue = void 0; + this.attached = false; + this.deployed = false; + this.classes = {}; + this.keyframes = {}; + this.options = Object(_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_0__["default"])({}, options, { + sheet: this, + parent: this, + classes: this.classes, + keyframes: this.keyframes + }); + + if (options.Renderer) { + this.renderer = new options.Renderer(this); + } + + this.rules = new RuleList(this.options); + + for (var name in styles) { + this.rules.add(name, styles[name]); + } + + this.rules.process(); + } + /** + * Attach renderable to the render tree. + */ + + + var _proto = StyleSheet.prototype; + + _proto.attach = function attach() { + if (this.attached) return this; + if (this.renderer) this.renderer.attach(); + this.attached = true; // Order is important, because we can't use insertRule API if style element is not attached. + + if (!this.deployed) this.deploy(); + return this; + } + /** + * Remove renderable from render tree. + */ + ; + + _proto.detach = function detach() { + if (!this.attached) return this; + if (this.renderer) this.renderer.detach(); + this.attached = false; + return this; + } + /** + * Add a rule to the current stylesheet. + * Will insert a rule also after the stylesheet has been rendered first time. + */ + ; + + _proto.addRule = function addRule(name, decl, options) { + var queue = this.queue; // Plugins can create rules. + // In order to preserve the right order, we need to queue all `.addRule` calls, + // which happen after the first `rules.add()` call. + + if (this.attached && !queue) this.queue = []; + var rule = this.rules.add(name, decl, options); + if (!rule) return null; + this.options.jss.plugins.onProcessRule(rule); + + if (this.attached) { + if (!this.deployed) return rule; // Don't insert rule directly if there is no stringified version yet. + // It will be inserted all together when .attach is called. + + if (queue) queue.push(rule);else { + this.insertRule(rule); + + if (this.queue) { + this.queue.forEach(this.insertRule, this); + this.queue = undefined; + } + } + return rule; + } // We can't add rules to a detached style node. + // We will redeploy the sheet once user will attach it. + + + this.deployed = false; + return rule; + } + /** + * Insert rule into the StyleSheet + */ + ; + + _proto.insertRule = function insertRule(rule) { + if (this.renderer) { + this.renderer.insertRule(rule); + } + } + /** + * Create and add rules. + * Will render also after Style Sheet was rendered the first time. + */ + ; + + _proto.addRules = function addRules(styles, options) { + var added = []; + + for (var name in styles) { + var rule = this.addRule(name, styles[name], options); + if (rule) added.push(rule); + } + + return added; + } + /** + * Get a rule by name. + */ + ; + + _proto.getRule = function getRule(name) { + return this.rules.get(name); + } + /** + * Delete a rule by name. + * Returns `true`: if rule has been deleted from the DOM. + */ + ; + + _proto.deleteRule = function deleteRule(name) { + var rule = typeof name === 'object' ? name : this.rules.get(name); + + if (!rule || // Style sheet was created without link: true and attached, in this case we + // won't be able to remove the CSS rule from the DOM. + this.attached && !rule.renderable) { + return false; + } + + this.rules.remove(rule); + + if (this.attached && rule.renderable && this.renderer) { + return this.renderer.deleteRule(rule.renderable); + } + + return true; + } + /** + * Get index of a rule. + */ + ; + + _proto.indexOf = function indexOf(rule) { + return this.rules.indexOf(rule); + } + /** + * Deploy pure CSS string to a renderable. + */ + ; + + _proto.deploy = function deploy() { + if (this.renderer) this.renderer.deploy(); + this.deployed = true; + return this; + } + /** + * Update the function values with a new data. + */ + ; + + _proto.update = function update() { + var _this$rules; + + (_this$rules = this.rules).update.apply(_this$rules, arguments); + + return this; + } + /** + * Updates a single rule. + */ + ; + + _proto.updateOne = function updateOne(rule, data, options) { + this.rules.updateOne(rule, data, options); + return this; + } + /** + * Convert rules to a CSS string. + */ + ; + + _proto.toString = function toString(options) { + return this.rules.toString(options); + }; + + return StyleSheet; +}(); + +var PluginsRegistry = +/*#__PURE__*/ +function () { + function PluginsRegistry() { + this.plugins = { + internal: [], + external: [] + }; + this.registry = void 0; + } + + var _proto = PluginsRegistry.prototype; + + /** + * Call `onCreateRule` hooks and return an object if returned by a hook. + */ + _proto.onCreateRule = function onCreateRule(name, decl, options) { + for (var i = 0; i < this.registry.onCreateRule.length; i++) { + var rule = this.registry.onCreateRule[i](name, decl, options); + if (rule) return rule; + } + + return null; + } + /** + * Call `onProcessRule` hooks. + */ + ; + + _proto.onProcessRule = function onProcessRule(rule) { + if (rule.isProcessed) return; + var sheet = rule.options.sheet; + + for (var i = 0; i < this.registry.onProcessRule.length; i++) { + this.registry.onProcessRule[i](rule, sheet); + } + + if (rule.style) this.onProcessStyle(rule.style, rule, sheet); + rule.isProcessed = true; + } + /** + * Call `onProcessStyle` hooks. + */ + ; + + _proto.onProcessStyle = function onProcessStyle(style, rule, sheet) { + for (var i = 0; i < this.registry.onProcessStyle.length; i++) { + // $FlowFixMe[prop-missing] + rule.style = this.registry.onProcessStyle[i](rule.style, rule, sheet); + } + } + /** + * Call `onProcessSheet` hooks. + */ + ; + + _proto.onProcessSheet = function onProcessSheet(sheet) { + for (var i = 0; i < this.registry.onProcessSheet.length; i++) { + this.registry.onProcessSheet[i](sheet); + } + } + /** + * Call `onUpdate` hooks. + */ + ; + + _proto.onUpdate = function onUpdate(data, rule, sheet, options) { + for (var i = 0; i < this.registry.onUpdate.length; i++) { + this.registry.onUpdate[i](data, rule, sheet, options); + } + } + /** + * Call `onChangeValue` hooks. + */ + ; + + _proto.onChangeValue = function onChangeValue(value, prop, rule) { + var processedValue = value; + + for (var i = 0; i < this.registry.onChangeValue.length; i++) { + processedValue = this.registry.onChangeValue[i](processedValue, prop, rule); + } + + return processedValue; + } + /** + * Register a plugin. + */ + ; + + _proto.use = function use(newPlugin, options) { + if (options === void 0) { + options = { + queue: 'external' + }; + } + + var plugins = this.plugins[options.queue]; // Avoids applying same plugin twice, at least based on ref. + + if (plugins.indexOf(newPlugin) !== -1) { + return; + } + + plugins.push(newPlugin); + this.registry = [].concat(this.plugins.external, this.plugins.internal).reduce(function (registry, plugin) { + for (var name in plugin) { + if (name in registry) { + registry[name].push(plugin[name]); + } else { + true ? Object(tiny_warning__WEBPACK_IMPORTED_MODULE_2__["default"])(false, "[JSS] Unknown hook \"" + name + "\".") : undefined; + } + } + + return registry; + }, { + onCreateRule: [], + onProcessRule: [], + onProcessStyle: [], + onProcessSheet: [], + onChangeValue: [], + onUpdate: [] + }); + }; + + return PluginsRegistry; +}(); + +/** + * Sheets registry to access them all at one place. + */ +var SheetsRegistry = +/*#__PURE__*/ +function () { + function SheetsRegistry() { + this.registry = []; + } + + var _proto = SheetsRegistry.prototype; + + /** + * Register a Style Sheet. + */ + _proto.add = function add(sheet) { + var registry = this.registry; + var index = sheet.options.index; + if (registry.indexOf(sheet) !== -1) return; + + if (registry.length === 0 || index >= this.index) { + registry.push(sheet); + return; + } // Find a position. + + + for (var i = 0; i < registry.length; i++) { + if (registry[i].options.index > index) { + registry.splice(i, 0, sheet); + return; + } + } + } + /** + * Reset the registry. + */ + ; + + _proto.reset = function reset() { + this.registry = []; + } + /** + * Remove a Style Sheet. + */ + ; + + _proto.remove = function remove(sheet) { + var index = this.registry.indexOf(sheet); + this.registry.splice(index, 1); + } + /** + * Convert all attached sheets to a CSS string. + */ + ; + + _proto.toString = function toString(_temp) { + var _ref = _temp === void 0 ? {} : _temp, + attached = _ref.attached, + options = Object(_babel_runtime_helpers_esm_objectWithoutPropertiesLoose__WEBPACK_IMPORTED_MODULE_6__["default"])(_ref, ["attached"]); + + var css = ''; + + for (var i = 0; i < this.registry.length; i++) { + var sheet = this.registry[i]; + + if (attached != null && sheet.attached !== attached) { + continue; + } + + if (css) css += '\n'; + css += sheet.toString(options); + } + + return css; + }; + + Object(_babel_runtime_helpers_esm_createClass__WEBPACK_IMPORTED_MODULE_3__["default"])(SheetsRegistry, [{ + key: "index", + + /** + * Current highest index number. + */ + get: function get() { + return this.registry.length === 0 ? 0 : this.registry[this.registry.length - 1].options.index; + } + }]); + + return SheetsRegistry; +}(); + +/** + * This is a global sheets registry. Only DomRenderer will add sheets to it. + * On the server one should use an own SheetsRegistry instance and add the + * sheets to it, because you need to make sure to create a new registry for + * each request in order to not leak sheets across requests. + */ + +var registry = new SheetsRegistry(); + +/* eslint-disable */ +// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 +var globalThis = typeof window != 'undefined' && window.Math == Math ? window : typeof self != 'undefined' && self.Math == Math ? self : Function('return this')(); + +var ns = '2f1acc6c3a606b082e5eef5e54414ffb'; +if (globalThis[ns] == null) globalThis[ns] = 0; // Bundle may contain multiple JSS versions at the same time. In order to identify +// the current version with just one short number and use it for classes generation +// we use a counter. Also it is more accurate, because user can manually reevaluate +// the module. + +var moduleId = globalThis[ns]++; + +var maxRules = 1e10; + +/** + * Returns a function which generates unique class names based on counters. + * When new generator function is created, rule counter is reseted. + * We need to reset the rule counter for SSR for each request. + */ +var createGenerateId = function createGenerateId(options) { + if (options === void 0) { + options = {}; + } + + var ruleCounter = 0; + return function (rule, sheet) { + ruleCounter += 1; + + if (ruleCounter > maxRules) { + true ? Object(tiny_warning__WEBPACK_IMPORTED_MODULE_2__["default"])(false, "[JSS] You might have a memory leak. Rule counter is at " + ruleCounter + ".") : undefined; + } + + var jssId = ''; + var prefix = ''; + + if (sheet) { + if (sheet.options.classNamePrefix) { + prefix = sheet.options.classNamePrefix; + } + + if (sheet.options.jss.id != null) { + jssId = String(sheet.options.jss.id); + } + } + + if (options.minify) { + // Using "c" because a number can't be the first char in a class name. + return "" + (prefix || 'c') + moduleId + jssId + ruleCounter; + } + + return prefix + rule.key + "-" + moduleId + (jssId ? "-" + jssId : '') + "-" + ruleCounter; + }; +}; + +/** + * Cache the value from the first time a function is called. + */ +var memoize = function memoize(fn) { + var value; + return function () { + if (!value) value = fn(); + return value; + }; +}; + +/** + * Get a style property value. + */ +var getPropertyValue = function getPropertyValue(cssRule, prop) { + try { + // Support CSSTOM. + if (cssRule.attributeStyleMap) { + return cssRule.attributeStyleMap.get(prop); + } + + return cssRule.style.getPropertyValue(prop); + } catch (err) { + // IE may throw if property is unknown. + return ''; + } +}; + +/** + * Set a style property. + */ +var setProperty = function setProperty(cssRule, prop, value) { + try { + var cssValue = value; + + if (Array.isArray(value)) { + cssValue = toCssValue(value, true); + + if (value[value.length - 1] === '!important') { + cssRule.style.setProperty(prop, cssValue, 'important'); + return true; + } + } // Support CSSTOM. + + + if (cssRule.attributeStyleMap) { + cssRule.attributeStyleMap.set(prop, cssValue); + } else { + cssRule.style.setProperty(prop, cssValue); + } + } catch (err) { + // IE may throw if property is unknown. + return false; + } + + return true; +}; + +/** + * Remove a style property. + */ +var removeProperty = function removeProperty(cssRule, prop) { + try { + // Support CSSTOM. + if (cssRule.attributeStyleMap) { + cssRule.attributeStyleMap.delete(prop); + } else { + cssRule.style.removeProperty(prop); + } + } catch (err) { + true ? Object(tiny_warning__WEBPACK_IMPORTED_MODULE_2__["default"])(false, "[JSS] DOMException \"" + err.message + "\" was thrown. Tried to remove property \"" + prop + "\".") : undefined; + } +}; + +/** + * Set the selector. + */ +var setSelector = function setSelector(cssRule, selectorText) { + cssRule.selectorText = selectorText; // Return false if setter was not successful. + // Currently works in chrome only. + + return cssRule.selectorText === selectorText; +}; +/** + * Gets the `head` element upon the first call and caches it. + * We assume it can't be null. + */ + + +var getHead = memoize(function () { + return document.querySelector('head'); +}); +/** + * Find attached sheet with an index higher than the passed one. + */ + +function findHigherSheet(registry, options) { + for (var i = 0; i < registry.length; i++) { + var sheet = registry[i]; + + if (sheet.attached && sheet.options.index > options.index && sheet.options.insertionPoint === options.insertionPoint) { + return sheet; + } + } + + return null; +} +/** + * Find attached sheet with the highest index. + */ + + +function findHighestSheet(registry, options) { + for (var i = registry.length - 1; i >= 0; i--) { + var sheet = registry[i]; + + if (sheet.attached && sheet.options.insertionPoint === options.insertionPoint) { + return sheet; + } + } + + return null; +} +/** + * Find a comment with "jss" inside. + */ + + +function findCommentNode(text) { + var head = getHead(); + + for (var i = 0; i < head.childNodes.length; i++) { + var node = head.childNodes[i]; + + if (node.nodeType === 8 && node.nodeValue.trim() === text) { + return node; + } + } + + return null; +} + +/** + * Find a node before which we can insert the sheet. + */ +function findPrevNode(options) { + var registry$1 = registry.registry; + + if (registry$1.length > 0) { + // Try to insert before the next higher sheet. + var sheet = findHigherSheet(registry$1, options); + + if (sheet && sheet.renderer) { + return { + parent: sheet.renderer.element.parentNode, + node: sheet.renderer.element + }; + } // Otherwise insert after the last attached. + + + sheet = findHighestSheet(registry$1, options); + + if (sheet && sheet.renderer) { + return { + parent: sheet.renderer.element.parentNode, + node: sheet.renderer.element.nextSibling + }; + } + } // Try to find a comment placeholder if registry is empty. + + + var insertionPoint = options.insertionPoint; + + if (insertionPoint && typeof insertionPoint === 'string') { + var comment = findCommentNode(insertionPoint); + + if (comment) { + return { + parent: comment.parentNode, + node: comment.nextSibling + }; + } // If user specifies an insertion point and it can't be found in the document - + // bad specificity issues may appear. + + + true ? Object(tiny_warning__WEBPACK_IMPORTED_MODULE_2__["default"])(false, "[JSS] Insertion point \"" + insertionPoint + "\" not found.") : undefined; + } + + return false; +} +/** + * Insert style element into the DOM. + */ + + +function insertStyle(style, options) { + var insertionPoint = options.insertionPoint; + var nextNode = findPrevNode(options); + + if (nextNode !== false && nextNode.parent) { + nextNode.parent.insertBefore(style, nextNode.node); + return; + } // Works with iframes and any node types. + + + if (insertionPoint && typeof insertionPoint.nodeType === 'number') { + // https://stackoverflow.com/questions/41328728/force-casting-in-flow + var insertionPointElement = insertionPoint; + var parentNode = insertionPointElement.parentNode; + if (parentNode) parentNode.insertBefore(style, insertionPointElement.nextSibling);else true ? Object(tiny_warning__WEBPACK_IMPORTED_MODULE_2__["default"])(false, '[JSS] Insertion point is not in the DOM.') : undefined; + return; + } + + getHead().appendChild(style); +} +/** + * Read jss nonce setting from the page if the user has set it. + */ + + +var getNonce = memoize(function () { + var node = document.querySelector('meta[property="csp-nonce"]'); + return node ? node.getAttribute('content') : null; +}); + +var _insertRule = function insertRule(container, rule, index) { + try { + if ('insertRule' in container) { + var c = container; + c.insertRule(rule, index); + } // Keyframes rule. + else if ('appendRule' in container) { + var _c = container; + + _c.appendRule(rule); + } + } catch (err) { + true ? Object(tiny_warning__WEBPACK_IMPORTED_MODULE_2__["default"])(false, "[JSS] " + err.message) : undefined; + return false; + } + + return container.cssRules[index]; +}; + +var getValidRuleInsertionIndex = function getValidRuleInsertionIndex(container, index) { + var maxIndex = container.cssRules.length; // In case previous insertion fails, passed index might be wrong + + if (index === undefined || index > maxIndex) { + // eslint-disable-next-line no-param-reassign + return maxIndex; + } + + return index; +}; + +var createStyle = function createStyle() { + var el = document.createElement('style'); // Without it, IE will have a broken source order specificity if we + // insert rules after we insert the style tag. + // It seems to kick-off the source order specificity algorithm. + + el.textContent = '\n'; + return el; +}; + +var DomRenderer = +/*#__PURE__*/ +function () { + // HTMLStyleElement needs fixing https://github.com/facebook/flow/issues/2696 + // Will be empty if link: true option is not set, because + // it is only for use together with insertRule API. + function DomRenderer(sheet) { + this.getPropertyValue = getPropertyValue; + this.setProperty = setProperty; + this.removeProperty = removeProperty; + this.setSelector = setSelector; + this.element = void 0; + this.sheet = void 0; + this.hasInsertedRules = false; + this.cssRules = []; + // There is no sheet when the renderer is used from a standalone StyleRule. + if (sheet) registry.add(sheet); + this.sheet = sheet; + + var _ref = this.sheet ? this.sheet.options : {}, + media = _ref.media, + meta = _ref.meta, + element = _ref.element; + + this.element = element || createStyle(); + this.element.setAttribute('data-jss', ''); + if (media) this.element.setAttribute('media', media); + if (meta) this.element.setAttribute('data-meta', meta); + var nonce = getNonce(); + if (nonce) this.element.setAttribute('nonce', nonce); + } + /** + * Insert style element into render tree. + */ + + + var _proto = DomRenderer.prototype; + + _proto.attach = function attach() { + // In the case the element node is external and it is already in the DOM. + if (this.element.parentNode || !this.sheet) return; + insertStyle(this.element, this.sheet.options); // When rules are inserted using `insertRule` API, after `sheet.detach().attach()` + // most browsers create a new CSSStyleSheet, except of all IEs. + + var deployed = Boolean(this.sheet && this.sheet.deployed); + + if (this.hasInsertedRules && deployed) { + this.hasInsertedRules = false; + this.deploy(); + } + } + /** + * Remove style element from render tree. + */ + ; + + _proto.detach = function detach() { + if (!this.sheet) return; + var parentNode = this.element.parentNode; + if (parentNode) parentNode.removeChild(this.element); // In the most browsers, rules inserted using insertRule() API will be lost when style element is removed. + // Though IE will keep them and we need a consistent behavior. + + if (this.sheet.options.link) { + this.cssRules = []; + this.element.textContent = '\n'; + } + } + /** + * Inject CSS string into element. + */ + ; + + _proto.deploy = function deploy() { + var sheet = this.sheet; + if (!sheet) return; + + if (sheet.options.link) { + this.insertRules(sheet.rules); + return; + } + + this.element.textContent = "\n" + sheet.toString() + "\n"; + } + /** + * Insert RuleList into an element. + */ + ; + + _proto.insertRules = function insertRules(rules, nativeParent) { + for (var i = 0; i < rules.index.length; i++) { + this.insertRule(rules.index[i], i, nativeParent); + } + } + /** + * Insert a rule into element. + */ + ; + + _proto.insertRule = function insertRule(rule, index, nativeParent) { + if (nativeParent === void 0) { + nativeParent = this.element.sheet; + } + + if (rule.rules) { + var parent = rule; + var latestNativeParent = nativeParent; + + if (rule.type === 'conditional' || rule.type === 'keyframes') { + var _insertionIndex = getValidRuleInsertionIndex(nativeParent, index); // We need to render the container without children first. + + + latestNativeParent = _insertRule(nativeParent, parent.toString({ + children: false + }), _insertionIndex); + + if (latestNativeParent === false) { + return false; + } + + this.refCssRule(rule, _insertionIndex, latestNativeParent); + } + + this.insertRules(parent.rules, latestNativeParent); + return latestNativeParent; + } + + var ruleStr = rule.toString(); + if (!ruleStr) return false; + var insertionIndex = getValidRuleInsertionIndex(nativeParent, index); + + var nativeRule = _insertRule(nativeParent, ruleStr, insertionIndex); + + if (nativeRule === false) { + return false; + } + + this.hasInsertedRules = true; + this.refCssRule(rule, insertionIndex, nativeRule); + return nativeRule; + }; + + _proto.refCssRule = function refCssRule(rule, index, cssRule) { + rule.renderable = cssRule; // We only want to reference the top level rules, deleteRule API doesn't support removing nested rules + // like rules inside media queries or keyframes + + if (rule.options.parent instanceof StyleSheet) { + this.cssRules[index] = cssRule; + } + } + /** + * Delete a rule. + */ + ; + + _proto.deleteRule = function deleteRule(cssRule) { + var sheet = this.element.sheet; + var index = this.indexOf(cssRule); + if (index === -1) return false; + sheet.deleteRule(index); + this.cssRules.splice(index, 1); + return true; + } + /** + * Get index of a CSS Rule. + */ + ; + + _proto.indexOf = function indexOf(cssRule) { + return this.cssRules.indexOf(cssRule); + } + /** + * Generate a new CSS rule and replace the existing one. + * + * Only used for some old browsers because they can't set a selector. + */ + ; + + _proto.replaceRule = function replaceRule(cssRule, rule) { + var index = this.indexOf(cssRule); + if (index === -1) return false; + this.element.sheet.deleteRule(index); + this.cssRules.splice(index, 1); + return this.insertRule(rule, index); + } + /** + * Get all rules elements. + */ + ; + + _proto.getRules = function getRules() { + return this.element.sheet.cssRules; + }; + + return DomRenderer; +}(); + +var instanceCounter = 0; + +var Jss = +/*#__PURE__*/ +function () { + function Jss(options) { + this.id = instanceCounter++; + this.version = "10.5.0"; + this.plugins = new PluginsRegistry(); + this.options = { + id: { + minify: false + }, + createGenerateId: createGenerateId, + Renderer: is_in_browser__WEBPACK_IMPORTED_MODULE_1__["default"] ? DomRenderer : null, + plugins: [] + }; + this.generateId = createGenerateId({ + minify: false + }); + + for (var i = 0; i < plugins.length; i++) { + this.plugins.use(plugins[i], { + queue: 'internal' + }); + } + + this.setup(options); + } + /** + * Prepares various options, applies plugins. + * Should not be used twice on the same instance, because there is no plugins + * deduplication logic. + */ + + + var _proto = Jss.prototype; + + _proto.setup = function setup(options) { + if (options === void 0) { + options = {}; + } + + if (options.createGenerateId) { + this.options.createGenerateId = options.createGenerateId; + } + + if (options.id) { + this.options.id = Object(_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_0__["default"])({}, this.options.id, options.id); + } + + if (options.createGenerateId || options.id) { + this.generateId = this.options.createGenerateId(this.options.id); + } + + if (options.insertionPoint != null) this.options.insertionPoint = options.insertionPoint; + + if ('Renderer' in options) { + this.options.Renderer = options.Renderer; + } // eslint-disable-next-line prefer-spread + + + if (options.plugins) this.use.apply(this, options.plugins); + return this; + } + /** + * Create a Style Sheet. + */ + ; + + _proto.createStyleSheet = function createStyleSheet(styles, options) { + if (options === void 0) { + options = {}; + } + + var _options = options, + index = _options.index; + + if (typeof index !== 'number') { + index = registry.index === 0 ? 0 : registry.index + 1; + } + + var sheet = new StyleSheet(styles, Object(_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_0__["default"])({}, options, { + jss: this, + generateId: options.generateId || this.generateId, + insertionPoint: this.options.insertionPoint, + Renderer: this.options.Renderer, + index: index + })); + this.plugins.onProcessSheet(sheet); + return sheet; + } + /** + * Detach the Style Sheet and remove it from the registry. + */ + ; + + _proto.removeStyleSheet = function removeStyleSheet(sheet) { + sheet.detach(); + registry.remove(sheet); + return this; + } + /** + * Create a rule without a Style Sheet. + * [Deprecated] will be removed in the next major version. + */ + ; + + _proto.createRule = function createRule$1(name, style, options) { + if (style === void 0) { + style = {}; + } + + if (options === void 0) { + options = {}; + } + + // Enable rule without name for inline styles. + if (typeof name === 'object') { + // $FlowFixMe[incompatible-call] + return this.createRule(undefined, name, style); + } // $FlowFixMe[incompatible-type] + + + var ruleOptions = Object(_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_0__["default"])({}, options, { + name: name, + jss: this, + Renderer: this.options.Renderer + }); + + if (!ruleOptions.generateId) ruleOptions.generateId = this.generateId; + if (!ruleOptions.classes) ruleOptions.classes = {}; + if (!ruleOptions.keyframes) ruleOptions.keyframes = {}; + + var rule = createRule(name, style, ruleOptions); + + if (rule) this.plugins.onProcessRule(rule); + return rule; + } + /** + * Register plugin. Passed function will be invoked with a rule instance. + */ + ; + + _proto.use = function use() { + var _this = this; + + for (var _len = arguments.length, plugins = new Array(_len), _key = 0; _key < _len; _key++) { + plugins[_key] = arguments[_key]; + } + + plugins.forEach(function (plugin) { + _this.plugins.use(plugin); + }); + return this; + }; + + return Jss; +}(); + +/** + * Extracts a styles object with only props that contain function values. + */ +function getDynamicStyles(styles) { + var to = null; + + for (var key in styles) { + var value = styles[key]; + var type = typeof value; + + if (type === 'function') { + if (!to) to = {}; + to[key] = value; + } else if (type === 'object' && value !== null && !Array.isArray(value)) { + var extracted = getDynamicStyles(value); + + if (extracted) { + if (!to) to = {}; + to[key] = extracted; + } + } + } + + return to; +} + +/** + * SheetsManager is like a WeakMap which is designed to count StyleSheet + * instances and attach/detach automatically. + */ +var SheetsManager = +/*#__PURE__*/ +function () { + function SheetsManager() { + this.length = 0; + this.sheets = new WeakMap(); + } + + var _proto = SheetsManager.prototype; + + _proto.get = function get(key) { + var entry = this.sheets.get(key); + return entry && entry.sheet; + }; + + _proto.add = function add(key, sheet) { + if (this.sheets.has(key)) return; + this.length++; + this.sheets.set(key, { + sheet: sheet, + refs: 0 + }); + }; + + _proto.manage = function manage(key) { + var entry = this.sheets.get(key); + + if (entry) { + if (entry.refs === 0) { + entry.sheet.attach(); + } + + entry.refs++; + return entry.sheet; + } + + Object(tiny_warning__WEBPACK_IMPORTED_MODULE_2__["default"])(false, "[JSS] SheetsManager: can't find sheet to manage"); + return undefined; + }; + + _proto.unmanage = function unmanage(key) { + var entry = this.sheets.get(key); + + if (entry) { + if (entry.refs > 0) { + entry.refs--; + if (entry.refs === 0) entry.sheet.detach(); + } + } else { + Object(tiny_warning__WEBPACK_IMPORTED_MODULE_2__["default"])(false, "SheetsManager: can't find sheet to unmanage"); + } + }; + + Object(_babel_runtime_helpers_esm_createClass__WEBPACK_IMPORTED_MODULE_3__["default"])(SheetsManager, [{ + key: "size", + get: function get() { + return this.length; + } + }]); + + return SheetsManager; +}(); + +/** + * A better abstraction over CSS. + * + * @copyright Oleg Isonen (Slobodskoi) / Isonen 2014-present + * @website https://github.com/cssinjs/jss + * @license MIT + */ + +/** + * Export a constant indicating if this browser has CSSTOM support. + * https://developers.google.com/web/updates/2018/03/cssom + */ +var hasCSSTOMSupport = typeof CSS === 'object' && CSS != null && 'number' in CSS; +/** + * Creates a new instance of Jss. + */ + +var create = function create(options) { + return new Jss(options); +}; +/** + * A global Jss instance. + */ + +var jss = create(); + +/* harmony default export */ __webpack_exports__["default"] = (jss); + + + +/***/ }), + +/***/ "./node_modules/lru-cache/index.js": +/*!*****************************************!*\ + !*** ./node_modules/lru-cache/index.js ***! + \*****************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +// A linked list to keep track of recently-used-ness +const Yallist = __webpack_require__(/*! yallist */ "./node_modules/yallist/yallist.js") + +const MAX = Symbol('max') +const LENGTH = Symbol('length') +const LENGTH_CALCULATOR = Symbol('lengthCalculator') +const ALLOW_STALE = Symbol('allowStale') +const MAX_AGE = Symbol('maxAge') +const DISPOSE = Symbol('dispose') +const NO_DISPOSE_ON_SET = Symbol('noDisposeOnSet') +const LRU_LIST = Symbol('lruList') +const CACHE = Symbol('cache') +const UPDATE_AGE_ON_GET = Symbol('updateAgeOnGet') + +const naiveLength = () => 1 + +// lruList is a yallist where the head is the youngest +// item, and the tail is the oldest. the list contains the Hit +// objects as the entries. +// Each Hit object has a reference to its Yallist.Node. This +// never changes. +// +// cache is a Map (or PseudoMap) that matches the keys to +// the Yallist.Node object. +class LRUCache { + constructor (options) { + if (typeof options === 'number') + options = { max: options } + + if (!options) + options = {} + + if (options.max && (typeof options.max !== 'number' || options.max < 0)) + throw new TypeError('max must be a non-negative number') + // Kind of weird to have a default max of Infinity, but oh well. + const max = this[MAX] = options.max || Infinity + + const lc = options.length || naiveLength + this[LENGTH_CALCULATOR] = (typeof lc !== 'function') ? naiveLength : lc + this[ALLOW_STALE] = options.stale || false + if (options.maxAge && typeof options.maxAge !== 'number') + throw new TypeError('maxAge must be a number') + this[MAX_AGE] = options.maxAge || 0 + this[DISPOSE] = options.dispose + this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false + this[UPDATE_AGE_ON_GET] = options.updateAgeOnGet || false + this.reset() + } + + // resize the cache when the max changes. + set max (mL) { + if (typeof mL !== 'number' || mL < 0) + throw new TypeError('max must be a non-negative number') + + this[MAX] = mL || Infinity + trim(this) + } + get max () { + return this[MAX] + } + + set allowStale (allowStale) { + this[ALLOW_STALE] = !!allowStale + } + get allowStale () { + return this[ALLOW_STALE] + } + + set maxAge (mA) { + if (typeof mA !== 'number') + throw new TypeError('maxAge must be a non-negative number') + + this[MAX_AGE] = mA + trim(this) + } + get maxAge () { + return this[MAX_AGE] + } + + // resize the cache when the lengthCalculator changes. + set lengthCalculator (lC) { + if (typeof lC !== 'function') + lC = naiveLength + + if (lC !== this[LENGTH_CALCULATOR]) { + this[LENGTH_CALCULATOR] = lC + this[LENGTH] = 0 + this[LRU_LIST].forEach(hit => { + hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key) + this[LENGTH] += hit.length + }) + } + trim(this) + } + get lengthCalculator () { return this[LENGTH_CALCULATOR] } + + get length () { return this[LENGTH] } + get itemCount () { return this[LRU_LIST].length } + + rforEach (fn, thisp) { + thisp = thisp || this + for (let walker = this[LRU_LIST].tail; walker !== null;) { + const prev = walker.prev + forEachStep(this, fn, walker, thisp) + walker = prev + } + } + + forEach (fn, thisp) { + thisp = thisp || this + for (let walker = this[LRU_LIST].head; walker !== null;) { + const next = walker.next + forEachStep(this, fn, walker, thisp) + walker = next + } + } + + keys () { + return this[LRU_LIST].toArray().map(k => k.key) + } + + values () { + return this[LRU_LIST].toArray().map(k => k.value) + } + + reset () { + if (this[DISPOSE] && + this[LRU_LIST] && + this[LRU_LIST].length) { + this[LRU_LIST].forEach(hit => this[DISPOSE](hit.key, hit.value)) + } + + this[CACHE] = new Map() // hash of items by key + this[LRU_LIST] = new Yallist() // list of items in order of use recency + this[LENGTH] = 0 // length of items in the list + } + + dump () { + return this[LRU_LIST].map(hit => + isStale(this, hit) ? false : { + k: hit.key, + v: hit.value, + e: hit.now + (hit.maxAge || 0) + }).toArray().filter(h => h) + } + + dumpLru () { + return this[LRU_LIST] + } + + set (key, value, maxAge) { + maxAge = maxAge || this[MAX_AGE] + + if (maxAge && typeof maxAge !== 'number') + throw new TypeError('maxAge must be a number') + + const now = maxAge ? Date.now() : 0 + const len = this[LENGTH_CALCULATOR](value, key) + + if (this[CACHE].has(key)) { + if (len > this[MAX]) { + del(this, this[CACHE].get(key)) + return false + } + + const node = this[CACHE].get(key) + const item = node.value + + // dispose of the old one before overwriting + // split out into 2 ifs for better coverage tracking + if (this[DISPOSE]) { + if (!this[NO_DISPOSE_ON_SET]) + this[DISPOSE](key, item.value) + } + + item.now = now + item.maxAge = maxAge + item.value = value + this[LENGTH] += len - item.length + item.length = len + this.get(key) + trim(this) + return true + } + + const hit = new Entry(key, value, len, now, maxAge) + + // oversized objects fall out of cache automatically. + if (hit.length > this[MAX]) { + if (this[DISPOSE]) + this[DISPOSE](key, value) + + return false + } + + this[LENGTH] += hit.length + this[LRU_LIST].unshift(hit) + this[CACHE].set(key, this[LRU_LIST].head) + trim(this) + return true + } + + has (key) { + if (!this[CACHE].has(key)) return false + const hit = this[CACHE].get(key).value + return !isStale(this, hit) + } + + get (key) { + return get(this, key, true) + } + + peek (key) { + return get(this, key, false) + } + + pop () { + const node = this[LRU_LIST].tail + if (!node) + return null + + del(this, node) + return node.value + } + + del (key) { + del(this, this[CACHE].get(key)) + } + + load (arr) { + // reset the cache + this.reset() + + const now = Date.now() + // A previous serialized cache has the most recent items first + for (let l = arr.length - 1; l >= 0; l--) { + const hit = arr[l] + const expiresAt = hit.e || 0 + if (expiresAt === 0) + // the item was created without expiration in a non aged cache + this.set(hit.k, hit.v) + else { + const maxAge = expiresAt - now + // dont add already expired items + if (maxAge > 0) { + this.set(hit.k, hit.v, maxAge) + } + } + } + } + + prune () { + this[CACHE].forEach((value, key) => get(this, key, false)) + } +} + +const get = (self, key, doUse) => { + const node = self[CACHE].get(key) + if (node) { + const hit = node.value + if (isStale(self, hit)) { + del(self, node) + if (!self[ALLOW_STALE]) + return undefined + } else { + if (doUse) { + if (self[UPDATE_AGE_ON_GET]) + node.value.now = Date.now() + self[LRU_LIST].unshiftNode(node) + } + } + return hit.value + } +} + +const isStale = (self, hit) => { + if (!hit || (!hit.maxAge && !self[MAX_AGE])) + return false + + const diff = Date.now() - hit.now + return hit.maxAge ? diff > hit.maxAge + : self[MAX_AGE] && (diff > self[MAX_AGE]) +} + +const trim = self => { + if (self[LENGTH] > self[MAX]) { + for (let walker = self[LRU_LIST].tail; + self[LENGTH] > self[MAX] && walker !== null;) { + // We know that we're about to delete this one, and also + // what the next least recently used key will be, so just + // go ahead and set it now. + const prev = walker.prev + del(self, walker) + walker = prev + } + } +} + +const del = (self, node) => { + if (node) { + const hit = node.value + if (self[DISPOSE]) + self[DISPOSE](hit.key, hit.value) + + self[LENGTH] -= hit.length + self[CACHE].delete(hit.key) + self[LRU_LIST].removeNode(node) + } +} + +class Entry { + constructor (key, value, length, now, maxAge) { + this.key = key + this.value = value + this.length = length + this.now = now + this.maxAge = maxAge || 0 + } +} + +const forEachStep = (self, fn, node, thisp) => { + let hit = node.value + if (isStale(self, hit)) { + del(self, node) + if (!self[ALLOW_STALE]) + hit = undefined + } + if (hit) + fn.call(thisp, hit.value, hit.key, self) +} + +module.exports = LRUCache + + +/***/ }), + +/***/ "./node_modules/meeting-pane/lib/meetingDetailsForm.js": +/*!*************************************************************!*\ + !*** ./node_modules/meeting-pane/lib/meetingDetailsForm.js ***! + \*************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +module.exports = "@prefix : .\n@prefix f: <#> .\n@prefix dc: .\n@prefix cal: .\n@prefix meeting: .\n@prefix ns: .\n@prefix rdf: .\n@prefix rdfs: .\n@prefix te: .\n@prefix dc: .\n@prefix xsd: .\n@prefix ui: .\n\n f:main a :Form;\n cal:summary \"Meeting Details\";\n :part f:titleField, f:locationField, f:startField,\n f:endField, f:eventComment, f:colorField .\n\n f:titleField a :SingleLineTextField;\n :maxLength 256;\n :property cal:summary;\n :label \"Name of meeting\";\n :size 80 .\n\n f:locationField a :SingleLineTextField;\n :maxLength 128;\n :property cal:location;\n :size 40 .\n\n f:startField a :DateField;\n :label \"Start\";\n :property cal:dtstart .\n\n f:endField a :DateField;\n :label \"End\";\n :property cal:dtend .\n\n f:colorField a :ColorField;\n :label \"Tab color\";\n # :default \"#ddddcc\"^^xsd:color;\n :property ui:backgroundColor .\n\n f:eventComment\n a ui:MultiLineTextField;\n # ui:maxLength\n # \"1048\";\n # ui:size\n # \"40\".\n ui:property\n cal:comment.\n\n###################################################\n\nf:settings a :Form;\n dc:title \"Tab settings\";\n :part f:labelField, f:targetField, f:viewField.\n\n f:labelField a :SingleLineTextField;\n :maxLength 128;\n :property rdfs:label;\n :label \"Label on tab\";\n :size 40 .\n\n f:targetField a :NamedNodeURIField;\n :maxLength 1024; # Longer?\n :property meeting:target;\n :label \"URL of resource\";\n :size 80 .\n\n f:colorField2 a :ColorField;\n :label \"Tab color\";\n # :default \"#ddddcc\"^^xsd:color;\n :property ui:backgroundColor .\n\n f:viewField a :SingleLineTextField;\n :maxLength 128;\n :property meeting:view;\n :label \"View mode (experts only)\";\n :size 40 .\n\n#\n"; +//# sourceMappingURL=meetingDetailsForm.js.map + +/***/ }), + +/***/ "./node_modules/meeting-pane/lib/meetingPane.js": +/*!******************************************************!*\ + !*** ./node_modules/meeting-pane/lib/meetingPane.js ***! + \******************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +/* Meeting materials and tools Pane + ** + ** Putting together some of the tools we have to manage a Meeting + */ +// const VideoRoomPrefix = 'https://appear.in/' +var VideoRoomPrefix = 'https://meet.jit.si/'; + +var UI = __webpack_require__(/*! solid-ui */ "./node_modules/solid-ui/lib/index.js"); + +var ns = UI.ns; + +var $rdf = __webpack_require__(/*! rdflib */ "./node_modules/rdflib/esm/index.js"); + +var meetingDetailsFormText = __webpack_require__(/*! ./meetingDetailsForm.js */ "./node_modules/meeting-pane/lib/meetingDetailsForm.js"); + +module.exports = { + icon: UI.icons.iconBase + 'noun_66617.svg', + name: 'meeting', + audience: [ns.solid('PowerUser')], + label: function label(subject, context) { + var kb = context.session.store; + var ns = UI.ns; + + if (kb.holds(subject, ns.rdf('type'), ns.meeting('Meeting'))) { + return 'Meeting'; + } + + return null; // Suppress pane otherwise + }, + // Create a new Meeting thing + // + // returns: A promise of a meeting object + // + mintClass: UI.ns.meeting('Meeting'), + mintNew: function mintNew(context, options) { + return new Promise(function (resolve, reject) { + var kb = context.session.store; + var ns = UI.ns; + options.newInstance = options.newInstance || kb.sym(options.newBase + 'index.ttl#this'); + var meeting = options.newInstance; + var meetingDoc = meeting.doc(); + var me = UI.authn.currentUser(); + + if (me) { + kb.add(meeting, ns.dc('author'), me, meetingDoc); + } + + kb.add(meeting, ns.rdf('type'), ns.meeting('Meeting'), meetingDoc); + kb.add(meeting, ns.dc('created'), new Date(), meetingDoc); + kb.add(meeting, ns.ui('backgroundColor'), new $rdf.Literal('#ddddcc', undefined, ns.xsd('color')), meetingDoc); + var toolList = new $rdf.Collection(); + kb.add(meeting, ns.meeting('toolList'), toolList, meetingDoc); + toolList.elements.push(meeting); // Add the meeting itself - see renderMain() + + kb.updater.put(meetingDoc, kb.statementsMatching(undefined, undefined, undefined, meetingDoc), 'text/turtle', function (uri2, ok, message) { + if (ok) { + resolve(options); + } else { + reject(new Error('Error writing meeting configuration: ' + message)); + } + }); + }); + }, + // Returns a div + render: function render(subject, dataBrowserContext) { + var dom = dataBrowserContext.dom; + var kb = dataBrowserContext.session.store; + var ns = UI.ns; + var updater = kb.updater; + var thisPane = this; + + var complain = function complain(message, color) { + console.log(message); + var pre = dom.createElement('pre'); + pre.setAttribute('style', 'background-color: ' + color || false); + div.appendChild(pre); + pre.appendChild(dom.createTextNode(message)); + }; + + var complainIfBad = function complainIfBad(ok, message) { + if (!ok) complain(message); + }; + + var meeting = subject; + var meetingDoc = subject.doc(); + var meetingBase = subject.dir().uri; + var div = dom.createElement('div'); + var table = div.appendChild(dom.createElement('table')); + table.style = 'width: 100%; height: 100%; margin:0;'; + var topTR = table.appendChild(dom.createElement('tr')); + topTR.appendChild(dom.createElement('div')); // topDiv + + var mainTR = table.appendChild(dom.createElement('tr')); + var toolBar0 = table.appendChild(dom.createElement('td')); + var toolBar1 = toolBar0.appendChild(dom.createElement('table')); + var toolBar = toolBar1.appendChild(dom.createElement('tr')); + topTR.setAttribute('style', 'height: 2em;'); // spacer if notthing else + + var me = null; // @@ Put code to find out logged in person + + var saveBackMeetingDoc = function saveBackMeetingDoc() { + updater.put(meetingDoc, kb.statementsMatching(undefined, undefined, undefined, meetingDoc), 'text/turtle', function (uri2, ok, message) { + if (ok) { + tabs.refresh(); + resetTools(); + } else { + message = 'FAILED to save new thing at: ' + meetingDoc + ' : ' + message; + complain(message); + } + }); + }; + + var saveAppDocumentLinkAndAddNewThing = function saveAppDocumentLinkAndAddNewThing(tool, thing, pred) { + var appDoc = thing.doc(); + + if (pred) { + kb.add(meeting, pred, thing, appDoc); // Specific Link back to meeting + } + + kb.add(thing, ns.meeting('parentMeeting'), meeting, appDoc); // Generic link back to meeting + + updater.put(appDoc, kb.statementsMatching(undefined, undefined, undefined, appDoc), 'text/turtle', function (uri2, ok, message) { + if (ok) { + saveBackMeetingDoc(); + } else { + complain('FAILED to save new tool at: ' + thing + ' : ' + message); + } + }); + }; + + var makeToolNode = function makeToolNode(target, pred, label, iconURI) { + if (pred) { + kb.add(meeting, pred, target, meetingDoc); + } + + var x = UI.widgets.newThing(meetingDoc); + if (label) kb.add(x, ns.rdfs('label'), label, meetingDoc); + if (iconURI) kb.add(x, ns.meeting('icon'), kb.sym(iconURI), meetingDoc); + kb.add(x, ns.rdf('type'), ns.meeting('Tool'), meetingDoc); + kb.add(x, ns.meeting('target'), target, meetingDoc); + var toolList = kb.the(meeting, ns.meeting('toolList')); + toolList.elements.push(x); + return x; + }; // Map from end-user non-iframeable Google maps URI to G Maps API + // Input: like https://www.google.co.uk/maps/place/Mastercard/@53.2717971,-6.2042699,17z/... + // Output: + + + function googleMapsSpecial(page) { + var initialPrefix = /https:\/\/www\.google\..*\/maps\//; + var finalPrefix = 'https://www.google.com/maps/embed/v1/'; + var myPersonalApiKEY = 'AIzaSyB8aaT6bY9tcLCmc2oPCkdUYLmTOWM8R54'; // Get your own key! + // GET YOUR KEY AT https://developers.google.com/maps/documentation/javascript/ + + var uri = page.uri; + if (!uri.match(initialPrefix)) return page; + if (uri.startsWith(finalPrefix)) return page; // Already done + + var map = uri.replace(initialPrefix, finalPrefix) + '&key=' + myPersonalApiKEY; + console.log('Converted Google Map URI! ' + map); + return $rdf.sym(map); + } // //////////////////// DRAG and Drop + + + var handleDroppedThing = function handleDroppedThing(target) { + // @@ idea: look + return new Promise(function (resolve) { + // Add a meeting tab for a web resource. Alas many resource canot be framed + // as they block framing, or are insecure. + var addIframeTool = function addIframeTool(target) { + var tool = makeToolNode(target, UI.ns.wf('attachment'), UI.utils.label(target), null); + kb.add(tool, UI.ns.meeting('view'), 'iframe', meetingDoc); + }; + + var addLink = function addLink(target) { + var pred = ns.wf('attachment'); + kb.add(subject, pred, target, subject.doc()); + var toolObject = { + icon: 'noun_160581.svg', + // right arrow "link" + limit: 1, + shareTab: true // but many things behind it + + }; + var newPaneOptions = { + newInstance: subject, + // kb.sym(subject.doc().uri + '#LinkListTool'), + pane: dataBrowserContext.session.paneRegistry.byName('link'), + // the pane to be used to mint a new thing + predicate: ns.meeting('attachmentTool'), + tabTitle: 'Links', + view: 'link', + // The pane to be used when it is viewed + noIndexHTML: true + }; + return makeNewPaneTool(toolObject, newPaneOptions); + }; // When paerson added to he meeting, make an ad hoc group + // of meeting participants is one does not already exist, and add them + + + var addParticipant = function addParticipant(target) { + var pref = kb.any(target, ns.foaf('preferredURI')); + var obj = pref ? kb.sym(pref) : target; + var group = kb.any(meeting, ns.meeting('attendeeGroup')); + + var addPersonToGroup = function addPersonToGroup(obj, group) { + var ins = [$rdf.st(group, UI.ns.vcard('hasMember'), obj, group.doc())]; // @@@ Complex rules about webid? + + var name = kb.any(obj, ns.vcard('fn')) || kb.any(obj, ns.foaf('name')); + + if (name) { + ins.push($rdf.st(obj, UI.ns.vcard('fn'), name, group.doc())); + } + + kb.fetcher.nowOrWhenFetched(group.doc(), undefined, function (ok, _body) { + if (!ok) { + complain("Can't read group to add person" + group); + return; + } + + kb.updater.update([], ins, function (uri, ok, body) { + complainIfBad(ok, body); + + if (ok) { + console.log('Addded to particpants OK: ' + obj); + } + }); + }); + }; + + if (group) { + addPersonToGroup(obj, group); + return; + } + + makeParticipantsGroup().then(function (options) { + var group = options.newInstance; + addPersonToGroup(obj, group); + kb.fetcher.putBack(meetingDoc, { + contentType: 'text/turtle' + }).then(function (_xhr) { + console.log('Particiants Group created: ' + group); + }); + })["catch"](function (err) { + complain(err); + }); + }; + + console.log('Dropped on thing ' + target); // icon was: UI.icons.iconBase + 'noun_25830.svg' + + var u = target.uri; + + if (u.startsWith('http:') && u.indexOf('#') < 0) { + // insecure Plain document + addLink(target); + return resolve(target); + } + + kb.fetcher.nowOrWhenFetched(target, function (ok, mess) { + function addAttachmentTab(target) { + target = googleMapsSpecial(target); + console.log('make web page attachement tab ' + target); // icon was: UI.icons.iconBase + 'noun_25830.svg' + + var tool = makeToolNode(target, UI.ns.wf('attachment'), UI.utils.label(target), null); + kb.add(tool, UI.ns.meeting('view'), 'iframe', meetingDoc); + return resolve(target); + } + + if (!ok) { + console.log('Error looking up dropped thing, will just add it anyway. ' + target + ': ' + mess); + return addAttachmentTab(target); // You can still try iframing it. (Could also add to list of links in PersonTR widgets) + } else { + var obj = target; + var types = kb.findTypeURIs(obj); + + for (var ty in types) { + console.log(' drop object type includes: ' + ty); + } + + if (ns.vcard('Individual').uri in types || ns.foaf('Person').uri in types || ns.foaf('Agent').uri in types) { + addParticipant(target); + return resolve(target); + } + + if (u.startsWith('https:') && u.indexOf('#') < 0) { + // Plain secure document + // can we iframe it? + var hh = kb.fetcher.getHeader(target, 'x-frame-options'); + var ok2 = true; + + if (hh) { + for (var j = 0; j < hh.length; j++) { + console.log('x-frame-options: ' + hh[j]); + + if (hh[j].indexOf('sameorigin') < 0) { + // (and diff origin @@) + ok2 = false; + } + + if (hh[j].indexOf('deny') < 0) { + ok2 = false; + } + } + } + + if (ok2) { + target = googleMapsSpecial(target); // tweak Google maps to embed OK + + addIframeTool(target); // Something we can maybe iframe + + return resolve(target); + } + } // Something we cannot iframe, and must link to: + + + console.log('Default: assume web page attachement ' + target); // icon was: UI.icons.iconBase + 'noun_25830.svg' + + return addAttachmentTab(target); + } + }); + }); // promise + }; // When a set of URIs are dropped on the tabs + + + var droppedURIHandler = function droppedURIHandler(uris) { + Promise.all(uris.map(function (u) { + var target = $rdf.sym(u); // Attachment needs text label to disinguish I think not icon. + + return handleDroppedThing(target); // can add to meetingDoc but must be sync + })).then(function (_a) { + saveBackMeetingDoc(); + }); + }; + + var droppedFileHandler = function droppedFileHandler(files) { + UI.widgets.uploadFiles(kb.fetcher, files, meeting.dir().uri + 'Files', meeting.dir().uri + 'Pictures', function (theFile, _destURI) { + if (theFile.type.startsWith('image/')) { + makePicturesFolder('Files'); // If necessary + } else { + makeMaterialsFolder('Pictures'); + } + }); + }; // ////////////////////////////////////////////////////// end of drag drop + + + var makeGroup = function makeGroup(_toolObject) { + var newBase = meetingBase + 'Group/'; + var kb = dataBrowserContext.session.store; + var group = kb.any(meeting, ns.meeting('particpants')); + + if (!group) { + group = $rdf.sym(newBase + 'index.ttl#this'); + } + + console.log('Participant group: ' + group); + var tool = makeToolNode(group, ns.meeting('particpants'), 'Particpants', UI.icons.iconBase + 'noun_339237.svg'); // group: noun_339237.svg 'noun_15695.svg' + + kb.add(tool, UI.ns.meeting('view'), 'peoplePicker', meetingDoc); + saveBackMeetingDoc(); + }; + /* + var makeAddressBook = function (toolObject) { + var newBase = meetingBase + 'Group/' + var kb = UI.store + var group = kb.any(meeting, ns.meeting('addressBook')) + if (!group) { + group = $rdf.sym(newBase + 'index.ttl#this') + } + // Create a tab for the addressbook + var div = dom.createElement('div') + var context = { dom: dom, div: div } + var book + UI.authn.findAppInstances(context, ns.vcard('AddressBook')).then( + function (context) { + if (context.instances.length === 0) { + complain('You have no solid address book. It is really handy to have one to keep track of people and groups') + } else if (context.instances.length > 1) { + var s = context.instances.map(function (x) { return '' + x }).join(', ') + complain('You have more than one solid address book: ' + s + ' Not supported yet.') + } else { // addressbook + book = context.instances[0] + var tool = makeToolNode(book, ns.meeting('addressBook'), 'Address Book', UI.icons.iconBase + 'noun_15695.svg') // group: noun_339237.svg + kb.add(tool, UI.ns.meeting('view'), 'contact', meetingDoc) + saveBackMeetingDoc() + } + } + ) + } + */ + + + var makePoll = function makePoll(toolObject) { + var newPaneOptions = { + useExisting: meeting, + // Regard the meeting as being the schedulable event itself. + // newInstance: meeting, + pane: dataBrowserContext.session.paneRegistry.byName('schedule'), + view: 'schedule', + // predicate: ns.meeting('schedulingPoll'), + // newBase: meetingBase + 'Schedule/', Not needed as uses existing meeting + tabTitle: 'Schedule poll', + noIndexHTML: true + }; + return makeNewPaneTool(toolObject, newPaneOptions); + }; + + var makePicturesFolder = function makePicturesFolder(folderName) { + var toolObject = { + icon: 'noun_598334.svg', + // Slideshow @@ find a "picture" icon? + limit: 1, + shareTab: true // but many things behind it + + }; + var newPaneOptions = { + newInstance: kb.sym(meeting.dir().uri + folderName + '/'), + pane: dataBrowserContext.session.paneRegistry.byName('folder'), + // @@ slideshow?? + predicate: ns.meeting('pictures'), + shareTab: true, + tabTitle: folderName, + view: 'slideshow', + noIndexHTML: true + }; + return makeNewPaneTool(toolObject, newPaneOptions); + }; + + var makeMaterialsFolder = function makeMaterialsFolder(_folderName) { + var toolObject = { + icon: 'noun_681601.svg', + // Document + limit: 1, + shareTab: true // but many things behind it + + }; + var options = { + newInstance: kb.sym(meeting.dir().uri + 'Files/'), + pane: dataBrowserContext.session.paneRegistry.byName('folder'), + predicate: ns.meeting('materialsFolder'), + tabTitle: 'Materials', + noIndexHTML: true + }; + return makeNewPaneTool(toolObject, options); + }; + + var makeParticipantsGroup = function makeParticipantsGroup() { + var toolObject = { + icon: 'noun_339237.svg', + // Group of people + limit: 1, + // Only one tab + shareTab: true // but many things behind it + + }; + var options = { + newInstance: kb.sym(meeting.dir().uri + 'Attendees/index.ttl#this'), + pane: dataBrowserContext.session.paneRegistry.byName('contact'), + predicate: ns.meeting('attendeeGroup'), + tabTitle: 'Attendees', + instanceClass: ns.vcard('Group'), + instanceName: UI.utils.label(subject) + ' attendees', + noIndexHTML: true + }; + return makeNewPaneTool(toolObject, options); + }; // Make Pad for notes of meeting + + + var makePad = function makePad(toolObject) { + var newPaneOptions = { + newBase: meetingBase + 'SharedNotes/', + predicate: UI.ns.meeting('sharedNotes'), + tabTitle: 'Shared Notes', + pane: dataBrowserContext.session.paneRegistry.byName('pad') + }; + return makeNewPaneTool(toolObject, newPaneOptions); + }; // Make Sub-meeting of meeting + + + var makeMeeting = function makeMeeting(toolObject) { + UI.widgets.askName(dom, kb, parameterCell, ns.foaf('name'), UI.ns.meeting('Meeting')).then(function (name) { + if (!name) { + return resetTools(); + } + + var URIsegment = encodeURIComponent(name); + var options = { + newBase: meetingBase + URIsegment + '/', + // @@@ sanitize + predicate: UI.ns.meeting('subMeeting'), + tabTitle: name, + pane: dataBrowserContext.session.paneRegistry.byName('meeting') + }; + return makeNewPaneTool(toolObject, options); + })["catch"](function (e) { + complain('Error making new sub-meeting: ' + e); + }); + }; // Returns promise of newPaneOptions + // In: options. + // me?, predicate, newInstance ?, newBase, instanceClass + // out: options. the above plus + // me, newInstance + + + function makeNewPaneTool(toolObject, options) { + return new Promise(function (resolve, reject) { + var kb = dataBrowserContext.session.store; + + if (!options.useExisting) { + // useExisting means use existing object in new role + var existing = kb.any(meeting, options.predicate); + + if (existing) { + if (toolObject.limit && toolObject.limit === 1 && !toolObject.shareTab) { + complain('Already have ' + existing + ' as ' + UI.utils.label(options.predicate)); + complain('Cant have two'); + return resolve(null); + } + + if (toolObject.shareTab) { + // return existing one + console.log('Using existing ' + existing + ' as ' + UI.utils.label(options.predicate)); + return resolve({ + me: me, + newInstance: existing, + instanceClass: options.instanceClass + }); + } + } + } + + if (!me && !options.me) { + reject(new Error('Username not defined for new tool')); + } + + options.me = options.me || me; + options.newInstance = options.useExisting || options.newInstance || kb.sym(options.newBase + 'index.ttl#this'); + options.pane.mintNew(dataBrowserContext, options).then(function (options) { + var tool = makeToolNode(options.newInstance, options.predicate, options.tabTitle, options.pane.icon); + + if (options.view) { + kb.add(tool, UI.ns.meeting('view'), options.view, meetingDoc); + } + + saveBackMeetingDoc(); + kb.fetcher.putBack(meetingDoc, { + contentType: 'text/turtle' + }).then(function (_xhr) { + resolve(options); + })["catch"](function (err) { + reject(err); + }); + })["catch"](function (err) { + complain(err); + reject(err); + }); + }); + } + + var makeAgenda = function makeAgenda(_toolObject) {// selectTool(icon) + }; + + var makeActions = function makeActions(_toolObject) { + var newBase = meetingBase + 'Actions/'; + var kb = dataBrowserContext.session.store; + + if (kb.holds(meeting, ns.meeting('actions'))) { + console.log('Ignored - already have actions'); + return; // already got one + } + + var appDoc = kb.sym(newBase + 'config.ttl'); + var newInstance = kb.sym(newBase + 'config.ttl#this'); + var stateStore = kb.sym(newBase + 'state.ttl'); + kb.add(newInstance, ns.dc('title'), (kb.anyValue(meeting, ns.cal('summary')) || 'Meeting ') + ' actions', appDoc); + kb.add(newInstance, ns.wf('issueClass'), ns.wf('Task'), appDoc); + kb.add(newInstance, ns.wf('initialState'), ns.wf('Open'), appDoc); + kb.add(newInstance, ns.wf('stateStore'), stateStore, appDoc); + kb.add(newInstance, ns.wf('assigneeClass'), ns.foaf('Person'), appDoc); // @@ set to people in the meeting? + + kb.add(newInstance, ns.rdf('type'), ns.wf('Tracker'), appDoc); // Flag its type in the chat itself as well as in the master meeting config file + + kb.add(newInstance, ns.rdf('type'), ns.wf('Tracker'), appDoc); + var tool = makeToolNode(newInstance, ns.meeting('actions'), 'Actions', UI.icons.iconBase + 'noun_17020.svg'); + saveAppDocumentLinkAndAddNewThing(tool, newInstance, ns.meeting('actions')); + }; + + var makeChat = function makeChat(_toolObject) { + var newBase = meetingBase + 'Chat/'; + var kb = dataBrowserContext.session.store; + + if (kb.holds(meeting, ns.meeting('chat'))) { + console.log('Ignored - already have chat'); + return; // already got one + } + + var messageStore = kb.sym(newBase + 'chat.ttl'); + kb.add(messageStore, ns.rdf('type'), ns.meeting('Chat'), messageStore); + var tool = makeToolNode(messageStore, ns.meeting('chat'), 'Chat', UI.icons.iconBase + 'noun_346319.svg'); + saveAppDocumentLinkAndAddNewThing(tool, messageStore, ns.meeting('chat')); + }; + + var makeVideoCall = function makeVideoCall(_toolObject) { + var kb = dataBrowserContext.session.store; + var newInstance = $rdf.sym(VideoRoomPrefix + UI.utils.genUuid()); + + if (kb.holds(meeting, ns.meeting('videoCallPage'))) { + console.log('Ignored - already have a videoCallPage'); + return; // already got one + } + + kb.add(newInstance, ns.rdf('type'), ns.meeting('VideoCallPage'), meetingDoc); + var tool = makeToolNode(newInstance, ns.meeting('videoCallPage'), 'Video call', UI.icons.iconBase + 'noun_260227.svg'); + kb.add(tool, ns.meeting('view'), 'iframe', meetingDoc); + saveBackMeetingDoc(); + }; + + var makeAttachment = function makeAttachment(_toolObject) { + UI.widgets.askName(dom, kb, parameterCell, ns.log('uri'), UI.ns.rdf('Resource')).then(function (uri) { + if (!uri) { + return resetTools(); + } + + var kb = dataBrowserContext.session.store; + var ns = UI.ns; + var target = kb.sym(uri); + var tool = makeToolNode(target, ns.wf('attachment'), UI.utils.label(target), null); + kb.add(tool, ns.meeting('view'), 'iframe', meetingDoc); + saveBackMeetingDoc(); + })["catch"](function (e) { + complain('Error making new sub-meeting: ' + e); + }); + }; + + var makeSharing = function makeSharing(toolObject) { + var kb = dataBrowserContext.session.store; + var ns = UI.ns; + var target = meeting.dir(); + + if (toolObject.limit && toolObject.limit === 1 && kb.holds(meeting, ns.wf('sharingControl'))) { + complain('Ignored - already have ' + UI.utils.label(options.predicate)); + return; + } + + var tool = makeToolNode(target, ns.wf('sharingControl'), 'Sharing', UI.icons.iconBase + 'noun_123691.svg'); + kb.add(tool, ns.meeting('view'), 'sharing', meetingDoc); + saveBackMeetingDoc(); + }; + + var makeNewMeeting = function makeNewMeeting() { + // @@@ make option of continuing series + var appDetails = { + noun: 'meeting' + }; + + var gotWS = function gotWS(ws, base) { + thisPane.mintNew(dataBrowserContext, { + newBase: base + }).then(function (options) { + var newInstance = options.newInstance; + parameterCell.removeChild(mintUI); + var p = parameterCell.appendChild(dom.createElement('p')); + p.setAttribute('style', 'font-size: 140%;'); + p.innerHTML = "Your new meeting is ready to be set up. " + "

Go to your new meeting."; + })["catch"](function (err) { + parameterCell.removeChild(mintUI); + parameterCell.appendChild(UI.widgets.errorMessageBlock(dom, err)); + }); + }; + + var mintUI = UI.authn.selectWorkspace(dom, appDetails, gotWS); + parameterCell.appendChild(mintUI); + }; // //////////////////////////////////////////////////////////// end of new tab creation functions + + + var toolIcons = [{ + icon: 'noun_339237.svg', + maker: makeGroup, + hint: 'Make a group of people', + limit: 1 + }, { + icon: 'noun_346777.svg', + maker: makePoll, + hint: 'Make a poll to schedule the meeting' + }, // When meet THIS or NEXT time + { + icon: 'noun_48218.svg', + maker: makeAgenda, + limit: 1, + hint: 'Add an agenda list', + disabled: true + }, // When meet THIS or NEXT time + { + icon: 'noun_79217.svg', + maker: makePad, + hint: 'Add a shared notepad' + }, { + icon: 'noun_346319.svg', + maker: makeChat, + limit: 1, + hint: 'Add a chat channel for the meeting' + }, { + icon: 'noun_17020.svg', + maker: makeActions, + limit: 1, + hint: 'Add a list of action items' + }, // When meet THIS or NEXT time + { + icon: 'noun_260227.svg', + maker: makeVideoCall, + limit: 1, + hint: 'Add a video call for the meeting' + }, { + icon: 'noun_25830.svg', + maker: makeAttachment, + hint: 'Attach meeting materials', + disabled: false + }, { + icon: 'noun_123691.svg', + maker: makeSharing, + limit: 1, + hint: 'Control Sharing', + disabled: false + }, { + icon: 'noun_66617.svg', + maker: makeMeeting, + hint: 'Make a sub meeting', + disabled: false + }]; // 'noun_66617.svg' + + var settingsForm = $rdf.sym('https://solid.github.io/solid-panes/meeting/meetingDetailsForm.ttl#settings'); + $rdf.parse(meetingDetailsFormText, kb, settingsForm.doc().uri, 'text/turtle'); // Load form directly + + var iconStyle = 'padding: 1em; width: 3em; height: 3em;'; + var iconCell = toolBar.appendChild(dom.createElement('td')); + var parameterCell = toolBar.appendChild(dom.createElement('td')); + var star = iconCell.appendChild(dom.createElement('img')); + var visible = false; // the inividual tools tools + + star.setAttribute('src', UI.icons.iconBase + 'noun_19460_green.svg'); // noun_272948.svg + + star.setAttribute('style', iconStyle + 'opacity: 50%;'); + star.setAttribute('title', 'Add another tool to the meeting'); + + var selectNewTool = function selectNewTool(_event) { + visible = !visible; + star.setAttribute('style', iconStyle + (visible ? 'background-color: yellow;' : '')); + styleTheIcons(visible ? '' : 'display: none;'); + }; + + var loginOutButton; + UI.authn.checkUser().then(function (webId) { + if (webId) { + me = webId; + star.addEventListener('click', selectNewTool); + star.setAttribute('style', iconStyle); + return; + } + + loginOutButton = UI.authn.loginStatusBox(dom, function (webIdUri) { + if (webIdUri) { + me = kb.sym(webIdUri); + parameterCell.removeChild(loginOutButton); // loginOutButton.setAttribute('',iconStyle) // make it match the icons + + star.addEventListener('click', selectNewTool); + star.setAttribute('style', iconStyle); + } else { + console.log('(Logged out)'); + me = null; + } + }); + loginOutButton.setAttribute('style', 'margin: 0.5em 1em;'); + parameterCell.appendChild(loginOutButton); + }); + var iconArray = []; + + for (var i = 0; i < toolIcons.length; i++) { + var foo = function foo() { + var toolObject = toolIcons[i]; + var icon = iconCell.appendChild(dom.createElement('img')); + icon.setAttribute('src', UI.icons.iconBase + toolObject.icon); + icon.setAttribute('style', iconStyle + 'display: none;'); + iconArray.push(icon); + icon.tool = toolObject; + var maker = toolObject.maker; + + if (!toolObject.disabled) { + icon.addEventListener('click', function (_event) { + selectTool(icon); + maker(toolObject); + }); + } + }; + + foo(); + } + + var styleTheIcons = function styleTheIcons(style) { + for (var i = 0; i < iconArray.length; i++) { + var st = iconStyle + style; + + if (toolIcons[i].disabled) { + st += 'opacity: 0.3;'; + } + + iconArray[i].setAttribute('style', st); // eg 'background-color: #ccc;' + } + }; + + var resetTools = function resetTools() { + styleTheIcons('display: none;'); + star.setAttribute('style', iconStyle); + }; + + var selectTool = function selectTool(icon) { + styleTheIcons('display: none;'); // 'background-color: #ccc;' + + icon.setAttribute('style', iconStyle + 'background-color: yellow;'); + }; // ////////////////////////////// + + + var renderTab = function renderTab(div, item) { + if (kb.holds(item, ns.rdf('type'), ns.meeting('Tool'))) { + var target = kb.any(item, ns.meeting('target')); + var label = kb.any(item, ns.rdfs('label')); + label = label ? label.value : UI.utils.label(target); + var s = div.appendChild(dom.createElement('div')); + s.textContent = label; + s.setAttribute('style', 'margin-left: 0.7em'); + var icon = kb.any(item, ns.meeting('icon')); + + if (icon) { + // Make sure the icon is cleanly on the left of the label + var table = div.appendChild(dom.createElement('table')); + var tr = table.appendChild(dom.createElement('tr')); + var left = tr.appendChild(dom.createElement('td')); + var right = tr.appendChild(dom.createElement('td')); // var img = div.appendChild(dom.createElement('img')) + + var img = left.appendChild(dom.createElement('img')); + img.setAttribute('src', icon.uri); // img.setAttribute('style', 'max-width: 1.5em; max-height: 1.5em;') // @@ SVG shrinks to 0 + + img.setAttribute('style', 'width: 1.5em; height: 1.5em;'); // @ + + img.setAttribute('title', label); + right.appendChild(s); + } else { + div.appendChild(s); + } + } else { + div.textContent = UI.utils.label(item); + } + }; + + var tipDiv = function tipDiv(text) { + var d = dom.createElement('div'); + var p = d.appendChild(dom.createElement('p')); + p.setAttribute('style', 'margin: 0em; padding:3em; color: #888;'); + p.textContent = 'Tip: ' + text; + return d; + }; + + var renderTabSettings = function renderTabSettings(containerDiv, subject) { + containerDiv.innerHTML = ''; + containerDiv.style += 'border-color: #eed;'; + containerDiv.appendChild(dom.createElement('h3')).textContent = 'Adjust this tab'; + + if (kb.holds(subject, ns.rdf('type'), ns.meeting('Tool'))) { + var form = $rdf.sym('https://solid.github.io/solid-panes/meeting/meetingDetailsForm.ttl#settings'); + UI.widgets.appendForm(document, containerDiv, {}, subject, form, meeting.doc(), complainIfBad); + var delButton = UI.widgets.deleteButtonWithCheck(dom, containerDiv, 'tab', function () { + var toolList = kb.the(meeting, ns.meeting('toolList')); + + for (var i = 0; i < toolList.elements.length; i++) { + if (toolList.elements[i].sameTerm(subject)) { + toolList.elements.splice(i, 1); + break; + } + } + + var target = kb.any(subject, ns.meeting('target')); + var ds = kb.statementsMatching(subject).concat(kb.statementsMatching(undefined, undefined, subject)).concat(kb.statementsMatching(meeting, undefined, target)); + kb.remove(ds); // Remove all links to and from the tab node + + saveBackMeetingDoc(); + }); + delButton.setAttribute('style', 'width: 1.5em; height: 1.5em;'); // delButton.setAttribute('class', '') + // delButton.setAttribute('style', 'height: 2em; width: 2em; margin: 1em; border-radius: 0.5em; padding: 1em; font-size: 120%; background-color: red; color: white;') + // delButton.textContent = 'Delete this tab' + } else { + containerDiv.appendChild(dom.createElement('h4')).textContent = '(No adjustments available)'; + } + }; + + var renderMain = function renderMain(containerDiv, subject) { + var pane = null; + var table; + var selectedGroup = null; + containerDiv.innerHTML = ''; + + var complainIfBad = function complainIfBad(ok, message) { + if (!ok) { + containerDiv.textContent = '' + message; + } + }; + + var showIframe = function showIframe(target) { + var iframe = containerDiv.appendChild(dom.createElement('iframe')); // iframe.setAttribute('sandbox', '') // All restrictions + + iframe.setAttribute('src', target.uri); // See https://stackoverflow.com/questions/325273/make-iframe-to-fit-100-of-containers-remaining-height + // Set the container position (sic) so it becaomes a 100% reference for the size of the iframe height 100% + + /* For now at least , leave the container style as set by the tab system. 20200115b + containerDiv.setAttribute( + 'style', + 'position: relative; top: 0px; left:0px; right:0px; resize: both; overflow:scroll; min-width: 30em; min-height: 30em;' + ) + */ + // iframe.setAttribute('style', 'height: 350px; border: 0; margin: 0; padding: 0; resize:both; overflow:scroll; width: 100%;') + // iframe.setAttribute('style', 'border: none; margin: 0; padding: 0; height: 100%; width: 100%; resize: both; overflow:scroll;') + + iframe.setAttribute('style', 'border: none; margin: 0; padding: 0; height: 100%; width: 100%;'); // Following https://dev.chromium.org/Home/chromium-security/deprecating-permissions-in-cross-origin-iframes : + + iframe.setAttribute('allow', 'microphone camera'); // Allow iframe to request camera and mic + // containerDiv.style.resize = 'none' // Remove scroll bars on outer div - don't seem to work so well + + iframe.setAttribute('name', 'disable-x-frame-options'); // For electron: see https://github.com/electron/electron/pull/573 + + containerDiv.style.padding = 0; + }; + + var renderPeoplePicker = function renderPeoplePicker() { + var context = { + div: containerDiv, + dom: dom + }; + containerDiv.appendChild(dom.createElement('h4')).textContent = 'Meeting Participants'; + + var groupPickedCb = function groupPickedCb(group) { + var toIns = [$rdf.st(meeting, ns.meeting('particpantGroup'), group, meeting.doc())]; + kb.updater.update([], toIns, function (uri, ok, message) { + if (ok) { + selectedGroup = group; + } else { + complain('Cant save participants group: ' + message); + } + }); + }; + + selectedGroup = kb.any(meeting, ns.meeting('particpantGroup')); + UI.authn.loadTypeIndexes(context).then(function () { + // Assumes that the type index has an entry for addressbook + var options = { + defaultNewGroupName: 'Meeting Participants', + selectedGroup: selectedGroup + }; + var picker = new UI.widgets.PeoplePicker(context.div, context.index["private"][0], groupPickedCb, options); + picker.render(); + }); + }; + + var renderDetails = function renderDetails() { + containerDiv.appendChild(dom.createElement('h3')).textContent = 'Details of meeting'; + var form = $rdf.sym('https://solid.github.io/solid-panes/meeting/meetingDetailsForm.ttl#main'); + UI.widgets.appendForm(document, containerDiv, {}, meeting, form, meeting.doc(), complainIfBad); + containerDiv.appendChild(tipDiv('Drag URL-bar icons of web pages into the tab bar on the left to add new meeting materials.')); + me = UI.authn.currentUser(); + + if (me) { + kb.add(meeting, ns.dc('author'), me, meetingDoc); // @@ should nly be on initial creation? + } + + var context = { + noun: 'meeting', + me: me, + statusArea: containerDiv, + div: containerDiv, + dom: dom + }; + UI.authn.registrationControl(context, meeting, ns.meeting('Meeting')).then(function (_context) { + console.log('Registration control finsished.'); + }); + var options = {}; + UI.pad.manageParticipation(dom, containerDiv, meetingDoc, meeting, me, options); // "Make a new meeting" button + + var imageStyle = 'height: 2em; width: 2em; margin:0.5em;'; + var detailsBottom = containerDiv.appendChild(dom.createElement('div')); + var spawn = detailsBottom.appendChild(dom.createElement('img')); + spawn.setAttribute('src', UI.icons.iconBase + 'noun_145978.svg'); + spawn.setAttribute('title', 'Make a fresh new meeting'); + spawn.addEventListener('click', makeNewMeeting); + spawn.setAttribute('style', imageStyle); // "Fork me on Github" button + + var forka = detailsBottom.appendChild(dom.createElement('a')); + forka.setAttribute('href', 'https://github.com/solid/solid-panes'); // @@ Move when code moves + + forka.setAttribute('target', '_blank'); + var fork = forka.appendChild(dom.createElement('img')); + fork.setAttribute('src', UI.icons.iconBase + 'noun_368567.svg'); + fork.setAttribute('title', 'Fork me on github'); + fork.setAttribute('style', imageStyle + 'opacity: 50%;'); + }; + + if (kb.holds(subject, ns.rdf('type'), ns.meeting('Tool'))) { + var target = kb.any(subject, ns.meeting('target')); + + if (target.sameTerm(meeting) && !kb.any(subject, ns.meeting('view'))) { + // self reference? force details form + renderDetails(); // Legacy meeting instances + } else { + var view = kb.any(subject, ns.meeting('view')); + view = view ? view.value : null; + + if (view === 'details') { + renderDetails(); + } else if (view === 'peoplePicker') { + renderPeoplePicker(); + } else if (view === 'iframe') { + showIframe(target); + } else { + pane = view ? dataBrowserContext.session.paneRegistry.byName(view) : null; + table = containerDiv.appendChild(dom.createElement('table')); + table.style.width = '100%'; + dataBrowserContext.getOutliner(dom).GotoSubject(target, true, pane, false, undefined, table); + } + } + } else if (subject.sameTerm(meeting)) { + // self reference? force details form + renderDetails(); + } else if (subject.sameTerm(subject.doc()) && !kb.holds(subject, UI.ns.rdf('type'), UI.ns.meeting('Chat')) && !kb.holds(subject, UI.ns.rdf('type'), UI.ns.meeting('PaneView'))) {} else { + table = containerDiv.appendChild(dom.createElement('table')); + dataBrowserContext.getOutliner(dom).GotoSubject(subject, true, undefined, false, undefined, table); + } + }; + + var options = { + dom: dom + }; + options.predicate = ns.meeting('toolList'); + options.subject = subject; + options.ordered = true; + options.orientation = 1; // tabs on LHS + + options.renderMain = renderMain; + options.renderTab = renderTab; + options.renderTabSettings = renderTabSettings; + options.backgroundColor = kb.anyValue(subject, ns.ui('backgroundColor')) || '#ddddcc'; + var tabs = mainTR.appendChild(UI.tabs.tabWidget(options)); + UI.aclControl.preventBrowserDropEvents(dom); + UI.widgets.makeDropTarget(tabs.tabContainer, droppedURIHandler, droppedFileHandler); + UI.widgets.makeDropTarget(iconCell, droppedURIHandler, droppedFileHandler); + return div; + } +}; // ends +//# sourceMappingURL=meetingPane.js.map + +/***/ }), + +/***/ "./node_modules/mime-db/db.json": +/*!**************************************!*\ + !*** ./node_modules/mime-db/db.json ***! + \**************************************/ +/*! exports provided: application/1d-interleaved-parityfec, application/3gpdash-qoe-report+xml, application/3gpp-ims+xml, application/a2l, application/activemessage, application/activity+json, application/alto-costmap+json, application/alto-costmapfilter+json, application/alto-directory+json, application/alto-endpointcost+json, application/alto-endpointcostparams+json, application/alto-endpointprop+json, application/alto-endpointpropparams+json, application/alto-error+json, application/alto-networkmap+json, application/alto-networkmapfilter+json, application/alto-updatestreamcontrol+json, application/alto-updatestreamparams+json, application/aml, application/andrew-inset, application/applefile, application/applixware, application/atf, application/atfx, application/atom+xml, application/atomcat+xml, application/atomdeleted+xml, application/atomicmail, application/atomsvc+xml, application/atsc-dwd+xml, application/atsc-dynamic-event-message, application/atsc-held+xml, application/atsc-rdt+json, application/atsc-rsat+xml, application/atxml, application/auth-policy+xml, application/bacnet-xdd+zip, application/batch-smtp, application/bdoc, application/beep+xml, application/calendar+json, application/calendar+xml, application/call-completion, application/cals-1840, application/cap+xml, application/cbor, application/cbor-seq, application/cccex, application/ccmp+xml, application/ccxml+xml, application/cdfx+xml, application/cdmi-capability, application/cdmi-container, application/cdmi-domain, application/cdmi-object, application/cdmi-queue, application/cdni, application/cea, application/cea-2018+xml, application/cellml+xml, application/cfw, application/clue+xml, application/clue_info+xml, application/cms, application/cnrp+xml, application/coap-group+json, application/coap-payload, application/commonground, application/conference-info+xml, application/cose, application/cose-key, application/cose-key-set, application/cpl+xml, application/csrattrs, application/csta+xml, application/cstadata+xml, application/csvm+json, application/cu-seeme, application/cwt, application/cybercash, application/dart, application/dash+xml, application/dashdelta, application/davmount+xml, application/dca-rft, application/dcd, application/dec-dx, application/dialog-info+xml, application/dicom, application/dicom+json, application/dicom+xml, application/dii, application/dit, application/dns, application/dns+json, application/dns-message, application/docbook+xml, application/dots+cbor, application/dskpp+xml, application/dssc+der, application/dssc+xml, application/dvcs, application/ecmascript, application/edi-consent, application/edi-x12, application/edifact, application/efi, application/emergencycalldata.comment+xml, application/emergencycalldata.control+xml, application/emergencycalldata.deviceinfo+xml, application/emergencycalldata.ecall.msd, application/emergencycalldata.providerinfo+xml, application/emergencycalldata.serviceinfo+xml, application/emergencycalldata.subscriberinfo+xml, application/emergencycalldata.veds+xml, application/emma+xml, application/emotionml+xml, application/encaprtp, application/epp+xml, application/epub+zip, application/eshop, application/exi, application/expect-ct-report+json, application/fastinfoset, application/fastsoap, application/fdt+xml, application/fhir+json, application/fhir+xml, application/fido.trusted-apps+json, application/fits, application/flexfec, application/font-sfnt, application/font-tdpfr, application/font-woff, application/framework-attributes+xml, application/geo+json, application/geo+json-seq, application/geopackage+sqlite3, application/geoxacml+xml, application/gltf-buffer, application/gml+xml, application/gpx+xml, application/gxf, application/gzip, application/h224, application/held+xml, application/hjson, application/http, application/hyperstudio, application/ibe-key-request+xml, application/ibe-pkg-reply+xml, application/ibe-pp-data, application/iges, application/im-iscomposing+xml, application/index, application/index.cmd, application/index.obj, application/index.response, application/index.vnd, application/inkml+xml, application/iotp, application/ipfix, application/ipp, application/isup, application/its+xml, application/java-archive, application/java-serialized-object, application/java-vm, application/javascript, application/jf2feed+json, application/jose, application/jose+json, application/jrd+json, application/json, application/json-patch+json, application/json-seq, application/json5, application/jsonml+json, application/jwk+json, application/jwk-set+json, application/jwt, application/kpml-request+xml, application/kpml-response+xml, application/ld+json, application/lgr+xml, application/link-format, application/load-control+xml, application/lost+xml, application/lostsync+xml, application/lpf+zip, application/lxf, application/mac-binhex40, application/mac-compactpro, application/macwriteii, application/mads+xml, application/manifest+json, application/marc, application/marcxml+xml, application/mathematica, application/mathml+xml, application/mathml-content+xml, application/mathml-presentation+xml, application/mbms-associated-procedure-description+xml, application/mbms-deregister+xml, application/mbms-envelope+xml, application/mbms-msk+xml, application/mbms-msk-response+xml, application/mbms-protection-description+xml, application/mbms-reception-report+xml, application/mbms-register+xml, application/mbms-register-response+xml, application/mbms-schedule+xml, application/mbms-user-service-description+xml, application/mbox, application/media-policy-dataset+xml, application/media_control+xml, application/mediaservercontrol+xml, application/merge-patch+json, application/metalink+xml, application/metalink4+xml, application/mets+xml, application/mf4, application/mikey, application/mipc, application/mmt-aei+xml, application/mmt-usd+xml, application/mods+xml, application/moss-keys, application/moss-signature, application/mosskey-data, application/mosskey-request, application/mp21, application/mp4, application/mpeg4-generic, application/mpeg4-iod, application/mpeg4-iod-xmt, application/mrb-consumer+xml, application/mrb-publish+xml, application/msc-ivr+xml, application/msc-mixer+xml, application/msword, application/mud+json, application/multipart-core, application/mxf, application/n-quads, application/n-triples, application/nasdata, application/news-checkgroups, application/news-groupinfo, application/news-transmission, application/nlsml+xml, application/node, application/nss, application/ocsp-request, application/ocsp-response, application/octet-stream, application/oda, application/odm+xml, application/odx, application/oebps-package+xml, application/ogg, application/omdoc+xml, application/onenote, application/oscore, application/oxps, application/p2p-overlay+xml, application/parityfec, application/passport, application/patch-ops-error+xml, application/pdf, application/pdx, application/pem-certificate-chain, application/pgp-encrypted, application/pgp-keys, application/pgp-signature, application/pics-rules, application/pidf+xml, application/pidf-diff+xml, application/pkcs10, application/pkcs12, application/pkcs7-mime, application/pkcs7-signature, application/pkcs8, application/pkcs8-encrypted, application/pkix-attr-cert, application/pkix-cert, application/pkix-crl, application/pkix-pkipath, application/pkixcmp, application/pls+xml, application/poc-settings+xml, application/postscript, application/ppsp-tracker+json, application/problem+json, application/problem+xml, application/provenance+xml, application/prs.alvestrand.titrax-sheet, application/prs.cww, application/prs.hpub+zip, application/prs.nprend, application/prs.plucker, application/prs.rdf-xml-crypt, application/prs.xsf+xml, application/pskc+xml, application/pvd+json, application/qsig, application/raml+yaml, application/raptorfec, application/rdap+json, application/rdf+xml, application/reginfo+xml, application/relax-ng-compact-syntax, application/remote-printing, application/reputon+json, application/resource-lists+xml, application/resource-lists-diff+xml, application/rfc+xml, application/riscos, application/rlmi+xml, application/rls-services+xml, application/route-apd+xml, application/route-s-tsid+xml, application/route-usd+xml, application/rpki-ghostbusters, application/rpki-manifest, application/rpki-publication, application/rpki-roa, application/rpki-updown, application/rsd+xml, application/rss+xml, application/rtf, application/rtploopback, application/rtx, application/samlassertion+xml, application/samlmetadata+xml, application/sbe, application/sbml+xml, application/scaip+xml, application/scim+json, application/scvp-cv-request, application/scvp-cv-response, application/scvp-vp-request, application/scvp-vp-response, application/sdp, application/secevent+jwt, application/senml+cbor, application/senml+json, application/senml+xml, application/senml-etch+cbor, application/senml-etch+json, application/senml-exi, application/sensml+cbor, application/sensml+json, application/sensml+xml, application/sensml-exi, application/sep+xml, application/sep-exi, application/session-info, application/set-payment, application/set-payment-initiation, application/set-registration, application/set-registration-initiation, application/sgml, application/sgml-open-catalog, application/shf+xml, application/sieve, application/simple-filter+xml, application/simple-message-summary, application/simplesymbolcontainer, application/sipc, application/slate, application/smil, application/smil+xml, application/smpte336m, application/soap+fastinfoset, application/soap+xml, application/sparql-query, application/sparql-results+xml, application/spirits-event+xml, application/sql, application/srgs, application/srgs+xml, application/sru+xml, application/ssdl+xml, application/ssml+xml, application/stix+json, application/swid+xml, application/tamp-apex-update, application/tamp-apex-update-confirm, application/tamp-community-update, application/tamp-community-update-confirm, application/tamp-error, application/tamp-sequence-adjust, application/tamp-sequence-adjust-confirm, application/tamp-status-query, application/tamp-status-response, application/tamp-update, application/tamp-update-confirm, application/tar, application/taxii+json, application/td+json, application/tei+xml, application/tetra_isi, application/thraud+xml, application/timestamp-query, application/timestamp-reply, application/timestamped-data, application/tlsrpt+gzip, application/tlsrpt+json, application/tnauthlist, application/toml, application/trickle-ice-sdpfrag, application/trig, application/ttml+xml, application/tve-trigger, application/tzif, application/tzif-leap, application/ulpfec, application/urc-grpsheet+xml, application/urc-ressheet+xml, application/urc-targetdesc+xml, application/urc-uisocketdesc+xml, application/vcard+json, application/vcard+xml, application/vemmi, application/vividence.scriptfile, application/vnd.1000minds.decision-model+xml, application/vnd.3gpp-prose+xml, application/vnd.3gpp-prose-pc3ch+xml, application/vnd.3gpp-v2x-local-service-information, application/vnd.3gpp.access-transfer-events+xml, application/vnd.3gpp.bsf+xml, application/vnd.3gpp.gmop+xml, application/vnd.3gpp.mc-signalling-ear, application/vnd.3gpp.mcdata-affiliation-command+xml, application/vnd.3gpp.mcdata-info+xml, application/vnd.3gpp.mcdata-payload, application/vnd.3gpp.mcdata-service-config+xml, application/vnd.3gpp.mcdata-signalling, application/vnd.3gpp.mcdata-ue-config+xml, application/vnd.3gpp.mcdata-user-profile+xml, application/vnd.3gpp.mcptt-affiliation-command+xml, application/vnd.3gpp.mcptt-floor-request+xml, application/vnd.3gpp.mcptt-info+xml, application/vnd.3gpp.mcptt-location-info+xml, application/vnd.3gpp.mcptt-mbms-usage-info+xml, application/vnd.3gpp.mcptt-service-config+xml, application/vnd.3gpp.mcptt-signed+xml, application/vnd.3gpp.mcptt-ue-config+xml, application/vnd.3gpp.mcptt-ue-init-config+xml, application/vnd.3gpp.mcptt-user-profile+xml, application/vnd.3gpp.mcvideo-affiliation-command+xml, application/vnd.3gpp.mcvideo-affiliation-info+xml, application/vnd.3gpp.mcvideo-info+xml, application/vnd.3gpp.mcvideo-location-info+xml, application/vnd.3gpp.mcvideo-mbms-usage-info+xml, application/vnd.3gpp.mcvideo-service-config+xml, application/vnd.3gpp.mcvideo-transmission-request+xml, application/vnd.3gpp.mcvideo-ue-config+xml, application/vnd.3gpp.mcvideo-user-profile+xml, application/vnd.3gpp.mid-call+xml, application/vnd.3gpp.pic-bw-large, application/vnd.3gpp.pic-bw-small, application/vnd.3gpp.pic-bw-var, application/vnd.3gpp.sms, application/vnd.3gpp.sms+xml, application/vnd.3gpp.srvcc-ext+xml, application/vnd.3gpp.srvcc-info+xml, application/vnd.3gpp.state-and-event-info+xml, application/vnd.3gpp.ussd+xml, application/vnd.3gpp2.bcmcsinfo+xml, application/vnd.3gpp2.sms, application/vnd.3gpp2.tcap, application/vnd.3lightssoftware.imagescal, application/vnd.3m.post-it-notes, application/vnd.accpac.simply.aso, application/vnd.accpac.simply.imp, application/vnd.acucobol, application/vnd.acucorp, application/vnd.adobe.air-application-installer-package+zip, application/vnd.adobe.flash.movie, application/vnd.adobe.formscentral.fcdt, application/vnd.adobe.fxp, application/vnd.adobe.partial-upload, application/vnd.adobe.xdp+xml, application/vnd.adobe.xfdf, application/vnd.aether.imp, application/vnd.afpc.afplinedata, application/vnd.afpc.afplinedata-pagedef, application/vnd.afpc.foca-charset, application/vnd.afpc.foca-codedfont, application/vnd.afpc.foca-codepage, application/vnd.afpc.modca, application/vnd.afpc.modca-formdef, application/vnd.afpc.modca-mediummap, application/vnd.afpc.modca-objectcontainer, application/vnd.afpc.modca-overlay, application/vnd.afpc.modca-pagesegment, application/vnd.ah-barcode, application/vnd.ahead.space, application/vnd.airzip.filesecure.azf, application/vnd.airzip.filesecure.azs, application/vnd.amadeus+json, application/vnd.amazon.ebook, application/vnd.amazon.mobi8-ebook, application/vnd.americandynamics.acc, application/vnd.amiga.ami, application/vnd.amundsen.maze+xml, application/vnd.android.ota, application/vnd.android.package-archive, application/vnd.anki, application/vnd.anser-web-certificate-issue-initiation, application/vnd.anser-web-funds-transfer-initiation, application/vnd.antix.game-component, application/vnd.apache.thrift.binary, application/vnd.apache.thrift.compact, application/vnd.apache.thrift.json, application/vnd.api+json, application/vnd.aplextor.warrp+json, application/vnd.apothekende.reservation+json, application/vnd.apple.installer+xml, application/vnd.apple.keynote, application/vnd.apple.mpegurl, application/vnd.apple.numbers, application/vnd.apple.pages, application/vnd.apple.pkpass, application/vnd.arastra.swi, application/vnd.aristanetworks.swi, application/vnd.artisan+json, application/vnd.artsquare, application/vnd.astraea-software.iota, application/vnd.audiograph, application/vnd.autopackage, application/vnd.avalon+json, application/vnd.avistar+xml, application/vnd.balsamiq.bmml+xml, application/vnd.balsamiq.bmpr, application/vnd.banana-accounting, application/vnd.bbf.usp.error, application/vnd.bbf.usp.msg, application/vnd.bbf.usp.msg+json, application/vnd.bekitzur-stech+json, application/vnd.bint.med-content, application/vnd.biopax.rdf+xml, application/vnd.blink-idb-value-wrapper, application/vnd.blueice.multipass, application/vnd.bluetooth.ep.oob, application/vnd.bluetooth.le.oob, application/vnd.bmi, application/vnd.bpf, application/vnd.bpf3, application/vnd.businessobjects, application/vnd.byu.uapi+json, application/vnd.cab-jscript, application/vnd.canon-cpdl, application/vnd.canon-lips, application/vnd.capasystems-pg+json, application/vnd.cendio.thinlinc.clientconf, application/vnd.century-systems.tcp_stream, application/vnd.chemdraw+xml, application/vnd.chess-pgn, application/vnd.chipnuts.karaoke-mmd, application/vnd.ciedi, application/vnd.cinderella, application/vnd.cirpack.isdn-ext, application/vnd.citationstyles.style+xml, application/vnd.claymore, application/vnd.cloanto.rp9, application/vnd.clonk.c4group, application/vnd.cluetrust.cartomobile-config, application/vnd.cluetrust.cartomobile-config-pkg, application/vnd.coffeescript, application/vnd.collabio.xodocuments.document, application/vnd.collabio.xodocuments.document-template, application/vnd.collabio.xodocuments.presentation, application/vnd.collabio.xodocuments.presentation-template, application/vnd.collabio.xodocuments.spreadsheet, application/vnd.collabio.xodocuments.spreadsheet-template, application/vnd.collection+json, application/vnd.collection.doc+json, application/vnd.collection.next+json, application/vnd.comicbook+zip, application/vnd.comicbook-rar, application/vnd.commerce-battelle, application/vnd.commonspace, application/vnd.contact.cmsg, application/vnd.coreos.ignition+json, application/vnd.cosmocaller, application/vnd.crick.clicker, application/vnd.crick.clicker.keyboard, application/vnd.crick.clicker.palette, application/vnd.crick.clicker.template, application/vnd.crick.clicker.wordbank, application/vnd.criticaltools.wbs+xml, application/vnd.cryptii.pipe+json, application/vnd.crypto-shade-file, application/vnd.ctc-posml, application/vnd.ctct.ws+xml, application/vnd.cups-pdf, application/vnd.cups-postscript, application/vnd.cups-ppd, application/vnd.cups-raster, application/vnd.cups-raw, application/vnd.curl, application/vnd.curl.car, application/vnd.curl.pcurl, application/vnd.cyan.dean.root+xml, application/vnd.cybank, application/vnd.d2l.coursepackage1p0+zip, application/vnd.dart, application/vnd.data-vision.rdz, application/vnd.datapackage+json, application/vnd.dataresource+json, application/vnd.dbf, application/vnd.debian.binary-package, application/vnd.dece.data, application/vnd.dece.ttml+xml, application/vnd.dece.unspecified, application/vnd.dece.zip, application/vnd.denovo.fcselayout-link, application/vnd.desmume.movie, application/vnd.dir-bi.plate-dl-nosuffix, application/vnd.dm.delegation+xml, application/vnd.dna, application/vnd.document+json, application/vnd.dolby.mlp, application/vnd.dolby.mobile.1, application/vnd.dolby.mobile.2, application/vnd.doremir.scorecloud-binary-document, application/vnd.dpgraph, application/vnd.dreamfactory, application/vnd.drive+json, application/vnd.ds-keypoint, application/vnd.dtg.local, application/vnd.dtg.local.flash, application/vnd.dtg.local.html, application/vnd.dvb.ait, application/vnd.dvb.dvbisl+xml, application/vnd.dvb.dvbj, application/vnd.dvb.esgcontainer, application/vnd.dvb.ipdcdftnotifaccess, application/vnd.dvb.ipdcesgaccess, application/vnd.dvb.ipdcesgaccess2, application/vnd.dvb.ipdcesgpdd, application/vnd.dvb.ipdcroaming, application/vnd.dvb.iptv.alfec-base, application/vnd.dvb.iptv.alfec-enhancement, application/vnd.dvb.notif-aggregate-root+xml, application/vnd.dvb.notif-container+xml, application/vnd.dvb.notif-generic+xml, application/vnd.dvb.notif-ia-msglist+xml, application/vnd.dvb.notif-ia-registration-request+xml, application/vnd.dvb.notif-ia-registration-response+xml, application/vnd.dvb.notif-init+xml, application/vnd.dvb.pfr, application/vnd.dvb.service, application/vnd.dxr, application/vnd.dynageo, application/vnd.dzr, application/vnd.easykaraoke.cdgdownload, application/vnd.ecdis-update, application/vnd.ecip.rlp, application/vnd.ecowin.chart, application/vnd.ecowin.filerequest, application/vnd.ecowin.fileupdate, application/vnd.ecowin.series, application/vnd.ecowin.seriesrequest, application/vnd.ecowin.seriesupdate, application/vnd.efi.img, application/vnd.efi.iso, application/vnd.emclient.accessrequest+xml, application/vnd.enliven, application/vnd.enphase.envoy, application/vnd.eprints.data+xml, application/vnd.epson.esf, application/vnd.epson.msf, application/vnd.epson.quickanime, application/vnd.epson.salt, application/vnd.epson.ssf, application/vnd.ericsson.quickcall, application/vnd.espass-espass+zip, application/vnd.eszigno3+xml, application/vnd.etsi.aoc+xml, application/vnd.etsi.asic-e+zip, application/vnd.etsi.asic-s+zip, application/vnd.etsi.cug+xml, application/vnd.etsi.iptvcommand+xml, application/vnd.etsi.iptvdiscovery+xml, application/vnd.etsi.iptvprofile+xml, application/vnd.etsi.iptvsad-bc+xml, application/vnd.etsi.iptvsad-cod+xml, application/vnd.etsi.iptvsad-npvr+xml, application/vnd.etsi.iptvservice+xml, application/vnd.etsi.iptvsync+xml, application/vnd.etsi.iptvueprofile+xml, application/vnd.etsi.mcid+xml, application/vnd.etsi.mheg5, application/vnd.etsi.overload-control-policy-dataset+xml, application/vnd.etsi.pstn+xml, application/vnd.etsi.sci+xml, application/vnd.etsi.simservs+xml, application/vnd.etsi.timestamp-token, application/vnd.etsi.tsl+xml, application/vnd.etsi.tsl.der, application/vnd.eudora.data, application/vnd.evolv.ecig.profile, application/vnd.evolv.ecig.settings, application/vnd.evolv.ecig.theme, application/vnd.exstream-empower+zip, application/vnd.exstream-package, application/vnd.ezpix-album, application/vnd.ezpix-package, application/vnd.f-secure.mobile, application/vnd.fastcopy-disk-image, application/vnd.fdf, application/vnd.fdsn.mseed, application/vnd.fdsn.seed, application/vnd.ffsns, application/vnd.ficlab.flb+zip, application/vnd.filmit.zfc, application/vnd.fints, application/vnd.firemonkeys.cloudcell, application/vnd.flographit, application/vnd.fluxtime.clip, application/vnd.font-fontforge-sfd, application/vnd.framemaker, application/vnd.frogans.fnc, application/vnd.frogans.ltf, application/vnd.fsc.weblaunch, application/vnd.fujitsu.oasys, application/vnd.fujitsu.oasys2, application/vnd.fujitsu.oasys3, application/vnd.fujitsu.oasysgp, application/vnd.fujitsu.oasysprs, application/vnd.fujixerox.art-ex, application/vnd.fujixerox.art4, application/vnd.fujixerox.ddd, application/vnd.fujixerox.docuworks, application/vnd.fujixerox.docuworks.binder, application/vnd.fujixerox.docuworks.container, application/vnd.fujixerox.hbpl, application/vnd.fut-misnet, application/vnd.futoin+cbor, application/vnd.futoin+json, application/vnd.fuzzysheet, application/vnd.genomatix.tuxedo, application/vnd.gentics.grd+json, application/vnd.geo+json, application/vnd.geocube+xml, application/vnd.geogebra.file, application/vnd.geogebra.tool, application/vnd.geometry-explorer, application/vnd.geonext, application/vnd.geoplan, application/vnd.geospace, application/vnd.gerber, application/vnd.globalplatform.card-content-mgt, application/vnd.globalplatform.card-content-mgt-response, application/vnd.gmx, application/vnd.google-apps.document, application/vnd.google-apps.presentation, application/vnd.google-apps.spreadsheet, application/vnd.google-earth.kml+xml, application/vnd.google-earth.kmz, application/vnd.gov.sk.e-form+xml, application/vnd.gov.sk.e-form+zip, application/vnd.gov.sk.xmldatacontainer+xml, application/vnd.grafeq, application/vnd.gridmp, application/vnd.groove-account, application/vnd.groove-help, application/vnd.groove-identity-message, application/vnd.groove-injector, application/vnd.groove-tool-message, application/vnd.groove-tool-template, application/vnd.groove-vcard, application/vnd.hal+json, application/vnd.hal+xml, application/vnd.handheld-entertainment+xml, application/vnd.hbci, application/vnd.hc+json, application/vnd.hcl-bireports, application/vnd.hdt, application/vnd.heroku+json, application/vnd.hhe.lesson-player, application/vnd.hp-hpgl, application/vnd.hp-hpid, application/vnd.hp-hps, application/vnd.hp-jlyt, application/vnd.hp-pcl, application/vnd.hp-pclxl, application/vnd.httphone, application/vnd.hydrostatix.sof-data, application/vnd.hyper+json, application/vnd.hyper-item+json, application/vnd.hyperdrive+json, application/vnd.hzn-3d-crossword, application/vnd.ibm.afplinedata, application/vnd.ibm.electronic-media, application/vnd.ibm.minipay, application/vnd.ibm.modcap, application/vnd.ibm.rights-management, application/vnd.ibm.secure-container, application/vnd.iccprofile, application/vnd.ieee.1905, application/vnd.igloader, application/vnd.imagemeter.folder+zip, application/vnd.imagemeter.image+zip, application/vnd.immervision-ivp, application/vnd.immervision-ivu, application/vnd.ims.imsccv1p1, application/vnd.ims.imsccv1p2, application/vnd.ims.imsccv1p3, application/vnd.ims.lis.v2.result+json, application/vnd.ims.lti.v2.toolconsumerprofile+json, application/vnd.ims.lti.v2.toolproxy+json, application/vnd.ims.lti.v2.toolproxy.id+json, application/vnd.ims.lti.v2.toolsettings+json, application/vnd.ims.lti.v2.toolsettings.simple+json, application/vnd.informedcontrol.rms+xml, application/vnd.informix-visionary, application/vnd.infotech.project, application/vnd.infotech.project+xml, application/vnd.innopath.wamp.notification, application/vnd.insors.igm, application/vnd.intercon.formnet, application/vnd.intergeo, application/vnd.intertrust.digibox, application/vnd.intertrust.nncp, application/vnd.intu.qbo, application/vnd.intu.qfx, application/vnd.iptc.g2.catalogitem+xml, application/vnd.iptc.g2.conceptitem+xml, application/vnd.iptc.g2.knowledgeitem+xml, application/vnd.iptc.g2.newsitem+xml, application/vnd.iptc.g2.newsmessage+xml, application/vnd.iptc.g2.packageitem+xml, application/vnd.iptc.g2.planningitem+xml, application/vnd.ipunplugged.rcprofile, application/vnd.irepository.package+xml, application/vnd.is-xpr, application/vnd.isac.fcs, application/vnd.iso11783-10+zip, application/vnd.jam, application/vnd.japannet-directory-service, application/vnd.japannet-jpnstore-wakeup, application/vnd.japannet-payment-wakeup, application/vnd.japannet-registration, application/vnd.japannet-registration-wakeup, application/vnd.japannet-setstore-wakeup, application/vnd.japannet-verification, application/vnd.japannet-verification-wakeup, application/vnd.jcp.javame.midlet-rms, application/vnd.jisp, application/vnd.joost.joda-archive, application/vnd.jsk.isdn-ngn, application/vnd.kahootz, application/vnd.kde.karbon, application/vnd.kde.kchart, application/vnd.kde.kformula, application/vnd.kde.kivio, application/vnd.kde.kontour, application/vnd.kde.kpresenter, application/vnd.kde.kspread, application/vnd.kde.kword, application/vnd.kenameaapp, application/vnd.kidspiration, application/vnd.kinar, application/vnd.koan, application/vnd.kodak-descriptor, application/vnd.las, application/vnd.las.las+json, application/vnd.las.las+xml, application/vnd.laszip, application/vnd.leap+json, application/vnd.liberty-request+xml, application/vnd.llamagraphics.life-balance.desktop, application/vnd.llamagraphics.life-balance.exchange+xml, application/vnd.logipipe.circuit+zip, application/vnd.loom, application/vnd.lotus-1-2-3, application/vnd.lotus-approach, application/vnd.lotus-freelance, application/vnd.lotus-notes, application/vnd.lotus-organizer, application/vnd.lotus-screencam, application/vnd.lotus-wordpro, application/vnd.macports.portpkg, application/vnd.mapbox-vector-tile, application/vnd.marlin.drm.actiontoken+xml, application/vnd.marlin.drm.conftoken+xml, application/vnd.marlin.drm.license+xml, application/vnd.marlin.drm.mdcf, application/vnd.mason+json, application/vnd.maxmind.maxmind-db, application/vnd.mcd, application/vnd.medcalcdata, application/vnd.mediastation.cdkey, application/vnd.meridian-slingshot, application/vnd.mfer, application/vnd.mfmp, application/vnd.micro+json, application/vnd.micrografx.flo, application/vnd.micrografx.igx, application/vnd.microsoft.portable-executable, application/vnd.microsoft.windows.thumbnail-cache, application/vnd.miele+json, application/vnd.mif, application/vnd.minisoft-hp3000-save, application/vnd.mitsubishi.misty-guard.trustweb, application/vnd.mobius.daf, application/vnd.mobius.dis, application/vnd.mobius.mbk, application/vnd.mobius.mqy, application/vnd.mobius.msl, application/vnd.mobius.plc, application/vnd.mobius.txf, application/vnd.mophun.application, application/vnd.mophun.certificate, application/vnd.motorola.flexsuite, application/vnd.motorola.flexsuite.adsi, application/vnd.motorola.flexsuite.fis, application/vnd.motorola.flexsuite.gotap, application/vnd.motorola.flexsuite.kmr, application/vnd.motorola.flexsuite.ttc, application/vnd.motorola.flexsuite.wem, application/vnd.motorola.iprm, application/vnd.mozilla.xul+xml, application/vnd.ms-3mfdocument, application/vnd.ms-artgalry, application/vnd.ms-asf, application/vnd.ms-cab-compressed, application/vnd.ms-color.iccprofile, application/vnd.ms-excel, application/vnd.ms-excel.addin.macroenabled.12, application/vnd.ms-excel.sheet.binary.macroenabled.12, application/vnd.ms-excel.sheet.macroenabled.12, application/vnd.ms-excel.template.macroenabled.12, application/vnd.ms-fontobject, application/vnd.ms-htmlhelp, application/vnd.ms-ims, application/vnd.ms-lrm, application/vnd.ms-office.activex+xml, application/vnd.ms-officetheme, application/vnd.ms-opentype, application/vnd.ms-outlook, application/vnd.ms-package.obfuscated-opentype, application/vnd.ms-pki.seccat, application/vnd.ms-pki.stl, application/vnd.ms-playready.initiator+xml, application/vnd.ms-powerpoint, application/vnd.ms-powerpoint.addin.macroenabled.12, application/vnd.ms-powerpoint.presentation.macroenabled.12, application/vnd.ms-powerpoint.slide.macroenabled.12, application/vnd.ms-powerpoint.slideshow.macroenabled.12, application/vnd.ms-powerpoint.template.macroenabled.12, application/vnd.ms-printdevicecapabilities+xml, application/vnd.ms-printing.printticket+xml, application/vnd.ms-printschematicket+xml, application/vnd.ms-project, application/vnd.ms-tnef, application/vnd.ms-windows.devicepairing, application/vnd.ms-windows.nwprinting.oob, application/vnd.ms-windows.printerpairing, application/vnd.ms-windows.wsd.oob, application/vnd.ms-wmdrm.lic-chlg-req, application/vnd.ms-wmdrm.lic-resp, application/vnd.ms-wmdrm.meter-chlg-req, application/vnd.ms-wmdrm.meter-resp, application/vnd.ms-word.document.macroenabled.12, application/vnd.ms-word.template.macroenabled.12, application/vnd.ms-works, application/vnd.ms-wpl, application/vnd.ms-xpsdocument, application/vnd.msa-disk-image, application/vnd.mseq, application/vnd.msign, application/vnd.multiad.creator, application/vnd.multiad.creator.cif, application/vnd.music-niff, application/vnd.musician, application/vnd.muvee.style, application/vnd.mynfc, application/vnd.ncd.control, application/vnd.ncd.reference, application/vnd.nearst.inv+json, application/vnd.nervana, application/vnd.netfpx, application/vnd.neurolanguage.nlu, application/vnd.nimn, application/vnd.nintendo.nitro.rom, application/vnd.nintendo.snes.rom, application/vnd.nitf, application/vnd.noblenet-directory, application/vnd.noblenet-sealer, application/vnd.noblenet-web, application/vnd.nokia.catalogs, application/vnd.nokia.conml+wbxml, application/vnd.nokia.conml+xml, application/vnd.nokia.iptv.config+xml, application/vnd.nokia.isds-radio-presets, application/vnd.nokia.landmark+wbxml, application/vnd.nokia.landmark+xml, application/vnd.nokia.landmarkcollection+xml, application/vnd.nokia.n-gage.ac+xml, application/vnd.nokia.n-gage.data, application/vnd.nokia.n-gage.symbian.install, application/vnd.nokia.ncd, application/vnd.nokia.pcd+wbxml, application/vnd.nokia.pcd+xml, application/vnd.nokia.radio-preset, application/vnd.nokia.radio-presets, application/vnd.novadigm.edm, application/vnd.novadigm.edx, application/vnd.novadigm.ext, application/vnd.ntt-local.content-share, application/vnd.ntt-local.file-transfer, application/vnd.ntt-local.ogw_remote-access, application/vnd.ntt-local.sip-ta_remote, application/vnd.ntt-local.sip-ta_tcp_stream, application/vnd.oasis.opendocument.chart, application/vnd.oasis.opendocument.chart-template, application/vnd.oasis.opendocument.database, application/vnd.oasis.opendocument.formula, application/vnd.oasis.opendocument.formula-template, application/vnd.oasis.opendocument.graphics, application/vnd.oasis.opendocument.graphics-template, application/vnd.oasis.opendocument.image, application/vnd.oasis.opendocument.image-template, application/vnd.oasis.opendocument.presentation, application/vnd.oasis.opendocument.presentation-template, application/vnd.oasis.opendocument.spreadsheet, application/vnd.oasis.opendocument.spreadsheet-template, application/vnd.oasis.opendocument.text, application/vnd.oasis.opendocument.text-master, application/vnd.oasis.opendocument.text-template, application/vnd.oasis.opendocument.text-web, application/vnd.obn, application/vnd.ocf+cbor, application/vnd.oci.image.manifest.v1+json, application/vnd.oftn.l10n+json, application/vnd.oipf.contentaccessdownload+xml, application/vnd.oipf.contentaccessstreaming+xml, application/vnd.oipf.cspg-hexbinary, application/vnd.oipf.dae.svg+xml, application/vnd.oipf.dae.xhtml+xml, application/vnd.oipf.mippvcontrolmessage+xml, application/vnd.oipf.pae.gem, application/vnd.oipf.spdiscovery+xml, application/vnd.oipf.spdlist+xml, application/vnd.oipf.ueprofile+xml, application/vnd.oipf.userprofile+xml, application/vnd.olpc-sugar, application/vnd.oma-scws-config, application/vnd.oma-scws-http-request, application/vnd.oma-scws-http-response, application/vnd.oma.bcast.associated-procedure-parameter+xml, application/vnd.oma.bcast.drm-trigger+xml, application/vnd.oma.bcast.imd+xml, application/vnd.oma.bcast.ltkm, application/vnd.oma.bcast.notification+xml, application/vnd.oma.bcast.provisioningtrigger, application/vnd.oma.bcast.sgboot, application/vnd.oma.bcast.sgdd+xml, application/vnd.oma.bcast.sgdu, application/vnd.oma.bcast.simple-symbol-container, application/vnd.oma.bcast.smartcard-trigger+xml, application/vnd.oma.bcast.sprov+xml, application/vnd.oma.bcast.stkm, application/vnd.oma.cab-address-book+xml, application/vnd.oma.cab-feature-handler+xml, application/vnd.oma.cab-pcc+xml, application/vnd.oma.cab-subs-invite+xml, application/vnd.oma.cab-user-prefs+xml, application/vnd.oma.dcd, application/vnd.oma.dcdc, application/vnd.oma.dd2+xml, application/vnd.oma.drm.risd+xml, application/vnd.oma.group-usage-list+xml, application/vnd.oma.lwm2m+json, application/vnd.oma.lwm2m+tlv, application/vnd.oma.pal+xml, application/vnd.oma.poc.detailed-progress-report+xml, application/vnd.oma.poc.final-report+xml, application/vnd.oma.poc.groups+xml, application/vnd.oma.poc.invocation-descriptor+xml, application/vnd.oma.poc.optimized-progress-report+xml, application/vnd.oma.push, application/vnd.oma.scidm.messages+xml, application/vnd.oma.xcap-directory+xml, application/vnd.omads-email+xml, application/vnd.omads-file+xml, application/vnd.omads-folder+xml, application/vnd.omaloc-supl-init, application/vnd.onepager, application/vnd.onepagertamp, application/vnd.onepagertamx, application/vnd.onepagertat, application/vnd.onepagertatp, application/vnd.onepagertatx, application/vnd.openblox.game+xml, application/vnd.openblox.game-binary, application/vnd.openeye.oeb, application/vnd.openofficeorg.extension, application/vnd.openstreetmap.data+xml, application/vnd.openxmlformats-officedocument.custom-properties+xml, application/vnd.openxmlformats-officedocument.customxmlproperties+xml, application/vnd.openxmlformats-officedocument.drawing+xml, application/vnd.openxmlformats-officedocument.drawingml.chart+xml, application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml, application/vnd.openxmlformats-officedocument.drawingml.diagramcolors+xml, application/vnd.openxmlformats-officedocument.drawingml.diagramdata+xml, application/vnd.openxmlformats-officedocument.drawingml.diagramlayout+xml, application/vnd.openxmlformats-officedocument.drawingml.diagramstyle+xml, application/vnd.openxmlformats-officedocument.extended-properties+xml, application/vnd.openxmlformats-officedocument.presentationml.commentauthors+xml, application/vnd.openxmlformats-officedocument.presentationml.comments+xml, application/vnd.openxmlformats-officedocument.presentationml.handoutmaster+xml, application/vnd.openxmlformats-officedocument.presentationml.notesmaster+xml, application/vnd.openxmlformats-officedocument.presentationml.notesslide+xml, application/vnd.openxmlformats-officedocument.presentationml.presentation, application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml, application/vnd.openxmlformats-officedocument.presentationml.presprops+xml, application/vnd.openxmlformats-officedocument.presentationml.slide, application/vnd.openxmlformats-officedocument.presentationml.slide+xml, application/vnd.openxmlformats-officedocument.presentationml.slidelayout+xml, application/vnd.openxmlformats-officedocument.presentationml.slidemaster+xml, application/vnd.openxmlformats-officedocument.presentationml.slideshow, application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml, application/vnd.openxmlformats-officedocument.presentationml.slideupdateinfo+xml, application/vnd.openxmlformats-officedocument.presentationml.tablestyles+xml, application/vnd.openxmlformats-officedocument.presentationml.tags+xml, application/vnd.openxmlformats-officedocument.presentationml.template, application/vnd.openxmlformats-officedocument.presentationml.template.main+xml, application/vnd.openxmlformats-officedocument.presentationml.viewprops+xml, application/vnd.openxmlformats-officedocument.spreadsheetml.calcchain+xml, application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml, application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml, application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml, application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml, application/vnd.openxmlformats-officedocument.spreadsheetml.externallink+xml, application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcachedefinition+xml, application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcacherecords+xml, application/vnd.openxmlformats-officedocument.spreadsheetml.pivottable+xml, application/vnd.openxmlformats-officedocument.spreadsheetml.querytable+xml, application/vnd.openxmlformats-officedocument.spreadsheetml.revisionheaders+xml, application/vnd.openxmlformats-officedocument.spreadsheetml.revisionlog+xml, application/vnd.openxmlformats-officedocument.spreadsheetml.sharedstrings+xml, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml, application/vnd.openxmlformats-officedocument.spreadsheetml.sheetmetadata+xml, application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml, application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml, application/vnd.openxmlformats-officedocument.spreadsheetml.tablesinglecells+xml, application/vnd.openxmlformats-officedocument.spreadsheetml.template, application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml, application/vnd.openxmlformats-officedocument.spreadsheetml.usernames+xml, application/vnd.openxmlformats-officedocument.spreadsheetml.volatiledependencies+xml, application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml, application/vnd.openxmlformats-officedocument.theme+xml, application/vnd.openxmlformats-officedocument.themeoverride+xml, application/vnd.openxmlformats-officedocument.vmldrawing, application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml, application/vnd.openxmlformats-officedocument.wordprocessingml.document, application/vnd.openxmlformats-officedocument.wordprocessingml.document.glossary+xml, application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml, application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml, application/vnd.openxmlformats-officedocument.wordprocessingml.fonttable+xml, application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml, application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml, application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml, application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml, application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml, application/vnd.openxmlformats-officedocument.wordprocessingml.template, application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml, application/vnd.openxmlformats-officedocument.wordprocessingml.websettings+xml, application/vnd.openxmlformats-package.core-properties+xml, application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml, application/vnd.openxmlformats-package.relationships+xml, application/vnd.oracle.resource+json, application/vnd.orange.indata, application/vnd.osa.netdeploy, application/vnd.osgeo.mapguide.package, application/vnd.osgi.bundle, application/vnd.osgi.dp, application/vnd.osgi.subsystem, application/vnd.otps.ct-kip+xml, application/vnd.oxli.countgraph, application/vnd.pagerduty+json, application/vnd.palm, application/vnd.panoply, application/vnd.paos.xml, application/vnd.patentdive, application/vnd.patientecommsdoc, application/vnd.pawaafile, application/vnd.pcos, application/vnd.pg.format, application/vnd.pg.osasli, application/vnd.piaccess.application-licence, application/vnd.picsel, application/vnd.pmi.widget, application/vnd.poc.group-advertisement+xml, application/vnd.pocketlearn, application/vnd.powerbuilder6, application/vnd.powerbuilder6-s, application/vnd.powerbuilder7, application/vnd.powerbuilder7-s, application/vnd.powerbuilder75, application/vnd.powerbuilder75-s, application/vnd.preminet, application/vnd.previewsystems.box, application/vnd.proteus.magazine, application/vnd.psfs, application/vnd.publishare-delta-tree, application/vnd.pvi.ptid1, application/vnd.pwg-multiplexed, application/vnd.pwg-xhtml-print+xml, application/vnd.qualcomm.brew-app-res, application/vnd.quarantainenet, application/vnd.quark.quarkxpress, application/vnd.quobject-quoxdocument, application/vnd.radisys.moml+xml, application/vnd.radisys.msml+xml, application/vnd.radisys.msml-audit+xml, application/vnd.radisys.msml-audit-conf+xml, application/vnd.radisys.msml-audit-conn+xml, application/vnd.radisys.msml-audit-dialog+xml, application/vnd.radisys.msml-audit-stream+xml, application/vnd.radisys.msml-conf+xml, application/vnd.radisys.msml-dialog+xml, application/vnd.radisys.msml-dialog-base+xml, application/vnd.radisys.msml-dialog-fax-detect+xml, application/vnd.radisys.msml-dialog-fax-sendrecv+xml, application/vnd.radisys.msml-dialog-group+xml, application/vnd.radisys.msml-dialog-speech+xml, application/vnd.radisys.msml-dialog-transform+xml, application/vnd.rainstor.data, application/vnd.rapid, application/vnd.rar, application/vnd.realvnc.bed, application/vnd.recordare.musicxml, application/vnd.recordare.musicxml+xml, application/vnd.renlearn.rlprint, application/vnd.restful+json, application/vnd.rig.cryptonote, application/vnd.rim.cod, application/vnd.rn-realmedia, application/vnd.rn-realmedia-vbr, application/vnd.route66.link66+xml, application/vnd.rs-274x, application/vnd.ruckus.download, application/vnd.s3sms, application/vnd.sailingtracker.track, application/vnd.sar, application/vnd.sbm.cid, application/vnd.sbm.mid2, application/vnd.scribus, application/vnd.sealed.3df, application/vnd.sealed.csf, application/vnd.sealed.doc, application/vnd.sealed.eml, application/vnd.sealed.mht, application/vnd.sealed.net, application/vnd.sealed.ppt, application/vnd.sealed.tiff, application/vnd.sealed.xls, application/vnd.sealedmedia.softseal.html, application/vnd.sealedmedia.softseal.pdf, application/vnd.seemail, application/vnd.sema, application/vnd.semd, application/vnd.semf, application/vnd.shade-save-file, application/vnd.shana.informed.formdata, application/vnd.shana.informed.formtemplate, application/vnd.shana.informed.interchange, application/vnd.shana.informed.package, application/vnd.shootproof+json, application/vnd.shopkick+json, application/vnd.shp, application/vnd.shx, application/vnd.sigrok.session, application/vnd.simtech-mindmapper, application/vnd.siren+json, application/vnd.smaf, application/vnd.smart.notebook, application/vnd.smart.teacher, application/vnd.snesdev-page-table, application/vnd.software602.filler.form+xml, application/vnd.software602.filler.form-xml-zip, application/vnd.solent.sdkm+xml, application/vnd.spotfire.dxp, application/vnd.spotfire.sfs, application/vnd.sqlite3, application/vnd.sss-cod, application/vnd.sss-dtf, application/vnd.sss-ntf, application/vnd.stardivision.calc, application/vnd.stardivision.draw, application/vnd.stardivision.impress, application/vnd.stardivision.math, application/vnd.stardivision.writer, application/vnd.stardivision.writer-global, application/vnd.stepmania.package, application/vnd.stepmania.stepchart, application/vnd.street-stream, application/vnd.sun.wadl+xml, application/vnd.sun.xml.calc, application/vnd.sun.xml.calc.template, application/vnd.sun.xml.draw, application/vnd.sun.xml.draw.template, application/vnd.sun.xml.impress, application/vnd.sun.xml.impress.template, application/vnd.sun.xml.math, application/vnd.sun.xml.writer, application/vnd.sun.xml.writer.global, application/vnd.sun.xml.writer.template, application/vnd.sus-calendar, application/vnd.svd, application/vnd.swiftview-ics, application/vnd.symbian.install, application/vnd.syncml+xml, application/vnd.syncml.dm+wbxml, application/vnd.syncml.dm+xml, application/vnd.syncml.dm.notification, application/vnd.syncml.dmddf+wbxml, application/vnd.syncml.dmddf+xml, application/vnd.syncml.dmtnds+wbxml, application/vnd.syncml.dmtnds+xml, application/vnd.syncml.ds.notification, application/vnd.tableschema+json, application/vnd.tao.intent-module-archive, application/vnd.tcpdump.pcap, application/vnd.think-cell.ppttc+json, application/vnd.tmd.mediaflex.api+xml, application/vnd.tml, application/vnd.tmobile-livetv, application/vnd.tri.onesource, application/vnd.trid.tpt, application/vnd.triscape.mxs, application/vnd.trueapp, application/vnd.truedoc, application/vnd.ubisoft.webplayer, application/vnd.ufdl, application/vnd.uiq.theme, application/vnd.umajin, application/vnd.unity, application/vnd.uoml+xml, application/vnd.uplanet.alert, application/vnd.uplanet.alert-wbxml, application/vnd.uplanet.bearer-choice, application/vnd.uplanet.bearer-choice-wbxml, application/vnd.uplanet.cacheop, application/vnd.uplanet.cacheop-wbxml, application/vnd.uplanet.channel, application/vnd.uplanet.channel-wbxml, application/vnd.uplanet.list, application/vnd.uplanet.list-wbxml, application/vnd.uplanet.listcmd, application/vnd.uplanet.listcmd-wbxml, application/vnd.uplanet.signal, application/vnd.uri-map, application/vnd.valve.source.material, application/vnd.vcx, application/vnd.vd-study, application/vnd.vectorworks, application/vnd.vel+json, application/vnd.verimatrix.vcas, application/vnd.veryant.thin, application/vnd.ves.encrypted, application/vnd.vidsoft.vidconference, application/vnd.visio, application/vnd.visionary, application/vnd.vividence.scriptfile, application/vnd.vsf, application/vnd.wap.sic, application/vnd.wap.slc, application/vnd.wap.wbxml, application/vnd.wap.wmlc, application/vnd.wap.wmlscriptc, application/vnd.webturbo, application/vnd.wfa.p2p, application/vnd.wfa.wsc, application/vnd.windows.devicepairing, application/vnd.wmc, application/vnd.wmf.bootstrap, application/vnd.wolfram.mathematica, application/vnd.wolfram.mathematica.package, application/vnd.wolfram.player, application/vnd.wordperfect, application/vnd.wqd, application/vnd.wrq-hp3000-labelled, application/vnd.wt.stf, application/vnd.wv.csp+wbxml, application/vnd.wv.csp+xml, application/vnd.wv.ssp+xml, application/vnd.xacml+json, application/vnd.xara, application/vnd.xfdl, application/vnd.xfdl.webform, application/vnd.xmi+xml, application/vnd.xmpie.cpkg, application/vnd.xmpie.dpkg, application/vnd.xmpie.plan, application/vnd.xmpie.ppkg, application/vnd.xmpie.xlim, application/vnd.yamaha.hv-dic, application/vnd.yamaha.hv-script, application/vnd.yamaha.hv-voice, application/vnd.yamaha.openscoreformat, application/vnd.yamaha.openscoreformat.osfpvg+xml, application/vnd.yamaha.remote-setup, application/vnd.yamaha.smaf-audio, application/vnd.yamaha.smaf-phrase, application/vnd.yamaha.through-ngn, application/vnd.yamaha.tunnel-udpencap, application/vnd.yaoweme, application/vnd.yellowriver-custom-menu, application/vnd.youtube.yt, application/vnd.zul, application/vnd.zzazz.deck+xml, application/voicexml+xml, application/voucher-cms+json, application/vq-rtcpxr, application/wasm, application/watcherinfo+xml, application/webpush-options+json, application/whoispp-query, application/whoispp-response, application/widget, application/winhlp, application/wita, application/wordperfect5.1, application/wsdl+xml, application/wspolicy+xml, application/x-7z-compressed, application/x-abiword, application/x-ace-compressed, application/x-amf, application/x-apple-diskimage, application/x-arj, application/x-authorware-bin, application/x-authorware-map, application/x-authorware-seg, application/x-bcpio, application/x-bdoc, application/x-bittorrent, application/x-blorb, application/x-bzip, application/x-bzip2, application/x-cbr, application/x-cdlink, application/x-cfs-compressed, application/x-chat, application/x-chess-pgn, application/x-chrome-extension, application/x-cocoa, application/x-compress, application/x-conference, application/x-cpio, application/x-csh, application/x-deb, application/x-debian-package, application/x-dgc-compressed, application/x-director, application/x-doom, application/x-dtbncx+xml, application/x-dtbook+xml, application/x-dtbresource+xml, application/x-dvi, application/x-envoy, application/x-eva, application/x-font-bdf, application/x-font-dos, application/x-font-framemaker, application/x-font-ghostscript, application/x-font-libgrx, application/x-font-linux-psf, application/x-font-pcf, application/x-font-snf, application/x-font-speedo, application/x-font-sunos-news, application/x-font-type1, application/x-font-vfont, application/x-freearc, application/x-futuresplash, application/x-gca-compressed, application/x-glulx, application/x-gnumeric, application/x-gramps-xml, application/x-gtar, application/x-gzip, application/x-hdf, application/x-httpd-php, application/x-install-instructions, application/x-iso9660-image, application/x-java-archive-diff, application/x-java-jnlp-file, application/x-javascript, application/x-keepass2, application/x-latex, application/x-lua-bytecode, application/x-lzh-compressed, application/x-makeself, application/x-mie, application/x-mobipocket-ebook, application/x-mpegurl, application/x-ms-application, application/x-ms-shortcut, application/x-ms-wmd, application/x-ms-wmz, application/x-ms-xbap, application/x-msaccess, application/x-msbinder, application/x-mscardfile, application/x-msclip, application/x-msdos-program, application/x-msdownload, application/x-msmediaview, application/x-msmetafile, application/x-msmoney, application/x-mspublisher, application/x-msschedule, application/x-msterminal, application/x-mswrite, application/x-netcdf, application/x-ns-proxy-autoconfig, application/x-nzb, application/x-perl, application/x-pilot, application/x-pkcs12, application/x-pkcs7-certificates, application/x-pkcs7-certreqresp, application/x-pki-message, application/x-rar-compressed, application/x-redhat-package-manager, application/x-research-info-systems, application/x-sea, application/x-sh, application/x-shar, application/x-shockwave-flash, application/x-silverlight-app, application/x-sql, application/x-stuffit, application/x-stuffitx, application/x-subrip, application/x-sv4cpio, application/x-sv4crc, application/x-t3vm-image, application/x-tads, application/x-tar, application/x-tcl, application/x-tex, application/x-tex-tfm, application/x-texinfo, application/x-tgif, application/x-ustar, application/x-virtualbox-hdd, application/x-virtualbox-ova, application/x-virtualbox-ovf, application/x-virtualbox-vbox, application/x-virtualbox-vbox-extpack, application/x-virtualbox-vdi, application/x-virtualbox-vhd, application/x-virtualbox-vmdk, application/x-wais-source, application/x-web-app-manifest+json, application/x-www-form-urlencoded, application/x-x509-ca-cert, application/x-x509-ca-ra-cert, application/x-x509-next-ca-cert, application/x-xfig, application/x-xliff+xml, application/x-xpinstall, application/x-xz, application/x-zmachine, application/x400-bp, application/xacml+xml, application/xaml+xml, application/xcap-att+xml, application/xcap-caps+xml, application/xcap-diff+xml, application/xcap-el+xml, application/xcap-error+xml, application/xcap-ns+xml, application/xcon-conference-info+xml, application/xcon-conference-info-diff+xml, application/xenc+xml, application/xhtml+xml, application/xhtml-voice+xml, application/xliff+xml, application/xml, application/xml-dtd, application/xml-external-parsed-entity, application/xml-patch+xml, application/xmpp+xml, application/xop+xml, application/xproc+xml, application/xslt+xml, application/xspf+xml, application/xv+xml, application/yang, application/yang-data+json, application/yang-data+xml, application/yang-patch+json, application/yang-patch+xml, application/yin+xml, application/zip, application/zlib, application/zstd, audio/1d-interleaved-parityfec, audio/32kadpcm, audio/3gpp, audio/3gpp2, audio/aac, audio/ac3, audio/adpcm, audio/amr, audio/amr-wb, audio/amr-wb+, audio/aptx, audio/asc, audio/atrac-advanced-lossless, audio/atrac-x, audio/atrac3, audio/basic, audio/bv16, audio/bv32, audio/clearmode, audio/cn, audio/dat12, audio/dls, audio/dsr-es201108, audio/dsr-es202050, audio/dsr-es202211, audio/dsr-es202212, audio/dv, audio/dvi4, audio/eac3, audio/encaprtp, audio/evrc, audio/evrc-qcp, audio/evrc0, audio/evrc1, audio/evrcb, audio/evrcb0, audio/evrcb1, audio/evrcnw, audio/evrcnw0, audio/evrcnw1, audio/evrcwb, audio/evrcwb0, audio/evrcwb1, audio/evs, audio/flexfec, audio/fwdred, audio/g711-0, audio/g719, audio/g722, audio/g7221, audio/g723, audio/g726-16, audio/g726-24, audio/g726-32, audio/g726-40, audio/g728, audio/g729, audio/g7291, audio/g729d, audio/g729e, audio/gsm, audio/gsm-efr, audio/gsm-hr-08, audio/ilbc, audio/ip-mr_v2.5, audio/isac, audio/l16, audio/l20, audio/l24, audio/l8, audio/lpc, audio/melp, audio/melp1200, audio/melp2400, audio/melp600, audio/mhas, audio/midi, audio/mobile-xmf, audio/mp3, audio/mp4, audio/mp4a-latm, audio/mpa, audio/mpa-robust, audio/mpeg, audio/mpeg4-generic, audio/musepack, audio/ogg, audio/opus, audio/parityfec, audio/pcma, audio/pcma-wb, audio/pcmu, audio/pcmu-wb, audio/prs.sid, audio/qcelp, audio/raptorfec, audio/red, audio/rtp-enc-aescm128, audio/rtp-midi, audio/rtploopback, audio/rtx, audio/s3m, audio/silk, audio/smv, audio/smv-qcp, audio/smv0, audio/sp-midi, audio/speex, audio/t140c, audio/t38, audio/telephone-event, audio/tetra_acelp, audio/tetra_acelp_bb, audio/tone, audio/uemclip, audio/ulpfec, audio/usac, audio/vdvi, audio/vmr-wb, audio/vnd.3gpp.iufp, audio/vnd.4sb, audio/vnd.audiokoz, audio/vnd.celp, audio/vnd.cisco.nse, audio/vnd.cmles.radio-events, audio/vnd.cns.anp1, audio/vnd.cns.inf1, audio/vnd.dece.audio, audio/vnd.digital-winds, audio/vnd.dlna.adts, audio/vnd.dolby.heaac.1, audio/vnd.dolby.heaac.2, audio/vnd.dolby.mlp, audio/vnd.dolby.mps, audio/vnd.dolby.pl2, audio/vnd.dolby.pl2x, audio/vnd.dolby.pl2z, audio/vnd.dolby.pulse.1, audio/vnd.dra, audio/vnd.dts, audio/vnd.dts.hd, audio/vnd.dts.uhd, audio/vnd.dvb.file, audio/vnd.everad.plj, audio/vnd.hns.audio, audio/vnd.lucent.voice, audio/vnd.ms-playready.media.pya, audio/vnd.nokia.mobile-xmf, audio/vnd.nortel.vbk, audio/vnd.nuera.ecelp4800, audio/vnd.nuera.ecelp7470, audio/vnd.nuera.ecelp9600, audio/vnd.octel.sbc, audio/vnd.presonus.multitrack, audio/vnd.qcelp, audio/vnd.rhetorex.32kadpcm, audio/vnd.rip, audio/vnd.rn-realaudio, audio/vnd.sealedmedia.softseal.mpeg, audio/vnd.vmx.cvsd, audio/vnd.wave, audio/vorbis, audio/vorbis-config, audio/wav, audio/wave, audio/webm, audio/x-aac, audio/x-aiff, audio/x-caf, audio/x-flac, audio/x-m4a, audio/x-matroska, audio/x-mpegurl, audio/x-ms-wax, audio/x-ms-wma, audio/x-pn-realaudio, audio/x-pn-realaudio-plugin, audio/x-realaudio, audio/x-tta, audio/x-wav, audio/xm, chemical/x-cdx, chemical/x-cif, chemical/x-cmdf, chemical/x-cml, chemical/x-csml, chemical/x-pdb, chemical/x-xyz, font/collection, font/otf, font/sfnt, font/ttf, font/woff, font/woff2, image/aces, image/apng, image/avci, image/avcs, image/bmp, image/cgm, image/dicom-rle, image/emf, image/fits, image/g3fax, image/gif, image/heic, image/heic-sequence, image/heif, image/heif-sequence, image/hej2k, image/hsj2, image/ief, image/jls, image/jp2, image/jpeg, image/jph, image/jphc, image/jpm, image/jpx, image/jxr, image/jxra, image/jxrs, image/jxs, image/jxsc, image/jxsi, image/jxss, image/ktx, image/naplps, image/pjpeg, image/png, image/prs.btif, image/prs.pti, image/pwg-raster, image/sgi, image/svg+xml, image/t38, image/tiff, image/tiff-fx, image/vnd.adobe.photoshop, image/vnd.airzip.accelerator.azv, image/vnd.cns.inf2, image/vnd.dece.graphic, image/vnd.djvu, image/vnd.dvb.subtitle, image/vnd.dwg, image/vnd.dxf, image/vnd.fastbidsheet, image/vnd.fpx, image/vnd.fst, image/vnd.fujixerox.edmics-mmr, image/vnd.fujixerox.edmics-rlc, image/vnd.globalgraphics.pgb, image/vnd.microsoft.icon, image/vnd.mix, image/vnd.mozilla.apng, image/vnd.ms-dds, image/vnd.ms-modi, image/vnd.ms-photo, image/vnd.net-fpx, image/vnd.radiance, image/vnd.sealed.png, image/vnd.sealedmedia.softseal.gif, image/vnd.sealedmedia.softseal.jpg, image/vnd.svf, image/vnd.tencent.tap, image/vnd.valve.source.texture, image/vnd.wap.wbmp, image/vnd.xiff, image/vnd.zbrush.pcx, image/webp, image/wmf, image/x-3ds, image/x-cmu-raster, image/x-cmx, image/x-freehand, image/x-icon, image/x-jng, image/x-mrsid-image, image/x-ms-bmp, image/x-pcx, image/x-pict, image/x-portable-anymap, image/x-portable-bitmap, image/x-portable-graymap, image/x-portable-pixmap, image/x-rgb, image/x-tga, image/x-xbitmap, image/x-xcf, image/x-xpixmap, image/x-xwindowdump, message/cpim, message/delivery-status, message/disposition-notification, message/external-body, message/feedback-report, message/global, message/global-delivery-status, message/global-disposition-notification, message/global-headers, message/http, message/imdn+xml, message/news, message/partial, message/rfc822, message/s-http, message/sip, message/sipfrag, message/tracking-status, message/vnd.si.simp, message/vnd.wfa.wsc, model/3mf, model/gltf+json, model/gltf-binary, model/iges, model/mesh, model/mtl, model/obj, model/stl, model/vnd.collada+xml, model/vnd.dwf, model/vnd.flatland.3dml, model/vnd.gdl, model/vnd.gs-gdl, model/vnd.gs.gdl, model/vnd.gtw, model/vnd.moml+xml, model/vnd.mts, model/vnd.opengex, model/vnd.parasolid.transmit.binary, model/vnd.parasolid.transmit.text, model/vnd.rosette.annotated-data-model, model/vnd.usdz+zip, model/vnd.valve.source.compiled-map, model/vnd.vtu, model/vrml, model/x3d+binary, model/x3d+fastinfoset, model/x3d+vrml, model/x3d+xml, model/x3d-vrml, multipart/alternative, multipart/appledouble, multipart/byteranges, multipart/digest, multipart/encrypted, multipart/form-data, multipart/header-set, multipart/mixed, multipart/multilingual, multipart/parallel, multipart/related, multipart/report, multipart/signed, multipart/vnd.bint.med-plus, multipart/voice-message, multipart/x-mixed-replace, text/1d-interleaved-parityfec, text/cache-manifest, text/calendar, text/calender, text/cmd, text/coffeescript, text/css, text/csv, text/csv-schema, text/directory, text/dns, text/ecmascript, text/encaprtp, text/enriched, text/flexfec, text/fwdred, text/grammar-ref-list, text/html, text/jade, text/javascript, text/jcr-cnd, text/jsx, text/less, text/markdown, text/mathml, text/mdx, text/mizar, text/n3, text/parameters, text/parityfec, text/plain, text/provenance-notation, text/prs.fallenstein.rst, text/prs.lines.tag, text/prs.prop.logic, text/raptorfec, text/red, text/rfc822-headers, text/richtext, text/rtf, text/rtp-enc-aescm128, text/rtploopback, text/rtx, text/sgml, text/shex, text/slim, text/strings, text/stylus, text/t140, text/tab-separated-values, text/troff, text/turtle, text/ulpfec, text/uri-list, text/vcard, text/vnd.a, text/vnd.abc, text/vnd.ascii-art, text/vnd.curl, text/vnd.curl.dcurl, text/vnd.curl.mcurl, text/vnd.curl.scurl, text/vnd.debian.copyright, text/vnd.dmclientscript, text/vnd.dvb.subtitle, text/vnd.esmertec.theme-descriptor, text/vnd.ficlab.flt, text/vnd.fly, text/vnd.fmi.flexstor, text/vnd.gml, text/vnd.graphviz, text/vnd.hgl, text/vnd.in3d.3dml, text/vnd.in3d.spot, text/vnd.iptc.newsml, text/vnd.iptc.nitf, text/vnd.latex-z, text/vnd.motorola.reflex, text/vnd.ms-mediapackage, text/vnd.net2phone.commcenter.command, text/vnd.radisys.msml-basic-layout, text/vnd.senx.warpscript, text/vnd.si.uricatalogue, text/vnd.sosi, text/vnd.sun.j2me.app-descriptor, text/vnd.trolltech.linguist, text/vnd.wap.si, text/vnd.wap.sl, text/vnd.wap.wml, text/vnd.wap.wmlscript, text/vtt, text/x-asm, text/x-c, text/x-component, text/x-fortran, text/x-gwt-rpc, text/x-handlebars-template, text/x-java-source, text/x-jquery-tmpl, text/x-lua, text/x-markdown, text/x-nfo, text/x-opml, text/x-org, text/x-pascal, text/x-processing, text/x-sass, text/x-scss, text/x-setext, text/x-sfv, text/x-suse-ymp, text/x-uuencode, text/x-vcalendar, text/x-vcard, text/xml, text/xml-external-parsed-entity, text/yaml, video/1d-interleaved-parityfec, video/3gpp, video/3gpp-tt, video/3gpp2, video/bmpeg, video/bt656, video/celb, video/dv, video/encaprtp, video/flexfec, video/h261, video/h263, video/h263-1998, video/h263-2000, video/h264, video/h264-rcdo, video/h264-svc, video/h265, video/iso.segment, video/jpeg, video/jpeg2000, video/jpm, video/mj2, video/mp1s, video/mp2p, video/mp2t, video/mp4, video/mp4v-es, video/mpeg, video/mpeg4-generic, video/mpv, video/nv, video/ogg, video/parityfec, video/pointer, video/quicktime, video/raptorfec, video/raw, video/rtp-enc-aescm128, video/rtploopback, video/rtx, video/smpte291, video/smpte292m, video/ulpfec, video/vc1, video/vc2, video/vnd.cctv, video/vnd.dece.hd, video/vnd.dece.mobile, video/vnd.dece.mp4, video/vnd.dece.pd, video/vnd.dece.sd, video/vnd.dece.video, video/vnd.directv.mpeg, video/vnd.directv.mpeg-tts, video/vnd.dlna.mpeg-tts, video/vnd.dvb.file, video/vnd.fvt, video/vnd.hns.video, video/vnd.iptvforum.1dparityfec-1010, video/vnd.iptvforum.1dparityfec-2005, video/vnd.iptvforum.2dparityfec-1010, video/vnd.iptvforum.2dparityfec-2005, video/vnd.iptvforum.ttsavc, video/vnd.iptvforum.ttsmpeg2, video/vnd.motorola.video, video/vnd.motorola.videop, video/vnd.mpegurl, video/vnd.ms-playready.media.pyv, video/vnd.nokia.interleaved-multimedia, video/vnd.nokia.mp4vr, video/vnd.nokia.videovoip, video/vnd.objectvideo, video/vnd.radgamettools.bink, video/vnd.radgamettools.smacker, video/vnd.sealed.mpeg1, video/vnd.sealed.mpeg4, video/vnd.sealed.swf, video/vnd.sealedmedia.softseal.mov, video/vnd.uvvu.mp4, video/vnd.vivo, video/vnd.youtube.yt, video/vp8, video/webm, video/x-f4v, video/x-fli, video/x-flv, video/x-m4v, video/x-matroska, video/x-mng, video/x-ms-asf, video/x-ms-vob, video/x-ms-wm, video/x-ms-wmv, video/x-ms-wmx, video/x-ms-wvx, video/x-msvideo, video/x-sgi-movie, video/x-smv, x-conference/x-cooltalk, x-shader/x-fragment, x-shader/x-vertex, default */ +/***/ (function(module) { + +module.exports = JSON.parse("{\"application/1d-interleaved-parityfec\":{\"source\":\"iana\"},\"application/3gpdash-qoe-report+xml\":{\"source\":\"iana\",\"charset\":\"UTF-8\",\"compressible\":true},\"application/3gpp-ims+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/a2l\":{\"source\":\"iana\"},\"application/activemessage\":{\"source\":\"iana\"},\"application/activity+json\":{\"source\":\"iana\",\"compressible\":true},\"application/alto-costmap+json\":{\"source\":\"iana\",\"compressible\":true},\"application/alto-costmapfilter+json\":{\"source\":\"iana\",\"compressible\":true},\"application/alto-directory+json\":{\"source\":\"iana\",\"compressible\":true},\"application/alto-endpointcost+json\":{\"source\":\"iana\",\"compressible\":true},\"application/alto-endpointcostparams+json\":{\"source\":\"iana\",\"compressible\":true},\"application/alto-endpointprop+json\":{\"source\":\"iana\",\"compressible\":true},\"application/alto-endpointpropparams+json\":{\"source\":\"iana\",\"compressible\":true},\"application/alto-error+json\":{\"source\":\"iana\",\"compressible\":true},\"application/alto-networkmap+json\":{\"source\":\"iana\",\"compressible\":true},\"application/alto-networkmapfilter+json\":{\"source\":\"iana\",\"compressible\":true},\"application/alto-updatestreamcontrol+json\":{\"source\":\"iana\",\"compressible\":true},\"application/alto-updatestreamparams+json\":{\"source\":\"iana\",\"compressible\":true},\"application/aml\":{\"source\":\"iana\"},\"application/andrew-inset\":{\"source\":\"iana\",\"extensions\":[\"ez\"]},\"application/applefile\":{\"source\":\"iana\"},\"application/applixware\":{\"source\":\"apache\",\"extensions\":[\"aw\"]},\"application/atf\":{\"source\":\"iana\"},\"application/atfx\":{\"source\":\"iana\"},\"application/atom+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"atom\"]},\"application/atomcat+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"atomcat\"]},\"application/atomdeleted+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"atomdeleted\"]},\"application/atomicmail\":{\"source\":\"iana\"},\"application/atomsvc+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"atomsvc\"]},\"application/atsc-dwd+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"dwd\"]},\"application/atsc-dynamic-event-message\":{\"source\":\"iana\"},\"application/atsc-held+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"held\"]},\"application/atsc-rdt+json\":{\"source\":\"iana\",\"compressible\":true},\"application/atsc-rsat+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"rsat\"]},\"application/atxml\":{\"source\":\"iana\"},\"application/auth-policy+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/bacnet-xdd+zip\":{\"source\":\"iana\",\"compressible\":false},\"application/batch-smtp\":{\"source\":\"iana\"},\"application/bdoc\":{\"compressible\":false,\"extensions\":[\"bdoc\"]},\"application/beep+xml\":{\"source\":\"iana\",\"charset\":\"UTF-8\",\"compressible\":true},\"application/calendar+json\":{\"source\":\"iana\",\"compressible\":true},\"application/calendar+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"xcs\"]},\"application/call-completion\":{\"source\":\"iana\"},\"application/cals-1840\":{\"source\":\"iana\"},\"application/cap+xml\":{\"source\":\"iana\",\"charset\":\"UTF-8\",\"compressible\":true},\"application/cbor\":{\"source\":\"iana\"},\"application/cbor-seq\":{\"source\":\"iana\"},\"application/cccex\":{\"source\":\"iana\"},\"application/ccmp+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/ccxml+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"ccxml\"]},\"application/cdfx+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"cdfx\"]},\"application/cdmi-capability\":{\"source\":\"iana\",\"extensions\":[\"cdmia\"]},\"application/cdmi-container\":{\"source\":\"iana\",\"extensions\":[\"cdmic\"]},\"application/cdmi-domain\":{\"source\":\"iana\",\"extensions\":[\"cdmid\"]},\"application/cdmi-object\":{\"source\":\"iana\",\"extensions\":[\"cdmio\"]},\"application/cdmi-queue\":{\"source\":\"iana\",\"extensions\":[\"cdmiq\"]},\"application/cdni\":{\"source\":\"iana\"},\"application/cea\":{\"source\":\"iana\"},\"application/cea-2018+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/cellml+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/cfw\":{\"source\":\"iana\"},\"application/clue+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/clue_info+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/cms\":{\"source\":\"iana\"},\"application/cnrp+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/coap-group+json\":{\"source\":\"iana\",\"compressible\":true},\"application/coap-payload\":{\"source\":\"iana\"},\"application/commonground\":{\"source\":\"iana\"},\"application/conference-info+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/cose\":{\"source\":\"iana\"},\"application/cose-key\":{\"source\":\"iana\"},\"application/cose-key-set\":{\"source\":\"iana\"},\"application/cpl+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/csrattrs\":{\"source\":\"iana\"},\"application/csta+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/cstadata+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/csvm+json\":{\"source\":\"iana\",\"compressible\":true},\"application/cu-seeme\":{\"source\":\"apache\",\"extensions\":[\"cu\"]},\"application/cwt\":{\"source\":\"iana\"},\"application/cybercash\":{\"source\":\"iana\"},\"application/dart\":{\"compressible\":true},\"application/dash+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"mpd\"]},\"application/dashdelta\":{\"source\":\"iana\"},\"application/davmount+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"davmount\"]},\"application/dca-rft\":{\"source\":\"iana\"},\"application/dcd\":{\"source\":\"iana\"},\"application/dec-dx\":{\"source\":\"iana\"},\"application/dialog-info+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/dicom\":{\"source\":\"iana\"},\"application/dicom+json\":{\"source\":\"iana\",\"compressible\":true},\"application/dicom+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/dii\":{\"source\":\"iana\"},\"application/dit\":{\"source\":\"iana\"},\"application/dns\":{\"source\":\"iana\"},\"application/dns+json\":{\"source\":\"iana\",\"compressible\":true},\"application/dns-message\":{\"source\":\"iana\"},\"application/docbook+xml\":{\"source\":\"apache\",\"compressible\":true,\"extensions\":[\"dbk\"]},\"application/dots+cbor\":{\"source\":\"iana\"},\"application/dskpp+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/dssc+der\":{\"source\":\"iana\",\"extensions\":[\"dssc\"]},\"application/dssc+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"xdssc\"]},\"application/dvcs\":{\"source\":\"iana\"},\"application/ecmascript\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"ecma\",\"es\"]},\"application/edi-consent\":{\"source\":\"iana\"},\"application/edi-x12\":{\"source\":\"iana\",\"compressible\":false},\"application/edifact\":{\"source\":\"iana\",\"compressible\":false},\"application/efi\":{\"source\":\"iana\"},\"application/emergencycalldata.comment+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/emergencycalldata.control+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/emergencycalldata.deviceinfo+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/emergencycalldata.ecall.msd\":{\"source\":\"iana\"},\"application/emergencycalldata.providerinfo+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/emergencycalldata.serviceinfo+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/emergencycalldata.subscriberinfo+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/emergencycalldata.veds+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/emma+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"emma\"]},\"application/emotionml+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"emotionml\"]},\"application/encaprtp\":{\"source\":\"iana\"},\"application/epp+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/epub+zip\":{\"source\":\"iana\",\"compressible\":false,\"extensions\":[\"epub\"]},\"application/eshop\":{\"source\":\"iana\"},\"application/exi\":{\"source\":\"iana\",\"extensions\":[\"exi\"]},\"application/expect-ct-report+json\":{\"source\":\"iana\",\"compressible\":true},\"application/fastinfoset\":{\"source\":\"iana\"},\"application/fastsoap\":{\"source\":\"iana\"},\"application/fdt+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"fdt\"]},\"application/fhir+json\":{\"source\":\"iana\",\"charset\":\"UTF-8\",\"compressible\":true},\"application/fhir+xml\":{\"source\":\"iana\",\"charset\":\"UTF-8\",\"compressible\":true},\"application/fido.trusted-apps+json\":{\"compressible\":true},\"application/fits\":{\"source\":\"iana\"},\"application/flexfec\":{\"source\":\"iana\"},\"application/font-sfnt\":{\"source\":\"iana\"},\"application/font-tdpfr\":{\"source\":\"iana\",\"extensions\":[\"pfr\"]},\"application/font-woff\":{\"source\":\"iana\",\"compressible\":false},\"application/framework-attributes+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/geo+json\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"geojson\"]},\"application/geo+json-seq\":{\"source\":\"iana\"},\"application/geopackage+sqlite3\":{\"source\":\"iana\"},\"application/geoxacml+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/gltf-buffer\":{\"source\":\"iana\"},\"application/gml+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"gml\"]},\"application/gpx+xml\":{\"source\":\"apache\",\"compressible\":true,\"extensions\":[\"gpx\"]},\"application/gxf\":{\"source\":\"apache\",\"extensions\":[\"gxf\"]},\"application/gzip\":{\"source\":\"iana\",\"compressible\":false,\"extensions\":[\"gz\"]},\"application/h224\":{\"source\":\"iana\"},\"application/held+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/hjson\":{\"extensions\":[\"hjson\"]},\"application/http\":{\"source\":\"iana\"},\"application/hyperstudio\":{\"source\":\"iana\",\"extensions\":[\"stk\"]},\"application/ibe-key-request+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/ibe-pkg-reply+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/ibe-pp-data\":{\"source\":\"iana\"},\"application/iges\":{\"source\":\"iana\"},\"application/im-iscomposing+xml\":{\"source\":\"iana\",\"charset\":\"UTF-8\",\"compressible\":true},\"application/index\":{\"source\":\"iana\"},\"application/index.cmd\":{\"source\":\"iana\"},\"application/index.obj\":{\"source\":\"iana\"},\"application/index.response\":{\"source\":\"iana\"},\"application/index.vnd\":{\"source\":\"iana\"},\"application/inkml+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"ink\",\"inkml\"]},\"application/iotp\":{\"source\":\"iana\"},\"application/ipfix\":{\"source\":\"iana\",\"extensions\":[\"ipfix\"]},\"application/ipp\":{\"source\":\"iana\"},\"application/isup\":{\"source\":\"iana\"},\"application/its+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"its\"]},\"application/java-archive\":{\"source\":\"apache\",\"compressible\":false,\"extensions\":[\"jar\",\"war\",\"ear\"]},\"application/java-serialized-object\":{\"source\":\"apache\",\"compressible\":false,\"extensions\":[\"ser\"]},\"application/java-vm\":{\"source\":\"apache\",\"compressible\":false,\"extensions\":[\"class\"]},\"application/javascript\":{\"source\":\"iana\",\"charset\":\"UTF-8\",\"compressible\":true,\"extensions\":[\"js\",\"mjs\"]},\"application/jf2feed+json\":{\"source\":\"iana\",\"compressible\":true},\"application/jose\":{\"source\":\"iana\"},\"application/jose+json\":{\"source\":\"iana\",\"compressible\":true},\"application/jrd+json\":{\"source\":\"iana\",\"compressible\":true},\"application/json\":{\"source\":\"iana\",\"charset\":\"UTF-8\",\"compressible\":true,\"extensions\":[\"json\",\"map\"]},\"application/json-patch+json\":{\"source\":\"iana\",\"compressible\":true},\"application/json-seq\":{\"source\":\"iana\"},\"application/json5\":{\"extensions\":[\"json5\"]},\"application/jsonml+json\":{\"source\":\"apache\",\"compressible\":true,\"extensions\":[\"jsonml\"]},\"application/jwk+json\":{\"source\":\"iana\",\"compressible\":true},\"application/jwk-set+json\":{\"source\":\"iana\",\"compressible\":true},\"application/jwt\":{\"source\":\"iana\"},\"application/kpml-request+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/kpml-response+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/ld+json\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"jsonld\"]},\"application/lgr+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"lgr\"]},\"application/link-format\":{\"source\":\"iana\"},\"application/load-control+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/lost+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"lostxml\"]},\"application/lostsync+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/lpf+zip\":{\"source\":\"iana\",\"compressible\":false},\"application/lxf\":{\"source\":\"iana\"},\"application/mac-binhex40\":{\"source\":\"iana\",\"extensions\":[\"hqx\"]},\"application/mac-compactpro\":{\"source\":\"apache\",\"extensions\":[\"cpt\"]},\"application/macwriteii\":{\"source\":\"iana\"},\"application/mads+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"mads\"]},\"application/manifest+json\":{\"charset\":\"UTF-8\",\"compressible\":true,\"extensions\":[\"webmanifest\"]},\"application/marc\":{\"source\":\"iana\",\"extensions\":[\"mrc\"]},\"application/marcxml+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"mrcx\"]},\"application/mathematica\":{\"source\":\"iana\",\"extensions\":[\"ma\",\"nb\",\"mb\"]},\"application/mathml+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"mathml\"]},\"application/mathml-content+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/mathml-presentation+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/mbms-associated-procedure-description+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/mbms-deregister+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/mbms-envelope+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/mbms-msk+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/mbms-msk-response+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/mbms-protection-description+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/mbms-reception-report+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/mbms-register+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/mbms-register-response+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/mbms-schedule+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/mbms-user-service-description+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/mbox\":{\"source\":\"iana\",\"extensions\":[\"mbox\"]},\"application/media-policy-dataset+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/media_control+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/mediaservercontrol+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"mscml\"]},\"application/merge-patch+json\":{\"source\":\"iana\",\"compressible\":true},\"application/metalink+xml\":{\"source\":\"apache\",\"compressible\":true,\"extensions\":[\"metalink\"]},\"application/metalink4+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"meta4\"]},\"application/mets+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"mets\"]},\"application/mf4\":{\"source\":\"iana\"},\"application/mikey\":{\"source\":\"iana\"},\"application/mipc\":{\"source\":\"iana\"},\"application/mmt-aei+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"maei\"]},\"application/mmt-usd+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"musd\"]},\"application/mods+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"mods\"]},\"application/moss-keys\":{\"source\":\"iana\"},\"application/moss-signature\":{\"source\":\"iana\"},\"application/mosskey-data\":{\"source\":\"iana\"},\"application/mosskey-request\":{\"source\":\"iana\"},\"application/mp21\":{\"source\":\"iana\",\"extensions\":[\"m21\",\"mp21\"]},\"application/mp4\":{\"source\":\"iana\",\"extensions\":[\"mp4s\",\"m4p\"]},\"application/mpeg4-generic\":{\"source\":\"iana\"},\"application/mpeg4-iod\":{\"source\":\"iana\"},\"application/mpeg4-iod-xmt\":{\"source\":\"iana\"},\"application/mrb-consumer+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"xdf\"]},\"application/mrb-publish+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"xdf\"]},\"application/msc-ivr+xml\":{\"source\":\"iana\",\"charset\":\"UTF-8\",\"compressible\":true},\"application/msc-mixer+xml\":{\"source\":\"iana\",\"charset\":\"UTF-8\",\"compressible\":true},\"application/msword\":{\"source\":\"iana\",\"compressible\":false,\"extensions\":[\"doc\",\"dot\"]},\"application/mud+json\":{\"source\":\"iana\",\"compressible\":true},\"application/multipart-core\":{\"source\":\"iana\"},\"application/mxf\":{\"source\":\"iana\",\"extensions\":[\"mxf\"]},\"application/n-quads\":{\"source\":\"iana\",\"extensions\":[\"nq\"]},\"application/n-triples\":{\"source\":\"iana\",\"extensions\":[\"nt\"]},\"application/nasdata\":{\"source\":\"iana\"},\"application/news-checkgroups\":{\"source\":\"iana\",\"charset\":\"US-ASCII\"},\"application/news-groupinfo\":{\"source\":\"iana\",\"charset\":\"US-ASCII\"},\"application/news-transmission\":{\"source\":\"iana\"},\"application/nlsml+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/node\":{\"source\":\"iana\",\"extensions\":[\"cjs\"]},\"application/nss\":{\"source\":\"iana\"},\"application/ocsp-request\":{\"source\":\"iana\"},\"application/ocsp-response\":{\"source\":\"iana\"},\"application/octet-stream\":{\"source\":\"iana\",\"compressible\":false,\"extensions\":[\"bin\",\"dms\",\"lrf\",\"mar\",\"so\",\"dist\",\"distz\",\"pkg\",\"bpk\",\"dump\",\"elc\",\"deploy\",\"exe\",\"dll\",\"deb\",\"dmg\",\"iso\",\"img\",\"msi\",\"msp\",\"msm\",\"buffer\"]},\"application/oda\":{\"source\":\"iana\",\"extensions\":[\"oda\"]},\"application/odm+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/odx\":{\"source\":\"iana\"},\"application/oebps-package+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"opf\"]},\"application/ogg\":{\"source\":\"iana\",\"compressible\":false,\"extensions\":[\"ogx\"]},\"application/omdoc+xml\":{\"source\":\"apache\",\"compressible\":true,\"extensions\":[\"omdoc\"]},\"application/onenote\":{\"source\":\"apache\",\"extensions\":[\"onetoc\",\"onetoc2\",\"onetmp\",\"onepkg\"]},\"application/oscore\":{\"source\":\"iana\"},\"application/oxps\":{\"source\":\"iana\",\"extensions\":[\"oxps\"]},\"application/p2p-overlay+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"relo\"]},\"application/parityfec\":{\"source\":\"iana\"},\"application/passport\":{\"source\":\"iana\"},\"application/patch-ops-error+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"xer\"]},\"application/pdf\":{\"source\":\"iana\",\"compressible\":false,\"extensions\":[\"pdf\"]},\"application/pdx\":{\"source\":\"iana\"},\"application/pem-certificate-chain\":{\"source\":\"iana\"},\"application/pgp-encrypted\":{\"source\":\"iana\",\"compressible\":false,\"extensions\":[\"pgp\"]},\"application/pgp-keys\":{\"source\":\"iana\"},\"application/pgp-signature\":{\"source\":\"iana\",\"extensions\":[\"asc\",\"sig\"]},\"application/pics-rules\":{\"source\":\"apache\",\"extensions\":[\"prf\"]},\"application/pidf+xml\":{\"source\":\"iana\",\"charset\":\"UTF-8\",\"compressible\":true},\"application/pidf-diff+xml\":{\"source\":\"iana\",\"charset\":\"UTF-8\",\"compressible\":true},\"application/pkcs10\":{\"source\":\"iana\",\"extensions\":[\"p10\"]},\"application/pkcs12\":{\"source\":\"iana\"},\"application/pkcs7-mime\":{\"source\":\"iana\",\"extensions\":[\"p7m\",\"p7c\"]},\"application/pkcs7-signature\":{\"source\":\"iana\",\"extensions\":[\"p7s\"]},\"application/pkcs8\":{\"source\":\"iana\",\"extensions\":[\"p8\"]},\"application/pkcs8-encrypted\":{\"source\":\"iana\"},\"application/pkix-attr-cert\":{\"source\":\"iana\",\"extensions\":[\"ac\"]},\"application/pkix-cert\":{\"source\":\"iana\",\"extensions\":[\"cer\"]},\"application/pkix-crl\":{\"source\":\"iana\",\"extensions\":[\"crl\"]},\"application/pkix-pkipath\":{\"source\":\"iana\",\"extensions\":[\"pkipath\"]},\"application/pkixcmp\":{\"source\":\"iana\",\"extensions\":[\"pki\"]},\"application/pls+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"pls\"]},\"application/poc-settings+xml\":{\"source\":\"iana\",\"charset\":\"UTF-8\",\"compressible\":true},\"application/postscript\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"ai\",\"eps\",\"ps\"]},\"application/ppsp-tracker+json\":{\"source\":\"iana\",\"compressible\":true},\"application/problem+json\":{\"source\":\"iana\",\"compressible\":true},\"application/problem+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/provenance+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"provx\"]},\"application/prs.alvestrand.titrax-sheet\":{\"source\":\"iana\"},\"application/prs.cww\":{\"source\":\"iana\",\"extensions\":[\"cww\"]},\"application/prs.hpub+zip\":{\"source\":\"iana\",\"compressible\":false},\"application/prs.nprend\":{\"source\":\"iana\"},\"application/prs.plucker\":{\"source\":\"iana\"},\"application/prs.rdf-xml-crypt\":{\"source\":\"iana\"},\"application/prs.xsf+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/pskc+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"pskcxml\"]},\"application/pvd+json\":{\"source\":\"iana\",\"compressible\":true},\"application/qsig\":{\"source\":\"iana\"},\"application/raml+yaml\":{\"compressible\":true,\"extensions\":[\"raml\"]},\"application/raptorfec\":{\"source\":\"iana\"},\"application/rdap+json\":{\"source\":\"iana\",\"compressible\":true},\"application/rdf+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"rdf\",\"owl\"]},\"application/reginfo+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"rif\"]},\"application/relax-ng-compact-syntax\":{\"source\":\"iana\",\"extensions\":[\"rnc\"]},\"application/remote-printing\":{\"source\":\"iana\"},\"application/reputon+json\":{\"source\":\"iana\",\"compressible\":true},\"application/resource-lists+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"rl\"]},\"application/resource-lists-diff+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"rld\"]},\"application/rfc+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/riscos\":{\"source\":\"iana\"},\"application/rlmi+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/rls-services+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"rs\"]},\"application/route-apd+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"rapd\"]},\"application/route-s-tsid+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"sls\"]},\"application/route-usd+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"rusd\"]},\"application/rpki-ghostbusters\":{\"source\":\"iana\",\"extensions\":[\"gbr\"]},\"application/rpki-manifest\":{\"source\":\"iana\",\"extensions\":[\"mft\"]},\"application/rpki-publication\":{\"source\":\"iana\"},\"application/rpki-roa\":{\"source\":\"iana\",\"extensions\":[\"roa\"]},\"application/rpki-updown\":{\"source\":\"iana\"},\"application/rsd+xml\":{\"source\":\"apache\",\"compressible\":true,\"extensions\":[\"rsd\"]},\"application/rss+xml\":{\"source\":\"apache\",\"compressible\":true,\"extensions\":[\"rss\"]},\"application/rtf\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"rtf\"]},\"application/rtploopback\":{\"source\":\"iana\"},\"application/rtx\":{\"source\":\"iana\"},\"application/samlassertion+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/samlmetadata+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/sbe\":{\"source\":\"iana\"},\"application/sbml+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"sbml\"]},\"application/scaip+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/scim+json\":{\"source\":\"iana\",\"compressible\":true},\"application/scvp-cv-request\":{\"source\":\"iana\",\"extensions\":[\"scq\"]},\"application/scvp-cv-response\":{\"source\":\"iana\",\"extensions\":[\"scs\"]},\"application/scvp-vp-request\":{\"source\":\"iana\",\"extensions\":[\"spq\"]},\"application/scvp-vp-response\":{\"source\":\"iana\",\"extensions\":[\"spp\"]},\"application/sdp\":{\"source\":\"iana\",\"extensions\":[\"sdp\"]},\"application/secevent+jwt\":{\"source\":\"iana\"},\"application/senml+cbor\":{\"source\":\"iana\"},\"application/senml+json\":{\"source\":\"iana\",\"compressible\":true},\"application/senml+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"senmlx\"]},\"application/senml-etch+cbor\":{\"source\":\"iana\"},\"application/senml-etch+json\":{\"source\":\"iana\",\"compressible\":true},\"application/senml-exi\":{\"source\":\"iana\"},\"application/sensml+cbor\":{\"source\":\"iana\"},\"application/sensml+json\":{\"source\":\"iana\",\"compressible\":true},\"application/sensml+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"sensmlx\"]},\"application/sensml-exi\":{\"source\":\"iana\"},\"application/sep+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/sep-exi\":{\"source\":\"iana\"},\"application/session-info\":{\"source\":\"iana\"},\"application/set-payment\":{\"source\":\"iana\"},\"application/set-payment-initiation\":{\"source\":\"iana\",\"extensions\":[\"setpay\"]},\"application/set-registration\":{\"source\":\"iana\"},\"application/set-registration-initiation\":{\"source\":\"iana\",\"extensions\":[\"setreg\"]},\"application/sgml\":{\"source\":\"iana\"},\"application/sgml-open-catalog\":{\"source\":\"iana\"},\"application/shf+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"shf\"]},\"application/sieve\":{\"source\":\"iana\",\"extensions\":[\"siv\",\"sieve\"]},\"application/simple-filter+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/simple-message-summary\":{\"source\":\"iana\"},\"application/simplesymbolcontainer\":{\"source\":\"iana\"},\"application/sipc\":{\"source\":\"iana\"},\"application/slate\":{\"source\":\"iana\"},\"application/smil\":{\"source\":\"iana\"},\"application/smil+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"smi\",\"smil\"]},\"application/smpte336m\":{\"source\":\"iana\"},\"application/soap+fastinfoset\":{\"source\":\"iana\"},\"application/soap+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/sparql-query\":{\"source\":\"iana\",\"extensions\":[\"rq\"]},\"application/sparql-results+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"srx\"]},\"application/spirits-event+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/sql\":{\"source\":\"iana\"},\"application/srgs\":{\"source\":\"iana\",\"extensions\":[\"gram\"]},\"application/srgs+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"grxml\"]},\"application/sru+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"sru\"]},\"application/ssdl+xml\":{\"source\":\"apache\",\"compressible\":true,\"extensions\":[\"ssdl\"]},\"application/ssml+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"ssml\"]},\"application/stix+json\":{\"source\":\"iana\",\"compressible\":true},\"application/swid+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"swidtag\"]},\"application/tamp-apex-update\":{\"source\":\"iana\"},\"application/tamp-apex-update-confirm\":{\"source\":\"iana\"},\"application/tamp-community-update\":{\"source\":\"iana\"},\"application/tamp-community-update-confirm\":{\"source\":\"iana\"},\"application/tamp-error\":{\"source\":\"iana\"},\"application/tamp-sequence-adjust\":{\"source\":\"iana\"},\"application/tamp-sequence-adjust-confirm\":{\"source\":\"iana\"},\"application/tamp-status-query\":{\"source\":\"iana\"},\"application/tamp-status-response\":{\"source\":\"iana\"},\"application/tamp-update\":{\"source\":\"iana\"},\"application/tamp-update-confirm\":{\"source\":\"iana\"},\"application/tar\":{\"compressible\":true},\"application/taxii+json\":{\"source\":\"iana\",\"compressible\":true},\"application/td+json\":{\"source\":\"iana\",\"compressible\":true},\"application/tei+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"tei\",\"teicorpus\"]},\"application/tetra_isi\":{\"source\":\"iana\"},\"application/thraud+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"tfi\"]},\"application/timestamp-query\":{\"source\":\"iana\"},\"application/timestamp-reply\":{\"source\":\"iana\"},\"application/timestamped-data\":{\"source\":\"iana\",\"extensions\":[\"tsd\"]},\"application/tlsrpt+gzip\":{\"source\":\"iana\"},\"application/tlsrpt+json\":{\"source\":\"iana\",\"compressible\":true},\"application/tnauthlist\":{\"source\":\"iana\"},\"application/toml\":{\"compressible\":true,\"extensions\":[\"toml\"]},\"application/trickle-ice-sdpfrag\":{\"source\":\"iana\"},\"application/trig\":{\"source\":\"iana\"},\"application/ttml+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"ttml\"]},\"application/tve-trigger\":{\"source\":\"iana\"},\"application/tzif\":{\"source\":\"iana\"},\"application/tzif-leap\":{\"source\":\"iana\"},\"application/ulpfec\":{\"source\":\"iana\"},\"application/urc-grpsheet+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/urc-ressheet+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"rsheet\"]},\"application/urc-targetdesc+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/urc-uisocketdesc+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vcard+json\":{\"source\":\"iana\",\"compressible\":true},\"application/vcard+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vemmi\":{\"source\":\"iana\"},\"application/vividence.scriptfile\":{\"source\":\"apache\"},\"application/vnd.1000minds.decision-model+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"1km\"]},\"application/vnd.3gpp-prose+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.3gpp-prose-pc3ch+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.3gpp-v2x-local-service-information\":{\"source\":\"iana\"},\"application/vnd.3gpp.access-transfer-events+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.3gpp.bsf+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.3gpp.gmop+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.3gpp.mc-signalling-ear\":{\"source\":\"iana\"},\"application/vnd.3gpp.mcdata-affiliation-command+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.3gpp.mcdata-info+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.3gpp.mcdata-payload\":{\"source\":\"iana\"},\"application/vnd.3gpp.mcdata-service-config+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.3gpp.mcdata-signalling\":{\"source\":\"iana\"},\"application/vnd.3gpp.mcdata-ue-config+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.3gpp.mcdata-user-profile+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.3gpp.mcptt-affiliation-command+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.3gpp.mcptt-floor-request+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.3gpp.mcptt-info+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.3gpp.mcptt-location-info+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.3gpp.mcptt-mbms-usage-info+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.3gpp.mcptt-service-config+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.3gpp.mcptt-signed+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.3gpp.mcptt-ue-config+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.3gpp.mcptt-ue-init-config+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.3gpp.mcptt-user-profile+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.3gpp.mcvideo-affiliation-command+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.3gpp.mcvideo-affiliation-info+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.3gpp.mcvideo-info+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.3gpp.mcvideo-location-info+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.3gpp.mcvideo-mbms-usage-info+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.3gpp.mcvideo-service-config+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.3gpp.mcvideo-transmission-request+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.3gpp.mcvideo-ue-config+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.3gpp.mcvideo-user-profile+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.3gpp.mid-call+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.3gpp.pic-bw-large\":{\"source\":\"iana\",\"extensions\":[\"plb\"]},\"application/vnd.3gpp.pic-bw-small\":{\"source\":\"iana\",\"extensions\":[\"psb\"]},\"application/vnd.3gpp.pic-bw-var\":{\"source\":\"iana\",\"extensions\":[\"pvb\"]},\"application/vnd.3gpp.sms\":{\"source\":\"iana\"},\"application/vnd.3gpp.sms+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.3gpp.srvcc-ext+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.3gpp.srvcc-info+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.3gpp.state-and-event-info+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.3gpp.ussd+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.3gpp2.bcmcsinfo+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.3gpp2.sms\":{\"source\":\"iana\"},\"application/vnd.3gpp2.tcap\":{\"source\":\"iana\",\"extensions\":[\"tcap\"]},\"application/vnd.3lightssoftware.imagescal\":{\"source\":\"iana\"},\"application/vnd.3m.post-it-notes\":{\"source\":\"iana\",\"extensions\":[\"pwn\"]},\"application/vnd.accpac.simply.aso\":{\"source\":\"iana\",\"extensions\":[\"aso\"]},\"application/vnd.accpac.simply.imp\":{\"source\":\"iana\",\"extensions\":[\"imp\"]},\"application/vnd.acucobol\":{\"source\":\"iana\",\"extensions\":[\"acu\"]},\"application/vnd.acucorp\":{\"source\":\"iana\",\"extensions\":[\"atc\",\"acutc\"]},\"application/vnd.adobe.air-application-installer-package+zip\":{\"source\":\"apache\",\"compressible\":false,\"extensions\":[\"air\"]},\"application/vnd.adobe.flash.movie\":{\"source\":\"iana\"},\"application/vnd.adobe.formscentral.fcdt\":{\"source\":\"iana\",\"extensions\":[\"fcdt\"]},\"application/vnd.adobe.fxp\":{\"source\":\"iana\",\"extensions\":[\"fxp\",\"fxpl\"]},\"application/vnd.adobe.partial-upload\":{\"source\":\"iana\"},\"application/vnd.adobe.xdp+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"xdp\"]},\"application/vnd.adobe.xfdf\":{\"source\":\"iana\",\"extensions\":[\"xfdf\"]},\"application/vnd.aether.imp\":{\"source\":\"iana\"},\"application/vnd.afpc.afplinedata\":{\"source\":\"iana\"},\"application/vnd.afpc.afplinedata-pagedef\":{\"source\":\"iana\"},\"application/vnd.afpc.foca-charset\":{\"source\":\"iana\"},\"application/vnd.afpc.foca-codedfont\":{\"source\":\"iana\"},\"application/vnd.afpc.foca-codepage\":{\"source\":\"iana\"},\"application/vnd.afpc.modca\":{\"source\":\"iana\"},\"application/vnd.afpc.modca-formdef\":{\"source\":\"iana\"},\"application/vnd.afpc.modca-mediummap\":{\"source\":\"iana\"},\"application/vnd.afpc.modca-objectcontainer\":{\"source\":\"iana\"},\"application/vnd.afpc.modca-overlay\":{\"source\":\"iana\"},\"application/vnd.afpc.modca-pagesegment\":{\"source\":\"iana\"},\"application/vnd.ah-barcode\":{\"source\":\"iana\"},\"application/vnd.ahead.space\":{\"source\":\"iana\",\"extensions\":[\"ahead\"]},\"application/vnd.airzip.filesecure.azf\":{\"source\":\"iana\",\"extensions\":[\"azf\"]},\"application/vnd.airzip.filesecure.azs\":{\"source\":\"iana\",\"extensions\":[\"azs\"]},\"application/vnd.amadeus+json\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.amazon.ebook\":{\"source\":\"apache\",\"extensions\":[\"azw\"]},\"application/vnd.amazon.mobi8-ebook\":{\"source\":\"iana\"},\"application/vnd.americandynamics.acc\":{\"source\":\"iana\",\"extensions\":[\"acc\"]},\"application/vnd.amiga.ami\":{\"source\":\"iana\",\"extensions\":[\"ami\"]},\"application/vnd.amundsen.maze+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.android.ota\":{\"source\":\"iana\"},\"application/vnd.android.package-archive\":{\"source\":\"apache\",\"compressible\":false,\"extensions\":[\"apk\"]},\"application/vnd.anki\":{\"source\":\"iana\"},\"application/vnd.anser-web-certificate-issue-initiation\":{\"source\":\"iana\",\"extensions\":[\"cii\"]},\"application/vnd.anser-web-funds-transfer-initiation\":{\"source\":\"apache\",\"extensions\":[\"fti\"]},\"application/vnd.antix.game-component\":{\"source\":\"iana\",\"extensions\":[\"atx\"]},\"application/vnd.apache.thrift.binary\":{\"source\":\"iana\"},\"application/vnd.apache.thrift.compact\":{\"source\":\"iana\"},\"application/vnd.apache.thrift.json\":{\"source\":\"iana\"},\"application/vnd.api+json\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.aplextor.warrp+json\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.apothekende.reservation+json\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.apple.installer+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"mpkg\"]},\"application/vnd.apple.keynote\":{\"source\":\"iana\",\"extensions\":[\"keynote\"]},\"application/vnd.apple.mpegurl\":{\"source\":\"iana\",\"extensions\":[\"m3u8\"]},\"application/vnd.apple.numbers\":{\"source\":\"iana\",\"extensions\":[\"numbers\"]},\"application/vnd.apple.pages\":{\"source\":\"iana\",\"extensions\":[\"pages\"]},\"application/vnd.apple.pkpass\":{\"compressible\":false,\"extensions\":[\"pkpass\"]},\"application/vnd.arastra.swi\":{\"source\":\"iana\"},\"application/vnd.aristanetworks.swi\":{\"source\":\"iana\",\"extensions\":[\"swi\"]},\"application/vnd.artisan+json\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.artsquare\":{\"source\":\"iana\"},\"application/vnd.astraea-software.iota\":{\"source\":\"iana\",\"extensions\":[\"iota\"]},\"application/vnd.audiograph\":{\"source\":\"iana\",\"extensions\":[\"aep\"]},\"application/vnd.autopackage\":{\"source\":\"iana\"},\"application/vnd.avalon+json\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.avistar+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.balsamiq.bmml+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"bmml\"]},\"application/vnd.balsamiq.bmpr\":{\"source\":\"iana\"},\"application/vnd.banana-accounting\":{\"source\":\"iana\"},\"application/vnd.bbf.usp.error\":{\"source\":\"iana\"},\"application/vnd.bbf.usp.msg\":{\"source\":\"iana\"},\"application/vnd.bbf.usp.msg+json\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.bekitzur-stech+json\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.bint.med-content\":{\"source\":\"iana\"},\"application/vnd.biopax.rdf+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.blink-idb-value-wrapper\":{\"source\":\"iana\"},\"application/vnd.blueice.multipass\":{\"source\":\"iana\",\"extensions\":[\"mpm\"]},\"application/vnd.bluetooth.ep.oob\":{\"source\":\"iana\"},\"application/vnd.bluetooth.le.oob\":{\"source\":\"iana\"},\"application/vnd.bmi\":{\"source\":\"iana\",\"extensions\":[\"bmi\"]},\"application/vnd.bpf\":{\"source\":\"iana\"},\"application/vnd.bpf3\":{\"source\":\"iana\"},\"application/vnd.businessobjects\":{\"source\":\"iana\",\"extensions\":[\"rep\"]},\"application/vnd.byu.uapi+json\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.cab-jscript\":{\"source\":\"iana\"},\"application/vnd.canon-cpdl\":{\"source\":\"iana\"},\"application/vnd.canon-lips\":{\"source\":\"iana\"},\"application/vnd.capasystems-pg+json\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.cendio.thinlinc.clientconf\":{\"source\":\"iana\"},\"application/vnd.century-systems.tcp_stream\":{\"source\":\"iana\"},\"application/vnd.chemdraw+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"cdxml\"]},\"application/vnd.chess-pgn\":{\"source\":\"iana\"},\"application/vnd.chipnuts.karaoke-mmd\":{\"source\":\"iana\",\"extensions\":[\"mmd\"]},\"application/vnd.ciedi\":{\"source\":\"iana\"},\"application/vnd.cinderella\":{\"source\":\"iana\",\"extensions\":[\"cdy\"]},\"application/vnd.cirpack.isdn-ext\":{\"source\":\"iana\"},\"application/vnd.citationstyles.style+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"csl\"]},\"application/vnd.claymore\":{\"source\":\"iana\",\"extensions\":[\"cla\"]},\"application/vnd.cloanto.rp9\":{\"source\":\"iana\",\"extensions\":[\"rp9\"]},\"application/vnd.clonk.c4group\":{\"source\":\"iana\",\"extensions\":[\"c4g\",\"c4d\",\"c4f\",\"c4p\",\"c4u\"]},\"application/vnd.cluetrust.cartomobile-config\":{\"source\":\"iana\",\"extensions\":[\"c11amc\"]},\"application/vnd.cluetrust.cartomobile-config-pkg\":{\"source\":\"iana\",\"extensions\":[\"c11amz\"]},\"application/vnd.coffeescript\":{\"source\":\"iana\"},\"application/vnd.collabio.xodocuments.document\":{\"source\":\"iana\"},\"application/vnd.collabio.xodocuments.document-template\":{\"source\":\"iana\"},\"application/vnd.collabio.xodocuments.presentation\":{\"source\":\"iana\"},\"application/vnd.collabio.xodocuments.presentation-template\":{\"source\":\"iana\"},\"application/vnd.collabio.xodocuments.spreadsheet\":{\"source\":\"iana\"},\"application/vnd.collabio.xodocuments.spreadsheet-template\":{\"source\":\"iana\"},\"application/vnd.collection+json\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.collection.doc+json\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.collection.next+json\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.comicbook+zip\":{\"source\":\"iana\",\"compressible\":false},\"application/vnd.comicbook-rar\":{\"source\":\"iana\"},\"application/vnd.commerce-battelle\":{\"source\":\"iana\"},\"application/vnd.commonspace\":{\"source\":\"iana\",\"extensions\":[\"csp\"]},\"application/vnd.contact.cmsg\":{\"source\":\"iana\",\"extensions\":[\"cdbcmsg\"]},\"application/vnd.coreos.ignition+json\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.cosmocaller\":{\"source\":\"iana\",\"extensions\":[\"cmc\"]},\"application/vnd.crick.clicker\":{\"source\":\"iana\",\"extensions\":[\"clkx\"]},\"application/vnd.crick.clicker.keyboard\":{\"source\":\"iana\",\"extensions\":[\"clkk\"]},\"application/vnd.crick.clicker.palette\":{\"source\":\"iana\",\"extensions\":[\"clkp\"]},\"application/vnd.crick.clicker.template\":{\"source\":\"iana\",\"extensions\":[\"clkt\"]},\"application/vnd.crick.clicker.wordbank\":{\"source\":\"iana\",\"extensions\":[\"clkw\"]},\"application/vnd.criticaltools.wbs+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"wbs\"]},\"application/vnd.cryptii.pipe+json\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.crypto-shade-file\":{\"source\":\"iana\"},\"application/vnd.ctc-posml\":{\"source\":\"iana\",\"extensions\":[\"pml\"]},\"application/vnd.ctct.ws+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.cups-pdf\":{\"source\":\"iana\"},\"application/vnd.cups-postscript\":{\"source\":\"iana\"},\"application/vnd.cups-ppd\":{\"source\":\"iana\",\"extensions\":[\"ppd\"]},\"application/vnd.cups-raster\":{\"source\":\"iana\"},\"application/vnd.cups-raw\":{\"source\":\"iana\"},\"application/vnd.curl\":{\"source\":\"iana\"},\"application/vnd.curl.car\":{\"source\":\"apache\",\"extensions\":[\"car\"]},\"application/vnd.curl.pcurl\":{\"source\":\"apache\",\"extensions\":[\"pcurl\"]},\"application/vnd.cyan.dean.root+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.cybank\":{\"source\":\"iana\"},\"application/vnd.d2l.coursepackage1p0+zip\":{\"source\":\"iana\",\"compressible\":false},\"application/vnd.dart\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"dart\"]},\"application/vnd.data-vision.rdz\":{\"source\":\"iana\",\"extensions\":[\"rdz\"]},\"application/vnd.datapackage+json\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.dataresource+json\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.dbf\":{\"source\":\"iana\"},\"application/vnd.debian.binary-package\":{\"source\":\"iana\"},\"application/vnd.dece.data\":{\"source\":\"iana\",\"extensions\":[\"uvf\",\"uvvf\",\"uvd\",\"uvvd\"]},\"application/vnd.dece.ttml+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"uvt\",\"uvvt\"]},\"application/vnd.dece.unspecified\":{\"source\":\"iana\",\"extensions\":[\"uvx\",\"uvvx\"]},\"application/vnd.dece.zip\":{\"source\":\"iana\",\"extensions\":[\"uvz\",\"uvvz\"]},\"application/vnd.denovo.fcselayout-link\":{\"source\":\"iana\",\"extensions\":[\"fe_launch\"]},\"application/vnd.desmume.movie\":{\"source\":\"iana\"},\"application/vnd.dir-bi.plate-dl-nosuffix\":{\"source\":\"iana\"},\"application/vnd.dm.delegation+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.dna\":{\"source\":\"iana\",\"extensions\":[\"dna\"]},\"application/vnd.document+json\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.dolby.mlp\":{\"source\":\"apache\",\"extensions\":[\"mlp\"]},\"application/vnd.dolby.mobile.1\":{\"source\":\"iana\"},\"application/vnd.dolby.mobile.2\":{\"source\":\"iana\"},\"application/vnd.doremir.scorecloud-binary-document\":{\"source\":\"iana\"},\"application/vnd.dpgraph\":{\"source\":\"iana\",\"extensions\":[\"dpg\"]},\"application/vnd.dreamfactory\":{\"source\":\"iana\",\"extensions\":[\"dfac\"]},\"application/vnd.drive+json\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.ds-keypoint\":{\"source\":\"apache\",\"extensions\":[\"kpxx\"]},\"application/vnd.dtg.local\":{\"source\":\"iana\"},\"application/vnd.dtg.local.flash\":{\"source\":\"iana\"},\"application/vnd.dtg.local.html\":{\"source\":\"iana\"},\"application/vnd.dvb.ait\":{\"source\":\"iana\",\"extensions\":[\"ait\"]},\"application/vnd.dvb.dvbisl+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.dvb.dvbj\":{\"source\":\"iana\"},\"application/vnd.dvb.esgcontainer\":{\"source\":\"iana\"},\"application/vnd.dvb.ipdcdftnotifaccess\":{\"source\":\"iana\"},\"application/vnd.dvb.ipdcesgaccess\":{\"source\":\"iana\"},\"application/vnd.dvb.ipdcesgaccess2\":{\"source\":\"iana\"},\"application/vnd.dvb.ipdcesgpdd\":{\"source\":\"iana\"},\"application/vnd.dvb.ipdcroaming\":{\"source\":\"iana\"},\"application/vnd.dvb.iptv.alfec-base\":{\"source\":\"iana\"},\"application/vnd.dvb.iptv.alfec-enhancement\":{\"source\":\"iana\"},\"application/vnd.dvb.notif-aggregate-root+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.dvb.notif-container+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.dvb.notif-generic+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.dvb.notif-ia-msglist+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.dvb.notif-ia-registration-request+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.dvb.notif-ia-registration-response+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.dvb.notif-init+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.dvb.pfr\":{\"source\":\"iana\"},\"application/vnd.dvb.service\":{\"source\":\"iana\",\"extensions\":[\"svc\"]},\"application/vnd.dxr\":{\"source\":\"iana\"},\"application/vnd.dynageo\":{\"source\":\"iana\",\"extensions\":[\"geo\"]},\"application/vnd.dzr\":{\"source\":\"iana\"},\"application/vnd.easykaraoke.cdgdownload\":{\"source\":\"iana\"},\"application/vnd.ecdis-update\":{\"source\":\"iana\"},\"application/vnd.ecip.rlp\":{\"source\":\"iana\"},\"application/vnd.ecowin.chart\":{\"source\":\"iana\",\"extensions\":[\"mag\"]},\"application/vnd.ecowin.filerequest\":{\"source\":\"iana\"},\"application/vnd.ecowin.fileupdate\":{\"source\":\"iana\"},\"application/vnd.ecowin.series\":{\"source\":\"iana\"},\"application/vnd.ecowin.seriesrequest\":{\"source\":\"iana\"},\"application/vnd.ecowin.seriesupdate\":{\"source\":\"iana\"},\"application/vnd.efi.img\":{\"source\":\"iana\"},\"application/vnd.efi.iso\":{\"source\":\"iana\"},\"application/vnd.emclient.accessrequest+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.enliven\":{\"source\":\"iana\",\"extensions\":[\"nml\"]},\"application/vnd.enphase.envoy\":{\"source\":\"iana\"},\"application/vnd.eprints.data+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.epson.esf\":{\"source\":\"iana\",\"extensions\":[\"esf\"]},\"application/vnd.epson.msf\":{\"source\":\"iana\",\"extensions\":[\"msf\"]},\"application/vnd.epson.quickanime\":{\"source\":\"iana\",\"extensions\":[\"qam\"]},\"application/vnd.epson.salt\":{\"source\":\"iana\",\"extensions\":[\"slt\"]},\"application/vnd.epson.ssf\":{\"source\":\"iana\",\"extensions\":[\"ssf\"]},\"application/vnd.ericsson.quickcall\":{\"source\":\"iana\"},\"application/vnd.espass-espass+zip\":{\"source\":\"iana\",\"compressible\":false},\"application/vnd.eszigno3+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"es3\",\"et3\"]},\"application/vnd.etsi.aoc+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.etsi.asic-e+zip\":{\"source\":\"iana\",\"compressible\":false},\"application/vnd.etsi.asic-s+zip\":{\"source\":\"iana\",\"compressible\":false},\"application/vnd.etsi.cug+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.etsi.iptvcommand+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.etsi.iptvdiscovery+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.etsi.iptvprofile+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.etsi.iptvsad-bc+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.etsi.iptvsad-cod+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.etsi.iptvsad-npvr+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.etsi.iptvservice+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.etsi.iptvsync+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.etsi.iptvueprofile+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.etsi.mcid+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.etsi.mheg5\":{\"source\":\"iana\"},\"application/vnd.etsi.overload-control-policy-dataset+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.etsi.pstn+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.etsi.sci+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.etsi.simservs+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.etsi.timestamp-token\":{\"source\":\"iana\"},\"application/vnd.etsi.tsl+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.etsi.tsl.der\":{\"source\":\"iana\"},\"application/vnd.eudora.data\":{\"source\":\"iana\"},\"application/vnd.evolv.ecig.profile\":{\"source\":\"iana\"},\"application/vnd.evolv.ecig.settings\":{\"source\":\"iana\"},\"application/vnd.evolv.ecig.theme\":{\"source\":\"iana\"},\"application/vnd.exstream-empower+zip\":{\"source\":\"iana\",\"compressible\":false},\"application/vnd.exstream-package\":{\"source\":\"iana\"},\"application/vnd.ezpix-album\":{\"source\":\"iana\",\"extensions\":[\"ez2\"]},\"application/vnd.ezpix-package\":{\"source\":\"iana\",\"extensions\":[\"ez3\"]},\"application/vnd.f-secure.mobile\":{\"source\":\"iana\"},\"application/vnd.fastcopy-disk-image\":{\"source\":\"iana\"},\"application/vnd.fdf\":{\"source\":\"iana\",\"extensions\":[\"fdf\"]},\"application/vnd.fdsn.mseed\":{\"source\":\"iana\",\"extensions\":[\"mseed\"]},\"application/vnd.fdsn.seed\":{\"source\":\"iana\",\"extensions\":[\"seed\",\"dataless\"]},\"application/vnd.ffsns\":{\"source\":\"iana\"},\"application/vnd.ficlab.flb+zip\":{\"source\":\"iana\",\"compressible\":false},\"application/vnd.filmit.zfc\":{\"source\":\"iana\"},\"application/vnd.fints\":{\"source\":\"iana\"},\"application/vnd.firemonkeys.cloudcell\":{\"source\":\"iana\"},\"application/vnd.flographit\":{\"source\":\"iana\",\"extensions\":[\"gph\"]},\"application/vnd.fluxtime.clip\":{\"source\":\"iana\",\"extensions\":[\"ftc\"]},\"application/vnd.font-fontforge-sfd\":{\"source\":\"iana\"},\"application/vnd.framemaker\":{\"source\":\"iana\",\"extensions\":[\"fm\",\"frame\",\"maker\",\"book\"]},\"application/vnd.frogans.fnc\":{\"source\":\"iana\",\"extensions\":[\"fnc\"]},\"application/vnd.frogans.ltf\":{\"source\":\"iana\",\"extensions\":[\"ltf\"]},\"application/vnd.fsc.weblaunch\":{\"source\":\"iana\",\"extensions\":[\"fsc\"]},\"application/vnd.fujitsu.oasys\":{\"source\":\"iana\",\"extensions\":[\"oas\"]},\"application/vnd.fujitsu.oasys2\":{\"source\":\"iana\",\"extensions\":[\"oa2\"]},\"application/vnd.fujitsu.oasys3\":{\"source\":\"iana\",\"extensions\":[\"oa3\"]},\"application/vnd.fujitsu.oasysgp\":{\"source\":\"iana\",\"extensions\":[\"fg5\"]},\"application/vnd.fujitsu.oasysprs\":{\"source\":\"iana\",\"extensions\":[\"bh2\"]},\"application/vnd.fujixerox.art-ex\":{\"source\":\"iana\"},\"application/vnd.fujixerox.art4\":{\"source\":\"iana\"},\"application/vnd.fujixerox.ddd\":{\"source\":\"iana\",\"extensions\":[\"ddd\"]},\"application/vnd.fujixerox.docuworks\":{\"source\":\"iana\",\"extensions\":[\"xdw\"]},\"application/vnd.fujixerox.docuworks.binder\":{\"source\":\"iana\",\"extensions\":[\"xbd\"]},\"application/vnd.fujixerox.docuworks.container\":{\"source\":\"iana\"},\"application/vnd.fujixerox.hbpl\":{\"source\":\"iana\"},\"application/vnd.fut-misnet\":{\"source\":\"iana\"},\"application/vnd.futoin+cbor\":{\"source\":\"iana\"},\"application/vnd.futoin+json\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.fuzzysheet\":{\"source\":\"iana\",\"extensions\":[\"fzs\"]},\"application/vnd.genomatix.tuxedo\":{\"source\":\"iana\",\"extensions\":[\"txd\"]},\"application/vnd.gentics.grd+json\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.geo+json\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.geocube+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.geogebra.file\":{\"source\":\"iana\",\"extensions\":[\"ggb\"]},\"application/vnd.geogebra.tool\":{\"source\":\"iana\",\"extensions\":[\"ggt\"]},\"application/vnd.geometry-explorer\":{\"source\":\"iana\",\"extensions\":[\"gex\",\"gre\"]},\"application/vnd.geonext\":{\"source\":\"iana\",\"extensions\":[\"gxt\"]},\"application/vnd.geoplan\":{\"source\":\"iana\",\"extensions\":[\"g2w\"]},\"application/vnd.geospace\":{\"source\":\"iana\",\"extensions\":[\"g3w\"]},\"application/vnd.gerber\":{\"source\":\"iana\"},\"application/vnd.globalplatform.card-content-mgt\":{\"source\":\"iana\"},\"application/vnd.globalplatform.card-content-mgt-response\":{\"source\":\"iana\"},\"application/vnd.gmx\":{\"source\":\"iana\",\"extensions\":[\"gmx\"]},\"application/vnd.google-apps.document\":{\"compressible\":false,\"extensions\":[\"gdoc\"]},\"application/vnd.google-apps.presentation\":{\"compressible\":false,\"extensions\":[\"gslides\"]},\"application/vnd.google-apps.spreadsheet\":{\"compressible\":false,\"extensions\":[\"gsheet\"]},\"application/vnd.google-earth.kml+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"kml\"]},\"application/vnd.google-earth.kmz\":{\"source\":\"iana\",\"compressible\":false,\"extensions\":[\"kmz\"]},\"application/vnd.gov.sk.e-form+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.gov.sk.e-form+zip\":{\"source\":\"iana\",\"compressible\":false},\"application/vnd.gov.sk.xmldatacontainer+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.grafeq\":{\"source\":\"iana\",\"extensions\":[\"gqf\",\"gqs\"]},\"application/vnd.gridmp\":{\"source\":\"iana\"},\"application/vnd.groove-account\":{\"source\":\"iana\",\"extensions\":[\"gac\"]},\"application/vnd.groove-help\":{\"source\":\"iana\",\"extensions\":[\"ghf\"]},\"application/vnd.groove-identity-message\":{\"source\":\"iana\",\"extensions\":[\"gim\"]},\"application/vnd.groove-injector\":{\"source\":\"iana\",\"extensions\":[\"grv\"]},\"application/vnd.groove-tool-message\":{\"source\":\"iana\",\"extensions\":[\"gtm\"]},\"application/vnd.groove-tool-template\":{\"source\":\"iana\",\"extensions\":[\"tpl\"]},\"application/vnd.groove-vcard\":{\"source\":\"iana\",\"extensions\":[\"vcg\"]},\"application/vnd.hal+json\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.hal+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"hal\"]},\"application/vnd.handheld-entertainment+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"zmm\"]},\"application/vnd.hbci\":{\"source\":\"iana\",\"extensions\":[\"hbci\"]},\"application/vnd.hc+json\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.hcl-bireports\":{\"source\":\"iana\"},\"application/vnd.hdt\":{\"source\":\"iana\"},\"application/vnd.heroku+json\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.hhe.lesson-player\":{\"source\":\"iana\",\"extensions\":[\"les\"]},\"application/vnd.hp-hpgl\":{\"source\":\"iana\",\"extensions\":[\"hpgl\"]},\"application/vnd.hp-hpid\":{\"source\":\"iana\",\"extensions\":[\"hpid\"]},\"application/vnd.hp-hps\":{\"source\":\"iana\",\"extensions\":[\"hps\"]},\"application/vnd.hp-jlyt\":{\"source\":\"iana\",\"extensions\":[\"jlt\"]},\"application/vnd.hp-pcl\":{\"source\":\"iana\",\"extensions\":[\"pcl\"]},\"application/vnd.hp-pclxl\":{\"source\":\"iana\",\"extensions\":[\"pclxl\"]},\"application/vnd.httphone\":{\"source\":\"iana\"},\"application/vnd.hydrostatix.sof-data\":{\"source\":\"iana\",\"extensions\":[\"sfd-hdstx\"]},\"application/vnd.hyper+json\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.hyper-item+json\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.hyperdrive+json\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.hzn-3d-crossword\":{\"source\":\"iana\"},\"application/vnd.ibm.afplinedata\":{\"source\":\"iana\"},\"application/vnd.ibm.electronic-media\":{\"source\":\"iana\"},\"application/vnd.ibm.minipay\":{\"source\":\"iana\",\"extensions\":[\"mpy\"]},\"application/vnd.ibm.modcap\":{\"source\":\"iana\",\"extensions\":[\"afp\",\"listafp\",\"list3820\"]},\"application/vnd.ibm.rights-management\":{\"source\":\"iana\",\"extensions\":[\"irm\"]},\"application/vnd.ibm.secure-container\":{\"source\":\"iana\",\"extensions\":[\"sc\"]},\"application/vnd.iccprofile\":{\"source\":\"iana\",\"extensions\":[\"icc\",\"icm\"]},\"application/vnd.ieee.1905\":{\"source\":\"iana\"},\"application/vnd.igloader\":{\"source\":\"iana\",\"extensions\":[\"igl\"]},\"application/vnd.imagemeter.folder+zip\":{\"source\":\"iana\",\"compressible\":false},\"application/vnd.imagemeter.image+zip\":{\"source\":\"iana\",\"compressible\":false},\"application/vnd.immervision-ivp\":{\"source\":\"iana\",\"extensions\":[\"ivp\"]},\"application/vnd.immervision-ivu\":{\"source\":\"iana\",\"extensions\":[\"ivu\"]},\"application/vnd.ims.imsccv1p1\":{\"source\":\"iana\"},\"application/vnd.ims.imsccv1p2\":{\"source\":\"iana\"},\"application/vnd.ims.imsccv1p3\":{\"source\":\"iana\"},\"application/vnd.ims.lis.v2.result+json\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.ims.lti.v2.toolconsumerprofile+json\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.ims.lti.v2.toolproxy+json\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.ims.lti.v2.toolproxy.id+json\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.ims.lti.v2.toolsettings+json\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.ims.lti.v2.toolsettings.simple+json\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.informedcontrol.rms+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.informix-visionary\":{\"source\":\"iana\"},\"application/vnd.infotech.project\":{\"source\":\"iana\"},\"application/vnd.infotech.project+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.innopath.wamp.notification\":{\"source\":\"iana\"},\"application/vnd.insors.igm\":{\"source\":\"iana\",\"extensions\":[\"igm\"]},\"application/vnd.intercon.formnet\":{\"source\":\"iana\",\"extensions\":[\"xpw\",\"xpx\"]},\"application/vnd.intergeo\":{\"source\":\"iana\",\"extensions\":[\"i2g\"]},\"application/vnd.intertrust.digibox\":{\"source\":\"iana\"},\"application/vnd.intertrust.nncp\":{\"source\":\"iana\"},\"application/vnd.intu.qbo\":{\"source\":\"iana\",\"extensions\":[\"qbo\"]},\"application/vnd.intu.qfx\":{\"source\":\"iana\",\"extensions\":[\"qfx\"]},\"application/vnd.iptc.g2.catalogitem+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.iptc.g2.conceptitem+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.iptc.g2.knowledgeitem+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.iptc.g2.newsitem+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.iptc.g2.newsmessage+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.iptc.g2.packageitem+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.iptc.g2.planningitem+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.ipunplugged.rcprofile\":{\"source\":\"iana\",\"extensions\":[\"rcprofile\"]},\"application/vnd.irepository.package+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"irp\"]},\"application/vnd.is-xpr\":{\"source\":\"iana\",\"extensions\":[\"xpr\"]},\"application/vnd.isac.fcs\":{\"source\":\"iana\",\"extensions\":[\"fcs\"]},\"application/vnd.iso11783-10+zip\":{\"source\":\"iana\",\"compressible\":false},\"application/vnd.jam\":{\"source\":\"iana\",\"extensions\":[\"jam\"]},\"application/vnd.japannet-directory-service\":{\"source\":\"iana\"},\"application/vnd.japannet-jpnstore-wakeup\":{\"source\":\"iana\"},\"application/vnd.japannet-payment-wakeup\":{\"source\":\"iana\"},\"application/vnd.japannet-registration\":{\"source\":\"iana\"},\"application/vnd.japannet-registration-wakeup\":{\"source\":\"iana\"},\"application/vnd.japannet-setstore-wakeup\":{\"source\":\"iana\"},\"application/vnd.japannet-verification\":{\"source\":\"iana\"},\"application/vnd.japannet-verification-wakeup\":{\"source\":\"iana\"},\"application/vnd.jcp.javame.midlet-rms\":{\"source\":\"iana\",\"extensions\":[\"rms\"]},\"application/vnd.jisp\":{\"source\":\"iana\",\"extensions\":[\"jisp\"]},\"application/vnd.joost.joda-archive\":{\"source\":\"iana\",\"extensions\":[\"joda\"]},\"application/vnd.jsk.isdn-ngn\":{\"source\":\"iana\"},\"application/vnd.kahootz\":{\"source\":\"iana\",\"extensions\":[\"ktz\",\"ktr\"]},\"application/vnd.kde.karbon\":{\"source\":\"iana\",\"extensions\":[\"karbon\"]},\"application/vnd.kde.kchart\":{\"source\":\"iana\",\"extensions\":[\"chrt\"]},\"application/vnd.kde.kformula\":{\"source\":\"iana\",\"extensions\":[\"kfo\"]},\"application/vnd.kde.kivio\":{\"source\":\"iana\",\"extensions\":[\"flw\"]},\"application/vnd.kde.kontour\":{\"source\":\"iana\",\"extensions\":[\"kon\"]},\"application/vnd.kde.kpresenter\":{\"source\":\"iana\",\"extensions\":[\"kpr\",\"kpt\"]},\"application/vnd.kde.kspread\":{\"source\":\"iana\",\"extensions\":[\"ksp\"]},\"application/vnd.kde.kword\":{\"source\":\"iana\",\"extensions\":[\"kwd\",\"kwt\"]},\"application/vnd.kenameaapp\":{\"source\":\"iana\",\"extensions\":[\"htke\"]},\"application/vnd.kidspiration\":{\"source\":\"iana\",\"extensions\":[\"kia\"]},\"application/vnd.kinar\":{\"source\":\"iana\",\"extensions\":[\"kne\",\"knp\"]},\"application/vnd.koan\":{\"source\":\"iana\",\"extensions\":[\"skp\",\"skd\",\"skt\",\"skm\"]},\"application/vnd.kodak-descriptor\":{\"source\":\"iana\",\"extensions\":[\"sse\"]},\"application/vnd.las\":{\"source\":\"iana\"},\"application/vnd.las.las+json\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.las.las+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"lasxml\"]},\"application/vnd.laszip\":{\"source\":\"iana\"},\"application/vnd.leap+json\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.liberty-request+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.llamagraphics.life-balance.desktop\":{\"source\":\"iana\",\"extensions\":[\"lbd\"]},\"application/vnd.llamagraphics.life-balance.exchange+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"lbe\"]},\"application/vnd.logipipe.circuit+zip\":{\"source\":\"iana\",\"compressible\":false},\"application/vnd.loom\":{\"source\":\"iana\"},\"application/vnd.lotus-1-2-3\":{\"source\":\"iana\",\"extensions\":[\"123\"]},\"application/vnd.lotus-approach\":{\"source\":\"iana\",\"extensions\":[\"apr\"]},\"application/vnd.lotus-freelance\":{\"source\":\"iana\",\"extensions\":[\"pre\"]},\"application/vnd.lotus-notes\":{\"source\":\"iana\",\"extensions\":[\"nsf\"]},\"application/vnd.lotus-organizer\":{\"source\":\"iana\",\"extensions\":[\"org\"]},\"application/vnd.lotus-screencam\":{\"source\":\"iana\",\"extensions\":[\"scm\"]},\"application/vnd.lotus-wordpro\":{\"source\":\"iana\",\"extensions\":[\"lwp\"]},\"application/vnd.macports.portpkg\":{\"source\":\"iana\",\"extensions\":[\"portpkg\"]},\"application/vnd.mapbox-vector-tile\":{\"source\":\"iana\"},\"application/vnd.marlin.drm.actiontoken+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.marlin.drm.conftoken+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.marlin.drm.license+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.marlin.drm.mdcf\":{\"source\":\"iana\"},\"application/vnd.mason+json\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.maxmind.maxmind-db\":{\"source\":\"iana\"},\"application/vnd.mcd\":{\"source\":\"iana\",\"extensions\":[\"mcd\"]},\"application/vnd.medcalcdata\":{\"source\":\"iana\",\"extensions\":[\"mc1\"]},\"application/vnd.mediastation.cdkey\":{\"source\":\"iana\",\"extensions\":[\"cdkey\"]},\"application/vnd.meridian-slingshot\":{\"source\":\"iana\"},\"application/vnd.mfer\":{\"source\":\"iana\",\"extensions\":[\"mwf\"]},\"application/vnd.mfmp\":{\"source\":\"iana\",\"extensions\":[\"mfm\"]},\"application/vnd.micro+json\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.micrografx.flo\":{\"source\":\"iana\",\"extensions\":[\"flo\"]},\"application/vnd.micrografx.igx\":{\"source\":\"iana\",\"extensions\":[\"igx\"]},\"application/vnd.microsoft.portable-executable\":{\"source\":\"iana\"},\"application/vnd.microsoft.windows.thumbnail-cache\":{\"source\":\"iana\"},\"application/vnd.miele+json\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.mif\":{\"source\":\"iana\",\"extensions\":[\"mif\"]},\"application/vnd.minisoft-hp3000-save\":{\"source\":\"iana\"},\"application/vnd.mitsubishi.misty-guard.trustweb\":{\"source\":\"iana\"},\"application/vnd.mobius.daf\":{\"source\":\"iana\",\"extensions\":[\"daf\"]},\"application/vnd.mobius.dis\":{\"source\":\"iana\",\"extensions\":[\"dis\"]},\"application/vnd.mobius.mbk\":{\"source\":\"iana\",\"extensions\":[\"mbk\"]},\"application/vnd.mobius.mqy\":{\"source\":\"iana\",\"extensions\":[\"mqy\"]},\"application/vnd.mobius.msl\":{\"source\":\"iana\",\"extensions\":[\"msl\"]},\"application/vnd.mobius.plc\":{\"source\":\"iana\",\"extensions\":[\"plc\"]},\"application/vnd.mobius.txf\":{\"source\":\"iana\",\"extensions\":[\"txf\"]},\"application/vnd.mophun.application\":{\"source\":\"iana\",\"extensions\":[\"mpn\"]},\"application/vnd.mophun.certificate\":{\"source\":\"iana\",\"extensions\":[\"mpc\"]},\"application/vnd.motorola.flexsuite\":{\"source\":\"iana\"},\"application/vnd.motorola.flexsuite.adsi\":{\"source\":\"iana\"},\"application/vnd.motorola.flexsuite.fis\":{\"source\":\"iana\"},\"application/vnd.motorola.flexsuite.gotap\":{\"source\":\"iana\"},\"application/vnd.motorola.flexsuite.kmr\":{\"source\":\"iana\"},\"application/vnd.motorola.flexsuite.ttc\":{\"source\":\"iana\"},\"application/vnd.motorola.flexsuite.wem\":{\"source\":\"iana\"},\"application/vnd.motorola.iprm\":{\"source\":\"iana\"},\"application/vnd.mozilla.xul+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"xul\"]},\"application/vnd.ms-3mfdocument\":{\"source\":\"iana\"},\"application/vnd.ms-artgalry\":{\"source\":\"iana\",\"extensions\":[\"cil\"]},\"application/vnd.ms-asf\":{\"source\":\"iana\"},\"application/vnd.ms-cab-compressed\":{\"source\":\"iana\",\"extensions\":[\"cab\"]},\"application/vnd.ms-color.iccprofile\":{\"source\":\"apache\"},\"application/vnd.ms-excel\":{\"source\":\"iana\",\"compressible\":false,\"extensions\":[\"xls\",\"xlm\",\"xla\",\"xlc\",\"xlt\",\"xlw\"]},\"application/vnd.ms-excel.addin.macroenabled.12\":{\"source\":\"iana\",\"extensions\":[\"xlam\"]},\"application/vnd.ms-excel.sheet.binary.macroenabled.12\":{\"source\":\"iana\",\"extensions\":[\"xlsb\"]},\"application/vnd.ms-excel.sheet.macroenabled.12\":{\"source\":\"iana\",\"extensions\":[\"xlsm\"]},\"application/vnd.ms-excel.template.macroenabled.12\":{\"source\":\"iana\",\"extensions\":[\"xltm\"]},\"application/vnd.ms-fontobject\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"eot\"]},\"application/vnd.ms-htmlhelp\":{\"source\":\"iana\",\"extensions\":[\"chm\"]},\"application/vnd.ms-ims\":{\"source\":\"iana\",\"extensions\":[\"ims\"]},\"application/vnd.ms-lrm\":{\"source\":\"iana\",\"extensions\":[\"lrm\"]},\"application/vnd.ms-office.activex+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.ms-officetheme\":{\"source\":\"iana\",\"extensions\":[\"thmx\"]},\"application/vnd.ms-opentype\":{\"source\":\"apache\",\"compressible\":true},\"application/vnd.ms-outlook\":{\"compressible\":false,\"extensions\":[\"msg\"]},\"application/vnd.ms-package.obfuscated-opentype\":{\"source\":\"apache\"},\"application/vnd.ms-pki.seccat\":{\"source\":\"apache\",\"extensions\":[\"cat\"]},\"application/vnd.ms-pki.stl\":{\"source\":\"apache\",\"extensions\":[\"stl\"]},\"application/vnd.ms-playready.initiator+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.ms-powerpoint\":{\"source\":\"iana\",\"compressible\":false,\"extensions\":[\"ppt\",\"pps\",\"pot\"]},\"application/vnd.ms-powerpoint.addin.macroenabled.12\":{\"source\":\"iana\",\"extensions\":[\"ppam\"]},\"application/vnd.ms-powerpoint.presentation.macroenabled.12\":{\"source\":\"iana\",\"extensions\":[\"pptm\"]},\"application/vnd.ms-powerpoint.slide.macroenabled.12\":{\"source\":\"iana\",\"extensions\":[\"sldm\"]},\"application/vnd.ms-powerpoint.slideshow.macroenabled.12\":{\"source\":\"iana\",\"extensions\":[\"ppsm\"]},\"application/vnd.ms-powerpoint.template.macroenabled.12\":{\"source\":\"iana\",\"extensions\":[\"potm\"]},\"application/vnd.ms-printdevicecapabilities+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.ms-printing.printticket+xml\":{\"source\":\"apache\",\"compressible\":true},\"application/vnd.ms-printschematicket+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.ms-project\":{\"source\":\"iana\",\"extensions\":[\"mpp\",\"mpt\"]},\"application/vnd.ms-tnef\":{\"source\":\"iana\"},\"application/vnd.ms-windows.devicepairing\":{\"source\":\"iana\"},\"application/vnd.ms-windows.nwprinting.oob\":{\"source\":\"iana\"},\"application/vnd.ms-windows.printerpairing\":{\"source\":\"iana\"},\"application/vnd.ms-windows.wsd.oob\":{\"source\":\"iana\"},\"application/vnd.ms-wmdrm.lic-chlg-req\":{\"source\":\"iana\"},\"application/vnd.ms-wmdrm.lic-resp\":{\"source\":\"iana\"},\"application/vnd.ms-wmdrm.meter-chlg-req\":{\"source\":\"iana\"},\"application/vnd.ms-wmdrm.meter-resp\":{\"source\":\"iana\"},\"application/vnd.ms-word.document.macroenabled.12\":{\"source\":\"iana\",\"extensions\":[\"docm\"]},\"application/vnd.ms-word.template.macroenabled.12\":{\"source\":\"iana\",\"extensions\":[\"dotm\"]},\"application/vnd.ms-works\":{\"source\":\"iana\",\"extensions\":[\"wps\",\"wks\",\"wcm\",\"wdb\"]},\"application/vnd.ms-wpl\":{\"source\":\"iana\",\"extensions\":[\"wpl\"]},\"application/vnd.ms-xpsdocument\":{\"source\":\"iana\",\"compressible\":false,\"extensions\":[\"xps\"]},\"application/vnd.msa-disk-image\":{\"source\":\"iana\"},\"application/vnd.mseq\":{\"source\":\"iana\",\"extensions\":[\"mseq\"]},\"application/vnd.msign\":{\"source\":\"iana\"},\"application/vnd.multiad.creator\":{\"source\":\"iana\"},\"application/vnd.multiad.creator.cif\":{\"source\":\"iana\"},\"application/vnd.music-niff\":{\"source\":\"iana\"},\"application/vnd.musician\":{\"source\":\"iana\",\"extensions\":[\"mus\"]},\"application/vnd.muvee.style\":{\"source\":\"iana\",\"extensions\":[\"msty\"]},\"application/vnd.mynfc\":{\"source\":\"iana\",\"extensions\":[\"taglet\"]},\"application/vnd.ncd.control\":{\"source\":\"iana\"},\"application/vnd.ncd.reference\":{\"source\":\"iana\"},\"application/vnd.nearst.inv+json\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.nervana\":{\"source\":\"iana\"},\"application/vnd.netfpx\":{\"source\":\"iana\"},\"application/vnd.neurolanguage.nlu\":{\"source\":\"iana\",\"extensions\":[\"nlu\"]},\"application/vnd.nimn\":{\"source\":\"iana\"},\"application/vnd.nintendo.nitro.rom\":{\"source\":\"iana\"},\"application/vnd.nintendo.snes.rom\":{\"source\":\"iana\"},\"application/vnd.nitf\":{\"source\":\"iana\",\"extensions\":[\"ntf\",\"nitf\"]},\"application/vnd.noblenet-directory\":{\"source\":\"iana\",\"extensions\":[\"nnd\"]},\"application/vnd.noblenet-sealer\":{\"source\":\"iana\",\"extensions\":[\"nns\"]},\"application/vnd.noblenet-web\":{\"source\":\"iana\",\"extensions\":[\"nnw\"]},\"application/vnd.nokia.catalogs\":{\"source\":\"iana\"},\"application/vnd.nokia.conml+wbxml\":{\"source\":\"iana\"},\"application/vnd.nokia.conml+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.nokia.iptv.config+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.nokia.isds-radio-presets\":{\"source\":\"iana\"},\"application/vnd.nokia.landmark+wbxml\":{\"source\":\"iana\"},\"application/vnd.nokia.landmark+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.nokia.landmarkcollection+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.nokia.n-gage.ac+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"ac\"]},\"application/vnd.nokia.n-gage.data\":{\"source\":\"iana\",\"extensions\":[\"ngdat\"]},\"application/vnd.nokia.n-gage.symbian.install\":{\"source\":\"iana\",\"extensions\":[\"n-gage\"]},\"application/vnd.nokia.ncd\":{\"source\":\"iana\"},\"application/vnd.nokia.pcd+wbxml\":{\"source\":\"iana\"},\"application/vnd.nokia.pcd+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.nokia.radio-preset\":{\"source\":\"iana\",\"extensions\":[\"rpst\"]},\"application/vnd.nokia.radio-presets\":{\"source\":\"iana\",\"extensions\":[\"rpss\"]},\"application/vnd.novadigm.edm\":{\"source\":\"iana\",\"extensions\":[\"edm\"]},\"application/vnd.novadigm.edx\":{\"source\":\"iana\",\"extensions\":[\"edx\"]},\"application/vnd.novadigm.ext\":{\"source\":\"iana\",\"extensions\":[\"ext\"]},\"application/vnd.ntt-local.content-share\":{\"source\":\"iana\"},\"application/vnd.ntt-local.file-transfer\":{\"source\":\"iana\"},\"application/vnd.ntt-local.ogw_remote-access\":{\"source\":\"iana\"},\"application/vnd.ntt-local.sip-ta_remote\":{\"source\":\"iana\"},\"application/vnd.ntt-local.sip-ta_tcp_stream\":{\"source\":\"iana\"},\"application/vnd.oasis.opendocument.chart\":{\"source\":\"iana\",\"extensions\":[\"odc\"]},\"application/vnd.oasis.opendocument.chart-template\":{\"source\":\"iana\",\"extensions\":[\"otc\"]},\"application/vnd.oasis.opendocument.database\":{\"source\":\"iana\",\"extensions\":[\"odb\"]},\"application/vnd.oasis.opendocument.formula\":{\"source\":\"iana\",\"extensions\":[\"odf\"]},\"application/vnd.oasis.opendocument.formula-template\":{\"source\":\"iana\",\"extensions\":[\"odft\"]},\"application/vnd.oasis.opendocument.graphics\":{\"source\":\"iana\",\"compressible\":false,\"extensions\":[\"odg\"]},\"application/vnd.oasis.opendocument.graphics-template\":{\"source\":\"iana\",\"extensions\":[\"otg\"]},\"application/vnd.oasis.opendocument.image\":{\"source\":\"iana\",\"extensions\":[\"odi\"]},\"application/vnd.oasis.opendocument.image-template\":{\"source\":\"iana\",\"extensions\":[\"oti\"]},\"application/vnd.oasis.opendocument.presentation\":{\"source\":\"iana\",\"compressible\":false,\"extensions\":[\"odp\"]},\"application/vnd.oasis.opendocument.presentation-template\":{\"source\":\"iana\",\"extensions\":[\"otp\"]},\"application/vnd.oasis.opendocument.spreadsheet\":{\"source\":\"iana\",\"compressible\":false,\"extensions\":[\"ods\"]},\"application/vnd.oasis.opendocument.spreadsheet-template\":{\"source\":\"iana\",\"extensions\":[\"ots\"]},\"application/vnd.oasis.opendocument.text\":{\"source\":\"iana\",\"compressible\":false,\"extensions\":[\"odt\"]},\"application/vnd.oasis.opendocument.text-master\":{\"source\":\"iana\",\"extensions\":[\"odm\"]},\"application/vnd.oasis.opendocument.text-template\":{\"source\":\"iana\",\"extensions\":[\"ott\"]},\"application/vnd.oasis.opendocument.text-web\":{\"source\":\"iana\",\"extensions\":[\"oth\"]},\"application/vnd.obn\":{\"source\":\"iana\"},\"application/vnd.ocf+cbor\":{\"source\":\"iana\"},\"application/vnd.oci.image.manifest.v1+json\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.oftn.l10n+json\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.oipf.contentaccessdownload+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.oipf.contentaccessstreaming+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.oipf.cspg-hexbinary\":{\"source\":\"iana\"},\"application/vnd.oipf.dae.svg+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.oipf.dae.xhtml+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.oipf.mippvcontrolmessage+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.oipf.pae.gem\":{\"source\":\"iana\"},\"application/vnd.oipf.spdiscovery+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.oipf.spdlist+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.oipf.ueprofile+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.oipf.userprofile+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.olpc-sugar\":{\"source\":\"iana\",\"extensions\":[\"xo\"]},\"application/vnd.oma-scws-config\":{\"source\":\"iana\"},\"application/vnd.oma-scws-http-request\":{\"source\":\"iana\"},\"application/vnd.oma-scws-http-response\":{\"source\":\"iana\"},\"application/vnd.oma.bcast.associated-procedure-parameter+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.oma.bcast.drm-trigger+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.oma.bcast.imd+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.oma.bcast.ltkm\":{\"source\":\"iana\"},\"application/vnd.oma.bcast.notification+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.oma.bcast.provisioningtrigger\":{\"source\":\"iana\"},\"application/vnd.oma.bcast.sgboot\":{\"source\":\"iana\"},\"application/vnd.oma.bcast.sgdd+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.oma.bcast.sgdu\":{\"source\":\"iana\"},\"application/vnd.oma.bcast.simple-symbol-container\":{\"source\":\"iana\"},\"application/vnd.oma.bcast.smartcard-trigger+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.oma.bcast.sprov+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.oma.bcast.stkm\":{\"source\":\"iana\"},\"application/vnd.oma.cab-address-book+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.oma.cab-feature-handler+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.oma.cab-pcc+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.oma.cab-subs-invite+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.oma.cab-user-prefs+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.oma.dcd\":{\"source\":\"iana\"},\"application/vnd.oma.dcdc\":{\"source\":\"iana\"},\"application/vnd.oma.dd2+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"dd2\"]},\"application/vnd.oma.drm.risd+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.oma.group-usage-list+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.oma.lwm2m+json\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.oma.lwm2m+tlv\":{\"source\":\"iana\"},\"application/vnd.oma.pal+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.oma.poc.detailed-progress-report+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.oma.poc.final-report+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.oma.poc.groups+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.oma.poc.invocation-descriptor+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.oma.poc.optimized-progress-report+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.oma.push\":{\"source\":\"iana\"},\"application/vnd.oma.scidm.messages+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.oma.xcap-directory+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.omads-email+xml\":{\"source\":\"iana\",\"charset\":\"UTF-8\",\"compressible\":true},\"application/vnd.omads-file+xml\":{\"source\":\"iana\",\"charset\":\"UTF-8\",\"compressible\":true},\"application/vnd.omads-folder+xml\":{\"source\":\"iana\",\"charset\":\"UTF-8\",\"compressible\":true},\"application/vnd.omaloc-supl-init\":{\"source\":\"iana\"},\"application/vnd.onepager\":{\"source\":\"iana\"},\"application/vnd.onepagertamp\":{\"source\":\"iana\"},\"application/vnd.onepagertamx\":{\"source\":\"iana\"},\"application/vnd.onepagertat\":{\"source\":\"iana\"},\"application/vnd.onepagertatp\":{\"source\":\"iana\"},\"application/vnd.onepagertatx\":{\"source\":\"iana\"},\"application/vnd.openblox.game+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"obgx\"]},\"application/vnd.openblox.game-binary\":{\"source\":\"iana\"},\"application/vnd.openeye.oeb\":{\"source\":\"iana\"},\"application/vnd.openofficeorg.extension\":{\"source\":\"apache\",\"extensions\":[\"oxt\"]},\"application/vnd.openstreetmap.data+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"osm\"]},\"application/vnd.openxmlformats-officedocument.custom-properties+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.openxmlformats-officedocument.customxmlproperties+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.openxmlformats-officedocument.drawing+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.openxmlformats-officedocument.drawingml.chart+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.openxmlformats-officedocument.drawingml.diagramcolors+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.openxmlformats-officedocument.drawingml.diagramdata+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.openxmlformats-officedocument.drawingml.diagramlayout+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.openxmlformats-officedocument.drawingml.diagramstyle+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.openxmlformats-officedocument.extended-properties+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.openxmlformats-officedocument.presentationml.commentauthors+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.openxmlformats-officedocument.presentationml.comments+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.openxmlformats-officedocument.presentationml.handoutmaster+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.openxmlformats-officedocument.presentationml.notesmaster+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.openxmlformats-officedocument.presentationml.notesslide+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.openxmlformats-officedocument.presentationml.presentation\":{\"source\":\"iana\",\"compressible\":false,\"extensions\":[\"pptx\"]},\"application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.openxmlformats-officedocument.presentationml.presprops+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.openxmlformats-officedocument.presentationml.slide\":{\"source\":\"iana\",\"extensions\":[\"sldx\"]},\"application/vnd.openxmlformats-officedocument.presentationml.slide+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.openxmlformats-officedocument.presentationml.slidelayout+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.openxmlformats-officedocument.presentationml.slidemaster+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.openxmlformats-officedocument.presentationml.slideshow\":{\"source\":\"iana\",\"extensions\":[\"ppsx\"]},\"application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.openxmlformats-officedocument.presentationml.slideupdateinfo+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.openxmlformats-officedocument.presentationml.tablestyles+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.openxmlformats-officedocument.presentationml.tags+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.openxmlformats-officedocument.presentationml.template\":{\"source\":\"iana\",\"extensions\":[\"potx\"]},\"application/vnd.openxmlformats-officedocument.presentationml.template.main+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.openxmlformats-officedocument.presentationml.viewprops+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.openxmlformats-officedocument.spreadsheetml.calcchain+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.openxmlformats-officedocument.spreadsheetml.externallink+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcachedefinition+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcacherecords+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.openxmlformats-officedocument.spreadsheetml.pivottable+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.openxmlformats-officedocument.spreadsheetml.querytable+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.openxmlformats-officedocument.spreadsheetml.revisionheaders+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.openxmlformats-officedocument.spreadsheetml.revisionlog+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.openxmlformats-officedocument.spreadsheetml.sharedstrings+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\":{\"source\":\"iana\",\"compressible\":false,\"extensions\":[\"xlsx\"]},\"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.openxmlformats-officedocument.spreadsheetml.sheetmetadata+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.openxmlformats-officedocument.spreadsheetml.tablesinglecells+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.openxmlformats-officedocument.spreadsheetml.template\":{\"source\":\"iana\",\"extensions\":[\"xltx\"]},\"application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.openxmlformats-officedocument.spreadsheetml.usernames+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.openxmlformats-officedocument.spreadsheetml.volatiledependencies+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.openxmlformats-officedocument.theme+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.openxmlformats-officedocument.themeoverride+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.openxmlformats-officedocument.vmldrawing\":{\"source\":\"iana\"},\"application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.openxmlformats-officedocument.wordprocessingml.document\":{\"source\":\"iana\",\"compressible\":false,\"extensions\":[\"docx\"]},\"application/vnd.openxmlformats-officedocument.wordprocessingml.document.glossary+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.openxmlformats-officedocument.wordprocessingml.fonttable+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.openxmlformats-officedocument.wordprocessingml.template\":{\"source\":\"iana\",\"extensions\":[\"dotx\"]},\"application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.openxmlformats-officedocument.wordprocessingml.websettings+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.openxmlformats-package.core-properties+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.openxmlformats-package.relationships+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.oracle.resource+json\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.orange.indata\":{\"source\":\"iana\"},\"application/vnd.osa.netdeploy\":{\"source\":\"iana\"},\"application/vnd.osgeo.mapguide.package\":{\"source\":\"iana\",\"extensions\":[\"mgp\"]},\"application/vnd.osgi.bundle\":{\"source\":\"iana\"},\"application/vnd.osgi.dp\":{\"source\":\"iana\",\"extensions\":[\"dp\"]},\"application/vnd.osgi.subsystem\":{\"source\":\"iana\",\"extensions\":[\"esa\"]},\"application/vnd.otps.ct-kip+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.oxli.countgraph\":{\"source\":\"iana\"},\"application/vnd.pagerduty+json\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.palm\":{\"source\":\"iana\",\"extensions\":[\"pdb\",\"pqa\",\"oprc\"]},\"application/vnd.panoply\":{\"source\":\"iana\"},\"application/vnd.paos.xml\":{\"source\":\"iana\"},\"application/vnd.patentdive\":{\"source\":\"iana\"},\"application/vnd.patientecommsdoc\":{\"source\":\"iana\"},\"application/vnd.pawaafile\":{\"source\":\"iana\",\"extensions\":[\"paw\"]},\"application/vnd.pcos\":{\"source\":\"iana\"},\"application/vnd.pg.format\":{\"source\":\"iana\",\"extensions\":[\"str\"]},\"application/vnd.pg.osasli\":{\"source\":\"iana\",\"extensions\":[\"ei6\"]},\"application/vnd.piaccess.application-licence\":{\"source\":\"iana\"},\"application/vnd.picsel\":{\"source\":\"iana\",\"extensions\":[\"efif\"]},\"application/vnd.pmi.widget\":{\"source\":\"iana\",\"extensions\":[\"wg\"]},\"application/vnd.poc.group-advertisement+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.pocketlearn\":{\"source\":\"iana\",\"extensions\":[\"plf\"]},\"application/vnd.powerbuilder6\":{\"source\":\"iana\",\"extensions\":[\"pbd\"]},\"application/vnd.powerbuilder6-s\":{\"source\":\"iana\"},\"application/vnd.powerbuilder7\":{\"source\":\"iana\"},\"application/vnd.powerbuilder7-s\":{\"source\":\"iana\"},\"application/vnd.powerbuilder75\":{\"source\":\"iana\"},\"application/vnd.powerbuilder75-s\":{\"source\":\"iana\"},\"application/vnd.preminet\":{\"source\":\"iana\"},\"application/vnd.previewsystems.box\":{\"source\":\"iana\",\"extensions\":[\"box\"]},\"application/vnd.proteus.magazine\":{\"source\":\"iana\",\"extensions\":[\"mgz\"]},\"application/vnd.psfs\":{\"source\":\"iana\"},\"application/vnd.publishare-delta-tree\":{\"source\":\"iana\",\"extensions\":[\"qps\"]},\"application/vnd.pvi.ptid1\":{\"source\":\"iana\",\"extensions\":[\"ptid\"]},\"application/vnd.pwg-multiplexed\":{\"source\":\"iana\"},\"application/vnd.pwg-xhtml-print+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.qualcomm.brew-app-res\":{\"source\":\"iana\"},\"application/vnd.quarantainenet\":{\"source\":\"iana\"},\"application/vnd.quark.quarkxpress\":{\"source\":\"iana\",\"extensions\":[\"qxd\",\"qxt\",\"qwd\",\"qwt\",\"qxl\",\"qxb\"]},\"application/vnd.quobject-quoxdocument\":{\"source\":\"iana\"},\"application/vnd.radisys.moml+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.radisys.msml+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.radisys.msml-audit+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.radisys.msml-audit-conf+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.radisys.msml-audit-conn+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.radisys.msml-audit-dialog+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.radisys.msml-audit-stream+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.radisys.msml-conf+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.radisys.msml-dialog+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.radisys.msml-dialog-base+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.radisys.msml-dialog-fax-detect+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.radisys.msml-dialog-fax-sendrecv+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.radisys.msml-dialog-group+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.radisys.msml-dialog-speech+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.radisys.msml-dialog-transform+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.rainstor.data\":{\"source\":\"iana\"},\"application/vnd.rapid\":{\"source\":\"iana\"},\"application/vnd.rar\":{\"source\":\"iana\"},\"application/vnd.realvnc.bed\":{\"source\":\"iana\",\"extensions\":[\"bed\"]},\"application/vnd.recordare.musicxml\":{\"source\":\"iana\",\"extensions\":[\"mxl\"]},\"application/vnd.recordare.musicxml+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"musicxml\"]},\"application/vnd.renlearn.rlprint\":{\"source\":\"iana\"},\"application/vnd.restful+json\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.rig.cryptonote\":{\"source\":\"iana\",\"extensions\":[\"cryptonote\"]},\"application/vnd.rim.cod\":{\"source\":\"apache\",\"extensions\":[\"cod\"]},\"application/vnd.rn-realmedia\":{\"source\":\"apache\",\"extensions\":[\"rm\"]},\"application/vnd.rn-realmedia-vbr\":{\"source\":\"apache\",\"extensions\":[\"rmvb\"]},\"application/vnd.route66.link66+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"link66\"]},\"application/vnd.rs-274x\":{\"source\":\"iana\"},\"application/vnd.ruckus.download\":{\"source\":\"iana\"},\"application/vnd.s3sms\":{\"source\":\"iana\"},\"application/vnd.sailingtracker.track\":{\"source\":\"iana\",\"extensions\":[\"st\"]},\"application/vnd.sar\":{\"source\":\"iana\"},\"application/vnd.sbm.cid\":{\"source\":\"iana\"},\"application/vnd.sbm.mid2\":{\"source\":\"iana\"},\"application/vnd.scribus\":{\"source\":\"iana\"},\"application/vnd.sealed.3df\":{\"source\":\"iana\"},\"application/vnd.sealed.csf\":{\"source\":\"iana\"},\"application/vnd.sealed.doc\":{\"source\":\"iana\"},\"application/vnd.sealed.eml\":{\"source\":\"iana\"},\"application/vnd.sealed.mht\":{\"source\":\"iana\"},\"application/vnd.sealed.net\":{\"source\":\"iana\"},\"application/vnd.sealed.ppt\":{\"source\":\"iana\"},\"application/vnd.sealed.tiff\":{\"source\":\"iana\"},\"application/vnd.sealed.xls\":{\"source\":\"iana\"},\"application/vnd.sealedmedia.softseal.html\":{\"source\":\"iana\"},\"application/vnd.sealedmedia.softseal.pdf\":{\"source\":\"iana\"},\"application/vnd.seemail\":{\"source\":\"iana\",\"extensions\":[\"see\"]},\"application/vnd.sema\":{\"source\":\"iana\",\"extensions\":[\"sema\"]},\"application/vnd.semd\":{\"source\":\"iana\",\"extensions\":[\"semd\"]},\"application/vnd.semf\":{\"source\":\"iana\",\"extensions\":[\"semf\"]},\"application/vnd.shade-save-file\":{\"source\":\"iana\"},\"application/vnd.shana.informed.formdata\":{\"source\":\"iana\",\"extensions\":[\"ifm\"]},\"application/vnd.shana.informed.formtemplate\":{\"source\":\"iana\",\"extensions\":[\"itp\"]},\"application/vnd.shana.informed.interchange\":{\"source\":\"iana\",\"extensions\":[\"iif\"]},\"application/vnd.shana.informed.package\":{\"source\":\"iana\",\"extensions\":[\"ipk\"]},\"application/vnd.shootproof+json\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.shopkick+json\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.shp\":{\"source\":\"iana\"},\"application/vnd.shx\":{\"source\":\"iana\"},\"application/vnd.sigrok.session\":{\"source\":\"iana\"},\"application/vnd.simtech-mindmapper\":{\"source\":\"iana\",\"extensions\":[\"twd\",\"twds\"]},\"application/vnd.siren+json\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.smaf\":{\"source\":\"iana\",\"extensions\":[\"mmf\"]},\"application/vnd.smart.notebook\":{\"source\":\"iana\"},\"application/vnd.smart.teacher\":{\"source\":\"iana\",\"extensions\":[\"teacher\"]},\"application/vnd.snesdev-page-table\":{\"source\":\"iana\"},\"application/vnd.software602.filler.form+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"fo\"]},\"application/vnd.software602.filler.form-xml-zip\":{\"source\":\"iana\"},\"application/vnd.solent.sdkm+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"sdkm\",\"sdkd\"]},\"application/vnd.spotfire.dxp\":{\"source\":\"iana\",\"extensions\":[\"dxp\"]},\"application/vnd.spotfire.sfs\":{\"source\":\"iana\",\"extensions\":[\"sfs\"]},\"application/vnd.sqlite3\":{\"source\":\"iana\"},\"application/vnd.sss-cod\":{\"source\":\"iana\"},\"application/vnd.sss-dtf\":{\"source\":\"iana\"},\"application/vnd.sss-ntf\":{\"source\":\"iana\"},\"application/vnd.stardivision.calc\":{\"source\":\"apache\",\"extensions\":[\"sdc\"]},\"application/vnd.stardivision.draw\":{\"source\":\"apache\",\"extensions\":[\"sda\"]},\"application/vnd.stardivision.impress\":{\"source\":\"apache\",\"extensions\":[\"sdd\"]},\"application/vnd.stardivision.math\":{\"source\":\"apache\",\"extensions\":[\"smf\"]},\"application/vnd.stardivision.writer\":{\"source\":\"apache\",\"extensions\":[\"sdw\",\"vor\"]},\"application/vnd.stardivision.writer-global\":{\"source\":\"apache\",\"extensions\":[\"sgl\"]},\"application/vnd.stepmania.package\":{\"source\":\"iana\",\"extensions\":[\"smzip\"]},\"application/vnd.stepmania.stepchart\":{\"source\":\"iana\",\"extensions\":[\"sm\"]},\"application/vnd.street-stream\":{\"source\":\"iana\"},\"application/vnd.sun.wadl+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"wadl\"]},\"application/vnd.sun.xml.calc\":{\"source\":\"apache\",\"extensions\":[\"sxc\"]},\"application/vnd.sun.xml.calc.template\":{\"source\":\"apache\",\"extensions\":[\"stc\"]},\"application/vnd.sun.xml.draw\":{\"source\":\"apache\",\"extensions\":[\"sxd\"]},\"application/vnd.sun.xml.draw.template\":{\"source\":\"apache\",\"extensions\":[\"std\"]},\"application/vnd.sun.xml.impress\":{\"source\":\"apache\",\"extensions\":[\"sxi\"]},\"application/vnd.sun.xml.impress.template\":{\"source\":\"apache\",\"extensions\":[\"sti\"]},\"application/vnd.sun.xml.math\":{\"source\":\"apache\",\"extensions\":[\"sxm\"]},\"application/vnd.sun.xml.writer\":{\"source\":\"apache\",\"extensions\":[\"sxw\"]},\"application/vnd.sun.xml.writer.global\":{\"source\":\"apache\",\"extensions\":[\"sxg\"]},\"application/vnd.sun.xml.writer.template\":{\"source\":\"apache\",\"extensions\":[\"stw\"]},\"application/vnd.sus-calendar\":{\"source\":\"iana\",\"extensions\":[\"sus\",\"susp\"]},\"application/vnd.svd\":{\"source\":\"iana\",\"extensions\":[\"svd\"]},\"application/vnd.swiftview-ics\":{\"source\":\"iana\"},\"application/vnd.symbian.install\":{\"source\":\"apache\",\"extensions\":[\"sis\",\"sisx\"]},\"application/vnd.syncml+xml\":{\"source\":\"iana\",\"charset\":\"UTF-8\",\"compressible\":true,\"extensions\":[\"xsm\"]},\"application/vnd.syncml.dm+wbxml\":{\"source\":\"iana\",\"charset\":\"UTF-8\",\"extensions\":[\"bdm\"]},\"application/vnd.syncml.dm+xml\":{\"source\":\"iana\",\"charset\":\"UTF-8\",\"compressible\":true,\"extensions\":[\"xdm\"]},\"application/vnd.syncml.dm.notification\":{\"source\":\"iana\"},\"application/vnd.syncml.dmddf+wbxml\":{\"source\":\"iana\"},\"application/vnd.syncml.dmddf+xml\":{\"source\":\"iana\",\"charset\":\"UTF-8\",\"compressible\":true,\"extensions\":[\"ddf\"]},\"application/vnd.syncml.dmtnds+wbxml\":{\"source\":\"iana\"},\"application/vnd.syncml.dmtnds+xml\":{\"source\":\"iana\",\"charset\":\"UTF-8\",\"compressible\":true},\"application/vnd.syncml.ds.notification\":{\"source\":\"iana\"},\"application/vnd.tableschema+json\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.tao.intent-module-archive\":{\"source\":\"iana\",\"extensions\":[\"tao\"]},\"application/vnd.tcpdump.pcap\":{\"source\":\"iana\",\"extensions\":[\"pcap\",\"cap\",\"dmp\"]},\"application/vnd.think-cell.ppttc+json\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.tmd.mediaflex.api+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.tml\":{\"source\":\"iana\"},\"application/vnd.tmobile-livetv\":{\"source\":\"iana\",\"extensions\":[\"tmo\"]},\"application/vnd.tri.onesource\":{\"source\":\"iana\"},\"application/vnd.trid.tpt\":{\"source\":\"iana\",\"extensions\":[\"tpt\"]},\"application/vnd.triscape.mxs\":{\"source\":\"iana\",\"extensions\":[\"mxs\"]},\"application/vnd.trueapp\":{\"source\":\"iana\",\"extensions\":[\"tra\"]},\"application/vnd.truedoc\":{\"source\":\"iana\"},\"application/vnd.ubisoft.webplayer\":{\"source\":\"iana\"},\"application/vnd.ufdl\":{\"source\":\"iana\",\"extensions\":[\"ufd\",\"ufdl\"]},\"application/vnd.uiq.theme\":{\"source\":\"iana\",\"extensions\":[\"utz\"]},\"application/vnd.umajin\":{\"source\":\"iana\",\"extensions\":[\"umj\"]},\"application/vnd.unity\":{\"source\":\"iana\",\"extensions\":[\"unityweb\"]},\"application/vnd.uoml+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"uoml\"]},\"application/vnd.uplanet.alert\":{\"source\":\"iana\"},\"application/vnd.uplanet.alert-wbxml\":{\"source\":\"iana\"},\"application/vnd.uplanet.bearer-choice\":{\"source\":\"iana\"},\"application/vnd.uplanet.bearer-choice-wbxml\":{\"source\":\"iana\"},\"application/vnd.uplanet.cacheop\":{\"source\":\"iana\"},\"application/vnd.uplanet.cacheop-wbxml\":{\"source\":\"iana\"},\"application/vnd.uplanet.channel\":{\"source\":\"iana\"},\"application/vnd.uplanet.channel-wbxml\":{\"source\":\"iana\"},\"application/vnd.uplanet.list\":{\"source\":\"iana\"},\"application/vnd.uplanet.list-wbxml\":{\"source\":\"iana\"},\"application/vnd.uplanet.listcmd\":{\"source\":\"iana\"},\"application/vnd.uplanet.listcmd-wbxml\":{\"source\":\"iana\"},\"application/vnd.uplanet.signal\":{\"source\":\"iana\"},\"application/vnd.uri-map\":{\"source\":\"iana\"},\"application/vnd.valve.source.material\":{\"source\":\"iana\"},\"application/vnd.vcx\":{\"source\":\"iana\",\"extensions\":[\"vcx\"]},\"application/vnd.vd-study\":{\"source\":\"iana\"},\"application/vnd.vectorworks\":{\"source\":\"iana\"},\"application/vnd.vel+json\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.verimatrix.vcas\":{\"source\":\"iana\"},\"application/vnd.veryant.thin\":{\"source\":\"iana\"},\"application/vnd.ves.encrypted\":{\"source\":\"iana\"},\"application/vnd.vidsoft.vidconference\":{\"source\":\"iana\"},\"application/vnd.visio\":{\"source\":\"iana\",\"extensions\":[\"vsd\",\"vst\",\"vss\",\"vsw\"]},\"application/vnd.visionary\":{\"source\":\"iana\",\"extensions\":[\"vis\"]},\"application/vnd.vividence.scriptfile\":{\"source\":\"iana\"},\"application/vnd.vsf\":{\"source\":\"iana\",\"extensions\":[\"vsf\"]},\"application/vnd.wap.sic\":{\"source\":\"iana\"},\"application/vnd.wap.slc\":{\"source\":\"iana\"},\"application/vnd.wap.wbxml\":{\"source\":\"iana\",\"charset\":\"UTF-8\",\"extensions\":[\"wbxml\"]},\"application/vnd.wap.wmlc\":{\"source\":\"iana\",\"extensions\":[\"wmlc\"]},\"application/vnd.wap.wmlscriptc\":{\"source\":\"iana\",\"extensions\":[\"wmlsc\"]},\"application/vnd.webturbo\":{\"source\":\"iana\",\"extensions\":[\"wtb\"]},\"application/vnd.wfa.p2p\":{\"source\":\"iana\"},\"application/vnd.wfa.wsc\":{\"source\":\"iana\"},\"application/vnd.windows.devicepairing\":{\"source\":\"iana\"},\"application/vnd.wmc\":{\"source\":\"iana\"},\"application/vnd.wmf.bootstrap\":{\"source\":\"iana\"},\"application/vnd.wolfram.mathematica\":{\"source\":\"iana\"},\"application/vnd.wolfram.mathematica.package\":{\"source\":\"iana\"},\"application/vnd.wolfram.player\":{\"source\":\"iana\",\"extensions\":[\"nbp\"]},\"application/vnd.wordperfect\":{\"source\":\"iana\",\"extensions\":[\"wpd\"]},\"application/vnd.wqd\":{\"source\":\"iana\",\"extensions\":[\"wqd\"]},\"application/vnd.wrq-hp3000-labelled\":{\"source\":\"iana\"},\"application/vnd.wt.stf\":{\"source\":\"iana\",\"extensions\":[\"stf\"]},\"application/vnd.wv.csp+wbxml\":{\"source\":\"iana\"},\"application/vnd.wv.csp+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.wv.ssp+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.xacml+json\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.xara\":{\"source\":\"iana\",\"extensions\":[\"xar\"]},\"application/vnd.xfdl\":{\"source\":\"iana\",\"extensions\":[\"xfdl\"]},\"application/vnd.xfdl.webform\":{\"source\":\"iana\"},\"application/vnd.xmi+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/vnd.xmpie.cpkg\":{\"source\":\"iana\"},\"application/vnd.xmpie.dpkg\":{\"source\":\"iana\"},\"application/vnd.xmpie.plan\":{\"source\":\"iana\"},\"application/vnd.xmpie.ppkg\":{\"source\":\"iana\"},\"application/vnd.xmpie.xlim\":{\"source\":\"iana\"},\"application/vnd.yamaha.hv-dic\":{\"source\":\"iana\",\"extensions\":[\"hvd\"]},\"application/vnd.yamaha.hv-script\":{\"source\":\"iana\",\"extensions\":[\"hvs\"]},\"application/vnd.yamaha.hv-voice\":{\"source\":\"iana\",\"extensions\":[\"hvp\"]},\"application/vnd.yamaha.openscoreformat\":{\"source\":\"iana\",\"extensions\":[\"osf\"]},\"application/vnd.yamaha.openscoreformat.osfpvg+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"osfpvg\"]},\"application/vnd.yamaha.remote-setup\":{\"source\":\"iana\"},\"application/vnd.yamaha.smaf-audio\":{\"source\":\"iana\",\"extensions\":[\"saf\"]},\"application/vnd.yamaha.smaf-phrase\":{\"source\":\"iana\",\"extensions\":[\"spf\"]},\"application/vnd.yamaha.through-ngn\":{\"source\":\"iana\"},\"application/vnd.yamaha.tunnel-udpencap\":{\"source\":\"iana\"},\"application/vnd.yaoweme\":{\"source\":\"iana\"},\"application/vnd.yellowriver-custom-menu\":{\"source\":\"iana\",\"extensions\":[\"cmp\"]},\"application/vnd.youtube.yt\":{\"source\":\"iana\"},\"application/vnd.zul\":{\"source\":\"iana\",\"extensions\":[\"zir\",\"zirz\"]},\"application/vnd.zzazz.deck+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"zaz\"]},\"application/voicexml+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"vxml\"]},\"application/voucher-cms+json\":{\"source\":\"iana\",\"compressible\":true},\"application/vq-rtcpxr\":{\"source\":\"iana\"},\"application/wasm\":{\"compressible\":true,\"extensions\":[\"wasm\"]},\"application/watcherinfo+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/webpush-options+json\":{\"source\":\"iana\",\"compressible\":true},\"application/whoispp-query\":{\"source\":\"iana\"},\"application/whoispp-response\":{\"source\":\"iana\"},\"application/widget\":{\"source\":\"iana\",\"extensions\":[\"wgt\"]},\"application/winhlp\":{\"source\":\"apache\",\"extensions\":[\"hlp\"]},\"application/wita\":{\"source\":\"iana\"},\"application/wordperfect5.1\":{\"source\":\"iana\"},\"application/wsdl+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"wsdl\"]},\"application/wspolicy+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"wspolicy\"]},\"application/x-7z-compressed\":{\"source\":\"apache\",\"compressible\":false,\"extensions\":[\"7z\"]},\"application/x-abiword\":{\"source\":\"apache\",\"extensions\":[\"abw\"]},\"application/x-ace-compressed\":{\"source\":\"apache\",\"extensions\":[\"ace\"]},\"application/x-amf\":{\"source\":\"apache\"},\"application/x-apple-diskimage\":{\"source\":\"apache\",\"extensions\":[\"dmg\"]},\"application/x-arj\":{\"compressible\":false,\"extensions\":[\"arj\"]},\"application/x-authorware-bin\":{\"source\":\"apache\",\"extensions\":[\"aab\",\"x32\",\"u32\",\"vox\"]},\"application/x-authorware-map\":{\"source\":\"apache\",\"extensions\":[\"aam\"]},\"application/x-authorware-seg\":{\"source\":\"apache\",\"extensions\":[\"aas\"]},\"application/x-bcpio\":{\"source\":\"apache\",\"extensions\":[\"bcpio\"]},\"application/x-bdoc\":{\"compressible\":false,\"extensions\":[\"bdoc\"]},\"application/x-bittorrent\":{\"source\":\"apache\",\"extensions\":[\"torrent\"]},\"application/x-blorb\":{\"source\":\"apache\",\"extensions\":[\"blb\",\"blorb\"]},\"application/x-bzip\":{\"source\":\"apache\",\"compressible\":false,\"extensions\":[\"bz\"]},\"application/x-bzip2\":{\"source\":\"apache\",\"compressible\":false,\"extensions\":[\"bz2\",\"boz\"]},\"application/x-cbr\":{\"source\":\"apache\",\"extensions\":[\"cbr\",\"cba\",\"cbt\",\"cbz\",\"cb7\"]},\"application/x-cdlink\":{\"source\":\"apache\",\"extensions\":[\"vcd\"]},\"application/x-cfs-compressed\":{\"source\":\"apache\",\"extensions\":[\"cfs\"]},\"application/x-chat\":{\"source\":\"apache\",\"extensions\":[\"chat\"]},\"application/x-chess-pgn\":{\"source\":\"apache\",\"extensions\":[\"pgn\"]},\"application/x-chrome-extension\":{\"extensions\":[\"crx\"]},\"application/x-cocoa\":{\"source\":\"nginx\",\"extensions\":[\"cco\"]},\"application/x-compress\":{\"source\":\"apache\"},\"application/x-conference\":{\"source\":\"apache\",\"extensions\":[\"nsc\"]},\"application/x-cpio\":{\"source\":\"apache\",\"extensions\":[\"cpio\"]},\"application/x-csh\":{\"source\":\"apache\",\"extensions\":[\"csh\"]},\"application/x-deb\":{\"compressible\":false},\"application/x-debian-package\":{\"source\":\"apache\",\"extensions\":[\"deb\",\"udeb\"]},\"application/x-dgc-compressed\":{\"source\":\"apache\",\"extensions\":[\"dgc\"]},\"application/x-director\":{\"source\":\"apache\",\"extensions\":[\"dir\",\"dcr\",\"dxr\",\"cst\",\"cct\",\"cxt\",\"w3d\",\"fgd\",\"swa\"]},\"application/x-doom\":{\"source\":\"apache\",\"extensions\":[\"wad\"]},\"application/x-dtbncx+xml\":{\"source\":\"apache\",\"compressible\":true,\"extensions\":[\"ncx\"]},\"application/x-dtbook+xml\":{\"source\":\"apache\",\"compressible\":true,\"extensions\":[\"dtb\"]},\"application/x-dtbresource+xml\":{\"source\":\"apache\",\"compressible\":true,\"extensions\":[\"res\"]},\"application/x-dvi\":{\"source\":\"apache\",\"compressible\":false,\"extensions\":[\"dvi\"]},\"application/x-envoy\":{\"source\":\"apache\",\"extensions\":[\"evy\"]},\"application/x-eva\":{\"source\":\"apache\",\"extensions\":[\"eva\"]},\"application/x-font-bdf\":{\"source\":\"apache\",\"extensions\":[\"bdf\"]},\"application/x-font-dos\":{\"source\":\"apache\"},\"application/x-font-framemaker\":{\"source\":\"apache\"},\"application/x-font-ghostscript\":{\"source\":\"apache\",\"extensions\":[\"gsf\"]},\"application/x-font-libgrx\":{\"source\":\"apache\"},\"application/x-font-linux-psf\":{\"source\":\"apache\",\"extensions\":[\"psf\"]},\"application/x-font-pcf\":{\"source\":\"apache\",\"extensions\":[\"pcf\"]},\"application/x-font-snf\":{\"source\":\"apache\",\"extensions\":[\"snf\"]},\"application/x-font-speedo\":{\"source\":\"apache\"},\"application/x-font-sunos-news\":{\"source\":\"apache\"},\"application/x-font-type1\":{\"source\":\"apache\",\"extensions\":[\"pfa\",\"pfb\",\"pfm\",\"afm\"]},\"application/x-font-vfont\":{\"source\":\"apache\"},\"application/x-freearc\":{\"source\":\"apache\",\"extensions\":[\"arc\"]},\"application/x-futuresplash\":{\"source\":\"apache\",\"extensions\":[\"spl\"]},\"application/x-gca-compressed\":{\"source\":\"apache\",\"extensions\":[\"gca\"]},\"application/x-glulx\":{\"source\":\"apache\",\"extensions\":[\"ulx\"]},\"application/x-gnumeric\":{\"source\":\"apache\",\"extensions\":[\"gnumeric\"]},\"application/x-gramps-xml\":{\"source\":\"apache\",\"extensions\":[\"gramps\"]},\"application/x-gtar\":{\"source\":\"apache\",\"extensions\":[\"gtar\"]},\"application/x-gzip\":{\"source\":\"apache\"},\"application/x-hdf\":{\"source\":\"apache\",\"extensions\":[\"hdf\"]},\"application/x-httpd-php\":{\"compressible\":true,\"extensions\":[\"php\"]},\"application/x-install-instructions\":{\"source\":\"apache\",\"extensions\":[\"install\"]},\"application/x-iso9660-image\":{\"source\":\"apache\",\"extensions\":[\"iso\"]},\"application/x-java-archive-diff\":{\"source\":\"nginx\",\"extensions\":[\"jardiff\"]},\"application/x-java-jnlp-file\":{\"source\":\"apache\",\"compressible\":false,\"extensions\":[\"jnlp\"]},\"application/x-javascript\":{\"compressible\":true},\"application/x-keepass2\":{\"extensions\":[\"kdbx\"]},\"application/x-latex\":{\"source\":\"apache\",\"compressible\":false,\"extensions\":[\"latex\"]},\"application/x-lua-bytecode\":{\"extensions\":[\"luac\"]},\"application/x-lzh-compressed\":{\"source\":\"apache\",\"extensions\":[\"lzh\",\"lha\"]},\"application/x-makeself\":{\"source\":\"nginx\",\"extensions\":[\"run\"]},\"application/x-mie\":{\"source\":\"apache\",\"extensions\":[\"mie\"]},\"application/x-mobipocket-ebook\":{\"source\":\"apache\",\"extensions\":[\"prc\",\"mobi\"]},\"application/x-mpegurl\":{\"compressible\":false},\"application/x-ms-application\":{\"source\":\"apache\",\"extensions\":[\"application\"]},\"application/x-ms-shortcut\":{\"source\":\"apache\",\"extensions\":[\"lnk\"]},\"application/x-ms-wmd\":{\"source\":\"apache\",\"extensions\":[\"wmd\"]},\"application/x-ms-wmz\":{\"source\":\"apache\",\"extensions\":[\"wmz\"]},\"application/x-ms-xbap\":{\"source\":\"apache\",\"extensions\":[\"xbap\"]},\"application/x-msaccess\":{\"source\":\"apache\",\"extensions\":[\"mdb\"]},\"application/x-msbinder\":{\"source\":\"apache\",\"extensions\":[\"obd\"]},\"application/x-mscardfile\":{\"source\":\"apache\",\"extensions\":[\"crd\"]},\"application/x-msclip\":{\"source\":\"apache\",\"extensions\":[\"clp\"]},\"application/x-msdos-program\":{\"extensions\":[\"exe\"]},\"application/x-msdownload\":{\"source\":\"apache\",\"extensions\":[\"exe\",\"dll\",\"com\",\"bat\",\"msi\"]},\"application/x-msmediaview\":{\"source\":\"apache\",\"extensions\":[\"mvb\",\"m13\",\"m14\"]},\"application/x-msmetafile\":{\"source\":\"apache\",\"extensions\":[\"wmf\",\"wmz\",\"emf\",\"emz\"]},\"application/x-msmoney\":{\"source\":\"apache\",\"extensions\":[\"mny\"]},\"application/x-mspublisher\":{\"source\":\"apache\",\"extensions\":[\"pub\"]},\"application/x-msschedule\":{\"source\":\"apache\",\"extensions\":[\"scd\"]},\"application/x-msterminal\":{\"source\":\"apache\",\"extensions\":[\"trm\"]},\"application/x-mswrite\":{\"source\":\"apache\",\"extensions\":[\"wri\"]},\"application/x-netcdf\":{\"source\":\"apache\",\"extensions\":[\"nc\",\"cdf\"]},\"application/x-ns-proxy-autoconfig\":{\"compressible\":true,\"extensions\":[\"pac\"]},\"application/x-nzb\":{\"source\":\"apache\",\"extensions\":[\"nzb\"]},\"application/x-perl\":{\"source\":\"nginx\",\"extensions\":[\"pl\",\"pm\"]},\"application/x-pilot\":{\"source\":\"nginx\",\"extensions\":[\"prc\",\"pdb\"]},\"application/x-pkcs12\":{\"source\":\"apache\",\"compressible\":false,\"extensions\":[\"p12\",\"pfx\"]},\"application/x-pkcs7-certificates\":{\"source\":\"apache\",\"extensions\":[\"p7b\",\"spc\"]},\"application/x-pkcs7-certreqresp\":{\"source\":\"apache\",\"extensions\":[\"p7r\"]},\"application/x-pki-message\":{\"source\":\"iana\"},\"application/x-rar-compressed\":{\"source\":\"apache\",\"compressible\":false,\"extensions\":[\"rar\"]},\"application/x-redhat-package-manager\":{\"source\":\"nginx\",\"extensions\":[\"rpm\"]},\"application/x-research-info-systems\":{\"source\":\"apache\",\"extensions\":[\"ris\"]},\"application/x-sea\":{\"source\":\"nginx\",\"extensions\":[\"sea\"]},\"application/x-sh\":{\"source\":\"apache\",\"compressible\":true,\"extensions\":[\"sh\"]},\"application/x-shar\":{\"source\":\"apache\",\"extensions\":[\"shar\"]},\"application/x-shockwave-flash\":{\"source\":\"apache\",\"compressible\":false,\"extensions\":[\"swf\"]},\"application/x-silverlight-app\":{\"source\":\"apache\",\"extensions\":[\"xap\"]},\"application/x-sql\":{\"source\":\"apache\",\"extensions\":[\"sql\"]},\"application/x-stuffit\":{\"source\":\"apache\",\"compressible\":false,\"extensions\":[\"sit\"]},\"application/x-stuffitx\":{\"source\":\"apache\",\"extensions\":[\"sitx\"]},\"application/x-subrip\":{\"source\":\"apache\",\"extensions\":[\"srt\"]},\"application/x-sv4cpio\":{\"source\":\"apache\",\"extensions\":[\"sv4cpio\"]},\"application/x-sv4crc\":{\"source\":\"apache\",\"extensions\":[\"sv4crc\"]},\"application/x-t3vm-image\":{\"source\":\"apache\",\"extensions\":[\"t3\"]},\"application/x-tads\":{\"source\":\"apache\",\"extensions\":[\"gam\"]},\"application/x-tar\":{\"source\":\"apache\",\"compressible\":true,\"extensions\":[\"tar\"]},\"application/x-tcl\":{\"source\":\"apache\",\"extensions\":[\"tcl\",\"tk\"]},\"application/x-tex\":{\"source\":\"apache\",\"extensions\":[\"tex\"]},\"application/x-tex-tfm\":{\"source\":\"apache\",\"extensions\":[\"tfm\"]},\"application/x-texinfo\":{\"source\":\"apache\",\"extensions\":[\"texinfo\",\"texi\"]},\"application/x-tgif\":{\"source\":\"apache\",\"extensions\":[\"obj\"]},\"application/x-ustar\":{\"source\":\"apache\",\"extensions\":[\"ustar\"]},\"application/x-virtualbox-hdd\":{\"compressible\":true,\"extensions\":[\"hdd\"]},\"application/x-virtualbox-ova\":{\"compressible\":true,\"extensions\":[\"ova\"]},\"application/x-virtualbox-ovf\":{\"compressible\":true,\"extensions\":[\"ovf\"]},\"application/x-virtualbox-vbox\":{\"compressible\":true,\"extensions\":[\"vbox\"]},\"application/x-virtualbox-vbox-extpack\":{\"compressible\":false,\"extensions\":[\"vbox-extpack\"]},\"application/x-virtualbox-vdi\":{\"compressible\":true,\"extensions\":[\"vdi\"]},\"application/x-virtualbox-vhd\":{\"compressible\":true,\"extensions\":[\"vhd\"]},\"application/x-virtualbox-vmdk\":{\"compressible\":true,\"extensions\":[\"vmdk\"]},\"application/x-wais-source\":{\"source\":\"apache\",\"extensions\":[\"src\"]},\"application/x-web-app-manifest+json\":{\"compressible\":true,\"extensions\":[\"webapp\"]},\"application/x-www-form-urlencoded\":{\"source\":\"iana\",\"compressible\":true},\"application/x-x509-ca-cert\":{\"source\":\"iana\",\"extensions\":[\"der\",\"crt\",\"pem\"]},\"application/x-x509-ca-ra-cert\":{\"source\":\"iana\"},\"application/x-x509-next-ca-cert\":{\"source\":\"iana\"},\"application/x-xfig\":{\"source\":\"apache\",\"extensions\":[\"fig\"]},\"application/x-xliff+xml\":{\"source\":\"apache\",\"compressible\":true,\"extensions\":[\"xlf\"]},\"application/x-xpinstall\":{\"source\":\"apache\",\"compressible\":false,\"extensions\":[\"xpi\"]},\"application/x-xz\":{\"source\":\"apache\",\"extensions\":[\"xz\"]},\"application/x-zmachine\":{\"source\":\"apache\",\"extensions\":[\"z1\",\"z2\",\"z3\",\"z4\",\"z5\",\"z6\",\"z7\",\"z8\"]},\"application/x400-bp\":{\"source\":\"iana\"},\"application/xacml+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/xaml+xml\":{\"source\":\"apache\",\"compressible\":true,\"extensions\":[\"xaml\"]},\"application/xcap-att+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"xav\"]},\"application/xcap-caps+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"xca\"]},\"application/xcap-diff+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"xdf\"]},\"application/xcap-el+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"xel\"]},\"application/xcap-error+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"xer\"]},\"application/xcap-ns+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"xns\"]},\"application/xcon-conference-info+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/xcon-conference-info-diff+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/xenc+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"xenc\"]},\"application/xhtml+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"xhtml\",\"xht\"]},\"application/xhtml-voice+xml\":{\"source\":\"apache\",\"compressible\":true},\"application/xliff+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"xlf\"]},\"application/xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"xml\",\"xsl\",\"xsd\",\"rng\"]},\"application/xml-dtd\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"dtd\"]},\"application/xml-external-parsed-entity\":{\"source\":\"iana\"},\"application/xml-patch+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/xmpp+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/xop+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"xop\"]},\"application/xproc+xml\":{\"source\":\"apache\",\"compressible\":true,\"extensions\":[\"xpl\"]},\"application/xslt+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"xslt\"]},\"application/xspf+xml\":{\"source\":\"apache\",\"compressible\":true,\"extensions\":[\"xspf\"]},\"application/xv+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"mxml\",\"xhvml\",\"xvml\",\"xvm\"]},\"application/yang\":{\"source\":\"iana\",\"extensions\":[\"yang\"]},\"application/yang-data+json\":{\"source\":\"iana\",\"compressible\":true},\"application/yang-data+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/yang-patch+json\":{\"source\":\"iana\",\"compressible\":true},\"application/yang-patch+xml\":{\"source\":\"iana\",\"compressible\":true},\"application/yin+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"yin\"]},\"application/zip\":{\"source\":\"iana\",\"compressible\":false,\"extensions\":[\"zip\"]},\"application/zlib\":{\"source\":\"iana\"},\"application/zstd\":{\"source\":\"iana\"},\"audio/1d-interleaved-parityfec\":{\"source\":\"iana\"},\"audio/32kadpcm\":{\"source\":\"iana\"},\"audio/3gpp\":{\"source\":\"iana\",\"compressible\":false,\"extensions\":[\"3gpp\"]},\"audio/3gpp2\":{\"source\":\"iana\"},\"audio/aac\":{\"source\":\"iana\"},\"audio/ac3\":{\"source\":\"iana\"},\"audio/adpcm\":{\"source\":\"apache\",\"extensions\":[\"adp\"]},\"audio/amr\":{\"source\":\"iana\"},\"audio/amr-wb\":{\"source\":\"iana\"},\"audio/amr-wb+\":{\"source\":\"iana\"},\"audio/aptx\":{\"source\":\"iana\"},\"audio/asc\":{\"source\":\"iana\"},\"audio/atrac-advanced-lossless\":{\"source\":\"iana\"},\"audio/atrac-x\":{\"source\":\"iana\"},\"audio/atrac3\":{\"source\":\"iana\"},\"audio/basic\":{\"source\":\"iana\",\"compressible\":false,\"extensions\":[\"au\",\"snd\"]},\"audio/bv16\":{\"source\":\"iana\"},\"audio/bv32\":{\"source\":\"iana\"},\"audio/clearmode\":{\"source\":\"iana\"},\"audio/cn\":{\"source\":\"iana\"},\"audio/dat12\":{\"source\":\"iana\"},\"audio/dls\":{\"source\":\"iana\"},\"audio/dsr-es201108\":{\"source\":\"iana\"},\"audio/dsr-es202050\":{\"source\":\"iana\"},\"audio/dsr-es202211\":{\"source\":\"iana\"},\"audio/dsr-es202212\":{\"source\":\"iana\"},\"audio/dv\":{\"source\":\"iana\"},\"audio/dvi4\":{\"source\":\"iana\"},\"audio/eac3\":{\"source\":\"iana\"},\"audio/encaprtp\":{\"source\":\"iana\"},\"audio/evrc\":{\"source\":\"iana\"},\"audio/evrc-qcp\":{\"source\":\"iana\"},\"audio/evrc0\":{\"source\":\"iana\"},\"audio/evrc1\":{\"source\":\"iana\"},\"audio/evrcb\":{\"source\":\"iana\"},\"audio/evrcb0\":{\"source\":\"iana\"},\"audio/evrcb1\":{\"source\":\"iana\"},\"audio/evrcnw\":{\"source\":\"iana\"},\"audio/evrcnw0\":{\"source\":\"iana\"},\"audio/evrcnw1\":{\"source\":\"iana\"},\"audio/evrcwb\":{\"source\":\"iana\"},\"audio/evrcwb0\":{\"source\":\"iana\"},\"audio/evrcwb1\":{\"source\":\"iana\"},\"audio/evs\":{\"source\":\"iana\"},\"audio/flexfec\":{\"source\":\"iana\"},\"audio/fwdred\":{\"source\":\"iana\"},\"audio/g711-0\":{\"source\":\"iana\"},\"audio/g719\":{\"source\":\"iana\"},\"audio/g722\":{\"source\":\"iana\"},\"audio/g7221\":{\"source\":\"iana\"},\"audio/g723\":{\"source\":\"iana\"},\"audio/g726-16\":{\"source\":\"iana\"},\"audio/g726-24\":{\"source\":\"iana\"},\"audio/g726-32\":{\"source\":\"iana\"},\"audio/g726-40\":{\"source\":\"iana\"},\"audio/g728\":{\"source\":\"iana\"},\"audio/g729\":{\"source\":\"iana\"},\"audio/g7291\":{\"source\":\"iana\"},\"audio/g729d\":{\"source\":\"iana\"},\"audio/g729e\":{\"source\":\"iana\"},\"audio/gsm\":{\"source\":\"iana\"},\"audio/gsm-efr\":{\"source\":\"iana\"},\"audio/gsm-hr-08\":{\"source\":\"iana\"},\"audio/ilbc\":{\"source\":\"iana\"},\"audio/ip-mr_v2.5\":{\"source\":\"iana\"},\"audio/isac\":{\"source\":\"apache\"},\"audio/l16\":{\"source\":\"iana\"},\"audio/l20\":{\"source\":\"iana\"},\"audio/l24\":{\"source\":\"iana\",\"compressible\":false},\"audio/l8\":{\"source\":\"iana\"},\"audio/lpc\":{\"source\":\"iana\"},\"audio/melp\":{\"source\":\"iana\"},\"audio/melp1200\":{\"source\":\"iana\"},\"audio/melp2400\":{\"source\":\"iana\"},\"audio/melp600\":{\"source\":\"iana\"},\"audio/mhas\":{\"source\":\"iana\"},\"audio/midi\":{\"source\":\"apache\",\"extensions\":[\"mid\",\"midi\",\"kar\",\"rmi\"]},\"audio/mobile-xmf\":{\"source\":\"iana\",\"extensions\":[\"mxmf\"]},\"audio/mp3\":{\"compressible\":false,\"extensions\":[\"mp3\"]},\"audio/mp4\":{\"source\":\"iana\",\"compressible\":false,\"extensions\":[\"m4a\",\"mp4a\"]},\"audio/mp4a-latm\":{\"source\":\"iana\"},\"audio/mpa\":{\"source\":\"iana\"},\"audio/mpa-robust\":{\"source\":\"iana\"},\"audio/mpeg\":{\"source\":\"iana\",\"compressible\":false,\"extensions\":[\"mpga\",\"mp2\",\"mp2a\",\"mp3\",\"m2a\",\"m3a\"]},\"audio/mpeg4-generic\":{\"source\":\"iana\"},\"audio/musepack\":{\"source\":\"apache\"},\"audio/ogg\":{\"source\":\"iana\",\"compressible\":false,\"extensions\":[\"oga\",\"ogg\",\"spx\"]},\"audio/opus\":{\"source\":\"iana\"},\"audio/parityfec\":{\"source\":\"iana\"},\"audio/pcma\":{\"source\":\"iana\"},\"audio/pcma-wb\":{\"source\":\"iana\"},\"audio/pcmu\":{\"source\":\"iana\"},\"audio/pcmu-wb\":{\"source\":\"iana\"},\"audio/prs.sid\":{\"source\":\"iana\"},\"audio/qcelp\":{\"source\":\"iana\"},\"audio/raptorfec\":{\"source\":\"iana\"},\"audio/red\":{\"source\":\"iana\"},\"audio/rtp-enc-aescm128\":{\"source\":\"iana\"},\"audio/rtp-midi\":{\"source\":\"iana\"},\"audio/rtploopback\":{\"source\":\"iana\"},\"audio/rtx\":{\"source\":\"iana\"},\"audio/s3m\":{\"source\":\"apache\",\"extensions\":[\"s3m\"]},\"audio/silk\":{\"source\":\"apache\",\"extensions\":[\"sil\"]},\"audio/smv\":{\"source\":\"iana\"},\"audio/smv-qcp\":{\"source\":\"iana\"},\"audio/smv0\":{\"source\":\"iana\"},\"audio/sp-midi\":{\"source\":\"iana\"},\"audio/speex\":{\"source\":\"iana\"},\"audio/t140c\":{\"source\":\"iana\"},\"audio/t38\":{\"source\":\"iana\"},\"audio/telephone-event\":{\"source\":\"iana\"},\"audio/tetra_acelp\":{\"source\":\"iana\"},\"audio/tetra_acelp_bb\":{\"source\":\"iana\"},\"audio/tone\":{\"source\":\"iana\"},\"audio/uemclip\":{\"source\":\"iana\"},\"audio/ulpfec\":{\"source\":\"iana\"},\"audio/usac\":{\"source\":\"iana\"},\"audio/vdvi\":{\"source\":\"iana\"},\"audio/vmr-wb\":{\"source\":\"iana\"},\"audio/vnd.3gpp.iufp\":{\"source\":\"iana\"},\"audio/vnd.4sb\":{\"source\":\"iana\"},\"audio/vnd.audiokoz\":{\"source\":\"iana\"},\"audio/vnd.celp\":{\"source\":\"iana\"},\"audio/vnd.cisco.nse\":{\"source\":\"iana\"},\"audio/vnd.cmles.radio-events\":{\"source\":\"iana\"},\"audio/vnd.cns.anp1\":{\"source\":\"iana\"},\"audio/vnd.cns.inf1\":{\"source\":\"iana\"},\"audio/vnd.dece.audio\":{\"source\":\"iana\",\"extensions\":[\"uva\",\"uvva\"]},\"audio/vnd.digital-winds\":{\"source\":\"iana\",\"extensions\":[\"eol\"]},\"audio/vnd.dlna.adts\":{\"source\":\"iana\"},\"audio/vnd.dolby.heaac.1\":{\"source\":\"iana\"},\"audio/vnd.dolby.heaac.2\":{\"source\":\"iana\"},\"audio/vnd.dolby.mlp\":{\"source\":\"iana\"},\"audio/vnd.dolby.mps\":{\"source\":\"iana\"},\"audio/vnd.dolby.pl2\":{\"source\":\"iana\"},\"audio/vnd.dolby.pl2x\":{\"source\":\"iana\"},\"audio/vnd.dolby.pl2z\":{\"source\":\"iana\"},\"audio/vnd.dolby.pulse.1\":{\"source\":\"iana\"},\"audio/vnd.dra\":{\"source\":\"iana\",\"extensions\":[\"dra\"]},\"audio/vnd.dts\":{\"source\":\"iana\",\"extensions\":[\"dts\"]},\"audio/vnd.dts.hd\":{\"source\":\"iana\",\"extensions\":[\"dtshd\"]},\"audio/vnd.dts.uhd\":{\"source\":\"iana\"},\"audio/vnd.dvb.file\":{\"source\":\"iana\"},\"audio/vnd.everad.plj\":{\"source\":\"iana\"},\"audio/vnd.hns.audio\":{\"source\":\"iana\"},\"audio/vnd.lucent.voice\":{\"source\":\"iana\",\"extensions\":[\"lvp\"]},\"audio/vnd.ms-playready.media.pya\":{\"source\":\"iana\",\"extensions\":[\"pya\"]},\"audio/vnd.nokia.mobile-xmf\":{\"source\":\"iana\"},\"audio/vnd.nortel.vbk\":{\"source\":\"iana\"},\"audio/vnd.nuera.ecelp4800\":{\"source\":\"iana\",\"extensions\":[\"ecelp4800\"]},\"audio/vnd.nuera.ecelp7470\":{\"source\":\"iana\",\"extensions\":[\"ecelp7470\"]},\"audio/vnd.nuera.ecelp9600\":{\"source\":\"iana\",\"extensions\":[\"ecelp9600\"]},\"audio/vnd.octel.sbc\":{\"source\":\"iana\"},\"audio/vnd.presonus.multitrack\":{\"source\":\"iana\"},\"audio/vnd.qcelp\":{\"source\":\"iana\"},\"audio/vnd.rhetorex.32kadpcm\":{\"source\":\"iana\"},\"audio/vnd.rip\":{\"source\":\"iana\",\"extensions\":[\"rip\"]},\"audio/vnd.rn-realaudio\":{\"compressible\":false},\"audio/vnd.sealedmedia.softseal.mpeg\":{\"source\":\"iana\"},\"audio/vnd.vmx.cvsd\":{\"source\":\"iana\"},\"audio/vnd.wave\":{\"compressible\":false},\"audio/vorbis\":{\"source\":\"iana\",\"compressible\":false},\"audio/vorbis-config\":{\"source\":\"iana\"},\"audio/wav\":{\"compressible\":false,\"extensions\":[\"wav\"]},\"audio/wave\":{\"compressible\":false,\"extensions\":[\"wav\"]},\"audio/webm\":{\"source\":\"apache\",\"compressible\":false,\"extensions\":[\"weba\"]},\"audio/x-aac\":{\"source\":\"apache\",\"compressible\":false,\"extensions\":[\"aac\"]},\"audio/x-aiff\":{\"source\":\"apache\",\"extensions\":[\"aif\",\"aiff\",\"aifc\"]},\"audio/x-caf\":{\"source\":\"apache\",\"compressible\":false,\"extensions\":[\"caf\"]},\"audio/x-flac\":{\"source\":\"apache\",\"extensions\":[\"flac\"]},\"audio/x-m4a\":{\"source\":\"nginx\",\"extensions\":[\"m4a\"]},\"audio/x-matroska\":{\"source\":\"apache\",\"extensions\":[\"mka\"]},\"audio/x-mpegurl\":{\"source\":\"apache\",\"extensions\":[\"m3u\"]},\"audio/x-ms-wax\":{\"source\":\"apache\",\"extensions\":[\"wax\"]},\"audio/x-ms-wma\":{\"source\":\"apache\",\"extensions\":[\"wma\"]},\"audio/x-pn-realaudio\":{\"source\":\"apache\",\"extensions\":[\"ram\",\"ra\"]},\"audio/x-pn-realaudio-plugin\":{\"source\":\"apache\",\"extensions\":[\"rmp\"]},\"audio/x-realaudio\":{\"source\":\"nginx\",\"extensions\":[\"ra\"]},\"audio/x-tta\":{\"source\":\"apache\"},\"audio/x-wav\":{\"source\":\"apache\",\"extensions\":[\"wav\"]},\"audio/xm\":{\"source\":\"apache\",\"extensions\":[\"xm\"]},\"chemical/x-cdx\":{\"source\":\"apache\",\"extensions\":[\"cdx\"]},\"chemical/x-cif\":{\"source\":\"apache\",\"extensions\":[\"cif\"]},\"chemical/x-cmdf\":{\"source\":\"apache\",\"extensions\":[\"cmdf\"]},\"chemical/x-cml\":{\"source\":\"apache\",\"extensions\":[\"cml\"]},\"chemical/x-csml\":{\"source\":\"apache\",\"extensions\":[\"csml\"]},\"chemical/x-pdb\":{\"source\":\"apache\"},\"chemical/x-xyz\":{\"source\":\"apache\",\"extensions\":[\"xyz\"]},\"font/collection\":{\"source\":\"iana\",\"extensions\":[\"ttc\"]},\"font/otf\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"otf\"]},\"font/sfnt\":{\"source\":\"iana\"},\"font/ttf\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"ttf\"]},\"font/woff\":{\"source\":\"iana\",\"extensions\":[\"woff\"]},\"font/woff2\":{\"source\":\"iana\",\"extensions\":[\"woff2\"]},\"image/aces\":{\"source\":\"iana\",\"extensions\":[\"exr\"]},\"image/apng\":{\"compressible\":false,\"extensions\":[\"apng\"]},\"image/avci\":{\"source\":\"iana\"},\"image/avcs\":{\"source\":\"iana\"},\"image/bmp\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"bmp\"]},\"image/cgm\":{\"source\":\"iana\",\"extensions\":[\"cgm\"]},\"image/dicom-rle\":{\"source\":\"iana\",\"extensions\":[\"drle\"]},\"image/emf\":{\"source\":\"iana\",\"extensions\":[\"emf\"]},\"image/fits\":{\"source\":\"iana\",\"extensions\":[\"fits\"]},\"image/g3fax\":{\"source\":\"iana\",\"extensions\":[\"g3\"]},\"image/gif\":{\"source\":\"iana\",\"compressible\":false,\"extensions\":[\"gif\"]},\"image/heic\":{\"source\":\"iana\",\"extensions\":[\"heic\"]},\"image/heic-sequence\":{\"source\":\"iana\",\"extensions\":[\"heics\"]},\"image/heif\":{\"source\":\"iana\",\"extensions\":[\"heif\"]},\"image/heif-sequence\":{\"source\":\"iana\",\"extensions\":[\"heifs\"]},\"image/hej2k\":{\"source\":\"iana\",\"extensions\":[\"hej2\"]},\"image/hsj2\":{\"source\":\"iana\",\"extensions\":[\"hsj2\"]},\"image/ief\":{\"source\":\"iana\",\"extensions\":[\"ief\"]},\"image/jls\":{\"source\":\"iana\",\"extensions\":[\"jls\"]},\"image/jp2\":{\"source\":\"iana\",\"compressible\":false,\"extensions\":[\"jp2\",\"jpg2\"]},\"image/jpeg\":{\"source\":\"iana\",\"compressible\":false,\"extensions\":[\"jpeg\",\"jpg\",\"jpe\"]},\"image/jph\":{\"source\":\"iana\",\"extensions\":[\"jph\"]},\"image/jphc\":{\"source\":\"iana\",\"extensions\":[\"jhc\"]},\"image/jpm\":{\"source\":\"iana\",\"compressible\":false,\"extensions\":[\"jpm\"]},\"image/jpx\":{\"source\":\"iana\",\"compressible\":false,\"extensions\":[\"jpx\",\"jpf\"]},\"image/jxr\":{\"source\":\"iana\",\"extensions\":[\"jxr\"]},\"image/jxra\":{\"source\":\"iana\",\"extensions\":[\"jxra\"]},\"image/jxrs\":{\"source\":\"iana\",\"extensions\":[\"jxrs\"]},\"image/jxs\":{\"source\":\"iana\",\"extensions\":[\"jxs\"]},\"image/jxsc\":{\"source\":\"iana\",\"extensions\":[\"jxsc\"]},\"image/jxsi\":{\"source\":\"iana\",\"extensions\":[\"jxsi\"]},\"image/jxss\":{\"source\":\"iana\",\"extensions\":[\"jxss\"]},\"image/ktx\":{\"source\":\"iana\",\"extensions\":[\"ktx\"]},\"image/naplps\":{\"source\":\"iana\"},\"image/pjpeg\":{\"compressible\":false},\"image/png\":{\"source\":\"iana\",\"compressible\":false,\"extensions\":[\"png\"]},\"image/prs.btif\":{\"source\":\"iana\",\"extensions\":[\"btif\"]},\"image/prs.pti\":{\"source\":\"iana\",\"extensions\":[\"pti\"]},\"image/pwg-raster\":{\"source\":\"iana\"},\"image/sgi\":{\"source\":\"apache\",\"extensions\":[\"sgi\"]},\"image/svg+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"svg\",\"svgz\"]},\"image/t38\":{\"source\":\"iana\",\"extensions\":[\"t38\"]},\"image/tiff\":{\"source\":\"iana\",\"compressible\":false,\"extensions\":[\"tif\",\"tiff\"]},\"image/tiff-fx\":{\"source\":\"iana\",\"extensions\":[\"tfx\"]},\"image/vnd.adobe.photoshop\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"psd\"]},\"image/vnd.airzip.accelerator.azv\":{\"source\":\"iana\",\"extensions\":[\"azv\"]},\"image/vnd.cns.inf2\":{\"source\":\"iana\"},\"image/vnd.dece.graphic\":{\"source\":\"iana\",\"extensions\":[\"uvi\",\"uvvi\",\"uvg\",\"uvvg\"]},\"image/vnd.djvu\":{\"source\":\"iana\",\"extensions\":[\"djvu\",\"djv\"]},\"image/vnd.dvb.subtitle\":{\"source\":\"iana\",\"extensions\":[\"sub\"]},\"image/vnd.dwg\":{\"source\":\"iana\",\"extensions\":[\"dwg\"]},\"image/vnd.dxf\":{\"source\":\"iana\",\"extensions\":[\"dxf\"]},\"image/vnd.fastbidsheet\":{\"source\":\"iana\",\"extensions\":[\"fbs\"]},\"image/vnd.fpx\":{\"source\":\"iana\",\"extensions\":[\"fpx\"]},\"image/vnd.fst\":{\"source\":\"iana\",\"extensions\":[\"fst\"]},\"image/vnd.fujixerox.edmics-mmr\":{\"source\":\"iana\",\"extensions\":[\"mmr\"]},\"image/vnd.fujixerox.edmics-rlc\":{\"source\":\"iana\",\"extensions\":[\"rlc\"]},\"image/vnd.globalgraphics.pgb\":{\"source\":\"iana\"},\"image/vnd.microsoft.icon\":{\"source\":\"iana\",\"extensions\":[\"ico\"]},\"image/vnd.mix\":{\"source\":\"iana\"},\"image/vnd.mozilla.apng\":{\"source\":\"iana\"},\"image/vnd.ms-dds\":{\"extensions\":[\"dds\"]},\"image/vnd.ms-modi\":{\"source\":\"iana\",\"extensions\":[\"mdi\"]},\"image/vnd.ms-photo\":{\"source\":\"apache\",\"extensions\":[\"wdp\"]},\"image/vnd.net-fpx\":{\"source\":\"iana\",\"extensions\":[\"npx\"]},\"image/vnd.radiance\":{\"source\":\"iana\"},\"image/vnd.sealed.png\":{\"source\":\"iana\"},\"image/vnd.sealedmedia.softseal.gif\":{\"source\":\"iana\"},\"image/vnd.sealedmedia.softseal.jpg\":{\"source\":\"iana\"},\"image/vnd.svf\":{\"source\":\"iana\"},\"image/vnd.tencent.tap\":{\"source\":\"iana\",\"extensions\":[\"tap\"]},\"image/vnd.valve.source.texture\":{\"source\":\"iana\",\"extensions\":[\"vtf\"]},\"image/vnd.wap.wbmp\":{\"source\":\"iana\",\"extensions\":[\"wbmp\"]},\"image/vnd.xiff\":{\"source\":\"iana\",\"extensions\":[\"xif\"]},\"image/vnd.zbrush.pcx\":{\"source\":\"iana\",\"extensions\":[\"pcx\"]},\"image/webp\":{\"source\":\"apache\",\"extensions\":[\"webp\"]},\"image/wmf\":{\"source\":\"iana\",\"extensions\":[\"wmf\"]},\"image/x-3ds\":{\"source\":\"apache\",\"extensions\":[\"3ds\"]},\"image/x-cmu-raster\":{\"source\":\"apache\",\"extensions\":[\"ras\"]},\"image/x-cmx\":{\"source\":\"apache\",\"extensions\":[\"cmx\"]},\"image/x-freehand\":{\"source\":\"apache\",\"extensions\":[\"fh\",\"fhc\",\"fh4\",\"fh5\",\"fh7\"]},\"image/x-icon\":{\"source\":\"apache\",\"compressible\":true,\"extensions\":[\"ico\"]},\"image/x-jng\":{\"source\":\"nginx\",\"extensions\":[\"jng\"]},\"image/x-mrsid-image\":{\"source\":\"apache\",\"extensions\":[\"sid\"]},\"image/x-ms-bmp\":{\"source\":\"nginx\",\"compressible\":true,\"extensions\":[\"bmp\"]},\"image/x-pcx\":{\"source\":\"apache\",\"extensions\":[\"pcx\"]},\"image/x-pict\":{\"source\":\"apache\",\"extensions\":[\"pic\",\"pct\"]},\"image/x-portable-anymap\":{\"source\":\"apache\",\"extensions\":[\"pnm\"]},\"image/x-portable-bitmap\":{\"source\":\"apache\",\"extensions\":[\"pbm\"]},\"image/x-portable-graymap\":{\"source\":\"apache\",\"extensions\":[\"pgm\"]},\"image/x-portable-pixmap\":{\"source\":\"apache\",\"extensions\":[\"ppm\"]},\"image/x-rgb\":{\"source\":\"apache\",\"extensions\":[\"rgb\"]},\"image/x-tga\":{\"source\":\"apache\",\"extensions\":[\"tga\"]},\"image/x-xbitmap\":{\"source\":\"apache\",\"extensions\":[\"xbm\"]},\"image/x-xcf\":{\"compressible\":false},\"image/x-xpixmap\":{\"source\":\"apache\",\"extensions\":[\"xpm\"]},\"image/x-xwindowdump\":{\"source\":\"apache\",\"extensions\":[\"xwd\"]},\"message/cpim\":{\"source\":\"iana\"},\"message/delivery-status\":{\"source\":\"iana\"},\"message/disposition-notification\":{\"source\":\"iana\",\"extensions\":[\"disposition-notification\"]},\"message/external-body\":{\"source\":\"iana\"},\"message/feedback-report\":{\"source\":\"iana\"},\"message/global\":{\"source\":\"iana\",\"extensions\":[\"u8msg\"]},\"message/global-delivery-status\":{\"source\":\"iana\",\"extensions\":[\"u8dsn\"]},\"message/global-disposition-notification\":{\"source\":\"iana\",\"extensions\":[\"u8mdn\"]},\"message/global-headers\":{\"source\":\"iana\",\"extensions\":[\"u8hdr\"]},\"message/http\":{\"source\":\"iana\",\"compressible\":false},\"message/imdn+xml\":{\"source\":\"iana\",\"compressible\":true},\"message/news\":{\"source\":\"iana\"},\"message/partial\":{\"source\":\"iana\",\"compressible\":false},\"message/rfc822\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"eml\",\"mime\"]},\"message/s-http\":{\"source\":\"iana\"},\"message/sip\":{\"source\":\"iana\"},\"message/sipfrag\":{\"source\":\"iana\"},\"message/tracking-status\":{\"source\":\"iana\"},\"message/vnd.si.simp\":{\"source\":\"iana\"},\"message/vnd.wfa.wsc\":{\"source\":\"iana\",\"extensions\":[\"wsc\"]},\"model/3mf\":{\"source\":\"iana\",\"extensions\":[\"3mf\"]},\"model/gltf+json\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"gltf\"]},\"model/gltf-binary\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"glb\"]},\"model/iges\":{\"source\":\"iana\",\"compressible\":false,\"extensions\":[\"igs\",\"iges\"]},\"model/mesh\":{\"source\":\"iana\",\"compressible\":false,\"extensions\":[\"msh\",\"mesh\",\"silo\"]},\"model/mtl\":{\"source\":\"iana\",\"extensions\":[\"mtl\"]},\"model/obj\":{\"source\":\"iana\",\"extensions\":[\"obj\"]},\"model/stl\":{\"source\":\"iana\",\"extensions\":[\"stl\"]},\"model/vnd.collada+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"dae\"]},\"model/vnd.dwf\":{\"source\":\"iana\",\"extensions\":[\"dwf\"]},\"model/vnd.flatland.3dml\":{\"source\":\"iana\"},\"model/vnd.gdl\":{\"source\":\"iana\",\"extensions\":[\"gdl\"]},\"model/vnd.gs-gdl\":{\"source\":\"apache\"},\"model/vnd.gs.gdl\":{\"source\":\"iana\"},\"model/vnd.gtw\":{\"source\":\"iana\",\"extensions\":[\"gtw\"]},\"model/vnd.moml+xml\":{\"source\":\"iana\",\"compressible\":true},\"model/vnd.mts\":{\"source\":\"iana\",\"extensions\":[\"mts\"]},\"model/vnd.opengex\":{\"source\":\"iana\",\"extensions\":[\"ogex\"]},\"model/vnd.parasolid.transmit.binary\":{\"source\":\"iana\",\"extensions\":[\"x_b\"]},\"model/vnd.parasolid.transmit.text\":{\"source\":\"iana\",\"extensions\":[\"x_t\"]},\"model/vnd.rosette.annotated-data-model\":{\"source\":\"iana\"},\"model/vnd.usdz+zip\":{\"source\":\"iana\",\"compressible\":false,\"extensions\":[\"usdz\"]},\"model/vnd.valve.source.compiled-map\":{\"source\":\"iana\",\"extensions\":[\"bsp\"]},\"model/vnd.vtu\":{\"source\":\"iana\",\"extensions\":[\"vtu\"]},\"model/vrml\":{\"source\":\"iana\",\"compressible\":false,\"extensions\":[\"wrl\",\"vrml\"]},\"model/x3d+binary\":{\"source\":\"apache\",\"compressible\":false,\"extensions\":[\"x3db\",\"x3dbz\"]},\"model/x3d+fastinfoset\":{\"source\":\"iana\",\"extensions\":[\"x3db\"]},\"model/x3d+vrml\":{\"source\":\"apache\",\"compressible\":false,\"extensions\":[\"x3dv\",\"x3dvz\"]},\"model/x3d+xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"x3d\",\"x3dz\"]},\"model/x3d-vrml\":{\"source\":\"iana\",\"extensions\":[\"x3dv\"]},\"multipart/alternative\":{\"source\":\"iana\",\"compressible\":false},\"multipart/appledouble\":{\"source\":\"iana\"},\"multipart/byteranges\":{\"source\":\"iana\"},\"multipart/digest\":{\"source\":\"iana\"},\"multipart/encrypted\":{\"source\":\"iana\",\"compressible\":false},\"multipart/form-data\":{\"source\":\"iana\",\"compressible\":false},\"multipart/header-set\":{\"source\":\"iana\"},\"multipart/mixed\":{\"source\":\"iana\"},\"multipart/multilingual\":{\"source\":\"iana\"},\"multipart/parallel\":{\"source\":\"iana\"},\"multipart/related\":{\"source\":\"iana\",\"compressible\":false},\"multipart/report\":{\"source\":\"iana\"},\"multipart/signed\":{\"source\":\"iana\",\"compressible\":false},\"multipart/vnd.bint.med-plus\":{\"source\":\"iana\"},\"multipart/voice-message\":{\"source\":\"iana\"},\"multipart/x-mixed-replace\":{\"source\":\"iana\"},\"text/1d-interleaved-parityfec\":{\"source\":\"iana\"},\"text/cache-manifest\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"appcache\",\"manifest\"]},\"text/calendar\":{\"source\":\"iana\",\"extensions\":[\"ics\",\"ifb\"]},\"text/calender\":{\"compressible\":true},\"text/cmd\":{\"compressible\":true},\"text/coffeescript\":{\"extensions\":[\"coffee\",\"litcoffee\"]},\"text/css\":{\"source\":\"iana\",\"charset\":\"UTF-8\",\"compressible\":true,\"extensions\":[\"css\"]},\"text/csv\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"csv\"]},\"text/csv-schema\":{\"source\":\"iana\"},\"text/directory\":{\"source\":\"iana\"},\"text/dns\":{\"source\":\"iana\"},\"text/ecmascript\":{\"source\":\"iana\"},\"text/encaprtp\":{\"source\":\"iana\"},\"text/enriched\":{\"source\":\"iana\"},\"text/flexfec\":{\"source\":\"iana\"},\"text/fwdred\":{\"source\":\"iana\"},\"text/grammar-ref-list\":{\"source\":\"iana\"},\"text/html\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"html\",\"htm\",\"shtml\"]},\"text/jade\":{\"extensions\":[\"jade\"]},\"text/javascript\":{\"source\":\"iana\",\"compressible\":true},\"text/jcr-cnd\":{\"source\":\"iana\"},\"text/jsx\":{\"compressible\":true,\"extensions\":[\"jsx\"]},\"text/less\":{\"compressible\":true,\"extensions\":[\"less\"]},\"text/markdown\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"markdown\",\"md\"]},\"text/mathml\":{\"source\":\"nginx\",\"extensions\":[\"mml\"]},\"text/mdx\":{\"compressible\":true,\"extensions\":[\"mdx\"]},\"text/mizar\":{\"source\":\"iana\"},\"text/n3\":{\"source\":\"iana\",\"charset\":\"UTF-8\",\"compressible\":true,\"extensions\":[\"n3\"]},\"text/parameters\":{\"source\":\"iana\",\"charset\":\"UTF-8\"},\"text/parityfec\":{\"source\":\"iana\"},\"text/plain\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"txt\",\"text\",\"conf\",\"def\",\"list\",\"log\",\"in\",\"ini\"]},\"text/provenance-notation\":{\"source\":\"iana\",\"charset\":\"UTF-8\"},\"text/prs.fallenstein.rst\":{\"source\":\"iana\"},\"text/prs.lines.tag\":{\"source\":\"iana\",\"extensions\":[\"dsc\"]},\"text/prs.prop.logic\":{\"source\":\"iana\"},\"text/raptorfec\":{\"source\":\"iana\"},\"text/red\":{\"source\":\"iana\"},\"text/rfc822-headers\":{\"source\":\"iana\"},\"text/richtext\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"rtx\"]},\"text/rtf\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"rtf\"]},\"text/rtp-enc-aescm128\":{\"source\":\"iana\"},\"text/rtploopback\":{\"source\":\"iana\"},\"text/rtx\":{\"source\":\"iana\"},\"text/sgml\":{\"source\":\"iana\",\"extensions\":[\"sgml\",\"sgm\"]},\"text/shex\":{\"extensions\":[\"shex\"]},\"text/slim\":{\"extensions\":[\"slim\",\"slm\"]},\"text/strings\":{\"source\":\"iana\"},\"text/stylus\":{\"extensions\":[\"stylus\",\"styl\"]},\"text/t140\":{\"source\":\"iana\"},\"text/tab-separated-values\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"tsv\"]},\"text/troff\":{\"source\":\"iana\",\"extensions\":[\"t\",\"tr\",\"roff\",\"man\",\"me\",\"ms\"]},\"text/turtle\":{\"source\":\"iana\",\"charset\":\"UTF-8\",\"extensions\":[\"ttl\"]},\"text/ulpfec\":{\"source\":\"iana\"},\"text/uri-list\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"uri\",\"uris\",\"urls\"]},\"text/vcard\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"vcard\"]},\"text/vnd.a\":{\"source\":\"iana\"},\"text/vnd.abc\":{\"source\":\"iana\"},\"text/vnd.ascii-art\":{\"source\":\"iana\"},\"text/vnd.curl\":{\"source\":\"iana\",\"extensions\":[\"curl\"]},\"text/vnd.curl.dcurl\":{\"source\":\"apache\",\"extensions\":[\"dcurl\"]},\"text/vnd.curl.mcurl\":{\"source\":\"apache\",\"extensions\":[\"mcurl\"]},\"text/vnd.curl.scurl\":{\"source\":\"apache\",\"extensions\":[\"scurl\"]},\"text/vnd.debian.copyright\":{\"source\":\"iana\",\"charset\":\"UTF-8\"},\"text/vnd.dmclientscript\":{\"source\":\"iana\"},\"text/vnd.dvb.subtitle\":{\"source\":\"iana\",\"extensions\":[\"sub\"]},\"text/vnd.esmertec.theme-descriptor\":{\"source\":\"iana\",\"charset\":\"UTF-8\"},\"text/vnd.ficlab.flt\":{\"source\":\"iana\"},\"text/vnd.fly\":{\"source\":\"iana\",\"extensions\":[\"fly\"]},\"text/vnd.fmi.flexstor\":{\"source\":\"iana\",\"extensions\":[\"flx\"]},\"text/vnd.gml\":{\"source\":\"iana\"},\"text/vnd.graphviz\":{\"source\":\"iana\",\"extensions\":[\"gv\"]},\"text/vnd.hgl\":{\"source\":\"iana\"},\"text/vnd.in3d.3dml\":{\"source\":\"iana\",\"extensions\":[\"3dml\"]},\"text/vnd.in3d.spot\":{\"source\":\"iana\",\"extensions\":[\"spot\"]},\"text/vnd.iptc.newsml\":{\"source\":\"iana\"},\"text/vnd.iptc.nitf\":{\"source\":\"iana\"},\"text/vnd.latex-z\":{\"source\":\"iana\"},\"text/vnd.motorola.reflex\":{\"source\":\"iana\"},\"text/vnd.ms-mediapackage\":{\"source\":\"iana\"},\"text/vnd.net2phone.commcenter.command\":{\"source\":\"iana\"},\"text/vnd.radisys.msml-basic-layout\":{\"source\":\"iana\"},\"text/vnd.senx.warpscript\":{\"source\":\"iana\"},\"text/vnd.si.uricatalogue\":{\"source\":\"iana\"},\"text/vnd.sosi\":{\"source\":\"iana\"},\"text/vnd.sun.j2me.app-descriptor\":{\"source\":\"iana\",\"charset\":\"UTF-8\",\"extensions\":[\"jad\"]},\"text/vnd.trolltech.linguist\":{\"source\":\"iana\",\"charset\":\"UTF-8\"},\"text/vnd.wap.si\":{\"source\":\"iana\"},\"text/vnd.wap.sl\":{\"source\":\"iana\"},\"text/vnd.wap.wml\":{\"source\":\"iana\",\"extensions\":[\"wml\"]},\"text/vnd.wap.wmlscript\":{\"source\":\"iana\",\"extensions\":[\"wmls\"]},\"text/vtt\":{\"source\":\"iana\",\"charset\":\"UTF-8\",\"compressible\":true,\"extensions\":[\"vtt\"]},\"text/x-asm\":{\"source\":\"apache\",\"extensions\":[\"s\",\"asm\"]},\"text/x-c\":{\"source\":\"apache\",\"extensions\":[\"c\",\"cc\",\"cxx\",\"cpp\",\"h\",\"hh\",\"dic\"]},\"text/x-component\":{\"source\":\"nginx\",\"extensions\":[\"htc\"]},\"text/x-fortran\":{\"source\":\"apache\",\"extensions\":[\"f\",\"for\",\"f77\",\"f90\"]},\"text/x-gwt-rpc\":{\"compressible\":true},\"text/x-handlebars-template\":{\"extensions\":[\"hbs\"]},\"text/x-java-source\":{\"source\":\"apache\",\"extensions\":[\"java\"]},\"text/x-jquery-tmpl\":{\"compressible\":true},\"text/x-lua\":{\"extensions\":[\"lua\"]},\"text/x-markdown\":{\"compressible\":true,\"extensions\":[\"mkd\"]},\"text/x-nfo\":{\"source\":\"apache\",\"extensions\":[\"nfo\"]},\"text/x-opml\":{\"source\":\"apache\",\"extensions\":[\"opml\"]},\"text/x-org\":{\"compressible\":true,\"extensions\":[\"org\"]},\"text/x-pascal\":{\"source\":\"apache\",\"extensions\":[\"p\",\"pas\"]},\"text/x-processing\":{\"compressible\":true,\"extensions\":[\"pde\"]},\"text/x-sass\":{\"extensions\":[\"sass\"]},\"text/x-scss\":{\"extensions\":[\"scss\"]},\"text/x-setext\":{\"source\":\"apache\",\"extensions\":[\"etx\"]},\"text/x-sfv\":{\"source\":\"apache\",\"extensions\":[\"sfv\"]},\"text/x-suse-ymp\":{\"compressible\":true,\"extensions\":[\"ymp\"]},\"text/x-uuencode\":{\"source\":\"apache\",\"extensions\":[\"uu\"]},\"text/x-vcalendar\":{\"source\":\"apache\",\"extensions\":[\"vcs\"]},\"text/x-vcard\":{\"source\":\"apache\",\"extensions\":[\"vcf\"]},\"text/xml\":{\"source\":\"iana\",\"compressible\":true,\"extensions\":[\"xml\"]},\"text/xml-external-parsed-entity\":{\"source\":\"iana\"},\"text/yaml\":{\"extensions\":[\"yaml\",\"yml\"]},\"video/1d-interleaved-parityfec\":{\"source\":\"iana\"},\"video/3gpp\":{\"source\":\"iana\",\"extensions\":[\"3gp\",\"3gpp\"]},\"video/3gpp-tt\":{\"source\":\"iana\"},\"video/3gpp2\":{\"source\":\"iana\",\"extensions\":[\"3g2\"]},\"video/bmpeg\":{\"source\":\"iana\"},\"video/bt656\":{\"source\":\"iana\"},\"video/celb\":{\"source\":\"iana\"},\"video/dv\":{\"source\":\"iana\"},\"video/encaprtp\":{\"source\":\"iana\"},\"video/flexfec\":{\"source\":\"iana\"},\"video/h261\":{\"source\":\"iana\",\"extensions\":[\"h261\"]},\"video/h263\":{\"source\":\"iana\",\"extensions\":[\"h263\"]},\"video/h263-1998\":{\"source\":\"iana\"},\"video/h263-2000\":{\"source\":\"iana\"},\"video/h264\":{\"source\":\"iana\",\"extensions\":[\"h264\"]},\"video/h264-rcdo\":{\"source\":\"iana\"},\"video/h264-svc\":{\"source\":\"iana\"},\"video/h265\":{\"source\":\"iana\"},\"video/iso.segment\":{\"source\":\"iana\"},\"video/jpeg\":{\"source\":\"iana\",\"extensions\":[\"jpgv\"]},\"video/jpeg2000\":{\"source\":\"iana\"},\"video/jpm\":{\"source\":\"apache\",\"extensions\":[\"jpm\",\"jpgm\"]},\"video/mj2\":{\"source\":\"iana\",\"extensions\":[\"mj2\",\"mjp2\"]},\"video/mp1s\":{\"source\":\"iana\"},\"video/mp2p\":{\"source\":\"iana\"},\"video/mp2t\":{\"source\":\"iana\",\"extensions\":[\"ts\"]},\"video/mp4\":{\"source\":\"iana\",\"compressible\":false,\"extensions\":[\"mp4\",\"mp4v\",\"mpg4\"]},\"video/mp4v-es\":{\"source\":\"iana\"},\"video/mpeg\":{\"source\":\"iana\",\"compressible\":false,\"extensions\":[\"mpeg\",\"mpg\",\"mpe\",\"m1v\",\"m2v\"]},\"video/mpeg4-generic\":{\"source\":\"iana\"},\"video/mpv\":{\"source\":\"iana\"},\"video/nv\":{\"source\":\"iana\"},\"video/ogg\":{\"source\":\"iana\",\"compressible\":false,\"extensions\":[\"ogv\"]},\"video/parityfec\":{\"source\":\"iana\"},\"video/pointer\":{\"source\":\"iana\"},\"video/quicktime\":{\"source\":\"iana\",\"compressible\":false,\"extensions\":[\"qt\",\"mov\"]},\"video/raptorfec\":{\"source\":\"iana\"},\"video/raw\":{\"source\":\"iana\"},\"video/rtp-enc-aescm128\":{\"source\":\"iana\"},\"video/rtploopback\":{\"source\":\"iana\"},\"video/rtx\":{\"source\":\"iana\"},\"video/smpte291\":{\"source\":\"iana\"},\"video/smpte292m\":{\"source\":\"iana\"},\"video/ulpfec\":{\"source\":\"iana\"},\"video/vc1\":{\"source\":\"iana\"},\"video/vc2\":{\"source\":\"iana\"},\"video/vnd.cctv\":{\"source\":\"iana\"},\"video/vnd.dece.hd\":{\"source\":\"iana\",\"extensions\":[\"uvh\",\"uvvh\"]},\"video/vnd.dece.mobile\":{\"source\":\"iana\",\"extensions\":[\"uvm\",\"uvvm\"]},\"video/vnd.dece.mp4\":{\"source\":\"iana\"},\"video/vnd.dece.pd\":{\"source\":\"iana\",\"extensions\":[\"uvp\",\"uvvp\"]},\"video/vnd.dece.sd\":{\"source\":\"iana\",\"extensions\":[\"uvs\",\"uvvs\"]},\"video/vnd.dece.video\":{\"source\":\"iana\",\"extensions\":[\"uvv\",\"uvvv\"]},\"video/vnd.directv.mpeg\":{\"source\":\"iana\"},\"video/vnd.directv.mpeg-tts\":{\"source\":\"iana\"},\"video/vnd.dlna.mpeg-tts\":{\"source\":\"iana\"},\"video/vnd.dvb.file\":{\"source\":\"iana\",\"extensions\":[\"dvb\"]},\"video/vnd.fvt\":{\"source\":\"iana\",\"extensions\":[\"fvt\"]},\"video/vnd.hns.video\":{\"source\":\"iana\"},\"video/vnd.iptvforum.1dparityfec-1010\":{\"source\":\"iana\"},\"video/vnd.iptvforum.1dparityfec-2005\":{\"source\":\"iana\"},\"video/vnd.iptvforum.2dparityfec-1010\":{\"source\":\"iana\"},\"video/vnd.iptvforum.2dparityfec-2005\":{\"source\":\"iana\"},\"video/vnd.iptvforum.ttsavc\":{\"source\":\"iana\"},\"video/vnd.iptvforum.ttsmpeg2\":{\"source\":\"iana\"},\"video/vnd.motorola.video\":{\"source\":\"iana\"},\"video/vnd.motorola.videop\":{\"source\":\"iana\"},\"video/vnd.mpegurl\":{\"source\":\"iana\",\"extensions\":[\"mxu\",\"m4u\"]},\"video/vnd.ms-playready.media.pyv\":{\"source\":\"iana\",\"extensions\":[\"pyv\"]},\"video/vnd.nokia.interleaved-multimedia\":{\"source\":\"iana\"},\"video/vnd.nokia.mp4vr\":{\"source\":\"iana\"},\"video/vnd.nokia.videovoip\":{\"source\":\"iana\"},\"video/vnd.objectvideo\":{\"source\":\"iana\"},\"video/vnd.radgamettools.bink\":{\"source\":\"iana\"},\"video/vnd.radgamettools.smacker\":{\"source\":\"iana\"},\"video/vnd.sealed.mpeg1\":{\"source\":\"iana\"},\"video/vnd.sealed.mpeg4\":{\"source\":\"iana\"},\"video/vnd.sealed.swf\":{\"source\":\"iana\"},\"video/vnd.sealedmedia.softseal.mov\":{\"source\":\"iana\"},\"video/vnd.uvvu.mp4\":{\"source\":\"iana\",\"extensions\":[\"uvu\",\"uvvu\"]},\"video/vnd.vivo\":{\"source\":\"iana\",\"extensions\":[\"viv\"]},\"video/vnd.youtube.yt\":{\"source\":\"iana\"},\"video/vp8\":{\"source\":\"iana\"},\"video/webm\":{\"source\":\"apache\",\"compressible\":false,\"extensions\":[\"webm\"]},\"video/x-f4v\":{\"source\":\"apache\",\"extensions\":[\"f4v\"]},\"video/x-fli\":{\"source\":\"apache\",\"extensions\":[\"fli\"]},\"video/x-flv\":{\"source\":\"apache\",\"compressible\":false,\"extensions\":[\"flv\"]},\"video/x-m4v\":{\"source\":\"apache\",\"extensions\":[\"m4v\"]},\"video/x-matroska\":{\"source\":\"apache\",\"compressible\":false,\"extensions\":[\"mkv\",\"mk3d\",\"mks\"]},\"video/x-mng\":{\"source\":\"apache\",\"extensions\":[\"mng\"]},\"video/x-ms-asf\":{\"source\":\"apache\",\"extensions\":[\"asf\",\"asx\"]},\"video/x-ms-vob\":{\"source\":\"apache\",\"extensions\":[\"vob\"]},\"video/x-ms-wm\":{\"source\":\"apache\",\"extensions\":[\"wm\"]},\"video/x-ms-wmv\":{\"source\":\"apache\",\"compressible\":false,\"extensions\":[\"wmv\"]},\"video/x-ms-wmx\":{\"source\":\"apache\",\"extensions\":[\"wmx\"]},\"video/x-ms-wvx\":{\"source\":\"apache\",\"extensions\":[\"wvx\"]},\"video/x-msvideo\":{\"source\":\"apache\",\"extensions\":[\"avi\"]},\"video/x-sgi-movie\":{\"source\":\"apache\",\"extensions\":[\"movie\"]},\"video/x-smv\":{\"source\":\"apache\",\"extensions\":[\"smv\"]},\"x-conference/x-cooltalk\":{\"source\":\"apache\",\"extensions\":[\"ice\"]},\"x-shader/x-fragment\":{\"compressible\":true},\"x-shader/x-vertex\":{\"compressible\":true}}"); + +/***/ }), + +/***/ "./node_modules/mime-db/index.js": +/*!***************************************!*\ + !*** ./node_modules/mime-db/index.js ***! + \***************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +/*! + * mime-db + * Copyright(c) 2014 Jonathan Ong + * MIT Licensed + */ + +/** + * Module exports. + */ + +module.exports = __webpack_require__(/*! ./db.json */ "./node_modules/mime-db/db.json") + + +/***/ }), + +/***/ "./node_modules/mime-types/index.js": +/*!******************************************!*\ + !*** ./node_modules/mime-types/index.js ***! + \******************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/*! + * mime-types + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + + + +/** + * Module dependencies. + * @private + */ + +var db = __webpack_require__(/*! mime-db */ "./node_modules/mime-db/index.js") +var extname = __webpack_require__(/*! path */ "./node_modules/node-libs-browser/node_modules/path-browserify/index.js").extname + +/** + * Module variables. + * @private + */ + +var EXTRACT_TYPE_REGEXP = /^\s*([^;\s]*)(?:;|\s|$)/ +var TEXT_TYPE_REGEXP = /^text\//i + +/** + * Module exports. + * @public + */ + +exports.charset = charset +exports.charsets = { lookup: charset } +exports.contentType = contentType +exports.extension = extension +exports.extensions = Object.create(null) +exports.lookup = lookup +exports.types = Object.create(null) + +// Populate the extensions/types maps +populateMaps(exports.extensions, exports.types) + +/** + * Get the default charset for a MIME type. + * + * @param {string} type + * @return {boolean|string} + */ + +function charset (type) { + if (!type || typeof type !== 'string') { + return false + } + + // TODO: use media-typer + var match = EXTRACT_TYPE_REGEXP.exec(type) + var mime = match && db[match[1].toLowerCase()] + + if (mime && mime.charset) { + return mime.charset + } + + // default text/* to utf-8 + if (match && TEXT_TYPE_REGEXP.test(match[1])) { + return 'UTF-8' + } + + return false +} + +/** + * Create a full Content-Type header given a MIME type or extension. + * + * @param {string} str + * @return {boolean|string} + */ + +function contentType (str) { + // TODO: should this even be in this module? + if (!str || typeof str !== 'string') { + return false + } + + var mime = str.indexOf('/') === -1 + ? exports.lookup(str) + : str + + if (!mime) { + return false + } + + // TODO: use content-type or other module + if (mime.indexOf('charset') === -1) { + var charset = exports.charset(mime) + if (charset) mime += '; charset=' + charset.toLowerCase() + } + + return mime +} + +/** + * Get the default extension for a MIME type. + * + * @param {string} type + * @return {boolean|string} + */ + +function extension (type) { + if (!type || typeof type !== 'string') { + return false + } + + // TODO: use media-typer + var match = EXTRACT_TYPE_REGEXP.exec(type) + + // get extensions + var exts = match && exports.extensions[match[1].toLowerCase()] + + if (!exts || !exts.length) { + return false + } + + return exts[0] +} + +/** + * Lookup the MIME type for a file path/extension. + * + * @param {string} path + * @return {boolean|string} + */ + +function lookup (path) { + if (!path || typeof path !== 'string') { + return false + } + + // get the extension ("ext" or ".ext" or full path) + var extension = extname('x.' + path) + .toLowerCase() + .substr(1) + + if (!extension) { + return false + } + + return exports.types[extension] || false +} + +/** + * Populate the extensions and types maps. + * @private + */ + +function populateMaps (extensions, types) { + // source preference (least -> most) + var preference = ['nginx', 'apache', undefined, 'iana'] + + Object.keys(db).forEach(function forEachMimeType (type) { + var mime = db[type] + var exts = mime.extensions + + if (!exts || !exts.length) { + return + } + + // mime -> extensions + extensions[type] = exts + + // extension -> mime + for (var i = 0; i < exts.length; i++) { + var extension = exts[i] + + if (types[extension]) { + var from = preference.indexOf(db[types[extension]].source) + var to = preference.indexOf(mime.source) + + if (types[extension] !== 'application/octet-stream' && + (from > to || (from === to && types[extension].substr(0, 12) === 'application/'))) { + // skip the remapping + continue + } + } + + // set the extension -> mime + types[extension] = type + } + }) +} + + +/***/ }), + +/***/ "./node_modules/n3/src/IRIs.js": +/*!*************************************!*\ + !*** ./node_modules/n3/src/IRIs.js ***! + \*************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +const RDF = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#', + XSD = 'http://www.w3.org/2001/XMLSchema#', + SWAP = 'http://www.w3.org/2000/10/swap/'; + +/* harmony default export */ __webpack_exports__["default"] = ({ + xsd: { + decimal: `${XSD}decimal`, + boolean: `${XSD}boolean`, + double: `${XSD}double`, + integer: `${XSD}integer`, + string: `${XSD}string`, + }, + rdf: { + type: `${RDF}type`, + nil: `${RDF}nil`, + first: `${RDF}first`, + rest: `${RDF}rest`, + langString: `${RDF}langString`, + }, + owl: { + sameAs: 'http://www.w3.org/2002/07/owl#sameAs', + }, + r: { + forSome: `${SWAP}reify#forSome`, + forAll: `${SWAP}reify#forAll`, + }, + log: { + implies: `${SWAP}log#implies`, + }, +}); + + +/***/ }), + +/***/ "./node_modules/n3/src/N3DataFactory.js": +/*!**********************************************!*\ + !*** ./node_modules/n3/src/N3DataFactory.js ***! + \**********************************************/ +/*! exports provided: default, Term, NamedNode, Literal, BlankNode, Variable, DefaultGraph, termFromId, termToId, Quad, Triple, escapeQuotes, unescapeQuotes */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Term", function() { return Term; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NamedNode", function() { return NamedNode; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Literal", function() { return Literal; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BlankNode", function() { return BlankNode; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Variable", function() { return Variable; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DefaultGraph", function() { return DefaultGraph; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "termFromId", function() { return termFromId; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "termToId", function() { return termToId; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Quad", function() { return Quad; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Triple", function() { return Quad; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "escapeQuotes", function() { return escapeQuotes; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "unescapeQuotes", function() { return unescapeQuotes; }); +/* harmony import */ var _IRIs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./IRIs */ "./node_modules/n3/src/IRIs.js"); +/* harmony import */ var _N3Util__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./N3Util */ "./node_modules/n3/src/N3Util.js"); +// N3.js implementations of the RDF/JS core data types +// See https://github.com/rdfjs/representation-task-force/blob/master/interface-spec.md + + + +const { rdf, xsd } = _IRIs__WEBPACK_IMPORTED_MODULE_0__["default"]; + +// eslint-disable-next-line prefer-const +let DEFAULTGRAPH; +let _blankNodeCounter = 0; + +const escapedLiteral = /^"(.*".*)(?="[^"]*$)/; +const quadId = /^<<("(?:""|[^"])*"[^ ]*|[^ ]+) ("(?:""|[^"])*"[^ ]*|[^ ]+) ("(?:""|[^"])*"[^ ]*|[^ ]+) ?("(?:""|[^"])*"[^ ]*|[^ ]+)?>>$/; + +// ## DataFactory singleton +const DataFactory = { + namedNode, + blankNode, + variable, + literal, + defaultGraph, + quad, + triple: quad, +}; +/* harmony default export */ __webpack_exports__["default"] = (DataFactory); + +// ## Term constructor +class Term { + constructor(id) { + this.id = id; + } + + // ### The value of this term + get value() { + return this.id; + } + + // ### Returns whether this object represents the same term as the other + equals(other) { + // If both terms were created by this library, + // equality can be computed through ids + if (other instanceof Term) + return this.id === other.id; + // Otherwise, compare term type and value + return !!other && this.termType === other.termType && + this.value === other.value; + } + + // ### Returns a plain object representation of this term + toJSON() { + return { + termType: this.termType, + value: this.value, + }; + } +} + + +// ## NamedNode constructor +class NamedNode extends Term { + // ### The term type of this term + get termType() { + return 'NamedNode'; + } +} + +// ## Literal constructor +class Literal extends Term { + // ### The term type of this term + get termType() { + return 'Literal'; + } + + // ### The text value of this literal + get value() { + return this.id.substring(1, this.id.lastIndexOf('"')); + } + + // ### The language of this literal + get language() { + // Find the last quotation mark (e.g., '"abc"@en-us') + const id = this.id; + let atPos = id.lastIndexOf('"') + 1; + // If "@" it follows, return the remaining substring; empty otherwise + return atPos < id.length && id[atPos++] === '@' ? id.substr(atPos).toLowerCase() : ''; + } + + // ### The datatype IRI of this literal + get datatype() { + return new NamedNode(this.datatypeString); + } + + // ### The datatype string of this literal + get datatypeString() { + // Find the last quotation mark (e.g., '"abc"^^http://ex.org/types#t') + const id = this.id, dtPos = id.lastIndexOf('"') + 1; + const char = dtPos < id.length ? id[dtPos] : ''; + // If "^" it follows, return the remaining substring + return char === '^' ? id.substr(dtPos + 2) : + // If "@" follows, return rdf:langString; xsd:string otherwise + (char !== '@' ? xsd.string : rdf.langString); + } + + // ### Returns whether this object represents the same term as the other + equals(other) { + // If both literals were created by this library, + // equality can be computed through ids + if (other instanceof Literal) + return this.id === other.id; + // Otherwise, compare term type, value, language, and datatype + return !!other && !!other.datatype && + this.termType === other.termType && + this.value === other.value && + this.language === other.language && + this.datatype.value === other.datatype.value; + } + + toJSON() { + return { + termType: this.termType, + value: this.value, + language: this.language, + datatype: { termType: 'NamedNode', value: this.datatypeString }, + }; + } +} + +// ## BlankNode constructor +class BlankNode extends Term { + constructor(name) { + super(`_:${name}`); + } + + // ### The term type of this term + get termType() { + return 'BlankNode'; + } + + // ### The name of this blank node + get value() { + return this.id.substr(2); + } +} + +class Variable extends Term { + constructor(name) { + super(`?${name}`); + } + + // ### The term type of this term + get termType() { + return 'Variable'; + } + + // ### The name of this variable + get value() { + return this.id.substr(1); + } +} + +// ## DefaultGraph constructor +class DefaultGraph extends Term { + constructor() { + super(''); + return DEFAULTGRAPH || this; + } + + // ### The term type of this term + get termType() { + return 'DefaultGraph'; + } + + // ### Returns whether this object represents the same term as the other + equals(other) { + // If both terms were created by this library, + // equality can be computed through strict equality; + // otherwise, compare term types. + return (this === other) || (!!other && (this.termType === other.termType)); + } +} + +// ## DefaultGraph singleton +DEFAULTGRAPH = new DefaultGraph(); + + +// ### Constructs a term from the given internal string ID +function termFromId(id, factory) { + factory = factory || DataFactory; + + // Falsy value or empty string indicate the default graph + if (!id) + return factory.defaultGraph(); + + // Identify the term type based on the first character + switch (id[0]) { + case '?': + return factory.variable(id.substr(1)); + case '_': + return factory.blankNode(id.substr(2)); + case '"': + // Shortcut for internal literals + if (factory === DataFactory) + return new Literal(id); + // Literal without datatype or language + if (id[id.length - 1] === '"') + return factory.literal(id.substr(1, id.length - 2)); + // Literal with datatype or language + const endPos = id.lastIndexOf('"', id.length - 1); + return factory.literal(id.substr(1, endPos - 1), + id[endPos + 1] === '@' ? id.substr(endPos + 2) + : factory.namedNode(id.substr(endPos + 3))); + case '<': + const components = quadId.exec(id); + return factory.quad( + termFromId(unescapeQuotes(components[1]), factory), + termFromId(unescapeQuotes(components[2]), factory), + termFromId(unescapeQuotes(components[3]), factory), + components[4] && termFromId(unescapeQuotes(components[4]), factory) + ); + default: + return factory.namedNode(id); + } +} + +// ### Constructs an internal string ID from the given term or ID string +function termToId(term) { + if (typeof term === 'string') + return term; + if (term instanceof Term && term.termType !== 'Quad') + return term.id; + if (!term) + return DEFAULTGRAPH.id; + + // Term instantiated with another library + switch (term.termType) { + case 'NamedNode': return term.value; + case 'BlankNode': return `_:${term.value}`; + case 'Variable': return `?${term.value}`; + case 'DefaultGraph': return ''; + case 'Literal': return `"${term.value}"${ + term.language ? `@${term.language}` : + (term.datatype && term.datatype.value !== xsd.string ? `^^${term.datatype.value}` : '')}`; + case 'Quad': + // To identify RDF* quad components, we escape quotes by doubling them. + // This avoids the overhead of backslash parsing of Turtle-like syntaxes. + return `<<${ + escapeQuotes(termToId(term.subject)) + } ${ + escapeQuotes(termToId(term.predicate)) + } ${ + escapeQuotes(termToId(term.object)) + }${ + (Object(_N3Util__WEBPACK_IMPORTED_MODULE_1__["isDefaultGraph"])(term.graph)) ? '' : ` ${termToId(term.graph)}` + }>>`; + default: throw new Error(`Unexpected termType: ${term.termType}`); + } +} + + +// ## Quad constructor +class Quad extends Term { + constructor(subject, predicate, object, graph) { + super(''); + this.subject = subject; + this.predicate = predicate; + this.object = object; + this.graph = graph || DEFAULTGRAPH; + } + + // ### The term type of this term + get termType() { + return 'Quad'; + } + + // ### Returns a plain object representation of this quad + toJSON() { + return { + termType: this.termType, + subject: this.subject.toJSON(), + predicate: this.predicate.toJSON(), + object: this.object.toJSON(), + graph: this.graph.toJSON(), + }; + } + + // ### Returns whether this object represents the same quad as the other + equals(other) { + return !!other && this.subject.equals(other.subject) && + this.predicate.equals(other.predicate) && + this.object.equals(other.object) && + this.graph.equals(other.graph); + } +} + + +// ### Escapes the quotes within the given literal +function escapeQuotes(id) { + return id.replace(escapedLiteral, (_, quoted) => `"${quoted.replace(/"/g, '""')}`); +} + +// ### Unescapes the quotes within the given literal +function unescapeQuotes(id) { + return id.replace(escapedLiteral, (_, quoted) => `"${quoted.replace(/""/g, '"')}`); +} + +// ### Creates an IRI +function namedNode(iri) { + return new NamedNode(iri); +} + +// ### Creates a blank node +function blankNode(name) { + return new BlankNode(name || `n3-${_blankNodeCounter++}`); +} + +// ### Creates a literal +function literal(value, languageOrDataType) { + // Create a language-tagged string + if (typeof languageOrDataType === 'string') + return new Literal(`"${value}"@${languageOrDataType.toLowerCase()}`); + + // Automatically determine datatype for booleans and numbers + let datatype = languageOrDataType ? languageOrDataType.value : ''; + if (datatype === '') { + // Convert a boolean + if (typeof value === 'boolean') + datatype = xsd.boolean; + // Convert an integer or double + else if (typeof value === 'number') { + if (Number.isFinite(value)) + datatype = Number.isInteger(value) ? xsd.integer : xsd.double; + else { + datatype = xsd.double; + if (!Number.isNaN(value)) + value = value > 0 ? 'INF' : '-INF'; + } + } + } + + // Create a datatyped literal + return (datatype === '' || datatype === xsd.string) ? + new Literal(`"${value}"`) : + new Literal(`"${value}"^^${datatype}`); +} + +// ### Creates a variable +function variable(name) { + return new Variable(name); +} + +// ### Returns the default graph +function defaultGraph() { + return DEFAULTGRAPH; +} + +// ### Creates a quad +function quad(subject, predicate, object, graph) { + return new Quad(subject, predicate, object, graph); +} + + +/***/ }), + +/***/ "./node_modules/n3/src/N3Lexer.js": +/*!****************************************!*\ + !*** ./node_modules/n3/src/N3Lexer.js ***! + \****************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* WEBPACK VAR INJECTION */(function(Buffer) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return N3Lexer; }); +/* harmony import */ var _IRIs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./IRIs */ "./node_modules/n3/src/IRIs.js"); +/* harmony import */ var queue_microtask__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! queue-microtask */ "./node_modules/queue-microtask/index.js"); +/* harmony import */ var queue_microtask__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(queue_microtask__WEBPACK_IMPORTED_MODULE_1__); +// **N3Lexer** tokenizes N3 documents. + + + +const { xsd } = _IRIs__WEBPACK_IMPORTED_MODULE_0__["default"]; + +// Regular expression and replacement string to escape N3 strings +const escapeSequence = /\\u([a-fA-F0-9]{4})|\\U([a-fA-F0-9]{8})|\\([^])/g; +const escapeReplacements = { + '\\': '\\', "'": "'", '"': '"', + 'n': '\n', 'r': '\r', 't': '\t', 'f': '\f', 'b': '\b', + '_': '_', '~': '~', '.': '.', '-': '-', '!': '!', '$': '$', '&': '&', + '(': '(', ')': ')', '*': '*', '+': '+', ',': ',', ';': ';', '=': '=', + '/': '/', '?': '?', '#': '#', '@': '@', '%': '%', +}; +const illegalIriChars = /[\x00-\x20<>\\"\{\}\|\^\`]/; + +const lineModeRegExps = { + _iri: true, + _unescapedIri: true, + _simpleQuotedString: true, + _langcode: true, + _blank: true, + _newline: true, + _comment: true, + _whitespace: true, + _endOfFile: true, +}; +const invalidRegExp = /$0^/; + +// ## Constructor +class N3Lexer { + constructor(options) { + // ## Regular expressions + // It's slightly faster to have these as properties than as in-scope variables + this._iri = /^<((?:[^ <>{}\\]|\\[uU])+)>[ \t]*/; // IRI with escape sequences; needs sanity check after unescaping + this._unescapedIri = /^<([^\x00-\x20<>\\"\{\}\|\^\`]*)>[ \t]*/; // IRI without escape sequences; no unescaping + this._simpleQuotedString = /^"([^"\\\r\n]*)"(?=[^"])/; // string without escape sequences + this._simpleApostropheString = /^'([^'\\\r\n]*)'(?=[^'])/; + this._langcode = /^@([a-z]+(?:-[a-z0-9]+)*)(?=[^a-z0-9\-])/i; + this._prefix = /^((?:[A-Za-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])(?:\.?[\-0-9A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])*)?:(?=[#\s<])/; + this._prefixed = /^((?:[A-Za-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])(?:\.?[\-0-9A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])*)?:((?:(?:[0-:A-Z_a-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff]|%[0-9a-fA-F]{2}|\\[!#-\/;=?\-@_~])(?:(?:[\.\-0-:A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff]|%[0-9a-fA-F]{2}|\\[!#-\/;=?\-@_~])*(?:[\-0-:A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff]|%[0-9a-fA-F]{2}|\\[!#-\/;=?\-@_~]))?)?)(?:[ \t]+|(?=\.?[,;!\^\s#()\[\]\{\}"'<>]))/; + this._variable = /^\?(?:(?:[A-Z_a-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])(?:[\-0-:A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])*)(?=[.,;!\^\s#()\[\]\{\}"'<>])/; + this._blank = /^_:((?:[0-9A-Z_a-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])(?:\.?[\-0-9A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])*)(?:[ \t]+|(?=\.?[,;:\s#()\[\]\{\}"'<>]))/; + this._number = /^[\-+]?(?:(\d+\.\d*|\.?\d+)[eE][\-+]?|\d*(\.)?)\d+(?=\.?[,;:\s#()\[\]\{\}"'<>])/; + this._boolean = /^(?:true|false)(?=[.,;\s#()\[\]\{\}"'<>])/; + this._keyword = /^@[a-z]+(?=[\s#<:])/i; + this._sparqlKeyword = /^(?:PREFIX|BASE|GRAPH)(?=[\s#<])/i; + this._shortPredicates = /^a(?=[\s()\[\]\{\}"'<>])/; + this._newline = /^[ \t]*(?:#[^\n\r]*)?(?:\r\n|\n|\r)[ \t]*/; + this._comment = /#([^\n\r]*)/; + this._whitespace = /^[ \t]+/; + this._endOfFile = /^(?:#[^\n\r]*)?$/; + options = options || {}; + + // In line mode (N-Triples or N-Quads), only simple features may be parsed + if (this._lineMode = !!options.lineMode) { + this._n3Mode = false; + // Don't tokenize special literals + for (const key in this) { + if (!(key in lineModeRegExps) && this[key] instanceof RegExp) + this[key] = invalidRegExp; + } + } + // When not in line mode, enable N3 functionality by default + else { + this._n3Mode = options.n3 !== false; + } + // Don't output comment tokens by default + this._comments = !!options.comments; + // Cache the last tested closing position of long literals + this._literalClosingPos = 0; + } + + // ## Private methods + + // ### `_tokenizeToEnd` tokenizes as for as possible, emitting tokens through the callback + _tokenizeToEnd(callback, inputFinished) { + // Continue parsing as far as possible; the loop will return eventually + let input = this._input; + const outputComments = this._comments; + while (true) { + // Count and skip whitespace lines + let whiteSpaceMatch, comment; + while (whiteSpaceMatch = this._newline.exec(input)) { + // Try to find a comment + if (outputComments && (comment = this._comment.exec(whiteSpaceMatch[0]))) + callback(null, { line: this._line, type: 'comment', value: comment[1], prefix: '' }); + // Advance the input + input = input.substr(whiteSpaceMatch[0].length, input.length); + this._line++; + } + // Skip whitespace on current line + if (!whiteSpaceMatch && (whiteSpaceMatch = this._whitespace.exec(input))) + input = input.substr(whiteSpaceMatch[0].length, input.length); + + // Stop for now if we're at the end + if (this._endOfFile.test(input)) { + // If the input is finished, emit EOF + if (inputFinished) { + // Try to find a final comment + if (outputComments && (comment = this._comment.exec(input))) + callback(null, { line: this._line, type: 'comment', value: comment[1], prefix: '' }); + callback(input = null, { line: this._line, type: 'eof', value: '', prefix: '' }); + } + return this._input = input; + } + + // Look for specific token types based on the first character + const line = this._line, firstChar = input[0]; + let type = '', value = '', prefix = '', + match = null, matchLength = 0, inconclusive = false; + switch (firstChar) { + case '^': + // We need at least 3 tokens lookahead to distinguish ^^ and ^^pre:fixed + if (input.length < 3) + break; + // Try to match a type + else if (input[1] === '^') { + this._previousMarker = '^^'; + // Move to type IRI or prefixed name + input = input.substr(2); + if (input[0] !== '<') { + inconclusive = true; + break; + } + } + // If no type, it must be a path expression + else { + if (this._n3Mode) { + matchLength = 1; + type = '^'; + } + break; + } + // Fall through in case the type is an IRI + case '<': + // Try to find a full IRI without escape sequences + if (match = this._unescapedIri.exec(input)) + type = 'IRI', value = match[1]; + // Try to find a full IRI with escape sequences + else if (match = this._iri.exec(input)) { + value = this._unescape(match[1]); + if (value === null || illegalIriChars.test(value)) + return reportSyntaxError(this); + type = 'IRI'; + } + // Try to find a nested triple + else if (input.length > 1 && input[1] === '<') + type = '<<', matchLength = 2; + // Try to find a backwards implication arrow + else if (this._n3Mode && input.length > 1 && input[1] === '=') + type = 'inverse', matchLength = 2, value = '>'; + break; + + case '>': + if (input.length > 1 && input[1] === '>') + type = '>>', matchLength = 2; + break; + + case '_': + // Try to find a blank node. Since it can contain (but not end with) a dot, + // we always need a non-dot character before deciding it is a blank node. + // Therefore, try inserting a space if we're at the end of the input. + if ((match = this._blank.exec(input)) || + inputFinished && (match = this._blank.exec(`${input} `))) + type = 'blank', prefix = '_', value = match[1]; + break; + + case '"': + // Try to find a literal without escape sequences + if (match = this._simpleQuotedString.exec(input)) + value = match[1]; + // Try to find a literal wrapped in three pairs of quotes + else { + ({ value, matchLength } = this._parseLiteral(input)); + if (value === null) + return reportSyntaxError(this); + } + if (match !== null || matchLength !== 0) { + type = 'literal'; + this._literalClosingPos = 0; + } + break; + + case "'": + if (!this._lineMode) { + // Try to find a literal without escape sequences + if (match = this._simpleApostropheString.exec(input)) + value = match[1]; + // Try to find a literal wrapped in three pairs of quotes + else { + ({ value, matchLength } = this._parseLiteral(input)); + if (value === null) + return reportSyntaxError(this); + } + if (match !== null || matchLength !== 0) { + type = 'literal'; + this._literalClosingPos = 0; + } + } + break; + + case '?': + // Try to find a variable + if (this._n3Mode && (match = this._variable.exec(input))) + type = 'var', value = match[0]; + break; + + case '@': + // Try to find a language code + if (this._previousMarker === 'literal' && (match = this._langcode.exec(input))) + type = 'langcode', value = match[1]; + // Try to find a keyword + else if (match = this._keyword.exec(input)) + type = match[0]; + break; + + case '.': + // Try to find a dot as punctuation + if (input.length === 1 ? inputFinished : (input[1] < '0' || input[1] > '9')) { + type = '.'; + matchLength = 1; + break; + } + // Fall through to numerical case (could be a decimal dot) + + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + case '+': + case '-': + // Try to find a number. Since it can contain (but not end with) a dot, + // we always need a non-dot character before deciding it is a number. + // Therefore, try inserting a space if we're at the end of the input. + if (match = this._number.exec(input) || + inputFinished && (match = this._number.exec(`${input} `))) { + type = 'literal', value = match[0]; + prefix = (typeof match[1] === 'string' ? xsd.double : + (typeof match[2] === 'string' ? xsd.decimal : xsd.integer)); + } + break; + + case 'B': + case 'b': + case 'p': + case 'P': + case 'G': + case 'g': + // Try to find a SPARQL-style keyword + if (match = this._sparqlKeyword.exec(input)) + type = match[0].toUpperCase(); + else + inconclusive = true; + break; + + case 'f': + case 't': + // Try to match a boolean + if (match = this._boolean.exec(input)) + type = 'literal', value = match[0], prefix = xsd.boolean; + else + inconclusive = true; + break; + + case 'a': + // Try to find an abbreviated predicate + if (match = this._shortPredicates.exec(input)) + type = 'abbreviation', value = 'a'; + else + inconclusive = true; + break; + + case '=': + // Try to find an implication arrow or equals sign + if (this._n3Mode && input.length > 1) { + type = 'abbreviation'; + if (input[1] !== '>') + matchLength = 1, value = '='; + else + matchLength = 2, value = '>'; + } + break; + + case '!': + if (!this._n3Mode) + break; + case ',': + case ';': + case '[': + case ']': + case '(': + case ')': + case '{': + case '}': + if (!this._lineMode) { + matchLength = 1; + type = firstChar; + } + break; + + default: + inconclusive = true; + } + + // Some first characters do not allow an immediate decision, so inspect more + if (inconclusive) { + // Try to find a prefix + if ((this._previousMarker === '@prefix' || this._previousMarker === 'PREFIX') && + (match = this._prefix.exec(input))) + type = 'prefix', value = match[1] || ''; + // Try to find a prefixed name. Since it can contain (but not end with) a dot, + // we always need a non-dot character before deciding it is a prefixed name. + // Therefore, try inserting a space if we're at the end of the input. + else if ((match = this._prefixed.exec(input)) || + inputFinished && (match = this._prefixed.exec(`${input} `))) + type = 'prefixed', prefix = match[1] || '', value = this._unescape(match[2]); + } + + // A type token is special: it can only be emitted after an IRI or prefixed name is read + if (this._previousMarker === '^^') { + switch (type) { + case 'prefixed': type = 'type'; break; + case 'IRI': type = 'typeIRI'; break; + default: type = ''; + } + } + + // What if nothing of the above was found? + if (!type) { + // We could be in streaming mode, and then we just wait for more input to arrive. + // Otherwise, a syntax error has occurred in the input. + // One exception: error on an unaccounted linebreak (= not inside a triple-quoted literal). + if (inputFinished || (!/^'''|^"""/.test(input) && /\n|\r/.test(input))) + return reportSyntaxError(this); + else + return this._input = input; + } + + // Emit the parsed token + const token = { line: line, type: type, value: value, prefix: prefix }; + callback(null, token); + this.previousToken = token; + this._previousMarker = type; + // Advance to next part to tokenize + input = input.substr(matchLength || match[0].length, input.length); + } + + // Signals the syntax error through the callback + function reportSyntaxError(self) { callback(self._syntaxError(/^\S*/.exec(input)[0])); } + } + + // ### `_unescape` replaces N3 escape codes by their corresponding characters + _unescape(item) { + let invalid = false; + const replaced = item.replace(escapeSequence, (sequence, unicode4, unicode8, escapedChar) => { + // 4-digit unicode character + if (typeof unicode4 === 'string') + return String.fromCharCode(Number.parseInt(unicode4, 16)); + // 8-digit unicode character + if (typeof unicode8 === 'string') { + let charCode = Number.parseInt(unicode8, 16); + return charCode <= 0xFFFF ? String.fromCharCode(Number.parseInt(unicode8, 16)) : + String.fromCharCode(0xD800 + ((charCode -= 0x10000) >> 10), 0xDC00 + (charCode & 0x3FF)); + } + // fixed escape sequence + if (escapedChar in escapeReplacements) + return escapeReplacements[escapedChar]; + // invalid escape sequence + invalid = true; + return ''; + }); + return invalid ? null : replaced; + } + + // ### `_parseLiteral` parses a literal into an unescaped value + _parseLiteral(input) { + // Ensure we have enough lookahead to identify triple-quoted strings + if (input.length >= 3) { + // Identify the opening quote(s) + const opening = input.match(/^(?:"""|"|'''|'|)/)[0]; + const openingLength = opening.length; + + // Find the next candidate closing quotes + let closingPos = Math.max(this._literalClosingPos, openingLength); + while ((closingPos = input.indexOf(opening, closingPos)) > 0) { + // Count backslashes right before the closing quotes + let backslashCount = 0; + while (input[closingPos - backslashCount - 1] === '\\') + backslashCount++; + + // An even number of backslashes (in particular 0) + // means these are actual, non-escaped closing quotes + if (backslashCount % 2 === 0) { + // Extract and unescape the value + const raw = input.substring(openingLength, closingPos); + const lines = raw.split(/\r\n|\r|\n/).length - 1; + const matchLength = closingPos + openingLength; + // Only triple-quoted strings can be multi-line + if (openingLength === 1 && lines !== 0 || + openingLength === 3 && this._lineMode) + break; + this._line += lines; + return { value: this._unescape(raw), matchLength }; + } + closingPos++; + } + this._literalClosingPos = input.length - openingLength + 1; + } + return { value: '', matchLength: 0 }; + } + + // ### `_syntaxError` creates a syntax error for the given issue + _syntaxError(issue) { + this._input = null; + const err = new Error(`Unexpected "${issue}" on line ${this._line}.`); + err.context = { + token: undefined, + line: this._line, + previousToken: this.previousToken, + }; + return err; + } + + // ## Public methods + + // ### `tokenize` starts the transformation of an N3 document into an array of tokens. + // The input can be a string or a stream. + tokenize(input, callback) { + this._line = 1; + + // If the input is a string, continuously emit tokens through the callback until the end + if (typeof input === 'string') { + this._input = input; + // If a callback was passed, asynchronously call it + if (typeof callback === 'function') + queue_microtask__WEBPACK_IMPORTED_MODULE_1___default()(() => this._tokenizeToEnd(callback, true)); + // If no callback was passed, tokenize synchronously and return + else { + const tokens = []; + let error; + this._tokenizeToEnd((e, t) => e ? (error = e) : tokens.push(t), true); + if (error) throw error; + return tokens; + } + } + // Otherwise, the input must be a stream + else { + this._input = ''; + this._pendingBuffer = null; + if (typeof input.setEncoding === 'function') + input.setEncoding('utf8'); + // Adds the data chunk to the buffer and parses as far as possible + input.on('data', data => { + if (this._input !== null && data.length !== 0) { + // Prepend any previous pending writes + if (this._pendingBuffer) { + data = Buffer.concat([this._pendingBuffer, data]); + this._pendingBuffer = null; + } + // Hold if the buffer ends in an incomplete unicode sequence + if (data[data.length - 1] & 0x80) { + this._pendingBuffer = data; + } + // Otherwise, tokenize as far as possible + else { + this._input += data; + this._tokenizeToEnd(callback, false); + } + } + }); + // Parses until the end + input.on('end', () => { + if (this._input !== null) + this._tokenizeToEnd(callback, true); + }); + input.on('error', callback); + } + } +} + +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../node-libs-browser/node_modules/buffer/index.js */ "./node_modules/node-libs-browser/node_modules/buffer/index.js").Buffer)) + +/***/ }), + +/***/ "./node_modules/n3/src/N3Parser.js": +/*!*****************************************!*\ + !*** ./node_modules/n3/src/N3Parser.js ***! + \*****************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return N3Parser; }); +/* harmony import */ var _N3Lexer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./N3Lexer */ "./node_modules/n3/src/N3Lexer.js"); +/* harmony import */ var _N3DataFactory__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./N3DataFactory */ "./node_modules/n3/src/N3DataFactory.js"); +/* harmony import */ var _IRIs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./IRIs */ "./node_modules/n3/src/IRIs.js"); +// **N3Parser** parses N3 documents. + + + + +let blankNodePrefix = 0; + +// ## Constructor +class N3Parser { + constructor(options) { + this._contextStack = []; + this._graph = null; + + // Set the document IRI + options = options || {}; + this._setBase(options.baseIRI); + options.factory && initDataFactory(this, options.factory); + + // Set supported features depending on the format + const format = (typeof options.format === 'string') ? + options.format.match(/\w*$/)[0].toLowerCase() : '', + isTurtle = /turtle/.test(format), isTriG = /trig/.test(format), + isNTriples = /triple/.test(format), isNQuads = /quad/.test(format), + isN3 = this._n3Mode = /n3/.test(format), + isLineMode = isNTriples || isNQuads; + if (!(this._supportsNamedGraphs = !(isTurtle || isN3))) + this._readPredicateOrNamedGraph = this._readPredicate; + // Support triples in other graphs + this._supportsQuads = !(isTurtle || isTriG || isNTriples || isN3); + // Support nesting of triples + this._supportsRDFStar = format === '' || /star|\*$/.test(format); + // Disable relative IRIs in N-Triples or N-Quads mode + if (isLineMode) + this._resolveRelativeIRI = iri => { return null; }; + this._blankNodePrefix = typeof options.blankNodePrefix !== 'string' ? '' : + options.blankNodePrefix.replace(/^(?!_:)/, '_:'); + this._lexer = options.lexer || new _N3Lexer__WEBPACK_IMPORTED_MODULE_0__["default"]({ lineMode: isLineMode, n3: isN3 }); + // Disable explicit quantifiers by default + this._explicitQuantifiers = !!options.explicitQuantifiers; + } + + // ## Static class methods + + // ### `_resetBlankNodePrefix` restarts blank node prefix identification + static _resetBlankNodePrefix() { + blankNodePrefix = 0; + } + + // ## Private methods + + // ### `_setBase` sets the base IRI to resolve relative IRIs + _setBase(baseIRI) { + if (!baseIRI) { + this._base = ''; + this._basePath = ''; + } + else { + // Remove fragment if present + const fragmentPos = baseIRI.indexOf('#'); + if (fragmentPos >= 0) + baseIRI = baseIRI.substr(0, fragmentPos); + // Set base IRI and its components + this._base = baseIRI; + this._basePath = baseIRI.indexOf('/') < 0 ? baseIRI : + baseIRI.replace(/[^\/?]*(?:\?.*)?$/, ''); + baseIRI = baseIRI.match(/^(?:([a-z][a-z0-9+.-]*:))?(?:\/\/[^\/]*)?/i); + this._baseRoot = baseIRI[0]; + this._baseScheme = baseIRI[1]; + } + } + + // ### `_saveContext` stores the current parsing context + // when entering a new scope (list, blank node, formula) + _saveContext(type, graph, subject, predicate, object) { + const n3Mode = this._n3Mode; + this._contextStack.push({ + subject: subject, predicate: predicate, object: object, + graph: graph, type: type, + inverse: n3Mode ? this._inversePredicate : false, + blankPrefix: n3Mode ? this._prefixes._ : '', + quantified: n3Mode ? this._quantified : null, + }); + // The settings below only apply to N3 streams + if (n3Mode) { + // Every new scope resets the predicate direction + this._inversePredicate = false; + // In N3, blank nodes are scoped to a formula + // (using a dot as separator, as a blank node label cannot start with it) + this._prefixes._ = (this._graph ? `${this._graph.id.substr(2)}.` : '.'); + // Quantifiers are scoped to a formula + this._quantified = Object.create(this._quantified); + } + } + + // ### `_restoreContext` restores the parent context + // when leaving a scope (list, blank node, formula) + _restoreContext() { + const context = this._contextStack.pop(), n3Mode = this._n3Mode; + this._subject = context.subject; + this._predicate = context.predicate; + this._object = context.object; + this._graph = context.graph; + // The settings below only apply to N3 streams + if (n3Mode) { + this._inversePredicate = context.inverse; + this._prefixes._ = context.blankPrefix; + this._quantified = context.quantified; + } + } + + // ### `_readInTopContext` reads a token when in the top context + _readInTopContext(token) { + switch (token.type) { + // If an EOF token arrives in the top context, signal that we're done + case 'eof': + if (this._graph !== null) + return this._error('Unclosed graph', token); + delete this._prefixes._; + return this._callback(null, null, this._prefixes); + // It could be a prefix declaration + case 'PREFIX': + this._sparqlStyle = true; + case '@prefix': + return this._readPrefix; + // It could be a base declaration + case 'BASE': + this._sparqlStyle = true; + case '@base': + return this._readBaseIRI; + // It could be a graph + case '{': + if (this._supportsNamedGraphs) { + this._graph = ''; + this._subject = null; + return this._readSubject; + } + case 'GRAPH': + if (this._supportsNamedGraphs) + return this._readNamedGraphLabel; + // Otherwise, the next token must be a subject + default: + return this._readSubject(token); + } + } + + // ### `_readEntity` reads an IRI, prefixed name, blank node, or variable + _readEntity(token, quantifier) { + let value; + switch (token.type) { + // Read a relative or absolute IRI + case 'IRI': + case 'typeIRI': + const iri = this._resolveIRI(token.value); + if (iri === null) + return this._error('Invalid IRI', token); + value = this._namedNode(iri); + break; + // Read a prefixed name + case 'type': + case 'prefixed': + const prefix = this._prefixes[token.prefix]; + if (prefix === undefined) + return this._error(`Undefined prefix "${token.prefix}:"`, token); + value = this._namedNode(prefix + token.value); + break; + // Read a blank node + case 'blank': + value = this._blankNode(this._prefixes[token.prefix] + token.value); + break; + // Read a variable + case 'var': + value = this._variable(token.value.substr(1)); + break; + // Everything else is not an entity + default: + return this._error(`Expected entity but got ${token.type}`, token); + } + // In N3 mode, replace the entity if it is quantified + if (!quantifier && this._n3Mode && (value.id in this._quantified)) + value = this._quantified[value.id]; + return value; + } + + // ### `_readSubject` reads a quad's subject + _readSubject(token) { + this._predicate = null; + switch (token.type) { + case '[': + // Start a new quad with a new blank node as subject + this._saveContext('blank', this._graph, + this._subject = this._blankNode(), null, null); + return this._readBlankNodeHead; + case '(': + // Start a new list + this._saveContext('list', this._graph, this.RDF_NIL, null, null); + this._subject = null; + return this._readListItem; + case '{': + // Start a new formula + if (!this._n3Mode) + return this._error('Unexpected graph', token); + this._saveContext('formula', this._graph, + this._graph = this._blankNode(), null, null); + return this._readSubject; + case '}': + // No subject; the graph in which we are reading is closed instead + return this._readPunctuation(token); + case '@forSome': + if (!this._n3Mode) + return this._error('Unexpected "@forSome"', token); + this._subject = null; + this._predicate = this.N3_FORSOME; + this._quantifier = this._blankNode; + return this._readQuantifierList; + case '@forAll': + if (!this._n3Mode) + return this._error('Unexpected "@forAll"', token); + this._subject = null; + this._predicate = this.N3_FORALL; + this._quantifier = this._variable; + return this._readQuantifierList; + case 'literal': + if (!this._n3Mode) + return this._error('Unexpected literal', token); + + if (token.prefix.length === 0) { + this._literalValue = token.value; + return this._completeSubjectLiteral; + } + else + this._subject = this._literal(token.value, this._namedNode(token.prefix)); + + break; + case '<<': + if (!this._supportsRDFStar) + return this._error('Unexpected RDF* syntax', token); + this._saveContext('<<', this._graph, null, null, null); + this._graph = null; + return this._readSubject; + default: + // Read the subject entity + if ((this._subject = this._readEntity(token)) === undefined) + return; + // In N3 mode, the subject might be a path + if (this._n3Mode) + return this._getPathReader(this._readPredicateOrNamedGraph); + } + + // The next token must be a predicate, + // or, if the subject was actually a graph IRI, a named graph + return this._readPredicateOrNamedGraph; + } + + // ### `_readPredicate` reads a quad's predicate + _readPredicate(token) { + const type = token.type; + switch (type) { + case 'inverse': + this._inversePredicate = true; + case 'abbreviation': + this._predicate = this.ABBREVIATIONS[token.value]; + break; + case '.': + case ']': + case '}': + // Expected predicate didn't come, must have been trailing semicolon + if (this._predicate === null) + return this._error(`Unexpected ${type}`, token); + this._subject = null; + return type === ']' ? this._readBlankNodeTail(token) : this._readPunctuation(token); + case ';': + // Additional semicolons can be safely ignored + return this._predicate !== null ? this._readPredicate : + this._error('Expected predicate but got ;', token); + case 'blank': + if (!this._n3Mode) + return this._error('Disallowed blank node as predicate', token); + default: + if ((this._predicate = this._readEntity(token)) === undefined) + return; + } + // The next token must be an object + return this._readObject; + } + + // ### `_readObject` reads a quad's object + _readObject(token) { + switch (token.type) { + case 'literal': + // Regular literal, can still get a datatype or language + if (token.prefix.length === 0) { + this._literalValue = token.value; + return this._readDataTypeOrLang; + } + // Pre-datatyped string literal (prefix stores the datatype) + else + this._object = this._literal(token.value, this._namedNode(token.prefix)); + break; + case '[': + // Start a new quad with a new blank node as subject + this._saveContext('blank', this._graph, this._subject, this._predicate, + this._subject = this._blankNode()); + return this._readBlankNodeHead; + case '(': + // Start a new list + this._saveContext('list', this._graph, this._subject, this._predicate, this.RDF_NIL); + this._subject = null; + return this._readListItem; + case '{': + // Start a new formula + if (!this._n3Mode) + return this._error('Unexpected graph', token); + this._saveContext('formula', this._graph, this._subject, this._predicate, + this._graph = this._blankNode()); + return this._readSubject; + case '<<': + if (!this._supportsRDFStar) + return this._error('Unexpected RDF* syntax', token); + this._saveContext('<<', this._graph, this._subject, this._predicate, null); + this._graph = null; + return this._readSubject; + default: + // Read the object entity + if ((this._object = this._readEntity(token)) === undefined) + return; + // In N3 mode, the object might be a path + if (this._n3Mode) + return this._getPathReader(this._getContextEndReader()); + } + return this._getContextEndReader(); + } + + // ### `_readPredicateOrNamedGraph` reads a quad's predicate, or a named graph + _readPredicateOrNamedGraph(token) { + return token.type === '{' ? this._readGraph(token) : this._readPredicate(token); + } + + // ### `_readGraph` reads a graph + _readGraph(token) { + if (token.type !== '{') + return this._error(`Expected graph but got ${token.type}`, token); + // The "subject" we read is actually the GRAPH's label + this._graph = this._subject, this._subject = null; + return this._readSubject; + } + + // ### `_readBlankNodeHead` reads the head of a blank node + _readBlankNodeHead(token) { + if (token.type === ']') { + this._subject = null; + return this._readBlankNodeTail(token); + } + else { + this._predicate = null; + return this._readPredicate(token); + } + } + + // ### `_readBlankNodeTail` reads the end of a blank node + _readBlankNodeTail(token) { + if (token.type !== ']') + return this._readBlankNodePunctuation(token); + + // Store blank node quad + if (this._subject !== null) + this._emit(this._subject, this._predicate, this._object, this._graph); + + // Restore the parent context containing this blank node + const empty = this._predicate === null; + this._restoreContext(); + // If the blank node was the subject, continue reading the predicate + if (this._object === null) + // If the blank node was empty, it could be a named graph label + return empty ? this._readPredicateOrNamedGraph : this._readPredicateAfterBlank; + // If the blank node was the object, restore previous context and read punctuation + else + return this._getContextEndReader(); + } + + // ### `_readPredicateAfterBlank` reads a predicate after an anonymous blank node + _readPredicateAfterBlank(token) { + switch (token.type) { + case '.': + case '}': + // No predicate is coming if the triple is terminated here + this._subject = null; + return this._readPunctuation(token); + default: + return this._readPredicate(token); + } + } + + // ### `_readListItem` reads items from a list + _readListItem(token) { + let item = null, // The item of the list + list = null, // The list itself + next = this._readListItem; // The next function to execute + const previousList = this._subject, // The previous list that contains this list + stack = this._contextStack, // The stack of parent contexts + parent = stack[stack.length - 1]; // The parent containing the current list + + switch (token.type) { + case '[': + // Stack the current list quad and start a new quad with a blank node as subject + this._saveContext('blank', this._graph, + list = this._blankNode(), this.RDF_FIRST, + this._subject = item = this._blankNode()); + next = this._readBlankNodeHead; + break; + case '(': + // Stack the current list quad and start a new list + this._saveContext('list', this._graph, + list = this._blankNode(), this.RDF_FIRST, this.RDF_NIL); + this._subject = null; + break; + case ')': + // Closing the list; restore the parent context + this._restoreContext(); + // If this list is contained within a parent list, return the membership quad here. + // This will be ` rdf:first .`. + if (stack.length !== 0 && stack[stack.length - 1].type === 'list') + this._emit(this._subject, this._predicate, this._object, this._graph); + // Was this list the parent's subject? + if (this._predicate === null) { + // The next token is the predicate + next = this._readPredicate; + // No list tail if this was an empty list + if (this._subject === this.RDF_NIL) + return next; + } + // The list was in the parent context's object + else { + next = this._getContextEndReader(); + // No list tail if this was an empty list + if (this._object === this.RDF_NIL) + return next; + } + // Close the list by making the head nil + list = this.RDF_NIL; + break; + case 'literal': + // Regular literal, can still get a datatype or language + if (token.prefix.length === 0) { + this._literalValue = token.value; + next = this._readListItemDataTypeOrLang; + } + // Pre-datatyped string literal (prefix stores the datatype) + else { + item = this._literal(token.value, this._namedNode(token.prefix)); + next = this._getContextEndReader(); + } + break; + case '{': + // Start a new formula + if (!this._n3Mode) + return this._error('Unexpected graph', token); + this._saveContext('formula', this._graph, this._subject, this._predicate, + this._graph = this._blankNode()); + return this._readSubject; + default: + if ((item = this._readEntity(token)) === undefined) + return; + } + + // Create a new blank node if no item head was assigned yet + if (list === null) + this._subject = list = this._blankNode(); + + // Is this the first element of the list? + if (previousList === null) { + // This list is either the subject or the object of its parent + if (parent.predicate === null) + parent.subject = list; + else + parent.object = list; + } + else { + // Continue the previous list with the current list + this._emit(previousList, this.RDF_REST, list, this._graph); + } + // If an item was read, add it to the list + if (item !== null) { + // In N3 mode, the item might be a path + if (this._n3Mode && (token.type === 'IRI' || token.type === 'prefixed')) { + // Create a new context to add the item's path + this._saveContext('item', this._graph, list, this.RDF_FIRST, item); + this._subject = item, this._predicate = null; + // _readPath will restore the context and output the item + return this._getPathReader(this._readListItem); + } + // Output the item + this._emit(list, this.RDF_FIRST, item, this._graph); + } + return next; + } + + // ### `_readDataTypeOrLang` reads an _optional_ datatype or language + _readDataTypeOrLang(token) { + return this._completeObjectLiteral(token, false); + } + + + // ### `_readListItemDataTypeOrLang` reads an _optional_ datatype or language in a list + _readListItemDataTypeOrLang(token) { + return this._completeObjectLiteral(token, true); + } + + // ### `_completeLiteral` completes a literal with an optional datatype or language + _completeLiteral(token) { + // Create a simple string literal by default + let literal = this._literal(this._literalValue); + + switch (token.type) { + // Create a datatyped literal + case 'type': + case 'typeIRI': + const datatype = this._readEntity(token); + if (datatype === undefined) return; // No datatype means an error occurred + literal = this._literal(this._literalValue, datatype); + token = null; + break; + // Create a language-tagged string + case 'langcode': + literal = this._literal(this._literalValue, token.value); + token = null; + break; + } + + return { token, literal }; + } + + // Completes a literal in subject position + _completeSubjectLiteral(token) { + this._subject = this._completeLiteral(token).literal; + return this._readPredicateOrNamedGraph; + } + + // Completes a literal in object position + _completeObjectLiteral(token, listItem) { + const completed = this._completeLiteral(token); + if (!completed) + return; + this._object = completed.literal; + + // If this literal was part of a list, write the item + // (we could also check the context stack, but passing in a flag is faster) + if (listItem) + this._emit(this._subject, this.RDF_FIRST, this._object, this._graph); + // If the token was consumed, continue with the rest of the input + if (completed.token === null) + return this._getContextEndReader(); + // Otherwise, consume the token now + else { + this._readCallback = this._getContextEndReader(); + return this._readCallback(completed.token); + } + } + + // ### `_readFormulaTail` reads the end of a formula + _readFormulaTail(token) { + if (token.type !== '}') + return this._readPunctuation(token); + + // Store the last quad of the formula + if (this._subject !== null) + this._emit(this._subject, this._predicate, this._object, this._graph); + + // Restore the parent context containing this formula + this._restoreContext(); + // If the formula was the subject, continue reading the predicate. + // If the formula was the object, read punctuation. + return this._object === null ? this._readPredicate : this._getContextEndReader(); + } + + // ### `_readPunctuation` reads punctuation between quads or quad parts + _readPunctuation(token) { + let next, graph = this._graph; + const subject = this._subject, inversePredicate = this._inversePredicate; + switch (token.type) { + // A closing brace ends a graph + case '}': + if (this._graph === null) + return this._error('Unexpected graph closing', token); + if (this._n3Mode) + return this._readFormulaTail(token); + this._graph = null; + // A dot just ends the statement, without sharing anything with the next + case '.': + this._subject = null; + next = this._contextStack.length ? this._readSubject : this._readInTopContext; + if (inversePredicate) this._inversePredicate = false; + break; + // Semicolon means the subject is shared; predicate and object are different + case ';': + next = this._readPredicate; + break; + // Comma means both the subject and predicate are shared; the object is different + case ',': + next = this._readObject; + break; + default: + // An entity means this is a quad (only allowed if not already inside a graph) + if (this._supportsQuads && this._graph === null && (graph = this._readEntity(token)) !== undefined) { + next = this._readQuadPunctuation; + break; + } + return this._error(`Expected punctuation to follow "${this._object.id}"`, token); + } + // A quad has been completed now, so return it + if (subject !== null) { + const predicate = this._predicate, object = this._object; + if (!inversePredicate) + this._emit(subject, predicate, object, graph); + else + this._emit(object, predicate, subject, graph); + } + return next; + } + + // ### `_readBlankNodePunctuation` reads punctuation in a blank node + _readBlankNodePunctuation(token) { + let next; + switch (token.type) { + // Semicolon means the subject is shared; predicate and object are different + case ';': + next = this._readPredicate; + break; + // Comma means both the subject and predicate are shared; the object is different + case ',': + next = this._readObject; + break; + default: + return this._error(`Expected punctuation to follow "${this._object.id}"`, token); + } + // A quad has been completed now, so return it + this._emit(this._subject, this._predicate, this._object, this._graph); + return next; + } + + // ### `_readQuadPunctuation` reads punctuation after a quad + _readQuadPunctuation(token) { + if (token.type !== '.') + return this._error('Expected dot to follow quad', token); + return this._readInTopContext; + } + + // ### `_readPrefix` reads the prefix of a prefix declaration + _readPrefix(token) { + if (token.type !== 'prefix') + return this._error('Expected prefix to follow @prefix', token); + this._prefix = token.value; + return this._readPrefixIRI; + } + + // ### `_readPrefixIRI` reads the IRI of a prefix declaration + _readPrefixIRI(token) { + if (token.type !== 'IRI') + return this._error(`Expected IRI to follow prefix "${this._prefix}:"`, token); + const prefixNode = this._readEntity(token); + this._prefixes[this._prefix] = prefixNode.value; + this._prefixCallback(this._prefix, prefixNode); + return this._readDeclarationPunctuation; + } + + // ### `_readBaseIRI` reads the IRI of a base declaration + _readBaseIRI(token) { + const iri = token.type === 'IRI' && this._resolveIRI(token.value); + if (!iri) + return this._error('Expected valid IRI to follow base declaration', token); + this._setBase(iri); + return this._readDeclarationPunctuation; + } + + // ### `_readNamedGraphLabel` reads the label of a named graph + _readNamedGraphLabel(token) { + switch (token.type) { + case 'IRI': + case 'blank': + case 'prefixed': + return this._readSubject(token), this._readGraph; + case '[': + return this._readNamedGraphBlankLabel; + default: + return this._error('Invalid graph label', token); + } + } + + // ### `_readNamedGraphLabel` reads a blank node label of a named graph + _readNamedGraphBlankLabel(token) { + if (token.type !== ']') + return this._error('Invalid graph label', token); + this._subject = this._blankNode(); + return this._readGraph; + } + + // ### `_readDeclarationPunctuation` reads the punctuation of a declaration + _readDeclarationPunctuation(token) { + // SPARQL-style declarations don't have punctuation + if (this._sparqlStyle) { + this._sparqlStyle = false; + return this._readInTopContext(token); + } + + if (token.type !== '.') + return this._error('Expected declaration to end with a dot', token); + return this._readInTopContext; + } + + // Reads a list of quantified symbols from a @forSome or @forAll statement + _readQuantifierList(token) { + let entity; + switch (token.type) { + case 'IRI': + case 'prefixed': + if ((entity = this._readEntity(token, true)) !== undefined) + break; + default: + return this._error(`Unexpected ${token.type}`, token); + } + // Without explicit quantifiers, map entities to a quantified entity + if (!this._explicitQuantifiers) + this._quantified[entity.id] = this._quantifier(this._blankNode().value); + // With explicit quantifiers, output the reified quantifier + else { + // If this is the first item, start a new quantifier list + if (this._subject === null) + this._emit(this._graph || this.DEFAULTGRAPH, this._predicate, + this._subject = this._blankNode(), this.QUANTIFIERS_GRAPH); + // Otherwise, continue the previous list + else + this._emit(this._subject, this.RDF_REST, + this._subject = this._blankNode(), this.QUANTIFIERS_GRAPH); + // Output the list item + this._emit(this._subject, this.RDF_FIRST, entity, this.QUANTIFIERS_GRAPH); + } + return this._readQuantifierPunctuation; + } + + // Reads punctuation from a @forSome or @forAll statement + _readQuantifierPunctuation(token) { + // Read more quantifiers + if (token.type === ',') + return this._readQuantifierList; + // End of the quantifier list + else { + // With explicit quantifiers, close the quantifier list + if (this._explicitQuantifiers) { + this._emit(this._subject, this.RDF_REST, this.RDF_NIL, this.QUANTIFIERS_GRAPH); + this._subject = null; + } + // Read a dot + this._readCallback = this._getContextEndReader(); + return this._readCallback(token); + } + } + + // ### `_getPathReader` reads a potential path and then resumes with the given function + _getPathReader(afterPath) { + this._afterPath = afterPath; + return this._readPath; + } + + // ### `_readPath` reads a potential path + _readPath(token) { + switch (token.type) { + // Forward path + case '!': return this._readForwardPath; + // Backward path + case '^': return this._readBackwardPath; + // Not a path; resume reading where we left off + default: + const stack = this._contextStack, parent = stack.length && stack[stack.length - 1]; + // If we were reading a list item, we still need to output it + if (parent && parent.type === 'item') { + // The list item is the remaining subejct after reading the path + const item = this._subject; + // Switch back to the context of the list + this._restoreContext(); + // Output the list item + this._emit(this._subject, this.RDF_FIRST, item, this._graph); + } + return this._afterPath(token); + } + } + + // ### `_readForwardPath` reads a '!' path + _readForwardPath(token) { + let subject, predicate; + const object = this._blankNode(); + // The next token is the predicate + if ((predicate = this._readEntity(token)) === undefined) + return; + // If we were reading a subject, replace the subject by the path's object + if (this._predicate === null) + subject = this._subject, this._subject = object; + // If we were reading an object, replace the subject by the path's object + else + subject = this._object, this._object = object; + // Emit the path's current quad and read its next section + this._emit(subject, predicate, object, this._graph); + return this._readPath; + } + + // ### `_readBackwardPath` reads a '^' path + _readBackwardPath(token) { + const subject = this._blankNode(); + let predicate, object; + // The next token is the predicate + if ((predicate = this._readEntity(token)) === undefined) + return; + // If we were reading a subject, replace the subject by the path's subject + if (this._predicate === null) + object = this._subject, this._subject = subject; + // If we were reading an object, replace the subject by the path's subject + else + object = this._object, this._object = subject; + // Emit the path's current quad and read its next section + this._emit(subject, predicate, object, this._graph); + return this._readPath; + } + + // ### `_readRDFStarTailOrGraph` reads the graph of a nested RDF* quad or the end of a nested RDF* triple + _readRDFStarTailOrGraph(token) { + if (token.type !== '>>') { + // An entity means this is a quad (only allowed if not already inside a graph) + if (this._supportsQuads && this._graph === null && (this._graph = this._readEntity(token)) !== undefined) + return this._readRDFStarTail; + return this._error(`Expected >> to follow "${this._object.id}"`, token); + } + return this._readRDFStarTail(token); + } + + // ### `_readRDFStarTail` reads the end of a nested RDF* triple + _readRDFStarTail(token) { + if (token.type !== '>>') + return this._error(`Expected >> but got ${token.type}`, token); + // Read the quad and restore the previous context + const quad = this._quad(this._subject, this._predicate, this._object, + this._graph || this.DEFAULTGRAPH); + this._restoreContext(); + // If the triple was the subject, continue by reading the predicate. + if (this._subject === null) { + this._subject = quad; + return this._readPredicate; + } + // If the triple was the object, read context end. + else { + this._object = quad; + return this._getContextEndReader(); + } + } + + // ### `_getContextEndReader` gets the next reader function at the end of a context + _getContextEndReader() { + const contextStack = this._contextStack; + if (!contextStack.length) + return this._readPunctuation; + + switch (contextStack[contextStack.length - 1].type) { + case 'blank': + return this._readBlankNodeTail; + case 'list': + return this._readListItem; + case 'formula': + return this._readFormulaTail; + case '<<': + return this._readRDFStarTailOrGraph; + } + } + + // ### `_emit` sends a quad through the callback + _emit(subject, predicate, object, graph) { + this._callback(null, this._quad(subject, predicate, object, graph || this.DEFAULTGRAPH)); + } + + // ### `_error` emits an error message through the callback + _error(message, token) { + const err = new Error(`${message} on line ${token.line}.`); + err.context = { + token: token, + line: token.line, + previousToken: this._lexer.previousToken, + }; + this._callback(err); + this._callback = noop; + } + + // ### `_resolveIRI` resolves an IRI against the base path + _resolveIRI(iri) { + return /^[a-z][a-z0-9+.-]*:/i.test(iri) ? iri : this._resolveRelativeIRI(iri); + } + + // ### `_resolveRelativeIRI` resolves an IRI against the base path, + // assuming that a base path has been set and that the IRI is indeed relative + _resolveRelativeIRI(iri) { + // An empty relative IRI indicates the base IRI + if (!iri.length) + return this._base; + // Decide resolving strategy based in the first character + switch (iri[0]) { + // Resolve relative fragment IRIs against the base IRI + case '#': return this._base + iri; + // Resolve relative query string IRIs by replacing the query string + case '?': return this._base.replace(/(?:\?.*)?$/, iri); + // Resolve root-relative IRIs at the root of the base IRI + case '/': + // Resolve scheme-relative IRIs to the scheme + return (iri[1] === '/' ? this._baseScheme : this._baseRoot) + this._removeDotSegments(iri); + // Resolve all other IRIs at the base IRI's path + default: + // Relative IRIs cannot contain a colon in the first path segment + return (/^[^/:]*:/.test(iri)) ? null : this._removeDotSegments(this._basePath + iri); + } + } + + // ### `_removeDotSegments` resolves './' and '../' path segments in an IRI as per RFC3986 + _removeDotSegments(iri) { + // Don't modify the IRI if it does not contain any dot segments + if (!/(^|\/)\.\.?($|[/#?])/.test(iri)) + return iri; + + // Start with an imaginary slash before the IRI in order to resolve trailing './' and '../' + const length = iri.length; + let result = '', i = -1, pathStart = -1, segmentStart = 0, next = '/'; + + while (i < length) { + switch (next) { + // The path starts with the first slash after the authority + case ':': + if (pathStart < 0) { + // Skip two slashes before the authority + if (iri[++i] === '/' && iri[++i] === '/') + // Skip to slash after the authority + while ((pathStart = i + 1) < length && iri[pathStart] !== '/') + i = pathStart; + } + break; + // Don't modify a query string or fragment + case '?': + case '#': + i = length; + break; + // Handle '/.' or '/..' path segments + case '/': + if (iri[i + 1] === '.') { + next = iri[++i + 1]; + switch (next) { + // Remove a '/.' segment + case '/': + result += iri.substring(segmentStart, i - 1); + segmentStart = i + 1; + break; + // Remove a trailing '/.' segment + case undefined: + case '?': + case '#': + return result + iri.substring(segmentStart, i) + iri.substr(i + 1); + // Remove a '/..' segment + case '.': + next = iri[++i + 1]; + if (next === undefined || next === '/' || next === '?' || next === '#') { + result += iri.substring(segmentStart, i - 2); + // Try to remove the parent path from result + if ((segmentStart = result.lastIndexOf('/')) >= pathStart) + result = result.substr(0, segmentStart); + // Remove a trailing '/..' segment + if (next !== '/') + return `${result}/${iri.substr(i + 1)}`; + segmentStart = i + 1; + } + } + } + } + next = iri[++i]; + } + return result + iri.substring(segmentStart); + } + + // ## Public methods + + // ### `parse` parses the N3 input and emits each parsed quad through the callback + parse(input, quadCallback, prefixCallback) { + // The read callback is the next function to be executed when a token arrives. + // We start reading in the top context. + this._readCallback = this._readInTopContext; + this._sparqlStyle = false; + this._prefixes = Object.create(null); + this._prefixes._ = this._blankNodePrefix ? this._blankNodePrefix.substr(2) + : `b${blankNodePrefix++}_`; + this._prefixCallback = prefixCallback || noop; + this._inversePredicate = false; + this._quantified = Object.create(null); + + // Parse synchronously if no quad callback is given + if (!quadCallback) { + const quads = []; + let error; + this._callback = (e, t) => { e ? (error = e) : t && quads.push(t); }; + this._lexer.tokenize(input).every(token => { + return this._readCallback = this._readCallback(token); + }); + if (error) throw error; + return quads; + } + + // Parse asynchronously otherwise, executing the read callback when a token arrives + this._callback = quadCallback; + this._lexer.tokenize(input, (error, token) => { + if (error !== null) + this._callback(error), this._callback = noop; + else if (this._readCallback) + this._readCallback = this._readCallback(token); + }); + } +} + +// The empty function +function noop() {} + +// Initializes the parser with the given data factory +function initDataFactory(parser, factory) { + // Set factory methods + const namedNode = factory.namedNode; + parser._namedNode = namedNode; + parser._blankNode = factory.blankNode; + parser._literal = factory.literal; + parser._variable = factory.variable; + parser._quad = factory.quad; + parser.DEFAULTGRAPH = factory.defaultGraph(); + + // Set common named nodes + parser.RDF_FIRST = namedNode(_IRIs__WEBPACK_IMPORTED_MODULE_2__["default"].rdf.first); + parser.RDF_REST = namedNode(_IRIs__WEBPACK_IMPORTED_MODULE_2__["default"].rdf.rest); + parser.RDF_NIL = namedNode(_IRIs__WEBPACK_IMPORTED_MODULE_2__["default"].rdf.nil); + parser.N3_FORALL = namedNode(_IRIs__WEBPACK_IMPORTED_MODULE_2__["default"].r.forAll); + parser.N3_FORSOME = namedNode(_IRIs__WEBPACK_IMPORTED_MODULE_2__["default"].r.forSome); + parser.ABBREVIATIONS = { + 'a': namedNode(_IRIs__WEBPACK_IMPORTED_MODULE_2__["default"].rdf.type), + '=': namedNode(_IRIs__WEBPACK_IMPORTED_MODULE_2__["default"].owl.sameAs), + '>': namedNode(_IRIs__WEBPACK_IMPORTED_MODULE_2__["default"].log.implies), + }; + parser.QUANTIFIERS_GRAPH = namedNode('urn:n3:quantifiers'); +} +initDataFactory(N3Parser.prototype, _N3DataFactory__WEBPACK_IMPORTED_MODULE_1__["default"]); + + +/***/ }), + +/***/ "./node_modules/n3/src/N3Store.js": +/*!****************************************!*\ + !*** ./node_modules/n3/src/N3Store.js ***! + \****************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return N3Store; }); +/* harmony import */ var _N3DataFactory__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./N3DataFactory */ "./node_modules/n3/src/N3DataFactory.js"); +/* harmony import */ var readable_stream__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! readable-stream */ "./node_modules/readable-stream/readable-browser.js"); +/* harmony import */ var readable_stream__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(readable_stream__WEBPACK_IMPORTED_MODULE_1__); +/* harmony import */ var _IRIs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./IRIs */ "./node_modules/n3/src/IRIs.js"); +// **N3Store** objects store N3 quads by graph in memory. + + + + +// ## Constructor +class N3Store { + constructor(quads, options) { + // The number of quads is initially zero + this._size = 0; + // `_graphs` contains subject, predicate, and object indexes per graph + this._graphs = Object.create(null); + // `_ids` maps entities such as `http://xmlns.com/foaf/0.1/name` to numbers, + // saving memory by using only numbers as keys in `_graphs` + this._id = 0; + this._ids = Object.create(null); + this._ids['><'] = 0; // dummy entry, so the first actual key is non-zero + this._entities = Object.create(null); // inverse of `_ids` + // `_blankNodeIndex` is the index of the last automatically named blank node + this._blankNodeIndex = 0; + + // Shift parameters if `quads` is not given + if (!options && quads && !quads[0]) + options = quads, quads = null; + options = options || {}; + this._factory = options.factory || _N3DataFactory__WEBPACK_IMPORTED_MODULE_0__["default"]; + + // Add quads if passed + if (quads) + this.addQuads(quads); + } + + // ## Public properties + + // ### `size` returns the number of quads in the store + get size() { + // Return the quad count if if was cached + let size = this._size; + if (size !== null) + return size; + + // Calculate the number of quads by counting to the deepest level + size = 0; + const graphs = this._graphs; + let subjects, subject; + for (const graphKey in graphs) + for (const subjectKey in (subjects = graphs[graphKey].subjects)) + for (const predicateKey in (subject = subjects[subjectKey])) + size += Object.keys(subject[predicateKey]).length; + return this._size = size; + } + + // ## Private methods + + // ### `_addToIndex` adds a quad to a three-layered index. + // Returns if the index has changed, if the entry did not already exist. + _addToIndex(index0, key0, key1, key2) { + // Create layers as necessary + const index1 = index0[key0] || (index0[key0] = {}); + const index2 = index1[key1] || (index1[key1] = {}); + // Setting the key to _any_ value signals the presence of the quad + const existed = key2 in index2; + if (!existed) + index2[key2] = null; + return !existed; + } + + // ### `_removeFromIndex` removes a quad from a three-layered index + _removeFromIndex(index0, key0, key1, key2) { + // Remove the quad from the index + const index1 = index0[key0], index2 = index1[key1]; + delete index2[key2]; + + // Remove intermediary index layers if they are empty + for (const key in index2) return; + delete index1[key1]; + for (const key in index1) return; + delete index0[key0]; + } + + // ### `_findInIndex` finds a set of quads in a three-layered index. + // The index base is `index0` and the keys at each level are `key0`, `key1`, and `key2`. + // Any of these keys can be undefined, which is interpreted as a wildcard. + // `name0`, `name1`, and `name2` are the names of the keys at each level, + // used when reconstructing the resulting quad + // (for instance: _subject_, _predicate_, and _object_). + // Finally, `graph` will be the graph of the created quads. + // If `callback` is given, each result is passed through it + // and iteration halts when it returns truthy for any quad. + // If instead `array` is given, each result is added to the array. + _findInIndex(index0, key0, key1, key2, name0, name1, name2, graph, callback, array) { + let tmp, index1, index2; + // Depending on the number of variables, keys or reverse index are faster + const varCount = !key0 + !key1 + !key2, + entityKeys = varCount > 1 ? Object.keys(this._ids) : this._entities; + + // If a key is specified, use only that part of index 0. + if (key0) (tmp = index0, index0 = {})[key0] = tmp[key0]; + for (const value0 in index0) { + const entity0 = entityKeys[value0]; + + if (index1 = index0[value0]) { + // If a key is specified, use only that part of index 1. + if (key1) (tmp = index1, index1 = {})[key1] = tmp[key1]; + for (const value1 in index1) { + const entity1 = entityKeys[value1]; + + if (index2 = index1[value1]) { + // If a key is specified, use only that part of index 2, if it exists. + const values = key2 ? (key2 in index2 ? [key2] : []) : Object.keys(index2); + // Create quads for all items found in index 2. + for (let l = 0; l < values.length; l++) { + const parts = { subject: null, predicate: null, object: null }; + parts[name0] = Object(_N3DataFactory__WEBPACK_IMPORTED_MODULE_0__["termFromId"])(entity0, this._factory); + parts[name1] = Object(_N3DataFactory__WEBPACK_IMPORTED_MODULE_0__["termFromId"])(entity1, this._factory); + parts[name2] = Object(_N3DataFactory__WEBPACK_IMPORTED_MODULE_0__["termFromId"])(entityKeys[values[l]], this._factory); + const quad = this._factory.quad( + parts.subject, parts.predicate, parts.object, Object(_N3DataFactory__WEBPACK_IMPORTED_MODULE_0__["termFromId"])(graph, this._factory)); + if (array) + array.push(quad); + else if (callback(quad)) + return true; + } + } + } + } + } + return array; + } + + // ### `_loop` executes the callback on all keys of index 0 + _loop(index0, callback) { + for (const key0 in index0) + callback(key0); + } + + // ### `_loopByKey0` executes the callback on all keys of a certain entry in index 0 + _loopByKey0(index0, key0, callback) { + let index1, key1; + if (index1 = index0[key0]) { + for (key1 in index1) + callback(key1); + } + } + + // ### `_loopByKey1` executes the callback on given keys of all entries in index 0 + _loopByKey1(index0, key1, callback) { + let key0, index1; + for (key0 in index0) { + index1 = index0[key0]; + if (index1[key1]) + callback(key0); + } + } + + // ### `_loopBy2Keys` executes the callback on given keys of certain entries in index 2 + _loopBy2Keys(index0, key0, key1, callback) { + let index1, index2, key2; + if ((index1 = index0[key0]) && (index2 = index1[key1])) { + for (key2 in index2) + callback(key2); + } + } + + // ### `_countInIndex` counts matching quads in a three-layered index. + // The index base is `index0` and the keys at each level are `key0`, `key1`, and `key2`. + // Any of these keys can be undefined, which is interpreted as a wildcard. + _countInIndex(index0, key0, key1, key2) { + let count = 0, tmp, index1, index2; + + // If a key is specified, count only that part of index 0 + if (key0) (tmp = index0, index0 = {})[key0] = tmp[key0]; + for (const value0 in index0) { + if (index1 = index0[value0]) { + // If a key is specified, count only that part of index 1 + if (key1) (tmp = index1, index1 = {})[key1] = tmp[key1]; + for (const value1 in index1) { + if (index2 = index1[value1]) { + // If a key is specified, count the quad if it exists + if (key2) (key2 in index2) && count++; + // Otherwise, count all quads + else count += Object.keys(index2).length; + } + } + } + } + return count; + } + + // ### `_getGraphs` returns an array with the given graph, + // or all graphs if the argument is null or undefined. + _getGraphs(graph) { + if (!isString(graph)) + return this._graphs; + const graphs = {}; + graphs[graph] = this._graphs[graph]; + return graphs; + } + + // ### `_uniqueEntities` returns a function that accepts an entity ID + // and passes the corresponding entity to callback if it hasn't occurred before. + _uniqueEntities(callback) { + const uniqueIds = Object.create(null); + return id => { + if (!(id in uniqueIds)) { + uniqueIds[id] = true; + callback(Object(_N3DataFactory__WEBPACK_IMPORTED_MODULE_0__["termFromId"])(this._entities[id], this._factory)); + } + }; + } + + // ## Public methods + + // ### `addQuad` adds a new quad to the store. + // Returns if the quad index has changed, if the quad did not already exist. + addQuad(subject, predicate, object, graph) { + // Shift arguments if a quad object is given instead of components + if (!predicate) + graph = subject.graph, object = subject.object, + predicate = subject.predicate, subject = subject.subject; + + // Convert terms to internal string representation + subject = Object(_N3DataFactory__WEBPACK_IMPORTED_MODULE_0__["termToId"])(subject); + predicate = Object(_N3DataFactory__WEBPACK_IMPORTED_MODULE_0__["termToId"])(predicate); + object = Object(_N3DataFactory__WEBPACK_IMPORTED_MODULE_0__["termToId"])(object); + graph = Object(_N3DataFactory__WEBPACK_IMPORTED_MODULE_0__["termToId"])(graph); + + // Find the graph that will contain the triple + let graphItem = this._graphs[graph]; + // Create the graph if it doesn't exist yet + if (!graphItem) { + graphItem = this._graphs[graph] = { subjects: {}, predicates: {}, objects: {} }; + // Freezing a graph helps subsequent `add` performance, + // and properties will never be modified anyway + Object.freeze(graphItem); + } + + // Since entities can often be long IRIs, we avoid storing them in every index. + // Instead, we have a separate index that maps entities to numbers, + // which are then used as keys in the other indexes. + const ids = this._ids; + const entities = this._entities; + subject = ids[subject] || (ids[entities[++this._id] = subject] = this._id); + predicate = ids[predicate] || (ids[entities[++this._id] = predicate] = this._id); + object = ids[object] || (ids[entities[++this._id] = object] = this._id); + + const changed = this._addToIndex(graphItem.subjects, subject, predicate, object); + this._addToIndex(graphItem.predicates, predicate, object, subject); + this._addToIndex(graphItem.objects, object, subject, predicate); + + // The cached quad count is now invalid + this._size = null; + return changed; + } + + // ### `addQuads` adds multiple quads to the store + addQuads(quads) { + for (let i = 0; i < quads.length; i++) + this.addQuad(quads[i]); + } + + // ### `import` adds a stream of quads to the store + import(stream) { + stream.on('data', quad => { this.addQuad(quad); }); + return stream; + } + + // ### `removeQuad` removes a quad from the store if it exists + removeQuad(subject, predicate, object, graph) { + // Shift arguments if a quad object is given instead of components + if (!predicate) + graph = subject.graph, object = subject.object, + predicate = subject.predicate, subject = subject.subject; + + // Convert terms to internal string representation + subject = Object(_N3DataFactory__WEBPACK_IMPORTED_MODULE_0__["termToId"])(subject); + predicate = Object(_N3DataFactory__WEBPACK_IMPORTED_MODULE_0__["termToId"])(predicate); + object = Object(_N3DataFactory__WEBPACK_IMPORTED_MODULE_0__["termToId"])(object); + graph = Object(_N3DataFactory__WEBPACK_IMPORTED_MODULE_0__["termToId"])(graph); + + // Find internal identifiers for all components + // and verify the quad exists. + const ids = this._ids, graphs = this._graphs; + let graphItem, subjects, predicates; + if (!(subject = ids[subject]) || !(predicate = ids[predicate]) || + !(object = ids[object]) || !(graphItem = graphs[graph]) || + !(subjects = graphItem.subjects[subject]) || + !(predicates = subjects[predicate]) || + !(object in predicates)) + return false; + + // Remove it from all indexes + this._removeFromIndex(graphItem.subjects, subject, predicate, object); + this._removeFromIndex(graphItem.predicates, predicate, object, subject); + this._removeFromIndex(graphItem.objects, object, subject, predicate); + if (this._size !== null) this._size--; + + // Remove the graph if it is empty + for (subject in graphItem.subjects) return true; + delete graphs[graph]; + return true; + } + + // ### `removeQuads` removes multiple quads from the store + removeQuads(quads) { + for (let i = 0; i < quads.length; i++) + this.removeQuad(quads[i]); + } + + // ### `remove` removes a stream of quads from the store + remove(stream) { + stream.on('data', quad => { this.removeQuad(quad); }); + return stream; + } + + // ### `removeMatches` removes all matching quads from the store + // Setting any field to `undefined` or `null` indicates a wildcard. + removeMatches(subject, predicate, object, graph) { + return this.remove(this.match(subject, predicate, object, graph)); + } + + // ### `deleteGraph` removes all triples with the given graph from the store + deleteGraph(graph) { + return this.removeMatches(null, null, null, graph); + } + + // ### `getQuads` returns an array of quads matching a pattern. + // Setting any field to `undefined` or `null` indicates a wildcard. + getQuads(subject, predicate, object, graph) { + // Convert terms to internal string representation + subject = subject && Object(_N3DataFactory__WEBPACK_IMPORTED_MODULE_0__["termToId"])(subject); + predicate = predicate && Object(_N3DataFactory__WEBPACK_IMPORTED_MODULE_0__["termToId"])(predicate); + object = object && Object(_N3DataFactory__WEBPACK_IMPORTED_MODULE_0__["termToId"])(object); + graph = graph && Object(_N3DataFactory__WEBPACK_IMPORTED_MODULE_0__["termToId"])(graph); + + const quads = [], graphs = this._getGraphs(graph), ids = this._ids; + let content, subjectId, predicateId, objectId; + + // Translate IRIs to internal index keys. + if (isString(subject) && !(subjectId = ids[subject]) || + isString(predicate) && !(predicateId = ids[predicate]) || + isString(object) && !(objectId = ids[object])) + return quads; + + for (const graphId in graphs) { + // Only if the specified graph contains triples, there can be results + if (content = graphs[graphId]) { + // Choose the optimal index, based on what fields are present + if (subjectId) { + if (objectId) + // If subject and object are given, the object index will be the fastest + this._findInIndex(content.objects, objectId, subjectId, predicateId, + 'object', 'subject', 'predicate', graphId, null, quads); + else + // If only subject and possibly predicate are given, the subject index will be the fastest + this._findInIndex(content.subjects, subjectId, predicateId, null, + 'subject', 'predicate', 'object', graphId, null, quads); + } + else if (predicateId) + // If only predicate and possibly object are given, the predicate index will be the fastest + this._findInIndex(content.predicates, predicateId, objectId, null, + 'predicate', 'object', 'subject', graphId, null, quads); + else if (objectId) + // If only object is given, the object index will be the fastest + this._findInIndex(content.objects, objectId, null, null, + 'object', 'subject', 'predicate', graphId, null, quads); + else + // If nothing is given, iterate subjects and predicates first + this._findInIndex(content.subjects, null, null, null, + 'subject', 'predicate', 'object', graphId, null, quads); + } + } + return quads; + } + + // ### `match` returns a stream of quads matching a pattern. + // Setting any field to `undefined` or `null` indicates a wildcard. + match(subject, predicate, object, graph) { + const stream = new readable_stream__WEBPACK_IMPORTED_MODULE_1__["Readable"]({ objectMode: true }); + + // Initialize stream once it is being read + stream._read = () => { + for (const quad of this.getQuads(subject, predicate, object, graph)) + stream.push(quad); + stream.push(null); + }; + + return stream; + } + + // ### `countQuads` returns the number of quads matching a pattern. + // Setting any field to `undefined` or `null` indicates a wildcard. + countQuads(subject, predicate, object, graph) { + // Convert terms to internal string representation + subject = subject && Object(_N3DataFactory__WEBPACK_IMPORTED_MODULE_0__["termToId"])(subject); + predicate = predicate && Object(_N3DataFactory__WEBPACK_IMPORTED_MODULE_0__["termToId"])(predicate); + object = object && Object(_N3DataFactory__WEBPACK_IMPORTED_MODULE_0__["termToId"])(object); + graph = graph && Object(_N3DataFactory__WEBPACK_IMPORTED_MODULE_0__["termToId"])(graph); + + const graphs = this._getGraphs(graph), ids = this._ids; + let count = 0, content, subjectId, predicateId, objectId; + + // Translate IRIs to internal index keys. + if (isString(subject) && !(subjectId = ids[subject]) || + isString(predicate) && !(predicateId = ids[predicate]) || + isString(object) && !(objectId = ids[object])) + return 0; + + for (const graphId in graphs) { + // Only if the specified graph contains triples, there can be results + if (content = graphs[graphId]) { + // Choose the optimal index, based on what fields are present + if (subject) { + if (object) + // If subject and object are given, the object index will be the fastest + count += this._countInIndex(content.objects, objectId, subjectId, predicateId); + else + // If only subject and possibly predicate are given, the subject index will be the fastest + count += this._countInIndex(content.subjects, subjectId, predicateId, objectId); + } + else if (predicate) { + // If only predicate and possibly object are given, the predicate index will be the fastest + count += this._countInIndex(content.predicates, predicateId, objectId, subjectId); + } + else { + // If only object is possibly given, the object index will be the fastest + count += this._countInIndex(content.objects, objectId, subjectId, predicateId); + } + } + } + return count; + } + + // ### `forEach` executes the callback on all quads. + // Setting any field to `undefined` or `null` indicates a wildcard. + forEach(callback, subject, predicate, object, graph) { + this.some(quad => { + callback(quad); + return false; + }, subject, predicate, object, graph); + } + + // ### `every` executes the callback on all quads, + // and returns `true` if it returns truthy for all them. + // Setting any field to `undefined` or `null` indicates a wildcard. + every(callback, subject, predicate, object, graph) { + let some = false; + const every = !this.some(quad => { + some = true; + return !callback(quad); + }, subject, predicate, object, graph); + return some && every; + } + + // ### `some` executes the callback on all quads, + // and returns `true` if it returns truthy for any of them. + // Setting any field to `undefined` or `null` indicates a wildcard. + some(callback, subject, predicate, object, graph) { + // Convert terms to internal string representation + subject = subject && Object(_N3DataFactory__WEBPACK_IMPORTED_MODULE_0__["termToId"])(subject); + predicate = predicate && Object(_N3DataFactory__WEBPACK_IMPORTED_MODULE_0__["termToId"])(predicate); + object = object && Object(_N3DataFactory__WEBPACK_IMPORTED_MODULE_0__["termToId"])(object); + graph = graph && Object(_N3DataFactory__WEBPACK_IMPORTED_MODULE_0__["termToId"])(graph); + + const graphs = this._getGraphs(graph), ids = this._ids; + let content, subjectId, predicateId, objectId; + + // Translate IRIs to internal index keys. + if (isString(subject) && !(subjectId = ids[subject]) || + isString(predicate) && !(predicateId = ids[predicate]) || + isString(object) && !(objectId = ids[object])) + return false; + + for (const graphId in graphs) { + // Only if the specified graph contains triples, there can be results + if (content = graphs[graphId]) { + // Choose the optimal index, based on what fields are present + if (subjectId) { + if (objectId) { + // If subject and object are given, the object index will be the fastest + if (this._findInIndex(content.objects, objectId, subjectId, predicateId, + 'object', 'subject', 'predicate', graphId, callback, null)) + return true; + } + else + // If only subject and possibly predicate are given, the subject index will be the fastest + if (this._findInIndex(content.subjects, subjectId, predicateId, null, + 'subject', 'predicate', 'object', graphId, callback, null)) + return true; + } + else if (predicateId) { + // If only predicate and possibly object are given, the predicate index will be the fastest + if (this._findInIndex(content.predicates, predicateId, objectId, null, + 'predicate', 'object', 'subject', graphId, callback, null)) { + return true; + } + } + else if (objectId) { + // If only object is given, the object index will be the fastest + if (this._findInIndex(content.objects, objectId, null, null, + 'object', 'subject', 'predicate', graphId, callback, null)) { + return true; + } + } + else + // If nothing is given, iterate subjects and predicates first + if (this._findInIndex(content.subjects, null, null, null, + 'subject', 'predicate', 'object', graphId, callback, null)) { + return true; + } + } + } + return false; + } + + // ### `getSubjects` returns all subjects that match the pattern. + // Setting any field to `undefined` or `null` indicates a wildcard. + getSubjects(predicate, object, graph) { + const results = []; + this.forSubjects(s => { results.push(s); }, predicate, object, graph); + return results; + } + + // ### `forSubjects` executes the callback on all subjects that match the pattern. + // Setting any field to `undefined` or `null` indicates a wildcard. + forSubjects(callback, predicate, object, graph) { + // Convert terms to internal string representation + predicate = predicate && Object(_N3DataFactory__WEBPACK_IMPORTED_MODULE_0__["termToId"])(predicate); + object = object && Object(_N3DataFactory__WEBPACK_IMPORTED_MODULE_0__["termToId"])(object); + graph = graph && Object(_N3DataFactory__WEBPACK_IMPORTED_MODULE_0__["termToId"])(graph); + + const ids = this._ids, graphs = this._getGraphs(graph); + let content, predicateId, objectId; + callback = this._uniqueEntities(callback); + + // Translate IRIs to internal index keys. + if (isString(predicate) && !(predicateId = ids[predicate]) || + isString(object) && !(objectId = ids[object])) + return; + + for (graph in graphs) { + // Only if the specified graph contains triples, there can be results + if (content = graphs[graph]) { + // Choose optimal index based on which fields are wildcards + if (predicateId) { + if (objectId) + // If predicate and object are given, the POS index is best. + this._loopBy2Keys(content.predicates, predicateId, objectId, callback); + else + // If only predicate is given, the SPO index is best. + this._loopByKey1(content.subjects, predicateId, callback); + } + else if (objectId) + // If only object is given, the OSP index is best. + this._loopByKey0(content.objects, objectId, callback); + else + // If no params given, iterate all the subjects + this._loop(content.subjects, callback); + } + } + } + + // ### `getPredicates` returns all predicates that match the pattern. + // Setting any field to `undefined` or `null` indicates a wildcard. + getPredicates(subject, object, graph) { + const results = []; + this.forPredicates(p => { results.push(p); }, subject, object, graph); + return results; + } + + // ### `forPredicates` executes the callback on all predicates that match the pattern. + // Setting any field to `undefined` or `null` indicates a wildcard. + forPredicates(callback, subject, object, graph) { + // Convert terms to internal string representation + subject = subject && Object(_N3DataFactory__WEBPACK_IMPORTED_MODULE_0__["termToId"])(subject); + object = object && Object(_N3DataFactory__WEBPACK_IMPORTED_MODULE_0__["termToId"])(object); + graph = graph && Object(_N3DataFactory__WEBPACK_IMPORTED_MODULE_0__["termToId"])(graph); + + const ids = this._ids, graphs = this._getGraphs(graph); + let content, subjectId, objectId; + callback = this._uniqueEntities(callback); + + // Translate IRIs to internal index keys. + if (isString(subject) && !(subjectId = ids[subject]) || + isString(object) && !(objectId = ids[object])) + return; + + for (graph in graphs) { + // Only if the specified graph contains triples, there can be results + if (content = graphs[graph]) { + // Choose optimal index based on which fields are wildcards + if (subjectId) { + if (objectId) + // If subject and object are given, the OSP index is best. + this._loopBy2Keys(content.objects, objectId, subjectId, callback); + else + // If only subject is given, the SPO index is best. + this._loopByKey0(content.subjects, subjectId, callback); + } + else if (objectId) + // If only object is given, the POS index is best. + this._loopByKey1(content.predicates, objectId, callback); + else + // If no params given, iterate all the predicates. + this._loop(content.predicates, callback); + } + } + } + + // ### `getObjects` returns all objects that match the pattern. + // Setting any field to `undefined` or `null` indicates a wildcard. + getObjects(subject, predicate, graph) { + const results = []; + this.forObjects(o => { results.push(o); }, subject, predicate, graph); + return results; + } + + // ### `forObjects` executes the callback on all objects that match the pattern. + // Setting any field to `undefined` or `null` indicates a wildcard. + forObjects(callback, subject, predicate, graph) { + // Convert terms to internal string representation + subject = subject && Object(_N3DataFactory__WEBPACK_IMPORTED_MODULE_0__["termToId"])(subject); + predicate = predicate && Object(_N3DataFactory__WEBPACK_IMPORTED_MODULE_0__["termToId"])(predicate); + graph = graph && Object(_N3DataFactory__WEBPACK_IMPORTED_MODULE_0__["termToId"])(graph); + + const ids = this._ids, graphs = this._getGraphs(graph); + let content, subjectId, predicateId; + callback = this._uniqueEntities(callback); + + // Translate IRIs to internal index keys. + if (isString(subject) && !(subjectId = ids[subject]) || + isString(predicate) && !(predicateId = ids[predicate])) + return; + + for (graph in graphs) { + // Only if the specified graph contains triples, there can be results + if (content = graphs[graph]) { + // Choose optimal index based on which fields are wildcards + if (subjectId) { + if (predicateId) + // If subject and predicate are given, the SPO index is best. + this._loopBy2Keys(content.subjects, subjectId, predicateId, callback); + else + // If only subject is given, the OSP index is best. + this._loopByKey1(content.objects, subjectId, callback); + } + else if (predicateId) + // If only predicate is given, the POS index is best. + this._loopByKey0(content.predicates, predicateId, callback); + else + // If no params given, iterate all the objects. + this._loop(content.objects, callback); + } + } + } + + // ### `getGraphs` returns all graphs that match the pattern. + // Setting any field to `undefined` or `null` indicates a wildcard. + getGraphs(subject, predicate, object) { + const results = []; + this.forGraphs(g => { results.push(g); }, subject, predicate, object); + return results; + } + + // ### `forGraphs` executes the callback on all graphs that match the pattern. + // Setting any field to `undefined` or `null` indicates a wildcard. + forGraphs(callback, subject, predicate, object) { + for (const graph in this._graphs) { + this.some(quad => { + callback(quad.graph); + return true; // Halt iteration of some() + }, subject, predicate, object, graph); + } + } + + // ### `createBlankNode` creates a new blank node, returning its name + createBlankNode(suggestedName) { + let name, index; + // Generate a name based on the suggested name + if (suggestedName) { + name = suggestedName = `_:${suggestedName}`, index = 1; + while (this._ids[name]) + name = suggestedName + index++; + } + // Generate a generic blank node name + else { + do { name = `_:b${this._blankNodeIndex++}`; } + while (this._ids[name]); + } + // Add the blank node to the entities, avoiding the generation of duplicates + this._ids[name] = ++this._id; + this._entities[this._id] = name; + return this._factory.blankNode(name.substr(2)); + } + + // ### `extractLists` finds and removes all list triples + // and returns the items per list. + extractLists({ remove = false, ignoreErrors = false } = {}) { + const lists = {}; // has scalar keys so could be a simple Object + const onError = ignoreErrors ? (() => true) : + ((node, message) => { throw new Error(`${node.value} ${message}`); }); + + // Traverse each list from its tail + const tails = this.getQuads(null, _IRIs__WEBPACK_IMPORTED_MODULE_2__["default"].rdf.rest, _IRIs__WEBPACK_IMPORTED_MODULE_2__["default"].rdf.nil, null); + const toRemove = remove ? [...tails] : []; + tails.forEach(tailQuad => { + const items = []; // the members found as objects of rdf:first quads + let malformed = false; // signals whether the current list is malformed + let head; // the head of the list (_:b1 in above example) + let headPos; // set to subject or object when head is set + const graph = tailQuad.graph; // make sure list is in exactly one graph + + // Traverse the list from tail to end + let current = tailQuad.subject; + while (current && !malformed) { + const objectQuads = this.getQuads(null, null, current, null); + const subjectQuads = this.getQuads(current, null, null, null); + let quad, first = null, rest = null, parent = null; + + // Find the first and rest of this list node + for (let i = 0; i < subjectQuads.length && !malformed; i++) { + quad = subjectQuads[i]; + if (!quad.graph.equals(graph)) + malformed = onError(current, 'not confined to single graph'); + else if (head) + malformed = onError(current, 'has non-list arcs out'); + + // one rdf:first + else if (quad.predicate.value === _IRIs__WEBPACK_IMPORTED_MODULE_2__["default"].rdf.first) { + if (first) + malformed = onError(current, 'has multiple rdf:first arcs'); + else + toRemove.push(first = quad); + } + + // one rdf:rest + else if (quad.predicate.value === _IRIs__WEBPACK_IMPORTED_MODULE_2__["default"].rdf.rest) { + if (rest) + malformed = onError(current, 'has multiple rdf:rest arcs'); + else + toRemove.push(rest = quad); + } + + // alien triple + else if (objectQuads.length) + malformed = onError(current, 'can\'t be subject and object'); + else { + head = quad; // e.g. { (1 2 3) :p :o } + headPos = 'subject'; + } + } + + // { :s :p (1 2) } arrives here with no head + // { (1 2) :p :o } arrives here with head set to the list. + for (let i = 0; i < objectQuads.length && !malformed; ++i) { + quad = objectQuads[i]; + if (head) + malformed = onError(current, 'can\'t have coreferences'); + // one rdf:rest + else if (quad.predicate.value === _IRIs__WEBPACK_IMPORTED_MODULE_2__["default"].rdf.rest) { + if (parent) + malformed = onError(current, 'has incoming rdf:rest arcs'); + else + parent = quad; + } + else { + head = quad; // e.g. { :s :p (1 2) } + headPos = 'object'; + } + } + + // Store the list item and continue with parent + if (!first) + malformed = onError(current, 'has no list head'); + else + items.unshift(first.object); + current = parent && parent.subject; + } + + // Don't remove any quads if the list is malformed + if (malformed) + remove = false; + // Store the list under the value of its head + else if (head) + lists[head[headPos].value] = items; + }); + + // Remove list quads if requested + if (remove) + this.removeQuads(toRemove); + return lists; + } +} + +// Determines whether the argument is a string +function isString(s) { + return typeof s === 'string' || s instanceof String; +} + + +/***/ }), + +/***/ "./node_modules/n3/src/N3StreamParser.js": +/*!***********************************************!*\ + !*** ./node_modules/n3/src/N3StreamParser.js ***! + \***********************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return N3StreamParser; }); +/* harmony import */ var _N3Parser__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./N3Parser */ "./node_modules/n3/src/N3Parser.js"); +/* harmony import */ var readable_stream__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! readable-stream */ "./node_modules/readable-stream/readable-browser.js"); +/* harmony import */ var readable_stream__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(readable_stream__WEBPACK_IMPORTED_MODULE_1__); +// **N3StreamParser** parses a text stream into a quad stream. + + + +// ## Constructor +class N3StreamParser extends readable_stream__WEBPACK_IMPORTED_MODULE_1__["Transform"] { + constructor(options) { + super({ decodeStrings: true }); + this._readableState.objectMode = true; + + // Set up parser with dummy stream to obtain `data` and `end` callbacks + const parser = new _N3Parser__WEBPACK_IMPORTED_MODULE_0__["default"](options); + let onData, onEnd; + parser.parse({ + on: (event, callback) => { + switch (event) { + case 'data': onData = callback; break; + case 'end': onEnd = callback; break; + } + }, + }, + // Handle quads by pushing them down the pipeline + (error, quad) => { error && this.emit('error', error) || quad && this.push(quad); }, + // Emit prefixes through the `prefix` event + (prefix, uri) => { this.emit('prefix', prefix, uri); } + ); + + // Implement Transform methods through parser callbacks + this._transform = (chunk, encoding, done) => { onData(chunk); done(); }; + this._flush = done => { onEnd(); done(); }; + } + + // ### Parses a stream of strings + import(stream) { + stream.on('data', chunk => { this.write(chunk); }); + stream.on('end', () => { this.end(); }); + stream.on('error', error => { this.emit('error', error); }); + return this; + } +} + + +/***/ }), + +/***/ "./node_modules/n3/src/N3StreamWriter.js": +/*!***********************************************!*\ + !*** ./node_modules/n3/src/N3StreamWriter.js ***! + \***********************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return N3StreamWriter; }); +/* harmony import */ var readable_stream__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! readable-stream */ "./node_modules/readable-stream/readable-browser.js"); +/* harmony import */ var readable_stream__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(readable_stream__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _N3Writer__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./N3Writer */ "./node_modules/n3/src/N3Writer.js"); +// **N3StreamWriter** serializes a quad stream into a text stream. + + + +// ## Constructor +class N3StreamWriter extends readable_stream__WEBPACK_IMPORTED_MODULE_0__["Transform"] { + constructor(options) { + super({ encoding: 'utf8' }); + this._writableState.objectMode = true; + + // Set up writer with a dummy stream object + const writer = this._writer = new _N3Writer__WEBPACK_IMPORTED_MODULE_1__["default"]({ + write: (quad, encoding, callback) => { this.push(quad); callback && callback(); }, + end: callback => { this.push(null); callback && callback(); }, + }, options); + + // Implement Transform methods on top of writer + this._transform = (quad, encoding, done) => { writer.addQuad(quad, done); }; + this._flush = done => { writer.end(done); }; + } + +// ### Serializes a stream of quads + import(stream) { + stream.on('data', quad => { this.write(quad); }); + stream.on('end', () => { this.end(); }); + stream.on('error', error => { this.emit('error', error); }); + stream.on('prefix', (prefix, iri) => { this._writer.addPrefix(prefix, iri); }); + return this; + } +} + + +/***/ }), + +/***/ "./node_modules/n3/src/N3Util.js": +/*!***************************************!*\ + !*** ./node_modules/n3/src/N3Util.js ***! + \***************************************/ +/*! exports provided: isNamedNode, isBlankNode, isLiteral, isVariable, isDefaultGraph, inDefaultGraph, prefix, prefixes */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isNamedNode", function() { return isNamedNode; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isBlankNode", function() { return isBlankNode; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isLiteral", function() { return isLiteral; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isVariable", function() { return isVariable; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isDefaultGraph", function() { return isDefaultGraph; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "inDefaultGraph", function() { return inDefaultGraph; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "prefix", function() { return prefix; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "prefixes", function() { return prefixes; }); +/* harmony import */ var _N3DataFactory__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./N3DataFactory */ "./node_modules/n3/src/N3DataFactory.js"); +// **N3Util** provides N3 utility functions. + + + +// Tests whether the given term represents an IRI +function isNamedNode(term) { + return !!term && term.termType === 'NamedNode'; +} + +// Tests whether the given term represents a blank node +function isBlankNode(term) { + return !!term && term.termType === 'BlankNode'; +} + +// Tests whether the given term represents a literal +function isLiteral(term) { + return !!term && term.termType === 'Literal'; +} + +// Tests whether the given term represents a variable +function isVariable(term) { + return !!term && term.termType === 'Variable'; +} + +// Tests whether the given term represents the default graph +function isDefaultGraph(term) { + return !!term && term.termType === 'DefaultGraph'; +} + +// Tests whether the given quad is in the default graph +function inDefaultGraph(quad) { + return isDefaultGraph(quad.graph); +} + +// Creates a function that prepends the given IRI to a local name +function prefix(iri, factory) { + return prefixes({ '': iri }, factory)(''); +} + +// Creates a function that allows registering and expanding prefixes +function prefixes(defaultPrefixes, factory) { + // Add all of the default prefixes + const prefixes = Object.create(null); + for (const prefix in defaultPrefixes) + processPrefix(prefix, defaultPrefixes[prefix]); + // Set the default factory if none was specified + factory = factory || _N3DataFactory__WEBPACK_IMPORTED_MODULE_0__["default"]; + + // Registers a new prefix (if an IRI was specified) + // or retrieves a function that expands an existing prefix (if no IRI was specified) + function processPrefix(prefix, iri) { + // Create a new prefix if an IRI is specified or the prefix doesn't exist + if (typeof iri === 'string') { + // Create a function that expands the prefix + const cache = Object.create(null); + prefixes[prefix] = local => { + return cache[local] || (cache[local] = factory.namedNode(iri + local)); + }; + } + else if (!(prefix in prefixes)) { + throw new Error(`Unknown prefix: ${prefix}`); + } + return prefixes[prefix]; + } + return processPrefix; +} + + +/***/ }), + +/***/ "./node_modules/n3/src/N3Writer.js": +/*!*****************************************!*\ + !*** ./node_modules/n3/src/N3Writer.js ***! + \*****************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return N3Writer; }); +/* harmony import */ var _IRIs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./IRIs */ "./node_modules/n3/src/IRIs.js"); +/* harmony import */ var _N3DataFactory__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./N3DataFactory */ "./node_modules/n3/src/N3DataFactory.js"); +/* harmony import */ var _N3Util__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./N3Util */ "./node_modules/n3/src/N3Util.js"); +// **N3Writer** writes N3 documents. + + + + +const DEFAULTGRAPH = _N3DataFactory__WEBPACK_IMPORTED_MODULE_1__["default"].defaultGraph(); + +const { rdf, xsd } = _IRIs__WEBPACK_IMPORTED_MODULE_0__["default"]; + +// Characters in literals that require escaping +const escape = /["\\\t\n\r\b\f\u0000-\u0019\ud800-\udbff]/, + escapeAll = /["\\\t\n\r\b\f\u0000-\u0019]|[\ud800-\udbff][\udc00-\udfff]/g, + escapedCharacters = { + '\\': '\\\\', '"': '\\"', '\t': '\\t', + '\n': '\\n', '\r': '\\r', '\b': '\\b', '\f': '\\f', + }; + +// ## Placeholder class to represent already pretty-printed terms +class SerializedTerm extends _N3DataFactory__WEBPACK_IMPORTED_MODULE_1__["Term"] { + // Pretty-printed nodes are not equal to any other node + // (e.g., [] does not equal []) + equals() { + return false; + } +} + +// ## Constructor +class N3Writer { + constructor(outputStream, options) { + // ### `_prefixRegex` matches a prefixed name or IRI that begins with one of the added prefixes + this._prefixRegex = /$0^/; + + // Shift arguments if the first argument is not a stream + if (outputStream && typeof outputStream.write !== 'function') + options = outputStream, outputStream = null; + options = options || {}; + this._lists = options.lists; + + // If no output stream given, send the output as string through the end callback + if (!outputStream) { + let output = ''; + this._outputStream = { + write(chunk, encoding, done) { output += chunk; done && done(); }, + end: done => { done && done(null, output); }, + }; + this._endStream = true; + } + else { + this._outputStream = outputStream; + this._endStream = options.end === undefined ? true : !!options.end; + } + + // Initialize writer, depending on the format + this._subject = null; + if (!(/triple|quad/i).test(options.format)) { + this._graph = DEFAULTGRAPH; + this._prefixIRIs = Object.create(null); + options.prefixes && this.addPrefixes(options.prefixes); + } + else { + this._writeQuad = this._writeQuadLine; + } + } + + // ## Private methods + + // ### Whether the current graph is the default graph + get _inDefaultGraph() { + return DEFAULTGRAPH.equals(this._graph); + } + + // ### `_write` writes the argument to the output stream + _write(string, callback) { + this._outputStream.write(string, 'utf8', callback); + } + + // ### `_writeQuad` writes the quad to the output stream + _writeQuad(subject, predicate, object, graph, done) { + try { + // Write the graph's label if it has changed + if (!graph.equals(this._graph)) { + // Close the previous graph and start the new one + this._write((this._subject === null ? '' : (this._inDefaultGraph ? '.\n' : '\n}\n')) + + (DEFAULTGRAPH.equals(graph) ? '' : `${this._encodeIriOrBlank(graph)} {\n`)); + this._graph = graph; + this._subject = null; + } + // Don't repeat the subject if it's the same + if (subject.equals(this._subject)) { + // Don't repeat the predicate if it's the same + if (predicate.equals(this._predicate)) + this._write(`, ${this._encodeObject(object)}`, done); + // Same subject, different predicate + else + this._write(`;\n ${ + this._encodePredicate(this._predicate = predicate)} ${ + this._encodeObject(object)}`, done); + } + // Different subject; write the whole quad + else + this._write(`${(this._subject === null ? '' : '.\n') + + this._encodeSubject(this._subject = subject)} ${ + this._encodePredicate(this._predicate = predicate)} ${ + this._encodeObject(object)}`, done); + } + catch (error) { done && done(error); } + } + + // ### `_writeQuadLine` writes the quad to the output stream as a single line + _writeQuadLine(subject, predicate, object, graph, done) { + // Write the quad without prefixes + delete this._prefixMatch; + this._write(this.quadToString(subject, predicate, object, graph), done); + } + + // ### `quadToString` serializes a quad as a string + quadToString(subject, predicate, object, graph) { + return `${this._encodeSubject(subject)} ${ + this._encodeIriOrBlank(predicate)} ${ + this._encodeObject(object) + }${graph && graph.value ? ` ${this._encodeIriOrBlank(graph)} .\n` : ' .\n'}`; + } + + // ### `quadsToString` serializes an array of quads as a string + quadsToString(quads) { + return quads.map(t => { + return this.quadToString(t.subject, t.predicate, t.object, t.graph); + }).join(''); + } + + // ### `_encodeSubject` represents a subject + _encodeSubject(entity) { + return entity.termType === 'Quad' ? + this._encodeQuad(entity) : this._encodeIriOrBlank(entity); + } + + // ### `_encodeIriOrBlank` represents an IRI or blank node + _encodeIriOrBlank(entity) { + // A blank node or list is represented as-is + if (entity.termType !== 'NamedNode') { + // If it is a list head, pretty-print it + if (this._lists && (entity.value in this._lists)) + entity = this.list(this._lists[entity.value]); + return 'id' in entity ? entity.id : `_:${entity.value}`; + } + // Escape special characters + let iri = entity.value; + if (escape.test(iri)) + iri = iri.replace(escapeAll, characterReplacer); + // Try to represent the IRI as prefixed name + const prefixMatch = this._prefixRegex.exec(iri); + return !prefixMatch ? `<${iri}>` : + (!prefixMatch[1] ? iri : this._prefixIRIs[prefixMatch[1]] + prefixMatch[2]); + } + + // ### `_encodeLiteral` represents a literal + _encodeLiteral(literal) { + // Escape special characters + let value = literal.value; + if (escape.test(value)) + value = value.replace(escapeAll, characterReplacer); + // Write the literal, possibly with type or language + if (literal.language) + return `"${value}"@${literal.language}`; + else if (literal.datatype.value !== xsd.string) + return `"${value}"^^${this._encodeIriOrBlank(literal.datatype)}`; + else + return `"${value}"`; + } + + // ### `_encodePredicate` represents a predicate + _encodePredicate(predicate) { + return predicate.value === rdf.type ? 'a' : this._encodeIriOrBlank(predicate); + } + + // ### `_encodeObject` represents an object + _encodeObject(object) { + switch (object.termType) { + case 'Quad': + return this._encodeQuad(object); + case 'Literal': + return this._encodeLiteral(object); + default: + return this._encodeIriOrBlank(object); + } + } + + // ### `_encodeQuad` encodes an RDF* quad + _encodeQuad({ subject, predicate, object, graph }) { + return `<<${ + this._encodeSubject(subject)} ${ + this._encodePredicate(predicate)} ${ + this._encodeObject(object)}${ + Object(_N3Util__WEBPACK_IMPORTED_MODULE_2__["isDefaultGraph"])(graph) ? '' : ` ${this._encodeIriOrBlank(graph)}`}>>`; + } + + // ### `_blockedWrite` replaces `_write` after the writer has been closed + _blockedWrite() { + throw new Error('Cannot write because the writer has been closed.'); + } + + // ### `addQuad` adds the quad to the output stream + addQuad(subject, predicate, object, graph, done) { + // The quad was given as an object, so shift parameters + if (object === undefined) + this._writeQuad(subject.subject, subject.predicate, subject.object, subject.graph, predicate); + // The optional `graph` parameter was not provided + else if (typeof graph === 'function') + this._writeQuad(subject, predicate, object, DEFAULTGRAPH, graph); + // The `graph` parameter was provided + else + this._writeQuad(subject, predicate, object, graph || DEFAULTGRAPH, done); + } + + // ### `addQuads` adds the quads to the output stream + addQuads(quads) { + for (let i = 0; i < quads.length; i++) + this.addQuad(quads[i]); + } + + // ### `addPrefix` adds the prefix to the output stream + addPrefix(prefix, iri, done) { + const prefixes = {}; + prefixes[prefix] = iri; + this.addPrefixes(prefixes, done); + } + + // ### `addPrefixes` adds the prefixes to the output stream + addPrefixes(prefixes, done) { + // Ignore prefixes if not supported by the serialization + if (!this._prefixIRIs) + return done && done(); + + // Write all new prefixes + let hasPrefixes = false; + for (let prefix in prefixes) { + let iri = prefixes[prefix]; + if (typeof iri !== 'string') + iri = iri.value; + hasPrefixes = true; + // Finish a possible pending quad + if (this._subject !== null) { + this._write(this._inDefaultGraph ? '.\n' : '\n}\n'); + this._subject = null, this._graph = ''; + } + // Store and write the prefix + this._prefixIRIs[iri] = (prefix += ':'); + this._write(`@prefix ${prefix} <${iri}>.\n`); + } + // Recreate the prefix matcher + if (hasPrefixes) { + let IRIlist = '', prefixList = ''; + for (const prefixIRI in this._prefixIRIs) { + IRIlist += IRIlist ? `|${prefixIRI}` : prefixIRI; + prefixList += (prefixList ? '|' : '') + this._prefixIRIs[prefixIRI]; + } + IRIlist = IRIlist.replace(/[\]\/\(\)\*\+\?\.\\\$]/g, '\\$&'); + this._prefixRegex = new RegExp(`^(?:${prefixList})[^\/]*$|` + + `^(${IRIlist})([a-zA-Z][\\-_a-zA-Z0-9]*)$`); + } + // End a prefix block with a newline + this._write(hasPrefixes ? '\n' : '', done); + } + + // ### `blank` creates a blank node with the given content + blank(predicate, object) { + let children = predicate, child, length; + // Empty blank node + if (predicate === undefined) + children = []; + // Blank node passed as blank(Term("predicate"), Term("object")) + else if (predicate.termType) + children = [{ predicate: predicate, object: object }]; + // Blank node passed as blank({ predicate: predicate, object: object }) + else if (!('length' in predicate)) + children = [predicate]; + + switch (length = children.length) { + // Generate an empty blank node + case 0: + return new SerializedTerm('[]'); + // Generate a non-nested one-triple blank node + case 1: + child = children[0]; + if (!(child.object instanceof SerializedTerm)) + return new SerializedTerm(`[ ${this._encodePredicate(child.predicate)} ${ + this._encodeObject(child.object)} ]`); + // Generate a multi-triple or nested blank node + default: + let contents = '['; + // Write all triples in order + for (let i = 0; i < length; i++) { + child = children[i]; + // Write only the object is the predicate is the same as the previous + if (child.predicate.equals(predicate)) + contents += `, ${this._encodeObject(child.object)}`; + // Otherwise, write the predicate and the object + else { + contents += `${(i ? ';\n ' : '\n ') + + this._encodePredicate(child.predicate)} ${ + this._encodeObject(child.object)}`; + predicate = child.predicate; + } + } + return new SerializedTerm(`${contents}\n]`); + } + } + + // ### `list` creates a list node with the given content + list(elements) { + const length = elements && elements.length || 0, contents = new Array(length); + for (let i = 0; i < length; i++) + contents[i] = this._encodeObject(elements[i]); + return new SerializedTerm(`(${contents.join(' ')})`); + } + + // ### `end` signals the end of the output stream + end(done) { + // Finish a possible pending quad + if (this._subject !== null) { + this._write(this._inDefaultGraph ? '.\n' : '\n}\n'); + this._subject = null; + } + // Disallow further writing + this._write = this._blockedWrite; + + // Try to end the underlying stream, ensuring done is called exactly one time + let singleDone = done && ((error, result) => { singleDone = null, done(error, result); }); + if (this._endStream) { + try { return this._outputStream.end(singleDone); } + catch (error) { /* error closing stream */ } + } + singleDone && singleDone(); + } +} + +// Replaces a character by its escaped version +function characterReplacer(character) { + // Replace a single character by its escaped version + let result = escapedCharacters[character]; + if (result === undefined) { + // Replace a single character with its 4-bit unicode escape sequence + if (character.length === 1) { + result = character.charCodeAt(0).toString(16); + result = '\\u0000'.substr(0, 6 - result.length) + result; + } + // Replace a surrogate pair with its 8-bit unicode escape sequence + else { + result = ((character.charCodeAt(0) - 0xD800) * 0x400 + + character.charCodeAt(1) + 0x2400).toString(16); + result = '\\U00000000'.substr(0, 10 - result.length) + result; + } + } + return result; +} + + +/***/ }), + +/***/ "./node_modules/n3/src/index.js": +/*!**************************************!*\ + !*** ./node_modules/n3/src/index.js ***! + \**************************************/ +/*! exports provided: Lexer, Parser, Writer, Store, StreamParser, StreamWriter, Util, DataFactory, Term, NamedNode, Literal, BlankNode, Variable, DefaultGraph, Quad, Triple, termFromId, termToId */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _N3Lexer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./N3Lexer */ "./node_modules/n3/src/N3Lexer.js"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Lexer", function() { return _N3Lexer__WEBPACK_IMPORTED_MODULE_0__["default"]; }); + +/* harmony import */ var _N3Parser__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./N3Parser */ "./node_modules/n3/src/N3Parser.js"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Parser", function() { return _N3Parser__WEBPACK_IMPORTED_MODULE_1__["default"]; }); + +/* harmony import */ var _N3Writer__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./N3Writer */ "./node_modules/n3/src/N3Writer.js"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Writer", function() { return _N3Writer__WEBPACK_IMPORTED_MODULE_2__["default"]; }); + +/* harmony import */ var _N3Store__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./N3Store */ "./node_modules/n3/src/N3Store.js"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Store", function() { return _N3Store__WEBPACK_IMPORTED_MODULE_3__["default"]; }); + +/* harmony import */ var _N3StreamParser__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./N3StreamParser */ "./node_modules/n3/src/N3StreamParser.js"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StreamParser", function() { return _N3StreamParser__WEBPACK_IMPORTED_MODULE_4__["default"]; }); + +/* harmony import */ var _N3StreamWriter__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./N3StreamWriter */ "./node_modules/n3/src/N3StreamWriter.js"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StreamWriter", function() { return _N3StreamWriter__WEBPACK_IMPORTED_MODULE_5__["default"]; }); + +/* harmony import */ var _N3Util__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./N3Util */ "./node_modules/n3/src/N3Util.js"); +/* harmony reexport (module object) */ __webpack_require__.d(__webpack_exports__, "Util", function() { return _N3Util__WEBPACK_IMPORTED_MODULE_6__; }); +/* harmony import */ var _N3DataFactory__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./N3DataFactory */ "./node_modules/n3/src/N3DataFactory.js"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DataFactory", function() { return _N3DataFactory__WEBPACK_IMPORTED_MODULE_7__["default"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Term", function() { return _N3DataFactory__WEBPACK_IMPORTED_MODULE_7__["Term"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NamedNode", function() { return _N3DataFactory__WEBPACK_IMPORTED_MODULE_7__["NamedNode"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Literal", function() { return _N3DataFactory__WEBPACK_IMPORTED_MODULE_7__["Literal"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BlankNode", function() { return _N3DataFactory__WEBPACK_IMPORTED_MODULE_7__["BlankNode"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Variable", function() { return _N3DataFactory__WEBPACK_IMPORTED_MODULE_7__["Variable"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DefaultGraph", function() { return _N3DataFactory__WEBPACK_IMPORTED_MODULE_7__["DefaultGraph"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Quad", function() { return _N3DataFactory__WEBPACK_IMPORTED_MODULE_7__["Quad"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Triple", function() { return _N3DataFactory__WEBPACK_IMPORTED_MODULE_7__["Triple"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "termFromId", function() { return _N3DataFactory__WEBPACK_IMPORTED_MODULE_7__["termFromId"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "termToId", function() { return _N3DataFactory__WEBPACK_IMPORTED_MODULE_7__["termToId"]; }); + + + + + + + + + + + + + + +/***/ }), + +/***/ "./node_modules/node-forge/lib/baseN.js": +/*!**********************************************!*\ + !*** ./node_modules/node-forge/lib/baseN.js ***! + \**********************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +/* WEBPACK VAR INJECTION */(function(Buffer) {/** + * Base-N/Base-X encoding/decoding functions. + * + * Original implementation from base-x: + * https://github.com/cryptocoinjs/base-x + * + * Which is MIT licensed: + * + * The MIT License (MIT) + * + * Copyright base-x contributors (c) 2016 + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + */ +var api = {}; +module.exports = api; + +// baseN alphabet indexes +var _reverseAlphabets = {}; + +/** + * BaseN-encodes a Uint8Array using the given alphabet. + * + * @param input the Uint8Array to encode. + * @param maxline the maximum number of encoded characters per line to use, + * defaults to none. + * + * @return the baseN-encoded output string. + */ +api.encode = function(input, alphabet, maxline) { + if(typeof alphabet !== 'string') { + throw new TypeError('"alphabet" must be a string.'); + } + if(maxline !== undefined && typeof maxline !== 'number') { + throw new TypeError('"maxline" must be a number.'); + } + + var output = ''; + + if(!(input instanceof Uint8Array)) { + // assume forge byte buffer + output = _encodeWithByteBuffer(input, alphabet); + } else { + var i = 0; + var base = alphabet.length; + var first = alphabet.charAt(0); + var digits = [0]; + for(i = 0; i < input.length; ++i) { + for(var j = 0, carry = input[i]; j < digits.length; ++j) { + carry += digits[j] << 8; + digits[j] = carry % base; + carry = (carry / base) | 0; + } + + while(carry > 0) { + digits.push(carry % base); + carry = (carry / base) | 0; + } + } + + // deal with leading zeros + for(i = 0; input[i] === 0 && i < input.length - 1; ++i) { + output += first; + } + // convert digits to a string + for(i = digits.length - 1; i >= 0; --i) { + output += alphabet[digits[i]]; + } + } + + if(maxline) { + var regex = new RegExp('.{1,' + maxline + '}', 'g'); + output = output.match(regex).join('\r\n'); + } + + return output; +}; + +/** + * Decodes a baseN-encoded (using the given alphabet) string to a + * Uint8Array. + * + * @param input the baseN-encoded input string. + * + * @return the Uint8Array. + */ +api.decode = function(input, alphabet) { + if(typeof input !== 'string') { + throw new TypeError('"input" must be a string.'); + } + if(typeof alphabet !== 'string') { + throw new TypeError('"alphabet" must be a string.'); + } + + var table = _reverseAlphabets[alphabet]; + if(!table) { + // compute reverse alphabet + table = _reverseAlphabets[alphabet] = []; + for(var i = 0; i < alphabet.length; ++i) { + table[alphabet.charCodeAt(i)] = i; + } + } + + // remove whitespace characters + input = input.replace(/\s/g, ''); + + var base = alphabet.length; + var first = alphabet.charAt(0); + var bytes = [0]; + for(var i = 0; i < input.length; i++) { + var value = table[input.charCodeAt(i)]; + if(value === undefined) { + return; + } + + for(var j = 0, carry = value; j < bytes.length; ++j) { + carry += bytes[j] * base; + bytes[j] = carry & 0xff; + carry >>= 8; + } + + while(carry > 0) { + bytes.push(carry & 0xff); + carry >>= 8; + } + } + + // deal with leading zeros + for(var k = 0; input[k] === first && k < input.length - 1; ++k) { + bytes.push(0); + } + + if(typeof Buffer !== 'undefined') { + return Buffer.from(bytes.reverse()); + } + + return new Uint8Array(bytes.reverse()); +}; + +function _encodeWithByteBuffer(input, alphabet) { + var i = 0; + var base = alphabet.length; + var first = alphabet.charAt(0); + var digits = [0]; + for(i = 0; i < input.length(); ++i) { + for(var j = 0, carry = input.at(i); j < digits.length; ++j) { + carry += digits[j] << 8; + digits[j] = carry % base; + carry = (carry / base) | 0; + } + + while(carry > 0) { + digits.push(carry % base); + carry = (carry / base) | 0; + } + } + + var output = ''; + + // deal with leading zeros + for(i = 0; input.at(i) === 0 && i < input.length() - 1; ++i) { + output += first; + } + // convert digits to a string + for(i = digits.length - 1; i >= 0; --i) { + output += alphabet[digits[i]]; + } + + return output; +} + +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../node-libs-browser/node_modules/buffer/index.js */ "./node_modules/node-libs-browser/node_modules/buffer/index.js").Buffer)) + +/***/ }), + +/***/ "./node_modules/node-forge/lib/forge.js": +/*!**********************************************!*\ + !*** ./node_modules/node-forge/lib/forge.js ***! + \**********************************************/ +/*! no static exports found */ +/***/ (function(module, exports) { + +/** + * Node.js module for Forge. + * + * @author Dave Longley + * + * Copyright 2011-2016 Digital Bazaar, Inc. + */ +module.exports = { + // default options + options: { + usePureJavaScript: false + } +}; + + +/***/ }), + +/***/ "./node_modules/node-forge/lib/md.js": +/*!*******************************************!*\ + !*** ./node_modules/node-forge/lib/md.js ***! + \*******************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * Node.js module for Forge message digests. + * + * @author Dave Longley + * + * Copyright 2011-2017 Digital Bazaar, Inc. + */ +var forge = __webpack_require__(/*! ./forge */ "./node_modules/node-forge/lib/forge.js"); + +module.exports = forge.md = forge.md || {}; +forge.md.algorithms = forge.md.algorithms || {}; + + +/***/ }), + +/***/ "./node_modules/node-forge/lib/sha1.js": +/*!*********************************************!*\ + !*** ./node_modules/node-forge/lib/sha1.js ***! + \*********************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * Secure Hash Algorithm with 160-bit digest (SHA-1) implementation. + * + * @author Dave Longley + * + * Copyright (c) 2010-2015 Digital Bazaar, Inc. + */ +var forge = __webpack_require__(/*! ./forge */ "./node_modules/node-forge/lib/forge.js"); +__webpack_require__(/*! ./md */ "./node_modules/node-forge/lib/md.js"); +__webpack_require__(/*! ./util */ "./node_modules/node-forge/lib/util.js"); + +var sha1 = module.exports = forge.sha1 = forge.sha1 || {}; +forge.md.sha1 = forge.md.algorithms.sha1 = sha1; + +/** + * Creates a SHA-1 message digest object. + * + * @return a message digest object. + */ +sha1.create = function() { + // do initialization as necessary + if(!_initialized) { + _init(); + } + + // SHA-1 state contains five 32-bit integers + var _state = null; + + // input buffer + var _input = forge.util.createBuffer(); + + // used for word storage + var _w = new Array(80); + + // message digest object + var md = { + algorithm: 'sha1', + blockLength: 64, + digestLength: 20, + // 56-bit length of message so far (does not including padding) + messageLength: 0, + // true message length + fullMessageLength: null, + // size of message length in bytes + messageLengthSize: 8 + }; + + /** + * Starts the digest. + * + * @return this digest object. + */ + md.start = function() { + // up to 56-bit message length for convenience + md.messageLength = 0; + + // full message length (set md.messageLength64 for backwards-compatibility) + md.fullMessageLength = md.messageLength64 = []; + var int32s = md.messageLengthSize / 4; + for(var i = 0; i < int32s; ++i) { + md.fullMessageLength.push(0); + } + _input = forge.util.createBuffer(); + _state = { + h0: 0x67452301, + h1: 0xEFCDAB89, + h2: 0x98BADCFE, + h3: 0x10325476, + h4: 0xC3D2E1F0 + }; + return md; + }; + // start digest automatically for first time + md.start(); + + /** + * Updates the digest with the given message input. The given input can + * treated as raw input (no encoding will be applied) or an encoding of + * 'utf8' maybe given to encode the input using UTF-8. + * + * @param msg the message input to update with. + * @param encoding the encoding to use (default: 'raw', other: 'utf8'). + * + * @return this digest object. + */ + md.update = function(msg, encoding) { + if(encoding === 'utf8') { + msg = forge.util.encodeUtf8(msg); + } + + // update message length + var len = msg.length; + md.messageLength += len; + len = [(len / 0x100000000) >>> 0, len >>> 0]; + for(var i = md.fullMessageLength.length - 1; i >= 0; --i) { + md.fullMessageLength[i] += len[1]; + len[1] = len[0] + ((md.fullMessageLength[i] / 0x100000000) >>> 0); + md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0; + len[0] = ((len[1] / 0x100000000) >>> 0); + } + + // add bytes to input buffer + _input.putBytes(msg); + + // process bytes + _update(_state, _w, _input); + + // compact input buffer every 2K or if empty + if(_input.read > 2048 || _input.length() === 0) { + _input.compact(); + } + + return md; + }; + + /** + * Produces the digest. + * + * @return a byte buffer containing the digest value. + */ + md.digest = function() { + /* Note: Here we copy the remaining bytes in the input buffer and + add the appropriate SHA-1 padding. Then we do the final update + on a copy of the state so that if the user wants to get + intermediate digests they can do so. */ + + /* Determine the number of bytes that must be added to the message + to ensure its length is congruent to 448 mod 512. In other words, + the data to be digested must be a multiple of 512 bits (or 128 bytes). + This data includes the message, some padding, and the length of the + message. Since the length of the message will be encoded as 8 bytes (64 + bits), that means that the last segment of the data must have 56 bytes + (448 bits) of message and padding. Therefore, the length of the message + plus the padding must be congruent to 448 mod 512 because + 512 - 128 = 448. + + In order to fill up the message length it must be filled with + padding that begins with 1 bit followed by all 0 bits. Padding + must *always* be present, so if the message length is already + congruent to 448 mod 512, then 512 padding bits must be added. */ + + var finalBlock = forge.util.createBuffer(); + finalBlock.putBytes(_input.bytes()); + + // compute remaining size to be digested (include message length size) + var remaining = ( + md.fullMessageLength[md.fullMessageLength.length - 1] + + md.messageLengthSize); + + // add padding for overflow blockSize - overflow + // _padding starts with 1 byte with first bit is set (byte value 128), then + // there may be up to (blockSize - 1) other pad bytes + var overflow = remaining & (md.blockLength - 1); + finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow)); + + // serialize message length in bits in big-endian order; since length + // is stored in bytes we multiply by 8 and add carry from next int + var next, carry; + var bits = md.fullMessageLength[0] * 8; + for(var i = 0; i < md.fullMessageLength.length - 1; ++i) { + next = md.fullMessageLength[i + 1] * 8; + carry = (next / 0x100000000) >>> 0; + bits += carry; + finalBlock.putInt32(bits >>> 0); + bits = next >>> 0; + } + finalBlock.putInt32(bits); + + var s2 = { + h0: _state.h0, + h1: _state.h1, + h2: _state.h2, + h3: _state.h3, + h4: _state.h4 + }; + _update(s2, _w, finalBlock); + var rval = forge.util.createBuffer(); + rval.putInt32(s2.h0); + rval.putInt32(s2.h1); + rval.putInt32(s2.h2); + rval.putInt32(s2.h3); + rval.putInt32(s2.h4); + return rval; + }; + + return md; +}; + +// sha-1 padding bytes not initialized yet +var _padding = null; +var _initialized = false; + +/** + * Initializes the constant tables. + */ +function _init() { + // create padding + _padding = String.fromCharCode(128); + _padding += forge.util.fillString(String.fromCharCode(0x00), 64); + + // now initialized + _initialized = true; +} + +/** + * Updates a SHA-1 state with the given byte buffer. + * + * @param s the SHA-1 state to update. + * @param w the array to use to store words. + * @param bytes the byte buffer to update with. + */ +function _update(s, w, bytes) { + // consume 512 bit (64 byte) chunks + var t, a, b, c, d, e, f, i; + var len = bytes.length(); + while(len >= 64) { + // the w array will be populated with sixteen 32-bit big-endian words + // and then extended into 80 32-bit words according to SHA-1 algorithm + // and for 32-79 using Max Locktyukhin's optimization + + // initialize hash value for this chunk + a = s.h0; + b = s.h1; + c = s.h2; + d = s.h3; + e = s.h4; + + // round 1 + for(i = 0; i < 16; ++i) { + t = bytes.getInt32(); + w[i] = t; + f = d ^ (b & (c ^ d)); + t = ((a << 5) | (a >>> 27)) + f + e + 0x5A827999 + t; + e = d; + d = c; + // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug + c = ((b << 30) | (b >>> 2)) >>> 0; + b = a; + a = t; + } + for(; i < 20; ++i) { + t = (w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]); + t = (t << 1) | (t >>> 31); + w[i] = t; + f = d ^ (b & (c ^ d)); + t = ((a << 5) | (a >>> 27)) + f + e + 0x5A827999 + t; + e = d; + d = c; + // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug + c = ((b << 30) | (b >>> 2)) >>> 0; + b = a; + a = t; + } + // round 2 + for(; i < 32; ++i) { + t = (w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]); + t = (t << 1) | (t >>> 31); + w[i] = t; + f = b ^ c ^ d; + t = ((a << 5) | (a >>> 27)) + f + e + 0x6ED9EBA1 + t; + e = d; + d = c; + // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug + c = ((b << 30) | (b >>> 2)) >>> 0; + b = a; + a = t; + } + for(; i < 40; ++i) { + t = (w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]); + t = (t << 2) | (t >>> 30); + w[i] = t; + f = b ^ c ^ d; + t = ((a << 5) | (a >>> 27)) + f + e + 0x6ED9EBA1 + t; + e = d; + d = c; + // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug + c = ((b << 30) | (b >>> 2)) >>> 0; + b = a; + a = t; + } + // round 3 + for(; i < 60; ++i) { + t = (w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]); + t = (t << 2) | (t >>> 30); + w[i] = t; + f = (b & c) | (d & (b ^ c)); + t = ((a << 5) | (a >>> 27)) + f + e + 0x8F1BBCDC + t; + e = d; + d = c; + // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug + c = ((b << 30) | (b >>> 2)) >>> 0; + b = a; + a = t; + } + // round 4 + for(; i < 80; ++i) { + t = (w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]); + t = (t << 2) | (t >>> 30); + w[i] = t; + f = b ^ c ^ d; + t = ((a << 5) | (a >>> 27)) + f + e + 0xCA62C1D6 + t; + e = d; + d = c; + // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug + c = ((b << 30) | (b >>> 2)) >>> 0; + b = a; + a = t; + } + + // update hash state + s.h0 = (s.h0 + a) | 0; + s.h1 = (s.h1 + b) | 0; + s.h2 = (s.h2 + c) | 0; + s.h3 = (s.h3 + d) | 0; + s.h4 = (s.h4 + e) | 0; + + len -= 64; + } +} + + +/***/ }), + +/***/ "./node_modules/node-forge/lib/sha256.js": +/*!***********************************************!*\ + !*** ./node_modules/node-forge/lib/sha256.js ***! + \***********************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * Secure Hash Algorithm with 256-bit digest (SHA-256) implementation. + * + * See FIPS 180-2 for details. + * + * @author Dave Longley + * + * Copyright (c) 2010-2015 Digital Bazaar, Inc. + */ +var forge = __webpack_require__(/*! ./forge */ "./node_modules/node-forge/lib/forge.js"); +__webpack_require__(/*! ./md */ "./node_modules/node-forge/lib/md.js"); +__webpack_require__(/*! ./util */ "./node_modules/node-forge/lib/util.js"); + +var sha256 = module.exports = forge.sha256 = forge.sha256 || {}; +forge.md.sha256 = forge.md.algorithms.sha256 = sha256; + +/** + * Creates a SHA-256 message digest object. + * + * @return a message digest object. + */ +sha256.create = function() { + // do initialization as necessary + if(!_initialized) { + _init(); + } + + // SHA-256 state contains eight 32-bit integers + var _state = null; + + // input buffer + var _input = forge.util.createBuffer(); + + // used for word storage + var _w = new Array(64); + + // message digest object + var md = { + algorithm: 'sha256', + blockLength: 64, + digestLength: 32, + // 56-bit length of message so far (does not including padding) + messageLength: 0, + // true message length + fullMessageLength: null, + // size of message length in bytes + messageLengthSize: 8 + }; + + /** + * Starts the digest. + * + * @return this digest object. + */ + md.start = function() { + // up to 56-bit message length for convenience + md.messageLength = 0; + + // full message length (set md.messageLength64 for backwards-compatibility) + md.fullMessageLength = md.messageLength64 = []; + var int32s = md.messageLengthSize / 4; + for(var i = 0; i < int32s; ++i) { + md.fullMessageLength.push(0); + } + _input = forge.util.createBuffer(); + _state = { + h0: 0x6A09E667, + h1: 0xBB67AE85, + h2: 0x3C6EF372, + h3: 0xA54FF53A, + h4: 0x510E527F, + h5: 0x9B05688C, + h6: 0x1F83D9AB, + h7: 0x5BE0CD19 + }; + return md; + }; + // start digest automatically for first time + md.start(); + + /** + * Updates the digest with the given message input. The given input can + * treated as raw input (no encoding will be applied) or an encoding of + * 'utf8' maybe given to encode the input using UTF-8. + * + * @param msg the message input to update with. + * @param encoding the encoding to use (default: 'raw', other: 'utf8'). + * + * @return this digest object. + */ + md.update = function(msg, encoding) { + if(encoding === 'utf8') { + msg = forge.util.encodeUtf8(msg); + } + + // update message length + var len = msg.length; + md.messageLength += len; + len = [(len / 0x100000000) >>> 0, len >>> 0]; + for(var i = md.fullMessageLength.length - 1; i >= 0; --i) { + md.fullMessageLength[i] += len[1]; + len[1] = len[0] + ((md.fullMessageLength[i] / 0x100000000) >>> 0); + md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0; + len[0] = ((len[1] / 0x100000000) >>> 0); + } + + // add bytes to input buffer + _input.putBytes(msg); + + // process bytes + _update(_state, _w, _input); + + // compact input buffer every 2K or if empty + if(_input.read > 2048 || _input.length() === 0) { + _input.compact(); + } + + return md; + }; + + /** + * Produces the digest. + * + * @return a byte buffer containing the digest value. + */ + md.digest = function() { + /* Note: Here we copy the remaining bytes in the input buffer and + add the appropriate SHA-256 padding. Then we do the final update + on a copy of the state so that if the user wants to get + intermediate digests they can do so. */ + + /* Determine the number of bytes that must be added to the message + to ensure its length is congruent to 448 mod 512. In other words, + the data to be digested must be a multiple of 512 bits (or 128 bytes). + This data includes the message, some padding, and the length of the + message. Since the length of the message will be encoded as 8 bytes (64 + bits), that means that the last segment of the data must have 56 bytes + (448 bits) of message and padding. Therefore, the length of the message + plus the padding must be congruent to 448 mod 512 because + 512 - 128 = 448. + + In order to fill up the message length it must be filled with + padding that begins with 1 bit followed by all 0 bits. Padding + must *always* be present, so if the message length is already + congruent to 448 mod 512, then 512 padding bits must be added. */ + + var finalBlock = forge.util.createBuffer(); + finalBlock.putBytes(_input.bytes()); + + // compute remaining size to be digested (include message length size) + var remaining = ( + md.fullMessageLength[md.fullMessageLength.length - 1] + + md.messageLengthSize); + + // add padding for overflow blockSize - overflow + // _padding starts with 1 byte with first bit is set (byte value 128), then + // there may be up to (blockSize - 1) other pad bytes + var overflow = remaining & (md.blockLength - 1); + finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow)); + + // serialize message length in bits in big-endian order; since length + // is stored in bytes we multiply by 8 and add carry from next int + var next, carry; + var bits = md.fullMessageLength[0] * 8; + for(var i = 0; i < md.fullMessageLength.length - 1; ++i) { + next = md.fullMessageLength[i + 1] * 8; + carry = (next / 0x100000000) >>> 0; + bits += carry; + finalBlock.putInt32(bits >>> 0); + bits = next >>> 0; + } + finalBlock.putInt32(bits); + + var s2 = { + h0: _state.h0, + h1: _state.h1, + h2: _state.h2, + h3: _state.h3, + h4: _state.h4, + h5: _state.h5, + h6: _state.h6, + h7: _state.h7 + }; + _update(s2, _w, finalBlock); + var rval = forge.util.createBuffer(); + rval.putInt32(s2.h0); + rval.putInt32(s2.h1); + rval.putInt32(s2.h2); + rval.putInt32(s2.h3); + rval.putInt32(s2.h4); + rval.putInt32(s2.h5); + rval.putInt32(s2.h6); + rval.putInt32(s2.h7); + return rval; + }; + + return md; +}; + +// sha-256 padding bytes not initialized yet +var _padding = null; +var _initialized = false; + +// table of constants +var _k = null; + +/** + * Initializes the constant tables. + */ +function _init() { + // create padding + _padding = String.fromCharCode(128); + _padding += forge.util.fillString(String.fromCharCode(0x00), 64); + + // create K table for SHA-256 + _k = [ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, + 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, + 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, + 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, + 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, + 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, + 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, + 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, + 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2]; + + // now initialized + _initialized = true; +} + +/** + * Updates a SHA-256 state with the given byte buffer. + * + * @param s the SHA-256 state to update. + * @param w the array to use to store words. + * @param bytes the byte buffer to update with. + */ +function _update(s, w, bytes) { + // consume 512 bit (64 byte) chunks + var t1, t2, s0, s1, ch, maj, i, a, b, c, d, e, f, g, h; + var len = bytes.length(); + while(len >= 64) { + // the w array will be populated with sixteen 32-bit big-endian words + // and then extended into 64 32-bit words according to SHA-256 + for(i = 0; i < 16; ++i) { + w[i] = bytes.getInt32(); + } + for(; i < 64; ++i) { + // XOR word 2 words ago rot right 17, rot right 19, shft right 10 + t1 = w[i - 2]; + t1 = + ((t1 >>> 17) | (t1 << 15)) ^ + ((t1 >>> 19) | (t1 << 13)) ^ + (t1 >>> 10); + // XOR word 15 words ago rot right 7, rot right 18, shft right 3 + t2 = w[i - 15]; + t2 = + ((t2 >>> 7) | (t2 << 25)) ^ + ((t2 >>> 18) | (t2 << 14)) ^ + (t2 >>> 3); + // sum(t1, word 7 ago, t2, word 16 ago) modulo 2^32 + w[i] = (t1 + w[i - 7] + t2 + w[i - 16]) | 0; + } + + // initialize hash value for this chunk + a = s.h0; + b = s.h1; + c = s.h2; + d = s.h3; + e = s.h4; + f = s.h5; + g = s.h6; + h = s.h7; + + // round function + for(i = 0; i < 64; ++i) { + // Sum1(e) + s1 = + ((e >>> 6) | (e << 26)) ^ + ((e >>> 11) | (e << 21)) ^ + ((e >>> 25) | (e << 7)); + // Ch(e, f, g) (optimized the same way as SHA-1) + ch = g ^ (e & (f ^ g)); + // Sum0(a) + s0 = + ((a >>> 2) | (a << 30)) ^ + ((a >>> 13) | (a << 19)) ^ + ((a >>> 22) | (a << 10)); + // Maj(a, b, c) (optimized the same way as SHA-1) + maj = (a & b) | (c & (a ^ b)); + + // main algorithm + t1 = h + s1 + ch + _k[i] + w[i]; + t2 = s0 + maj; + h = g; + g = f; + f = e; + // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug + // can't truncate with `| 0` + e = (d + t1) >>> 0; + d = c; + c = b; + b = a; + // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug + // can't truncate with `| 0` + a = (t1 + t2) >>> 0; + } + + // update hash state + s.h0 = (s.h0 + a) | 0; + s.h1 = (s.h1 + b) | 0; + s.h2 = (s.h2 + c) | 0; + s.h3 = (s.h3 + d) | 0; + s.h4 = (s.h4 + e) | 0; + s.h5 = (s.h5 + f) | 0; + s.h6 = (s.h6 + g) | 0; + s.h7 = (s.h7 + h) | 0; + len -= 64; + } +} + + +/***/ }), + +/***/ "./node_modules/node-forge/lib/util.js": +/*!*********************************************!*\ + !*** ./node_modules/node-forge/lib/util.js ***! + \*********************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +/* WEBPACK VAR INJECTION */(function(process, setImmediate, global, Buffer) {/** + * Utility functions for web applications. + * + * @author Dave Longley + * + * Copyright (c) 2010-2018 Digital Bazaar, Inc. + */ +var forge = __webpack_require__(/*! ./forge */ "./node_modules/node-forge/lib/forge.js"); +var baseN = __webpack_require__(/*! ./baseN */ "./node_modules/node-forge/lib/baseN.js"); + +/* Utilities API */ +var util = module.exports = forge.util = forge.util || {}; + +// define setImmediate and nextTick +(function() { + // use native nextTick (unless we're in webpack) + // webpack (or better node-libs-browser polyfill) sets process.browser. + // this way we can detect webpack properly + if(typeof process !== 'undefined' && process.nextTick && !process.browser) { + util.nextTick = process.nextTick; + if(typeof setImmediate === 'function') { + util.setImmediate = setImmediate; + } else { + // polyfill setImmediate with nextTick, older versions of node + // (those w/o setImmediate) won't totally starve IO + util.setImmediate = util.nextTick; + } + return; + } + + // polyfill nextTick with native setImmediate + if(typeof setImmediate === 'function') { + util.setImmediate = function() { return setImmediate.apply(undefined, arguments); }; + util.nextTick = function(callback) { + return setImmediate(callback); + }; + return; + } + + /* Note: A polyfill upgrade pattern is used here to allow combining + polyfills. For example, MutationObserver is fast, but blocks UI updates, + so it needs to allow UI updates periodically, so it falls back on + postMessage or setTimeout. */ + + // polyfill with setTimeout + util.setImmediate = function(callback) { + setTimeout(callback, 0); + }; + + // upgrade polyfill to use postMessage + if(typeof window !== 'undefined' && + typeof window.postMessage === 'function') { + var msg = 'forge.setImmediate'; + var callbacks = []; + util.setImmediate = function(callback) { + callbacks.push(callback); + // only send message when one hasn't been sent in + // the current turn of the event loop + if(callbacks.length === 1) { + window.postMessage(msg, '*'); + } + }; + function handler(event) { + if(event.source === window && event.data === msg) { + event.stopPropagation(); + var copy = callbacks.slice(); + callbacks.length = 0; + copy.forEach(function(callback) { + callback(); + }); + } + } + window.addEventListener('message', handler, true); + } + + // upgrade polyfill to use MutationObserver + if(typeof MutationObserver !== 'undefined') { + // polyfill with MutationObserver + var now = Date.now(); + var attr = true; + var div = document.createElement('div'); + var callbacks = []; + new MutationObserver(function() { + var copy = callbacks.slice(); + callbacks.length = 0; + copy.forEach(function(callback) { + callback(); + }); + }).observe(div, {attributes: true}); + var oldSetImmediate = util.setImmediate; + util.setImmediate = function(callback) { + if(Date.now() - now > 15) { + now = Date.now(); + oldSetImmediate(callback); + } else { + callbacks.push(callback); + // only trigger observer when it hasn't been triggered in + // the current turn of the event loop + if(callbacks.length === 1) { + div.setAttribute('a', attr = !attr); + } + } + }; + } + + util.nextTick = util.setImmediate; +})(); + +// check if running under Node.js +util.isNodejs = + typeof process !== 'undefined' && process.versions && process.versions.node; + + +// 'self' will also work in Web Workers (instance of WorkerGlobalScope) while +// it will point to `window` in the main thread. +// To remain compatible with older browsers, we fall back to 'window' if 'self' +// is not available. +util.globalScope = (function() { + if(util.isNodejs) { + return global; + } + + return typeof self === 'undefined' ? window : self; +})(); + +// define isArray +util.isArray = Array.isArray || function(x) { + return Object.prototype.toString.call(x) === '[object Array]'; +}; + +// define isArrayBuffer +util.isArrayBuffer = function(x) { + return typeof ArrayBuffer !== 'undefined' && x instanceof ArrayBuffer; +}; + +// define isArrayBufferView +util.isArrayBufferView = function(x) { + return x && util.isArrayBuffer(x.buffer) && x.byteLength !== undefined; +}; + +/** + * Ensure a bits param is 8, 16, 24, or 32. Used to validate input for + * algorithms where bit manipulation, JavaScript limitations, and/or algorithm + * design only allow for byte operations of a limited size. + * + * @param n number of bits. + * + * Throw Error if n invalid. + */ +function _checkBitsParam(n) { + if(!(n === 8 || n === 16 || n === 24 || n === 32)) { + throw new Error('Only 8, 16, 24, or 32 bits supported: ' + n); + } +} + +// TODO: set ByteBuffer to best available backing +util.ByteBuffer = ByteStringBuffer; + +/** Buffer w/BinaryString backing */ + +/** + * Constructor for a binary string backed byte buffer. + * + * @param [b] the bytes to wrap (either encoded as string, one byte per + * character, or as an ArrayBuffer or Typed Array). + */ +function ByteStringBuffer(b) { + // TODO: update to match DataBuffer API + + // the data in this buffer + this.data = ''; + // the pointer for reading from this buffer + this.read = 0; + + if(typeof b === 'string') { + this.data = b; + } else if(util.isArrayBuffer(b) || util.isArrayBufferView(b)) { + if(typeof Buffer !== 'undefined' && b instanceof Buffer) { + this.data = b.toString('binary'); + } else { + // convert native buffer to forge buffer + // FIXME: support native buffers internally instead + var arr = new Uint8Array(b); + try { + this.data = String.fromCharCode.apply(null, arr); + } catch(e) { + for(var i = 0; i < arr.length; ++i) { + this.putByte(arr[i]); + } + } + } + } else if(b instanceof ByteStringBuffer || + (typeof b === 'object' && typeof b.data === 'string' && + typeof b.read === 'number')) { + // copy existing buffer + this.data = b.data; + this.read = b.read; + } + + // used for v8 optimization + this._constructedStringLength = 0; +} +util.ByteStringBuffer = ByteStringBuffer; + +/* Note: This is an optimization for V8-based browsers. When V8 concatenates + a string, the strings are only joined logically using a "cons string" or + "constructed/concatenated string". These containers keep references to one + another and can result in very large memory usage. For example, if a 2MB + string is constructed by concatenating 4 bytes together at a time, the + memory usage will be ~44MB; so ~22x increase. The strings are only joined + together when an operation requiring their joining takes place, such as + substr(). This function is called when adding data to this buffer to ensure + these types of strings are periodically joined to reduce the memory + footprint. */ +var _MAX_CONSTRUCTED_STRING_LENGTH = 4096; +util.ByteStringBuffer.prototype._optimizeConstructedString = function(x) { + this._constructedStringLength += x; + if(this._constructedStringLength > _MAX_CONSTRUCTED_STRING_LENGTH) { + // this substr() should cause the constructed string to join + this.data.substr(0, 1); + this._constructedStringLength = 0; + } +}; + +/** + * Gets the number of bytes in this buffer. + * + * @return the number of bytes in this buffer. + */ +util.ByteStringBuffer.prototype.length = function() { + return this.data.length - this.read; +}; + +/** + * Gets whether or not this buffer is empty. + * + * @return true if this buffer is empty, false if not. + */ +util.ByteStringBuffer.prototype.isEmpty = function() { + return this.length() <= 0; +}; + +/** + * Puts a byte in this buffer. + * + * @param b the byte to put. + * + * @return this buffer. + */ +util.ByteStringBuffer.prototype.putByte = function(b) { + return this.putBytes(String.fromCharCode(b)); +}; + +/** + * Puts a byte in this buffer N times. + * + * @param b the byte to put. + * @param n the number of bytes of value b to put. + * + * @return this buffer. + */ +util.ByteStringBuffer.prototype.fillWithByte = function(b, n) { + b = String.fromCharCode(b); + var d = this.data; + while(n > 0) { + if(n & 1) { + d += b; + } + n >>>= 1; + if(n > 0) { + b += b; + } + } + this.data = d; + this._optimizeConstructedString(n); + return this; +}; + +/** + * Puts bytes in this buffer. + * + * @param bytes the bytes (as a binary encoded string) to put. + * + * @return this buffer. + */ +util.ByteStringBuffer.prototype.putBytes = function(bytes) { + this.data += bytes; + this._optimizeConstructedString(bytes.length); + return this; +}; + +/** + * Puts a UTF-16 encoded string into this buffer. + * + * @param str the string to put. + * + * @return this buffer. + */ +util.ByteStringBuffer.prototype.putString = function(str) { + return this.putBytes(util.encodeUtf8(str)); +}; + +/** + * Puts a 16-bit integer in this buffer in big-endian order. + * + * @param i the 16-bit integer. + * + * @return this buffer. + */ +util.ByteStringBuffer.prototype.putInt16 = function(i) { + return this.putBytes( + String.fromCharCode(i >> 8 & 0xFF) + + String.fromCharCode(i & 0xFF)); +}; + +/** + * Puts a 24-bit integer in this buffer in big-endian order. + * + * @param i the 24-bit integer. + * + * @return this buffer. + */ +util.ByteStringBuffer.prototype.putInt24 = function(i) { + return this.putBytes( + String.fromCharCode(i >> 16 & 0xFF) + + String.fromCharCode(i >> 8 & 0xFF) + + String.fromCharCode(i & 0xFF)); +}; + +/** + * Puts a 32-bit integer in this buffer in big-endian order. + * + * @param i the 32-bit integer. + * + * @return this buffer. + */ +util.ByteStringBuffer.prototype.putInt32 = function(i) { + return this.putBytes( + String.fromCharCode(i >> 24 & 0xFF) + + String.fromCharCode(i >> 16 & 0xFF) + + String.fromCharCode(i >> 8 & 0xFF) + + String.fromCharCode(i & 0xFF)); +}; + +/** + * Puts a 16-bit integer in this buffer in little-endian order. + * + * @param i the 16-bit integer. + * + * @return this buffer. + */ +util.ByteStringBuffer.prototype.putInt16Le = function(i) { + return this.putBytes( + String.fromCharCode(i & 0xFF) + + String.fromCharCode(i >> 8 & 0xFF)); +}; + +/** + * Puts a 24-bit integer in this buffer in little-endian order. + * + * @param i the 24-bit integer. + * + * @return this buffer. + */ +util.ByteStringBuffer.prototype.putInt24Le = function(i) { + return this.putBytes( + String.fromCharCode(i & 0xFF) + + String.fromCharCode(i >> 8 & 0xFF) + + String.fromCharCode(i >> 16 & 0xFF)); +}; + +/** + * Puts a 32-bit integer in this buffer in little-endian order. + * + * @param i the 32-bit integer. + * + * @return this buffer. + */ +util.ByteStringBuffer.prototype.putInt32Le = function(i) { + return this.putBytes( + String.fromCharCode(i & 0xFF) + + String.fromCharCode(i >> 8 & 0xFF) + + String.fromCharCode(i >> 16 & 0xFF) + + String.fromCharCode(i >> 24 & 0xFF)); +}; + +/** + * Puts an n-bit integer in this buffer in big-endian order. + * + * @param i the n-bit integer. + * @param n the number of bits in the integer (8, 16, 24, or 32). + * + * @return this buffer. + */ +util.ByteStringBuffer.prototype.putInt = function(i, n) { + _checkBitsParam(n); + var bytes = ''; + do { + n -= 8; + bytes += String.fromCharCode((i >> n) & 0xFF); + } while(n > 0); + return this.putBytes(bytes); +}; + +/** + * Puts a signed n-bit integer in this buffer in big-endian order. Two's + * complement representation is used. + * + * @param i the n-bit integer. + * @param n the number of bits in the integer (8, 16, 24, or 32). + * + * @return this buffer. + */ +util.ByteStringBuffer.prototype.putSignedInt = function(i, n) { + // putInt checks n + if(i < 0) { + i += 2 << (n - 1); + } + return this.putInt(i, n); +}; + +/** + * Puts the given buffer into this buffer. + * + * @param buffer the buffer to put into this one. + * + * @return this buffer. + */ +util.ByteStringBuffer.prototype.putBuffer = function(buffer) { + return this.putBytes(buffer.getBytes()); +}; + +/** + * Gets a byte from this buffer and advances the read pointer by 1. + * + * @return the byte. + */ +util.ByteStringBuffer.prototype.getByte = function() { + return this.data.charCodeAt(this.read++); +}; + +/** + * Gets a uint16 from this buffer in big-endian order and advances the read + * pointer by 2. + * + * @return the uint16. + */ +util.ByteStringBuffer.prototype.getInt16 = function() { + var rval = ( + this.data.charCodeAt(this.read) << 8 ^ + this.data.charCodeAt(this.read + 1)); + this.read += 2; + return rval; +}; + +/** + * Gets a uint24 from this buffer in big-endian order and advances the read + * pointer by 3. + * + * @return the uint24. + */ +util.ByteStringBuffer.prototype.getInt24 = function() { + var rval = ( + this.data.charCodeAt(this.read) << 16 ^ + this.data.charCodeAt(this.read + 1) << 8 ^ + this.data.charCodeAt(this.read + 2)); + this.read += 3; + return rval; +}; + +/** + * Gets a uint32 from this buffer in big-endian order and advances the read + * pointer by 4. + * + * @return the word. + */ +util.ByteStringBuffer.prototype.getInt32 = function() { + var rval = ( + this.data.charCodeAt(this.read) << 24 ^ + this.data.charCodeAt(this.read + 1) << 16 ^ + this.data.charCodeAt(this.read + 2) << 8 ^ + this.data.charCodeAt(this.read + 3)); + this.read += 4; + return rval; +}; + +/** + * Gets a uint16 from this buffer in little-endian order and advances the read + * pointer by 2. + * + * @return the uint16. + */ +util.ByteStringBuffer.prototype.getInt16Le = function() { + var rval = ( + this.data.charCodeAt(this.read) ^ + this.data.charCodeAt(this.read + 1) << 8); + this.read += 2; + return rval; +}; + +/** + * Gets a uint24 from this buffer in little-endian order and advances the read + * pointer by 3. + * + * @return the uint24. + */ +util.ByteStringBuffer.prototype.getInt24Le = function() { + var rval = ( + this.data.charCodeAt(this.read) ^ + this.data.charCodeAt(this.read + 1) << 8 ^ + this.data.charCodeAt(this.read + 2) << 16); + this.read += 3; + return rval; +}; + +/** + * Gets a uint32 from this buffer in little-endian order and advances the read + * pointer by 4. + * + * @return the word. + */ +util.ByteStringBuffer.prototype.getInt32Le = function() { + var rval = ( + this.data.charCodeAt(this.read) ^ + this.data.charCodeAt(this.read + 1) << 8 ^ + this.data.charCodeAt(this.read + 2) << 16 ^ + this.data.charCodeAt(this.read + 3) << 24); + this.read += 4; + return rval; +}; + +/** + * Gets an n-bit integer from this buffer in big-endian order and advances the + * read pointer by ceil(n/8). + * + * @param n the number of bits in the integer (8, 16, 24, or 32). + * + * @return the integer. + */ +util.ByteStringBuffer.prototype.getInt = function(n) { + _checkBitsParam(n); + var rval = 0; + do { + // TODO: Use (rval * 0x100) if adding support for 33 to 53 bits. + rval = (rval << 8) + this.data.charCodeAt(this.read++); + n -= 8; + } while(n > 0); + return rval; +}; + +/** + * Gets a signed n-bit integer from this buffer in big-endian order, using + * two's complement, and advances the read pointer by n/8. + * + * @param n the number of bits in the integer (8, 16, 24, or 32). + * + * @return the integer. + */ +util.ByteStringBuffer.prototype.getSignedInt = function(n) { + // getInt checks n + var x = this.getInt(n); + var max = 2 << (n - 2); + if(x >= max) { + x -= max << 1; + } + return x; +}; + +/** + * Reads bytes out as a binary encoded string and clears them from the + * buffer. Note that the resulting string is binary encoded (in node.js this + * encoding is referred to as `binary`, it is *not* `utf8`). + * + * @param count the number of bytes to read, undefined or null for all. + * + * @return a binary encoded string of bytes. + */ +util.ByteStringBuffer.prototype.getBytes = function(count) { + var rval; + if(count) { + // read count bytes + count = Math.min(this.length(), count); + rval = this.data.slice(this.read, this.read + count); + this.read += count; + } else if(count === 0) { + rval = ''; + } else { + // read all bytes, optimize to only copy when needed + rval = (this.read === 0) ? this.data : this.data.slice(this.read); + this.clear(); + } + return rval; +}; + +/** + * Gets a binary encoded string of the bytes from this buffer without + * modifying the read pointer. + * + * @param count the number of bytes to get, omit to get all. + * + * @return a string full of binary encoded characters. + */ +util.ByteStringBuffer.prototype.bytes = function(count) { + return (typeof(count) === 'undefined' ? + this.data.slice(this.read) : + this.data.slice(this.read, this.read + count)); +}; + +/** + * Gets a byte at the given index without modifying the read pointer. + * + * @param i the byte index. + * + * @return the byte. + */ +util.ByteStringBuffer.prototype.at = function(i) { + return this.data.charCodeAt(this.read + i); +}; + +/** + * Puts a byte at the given index without modifying the read pointer. + * + * @param i the byte index. + * @param b the byte to put. + * + * @return this buffer. + */ +util.ByteStringBuffer.prototype.setAt = function(i, b) { + this.data = this.data.substr(0, this.read + i) + + String.fromCharCode(b) + + this.data.substr(this.read + i + 1); + return this; +}; + +/** + * Gets the last byte without modifying the read pointer. + * + * @return the last byte. + */ +util.ByteStringBuffer.prototype.last = function() { + return this.data.charCodeAt(this.data.length - 1); +}; + +/** + * Creates a copy of this buffer. + * + * @return the copy. + */ +util.ByteStringBuffer.prototype.copy = function() { + var c = util.createBuffer(this.data); + c.read = this.read; + return c; +}; + +/** + * Compacts this buffer. + * + * @return this buffer. + */ +util.ByteStringBuffer.prototype.compact = function() { + if(this.read > 0) { + this.data = this.data.slice(this.read); + this.read = 0; + } + return this; +}; + +/** + * Clears this buffer. + * + * @return this buffer. + */ +util.ByteStringBuffer.prototype.clear = function() { + this.data = ''; + this.read = 0; + return this; +}; + +/** + * Shortens this buffer by triming bytes off of the end of this buffer. + * + * @param count the number of bytes to trim off. + * + * @return this buffer. + */ +util.ByteStringBuffer.prototype.truncate = function(count) { + var len = Math.max(0, this.length() - count); + this.data = this.data.substr(this.read, len); + this.read = 0; + return this; +}; + +/** + * Converts this buffer to a hexadecimal string. + * + * @return a hexadecimal string. + */ +util.ByteStringBuffer.prototype.toHex = function() { + var rval = ''; + for(var i = this.read; i < this.data.length; ++i) { + var b = this.data.charCodeAt(i); + if(b < 16) { + rval += '0'; + } + rval += b.toString(16); + } + return rval; +}; + +/** + * Converts this buffer to a UTF-16 string (standard JavaScript string). + * + * @return a UTF-16 string. + */ +util.ByteStringBuffer.prototype.toString = function() { + return util.decodeUtf8(this.bytes()); +}; + +/** End Buffer w/BinaryString backing */ + +/** Buffer w/UInt8Array backing */ + +/** + * FIXME: Experimental. Do not use yet. + * + * Constructor for an ArrayBuffer-backed byte buffer. + * + * The buffer may be constructed from a string, an ArrayBuffer, DataView, or a + * TypedArray. + * + * If a string is given, its encoding should be provided as an option, + * otherwise it will default to 'binary'. A 'binary' string is encoded such + * that each character is one byte in length and size. + * + * If an ArrayBuffer, DataView, or TypedArray is given, it will be used + * *directly* without any copying. Note that, if a write to the buffer requires + * more space, the buffer will allocate a new backing ArrayBuffer to + * accommodate. The starting read and write offsets for the buffer may be + * given as options. + * + * @param [b] the initial bytes for this buffer. + * @param options the options to use: + * [readOffset] the starting read offset to use (default: 0). + * [writeOffset] the starting write offset to use (default: the + * length of the first parameter). + * [growSize] the minimum amount, in bytes, to grow the buffer by to + * accommodate writes (default: 1024). + * [encoding] the encoding ('binary', 'utf8', 'utf16', 'hex') for the + * first parameter, if it is a string (default: 'binary'). + */ +function DataBuffer(b, options) { + // default options + options = options || {}; + + // pointers for read from/write to buffer + this.read = options.readOffset || 0; + this.growSize = options.growSize || 1024; + + var isArrayBuffer = util.isArrayBuffer(b); + var isArrayBufferView = util.isArrayBufferView(b); + if(isArrayBuffer || isArrayBufferView) { + // use ArrayBuffer directly + if(isArrayBuffer) { + this.data = new DataView(b); + } else { + // TODO: adjust read/write offset based on the type of view + // or specify that this must be done in the options ... that the + // offsets are byte-based + this.data = new DataView(b.buffer, b.byteOffset, b.byteLength); + } + this.write = ('writeOffset' in options ? + options.writeOffset : this.data.byteLength); + return; + } + + // initialize to empty array buffer and add any given bytes using putBytes + this.data = new DataView(new ArrayBuffer(0)); + this.write = 0; + + if(b !== null && b !== undefined) { + this.putBytes(b); + } + + if('writeOffset' in options) { + this.write = options.writeOffset; + } +} +util.DataBuffer = DataBuffer; + +/** + * Gets the number of bytes in this buffer. + * + * @return the number of bytes in this buffer. + */ +util.DataBuffer.prototype.length = function() { + return this.write - this.read; +}; + +/** + * Gets whether or not this buffer is empty. + * + * @return true if this buffer is empty, false if not. + */ +util.DataBuffer.prototype.isEmpty = function() { + return this.length() <= 0; +}; + +/** + * Ensures this buffer has enough empty space to accommodate the given number + * of bytes. An optional parameter may be given that indicates a minimum + * amount to grow the buffer if necessary. If the parameter is not given, + * the buffer will be grown by some previously-specified default amount + * or heuristic. + * + * @param amount the number of bytes to accommodate. + * @param [growSize] the minimum amount, in bytes, to grow the buffer by if + * necessary. + */ +util.DataBuffer.prototype.accommodate = function(amount, growSize) { + if(this.length() >= amount) { + return this; + } + growSize = Math.max(growSize || this.growSize, amount); + + // grow buffer + var src = new Uint8Array( + this.data.buffer, this.data.byteOffset, this.data.byteLength); + var dst = new Uint8Array(this.length() + growSize); + dst.set(src); + this.data = new DataView(dst.buffer); + + return this; +}; + +/** + * Puts a byte in this buffer. + * + * @param b the byte to put. + * + * @return this buffer. + */ +util.DataBuffer.prototype.putByte = function(b) { + this.accommodate(1); + this.data.setUint8(this.write++, b); + return this; +}; + +/** + * Puts a byte in this buffer N times. + * + * @param b the byte to put. + * @param n the number of bytes of value b to put. + * + * @return this buffer. + */ +util.DataBuffer.prototype.fillWithByte = function(b, n) { + this.accommodate(n); + for(var i = 0; i < n; ++i) { + this.data.setUint8(b); + } + return this; +}; + +/** + * Puts bytes in this buffer. The bytes may be given as a string, an + * ArrayBuffer, a DataView, or a TypedArray. + * + * @param bytes the bytes to put. + * @param [encoding] the encoding for the first parameter ('binary', 'utf8', + * 'utf16', 'hex'), if it is a string (default: 'binary'). + * + * @return this buffer. + */ +util.DataBuffer.prototype.putBytes = function(bytes, encoding) { + if(util.isArrayBufferView(bytes)) { + var src = new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength); + var len = src.byteLength - src.byteOffset; + this.accommodate(len); + var dst = new Uint8Array(this.data.buffer, this.write); + dst.set(src); + this.write += len; + return this; + } + + if(util.isArrayBuffer(bytes)) { + var src = new Uint8Array(bytes); + this.accommodate(src.byteLength); + var dst = new Uint8Array(this.data.buffer); + dst.set(src, this.write); + this.write += src.byteLength; + return this; + } + + // bytes is a util.DataBuffer or equivalent + if(bytes instanceof util.DataBuffer || + (typeof bytes === 'object' && + typeof bytes.read === 'number' && typeof bytes.write === 'number' && + util.isArrayBufferView(bytes.data))) { + var src = new Uint8Array(bytes.data.byteLength, bytes.read, bytes.length()); + this.accommodate(src.byteLength); + var dst = new Uint8Array(bytes.data.byteLength, this.write); + dst.set(src); + this.write += src.byteLength; + return this; + } + + if(bytes instanceof util.ByteStringBuffer) { + // copy binary string and process as the same as a string parameter below + bytes = bytes.data; + encoding = 'binary'; + } + + // string conversion + encoding = encoding || 'binary'; + if(typeof bytes === 'string') { + var view; + + // decode from string + if(encoding === 'hex') { + this.accommodate(Math.ceil(bytes.length / 2)); + view = new Uint8Array(this.data.buffer, this.write); + this.write += util.binary.hex.decode(bytes, view, this.write); + return this; + } + if(encoding === 'base64') { + this.accommodate(Math.ceil(bytes.length / 4) * 3); + view = new Uint8Array(this.data.buffer, this.write); + this.write += util.binary.base64.decode(bytes, view, this.write); + return this; + } + + // encode text as UTF-8 bytes + if(encoding === 'utf8') { + // encode as UTF-8 then decode string as raw binary + bytes = util.encodeUtf8(bytes); + encoding = 'binary'; + } + + // decode string as raw binary + if(encoding === 'binary' || encoding === 'raw') { + // one byte per character + this.accommodate(bytes.length); + view = new Uint8Array(this.data.buffer, this.write); + this.write += util.binary.raw.decode(view); + return this; + } + + // encode text as UTF-16 bytes + if(encoding === 'utf16') { + // two bytes per character + this.accommodate(bytes.length * 2); + view = new Uint16Array(this.data.buffer, this.write); + this.write += util.text.utf16.encode(view); + return this; + } + + throw new Error('Invalid encoding: ' + encoding); + } + + throw Error('Invalid parameter: ' + bytes); +}; + +/** + * Puts the given buffer into this buffer. + * + * @param buffer the buffer to put into this one. + * + * @return this buffer. + */ +util.DataBuffer.prototype.putBuffer = function(buffer) { + this.putBytes(buffer); + buffer.clear(); + return this; +}; + +/** + * Puts a string into this buffer. + * + * @param str the string to put. + * @param [encoding] the encoding for the string (default: 'utf16'). + * + * @return this buffer. + */ +util.DataBuffer.prototype.putString = function(str) { + return this.putBytes(str, 'utf16'); +}; + +/** + * Puts a 16-bit integer in this buffer in big-endian order. + * + * @param i the 16-bit integer. + * + * @return this buffer. + */ +util.DataBuffer.prototype.putInt16 = function(i) { + this.accommodate(2); + this.data.setInt16(this.write, i); + this.write += 2; + return this; +}; + +/** + * Puts a 24-bit integer in this buffer in big-endian order. + * + * @param i the 24-bit integer. + * + * @return this buffer. + */ +util.DataBuffer.prototype.putInt24 = function(i) { + this.accommodate(3); + this.data.setInt16(this.write, i >> 8 & 0xFFFF); + this.data.setInt8(this.write, i >> 16 & 0xFF); + this.write += 3; + return this; +}; + +/** + * Puts a 32-bit integer in this buffer in big-endian order. + * + * @param i the 32-bit integer. + * + * @return this buffer. + */ +util.DataBuffer.prototype.putInt32 = function(i) { + this.accommodate(4); + this.data.setInt32(this.write, i); + this.write += 4; + return this; +}; + +/** + * Puts a 16-bit integer in this buffer in little-endian order. + * + * @param i the 16-bit integer. + * + * @return this buffer. + */ +util.DataBuffer.prototype.putInt16Le = function(i) { + this.accommodate(2); + this.data.setInt16(this.write, i, true); + this.write += 2; + return this; +}; + +/** + * Puts a 24-bit integer in this buffer in little-endian order. + * + * @param i the 24-bit integer. + * + * @return this buffer. + */ +util.DataBuffer.prototype.putInt24Le = function(i) { + this.accommodate(3); + this.data.setInt8(this.write, i >> 16 & 0xFF); + this.data.setInt16(this.write, i >> 8 & 0xFFFF, true); + this.write += 3; + return this; +}; + +/** + * Puts a 32-bit integer in this buffer in little-endian order. + * + * @param i the 32-bit integer. + * + * @return this buffer. + */ +util.DataBuffer.prototype.putInt32Le = function(i) { + this.accommodate(4); + this.data.setInt32(this.write, i, true); + this.write += 4; + return this; +}; + +/** + * Puts an n-bit integer in this buffer in big-endian order. + * + * @param i the n-bit integer. + * @param n the number of bits in the integer (8, 16, 24, or 32). + * + * @return this buffer. + */ +util.DataBuffer.prototype.putInt = function(i, n) { + _checkBitsParam(n); + this.accommodate(n / 8); + do { + n -= 8; + this.data.setInt8(this.write++, (i >> n) & 0xFF); + } while(n > 0); + return this; +}; + +/** + * Puts a signed n-bit integer in this buffer in big-endian order. Two's + * complement representation is used. + * + * @param i the n-bit integer. + * @param n the number of bits in the integer. + * + * @return this buffer. + */ +util.DataBuffer.prototype.putSignedInt = function(i, n) { + _checkBitsParam(n); + this.accommodate(n / 8); + if(i < 0) { + i += 2 << (n - 1); + } + return this.putInt(i, n); +}; + +/** + * Gets a byte from this buffer and advances the read pointer by 1. + * + * @return the byte. + */ +util.DataBuffer.prototype.getByte = function() { + return this.data.getInt8(this.read++); +}; + +/** + * Gets a uint16 from this buffer in big-endian order and advances the read + * pointer by 2. + * + * @return the uint16. + */ +util.DataBuffer.prototype.getInt16 = function() { + var rval = this.data.getInt16(this.read); + this.read += 2; + return rval; +}; + +/** + * Gets a uint24 from this buffer in big-endian order and advances the read + * pointer by 3. + * + * @return the uint24. + */ +util.DataBuffer.prototype.getInt24 = function() { + var rval = ( + this.data.getInt16(this.read) << 8 ^ + this.data.getInt8(this.read + 2)); + this.read += 3; + return rval; +}; + +/** + * Gets a uint32 from this buffer in big-endian order and advances the read + * pointer by 4. + * + * @return the word. + */ +util.DataBuffer.prototype.getInt32 = function() { + var rval = this.data.getInt32(this.read); + this.read += 4; + return rval; +}; + +/** + * Gets a uint16 from this buffer in little-endian order and advances the read + * pointer by 2. + * + * @return the uint16. + */ +util.DataBuffer.prototype.getInt16Le = function() { + var rval = this.data.getInt16(this.read, true); + this.read += 2; + return rval; +}; + +/** + * Gets a uint24 from this buffer in little-endian order and advances the read + * pointer by 3. + * + * @return the uint24. + */ +util.DataBuffer.prototype.getInt24Le = function() { + var rval = ( + this.data.getInt8(this.read) ^ + this.data.getInt16(this.read + 1, true) << 8); + this.read += 3; + return rval; +}; + +/** + * Gets a uint32 from this buffer in little-endian order and advances the read + * pointer by 4. + * + * @return the word. + */ +util.DataBuffer.prototype.getInt32Le = function() { + var rval = this.data.getInt32(this.read, true); + this.read += 4; + return rval; +}; + +/** + * Gets an n-bit integer from this buffer in big-endian order and advances the + * read pointer by n/8. + * + * @param n the number of bits in the integer (8, 16, 24, or 32). + * + * @return the integer. + */ +util.DataBuffer.prototype.getInt = function(n) { + _checkBitsParam(n); + var rval = 0; + do { + // TODO: Use (rval * 0x100) if adding support for 33 to 53 bits. + rval = (rval << 8) + this.data.getInt8(this.read++); + n -= 8; + } while(n > 0); + return rval; +}; + +/** + * Gets a signed n-bit integer from this buffer in big-endian order, using + * two's complement, and advances the read pointer by n/8. + * + * @param n the number of bits in the integer (8, 16, 24, or 32). + * + * @return the integer. + */ +util.DataBuffer.prototype.getSignedInt = function(n) { + // getInt checks n + var x = this.getInt(n); + var max = 2 << (n - 2); + if(x >= max) { + x -= max << 1; + } + return x; +}; + +/** + * Reads bytes out as a binary encoded string and clears them from the + * buffer. + * + * @param count the number of bytes to read, undefined or null for all. + * + * @return a binary encoded string of bytes. + */ +util.DataBuffer.prototype.getBytes = function(count) { + // TODO: deprecate this method, it is poorly named and + // this.toString('binary') replaces it + // add a toTypedArray()/toArrayBuffer() function + var rval; + if(count) { + // read count bytes + count = Math.min(this.length(), count); + rval = this.data.slice(this.read, this.read + count); + this.read += count; + } else if(count === 0) { + rval = ''; + } else { + // read all bytes, optimize to only copy when needed + rval = (this.read === 0) ? this.data : this.data.slice(this.read); + this.clear(); + } + return rval; +}; + +/** + * Gets a binary encoded string of the bytes from this buffer without + * modifying the read pointer. + * + * @param count the number of bytes to get, omit to get all. + * + * @return a string full of binary encoded characters. + */ +util.DataBuffer.prototype.bytes = function(count) { + // TODO: deprecate this method, it is poorly named, add "getString()" + return (typeof(count) === 'undefined' ? + this.data.slice(this.read) : + this.data.slice(this.read, this.read + count)); +}; + +/** + * Gets a byte at the given index without modifying the read pointer. + * + * @param i the byte index. + * + * @return the byte. + */ +util.DataBuffer.prototype.at = function(i) { + return this.data.getUint8(this.read + i); +}; + +/** + * Puts a byte at the given index without modifying the read pointer. + * + * @param i the byte index. + * @param b the byte to put. + * + * @return this buffer. + */ +util.DataBuffer.prototype.setAt = function(i, b) { + this.data.setUint8(i, b); + return this; +}; + +/** + * Gets the last byte without modifying the read pointer. + * + * @return the last byte. + */ +util.DataBuffer.prototype.last = function() { + return this.data.getUint8(this.write - 1); +}; + +/** + * Creates a copy of this buffer. + * + * @return the copy. + */ +util.DataBuffer.prototype.copy = function() { + return new util.DataBuffer(this); +}; + +/** + * Compacts this buffer. + * + * @return this buffer. + */ +util.DataBuffer.prototype.compact = function() { + if(this.read > 0) { + var src = new Uint8Array(this.data.buffer, this.read); + var dst = new Uint8Array(src.byteLength); + dst.set(src); + this.data = new DataView(dst); + this.write -= this.read; + this.read = 0; + } + return this; +}; + +/** + * Clears this buffer. + * + * @return this buffer. + */ +util.DataBuffer.prototype.clear = function() { + this.data = new DataView(new ArrayBuffer(0)); + this.read = this.write = 0; + return this; +}; + +/** + * Shortens this buffer by triming bytes off of the end of this buffer. + * + * @param count the number of bytes to trim off. + * + * @return this buffer. + */ +util.DataBuffer.prototype.truncate = function(count) { + this.write = Math.max(0, this.length() - count); + this.read = Math.min(this.read, this.write); + return this; +}; + +/** + * Converts this buffer to a hexadecimal string. + * + * @return a hexadecimal string. + */ +util.DataBuffer.prototype.toHex = function() { + var rval = ''; + for(var i = this.read; i < this.data.byteLength; ++i) { + var b = this.data.getUint8(i); + if(b < 16) { + rval += '0'; + } + rval += b.toString(16); + } + return rval; +}; + +/** + * Converts this buffer to a string, using the given encoding. If no + * encoding is given, 'utf8' (UTF-8) is used. + * + * @param [encoding] the encoding to use: 'binary', 'utf8', 'utf16', 'hex', + * 'base64' (default: 'utf8'). + * + * @return a string representation of the bytes in this buffer. + */ +util.DataBuffer.prototype.toString = function(encoding) { + var view = new Uint8Array(this.data, this.read, this.length()); + encoding = encoding || 'utf8'; + + // encode to string + if(encoding === 'binary' || encoding === 'raw') { + return util.binary.raw.encode(view); + } + if(encoding === 'hex') { + return util.binary.hex.encode(view); + } + if(encoding === 'base64') { + return util.binary.base64.encode(view); + } + + // decode to text + if(encoding === 'utf8') { + return util.text.utf8.decode(view); + } + if(encoding === 'utf16') { + return util.text.utf16.decode(view); + } + + throw new Error('Invalid encoding: ' + encoding); +}; + +/** End Buffer w/UInt8Array backing */ + +/** + * Creates a buffer that stores bytes. A value may be given to populate the + * buffer with data. This value can either be string of encoded bytes or a + * regular string of characters. When passing a string of binary encoded + * bytes, the encoding `raw` should be given. This is also the default. When + * passing a string of characters, the encoding `utf8` should be given. + * + * @param [input] a string with encoded bytes to store in the buffer. + * @param [encoding] (default: 'raw', other: 'utf8'). + */ +util.createBuffer = function(input, encoding) { + // TODO: deprecate, use new ByteBuffer() instead + encoding = encoding || 'raw'; + if(input !== undefined && encoding === 'utf8') { + input = util.encodeUtf8(input); + } + return new util.ByteBuffer(input); +}; + +/** + * Fills a string with a particular value. If you want the string to be a byte + * string, pass in String.fromCharCode(theByte). + * + * @param c the character to fill the string with, use String.fromCharCode + * to fill the string with a byte value. + * @param n the number of characters of value c to fill with. + * + * @return the filled string. + */ +util.fillString = function(c, n) { + var s = ''; + while(n > 0) { + if(n & 1) { + s += c; + } + n >>>= 1; + if(n > 0) { + c += c; + } + } + return s; +}; + +/** + * Performs a per byte XOR between two byte strings and returns the result as a + * string of bytes. + * + * @param s1 first string of bytes. + * @param s2 second string of bytes. + * @param n the number of bytes to XOR. + * + * @return the XOR'd result. + */ +util.xorBytes = function(s1, s2, n) { + var s3 = ''; + var b = ''; + var t = ''; + var i = 0; + var c = 0; + for(; n > 0; --n, ++i) { + b = s1.charCodeAt(i) ^ s2.charCodeAt(i); + if(c >= 10) { + s3 += t; + t = ''; + c = 0; + } + t += String.fromCharCode(b); + ++c; + } + s3 += t; + return s3; +}; + +/** + * Converts a hex string into a 'binary' encoded string of bytes. + * + * @param hex the hexadecimal string to convert. + * + * @return the binary-encoded string of bytes. + */ +util.hexToBytes = function(hex) { + // TODO: deprecate: "Deprecated. Use util.binary.hex.decode instead." + var rval = ''; + var i = 0; + if(hex.length & 1 == 1) { + // odd number of characters, convert first character alone + i = 1; + rval += String.fromCharCode(parseInt(hex[0], 16)); + } + // convert 2 characters (1 byte) at a time + for(; i < hex.length; i += 2) { + rval += String.fromCharCode(parseInt(hex.substr(i, 2), 16)); + } + return rval; +}; + +/** + * Converts a 'binary' encoded string of bytes to hex. + * + * @param bytes the byte string to convert. + * + * @return the string of hexadecimal characters. + */ +util.bytesToHex = function(bytes) { + // TODO: deprecate: "Deprecated. Use util.binary.hex.encode instead." + return util.createBuffer(bytes).toHex(); +}; + +/** + * Converts an 32-bit integer to 4-big-endian byte string. + * + * @param i the integer. + * + * @return the byte string. + */ +util.int32ToBytes = function(i) { + return ( + String.fromCharCode(i >> 24 & 0xFF) + + String.fromCharCode(i >> 16 & 0xFF) + + String.fromCharCode(i >> 8 & 0xFF) + + String.fromCharCode(i & 0xFF)); +}; + +// base64 characters, reverse mapping +var _base64 = + 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; +var _base64Idx = [ +/*43 -43 = 0*/ +/*'+', 1, 2, 3,'/' */ + 62, -1, -1, -1, 63, + +/*'0','1','2','3','4','5','6','7','8','9' */ + 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, + +/*15, 16, 17,'=', 19, 20, 21 */ + -1, -1, -1, 64, -1, -1, -1, + +/*65 - 43 = 22*/ +/*'A','B','C','D','E','F','G','H','I','J','K','L','M', */ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, + +/*'N','O','P','Q','R','S','T','U','V','W','X','Y','Z' */ + 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, + +/*91 - 43 = 48 */ +/*48, 49, 50, 51, 52, 53 */ + -1, -1, -1, -1, -1, -1, + +/*97 - 43 = 54*/ +/*'a','b','c','d','e','f','g','h','i','j','k','l','m' */ + 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, + +/*'n','o','p','q','r','s','t','u','v','w','x','y','z' */ + 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51 +]; + +// base58 characters (Bitcoin alphabet) +var _base58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'; + +/** + * Base64 encodes a 'binary' encoded string of bytes. + * + * @param input the binary encoded string of bytes to base64-encode. + * @param maxline the maximum number of encoded characters per line to use, + * defaults to none. + * + * @return the base64-encoded output. + */ +util.encode64 = function(input, maxline) { + // TODO: deprecate: "Deprecated. Use util.binary.base64.encode instead." + var line = ''; + var output = ''; + var chr1, chr2, chr3; + var i = 0; + while(i < input.length) { + chr1 = input.charCodeAt(i++); + chr2 = input.charCodeAt(i++); + chr3 = input.charCodeAt(i++); + + // encode 4 character group + line += _base64.charAt(chr1 >> 2); + line += _base64.charAt(((chr1 & 3) << 4) | (chr2 >> 4)); + if(isNaN(chr2)) { + line += '=='; + } else { + line += _base64.charAt(((chr2 & 15) << 2) | (chr3 >> 6)); + line += isNaN(chr3) ? '=' : _base64.charAt(chr3 & 63); + } + + if(maxline && line.length > maxline) { + output += line.substr(0, maxline) + '\r\n'; + line = line.substr(maxline); + } + } + output += line; + return output; +}; + +/** + * Base64 decodes a string into a 'binary' encoded string of bytes. + * + * @param input the base64-encoded input. + * + * @return the binary encoded string. + */ +util.decode64 = function(input) { + // TODO: deprecate: "Deprecated. Use util.binary.base64.decode instead." + + // remove all non-base64 characters + input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ''); + + var output = ''; + var enc1, enc2, enc3, enc4; + var i = 0; + + while(i < input.length) { + enc1 = _base64Idx[input.charCodeAt(i++) - 43]; + enc2 = _base64Idx[input.charCodeAt(i++) - 43]; + enc3 = _base64Idx[input.charCodeAt(i++) - 43]; + enc4 = _base64Idx[input.charCodeAt(i++) - 43]; + + output += String.fromCharCode((enc1 << 2) | (enc2 >> 4)); + if(enc3 !== 64) { + // decoded at least 2 bytes + output += String.fromCharCode(((enc2 & 15) << 4) | (enc3 >> 2)); + if(enc4 !== 64) { + // decoded 3 bytes + output += String.fromCharCode(((enc3 & 3) << 6) | enc4); + } + } + } + + return output; +}; + +/** + * Encodes the given string of characters (a standard JavaScript + * string) as a binary encoded string where the bytes represent + * a UTF-8 encoded string of characters. Non-ASCII characters will be + * encoded as multiple bytes according to UTF-8. + * + * @param str a standard string of characters to encode. + * + * @return the binary encoded string. + */ +util.encodeUtf8 = function(str) { + return unescape(encodeURIComponent(str)); +}; + +/** + * Decodes a binary encoded string that contains bytes that + * represent a UTF-8 encoded string of characters -- into a + * string of characters (a standard JavaScript string). + * + * @param str the binary encoded string to decode. + * + * @return the resulting standard string of characters. + */ +util.decodeUtf8 = function(str) { + return decodeURIComponent(escape(str)); +}; + +// binary encoding/decoding tools +// FIXME: Experimental. Do not use yet. +util.binary = { + raw: {}, + hex: {}, + base64: {}, + base58: {}, + baseN : { + encode: baseN.encode, + decode: baseN.decode + } +}; + +/** + * Encodes a Uint8Array as a binary-encoded string. This encoding uses + * a value between 0 and 255 for each character. + * + * @param bytes the Uint8Array to encode. + * + * @return the binary-encoded string. + */ +util.binary.raw.encode = function(bytes) { + return String.fromCharCode.apply(null, bytes); +}; + +/** + * Decodes a binary-encoded string to a Uint8Array. This encoding uses + * a value between 0 and 255 for each character. + * + * @param str the binary-encoded string to decode. + * @param [output] an optional Uint8Array to write the output to; if it + * is too small, an exception will be thrown. + * @param [offset] the start offset for writing to the output (default: 0). + * + * @return the Uint8Array or the number of bytes written if output was given. + */ +util.binary.raw.decode = function(str, output, offset) { + var out = output; + if(!out) { + out = new Uint8Array(str.length); + } + offset = offset || 0; + var j = offset; + for(var i = 0; i < str.length; ++i) { + out[j++] = str.charCodeAt(i); + } + return output ? (j - offset) : out; +}; + +/** + * Encodes a 'binary' string, ArrayBuffer, DataView, TypedArray, or + * ByteBuffer as a string of hexadecimal characters. + * + * @param bytes the bytes to convert. + * + * @return the string of hexadecimal characters. + */ +util.binary.hex.encode = util.bytesToHex; + +/** + * Decodes a hex-encoded string to a Uint8Array. + * + * @param hex the hexadecimal string to convert. + * @param [output] an optional Uint8Array to write the output to; if it + * is too small, an exception will be thrown. + * @param [offset] the start offset for writing to the output (default: 0). + * + * @return the Uint8Array or the number of bytes written if output was given. + */ +util.binary.hex.decode = function(hex, output, offset) { + var out = output; + if(!out) { + out = new Uint8Array(Math.ceil(hex.length / 2)); + } + offset = offset || 0; + var i = 0, j = offset; + if(hex.length & 1) { + // odd number of characters, convert first character alone + i = 1; + out[j++] = parseInt(hex[0], 16); + } + // convert 2 characters (1 byte) at a time + for(; i < hex.length; i += 2) { + out[j++] = parseInt(hex.substr(i, 2), 16); + } + return output ? (j - offset) : out; +}; + +/** + * Base64-encodes a Uint8Array. + * + * @param input the Uint8Array to encode. + * @param maxline the maximum number of encoded characters per line to use, + * defaults to none. + * + * @return the base64-encoded output string. + */ +util.binary.base64.encode = function(input, maxline) { + var line = ''; + var output = ''; + var chr1, chr2, chr3; + var i = 0; + while(i < input.byteLength) { + chr1 = input[i++]; + chr2 = input[i++]; + chr3 = input[i++]; + + // encode 4 character group + line += _base64.charAt(chr1 >> 2); + line += _base64.charAt(((chr1 & 3) << 4) | (chr2 >> 4)); + if(isNaN(chr2)) { + line += '=='; + } else { + line += _base64.charAt(((chr2 & 15) << 2) | (chr3 >> 6)); + line += isNaN(chr3) ? '=' : _base64.charAt(chr3 & 63); + } + + if(maxline && line.length > maxline) { + output += line.substr(0, maxline) + '\r\n'; + line = line.substr(maxline); + } + } + output += line; + return output; +}; + +/** + * Decodes a base64-encoded string to a Uint8Array. + * + * @param input the base64-encoded input string. + * @param [output] an optional Uint8Array to write the output to; if it + * is too small, an exception will be thrown. + * @param [offset] the start offset for writing to the output (default: 0). + * + * @return the Uint8Array or the number of bytes written if output was given. + */ +util.binary.base64.decode = function(input, output, offset) { + var out = output; + if(!out) { + out = new Uint8Array(Math.ceil(input.length / 4) * 3); + } + + // remove all non-base64 characters + input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ''); + + offset = offset || 0; + var enc1, enc2, enc3, enc4; + var i = 0, j = offset; + + while(i < input.length) { + enc1 = _base64Idx[input.charCodeAt(i++) - 43]; + enc2 = _base64Idx[input.charCodeAt(i++) - 43]; + enc3 = _base64Idx[input.charCodeAt(i++) - 43]; + enc4 = _base64Idx[input.charCodeAt(i++) - 43]; + + out[j++] = (enc1 << 2) | (enc2 >> 4); + if(enc3 !== 64) { + // decoded at least 2 bytes + out[j++] = ((enc2 & 15) << 4) | (enc3 >> 2); + if(enc4 !== 64) { + // decoded 3 bytes + out[j++] = ((enc3 & 3) << 6) | enc4; + } + } + } + + // make sure result is the exact decoded length + return output ? (j - offset) : out.subarray(0, j); +}; + +// add support for base58 encoding/decoding with Bitcoin alphabet +util.binary.base58.encode = function(input, maxline) { + return util.binary.baseN.encode(input, _base58, maxline); +}; +util.binary.base58.decode = function(input, maxline) { + return util.binary.baseN.decode(input, _base58, maxline); +}; + +// text encoding/decoding tools +// FIXME: Experimental. Do not use yet. +util.text = { + utf8: {}, + utf16: {} +}; + +/** + * Encodes the given string as UTF-8 in a Uint8Array. + * + * @param str the string to encode. + * @param [output] an optional Uint8Array to write the output to; if it + * is too small, an exception will be thrown. + * @param [offset] the start offset for writing to the output (default: 0). + * + * @return the Uint8Array or the number of bytes written if output was given. + */ +util.text.utf8.encode = function(str, output, offset) { + str = util.encodeUtf8(str); + var out = output; + if(!out) { + out = new Uint8Array(str.length); + } + offset = offset || 0; + var j = offset; + for(var i = 0; i < str.length; ++i) { + out[j++] = str.charCodeAt(i); + } + return output ? (j - offset) : out; +}; + +/** + * Decodes the UTF-8 contents from a Uint8Array. + * + * @param bytes the Uint8Array to decode. + * + * @return the resulting string. + */ +util.text.utf8.decode = function(bytes) { + return util.decodeUtf8(String.fromCharCode.apply(null, bytes)); +}; + +/** + * Encodes the given string as UTF-16 in a Uint8Array. + * + * @param str the string to encode. + * @param [output] an optional Uint8Array to write the output to; if it + * is too small, an exception will be thrown. + * @param [offset] the start offset for writing to the output (default: 0). + * + * @return the Uint8Array or the number of bytes written if output was given. + */ +util.text.utf16.encode = function(str, output, offset) { + var out = output; + if(!out) { + out = new Uint8Array(str.length * 2); + } + var view = new Uint16Array(out.buffer); + offset = offset || 0; + var j = offset; + var k = offset; + for(var i = 0; i < str.length; ++i) { + view[k++] = str.charCodeAt(i); + j += 2; + } + return output ? (j - offset) : out; +}; + +/** + * Decodes the UTF-16 contents from a Uint8Array. + * + * @param bytes the Uint8Array to decode. + * + * @return the resulting string. + */ +util.text.utf16.decode = function(bytes) { + return String.fromCharCode.apply(null, new Uint16Array(bytes.buffer)); +}; + +/** + * Deflates the given data using a flash interface. + * + * @param api the flash interface. + * @param bytes the data. + * @param raw true to return only raw deflate data, false to include zlib + * header and trailer. + * + * @return the deflated data as a string. + */ +util.deflate = function(api, bytes, raw) { + bytes = util.decode64(api.deflate(util.encode64(bytes)).rval); + + // strip zlib header and trailer if necessary + if(raw) { + // zlib header is 2 bytes (CMF,FLG) where FLG indicates that + // there is a 4-byte DICT (alder-32) block before the data if + // its 5th bit is set + var start = 2; + var flg = bytes.charCodeAt(1); + if(flg & 0x20) { + start = 6; + } + // zlib trailer is 4 bytes of adler-32 + bytes = bytes.substring(start, bytes.length - 4); + } + + return bytes; +}; + +/** + * Inflates the given data using a flash interface. + * + * @param api the flash interface. + * @param bytes the data. + * @param raw true if the incoming data has no zlib header or trailer and is + * raw DEFLATE data. + * + * @return the inflated data as a string, null on error. + */ +util.inflate = function(api, bytes, raw) { + // TODO: add zlib header and trailer if necessary/possible + var rval = api.inflate(util.encode64(bytes)).rval; + return (rval === null) ? null : util.decode64(rval); +}; + +/** + * Sets a storage object. + * + * @param api the storage interface. + * @param id the storage ID to use. + * @param obj the storage object, null to remove. + */ +var _setStorageObject = function(api, id, obj) { + if(!api) { + throw new Error('WebStorage not available.'); + } + + var rval; + if(obj === null) { + rval = api.removeItem(id); + } else { + // json-encode and base64-encode object + obj = util.encode64(JSON.stringify(obj)); + rval = api.setItem(id, obj); + } + + // handle potential flash error + if(typeof(rval) !== 'undefined' && rval.rval !== true) { + var error = new Error(rval.error.message); + error.id = rval.error.id; + error.name = rval.error.name; + throw error; + } +}; + +/** + * Gets a storage object. + * + * @param api the storage interface. + * @param id the storage ID to use. + * + * @return the storage object entry or null if none exists. + */ +var _getStorageObject = function(api, id) { + if(!api) { + throw new Error('WebStorage not available.'); + } + + // get the existing entry + var rval = api.getItem(id); + + /* Note: We check api.init because we can't do (api == localStorage) + on IE because of "Class doesn't support Automation" exception. Only + the flash api has an init method so this works too, but we need a + better solution in the future. */ + + // flash returns item wrapped in an object, handle special case + if(api.init) { + if(rval.rval === null) { + if(rval.error) { + var error = new Error(rval.error.message); + error.id = rval.error.id; + error.name = rval.error.name; + throw error; + } + // no error, but also no item + rval = null; + } else { + rval = rval.rval; + } + } + + // handle decoding + if(rval !== null) { + // base64-decode and json-decode data + rval = JSON.parse(util.decode64(rval)); + } + + return rval; +}; + +/** + * Stores an item in local storage. + * + * @param api the storage interface. + * @param id the storage ID to use. + * @param key the key for the item. + * @param data the data for the item (any javascript object/primitive). + */ +var _setItem = function(api, id, key, data) { + // get storage object + var obj = _getStorageObject(api, id); + if(obj === null) { + // create a new storage object + obj = {}; + } + // update key + obj[key] = data; + + // set storage object + _setStorageObject(api, id, obj); +}; + +/** + * Gets an item from local storage. + * + * @param api the storage interface. + * @param id the storage ID to use. + * @param key the key for the item. + * + * @return the item. + */ +var _getItem = function(api, id, key) { + // get storage object + var rval = _getStorageObject(api, id); + if(rval !== null) { + // return data at key + rval = (key in rval) ? rval[key] : null; + } + + return rval; +}; + +/** + * Removes an item from local storage. + * + * @param api the storage interface. + * @param id the storage ID to use. + * @param key the key for the item. + */ +var _removeItem = function(api, id, key) { + // get storage object + var obj = _getStorageObject(api, id); + if(obj !== null && key in obj) { + // remove key + delete obj[key]; + + // see if entry has no keys remaining + var empty = true; + for(var prop in obj) { + empty = false; + break; + } + if(empty) { + // remove entry entirely if no keys are left + obj = null; + } + + // set storage object + _setStorageObject(api, id, obj); + } +}; + +/** + * Clears the local disk storage identified by the given ID. + * + * @param api the storage interface. + * @param id the storage ID to use. + */ +var _clearItems = function(api, id) { + _setStorageObject(api, id, null); +}; + +/** + * Calls a storage function. + * + * @param func the function to call. + * @param args the arguments for the function. + * @param location the location argument. + * + * @return the return value from the function. + */ +var _callStorageFunction = function(func, args, location) { + var rval = null; + + // default storage types + if(typeof(location) === 'undefined') { + location = ['web', 'flash']; + } + + // apply storage types in order of preference + var type; + var done = false; + var exception = null; + for(var idx in location) { + type = location[idx]; + try { + if(type === 'flash' || type === 'both') { + if(args[0] === null) { + throw new Error('Flash local storage not available.'); + } + rval = func.apply(this, args); + done = (type === 'flash'); + } + if(type === 'web' || type === 'both') { + args[0] = localStorage; + rval = func.apply(this, args); + done = true; + } + } catch(ex) { + exception = ex; + } + if(done) { + break; + } + } + + if(!done) { + throw exception; + } + + return rval; +}; + +/** + * Stores an item on local disk. + * + * The available types of local storage include 'flash', 'web', and 'both'. + * + * The type 'flash' refers to flash local storage (SharedObject). In order + * to use flash local storage, the 'api' parameter must be valid. The type + * 'web' refers to WebStorage, if supported by the browser. The type 'both' + * refers to storing using both 'flash' and 'web', not just one or the + * other. + * + * The location array should list the storage types to use in order of + * preference: + * + * ['flash']: flash only storage + * ['web']: web only storage + * ['both']: try to store in both + * ['flash','web']: store in flash first, but if not available, 'web' + * ['web','flash']: store in web first, but if not available, 'flash' + * + * The location array defaults to: ['web', 'flash'] + * + * @param api the flash interface, null to use only WebStorage. + * @param id the storage ID to use. + * @param key the key for the item. + * @param data the data for the item (any javascript object/primitive). + * @param location an array with the preferred types of storage to use. + */ +util.setItem = function(api, id, key, data, location) { + _callStorageFunction(_setItem, arguments, location); +}; + +/** + * Gets an item on local disk. + * + * Set setItem() for details on storage types. + * + * @param api the flash interface, null to use only WebStorage. + * @param id the storage ID to use. + * @param key the key for the item. + * @param location an array with the preferred types of storage to use. + * + * @return the item. + */ +util.getItem = function(api, id, key, location) { + return _callStorageFunction(_getItem, arguments, location); +}; + +/** + * Removes an item on local disk. + * + * Set setItem() for details on storage types. + * + * @param api the flash interface. + * @param id the storage ID to use. + * @param key the key for the item. + * @param location an array with the preferred types of storage to use. + */ +util.removeItem = function(api, id, key, location) { + _callStorageFunction(_removeItem, arguments, location); +}; + +/** + * Clears the local disk storage identified by the given ID. + * + * Set setItem() for details on storage types. + * + * @param api the flash interface if flash is available. + * @param id the storage ID to use. + * @param location an array with the preferred types of storage to use. + */ +util.clearItems = function(api, id, location) { + _callStorageFunction(_clearItems, arguments, location); +}; + +/** + * Parses the scheme, host, and port from an http(s) url. + * + * @param str the url string. + * + * @return the parsed url object or null if the url is invalid. + */ +util.parseUrl = function(str) { + // FIXME: this regex looks a bit broken + var regex = /^(https?):\/\/([^:&^\/]*):?(\d*)(.*)$/g; + regex.lastIndex = 0; + var m = regex.exec(str); + var url = (m === null) ? null : { + full: str, + scheme: m[1], + host: m[2], + port: m[3], + path: m[4] + }; + if(url) { + url.fullHost = url.host; + if(url.port) { + if(url.port !== 80 && url.scheme === 'http') { + url.fullHost += ':' + url.port; + } else if(url.port !== 443 && url.scheme === 'https') { + url.fullHost += ':' + url.port; + } + } else if(url.scheme === 'http') { + url.port = 80; + } else if(url.scheme === 'https') { + url.port = 443; + } + url.full = url.scheme + '://' + url.fullHost; + } + return url; +}; + +/* Storage for query variables */ +var _queryVariables = null; + +/** + * Returns the window location query variables. Query is parsed on the first + * call and the same object is returned on subsequent calls. The mapping + * is from keys to an array of values. Parameters without values will have + * an object key set but no value added to the value array. Values are + * unescaped. + * + * ...?k1=v1&k2=v2: + * { + * "k1": ["v1"], + * "k2": ["v2"] + * } + * + * ...?k1=v1&k1=v2: + * { + * "k1": ["v1", "v2"] + * } + * + * ...?k1=v1&k2: + * { + * "k1": ["v1"], + * "k2": [] + * } + * + * ...?k1=v1&k1: + * { + * "k1": ["v1"] + * } + * + * ...?k1&k1: + * { + * "k1": [] + * } + * + * @param query the query string to parse (optional, default to cached + * results from parsing window location search query). + * + * @return object mapping keys to variables. + */ +util.getQueryVariables = function(query) { + var parse = function(q) { + var rval = {}; + var kvpairs = q.split('&'); + for(var i = 0; i < kvpairs.length; i++) { + var pos = kvpairs[i].indexOf('='); + var key; + var val; + if(pos > 0) { + key = kvpairs[i].substring(0, pos); + val = kvpairs[i].substring(pos + 1); + } else { + key = kvpairs[i]; + val = null; + } + if(!(key in rval)) { + rval[key] = []; + } + // disallow overriding object prototype keys + if(!(key in Object.prototype) && val !== null) { + rval[key].push(unescape(val)); + } + } + return rval; + }; + + var rval; + if(typeof(query) === 'undefined') { + // set cached variables if needed + if(_queryVariables === null) { + if(typeof(window) !== 'undefined' && window.location && window.location.search) { + // parse window search query + _queryVariables = parse(window.location.search.substring(1)); + } else { + // no query variables available + _queryVariables = {}; + } + } + rval = _queryVariables; + } else { + // parse given query + rval = parse(query); + } + return rval; +}; + +/** + * Parses a fragment into a path and query. This method will take a URI + * fragment and break it up as if it were the main URI. For example: + * /bar/baz?a=1&b=2 + * results in: + * { + * path: ["bar", "baz"], + * query: {"k1": ["v1"], "k2": ["v2"]} + * } + * + * @return object with a path array and query object. + */ +util.parseFragment = function(fragment) { + // default to whole fragment + var fp = fragment; + var fq = ''; + // split into path and query if possible at the first '?' + var pos = fragment.indexOf('?'); + if(pos > 0) { + fp = fragment.substring(0, pos); + fq = fragment.substring(pos + 1); + } + // split path based on '/' and ignore first element if empty + var path = fp.split('/'); + if(path.length > 0 && path[0] === '') { + path.shift(); + } + // convert query into object + var query = (fq === '') ? {} : util.getQueryVariables(fq); + + return { + pathString: fp, + queryString: fq, + path: path, + query: query + }; +}; + +/** + * Makes a request out of a URI-like request string. This is intended to + * be used where a fragment id (after a URI '#') is parsed as a URI with + * path and query parts. The string should have a path beginning and + * delimited by '/' and optional query parameters following a '?'. The + * query should be a standard URL set of key value pairs delimited by + * '&'. For backwards compatibility the initial '/' on the path is not + * required. The request object has the following API, (fully described + * in the method code): + * { + * path: . + * query: , + * getPath(i): get part or all of the split path array, + * getQuery(k, i): get part or all of a query key array, + * getQueryLast(k, _default): get last element of a query key array. + * } + * + * @return object with request parameters. + */ +util.makeRequest = function(reqString) { + var frag = util.parseFragment(reqString); + var req = { + // full path string + path: frag.pathString, + // full query string + query: frag.queryString, + /** + * Get path or element in path. + * + * @param i optional path index. + * + * @return path or part of path if i provided. + */ + getPath: function(i) { + return (typeof(i) === 'undefined') ? frag.path : frag.path[i]; + }, + /** + * Get query, values for a key, or value for a key index. + * + * @param k optional query key. + * @param i optional query key index. + * + * @return query, values for a key, or value for a key index. + */ + getQuery: function(k, i) { + var rval; + if(typeof(k) === 'undefined') { + rval = frag.query; + } else { + rval = frag.query[k]; + if(rval && typeof(i) !== 'undefined') { + rval = rval[i]; + } + } + return rval; + }, + getQueryLast: function(k, _default) { + var rval; + var vals = req.getQuery(k); + if(vals) { + rval = vals[vals.length - 1]; + } else { + rval = _default; + } + return rval; + } + }; + return req; +}; + +/** + * Makes a URI out of a path, an object with query parameters, and a + * fragment. Uses jQuery.param() internally for query string creation. + * If the path is an array, it will be joined with '/'. + * + * @param path string path or array of strings. + * @param query object with query parameters. (optional) + * @param fragment fragment string. (optional) + * + * @return string object with request parameters. + */ +util.makeLink = function(path, query, fragment) { + // join path parts if needed + path = jQuery.isArray(path) ? path.join('/') : path; + + var qstr = jQuery.param(query || {}); + fragment = fragment || ''; + return path + + ((qstr.length > 0) ? ('?' + qstr) : '') + + ((fragment.length > 0) ? ('#' + fragment) : ''); +}; + +/** + * Check if an object is empty. + * + * Taken from: + * http://stackoverflow.com/questions/679915/how-do-i-test-for-an-empty-javascript-object-from-json/679937#679937 + * + * @param object the object to check. + */ +util.isEmpty = function(obj) { + for(var prop in obj) { + if(obj.hasOwnProperty(prop)) { + return false; + } + } + return true; +}; + +/** + * Format with simple printf-style interpolation. + * + * %%: literal '%' + * %s,%o: convert next argument into a string. + * + * @param format the string to format. + * @param ... arguments to interpolate into the format string. + */ +util.format = function(format) { + var re = /%./g; + // current match + var match; + // current part + var part; + // current arg index + var argi = 0; + // collected parts to recombine later + var parts = []; + // last index found + var last = 0; + // loop while matches remain + while((match = re.exec(format))) { + part = format.substring(last, re.lastIndex - 2); + // don't add empty strings (ie, parts between %s%s) + if(part.length > 0) { + parts.push(part); + } + last = re.lastIndex; + // switch on % code + var code = match[0][1]; + switch(code) { + case 's': + case 'o': + // check if enough arguments were given + if(argi < arguments.length) { + parts.push(arguments[argi++ + 1]); + } else { + parts.push(''); + } + break; + // FIXME: do proper formating for numbers, etc + //case 'f': + //case 'd': + case '%': + parts.push('%'); + break; + default: + parts.push('<%' + code + '?>'); + } + } + // add trailing part of format string + parts.push(format.substring(last)); + return parts.join(''); +}; + +/** + * Formats a number. + * + * http://snipplr.com/view/5945/javascript-numberformat--ported-from-php/ + */ +util.formatNumber = function(number, decimals, dec_point, thousands_sep) { + // http://kevin.vanzonneveld.net + // + original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com) + // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) + // + bugfix by: Michael White (http://crestidg.com) + // + bugfix by: Benjamin Lupton + // + bugfix by: Allan Jensen (http://www.winternet.no) + // + revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com) + // * example 1: number_format(1234.5678, 2, '.', ''); + // * returns 1: 1234.57 + + var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals; + var d = dec_point === undefined ? ',' : dec_point; + var t = thousands_sep === undefined ? + '.' : thousands_sep, s = n < 0 ? '-' : ''; + var i = parseInt((n = Math.abs(+n || 0).toFixed(c)), 10) + ''; + var j = (i.length > 3) ? i.length % 3 : 0; + return s + (j ? i.substr(0, j) + t : '') + + i.substr(j).replace(/(\d{3})(?=\d)/g, '$1' + t) + + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : ''); +}; + +/** + * Formats a byte size. + * + * http://snipplr.com/view/5949/format-humanize-file-byte-size-presentation-in-javascript/ + */ +util.formatSize = function(size) { + if(size >= 1073741824) { + size = util.formatNumber(size / 1073741824, 2, '.', '') + ' GiB'; + } else if(size >= 1048576) { + size = util.formatNumber(size / 1048576, 2, '.', '') + ' MiB'; + } else if(size >= 1024) { + size = util.formatNumber(size / 1024, 0) + ' KiB'; + } else { + size = util.formatNumber(size, 0) + ' bytes'; + } + return size; +}; + +/** + * Converts an IPv4 or IPv6 string representation into bytes (in network order). + * + * @param ip the IPv4 or IPv6 address to convert. + * + * @return the 4-byte IPv6 or 16-byte IPv6 address or null if the address can't + * be parsed. + */ +util.bytesFromIP = function(ip) { + if(ip.indexOf('.') !== -1) { + return util.bytesFromIPv4(ip); + } + if(ip.indexOf(':') !== -1) { + return util.bytesFromIPv6(ip); + } + return null; +}; + +/** + * Converts an IPv4 string representation into bytes (in network order). + * + * @param ip the IPv4 address to convert. + * + * @return the 4-byte address or null if the address can't be parsed. + */ +util.bytesFromIPv4 = function(ip) { + ip = ip.split('.'); + if(ip.length !== 4) { + return null; + } + var b = util.createBuffer(); + for(var i = 0; i < ip.length; ++i) { + var num = parseInt(ip[i], 10); + if(isNaN(num)) { + return null; + } + b.putByte(num); + } + return b.getBytes(); +}; + +/** + * Converts an IPv6 string representation into bytes (in network order). + * + * @param ip the IPv6 address to convert. + * + * @return the 16-byte address or null if the address can't be parsed. + */ +util.bytesFromIPv6 = function(ip) { + var blanks = 0; + ip = ip.split(':').filter(function(e) { + if(e.length === 0) ++blanks; + return true; + }); + var zeros = (8 - ip.length + blanks) * 2; + var b = util.createBuffer(); + for(var i = 0; i < 8; ++i) { + if(!ip[i] || ip[i].length === 0) { + b.fillWithByte(0, zeros); + zeros = 0; + continue; + } + var bytes = util.hexToBytes(ip[i]); + if(bytes.length < 2) { + b.putByte(0); + } + b.putBytes(bytes); + } + return b.getBytes(); +}; + +/** + * Converts 4-bytes into an IPv4 string representation or 16-bytes into + * an IPv6 string representation. The bytes must be in network order. + * + * @param bytes the bytes to convert. + * + * @return the IPv4 or IPv6 string representation if 4 or 16 bytes, + * respectively, are given, otherwise null. + */ +util.bytesToIP = function(bytes) { + if(bytes.length === 4) { + return util.bytesToIPv4(bytes); + } + if(bytes.length === 16) { + return util.bytesToIPv6(bytes); + } + return null; +}; + +/** + * Converts 4-bytes into an IPv4 string representation. The bytes must be + * in network order. + * + * @param bytes the bytes to convert. + * + * @return the IPv4 string representation or null for an invalid # of bytes. + */ +util.bytesToIPv4 = function(bytes) { + if(bytes.length !== 4) { + return null; + } + var ip = []; + for(var i = 0; i < bytes.length; ++i) { + ip.push(bytes.charCodeAt(i)); + } + return ip.join('.'); +}; + +/** + * Converts 16-bytes into an IPv16 string representation. The bytes must be + * in network order. + * + * @param bytes the bytes to convert. + * + * @return the IPv16 string representation or null for an invalid # of bytes. + */ +util.bytesToIPv6 = function(bytes) { + if(bytes.length !== 16) { + return null; + } + var ip = []; + var zeroGroups = []; + var zeroMaxGroup = 0; + for(var i = 0; i < bytes.length; i += 2) { + var hex = util.bytesToHex(bytes[i] + bytes[i + 1]); + // canonicalize zero representation + while(hex[0] === '0' && hex !== '0') { + hex = hex.substr(1); + } + if(hex === '0') { + var last = zeroGroups[zeroGroups.length - 1]; + var idx = ip.length; + if(!last || idx !== last.end + 1) { + zeroGroups.push({start: idx, end: idx}); + } else { + last.end = idx; + if((last.end - last.start) > + (zeroGroups[zeroMaxGroup].end - zeroGroups[zeroMaxGroup].start)) { + zeroMaxGroup = zeroGroups.length - 1; + } + } + } + ip.push(hex); + } + if(zeroGroups.length > 0) { + var group = zeroGroups[zeroMaxGroup]; + // only shorten group of length > 0 + if(group.end - group.start > 0) { + ip.splice(group.start, group.end - group.start + 1, ''); + if(group.start === 0) { + ip.unshift(''); + } + if(group.end === 7) { + ip.push(''); + } + } + } + return ip.join(':'); +}; + +/** + * Estimates the number of processes that can be run concurrently. If + * creating Web Workers, keep in mind that the main JavaScript process needs + * its own core. + * + * @param options the options to use: + * update true to force an update (not use the cached value). + * @param callback(err, max) called once the operation completes. + */ +util.estimateCores = function(options, callback) { + if(typeof options === 'function') { + callback = options; + options = {}; + } + options = options || {}; + if('cores' in util && !options.update) { + return callback(null, util.cores); + } + if(typeof navigator !== 'undefined' && + 'hardwareConcurrency' in navigator && + navigator.hardwareConcurrency > 0) { + util.cores = navigator.hardwareConcurrency; + return callback(null, util.cores); + } + if(typeof Worker === 'undefined') { + // workers not available + util.cores = 1; + return callback(null, util.cores); + } + if(typeof Blob === 'undefined') { + // can't estimate, default to 2 + util.cores = 2; + return callback(null, util.cores); + } + + // create worker concurrency estimation code as blob + var blobUrl = URL.createObjectURL(new Blob(['(', + function() { + self.addEventListener('message', function(e) { + // run worker for 4 ms + var st = Date.now(); + var et = st + 4; + while(Date.now() < et); + self.postMessage({st: st, et: et}); + }); + }.toString(), + ')()'], {type: 'application/javascript'})); + + // take 5 samples using 16 workers + sample([], 5, 16); + + function sample(max, samples, numWorkers) { + if(samples === 0) { + // get overlap average + var avg = Math.floor(max.reduce(function(avg, x) { + return avg + x; + }, 0) / max.length); + util.cores = Math.max(1, avg); + URL.revokeObjectURL(blobUrl); + return callback(null, util.cores); + } + map(numWorkers, function(err, results) { + max.push(reduce(numWorkers, results)); + sample(max, samples - 1, numWorkers); + }); + } + + function map(numWorkers, callback) { + var workers = []; + var results = []; + for(var i = 0; i < numWorkers; ++i) { + var worker = new Worker(blobUrl); + worker.addEventListener('message', function(e) { + results.push(e.data); + if(results.length === numWorkers) { + for(var i = 0; i < numWorkers; ++i) { + workers[i].terminate(); + } + callback(null, results); + } + }); + workers.push(worker); + } + for(var i = 0; i < numWorkers; ++i) { + workers[i].postMessage(i); + } + } + + function reduce(numWorkers, results) { + // find overlapping time windows + var overlaps = []; + for(var n = 0; n < numWorkers; ++n) { + var r1 = results[n]; + var overlap = overlaps[n] = []; + for(var i = 0; i < numWorkers; ++i) { + if(n === i) { + continue; + } + var r2 = results[i]; + if((r1.st > r2.st && r1.st < r2.et) || + (r2.st > r1.st && r2.st < r1.et)) { + overlap.push(i); + } + } + } + // get maximum overlaps ... don't include overlapping worker itself + // as the main JS process was also being scheduled during the work and + // would have to be subtracted from the estimate anyway + return overlaps.reduce(function(max, overlap) { + return Math.max(max, overlap.length); + }, 0); + } +}; + +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../process/browser.js */ "./node_modules/process/browser.js"), __webpack_require__(/*! ./../../timers-browserify/main.js */ "./node_modules/timers-browserify/main.js").setImmediate, __webpack_require__(/*! ./../../webpack/buildin/global.js */ "./node_modules/webpack/buildin/global.js"), __webpack_require__(/*! ./../../node-libs-browser/node_modules/buffer/index.js */ "./node_modules/node-libs-browser/node_modules/buffer/index.js").Buffer)) + +/***/ }), + +/***/ "./node_modules/node-libs-browser/node_modules/buffer/index.js": +/*!*********************************************************************!*\ + !*** ./node_modules/node-libs-browser/node_modules/buffer/index.js ***! + \*********************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(global) {/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ +/* eslint-disable no-proto */ + + + +var base64 = __webpack_require__(/*! base64-js */ "./node_modules/base64-js/index.js") +var ieee754 = __webpack_require__(/*! ieee754 */ "./node_modules/ieee754/index.js") +var isArray = __webpack_require__(/*! isarray */ "./node_modules/isarray/index.js") + +exports.Buffer = Buffer +exports.SlowBuffer = SlowBuffer +exports.INSPECT_MAX_BYTES = 50 + +/** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Use Object implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * Due to various browser bugs, sometimes the Object implementation will be used even + * when the browser supports typed arrays. + * + * Note: + * + * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, + * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. + * + * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. + * + * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of + * incorrect length in some situations. + + * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they + * get the Object implementation, which is slower but behaves correctly. + */ +Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined + ? global.TYPED_ARRAY_SUPPORT + : typedArraySupport() + +/* + * Export kMaxLength after typed array support is determined. + */ +exports.kMaxLength = kMaxLength() + +function typedArraySupport () { + try { + var arr = new Uint8Array(1) + arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }} + return arr.foo() === 42 && // typed array instances can be augmented + typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray` + arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray` + } catch (e) { + return false + } +} + +function kMaxLength () { + return Buffer.TYPED_ARRAY_SUPPORT + ? 0x7fffffff + : 0x3fffffff +} + +function createBuffer (that, length) { + if (kMaxLength() < length) { + throw new RangeError('Invalid typed array length') + } + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = new Uint8Array(length) + that.__proto__ = Buffer.prototype + } else { + // Fallback: Return an object instance of the Buffer class + if (that === null) { + that = new Buffer(length) + } + that.length = length + } + + return that +} + +/** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + +function Buffer (arg, encodingOrOffset, length) { + if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { + return new Buffer(arg, encodingOrOffset, length) + } + + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new Error( + 'If encoding is specified then the first argument must be a string' + ) + } + return allocUnsafe(this, arg) + } + return from(this, arg, encodingOrOffset, length) +} + +Buffer.poolSize = 8192 // not used by this implementation + +// TODO: Legacy, not needed anymore. Remove in next major version. +Buffer._augment = function (arr) { + arr.__proto__ = Buffer.prototype + return arr +} + +function from (that, value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number') + } + + if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { + return fromArrayBuffer(that, value, encodingOrOffset, length) + } + + if (typeof value === 'string') { + return fromString(that, value, encodingOrOffset) + } + + return fromObject(that, value) +} + +/** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ +Buffer.from = function (value, encodingOrOffset, length) { + return from(null, value, encodingOrOffset, length) +} + +if (Buffer.TYPED_ARRAY_SUPPORT) { + Buffer.prototype.__proto__ = Uint8Array.prototype + Buffer.__proto__ = Uint8Array + if (typeof Symbol !== 'undefined' && Symbol.species && + Buffer[Symbol.species] === Buffer) { + // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 + Object.defineProperty(Buffer, Symbol.species, { + value: null, + configurable: true + }) + } +} + +function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be a number') + } else if (size < 0) { + throw new RangeError('"size" argument must not be negative') + } +} + +function alloc (that, size, fill, encoding) { + assertSize(size) + if (size <= 0) { + return createBuffer(that, size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' + ? createBuffer(that, size).fill(fill, encoding) + : createBuffer(that, size).fill(fill) + } + return createBuffer(that, size) +} + +/** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ +Buffer.alloc = function (size, fill, encoding) { + return alloc(null, size, fill, encoding) +} + +function allocUnsafe (that, size) { + assertSize(size) + that = createBuffer(that, size < 0 ? 0 : checked(size) | 0) + if (!Buffer.TYPED_ARRAY_SUPPORT) { + for (var i = 0; i < size; ++i) { + that[i] = 0 + } + } + return that +} + +/** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ +Buffer.allocUnsafe = function (size) { + return allocUnsafe(null, size) +} +/** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ +Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(null, size) +} + +function fromString (that, string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8' + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding') + } + + var length = byteLength(string, encoding) | 0 + that = createBuffer(that, length) + + var actual = that.write(string, encoding) + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + that = that.slice(0, actual) + } + + return that +} + +function fromArrayLike (that, array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0 + that = createBuffer(that, length) + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255 + } + return that +} + +function fromArrayBuffer (that, array, byteOffset, length) { + array.byteLength // this throws if `array` is not a valid ArrayBuffer + + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('\'offset\' is out of bounds') + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('\'length\' is out of bounds') + } + + if (byteOffset === undefined && length === undefined) { + array = new Uint8Array(array) + } else if (length === undefined) { + array = new Uint8Array(array, byteOffset) + } else { + array = new Uint8Array(array, byteOffset, length) + } + + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = array + that.__proto__ = Buffer.prototype + } else { + // Fallback: Return an object instance of the Buffer class + that = fromArrayLike(that, array) + } + return that +} + +function fromObject (that, obj) { + if (Buffer.isBuffer(obj)) { + var len = checked(obj.length) | 0 + that = createBuffer(that, len) + + if (that.length === 0) { + return that + } + + obj.copy(that, 0, 0, len) + return that + } + + if (obj) { + if ((typeof ArrayBuffer !== 'undefined' && + obj.buffer instanceof ArrayBuffer) || 'length' in obj) { + if (typeof obj.length !== 'number' || isnan(obj.length)) { + return createBuffer(that, 0) + } + return fromArrayLike(that, obj) + } + + if (obj.type === 'Buffer' && isArray(obj.data)) { + return fromArrayLike(that, obj.data) + } + } + + throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') +} + +function checked (length) { + // Note: cannot use `length < kMaxLength()` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= kMaxLength()) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + kMaxLength().toString(16) + ' bytes') + } + return length | 0 +} + +function SlowBuffer (length) { + if (+length != length) { // eslint-disable-line eqeqeq + length = 0 + } + return Buffer.alloc(+length) +} + +Buffer.isBuffer = function isBuffer (b) { + return !!(b != null && b._isBuffer) +} + +Buffer.compare = function compare (a, b) { + if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { + throw new TypeError('Arguments must be Buffers') + } + + if (a === b) return 0 + + var x = a.length + var y = b.length + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i] + y = b[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +} + +Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } +} + +Buffer.concat = function concat (list, length) { + if (!isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + + if (list.length === 0) { + return Buffer.alloc(0) + } + + var i + if (length === undefined) { + length = 0 + for (i = 0; i < list.length; ++i) { + length += list[i].length + } + } + + var buffer = Buffer.allocUnsafe(length) + var pos = 0 + for (i = 0; i < list.length; ++i) { + var buf = list[i] + if (!Buffer.isBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + buf.copy(buffer, pos) + pos += buf.length + } + return buffer +} + +function byteLength (string, encoding) { + if (Buffer.isBuffer(string)) { + return string.length + } + if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && + (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + string = '' + string + } + + var len = string.length + if (len === 0) return 0 + + // Use a for loop to avoid recursion + var loweredCase = false + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + case undefined: + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) return utf8ToBytes(string).length // assume utf8 + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} +Buffer.byteLength = byteLength + +function slowToString (encoding, start, end) { + var loweredCase = false + + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0 + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length + } + + if (end <= 0) { + return '' + } + + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0 + start >>>= 0 + + if (end <= start) { + return '' + } + + if (!encoding) encoding = 'utf8' + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase() + loweredCase = true + } + } +} + +// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect +// Buffer instances. +Buffer.prototype._isBuffer = true + +function swap (b, n, m) { + var i = b[n] + b[n] = b[m] + b[m] = i +} + +Buffer.prototype.swap16 = function swap16 () { + var len = this.length + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1) + } + return this +} + +Buffer.prototype.swap32 = function swap32 () { + var len = this.length + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3) + swap(this, i + 1, i + 2) + } + return this +} + +Buffer.prototype.swap64 = function swap64 () { + var len = this.length + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7) + swap(this, i + 1, i + 6) + swap(this, i + 2, i + 5) + swap(this, i + 3, i + 4) + } + return this +} + +Buffer.prototype.toString = function toString () { + var length = this.length | 0 + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) +} + +Buffer.prototype.equals = function equals (b) { + if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 +} + +Buffer.prototype.inspect = function inspect () { + var str = '' + var max = exports.INSPECT_MAX_BYTES + if (this.length > 0) { + str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') + if (this.length > max) str += ' ... ' + } + return '' +} + +Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (!Buffer.isBuffer(target)) { + throw new TypeError('Argument must be a Buffer') + } + + if (start === undefined) { + start = 0 + } + if (end === undefined) { + end = target ? target.length : 0 + } + if (thisStart === undefined) { + thisStart = 0 + } + if (thisEnd === undefined) { + thisEnd = this.length + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0 + end >>>= 0 + thisStart >>>= 0 + thisEnd >>>= 0 + + if (this === target) return 0 + + var x = thisEnd - thisStart + var y = end - start + var len = Math.min(x, y) + + var thisCopy = this.slice(thisStart, thisEnd) + var targetCopy = target.slice(start, end) + + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i] + y = targetCopy[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +} + +// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, +// OR the last index of `val` in `buffer` at offset <= `byteOffset`. +// +// Arguments: +// - buffer - a Buffer to search +// - val - a string, Buffer, or number +// - byteOffset - an index into `buffer`; will be clamped to an int32 +// - encoding - an optional encoding, relevant is val is a string +// - dir - true for indexOf, false for lastIndexOf +function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset + byteOffset = 0 + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000 + } + byteOffset = +byteOffset // Coerce to Number. + if (isNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1) + } + + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1 + } else if (byteOffset < 0) { + if (dir) byteOffset = 0 + else return -1 + } + + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding) + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (Buffer.isBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF // Search for a byte value [0-255] + if (Buffer.TYPED_ARRAY_SUPPORT && + typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) + } + + throw new TypeError('val must be string, number or Buffer') +} + +function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + var indexSize = 1 + var arrLength = arr.length + var valLength = val.length + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase() + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2 + arrLength /= 2 + valLength /= 2 + byteOffset /= 2 + } + } + + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + var i + if (dir) { + var foundIndex = -1 + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex + foundIndex = -1 + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength + for (i = byteOffset; i >= 0; i--) { + var found = true + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false + break + } + } + if (found) return i + } + } + + return -1 +} + +Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 +} + +Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) +} + +Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) +} + +function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0 + var remaining = buf.length - offset + if (!length) { + length = remaining + } else { + length = Number(length) + if (length > remaining) { + length = remaining + } + } + + // must be an even number of digits + var strLen = string.length + if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') + + if (length > strLen / 2) { + length = strLen / 2 + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16) + if (isNaN(parsed)) return i + buf[offset + i] = parsed + } + return i +} + +function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) +} + +function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) +} + +function latin1Write (buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) +} + +function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) +} + +function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) +} + +Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8' + length = this.length + offset = 0 + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset + length = this.length + offset = 0 + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset | 0 + if (isFinite(length)) { + length = length | 0 + if (encoding === undefined) encoding = 'utf8' + } else { + encoding = length + length = undefined + } + // legacy write(string, encoding, offset, length) - remove in v0.13 + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } + + var remaining = this.length - offset + if (length === undefined || length > remaining) length = remaining + + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8' + + var loweredCase = false + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) + + case 'ascii': + return asciiWrite(this, string, offset, length) + + case 'latin1': + case 'binary': + return latin1Write(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} + +Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } +} + +function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return base64.fromByteArray(buf) + } else { + return base64.fromByteArray(buf.slice(start, end)) + } +} + +function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end) + var res = [] + + var i = start + while (i < end) { + var firstByte = buf[i] + var codePoint = null + var bytesPerSequence = (firstByte > 0xEF) ? 4 + : (firstByte > 0xDF) ? 3 + : (firstByte > 0xBF) ? 2 + : 1 + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte + } + break + case 2: + secondByte = buf[i + 1] + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint + } + } + break + case 3: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint + } + } + break + case 4: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + fourthByte = buf[i + 3] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD + bytesPerSequence = 1 + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000 + res.push(codePoint >>> 10 & 0x3FF | 0xD800) + codePoint = 0xDC00 | codePoint & 0x3FF + } + + res.push(codePoint) + i += bytesPerSequence + } + + return decodeCodePointsArray(res) +} + +// Based on http://stackoverflow.com/a/22747272/680742, the browser with +// the lowest limit is Chrome, with 0x10000 args. +// We go 1 magnitude less, for safety +var MAX_ARGUMENTS_LENGTH = 0x1000 + +function decodeCodePointsArray (codePoints) { + var len = codePoints.length + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + var res = '' + var i = 0 + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ) + } + return res +} + +function asciiSlice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F) + } + return ret +} + +function latin1Slice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]) + } + return ret +} + +function hexSlice (buf, start, end) { + var len = buf.length + + if (!start || start < 0) start = 0 + if (!end || end < 0 || end > len) end = len + + var out = '' + for (var i = start; i < end; ++i) { + out += toHex(buf[i]) + } + return out +} + +function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end) + var res = '' + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256) + } + return res +} + +Buffer.prototype.slice = function slice (start, end) { + var len = this.length + start = ~~start + end = end === undefined ? len : ~~end + + if (start < 0) { + start += len + if (start < 0) start = 0 + } else if (start > len) { + start = len + } + + if (end < 0) { + end += len + if (end < 0) end = 0 + } else if (end > len) { + end = len + } + + if (end < start) end = start + + var newBuf + if (Buffer.TYPED_ARRAY_SUPPORT) { + newBuf = this.subarray(start, end) + newBuf.__proto__ = Buffer.prototype + } else { + var sliceLen = end - start + newBuf = new Buffer(sliceLen, undefined) + for (var i = 0; i < sliceLen; ++i) { + newBuf[i] = this[i + start] + } + } + + return newBuf +} + +/* + * Need to make sure that buffer isn't trying to write out of bounds. + */ +function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') +} + +Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + + return val +} + +Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) { + checkOffset(offset, byteLength, this.length) + } + + var val = this[offset + --byteLength] + var mul = 1 + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul + } + + return val +} + +Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length) + return this[offset] +} + +Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + return this[offset] | (this[offset + 1] << 8) +} + +Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + return (this[offset] << 8) | this[offset + 1] +} + +Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) +} + +Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) +} + +Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val +} + +Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var i = byteLength + var mul = 1 + var val = this[offset + --i] + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val +} + +Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length) + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) +} + +Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset] | (this[offset + 1] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} + +Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset + 1] | (this[offset] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} + +Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) +} + +Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) +} + +Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, true, 23, 4) +} + +Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, false, 23, 4) +} + +Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, true, 52, 8) +} + +Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, false, 52, 8) +} + +function checkInt (buf, value, offset, ext, max, min) { + if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') +} + +Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + var mul = 1 + var i = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + var i = byteLength - 1 + var mul = 1 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) + this[offset] = (value & 0xff) + return offset + 1 +} + +function objectWriteUInt16 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffff + value + 1 + for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { + buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> + (littleEndian ? i : 1 - i) * 8 + } +} + +Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + } else { + objectWriteUInt16(this, value, offset, true) + } + return offset + 2 +} + +Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + } else { + objectWriteUInt16(this, value, offset, false) + } + return offset + 2 +} + +function objectWriteUInt32 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffffffff + value + 1 + for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { + buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff + } +} + +Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset + 3] = (value >>> 24) + this[offset + 2] = (value >>> 16) + this[offset + 1] = (value >>> 8) + this[offset] = (value & 0xff) + } else { + objectWriteUInt32(this, value, offset, true) + } + return offset + 4 +} + +Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + } else { + objectWriteUInt32(this, value, offset, false) + } + return offset + 4 +} + +Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + var i = 0 + var mul = 1 + var sub = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + var i = byteLength - 1 + var mul = 1 + var sub = 0 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) + if (value < 0) value = 0xff + value + 1 + this[offset] = (value & 0xff) + return offset + 1 +} + +Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + } else { + objectWriteUInt16(this, value, offset, true) + } + return offset + 2 +} + +Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + } else { + objectWriteUInt16(this, value, offset, false) + } + return offset + 2 +} + +Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + this[offset + 2] = (value >>> 16) + this[offset + 3] = (value >>> 24) + } else { + objectWriteUInt32(this, value, offset, true) + } + return offset + 4 +} + +Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + if (value < 0) value = 0xffffffff + value + 1 + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + } else { + objectWriteUInt32(this, value, offset, false) + } + return offset + 4 +} + +function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') +} + +function writeFloat (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) + } + ieee754.write(buf, value, offset, littleEndian, 23, 4) + return offset + 4 +} + +Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) +} + +function writeDouble (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) + } + ieee754.write(buf, value, offset, littleEndian, 52, 8) + return offset + 8 +} + +Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) +} + +// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) +Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!start) start = 0 + if (!end && end !== 0) end = this.length + if (targetStart >= target.length) targetStart = target.length + if (!targetStart) targetStart = 0 + if (end > 0 && end < start) end = start + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start + } + + var len = end - start + var i + + if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (i = len - 1; i >= 0; --i) { + target[i + targetStart] = this[i + start] + } + } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { + // ascending copy from start + for (i = 0; i < len; ++i) { + target[i + targetStart] = this[i + start] + } + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, start + len), + targetStart + ) + } + + return len +} + +// Usage: +// buffer.fill(number[, offset[, end]]) +// buffer.fill(buffer[, offset[, end]]) +// buffer.fill(string[, offset[, end]][, encoding]) +Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start + start = 0 + end = this.length + } else if (typeof end === 'string') { + encoding = end + end = this.length + } + if (val.length === 1) { + var code = val.charCodeAt(0) + if (code < 256) { + val = code + } + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + } else if (typeof val === 'number') { + val = val & 255 + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } + + if (end <= start) { + return this + } + + start = start >>> 0 + end = end === undefined ? this.length : end >>> 0 + + if (!val) val = 0 + + var i + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val + } + } else { + var bytes = Buffer.isBuffer(val) + ? val + : utf8ToBytes(new Buffer(val, encoding).toString()) + var len = bytes.length + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len] + } + } + + return this +} + +// HELPER FUNCTIONS +// ================ + +var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g + +function base64clean (str) { + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = stringtrim(str).replace(INVALID_BASE64_RE, '') + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '=' + } + return str +} + +function stringtrim (str) { + if (str.trim) return str.trim() + return str.replace(/^\s+|\s+$/g, '') +} + +function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) +} + +function utf8ToBytes (string, units) { + units = units || Infinity + var codePoint + var length = string.length + var leadSurrogate = null + var bytes = [] + + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i) + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } + + // valid lead + leadSurrogate = codePoint + + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + leadSurrogate = codePoint + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + } + + leadSurrogate = null + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint) + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else { + throw new Error('Invalid code point') + } + } + + return bytes +} + +function asciiToBytes (str) { + var byteArray = [] + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF) + } + return byteArray +} + +function utf16leToBytes (str, units) { + var c, hi, lo + var byteArray = [] + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i) + hi = c >> 8 + lo = c % 256 + byteArray.push(lo) + byteArray.push(hi) + } + + return byteArray +} + +function base64ToBytes (str) { + return base64.toByteArray(base64clean(str)) +} + +function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i] + } + return i +} + +function isnan (val) { + return val !== val // eslint-disable-line no-self-compare +} + +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../../webpack/buildin/global.js */ "./node_modules/webpack/buildin/global.js"))) + +/***/ }), + +/***/ "./node_modules/node-libs-browser/node_modules/path-browserify/index.js": +/*!******************************************************************************!*\ + !*** ./node_modules/node-libs-browser/node_modules/path-browserify/index.js ***! + \******************************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +/* WEBPACK VAR INJECTION */(function(process) {// .dirname, .basename, and .extname methods are extracted from Node.js v8.11.1, +// backported and transplited with Babel, with backwards-compat fixes + +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// resolves . and .. elements in a path array with directory names there +// must be no slashes, empty elements, or device names (c:\) in the array +// (so also no leading and trailing slashes - it does not distinguish +// relative and absolute paths) +function normalizeArray(parts, allowAboveRoot) { + // if the path tries to go above the root, `up` ends up > 0 + var up = 0; + for (var i = parts.length - 1; i >= 0; i--) { + var last = parts[i]; + if (last === '.') { + parts.splice(i, 1); + } else if (last === '..') { + parts.splice(i, 1); + up++; + } else if (up) { + parts.splice(i, 1); + up--; + } + } + + // if the path is allowed to go above the root, restore leading ..s + if (allowAboveRoot) { + for (; up--; up) { + parts.unshift('..'); + } + } + + return parts; +} + +// path.resolve([from ...], to) +// posix version +exports.resolve = function() { + var resolvedPath = '', + resolvedAbsolute = false; + + for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) { + var path = (i >= 0) ? arguments[i] : process.cwd(); + + // Skip empty and invalid entries + if (typeof path !== 'string') { + throw new TypeError('Arguments to path.resolve must be strings'); + } else if (!path) { + continue; + } + + resolvedPath = path + '/' + resolvedPath; + resolvedAbsolute = path.charAt(0) === '/'; + } + + // At this point the path should be resolved to a full absolute path, but + // handle relative paths to be safe (might happen when process.cwd() fails) + + // Normalize the path + resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) { + return !!p; + }), !resolvedAbsolute).join('/'); + + return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.'; +}; + +// path.normalize(path) +// posix version +exports.normalize = function(path) { + var isAbsolute = exports.isAbsolute(path), + trailingSlash = substr(path, -1) === '/'; + + // Normalize the path + path = normalizeArray(filter(path.split('/'), function(p) { + return !!p; + }), !isAbsolute).join('/'); + + if (!path && !isAbsolute) { + path = '.'; + } + if (path && trailingSlash) { + path += '/'; + } + + return (isAbsolute ? '/' : '') + path; +}; + +// posix version +exports.isAbsolute = function(path) { + return path.charAt(0) === '/'; +}; + +// posix version +exports.join = function() { + var paths = Array.prototype.slice.call(arguments, 0); + return exports.normalize(filter(paths, function(p, index) { + if (typeof p !== 'string') { + throw new TypeError('Arguments to path.join must be strings'); + } + return p; + }).join('/')); +}; + + +// path.relative(from, to) +// posix version +exports.relative = function(from, to) { + from = exports.resolve(from).substr(1); + to = exports.resolve(to).substr(1); + + function trim(arr) { + var start = 0; + for (; start < arr.length; start++) { + if (arr[start] !== '') break; + } + + var end = arr.length - 1; + for (; end >= 0; end--) { + if (arr[end] !== '') break; + } + + if (start > end) return []; + return arr.slice(start, end - start + 1); + } + + var fromParts = trim(from.split('/')); + var toParts = trim(to.split('/')); + + var length = Math.min(fromParts.length, toParts.length); + var samePartsLength = length; + for (var i = 0; i < length; i++) { + if (fromParts[i] !== toParts[i]) { + samePartsLength = i; + break; + } + } + + var outputParts = []; + for (var i = samePartsLength; i < fromParts.length; i++) { + outputParts.push('..'); + } + + outputParts = outputParts.concat(toParts.slice(samePartsLength)); + + return outputParts.join('/'); +}; + +exports.sep = '/'; +exports.delimiter = ':'; + +exports.dirname = function (path) { + if (typeof path !== 'string') path = path + ''; + if (path.length === 0) return '.'; + var code = path.charCodeAt(0); + var hasRoot = code === 47 /*/*/; + var end = -1; + var matchedSlash = true; + for (var i = path.length - 1; i >= 1; --i) { + code = path.charCodeAt(i); + if (code === 47 /*/*/) { + if (!matchedSlash) { + end = i; + break; + } + } else { + // We saw the first non-path separator + matchedSlash = false; + } + } + + if (end === -1) return hasRoot ? '/' : '.'; + if (hasRoot && end === 1) { + // return '//'; + // Backwards-compat fix: + return '/'; + } + return path.slice(0, end); +}; + +function basename(path) { + if (typeof path !== 'string') path = path + ''; + + var start = 0; + var end = -1; + var matchedSlash = true; + var i; + + for (i = path.length - 1; i >= 0; --i) { + if (path.charCodeAt(i) === 47 /*/*/) { + // If we reached a path separator that was not part of a set of path + // separators at the end of the string, stop now + if (!matchedSlash) { + start = i + 1; + break; + } + } else if (end === -1) { + // We saw the first non-path separator, mark this as the end of our + // path component + matchedSlash = false; + end = i + 1; + } + } + + if (end === -1) return ''; + return path.slice(start, end); +} + +// Uses a mixed approach for backwards-compatibility, as ext behavior changed +// in new Node.js versions, so only basename() above is backported here +exports.basename = function (path, ext) { + var f = basename(path); + if (ext && f.substr(-1 * ext.length) === ext) { + f = f.substr(0, f.length - ext.length); + } + return f; +}; + +exports.extname = function (path) { + if (typeof path !== 'string') path = path + ''; + var startDot = -1; + var startPart = 0; + var end = -1; + var matchedSlash = true; + // Track the state of characters (if any) we see before our first dot and + // after any path separator we find + var preDotState = 0; + for (var i = path.length - 1; i >= 0; --i) { + var code = path.charCodeAt(i); + if (code === 47 /*/*/) { + // If we reached a path separator that was not part of a set of path + // separators at the end of the string, stop now + if (!matchedSlash) { + startPart = i + 1; + break; + } + continue; + } + if (end === -1) { + // We saw the first non-path separator, mark this as the end of our + // extension + matchedSlash = false; + end = i + 1; + } + if (code === 46 /*.*/) { + // If this is our first dot, mark it as the start of our extension + if (startDot === -1) + startDot = i; + else if (preDotState !== 1) + preDotState = 1; + } else if (startDot !== -1) { + // We saw a non-dot and non-path separator before our dot, so we should + // have a good chance at having a non-empty extension + preDotState = -1; + } + } + + if (startDot === -1 || end === -1 || + // We saw a non-dot character immediately before the dot + preDotState === 0 || + // The (right-most) trimmed path component is exactly '..' + preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) { + return ''; + } + return path.slice(startDot, end); +}; + +function filter (xs, f) { + if (xs.filter) return xs.filter(f); + var res = []; + for (var i = 0; i < xs.length; i++) { + if (f(xs[i], i, xs)) res.push(xs[i]); + } + return res; +} + +// String.prototype.substr - negative index don't work in IE8 +var substr = 'ab'.substr(-1) === 'b' + ? function (str, start, len) { return str.substr(start, len) } + : function (str, start, len) { + if (start < 0) start = str.length + start; + return str.substr(start, len); + } +; + +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../../process/browser.js */ "./node_modules/process/browser.js"))) + +/***/ }), + +/***/ "./node_modules/object-assign/index.js": +/*!*********************************************!*\ + !*** ./node_modules/object-assign/index.js ***! + \*********************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* +object-assign +(c) Sindre Sorhus +@license MIT +*/ + + +/* eslint-disable no-unused-vars */ +var getOwnPropertySymbols = Object.getOwnPropertySymbols; +var hasOwnProperty = Object.prototype.hasOwnProperty; +var propIsEnumerable = Object.prototype.propertyIsEnumerable; + +function toObject(val) { + if (val === null || val === undefined) { + throw new TypeError('Object.assign cannot be called with null or undefined'); + } + + return Object(val); +} + +function shouldUseNative() { + try { + if (!Object.assign) { + return false; + } + + // Detect buggy property enumeration order in older V8 versions. + + // https://bugs.chromium.org/p/v8/issues/detail?id=4118 + var test1 = new String('abc'); // eslint-disable-line no-new-wrappers + test1[5] = 'de'; + if (Object.getOwnPropertyNames(test1)[0] === '5') { + return false; + } + + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 + var test2 = {}; + for (var i = 0; i < 10; i++) { + test2['_' + String.fromCharCode(i)] = i; + } + var order2 = Object.getOwnPropertyNames(test2).map(function (n) { + return test2[n]; + }); + if (order2.join('') !== '0123456789') { + return false; + } + + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 + var test3 = {}; + 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { + test3[letter] = letter; + }); + if (Object.keys(Object.assign({}, test3)).join('') !== + 'abcdefghijklmnopqrst') { + return false; + } + + return true; + } catch (err) { + // We don't expect any of the above to throw, but better to be safe. + return false; + } +} + +module.exports = shouldUseNative() ? Object.assign : function (target, source) { + var from; + var to = toObject(target); + var symbols; + + for (var s = 1; s < arguments.length; s++) { + from = Object(arguments[s]); + + for (var key in from) { + if (hasOwnProperty.call(from, key)) { + to[key] = from[key]; + } + } + + if (getOwnPropertySymbols) { + symbols = getOwnPropertySymbols(from); + for (var i = 0; i < symbols.length; i++) { + if (propIsEnumerable.call(from, symbols[i])) { + to[symbols[i]] = from[symbols[i]]; + } + } + } + } + + return to; +}; + + +/***/ }), + +/***/ "./node_modules/pane-registry/paneRegistry.js": +/*!****************************************************!*\ + !*** ./node_modules/pane-registry/paneRegistry.js ***! + \****************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +/* SOLID PANE REGISTRY + ** + ** Panes are regions of the outline view in which a particular subject is + ** displayed in a particular way. + ** Different paneRegistry about the same subject are typically stacked vertically. + ** Panes may be used naked or with a pane selection header. + ** + ** The label() method has two functions: it determines whether the pane is + ** relevant to a given subject, returning null if not. + ** If it is relevant, then it returns a suitable tooltip for a control which selects the pane + */ + +// create the unique UI module on which to attach paneRegistry (no, don't attach as UI dot paneRegistry any more) +// var UI = require('solid-ui') // Note we will add the paneRegistry register to this. + +const $rdf = __webpack_require__(/*! rdflib */ "./node_modules/rdflib/esm/index.js") + +const paneRegistry = (module.exports = {}) + +paneRegistry.list = [] +paneRegistry.paneForIcon = [] +paneRegistry.paneForPredicate = [] +paneRegistry.register = function (p, requireQueryButton) { + p.requireQueryButton = requireQueryButton + if (!p.name) { + console.log('*** No name for pane!') + return + } + console.log(' registering pane: ' + p.name) + if (!p.label) { + console.log('*** No label for pane!') + return + } + paneRegistry.list.push(p) + if (!(p.name in paneRegistry)) { + // don't overwrite methods + paneRegistry[p.name] = p + // console.log(' Indexing '+ p.name +' pane ...') + } + if (p.icon) { + paneRegistry.paneForIcon[p.icon] = p + } + if (p.predicates) { + for (var x in p.predicates) { + paneRegistry.paneForPredicate[x] = { pred: x, code: p.predicates[x] } + } + } +} + +paneRegistry.byName = function (name) { + for (var i = 0; i < paneRegistry.list.length; i++) { + if (paneRegistry.list[i].name === name) return paneRegistry.list[i] + } + console.warn(`No view with name ${name} found in the registry of views (aka paneRegistry)`) + return null +} + +paneRegistry.ConnectedStore = class ConnectedStore extends $rdf.Store { + constructor (features) { + super(features) + this.fetcher = $rdf.fetcher(this, {}) + } +} + +paneRegistry.LiveStore = class LiveStore extends $rdf.Store { + constructor (features) { + super(features) + this.updater = new $rdf.UpdateManager(this) + } +} + +// ENDS + + +/***/ }), + +/***/ "./node_modules/process/browser.js": +/*!*****************************************!*\ + !*** ./node_modules/process/browser.js ***! + \*****************************************/ +/*! no static exports found */ +/***/ (function(module, exports) { + +// shim for using process in browser +var process = module.exports = {}; + +// cached from whatever global is present so that test runners that stub it +// don't break things. But we need to wrap it in a try catch in case it is +// wrapped in strict mode code which doesn't define any globals. It's inside a +// function because try/catches deoptimize in certain engines. + +var cachedSetTimeout; +var cachedClearTimeout; + +function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); +} +function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); +} +(function () { + try { + if (typeof setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } else { + cachedSetTimeout = defaultSetTimout; + } + } catch (e) { + cachedSetTimeout = defaultSetTimout; + } + try { + if (typeof clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } else { + cachedClearTimeout = defaultClearTimeout; + } + } catch (e) { + cachedClearTimeout = defaultClearTimeout; + } +} ()) +function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + +} +function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + +} +var queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; + +function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } +} + +function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); +} + +process.nextTick = function (fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } +}; + +// v8 likes predictible objects +function Item(fun, array) { + this.fun = fun; + this.array = array; +} +Item.prototype.run = function () { + this.fun.apply(null, this.array); +}; +process.title = 'browser'; +process.browser = true; +process.env = {}; +process.argv = []; +process.version = ''; // empty string to avoid regexp issues +process.versions = {}; + +function noop() {} + +process.on = noop; +process.addListener = noop; +process.once = noop; +process.off = noop; +process.removeListener = noop; +process.removeAllListeners = noop; +process.emit = noop; +process.prependListener = noop; +process.prependOnceListener = noop; + +process.listeners = function (name) { return [] } + +process.binding = function (name) { + throw new Error('process.binding is not supported'); +}; + +process.cwd = function () { return '/' }; +process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); +}; +process.umask = function() { return 0; }; + + +/***/ }), + +/***/ "./node_modules/prop-types/checkPropTypes.js": +/*!***************************************************!*\ + !*** ./node_modules/prop-types/checkPropTypes.js ***! + \***************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + + + +var printWarning = function() {}; + +if (true) { + var ReactPropTypesSecret = __webpack_require__(/*! ./lib/ReactPropTypesSecret */ "./node_modules/prop-types/lib/ReactPropTypesSecret.js"); + var loggedTypeFailures = {}; + var has = Function.call.bind(Object.prototype.hasOwnProperty); + + printWarning = function(text) { + var message = 'Warning: ' + text; + if (typeof console !== 'undefined') { + console.error(message); + } + try { + // --- Welcome to debugging React --- + // This error was thrown as a convenience so that you can use this stack + // to find the callsite that caused this warning to fire. + throw new Error(message); + } catch (x) {} + }; +} + +/** + * Assert that the values match with the type specs. + * Error messages are memorized and will only be shown once. + * + * @param {object} typeSpecs Map of name to a ReactPropType + * @param {object} values Runtime values that need to be type-checked + * @param {string} location e.g. "prop", "context", "child context" + * @param {string} componentName Name of the component for error messages. + * @param {?Function} getStack Returns the component stack. + * @private + */ +function checkPropTypes(typeSpecs, values, location, componentName, getStack) { + if (true) { + for (var typeSpecName in typeSpecs) { + if (has(typeSpecs, typeSpecName)) { + var error; + // Prop type validation may throw. In case they do, we don't want to + // fail the render phase where it didn't fail before. So we log it. + // After these have been cleaned up, we'll let them throw. + try { + // This is intentionally an invariant that gets caught. It's the same + // behavior as without this statement except with a better message. + if (typeof typeSpecs[typeSpecName] !== 'function') { + var err = Error( + (componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' + ); + err.name = 'Invariant Violation'; + throw err; + } + error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret); + } catch (ex) { + error = ex; + } + if (error && !(error instanceof Error)) { + printWarning( + (componentName || 'React class') + ': type specification of ' + + location + ' `' + typeSpecName + '` is invalid; the type checker ' + + 'function must return `null` or an `Error` but returned a ' + typeof error + '. ' + + 'You may have forgotten to pass an argument to the type checker ' + + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + + 'shape all require an argument).' + ); + } + if (error instanceof Error && !(error.message in loggedTypeFailures)) { + // Only monitor this failure once because there tends to be a lot of the + // same error. + loggedTypeFailures[error.message] = true; + + var stack = getStack ? getStack() : ''; + + printWarning( + 'Failed ' + location + ' type: ' + error.message + (stack != null ? stack : '') + ); + } + } + } + } +} + +/** + * Resets warning cache when testing. + * + * @private + */ +checkPropTypes.resetWarningCache = function() { + if (true) { + loggedTypeFailures = {}; + } +} + +module.exports = checkPropTypes; + + +/***/ }), + +/***/ "./node_modules/prop-types/factoryWithTypeCheckers.js": +/*!************************************************************!*\ + !*** ./node_modules/prop-types/factoryWithTypeCheckers.js ***! + \************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + + + +var ReactIs = __webpack_require__(/*! react-is */ "./node_modules/react-is/index.js"); +var assign = __webpack_require__(/*! object-assign */ "./node_modules/object-assign/index.js"); + +var ReactPropTypesSecret = __webpack_require__(/*! ./lib/ReactPropTypesSecret */ "./node_modules/prop-types/lib/ReactPropTypesSecret.js"); +var checkPropTypes = __webpack_require__(/*! ./checkPropTypes */ "./node_modules/prop-types/checkPropTypes.js"); + +var has = Function.call.bind(Object.prototype.hasOwnProperty); +var printWarning = function() {}; + +if (true) { + printWarning = function(text) { + var message = 'Warning: ' + text; + if (typeof console !== 'undefined') { + console.error(message); + } + try { + // --- Welcome to debugging React --- + // This error was thrown as a convenience so that you can use this stack + // to find the callsite that caused this warning to fire. + throw new Error(message); + } catch (x) {} + }; +} + +function emptyFunctionThatReturnsNull() { + return null; +} + +module.exports = function(isValidElement, throwOnDirectAccess) { + /* global Symbol */ + var ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator; + var FAUX_ITERATOR_SYMBOL = '@@iterator'; // Before Symbol spec. + + /** + * Returns the iterator method function contained on the iterable object. + * + * Be sure to invoke the function with the iterable as context: + * + * var iteratorFn = getIteratorFn(myIterable); + * if (iteratorFn) { + * var iterator = iteratorFn.call(myIterable); + * ... + * } + * + * @param {?object} maybeIterable + * @return {?function} + */ + function getIteratorFn(maybeIterable) { + var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]); + if (typeof iteratorFn === 'function') { + return iteratorFn; + } + } + + /** + * Collection of methods that allow declaration and validation of props that are + * supplied to React components. Example usage: + * + * var Props = require('ReactPropTypes'); + * var MyArticle = React.createClass({ + * propTypes: { + * // An optional string prop named "description". + * description: Props.string, + * + * // A required enum prop named "category". + * category: Props.oneOf(['News','Photos']).isRequired, + * + * // A prop named "dialog" that requires an instance of Dialog. + * dialog: Props.instanceOf(Dialog).isRequired + * }, + * render: function() { ... } + * }); + * + * A more formal specification of how these methods are used: + * + * type := array|bool|func|object|number|string|oneOf([...])|instanceOf(...) + * decl := ReactPropTypes.{type}(.isRequired)? + * + * Each and every declaration produces a function with the same signature. This + * allows the creation of custom validation functions. For example: + * + * var MyLink = React.createClass({ + * propTypes: { + * // An optional string or URI prop named "href". + * href: function(props, propName, componentName) { + * var propValue = props[propName]; + * if (propValue != null && typeof propValue !== 'string' && + * !(propValue instanceof URI)) { + * return new Error( + * 'Expected a string or an URI for ' + propName + ' in ' + + * componentName + * ); + * } + * } + * }, + * render: function() {...} + * }); + * + * @internal + */ + + var ANONYMOUS = '<>'; + + // Important! + // Keep this list in sync with production version in `./factoryWithThrowingShims.js`. + var ReactPropTypes = { + array: createPrimitiveTypeChecker('array'), + bool: createPrimitiveTypeChecker('boolean'), + func: createPrimitiveTypeChecker('function'), + number: createPrimitiveTypeChecker('number'), + object: createPrimitiveTypeChecker('object'), + string: createPrimitiveTypeChecker('string'), + symbol: createPrimitiveTypeChecker('symbol'), + + any: createAnyTypeChecker(), + arrayOf: createArrayOfTypeChecker, + element: createElementTypeChecker(), + elementType: createElementTypeTypeChecker(), + instanceOf: createInstanceTypeChecker, + node: createNodeChecker(), + objectOf: createObjectOfTypeChecker, + oneOf: createEnumTypeChecker, + oneOfType: createUnionTypeChecker, + shape: createShapeTypeChecker, + exact: createStrictShapeTypeChecker, + }; + + /** + * inlined Object.is polyfill to avoid requiring consumers ship their own + * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is + */ + /*eslint-disable no-self-compare*/ + function is(x, y) { + // SameValue algorithm + if (x === y) { + // Steps 1-5, 7-10 + // Steps 6.b-6.e: +0 != -0 + return x !== 0 || 1 / x === 1 / y; + } else { + // Step 6.a: NaN == NaN + return x !== x && y !== y; + } + } + /*eslint-enable no-self-compare*/ + + /** + * We use an Error-like object for backward compatibility as people may call + * PropTypes directly and inspect their output. However, we don't use real + * Errors anymore. We don't inspect their stack anyway, and creating them + * is prohibitively expensive if they are created too often, such as what + * happens in oneOfType() for any type before the one that matched. + */ + function PropTypeError(message) { + this.message = message; + this.stack = ''; + } + // Make `instanceof Error` still work for returned errors. + PropTypeError.prototype = Error.prototype; + + function createChainableTypeChecker(validate) { + if (true) { + var manualPropTypeCallCache = {}; + var manualPropTypeWarningCount = 0; + } + function checkType(isRequired, props, propName, componentName, location, propFullName, secret) { + componentName = componentName || ANONYMOUS; + propFullName = propFullName || propName; + + if (secret !== ReactPropTypesSecret) { + if (throwOnDirectAccess) { + // New behavior only for users of `prop-types` package + var err = new Error( + 'Calling PropTypes validators directly is not supported by the `prop-types` package. ' + + 'Use `PropTypes.checkPropTypes()` to call them. ' + + 'Read more at http://fb.me/use-check-prop-types' + ); + err.name = 'Invariant Violation'; + throw err; + } else if ( true && typeof console !== 'undefined') { + // Old behavior for people using React.PropTypes + var cacheKey = componentName + ':' + propName; + if ( + !manualPropTypeCallCache[cacheKey] && + // Avoid spamming the console because they are often not actionable except for lib authors + manualPropTypeWarningCount < 3 + ) { + printWarning( + 'You are manually calling a React.PropTypes validation ' + + 'function for the `' + propFullName + '` prop on `' + componentName + '`. This is deprecated ' + + 'and will throw in the standalone `prop-types` package. ' + + 'You may be seeing this warning due to a third-party PropTypes ' + + 'library. See https://fb.me/react-warning-dont-call-proptypes ' + 'for details.' + ); + manualPropTypeCallCache[cacheKey] = true; + manualPropTypeWarningCount++; + } + } + } + if (props[propName] == null) { + if (isRequired) { + if (props[propName] === null) { + return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required ' + ('in `' + componentName + '`, but its value is `null`.')); + } + return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required in ' + ('`' + componentName + '`, but its value is `undefined`.')); + } + return null; + } else { + return validate(props, propName, componentName, location, propFullName); + } + } + + var chainedCheckType = checkType.bind(null, false); + chainedCheckType.isRequired = checkType.bind(null, true); + + return chainedCheckType; + } + + function createPrimitiveTypeChecker(expectedType) { + function validate(props, propName, componentName, location, propFullName, secret) { + var propValue = props[propName]; + var propType = getPropType(propValue); + if (propType !== expectedType) { + // `propValue` being instance of, say, date/regexp, pass the 'object' + // check, but we can offer a more precise error message here rather than + // 'of type `object`'. + var preciseType = getPreciseType(propValue); + + return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + preciseType + '` supplied to `' + componentName + '`, expected ') + ('`' + expectedType + '`.')); + } + return null; + } + return createChainableTypeChecker(validate); + } + + function createAnyTypeChecker() { + return createChainableTypeChecker(emptyFunctionThatReturnsNull); + } + + function createArrayOfTypeChecker(typeChecker) { + function validate(props, propName, componentName, location, propFullName) { + if (typeof typeChecker !== 'function') { + return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside arrayOf.'); + } + var propValue = props[propName]; + if (!Array.isArray(propValue)) { + var propType = getPropType(propValue); + return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an array.')); + } + for (var i = 0; i < propValue.length; i++) { + var error = typeChecker(propValue, i, componentName, location, propFullName + '[' + i + ']', ReactPropTypesSecret); + if (error instanceof Error) { + return error; + } + } + return null; + } + return createChainableTypeChecker(validate); + } + + function createElementTypeChecker() { + function validate(props, propName, componentName, location, propFullName) { + var propValue = props[propName]; + if (!isValidElement(propValue)) { + var propType = getPropType(propValue); + return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected a single ReactElement.')); + } + return null; + } + return createChainableTypeChecker(validate); + } + + function createElementTypeTypeChecker() { + function validate(props, propName, componentName, location, propFullName) { + var propValue = props[propName]; + if (!ReactIs.isValidElementType(propValue)) { + var propType = getPropType(propValue); + return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected a single ReactElement type.')); + } + return null; + } + return createChainableTypeChecker(validate); + } + + function createInstanceTypeChecker(expectedClass) { + function validate(props, propName, componentName, location, propFullName) { + if (!(props[propName] instanceof expectedClass)) { + var expectedClassName = expectedClass.name || ANONYMOUS; + var actualClassName = getClassName(props[propName]); + return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + actualClassName + '` supplied to `' + componentName + '`, expected ') + ('instance of `' + expectedClassName + '`.')); + } + return null; + } + return createChainableTypeChecker(validate); + } + + function createEnumTypeChecker(expectedValues) { + if (!Array.isArray(expectedValues)) { + if (true) { + if (arguments.length > 1) { + printWarning( + 'Invalid arguments supplied to oneOf, expected an array, got ' + arguments.length + ' arguments. ' + + 'A common mistake is to write oneOf(x, y, z) instead of oneOf([x, y, z]).' + ); + } else { + printWarning('Invalid argument supplied to oneOf, expected an array.'); + } + } + return emptyFunctionThatReturnsNull; + } + + function validate(props, propName, componentName, location, propFullName) { + var propValue = props[propName]; + for (var i = 0; i < expectedValues.length; i++) { + if (is(propValue, expectedValues[i])) { + return null; + } + } + + var valuesString = JSON.stringify(expectedValues, function replacer(key, value) { + var type = getPreciseType(value); + if (type === 'symbol') { + return String(value); + } + return value; + }); + return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of value `' + String(propValue) + '` ' + ('supplied to `' + componentName + '`, expected one of ' + valuesString + '.')); + } + return createChainableTypeChecker(validate); + } + + function createObjectOfTypeChecker(typeChecker) { + function validate(props, propName, componentName, location, propFullName) { + if (typeof typeChecker !== 'function') { + return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside objectOf.'); + } + var propValue = props[propName]; + var propType = getPropType(propValue); + if (propType !== 'object') { + return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an object.')); + } + for (var key in propValue) { + if (has(propValue, key)) { + var error = typeChecker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret); + if (error instanceof Error) { + return error; + } + } + } + return null; + } + return createChainableTypeChecker(validate); + } + + function createUnionTypeChecker(arrayOfTypeCheckers) { + if (!Array.isArray(arrayOfTypeCheckers)) { + true ? printWarning('Invalid argument supplied to oneOfType, expected an instance of array.') : undefined; + return emptyFunctionThatReturnsNull; + } + + for (var i = 0; i < arrayOfTypeCheckers.length; i++) { + var checker = arrayOfTypeCheckers[i]; + if (typeof checker !== 'function') { + printWarning( + 'Invalid argument supplied to oneOfType. Expected an array of check functions, but ' + + 'received ' + getPostfixForTypeWarning(checker) + ' at index ' + i + '.' + ); + return emptyFunctionThatReturnsNull; + } + } + + function validate(props, propName, componentName, location, propFullName) { + for (var i = 0; i < arrayOfTypeCheckers.length; i++) { + var checker = arrayOfTypeCheckers[i]; + if (checker(props, propName, componentName, location, propFullName, ReactPropTypesSecret) == null) { + return null; + } + } + + return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`.')); + } + return createChainableTypeChecker(validate); + } + + function createNodeChecker() { + function validate(props, propName, componentName, location, propFullName) { + if (!isNode(props[propName])) { + return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`, expected a ReactNode.')); + } + return null; + } + return createChainableTypeChecker(validate); + } + + function createShapeTypeChecker(shapeTypes) { + function validate(props, propName, componentName, location, propFullName) { + var propValue = props[propName]; + var propType = getPropType(propValue); + if (propType !== 'object') { + return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.')); + } + for (var key in shapeTypes) { + var checker = shapeTypes[key]; + if (!checker) { + continue; + } + var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret); + if (error) { + return error; + } + } + return null; + } + return createChainableTypeChecker(validate); + } + + function createStrictShapeTypeChecker(shapeTypes) { + function validate(props, propName, componentName, location, propFullName) { + var propValue = props[propName]; + var propType = getPropType(propValue); + if (propType !== 'object') { + return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.')); + } + // We need to check all keys in case some are required but missing from + // props. + var allKeys = assign({}, props[propName], shapeTypes); + for (var key in allKeys) { + var checker = shapeTypes[key]; + if (!checker) { + return new PropTypeError( + 'Invalid ' + location + ' `' + propFullName + '` key `' + key + '` supplied to `' + componentName + '`.' + + '\nBad object: ' + JSON.stringify(props[propName], null, ' ') + + '\nValid keys: ' + JSON.stringify(Object.keys(shapeTypes), null, ' ') + ); + } + var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret); + if (error) { + return error; + } + } + return null; + } + + return createChainableTypeChecker(validate); + } + + function isNode(propValue) { + switch (typeof propValue) { + case 'number': + case 'string': + case 'undefined': + return true; + case 'boolean': + return !propValue; + case 'object': + if (Array.isArray(propValue)) { + return propValue.every(isNode); + } + if (propValue === null || isValidElement(propValue)) { + return true; + } + + var iteratorFn = getIteratorFn(propValue); + if (iteratorFn) { + var iterator = iteratorFn.call(propValue); + var step; + if (iteratorFn !== propValue.entries) { + while (!(step = iterator.next()).done) { + if (!isNode(step.value)) { + return false; + } + } + } else { + // Iterator will provide entry [k,v] tuples rather than values. + while (!(step = iterator.next()).done) { + var entry = step.value; + if (entry) { + if (!isNode(entry[1])) { + return false; + } + } + } + } + } else { + return false; + } + + return true; + default: + return false; + } + } + + function isSymbol(propType, propValue) { + // Native Symbol. + if (propType === 'symbol') { + return true; + } + + // falsy value can't be a Symbol + if (!propValue) { + return false; + } + + // 19.4.3.5 Symbol.prototype[@@toStringTag] === 'Symbol' + if (propValue['@@toStringTag'] === 'Symbol') { + return true; + } + + // Fallback for non-spec compliant Symbols which are polyfilled. + if (typeof Symbol === 'function' && propValue instanceof Symbol) { + return true; + } + + return false; + } + + // Equivalent of `typeof` but with special handling for array and regexp. + function getPropType(propValue) { + var propType = typeof propValue; + if (Array.isArray(propValue)) { + return 'array'; + } + if (propValue instanceof RegExp) { + // Old webkits (at least until Android 4.0) return 'function' rather than + // 'object' for typeof a RegExp. We'll normalize this here so that /bla/ + // passes PropTypes.object. + return 'object'; + } + if (isSymbol(propType, propValue)) { + return 'symbol'; + } + return propType; + } + + // This handles more types than `getPropType`. Only used for error messages. + // See `createPrimitiveTypeChecker`. + function getPreciseType(propValue) { + if (typeof propValue === 'undefined' || propValue === null) { + return '' + propValue; + } + var propType = getPropType(propValue); + if (propType === 'object') { + if (propValue instanceof Date) { + return 'date'; + } else if (propValue instanceof RegExp) { + return 'regexp'; + } + } + return propType; + } + + // Returns a string that is postfixed to a warning about an invalid type. + // For example, "undefined" or "of type array" + function getPostfixForTypeWarning(value) { + var type = getPreciseType(value); + switch (type) { + case 'array': + case 'object': + return 'an ' + type; + case 'boolean': + case 'date': + case 'regexp': + return 'a ' + type; + default: + return type; + } + } + + // Returns class name of the object, if any. + function getClassName(propValue) { + if (!propValue.constructor || !propValue.constructor.name) { + return ANONYMOUS; + } + return propValue.constructor.name; + } + + ReactPropTypes.checkPropTypes = checkPropTypes; + ReactPropTypes.resetWarningCache = checkPropTypes.resetWarningCache; + ReactPropTypes.PropTypes = ReactPropTypes; + + return ReactPropTypes; +}; + + +/***/ }), + +/***/ "./node_modules/prop-types/index.js": +/*!******************************************!*\ + !*** ./node_modules/prop-types/index.js ***! + \******************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * Copyright (c) 2013-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +if (true) { + var ReactIs = __webpack_require__(/*! react-is */ "./node_modules/react-is/index.js"); + + // By explicitly using `prop-types` you are opting into new development behavior. + // http://fb.me/prop-types-in-prod + var throwOnDirectAccess = true; + module.exports = __webpack_require__(/*! ./factoryWithTypeCheckers */ "./node_modules/prop-types/factoryWithTypeCheckers.js")(ReactIs.isElement, throwOnDirectAccess); +} else {} + + +/***/ }), + +/***/ "./node_modules/prop-types/lib/ReactPropTypesSecret.js": +/*!*************************************************************!*\ + !*** ./node_modules/prop-types/lib/ReactPropTypesSecret.js ***! + \*************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + + + +var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'; + +module.exports = ReactPropTypesSecret; + + +/***/ }), + +/***/ "./node_modules/queue-microtask/index.js": +/*!***********************************************!*\ + !*** ./node_modules/queue-microtask/index.js ***! + \***********************************************/ +/*! no static exports found */ +/***/ (function(module, exports) { + +/*! queue-microtask. MIT License. Feross Aboukhadijeh */ +let promise + +module.exports = typeof queueMicrotask === 'function' + ? queueMicrotask.bind(globalThis) + // reuse resolved promise, and allocate it lazily + : cb => (promise || (promise = Promise.resolve())) + .then(cb) + .catch(err => setTimeout(() => { throw err }, 0)) + + +/***/ }), + +/***/ "./node_modules/rdf-canonize/lib/AsyncAlgorithm.js": +/*!*********************************************************!*\ + !*** ./node_modules/rdf-canonize/lib/AsyncAlgorithm.js ***! + \*********************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2016-2017 Digital Bazaar, Inc. All rights reserved. + */ + + +const util = __webpack_require__(/*! ./util */ "./node_modules/rdf-canonize/lib/util.js"); + +module.exports = class AsyncAlgorithm { + constructor({ + maxCallStackDepth = 500, + maxTotalCallStackDepth = 0xFFFFFFFF, + // milliseconds + timeSlice = 10 + } = {}) { + this.schedule = {}; + this.schedule.MAX_DEPTH = maxCallStackDepth; + this.schedule.MAX_TOTAL_DEPTH = maxTotalCallStackDepth; + this.schedule.depth = 0; + this.schedule.totalDepth = 0; + this.schedule.timeSlice = timeSlice; + } + + // do some work in a time slice, but in serial + doWork(fn, callback) { + const schedule = this.schedule; + + if(schedule.totalDepth >= schedule.MAX_TOTAL_DEPTH) { + return callback(new Error( + 'Maximum total call stack depth exceeded; canonicalization aborting.')); + } + + (function work() { + if(schedule.depth === schedule.MAX_DEPTH) { + // stack too deep, run on next tick + schedule.depth = 0; + schedule.running = false; + return util.nextTick(work); + } + + // if not yet running, force run + const now = Date.now(); + if(!schedule.running) { + schedule.start = Date.now(); + schedule.deadline = schedule.start + schedule.timeSlice; + } + + // TODO: should also include an estimate of expectedWorkTime + if(now < schedule.deadline) { + schedule.running = true; + schedule.depth++; + schedule.totalDepth++; + return fn((err, result) => { + schedule.depth--; + schedule.totalDepth--; + callback(err, result); + }); + } + + // not enough time left in this slice, run after letting browser + // do some other things + schedule.depth = 0; + schedule.running = false; + util.setImmediate(work); + })(); + } + + // asynchronously loop + forEach(iterable, fn, callback) { + const self = this; + let iterator; + let idx = 0; + let length; + if(Array.isArray(iterable)) { + length = iterable.length; + iterator = () => { + if(idx === length) { + return false; + } + iterator.value = iterable[idx++]; + iterator.key = idx; + return true; + }; + } else { + const keys = Object.keys(iterable); + length = keys.length; + iterator = () => { + if(idx === length) { + return false; + } + iterator.key = keys[idx++]; + iterator.value = iterable[iterator.key]; + return true; + }; + } + + (function iterate(err) { + if(err) { + return callback(err); + } + if(iterator()) { + return self.doWork(() => fn(iterator.value, iterator.key, iterate)); + } + callback(); + })(); + } + + // asynchronous waterfall + waterfall(fns, callback) { + const self = this; + self.forEach( + fns, (fn, idx, callback) => self.doWork(fn, callback), callback); + } + + // asynchronous while + whilst(condition, fn, callback) { + const self = this; + (function loop(err) { + if(err) { + return callback(err); + } + if(!condition()) { + return callback(); + } + self.doWork(fn, loop); + })(); + } +}; + + +/***/ }), + +/***/ "./node_modules/rdf-canonize/lib/IdentifierIssuer.js": +/*!***********************************************************!*\ + !*** ./node_modules/rdf-canonize/lib/IdentifierIssuer.js ***! + \***********************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* + * Copyright (c) 2016-2017 Digital Bazaar, Inc. All rights reserved. + */ + + +const util = __webpack_require__(/*! ./util */ "./node_modules/rdf-canonize/lib/util.js"); + +module.exports = class IdentifierIssuer { + /** + * Creates a new IdentifierIssuer. A IdentifierIssuer issues unique + * identifiers, keeping track of any previously issued identifiers. + * + * @param prefix the prefix to use (''). + */ + constructor(prefix) { + this.prefix = prefix; + this.counter = 0; + this.existing = {}; + } + + /** + * Copies this IdentifierIssuer. + * + * @return a copy of this IdentifierIssuer. + */ + clone() { + const copy = new IdentifierIssuer(this.prefix); + copy.counter = this.counter; + copy.existing = util.clone(this.existing); + return copy; + } + + /** + * Gets the new identifier for the given old identifier, where if no old + * identifier is given a new identifier will be generated. + * + * @param [old] the old identifier to get the new identifier for. + * + * @return the new identifier. + */ + getId(old) { + // return existing old identifier + if(old && old in this.existing) { + return this.existing[old]; + } + + // get next identifier + const identifier = this.prefix + this.counter; + this.counter += 1; + + // save mapping + if(old) { + this.existing[old] = identifier; + } + + return identifier; + } + + /** + * Returns true if the given old identifer has already been assigned a new + * identifier. + * + * @param old the old identifier to check. + * + * @return true if the old identifier has been assigned a new identifier, + * false if not. + */ + hasId(old) { + return (old in this.existing); + } +}; + + +/***/ }), + +/***/ "./node_modules/rdf-canonize/lib/MessageDigest-browser.js": +/*!****************************************************************!*\ + !*** ./node_modules/rdf-canonize/lib/MessageDigest-browser.js ***! + \****************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* + * Copyright (c) 2016-2017 Digital Bazaar, Inc. All rights reserved. + */ + + +const forge = __webpack_require__(/*! node-forge/lib/forge */ "./node_modules/node-forge/lib/forge.js"); +__webpack_require__(/*! node-forge/lib/md */ "./node_modules/node-forge/lib/md.js"); +__webpack_require__(/*! node-forge/lib/sha1 */ "./node_modules/node-forge/lib/sha1.js"); +__webpack_require__(/*! node-forge/lib/sha256 */ "./node_modules/node-forge/lib/sha256.js"); + +module.exports = class MessageDigest { + /** + * Creates a new MessageDigest. + * + * @param algorithm the algorithm to use. + */ + constructor(algorithm) { + this.md = forge.md[algorithm].create(); + } + + update(msg) { + this.md.update(msg, 'utf8'); + } + + digest() { + return this.md.digest().toHex(); + } +}; + + +/***/ }), + +/***/ "./node_modules/rdf-canonize/lib/NQuads.js": +/*!*************************************************!*\ + !*** ./node_modules/rdf-canonize/lib/NQuads.js ***! + \*************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* + * Copyright (c) 2016-2017 Digital Bazaar, Inc. All rights reserved. + */ + + +// eslint-disable-next-line no-unused-vars +const TERMS = ['subject', 'predicate', 'object', 'graph']; +const RDF = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'; +const RDF_LANGSTRING = RDF + 'langString'; +const XSD_STRING = 'http://www.w3.org/2001/XMLSchema#string'; + +// build regexes +const REGEX = {}; +(() => { + const iri = '(?:<([^:]+:[^>]*)>)'; + // https://www.w3.org/TR/turtle/#grammar-production-BLANK_NODE_LABEL + const PN_CHARS_BASE = + 'A-Z' + 'a-z' + + '\u00C0-\u00D6' + + '\u00D8-\u00F6' + + '\u00F8-\u02FF' + + '\u0370-\u037D' + + '\u037F-\u1FFF' + + '\u200C-\u200D' + + '\u2070-\u218F' + + '\u2C00-\u2FEF' + + '\u3001-\uD7FF' + + '\uF900-\uFDCF' + + '\uFDF0-\uFFFD'; + // TODO: + //'\u10000-\uEFFFF'; + const PN_CHARS_U = + PN_CHARS_BASE + + '_'; + const PN_CHARS = + PN_CHARS_U + + '0-9' + + '-' + + '\u00B7' + + '\u0300-\u036F' + + '\u203F-\u2040'; + const BLANK_NODE_LABEL = + '(_:' + + '(?:[' + PN_CHARS_U + '0-9])' + + '(?:(?:[' + PN_CHARS + '.])*(?:[' + PN_CHARS + ']))?' + + ')'; + const bnode = BLANK_NODE_LABEL; + const plain = '"([^"\\\\]*(?:\\\\.[^"\\\\]*)*)"'; + const datatype = '(?:\\^\\^' + iri + ')'; + const language = '(?:@([a-zA-Z]+(?:-[a-zA-Z0-9]+)*))'; + const literal = '(?:' + plain + '(?:' + datatype + '|' + language + ')?)'; + const ws = '[ \\t]+'; + const wso = '[ \\t]*'; + + // define quad part regexes + const subject = '(?:' + iri + '|' + bnode + ')' + ws; + const property = iri + ws; + const object = '(?:' + iri + '|' + bnode + '|' + literal + ')' + wso; + const graphName = '(?:\\.|(?:(?:' + iri + '|' + bnode + ')' + wso + '\\.))'; + + // end of line and empty regexes + REGEX.eoln = /(?:\r\n)|(?:\n)|(?:\r)/g; + REGEX.empty = new RegExp('^' + wso + '$'); + + // full quad regex + REGEX.quad = new RegExp( + '^' + wso + subject + property + object + graphName + wso + '$'); +})(); + +module.exports = class NQuads { + /** + * Parses RDF in the form of N-Quads. + * + * @param input the N-Quads input to parse. + * + * @return an RDF dataset (an array of quads per http://rdf.js.org/). + */ + static parse(input) { + // build RDF dataset + const dataset = []; + + const graphs = {}; + + // split N-Quad input into lines + const lines = input.split(REGEX.eoln); + let lineNumber = 0; + for(const line of lines) { + lineNumber++; + + // skip empty lines + if(REGEX.empty.test(line)) { + continue; + } + + // parse quad + const match = line.match(REGEX.quad); + if(match === null) { + throw new Error('N-Quads parse error on line ' + lineNumber + '.'); + } + + // create RDF quad + const quad = {}; + + // get subject + if(match[1] !== undefined) { + quad.subject = {termType: 'NamedNode', value: match[1]}; + } else { + quad.subject = {termType: 'BlankNode', value: match[2]}; + } + + // get predicate + quad.predicate = {termType: 'NamedNode', value: match[3]}; + + // get object + if(match[4] !== undefined) { + quad.object = {termType: 'NamedNode', value: match[4]}; + } else if(match[5] !== undefined) { + quad.object = {termType: 'BlankNode', value: match[5]}; + } else { + quad.object = { + termType: 'Literal', + value: undefined, + datatype: { + termType: 'NamedNode' + } + }; + if(match[7] !== undefined) { + quad.object.datatype.value = match[7]; + } else if(match[8] !== undefined) { + quad.object.datatype.value = RDF_LANGSTRING; + quad.object.language = match[8]; + } else { + quad.object.datatype.value = XSD_STRING; + } + quad.object.value = _unescape(match[6]); + } + + // get graph + if(match[9] !== undefined) { + quad.graph = { + termType: 'NamedNode', + value: match[9] + }; + } else if(match[10] !== undefined) { + quad.graph = { + termType: 'BlankNode', + value: match[10] + }; + } else { + quad.graph = { + termType: 'DefaultGraph', + value: '' + }; + } + + // only add quad if it is unique in its graph + if(!(quad.graph.value in graphs)) { + graphs[quad.graph.value] = [quad]; + dataset.push(quad); + } else { + let unique = true; + const quads = graphs[quad.graph.value]; + for(const q of quads) { + if(_compareTriples(q, quad)) { + unique = false; + break; + } + } + if(unique) { + quads.push(quad); + dataset.push(quad); + } + } + } + + return dataset; + } + + /** + * Converts an RDF dataset to N-Quads. + * + * @param dataset (array of quads) the RDF dataset to convert. + * + * @return the N-Quads string. + */ + static serialize(dataset) { + if(!Array.isArray(dataset)) { + dataset = NQuads.legacyDatasetToQuads(dataset); + } + const quads = []; + for(const quad of dataset) { + quads.push(NQuads.serializeQuad(quad)); + } + return quads.sort().join(''); + } + + /** + * Converts an RDF quad to an N-Quad string (a single quad). + * + * @param quad the RDF quad convert. + * + * @return the N-Quad string. + */ + static serializeQuad(quad) { + const s = quad.subject; + const p = quad.predicate; + const o = quad.object; + const g = quad.graph; + + let nquad = ''; + + // subject and predicate can only be NamedNode or BlankNode + [s, p].forEach(term => { + if(term.termType === 'NamedNode') { + nquad += '<' + term.value + '>'; + } else { + nquad += term.value; + } + nquad += ' '; + }); + + // object is NamedNode, BlankNode, or Literal + if(o.termType === 'NamedNode') { + nquad += '<' + o.value + '>'; + } else if(o.termType === 'BlankNode') { + nquad += o.value; + } else { + nquad += '"' + _escape(o.value) + '"'; + if(o.datatype.value === RDF_LANGSTRING) { + if(o.language) { + nquad += '@' + o.language; + } + } else if(o.datatype.value !== XSD_STRING) { + nquad += '^^<' + o.datatype.value + '>'; + } + } + + // graph can only be NamedNode or BlankNode (or DefaultGraph, but that + // does not add to `nquad`) + if(g.termType === 'NamedNode') { + nquad += ' <' + g.value + '>'; + } else if(g.termType === 'BlankNode') { + nquad += ' ' + g.value; + } + + nquad += ' .\n'; + return nquad; + } + + /** + * Converts a legacy-formatted dataset to an array of quads dataset per + * http://rdf.js.org/. + * + * @param dataset the legacy dataset to convert. + * + * @return the array of quads dataset. + */ + static legacyDatasetToQuads(dataset) { + const quads = []; + + const termTypeMap = { + 'blank node': 'BlankNode', + IRI: 'NamedNode', + literal: 'Literal' + }; + + for(const graphName in dataset) { + const triples = dataset[graphName]; + triples.forEach(triple => { + const quad = {}; + for(const componentName in triple) { + const oldComponent = triple[componentName]; + const newComponent = { + termType: termTypeMap[oldComponent.type], + value: oldComponent.value + }; + if(newComponent.termType === 'Literal') { + newComponent.datatype = { + termType: 'NamedNode' + }; + if('datatype' in oldComponent) { + newComponent.datatype.value = oldComponent.datatype; + } + if('language' in oldComponent) { + if(!('datatype' in oldComponent)) { + newComponent.datatype.value = RDF_LANGSTRING; + } + newComponent.language = oldComponent.language; + } else if(!('datatype' in oldComponent)) { + newComponent.datatype.value = XSD_STRING; + } + } + quad[componentName] = newComponent; + } + if(graphName === '@default') { + quad.graph = { + termType: 'DefaultGraph', + value: '' + }; + } else { + quad.graph = { + termType: graphName.startsWith('_:') ? 'BlankNode' : 'NamedNode', + value: graphName + }; + } + quads.push(quad); + }); + } + + return quads; + } +}; + +/** + * Compares two RDF triples for equality. + * + * @param t1 the first triple. + * @param t2 the second triple. + * + * @return true if the triples are the same, false if not. + */ +function _compareTriples(t1, t2) { + for(const k in t1) { + if(t1[k].termType !== t2[k].termType || t1[k].value !== t2[k].value) { + return false; + } + } + if(t1.object.termType !== 'Literal') { + return true; + } + return ( + (t1.object.datatype.termType === t2.object.datatype.termType) && + (t1.object.datatype.value === t2.object.datatype.value) && + (t1.object.language === t2.object.language) + ); +} + +const _escapeRegex = /["\\\n\r]/g; +/** + * Escape string to N-Quads literal + */ +function _escape(s) { + return s.replace(_escapeRegex, function(match) { + switch(match) { + case '"': return '\\"'; + case '\\': return '\\\\'; + case '\n': return '\\n'; + case '\r': return '\\r'; + } + }); +} + +const _unescapeRegex = + /(?:\\([tbnrf"'\\]))|(?:\\u([0-9A-Fa-f]{4}))|(?:\\U([0-9A-Fa-f]{8}))/g; +/** + * Unescape N-Quads literal to string + */ +function _unescape(s) { + return s.replace(_unescapeRegex, function(match, code, u, U) { + if(code) { + switch(code) { + case 't': return '\t'; + case 'b': return '\b'; + case 'n': return '\n'; + case 'r': return '\r'; + case 'f': return '\f'; + case '"': return '"'; + case '\'': return '\''; + case '\\': return '\\'; + } + } + if(u) { + return String.fromCharCode(parseInt(u, 16)); + } + if(U) { + // FIXME: support larger values + throw new Error('Unsupported U escape'); + } + }); +} + + +/***/ }), + +/***/ "./node_modules/rdf-canonize/lib/Permutator.js": +/*!*****************************************************!*\ + !*** ./node_modules/rdf-canonize/lib/Permutator.js ***! + \*****************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* + * Copyright (c) 2016-2017 Digital Bazaar, Inc. All rights reserved. + */ + + +// TODO: convert to ES6 iterable + +module.exports = class Permutator { + /** + * A Permutator iterates over all possible permutations of the given array + * of elements. + * + * @param list the array of elements to iterate over. + */ + constructor(list) { + // original array + this.list = list.sort(); + // indicates whether there are more permutations + this.done = false; + // directional info for permutation algorithm + this.left = {}; + for(let i = 0; i < list.length; ++i) { + this.left[list[i]] = true; + } + } + + /** + * Returns true if there is another permutation. + * + * @return true if there is another permutation, false if not. + */ + hasNext() { + return !this.done; + } + + /** + * Gets the next permutation. Call hasNext() to ensure there is another one + * first. + * + * @return the next permutation. + */ + next() { + // copy current permutation + const rval = this.list.slice(); + + /* Calculate the next permutation using the Steinhaus-Johnson-Trotter + permutation algorithm. */ + + // get largest mobile element k + // (mobile: element is greater than the one it is looking at) + let k = null; + let pos = 0; + const length = this.list.length; + for(let i = 0; i < length; ++i) { + const element = this.list[i]; + const left = this.left[element]; + if((k === null || element > k) && + ((left && i > 0 && element > this.list[i - 1]) || + (!left && i < (length - 1) && element > this.list[i + 1]))) { + k = element; + pos = i; + } + } + + // no more permutations + if(k === null) { + this.done = true; + } else { + // swap k and the element it is looking at + const swap = this.left[k] ? pos - 1 : pos + 1; + this.list[pos] = this.list[swap]; + this.list[swap] = k; + + // reverse the direction of all elements larger than k + for(let i = 0; i < length; ++i) { + if(this.list[i] > k) { + this.left[this.list[i]] = !this.left[this.list[i]]; + } + } + } + + return rval; + } +}; + + + +/***/ }), + +/***/ "./node_modules/rdf-canonize/lib/URDNA2015.js": +/*!****************************************************!*\ + !*** ./node_modules/rdf-canonize/lib/URDNA2015.js ***! + \****************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* + * Copyright (c) 2016-2017 Digital Bazaar, Inc. All rights reserved. + */ + + +const AsyncAlgorithm = __webpack_require__(/*! ./AsyncAlgorithm */ "./node_modules/rdf-canonize/lib/AsyncAlgorithm.js"); +const IdentifierIssuer = __webpack_require__(/*! ./IdentifierIssuer */ "./node_modules/rdf-canonize/lib/IdentifierIssuer.js"); +const MessageDigest = __webpack_require__(/*! ./MessageDigest */ "./node_modules/rdf-canonize/lib/MessageDigest-browser.js"); +const Permutator = __webpack_require__(/*! ./Permutator */ "./node_modules/rdf-canonize/lib/Permutator.js"); +const NQuads = __webpack_require__(/*! ./NQuads */ "./node_modules/rdf-canonize/lib/NQuads.js"); +const util = __webpack_require__(/*! ./util */ "./node_modules/rdf-canonize/lib/util.js"); + +const POSITIONS = {subject: 's', object: 'o', graph: 'g'}; + +module.exports = class URDNA2015 extends AsyncAlgorithm { + constructor(options) { + options = options || {}; + super(options); + this.name = 'URDNA2015'; + this.options = Object.assign({}, options); + this.blankNodeInfo = {}; + this.hashToBlankNodes = {}; + this.canonicalIssuer = new IdentifierIssuer('_:c14n'); + this.hashAlgorithm = 'sha256'; + this.quads; + } + + // 4.4) Normalization Algorithm + main(dataset, callback) { + const self = this; + self.schedule.start = Date.now(); + let result; + self.quads = dataset; + + // 1) Create the normalization state. + + // Note: Optimize by generating non-normalized blank node map concurrently. + const nonNormalized = {}; + + self.waterfall([ + callback => { + // 2) For every quad in input dataset: + self.forEach(dataset, (quad, idx, callback) => { + // 2.1) For each blank node that occurs in the quad, add a reference + // to the quad using the blank node identifier in the blank node to + // quads map, creating a new entry if necessary. + self.forEachComponent(quad, component => { + if(component.termType !== 'BlankNode') { + return; + } + const id = component.value; + if(id in self.blankNodeInfo) { + self.blankNodeInfo[id].quads.push(quad); + } else { + nonNormalized[id] = true; + self.blankNodeInfo[id] = {quads: [quad]}; + } + }); + + callback(); + }, callback); + }, + callback => { + // 3) Create a list of non-normalized blank node identifiers + // non-normalized identifiers and populate it using the keys from the + // blank node to quads map. + // Note: We use a map here and it was generated during step 2. + + // 4) Initialize simple, a boolean flag, to true. + let simple = true; + + // 5) While simple is true, issue canonical identifiers for blank nodes: + self.whilst(() => simple, callback => { + // 5.1) Set simple to false. + simple = false; + + // 5.2) Clear hash to blank nodes map. + self.hashToBlankNodes = {}; + + self.waterfall([ + callback => { + // 5.3) For each blank node identifier identifier in + // non-normalized identifiers: + self.forEach(nonNormalized, (value, id, callback) => { + // 5.3.1) Create a hash, hash, according to the Hash First + // Degree Quads algorithm. + self.hashFirstDegreeQuads(id, (err, hash) => { + if(err) { + return callback(err); + } + // 5.3.2) Add hash and identifier to hash to blank nodes map, + // creating a new entry if necessary. + if(hash in self.hashToBlankNodes) { + self.hashToBlankNodes[hash].push(id); + } else { + self.hashToBlankNodes[hash] = [id]; + } + callback(); + }); + }, callback); + }, + callback => { + // 5.4) For each hash to identifier list mapping in hash to blank + // nodes map, lexicographically-sorted by hash: + const hashes = Object.keys(self.hashToBlankNodes).sort(); + self.forEach(hashes, (hash, i, callback) => { + // 5.4.1) If the length of identifier list is greater than 1, + // continue to the next mapping. + const idList = self.hashToBlankNodes[hash]; + if(idList.length > 1) { + return callback(); + } + + // 5.4.2) Use the Issue Identifier algorithm, passing canonical + // issuer and the single blank node identifier in identifier + // list, identifier, to issue a canonical replacement identifier + // for identifier. + // TODO: consider changing `getId` to `issue` + const id = idList[0]; + self.canonicalIssuer.getId(id); + + // 5.4.3) Remove identifier from non-normalized identifiers. + delete nonNormalized[id]; + + // 5.4.4) Remove hash from the hash to blank nodes map. + delete self.hashToBlankNodes[hash]; + + // 5.4.5) Set simple to true. + simple = true; + callback(); + }, callback); + } + ], callback); + }, callback); + }, + callback => { + // 6) For each hash to identifier list mapping in hash to blank nodes + // map, lexicographically-sorted by hash: + const hashes = Object.keys(self.hashToBlankNodes).sort(); + self.forEach(hashes, (hash, idx, callback) => { + // 6.1) Create hash path list where each item will be a result of + // running the Hash N-Degree Quads algorithm. + const hashPathList = []; + + // 6.2) For each blank node identifier identifier in identifier list: + const idList = self.hashToBlankNodes[hash]; + self.waterfall([ + callback => { + self.forEach(idList, (id, idx, callback) => { + // 6.2.1) If a canonical identifier has already been issued for + // identifier, continue to the next identifier. + if(self.canonicalIssuer.hasId(id)) { + return callback(); + } + + // 6.2.2) Create temporary issuer, an identifier issuer + // initialized with the prefix _:b. + const issuer = new IdentifierIssuer('_:b'); + + // 6.2.3) Use the Issue Identifier algorithm, passing temporary + // issuer and identifier, to issue a new temporary blank node + // identifier for identifier. + issuer.getId(id); + + // 6.2.4) Run the Hash N-Degree Quads algorithm, passing + // temporary issuer, and append the result to the hash path + // list. + self.hashNDegreeQuads(id, issuer, (err, result) => { + if(err) { + return callback(err); + } + hashPathList.push(result); + callback(); + }); + }, callback); + }, + callback => { + // 6.3) For each result in the hash path list, + // lexicographically-sorted by the hash in result: + // TODO: use `String.localeCompare`? + hashPathList.sort((a, b) => + (a.hash < b.hash) ? -1 : ((a.hash > b.hash) ? 1 : 0)); + self.forEach(hashPathList, (result, idx, callback) => { + // 6.3.1) For each blank node identifier, existing identifier, + // that was issued a temporary identifier by identifier issuer + // in result, issue a canonical identifier, in the same order, + // using the Issue Identifier algorithm, passing canonical + // issuer and existing identifier. + for(const existing in result.issuer.existing) { + self.canonicalIssuer.getId(existing); + } + callback(); + }, callback); + } + ], callback); + }, callback); + }, callback => { + /* Note: At this point all blank nodes in the set of RDF quads have been + assigned canonical identifiers, which have been stored in the canonical + issuer. Here each quad is updated by assigning each of its blank nodes + its new identifier. */ + + // 7) For each quad, quad, in input dataset: + const normalized = []; + self.waterfall([ + callback => { + self.forEach(self.quads, (quad, idx, callback) => { + // 7.1) Create a copy, quad copy, of quad and replace any existing + // blank node identifiers using the canonical identifiers + // previously issued by canonical issuer. + // Note: We optimize away the copy here. + self.forEachComponent(quad, component => { + if(component.termType === 'BlankNode' && + !component.value.startsWith(self.canonicalIssuer.prefix)) { + component.value = self.canonicalIssuer.getId(component.value); + } + }); + // 7.2) Add quad copy to the normalized dataset. + normalized.push(NQuads.serializeQuad(quad)); + callback(); + }, callback); + }, + callback => { + // sort normalized output + normalized.sort(); + + // 8) Return the normalized dataset. + result = normalized.join(''); + return callback(); + } + ], callback); + } + ], err => callback(err, result)); + } + + // 4.6) Hash First Degree Quads + hashFirstDegreeQuads(id, callback) { + const self = this; + + // return cached hash + const info = self.blankNodeInfo[id]; + if('hash' in info) { + return callback(null, info.hash); + } + + // 1) Initialize nquads to an empty list. It will be used to store quads in + // N-Quads format. + const nquads = []; + + // 2) Get the list of quads quads associated with the reference blank node + // identifier in the blank node to quads map. + const quads = info.quads; + + // 3) For each quad quad in quads: + self.forEach(quads, (quad, idx, callback) => { + // 3.1) Serialize the quad in N-Quads format with the following special + // rule: + + // 3.1.1) If any component in quad is an blank node, then serialize it + // using a special identifier as follows: + const copy = {predicate: quad.predicate}; + self.forEachComponent(quad, (component, key) => { + // 3.1.2) If the blank node's existing blank node identifier matches the + // reference blank node identifier then use the blank node identifier + // _:a, otherwise, use the blank node identifier _:z. + copy[key] = self.modifyFirstDegreeComponent(id, component, key); + }); + nquads.push(NQuads.serializeQuad(copy)); + callback(); + }, err => { + if(err) { + return callback(err); + } + // 4) Sort nquads in lexicographical order. + nquads.sort(); + + // 5) Return the hash that results from passing the sorted, joined nquads + // through the hash algorithm. + const md = new MessageDigest(self.hashAlgorithm); + for(let i = 0; i < nquads.length; ++i) { + md.update(nquads[i]); + } + // TODO: represent as byte buffer instead to cut memory usage in half + info.hash = md.digest(); + callback(null, info.hash); + }); + } + + // 4.7) Hash Related Blank Node + hashRelatedBlankNode(related, quad, issuer, position, callback) { + const self = this; + + // 1) Set the identifier to use for related, preferring first the canonical + // identifier for related if issued, second the identifier issued by issuer + // if issued, and last, if necessary, the result of the Hash First Degree + // Quads algorithm, passing related. + let id; + self.waterfall([ + callback => { + if(self.canonicalIssuer.hasId(related)) { + id = self.canonicalIssuer.getId(related); + return callback(); + } + if(issuer.hasId(related)) { + id = issuer.getId(related); + return callback(); + } + self.hashFirstDegreeQuads(related, (err, hash) => { + if(err) { + return callback(err); + } + id = hash; + callback(); + }); + } + ], err => { + if(err) { + return callback(err); + } + + // 2) Initialize a string input to the value of position. + // Note: We use a hash object instead. + const md = new MessageDigest(self.hashAlgorithm); + md.update(position); + + // 3) If position is not g, append <, the value of the predicate in quad, + // and > to input. + if(position !== 'g') { + md.update(self.getRelatedPredicate(quad)); + } + + // 4) Append identifier to input. + md.update(id); + + // 5) Return the hash that results from passing input through the hash + // algorithm. + // TODO: represent as byte buffer instead to cut memory usage in half + return callback(null, md.digest()); + }); + } + + // 4.8) Hash N-Degree Quads + hashNDegreeQuads(id, issuer, callback) { + const self = this; + + // 1) Create a hash to related blank nodes map for storing hashes that + // identify related blank nodes. + // Note: 2) and 3) handled within `createHashToRelated` + let hashToRelated; + const md = new MessageDigest(self.hashAlgorithm); + self.waterfall([ + callback => self.createHashToRelated(id, issuer, (err, result) => { + if(err) { + return callback(err); + } + hashToRelated = result; + callback(); + }), + callback => { + // 4) Create an empty string, data to hash. + // Note: We created a hash object `md` above instead. + + // 5) For each related hash to blank node list mapping in hash to + // related blank nodes map, sorted lexicographically by related hash: + const hashes = Object.keys(hashToRelated).sort(); + self.forEach(hashes, (hash, idx, callback) => { + // 5.1) Append the related hash to the data to hash. + md.update(hash); + + // 5.2) Create a string chosen path. + let chosenPath = ''; + + // 5.3) Create an unset chosen issuer variable. + let chosenIssuer; + + // 5.4) For each permutation of blank node list: + const permutator = new Permutator(hashToRelated[hash]); + self.whilst(() => permutator.hasNext(), nextPermutation => { + const permutation = permutator.next(); + + // 5.4.1) Create a copy of issuer, issuer copy. + let issuerCopy = issuer.clone(); + + // 5.4.2) Create a string path. + let path = ''; + + // 5.4.3) Create a recursion list, to store blank node identifiers + // that must be recursively processed by this algorithm. + const recursionList = []; + + self.waterfall([ + callback => { + // 5.4.4) For each related in permutation: + self.forEach(permutation, (related, idx, callback) => { + // 5.4.4.1) If a canonical identifier has been issued for + // related, append it to path. + if(self.canonicalIssuer.hasId(related)) { + path += self.canonicalIssuer.getId(related); + } else { + // 5.4.4.2) Otherwise: + // 5.4.4.2.1) If issuer copy has not issued an identifier + // for related, append related to recursion list. + if(!issuerCopy.hasId(related)) { + recursionList.push(related); + } + // 5.4.4.2.2) Use the Issue Identifier algorithm, passing + // issuer copy and related and append the result to path. + path += issuerCopy.getId(related); + } + + // 5.4.4.3) If chosen path is not empty and the length of path + // is greater than or equal to the length of chosen path and + // path is lexicographically greater than chosen path, then + // skip to the next permutation. + // Note: Comparing path length to chosen path length can be + // optimized away; only compare lexicographically. + if(chosenPath.length !== 0 && path > chosenPath) { + // FIXME: may cause inaccurate total depth calculation + return nextPermutation(); + } + callback(); + }, callback); + }, + callback => { + // 5.4.5) For each related in recursion list: + self.forEach(recursionList, (related, idx, callback) => { + // 5.4.5.1) Set result to the result of recursively executing + // the Hash N-Degree Quads algorithm, passing related for + // identifier and issuer copy for path identifier issuer. + self.hashNDegreeQuads(related, issuerCopy, (err, result) => { + if(err) { + return callback(err); + } + + // 5.4.5.2) Use the Issue Identifier algorithm, passing + // issuer copy and related and append the result to path. + path += issuerCopy.getId(related); + + // 5.4.5.3) Append <, the hash in result, and > to path. + path += '<' + result.hash + '>'; + + // 5.4.5.4) Set issuer copy to the identifier issuer in + // result. + issuerCopy = result.issuer; + + // 5.4.5.5) If chosen path is not empty and the length of + // path is greater than or equal to the length of chosen + // path and path is lexicographically greater than chosen + // path, then skip to the next permutation. + // Note: Comparing path length to chosen path length can be + // optimized away; only compare lexicographically. + if(chosenPath.length !== 0 && path > chosenPath) { + // FIXME: may cause inaccurate total depth calculation + return nextPermutation(); + } + callback(); + }); + }, callback); + }, + callback => { + // 5.4.6) If chosen path is empty or path is lexicographically + // less than chosen path, set chosen path to path and chosen + // issuer to issuer copy. + if(chosenPath.length === 0 || path < chosenPath) { + chosenPath = path; + chosenIssuer = issuerCopy; + } + callback(); + } + ], nextPermutation); + }, err => { + if(err) { + return callback(err); + } + + // 5.5) Append chosen path to data to hash. + md.update(chosenPath); + + // 5.6) Replace issuer, by reference, with chosen issuer. + issuer = chosenIssuer; + callback(); + }); + }, callback); + } + ], err => { + // 6) Return issuer and the hash that results from passing data to hash + // through the hash algorithm. + callback(err, {hash: md.digest(), issuer}); + }); + } + + // helper for modifying component during Hash First Degree Quads + modifyFirstDegreeComponent(id, component) { + if(component.termType !== 'BlankNode') { + return component; + } + component = util.clone(component); + component.value = (component.value === id ? '_:a' : '_:z'); + return component; + } + + // helper for getting a related predicate + getRelatedPredicate(quad) { + return '<' + quad.predicate.value + '>'; + } + + // helper for creating hash to related blank nodes map + createHashToRelated(id, issuer, callback) { + const self = this; + + // 1) Create a hash to related blank nodes map for storing hashes that + // identify related blank nodes. + const hashToRelated = {}; + + // 2) Get a reference, quads, to the list of quads in the blank node to + // quads map for the key identifier. + const quads = self.blankNodeInfo[id].quads; + + // 3) For each quad in quads: + self.forEach(quads, (quad, idx, callback) => { + // 3.1) For each component in quad, if component is the subject, object, + // and graph name and it is a blank node that is not identified by + // identifier: + self.forEach(quad, (component, key, callback) => { + if(key === 'predicate' || + !(component.termType === 'BlankNode' && component.value !== id)) { + return callback(); + } + // 3.1.1) Set hash to the result of the Hash Related Blank Node + // algorithm, passing the blank node identifier for component as + // related, quad, path identifier issuer as issuer, and position as + // either s, o, or g based on whether component is a subject, object, + // graph name, respectively. + const related = component.value; + const position = POSITIONS[key]; + self.hashRelatedBlankNode( + related, quad, issuer, position, (err, hash) => { + if(err) { + return callback(err); + } + // 3.1.2) Add a mapping of hash to the blank node identifier for + // component to hash to related blank nodes map, adding an entry as + // necessary. + if(hash in hashToRelated) { + hashToRelated[hash].push(related); + } else { + hashToRelated[hash] = [related]; + } + callback(); + }); + }, callback); + }, err => callback(err, hashToRelated)); + } + + // helper that iterates over quad components (skips predicate) + forEachComponent(quad, op) { + for(const key in quad) { + // skip `predicate` + if(key === 'predicate') { + continue; + } + op(quad[key], key, quad); + } + } +}; + + +/***/ }), + +/***/ "./node_modules/rdf-canonize/lib/URDNA2015Sync.js": +/*!********************************************************!*\ + !*** ./node_modules/rdf-canonize/lib/URDNA2015Sync.js ***! + \********************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* + * Copyright (c) 2016 Digital Bazaar, Inc. All rights reserved. + */ + + +const IdentifierIssuer = __webpack_require__(/*! ./IdentifierIssuer */ "./node_modules/rdf-canonize/lib/IdentifierIssuer.js"); +const MessageDigest = __webpack_require__(/*! ./MessageDigest */ "./node_modules/rdf-canonize/lib/MessageDigest-browser.js"); +const Permutator = __webpack_require__(/*! ./Permutator */ "./node_modules/rdf-canonize/lib/Permutator.js"); +const NQuads = __webpack_require__(/*! ./NQuads */ "./node_modules/rdf-canonize/lib/NQuads.js"); +const util = __webpack_require__(/*! ./util */ "./node_modules/rdf-canonize/lib/util.js"); + +const POSITIONS = {subject: 's', object: 'o', graph: 'g'}; + +module.exports = class URDNA2015Sync { + constructor() { + this.name = 'URDNA2015'; + this.blankNodeInfo = {}; + this.hashToBlankNodes = {}; + this.canonicalIssuer = new IdentifierIssuer('_:c14n'); + this.hashAlgorithm = 'sha256'; + this.quads; + } + + // 4.4) Normalization Algorithm + main(dataset) { + const self = this; + self.quads = dataset; + + // 1) Create the normalization state. + + // Note: Optimize by generating non-normalized blank node map concurrently. + const nonNormalized = {}; + + // 2) For every quad in input dataset: + for(const quad of dataset) { + // 2.1) For each blank node that occurs in the quad, add a reference + // to the quad using the blank node identifier in the blank node to + // quads map, creating a new entry if necessary. + self.forEachComponent(quad, component => { + if(component.termType !== 'BlankNode') { + return; + } + const id = component.value; + if(id in self.blankNodeInfo) { + self.blankNodeInfo[id].quads.push(quad); + } else { + nonNormalized[id] = true; + self.blankNodeInfo[id] = {quads: [quad]}; + } + }); + } + + // 3) Create a list of non-normalized blank node identifiers + // non-normalized identifiers and populate it using the keys from the + // blank node to quads map. + // Note: We use a map here and it was generated during step 2. + + // 4) Initialize simple, a boolean flag, to true. + let simple = true; + + // 5) While simple is true, issue canonical identifiers for blank nodes: + while(simple) { + // 5.1) Set simple to false. + simple = false; + + // 5.2) Clear hash to blank nodes map. + self.hashToBlankNodes = {}; + + // 5.3) For each blank node identifier identifier in non-normalized + // identifiers: + for(const id in nonNormalized) { + // 5.3.1) Create a hash, hash, according to the Hash First Degree + // Quads algorithm. + const hash = self.hashFirstDegreeQuads(id); + + // 5.3.2) Add hash and identifier to hash to blank nodes map, + // creating a new entry if necessary. + if(hash in self.hashToBlankNodes) { + self.hashToBlankNodes[hash].push(id); + } else { + self.hashToBlankNodes[hash] = [id]; + } + } + + // 5.4) For each hash to identifier list mapping in hash to blank + // nodes map, lexicographically-sorted by hash: + const hashes = Object.keys(self.hashToBlankNodes).sort(); + for(let i = 0; i < hashes.length; ++i) { + // 5.4.1) If the length of identifier list is greater than 1, + // continue to the next mapping. + const hash = hashes[i]; + const idList = self.hashToBlankNodes[hash]; + if(idList.length > 1) { + continue; + } + + // 5.4.2) Use the Issue Identifier algorithm, passing canonical + // issuer and the single blank node identifier in identifier + // list, identifier, to issue a canonical replacement identifier + // for identifier. + // TODO: consider changing `getId` to `issue` + const id = idList[0]; + self.canonicalIssuer.getId(id); + + // 5.4.3) Remove identifier from non-normalized identifiers. + delete nonNormalized[id]; + + // 5.4.4) Remove hash from the hash to blank nodes map. + delete self.hashToBlankNodes[hash]; + + // 5.4.5) Set simple to true. + simple = true; + } + } + + // 6) For each hash to identifier list mapping in hash to blank nodes map, + // lexicographically-sorted by hash: + const hashes = Object.keys(self.hashToBlankNodes).sort(); + for(let i = 0; i < hashes.length; ++i) { + // 6.1) Create hash path list where each item will be a result of + // running the Hash N-Degree Quads algorithm. + const hashPathList = []; + + // 6.2) For each blank node identifier identifier in identifier list: + const hash = hashes[i]; + const idList = self.hashToBlankNodes[hash]; + for(let j = 0; j < idList.length; ++j) { + // 6.2.1) If a canonical identifier has already been issued for + // identifier, continue to the next identifier. + const id = idList[j]; + if(self.canonicalIssuer.hasId(id)) { + continue; + } + + // 6.2.2) Create temporary issuer, an identifier issuer + // initialized with the prefix _:b. + const issuer = new IdentifierIssuer('_:b'); + + // 6.2.3) Use the Issue Identifier algorithm, passing temporary + // issuer and identifier, to issue a new temporary blank node + // identifier for identifier. + issuer.getId(id); + + // 6.2.4) Run the Hash N-Degree Quads algorithm, passing + // temporary issuer, and append the result to the hash path list. + const result = self.hashNDegreeQuads(id, issuer); + hashPathList.push(result); + } + + // 6.3) For each result in the hash path list, + // lexicographically-sorted by the hash in result: + // TODO: use `String.localeCompare`? + hashPathList.sort((a, b) => + (a.hash < b.hash) ? -1 : ((a.hash > b.hash) ? 1 : 0)); + for(let j = 0; j < hashPathList.length; ++j) { + // 6.3.1) For each blank node identifier, existing identifier, + // that was issued a temporary identifier by identifier issuer + // in result, issue a canonical identifier, in the same order, + // using the Issue Identifier algorithm, passing canonical + // issuer and existing identifier. + const result = hashPathList[j]; + for(const existing in result.issuer.existing) { + self.canonicalIssuer.getId(existing); + } + } + } + + /* Note: At this point all blank nodes in the set of RDF quads have been + assigned canonical identifiers, which have been stored in the canonical + issuer. Here each quad is updated by assigning each of its blank nodes + its new identifier. */ + + // 7) For each quad, quad, in input dataset: + const normalized = []; + for(let i = 0; i < self.quads.length; ++i) { + // 7.1) Create a copy, quad copy, of quad and replace any existing + // blank node identifiers using the canonical identifiers + // previously issued by canonical issuer. + // Note: We optimize away the copy here. + const quad = self.quads[i]; + self.forEachComponent(quad, component => { + if(component.termType === 'BlankNode' && + !component.value.startsWith(self.canonicalIssuer.prefix)) { + component.value = self.canonicalIssuer.getId(component.value); + } + }); + // 7.2) Add quad copy to the normalized dataset. + normalized.push(NQuads.serializeQuad(quad)); + } + + // sort normalized output + normalized.sort(); + + // 8) Return the normalized dataset. + return normalized.join(''); + } + + // 4.6) Hash First Degree Quads + hashFirstDegreeQuads(id) { + const self = this; + + // return cached hash + const info = self.blankNodeInfo[id]; + if('hash' in info) { + return info.hash; + } + + // 1) Initialize nquads to an empty list. It will be used to store quads in + // N-Quads format. + const nquads = []; + + // 2) Get the list of quads `quads` associated with the reference blank node + // identifier in the blank node to quads map. + const quads = info.quads; + + // 3) For each quad `quad` in `quads`: + for(let i = 0; i < quads.length; ++i) { + const quad = quads[i]; + + // 3.1) Serialize the quad in N-Quads format with the following special + // rule: + + // 3.1.1) If any component in quad is an blank node, then serialize it + // using a special identifier as follows: + const copy = {predicate: quad.predicate}; + self.forEachComponent(quad, (component, key) => { + // 3.1.2) If the blank node's existing blank node identifier matches + // the reference blank node identifier then use the blank node + // identifier _:a, otherwise, use the blank node identifier _:z. + copy[key] = self.modifyFirstDegreeComponent(id, component, key); + }); + nquads.push(NQuads.serializeQuad(copy)); + } + + // 4) Sort nquads in lexicographical order. + nquads.sort(); + + // 5) Return the hash that results from passing the sorted, joined nquads + // through the hash algorithm. + const md = new MessageDigest(self.hashAlgorithm); + for(let i = 0; i < nquads.length; ++i) { + md.update(nquads[i]); + } + // TODO: represent as byte buffer instead to cut memory usage in half + info.hash = md.digest(); + return info.hash; + } + + // 4.7) Hash Related Blank Node + hashRelatedBlankNode(related, quad, issuer, position) { + const self = this; + + // 1) Set the identifier to use for related, preferring first the canonical + // identifier for related if issued, second the identifier issued by issuer + // if issued, and last, if necessary, the result of the Hash First Degree + // Quads algorithm, passing related. + let id; + if(self.canonicalIssuer.hasId(related)) { + id = self.canonicalIssuer.getId(related); + } else if(issuer.hasId(related)) { + id = issuer.getId(related); + } else { + id = self.hashFirstDegreeQuads(related); + } + + // 2) Initialize a string input to the value of position. + // Note: We use a hash object instead. + const md = new MessageDigest(self.hashAlgorithm); + md.update(position); + + // 3) If position is not g, append <, the value of the predicate in quad, + // and > to input. + if(position !== 'g') { + md.update(self.getRelatedPredicate(quad)); + } + + // 4) Append identifier to input. + md.update(id); + + // 5) Return the hash that results from passing input through the hash + // algorithm. + // TODO: represent as byte buffer instead to cut memory usage in half + return md.digest(); + } + + // 4.8) Hash N-Degree Quads + hashNDegreeQuads(id, issuer) { + const self = this; + + // 1) Create a hash to related blank nodes map for storing hashes that + // identify related blank nodes. + // Note: 2) and 3) handled within `createHashToRelated` + const md = new MessageDigest(self.hashAlgorithm); + const hashToRelated = self.createHashToRelated(id, issuer); + + // 4) Create an empty string, data to hash. + // Note: We created a hash object `md` above instead. + + // 5) For each related hash to blank node list mapping in hash to related + // blank nodes map, sorted lexicographically by related hash: + const hashes = Object.keys(hashToRelated).sort(); + for(let i = 0; i < hashes.length; ++i) { + // 5.1) Append the related hash to the data to hash. + const hash = hashes[i]; + md.update(hash); + + // 5.2) Create a string chosen path. + let chosenPath = ''; + + // 5.3) Create an unset chosen issuer variable. + let chosenIssuer; + + // 5.4) For each permutation of blank node list: + const permutator = new Permutator(hashToRelated[hash]); + while(permutator.hasNext()) { + const permutation = permutator.next(); + + // 5.4.1) Create a copy of issuer, issuer copy. + let issuerCopy = issuer.clone(); + + // 5.4.2) Create a string path. + let path = ''; + + // 5.4.3) Create a recursion list, to store blank node identifiers + // that must be recursively processed by this algorithm. + const recursionList = []; + + // 5.4.4) For each related in permutation: + let nextPermutation = false; + for(let j = 0; j < permutation.length; ++j) { + // 5.4.4.1) If a canonical identifier has been issued for + // related, append it to path. + const related = permutation[j]; + if(self.canonicalIssuer.hasId(related)) { + path += self.canonicalIssuer.getId(related); + } else { + // 5.4.4.2) Otherwise: + // 5.4.4.2.1) If issuer copy has not issued an identifier for + // related, append related to recursion list. + if(!issuerCopy.hasId(related)) { + recursionList.push(related); + } + // 5.4.4.2.2) Use the Issue Identifier algorithm, passing + // issuer copy and related and append the result to path. + path += issuerCopy.getId(related); + } + + // 5.4.4.3) If chosen path is not empty and the length of path + // is greater than or equal to the length of chosen path and + // path is lexicographically greater than chosen path, then + // skip to the next permutation. + // Note: Comparing path length to chosen path length can be optimized + // away; only compare lexicographically. + if(chosenPath.length !== 0 && path > chosenPath) { + nextPermutation = true; + break; + } + } + + if(nextPermutation) { + continue; + } + + // 5.4.5) For each related in recursion list: + for(let j = 0; j < recursionList.length; ++j) { + // 5.4.5.1) Set result to the result of recursively executing + // the Hash N-Degree Quads algorithm, passing related for + // identifier and issuer copy for path identifier issuer. + const related = recursionList[j]; + const result = self.hashNDegreeQuads(related, issuerCopy); + + // 5.4.5.2) Use the Issue Identifier algorithm, passing issuer + // copy and related and append the result to path. + path += issuerCopy.getId(related); + + // 5.4.5.3) Append <, the hash in result, and > to path. + path += '<' + result.hash + '>'; + + // 5.4.5.4) Set issuer copy to the identifier issuer in + // result. + issuerCopy = result.issuer; + + // 5.4.5.5) If chosen path is not empty and the length of path + // is greater than or equal to the length of chosen path and + // path is lexicographically greater than chosen path, then + // skip to the next permutation. + // Note: Comparing path length to chosen path length can be optimized + // away; only compare lexicographically. + if(chosenPath.length !== 0 && path > chosenPath) { + nextPermutation = true; + break; + } + } + + if(nextPermutation) { + continue; + } + + // 5.4.6) If chosen path is empty or path is lexicographically + // less than chosen path, set chosen path to path and chosen + // issuer to issuer copy. + if(chosenPath.length === 0 || path < chosenPath) { + chosenPath = path; + chosenIssuer = issuerCopy; + } + } + + // 5.5) Append chosen path to data to hash. + md.update(chosenPath); + + // 5.6) Replace issuer, by reference, with chosen issuer. + issuer = chosenIssuer; + } + + // 6) Return issuer and the hash that results from passing data to hash + // through the hash algorithm. + return {hash: md.digest(), issuer}; + } + + // helper for modifying component during Hash First Degree Quads + modifyFirstDegreeComponent(id, component) { + if(component.termType !== 'BlankNode') { + return component; + } + component = util.clone(component); + component.value = (component.value === id ? '_:a' : '_:z'); + return component; + } + + // helper for getting a related predicate + getRelatedPredicate(quad) { + return '<' + quad.predicate.value + '>'; + } + + // helper for creating hash to related blank nodes map + createHashToRelated(id, issuer) { + const self = this; + + // 1) Create a hash to related blank nodes map for storing hashes that + // identify related blank nodes. + const hashToRelated = {}; + + // 2) Get a reference, quads, to the list of quads in the blank node to + // quads map for the key identifier. + const quads = self.blankNodeInfo[id].quads; + + // 3) For each quad in quads: + for(let i = 0; i < quads.length; ++i) { + // 3.1) For each component in quad, if component is the subject, object, + // and graph name and it is a blank node that is not identified by + // identifier: + const quad = quads[i]; + for(const key in quad) { + const component = quad[key]; + if(key === 'predicate' || + !(component.termType === 'BlankNode' && component.value !== id)) { + continue; + } + // 3.1.1) Set hash to the result of the Hash Related Blank Node + // algorithm, passing the blank node identifier for component as + // related, quad, path identifier issuer as issuer, and position as + // either s, o, or g based on whether component is a subject, object, + // graph name, respectively. + const related = component.value; + const position = POSITIONS[key]; + const hash = self.hashRelatedBlankNode(related, quad, issuer, position); + + // 3.1.2) Add a mapping of hash to the blank node identifier for + // component to hash to related blank nodes map, adding an entry as + // necessary. + if(hash in hashToRelated) { + hashToRelated[hash].push(related); + } else { + hashToRelated[hash] = [related]; + } + } + } + + return hashToRelated; + } + + // helper that iterates over quad components (skips predicate) + forEachComponent(quad, op) { + for(const key in quad) { + // skip `predicate` + if(key === 'predicate') { + continue; + } + op(quad[key], key, quad); + } + } +}; + + +/***/ }), + +/***/ "./node_modules/rdf-canonize/lib/URGNA2012.js": +/*!****************************************************!*\ + !*** ./node_modules/rdf-canonize/lib/URGNA2012.js ***! + \****************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* + * Copyright (c) 2016-2017 Digital Bazaar, Inc. All rights reserved. + */ + + +const URDNA2015 = __webpack_require__(/*! ./URDNA2015 */ "./node_modules/rdf-canonize/lib/URDNA2015.js"); +const util = __webpack_require__(/*! ./util */ "./node_modules/rdf-canonize/lib/util.js"); + +module.exports = class URDNA2012 extends URDNA2015 { + constructor(options) { + super(options); + this.name = 'URGNA2012'; + this.hashAlgorithm = 'sha1'; + } + + // helper for modifying component during Hash First Degree Quads + modifyFirstDegreeComponent(id, component, key) { + if(component.termType !== 'BlankNode') { + return component; + } + component = util.clone(component); + if(key === 'name') { + component.value = '_:g'; + } else { + component.value = (component.value === id ? '_:a' : '_:z'); + } + return component; + } + + // helper for getting a related predicate + getRelatedPredicate(quad) { + return quad.predicate.value; + } + + // helper for creating hash to related blank nodes map + createHashToRelated(id, issuer, callback) { + const self = this; + + // 1) Create a hash to related blank nodes map for storing hashes that + // identify related blank nodes. + const hashToRelated = {}; + + // 2) Get a reference, quads, to the list of quads in the blank node to + // quads map for the key identifier. + const quads = self.blankNodeInfo[id].quads; + + // 3) For each quad in quads: + self.forEach(quads, (quad, idx, callback) => { + // 3.1) If the quad's subject is a blank node that does not match + // identifier, set hash to the result of the Hash Related Blank Node + // algorithm, passing the blank node identifier for subject as related, + // quad, path identifier issuer as issuer, and p as position. + let position; + let related; + if(quad.subject.termType === 'BlankNode' && quad.subject.value !== id) { + related = quad.subject.value; + position = 'p'; + } else if( + quad.object.termType === 'BlankNode' && quad.object.value !== id) { + // 3.2) Otherwise, if quad's object is a blank node that does not match + // identifier, to the result of the Hash Related Blank Node algorithm, + // passing the blank node identifier for object as related, quad, path + // identifier issuer as issuer, and r as position. + related = quad.object.value; + position = 'r'; + } else { + // 3.3) Otherwise, continue to the next quad. + return callback(); + } + // 3.4) Add a mapping of hash to the blank node identifier for the + // component that matched (subject or object) to hash to related blank + // nodes map, adding an entry as necessary. + self.hashRelatedBlankNode( + related, quad, issuer, position, (err, hash) => { + if(err) { + return callback(err); + } + if(hash in hashToRelated) { + hashToRelated[hash].push(related); + } else { + hashToRelated[hash] = [related]; + } + callback(); + }); + }, err => callback(err, hashToRelated)); + } +}; + + +/***/ }), + +/***/ "./node_modules/rdf-canonize/lib/URGNA2012Sync.js": +/*!********************************************************!*\ + !*** ./node_modules/rdf-canonize/lib/URGNA2012Sync.js ***! + \********************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* + * Copyright (c) 2016 Digital Bazaar, Inc. All rights reserved. + */ + + +const URDNA2015Sync = __webpack_require__(/*! ./URDNA2015Sync */ "./node_modules/rdf-canonize/lib/URDNA2015Sync.js"); +const util = __webpack_require__(/*! ./util */ "./node_modules/rdf-canonize/lib/util.js"); + +module.exports = class URDNA2012Sync extends URDNA2015Sync { + constructor() { + super(); + this.name = 'URGNA2012'; + this.hashAlgorithm = 'sha1'; + } + + // helper for modifying component during Hash First Degree Quads + modifyFirstDegreeComponent(id, component, key) { + if(component.termType !== 'BlankNode') { + return component; + } + component = util.clone(component); + if(key === 'name') { + component.value = '_:g'; + } else { + component.value = (component.value === id ? '_:a' : '_:z'); + } + return component; + } + + // helper for getting a related predicate + getRelatedPredicate(quad) { + return quad.predicate.value; + } + + // helper for creating hash to related blank nodes map + createHashToRelated(id, issuer) { + const self = this; + + // 1) Create a hash to related blank nodes map for storing hashes that + // identify related blank nodes. + const hashToRelated = {}; + + // 2) Get a reference, quads, to the list of quads in the blank node to + // quads map for the key identifier. + const quads = self.blankNodeInfo[id].quads; + + // 3) For each quad in quads: + for(let i = 0; i < quads.length; ++i) { + // 3.1) If the quad's subject is a blank node that does not match + // identifier, set hash to the result of the Hash Related Blank Node + // algorithm, passing the blank node identifier for subject as related, + // quad, path identifier issuer as issuer, and p as position. + const quad = quads[i]; + let position; + let related; + if(quad.subject.termType === 'BlankNode' && quad.subject.value !== id) { + related = quad.subject.value; + position = 'p'; + } else if( + quad.object.termType === 'BlankNode' && quad.object.value !== id) { + // 3.2) Otherwise, if quad's object is a blank node that does not match + // identifier, to the result of the Hash Related Blank Node algorithm, + // passing the blank node identifier for object as related, quad, path + // identifier issuer as issuer, and r as position. + related = quad.object.value; + position = 'r'; + } else { + // 3.3) Otherwise, continue to the next quad. + continue; + } + // 3.4) Add a mapping of hash to the blank node identifier for the + // component that matched (subject or object) to hash to related blank + // nodes map, adding an entry as necessary. + const hash = self.hashRelatedBlankNode(related, quad, issuer, position); + if(hash in hashToRelated) { + hashToRelated[hash].push(related); + } else { + hashToRelated[hash] = [related]; + } + } + + return hashToRelated; + } +}; + + +/***/ }), + +/***/ "./node_modules/rdf-canonize/lib/index.js": +/*!************************************************!*\ + !*** ./node_modules/rdf-canonize/lib/index.js ***! + \************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * An implementation of the RDF Dataset Normalization specification. + * This library works in the browser and node.js. + * + * BSD 3-Clause License + * Copyright (c) 2016-2017 Digital Bazaar, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * Neither the name of the Digital Bazaar, Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A + * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED + * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + + +const util = __webpack_require__(/*! ./util */ "./node_modules/rdf-canonize/lib/util.js"); +const URDNA2015 = __webpack_require__(/*! ./URDNA2015 */ "./node_modules/rdf-canonize/lib/URDNA2015.js"); +const URGNA2012 = __webpack_require__(/*! ./URGNA2012 */ "./node_modules/rdf-canonize/lib/URGNA2012.js"); +const URDNA2015Sync = __webpack_require__(/*! ./URDNA2015Sync */ "./node_modules/rdf-canonize/lib/URDNA2015Sync.js"); +const URGNA2012Sync = __webpack_require__(/*! ./URGNA2012Sync */ "./node_modules/rdf-canonize/lib/URGNA2012Sync.js"); + +// optional native support +let rdfCanonizeNative; +try { + rdfCanonizeNative = __webpack_require__(/*! rdf-canonize-native */ 1); +} catch(e) {} + +const api = {}; +module.exports = api; + +// expose helpers +api.NQuads = __webpack_require__(/*! ./NQuads */ "./node_modules/rdf-canonize/lib/NQuads.js"); +api.IdentifierIssuer = __webpack_require__(/*! ./IdentifierIssuer */ "./node_modules/rdf-canonize/lib/IdentifierIssuer.js"); + +/** + * Get or set native API. + * + * @param api the native API. + * + * @return the currently set native API. + */ +api._rdfCanonizeNative = function(api) { + if(api) { + rdfCanonizeNative = api; + } + return rdfCanonizeNative; +}; + +/** + * Asynchronously canonizes an RDF dataset. + * + * @param dataset the dataset to canonize. + * @param options the options to use: + * algorithm the canonicalization algorithm to use, `URDNA2015` or + * `URGNA2012`. + * [useNative] use native implementation (default: false). + * @param [callback(err, canonical)] called once the operation completes. + * + * @return a Promise that resolves to the canonicalized RDF Dataset. + */ +api.canonize = util.callbackify(async function(dataset, options) { + let callback; + const promise = new Promise((resolve, reject) => { + callback = (err, canonical) => { + if(err) { + return reject(err); + } + + /*if(options.format === 'application/n-quads') { + canonical = canonical.join(''); + } + canonical = _parseNQuads(canonical.join(''));*/ + + resolve(canonical); + }; + }); + + // back-compat with legacy dataset + if(!Array.isArray(dataset)) { + dataset = api.NQuads.legacyDatasetToQuads(dataset); + } + + // TODO: convert algorithms to Promise-based async + if(options.useNative) { + if(rdfCanonizeNative) { + rdfCanonizeNative.canonize(dataset, options, callback); + } else { + throw new Error('rdf-canonize-native not available'); + } + } else { + if(options.algorithm === 'URDNA2015') { + new URDNA2015(options).main(dataset, callback); + } else if(options.algorithm === 'URGNA2012') { + new URGNA2012(options).main(dataset, callback); + } else if(!('algorithm' in options)) { + throw new Error('No RDF Dataset Canonicalization algorithm specified.'); + } else { + throw new Error( + 'Invalid RDF Dataset Canonicalization algorithm: ' + options.algorithm); + } + } + + return promise; +}); + +/** + * Synchronously canonizes an RDF dataset. + * + * @param dataset the dataset to canonize. + * @param options the options to use: + * algorithm the canonicalization algorithm to use, `URDNA2015` or + * `URGNA2012`. + * [useNative] use native implementation (default: false). + * + * @return the RDF dataset in canonical form. + */ +api.canonizeSync = function(dataset, options) { + // back-compat with legacy dataset + if(!Array.isArray(dataset)) { + dataset = api.NQuads.legacyDatasetToQuads(dataset); + } + + if(options.useNative) { + if(rdfCanonizeNative) { + return rdfCanonizeNative.canonizeSync(dataset, options); + } + throw new Error('rdf-canonize-native not available'); + } + if(options.algorithm === 'URDNA2015') { + return new URDNA2015Sync(options).main(dataset); + } else if(options.algorithm === 'URGNA2012') { + return new URGNA2012Sync(options).main(dataset); + } + if(!('algorithm' in options)) { + throw new Error('No RDF Dataset Canonicalization algorithm specified.'); + } + throw new Error( + 'Invalid RDF Dataset Canonicalization algorithm: ' + options.algorithm); +}; + + +/***/ }), + +/***/ "./node_modules/rdf-canonize/lib/util.js": +/*!***********************************************!*\ + !*** ./node_modules/rdf-canonize/lib/util.js ***! + \***********************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(setImmediate, process) {/* + * Copyright (c) 2016-2017 Digital Bazaar, Inc. All rights reserved. + */ + + +const api = {}; +module.exports = api; + +// define setImmediate and nextTick +//// nextTick implementation with browser-compatible fallback //// +// from https://github.com/caolan/async/blob/master/lib/async.js + +// capture the global reference to guard against fakeTimer mocks +const _setImmediate = typeof setImmediate === 'function' && setImmediate; + +const _delay = _setImmediate ? + // not a direct alias (for IE10 compatibility) + fn => _setImmediate(fn) : + fn => setTimeout(fn, 0); + +if(typeof process === 'object' && typeof process.nextTick === 'function') { + api.nextTick = process.nextTick; +} else { + api.nextTick = _delay; +} +api.setImmediate = _setImmediate ? _delay : api.nextTick; + +/** + * Clones an object, array, or string/number. If a typed JavaScript object + * is given, such as a Date, it will be converted to a string. + * + * @param value the value to clone. + * + * @return the cloned value. + */ +api.clone = function(value) { + if(value && typeof value === 'object') { + let rval; + if(Array.isArray(value)) { + rval = []; + for(let i = 0; i < value.length; ++i) { + rval[i] = api.clone(value[i]); + } + } else if(api.isObject(value)) { + rval = {}; + for(const key in value) { + rval[key] = api.clone(value[key]); + } + } else { + rval = value.toString(); + } + return rval; + } + return value; +}; + +/** + * Returns true if the given value is an Object. + * + * @param v the value to check. + * + * @return true if the value is an Object, false if not. + */ +api.isObject = v => Object.prototype.toString.call(v) === '[object Object]'; + +/** + * Returns true if the given value is undefined. + * + * @param v the value to check. + * + * @return true if the value is undefined, false if not. + */ +api.isUndefined = v => typeof v === 'undefined'; + +api.callbackify = fn => { + return async function(...args) { + const callback = args[args.length - 1]; + if(typeof callback === 'function') { + args.pop(); + } + + let result; + try { + result = await fn.apply(null, args); + } catch(e) { + if(typeof callback === 'function') { + return _invokeCallback(callback, e); + } + throw e; + } + + if(typeof callback === 'function') { + return _invokeCallback(callback, null, result); + } + + return result; + }; +}; + +function _invokeCallback(callback, err, result) { + try { + return callback(err, result); + } catch(unhandledError) { + // throw unhandled errors to prevent "unhandled rejected promise" + // and simulate what would have happened in a promiseless API + process.nextTick(() => { + throw unhandledError; + }); + } +} + +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../timers-browserify/main.js */ "./node_modules/timers-browserify/main.js").setImmediate, __webpack_require__(/*! ./../../process/browser.js */ "./node_modules/process/browser.js"))) + +/***/ }), + +/***/ "./node_modules/rdflib/esm/blank-node.js": +/*!***********************************************!*\ + !*** ./node_modules/rdflib/esm/blank-node.js ***! + \***********************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return BlankNode; }); +/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js"); +/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/assertThisInitialized */ "./node_modules/@babel/runtime/helpers/assertThisInitialized.js"); +/* harmony import */ var _babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_1__); +/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js"); +/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_2__); +/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/inherits */ "./node_modules/@babel/runtime/helpers/inherits.js"); +/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3__); +/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "./node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"); +/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__); +/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "./node_modules/@babel/runtime/helpers/getPrototypeOf.js"); +/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__); +/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "./node_modules/@babel/runtime/helpers/defineProperty.js"); +/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__); +/* harmony import */ var _class_order__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./class-order */ "./node_modules/rdflib/esm/class-order.js"); +/* harmony import */ var _node_internal__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./node-internal */ "./node_modules/rdflib/esm/node-internal.js"); +/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./types */ "./node_modules/rdflib/esm/types.js"); + + + + + + + + +function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5___default()(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5___default()(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4___default()(this, result); }; } + +function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } + + + + + +/** + * An RDF blank node is a Node without a URI + * @link https://rdf.js.org/data-model-spec/#blanknode-interface + */ +var BlankNode = /*#__PURE__*/function (_Node) { + _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3___default()(BlankNode, _Node); + + var _super = _createSuper(BlankNode); + + _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_2___default()(BlankNode, null, [{ + key: "getId", + + /** + * The next unique identifier for blank nodes + */ + value: function getId(id) { + if (id) { + if (typeof id !== 'string') { + console.log('Bad blank id:', id); + throw new Error('Bad id argument to new blank node: ' + id); + } + + if (id.includes('#')) { + // Is a URI with hash fragment + var fragments = id.split('#'); + return fragments[fragments.length - 1]; + } + + return id; + } + + return 'n' + BlankNode.nextId++; + } + }]); + + /** + * Initializes this node + * @param [id] The identifier for the blank node + */ + function BlankNode(id) { + var _this; + + _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, BlankNode); + + _this = _super.call(this, BlankNode.getId(id)); + + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6___default()(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_1___default()(_this), "termType", _types__WEBPACK_IMPORTED_MODULE_9__["BlankNodeTermType"]); + + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6___default()(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_1___default()(_this), "classOrder", _class_order__WEBPACK_IMPORTED_MODULE_7__["default"].BlankNode); + + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6___default()(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_1___default()(_this), "isBlank", 1); + + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6___default()(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_1___default()(_this), "isVar", 1); + + return _this; + } + /** + * The identifier for the blank node + */ + + + _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_2___default()(BlankNode, [{ + key: "compareTerm", + value: function compareTerm(other) { + if (this.classOrder < other.classOrder) { + return -1; + } + + if (this.classOrder > other.classOrder) { + return +1; + } + + if (this.id < other.id) { + return -1; + } + + if (this.id > other.id) { + return +1; + } + + return 0; + } + /** + * Gets a copy of this blank node in the specified formula + * @param formula The formula + */ + + }, { + key: "copy", + value: function copy(formula) { + // depends on the formula + var bnodeNew = new BlankNode(); + formula.copyTo(this, bnodeNew); + return bnodeNew; + } + }, { + key: "toCanonical", + value: function toCanonical() { + return BlankNode.NTAnonymousNodePrefix + this.value; + } + }, { + key: "toString", + value: function toString() { + return BlankNode.NTAnonymousNodePrefix + this.id; + } + }, { + key: "id", + get: function get() { + return this.value; + }, + set: function set(value) { + this.value = value; + } + }]); + + return BlankNode; +}(_node_internal__WEBPACK_IMPORTED_MODULE_8__["default"]); + +_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6___default()(BlankNode, "nextId", 0); + +_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6___default()(BlankNode, "NTAnonymousNodePrefix", '_:'); + + + +/***/ }), + +/***/ "./node_modules/rdflib/esm/class-order.js": +/*!************************************************!*\ + !*** ./node_modules/rdflib/esm/class-order.js ***! + \************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/** +* Class orders +*/ +var ClassOrder = { + 'Literal': 1, + 'Collection': 3, + 'Graph': 4, + 'NamedNode': 5, + 'BlankNode': 6, + 'Variable': 7 +}; +/* harmony default export */ __webpack_exports__["default"] = (ClassOrder); + +/***/ }), + +/***/ "./node_modules/rdflib/esm/collection.js": +/*!***********************************************!*\ + !*** ./node_modules/rdflib/esm/collection.js ***! + \***********************************************/ +/*! exports provided: fromValue, default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "fromValue", function() { return fromValue; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return Collection; }); +/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js"); +/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js"); +/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__); +/* harmony import */ var _babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/assertThisInitialized */ "./node_modules/@babel/runtime/helpers/assertThisInitialized.js"); +/* harmony import */ var _babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__); +/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/inherits */ "./node_modules/@babel/runtime/helpers/inherits.js"); +/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3__); +/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "./node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"); +/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__); +/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "./node_modules/@babel/runtime/helpers/getPrototypeOf.js"); +/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__); +/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "./node_modules/@babel/runtime/helpers/defineProperty.js"); +/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__); +/* harmony import */ var _blank_node__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./blank-node */ "./node_modules/rdflib/esm/blank-node.js"); +/* harmony import */ var _class_order__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./class-order */ "./node_modules/rdflib/esm/class-order.js"); +/* harmony import */ var _literal__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./literal */ "./node_modules/rdflib/esm/literal.js"); +/* harmony import */ var _node_internal__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./node-internal */ "./node_modules/rdflib/esm/node-internal.js"); +/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./types */ "./node_modules/rdflib/esm/types.js"); +/* harmony import */ var _utils_terms__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./utils/terms */ "./node_modules/rdflib/esm/utils/terms.js"); + + + + + + + + +function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5___default()(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5___default()(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4___default()(this, result); }; } + +function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } + + + + + + + + +/** + * Creates an RDF Node from a native javascript value. + * RDF Nodes are returned unchanged, undefined returned as itself. + * Arrays return Collections. + * Strings, numbers and booleans return Literals. + * @param value {Node|Date|String|Number|Boolean|Undefined} + * @return {Node|Collection} + */ +function fromValue(value) { + if (typeof value === 'undefined' || value === null) { + return value; + } + + if (Object(_utils_terms__WEBPACK_IMPORTED_MODULE_12__["isTerm"])(value)) { + // a Node subclass or a Collection + return value; + } + + if (Array.isArray(value)) { + return new Collection(value); + } + + return _literal__WEBPACK_IMPORTED_MODULE_9__["default"].fromValue(value); +} +/** + * A collection of other RDF nodes + * + * Use generic T to control the contents of the array. + */ + +var Collection = /*#__PURE__*/function (_Node) { + _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3___default()(Collection, _Node); + + var _super = _createSuper(Collection); + + /** + * The nodes in this collection + */ + function Collection(initial) { + var _this; + + _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, Collection); + + _this = _super.call(this, (_blank_node__WEBPACK_IMPORTED_MODULE_7__["default"].nextId++).toString()); + + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6___default()(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2___default()(_this), "termType", _types__WEBPACK_IMPORTED_MODULE_11__["CollectionTermType"]); + + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6___default()(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2___default()(_this), "classOrder", _class_order__WEBPACK_IMPORTED_MODULE_8__["default"].Collection); + + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6___default()(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2___default()(_this), "closed", false); + + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6___default()(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2___default()(_this), "compareTerm", _blank_node__WEBPACK_IMPORTED_MODULE_7__["default"].prototype.compareTerm); + + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6___default()(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2___default()(_this), "elements", []); + + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6___default()(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2___default()(_this), "isVar", 0); + + if (initial && initial.length > 0) { + initial.forEach(function (element) { + _this.elements.push(fromValue(element)); + }); + } + + return _this; + } + + _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default()(Collection, [{ + key: "append", + + /** + * Appends an element to this collection + * @param element - The new element + */ + value: function append(element) { + return this.elements.push(element); + } + /** + * Closes this collection + */ + + }, { + key: "close", + value: function close() { + this.closed = true; + return this.closed; + } + /** + * Removes the first element from the collection (and return it) + */ + + }, { + key: "shift", + value: function shift() { + return this.elements.shift(); + } + /** + * Creates a new Collection with the substituting bindings applied + * @param bindings - The bindings to substitute + */ + + }, { + key: "substitute", + value: function substitute(bindings) { + var elementsCopy = this.elements.map(function (ea) { + return ea.substitute(bindings); + }); + return new Collection(elementsCopy); + } + }, { + key: "toNT", + value: function toNT() { + return Collection.toNT(this); + } + }, { + key: "toString", + + /** + * Serializes the collection to a string. + * Surrounded by (parentheses) and separated by spaces. + */ + value: function toString() { + return '(' + this.elements.join(' ') + ')'; + } + /** + * Prepends the specified element to the collection's front + * @param element - The element to prepend + */ + + }, { + key: "unshift", + value: function unshift(element) { + return this.elements.unshift(element); + } + }, { + key: "id", + get: function get() { + return this.value; + }, + set: function set(value) { + this.value = value; + } + }], [{ + key: "toNT", + value: function toNT(collection) { + return _blank_node__WEBPACK_IMPORTED_MODULE_7__["default"].NTAnonymousNodePrefix + collection.id; + } + }]); + + return Collection; +}(_node_internal__WEBPACK_IMPORTED_MODULE_10__["default"]); + +_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6___default()(Collection, "termType", _types__WEBPACK_IMPORTED_MODULE_11__["CollectionTermType"]); + + + +/***/ }), + +/***/ "./node_modules/rdflib/esm/convert.js": +/*!********************************************!*\ + !*** ./node_modules/rdflib/esm/convert.js ***! + \********************************************/ +/*! exports provided: convertToJson, convertToNQuads */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "convertToJson", function() { return convertToJson; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "convertToNQuads", function() { return convertToNQuads; }); +/* harmony import */ var async__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! async */ "./node_modules/async/dist/async.mjs"); +/* harmony import */ var jsonld__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! jsonld */ "./node_modules/jsonld/lib/jsonld.js"); +/* harmony import */ var jsonld__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(jsonld__WEBPACK_IMPORTED_MODULE_1__); +/* harmony import */ var n3__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! n3 */ "./node_modules/n3/src/index.js"); + // @@ Goal: remove this dependency + + + // @@ Goal: remove this dependency + +function convertToJson(n3String, jsonCallback) { + var jsonString; + var n3Parser = new n3__WEBPACK_IMPORTED_MODULE_2__["Parser"](); + var n3Writer = new n3__WEBPACK_IMPORTED_MODULE_2__["Writer"]({ + format: 'N-Quads' + }); + async__WEBPACK_IMPORTED_MODULE_0__["default"].waterfall([function (callback) { + n3Parser.parse(n3String, function (error, quad, prefixes) { + if (error) { + callback(error); + } else if (quad !== null) { + n3Writer.addQuad(quad); + } else { + n3Writer.end(callback); + } + }); + }, function (result, callback) { + try { + jsonld__WEBPACK_IMPORTED_MODULE_1___default.a.fromRDF(result, { + format: 'application/nquads' + }).then(function (result) { + callback(null, result); + }); + } catch (err) { + callback(err); + } + }, function (json, callback) { + jsonString = JSON.stringify(json); + jsonCallback(null, jsonString); + }], function (err, result) { + jsonCallback(err, jsonString); + }); +} +function convertToNQuads(n3String, nquadCallback) { + var nquadString; + var n3Parser = new n3__WEBPACK_IMPORTED_MODULE_2__["Parser"](); + var n3Writer = new n3__WEBPACK_IMPORTED_MODULE_2__["Writer"]({ + format: 'N-Quads' + }); + async__WEBPACK_IMPORTED_MODULE_0__["default"].waterfall([function (callback) { + n3Parser.parse(n3String, function (error, triple, prefixes) { + if (error) { + callback(error); + } else if (quad !== null) { + n3Writer.addQuad(quad); + } else { + n3Writer.end(callback); + } + }); + }, function (result, callback) { + nquadString = result; + nquadCallback(null, nquadString); + }], function (err, result) { + nquadCallback(err, nquadString); + }); +} + +/***/ }), + +/***/ "./node_modules/rdflib/esm/default-graph.js": +/*!**************************************************!*\ + !*** ./node_modules/rdflib/esm/default-graph.js ***! + \**************************************************/ +/*! exports provided: default, isDefaultGraph */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return DefaultGraph; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isDefaultGraph", function() { return isDefaultGraph; }); +/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js"); +/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js"); +/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__); +/* harmony import */ var _babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/assertThisInitialized */ "./node_modules/@babel/runtime/helpers/assertThisInitialized.js"); +/* harmony import */ var _babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__); +/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/inherits */ "./node_modules/@babel/runtime/helpers/inherits.js"); +/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3__); +/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "./node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"); +/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__); +/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "./node_modules/@babel/runtime/helpers/getPrototypeOf.js"); +/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__); +/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "./node_modules/@babel/runtime/helpers/defineProperty.js"); +/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__); +/* harmony import */ var _node_internal__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./node-internal */ "./node_modules/rdflib/esm/node-internal.js"); +/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./types */ "./node_modules/rdflib/esm/types.js"); +/* harmony import */ var _utils_default_graph_uri__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./utils/default-graph-uri */ "./node_modules/rdflib/esm/utils/default-graph-uri.js"); + + + + + + + + +function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5___default()(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5___default()(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4___default()(this, result); }; } + +function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } + + + + +/** The RDF default graph */ + +var DefaultGraph = /*#__PURE__*/function (_Node) { + _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3___default()(DefaultGraph, _Node); + + var _super = _createSuper(DefaultGraph); + + function DefaultGraph() { + var _this; + + _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, DefaultGraph); + + _this = _super.call(this, ''); + + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6___default()(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2___default()(_this), "value", ''); + + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6___default()(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2___default()(_this), "termType", _types__WEBPACK_IMPORTED_MODULE_8__["DefaultGraphTermType"]); + + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6___default()(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2___default()(_this), "uri", _utils_default_graph_uri__WEBPACK_IMPORTED_MODULE_9__["defaultGraphURI"]); + + return _this; + } + + _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default()(DefaultGraph, [{ + key: "toCanonical", + value: function toCanonical() { + return this.value; + } + }, { + key: "toString", + value: function toString() { + return 'DefaultGraph'; + } + }]); + + return DefaultGraph; +}(_node_internal__WEBPACK_IMPORTED_MODULE_7__["default"]); + + +function isDefaultGraph(object) { + return !!object && object.termType === _types__WEBPACK_IMPORTED_MODULE_8__["DefaultGraphTermType"]; +} + +/***/ }), + +/***/ "./node_modules/rdflib/esm/empty.js": +/*!******************************************!*\ + !*** ./node_modules/rdflib/esm/empty.js ***! + \******************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return Empty; }); +/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js"); +/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js"); +/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__); +/* harmony import */ var _babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/assertThisInitialized */ "./node_modules/@babel/runtime/helpers/assertThisInitialized.js"); +/* harmony import */ var _babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__); +/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/inherits */ "./node_modules/@babel/runtime/helpers/inherits.js"); +/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3__); +/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "./node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"); +/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__); +/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "./node_modules/@babel/runtime/helpers/getPrototypeOf.js"); +/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__); +/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "./node_modules/@babel/runtime/helpers/defineProperty.js"); +/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__); +/* harmony import */ var _node_internal__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./node-internal */ "./node_modules/rdflib/esm/node-internal.js"); +/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./types */ "./node_modules/rdflib/esm/types.js"); + + + + + + + + +function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5___default()(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5___default()(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4___default()(this, result); }; } + +function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } + + + + +/** +* An empty node +*/ +var Empty = /*#__PURE__*/function (_Node) { + _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3___default()(Empty, _Node); + + var _super = _createSuper(Empty); + + function Empty() { + var _this; + + _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, Empty); + + _this = _super.call(this, ''); + + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6___default()(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2___default()(_this), "termType", _types__WEBPACK_IMPORTED_MODULE_8__["EmptyTermType"]); + + return _this; + } + + _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default()(Empty, [{ + key: "toString", + value: function toString() { + return '()'; + } + }]); + + return Empty; +}(_node_internal__WEBPACK_IMPORTED_MODULE_7__["default"]); + + + +/***/ }), + +/***/ "./node_modules/rdflib/esm/factories/canonical-data-factory.js": +/*!*********************************************************************!*\ + !*** ./node_modules/rdflib/esm/factories/canonical-data-factory.js ***! + \*********************************************************************/ +/*! exports provided: defaultGraphURI, default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "./node_modules/@babel/runtime/helpers/defineProperty.js"); +/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _blank_node__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../blank-node */ "./node_modules/rdflib/esm/blank-node.js"); +/* harmony import */ var _literal__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../literal */ "./node_modules/rdflib/esm/literal.js"); +/* harmony import */ var _named_node__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../named-node */ "./node_modules/rdflib/esm/named-node.js"); +/* harmony import */ var _statement__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../statement */ "./node_modules/rdflib/esm/statement.js"); +/* harmony import */ var _variable__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../variable */ "./node_modules/rdflib/esm/variable.js"); +/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../types */ "./node_modules/rdflib/esm/types.js"); +/* harmony import */ var _default_graph__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../default-graph */ "./node_modules/rdflib/esm/default-graph.js"); +/* harmony import */ var _factory_types__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./factory-types */ "./node_modules/rdflib/esm/factories/factory-types.js"); +/* harmony import */ var _utils_terms__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../utils/terms */ "./node_modules/rdflib/esm/utils/terms.js"); +/* harmony import */ var _utils_default_graph_uri__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../utils/default-graph-uri */ "./node_modules/rdflib/esm/utils/default-graph-uri.js"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "defaultGraphURI", function() { return _utils_default_graph_uri__WEBPACK_IMPORTED_MODULE_10__["defaultGraphURI"]; }); + + + +var _supports; + + + + + + + + + + + +/** + * Gets the default graph + */ + +var _defaultGraph = new _default_graph__WEBPACK_IMPORTED_MODULE_7__["default"](); +/** A basic internal RDFlib datafactory, which does not support Collections */ + + +var CanonicalDataFactory = { + supports: (_supports = {}, _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0___default()(_supports, _factory_types__WEBPACK_IMPORTED_MODULE_8__["Feature"].collections, false), _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0___default()(_supports, _factory_types__WEBPACK_IMPORTED_MODULE_8__["Feature"].defaultGraphType, false), _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0___default()(_supports, _factory_types__WEBPACK_IMPORTED_MODULE_8__["Feature"].equalsMethod, true), _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0___default()(_supports, _factory_types__WEBPACK_IMPORTED_MODULE_8__["Feature"].identity, false), _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0___default()(_supports, _factory_types__WEBPACK_IMPORTED_MODULE_8__["Feature"].id, true), _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0___default()(_supports, _factory_types__WEBPACK_IMPORTED_MODULE_8__["Feature"].reversibleId, false), _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0___default()(_supports, _factory_types__WEBPACK_IMPORTED_MODULE_8__["Feature"].variableType, true), _supports), + + /** + * Creates a new blank node + * @param value - The blank node's identifier + */ + blankNode: function blankNode(value) { + return new _blank_node__WEBPACK_IMPORTED_MODULE_1__["default"](value); + }, + defaultGraph: function defaultGraph() { + return _defaultGraph; + }, + + /** + * Compares to (rdf) objects for equality. + */ + equals: function equals(a, b) { + if (a === b || !a || !b) { + return true; + } + + if (Object(_utils_terms__WEBPACK_IMPORTED_MODULE_9__["isQuad"])(a) || Object(_utils_terms__WEBPACK_IMPORTED_MODULE_9__["isQuad"])(b)) { + if (Object(_utils_terms__WEBPACK_IMPORTED_MODULE_9__["isQuad"])(a) && Object(_utils_terms__WEBPACK_IMPORTED_MODULE_9__["isQuad"])(b)) { + return this.equals(a.subject, b.subject) && this.equals(a.predicate, b.predicate) && this.equals(a.object, b.object) && this.equals(a.graph, b.graph); + } + + return false; + } + + if (Object(_utils_terms__WEBPACK_IMPORTED_MODULE_9__["isTerm"])(a) && Object(_utils_terms__WEBPACK_IMPORTED_MODULE_9__["isTerm"])(b)) { + return this.id(a) === this.id(b); + } + + return false; + }, + + /** + * Generates a uniquely identifiably *idempotent* string for the given {term}. + * + * Equivalent to [[Term.hashString]] + * + * @example Use this to associate data with a term in an object + * { obj[id(term)] = "myData" } + */ + id: function id(term) { + if (!term) { + return 'undefined'; + } + + if (Object(_utils_terms__WEBPACK_IMPORTED_MODULE_9__["isQuad"])(term)) { + return this.quadToNQ(term); + } + + switch (term.termType) { + case _types__WEBPACK_IMPORTED_MODULE_6__["DefaultGraphTermType"]: + return 'defaultGraph'; + + case _types__WEBPACK_IMPORTED_MODULE_6__["VariableTermType"]: + return _variable__WEBPACK_IMPORTED_MODULE_5__["default"].toString(term); + + default: + var nq = this.termToNQ(term); + + if (nq) { + return nq; + } + + throw new Error("Can't id term with type '".concat(term.termType, "'")); + } + }, + isQuad: function isQuad(obj) { + return obj instanceof _statement__WEBPACK_IMPORTED_MODULE_4__["default"]; + }, + + /** + * Creates a new literal node. Does some JS literal parsing for ease of use. + * @param value - The lexical value + * @param languageOrDatatype - Either the language or the datatype + */ + literal: function literal(value, languageOrDatatype) { + if (typeof value !== "string" && !languageOrDatatype) { + return _literal__WEBPACK_IMPORTED_MODULE_2__["default"].fromValue(value); + } + + var strValue = typeof value === 'string' ? value : '' + value; + + if (typeof languageOrDatatype === 'string') { + if (languageOrDatatype.indexOf(':') === -1) { + return new _literal__WEBPACK_IMPORTED_MODULE_2__["default"](strValue, languageOrDatatype); + } else { + return new _literal__WEBPACK_IMPORTED_MODULE_2__["default"](strValue, null, this.namedNode(languageOrDatatype)); + } + } else { + return new _literal__WEBPACK_IMPORTED_MODULE_2__["default"](strValue, null, languageOrDatatype); + } + }, + + /** + * Creates a new named node + * @param value - The new named node + */ + namedNode: function namedNode(value) { + return new _named_node__WEBPACK_IMPORTED_MODULE_3__["default"](value); + }, + + /** + * Creates a new statement + * @param subject - The subject + * @param predicate - The predicate + * @param object - The object + * @param graph - The containing graph + */ + quad: function quad(subject, predicate, object, graph) { + return new _statement__WEBPACK_IMPORTED_MODULE_4__["default"](subject, predicate, object, graph || _defaultGraph); + }, + + /** + * Creates a new statement + * @param subject - The subject + * @param predicate - The predicate + * @param object - The object + * @param graph - The containing graph + */ + triple: function triple(subject, predicate, object, graph) { + return this.quad(subject, predicate, object, graph); + }, + quadToNQ: function quadToNQ(q) { + return "".concat(this.termToNQ(q.subject), " ").concat(this.termToNQ(q.predicate), " ").concat(this.termToNQ(q.object), " ").concat(this.termToNQ(q.graph), " ."); + }, + + /** Stringify a {term} to n-quads serialization. */ + termToNQ: function termToNQ(term) { + var _this = this; + + switch (term.termType) { + case _types__WEBPACK_IMPORTED_MODULE_6__["BlankNodeTermType"]: + return '_:' + term.value; + + case _types__WEBPACK_IMPORTED_MODULE_6__["DefaultGraphTermType"]: + return ''; + + case _types__WEBPACK_IMPORTED_MODULE_6__["EmptyTermType"]: + return ''; + + case _types__WEBPACK_IMPORTED_MODULE_6__["LiteralTermType"]: + return _literal__WEBPACK_IMPORTED_MODULE_2__["default"].toNT(term); + + case _types__WEBPACK_IMPORTED_MODULE_6__["GraphTermType"]: + case _types__WEBPACK_IMPORTED_MODULE_6__["NamedNodeTermType"]: + return '<' + term.value + '>'; + + case _types__WEBPACK_IMPORTED_MODULE_6__["CollectionTermType"]: + return '(' + term.elements.map(function (t) { + return _this.termToNQ(t); + }).join(' ') + ')'; + + default: + throw new Error("Can't serialize nonstandard term type (was '".concat(term.termType, "')")); + } + }, + + /** Convert an rdf object (term or quad) to n-quads serialization. */ + toNQ: function toNQ(term) { + if (this.isQuad(term)) { + return this.quadToNQ(term); + } + + return this.termToNQ(term); + }, + + /** + * Creates a new variable + * @param name - The name for the variable + */ + variable: function variable(name) { + return new _variable__WEBPACK_IMPORTED_MODULE_5__["default"](name); + } +}; +/** Contains the factory methods as defined in the spec, plus id */ + +/* harmony default export */ __webpack_exports__["default"] = (CanonicalDataFactory); + +/***/ }), + +/***/ "./node_modules/rdflib/esm/factories/extended-term-factory.js": +/*!********************************************************************!*\ + !*** ./node_modules/rdflib/esm/factories/extended-term-factory.js ***! + \********************************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "./node_modules/@babel/runtime/helpers/defineProperty.js"); +/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _collection__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../collection */ "./node_modules/rdflib/esm/collection.js"); +/* harmony import */ var _canonical_data_factory__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./canonical-data-factory */ "./node_modules/rdflib/esm/factories/canonical-data-factory.js"); +/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../types */ "./node_modules/rdflib/esm/types.js"); +/* harmony import */ var _factory_types__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./factory-types */ "./node_modules/rdflib/esm/factories/factory-types.js"); +/* harmony import */ var _utils_terms__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/terms */ "./node_modules/rdflib/esm/utils/terms.js"); +/* harmony import */ var _variable__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../variable */ "./node_modules/rdflib/esm/variable.js"); + + +var _supports; + +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0___default()(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } + + + + + + + + +/** + * Data factory which also supports Collections + * + * Necessary for preventing circular dependencies. + */ +var ExtendedTermFactory = _objectSpread(_objectSpread({}, _canonical_data_factory__WEBPACK_IMPORTED_MODULE_2__["default"]), {}, { + supports: (_supports = {}, _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0___default()(_supports, _factory_types__WEBPACK_IMPORTED_MODULE_4__["Feature"].collections, true), _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0___default()(_supports, _factory_types__WEBPACK_IMPORTED_MODULE_4__["Feature"].defaultGraphType, false), _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0___default()(_supports, _factory_types__WEBPACK_IMPORTED_MODULE_4__["Feature"].equalsMethod, true), _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0___default()(_supports, _factory_types__WEBPACK_IMPORTED_MODULE_4__["Feature"].identity, false), _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0___default()(_supports, _factory_types__WEBPACK_IMPORTED_MODULE_4__["Feature"].id, true), _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0___default()(_supports, _factory_types__WEBPACK_IMPORTED_MODULE_4__["Feature"].reversibleId, false), _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0___default()(_supports, _factory_types__WEBPACK_IMPORTED_MODULE_4__["Feature"].variableType, true), _supports), + + /** + * Creates a new collection + * @param elements - The initial element + */ + collection: function collection(elements) { + return new _collection__WEBPACK_IMPORTED_MODULE_1__["default"](elements); + }, + id: function id(term) { + var _this = this; + + if (Object(_utils_terms__WEBPACK_IMPORTED_MODULE_5__["isCollection"])(term)) { + return "( ".concat(term.elements.map(function (e) { + return _this.id(e); + }).join(', '), " )"); + } + + if (Object(_utils_terms__WEBPACK_IMPORTED_MODULE_5__["isVariable"])(term)) { + return _variable__WEBPACK_IMPORTED_MODULE_6__["default"].toString(term); + } + + return _canonical_data_factory__WEBPACK_IMPORTED_MODULE_2__["default"].id(term); + }, + termToNQ: function termToNQ(term) { + if (term.termType === _types__WEBPACK_IMPORTED_MODULE_3__["CollectionTermType"]) { + return _collection__WEBPACK_IMPORTED_MODULE_1__["default"].toNT(term); + } + + return _canonical_data_factory__WEBPACK_IMPORTED_MODULE_2__["default"].termToNQ(term); + } +}); + +/* harmony default export */ __webpack_exports__["default"] = (ExtendedTermFactory); + +/***/ }), + +/***/ "./node_modules/rdflib/esm/factories/factory-types.js": +/*!************************************************************!*\ + !*** ./node_modules/rdflib/esm/factories/factory-types.js ***! + \************************************************************/ +/*! exports provided: Feature */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Feature", function() { return Feature; }); +/** A set of features that may be supported by a Data Factory */ +var Feature; +/** + * Defines a DataFactory as used in rdflib, based on the RDF/JS: Data model specification, + * but with additional extensions + * + * bnIndex is optional but useful. + */ + +(function (Feature) { + Feature["collections"] = "COLLECTIONS"; + Feature["defaultGraphType"] = "DEFAULT_GRAPH_TYPE"; + Feature["equalsMethod"] = "EQUALS_METHOD"; + Feature["id"] = "ID"; + Feature["identity"] = "IDENTITY"; + Feature["reversibleId"] = "REVERSIBLE_ID"; + Feature["variableType"] = "VARIABLE_TYPE"; +})(Feature || (Feature = {})); + +/***/ }), + +/***/ "./node_modules/rdflib/esm/factories/rdflib-data-factory.js": +/*!******************************************************************!*\ + !*** ./node_modules/rdflib/esm/factories/rdflib-data-factory.js ***! + \******************************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "./node_modules/@babel/runtime/helpers/defineProperty.js"); +/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _store__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../store */ "./node_modules/rdflib/esm/store.js"); +/* harmony import */ var _fetcher__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../fetcher */ "./node_modules/rdflib/esm/fetcher.js"); +/* harmony import */ var _extended_term_factory__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./extended-term-factory */ "./node_modules/rdflib/esm/factories/extended-term-factory.js"); + + +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0___default()(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } + + + + + +/** Full RDFLib.js Data Factory */ +var RDFlibDataFactory = _objectSpread(_objectSpread({}, _extended_term_factory__WEBPACK_IMPORTED_MODULE_3__["default"]), {}, { + /** + * Creates a new fetcher + * @param store - The store to use + * @param options - The options + */ + fetcher: function fetcher(store, options) { + return new _fetcher__WEBPACK_IMPORTED_MODULE_2__["default"](store, options); + }, + + /** + * Creates a new graph (store) + */ + graph: function graph() { + var features = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : undefined; + var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; + return new _store__WEBPACK_IMPORTED_MODULE_1__["default"](features, opts || { + rdfFactory: _extended_term_factory__WEBPACK_IMPORTED_MODULE_3__["default"] + }); + }, + + /** + * Creates a new literal node + * @param val The lexical value + * @param lang The language + * @param dt The datatype + */ + lit: function lit(val, lang, dt) { + return this.literal('' + val, lang || dt); + }, + + /** + * Creates a new statement + * @param subject The subject + * @param predicate The predicate + * @param object The object + * @param graph The containing graph + */ + st: function st(subject, predicate, object, graph) { + return this.quad(subject, predicate, object, graph); + } +}); + +/* harmony default export */ __webpack_exports__["default"] = (RDFlibDataFactory); + +/***/ }), + +/***/ "./node_modules/rdflib/esm/fetcher.js": +/*!********************************************!*\ + !*** ./node_modules/rdflib/esm/fetcher.js ***! + \********************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return Fetcher; }); +/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js"); +/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js"); +/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__); +/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js"); +/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_2__); +/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/inherits */ "./node_modules/@babel/runtime/helpers/inherits.js"); +/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3__); +/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "./node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"); +/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__); +/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "./node_modules/@babel/runtime/helpers/getPrototypeOf.js"); +/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__); +/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js"); +/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_6__); +/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "./node_modules/@babel/runtime/helpers/defineProperty.js"); +/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_7__); +/* harmony import */ var _store__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./store */ "./node_modules/rdflib/esm/store.js"); +/* harmony import */ var _log__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./log */ "./node_modules/rdflib/esm/log.js"); +/* harmony import */ var _n3parser__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./n3parser */ "./node_modules/rdflib/esm/n3parser.js"); +/* harmony import */ var _named_node__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./named-node */ "./node_modules/rdflib/esm/named-node.js"); +/* harmony import */ var _namespace__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./namespace */ "./node_modules/rdflib/esm/namespace.js"); +/* harmony import */ var _parse__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./parse */ "./node_modules/rdflib/esm/parse.js"); +/* harmony import */ var _rdfaparser__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./rdfaparser */ "./node_modules/rdflib/esm/rdfaparser.js"); +/* harmony import */ var _rdfxmlparser__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./rdfxmlparser */ "./node_modules/rdflib/esm/rdfxmlparser.js"); +/* harmony import */ var _uri__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./uri */ "./node_modules/rdflib/esm/uri.js"); +/* harmony import */ var _utils_terms__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./utils/terms */ "./node_modules/rdflib/esm/utils/terms.js"); +/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./utils-js */ "./node_modules/rdflib/esm/utils-js.js"); +/* harmony import */ var _serialize__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ./serialize */ "./node_modules/rdflib/esm/serialize.js"); +/* harmony import */ var cross_fetch__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! cross-fetch */ "./node_modules/cross-fetch/dist/browser-ponyfill.js"); +/* harmony import */ var cross_fetch__WEBPACK_IMPORTED_MODULE_20___default = /*#__PURE__*/__webpack_require__.n(cross_fetch__WEBPACK_IMPORTED_MODULE_20__); +/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ./types */ "./node_modules/rdflib/esm/types.js"); +/* harmony import */ var _utils_termValue__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ./utils/termValue */ "./node_modules/rdflib/esm/utils/termValue.js"); +/* harmony import */ var _jsonldparser__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! ./jsonldparser */ "./node_modules/rdflib/esm/jsonldparser.js"); + + + + + + + + + +function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5___default()(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5___default()(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4___default()(this, result); }; } + +function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } + +/* global $SolidTestEnvironment */ + +/** + * + * Project: rdflib.js + * + * @file: fetcher.js + * + * Description: contains functions for requesting/fetching/retracting + * This implements quite a lot of the web architecture. + * A fetcher is bound to a specific quad store, into which + * it loads stuff and into which it writes its metadata + * @@ The metadata could be optionally a separate graph + * + * - implements semantics of HTTP headers, Internet Content Types + * - selects parsers for rdf/xml, n3, rdfa, grddl + * + * TO do: + * - Implement a runtime registry for parsers and serializers + * - + */ + +/** + * Things to test: callbacks on request, refresh, retract + * loading from HTTP, HTTPS, FTP, FILE, others? + * To do: + * Firing up a mail client for mid: (message:) URLs + */ + + + + + + + + + + + + + + + + +var Parsable = { + 'text/n3': true, + 'text/turtle': true, + 'application/rdf+xml': true, + 'application/xhtml+xml': true, + 'text/html': true, + 'application/ld+json': true +}; // This is a minimal set to allow the use of damaged servers if necessary + +var CONTENT_TYPE_BY_EXT = { + 'rdf': _types__WEBPACK_IMPORTED_MODULE_21__["RDFXMLContentType"], + 'owl': _types__WEBPACK_IMPORTED_MODULE_21__["RDFXMLContentType"], + 'n3': 'text/n3', + 'ttl': 'text/turtle', + 'nt': 'text/n3', + 'acl': 'text/n3', + 'html': 'text/html', + 'xml': 'text/xml' +}; // Convenience namespaces needed in this module. +// These are deliberately not exported as the user application should +// make its own list and not rely on the prefixes used here, +// and not be tempted to add to them, and them clash with those of another +// application. + +var getNS = function getNS(factory) { + return { + link: Object(_namespace__WEBPACK_IMPORTED_MODULE_12__["default"])('http://www.w3.org/2007/ont/link#', factory), + http: Object(_namespace__WEBPACK_IMPORTED_MODULE_12__["default"])('http://www.w3.org/2007/ont/http#', factory), + httph: Object(_namespace__WEBPACK_IMPORTED_MODULE_12__["default"])('http://www.w3.org/2007/ont/httph#', factory), + // headers + rdf: Object(_namespace__WEBPACK_IMPORTED_MODULE_12__["default"])('http://www.w3.org/1999/02/22-rdf-syntax-ns#', factory), + rdfs: Object(_namespace__WEBPACK_IMPORTED_MODULE_12__["default"])('http://www.w3.org/2000/01/rdf-schema#', factory), + dc: Object(_namespace__WEBPACK_IMPORTED_MODULE_12__["default"])('http://purl.org/dc/elements/1.1/', factory), + ldp: Object(_namespace__WEBPACK_IMPORTED_MODULE_12__["default"])('http://www.w3.org/ns/ldp#', factory) + }; +}; + +var ns = getNS(); + +var Handler = // TODO: Document, type +// TODO: Document, type +function Handler(response, dom) { + _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_6___default()(this, Handler); + + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_7___default()(this, "response", void 0); + + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_7___default()(this, "dom", void 0); + + this.response = response; // The type assertion operator here might need to be removed. + + this.dom = dom; +}; + +_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_7___default()(Handler, "pattern", void 0); + +var RDFXMLHandler = /*#__PURE__*/function (_Handler) { + _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3___default()(RDFXMLHandler, _Handler); + + var _super = _createSuper(RDFXMLHandler); + + function RDFXMLHandler() { + _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_6___default()(this, RDFXMLHandler); + + return _super.apply(this, arguments); + } + + _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_2___default()(RDFXMLHandler, [{ + key: "parse", + value: function parse(fetcher, + /** An XML String */ + responseText, + /** Requires .original */ + options) { + var kb = fetcher.store; + + if (!this.dom) { + this.dom = _utils_js__WEBPACK_IMPORTED_MODULE_18__["parseXML"](responseText); + } + + var root = this.dom.documentElement; + + if (root.nodeName === 'parsererror') { + // Mozilla only See issue/issue110 + // have to fail the request + return fetcher.failFetch(options, 'Badly formed XML in ' + options.resource.value, 'parse_error'); + } + + var parser = new _rdfxmlparser__WEBPACK_IMPORTED_MODULE_15__["default"](kb); + + try { + parser.parse(this.dom, options.original.value, options.original); + } catch (err) { + return fetcher.failFetch(options, 'Syntax error parsing RDF/XML! ' + err, 'parse_error'); + } + + if (!options.noMeta) { + kb.add(options.original, ns.rdf('type'), ns.link('RDFDocument'), fetcher.appNode); + } + + return fetcher.doneFetch(options, this.response); + } + }], [{ + key: "toString", + value: function toString() { + return 'RDFXMLHandler'; + } + }, { + key: "register", + value: function register(fetcher) { + fetcher.mediatypes[_types__WEBPACK_IMPORTED_MODULE_21__["RDFXMLContentType"]] = { + 'q': 0.9 + }; + } + }]); + + return RDFXMLHandler; +}(Handler); + +RDFXMLHandler.pattern = new RegExp('application/rdf\\+xml'); + +var XHTMLHandler = /*#__PURE__*/function (_Handler2) { + _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3___default()(XHTMLHandler, _Handler2); + + var _super2 = _createSuper(XHTMLHandler); + + function XHTMLHandler() { + _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_6___default()(this, XHTMLHandler); + + return _super2.apply(this, arguments); + } + + _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_2___default()(XHTMLHandler, [{ + key: "parse", + value: function parse(fetcher, responseText, options) { + var relation, reverse; + + if (!this.dom) { + this.dom = _utils_js__WEBPACK_IMPORTED_MODULE_18__["parseXML"](responseText); + } + + var kb = fetcher.store; // dc:title + + var title = this.dom.getElementsByTagName('title'); + + if (title.length > 0) { + kb.add(options.resource, ns.dc('title'), kb.rdfFactory.literal(title[0].textContent), options.resource); // log.info("Inferring title of " + xhr.resource) + } // link rel + + + var links = this.dom.getElementsByTagName('link'); + + for (var x = links.length - 1; x >= 0; x--) { + // @@ rev + relation = links[x].getAttribute('rel'); + reverse = false; + + if (!relation) { + relation = links[x].getAttribute('rev'); + reverse = true; + } + + if (relation) { + fetcher.linkData(options.original, relation, links[x].getAttribute('href'), options.resource, reverse); + } + } // Data Islands + + + var scripts = this.dom.getElementsByTagName('script'); + + for (var i = 0; i < scripts.length; i++) { + var contentType = scripts[i].getAttribute('type'); + + if (Parsable[contentType]) { + // @ts-ignore incompatibility between Store.add and Formula.add + Object(_parse__WEBPACK_IMPORTED_MODULE_13__["default"])(scripts[i].textContent, kb, options.original.value, contentType); // @ts-ignore incompatibility between Store.add and Formula.add + + Object(_parse__WEBPACK_IMPORTED_MODULE_13__["default"])(scripts[i].textContent, kb, options.original.value, contentType); + } + } + + if (!options.noMeta) { + kb.add(options.resource, ns.rdf('type'), ns.link('WebPage'), fetcher.appNode); + } + + if (!options.noRDFa && _rdfaparser__WEBPACK_IMPORTED_MODULE_14__["parseRDFaDOM"]) { + // enable by default + try { + Object(_rdfaparser__WEBPACK_IMPORTED_MODULE_14__["parseRDFaDOM"])(this.dom, kb, options.original.value); + } catch (err) { + var msg = 'Error trying to parse ' + options.resource + ' as RDFa:\n' + err + ':\n' + err.stack; + return fetcher.failFetch(options, msg, 'parse_error'); + } + } + + return fetcher.doneFetch(options, this.response); + } + }], [{ + key: "toString", + value: function toString() { + return 'XHTMLHandler'; + } + }, { + key: "register", + value: function register(fetcher) { + fetcher.mediatypes[_types__WEBPACK_IMPORTED_MODULE_21__["XHTMLContentType"]] = {}; + } + }]); + + return XHTMLHandler; +}(Handler); + +XHTMLHandler.pattern = new RegExp('application/xhtml'); + +var XMLHandler = /*#__PURE__*/function (_Handler3) { + _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3___default()(XMLHandler, _Handler3); + + var _super3 = _createSuper(XMLHandler); + + function XMLHandler() { + _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_6___default()(this, XMLHandler); + + return _super3.apply(this, arguments); + } + + _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_2___default()(XMLHandler, [{ + key: "parse", + value: function parse(fetcher, responseText, options) { + var dom = _utils_js__WEBPACK_IMPORTED_MODULE_18__["parseXML"](responseText); // XML Semantics defined by root element namespace + // figure out the root element + + for (var c = 0; c < dom.childNodes.length; c++) { + // is this node an element? + if (dom.childNodes[c].nodeType === 1) { + // We've found the first element, it's the root + var _ns = dom.childNodes[c].namespaceURI; // Is it RDF/XML? + + if (_ns && _ns === _ns['rdf']) { + fetcher.addStatus(options.req, 'Has XML root element in the RDF namespace, so assume RDF/XML.'); + var rdfHandler = new RDFXMLHandler(this.response, dom); + return rdfHandler.parse(fetcher, responseText, options); + } + + break; + } + } // Or it could be XHTML? + // Maybe it has an XHTML DOCTYPE? + + + if (dom.doctype) { + // log.info("We found a DOCTYPE in " + xhr.resource) + if (dom.doctype.name === 'html' && dom.doctype.publicId.match(/^-\/\/W3C\/\/DTD XHTML/) && dom.doctype.systemId.match(/http:\/\/www.w3.org\/TR\/xhtml/)) { + fetcher.addStatus(options.req, 'Has XHTML DOCTYPE. Switching to XHTML Handler.\n'); + var xhtmlHandler = new XHTMLHandler(this.response, dom); + return xhtmlHandler.parse(fetcher, responseText, options); + } + } // Or what about an XHTML namespace? + + + var html = dom.getElementsByTagName('html')[0]; + + if (html) { + var xmlns = html.getAttribute('xmlns'); + + if (xmlns && xmlns.match(/^http:\/\/www.w3.org\/1999\/xhtml/)) { + fetcher.addStatus(options.req, 'Has a default namespace for ' + 'XHTML. Switching to XHTMLHandler.\n'); + + var _xhtmlHandler = new XHTMLHandler(this.response, dom); + + return _xhtmlHandler.parse(fetcher, responseText, options); + } + } // At this point we should check the namespace document (cache it!) and + // look for a GRDDL transform + // @@ Get namespace document , parse it, look for grddl:namespaceTransform ?y + // Apply ?y to dom + // We give up. What dialect is this? + + + return fetcher.failFetch(options, 'Unsupported dialect of XML: not RDF or XHTML namespace, etc.\n' + responseText.slice(0, 80), 901); + } + }], [{ + key: "toString", + value: function toString() { + return 'XMLHandler'; + } + }, { + key: "register", + value: function register(fetcher) { + fetcher.mediatypes['text/xml'] = { + 'q': 0.5 + }; + fetcher.mediatypes['application/xml'] = { + 'q': 0.5 + }; + } + }]); + + return XMLHandler; +}(Handler); + +XMLHandler.pattern = new RegExp('(text|application)/(.*)xml'); + +var HTMLHandler = /*#__PURE__*/function (_Handler4) { + _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3___default()(HTMLHandler, _Handler4); + + var _super4 = _createSuper(HTMLHandler); + + function HTMLHandler() { + _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_6___default()(this, HTMLHandler); + + return _super4.apply(this, arguments); + } + + _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_2___default()(HTMLHandler, [{ + key: "parse", + value: function parse(fetcher, responseText, options) { + var kb = fetcher.store; // We only handle XHTML so we have to figure out if this is XML + // log.info("Sniffing HTML " + xhr.resource + " for XHTML.") + + if (isXML(responseText)) { + fetcher.addStatus(options.req, "Has an XML declaration. We'll assume " + "it's XHTML as the content-type was text/html.\n"); + var xhtmlHandler = new XHTMLHandler(this.response); + return xhtmlHandler.parse(fetcher, responseText, options); + } // DOCTYPE html + + + if (isXHTML(responseText)) { + fetcher.addStatus(options.req, 'Has XHTML DOCTYPE. Switching to XHTMLHandler.\n'); + + var _xhtmlHandler2 = new XHTMLHandler(this.response); + + return _xhtmlHandler2.parse(fetcher, responseText, options); + } // xmlns + + + if (isXMLNS(responseText)) { + fetcher.addStatus(options.req, 'Has default namespace for XHTML, so switching to XHTMLHandler.\n'); + + var _xhtmlHandler3 = new XHTMLHandler(this.response); + + return _xhtmlHandler3.parse(fetcher, responseText, options); + } // dc:title + // no need to escape '/' here + + + var titleMatch = new RegExp('([\\s\\S]+?)', 'im').exec(responseText); + + if (titleMatch) { + kb.add(options.resource, ns.dc('title'), kb.rdfFactory.literal(titleMatch[1]), options.resource); // think about xml:lang later + } + + kb.add(options.resource, ns.rdf('type'), ns.link('WebPage'), fetcher.appNode); + fetcher.addStatus(options.req, 'non-XML HTML document, not parsed for data.'); + return fetcher.doneFetch(options, this.response); + } + }], [{ + key: "toString", + value: function toString() { + return 'HTMLHandler'; + } + }, { + key: "register", + value: function register(fetcher) { + fetcher.mediatypes['text/html'] = { + 'q': 0.9 + }; + } + }]); + + return HTMLHandler; +}(Handler); + +HTMLHandler.pattern = new RegExp('text/html'); + +var JsonLdHandler = /*#__PURE__*/function (_Handler5) { + _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3___default()(JsonLdHandler, _Handler5); + + var _super5 = _createSuper(JsonLdHandler); + + function JsonLdHandler() { + _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_6___default()(this, JsonLdHandler); + + return _super5.apply(this, arguments); + } + + _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_2___default()(JsonLdHandler, [{ + key: "parse", + value: function parse(fetcher, responseText, options, response) { + var kb = fetcher.store; + return new Promise(function (resolve, reject) { + try { + Object(_jsonldparser__WEBPACK_IMPORTED_MODULE_23__["default"])(responseText, kb, options.original.value, resolve); + } catch (err) { + var msg = 'Error trying to parse ' + options.resource + ' as JSON-LD:\n' + err; // not err.stack -- irrelevant + + resolve(fetcher.failFetch(options, msg, 'parse_error', response)); + } + }); + } + }], [{ + key: "toString", + value: function toString() { + return 'JsonLdHandler'; + } + }, { + key: "register", + value: function register(fetcher) { + fetcher.mediatypes['application/ld+json'] = { + 'q': 0.9 + }; + } + }]); + + return JsonLdHandler; +}(Handler); + +JsonLdHandler.pattern = /application\/ld\+json/; + +var TextHandler = /*#__PURE__*/function (_Handler6) { + _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3___default()(TextHandler, _Handler6); + + var _super6 = _createSuper(TextHandler); + + function TextHandler() { + _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_6___default()(this, TextHandler); + + return _super6.apply(this, arguments); + } + + _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_2___default()(TextHandler, [{ + key: "parse", + value: function parse(fetcher, responseText, options) { + // We only speak dialects of XML right now. Is this XML? + // Look for an XML declaration + if (isXML(responseText)) { + fetcher.addStatus(options.req, 'Warning: ' + options.resource + " has an XML declaration. We'll assume " + "it's XML but its content-type wasn't XML.\n"); + var xmlHandler = new XMLHandler(this.response); + return xmlHandler.parse(fetcher, responseText, options); + } // Look for an XML declaration + + + if (responseText.slice(0, 500).match(/xmlns:/)) { + fetcher.addStatus(options.req, "May have an XML namespace. We'll assume " + "it's XML but its content-type wasn't XML.\n"); + + var _xmlHandler = new XMLHandler(this.response); + + return _xmlHandler.parse(fetcher, responseText, options); + } // We give up finding semantics - this is not an error, just no data + + + fetcher.addStatus(options.req, 'Plain text document, no known RDF semantics.'); + return fetcher.doneFetch(options, this.response); + } + }], [{ + key: "toString", + value: function toString() { + return 'TextHandler'; + } + }, { + key: "register", + value: function register(fetcher) { + fetcher.mediatypes['text/plain'] = { + 'q': 0.5 + }; + } + }]); + + return TextHandler; +}(Handler); + +TextHandler.pattern = new RegExp('text/plain'); + +var N3Handler = /*#__PURE__*/function (_Handler7) { + _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3___default()(N3Handler, _Handler7); + + var _super7 = _createSuper(N3Handler); + + function N3Handler() { + _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_6___default()(this, N3Handler); + + return _super7.apply(this, arguments); + } + + _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_2___default()(N3Handler, [{ + key: "parse", + value: function parse(fetcher, responseText, options, response) { + // Parse the text of this N3 file + var kb = fetcher.store; + var p = Object(_n3parser__WEBPACK_IMPORTED_MODULE_10__["default"])(kb, kb, options.original.value, options.original.value, null, null, '', null); // p.loadBuf(xhr.responseText) + + try { + p.loadBuf(responseText); + } catch (err) { + var msg = 'Error trying to parse ' + options.resource + ' as Notation3:\n' + err; // not err.stack -- irrelevant + + return fetcher.failFetch(options, msg, 'parse_error', response); + } + + fetcher.addStatus(options.req, 'N3 parsed: ' + p.statementCount + ' triples in ' + p.lines + ' lines.'); + fetcher.store.add(options.original, ns.rdf('type'), ns.link('RDFDocument'), fetcher.appNode); + return fetcher.doneFetch(options, this.response); + } + }], [{ + key: "toString", + value: function toString() { + return 'N3Handler'; + } + }, { + key: "register", + value: function register(fetcher) { + fetcher.mediatypes['text/n3'] = { + 'q': '1.0' + }; // as per 2008 spec + + /* + fetcher.mediatypes['application/x-turtle'] = { + 'q': 1.0 + } // pre 2008 + */ + + fetcher.mediatypes['text/turtle'] = { + 'q': 1.0 + }; // post 2008 + } + }]); + + return N3Handler; +}(Handler); + +N3Handler.pattern = new RegExp('(application|text)/(x-)?(rdf\\+)?(n3|turtle)'); +var defaultHandlers = { + RDFXMLHandler: RDFXMLHandler, + XHTMLHandler: XHTMLHandler, + XMLHandler: XMLHandler, + HTMLHandler: HTMLHandler, + TextHandler: TextHandler, + N3Handler: N3Handler, + JsonLdHandler: JsonLdHandler +}; + +function isXHTML(responseText) { + var docTypeStart = responseText.indexOf(''); + + if (docTypeStart === -1 || docTypeEnd === -1 || docTypeStart > docTypeEnd) { + return false; + } + + return responseText.substr(docTypeStart, docTypeEnd - docTypeStart).indexOf('XHTML') !== -1; +} + +function isXML(responseText) { + var match = responseText.match(/\s*<\?xml\s+version\s*=[^<>]+\?>/); + return !!match; +} + +function isXMLNS(responseText) { + var match = responseText.match(/[^(/); + return !!match; +} + +/** Fetcher + * + * The Fetcher object is a helper object for a quadstore + * which turns it from an offline store to an online store. + * The fetcher deals with loading data files rom the web, + * figuring how to parse them. It will also refresh, remove, the data + * and put back the fata to the web. + */ +var Fetcher = /*#__PURE__*/function () { + /** Denoting this session */ + + /** + * this.requested[uri] states: + * undefined no record of web access or records reset + * true has been requested, fetch in progress + * 'done' received, Ok + * 401 Not logged in + * 403 HTTP status unauthorized + * 404 Resource does not exist. Can be created etc. + * 'redirected' In attempt to counter CORS problems retried. + * 'parse_error' Parse error + * 'unsupported_protocol' URI is not a protocol Fetcher can deal with + * other strings mean various other errors. + */ + + /** List of timeouts associated with a requested URL */ + + /** Redirected from *key uri* to *value uri* */ + + /** fetchCallbacks[uri].push(callback) */ + + /** Keep track of explicit 404s -> we can overwrite etc */ + // TODO: Document this + + /** Methods added by calling Util.callbackify in the constructor*/ + function Fetcher(store) { + var _this = this; + + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_6___default()(this, Fetcher); + + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_7___default()(this, "store", void 0); + + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_7___default()(this, "timeout", void 0); + + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_7___default()(this, "_fetch", void 0); + + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_7___default()(this, "mediatypes", void 0); + + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_7___default()(this, "appNode", void 0); + + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_7___default()(this, "requested", void 0); + + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_7___default()(this, "timeouts", void 0); + + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_7___default()(this, "redirectedTo", void 0); + + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_7___default()(this, "fetchQueue", void 0); + + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_7___default()(this, "fetchCallbacks", void 0); + + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_7___default()(this, "nonexistent", void 0); + + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_7___default()(this, "lookedUp", void 0); + + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_7___default()(this, "handlers", void 0); + + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_7___default()(this, "ns", void 0); + + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_7___default()(this, "fireCallbacks", void 0); + + this.store = store || new _store__WEBPACK_IMPORTED_MODULE_8__["default"](); + this.ns = getNS(this.store.rdfFactory); + this.timeout = options.timeout || 30000; + + this._fetch = options.fetch || typeof window !== 'undefined' && window.solidFetcher || cross_fetch__WEBPACK_IMPORTED_MODULE_20___default.a; + + if (!this._fetch) { + throw new Error('No _fetch function available for Fetcher'); + } + + this.appNode = this.store.rdfFactory.blankNode(); + this.store.fetcher = this; // Bi-linked + + this.requested = {}; + this.timeouts = {}; + this.redirectedTo = {}; + this.fetchQueue = {}; + this.fetchCallbacks = {}; + this.nonexistent = {}; + this.lookedUp = {}; + this.handlers = []; + this.mediatypes = { + 'image/*': { + 'q': 0.9 + }, + '*/*': { + 'q': 0.1 + } // Must allow access to random content + + }; // Util.callbackify(this, ['request', 'recv', 'headers', 'load', 'fail', + // 'refresh', 'retract', 'done']) + // In switching to fetch(), 'recv', 'headers' and 'load' do not make sense + + _utils_js__WEBPACK_IMPORTED_MODULE_18__["callbackify"](this, ['request', 'fail', 'refresh', 'retract', 'done']); + Object.keys(options.handlers || defaultHandlers).map(function (key) { + return _this.addHandler(defaultHandlers[key]); + }); + } + + _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_2___default()(Fetcher, [{ + key: "load", + + /** + * Promise-based load function + * + * Loads a web resource or resources into the store. + * + * A resource may be given as NamedNode object, or as a plain URI. + * an array of resources will be given, in which they will be fetched in parallel. + * By default, the HTTP headers are recorded also, in the same store, in a separate graph. + * This allows code like editable() for example to test things about the resource. + * + * @param uri {Array|Array|RDFlibNamedNode|string} + * + * @param [options={}] {Object} + * + * @param [options.fetch] {Function} + * + * @param [options.referringTerm] {RDFlibNamedNode} Referring term, the resource which + * referred to this (for tracking bad links) + * + * @param [options.contentType] {string} Provided content type (for writes) + * + * @param [options.forceContentType] {string} Override the incoming header to + * force the data to be treated as this content-type (for reads) + * + * @param [options.force] {boolean} Load the data even if loaded before. + * Also sets the `Cache-Control:` header to `no-cache` + * + * @param [options.baseURI=docuri] {Node|string} Original uri to preserve + * through proxying etc (`xhr.original`). + * + * @param [options.proxyUsed] {boolean} Whether this request is a retry via + * a proxy (generally done from an error handler) + * + * @param [options.withCredentials] {boolean} flag for XHR/CORS etc + * + * @param [options.clearPreviousData] {boolean} Before we parse new data, + * clear old, but only on status 200 responses + * + * @param [options.noMeta] {boolean} Prevents the addition of various metadata + * triples (about the fetch request) to the store + * + * @param [options.noRDFa] {boolean} + * + * @returns {Promise} + */ + value: function load(uri) { + var _this2 = this; + + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + options = Object.assign({}, options); // Take a copy as we add stuff to the options!! + + if (uri instanceof Array) { + return Promise.all(uri.map(function (x) { + return _this2.load(x, Object.assign({}, options)); + })); + } + + var uriIn = uri; + var docuri = Object(_utils_termValue__WEBPACK_IMPORTED_MODULE_22__["termValue"])(uriIn); + docuri = docuri.split('#')[0]; + options = this.initFetchOptions(docuri, options); + var initialisedOptions = this.initFetchOptions(docuri, options); + return this.pendingFetchPromise(docuri, initialisedOptions.baseURI, initialisedOptions); + } + }, { + key: "pendingFetchPromise", + value: function pendingFetchPromise(uri, originalUri, options) { + var _this3 = this; + + var pendingPromise; // Check to see if some request is already dealing with this uri + + if (!options.force && this.fetchQueue[originalUri]) { + pendingPromise = this.fetchQueue[originalUri]; + } else { + pendingPromise = Promise.race([this.setRequestTimeout(uri, options), this.fetchUri(uri, options)]); + this.fetchQueue[originalUri] = pendingPromise; // Clean up the queued promise after a time, if it's resolved + + this.cleanupFetchRequest(originalUri, undefined, this.timeout); + } + + return pendingPromise.then(function (x) { + if (uri in _this3.timeouts) { + _this3.timeouts[uri].forEach(clearTimeout); + + delete _this3.timeouts[uri]; + } + + return x; + }); + } + /** + * @param _options - DEPRECATED + */ + + }, { + key: "cleanupFetchRequest", + value: function cleanupFetchRequest(originalUri, _options, timeout) { + var _this4 = this; + + if (_options !== undefined) { + console.warn("_options is deprecated"); + } + + this.timeouts[originalUri] = (this.timeouts[originalUri] || []).concat(setTimeout(function () { + if (!_this4.isPending(originalUri)) { + delete _this4.fetchQueue[originalUri]; + } + }, timeout)); + } + }, { + key: "initFetchOptions", + value: function initFetchOptions(uri, options) { + var kb = this.store; + var isGet = !options.method || options.method.toUpperCase() === 'GET'; + + if (!isGet) { + options.force = true; + } + + options.resource = kb.rdfFactory.namedNode(uri); // This might be proxified + + options.baseURI = options.baseURI || uri; // Preserve though proxying etc + + options.original = kb.rdfFactory.namedNode(options.baseURI); + options.req = kb.bnode(); + options.headers = options.headers || new cross_fetch__WEBPACK_IMPORTED_MODULE_20__["Headers"](); + + if (options.contentType) { + options.headers['content-type'] = options.contentType; + } + + if (options.force) { + options.cache = 'no-cache'; + } + + var acceptString = this.acceptString(); + options.headers['accept'] = acceptString; + var requestedURI = Fetcher.offlineOverride(uri); + options.requestedURI = requestedURI; + Fetcher.setCredentials(requestedURI, options); + var actualProxyURI = Fetcher.proxyIfNecessary(requestedURI); + + if (requestedURI !== actualProxyURI) { + options.proxyUsed = true; + } + + options.actualProxyURI = actualProxyURI; + return options; + } + /** + * (The promise chain ends in either a `failFetch()` or a `doneFetch()`) + * + * @param docuri {string} + * @param options {Object} + * + * @returns {Promise} fetch() result or an { error, status } object + */ + + }, { + key: "fetchUri", + value: function fetchUri(docuri, options) { + var _this5 = this; + + if (!docuri) { + return Promise.reject(new Error('Cannot fetch an empty uri')); + } + + if (Fetcher.unsupportedProtocol(docuri)) { + return this.failFetch(options, 'fetcher: Unsupported protocol', 'unsupported_protocol'); + } + + var state = this.getState(docuri); + + if (!options.force) { + if (state === 'fetched') { + // URI already fetched and added to store + return Promise.resolve( // @ts-ignore This is not a valid response object + this.doneFetch(options, { + status: 200, + ok: true, + statusText: 'Already loaded into quadstore.' + })); + } + + if (state === 'failed' && this.requested[docuri] === 404) { + // Remember nonexistence + var _message = 'Previously failed: ' + this.requested[docuri]; // @ts-ignore This is not a valid response object + + + var dummyResponse = { + url: docuri, + // This does not comply to Fetch spec, it can be a string value in rdflib + status: this.requested[docuri], + statusText: _message, + responseText: _message, + headers: new cross_fetch__WEBPACK_IMPORTED_MODULE_20__["Headers"](), + // Headers() ??? + ok: false, + body: null, + bodyUsed: false, + size: 0, + timeout: 0 + }; + return this.failFetch(options, _message, this.requested[docuri], dummyResponse); + } + } else { + // options.force == true + delete this.nonexistent[docuri]; + } + + this.fireCallbacks('request', [docuri]); + this.requested[docuri] = true; // mark this uri as 'requested' + + if (!options.noMeta) { + this.saveRequestMetadata(docuri, options); + } + + var actualProxyURI = options.actualProxyURI; + return this._fetch(actualProxyURI, options).then(function (response) { + return _this5.handleResponse(response, docuri, options); + }, function (error) { + // @@ handleError? + // @ts-ignore Invalid response object + var dummyResponse = { + url: actualProxyURI, + status: 999, + // @@ what number/string should fetch failures report? + statusText: (error.name || 'network failure') + ': ' + (error.errno || error.code || error.type), + responseText: error.message, + headers: new cross_fetch__WEBPACK_IMPORTED_MODULE_20__["Headers"](), + // Headers() ??? + ok: false, + body: null, + bodyUsed: false, + size: 0, + timeout: 0 + }; + console.log('Fetcher: <' + actualProxyURI + '> Non-HTTP fetch exception: ' + error); + return _this5.handleError(dummyResponse, docuri, options); // possible credentials retry + // return this.failFetch(options, 'fetch failed: ' + error, 999, dummyResponse) // Fake status code: fetch exception + // handleError expects a response so we fake some important bits. + + /* + this.handleError(, docuri, options) + */ + }); + } + /** + * Asks for a doc to be loaded if necessary then calls back + * + * Calling methods: + * nowOrWhenFetched (uri, userCallback) + * nowOrWhenFetched (uri, options, userCallback) + * nowOrWhenFetched (uri, referringTerm, userCallback, options) <-- old + * nowOrWhenFetched (uri, referringTerm, userCallback) <-- old + * + * Options include: + * referringTerm The document in which this link was found. + * this is valuable when finding the source of bad URIs + * force boolean. Never mind whether you have tried before, + * load this from scratch. + * forceContentType Override the incoming header to force the data to be + * treated as this content-type. + * + * Callback function takes: + * + * ok True if the fetch worked, and got a 200 response. + * False if any error happened + * + * errmessage Text error message if not OK. + * + * response The fetch Response object (was: XHR) if there was was one + * includes response.status as the HTTP status if any. + */ + + }, { + key: "nowOrWhenFetched", + value: function nowOrWhenFetched(uriIn, p2, userCallback) { + var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; + var uri = Object(_utils_termValue__WEBPACK_IMPORTED_MODULE_22__["termValue"])(uriIn); + + if (typeof p2 === 'function') { + // nowOrWhenFetched (uri, userCallback) + userCallback = p2; + } else if (typeof p2 === 'undefined') {// original calling signature + // referringTerm = undefined + } else if (Object(_utils_terms__WEBPACK_IMPORTED_MODULE_17__["isNamedNode"])(p2)) { + // referringTerm = p2 + options.referringTerm = p2; + } else { + // nowOrWhenFetched (uri, options, userCallback) + options = p2; + } + + this.load(uri, options).then(function (fetchResponse) { + if (userCallback) { + if (fetchResponse) { + if (fetchResponse.ok) { + userCallback(true, 'OK', fetchResponse); + } else { + // console.log('@@@ fetcher.js Should not take this path !!!!!!!!!!!!') + var oops = 'HTTP error: Status ' + fetchResponse.status + ' (' + fetchResponse.statusText + ')'; + + if (fetchResponse.responseText) { + oops += ' ' + fetchResponse.responseText; // not in 404, dns error, nock failure + } + + console.log(oops + ' fetching ' + uri); + userCallback(false, oops, fetchResponse); + } + } else { + var _oops = '@@ nowOrWhenFetched: no response object!'; + console.log(_oops); + userCallback(false, _oops); + } + } + }, function (err) { + var message = err.message || err.statusText; + message = 'Failed to load <' + uri + '> ' + message; + console.log(message); + + if (err.response && err.response.status) { + message += ' status: ' + err.response.status; + } + + userCallback(false, message, err.response); + }); + } + /** + * Records a status message (as a literal node) by appending it to the + * request's metadata status collection. + * + */ + + }, { + key: "addStatus", + value: function addStatus(req, statusMessage) { + // + var now = new Date(); + statusMessage = '[' + now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds() + '.' + now.getMilliseconds() + '] ' + statusMessage; // + + var kb = this.store; + var statusNode = kb.the(req, this.ns.link('status')); + + if (Object(_utils_terms__WEBPACK_IMPORTED_MODULE_17__["isCollection"])(statusNode)) { + statusNode.append(kb.rdfFactory.literal(statusMessage)); + } else { + _log__WEBPACK_IMPORTED_MODULE_9__["default"].warn('web.js: No list to add to: ' + statusNode + ',' + statusMessage); + } + } + /** + * Records errors in the system on failure: + * + * - Adds an entry to the request status collection + * - Adds an error triple with the fail message to the metadata + * - Fires the 'fail' callback + * - Rejects with an error result object, which has a response object if any + */ + + }, { + key: "failFetch", + value: function failFetch(options, errorMessage, statusCode, response) { + this.addStatus(options.req, errorMessage); + + if (!options.noMeta) { + this.store.add(options.original, this.ns.link('error'), this.store.rdfFactory.literal(errorMessage)); + } + + var meth = (options.method || 'GET').toUpperCase(); + var isGet = meth === 'GET' || meth === 'HEAD'; + + if (isGet) { + // only cache the status code on GET or HEAD + if (!options.resource.equals(options.original)) {// console.log('@@ Recording failure ' + meth + ' original ' + options.original +option '( as ' + options.resource + ') : ' + statusCode) + } else {// console.log('@@ Recording ' + meth + ' failure for ' + options.original + ': ' + statusCode) + } + + this.requested[_uri__WEBPACK_IMPORTED_MODULE_16__["docpart"](options.original.value)] = statusCode; + this.fireCallbacks('fail', [options.original.value, errorMessage]); + } + + var err = new Error('Fetcher: ' + errorMessage); // err.ok = false // Is taken as a response, will work too @@ phase out? + + err.status = statusCode; + err.statusText = errorMessage; + err.response = response; + return Promise.reject(err); + } // in the why part of the quad distinguish between HTML and HTTP header + // Reverse is set iif the link was rev= as opposed to rel= + + }, { + key: "linkData", + value: function linkData(originalUri, rel, uri, why, reverse) { + if (!uri) return; + var kb = this.store; + var predicate; // See http://www.w3.org/TR/powder-dr/#httplink for describedby 2008-12-10 + + var obj = kb.rdfFactory.namedNode(_uri__WEBPACK_IMPORTED_MODULE_16__["join"](uri, originalUri.value)); + + if (rel === 'alternate' || rel === 'seeAlso' || rel === 'meta' || rel === 'describedby') { + if (obj.value === originalUri.value) { + return; + } + + predicate = this.ns.rdfs('seeAlso'); + } else if (rel === 'type') { + predicate = kb.rdfFactory.namedNode('http://www.w3.org/1999/02/22-rdf-syntax-ns#type'); + } else { + // See https://www.iana.org/assignments/link-relations/link-relations.xml + // Alas not yet in RDF yet for each predicate + // encode space in e.g. rel="shortcut icon" + predicate = kb.rdfFactory.namedNode(_uri__WEBPACK_IMPORTED_MODULE_16__["join"](encodeURIComponent(rel), 'http://www.iana.org/assignments/link-relations/')); + } + + if (reverse) { + kb.add(obj, predicate, originalUri, why); + } else { + kb.add(originalUri, predicate, obj, why); + } + } + }, { + key: "parseLinkHeader", + value: function parseLinkHeader(linkHeader, originalUri, reqNode) { + if (!linkHeader) { + return; + } // const linkexp = /<[^>]*>\s*(\s*;\s*[^()<>@,;:"/[\]?={} \t]+=(([^()<>@,;:"/[]?={} \t]+)|("[^"]*")))*(,|$)/g + // const paramexp = /[^()<>@,;:"/[]?={} \t]+=(([^()<>@,;:"/[]?={} \t]+)|("[^"]*"))/g + // From https://www.dcode.fr/regular-expression-simplificator: + // const linkexp = /<[^>]*>\s*(\s*;\s*[^()<>@,;:"/[\]?={} t]+=["]))*[,$]/g + // const paramexp = /[^\\<>@,;:"\/\[\]?={} \t]+=["])/g + // Original: + + + var linkexp = /<[^>]*>\s*(\s*;\s*[^()<>@,;:"/[\]?={} \t]+=(([^\(\)<>@,;:"\/\[\]\?={} \t]+)|("[^"]*")))*(,|$)/g; + var paramexp = /[^\(\)<>@,;:"\/\[\]\?={} \t]+=(([^\(\)<>@,;:"\/\[\]\?={} \t]+)|("[^"]*"))/g; + var matches = linkHeader.match(linkexp); + if (matches == null) return; + + for (var i = 0; i < matches.length; i++) { + var split = matches[i].split('>'); + var href = split[0].substring(1); + var ps = split[1]; + var s = ps.match(paramexp); + if (s == null) return; + + for (var j = 0; j < s.length; j++) { + var p = s[j]; + var paramsplit = p.split('='); // var name = paramsplit[0] + + var rel = paramsplit[1].replace(/["']/g, ''); // '" + + this.linkData(originalUri, rel, href, reqNode); + } + } + } + }, { + key: "doneFetch", + value: function doneFetch(options, response) { + this.addStatus(options.req, 'Done.'); + this.requested[options.original.value] = 'done'; + this.fireCallbacks('done', [options.original.value]); + response.req = options.req; // Set the request meta blank node + + return response; + } + /** + * Note two nodes are now smushed + * If only one was flagged as looked up, then the new node is looked up again, + * which will make sure all the URIs are dereferenced + */ + + }, { + key: "nowKnownAs", + value: function nowKnownAs(was, now) { + if (this.lookedUp[was.value]) { + // Transfer userCallback + if (!this.lookedUp[now.value]) { + this.lookUpThing(now, was); + } + } else if (this.lookedUp[now.value]) { + if (!this.lookedUp[was.value]) { + this.lookUpThing(was, now); + } + } + } + /** + * Writes back to the web what we have in the store for this uri + */ + + }, { + key: "putBack", + value: function putBack(uri) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + var uriSting = Object(_utils_termValue__WEBPACK_IMPORTED_MODULE_22__["termValue"])(uri); + var doc = new _named_node__WEBPACK_IMPORTED_MODULE_11__["default"](uriSting).doc(); // strip off # + + options.contentType = options.contentType || _types__WEBPACK_IMPORTED_MODULE_21__["TurtleContentType"]; + options.data = Object(_serialize__WEBPACK_IMPORTED_MODULE_19__["default"])(doc, this.store, doc.value, options.contentType); + return this.webOperation('PUT', uriSting, options); + } + }, { + key: "webCopy", + value: function webCopy(here, there, contentType) { + var _this6 = this; + + return this.webOperation('GET', here).then(function (result) { + return _this6.webOperation('PUT', // change to binary from text + there, { + data: result.responseText, + contentType: contentType + }); + }); + } + }, { + key: "delete", + value: function _delete(uri, options) { + var _this7 = this; + + return this.webOperation('DELETE', uri, options).then(function (response) { + _this7.requested[uri] = 404; + _this7.nonexistent[uri] = true; + + _this7.unload(_this7.store.rdfFactory.namedNode(uri)); + + return response; + }); + } + /** Create an empty resource if it really does not exist + * Be absolutely sure something does not exist before creating a new empty file + * as otherwise existing could be deleted. + * @param doc - The resource + */ + + }, { + key: "createIfNotExists", + value: function () { + var _createIfNotExists = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee(doc) { + var contentType, + data, + fetcher, + response, + _args = arguments; + return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + contentType = _args.length > 1 && _args[1] !== undefined ? _args[1] : _types__WEBPACK_IMPORTED_MODULE_21__["TurtleContentType"]; + data = _args.length > 2 && _args[2] !== undefined ? _args[2] : ''; + fetcher = this; + _context.prev = 3; + _context.next = 6; + return fetcher.load(doc); + + case 6: + response = _context.sent; + _context.next = 29; + break; + + case 9: + _context.prev = 9; + _context.t0 = _context["catch"](3); + + if (!(_context.t0.response.status === 404)) { + _context.next = 27; + break; + } + + console.log('createIfNotExists: doc does NOT exist, will create... ' + doc); + _context.prev = 13; + _context.next = 16; + return fetcher.webOperation('PUT', doc.value, { + data: data, + contentType: contentType + }); + + case 16: + response = _context.sent; + _context.next = 23; + break; + + case 19: + _context.prev = 19; + _context.t1 = _context["catch"](13); + console.log('createIfNotExists doc FAILED: ' + doc + ': ' + _context.t1); + throw _context.t1; + + case 23: + delete fetcher.requested[doc.value]; // delete cached 404 error + // console.log('createIfNotExists doc created ok ' + doc) + + return _context.abrupt("return", response); + + case 27: + console.log('createIfNotExists doc load error NOT 404: ' + doc + ': ' + _context.t0); + throw _context.t0; + + case 29: + return _context.abrupt("return", response); + + case 30: + case "end": + return _context.stop(); + } + } + }, _callee, this, [[3, 9], [13, 19]]); + })); + + function createIfNotExists(_x) { + return _createIfNotExists.apply(this, arguments); + } + + return createIfNotExists; + }() + /** + * @param parentURI URI of parent container + * @param folderName - Optional folder name (slug) + * @param data - Optional folder metadata + */ + + }, { + key: "createContainer", + value: function createContainer(parentURI, folderName, data) { + var headers = { + // Force the right mime type for containers + 'content-type': _types__WEBPACK_IMPORTED_MODULE_21__["TurtleContentType"], + 'link': this.ns.ldp('BasicContainer') + '; rel="type"' + }; + + if (folderName) { + headers['slug'] = folderName; + } // @ts-ignore These headers lack some of the required operators. + + + var options = { + headers: headers + }; + + if (data) { + options.body = data; + } + + return this.webOperation('POST', parentURI, options); + } + }, { + key: "invalidateCache", + value: function invalidateCache(iri) { + var uri = Object(_utils_termValue__WEBPACK_IMPORTED_MODULE_22__["termValue"])(iri); + var fetcher = this; + + if (fetcher.fetchQueue && fetcher.fetchQueue[uri]) { + console.log('Internal error - fetchQueue exists ' + uri); + var promise = fetcher.fetchQueue[uri]; + + if (promise['PromiseStatus'] === 'resolved') { + delete fetcher.fetchQueue[uri]; + } else { + // pending + delete fetcher.fetchQueue[uri]; + console.log('*** Fetcher: pending fetchQueue deleted ' + uri); + } + } + + if (fetcher.requested[uri] && fetcher.requested[uri] !== 'done' && fetcher.requested[uri] !== 'failed' && fetcher.requested[uri] !== 404) { + var msg = "Rdflib: fetcher: Destructive operation on <".concat(fetcher.requested[uri], "> file being fetched! ") + uri; + console.error(msg); // alert(msg) + } else { + delete fetcher.requested[uri]; // invalidate read cache -- @@ messes up logic if request in progress ?? + + delete fetcher.nonexistent[uri]; + } + } + /** + * A generic web opeation, at the fetch() level. + * does not invole the quadstore. + * + * Returns promise of Response + * If data is returned, copies it to response.responseText before returning + */ + + }, { + key: "webOperation", + value: function webOperation(method, uriIn) { + var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + var uri = Object(_utils_termValue__WEBPACK_IMPORTED_MODULE_22__["termValue"])(uriIn); + options.method = method; + options.body = options.data || options.body; + options.force = true; + var fetcher = this; + + if (options.body && !options.contentType) { + throw new Error('Web operation sending data must have a defined contentType.'); + } + + if (options.contentType) { + options.headers = options.headers || {}; + options.headers['content-type'] = options.contentType; + } + + Fetcher.setCredentials(uri, options); + return new Promise(function (resolve, reject) { + fetcher._fetch(uri, options).then(function (response) { + if (response.ok) { + if (method === 'PUT' || method === 'PATCH' || method === 'POST' || method === 'DELETE') { + fetcher.invalidateCache(uri); + } + + if (response.body) { + response.text().then(function (data) { + response.responseText = data; + resolve(response); + }); + } else { + resolve(response); + } + } else { + var msg = 'Web error: ' + response.status; + if (response.statusText) msg += ' (' + response.statusText + ')'; + msg += ' on ' + method + ' of <' + uri + '>'; + if (response.responseText) msg += ': ' + response.responseText; + var e2 = new Error(msg); + e2.response = response; + reject(e2); + } + }, function (err) { + var msg = 'Fetch error for ' + method + ' of <' + uri + '>:' + err; + reject(new Error(msg)); + }); + }); + } + /** + * Looks up something. + * Looks up all the URIs a things has. + * + * @param term - canonical term for the thing whose URI is + * to be dereferenced + * @param rterm - the resource which referred to this + * (for tracking bad links) + */ + + }, { + key: "lookUpThing", + value: function lookUpThing(term, rterm) { + var _this8 = this; + + var uris = this.store.uris(term); // Get all URIs + + uris = uris.map(function (u) { + return _uri__WEBPACK_IMPORTED_MODULE_16__["docpart"](u); + }); // Drop hash fragments + + uris.forEach(function (u) { + _this8.lookedUp[u] = true; + }); // @ts-ignore Recursive type + + return this.load(uris, { + referringTerm: rterm + }); + } + /** + * Looks up response header. + * + * @returns {Array|undefined} a list of header values found in a stored HTTP + * response, or [] if response was found but no header found, + * or undefined if no response is available. + * Looks for { [] link:requestedURI ?uri; link:response [ httph:header-name ?value ] } + */ + + }, { + key: "getHeader", + value: function getHeader(doc, header) { + var kb = this.store; // look for the URI (AS A STRING NOT A NODE) for a stored request + + var docuri = doc.value; + var requests = kb.each(undefined, this.ns.link('requestedURI'), kb.rdfFactory.literal(docuri)); + + for (var r = 0; r < requests.length; r++) { + var request = requests[r]; + + if (request !== undefined) { + var _response = kb.any(request, this.ns.link('response')); + + if (_response !== undefined && kb.anyValue(_response, this.ns.http('status')) && kb.anyValue(_response, this.ns.http('status')).startsWith('2')) { + // Only look at success returns - not 401 error messagess etc + var results = kb.each(_response, this.ns.httph(header.toLowerCase())); + + if (results.length) { + return results.map(function (v) { + return v.value; + }); + } + + return []; + } + } + } + + return undefined; + } + }, { + key: "saveRequestMetadata", + value: function saveRequestMetadata(docuri, options) { + var req = options.req; + var kb = this.store; + var rterm = options.referringTerm; + this.addStatus(options.req, 'Accept: ' + options.headers['accept']); + + if (Object(_utils_terms__WEBPACK_IMPORTED_MODULE_17__["isNamedNode"])(rterm)) { + kb.add(kb.rdfFactory.namedNode(docuri), this.ns.link('requestedBy'), rterm, this.appNode); + } + + if (options.original && options.original.value !== docuri) { + kb.add(req, this.ns.link('orginalURI'), kb.rdfFactory.literal(options.original.value), this.appNode); + } + + var now = new Date(); + var timeNow = '[' + now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds() + '] '; + kb.add(req, this.ns.rdfs('label'), kb.rdfFactory.literal(timeNow + ' Request for ' + docuri), this.appNode); // We store the docuri as a string, not as a node, + // see https://github.com/linkeddata/rdflib.js/pull/427#pullrequestreview-447910061 + + kb.add(req, this.ns.link('requestedURI'), kb.rdfFactory.literal(docuri), this.appNode); + kb.add(req, this.ns.link('status'), kb.collection(), this.appNode); + } + }, { + key: "saveResponseMetadata", + value: function saveResponseMetadata(response, options) { + var _this9 = this; + + var kb = this.store; + var responseNode = kb.bnode(); + kb.add(options.req, this.ns.link('response'), responseNode, responseNode); + kb.add(responseNode, this.ns.http('status'), kb.rdfFactory.literal(response.status), responseNode); + kb.add(responseNode, this.ns.http('statusText'), kb.rdfFactory.literal(response.statusText), responseNode); + + if (!options.resource.value.startsWith('http')) { + return responseNode; + } // Save the response headers + + + response.headers.forEach(function (value, header) { + kb.add(responseNode, _this9.ns.httph(header), _this9.store.rdfFactory.literal(value), responseNode); + + if (header === 'content-type') { + kb.add(options.resource, _this9.ns.rdf('type'), kb.rdfFactory.namedNode(_utils_js__WEBPACK_IMPORTED_MODULE_18__["mediaTypeClass"](value).value), responseNode); + } + }); + return responseNode; + } + }, { + key: "objectRefresh", + value: function objectRefresh(term) { + var uris = this.store.uris(term); // Get all URIs + + if (typeof uris !== 'undefined') { + for (var i = 0; i < uris.length; i++) { + this.refresh(this.store.rdfFactory.namedNode(_uri__WEBPACK_IMPORTED_MODULE_16__["docpart"](uris[i]))); // what about rterm? + } + } + } + /* refresh Reload data from a given document + ** + ** @param term - An RDF Named Node for the eodcument in question + ** @param userCallback - A function userCallback(ok, message, response) + */ + + }, { + key: "refresh", + value: function refresh(term, userCallback) { + // sources_refresh + this.fireCallbacks('refresh', arguments); + this.nowOrWhenFetched(term, { + force: true, + clearPreviousData: true + }, userCallback); + } + /* refreshIfExpired Conditional refresh if Expired + ** + ** @param term - An RDF Named Node for the eodcument in question + ** @param userCallback - A function userCallback(ok, message, response) + */ + + }, { + key: "refreshIfExpired", + value: function refreshIfExpired(term, userCallback) { + var exp = this.getHeader(term, 'Expires'); + + if (!exp || new Date(exp[0]).getTime() <= new Date().getTime()) { + this.refresh(term, userCallback); + } else { + userCallback(true, 'Not expired', {}); + } + } + }, { + key: "retract", + value: function retract(term) { + // sources_retract + this.store.removeMany(undefined, undefined, undefined, term); + + if (term.value) { + delete this.requested[_uri__WEBPACK_IMPORTED_MODULE_16__["docpart"](term.value)]; + } + + this.fireCallbacks('retract', arguments); + } + }, { + key: "getState", + value: function getState(docuri) { + if (typeof this.requested[docuri] === 'undefined') { + return 'unrequested'; + } else if (this.requested[docuri] === true) { + return 'requested'; + } else if (this.requested[docuri] === 'done') { + return 'fetched'; + } else if (this.requested[docuri] === 'redirected') { + return this.getState(this.redirectedTo[docuri]); + } else { + // An non-200 HTTP error status + return 'failed'; + } + } + }, { + key: "isPending", + value: function isPending(docuri) { + // sources_pending + // doing anyStatementMatching is wasting time + // if it's not pending: false -> flailed + // 'done' -> done 'redirected' -> redirected + return this.requested[docuri] === true; + } + }, { + key: "unload", + value: function unload(term) { + this.store.removeDocument(term); + delete this.requested[term.value]; // So it can be load2ed again + } + }, { + key: "addHandler", + value: function addHandler(handler) { + this.handlers.push(handler); + handler.register(this); + } + }, { + key: "retryNoCredentials", + value: function retryNoCredentials(docuri, options) { + console.log('Fetcher: CORS: RETRYING with NO CREDENTIALS for ' + options.resource); + options.retriedWithNoCredentials = true; // protect against being called twice + + delete this.requested[docuri]; // forget the original request happened + + delete this.fetchQueue[docuri]; // Note: XHR property was withCredentials, but fetch property is just credentials + + var newOptions = Object.assign({}, options, { + credentials: 'omit' + }); + this.addStatus(options.req, 'Abort: Will retry with credentials SUPPRESSED to see if that helps'); + return this.load(docuri, newOptions); + } + /** + * Tests whether a request is being made to a cross-site URI (for purposes + * of retrying with a proxy) + */ + + }, { + key: "isCrossSite", + value: function isCrossSite(uri) { + // Mashup situation, not node etc + if (typeof document === 'undefined' || !document.location) { + return false; + } + + var hostpart = _uri__WEBPACK_IMPORTED_MODULE_16__["hostpart"]; + var here = '' + document.location; + return (hostpart(here) && hostpart(uri) && hostpart(here)) !== hostpart(uri); + } + /** + * Called when there's a network error in fetch(), or a response + * with status of 0. + */ + + }, { + key: "handleError", + value: function handleError(response, docuri, options) { + if (this.isCrossSite(docuri)) { + // Make sure we haven't retried already + if (options.credentials && options.credentials === 'include' && !options.retriedWithNoCredentials) { + return this.retryNoCredentials(docuri, options); + } // Now attempt retry via proxy + + + var proxyUri = Fetcher.crossSiteProxy(docuri); + + if (proxyUri && !options.proxyUsed) { + console.log('web: Direct failed so trying proxy ' + proxyUri); + return this.redirectToProxy(proxyUri, options); + } + } + + var message; + + if (response instanceof Error) { + message = 'Fetch error: ' + response.message; + } else { + message = response.statusText; + + if (response.responseText) { + message += " ".concat(response.responseText); + } + } // This is either not a CORS error, or retries have been made + + + return this.failFetch(options, message, response.status || 998, response); + } // deduce some things from the HTTP transaction + + }, { + key: "addType", + value: function addType(rdfType, req, kb, locURI) { + // add type to all redirected resources too + var prev = req; + + if (locURI) { + var reqURI = kb.any(prev, this.ns.link('requestedURI')); + + if (reqURI && reqURI.value !== locURI) { + kb.add(kb.rdfFactory.namedNode(locURI), this.ns.rdf('type'), rdfType, this.appNode); + } + } + + for (;;) { + var doc = kb.any(prev, this.ns.link('requestedURI')); + + if (doc && doc.value) { + kb.add(kb.rdfFactory.namedNode(doc.value), this.ns.rdf('type'), rdfType, this.appNode); + } // convert Literal + + + prev = kb.any(undefined, kb.rdfFactory.namedNode('http://www.w3.org/2007/ont/link#redirectedRequest'), prev); + + if (!prev) { + break; + } + + var response = kb.any(prev, kb.rdfFactory.namedNode('http://www.w3.org/2007/ont/link#response')); + + if (!response) { + break; + } + + var redirection = kb.any(response, kb.rdfFactory.namedNode('http://www.w3.org/2007/ont/http#status')); + + if (!redirection) { + break; + } // @ts-ignore always true? + + + if (redirection !== '301' && redirection !== '302') { + break; + } + } + } + /** + * Handle fetch() response + */ + + }, { + key: "handleResponse", + value: function handleResponse(response, docuri, options) { + var _this10 = this; + + var kb = this.store; + var headers = response.headers; + var reqNode = options.req; + var responseNode = this.saveResponseMetadata(response, options); + var contentType = this.normalizedContentType(options, headers) || ''; + var contentLocation = headers.get('content-location'); // this.fireCallbacks('recv', xhr.args) + // this.fireCallbacks('headers', [{uri: docuri, headers: xhr.headers}]) + // Check for masked errors (CORS, etc) + + if (response.status === 0) { + console.log('Masked error - status 0 for ' + docuri); + return this.handleError(response, docuri, options); + } + + if (response.status >= 400) { + if (response.status === 404) { + this.nonexistent[options.original.value] = true; + this.nonexistent[docuri] = true; + } + + return this.saveErrorResponse(response, responseNode).then(function () { + var errorMessage = options.resource + ' ' + response.statusText; + return _this10.failFetch(options, errorMessage, response.status, response); + }); + } + + var diffLocation = null; + var absContentLocation = null; + + if (contentLocation) { + absContentLocation = _uri__WEBPACK_IMPORTED_MODULE_16__["join"](contentLocation, docuri); + + if (absContentLocation !== docuri) { + diffLocation = absContentLocation; + } + } + + if (response.status === 200) { + this.addType(this.ns.link('Document'), reqNode, kb, docuri); + + if (diffLocation) { + this.addType(this.ns.link('Document'), reqNode, kb, diffLocation); + } // Before we parse new data clear old but only on 200 + + + if (options.clearPreviousData) { + kb.removeDocument(options.resource); + } + + var isImage = contentType.includes('image/') || contentType.includes('application/pdf'); + + if (contentType && isImage) { + this.addType(kb.rdfFactory.namedNode('http://purl.org/dc/terms/Image'), reqNode, kb, docuri); + + if (diffLocation) { + this.addType(kb.rdfFactory.namedNode('http://purl.org/dc/terms/Image'), reqNode, kb, diffLocation); + } + } + } // If we have already got the thing at this location, abort + + + if (contentLocation) { + if (!options.force && diffLocation && this.requested[absContentLocation] === 'done') { + // we have already fetched this + // should we smush too? + // log.info("HTTP headers indicate we have already" + " retrieved " + + // xhr.resource + " as " + absContentLocation + ". Aborting.") + return this.doneFetch(options, response); + } + + this.requested[absContentLocation] = true; + } + + this.parseLinkHeader(headers.get('link'), options.original, reqNode); + var handler = this.handlerForContentType(contentType, response); + + if (!handler) { + // Not a problem, we just don't extract data + this.addStatus(reqNode, 'Fetch over. No data handled.'); + return this.doneFetch(options, response); + } + + return response.text() // @ts-ignore Types seem right + .then(function (responseText) { + response.responseText = responseText; + return handler.parse(_this10, responseText, options, response); + }); + } + }, { + key: "saveErrorResponse", + value: function saveErrorResponse(response, responseNode) { + var _this11 = this; + + var kb = this.store; + return response.text().then(function (content) { + if (content.length > 10) { + kb.add(responseNode, _this11.ns.http('content'), kb.rdfFactory.literal(content), responseNode); + } + }); + } + }, { + key: "handlerForContentType", + value: function handlerForContentType(contentType, response) { + if (!contentType) { + return null; + } + + var Handler = this.handlers.find(function (handler) { + return contentType.match(handler.pattern); + }); // @ts-ignore in practice all Handlers have constructors. + + return Handler ? new Handler(response) : null; + } + }, { + key: "guessContentType", + value: function guessContentType(uri) { + return CONTENT_TYPE_BY_EXT[uri.split('.').pop()]; + } + }, { + key: "normalizedContentType", + value: function normalizedContentType(options, headers) { + if (options.forceContentType) { + return options.forceContentType; + } + + var contentType = headers.get('content-type'); + + if (!contentType || contentType.includes('application/octet-stream')) { + var guess = this.guessContentType(options.resource.value); + + if (guess) { + return guess; + } + } + + var protocol = _uri__WEBPACK_IMPORTED_MODULE_16__["protocol"](options.resource.value); + + if (!contentType && ['file', 'chrome'].includes(protocol)) { + return 'text/xml'; + } + + return contentType; + } + /** + * Sends a new request to the specified uri. (Extracted from `onerrorFactory()`) + */ + + }, { + key: "redirectToProxy", + value: function redirectToProxy(newURI, options) { + var _this12 = this; + + this.addStatus(options.req, 'BLOCKED -> Cross-site Proxy to <' + newURI + '>'); + options.proxyUsed = true; + var kb = this.store; + var oldReq = options.req; // request metadata blank node + + if (!options.noMeta) { + kb.add(oldReq, this.ns.link('redirectedTo'), kb.rdfFactory.namedNode(newURI), oldReq); + this.addStatus(oldReq, 'redirected to new request'); // why + } + + this.requested[options.resource.value] = 'redirected'; + this.redirectedTo[options.resource.value] = newURI; + var newOptions = Object.assign({}, options); + newOptions.baseURI = options.resource.value; + return this.fetchUri(newURI, newOptions).then(function (response) { + if (!newOptions.noMeta) { + kb.add(oldReq, _this12.ns.link('redirectedRequest'), newOptions.req, _this12.appNode); + } + + return response; + }); + } + }, { + key: "setRequestTimeout", + value: function setRequestTimeout(uri, options) { + var _this13 = this; + + return new Promise(function (resolve) { + _this13.timeouts[uri] = (_this13.timeouts[uri] || []).concat(setTimeout(function () { + if (_this13.isPending(uri) && !options.retriedWithNoCredentials && !options.proxyUsed) { + resolve(_this13.failFetch(options, "Request to ".concat(uri, " timed out"), 'timeout')); + } + }, _this13.timeout)); + }); + } + }, { + key: "addFetchCallback", + value: function addFetchCallback(uri, callback) { + if (!this.fetchCallbacks[uri]) { + this.fetchCallbacks[uri] = [callback]; + } else { + this.fetchCallbacks[uri].push(callback); + } + } + }, { + key: "acceptString", + value: function acceptString() { + var acceptstring = ''; + + for (var mediaType in this.mediatypes) { + if (acceptstring !== '') { + acceptstring += ', '; + } + + acceptstring += mediaType; + + for (var property in this.mediatypes[mediaType]) { + acceptstring += ';' + property + '=' + this.mediatypes[mediaType][property]; + } + } + + return acceptstring; + } // var updatesVia = new $rdf.UpdatesVia(this) // Subscribe to headers + // @@@@@@@@ This is turned off because it causes a websocket to be set up for ANY fetch + // whether we want to track it ot not. including ontologies loaed though the XSSproxy + + }], [{ + key: "crossSiteProxy", + value: function crossSiteProxy(uri) { + if (Fetcher.crossSiteProxyTemplate) { + return Fetcher.crossSiteProxyTemplate.replace('{uri}', encodeURIComponent(uri)); + } else { + return undefined; + } + } + }, { + key: "offlineOverride", + value: function offlineOverride(uri) { + // Map the URI to a localhost proxy if we are running on localhost + // This is used for working offline, e.g. on planes. + // Is the script itself is running in localhost, then access all + // data in a localhost mirror. + // Do not remove without checking with TimBL + var requestedURI = uri; + var UI; + + if (typeof window !== 'undefined' && window.panes && (UI = window.panes.UI) && UI.preferences && UI.preferences.get('offlineModeUsingLocalhost')) { + if (requestedURI.slice(0, 7) === 'http://' && requestedURI.slice(7, 17) !== 'localhost/') { + requestedURI = 'http://localhost/' + requestedURI.slice(7); + _log__WEBPACK_IMPORTED_MODULE_9__["default"].warn('Localhost kludge for offline use: actually getting <' + requestedURI + '>'); + } else {// log.warn("Localhost kludge NOT USED <" + requestedURI + ">") + } + } else {// log.warn("Localhost kludge OFF offline use: actually getting <" + + // requestedURI + ">") + } + + return requestedURI; + } + }, { + key: "proxyIfNecessary", + value: function proxyIfNecessary(uri) { + var UI; + + if (typeof window !== 'undefined' && window.panes && (UI = window.panes.UI) && UI.isExtension) { + return uri; + } // Extension does not need proxy + + + if (typeof $SolidTestEnvironment !== 'undefined' && $SolidTestEnvironment.localSiteMap) { + // nested dictionaries of URI parts from origin down + var hostpath = uri.split('/').slice(2); // the bit after the // + + var lookup = function lookup(parts, index) { + var z = index[parts.shift()]; + + if (!z) { + return null; + } + + if (typeof z === 'string') { + return z + parts.join('/'); + } + + if (!parts) { + return null; + } + + return lookup(parts, z); + }; + + var y = lookup(hostpath, $SolidTestEnvironment.localSiteMap); + + if (y) { + return y; + } + } // browser does 2014 on as https browser script not trusted + // If the web app origin is https: then the mixed content rules + // prevent it loading insecure http: stuff so we need proxy. + + + if (Fetcher.crossSiteProxyTemplate && typeof document !== 'undefined' && document.location && ('' + document.location).slice(0, 6) === 'https:' && // origin is secure + uri.slice(0, 5) === 'http:') { + // requested data is not + return Fetcher.crossSiteProxyTemplate.replace('{uri}', encodeURIComponent(uri)); + } + + return uri; + } + /** + * Tests whether the uri's protocol is supported by the Fetcher. + * @param uri + */ + + }, { + key: "unsupportedProtocol", + value: function unsupportedProtocol(uri) { + var pcol = _uri__WEBPACK_IMPORTED_MODULE_16__["protocol"](uri); + return pcol === 'tel' || pcol === 'mailto' || pcol === 'urn'; + } + /** Decide on credentials using old XXHR api or new fetch() one + * @param requestedURI + * @param options + */ + + }, { + key: "setCredentials", + value: function setCredentials(requestedURI) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + // 2014 CORS problem: + // XMLHttpRequest cannot load http://www.w3.org/People/Berners-Lee/card. + // A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' + // header when the credentials flag is true. + // @ Many ontology files under http: and need CORS wildcard -> + // can't have credentials + if (options.credentials === undefined) { + // Caller using new fetch convention + if (options.withCredentials !== undefined) { + // XHR style is what Fetcher specified before + options.credentials = options.withCredentials ? 'include' : 'omit'; + } else { + options.credentials = 'include'; // default is to be logged on + } + } + } + }]); + + return Fetcher; +}(); + +_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_7___default()(Fetcher, "HANDLERS", void 0); + +_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_7___default()(Fetcher, "CONTENT_TYPE_BY_EXT", void 0); + +_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_7___default()(Fetcher, "crossSiteProxyTemplate", void 0); + + +Fetcher.HANDLERS = defaultHandlers; +Fetcher.CONTENT_TYPE_BY_EXT = CONTENT_TYPE_BY_EXT; + +/***/ }), + +/***/ "./node_modules/rdflib/esm/formula.js": +/*!********************************************!*\ + !*** ./node_modules/rdflib/esm/formula.js ***! + \********************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return Formula; }); +/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js"); +/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js"); +/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__); +/* harmony import */ var _babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/assertThisInitialized */ "./node_modules/@babel/runtime/helpers/assertThisInitialized.js"); +/* harmony import */ var _babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__); +/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/inherits */ "./node_modules/@babel/runtime/helpers/inherits.js"); +/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3__); +/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "./node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"); +/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__); +/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "./node_modules/@babel/runtime/helpers/getPrototypeOf.js"); +/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__); +/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "./node_modules/@babel/runtime/helpers/defineProperty.js"); +/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__); +/* harmony import */ var _class_order__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./class-order */ "./node_modules/rdflib/esm/class-order.js"); +/* harmony import */ var _collection__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./collection */ "./node_modules/rdflib/esm/collection.js"); +/* harmony import */ var _factories_canonical_data_factory__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./factories/canonical-data-factory */ "./node_modules/rdflib/esm/factories/canonical-data-factory.js"); +/* harmony import */ var _log__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./log */ "./node_modules/rdflib/esm/log.js"); +/* harmony import */ var _namespace__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./namespace */ "./node_modules/rdflib/esm/namespace.js"); +/* harmony import */ var _node_internal__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./node-internal */ "./node_modules/rdflib/esm/node-internal.js"); +/* harmony import */ var _serialize__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./serialize */ "./node_modules/rdflib/esm/serialize.js"); +/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./types */ "./node_modules/rdflib/esm/types.js"); +/* harmony import */ var _utils_terms__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./utils/terms */ "./node_modules/rdflib/esm/utils/terms.js"); +/* harmony import */ var _variable__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./variable */ "./node_modules/rdflib/esm/variable.js"); +/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./utils */ "./node_modules/rdflib/esm/utils.js"); +/* harmony import */ var _named_node__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./named-node */ "./node_modules/rdflib/esm/named-node.js"); + + + + + + + + +function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = o[Symbol.iterator](); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } + +function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } + +function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } + +function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5___default()(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5___default()(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4___default()(this, result); }; } + +function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } + + + + + + + + + + + + + + +/** + * A formula, or store of RDF statements + */ +var Formula = /*#__PURE__*/function (_Node) { + _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3___default()(Formula, _Node); + + var _super = _createSuper(Formula); + + /** + * The accompanying fetcher instance. + * + * Is set by the fetcher when initialized. + */ + + /** + * A namespace for the specified namespace's URI + * @param nsuri The URI for the namespace + */ + + /** The factory used to generate statements and terms */ + + /** + * Initializes this formula + * @constructor + * @param statements - Initial array of statements + * @param constraints - initial array of constraints + * @param initBindings - initial bindings used in Query + * @param optional - optional + * @param opts + * @param opts.rdfFactory - The rdf factory that should be used by the store + */ + function Formula() { + var _this; + + var statements = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; + var constraints = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; + var initBindings = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : []; + var optional = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : []; + var opts = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {}; + + _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, Formula); + + _this = _super.call(this, ''); + _this.statements = statements; + _this.constraints = constraints; + _this.initBindings = initBindings; + _this.optional = optional; + + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6___default()(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2___default()(_this), "termType", _types__WEBPACK_IMPORTED_MODULE_14__["GraphTermType"]); + + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6___default()(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2___default()(_this), "classOrder", _class_order__WEBPACK_IMPORTED_MODULE_7__["default"].Graph); + + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6___default()(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2___default()(_this), "fetcher", void 0); + + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6___default()(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2___default()(_this), "isVar", 0); + + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6___default()(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2___default()(_this), "ns", _namespace__WEBPACK_IMPORTED_MODULE_11__["default"]); + + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6___default()(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2___default()(_this), "rdfFactory", void 0); + + _this.rdfFactory = opts && opts.rdfFactory || _factories_canonical_data_factory__WEBPACK_IMPORTED_MODULE_9__["default"]; // Enable default factory methods on this while preserving factory context. + + var _iterator = _createForOfIteratorHelper(_utils__WEBPACK_IMPORTED_MODULE_17__["appliedFactoryMethods"]), + _step; + + try { + var _loop = function _loop() { + var factoryMethod = _step.value; + + _this[factoryMethod] = function () { + var _this$rdfFactory; + + return (_this$rdfFactory = _this.rdfFactory)[factoryMethod].apply(_this$rdfFactory, arguments); + }; + }; + + for (_iterator.s(); !(_step = _iterator.n()).done;) { + _loop(); + } + } catch (err) { + _iterator.e(err); + } finally { + _iterator.f(); + } + + return _this; + } + /** Add a statement from its parts + * @param subject - the first part of the statement + * @param predicate - the second part of the statement + * @param object - the third part of the statement + * @param graph - the last part of the statement + */ + + + _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default()(Formula, [{ + key: "add", + value: function add(subject, predicate, object, graph) { + var _this2 = this; + + if (arguments.length === 1) { + subject.forEach(function (st) { + return _this2.add(st.subject, st.predicate, st.object, st.graph); + }); + } + + return this.statements.push(this.rdfFactory.quad(subject, predicate, object, graph)); + } + /** Add a statment object + * @param {Statement} statement - An existing constructed statement to add + */ + + }, { + key: "addStatement", + value: function addStatement(statement) { + return this.add(statement); + } + /** + * Shortcut for adding blankNodes + * @param [id] + */ + + }, { + key: "bnode", + value: function bnode(id) { + return this.rdfFactory.blankNode(id); + } + /** + * Adds all the statements to this formula + * @param statements - A collection of statements + */ + + }, { + key: "addAll", + value: function addAll(statements) { + var _this3 = this; + + statements.forEach(function (quad) { + _this3.add(quad.subject, quad.predicate, quad.object, quad.graph); + }); + } + /** Follow link from one node, using one wildcard, looking for one + * + * For example, any(me, knows, null, profile) - a person I know accoring to my profile . + * any(me, knows, null, null) - a person I know accoring to anything in store . + * any(null, knows, me, null) - a person who know me accoring to anything in store . + * + * @param s - A node to search for as subject, or if null, a wildcard + * @param p - A node to search for as predicate, or if null, a wildcard + * @param o - A node to search for as object, or if null, a wildcard + * @param g - A node to search for as graph, or if null, a wildcard + * @returns A node which match the wildcard position, or null + */ + + }, { + key: "any", + value: function any(s, p, o, g) { + var st = this.anyStatementMatching(s, p, o, g); + + if (st == null) { + return null; + } else if (s == null) { + return st.subject; + } else if (p == null) { + return st.predicate; + } else if (o == null) { + return st.object; + } + + return null; + } + /** + * Gets the value of a node that matches the specified pattern + * @param s The subject + * @param p The predicate + * @param o The object + * @param g The graph that contains the statement + */ + + }, { + key: "anyValue", + value: function anyValue(s, p, o, g) { + var y = this.any(s, p, o, g); + return y ? y.value : void 0; + } + /** + * Gets the first JavaScript object equivalent to a node based on the specified pattern + * @param s The subject + * @param p The predicate + * @param o The object + * @param g The graph that contains the statement + */ + + }, { + key: "anyJS", + value: function anyJS(s, p, o, g) { + var y = this.any(s, p, o, g); + return y ? _node_internal__WEBPACK_IMPORTED_MODULE_12__["default"].toJS(y) : void 0; + } + /** + * Gets the first statement that matches the specified pattern + */ + + }, { + key: "anyStatementMatching", + value: function anyStatementMatching(s, p, o, g) { + var x = this.statementsMatching(s, p, o, g, true); + + if (!x || x.length === 0) { + return undefined; + } + + return x[0]; + } + /** + * Returns a unique index-safe identifier for the given term. + * + * Falls back to the rdflib hashString implementation if the given factory doesn't support id. + */ + + }, { + key: "id", + value: function id(term) { + return this.rdfFactory.id(term); + } + /** + * Search the Store + * This is really a teaching method as to do this properly you would use IndexedFormula + * + * @param s - A node to search for as subject, or if null, a wildcard + * @param p - A node to search for as predicate, or if null, a wildcard + * @param o - A node to search for as object, or if null, a wildcard + * @param g - A node to search for as graph, or if null, a wildcard + * @param justOne - flag - stop when found one rather than get all of them? + * @returns {Array} - An array of nodes which match the wildcard position + */ + + }, { + key: "statementsMatching", + value: function statementsMatching(s, p, o, g, justOne) { + var sts = this.statements.filter(function (st) { + return (!s || s.equals(st.subject)) && (!p || p.equals(st.predicate)) && (!o || o.equals(st.object)) && (!g || g.equals(st.subject)); + }); + + if (justOne) { + return sts.length === 0 ? [] : [sts[0]]; + } + + return sts; + } + /** + * Finds the types in the list which have no *stored* subtypes + * These are a set of classes which provide by themselves complete + * information -- the other classes are redundant for those who + * know the class DAG. + * @param types A map of the types + */ + + }, { + key: "bottomTypeURIs", + value: function bottomTypeURIs(types) { + var bots; + var bottom; + var elt; + var i; + var len; + var ref; + var subs; + var v; + bots = []; + + for (var _k in types) { + if (!types.hasOwnProperty(_k)) continue; + v = types[_k]; + subs = this.each(void 0, this.rdfFactory.namedNode('http://www.w3.org/2000/01/rdf-schema#subClassOf'), this.rdfFactory.namedNode(_k)); + bottom = true; + i = 0; + + for (len = subs.length; i < len; i++) { + elt = subs[i]; + ref = elt.uri; + + if (ref in types) { + // the subclass is one we know + bottom = false; + break; + } + } + + if (bottom) { + bots[_k] = v; + } + } + + return bots; + } + /** Creates a new collection */ + + }, { + key: "collection", + value: function collection() { + return new _collection__WEBPACK_IMPORTED_MODULE_8__["default"](); + } + /** Follow links from one node, using one wildcard. + * + * For example, each(me, knows, null, profile) - people I know accoring to my profile . + * each(me, knows, null, null) - people I know accoring to anything in store . + * each(null, knows, me, null) - people who know me accoring to anything in store . + * + * @param s - A node to search for as subject, or if null, a wildcard + * @param p - A node to search for as predicate, or if null, a wildcard + * @param o - A node to search for as object, or if null, a wildcard + * @param g - A node to search for as graph, or if null, a wildcard + * @returns {Array} - An array of nodes which match the wildcard position + */ + + }, { + key: "each", + value: function each(s, p, o, g) { + var results = []; + var sts = this.statementsMatching(s, p, o, g, false); + + if (s == null) { + for (var i = 0, len = sts.length; i < len; i++) { + results.push(sts[i].subject); + } + } else if (p == null) { + for (var l = 0, len1 = sts.length; l < len1; l++) { + results.push(sts[l].predicate); + } + } else if (o == null) { + for (var m = 0, len2 = sts.length; m < len2; m++) { + results.push(sts[m].object); + } + } else if (g == null) { + for (var _q = 0, len3 = sts.length; _q < len3; _q++) { + results.push(new _named_node__WEBPACK_IMPORTED_MODULE_18__["default"](sts[_q].graph.value)); + } + } + + return results; + } + /** + * Test whether this formula is equals to {other} + * @param other - The other formula + */ + + }, { + key: "equals", + value: function equals(other) { + if (!other) { + return false; + } + + return this.hashString() === other.hashString(); + } + /** + * For thisClass or any subclass, anything which has it is its type + * or is the object of something which has the type as its range, or subject + * of something which has the type as its domain + * We don't bother doing subproperty (yet?)as it doesn't seeem to be used + * much. + * Get all the Classes of which we can RDFS-infer the subject is a member + * @return a hash of URIs + */ + + }, { + key: "findMembersNT", + value: function findMembersNT(thisClass) { + var len2; + var len4; + var m; + var members; + var pred; + var ref; + var ref1; + var ref2; + var ref3; + var ref4; + var ref5; + var seeds; + var st; + var u; + seeds = {}; + seeds[thisClass.toNT()] = true; + members = {}; + ref = this.transitiveClosure(seeds, this.rdfFactory.namedNode('http://www.w3.org/2000/01/rdf-schema#subClassOf'), true); + + for (var t in ref) { + if (!ref.hasOwnProperty(t)) continue; + ref1 = this.statementsMatching(void 0, this.rdfFactory.namedNode('http://www.w3.org/1999/02/22-rdf-syntax-ns#type'), this.fromNT(t)); + + for (var i = 0, len = ref1.length; i < len; i++) { + st = ref1[i]; + members[st.subject.toNT()] = st; + } + + ref2 = this.each(void 0, this.rdfFactory.namedNode('http://www.w3.org/2000/01/rdf-schema#domain'), this.fromNT(t)); + + for (var l = 0, len1 = ref2.length; l < len1; l++) { + pred = ref2[l]; + ref3 = this.statementsMatching(void 0, pred); + + for (m = 0, len2 = ref3.length; m < len2; m++) { + st = ref3[m]; + members[st.subject.toNT()] = st; + } + } + + ref4 = this.each(void 0, this.rdfFactory.namedNode('http://www.w3.org/2000/01/rdf-schema#range'), this.fromNT(t)); + + for (var _q2 = 0, len3 = ref4.length; _q2 < len3; _q2++) { + pred = ref4[_q2]; + ref5 = this.statementsMatching(void 0, pred); + + for (u = 0, len4 = ref5.length; u < len4; u++) { + st = ref5[u]; + members[st.object.toNT()] = st; + } + } + } + + return members; + } + /** + * For thisClass or any subclass, anything which has it is its type + * or is the object of something which has the type as its range, or subject + * of something which has the type as its domain + * We don't bother doing subproperty (yet?)as it doesn't seeem to be used + * much. + * Get all the Classes of which we can RDFS-infer the subject is a member + * @param subject - A named node + */ + + }, { + key: "findMemberURIs", + value: function findMemberURIs(subject) { + return this.NTtoURI(this.findMembersNT(subject)); + } + /** + * Get all the Classes of which we can RDFS-infer the subject is a superclass + * Returns a hash table where key is NT of type and value is statement why we + * think so. + * Does NOT return terms, returns URI strings. + * We use NT representations in this version because they handle blank nodes. + */ + + }, { + key: "findSubClassesNT", + value: function findSubClassesNT(subject) { + var types = {}; + types[subject.toNT()] = true; + return this.transitiveClosure(types, this.rdfFactory.namedNode('http://www.w3.org/2000/01/rdf-schema#subClassOf'), true); + } + /** + * Get all the Classes of which we can RDFS-infer the subject is a subclass + * @param {RDFlibNamedNode} subject - The thing whose classes are to be found + * @returns a hash table where key is NT of type and value is statement why we + * think so. + * Does NOT return terms, returns URI strings. + * We use NT representations in this version because they handle blank nodes. + */ + + }, { + key: "findSuperClassesNT", + value: function findSuperClassesNT(subject) { + var types = {}; + types[subject.toNT()] = true; + return this.transitiveClosure(types, this.rdfFactory.namedNode('http://www.w3.org/2000/01/rdf-schema#subClassOf'), false); + } + /** + * Get all the Classes of which we can RDFS-infer the subject is a member + * todo: This will loop is there is a class subclass loop (Sublass loops are + * not illegal) + * @param {RDFlibNamedNode} subject - The thing whose classes are to be found + * @returns a hash table where key is NT of type and value is statement why we think so. + * Does NOT return terms, returns URI strings. + * We use NT representations in this version because they handle blank nodes. + */ + + }, { + key: "findTypesNT", + value: function findTypesNT(subject) { + var domain; + var range; + var rdftype; + var ref; + var ref1; + var ref2; + var ref3; + var st; + var types; + rdftype = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type'; + types = []; + ref = this.statementsMatching(subject, void 0, void 0); + + for (var i = 0, len = ref.length; i < len; i++) { + st = ref[i]; + + if (st.predicate.uri === rdftype) { + types[st.object.toNT()] = st; + } else { + ref1 = this.each(st.predicate, this.rdfFactory.namedNode('http://www.w3.org/2000/01/rdf-schema#domain')); + + for (var l = 0, len1 = ref1.length; l < len1; l++) { + range = ref1[l]; + types[range.toNT()] = st; + } + } + } + + ref2 = this.statementsMatching(void 0, void 0, subject); + + for (var m = 0, len2 = ref2.length; m < len2; m++) { + st = ref2[m]; + ref3 = this.each(st.predicate, this.rdfFactory.namedNode('http://www.w3.org/2000/01/rdf-schema#range')); + + for (var _q3 = 0, len3 = ref3.length; _q3 < len3; _q3++) { + domain = ref3[_q3]; + types[domain.toNT()] = st; + } + } + + return this.transitiveClosure(types, this.rdfFactory.namedNode('http://www.w3.org/2000/01/rdf-schema#subClassOf'), false); + } + /** + * Get all the Classes of which we can RDFS-infer the subject is a member + * todo: This will loop is there is a class subclass loop (Sublass loops are + * not illegal) + * Returns a hash table where key is NT of type and value is statement why we + * think so. + * Does NOT return terms, returns URI strings. + * We use NT representations in this version because they handle blank nodes. + * @param subject - A subject node + */ + + }, { + key: "findTypeURIs", + value: function findTypeURIs(subject) { + return this.NTtoURI(this.findTypesNT(subject)); + } + /** Trace statements which connect directly, or through bnodes + * + * @param subject - The node to start looking for statments + * @param doc - The document to be searched, or null to search all documents + * @returns an array of statements, duplicate statements are suppresssed. + */ + + }, { + key: "connectedStatements", + value: function connectedStatements(subject, doc, excludePredicateURIs) { + excludePredicateURIs = excludePredicateURIs || []; + var todo = [subject]; + var done = {}; + var doneArcs = {}; + var result = []; + var self = this; + + var follow = function follow(x) { + var queue = function queue(x) { + if (x.termType === 'BlankNode' && !done[x.value]) { + done[x.value] = true; + todo.push(x); + } + }; + + var sts = self.statementsMatching(null, null, x, doc).concat(self.statementsMatching(x, null, null, doc)); + sts = sts.filter(function (st) { + if (excludePredicateURIs[st.predicate.value]) return false; + var hash = st.toNT(); + if (doneArcs[hash]) return false; + doneArcs[hash] = true; + return true; + }); + sts.forEach(function (st) { + queue(st.subject); + queue(st.object); + }); + result = result.concat(sts); + }; + + while (todo.length) { + follow(todo.shift()); + } // console.log('' + result.length + ' statements about ' + subject) + + + return result; + } + /** + * Creates a new empty formula + * + * @param _features - Not applicable, but necessary for typing to pass + */ + + }, { + key: "formula", + value: function formula(_features) { + return new Formula(); + } + /** + * Transforms an NTriples string format into a Node. + * The blank node bit should not be used on program-external values; designed + * for internal work such as storing a blank node id in an HTML attribute. + * This will only parse the strings generated by the various toNT() methods. + */ + + }, { + key: "fromNT", + value: function fromNT(str) { + var dt, k, lang; + + switch (str[0]) { + case '<': + return this.sym(str.slice(1, -1)); + + case '"': + lang = void 0; + dt = void 0; + k = str.lastIndexOf('"'); + + if (k < str.length - 1) { + if (str[k + 1] === '@') { + lang = str.slice(k + 2); + } else if (str.slice(k + 1, k + 3) === '^^') { + dt = this.fromNT(str.slice(k + 3)); + } else { + throw new Error("Can't convert string from NT: " + str); + } + } + + str = str.slice(1, k); + str = str.replace(/\\"/g, '"'); + str = str.replace(/\\n/g, '\n'); + str = str.replace(/\\\\/g, '\\'); + return this.rdfFactory.literal(str, lang || dt); + + case '_': + return this.rdfFactory.blankNode(str.slice(2)); + + case '?': + return new _variable__WEBPACK_IMPORTED_MODULE_16__["default"](str.slice(1)); + } + + throw new Error("Can't convert from NT: " + str); + } + /** Returns true if this formula holds the specified statement(s) */ + + }, { + key: "holds", + value: function holds(s, p, o, g) { + var i; + + if (arguments.length === 1) { + if (!s) { + return true; + } + + if (s instanceof Array) { + for (i = 0; i < s.length; i++) { + if (!this.holds(s[i])) { + return false; + } + } + + return true; + } else if (Object(_utils_terms__WEBPACK_IMPORTED_MODULE_15__["isStatement"])(s)) { + return this.holds(s.subject, s.predicate, s.object, s.graph); + } else if (s.statements) { + return this.holds(s.statements); + } + } + + var st = this.anyStatementMatching(s, p, o, g); + return st != null; + } + /** + * Returns true if this formula holds the specified {statement} + */ + + }, { + key: "holdsStatement", + value: function holdsStatement(statement) { + return this.holds(statement.subject, statement.predicate, statement.object, statement.graph); + } + /** + * Used by the n3parser to generate list elements + * @param values - The values of the collection + * @param context - The store + * @return {BlankNode|Collection} - The term for the statement + */ + + }, { + key: "list", + value: function list(values, context) { + if (context.rdfFactory.supports["COLLECTIONS"]) { + var collection = context.rdfFactory.collection(); + values.forEach(function (val) { + collection.append(val); + }); + return collection; + } else { + var node = context.rdfFactory.blankNode(); + + var _statements = Object(_utils__WEBPACK_IMPORTED_MODULE_17__["arrayToStatements"])(context.rdfFactory, node, values); + + context.addAll(_statements); + return node; + } + } + /** + * Transform a collection of NTriple URIs into their URI strings + * @param t - Some iterable collection of NTriple URI strings + * @return A collection of the URIs as strings + * todo: explain why it is important to go through NT + */ + + }, { + key: "NTtoURI", + value: function NTtoURI(t) { + var k, v; + var uris = {}; + + for (k in t) { + if (!t.hasOwnProperty(k)) continue; + v = t[k]; + + if (k[0] === '<') { + uris[k.slice(1, -1)] = v; + } + } + + return uris; + } + /** + * Serializes this formula + * @param base - The base string + * @param contentType - The content type of the syntax to use + * @param provenance - The provenance URI + */ + + }, { + key: "serialize", + value: function serialize(base, contentType, provenance) { + var documentString; + var sts; + var sz; + sz = Object(_serialize__WEBPACK_IMPORTED_MODULE_13__["default"])(this); + sz.suggestNamespaces(this.ns); + sz.setBase(base); + + if (provenance) { + sts = this.statementsMatching(void 0, void 0, void 0, provenance); + } else { + sts = this.statements; + } + + switch (contentType != null ? contentType : 'text/n3') { + case 'application/rdf+xml': + documentString = sz.statementsToXML(sts); + break; + + case 'text/n3': + case 'text/turtle': + documentString = sz.statementsToN3(sts); + break; + + default: + throw new Error('serialize: Content-type ' + contentType + ' not supported.'); + } + + return documentString; + } + /** + * Creates a new formula with the substituting bindings applied + * @param bindings - The bindings to substitute + */ + + }, { + key: "substitute", + value: function substitute(bindings) { + var statementsCopy = this.statements.map(function (ea) { + return ea.substitute(bindings); + }); + console.log('Formula subs statmnts:' + statementsCopy); + var y = new Formula(); + y.addAll(statementsCopy); + console.log('indexed-form subs formula:' + y); + return y; + } + }, { + key: "sym", + value: function sym(uri, name) { + if (name) { + throw new Error('This feature (kb.sym with 2 args) is removed. Do not assume prefix mappings.'); + } + + return this.rdfFactory.namedNode(uri); + } + /** + * Gets the node matching the specified pattern. Throws when no match could be made. + * @param s - The subject + * @param p - The predicate + * @param o - The object + * @param g - The graph that contains the statement + */ + + }, { + key: "the", + value: function the(s, p, o, g) { + var x = this.any(s, p, o, g); + + if (x == null) { + _log__WEBPACK_IMPORTED_MODULE_10__["default"].error('No value found for the() {' + s + ' ' + p + ' ' + o + '}.'); + } + + return x; + } + /** + * RDFS Inference + * These are hand-written implementations of a backward-chaining reasoner + * over the RDFS axioms. + * @param seeds - A hash of NTs of classes to start with + * @param predicate - The property to trace though + * @param inverse - Trace inverse direction + */ + + }, { + key: "transitiveClosure", + value: function transitiveClosure(seeds, predicate, inverse) { + var elt, i, len, s, sups, t; + var agenda = {}; + Object.assign(agenda, seeds); // make a copy + + var done = {}; // classes we have looked up + + while (true) { + t = function () { + for (var p in agenda) { + if (!agenda.hasOwnProperty(p)) continue; + return p; + } + }(); + + if (t == null) { + return done; + } + + sups = inverse ? this.each(void 0, predicate, this.fromNT(t)) : this.each(this.fromNT(t), predicate); + + for (i = 0, len = sups.length; i < len; i++) { + elt = sups[i]; + s = elt.toNT(); + + if (s in done) { + continue; + } + + if (s in agenda) { + continue; + } + + agenda[s] = agenda[t]; + } + + done[t] = agenda[t]; + delete agenda[t]; + } + } + /** + * Finds the types in the list which have no *stored* supertypes + * We exclude the universal class, owl:Things and rdf:Resource, as it is + * information-free. + * @param types - The types + */ + + }, { + key: "topTypeURIs", + value: function topTypeURIs(types) { + var i; + var j; + var k; + var len; + var n; + var ref; + var tops; + var v; + tops = []; + + for (k in types) { + if (!types.hasOwnProperty(k)) continue; + v = types[k]; + n = 0; + ref = this.each(this.rdfFactory.namedNode(k), this.rdfFactory.namedNode('http://www.w3.org/2000/01/rdf-schema#subClassOf')); + + for (i = 0, len = ref.length; i < len; i++) { + j = ref[i]; + + if (j.uri !== 'http://www.w3.org/2000/01/rdf-schema#Resource') { + n++; + break; + } + } + + if (!n) { + tops[k] = v; + } + } + + if (tops['http://www.w3.org/2000/01/rdf-schema#Resource']) { + delete tops['http://www.w3.org/2000/01/rdf-schema#Resource']; + } + + if (tops['http://www.w3.org/2002/07/owl#Thing']) { + delete tops['http://www.w3.org/2002/07/owl#Thing']; + } + + return tops; + } + /** + * Serializes this formula to a string + */ + + }, { + key: "toString", + value: function toString() { + return '{' + this.statements.join('\n') + '}'; + } + /** + * Gets a new variable + * @param name - The variable's name + */ + + }, { + key: "variable", + value: function variable(name) { + return new _variable__WEBPACK_IMPORTED_MODULE_16__["default"](name); + } + /** + * Gets the number of statements in this formula that matches the specified pattern + * @param s - The subject + * @param p - The predicate + * @param o - The object + * @param g - The graph that contains the statement + */ + + }, { + key: "whether", + value: function whether(s, p, o, g) { + return this.statementsMatching(s, p, o, g, false).length; + } + }]); + + return Formula; +}(_node_internal__WEBPACK_IMPORTED_MODULE_12__["default"]); + + + +/***/ }), + +/***/ "./node_modules/rdflib/esm/index.js": +/*!******************************************!*\ + !*** ./node_modules/rdflib/esm/index.js ***! + \******************************************/ +/*! exports provided: isStatement, isStore, isCollection, isRDFlibObject, isVariable, isTerm, isLiteral, isQuad, isNamedNode, isBlankNode, isSubject, isPredicate, isRDFObject, isGraph, BlankNode, Collection, convert, DataFactory, Empty, Fetcher, Formula, Store, jsonParser, Literal, log, N3Parser, NamedNode, Namespace, Node, parse, Query, queryToSPARQL, RDFaProcessor, RDFParser, serialize, Serializer, SPARQLToQuery, sparqlUpdateParser, Statement, term, UpdateManager, UpdatesSocket, UpdatesVia, uri, Util, Variable, IndexedFormula, NextId, fromNT, fetcher, graph, lit, st, sym, blankNode, defaultGraph, literal, namedNode, quad, triple, variable, termValue */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "term", function() { return term; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NextId", function() { return NextId; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "fromNT", function() { return fromNT; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "fetcher", function() { return fetcher; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "graph", function() { return graph; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "lit", function() { return lit; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "st", function() { return st; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sym", function() { return namedNode; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "blankNode", function() { return blankNode; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "defaultGraph", function() { return defaultGraph; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "literal", function() { return literal; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "namedNode", function() { return namedNode; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "quad", function() { return quad; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "triple", function() { return triple; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "variable", function() { return variable; }); +/* harmony import */ var _blank_node__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./blank-node */ "./node_modules/rdflib/esm/blank-node.js"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BlankNode", function() { return _blank_node__WEBPACK_IMPORTED_MODULE_0__["default"]; }); + +/* harmony import */ var _collection__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./collection */ "./node_modules/rdflib/esm/collection.js"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Collection", function() { return _collection__WEBPACK_IMPORTED_MODULE_1__["default"]; }); + +/* harmony import */ var _convert__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./convert */ "./node_modules/rdflib/esm/convert.js"); +/* harmony reexport (module object) */ __webpack_require__.d(__webpack_exports__, "convert", function() { return _convert__WEBPACK_IMPORTED_MODULE_2__; }); +/* harmony import */ var _empty__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./empty */ "./node_modules/rdflib/esm/empty.js"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Empty", function() { return _empty__WEBPACK_IMPORTED_MODULE_3__["default"]; }); + +/* harmony import */ var _fetcher__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./fetcher */ "./node_modules/rdflib/esm/fetcher.js"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Fetcher", function() { return _fetcher__WEBPACK_IMPORTED_MODULE_4__["default"]; }); + +/* harmony import */ var _formula__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./formula */ "./node_modules/rdflib/esm/formula.js"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Formula", function() { return _formula__WEBPACK_IMPORTED_MODULE_5__["default"]; }); + +/* harmony import */ var _store__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./store */ "./node_modules/rdflib/esm/store.js"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Store", function() { return _store__WEBPACK_IMPORTED_MODULE_6__["default"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "IndexedFormula", function() { return _store__WEBPACK_IMPORTED_MODULE_6__["default"]; }); + +/* harmony import */ var _jsonparser__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./jsonparser */ "./node_modules/rdflib/esm/jsonparser.js"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "jsonParser", function() { return _jsonparser__WEBPACK_IMPORTED_MODULE_7__["default"]; }); + +/* harmony import */ var _literal__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./literal */ "./node_modules/rdflib/esm/literal.js"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Literal", function() { return _literal__WEBPACK_IMPORTED_MODULE_8__["default"]; }); + +/* harmony import */ var _log__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./log */ "./node_modules/rdflib/esm/log.js"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "log", function() { return _log__WEBPACK_IMPORTED_MODULE_9__["default"]; }); + +/* harmony import */ var _n3parser__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./n3parser */ "./node_modules/rdflib/esm/n3parser.js"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "N3Parser", function() { return _n3parser__WEBPACK_IMPORTED_MODULE_10__["default"]; }); + +/* harmony import */ var _named_node__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./named-node */ "./node_modules/rdflib/esm/named-node.js"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NamedNode", function() { return _named_node__WEBPACK_IMPORTED_MODULE_11__["default"]; }); + +/* harmony import */ var _namespace__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./namespace */ "./node_modules/rdflib/esm/namespace.js"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Namespace", function() { return _namespace__WEBPACK_IMPORTED_MODULE_12__["default"]; }); + +/* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./node */ "./node_modules/rdflib/esm/node.js"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Node", function() { return _node__WEBPACK_IMPORTED_MODULE_13__["default"]; }); + +/* harmony import */ var _parse__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./parse */ "./node_modules/rdflib/esm/parse.js"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "parse", function() { return _parse__WEBPACK_IMPORTED_MODULE_14__["default"]; }); + +/* harmony import */ var _query__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./query */ "./node_modules/rdflib/esm/query.js"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Query", function() { return _query__WEBPACK_IMPORTED_MODULE_15__["Query"]; }); + +/* harmony import */ var _query_to_sparql__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./query-to-sparql */ "./node_modules/rdflib/esm/query-to-sparql.js"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "queryToSPARQL", function() { return _query_to_sparql__WEBPACK_IMPORTED_MODULE_16__["default"]; }); + +/* harmony import */ var _rdfaparser__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./rdfaparser */ "./node_modules/rdflib/esm/rdfaparser.js"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RDFaProcessor", function() { return _rdfaparser__WEBPACK_IMPORTED_MODULE_17__["default"]; }); + +/* harmony import */ var _rdfxmlparser__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./rdfxmlparser */ "./node_modules/rdflib/esm/rdfxmlparser.js"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RDFParser", function() { return _rdfxmlparser__WEBPACK_IMPORTED_MODULE_18__["default"]; }); + +/* harmony import */ var _serialize__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ./serialize */ "./node_modules/rdflib/esm/serialize.js"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "serialize", function() { return _serialize__WEBPACK_IMPORTED_MODULE_19__["default"]; }); + +/* harmony import */ var _serializer__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ./serializer */ "./node_modules/rdflib/esm/serializer.js"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Serializer", function() { return _serializer__WEBPACK_IMPORTED_MODULE_20__["default"]; }); + +/* harmony import */ var _sparql_to_query__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ./sparql-to-query */ "./node_modules/rdflib/esm/sparql-to-query.js"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SPARQLToQuery", function() { return _sparql_to_query__WEBPACK_IMPORTED_MODULE_21__["default"]; }); + +/* harmony import */ var _patch_parser__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ./patch-parser */ "./node_modules/rdflib/esm/patch-parser.js"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "sparqlUpdateParser", function() { return _patch_parser__WEBPACK_IMPORTED_MODULE_22__["default"]; }); + +/* harmony import */ var _statement__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! ./statement */ "./node_modules/rdflib/esm/statement.js"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Statement", function() { return _statement__WEBPACK_IMPORTED_MODULE_23__["default"]; }); + +/* harmony import */ var _update_manager__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(/*! ./update-manager */ "./node_modules/rdflib/esm/update-manager.js"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "UpdateManager", function() { return _update_manager__WEBPACK_IMPORTED_MODULE_24__["default"]; }); + +/* harmony import */ var _updates_via__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(/*! ./updates-via */ "./node_modules/rdflib/esm/updates-via.js"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "UpdatesSocket", function() { return _updates_via__WEBPACK_IMPORTED_MODULE_25__["UpdatesSocket"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "UpdatesVia", function() { return _updates_via__WEBPACK_IMPORTED_MODULE_25__["UpdatesVia"]; }); + +/* harmony import */ var _uri__WEBPACK_IMPORTED_MODULE_26__ = __webpack_require__(/*! ./uri */ "./node_modules/rdflib/esm/uri.js"); +/* harmony reexport (module object) */ __webpack_require__.d(__webpack_exports__, "uri", function() { return _uri__WEBPACK_IMPORTED_MODULE_26__; }); +/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_27__ = __webpack_require__(/*! ./utils-js */ "./node_modules/rdflib/esm/utils-js.js"); +/* harmony reexport (module object) */ __webpack_require__.d(__webpack_exports__, "Util", function() { return _utils_js__WEBPACK_IMPORTED_MODULE_27__; }); +/* harmony import */ var _variable__WEBPACK_IMPORTED_MODULE_28__ = __webpack_require__(/*! ./variable */ "./node_modules/rdflib/esm/variable.js"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Variable", function() { return _variable__WEBPACK_IMPORTED_MODULE_28__["default"]; }); + +/* harmony import */ var _factories_rdflib_data_factory__WEBPACK_IMPORTED_MODULE_29__ = __webpack_require__(/*! ./factories/rdflib-data-factory */ "./node_modules/rdflib/esm/factories/rdflib-data-factory.js"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DataFactory", function() { return _factories_rdflib_data_factory__WEBPACK_IMPORTED_MODULE_29__["default"]; }); + +/* harmony import */ var _utils_terms__WEBPACK_IMPORTED_MODULE_30__ = __webpack_require__(/*! ./utils/terms */ "./node_modules/rdflib/esm/utils/terms.js"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "isStatement", function() { return _utils_terms__WEBPACK_IMPORTED_MODULE_30__["isStatement"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "isStore", function() { return _utils_terms__WEBPACK_IMPORTED_MODULE_30__["isStore"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "isCollection", function() { return _utils_terms__WEBPACK_IMPORTED_MODULE_30__["isCollection"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "isRDFlibObject", function() { return _utils_terms__WEBPACK_IMPORTED_MODULE_30__["isRDFlibObject"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "isVariable", function() { return _utils_terms__WEBPACK_IMPORTED_MODULE_30__["isVariable"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "isTerm", function() { return _utils_terms__WEBPACK_IMPORTED_MODULE_30__["isTerm"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "isLiteral", function() { return _utils_terms__WEBPACK_IMPORTED_MODULE_30__["isLiteral"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "isQuad", function() { return _utils_terms__WEBPACK_IMPORTED_MODULE_30__["isQuad"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "isNamedNode", function() { return _utils_terms__WEBPACK_IMPORTED_MODULE_30__["isNamedNode"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "isBlankNode", function() { return _utils_terms__WEBPACK_IMPORTED_MODULE_30__["isBlankNode"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "isSubject", function() { return _utils_terms__WEBPACK_IMPORTED_MODULE_30__["isSubject"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "isPredicate", function() { return _utils_terms__WEBPACK_IMPORTED_MODULE_30__["isPredicate"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "isRDFObject", function() { return _utils_terms__WEBPACK_IMPORTED_MODULE_30__["isRDFObject"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "isGraph", function() { return _utils_terms__WEBPACK_IMPORTED_MODULE_30__["isGraph"]; }); + +/* harmony import */ var _utils_termValue__WEBPACK_IMPORTED_MODULE_31__ = __webpack_require__(/*! ./utils/termValue */ "./node_modules/rdflib/esm/utils/termValue.js"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "termValue", function() { return _utils_termValue__WEBPACK_IMPORTED_MODULE_31__["termValue"]; }); + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + // Prepare bound versions of data factory methods for export + +var boundDataFactory = {}; + +for (var name in _factories_rdflib_data_factory__WEBPACK_IMPORTED_MODULE_29__["default"]) { + if (typeof _factories_rdflib_data_factory__WEBPACK_IMPORTED_MODULE_29__["default"][name] === 'function') boundDataFactory[name] = _factories_rdflib_data_factory__WEBPACK_IMPORTED_MODULE_29__["default"][name].bind(_factories_rdflib_data_factory__WEBPACK_IMPORTED_MODULE_29__["default"]); +} + +var fetcher = boundDataFactory.fetcher, + graph = boundDataFactory.graph, + lit = boundDataFactory.lit, + st = boundDataFactory.st, + namedNode = boundDataFactory.namedNode, + variable = boundDataFactory.variable, + blankNode = boundDataFactory.blankNode, + defaultGraph = boundDataFactory.defaultGraph, + literal = boundDataFactory.literal, + quad = boundDataFactory.quad, + triple = boundDataFactory.triple; +var formula = new _formula__WEBPACK_IMPORTED_MODULE_5__["default"](); + +var fromNT = function fromNT(str) { + return formula.fromNT(str); +}; + +var term = _node__WEBPACK_IMPORTED_MODULE_13__["default"].fromValue; // TODO: this export is broken; +// it exports the _current_ value of nextId, which is always 0 + +var NextId = _blank_node__WEBPACK_IMPORTED_MODULE_0__["default"].nextId; + + + + +/***/ }), + +/***/ "./node_modules/rdflib/esm/jsonldparser.js": +/*!*************************************************!*\ + !*** ./node_modules/rdflib/esm/jsonldparser.js ***! + \*************************************************/ +/*! exports provided: jsonldObjectToTerm, default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "jsonldObjectToTerm", function() { return jsonldObjectToTerm; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return jsonldParser; }); +/* harmony import */ var jsonld__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! jsonld */ "./node_modules/jsonld/lib/jsonld.js"); +/* harmony import */ var jsonld__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(jsonld__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./utils */ "./node_modules/rdflib/esm/utils.js"); + + +/** + * Parses json-ld formatted JS objects to a rdf Term. + * @param kb - The DataFactory to use. + * @param obj - The json-ld object to process. + * @return {Literal|NamedNode|BlankNode|Collection} + */ + +function jsonldObjectToTerm(kb, obj) { + if (typeof obj === 'string') { + return kb.rdfFactory.literal(obj); + } + + if (Object.prototype.hasOwnProperty.call(obj, '@list')) { + if (kb.rdfFactory.supports["COLLECTIONS"] === true) { + return listToCollection(kb, obj['@list']); + } + + return listToStatements(kb, obj); + } + + if (Object.prototype.hasOwnProperty.call(obj, '@id')) { + return kb.rdfFactory.namedNode(obj['@id']); + } + + if (Object.prototype.hasOwnProperty.call(obj, '@language')) { + return kb.rdfFactory.literal(obj['@value'], obj['@language']); + } + + if (Object.prototype.hasOwnProperty.call(obj, '@type')) { + return kb.rdfFactory.literal(obj['@value'], kb.rdfFactory.namedNode(obj['@type'])); + } + + if (Object.prototype.hasOwnProperty.call(obj, '@value')) { + return kb.rdfFactory.literal(obj['@value']); + } + + return kb.rdfFactory.literal(obj); +} +/** + * Adds the statements in a json-ld list object to {kb}. + */ + +function listToStatements(kb, obj) { + var listId = obj['@id'] ? kb.rdfFactory.namedNode(obj['@id']) : kb.rdfFactory.blankNode(); + var items = obj['@list'].map(function (listItem) { + return jsonldObjectToTerm(kb, listItem); + }); + var statements = Object(_utils__WEBPACK_IMPORTED_MODULE_1__["arrayToStatements"])(kb.rdfFactory, listId, items); + kb.addAll(statements); + return listId; +} + +function listToCollection(kb, obj) { + if (!Array.isArray(obj)) { + throw new TypeError("Object must be an array"); + } + + return kb.rdfFactory.collection(obj.map(function (o) { + return jsonldObjectToTerm(kb, o); + })); +} +/** + * Takes a json-ld formatted string {str} and adds its statements to {kb}. + * + * Ensure that {kb.rdfFactory} is a DataFactory. + */ + + +function jsonldParser(str, kb, base, callback) { + var baseString = base && Object.prototype.hasOwnProperty.call(base, 'termType') ? base.value : base; + return jsonld__WEBPACK_IMPORTED_MODULE_0___default.a.flatten(JSON.parse(str), null, { + base: baseString + }).then(function (flattened) { + return flattened.reduce(function (store, flatResource) { + var id = flatResource['@id'] ? kb.rdfFactory.namedNode(flatResource['@id']) : kb.rdfFactory.blankNode(); + + for (var _i = 0, _Object$keys = Object.keys(flatResource); _i < _Object$keys.length; _i++) { + var property = _Object$keys[_i]; + + if (property === '@id') { + continue; + } + + var value = flatResource[property]; + + if (Array.isArray(value)) { + for (var i = 0; i < value.length; i++) { + kb.addStatement(kb.rdfFactory.quad(id, kb.rdfFactory.namedNode(property), jsonldObjectToTerm(kb, value[i]))); + } + } else { + kb.addStatement(kb.rdfFactory.quad(id, kb.rdfFactory.namedNode(property), jsonldObjectToTerm(kb, value))); + } + } + + return kb; + }, kb); + }).then(callback).catch(callback); +} + +/***/ }), + +/***/ "./node_modules/rdflib/esm/jsonparser.js": +/*!***********************************************!*\ + !*** ./node_modules/rdflib/esm/jsonparser.js ***! + \***********************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony default export */ __webpack_exports__["default"] = ((function () { + return { + parseJSON: function parseJSON(data, source, store) { + var subject, predicate, object; + var bnodes = {}; + var why = store.sym(source); + + for (var x in data) { + if (x.indexOf('_:') === 0) { + if (bnodes[x]) { + subject = bnodes[x]; + } else { + subject = store.bnode(x); + bnodes[x] = subject; + } + } else { + subject = store.sym(x); + } + + var preds = data[x]; + + for (var y in preds) { + var objects = preds[y]; + predicate = store.sym(y); + + for (var z in objects) { + var obj = objects[z]; + + if (obj.type === 'uri') { + object = store.sym(obj.value); + store.add(subject, predicate, object, why); + } else if (obj.type === 'BlankNode') { + if (bnodes[obj.value]) { + object = bnodes[obj.value]; + } else { + object = store.bnode(obj.value); + bnodes[obj.value] = object; + } + + store.add(subject, predicate, object, why); + } else if (obj.type === 'Literal') { + // var datatype + if (obj.datatype) { + object = store.literal(obj.value, undefined, store.sym(obj.datatype)); + } else if (obj.lang) { + object = store.literal(obj.value, obj.lang); + } else { + object = store.literal(obj.value); + } + + store.add(subject, predicate, object, why); + } else { + throw new Error('error: unexpected termtype: ' + z.type); + } + } + } + } + } + }; +})()); + +/***/ }), + +/***/ "./node_modules/rdflib/esm/literal.js": +/*!********************************************!*\ + !*** ./node_modules/rdflib/esm/literal.js ***! + \********************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return Literal; }); +/* harmony import */ var _babel_runtime_helpers_typeof__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "./node_modules/@babel/runtime/helpers/typeof.js"); +/* harmony import */ var _babel_runtime_helpers_typeof__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_typeof__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js"); +/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_1__); +/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js"); +/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_2__); +/* harmony import */ var _babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/assertThisInitialized */ "./node_modules/@babel/runtime/helpers/assertThisInitialized.js"); +/* harmony import */ var _babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_3__); +/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/inherits */ "./node_modules/@babel/runtime/helpers/inherits.js"); +/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4__); +/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "./node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"); +/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_5__); +/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "./node_modules/@babel/runtime/helpers/getPrototypeOf.js"); +/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_6__); +/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "./node_modules/@babel/runtime/helpers/defineProperty.js"); +/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_7__); +/* harmony import */ var _class_order__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./class-order */ "./node_modules/rdflib/esm/class-order.js"); +/* harmony import */ var _named_node__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./named-node */ "./node_modules/rdflib/esm/named-node.js"); +/* harmony import */ var _node_internal__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./node-internal */ "./node_modules/rdflib/esm/node-internal.js"); +/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./types */ "./node_modules/rdflib/esm/types.js"); +/* harmony import */ var _utils_terms__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./utils/terms */ "./node_modules/rdflib/esm/utils/terms.js"); +/* harmony import */ var _xsd_internal__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./xsd-internal */ "./node_modules/rdflib/esm/xsd-internal.js"); + + + + + + + + + +function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_6___default()(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_6___default()(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_5___default()(this, result); }; } + +function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } + + + + + + + + +/** + * An RDF literal, containing some value which isn't expressed as an IRI. + * @link https://rdf.js.org/data-model-spec/#literal-interface + */ +var Literal = /*#__PURE__*/function (_Node) { + _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4___default()(Literal, _Node); + + var _super = _createSuper(Literal); + + /** + * The literal's datatype as a named node + */ + + /** + * The language for the literal + */ + + /** + * Initializes a literal + * @param value - The literal's lexical value + * @param language - The language for the literal. Defaults to ''. + * @param datatype - The literal's datatype as a named node. Defaults to xsd:string. + */ + function Literal(value, language, datatype) { + var _this; + + _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_1___default()(this, Literal); + + _this = _super.call(this, value); + + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_7___default()(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_3___default()(_this), "termType", _types__WEBPACK_IMPORTED_MODULE_11__["LiteralTermType"]); + + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_7___default()(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_3___default()(_this), "classOrder", _class_order__WEBPACK_IMPORTED_MODULE_8__["default"].Literal); + + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_7___default()(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_3___default()(_this), "datatype", _xsd_internal__WEBPACK_IMPORTED_MODULE_13__["default"].string); + + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_7___default()(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_3___default()(_this), "isVar", 0); + + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_7___default()(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_3___default()(_this), "language", ''); + + if (language) { + _this.language = language; + _this.datatype = _xsd_internal__WEBPACK_IMPORTED_MODULE_13__["default"].langString; + } else if (datatype) { + _this.datatype = _named_node__WEBPACK_IMPORTED_MODULE_9__["default"].fromValue(datatype); + } else { + _this.datatype = _xsd_internal__WEBPACK_IMPORTED_MODULE_13__["default"].string; + } + + return _this; + } + /** + * Gets a copy of this literal + */ + + + _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_2___default()(Literal, [{ + key: "copy", + value: function copy() { + return new Literal(this.value, this.lang, this.datatype); + } + /** + * Gets whether two literals are the same + * @param other The other statement + */ + + }, { + key: "equals", + value: function equals(other) { + if (!other) { + return false; + } + + return this.termType === other.termType && this.value === other.value && this.language === other.language && (!this.datatype && !other.datatype || this.datatype && this.datatype.equals(other.datatype)); + } + /** + * The language for the literal + * @deprecated use {language} instead + */ + + }, { + key: "toNT", + value: function toNT() { + return Literal.toNT(this); + } + /** Serializes a literal to an N-Triples string */ + + }, { + key: "toString", + value: function toString() { + return '' + this.value; + } + /** + * Builds a literal node from a boolean value + * @param value - The value + */ + + }, { + key: "lang", + get: function get() { + return this.language; + }, + set: function set(language) { + this.language = language || ''; + } + }], [{ + key: "toNT", + value: function toNT(literal) { + if (typeof literal.value === 'number') { + return '' + literal.value; + } else if (typeof literal.value !== 'string') { + throw new Error('Value of RDF literal is not string or number: ' + literal.value); + } + + var str = literal.value; + str = str.replace(/\\/g, '\\\\'); + str = str.replace(/\"/g, '\\"'); + str = str.replace(/\n/g, '\\n'); + str = '"' + str + '"'; + + if (literal.language) { + str += '@' + literal.language; + } else if (!literal.datatype.equals(_xsd_internal__WEBPACK_IMPORTED_MODULE_13__["default"].string)) { + // Only add datatype if it's not a string + str += '^^' + literal.datatype.toCanonical(); + } + + return str; + } + }, { + key: "fromBoolean", + value: function fromBoolean(value) { + var strValue = value ? '1' : '0'; + return new Literal(strValue, null, _xsd_internal__WEBPACK_IMPORTED_MODULE_13__["default"].boolean); + } + /** + * Builds a literal node from a date value + * @param value The value + */ + + }, { + key: "fromDate", + value: function fromDate(value) { + if (!(value instanceof Date)) { + throw new TypeError('Invalid argument to Literal.fromDate()'); + } + + var d2 = function d2(x) { + return ('' + (100 + x)).slice(1, 3); + }; + + var date = '' + value.getUTCFullYear() + '-' + d2(value.getUTCMonth() + 1) + '-' + d2(value.getUTCDate()) + 'T' + d2(value.getUTCHours()) + ':' + d2(value.getUTCMinutes()) + ':' + d2(value.getUTCSeconds()) + 'Z'; + return new Literal(date, null, _xsd_internal__WEBPACK_IMPORTED_MODULE_13__["default"].dateTime); + } + /** + * Builds a literal node from a number value + * @param value - The value + */ + + }, { + key: "fromNumber", + value: function fromNumber(value) { + if (typeof value !== 'number') { + throw new TypeError('Invalid argument to Literal.fromNumber()'); + } + + var datatype; + var strValue = value.toString(); + + if (strValue.indexOf('e') < 0 && Math.abs(value) <= Number.MAX_SAFE_INTEGER) { + datatype = Number.isInteger(value) ? _xsd_internal__WEBPACK_IMPORTED_MODULE_13__["default"].integer : _xsd_internal__WEBPACK_IMPORTED_MODULE_13__["default"].decimal; + } else { + datatype = _xsd_internal__WEBPACK_IMPORTED_MODULE_13__["default"].double; + } + + return new Literal(strValue, null, datatype); + } + /** + * Builds a literal node from an input value + * @param value - The input value + */ + + }, { + key: "fromValue", + value: function fromValue(value) { + if (Object(_utils_terms__WEBPACK_IMPORTED_MODULE_12__["isLiteral"])(value)) { + return value; + } + + switch (_babel_runtime_helpers_typeof__WEBPACK_IMPORTED_MODULE_0___default()(value)) { + case 'object': + if (value instanceof Date) { + return Literal.fromDate(value); + } + + case 'boolean': + return Literal.fromBoolean(value); + + case 'number': + return Literal.fromNumber(value); + + case 'string': + return new Literal(value); + } + + throw new Error("Can't make literal from " + value + ' of type ' + _babel_runtime_helpers_typeof__WEBPACK_IMPORTED_MODULE_0___default()(value)); + } + }]); + + return Literal; +}(_node_internal__WEBPACK_IMPORTED_MODULE_10__["default"]); + + + +/***/ }), + +/***/ "./node_modules/rdflib/esm/log.js": +/*!****************************************!*\ + !*** ./node_modules/rdflib/esm/log.js ***! + \****************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/** + * A Dummy log + * @module log + */ +var log = { + debug: function debug(x) {}, + warn: function warn(x) {}, + info: function info(x) {}, + error: function error(x) {}, + success: function success(x) {}, + msg: function msg(x) {} +}; +/* harmony default export */ __webpack_exports__["default"] = (log); + +/***/ }), + +/***/ "./node_modules/rdflib/esm/n3parser.js": +/*!*********************************************!*\ + !*** ./node_modules/rdflib/esm/n3parser.js ***! + \*********************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _babel_runtime_helpers_typeof__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "./node_modules/@babel/runtime/helpers/typeof.js"); +/* harmony import */ var _babel_runtime_helpers_typeof__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_typeof__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _uri__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./uri */ "./node_modules/rdflib/esm/uri.js"); +/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./utils */ "./node_modules/rdflib/esm/utils.js"); + + +/** +* +* UTF-8 data encode / decode +* http://www.webtoolkit.info/ +* +**/ + + +/* harmony default export */ __webpack_exports__["default"] = ((function () { + function hexify(str) { + // also used in parser + return encodeURI(str); + } + + var Utf8 = { + // public method for url encoding + encode: function encode(string) { + string = string.replace(/\r\n/g, "\n"); + var utftext = ""; + + for (var n = 0; n < string.length; n++) { + var c = string.charCodeAt(n); + + if (c < 128) { + utftext += String.fromCharCode(c); + } else if (c > 127 && c < 2048) { + utftext += String.fromCharCode(c >> 6 | 192); + utftext += String.fromCharCode(c & 63 | 128); + } else { + utftext += String.fromCharCode(c >> 12 | 224); + utftext += String.fromCharCode(c >> 6 & 63 | 128); + utftext += String.fromCharCode(c & 63 | 128); + } + } + + return utftext; + }, + // public method for url decoding + decode: function decode(utftext) { + var string = ""; + var i = 0; + + while (i < utftext.length) { + var c = utftext.charCodeAt(i); + + if (c < 128) { + string += String.fromCharCode(c); + i++; + } else if (c > 191 && c < 224) { + string += String.fromCharCode((c & 31) << 6 | utftext.charCodeAt(i + 1) & 63); + i += 2; + } else { + string += String.fromCharCode((c & 15) << 12 | (utftext.charCodeAt(i + 1) & 63) << 6 | utftext.charCodeAt(i + 2) & 63); + i += 3; + } + } + + return string; + } + }; // Things we need to define to make converted pythn code work in js + // environment of $rdf + + var RDFSink_forSomeSym = "http://www.w3.org/2000/10/swap/log#forSome"; + var RDFSink_forAllSym = "http://www.w3.org/2000/10/swap/log#forAll"; + var Logic_NS = "http://www.w3.org/2000/10/swap/log#"; // pyjs seems to reference runtime library which I didn't find + + var pyjslib_Tuple = function pyjslib_Tuple(theList) { + return theList; + }; + + var pyjslib_List = function pyjslib_List(theList) { + return theList; + }; + + var pyjslib_Dict = function pyjslib_Dict(listOfPairs) { + if (listOfPairs.length > 0) throw "missing.js: oops nnonempty dict not imp"; + return []; + }; + + var pyjslib_len = function pyjslib_len(s) { + return s.length; + }; + + var pyjslib_slice = function pyjslib_slice(str, i, j) { + if (typeof str.slice == 'undefined') throw '@@ mising.js: No .slice function for ' + str + ' of type ' + _babel_runtime_helpers_typeof__WEBPACK_IMPORTED_MODULE_0___default()(str); + if (typeof j == 'undefined' || j == null) return str.slice(i); + return str.slice(i, j); // @ exactly the same spec? + }; + + var StopIteration = Error('dummy error stop iteration'); + + var pyjslib_Iterator = function pyjslib_Iterator(theList) { + this.last = 0; + this.li = theList; + + this.next = function () { + if (this.last == this.li.length) throw StopIteration; + return this.li[this.last++]; + }; + + return this; + }; + + var ord = function ord(str) { + return str.charCodeAt(0); + }; + + var string_find = function string_find(str, s) { + return str.indexOf(s); + }; + + var assertFudge = function assertFudge(condition, desc) { + if (condition) return; + if (desc) throw "python Assertion failed: " + desc; + throw "(python) Assertion failed."; + }; + + var stringFromCharCode = function stringFromCharCode(uesc) { + return String.fromCharCode(uesc); + }; + + String.prototype.encode = function (encoding) { + if (encoding != 'utf-8') throw "UTF8_converter: can only do utf-8"; + return Utf8.encode(this); + }; + + String.prototype.decode = function (encoding) { + if (encoding != 'utf-8') throw "UTF8_converter: can only do utf-8"; //return Utf8.decode(this); + + return this; + }; + + var uripath_join = function uripath_join(base, given) { + return _uri__WEBPACK_IMPORTED_MODULE_1__["join"](given, base); // sad but true + }; + + var becauseSubexpression = null; // No reason needed + + var diag_tracking = 0; + var diag_chatty_flag = 0; + + var diag_progress = function diag_progress(str) { + /*$rdf.log.debug(str);*/ + }; // why_BecauseOfData = function(doc, reason) { return doc }; + + + var RDF_type_URI = "http://www.w3.org/1999/02/22-rdf-syntax-ns#type"; + var DAML_sameAs_URI = "http://www.w3.org/2002/07/owl#sameAs"; + /* + function SyntaxError(details) { + return new __SyntaxError(details); + } + */ + + function __SyntaxError(details) { + this.details = details; + } + /* + + $Id: n3parser.js 14561 2008-02-23 06:37:26Z kennyluck $ + + HAND EDITED FOR CONVERSION TO JAVASCRIPT + + This module implements a Nptation3 parser, and the final + part of a notation3 serializer. + + See also: + + Notation 3 + http://www.w3.org/DesignIssues/Notation3 + + Closed World Machine - and RDF Processor + http://www.w3.org/2000/10/swap/cwm + + To DO: See also "@@" in comments + + - Clean up interfaces + ______________________________________________ + + Module originally by Dan Connolly, includeing notation3 + parser and RDF generator. TimBL added RDF stream model + and N3 generation, replaced stream model with use + of common store/formula API. Yosi Scharf developped + the module, including tests and test harness. + + */ + + + var ADDED_HASH = "#"; + var LOG_implies_URI = "http://www.w3.org/2000/10/swap/log#implies"; + var INTEGER_DATATYPE = "http://www.w3.org/2001/XMLSchema#integer"; + var FLOAT_DATATYPE = "http://www.w3.org/2001/XMLSchema#double"; + var DECIMAL_DATATYPE = "http://www.w3.org/2001/XMLSchema#decimal"; + var DATE_DATATYPE = "http://www.w3.org/2001/XMLSchema#date"; + var DATETIME_DATATYPE = "http://www.w3.org/2001/XMLSchema#dateTime"; + var BOOLEAN_DATATYPE = "http://www.w3.org/2001/XMLSchema#boolean"; + var option_noregen = 0; + var _notQNameChars = "\t\r\n !\"#$%&'()*.,+/;<=>?@[\\]^`{|}~"; + + var _notNameChars = _notQNameChars + ":"; + + var _rdfns = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"; + var N3CommentCharacter = "#"; + var eol = new RegExp("^[ \\t]*(#[^\\n]*)?\\r?\\n", 'g'); + var eof = new RegExp("^[ \\t]*(#[^\\n]*)?$", 'g'); + var ws = new RegExp("^[ \\t]*", 'g'); + var signed_integer = new RegExp("^[-+]?[0-9]+", 'g'); + var number_syntax = new RegExp("^([-+]?[0-9]+)(\\.[0-9]+)?(e[-+]?[0-9]+)?", 'g'); + var datetime_syntax = new RegExp('^[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9](T[0-9][0-9]:[0-9][0-9](:[0-9][0-9](\\.[0-9]*)?)?)?Z?'); + var digitstring = new RegExp("^[0-9]+", 'g'); + var interesting = new RegExp("[\\\\\\r\\n\\\"]", 'g'); + var langcode = new RegExp("^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*", 'g'); + + function SinkParser(store, openFormula, thisDoc, baseURI, genPrefix, metaURI, flags, why) { + return new __SinkParser(store, openFormula, thisDoc, baseURI, genPrefix, metaURI, flags, why); + } + + function __SinkParser(store, openFormula, thisDoc, baseURI, genPrefix, metaURI, flags, why) { + if (typeof openFormula == 'undefined') openFormula = null; + if (typeof thisDoc == 'undefined') thisDoc = ""; + if (typeof baseURI == 'undefined') baseURI = null; + if (typeof genPrefix == 'undefined') genPrefix = ""; + if (typeof metaURI == 'undefined') metaURI = null; + if (typeof flags == 'undefined') flags = ""; + if (typeof why == 'undefined') why = null; + /* + note: namespace names should *not* end in #; + the # will get added during qname processing */ + + this._bindings = new pyjslib_Dict([]); + this._flags = flags; + + if (thisDoc != "") { + assertFudge(thisDoc.indexOf(":") >= 0, "Document URI not absolute: " + thisDoc); + this._bindings[""] = thisDoc + "#"; + } + + this._store = store; + + if (genPrefix) { + store.setGenPrefix(genPrefix); + } + + this._thisDoc = thisDoc; + this.source = store.sym(thisDoc); + this.lines = 0; + this.statementCount = 0; + this.startOfLine = 0; + this.previousLine = 0; + this._genPrefix = genPrefix; + this.keywords = new pyjslib_List(["a", "this", "bind", "has", "is", "of", "true", "false"]); + this.keywordsSet = 0; + this._anonymousNodes = new pyjslib_Dict([]); + this._variables = new pyjslib_Dict([]); + this._parentVariables = new pyjslib_Dict([]); + this._reason = why; + this._reason2 = null; + + if (diag_tracking) { + this._reason2 = why_BecauseOfData(store.sym(thisDoc), this._reason); + } + + if (baseURI) { + this._baseURI = baseURI; + } else { + if (thisDoc) { + this._baseURI = thisDoc; + } else { + this._baseURI = null; + } + } + + assertFudge(!this._baseURI || this._baseURI.indexOf(":") >= 0); + + if (!this._genPrefix) { + if (this._thisDoc) { + this._genPrefix = this._thisDoc + "#_g"; + } else { + this._genPrefix = RDFSink_uniqueURI(); + } + } + + if (openFormula == null) { + if (this._thisDoc) { + this._formula = store.formula(thisDoc + "#_formula"); + } else { + this._formula = store.formula(); + } + } else { + this._formula = openFormula; + } + + this._context = this._formula; + this._parentContext = null; + } + + __SinkParser.prototype.here = function (i) { + return this._genPrefix + "_L" + this.lines + "C" + (i - this.startOfLine + 1); + }; + + __SinkParser.prototype.formula = function () { + return this._formula; + }; + + __SinkParser.prototype.loadStream = function (stream) { + return this.loadBuf(stream.read()); + }; + + __SinkParser.prototype.loadBuf = function (buf) { + /* + Parses a buffer and returns its top level formula*/ + this.startDoc(); + this.feed(buf); + return this.endDoc(); + }; + + __SinkParser.prototype.feed = function (octets) { + /* + Feed an octet stream tothe parser + if BadSyntax is raised, the string + passed in the exception object is the + remainder after any statements have been parsed. + So if there is more data to feed to the + parser, it should be straightforward to recover.*/ + var str = octets.decode("utf-8"); + var i = 0; + + while (i >= 0) { + var j = this.skipSpace(str, i); + + if (j < 0) { + return; + } + + var i = this.directiveOrStatement(str, j); + + if (i < 0) { + throw BadSyntax(this._thisDoc, this.lines, str, j, "expected directive or statement"); + } + } + }; + + __SinkParser.prototype.directiveOrStatement = function (str, h) { + var i = this.skipSpace(str, h); + + if (i < 0) { + return i; + } + + var j = this.directive(str, i); + + if (j >= 0) { + return this.checkDot(str, j); + } + + var j = this.statement(str, i); + + if (j >= 0) { + return this.checkDot(str, j); + } + + return j; + }; + + __SinkParser.prototype.tok = function (tok, str, i) { + /* + Check for keyword. Space must have been stripped on entry and + we must not be at end of file.*/ + var whitespace = "\t\n\v\f\r "; + + if (str.slice(i, i + 1) == "@") { + var i = i + 1; + } else { + if (Object(_utils__WEBPACK_IMPORTED_MODULE_2__["ArrayIndexOf"])(this.keywords, tok) < 0) { + return -1; + } + } + + var k = i + pyjslib_len(tok); + + if (str.slice(i, k) == tok && _notQNameChars.indexOf(str.charAt(k)) >= 0) { + return k; + } else { + return -1; + } + }; + + __SinkParser.prototype.directive = function (str, i) { + var j = this.skipSpace(str, i); + + if (j < 0) { + return j; + } + + var res = new pyjslib_List([]); + var j = this.tok("bind", str, i); + + if (j > 0) { + throw BadSyntax(this._thisDoc, this.lines, str, i, "keyword bind is obsolete: use @prefix"); + } + + var j = this.tok("keywords", str, i); + + if (j > 0) { + var i = this.commaSeparatedList(str, j, res, false); + + if (i < 0) { + throw BadSyntax(this._thisDoc, this.lines, str, i, "'@keywords' needs comma separated list of words"); + } + + this.setKeywords(pyjslib_slice(res, null, null)); + + if (diag_chatty_flag > 80) { + diag_progress("Keywords ", this.keywords); + } + + return i; + } + + var j = this.tok("forAll", str, i); + + if (j > 0) { + var i = this.commaSeparatedList(str, j, res, true); + + if (i < 0) { + throw BadSyntax(this._thisDoc, this.lines, str, i, "Bad variable list after @forAll"); + } + + var __x = new pyjslib_Iterator(res); + + try { + while (true) { + var x = __x.next(); + + if (Object(_utils__WEBPACK_IMPORTED_MODULE_2__["ArrayIndexOf"])(this._variables, x) < 0 || Object(_utils__WEBPACK_IMPORTED_MODULE_2__["ArrayIndexOf"])(this._parentVariables, x) >= 0) { + this._variables[x] = this._context.newUniversal(x); + } + } + } catch (e) { + if (e != StopIteration) { + throw e; + } + } + + return i; + } + + var j = this.tok("forSome", str, i); + + if (j > 0) { + var i = this.commaSeparatedList(str, j, res, this.uri_ref2); + + if (i < 0) { + throw BadSyntax(this._thisDoc, this.lines, str, i, "Bad variable list after @forSome"); + } + + var __x = new pyjslib_Iterator(res); + + try { + while (true) { + var x = __x.next(); + + this._context.declareExistential(x); + } + } catch (e) { + if (e != StopIteration) { + throw e; + } + } + + return i; + } + + var j = this.tok("prefix", str, i); + + if (j >= 0) { + var t = new pyjslib_List([]); + var i = this.qname(str, j, t); + + if (i < 0) { + throw BadSyntax(this._thisDoc, this.lines, str, j, "expected qname after @prefix"); + } + + var j = this.uri_ref2(str, i, t); + + if (j < 0) { + throw BadSyntax(this._thisDoc, this.lines, str, i, "expected after @prefix _qname_"); + } + + var ns = t[1].uri; + + if (this._baseURI) { + var ns = uripath_join(this._baseURI, ns); + } else { + assertFudge(ns.indexOf(":") >= 0, "With no base URI, cannot handle relative URI for NS"); + } + + assertFudge(ns.indexOf(":") >= 0); + this._bindings[t[0][0]] = ns; + this.bind(t[0][0], hexify(ns)); + return j; + } + + var j = this.tok("base", str, i); + + if (j >= 0) { + var t = new pyjslib_List([]); + var i = this.uri_ref2(str, j, t); + + if (i < 0) { + throw BadSyntax(this._thisDoc, this.lines, str, j, "expected after @base "); + } + + var ns = t[0].uri; + + if (this._baseURI) { + var ns = uripath_join(this._baseURI, ns); + } else { + throw BadSyntax(this._thisDoc, this.lines, str, j, "With no previous base URI, cannot use relative URI in @base <" + ns + ">"); + } + + assertFudge(ns.indexOf(":") >= 0); + this._baseURI = ns; + return i; + } + + return -1; + }; + + __SinkParser.prototype.bind = function (qn, uri) { + if (qn == "") {} else { + this._store.setPrefixForURI(qn, uri); + } + }; + + __SinkParser.prototype.setKeywords = function (k) { + /* + Takes a list of strings*/ + if (k == null) { + this.keywordsSet = 0; + } else { + this.keywords = k; + this.keywordsSet = 1; + } + }; + + __SinkParser.prototype.startDoc = function () {}; + + __SinkParser.prototype.endDoc = function () { + /* + Signal end of document and stop parsing. returns formula*/ + return this._formula; + }; + + __SinkParser.prototype.makeStatement = function (quad) { + quad[0].add(quad[2], quad[1], quad[3], this.source); + this.statementCount += 1; + }; + + __SinkParser.prototype.statement = function (str, i) { + var r = new pyjslib_List([]); + var i = this.object(str, i, r); + + if (i < 0) { + return i; + } + + var j = this.property_list(str, i, r[0]); + + if (j < 0) { + throw BadSyntax(this._thisDoc, this.lines, str, i, "expected propertylist"); + } + + return j; + }; + + __SinkParser.prototype.subject = function (str, i, res) { + return this.item(str, i, res); + }; + + __SinkParser.prototype.verb = function (str, i, res) { + /* + has _prop_ + is _prop_ of + a + = + _prop_ + >- prop -> + <- prop -< + _operator_*/ + var j = this.skipSpace(str, i); + + if (j < 0) { + return j; + } + + var r = new pyjslib_List([]); + var j = this.tok("has", str, i); + + if (j >= 0) { + var i = this.prop(str, j, r); + + if (i < 0) { + throw BadSyntax(this._thisDoc, this.lines, str, j, "expected property after 'has'"); + } + + res.push(new pyjslib_Tuple(["->", r[0]])); + return i; + } + + var j = this.tok("is", str, i); + + if (j >= 0) { + var i = this.prop(str, j, r); + + if (i < 0) { + throw BadSyntax(this._thisDoc, this.lines, str, j, "expected after 'is'"); + } + + var j = this.skipSpace(str, i); + + if (j < 0) { + throw BadSyntax(this._thisDoc, this.lines, str, i, "End of file found, expected property after 'is'"); + return j; + } + + var i = j; + var j = this.tok("of", str, i); + + if (j < 0) { + throw BadSyntax(this._thisDoc, this.lines, str, i, "expected 'of' after 'is' "); + } + + res.push(new pyjslib_Tuple(["<-", r[0]])); + return j; + } + + var j = this.tok("a", str, i); + + if (j >= 0) { + res.push(new pyjslib_Tuple(["->", this._store.sym(RDF_type_URI)])); + return j; + } + + if (str.slice(i, i + 2) == "<=") { + res.push(new pyjslib_Tuple(["<-", this._store.sym(Logic_NS + "implies")])); + return i + 2; + } + + if (str.slice(i, i + 1) == "=") { + if (str.slice(i + 1, i + 2) == ">") { + res.push(new pyjslib_Tuple(["->", this._store.sym(Logic_NS + "implies")])); + return i + 2; + } + + res.push(new pyjslib_Tuple(["->", this._store.sym(DAML_sameAs_URI)])); + return i + 1; + } + + if (str.slice(i, i + 2) == ":=") { + res.push(new pyjslib_Tuple(["->", Logic_NS + "becomes"])); + return i + 2; + } + + var j = this.prop(str, i, r); + + if (j >= 0) { + res.push(new pyjslib_Tuple(["->", r[0]])); + return j; + } + + if (str.slice(i, i + 2) == ">-" || str.slice(i, i + 2) == "<-") { + throw BadSyntax(this._thisDoc, this.lines, str, j, ">- ... -> syntax is obsolete."); + } + + return -1; + }; + + __SinkParser.prototype.prop = function (str, i, res) { + return this.item(str, i, res); + }; + + __SinkParser.prototype.item = function (str, i, res) { + return this.path(str, i, res); + }; + + __SinkParser.prototype.blankNode = function (uri) { + return this._context.bnode(uri, this._reason2); + }; + + __SinkParser.prototype.path = function (str, i, res) { + /* + Parse the path production. + */ + var j = this.nodeOrLiteral(str, i, res); + + if (j < 0) { + return j; + } + + while ("!^.".indexOf(str.slice(j, j + 1)) >= 0) { + var ch = str.slice(j, j + 1); + + if (ch == ".") { + var ahead = str.slice(j + 1, j + 2); + + if (!ahead || _notNameChars.indexOf(ahead) >= 0 && ":?<[{(".indexOf(ahead) < 0) { + break; + } + } + + var subj = res.pop(); + var obj = this.blankNode(this.here(j)); + var j = this.node(str, j + 1, res); + + if (j < 0) { + throw BadSyntax(this._thisDoc, this.lines, str, j, "EOF found in middle of path syntax"); + } + + var pred = res.pop(); + + if (ch == "^") { + this.makeStatement(new pyjslib_Tuple([this._context, pred, obj, subj])); + } else { + this.makeStatement(new pyjslib_Tuple([this._context, pred, subj, obj])); + } + + res.push(obj); + } + + return j; + }; + + __SinkParser.prototype.anonymousNode = function (ln) { + /* + Remember or generate a term for one of these _: anonymous nodes*/ + var term = this._anonymousNodes[ln]; + + if (term) { + return term; + } + + var term = this._store.bnode(ln); // var term = this._store.bnode(this._context, this._reason2); eh? + + + this._anonymousNodes[ln] = term; + return term; + }; + + __SinkParser.prototype.node = function (str, i, res, subjectAlready) { + if (typeof subjectAlready == 'undefined') subjectAlready = null; + /* + Parse the production. + Space is now skipped once at the beginning + instead of in multipe calls to self.skipSpace(). + */ + + var subj = subjectAlready; + var j = this.skipSpace(str, i); + + if (j < 0) { + return j; + } + + var i = j; + var ch = str.slice(i, i + 1); + + if (ch == "[") { + var bnodeID = this.here(i); + var j = this.skipSpace(str, i + 1); + + if (j < 0) { + throw BadSyntax(this._thisDoc, this.lines, str, i, "EOF after '['"); + } + + if (str.slice(j, j + 1) == "=") { + var i = j + 1; + var objs = new pyjslib_List([]); + var j = this.objectList(str, i, objs); + + if (j >= 0) { + var subj = objs[0]; + + if (pyjslib_len(objs) > 1) { + var __obj = new pyjslib_Iterator(objs); + + try { + while (true) { + var obj = __obj.next(); + + this.makeStatement(new pyjslib_Tuple([this._context, this._store.sym(DAML_sameAs_URI), subj, obj])); + } + } catch (e) { + if (e != StopIteration) { + throw e; + } + } + } + + var j = this.skipSpace(str, j); + + if (j < 0) { + throw BadSyntax(this._thisDoc, this.lines, str, i, "EOF when objectList expected after [ = "); + } + + if (str.slice(j, j + 1) == ";") { + var j = j + 1; + } + } else { + throw BadSyntax(this._thisDoc, this.lines, str, i, "objectList expected after [= "); + } + } + + if (subj == null) { + var subj = this.blankNode(bnodeID); + } + + var i = this.property_list(str, j, subj); + + if (i < 0) { + throw BadSyntax(this._thisDoc, this.lines, str, j, "property_list expected"); + } + + var j = this.skipSpace(str, i); + + if (j < 0) { + throw BadSyntax(this._thisDoc, this.lines, str, i, "EOF when ']' expected after [ "); + } + + if (str.slice(j, j + 1) != "]") { + throw BadSyntax(this._thisDoc, this.lines, str, j, "']' expected"); + } + + res.push(subj); + return j + 1; + } + + if (ch == "{") { + var ch2 = str.slice(i + 1, i + 2); + + if (ch2 == "$") { + i += 1; + var j = i + 1; + var mylist = new pyjslib_List([]); + var first_run = true; + + while (1) { + var i = this.skipSpace(str, j); + + if (i < 0) { + throw BadSyntax(this._thisDoc, this.lines, str, i, "needed '$}', found end."); + } + + if (str.slice(i, i + 2) == "$}") { + var j = i + 2; + break; + } + + if (!first_run) { + if (str.slice(i, i + 1) == ",") { + i += 1; + } else { + throw BadSyntax(this._thisDoc, this.lines, str, i, "expected: ','"); + } + } else { + var first_run = false; + } + + var item = new pyjslib_List([]); + var j = this.item(str, i, item); + + if (j < 0) { + throw BadSyntax(this._thisDoc, this.lines, str, i, "expected item in set or '$}'"); + } + + mylist.push(item[0]); + } + + res.push(this._store.newSet(mylist, this._context)); + return j; + } else { + var j = i + 1; + var oldParentContext = this._parentContext; + this._parentContext = this._context; + var parentAnonymousNodes = this._anonymousNodes; + var grandParentVariables = this._parentVariables; + this._parentVariables = this._variables; + this._anonymousNodes = new pyjslib_Dict([]); + this._variables = this._variables.slice(); + var reason2 = this._reason2; + this._reason2 = becauseSubexpression; + + if (subj == null) { + var subj = this._store.formula(); + } + + this._context = subj; + + while (1) { + var i = this.skipSpace(str, j); + + if (i < 0) { + throw BadSyntax(this._thisDoc, this.lines, str, i, "needed '}', found end."); + } + + if (str.slice(i, i + 1) == "}") { + var j = i + 1; + break; + } + + var j = this.directiveOrStatement(str, i); + + if (j < 0) { + throw BadSyntax(this._thisDoc, this.lines, str, i, "expected statement or '}'"); + } + } + + this._anonymousNodes = parentAnonymousNodes; + this._variables = this._parentVariables; + this._parentVariables = grandParentVariables; + this._context = this._parentContext; + this._reason2 = reason2; + this._parentContext = oldParentContext; + res.push(subj.close()); + return j; + } + } + + if (ch == "(") { + var thing_type = this._store.list; + var ch2 = str.slice(i + 1, i + 2); + + if (ch2 == "$") { + var thing_type = this._store.newSet; + i += 1; + } + + var j = i + 1; + var mylist = new pyjslib_List([]); + + while (1) { + var i = this.skipSpace(str, j); + + if (i < 0) { + throw BadSyntax(this._thisDoc, this.lines, str, i, "needed ')', found end."); + } + + if (str.slice(i, i + 1) == ")") { + var j = i + 1; + break; + } + + var item = new pyjslib_List([]); + var j = this.item(str, i, item); + + if (j < 0) { + throw BadSyntax(this._thisDoc, this.lines, str, i, "expected item in list or ')'"); + } + + mylist.push(item[0]); + } + + res.push(thing_type(mylist, this._context)); + return j; + } + + var j = this.tok("this", str, i); + + if (j >= 0) { + throw BadSyntax(this._thisDoc, this.lines, str, i, "Keyword 'this' was ancient N3. Now use @forSome and @forAll keywords."); + res.push(this._context); + return j; + } + + var j = this.tok("true", str, i); + + if (j >= 0) { + res.push(true); + return j; + } + + var j = this.tok("false", str, i); + + if (j >= 0) { + res.push(false); + return j; + } + + if (subj == null) { + var j = this.uri_ref2(str, i, res); + + if (j >= 0) { + return j; + } + } + + return -1; + }; + + __SinkParser.prototype.property_list = function (str, i, subj) { + /* + Parse property list + Leaves the terminating punctuation in the buffer + */ + while (1) { + var j = this.skipSpace(str, i); + + if (j < 0) { + throw BadSyntax(this._thisDoc, this.lines, str, i, "EOF found when expected verb in property list"); + return j; + } + + if (str.slice(j, j + 2) == ":-") { + var i = j + 2; + var res = new pyjslib_List([]); + var j = this.node(str, i, res, subj); + + if (j < 0) { + throw BadSyntax(this._thisDoc, this.lines, str, i, "bad {} or () or [] node after :- "); + } + + var i = j; + continue; + } + + var i = j; + var v = new pyjslib_List([]); + var j = this.verb(str, i, v); + + if (j <= 0) { + return i; + } + + var objs = new pyjslib_List([]); + var i = this.objectList(str, j, objs); + + if (i < 0) { + throw BadSyntax(this._thisDoc, this.lines, str, j, "objectList expected"); + } + + var __obj = new pyjslib_Iterator(objs); + + try { + while (true) { + var obj = __obj.next(); + + var pairFudge = v[0]; + var dir = pairFudge[0]; + var sym = pairFudge[1]; + + if (dir == "->") { + this.makeStatement(new pyjslib_Tuple([this._context, sym, subj, obj])); + } else { + this.makeStatement(new pyjslib_Tuple([this._context, sym, obj, subj])); + } + } + } catch (e) { + if (e != StopIteration) { + throw e; + } + } + + var j = this.skipSpace(str, i); + + if (j < 0) { + throw BadSyntax(this._thisDoc, this.lines, str, j, "EOF found in list of objects"); + return j; + } + + if (str.slice(i, i + 1) != ";") { + return i; + } + + var i = i + 1; + } + }; + + __SinkParser.prototype.commaSeparatedList = function (str, j, res, ofUris) { + /* + return value: -1 bad syntax; >1 new position in str + res has things found appended + Used to use a final value of the function to be called, e.g. this.bareWord + but passing the function didn't work fo js converion pyjs + */ + var i = this.skipSpace(str, j); + + if (i < 0) { + throw BadSyntax(this._thisDoc, this.lines, str, i, "EOF found expecting comma sep list"); + return i; + } + + if (str.charAt(i) == ".") { + return j; + } + + if (ofUris) { + var i = this.uri_ref2(str, i, res); + } else { + var i = this.bareWord(str, i, res); + } + + if (i < 0) { + return -1; + } + + while (1) { + var j = this.skipSpace(str, i); + + if (j < 0) { + return j; + } + + var ch = str.slice(j, j + 1); + + if (ch != ",") { + if (ch != ".") { + return -1; + } + + return j; + } + + if (ofUris) { + var i = this.uri_ref2(str, j + 1, res); + } else { + var i = this.bareWord(str, j + 1, res); + } + + if (i < 0) { + throw BadSyntax(this._thisDoc, this.lines, str, i, "bad list content"); + return i; + } + } + }; + + __SinkParser.prototype.objectList = function (str, i, res) { + var i = this.object(str, i, res); + + if (i < 0) { + return -1; + } + + while (1) { + var j = this.skipSpace(str, i); + + if (j < 0) { + throw BadSyntax(this._thisDoc, this.lines, str, j, "EOF found after object"); + return j; + } + + if (str.slice(j, j + 1) != ",") { + return j; + } + + var i = this.object(str, j + 1, res); + + if (i < 0) { + return i; + } + } + }; + + __SinkParser.prototype.checkDot = function (str, i) { + var j = this.skipSpace(str, i); + + if (j < 0) { + return j; + } + + if (str.slice(j, j + 1) == ".") { + return j + 1; + } + + if (str.slice(j, j + 1) == "}") { + return j; + } + + if (str.slice(j, j + 1) == "]") { + return j; + } + + throw BadSyntax(this._thisDoc, this.lines, str, j, "expected '.' or '}' or ']' at end of statement"); + return i; + }; + + __SinkParser.prototype.uri_ref2 = function (str, i, res) { + /* + Generate uri from n3 representation. + Note that the RDF convention of directly concatenating + NS and local name is now used though I prefer inserting a '#' + to make the namesapces look more like what XML folks expect. + */ + var qn = new pyjslib_List([]); + var j = this.qname(str, i, qn); + + if (j >= 0) { + var pairFudge = qn[0]; + var pfx = pairFudge[0]; + var ln = pairFudge[1]; + + if (pfx == null) { + assertFudge(0, "not used?"); + var ns = this._baseURI + ADDED_HASH; + } else { + var ns = this._bindings[pfx]; + + if (!ns) { + if (pfx == "_") { + res.push(this.anonymousNode(ln)); + return j; + } + + throw BadSyntax(this._thisDoc, this.lines, str, i, "Prefix " + pfx + " not bound."); + } + } + + var symb = this._store.sym(ns + ln); + + if (Object(_utils__WEBPACK_IMPORTED_MODULE_2__["ArrayIndexOf"])(this._variables, symb) >= 0) { + res.push(this._variables[symb]); + } else { + res.push(symb); + } + + return j; + } + + var i = this.skipSpace(str, i); + + if (i < 0) { + return -1; + } + + if (str.charAt(i) == "?") { + var v = new pyjslib_List([]); + var j = this.variable(str, i, v); + + if (j > 0) { + res.push(v[0]); + return j; + } + + return -1; + } else if (str.charAt(i) == "<") { + var i = i + 1; + var st = i; + + while (i < pyjslib_len(str)) { + if (str.charAt(i) == ">") { + var uref = str.slice(st, i); + + if (this._baseURI) { + var uref = uripath_join(this._baseURI, uref); + } else { + assertFudge(uref.indexOf(":") >= 0, "With no base URI, cannot deal with relative URIs"); + } + + if (str.slice(i - 1, i) == "#" && !(pyjslib_slice(uref, -1, null) == "#")) { + var uref = uref + "#"; + } + + var symb = this._store.sym(uref); + + if (Object(_utils__WEBPACK_IMPORTED_MODULE_2__["ArrayIndexOf"])(this._variables, symb) >= 0) { + res.push(this._variables[symb]); + } else { + res.push(symb); + } + + return i + 1; + } + + var i = i + 1; + } + + throw BadSyntax(this._thisDoc, this.lines, str, j, "unterminated URI reference"); + } else if (this.keywordsSet) { + var v = new pyjslib_List([]); + var j = this.bareWord(str, i, v); + + if (j < 0) { + return -1; + } + + if (Object(_utils__WEBPACK_IMPORTED_MODULE_2__["ArrayIndexOf"])(this.keywords, v[0]) >= 0) { + throw BadSyntax(this._thisDoc, this.lines, str, i, "Keyword \"" + v[0] + "\" not allowed here."); + } + + res.push(this._store.sym(this._bindings[""] + v[0])); + return j; + } else { + return -1; + } + }; + + __SinkParser.prototype.skipSpace = function (str, i) { + /* + Skip white space, newlines and comments. + return -1 if EOF, else position of first non-ws character*/ + var whitespace = " \n\r\t\f\x0B\xA0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u200B\u2028\u2029\u3000"; + + for (var j = i ? i : 0; j < str.length; j++) { + var ch = str.charAt(j); // console.log(" skipspace j= "+j + " i= " + i + " n= " + str.length); + // console.log(" skipspace ch <" + ch + ">"); + + if (whitespace.indexOf(ch) < 0) { + //not ws + // console.log(" skipspace 2 ch <" + ch + ">"); + if (str.charAt(j) === '#') { + for (;; j++) { + // console.log(" skipspace2 j= "+j + " i= " + i + " n= " + str.length); + if (j === str.length) { + return -1; // EOF + } + + if (str.charAt(j) === '\n') { + this.lines = this.lines + 1; + break; + } + } + + ; + } else { + // Not hash - something interesting + // console.log(" skipspace 3 ch <" + ch + ">"); + return j; + } + } else { + // Whitespace + // console.log(" skipspace 5 ch <" + ch + ">"); + if (str.charAt(j) === '\n') { + this.lines = this.lines + 1; + } + } + } // next j + + + return -1; // EOF + }; + + __SinkParser.prototype.variable = function (str, i, res) { + /* + ?abc -> variable(:abc) + */ + var j = this.skipSpace(str, i); + + if (j < 0) { + return -1; + } + + if (str.slice(j, j + 1) != "?") { + return -1; + } + + var j = j + 1; + var i = j; + + if ("0123456789-".indexOf(str.charAt(j)) >= 0) { + throw BadSyntax(this._thisDoc, this.lines, str, j, "Varible name can't start with '" + str.charAt(j) + "s'"); + return -1; + } + + while (i < pyjslib_len(str) && _notNameChars.indexOf(str.charAt(i)) < 0) { + var i = i + 1; + } + + if (this._parentContext == null) { + throw BadSyntax(this._thisDoc, this.lines, str, j, "Can't use ?xxx syntax for variable in outermost level: " + str.slice(j - 1, i)); + } + + res.push(this._store.variable(str.slice(j, i))); + return i; + }; + + __SinkParser.prototype.bareWord = function (str, i, res) { + /* + abc -> :abc + */ + var j = this.skipSpace(str, i); + + if (j < 0) { + return -1; + } + + var ch = str.charAt(j); + + if ("0123456789-".indexOf(ch) >= 0) { + return -1; + } + + if (_notNameChars.indexOf(ch) >= 0) { + return -1; + } + + var i = j; + + while (i < pyjslib_len(str) && _notNameChars.indexOf(str.charAt(i)) < 0) { + var i = i + 1; + } + + res.push(str.slice(j, i)); + return i; + }; + + __SinkParser.prototype.qname = function (str, i, res) { + /* + xyz:def -> ('xyz', 'def') + If not in keywords and keywordsSet: def -> ('', 'def') + :def -> ('', 'def') + */ + var i = this.skipSpace(str, i); + + if (i < 0) { + return -1; + } + + var c = str.charAt(i); + + if ("0123456789-+".indexOf(c) >= 0) { + return -1; + } + + if (_notNameChars.indexOf(c) < 0) { + var ln = c; + var i = i + 1; + + while (i < pyjslib_len(str)) { + var c = str.charAt(i); + + if (_notNameChars.indexOf(c) < 0) { + var ln = ln + c; + var i = i + 1; + } else { + break; + } + } + } else { + var ln = ""; + } + + if (i < pyjslib_len(str) && str.charAt(i) == ":") { + var pfx = ln; + var i = i + 1; + var ln = ""; + + while (i < pyjslib_len(str)) { + var c = str.charAt(i); + + if (_notNameChars.indexOf(c) < 0) { + var ln = ln + c; + var i = i + 1; + } else { + break; + } + } + + res.push(new pyjslib_Tuple([pfx, ln])); + return i; + } else { + if (ln && this.keywordsSet && Object(_utils__WEBPACK_IMPORTED_MODULE_2__["ArrayIndexOf"])(this.keywords, ln) < 0) { + res.push(new pyjslib_Tuple(["", ln])); + return i; + } + + return -1; + } + }; + + __SinkParser.prototype.object = function (str, i, res) { + var j = this.subject(str, i, res); + + if (j >= 0) { + return j; + } else { + var j = this.skipSpace(str, i); + + if (j < 0) { + return -1; + } else { + var i = j; + } + + var delim = null; + var ch = str.charAt(i); + + if (ch == "\"" || ch == "'") { + if (str.slice(i, i + 3 == ch + ch)) { + delim = ch + ch + ch; + } else { + delim = ch; + } + + var i = i + pyjslib_len(delim); + var pairFudge = this.strconst(str, i, delim); + var j = pairFudge[0]; + var s = pairFudge[1]; + res.push(this._store.literal(s)); + diag_progress("New string const ", s, j); + return j; + } else { + return -1; + } + } + }; + + __SinkParser.prototype.nodeOrLiteral = function (str, i, res) { + var j = this.node(str, i, res); + + if (j >= 0) { + return j; + } else { + var j = this.skipSpace(str, i); + + if (j < 0) { + return -1; + } else { + var i = j; + } + + var ch = str.charAt(i); + + if ("-+0987654321".indexOf(ch) >= 0) { + datetime_syntax.lastIndex = 0; + var m = datetime_syntax.exec(str.slice(i)); + + if (m != null) { + // j = ( i + datetime_syntax.lastIndex ) ; + var val = m[0]; + j = i + val.length; + + if (val.indexOf("T") >= 0) { + res.push(this._store.literal(val, this._store.sym(DATETIME_DATATYPE))); + } else { + res.push(this._store.literal(val, this._store.sym(DATE_DATATYPE))); + } + } else { + number_syntax.lastIndex = 0; + var m = number_syntax.exec(str.slice(i)); + + if (m == null) { + throw BadSyntax(this._thisDoc, this.lines, str, i, "Bad number or date syntax"); + } + + j = i + number_syntax.lastIndex; + var val = str.slice(i, j); + + if (val.indexOf("e") >= 0) { + res.push(this._store.literal(parseFloat(val), this._store.sym(FLOAT_DATATYPE))); + } else if (str.slice(i, j).indexOf(".") >= 0) { + res.push(this._store.literal(parseFloat(val), this._store.sym(DECIMAL_DATATYPE))); + } else { + res.push(this._store.literal(parseInt(val), this._store.sym(INTEGER_DATATYPE))); + } + } + + ; + return j; // Where we have got up to + } + + if (str.charAt(i) == "\"") { + if (str.slice(i, i + 3) == "\"\"\"") { + var delim = "\"\"\""; + } else { + var delim = "\""; + } + + var i = i + pyjslib_len(delim); + var dt = null; + var pairFudge = this.strconst(str, i, delim); + var j = pairFudge[0]; + var s = pairFudge[1]; + var lang = null; + + if (str.slice(j, j + 1) == "@") { + langcode.lastIndex = 0; + var m = langcode.exec(str.slice(j + 1)); + + if (m == null) { + throw BadSyntax(this._thisDoc, startline, str, i, "Bad language code syntax on string literal, after @"); + } + + var i = langcode.lastIndex + j + 1; + var lang = str.slice(j + 1, i); + var j = i; + } + + if (str.slice(j, j + 2) == "^^") { + var res2 = new pyjslib_List([]); + var j = this.uri_ref2(str, j + 2, res2); + var dt = res2[0]; + } + + res.push(this._store.literal(s, lang || dt)); + return j; + } else { + return -1; + } + } + }; + + __SinkParser.prototype.strconst = function (str, i, delim) { + /* + parse an N3 string constant delimited by delim. + return index, val + */ + var j = i; + var ustr = ""; + var startline = this.lines; + + while (j < pyjslib_len(str)) { + var i = j + pyjslib_len(delim); + + if (str.slice(j, i) == delim) { + return new pyjslib_Tuple([i, ustr]); + } + + if (str.charAt(j) == "\"") { + var ustr = ustr + "\""; + var j = j + 1; + continue; + } + + interesting.lastIndex = 0; + var m = interesting.exec(str.slice(j)); + + if (!m) { + throw BadSyntax(this._thisDoc, startline, str, j, "Closing quote missing in string at ^ in " + str.slice(j - 20, j) + "^" + str.slice(j, j + 20)); + } + + var i = j + interesting.lastIndex - 1; + var ustr = ustr + str.slice(j, i); + var ch = str.charAt(i); + + if (ch == "\"") { + var j = i; + continue; + } else if (ch == "\r") { + var j = i + 1; + continue; + } else if (ch == "\n") { + if (delim == "\"") { + throw BadSyntax(this._thisDoc, startline, str, i, "newline found in string literal"); + } + + this.lines = this.lines + 1; + var ustr = ustr + ch; + var j = i + 1; + this.previousLine = this.startOfLine; + this.startOfLine = j; + } else if (ch == "\\") { + var j = i + 1; + var ch = str.slice(j, j + 1); + + if (!ch) { + throw BadSyntax(this._thisDoc, startline, str, i, "unterminated string literal (2)"); + } + + var k = string_find("abfrtvn\\\"", ch); + + if (k >= 0) { + var uch = "\a\b\f\r\t\v\n\\\"".charAt(k); + var ustr = ustr + uch; + var j = j + 1; + } else if (ch == "u") { + var pairFudge = this.uEscape(str, j + 1, startline); + var j = pairFudge[0]; + var ch = pairFudge[1]; + var ustr = ustr + ch; + } else if (ch == "U") { + var pairFudge = this.UEscape(str, j + 1, startline); + var j = pairFudge[0]; + var ch = pairFudge[1]; + var ustr = ustr + ch; + } else { + throw BadSyntax(this._thisDoc, this.lines, str, i, "bad escape"); + } + } + } + + throw BadSyntax(this._thisDoc, this.lines, str, i, "unterminated string literal"); + }; + + __SinkParser.prototype.uEscape = function (str, i, startline) { + var j = i; + var count = 0; + var value = 0; + + while (count < 4) { + var chFudge = str.slice(j, j + 1); + var ch = chFudge.toLowerCase(); + var j = j + 1; + + if (ch == "") { + throw BadSyntax(this._thisDoc, startline, str, i, "unterminated string literal(3)"); + } + + var k = string_find("0123456789abcdef", ch); + + if (k < 0) { + throw BadSyntax(this._thisDoc, startline, str, i, "bad string literal hex escape"); + } + + var value = value * 16 + k; + var count = count + 1; + } + + var uch = String.fromCharCode(value); + return new pyjslib_Tuple([j, uch]); + }; + + __SinkParser.prototype.UEscape = function (str, i, startline) { + var j = i; + var count = 0; + var value = "\\U"; + + while (count < 8) { + var chFudge = str.slice(j, j + 1); + var ch = chFudge.toLowerCase(); + var j = j + 1; + + if (ch == "") { + throw BadSyntax(this._thisDoc, startline, str, i, "unterminated string literal(3)"); + } + + var k = string_find("0123456789abcdef", ch); + + if (k < 0) { + throw BadSyntax(this._thisDoc, startline, str, i, "bad string literal hex escape"); + } + + var value = value + ch; + var count = count + 1; + } + + var uch = stringFromCharCode("0x" + pyjslib_slice(value, 2, 10) - 0); + return new pyjslib_Tuple([j, uch]); + }; + + function OLD_BadSyntax(uri, lines, str, i, why) { + return new __OLD_BadSyntax(uri, lines, str, i, why); + } + + function __OLD_BadSyntax(uri, lines, str, i, why) { + this._str = str.encode("utf-8"); + this._str = str; + this._i = i; + this._why = why; + this.lines = lines; + this._uri = uri; + } + + __OLD_BadSyntax.prototype.toString = function () { + var str = this._str; + var i = this._i; + var st = 0; + + if (i > 60) { + var pre = "..."; + var st = i - 60; + } else { + var pre = ""; + } + + if (pyjslib_len(str) - i > 60) { + var post = "..."; + } else { + var post = ""; + } + + return "Line %i of <%s>: Bad syntax (%s) at ^ in:\n\"%s%s^%s%s\"" % new pyjslib_Tuple([this.lines + 1, this._uri, this._why, pre, str.slice(st, i), str.slice(i, i + 60), post]); + }; + + function BadSyntax(uri, lines, str, i, why) { + var lineNo = lines + 1; + var msg = "Line " + lineNo + " of <" + uri + ">: Bad syntax: " + why + "\nat: \"" + str.slice(i, i + 30) + "\""; + var e = new SyntaxError(msg, uri, lineNo); + e.lineNo = lineNo; + e.characterInFile = i; + e.syntaxProblem = why; + return e; + } + + function stripCR(str) { + var res = ""; + + var __ch = new pyjslib_Iterator(str); + + try { + while (true) { + var ch = __ch.next(); + + if (ch != "\r") { + var res = res + ch; + } + } + } catch (e) { + if (e != StopIteration) { + throw e; + } + } + + return res; + } + + function dummyWrite(x) {} + + return SinkParser; +})()); + +/***/ }), + +/***/ "./node_modules/rdflib/esm/named-node.js": +/*!***********************************************!*\ + !*** ./node_modules/rdflib/esm/named-node.js ***! + \***********************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return NamedNode; }); +/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js"); +/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js"); +/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__); +/* harmony import */ var _babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/assertThisInitialized */ "./node_modules/@babel/runtime/helpers/assertThisInitialized.js"); +/* harmony import */ var _babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__); +/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/inherits */ "./node_modules/@babel/runtime/helpers/inherits.js"); +/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3__); +/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "./node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"); +/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__); +/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "./node_modules/@babel/runtime/helpers/getPrototypeOf.js"); +/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__); +/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "./node_modules/@babel/runtime/helpers/defineProperty.js"); +/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__); +/* harmony import */ var _class_order__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./class-order */ "./node_modules/rdflib/esm/class-order.js"); +/* harmony import */ var _node_internal__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./node-internal */ "./node_modules/rdflib/esm/node-internal.js"); +/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./types */ "./node_modules/rdflib/esm/types.js"); +/* harmony import */ var _utils_termValue__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./utils/termValue */ "./node_modules/rdflib/esm/utils/termValue.js"); +/* harmony import */ var _utils_terms__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./utils/terms */ "./node_modules/rdflib/esm/utils/terms.js"); + + + + + + + + +function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5___default()(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5___default()(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4___default()(this, result); }; } + +function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } + + + + + + +/** + * A named (IRI) RDF node + */ + +var NamedNode = /*#__PURE__*/function (_Node) { + _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3___default()(NamedNode, _Node); + + var _super = _createSuper(NamedNode); + + /** + * Create a named (IRI) RDF Node + * @constructor + * @param iri - The IRI for this node + */ + function NamedNode(iri) { + var _this; + + _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, NamedNode); + + _this = _super.call(this, Object(_utils_termValue__WEBPACK_IMPORTED_MODULE_10__["termValue"])(iri)); + + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6___default()(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2___default()(_this), "termType", _types__WEBPACK_IMPORTED_MODULE_9__["NamedNodeTermType"]); + + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6___default()(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2___default()(_this), "classOrder", _class_order__WEBPACK_IMPORTED_MODULE_7__["default"].NamedNode); + + if (!_this.value) { + throw new Error('Missing IRI for NamedNode'); + } + + if (!_this.value.includes(':')) { + throw new Error('NamedNode IRI "' + iri + '" must be absolute.'); + } + + if (_this.value.includes(' ')) { + var message = 'Error: NamedNode IRI "' + iri + '" must not contain unencoded spaces.'; + throw new Error(message); + } + + return _this; + } + /** + * Returns an $rdf node for the containing directory, ending in slash. + */ + + + _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default()(NamedNode, [{ + key: "dir", + value: function dir() { + var str = this.value.split('#')[0]; + var p = str.slice(0, -1).lastIndexOf('/'); + var q = str.indexOf('//'); + if (q >= 0 && p < q + 2 || p < 0) return null; + return new NamedNode(str.slice(0, p + 1)); + } + /** + * Returns an NN for the whole web site, ending in slash. + * Contrast with the "origin" which does NOT have a trailing slash + */ + + }, { + key: "site", + value: function site() { + var str = this.value.split('#')[0]; + var p = str.indexOf('//'); + if (p < 0) throw new Error('This URI does not have a web site part (origin)'); + var q = str.indexOf('/', p + 2); + + if (q < 0) { + return new NamedNode(str.slice(0) + '/'); // Add slash to a bare origin + } else { + return new NamedNode(str.slice(0, q + 1)); + } + } + /** + * Creates the fetchable named node for the document. + * Removes everything from the # anchor tag. + */ + + }, { + key: "doc", + value: function doc() { + if (this.value.indexOf('#') < 0) { + return this; + } else { + return new NamedNode(this.value.split('#')[0]); + } + } + /** + * Returns the URI including + */ + + }, { + key: "toString", + value: function toString() { + return '<' + this.value + '>'; + } + /** The local identifier with the document */ + + }, { + key: "id", + value: function id() { + return this.value.split('#')[1]; + } + /** Alias for value, favored by Tim */ + + }, { + key: "uri", + get: function get() { + return this.value; + }, + set: function set(uri) { + this.value = uri; + } + /** + * Creates a named node from the specified input value + * @param value - An input value + */ + + }], [{ + key: "fromValue", + value: function fromValue(value) { + if (typeof value === 'undefined' || value === null) { + return value; + } + + if (Object(_utils_terms__WEBPACK_IMPORTED_MODULE_11__["isTerm"])(value)) { + return value; + } + + return new NamedNode(value); + } + }]); + + return NamedNode; +}(_node_internal__WEBPACK_IMPORTED_MODULE_8__["default"]); + + + +/***/ }), + +/***/ "./node_modules/rdflib/esm/namespace.js": +/*!**********************************************!*\ + !*** ./node_modules/rdflib/esm/namespace.js ***! + \**********************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return Namespace; }); +/* harmony import */ var _named_node__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./named-node */ "./node_modules/rdflib/esm/named-node.js"); + + +/** + * Gets a namespace for the specified namespace's URI + * @param nsuri - The URI for the namespace + * @param [factory] - The factory for creating named nodes with + */ +function Namespace(nsuri, factory) { + var dataFactory = factory || { + namedNode: function namedNode(value) { + return new _named_node__WEBPACK_IMPORTED_MODULE_0__["default"](value); + } + }; + return function (ln) { + return dataFactory.namedNode(nsuri + (ln || '')); + }; +} + +/***/ }), + +/***/ "./node_modules/rdflib/esm/node-internal.js": +/*!**************************************************!*\ + !*** ./node_modules/rdflib/esm/node-internal.js ***! + \**************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return Node; }); +/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js"); +/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js"); +/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__); +/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "./node_modules/@babel/runtime/helpers/defineProperty.js"); +/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_2__); + + + + +/** + * The superclass of all RDF Statement objects, that is + * NamedNode, Literal, BlankNode, etc. + * Should not be instantiated directly. + * Also called Term. + * @link https://rdf.js.org/data-model-spec/#term-interface + * @class Node + */ +var Node = /*#__PURE__*/function () { + // Specified in './node.ts' to prevent circular dependency + // Specified in './node.ts' to prevent circular dependency + + /** The type of node */ + + /** The class order for this node */ + + /** The node's value */ + function Node(value) { + _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, Node); + + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_2___default()(this, "termType", void 0); + + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_2___default()(this, "classOrder", void 0); + + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_2___default()(this, "value", void 0); + + this.value = value; + } + /** + * Creates the substituted node for this one, according to the specified bindings + * @param bindings - Bindings of identifiers to nodes + */ + + + _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default()(Node, [{ + key: "substitute", + value: function substitute(bindings) { + console.log('@@@ node substitute' + this); + return this; + } + /** + * Compares this node with another + * @see {equals} to check if two nodes are equal + * @param other - The other node + */ + + }, { + key: "compareTerm", + value: function compareTerm(other) { + if (this.classOrder < other.classOrder) { + return -1; + } + + if (this.classOrder > other.classOrder) { + return +1; + } + + if (this.value < other.value) { + return -1; + } + + if (this.value > other.value) { + return +1; + } + + return 0; + } + /** + * Compares whether the two nodes are equal + * @param other The other node + */ + + }, { + key: "equals", + value: function equals(other) { + if (!other) { + return false; + } + + return this.termType === other.termType && this.value === other.value; + } + /** + * Creates a hash for this node + * @deprecated use {rdfFactory.id} instead if possible + */ + + }, { + key: "hashString", + value: function hashString() { + return this.toCanonical(); + } + /** + * Compares whether this node is the same as the other one + * @param other - Another node + */ + + }, { + key: "sameTerm", + value: function sameTerm(other) { + return this.equals(other); + } + /** + * Creates a canonical string representation of this node + */ + + }, { + key: "toCanonical", + value: function toCanonical() { + return this.toNT(); + } + /** + * Creates a n-triples string representation of this node + */ + + }, { + key: "toNT", + value: function toNT() { + return this.toString(); + } + /** + * Creates a n-quads string representation of this node + */ + + }, { + key: "toNQ", + value: function toNQ() { + return this.toNT(); + } + /** + * Creates a string representation of this node + */ + + }, { + key: "toString", + value: function toString() { + throw new Error('Node.toString() is abstract - see the subclasses instead'); + } + }]); + + return Node; +}(); + +_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_2___default()(Node, "fromValue", void 0); + +_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_2___default()(Node, "toJS", void 0); + + + +/***/ }), + +/***/ "./node_modules/rdflib/esm/node.js": +/*!*****************************************!*\ + !*** ./node_modules/rdflib/esm/node.js ***! + \*****************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _collection__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./collection */ "./node_modules/rdflib/esm/collection.js"); +/* harmony import */ var _node_internal__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./node-internal */ "./node_modules/rdflib/esm/node-internal.js"); +/* harmony import */ var _namespace__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./namespace */ "./node_modules/rdflib/esm/namespace.js"); +/* harmony import */ var _utils_terms__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./utils/terms */ "./node_modules/rdflib/esm/utils/terms.js"); +// This file attaches all functionality to Node +// that would otherwise require circular dependencies. + + + + + +/** + * Creates an RDF Node from a native javascript value. + * RDF Nodes are returned unchanged, undefined returned as itself. + * @method fromValue + * @static + * @param value {Node|Date|String|Number|Boolean|Undefined} + * @return {Node|Collection} + */ +_node_internal__WEBPACK_IMPORTED_MODULE_1__["default"].fromValue = _collection__WEBPACK_IMPORTED_MODULE_0__["fromValue"]; +/* harmony default export */ __webpack_exports__["default"] = (_node_internal__WEBPACK_IMPORTED_MODULE_1__["default"]); +var ns = { + xsd: Object(_namespace__WEBPACK_IMPORTED_MODULE_2__["default"])('http://www.w3.org/2001/XMLSchema#') +}; +/** + * Gets the javascript object equivalent to a node + * @param term The RDF node + */ + +_node_internal__WEBPACK_IMPORTED_MODULE_1__["default"].toJS = function (term) { + if (Object(_utils_terms__WEBPACK_IMPORTED_MODULE_3__["isCollection"])(term)) { + return term.elements.map(_node_internal__WEBPACK_IMPORTED_MODULE_1__["default"].toJS); // Array node (not standard RDFJS) + } + + if (!Object(_utils_terms__WEBPACK_IMPORTED_MODULE_3__["isLiteral"])(term)) return term; + + if (term.datatype.equals(ns.xsd('boolean'))) { + return term.value === '1' || term.value === 'true'; + } + + if (term.datatype.equals(ns.xsd('dateTime')) || term.datatype.equals(ns.xsd('date'))) { + return new Date(term.value); + } + + if (term.datatype.equals(ns.xsd('integer')) || term.datatype.equals(ns.xsd('float')) || term.datatype.equals(ns.xsd('decimal'))) { + return Number(term.value); + } + + return term.value; +}; + +/***/ }), + +/***/ "./node_modules/rdflib/esm/parse.js": +/*!******************************************!*\ + !*** ./node_modules/rdflib/esm/parse.js ***! + \******************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return parse; }); +/* harmony import */ var _factories_extended_term_factory__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./factories/extended-term-factory */ "./node_modules/rdflib/esm/factories/extended-term-factory.js"); +/* harmony import */ var _jsonldparser__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./jsonldparser */ "./node_modules/rdflib/esm/jsonldparser.js"); +/* harmony import */ var n3__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! n3 */ "./node_modules/n3/src/index.js"); +/* harmony import */ var _n3parser__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./n3parser */ "./node_modules/rdflib/esm/n3parser.js"); +/* harmony import */ var _rdfaparser__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./rdfaparser */ "./node_modules/rdflib/esm/rdfaparser.js"); +/* harmony import */ var _rdfxmlparser__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./rdfxmlparser */ "./node_modules/rdflib/esm/rdfxmlparser.js"); +/* harmony import */ var _patch_parser__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./patch-parser */ "./node_modules/rdflib/esm/patch-parser.js"); +/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./utils-js */ "./node_modules/rdflib/esm/utils-js.js"); +/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./types */ "./node_modules/rdflib/esm/types.js"); + + // @ts-ignore is this injected? + + // @@ Goal: remove this dependency + + + + + + + + +/** + * Parse a string and put the result into the graph kb. + * Normal method is sync. + * Unfortunately jsdonld is currently written to need to be called async. + * Hence the mess below with executeCallback. + * @param str - The input string to parse + * @param kb - The store to use + * @param base - The base URI to use + * @param contentType - The MIME content type string for the input - defaults to text/turtle + * @param [callback] - The callback to call when the data has been loaded + */ +function parse(str, kb, base) { + var contentType = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 'text/turtle'; + var callback = arguments.length > 4 ? arguments[4] : undefined; + contentType = contentType || _types__WEBPACK_IMPORTED_MODULE_8__["TurtleContentType"]; + contentType = contentType.split(';')[0]; + + try { + if (contentType === _types__WEBPACK_IMPORTED_MODULE_8__["N3ContentType"] || contentType === _types__WEBPACK_IMPORTED_MODULE_8__["TurtleContentType"]) { + var p = Object(_n3parser__WEBPACK_IMPORTED_MODULE_3__["default"])(kb, kb, base, base, null, null, '', null); + p.loadBuf(str); + executeCallback(); + } else if (contentType === _types__WEBPACK_IMPORTED_MODULE_8__["RDFXMLContentType"]) { + var parser = new _rdfxmlparser__WEBPACK_IMPORTED_MODULE_5__["default"](kb); + parser.parse(_utils_js__WEBPACK_IMPORTED_MODULE_7__["parseXML"](str), base, kb.sym(base)); + executeCallback(); + } else if (contentType === _types__WEBPACK_IMPORTED_MODULE_8__["XHTMLContentType"]) { + Object(_rdfaparser__WEBPACK_IMPORTED_MODULE_4__["parseRDFaDOM"])(_utils_js__WEBPACK_IMPORTED_MODULE_7__["parseXML"](str, { + contentType: _types__WEBPACK_IMPORTED_MODULE_8__["XHTMLContentType"] + }), kb, base); + executeCallback(); + } else if (contentType === _types__WEBPACK_IMPORTED_MODULE_8__["HTMLContentType"]) { + Object(_rdfaparser__WEBPACK_IMPORTED_MODULE_4__["parseRDFaDOM"])(_utils_js__WEBPACK_IMPORTED_MODULE_7__["parseXML"](str, { + contentType: _types__WEBPACK_IMPORTED_MODULE_8__["HTMLContentType"] + }), kb, base); + executeCallback(); + } else if (contentType === _types__WEBPACK_IMPORTED_MODULE_8__["SPARQLUpdateContentType"]) { + // @@ we handle a subset + Object(_patch_parser__WEBPACK_IMPORTED_MODULE_6__["default"])(str, kb, base); + executeCallback(); + } else if (contentType === _types__WEBPACK_IMPORTED_MODULE_8__["JSONLDContentType"]) { + Object(_jsonldparser__WEBPACK_IMPORTED_MODULE_1__["default"])(str, kb, base, executeCallback); + } else if (contentType === _types__WEBPACK_IMPORTED_MODULE_8__["NQuadsContentType"] || contentType === _types__WEBPACK_IMPORTED_MODULE_8__["NQuadsAltContentType"]) { + var n3Parser = new n3__WEBPACK_IMPORTED_MODULE_2__["Parser"]({ + factory: _factories_extended_term_factory__WEBPACK_IMPORTED_MODULE_0__["default"] + }); + nquadCallback(null, str); + } else if (contentType === undefined) { + throw new Error("contentType is undefined"); + } else { + throw new Error("Don't know how to parse " + contentType + ' yet'); + } + } catch (e) { + executeErrorCallback(e); + } + + parse.handled = { + 'text/n3': true, + 'text/turtle': true, + 'application/rdf+xml': true, + 'application/xhtml+xml': true, + 'text/html': true, + 'application/sparql-update': true, + 'application/ld+json': true, + 'application/nquads': true, + 'application/n-quads': true + }; + + function executeCallback() { + if (callback) { + callback(null, kb); + } else { + return; + } + } + + function executeErrorCallback(e) { + if ( // TODO: Always true, what is the right behavior + contentType !== _types__WEBPACK_IMPORTED_MODULE_8__["JSONLDContentType"] || // @ts-ignore always true? + contentType !== _types__WEBPACK_IMPORTED_MODULE_8__["NQuadsContentType"] || // @ts-ignore always true? + contentType !== _types__WEBPACK_IMPORTED_MODULE_8__["NQuadsAltContentType"]) { + if (callback) { + callback(e, kb); + } else { + var e2 = new Error('' + e + ' while trying to parse <' + base + '> as ' + contentType); //@ts-ignore .cause is not a default error property + + e2.cause = e; + throw e2; + } + } + } + /* + function setJsonLdBase (doc, base) { + if (doc instanceof Array) { + return + } + if (!('@context' in doc)) { + doc['@context'] = {} + } + doc['@context']['@base'] = base + } + */ + + + function nquadCallback(err, nquads) { + if (err) { + callback(err, kb); + } + + try { + n3Parser.parse(nquads, tripleCallback); + } catch (err) { + callback(err, kb); + } + } + + function tripleCallback(err, triple) { + if (triple) { + kb.add(triple.subject, triple.predicate, triple.object, triple.graph); + } else { + callback(err, kb); + } + } +} + +/***/ }), + +/***/ "./node_modules/rdflib/esm/patch-parser.js": +/*!*************************************************!*\ + !*** ./node_modules/rdflib/esm/patch-parser.js ***! + \*************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return sparqlUpdateParser; }); +/* harmony import */ var _n3parser__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./n3parser */ "./node_modules/rdflib/esm/n3parser.js"); +/* harmony import */ var _namespace__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./namespace */ "./node_modules/rdflib/esm/namespace.js"); +// Parse a simple SPARL-Update subset syntax for patches. +// +// This parses +// WHERE {xxx} DELETE {yyy} INSERT DATA {zzz} +// (not necessarily in that order) +// as though it were the n3 +// <#query> patch:where {xxx}; patch:delete {yyy}; patch:insert {zzz}. + + +function sparqlUpdateParser(str, kb, base) { + var i, j, k; + var keywords = ['INSERT', 'DELETE', 'WHERE']; + var SQNS = Object(_namespace__WEBPACK_IMPORTED_MODULE_1__["default"])('http://www.w3.org/ns/pim/patch#'); + var p = Object(_n3parser__WEBPACK_IMPORTED_MODULE_0__["default"])(kb, kb, base, base, null, null, '', null); + var clauses = {}; + + var badSyntax = function badSyntax(uri, lines, str, i, why) { + return 'Line ' + (lines + 1) + ' of <' + uri + '>: Bad syntax:\n ' + why + '\n at: "' + str.slice(i, i + 30) + '"'; + }; // var check = function (next, last, message) { + // if (next < 0) { + // throw badSyntax(p._thisDoc, p.lines, str, j, last, message) + // } + // return next + // } + + + i = 0; + var query = kb.sym(base + '#query'); // Invent a URI for the query + + clauses['query'] = query; // A way of accessing it in its N3 model. + + while (true) { + // console.log("A Now at i = " + i) + j = p.skipSpace(str, i); + + if (j < 0) { + return clauses; + } // console.log("B After space at j= " + j) + + + if (str[j] === ';') { + i = p.skipSpace(str, j + 1); + + if (i < 0) { + return clauses; // Allow end in a + } + + j = i; + } + + var found = false; + + for (k = 0; k < keywords.length; k++) { + var key = keywords[k]; + + if (str.slice(j, j + key.length) === key) { + i = p.skipSpace(str, j + key.length); + + if (i < 0) { + throw badSyntax(p._thisDoc, p.lines, str, j + key.length, 'found EOF, needed {...} after ' + key); + } + + if ((key === 'INSERT' || key === 'DELETE') && str.slice(i, i + 4) === 'DATA') { + // Some wanted 'DATA'. Whatever + j = p.skipSpace(str, i + 4); + + if (j < 0) { + throw badSyntax(p._thisDoc, p.lines, str, i + 4, 'needed {...} after INSERT DATA ' + key); + } + + i = j; + } + + var res2 = []; + j = p.node(str, i, res2); // Parse all the complexity of the clause + + if (j < 0) { + throw badSyntax(p._thisDoc, p.lines, str, i, 'bad syntax or EOF in {...} after ' + key); + } + + clauses[key.toLowerCase()] = res2[0]; + kb.add(query, SQNS(key.toLowerCase()), res2[0]); // , kb.sym(base) + // key is the keyword and res2 has the contents + + found = true; + i = j; + } + } + + if (!found && str.slice(j, j + 7) === '@prefix') { + i = p.directive(str, j); + + if (i < 0) { + throw badSyntax(p._thisDoc, p.lines, str, i, 'bad syntax or EOF after @prefix '); + } // console.log("P before dot i= " + i) + + + i = p.checkDot(str, i); // console.log("Q after dot i= " + i) + + found = true; + } + + if (!found) { + // console.log("Bad syntax " + j) + throw badSyntax(p._thisDoc, p.lines, str, j, "Unknown syntax at start of statememt: '" + str.slice(j).slice(0, 20) + "'"); + } + } // while + // return clauses + +} + +/***/ }), + +/***/ "./node_modules/rdflib/esm/query-to-sparql.js": +/*!****************************************************!*\ + !*** ./node_modules/rdflib/esm/query-to-sparql.js ***! + \****************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return queryToSPARQL; }); +/* harmony import */ var _log__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./log */ "./node_modules/rdflib/esm/log.js"); + +function queryToSPARQL(query) { + var indent = 0; + + function getSelect(query) { + var str = addIndent() + 'SELECT '; + + for (var i = 0; i < query.vars.length; i++) { + str += query.vars[i] + ' '; + } + + str += '\n'; + return str; + } + + function getPattern(pat) { + var str = ''; + var st = pat.statements; + + for (var x in st) { + _log__WEBPACK_IMPORTED_MODULE_0__["default"].debug('Found statement: ' + st); + str += addIndent() + st[x] + '\n'; + } + + return str; + } + + function getConstraints(pat) { + var str = ''; + + for (var v in pat.constraints) { + var foo = pat.constraints[v]; + str += addIndent() + 'FILTER ( ' + foo.describe(v) + ' ) ' + '\n'; + } + + return str; + } + + function getOptionals(pat) { + var str = ''; + + for (var x = 0; x < pat.optional.length; x++) { + // alert(pat.optional.termType) + _log__WEBPACK_IMPORTED_MODULE_0__["default"].debug('Found optional query'); + str += addIndent() + 'OPTIONAL { ' + '\n'; + indent++; + str += getPattern(pat.optional[x]); + str += getConstraints(pat.optional[x]); + str += getOptionals(pat.optional[x]); + indent--; + str += addIndent() + '}' + '\n'; + } + + return str; + } + + function getWhere(pat) { + var str = addIndent() + 'WHERE \n' + '{ \n'; + indent++; + str += getPattern(pat); + str += getConstraints(pat); + str += getOptionals(pat); + indent--; + str += '}'; + return str; + } + + function addIndent() { + var str = ''; + + for (var i = 0; i < indent; i++) { + str += ' '; + } + + return str; + } + + function getSPARQL(query) { + return getSelect(query) + getWhere(query.pat); + } + + return getSPARQL(query); +} + +/***/ }), + +/***/ "./node_modules/rdflib/esm/query.js": +/*!******************************************!*\ + !*** ./node_modules/rdflib/esm/query.js ***! + \******************************************/ +/*! exports provided: Query, indexedFormulaQuery */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Query", function() { return Query; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "indexedFormulaQuery", function() { return indexedFormulaQuery; }); +/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js"); +/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _store__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./store */ "./node_modules/rdflib/esm/store.js"); +/* harmony import */ var _utils_default_graph_uri__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./utils/default-graph-uri */ "./node_modules/rdflib/esm/utils/default-graph-uri.js"); +/* harmony import */ var _log__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./log */ "./node_modules/rdflib/esm/log.js"); +/* harmony import */ var _uri__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./uri */ "./node_modules/rdflib/esm/uri.js"); + +// Matching a formula against another formula +// Assync as well as Synchronously +// +// W3C open source licence 2005. +// +// This builds on term.js, match.js (and identity.js?) +// to allow a query of a formula. +// +// Here we introduce for the first time a subclass of term: variable. +// +// SVN ID: $Id: query.js 25116 2008-11-15 16:13:48Z timbl $ +// Variable +// +// Compare with BlankNode. They are similar, but a variable +// stands for something whose value is to be returned. +// Also, users name variables and want the same name back when stuff is printed + +/* jsl:option explicit */ +// Turn on JavaScriptLint variable declaration checking + + + + +/** + * Query class, for tracking queries the user has in the UI. + */ + +var Query = function Query(name, id) { + _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, Query); + + this.pat = new _store__WEBPACK_IMPORTED_MODULE_1__["default"](); // The pattern to search for + + this.vars = []; // Used by UI code but not in query.js + // this.orderBy = [] // Not used yet + + this.name = name; + this.id = id; +}; +/** + * This function will match a pattern to the current Store + * + * The callback function is called whenever a match is found + * When fetcher is supplied this will be called to load from the web + * any new nodes as they are discovered. This will cause the query to traverse the + * graph of linked data, sometimes called "Link Following Query" + * + * @param myQuery - a knowledgebase containing a pattern to use as query + * @param callback - whenever the pattern in myQuery is met this is called with + * the new bindings as parameter + * @param fetcher? - If and only if, you want link following, give a fetcher + * which has been created for the quadstore being queried. + * @param onDone - callback when query finished + */ + +function indexedFormulaQuery(myQuery, callback, fetcher, onDone) { + /** Debug strings + */ + function bindingDebug(b) { + var str = ''; + var v; + + for (v in b) { + if (b.hasOwnProperty(v)) { + str += ' ' + v + ' -> ' + b[v]; + } + } + + return str; + } + + function bindingsDebug(nbs) { + var str = 'Bindings: '; + var i; + var n = nbs.length; + + for (i = 0; i < n; i++) { + str += bindingDebug(nbs[i][0]) + ';\n\t'; + } + + return str; + } // bindingsDebug + + /** Unification + * + * Unification finds all bindings such that when the binding is applied + * to one term it is equal to the other. + * @returns {Arrray}- a list of bindings, where a binding is an associative array + * mapping variuable to value. + */ + + + function unifyTerm(self, other, bindings, formula) { + var actual = bindings[self]; + + if (actual === undefined) { + // Not mapped + if (self.isVar) { + var b = []; + b[self] = other; + return [[b, null]]; // Match + } + + actual = self; + } + + if (!actual.complexType) { + if (formula.redirections[actual]) { + actual = formula.redirections[actual]; + } + + if (formula.redirections[other]) { + other = formula.redirections[other]; + } + + if (actual.equals(other) || actual.uri && actual.uri === _utils_default_graph_uri__WEBPACK_IMPORTED_MODULE_2__["defaultGraphURI"]) { + // Used to mean 'any graph' in a query + return [[[], null]]; + } + + return []; + } + + if (self instanceof Array) { + if (!(other instanceof Array)) { + return []; + } + + return unifyContents(self, other, bindings); + } + + throw new Error('query.js: oops - code not written yet'); // return undefined; // for lint - no jslint objects to unreachables + // return actual.unifyContents(other, bindings) + } // unifyTerm + + + function unifyContents(self, other, bindings, formula) { + var nbs2; + + if (self.length !== other.length) { + return []; // no way + } + + if (!self.length) { + return [[[], null]]; // Success + } + + var nbs = unifyTerm(self[0], other[0], bindings, formula); + + if (nbs.length === 0) { + return nbs; + } + + var res = []; + var i; + var n = nbs.length; + var nb; + var j; + var m; + var v; + var nb2; + var bindings2; + + for (i = 0; i < n; i++) { + // for each possibility from the first term + nb = nbs[i][0]; // new bindings + + bindings2 = []; + + for (v in nb) { + if (nb.hasOwnProperty(v)) { + bindings2[v] = nb[v]; // copy + } + } + + for (v in bindings) { + if (bindings.hasOwnProperty(v)) { + bindings2[v] = bindings[v]; // copy + } + } + + nbs2 = unifyContents(self.slice(1), other.slice(1), bindings2, formula); + m = nbs2.length; + + for (j = 0; j < m; j++) { + nb2 = nbs2[j][0]; // @@@@ no idea whether this is used or right + + for (v in nb) { + if (nb.hasOwnProperty(v)) { + nb2[v] = nb[v]; + } + } + + res.push([nb2, null]); + } + } + + return res; + } // unifyContents + // Matching + // + // Matching finds all bindings such that when the binding is applied + // to one term it is equal to the other term. We only match formulae. + + /** if x is not in the bindings array, return the var; otherwise, return the bindings **/ + + + function bind(x, binding) { + var y = binding[x]; + + if (y === undefined) { + return x; + } + + return y; + } // When there are OPTIONAL clauses, we must return bindings without them if none of them + // succeed. However, if any of them do succeed, we should not. (This is what branchCount() + // tracked. The problem currently is (2011/7) that when several optionals exist, and they + // all match, multiple sets of bindings are returned, each with one optional filled in.) + + + function union(a, b) { + var c = {}; + var x; + + for (x in a) { + if (a.hasOwnProperty(x)) { + c[x] = a[x]; + } + } + + for (x in b) { + if (b.hasOwnProperty(x)) { + c[x] = b[x]; + } + } + + return c; + } + + function OptionalBranchJunction(originalCallback, trunkBindings) { + this.trunkBindings = trunkBindings; + this.originalCallback = originalCallback; + this.branches = []; // this.results = []; // result[i] is an array of bindings for branch i + // this.done = {}; // done[i] means all/any results are in for branch i + // this.count = {} + + return this; + } + + OptionalBranchJunction.prototype.checkAllDone = function () { + var i; + + for (i = 0; i < this.branches.length; i++) { + if (!this.branches[i].done) { + return; + } + } + + _log__WEBPACK_IMPORTED_MODULE_3__["default"].debug('OPTIONAL BIDNINGS ALL DONE:'); + this.doCallBacks(this.branches.length - 1, this.trunkBindings); + }; // Recrursively generate the cross product of the bindings + + + OptionalBranchJunction.prototype.doCallBacks = function (b, bindings) { + var j; + + if (b < 0) { + return this.originalCallback(bindings); + } + + for (j = 0; j < this.branches[b].results.length; j++) { + this.doCallBacks(b - 1, union(bindings, this.branches[b].results[j])); + } + }; // A mandatory branch is the normal one, where callbacks + // are made immediately and no junction is needed. + // Might be useful for onFinsihed callback for query API. + + + function MandatoryBranch(callback, onDone) { + this.count = 0; + this.success = false; + this.done = false; // this.results = [] + + this.callback = callback; + this.onDone = onDone; // this.junction = junction + // junction.branches.push(this) + + return this; + } + + MandatoryBranch.prototype.reportMatch = function (bindings) { + // log.error("@@@@ query.js 1"); // @@ + this.callback(bindings); + this.success = true; + }; + + MandatoryBranch.prototype.reportDone = function () { + this.done = true; + _log__WEBPACK_IMPORTED_MODULE_3__["default"].info('Mandatory query branch finished.***'); + + if (this.onDone !== undefined) { + this.onDone(); + } + }; // An optional branch hoards its results. + + + var OptionalBranch = function OptionalBranch(junction) { + this.count = 0; + this.done = false; + this.results = []; + this.junction = junction; + junction.branches.push(this); + return this; + }; + + OptionalBranch.prototype.reportMatch = function (bindings) { + this.results.push(bindings); + }; + + OptionalBranch.prototype.reportDone = function () { + _log__WEBPACK_IMPORTED_MODULE_3__["default"].debug('Optional branch finished - results.length = ' + this.results.length); + + if (this.results.length === 0) { + // This is what optional means: if no hits, + this.results.push({}); // mimic success, but with no bindings + + _log__WEBPACK_IMPORTED_MODULE_3__["default"].debug("Optional branch FAILED - that's OK."); + } + + this.done = true; + this.junction.checkAllDone(); + }; + /** prepare -- sets the index of the item to the possible matches + * @param f - formula + * @param item - an Statement, possibly w/ vars in it + * @param bindings - Bindings so far + * @returns false if the query fails -- there are no items that match + */ + + + function prepare(f, item, bindings) { + var terms, termIndex, i, ind; + item.nvars = 0; + item.index = null; // if (!f.statements) log.warn("@@@ prepare: f is "+f) + // log.debug("Prepare: f has "+ f.statements.length) + // log.debug("Prepare: Kb size "+f.statements.length+" Preparing "+item) + + terms = [item.subject, item.predicate, item.object, item.why]; + ind = [f.subjectIndex, f.predicateIndex, f.objectIndex, f.whyIndex]; + + for (i = 0; i < 4; i++) { + var t = terms[i]; // console.log(" Prepare (" + t + ") "+(t in bindings)) + + if (t.uri && t.uri === _utils_default_graph_uri__WEBPACK_IMPORTED_MODULE_2__["defaultGraphURI"]) {// chrome:session + // console.log(' query: Ignoring slot ' + i) + } else if (t.isVar && !(bindings[t] !== undefined)) { + item.nvars++; + } else { + t = bind(terms[i], bindings); // returns the RDF binding if bound, otherwise itself + // if (terms[i]!=bind(terms[i],bindings) alert("Term: "+terms[i]+"Binding: "+bind(terms[i], bindings)) + + if (f.redirections[f.id(t)]) { + t = f.redirections[f.id(t)]; // redirect + } + + termIndex = ind[i][f.id(t)]; + + if (!termIndex) { + item.index = []; + return false; // Query line cannot match + } + + if (item.index === null || item.index.length > termIndex.length) { + // Find smallest index + item.index = termIndex; + } + } + } + + if (item.index === null) { + // All 4 are variables? + item.index = f.statements; + } + + return true; + } // prepare + + /** sorting function -- negative if self is easier **/ + // We always prefer to start with a URI to be able to browse a graph + // this is why we put off items with more variables till later. + + + function easiestQuery(self, other) { + if (self.nvars !== other.nvars) { + return self.nvars - other.nvars; + } + + return self.index.length - other.index.length; + } + + var matchIndex = 0; // index + + /** matches a pattern formula against the knowledge base, e.g. to find matches for table-view + * + * @param f - knowledge base formula + * @param g - pattern formula (may have vars) + * @param bindingsSoFar - bindings accumulated in matching to date + * @param level - spaces to indent stuff also lets you know what level of recursion you're at + * @param fetcher - function (term, requestedBy) If you want link following + * @param localCallback - function(bindings, pattern, branch) called on sucess + * @returns nothing + * + * Will fetch linked data from the web iff the knowledge base an associated source fetcher (f.fetcher) + ***/ + + var match = function match(f, g, bindingsSoFar, level, fetcher, localCallback, branch) { + _log__WEBPACK_IMPORTED_MODULE_3__["default"].debug('Match begins, Branch count now: ' + branch.count + ' for ' + branch.pattern_debug); // log.debug("match: f has "+f.statements.length+", g has "+g.statements.length) + + var pattern = g.statements; + + if (pattern.length === 0) { + // when it's satisfied all the pattern triples + _log__WEBPACK_IMPORTED_MODULE_3__["default"].debug('FOUND MATCH WITH BINDINGS:' + bindingDebug(bindingsSoFar)); + + if (g.optional.length === 0) { + branch.reportMatch(bindingsSoFar); + } else { + _log__WEBPACK_IMPORTED_MODULE_3__["default"].debug('OPTIONAL: ' + g.optional); + var junction = new OptionalBranchJunction(callback, bindingsSoFar); // @@ won't work with nested optionals? nest callbacks + + var br = []; + var b; + + for (b = 0; b < g.optional.length; b++) { + br[b] = new OptionalBranch(junction); // Allocate branches to prevent premature ending + + br[b].pattern_debug = g.optional[b]; // for diagnotics only + } + + for (b = 0; b < g.optional.length; b++) { + br[b].count = br[b].count + 1; // Count how many matches we have yet to complete + + match(f, g.optional[b], bindingsSoFar, '', fetcher, callback, br[b]); + } + } + + branch.count--; + _log__WEBPACK_IMPORTED_MODULE_3__["default"].debug('Match ends -- success , Branch count now: ' + branch.count + ' for ' + branch.pattern_debug); + return; // Success + } + + var item; + var i; + var n = pattern.length; // log.debug(level + "Match "+n+" left, bs so far:"+bindingDebug(bindingsSoFar)) + // Follow links from variables in query + + if (fetcher) { + // Fetcher is used to fetch URIs, function first term is a URI term, second is the requester + var id = 'match' + matchIndex++; + + var fetchResource = function fetchResource(requestedTerm, id) { + var docuri = requestedTerm.uri.split('#')[0]; + fetcher.nowOrWhenFetched(docuri, undefined, function (ok, body, xhr) { + if (!ok) { + console.log('Error following link to <' + requestedTerm.uri + '> in query: ' + body); + } + + match(f, g, bindingsSoFar, level, fetcher, // match not match2 to look up any others necessary. + localCallback, branch); + }); + }; + + for (i = 0; i < n; i++) { + item = pattern[i]; // for each of the triples in the query + + if (bindingsSoFar[item.subject] !== undefined && bindingsSoFar[item.subject].uri && fetcher && fetcher.getState(Object(_uri__WEBPACK_IMPORTED_MODULE_4__["docpart"])(bindingsSoFar[item.subject].uri)) === 'unrequested') { + // fetch the subject info and return to id + fetchResource(bindingsSoFar[item.subject], id); + return; // only look up one per line this time, but we will come back again though match + } + + if (bindingsSoFar[item.object] !== undefined && bindingsSoFar[item.object].uri && fetcher && fetcher.getState(Object(_uri__WEBPACK_IMPORTED_MODULE_4__["docpart"])(bindingsSoFar[item.object].uri)) === 'unrequested') { + fetchResource(bindingsSoFar[item.object], id); + return; + } + } + } // if fetcher + + + match2(f, g, bindingsSoFar, level, fetcher, localCallback, branch); + }; // match + + + var constraintsSatisfied = function constraintsSatisfied(bindings, constraints) { + var res = true; + var x; + var test; + + for (x in bindings) { + if (bindings.hasOwnProperty(x)) { + if (constraints[x]) { + test = constraints[x].test; + + if (test && !test(bindings[x])) { + res = false; + } + } + } + } + + return res; + }; + /** match2 -- stuff after the fetch **/ + + + var match2 = function match2(f, g, bindingsSoFar, level, fetcher, callback, branch) { + // post fetch + var pattern = g.statements; + var n = pattern.length; + var i; + var k; + var nk; + var v; + var bindings2; + var newBindings1; + var item; + + for (i = 0; i < n; i++) { + // For each statement left in the query, run prepare + item = pattern[i]; // log.info('match2: item=' + item + ', bindingsSoFar=' + bindingDebug(bindingsSoFar)) + + prepare(f, item, bindingsSoFar); // if (item.index) console.log(' item.index.length ' + item.index.length) + } + + pattern.sort(easiestQuery); + item = pattern[0]; // log.debug("Sorted pattern:\n"+pattern) + + var rest = f.formula(); + rest.optional = g.optional; + rest.constraints = g.constraints; + rest.statements = pattern.slice(1); // No indexes: we will not query g. + + _log__WEBPACK_IMPORTED_MODULE_3__["default"].debug(level + 'match2 searching ' + item.index.length + ' for ' + item + '; bindings so far=' + bindingDebug(bindingsSoFar)); // var results = [] + + var c; + var nc = item.index.length; + var nbs1; + var st; + var onward = 0; // var x + + for (c = 0; c < nc; c++) { + // For each candidate statement + st = item.index[c]; // for each statement in the item's index, spawn a new match with that binding + + nbs1 = unifyContents([item.subject, item.predicate, item.object, item.why], [st.subject, st.predicate, st.object, st.why], bindingsSoFar, f); + _log__WEBPACK_IMPORTED_MODULE_3__["default"].info(level + ' From first: ' + nbs1.length + ': ' + bindingsDebug(nbs1)); + nk = nbs1.length; // branch.count += nk + // log.debug("Branch count bumped "+nk+" to: "+branch.count) + + for (k = 0; k < nk; k++) { + // For each way that statement binds + bindings2 = []; + newBindings1 = nbs1[k][0]; + + if (!constraintsSatisfied(newBindings1, g.constraints)) { + // branch.count-- + _log__WEBPACK_IMPORTED_MODULE_3__["default"].debug('Branch count CS: ' + branch.count); + } else { + for (v in newBindings1) { + if (newBindings1.hasOwnProperty(v)) { + bindings2[v] = newBindings1[v]; // copy + } + } + + for (v in bindingsSoFar) { + if (bindingsSoFar.hasOwnProperty(v)) { + bindings2[v] = bindingsSoFar[v]; // copy + } + } + + branch.count++; // Count how many matches we have yet to complete + + onward++; + match(f, rest, bindings2, level + ' ', fetcher, callback, branch); // call match + } + } + } + + branch.count--; + + if (onward === 0) { + _log__WEBPACK_IMPORTED_MODULE_3__["default"].debug('Match2 fails completely on ' + item); + } + + _log__WEBPACK_IMPORTED_MODULE_3__["default"].debug('Match2 ends, Branch count: ' + branch.count + ' for ' + branch.pattern_debug); + + if (branch.count === 0) { + _log__WEBPACK_IMPORTED_MODULE_3__["default"].debug('Branch finished.'); + branch.reportDone(); + } + }; // match2 + // ////////////////////////// Body of query() /////////////////////// + + + var f = this; + _log__WEBPACK_IMPORTED_MODULE_3__["default"].debug('Query on ' + this.statements.length); + var trunck = new MandatoryBranch(callback, onDone); + trunck.count++; // count one branch to complete at the moment + + if (myQuery.sync) { + match(f, myQuery.pat, myQuery.pat.initBindings, '', fetcher, callback, trunck); + } else { + // Give up thread: Allow other activities to run + setTimeout(function () { + match(f, myQuery.pat, myQuery.pat.initBindings, '', fetcher, callback, trunck); + }, 0); + } // returns nothing; callback does the work + +} // query + +/***/ }), + +/***/ "./node_modules/rdflib/esm/rdfaparser.js": +/*!***********************************************!*\ + !*** ./node_modules/rdflib/esm/rdfaparser.js ***! + \***********************************************/ +/*! exports provided: default, parseRDFaDOM */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return RDFaProcessor; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parseRDFaDOM", function() { return parseRDFaDOM; }); +/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js"); +/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js"); +/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__); +/* harmony import */ var _blank_node__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./blank-node */ "./node_modules/rdflib/esm/blank-node.js"); +/* harmony import */ var _literal__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./literal */ "./node_modules/rdflib/esm/literal.js"); +/* harmony import */ var _named_node__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./named-node */ "./node_modules/rdflib/esm/named-node.js"); +/* harmony import */ var _uri__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./uri */ "./node_modules/rdflib/esm/uri.js"); +/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./utils-js */ "./node_modules/rdflib/esm/utils-js.js"); +/* harmony import */ var _factories_canonical_data_factory__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./factories/canonical-data-factory */ "./node_modules/rdflib/esm/factories/canonical-data-factory.js"); + + +// RDFa Parser for rdflib.js +// Originally by: Alex Milowski +// From https://github.com/alexmilowski/green-turtle +// Converted: timbl 2015-08-25 not yet working +// Added wrapper: csarven 2016-05-09 working +// RDFaProcessor.prototype = new Object() // Was URIResolver +// RDFaProcessor.prototype.constructor=RDFaProcessor +// options.base = base URI not really an option, shopuld always be set. +// + + + + + + + +if (typeof Node === 'undefined') { + // @@@@@@ Global. Interface to xmldom. + var Node = { + ELEMENT_NODE: 1, + ATTRIBUTE_NODE: 2, + TEXT_NODE: 3, + CDATA_SECTION_NODE: 4, + ENTITY_REFERENCE_NODE: 5, + ENTITY_NODE: 6, + PROCESSING_INSTRUCTION_NODE: 7, + COMMENT_NODE: 8, + DOCUMENT_NODE: 9, + DOCUMENT_TYPE_NODE: 10, + DOCUMENT_FRAGMENT_NODE: 11, + NOTATION_NODE: 12 + }; +} + +var RDFaProcessor = /*#__PURE__*/function () { + function RDFaProcessor(kb, options) { + _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, RDFaProcessor); + + this.options = options || {}; + this.kb = kb; + this.target = options.target || { + graph: { + subjects: {}, + prefixes: {}, + terms: {} + } + }; // XXX: Added to track bnodes + + this.blankNodes = []; // XXX: Added for normalisation + + this.htmlOptions = { + 'selfClosing': 'br img input area base basefont col colgroup source wbr isindex link meta param hr' + }; + this.theOne = '_:' + new Date().getTime(); + this.language = null; + this.vocabulary = null; + this.blankCounter = 0; + this.langAttributes = [{ + namespaceURI: 'http://www.w3.org/XML/1998/namespace', + localName: 'lang' + }]; + this.inXHTMLMode = false; + this.absURIRE = /[\w\_\-]+:\S+/; + this.finishedHandlers = []; + this.init(); + } + + _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default()(RDFaProcessor, [{ + key: "addTriple", + value: function addTriple(origin, subject, predicate, object) { + var su, ob, pr, or; + + if (typeof subject === 'undefined') { + su = _factories_canonical_data_factory__WEBPACK_IMPORTED_MODULE_7__["default"].namedNode(this.options.base); + } else { + su = this.toRDFNodeObject(subject); + } + + pr = this.toRDFNodeObject(predicate); + ob = this.toRDFNodeObject(object); + or = _factories_canonical_data_factory__WEBPACK_IMPORTED_MODULE_7__["default"].namedNode(this.options.base); // console.log('Adding { ' + su + ' ' + pr + ' ' + ob + ' ' + or + ' }') + + this.kb.add(su, pr, ob, or); + } + }, { + key: "ancestorPath", + value: function ancestorPath(node) { + var path = ''; + + while (node && node.nodeType !== Node.DOCUMENT_NODE) { + path = '/' + node.localName + path; + node = node.parentNode; + } + + return path; + } + }, { + key: "copyMappings", + value: function copyMappings(mappings) { + var newMappings = {}; + + for (var k in mappings) { + newMappings[k] = mappings[k]; + } + + return newMappings; + } + }, { + key: "copyProperties", + value: function copyProperties() {} + }, { + key: "deriveDateTimeType", + value: function deriveDateTimeType(value) { + for (var i = 0; i < RDFaProcessor.dateTimeTypes.length; i++) { + // console.log("Checking "+value+" against "+RDFaProcessor.dateTimeTypes[i].type) + var matched = RDFaProcessor.dateTimeTypes[i].pattern.exec(value); + + if (matched && matched[0].length === value.length) { + // console.log("Matched!") + return RDFaProcessor.dateTimeTypes[i].type; + } + } + + return null; + } + }, { + key: "init", + value: function init() {} + }, { + key: "newBlankNode", + value: function newBlankNode() { + this.blankCounter++; + return '_:' + this.blankCounter; + } + }, { + key: "newSubjectOrigin", + value: function newSubjectOrigin(origin, subject) {} + }, { + key: "parseCURIE", + value: function parseCURIE(value, prefixes, base) { + var colon = value.indexOf(':'); + var uri; + + if (colon >= 0) { + var prefix = value.substring(0, colon); + + if (prefix === '') { + // default prefix + uri = prefixes['']; + return uri ? uri + value.substring(colon + 1) : null; + } else if (prefix === '_') { + // blank node + return '_:' + value.substring(colon + 1); + } else if (RDFaProcessor.NCNAME.test(prefix)) { + uri = prefixes[prefix]; + + if (uri) { + return uri + value.substring(colon + 1); + } + } + } + + return null; + } + }, { + key: "parseCURIEOrURI", + value: function parseCURIEOrURI(value, prefixes, base) { + var curie = this.parseCURIE(value, prefixes, base); + + if (curie) { + return curie; + } + + return this.resolveAndNormalize(base, value); + } + }, { + key: "parsePredicate", + value: function parsePredicate(value, defaultVocabulary, terms, prefixes, base, ignoreTerms) { + if (value === '') { + return null; + } + + var predicate = this.parseTermOrCURIEOrAbsURI(value, defaultVocabulary, ignoreTerms ? null : terms, prefixes, base); + + if (predicate && predicate.indexOf('_:') === 0) { + return null; + } + + return predicate; + } + }, { + key: "parsePrefixMappings", + value: function parsePrefixMappings(str, target) { + var values = this.tokenize(str); + var prefix = null; // var uri = null + + for (var i = 0; i < values.length; i++) { + if (values[i][values[i].length - 1] === ':') { + prefix = values[i].substring(0, values[i].length - 1); + } else if (prefix) { + target[prefix] = this.options.base ? _uri__WEBPACK_IMPORTED_MODULE_5__["join"](values[i], this.options.base) : values[i]; + prefix = null; + } + } + } + }, { + key: "parseSafeCURIEOrCURIEOrURI", + value: function parseSafeCURIEOrCURIEOrURI(value, prefixes, base) { + value = this.trim(value); + + if (value.charAt(0) === '[' && value.charAt(value.length - 1) === ']') { + value = value.substring(1, value.length - 1); + value = value.trim(value); + + if (value.length === 0) { + return null; + } + + if (value === '_:') { + // the one node + return this.theOne; + } + + return this.parseCURIE(value, prefixes, base); + } else { + return this.parseCURIEOrURI(value, prefixes, base); + } + } + }, { + key: "parseTermOrCURIEOrAbsURI", + value: function parseTermOrCURIEOrAbsURI(value, defaultVocabulary, terms, prefixes, base) { + // alert("Parsing "+value+" with default vocab "+defaultVocabulary) + value = this.trim(value); + var curie = this.parseCURIE(value, prefixes, base); + + if (curie) { + return curie; + } else if (terms) { + if (defaultVocabulary && !this.absURIRE.exec(value)) { + return defaultVocabulary + value; + } + + var term = terms[value]; + + if (term) { + return term; + } + + var lcvalue = value.toLowerCase(); + term = terms[lcvalue]; + + if (term) { + return term; + } + } + + if (this.absURIRE.exec(value)) { + return this.resolveAndNormalize(base, value); + } + + return null; + } + }, { + key: "parseTermOrCURIEOrURI", + value: function parseTermOrCURIEOrURI(value, defaultVocabulary, terms, prefixes, base) { + // alert("Parsing "+value+" with default vocab "+defaultVocabulary) + value = this.trim(value); + var curie = this.parseCURIE(value, prefixes, base); + + if (curie) { + return curie; + } else { + var term = terms[value]; + + if (term) { + return term; + } + + var lcvalue = value.toLowerCase(); + term = terms[lcvalue]; + + if (term) { + return term; + } + + if (defaultVocabulary && !this.absURIRE.exec(value)) { + return defaultVocabulary + value; + } + } + + return this.resolveAndNormalize(base, value); + } + }, { + key: "parseURI", + value: function parseURI(uri) { + return uri; // We just use strings as URIs, not objects now. + } + }, { + key: "process", + value: function process(node, options) { + /* + if (!window.console) { + window.console = { log: function() {} } + } */ + options = options || {}; + var base; + + if (node.nodeType === Node.DOCUMENT_NODE) { + if (node.baseURI && !options.baseURI) { + options.baseURI = node.baseURI; // be defensive as DOM implementations vary + } + + base = node.baseURI; + node = node.documentElement; + + if (!node.baseURI) { + node.baseURI = base; + } + + this.setContext(node); + } else if (node.parentNode.nodeType === Node.DOCUMENT_NODE) { + this.setContext(node); + } + + var queue = []; // Fix for Firefox that includes the hash in the base URI + + var removeHash = function removeHash(baseURI) { + // Fix for undefined baseURI property + if (!baseURI && options && options.baseURI) { + return options.baseURI; + } + + var hash = baseURI.indexOf('#'); + + if (hash >= 0) { + baseURI = baseURI.substring(0, hash); + } + + if (options && options.baseURIMap) { + baseURI = options.baseURIMap(baseURI); + } + + return baseURI; + }; + + queue.push({ + current: node, + context: this.push(null, removeHash(node.baseURI)) + }); + + while (queue.length > 0) { + var item = queue.shift(); + + if (item.parent) { + // Sequence Step 14: list triple generation + if (item.context.parent && item.context.parent.listMapping === item.listMapping) { + // Skip a child context with exactly the same mapping + continue; + } // console.log("Generating lists for "+item.subject+", tag "+item.parent.localName) + + + for (var _predicate in item.listMapping) { + var list = item.listMapping[_predicate]; + + if (list.length === 0) { + this.addTriple(item.parent, item.subject, _predicate, { + type: RDFaProcessor.objectURI, + value: 'http://www.w3.org/1999/02/22-rdf-syntax-ns#nil' + }); + continue; + } + + var bnodes = []; + + for (var _i = 0; _i < list.length; _i++) { + bnodes.push(this.newBlankNode()); // this.newSubject(item.parent,bnodes[i]) + } + + for (var _i2 = 0; _i2 < bnodes.length; _i2++) { + this.addTriple(item.parent, bnodes[_i2], 'http://www.w3.org/1999/02/22-rdf-syntax-ns#first', list[_i2]); + this.addTriple(item.parent, bnodes[_i2], 'http://www.w3.org/1999/02/22-rdf-syntax-ns#rest', { + type: RDFaProcessor.objectURI, + value: _i2 + 1 < bnodes.length ? bnodes[_i2 + 1] : 'http://www.w3.org/1999/02/22-rdf-syntax-ns#nil' + }); + } + + this.addTriple(item.parent, item.subject, _predicate, { + type: RDFaProcessor.objectURI, + value: bnodes[0] + }); + } + + continue; + } + + var current = item.current; + var context = item.context; // console.log("Tag: "+current.localName+", listMapping="+JSON.stringify(context.listMapping)) + // Sequence Step 1 + + var skip = false; + var newSubject = null; + var currentObjectResource = null; + var typedResource = null; + var prefixes = context.prefixes; + var prefixesCopied = false; + var incomplete = []; + var listMapping = context.listMapping; + var listMappingDifferent = !context.parent; + var language = context.language; + var vocabulary = context.vocabulary; // TODO: the "base" element may be used for HTML+RDFa 1.1 + + base = this.parseURI(removeHash(current.baseURI)); + current.item = null; // Sequence Step 2: set the default vocabulary + + var vocabAtt = current.getAttributeNode('vocab'); + + if (vocabAtt) { + var value = this.trim(vocabAtt.value); + + if (value.length > 0) { + vocabulary = value; + var baseSubject = base.spec; // this.newSubject(current,baseSubject) + + this.addTriple(current, baseSubject, 'http://www.w3.org/ns/rdfa#usesVocabulary', { + type: RDFaProcessor.objectURI, + value: vocabulary + }); + } else { + vocabulary = this.vocabulary; + } + } // Sequence Step 3: IRI mappings + // handle xmlns attributes + + + for (var i = 0; i < current.attributes.length; i++) { + var att = current.attributes[i]; // if (att.namespaceURI=="http://www.w3.org/2000/xmlns/") { + + if (att.nodeName.charAt(0) === 'x' && att.nodeName.indexOf('xmlns:') === 0) { + if (!prefixesCopied) { + prefixes = this.copyMappings(prefixes); + prefixesCopied = true; + } + + var prefix = att.nodeName.substring(6); // TODO: resolve relative? + + var ref = RDFaProcessor.trim(att.value); + prefixes[prefix] = this.options.base ? _uri__WEBPACK_IMPORTED_MODULE_5__["join"](ref, this.options.base) : ref; + } + } // Handle prefix mappings (@prefix) + + + var prefixAtt = current.getAttributeNode('prefix'); + + if (prefixAtt) { + if (!prefixesCopied) { + prefixes = this.copyMappings(prefixes); + prefixesCopied = true; + } + + this.parsePrefixMappings(prefixAtt.value, prefixes); + } // Sequence Step 4: language + + + var xmlLangAtt = null; + + for (var _i3 = 0; !xmlLangAtt && _i3 < this.langAttributes.length; _i3++) { + xmlLangAtt = current.getAttributeNodeNS(this.langAttributes[_i3].namespaceURI, this.langAttributes[_i3].localName); + } + + if (xmlLangAtt) { + var _value = RDFaProcessor.trim(xmlLangAtt.value); + + if (_value.length > 0) { + language = _value; + } else { + language = null; + } + } + + var relAtt = current.getAttributeNode('rel'); + var revAtt = current.getAttributeNode('rev'); + var typeofAtt = current.getAttributeNode('typeof'); + var propertyAtt = current.getAttributeNode('property'); + var datatypeAtt = current.getAttributeNode('datatype'); + var datetimeAtt = this.inHTMLMode ? current.getAttributeNode('datetime') : null; + var contentAtt = current.getAttributeNode('content'); + var aboutAtt = current.getAttributeNode('about'); + var srcAtt = current.getAttributeNode('src'); + var resourceAtt = current.getAttributeNode('resource'); + var hrefAtt = current.getAttributeNode('href'); + var inlistAtt = current.getAttributeNode('inlist'); + var relAttPredicates = []; + var predicate, values; + + if (relAtt) { + values = this.tokenize(relAtt.value); + + for (var _i4 = 0; _i4 < values.length; _i4++) { + predicate = this.parsePredicate(values[_i4], vocabulary, context.terms, prefixes, base, this.inHTMLMode && propertyAtt !== null); + + if (predicate) { + relAttPredicates.push(predicate); + } + } + } + + var revAttPredicates = []; + + if (revAtt) { + values = this.tokenize(revAtt.value); + + for (var _i5 = 0; _i5 < values.length; _i5++) { + predicate = this.parsePredicate(values[_i5], vocabulary, context.terms, prefixes, base, this.inHTMLMode && propertyAtt); + + if (predicate) { + revAttPredicates.push(predicate); + } + } + } // Section 3.1, bullet 7 + + + if (this.inHTMLMode && (relAtt || revAtt) && propertyAtt) { + if (relAttPredicates.length === 0) { + relAtt = null; + } + + if (revAttPredicates.length === 0) { + revAtt = null; + } + } + + if (relAtt || revAtt) { + // Sequence Step 6: establish new subject and value + if (aboutAtt) { + newSubject = this.parseSafeCURIEOrCURIEOrURI(aboutAtt.value, prefixes, base); + } + + if (typeofAtt) { + typedResource = newSubject; + } + + if (!newSubject) { + if (current.parentNode.nodeType === Node.DOCUMENT_NODE) { + newSubject = removeHash(current.baseURI); + } else if (context.parentObject) { + // TODO: Verify: If the xml:base has been set and the parentObject is the baseURI of the parent, then the subject needs to be the new base URI + newSubject = removeHash(current.parentNode.baseURI) === context.parentObject ? removeHash(current.baseURI) : context.parentObject; + } + } + + if (resourceAtt) { + currentObjectResource = this.parseSafeCURIEOrCURIEOrURI(resourceAtt.value, prefixes, base); + } + + if (!currentObjectResource) { + if (hrefAtt) { + currentObjectResource = this.resolveAndNormalize(base, encodeURI(hrefAtt.value)); + } else if (srcAtt) { + currentObjectResource = this.resolveAndNormalize(base, encodeURI(srcAtt.value)); + } else if (typeofAtt && !aboutAtt && !(this.inXHTMLMode && (current.localName === 'head' || current.localName === 'body'))) { + currentObjectResource = this.newBlankNode(); + } + } + + if (typeofAtt && !aboutAtt && this.inXHTMLMode && (current.localName === 'head' || current.localName === 'body')) { + typedResource = newSubject; + } else if (typeofAtt && !aboutAtt) { + typedResource = currentObjectResource; + } + } else if (propertyAtt && !contentAtt && !datatypeAtt) { + // Sequence Step 5.1: establish a new subject + if (aboutAtt) { + newSubject = this.parseSafeCURIEOrCURIEOrURI(aboutAtt.value, prefixes, base); + + if (typeofAtt) { + typedResource = newSubject; + } + } + + if (!newSubject && current.parentNode.nodeType === Node.DOCUMENT_NODE) { + newSubject = removeHash(current.baseURI); + + if (typeofAtt) { + typedResource = newSubject; + } + } else if (!newSubject && context.parentObject) { + // TODO: Verify: If the xml:base has been set and the parentObject is the baseURI of the parent, then the subject needs to be the new base URI + newSubject = removeHash(current.parentNode.baseURI) === context.parentObject ? removeHash(current.baseURI) : context.parentObject; + } + + if (typeofAtt && !typedResource) { + if (resourceAtt) { + typedResource = this.parseSafeCURIEOrCURIEOrURI(resourceAtt.value, prefixes, base); + } + + if (!typedResource && hrefAtt) { + typedResource = this.resolveAndNormalize(base, encodeURI(hrefAtt.value)); + } + + if (!typedResource && srcAtt) { + typedResource = this.resolveAndNormalize(base, encodeURI(srcAtt.value)); + } + + if (!typedResource && (this.inXHTMLMode || this.inHTMLMode) && (current.localName === 'head' || current.localName === 'body')) { + typedResource = newSubject; + } + + if (!typedResource) { + typedResource = this.newBlankNode(); + } + + currentObjectResource = typedResource; + } // console.log(current.localName+", newSubject="+newSubject+", typedResource="+typedResource+", currentObjectResource="+currentObjectResource) + + } else { + // Sequence Step 5.2: establish a new subject + if (aboutAtt) { + newSubject = this.parseSafeCURIEOrCURIEOrURI(aboutAtt.value, prefixes, base); + } + + if (!newSubject && resourceAtt) { + newSubject = this.parseSafeCURIEOrCURIEOrURI(resourceAtt.value, prefixes, base); + } + + if (!newSubject && hrefAtt) { + newSubject = this.resolveAndNormalize(base, encodeURI(hrefAtt.value)); + } + + if (!newSubject && srcAtt) { + newSubject = this.resolveAndNormalize(base, encodeURI(srcAtt.value)); + } + + if (!newSubject) { + if (current.parentNode.nodeType === Node.DOCUMENT_NODE) { + newSubject = removeHash(current.baseURI); + } else if ((this.inXHTMLMode || this.inHTMLMode) && (current.localName === 'head' || current.localName === 'body')) { + newSubject = removeHash(current.parentNode.baseURI) === context.parentObject ? removeHash(current.baseURI) : context.parentObject; + } else if (typeofAtt) { + newSubject = this.newBlankNode(); + } else if (context.parentObject) { + // TODO: Verify: If the xml:base has been set and the parentObject is the baseURI of the parent, then the subject needs to be the new base URI + newSubject = removeHash(current.parentNode.baseURI) === context.parentObject ? removeHash(current.baseURI) : context.parentObject; + + if (!propertyAtt) { + skip = true; + } + } + } + + if (typeofAtt) { + typedResource = newSubject; + } + } // console.log(current.tagName+": newSubject="+newSubject+", currentObjectResource="+currentObjectResource+", typedResource="+typedResource+", skip="+skip) + // var rdfaData = null + + + if (newSubject) { + // this.newSubject(current,newSubject) + if (aboutAtt || resourceAtt || typedResource) { + var id = newSubject; + + if (typeofAtt && !aboutAtt && !resourceAtt && currentObjectResource) { + id = currentObjectResource; + } // console.log("Setting data attribute for "+current.localName+" for subject "+id) + + + this.newSubjectOrigin(current, id); + } + } // Sequence Step 7: generate type triple + + + if (typedResource) { + values = this.tokenize(typeofAtt.value); + + for (var _i6 = 0; _i6 < values.length; _i6++) { + var object = this.parseTermOrCURIEOrAbsURI(values[_i6], vocabulary, context.terms, prefixes, base); + + if (object) { + this.addTriple(current, typedResource, RDFaProcessor.typeURI, { + type: RDFaProcessor.objectURI, + value: object + }); + } + } + } // Sequence Step 8: new list mappings if there is a new subject + // console.log("Step 8: newSubject="+newSubject+", context.parentObject="+context.parentObject) + + + if (newSubject && newSubject !== context.parentObject) { + // console.log("Generating new list mapping for "+newSubject) + listMapping = {}; + listMappingDifferent = true; + } // Sequence Step 9: generate object triple + + + if (currentObjectResource) { + if (relAtt && inlistAtt) { + for (var _i7 = 0; _i7 < relAttPredicates.length; _i7++) { + var _list = listMapping[relAttPredicates[_i7]]; + + if (!_list) { + _list = []; + listMapping[relAttPredicates[_i7]] = _list; + } + + _list.push({ + type: RDFaProcessor.objectURI, + value: currentObjectResource + }); + } + } else if (relAtt) { + for (var _i8 = 0; _i8 < relAttPredicates.length; _i8++) { + this.addTriple(current, newSubject, relAttPredicates[_i8], { + type: RDFaProcessor.objectURI, + value: currentObjectResource + }); + } + } + + if (revAtt) { + for (var _i9 = 0; _i9 < revAttPredicates.length; _i9++) { + this.addTriple(current, currentObjectResource, revAttPredicates[_i9], { + type: RDFaProcessor.objectURI, + value: newSubject + }); + } + } + } else { + // Sequence Step 10: incomplete triples + if (newSubject && !currentObjectResource && (relAtt || revAtt)) { + currentObjectResource = this.newBlankNode(); // alert(current.tagName+": generated blank node, newSubject="+newSubject+" currentObjectResource="+currentObjectResource) + } + + if (relAtt && inlistAtt) { + for (var _i10 = 0; _i10 < relAttPredicates.length; _i10++) { + var _list2 = listMapping[relAttPredicates[_i10]]; + + if (!_list2) { + _list2 = []; + listMapping[predicate] = _list2; + } // console.log("Adding incomplete list for "+predicate) + + + incomplete.push({ + predicate: relAttPredicates[_i10], + list: _list2 + }); + } + } else if (relAtt) { + for (var _i11 = 0; _i11 < relAttPredicates.length; _i11++) { + incomplete.push({ + predicate: relAttPredicates[_i11], + forward: true + }); + } + } + + if (revAtt) { + for (var _i12 = 0; _i12 < revAttPredicates.length; _i12++) { + incomplete.push({ + predicate: revAttPredicates[_i12], + forward: false + }); + } + } + } // Step 11: Current property values + + + if (propertyAtt) { + var datatype = null; + var content = null; + + if (datatypeAtt) { + datatype = datatypeAtt.value === '' ? RDFaProcessor.PlainLiteralURI : this.parseTermOrCURIEOrAbsURI(datatypeAtt.value, vocabulary, context.terms, prefixes, base); + + if (datetimeAtt && !contentAtt) { + content = datetimeAtt.value; + } else { + content = datatype === RDFaProcessor.XMLLiteralURI || datatype === RDFaProcessor.HTMLLiteralURI ? null : contentAtt ? contentAtt.value : current.textContent; + } + } else if (contentAtt) { + datatype = RDFaProcessor.PlainLiteralURI; + content = contentAtt.value; + } else if (datetimeAtt) { + content = datetimeAtt.value; + datatype = RDFaProcessor.deriveDateTimeType(content); + + if (!datatype) { + datatype = RDFaProcessor.PlainLiteralURI; + } + } else if (!relAtt && !revAtt) { + if (resourceAtt) { + content = this.parseSafeCURIEOrCURIEOrURI(resourceAtt.value, prefixes, base); + } + + if (!content && hrefAtt) { + content = this.resolveAndNormalize(base, encodeURI(hrefAtt.value)); + } else if (!content && srcAtt) { + content = this.resolveAndNormalize(base, encodeURI(srcAtt.value)); + } + + if (content) { + datatype = RDFaProcessor.objectURI; + } + } + + if (!datatype) { + if (typeofAtt && !aboutAtt) { + datatype = RDFaProcessor.objectURI; + content = typedResource; + } else { + content = current.textContent; + + if (this.inHTMLMode && current.localName === 'time') { + datatype = RDFaProcessor.deriveDateTimeType(content); + } + + if (!datatype) { + datatype = RDFaProcessor.PlainLiteralURI; + } + } + } + + values = this.tokenize(propertyAtt.value); + + for (var _i13 = 0; _i13 < values.length; _i13++) { + var _predicate2 = this.parsePredicate(values[_i13], vocabulary, context.terms, prefixes, base); + + if (_predicate2) { + if (inlistAtt) { + var _list3 = listMapping[_predicate2]; + + if (!_list3) { + _list3 = []; + listMapping[_predicate2] = _list3; + } + + _list3.push(datatype === RDFaProcessor.XMLLiteralURI || datatype === RDFaProcessor.HTMLLiteralURI ? { + type: datatype, + value: current.childNodes + } : { + type: datatype || RDFaProcessor.PlainLiteralURI, + value: content, + language: language + }); + } else { + if (datatype === RDFaProcessor.XMLLiteralURI || datatype === RDFaProcessor.HTMLLiteralURI) { + this.addTriple(current, newSubject, _predicate2, { + type: datatype, + value: current.childNodes + }); + } else { + this.addTriple(current, newSubject, _predicate2, { + type: datatype || RDFaProcessor.PlainLiteralURI, + value: content, + language: language + }); // console.log(newSubject+" "+predicate+"="+content) + } + } + } + } + } // Sequence Step 12: complete incomplete triples with new subject + + + if (newSubject && !skip) { + for (var _i14 = 0; _i14 < context.incomplete.length; _i14++) { + if (context.incomplete[_i14].list) { + // console.log("Adding subject "+newSubject+" to list for "+context.incomplete[i].predicate) + // TODO: it is unclear what to do here + context.incomplete[_i14].list.push({ + type: RDFaProcessor.objectURI, + value: newSubject + }); + } else if (context.incomplete[_i14].forward) { + // console.log(current.tagName+": completing forward triple "+context.incomplete[i].predicate+" with object="+newSubject) + this.addTriple(current, context.subject, context.incomplete[_i14].predicate, { + type: RDFaProcessor.objectURI, + value: newSubject + }); + } else { + // console.log(current.tagName+": completing reverse triple with object="+context.subject) + this.addTriple(current, newSubject, context.incomplete[_i14].predicate, { + type: RDFaProcessor.objectURI, + value: context.subject + }); + } + } + } + + var childContext = null; + var listSubject = newSubject; + + if (skip) { + // TODO: should subject be null? + childContext = this.push(context, context.subject); // TODO: should the entObject be passed along? If not, then intermediary children will keep properties from being associated with incomplete triples. + // TODO: Verify: if the current baseURI has changed and the parentObject is the parent's base URI, then the baseURI should change + + childContext.parentObject = removeHash(current.parentNode.baseURI) === context.parentObject ? removeHash(current.baseURI) : context.parentObject; + childContext.incomplete = context.incomplete; + childContext.language = language; + childContext.prefixes = prefixes; + childContext.vocabulary = vocabulary; + } else { + childContext = this.push(context, newSubject); + childContext.parentObject = currentObjectResource || newSubject || context.subject; + childContext.prefixes = prefixes; + childContext.incomplete = incomplete; + + if (currentObjectResource) { + // console.log("Generating new list mapping for "+currentObjectResource) + listSubject = currentObjectResource; + listMapping = {}; + listMappingDifferent = true; + } + + childContext.listMapping = listMapping; + childContext.language = language; + childContext.vocabulary = vocabulary; + } + + if (listMappingDifferent) { + // console.log("Pushing list parent "+current.localName) + queue.unshift({ + parent: current, + context: context, + subject: listSubject, + listMapping: listMapping + }); + } + + for (var child = current.lastChild; child; child = child.previousSibling) { + if (child.nodeType === Node.ELEMENT_NODE) { + // console.log("Pushing child "+child.localName) + // child.baseURI = current.baseURI + queue.unshift({ + current: child, + context: childContext + }); + } + } + } + + if (this.inHTMLMode) { + this.copyProperties(); + } + + for (var _i15 = 0; _i15 < this.finishedHandlers.length; _i15++) { + this.finishedHandlers[_i15](node); + } + } + }, { + key: "push", + value: function push(parent, subject) { + return { + parent: parent, + subject: subject || (parent ? parent.subject : null), + parentObject: null, + incomplete: [], + listMapping: parent ? parent.listMapping : {}, + language: parent ? parent.language : this.language, + prefixes: parent ? parent.prefixes : this.target.graph.prefixes, + terms: parent ? parent.terms : this.target.graph.terms, + vocabulary: parent ? parent.vocabulary : this.vocabulary + }; + } + }, { + key: "resolveAndNormalize", + value: function resolveAndNormalize(base, uri) { + // console.log("Joining " + uri + " to " + base + " making " + Uri.join(uri, base)) + return _uri__WEBPACK_IMPORTED_MODULE_5__["join"](uri, base); // @@ normalize? + } + }, { + key: "setContext", + value: function setContext(node) { + // We only recognized XHTML+RDFa 1.1 if the version is set propertyly + if (node.localName === 'html' && node.getAttribute('version') === 'XHTML+RDFa 1.1') { + this.setXHTMLContext(); + } else if (node.localName === 'html' || node.namespaceURI === 'http://www.w3.org/1999/xhtml') { + if (typeof document !== 'undefined' && document.doctype) { + if (document.doctype.publicId === '-//W3C//DTD XHTML+RDFa 1.0//EN' && document.doctype.systemId === 'http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd') { + console.log('WARNING: RDF 1.0 is not supported. Defaulting to HTML5 mode.'); + this.setHTMLContext(); + } else if (document.doctype.publicId === '-//W3C//DTD XHTML+RDFa 1.1//EN' && document.doctype.systemId === 'http://www.w3.org/MarkUp/DTD/xhtml-rdfa-2.dtd') { + this.setXHTMLContext(); + } else { + this.setHTMLContext(); + } + } else { + this.setHTMLContext(); + } + } else { + this.setXMLContext(); + } + } + }, { + key: "setHTMLContext", + value: function setHTMLContext() { + this.setInitialContext(); + this.langAttributes = [{ + namespaceURI: 'http://www.w3.org/XML/1998/namespace', + localName: 'lang' + }, { + namespaceURI: null, + localName: 'lang' + }]; + this.inXHTMLMode = false; + this.inHTMLMode = true; + } + }, { + key: "setInitialContext", + value: function setInitialContext() { + this.vocabulary = null; // By default, the prefixes are terms are loaded to the RDFa 1.1. standard within the graph constructor + + this.langAttributes = [{ + namespaceURI: 'http://www.w3.org/XML/1998/namespace', + localName: 'lang' + }]; + } + }, { + key: "setXHTMLContext", + value: function setXHTMLContext() { + this.setInitialContext(); + this.inXHTMLMode = true; + this.inHTMLMode = false; + this.langAttributes = [{ + namespaceURI: 'http://www.w3.org/XML/1998/namespace', + localName: 'lang' + }, { + namespaceURI: null, + localName: 'lang' + }]; // From http://www.w3.org/2011/rdfa-context/xhtml-rdfa-1.1 + + this.target.graph.terms['alternate'] = 'http://www.w3.org/1999/xhtml/vocab#alternate'; + this.target.graph.terms['appendix'] = 'http://www.w3.org/1999/xhtml/vocab#appendix'; + this.target.graph.terms['bookmark'] = 'http://www.w3.org/1999/xhtml/vocab#bookmark'; + this.target.graph.terms['cite'] = 'http://www.w3.org/1999/xhtml/vocab#cite'; + this.target.graph.terms['chapter'] = 'http://www.w3.org/1999/xhtml/vocab#chapter'; + this.target.graph.terms['contents'] = 'http://www.w3.org/1999/xhtml/vocab#contents'; + this.target.graph.terms['copyright'] = 'http://www.w3.org/1999/xhtml/vocab#copyright'; + this.target.graph.terms['first'] = 'http://www.w3.org/1999/xhtml/vocab#first'; + this.target.graph.terms['glossary'] = 'http://www.w3.org/1999/xhtml/vocab#glossary'; + this.target.graph.terms['help'] = 'http://www.w3.org/1999/xhtml/vocab#help'; + this.target.graph.terms['icon'] = 'http://www.w3.org/1999/xhtml/vocab#icon'; + this.target.graph.terms['index'] = 'http://www.w3.org/1999/xhtml/vocab#index'; + this.target.graph.terms['last'] = 'http://www.w3.org/1999/xhtml/vocab#last'; + this.target.graph.terms['license'] = 'http://www.w3.org/1999/xhtml/vocab#license'; + this.target.graph.terms['meta'] = 'http://www.w3.org/1999/xhtml/vocab#meta'; + this.target.graph.terms['next'] = 'http://www.w3.org/1999/xhtml/vocab#next'; + this.target.graph.terms['prev'] = 'http://www.w3.org/1999/xhtml/vocab#prev'; + this.target.graph.terms['previous'] = 'http://www.w3.org/1999/xhtml/vocab#previous'; + this.target.graph.terms['section'] = 'http://www.w3.org/1999/xhtml/vocab#section'; + this.target.graph.terms['stylesheet'] = 'http://www.w3.org/1999/xhtml/vocab#stylesheet'; + this.target.graph.terms['subsection'] = 'http://www.w3.org/1999/xhtml/vocab#subsection'; + this.target.graph.terms['start'] = 'http://www.w3.org/1999/xhtml/vocab#start'; + this.target.graph.terms['top'] = 'http://www.w3.org/1999/xhtml/vocab#top'; + this.target.graph.terms['up'] = 'http://www.w3.org/1999/xhtml/vocab#up'; + this.target.graph.terms['p3pv1'] = 'http://www.w3.org/1999/xhtml/vocab#p3pv1'; // other + + this.target.graph.terms['related'] = 'http://www.w3.org/1999/xhtml/vocab#related'; + this.target.graph.terms['role'] = 'http://www.w3.org/1999/xhtml/vocab#role'; + this.target.graph.terms['transformation'] = 'http://www.w3.org/1999/xhtml/vocab#transformation'; + } + }, { + key: "setXMLContext", + value: function setXMLContext() { + this.setInitialContext(); + this.inXHTMLMode = false; + this.inHTMLMode = false; + } + }, { + key: "tokenize", + value: function tokenize(str) { + return this.trim(str).split(/\s+/); + } + }, { + key: "toRDFNodeObject", + value: function toRDFNodeObject(x) { + if (typeof x === 'undefined') return undefined; + + if (typeof x === 'string') { + if (x.substring(0, 2) === '_:') { + if (typeof this.blankNodes[x.substring(2)] === 'undefined') { + this.blankNodes[x.substring(2)] = new _blank_node__WEBPACK_IMPORTED_MODULE_2__["default"](x.substring(2)); + } + + return this.blankNodes[x.substring(2)]; + } + + return _factories_canonical_data_factory__WEBPACK_IMPORTED_MODULE_7__["default"].namedNode(x); + } + + switch (x.type) { + case RDFaProcessor.objectURI: + if (x.value.substring(0, 2) === '_:') { + if (typeof this.blankNodes[x.value.substring(2)] === 'undefined') { + this.blankNodes[x.value.substring(2)] = new _blank_node__WEBPACK_IMPORTED_MODULE_2__["default"](x.value.substring(2)); + } + + return this.blankNodes[x.value.substring(2)]; + } + + return _factories_canonical_data_factory__WEBPACK_IMPORTED_MODULE_7__["default"].namedNode(x.value); + + case RDFaProcessor.PlainLiteralURI: + return new _literal__WEBPACK_IMPORTED_MODULE_3__["default"](x.value, x.language || ''); + + case RDFaProcessor.XMLLiteralURI: + case RDFaProcessor.HTMLLiteralURI: + var string = ''; + Object.keys(x.value).forEach(function (i) { + string += _utils_js__WEBPACK_IMPORTED_MODULE_6__["domToString"](x.value[i], this.htmlOptions); + }); + return new _literal__WEBPACK_IMPORTED_MODULE_3__["default"](string, '', new _named_node__WEBPACK_IMPORTED_MODULE_4__["default"](x.type)); + + default: + return new _literal__WEBPACK_IMPORTED_MODULE_3__["default"](x.value, '', new _named_node__WEBPACK_IMPORTED_MODULE_4__["default"](x.type)); + } + } + }, { + key: "trim", + value: function trim(str) { + return str.replace(/^\s\s*/, '').replace(/\s\s*$/, ''); + } + }], [{ + key: "parseRDFaDOM", + value: function parseRDFaDOM(dom, kb, base) { + var p = new RDFaProcessor(kb, { + 'base': base + }); // Cannot assign to read only property 'baseURI' of object '#': + + if (!dom.baseURI) { + // Note this became a read-only attribute some time before 2018 + dom.baseURI = base; // oinly set if not already set + } + + p.process(dom, { + baseURI: base + }); + } + }, { + key: "tokenize", + value: function tokenize(str) { + return this.trim(str).split(/\s+/); + } + }, { + key: "trim", + value: function trim(str) { + return str.replace(/^\s\s*/, '').replace(/\s\s*$/, ''); + } + }]); + + return RDFaProcessor; +}(); + + +RDFaProcessor.XMLLiteralURI = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#XMLLiteral'; +RDFaProcessor.HTMLLiteralURI = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#HTML'; +RDFaProcessor.PlainLiteralURI = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#PlainLiteral'; +RDFaProcessor.objectURI = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#object'; +RDFaProcessor.typeURI = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type'; +RDFaProcessor.nameChar = "[-A-Z_a-z\xC0-\xD6\xD8-\xF6\xF8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u10000-\uEFFFF.0-9\xB7\u0300-\u036F\u203F-\u2040]"; +RDFaProcessor.nameStartChar = "[A-Za-z\xC0-\xD6\xD8-\xF6\xF8-\xFF\u0100-\u0131\u0134-\u013E\u0141-\u0148\u014A-\u017E\u0180-\u01C3\u01CD-\u01F0\u01F4-\u01F5\u01FA-\u0217\u0250-\u02A8\u02BB-\u02C1\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03CE\u03D0-\u03D6\u03DA\u03DC\u03DE\u03E0\u03E2-\u03F3\u0401-\u040C\u040E-\u044F\u0451-\u045C\u045E-\u0481\u0490-\u04C4\u04C7-\u04C8\u04CB-\u04CC\u04D0-\u04EB\u04EE-\u04F5\u04F8-\u04F9\u0531-\u0556\u0559\u0561-\u0586\u05D0-\u05EA\u05F0-\u05F2\u0621-\u063A\u0641-\u064A\u0671-\u06B7\u06BA-\u06BE\u06C0-\u06CE\u06D0-\u06D3\u06D5\u06E5-\u06E6\u0905-\u0939\u093D\u0958-\u0961\u0985-\u098C\u098F-\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09DC-\u09DD\u09DF-\u09E1\u09F0-\u09F1\u0A05-\u0A0A\u0A0F-\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32-\u0A33\u0A35-\u0A36\u0A38-\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8B\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2-\u0AB3\u0AB5-\u0AB9\u0ABD\u0AE0\u0B05-\u0B0C\u0B0F-\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32-\u0B33\u0B36-\u0B39\u0B3D\u0B5C-\u0B5D\u0B5F-\u0B61\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99-\u0B9A\u0B9C\u0B9E-\u0B9F\u0BA3-\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB5\u0BB7-\u0BB9\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C33\u0C35-\u0C39\u0C60-\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CDE\u0CE0-\u0CE1\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D28\u0D2A-\u0D39\u0D60-\u0D61\u0E01-\u0E2E\u0E30\u0E32-\u0E33\u0E40-\u0E45\u0E81-\u0E82\u0E84\u0E87-\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA-\u0EAB\u0EAD-\u0EAE\u0EB0\u0EB2-\u0EB3\u0EBD\u0EC0-\u0EC4\u0F40-\u0F47\u0F49-\u0F69\u10A0-\u10C5\u10D0-\u10F6\u1100\u1102-\u1103\u1105-\u1107\u1109\u110B-\u110C\u110E-\u1112\u113C\u113E\u1140\u114C\u114E\u1150\u1154-\u1155\u1159\u115F-\u1161\u1163\u1165\u1167\u1169\u116D-\u116E\u1172-\u1173\u1175\u119E\u11A8\u11AB\u11AE-\u11AF\u11B7-\u11B8\u11BA\u11BC-\u11C2\u11EB\u11F0\u11F9\u1E00-\u1E9B\u1EA0-\u1EF9\u1F00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2126\u212A-\u212B\u212E\u2180-\u2182\u3041-\u3094\u30A1-\u30FA\u3105-\u312C\uAC00-\uD7A3\u4E00-\u9FA5\u3007\u3021-\u3029_]"; +RDFaProcessor.NCNAME = new RegExp('^' + RDFaProcessor.nameStartChar + RDFaProcessor.nameChar + '*$'); +/* +RDFaProcessor.prototype.resolveAndNormalize = function(base,href) { + var u = base.resolve(href) + var parsed = this.parseURI(u) + parsed.normalize() + return parsed.spec +} +*/ + +RDFaProcessor.dateTimeTypes = [{ + pattern: /-?P(?:[0-9]+Y)?(?:[0-9]+M)?(?:[0-9]+D)?(?:T(?:[0-9]+H)?(?:[0-9]+M)?(?:[0-9]+(?:\.[0-9]+)?S)?)?/, + type: 'http://www.w3.org/2001/XMLSchema#duration' +}, { + pattern: /-?(?:[1-9][0-9][0-9][0-9]|0[1-9][0-9][0-9]|00[1-9][0-9]|000[1-9])-[0-9][0-9]-[0-9][0-9]T(?:[0-1][0-9]|2[0-4]):[0-5][0-9]:[0-5][0-9](?:\.[0-9]+)?(?:Z|[+\-][0-9][0-9]:[0-9][0-9])?/, + type: 'http://www.w3.org/2001/XMLSchema#dateTime' +}, { + pattern: /-?(?:[1-9][0-9][0-9][0-9]|0[1-9][0-9][0-9]|00[1-9][0-9]|000[1-9])-[0-9][0-9]-[0-9][0-9](?:Z|[+\-][0-9][0-9]:[0-9][0-9])?/, + type: 'http://www.w3.org/2001/XMLSchema#date' +}, { + pattern: /(?:[0-1][0-9]|2[0-4]):[0-5][0-9]:[0-5][0-9](?:\.[0-9]+)?(?:Z|[+\-][0-9][0-9]:[0-9][0-9])?/, + type: 'http://www.w3.org/2001/XMLSchema#time' +}, { + pattern: /-?(?:[1-9][0-9][0-9][0-9]|0[1-9][0-9][0-9]|00[1-9][0-9]|000[1-9])-[0-9][0-9]/, + type: 'http://www.w3.org/2001/XMLSchema#gYearMonth' +}, { + pattern: /-?[1-9][0-9][0-9][0-9]|0[1-9][0-9][0-9]|00[1-9][0-9]|000[1-9]/, + type: 'http://www.w3.org/2001/XMLSchema#gYear' +}]; +var parseRDFaDOM = RDFaProcessor.parseRDFaDOM; + + +/***/ }), + +/***/ "./node_modules/rdflib/esm/rdfxmlparser.js": +/*!*************************************************!*\ + !*** ./node_modules/rdflib/esm/rdfxmlparser.js ***! + \*************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return RDFParser; }); +/* harmony import */ var _uri__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./uri */ "./node_modules/rdflib/esm/uri.js"); +/** + * RDF/XML PARSER + * + * Parser believed to be in full positive RDF/XML parsing compliance + * with the possible exception of handling deprecated RDF attributes + * appropriately. Parser is believed to comply fully with other W3C + * and industry standards where appropriate (DOM, ECMAScript, &c.) + * + * Author: David Sheets + * + * W3C® SOFTWARE NOTICE AND LICENSE + * http://www.w3.org/Consortium/Legal/2002/copyright-software-20021231 + * This work (and included software, documentation such as READMEs, or + * other related items) is being provided by the copyright holders under + * the following license. By obtaining, using and/or copying this work, + * you (the licensee) agree that you have read, understood, and will + * comply with the following terms and conditions. + * + * Permission to copy, modify, and distribute this software and its + * documentation, with or without modification, for any purpose and + * without fee or royalty is hereby granted, provided that you include + * the following on ALL copies of the software and documentation or + * portions thereof, including modifications: + * + * 1. The full text of this NOTICE in a location viewable to users of + * the redistributed or derivative work. + * 2. Any pre-existing intellectual property disclaimers, notices, or terms and + * conditions. If none exist, the W3C Software Short Notice should be + * included (hypertext is preferred, text is permitted) within the body + * of any redistributed or derivative code. + * 3. Notice of any changes or modifications to the files, including the + * date changes were made. (We recommend you provide URIs to the location + * from which the code is derived.) + * + * THIS SOFTWARE AND DOCUMENTATION IS PROVIDED "AS IS," AND COPYRIGHT + * HOLDERS MAKE NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY OR FITNESS + * FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE OR + * DOCUMENTATION WILL NOT INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS, + * TRADEMARKS OR OTHER RIGHTS. + * + * COPYRIGHT HOLDERS WILL NOT BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL + * OR CONSEQUENTIAL DAMAGES ARISING OUT OF ANY USE OF THE SOFTWARE OR + * DOCUMENTATION. + * + * The name and trademarks of copyright holders may NOT be used in + * advertising or publicity pertaining to the software without specific, + * written prior permission. Title to copyright in this software and any + * associated documentation will at all times remain with copyright + * holders. + */ + +/** + * @class RDFParser resource object tied to an RDFStore + * + * @author David Sheets + * +*/ + +/* + * @constructor + * @param {RDFStore} store An RDFStore object + */ + +function RDFParser(store) { + var RDFParser = {}; + /** Standard namespaces that we know how to handle @final + * @member RDFParser + */ + + RDFParser.ns = { + 'RDF': 'http://www.w3.org/1999/02/22-rdf-syntax-ns#', + 'RDFS': 'http://www.w3.org/2000/01/rdf-schema#' + }; + /** DOM Level 2 node type magic numbers @final + * @member RDFParser + */ + + RDFParser.nodeType = { + 'ELEMENT': 1, + 'ATTRIBUTE': 2, + 'TEXT': 3, + 'CDATA_SECTION': 4, + 'ENTITY_REFERENCE': 5, + 'ENTITY': 6, + 'PROCESSING_INSTRUCTION': 7, + 'COMMENT': 8, + 'DOCUMENT': 9, + 'DOCUMENT_TYPE': 10, + 'DOCUMENT_FRAGMENT': 11, + 'NOTATION': 12 + }; + /** + * Frame class for namespace and base URI lookups + * Base lookups will always resolve because the parser knows + * the default base. + * + * @private + */ + + this.frameFactory = function (parser, parent, element) { + return { + 'NODE': 1, + 'ARC': 2, + 'parent': parent, + 'parser': parser, + 'store': parser.store, + 'element': element, + 'lastChild': 0, + 'base': null, + 'lang': null, + 'node': null, + 'nodeType': null, + 'listIndex': 1, + 'rdfid': null, + 'datatype': null, + 'collection': false, + + /** Terminate the frame and notify the store that we're done */ + 'terminateFrame': function terminateFrame() { + if (this.collection) { + this.node.close(); + } + }, + + /** Add a symbol of a certain type to the this frame */ + 'addSymbol': function addSymbol(type, uri) { + uri = _uri__WEBPACK_IMPORTED_MODULE_0__["join"](uri, this.base); + this.node = this.store.sym(uri); + this.nodeType = type; + }, + + /** Load any constructed triples into the store */ + 'loadTriple': function loadTriple() { + if (this.parent.parent.collection) { + this.parent.parent.node.append(this.node); + } else { + this.store.add(this.parent.parent.node, this.parent.node, this.node, this.parser.why); + } + + if (this.parent.rdfid != null) { + // reify + var triple = this.store.sym(_uri__WEBPACK_IMPORTED_MODULE_0__["join"]('#' + this.parent.rdfid, this.base)); + this.store.add(triple, this.store.sym(RDFParser.ns.RDF + 'type'), this.store.sym(RDFParser.ns.RDF + 'Statement'), this.parser.why); + this.store.add(triple, this.store.sym(RDFParser.ns.RDF + 'subject'), this.parent.parent.node, this.parser.why); + this.store.add(triple, this.store.sym(RDFParser.ns.RDF + 'predicate'), this.parent.node, this.parser.why); + this.store.add(triple, this.store.sym(RDFParser.ns.RDF + 'object'), this.node, this.parser.why); + } + }, + + /** Check if it's OK to load a triple */ + 'isTripleToLoad': function isTripleToLoad() { + return this.parent != null && this.parent.parent != null && this.nodeType === this.NODE && this.parent.nodeType === this.ARC && this.parent.parent.nodeType === this.NODE; + }, + + /** Add a symbolic node to this frame */ + 'addNode': function addNode(uri) { + this.addSymbol(this.NODE, uri); + + if (this.isTripleToLoad()) { + this.loadTriple(); + } + }, + + /** Add a collection node to this frame */ + 'addCollection': function addCollection() { + this.nodeType = this.NODE; + this.node = this.store.collection(); + this.collection = true; + + if (this.isTripleToLoad()) { + this.loadTriple(); + } + }, + + /** Add a collection arc to this frame */ + 'addCollectionArc': function addCollectionArc() { + this.nodeType = this.ARC; + }, + + /** Add a bnode to this frame */ + 'addBNode': function addBNode(id) { + if (id != null) { + if (this.parser.bnodes[id] != null) { + this.node = this.parser.bnodes[id]; + } else { + this.node = this.parser.bnodes[id] = this.store.bnode(); + } + } else { + this.node = this.store.bnode(); + } + + this.nodeType = this.NODE; + + if (this.isTripleToLoad()) { + this.loadTriple(); + } + }, + + /** Add an arc or property to this frame */ + 'addArc': function addArc(uri) { + if (uri === RDFParser.ns.RDF + 'li') { + uri = RDFParser.ns.RDF + '_' + this.parent.listIndex; + this.parent.listIndex++; + } + + this.addSymbol(this.ARC, uri); + }, + + /** Add a literal to this frame */ + 'addLiteral': function addLiteral(value) { + if (this.parent.datatype && this.parent.datatype !== RDFParser.ns.RDF + 'langString') { + this.node = this.store.literal(value, this.store.sym(this.parent.datatype)); + } else { + this.node = this.store.literal(value, this.lang); + } + + this.nodeType = this.NODE; + + if (this.isTripleToLoad()) { + this.loadTriple(); + } + } + }; + }; // from the OpenLayers source .. needed to get around IE problems. + + + this.getAttributeNodeNS = function (node, uri, name) { + var attributeNode = null; + + if (node.getAttributeNodeNS) { + attributeNode = node.getAttributeNodeNS(uri, name); + } else { + var attributes = node.attributes; + var potentialNode, fullName; + + for (var i = 0; i < attributes.length; ++i) { + potentialNode = attributes[i]; + + if (potentialNode.namespaceURI === uri) { + fullName = potentialNode.prefix ? potentialNode.prefix + ':' + name : name; + + if (fullName === potentialNode.nodeName) { + attributeNode = potentialNode; + break; + } + } + } + } + + return attributeNode; + }; + /** Our triple store reference @private */ + + + this.store = store; + /** Our identified blank nodes @private */ + + this.bnodes = {}; + /** A context for context-aware stores @private */ + + this.why = null; + /** Reification flag */ + + this.reify = false; + /** + * Build our initial scope frame and parse the DOM into triples + * @param {DOMTree} document The DOM to parse + * @param {String} base The base URL to use + * @param {Object} why The context to which this resource belongs + */ + + this.parse = function (document, base, why) { + var children = document.childNodes; // clean up for the next run + + this.cleanParser(); // figure out the root element + + var root; + + if (document.nodeType === RDFParser.nodeType.DOCUMENT) { + for (var c = 0; c < children.length; c++) { + if (children[c].nodeType === RDFParser.nodeType.ELEMENT) { + root = children[c]; + break; + } + } + } else if (document.nodeType === RDFParser.nodeType.ELEMENT) { + root = document; + } else { + throw new Error("RDFParser: can't find root in " + base + '. Halting. '); // return false + } + + this.why = why; // our topmost frame + + var f = this.frameFactory(this); + this.base = base; + f.base = base; + f.lang = null; // was '' but can't have langs like that 2015 (!) + + this.parseDOM(this.buildFrame(f, root)); + return true; + }; + + this.parseDOM = function (frame) { + // a DOM utility function used in parsing + var rdfid; + + var elementURI = function (el) { + var result = ''; + + if (el.namespaceURI == null) { + throw new Error('RDF/XML syntax error: No namespace for ' + el.localName + ' in ' + this.base); + } + + if (el.namespaceURI) { + result = result + el.namespaceURI; + } + + if (el.localName) { + result = result + el.localName; + } else if (el.nodeName) { + if (el.nodeName.indexOf(':') >= 0) result = result + el.nodeName.split(':')[1];else result = result + el.nodeName; + } + + return result; + }.bind(this); + + var dig = true; // if we'll dig down in the tree on the next iter + + while (frame.parent) { + var dom = frame.element; + var attrs = dom.attributes; + + if (dom.nodeType === RDFParser.nodeType.TEXT || dom.nodeType === RDFParser.nodeType.CDATA_SECTION) { + // we have a literal + if (frame.parent.nodeType === frame.NODE) { + // must have had attributes, store as rdf:value + frame.addArc(RDFParser.ns.RDF + 'value'); + frame = this.buildFrame(frame); + } + + frame.addLiteral(dom.nodeValue); + } else if (elementURI(dom) !== RDFParser.ns.RDF + 'RDF') { + // not root + if (frame.parent && frame.parent.collection) { + // we're a collection element + frame.addCollectionArc(); + frame = this.buildFrame(frame, frame.element); + frame.parent.element = null; + } + + if (!frame.parent || !frame.parent.nodeType || frame.parent.nodeType === frame.ARC) { + // we need a node + var about = this.getAttributeNodeNS(dom, RDFParser.ns.RDF, 'about'); + rdfid = this.getAttributeNodeNS(dom, RDFParser.ns.RDF, 'ID'); + + if (about && rdfid) { + throw new Error('RDFParser: ' + dom.nodeName + ' has both rdf:id and rdf:about.' + ' Halting. Only one of these' + ' properties may be specified on a' + ' node.'); + } + + if (!about && rdfid) { + frame.addNode('#' + rdfid.nodeValue); + dom.removeAttributeNode(rdfid); + } else if (about == null && rdfid == null) { + var bnid = this.getAttributeNodeNS(dom, RDFParser.ns.RDF, 'nodeID'); + + if (bnid) { + frame.addBNode(bnid.nodeValue); + dom.removeAttributeNode(bnid); + } else { + frame.addBNode(); + } + } else { + frame.addNode(about.nodeValue); + dom.removeAttributeNode(about); + } // Typed nodes + + + var rdftype = this.getAttributeNodeNS(dom, RDFParser.ns.RDF, 'type'); + + if (RDFParser.ns.RDF + 'Description' !== elementURI(dom)) { + rdftype = { + 'nodeValue': elementURI(dom) + }; + } + + if (rdftype != null) { + this.store.add(frame.node, this.store.sym(RDFParser.ns.RDF + 'type'), this.store.sym(_uri__WEBPACK_IMPORTED_MODULE_0__["join"](rdftype.nodeValue, frame.base)), this.why); + + if (rdftype.nodeName) { + dom.removeAttributeNode(rdftype); + } + } // Property Attributes + + + for (var x = attrs.length - 1; x >= 0; x--) { + this.store.add(frame.node, this.store.sym(elementURI(attrs[x])), this.store.literal(attrs[x].nodeValue, frame.lang), this.why); + } + } else { + // we should add an arc (or implicit bnode+arc) + frame.addArc(elementURI(dom)); // save the arc's rdf:ID if it has one + + if (this.reify) { + rdfid = this.getAttributeNodeNS(dom, RDFParser.ns.RDF, 'ID'); + + if (rdfid) { + frame.rdfid = rdfid.nodeValue; + dom.removeAttributeNode(rdfid); + } + } + + var parsetype = this.getAttributeNodeNS(dom, RDFParser.ns.RDF, 'parseType'); + var datatype = this.getAttributeNodeNS(dom, RDFParser.ns.RDF, 'datatype'); + + if (datatype) { + frame.datatype = datatype.nodeValue; + dom.removeAttributeNode(datatype); + } + + if (parsetype) { + var nv = parsetype.nodeValue; + + if (nv === 'Literal') { + frame.datatype = RDFParser.ns.RDF + 'XMLLiteral'; + frame = this.buildFrame(frame); // Don't include the literal node, only its children + + frame.addLiteral(dom.childNodes); + dig = false; + } else if (nv === 'Resource') { + frame = this.buildFrame(frame, frame.element); + frame.parent.element = null; + frame.addBNode(); + } else if (nv === 'Collection') { + frame = this.buildFrame(frame, frame.element); + frame.parent.element = null; + frame.addCollection(); + } + + dom.removeAttributeNode(parsetype); + } + + if (attrs.length !== 0) { + var resource = this.getAttributeNodeNS(dom, RDFParser.ns.RDF, 'resource'); + var bnid2 = this.getAttributeNodeNS(dom, RDFParser.ns.RDF, 'nodeID'); + frame = this.buildFrame(frame); + + if (resource) { + frame.addNode(resource.nodeValue); + dom.removeAttributeNode(resource); + } else { + if (bnid2) { + frame.addBNode(bnid2.nodeValue); + dom.removeAttributeNode(bnid2); + } else { + frame.addBNode(); + } + } + + for (var x1 = attrs.length - 1; x1 >= 0; x1--) { + var f = this.buildFrame(frame); + f.addArc(elementURI(attrs[x1])); + + if (elementURI(attrs[x1]) === RDFParser.ns.RDF + 'type') { + this.buildFrame(f).addNode(attrs[x1].nodeValue); + } else { + this.buildFrame(f).addLiteral(attrs[x1].nodeValue); + } + } + } else if (dom.childNodes.length === 0) { + this.buildFrame(frame).addLiteral(''); + } + } + } // rdf:RDF + // dig dug + + + dom = frame.element; + + while (frame.parent) { + var pframe = frame; + + while (dom == null) { + frame = frame.parent; + dom = frame.element; + } + + var candidate = dom.childNodes && dom.childNodes[frame.lastChild]; + + if (!candidate || !dig) { + frame.terminateFrame(); + + if (!(frame = frame.parent)) { + break; + } // done + + + dom = frame.element; + dig = true; + } else if (candidate.nodeType !== RDFParser.nodeType.ELEMENT && candidate.nodeType !== RDFParser.nodeType.TEXT && candidate.nodeType !== RDFParser.nodeType.CDATA_SECTION || (candidate.nodeType === RDFParser.nodeType.TEXT || candidate.nodeType === RDFParser.nodeType.CDATA_SECTION) && dom.childNodes.length !== 1) { + frame.lastChild++; + } else { + // not a leaf + frame.lastChild++; + frame = this.buildFrame(pframe, dom.childNodes[frame.lastChild - 1]); + break; + } + } + } // while + + }; + /** + * Cleans out state from a previous parse run + * @private + */ + + + this.cleanParser = function () { + this.bnodes = {}; + this.why = null; + }; + /** + * Builds scope frame + * @private + */ + + + this.buildFrame = function (parent, element) { + var frame = this.frameFactory(this, parent, element); + + if (parent) { + frame.base = parent.base; + frame.lang = parent.lang; + } + + if (!element || element.nodeType === RDFParser.nodeType.TEXT || element.nodeType === RDFParser.nodeType.CDATA_SECTION) { + return frame; + } + + var attrs = element.attributes; + var base = element.getAttributeNode('xml:base'); + + if (base != null) { + frame.base = base.nodeValue; + element.removeAttribute('xml:base'); + } + + var lang = element.getAttributeNode('xml:lang'); + + if (lang != null) { + frame.lang = lang.nodeValue; + element.removeAttribute('xml:lang'); + } // remove all extraneous xml and xmlns attributes + + + for (var x = attrs.length - 1; x >= 0; x--) { + if (attrs[x].nodeName.substr(0, 3) === 'xml') { + if (attrs[x].name.slice(0, 6) === 'xmlns:') { + var uri = attrs[x].nodeValue; // alert('base for namespac attr:'+this.base) + + if (this.base) uri = _uri__WEBPACK_IMPORTED_MODULE_0__["join"](uri, this.base); + this.store.setPrefixForURI(attrs[x].name.slice(6), uri); + } // alert('rdfparser: xml atribute: '+attrs[x].name) //@@ + + + element.removeAttributeNode(attrs[x]); + } + } + + return frame; + }; +} + +/***/ }), + +/***/ "./node_modules/rdflib/esm/serialize.js": +/*!**********************************************!*\ + !*** ./node_modules/rdflib/esm/serialize.js ***! + \**********************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return serialize; }); +/* harmony import */ var _convert__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./convert */ "./node_modules/rdflib/esm/convert.js"); +/* harmony import */ var _serializer__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./serializer */ "./node_modules/rdflib/esm/serializer.js"); +/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./types */ "./node_modules/rdflib/esm/types.js"); + + + + +/** + * Serialize to the appropriate format + */ +function serialize( +/** The graph or nodes that should be serialized */ +target, +/** The store */ +kb, base, +/** + * The mime type. + * Defaults to Turtle. + */ +contentType, callback, options) { + base = base || target.value; + var opts = options || {}; + contentType = contentType || _types__WEBPACK_IMPORTED_MODULE_2__["TurtleContentType"]; // text/n3 if complex? + + var documentString = null; + + try { + var sz = Object(_serializer__WEBPACK_IMPORTED_MODULE_1__["default"])(kb); + if (opts.flags) sz.setFlags(opts.flags); + var newSts = kb.statementsMatching(undefined, undefined, undefined, target); + var n3String; + sz.suggestNamespaces(kb.namespaces); + sz.setBase(base); + + switch (contentType) { + case _types__WEBPACK_IMPORTED_MODULE_2__["RDFXMLContentType"]: + documentString = sz.statementsToXML(newSts); + return executeCallback(null, documentString); + + case _types__WEBPACK_IMPORTED_MODULE_2__["N3ContentType"]: + case _types__WEBPACK_IMPORTED_MODULE_2__["N3LegacyContentType"]: + documentString = sz.statementsToN3(newSts); + return executeCallback(null, documentString); + + case _types__WEBPACK_IMPORTED_MODULE_2__["TurtleContentType"]: + case _types__WEBPACK_IMPORTED_MODULE_2__["TurtleLegacyContentType"]: + sz.setFlags('si'); // Suppress = for sameAs and => for implies + + documentString = sz.statementsToN3(newSts); + return executeCallback(null, documentString); + + case _types__WEBPACK_IMPORTED_MODULE_2__["NTriplesContentType"]: + sz.setFlags('deinprstux'); // Suppress nice parts of N3 to make ntriples + + documentString = sz.statementsToNTriples(newSts); + return executeCallback(null, documentString); + + case _types__WEBPACK_IMPORTED_MODULE_2__["JSONLDContentType"]: + sz.setFlags('deinprstux'); // Use adapters to connect to incmpatible parser + + n3String = sz.statementsToNTriples(newSts); // n3String = sz.statementsToN3(newSts) + + _convert__WEBPACK_IMPORTED_MODULE_0__["convertToJson"](n3String, callback); + break; + + case _types__WEBPACK_IMPORTED_MODULE_2__["NQuadsContentType"]: + case _types__WEBPACK_IMPORTED_MODULE_2__["NQuadsAltContentType"]: + // @@@ just outpout the quads? Does not work for collections + sz.setFlags('deinprstux q'); // Suppress nice parts of N3 to make ntriples + + documentString = sz.statementsToNTriples(newSts); // q in flag means actually quads + + return executeCallback(null, documentString); + // n3String = sz.statementsToN3(newSts) + // documentString = convert.convertToNQuads(n3String, callback) + // break + + default: + throw new Error('Serialize: Content-type ' + contentType + ' not supported for data write.'); + } + } catch (err) { + if (callback) { + return callback(err, undefined); + } + + throw err; // Don't hide problems from caller in sync mode + } + + function executeCallback(err, result) { + if (callback) { + callback(err, result); + return; + } else { + return result; + } + } +} + +/***/ }), + +/***/ "./node_modules/rdflib/esm/serializer.js": +/*!***********************************************!*\ + !*** ./node_modules/rdflib/esm/serializer.js ***! + \***********************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _named_node__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./named-node */ "./node_modules/rdflib/esm/named-node.js"); +/* harmony import */ var _blank_node__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./blank-node */ "./node_modules/rdflib/esm/blank-node.js"); +/* harmony import */ var _uri__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./uri */ "./node_modules/rdflib/esm/uri.js"); +/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./utils-js */ "./node_modules/rdflib/esm/utils-js.js"); +/* harmony import */ var _factories_canonical_data_factory__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./factories/canonical-data-factory */ "./node_modules/rdflib/esm/factories/canonical-data-factory.js"); +/* harmony import */ var _xsd__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./xsd */ "./node_modules/rdflib/esm/xsd.js"); +/* Serialization of RDF Graphs +** +** Tim Berners-Lee 2006 +** This is was http://dig.csail.mit.edu/2005/ajar/ajaw/js/rdf/serialize.js +** This is or was https://github.com/linkeddata/rdflib.js/blob/master/src/serializer.js +** Licence: MIT +*/ + + + + + + +/* harmony default export */ __webpack_exports__["default"] = ((function () { + var __Serializer = function __Serializer(store) { + this.flags = ''; + this.base = null; + this.prefixes = []; // suggested prefixes + + this.namespaces = []; // complementary indexes + + this.suggestPrefix('rdf', 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'); // XML code assumes this! + + this.suggestPrefix('xml', 'reserved:reservedForFutureUse'); // XML reserves xml: in the spec. + + this.namespacesUsed = []; // Count actually used and so needed in @prefixes + + this.keywords = ['a']; // The only one we generate at the moment + + this.prefixchars = 'abcdefghijklmnopqustuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; + this.incoming = null; // Array not calculated yet + + this.formulas = []; // remebering original formulae from hashes + + this.store = store; + this.rdfFactory = store.rdfFactory || _factories_canonical_data_factory__WEBPACK_IMPORTED_MODULE_4__["default"]; + this.xsd = Object(_xsd__WEBPACK_IMPORTED_MODULE_5__["createXSD"])(this.rdfFactory); + }; + + __Serializer.prototype.setBase = function (base) { + this.base = base; + return this; + }; + + __Serializer.prototype.setFlags = function (flags) { + this.flags = flags || ''; + return this; + }; + + __Serializer.prototype.toStr = function (x) { + var s = x.toNT(); + + if (x.termType === 'Graph') { + this.formulas[s] = x; // remember as reverse does not work + } + + return s; + }; + + __Serializer.prototype.fromStr = function (s) { + if (s[0] === '{') { + var x = this.formulas[s]; + if (!x) console.log('No formula object for ' + s); + return x; + } + + return this.store.fromNT(s); + }; + /* Accumulate Namespaces + ** + ** These are only hints. If two overlap, only one gets used + ** There is therefore no guarantee in general. + */ + + + __Serializer.prototype.suggestPrefix = function (prefix, uri) { + if (prefix.slice(0, 7) === 'default') return; // Try to weed these out + + if (prefix.slice(0, 2) === 'ns') return; // From others inferior algos + + if (!prefix || !uri) return; // empty strings not suitable + + if (prefix in this.namespaces || uri in this.prefixes) return; // already used + + this.prefixes[uri] = prefix; + this.namespaces[prefix] = uri; + }; // Takes a namespace -> prefix map + + + __Serializer.prototype.suggestNamespaces = function (namespaces) { + for (var px in namespaces) { + this.suggestPrefix(px, namespaces[px]); + } + + return this; + }; + + __Serializer.prototype.checkIntegrity = function () { + var p, ns; + + for (p in this.namespaces) { + if (this.prefixes[this.namespaces[p]] !== p) { + throw new Error('Serializer integity error 1: ' + p + ', ' + this.namespaces[p] + ', ' + this.prefixes[this.namespaces[p]] + '!'); + } + } + + for (ns in this.prefixes) { + if (this.namespaces[this.prefixes[ns]] !== ns) { + throw new Error('Serializer integity error 2: ' + ns + ', ' + this.prefixs[ns] + ', ' + this.namespaces[this.prefixes[ns]] + '!'); + } + } + }; // Make up an unused prefix for a random namespace + + + __Serializer.prototype.makeUpPrefix = function (uri) { + var p = uri; + + function canUseMethod(pp) { + if (!__Serializer.prototype.validPrefix.test(pp)) return false; // bad format + + if (pp === 'ns') return false; // boring + + if (pp in this.namespaces) return false; // already used + + this.prefixes[uri] = pp; + this.namespaces[pp] = uri; + return pp; + } + + var canUse = canUseMethod.bind(this); + if ('#/'.indexOf(p[p.length - 1]) >= 0) p = p.slice(0, -1); + var slash = p.lastIndexOf('/'); + if (slash >= 0) p = p.slice(slash + 1); + var i = 0; + + while (i < p.length) { + if (this.prefixchars.indexOf(p[i])) { + i++; + } else { + break; + } + } + + p = p.slice(0, i); + if (p.length < 6 && canUse(p)) return p; // exact is best + + if (canUse(p.slice(0, 3))) return p.slice(0, 3); + if (canUse(p.slice(0, 2))) return p.slice(0, 2); + if (canUse(p.slice(0, 4))) return p.slice(0, 4); + if (canUse(p.slice(0, 1))) return p.slice(0, 1); + if (canUse(p.slice(0, 5))) return p.slice(0, 5); + + if (!__Serializer.prototype.validPrefix.test(p)) { + p = 'n'; // Otherwise the loop below may never termimnate + } + + for (var j = 0;; j++) { + if (canUse(p.slice(0, 3) + j)) return p.slice(0, 3) + j; + } + }; + + __Serializer.prototype.rootSubjects = function (sts) { + var incoming = {}; + var subjects = {}; + var allBnodes = {}; + /* This scan is to find out which nodes will have to be the roots of trees + ** in the serialized form. This will be any symbols, and any bnodes + ** which hve more or less than one incoming arc, and any bnodes which have + ** one incoming arc but it is an uninterrupted loop of such nodes back to itself. + ** This should be kept linear time with repect to the number of statements. + ** Note it does not use any indexing of the store. + */ + + for (var i = 0; i < sts.length; i++) { + var st = sts[i]; + + var checkMentions = function checkMentions(x) { + if (!incoming.hasOwnProperty(x)) incoming[x] = []; + incoming[x].push(st.subject); // List of things which will cause this to be printed + }; + + var st2 = [st.subject, st.predicate, st.object]; + st2.map(function (y) { + if (y.termType === 'BlankNode') { + allBnodes[y.toNT()] = true; + } else if (y.termType === 'Collection') { + y.elements.forEach(function (z) { + checkMentions(z); // bnodes in collections important + }); + } + }); + checkMentions(sts[i].object); + var ss = subjects[this.toStr(st.subject)]; // Statements with this as subject + + if (!ss) ss = []; + ss.push(st); + subjects[this.toStr(st.subject)] = ss; // Make hash. @@ too slow for formula? + } + + var roots = []; + + for (var xNT in subjects) { + if (!subjects.hasOwnProperty(xNT)) continue; + var y = this.fromStr(xNT); + + if (y.termType !== 'BlankNode' || !incoming[y] || incoming[y].length !== 1) { + roots.push(y); + continue; + } + } + + this.incoming = incoming; // Keep for serializing @@ Bug for nested formulas + // Now do the scan using existing roots + + var rootsHash = {}; + + for (var k = 0; k < roots.length; k++) { + rootsHash[roots[k].toNT()] = true; + } + + return { + 'roots': roots, + 'subjects': subjects, + 'rootsHash': rootsHash, + 'incoming': incoming + }; + }; // ////////////////////////////////////////////////////// + + + __Serializer.prototype.toN3 = function (f) { + return this.statementsToN3(f.statements); + }; + + __Serializer.prototype._notQNameChars = '\t\r\n !"#$%&\'()*.,+/;<=>?@[\\]^`{|}~'; + __Serializer.prototype._notNameChars = __Serializer.prototype._notQNameChars + ':'; + + __Serializer.prototype.explicitURI = function (uri) { + if (this.flags.indexOf('r') < 0 && this.base) { + uri = _uri__WEBPACK_IMPORTED_MODULE_2__["refTo"](this.base, uri); + } else if (this.flags.indexOf('u') >= 0) { + // Unicode encoding NTriples style + uri = backslashUify(uri); + } else { + uri = hexify(uri); + } + + return '<' + uri + '>'; + }; + + __Serializer.prototype.statementsToNTriples = function (sts) { + var sorted = sts.slice(); + sorted.sort(); + var str = ''; + var rdfns = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'; + var self = this; + var kb = this.store; + var factory = this.rdfFactory; + + var termToNT = function termToNT(x) { + if (x.termType !== 'Collection') { + return self.atomicTermToN3(x); + } + + var list = x.elements; + var rest = kb.sym(rdfns + 'nill'); + + for (var i = list.length - 1; i >= 0; i--) { + var bnode = factory.blankNode(); + str += termToNT(bnode) + ' ' + termToNT(kb.sym(rdfns + 'first')) + ' ' + termToNT(list[i]) + '.\n'; + str += termToNT(bnode) + ' ' + termToNT(kb.sym(rdfns + 'rest')) + ' ' + termToNT(rest) + '.\n'; + rest = bnode; + } + + return self.atomicTermToN3(rest); + }; + + for (var i = 0; i < sorted.length; i++) { + var st = sorted[i]; + var s = ''; + s += termToNT(st.subject) + ' '; + s += termToNT(st.predicate) + ' '; + s += termToNT(st.object) + ' '; + + if (this.flags.indexOf('q') >= 0) { + // Do quads not nrtiples + s += termToNT(st.why) + ' '; + } + + s += '.\n'; + str += s; + } + + return str; + }; + + __Serializer.prototype.statementsToN3 = function (sts) { + var indent = 4; + var width = 80; + var kb = this.store; // A URI Map alows us to put the type statemnts at the top. + + var uriMap = { + 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type': 'aaa:00' + }; + + var SPO = function SPO(x, y) { + // Do limited canonicalization of bnodes + return _utils_js__WEBPACK_IMPORTED_MODULE_3__["heavyCompareSPO"](x, y, kb, uriMap); + }; + + sts.sort(SPO); + + if (this.base && !this.defaultNamespace) { + this.defaultNamespace = this.base + '#'; + } + + var predMap = {}; + + if (this.flags.indexOf('s') < 0) { + predMap['http://www.w3.org/2002/07/owl#sameAs'] = '='; + } + + if (this.flags.indexOf('t') < 0) { + predMap['http://www.w3.org/1999/02/22-rdf-syntax-ns#type'] = 'a'; + } + + if (this.flags.indexOf('i') < 0) { + predMap['http://www.w3.org/2000/10/swap/log#implies'] = '=>'; + } // //////////////////////// Arrange the bits of text + + + var spaces = function spaces(n) { + var s = ''; + + for (var i = 0; i < n; i++) { + s += ' '; + } + + return s; + }; + + var treeToLine = function treeToLine(tree) { + var str = ''; + + for (var i = 0; i < tree.length; i++) { + var branch = tree[i]; + var s2 = typeof branch === 'string' ? branch : treeToLine(branch); // Note the space before the dot in case statement ends 123. which is in fact allowed but be conservative. + + if (i !== 0) { + var ch = str.slice(-1) || ' '; + + if (s2 === ',' || s2 === ';') {// no gap + } else if (s2 === '.' && !'0123456789.'.includes(ch)) {// no gap except after number + // no gap + } else { + str += ' '; // separate from previous token + } + } + + str += s2; + } + + return str; + }; // Convert a nested tree of lists and strings to a string + + + var treeToString = function treeToString(tree, level) { + var str = ''; + var lastLength = 100000; + if (level === undefined) level = -1; + + for (var i = 0; i < tree.length; i++) { + var branch = tree[i]; + + if (typeof branch !== 'string') { + var substr = treeToString(branch, level + 1); + + if (substr.length < 10 * (width - indent * level) && substr.indexOf('"""') < 0) { + // Don't mess up multiline strings + var line = treeToLine(branch); + + if (line.length < width - indent * level) { + branch = line; // Note! treat as string below + + substr = ''; + } + } + + if (substr) lastLength = 10000; + str += substr; + } + + if (typeof branch === 'string') { + if (branch.length === 1 && str.slice(-1) === '\n') { + if (',.;'.indexOf(branch) >= 0) { + str = str.slice(0, -1) + branch + '\n'; // slip punct'n on end + + lastLength += 1; + continue; + } + } + + if (lastLength < indent * level + 4 || // if new line not necessary + lastLength + branch.length + 1 < width && ';.'.indexOf(str[str.length - 2]) < 0) { + // or the string fits on last line + str = str.slice(0, -1) + ' ' + branch + '\n'; // then continue on this line + + lastLength += branch.length + 1; + } else { + var _line = spaces(indent * level) + branch; + + str += _line + '\n'; + lastLength = _line.length; + + if (level < 0) { + str += '\n'; // extra blank line + + lastLength = 100000; // don't touch + } + } + } + } + + return str; + }; // //////////////////////////////////////////// Structure for N3 + // Convert a set of statements into a nested tree of lists and strings + + + function statementListToTreeMethod(statements) { + var stats = this.rootSubjects(statements); + var roots = stats.roots; + var results = []; + + for (var i = 0; i < roots.length; i++) { + var root = roots[i]; + results.push(subjectTree(root, stats)); + } + + return results; + } + + var statementListToTree = statementListToTreeMethod.bind(this); // The tree for a subject + + function subjectTree(subject, stats) { + if (subject.termType === 'BlankNode' && !stats.incoming[subject]) { + return objectTree(subject, stats, true).concat(['.']); // Anonymous bnode subject + } + + return [termToN3(subject, stats)].concat([propertyTree(subject, stats)]).concat(['.']); + } // The property tree for a single subject or anonymous node + + + function propertyTreeMethod(subject, stats) { + var results = []; + var lastPred = null; + var sts = stats.subjects[this.toStr(subject)] || []; // relevant statements + + if (typeof sts === 'undefined') { + throw new Error('Cant find statements for ' + subject); + } + + var objects = []; + + for (var i = 0; i < sts.length; i++) { + var st = sts[i]; + + if (st.predicate.uri === lastPred) { + objects.push(','); + } else { + if (lastPred) { + results = results.concat([objects]).concat([';']); + objects = []; + } + + results.push(predMap[st.predicate.uri] ? predMap[st.predicate.uri] : termToN3(st.predicate, stats)); + } + + lastPred = st.predicate.uri; + objects.push(objectTree(st.object, stats)); + } + + results = results.concat([objects]); + return results; + } + + var propertyTree = propertyTreeMethod.bind(this); + + function objectTreeMethod(obj, stats, force) { + if (obj.termType === 'BlankNode' && (force || stats.rootsHash[obj.toNT()] === undefined)) { + // if not a root + if (stats.subjects[this.toStr(obj)]) { + return ['[', propertyTree(obj, stats), ']']; + } else { + return '[]'; + } + } + + return termToN3(obj, stats); + } + + var objectTree = objectTreeMethod.bind(this); + + function termToN3Method(expr, stats) { + // + var i, res; + + switch (expr.termType) { + case 'Graph': + res = ['{']; + res = res.concat(statementListToTree(expr.statements)); + return res.concat(['}']); + + case 'Collection': + res = ['(']; + + for (i = 0; i < expr.elements.length; i++) { + res.push([objectTree(expr.elements[i], stats)]); + } + + res.push(')'); + return res; + + default: + return this.atomicTermToN3(expr); + } + } + + __Serializer.prototype.termToN3 = termToN3; + var termToN3 = termToN3Method.bind(this); + + function prefixDirectivesMethod() { + var str = ''; + + if (this.defaultNamespace) { + str += '@prefix : ' + this.explicitURI(this.defaultNamespace) + '.\n'; + } + + for (var ns in this.prefixes) { + if (!this.prefixes.hasOwnProperty(ns)) continue; + if (!this.namespacesUsed[ns]) continue; + str += '@prefix ' + this.prefixes[ns] + ': ' + this.explicitURI(ns) + '.\n'; + } + + return str + '\n'; + } + + var prefixDirectives = prefixDirectivesMethod.bind(this); // Body of statementsToN3: + + var tree = statementListToTree(sts); + return prefixDirectives() + treeToString(tree); + }; // //////////////////////////////////////////// Atomic Terms + // Deal with term level things and nesting with no bnode structure + + + __Serializer.prototype.atomicTermToN3 = function atomicTermToN3(expr, stats) { + switch (expr.termType) { + case 'BlankNode': + case 'Variable': + return expr.toNT(); + + case 'Literal': + var val = expr.value; + + if (typeof val !== 'string') { + throw new TypeError('Value of RDF literal node must be a string'); + } // var val = expr.value.toString() // should be a string already + + + if (expr.datatype && this.flags.indexOf('x') < 0) { + // Supress native numbers + switch (expr.datatype.uri) { + case 'http://www.w3.org/2001/XMLSchema#integer': + return val; + + case 'http://www.w3.org/2001/XMLSchema#decimal': + // In urtle must have dot + if (val.indexOf('.') < 0) val += '.0'; + return val; + + case 'http://www.w3.org/2001/XMLSchema#double': + // Must force use of 'e' + if (val.indexOf('.') < 0) val += '.0'; + if (val.indexOf('e') < 0) val += 'e0'; + return val; + + case 'http://www.w3.org/2001/XMLSchema#boolean': + return expr.value === '1' ? 'true' : 'false'; + } + } + + var str = this.stringToN3(expr.value); + + if (expr.language) { + str += '@' + expr.language; + } else if (!expr.datatype.equals(this.xsd.string)) { + str += '^^' + this.atomicTermToN3(expr.datatype, stats); + } + + return str; + + case 'NamedNode': + return this.symbolToN3(expr); + + default: + throw new Error('Internal: atomicTermToN3 cannot handle ' + expr + ' of termType: ' + expr.termType); + } + }; // stringToN3: String escaping for N3 + + + __Serializer.prototype.validPrefix = new RegExp(/^[a-zA-Z][a-zA-Z0-9]*$/); + __Serializer.prototype.forbidden1 = new RegExp(/[\\"\b\f\r\v\t\n\u0080-\uffff]/gm); + __Serializer.prototype.forbidden3 = new RegExp(/[\\"\b\f\r\v\u0080-\uffff]/gm); + + __Serializer.prototype.stringToN3 = function stringToN3(str, flags) { + if (!flags) flags = 'e'; + var res = ''; + var i, j, k; + var delim; + var forbidden; + + if (str.length > 20 && // Long enough to make sense + str.slice(-1) !== '"' && // corner case' + flags.indexOf('n') < 0 && ( // Force single line + str.indexOf('\n') > 0 || str.indexOf('"') > 0)) { + delim = '"""'; + forbidden = __Serializer.prototype.forbidden3; + } else { + delim = '"'; + forbidden = __Serializer.prototype.forbidden1; + } + + for (i = 0; i < str.length;) { + forbidden.lastIndex = 0; + var m = forbidden.exec(str.slice(i)); + if (m == null) break; + j = i + forbidden.lastIndex - 1; + res += str.slice(i, j); + var ch = str[j]; + + if (ch === '"' && delim === '"""' && str.slice(j, j + 3) !== '"""') { + res += ch; + } else { + k = '\b\f\r\t\v\n\\"'.indexOf(ch); // No escaping of bell (7)? + + if (k >= 0) { + res += '\\' + 'bfrtvn\\"'[k]; + } else { + if (flags.indexOf('e') >= 0) { + // Unicode escaping in strings not unix style + res += "\\u" + ('000' + ch.charCodeAt(0).toString(16).toLowerCase()).slice(-4); + } else { + // no 'e' flag + res += ch; + } + } + } + + i = j + 1; + } + + return delim + res + str.slice(i) + delim; + }; // A single symbol, either in <> or namespace notation + + + __Serializer.prototype.symbolToN3 = function symbolToN3(x) { + // c.f. symbolString() in notation3.py + var uri = x.uri; + var j = uri.indexOf('#'); + + if (j < 0 && this.flags.indexOf('/') < 0) { + j = uri.lastIndexOf('/'); + } + + if (j >= 0 && this.flags.indexOf('p') < 0 && ( // Can split at namespace but only if http[s]: URI or file: or ws[s] (why not others?) + uri.indexOf('http') === 0 || uri.indexOf('ws') === 0 || uri.indexOf('file') === 0)) { + var canSplit = true; + + for (var k = j + 1; k < uri.length; k++) { + if (__Serializer.prototype._notNameChars.indexOf(uri[k]) >= 0) { + canSplit = false; + break; + } + } + /* + if (uri.slice(0, j + 1) === this.base + '#') { // base-relative + if (canSplit) { + return ':' + uri.slice(j + 1) // assume deafult ns is local + } else { + return '<#' + uri.slice(j + 1) + '>' + } + } + */ + + + if (canSplit) { + var localid = uri.slice(j + 1); + var namesp = uri.slice(0, j + 1); + + if (this.defaultNamespace && this.defaultNamespace === namesp && this.flags.indexOf('d') < 0) { + // d -> suppress default + if (this.flags.indexOf('k') >= 0 && this.keyords.indexOf(localid) < 0) { + return localid; + } + + return ':' + localid; + } // this.checkIntegrity() // @@@ Remove when not testing + + + var prefix = this.prefixes[namesp]; + if (!prefix) prefix = this.makeUpPrefix(namesp); + + if (prefix) { + this.namespacesUsed[namesp] = true; + return prefix + ':' + localid; + } // Fall though if can't do qname + + } + } + + return this.explicitURI(uri); + }; // String escaping utilities + + + function hexify(str) { + // also used in parser + return encodeURI(str); + } + + function backslashUify(str) { + var res = ''; + var k; + + for (var i = 0; i < str.length; i++) { + k = str.charCodeAt(i); + + if (k > 65535) { + res += "\\U" + ('00000000' + k.toString(16)).slice(-8); // convert to upper? + } else if (k > 126) { + res += "\\u" + ('0000' + k.toString(16)).slice(-4); + } else { + res += str[i]; + } + } + + return res; + } // /////////////////////////// Quad store serialization + // @para. write - a function taking a single string to be output + // + + + __Serializer.prototype.writeStore = function (write) { + var kb = this.store; + var fetcher = kb.fetcher; + var session = fetcher && fetcher.appNode; // The core data + + var sources = this.store.index[3]; + + for (var s in sources) { + // -> assume we can use -> as short for log:semantics + var source = kb.fromNT(s); + if (session && source.equals(session)) continue; + write('\n' + this.atomicTermToN3(source) + ' ' + this.atomicTermToN3(kb.sym('http://www.w3.org/2000/10/swap/log#semantics')) + ' { ' + this.statementsToN3(kb.statementsMatching(undefined, undefined, undefined, source)) + ' }.\n'); + } // The metadata from HTTP interactions: + + + kb.statementsMatching(undefined, kb.sym('http://www.w3.org/2007/ont/link#requestedURI')).map(function (st) { + write('\n<' + st.object.value + '> log:metadata {\n'); + var sts = kb.statementsMatching(undefined, undefined, undefined, st.subject); + write(this.statementsToN3(this.statementsToN3(sts))); + write('}.\n'); + }); // Inferences we have made ourselves not attributable to anyone else + + var metaSources = []; + if (session) metaSources.push(session); + var metadata = []; + metaSources.map(function (source) { + metadata = metadata.concat(kb.statementsMatching(undefined, undefined, undefined, source)); + }); + write(this.statementsToN3(metadata)); + }; // ////////////////////////////////////////////// XML serialization + + + __Serializer.prototype.statementsToXML = function (sts) { + var indent = 4; + var width = 80; + var namespaceCounts = []; // which have been used + + namespaceCounts['http://www.w3.org/1999/02/22-rdf-syntax-ns#'] = true; + var liPrefix = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#_'; // prefix for ordered list items + // //////////////////////// Arrange the bits of XML text + + var spaces = function spaces(n) { + var s = ''; + + for (var i = 0; i < n; i++) { + s += ' '; + } + + return s; + }; + + var XMLtreeToLine = function XMLtreeToLine(tree) { + var str = ''; + + for (var i = 0; i < tree.length; i++) { + var branch = tree[i]; + var s2 = typeof branch === 'string' ? branch : XMLtreeToLine(branch); + str += s2; + } + + return str; + }; // Convert a nested tree of lists and strings to a string + + + var XMLtreeToString = function XMLtreeToString(tree, level) { + var str = ''; + var line; + var lastLength = 100000; + if (!level) level = 0; + + for (var i = 0; i < tree.length; i++) { + var branch = tree[i]; + + if (typeof branch !== 'string') { + var substr = XMLtreeToString(branch, level + 1); + + if (substr.length < 10 * (width - indent * level) && substr.indexOf('"""') < 0) { + // Don't mess up multiline strings + line = XMLtreeToLine(branch); + + if (line.length < width - indent * level) { + branch = ' ' + line; // @@ Hack: treat as string below + + substr = ''; + } + } + + if (substr) lastLength = 10000; + str += substr; + } + + if (typeof branch === 'string') { + if (lastLength < indent * level + 4) { + // continue + str = str.slice(0, -1) + ' ' + branch + '\n'; + lastLength += branch.length + 1; + } else { + line = spaces(indent * level) + branch; + str += line + '\n'; + lastLength = line.length; + } + } else {// not string + } + } + + return str; + }; + + function statementListToXMLTreeMethod(statements) { + this.suggestPrefix('rdf', 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'); + var stats = this.rootSubjects(statements); + var roots = stats.roots; + var results = []; + + for (var i = 0; i < roots.length; i++) { + var root = roots[i]; + results.push(subjectXMLTree(root, stats)); + } + + return results; + } + + var statementListToXMLTree = statementListToXMLTreeMethod.bind(this); + + function escapeForXML(str) { + if (typeof str === 'undefined') return '@@@undefined@@@@'; + return str.replace(/[&<"]/g, function (m) { + switch (m[0]) { + case '&': + return '&'; + + case '<': + return '<'; + + case '"': + return '"'; + // ' + } + }); + } + + function relURIMethod(term) { + return escapeForXML(this.base ? _utils_js__WEBPACK_IMPORTED_MODULE_3__["uri"].refTo(this.base, term.uri) : term.uri); + } + + var relURI = relURIMethod.bind(this); // The tree for a subject + + function subjectXMLTreeMethod(subject, stats) { + var results = []; + var type, t, st, pred; + var sts = stats.subjects[this.toStr(subject)]; // relevant statements + + if (typeof sts === 'undefined') { + // empty bnode + return propertyXMLTree(subject, stats); + } // Sort only on the predicate, leave the order at object + // level undisturbed. This leaves multilingual content in + // the order of entry (for partner literals), which helps + // readability. + // + // For the predicate sort, we attempt to split the uri + // as a hint to the sequence + + + sts.sort(function (a, b) { + var ap = a.predicate.uri; + var bp = b.predicate.uri; + + if (ap.substring(0, liPrefix.length) === liPrefix || bp.substring(0, liPrefix.length) === liPrefix) { + // we're only interested in sorting list items + return ap.localeCompare(bp); + } + + var as = ap.substring(liPrefix.length); + var bs = bp.substring(liPrefix.length); + var an = parseInt(as, 10); + var bn = parseInt(bs, 10); + + if (isNaN(an) || isNaN(bn) || an !== as || bn !== bs) { + // we only care about integers + return ap.localeCompare(bp); + } + + return an - bn; + }); + + for (var i = 0; i < sts.length; i++) { + st = sts[i]; // look for a type + + if (st.predicate.uri === 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type' && !type && st.object.termType === 'symbol') { + type = st.object; + continue; // don't include it as a child element + } // see whether predicate can be replaced with "li" + + + pred = st.predicate; + + if (pred.uri.substr(0, liPrefix.length) === liPrefix) { + var number = pred.uri.substr(liPrefix.length); // make sure these are actually numeric list items + + var intNumber = parseInt(number, 10); + + if (number === intNumber.toString()) { + // was numeric; don't need to worry about ordering since we've already + // sorted the statements + pred = this.rdfFactory.namedNode('http://www.w3.org/1999/02/22-rdf-syntax-ns#li'); + } + } + + t = qname(pred); + + switch (st.object.termType) { + case 'BlankNode': + if (stats.incoming[st.object].length === 1) { + // there should always be something in the incoming array for a bnode + results = results.concat(['<' + t + ' rdf:parseType="Resource">', subjectXMLTree(st.object, stats), '']); + } else { + results = results.concat(['<' + t + ' rdf:nodeID="' + st.object.toNT().slice(2) + '"/>']); + } + + break; + + case 'NamedNode': + results = results.concat(['<' + t + ' rdf:resource="' + relURI(st.object) + '"/>']); + break; + + case 'Literal': + results = results.concat(['<' + t + (st.object.datatype.equals(this.xsd.string) ? '' : ' rdf:datatype="' + escapeForXML(st.object.datatype.uri) + '"') + (st.object.language ? ' xml:lang="' + st.object.language + '"' : '') + '>' + escapeForXML(st.object.value) + '']); + break; + + case 'Collection': + results = results.concat(['<' + t + ' rdf:parseType="Collection">', collectionXMLTree(st.object, stats), '']); + break; + + default: + throw new Error("Can't serialize object of type " + st.object.termType + ' into XML'); + } // switch + + } + + var tag = type ? qname(type) : 'rdf:Description'; + var attrs = ''; + + if (subject.termType === 'BlankNode') { + if (!stats.incoming[subject] || stats.incoming[subject].length !== 1) { + // not an anonymous bnode + attrs = ' rdf:nodeID="' + subject.toNT().slice(2) + '"'; + } + } else { + attrs = ' rdf:about="' + relURI(subject) + '"'; + } + + return ['<' + tag + attrs + '>'].concat([results]).concat(['']); + } + + var subjectXMLTree = subjectXMLTreeMethod.bind(this); + + function collectionXMLTree(subject, stats) { + var res = []; + + for (var i = 0; i < subject.elements.length; i++) { + res.push(subjectXMLTree(subject.elements[i], stats)); + } + + return res; + } // The property tree for a single subject or anonymos node + + + function propertyXMLTreeMethod(subject, stats) { + var results = []; + var sts = stats.subjects[this.toStr(subject)]; // relevant statements + + if (!sts) return results; // No relevant statements + + sts.sort(); + + for (var i = 0; i < sts.length; i++) { + var st = sts[i]; + + switch (st.object.termType) { + case 'BlankNode': + if (stats.rootsHash[st.object.toNT()]) { + // This bnode has been done as a root -- no content here @@ what bout first time + results = results.concat(['<' + qname(st.predicate) + ' rdf:nodeID="' + st.object.toNT().slice(2) + '">', '']); + } else { + results = results.concat(['<' + qname(st.predicate) + ' rdf:parseType="Resource">', propertyXMLTree(st.object, stats), '']); + } + + break; + + case 'NamedNode': + results = results.concat(['<' + qname(st.predicate) + ' rdf:resource="' + relURI(st.object) + '"/>']); + break; + + case 'Literal': + results = results.concat(['<' + qname(st.predicate) + (st.object.datatype.equals(this.xsd.string) ? '' : ' rdf:datatype="' + escapeForXML(st.object.datatype.value) + '"') + (st.object.language ? ' xml:lang="' + st.object.language + '"' : '') + '>' + escapeForXML(st.object.value) + '']); + break; + + case 'Collection': + results = results.concat(['<' + qname(st.predicate) + ' rdf:parseType="Collection">', collectionXMLTree(st.object, stats), '']); + break; + + default: + throw new Error("Can't serialize object of type " + st.object.termType + ' into XML'); + } // switch + + } + + return results; + } + + var propertyXMLTree = propertyXMLTreeMethod.bind(this); + + function qnameMethod(term) { + var uri = term.uri; + var j = uri.indexOf('#'); + + if (j < 0 && this.flags.indexOf('/') < 0) { + j = uri.lastIndexOf('/'); + } + + if (j < 0) throw new Error('Cannot make qname out of <' + uri + '>'); + + for (var k = j + 1; k < uri.length; k++) { + if (__Serializer.prototype._notNameChars.indexOf(uri[k]) >= 0) { + throw new Error('Invalid character "' + uri[k] + '" cannot be in XML qname for URI: ' + uri); + } + } + + var localid = uri.slice(j + 1); + var namesp = uri.slice(0, j + 1); + + if (this.defaultNamespace && this.defaultNamespace === namesp && this.flags.indexOf('d') < 0) { + // d -> suppress default + return localid; + } + + var prefix = this.prefixes[namesp]; + if (!prefix) prefix = this.makeUpPrefix(namesp); + namespaceCounts[namesp] = true; + return prefix + ':' + localid; + } + + var qname = qnameMethod.bind(this); // Body of toXML: + + var tree = statementListToXMLTree(sts); + var str = '']; // @@ namespace declrations + + return XMLtreeToString(tree2, -1); + }; // End @@ body + + + var Serializer = function Serializer(store) { + return new __Serializer(store); + }; + + return Serializer; +})()); + +/***/ }), + +/***/ "./node_modules/rdflib/esm/sparql-to-query.js": +/*!****************************************************!*\ + !*** ./node_modules/rdflib/esm/sparql-to-query.js ***! + \****************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return SPARQLToQuery; }); +/* harmony import */ var _log__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./log */ "./node_modules/rdflib/esm/log.js"); +/* harmony import */ var _query__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./query */ "./node_modules/rdflib/esm/query.js"); +// Converting between SPARQL queries and the $rdf query API + +/* + +function SQuery () { + this.terms = [] + return this +} + +STerm.prototype.toString = STerm.val +SQuery.prototype.add = function (str) {this.terms.push()}*/ + + +/** + * @SPARQL: SPARQL text that is converted to a query object which is returned. + * @testMode: testing flag. Prevents loading of sources. + */ + +function SPARQLToQuery(SPARQL, testMode, kb) { + // AJAR_ClearTable() + var variableHash = []; + + function makeVar(name) { + if (variableHash[name]) { + return variableHash[name]; + } + + var newVar = kb.variable(name); + variableHash[name] = newVar; + return newVar; + } // term type functions + + + function isRealText(term) { + return typeof term === 'string' && term.match(/[^ \n\t]/); + } + + function isVar(term) { + return typeof term === 'string' && term.match(/^[\?\$]/); + } + + function fixSymbolBrackets(term) { + if (typeof term === 'string') { + return term.replace(/^</, '<').replace(/>$/, '>'); + } else { + return term; + } + } + + function isSymbol(term) { + return typeof term === 'string' && term.match(/^<[^>]*>$/); + } + + function isBnode(term) { + return typeof term === 'string' && (term.match(/^_:/) || term.match(/^$/)); + } + + function isPrefix(term) { + return typeof term === 'string' && term.match(/:$/); + } + + function isPrefixedSymbol(term) { + return typeof term === 'string' && term.match(/^:|^[^_][^:]*:/); + } + + function getPrefix(term) { + var a = term.split(':'); + return a[0]; + } + + function getSuffix(term) { + var a = term.split(':'); + return a[1]; + } + + function removeBrackets(term) { + if (isSymbol(term)) { + return term.slice(1, term.length - 1); + } else { + return term; + } + } // takes a string and returns an array of strings and Literals in the place of literals + + + function parseLiterals(str) { + // var sin = (str.indexOf(/[ \n]\'/)==-1)?null:str.indexOf(/[ \n]\'/), doub = (str.indexOf(/[ \n]\"/)==-1)?null:str.indexOf(/[ \n]\"/) + var sin = str.indexOf("'") === -1 ? null : str.indexOf("'"); + var doub = str.indexOf('"') === -1 ? null : str.indexOf('"'); // alert("S: "+sin+" D: "+doub) + + if (!sin && !doub) { + var a = new Array(1); + a[0] = str; + return a; + } + + var res = new Array(2); + var br; + var ind; + + if (!sin || doub && doub < sin) { + br = '"'; + ind = doub; + } else if (!doub || sin && sin < doub) { + br = "'"; + ind = sin; + } else { + _log__WEBPACK_IMPORTED_MODULE_0__["default"].error('SQARQL QUERY OOPS!'); + return res; + } + + res[0] = str.slice(0, ind); + var end = str.slice(ind + 1).indexOf(br); + + if (end === -1) { + _log__WEBPACK_IMPORTED_MODULE_0__["default"].error('SPARQL parsing error: no matching parentheses in literal ' + str); + return str; + } // alert(str.slice(end + ind + 2).match(/^\^\^/)) + + + var end2; + + if (str.slice(end + ind + 2).match(/^\^\^/)) { + end2 = str.slice(end + ind + 2).indexOf(' '); // alert(end2) + + res[1] = kb.literal(str.slice(ind + 1, ind + 1 + end), kb.sym(removeBrackets(str.slice(ind + 4 + end, ind + 2 + end + end2)))); // alert(res[1].datatype.uri) + + res = res.concat(parseLiterals(str.slice(end + ind + 3 + end2))); + } else if (str.slice(end + ind + 2).match(/^@/)) { + end2 = str.slice(end + ind + 2).indexOf(' '); // alert(end2) + + res[1] = kb.literal(str.slice(ind + 1, ind + 1 + end), str.slice(ind + 3 + end, ind + 2 + end + end2), null); // alert(res[1].datatype.uri) + + res = res.concat(parseLiterals(str.slice(end + ind + 2 + end2))); + } else { + res[1] = kb.literal(str.slice(ind + 1, ind + 1 + end)); + _log__WEBPACK_IMPORTED_MODULE_0__["default"].info('Literal found: ' + res[1]); + res = res.concat(parseLiterals(str.slice(end + ind + 2))); // finds any other literals + } + + return res; + } + + function spaceDelimit(str) { + str = str.replace(/\(/g, ' ( ').replace(/\)/g, ' ) ').replace(//g, '> ').replace(/{/g, ' { ').replace(/}/g, ' } ').replace(/[\t\n\r]/g, ' ').replace(/; /g, ' ; ').replace(/\. /g, ' . ').replace(/, /g, ' , '); + _log__WEBPACK_IMPORTED_MODULE_0__["default"].info('New str into spaceDelimit: \n' + str); + var res = []; + var br = str.split(' '); + + for (var x in br) { + if (isRealText(br[x])) { + res = res.concat(br[x]); + } + } + + return res; + } + + function replaceKeywords(input) { + var strarr = input; + + for (var x = 0; x < strarr.length; x++) { + if (strarr[x] === 'a') { + strarr[x] = ''; + } + + if (strarr[x] === 'is' && strarr[x + 2] === 'of') { + strarr.splice(x, 1); + strarr.splice(x + 1, 1); + var s = strarr[x - 1]; + strarr[x - 1] = strarr[x + 1]; + strarr[x + 1] = s; + } + } + + return strarr; + } + + function toTerms(input) { + var res = []; + + for (var x = 0; x < input.length; x++) { + if (typeof input[x] !== 'string') { + res[x] = input[x]; + continue; + } + + input[x] = fixSymbolBrackets(input[x]); + + if (isVar(input[x])) { + res[x] = makeVar(input[x].slice(1)); + } else if (isBnode(input[x])) { + _log__WEBPACK_IMPORTED_MODULE_0__["default"].info(input[x] + ' was identified as a bnode.'); + res[x] = kb.bnode(); + } else if (isSymbol(input[x])) { + _log__WEBPACK_IMPORTED_MODULE_0__["default"].info(input[x] + ' was identified as a symbol.'); + res[x] = kb.sym(removeBrackets(input[x])); + } else if (isPrefixedSymbol(input[x])) { + _log__WEBPACK_IMPORTED_MODULE_0__["default"].info(input[x] + ' was identified as a prefixed symbol'); + + if (prefixes[getPrefix(input[x])]) { + res[x] = kb.sym(input[x] = prefixes[getPrefix(input[x])] + getSuffix(input[x])); + } else { + _log__WEBPACK_IMPORTED_MODULE_0__["default"].error('SPARQL error: ' + input[x] + ' with prefix ' + getPrefix(input[x]) + ' does not have a correct prefix entry.'); + res[x] = input[x]; + } + } else { + res[x] = input[x]; + } + } + + return res; + } + + function tokenize(str) { + var token1 = parseLiterals(str); + var token2 = []; + + for (var x in token1) { + if (typeof token1[x] === 'string') { + token2 = token2.concat(spaceDelimit(token1[x])); + } else { + token2 = token2.concat(token1[x]); + } + } + + token2 = replaceKeywords(token2); + _log__WEBPACK_IMPORTED_MODULE_0__["default"].info('SPARQL Tokens: ' + token2); + return token2; + } // CASE-INSENSITIVE + + + function arrayIndexOf(str, arr) { + for (var i = 0; i < arr.length; i++) { + if (typeof arr[i] !== 'string') { + continue; + } + + if (arr[i].toLowerCase() === str.toLowerCase()) { + return i; + } + } // log.warn("No instance of "+str+" in array "+arr) + + + return null; + } // CASE-INSENSITIVE + + + function arrayIndicesOf(str, arr) { + var ind = []; + + for (var i = 0; i < arr.length; i++) { + if (typeof arr[i] !== 'string') { + continue; + } + + if (arr[i].toLowerCase() === str.toLowerCase()) { + ind.push(i); + } + } + + return ind; + } + + function setVars(input, query) { + _log__WEBPACK_IMPORTED_MODULE_0__["default"].info('SPARQL vars: ' + input); + + for (var x in input) { + if (isVar(input[x])) { + _log__WEBPACK_IMPORTED_MODULE_0__["default"].info('Added ' + input[x] + ' to query variables from SPARQL'); + var v = makeVar(input[x].slice(1)); + query.vars.push(v); + v.label = input[x].slice(1); + } else { + _log__WEBPACK_IMPORTED_MODULE_0__["default"].warn('Incorrect SPARQL variable in SELECT: ' + input[x]); + } + } + } + + function getPrefixDeclarations(input) { + var prefInd = arrayIndicesOf('PREFIX', input); + var res = []; + + for (var i in prefInd) { + var a = input[prefInd[i] + 1]; + var b = input[prefInd[i] + 2]; + + if (!isPrefix(a)) { + _log__WEBPACK_IMPORTED_MODULE_0__["default"].error('Invalid SPARQL prefix: ' + a); + } else if (!isSymbol(b)) { + _log__WEBPACK_IMPORTED_MODULE_0__["default"].error('Invalid SPARQL symbol: ' + b); + } else { + _log__WEBPACK_IMPORTED_MODULE_0__["default"].info('Prefix found: ' + a + ' -> ' + b); + var pref = getPrefix(a); + var symbol = removeBrackets(b); + res[pref] = symbol; + } + } + + return res; + } + + function getMatchingBracket(arr, open, close) { + _log__WEBPACK_IMPORTED_MODULE_0__["default"].info('Looking for a close bracket of type ' + close + ' in ' + arr); + var index = 0; + + for (var i = 0; i < arr.length; i++) { + if (arr[i] === open) { + index++; + } + + if (arr[i] === close) { + index--; + } + + if (index < 0) { + return i; + } + } + + _log__WEBPACK_IMPORTED_MODULE_0__["default"].error('Statement had no close parenthesis in SPARQL query'); + return 0; + } + + function constraintGreaterThan(value) { + this.describe = function (varstr) { + return varstr + ' > ' + value.toNT(); + }; + + this.test = function (term) { + if (term.value.match(/[0-9]+(\.[0-9]+)?([eE][+-]?[0-9]+)?/)) { + return parseFloat(term.value) > parseFloat(value); + } else { + return term.toNT() > value.toNT(); + } + }; + + return this; + } + + function constraintLessThan(value) { + // this is not the recommended usage. Should only work on literal, numeric, dateTime + this.describe = function (varstr) { + return varstr + ' < ' + value.toNT(); + }; + + this.test = function (term) { + // this.describe = function (varstr) { return varstr + " < "+value } + if (term.value.match(/[0-9]+(\.[0-9]+)?([eE][+-]?[0-9]+)?/)) { + return parseFloat(term.value) < parseFloat(value); + } else { + return term.toNT() < value.toNT(); + } + }; + + return this; + } // This should only work on literals but doesn't. + + + function ConstraintEqualTo(value) { + this.describe = function (varstr) { + return varstr + ' = ' + value.toNT(); + }; + + this.test = function (term) { + return value.equals(term); + }; + + return this; + } // value must be a literal + + + function ConstraintRegexp(value) { + this.describe = function (varstr) { + return "REGEXP( '" + value + "' , " + varstr + ' )'; + }; + + this.test = function (term) { + var str = value; // str = str.replace(/^//,"").replace(//$/,"") + + var rg = new RegExp(str); + + if (term.value) { + return rg.test(term.value); + } else { + return false; + } + }; + } + + function setConstraint(input, pat) { + if (input.length === 3 && input[0].termType === 'Variable' && (input[2].termType === 'NamedNode' || input[2].termType === 'Literal')) { + if (input[1] === '=') { + _log__WEBPACK_IMPORTED_MODULE_0__["default"].debug('Constraint added: ' + input); + pat.constraints[input[0]] = new ConstraintEqualTo(input[2]); + } else if (input[1] === '>') { + _log__WEBPACK_IMPORTED_MODULE_0__["default"].debug('Constraint added: ' + input); + pat.constraints[input[0]] = new ConstraintEqualTo(input[2]); + } else if (input[1] === '<') { + _log__WEBPACK_IMPORTED_MODULE_0__["default"].debug('Constraint added: ' + input); + pat.constraints[input[0]] = new ConstraintEqualTo(input[2]); + } else { + _log__WEBPACK_IMPORTED_MODULE_0__["default"].warn("I don't know how to handle the constraint: " + input); + } + } else if (input.length === 6 && typeof input[0] === 'string' && input[0].toLowerCase() === 'regexp' && input[1] === '(' && input[5] === ')' && input[3] === ',' && input[4].termType === 'Variable' && input[2].termType === 'Literal') { + _log__WEBPACK_IMPORTED_MODULE_0__["default"].debug('Constraint added: ' + input); + pat.constraints[input[4]] = new ConstraintRegexp(input[2].value); + } // log.warn("I don't know how to handle the constraint: "+input) + // alert("length: "+input.length+" input 0 type: "+input[0].termType+" input 1: "+input[1]+" input[2] type: "+input[2].termType) + + } + + function setOptional(terms, pat) { + _log__WEBPACK_IMPORTED_MODULE_0__["default"].debug('Optional query: ' + terms + ' not yet implemented.'); + var opt = kb.formula(); + setWhere(terms, opt); + pat.optional.push(opt); + } + + function setWhere(input, pat) { + var terms = toTerms(input); + var end; + _log__WEBPACK_IMPORTED_MODULE_0__["default"].debug('WHERE: ' + terms); + var opt; // var opt = arrayIndicesOf("OPTIONAL",terms) + + while (arrayIndexOf('OPTIONAL', terms)) { + opt = arrayIndexOf('OPTIONAL', terms); + _log__WEBPACK_IMPORTED_MODULE_0__["default"].debug('OPT: ' + opt + ' ' + terms[opt] + ' in ' + terms); + + if (terms[opt + 1] !== '{') { + _log__WEBPACK_IMPORTED_MODULE_0__["default"].warn('Bad optional opening bracket in word ' + opt); + } + + end = getMatchingBracket(terms.slice(opt + 2), '{', '}'); + + if (end === -1) { + _log__WEBPACK_IMPORTED_MODULE_0__["default"].error('No matching bracket in word ' + opt); + } else { + setOptional(terms.slice(opt + 2, opt + 2 + end), pat); // alert(pat.statements[0].toNT()) + + opt = arrayIndexOf('OPTIONAL', terms); + end = getMatchingBracket(terms.slice(opt + 2), '{', '}'); + terms.splice(opt, end + 3); + } + } + + _log__WEBPACK_IMPORTED_MODULE_0__["default"].debug('WHERE after optionals: ' + terms); + + while (arrayIndexOf('FILTER', terms)) { + var filt = arrayIndexOf('FILTER', terms); + + if (terms[filt + 1] !== '(') { + _log__WEBPACK_IMPORTED_MODULE_0__["default"].warn('Bad filter opening bracket in word ' + filt); + } + + end = getMatchingBracket(terms.slice(filt + 2), '(', ')'); + + if (end === -1) { + _log__WEBPACK_IMPORTED_MODULE_0__["default"].error('No matching bracket in word ' + filt); + } else { + setConstraint(terms.slice(filt + 2, filt + 2 + end), pat); + filt = arrayIndexOf('FILTER', terms); + end = getMatchingBracket(terms.slice(filt + 2), '(', ')'); + terms.splice(filt, end + 3); + } + } + + _log__WEBPACK_IMPORTED_MODULE_0__["default"].debug('WHERE after filters and optionals: ' + terms); + extractStatements(terms, pat); + } + + function extractStatements(terms, formula) { + var arrayZero = new Array(1); + arrayZero[0] = -1; // this is just to add the beginning of the where to the periods index. + + var per = arrayZero.concat(arrayIndicesOf('.', terms)); + var stat = []; + + for (var x = 0; x < per.length - 1; x++) { + stat[x] = terms.slice(per[x] + 1, per[x + 1]); + } // Now it's in an array of statements + + + for (x in stat) { + // THIS MUST BE CHANGED FOR COMMA, SEMICOLON + _log__WEBPACK_IMPORTED_MODULE_0__["default"].info('s+p+o ' + x + ' = ' + stat[x]); + var subj = stat[x][0]; + stat[x].splice(0, 1); + var sem = arrayZero.concat(arrayIndicesOf(';', stat[x])); + sem.push(stat[x].length); + var stat2 = []; + + for (var y = 0; y < sem.length - 1; y++) { + stat2[y] = stat[x].slice(sem[y] + 1, sem[y + 1]); + } + + for (x in stat2) { + _log__WEBPACK_IMPORTED_MODULE_0__["default"].info('p+o ' + x + ' = ' + stat[x]); + var pred = stat2[x][0]; + stat2[x].splice(0, 1); + var com = arrayZero.concat(arrayIndicesOf(',', stat2[x])); + com.push(stat2[x].length); + var stat3 = []; + + for (y = 0; y < com.length - 1; y++) { + stat3[y] = stat2[x].slice(com[y] + 1, com[y + 1]); + } + + for (x in stat3) { + var obj = stat3[x][0]; + _log__WEBPACK_IMPORTED_MODULE_0__["default"].info('Subj=' + subj + ' Pred=' + pred + ' Obj=' + obj); + formula.add(subj, pred, obj); + } + } + } + } // ******************************* Body of SPARQLToQuery ***************************// + + + _log__WEBPACK_IMPORTED_MODULE_0__["default"].info('SPARQL input: \n' + SPARQL); + var q = new _query__WEBPACK_IMPORTED_MODULE_1__["Query"](); + var sp = tokenize(SPARQL); // first tokenize everything + + var prefixes = getPrefixDeclarations(sp); + + if (!prefixes.rdf) { + prefixes.rdf = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'; + } + + if (!prefixes.rdfs) { + prefixes.rdfs = 'http://www.w3.org/2000/01/rdf-schema#'; + } + + var selectLoc = arrayIndexOf('SELECT', sp); + var whereLoc = arrayIndexOf('WHERE', sp); + + if (selectLoc < 0 || whereLoc < 0 || selectLoc > whereLoc) { + _log__WEBPACK_IMPORTED_MODULE_0__["default"].error('Invalid or nonexistent SELECT and WHERE tags in SPARQL query'); + return false; + } + + setVars(sp.slice(selectLoc + 1, whereLoc), q); + setWhere(sp.slice(whereLoc + 2, sp.length - 1), q.pat); + + if (testMode) { + return q; + } + + for (var x in q.pat.statements) { + var st = q.pat.statements[x]; + + if (st.subject.termType === 'NamedNode') { + if (kb.fetcher) { + kb.fetcher.lookUpThing(st.subject, 'sparql:' + st.subject); + } + } + + if (st.object.termType === 'NamedNode') { + if (kb.fetcher) { + kb.fetcher.lookUpThing(st.object, 'sparql:' + st.object); + } + } + } // alert(q.pat) + + + return q; // checkVars() + // *******************************************************************// +} + +/***/ }), + +/***/ "./node_modules/rdflib/esm/statement.js": +/*!**********************************************!*\ + !*** ./node_modules/rdflib/esm/statement.js ***! + \**********************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return Statement; }); +/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js"); +/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js"); +/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__); +/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "./node_modules/@babel/runtime/helpers/defineProperty.js"); +/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_2__); +/* harmony import */ var _node_internal__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./node-internal */ "./node_modules/rdflib/esm/node-internal.js"); +/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./types */ "./node_modules/rdflib/esm/types.js"); +/* harmony import */ var _default_graph__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./default-graph */ "./node_modules/rdflib/esm/default-graph.js"); + + + + + + +var defaultGraph = new _default_graph__WEBPACK_IMPORTED_MODULE_5__["default"](); +/** A Statement represents an RDF Triple or Quad. */ + +var Statement = /*#__PURE__*/function () { + /** The subject of the triple. What the Statement is about. */ + + /** The relationship which is asserted between the subject and object */ + + /** The thing or data value which is asserted to be related to the subject */ + + /** + * The graph param is a named node of the document in which the triple when + * it is stored on the web. + */ + + /** + * Construct a new statement + * + * @param subject - The subject of the triple. What the fact is about + * @param predicate - The relationship which is asserted between the subject and object + * @param object - The thing or data value which is asserted to be related to the subject + * @param {NamedNode} graph - The document where the triple is or was or will be stored on the web. + * + * The graph param is a named node of the document in which the triple when it is stored + * on the web. It exists because when you have read data from various places in the web, + * the “graph” tells you _why_ you have the triple. (At the moment, it is just the + * document, in future it could be an inference step) + * + * When you do UpdateManager.update() then the graph’s of all the statements must be the same, + * and give the document you are patching. In future, we may have a more + * powerful update() which can update more than one document. + */ + function Statement(subject, predicate, object, graph) { + _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, Statement); + + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_2___default()(this, "subject", void 0); + + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_2___default()(this, "predicate", void 0); + + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_2___default()(this, "object", void 0); + + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_2___default()(this, "graph", void 0); + + this.subject = _node_internal__WEBPACK_IMPORTED_MODULE_3__["default"].fromValue(subject); + this.predicate = _node_internal__WEBPACK_IMPORTED_MODULE_3__["default"].fromValue(predicate); + this.object = _node_internal__WEBPACK_IMPORTED_MODULE_3__["default"].fromValue(object); + this.graph = graph == undefined ? defaultGraph : _node_internal__WEBPACK_IMPORTED_MODULE_3__["default"].fromValue(graph); // property currently used by rdflib + } + /** Alias for graph, favored by Tim */ + + + _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default()(Statement, [{ + key: "equals", + + /** + * Checks whether two statements are the same + * @param other - The other statement + */ + value: function equals(other) { + return other.subject.equals(this.subject) && other.predicate.equals(this.predicate) && other.object.equals(this.object) && other.graph.equals(this.graph); + } + /** + * Creates a statement with the bindings substituted + * @param bindings The bindings + */ + + }, { + key: "substitute", + value: function substitute(bindings) { + var y = new Statement(this.subject.substitute(bindings), this.predicate.substitute(bindings), this.object.substitute(bindings), Object(_default_graph__WEBPACK_IMPORTED_MODULE_5__["isDefaultGraph"])(this.graph) ? this.graph : this.graph.substitute(bindings)); // 2016 + + console.log('@@@ statement substitute:' + y); + return y; + } + /** Creates a canonical string representation of this statement. */ + + }, { + key: "toCanonical", + value: function toCanonical() { + var terms = [this.subject.toCanonical(), this.predicate.toCanonical(), this.object.toCanonical()]; + + if (this.graph && this.graph.termType !== _types__WEBPACK_IMPORTED_MODULE_4__["DefaultGraphTermType"]) { + terms.push(this.graph.toCanonical()); + } + + return terms.join(' ') + ' .'; + } + /** Creates a n-triples string representation of this statement */ + + }, { + key: "toNT", + value: function toNT() { + return [this.subject.toNT(), this.predicate.toNT(), this.object.toNT()].join(' ') + ' .'; + } + /** Creates a n-quads string representation of this statement */ + + }, { + key: "toNQ", + value: function toNQ() { + return [this.subject.toNT(), this.predicate.toNT(), this.object.toNT(), Object(_default_graph__WEBPACK_IMPORTED_MODULE_5__["isDefaultGraph"])(this.graph) ? '' : this.graph.toNT()].join(' ') + ' .'; + } + /** Creates a string representation of this statement */ + + }, { + key: "toString", + value: function toString() { + return this.toNT(); + } + }, { + key: "why", + get: function get() { + return this.graph; + }, + set: function set(g) { + this.graph = g; + } + }]); + + return Statement; +}(); + + + +/***/ }), + +/***/ "./node_modules/rdflib/esm/store.js": +/*!******************************************!*\ + !*** ./node_modules/rdflib/esm/store.js ***! + \******************************************/ +/*! exports provided: defaultGraphURI, default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return IndexedFormula; }); +/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js"); +/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js"); +/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__); +/* harmony import */ var _babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/assertThisInitialized */ "./node_modules/@babel/runtime/helpers/assertThisInitialized.js"); +/* harmony import */ var _babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__); +/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/inherits */ "./node_modules/@babel/runtime/helpers/inherits.js"); +/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3__); +/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "./node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"); +/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__); +/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "./node_modules/@babel/runtime/helpers/getPrototypeOf.js"); +/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__); +/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "./node_modules/@babel/runtime/helpers/defineProperty.js"); +/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__); +/* harmony import */ var _class_order__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./class-order */ "./node_modules/rdflib/esm/class-order.js"); +/* harmony import */ var _factories_canonical_data_factory__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./factories/canonical-data-factory */ "./node_modules/rdflib/esm/factories/canonical-data-factory.js"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "defaultGraphURI", function() { return _factories_canonical_data_factory__WEBPACK_IMPORTED_MODULE_8__["defaultGraphURI"]; }); + +/* harmony import */ var _formula__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./formula */ "./node_modules/rdflib/esm/formula.js"); +/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./utils */ "./node_modules/rdflib/esm/utils.js"); +/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./utils-js */ "./node_modules/rdflib/esm/utils-js.js"); +/* harmony import */ var _utils_terms__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./utils/terms */ "./node_modules/rdflib/esm/utils/terms.js"); +/* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./node */ "./node_modules/rdflib/esm/node.js"); +/* harmony import */ var _variable__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./variable */ "./node_modules/rdflib/esm/variable.js"); +/* harmony import */ var _query__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./query */ "./node_modules/rdflib/esm/query.js"); +/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./types */ "./node_modules/rdflib/esm/types.js"); +/* harmony import */ var _named_node__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./named-node */ "./node_modules/rdflib/esm/named-node.js"); +/* harmony import */ var _index__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./index */ "./node_modules/rdflib/esm/index.js"); +/* harmony import */ var _blank_node__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ./blank-node */ "./node_modules/rdflib/esm/blank-node.js"); +/* harmony import */ var _default_graph__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ./default-graph */ "./node_modules/rdflib/esm/default-graph.js"); +/* harmony import */ var _literal__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ./literal */ "./node_modules/rdflib/esm/literal.js"); + + + + + + + + +function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = o[Symbol.iterator](); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } + +function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } + +function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } + +function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5___default()(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5___default()(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4___default()(this, result); }; } + +function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } + +/* Identity management and indexing for RDF + * + * This file provides IndexedFormula a formula (set of triples) which + * indexed by predicate, subject and object. + * + * It "smushes" (merges into a single node) things which are identical + * according to owl:sameAs or an owl:InverseFunctionalProperty + * or an owl:FunctionalProperty + * + * + * 2005-10 Written Tim Berners-Lee + * 2007 Changed so as not to munge statements from documents when smushing + * 2019 Converted to typescript + * + * +*/ + +/** @module store */ + + + + + + + + + + + + + + + +var owlNamespaceURI = 'http://www.w3.org/2002/07/owl#'; + // var link_ns = 'http://www.w3.org/2007/ont/link#' +// Handle Functional Property + +function handleFP(formula, subj, pred, obj) { + var o1 = formula.any(subj, pred, undefined); + + if (!o1) { + return false; // First time with this value + } // log.warn("Equating "+o1.uri+" and "+obj.uri + " because FP "+pred.uri); //@@ + + + formula.equate(o1, obj); + return true; +} // handleFP +// Handle Inverse Functional Property + + +function handleIFP(formula, subj, pred, obj) { + var s1 = formula.any(undefined, pred, obj); + + if (!s1) { + return false; // First time with this value + } // log.warn("Equating "+s1.uri+" and "+subj.uri + " because IFP "+pred.uri); //@@ + + + formula.equate(s1, subj); + return true; +} // handleIFP + + +function handleRDFType(formula, subj, pred, obj, why) { + //@ts-ignore this method does not seem to exist in this library + if (formula.typeCallback) { + formula.typeCallback(formula, obj, why); + } + + var x = formula.classActions[formula.id(obj)]; + var done = false; + + if (x) { + for (var i = 0; i < x.length; i++) { + done = done || x[i](formula, subj, pred, obj, why); + } + } + + return done; // statement given is not needed if true +} +/** + * Indexed Formula aka Store + */ + + +var IndexedFormula = /*#__PURE__*/function (_Formula) { + _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3___default()(IndexedFormula, _Formula); + + var _super = _createSuper(IndexedFormula); + + // IN future - allow pass array of statements to constructor + + /** + * An UpdateManager initialised to this store + */ + + /** + * Dictionary of namespace prefixes + */ + + /** Map of iri predicates to functions to call when adding { s type X } */ + + /** Map of iri predicates to functions to call when getting statement with {s X o} */ + + /** Redirect to lexically smaller equivalent symbol */ + + /** Reverse mapping to redirection: aliases for this */ + + /** Redirections we got from HTTP */ + + /** Array of statements with this X as subject */ + + /** Array of statements with this X as predicate */ + + /** Array of statements with this X as object */ + + /** Array of statements with X as provenance */ + + /** Function to remove quads from the store arrays with */ + + /** Callbacks which are triggered after a statement has been added to the store */ + + /** + * Creates a new formula + * @param features - What sort of autmatic processing to do? Array of string + * @param features.sameAs - Smush together A and B nodes whenever { A sameAs B } + * @param opts + * @param [opts.rdfFactory] - The data factory that should be used by the store + * @param [opts.rdfArrayRemove] - Function which removes statements from the store + * @param [opts.dataCallback] - Callback when a statement is added to the store, will not trigger when adding duplicates + */ + function IndexedFormula(features) { + var _this; + + var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, IndexedFormula); + + _this = _super.call(this, undefined, undefined, undefined, undefined, opts); + + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6___default()(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2___default()(_this), "updater", void 0); + + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6___default()(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2___default()(_this), "namespaces", void 0); + + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6___default()(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2___default()(_this), "classActions", void 0); + + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6___default()(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2___default()(_this), "propertyActions", void 0); + + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6___default()(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2___default()(_this), "redirections", void 0); + + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6___default()(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2___default()(_this), "aliases", void 0); + + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6___default()(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2___default()(_this), "HTTPRedirects", void 0); + + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6___default()(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2___default()(_this), "subjectIndex", void 0); + + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6___default()(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2___default()(_this), "predicateIndex", void 0); + + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6___default()(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2___default()(_this), "objectIndex", void 0); + + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6___default()(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2___default()(_this), "whyIndex", void 0); + + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6___default()(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2___default()(_this), "index", void 0); + + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6___default()(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2___default()(_this), "features", void 0); + + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6___default()(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2___default()(_this), "_universalVariables", void 0); + + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6___default()(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2___default()(_this), "_existentialVariables", void 0); + + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6___default()(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2___default()(_this), "rdfArrayRemove", void 0); + + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6___default()(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2___default()(_this), "dataCallbacks", void 0); + + _this.propertyActions = {}; + _this.classActions = {}; + _this.redirections = []; + _this.aliases = []; + _this.HTTPRedirects = []; + _this.subjectIndex = []; + _this.predicateIndex = []; + _this.objectIndex = []; + _this.whyIndex = []; + _this.index = [_this.subjectIndex, _this.predicateIndex, _this.objectIndex, _this.whyIndex]; + _this.namespaces = {}; // Dictionary of namespace prefixes + + _this.features = features || ['sameAs', 'InverseFunctionalProperty', 'FunctionalProperty']; + _this.rdfArrayRemove = opts.rdfArrayRemove || _utils_js__WEBPACK_IMPORTED_MODULE_11__["RDFArrayRemove"]; + + if (opts.dataCallback) { + _this.dataCallbacks = [opts.dataCallback]; + } + + _this.initPropertyActions(_this.features); + + return _this; + } + /** + * Gets the URI of the default graph + */ + + + _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default()(IndexedFormula, [{ + key: "substitute", + + /** + * Gets this graph with the bindings substituted + * @param bindings The bindings + */ + value: function substitute(bindings) { + var statementsCopy = this.statements.map(function (ea) { + return ea.substitute(bindings); + }); + var y = new IndexedFormula(); + y.add(statementsCopy); + return y; + } + /** + * Add a callback which will be triggered after a statement has been added to the store. + * @param cb + */ + + }, { + key: "addDataCallback", + value: function addDataCallback(cb) { + if (!this.dataCallbacks) { + this.dataCallbacks = []; + } + + this.dataCallbacks.push(cb); + } + /** + * Apply a set of statements to be deleted and to be inserted + * + * @param patch - The set of statements to be deleted and to be inserted + * @param target - The name of the document to patch + * @param patchCallback - Callback to be called when patching is complete + */ + + }, { + key: "applyPatch", + value: function applyPatch(patch, target, patchCallback) { + var targetKB = this; + var ds; + var binding = null; + + function doPatch(onDonePatch) { + if (patch['delete']) { + ds = patch['delete']; // console.log(bindingDebug(binding)) + // console.log('ds before substitute: ' + ds) + + if (binding) ds = ds.substitute(binding); // console.log('applyPatch: delete: ' + ds) + + ds = ds.statements; + var bad = []; + var ds2 = ds.map(function (st) { + // Find the actual statemnts in the store + var sts = targetKB.statementsMatching(st.subject, st.predicate, st.object, target); + + if (sts.length === 0) { + // log.info("NOT FOUND deletable " + st) + bad.push(st); + return null; + } else { + // log.info("Found deletable " + st) + return sts[0]; + } + }); + + if (bad.length) { + // console.log('Could not find to delete ' + bad.length + 'statements') + // console.log('despite ' + targetKB.statementsMatching(bad[0].subject, bad[0].predicate)[0]) + return patchCallback('Could not find to delete: ' + bad.join('\n or ')); + } + + ds2.map(function (st) { + targetKB.remove(st); + }); + } + + if (patch['insert']) { + // log.info("doPatch insert "+patch['insert']) + ds = patch['insert']; + if (binding) ds = ds.substitute(binding); + ds = ds.statements; + ds.map(function (st) { + st.graph = target; + targetKB.add(st.subject, st.predicate, st.object, st.graph); + }); + } + + onDonePatch(); + } + + if (patch.where) { + // log.info("Processing WHERE: " + patch.where + '\n') + var query = new _query__WEBPACK_IMPORTED_MODULE_15__["Query"]('patch'); + query.pat = patch.where; + query.pat.statements.map(function (st) { + st.graph = Object(_index__WEBPACK_IMPORTED_MODULE_18__["namedNode"])(target.value); + }); //@ts-ignore TODO: add sync property to Query when converting Query to typescript + + query.sync = true; + var bindingsFound = []; + targetKB.query(query, function onBinding(binding) { + bindingsFound.push(binding); // console.log(' got a binding: ' + bindingDebug(binding)) + }, targetKB.fetcher, function onDone() { + if (bindingsFound.length === 0) { + return patchCallback('No match found to be patched:' + patch.where); + } + + if (bindingsFound.length > 1) { + return patchCallback('Patch ambiguous. No patch done.'); + } + + binding = bindingsFound[0]; + doPatch(patchCallback); + }); + } else { + doPatch(patchCallback); + } + } + /** + * N3 allows for declaring blank nodes, this function enables that support + * + * @param x The blank node to be declared, supported in N3 + */ + + }, { + key: "declareExistential", + value: function declareExistential(x) { + if (!this._existentialVariables) this._existentialVariables = []; + + this._existentialVariables.push(x); + + return x; + } + /** + * @param features + */ + + }, { + key: "initPropertyActions", + value: function initPropertyActions(features) { + // If the predicate is #type, use handleRDFType to create a typeCallback on the object + this.propertyActions[this.rdfFactory.id(this.rdfFactory.namedNode('http://www.w3.org/1999/02/22-rdf-syntax-ns#type'))] = [handleRDFType]; // Assumption: these terms are not redirected @@fixme + + if (Object(_utils__WEBPACK_IMPORTED_MODULE_10__["ArrayIndexOf"])(features, 'sameAs') >= 0) { + this.propertyActions[this.rdfFactory.id(this.rdfFactory.namedNode("".concat(owlNamespaceURI, "sameAs")))] = [function (formula, subj, pred, obj, why) { + // log.warn("Equating "+subj.uri+" sameAs "+obj.uri); //@@ + formula.equate(subj, obj); + return true; // true if statement given is NOT needed in the store + }]; // sameAs -> equate & don't add to index + } + + if (Object(_utils__WEBPACK_IMPORTED_MODULE_10__["ArrayIndexOf"])(features, 'InverseFunctionalProperty') >= 0) { + this.classActions[this.rdfFactory.id(this.rdfFactory.namedNode("".concat(owlNamespaceURI, "InverseFunctionalProperty")))] = [function (formula, subj, pred, obj, addFn) { + // yes subj not pred! + return formula.newPropertyAction(subj, handleIFP); + }]; // IFP -> handleIFP, do add to index + } + + if (Object(_utils__WEBPACK_IMPORTED_MODULE_10__["ArrayIndexOf"])(features, 'FunctionalProperty') >= 0) { + this.classActions[this.rdfFactory.id(this.rdfFactory.namedNode("".concat(owlNamespaceURI, "FunctionalProperty")))] = [function (formula, subj, proj, obj, addFn) { + return formula.newPropertyAction(subj, handleFP); + }]; // FP => handleFP, do add to index + } + } + /** @deprecated Use {add} instead */ + + }, { + key: "addStatement", + value: function addStatement(st) { + this.add(st.subject, st.predicate, st.object, st.graph); + return this.statements.length; + } + /** + * Adds a triple (quad) to the store. + * + * @param subj - The thing about which the fact a relationship is asserted. + * Also accepts a statement or an array of Statements. + * @param pred - The relationship which is asserted + * @param obj - The object of the relationship, e.g. another thing or avalue. If passed a string, this will become a literal. + * @param why - The document in which the triple (S,P,O) was or will be stored on the web + * @returns The statement added to the store, or the store + */ + + }, { + key: "add", + value: function add(subj, pred, obj, why) { + var i; + + if (arguments.length === 1) { + if (subj instanceof Array) { + for (i = 0; i < subj.length; i++) { + this.add(subj[i]); + } + } else if (Object(_utils_terms__WEBPACK_IMPORTED_MODULE_12__["isQuad"])(subj)) { + this.add(subj.subject, subj.predicate, subj.object, subj.graph); + } else if (Object(_utils_terms__WEBPACK_IMPORTED_MODULE_12__["isStore"])(subj)) { + this.add(subj.statements); + } + + return this; + } + + var actions; + var st; + + if (!why) { + // system generated + why = this.fetcher ? this.fetcher.appNode : this.rdfFactory.defaultGraph(); + } + + if (typeof subj == 'string') { + subj = this.rdfFactory.namedNode(subj); + } + + pred = _node__WEBPACK_IMPORTED_MODULE_13__["default"].fromValue(pred); + var objNode = _node__WEBPACK_IMPORTED_MODULE_13__["default"].fromValue(obj); + why = _node__WEBPACK_IMPORTED_MODULE_13__["default"].fromValue(why); + + if (!Object(_utils_terms__WEBPACK_IMPORTED_MODULE_12__["isSubject"])(subj)) { + throw new Error('Subject is not a subject type'); + } + + if (!Object(_utils_terms__WEBPACK_IMPORTED_MODULE_12__["isPredicate"])(pred)) { + throw new Error("Predicate ".concat(pred, " is not a predicate type")); + } + + if (!Object(_utils_terms__WEBPACK_IMPORTED_MODULE_12__["isRDFlibObject"])(objNode)) { + throw new Error("Object ".concat(objNode, " is not an object type")); + } + + if (!Object(_utils_terms__WEBPACK_IMPORTED_MODULE_12__["isGraph"])(why)) { + throw new Error("Why is not a graph type"); + } //@ts-ignore This is not used internally + + + if (this.predicateCallback) { + //@ts-ignore This is not used internally + this.predicateCallback(this, pred, why); + } // Action return true if the statement does not need to be added + + + var predHash = this.id(this.canon(pred)); + actions = this.propertyActions[predHash]; // Predicate hash + + var done = false; + + if (actions) { + // alert('type: '+typeof actions +' @@ actions='+actions) + for (i = 0; i < actions.length; i++) { + done = done || actions[i](this, subj, pred, objNode, why); + } + } + + if (this.holds(subj, pred, objNode, why)) { + // Takes time but saves duplicates + // console.log('rdflib: Ignoring dup! {' + subj + ' ' + pred + ' ' + obj + ' ' + why + '}') + return null; // @@better to return self in all cases? + } // If we are tracking provenance, every thing should be loaded into the store + // if (done) return this.rdfFactory.quad(subj, pred, obj, why) + // Don't put it in the store + // still return this statement for owl:sameAs input + + + var hash = [this.id(this.canon(subj)), predHash, this.id(this.canon(objNode)), this.id(this.canon(why))]; // @ts-ignore this will fail if you pass a collection and the factory does not allow Collections + + st = this.rdfFactory.quad(subj, pred, objNode, why); + + for (i = 0; i < 4; i++) { + var ix = this.index[i]; + var h = hash[i]; + + if (!ix[h]) { + ix[h] = []; + } + + ix[h].push(st); // Set of things with this as subject, etc + } // log.debug("ADDING {"+subj+" "+pred+" "+objNode+"} "+why) + + + this.statements.push(st); + + if (this.dataCallbacks) { + var _iterator = _createForOfIteratorHelper(this.dataCallbacks), + _step; + + try { + for (_iterator.s(); !(_step = _iterator.n()).done;) { + var callback = _step.value; + callback(st); + } + } catch (err) { + _iterator.e(err); + } finally { + _iterator.f(); + } + } + + return st; + } + /** + * Returns the symbol with canonical URI as smushed + * @param term - An RDF node + */ + + }, { + key: "canon", + value: function canon(term) { + if (!term) { + // @@ TODO Should improve this to return proper value - doing this to keep it backward compatible + return term; + } + + var y = this.redirections[this.id(term)]; + + if (y) { + return y; + } + + switch (term.termType) { + case _types__WEBPACK_IMPORTED_MODULE_16__["BlankNodeTermType"]: + return new _blank_node__WEBPACK_IMPORTED_MODULE_19__["default"](term.value); + + case _types__WEBPACK_IMPORTED_MODULE_16__["CollectionTermType"]: + return term; + // non-RDF/JS type, should just need to cast + + case _types__WEBPACK_IMPORTED_MODULE_16__["DefaultGraphTermType"]: + return new _default_graph__WEBPACK_IMPORTED_MODULE_20__["default"](); + + case _types__WEBPACK_IMPORTED_MODULE_16__["EmptyTermType"]: + // non-RDF/JS type, should just need to cast + return term; + + case _types__WEBPACK_IMPORTED_MODULE_16__["GraphTermType"]: + // non-RDF/JS type, should just need to cast + return term; + + case _types__WEBPACK_IMPORTED_MODULE_16__["LiteralTermType"]: + return new _literal__WEBPACK_IMPORTED_MODULE_21__["default"](term.value, term.language, term.datatype); + + case _types__WEBPACK_IMPORTED_MODULE_16__["NamedNodeTermType"]: + return new _named_node__WEBPACK_IMPORTED_MODULE_17__["default"](term.value); + + case _types__WEBPACK_IMPORTED_MODULE_16__["VariableTermType"]: + return new _variable__WEBPACK_IMPORTED_MODULE_14__["default"](term.value); + + default: + throw new Error("Term Type not recognized for canonization: ".concat(term.termType)); + } + } + /** + * Checks this formula for consistency + */ + + }, { + key: "check", + value: function check() { + this.checkStatementList(this.statements); + + for (var p = 0; p < 4; p++) { + var ix = this.index[p]; + + for (var key in ix) { + if (ix.hasOwnProperty(key)) { + // @ts-ignore should this pass an array or a single statement? checkStateMentsList expects an array. + this.checkStatementList(ix[key], p); + } + } + } + } + /** + * Checks a list of statements for consistency + * @param sts - The list of statements to check + * @param from - An index with the array ['subject', 'predicate', 'object', 'why'] + */ + + }, { + key: "checkStatementList", + value: function checkStatementList(sts, from) { + if (from === undefined) { + from = 0; + } + + var names = ['subject', 'predicate', 'object', 'why']; + var origin = ' found in ' + names[from] + ' index.'; + var st; + + for (var j = 0; j < sts.length; j++) { + st = sts[j]; + var term = [st.subject, st.predicate, st.object, st.graph]; + + var arrayContains = function arrayContains(a, x) { + for (var i = 0; i < a.length; i++) { + if (a[i].subject.equals(x.subject) && a[i].predicate.equals(x.predicate) && a[i].object.equals(x.object) && a[i].why.equals(x.graph)) { + return true; + } + } + }; + + for (var p = 0; p < 4; p++) { + var c = this.canon(term[p]); + var h = this.id(c); + + if (!this.index[p][h]) {// throw new Error('No ' + name[p] + ' index for statement ' + st + '@' + st.why + origin) + } else { + if (!arrayContains(this.index[p][h], st)) {// throw new Error('Index for ' + name[p] + ' does not have statement ' + st + '@' + st.why + origin) + } + } + } + + if (!arrayContains(this.statements, st)) { + throw new Error('Statement list does not statement ' + st + '@' + st.graph + origin); + } + } + } + /** + * Closes this formula (and return it) + */ + + }, { + key: "close", + value: function close() { + return this; + } + }, { + key: "compareTerms", + value: function compareTerms(u1, u2) { + // Keep compatibility with downstream classOrder changes + if (Object.prototype.hasOwnProperty.call(u1, "compareTerm")) { + return u1.compareTerm(u2); + } + + if (_class_order__WEBPACK_IMPORTED_MODULE_7__["default"][u1.termType] < _class_order__WEBPACK_IMPORTED_MODULE_7__["default"][u2.termType]) { + return -1; + } + + if (_class_order__WEBPACK_IMPORTED_MODULE_7__["default"][u1.termType] > _class_order__WEBPACK_IMPORTED_MODULE_7__["default"][u2.termType]) { + return +1; + } + + if (u1.value < u2.value) { + return -1; + } + + if (u1.value > u2.value) { + return +1; + } + + return 0; + } + /** + * replaces @template with @target and add appropriate triples + * removes no triples by default and is a one-direction replication + * @param template node to copy + * @param target node to copy to + * @param flags Whether or not to do a two-directional copy and/or delete triples + */ + + }, { + key: "copyTo", + value: function copyTo(template, target, flags) { + if (!flags) flags = []; + var statList = this.statementsMatching(template); + + if (Object(_utils__WEBPACK_IMPORTED_MODULE_10__["ArrayIndexOf"])(flags, 'two-direction') !== -1) { + statList.concat(this.statementsMatching(undefined, undefined, template)); + } + + for (var i = 0; i < statList.length; i++) { + var st = statList[i]; + + switch (st.object.termType) { + case 'NamedNode': + this.add(target, st.predicate, st.object); + break; + + case 'Literal': + case 'BlankNode': // @ts-ignore Collections can appear here + + case 'Collection': + // @ts-ignore Possible bug: copy is not available on Collections + this.add(target, st.predicate, st.object.copy(this)); + } + + if (Object(_utils__WEBPACK_IMPORTED_MODULE_10__["ArrayIndexOf"])(flags, 'delete') !== -1) { + this.remove(st); + } + } + } + /** + * Simplify graph in store when we realize two identifiers are equivalent + * We replace the bigger with the smaller. + * @param u1in The first node + * @param u2in The second node + */ + + }, { + key: "equate", + value: function equate(u1in, u2in) { + // log.warn("Equating "+u1+" and "+u2); // @@ + // @@JAMBO Must canonicalize the uris to prevent errors from a=b=c + // 03-21-2010 + var u1 = this.canon(u1in); + var u2 = this.canon(u2in); + var d = this.compareTerms(u1, u2); + + if (!d) { + return true; // No information in {a = a} + } // var big + // var small + + + if (d < 0) { + // u1 less than u2 + return this.replaceWith(u2, u1); + } else { + return this.replaceWith(u1, u2); + } + } + /** + * Creates a new empty indexed formula + * Only applicable for IndexedFormula, but TypeScript won't allow a subclass to override a property + * @param features The list of features + */ + + }, { + key: "formula", + value: function formula(features) { + return new IndexedFormula(features); + } + /** + * Returns the number of statements contained in this IndexedFormula. + * (Getter proxy to this.statements). + * Usage: + * ``` + * var kb = rdf.graph() + * kb.length // -> 0 + * ``` + * @returns {Number} + */ + + }, { + key: "match", + + /** + * Returns any quads matching the given arguments. + * Standard RDFJS spec method for Source objects, implemented as an + * alias to `statementsMatching()` + * @param subject The subject + * @param predicate The predicate + * @param object The object + * @param graph The graph that contains the statement + */ + value: function match(subject, predicate, object, graph) { + return this.statementsMatching(_node__WEBPACK_IMPORTED_MODULE_13__["default"].fromValue(subject), _node__WEBPACK_IMPORTED_MODULE_13__["default"].fromValue(predicate), _node__WEBPACK_IMPORTED_MODULE_13__["default"].fromValue(object), _node__WEBPACK_IMPORTED_MODULE_13__["default"].fromValue(graph)); + } + /** + * Find out whether a given URI is used as symbol in the formula + * @param uri The URI to look for + */ + + }, { + key: "mentionsURI", + value: function mentionsURI(uri) { + var hash = '<' + uri + '>'; + return !!this.subjectIndex[hash] || !!this.objectIndex[hash] || !!this.predicateIndex[hash]; + } + /** + * Existentials are BNodes - something exists without naming + * @param uri An URI + */ + + }, { + key: "newExistential", + value: function newExistential(uri) { + if (!uri) return this.bnode(); + var x = this.sym(uri); // @ts-ignore x should be blanknode, but is namedNode. + + return this.declareExistential(x); + } + /** + * Adds a new property action + * @param pred the predicate that the function should be triggered on + * @param action the function that should trigger + */ + + }, { + key: "newPropertyAction", + value: function newPropertyAction(pred, action) { + // log.debug("newPropertyAction: "+pred) + var hash = this.id(pred); + + if (!this.propertyActions[hash]) { + this.propertyActions[hash] = []; + } + + this.propertyActions[hash].push(action); // Now apply the function to to statements already in the store + + var toBeFixed = this.statementsMatching(undefined, pred, undefined); + var done = false; + + for (var i = 0; i < toBeFixed.length; i++) { + // NOT optimized - sort toBeFixed etc + done = done || action(this, toBeFixed[i].subject, pred, toBeFixed[i].object); + } + + return done; + } + /** + * Creates a new universal node + * Universals are Variables + * @param uri An URI + */ + + }, { + key: "newUniversal", + value: function newUniversal(uri) { + var x = this.sym(uri); + if (!this._universalVariables) this._universalVariables = []; + + this._universalVariables.push(x); + + return x; + } // convenience function used by N3 parser + + }, { + key: "variable", + value: function variable(name) { + return new _variable__WEBPACK_IMPORTED_MODULE_14__["default"](name); + } + /** + * Find an unused id for a file being edited: return a symbol + * (Note: Slow iff a lot of them -- could be O(log(k)) ) + * @param doc A document named node + */ + + }, { + key: "nextSymbol", + value: function nextSymbol(doc) { + for (var i = 0;; i++) { + var uri = doc.value + '#n' + i; + if (!this.mentionsURI(uri)) return this.sym(uri); + } + } + /** + * Query this store asynchronously, return bindings in callback + * + * @param myQuery The query to be run + * @param callback Function to call when bindings + * @param Fetcher | null If you want the query to do link following + * @param onDone OBSOLETE - do not use this // @@ Why not ?? Called when query complete + */ + + }, { + key: "query", + value: function query(myQuery, callback, fetcher, onDone) { + return _query__WEBPACK_IMPORTED_MODULE_15__["indexedFormulaQuery"].call(this, myQuery, callback, fetcher, onDone); + } + /** + * Query this store synchronously and return bindings + * + * @param myQuery The query to be run + */ + + }, { + key: "querySync", + value: function querySync(myQuery) { + var results = []; + + function saveBinginds(bindings) { + results.push(bindings); + } + + function onDone() { + done = true; + } + + var done = false; // @ts-ignore TODO: Add .sync to Query + + myQuery.sync = true; + _query__WEBPACK_IMPORTED_MODULE_15__["indexedFormulaQuery"].call(this, myQuery, saveBinginds, null, onDone); + + if (!done) { + throw new Error('Sync query should have called done function'); + } + + return results; + } + /** + * Removes one or multiple statement(s) from this formula + * @param st - A Statement or array of Statements to remove + */ + + }, { + key: "remove", + value: function remove(st) { + if (st instanceof Array) { + for (var i = 0; i < st.length; i++) { + this.remove(st[i]); + } + + return this; + } + + if (Object(_utils_terms__WEBPACK_IMPORTED_MODULE_12__["isStore"])(st)) { + return this.remove(st.statements); + } + + var sts = this.statementsMatching(st.subject, st.predicate, st.object, st.graph); + + if (!sts.length) { + throw new Error('Statement to be removed is not on store: ' + st); + } + + this.removeStatement(sts[0]); + return this; + } + /** + * Removes all statemnts in a doc + * @param doc - The document / graph + */ + + }, { + key: "removeDocument", + value: function removeDocument(doc) { + var sts = this.statementsMatching(undefined, undefined, undefined, doc).slice(); // Take a copy as this is the actual index + + for (var i = 0; i < sts.length; i++) { + this.removeStatement(sts[i]); + } + + return this; + } + /** + * Remove all statements matching args (within limit) * + * @param subj The subject + * @param pred The predicate + * @param obj The object + * @param why The graph that contains the statement + * @param limit The number of statements to remove + */ + + }, { + key: "removeMany", + value: function removeMany(subj, pred, obj, why, limit) { + // log.debug("entering removeMany w/ subj,pred,obj,why,limit = " + subj +", "+ pred+", " + obj+", " + why+", " + limit) + var sts = this.statementsMatching(subj, pred, obj, why, false); // This is a subtle bug that occcured in updateCenter.js too. + // The fact is, this.statementsMatching returns this.whyIndex instead of a copy of it + // but for perfromance consideration, it's better to just do that + // so make a copy here. + + var statements = []; + + for (var i = 0; i < sts.length; i++) { + statements.push(sts[i]); + } + + if (limit) statements = statements.slice(0, limit); + + for (i = 0; i < statements.length; i++) { + this.remove(statements[i]); + } + } + /** + * Remove all matching statements + * @param subject The subject + * @param predicate The predicate + * @param object The object + * @param graph The graph that contains the statement + */ + + }, { + key: "removeMatches", + value: function removeMatches(subject, predicate, object, graph) { + this.removeStatements(this.statementsMatching(subject, predicate, object, graph)); + return this; + } + /** + * Remove a particular statement object from the store + * + * @param st - a statement which is already in the store and indexed. + * Make sure you only use this for these. + * Otherwise, you should use remove() above. + */ + + }, { + key: "removeStatement", + value: function removeStatement(st) { + // log.debug("entering remove w/ st=" + st) + var term = [st.subject, st.predicate, st.object, st.graph]; + + for (var p = 0; p < 4; p++) { + var c = this.canon(term[p]); + var h = this.id(c); + + if (!this.index[p][h]) {// log.warn ("Statement removal: no index '+p+': "+st) + } else { + this.rdfArrayRemove(this.index[p][h], st); + } + } + + this.rdfArrayRemove(this.statements, st); + return this; + } + /** + * Removes statements + * @param sts The statements to remove + */ + + }, { + key: "removeStatements", + value: function removeStatements(sts) { + for (var i = 0; i < sts.length; i++) { + this.remove(sts[i]); + } + + return this; + } + /** + * Replace big with small, obsoleted with obsoleting. + */ + + }, { + key: "replaceWith", + value: function replaceWith(big, small) { + // log.debug("Replacing "+big+" with "+small) // this.id(@@ + var oldhash = this.id(big); + var newhash = this.id(small); + + var moveIndex = function moveIndex(ix) { + var oldlist = ix[oldhash]; + + if (!oldlist) { + return; // none to move + } + + var newlist = ix[newhash]; + + if (!newlist) { + ix[newhash] = oldlist; + } else { + ix[newhash] = oldlist.concat(newlist); + } + + delete ix[oldhash]; + }; // the canonical one carries all the indexes + + + for (var i = 0; i < 4; i++) { + moveIndex(this.index[i]); + } + + this.redirections[oldhash] = small; + + if (big.value) { + // @@JAMBO: must update redirections,aliases from sub-items, too. + if (!this.aliases[newhash]) { + this.aliases[newhash] = []; + } + + this.aliases[newhash].push(big); // Back link + + if (this.aliases[oldhash]) { + for (i = 0; i < this.aliases[oldhash].length; i++) { + this.redirections[this.id(this.aliases[oldhash][i])] = small; + this.aliases[newhash].push(this.aliases[oldhash][i]); + } + } + + this.add(small, this.sym('http://www.w3.org/2007/ont/link#uri'), big); // If two things are equal, and one is requested, we should request the other. + + if (this.fetcher) { + this.fetcher.nowKnownAs(big, small); + } + } + + moveIndex(this.classActions); + moveIndex(this.propertyActions); // log.debug("Equate done. "+big+" to be known as "+small) + + return true; // true means the statement does not need to be put in + } + /** + * Return all equivalent URIs by which this is known + * @param x A named node + */ + + }, { + key: "allAliases", + value: function allAliases(x) { + var a = this.aliases[this.id(this.canon(x))] || []; + a.push(this.canon(x)); + return a; + } + /** + * Compare by canonical URI as smushed + * @param x A named node + * @param y Another named node + */ + + }, { + key: "sameThings", + value: function sameThings(x, y) { + if (x.equals(y)) { + return true; + } + + var x1 = this.canon(x); // alert('x1='+x1) + + if (!x1) return false; + var y1 = this.canon(y); // alert('y1='+y1); //@@ + + if (!y1) return false; + return x1.value === y1.value; + } + }, { + key: "setPrefixForURI", + value: function setPrefixForURI(prefix, nsuri) { + // TODO: This is a hack for our own issues, which ought to be fixed + // post-release + // See http://dig.csail.mit.edu/cgi-bin/roundup.cgi/$rdf/issue227 + if (prefix === 'tab' && this.namespaces['tab']) { + return; + } // There are files around with long badly generated prefixes like this + + + if (prefix.slice(0, 2) === 'ns' || prefix.slice(0, 7) === 'default') { + return; + } + + this.namespaces[prefix] = nsuri; + } + /** Search the Store + * + * ALL CONVENIENCE LOOKUP FUNCTIONS RELY ON THIS! + * @param subj - A node to search for as subject, or if null, a wildcard + * @param pred - A node to search for as predicate, or if null, a wildcard + * @param obj - A node to search for as object, or if null, a wildcard + * @param why - A node to search for as graph, or if null, a wildcard + * @param justOne - flag - stop when found one rather than get all of them? + * @returns An array of nodes which match the wildcard position + */ + + }, { + key: "statementsMatching", + value: function statementsMatching(subj, pred, obj, why, justOne) { + // log.debug("Matching {"+subj+" "+pred+" "+obj+"}") + var pat = [subj, pred, obj, why]; + var pattern = []; + var hash = []; + var wild = []; // wildcards + + var given = []; // Not wild + + var p; + var list; + + for (p = 0; p < 4; p++) { + pattern[p] = this.canon(_node__WEBPACK_IMPORTED_MODULE_13__["default"].fromValue(pat[p])); + + if (!pattern[p]) { + wild.push(p); + } else { + given.push(p); + hash[p] = this.id(pattern[p]); + } + } + + if (given.length === 0) { + return this.statements; + } + + if (given.length === 1) { + // Easy too, we have an index for that + p = given[0]; + list = this.index[p][hash[p]]; + + if (list && justOne) { + if (list.length > 1) { + list = list.slice(0, 1); + } + } + + list = list || []; + return list; + } // Now given.length is 2, 3 or 4. + // We hope that the scale-free nature of the data will mean we tend to get + // a short index in there somewhere! + + + var best = 1e10; // really bad + + var iBest; + var i; + + for (i = 0; i < given.length; i++) { + p = given[i]; // Which part we are dealing with + + list = this.index[p][hash[p]]; + + if (!list) { + return []; // No occurrences + } + + if (list.length < best) { + best = list.length; + iBest = i; // (not p!) + } + } // Ok, we have picked the shortest index but now we have to filter it + + + var pBest = given[iBest]; + var possibles = this.index[pBest][hash[pBest]]; + var check = given.slice(0, iBest).concat(given.slice(iBest + 1)); // remove iBest + + var results = []; + var parts = ['subject', 'predicate', 'object', 'why']; + + for (var j = 0; j < possibles.length; j++) { + var st = possibles[j]; + + for (i = 0; i < check.length; i++) { + // for each position to be checked + p = check[i]; + + if (!this.canon(st[parts[p]]).equals(pattern[p])) { + st = null; + break; + } + } + + if (st != null) { + results.push(st); + if (justOne) break; + } + } + + return results; + } + /** + * A list of all the URIs by which this thing is known + * @param term + */ + + }, { + key: "uris", + value: function uris(term) { + var cterm = this.canon(term); + var terms = this.aliases[this.id(cterm)]; + if (!cterm.value) return []; + var res = [cterm.value]; + + if (terms) { + for (var i = 0; i < terms.length; i++) { + res.push(terms[i].uri); + } + } + + return res; + } + }, { + key: "length", + get: function get() { + return this.statements.length; + } + }], [{ + key: "defaultGraphURI", + get: function get() { + return _factories_canonical_data_factory__WEBPACK_IMPORTED_MODULE_8__["defaultGraphURI"]; + } + }]); + + return IndexedFormula; +}(_formula__WEBPACK_IMPORTED_MODULE_9__["default"]); + +_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6___default()(IndexedFormula, "handleRDFType", void 0); + + +IndexedFormula.handleRDFType = handleRDFType; + +/***/ }), + +/***/ "./node_modules/rdflib/esm/types.js": +/*!******************************************!*\ + !*** ./node_modules/rdflib/esm/types.js ***! + \******************************************/ +/*! exports provided: NamedNodeTermType, BlankNodeTermType, LiteralTermType, VariableTermType, DefaultGraphTermType, CollectionTermType, EmptyTermType, GraphTermType, HTMLContentType, JSONLDContentType, N3ContentType, N3LegacyContentType, NQuadsAltContentType, NQuadsContentType, NTriplesContentType, RDFXMLContentType, SPARQLUpdateContentType, TurtleContentType, TurtleLegacyContentType, XHTMLContentType */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NamedNodeTermType", function() { return NamedNodeTermType; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BlankNodeTermType", function() { return BlankNodeTermType; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LiteralTermType", function() { return LiteralTermType; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VariableTermType", function() { return VariableTermType; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DefaultGraphTermType", function() { return DefaultGraphTermType; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CollectionTermType", function() { return CollectionTermType; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EmptyTermType", function() { return EmptyTermType; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GraphTermType", function() { return GraphTermType; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HTMLContentType", function() { return HTMLContentType; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "JSONLDContentType", function() { return JSONLDContentType; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "N3ContentType", function() { return N3ContentType; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "N3LegacyContentType", function() { return N3LegacyContentType; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NQuadsAltContentType", function() { return NQuadsAltContentType; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NQuadsContentType", function() { return NQuadsContentType; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NTriplesContentType", function() { return NTriplesContentType; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RDFXMLContentType", function() { return RDFXMLContentType; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SPARQLUpdateContentType", function() { return SPARQLUpdateContentType; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TurtleContentType", function() { return TurtleContentType; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TurtleLegacyContentType", function() { return TurtleLegacyContentType; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "XHTMLContentType", function() { return XHTMLContentType; }); +var NamedNodeTermType = "NamedNode"; +var BlankNodeTermType = "BlankNode"; +var LiteralTermType = "Literal"; +var VariableTermType = "Variable"; +var DefaultGraphTermType = "DefaultGraph"; // Non-RDF/JS types: + +var CollectionTermType = "Collection"; +var EmptyTermType = "Empty"; +var GraphTermType = "Graph"; +var HTMLContentType = "text/html"; +var JSONLDContentType = "application/ld+json"; +var N3ContentType = "text/n3"; +var N3LegacyContentType = "application/n3"; +var NQuadsAltContentType = "application/nquads"; +var NQuadsContentType = "application/n-quads"; +var NTriplesContentType = "application/n-triples"; +var RDFXMLContentType = "application/rdf+xml"; +var SPARQLUpdateContentType = "application/sparql-update"; +var TurtleContentType = "text/turtle"; +var TurtleLegacyContentType = "application/x-turtle"; +var XHTMLContentType = "application/xhtml+xml"; +/** + * A valid mime type header + */ + +/***/ }), + +/***/ "./node_modules/rdflib/esm/update-manager.js": +/*!***************************************************!*\ + !*** ./node_modules/rdflib/esm/update-manager.js ***! + \***************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return UpdateManager; }); +/* harmony import */ var _babel_runtime_helpers_typeof__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "./node_modules/@babel/runtime/helpers/typeof.js"); +/* harmony import */ var _babel_runtime_helpers_typeof__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_typeof__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js"); +/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_1__); +/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js"); +/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_2__); +/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "./node_modules/@babel/runtime/helpers/defineProperty.js"); +/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_3__); +/* harmony import */ var _store__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./store */ "./node_modules/rdflib/esm/store.js"); +/* harmony import */ var _uri__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./uri */ "./node_modules/rdflib/esm/uri.js"); +/* harmony import */ var _fetcher__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./fetcher */ "./node_modules/rdflib/esm/fetcher.js"); +/* harmony import */ var _namespace__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./namespace */ "./node_modules/rdflib/esm/namespace.js"); +/* harmony import */ var _serializer__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./serializer */ "./node_modules/rdflib/esm/serializer.js"); +/* harmony import */ var _utils_terms__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./utils/terms */ "./node_modules/rdflib/esm/utils/terms.js"); +/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./utils-js */ "./node_modules/rdflib/esm/utils-js.js"); +/* harmony import */ var _utils_termValue__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./utils/termValue */ "./node_modules/rdflib/esm/utils/termValue.js"); + + + + + +function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = o[Symbol.iterator](); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } + +function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } + +function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } + +/* @file Update Manager Class +** +** 2007-07-15 originall sparl update module by Joe Presbrey +** 2010-08-08 TimBL folded in Kenny's WEBDAV +** 2010-12-07 TimBL addred local file write code +*/ + + + + + + + + + + +/** +* The UpdateManager is a helper object for a store. +* Just as a Fetcher provides the store with the ability to read and write, +* the Update Manager provides functionality for making small patches in real time, +* and also looking out for concurrent updates from other agents +*/ +var UpdateManager = /*#__PURE__*/function () { + /** Index of objects for coordinating incoming and outgoing patches */ + + /** Object of namespaces */ + + /** + * @param store - The quadstore to store data and metadata. Created if not passed. + */ + function UpdateManager(store) { + _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_1___default()(this, UpdateManager); + + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_3___default()(this, "store", void 0); + + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_3___default()(this, "ifps", void 0); + + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_3___default()(this, "fps", void 0); + + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_3___default()(this, "patchControl", void 0); + + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_3___default()(this, "ns", void 0); + + store = store || new _store__WEBPACK_IMPORTED_MODULE_4__["default"](); + + if (store.updater) { + throw new Error("You can't have two UpdateManagers for the same store"); + } + + if (!store.fetcher) { + store.fetcher = new _fetcher__WEBPACK_IMPORTED_MODULE_6__["default"](store); + } + + this.store = store; + store.updater = this; + this.ifps = {}; + this.fps = {}; + this.ns = {}; + this.ns.link = Object(_namespace__WEBPACK_IMPORTED_MODULE_7__["default"])('http://www.w3.org/2007/ont/link#'); + this.ns.http = Object(_namespace__WEBPACK_IMPORTED_MODULE_7__["default"])('http://www.w3.org/2007/ont/http#'); + this.ns.httph = Object(_namespace__WEBPACK_IMPORTED_MODULE_7__["default"])('http://www.w3.org/2007/ont/httph#'); + this.ns.ldp = Object(_namespace__WEBPACK_IMPORTED_MODULE_7__["default"])('http://www.w3.org/ns/ldp#'); + this.ns.rdf = Object(_namespace__WEBPACK_IMPORTED_MODULE_7__["default"])('http://www.w3.org/1999/02/22-rdf-syntax-ns#'); + this.ns.rdfs = Object(_namespace__WEBPACK_IMPORTED_MODULE_7__["default"])('http://www.w3.org/2000/01/rdf-schema#'); + this.ns.rdf = Object(_namespace__WEBPACK_IMPORTED_MODULE_7__["default"])('http://www.w3.org/1999/02/22-rdf-syntax-ns#'); + this.ns.owl = Object(_namespace__WEBPACK_IMPORTED_MODULE_7__["default"])('http://www.w3.org/2002/07/owl#'); + this.patchControl = []; + } + + _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_2___default()(UpdateManager, [{ + key: "patchControlFor", + value: function patchControlFor(doc) { + if (!this.patchControl[doc.value]) { + this.patchControl[doc.value] = []; + } + + return this.patchControl[doc.value]; + } + /** + * Tests whether a file is editable. + * Files have to have a specific annotation that they are machine written, + * for safety. + * We don't actually check for write access on files. + * This version only looks at past HTTP requests, does not make new ones. + * + * @returns The method string SPARQL or DAV or + * LOCALFILE or false if known, undefined if not known. + */ + + }, { + key: "editable", + value: function editable(uri, kb) { + if (!uri) { + return false; // Eg subject is bnode, no known doc to write to + } + + if (!kb) { + kb = this.store; + } + + uri = Object(_utils_termValue__WEBPACK_IMPORTED_MODULE_11__["termValue"])(uri); + + if (uri.slice(0, 8) === 'file:///') { + if (kb.holds(this.store.rdfFactory.namedNode(uri), this.store.rdfFactory.namedNode('http://www.w3.org/1999/02/22-rdf-syntax-ns#type'), this.store.rdfFactory.namedNode('http://www.w3.org/2007/ont/link#MachineEditableDocument'))) { + return 'LOCALFILE'; + } // var sts = kb.statementsMatching(kb.sym(uri)) + // console.log('UpdateManager.editable: Not MachineEditableDocument file ' + + // uri + '\n') + // console.log(sts.map((x) => { return (x as Statement).toNT() }).join('\n')) + + + return false; // @@ Would be nifty of course to see whether we actually have write access first. + } + + var request; + var definitive = false; // @ts-ignore passes a string to kb.each, which expects a term. Should this work? + + var requests = kb.each(undefined, this.ns.link('requestedURI'), Object(_uri__WEBPACK_IMPORTED_MODULE_5__["docpart"])(uri)); + var method; + + for (var r = 0; r < requests.length; r++) { + request = requests[r]; + + if (request !== undefined) { + var response = kb.any(request, this.ns.link('response')); + + if (request !== undefined) { + var wacAllow = kb.anyValue(response, this.ns.httph('wac-allow')); + + if (wacAllow) { + var _iterator = _createForOfIteratorHelper(wacAllow.split(',')), + _step; + + try { + for (_iterator.s(); !(_step = _iterator.n()).done;) { + var bit = _step.value; + var lr = bit.split('='); + + if (lr[0].includes('user') && !lr[1].includes('write') && !lr[1].includes('append')) { + // console.log(' editable? excluded by WAC-Allow: ', wacAllow) + return false; + } + } + } catch (err) { + _iterator.e(err); + } finally { + _iterator.f(); + } + } + + var acceptPatch = kb.each(response, this.ns.httph('accept-patch')); + + if (acceptPatch.length) { + for (var i = 0; i < acceptPatch.length; i++) { + method = acceptPatch[i].value.trim(); + if (method.indexOf('application/sparql-update') >= 0) return 'SPARQL'; + } + } + + var authorVia = kb.each(response, this.ns.httph('ms-author-via')); + + if (authorVia.length) { + for (var _i = 0; _i < authorVia.length; _i++) { + method = authorVia[_i].value.trim(); + + if (method.indexOf('SPARQL') >= 0) { + return 'SPARQL'; + } + + if (method.indexOf('DAV') >= 0) { + return 'DAV'; + } + } + } + + var status = kb.each(response, this.ns.http('status')); + + if (status.length) { + for (var _i2 = 0; _i2 < status.length; _i2++) { + // @ts-ignore since statuses should be TFTerms, this should always be false + if (status[_i2] === 200 || status[_i2] === 404) { + definitive = true; // return false // A definitive answer + } + } + } + } else {// console.log('UpdateManager.editable: No response for ' + uri + '\n') + } + } + } + + if (requests.length === 0) {// console.log('UpdateManager.editable: No request for ' + uri + '\n') + } else { + if (definitive) { + return false; // We have got a request and it did NOT say editable => not editable + } + } // console.log('UpdateManager.editable: inconclusive for ' + uri + '\n') + + + return undefined; // We don't know (yet) as we haven't had a response (yet) + } + }, { + key: "anonymize", + value: function anonymize(obj) { + return obj.toNT().substr(0, 2) === '_:' && this.mentioned(obj) ? '?' + obj.toNT().substr(2) : obj.toNT(); + } + }, { + key: "anonymizeNT", + value: function anonymizeNT(stmt) { + return this.anonymize(stmt.subject) + ' ' + this.anonymize(stmt.predicate) + ' ' + this.anonymize(stmt.object) + ' .'; + } + /** + * Returns a list of all bnodes occurring in a statement + * @private + */ + + }, { + key: "statementBnodes", + value: function statementBnodes(st) { + return [st.subject, st.predicate, st.object].filter(function (x) { + return Object(_utils_terms__WEBPACK_IMPORTED_MODULE_9__["isBlankNode"])(x); + }); + } + /** + * Returns a list of all bnodes occurring in a list of statements + * @private + */ + + }, { + key: "statementArrayBnodes", + value: function statementArrayBnodes(sts) { + var bnodes = []; + + for (var i = 0; i < sts.length; i++) { + bnodes = bnodes.concat(this.statementBnodes(sts[i])); + } + + bnodes.sort(); // in place sort - result may have duplicates + + var bnodes2 = []; + + for (var j = 0; j < bnodes.length; j++) { + if (j === 0 || !bnodes[j].equals(bnodes[j - 1])) { + bnodes2.push(bnodes[j]); + } + } + + return bnodes2; + } + /** + * Makes a cached list of [Inverse-]Functional properties + * @private + */ + + }, { + key: "cacheIfps", + value: function cacheIfps() { + this.ifps = {}; + var a = this.store.each(undefined, this.ns.rdf('type'), this.ns.owl('InverseFunctionalProperty')); + + for (var i = 0; i < a.length; i++) { + this.ifps[a[i].value] = true; + } + + this.fps = {}; + a = this.store.each(undefined, this.ns.rdf('type'), this.ns.owl('FunctionalProperty')); + + for (var _i3 = 0; _i3 < a.length; _i3++) { + this.fps[a[_i3].value] = true; + } + } + /** + * Returns a context to bind a given node, up to a given depth + * @private + */ + + }, { + key: "bnodeContext2", + value: function bnodeContext2(x, source, depth) { + // Return a list of statements which indirectly identify a node + // Depth > 1 if try further indirection. + // Return array of statements (possibly empty), or null if failure + var sts = this.store.statementsMatching(undefined, undefined, x, source); // incoming links + + var y; + var res; + + for (var i = 0; i < sts.length; i++) { + if (this.fps[sts[i].predicate.value]) { + y = sts[i].subject; + + if (!y.isBlank) { + return [sts[i]]; + } + + if (depth) { + res = this.bnodeContext2(y, source, depth - 1); + + if (res) { + return res.concat([sts[i]]); + } + } + } + } // outgoing links + + + sts = this.store.statementsMatching(x, undefined, undefined, source); + + for (var _i4 = 0; _i4 < sts.length; _i4++) { + if (this.ifps[sts[_i4].predicate.value]) { + y = sts[_i4].object; + + if (!y.isBlank) { + return [sts[_i4]]; + } + + if (depth) { + res = this.bnodeContext2(y, source, depth - 1); + + if (res) { + return res.concat([sts[_i4]]); + } + } + } + } + + return null; // Failure + } + /** + * Returns the smallest context to bind a given single bnode + * @private + */ + + }, { + key: "bnodeContext1", + value: function bnodeContext1(x, source) { + // Return a list of statements which indirectly identify a node + // Breadth-first + for (var depth = 0; depth < 3; depth++) { + // Try simple first + var con = this.bnodeContext2(x, source, depth); + if (con !== null) return con; + } // If we can't guarantee unique with logic just send all info about node + + + return this.store.connectedStatements(x, source); // was: + // throw new Error('Unable to uniquely identify bnode: ' + x.toNT()) + } + /** + * @private + */ + + }, { + key: "mentioned", + value: function mentioned(x) { + return this.store.statementsMatching(x, null, null, null).length !== 0 || // Don't pin fresh bnodes + this.store.statementsMatching(null, x).length !== 0 || this.store.statementsMatching(null, null, x).length !== 0; + } + /** + * @private + */ + + }, { + key: "bnodeContext", + value: function bnodeContext(bnodes, doc) { + var context = []; + + if (bnodes.length) { + this.cacheIfps(); + + for (var i = 0; i < bnodes.length; i++) { + // Does this occur in old graph? + var bnode = bnodes[i]; + if (!this.mentioned(bnode)) continue; + context = context.concat(this.bnodeContext1(bnode, doc)); + } + } + + return context; + } + /** + * Returns the best context for a single statement + * @private + */ + + }, { + key: "statementContext", + value: function statementContext(st) { + var bnodes = this.statementBnodes(st); + return this.bnodeContext(bnodes, st.graph); + } + /** + * @private + */ + + }, { + key: "contextWhere", + value: function contextWhere(context) { + var updater = this; + return !context || context.length === 0 ? '' : 'WHERE { ' + context.map(function (x) { + return updater.anonymizeNT(x); + }).join('\n') + ' }\n'; + } + /** + * @private + */ + + }, { + key: "fire", + value: function fire(uri, query, callbackFunction) { + var _this = this; + + return Promise.resolve().then(function () { + if (!uri) { + throw new Error('No URI given for remote editing operation: ' + query); + } // console.log('UpdateManager: sending update to <' + uri + '>') + + + var options = { + noMeta: true, + contentType: 'application/sparql-update', + body: query + }; + return _this.store.fetcher.webOperation('PATCH', uri, options); + }).then(function (response) { + if (!response.ok) { + var _message = 'UpdateManager: update failed for <' + uri + '> status=' + response.status + ', ' + response.statusText + '\n for query: ' + query; // console.log(message) + + + throw new Error(_message); + } // console.log('UpdateManager: update Ok for <' + uri + '>') + + + callbackFunction(uri, response.ok, response.responseText, response); + }).catch(function (err) { + callbackFunction(uri, false, err.message, err); + }); + } // ARE THESE THEE FUNCTIONS USED? DEPROCATE? + + /** return a statemnet updating function + * + * This does NOT update the statement. + * It returns an object which includes + * function which can be used to change the object of the statement. + */ + + }, { + key: "update_statement", + value: function update_statement(statement) { + if (statement && !statement.graph) { + return; + } + + var updater = this; + var context = this.statementContext(statement); + return { + statement: statement ? [statement.subject, statement.predicate, statement.object, statement.graph] : undefined, + statementNT: statement ? this.anonymizeNT(statement) : undefined, + where: updater.contextWhere(context), + set_object: function set_object(obj, callbackFunction) { + var query = this.where; + query += 'DELETE DATA { ' + this.statementNT + ' } ;\n'; + query += 'INSERT DATA { ' + // @ts-ignore `this` might refer to the wrong scope. Does this work? + this.anonymize(this.statement[0]) + ' ' + // @ts-ignore + this.anonymize(this.statement[1]) + ' ' + // @ts-ignore + this.anonymize(obj) + ' ' + ' . }\n'; + updater.fire(this.statement[3].value, query, callbackFunction); + } + }; + } + }, { + key: "insert_statement", + value: function insert_statement(st, callbackFunction) { + var st0 = st instanceof Array ? st[0] : st; + var query = this.contextWhere(this.statementContext(st0)); + + if (st instanceof Array) { + var stText = ''; + + for (var i = 0; i < st.length; i++) { + stText += st[i] + '\n'; + } + + query += 'INSERT DATA { ' + stText + ' }\n'; + } else { + query += 'INSERT DATA { ' + this.anonymize(st.subject) + ' ' + this.anonymize(st.predicate) + ' ' + this.anonymize(st.object) + ' ' + ' . }\n'; + } + + this.fire(st0.graph.value, query, callbackFunction); + } + }, { + key: "delete_statement", + value: function delete_statement(st, callbackFunction) { + var st0 = st instanceof Array ? st[0] : st; + var query = this.contextWhere(this.statementContext(st0)); + + if (st instanceof Array) { + var stText = ''; + + for (var i = 0; i < st.length; i++) { + stText += st[i] + '\n'; + } + + query += 'DELETE DATA { ' + stText + ' }\n'; + } else { + query += 'DELETE DATA { ' + this.anonymize(st.subject) + ' ' + this.anonymize(st.predicate) + ' ' + this.anonymize(st.object) + ' ' + ' . }\n'; + } + + this.fire(st0.graph.value, query, callbackFunction); + } /// ////////////////////// + + /** + * Requests a now or future action to refresh changes coming downstream + * This is designed to allow the system to re-request the server version, + * when a websocket has pinged to say there are changes. + * If the websocket, by contrast, has sent a patch, then this may not be necessary. + * + * @param doc + * @param action + */ + + }, { + key: "requestDownstreamAction", + value: function requestDownstreamAction(doc, action) { + var control = this.patchControlFor(doc); + + if (!control.pendingUpstream) { + action(doc); + } else { + if (control.downstreamAction) { + if ('' + control.downstreamAction !== '' + action) { + // Kludge compare + throw new Error("Can't wait for > 1 different downstream actions"); + } + } else { + control.downstreamAction = action; + } + } + } + /** + * We want to start counting websocket notifications + * to distinguish the ones from others from our own. + */ + + }, { + key: "clearUpstreamCount", + value: function clearUpstreamCount(doc) { + var control = this.patchControlFor(doc); + control.upstreamCount = 0; + } + }, { + key: "getUpdatesVia", + value: function getUpdatesVia(doc) { + var linkHeaders = this.store.fetcher.getHeader(doc, 'updates-via'); + if (!linkHeaders || !linkHeaders.length) return null; + return linkHeaders[0].trim(); + } + }, { + key: "addDownstreamChangeListener", + value: function addDownstreamChangeListener(doc, listener) { + var _this2 = this; + + var control = this.patchControlFor(doc); + + if (!control.downstreamChangeListeners) { + control.downstreamChangeListeners = []; + } + + control.downstreamChangeListeners.push(listener); + this.setRefreshHandler(doc, function (doc) { + _this2.reloadAndSync(doc); + }); + } + }, { + key: "reloadAndSync", + value: function reloadAndSync(doc) { + var control = this.patchControlFor(doc); + var updater = this; + + if (control.reloading) { + // console.log(' Already reloading - note this load may be out of date') + control.outOfDate = true; + return; // once only needed @@ Not true, has changed again + } + + control.reloading = true; + var retryTimeout = 1000; // ms + + var tryReload = function tryReload() { + // console.log('try reload - timeout = ' + retryTimeout) + updater.reload(updater.store, doc, function (ok, message, response) { + if (ok) { + if (control.downstreamChangeListeners) { + for (var i = 0; i < control.downstreamChangeListeners.length; i++) { + // console.log(' Calling downstream listener ' + i) + control.downstreamChangeListeners[i](); + } + } + + control.reloading = false; + + if (control.outOfDate) { + // console.log(' Extra reload because of extra update.') + control.outOfDate = false; + tryReload(); + } + } else { + control.reloading = false; + + if (response.status === 0) { + // console.log('Network error refreshing the data. Retrying in ' + + // retryTimeout / 1000) + control.reloading = true; + retryTimeout = retryTimeout * 2; + setTimeout(tryReload, retryTimeout); + } else {// console.log('Error ' + (response as Response).status + 'refreshing the data:' + + // message + '. Stopped' + doc) + } + } + }); + }; + + tryReload(); + } + /** + * Sets up websocket to listen on + * + * There is coordination between upstream changes and downstream ones + * so that a reload is not done in the middle of an upstream patch. + * If you use this API then you get called when a change happens, and you + * have to reload the file yourself, and then refresh the UI. + * Alternative is addDownstreamChangeListener(), where you do not + * have to do the reload yourself. Do mot mix them. + * + * kb contains the HTTP metadata from previous operations + * + * @param doc + * @param handler + * + * @returns {boolean} + */ + + }, { + key: "setRefreshHandler", + value: function setRefreshHandler(doc, handler) { + var wssURI = this.getUpdatesVia(doc); // relative + // var kb = this.store + + var theHandler = handler; + var self = this; + var updater = this; + var retryTimeout = 1500; // *2 will be 3 Seconds, 6, 12, etc + + var retries = 0; + + if (!wssURI) { + // console.log('Server does not support live updates through Updates-Via :-(') + return false; + } + + wssURI = Object(_uri__WEBPACK_IMPORTED_MODULE_5__["join"])(wssURI, doc.value); + var validWssURI = wssURI.replace(/^http:/, 'ws:').replace(/^https:/, 'wss:'); // console.log('Web socket URI ' + wssURI) + + var openWebsocket = function openWebsocket() { + // From https://github.com/solid/solid-spec#live-updates + var socket; + + if (typeof WebSocket !== 'undefined') { + socket = new WebSocket(validWssURI); + } else if (typeof window !== 'undefined' && window.WebSocket) { + socket = window.WebSocket(validWssURI); + } else { + // console.log('Live update disabled, as WebSocket not supported by platform :-(') + return; + } + + socket.onopen = function () { + // console.log(' websocket open') + retryTimeout = 1500; // reset timeout to fast on success + + this.send('sub ' + doc.value); + + if (retries) { + // console.log('Web socket has been down, better check for any news.') + updater.requestDownstreamAction(doc, theHandler); + } + }; + + var control = self.patchControlFor(doc); + control.upstreamCount = 0; + + socket.onerror = function onerror(err) {// console.log('Error on Websocket:', err) + }; // https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent + // + // 1000 CLOSE_NORMAL Normal closure; the connection successfully completed whatever purpose for which it was created. + // 1001 CLOSE_GOING_AWAY The endpoint is going away, either + // because of a server failure or because the browser is navigating away from the page that opened the connection. + // 1002 CLOSE_PROTOCOL_ERROR The endpoint is terminating the connection due to a protocol error. + // 1003 CLOSE_UNSUPPORTED The connection is being terminated because the endpoint + // received data of a type it cannot accept (for example, a text-only endpoint received binary data). + // 1004 Reserved. A meaning might be defined in the future. + // 1005 CLOSE_NO_STATUS Reserved. Indicates that no status code was provided even though one was expected. + // 1006 CLOSE_ABNORMAL Reserved. Used to indicate that a connection was closed abnormally ( + // + // + + + socket.onclose = function (event) { + // console.log('*** Websocket closed with code ' + event.code + + // ", reason '" + event.reason + "' clean = " + event.wasClean) + retryTimeout *= 2; + retries += 1; // console.log('Retrying in ' + retryTimeout + 'ms') // (ask user?) + + setTimeout(function () { + // console.log('Trying websocket again') + openWebsocket(); + }, retryTimeout); + }; + + socket.onmessage = function (msg) { + if (msg.data && msg.data.slice(0, 3) === 'pub') { + if ('upstreamCount' in control) { + control.upstreamCount -= 1; + + if (control.upstreamCount >= 0) { + // console.log('just an echo: ' + control.upstreamCount) + return; // Just an echo + } + } // console.log('Assume a real downstream change: ' + control.upstreamCount + ' -> 0') + + + control.upstreamCount = 0; + self.requestDownstreamAction(doc, theHandler); + } + }; + }; // openWebsocket + + + openWebsocket(); + return true; + } + /** + * This high-level function updates the local store iff the web is changed successfully. + * Deletions, insertions may be undefined or single statements or lists or formulae (may contain bnodes which can be indirectly identified by a where clause). + * The `why` property of each statement must be the give the web document to be updated. + * The statements to be deleted and inserted may span more than one web document. + * @param deletions - Statement or statements to be deleted. + * @param insertions - Statement or statements to be inserted. + * @returns a promise + */ + + }, { + key: "updateMany", + value: function updateMany(deletions, insertions) { + var docs = deletions.concat(insertions).map(function (st) { + return st.why; + }); + var uniqueDocs = Array.from(new Set(docs)); + var thisUpdater = this; + var updates = uniqueDocs.map(function (doc) { + return thisUpdater.update(deletions.filter(function (st) { + return st.why.equals(doc); + }), insertions.filter(function (st) { + return st.why.equals(doc); + })); + }); + console.log(" @@@@@@@ updateMany to: ".concat(updates.length, " ")); + return Promise.all(updates); + } + /** + * This high-level function updates the local store iff the web is changed successfully. + * Deletions, insertions may be undefined or single statements or lists or formulae (may contain bnodes which can be indirectly identified by a where clause). + * The `why` property of each statement must be the same and give the web document to be updated. + * @param deletions - Statement or statements to be deleted. + * @param insertions - Statement or statements to be inserted. + * @param callback - called as callbackFunction(uri, success, errorbody) + * OR returns a promise + */ + + }, { + key: "update", + value: function update(deletions, insertions, callback, secondTry) { + var _this3 = this; + + if (!callback) { + var thisUpdater = this; + return new Promise(function (resolve, reject) { + // Promise version + thisUpdater.update(deletions, insertions, function (uri, ok, errorBody) { + if (!ok) { + reject(new Error(errorBody)); + } else { + resolve(); + } + }); // callbackFunction + }); // promise + } // if + + + try { + var kb = this.store; + var ds = !deletions ? [] : Object(_utils_terms__WEBPACK_IMPORTED_MODULE_9__["isStore"])(deletions) ? deletions.statements : deletions instanceof Array ? deletions : [deletions]; + var is = !insertions ? [] : Object(_utils_terms__WEBPACK_IMPORTED_MODULE_9__["isStore"])(insertions) ? insertions.statements : insertions instanceof Array ? insertions : [insertions]; + + if (!(ds instanceof Array)) { + throw new Error('Type Error ' + _babel_runtime_helpers_typeof__WEBPACK_IMPORTED_MODULE_0___default()(ds) + ': ' + ds); + } + + if (!(is instanceof Array)) { + throw new Error('Type Error ' + _babel_runtime_helpers_typeof__WEBPACK_IMPORTED_MODULE_0___default()(is) + ': ' + is); + } + + if (ds.length === 0 && is.length === 0) { + return callback(null, true); // success -- nothing needed to be done. + } + + var doc = ds.length ? ds[0].graph : is[0].graph; + + if (!doc) { + var _message2 = 'Error patching: statement does not specify which document to patch:' + ds[0] + ', ' + is[0]; // console.log(message) + + + throw new Error(_message2); + } + + var control = this.patchControlFor(doc); + var startTime = Date.now(); + var props = ['subject', 'predicate', 'object', 'why']; + var verbs = ['insert', 'delete']; + var clauses = { + 'delete': ds, + 'insert': is + }; + verbs.map(function (verb) { + clauses[verb].map(function (st) { + if (!doc.equals(st.graph)) { + throw new Error('update: destination ' + doc + ' inconsistent with delete quad ' + st.graph); + } + + props.map(function (prop) { + if (typeof st[prop] === 'undefined') { + throw new Error('update: undefined ' + prop + ' of statement.'); + } + }); + }); + }); + var protocol = this.editable(doc.value, kb); + + if (protocol === false) { + throw new Error('Update: Can\'t make changes in uneditable ' + doc); + } + + if (protocol === undefined) { + // Not enough metadata + if (secondTry) { + throw new Error('Update: Loaded ' + doc + "but stil can't figure out what editing protcol it supports."); + } // console.log(`Update: have not loaded ${doc} before: loading now...`); + + + this.store.fetcher.load(doc).then(function (response) { + _this3.update(deletions, insertions, callback, true); + }, function (err) { + if (err.response.status === 404) { + // nonexistent files are fine + _this3.update(deletions, insertions, callback, true); + } else { + throw new Error("Update: Can't get updatability status ".concat(doc, " before patching: ").concat(err)); + } + }); + return; + } else if (protocol.indexOf('SPARQL') >= 0) { + var bnodes = []; + if (ds.length) bnodes = this.statementArrayBnodes(ds); + if (is.length) bnodes = bnodes.concat(this.statementArrayBnodes(is)); + var context = this.bnodeContext(bnodes, doc); + var whereClause = this.contextWhere(context); + var query = ''; + + if (whereClause.length) { + // Is there a WHERE clause? + if (ds.length) { + query += 'DELETE { '; + + for (var i = 0; i < ds.length; i++) { + query += this.anonymizeNT(ds[i]) + '\n'; + } + + query += ' }\n'; + } + + if (is.length) { + query += 'INSERT { '; + + for (var _i5 = 0; _i5 < is.length; _i5++) { + query += this.anonymizeNT(is[_i5]) + '\n'; + } + + query += ' }\n'; + } + + query += whereClause; + } else { + // no where clause + if (ds.length) { + query += 'DELETE DATA { '; + + for (var _i6 = 0; _i6 < ds.length; _i6++) { + query += this.anonymizeNT(ds[_i6]) + '\n'; + } + + query += ' } \n'; + } + + if (is.length) { + if (ds.length) query += ' ; '; + query += 'INSERT DATA { '; + + for (var _i7 = 0; _i7 < is.length; _i7++) { + query += this.anonymizeNT(is[_i7]) + '\n'; + } + + query += ' }\n'; + } + } // Track pending upstream patches until they have finished their callbackFunction + + + control.pendingUpstream = control.pendingUpstream ? control.pendingUpstream + 1 : 1; + + if ('upstreamCount' in control) { + control.upstreamCount += 1; // count changes we originated ourselves + // console.log('upstream count up to : ' + control.upstreamCount) + } + + this.fire(doc.value, query, function (uri, success, body, response) { + response.elapsedTimeMs = Date.now() - startTime; + console.log(' UpdateManager: Return ' + (success ? 'success ' : 'FAILURE ') + response.status + ' elapsed ' + response.elapsedTimeMs + 'ms'); + + if (success) { + try { + kb.remove(ds); + } catch (e) { + success = false; + body = 'Remote Ok BUT error deleting ' + ds.length + ' from store!!! ' + e; + } // Add in any case -- help recover from weirdness?? + + + for (var _i8 = 0; _i8 < is.length; _i8++) { + kb.add(is[_i8].subject, is[_i8].predicate, is[_i8].object, doc); + } + } + + callback(uri, success, body, response); + control.pendingUpstream -= 1; // When upstream patches have been sent, reload state if downstream waiting + + if (control.pendingUpstream === 0 && control.downstreamAction) { + var downstreamAction = control.downstreamAction; + delete control.downstreamAction; // console.log('delayed downstream action:') + + downstreamAction(doc); + } + }); + } else if (protocol.indexOf('DAV') >= 0) { + this.updateDav(doc, ds, is, callback); + } else { + if (protocol.indexOf('LOCALFILE') >= 0) { + try { + this.updateLocalFile(doc, ds, is, callback); + } catch (e) { + callback(doc.value, false, 'Exception trying to write back file <' + doc.value + '>\n' // + tabulator.Util.stackString(e)) + ); + } + } else { + throw new Error("Unhandled edit method: '" + protocol + "' for " + doc); + } + } + } catch (e) { + callback(undefined, false, 'Exception in update: ' + e + '\n' + _utils_js__WEBPACK_IMPORTED_MODULE_10__["stackString"](e)); + } + } + }, { + key: "updateDav", + value: function updateDav(doc, ds, is, callbackFunction) { + var kb = this.store; // The code below is derived from Kenny's UpdateCenter.js + + var request = kb.any(doc, this.ns.link('request')); + + if (!request) { + throw new Error('No record of our HTTP GET request for document: ' + doc); + } // should not happen + + + var response = kb.any(request, this.ns.link('response')); + + if (!response) { + return null; // throw "No record HTTP GET response for document: "+doc + } + + var contentType = kb.the(response, this.ns.httph('content-type')).value; // prepare contents of revised document + + var newSts = kb.statementsMatching(undefined, undefined, undefined, doc).slice(); // copy! + + for (var i = 0; i < ds.length; i++) { + _utils_js__WEBPACK_IMPORTED_MODULE_10__["RDFArrayRemove"](newSts, ds[i]); + } + + for (var _i9 = 0; _i9 < is.length; _i9++) { + newSts.push(is[_i9]); + } + + var documentString = this.serialize(doc.value, newSts, contentType); // Write the new version back + + var candidateTarget = kb.the(response, this.ns.httph('content-location')); + var targetURI; + + if (candidateTarget) { + targetURI = Object(_uri__WEBPACK_IMPORTED_MODULE_5__["join"])(candidateTarget.value, targetURI); + } + + var options = { + contentType: contentType, + noMeta: true, + body: documentString + }; + return kb.fetcher.webOperation('PUT', targetURI, options).then(function (response) { + if (!response.ok) { + throw new Error(response.error); + } + + for (var _i10 = 0; _i10 < ds.length; _i10++) { + kb.remove(ds[_i10]); + } + + for (var _i11 = 0; _i11 < is.length; _i11++) { + kb.add(is[_i11].subject, is[_i11].predicate, is[_i11].object, doc); + } + + callbackFunction(doc.value, response.ok, response.responseText, response); + }).catch(function (err) { + callbackFunction(doc.value, false, err.message, err); + }); + } + /** + * Likely deprecated, since this lib no longer deals with browser extension + * + * @param doc + * @param ds + * @param is + * @param callbackFunction + */ + + }, { + key: "updateLocalFile", + value: function updateLocalFile(doc, ds, is, callbackFunction) { + var kb = this.store; // console.log('Writing back to local file\n') + // See http://simon-jung.blogspot.com/2007/10/firefox-extension-file-io.html + // prepare contents of revised document + + var newSts = kb.statementsMatching(undefined, undefined, undefined, doc).slice(); // copy! + + for (var i = 0; i < ds.length; i++) { + _utils_js__WEBPACK_IMPORTED_MODULE_10__["RDFArrayRemove"](newSts, ds[i]); + } + + for (var _i12 = 0; _i12 < is.length; _i12++) { + newSts.push(is[_i12]); + } // serialize to the appropriate format + + + var dot = doc.value.lastIndexOf('.'); + + if (dot < 1) { + throw new Error('Rewriting file: No filename extension: ' + doc.value); + } + + var ext = doc.value.slice(dot + 1); + var contentType = _fetcher__WEBPACK_IMPORTED_MODULE_6__["default"].CONTENT_TYPE_BY_EXT[ext]; + + if (!contentType) { + throw new Error('File extension .' + ext + ' not supported for data write'); + } + + var documentString = this.serialize(doc.value, newSts, contentType); // Write the new version back + // create component for file writing + // console.log('Writing back: <<<' + documentString + '>>>') + + var filename = doc.value.slice(7); // chop off file:// leaving /path + // console.log("Writeback: Filename: "+filename+"\n") + // @ts-ignore Where does Component come from? Perhaps deprecated? + + var file = Components.classes['@mozilla.org/file/local;1'] // @ts-ignore Where does Component come from? Perhaps deprecated? + .createInstance(Components.interfaces.nsILocalFile); + file.initWithPath(filename); + + if (!file.exists()) { + throw new Error('Rewriting file <' + doc.value + '> but it does not exist!'); + } // { + // file.create( Components.interfaces.nsIFile.NORMAL_FILE_TYPE, 420) + // } + // create file output stream and use write/create/truncate mode + // 0x02 writing, 0x08 create file, 0x20 truncate length if exist + // @ts-ignore Where does Component come from? Perhaps deprecated? + + + var stream = Components.classes['@mozilla.org/network/file-output-stream;1'] // @ts-ignore Where does Component come from? Perhaps deprecated? + .createInstance(Components.interfaces.nsIFileOutputStream); // Various JS systems object to 0666 in struct mode as dangerous + + stream.init(file, 0x02 | 0x08 | 0x20, parseInt('0666', 8), 0); // write data to file then close output stream + + stream.write(documentString, documentString.length); + stream.close(); + + for (var _i13 = 0; _i13 < ds.length; _i13++) { + kb.remove(ds[_i13]); + } + + for (var _i14 = 0; _i14 < is.length; _i14++) { + kb.add(is[_i14].subject, is[_i14].predicate, is[_i14].object, doc); + } + + callbackFunction(doc.value, true, ''); // success! + } + /** + * @throws {Error} On unsupported content type + * + * @returns {string} + */ + + }, { + key: "serialize", + value: function serialize(uri, data, contentType) { + var kb = this.store; + var documentString; + + if (typeof data === 'string') { + return data; + } // serialize to the appropriate format + + + var sz = Object(_serializer__WEBPACK_IMPORTED_MODULE_8__["default"])(kb); + sz.suggestNamespaces(kb.namespaces); + sz.setBase(uri); + + switch (contentType) { + case 'text/xml': + case 'application/rdf+xml': + documentString = sz.statementsToXML(data); + break; + + case 'text/n3': + case 'text/turtle': + case 'application/x-turtle': // Legacy + + case 'application/n3': + // Legacy + documentString = sz.statementsToN3(data); + break; + + default: + throw new Error('Content-type ' + contentType + ' not supported for data serialization'); + } + + return documentString; + } + /** + * This is suitable for an initial creation of a document. + */ + + }, { + key: "put", + value: function put(doc, data, contentType, callback) { + var _this4 = this; + + var kb = this.store; + var documentString; + return Promise.resolve().then(function () { + documentString = _this4.serialize(doc.value, data, contentType); + return kb.fetcher.webOperation('PUT', doc.value, { + contentType: contentType, + body: documentString + }); + }).then(function (response) { + if (!response.ok) { + return callback(doc.value, response.ok, response.error, response); + } + + delete kb.fetcher.nonexistent[doc.value]; + delete kb.fetcher.requested[doc.value]; // @@ could this mess with the requested state machine? if a fetch is in progress + + if (typeof data !== 'string') { + data.map(function (st) { + kb.addStatement(st); + }); + } + + callback(doc.value, response.ok, '', response); + }).catch(function (err) { + callback(doc.value, false, err.message); + }); + } + /** + * Reloads a document. + * + * Fast and cheap, no metadata. Measure times for the document. + * Load it provisionally. + * Don't delete the statements before the load, or it will leave a broken + * document in the meantime. + * + * @param kb + * @param doc {RDFlibNamedNode} + * @param callbackFunction + */ + + }, { + key: "reload", + value: function reload(kb, doc, callbackFunction) { + var startTime = Date.now(); // force sets no-cache and + + var options = { + force: true, + noMeta: true, + clearPreviousData: true + }; + kb.fetcher.nowOrWhenFetched(doc.value, options, function (ok, body, response) { + if (!ok) { + // console.log(' ERROR reloading data: ' + body) + callbackFunction(false, 'Error reloading data: ' + body, response); //@ts-ignore Where does onErrorWasCalled come from? + } else if (response.onErrorWasCalled || response.status !== 200) { + // console.log(' Non-HTTP error reloading data! onErrorWasCalled=' + + //@ts-ignore Where does onErrorWasCalled come from? + // response.onErrorWasCalled + ' status: ' + response.status) + callbackFunction(false, 'Non-HTTP error reloading data: ' + body, response); + } else { + var elapsedTimeMs = Date.now() - startTime; + if (!doc.reloadTimeTotal) doc.reloadTimeTotal = 0; + if (!doc.reloadTimeCount) doc.reloadTimeCount = 0; + doc.reloadTimeTotal += elapsedTimeMs; + doc.reloadTimeCount += 1; // console.log(' Fetch took ' + elapsedTimeMs + 'ms, av. of ' + + // doc.reloadTimeCount + ' = ' + + // (doc.reloadTimeTotal / doc.reloadTimeCount) + 'ms.') + + callbackFunction(true); + } + }); + } + }]); + + return UpdateManager; +}(); + + + +/***/ }), + +/***/ "./node_modules/rdflib/esm/updates-via.js": +/*!************************************************!*\ + !*** ./node_modules/rdflib/esm/updates-via.js ***! + \************************************************/ +/*! exports provided: UpdatesSocket, UpdatesVia */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "UpdatesSocket", function() { return UpdatesSocket; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "UpdatesVia", function() { return UpdatesVia; }); +/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js"); +/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js"); +/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__); +/* harmony import */ var _factories_rdflib_data_factory__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./factories/rdflib-data-factory */ "./node_modules/rdflib/esm/factories/rdflib-data-factory.js"); + + + +/* + * Updates-Via + */ + +var UpdatesSocket = /*#__PURE__*/function () { + function UpdatesSocket(parent, via) { + _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, UpdatesSocket); + + this.parent = parent; + this.via = via; + this.connected = false; + this.pending = {}; + this.subscribed = {}; + this.socket = {}; + + try { + this.socket = new WebSocket(via); + this.socket.onopen = this.onOpen; + this.socket.onclose = this.onClose; + this.socket.onmessage = this.onMessage; + this.socket.onerror = this.onError; + } catch (error) { + this.onError(error); + } + } + + _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default()(UpdatesSocket, [{ + key: "_decode", + value: function _decode(q) { + var elt; + var i; + var k; + var r; + var ref; + var ref1; + var v; + r = {}; + + ref = function () { + var j, len, ref, results; + ref = q.split('&'); + results = []; + + for (j = 0, len = ref.length; j < len; j++) { + elt = ref[j]; + results.push(elt.split('=')); + } + + return results; + }(); + + for (i in ref) { + elt = ref[i]; + ref1 = [decodeURIComponent(elt[0]), decodeURIComponent(elt[1])]; + k = ref1[0]; + v = ref1[1]; + + if (r[k] == null) { + r[k] = []; + } + + r[k].push(v); + } + + return r; + } + }, { + key: "_send", + value: function _send(method, uri, data) { + var base, message; + message = [method, uri, data].join(' '); + return typeof (base = this.socket).send === 'function' ? base.send(message) : void 0; + } + }, { + key: "_subscribe", + value: function _subscribe(uri) { + this._send('sub', uri, ''); + + this.subscribed[uri] = true; + return this.subscribed[uri]; + } + }, { + key: "onClose", + value: function onClose(e) { + var uri; + this.connected = false; + + for (uri in this.subscribed) { + this.pending[uri] = true; + } + + this.subscribed = {}; + return this.subscribed; + } + }, { + key: "onError", + value: function onError(e) { + throw new Error('onError' + e); + } + }, { + key: "onMessage", + value: function onMessage(e) { + var base, message; + message = e.data.split(' '); + + if (message[0] === 'ping') { + return typeof (base = this.socket).send === 'function' ? base.send('pong ' + message.slice(1).join(' ')) : void 0; + } else if (message[0] === 'pub') { + return this.parent.onUpdate(message[1], this._decode(message[2])); + } + } + }, { + key: "onOpen", + value: function onOpen(e) { + var results, uri; + this.connected = true; + results = []; + + for (uri in this.pending) { + delete this.pending[uri]; + results.push(this._subscribe(uri)); + } + + return results; + } + }, { + key: "subscribe", + value: function subscribe(uri) { + if (this.connected) { + return this._subscribe(uri); + } else { + this.pending[uri] = true; + return this.pending[uri]; + } + } + }]); + + return UpdatesSocket; +}(); +var UpdatesVia = /*#__PURE__*/function () { + function UpdatesVia(fetcher) { + _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, UpdatesVia); + + this.fetcher = fetcher; + this.graph = {}; + this.via = {}; + this.fetcher.addCallback('headers', this.onHeaders); + } + + _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default()(UpdatesVia, [{ + key: "onHeaders", + value: function onHeaders(d) { + var etag, uri, via; + + if (d.headers == null) { + return true; + } + + if (typeof WebSocket === 'undefined' || WebSocket === null) { + return true; + } + + etag = d.headers['etag']; + via = d.headers['updates-via']; + uri = d.uri; + + if (etag && via) { + this.graph[uri] = { + etag: etag, + via: via + }; + this.register(via, uri); + } + + return true; + } + }, { + key: "onUpdate", + value: function onUpdate(uri, d) { + return this.fetcher.refresh(_factories_rdflib_data_factory__WEBPACK_IMPORTED_MODULE_2__["default"].namedNode(uri)); + } + }, { + key: "register", + value: function register(via, uri) { + if (this.via[via] == null) { + this.via[via] = new UpdatesSocket(this, via); + } + + return this.via[via].subscribe(uri); + } + }]); + + return UpdatesVia; +}(); + +/***/ }), + +/***/ "./node_modules/rdflib/esm/uri.js": +/*!****************************************!*\ + !*** ./node_modules/rdflib/esm/uri.js ***! + \****************************************/ +/*! exports provided: docpart, document, hostpart, join, protocol, refTo */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "docpart", function() { return docpart; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "document", function() { return document; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hostpart", function() { return hostpart; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "join", function() { return join; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "protocol", function() { return protocol; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "refTo", function() { return refTo; }); +/* harmony import */ var _named_node__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./named-node */ "./node_modules/rdflib/esm/named-node.js"); +/* + * Implements URI-specific functions + * + * See RFC 2386 + * + * See also: + * http://www.w3.org/2005/10/ajaw/uri.js + * http://www.w3.org/2000/10/swap/uripath.py + * + */ +var alert = alert || console.log; + +/** + * Gets the document part of an URI + * @param uri The URI + */ + +function docpart(uri) { + var i; + i = uri.indexOf('#'); + + if (i < 0) { + return uri; + } else { + return uri.slice(0, i); + } +} +/** + * Gets the document part of an URI as a named node + * @param x - The URI + */ + +function document(x) { + return new _named_node__WEBPACK_IMPORTED_MODULE_0__["default"](docpart(x)); +} +/** + * Gets the hostname in an URI + * @param u The URI + */ + +function hostpart(u) { + var m = /[^\/]*\/\/([^\/]*)\//.exec(u); + + if (m) { + return m[1]; + } else { + return ''; + } +} +/** + * Joins an URI with a base + * @param given - The relative part + * @param base - The base URI + */ + +function join(given, base) { + var baseColon, baseScheme, baseSingle; + var colon, lastSlash, path; + var baseHash = base.indexOf('#'); + + if (baseHash > 0) { + base = base.slice(0, baseHash); + } + + if (given.length === 0) { + return base; + } + + if (given.indexOf('#') === 0) { + return base + given; + } + + colon = given.indexOf(':'); + + if (colon >= 0) { + return given; + } + + baseColon = base.indexOf(':'); + + if (base.length === 0) { + return given; + } + + if (baseColon < 0) { + alert('Invalid base: ' + base + ' in join with given: ' + given); + return given; + } + + baseScheme = base.slice(0, +baseColon + 1 || 9e9); + + if (given.indexOf('//') === 0) { + return baseScheme + given; + } + + if (base.indexOf('//', baseColon) === baseColon + 1) { + baseSingle = base.indexOf('/', baseColon + 3); + + if (baseSingle < 0) { + if (base.length - baseColon - 3 > 0) { + return base + '/' + given; + } else { + return baseScheme + given; + } + } + } else { + baseSingle = base.indexOf('/', baseColon + 1); + + if (baseSingle < 0) { + if (base.length - baseColon - 1 > 0) { + return base + '/' + given; + } else { + return baseScheme + given; + } + } + } + + if (given.indexOf('/') === 0) { + return base.slice(0, baseSingle) + given; + } + + path = base.slice(baseSingle); + lastSlash = path.lastIndexOf('/'); + + if (lastSlash < 0) { + return baseScheme + given; + } + + if (lastSlash >= 0 && lastSlash < path.length - 1) { + path = path.slice(0, +lastSlash + 1 || 9e9); + } + + path += given; + + while (path.match(/[^\/]*\/\.\.\//)) { + path = path.replace(/[^\/]*\/\.\.\//, ''); + } + + path = path.replace(/\.\//g, ''); + path = path.replace(/\/\.$/, '/'); + return base.slice(0, baseSingle) + path; +} +/** + * Gets the protocol part of an URI + * @param uri The URI + */ + +function protocol(uri) { + var i = uri.indexOf(':'); + + if (i < 0) { + return null; + } else { + return uri.slice(0, i); + } +} +/** + * Gets a relative uri + * @param base The base URI + * @param uri The absolute URI + */ + +function refTo(base, uri) { + var c, i, k, l, len, len1, n, o, p, q, ref, ref1, s; + var commonHost = new RegExp('^[-_a-zA-Z0-9.]+:(//[^/]*)?/[^/]*$'); + + if (!base) { + return uri; + } + + if (base === uri) { + return ''; + } + + for (i = o = 0, len = uri.length; o < len; i = ++o) { + var _c = uri[i]; + + if (_c !== base[i]) { + break; + } + } + + if (base.slice(0, i).match(commonHost)) { + k = uri.indexOf('//'); + + if (k < 0) { + k = -2; + } + + l = uri.indexOf('/', k + 2); + + if (uri[l + 1] !== '/' && base[l + 1] !== '/' && uri.slice(0, l) === base.slice(0, l)) { + return uri.slice(l); + } + } + + if (uri[i] === '#' && base.length === i) { + return uri.slice(i); + } + + while (i > 0 && uri[i - 1] !== '/') { + i--; + } + + if (i < 3) { + return uri; + } + + if (base.indexOf('//', i - 2) > 0 || uri.indexOf('//', i - 2) > 0) { + return uri; + } + + if (base.indexOf(':', i) > 0) { + return uri; + } + + n = 0; + ref = base.slice(i); + + for (p = 0, len1 = ref.length; p < len1; p++) { + c = ref[p]; + + if (c === '/') { + n++; + } + } + + if (n === 0 && i < uri.length && uri[i] === '#') { + return './' + uri.slice(i); + } + + if (n === 0 && i === uri.length) { + return './'; + } + + s = ''; + + if (n > 0) { + for (q = 1, ref1 = n; ref1 >= 1 ? q <= ref1 : q >= ref1; ref1 >= 1 ? ++q : --q) { + s += '../'; + } + } + + return s + uri.slice(i); +} + +/***/ }), + +/***/ "./node_modules/rdflib/esm/utils-js.js": +/*!*********************************************!*\ + !*** ./node_modules/rdflib/esm/utils-js.js ***! + \*********************************************/ +/*! exports provided: log, uri, string, mediaTypeClass, linkRelationProperty, callbackify, DOMParserFactory, domToString, dumpNode, dtstamp, heavyCompare, heavyCompareSPO, output, parseXML, RDFArrayRemove, string_startswith, stackString */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* WEBPACK VAR INJECTION */(function(module) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "string", function() { return string; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mediaTypeClass", function() { return mediaTypeClass; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "linkRelationProperty", function() { return linkRelationProperty; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "callbackify", function() { return callbackify; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DOMParserFactory", function() { return DOMParserFactory; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "domToString", function() { return domToString; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "dumpNode", function() { return dumpNode; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "dtstamp", function() { return dtstamp; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "heavyCompare", function() { return heavyCompare; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "heavyCompareSPO", function() { return heavyCompareSPO; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "output", function() { return output; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parseXML", function() { return parseXML; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RDFArrayRemove", function() { return RDFArrayRemove; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "string_startswith", function() { return string_startswith; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "stackString", function() { return stackString; }); +/* harmony import */ var _uri__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./uri */ "./node_modules/rdflib/esm/uri.js"); +/* harmony import */ var _log__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./log */ "./node_modules/rdflib/esm/log.js"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "log", function() { return _log__WEBPACK_IMPORTED_MODULE_1__["default"]; }); + +/* harmony reexport (module object) */ __webpack_require__.d(__webpack_exports__, "uri", function() { return _uri__WEBPACK_IMPORTED_MODULE_0__; }); +/* harmony import */ var _named_node__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./named-node */ "./node_modules/rdflib/esm/named-node.js"); +/* harmony import */ var xmldom__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! xmldom */ "xmldom"); +/* harmony import */ var xmldom__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(xmldom__WEBPACK_IMPORTED_MODULE_3__); +/** + * Utility functions for $rdf + * @module util + */ + + + + +var string = { + template: stringTemplate +}; + +function mediaTypeClass(mediaType) { + mediaType = mediaType.split(';')[0].trim(); // remove media type parameters + + return new _named_node__WEBPACK_IMPORTED_MODULE_2__["default"]('http://www.w3.org/ns/iana/media-types/' + mediaType + '#Resource'); +} +function linkRelationProperty(relation) { + return new _named_node__WEBPACK_IMPORTED_MODULE_2__["default"]('http://www.w3.org/ns/iana/link-relations/relation#' + relation.trim()); +} +/** + * Adds callback functionality to an object. + * Callback functions are indexed by a 'hook' string. + * They return true if they want to be called again. + * @method callbackify + * @param obj {Object} + * @param callbacks {Array} + */ + +function callbackify(obj, callbacks) { + obj.callbacks = {}; + + for (var x = callbacks.length - 1; x >= 0; x--) { + obj.callbacks[callbacks[x]] = []; + } + + obj.addHook = function (hook) { + if (!obj.callbacks[hook]) { + obj.callbacks[hook] = []; + } + }; + + obj.addCallback = function (hook, func) { + obj.callbacks[hook].push(func); + }; + + obj.removeCallback = function (hook, funcName) { + for (var i = 0; i < obj.callbacks[hook].length; i++) { + if (obj.callbacks[hook][i].name === funcName) { + obj.callbacks[hook].splice(i, 1); + return true; + } + } + + return false; + }; + + obj.insertCallback = function (hook, func) { + obj.callbacks[hook].unshift(func); + }; + + obj.fireCallbacks = function fireCallbacks(hook, args) { + var newCallbacks = []; + var replaceCallbacks = []; + var len = obj.callbacks[hook].length; + var x; + var callback; // log.info('!@$ Firing '+hook+' call back with length'+len) + + for (x = len - 1; x >= 0; x--) { + // log.info('@@ Firing '+hook+' callback '+ obj.callbacks[hook][x]) + callback = obj.callbacks[hook][x]; + + if (callback && callback.apply(obj, args)) { + newCallbacks.push(callback); + } + } + + for (x = newCallbacks.length - 1; x >= 0; x--) { + replaceCallbacks.push(newCallbacks[x]); + } + + for (x = len; x < obj.callbacks[hook].length; x++) { + replaceCallbacks.push(obj.callbacks[hook][x]); + } + + obj.callbacks[hook] = replaceCallbacks; + }; +} +/** + * Returns a DOM parser based on current runtime environment. + */ + +function DOMParserFactory() { + if (window.DOMParser) { + return new xmldom__WEBPACK_IMPORTED_MODULE_3__["DOMParser"](); + } else if (window.ActiveXObject) { + return new ActiveXObject('Microsoft.XMLDOM'); + } else { + return false; + } +} // From https://github.com/linkeddata/dokieli + +function domToString(node, options) { + options = options || {}; + var selfClosing = []; + + if ('selfClosing' in options) { + options.selfClosing.split(' ').forEach(function (n) { + selfClosing[n] = true; + }); + } + + var skipAttributes = []; + + if ('skipAttributes' in options) { + options.skipAttributes.split(' ').forEach(function (n) { + skipAttributes[n] = true; + }); + } + + return dumpNode(node, options, selfClosing, skipAttributes); +} +function dumpNode(node, options, selfClosing, skipAttributes) { + var i; + var out = ''; + var noEsc = [false]; + if (typeof node.nodeType === 'undefined') return out; + + if (node.nodeType === 1) { + if (node.hasAttribute('class') && 'classWithChildText' in options && node.matches(options.classWithChildText.class)) { + out += node.querySelector(options.classWithChildText.element).textContent; + } else if (!('skipNodeWithClass' in options && node.matches('.' + options.skipNodeWithClass))) { + var ename = node.nodeName.toLowerCase(); + out += '<' + ename; + var attrList = []; + + for (i = node.attributes.length - 1; i >= 0; i--) { + var atn = node.attributes[i]; + if (skipAttributes.length > 0 && skipAttributes[atn.name]) continue; + if (/^\d+$/.test(atn.name)) continue; + + if (atn.name === 'class' && 'replaceClassItemWith' in options && atn.value.split(' ').indexOf(options.replaceClassItemWith.source) > -1) { + var re = new RegExp(options.replaceClassItemWith.source, 'g'); + atn.value = atn.value.replace(re, options.replaceClassItemWith.target).trim(); + } + + if (!(atn.name === 'class' && 'skipClassWithValue' in options && options.skipClassWithValue === atn.value)) { + attrList.push(atn.name + '=\'' + atn.value.replace(/&/g, '&').replace(//g, '>').replace(/'/g, '"') + '\''); + } + } + + if (attrList.length > 0) { + if ('sortAttributes' in options && options.sortAttributes) { + attrList.sort(function (a, b) { + return a.toLowerCase().localeCompare(b.toLowerCase()); + }); + } + + out += ' ' + attrList.join(' '); + } + + if (selfClosing[ename]) { + out += ' />'; + } else { + out += '>'; + out += ename === 'html' ? '\n ' : ''; + noEsc.push(ename === 'style' || ename === 'script'); + + for (i = 0; i < node.childNodes.length; i++) { + out += dumpNode(node.childNodes[i]); + } + + noEsc.pop(); + out += ename === 'body' ? '' + '\n' : ''; + } + } + } else if (node.nodeType === 8) { + // FIXME: If comments are not tabbed in source, a new line is not prepended + out += ''; + } else if (node.nodeType === 3 || node.nodeType === 4) { + // XXX: Remove new lines which were added after DOM ready + var nl = node.nodeValue.replace(/\n+$/, ''); + out += noEsc[noEsc.length - 1] ? nl : nl.replace(/&/g, '&').replace(//g, '>'); + } else { + console.log('Warning; Cannot handle serialising nodes of type: ' + node.nodeType); + console.log(node); + } + + return out; +} +function dtstamp() { + var now = new Date(); + var year = now.getYear() + 1900; + var month = now.getMonth() + 1; + var day = now.getDate(); + var hour = now.getUTCHours(); + var minute = now.getUTCMinutes(); + var second = now.getSeconds(); + if (month < 10) month = '0' + month; + if (day < 10) day = '0' + day; + if (hour < 10) hour = '0' + hour; + if (minute < 10) minute = '0' + minute; + if (second < 10) second = '0' + second; + return year + '-' + month + '-' + day + 'T' + hour + ':' + minute + ':' + second + 'Z'; +} +/** + * Compares statements (heavy comparison for repeatable canonical ordering) + */ + +function heavyCompare(x, y, g, uriMap) { + var nonBlank = function nonBlank(x) { + return x.termType === 'BlankNode' ? null : x; + }; + + var signature = function signature(x) { + var lis = g.statementsMatching(x).map(function (st) { + return '' + nonBlank(st.subject) + ' ' + nonBlank(st.predicate) + ' ' + nonBlank(st.object); + }).concat(g.statementsMatching(undefined, undefined, x).map(function (st) { + return '' + nonBlank(st.subject) + ' ' + nonBlank(st.predicate) + ' ' + nonBlank(st.object); + })); + lis.sort(); + return lis.join('\n'); + }; + + var comparison = Object.prototype.hasOwnProperty.call(g, "compareTerms") ? g.compareTerms(x, y) : x.compareTerm(y); + + if (x.termType === 'BlankNode' && y.termType === 'BlankNode') { + if (comparison === 0) return 0; // Same + + if (signature(x) > signature(y)) return +1; + if (signature(x) < signature(y)) return -1; + return comparison; // Too bad -- this order not canonical. + // throw "different bnodes indistinquishable for sorting" + } else { + if (uriMap && x.uri && y.uri) { + return (uriMap[x.uri] || x.uri).localeCompare(uriMap[y.uri] || y.uri); + } + + return comparison; + } +} +function heavyCompareSPO(x, y, g, uriMap) { + return heavyCompare(x.subject, y.subject, g, uriMap) || heavyCompare(x.predicate, y.predicate, g, uriMap) || heavyCompare(x.object, y.object, g, uriMap); +} +/** + * Defines a simple debugging function + * @method output + * @param o {String} + */ + +function output(o) { + var k = document.createElement('div'); + k.textContent = o; + document.body.appendChild(k); +} + +/** + * Returns a DOM from parsex XML. + */ + +function parseXML(str, options) { + var dparser; + options = options || {}; + + if ( true && module && module.exports) { + // Node.js + var dom = new xmldom__WEBPACK_IMPORTED_MODULE_3__["DOMParser"]().parseFromString(str, options.contentType || 'application/xhtml+xml'); + return dom; + } else { + if (typeof window !== 'undefined' && window.DOMParser) { + dparser = new window.DOMParser(); // seems to actually work + } else { + dparser = new xmldom__WEBPACK_IMPORTED_MODULE_3__["DOMParser"](); // Doc says this works + } + } + + return dparser.parseFromString(str, 'application/xml'); +} +/** + * Removes all statements equal to x from a + */ + +function RDFArrayRemove(a, x) { + for (var i = 0; i < a.length; i++) { + // TODO: This used to be the following, which didnt always work..why + // if(a[i] === x) + if (a[i].subject.equals(x.subject) && a[i].predicate.equals(x.predicate) && a[i].object.equals(x.object) && a[i].why.equals(x.why)) { + a.splice(i, 1); + return; + } + } + + throw new Error('RDFArrayRemove: Array did not contain ' + x + ' ' + x.why); +} +function string_startswith(str, pref) { + // missing library routines + return str.slice(0, pref.length) === pref; +} +/** + * C++, python style %s -> subs + */ + +function stringTemplate(base, subs) { + var baseA = base.split('%s'); + var result = ''; + + for (var i = 0; i < subs.length; i++) { + subs[i] += ''; + result += baseA[i] + subs[i]; + } + + return result + baseA.slice(subs.length).join(); +} // Stack dump on errors - to pass errors back + + +function stackString(e) { + var str = '' + e + '\n'; + + if (!e.stack) { + return str + 'No stack available.\n'; + } + + var lines = e.stack.toString().split('\n'); + var toprint = []; + + for (var i = 0; i < lines.length; i++) { + var line = lines[i]; + + if (line.indexOf('ecmaunit.js') > -1) { + // remove useless bit of traceback + break; + } + + if (line.charAt(0) == '(') { + line = 'function' + line; + } + + var chunks = line.split('@'); + toprint.push(chunks); + } // toprint.reverse(); No - I prefer the latest at the top by the error message -tbl + + + for (var i = 0; i < toprint.length; i++) { + str += ' ' + toprint[i][1] + '\n ' + toprint[i][0]; + } + + return str; +} +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../webpack/buildin/harmony-module.js */ "./node_modules/webpack/buildin/harmony-module.js")(module))) + +/***/ }), + +/***/ "./node_modules/rdflib/esm/utils.js": +/*!******************************************!*\ + !*** ./node_modules/rdflib/esm/utils.js ***! + \******************************************/ +/*! exports provided: AJAR_handleNewTerm, appliedFactoryMethods, arrayToStatements, ArrayIndexOf */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AJAR_handleNewTerm", function() { return AJAR_handleNewTerm; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "appliedFactoryMethods", function() { return appliedFactoryMethods; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "arrayToStatements", function() { return arrayToStatements; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ArrayIndexOf", function() { return ArrayIndexOf; }); +/* harmony import */ var _log__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./log */ "./node_modules/rdflib/esm/log.js"); +/* harmony import */ var _uri__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./uri */ "./node_modules/rdflib/esm/uri.js"); +/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./utils-js */ "./node_modules/rdflib/esm/utils-js.js"); + + + + +/** RDF/JS spec Typeguards */ + +/** + * Loads ontologies of the data we load (this is the callback from the kb to + * the fetcher). + */ +function AJAR_handleNewTerm(kb, p, requestedBy) { + var sf = null; + + if (typeof kb.fetcher !== 'undefined') { + sf = kb.fetcher; + } else { + return; + } + + if (p.termType !== 'NamedNode') return; + var docuri = Object(_uri__WEBPACK_IMPORTED_MODULE_1__["docpart"])(p.uri); + var fixuri; + + if (p.uri.indexOf('#') < 0) { + // No hash + // @@ major hack for dbpedia Categories, which spread indefinitely + if (Object(_utils_js__WEBPACK_IMPORTED_MODULE_2__["string_startswith"])(p.uri, 'http://dbpedia.org/resource/Category:')) return; + /* + if (string_startswith(p.uri, 'http://xmlns.com/foaf/0.1/')) { + fixuri = "http://dig.csail.mit.edu/2005/ajar/ajaw/test/foaf" + // should give HTTP 303 to ontology -- now is :-) + } else + */ + + if (Object(_utils_js__WEBPACK_IMPORTED_MODULE_2__["string_startswith"])(p.uri, 'http://purl.org/dc/elements/1.1/') || Object(_utils_js__WEBPACK_IMPORTED_MODULE_2__["string_startswith"])(p.uri, 'http://purl.org/dc/terms/')) { + fixuri = 'http://dublincore.org/2005/06/13/dcq'; // dc fetched multiple times + } else if (Object(_utils_js__WEBPACK_IMPORTED_MODULE_2__["string_startswith"])(p.uri, 'http://xmlns.com/wot/0.1/')) { + fixuri = 'http://xmlns.com/wot/0.1/index.rdf'; + } else if (Object(_utils_js__WEBPACK_IMPORTED_MODULE_2__["string_startswith"])(p.uri, 'http://web.resource.org/cc/')) { + // log.warn("creative commons links to html instead of rdf. doesn't seem to content-negotiate.") + fixuri = 'http://web.resource.org/cc/schema.rdf'; + } + } + + if (fixuri) { + docuri = fixuri; + } + + if (sf && sf.getState(docuri) !== 'unrequested') return; + + if (fixuri) { + // only give warning once: else happens too often + _log__WEBPACK_IMPORTED_MODULE_0__["default"].warn('Assuming server still broken, faking redirect of <' + p.uri + '> to <' + docuri + '>'); + } + + return sf.fetch(docuri, { + referringTerm: requestedBy + }); +} +var appliedFactoryMethods = ['blankNode', 'defaultGraph', 'literal', 'namedNode', 'quad', 'variable', 'supports']; +var rdf = { + first: 'http://www.w3.org/1999/02/22-rdf-syntax-ns#first', + rest: 'http://www.w3.org/1999/02/22-rdf-syntax-ns#rest', + nil: 'http://www.w3.org/1999/02/22-rdf-syntax-ns#nil' +}; +/** + * Expands an array of Terms to a set of statements representing the rdf:list. + * @param rdfFactory - The factory to use + * @param subject - The iri of the first list item. + * @param data - The terms to expand into the list. + * @return The {data} as a set of statements. + */ + +function arrayToStatements(rdfFactory, subject, data) { + var statements = []; + data.reduce(function (id, _listObj, i, listData) { + statements.push(rdfFactory.quad(id, rdfFactory.namedNode(rdf.first), listData[i])); + var nextNode; + + if (i < listData.length - 1) { + nextNode = rdfFactory.blankNode(); + statements.push(rdfFactory.quad(id, rdfFactory.namedNode(rdf.rest), nextNode)); + } else { + statements.push(rdfFactory.quad(id, rdfFactory.namedNode(rdf.rest), rdfFactory.namedNode(rdf.nil))); + } + + return nextNode; + }, subject); + return statements; +} +function ArrayIndexOf(arr, item) { + var i = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var length = arr.length; + if (i < 0) i = length + i; + + for (; i < length; i++) { + if (arr[i] === item) { + return i; + } + } + + return -1; +} + +/***/ }), + +/***/ "./node_modules/rdflib/esm/utils/default-graph-uri.js": +/*!************************************************************!*\ + !*** ./node_modules/rdflib/esm/utils/default-graph-uri.js ***! + \************************************************************/ +/*! exports provided: defaultGraphURI, defaultGraphNode */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "defaultGraphURI", function() { return defaultGraphURI; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "defaultGraphNode", function() { return defaultGraphNode; }); +/* harmony import */ var _named_node__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../named-node */ "./node_modules/rdflib/esm/named-node.js"); +// Prevents circular dependencies between data-factory-internal and statement + +var defaultGraphURI = 'chrome:theSession'; +var defaultGraphNode = new _named_node__WEBPACK_IMPORTED_MODULE_0__["default"](defaultGraphURI); + +/***/ }), + +/***/ "./node_modules/rdflib/esm/utils/termValue.js": +/*!****************************************************!*\ + !*** ./node_modules/rdflib/esm/utils/termValue.js ***! + \****************************************************/ +/*! exports provided: termValue */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "termValue", function() { return termValue; }); +/** Retrieve the value of a term, or self if already a string. */ +function termValue(node) { + if (typeof node === 'string') { + return node; + } + + return node.value; +} + +/***/ }), + +/***/ "./node_modules/rdflib/esm/utils/terms.js": +/*!************************************************!*\ + !*** ./node_modules/rdflib/esm/utils/terms.js ***! + \************************************************/ +/*! exports provided: isStatement, isStore, isCollection, isRDFlibObject, isVariable, isTerm, isLiteral, isQuad, isNamedNode, isBlankNode, isSubject, isPredicate, isRDFObject, isGraph */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isStatement", function() { return isStatement; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isStore", function() { return isStore; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isCollection", function() { return isCollection; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isRDFlibObject", function() { return isRDFlibObject; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isVariable", function() { return isVariable; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isTerm", function() { return isTerm; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isLiteral", function() { return isLiteral; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isQuad", function() { return isQuad; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isNamedNode", function() { return isNamedNode; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isBlankNode", function() { return isBlankNode; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isSubject", function() { return isSubject; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isPredicate", function() { return isPredicate; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isRDFObject", function() { return isRDFObject; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isGraph", function() { return isGraph; }); +/* harmony import */ var _babel_runtime_helpers_typeof__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "./node_modules/@babel/runtime/helpers/typeof.js"); +/* harmony import */ var _babel_runtime_helpers_typeof__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_typeof__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../types */ "./node_modules/rdflib/esm/types.js"); + + + +/** TypeGuard for RDFLib Statements */ +function isStatement(obj) { + return _babel_runtime_helpers_typeof__WEBPACK_IMPORTED_MODULE_0___default()(obj) === 'object' && obj !== null && 'subject' in obj; +} +/** TypeGuard for RDFlib Stores */ + +function isStore(obj) { + return _babel_runtime_helpers_typeof__WEBPACK_IMPORTED_MODULE_0___default()(obj) === 'object' && obj !== null && 'statements' in obj; +} +/** TypeGuard for RDFLib Collections */ + +function isCollection(obj) { + return isTerm(obj) && obj.termType === _types__WEBPACK_IMPORTED_MODULE_1__["CollectionTermType"]; +} +/** TypeGuard for valid RDFlib Object types, also allows Collections */ + +function isRDFlibObject(obj) { + return obj && Object.prototype.hasOwnProperty.call(obj, 'termType') && (obj.termType === _types__WEBPACK_IMPORTED_MODULE_1__["NamedNodeTermType"] || obj.termType === _types__WEBPACK_IMPORTED_MODULE_1__["VariableTermType"] || obj.termType === _types__WEBPACK_IMPORTED_MODULE_1__["BlankNodeTermType"] || obj.termType === _types__WEBPACK_IMPORTED_MODULE_1__["CollectionTermType"] || obj.termType === _types__WEBPACK_IMPORTED_MODULE_1__["LiteralTermType"] || obj.termType === _types__WEBPACK_IMPORTED_MODULE_1__["GraphTermType"]); +} +/** TypeGuard for RDFLib Variables */ + +function isVariable(obj) { + return isTerm(obj) && obj.termType === _types__WEBPACK_IMPORTED_MODULE_1__["VariableTermType"]; +} +/** TypeGuard for RDF/JS spec Terms */ + +function isTerm(obj) { + return _babel_runtime_helpers_typeof__WEBPACK_IMPORTED_MODULE_0___default()(obj) === 'object' && obj !== null && 'termType' in obj; +} +/** TypeGuard for RDF/JS spec Literals */ + +function isLiteral(value) { + return value.termType === _types__WEBPACK_IMPORTED_MODULE_1__["LiteralTermType"]; +} +/** TypeGuard for RDF/JS spec Quads */ + +function isQuad(obj) { + return _babel_runtime_helpers_typeof__WEBPACK_IMPORTED_MODULE_0___default()(obj) === "object" && obj !== null && 'subject' in obj && 'predicate' in obj && 'object' in obj; +} +/** TypeGuard for RDF/JS spec NamedNodes */ + +function isNamedNode(obj) { + return isTerm(obj) && obj.termType === 'NamedNode'; +} +/** TypeGuard for RDF/JS spec BlankNodes */ + +function isBlankNode(obj) { + return isTerm(obj) && 'termType' in obj && obj.termType === 'BlankNode'; +} +/** TypeGuard for valid RDF/JS spec Subject types */ + +function isSubject(obj) { + return isTerm(obj) && (obj.termType === _types__WEBPACK_IMPORTED_MODULE_1__["NamedNodeTermType"] || obj.termType === _types__WEBPACK_IMPORTED_MODULE_1__["VariableTermType"] || obj.termType === _types__WEBPACK_IMPORTED_MODULE_1__["BlankNodeTermType"]); +} +/** TypeGuard for valid RDF/JS spec Predicate types */ + +function isPredicate(obj) { + return isTerm(obj) && (obj.termType === _types__WEBPACK_IMPORTED_MODULE_1__["NamedNodeTermType"] || obj.termType === _types__WEBPACK_IMPORTED_MODULE_1__["VariableTermType"]); +} +/** TypeGuard for valid RDF/JS spec Object types */ + +function isRDFObject(obj) { + return isTerm(obj) && (obj.termType === _types__WEBPACK_IMPORTED_MODULE_1__["NamedNodeTermType"] || obj.termType === _types__WEBPACK_IMPORTED_MODULE_1__["VariableTermType"] || obj.termType === _types__WEBPACK_IMPORTED_MODULE_1__["BlankNodeTermType"] || obj.termType === _types__WEBPACK_IMPORTED_MODULE_1__["LiteralTermType"]); +} +/** TypeGuard for valid RDF/JS Graph types */ + +function isGraph(obj) { + return isTerm(obj) && (obj.termType === _types__WEBPACK_IMPORTED_MODULE_1__["NamedNodeTermType"] || obj.termType === _types__WEBPACK_IMPORTED_MODULE_1__["VariableTermType"] || obj.termType === _types__WEBPACK_IMPORTED_MODULE_1__["BlankNodeTermType"] || obj.termType === _types__WEBPACK_IMPORTED_MODULE_1__["DefaultGraphTermType"]); +} + +/***/ }), + +/***/ "./node_modules/rdflib/esm/variable.js": +/*!*********************************************!*\ + !*** ./node_modules/rdflib/esm/variable.js ***! + \*********************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return Variable; }); +/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js"); +/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js"); +/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__); +/* harmony import */ var _babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/assertThisInitialized */ "./node_modules/@babel/runtime/helpers/assertThisInitialized.js"); +/* harmony import */ var _babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__); +/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/inherits */ "./node_modules/@babel/runtime/helpers/inherits.js"); +/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3__); +/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "./node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"); +/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__); +/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "./node_modules/@babel/runtime/helpers/getPrototypeOf.js"); +/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__); +/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "./node_modules/@babel/runtime/helpers/defineProperty.js"); +/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__); +/* harmony import */ var _class_order__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./class-order */ "./node_modules/rdflib/esm/class-order.js"); +/* harmony import */ var _node_internal__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./node-internal */ "./node_modules/rdflib/esm/node-internal.js"); +/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./types */ "./node_modules/rdflib/esm/types.js"); +/* harmony import */ var _uri__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./uri */ "./node_modules/rdflib/esm/uri.js"); + + + + + + + + +function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5___default()(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5___default()(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4___default()(this, result); }; } + +function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } + + + + + + +/** +* Variables are placeholders used in patterns to be matched. +* In cwm they are symbols which are the formula's list of quantified variables. +* In sparql they are not visibly URIs. Here we compromise, by having +* a common special base URI for variables. Their names are uris, +* but the ? notation has an implicit base uri of 'varid:' +*/ +var Variable = /*#__PURE__*/function (_Node) { + _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3___default()(Variable, _Node); + + var _super = _createSuper(Variable); + + /** The base string for a variable's name */ + + /** The unique identifier of this variable */ + + /** + * Initializes this variable + * @param name The variable's name + */ + function Variable() { + var _this; + + var name = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ''; + + _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, Variable); + + _this = _super.call(this, name); + + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6___default()(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2___default()(_this), "termType", _types__WEBPACK_IMPORTED_MODULE_9__["VariableTermType"]); + + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6___default()(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2___default()(_this), "base", 'varid:'); + + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6___default()(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2___default()(_this), "classOrder", _class_order__WEBPACK_IMPORTED_MODULE_7__["default"].Variable); + + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6___default()(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2___default()(_this), "isVar", 1); + + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6___default()(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2___default()(_this), "uri", void 0); + + _this.base = 'varid:'; + _this.uri = _uri__WEBPACK_IMPORTED_MODULE_10__["join"](name, _this.base); + return _this; + } + + _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default()(Variable, [{ + key: "equals", + value: function equals(other) { + if (!other) { + return false; + } + + return this.termType === other.termType && this.value === other.value; + } + }, { + key: "hashString", + value: function hashString() { + return this.toString(); + } + }, { + key: "substitute", + value: function substitute(bindings) { + var ref; + return (ref = bindings[this.toNT()]) != null ? ref : this; + } + }, { + key: "toString", + value: function toString() { + return Variable.toString(this); + } + }], [{ + key: "toString", + value: function toString(variable) { + if (variable.uri.slice(0, variable.base.length) === variable.base) { + return "?".concat(variable.uri.slice(variable.base.length)); + } + + return "?".concat(variable.uri); + } + }]); + + return Variable; +}(_node_internal__WEBPACK_IMPORTED_MODULE_8__["default"]); + + + +/***/ }), + +/***/ "./node_modules/rdflib/esm/xsd-internal.js": +/*!*************************************************!*\ + !*** ./node_modules/rdflib/esm/xsd-internal.js ***! + \*************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _named_node__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./named-node */ "./node_modules/rdflib/esm/named-node.js"); + +/* harmony default export */ __webpack_exports__["default"] = ({ + boolean: new _named_node__WEBPACK_IMPORTED_MODULE_0__["default"]('http://www.w3.org/2001/XMLSchema#boolean'), + dateTime: new _named_node__WEBPACK_IMPORTED_MODULE_0__["default"]('http://www.w3.org/2001/XMLSchema#dateTime'), + decimal: new _named_node__WEBPACK_IMPORTED_MODULE_0__["default"]('http://www.w3.org/2001/XMLSchema#decimal'), + double: new _named_node__WEBPACK_IMPORTED_MODULE_0__["default"]('http://www.w3.org/2001/XMLSchema#double'), + integer: new _named_node__WEBPACK_IMPORTED_MODULE_0__["default"]('http://www.w3.org/2001/XMLSchema#integer'), + langString: new _named_node__WEBPACK_IMPORTED_MODULE_0__["default"]('http://www.w3.org/1999/02/22-rdf-syntax-ns#langString'), + string: new _named_node__WEBPACK_IMPORTED_MODULE_0__["default"]('http://www.w3.org/2001/XMLSchema#string') +}); + +/***/ }), + +/***/ "./node_modules/rdflib/esm/xsd.js": +/*!****************************************!*\ + !*** ./node_modules/rdflib/esm/xsd.js ***! + \****************************************/ +/*! exports provided: createXSD, default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createXSD", function() { return createXSD; }); +/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js"); +/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _factories_canonical_data_factory__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./factories/canonical-data-factory */ "./node_modules/rdflib/esm/factories/canonical-data-factory.js"); + + +function createXSD() { + var localFactory = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _factories_canonical_data_factory__WEBPACK_IMPORTED_MODULE_1__["default"]; + + var XSD = function XSD() { + _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, XSD); + }; + + XSD.boolean = localFactory.namedNode('http://www.w3.org/2001/XMLSchema#boolean'); + XSD.dateTime = localFactory.namedNode('http://www.w3.org/2001/XMLSchema#dateTime'); + XSD.decimal = localFactory.namedNode('http://www.w3.org/2001/XMLSchema#decimal'); + XSD.double = localFactory.namedNode('http://www.w3.org/2001/XMLSchema#double'); + XSD.integer = localFactory.namedNode('http://www.w3.org/2001/XMLSchema#integer'); + XSD.langString = localFactory.namedNode('http://www.w3.org/1999/02/22-rdf-syntax-ns#langString'); + XSD.string = localFactory.namedNode('http://www.w3.org/2001/XMLSchema#string'); + return XSD; +} +var defaultXSD = createXSD(_factories_canonical_data_factory__WEBPACK_IMPORTED_MODULE_1__["default"]); +/* harmony default export */ __webpack_exports__["default"] = (defaultXSD); + +/***/ }), + +/***/ "./node_modules/react-display-name/lib/getDisplayName.js": +/*!***************************************************************!*\ + !*** ./node_modules/react-display-name/lib/getDisplayName.js ***! + \***************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = getDisplayName; +function getDisplayName(Component) { + return Component.displayName || Component.name || (typeof Component === 'string' && Component.length > 0 ? Component : 'Unknown'); +} + +/***/ }), + +/***/ "./node_modules/react-dom/cjs/react-dom.development.js": +/*!*************************************************************!*\ + !*** ./node_modules/react-dom/cjs/react-dom.development.js ***! + \*************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** @license React v17.0.1 + * react-dom.development.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + + + +if (true) { + (function() { +'use strict'; + +var React = __webpack_require__(/*! react */ "./node_modules/react/index.js"); +var _assign = __webpack_require__(/*! object-assign */ "./node_modules/object-assign/index.js"); +var Scheduler = __webpack_require__(/*! scheduler */ "./node_modules/scheduler/index.js"); +var tracing = __webpack_require__(/*! scheduler/tracing */ "./node_modules/scheduler/tracing.js"); + +var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; + +// by calls to these methods by a Babel plugin. +// +// In PROD (or in packages without access to React internals), +// they are left as they are instead. + +function warn(format) { + { + for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + args[_key - 1] = arguments[_key]; + } + + printWarning('warn', format, args); + } +} +function error(format) { + { + for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { + args[_key2 - 1] = arguments[_key2]; + } + + printWarning('error', format, args); + } +} + +function printWarning(level, format, args) { + // When changing this logic, you might want to also + // update consoleWithStackDev.www.js as well. + { + var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; + var stack = ReactDebugCurrentFrame.getStackAddendum(); + + if (stack !== '') { + format += '%s'; + args = args.concat([stack]); + } + + var argsWithFormat = args.map(function (item) { + return '' + item; + }); // Careful: RN currently depends on this prefix + + argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it + // breaks IE9: https://github.com/facebook/react/issues/13610 + // eslint-disable-next-line react-internal/no-production-logging + + Function.prototype.apply.call(console[level], console, argsWithFormat); + } +} + +if (!React) { + { + throw Error( "ReactDOM was loaded before React. Make sure you load the React package before loading ReactDOM." ); + } +} + +var FunctionComponent = 0; +var ClassComponent = 1; +var IndeterminateComponent = 2; // Before we know whether it is function or class + +var HostRoot = 3; // Root of a host tree. Could be nested inside another node. + +var HostPortal = 4; // A subtree. Could be an entry point to a different renderer. + +var HostComponent = 5; +var HostText = 6; +var Fragment = 7; +var Mode = 8; +var ContextConsumer = 9; +var ContextProvider = 10; +var ForwardRef = 11; +var Profiler = 12; +var SuspenseComponent = 13; +var MemoComponent = 14; +var SimpleMemoComponent = 15; +var LazyComponent = 16; +var IncompleteClassComponent = 17; +var DehydratedFragment = 18; +var SuspenseListComponent = 19; +var FundamentalComponent = 20; +var ScopeComponent = 21; +var Block = 22; +var OffscreenComponent = 23; +var LegacyHiddenComponent = 24; + +// Filter certain DOM attributes (e.g. src, href) if their values are empty strings. + +var enableProfilerTimer = true; // Record durations for commit and passive effects phases. + +var enableFundamentalAPI = false; // Experimental Scope support. +var enableNewReconciler = false; // Errors that are thrown while unmounting (or after in the case of passive effects) +var warnAboutStringRefs = false; + +var allNativeEvents = new Set(); +/** + * Mapping from registration name to event name + */ + + +var registrationNameDependencies = {}; +/** + * Mapping from lowercase registration names to the properly cased version, + * used to warn in the case of missing event handlers. Available + * only in true. + * @type {Object} + */ + +var possibleRegistrationNames = {} ; // Trust the developer to only use possibleRegistrationNames in true + +function registerTwoPhaseEvent(registrationName, dependencies) { + registerDirectEvent(registrationName, dependencies); + registerDirectEvent(registrationName + 'Capture', dependencies); +} +function registerDirectEvent(registrationName, dependencies) { + { + if (registrationNameDependencies[registrationName]) { + error('EventRegistry: More than one plugin attempted to publish the same ' + 'registration name, `%s`.', registrationName); + } + } + + registrationNameDependencies[registrationName] = dependencies; + + { + var lowerCasedName = registrationName.toLowerCase(); + possibleRegistrationNames[lowerCasedName] = registrationName; + + if (registrationName === 'onDoubleClick') { + possibleRegistrationNames.ondblclick = registrationName; + } + } + + for (var i = 0; i < dependencies.length; i++) { + allNativeEvents.add(dependencies[i]); + } +} + +var canUseDOM = !!(typeof window !== 'undefined' && typeof window.document !== 'undefined' && typeof window.document.createElement !== 'undefined'); + +// A reserved attribute. +// It is handled by React separately and shouldn't be written to the DOM. +var RESERVED = 0; // A simple string attribute. +// Attributes that aren't in the filter are presumed to have this type. + +var STRING = 1; // A string attribute that accepts booleans in React. In HTML, these are called +// "enumerated" attributes with "true" and "false" as possible values. +// When true, it should be set to a "true" string. +// When false, it should be set to a "false" string. + +var BOOLEANISH_STRING = 2; // A real boolean attribute. +// When true, it should be present (set either to an empty string or its name). +// When false, it should be omitted. + +var BOOLEAN = 3; // An attribute that can be used as a flag as well as with a value. +// When true, it should be present (set either to an empty string or its name). +// When false, it should be omitted. +// For any other value, should be present with that value. + +var OVERLOADED_BOOLEAN = 4; // An attribute that must be numeric or parse as a numeric. +// When falsy, it should be removed. + +var NUMERIC = 5; // An attribute that must be positive numeric or parse as a positive numeric. +// When falsy, it should be removed. + +var POSITIVE_NUMERIC = 6; + +/* eslint-disable max-len */ +var ATTRIBUTE_NAME_START_CHAR = ":A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD"; +/* eslint-enable max-len */ + +var ATTRIBUTE_NAME_CHAR = ATTRIBUTE_NAME_START_CHAR + "\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040"; +var ROOT_ATTRIBUTE_NAME = 'data-reactroot'; +var VALID_ATTRIBUTE_NAME_REGEX = new RegExp('^[' + ATTRIBUTE_NAME_START_CHAR + '][' + ATTRIBUTE_NAME_CHAR + ']*$'); +var hasOwnProperty = Object.prototype.hasOwnProperty; +var illegalAttributeNameCache = {}; +var validatedAttributeNameCache = {}; +function isAttributeNameSafe(attributeName) { + if (hasOwnProperty.call(validatedAttributeNameCache, attributeName)) { + return true; + } + + if (hasOwnProperty.call(illegalAttributeNameCache, attributeName)) { + return false; + } + + if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName)) { + validatedAttributeNameCache[attributeName] = true; + return true; + } + + illegalAttributeNameCache[attributeName] = true; + + { + error('Invalid attribute name: `%s`', attributeName); + } + + return false; +} +function shouldIgnoreAttribute(name, propertyInfo, isCustomComponentTag) { + if (propertyInfo !== null) { + return propertyInfo.type === RESERVED; + } + + if (isCustomComponentTag) { + return false; + } + + if (name.length > 2 && (name[0] === 'o' || name[0] === 'O') && (name[1] === 'n' || name[1] === 'N')) { + return true; + } + + return false; +} +function shouldRemoveAttributeWithWarning(name, value, propertyInfo, isCustomComponentTag) { + if (propertyInfo !== null && propertyInfo.type === RESERVED) { + return false; + } + + switch (typeof value) { + case 'function': // $FlowIssue symbol is perfectly valid here + + case 'symbol': + // eslint-disable-line + return true; + + case 'boolean': + { + if (isCustomComponentTag) { + return false; + } + + if (propertyInfo !== null) { + return !propertyInfo.acceptsBooleans; + } else { + var prefix = name.toLowerCase().slice(0, 5); + return prefix !== 'data-' && prefix !== 'aria-'; + } + } + + default: + return false; + } +} +function shouldRemoveAttribute(name, value, propertyInfo, isCustomComponentTag) { + if (value === null || typeof value === 'undefined') { + return true; + } + + if (shouldRemoveAttributeWithWarning(name, value, propertyInfo, isCustomComponentTag)) { + return true; + } + + if (isCustomComponentTag) { + return false; + } + + if (propertyInfo !== null) { + + switch (propertyInfo.type) { + case BOOLEAN: + return !value; + + case OVERLOADED_BOOLEAN: + return value === false; + + case NUMERIC: + return isNaN(value); + + case POSITIVE_NUMERIC: + return isNaN(value) || value < 1; + } + } + + return false; +} +function getPropertyInfo(name) { + return properties.hasOwnProperty(name) ? properties[name] : null; +} + +function PropertyInfoRecord(name, type, mustUseProperty, attributeName, attributeNamespace, sanitizeURL, removeEmptyString) { + this.acceptsBooleans = type === BOOLEANISH_STRING || type === BOOLEAN || type === OVERLOADED_BOOLEAN; + this.attributeName = attributeName; + this.attributeNamespace = attributeNamespace; + this.mustUseProperty = mustUseProperty; + this.propertyName = name; + this.type = type; + this.sanitizeURL = sanitizeURL; + this.removeEmptyString = removeEmptyString; +} // When adding attributes to this list, be sure to also add them to +// the `possibleStandardNames` module to ensure casing and incorrect +// name warnings. + + +var properties = {}; // These props are reserved by React. They shouldn't be written to the DOM. + +var reservedProps = ['children', 'dangerouslySetInnerHTML', // TODO: This prevents the assignment of defaultValue to regular +// elements (not just inputs). Now that ReactDOMInput assigns to the +// defaultValue property -- do we need this? +'defaultValue', 'defaultChecked', 'innerHTML', 'suppressContentEditableWarning', 'suppressHydrationWarning', 'style']; +reservedProps.forEach(function (name) { + properties[name] = new PropertyInfoRecord(name, RESERVED, false, // mustUseProperty + name, // attributeName + null, // attributeNamespace + false, // sanitizeURL + false); +}); // A few React string attributes have a different name. +// This is a mapping from React prop names to the attribute names. + +[['acceptCharset', 'accept-charset'], ['className', 'class'], ['htmlFor', 'for'], ['httpEquiv', 'http-equiv']].forEach(function (_ref) { + var name = _ref[0], + attributeName = _ref[1]; + properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty + attributeName, // attributeName + null, // attributeNamespace + false, // sanitizeURL + false); +}); // These are "enumerated" HTML attributes that accept "true" and "false". +// In React, we let users pass `true` and `false` even though technically +// these aren't boolean attributes (they are coerced to strings). + +['contentEditable', 'draggable', 'spellCheck', 'value'].forEach(function (name) { + properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, // mustUseProperty + name.toLowerCase(), // attributeName + null, // attributeNamespace + false, // sanitizeURL + false); +}); // These are "enumerated" SVG attributes that accept "true" and "false". +// In React, we let users pass `true` and `false` even though technically +// these aren't boolean attributes (they are coerced to strings). +// Since these are SVG attributes, their attribute names are case-sensitive. + +['autoReverse', 'externalResourcesRequired', 'focusable', 'preserveAlpha'].forEach(function (name) { + properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, // mustUseProperty + name, // attributeName + null, // attributeNamespace + false, // sanitizeURL + false); +}); // These are HTML boolean attributes. + +['allowFullScreen', 'async', // Note: there is a special case that prevents it from being written to the DOM +// on the client side because the browsers are inconsistent. Instead we call focus(). +'autoFocus', 'autoPlay', 'controls', 'default', 'defer', 'disabled', 'disablePictureInPicture', 'disableRemotePlayback', 'formNoValidate', 'hidden', 'loop', 'noModule', 'noValidate', 'open', 'playsInline', 'readOnly', 'required', 'reversed', 'scoped', 'seamless', // Microdata +'itemScope'].forEach(function (name) { + properties[name] = new PropertyInfoRecord(name, BOOLEAN, false, // mustUseProperty + name.toLowerCase(), // attributeName + null, // attributeNamespace + false, // sanitizeURL + false); +}); // These are the few React props that we set as DOM properties +// rather than attributes. These are all booleans. + +['checked', // Note: `option.selected` is not updated if `select.multiple` is +// disabled with `removeAttribute`. We have special logic for handling this. +'multiple', 'muted', 'selected' // NOTE: if you add a camelCased prop to this list, +// you'll need to set attributeName to name.toLowerCase() +// instead in the assignment below. +].forEach(function (name) { + properties[name] = new PropertyInfoRecord(name, BOOLEAN, true, // mustUseProperty + name, // attributeName + null, // attributeNamespace + false, // sanitizeURL + false); +}); // These are HTML attributes that are "overloaded booleans": they behave like +// booleans, but can also accept a string value. + +['capture', 'download' // NOTE: if you add a camelCased prop to this list, +// you'll need to set attributeName to name.toLowerCase() +// instead in the assignment below. +].forEach(function (name) { + properties[name] = new PropertyInfoRecord(name, OVERLOADED_BOOLEAN, false, // mustUseProperty + name, // attributeName + null, // attributeNamespace + false, // sanitizeURL + false); +}); // These are HTML attributes that must be positive numbers. + +['cols', 'rows', 'size', 'span' // NOTE: if you add a camelCased prop to this list, +// you'll need to set attributeName to name.toLowerCase() +// instead in the assignment below. +].forEach(function (name) { + properties[name] = new PropertyInfoRecord(name, POSITIVE_NUMERIC, false, // mustUseProperty + name, // attributeName + null, // attributeNamespace + false, // sanitizeURL + false); +}); // These are HTML attributes that must be numbers. + +['rowSpan', 'start'].forEach(function (name) { + properties[name] = new PropertyInfoRecord(name, NUMERIC, false, // mustUseProperty + name.toLowerCase(), // attributeName + null, // attributeNamespace + false, // sanitizeURL + false); +}); +var CAMELIZE = /[\-\:]([a-z])/g; + +var capitalize = function (token) { + return token[1].toUpperCase(); +}; // This is a list of all SVG attributes that need special casing, namespacing, +// or boolean value assignment. Regular attributes that just accept strings +// and have the same names are omitted, just like in the HTML attribute filter. +// Some of these attributes can be hard to find. This list was created by +// scraping the MDN documentation. + + +['accent-height', 'alignment-baseline', 'arabic-form', 'baseline-shift', 'cap-height', 'clip-path', 'clip-rule', 'color-interpolation', 'color-interpolation-filters', 'color-profile', 'color-rendering', 'dominant-baseline', 'enable-background', 'fill-opacity', 'fill-rule', 'flood-color', 'flood-opacity', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'glyph-name', 'glyph-orientation-horizontal', 'glyph-orientation-vertical', 'horiz-adv-x', 'horiz-origin-x', 'image-rendering', 'letter-spacing', 'lighting-color', 'marker-end', 'marker-mid', 'marker-start', 'overline-position', 'overline-thickness', 'paint-order', 'panose-1', 'pointer-events', 'rendering-intent', 'shape-rendering', 'stop-color', 'stop-opacity', 'strikethrough-position', 'strikethrough-thickness', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'text-anchor', 'text-decoration', 'text-rendering', 'underline-position', 'underline-thickness', 'unicode-bidi', 'unicode-range', 'units-per-em', 'v-alphabetic', 'v-hanging', 'v-ideographic', 'v-mathematical', 'vector-effect', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'word-spacing', 'writing-mode', 'xmlns:xlink', 'x-height' // NOTE: if you add a camelCased prop to this list, +// you'll need to set attributeName to name.toLowerCase() +// instead in the assignment below. +].forEach(function (attributeName) { + var name = attributeName.replace(CAMELIZE, capitalize); + properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty + attributeName, null, // attributeNamespace + false, // sanitizeURL + false); +}); // String SVG attributes with the xlink namespace. + +['xlink:actuate', 'xlink:arcrole', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type' // NOTE: if you add a camelCased prop to this list, +// you'll need to set attributeName to name.toLowerCase() +// instead in the assignment below. +].forEach(function (attributeName) { + var name = attributeName.replace(CAMELIZE, capitalize); + properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty + attributeName, 'http://www.w3.org/1999/xlink', false, // sanitizeURL + false); +}); // String SVG attributes with the xml namespace. + +['xml:base', 'xml:lang', 'xml:space' // NOTE: if you add a camelCased prop to this list, +// you'll need to set attributeName to name.toLowerCase() +// instead in the assignment below. +].forEach(function (attributeName) { + var name = attributeName.replace(CAMELIZE, capitalize); + properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty + attributeName, 'http://www.w3.org/XML/1998/namespace', false, // sanitizeURL + false); +}); // These attribute exists both in HTML and SVG. +// The attribute name is case-sensitive in SVG so we can't just use +// the React name like we do for attributes that exist only in HTML. + +['tabIndex', 'crossOrigin'].forEach(function (attributeName) { + properties[attributeName] = new PropertyInfoRecord(attributeName, STRING, false, // mustUseProperty + attributeName.toLowerCase(), // attributeName + null, // attributeNamespace + false, // sanitizeURL + false); +}); // These attributes accept URLs. These must not allow javascript: URLS. +// These will also need to accept Trusted Types object in the future. + +var xlinkHref = 'xlinkHref'; +properties[xlinkHref] = new PropertyInfoRecord('xlinkHref', STRING, false, // mustUseProperty +'xlink:href', 'http://www.w3.org/1999/xlink', true, // sanitizeURL +false); +['src', 'href', 'action', 'formAction'].forEach(function (attributeName) { + properties[attributeName] = new PropertyInfoRecord(attributeName, STRING, false, // mustUseProperty + attributeName.toLowerCase(), // attributeName + null, // attributeNamespace + true, // sanitizeURL + true); +}); + +// and any newline or tab are filtered out as if they're not part of the URL. +// https://url.spec.whatwg.org/#url-parsing +// Tab or newline are defined as \r\n\t: +// https://infra.spec.whatwg.org/#ascii-tab-or-newline +// A C0 control is a code point in the range \u0000 NULL to \u001F +// INFORMATION SEPARATOR ONE, inclusive: +// https://infra.spec.whatwg.org/#c0-control-or-space + +/* eslint-disable max-len */ + +var isJavaScriptProtocol = /^[\u0000-\u001F ]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*\:/i; +var didWarn = false; + +function sanitizeURL(url) { + { + if (!didWarn && isJavaScriptProtocol.test(url)) { + didWarn = true; + + error('A future version of React will block javascript: URLs as a security precaution. ' + 'Use event handlers instead if you can. If you need to generate unsafe HTML try ' + 'using dangerouslySetInnerHTML instead. React was passed %s.', JSON.stringify(url)); + } + } +} + +/** + * Get the value for a property on a node. Only used in DEV for SSR validation. + * The "expected" argument is used as a hint of what the expected value is. + * Some properties have multiple equivalent values. + */ +function getValueForProperty(node, name, expected, propertyInfo) { + { + if (propertyInfo.mustUseProperty) { + var propertyName = propertyInfo.propertyName; + return node[propertyName]; + } else { + if ( propertyInfo.sanitizeURL) { + // If we haven't fully disabled javascript: URLs, and if + // the hydration is successful of a javascript: URL, we + // still want to warn on the client. + sanitizeURL('' + expected); + } + + var attributeName = propertyInfo.attributeName; + var stringValue = null; + + if (propertyInfo.type === OVERLOADED_BOOLEAN) { + if (node.hasAttribute(attributeName)) { + var value = node.getAttribute(attributeName); + + if (value === '') { + return true; + } + + if (shouldRemoveAttribute(name, expected, propertyInfo, false)) { + return value; + } + + if (value === '' + expected) { + return expected; + } + + return value; + } + } else if (node.hasAttribute(attributeName)) { + if (shouldRemoveAttribute(name, expected, propertyInfo, false)) { + // We had an attribute but shouldn't have had one, so read it + // for the error message. + return node.getAttribute(attributeName); + } + + if (propertyInfo.type === BOOLEAN) { + // If this was a boolean, it doesn't matter what the value is + // the fact that we have it is the same as the expected. + return expected; + } // Even if this property uses a namespace we use getAttribute + // because we assume its namespaced name is the same as our config. + // To use getAttributeNS we need the local name which we don't have + // in our config atm. + + + stringValue = node.getAttribute(attributeName); + } + + if (shouldRemoveAttribute(name, expected, propertyInfo, false)) { + return stringValue === null ? expected : stringValue; + } else if (stringValue === '' + expected) { + return expected; + } else { + return stringValue; + } + } + } +} +/** + * Get the value for a attribute on a node. Only used in DEV for SSR validation. + * The third argument is used as a hint of what the expected value is. Some + * attributes have multiple equivalent values. + */ + +function getValueForAttribute(node, name, expected) { + { + if (!isAttributeNameSafe(name)) { + return; + } // If the object is an opaque reference ID, it's expected that + // the next prop is different than the server value, so just return + // expected + + + if (isOpaqueHydratingObject(expected)) { + return expected; + } + + if (!node.hasAttribute(name)) { + return expected === undefined ? undefined : null; + } + + var value = node.getAttribute(name); + + if (value === '' + expected) { + return expected; + } + + return value; + } +} +/** + * Sets the value for a property on a node. + * + * @param {DOMElement} node + * @param {string} name + * @param {*} value + */ + +function setValueForProperty(node, name, value, isCustomComponentTag) { + var propertyInfo = getPropertyInfo(name); + + if (shouldIgnoreAttribute(name, propertyInfo, isCustomComponentTag)) { + return; + } + + if (shouldRemoveAttribute(name, value, propertyInfo, isCustomComponentTag)) { + value = null; + } // If the prop isn't in the special list, treat it as a simple attribute. + + + if (isCustomComponentTag || propertyInfo === null) { + if (isAttributeNameSafe(name)) { + var _attributeName = name; + + if (value === null) { + node.removeAttribute(_attributeName); + } else { + node.setAttribute(_attributeName, '' + value); + } + } + + return; + } + + var mustUseProperty = propertyInfo.mustUseProperty; + + if (mustUseProperty) { + var propertyName = propertyInfo.propertyName; + + if (value === null) { + var type = propertyInfo.type; + node[propertyName] = type === BOOLEAN ? false : ''; + } else { + // Contrary to `setAttribute`, object properties are properly + // `toString`ed by IE8/9. + node[propertyName] = value; + } + + return; + } // The rest are treated as attributes with special cases. + + + var attributeName = propertyInfo.attributeName, + attributeNamespace = propertyInfo.attributeNamespace; + + if (value === null) { + node.removeAttribute(attributeName); + } else { + var _type = propertyInfo.type; + var attributeValue; + + if (_type === BOOLEAN || _type === OVERLOADED_BOOLEAN && value === true) { + // If attribute type is boolean, we know for sure it won't be an execution sink + // and we won't require Trusted Type here. + attributeValue = ''; + } else { + // `setAttribute` with objects becomes only `[object]` in IE8/9, + // ('' + value) makes it output the correct toString()-value. + { + attributeValue = '' + value; + } + + if (propertyInfo.sanitizeURL) { + sanitizeURL(attributeValue.toString()); + } + } + + if (attributeNamespace) { + node.setAttributeNS(attributeNamespace, attributeName, attributeValue); + } else { + node.setAttribute(attributeName, attributeValue); + } + } +} + +// ATTENTION +// When adding new symbols to this file, +// Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols' +// The Symbol used to tag the ReactElement-like types. If there is no native Symbol +// nor polyfill, then a plain number is used for performance. +var REACT_ELEMENT_TYPE = 0xeac7; +var REACT_PORTAL_TYPE = 0xeaca; +var REACT_FRAGMENT_TYPE = 0xeacb; +var REACT_STRICT_MODE_TYPE = 0xeacc; +var REACT_PROFILER_TYPE = 0xead2; +var REACT_PROVIDER_TYPE = 0xeacd; +var REACT_CONTEXT_TYPE = 0xeace; +var REACT_FORWARD_REF_TYPE = 0xead0; +var REACT_SUSPENSE_TYPE = 0xead1; +var REACT_SUSPENSE_LIST_TYPE = 0xead8; +var REACT_MEMO_TYPE = 0xead3; +var REACT_LAZY_TYPE = 0xead4; +var REACT_BLOCK_TYPE = 0xead9; +var REACT_SERVER_BLOCK_TYPE = 0xeada; +var REACT_FUNDAMENTAL_TYPE = 0xead5; +var REACT_SCOPE_TYPE = 0xead7; +var REACT_OPAQUE_ID_TYPE = 0xeae0; +var REACT_DEBUG_TRACING_MODE_TYPE = 0xeae1; +var REACT_OFFSCREEN_TYPE = 0xeae2; +var REACT_LEGACY_HIDDEN_TYPE = 0xeae3; + +if (typeof Symbol === 'function' && Symbol.for) { + var symbolFor = Symbol.for; + REACT_ELEMENT_TYPE = symbolFor('react.element'); + REACT_PORTAL_TYPE = symbolFor('react.portal'); + REACT_FRAGMENT_TYPE = symbolFor('react.fragment'); + REACT_STRICT_MODE_TYPE = symbolFor('react.strict_mode'); + REACT_PROFILER_TYPE = symbolFor('react.profiler'); + REACT_PROVIDER_TYPE = symbolFor('react.provider'); + REACT_CONTEXT_TYPE = symbolFor('react.context'); + REACT_FORWARD_REF_TYPE = symbolFor('react.forward_ref'); + REACT_SUSPENSE_TYPE = symbolFor('react.suspense'); + REACT_SUSPENSE_LIST_TYPE = symbolFor('react.suspense_list'); + REACT_MEMO_TYPE = symbolFor('react.memo'); + REACT_LAZY_TYPE = symbolFor('react.lazy'); + REACT_BLOCK_TYPE = symbolFor('react.block'); + REACT_SERVER_BLOCK_TYPE = symbolFor('react.server.block'); + REACT_FUNDAMENTAL_TYPE = symbolFor('react.fundamental'); + REACT_SCOPE_TYPE = symbolFor('react.scope'); + REACT_OPAQUE_ID_TYPE = symbolFor('react.opaque.id'); + REACT_DEBUG_TRACING_MODE_TYPE = symbolFor('react.debug_trace_mode'); + REACT_OFFSCREEN_TYPE = symbolFor('react.offscreen'); + REACT_LEGACY_HIDDEN_TYPE = symbolFor('react.legacy_hidden'); +} + +var MAYBE_ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator; +var FAUX_ITERATOR_SYMBOL = '@@iterator'; +function getIteratorFn(maybeIterable) { + if (maybeIterable === null || typeof maybeIterable !== 'object') { + return null; + } + + var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]; + + if (typeof maybeIterator === 'function') { + return maybeIterator; + } + + return null; +} + +// Helpers to patch console.logs to avoid logging during side-effect free +// replaying on render function. This currently only patches the object +// lazily which won't cover if the log function was extracted eagerly. +// We could also eagerly patch the method. +var disabledDepth = 0; +var prevLog; +var prevInfo; +var prevWarn; +var prevError; +var prevGroup; +var prevGroupCollapsed; +var prevGroupEnd; + +function disabledLog() {} + +disabledLog.__reactDisabledLog = true; +function disableLogs() { + { + if (disabledDepth === 0) { + /* eslint-disable react-internal/no-production-logging */ + prevLog = console.log; + prevInfo = console.info; + prevWarn = console.warn; + prevError = console.error; + prevGroup = console.group; + prevGroupCollapsed = console.groupCollapsed; + prevGroupEnd = console.groupEnd; // https://github.com/facebook/react/issues/19099 + + var props = { + configurable: true, + enumerable: true, + value: disabledLog, + writable: true + }; // $FlowFixMe Flow thinks console is immutable. + + Object.defineProperties(console, { + info: props, + log: props, + warn: props, + error: props, + group: props, + groupCollapsed: props, + groupEnd: props + }); + /* eslint-enable react-internal/no-production-logging */ + } + + disabledDepth++; + } +} +function reenableLogs() { + { + disabledDepth--; + + if (disabledDepth === 0) { + /* eslint-disable react-internal/no-production-logging */ + var props = { + configurable: true, + enumerable: true, + writable: true + }; // $FlowFixMe Flow thinks console is immutable. + + Object.defineProperties(console, { + log: _assign({}, props, { + value: prevLog + }), + info: _assign({}, props, { + value: prevInfo + }), + warn: _assign({}, props, { + value: prevWarn + }), + error: _assign({}, props, { + value: prevError + }), + group: _assign({}, props, { + value: prevGroup + }), + groupCollapsed: _assign({}, props, { + value: prevGroupCollapsed + }), + groupEnd: _assign({}, props, { + value: prevGroupEnd + }) + }); + /* eslint-enable react-internal/no-production-logging */ + } + + if (disabledDepth < 0) { + error('disabledDepth fell below zero. ' + 'This is a bug in React. Please file an issue.'); + } + } +} + +var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher; +var prefix; +function describeBuiltInComponentFrame(name, source, ownerFn) { + { + if (prefix === undefined) { + // Extract the VM specific prefix used by each line. + try { + throw Error(); + } catch (x) { + var match = x.stack.trim().match(/\n( *(at )?)/); + prefix = match && match[1] || ''; + } + } // We use the prefix to ensure our stacks line up with native stack frames. + + + return '\n' + prefix + name; + } +} +var reentry = false; +var componentFrameCache; + +{ + var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map; + componentFrameCache = new PossiblyWeakMap(); +} + +function describeNativeComponentFrame(fn, construct) { + // If something asked for a stack inside a fake render, it should get ignored. + if (!fn || reentry) { + return ''; + } + + { + var frame = componentFrameCache.get(fn); + + if (frame !== undefined) { + return frame; + } + } + + var control; + reentry = true; + var previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe It does accept undefined. + + Error.prepareStackTrace = undefined; + var previousDispatcher; + + { + previousDispatcher = ReactCurrentDispatcher.current; // Set the dispatcher in DEV because this might be call in the render function + // for warnings. + + ReactCurrentDispatcher.current = null; + disableLogs(); + } + + try { + // This should throw. + if (construct) { + // Something should be setting the props in the constructor. + var Fake = function () { + throw Error(); + }; // $FlowFixMe + + + Object.defineProperty(Fake.prototype, 'props', { + set: function () { + // We use a throwing setter instead of frozen or non-writable props + // because that won't throw in a non-strict mode function. + throw Error(); + } + }); + + if (typeof Reflect === 'object' && Reflect.construct) { + // We construct a different control for this case to include any extra + // frames added by the construct call. + try { + Reflect.construct(Fake, []); + } catch (x) { + control = x; + } + + Reflect.construct(fn, [], Fake); + } else { + try { + Fake.call(); + } catch (x) { + control = x; + } + + fn.call(Fake.prototype); + } + } else { + try { + throw Error(); + } catch (x) { + control = x; + } + + fn(); + } + } catch (sample) { + // This is inlined manually because closure doesn't do it for us. + if (sample && control && typeof sample.stack === 'string') { + // This extracts the first frame from the sample that isn't also in the control. + // Skipping one frame that we assume is the frame that calls the two. + var sampleLines = sample.stack.split('\n'); + var controlLines = control.stack.split('\n'); + var s = sampleLines.length - 1; + var c = controlLines.length - 1; + + while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) { + // We expect at least one stack frame to be shared. + // Typically this will be the root most one. However, stack frames may be + // cut off due to maximum stack limits. In this case, one maybe cut off + // earlier than the other. We assume that the sample is longer or the same + // and there for cut off earlier. So we should find the root most frame in + // the sample somewhere in the control. + c--; + } + + for (; s >= 1 && c >= 0; s--, c--) { + // Next we find the first one that isn't the same which should be the + // frame that called our sample function and the control. + if (sampleLines[s] !== controlLines[c]) { + // In V8, the first line is describing the message but other VMs don't. + // If we're about to return the first line, and the control is also on the same + // line, that's a pretty good indicator that our sample threw at same line as + // the control. I.e. before we entered the sample frame. So we ignore this result. + // This can happen if you passed a class to function component, or non-function. + if (s !== 1 || c !== 1) { + do { + s--; + c--; // We may still have similar intermediate frames from the construct call. + // The next one that isn't the same should be our match though. + + if (c < 0 || sampleLines[s] !== controlLines[c]) { + // V8 adds a "new" prefix for native classes. Let's remove it to make it prettier. + var _frame = '\n' + sampleLines[s].replace(' at new ', ' at '); + + { + if (typeof fn === 'function') { + componentFrameCache.set(fn, _frame); + } + } // Return the line we found. + + + return _frame; + } + } while (s >= 1 && c >= 0); + } + + break; + } + } + } + } finally { + reentry = false; + + { + ReactCurrentDispatcher.current = previousDispatcher; + reenableLogs(); + } + + Error.prepareStackTrace = previousPrepareStackTrace; + } // Fallback to just using the name if we couldn't make it throw. + + + var name = fn ? fn.displayName || fn.name : ''; + var syntheticFrame = name ? describeBuiltInComponentFrame(name) : ''; + + { + if (typeof fn === 'function') { + componentFrameCache.set(fn, syntheticFrame); + } + } + + return syntheticFrame; +} + +function describeClassComponentFrame(ctor, source, ownerFn) { + { + return describeNativeComponentFrame(ctor, true); + } +} +function describeFunctionComponentFrame(fn, source, ownerFn) { + { + return describeNativeComponentFrame(fn, false); + } +} + +function shouldConstruct(Component) { + var prototype = Component.prototype; + return !!(prototype && prototype.isReactComponent); +} + +function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) { + + if (type == null) { + return ''; + } + + if (typeof type === 'function') { + { + return describeNativeComponentFrame(type, shouldConstruct(type)); + } + } + + if (typeof type === 'string') { + return describeBuiltInComponentFrame(type); + } + + switch (type) { + case REACT_SUSPENSE_TYPE: + return describeBuiltInComponentFrame('Suspense'); + + case REACT_SUSPENSE_LIST_TYPE: + return describeBuiltInComponentFrame('SuspenseList'); + } + + if (typeof type === 'object') { + switch (type.$$typeof) { + case REACT_FORWARD_REF_TYPE: + return describeFunctionComponentFrame(type.render); + + case REACT_MEMO_TYPE: + // Memo may contain any component type so we recursively resolve it. + return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn); + + case REACT_BLOCK_TYPE: + return describeFunctionComponentFrame(type._render); + + case REACT_LAZY_TYPE: + { + var lazyComponent = type; + var payload = lazyComponent._payload; + var init = lazyComponent._init; + + try { + // Lazy may contain any component type so we recursively resolve it. + return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn); + } catch (x) {} + } + } + } + + return ''; +} + +function describeFiber(fiber) { + var owner = fiber._debugOwner ? fiber._debugOwner.type : null ; + var source = fiber._debugSource ; + + switch (fiber.tag) { + case HostComponent: + return describeBuiltInComponentFrame(fiber.type); + + case LazyComponent: + return describeBuiltInComponentFrame('Lazy'); + + case SuspenseComponent: + return describeBuiltInComponentFrame('Suspense'); + + case SuspenseListComponent: + return describeBuiltInComponentFrame('SuspenseList'); + + case FunctionComponent: + case IndeterminateComponent: + case SimpleMemoComponent: + return describeFunctionComponentFrame(fiber.type); + + case ForwardRef: + return describeFunctionComponentFrame(fiber.type.render); + + case Block: + return describeFunctionComponentFrame(fiber.type._render); + + case ClassComponent: + return describeClassComponentFrame(fiber.type); + + default: + return ''; + } +} + +function getStackByFiberInDevAndProd(workInProgress) { + try { + var info = ''; + var node = workInProgress; + + do { + info += describeFiber(node); + node = node.return; + } while (node); + + return info; + } catch (x) { + return '\nError generating stack: ' + x.message + '\n' + x.stack; + } +} + +function getWrappedName(outerType, innerType, wrapperName) { + var functionName = innerType.displayName || innerType.name || ''; + return outerType.displayName || (functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName); +} + +function getContextName(type) { + return type.displayName || 'Context'; +} + +function getComponentName(type) { + if (type == null) { + // Host root, text node or just invalid type. + return null; + } + + { + if (typeof type.tag === 'number') { + error('Received an unexpected object in getComponentName(). ' + 'This is likely a bug in React. Please file an issue.'); + } + } + + if (typeof type === 'function') { + return type.displayName || type.name || null; + } + + if (typeof type === 'string') { + return type; + } + + switch (type) { + case REACT_FRAGMENT_TYPE: + return 'Fragment'; + + case REACT_PORTAL_TYPE: + return 'Portal'; + + case REACT_PROFILER_TYPE: + return 'Profiler'; + + case REACT_STRICT_MODE_TYPE: + return 'StrictMode'; + + case REACT_SUSPENSE_TYPE: + return 'Suspense'; + + case REACT_SUSPENSE_LIST_TYPE: + return 'SuspenseList'; + } + + if (typeof type === 'object') { + switch (type.$$typeof) { + case REACT_CONTEXT_TYPE: + var context = type; + return getContextName(context) + '.Consumer'; + + case REACT_PROVIDER_TYPE: + var provider = type; + return getContextName(provider._context) + '.Provider'; + + case REACT_FORWARD_REF_TYPE: + return getWrappedName(type, type.render, 'ForwardRef'); + + case REACT_MEMO_TYPE: + return getComponentName(type.type); + + case REACT_BLOCK_TYPE: + return getComponentName(type._render); + + case REACT_LAZY_TYPE: + { + var lazyComponent = type; + var payload = lazyComponent._payload; + var init = lazyComponent._init; + + try { + return getComponentName(init(payload)); + } catch (x) { + return null; + } + } + } + } + + return null; +} + +var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; +var current = null; +var isRendering = false; +function getCurrentFiberOwnerNameInDevOrNull() { + { + if (current === null) { + return null; + } + + var owner = current._debugOwner; + + if (owner !== null && typeof owner !== 'undefined') { + return getComponentName(owner.type); + } + } + + return null; +} + +function getCurrentFiberStackInDev() { + { + if (current === null) { + return ''; + } // Safe because if current fiber exists, we are reconciling, + // and it is guaranteed to be the work-in-progress version. + + + return getStackByFiberInDevAndProd(current); + } +} + +function resetCurrentFiber() { + { + ReactDebugCurrentFrame.getCurrentStack = null; + current = null; + isRendering = false; + } +} +function setCurrentFiber(fiber) { + { + ReactDebugCurrentFrame.getCurrentStack = getCurrentFiberStackInDev; + current = fiber; + isRendering = false; + } +} +function setIsRendering(rendering) { + { + isRendering = rendering; + } +} +function getIsRendering() { + { + return isRendering; + } +} + +// Flow does not allow string concatenation of most non-string types. To work +// around this limitation, we use an opaque type that can only be obtained by +// passing the value through getToStringValue first. +function toString(value) { + return '' + value; +} +function getToStringValue(value) { + switch (typeof value) { + case 'boolean': + case 'number': + case 'object': + case 'string': + case 'undefined': + return value; + + default: + // function, symbol are assigned as empty strings + return ''; + } +} + +var hasReadOnlyValue = { + button: true, + checkbox: true, + image: true, + hidden: true, + radio: true, + reset: true, + submit: true +}; +function checkControlledValueProps(tagName, props) { + { + if (!(hasReadOnlyValue[props.type] || props.onChange || props.onInput || props.readOnly || props.disabled || props.value == null)) { + error('You provided a `value` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultValue`. Otherwise, ' + 'set either `onChange` or `readOnly`.'); + } + + if (!(props.onChange || props.readOnly || props.disabled || props.checked == null)) { + error('You provided a `checked` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultChecked`. Otherwise, ' + 'set either `onChange` or `readOnly`.'); + } + } +} + +function isCheckable(elem) { + var type = elem.type; + var nodeName = elem.nodeName; + return nodeName && nodeName.toLowerCase() === 'input' && (type === 'checkbox' || type === 'radio'); +} + +function getTracker(node) { + return node._valueTracker; +} + +function detachTracker(node) { + node._valueTracker = null; +} + +function getValueFromNode(node) { + var value = ''; + + if (!node) { + return value; + } + + if (isCheckable(node)) { + value = node.checked ? 'true' : 'false'; + } else { + value = node.value; + } + + return value; +} + +function trackValueOnNode(node) { + var valueField = isCheckable(node) ? 'checked' : 'value'; + var descriptor = Object.getOwnPropertyDescriptor(node.constructor.prototype, valueField); + var currentValue = '' + node[valueField]; // if someone has already defined a value or Safari, then bail + // and don't track value will cause over reporting of changes, + // but it's better then a hard failure + // (needed for certain tests that spyOn input values and Safari) + + if (node.hasOwnProperty(valueField) || typeof descriptor === 'undefined' || typeof descriptor.get !== 'function' || typeof descriptor.set !== 'function') { + return; + } + + var get = descriptor.get, + set = descriptor.set; + Object.defineProperty(node, valueField, { + configurable: true, + get: function () { + return get.call(this); + }, + set: function (value) { + currentValue = '' + value; + set.call(this, value); + } + }); // We could've passed this the first time + // but it triggers a bug in IE11 and Edge 14/15. + // Calling defineProperty() again should be equivalent. + // https://github.com/facebook/react/issues/11768 + + Object.defineProperty(node, valueField, { + enumerable: descriptor.enumerable + }); + var tracker = { + getValue: function () { + return currentValue; + }, + setValue: function (value) { + currentValue = '' + value; + }, + stopTracking: function () { + detachTracker(node); + delete node[valueField]; + } + }; + return tracker; +} + +function track(node) { + if (getTracker(node)) { + return; + } // TODO: Once it's just Fiber we can move this to node._wrapperState + + + node._valueTracker = trackValueOnNode(node); +} +function updateValueIfChanged(node) { + if (!node) { + return false; + } + + var tracker = getTracker(node); // if there is no tracker at this point it's unlikely + // that trying again will succeed + + if (!tracker) { + return true; + } + + var lastValue = tracker.getValue(); + var nextValue = getValueFromNode(node); + + if (nextValue !== lastValue) { + tracker.setValue(nextValue); + return true; + } + + return false; +} + +function getActiveElement(doc) { + doc = doc || (typeof document !== 'undefined' ? document : undefined); + + if (typeof doc === 'undefined') { + return null; + } + + try { + return doc.activeElement || doc.body; + } catch (e) { + return doc.body; + } +} + +var didWarnValueDefaultValue = false; +var didWarnCheckedDefaultChecked = false; +var didWarnControlledToUncontrolled = false; +var didWarnUncontrolledToControlled = false; + +function isControlled(props) { + var usesChecked = props.type === 'checkbox' || props.type === 'radio'; + return usesChecked ? props.checked != null : props.value != null; +} +/** + * Implements an host component that allows setting these optional + * props: `checked`, `value`, `defaultChecked`, and `defaultValue`. + * + * If `checked` or `value` are not supplied (or null/undefined), user actions + * that affect the checked state or value will trigger updates to the element. + * + * If they are supplied (and not null/undefined), the rendered element will not + * trigger updates to the element. Instead, the props must change in order for + * the rendered element to be updated. + * + * The rendered element will be initialized as unchecked (or `defaultChecked`) + * with an empty value (or `defaultValue`). + * + * See http://www.w3.org/TR/2012/WD-html5-20121025/the-input-element.html + */ + + +function getHostProps(element, props) { + var node = element; + var checked = props.checked; + + var hostProps = _assign({}, props, { + defaultChecked: undefined, + defaultValue: undefined, + value: undefined, + checked: checked != null ? checked : node._wrapperState.initialChecked + }); + + return hostProps; +} +function initWrapperState(element, props) { + { + checkControlledValueProps('input', props); + + if (props.checked !== undefined && props.defaultChecked !== undefined && !didWarnCheckedDefaultChecked) { + error('%s contains an input of type %s with both checked and defaultChecked props. ' + 'Input elements must be either controlled or uncontrolled ' + '(specify either the checked prop, or the defaultChecked prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://reactjs.org/link/controlled-components', getCurrentFiberOwnerNameInDevOrNull() || 'A component', props.type); + + didWarnCheckedDefaultChecked = true; + } + + if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValueDefaultValue) { + error('%s contains an input of type %s with both value and defaultValue props. ' + 'Input elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://reactjs.org/link/controlled-components', getCurrentFiberOwnerNameInDevOrNull() || 'A component', props.type); + + didWarnValueDefaultValue = true; + } + } + + var node = element; + var defaultValue = props.defaultValue == null ? '' : props.defaultValue; + node._wrapperState = { + initialChecked: props.checked != null ? props.checked : props.defaultChecked, + initialValue: getToStringValue(props.value != null ? props.value : defaultValue), + controlled: isControlled(props) + }; +} +function updateChecked(element, props) { + var node = element; + var checked = props.checked; + + if (checked != null) { + setValueForProperty(node, 'checked', checked, false); + } +} +function updateWrapper(element, props) { + var node = element; + + { + var controlled = isControlled(props); + + if (!node._wrapperState.controlled && controlled && !didWarnUncontrolledToControlled) { + error('A component is changing an uncontrolled input to be controlled. ' + 'This is likely caused by the value changing from undefined to ' + 'a defined value, which should not happen. ' + 'Decide between using a controlled or uncontrolled input ' + 'element for the lifetime of the component. More info: https://reactjs.org/link/controlled-components'); + + didWarnUncontrolledToControlled = true; + } + + if (node._wrapperState.controlled && !controlled && !didWarnControlledToUncontrolled) { + error('A component is changing a controlled input to be uncontrolled. ' + 'This is likely caused by the value changing from a defined to ' + 'undefined, which should not happen. ' + 'Decide between using a controlled or uncontrolled input ' + 'element for the lifetime of the component. More info: https://reactjs.org/link/controlled-components'); + + didWarnControlledToUncontrolled = true; + } + } + + updateChecked(element, props); + var value = getToStringValue(props.value); + var type = props.type; + + if (value != null) { + if (type === 'number') { + if (value === 0 && node.value === '' || // We explicitly want to coerce to number here if possible. + // eslint-disable-next-line + node.value != value) { + node.value = toString(value); + } + } else if (node.value !== toString(value)) { + node.value = toString(value); + } + } else if (type === 'submit' || type === 'reset') { + // Submit/reset inputs need the attribute removed completely to avoid + // blank-text buttons. + node.removeAttribute('value'); + return; + } + + { + // When syncing the value attribute, the value comes from a cascade of + // properties: + // 1. The value React property + // 2. The defaultValue React property + // 3. Otherwise there should be no change + if (props.hasOwnProperty('value')) { + setDefaultValue(node, props.type, value); + } else if (props.hasOwnProperty('defaultValue')) { + setDefaultValue(node, props.type, getToStringValue(props.defaultValue)); + } + } + + { + // When syncing the checked attribute, it only changes when it needs + // to be removed, such as transitioning from a checkbox into a text input + if (props.checked == null && props.defaultChecked != null) { + node.defaultChecked = !!props.defaultChecked; + } + } +} +function postMountWrapper(element, props, isHydrating) { + var node = element; // Do not assign value if it is already set. This prevents user text input + // from being lost during SSR hydration. + + if (props.hasOwnProperty('value') || props.hasOwnProperty('defaultValue')) { + var type = props.type; + var isButton = type === 'submit' || type === 'reset'; // Avoid setting value attribute on submit/reset inputs as it overrides the + // default value provided by the browser. See: #12872 + + if (isButton && (props.value === undefined || props.value === null)) { + return; + } + + var initialValue = toString(node._wrapperState.initialValue); // Do not assign value if it is already set. This prevents user text input + // from being lost during SSR hydration. + + if (!isHydrating) { + { + // When syncing the value attribute, the value property should use + // the wrapperState._initialValue property. This uses: + // + // 1. The value React property when present + // 2. The defaultValue React property when present + // 3. An empty string + if (initialValue !== node.value) { + node.value = initialValue; + } + } + } + + { + // Otherwise, the value attribute is synchronized to the property, + // so we assign defaultValue to the same thing as the value property + // assignment step above. + node.defaultValue = initialValue; + } + } // Normally, we'd just do `node.checked = node.checked` upon initial mount, less this bug + // this is needed to work around a chrome bug where setting defaultChecked + // will sometimes influence the value of checked (even after detachment). + // Reference: https://bugs.chromium.org/p/chromium/issues/detail?id=608416 + // We need to temporarily unset name to avoid disrupting radio button groups. + + + var name = node.name; + + if (name !== '') { + node.name = ''; + } + + { + // When syncing the checked attribute, both the checked property and + // attribute are assigned at the same time using defaultChecked. This uses: + // + // 1. The checked React property when present + // 2. The defaultChecked React property when present + // 3. Otherwise, false + node.defaultChecked = !node.defaultChecked; + node.defaultChecked = !!node._wrapperState.initialChecked; + } + + if (name !== '') { + node.name = name; + } +} +function restoreControlledState(element, props) { + var node = element; + updateWrapper(node, props); + updateNamedCousins(node, props); +} + +function updateNamedCousins(rootNode, props) { + var name = props.name; + + if (props.type === 'radio' && name != null) { + var queryRoot = rootNode; + + while (queryRoot.parentNode) { + queryRoot = queryRoot.parentNode; + } // If `rootNode.form` was non-null, then we could try `form.elements`, + // but that sometimes behaves strangely in IE8. We could also try using + // `form.getElementsByName`, but that will only return direct children + // and won't include inputs that use the HTML5 `form=` attribute. Since + // the input might not even be in a form. It might not even be in the + // document. Let's just use the local `querySelectorAll` to ensure we don't + // miss anything. + + + var group = queryRoot.querySelectorAll('input[name=' + JSON.stringify('' + name) + '][type="radio"]'); + + for (var i = 0; i < group.length; i++) { + var otherNode = group[i]; + + if (otherNode === rootNode || otherNode.form !== rootNode.form) { + continue; + } // This will throw if radio buttons rendered by different copies of React + // and the same name are rendered into the same form (same as #1939). + // That's probably okay; we don't support it just as we don't support + // mixing React radio buttons with non-React ones. + + + var otherProps = getFiberCurrentPropsFromNode(otherNode); + + if (!otherProps) { + { + throw Error( "ReactDOMInput: Mixing React and non-React radio inputs with the same `name` is not supported." ); + } + } // We need update the tracked value on the named cousin since the value + // was changed but the input saw no event or value set + + + updateValueIfChanged(otherNode); // If this is a controlled radio button group, forcing the input that + // was previously checked to update will cause it to be come re-checked + // as appropriate. + + updateWrapper(otherNode, otherProps); + } + } +} // In Chrome, assigning defaultValue to certain input types triggers input validation. +// For number inputs, the display value loses trailing decimal points. For email inputs, +// Chrome raises "The specified value is not a valid email address". +// +// Here we check to see if the defaultValue has actually changed, avoiding these problems +// when the user is inputting text +// +// https://github.com/facebook/react/issues/7253 + + +function setDefaultValue(node, type, value) { + if ( // Focused number inputs synchronize on blur. See ChangeEventPlugin.js + type !== 'number' || getActiveElement(node.ownerDocument) !== node) { + if (value == null) { + node.defaultValue = toString(node._wrapperState.initialValue); + } else if (node.defaultValue !== toString(value)) { + node.defaultValue = toString(value); + } + } +} + +var didWarnSelectedSetOnOption = false; +var didWarnInvalidChild = false; + +function flattenChildren(children) { + var content = ''; // Flatten children. We'll warn if they are invalid + // during validateProps() which runs for hydration too. + // Note that this would throw on non-element objects. + // Elements are stringified (which is normally irrelevant + // but matters for ). + + React.Children.forEach(children, function (child) { + if (child == null) { + return; + } + + content += child; // Note: we don't warn about invalid children here. + // Instead, this is done separately below so that + // it happens during the hydration code path too. + }); + return content; +} +/** + * Implements an