@sanity/client 4.0.1-1 → 5.0.0-esm.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 (68) hide show
  1. package/dist/index.browser.cjs +1335 -0
  2. package/dist/index.browser.cjs.map +1 -0
  3. package/dist/index.browser.js +1312 -0
  4. package/dist/index.browser.js.map +1 -0
  5. package/dist/index.cjs +1344 -0
  6. package/dist/index.cjs.js +15 -0
  7. package/dist/index.cjs.map +1 -0
  8. package/{sanityClient.d.ts → dist/index.d.ts} +991 -1117
  9. package/dist/index.js +1321 -0
  10. package/dist/index.js.map +1 -0
  11. package/package.json +81 -73
  12. package/src/SanityClient.ts +1261 -0
  13. package/src/assets/AssetsClient.ts +164 -0
  14. package/src/auth/AuthClient.ts +43 -0
  15. package/src/config.ts +95 -0
  16. package/src/data/dataMethods.ts +328 -0
  17. package/src/data/encodeQueryString.ts +28 -0
  18. package/src/data/listen.ts +195 -0
  19. package/src/data/patch.ts +353 -0
  20. package/src/data/transaction.ts +352 -0
  21. package/src/datasets/DatasetsClient.ts +97 -0
  22. package/src/generateHelpUrl.ts +5 -0
  23. package/src/http/browserMiddleware.ts +1 -0
  24. package/src/http/errors.ts +68 -0
  25. package/src/http/nodeMiddleware.ts +11 -0
  26. package/src/http/request.ts +50 -0
  27. package/src/http/requestOptions.ts +31 -0
  28. package/src/index.browser.ts +18 -0
  29. package/src/index.ts +57 -0
  30. package/src/projects/ProjectsClient.ts +45 -0
  31. package/src/types.ts +502 -0
  32. package/src/users/UsersClient.ts +46 -0
  33. package/src/util/defaults.ts +8 -0
  34. package/src/util/getSelection.ts +21 -0
  35. package/src/util/once.ts +12 -0
  36. package/src/util/pick.ts +9 -0
  37. package/src/validators.ts +76 -0
  38. package/src/warnings.ts +25 -0
  39. package/umd/sanityClient.js +5199 -5302
  40. package/umd/sanityClient.min.js +13 -13
  41. package/dist/sanityClient.browser.mjs +0 -2806
  42. package/dist/sanityClient.browser.mjs.map +0 -7
  43. package/index.js +0 -7
  44. package/lib/assets/assetsClient.js +0 -145
  45. package/lib/auth/authClient.js +0 -26
  46. package/lib/config.js +0 -88
  47. package/lib/data/dataMethods.js +0 -205
  48. package/lib/data/encodeQueryString.js +0 -31
  49. package/lib/data/listen.js +0 -164
  50. package/lib/data/patch.js +0 -121
  51. package/lib/data/transaction.js +0 -117
  52. package/lib/datasets/datasetsClient.js +0 -41
  53. package/lib/generateHelpUrl.js +0 -11
  54. package/lib/http/browserMiddleware.js +0 -9
  55. package/lib/http/errors.js +0 -56
  56. package/lib/http/nodeMiddleware.js +0 -22
  57. package/lib/http/queryString.js +0 -17
  58. package/lib/http/request.js +0 -52
  59. package/lib/http/requestOptions.js +0 -30
  60. package/lib/projects/projectsClient.js +0 -25
  61. package/lib/sanityClient.js +0 -118
  62. package/lib/users/usersClient.js +0 -20
  63. package/lib/util/defaults.js +0 -14
  64. package/lib/util/getSelection.js +0 -24
  65. package/lib/util/once.js +0 -20
  66. package/lib/util/pick.js +0 -17
  67. package/lib/validators.js +0 -76
  68. package/lib/warnings.js +0 -27
