@sanity/sdk-react 3.1.0 → 3.3.0-rc.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.
Files changed (63) hide show
  1. package/dist/_exports/dashboard-internal.d.ts +2 -0
  2. package/dist/_exports/dashboard-internal.js +2 -0
  3. package/dist/_exports/dashboard.d.ts +457 -7
  4. package/dist/_exports/dashboard.d.ts.map +1 -1
  5. package/dist/_exports/dashboard.js +623 -2
  6. package/dist/_exports/dashboard.js.map +1 -1
  7. package/dist/index.d.ts +227 -87
  8. package/dist/index.d.ts.map +1 -1
  9. package/dist/index.js +147 -30
  10. package/dist/index.js.map +1 -1
  11. package/dist/{useStudioWorkspacesByProjectIdDataset-DxUlukmF.js → useStudioWorkspacesByProjectIdDataset-BZ_Ud887.js} +53 -56
  12. package/dist/useStudioWorkspacesByProjectIdDataset-BZ_Ud887.js.map +1 -0
  13. package/package.json +34 -32
  14. package/src/_exports/dashboard-internal.ts +1 -0
  15. package/src/_exports/dashboard.test-d.ts +64 -0
  16. package/src/_exports/dashboard.ts +70 -0
  17. package/src/_exports/index.ts +1 -1
  18. package/src/_exports/sdk-react.ts +3 -0
  19. package/src/components/auth/AuthBoundary.test.tsx +115 -2
  20. package/src/components/auth/AuthBoundary.tsx +18 -5
  21. package/src/components/auth/LoginCallback.test.tsx +46 -7
  22. package/src/components/auth/LoginCallback.tsx +22 -4
  23. package/src/context/DashboardTokenRefresh.test.tsx +124 -22
  24. package/src/context/DashboardTokenRefresh.tsx +31 -15
  25. package/src/dashboard/createRemoteInstance.test.ts +168 -0
  26. package/src/dashboard/createRemoteInstance.ts +123 -0
  27. package/src/dashboard/module.ts +39 -0
  28. package/src/dashboard/remoteClientState.ts +27 -0
  29. package/src/dashboard/urlFor.test.ts +246 -0
  30. package/src/dashboard/urlFor.ts +462 -0
  31. package/src/hooks/applications/useApplication.test-d.ts +1 -1
  32. package/src/hooks/auth/useHandleOAuthCallback.test.tsx +16 -0
  33. package/src/hooks/auth/useHandleOAuthCallback.tsx +49 -0
  34. package/src/hooks/auth/useOAuthAuthorize.test.tsx +16 -0
  35. package/src/hooks/auth/useOAuthAuthorize.tsx +28 -0
  36. package/src/hooks/auth/useOAuthTokens.test.tsx +240 -0
  37. package/src/hooks/auth/useOAuthTokens.tsx +95 -0
  38. package/src/hooks/dashboard/useApplication.test.tsx +59 -0
  39. package/src/hooks/dashboard/useApplication.ts +22 -0
  40. package/src/hooks/dashboard/useApplicationConfig.test.tsx +106 -0
  41. package/src/hooks/dashboard/useApplicationConfig.ts +45 -0
  42. package/src/hooks/dashboard/useApplicationConfigs.test.tsx +89 -0
  43. package/src/hooks/dashboard/useApplicationConfigs.ts +26 -0
  44. package/src/hooks/dashboard/useApplicationForegroundId.test.tsx +54 -0
  45. package/src/hooks/dashboard/useApplicationForegroundId.ts +22 -0
  46. package/src/hooks/dashboard/useApplications.test.tsx +249 -0
  47. package/src/hooks/dashboard/useApplications.ts +128 -0
  48. package/src/hooks/dashboard/useEmit.test.tsx +124 -0
  49. package/src/hooks/dashboard/useEmit.ts +78 -0
  50. package/src/hooks/dashboard/useNavigate.ts +1 -3
  51. package/src/hooks/dashboard/useRemoteClient.test.tsx +88 -0
  52. package/src/hooks/dashboard/useRemoteClient.ts +10 -0
  53. package/src/hooks/dashboard/useTopic.test.tsx +200 -0
  54. package/src/hooks/dashboard/useTopic.ts +29 -0
  55. package/src/hooks/dashboard/useUpdateFavorite.test.tsx +8 -1
  56. package/src/hooks/document/useApplyDocumentActions.ts +3 -4
  57. package/src/hooks/document/useCreateDocument.ts +2 -3
  58. package/src/hooks/document/useDocument.ts +11 -6
  59. package/src/hooks/document/useEditDocument.ts +5 -5
  60. package/src/hooks/projection/useDocumentProjection.ts +6 -7
  61. package/src/hooks/query/useQuery.ts +3 -4
  62. package/dist/useStudioWorkspacesByProjectIdDataset-DxUlukmF.js.map +0 -1
  63. package/src/context/dashboardToken.ts +0 -63
