@jupyterlite/contents 0.1.0-beta.8 → 0.1.0-beta.9

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.
package/lib/contents.js CHANGED
@@ -1,8 +1,7 @@
1
1
  import { PageConfig, URLExt } from '@jupyterlab/coreutils';
2
2
  import { PathExt } from '@jupyterlab/coreutils';
3
- import { MIME } from './tokens';
3
+ import { MIME, FILE } from './tokens';
4
4
  import { PromiseDelegate } from '@lumino/coreutils';
5
- import mime from 'mime';
6
5
  /**
7
6
  * The name of the local storage.
8
7
  */
@@ -166,39 +165,49 @@ export class Contents {
166
165
  };
167
166
  break;
168
167
  }
169
- case 'file': {
170
- const ext = (_c = options === null || options === void 0 ? void 0 : options.ext) !== null && _c !== void 0 ? _c : '.txt';
171
- const counter = await this._incrementCounter('file');
172
- name = name || `untitled${counter || ''}${ext}`;
168
+ case 'notebook': {
169
+ const counter = await this._incrementCounter('notebook');
170
+ name = name || `Untitled${counter || ''}.ipynb`;
173
171
  file = {
174
172
  name,
175
173
  path: `${dirname}${name}`,
176
174
  last_modified: created,
177
175
  created,
178
- format: 'text',
179
- // TODO: handle mimetypes
180
- mimetype: MIME.PLAIN_TEXT,
181
- content: '',
182
- size: 0,
176
+ format: 'json',
177
+ mimetype: MIME.JSON,
178
+ content: Private.EMPTY_NB,
179
+ size: JSON.stringify(Private.EMPTY_NB).length,
183
180
  writable: true,
184
- type: 'file',
181
+ type: 'notebook',
185
182
  };
186
183
  break;
187
184
  }
188
185
  default: {
189
- const counter = await this._incrementCounter('notebook');
190
- name = name || `Untitled${counter || ''}.ipynb`;
186
+ const ext = (_c = options === null || options === void 0 ? void 0 : options.ext) !== null && _c !== void 0 ? _c : '.txt';
187
+ const counter = await this._incrementCounter('file');
188
+ const mimetype = FILE.getType(ext) || MIME.OCTET_STREAM;
189
+ let format;
190
+ if (FILE.hasFormat(ext, 'text') || mimetype.indexOf('text') !== -1) {
191
+ format = 'text';
192
+ }
193
+ else if (ext.indexOf('json') !== -1 || ext.indexOf('ipynb') !== -1) {
194
+ format = 'json';
195
+ }
196
+ else {
197
+ format = 'base64';
198
+ }
199
+ name = name || `untitled${counter || ''}${ext}`;
191
200
  file = {
192
201
  name,
193
202
  path: `${dirname}${name}`,
194
203
  last_modified: created,
195
204
  created,
196
- format: 'json',
197
- mimetype: MIME.JSON,
198
- content: Private.EMPTY_NB,
199
- size: JSON.stringify(Private.EMPTY_NB).length,
205
+ format,
206
+ mimetype,
207
+ content: '',
208
+ size: 0,
200
209
  writable: true,
201
- type: 'notebook',
210
+ type: 'file',
202
211
  };
203
212
  break;
204
213
  }
@@ -350,7 +359,12 @@ export class Contents {
350
359
  async save(path, options = {}) {
351
360
  var _a;
352
361
  path = decodeURIComponent(path);
353
- let item = (await this.get(path)) || (await this.newUntitled({ path }));
362
+ // process the file if coming from an upload
363
+ const ext = PathExt.extname((_a = options.name) !== null && _a !== void 0 ? _a : '');
364
+ let item = await this.get(path);
365
+ if (!item) {
366
+ item = await this.newUntitled({ path, ext, type: 'file' });
367
+ }
354
368
  if (!item) {
355
369
  return null;
356
370
  }
@@ -361,9 +375,6 @@ export class Contents {
361
375
  ...options,
362
376
  last_modified: modified,
363
377
  };
364
- // process the file if coming from an upload
365
- const ext = PathExt.extname((_a = options.name) !== null && _a !== void 0 ? _a : '');
366
- const mimetype = mime.getType(ext) || MIME.OCTET_STREAM;
367
378
  if (options.content && options.format === 'base64') {
368
379
  if (ext === '.ipynb') {
369
380
  item = {
@@ -373,7 +384,15 @@ export class Contents {
373
384
  type: 'notebook',
374
385
  };
375
386
  }
376
- else if (MIME.KNOWN_TEXT_TYPES.has(mimetype)) {
387
+ else if (FILE.hasFormat(ext, 'json')) {
388
+ item = {
389
+ ...item,
390
+ content: JSON.parse(this.unescapeContent(options.content)),
391
+ format: 'json',
392
+ type: 'file',
393
+ };
394
+ }
395
+ else if (FILE.hasFormat(ext, 'text')) {
377
396
  item = {
378
397
  ...item,
379
398
  content: this.unescapeContent(options.content),
@@ -558,7 +577,9 @@ export class Contents {
558
577
  return null;
559
578
  }
560
579
  const mimetype = model.mimetype || response.headers.get('Content-Type');
580
+ const ext = PathExt.extname(name);
561
581
  if (model.type === 'notebook' ||
582
+ FILE.hasFormat(ext, 'json') ||
562
583
  (mimetype === null || mimetype === void 0 ? void 0 : mimetype.indexOf('json')) !== -1 ||
563
584
  path.match(/\.(ipynb|[^/]*json[^/]*)$/)) {
564
585
  model = {
@@ -568,8 +589,7 @@ export class Contents {
568
589
  mimetype: model.mimetype || MIME.JSON,
569
590
  };
570
591
  }
571
- else if (mimetype.indexOf('text') !== -1 ||
572
- MIME.KNOWN_TEXT_TYPES.has(mimetype)) {
592
+ else if (FILE.hasFormat(ext, 'text') || mimetype.indexOf('text') !== -1) {
573
593
  model = {
574
594
  ...model,
575
595
  content: await response.text(),
@@ -0,0 +1,169 @@
1
+ export declare const DIR_MODE = 16895;
2
+ export declare const FILE_MODE = 33206;
3
+ export declare const SEEK_CUR = 1;
4
+ export declare const SEEK_END = 2;
5
+ export declare const DRIVE_SEPARATOR = ":";
6
+ export interface IStats {
7
+ dev: number;
8
+ ino: number;
9
+ mode: number;
10
+ nlink: number;
11
+ uid: number;
12
+ gid: number;
13
+ rdev: number;
14
+ size: number;
15
+ blksize: number;
16
+ blocks: number;
17
+ atime: Date;
18
+ mtime: Date;
19
+ ctime: Date;
20
+ timestamp?: number;
21
+ }
22
+ export interface IEmscriptenFSNode {
23
+ name: string;
24
+ mode: number;
25
+ parent: IEmscriptenFSNode;
26
+ mount: {
27
+ opts: {
28
+ root: string;
29
+ };
30
+ };
31
+ stream_ops: IEmscriptenStreamOps;
32
+ node_ops: IEmscriptenNodeOps;
33
+ timestamp: number;
34
+ }
35
+ export interface IEmscriptenStream {
36
+ node: IEmscriptenFSNode;
37
+ nfd: any;
38
+ flags: string;
39
+ position: number;
40
+ file?: DriveFS.IFile;
41
+ }
42
+ export interface IEmscriptenNodeOps {
43
+ getattr(node: IEmscriptenFSNode): IStats;
44
+ setattr(node: IEmscriptenFSNode, attr: IStats): void;
45
+ lookup(parent: IEmscriptenFSNode, name: string): IEmscriptenFSNode;
46
+ mknod(parent: IEmscriptenFSNode, name: string, mode: number, dev: any): IEmscriptenFSNode;
47
+ rename(oldNode: IEmscriptenFSNode, newDir: IEmscriptenFSNode, newName: string): void;
48
+ unlink(parent: IEmscriptenFSNode, name: string): void;
49
+ rmdir(parent: IEmscriptenFSNode, name: string): void;
50
+ readdir(node: IEmscriptenFSNode): string[];
51
+ symlink(parent: IEmscriptenFSNode, newName: string, oldPath: string): void;
52
+ readlink(node: IEmscriptenFSNode): string;
53
+ }
54
+ export interface IEmscriptenStreamOps {
55
+ open(stream: IEmscriptenStream): void;
56
+ close(stream: IEmscriptenStream): void;
57
+ read(stream: IEmscriptenStream, buffer: Uint8Array, offset: number, length: number, position: number): number;
58
+ write(stream: IEmscriptenStream, buffer: Uint8Array, offset: number, length: number, position: number): number;
59
+ llseek(stream: IEmscriptenStream, offset: number, whence: number): number;
60
+ }
61
+ export declare class DriveFSEmscriptenStreamOps implements IEmscriptenStreamOps {
62
+ private fs;
63
+ constructor(fs: DriveFS);
64
+ open(stream: IEmscriptenStream): void;
65
+ close(stream: IEmscriptenStream): void;
66
+ read(stream: IEmscriptenStream, buffer: Uint8Array, offset: number, length: number, position: number): number;
67
+ write(stream: IEmscriptenStream, buffer: Uint8Array, offset: number, length: number, position: number): number;
68
+ llseek(stream: IEmscriptenStream, offset: number, whence: number): number;
69
+ }
70
+ export declare class DriveFSEmscriptenNodeOps implements IEmscriptenNodeOps {
71
+ private fs;
72
+ constructor(fs: DriveFS);
73
+ getattr(node: IEmscriptenFSNode): IStats;
74
+ setattr(node: IEmscriptenFSNode, attr: IStats): void;
75
+ lookup(parent: IEmscriptenFSNode, name: string): IEmscriptenFSNode;
76
+ mknod(parent: IEmscriptenFSNode, name: string, mode: number, dev: any): IEmscriptenFSNode;
77
+ rename(oldNode: IEmscriptenFSNode, newDir: IEmscriptenFSNode, newName: string): void;
78
+ unlink(parent: IEmscriptenFSNode, name: string): void;
79
+ rmdir(parent: IEmscriptenFSNode, name: string): void;
80
+ readdir(node: IEmscriptenFSNode): string[];
81
+ symlink(parent: IEmscriptenFSNode, newName: string, oldPath: string): void;
82
+ readlink(node: IEmscriptenFSNode): string;
83
+ }
84
+ /**
85
+ * Wrap ServiceWorker requests for an Emscripten-compatible synchronous API.
86
+ */
87
+ export declare class ContentsAPI {
88
+ constructor(baseUrl: string, driveName: string, mountpoint: string, FS: any, ERRNO_CODES: any);
89
+ request(method: 'GET' | 'POST' | 'PUT' | 'DELETE', path: string, data?: string | null): any;
90
+ lookup(path: string): DriveFS.ILookup;
91
+ getmode(path: string): number;
92
+ mknod(path: string, mode: number): any;
93
+ rename(oldPath: string, newPath: string): void;
94
+ readdir(path: string): string[];
95
+ rmdir(path: string): void;
96
+ get(path: string): DriveFS.IFile;
97
+ put(path: string, value: DriveFS.IFile): any;
98
+ getattr(path: string): IStats;
99
+ /**
100
+ * Normalize a Path by making it compliant for the content manager
101
+ *
102
+ * @param path: the path relatively to the Emscripten drive
103
+ */
104
+ normalizePath(path: string): string;
105
+ /**
106
+ * Get the api/drive endpoint
107
+ */
108
+ get endpoint(): string;
109
+ private _baseUrl;
110
+ private _driveName;
111
+ private _mountpoint;
112
+ private FS;
113
+ private ERRNO_CODES;
114
+ }
115
+ export declare class DriveFS {
116
+ FS: any;
117
+ API: ContentsAPI;
118
+ PATH: DriveFS.IPath;
119
+ ERRNO_CODES: any;
120
+ driveName: string;
121
+ constructor(options: DriveFS.IOptions);
122
+ node_ops: IEmscriptenNodeOps;
123
+ stream_ops: IEmscriptenStreamOps;
124
+ mount(mount: any): IEmscriptenFSNode;
125
+ createNode(parent: IEmscriptenFSNode | null, name: string, mode: number, dev?: any): IEmscriptenFSNode;
126
+ getMode(path: string): number;
127
+ realPath(node: IEmscriptenFSNode): string;
128
+ }
129
+ /**
130
+ * A namespace for DriveFS configurations, etc.
131
+ */
132
+ export declare namespace DriveFS {
133
+ /**
134
+ * A file representation;
135
+ */
136
+ interface IFile {
137
+ data: Uint8Array;
138
+ format: 'json' | 'text' | 'base64';
139
+ }
140
+ /**
141
+ * The response to a lookup request;
142
+ */
143
+ interface ILookup {
144
+ ok: boolean;
145
+ mode: number;
146
+ }
147
+ /**
148
+ * The emscripten FS Path API;
149
+ */
150
+ interface IPath {
151
+ basename: (path: string) => string;
152
+ dirname: (path: string) => string;
153
+ join: (...parts: string[]) => string;
154
+ join2: (l: string, r: string) => string;
155
+ normalize: (path: string) => string;
156
+ splitPath: (filename: string) => string;
157
+ }
158
+ /**
159
+ * Initialization options for a drive;
160
+ */
161
+ interface IOptions {
162
+ FS: any;
163
+ PATH: IPath;
164
+ ERRNO_CODES: any;
165
+ baseUrl: string;
166
+ driveName: string;
167
+ mountpoint: string;
168
+ }
169
+ }
package/lib/drivefs.js ADDED
@@ -0,0 +1,327 @@
1
+ // Types and implementation inspired from https://github.com/jvilk/BrowserFS
2
+ // LICENSE: https://github.com/jvilk/BrowserFS/blob/8977a704ea469d05daf857e4818bef1f4f498326/LICENSE
3
+ // And from https://github.com/gzuidhof/starboard-notebook
4
+ // LICENSE: https://github.com/gzuidhof/starboard-notebook/blob/cd8d3fc30af4bd29cdd8f6b8c207df8138f5d5dd/LICENSE
5
+ export const DIR_MODE = 16895; // 040777
6
+ export const FILE_MODE = 33206; // 100666
7
+ export const SEEK_CUR = 1;
8
+ export const SEEK_END = 2;
9
+ export const DRIVE_SEPARATOR = ':';
10
+ const encoder = new TextEncoder();
11
+ const decoder = new TextDecoder('utf-8');
12
+ // Mapping flag -> do we need to overwrite the file upon closing it
13
+ const flagNeedsWrite = {
14
+ 0 /*O_RDONLY*/: false,
15
+ 1 /*O_WRONLY*/: true,
16
+ 2 /*O_RDWR*/: true,
17
+ 64 /*O_CREAT*/: true,
18
+ 65 /*O_WRONLY|O_CREAT*/: true,
19
+ 66 /*O_RDWR|O_CREAT*/: true,
20
+ 129 /*O_WRONLY|O_EXCL*/: true,
21
+ 193 /*O_WRONLY|O_CREAT|O_EXCL*/: true,
22
+ 514 /*O_RDWR|O_TRUNC*/: true,
23
+ 577 /*O_WRONLY|O_CREAT|O_TRUNC*/: true,
24
+ 578 /*O_CREAT|O_RDWR|O_TRUNC*/: true,
25
+ 705 /*O_WRONLY|O_CREAT|O_EXCL|O_TRUNC*/: true,
26
+ 706 /*O_RDWR|O_CREAT|O_EXCL|O_TRUNC*/: true,
27
+ 1024 /*O_APPEND*/: true,
28
+ 1025 /*O_WRONLY|O_APPEND*/: true,
29
+ 1026 /*O_RDWR|O_APPEND*/: true,
30
+ 1089 /*O_WRONLY|O_CREAT|O_APPEND*/: true,
31
+ 1090 /*O_RDWR|O_CREAT|O_APPEND*/: true,
32
+ 1153 /*O_WRONLY|O_EXCL|O_APPEND*/: true,
33
+ 1154 /*O_RDWR|O_EXCL|O_APPEND*/: true,
34
+ 1217 /*O_WRONLY|O_CREAT|O_EXCL|O_APPEND*/: true,
35
+ 1218 /*O_RDWR|O_CREAT|O_EXCL|O_APPEND*/: true,
36
+ 4096 /*O_RDONLY|O_DSYNC*/: true,
37
+ 4098 /*O_RDWR|O_DSYNC*/: true,
38
+ };
39
+ export class DriveFSEmscriptenStreamOps {
40
+ constructor(fs) {
41
+ this.fs = fs;
42
+ }
43
+ open(stream) {
44
+ const path = this.fs.realPath(stream.node);
45
+ if (this.fs.FS.isFile(stream.node.mode)) {
46
+ stream.file = this.fs.API.get(path);
47
+ }
48
+ }
49
+ close(stream) {
50
+ if (!this.fs.FS.isFile(stream.node.mode) || !stream.file) {
51
+ return;
52
+ }
53
+ const path = this.fs.realPath(stream.node);
54
+ const flags = stream.flags;
55
+ let parsedFlags = typeof flags === 'string' ? parseInt(flags, 10) : flags;
56
+ parsedFlags &= 0x1fff;
57
+ let needsWrite = true;
58
+ if (parsedFlags in flagNeedsWrite) {
59
+ needsWrite = flagNeedsWrite[parsedFlags];
60
+ }
61
+ if (needsWrite) {
62
+ this.fs.API.put(path, stream.file);
63
+ stream.file = undefined;
64
+ }
65
+ }
66
+ read(stream, buffer, offset, length, position) {
67
+ var _a;
68
+ if (length <= 0 || stream.file === undefined) {
69
+ return 0;
70
+ }
71
+ const size = Math.min(((_a = stream.file.data.length) !== null && _a !== void 0 ? _a : 0) - position, length);
72
+ try {
73
+ buffer.set(stream.file.data.subarray(position, position + size), offset);
74
+ }
75
+ catch (e) {
76
+ throw new this.fs.FS.ErrnoError(this.fs.ERRNO_CODES['EPERM']);
77
+ }
78
+ return size;
79
+ }
80
+ write(stream, buffer, offset, length, position) {
81
+ var _a, _b;
82
+ if (length <= 0 || stream.file === undefined) {
83
+ return 0;
84
+ }
85
+ stream.node.timestamp = Date.now();
86
+ try {
87
+ if (position + length > ((_b = (_a = stream.file) === null || _a === void 0 ? void 0 : _a.data.length) !== null && _b !== void 0 ? _b : 0)) {
88
+ const oldData = stream.file.data ? stream.file.data : new Uint8Array();
89
+ stream.file.data = new Uint8Array(position + length);
90
+ stream.file.data.set(oldData);
91
+ }
92
+ stream.file.data.set(buffer.subarray(offset, offset + length), position);
93
+ return length;
94
+ }
95
+ catch (e) {
96
+ throw new this.fs.FS.ErrnoError(this.fs.ERRNO_CODES['EPERM']);
97
+ }
98
+ }
99
+ llseek(stream, offset, whence) {
100
+ let position = offset;
101
+ if (whence === SEEK_CUR) {
102
+ position += stream.position;
103
+ }
104
+ else if (whence === SEEK_END) {
105
+ if (this.fs.FS.isFile(stream.node.mode)) {
106
+ if (stream.file !== undefined) {
107
+ position += stream.file.data.length;
108
+ }
109
+ else {
110
+ throw new this.fs.FS.ErrnoError(this.fs.ERRNO_CODES['EPERM']);
111
+ }
112
+ }
113
+ }
114
+ if (position < 0) {
115
+ throw new this.fs.FS.ErrnoError(this.fs.ERRNO_CODES['EINVAL']);
116
+ }
117
+ return position;
118
+ }
119
+ }
120
+ export class DriveFSEmscriptenNodeOps {
121
+ constructor(fs) {
122
+ this.fs = fs;
123
+ }
124
+ getattr(node) {
125
+ return this.fs.API.getattr(this.fs.realPath(node));
126
+ }
127
+ setattr(node, attr) {
128
+ // TODO
129
+ }
130
+ lookup(parent, name) {
131
+ const path = this.fs.PATH.join2(this.fs.realPath(parent), name);
132
+ const result = this.fs.API.lookup(path);
133
+ if (!result.ok) {
134
+ throw this.fs.FS.genericErrors[this.fs.ERRNO_CODES['ENOENT']];
135
+ }
136
+ return this.fs.createNode(parent, name, result.mode);
137
+ }
138
+ mknod(parent, name, mode, dev) {
139
+ const path = this.fs.PATH.join2(this.fs.realPath(parent), name);
140
+ this.fs.API.mknod(path, mode);
141
+ return this.fs.createNode(parent, name, mode, dev);
142
+ }
143
+ rename(oldNode, newDir, newName) {
144
+ this.fs.API.rename(oldNode.parent
145
+ ? this.fs.PATH.join2(this.fs.realPath(oldNode.parent), oldNode.name)
146
+ : oldNode.name, this.fs.PATH.join2(this.fs.realPath(newDir), newName));
147
+ // Updating the in-memory node
148
+ oldNode.name = newName;
149
+ oldNode.parent = newDir;
150
+ }
151
+ unlink(parent, name) {
152
+ this.fs.API.rmdir(this.fs.PATH.join2(this.fs.realPath(parent), name));
153
+ }
154
+ rmdir(parent, name) {
155
+ this.fs.API.rmdir(this.fs.PATH.join2(this.fs.realPath(parent), name));
156
+ }
157
+ readdir(node) {
158
+ return this.fs.API.readdir(this.fs.realPath(node));
159
+ }
160
+ symlink(parent, newName, oldPath) {
161
+ throw new this.fs.FS.ErrnoError(this.fs.ERRNO_CODES['EPERM']);
162
+ }
163
+ readlink(node) {
164
+ throw new this.fs.FS.ErrnoError(this.fs.ERRNO_CODES['EPERM']);
165
+ }
166
+ }
167
+ /**
168
+ * Wrap ServiceWorker requests for an Emscripten-compatible synchronous API.
169
+ */
170
+ export class ContentsAPI {
171
+ constructor(baseUrl, driveName, mountpoint, FS, ERRNO_CODES) {
172
+ this._baseUrl = baseUrl;
173
+ this._driveName = driveName;
174
+ this._mountpoint = mountpoint;
175
+ this.FS = FS;
176
+ this.ERRNO_CODES = ERRNO_CODES;
177
+ }
178
+ request(method, path, data = null) {
179
+ const xhr = new XMLHttpRequest();
180
+ xhr.open(method, encodeURI(`${this.endpoint}${path}`), false);
181
+ try {
182
+ if (data === null) {
183
+ xhr.send();
184
+ }
185
+ else {
186
+ xhr.send(data);
187
+ }
188
+ }
189
+ catch (e) {
190
+ console.error(e);
191
+ }
192
+ if (xhr.status >= 400) {
193
+ throw new this.FS.ErrnoError(this.ERRNO_CODES['EINVAL']);
194
+ }
195
+ return JSON.parse(xhr.responseText);
196
+ }
197
+ lookup(path) {
198
+ return this.request('GET', `${this.normalizePath(path)}?m=lookup`);
199
+ }
200
+ getmode(path) {
201
+ return Number.parseInt(this.request('GET', `${this.normalizePath(path)}?m=getmode`));
202
+ }
203
+ mknod(path, mode) {
204
+ return this.request('GET', `${this.normalizePath(path)}?m=mknod&args=${mode}`);
205
+ }
206
+ rename(oldPath, newPath) {
207
+ return this.request('GET', `${this.normalizePath(oldPath)}?m=rename&args=${this.normalizePath(newPath)}`);
208
+ }
209
+ readdir(path) {
210
+ const dirlist = this.request('GET', `${this.normalizePath(path)}?m=readdir`);
211
+ dirlist.push('.');
212
+ dirlist.push('..');
213
+ return dirlist;
214
+ }
215
+ rmdir(path) {
216
+ return this.request('GET', `${this.normalizePath(path)}?m=rmdir`);
217
+ }
218
+ get(path) {
219
+ const response = this.request('GET', `${this.normalizePath(path)}?m=get`);
220
+ const serializedContent = response.content;
221
+ const format = response.format;
222
+ switch (format) {
223
+ case 'json':
224
+ case 'text':
225
+ return {
226
+ data: encoder.encode(serializedContent),
227
+ format,
228
+ };
229
+ case 'base64': {
230
+ const binString = atob(serializedContent);
231
+ const len = binString.length;
232
+ const data = new Uint8Array(len);
233
+ for (let i = 0; i < len; i++) {
234
+ data[i] = binString.charCodeAt(i);
235
+ }
236
+ return {
237
+ data,
238
+ format,
239
+ };
240
+ }
241
+ default:
242
+ throw new this.FS.ErrnoError(this.ERRNO_CODES['ENOENT']);
243
+ }
244
+ }
245
+ put(path, value) {
246
+ switch (value.format) {
247
+ case 'json':
248
+ case 'text':
249
+ return this.request('PUT', `${this.normalizePath(path)}?m=put&args=${value.format}`, decoder.decode(value.data));
250
+ case 'base64': {
251
+ let binary = '';
252
+ for (let i = 0; i < value.data.byteLength; i++) {
253
+ binary += String.fromCharCode(value.data[i]);
254
+ }
255
+ return this.request('PUT', `${this.normalizePath(path)}?m=put&args=${value.format}`, btoa(binary));
256
+ }
257
+ }
258
+ }
259
+ getattr(path) {
260
+ const stats = this.request('GET', `${this.normalizePath(path)}?m=getattr`);
261
+ // Turn datetimes into proper objects
262
+ stats.atime = new Date(stats.atime);
263
+ stats.mtime = new Date(stats.mtime);
264
+ stats.ctime = new Date(stats.ctime);
265
+ return stats;
266
+ }
267
+ /**
268
+ * Normalize a Path by making it compliant for the content manager
269
+ *
270
+ * @param path: the path relatively to the Emscripten drive
271
+ */
272
+ normalizePath(path) {
273
+ // Remove mountpoint prefix
274
+ if (path.startsWith(this._mountpoint)) {
275
+ path = path.slice(this._mountpoint.length);
276
+ }
277
+ // Add JupyterLab drive name
278
+ if (this._driveName) {
279
+ path = `${this._driveName}${DRIVE_SEPARATOR}${path}`;
280
+ }
281
+ return path;
282
+ }
283
+ /**
284
+ * Get the api/drive endpoint
285
+ */
286
+ get endpoint() {
287
+ return `${this._baseUrl}api/drive/`;
288
+ }
289
+ }
290
+ export class DriveFS {
291
+ constructor(options) {
292
+ this.FS = options.FS;
293
+ this.PATH = options.PATH;
294
+ this.ERRNO_CODES = options.ERRNO_CODES;
295
+ this.API = new ContentsAPI(options.baseUrl, options.driveName, options.mountpoint, this.FS, this.ERRNO_CODES);
296
+ this.driveName = options.driveName;
297
+ this.node_ops = new DriveFSEmscriptenNodeOps(this);
298
+ this.stream_ops = new DriveFSEmscriptenStreamOps(this);
299
+ }
300
+ mount(mount) {
301
+ return this.createNode(null, mount.mountpoint, DIR_MODE | 511, 0);
302
+ }
303
+ createNode(parent, name, mode, dev) {
304
+ const FS = this.FS;
305
+ if (!FS.isDir(mode) && !FS.isFile(mode)) {
306
+ throw new FS.ErrnoError(this.ERRNO_CODES['EINVAL']);
307
+ }
308
+ const node = FS.createNode(parent, name, mode, dev);
309
+ node.node_ops = this.node_ops;
310
+ node.stream_ops = this.stream_ops;
311
+ return node;
312
+ }
313
+ getMode(path) {
314
+ return this.API.getmode(path);
315
+ }
316
+ realPath(node) {
317
+ const parts = [];
318
+ let currentNode = node;
319
+ parts.push(currentNode.name);
320
+ while (currentNode.parent !== currentNode) {
321
+ currentNode = currentNode.parent;
322
+ parts.push(currentNode.name);
323
+ }
324
+ parts.reverse();
325
+ return this.PATH.join.apply(null, parts);
326
+ }
327
+ }
package/lib/index.d.ts CHANGED
@@ -1,2 +1,3 @@
1
1
  export * from './contents';
2
+ export * from './drivefs';
2
3
  export * from './tokens';
package/lib/index.js CHANGED
@@ -1,4 +1,5 @@
1
1
  // Copyright (c) Jupyter Development Team.
2
2
  // Distributed under the terms of the Modified BSD License.
3
3
  export * from './contents';
4
+ export * from './drivefs';
4
5
  export * from './tokens';
package/lib/tokens.d.ts CHANGED
@@ -107,16 +107,20 @@ export interface IContents {
107
107
  * Commonly-used mimetypes
108
108
  */
109
109
  export declare namespace MIME {
110
- const JS = "application/javascript";
111
110
  const JSON = "application/json";
112
- const MANIFEST_JSON = "application/manifest+json";
113
111
  const PLAIN_TEXT = "text/plain";
114
- const PYTHON = "application/x-python-code";
115
- const SVG = "image/svg+xml";
116
- const XML = "application/xml";
112
+ const OCTET_STREAM = "octet/stream";
113
+ }
114
+ /**
115
+ * A namespace for file constructs.
116
+ */
117
+ export declare namespace FILE {
117
118
  /**
118
- * A list of mime types of common text file types
119
+ * Get a mimetype (or fallback).
119
120
  */
120
- const KNOWN_TEXT_TYPES: Set<string>;
121
- const OCTET_STREAM = "octet/stream";
121
+ function getType(ext: string, defaultType?: string | null): string;
122
+ /**
123
+ * Determine whether the given extension matches a given fileFormat.
124
+ */
125
+ function hasFormat(ext: string, fileFormat: 'base64' | 'text' | 'json'): boolean;
122
126
  }
package/lib/tokens.js CHANGED
@@ -1,3 +1,5 @@
1
+ import { PageConfig } from '@jupyterlab/coreutils';
2
+ import mime from 'mime';
1
3
  import { Token } from '@lumino/coreutils';
2
4
  /**
3
5
  * The token for the settings service.
@@ -8,24 +10,50 @@ export const IContents = new Token('@jupyterlite/contents:IContents');
8
10
  */
9
11
  export var MIME;
10
12
  (function (MIME) {
11
- MIME.JS = 'application/javascript';
12
13
  MIME.JSON = 'application/json';
13
- MIME.MANIFEST_JSON = 'application/manifest+json';
14
14
  MIME.PLAIN_TEXT = 'text/plain';
15
- MIME.PYTHON = 'application/x-python-code';
16
- MIME.SVG = 'image/svg+xml';
17
- MIME.XML = 'application/xml';
18
- /**
19
- * A list of mime types of common text file types
20
- */
21
- MIME.KNOWN_TEXT_TYPES = new Set([
22
- MIME.JS,
23
- MIME.JSON,
24
- MIME.MANIFEST_JSON,
25
- MIME.PLAIN_TEXT,
26
- MIME.PYTHON,
27
- MIME.SVG,
28
- MIME.XML,
29
- ]);
30
15
  MIME.OCTET_STREAM = 'octet/stream';
31
16
  })(MIME || (MIME = {}));
17
+ /**
18
+ * A namespace for file constructs.
19
+ */
20
+ export var FILE;
21
+ (function (FILE) {
22
+ /**
23
+ * Build-time configured file types.
24
+ */
25
+ const TYPES = JSON.parse(PageConfig.getOption('fileTypes') || '{}');
26
+ /**
27
+ * Get a mimetype (or fallback).
28
+ */
29
+ function getType(ext, defaultType = null) {
30
+ ext = ext.toLowerCase();
31
+ for (const fileType of Object.values(TYPES)) {
32
+ for (const fileExt of fileType.extensions || []) {
33
+ if (fileExt === ext && fileType.mimeTypes && fileType.mimeTypes.length) {
34
+ return fileType.mimeTypes[0];
35
+ }
36
+ }
37
+ }
38
+ return mime.getType(ext) || defaultType || MIME.OCTET_STREAM;
39
+ }
40
+ FILE.getType = getType;
41
+ /**
42
+ * Determine whether the given extension matches a given fileFormat.
43
+ */
44
+ function hasFormat(ext, fileFormat) {
45
+ ext = ext.toLowerCase();
46
+ for (const fileType of Object.values(TYPES)) {
47
+ if (fileType.fileFormat !== fileFormat) {
48
+ continue;
49
+ }
50
+ for (const fileExt of fileType.extensions || []) {
51
+ if (fileExt === ext) {
52
+ return true;
53
+ }
54
+ }
55
+ }
56
+ return false;
57
+ }
58
+ FILE.hasFormat = hasFormat;
59
+ })(FILE || (FILE = {}));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jupyterlite/contents",
3
- "version": "0.1.0-beta.8",
3
+ "version": "0.1.0-beta.9",
4
4
  "description": "JupyterLite - Contents",
5
5
  "homepage": "https://github.com/jupyterlite/jupyterlite",
6
6
  "bugs": {
@@ -42,9 +42,9 @@
42
42
  "watch": "tsc -b --watch"
43
43
  },
44
44
  "dependencies": {
45
- "@jupyterlab/nbformat": "~3.4.2",
46
- "@jupyterlab/services": "~6.4.2",
47
- "@jupyterlite/localforage": "^0.1.0-beta.8",
45
+ "@jupyterlab/nbformat": "~3.4.3",
46
+ "@jupyterlab/services": "~6.4.3",
47
+ "@jupyterlite/localforage": "^0.1.0-beta.9",
48
48
  "@lumino/coreutils": "^1.12.0",
49
49
  "localforage": "^1.9.0",
50
50
  "mime": "^3.0.0"
@@ -52,7 +52,7 @@
52
52
  "devDependencies": {
53
53
  "@babel/core": "^7.11.6",
54
54
  "@babel/preset-env": "^7.12.1",
55
- "@jupyterlab/testutils": "~3.4.2",
55
+ "@jupyterlab/testutils": "~3.4.3",
56
56
  "@types/jest": "^26.0.10",
57
57
  "@types/mime": "^2.0.3",
58
58
  "jest": "^26.4.2",