@statewalker/webrun-files 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/dist/cjs/index.cjs +564 -0
  2. package/dist/esm/index.js +551 -0
  3. package/dist/files-api.d.ts +44 -0
  4. package/dist/files-api.d.ts.map +1 -0
  5. package/dist/impl/index.d.ts +6 -0
  6. package/dist/impl/index.d.ts.map +1 -0
  7. package/dist/impl/mem-files-api.d.ts +13 -0
  8. package/dist/impl/mem-files-api.d.ts.map +1 -0
  9. package/dist/impl/node-files-api.d.ts +24 -0
  10. package/dist/impl/node-files-api.d.ts.map +1 -0
  11. package/dist/index.d.ts +11 -0
  12. package/dist/index.d.ts.map +1 -0
  13. package/dist/types.d.ts +57 -0
  14. package/dist/types.d.ts.map +1 -0
  15. package/dist/utils/collect-stream.d.ts +16 -0
  16. package/dist/utils/collect-stream.d.ts.map +1 -0
  17. package/dist/utils/index.d.ts +7 -0
  18. package/dist/utils/index.d.ts.map +1 -0
  19. package/dist/utils/normalize-path.d.ts +21 -0
  20. package/dist/utils/normalize-path.d.ts.map +1 -0
  21. package/dist/utils/path-utils.d.ts +20 -0
  22. package/dist/utils/path-utils.d.ts.map +1 -0
  23. package/package.json +29 -31
  24. package/src/files-api.ts +167 -0
  25. package/src/impl/index.ts +6 -0
  26. package/src/impl/mem-files-api.ts +306 -0
  27. package/src/impl/node-files-api.ts +261 -0
  28. package/src/index.ts +35 -0
  29. package/src/types.ts +68 -0
  30. package/src/utils/collect-stream.ts +35 -0
  31. package/src/utils/index.ts +7 -0
  32. package/src/utils/normalize-path.ts +34 -0
  33. package/src/utils/path-utils.ts +46 -0
  34. package/CHANGELOG.md +0 -2
  35. package/README.md +0 -17
  36. package/dist/index-umd.js +0 -1053
  37. package/dist/index-umd.min.js +0 -2
  38. package/dist/index.js +0 -1032
  39. package/dist/index.min.js +0 -2
  40. package/index.js +0 -1
  41. package/src/BrowserFilesApi.js +0 -335
  42. package/src/FilesApi.js +0 -133
  43. package/src/MemFilesApi.js +0 -129
  44. package/src/NodeFilesApi.js +0 -222
  45. package/src/addFilesApiLogger.js +0 -25
  46. package/src/getMimeType.js +0 -19
  47. package/src/index.js +0 -10
  48. package/src/mimeTypes.js +0 -96
  49. package/src/normalizePath.js +0 -8
  50. package/src/notImplemented.js +0 -3
  51. package/src/openBrowserFilesApi.js +0 -67
