@keboola/api-client-react 36.0.0 → 40.0.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/CHANGELOG.md CHANGED
@@ -1,5 +1,37 @@
1
1
  # @keboola/api-client-react
2
2
 
3
+ ## 40.0.0
4
+
5
+ ### Major Changes
6
+
7
+ - Drop `AuthProvider` and `useAuth`, and add `useSessionState(session)` — the bearer session table as a re-rendering value, which is what the gates and panels that used to read the provider now subscribe to. `useSessionState` takes a `BearerSession` (the renamed `SessionClient`); its shape is unchanged. `LegacyAuthProvider` / `useLegacyAuth` are untouched.
8
+
9
+ ### Patch Changes
10
+
11
+ - Updated dependencies:
12
+ - @keboola/api-client@40.0.0
13
+
14
+ ## 39.0.0
15
+
16
+ ### Patch Changes
17
+
18
+ - Updated dependencies:
19
+ - @keboola/api-client@39.0.0
20
+
21
+ ## 38.0.0
22
+
23
+ ### Patch Changes
24
+
25
+ - Updated dependencies:
26
+ - @keboola/api-client@38.0.0
27
+
28
+ ## 37.0.0
29
+
30
+ ### Patch Changes
31
+
32
+ - Updated dependencies:
33
+ - @keboola/api-client@37.0.0
34
+
3
35
  ## 36.0.0
4
36
 
5
37
  ### Patch Changes
package/dist/index.cjs CHANGED
@@ -5,12 +5,9 @@ let react_jsx_runtime = require("react/jsx-runtime");
5
5
  const MISSING_API_CLIENT_ERROR = "useApiClient must be used within <ApiClientProvider />";
6
6
  const MISSING_PROJECT_ERROR = "useProject must be used within <ApiClientProvider />";
7
7
  const MISSING_STACK_ERROR = "useStack must be used within <ApiClientProvider />";
8
- const MISSING_AUTH_ERROR = "useAuth must be used within <AuthProvider />";
9
8
  const MISSING_LEGACY_AUTH_ERROR = "useLegacyAuth must be used within <LegacyAuthProvider />";
10
9
  const ApiContext = (0, react.createContext)(null);
11
10
  const ApiProvider = ApiContext;
12
- const AuthContext = (0, react.createContext)(null);
13
- const AuthContextProvider = AuthContext;
14
11
  const LegacyAuthContext = (0, react.createContext)(null);
15
12
  const LegacyAuthContextProvider = LegacyAuthContext;
