@koolbase/core 12.18.0 → 12.20.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/dist/cjs/file-controller.d.ts +39 -0
- package/dist/cjs/file-controller.js +115 -0
- package/dist/cjs/files-controller.d.ts +62 -0
- package/dist/cjs/files-controller.js +160 -0
- package/dist/cjs/files-refresh.d.ts +9 -0
- package/dist/cjs/files-refresh.js +39 -0
- package/dist/cjs/index.d.ts +4 -0
- package/dist/cjs/index.js +10 -1
- package/dist/cjs/react/index.d.ts +2 -0
- package/dist/cjs/react/index.js +5 -1
- package/dist/cjs/react/use-file.d.ts +6 -0
- package/dist/cjs/react/use-file.js +35 -0
- package/dist/cjs/react/use-files.d.ts +8 -0
- package/dist/cjs/react/use-files.js +37 -0
- package/dist/cjs/storage.js +19 -8
- package/dist/esm/file-controller.d.ts +39 -0
- package/dist/esm/file-controller.js +111 -0
- package/dist/esm/files-controller.d.ts +62 -0
- package/dist/esm/files-controller.js +155 -0
- package/dist/esm/files-refresh.d.ts +9 -0
- package/dist/esm/files-refresh.js +34 -0
- package/dist/esm/index.d.ts +4 -0
- package/dist/esm/index.js +4 -0
- package/dist/esm/react/index.d.ts +2 -0
- package/dist/esm/react/index.js +2 -0
- package/dist/esm/react/use-file.d.ts +6 -0
- package/dist/esm/react/use-file.js +32 -0
- package/dist/esm/react/use-files.d.ts +8 -0
- package/dist/esm/react/use-files.js +34 -0
- package/dist/esm/storage.js +19 -8
- package/package.json +1 -1
package/dist/cjs/storage.js
CHANGED
|
@@ -8,8 +8,14 @@ const storage_errors_js_2 = require("./storage-errors.js");
|
|
|
8
8
|
const storage_transfer_js_1 = require("./storage-transfer.js");
|
|
9
9
|
const storage_multipart_js_1 = require("./storage-multipart.js");
|
|
10
10
|
const storage_errors_js_3 = require("./storage-errors.js");
|
|
11
|
+
const files_refresh_js_1 = require("./files-refresh.js");
|
|
11
12
|
const network_js_2 = require("./network.js");
|
|
12
13
|
const storage_files_js_1 = require("./storage-files.js");
|
|
14
|
+
/** An upload task whose success reloads the bucket's file lists (storage S4). */
|
|
15
|
+
function listsReload(task, bucket) {
|
|
16
|
+
task.result.then(() => { void (0, files_refresh_js_1.refreshBucketFiles)(bucket); }, () => { });
|
|
17
|
+
return task;
|
|
18
|
+
}
|
|
13
19
|
// --- Cloudflare image-transform URL helpers -------------------------------
|
|
14
20
|
// Module-private — callers use KoolbaseStorage.publicUrl / publicUrlForObject.
|
|
15
21
|
function clampInt(v, min, max) {
|
|
@@ -132,7 +138,7 @@ class KoolbaseStorage {
|
|
|
132
138
|
* const { object } = await task.result;
|
|
133
139
|
*/
|
|
134
140
|
startUpload(options) {
|
|
135
|
-
return (0, storage_transfer_js_1.runUploadTask)((task) => this.runUpload(options, task));
|
|
141
|
+
return listsReload((0, storage_transfer_js_1.runUploadTask)((task) => this.runUpload(options, task)), options.bucket);
|
|
136
142
|
}
|
|
137
143
|
async runUpload(options, task) {
|
|
138
144
|
task.checkCancelled();
|
|
@@ -242,14 +248,14 @@ class KoolbaseStorage {
|
|
|
242
248
|
* await Koolbase.storage.resumeUpload({ bucket: 'video', uploadId, file }).result;
|
|
243
249
|
*/
|
|
244
250
|
resumeUpload(options) {
|
|
245
|
-
return (0, storage_transfer_js_1.runUploadTask)(async (task) => {
|
|
251
|
+
return listsReload((0, storage_transfer_js_1.runUploadTask)(async (task) => {
|
|
246
252
|
const isBlob = typeof Blob !== 'undefined' && options.file instanceof Blob;
|
|
247
253
|
const blob = isBlob
|
|
248
254
|
? options.file
|
|
249
255
|
: await (await (0, network_js_1.sessionFetch)(options.file.uri)).blob();
|
|
250
256
|
task.setTotal(blob.size);
|
|
251
257
|
return this.runInParts(options.bucket, options, task, blob, '', options.uploadId);
|
|
252
|
-
});
|
|
258
|
+
}), options.bucket);
|
|
253
259
|
}
|
|
254
260
|
async runInParts(bucket, options, task, file, contentType, resumeId) {
|
|
255
261
|
const base = `${this.config.baseUrl}/v1/sdk/storage/uploads`;
|
|
@@ -466,7 +472,9 @@ class KoolbaseStorage {
|
|
|
466
472
|
if (!res.ok) {
|
|
467
473
|
throw await this.error(res, op === 'move' ? 'Failed to move the file' : 'Failed to copy the file');
|
|
468
474
|
}
|
|
469
|
-
|
|
475
|
+
const moved = mapObjectFromServer(await res.json());
|
|
476
|
+
void (0, files_refresh_js_1.refreshBucketFiles)(o.bucket, ...(o.toBucket && o.toBucket !== o.bucket ? [o.toBucket] : []));
|
|
477
|
+
return moved;
|
|
470
478
|
}
|
|
471
479
|
/**
|
|
472
480
|
* Apply a partial metadata update to an existing object. Returns the
|
|
@@ -514,6 +522,7 @@ class KoolbaseStorage {
|
|
|
514
522
|
throw await this.error(res, 'Failed to update metadata');
|
|
515
523
|
}
|
|
516
524
|
const raw = await res.json();
|
|
525
|
+
void (0, files_refresh_js_1.refreshBucketFiles)(bucket);
|
|
517
526
|
return mapObjectFromServer(raw);
|
|
518
527
|
}
|
|
519
528
|
/**
|
|
@@ -645,11 +654,11 @@ class KoolbaseStorage {
|
|
|
645
654
|
},
|
|
646
655
|
body: JSON.stringify({ bucket, path }),
|
|
647
656
|
});
|
|
648
|
-
if (res.
|
|
657
|
+
if (res.ok) {
|
|
658
|
+
void (0, files_refresh_js_1.refreshBucketFiles)(bucket);
|
|
649
659
|
return;
|
|
650
|
-
if (!res.ok) {
|
|
651
|
-
throw await this.error(res, 'Failed to delete file');
|
|
652
660
|
}
|
|
661
|
+
throw await this.error(res, 'Failed to delete file');
|
|
653
662
|
}
|
|
654
663
|
/**
|
|
655
664
|
* List all versions of a file path, newest-first. Returns a flat list
|
|
@@ -706,7 +715,9 @@ class KoolbaseStorage {
|
|
|
706
715
|
if (!res.ok) {
|
|
707
716
|
throw await this.error(res, 'Failed to restore version');
|
|
708
717
|
}
|
|
709
|
-
|
|
718
|
+
const restored = mapObjectFromServer(await res.json());
|
|
719
|
+
void (0, files_refresh_js_1.refreshBucketFiles)(bucket);
|
|
720
|
+
return restored;
|
|
710
721
|
}
|
|
711
722
|
/**
|
|
712
723
|
* Hard-remove a single history version — both the metadata row and
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import type { KoolbaseFileInfo } from './storage-files.js';
|
|
2
|
+
export type FileStatus = 'loading' | 'loaded' | 'notFound' | 'error';
|
|
3
|
+
export interface FileState {
|
|
4
|
+
readonly status: FileStatus;
|
|
5
|
+
/** The file's details, while status is 'loaded'. */
|
|
6
|
+
readonly file: KoolbaseFileInfo | null;
|
|
7
|
+
/** Why the first load failed, while status is 'error'. */
|
|
8
|
+
readonly error: unknown;
|
|
9
|
+
/** True while refresh() runs. */
|
|
10
|
+
readonly refreshing: boolean;
|
|
11
|
+
}
|
|
12
|
+
export declare const initialFileState: FileState;
|
|
13
|
+
type FileReader = {
|
|
14
|
+
getFileInfo(bucket: string, path: string): Promise<KoolbaseFileInfo>;
|
|
15
|
+
};
|
|
16
|
+
export declare class KoolbaseFileController {
|
|
17
|
+
readonly bucket: string;
|
|
18
|
+
readonly path: string;
|
|
19
|
+
private readonly storage;
|
|
20
|
+
private state;
|
|
21
|
+
private readonly listeners;
|
|
22
|
+
private generation;
|
|
23
|
+
private disposed;
|
|
24
|
+
private unregister;
|
|
25
|
+
constructor(storage: FileReader, bucket: string, path: string);
|
|
26
|
+
getState(): FileState;
|
|
27
|
+
/** Called on every change. Returns the unsubscribe. */
|
|
28
|
+
subscribe(listener: () => void): () => void;
|
|
29
|
+
/** The first load. Call once; refresh() for later loads. */
|
|
30
|
+
load(): Promise<void>;
|
|
31
|
+
/** Read it again. The file stays shown while it runs, and stays if it fails. */
|
|
32
|
+
refresh(): Promise<void>;
|
|
33
|
+
/** Stops all updates. Results still in flight are dropped when they land. */
|
|
34
|
+
dispose(): void;
|
|
35
|
+
private run;
|
|
36
|
+
private isStale;
|
|
37
|
+
private set;
|
|
38
|
+
}
|
|
39
|
+
export {};
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
// One file's details, by path, framework-free (storage S4).
|
|
2
|
+
//
|
|
3
|
+
// The data half of a file detail screen: loading, loaded, not found or
|
|
4
|
+
// error, and refresh. No React here, so it is tested in this package; useFile
|
|
5
|
+
// in @koolbase/react-native and @koolbase/js/react is a thin wrapper.
|
|
6
|
+
// Mirrors the Flutter SDK's KoolbaseFileController, with the record view's
|
|
7
|
+
// rules:
|
|
8
|
+
//
|
|
9
|
+
// - an empty path is not found, with no request
|
|
10
|
+
// - not found is not an error: the API answers a file you may not view as
|
|
11
|
+
// not found too, so a detail screen says "not available"
|
|
12
|
+
// - stale beats blank: a failed refresh keeps the file shown
|
|
13
|
+
// - a change made through this SDK in the bucket (an upload, a delete, a
|
|
14
|
+
// move, a metadata change, a restore) reads it again silently: deleted or
|
|
15
|
+
// moved away, the file is not found; replaced, it shows its new size
|
|
16
|
+
// - a result a later load superseded, or one landing after dispose(), is
|
|
17
|
+
// dropped
|
|
18
|
+
import { registerFilesRefresher } from './files-refresh.js';
|
|
19
|
+
import { KoolbaseStorageNotFoundError } from './storage-errors.js';
|
|
20
|
+
export const initialFileState = Object.freeze({
|
|
21
|
+
status: 'loading',
|
|
22
|
+
file: null,
|
|
23
|
+
error: null,
|
|
24
|
+
refreshing: false,
|
|
25
|
+
});
|
|
26
|
+
/** Whether [e] says there is no such file (or none this caller may view). */
|
|
27
|
+
function isNotFound(e) {
|
|
28
|
+
return e instanceof KoolbaseStorageNotFoundError || e?.code === 'not_found';
|
|
29
|
+
}
|
|
30
|
+
export class KoolbaseFileController {
|
|
31
|
+
constructor(storage, bucket, path) {
|
|
32
|
+
this.state = initialFileState;
|
|
33
|
+
this.listeners = new Set();
|
|
34
|
+
this.generation = 0;
|
|
35
|
+
this.disposed = false;
|
|
36
|
+
this.unregister = null;
|
|
37
|
+
this.storage = storage;
|
|
38
|
+
this.bucket = bucket;
|
|
39
|
+
this.path = path;
|
|
40
|
+
}
|
|
41
|
+
getState() {
|
|
42
|
+
return this.state;
|
|
43
|
+
}
|
|
44
|
+
/** Called on every change. Returns the unsubscribe. */
|
|
45
|
+
subscribe(listener) {
|
|
46
|
+
if (this.disposed)
|
|
47
|
+
return () => { };
|
|
48
|
+
this.listeners.add(listener);
|
|
49
|
+
return () => {
|
|
50
|
+
this.listeners.delete(listener);
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
/** The first load. Call once; refresh() for later loads. */
|
|
54
|
+
async load() {
|
|
55
|
+
if (this.disposed)
|
|
56
|
+
return;
|
|
57
|
+
if (this.path)
|
|
58
|
+
this.unregister ?? (this.unregister = registerFilesRefresher(this.bucket, () => this.run()));
|
|
59
|
+
await this.run();
|
|
60
|
+
}
|
|
61
|
+
/** Read it again. The file stays shown while it runs, and stays if it fails. */
|
|
62
|
+
async refresh() {
|
|
63
|
+
if (this.disposed)
|
|
64
|
+
return;
|
|
65
|
+
this.set({ refreshing: true });
|
|
66
|
+
await this.run();
|
|
67
|
+
}
|
|
68
|
+
/** Stops all updates. Results still in flight are dropped when they land. */
|
|
69
|
+
dispose() {
|
|
70
|
+
this.disposed = true;
|
|
71
|
+
this.unregister?.();
|
|
72
|
+
this.unregister = null;
|
|
73
|
+
this.listeners.clear();
|
|
74
|
+
}
|
|
75
|
+
async run() {
|
|
76
|
+
if (this.disposed)
|
|
77
|
+
return;
|
|
78
|
+
const gen = ++this.generation;
|
|
79
|
+
if (!this.path) {
|
|
80
|
+
this.set({ status: 'notFound', file: null, error: null, refreshing: false });
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
try {
|
|
84
|
+
const file = await this.storage.getFileInfo(this.bucket, this.path);
|
|
85
|
+
if (this.isStale(gen))
|
|
86
|
+
return;
|
|
87
|
+
this.set({ status: 'loaded', file, error: null, refreshing: false });
|
|
88
|
+
}
|
|
89
|
+
catch (e) {
|
|
90
|
+
if (this.isStale(gen))
|
|
91
|
+
return;
|
|
92
|
+
if (isNotFound(e))
|
|
93
|
+
this.set({ status: 'notFound', file: null, error: null, refreshing: false });
|
|
94
|
+
// Only a first load with nothing to show is the error state.
|
|
95
|
+
else if (this.state.file === null)
|
|
96
|
+
this.set({ status: 'error', file: null, error: e, refreshing: false });
|
|
97
|
+
else
|
|
98
|
+
this.set({ refreshing: false });
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
isStale(gen) {
|
|
102
|
+
return this.disposed || gen !== this.generation;
|
|
103
|
+
}
|
|
104
|
+
set(change) {
|
|
105
|
+
if (this.disposed)
|
|
106
|
+
return;
|
|
107
|
+
this.state = Object.freeze({ ...this.state, ...change });
|
|
108
|
+
for (const l of [...this.listeners])
|
|
109
|
+
l();
|
|
110
|
+
}
|
|
111
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import type { KoolbaseFileInfo, KoolbaseFilePage, KoolbaseFileSort, ListFilesOptions } from './storage-files.js';
|
|
2
|
+
export type FilesStatus = 'loading' | 'loaded' | 'error';
|
|
3
|
+
/** Which files, in what order. The bucket's view rule decides the rest. */
|
|
4
|
+
export interface FilesQuery {
|
|
5
|
+
/** Only files whose path starts with this, taken literally. */
|
|
6
|
+
prefix?: string;
|
|
7
|
+
/** By path unless set. */
|
|
8
|
+
sort?: KoolbaseFileSort;
|
|
9
|
+
/** Z to A, newest first, largest first. */
|
|
10
|
+
descending?: boolean;
|
|
11
|
+
/** Files per page: 50 unless set, at most 100. */
|
|
12
|
+
limit?: number;
|
|
13
|
+
}
|
|
14
|
+
export interface FilesState {
|
|
15
|
+
readonly status: FilesStatus;
|
|
16
|
+
readonly files: readonly KoolbaseFileInfo[];
|
|
17
|
+
/** Why the first load failed, while status is 'error'. */
|
|
18
|
+
readonly error: unknown;
|
|
19
|
+
/** True while refresh() runs. */
|
|
20
|
+
readonly refreshing: boolean;
|
|
21
|
+
/** True while loadMore() runs. */
|
|
22
|
+
readonly loadingMore: boolean;
|
|
23
|
+
/** Whether there is a page past the last one loaded. True before the first load. */
|
|
24
|
+
readonly hasMore: boolean;
|
|
25
|
+
}
|
|
26
|
+
export declare const initialFilesState: FilesState;
|
|
27
|
+
/** One string per distinct listing. */
|
|
28
|
+
export declare function filesQueryKey(bucket: string, query?: FilesQuery): string;
|
|
29
|
+
type FilesReader = {
|
|
30
|
+
listFiles(options: ListFilesOptions): Promise<KoolbaseFilePage>;
|
|
31
|
+
};
|
|
32
|
+
export declare class KoolbaseFilesController {
|
|
33
|
+
readonly bucket: string;
|
|
34
|
+
private readonly storage;
|
|
35
|
+
private readonly spec;
|
|
36
|
+
private state;
|
|
37
|
+
private readonly listeners;
|
|
38
|
+
private generation;
|
|
39
|
+
private disposed;
|
|
40
|
+
private pageOne;
|
|
41
|
+
private laterPages;
|
|
42
|
+
private cursor;
|
|
43
|
+
private unregister;
|
|
44
|
+
constructor(storage: FilesReader, bucket: string, query?: FilesQuery);
|
|
45
|
+
getState(): FilesState;
|
|
46
|
+
/** Called on every change. Returns the unsubscribe. */
|
|
47
|
+
subscribe(listener: () => void): () => void;
|
|
48
|
+
/** The first load. Call once; refresh() for later loads. */
|
|
49
|
+
load(): Promise<void>;
|
|
50
|
+
/** Page one again. What is shown stays while it runs, and stays if it fails. */
|
|
51
|
+
refresh(): Promise<void>;
|
|
52
|
+
/** The next page, appended. Does nothing unless loaded with a page to come. */
|
|
53
|
+
loadMore(): Promise<void>;
|
|
54
|
+
/** Stops all updates. Results still in flight are dropped when they land. */
|
|
55
|
+
dispose(): void;
|
|
56
|
+
private firstPage;
|
|
57
|
+
private publish;
|
|
58
|
+
private options;
|
|
59
|
+
private isStale;
|
|
60
|
+
private set;
|
|
61
|
+
}
|
|
62
|
+
export {};
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
// A bucket's files read as a list, framework-free (storage S4).
|
|
2
|
+
//
|
|
3
|
+
// The data half of a file gallery: loading, loaded or error, refresh, and
|
|
4
|
+
// the next page by cursor. No React here, so it is tested in this package;
|
|
5
|
+
// useFiles in @koolbase/react-native and @koolbase/js/react is a thin
|
|
6
|
+
// wrapper. Mirrors the Flutter SDK's KoolbaseFilesController.
|
|
7
|
+
//
|
|
8
|
+
// - only a first load with nothing to show is the error state; a failed
|
|
9
|
+
// refresh or loadMore keeps what is shown (stale beats blank)
|
|
10
|
+
// - loadMore appends the next page while there is one; a file already
|
|
11
|
+
// shown is never shown twice (matched by path)
|
|
12
|
+
// - an upload, delete, move, copy, metadata change or restore made through
|
|
13
|
+
// this SDK in the bucket reloads page one silently (files-refresh.ts)
|
|
14
|
+
// - every fetch belongs to a generation: a result from a fetch a later
|
|
15
|
+
// refresh superseded, or one landing after dispose(), is dropped
|
|
16
|
+
import { registerFilesRefresher } from './files-refresh.js';
|
|
17
|
+
export const initialFilesState = Object.freeze({
|
|
18
|
+
status: 'loading',
|
|
19
|
+
files: Object.freeze([]),
|
|
20
|
+
error: null,
|
|
21
|
+
refreshing: false,
|
|
22
|
+
loadingMore: false,
|
|
23
|
+
hasMore: true,
|
|
24
|
+
});
|
|
25
|
+
/** One string per distinct listing. */
|
|
26
|
+
export function filesQueryKey(bucket, query = {}) {
|
|
27
|
+
return JSON.stringify([bucket, query.prefix ?? '', query.sort ?? 'path', query.descending === true, query.limit ?? null]);
|
|
28
|
+
}
|
|
29
|
+
/** Page one, then the later pages without any file already shown. */
|
|
30
|
+
function mergeByPath(first, rest) {
|
|
31
|
+
const seen = new Set(first.map((f) => f.path));
|
|
32
|
+
const out = [...first];
|
|
33
|
+
for (const f of rest) {
|
|
34
|
+
if (seen.has(f.path))
|
|
35
|
+
continue;
|
|
36
|
+
seen.add(f.path);
|
|
37
|
+
out.push(f);
|
|
38
|
+
}
|
|
39
|
+
return out;
|
|
40
|
+
}
|
|
41
|
+
export class KoolbaseFilesController {
|
|
42
|
+
constructor(storage, bucket, query = {}) {
|
|
43
|
+
this.state = initialFilesState;
|
|
44
|
+
this.listeners = new Set();
|
|
45
|
+
this.generation = 0;
|
|
46
|
+
this.disposed = false;
|
|
47
|
+
this.pageOne = [];
|
|
48
|
+
this.laterPages = [];
|
|
49
|
+
this.cursor = null;
|
|
50
|
+
this.unregister = null;
|
|
51
|
+
this.storage = storage;
|
|
52
|
+
this.bucket = bucket;
|
|
53
|
+
this.spec = query;
|
|
54
|
+
}
|
|
55
|
+
getState() {
|
|
56
|
+
return this.state;
|
|
57
|
+
}
|
|
58
|
+
/** Called on every change. Returns the unsubscribe. */
|
|
59
|
+
subscribe(listener) {
|
|
60
|
+
if (this.disposed)
|
|
61
|
+
return () => { };
|
|
62
|
+
this.listeners.add(listener);
|
|
63
|
+
return () => {
|
|
64
|
+
this.listeners.delete(listener);
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
/** The first load. Call once; refresh() for later loads. */
|
|
68
|
+
async load() {
|
|
69
|
+
if (this.disposed)
|
|
70
|
+
return;
|
|
71
|
+
this.unregister ?? (this.unregister = registerFilesRefresher(this.bucket, () => this.firstPage()));
|
|
72
|
+
await this.firstPage();
|
|
73
|
+
}
|
|
74
|
+
/** Page one again. What is shown stays while it runs, and stays if it fails. */
|
|
75
|
+
async refresh() {
|
|
76
|
+
if (this.disposed)
|
|
77
|
+
return;
|
|
78
|
+
this.set({ refreshing: true });
|
|
79
|
+
await this.firstPage();
|
|
80
|
+
}
|
|
81
|
+
/** The next page, appended. Does nothing unless loaded with a page to come. */
|
|
82
|
+
async loadMore() {
|
|
83
|
+
const s = this.state;
|
|
84
|
+
if (this.disposed || s.loadingMore || !s.hasMore || s.status !== 'loaded' || this.cursor === null)
|
|
85
|
+
return;
|
|
86
|
+
const gen = this.generation;
|
|
87
|
+
this.set({ loadingMore: true });
|
|
88
|
+
try {
|
|
89
|
+
const page = await this.storage.listFiles(this.options(this.cursor));
|
|
90
|
+
if (this.isStale(gen))
|
|
91
|
+
return;
|
|
92
|
+
this.laterPages = [...this.laterPages, ...page.files];
|
|
93
|
+
this.cursor = page.nextCursor;
|
|
94
|
+
this.publish({});
|
|
95
|
+
}
|
|
96
|
+
catch {
|
|
97
|
+
// Keep what is shown; the caller can try again.
|
|
98
|
+
}
|
|
99
|
+
finally {
|
|
100
|
+
if (!this.isStale(gen))
|
|
101
|
+
this.set({ loadingMore: false });
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
/** Stops all updates. Results still in flight are dropped when they land. */
|
|
105
|
+
dispose() {
|
|
106
|
+
this.disposed = true;
|
|
107
|
+
this.unregister?.();
|
|
108
|
+
this.unregister = null;
|
|
109
|
+
this.listeners.clear();
|
|
110
|
+
}
|
|
111
|
+
async firstPage() {
|
|
112
|
+
const gen = ++this.generation;
|
|
113
|
+
if (this.state.loadingMore)
|
|
114
|
+
this.set({ loadingMore: false });
|
|
115
|
+
try {
|
|
116
|
+
const page = await this.storage.listFiles(this.options(undefined));
|
|
117
|
+
if (!this.isStale(gen)) {
|
|
118
|
+
this.pageOne = page.files;
|
|
119
|
+
this.laterPages = [];
|
|
120
|
+
this.cursor = page.nextCursor;
|
|
121
|
+
this.publish({ status: 'loaded', error: null, refreshing: false });
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
catch (error) {
|
|
125
|
+
// Only a first load with nothing to show is the error state. Whichever
|
|
126
|
+
// fetch is newest ends a refresh, a silent one included.
|
|
127
|
+
if (!this.isStale(gen)) {
|
|
128
|
+
this.set(this.state.files.length === 0 ? { status: 'error', error, refreshing: false } : { refreshing: false });
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
publish(patch) {
|
|
133
|
+
this.set({ ...patch, files: mergeByPath(this.pageOne, this.laterPages), hasMore: this.cursor !== null });
|
|
134
|
+
}
|
|
135
|
+
options(cursor) {
|
|
136
|
+
return {
|
|
137
|
+
bucket: this.bucket,
|
|
138
|
+
...(this.spec.prefix ? { prefix: this.spec.prefix } : {}),
|
|
139
|
+
...(this.spec.limit != null ? { limit: this.spec.limit } : {}),
|
|
140
|
+
...(this.spec.sort ? { sort: this.spec.sort } : {}),
|
|
141
|
+
...(this.spec.descending ? { descending: true } : {}),
|
|
142
|
+
...(cursor ? { cursor } : {}),
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
isStale(gen) {
|
|
146
|
+
return this.disposed || gen !== this.generation;
|
|
147
|
+
}
|
|
148
|
+
set(patch) {
|
|
149
|
+
if (this.disposed)
|
|
150
|
+
return;
|
|
151
|
+
this.state = Object.freeze({ ...this.state, ...patch });
|
|
152
|
+
for (const listener of [...this.listeners])
|
|
153
|
+
listener();
|
|
154
|
+
}
|
|
155
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/** Registers one file list's reload; returns the unregister. */
|
|
2
|
+
export declare function registerFilesRefresher(bucket: string, refresh: () => Promise<void>): () => void;
|
|
3
|
+
/**
|
|
4
|
+
* Reloads every file list on [buckets]. One after another; a failure in one
|
|
5
|
+
* never stops the others, and never reaches the change that caused it.
|
|
6
|
+
*/
|
|
7
|
+
export declare function refreshBucketFiles(...buckets: string[]): Promise<void>;
|
|
8
|
+
/** Tests only. */
|
|
9
|
+
export declare function clearFilesRefreshers(): void;
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
// File lists reloaded after a change made through this SDK (storage S4): an
|
|
2
|
+
// upload, a delete, a move or copy, a metadata change, a restore. Keyed by
|
|
3
|
+
// bucket; each list reloads ITSELF, with its own prefix and order.
|
|
4
|
+
const refreshers = new Map();
|
|
5
|
+
let next = 0;
|
|
6
|
+
/** Registers one file list's reload; returns the unregister. */
|
|
7
|
+
export function registerFilesRefresher(bucket, refresh) {
|
|
8
|
+
const key = `${bucket}\u0000${++next}`;
|
|
9
|
+
refreshers.set(key, refresh);
|
|
10
|
+
return () => {
|
|
11
|
+
refreshers.delete(key);
|
|
12
|
+
};
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Reloads every file list on [buckets]. One after another; a failure in one
|
|
16
|
+
* never stops the others, and never reaches the change that caused it.
|
|
17
|
+
*/
|
|
18
|
+
export async function refreshBucketFiles(...buckets) {
|
|
19
|
+
const prefixes = buckets.map((b) => `${b}\u0000`);
|
|
20
|
+
const due = [...refreshers.entries()].filter(([k]) => prefixes.some((p) => k.startsWith(p))).map(([, f]) => f);
|
|
21
|
+
for (const refresh of due) {
|
|
22
|
+
try {
|
|
23
|
+
await refresh();
|
|
24
|
+
}
|
|
25
|
+
catch (e) {
|
|
26
|
+
// eslint-disable-next-line no-console
|
|
27
|
+
console.warn('[Koolbase] A file list failed to reload after a change:', e);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
/** Tests only. */
|
|
32
|
+
export function clearFilesRefreshers() {
|
|
33
|
+
refreshers.clear();
|
|
34
|
+
}
|
package/dist/esm/index.d.ts
CHANGED
|
@@ -23,6 +23,10 @@ export { KoolbaseStorage } from './storage.js';
|
|
|
23
23
|
export { KoolbaseUploadTask } from './storage-transfer.js';
|
|
24
24
|
export type { KoolbaseUploadProgress, KoolbaseUploadState } from './storage-transfer.js';
|
|
25
25
|
export type { KoolbaseFileInfo, KoolbaseFilePage, KoolbaseFileSort, ListFilesOptions } from './storage-files.js';
|
|
26
|
+
export { KoolbaseFilesController, initialFilesState, filesQueryKey } from './files-controller.js';
|
|
27
|
+
export type { FilesQuery, FilesState, FilesStatus } from './files-controller.js';
|
|
28
|
+
export { KoolbaseFileController, initialFileState } from './file-controller.js';
|
|
29
|
+
export type { FileState, FileStatus } from './file-controller.js';
|
|
26
30
|
export { KoolbaseAnalytics, disabledAnalytics } from './analytics.js';
|
|
27
31
|
export { KoolbaseFiscal, KoolbaseFiscalError, decodeFiscalResponse, isFiscalized, isPending } from './fiscal.js';
|
|
28
32
|
export type { FiscalIntentResult, FiscalStatus } from './fiscal.js';
|
package/dist/esm/index.js
CHANGED
|
@@ -23,6 +23,10 @@ export { KoolbaseRealtime } from './realtime.js';
|
|
|
23
23
|
export { KoolbaseConnectivity } from './connectivity.js';
|
|
24
24
|
export { KoolbaseStorage } from './storage.js';
|
|
25
25
|
export { KoolbaseUploadTask } from './storage-transfer.js';
|
|
26
|
+
// A bucket's files as list state (storage S4).
|
|
27
|
+
export { KoolbaseFilesController, initialFilesState, filesQueryKey } from './files-controller.js';
|
|
28
|
+
// One file's details as state (storage S4).
|
|
29
|
+
export { KoolbaseFileController, initialFileState } from './file-controller.js';
|
|
26
30
|
export { KoolbaseAnalytics, disabledAnalytics } from './analytics.js';
|
|
27
31
|
export { KoolbaseFiscal, KoolbaseFiscalError, decodeFiscalResponse, isFiscalized, isPending } from './fiscal.js';
|
|
28
32
|
export { KoolbaseMessaging } from './messaging.js';
|
|
@@ -1,2 +1,4 @@
|
|
|
1
1
|
export { createUseCollection, type UseCollectionResult } from './use-collection.js';
|
|
2
2
|
export { createUseRecord, type UseRecordResult } from './use-record.js';
|
|
3
|
+
export { createUseFiles, type UseFilesResult } from './use-files.js';
|
|
4
|
+
export { createUseFile, type UseFileResult } from './use-file.js';
|
package/dist/esm/react/index.js
CHANGED
|
@@ -4,3 +4,5 @@
|
|
|
4
4
|
// core's root entry, so importing @koolbase/core never loads React.
|
|
5
5
|
export { createUseCollection } from './use-collection.js';
|
|
6
6
|
export { createUseRecord } from './use-record.js';
|
|
7
|
+
export { createUseFiles } from './use-files.js';
|
|
8
|
+
export { createUseFile } from './use-file.js';
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { type FileState, type KoolbaseStorage } from '../index.js';
|
|
2
|
+
export interface UseFileResult extends FileState {
|
|
3
|
+
/** Read it again. The file stays shown while it runs, and stays if it fails. */
|
|
4
|
+
refresh: () => Promise<void>;
|
|
5
|
+
}
|
|
6
|
+
export declare function createUseFile(getStorage: () => Pick<KoolbaseStorage, 'getFileInfo'>): (bucket: string, path: string | null | undefined) => UseFileResult;
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
// useFile: one file's details as React state (storage S4).
|
|
2
|
+
//
|
|
3
|
+
// A thin wrapper. Everything about getting the file right lives in
|
|
4
|
+
// @koolbase/core's KoolbaseFileController, which is tested there; this file
|
|
5
|
+
// only ties one controller's lifetime to a component's.
|
|
6
|
+
import { useCallback, useEffect, useState, useSyncExternalStore } from 'react';
|
|
7
|
+
import { KoolbaseFileController, initialFileState } from '../index.js';
|
|
8
|
+
const noop = () => { };
|
|
9
|
+
const done = () => Promise.resolve();
|
|
10
|
+
export function createUseFile(getStorage) {
|
|
11
|
+
return function useFile(bucket, path) {
|
|
12
|
+
const p = path ?? '';
|
|
13
|
+
const key = JSON.stringify([bucket, p]);
|
|
14
|
+
const [current, setCurrent] = useState(null);
|
|
15
|
+
useEffect(() => {
|
|
16
|
+
// Created here, not during render, so React strict mode's second run
|
|
17
|
+
// never keeps a disposed controller.
|
|
18
|
+
const controller = new KoolbaseFileController(getStorage(), bucket, p);
|
|
19
|
+
setCurrent({ key, controller });
|
|
20
|
+
void controller.load();
|
|
21
|
+
return () => controller.dispose();
|
|
22
|
+
}, [key]);
|
|
23
|
+
// A controller from the previous file reads as a fresh load, never as
|
|
24
|
+
// the previous file.
|
|
25
|
+
const controller = current?.key === key ? current.controller : null;
|
|
26
|
+
const subscribe = useCallback((onChange) => (controller ? controller.subscribe(onChange) : noop), [controller]);
|
|
27
|
+
const getSnapshot = useCallback(() => (controller ? controller.getState() : initialFileState), [controller]);
|
|
28
|
+
const state = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
|
|
29
|
+
const refresh = useCallback(() => (controller ? controller.refresh() : done()), [controller]);
|
|
30
|
+
return { ...state, refresh };
|
|
31
|
+
};
|
|
32
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { type FilesQuery, type FilesState, type KoolbaseStorage } from '../index.js';
|
|
2
|
+
export interface UseFilesResult extends FilesState {
|
|
3
|
+
/** Page one again. What is shown stays while it runs, and stays if it fails. */
|
|
4
|
+
refresh: () => Promise<void>;
|
|
5
|
+
/** The next page, appended, while hasMore. */
|
|
6
|
+
loadMore: () => Promise<void>;
|
|
7
|
+
}
|
|
8
|
+
export declare function createUseFiles(getStorage: () => Pick<KoolbaseStorage, 'listFiles'>): (bucket: string, query?: FilesQuery) => UseFilesResult;
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
// useFiles: a bucket's files as React state (storage S4).
|
|
2
|
+
//
|
|
3
|
+
// A thin wrapper. Everything about getting the files right lives in
|
|
4
|
+
// @koolbase/core's KoolbaseFilesController, which is tested there; this
|
|
5
|
+
// file only ties one controller's lifetime to a component's.
|
|
6
|
+
import { useCallback, useEffect, useState, useSyncExternalStore } from 'react';
|
|
7
|
+
import { KoolbaseFilesController, filesQueryKey, initialFilesState, } from '../index.js';
|
|
8
|
+
const noop = () => { };
|
|
9
|
+
const done = () => Promise.resolve();
|
|
10
|
+
export function createUseFiles(getStorage) {
|
|
11
|
+
return function useFiles(bucket, query = {}) {
|
|
12
|
+
// The query as a value: an inline object is a new object every render,
|
|
13
|
+
// and must not start a new fetch every render.
|
|
14
|
+
const key = filesQueryKey(bucket, query);
|
|
15
|
+
const [current, setCurrent] = useState(null);
|
|
16
|
+
useEffect(() => {
|
|
17
|
+
// Created here, not during render, so React strict mode's second run
|
|
18
|
+
// never keeps a disposed controller.
|
|
19
|
+
const controller = new KoolbaseFilesController(getStorage(), bucket, query);
|
|
20
|
+
setCurrent({ key, controller });
|
|
21
|
+
void controller.load();
|
|
22
|
+
return () => controller.dispose();
|
|
23
|
+
}, [key]);
|
|
24
|
+
// A controller from the previous key reads as a fresh load, never as
|
|
25
|
+
// the previous listing's files.
|
|
26
|
+
const controller = current?.key === key ? current.controller : null;
|
|
27
|
+
const subscribe = useCallback((onChange) => (controller ? controller.subscribe(onChange) : noop), [controller]);
|
|
28
|
+
const getSnapshot = useCallback(() => (controller ? controller.getState() : initialFilesState), [controller]);
|
|
29
|
+
const state = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
|
|
30
|
+
const refresh = useCallback(() => (controller ? controller.refresh() : done()), [controller]);
|
|
31
|
+
const loadMore = useCallback(() => (controller ? controller.loadMore() : done()), [controller]);
|
|
32
|
+
return { ...state, refresh, loadMore };
|
|
33
|
+
};
|
|
34
|
+
}
|