@sfxcode/nuxt-ui-mongocamp 1.5.6 → 1.5.7

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/module.d.mts CHANGED
@@ -34,6 +34,15 @@ interface ModuleOptions {
34
34
  * `sessionGuard`; no effect in server proxy mode.
35
35
  */
36
36
  sessionGuardVerify?: boolean;
37
+ /**
38
+ * Opt-in for apps that keep working without a network (e.g. an installable PWA with its own local data):
39
+ * - `useMongocampConnection()` is kept current in the browser (online / offline / server unreachable, with retries);
40
+ * - the session guard clears a session only while the server can be reached, so an expired token never logs the
41
+ * user out while offline (nothing could renew it; the next navigation after the server is back decides);
42
+ * - the server version (`$mongocampVersion`) loads in the background with a timeout and never holds up the start.
43
+ * Default false.
44
+ */
45
+ offline?: boolean;
37
46
  /**
38
47
  * Path the session guard navigates to after clearing an expired session — e.g. '/login'. Always
39
48
  * treated as allowed by the middleware itself, so it can never cause a redirect loop.
package/dist/module.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "compatibility": {
5
5
  "nuxt": ">=3.16.0"
6
6
  },
7
- "version": "1.5.6",
7
+ "version": "1.5.7",
8
8
  "builder": {
9
9
  "@nuxt/module-builder": "1.0.4",
10
10
  "unbuild": "3.6.1"
package/dist/module.mjs CHANGED
@@ -53,6 +53,7 @@ const module$1 = defineNuxtModule({
53
53
  logoutPath: "/logout",
54
54
  sessionGuard: false,
55
55
  sessionGuardVerify: false,
56
+ offline: false,
56
57
  loginPath: "/",
57
58
  managerRoles: [],
58
59
  securedRouteParts: [],
@@ -17,13 +17,13 @@ declare const __VLS_template: () => {
17
17
  };
18
18
  type __VLS_Slots = ReturnType<typeof __VLS_template>['__VLS_Slots'];
19
19
  declare const __VLS_base: import("vue").DefineComponent<__VLS_Props, {}, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {
20
- clear: () => any;
21
20
  open: () => any;
21
+ clear: () => any;
22
22
  confirm: () => any;
23
23
  selectAll: () => any;
24
24
  }, string, import("vue").PublicProps, Readonly<__VLS_Props> & Readonly<{
25
- onClear?: (() => any) | undefined;
26
25
  onOpen?: (() => any) | undefined;
26
+ onClear?: (() => any) | undefined;
27
27
  onConfirm?: (() => any) | undefined;
28
28
  onSelectAll?: (() => any) | undefined;
29
29
  }>, {}, {}, {}, {}, string, import("vue").ComponentProvideOptions, false, {}, any>;
@@ -17,13 +17,13 @@ declare const __VLS_template: () => {
17
17
  };
18
18
  type __VLS_Slots = ReturnType<typeof __VLS_template>['__VLS_Slots'];
19
19
  declare const __VLS_base: import("vue").DefineComponent<__VLS_Props, {}, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {
20
- clear: () => any;
21
20
  open: () => any;
21
+ clear: () => any;
22
22
  confirm: () => any;
23
23
  selectAll: () => any;
24
24
  }, string, import("vue").PublicProps, Readonly<__VLS_Props> & Readonly<{
25
- onClear?: (() => any) | undefined;
26
25
  onOpen?: (() => any) | undefined;
26
+ onClear?: (() => any) | undefined;
27
27
  onConfirm?: (() => any) | undefined;
28
28
  onSelectAll?: (() => any) | undefined;
29
29
  }>, {}, {}, {}, {}, string, import("vue").ComponentProvideOptions, false, {}, any>;
@@ -7,17 +7,17 @@ type __VLS_ModelProps = {
7
7
  };
8
8
  type __VLS_PublicProps = __VLS_Props & __VLS_ModelProps;
9
9
  declare const __VLS_export: import("vue").DefineComponent<__VLS_PublicProps, {}, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {
10
+ "update:open": (value: boolean) => any;
10
11
  done: (payload: {
11
12
  target: string;
12
13
  copied: number;
13
14
  }) => any;
14
- "update:open": (value: boolean) => any;
15
15
  }, string, import("vue").PublicProps, Readonly<__VLS_PublicProps> & Readonly<{
16
+ "onUpdate:open"?: ((value: boolean) => any) | undefined;
16
17
  onDone?: ((payload: {
17
18
  target: string;
18
19
  copied: number;
19
20
  }) => any) | undefined;
20
- "onUpdate:open"?: ((value: boolean) => any) | undefined;
21
21
  }>, {}, {}, {}, {}, string, import("vue").ComponentProvideOptions, false, {}, any>;
22
22
  declare const _default: typeof __VLS_export;
23
23
  export default _default;
@@ -7,17 +7,17 @@ type __VLS_ModelProps = {
7
7
  };
8
8
  type __VLS_PublicProps = __VLS_Props & __VLS_ModelProps;
9
9
  declare const __VLS_export: import("vue").DefineComponent<__VLS_PublicProps, {}, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {
10
+ "update:open": (value: boolean) => any;
10
11
  done: (payload: {
11
12
  target: string;
12
13
  copied: number;
13
14
  }) => any;
14
- "update:open": (value: boolean) => any;
15
15
  }, string, import("vue").PublicProps, Readonly<__VLS_PublicProps> & Readonly<{
16
+ "onUpdate:open"?: ((value: boolean) => any) | undefined;
16
17
  onDone?: ((payload: {
17
18
  target: string;
18
19
  copied: number;
19
20
  }) => any) | undefined;
20
- "onUpdate:open"?: ((value: boolean) => any) | undefined;
21
21
  }>, {}, {}, {}, {}, string, import("vue").ComponentProvideOptions, false, {}, any>;
22
22
  declare const _default: typeof __VLS_export;
23
23
  export default _default;
@@ -6,17 +6,17 @@ type __VLS_ModelProps = {
6
6
  };
7
7
  type __VLS_PublicProps = __VLS_Props & __VLS_ModelProps;
8
8
  declare const __VLS_export: import("vue").DefineComponent<__VLS_PublicProps, {}, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {
9
+ "update:open": (value: boolean) => any;
9
10
  done: (payload: {
10
11
  source: string;
11
12
  target: string;
12
13
  }) => any;
13
- "update:open": (value: boolean) => any;
14
14
  }, string, import("vue").PublicProps, Readonly<__VLS_PublicProps> & Readonly<{
15
+ "onUpdate:open"?: ((value: boolean) => any) | undefined;
15
16
  onDone?: ((payload: {
16
17
  source: string;
17
18
  target: string;
18
19
  }) => any) | undefined;
19
- "onUpdate:open"?: ((value: boolean) => any) | undefined;
20
20
  }>, {}, {}, {}, {}, string, import("vue").ComponentProvideOptions, false, {}, any>;
21
21
  declare const _default: typeof __VLS_export;
22
22
  export default _default;
@@ -6,17 +6,17 @@ type __VLS_ModelProps = {
6
6
  };
7
7
  type __VLS_PublicProps = __VLS_Props & __VLS_ModelProps;
8
8
  declare const __VLS_export: import("vue").DefineComponent<__VLS_PublicProps, {}, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {
9
+ "update:open": (value: boolean) => any;
9
10
  done: (payload: {
10
11
  source: string;
11
12
  target: string;
12
13
  }) => any;
13
- "update:open": (value: boolean) => any;
14
14
  }, string, import("vue").PublicProps, Readonly<__VLS_PublicProps> & Readonly<{
15
+ "onUpdate:open"?: ((value: boolean) => any) | undefined;
15
16
  onDone?: ((payload: {
16
17
  source: string;
17
18
  target: string;
18
19
  }) => any) | undefined;
19
- "onUpdate:open"?: ((value: boolean) => any) | undefined;
20
20
  }>, {}, {}, {}, {}, string, import("vue").ComponentProvideOptions, false, {}, any>;
21
21
  declare const _default: typeof __VLS_export;
22
22
  export default _default;
@@ -19,11 +19,11 @@ type __VLS_ModelProps = {
19
19
  };
20
20
  type __VLS_PublicProps = __VLS_Props & __VLS_ModelProps;
21
21
  declare const __VLS_export: import("vue").DefineComponent<__VLS_PublicProps, {}, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {
22
- select: (entry: PaletteEntry) => any;
23
22
  "update:open": (value: boolean) => any;
23
+ select: (entry: PaletteEntry) => any;
24
24
  }, string, import("vue").PublicProps, Readonly<__VLS_PublicProps> & Readonly<{
25
- onSelect?: ((entry: PaletteEntry) => any) | undefined;
26
25
  "onUpdate:open"?: ((value: boolean) => any) | undefined;
26
+ onSelect?: ((entry: PaletteEntry) => any) | undefined;
27
27
  }>, {
28
28
  shortcut: string;
29
29
  cacheMs: number;
@@ -19,11 +19,11 @@ type __VLS_ModelProps = {
19
19
  };
20
20
  type __VLS_PublicProps = __VLS_Props & __VLS_ModelProps;
21
21
  declare const __VLS_export: import("vue").DefineComponent<__VLS_PublicProps, {}, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {
22
- select: (entry: PaletteEntry) => any;
23
22
  "update:open": (value: boolean) => any;
23
+ select: (entry: PaletteEntry) => any;
24
24
  }, string, import("vue").PublicProps, Readonly<__VLS_PublicProps> & Readonly<{
25
- onSelect?: ((entry: PaletteEntry) => any) | undefined;
26
25
  "onUpdate:open"?: ((value: boolean) => any) | undefined;
26
+ onSelect?: ((entry: PaletteEntry) => any) | undefined;
27
27
  }>, {
28
28
  shortcut: string;
29
29
  cacheMs: number;
@@ -2,15 +2,15 @@ import type { Grant, JsonSchema, JsonValueBoolean, Role, SchemaAnalysis, UserPro
2
2
  declare const _default: () => {
3
3
  listUsers: (filter?: string) => Promise<UserProfile[]>;
4
4
  addUser: (userId: string, password: string, apiKey?: string, roles?: string[]) => Promise<UserProfile>;
5
- deleteUser: (userId: string) => Promise<any>;
5
+ deleteUser: (userId: string) => Promise<JsonValueBoolean>;
6
6
  updateUserRoles: (userId: string, roles: string[]) => Promise<UserProfile>;
7
- updateUserPassword: (userId: string, password: string) => Promise<any>;
7
+ updateUserPassword: (userId: string, password: string) => Promise<JsonValueBoolean>;
8
8
  listRoles: (filter?: string) => Promise<Role[]>;
9
9
  addRole: (name: string, isAdmin?: boolean, collectionGrants?: Grant[]) => Promise<Role>;
10
10
  updateRole: (roleName: string, isAdmin: boolean, collectionGrants?: Grant[]) => Promise<Role>;
11
- deleteRole: (roleName: string) => Promise<any>;
11
+ deleteRole: (roleName: string) => Promise<JsonValueBoolean>;
12
12
  listCollections: () => Promise<string[]>;
13
- clearCollection: (collectionName: string) => Promise<any>;
13
+ clearCollection: (collectionName: string) => Promise<JsonValueBoolean>;
14
14
  deleteCollection: (collectionName: string) => Promise<JsonValueBoolean>;
15
15
  getJsonSchema: (collectionName: string) => Promise<JsonSchema>;
16
16
  getSchemaAnalysis: (collectionName: string, documents: number, depth?: number) => Promise<SchemaAnalysis>;
@@ -1 +1,13 @@
1
- export declare function useMongocampClientApi(): any;
1
+ export declare function useMongocampClientApi(): {
2
+ adminApi: import("@sfxcode/nuxt-mongocamp-server").AdminApi;
3
+ applicationApi: import("@sfxcode/nuxt-mongocamp-server").ApplicationApi;
4
+ authApi: import("@sfxcode/nuxt-mongocamp-server").AuthApi;
5
+ bucketApi: import("@sfxcode/nuxt-mongocamp-server").BucketApi;
6
+ collectionApi: import("@sfxcode/nuxt-mongocamp-server").CollectionApi;
7
+ databaseApi: import("@sfxcode/nuxt-mongocamp-server").DatabaseApi;
8
+ documentApi: import("@sfxcode/nuxt-mongocamp-server").DocumentApi;
9
+ fileApi: import("@sfxcode/nuxt-mongocamp-server").FileApi;
10
+ indexApi: import("@sfxcode/nuxt-mongocamp-server").IndexApi;
11
+ systemApi: import("@sfxcode/nuxt-mongocamp-server").SystemApi;
12
+ jobApi: import("@sfxcode/nuxt-mongocamp-server").JobsApi;
13
+ };
@@ -0,0 +1,25 @@
1
+ import type { ComputedRef, Ref } from 'vue';
2
+ import type { ConnectionState } from '../utils/connection.js';
3
+ export interface MongocampConnection {
4
+ /** `online`, `offline` (no network at all) or `unreachable` (network, but the server does not answer). */
5
+ state: Ref<ConnectionState>;
6
+ /** Shorthand for `state === 'online'`. */
7
+ isOnline: ComputedRef<boolean>;
8
+ /** When the server last answered a check or a reported request. */
9
+ lastAnswer: Ref<string | null>;
10
+ /** Asks the server now (`GET /version`, with a short timeout) and returns the new state. */
11
+ check: () => Promise<ConnectionState>;
12
+ /**
13
+ * Feeds the outcome of an app's own request into the state, so a failing request switches to `unreachable` at once
14
+ * instead of waiting for the next check: pass nothing after a success, or the caught error after a failure. An error
15
+ * with an HTTP status (401, 404, 500, ...) still proves the server answered. Returns whether it was a network failure.
16
+ */
17
+ report: (error?: unknown) => boolean;
18
+ }
19
+ /**
20
+ * Whether the MongoCamp server can be reached right now. One shared state per app. With the module option `offline`,
21
+ * the plugin keeps it current (browser online/offline events, a retry with backoff while unreachable, a check when the
22
+ * tab becomes visible) and the session guard keeps the session while it is not `online`. Without that option the state
23
+ * still works but only changes through `check()` and `report()`.
24
+ */
25
+ export declare function useMongocampConnection(): MongocampConnection;
@@ -0,0 +1,33 @@
1
+ import { computed } from "vue";
2
+ import { useState } from "#app";
3
+ import { useMongocampClientApi } from "#imports";
4
+ import { CONNECTION_CHECK_TIMEOUT_MS, initialConnectionState, isNetworkFailure, nextConnectionState } from "../utils/connection.js";
5
+ export function useMongocampConnection() {
6
+ const state = useState("mongocamp.connection.state", () => initialConnectionState(typeof navigator === "undefined" ? void 0 : navigator.onLine));
7
+ const lastAnswer = useState("mongocamp.connection.lastAnswer", () => null);
8
+ const { systemApi } = useMongocampClientApi();
9
+ function apply(event) {
10
+ state.value = nextConnectionState(state.value, event);
11
+ if (event === "server-answered") lastAnswer.value = (/* @__PURE__ */ new Date()).toISOString();
12
+ }
13
+ function report(error) {
14
+ const failed = error !== void 0 && isNetworkFailure(error);
15
+ apply(failed ? "network-failure" : "server-answered");
16
+ return failed;
17
+ }
18
+ async function check() {
19
+ if (typeof navigator !== "undefined" && navigator.onLine === false) {
20
+ apply("browser-offline");
21
+ return state.value;
22
+ }
23
+ apply("browser-online");
24
+ try {
25
+ await systemApi.version({ signal: AbortSignal.timeout(CONNECTION_CHECK_TIMEOUT_MS) });
26
+ report();
27
+ } catch (error) {
28
+ report(error);
29
+ }
30
+ return state.value;
31
+ }
32
+ return { state, isOnline: computed(() => state.value === "online"), lastAnswer, check, report };
33
+ }
@@ -1,10 +1,10 @@
1
1
  export declare function useMongocampRoles(): {
2
- isLoggedIn: any;
3
- isAdmin: import("vue").ComputedRef<any>;
4
- isManager: import("vue").ComputedRef<any>;
2
+ isLoggedIn: import("vue").ComputedRef<boolean>;
3
+ isAdmin: import("vue").ComputedRef<boolean>;
4
+ isManager: import("vue").ComputedRef<boolean>;
5
5
  isProxyMode: boolean;
6
- canSeeAdmin: import("vue").ComputedRef<any>;
7
- canSeeManagement: import("vue").ComputedRef<any>;
6
+ canSeeAdmin: import("vue").ComputedRef<boolean>;
7
+ canSeeManagement: import("vue").ComputedRef<boolean>;
8
8
  notAllowedPath: string;
9
9
  logoutRedirectPath: string;
10
10
  logoutPath: string;
@@ -1,2 +1,6 @@
1
- declare const _default: any;
1
+ declare const _default: import("nuxt/app").Plugin<{
2
+ mongocampVersion: import("vue").Ref<import("@sfxcode/nuxt-mongocamp-server").Version | null | undefined, import("@sfxcode/nuxt-mongocamp-server").Version | null | undefined>;
3
+ }> & import("nuxt/app").ObjectPlugin<{
4
+ mongocampVersion: import("vue").Ref<import("@sfxcode/nuxt-mongocamp-server").Version | null | undefined, import("@sfxcode/nuxt-mongocamp-server").Version | null | undefined>;
5
+ }>;
2
6
  export default _default;
@@ -1,7 +1,11 @@
1
+ import { watch } from "vue";
1
2
  import { defineNuxtPlugin, addRouteMiddleware, navigateTo, useAsyncData, useRuntimeConfig } from "#app";
2
3
  import { useMongocampAuth, useMongocampClientApi, useMongocampStorage } from "#imports";
3
4
  import { useMongocampRoles } from "./composables/useMongocampRoles.js";
4
5
  import { useMongocampSession } from "./composables/useMongocampSession.js";
6
+ import { useMongocampConnection } from "./composables/useMongocampConnection.js";
7
+ import { CONNECTION_CHECK_TIMEOUT_MS, CONNECTION_RETRY_MAX_MS, CONNECTION_RETRY_MS } from "./utils/connection.js";
8
+ import { nextDelay } from "./utils/autoRefresh.js";
5
9
  import { createVerifyCache, runSessionGuard } from "./utils/sessionGuard.js";
6
10
  export default defineNuxtPlugin(async (_nuxtApp) => {
7
11
  const { systemApi } = useMongocampClientApi();
@@ -9,9 +13,21 @@ export default defineNuxtPlugin(async (_nuxtApp) => {
9
13
  const useGlobalAuthMiddleware = config.public.nuxtUiMongocampOptions.useGlobalAuthMiddleware ?? false;
10
14
  const useServerProxy = config.public.nuxtUiMongocampOptions.useServerProxy ?? false;
11
15
  const sessionGuard = config.public.nuxtUiMongocampOptions.sessionGuard ?? false;
16
+ const offline = config.public.nuxtUiMongocampOptions.offline ?? false;
12
17
  const sessionGuardVerify = (config.public.nuxtUiMongocampOptions.sessionGuardVerify ?? false) && import.meta.client;
13
18
  const verifyCache = createVerifyCache(3e4);
14
- const { data: version } = await useAsyncData("version", () => systemApi.version());
19
+ const { data: version } = offline && import.meta.client ? await useAsyncData("version", async () => {
20
+ const connection = useMongocampConnection();
21
+ try {
22
+ const result = await systemApi.version({ signal: AbortSignal.timeout(CONNECTION_CHECK_TIMEOUT_MS) });
23
+ connection.report();
24
+ return result;
25
+ } catch (error) {
26
+ connection.report(error);
27
+ return null;
28
+ }
29
+ }, { lazy: true, server: false }) : await useAsyncData("version", () => systemApi.version());
30
+ if (offline && import.meta.client) watchConnection();
15
31
  if (sessionGuard && !useServerProxy) {
16
32
  addRouteMiddleware("session-guard", async (to) => {
17
33
  const { checkExpiry, invalidateSession, verify } = useMongocampSession();
@@ -23,7 +39,9 @@ export default defineNuxtPlugin(async (_nuxtApp) => {
23
39
  invalidate: invalidateSession,
24
40
  verify: sessionGuardVerify ? () => verifyCache(String(useMongocampStorage().value?.token ?? ""), verify) : void 0,
25
41
  // a fresh call: it must read the session as it is after the invalidation
26
- isAllowed: (path) => useMongocampRoles().isAllowedPathForRoute(path)
42
+ isAllowed: (path) => useMongocampRoles().isAllowedPathForRoute(path),
43
+ // only asked when a session is about to be cleared, so it costs a request only for an expired token
44
+ serverReachable: offline ? async () => await useMongocampConnection().check() === "online" : void 0
27
45
  });
28
46
  if (outcome === "redirect") return navigateTo(loginPath);
29
47
  }, { global: true });
@@ -47,3 +65,37 @@ export default defineNuxtPlugin(async (_nuxtApp) => {
47
65
  }
48
66
  };
49
67
  });
68
+ function watchConnection() {
69
+ const connection = useMongocampConnection();
70
+ let timer;
71
+ let failures = 0;
72
+ function schedule() {
73
+ if (timer !== void 0) clearTimeout(timer);
74
+ timer = void 0;
75
+ if (connection.state.value !== "unreachable") {
76
+ failures = 0;
77
+ return;
78
+ }
79
+ timer = setTimeout(async () => {
80
+ timer = void 0;
81
+ failures++;
82
+ await connection.check();
83
+ schedule();
84
+ }, nextDelay(CONNECTION_RETRY_MS, failures, { maxMs: CONNECTION_RETRY_MAX_MS }));
85
+ }
86
+ async function checkNow() {
87
+ await connection.check();
88
+ schedule();
89
+ }
90
+ window.addEventListener("online", () => {
91
+ void checkNow();
92
+ });
93
+ window.addEventListener("offline", () => {
94
+ void connection.check();
95
+ schedule();
96
+ });
97
+ document.addEventListener("visibilitychange", () => {
98
+ if (!document.hidden && !connection.isOnline.value) void checkNow();
99
+ });
100
+ watch(connection.state, () => schedule());
101
+ }
@@ -2,3 +2,4 @@ export { formatBytes } from './utils/formatBytes.js';
2
2
  export { connectionUsage, formatCount, formatUptime } from './utils/serverInfo.js';
3
3
  export { groupCollectionNames } from './utils/collectionNames.js';
4
4
  export { bucketNameOf, isBucketMemberCollection, isProtectedCollection } from './utils/collectionProtection.js';
5
+ export { isNetworkFailure } from './utils/connection.js';
@@ -2,3 +2,4 @@ export { formatBytes } from "./utils/formatBytes.js";
2
2
  export { connectionUsage, formatCount, formatUptime } from "./utils/serverInfo.js";
3
3
  export { groupCollectionNames } from "./utils/collectionNames.js";
4
4
  export { bucketNameOf, isBucketMemberCollection, isProtectedCollection } from "./utils/collectionProtection.js";
5
+ export { isNetworkFailure } from "./utils/connection.js";
@@ -0,0 +1,23 @@
1
+ /**
2
+ * - `online`: the MongoCamp server answered recently.
3
+ * - `offline`: the browser itself reports no network.
4
+ * - `unreachable`: the browser has a network, but the server does not answer (e.g. a WLAN without internet, or the
5
+ * server is down). Also the state right after the browser reports a network again, until a check succeeds.
6
+ */
7
+ export type ConnectionState = 'online' | 'offline' | 'unreachable';
8
+ export type ConnectionEvent = 'browser-online' | 'browser-offline' | 'server-answered' | 'network-failure';
9
+ /** First wait between checks while the server cannot be reached; it doubles per failed check up to the ceiling. */
10
+ export declare const CONNECTION_RETRY_MS = 5000;
11
+ export declare const CONNECTION_RETRY_MAX_MS = 60000;
12
+ /** A check that takes longer than this counts as failed (a WLAN without internet can stall a request for minutes). */
13
+ export declare const CONNECTION_CHECK_TIMEOUT_MS = 5000;
14
+ export declare function nextConnectionState(current: ConnectionState, event: ConnectionEvent): ConnectionState;
15
+ /** The state to start with, from the browser's own flag (`navigator.onLine`); `undefined` (server side) counts as online. */
16
+ export declare function initialConnectionState(browserOnline: boolean | undefined): ConnectionState;
17
+ /**
18
+ * True when a request failed without any answer from the server: a network error, a timeout or an abort. An error that
19
+ * carries an HTTP status (401, 404, 500, ...) is an answer and therefore never a network failure — the server was there.
20
+ * Covers the generated MongoCamp client (`FetchError` with a `cause`, `ResponseError` with a `response`), ofetch/`$fetch`
21
+ * (`FetchError` with `statusCode` only when the server answered), plain `fetch` (`TypeError`) and `AbortSignal.timeout`.
22
+ */
23
+ export declare function isNetworkFailure(error: unknown): boolean;
@@ -0,0 +1,31 @@
1
+ export const CONNECTION_RETRY_MS = 5e3;
2
+ export const CONNECTION_RETRY_MAX_MS = 6e4;
3
+ export const CONNECTION_CHECK_TIMEOUT_MS = 5e3;
4
+ export function nextConnectionState(current, event) {
5
+ switch (event) {
6
+ case "browser-offline":
7
+ return "offline";
8
+ case "browser-online":
9
+ return current === "online" ? "online" : "unreachable";
10
+ case "server-answered":
11
+ return "online";
12
+ case "network-failure":
13
+ return current === "offline" ? "offline" : "unreachable";
14
+ }
15
+ }
16
+ export function initialConnectionState(browserOnline) {
17
+ return browserOnline === false ? "offline" : "online";
18
+ }
19
+ function statusOf(error) {
20
+ const response = error.response;
21
+ const responseStatus = typeof response === "object" && response !== null ? response.status : void 0;
22
+ return error.status ?? error.statusCode ?? responseStatus;
23
+ }
24
+ export function isNetworkFailure(error) {
25
+ if (typeof error !== "object" || error === null) return false;
26
+ const e = error;
27
+ if (statusOf(e) !== void 0) return false;
28
+ if (e.name === "AbortError" || e.name === "TimeoutError" || e.name === "FetchError") return true;
29
+ if (error instanceof TypeError) return true;
30
+ return e.cause !== void 0 && e.cause !== error && isNetworkFailure(e.cause);
31
+ }
@@ -7,6 +7,7 @@ interface SessionGuardDeps {
7
7
  invalidate: () => Promise<void>;
8
8
  verify?: () => Promise<VerifyResult>;
9
9
  isAllowed: (path: string) => boolean;
10
+ serverReachable?: () => Promise<boolean>;
10
11
  }
11
12
  export declare function runSessionGuard(deps: SessionGuardDeps): Promise<'continue' | 'redirect'>;
12
13
  export declare function createVerifyCache(ttlMs: number, now?: () => number): (key: string, run: () => Promise<VerifyResult>) => Promise<VerifyResult>;
@@ -1,6 +1,7 @@
1
1
  export async function runSessionGuard(deps) {
2
2
  const expiry = deps.checkExpiry();
3
3
  if (expiry !== "expired" && !(expiry === "valid" && deps.verify && await isRejectedByServer(deps.verify))) return "continue";
4
+ if (deps.serverReachable && !await isReachable(deps.serverReachable)) return "continue";
4
5
  try {
5
6
  await deps.invalidate();
6
7
  } catch {
@@ -9,6 +10,13 @@ export async function runSessionGuard(deps) {
9
10
  if (deps.path === deps.loginPath) return "continue";
10
11
  return deps.isAllowed(deps.path) ? "continue" : "redirect";
11
12
  }
13
+ async function isReachable(serverReachable) {
14
+ try {
15
+ return await serverReachable();
16
+ } catch {
17
+ return false;
18
+ }
19
+ }
12
20
  async function isRejectedByServer(verify) {
13
21
  try {
14
22
  return await verify() === "invalid";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sfxcode/nuxt-ui-mongocamp",
3
- "version": "1.5.6",
3
+ "version": "1.5.7",
4
4
  "description": "A Nuxt module that wraps @sfxcode/nuxt-mongocamp-server with ready-made UI components, composables, and a runtime plugin",
5
5
  "repository": "sfxcode/nuxt-ui-mongocamp",
6
6
  "homepage": "https://sfxcode.github.io/nuxt-ui-mongocamp/",