16
13
  const useApiClient = () => {
@@ -28,12 +25,6 @@ const useStack = () => {
28
25
  if (api === null) throw new Error(MISSING_STACK_ERROR);
29
26
  return api.context.stack;
30
27
  };
31
- /** The bearer (OAuth) lifecycle session. Throws outside `<AuthProvider />`. */
32
- const useAuth = () => {
33
- const session = (0, react.use)(AuthContext);
34
- if (session === null) throw new Error(MISSING_AUTH_ERROR);
35
- return session;
36
- };
37
28
  /** The legacy (SAPI) lifecycle session. Throws outside `<LegacyAuthProvider />`. */
38
29
  const useLegacyAuth = () => {
39
30
  const session = (0, react.use)(LegacyAuthContext);
@@ -52,89 +43,9 @@ const ApiClientProvider = ({ api, children }) => /* @__PURE__ */ (0, react_jsx_r
52
43
  children
53
44
  });
54
45
  //#endregion
55
- //#region src/AuthProvider.tsx
56
- const AuthProvider = ({ session, baseUrl, credential, projectId, onAccessTokenChange, onRestore, loadingFallback = null, errorFallback = null, anonymousFallback = null, children }) => {
57
- const [snapshot, setSnapshot] = (0, react.useState)(() => session.debug());
58
- const [isRestoring, setIsRestoring] = (0, react.useState)(() => session.hasPersistedValue());
59
- const [restoreStatus, setRestoreStatus] = (0, react.useState)(null);
60
- const restoreStartedRef = (0, react.useRef)(false);
61
- const onRestoreRef = (0, react.useRef)(onRestore);
62
- (0, react.useEffect)(() => {
63
- onRestoreRef.current = onRestore;
64
- }, [onRestore]);
65
- (0, react.useEffect)(() => session.subscribe(setSnapshot), [session]);
66
- (0, react.useEffect)(() => {
67
- if (baseUrl === void 0) return;
68
- if (snapshot.config.baseUrl !== null) return;
69
- session.setBaseUrl(baseUrl);
70
- }, [
71
- session,
72
- baseUrl,
73
- snapshot.config.baseUrl
74
- ]);
75
- (0, react.useEffect)(() => {
76
- if (restoreStartedRef.current) return;
77
- restoreStartedRef.current = true;
78
- const reportCallbackFailure = (error) => console.error("Keboola bearer session onRestore callback failed", error);
79
- const settle = (result) => {
80
- setRestoreStatus(result.status);
81
- try {
82
- Promise.resolve(onRestoreRef.current?.(result)).catch(reportCallbackFailure);
83
- } catch (error) {
84
- reportCallbackFailure(error);
85
- }
86
- };
87
- session.restore().then(settle).catch((error) => {
88
- console.error("Keboola bearer session restore failed", error);
89
- settle({ status: "empty" });
90
- }).finally(() => setIsRestoring(false));
91
- }, [session]);
92
- (0, react.useEffect)(() => {
93
- if (restoreStatus === null || restoreStatus === "restored") return;
94
- if (credential === void 0) return;
95
- if (snapshot.config.status !== "anonymous") return;
96
- session.authenticate(credential);
97
- }, [
98
- session,
99
- restoreStatus,
100
- credential,
101
- snapshot.config.status
102
- ]);
103
- (0, react.useEffect)(() => {
104
- if (restoreStatus === null || restoreStatus === "restored") return;
105
- if (projectId === void 0) return;
106
- if (snapshot.config.status !== "authenticated") return;
107
- session.setProject(projectId);
108
- }, [
109
- session,
110
- restoreStatus,
111
- projectId,
112
- snapshot.config.status
113
- ]);
114
- const accessToken = snapshot.config.status === "anonymous" ? void 0 : snapshot.config.credential.accessToken;
115
- (0, react.useEffect)(() => {
116
- if (accessToken !== void 0) onAccessTokenChange?.(accessToken);
117
- }, [accessToken, onAccessTokenChange]);
118
- const isProgrammatic = credential !== void 0 && projectId !== void 0;
119
- const content = (() => {
120
- if (snapshot.storage === "ready") {
121
- if (typeof children !== "function") return children;
122
- if (snapshot.config.status !== "scoped") return null;
123
- const { projectId: scopedProjectId, baseUrl: scopedBaseUrl } = snapshot.config;
124
- return children({
125
- projectId: scopedProjectId,
126
- baseUrl: scopedBaseUrl
127
- });
128
- }
129
- if (snapshot.storage === "errored") return errorFallback;
130
- if (isRestoring || snapshot.storage === "pending" || isProgrammatic) return loadingFallback;
131
- return anonymousFallback;
132
- })();
133
- return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(AuthContextProvider, {
134
- value: session,
135
- children: content
136
- });
137
- };
46
+ //#region src/useSessionState.ts
47
+ /** The session table as a re-rendering value — the binding every gate and panel reads it through. */
48
+ const useSessionState = (session) => (0, react.useSyncExternalStore)(session.subscribe, session.getState);
138
49
  //#endregion
139
50
  //#region src/LegacyAuthProvider.tsx
140
51
  /**
@@ -170,12 +81,11 @@ const LegacyAuthProvider = ({ session, baseUrl, storageToken, managementToken, f
170
81
  };
171
82
  //#endregion
172
83
  exports.ApiClientProvider = ApiClientProvider;
173
- exports.AuthProvider = AuthProvider;
174
84
  exports.LegacyAuthProvider = LegacyAuthProvider;
175
85
  exports.useApiClient = useApiClient;
176
- exports.useAuth = useAuth;
177
86
  exports.useLegacyAuth = useLegacyAuth;
178
87
  exports.useProject = useProject;
88
+ exports.useSessionState = useSessionState;
179
89
  exports.useStack = useStack;
180
90
 
181
91
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["createContext","use","useState","useRef","useState","useRef"],"sources":["../src/context.ts","../src/ApiClientProvider.tsx","../src/AuthProvider.tsx","../src/LegacyAuthProvider.tsx"],"sourcesContent":["import { createContext, use } from 'react';\n\nimport type { BearerSession, KeboolaApi, LegacySession } from '@keboola/api-client';\n\nconst MISSING_API_CLIENT_ERROR = 'useApiClient must be used within <ApiClientProvider />';\nconst MISSING_PROJECT_ERROR = 'useProject must be used within <ApiClientProvider />';\nconst MISSING_STACK_ERROR = 'useStack must be used within <ApiClientProvider />';\nconst MISSING_AUTH_ERROR = 'useAuth must be used within <AuthProvider />';\nconst MISSING_LEGACY_AUTH_ERROR = 'useLegacyAuth must be used within <LegacyAuthProvider />';\n\n// The product API (`auth` + `management` + every product namespace), flow-agnostic. Both the\n// bearer and legacy flows produce the same `KeboolaApi` surface, so consumers never branch on flow.\nconst ApiContext = createContext<KeboolaApi | null>(null);\nexport const ApiProvider = ApiContext;\n\n// The lifecycle sessions live in their own, flow-specific contexts so the auth surface a component\n// reaches for is explicit. Only the matching provider is mounted per flow.\nconst AuthContext = createContext<BearerSession | null>(null);\nexport const AuthContextProvider = AuthContext;\n\nconst LegacyAuthContext = createContext<LegacySession | null>(null);\nexport const LegacyAuthContextProvider = LegacyAuthContext;\n\nexport const useApiClient = () => {\n const api = use(ApiContext);\n if (api === null) throw new Error(MISSING_API_CLIENT_ERROR);\n return api;\n};\n\nexport const useProject = () => {\n const api = use(ApiContext);\n if (api === null) throw new Error(MISSING_PROJECT_ERROR);\n return api.context.project;\n};\n\nexport const useStack = () => {\n const api = use(ApiContext);\n if (api === null) throw new Error(MISSING_STACK_ERROR);\n return api.context.stack;\n};\n\n/** The bearer (OAuth) lifecycle session. Throws outside `<AuthProvider />`. */\nexport const useAuth = () => {\n const session = use(AuthContext);\n if (session === null) throw new Error(MISSING_AUTH_ERROR);\n return session;\n};\n\n/** The legacy (SAPI) lifecycle session. Throws outside `<LegacyAuthProvider />`. */\nexport const useLegacyAuth = () => {\n const session = use(LegacyAuthContext);\n if (session === null) throw new Error(MISSING_LEGACY_AUTH_ERROR);\n return session;\n};\n","import type { ReactNode } from 'react';\n\nimport type { KeboolaApi } from '@keboola/api-client';\n\nimport { ApiProvider } from './context';\n\ntype Props = {\n /** The flow-agnostic product API — the `api` half of a keboola client. */\n api: KeboolaApi;\n children: ReactNode;\n};\n\n/**\n * Provides the product API to `useApiClient()`. A pure pass-through: the auth lifecycle (driving\n * to ready, gating on a fallback) belongs to `AuthProvider` / `LegacyAuthProvider`, which mount\n * this provider once their session is ready.\n */\nexport const ApiClientProvider = ({ api, children }: Props) => (\n <ApiProvider value={api}>{children}</ApiProvider>\n);\n","import { useEffect, useRef, useState } from 'react';\nimport type { ReactNode } from 'react';\n\nimport type { BearerSession } from '@keboola/api-client';\n\nimport { AuthContextProvider } from './context';\n\ntype BearerCredential = Parameters<BearerSession['authenticate']>[0];\ntype Snapshot = ReturnType<BearerSession['debug']>;\ntype RestoreResult = Awaited<ReturnType<BearerSession['restore']>>;\ntype RestoreStatus = RestoreResult['status'];\n\n/** The session state guaranteed to exist once the storage build is ready. */\ntype ScopedState = { projectId: number; baseUrl: string };\n\ntype BaseProps = {\n session: BearerSession;\n onAccessTokenChange?: (accessToken: string) => void;\n /**\n * Fires once with the outcome of the boot `restore()`.\n *\n * - `empty`, `restored` and `expired` are three different things to say to a user, and the slot\n * that renders cannot tell them apart: `expired` and `empty` both land in `anonymousFallback`,\n * and so does a `restored` session that carried no project.\n * - A `restore()` that throws (offline, a 5xx) reports `empty` — the same value the provider acts\n * on — so a caller never reads a transport failure as an expiry.\n */\n onRestore?: (result: RestoreResult) => void;\n /** Rendered while a persisted session is being restored, or the bootstrap is in flight. */\n loadingFallback?: ReactNode;\n /** Rendered when the storage build fails. */\n errorFallback?: ReactNode;\n /**\n * Rendered only once the session is scoped and the storage build is ready. Pass a function to\n * receive the scoped state (the project the session settled on) without re-narrowing it yourself.\n */\n children: ReactNode | ((scoped: ScopedState) => ReactNode);\n};\n\n/**\n * Two mutually exclusive bootstrap modes, discriminated by whether a credential is supplied:\n * - **programmatic** — `credential` + `projectId` given, so `baseUrl` is **required**: a credential\n * is bound to the stack that issued it and `authenticate` refuses an unconfigured session.\n * - **interactive** — none of the three given; the stack comes from the session instead — `restore()`\n * adopts the persisted one, otherwise the login UI sets it. `anonymousFallback` is **required**\n * here (a missing login UI would leave the app on a permanently blank screen).\n */\ntype Props = BaseProps &\n (\n | {\n credential: BearerCredential;\n projectId: number;\n baseUrl: string;\n anonymousFallback?: never;\n }\n | {\n credential?: undefined;\n projectId?: undefined;\n baseUrl?: never;\n anonymousFallback: ReactNode;\n }\n );\n\nexport const AuthProvider = ({\n session,\n baseUrl,\n credential,\n projectId,\n onAccessTokenChange,\n onRestore,\n loadingFallback = null,\n errorFallback = null,\n anonymousFallback = null,\n children,\n}: Props) => {\n const [snapshot, setSnapshot] = useState<Snapshot>(() => session.debug());\n const [isRestoring, setIsRestoring] = useState(() => session.hasPersistedValue());\n const [restoreStatus, setRestoreStatus] = useState<RestoreStatus | null>(null);\n const restoreStartedRef = useRef(false);\n // Held in a ref so the restore effect keeps `[session]` as its only dependency — a caller passing\n // an inline closure must not re-arm the restore. A passive effect is enough: the ref starts at the\n // mount-time callback, and `restore()` settles in a later microtask than any commit's effects, so\n // there is no window in which a stale closure could be the one called.\n const onRestoreRef = useRef(onRestore);\n useEffect(() => {\n onRestoreRef.current = onRestore;\n }, [onRestore]);\n\n useEffect(() => session.subscribe(setSnapshot), [session]);\n\n // Programmatic only. Interactive leaves the stack unset: `restore()` adopts the persisted one, and\n // failing that the login UI picks it — so there is nothing to configure up front.\n useEffect(() => {\n if (baseUrl === undefined) return;\n if (snapshot.config.baseUrl !== null) return;\n session.setBaseUrl(baseUrl);\n }, [session, baseUrl, snapshot.config.baseUrl]);\n\n // Runs regardless of whether a stack is configured — with none, `restore()` adopts the stack the\n // persisted session belongs to. (Declared after the effect above, so programmatic mode has already\n // configured its stack by the time this runs.) The ref guards StrictMode's double-invoked effect:\n // `restoreStatus` only lands asynchronously, so it cannot prevent a second synchronous call.\n useEffect(() => {\n if (restoreStartedRef.current) return;\n restoreStartedRef.current = true;\n const reportCallbackFailure = (error: unknown) =>\n console.error('Keboola bearer session onRestore callback failed', error);\n\n // The consumer's callback is isolated: it runs inside the promise chain, so a throw would\n // otherwise land in the `.catch` below — reporting a successful restore as a failure, logging a\n // lie, and calling `settle` a second time. `Promise.resolve` covers an `async` callback too:\n // TypeScript accepts one against this `void` return type, and its rejection would escape the\n // `try` as an unhandled rejection.\n const settle = (result: RestoreResult) => {\n setRestoreStatus(result.status);\n try {\n void Promise.resolve(onRestoreRef.current?.(result)).catch(reportCallbackFailure);\n } catch (error) {\n reportCallbackFailure(error);\n }\n };\n session\n .restore()\n .then(settle)\n .catch((error) => {\n console.error('Keboola bearer session restore failed', error);\n settle({ status: 'empty' });\n })\n .finally(() => setIsRestoring(false));\n }, [session]);\n\n useEffect(() => {\n if (restoreStatus === null || restoreStatus === 'restored') return;\n if (credential === undefined) return;\n if (snapshot.config.status !== 'anonymous') return;\n session.authenticate(credential);\n }, [session, restoreStatus, credential, snapshot.config.status]);\n\n useEffect(() => {\n if (restoreStatus === null || restoreStatus === 'restored') return;\n if (projectId === undefined) return;\n if (snapshot.config.status !== 'authenticated') return;\n session.setProject(projectId);\n }, [session, restoreStatus, projectId, snapshot.config.status]);\n\n const accessToken =\n snapshot.config.status === 'anonymous' ? undefined : snapshot.config.credential.accessToken;\n\n useEffect(() => {\n if (accessToken !== undefined) onAccessTokenChange?.(accessToken);\n }, [accessToken, onAccessTokenChange]);\n\n // Programmatic mode drives itself to ready, so it must never fall through to `anonymousFallback`.\n const isProgrammatic = credential !== undefined && projectId !== undefined;\n\n const content = (() => {\n if (snapshot.storage === 'ready') {\n if (typeof children !== 'function') return children;\n // A ready storage build implies a scoped session; narrowing here is for the type checker.\n if (snapshot.config.status !== 'scoped') return null;\n const { projectId: scopedProjectId, baseUrl: scopedBaseUrl } = snapshot.config;\n return children({ projectId: scopedProjectId, baseUrl: scopedBaseUrl });\n }\n if (snapshot.storage === 'errored') return errorFallback;\n if (isRestoring || snapshot.storage === 'pending' || isProgrammatic) return loadingFallback;\n return anonymousFallback;\n })();\n\n return <AuthContextProvider value={session}>{content}</AuthContextProvider>;\n};\n","import { useEffect, useRef, useState } from 'react';\nimport type { ReactNode } from 'react';\n\nimport type { LegacySession } from '@keboola/api-client';\n\nimport { LegacyAuthContextProvider } from './context';\n\ntype Props = {\n session: LegacySession;\n /** Stack base URL. */\n baseUrl: string;\n /** SAPI token — drives the storage build to ready. */\n storageToken: string;\n /** Optional manage-api token — unlocks `api.management`. */\n managementToken?: string;\n /** Rendered until the storage build reaches ready. */\n fallback?: ReactNode;\n /** Rendered when the storage build fails — e.g. the SAPI token is expired or revoked. */\n errorFallback?: ReactNode;\n children: ReactNode;\n};\n\n/**\n * Owns the legacy (SAPI) lifecycle: on mount it configures the stack and drives the session to\n * ready, rendering `fallback` until the storage build resolves. The backend-injected SAPI token is\n * known up front, so this drives itself (unlike the interactive bearer `AuthProvider`). Exposes the\n * session via `useLegacyAuth()` and gates `children` behind readiness.\n */\nexport const LegacyAuthProvider = ({\n session,\n baseUrl,\n storageToken,\n managementToken,\n fallback = null,\n errorFallback = fallback,\n children,\n}: Props) => {\n // The build state, not just readiness: `errored` and `pending` render differently.\n const [storageState, setStorageState] = useState(() => session.debug().storage);\n // Guards the once-only drive against React StrictMode's double-mounted effect.\n const startedRef = useRef<boolean>(false);\n\n useEffect(() => {\n const unsubscribe = session.subscribe((snapshot) => setStorageState(snapshot.storage));\n\n if (!startedRef.current) {\n startedRef.current = true;\n session.setBaseUrl(baseUrl);\n if (managementToken) session.authenticateManagement(managementToken);\n // Fire-and-forget: `subscribe` moves `storageState` once the build resolves. A failed build\n // resolves rather than rejects, so this catch only covers a synchronous throw.\n void session\n .authenticateStorageAsync(storageToken)\n .catch((error) => console.error('Keboola session bootstrap failed', error));\n }\n\n return unsubscribe;\n // drive to ready only on initial mount\n // oxlint-disable-next-line react/exhaustive-deps\n }, []);\n\n // The only place a failed build is observable — nothing rejects, so without this it is silent.\n useEffect(() => {\n if (storageState === 'errored') {\n console.error('Keboola session bootstrap failed: the storage build errored.');\n }\n }, [storageState]);\n\n const content = (() => {\n if (storageState === 'ready') return children;\n if (storageState === 'errored') return errorFallback;\n return fallback;\n })();\n\n return <LegacyAuthContextProvider value={session}>{content}</LegacyAuthContextProvider>;\n};\n"],"mappings":";;;;AAIA,MAAM,2BAA2B;AACjC,MAAM,wBAAwB;AAC9B,MAAM,sBAAsB;AAC5B,MAAM,qBAAqB;AAC3B,MAAM,4BAA4B;AAIlC,MAAM,cAAA,GAAaA,MAAAA,cAAAA,CAAiC,IAAI;AACxD,MAAa,cAAc;AAI3B,MAAM,eAAA,GAAcA,MAAAA,cAAAA,CAAoC,IAAI;AAC5D,MAAa,sBAAsB;AAEnC,MAAM,qBAAA,GAAoBA,MAAAA,cAAAA,CAAoC,IAAI;AAClE,MAAa,4BAA4B;AAEzC,MAAa,qBAAqB;CAChC,MAAM,OAAA,GAAMC,MAAAA,IAAAA,CAAI,UAAU;CAC1B,IAAI,QAAQ,MAAM,MAAM,IAAI,MAAM,wBAAwB;CAC1D,OAAO;AACT;AAEA,MAAa,m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AAY,CAAC,CACtC,OAAO,UAAU,QAAQ,MAAM,oCAAoC,KAAK,CAAC;EAC9E;EAEA,OAAO;CAGT,GAAG,CAAC,CAAC;CAGL,CAAA,GAAA,MAAA,UAAA,OAAgB;EACd,IAAI,iBAAiB,WACnB,QAAQ,MAAM,8DAA8D;CAEhF,GAAG,CAAC,YAAY,CAAC;CAQjB,OAAO,iBAAA,GAAA,kBAAA,IAAA,CAAC,2BAAD;EAA2B,OAAO;EANlB,iBAAA;GACrB,IAAI,iBAAiB,SAAS,OAAO;GACrC,IAAI,iBAAiB,WAAW,OAAO;GACvC,OAAO;EACT,EAAA,CAEyD;CAA6B,CAAA;AACxF"}
1
+ {"version":3,"file":"index.cjs","names":["createContext","use","useSyncExternalStore","useState","useRef"],"sources":["../src/context.ts","../src/ApiClientProvider.tsx","../src/useSessionState.ts","../src/LegacyAuthProvider.tsx"],"sourcesContent":["import { createContext, use } from 'react';\n\nimport type { KeboolaApi, LegacySession } from '@keboola/api-client';\n\nconst MISSING_API_CLIENT_ERROR = 'useApiClient must be used within <ApiClientProvider />';\nconst MISSING_PROJECT_ERROR = 'useProject must be used within <ApiClientProvider />';\nconst MISSING_STACK_ERROR = 'useStack must be used within <ApiClientProvider />';\nconst MISSING_LEGACY_AUTH_ERROR = 'useLegacyAuth must be used within <LegacyAuthProvider />';\n\n// The product API (`auth` + `management` + every product namespace), flow-agnostic. Both the\n// bearer and legacy flows produce the same `KeboolaApi` surface, so consumers never branch on flow.\nconst ApiContext = createContext<KeboolaApi | null>(null);\nexport const ApiProvider = ApiContext;\n\n// The legacy lifecycle session lives in its own context; the bearer flows read their table through\n// `useSessionState` instead.\nconst LegacyAuthContext = createContext<LegacySession | null>(null);\nexport const LegacyAuthContextProvider = LegacyAuthContext;\n\nexport const useApiClient = () => {\n const api = use(ApiContext);\n if (api === null) throw new Error(MISSING_API_CLIENT_ERROR);\n return api;\n};\n\nexport const useProject = () => {\n const api = use(ApiContext);\n if (api === null) throw new Error(MISSING_PROJECT_ERROR);\n return api.context.project;\n};\n\nexport const useStack = () => {\n const api = use(ApiContext);\n if (api === null) throw new Error(MISSING_STACK_ERROR);\n return api.context.stack;\n};\n\n/** The legacy (SAPI) lifecycle session. Throws outside `<LegacyAuthProvider />`. */\nexport const useLegacyAuth = () => {\n const session = use(LegacyAuthContext);\n if (session === null) throw new Error(MISSING_LEGACY_AUTH_ERROR);\n return session;\n};\n","import type { ReactNode } from 'react';\n\nimport type { KeboolaApi } from '@keboola/api-client';\n\nimport { ApiProvider } from './context';\n\ntype Props = {\n /** The flow-agnostic product API — the `api` half of a keboola client. */\n api: KeboolaApi;\n children: ReactNode;\n};\n\n/**\n * Provides the product API to `useApiClient()`. A pure pass-through: the auth lifecycle (driving\n * to ready, gating on a fallback) belongs to `AuthProvider` / `LegacyAuthProvider`, which mount\n * this provider once their session is ready.\n */\nexport const ApiClientProvider = ({ api, children }: Props) => (\n <ApiProvider value={api}>{children}</ApiProvider>\n);\n","import { useSyncExternalStore } from 'react';\n\nimport type { BearerSession } from '@keboola/api-client';\n\n/** The session table as a re-rendering value — the binding every gate and panel reads it through. */\nexport const useSessionState = (session: BearerSession) =>\n useSyncExternalStore(session.subscribe, session.getState);\n","import { useEffect, useRef, useState } from 'react';\nimport type { ReactNode } from 'react';\n\nimport type { LegacySession } from '@keboola/api-client';\n\nimport { LegacyAuthContextProvider } from './context';\n\ntype Props = {\n session: LegacySession;\n /** Stack base URL. */\n baseUrl: string;\n /** SAPI token — drives the storage build to ready. */\n storageToken: string;\n /** Optional manage-api token — unlocks `api.management`. */\n managementToken?: string;\n /** Rendered until the storage build reaches ready. */\n fallback?: ReactNode;\n /** Rendered when the storage build fails — e.g. the SAPI token is expired or revoked. */\n errorFallback?: ReactNode;\n children: ReactNode;\n};\n\n/**\n * Owns the legacy (SAPI) lifecycle: on mount it configures the stack and drives the session to\n * ready, rendering `fallback` until the storage build resolves. The backend-injected SAPI token is\n * known up front, so this drives itself (unlike the interactive bearer `AuthProvider`). Exposes the\n * session via `useLegacyAuth()` and gates `children` behind readiness.\n */\nexport const LegacyAuthProvider = ({\n session,\n baseUrl,\n storageToken,\n managementToken,\n fallback = null,\n errorFallback = fallback,\n children,\n}: Props) => {\n // The build state, not just readiness: `errored` and `pending` render differently.\n const [storageState, setStorageState] = useState(() => session.debug().storage);\n // Guards the once-only drive against React StrictMode's double-mounted effect.\n const startedRef = useRef<boolean>(false);\n\n useEffect(() => {\n const unsubscribe = session.subscribe((snapshot) => setStorageState(snapshot.storage));\n\n if (!startedRef.current) {\n startedRef.current = true;\n session.setBaseUrl(baseUrl);\n if (managementToken) session.authenticateManagement(managementToken);\n // Fire-and-forget: `subscribe` moves `storageState` once the build resolves. A failed build\n // resolves rather than rejects, so this catch only covers a synchronous throw.\n void session\n .authenticateStorageAsync(storageToken)\n .catch((error) => console.error('Keboola session bootstrap failed', error));\n }\n\n return unsubscribe;\n // drive to ready only on initial mount\n // oxlint-disable-next-line react/exhaustive-deps\n }, []);\n\n // The only place a failed build is observable — nothing rejects, so without this it is silent.\n useEffect(() => {\n if (storageState === 'errored') {\n console.error('Keboola session bootstrap failed: the storage build errored.');\n }\n }, [storageState]);\n\n const content = (() => {\n if (storageState === 'ready') return children;\n if (storageState === 'errored') return errorFallback;\n return fallback;\n })();\n\n return <LegacyAuthContextProvider value={session}>{content}</LegacyAuthContextProvider>;\n};\n"],"mappings":";;;;AAIA,MAAM,2BAA2B;AACjC,MAAM,wBAAwB;AAC9B,MAAM,sBAAsB;AAC5B,MAAM,4BAA4B;AAIlC,MAAM,cAAA,GAAaA,MAAAA,cAAAA,CAAiC,IAAI;AACxD,MAAa,cAAc;AAI3B,MAAM,qBAAA,GAAoBA,MAAAA,cAAAA,CAAoC,IAAI;AAClE,MAAa,4BAA4B;AAEzC,MAAa,qBAAqB;CAChC,MAAM,OAAA,GAAMC,MAAAA,IAAAA,CAAI,UAAU;CAC1B,IAAI,QAAQ,MAAM,MAAM,IAAI,MAAM,wBAAwB;CAC1D,OAAO;AACT;A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CAAC,CAAC;CAGL,CAAA,GAAA,MAAA,UAAA,OAAgB;EACd,IAAI,iBAAiB,WACnB,QAAQ,MAAM,8DAA8D;CAEhF,GAAG,CAAC,YAAY,CAAC;CAQjB,OAAO,iBAAA,GAAA,kBAAA,IAAA,CAAC,2BAAD;EAA2B,OAAO;EANlB,iBAAA;GACrB,IAAI,iBAAiB,SAAS,OAAO;GACrC,IAAI,iBAAiB,WAAW,OAAO;GACvC,OAAO;EACT,EAAA,CAEyD;CAA6B,CAAA;AACxF"}
package/dist/index.d.cts CHANGED
@@ -27,89 +27,6 @@ declare const useStack: () => {
27
27
  getComponent: (componentId: string) => import("@keboola/api-client/storage/types").StackComponent | null;
28
28
  hasComponent: (...componentId: string[]) => boolean;
29
29
  };
30
- /** The bearer (OAuth) lifecycle session. Throws outside `<AuthProvider />`. */
31
- declare const useAuth: () => {
32
- hasPersistedValue: () => boolean;
33
- setBaseUrl: (baseUrl: string) => void;
34
- isStorageReady: () => boolean;
35
- authenticate: (tokens: {
36
- accessToken: string;
37
- refreshToken: string;
38
- expiresIn: number;
39
- }) => void;
40
- setProject: (projectId: number) => void;
41
- setProjectAsync: (projectId: number) => Promise<void>;
42
- clearProject: () => void;
43
- forProject: (projectId: number) => Promise<import("@keboola/api-client").ProjectClients>;
44
- reset: () => void;
45
- debugForceRefresh: () => void;
46
- getAuthHeaders: (projectId?: number) => Promise<Record<string, string>>;
47
- restore: () => Promise<{
48
- status: 'empty' | 'restored' | 'expired';
49
- }>;
50
- subscribe: (listener: (snapshot: {
51
- type: 'Bearer';
52
- config: {
53
- status: 'anonymous';
54
- baseUrl: string | null;
55
- } | {
56
- status: 'authenticated';
57
- baseUrl: string;
58
- credential: {
59
- accessToken: string;
60
- refreshToken: string;
61
- expiresIn: number;
62
- } & {
63
- issuedAt: number;
64
- };
65
- } | {
66
- status: 'scoped';
67
- baseUrl: string;
68
- credential: {
69
- accessToken: string;
70
- refreshToken: string;
71
- expiresIn: number;
72
- } & {
73
- issuedAt: number;
74
- };
75
- projectId: number;
76
- };
77
- authReady: boolean;
78
- managementReady: boolean;
79
- storage: import("@keboola/api-client").AsyncState<unknown>['state'];
80
- }) => void) => () => void;
81
- debug: () => {
82
- type: 'Bearer';
83
- config: {
84
- status: 'anonymous';
85
- baseUrl: string | null;
86
- } | {
87
- status: 'authenticated';
88
- baseUrl: string;
89
- credential: {
90
- accessToken: string;
91
- refreshToken: string;
92
- expiresIn: number;
93
- } & {
94
- issuedAt: number;
95
- };
96
- } | {
97
- status: 'scoped';
98
- baseUrl: string;
99
- credential: {
100
- accessToken: string;
101
- refreshToken: string;
102
- expiresIn: number;
103
- } & {
104
- issuedAt: number;
105
- };
106
- projectId: number;
107
- };
108
- authReady: boolean;
109
- managementReady: boolean;
110
- storage: import("@keboola/api-client").AsyncState<unknown>['state'];
111
- };
112
- };
113
30
  /** The legacy (SAPI) lifecycle session. Throws outside `<LegacyAuthProvider />`. */
114
31
  declare const useLegacyAuth: () => {
115
32
  setBaseUrl: (baseUrl: string) => void;
@@ -142,7 +59,7 @@ declare const useLegacyAuth: () => {
142
59
  };
143
60
  //#endregion
144
61
  //#region src/ApiClientProvider.d.ts
145
- type Props$2 = {
62
+ type Props$1 = {
146
63
  /** The flow-agnostic product API — the `api` half of a keboola client. */
147
64
  api: KeboolaApi;
148
65
  children: ReactNode;
@@ -152,59 +69,11 @@ type Props$2 = {
152
69
  * to ready, gating on a fallback) belongs to `AuthProvider` / `LegacyAuthProvider`, which mount
153
70
  * this provider once their session is ready.
154
71
  */
155
- declare const ApiClientProvider: ({ api, children }: Props$2) => import("react/jsx-runtime").JSX.Element;
72
+ declare const ApiClientProvider: ({ api, children }: Props$1) => import("react").JSX.Element;
156
73
  //#endregion
157
- //#region src/AuthProvider.d.ts
158
- type BearerCredential = Parameters<BearerSession['authenticate']>[0];
159
- type RestoreResult = Awaited<ReturnType<BearerSession['restore']>>;
160
- /** The session state guaranteed to exist once the storage build is ready. */
161
- type ScopedState = {
162
- projectId: number;
163
- baseUrl: string;
164
- };
165
- type BaseProps = {
166
- session: BearerSession;
167
- onAccessTokenChange?: (accessToken: string) => void;
168
- /**
169
- * Fires once with the outcome of the boot `restore()`.
170
- *
171
- * - `empty`, `restored` and `expired` are three different things to say to a user, and the slot
172
- * that renders cannot tell them apart: `expired` and `empty` both land in `anonymousFallback`,
173
- * and so does a `restored` session that carried no project.
174
- * - A `restore()` that throws (offline, a 5xx) reports `empty` — the same value the provider acts
175
- * on — so a caller never reads a transport failure as an expiry.
176
- */
177
- onRestore?: (result: RestoreResult) => void;
178
- /** Rendered while a persisted session is being restored, or the bootstrap is in flight. */
179
- loadingFallback?: ReactNode;
180
- /** Rendered when the storage build fails. */
181
- errorFallback?: ReactNode;
182
- /**
183
- * Rendered only once the session is scoped and the storage build is ready. Pass a function to
184
- * receive the scoped state (the project the session settled on) without re-narrowing it yourself.
185
- */
186
- children: ReactNode | ((scoped: ScopedState) => ReactNode);
187
- };
188
- /**
189
- * Two mutually exclusive bootstrap modes, discriminated by whether a credential is supplied:
190
- * - **programmatic** — `credential` + `projectId` given, so `baseUrl` is **required**: a credential
191
- * is bound to the stack that issued it and `authenticate` refuses an unconfigured session.
192
- * - **interactive** — none of the three given; the stack comes from the session instead — `restore()`
193
- * adopts the persisted one, otherwise the login UI sets it. `anonymousFallback` is **required**
194
- * here (a missing login UI would leave the app on a permanently blank screen).
195
- */
196
- type Props$1 = BaseProps & ({
197
- credential: BearerCredential;
198
- projectId: number;
199
- baseUrl: string;
200
- anonymousFallback?: never;
201
- } | {
202
- credential?: undefined;
203
- projectId?: undefined;
204
- baseUrl?: never;
205
- anonymousFallback: ReactNode;
206
- });
207
- declare const AuthProvider: ({ session, baseUrl, credential, projectId, onAccessTokenChange, onRestore, loadingFallback, errorFallback, anonymousFallback, children }: Props$1) => import("react/jsx-runtime").JSX.Element;
74
+ //#region src/useSessionState.d.ts
75
+ /** The session table as a re-rendering value — the binding every gate and panel reads it through. */
76
+ declare const useSessionState: (session: BearerSession) => import("@keboola/api-client").SessionState;
208
77
  //#endregion
209
78
  //#region src/LegacyAuthProvider.d.ts
210
79
  type Props = {
@@ -227,7 +96,7 @@ type Props = {
227
96
  * known up front, so this drives itself (unlike the interactive bearer `AuthProvider`). Exposes the
228
97
  * session via `useLegacyAuth()` and gates `children` behind readiness.
229
98
  */
230
- declare const LegacyAuthProvider: ({ session, baseUrl, storageToken, managementToken, fallback, errorFallback, children }: Props) => import("react/jsx-runtime").JSX.Element;
99
+ declare const LegacyAuthProvider: ({ session, baseUrl, storageToken, managementToken, fallback, errorFallback, children }: Props) => import("react").JSX.Element;
231
100
  //#endregion
232
- export { ApiClientProvider, AuthProvider, LegacyAuthProvider, useApiClient, useAuth, useLegacyAuth, useProject, useStack };
101
+ export { ApiClientProvider, LegacyAuthProvider, useApiClient, useLegacyAuth, useProject, useSessionState, useStack };
233
102
  //# sourceMappingURL=index.d.cts.map
package/dist/index.d.ts CHANGED
@@ -27,89 +27,6 @@ declare const useStack: () => {
27
27
  getComponent: (componentId: string) => import("@keboola/api-client/storage/types").StackComponent | null;
28
28
  hasComponent: (...componentId: string[]) => boolean;
29
29
  };
30
- /** The bearer (OAuth) lifecycle session. Throws outside `<AuthProvider />`. */
31
- declare const useAuth: () => {
32
- hasPersistedValue: () => boolean;
33
- setBaseUrl: (baseUrl: string) => void;
34
- isStorageReady: () => boolean;
35
- authenticate: (tokens: {
36
- accessToken: string;
37
- refreshToken: string;
38
- expiresIn: number;
39
- }) => void;
40
- setProject: (projectId: number) => void;
41
- setProjectAsync: (projectId: number) => Promise<void>;
42
- clearProject: () => void;
43
- forProject: (projectId: number) => Promise<import("@keboola/api-client").ProjectClients>;
44
- reset: () => void;
45
- debugForceRefresh: () => void;
46
- getAuthHeaders: (projectId?: number) => Promise<Record<string, string>>;
47
- restore: () => Promise<{
48
- status: 'empty' | 'restored' | 'expired';
49
- }>;
50
- subscribe: (listener: (snapshot: {
51
- type: 'Bearer';
52
- config: {
53
- status: 'anonymous';
54
- baseUrl: string | null;
55
- } | {
56
- status: 'authenticated';
57
- baseUrl: string;
58
- credential: {
59
- accessToken: string;
60
- refreshToken: string;
61
- expiresIn: number;
62
- } & {
63
- issuedAt: number;
64
- };
65
- } | {
66
- status: 'scoped';
67
- baseUrl: string;
68
- credential: {
69
- accessToken: string;
70
- refreshToken: string;
71
- expiresIn: number;
72
- } & {
73
- issuedAt: number;
74
- };
75
- projectId: number;
76
- };
77
- authReady: boolean;
78
- managementReady: boolean;
79
- storage: import("@keboola/api-client").AsyncState<unknown>['state'];
80
- }) => void) => () => void;
81
- debug: () => {
82
- type: 'Bearer';
83
- config: {
84
- status: 'anonymous';
85
- baseUrl: string | null;
86
- } | {
87
- status: 'authenticated';
88
- baseUrl: string;
89
- credential: {
90
- accessToken: string;
91
- refreshToken: string;
92
- expiresIn: number;
93
- } & {
94
- issuedAt: number;
95
- };
96
- } | {
97
- status: 'scoped';
98
- baseUrl: string;
99
- credential: {
100
- accessToken: string;
101
- refreshToken: string;
102
- expiresIn: number;
103
- } & {
104
- issuedAt: number;
105
- };
106
- projectId: number;
107
- };
108
- authReady: boolean;
109
- managementReady: boolean;
110
- storage: import("@keboola/api-client").AsyncState<unknown>['state'];
111
- };
112
- };
113
30
  /** The legacy (SAPI) lifecycle session. Throws outside `<LegacyAuthProvider />`. */
114
31
  declare const useLegacyAuth: () => {
115
32
  setBaseUrl: (baseUrl: string) => void;
@@ -142,7 +59,7 @@ declare const useLegacyAuth: () => {
142
59
  };
143
60
  //#endregion
144
61
  //#region src/ApiClientProvider.d.ts
145
- type Props$2 = {
62
+ type Props$1 = {
146
63
  /** The flow-agnostic product API — the `api` half of a keboola client. */
147
64
  api: KeboolaApi;
148
65
  children: ReactNode;
@@ -152,59 +69,11 @@ type Props$2 = {
152
69
  * to ready, gating on a fallback) belongs to `AuthProvider` / `LegacyAuthProvider`, which mount
153
70
  * this provider once their session is ready.
154
71
  */
155
- declare const ApiClientProvider: ({ api, children }: Props$2) => import("react/jsx-runtime").JSX.Element;
72
+ declare const ApiClientProvider: ({ api, children }: Props$1) => import("react").JSX.Element;
156
73
  //#endregion
157
- //#region src/AuthProvider.d.ts
158
- type BearerCredential = Parameters<BearerSession['authenticate']>[0];
159
- type RestoreResult = Awaited<ReturnType<BearerSession['restore']>>;
160
- /** The session state guaranteed to exist once the storage build is ready. */
161
- type ScopedState = {
162
- projectId: number;
163
- baseUrl: string;
164
- };
165
- type BaseProps = {
166
- session: BearerSession;
167
- onAccessTokenChange?: (accessToken: string) => void;
168
- /**
169
- * Fires once with the outcome of the boot `restore()`.
170
- *
171
- * - `empty`, `restored` and `expired` are three different things to say to a user, and the slot
172
- * that renders cannot tell them apart: `expired` and `empty` both land in `anonymousFallback`,
173
- * and so does a `restored` session that carried no project.
174
- * - A `restore()` that throws (offline, a 5xx) reports `empty` — the same value the provider acts
175
- * on — so a caller never reads a transport failure as an expiry.
176
- */
177
- onRestore?: (result: RestoreResult) => void;
178
- /** Rendered while a persisted session is being restored, or the bootstrap is in flight. */
179
- loadingFallback?: ReactNode;
180
- /** Rendered when the storage build fails. */
181
- errorFallback?: ReactNode;
182
- /**
183
- * Rendered only once the session is scoped and the storage build is ready. Pass a function to
184
- * receive the scoped state (the project the session settled on) without re-narrowing it yourself.
185
- */
186
- children: ReactNode | ((scoped: ScopedState) => ReactNode);
187
- };
188
- /**
189
- * Two mutually exclusive bootstrap modes, discriminated by whether a credential is supplied:
190
- * - **programmatic** — `credential` + `projectId` given, so `baseUrl` is **required**: a credential
191
- * is bound to the stack that issued it and `authenticate` refuses an unconfigured session.
192
- * - **interactive** — none of the three given; the stack comes from the session instead — `restore()`
193
- * adopts the persisted one, otherwise the login UI sets it. `anonymousFallback` is **required**
194
- * here (a missing login UI would leave the app on a permanently blank screen).
195
- */
196
- type Props$1 = BaseProps & ({
197
- credential: BearerCredential;
198
- projectId: number;
199
- baseUrl: string;
200
- anonymousFallback?: never;
201
- } | {
202
- credential?: undefined;
203
- projectId?: undefined;
204
- baseUrl?: never;
205
- anonymousFallback: ReactNode;
206
- });
207
- declare const AuthProvider: ({ session, baseUrl, credential, projectId, onAccessTokenChange, onRestore, loadingFallback, errorFallback, anonymousFallback, children }: Props$1) => import("react/jsx-runtime").JSX.Element;
74
+ //#region src/useSessionState.d.ts
75
+ /** The session table as a re-rendering value — the binding every gate and panel reads it through. */
76
+ declare const useSessionState: (session: BearerSession) => import("@keboola/api-client").SessionState;
208
77
  //#endregion
209
78
  //#region src/LegacyAuthProvider.d.ts
210
79
  type Props = {
@@ -227,7 +96,7 @@ type Props = {
227
96
  * known up front, so this drives itself (unlike the interactive bearer `AuthProvider`). Exposes the
228
97
  * session via `useLegacyAuth()` and gates `children` behind readiness.
229
98
  */
230
- declare const LegacyAuthProvider: ({ session, baseUrl, storageToken, managementToken, fallback, errorFallback, children }: Props) => import("react/jsx-runtime").JSX.Element;
99
+ declare const LegacyAuthProvider: ({ session, baseUrl, storageToken, managementToken, fallback, errorFallback, children }: Props) => import("react").JSX.Element;
231
100
  //#endregion
232
- export { ApiClientProvider, AuthProvider, LegacyAuthProvider, useApiClient, useAuth, useLegacyAuth, useProject, useStack };
101
+ export { ApiClientProvider, LegacyAuthProvider, useApiClient, useLegacyAuth, useProject, useSessionState, useStack };
233
102
  //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -1,15 +1,12 @@
1
- import { createContext, use, useEffect, useRef, useState } from "react";
1
+ import { createContext, use, useEffect, useRef, useState, useSyncExternalStore } from "react";
2
2
  import { jsx } from "react/jsx-runtime";
3
3
  //#region src/context.ts
4
4
  const MISSING_API_CLIENT_ERROR = "useApiClient must be used within <ApiClientProvider />";
5
5
  const MISSING_PROJECT_ERROR = "useProject must be used within <ApiClientProvider />";
6
6
  const MISSING_STACK_ERROR = "useStack must be used within <ApiClientProvider />";
7
- const MISSING_AUTH_ERROR = "useAuth must be used within <AuthProvider />";
8
7
  const MISSING_LEGACY_AUTH_ERROR = "useLegacyAuth must be used within <LegacyAuthProvider />";
9
8
  const ApiContext = createContext(null);
10
9
  const ApiProvider = ApiContext;
11
- const AuthContext = createContext(null);
12
- const AuthContextProvider = AuthContext;
13
10
  const LegacyAuthContext = createContext(null);
14
11
  const LegacyAuthContextProvider = LegacyAuthContext;
15
12
  const useApiClient = () => {
@@ -27,12 +24,6 @@ const useStack = () => {
27
24
  if (api === null) throw new Error(MISSING_STACK_ERROR);
28
25
  return api.context.stack;
29
26
  };
30
- /** The bearer (OAuth) lifecycle session. Throws outside `<AuthProvider />`. */
31
- const useAuth = () => {
32
- const session = use(AuthContext);
33
- if (session === null) throw new Error(MISSING_AUTH_ERROR);
34
- return session;
35
- };
36
27
  /** The legacy (SAPI) lifecycle session. Throws outside `<LegacyAuthProvider />`. */
37
28
  const useLegacyAuth = () => {
38
29
  const session = use(LegacyAuthContext);
@@ -51,89 +42,9 @@ const ApiClientProvider = ({ api, children }) => /* @__PURE__ */ jsx(ApiProvider
51
42
  children
52
43
  });
53
44
  //#endregion
54
- //#region src/AuthProvider.tsx
55
- const AuthProvider = ({ session, baseUrl, credential, projectId, onAccessTokenChange, onRestore, loadingFallback = null, errorFallback = null, anonymousFallback = null, children }) => {
56
- const [snapshot, setSnapshot] = useState(() => session.debug());
57
- const [isRestoring, setIsRestoring] = useState(() => session.hasPersistedValue());
58
- const [restoreStatus, setRestoreStatus] = useState(null);
59
- const restoreStartedRef = useRef(false);
60
- const onRestoreRef = useRef(onRestore);
61
- useEffect(() => {
62
- onRestoreRef.current = onRestore;
63
- }, [onRestore]);
64
- useEffect(() => session.subscribe(setSnapshot), [session]);
65
- useEffect(() => {
66
- if (baseUrl === void 0) return;
67
- if (snapshot.config.baseUrl !== null) return;
68
- session.setBaseUrl(baseUrl);
69
- }, [
70
- session,
71
- baseUrl,
72
- snapshot.config.baseUrl
73
- ]);
74
- useEffect(() => {
75
- if (restoreStartedRef.current) return;
76
- restoreStartedRef.current = true;
77
- const reportCallbackFailure = (error) => console.error("Keboola bearer session onRestore callback failed", error);
78
- const settle = (result) => {
79
- setRestoreStatus(result.status);
80
- try {
81
- Promise.resolve(onRestoreRef.current?.(result)).catch(reportCallbackFailure);
82
- } catch (error) {
83
- reportCallbackFailure(error);
84
- }
85
- };
86
- session.restore().then(settle).catch((error) => {
87
- console.error("Keboola bearer session restore failed", error);
88
- settle({ status: "empty" });
89
- }).finally(() => setIsRestoring(false));
90
- }, [session]);
91
- useEffect(() => {
92
- if (restoreStatus === null || restoreStatus === "restored") return;
93
- if (credential === void 0) return;
94
- if (snapshot.config.status !== "anonymous") return;
95
- session.authenticate(credential);
96
- }, [
97
- session,
98
- restoreStatus,
99
- credential,
100
- snapshot.config.status
101
- ]);
102
- useEffect(() => {
103
- if (restoreStatus === null || restoreStatus === "restored") return;
104
- if (projectId === void 0) return;
105
- if (snapshot.config.status !== "authenticated") return;
106
- session.setProject(projectId);
107
- }, [
108
- session,
109
- restoreStatus,
110
- projectId,
111
- snapshot.config.status
112
- ]);
113
- const accessToken = snapshot.config.status === "anonymous" ? void 0 : snapshot.config.credential.accessToken;
114
- useEffect(() => {
115
- if (accessToken !== void 0) onAccessTokenChange?.(accessToken);
116
- }, [accessToken, onAccessTokenChange]);
117
- const isProgrammatic = credential !== void 0 && projectId !== void 0;
118
- const content = (() => {
119
- if (snapshot.storage === "ready") {
120
- if (typeof children !== "function") return children;
121
- if (snapshot.config.status !== "scoped") return null;
122
- const { projectId: scopedProjectId, baseUrl: scopedBaseUrl } = snapshot.config;
123
- return children({
124
- projectId: scopedProjectId,
125
- baseUrl: scopedBaseUrl
126
- });
127
- }
128
- if (snapshot.storage === "errored") return errorFallback;
129
- if (isRestoring || snapshot.storage === "pending" || isProgrammatic) return loadingFallback;
130
- return anonymousFallback;
131
- })();
132
- return /* @__PURE__ */ jsx(AuthContextProvider, {
133
- value: session,
134
- children: content
135
- });
136
- };
45
+ //#region src/useSessionState.ts
46
+ /** The session table as a re-rendering value — the binding every gate and panel reads it through. */
47
+ const useSessionState = (session) => useSyncExternalStore(session.subscribe, session.getState);
137
48
  //#endregion
138
49
  //#region src/LegacyAuthProvider.tsx
139
50
  /**
@@ -168,6 +79,6 @@ const LegacyAuthProvider = ({ session, baseUrl, storageToken, managementToken, f
168
79
  });
169
80
  };
170
81
  //#endregion
171
- export { ApiClientProvider, AuthProvider, LegacyAuthProvider, useApiClient, useAuth, useLegacyAuth, useProject, useStack };
82
+ export { ApiClientProvider, LegacyAuthProvider, useApiClient, useLegacyAuth, useProject, useSessionState, useStack };
172
83
 
173
84
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/context.ts","../src/ApiClientProvider.tsx","../src/AuthProvider.tsx","../src/LegacyAuthProvider.tsx"],"sourcesContent":["import { createContext, use } from 'react';\n\nimport type { BearerSession, KeboolaApi, LegacySession } from '@keboola/api-client';\n\nconst MISSING_API_CLIENT_ERROR = 'useApiClient must be used within <ApiClientProvider />';\nconst MISSING_PROJECT_ERROR = 'useProject must be used within <ApiClientProvider />';\nconst MISSING_STACK_ERROR = 'useStack must be used within <ApiClientProvider />';\nconst MISSING_AUTH_ERROR = 'useAuth must be used within <AuthProvider />';\nconst MISSING_LEGACY_AUTH_ERROR = 'useLegacyAuth must be used within <LegacyAuthProvider />';\n\n// The product API (`auth` + `management` + every product namespace), flow-agnostic. Both the\n// bearer and legacy flows produce the same `KeboolaApi` surface, so consumers never branch on flow.\nconst ApiContext = createContext<KeboolaApi | null>(null);\nexport const ApiProvider = ApiContext;\n\n// The lifecycle sessions live in their own, flow-specific contexts so the auth surface a component\n// reaches for is explicit. Only the matching provider is mounted per flow.\nconst AuthContext = createContext<BearerSession | null>(null);\nexport const AuthContextProvider = AuthContext;\n\nconst LegacyAuthContext = createContext<LegacySession | null>(null);\nexport const LegacyAuthContextProvider = LegacyAuthContext;\n\nexport const useApiClient = () => {\n const api = use(ApiContext);\n if (api === null) throw new Error(MISSING_API_CLIENT_ERROR);\n return api;\n};\n\nexport const useProject = () => {\n const api = use(ApiContext);\n if (api === null) throw new Error(MISSING_PROJECT_ERROR);\n return api.context.project;\n};\n\nexport const useStack = () => {\n const api = use(ApiContext);\n if (api === null) throw new Error(MISSING_STACK_ERROR);\n return api.context.stack;\n};\n\n/** The bearer (OAuth) lifecycle session. Throws outside `<AuthProvider />`. */\nexport const useAuth = () => {\n const session = use(AuthContext);\n if (session === null) throw new Error(MISSING_AUTH_ERROR);\n return session;\n};\n\n/** The legacy (SAPI) lifecycle session. Throws outside `<LegacyAuthProvider />`. */\nexport const useLegacyAuth = () => {\n const session = use(LegacyAuthContext);\n if (session === null) throw new Error(MISSING_LEGACY_AUTH_ERROR);\n return session;\n};\n","import type { ReactNode } from 'react';\n\nimport type { KeboolaApi } from '@keboola/api-client';\n\nimport { ApiProvider } from './context';\n\ntype Props = {\n /** The flow-agnostic product API — the `api` half of a keboola client. */\n api: KeboolaApi;\n children: ReactNode;\n};\n\n/**\n * Provides the product API to `useApiClient()`. A pure pass-through: the auth lifecycle (driving\n * to ready, gating on a fallback) belongs to `AuthProvider` / `LegacyAuthProvider`, which mount\n * this provider once their session is ready.\n */\nexport const ApiClientProvider = ({ api, children }: Props) => (\n <ApiProvider value={api}>{children}</ApiProvider>\n);\n","import { useEffect, useRef, useState } from 'react';\nimport type { ReactNode } from 'react';\n\nimport type { BearerSession } from '@keboola/api-client';\n\nimport { AuthContextProvider } from './context';\n\ntype BearerCredential = Parameters<BearerSession['authenticate']>[0];\ntype Snapshot = ReturnType<BearerSession['debug']>;\ntype RestoreResult = Awaited<ReturnType<BearerSession['restore']>>;\ntype RestoreStatus = RestoreResult['status'];\n\n/** The session state guaranteed to exist once the storage build is ready. */\ntype ScopedState = { projectId: number; baseUrl: string };\n\ntype BaseProps = {\n session: BearerSession;\n onAccessTokenChange?: (accessToken: string) => void;\n /**\n * Fires once with the outcome of the boot `restore()`.\n *\n * - `empty`, `restored` and `expired` are three different things to say to a user, and the slot\n * that renders cannot tell them apart: `expired` and `empty` both land in `anonymousFallback`,\n * and so does a `restored` session that carried no project.\n * - A `restore()` that throws (offline, a 5xx) reports `empty` — the same value the provider acts\n * on — so a caller never reads a transport failure as an expiry.\n */\n onRestore?: (result: RestoreResult) => void;\n /** Rendered while a persisted session is being restored, or the bootstrap is in flight. */\n loadingFallback?: ReactNode;\n /** Rendered when the storage build fails. */\n errorFallback?: ReactNode;\n /**\n * Rendered only once the session is scoped and the storage build is ready. Pass a function to\n * receive the scoped state (the project the session settled on) without re-narrowing it yourself.\n */\n children: ReactNode | ((scoped: ScopedState) => ReactNode);\n};\n\n/**\n * Two mutually exclusive bootstrap modes, discriminated by whether a credential is supplied:\n * - **programmatic** — `credential` + `projectId` given, so `baseUrl` is **required**: a credential\n * is bound to the stack that issued it and `authenticate` refuses an unconfigured session.\n * - **interactive** — none of the three given; the stack comes from the session instead — `restore()`\n * adopts the persisted one, otherwise the login UI sets it. `anonymousFallback` is **required**\n * here (a missing login UI would leave the app on a permanently blank screen).\n */\ntype Props = BaseProps &\n (\n | {\n credential: BearerCredential;\n projectId: number;\n baseUrl: string;\n anonymousFallback?: never;\n }\n | {\n credential?: undefined;\n projectId?: undefined;\n baseUrl?: never;\n anonymousFallback: ReactNode;\n }\n );\n\nexport const AuthProvider = ({\n session,\n baseUrl,\n credential,\n projectId,\n onAccessTokenChange,\n onRestore,\n loadingFallback = null,\n errorFallback = null,\n anonymousFallback = null,\n children,\n}: Props) => {\n const [snapshot, setSnapshot] = useState<Snapshot>(() => session.debug());\n const [isRestoring, setIsRestoring] = useState(() => session.hasPersistedValue());\n const [restoreStatus, setRestoreStatus] = useState<RestoreStatus | null>(null);\n const restoreStartedRef = useRef(false);\n // Held in a ref so the restore effect keeps `[session]` as its only dependency — a caller passing\n // an inline closure must not re-arm the restore. A passive effect is enough: the ref starts at the\n // mount-time callback, and `restore()` settles in a later microtask than any commit's effects, so\n // there is no window in which a stale closure could be the one called.\n const onRestoreRef = useRef(onRestore);\n useEffect(() => {\n onRestoreRef.current = onRestore;\n }, [onRestore]);\n\n useEffect(() => session.subscribe(setSnapshot), [session]);\n\n // Programmatic only. Interactive leaves the stack unset: `restore()` adopts the persisted one, and\n // failing that the login UI picks it — so there is nothing to configure up front.\n useEffect(() => {\n if (baseUrl === undefined) return;\n if (snapshot.config.baseUrl !== null) return;\n session.setBaseUrl(baseUrl);\n }, [session, baseUrl, snapshot.config.baseUrl]);\n\n // Runs regardless of whether a stack is configured — with none, `restore()` adopts the stack the\n // persisted session belongs to. (Declared after the effect above, so programmatic mode has already\n // configured its stack by the time this runs.) The ref guards StrictMode's double-invoked effect:\n // `restoreStatus` only lands asynchronously, so it cannot prevent a second synchronous call.\n useEffect(() => {\n if (restoreStartedRef.current) return;\n restoreStartedRef.current = true;\n const reportCallbackFailure = (error: unknown) =>\n console.error('Keboola bearer session onRestore callback failed', error);\n\n // The consumer's callback is isolated: it runs inside the promise chain, so a throw would\n // otherwise land in the `.catch` below — reporting a successful restore as a failure, logging a\n // lie, and calling `settle` a second time. `Promise.resolve` covers an `async` callback too:\n // TypeScript accepts one against this `void` return type, and its rejection would escape the\n // `try` as an unhandled rejection.\n const settle = (result: RestoreResult) => {\n setRestoreStatus(result.status);\n try {\n void Promise.resolve(onRestoreRef.current?.(result)).catch(reportCallbackFailure);\n } catch (error) {\n reportCallbackFailure(error);\n }\n };\n session\n .restore()\n .then(settle)\n .catch((error) => {\n console.error('Keboola bearer session restore failed', error);\n settle({ status: 'empty' });\n })\n .finally(() => setIsRestoring(false));\n }, [session]);\n\n useEffect(() => {\n if (restoreStatus === null || restoreStatus === 'restored') return;\n if (credential === undefined) return;\n if (snapshot.config.status !== 'anonymous') return;\n session.authenticate(credential);\n }, [session, restoreStatus, credential, snapshot.config.status]);\n\n useEffect(() => {\n if (restoreStatus === null || restoreStatus === 'restored') return;\n if (projectId === undefined) return;\n if (snapshot.config.status !== 'authenticated') return;\n session.setProject(projectId);\n }, [session, restoreStatus, projectId, snapshot.config.status]);\n\n const accessToken =\n snapshot.config.status === 'anonymous' ? undefined : snapshot.config.credential.accessToken;\n\n useEffect(() => {\n if (accessToken !== undefined) onAccessTokenChange?.(accessToken);\n }, [accessToken, onAccessTokenChange]);\n\n // Programmatic mode drives itself to ready, so it must never fall through to `anonymousFallback`.\n const isProgrammatic = credential !== undefined && projectId !== undefined;\n\n const content = (() => {\n if (snapshot.storage === 'ready') {\n if (typeof children !== 'function') return children;\n // A ready storage build implies a scoped session; narrowing here is for the type checker.\n if (snapshot.config.status !== 'scoped') return null;\n const { projectId: scopedProjectId, baseUrl: scopedBaseUrl } = snapshot.config;\n return children({ projectId: scopedProjectId, baseUrl: scopedBaseUrl });\n }\n if (snapshot.storage === 'errored') return errorFallback;\n if (isRestoring || snapshot.storage === 'pending' || isProgrammatic) return loadingFallback;\n return anonymousFallback;\n })();\n\n return <AuthContextProvider value={session}>{content}</AuthContextProvider>;\n};\n","import { useEffect, useRef, useState } from 'react';\nimport type { ReactNode } from 'react';\n\nimport type { LegacySession } from '@keboola/api-client';\n\nimport { LegacyAuthContextProvider } from './context';\n\ntype Props = {\n session: LegacySession;\n /** Stack base URL. */\n baseUrl: string;\n /** SAPI token — drives the storage build to ready. */\n storageToken: string;\n /** Optional manage-api token — unlocks `api.management`. */\n managementToken?: string;\n /** Rendered until the storage build reaches ready. */\n fallback?: ReactNode;\n /** Rendered when the storage build fails — e.g. the SAPI token is expired or revoked. */\n errorFallback?: ReactNode;\n children: ReactNode;\n};\n\n/**\n * Owns the legacy (SAPI) lifecycle: on mount it configures the stack and drives the session to\n * ready, rendering `fallback` until the storage build resolves. The backend-injected SAPI token is\n * known up front, so this drives itself (unlike the interactive bearer `AuthProvider`). Exposes the\n * session via `useLegacyAuth()` and gates `children` behind readiness.\n */\nexport const LegacyAuthProvider = ({\n session,\n baseUrl,\n storageToken,\n managementToken,\n fallback = null,\n errorFallback = fallback,\n children,\n}: Props) => {\n // The build state, not just readiness: `errored` and `pending` render differently.\n const [storageState, setStorageState] = useState(() => session.debug().storage);\n // Guards the once-only drive against React StrictMode's double-mounted effect.\n const startedRef = useRef<boolean>(false);\n\n useEffect(() => {\n const unsubscribe = session.subscribe((snapshot) => setStorageState(snapshot.storage));\n\n if (!startedRef.current) {\n startedRef.current = true;\n session.setBaseUrl(baseUrl);\n if (managementToken) session.authenticateManagement(managementToken);\n // Fire-and-forget: `subscribe` moves `storageState` once the build resolves. A failed build\n // resolves rather than rejects, so this catch only covers a synchronous throw.\n void session\n .authenticateStorageAsync(storageToken)\n .catch((error) => console.error('Keboola session bootstrap failed', error));\n }\n\n return unsubscribe;\n // drive to ready only on initial mount\n // oxlint-disable-next-line react/exhaustive-deps\n }, []);\n\n // The only place a failed build is observable — nothing rejects, so without this it is silent.\n useEffect(() => {\n if (storageState === 'errored') {\n console.error('Keboola session bootstrap failed: the storage build errored.');\n }\n }, [storageState]);\n\n const content = (() => {\n if (storageState === 'ready') return children;\n if (storageState === 'errored') return errorFallback;\n return fallback;\n })();\n\n return <LegacyAuthContextProvider value={session}>{content}</LegacyAuthContextProvider>;\n};\n"],"mappings":";;;AAIA,MAAM,2BAA2B;AACjC,MAAM,wBAAwB;AAC9B,MAAM,sBAAsB;AAC5B,MAAM,qBAAqB;AAC3B,MAAM,4BAA4B;AAIlC,MAAM,aAAa,cAAiC,IAAI;AACxD,MAAa,cAAc;AAI3B,MAAM,cAAc,cAAoC,IAAI;AAC5D,MAAa,sBAAsB;AAEnC,MAAM,oBAAoB,cAAoC,IAAI;AAClE,MAAa,4BAA4B;AAEzC,MAAa,qBAAqB;CAChC,MAAM,MAAM,IAAI,UAAU;CAC1B,IAAI,QAAQ,MAAM,MAAM,IAAI,MAAM,wBAAwB;CAC1D,OAAO;AACT;AAEA,MAAa,mBAAmB;CAC9B,MAAM,MAAM,IAAI,UAAU;CAC1B,IAAI,QAAQ,MAAM,MAAM,IAAI,MAAM,qBAAqB;CACvD,OAAO,IAAI,QAAQ;AACrB;AAEA,MAAa,iBAAiB;CAC5B,MAAM,MAAM,IAAI,UAAU;CAC1B,IAAI,QAAQ,MAAM,MAAM,IAAI,MAAM,mBA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,YAAY,aAAa,gBAAgB,OAAO;EAC5E,OAAO;CACT,EAAA,CAAG;CAEH,OAAO,oBAAC,qBAAD;EAAqB,OAAO;EAAU,UAAA;CAA6B,CAAA;AAC5E;;;;;;;;;AC7IA,MAAa,sBAAsB,EACjC,SACA,SACA,cACA,iBACA,WAAW,MACX,gBAAgB,UAChB,eACW;CAEX,MAAM,CAAC,cAAc,mBAAmB,eAAe,QAAQ,MAAM,CAAC,CAAC,OAAO;CAE9E,MAAM,aAAa,OAAgB,KAAK;CAExC,gBAAgB;EACd,MAAM,cAAc,QAAQ,WAAW,aAAa,gBAAgB,SAAS,OAAO,CAAC;EAErF,IAAI,CAAC,WAAW,SAAS;GACvB,WAAW,UAAU;GACrB,QAAQ,WAAW,OAAO;GAC1B,IAAI,iBAAiB,QAAQ,uBAAuB,eAAe;GAGnE,QACG,yBAAyB,YAAY,CAAC,CACtC,OAAO,UAAU,QAAQ,MAAM,oCAAoC,KAAK,CAAC;EAC9E;EAEA,OAAO;CAGT,GAAG,CAAC,CAAC;CAGL,gBAAgB;EACd,IAAI,iBAAiB,WACnB,QAAQ,MAAM,8DAA8D;CAEhF,GAAG,CAAC,YAAY,CAAC;CAQjB,OAAO,oBAAC,2BAAD;EAA2B,OAAO;EANlB,iBAAA;GACrB,IAAI,iBAAiB,SAAS,OAAO;GACrC,IAAI,iBAAiB,WAAW,OAAO;GACvC,OAAO;EACT,EAAA,CAEyD;CAA6B,CAAA;AACxF"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/context.ts","../src/ApiClientProvider.tsx","../src/useSessionState.ts","../src/LegacyAuthProvider.tsx"],"sourcesContent":["import { createContext, use } from 'react';\n\nimport type { KeboolaApi, LegacySession } from '@keboola/api-client';\n\nconst MISSING_API_CLIENT_ERROR = 'useApiClient must be used within <ApiClientProvider />';\nconst MISSING_PROJECT_ERROR = 'useProject must be used within <ApiClientProvider />';\nconst MISSING_STACK_ERROR = 'useStack must be used within <ApiClientProvider />';\nconst MISSING_LEGACY_AUTH_ERROR = 'useLegacyAuth must be used within <LegacyAuthProvider />';\n\n// The product API (`auth` + `management` + every product namespace), flow-agnostic. Both the\n// bearer and legacy flows produce the same `KeboolaApi` surface, so consumers never branch on flow.\nconst ApiContext = createContext<KeboolaApi | null>(null);\nexport const ApiProvider = ApiContext;\n\n// The legacy lifecycle session lives in its own context; the bearer flows read their table through\n// `useSessionState` instead.\nconst LegacyAuthContext = createContext<LegacySession | null>(null);\nexport const LegacyAuthContextProvider = LegacyAuthContext;\n\nexport const useApiClient = () => {\n const api = use(ApiContext);\n if (api === null) throw new Error(MISSING_API_CLIENT_ERROR);\n return api;\n};\n\nexport const useProject = () => {\n const api = use(ApiContext);\n if (api === null) throw new Error(MISSING_PROJECT_ERROR);\n return api.context.project;\n};\n\nexport const useStack = () => {\n const api = use(ApiContext);\n if (api === null) throw new Error(MISSING_STACK_ERROR);\n return api.context.stack;\n};\n\n/** The legacy (SAPI) lifecycle session. Throws outside `<LegacyAuthProvider />`. */\nexport const useLegacyAuth = () => {\n const session = use(LegacyAuthContext);\n if (session === null) throw new Error(MISSING_LEGACY_AUTH_ERROR);\n return session;\n};\n","import type { ReactNode } from 'react';\n\nimport type { KeboolaApi } from '@keboola/api-client';\n\nimport { ApiProvider } from './context';\n\ntype Props = {\n /** The flow-agnostic product API — the `api` half of a keboola client. */\n api: KeboolaApi;\n children: ReactNode;\n};\n\n/**\n * Provides the product API to `useApiClient()`. A pure pass-through: the auth lifecycle (driving\n * to ready, gating on a fallback) belongs to `AuthProvider` / `LegacyAuthProvider`, which mount\n * this provider once their session is ready.\n */\nexport const ApiClientProvider = ({ api, children }: Props) => (\n <ApiProvider value={api}>{children}</ApiProvider>\n);\n","import { useSyncExternalStore } from 'react';\n\nimport type { BearerSession } from '@keboola/api-client';\n\n/** The session table as a re-rendering value — the binding every gate and panel reads it through. */\nexport const useSessionState = (session: BearerSession) =>\n useSyncExternalStore(session.subscribe, session.getState);\n","import { useEffect, useRef, useState } from 'react';\nimport type { ReactNode } from 'react';\n\nimport type { LegacySession } from '@keboola/api-client';\n\nimport { LegacyAuthContextProvider } from './context';\n\ntype Props = {\n session: LegacySession;\n /** Stack base URL. */\n baseUrl: string;\n /** SAPI token — drives the storage build to ready. */\n storageToken: string;\n /** Optional manage-api token — unlocks `api.management`. */\n managementToken?: string;\n /** Rendered until the storage build reaches ready. */\n fallback?: ReactNode;\n /** Rendered when the storage build fails — e.g. the SAPI token is expired or revoked. */\n errorFallback?: ReactNode;\n children: ReactNode;\n};\n\n/**\n * Owns the legacy (SAPI) lifecycle: on mount it configures the stack and drives the session to\n * ready, rendering `fallback` until the storage build resolves. The backend-injected SAPI token is\n * known up front, so this drives itself (unlike the interactive bearer `AuthProvider`). Exposes the\n * session via `useLegacyAuth()` and gates `children` behind readiness.\n */\nexport const LegacyAuthProvider = ({\n session,\n baseUrl,\n storageToken,\n managementToken,\n fallback = null,\n errorFallback = fallback,\n children,\n}: Props) => {\n // The build state, not just readiness: `errored` and `pending` render differently.\n const [storageState, setStorageState] = useState(() => session.debug().storage);\n // Guards the once-only drive against React StrictMode's double-mounted effect.\n const startedRef = useRef<boolean>(false);\n\n useEffect(() => {\n const unsubscribe = session.subscribe((snapshot) => setStorageState(snapshot.storage));\n\n if (!startedRef.current) {\n startedRef.current = true;\n session.setBaseUrl(baseUrl);\n if (managementToken) session.authenticateManagement(managementToken);\n // Fire-and-forget: `subscribe` moves `storageState` once the build resolves. A failed build\n // resolves rather than rejects, so this catch only covers a synchronous throw.\n void session\n .authenticateStorageAsync(storageToken)\n .catch((error) => console.error('Keboola session bootstrap failed', error));\n }\n\n return unsubscribe;\n // drive to ready only on initial mount\n // oxlint-disable-next-line react/exhaustive-deps\n }, []);\n\n // The only place a failed build is observable — nothing rejects, so without this it is silent.\n useEffect(() => {\n if (storageState === 'errored') {\n console.error('Keboola session bootstrap failed: the storage build errored.');\n }\n }, [storageState]);\n\n const content = (() => {\n if (storageState === 'ready') return children;\n if (storageState === 'errored') return errorFallback;\n return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AAW,SAAS;GACvB,WAAW,UAAU;GACrB,QAAQ,WAAW,OAAO;GAC1B,IAAI,iBAAiB,QAAQ,uBAAuB,eAAe;GAGnE,QACG,yBAAyB,YAAY,CAAC,CACtC,OAAO,UAAU,QAAQ,MAAM,oCAAoC,KAAK,CAAC;EAC9E;EAEA,OAAO;CAGT,GAAG,CAAC,CAAC;CAGL,gBAAgB;EACd,IAAI,iBAAiB,WACnB,QAAQ,MAAM,8DAA8D;CAEhF,GAAG,CAAC,YAAY,CAAC;CAQjB,OAAO,oBAAC,2BAAD;EAA2B,OAAO;EANlB,iBAAA;GACrB,IAAI,iBAAiB,SAAS,OAAO;GACrC,IAAI,iBAAiB,WAAW,OAAO;GACvC,OAAO;EACT,EAAA,CAEyD;CAA6B,CAAA;AACxF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@keboola/api-client-react",
3
- "version": "36.0.0",
3
+ "version": "40.0.0",
4
4
  "description": "React bindings for @keboola/api-client",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -51,7 +51,7 @@
51
51
  },
52
52
  "peerDependencies": {
53
53
  "react": "^19.0.0",
54
- "@keboola/api-client": "^36.0.0"
54
+ "@keboola/api-client": "^40.0.0"
55
55
  },
56
56
  "devDependencies": {
57
57
  "@arethetypeswrong/cli": "^0.18.2",
@@ -59,23 +59,25 @@
59
59
  "@testing-library/jest-dom": "^7.0.1",
60
60
  "@testing-library/react": "^16.3.3",
61
61
  "@types/node": "24.12.0",
62
- "@types/react": "^19.2.15",
63
- "@types/react-dom": "^19.2.3",
62
+ "@types/react": "^19.3.0",
63
+ "@types/react-dom": "^19.3.0",
64
64
  "@typescript/native": "npm:typescript@^7.0.2",
65
65
  "@vitejs/plugin-react": "^6.1.1",
66
66
  "jsdom": "^26.1.0",
67
67
  "msw": "^2.15.0",
68
68
  "oxfmt": "^0.66.0",
69
69
  "oxlint": "^1.81.0",
70
- "react-dom": "^19.2.7",
70
+ "react": "^19.3.0",
71
+ "react-dom": "^19.3.0",
71
72
  "tsdown": "^0.22.14",
72
73
  "typescript": "npm:@typescript/typescript6@^6.0.2",
73
74
  "vite": "^8.3.0",
74
- "vitest": "^4.1.11",
75
- "@keboola/api-client": "^36.0.0",
76
- "@keboola/tsconfig": "^0.2.1",
77
- "@keboola/oxlint-config": "^10.1.0",
78
- "@keboola/api-fixtures": "^31.0.0"
75
+ "vitest": "^5.0.1",
76
+ "@keboola/api-client": "^40.0.0",
77
+ "@keboola/api-fixtures": "^35.0.0",
78
+ "@keboola/eslint-plugin-design": "^0.5.0",
79
+ "@keboola/oxlint-config": "^10.2.0",
80
+ "@keboola/tsconfig": "^0.2.1"
79
81
  },
80
82
  "scripts": {
81
83
  "type-check": "tsc",