@@ -0,0 +1,462 @@
1
+ /** @public */
2
+ export interface DashboardUrl {
3
+ url(options?: {origin?: string}): string
4
+ toURL(options: {origin: string}): URL
5
+ toString(): string
6
+ }
7
+
8
+ // URL requires an origin; public output always strips this parsing base.
9
+ const relativeUrlBase = 'https://dashboard.invalid'
10
+
11
+ /** @public */
12
+ export interface EditIntentParameters {
13
+ id: string
14
+ /** The document schema type, for example `post`. */
15
+ type?: string
16
+ /** Requests a Studio edit mode, such as `structure` or `presentation`. */
17
+ mode?: 'structure' | 'presentation' | (string & Record<never, never>)
18
+ }
19
+
20
+ /** @public */
21
+ export interface CreateIntentParameters {
22
+ template: string
23
+ type: string
24
+ }
25
+
26
+ /** @public */
27
+ export interface ReleaseIntentParameters {
28
+ id: string
29
+ }
30
+
31
+ /** @public */
32
+ export interface StudioWorkspaceUrl extends DashboardUrl {
33
+ intent(intent: 'edit', parameters: EditIntentParameters): StudioIntentUrl
34
+ intent(intent: 'create', parameters: CreateIntentParameters): StudioIntentUrl
35
+ intent(intent: 'release', parameters: ReleaseIntentParameters): StudioIntentUrl
36
+ path(...path: string[]): DashboardUrl
37
+ task(taskId: string): DashboardUrl
38
+ }
39
+
40
+ /** @public */
41
+ export interface StudioUrl extends StudioWorkspaceUrl {
42
+ workspace(workspace: string): StudioWorkspaceUrl
43
+ }
44
+
45
+ /** @public */
46
+ export interface StudioIntentUrl extends DashboardUrl {
47
+ perspective(perspective: string): StudioIntentUrl
48
+ comment(commentId: string): StudioIntentUrl
49
+ task(taskId: string): DashboardUrl
50
+ }
51
+
52
+ /** @public */
53
+ export interface CoreApplicationUrl extends DashboardUrl {
54
+ path(...path: string[]): DashboardUrl
55
+ }
56
+
57
+ /** @public */
58
+ export interface MediaLibraryUrl extends DashboardUrl {
59
+ asset(assetId: string): DashboardUrl
60
+ collection(collectionId: string): DashboardUrl
61
+ }
62
+
63
+ /** @public */
64
+ export interface CanvasUrl extends DashboardUrl {
65
+ document(documentId: string): DashboardUrl
66
+ }
67
+
68
+ type IntentArguments =
69
+ | [intent: 'edit', parameters: EditIntentParameters]
70
+ | [intent: 'create', parameters: CreateIntentParameters]
71
+ | [intent: 'release', parameters: ReleaseIntentParameters]
72
+
73
+ type BuilderRegistry = Readonly<
74
+ Record<
75
+ string,
76
+ {
77
+ readonly namespace: string
78
+ new (url: URL): UrlBuilder
79
+ }
80
+ >
81
+ >
82
+
83
+ type BuilderMethods<Builders extends BuilderRegistry> = {
84
+ readonly [Name in keyof Builders]: () => InstanceType<Builders[Name]>
85
+ }
86
+
87
+ const splitPath = (path: readonly string[]) =>
88
+ path.flatMap((part) => part.split('/')).filter(Boolean)
89
+
90
+ const intentParametersOf = (...[intent, parameters]: IntentArguments) => {
91
+ const searchParameters = new URLSearchParams()
92
+
93
+ switch (intent) {
94
+ case 'edit': {
95
+ const {id, type, mode} = parameters
96
+ searchParameters.set('id', id)
97
+ if (type !== undefined) searchParameters.set('type', type)
98
+ if (mode !== undefined) searchParameters.set('mode', mode)
99
+ break
100
+ }
101
+ case 'create': {
102
+ searchParameters.set('template', parameters.template)
103
+ searchParameters.set('type', parameters.type)
104
+ break
105
+ }
106
+ case 'release': {
107
+ searchParameters.set('id', parameters.id)
108
+ break
109
+ }
110
+ }
111
+
112
+ return searchParameters
113
+ }
114
+
115
+ const parseIntentParameters = (parameters: string) =>
116
+ new URLSearchParams(parameters.replaceAll(';', '&'))
117
+
118
+ const serializeIntentParameters = (parameters: URLSearchParams) =>
119
+ Array.from(
120
+ parameters,
121
+ ([name, value]) => `${encodeURIComponent(name)}=${encodeURIComponent(value)}`,
122
+ ).join(';')
123
+
124
+ const appendSegments = (url: URL, segments: readonly string[]): URL => {
125
+ const nextUrl = new URL(url)
126
+ if (segments.length === 0) return nextUrl
127
+
128
+ nextUrl.pathname = `${nextUrl.pathname.replace(/\/$/, '')}/${segments
129
+ .map(encodeURIComponent)
130
+ .join('/')}`
131
+ return nextUrl
132
+ }
133
+
134
+ /**
135
+ * Base class for immutable URL grammars.
136
+ *
137
+ * @public
138
+ */
139
+ export class UrlBuilder implements DashboardUrl {
140
+ readonly #url: URL
141
+
142
+ /**
143
+ * Creates an immutable URL builder at the supplied URL.
144
+ *
145
+ * @example
146
+ * ```ts
147
+ * const builder = new UrlBuilder(
148
+ * new URL('/applications/my-app', 'https://dashboard.sanity.io'),
149
+ * )
150
+ *
151
+ * builder.url() // '/applications/my-app'
152
+ * ```
153
+ */
154
+ constructor(url: URL) {
155
+ this.#url = new URL(url)
156
+ }
157
+
158
+ /**
159
+ * Returns a builder with each value appended as one encoded path segment.
160
+ *
161
+ * Route literals and identifiers can be passed together. A slash inside a value stays within
162
+ * that segment instead of creating another route level.
163
+ *
164
+ * @example
165
+ * ```ts
166
+ * class DocumentUrlBuilder extends UrlBuilder {
167
+ * document(documentId: string) {
168
+ * return this.append('documents', documentId)
169
+ * }
170
+ * }
171
+ *
172
+ * const builder = new DocumentUrlBuilder(new URL('https://dashboard.sanity.io'))
173
+ * builder.document('drafts/document-1').url()
174
+ * // '/documents/drafts%2Fdocument-1'
175
+ * ```
176
+ */
177
+ protected append(...segments: string[]): this {
178
+ return this.#create(appendSegments(this.#url, segments))
179
+ }
180
+
181
+ /**
182
+ * Returns a builder with changes made through the platform `URL` API.
183
+ *
184
+ * This supports URL details outside the path grammar, including search parameters and hashes.
185
+ *
186
+ * @example
187
+ * ```ts
188
+ * class DocumentUrlBuilder extends UrlBuilder {
189
+ * perspective(name: string) {
190
+ * return this.edit((url) => url.searchParams.set('perspective', name))
191
+ * }
192
+ *
193
+ * panel(panelId: string) {
194
+ * return this.edit((url) => {
195
+ * url.hash = `panel/${panelId}`
196
+ * })
197
+ * }
198
+ * }
199
+ * ```
200
+ */
201
+ protected edit(update: (url: URL) => void): this {
202
+ const url = new URL(this.#url)
203
+ update(url)
204
+ return this.#create(url)
205
+ }
206
+
207
+ /**
208
+ * Returns another builder type rooted at the appended path segments.
209
+ *
210
+ * Use this inside a custom builder method only when its route enters a child grammar with
211
+ * different methods; use `append` when chaining stays on the current grammar.
212
+ *
213
+ * @example
214
+ * ```ts
215
+ * class DocumentUrlBuilder extends UrlBuilder {
216
+ * perspective(name: string) {
217
+ * return this.edit((url) => url.searchParams.set('perspective', name))
218
+ * }
219
+ * }
220
+ *
221
+ * class ApplicationUrlBuilder extends UrlBuilder {
222
+ * document(documentId: string) {
223
+ * return this.transitionTo(DocumentUrlBuilder, 'documents', documentId)
224
+ * }
225
+ * }
226
+ *
227
+ * const builder = new ApplicationUrlBuilder(new URL('https://dashboard.sanity.io'))
228
+ * builder.document('document-1').perspective('published').url()
229
+ * // '/documents/document-1?perspective=published'
230
+ * ```
231
+ */
232
+ protected transitionTo<Builder extends UrlBuilder>(
233
+ Builder: new (url: URL) => Builder,
234
+ ...segments: string[]
235
+ ): Builder {
236
+ return new Builder(appendSegments(this.#url, segments))
237
+ }
238
+
239
+ /**
240
+ * Returns the URL as a relative string by default.
241
+ *
242
+ * Supplying an origin returns an absolute URL string for the same dashboard route.
243
+ *
244
+ * @example
245
+ * ```ts
246
+ * const builder = new UrlBuilder(
247
+ * new URL('/applications/my-app', 'https://dashboard.sanity.io'),
248
+ * )
249
+ *
250
+ * builder.url() // '/applications/my-app'
251
+ * builder.url({origin: 'https://dashboard.sanity.io'})
252
+ * // 'https://dashboard.sanity.io/applications/my-app'
253
+ * ```
254
+ */
255
+ url(options?: {origin?: string}): string {
256
+ const relativeUrl = this.#relativeUrl()
257
+ return options?.origin === undefined ? relativeUrl : new URL(relativeUrl, options.origin).href
258
+ }
259
+
260
+ /**
261
+ * Returns the URL as a platform `URL` object using the supplied origin.
262
+ *
263
+ * @example
264
+ * ```ts
265
+ * const builder = new UrlBuilder(
266
+ * new URL('/applications/my-app', 'https://dashboard.sanity.io'),
267
+ * )
268
+ *
269
+ * builder.toURL({origin: 'https://dashboard.sanity.io'}).pathname
270
+ * // '/applications/my-app'
271
+ * ```
272
+ */
273
+ toURL({origin}: {origin: string}): URL {
274
+ return new URL(this.#relativeUrl(), origin)
275
+ }
276
+
277
+ /**
278
+ * Returns the same relative URL as {@link UrlBuilder.url}.
279
+ *
280
+ * @example
281
+ * ```ts
282
+ * const builder = new UrlBuilder(
283
+ * new URL('/applications/my-app', 'https://dashboard.sanity.io'),
284
+ * )
285
+ *
286
+ * `${builder}` // '/applications/my-app'
287
+ * ```
288
+ */
289
+ toString(): string {
290
+ return this.url()
291
+ }
292
+
293
+ #relativeUrl(): string {
294
+ return `${this.#url.pathname}${this.#url.search}${this.#url.hash}`
295
+ }
296
+
297
+ #create(url: URL): this {
298
+ const Builder = this.constructor as new (url: URL) => this
299
+ return new Builder(url)
300
+ }
301
+ }
302
+
303
+ class CoreApplicationUrlBuilder extends UrlBuilder implements CoreApplicationUrl {
304
+ static readonly namespace = 'applications'
305
+
306
+ path(...path: string[]): this {
307
+ return this.append(...splitPath(path))
308
+ }
309
+ }
310
+
311
+ class MediaLibraryUrlBuilder extends UrlBuilder implements MediaLibraryUrl {
312
+ static readonly namespace = 'media'
313
+
314
+ asset(assetId: string): DashboardUrl {
315
+ return this.append('assets', assetId)
316
+ }
317
+
318
+ collection(collectionId: string): DashboardUrl {
319
+ return this.append('collections', collectionId)
320
+ }
321
+ }
322
+
323
+ class CanvasUrlBuilder extends UrlBuilder implements CanvasUrl {
324
+ static readonly namespace = 'canvas'
325
+
326
+ document(documentId: string): DashboardUrl {
327
+ return this.append('doc', documentId)
328
+ }
329
+ }
330
+
331
+ class StudioUrlBuilder
332
+ extends UrlBuilder
333
+ implements StudioUrl, StudioWorkspaceUrl, StudioIntentUrl
334
+ {
335
+ static readonly namespace = 'studios'
336
+
337
+ workspace(workspace: string): StudioWorkspaceUrl {
338
+ return this.append(workspace)
339
+ }
340
+
341
+ intent(intent: 'edit', parameters: EditIntentParameters): StudioIntentUrl
342
+ intent(intent: 'create', parameters: CreateIntentParameters): StudioIntentUrl
343
+ intent(intent: 'release', parameters: ReleaseIntentParameters): StudioIntentUrl
344
+ intent(...args: IntentArguments): StudioIntentUrl {
345
+ return this.append('intent', args[0]).edit((url) => {
346
+ url.pathname = `${url.pathname}/${serializeIntentParameters(intentParametersOf(...args))}/`
347
+ })
348
+ }
349
+
350
+ perspective(perspective: string): StudioIntentUrl {
351
+ return this.edit((url) => url.searchParams.set('perspective', perspective))
352
+ }
353
+
354
+ comment(commentId: string): StudioIntentUrl {
355
+ return this.edit((url) => {
356
+ const segments = url.pathname.split('/')
357
+ const parametersIndex = segments.length - 2
358
+ const parameters = parseIntentParameters(segments[parametersIndex]!)
359
+ parameters.set('inspect', 'sanity/comments')
360
+ parameters.set('comment', commentId)
361
+ segments[parametersIndex] = serializeIntentParameters(parameters)
362
+ url.pathname = segments.join('/')
363
+ })
364
+ }
365
+
366
+ task(taskId: string): DashboardUrl {
367
+ return this.edit((url) => url.searchParams.set('selectedTask', taskId))
368
+ }
369
+
370
+ path(...path: string[]): DashboardUrl {
371
+ return this.append(...splitPath(path))
372
+ }
373
+ }
374
+
375
+ /** @public */
376
+ export interface Urls {
377
+ studios(): DashboardUrl
378
+ studios(appId: string): StudioUrl
379
+ applications(): DashboardUrl
380
+ applications(appId: string): CoreApplicationUrl
381
+ mediaLibrary(): MediaLibraryUrl
382
+ canvas(): CanvasUrl
383
+ home(): DashboardUrl
384
+ extend<
385
+ const Builders extends Readonly<
386
+ Record<
387
+ string,
388
+ {
389
+ readonly namespace: string
390
+ new (url: URL): UrlBuilder
391
+ }
392
+ >
393
+ >,
394
+ >(
395
+ builders: Builders & Partial<Record<keyof this, never>>,
396
+ ): this & {readonly [Name in keyof Builders]: () => InstanceType<Builders[Name]>}
397
+ }
398
+
399
+ const createRootBuilder = <Builder extends UrlBuilder>(
400
+ Builder: (new (url: URL) => Builder) & {readonly namespace: string},
401
+ ...segments: string[]
402
+ ): Builder =>
403
+ new Builder(appendSegments(new URL(relativeUrlBase), [Builder.namespace, ...segments]))
404
+
405
+ const createUrls = <const Builders extends BuilderRegistry>(
406
+ builders: Builders,
407
+ ): Urls & BuilderMethods<Builders> => {
408
+ function studios(): DashboardUrl
409
+ function studios(appId: string): StudioUrl
410
+ function studios(appId?: string): DashboardUrl | StudioUrl {
411
+ return appId === undefined
412
+ ? new UrlBuilder(new URL('/studios/', relativeUrlBase))
413
+ : createRootBuilder(StudioUrlBuilder, appId)
414
+ }
415
+
416
+ function applications(): DashboardUrl
417
+ function applications(appId: string): CoreApplicationUrl
418
+ function applications(appId?: string): DashboardUrl | CoreApplicationUrl {
419
+ return appId === undefined
420
+ ? new UrlBuilder(new URL('/applications/', relativeUrlBase))
421
+ : createRootBuilder(CoreApplicationUrlBuilder, appId)
422
+ }
423
+
424
+ const methods = Object.fromEntries(
425
+ Object.entries(builders).map(([name, Builder]) => [name, () => createRootBuilder(Builder)]),
426
+ )
427
+
428
+ const urls = {
429
+ studios,
430
+ applications,
431
+ mediaLibrary: () => createRootBuilder(MediaLibraryUrlBuilder),
432
+ canvas: () => createRootBuilder(CanvasUrlBuilder),
433
+ home: () => new UrlBuilder(new URL(relativeUrlBase)),
434
+ extend<const AddedBuilders extends BuilderRegistry>(addedBuilders: AddedBuilders) {
435
+ const namespaces = new Set([
436
+ '',
437
+ StudioUrlBuilder.namespace,
438
+ CoreApplicationUrlBuilder.namespace,
439
+ MediaLibraryUrlBuilder.namespace,
440
+ CanvasUrlBuilder.namespace,
441
+ ...Object.values(builders).map((Builder) => Builder.namespace),
442
+ ])
443
+
444
+ for (const [name, Builder] of Object.entries(addedBuilders)) {
445
+ if (name in urls || name in methods) {
446
+ throw new Error(`URL builder "${name}" already exists`)
447
+ }
448
+ if (namespaces.has(Builder.namespace)) {
449
+ throw new Error(`URL namespace "${Builder.namespace}" already exists`)
450
+ }
451
+ namespaces.add(Builder.namespace)
452
+ }
453
+
454
+ return createUrls({...builders, ...addedBuilders})
455
+ },
456
+ }
457
+
458
+ return Object.assign(urls, methods) as Urls & BuilderMethods<Builders>
459
+ }
460
+
461
+ /** @public */
462
+ export const urlFor: Urls = createUrls({})
@@ -19,7 +19,7 @@ test('useApplication — no include: the base application', () => {
19
19
  test('useApplication — config.studio include adds config.studio', () => {
20
20
  const result = useApplication('app_1', {include: ['config.studio']})
21
21
  expectTypeOf(result.data).toEqualTypeOf<Application<'config.studio'>>()
22
- expectTypeOf(result.data.config.studio).toEqualTypeOf<ApplicationStudioConfig>()
22
+ expectTypeOf(result.data.config.studio).toEqualTypeOf<ApplicationStudioConfig | undefined>()
23
23
  })
24
24
 
25
25
  test('useApplication — a deployment-child include forces the deployment in', () => {
@@ -0,0 +1,16 @@
1
+ import {handleOAuthCallback} from '@sanity/sdk'
2
+ import {identity} from 'rxjs'
3
+ import {describe, it} from 'vitest'
4
+
5
+ import {createCallbackHook} from '../helpers/createCallbackHook'
6
+
7
+ vi.mock('../helpers/createCallbackHook', () => ({createCallbackHook: vi.fn(identity)}))
8
+ vi.mock('@sanity/sdk', () => ({handleOAuthCallback: vi.fn()}))
9
+
10
+ describe('useHandleOAuthCallback', () => {
11
+ it('calls `createCallbackHook` with `handleOAuthCallback`', async () => {
12
+ const {useHandleOAuthCallback} = await import('./useHandleOAuthCallback')
13
+ expect(createCallbackHook).toHaveBeenCalledWith(handleOAuthCallback)
14
+ expect(useHandleOAuthCallback).toBe(handleOAuthCallback)
15
+ })
16
+ })
@@ -0,0 +1,49 @@
1
+ import {handleOAuthCallback} from '@sanity/sdk'
2
+
3
+ import {createCallbackHook} from '../helpers/createCallbackHook'
4
+
5
+ /**
6
+ * A React hook that returns a function for handling the OAuth redirect callback.
7
+ *
8
+ * @remarks
9
+ * This is the OAuth counterpart to `useHandleAuthCallback`. The returned
10
+ * function invokes core's `handleOAuthCallback`, which validates the `state`
11
+ * parameter, surfaces `?error=` redirects, exchanges the authorization `code`
12
+ * for tokens, persists them, and transitions the auth state to `LOGGED_IN` —
13
+ * all in core. On success it resolves the same-origin location the user was on
14
+ * when the flow started (so deep links survive login), otherwise the callback
15
+ * URL cleaned of the OAuth params (`code`, `state`, `error`,
16
+ * `error_description`). It resolves `false` when there was nothing to handle.
17
+ * The resolved URL may be a different route, so navigate to it rather than
18
+ * only calling `history.replaceState`.
19
+ *
20
+ * `AuthBoundary` runs this for you when the app lands on the OAuth redirect
21
+ * URI. Reach for this hook only when building a custom callback component.
22
+ *
23
+ * Concurrent calls are single-flight in core, so React StrictMode's double
24
+ * invocation will not trigger a second code exchange, and a repeated call with
25
+ * a stale callback URL is ignored once a session is established.
26
+ *
27
+ * @example
28
+ * ```tsx
29
+ * function OAuthCallback() {
30
+ * const handleCallback = useHandleOAuthCallback()
31
+ * const navigate = useNavigate() // your router's navigation
32
+ *
33
+ * useEffect(() => {
34
+ * handleCallback(window.location.href)
35
+ * .then((nextUrl) => {
36
+ * // Returns the user to where they started, with OAuth params removed
37
+ * if (nextUrl) navigate(nextUrl, {replace: true})
38
+ * })
39
+ * .catch(console.error)
40
+ * }, [handleCallback, navigate])
41
+ *
42
+ * return <div>Completing sign-in…</div>
43
+ * }
44
+ * ```
45
+ *
46
+ * @returns A callback handler that processes the OAuth redirect
47
+ * @public
48
+ */
49
+ export const useHandleOAuthCallback = createCallbackHook(handleOAuthCallback)
@@ -0,0 +1,16 @@
1
+ import {startOAuthAuthorization} from '@sanity/sdk'
2
+ import {identity} from 'rxjs'
3
+ import {describe, it} from 'vitest'
4
+
5
+ import {createCallbackHook} from '../helpers/createCallbackHook'
6
+
7
+ vi.mock('../helpers/createCallbackHook', () => ({createCallbackHook: vi.fn(identity)}))
8
+ vi.mock('@sanity/sdk', () => ({startOAuthAuthorization: vi.fn()}))
9
+
10
+ describe('useOAuthAuthorize', () => {
11
+ it('calls `createCallbackHook` with `startOAuthAuthorization`', async () => {
12
+ const {useOAuthAuthorize} = await import('./useOAuthAuthorize')
13
+ expect(createCallbackHook).toHaveBeenCalledWith(startOAuthAuthorization)
14
+ expect(useOAuthAuthorize).toBe(startOAuthAuthorization)
15
+ })
16
+ })
@@ -0,0 +1,28 @@
1
+ import {startOAuthAuthorization} from '@sanity/sdk'
2
+
3
+ import {createCallbackHook} from '../helpers/createCallbackHook'
4
+
5
+ /**
6
+ * A React hook that returns a function for starting the OAuth authorization-code + PKCE flow.
7
+ *
8
+ * @remarks
9
+ * The returned function invokes core's `startOAuthAuthorization`, which generates
10
+ * the PKCE `code_verifier`, `code_challenge` and `state`, persists the verifier and
11
+ * state to `sessionStorage`, and navigates the browser to the authorize endpoint.
12
+ * `clientId`, `redirectUri` and `organizationId` are read from the instance's
13
+ * `auth.oauth` config. The returned promise rejects if the instance has no `auth.oauth` config.
14
+ *
15
+ * Pair with {@link useHandleOAuthCallback} on the redirect URI to complete the flow.
16
+ *
17
+ * @example
18
+ * ```tsx
19
+ * function LoginButton() {
20
+ * const authorize = useOAuthAuthorize()
21
+ * return <button onClick={() => authorize().catch(console.error)}>Sign in</button>
22
+ * }
23
+ * ```
24
+ *
25
+ * @returns A function that starts the OAuth flow by navigating to the authorization URL
26
+ * @public
27
+ */
28
+ export const useOAuthAuthorize = createCallbackHook(startOAuthAuthorization)