@jupyterlite/contents 0.1.0-alpha.9 → 0.1.0-beta.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.
package/lib/contents.d.ts CHANGED
@@ -1,27 +1,25 @@
1
- import { Contents as ServerContents, ServerConnection } from '@jupyterlab/services';
2
- import { ModelDB } from '@jupyterlab/observables';
3
- import { ISignal } from '@lumino/signaling';
1
+ import { Contents as ServerContents } from '@jupyterlab/services';
4
2
  import { IContents } from './tokens';
5
3
  /**
6
4
  * A class to handle requests to /api/contents
7
5
  */
8
6
  export declare class Contents implements IContents {
9
7
  /**
10
- * A signal emitted when the file has changed.
8
+ * Construct a new localForage-powered contents provider
11
9
  */
12
- get fileChanged(): ISignal<ServerContents.IManager, ServerContents.IChangedArgs>;
10
+ constructor(options?: Contents.IOptions);
13
11
  /**
14
- * Test whether the manager has been disposed.
12
+ * Initialize the default storage for contents.
15
13
  */
16
- get isDisposed(): boolean;
14
+ protected createDefaultStorage(): LocalForage;
17
15
  /**
18
- * Return the server settings.
16
+ * Initialize the default storage for counting file suffixes.
19
17
  */
20
- get serverSettings(): ServerConnection.ISettings;
18
+ protected createDefaultCounters(): LocalForage;
21
19
  /**
22
- * Dispose of the resources held by the manager.
20
+ * Create the default checkpoint storage.
23
21
  */
24
- dispose(): void;
22
+ protected createDefaultCheckpoints(): LocalForage;
25
23
  /**
26
24
  * Create a new untitled file or directory in the specified directory path.
27
25
  *
@@ -29,7 +27,7 @@ export declare class Contents implements IContents {
29
27
  *
30
28
  * @returns A promise which resolves with the created file content when the file is created.
31
29
  */
32
- newUntitled(options?: ServerContents.ICreateOptions): Promise<ServerContents.IModel>;
30
+ newUntitled(options?: ServerContents.ICreateOptions): Promise<ServerContents.IModel | null>;
33
31
  /**
34
32
  * Copy a file into a given directory.
35
33
  *
@@ -51,32 +49,7 @@ export declare class Contents implements IContents {
51
49
  *
52
50
  * @returns A promise which resolves with the file content.
53
51
  */
54
- get(path: string, options?: ServerContents.IFetchOptions): Promise<ServerContents.IModel>;
55
- /**
56
- * retrieve the contents for this path from the union of local storage and
57
- * `api/contents/{path}/all.json`.
58
- *
59
- * @param path - The contents path to retrieve
60
- *
61
- * @returns A promise which resolves with a Map of contents, keyed by local file name
62
- */
63
- getFolder(path: string): Promise<ServerContents.IModel>;
64
- private _serverContents;
65
- /**
66
- * retrieve the contents for this path from `__index__.json` in the appropriate
67
- * folder.
68
- *
69
- * @param newLocalPath - The new file path.
70
- *
71
- * @returns A promise which resolves with a Map of contents, keyed by local file name
72
- */
73
- getServerDirectory(path: string): Promise<Map<string, ServerContents.IModel>>;
74
- /**
75
- * Attempt to recover the model from `{:path}/__all__.json` file, fall back to
76
- * deriving the model (including content) off the file in `/files/`. Otherwise
77
- * return `null`.
78
- */
79
- getServerContents(path: string, options?: ServerContents.IFetchOptions): Promise<ServerContents.IModel | null>;
52
+ get(path: string, options?: ServerContents.IFetchOptions): Promise<ServerContents.IModel | null>;
80
53
  /**
81
54
  * Rename a file or directory.
82
55
  *
@@ -94,7 +67,7 @@ export declare class Contents implements IContents {
94
67
  *
95
68
  * @returns A promise which resolves with the file content model when the file is saved.
96
69
  */
97
- save(path: string, options?: Partial<ServerContents.IModel>): Promise<ServerContents.IModel>;
70
+ save(path: string, options?: Partial<ServerContents.IModel>): Promise<ServerContents.IModel | null>;
98
71
  /**
99
72
  * Delete a file.
100
73
  *
@@ -138,67 +111,29 @@ export declare class Contents implements IContents {
138
111
  */
139
112
  deleteCheckpoint(path: string, checkpointID: string): Promise<void>;
140
113
  /**
141
- * Add an `IDrive` to the manager.
142
- */
143
- addDrive(drive: ServerContents.IDrive): void;
144
- /**
145
- * Given a path of the form `drive:local/portion/of/it.txt`
146
- * get the local part of it.
147
- *
148
- * @param path: the path.
149
- *
150
- * @returns The local part of the path.
151
- */
152
- localPath(path: string): string;
153
- /**
154
- * Normalize a global path. Reduces '..' and '.' parts, and removes
155
- * leading slashes from the local part of the path, while retaining
156
- * the drive name if it exists.
157
- *
158
- * @param path: the path.
159
- *
160
- * @returns The normalized path.
161
- */
162
- normalize(path: string): string;
163
- /**
164
- * Resolve a global path, starting from the root path. Behaves like
165
- * posix-path.resolve, with 3 differences:
166
- * - will never prepend cwd
167
- * - if root has a drive name, the result is prefixed with "<drive>:"
168
- * - before adding drive name, leading slashes are removed
169
- *
170
- * @param path: the path.
171
- *
172
- * @returns The normalized path.
173
- */
174
- resolvePath(root: string, path: string): string;
175
- /**
176
- * Given a path of the form `drive:local/portion/of/it.txt`
177
- * get the name of the drive. If the path is missing
178
- * a drive portion, returns an empty string.
114
+ * retrieve the contents for this path from the union of local storage and
115
+ * `api/contents/{path}/all.json`.
179
116
  *
180
- * @param path: the path.
117
+ * @param path - The contents path to retrieve
181
118
  *
182
- * @returns The drive name for the path, or the empty string.
119
+ * @returns A promise which resolves with a Map of contents, keyed by local file name
183
120
  */
184
- driveName(path: string): string;
121
+ private _getFolder;
185
122
  /**
186
- * Given a path, get a ModelDB.IFactory from the
187
- * relevant backend. Returns `null` if the backend
188
- * does not provide one.
123
+ * Attempt to recover the model from `{:path}/__all__.json` file, fall back to
124
+ * deriving the model (including content) off the file in `/files/`. Otherwise
125
+ * return `null`.
189
126
  */
190
- getModelDBFactory(path: string): ModelDB.IFactory | null;
127
+ private _getServerContents;
191
128
  /**
192
- * Get an encoded download url given a file path.
193
- *
194
- * @param path - An absolute POSIX file path on the server.
129
+ * retrieve the contents for this path from `__index__.json` in the appropriate
130
+ * folder.
195
131
  *
196
- * #### Notes
197
- * It is expected that the path contains no relative paths.
132
+ * @param newLocalPath - The new file path.
198
133
  *
199
- * The returned URL may include a query parameter.
134
+ * @returns A promise which resolves with a Map of contents, keyed by local file name
200
135
  */
201
- getDownloadUrl(path: string): Promise<string>;
136
+ private _getServerDirectory;
202
137
  /**
203
138
  * Increment the counter for a given file type.
204
139
  * Used to avoid collisions when creating new untitled files.
@@ -206,9 +141,20 @@ export declare class Contents implements IContents {
206
141
  * @param type The file type to increment the counter for.
207
142
  */
208
143
  private _incrementCounter;
209
- private _isDisposed;
210
- private _fileChanged;
144
+ private _serverContents;
145
+ private _storageName;
211
146
  private _storage;
212
147
  private _counters;
213
148
  private _checkpoints;
214
149
  }