@@ -0,0 +1,45 @@
1
+ import {type Observable} from 'rxjs'
2
+
3
+ import type {ObservableSanityClient, SanityClient} from '../SanityClient'
4
+ import type {SanityProject} from '../types'
5
+
6
+ export class BaseProjectsClient {
7
+ client: SanityClient | ObservableSanityClient
8
+
9
+ /**
10
+ * Fetch a list of projects the authenticated user has access to
11
+ */
12
+ list(this: ProjectsClient): Promise<SanityProject[]>
13
+ list(this: ObservableProjectsClient): Observable<SanityProject[]>
14
+ list(): Promise<SanityProject[]> | Observable<SanityProject[]> {
15
+ return this.client.request({uri: '/projects'})
16
+ }
17
+
18
+ /**
19
+ * Fetch a project by project ID
20
+ *
21
+ * @param projectId - ID of the project to fetch
22
+ */
23
+ getById(this: ProjectsClient, projectId: string): Promise<SanityProject>
24
+ getById(this: ObservableProjectsClient, projectId: string): Observable<SanityProject>
25
+ getById(projectId: string): Promise<SanityProject> | Observable<SanityProject> {
26
+ return this.client.request({uri: `/projects/${projectId}`})
27
+ }
28
+ }
29
+
30
+ export class ObservableProjectsClient extends BaseProjectsClient {
31
+ client: ObservableSanityClient
32
+
33
+ constructor(client: ObservableSanityClient) {
34
+ super()
35
+ this.client = client
36
+ }
37
+ }
38
+
39
+ export class ProjectsClient extends BaseProjectsClient {
40
+ client: SanityClient
41
+ constructor(client: SanityClient) {
42
+ super()
43
+ this.client = client
44
+ }
45
+ }
package/src/types.ts ADDED
@@ -0,0 +1,502 @@
1
+ import type {Requester} from 'get-it'
2
+
3
+ export interface RequestOptions {
4
+ timeout?: number
5
+ token?: string
6
+ tag?: string
7
+ headers?: Record<string, string>
8
+ method?: string
9
+ query?: any
10
+ body?: any
11
+ }
12
+
13
+ export interface ClientConfig {
14
+ projectId?: string
15
+ dataset?: string
16
+ useCdn?: boolean
17
+ token?: string
18
+ apiHost?: string
19
+ apiVersion?: string
20
+ proxy?: string
21
+ requestTagPrefix?: string
22
+ ignoreBrowserTokenWarning?: boolean
23
+ withCredentials?: boolean
24
+ allowReconfigure?: boolean
25
+ timeout?: number
26
+
27
+ /**
28
+ * @deprecated Don't use
29
+ */
30
+ useProjectHostname?: boolean
31
+
32
+ /**
33
+ * @deprecated Don't use
34
+ */
35
+ requester?: Requester
36
+ }
37
+
38
+ export interface InitializedClientConfig extends ClientConfig {
39
+ // These are required in the initialized config
40
+ apiHost: string
41
+ apiVersion: string
42
+ useProjectHostname: boolean
43
+ useCdn: boolean
44
+ // These are added by the initConfig function
45
+ // @TODO consider moving these to private properties on the class instead of adding them to the config
46
+ /**
47
+ * @deprecated Don't use
48
+ */
49
+ isDefaultApi: boolean
50
+ /**
51
+ * @deprecated Don't use
52
+ */
53
+ url: string
54
+ /**
55
+ * @deprecated Don't use
56
+ */
57
+ cdnUrl: string
58
+ }
59
+
60
+ export type AssetMetadataType =
61
+ | 'location'
62
+ | 'exif'
63
+ | 'image'
64
+ | 'palette'
65
+ | 'lqip'
66
+ | 'blurhash'
67
+ | 'none'
68
+
69
+ export interface UploadClientConfig {
70
+ /**
71
+ * Optional request tag for the upload
72
+ */
73
+ tag?: string
74
+
75
+ /**
76
+ * Whether or not to preserve the original filename (default: true)
77
+ */
78
+ preserveFilename?: boolean
79
+
80
+ /**
81
+ * Filename for this file (optional)
82
+ */
83
+ filename?: string
84
+
85
+ /**
86
+ * Milliseconds to wait before timing the request out
87
+ */
88
+ timeout?: number
89
+
90
+ /**
91
+ * Mime type of the file
92
+ */
93
+ contentType?: string
94
+
95
+ /**
96
+ * Array of metadata parts to extract from asset
97
+ */
98
+ extract?: AssetMetadataType[]
99
+
100
+ /**
101
+ * Optional freeform label for the asset. Generally not used.
102
+ */
103
+ label?: string
104
+
105
+ /**
106
+ * Optional title for the asset
107
+ */
108
+ title?: string
109
+
110
+ /**
111
+ * Optional description for the asset
112
+ */
113
+ description?: string
114
+
115
+ /**
116
+ * The credit to person(s) and/or organization(s) required by the supplier of the asset to be used when published
117
+ */
118
+ creditLine?: string
119
+
120
+ /**
121
+ * Source data (when the asset is from an external service)
122
+ */
123
+ source?: {
124
+ /**
125
+ * The (u)id of the asset within the source, i.e. 'i-f323r1E'
126
+ */
127
+ id: string
128
+
129
+ /**
130
+ * The name of the source, i.e. 'unsplash'
131
+ */
132
+ name: string
133
+
134
+ /**
135
+ * A url to where to find the asset, or get more info about it in the source
136
+ */
137
+ url?: string
138
+ }
139
+ }
140
+
141
+ export interface SanityReference {
142
+ _ref: string
143
+ }
144
+
145
+ export type SanityDocument<T extends Record<string, any> = Record<string, any>> = {
146
+ [P in keyof T]: T[P]
147
+ } & {
148
+ _id: string
149
+ _rev: string
150
+ _type: string
151
+ _createdAt: string
152
+ _updatedAt: string
153
+ }
154
+
155
+ export interface SanityAssetDocument extends SanityDocument {
156
+ url: string
157
+ path: string
158
+ size: number
159
+ assetId: string
160
+ mimeType: string
161
+ sha1hash: string
162
+ extension: string
163
+ uploadId?: string
164
+ originalFilename?: string
165
+ }
166
+
167
+ export interface SanityImagePalette {
168
+ background: string
169
+ foreground: string
170
+ population: number
171
+ title: string
172
+ }
173
+
174
+ export interface SanityImageAssetDocument extends SanityAssetDocument {
175
+ metadata: {
176
+ _type: 'sanity.imageMetadata'
177
+ hasAlpha: boolean
178
+ isOpaque: boolean
179
+ lqip?: string
180
+ blurHash?: string
181
+ dimensions: {
182
+ _type: 'sanity.imageDimensions'
183
+ aspectRatio: number
184
+ height: number
185
+ width: number
186
+ }
187
+ palette?: {
188
+ _type: 'sanity.imagePalette'
189
+ darkMuted?: SanityImagePalette
190
+ darkVibrant?: SanityImagePalette
191
+ dominant?: SanityImagePalette
192
+ lightMuted?: SanityImagePalette
193
+ lightVibrant?: SanityImagePalette
194
+ muted?: SanityImagePalette
195
+ vibrant?: SanityImagePalette
196
+ }
197
+ image?: {
198
+ _type: 'sanity.imageExifTags'
199
+ [key: string]: any
200
+ }
201
+ exif?: {
202
+ _type: 'sanity.imageExifMetadata'
203
+ [key: string]: any
204
+ }
205
+ }
206
+ }
207
+
208
+ export interface ErrorProps {
209
+ message: string
210
+ response: any
211
+ statusCode: number
212
+ responseBody: any
213
+ details: any
214
+ }
215
+
216
+ export type HttpRequest = {
217
+ defaultRequester: Requester
218
+ (options: RequestOptions, requester: Requester): ReturnType<Requester>
219
+ }
220
+
221
+ export interface RequestObservableOptions extends Omit<RequestOptions, 'url'> {
222
+ url?: string
223
+ uri?: string
224
+ canUseCdn?: boolean
225
+ tag?: string
226
+ }
227
+
228
+ export interface ProgressEvent {
229
+ type: 'progress'
230
+ stage: 'upload' | 'download'
231
+ percent: number
232
+ total?: number
233
+ loaded?: number
234
+ lengthComputable: boolean
235
+ }
236
+
237
+ export interface ResponseEvent<T = unknown> {
238
+ type: 'response'
239
+ body: T
240
+ url: string
241
+ method: string
242
+ statusCode: number
243
+ statusMessage?: string
244
+ headers: Record<string, string>
245
+ }
246
+
247
+ export type HttpRequestEvent<T = unknown> = ResponseEvent<T> | ProgressEvent
248
+
249
+ export interface AuthProvider {
250
+ name: string
251
+ title: string
252
+ url: string
253
+ }
254
+
255
+ export type AuthProviderResponse = {providers: AuthProvider[]}
256
+
257
+ export type DatasetAclMode = 'public' | 'private' | 'custom'
258
+
259
+ export type DatasetResponse = {datasetName: string; aclMode: DatasetAclMode}
260
+ export type DatasetsResponse = {name: string; aclMode: DatasetAclMode}[]
261
+
262
+ export interface SanityProjectMember {
263
+ id: string
264
+ role: string
265
+ isRobot: boolean
266
+ isCurrentUser: boolean
267
+ }
268
+
269
+ export interface SanityProject {
270
+ id: string
271
+ displayName: string
272
+ studioHost: string | null
273
+ organizationId: string | null
274
+ isBlocked: boolean
275
+ isDisabled: boolean
276
+ isDisabledByUser: boolean
277
+ createdAt: string
278
+ pendingInvites?: number
279
+ maxRetentionDays?: number
280
+ members: SanityProjectMember[]
281
+ metadata: {
282
+ color?: string
283
+ externalStudioHost?: string
284
+ }
285
+ }
286
+
287
+ export interface SanityUser {
288
+ id: string
289
+ projectId: string
290
+ displayName: string
291
+ familyName: string | null
292
+ givenName: string | null
293
+ middleName: string | null
294
+ imageUrl: string | null
295
+ createdAt: string
296
+ updatedAt: string
297
+ isCurrentUser: boolean
298
+ }
299
+
300
+ export interface CurrentSanityUser {
301
+ id: string
302
+ name: string
303
+ email: string
304
+ profileImage: string | null
305
+ role: string
306
+ }
307
+
308
+ export type SanityDocumentStub<T extends Record<string, any> = Record<string, any>> = {
309
+ [P in keyof T]: T[P]
310
+ } & {
311
+ _type: string
312
+ }
313
+
314
+ export type IdentifiedSanityDocumentStub<T extends Record<string, any> = Record<string, any>> = {
315
+ [P in keyof T]: T[P]
316
+ } & {
317
+ _id: string
318
+ } & SanityDocumentStub
319
+
320
+ export type InsertPatch =
321
+ | {before: string; items: any[]}
322
+ | {after: string; items: any[]}
323
+ | {replace: string; items: any[]}
324
+
325
+ // Note: this is actually incorrect/invalid, but implemented as-is for backwards compatibility
326
+ export interface PatchOperations {
327
+ set?: {[key: string]: any}
328
+ setIfMissing?: {[key: string]: any}
329
+ diffMatchPatch?: {[key: string]: any}
330
+ unset?: string[]
331
+ inc?: {[key: string]: number}
332
+ dec?: {[key: string]: number}
333
+ insert?: InsertPatch
334
+ ifRevisionID?: string
335
+ }
336
+
337
+ export type QueryParams = {[key: string]: any}
338
+ export type MutationSelection = {query: string; params?: QueryParams} | {id: string | string[]}
339
+ export type PatchSelection = string | string[] | MutationSelection
340
+ export type PatchMutationOperation = PatchOperations & MutationSelection
341
+
342
+ export type Mutation<R extends Record<string, any> = Record<string, any>> =
343
+ | {create: SanityDocumentStub<R>}
344
+ | {createOrReplace: IdentifiedSanityDocumentStub<R>}
345
+ | {createIfNotExists: IdentifiedSanityDocumentStub<R>}
346
+ | {delete: MutationSelection}
347
+ | {patch: PatchMutationOperation}
348
+
349
+ export type MutationEvent<R extends Record<string, any> = Record<string, any>> = {
350
+ type: 'mutation'
351
+ documentId: string
352
+ eventId: string
353
+ identity: string
354
+ mutations: Mutation[]
355
+ previousRev?: string
356
+ resultRev?: string
357
+ result?: SanityDocument<R>
358
+ previous?: SanityDocument<R> | null
359
+ effects?: {apply: unknown[]; revert: unknown[]}
360
+ timestamp: string
361
+ transactionId: string
362
+ transition: 'update' | 'appear' | 'disappear'
363
+ visibility: 'query' | 'transaction'
364
+ }
365
+
366
+ export type ChannelErrorEvent = {
367
+ type: 'channelError'
368
+ message: string
369
+ }
370
+
371
+ export type DisconnectEvent = {
372
+ type: 'disconnect'
373
+ reason: string
374
+ }
375
+
376
+ export type ReconnectEvent = {
377
+ type: 'reconnect'
378
+ }
379
+
380
+ export type WelcomeEvent = {
381
+ type: 'welcome'
382
+ }
383
+
384
+ export type ListenEvent<R extends Record<string, any>> =
385
+ | MutationEvent<R>
386
+ | ChannelErrorEvent
387
+ | DisconnectEvent
388
+ | ReconnectEvent
389
+ | WelcomeEvent
390
+
391
+ export type ListenEventName = 'mutation' | 'welcome' | 'reconnect'
392
+
393
+ export interface ListenOptions {
394
+ includeResult?: boolean
395
+ includePreviousRevision?: boolean
396
+ visibility?: 'sync' | 'async' | 'query'
397
+ events?: ListenEventName[]
398
+ effectFormat?: 'mendoza'
399
+ tag?: string
400
+ }
401
+
402
+ export type FilteredResponseQueryOptions = RequestOptions & {
403
+ filterResponse?: true
404
+ }
405
+
406
+ export type UnfilteredResponseQueryOptions = RequestOptions & {
407
+ filterResponse: false
408
+ }
409
+
410
+ export interface RawQueryResponse<R> {
411
+ q: string
412
+ ms: number
413
+ result: R
414
+ }
415
+
416
+ export type BaseMutationOptions = RequestOptions & {
417
+ visibility?: 'sync' | 'async' | 'deferred'
418
+ returnDocuments?: boolean
419
+ returnFirst?: boolean
420
+ dryRun?: boolean
421
+ autoGenerateArrayKeys?: boolean
422
+ skipCrossDatasetReferenceValidation?: boolean
423
+ }
424
+
425
+ export type FirstDocumentMutationOptions = BaseMutationOptions & {
426
+ returnFirst?: true
427
+ returnDocuments?: true
428
+ }
429
+
430
+ export type FirstDocumentIdMutationOptions = BaseMutationOptions & {
431
+ returnFirst?: true
432
+ returnDocuments: false
433
+ }
434
+
435
+ export type AllDocumentsMutationOptions = BaseMutationOptions & {
436
+ returnFirst: false
437
+ returnDocuments?: true
438
+ }
439
+
440
+ export type MutationOperation = 'create' | 'delete' | 'update' | 'none'
441
+
442
+ export interface SingleMutationResult {
443
+ transactionId: string
444
+ documentId: string
445
+ results: {id: string; operation: MutationOperation}[]
446
+ }
447
+
448
+ export interface MultipleMutationResult {
449
+ transactionId: string
450
+ documentIds: string[]
451
+ results: {id: string; operation: MutationOperation}[]
452
+ }
453
+
454
+ export type AllDocumentIdsMutationOptions = BaseMutationOptions & {
455
+ returnFirst: false
456
+ returnDocuments: false
457
+ }
458
+
459
+ export type AttributeSet = {[key: string]: any}
460
+
461
+ export type TransactionFirstDocumentMutationOptions = BaseMutationOptions & {
462
+ returnFirst: true
463
+ returnDocuments: true
464
+ }
465
+
466
+ export type TransactionFirstDocumentIdMutationOptions = BaseMutationOptions & {
467
+ returnFirst: true
468
+ returnDocuments?: false
469
+ }
470
+
471
+ export type TransactionAllDocumentsMutationOptions = BaseMutationOptions & {
472
+ returnFirst?: false
473
+ returnDocuments: true
474
+ }
475
+
476
+ export type TransactionAllDocumentIdsMutationOptions = BaseMutationOptions & {
477
+ returnFirst?: false
478
+ returnDocuments?: false
479
+ }
480
+
481
+ export type TransactionMutationOptions =
482
+ | TransactionFirstDocumentMutationOptions
483
+ | TransactionFirstDocumentIdMutationOptions
484
+ | TransactionAllDocumentsMutationOptions
485
+ | TransactionAllDocumentIdsMutationOptions
486
+
487
+ export interface RawRequestOptions {
488
+ url?: string
489
+ uri?: string
490
+ method?: string
491
+ token?: string
492
+ json?: boolean
493
+ tag?: string
494
+ useGlobalApi?: boolean
495
+ withCredentials?: boolean
496
+ query?: {[key: string]: string | string[]}
497
+ headers?: {[key: string]: string}
498
+ timeout?: number
499
+ proxy?: string
500
+ body?: any
501
+ maxRedirects?: number
502
+ }
@@ -0,0 +1,46 @@
1
+ import {type Observable} from 'rxjs'
2
+
3
+ import type {ObservableSanityClient, SanityClient} from '../SanityClient'
4
+ import type {CurrentSanityUser, SanityUser} from '../types'
5
+
6
+ export class BaseUsersClient {
7
+ client: SanityClient | ObservableSanityClient
8
+
9
+ /**
10
+ * Fetch a user by user ID
11
+ *
12
+ * @param id - User ID of the user to fetch. If `me` is provided, a minimal response including the users role is returned.
13
+ */
14
+ getById<T extends 'me' | string>(
15
+ this: UsersClient,
16
+ id: T
17
+ ): Promise<T extends 'me' ? CurrentSanityUser : SanityUser>
18
+ getById<T extends 'me' | string>(
19
+ this: ObservableUsersClient,
20
+ id: T
21
+ ): Observable<T extends 'me' ? CurrentSanityUser : SanityUser>
22
+ getById<T extends 'me' | string>(
23
+ id: T
24
+ ):
25
+ | Promise<T extends 'me' ? CurrentSanityUser : SanityUser>
26
+ | Observable<T extends 'me' ? CurrentSanityUser : SanityUser> {
27
+ return this.client.request({uri: `/users/${id}`})
28
+ }
29
+ }
30
+
31
+ export class ObservableUsersClient extends BaseUsersClient {
32
+ client: ObservableSanityClient
33
+
34
+ constructor(client: ObservableSanityClient) {
35
+ super()
36
+ this.client = client
37
+ }
38
+ }
39
+
40
+ export class UsersClient extends BaseUsersClient {
41
+ client: SanityClient
42
+ constructor(client: SanityClient) {
43
+ super()
44
+ this.client = client
45
+ }
46
+ }
@@ -0,0 +1,8 @@
1
+ export default (obj: any, defaults: any) =>
2
+ Object.keys(defaults)
3
+ .concat(Object.keys(obj))
4
+ .reduce((target, prop) => {
5
+ target[prop] = typeof obj[prop] === 'undefined' ? defaults[prop] : obj[prop]
6
+
7
+ return target
8
+ }, {} as any)
@@ -0,0 +1,21 @@
1
+ import type {MutationSelection} from '../types'
2
+
3
+ export default function getSelection(sel: unknown): MutationSelection {
4
+ if (typeof sel === 'string' || Array.isArray(sel)) {
5
+ return {id: sel}
6
+ }
7
+
8
+ if (typeof sel === 'object' && sel !== null && 'query' in sel && typeof sel.query === 'string') {
9
+ return 'params' in sel && typeof sel.params === 'object' && sel.params !== null
10
+ ? {query: sel.query, params: sel.params}
11
+ : {query: sel.query}
12
+ }
13
+
14
+ const selectionOpts = [
15
+ '* Document ID (<docId>)',
16
+ '* Array of document IDs',
17
+ '* Object containing `query`',
18
+ ].join('\n')
19
+
20
+ throw new Error(`Unknown selection - must be one of:\n\n${selectionOpts}`)
21
+ }
@@ -0,0 +1,12 @@
1
+ export default (fn: any) => {
2
+ let didCall = false
3
+ let returnValue: any
4
+ return (...args: any[]) => {
5
+ if (didCall) {
6
+ return returnValue
7
+ }
8
+ returnValue = fn(...args)
9
+ didCall = true
10
+ return returnValue
11
+ }
12
+ }
@@ -0,0 +1,9 @@
1
+ export default (obj: any, props: any) =>
2
+ props.reduce((selection: any, prop: any) => {
3
+ if (typeof obj[prop] === 'undefined') {
4
+ return selection
5
+ }
6
+
7
+ selection[prop] = obj[prop]
8
+ return selection
9
+ }, {})