@vite-hub/device 0.0.0-claim → 0.3.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/LICENSE +201 -0
- package/README.md +118 -1
- package/dist/device-CxuDKYfP.js +686 -0
- package/dist/index.d.ts +56 -0
- package/dist/index.js +43 -0
- package/dist/vue.d.ts +78 -0
- package/dist/vue.js +282 -0
- package/package.json +67 -4
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { Result } from "@vite-hub/runtime";
|
|
2
|
+
//#region src/device.d.ts
|
|
3
|
+
/** What `inspectDevice()` returns. */
|
|
4
|
+
interface DeviceInspection {
|
|
5
|
+
/**
|
|
6
|
+
* The account that the stored copies belong to: the account that this page named with `setDeviceAccount()`, or before
|
|
7
|
+
* that, the account of the copies from the last visit. `null` when there is none.
|
|
8
|
+
*/
|
|
9
|
+
account: string | null;
|
|
10
|
+
/** `true` when new copies go to IndexedDB and survive a reload. */
|
|
11
|
+
persisted: boolean;
|
|
12
|
+
/** `indexeddb`, or `memory` when the browser has no working IndexedDB, or before `openDevice()`. */
|
|
13
|
+
storage: "indexeddb" | "memory";
|
|
14
|
+
/** Each stored copy, by key. */
|
|
15
|
+
entries: {
|
|
16
|
+
key: string;
|
|
17
|
+
storedAt: Date;
|
|
18
|
+
bytes: number;
|
|
19
|
+
}[];
|
|
20
|
+
}
|
|
21
|
+
interface OpenDeviceOptions {
|
|
22
|
+
/**
|
|
23
|
+
* The version of the stored data. When it is not the version of the stored copies, the device deletes them, so a new
|
|
24
|
+
* build does not show answers of an old shape. Use a build id, or a number that you change with the shape of the data.
|
|
25
|
+
*/
|
|
26
|
+
version?: string;
|
|
27
|
+
}
|
|
28
|
+
//#endregion
|
|
29
|
+
//#region src/index.d.ts
|
|
30
|
+
/**
|
|
31
|
+
* Reads the stored copies into memory, so the first render of `useStoredData()` shows them at once. Await it before
|
|
32
|
+
* `app.mount()`. It never fails: without IndexedDB, or when IndexedDB takes more than 1 second, the page keeps its
|
|
33
|
+
* copies in memory and `inspectDevice()` says `storage: "memory"`. On the server, it does nothing.
|
|
34
|
+
*
|
|
35
|
+
* ```ts
|
|
36
|
+
* import { openDevice } from 'vite-hub/device'
|
|
37
|
+
*
|
|
38
|
+
* await openDevice({ version: '2' })
|
|
39
|
+
* app.mount('#app')
|
|
40
|
+
* ```
|
|
41
|
+
*/
|
|
42
|
+
export declare function openDevice(options?: OpenDeviceOptions): Promise<void>;
|
|
43
|
+
/**
|
|
44
|
+
* Names the signed-in account, so its copies stay on the device across reloads. Call it each time the app learns who
|
|
45
|
+
* is signed in. Another account, or `null` after a sign-out, deletes every copy in every tab. The device stores only the
|
|
46
|
+
* answers of loader calls that start after the page names an account, so each read that runs calls its loader again.
|
|
47
|
+
* After `openDevice()`, the page names the account at once: a read that starts right after the call can be stored. The
|
|
48
|
+
* promise resolves when the disk follows, so a page does not need to wait for it before its reads.
|
|
49
|
+
*/
|
|
50
|
+
export declare function setDeviceAccount(account: string | null): Promise<Result<void, "DEVICE_STORAGE_FAILED">>;
|
|
51
|
+
/** Deletes every stored copy, in this tab and in every other tab of the app. The account stays. */
|
|
52
|
+
export declare function clearDevice(): Promise<Result<void, "DEVICE_STORAGE_FAILED">>;
|
|
53
|
+
/** The account, the storage, and each stored copy of this tab, to debug stored reads in code or in the browser console. */
|
|
54
|
+
export declare function inspectDevice(): DeviceInspection;
|
|
55
|
+
//#endregion
|
|
56
|
+
export type { DeviceInspection, OpenDeviceOptions };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { i as currentDevice, t as checkAccount } from "./device-CxuDKYfP.js";
|
|
2
|
+
//#region src/index.ts
|
|
3
|
+
/**
|
|
4
|
+
* Reads the stored copies into memory, so the first render of `useStoredData()` shows them at once. Await it before
|
|
5
|
+
* `app.mount()`. It never fails: without IndexedDB, or when IndexedDB takes more than 1 second, the page keeps its
|
|
6
|
+
* copies in memory and `inspectDevice()` says `storage: "memory"`. On the server, it does nothing.
|
|
7
|
+
*
|
|
8
|
+
* ```ts
|
|
9
|
+
* import { openDevice } from 'vite-hub/device'
|
|
10
|
+
*
|
|
11
|
+
* await openDevice({ version: '2' })
|
|
12
|
+
* app.mount('#app')
|
|
13
|
+
* ```
|
|
14
|
+
*/
|
|
15
|
+
function openDevice(options) {
|
|
16
|
+
return currentDevice()?.open(options) ?? Promise.resolve();
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Names the signed-in account, so its copies stay on the device across reloads. Call it each time the app learns who
|
|
20
|
+
* is signed in. Another account, or `null` after a sign-out, deletes every copy in every tab. The device stores only the
|
|
21
|
+
* answers of loader calls that start after the page names an account, so each read that runs calls its loader again.
|
|
22
|
+
* After `openDevice()`, the page names the account at once: a read that starts right after the call can be stored. The
|
|
23
|
+
* promise resolves when the disk follows, so a page does not need to wait for it before its reads.
|
|
24
|
+
*/
|
|
25
|
+
function setDeviceAccount(account) {
|
|
26
|
+
checkAccount(account);
|
|
27
|
+
return currentDevice()?.setAccount(account) ?? Promise.resolve([void 0, void 0]);
|
|
28
|
+
}
|
|
29
|
+
/** Deletes every stored copy, in this tab and in every other tab of the app. The account stays. */
|
|
30
|
+
function clearDevice() {
|
|
31
|
+
return currentDevice()?.clear() ?? Promise.resolve([void 0, void 0]);
|
|
32
|
+
}
|
|
33
|
+
/** The account, the storage, and each stored copy of this tab, to debug stored reads in code or in the browser console. */
|
|
34
|
+
function inspectDevice() {
|
|
35
|
+
return currentDevice()?.inspect() ?? {
|
|
36
|
+
account: null,
|
|
37
|
+
persisted: false,
|
|
38
|
+
storage: "memory",
|
|
39
|
+
entries: []
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
//#endregion
|
|
43
|
+
export { clearDevice, inspectDevice, openDevice, setDeviceAccount };
|
package/dist/vue.d.ts
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { MaybeRefOrGetter, Ref } from "vue";
|
|
2
|
+
//#region src/vue.d.ts
|
|
3
|
+
/** `idle` on the server and before the loader starts, `pending` while the loader runs, then `success` or `error`. */
|
|
4
|
+
export type StoredDataStatus = "idle" | "pending" | "success" | "error";
|
|
5
|
+
export interface UseStoredDataOptions<TData, TDefault> {
|
|
6
|
+
/** The value before the first answer, when the device has no copy. */
|
|
7
|
+
default?: () => TDefault;
|
|
8
|
+
/** The age in milliseconds after which a stored copy does not show. 7 days by default. */
|
|
9
|
+
maxAge?: number;
|
|
10
|
+
/**
|
|
11
|
+
* The account that an answer belongs to, or `null` when nobody is signed in. Give it to the read that says who is
|
|
12
|
+
* signed in, such as `/api/session`: each answer names its account, as `setDeviceAccount()` does, and is stored under
|
|
13
|
+
* it. A stored copy and a failed call name nothing.
|
|
14
|
+
*/
|
|
15
|
+
account?: (value: TData) => string | null;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* What the loader gets. `signal` aborts when a newer call starts, when the last component of the read unmounts or
|
|
19
|
+
* moves to another key, when another account, a sign-out, or a clear makes the answer old, and when the page names its
|
|
20
|
+
* account, because the device stores only the answers of calls that start after that.
|
|
21
|
+
*/
|
|
22
|
+
export interface StoredDataContext {
|
|
23
|
+
signal: AbortSignal;
|
|
24
|
+
}
|
|
25
|
+
export interface UseStoredDataReturn<TData, TDefault> {
|
|
26
|
+
/** The stored copy, then the answer of the loader. Before both, the default. */
|
|
27
|
+
data: Ref<TData | TDefault>;
|
|
28
|
+
status: Readonly<Ref<StoredDataStatus>>;
|
|
29
|
+
/** What the last loader call threw. A stored copy stays in `data`. */
|
|
30
|
+
error: Readonly<Ref<Error | undefined>>;
|
|
31
|
+
/** When the copy in `data` was stored. `undefined` once `data` is an answer of this page, or the default. */
|
|
32
|
+
storedAt: Readonly<Ref<Date | undefined>>;
|
|
33
|
+
/** Runs the loader again. A newer call aborts an older one. It never throws: a failure goes to `error`. */
|
|
34
|
+
refresh: () => Promise<void>;
|
|
35
|
+
}
|
|
36
|
+
/** The query of `useStoredFetch()`. A `null` or `undefined` value is left out. */
|
|
37
|
+
export type StoredFetchQuery = Record<string, string | number | boolean | null | undefined>;
|
|
38
|
+
export interface UseStoredFetchOptions<TData, TDefault> extends UseStoredDataOptions<TData, TDefault> {
|
|
39
|
+
/** Joins the query of the URL. A ref or a getter makes it reactive: a new query is a new read. */
|
|
40
|
+
query?: MaybeRefOrGetter<StoredFetchQuery>;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Server data that shows the last answer at once from the device, then always asks the server again. The same shape as
|
|
44
|
+
* Nuxt `useAsyncData()`. Reads of the same key share one state and one loader call.
|
|
45
|
+
*
|
|
46
|
+
* The first render shows the stored copy when `openDevice()` finished before the app mounted. On the server, it reads no
|
|
47
|
+
* storage and calls no loader: `data` is the default and `status` is `idle`. In a component that hydrates server HTML,
|
|
48
|
+
* the first render is the same as on the server, also when the device is open. The stored copy shows and the loader
|
|
49
|
+
* starts when the component mounts.
|
|
50
|
+
*
|
|
51
|
+
* ```vue
|
|
52
|
+
* <script setup lang="ts">
|
|
53
|
+
* import { useStoredData } from 'vite-hub/device/vue'
|
|
54
|
+
*
|
|
55
|
+
* const { data: projects, storedAt } = useStoredData('projects', () =>
|
|
56
|
+
* fetch('/api/projects').then(response => response.json() as Promise<Project[]>), { default: () => [] })
|
|
57
|
+
* <\/script>
|
|
58
|
+
* ```
|
|
59
|
+
*/
|
|
60
|
+
export declare function useStoredData<TData, TDefault = undefined>(key: MaybeRefOrGetter<string>, loader: (context: StoredDataContext) => Promise<TData>, options?: UseStoredDataOptions<TData, TDefault>): UseStoredDataReturn<TData, TDefault>;
|
|
61
|
+
/**
|
|
62
|
+
* A GET request for JSON with `useStoredData()`: the last answer at once from the device, then the answer of the
|
|
63
|
+
* server. The key of the read is the URL, so reads of the same URL and query share one state and one request. A
|
|
64
|
+
* status that is not 2xx goes to `error` with `DEVICE_FETCH_FAILED`, and the device never stores it.
|
|
65
|
+
*
|
|
66
|
+
* ```vue
|
|
67
|
+
* <script setup lang="ts">
|
|
68
|
+
* import { useStoredFetch } from 'vite-hub/device/vue'
|
|
69
|
+
*
|
|
70
|
+
* const { data: projects } = useStoredFetch<Project[]>('/api/projects', { query: { team: 't1' }, default: () => [] })
|
|
71
|
+
* <\/script>
|
|
72
|
+
* ```
|
|
73
|
+
*/
|
|
74
|
+
export declare function useStoredFetch<TData = unknown>(url: MaybeRefOrGetter<string>, options: UseStoredFetchOptions<TData, TData> & {
|
|
75
|
+
default: () => NoInfer<TData>;
|
|
76
|
+
}): UseStoredDataReturn<TData, TData>;
|
|
77
|
+
export declare function useStoredFetch<TData = unknown, TDefault = undefined>(url: MaybeRefOrGetter<string>, options?: UseStoredFetchOptions<TData, TDefault>): UseStoredDataReturn<TData, TDefault>;
|
|
78
|
+
//#endregion
|
package/dist/vue.js
ADDED
|
@@ -0,0 +1,282 @@
|
|
|
1
|
+
import { a as deviceErrors, i as currentDevice, n as checkKey, r as checkMaxAge, t as checkAccount } from "./device-CxuDKYfP.js";
|
|
2
|
+
import { computed, getCurrentInstance, getCurrentScope, onMounted, onScopeDispose, shallowRef, toValue, watch } from "vue";
|
|
3
|
+
//#region src/vue.ts
|
|
4
|
+
const week = 6048e5;
|
|
5
|
+
const reads = /* @__PURE__ */ new Map();
|
|
6
|
+
let watching = false;
|
|
7
|
+
/**
|
|
8
|
+
* The read whose answer names the account right now, and the epoch of the event of that naming. For that event only, it
|
|
9
|
+
* keeps its answer and does not start over. A later event, such as a naming that the event started, applies to it.
|
|
10
|
+
*/
|
|
11
|
+
let claiming;
|
|
12
|
+
/** The reads with `account` whose loader runs. */
|
|
13
|
+
const identifying = /* @__PURE__ */ new Set();
|
|
14
|
+
/**
|
|
15
|
+
* The reads that show a stored copy and wait for the naming before they call their loader. A held read always starts
|
|
16
|
+
* its loader, at the naming or when the last running read with `account` ends or goes. The hold only saves the call that
|
|
17
|
+
* the naming would start over: it never decides what is stored. It applies to reads that start after the session read,
|
|
18
|
+
* and not to reads that wait for the mount during hydration.
|
|
19
|
+
*/
|
|
20
|
+
const held = /* @__PURE__ */ new Set();
|
|
21
|
+
/**
|
|
22
|
+
* Calls the loaders of the held reads, when the read that says who is signed in failed or went before it named an
|
|
23
|
+
* account. A naming calls them through its event.
|
|
24
|
+
*/
|
|
25
|
+
function startHeld(device) {
|
|
26
|
+
const waiting = [...held];
|
|
27
|
+
for (const read of waiting) {
|
|
28
|
+
if (identifying.size) return;
|
|
29
|
+
load(read, read.loader, device);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Follows the device: a copy that loads late shows, a naming of the account calls every loader again, and a reset starts
|
|
34
|
+
* every read over.
|
|
35
|
+
*/
|
|
36
|
+
function watchDevice(device) {
|
|
37
|
+
if (watching) return;
|
|
38
|
+
watching = true;
|
|
39
|
+
device.subscribe((event) => {
|
|
40
|
+
if (event.type === "load") {
|
|
41
|
+
for (const key of event.keys) {
|
|
42
|
+
const read = reads.get(key);
|
|
43
|
+
if (read && !read.answered) show(read, device);
|
|
44
|
+
}
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
for (const read of reads.values()) {
|
|
48
|
+
if (read === claiming?.read && device.epoch() === claiming.epoch) continue;
|
|
49
|
+
if (event.type === "reset") {
|
|
50
|
+
read.answered = false;
|
|
51
|
+
read.data.value = read.fallback();
|
|
52
|
+
read.storedAt.value = void 0;
|
|
53
|
+
read.error.value = void 0;
|
|
54
|
+
}
|
|
55
|
+
if (read.status.value !== "idle") load(read, read.loader, device);
|
|
56
|
+
}
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
function show(read, device) {
|
|
60
|
+
const stored = device.read(read.key, read.maxAge);
|
|
61
|
+
if (!stored) return;
|
|
62
|
+
read.data.value = stored.value;
|
|
63
|
+
read.storedAt.value = new Date(stored.storedAt);
|
|
64
|
+
}
|
|
65
|
+
async function load(read, loader, device) {
|
|
66
|
+
if (!read.users) return;
|
|
67
|
+
read.controller?.abort();
|
|
68
|
+
read.loader = loader;
|
|
69
|
+
read.status.value = "pending";
|
|
70
|
+
held.delete(read);
|
|
71
|
+
if (!read.account && read.storedAt.value && identifying.size && !device.named()) {
|
|
72
|
+
read.controller = void 0;
|
|
73
|
+
held.add(read);
|
|
74
|
+
if (!read.heldUntil) {
|
|
75
|
+
let resolve = () => void 0;
|
|
76
|
+
read.heldUntil = {
|
|
77
|
+
promise: new Promise((done) => resolve = done),
|
|
78
|
+
resolve
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
return read.heldUntil.promise;
|
|
82
|
+
}
|
|
83
|
+
const controller = new AbortController();
|
|
84
|
+
read.controller = controller;
|
|
85
|
+
if (read.account) identifying.add(read);
|
|
86
|
+
const since = device.epoch();
|
|
87
|
+
try {
|
|
88
|
+
const value = await loader({ signal: controller.signal }, read.key);
|
|
89
|
+
if (controller.signal.aborted || device.epoch() !== since) return;
|
|
90
|
+
const account = read.account?.(value);
|
|
91
|
+
if (account === void 0) {
|
|
92
|
+
publish(read, value);
|
|
93
|
+
return device.write(read.key, value, read.maxAge, since);
|
|
94
|
+
}
|
|
95
|
+
checkAccount(account);
|
|
96
|
+
for (;;) {
|
|
97
|
+
while (device.loading()) {
|
|
98
|
+
await device.whenOpen();
|
|
99
|
+
if (controller.signal.aborted || device.epoch() !== since) return;
|
|
100
|
+
}
|
|
101
|
+
claiming = {
|
|
102
|
+
read,
|
|
103
|
+
epoch: since + 1
|
|
104
|
+
};
|
|
105
|
+
let claimed;
|
|
106
|
+
try {
|
|
107
|
+
claimed = device.claim(read.key, value, read.maxAge, since, account);
|
|
108
|
+
} finally {
|
|
109
|
+
claiming = void 0;
|
|
110
|
+
}
|
|
111
|
+
if (claimed) break;
|
|
112
|
+
if (controller.signal.aborted || device.epoch() !== since || !device.loading()) return;
|
|
113
|
+
}
|
|
114
|
+
if (controller.signal.aborted) return;
|
|
115
|
+
publish(read, value);
|
|
116
|
+
} catch (error) {
|
|
117
|
+
if (controller.signal.aborted || device.epoch() !== since) return;
|
|
118
|
+
read.error.value = error instanceof Error ? error : new Error(String(error), { cause: error });
|
|
119
|
+
read.status.value = "error";
|
|
120
|
+
} finally {
|
|
121
|
+
if (read.controller === controller) {
|
|
122
|
+
read.heldUntil?.resolve();
|
|
123
|
+
read.heldUntil = void 0;
|
|
124
|
+
if (identifying.delete(read)) startHeld(device);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
/** Shows an answer of the loader in the read. */
|
|
129
|
+
function publish(read, value) {
|
|
130
|
+
read.answered = true;
|
|
131
|
+
read.data.value = value;
|
|
132
|
+
read.storedAt.value = void 0;
|
|
133
|
+
read.error.value = void 0;
|
|
134
|
+
read.status.value = "success";
|
|
135
|
+
}
|
|
136
|
+
/** Returns the shared read of `key`. A new read calls its loader at once, unless `start` is `false`: then it stays `idle`. */
|
|
137
|
+
function acquire(key, loader, fallback, maxAge, account, device, owner, start = true) {
|
|
138
|
+
const existing = reads.get(key);
|
|
139
|
+
if (existing) {
|
|
140
|
+
existing.users++;
|
|
141
|
+
existing.loaders.set(owner, loader);
|
|
142
|
+
return existing;
|
|
143
|
+
}
|
|
144
|
+
const read = {
|
|
145
|
+
key,
|
|
146
|
+
data: shallowRef(),
|
|
147
|
+
status: shallowRef("idle"),
|
|
148
|
+
error: shallowRef(),
|
|
149
|
+
storedAt: shallowRef(),
|
|
150
|
+
answered: false,
|
|
151
|
+
users: 1,
|
|
152
|
+
controller: void 0,
|
|
153
|
+
loaders: /* @__PURE__ */ new Map([[owner, loader]]),
|
|
154
|
+
loader,
|
|
155
|
+
fallback,
|
|
156
|
+
maxAge,
|
|
157
|
+
account,
|
|
158
|
+
heldUntil: void 0
|
|
159
|
+
};
|
|
160
|
+
read.data.value = fallback();
|
|
161
|
+
show(read, device);
|
|
162
|
+
reads.set(key, read);
|
|
163
|
+
if (start) load(read, loader, device);
|
|
164
|
+
return read;
|
|
165
|
+
}
|
|
166
|
+
/**
|
|
167
|
+
* When a user of a read goes, such as a component that unmounts or moves to another key, its loader goes too: a reset
|
|
168
|
+
* calls the loader of a user that still reads this key, not one that now reads another key. When the last user goes,
|
|
169
|
+
* the loader call stops, so a late answer cannot replace a newer one.
|
|
170
|
+
*/
|
|
171
|
+
function release(read, device, owner) {
|
|
172
|
+
read.users--;
|
|
173
|
+
const gone = read.loaders.get(owner);
|
|
174
|
+
read.loaders.delete(owner);
|
|
175
|
+
if (read.users) {
|
|
176
|
+
if (read.loader === gone) read.loader = [...read.loaders.values()].at(-1) ?? read.loader;
|
|
177
|
+
return;
|
|
178
|
+
}
|
|
179
|
+
read.controller?.abort();
|
|
180
|
+
held.delete(read);
|
|
181
|
+
read.heldUntil?.resolve();
|
|
182
|
+
read.heldUntil = void 0;
|
|
183
|
+
if (reads.get(read.key) === read) reads.delete(read.key);
|
|
184
|
+
if (identifying.delete(read)) startHeld(device);
|
|
185
|
+
}
|
|
186
|
+
/**
|
|
187
|
+
* Server data that shows the last answer at once from the device, then always asks the server again. The same shape as
|
|
188
|
+
* Nuxt `useAsyncData()`. Reads of the same key share one state and one loader call.
|
|
189
|
+
*
|
|
190
|
+
* The first render shows the stored copy when `openDevice()` finished before the app mounted. On the server, it reads no
|
|
191
|
+
* storage and calls no loader: `data` is the default and `status` is `idle`. In a component that hydrates server HTML,
|
|
192
|
+
* the first render is the same as on the server, also when the device is open. The stored copy shows and the loader
|
|
193
|
+
* starts when the component mounts.
|
|
194
|
+
*
|
|
195
|
+
* ```vue
|
|
196
|
+
* <script setup lang="ts">
|
|
197
|
+
* import { useStoredData } from 'vite-hub/device/vue'
|
|
198
|
+
*
|
|
199
|
+
* const { data: projects, storedAt } = useStoredData('projects', () =>
|
|
200
|
+
* fetch('/api/projects').then(response => response.json() as Promise<Project[]>), { default: () => [] })
|
|
201
|
+
* <\/script>
|
|
202
|
+
* ```
|
|
203
|
+
*/
|
|
204
|
+
function useStoredData(key, loader, options = {}) {
|
|
205
|
+
return useRead(key, (context) => loader(context), options);
|
|
206
|
+
}
|
|
207
|
+
function useStoredFetch(url, options = {}) {
|
|
208
|
+
const { query, ...read } = options;
|
|
209
|
+
return useRead(() => fetchKey(toValue(url), toValue(query)), fetchJSON, read);
|
|
210
|
+
}
|
|
211
|
+
/**
|
|
212
|
+
* The key of a `useStoredFetch()` read, which is also the URL that it requests: the path and the query of a URL on the
|
|
213
|
+
* origin of the page, or the whole URL on another origin. The query is sorted by name, so the order in the code does
|
|
214
|
+
* not make another key. The hash goes.
|
|
215
|
+
*/
|
|
216
|
+
function fetchKey(url, query) {
|
|
217
|
+
const page = typeof document === "undefined" ? "http://localhost/" : document.baseURI;
|
|
218
|
+
const target = new URL(url, page);
|
|
219
|
+
for (const [name, value] of Object.entries(query ?? {})) if (value !== null && value !== void 0) target.searchParams.append(name, String(value));
|
|
220
|
+
target.searchParams.sort();
|
|
221
|
+
target.hash = "";
|
|
222
|
+
return target.origin === new URL(page).origin ? target.pathname + target.search : target.href;
|
|
223
|
+
}
|
|
224
|
+
/** Asks for the JSON at `key`. An answer that is not 2xx throws, so the device never stores an error body. */
|
|
225
|
+
async function fetchJSON({ signal }, key) {
|
|
226
|
+
const response = await fetch(key, {
|
|
227
|
+
signal,
|
|
228
|
+
headers: { accept: "application/json" }
|
|
229
|
+
});
|
|
230
|
+
if (!response.ok) throw deviceErrors.DEVICE_FETCH_FAILED({
|
|
231
|
+
url: key,
|
|
232
|
+
status: response.status
|
|
233
|
+
});
|
|
234
|
+
return await response.json();
|
|
235
|
+
}
|
|
236
|
+
/** The shared read of `key` for one component, or the server render of it. */
|
|
237
|
+
function useRead(key, loader, options) {
|
|
238
|
+
const maxAge = checkMaxAge(options.maxAge ?? week);
|
|
239
|
+
const fallback = options.default ?? (() => void 0);
|
|
240
|
+
const account = options.account;
|
|
241
|
+
const device = currentDevice();
|
|
242
|
+
if (!device) {
|
|
243
|
+
checkKey(toValue(key));
|
|
244
|
+
return {
|
|
245
|
+
data: shallowRef(fallback()),
|
|
246
|
+
status: shallowRef("idle"),
|
|
247
|
+
error: shallowRef(),
|
|
248
|
+
storedAt: shallowRef(),
|
|
249
|
+
refresh: async () => void 0
|
|
250
|
+
};
|
|
251
|
+
}
|
|
252
|
+
watchDevice(device);
|
|
253
|
+
const hydrating = shallowRef(Boolean(getCurrentInstance()?.vnode.el));
|
|
254
|
+
const rendered = shallowRef(hydrating.value ? fallback() : void 0);
|
|
255
|
+
const owner = {};
|
|
256
|
+
const current = shallowRef(acquire(checkKey(toValue(key)), loader, fallback, maxAge, account, device, owner, !hydrating.value));
|
|
257
|
+
if (hydrating.value) onMounted(() => {
|
|
258
|
+
hydrating.value = false;
|
|
259
|
+
if (current.value.status.value === "idle") load(current.value, loader, device);
|
|
260
|
+
});
|
|
261
|
+
if (typeof key !== "string") watch(() => toValue(key), (next) => {
|
|
262
|
+
const previous = current.value;
|
|
263
|
+
current.value = acquire(checkKey(next), loader, fallback, maxAge, account, device, owner);
|
|
264
|
+
release(previous, device, owner);
|
|
265
|
+
});
|
|
266
|
+
if (getCurrentScope()) onScopeDispose(() => release(current.value, device, owner));
|
|
267
|
+
return {
|
|
268
|
+
data: computed({
|
|
269
|
+
get: () => hydrating.value ? rendered.value : current.value.data.value,
|
|
270
|
+
set: (value) => {
|
|
271
|
+
if (hydrating.value) rendered.value = value;
|
|
272
|
+
current.value.data.value = value;
|
|
273
|
+
}
|
|
274
|
+
}),
|
|
275
|
+
status: computed(() => hydrating.value ? "idle" : current.value.status.value),
|
|
276
|
+
error: computed(() => hydrating.value ? void 0 : current.value.error.value),
|
|
277
|
+
storedAt: computed(() => hydrating.value ? void 0 : current.value.storedAt.value),
|
|
278
|
+
refresh: () => load(current.value, loader, device)
|
|
279
|
+
};
|
|
280
|
+
}
|
|
281
|
+
//#endregion
|
|
282
|
+
export { useStoredData, useStoredFetch };
|
package/package.json
CHANGED
|
@@ -1,12 +1,75 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@vite-hub/device",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "0.3.0",
|
|
4
|
+
"description": "Stored reads for the browser: show the last server answer at once from the device, for the signed-in account, then refresh it.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"cache",
|
|
7
|
+
"indexeddb",
|
|
8
|
+
"offline",
|
|
9
|
+
"stale-while-revalidate",
|
|
10
|
+
"vitehub",
|
|
11
|
+
"vue"
|
|
12
|
+
],
|
|
13
|
+
"homepage": "https://vitehub.dev",
|
|
14
|
+
"bugs": "https://github.com/vite-hub/vitehub/issues",
|
|
5
15
|
"license": "Apache-2.0",
|
|
16
|
+
"author": "onmax <maximogarciamtnez@gmail.com>",
|
|
6
17
|
"repository": {
|
|
7
18
|
"type": "git",
|
|
8
19
|
"url": "git+https://github.com/vite-hub/vitehub.git",
|
|
9
20
|
"directory": "packages/device"
|
|
10
21
|
},
|
|
11
|
-
"
|
|
12
|
-
|
|
22
|
+
"files": [
|
|
23
|
+
"dist",
|
|
24
|
+
"package.json"
|
|
25
|
+
],
|
|
26
|
+
"type": "module",
|
|
27
|
+
"sideEffects": false,
|
|
28
|
+
"types": "./dist/index.d.ts",
|
|
29
|
+
"exports": {
|
|
30
|
+
".": {
|
|
31
|
+
"types": "./dist/index.d.ts",
|
|
32
|
+
"import": "./dist/index.js",
|
|
33
|
+
"default": "./dist/index.js"
|
|
34
|
+
},
|
|
35
|
+
"./vue": {
|
|
36
|
+
"types": "./dist/vue.d.ts",
|
|
37
|
+
"import": "./dist/vue.js",
|
|
38
|
+
"default": "./dist/vue.js"
|
|
39
|
+
},
|
|
40
|
+
"./package.json": "./package.json"
|
|
41
|
+
},
|
|
42
|
+
"dependencies": {
|
|
43
|
+
"@vite-hub/runtime": "0.3.0"
|
|
44
|
+
},
|
|
45
|
+
"devDependencies": {
|
|
46
|
+
"@types/node": "^24.19.1",
|
|
47
|
+
"@vite-hub/internal": "0.0.1",
|
|
48
|
+
"happy-dom": "21.0.3",
|
|
49
|
+
"playwright-core": "^1.63.0",
|
|
50
|
+
"publint": "^0.3.25",
|
|
51
|
+
"typescript": "^6.0.3",
|
|
52
|
+
"vite": "^8.2.2",
|
|
53
|
+
"vite-plus": "^0.3.3",
|
|
54
|
+
"vitest": "^4.1.11",
|
|
55
|
+
"vue": "3.5.44"
|
|
56
|
+
},
|
|
57
|
+
"peerDependencies": {
|
|
58
|
+
"vue": "^3.5.0"
|
|
59
|
+
},
|
|
60
|
+
"peerDependenciesMeta": {
|
|
61
|
+
"vue": {
|
|
62
|
+
"optional": true
|
|
63
|
+
}
|
|
64
|
+
},
|
|
65
|
+
"engines": {
|
|
66
|
+
"node": ">=22.18.0"
|
|
67
|
+
},
|
|
68
|
+
"scripts": {
|
|
69
|
+
"build": "vp pack",
|
|
70
|
+
"dev": "vp pack --watch",
|
|
71
|
+
"typecheck": "vp run --cache -t @vite-hub/device#build && node ../../test/package-typecheck.mjs --noEmit -p ./tsconfig.json",
|
|
72
|
+
"test": "vp run --cache -t @vite-hub/device#build && vp test",
|
|
73
|
+
"test:browser": "node --test test/browser/device.browser.mjs"
|
|
74
|
+
}
|
|
75
|
+
}
|