package/dist/index.min.js DELETED
@@ -1,2 +0,0 @@
1
- // @statewalker/webrun-files v0.3.0 https://github.com/statewalker/webrun-files Copyright 2023 Mikhail Kotelnikov
2
- function t(t){const e=t.split("/").filter((t=>!!t&&"."!==t));return 0===e.length&&e.push(""),e.unshift(""),e.join("/")}function e(){throw new Error("Not implemented.")}class i{constructor(t){this.options=t||{}}async*list(t,i={}){yield e()}async stats(t){return e()}async remove(t){return e()}async write(t,i){return e()}async*read(t,i){yield e()}async copy(t,e,i={}){const n=async(t,e,i)=>{e=`${e}${i.path.substring(t.length)}`;const n=this.read(i);return await this.write(e,n)},s=void 0===i.recursive||!!i.recursive,o=await this.stats(t);if("directory"===o.kind)for await(const o of this.list(t,{...i,recursive:s}))"directory"!==o.kind&&await n(t,e,o);else await n(t,e,o);return!0}async move(t,e,i={}){return!!await this.copy(t,e,i)&&(await this.remove(t),!0)}normalizePath(e){return t("object"==typeof e?e.path:e+"")}}const n=[{extensions:["aac"],mime:"audio/aac",description:"AAC audio"},{extensions:["abw"],mime:"application/x-abiword",description:"AbiWord document"},{extensions:["arc"],mime:"application/x-freearc",description:"Archive document (multiple files embedded)"},{extensions:["avi"],mime:"video/x-msvideo",description:"AVI: Audio Video Interleave"},{extensions:["azw"],mime:"application/vnd.amazon.ebook",description:"Amazon Kindle eBook format"},{extensions:["bin"],mime:"application/octet-stream",description:"Any kind of binary data"},{extensions:["bmp"],mime:"image/bmp",description:"Windows OS/2 Bitmap Graphics"},{extensions:["bz"],mime:"application/x-bzip",description:"BZip archive"},{extensions:["bz2"],mime:"application/x-bzip2",description:"BZip2 archive"},{extensions:["csh"],mime:"application/x-csh",description:"C-Shell script"},{extensions:["css"],mime:"text/css",description:"Cascading Style Sheets (CSS)"},{extensions:["csv"],mime:"text/csv",description:"Comma-separated values (CSV)"},{extensions:["doc"],mime:"application/msword",description:"Microsoft Word"},{extensions:["docx"],mime:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",description:"Microsoft Word (OpenXML)"},{extensions:["eot"],mime:"application/vnd.ms-fontobject",description:"MS Embedded OpenType fonts"},{extensions:["epub"],mime:"application/epub+zip",description:"Electronic publication (EPUB)"},{extensions:["gz"],mime:"application/gzip",description:"GZip Compressed Archive"},{extensions:["gif"],mime:"image/gif",description:"Graphics Interchange Format (GIF)"},{extensions:["htm","html"],mime:"text/html",description:"HyperText Markup Language (HTML)"},{extensions:["ico"],mime:"image/vnd.microsoft.icon",description:"Icon format"},{extensions:["ics"],mime:"text/calendar",description:"iCalendar format"},{extensions:["jar"],mime:"application/java-archive",description:"Java Archive (JAR)"},{extensions:["jpg","jpeg"],mime:"image/jpeg",description:"JPEG images"},{extensions:["js"],mime:"text/javascript",description:"JavaScript per the following specifications: https://html.spec.whatwg.org/multipage/#scriptingLanguages, https://html.spec.whatwg.org/multipage/#dependencies:willful-violation, https://datatracker.ietf.org/doc/draft-ietf-dispatch-javascript-mjs/"},{extensions:["json"],mime:"application/json",description:"JSON format"},{extensions:["jsonld"],mime:"application/ld+json",description:"JSON-LD format"},{extensions:["mid","midi"],mime:"application/ld+json",description:"Musical Instrument Digital Interface (MIDI)\taudio/midi audio/x-midi"},{extensions:["mjs"],mime:"text/javascript",description:"JavaScript module"},{extensions:["mp3"],mime:"audio/mpeg",description:"MP3 audio"},{extensions:["md"],mime:"text/markdown",description:"Markdown"},{extensions:["mpeg"],mime:"video/mpeg",description:"MPEG Video"},{extensions:["mpkg"],mime:"application/vnd.apple.installer+xml",description:"Apple Installer Package"},{extensions:["odp"],mime:"application/vnd.oasis.opendocument.presentation",description:"OpenDocument presentation document"},{extensions:["ods"],mime:"application/vnd.oasis.opendocument.spreadsheet",description:"OpenDocument spreadsheet document"},{extensions:["odt"],mime:"application/vnd.oasis.opendocument.text",description:"OpenDocument text document"},{extensions:["oga"],mime:"audio/ogg",description:"OGG audio"},{extensions:["ogv"],mime:"video/ogg",description:"OGG video"},{extensions:["ogx"],mime:"application/ogg",description:"OGG"},{extensions:["opus"],mime:"audio/opus",description:"Opus audio"},{extensions:["otf"],mime:"font/otf",description:"OpenType font"},{extensions:["png"],mime:"image/png",description:"Portable Network Graphics"},{extensions:["pdf"],mime:"application/pdf",description:"Adobe Portable Document Format (PDF)"},{extensions:["php"],mime:"application/x-httpd-php",description:"Hypertext Preprocessor (Personal Home Page)"},{extensions:["ppt"],mime:"application/vnd.ms-powerpoint",description:"Microsoft PowerPoint"},{extensions:["pptx"],mime:"application/vnd.openxmlformats-officedocument.presentationml.presentation",description:"Microsoft PowerPoint (OpenXML)"},{extensions:["rar"],mime:"application/vnd.rar",description:"RAR archive"},{extensions:["rtf"],mime:"application/rtf",description:"Rich Text Format (RTF)"},{extensions:["sh"],mime:"application/x-sh",description:"Bourne shell script"},{extensions:["svg"],mime:"image/svg+xml",description:"Scalable Vector Graphics (SVG)"},{extensions:["swf"],mime:"application/x-shockwave-flash",description:"Small web format (SWF) or Adobe Flash document"},{extensions:["tar"],mime:"application/x-tar",description:"Tape Archive (TAR)"},{extensions:["tif","tiff"],mime:"image/tiff",description:"Tagged Image File Format (TIFF)"},{extensions:["ttf"],mime:"font/ttf",description:"TrueType Font"},{extensions:["txt"],mime:"text/plain",description:"Text, (generally ASCII or ISO 8859-n)"},{extensions:["vsd"],mime:"application/vnd.visio",description:"Microsoft Visio"},{extensions:["wav"],mime:"audio/wav",description:"Waveform Audio Format"},{extensions:["weba"],mime:"audio/webm",description:"WEBM audio"},{extensions:["webm"],mime:"video/webm",description:"WEBM video"},{extensions:["webp"],mime:"image/webp",description:"WEBP image"},{extensions:["woff"],mime:"font/woff",description:"Web Open Font Format (WOFF)"},{extensions:["woff2"],mime:"font/woff2",description:"Web Open Font Format (WOFF)"},{extensions:["xhtml"],mime:"application/xhtml+xml",description:"XHTML"},{extensions:["xls"],mime:"application/vnd.ms-excel",description:"Microsoft Excel"},{extensions:["xlsx"],mime:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",description:"Microsoft Excel (OpenXML)"},{extensions:["xml"],mime:"application/xml",description:"XML; application/xml - if not readable from casual users (RFC 3023, section 3); text/xml - if readable from casual users (RFC 3023, section 3)"},{extensions:["xul"],mime:"application/vnd.mozilla.xul+xml",description:"XUL"},{extensions:["zip"],mime:"application/zip",description:"ZIP archive"},{extensions:["3gp"],mime:"video/3gpp",description:"3GPP audio/video container"},{extensions:["3g2"],mime:"video/3gpp2",description:"3GPP2 audio/video container; audio/3gpp if it doesn't contain video; audio/3gpp2 if it doesn't contain video"},{extensions:["7z"],mime:"application/x-7z-compressed",description:"7-zip archive"},{extensions:["jsx"],mime:"text/jsx",description:"JavaScript Syntax Extension / JavaScript XML format"},{extensions:["ts"],mime:"text/ts",description:"TypeScript format"},{extensions:["tsx"],mime:"text/tsx",description:"TypeScript Syntax Extension / TypeScript XML format"}],s=n.reduce(((t,e)=>(t[e.mime]=e.description,t)),{}),o=n.reduce(((t,e)=>{for(const i of e.extensions)t[i]=e.mime;return t}),{}),a=n.reduce(((t,e)=>(t[e.mime]=e.extensions,t)),{});function r(t){const e=t=t||"",i=(t=(t=t.split("?").shift()).split("/").pop()).split(".").pop();let n=o[i];return n||(n=e.match(/api\.observablehq\.com/)||e.match(/\.ojs$/)?"application/javascript-observable":"application/binary"),n}class c extends i{constructor(t){super(t),this.index={"/":{kind:"directory",path:"/",name:""}}}async*list(t,{recursive:e=!1}={}){await this._init();const i=this.normalizePath(t),n=this._getPaths();for(const t of n){if(0!==t.indexOf(i)||t===i)continue;const n=t.substring(i.length+1).split("/");(e||1===n.length)&&(yield this._getFileInfo(t))}}async stats(t){await this._init();const e=this.normalizePath(t);return this._getFileInfo(e)}async remove(t){await this._init();const e=await this.stats(t);if(!e)return!1;for await(const{path:t}of this.list(e,{recursive:!0}))"/"!==t&&delete this.index[t];delete this.index[e.path]}async write(t,e){await this._init(),await this._doWrite(t,e)}async*read(t){await this._init();const e=this.normalizePath(t),i=this.index[e];if(!i||"file"!==i.kind)return;const n=i.content;yield*n}async _init(){return this._initPromise=this._initPromise||Promise.resolve().then((()=>this._addEntries(this.options.files)))}async _doWrite(t,e){const i=this.normalizePath(t).split("/").filter((t=>!!t)),n=[""];let s;for(let t=0;t<i.length;t++){const e=i[t];n.push(e);const o=n.join("/");s=this.index[o]=this.index[o]||{path:o,name:e,kind:"directory"}}s.kind="file",s.content=[],s.type=r(s.path),s.size=0,s.lastModified=Date.now(),"function"==typeof e&&(e=e());for await(let t of e)t=new Uint8Array(t),s.content.push(t),s.size+=t.length}async _addEntries(t={}){for(let[e,i]of Object.entries(t))"string"==typeof i?i=[(new TextEncoder).encode(i)]:i instanceof Uint8Array&&(i=[i]),await this._doWrite(e,i)}_getPaths(){return this._getIndexPaths(this.index)}_getIndexPaths(t){return Object.keys(t).sort((function(t,e){return t>e?1:t<e?-1:0}))}_getFileInfo(t){const e=this.index[t];if(!e)return null;const i={...e};return delete i.content,i}}class d extends i{constructor(t){if(super(t),!this.fs)throw new Error("File System is not defined.");if(!this.rootDir)throw new Error("Root directory is not defined.")}get rootDirSegments(){return this._rootDirSegments||(this._rootDirSegments=this._toPathSegments(this.options.rootDir||"./")),this._rootDirSegments}get rootDir(){return this._rootDir||(this._rootDir=this.rootDirSegments.join("/")),this._rootDir}get fs(){return this.options.fs}async _init(){return this._initialized=this._initialized||(async()=>{const t=this.rootDir;return await m(this.fs,t)})()}async*list(t,{recursive:e=!1}={}){await this._init();const i=this._expandPath(t),n=await this._stats(i);if(n&&"directory"===n.kind)for await(let t of f(this.fs,i,e))yield this._getFileInfo(t.path,t.stat)}async stats(t){await this._init();const e=this._expandPath(t);return this._stats(e)}async remove(t){await this._init();const e=this._expandPath(t);return await h(this.fs,e)}async write(t,e){await this._init();const i=this._expandPath(t),n=p(i);let s;await this.fs.mkdir(n,{recursive:!0});try{s=await this.fs.open(i,"w"),"function"==typeof e&&(e=e()),await s.writeFile(e)}finally{s&&await s.close()}}async*read(t,{start:e=0,bufferSize:i=8192}={}){await this._init();const n=this._expandPath(t);let s;try{s=await this.fs.open(n,"r");const t=0;for(let n=e,o=0;;n+=o){const e=new Uint8ClampedArray(i),a=await s.read(e,t,i,n);if(o=a.bytesRead,0===o)break;yield o<i?a.buffer.slice(0,o):a.buffer}}finally{s&&await s.close()}}async _stats(t){try{const e=await this.fs.stat(t);return this._getFileInfo(t,e)}catch(t){if("ENOENT"!==t.code)throw t;return null}}_getFileInfo(t,e){const i=this._toPathSegments(t).slice(this.rootDirSegments.length);i.unshift("");const n=i[i.length-1];let s={path:t=i.join("/"),name:n,kind:""};return e.isFile()?(s.size=e.size||0,s.type=r(t),s.kind="file",s.lastModified=new Date(e.mtime).getTime()):s.kind="directory",s}_toPathSegments(t){return(t=this.normalizePath(t)).split("/")}_expandPath(t){const e="object"==typeof t?t.path:t+"",i=this._toPathSegments(e).filter((t=>!!t));return i.unshift(...this.rootDirSegments),i.join("/")}}function p(t){const e=t.split("/");return e.pop(),e.join("/")}function l(...t){let e=t.map((t=>t.split("/"))).reduce(((t,e)=>(t.push(...e),t)),[]);const i=e.shift();return e=e.filter((t=>!!t&&"."!==t)),e.unshift(i),e.join("/")}async function m(t,e){try{const i=await t.stat(e);if(i&&i.isDirectory())return!0}catch(t){}const i=p(e);return e!==i&&(await m(t,i),await t.mkdir(e,{recursive:!0}),!0)}async function h(t,e){try{if((await t.stat(e)).isDirectory()){for await(let i of f(t,e,!1))await h(t,i.path);await t.rmdir(e)}else await t.unlink(e)}catch(t){if("ENOENT"!==t.code)throw t}}async function*f(t,e,i){try{if((await t.stat(e)).isDirectory()){const n=await t.readdir(e);for(const s of n.sort()){const n=l(e,s);let o=await t.stat(n);yield{path:n,stat:o},i&&o.isDirectory()&&(yield*f(t,n,!0))}}}catch(t){if("ENOENT"!==t.code)throw t}}class u{static canApply(t){return(t?.isDirectory||t?.isFile)&&"string"==typeof t?.name}async*listDirectoryChildren(t){let e=t.createReader();for(;;){const t=await new Promise(((t,i)=>e.readEntries(t,i)));if(!t.length)break;yield*t}}isDirectoryHandle(t){return t?.isDirectory}isFileHandle(t){return t?.isFile}async getSubdirectoryHandle(t,e,i){return new Promise(((n,s)=>t.getDirectory(e,{create:i},n,s)))}async getFileHandle(t,e,i=!0){return new Promise(((n,s)=>t.getFile(e,{create:i},n,s)))}async removeDirectoryEntry(t,e){return new Promise(((t,i)=>e.remove(t,i)))}async getFile(t){return await new Promise(((e,i)=>t.file(e,i)))}async getFileWriteStream(t){throw new Error("Not implemented")}}class y{static canApply(t){return"file"===t?.kind||"directory"===t?.kind}async*listDirectoryChildren(t){yield*t.values()}isDirectoryHandle(t){return"directory"===t?.kind}isFileHandle(t){return"file"===t?.kind}async getSubdirectoryHandle(t,e,i){return await t.getDirectoryHandle(e,{create:i})}async getFileHandle(t,e,i=!0){return await t.getFileHandle(e,{create:i})}async removeDirectoryEntry(t,e){return await t.removeEntry(e.name,{recursive:!0})}async getFile(t){return await t.getFile()}async getFileWriteStream(t){return await t.createWritable()}}class w extends i{constructor(t){if(super(t),!this.rootHandle)throw new Error("Root directory handle is not defined");if(!this.adapter)throw new Error("Can not define a browser adapter for the specified root handle")}get rootHandle(){return this.options.rootHandle||this.options.rootHandler}get adapter(){if(!this._adapter){const t=this.rootHandle;let e=u.canApply(t)?new u:y.canApply(t)?new y:null;this._adapter=e}return this._adapter}async*list(t,{recursive:e=!1}={}){const i=this._getPathSegments(t),n=await this._getHandle(i);if(!n)return;const s=this;this.adapter.isDirectoryHandle(n)&&(yield*async function*t(e,i,n){for await(const o of s._listDirectoryContent(i))yield await s._getFileInfo([...e,o.name],o),n&&s.adapter.isDirectoryHandle(o)&&(yield*t([...e,o.name],o,n))}(i,n,e))}async stats(t){const e=this._getPathSegments(t),i=await this._getHandle(e);return i?await this._getFileInfo(e,i):null}async remove(t){const e=async(t,i)=>{let n=!0;if(this.adapter.isDirectoryHandle(i)){const t=[];for await(let e of this.adapter.listDirectoryChildren(i))t.push(e);for(let s of t)n=n&&await e(i,s)}return t&&(n&=await this.adapter.removeDirectoryEntry(t,i)),n},i=this._getPathSegments(t),n=await this._getHandle(i);i.pop();const s=await this._getHandle(i);return e(s!==n?s:null,n)}async write(t,e){const i=this._getPathSegments(t),n=i.pop(),s=await this._getDirectoryHandle(i,!0),o=await this.adapter.getFileHandle(s,n,!0),a=await this.adapter.getFileWriteStream(o);try{"function"==typeof e&&(e=e());for await(let t of e)await a.write(t.buffer?t.buffer:t)}finally{await a.close()}}async*read(t){const e=this._getPathSegments(t),i=e.pop(),n=await this._getDirectoryHandle(e,!1),s=await this.adapter.getFileHandle(n,i,!1);if(!s)return;const o=(await this.adapter.getFile(s)).stream().getReader();try{let t;for(;(t=await o.read())&&!t.done;)yield await t.value}finally{await o.cancel&&o.cancel()}}async _getFileInfo(t,e){const i=(t=[...t])[t.length-1];t.unshift("");const n=t.join("/"),s={kind:"",path:n,name:i};if(this.adapter.isDirectoryHandle(e))s.kind="directory";else{s.kind="file";const t=await this.adapter.getFile(e);s.size=t.size,s.type=r(n),s.lastModified=t.lastModified}return s}_getPathSegments(t){return("object"==typeof t?t.path:t+"").split("/").filter((t=>!!t))}async _getHandle(t){const e=[...t],i=e.pop(),n=!1;try{const t=await this._getDirectoryHandle(e,n);try{return i?await this.adapter.getSubdirectoryHandle(t,i,n):t}catch(e){return await this.adapter.getFileHandle(t,i,n)}}catch(t){return}}async _getDirectoryHandle(t,e=!0){t=[...t];let i=this.rootHandle;for(let n of t)if(i=await this.adapter.getSubdirectoryHandle(i,n,e),!i)break;return i}async*_listDirectoryContent(t){let e=[];for await(const i of this.adapter.listDirectoryChildren(t))e.push(i);e=e.sort(((t,e)=>e.name>t.name?1:-1)),yield*e}}function g({filesApi:t,log:e=console.log,wrapper:i={}}){return["list","stats","remove","write","read","copy","move"].reduce(((i,n)=>{const s=t[n].bind(t);return i[n]=(...i)=>{let o={method:n,stage:"enter",args:i};try{return e(o),o.result=s.call(t,...i)}catch(t){o.error=t}finally{o.stage="exit",e(o)}},i}),i)}async function x({handlerKey:t="root-dir",readwrite:e=!0,index:i={},get:n=(async t=>i[t]),set:s=(async(t,e)=>i[t]=e),del:o=(async t=>delete i[t])}={}){let a=await n(t);if(a||(a=await window.showDirectoryPicker(),await s(t,a)),!await _(a,e))throw new Error("Access was not granted");if(!await v(a))throw await o(t),new Error("Can not access to the folder. Please try again.");return new w({rootHandler:a})}async function v(t){let e=!1;try{if("file"===t.kind)await t.getFile();else for await(let e of t.values())break;e=!0}catch(i){console.log(i,t),e=!1}return e}async function _(t,e){const i={};e&&(i.mode="readwrite");let n=!1;return"granted"===await t.queryPermission(i)&&(n=!0),n||"granted"!==await t.requestPermission(i)||(n=!0),n}export{w as BrowserFilesApi,i as FilesApi,c as MemFilesApi,d as NodeFilesApi,g as addFilesApiLogger,o as extensionToMimeType,r as getMimeType,v as isHandlerAccessible,a as mimeTypeToExtensions,n as mimeTypes,s as mimeTypesDescriptions,t as normalizePath,x as openBrowserFilesApi,_ as verifyPermission};
package/index.js DELETED
@@ -1 +0,0 @@
1
- export * from './src/index.js';
@@ -1,335 +0,0 @@
1
- import FilesApi from "./FilesApi.js";
2
- import getMimeType from "./getMimeType.js";
3
-
4
- /**
5
- * Stateless adapter for the "File and Directory Entries API".
6
- * See https://developer.mozilla.org/en-US/docs/Web/API/File_and_Directory_Entries_API
7
- *
8
- * ## File and Directory Entries API
9
- * The File and Directory Entries API simulates a local file system
10
- * this web apps can navigate within and access files in. You can
11
- * develop apps which read, write, and create files and/or directories
12
- * in a virtual, sandboxed file system.
13
- */
14
- class AdapterForFilesAndDirectoryEntriesApi {
15
- static canApply(handle) {
16
- return ((handle?.isDirectory || handle?.isFile) &&
17
- (typeof handle?.name === "string"));
18
- }
19
-
20
- async *listDirectoryChildren(handle) {
21
- let dirReader = handle.createReader();
22
- while (true) {
23
- const list = await new Promise((resolve, reject) =>
24
- dirReader.readEntries(resolve, reject)
25
- );
26
- if (!list.length) break;
27
- yield* list;
28
- }
29
- }
30
-
31
- isDirectoryHandle(handle) {
32
- return handle?.isDirectory;
33
- }
34
- isFileHandle(handle) {
35
- return handle?.isFile;
36
- }
37
-
38
- async getSubdirectoryHandle(dirHandle, directoryName, create) {
39
- return new Promise((resolve, reject) =>
40
- dirHandle.getDirectory(
41
- directoryName,
42
- { create },
43
- resolve,
44
- reject,
45
- )
46
- );
47
- }
48
-
49
- async getFileHandle(dirHandle, fileName, create = true) {
50
- return new Promise((resolve, reject) =>
51
- dirHandle.getFile(
52
- fileName,
53
- { create },
54
- resolve,
55
- reject,
56
- )
57
- );
58
- }
59
-
60
- async removeDirectoryEntry(dirHandle, handle) {
61
- return new Promise((resolve, reject) => handle.remove(resolve, reject));
62
- }
63
-
64
- async getFile(handle) {
65
- const file = await new Promise((resolve, reject) =>
66
- handle.file(resolve, reject)
67
- );
68
- return file;
69
- }
70
-
71
- async getFileWriteStream(handle) {
72
- throw new Error("Not implemented");
73
- }
74
- }
75
-
76
- /**
77
- * Stateless adapter for the "File System API" and "File System Access API".
78
- * See:
79
- * - https://developer.mozilla.org/en-US/docs/Web/API/File_System_API
80
- * - https://wicg.github.io/file-system-access/
81
- */
82
- class AdapterForFileSystemApi {
83
- static canApply(handle) {
84
- return (handle?.kind === "file" || handle?.kind === "directory");
85
- }
86
-
87
- async *listDirectoryChildren(handle) {
88
- yield* handle.values();
89
- }
90
-
91
- isDirectoryHandle(handle) {
92
- return handle?.kind === "directory";
93
- }
94
- isFileHandle(handle) {
95
- return handle?.kind === "file";
96
- }
97
-
98
- async getSubdirectoryHandle(dirHandle, directoryName, create) {
99
- return await dirHandle.getDirectoryHandle(directoryName, { create });
100
- }
101
-
102
- async getFileHandle(dirHandle, fileName, create = true) {
103
- return await dirHandle.getFileHandle(fileName, { create });
104
- }
105
-
106
- async removeDirectoryEntry(dirHandle, handle) {
107
- return await dirHandle.removeEntry(handle.name, { recursive: true });
108
- }
109
-
110
- async getFile(handle) {
111
- return await handle.getFile();
112
- }
113
-
114
- async getFileWriteStream(handle) {
115
- return await handle.createWritable(); // Write the contents of the file to the stream.
116
- }
117
- }
118
-
119
- export default class BrowserFilesApi extends FilesApi {
120
- constructor(options) {
121
- super(options);
122
- if (!this.rootHandle) {
123
- throw new Error("Root directory handle is not defined");
124
- }
125
- if (!this.adapter) {
126
- throw new Error(
127
- "Can not define a browser adapter for the specified root handle",
128
- );
129
- }
130
- }
131
-
132
- get rootHandle() {
133
- return this.options.rootHandle || this.options.rootHandler;
134
- }
135
-
136
- get adapter() {
137
- if (!this._adapter) {
138
- const handle = this.rootHandle;
139
- let adapter = AdapterForFilesAndDirectoryEntriesApi.canApply(handle)
140
- ? new AdapterForFilesAndDirectoryEntriesApi()
141
- : AdapterForFileSystemApi.canApply(handle)
142
- ? new AdapterForFileSystemApi()
143
- : null;
144
- this._adapter = adapter;
145
- }
146
- return this._adapter;
147
- }
148
-
149
- async *list(file, { recursive = false } = {}) {
150
- const segments = this._getPathSegments(file);
151
- const handle = await this._getHandle(segments);
152
- if (!handle) return;
153
- const that = this;
154
- if (this.adapter.isDirectoryHandle(handle)) {
155
- // yield await this._getFileInfo(segments, handle);
156
- yield* listChildren(segments, handle, recursive);
157
- }
158
-
159
- async function* listChildren(segments, dirHandle, recursive) {
160
- for await (const handle of that._listDirectoryContent(dirHandle)) {
161
- yield await that._getFileInfo([...segments, handle.name], handle);
162
- if (recursive && that.adapter.isDirectoryHandle(handle)) {
163
- yield* listChildren(
164
- [...segments, handle.name],
165
- handle,
166
- recursive,
167
- );
168
- }
169
- }
170
- }
171
- }
172
-
173
- async stats(file) {
174
- const segments = this._getPathSegments(file);
175
- const handle = await this._getHandle(segments);
176
- return handle ? await this._getFileInfo(segments, handle) : null;
177
- }
178
-
179
- async remove(file) {
180
- const doRemove = async (dirHandle, handle) => {
181
- let result = true;
182
- if (this.adapter.isDirectoryHandle(handle)) {
183
- const children = [];
184
- for await (let child of this.adapter.listDirectoryChildren(handle)) {
185
- children.push(child);
186
- }
187
- for (let child of children) {
188
- result = result && await doRemove(handle, child);
189
- }
190
- }
191
- if (dirHandle) {
192
- result &= await this.adapter.removeDirectoryEntry(dirHandle, handle);
193
- }
194
- return result;
195
- };
196
-
197
- const segments = this._getPathSegments(file);
198
- const handle = await this._getHandle(segments);
199
- segments.pop();
200
- const dirHandle = await this._getHandle(segments);
201
- return doRemove(dirHandle !== handle ? dirHandle : null, handle);
202
- }
203
-
204
- async write(file, content) {
205
- const segments = this._getPathSegments(file);
206
- const fileName = segments.pop();
207
- const dirHandle = await this._getDirectoryHandle(segments, true);
208
- const fileHandle = await this.adapter.getFileHandle(
209
- dirHandle,
210
- fileName,
211
- true,
212
- );
213
- const writable = await this.adapter.getFileWriteStream(fileHandle);
214
- try {
215
- if (typeof content === "function") content = content();
216
- for await (let block of content) {
217
- await writable.write(block.buffer ? block.buffer : block); // Close the file and write the contents to disk.
218
- }
219
- } finally {
220
- await writable.close();
221
- }
222
- }
223
-
224
- async *read(file /* { start = 0, bufferSize = 1024 * 8 } = {} */) {
225
- const segments = this._getPathSegments(file);
226
-
227
- const fileName = segments.pop();
228
- const dirHandle = await this._getDirectoryHandle(segments, false);
229
- const fileHandle = await this.adapter.getFileHandle(
230
- dirHandle,
231
- fileName,
232
- false,
233
- );
234
- if (!fileHandle) return;
235
- const fileData = await this.adapter.getFile(fileHandle);
236
- const stream = fileData.stream();
237
- const reader = stream.getReader();
238
- try {
239
- let chunk;
240
- while (chunk = await reader.read()) {
241
- if (chunk.done) break;
242
- yield await chunk.value;
243
- }
244
- } finally {
245
- await reader.cancel && reader.cancel();
246
- // stream.cancel && stream.cancel();
247
- }
248
- }
249
-
250
- // TODO:
251
- // async copy(fromPath, toPath, options = {}) { ... }
252
-
253
- // TODO:
254
- // async move(fromPath, toPath, options = {}) { ... }
255
-
256
- // ---------------------------------------------------------
257
- // Private methods
258
-
259
- async _getFileInfo(segments, handle) {
260
- segments = [...segments];
261
- const name = segments[segments.length - 1];
262
- segments.unshift("");
263
- const path = segments.join("/");
264
- const info = {
265
- kind: "",
266
- path,
267
- name,
268
- };
269
- if (this.adapter.isDirectoryHandle(handle)) {
270
- info.kind = "directory";
271
- } else {
272
- info.kind = "file";
273
-
274
- const file = await this.adapter.getFile(handle);
275
- info.size = file.size;
276
- info.type = getMimeType(path);
277
- info.lastModified = file.lastModified;
278
- }
279
- return info;
280
- }
281
-
282
- _getPathSegments(file) {
283
- let filePath = typeof file === "object" ? file.path : file + "";
284
- // filePath = this.normalizePath(filePath);
285
- const segments = filePath.split("/").filter((s) => !!s);
286
- return segments;
287
- }
288
-
289
- async _getHandle(segments) {
290
- const parentDirSegments = [...segments];
291
- const name = parentDirSegments.pop();
292
- const create = false;
293
- try {
294
- const dirHandle = await this._getDirectoryHandle(
295
- parentDirSegments,
296
- create,
297
- );
298
- try {
299
- if (!name) return dirHandle;
300
- return await this.adapter.getSubdirectoryHandle(
301
- dirHandle,
302
- name,
303
- create,
304
- );
305
- } catch (error) {
306
- return await this.adapter.getFileHandle(dirHandle, name, create);
307
- }
308
- } catch (error) {
309
- return undefined;
310
- }
311
- }
312
-
313
- async _getDirectoryHandle(segments, create = true) {
314
- segments = [...segments];
315
- let dirHandle = this.rootHandle;
316
- for (let directoryName of segments) {
317
- dirHandle = await this.adapter.getSubdirectoryHandle(
318
- dirHandle,
319
- directoryName,
320
- create,
321
- );
322
- if (!dirHandle) break;
323
- }
324
- return dirHandle;
325
- }
326
-
327
- async *_listDirectoryContent(handle) {
328
- let entries = [];
329
- for await (const entry of this.adapter.listDirectoryChildren(handle)) {
330
- entries.push(entry);
331
- }
332
- entries = entries.sort((a, b) => b.name > a.name ? 1 : -1);
333
- yield* entries;
334
- }
335
- }
package/src/FilesApi.js DELETED
@@ -1,133 +0,0 @@
1
- import normalizePath from "./normalizePath.js";
2
- import notImplemented from "./notImplemented.js";
3
-
4
- /*
5
- * FileInfo
6
- * - `kind` - (`file`|`directory`) kind of the returned entity
7
- * - `name` - the local name of this file entry (the last segment of the path)
8
- * - `path` - path to the file from the root of the "file system"
9
- * - `type` - an optional mime type of the file content; it is not defined for directories
10
- * - `size` - size of the file (only for files)
11
- * - `lastModified` - modification time as a long integer
12
- */
13
-
14
- /**
15
- * This is a common interface providing access to methods dealing with files.
16
- */
17
- export default class FilesApi {
18
- constructor(options) {
19
- this.options = options || {};
20
- }
21
-
22
- /**
23
- * Returns an async generator providing information about files (FileInfo[]).
24
- * Paths corresponding to directories has the "/" trailing symbol.
25
- * @param {Object|String} file path to the folder or an object returned by the `list` or `info` methods
26
- * @param {Object} options optional parameters
27
- * @param {Boolean} options.recursive this flag defines if the returned generator
28
- * should give access to all child directories and files or just direct children
29
- * @return {AsyncGenerator<FileInfo>} generator returning information about
30
- * individual file entries
31
- */
32
- async *list(file, options = {}) {
33
- yield notImplemented(file, options);
34
- }
35
-
36
- /**
37
- * Returns information about an individual file.
38
- * @param {Object|String} file path to the file or an object returned by
39
- * the `list` or `info` methods
40
- * @return {FileInfo} information about the file corresponding to the specified
41
- * path or null if there is no such a file
42
- */
43
- async stats(file) {
44
- return notImplemented(file);
45
- }
46
-
47
- /**
48
- * Removes file or folder corresponding to the specified path.
49
- * All children of this entry will be removed as well.
50
- * @param {Object|String} file path to the file to remove or an object
51
- * returned by the `list` or `info` methods
52
- * @return {Boolean} return true if the file was removed
53
- */
54
- async remove(file) {
55
- return notImplemented(file);
56
- }
57
-
58
- /**
59
- * Creates and returns a write stream for the file with the specified path.
60
- * @param {Object|String} file path to the file or an object returned by
61
- * the `list` or `info` methods
62
- * @param {AsyncGenerator|AsyncIterator} content async generator function providing the binary
63
- * file content to store
64
- * @return {any} result of the action execution
65
- */
66
- async write(file, content) {
67
- return notImplemented(file, content);
68
- }
69
-
70
- /**
71
- * Creates an returns an AsyncIterator returning byte blocks with the file content.
72
- * @param {Object|String} file path to the file or an object returned by
73
- * the `list` or `info` methods
74
- * @param {object} options read parameters
75
- * @param {number} options.start starting read position; default value is 0
76
- * @param {number} options.bufferSize the optional size of returned chunks buffers
77
- */
78
- async *read(file, options) {
79
- yield notImplemented(file, options);
80
- }
81
-
82
- /**
83
- * Copies a file from one path to another.
84
- * @param {String} fromPath path to the source file
85
- * @param {String} toPath path to the target file
86
- * @param {Object} options additional options
87
- * @param {Store} options.recursive if this flag is true then subfolders are also copied
88
- * @param {Store} options.target optional target store where data should be copied
89
- * @return {Boolean} if the file was successfully copied
90
- */
91
- async copy(source, target, options = {}) {
92
- const doCopy = async (sourcePath, targetPath, sourceFile) => {
93
- const suffix = sourceFile.path.substring(sourcePath.length);
94
- targetPath = `${targetPath}${suffix}`;
95
- const content = this.read(sourceFile);
96
- return await this.write(targetPath, content);
97
- };
98
- const recursive = options.recursive === undefined || !!options.recursive;
99
- const sourceFile = await this.stats(source);
100
- if (sourceFile.kind === "directory") {
101
- for await (const file of this.list(source, { ...options, recursive })) {
102
- if (file.kind === "directory") continue;
103
- await doCopy(source, target, file);
104
- }
105
- } else {
106
- await doCopy(source, target, sourceFile);
107
- }
108
- return true;
109
- }
110
-
111
- /**
112
- * Moves files from the initial position to the target path.
113
- * The default implementation creates a new file copy in the new location
114
- * and removes the old file.
115
- *
116
- * @param {String} fromPath path to the source file
117
- * @param {String} toPath path to the target file
118
- * @param {Object} options additional options
119
- * @param {Store} options.target optional target store where data should be moved
120
- * @return {Boolean} if the file was successfully moved
121
- */
122
- async move(fromPath, toPath, options = {}) {
123
- if (!await this.copy(fromPath, toPath, options)) return false;
124
- await this.remove(fromPath);
125
- return true;
126
- }
127
-
128
- normalizePath(file) {
129
- let filePath = typeof file === "object" ? file.path : file + "";
130
- return normalizePath(filePath);
131
- }
132
- }
133
-
@@ -1,129 +0,0 @@
1
- import FilesApi from "./FilesApi.js";
2
- import getMimeType from "./getMimeType.js";
3
-
4
- export default class MemFilesApi extends FilesApi {
5
- constructor(options) {
6
- super(options);
7
- this.index = {
8
- "/" : {
9
- "kind": "directory",
10
- "path": "/",
11
- "name": ""
12
- }
13
- };
14
- }
15
-
16
- async *list(file, { recursive = false } = {}) {
17
- await this._init();
18
- const filePath = this.normalizePath(file);
19
- const paths = this._getPaths();
20
- for (const path of paths) {
21
- if (path.indexOf(filePath) !== 0 || path === filePath) continue;
22
- const suffix = path.substring(filePath.length + 1);
23
- const segments = suffix.split("/");
24
- if (recursive || segments.length === 1) {
25
- yield this._getFileInfo(path);
26
- }
27
- }
28
- }
29
-
30
- async stats(file) {
31
- await this._init();
32
- const filePath = this.normalizePath(file);
33
- return this._getFileInfo(filePath);
34
- }
35
-
36
- async remove(file) {
37
- await this._init();
38
- const fileInfo = await this.stats(file);
39
- if (!fileInfo) return false;
40
- for await (const { path } of this.list(fileInfo, { recursive: true })) {
41
- if (path !== "/") delete this.index[path];
42
- }
43
- delete this.index[fileInfo.path];
44
- }
45
-
46
- async write(file, content) {
47
- await this._init();
48
- await this._doWrite(file, content);
49
- }
50
-
51
- async *read(file /* { start = 0, bufferSize = 1024 * 8 } = {} */) {
52
- await this._init();
53
- const filePath = this.normalizePath(file);
54
- const fileInfo = this.index[filePath];
55
- if (!fileInfo || fileInfo.kind !== "file") return ; // throw new Error("Not a file");
56
- const content = fileInfo.content;
57
- yield* content;
58
- }
59
-
60
- // TODO:
61
- // async copy(fromPath, toPath, options = {}) { ... }
62
-
63
- // TODO:
64
- // async move(fromPath, toPath, options = {}) { ... }
65
-
66
- async _init() {
67
- return this._initPromise = this._initPromise ||
68
- Promise.resolve().then(() => this._addEntries(this.options.files));
69
- }
70
-
71
- async _doWrite(file, content) {
72
- const filePath = this.normalizePath(file);
73
- const segments = filePath.split("/").filter((s) => !!s);
74
- const pathSegments = [""];
75
- let info;
76
- for (let i = 0; i < segments.length; i++) {
77
- const name = segments[i];
78
- pathSegments.push(name);
79
- const path = pathSegments.join("/");
80
- info = this.index[path] = this.index[path] || {
81
- path,
82
- name,
83
- kind: "directory",
84
- };
85
- }
86
- info.kind = "file";
87
- info.content = [];
88
- info.type = getMimeType(info.path);
89
- info.size = 0;
90
- info.lastModified = Date.now();
91
- if (typeof content === "function") content = content();
92
- for await (let chunk of content) {
93
- chunk = new Uint8Array(chunk);
94
- info.content.push(chunk);
95
- info.size += chunk.length;
96
- }
97
- }
98
-
99
- async _addEntries(index = {}) {
100
- for (let [path, content] of Object.entries(index)) {
101
- if (typeof content === "string") {
102
- content = [new TextEncoder().encode(content)];
103
- } else if (content instanceof Uint8Array) {
104
- content = [content];
105
- }
106
- await this._doWrite(path, content);
107
- }
108
- }
109
-
110
- _getPaths() {
111
- return this._getIndexPaths(this.index);
112
- }
113
-
114
- _getIndexPaths(index) {
115
- return Object.keys(index).sort(compare);
116
- function compare(a, b) {
117
- return a > b ? 1 : a < b ? -1 : 0;
118
- }
119
- }
120
-
121
- _getFileInfo(path) {
122
- const fileInfo = this.index[path];
123
- if (!fileInfo) return null;
124
- const info = { ...fileInfo };
125
- delete info.content;
126
- return info;
127
- }
128
-
129
- }