150
+ /**
151
+ * A namespace for contents information.
152
+ */
153
+ export declare namespace Contents {
154
+ interface IOptions {
155
+ /**
156
+ * The name of the storage instance on e.g. IndexedDB, localStorage
157
+ */
158
+ contentsStorageName: string;
159
+ }
160
+ }
package/lib/contents.js CHANGED
@@ -1,67 +1,72 @@
1
1
  import { PageConfig, URLExt } from '@jupyterlab/coreutils';
2
- import { ServerConnection } from '@jupyterlab/services';
3
2
  import { PathExt } from '@jupyterlab/coreutils';
4
- import { Signal } from '@lumino/signaling';
5
3
  import localforage from 'localforage';
6
4
  /**
7
5
  * The name of the local storage.
8
6
  */
9
- const STORAGE_NAME = 'JupyterLite Storage';
7
+ const DEFAULT_STORAGE_NAME = 'JupyterLite Storage';
10
8
  /**
11
9
  * The number of checkpoints to save.
12
10
  */
13
11
  const N_CHECKPOINTS = 5;
12
+ /**
13
+ * A list of mime types of text files
14
+ */
15
+ const EXTRA_TEXT_MIME_TYPES = new Set([
16
+ 'application/javascript',
17
+ 'application/json',
18
+ 'application/manifest+json',
19
+ 'application/x-python-code',
20
+ 'application/xml',
21
+ 'image/svg+xml',
22
+ ]);
14
23
  /**
15
24
  * A class to handle requests to /api/contents
16
25
  */
