@pylo/react 0.7.0 → 0.8.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/README.md +5 -107
- package/dist/chunk-3WSGP2SO.js +483 -0
- package/dist/{chunk-VUY6OTMP.js → chunk-A6UGLYBT.js} +1 -1
- package/dist/chunk-KOUVF33C.js +540 -0
- package/dist/chunk-R3IJ4HH6.js +540 -0
- package/dist/chunk-RCW4MW4F.js +540 -0
- package/dist/{chunk-SBMMJYJT.js → chunk-XCHM5XBY.js} +129 -7
- package/dist/chunk-XR5CLHMS.js +470 -0
- package/dist/chunk-ZWYBNMHS.js +500 -0
- package/dist/hooks.js +2 -2
- package/dist/index.d.ts +19 -6
- package/dist/index.js +4 -3
- package/dist/provider-X8jgqOeN.d.ts +74 -0
- package/dist/provider.d.ts +1 -1
- package/dist/provider.js +1 -1
- package/package.json +4 -4
package/README.md
CHANGED
|
@@ -1,113 +1,11 @@
|
|
|
1
1
|
# @pylo/react
|
|
2
2
|
|
|
3
|
-
Type-safe Pylo SDK for React single-page apps
|
|
4
|
-
typed client, generated from your own Pylo schema.
|
|
3
|
+
Type-safe Pylo SDK for React single-page apps, such as Vite.
|
|
5
4
|
|
|
6
|
-
|
|
7
|
-
cookies. For Expo and React Native use [`@pylo/expo`](../expo).
|
|
5
|
+
## Documentation
|
|
8
6
|
|
|
9
|
-
|
|
7
|
+
[https://docs.pyloapp.com/getting-started/quickstart-react](https://docs.pyloapp.com/getting-started/quickstart-react)
|
|
10
8
|
|
|
11
|
-
|
|
12
|
-
npm install @pylo/react @tanstack/react-query
|
|
13
|
-
```
|
|
9
|
+
## License
|
|
14
10
|
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
Add a `pylo.config.ts` at your project root, then run the generator. It writes
|
|
18
|
-
`.pylo/index.ts` and registers the schema, so no `declare module` is needed.
|
|
19
|
-
|
|
20
|
-
```bash
|
|
21
|
-
npx pylo generate
|
|
22
|
-
```
|
|
23
|
-
|
|
24
|
-
## Set up
|
|
25
|
-
|
|
26
|
-
Your app owns the QueryClient. `PyloProvider` goes inside it, because signing
|
|
27
|
-
out clears the query cache.
|
|
28
|
-
|
|
29
|
-
```tsx
|
|
30
|
-
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
|
31
|
-
import { PyloProvider } from "@pylo/react";
|
|
32
|
-
|
|
33
|
-
const queryClient = new QueryClient();
|
|
34
|
-
|
|
35
|
-
export function App() {
|
|
36
|
-
return (
|
|
37
|
-
<QueryClientProvider client={queryClient}>
|
|
38
|
-
<PyloProvider appId={import.meta.env.VITE_PYLO_APP_ID}>
|
|
39
|
-
<Routes />
|
|
40
|
-
</PyloProvider>
|
|
41
|
-
</QueryClientProvider>
|
|
42
|
-
);
|
|
43
|
-
}
|
|
44
|
-
```
|
|
45
|
-
|
|
46
|
-
## Sign in
|
|
47
|
-
|
|
48
|
-
```tsx
|
|
49
|
-
import { usePyloAuth } from "@pylo/react";
|
|
50
|
-
|
|
51
|
-
function SignIn() {
|
|
52
|
-
const { isLoading, isSignedIn, user, login, logout } = usePyloAuth();
|
|
53
|
-
|
|
54
|
-
if (isLoading) return <Spinner />;
|
|
55
|
-
if (isSignedIn) return <button onClick={() => logout()}>Sign out {user?.email}</button>;
|
|
56
|
-
|
|
57
|
-
return <button onClick={() => login(email, password)}>Sign in</button>;
|
|
58
|
-
}
|
|
59
|
-
```
|
|
60
|
-
|
|
61
|
-
`isLoading` stays true until stored tokens have been read, so an already
|
|
62
|
-
signed-in user never sees a login screen flash.
|
|
63
|
-
|
|
64
|
-
## Query data
|
|
65
|
-
|
|
66
|
-
```tsx
|
|
67
|
-
import { createPyloHooks } from "@pylo/react";
|
|
68
|
-
import type { PyloSchema } from "@pylo/types";
|
|
69
|
-
|
|
70
|
-
const { usePyloList, usePyloUpsert } = createPyloHooks<PyloSchema>();
|
|
71
|
-
|
|
72
|
-
function Contacts() {
|
|
73
|
-
const { data, isLoading } = usePyloList("contact", {
|
|
74
|
-
select: { id: true, name: true, company: { select: { name: true } } },
|
|
75
|
-
});
|
|
76
|
-
|
|
77
|
-
const upsert = usePyloUpsert("contact");
|
|
78
|
-
|
|
79
|
-
return <List rows={data} onRename={(id, name) => upsert.mutate({ id, name })} />;
|
|
80
|
-
}
|
|
81
|
-
```
|
|
82
|
-
|
|
83
|
-
For imperative calls outside a query, `usePyloClient<PyloSchema>()` returns the
|
|
84
|
-
same typed client the server SDK exposes.
|
|
85
|
-
|
|
86
|
-
## Token storage
|
|
87
|
-
|
|
88
|
-
Tokens live in `localStorage`, which any script running on your page can read.
|
|
89
|
-
Refresh tokens rotate on every use, but a strong Content Security Policy is what
|
|
90
|
-
actually protects them. If your app has a backend, keep the tokens there and
|
|
91
|
-
proxy requests through it instead.
|
|
92
|
-
|
|
93
|
-
The token is refreshed before it expires and once more if a request comes back
|
|
94
|
-
unauthorized. Only a rejected refresh token ends the session: a transient server
|
|
95
|
-
error leaves it intact, so a backend deploy does not sign everyone out.
|
|
96
|
-
|
|
97
|
-
## Bringing your own auth
|
|
98
|
-
|
|
99
|
-
Pass `getToken` instead, and the provider skips login, logout and refresh
|
|
100
|
-
entirely.
|
|
101
|
-
|
|
102
|
-
```tsx
|
|
103
|
-
<PyloProvider getToken={() => auth.getAccessToken()}>
|
|
104
|
-
```
|
|
105
|
-
|
|
106
|
-
## Custom storage
|
|
107
|
-
|
|
108
|
-
`PyloProvider` takes any `PyloStorage`: three async methods for get, set and
|
|
109
|
-
remove.
|
|
110
|
-
|
|
111
|
-
```ts
|
|
112
|
-
import type { PyloStorage } from "@pylo/react";
|
|
113
|
-
```
|
|
11
|
+
[MIT](./LICENSE)
|
|
@@ -0,0 +1,483 @@
|
|
|
1
|
+
// src/provider.tsx
|
|
2
|
+
import {
|
|
3
|
+
createContext,
|
|
4
|
+
useContext,
|
|
5
|
+
useEffect,
|
|
6
|
+
useMemo,
|
|
7
|
+
useRef,
|
|
8
|
+
useSyncExternalStore
|
|
9
|
+
} from "react";
|
|
10
|
+
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
|
11
|
+
import { createPyloClient, resolveEndpoint } from "@pylo/core";
|
|
12
|
+
import { ME_QUERY } from "@pylo/auth";
|
|
13
|
+
|
|
14
|
+
// src/session/store.ts
|
|
15
|
+
import {
|
|
16
|
+
graphqlRequest,
|
|
17
|
+
hasErrors,
|
|
18
|
+
extractErrorMessage,
|
|
19
|
+
isUnauthorizedError,
|
|
20
|
+
shouldRefreshToken,
|
|
21
|
+
safeRedirectPath,
|
|
22
|
+
LOGIN_MUTATION,
|
|
23
|
+
REDEEM_LOGIN_HANDOFF_MUTATION,
|
|
24
|
+
REFRESH_TOKEN_MUTATION
|
|
25
|
+
} from "@pylo/auth";
|
|
26
|
+
function createSessionStore(options) {
|
|
27
|
+
var _a;
|
|
28
|
+
const prefix = (_a = options.keyPrefix) != null ? _a : "pylo";
|
|
29
|
+
const AUTH_KEY = `${prefix}.auth_token`;
|
|
30
|
+
const REFRESH_KEY = `${prefix}.refresh_token`;
|
|
31
|
+
let state = { status: "loading", token: null };
|
|
32
|
+
let refreshToken = null;
|
|
33
|
+
let inFlight = null;
|
|
34
|
+
let ready = null;
|
|
35
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
36
|
+
function setState(next) {
|
|
37
|
+
state = next;
|
|
38
|
+
for (const listener of listeners) listener();
|
|
39
|
+
}
|
|
40
|
+
async function persist(auth, refresh2) {
|
|
41
|
+
refreshToken = refresh2;
|
|
42
|
+
await options.storage.setItem(AUTH_KEY, auth);
|
|
43
|
+
await options.storage.setItem(REFRESH_KEY, refresh2);
|
|
44
|
+
setState({ status: "signedIn", token: auth });
|
|
45
|
+
}
|
|
46
|
+
async function signIn(auth, refresh2) {
|
|
47
|
+
var _a2;
|
|
48
|
+
await persist(auth, refresh2);
|
|
49
|
+
(_a2 = options.onSignIn) == null ? void 0 : _a2.call(options);
|
|
50
|
+
}
|
|
51
|
+
async function clear() {
|
|
52
|
+
var _a2;
|
|
53
|
+
refreshToken = null;
|
|
54
|
+
await options.storage.removeItem(AUTH_KEY);
|
|
55
|
+
await options.storage.removeItem(REFRESH_KEY);
|
|
56
|
+
setState({ status: "signedOut", token: null });
|
|
57
|
+
(_a2 = options.onSignOut) == null ? void 0 : _a2.call(options);
|
|
58
|
+
}
|
|
59
|
+
async function runRefresh() {
|
|
60
|
+
await init();
|
|
61
|
+
if (state.status !== "signedIn") return null;
|
|
62
|
+
if (!refreshToken) {
|
|
63
|
+
await clear();
|
|
64
|
+
return null;
|
|
65
|
+
}
|
|
66
|
+
const response = await graphqlRequest(
|
|
67
|
+
options.endpoint,
|
|
68
|
+
REFRESH_TOKEN_MUTATION,
|
|
69
|
+
{ input: { refresh_token: refreshToken } }
|
|
70
|
+
);
|
|
71
|
+
if (hasErrors(response) || !response.data) {
|
|
72
|
+
if (isUnauthorizedError(response)) {
|
|
73
|
+
await clear();
|
|
74
|
+
return null;
|
|
75
|
+
}
|
|
76
|
+
return state.token;
|
|
77
|
+
}
|
|
78
|
+
const { auth_token, refresh_token } = response.data.refreshToken.data;
|
|
79
|
+
await persist(auth_token, refresh_token);
|
|
80
|
+
return auth_token;
|
|
81
|
+
}
|
|
82
|
+
function init() {
|
|
83
|
+
ready != null ? ready : ready = (async () => {
|
|
84
|
+
try {
|
|
85
|
+
const [auth, stored] = await Promise.all([
|
|
86
|
+
options.storage.getItem(AUTH_KEY),
|
|
87
|
+
options.storage.getItem(REFRESH_KEY)
|
|
88
|
+
]);
|
|
89
|
+
refreshToken = stored;
|
|
90
|
+
setState(
|
|
91
|
+
auth ? { status: "signedIn", token: auth } : { status: "signedOut", token: null }
|
|
92
|
+
);
|
|
93
|
+
} catch {
|
|
94
|
+
refreshToken = null;
|
|
95
|
+
setState({ status: "signedOut", token: null });
|
|
96
|
+
}
|
|
97
|
+
})();
|
|
98
|
+
return ready;
|
|
99
|
+
}
|
|
100
|
+
function refresh() {
|
|
101
|
+
inFlight != null ? inFlight : inFlight = runRefresh().finally(() => {
|
|
102
|
+
inFlight = null;
|
|
103
|
+
});
|
|
104
|
+
return inFlight;
|
|
105
|
+
}
|
|
106
|
+
return {
|
|
107
|
+
getState: () => state,
|
|
108
|
+
subscribe(listener) {
|
|
109
|
+
listeners.add(listener);
|
|
110
|
+
return () => void listeners.delete(listener);
|
|
111
|
+
},
|
|
112
|
+
init,
|
|
113
|
+
async getToken() {
|
|
114
|
+
await init();
|
|
115
|
+
if (!state.token) return null;
|
|
116
|
+
if (shouldRefreshToken(state.token)) return refresh();
|
|
117
|
+
return state.token;
|
|
118
|
+
},
|
|
119
|
+
refresh,
|
|
120
|
+
async login(email, password) {
|
|
121
|
+
var _a2;
|
|
122
|
+
const response = await graphqlRequest(
|
|
123
|
+
options.endpoint,
|
|
124
|
+
LOGIN_MUTATION,
|
|
125
|
+
{
|
|
126
|
+
input: {
|
|
127
|
+
email,
|
|
128
|
+
password,
|
|
129
|
+
...options.appId !== void 0 ? { pylo_app_id: options.appId } : {}
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
);
|
|
133
|
+
if (hasErrors(response)) {
|
|
134
|
+
return {
|
|
135
|
+
success: false,
|
|
136
|
+
error: {
|
|
137
|
+
code: "INVALID_CREDENTIALS",
|
|
138
|
+
message: (_a2 = extractErrorMessage(response.errors)) != null ? _a2 : "Login failed"
|
|
139
|
+
}
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
if (!response.data) {
|
|
143
|
+
return {
|
|
144
|
+
success: false,
|
|
145
|
+
error: { code: "SERVER_ERROR", message: "No data returned" }
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
const { auth_token, refresh_token } = response.data.login.data;
|
|
149
|
+
await signIn(auth_token, refresh_token);
|
|
150
|
+
return { success: true, authToken: auth_token, refreshToken: refresh_token };
|
|
151
|
+
},
|
|
152
|
+
async redeemHandoff(code, verifier) {
|
|
153
|
+
var _a2;
|
|
154
|
+
let response;
|
|
155
|
+
try {
|
|
156
|
+
response = await graphqlRequest(
|
|
157
|
+
options.endpoint,
|
|
158
|
+
REDEEM_LOGIN_HANDOFF_MUTATION,
|
|
159
|
+
{ input: { code, handoff_verifier: verifier } }
|
|
160
|
+
);
|
|
161
|
+
} catch (error) {
|
|
162
|
+
return {
|
|
163
|
+
success: false,
|
|
164
|
+
error: {
|
|
165
|
+
code: "SIGN_IN_FAILED",
|
|
166
|
+
message: error instanceof Error ? error.message : "Sign-in failed"
|
|
167
|
+
}
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
if (hasErrors(response) || !response.data) {
|
|
171
|
+
return {
|
|
172
|
+
success: false,
|
|
173
|
+
error: {
|
|
174
|
+
code: "SIGN_IN_FAILED",
|
|
175
|
+
message: (_a2 = extractErrorMessage(response.errors)) != null ? _a2 : "Sign-in failed"
|
|
176
|
+
}
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
const { auth_token, refresh_token, redirect } = response.data.redeemLoginHandoff.data;
|
|
180
|
+
await signIn(auth_token, refresh_token);
|
|
181
|
+
const safe = safeRedirectPath(redirect);
|
|
182
|
+
return {
|
|
183
|
+
success: true,
|
|
184
|
+
authToken: auth_token,
|
|
185
|
+
refreshToken: refresh_token,
|
|
186
|
+
...safe !== null ? { redirect: safe } : {}
|
|
187
|
+
};
|
|
188
|
+
},
|
|
189
|
+
logout: clear
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// src/session/social.ts
|
|
194
|
+
import {
|
|
195
|
+
buildSocialStartUrl,
|
|
196
|
+
createHandoffChallenge,
|
|
197
|
+
createHandoffVerifier,
|
|
198
|
+
parseHandoffCallback
|
|
199
|
+
} from "@pylo/auth";
|
|
200
|
+
function failed(code, message) {
|
|
201
|
+
return { success: false, error: { code, message } };
|
|
202
|
+
}
|
|
203
|
+
function createSocialSignIn(o) {
|
|
204
|
+
const verifierKey = `${o.keyPrefix}.handoff_verifier`;
|
|
205
|
+
function redeem(parsed, verifier) {
|
|
206
|
+
if (!parsed) return failed("SIGN_IN_FAILED", "No sign-in response in this URL");
|
|
207
|
+
if ("error" in parsed) return failed("SIGN_IN_FAILED", parsed.error);
|
|
208
|
+
if (!verifier) {
|
|
209
|
+
return failed("SIGN_IN_FAILED", "No sign-in was started in this browser session");
|
|
210
|
+
}
|
|
211
|
+
return o.store.redeemHandoff(parsed.code, verifier);
|
|
212
|
+
}
|
|
213
|
+
return {
|
|
214
|
+
async signInWith(provider, { returnUrl, redirect, invite }) {
|
|
215
|
+
let verifier;
|
|
216
|
+
let startUrl;
|
|
217
|
+
let finalUrl = null;
|
|
218
|
+
try {
|
|
219
|
+
verifier = createHandoffVerifier(o.crypto);
|
|
220
|
+
const challenge = await createHandoffChallenge(verifier, o.crypto);
|
|
221
|
+
startUrl = buildSocialStartUrl({
|
|
222
|
+
endpoint: o.endpoint,
|
|
223
|
+
provider,
|
|
224
|
+
appId: o.appId,
|
|
225
|
+
returnUrl,
|
|
226
|
+
challenge,
|
|
227
|
+
...redirect !== void 0 ? { redirect } : {},
|
|
228
|
+
...invite !== void 0 ? { invite } : {}
|
|
229
|
+
});
|
|
230
|
+
if (o.openAuthSession) finalUrl = await o.openAuthSession(startUrl, returnUrl);
|
|
231
|
+
} catch (error) {
|
|
232
|
+
return failed(
|
|
233
|
+
"SIGN_IN_FAILED",
|
|
234
|
+
error instanceof Error ? error.message : "Sign-in failed"
|
|
235
|
+
);
|
|
236
|
+
}
|
|
237
|
+
if (o.openAuthSession) {
|
|
238
|
+
if (finalUrl === null) return failed("CANCELLED", "Sign-in was cancelled");
|
|
239
|
+
return redeem(parseHandoffCallback(finalUrl), verifier);
|
|
240
|
+
}
|
|
241
|
+
sessionStorage.setItem(verifierKey, verifier);
|
|
242
|
+
location.assign(startUrl);
|
|
243
|
+
return new Promise(() => {
|
|
244
|
+
});
|
|
245
|
+
},
|
|
246
|
+
async completeSignIn(url = location.href) {
|
|
247
|
+
const verifier = sessionStorage.getItem(verifierKey);
|
|
248
|
+
sessionStorage.removeItem(verifierKey);
|
|
249
|
+
const parsed = parseHandoffCallback(url);
|
|
250
|
+
if (parsed) {
|
|
251
|
+
const clean = new URL(url);
|
|
252
|
+
clean.searchParams.delete("code");
|
|
253
|
+
clean.searchParams.delete("error");
|
|
254
|
+
history.replaceState(history.state, "", clean.toString());
|
|
255
|
+
}
|
|
256
|
+
return redeem(parsed, verifier);
|
|
257
|
+
}
|
|
258
|
+
};
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
// src/session/storage.ts
|
|
262
|
+
function createMemoryStorage() {
|
|
263
|
+
const store = /* @__PURE__ */ new Map();
|
|
264
|
+
return {
|
|
265
|
+
getItem: async (key) => {
|
|
266
|
+
var _a;
|
|
267
|
+
return (_a = store.get(key)) != null ? _a : null;
|
|
268
|
+
},
|
|
269
|
+
setItem: async (key, value) => void store.set(key, value),
|
|
270
|
+
removeItem: async (key) => void store.delete(key)
|
|
271
|
+
};
|
|
272
|
+
}
|
|
273
|
+
function createLocalStorageAdapter() {
|
|
274
|
+
let web;
|
|
275
|
+
try {
|
|
276
|
+
web = globalThis.localStorage;
|
|
277
|
+
} catch {
|
|
278
|
+
web = void 0;
|
|
279
|
+
}
|
|
280
|
+
if (!web) return createMemoryStorage();
|
|
281
|
+
const fallback = createMemoryStorage();
|
|
282
|
+
return {
|
|
283
|
+
getItem: async (key) => {
|
|
284
|
+
try {
|
|
285
|
+
const value = web.getItem(key);
|
|
286
|
+
if (value !== null) return value;
|
|
287
|
+
} catch {
|
|
288
|
+
}
|
|
289
|
+
return fallback.getItem(key);
|
|
290
|
+
},
|
|
291
|
+
setItem: async (key, value) => {
|
|
292
|
+
try {
|
|
293
|
+
web.setItem(key, value);
|
|
294
|
+
} catch {
|
|
295
|
+
await fallback.setItem(key, value);
|
|
296
|
+
}
|
|
297
|
+
},
|
|
298
|
+
removeItem: async (key) => {
|
|
299
|
+
try {
|
|
300
|
+
web.removeItem(key);
|
|
301
|
+
} catch {
|
|
302
|
+
}
|
|
303
|
+
await fallback.removeItem(key);
|
|
304
|
+
}
|
|
305
|
+
};
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
// src/transport.ts
|
|
309
|
+
import {
|
|
310
|
+
graphqlRequest as graphqlRequest2,
|
|
311
|
+
hasErrors as hasErrors2,
|
|
312
|
+
extractErrorMessage as extractErrorMessage2,
|
|
313
|
+
isUnauthorizedError as isUnauthorizedError2
|
|
314
|
+
} from "@pylo/auth";
|
|
315
|
+
import { PyloError } from "@pylo/core";
|
|
316
|
+
function createDirectTransport(options) {
|
|
317
|
+
function send(query, variables, headers, token) {
|
|
318
|
+
return graphqlRequest2(
|
|
319
|
+
options.endpoint,
|
|
320
|
+
query,
|
|
321
|
+
variables,
|
|
322
|
+
{
|
|
323
|
+
...token !== null ? { token } : {},
|
|
324
|
+
...headers !== void 0 ? { headers } : {}
|
|
325
|
+
}
|
|
326
|
+
);
|
|
327
|
+
}
|
|
328
|
+
return async (query, variables, headers) => {
|
|
329
|
+
var _a;
|
|
330
|
+
let response = await send(query, variables, headers, await options.getToken());
|
|
331
|
+
if (isUnauthorizedError2(response) && options.onUnauthorized) {
|
|
332
|
+
const token = await options.onUnauthorized();
|
|
333
|
+
if (token !== null) {
|
|
334
|
+
response = await send(query, variables, headers, token);
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
if (hasErrors2(response)) {
|
|
338
|
+
throw new PyloError(
|
|
339
|
+
(_a = extractErrorMessage2(response.errors)) != null ? _a : "GraphQL request failed",
|
|
340
|
+
response.errors
|
|
341
|
+
);
|
|
342
|
+
}
|
|
343
|
+
if (!response.data) {
|
|
344
|
+
throw new PyloError("No data returned from GraphQL request");
|
|
345
|
+
}
|
|
346
|
+
return response.data;
|
|
347
|
+
};
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
// src/provider.tsx
|
|
351
|
+
import { jsx } from "react/jsx-runtime";
|
|
352
|
+
var PyloContext = createContext(null);
|
|
353
|
+
function usePyloContext() {
|
|
354
|
+
const value = useContext(PyloContext);
|
|
355
|
+
if (!value) {
|
|
356
|
+
throw new Error("usePylo* must be used inside <PyloProvider>");
|
|
357
|
+
}
|
|
358
|
+
return value;
|
|
359
|
+
}
|
|
360
|
+
var SIGNED_OUT = { status: "signedOut", token: null };
|
|
361
|
+
var NO_OP = () => () => {
|
|
362
|
+
};
|
|
363
|
+
function PyloProvider(props) {
|
|
364
|
+
var _a, _b;
|
|
365
|
+
const queryClient = useQueryClient();
|
|
366
|
+
const endpoint = resolveEndpoint(props.endpoint);
|
|
367
|
+
const storeRef = useRef(null);
|
|
368
|
+
const socialRef = useRef(null);
|
|
369
|
+
const openAuthSessionRef = useRef(props.openAuthSession);
|
|
370
|
+
openAuthSessionRef.current = props.openAuthSession;
|
|
371
|
+
if (storeRef.current === null && !props.getToken) {
|
|
372
|
+
storeRef.current = createSessionStore({
|
|
373
|
+
endpoint,
|
|
374
|
+
storage: (_a = props.storage) != null ? _a : createLocalStorageAdapter(),
|
|
375
|
+
...props.appId !== void 0 ? { appId: props.appId } : {},
|
|
376
|
+
...props.keyPrefix !== void 0 ? { keyPrefix: props.keyPrefix } : {},
|
|
377
|
+
onSignOut: () => queryClient.clear(),
|
|
378
|
+
onSignIn: () => void queryClient.invalidateQueries({ queryKey: ["pylo"] })
|
|
379
|
+
});
|
|
380
|
+
if (props.appId !== void 0) {
|
|
381
|
+
socialRef.current = createSocialSignIn({
|
|
382
|
+
endpoint,
|
|
383
|
+
appId: props.appId,
|
|
384
|
+
keyPrefix: (_b = props.keyPrefix) != null ? _b : "pylo",
|
|
385
|
+
store: storeRef.current,
|
|
386
|
+
...props.openAuthSession ? {
|
|
387
|
+
openAuthSession: (url, returnUrl) => openAuthSessionRef.current(url, returnUrl)
|
|
388
|
+
} : {},
|
|
389
|
+
...props.handoffCrypto ? { crypto: props.handoffCrypto } : {}
|
|
390
|
+
});
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
const store = storeRef.current;
|
|
394
|
+
const social = socialRef.current;
|
|
395
|
+
const state = useSyncExternalStore(
|
|
396
|
+
store ? store.subscribe : NO_OP,
|
|
397
|
+
store ? store.getState : () => SIGNED_OUT,
|
|
398
|
+
store ? store.getState : () => SIGNED_OUT
|
|
399
|
+
);
|
|
400
|
+
useEffect(() => {
|
|
401
|
+
void (store == null ? void 0 : store.init());
|
|
402
|
+
}, [store]);
|
|
403
|
+
const getTokenProp = props.getToken;
|
|
404
|
+
const getTokenRef = useRef(getTokenProp);
|
|
405
|
+
getTokenRef.current = getTokenProp;
|
|
406
|
+
const isEscapeHatch = getTokenProp !== void 0;
|
|
407
|
+
const value = useMemo(() => {
|
|
408
|
+
const getToken = isEscapeHatch ? () => getTokenRef.current() : () => store.getToken();
|
|
409
|
+
const transport = createDirectTransport({
|
|
410
|
+
endpoint,
|
|
411
|
+
getToken,
|
|
412
|
+
...store ? { onUnauthorized: () => store.refresh() } : {}
|
|
413
|
+
});
|
|
414
|
+
return { transport, endpoint, state, store, social, getToken };
|
|
415
|
+
}, [endpoint, state, store, social, isEscapeHatch]);
|
|
416
|
+
return /* @__PURE__ */ jsx(PyloContext.Provider, { value, children: props.children });
|
|
417
|
+
}
|
|
418
|
+
function usePyloTransport() {
|
|
419
|
+
return usePyloContext().transport;
|
|
420
|
+
}
|
|
421
|
+
function usePyloClient() {
|
|
422
|
+
const { endpoint, getToken } = usePyloContext();
|
|
423
|
+
return useMemo(
|
|
424
|
+
() => createPyloClient({
|
|
425
|
+
endpoint,
|
|
426
|
+
auth: async () => {
|
|
427
|
+
const token = await getToken();
|
|
428
|
+
return token !== null ? { token } : {};
|
|
429
|
+
}
|
|
430
|
+
}),
|
|
431
|
+
[endpoint, getToken]
|
|
432
|
+
);
|
|
433
|
+
}
|
|
434
|
+
function usePyloAuth() {
|
|
435
|
+
const { state, store, social, transport, getToken } = usePyloContext();
|
|
436
|
+
const isSignedIn = state.status === "signedIn";
|
|
437
|
+
const me = useQuery({
|
|
438
|
+
queryKey: ["pylo", "me"],
|
|
439
|
+
queryFn: async () => {
|
|
440
|
+
const data = await transport(ME_QUERY, {});
|
|
441
|
+
return data.me.current_user.data;
|
|
442
|
+
},
|
|
443
|
+
enabled: isSignedIn
|
|
444
|
+
});
|
|
445
|
+
return {
|
|
446
|
+
isLoading: state.status === "loading" || isSignedIn && me.isLoading,
|
|
447
|
+
isSignedIn,
|
|
448
|
+
user: me.data,
|
|
449
|
+
login: async (email, password) => {
|
|
450
|
+
if (!store) {
|
|
451
|
+
throw new Error("login is unavailable when PyloProvider is given getToken");
|
|
452
|
+
}
|
|
453
|
+
return store.login(email, password);
|
|
454
|
+
},
|
|
455
|
+
logout: async () => {
|
|
456
|
+
if (!store) {
|
|
457
|
+
throw new Error("logout is unavailable when PyloProvider is given getToken");
|
|
458
|
+
}
|
|
459
|
+
await store.logout();
|
|
460
|
+
},
|
|
461
|
+
signInWith: async (provider, options) => requireSocial("signInWith").signInWith(provider, options),
|
|
462
|
+
completeSignIn: async (url) => requireSocial("completeSignIn").completeSignIn(url),
|
|
463
|
+
getToken
|
|
464
|
+
};
|
|
465
|
+
function requireSocial(method) {
|
|
466
|
+
if (!store) {
|
|
467
|
+
throw new Error(`${method} is unavailable when PyloProvider is given getToken`);
|
|
468
|
+
}
|
|
469
|
+
if (!social) throw new Error(`${method} requires PyloProvider's appId`);
|
|
470
|
+
return social;
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
export {
|
|
475
|
+
createSessionStore,
|
|
476
|
+
createMemoryStorage,
|
|
477
|
+
createLocalStorageAdapter,
|
|
478
|
+
createDirectTransport,
|
|
479
|
+
PyloProvider,
|
|
480
|
+
usePyloTransport,
|
|
481
|
+
usePyloClient,
|
|
482
|
+
usePyloAuth
|
|
483
|
+
};
|