@aventoapp/framework 0.1.0 → 0.2.1
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/README.md +260 -0
- package/dist/index.js.map +1 -1
- package/dist/native/index.js.map +1 -1
- package/dist/offline/index.js +399 -0
- package/dist/offline/index.js.map +7 -0
- package/dist/server/index.js +75 -0
- package/dist/server/index.js.map +3 -3
- package/dist/server/workflow/index.js.map +1 -1
- package/dist/shared/index.js.map +1 -1
- package/dist/web/index.js.map +1 -1
- package/package.json +10 -7
- package/schemas/Workflow.json +14 -14
- package/schemas/WorkflowHistory.json +22 -22
- package/schemas/WorkflowInstance.json +16 -16
- package/schemas/WorkflowState.json +18 -18
- package/schemas/WorkflowTransition.json +27 -27
- package/src/index.js +8 -8
- package/src/native/components/NativeAuthProvider.jsx +249 -249
- package/src/native/components/NativeDetail.jsx +270 -270
- package/src/native/components/NativeForm.jsx +543 -543
- package/src/native/components/NativeGrid.jsx +90 -90
- package/src/native/components/NativeJsonGrid.jsx +213 -213
- package/src/native/components/NativeJsonView.jsx +454 -454
- package/src/native/components/NativeJsonViewContext.js +17 -17
- package/src/native/components/NativeShell.jsx +68 -68
- package/src/native/components/NativeViewComponent.jsx +351 -351
- package/src/native/extensions/NativeExtensionRegistry.js +81 -81
- package/src/native/hooks/useNativeStore.js +72 -72
- package/src/native/index.js +15 -15
- package/src/native/layouts/NativeStackLayout.jsx +30 -30
- package/src/native/layouts/NativeTabLayout.jsx +96 -96
- package/src/native/storage.js +13 -13
- package/src/native/stores/NativeBaseStore.js +348 -348
- package/src/native/stores/NativeStoreContext.jsx +53 -53
- package/src/offline/clock.js +12 -0
- package/src/offline/coalesce.js +45 -0
- package/src/offline/diff.js +17 -0
- package/src/offline/idb.js +52 -0
- package/src/offline/index.js +13 -0
- package/src/offline/kit.js +121 -0
- package/src/offline/outbox.js +83 -0
- package/src/offline/store.js +26 -0
- package/src/offline/syncer.js +55 -0
- package/src/server/ai/capabilities-routes.js +106 -106
- package/src/server/ai/index.js +1 -1
- package/src/server/cache/MemoryCache.js +153 -153
- package/src/server/cache/index.js +2 -2
- package/src/server/cache/middleware.js +12 -12
- package/src/server/db/index.js +14 -14
- package/src/server/db/mongo.js +137 -137
- package/src/server/db/postgres.js +144 -144
- package/src/server/index.js +42 -38
- package/src/server/middleware/auth.js +682 -682
- package/src/server/middleware/can-flags.js +132 -132
- package/src/server/middleware/entityRoles.js +105 -105
- package/src/server/middleware/index.js +58 -58
- package/src/server/middleware/permissions.js +240 -240
- package/src/server/middleware/tenant.js +203 -203
- package/src/server/offline/field-lww.js +66 -0
- package/src/server/offline/index.js +1 -0
- package/src/server/realtime/EventBus.js +45 -45
- package/src/server/realtime/WebSocketServer.js +105 -105
- package/src/server/realtime/index.js +3 -3
- package/src/server/realtime/middleware.js +18 -18
- package/src/server/services/email-templates.js +157 -157
- package/src/server/services/email.js +78 -78
- package/src/server/services/index.js +15 -15
- package/src/server/services/storage.js +119 -119
- package/src/server/utils/index.js +16 -16
- package/src/server/utils/paginate.js +65 -65
- package/src/server/utils/query-builder.js +293 -293
- package/src/server/utils/route-loader.js +61 -61
- package/src/server/workflow/WorkflowEngine.js +494 -494
- package/src/server/workflow/index.js +2 -2
- package/src/server/workflow/workflow-routes.js +174 -174
- package/src/shared/index.js +10 -10
- package/src/shared/utils/field-accessor.js +108 -108
- package/src/shared/utils/index.js +7 -7
- package/src/shared/utils/validation-utils.js +83 -83
- package/src/web/components/AppRouter/AppRouter.jsx +130 -130
- package/src/web/components/AppRouter/index.js +1 -1
- package/src/web/components/AppShell/AppShell.jsx +101 -101
- package/src/web/components/AppShell/DefaultUserMenu.jsx +54 -54
- package/src/web/components/AppShell/ShellConfig.js +53 -53
- package/src/web/components/AppShell/index.js +3 -3
- package/src/web/components/AuthProvider.jsx +426 -426
- package/src/web/components/CardList/CardList.jsx +272 -272
- package/src/web/components/CardList/index.js +2 -2
- package/src/web/components/DetailView/DetailView.jsx +281 -281
- package/src/web/components/DetailView/index.js +2 -2
- package/src/web/components/Form/Form.jsx +300 -300
- package/src/web/components/Form/FormField.jsx +226 -226
- package/src/web/components/Form/index.js +3 -3
- package/src/web/components/Grid/Grid.jsx +304 -304
- package/src/web/components/Grid/index.js +2 -2
- package/src/web/components/IconRegistry/IconRegistry.jsx +127 -127
- package/src/web/components/IconRegistry/index.js +1 -1
- package/src/web/components/JsonView/JsonView.jsx +647 -647
- package/src/web/components/JsonView/ViewComponent.jsx +1045 -1045
- package/src/web/components/JsonView/ViewToolbar.jsx +141 -141
- package/src/web/components/JsonView/index.js +14 -14
- package/src/web/components/JsonView/layouts/SingleLayout.jsx +41 -41
- package/src/web/components/JsonView/layouts/SplitLayout.jsx +122 -122
- package/src/web/components/JsonView/layouts/TabLayout.jsx +112 -112
- package/src/web/components/JsonView/layouts/index.js +8 -8
- package/src/web/components/Layout.jsx +265 -265
- package/src/web/components/MobileLayout/MobileLayout.jsx +385 -385
- package/src/web/components/MobileLayout/index.js +1 -1
- package/src/web/components/Navigation/Navigation.jsx +248 -248
- package/src/web/components/Navigation/index.js +1 -1
- package/src/web/components/NotificationProvider.jsx +55 -55
- package/src/web/components/Pagination/InfiniteScroll.jsx +82 -82
- package/src/web/components/Pagination/Pagination.jsx +73 -73
- package/src/web/components/Pagination/index.js +8 -8
- package/src/web/components/SimpleList/SimpleList.jsx +177 -177
- package/src/web/components/SimpleList/index.js +2 -2
- package/src/web/components/TenantProvider.jsx +121 -121
- package/src/web/components/WorkflowActions/WorkflowActions.jsx +71 -71
- package/src/web/components/WorkflowActions/index.js +1 -1
- package/src/web/components/WorkflowField/WorkflowField.jsx +176 -176
- package/src/web/components/WorkflowField/index.js +2 -2
- package/src/web/components/WorkflowField/workflowColors.js +32 -32
- package/src/web/components/auth/DevTenantSelector.jsx +90 -90
- package/src/web/components/auth/ForgotPasswordForm.jsx +94 -94
- package/src/web/components/auth/RegisterForm.jsx +168 -168
- package/src/web/components/auth/ResetPasswordForm.jsx +121 -121
- package/src/web/components/auth/VerifyEmailView.jsx +85 -85
- package/src/web/components/auth/index.js +5 -5
- package/src/web/components/index.js +39 -39
- package/src/web/components/layouts/CardListLayout.jsx +68 -68
- package/src/web/components/layouts/FullscreenLayout.jsx +30 -30
- package/src/web/components/layouts/MobileStackLayout.jsx +28 -28
- package/src/web/components/layouts/WizardLayout.jsx +86 -86
- package/src/web/components/layouts/index.js +4 -4
- package/src/web/components/mobile/Badge.jsx +105 -105
- package/src/web/components/mobile/BadgeThemeEditor.jsx +104 -104
- package/src/web/components/mobile/EmptyState.jsx +30 -30
- package/src/web/components/mobile/QuickActionButton.jsx +77 -77
- package/src/web/components/mobile/ServerAutocomplete.jsx +123 -123
- package/src/web/components/mobile/StarRating.jsx +42 -42
- package/src/web/components/mobile/StatCard.jsx +65 -65
- package/src/web/components/mobile/index.js +7 -7
- package/src/web/extensions/ExtensionRegistry.js +79 -79
- package/src/web/extensions/index.js +7 -7
- package/src/web/hooks/index.js +15 -15
- package/src/web/hooks/useApi.js +76 -76
- package/src/web/hooks/useAuth.js +37 -37
- package/src/web/hooks/useDebouncedSave.js +158 -158
- package/src/web/hooks/useIsMobile.js +14 -14
- package/src/web/hooks/useOfflineQueue.js +99 -99
- package/src/web/hooks/useSelectionModel.js +143 -143
- package/src/web/hooks/useServerAutocomplete.js +146 -146
- package/src/web/hooks/useStore.js +107 -107
- package/src/web/hooks/useSubscription.js +130 -130
- package/src/web/hooks/useTenant.js +39 -39
- package/src/web/hooks/useTenantResolver.js +65 -65
- package/src/web/hooks/useUndoRedo.js +77 -77
- package/src/web/hooks/useViews.js +113 -113
- package/src/web/hooks/useWorkflow.js +190 -190
- package/src/web/index.js +117 -117
- package/src/web/stores/BaseStore.js +439 -439
- package/src/web/stores/StoreContext.jsx +93 -93
- package/src/web/stores/index.js +3 -3
- package/src/web/theme/index.js +3 -3
- package/src/web/theme/mui-theme.js +228 -228
- package/src/web/utils/formatTimeAgo.js +22 -22
- package/src/web/utils/index.js +1 -1
- package/src/web/views/ViewRegistry.js +235 -235
- package/src/web/views/index.js +2 -2
|
@@ -1,53 +1,53 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* NativeStoreContext
|
|
3
|
-
*
|
|
4
|
-
* React context provider that injects auth from NativeAuthProvider into stores.
|
|
5
|
-
*/
|
|
6
|
-
import React, { createContext, useContext, useMemo, useRef } from 'react';
|
|
7
|
-
import { useNativeAuth } from '../components/NativeAuthProvider.jsx';
|
|
8
|
-
|
|
9
|
-
export const NativeStoreContext = createContext(null);
|
|
10
|
-
|
|
11
|
-
/**
|
|
12
|
-
* NativeStoreProvider
|
|
13
|
-
*
|
|
14
|
-
* Wraps the app to provide store access with automatic auth integration.
|
|
15
|
-
*
|
|
16
|
-
* @param {Object} props
|
|
17
|
-
* @param {Object} props.stores - Object mapping store names to store instances
|
|
18
|
-
* @param {React.ReactNode} props.children
|
|
19
|
-
*/
|
|
20
|
-
export function NativeStoreProvider({ stores = {}, children }) {
|
|
21
|
-
const { getAuthHeader } = useNativeAuth();
|
|
22
|
-
|
|
23
|
-
const storesRef = useRef(stores);
|
|
24
|
-
const getAuthHeaderRef = useRef(getAuthHeader);
|
|
25
|
-
|
|
26
|
-
getAuthHeaderRef.current = getAuthHeader;
|
|
27
|
-
|
|
28
|
-
// Initialize all stores synchronously so they are ready before child effects
|
|
29
|
-
const initializedRef = useRef(false);
|
|
30
|
-
if (!initializedRef.current) {
|
|
31
|
-
Object.values(storesRef.current).forEach(store => {
|
|
32
|
-
if (store && typeof store._initialize === 'function') {
|
|
33
|
-
store._initialize(
|
|
34
|
-
() => getAuthHeaderRef.current()
|
|
35
|
-
);
|
|
36
|
-
}
|
|
37
|
-
});
|
|
38
|
-
initializedRef.current = true;
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
const contextValue = useMemo(() => ({
|
|
42
|
-
stores: storesRef.current,
|
|
43
|
-
getStore: (name) => storesRef.current[name] || null
|
|
44
|
-
}), []);
|
|
45
|
-
|
|
46
|
-
return (
|
|
47
|
-
<NativeStoreContext.Provider value={contextValue}>
|
|
48
|
-
{children}
|
|
49
|
-
</NativeStoreContext.Provider>
|
|
50
|
-
);
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
export default NativeStoreProvider;
|
|
1
|
+
/**
|
|
2
|
+
* NativeStoreContext
|
|
3
|
+
*
|
|
4
|
+
* React context provider that injects auth from NativeAuthProvider into stores.
|
|
5
|
+
*/
|
|
6
|
+
import React, { createContext, useContext, useMemo, useRef } from 'react';
|
|
7
|
+
import { useNativeAuth } from '../components/NativeAuthProvider.jsx';
|
|
8
|
+
|
|
9
|
+
export const NativeStoreContext = createContext(null);
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* NativeStoreProvider
|
|
13
|
+
*
|
|
14
|
+
* Wraps the app to provide store access with automatic auth integration.
|
|
15
|
+
*
|
|
16
|
+
* @param {Object} props
|
|
17
|
+
* @param {Object} props.stores - Object mapping store names to store instances
|
|
18
|
+
* @param {React.ReactNode} props.children
|
|
19
|
+
*/
|
|
20
|
+
export function NativeStoreProvider({ stores = {}, children }) {
|
|
21
|
+
const { getAuthHeader } = useNativeAuth();
|
|
22
|
+
|
|
23
|
+
const storesRef = useRef(stores);
|
|
24
|
+
const getAuthHeaderRef = useRef(getAuthHeader);
|
|
25
|
+
|
|
26
|
+
getAuthHeaderRef.current = getAuthHeader;
|
|
27
|
+
|
|
28
|
+
// Initialize all stores synchronously so they are ready before child effects
|
|
29
|
+
const initializedRef = useRef(false);
|
|
30
|
+
if (!initializedRef.current) {
|
|
31
|
+
Object.values(storesRef.current).forEach(store => {
|
|
32
|
+
if (store && typeof store._initialize === 'function') {
|
|
33
|
+
store._initialize(
|
|
34
|
+
() => getAuthHeaderRef.current()
|
|
35
|
+
);
|
|
36
|
+
}
|
|
37
|
+
});
|
|
38
|
+
initializedRef.current = true;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const contextValue = useMemo(() => ({
|
|
42
|
+
stores: storesRef.current,
|
|
43
|
+
getStore: (name) => storesRef.current[name] || null
|
|
44
|
+
}), []);
|
|
45
|
+
|
|
46
|
+
return (
|
|
47
|
+
<NativeStoreContext.Provider value={contextValue}>
|
|
48
|
+
{children}
|
|
49
|
+
</NativeStoreContext.Provider>
|
|
50
|
+
);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export default NativeStoreProvider;
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
// A monotonic-ish wall clock that can be calibrated against server time so a
|
|
2
|
+
// wrong device clock doesn't poison cross-client timestamp ordering.
|
|
3
|
+
export function createClock({ nowFn = () => Date.now() } = {}) {
|
|
4
|
+
let offset = 0;
|
|
5
|
+
return {
|
|
6
|
+
now() { return nowFn() + offset; },
|
|
7
|
+
setOffsetFromServer(serverEpochMs, localAtMs = nowFn()) {
|
|
8
|
+
offset = serverEpochMs - localAtMs;
|
|
9
|
+
},
|
|
10
|
+
getOffsetMs() { return offset; },
|
|
11
|
+
};
|
|
12
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
// Collapse repeated offline edits so the outbox holds one entry per
|
|
2
|
+
// (resource, recordId), keeping the latest value per field by client timestamp.
|
|
3
|
+
export function coalescePatch(queue, entry) {
|
|
4
|
+
const idx = queue.findIndex(
|
|
5
|
+
(e) => e.resource === entry.resource && e.recordId === entry.recordId,
|
|
6
|
+
);
|
|
7
|
+
if (idx === -1) {
|
|
8
|
+
return [...queue, cloneEntry(entry)];
|
|
9
|
+
}
|
|
10
|
+
const existing = queue[idx];
|
|
11
|
+
const merged = cloneEntry(existing);
|
|
12
|
+
for (const field of Object.keys(entry.fields)) {
|
|
13
|
+
// Always store a numeric ts — a field with no incoming timestamp defaults to
|
|
14
|
+
// 0 so `undefined` never lands in fieldTimes (it would break the LWW compare).
|
|
15
|
+
const incomingTs = tsOf(entry.fieldTimes, field);
|
|
16
|
+
const currentTs = merged.fieldTimes[field];
|
|
17
|
+
if (currentTs === undefined || incomingTs >= currentTs) {
|
|
18
|
+
merged.fields[field] = entry.fields[field];
|
|
19
|
+
merged.fieldTimes[field] = incomingTs;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
const out = queue.slice();
|
|
23
|
+
out[idx] = merged;
|
|
24
|
+
return out;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function cloneEntry(e) {
|
|
28
|
+
// Normalize: every field carries a numeric ts (default 0), never undefined.
|
|
29
|
+
const fieldTimes = {};
|
|
30
|
+
for (const field of Object.keys(e.fields)) fieldTimes[field] = tsOf(e.fieldTimes, field);
|
|
31
|
+
for (const field of Object.keys(e.fieldTimes || {})) {
|
|
32
|
+
if (fieldTimes[field] === undefined) fieldTimes[field] = tsOf(e.fieldTimes, field);
|
|
33
|
+
}
|
|
34
|
+
return {
|
|
35
|
+
resource: e.resource,
|
|
36
|
+
recordId: e.recordId,
|
|
37
|
+
fields: { ...e.fields },
|
|
38
|
+
fieldTimes,
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function tsOf(fieldTimes, field) {
|
|
43
|
+
const t = fieldTimes ? fieldTimes[field] : undefined;
|
|
44
|
+
return t === undefined || t === null ? 0 : t;
|
|
45
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
// Shallow field diff: only keys present in `next` whose value differs from `prev`.
|
|
2
|
+
// Never includes keys absent from `next` — so untouched fields are never sent.
|
|
3
|
+
export function diffFields(prev, next) {
|
|
4
|
+
const base = prev && typeof prev === 'object' ? prev : {};
|
|
5
|
+
const out = {};
|
|
6
|
+
for (const key of Object.keys(next || {})) {
|
|
7
|
+
if (!sameValue(base[key], next[key])) out[key] = next[key];
|
|
8
|
+
}
|
|
9
|
+
return out;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
function sameValue(a, b) {
|
|
13
|
+
if (a === b) return true;
|
|
14
|
+
// NaN === NaN
|
|
15
|
+
if (typeof a === 'number' && typeof b === 'number' && Number.isNaN(a) && Number.isNaN(b)) return true;
|
|
16
|
+
return false;
|
|
17
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
// Minimal promisified IndexedDB wrapper over three fixed stores.
|
|
2
|
+
// `indexedDB` is injected so this runs under fake-indexeddb in tests and
|
|
3
|
+
// window.indexedDB in the browser. No external dependency.
|
|
4
|
+
|
|
5
|
+
const STORES = ['cache', 'outbox', 'meta'];
|
|
6
|
+
const DB_VERSION = 1;
|
|
7
|
+
|
|
8
|
+
export function createIdb({ name = 'avento-offline', indexedDB } = {}) {
|
|
9
|
+
if (!indexedDB) throw new Error('createIdb requires an indexedDB implementation');
|
|
10
|
+
let dbPromise = null;
|
|
11
|
+
|
|
12
|
+
function open() {
|
|
13
|
+
if (dbPromise) return dbPromise;
|
|
14
|
+
dbPromise = new Promise((resolve, reject) => {
|
|
15
|
+
const req = indexedDB.open(name, DB_VERSION);
|
|
16
|
+
req.onupgradeneeded = () => {
|
|
17
|
+
const db = req.result;
|
|
18
|
+
for (const s of STORES) {
|
|
19
|
+
if (!db.objectStoreNames.contains(s)) db.createObjectStore(s);
|
|
20
|
+
}
|
|
21
|
+
};
|
|
22
|
+
req.onsuccess = () => resolve(req.result);
|
|
23
|
+
req.onerror = () => reject(req.error);
|
|
24
|
+
}).catch((err) => {
|
|
25
|
+
// Don't cache a transient open failure forever — clear so the next call retries.
|
|
26
|
+
dbPromise = null;
|
|
27
|
+
throw err;
|
|
28
|
+
});
|
|
29
|
+
return dbPromise;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function tx(store, mode, fn) {
|
|
33
|
+
return open().then((db) => new Promise((resolve, reject) => {
|
|
34
|
+
const t = db.transaction(store, mode);
|
|
35
|
+
const os = t.objectStore(store);
|
|
36
|
+
let result;
|
|
37
|
+
const r = fn(os);
|
|
38
|
+
if (r) r.onsuccess = () => { result = r.result; };
|
|
39
|
+
t.oncomplete = () => resolve(result);
|
|
40
|
+
t.onerror = () => reject(t.error);
|
|
41
|
+
t.onabort = () => reject(t.error);
|
|
42
|
+
}));
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
return {
|
|
46
|
+
get: (store, key) => tx(store, 'readonly', (os) => os.get(key)),
|
|
47
|
+
set: (store, key, value) => tx(store, 'readwrite', (os) => os.put(value, key)),
|
|
48
|
+
del: (store, key) => tx(store, 'readwrite', (os) => os.delete(key)),
|
|
49
|
+
clear: (store) => tx(store, 'readwrite', (os) => os.clear()),
|
|
50
|
+
all: (store) => tx(store, 'readonly', (os) => os.getAll()),
|
|
51
|
+
};
|
|
52
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
// @aventoapp/framework/offline
|
|
2
|
+
// Framework-agnostic offline read-cache + write-outbox + sync engine.
|
|
3
|
+
// MUST stay React-free and DOM-optional (browser globals only behind injection).
|
|
4
|
+
|
|
5
|
+
export const OFFLINE_KIT_VERSION = '0.1.0';
|
|
6
|
+
export { diffFields } from './diff.js';
|
|
7
|
+
export { createClock } from './clock.js';
|
|
8
|
+
export { coalescePatch } from './coalesce.js';
|
|
9
|
+
export { createIdb } from './idb.js';
|
|
10
|
+
export { createStore } from './store.js';
|
|
11
|
+
export { createOutbox } from './outbox.js';
|
|
12
|
+
export { createSyncer } from './syncer.js';
|
|
13
|
+
export { createOfflineKit } from './kit.js';
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import { diffFields } from './diff.js';
|
|
2
|
+
import { createStore } from './store.js';
|
|
3
|
+
import { createOutbox } from './outbox.js';
|
|
4
|
+
import { createSyncer } from './syncer.js';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Create an offline-first sync kit.
|
|
8
|
+
*
|
|
9
|
+
* @param {object} opts
|
|
10
|
+
* @param {object} opts.idb - IndexedDB-compatible handle used for the local
|
|
11
|
+
* cache store and the outbox (e.g. `indexedDB` / `fake-indexeddb`).
|
|
12
|
+
* @param {{ now: () => number }} opts.clock - Clock used to timestamp field
|
|
13
|
+
* edits and `lastSyncedAt`. Injected for testability.
|
|
14
|
+
* @param {boolean | (() => boolean)} opts.isOnline - Initial online state, or
|
|
15
|
+
* a function returning it. **`isOnline` is consulted only once at
|
|
16
|
+
* construction to seed the initial online state. After construction,
|
|
17
|
+
* connectivity changes MUST be pushed via `setOnline(true|false)` (e.g.
|
|
18
|
+
* from window 'online'/'offline' listeners); the kit does not re-poll
|
|
19
|
+
* `isOnline`.**
|
|
20
|
+
* @param {(req: object) => Promise<{ ok: boolean, body?: any }>} opts.request
|
|
21
|
+
* Transport function used for reads, patch sends, and blob sends.
|
|
22
|
+
* @returns {object} The offline kit instance (defineSyncedResource, read/edit,
|
|
23
|
+
* queueBlob, flushNow, setOnline, getStatus, subscribe).
|
|
24
|
+
*/
|
|
25
|
+
export function createOfflineKit({ idb, clock, isOnline, request }) {
|
|
26
|
+
const kitNonce = Math.random().toString(36).slice(2, 8);
|
|
27
|
+
let seq = 0;
|
|
28
|
+
const nextId = () => `${kitNonce}-${++seq}`;
|
|
29
|
+
|
|
30
|
+
const resources = new Map();
|
|
31
|
+
const store = createStore({ idb, clock });
|
|
32
|
+
const outbox = createOutbox({ idb });
|
|
33
|
+
// `isOnline` seeds the initial state; after creation, `online` is the sole
|
|
34
|
+
// source of truth so `setOnline()` (e.g. wired to window online/offline
|
|
35
|
+
// events) can always override it — re-invoking `isOnline()` on every read
|
|
36
|
+
// would make setOnline() a no-op whenever the consumer passed a function.
|
|
37
|
+
let online = typeof isOnline === 'function' ? isOnline() : !!isOnline;
|
|
38
|
+
const onlineNow = () => online;
|
|
39
|
+
|
|
40
|
+
const transport = {
|
|
41
|
+
async sendPatch(entry) {
|
|
42
|
+
const def = resources.get(entry.resource);
|
|
43
|
+
const { url, method } = def.patch(entry.recordId);
|
|
44
|
+
const body = { ...entry.fields, _fieldTimes: entry.fieldTimes };
|
|
45
|
+
const res = await request({ url, method, body });
|
|
46
|
+
return { ok: !!res && res.ok };
|
|
47
|
+
},
|
|
48
|
+
async sendBlob(rec) {
|
|
49
|
+
const res = await request({ url: rec.url, method: rec.method, body: rec.blob, headers: rec.headers, isBlob: true, idemKey: rec.idemKey, meta: rec.meta });
|
|
50
|
+
return { ok: !!res && res.ok };
|
|
51
|
+
},
|
|
52
|
+
};
|
|
53
|
+
const syncer = createSyncer({ outbox, transport, isOnline: onlineNow });
|
|
54
|
+
|
|
55
|
+
let lastSyncedAt = null;
|
|
56
|
+
const subscribers = new Set();
|
|
57
|
+
function emit() {
|
|
58
|
+
const s = getStatusSync();
|
|
59
|
+
for (const fn of subscribers) fn(s);
|
|
60
|
+
}
|
|
61
|
+
let pendingCache = 0;
|
|
62
|
+
async function refreshPending() {
|
|
63
|
+
const { patches, blobs } = await outbox.list();
|
|
64
|
+
pendingCache = patches.length + blobs.length;
|
|
65
|
+
emit();
|
|
66
|
+
}
|
|
67
|
+
function getStatusSync() {
|
|
68
|
+
return { online: onlineNow(), pendingCount: pendingCache, lastSyncedAt, flushing: syncer.running() };
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const kit = {
|
|
72
|
+
defineSyncedResource(def) { resources.set(def.name, def); },
|
|
73
|
+
|
|
74
|
+
async readSynced(name, id) {
|
|
75
|
+
const def = resources.get(name);
|
|
76
|
+
const key = `${name}/${id}`;
|
|
77
|
+
const res = await store.readThrough(key, async () => {
|
|
78
|
+
if (!onlineNow()) return { ok: false };
|
|
79
|
+
const r = await request({ url: def.load(id), method: 'GET' });
|
|
80
|
+
return r && r.ok ? { ok: true, data: r.body } : { ok: false };
|
|
81
|
+
});
|
|
82
|
+
return res;
|
|
83
|
+
},
|
|
84
|
+
|
|
85
|
+
async primeCache(name, id, data) {
|
|
86
|
+
await store.putCached(`${name}/${id}`, data);
|
|
87
|
+
},
|
|
88
|
+
|
|
89
|
+
async editSynced(name, id, partialFields) {
|
|
90
|
+
const key = `${name}/${id}`;
|
|
91
|
+
const cached = (await store.getCached(key)) || {};
|
|
92
|
+
const changed = diffFields(cached, partialFields);
|
|
93
|
+
if (Object.keys(changed).length === 0) return;
|
|
94
|
+
const ts = clock.now();
|
|
95
|
+
const fieldTimes = {};
|
|
96
|
+
for (const k of Object.keys(changed)) fieldTimes[k] = ts;
|
|
97
|
+
await store.putCached(key, { ...cached, ...changed }); // optimistic
|
|
98
|
+
await outbox.enqueuePatch({ id: nextId(), resource: name, recordId: String(id), fields: changed, fieldTimes });
|
|
99
|
+
await refreshPending();
|
|
100
|
+
if (onlineNow()) await kit.flushNow();
|
|
101
|
+
},
|
|
102
|
+
|
|
103
|
+
async queueBlob(name, { url, idemKey, blob, meta = {}, method = 'POST', headers }) {
|
|
104
|
+
await outbox.enqueueBlob({ id: nextId(), resource: name, url, method, idemKey, blob, meta, headers });
|
|
105
|
+
await refreshPending();
|
|
106
|
+
if (onlineNow()) await kit.flushNow();
|
|
107
|
+
},
|
|
108
|
+
|
|
109
|
+
async flushNow() {
|
|
110
|
+
const res = await syncer.flush();
|
|
111
|
+
if (res.sentPatches > 0 || res.sentBlobs > 0) lastSyncedAt = clock.now();
|
|
112
|
+
await refreshPending();
|
|
113
|
+
return res;
|
|
114
|
+
},
|
|
115
|
+
|
|
116
|
+
setOnline(v) { online = v; emit(); },
|
|
117
|
+
getStatus: getStatusSync,
|
|
118
|
+
subscribe(fn) { subscribers.add(fn); fn(getStatusSync()); return () => subscribers.delete(fn); },
|
|
119
|
+
};
|
|
120
|
+
return kit;
|
|
121
|
+
}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { coalescePatch } from './coalesce.js';
|
|
2
|
+
|
|
3
|
+
const KEY = 'queue';
|
|
4
|
+
|
|
5
|
+
export function createOutbox({ idb }) {
|
|
6
|
+
async function read() {
|
|
7
|
+
return (await idb.get('outbox', KEY)) || { patches: [], blobs: [] };
|
|
8
|
+
}
|
|
9
|
+
async function write(state) {
|
|
10
|
+
await idb.set('outbox', KEY, state);
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
// Single-tab mutex: every mutation is a non-atomic read-modify-write across two
|
|
14
|
+
// IDB transactions, so concurrent un-awaited mutations would race and clobber
|
|
15
|
+
// each other (lost edit). Serialize them through a promise chain. `list()` is a
|
|
16
|
+
// single `idb.get` (one transaction = consistent snapshot) so it stays lock-free.
|
|
17
|
+
let chain = Promise.resolve();
|
|
18
|
+
function withLock(fn) {
|
|
19
|
+
const run = chain.then(() => fn());
|
|
20
|
+
chain = run.then(() => {}, () => {});
|
|
21
|
+
return run;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
return {
|
|
25
|
+
enqueuePatch(entry) {
|
|
26
|
+
return withLock(async () => {
|
|
27
|
+
const state = await read();
|
|
28
|
+
// coalescePatch keys on resource+recordId; carry an id on the surviving entry.
|
|
29
|
+
const before = state.patches.find((p) => p.resource === entry.resource && p.recordId === entry.recordId);
|
|
30
|
+
const patches = coalescePatch(state.patches, entry);
|
|
31
|
+
const survivor = patches.find((p) => p.resource === entry.resource && p.recordId === entry.recordId);
|
|
32
|
+
if (survivor && !survivor.id) survivor.id = before ? before.id : entry.id;
|
|
33
|
+
state.patches = patches;
|
|
34
|
+
await write(state);
|
|
35
|
+
});
|
|
36
|
+
},
|
|
37
|
+
enqueueBlob(rec) {
|
|
38
|
+
return withLock(async () => {
|
|
39
|
+
const state = await read();
|
|
40
|
+
state.blobs.push({ kind: 'blob', ...rec });
|
|
41
|
+
await write(state);
|
|
42
|
+
});
|
|
43
|
+
},
|
|
44
|
+
async list() {
|
|
45
|
+
return read();
|
|
46
|
+
},
|
|
47
|
+
remove(id) {
|
|
48
|
+
return withLock(async () => {
|
|
49
|
+
const state = await read();
|
|
50
|
+
state.patches = state.patches.filter((p) => p.id !== id);
|
|
51
|
+
state.blobs = state.blobs.filter((b) => b.id !== id);
|
|
52
|
+
await write(state);
|
|
53
|
+
});
|
|
54
|
+
},
|
|
55
|
+
// Field-scoped acknowledgement of a sent patch snapshot. Removes only the
|
|
56
|
+
// fields that were actually sent (ts still matches the snapshot); a field
|
|
57
|
+
// that coalesced in during the send has a newer ts and is retained so it
|
|
58
|
+
// still gets flushed. Drops the entry entirely when no fields remain.
|
|
59
|
+
ackPatch(sentEntry) {
|
|
60
|
+
return withLock(async () => {
|
|
61
|
+
const state = await read();
|
|
62
|
+
const idx = state.patches.findIndex(
|
|
63
|
+
(p) => p.resource === sentEntry.resource && p.recordId === sentEntry.recordId,
|
|
64
|
+
);
|
|
65
|
+
if (idx === -1) return;
|
|
66
|
+
const cur = state.patches[idx];
|
|
67
|
+
const sentTimes = sentEntry.fieldTimes || {};
|
|
68
|
+
for (const field of Object.keys(sentTimes)) {
|
|
69
|
+
if (cur.fieldTimes[field] === sentTimes[field]) {
|
|
70
|
+
delete cur.fields[field];
|
|
71
|
+
delete cur.fieldTimes[field];
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
if (Object.keys(cur.fields).length === 0) {
|
|
75
|
+
state.patches.splice(idx, 1);
|
|
76
|
+
} else {
|
|
77
|
+
state.patches[idx] = cur;
|
|
78
|
+
}
|
|
79
|
+
await write(state);
|
|
80
|
+
});
|
|
81
|
+
},
|
|
82
|
+
};
|
|
83
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
// Read-through cache: serve fresh when online, fall back to the last snapshot
|
|
2
|
+
// when offline. Backed by the idb 'cache' store.
|
|
3
|
+
export function createStore({ idb, clock }) {
|
|
4
|
+
async function getEntry(key) {
|
|
5
|
+
return (await idb.get('cache', key)) || null;
|
|
6
|
+
}
|
|
7
|
+
return {
|
|
8
|
+
async readThrough(key, fetcher) {
|
|
9
|
+
const res = await fetcher();
|
|
10
|
+
if (res && res.ok) {
|
|
11
|
+
await idb.set('cache', key, { data: res.data, fetchedAt: clock.now() });
|
|
12
|
+
return { data: res.data, fromCache: false };
|
|
13
|
+
}
|
|
14
|
+
const entry = await getEntry(key);
|
|
15
|
+
if (entry) return { data: entry.data, fromCache: true, fetchedAt: entry.fetchedAt };
|
|
16
|
+
return { data: null, fromCache: true };
|
|
17
|
+
},
|
|
18
|
+
async getCached(key) {
|
|
19
|
+
const entry = await getEntry(key);
|
|
20
|
+
return entry ? entry.data : null;
|
|
21
|
+
},
|
|
22
|
+
async putCached(key, data) {
|
|
23
|
+
await idb.set('cache', key, { data, fetchedAt: clock.now() });
|
|
24
|
+
},
|
|
25
|
+
};
|
|
26
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
// Drains the outbox in order: all patches first, then blobs. A failed send in a
|
|
2
|
+
// category leaves that item queued and stops that category (FIFO, no reorder).
|
|
3
|
+
export function createSyncer({ outbox, transport, isOnline }) {
|
|
4
|
+
let flushing = false;
|
|
5
|
+
// Work enqueued while a flush is in flight would otherwise be stranded until an
|
|
6
|
+
// unrelated future trigger; this latch makes the active flush re-run once more.
|
|
7
|
+
let pendingFlush = false;
|
|
8
|
+
|
|
9
|
+
async function flush() {
|
|
10
|
+
if (flushing) { pendingFlush = true; return { sentPatches: 0, sentBlobs: 0, remaining: await remaining() }; }
|
|
11
|
+
if (!isOnline()) return { sentPatches: 0, sentBlobs: 0, remaining: await remaining() };
|
|
12
|
+
flushing = true;
|
|
13
|
+
let sentPatches = 0; let sentBlobs = 0;
|
|
14
|
+
try {
|
|
15
|
+
let { patches, blobs } = await outbox.list();
|
|
16
|
+
for (const p of patches) {
|
|
17
|
+
const r = await transport.sendPatch(p);
|
|
18
|
+
if (!r || !r.ok) break;
|
|
19
|
+
// Field-scoped ack: remove only the fields we actually sent. A field that
|
|
20
|
+
// coalesced into this record during the send has a newer ts and is kept.
|
|
21
|
+
await outbox.ackPatch(p);
|
|
22
|
+
sentPatches++;
|
|
23
|
+
}
|
|
24
|
+
// A failed patch above breaks only the patch loop — blobs are append-only and
|
|
25
|
+
// independent of preceding patches, so the blob drain always runs.
|
|
26
|
+
for (const b of blobs) {
|
|
27
|
+
const r = await transport.sendBlob(b);
|
|
28
|
+
if (!r || !r.ok) break;
|
|
29
|
+
await outbox.remove(b.id);
|
|
30
|
+
sentBlobs++;
|
|
31
|
+
}
|
|
32
|
+
} finally {
|
|
33
|
+
flushing = false;
|
|
34
|
+
}
|
|
35
|
+
// Drain anything enqueued mid-flush. Loop until a flush completes with no
|
|
36
|
+
// pending work (each recursion re-checks the latch in its own finally).
|
|
37
|
+
if (pendingFlush) {
|
|
38
|
+
pendingFlush = false;
|
|
39
|
+
const again = await flush();
|
|
40
|
+
return {
|
|
41
|
+
sentPatches: sentPatches + again.sentPatches,
|
|
42
|
+
sentBlobs: sentBlobs + again.sentBlobs,
|
|
43
|
+
remaining: again.remaining,
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
return { sentPatches, sentBlobs, remaining: await remaining() };
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
async function remaining() {
|
|
50
|
+
const { patches, blobs } = await outbox.list();
|
|
51
|
+
return patches.length + blobs.length;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
return { flush, running: () => flushing };
|
|
55
|
+
}
|