17
26
  export class Contents {
18
- constructor() {
19
- this._serverContents = new Map();
20
- this._isDisposed = false;
21
- this._fileChanged = new Signal(this);
22
- this._storage = localforage.createInstance({
23
- name: STORAGE_NAME,
24
- description: 'Offline Storage for Notebooks and Files',
25
- storeName: 'files',
26
- version: 1
27
- });
28
- this._counters = localforage.createInstance({
29
- name: STORAGE_NAME,
30
- description: 'Store the current file suffix counters',
31
- storeName: 'counters',
32
- version: 1
33
- });
34
- this._checkpoints = localforage.createInstance({
35
- name: STORAGE_NAME,
36
- description: 'Offline Storage for Checkpoints',
37
- storeName: 'checkpoints',
38
- version: 1
39
- });
40
- }
41
27
  /**
42
- * A signal emitted when the file has changed.
28
+ * Construct a new localForage-powered contents provider
43
29
  */
44
- get fileChanged() {
45
- return this._fileChanged;
30
+ constructor(options) {
31
+ this._serverContents = new Map();
32
+ this._storageName = DEFAULT_STORAGE_NAME;
33
+ this._storageName = (options || {}).contentsStorageName || DEFAULT_STORAGE_NAME;
34
+ this._storage = this.createDefaultStorage();
35
+ this._counters = this.createDefaultCounters();
36
+ this._checkpoints = this.createDefaultCheckpoints();
46
37
  }
47
38
  /**
48
- * Test whether the manager has been disposed.
39
+ * Initialize the default storage for contents.
49
40
  */
50
- get isDisposed() {
51
- return this._isDisposed;
41
+ createDefaultStorage() {
42
+ return localforage.createInstance({
43
+ name: this._storageName,
44
+ description: 'Offline Storage for Notebooks and Files',
45
+ storeName: 'files',
46
+ version: 1,
47
+ });
52
48
  }
53
49
  /**
54
- * Return the server settings.
50
+ * Initialize the default storage for counting file suffixes.
55
51
  */
56
- get serverSettings() {
57
- // TODO: placeholder
58
- return ServerConnection.makeSettings();
52
+ createDefaultCounters() {
53
+ return localforage.createInstance({
54
+ name: this._storageName,
55
+ description: 'Store the current file suffix counters',
56
+ storeName: 'counters',
57
+ version: 1,
58
+ });
59
59
  }
60
60
  /**
61
- * Dispose of the resources held by the manager.
61
+ * Create the default checkpoint storage.
62
62
  */
63
- dispose() {
64
- throw new Error('Method not implemented.');
63
+ createDefaultCheckpoints() {
64
+ return localforage.createInstance({
65
+ name: this._storageName,
66
+ description: 'Offline Storage for Checkpoints',
67
+ storeName: 'checkpoints',
68
+ version: 1,
69
+ });
65
70
  }
66
71
  /**
67
72
  * Create a new untitled file or directory in the specified directory path.
@@ -75,16 +80,36 @@ export class Contents {
75
80
  const path = (_a = options === null || options === void 0 ? void 0 : options.path) !== null && _a !== void 0 ? _a : '';
76
81
  const type = (_b = options === null || options === void 0 ? void 0 : options.type) !== null && _b !== void 0 ? _b : 'notebook';
77
82
  const created = new Date().toISOString();
78
- const prefix = path ? `${path}/` : '';
79
- let file;
83
+ let dirname = PathExt.dirname(path);
84
+ const basename = PathExt.basename(path);
85
+ const extname = PathExt.extname(path);
86
+ const item = await this.get(dirname);
87
+ // handle the case of "Save As", where the path points to the new file
88
+ // to create, e.g. subfolder/example-copy.ipynb
80
89
  let name = '';
90
+ if (path && !extname && item) {
91
+ // directory
92
+ dirname = `${path}/`;
93
+ name = '';
94
+ }
95
+ else if (dirname && basename) {
96
+ // file in a subfolder
97
+ dirname = `${dirname}/`;
98
+ name = basename;
99
+ }
100
+ else {
101
+ // file at the top level
102
+ dirname = '';
103
+ name = path;
104
+ }
105
+ let file;
81
106
  switch (type) {
82
107
  case 'directory': {
83
108
  const counter = await this._incrementCounter('directory');
84
- name += `Untitled Folder${counter || ''}`;
109
+ name = `Untitled Folder${counter || ''}`;
85
110
  file = {
86
111
  name,
87
- path: `${prefix}${name}`,
112
+ path: `${dirname}${name}`,
88
113
  last_modified: created,
89
114
  created,
90
115
  format: 'text',
@@ -92,17 +117,17 @@ export class Contents {
92
117
  content: null,
93
118
  size: undefined,
94
119
  writable: true,
95
- type: 'directory'
120
+ type: 'directory',
96
121
  };
97
122
  break;
98
123
  }
99
124
  case 'file': {
100
125
  const ext = (_c = options === null || options === void 0 ? void 0 : options.ext) !== null && _c !== void 0 ? _c : '.txt';
101
126
  const counter = await this._incrementCounter('file');
102
- name += `untitled${counter || ''}${ext}`;
127
+ name = name || `untitled${counter || ''}${ext}`;
103
128
  file = {
104
129
  name,
105
- path: `${prefix}${name}`,
130
+ path: `${dirname}${name}`,
106
131
  last_modified: created,
107
132
  created,
108
133
  format: 'text',
@@ -111,16 +136,16 @@ export class Contents {
111
136
  content: '',
112
137
  size: 0,
113
138
  writable: true,
114
- type: 'file'
139
+ type: 'file',
115
140
  };
116
141
  break;
117
142
  }
118
143
  default: {
119
144
  const counter = await this._incrementCounter('notebook');
120
- name += `Untitled${counter || ''}.ipynb`;
145
+ name = name || `Untitled${counter || ''}.ipynb`;
121
146
  file = {
122
147
  name,
123
- path: `${prefix}${name}`,
148
+ path: `${dirname}${name}`,
124
149
  last_modified: created,
125
150
  created,
126
151
  format: 'json',
@@ -128,12 +153,12 @@ export class Contents {
128
153
  content: Private.EMPTY_NB,
129
154
  size: JSON.stringify(Private.EMPTY_NB).length,
130
155
  writable: true,
131
- type: 'notebook'
156
+ type: 'notebook',
132
157
  };
133
158
  break;
134
159
  }
135
160
  }
136
- const key = `${prefix}${name}`;
161
+ const key = file.path;
137
162
  await this._storage.setItem(key, file);
138
163
  return file;
139
164
  }
@@ -160,10 +185,13 @@ export class Contents {
160
185
  }
161
186
  const toPath = `${toDir}${name}`;
162
187
  let item = await this.get(path, { content: true });
188
+ if (!item) {
189
+ throw Error(`Could not find file with path ${path}`);
190
+ }
163
191
  item = {
164
192
  ...item,
165
193
  name,
166
- path: toPath
194
+ path: toPath,
167
195
  };
168
196
  await this._storage.setItem(toPath, item);
169
197
  return item;
@@ -180,19 +208,19 @@ export class Contents {
180
208
  // remove leading slash
181
209
  path = decodeURIComponent(path.replace(/^\//, ''));
182
210
  if (path === '') {
183
- return await this.getFolder(path);
211
+ return await this._getFolder(path);
184
212
  }
185
213
  const item = await this._storage.getItem(path);
186
- const serverItem = await this.getServerContents(path, options);
214
+ const serverItem = await this._getServerContents(path, options);
187
215
  const model = (item || serverItem);
188
216
  if (!model) {
189
- throw Error(`Could not find file with path ${path}`);
217
+ return null;
190
218
  }
191
219
  if (!(options === null || options === void 0 ? void 0 : options.content)) {
192
220
  return {
193
221
  ...model,
194
222
  content: null,
195
- size: undefined
223
+ size: undefined,
196
224
  };
197
225
  }
198
226
  // for directories, find all files with the path as the prefix
@@ -207,7 +235,7 @@ export class Contents {
207
235
  });
208
236
  const serverContents = serverItem
209
237
  ? serverItem.content
210
- : Array.from((await this.getServerDirectory(path)).values());
238
+ : Array.from((await this._getServerDirectory(path)).values());
211
239
  for (const file of serverContents) {
212
240
  if (!contentMap.has(file.name)) {
213
241
  contentMap.set(file.name, file);
@@ -224,136 +252,11 @@ export class Contents {
224
252
  content,
225
253
  size: undefined,
226
254
  writable: true,
227
- type: 'directory'
255
+ type: 'directory',
228
256
  };
229
257
  }
230
258
  return model;
231
259
  }
232
- /**
233
- * retrieve the contents for this path from the union of local storage and
234
- * `api/contents/{path}/all.json`.
235
- *
236
- * @param path - The contents path to retrieve
237
- *
238
- * @returns A promise which resolves with a Map of contents, keyed by local file name
239
- */
240
- async getFolder(path) {
241
- const content = new Map();
242
- await this._storage.iterate((item, key) => {
243
- if (key.includes('/')) {
244
- return;
245
- }
246
- const file = item;
247
- content.set(file.path, file);
248
- });
249
- // layer in contents that don't have local overwrites
250
- for (const file of (await this.getServerDirectory(path)).values()) {
251
- if (!content.has(file.path)) {
252
- content.set(file.path, file);
253
- }
254
- }
255
- return {
256
- name: '',
257
- path,
258
- last_modified: new Date(0).toISOString(),
259
- created: new Date(0).toISOString(),
260
- format: 'json',
261
- mimetype: 'application/json',
262
- content: Array.from(content.values()),
263
- size: undefined,
264
- writable: true,
265
- type: 'directory'
266
- };
267
- }
268
- /**
269
- * retrieve the contents for this path from `__index__.json` in the appropriate
270
- * folder.
271
- *
272
- * @param newLocalPath - The new file path.
273
- *
274
- * @returns A promise which resolves with a Map of contents, keyed by local file name
275
- */
276
- async getServerDirectory(path) {
277
- const content = this._serverContents.get(path) || new Map();
278
- if (!this._serverContents.has(path)) {
279
- const apiURL = URLExt.join(PageConfig.getBaseUrl(), 'api/contents', path, 'all.json');
280
- try {
281
- const response = await fetch(apiURL);
282
- const json = JSON.parse(await response.text());
283
- for (const file of json['content']) {
284
- content.set(file.name, file);
285
- }
286
- }
287
- catch (err) {
288
- console.warn(`don't worry, about ${err}... nothing's broken. if there had been a
289
- file at ${apiURL}, you might see some more files.`);
290
- }
291
- this._serverContents.set(path, content);
292
- }
293
- return content;
294
- }
295
- /**
296
- * Attempt to recover the model from `{:path}/__all__.json` file, fall back to
297
- * deriving the model (including content) off the file in `/files/`. Otherwise
298
- * return `null`.
299
- */
300
- async getServerContents(path, options) {
301
- const name = PathExt.basename(path);
302
- const parentContents = await this.getServerDirectory(URLExt.join(path, '..'));
303
- let model = parentContents.get(name) || {
304
- name,
305
- path,
306
- last_modified: new Date(0).toISOString(),
307
- created: new Date(0).toISOString(),
308
- format: 'text',
309
- mimetype: 'text/plain',
310
- type: 'file',
311
- writable: true,
312
- content: null
313
- };
314
- if (options === null || options === void 0 ? void 0 : options.content) {
315
- if (model.type === 'directory') {
316
- const serverContents = await this.getServerDirectory(path);
317
- model = { ...model, content: Array.from(serverContents.values()) };
318
- }
319
- else {
320
- const fileUrl = URLExt.join(PageConfig.getBaseUrl(), 'files', path);
321
- const response = await fetch(fileUrl);
322
- if (!response.ok) {
323
- return null;
324
- }
325
- const mimetype = model.mimetype || response.headers.get('Content-Type');
326
- if (model.type === 'notebook' ||
327
- (mimetype === null || mimetype === void 0 ? void 0 : mimetype.indexOf('json')) !== -1 ||
328
- path.match(/\.(ipynb|[^/]*json[^/]*)$/)) {
329
- model = {
330
- ...model,
331
- content: await response.json(),
332
- format: 'json',
333
- mimetype: model.mimetype || 'application/json'
334
- };
335
- // TODO: this is not great, need a better oracle
336
- }
337
- else if (mimetype.indexOf('xml') !== -1 || mimetype.indexOf('text') !== -1) {
338
- model = {
339
- ...model,
340
- content: await response.text(),
341
- format: 'text',
342
- mimetype: mimetype || 'text/plain'
343
- };
344
- }
345
- else {
346
- model = {
347
- ...model,
348
- content: btoa(String.fromCharCode(...new Uint8Array(await response.arrayBuffer()))),
349
- format: 'base64',
350
- mimetype: mimetype || 'octet/stream'
351
- };
352
- }
353
- }
354
- }
355
- return model;
356
- }
357
260
  /**
358
261
  * Rename a file or directory.
359
262
  *
@@ -374,7 +277,7 @@ export class Contents {
374
277
  ...file,
375
278
  name,
376
279
  path: newLocalPath,
377
- last_modified: modified
280
+ last_modified: modified,
378
281
  };
379
282
  await this._storage.setItem(newLocalPath, newFile);
380
283
  // remove the old file
@@ -400,28 +303,29 @@ export class Contents {
400
303
  */
401
304
  async save(path, options = {}) {
402
305
  var _a;
403
- let item = await this.get(path);
306
+ path = decodeURIComponent(path);
307
+ let item = (await this.get(path)) || (await this.newUntitled({ path }));
404
308
  if (!item) {
405
- item = await this.newUntitled({ path });
309
+ return null;
406
310
  }
407
311
  // override with the new values
408
312
  const modified = new Date().toISOString();
409
313
  item = {
410
314
  ...item,
411
315
  ...options,
412
- last_modified: modified
316
+ last_modified: modified,
413
317
  };
414
318
  // process the file if coming from an upload
415
319
  const ext = PathExt.extname((_a = options.name) !== null && _a !== void 0 ? _a : '');
416
320
  if (options.content && options.format === 'base64') {
417
321
  // TODO: keep base64 if not a text file (image)
418
- const content = atob(options.content);
322
+ const content = decodeURIComponent(escape(atob(options.content)));
419
323
  const nb = ext === '.ipynb';
420
324
  item = {
421
325
  ...item,
422
326
  content: nb ? JSON.parse(content) : content,
423
327
  format: nb ? 'json' : 'text',
424
- type: nb ? 'notebook' : 'file'
328
+ type: nb ? 'notebook' : 'file',
425
329
  };
426
330
  }
427
331
  await this._storage.setItem(path, item);
@@ -444,7 +348,7 @@ export class Contents {
444
348
  await Promise.all(toDelete.map(async (p) => {
445
349
  return Promise.all([
446
350
  this._storage.removeItem(p),
447
- this._checkpoints.removeItem(p)
351
+ this._checkpoints.removeItem(p),
448
352
  ]);
449
353
  }));
450
354
  }
@@ -458,8 +362,12 @@ export class Contents {
458
362
  */
459
363
  async createCheckpoint(path) {
460
364
  var _a;
365
+ path = decodeURIComponent(path);
461
366
  const item = await this.get(path, { content: true });
462
- const copies = ((_a = (await this._checkpoints.getItem(path))) !== null && _a !== void 0 ? _a : []).filter(item => !!item);
367
+ if (!item) {
368
+ throw Error(`Could not find file with path ${path}`);
369
+ }
370
+ const copies = ((_a = (await this._checkpoints.getItem(path))) !== null && _a !== void 0 ? _a : []).filter((item) => !!item);
463
371
  copies.push(item);
464
372
  // keep only a certain amount of checkpoints per file
465
373
  if (copies.length > N_CHECKPOINTS) {
@@ -469,7 +377,7 @@ export class Contents {
469
377
  const id = `${copies.length - 1}`;
470
378
  return {
471
379
  id,
472
- last_modified: item.last_modified
380
+ last_modified: item.last_modified,
473
381
  };
474
382
  }
475
383
  /**
@@ -484,11 +392,11 @@ export class Contents {
484
392
  const copies = ((await this._checkpoints.getItem(path)) ||
485
393
  []);
486
394
  return copies
487
- .filter(item => !!item)
395
+ .filter((item) => !!item)
488
396
  .map((file, id) => {
489
397
  return {
490
398
  id: id.toString(),
491
- last_modified: file.last_modified
399
+ last_modified: file.last_modified,
492
400
  };
493
401
  });
494
402
  }
@@ -501,6 +409,7 @@ export class Contents {
501
409
  * @returns A promise which resolves when the checkpoint is restored.
502
410
  */
503
411
  async restoreCheckpoint(path, checkpointID) {
412
+ path = decodeURIComponent(path);
504
413
  const copies = ((await this._checkpoints.getItem(path)) ||
505
414
  []);
506
415
  const id = parseInt(checkpointID);
@@ -516,6 +425,7 @@ export class Contents {
516
425
  * @returns A promise which resolves when the checkpoint is deleted.
517
426
  */
518
427
  async deleteCheckpoint(path, checkpointID) {
428
+ path = decodeURIComponent(path);
519
429
  const copies = ((await this._checkpoints.getItem(path)) ||
520
430
  []);
521
431
  const id = parseInt(checkpointID);
@@ -523,80 +433,136 @@ export class Contents {
523
433
  await this._checkpoints.setItem(path, copies);
524
434
  }
525
435
  /**
526
- * Add an `IDrive` to the manager.
527
- */
528
- addDrive(drive) {
529
- throw new Error('Method not implemented.');
530
- }
531
- /**
532
- * Given a path of the form `drive:local/portion/of/it.txt`
533
- * get the local part of it.
534
- *
535
- * @param path: the path.
536
- *
537
- * @returns The local part of the path.
538
- */
539
- localPath(path) {
540
- throw new Error('Method not implemented.');
541
- }
542
- /**
543
- * Normalize a global path. Reduces '..' and '.' parts, and removes
544
- * leading slashes from the local part of the path, while retaining
545
- * the drive name if it exists.
546
- *
547
- * @param path: the path.
548
- *
549
- * @returns The normalized path.
550
- */
551
- normalize(path) {
552
- throw new Error('Method not implemented.');
553
- }
554
- /**
555
- * Resolve a global path, starting from the root path. Behaves like
556
- * posix-path.resolve, with 3 differences:
557
- * - will never prepend cwd
558
- * - if root has a drive name, the result is prefixed with "<drive>:"
559
- * - before adding drive name, leading slashes are removed
560
- *
561
- * @param path: the path.
562
- *
563
- * @returns The normalized path.
564
- */
565
- resolvePath(root, path) {
566
- throw new Error('Method not implemented.');
567
- }
568
- /**
569
- * Given a path of the form `drive:local/portion/of/it.txt`
570
- * get the name of the drive. If the path is missing
571
- * a drive portion, returns an empty string.
436
+ * retrieve the contents for this path from the union of local storage and
437
+ * `api/contents/{path}/all.json`.
572
438
  *
573
- * @param path: the path.
439
+ * @param path - The contents path to retrieve
574
440
  *
575
- * @returns The drive name for the path, or the empty string.
441
+ * @returns A promise which resolves with a Map of contents, keyed by local file name
576
442
  */
577
- driveName(path) {
578
- throw new Error('Method not implemented.');
443
+ async _getFolder(path) {
444
+ const content = new Map();
445
+ await this._storage.iterate((item, key) => {
446
+ if (key.includes('/')) {
447
+ return;
448
+ }
449
+ const file = item;
450
+ content.set(file.path, file);
451
+ });
452
+ // layer in contents that don't have local overwrites
453
+ for (const file of (await this._getServerDirectory(path)).values()) {
454
+ if (!content.has(file.path)) {
455
+ content.set(file.path, file);
456
+ }
457
+ }
458
+ if (path && content.size === 0) {
459
+ return null;
460
+ }
461
+ return {
462
+ name: '',
463
+ path,
464
+ last_modified: new Date(0).toISOString(),
465
+ created: new Date(0).toISOString(),
466
+ format: 'json',
467
+ mimetype: 'application/json',
468
+ content: Array.from(content.values()),
469
+ size: undefined,
470
+ writable: true,
471
+ type: 'directory',
472
+ };
579
473
  }
580
474
  /**
581
- * Given a path, get a ModelDB.IFactory from the
582
- * relevant backend. Returns `null` if the backend
583
- * does not provide one.
475
+ * Attempt to recover the model from `{:path}/__all__.json` file, fall back to
476
+ * deriving the model (including content) off the file in `/files/`. Otherwise
477
+ * return `null`.
584
478
  */
585
- getModelDBFactory(path) {
586
- throw new Error('Method not implemented.');
479
+ async _getServerContents(path, options) {
480
+ const name = PathExt.basename(path);
481
+ const parentContents = await this._getServerDirectory(URLExt.join(path, '..'));
482
+ let model = parentContents.get(name);
483
+ if (!model) {
484
+ return null;
485
+ }
486
+ model = model || {
487
+ name,
488
+ path,
489
+ last_modified: new Date(0).toISOString(),
490
+ created: new Date(0).toISOString(),
491
+ format: 'text',
492
+ mimetype: 'text/plain',
493
+ type: 'file',
494
+ writable: true,
495
+ content: null,
496
+ };
497
+ if (options === null || options === void 0 ? void 0 : options.content) {
498
+ if (model.type === 'directory') {
499
+ const serverContents = await this._getServerDirectory(path);
500
+ model = { ...model, content: Array.from(serverContents.values()) };
501
+ }
502
+ else {
503
+ const fileUrl = URLExt.join(PageConfig.getBaseUrl(), 'files', path);
504
+ const response = await fetch(fileUrl);
505
+ if (!response.ok) {
506
+ return null;
507
+ }
508
+ const mimetype = model.mimetype || response.headers.get('Content-Type');
509
+ if (model.type === 'notebook' ||
510
+ (mimetype === null || mimetype === void 0 ? void 0 : mimetype.indexOf('json')) !== -1 ||
511
+ path.match(/\.(ipynb|[^/]*json[^/]*)$/)) {
512
+ model = {
513
+ ...model,
514
+ content: await response.json(),
515
+ format: 'json',
516
+ mimetype: model.mimetype || 'application/json',
517
+ };
518
+ }
519
+ else if (mimetype.indexOf('text') !== -1 ||
520
+ EXTRA_TEXT_MIME_TYPES.has(mimetype)) {
521
+ model = {
522
+ ...model,
523
+ content: await response.text(),
524
+ format: 'text',
525
+ mimetype: mimetype || 'text/plain',
526
+ };
527
+ }
528
+ else {
529
+ model = {
530
+ ...model,
531
+ content: btoa(String.fromCharCode(...new Uint8Array(await response.arrayBuffer()))),
532
+ format: 'base64',
533
+ mimetype: mimetype || 'octet/stream',
534
+ };
535
+ }
536
+ }
537
+ }
538
+ return model;
587
539
  }
588
540
  /**
589
- * Get an encoded download url given a file path.
590
- *
591
- * @param path - An absolute POSIX file path on the server.
541
+ * retrieve the contents for this path from `__index__.json` in the appropriate
542
+ * folder.
592
543
  *
593
- * #### Notes
594
- * It is expected that the path contains no relative paths.
544
+ * @param newLocalPath - The new file path.
595
545
  *
596
- * The returned URL may include a query parameter.
546
+ * @returns A promise which resolves with a Map of contents, keyed by local file name
597
547
  */
598
- getDownloadUrl(path) {
599
- throw new Error('Method not implemented.');
548
+ async _getServerDirectory(path) {
549
+ const content = this._serverContents.get(path) || new Map();
550
+ if (!this._serverContents.has(path)) {
551
+ const apiURL = URLExt.join(PageConfig.getBaseUrl(), 'api/contents', path, 'all.json');
552
+ try {
553
+ const response = await fetch(apiURL);
554
+ const json = JSON.parse(await response.text());
555
+ for (const file of json['content']) {
556
+ content.set(file.name, file);
557
+ }
558
+ }
559
+ catch (err) {
560
+ console.warn(`don't worry, about ${err}... nothing's broken. if there had been a
561
+ file at ${apiURL}, you might see some more files.`);
562
+ }
563
+ this._serverContents.set(path, content);
564
+ }
565
+ return content;
600
566
  }
601
567
  /**
602
568
  * Increment the counter for a given file type.
@@ -622,10 +588,10 @@ var Private;
622
588
  */
623
589
  Private.EMPTY_NB = {
624
590
  metadata: {
625
- orig_nbformat: 4
591
+ orig_nbformat: 4,
626
592
  },
627
593
  nbformat_minor: 4,
628
594
  nbformat: 4,
629
- cells: []
595
+ cells: [],
630
596
  };
631
597
  })(Private || (Private = {}));
package/lib/tokens.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { Contents } from '@jupyterlab/services';
1
+ import { Contents as ServerContents } from '@jupyterlab/services';
2
2
  import { Token } from '@lumino/coreutils';
3
3
  /**
4
4
  * The token for the settings service.
@@ -7,5 +7,95 @@ export declare const IContents: Token<IContents>;
7
7
  /**
8
8
  * The interface for the contents service.
9
9
  */
10
- export interface IContents extends Contents.IManager {
10
+ export interface IContents {
11
+ /**
12
+ * Create a new untitled file or directory in the specified directory path.
13
+ *
14
+ * @param options: The options used to create the file.
15
+ *
16
+ * @returns A promise which resolves with the created file content when the file is created.
17
+ */
18
+ newUntitled(options?: ServerContents.ICreateOptions): Promise<ServerContents.IModel | null>;
19
+ /**
20
+ * Copy a file into a given directory.
21
+ *
22
+ * @param path - The original file path.
23
+ * @param toDir - The destination directory path.
24
+ *
25
+ * @returns A promise which resolves with the new contents model when the
26
+ * file is copied.
27
+ *
28
+ * #### Notes
29
+ * The server will select the name of the copied file.
30
+ */
31
+ copy(path: string, toDir: string): Promise<ServerContents.IModel>;
32
+ /**
33
+ * Get a file or directory.
34
+ *
35
+ * @param path: The path to the file.
36
+ * @param options: The options used to fetch the file.
37
+ *
38
+ * @returns A promise which resolves with the file content.
39
+ */
40
+ get(path: string, options?: ServerContents.IFetchOptions): Promise<ServerContents.IModel | null>;
41
+ /**
42
+ * Rename a file or directory.
43
+ *
44
+ * @param oldLocalPath - The original file path.
45
+ * @param newLocalPath - The new file path.
46
+ *
47
+ * @returns A promise which resolves with the new file content model when the file is renamed.
48
+ */
49
+ rename(oldLocalPath: string, newLocalPath: string): Promise<ServerContents.IModel>;
50
+ /**
51
+ * Save a file.
52
+ *
53
+ * @param path - The desired file path.
54
+ * @param options - Optional overrides to the model.
55
+ *
56
+ * @returns A promise which resolves with the file content model when the file is saved.
57
+ */
58
+ save(path: string, options?: Partial<ServerContents.IModel>): Promise<ServerContents.IModel | null>;
59
+ /**
60
+ * Delete a file.
61
+ *
62
+ * @param path - The path to the file.
63
+ */
64
+ delete(path: string): Promise<void>;
65
+ /**
66
+ * Create a checkpoint for a file.
67
+ *
68
+ * @param path - The path of the file.
69
+ *
70
+ * @returns A promise which resolves with the new checkpoint model when the
71
+ * checkpoint is created.
72
+ */
73
+ createCheckpoint(path: string): Promise<ServerContents.ICheckpointModel>;
74
+ /**
75
+ * List available checkpoints for a file.
76
+ *
77
+ * @param path - The path of the file.
78
+ *
79
+ * @returns A promise which resolves with a list of checkpoint models for
80
+ * the file.
81
+ */
82
+ listCheckpoints(path: string): Promise<ServerContents.ICheckpointModel[]>;
83
+ /**
84
+ * Restore a file to a known checkpoint state.
85
+ *
86
+ * @param path - The path of the file.
87
+ * @param checkpointID - The id of the checkpoint to restore.
88
+ *
89
+ * @returns A promise which resolves when the checkpoint is restored.
90
+ */
91
+ restoreCheckpoint(path: string, checkpointID: string): Promise<void>;
92
+ /**
93
+ * Delete a checkpoint for a file.
94
+ *
95
+ * @param path - The path of the file.
96
+ * @param checkpointID - The id of the checkpoint to delete.
97
+ *
98
+ * @returns A promise which resolves when the checkpoint is deleted.
99
+ */
100
+ deleteCheckpoint(path: string, checkpointID: string): Promise<void>;
11
101
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jupyterlite/contents",
3
- "version": "0.1.0-alpha.9",
3
+ "version": "0.1.0-beta.0",
4
4
  "description": "JupyterLite - Contents",
5
5
  "homepage": "https://github.com/jupyterlite/jupyterlite",
6
6
  "bugs": {
@@ -42,21 +42,20 @@
42
42
  "watch": "tsc -b --watch"
43
43
  },
44
44
  "dependencies": {
45
- "@jupyterlab/nbformat": "~3.1.12",
46
- "@jupyterlab/services": "~6.1.12",
45
+ "@jupyterlab/nbformat": "~3.2.9",
46
+ "@jupyterlab/services": "~6.2.9",
47
47
  "@lumino/coreutils": "^1.8.0",
48
- "@lumino/signaling": "^1.7.0",
49
48
  "localforage": "^1.9.0"
50
49
  },
51
50
  "devDependencies": {
52
51
  "@babel/core": "^7.11.6",
53
52
  "@babel/preset-env": "^7.12.1",
54
- "@jupyterlab/testutils": "~3.1.12",
53
+ "@jupyterlab/testutils": "~3.2.9",
55
54
  "@types/jest": "^26.0.10",
56
55
  "jest": "^26.4.2",
57
56
  "rimraf": "~3.0.0",
58
57
  "ts-jest": "^26.3.0",
59
- "typescript": "~4.2.3"
58
+ "typescript": "~4.5.2"
60
59
  },
61
60
  "publishConfig": {
62
61
  "access": "public"