@jupyterlite/contents 0.1.0-alpha.9 → 0.1.0-beta.2

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