-
Notifications
You must be signed in to change notification settings - Fork 392
/
prepareConfig.ts
519 lines (468 loc) · 15.7 KB
/
prepareConfig.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
/* eslint-disable max-nested-callbacks */
import createClient, {SanityClient} from '@sanity/client'
import {map, shareReplay} from 'rxjs/operators'
import {CurrentUser, Schema} from '@sanity/types'
import {studioTheme} from '@sanity/ui'
import {startCase} from 'lodash'
import {fromUrl} from '@sanity/bifur-client'
import {createElement, isValidElement} from 'react'
import {isValidElementType} from 'react-is'
import {createSchema} from '../schema'
import {AuthStore, createAuthStore} from '../store/_legacy'
import {FileSource, ImageSource} from '../form/studio/assetSource'
import {InitialValueTemplateItem, Template, TemplateResponse} from '../templates'
import {isNonNullable} from '../util'
import {validateWorkspaces} from '../studio'
import {filterDefinitions} from '../studio/components/navbar/search/definitions/defaultFilters'
import {operatorDefinitions} from '../studio/components/navbar/search/definitions/operators/defaultOperators'
import {
Config,
PreparedConfig,
SingleWorkspace,
Source,
SourceClientOptions,
SourceOptions,
WorkspaceOptions,
WorkspaceSummary,
} from './types'
import {
documentActionsReducer,
documentBadgesReducer,
documentLanguageFilterReducer,
fileAssetSourceResolver,
imageAssetSourceResolver,
initialDocumentActions,
initialDocumentBadges,
initialLanguageFilter,
newDocumentOptionsResolver,
resolveProductionUrlReducer,
schemaTemplatesReducer,
schemaTypesReducer,
toolsReducer,
} from './configPropertyReducers'
import {resolveConfigProperty} from './resolveConfigProperty'
import {ConfigResolutionError} from './ConfigResolutionError'
import {SchemaError} from './SchemaError'
import {createDefaultIcon} from './createDefaultIcon'
type InternalSource = WorkspaceSummary['__internal']['sources'][number]
function normalizeIcon(
icon: React.ComponentType | React.ElementType | undefined,
title: string,
subtitle = ''
): JSX.Element {
if (isValidElementType(icon)) return createElement(icon)
if (isValidElement(icon)) return icon
return createDefaultIcon(title, subtitle)
}
/**
* Takes in a config (created from the `defineConfig` function) and returns
* an array of `WorkspaceSummary`. Note: this only partially resolves a config.
*
* For usage inside the Studio, it's preferred to pull the pre-resolved
* workspaces and sources via `useWorkspace` or `useSource`. For usage outside
* the Studio or for testing, use `resolveConfig`.
*
* @internal
*/
export function prepareConfig(config: Config): PreparedConfig {
const workspaceOptions: WorkspaceOptions[] | [SingleWorkspace] = Array.isArray(config)
? config
: [config]
try {
validateWorkspaces({workspaces: workspaceOptions})
} catch (e) {
throw new ConfigResolutionError({
name: '',
type: 'workspace',
causes: [e.message],
})
}
const workspaces = workspaceOptions.map(
({unstable_sources: nestedSources = [], ...rootSource}): WorkspaceSummary => {
const sources = [rootSource as SourceOptions, ...nestedSources]
const resolvedSources = sources.map((source): InternalSource => {
const clientFactory = source.unstable_clientFactory || createClient
const projectId = source.projectId
const dataset = source.dataset
const auth = source.auth || createAuthStore({clientFactory, dataset, projectId})
let schemaTypes
try {
schemaTypes = resolveConfigProperty({
propertyName: 'schema.types',
config: source,
context: {projectId, dataset},
initialValue: [],
reducer: schemaTypesReducer,
})
} catch (e) {
throw new ConfigResolutionError({
name: source.name,
type: 'source',
causes: [e],
})
}
const schema = createSchema({
name: source.name,
types: schemaTypes,
})
const schemaValidationProblemGroups = schema._validation
const schemaErrors = schemaValidationProblemGroups?.filter((msg) =>
msg.problems.some((p) => p.severity === 'error')
)
if (schemaValidationProblemGroups && schemaErrors?.length) {
// TODO: consider using the `ConfigResolutionError`
throw new SchemaError(schema)
}
const source$ = auth.state.pipe(
map(({client, authenticated, currentUser}) => {
return resolveSource({
config: source,
client,
currentUser,
schema,
authenticated,
auth,
})
}),
shareReplay(1)
)
return Object.assign(source$, {
name: source.name,
projectId: source.projectId,
dataset: source.dataset,
title: source.title || startCase(source.name),
auth,
schema,
})
})
const title = rootSource.title || startCase(rootSource.name)
const workspaceSummary: WorkspaceSummary = {
type: 'workspace-summary',
auth: resolvedSources[0].auth,
basePath: rootSource.basePath || '/',
dataset: rootSource.dataset,
schema: resolvedSources[0].schema,
icon: normalizeIcon(
rootSource.icon,
title,
`${rootSource.projectId} ${rootSource.dataset}`
),
name: rootSource.name || 'default',
projectId: rootSource.projectId,
theme: rootSource.theme || studioTheme,
title,
subtitle: rootSource.subtitle,
__internal: {
sources: resolvedSources,
},
}
return workspaceSummary
}
)
return {type: 'prepared-config', workspaces}
}
interface ResolveSourceOptions {
config: SourceOptions
schema: Schema
client: SanityClient
currentUser: CurrentUser | null
authenticated: boolean
auth: AuthStore
}
function getBifurClient(client: SanityClient, auth: AuthStore) {
const bifurVersionedClient = client.withConfig({apiVersion: '2022-06-30'})
const dataset = bifurVersionedClient.config().dataset
const url = bifurVersionedClient.getUrl(`/socket/${dataset}`).replace(/^http/, 'ws')
const options = auth.token ? {token$: auth.token} : {}
return fromUrl(url, options)
}
function resolveSource({
config,
client,
currentUser,
schema,
authenticated,
auth,
}: ResolveSourceOptions): Source {
const {dataset, projectId} = config
const bifur = getBifurClient(client, auth)
const errors: unknown[] = []
const clients: Record<string, SanityClient> = {}
const getClient = (options: SourceClientOptions): SanityClient => {
if (!options || !options.apiVersion) {
throw new Error('Missing required `apiVersion` option')
}
if (!clients[options.apiVersion]) {
clients[options.apiVersion] = client.withConfig(options)
}
return clients[options.apiVersion]
}
const context = {
client,
getClient,
currentUser,
dataset,
projectId,
schema,
}
// <TEMPORARY UGLY HACK TO PRINT DEPRECATION WARNINGS ON USE>
/* eslint-disable no-proto */
const wrappedClient = client as any
context.client = [...Object.keys(client), ...Object.keys(wrappedClient.__proto__)].reduce(
(acc, key) => {
const original = Object.hasOwnProperty.call(client, key)
? wrappedClient[key]
: wrappedClient.__proto__[key]
return Object.defineProperty(acc, key, {
get() {
console.warn(
'`configContext.client` is deprecated and will be removed in the next release! Use `context.getClient({apiVersion: "2021-06-07"})` instead'
)
return original
},
})
},
{}
) as any as SanityClient
/* eslint-enable no-proto */
// </TEMPORARY UGLY HACK TO PRINT DEPRECATION WARNINGS ON USE>
let templates!: Source['templates']
try {
templates = resolveConfigProperty({
config,
context,
propertyName: 'schema.templates',
reducer: schemaTemplatesReducer,
initialValue: schema
.getTypeNames()
.filter((typeName) => !/^sanity\./.test(typeName))
.map((typeName) => schema.get(typeName))
.filter(isNonNullable)
.filter((schemaType) => schemaType.type?.name === 'document')
.map((schemaType) => {
const template: Template = {
id: schemaType.name,
schemaType: schemaType.name,
title: schemaType.title || schemaType.name,
icon: schemaType.icon,
value: schemaType.initialValue || {_type: schemaType.name},
}
return template
}),
})
// TODO: validate templates
// TODO: validate that each one has a unique template ID
} catch (e) {
errors.push(e)
}
let tools!: Source['tools']
try {
tools = resolveConfigProperty({
config,
context,
initialValue: [],
propertyName: 'tools',
reducer: toolsReducer,
})
} catch (e) {
errors.push(e)
}
// In this case we want to throw an error because it is not possible to have
// a tool with the name "tool" due to logic that happens in the router.
if (tools.some(({name}) => name === 'tool')) {
throw new Error('A tool cannot have the name "tool". Please enter a different name.')
}
const initialTemplatesResponses = templates
// filter out the ones with parameters to fill
.filter((template) => !template.parameters?.length)
.map(
(template): TemplateResponse => ({
templateId: template.id,
description: template.description,
icon: template.icon,
title: template.title,
})
)
const templateMap = templates.reduce((acc, template) => {
acc.set(template.id, template)
return acc
}, new Map<string, Template>())
// TODO: extract this function
const resolveNewDocumentOptions: Source['document']['resolveNewDocumentOptions'] = (
creationContext
) => {
const {schemaType: schemaTypeName} = creationContext
const templateResponses = resolveConfigProperty({
config,
context: {...context, creationContext},
initialValue: initialTemplatesResponses,
propertyName: 'document.resolveNewDocumentOptions',
reducer: newDocumentOptionsResolver,
})
const templateErrors: unknown[] = []
// TODO: validate template responses
// ensure there is a matching template per each one
if (templateErrors.length) {
throw new ConfigResolutionError({
name: config.name,
// TODO: figure out this name
type: 'source',
causes: templateErrors,
})
}
return (
templateResponses
// take the template responses and transform them into the formal
// `InitialValueTemplateItem`
.map((response, index): InitialValueTemplateItem => {
const template = templateMap.get(response.templateId)
if (!template) {
throw new Error(`Could not find template with ID \`${response.templateId}\``)
}
const schemaType = schema.get(template.schemaType)
if (!schemaType) {
throw new Error(
`Could not find matching schema type \`${template.schemaType}\` for template \`${template.id}\``
)
}
const title = response.title || template.title
// Don't show the type name as subtitle if it's the same as the template name
const defaultSubtitle = schemaType?.title === title ? undefined : schemaType?.title
return {
id: `${response.templateId}-${index}`,
templateId: response.templateId,
type: 'initialValueTemplateItem',
title,
subtitle: response.subtitle || defaultSubtitle,
description: response.description || template.description,
icon: response.icon || template.icon || schemaType?.icon,
initialDocumentId: response.initialDocumentId,
parameters: response.parameters,
schemaType: template.schemaType,
}
})
.filter((item) => {
// if we are in a creationContext where there is no schema type,
// then keep everything
if (!schemaTypeName) return true
// else only keep the `schemaType`s that match the creationContext
return schemaTypeName === templateMap.get(item.templateId)?.schemaType
})
)
}
let staticInitialValueTemplateItems!: InitialValueTemplateItem[]
try {
staticInitialValueTemplateItems = resolveNewDocumentOptions({type: 'global'})
} catch (e) {
errors.push(e)
}
if (errors.length) {
throw new ConfigResolutionError({
name: config.name,
type: 'source',
causes: errors,
})
}
const source: Source = {
type: 'source',
name: config.name,
title: config.title || startCase(config.name),
schema,
getClient,
dataset,
projectId,
tools,
currentUser,
authenticated,
templates,
auth,
document: {
actions: (partialContext) =>
resolveConfigProperty({
config,
context: {...context, ...partialContext},
initialValue: initialDocumentActions,
propertyName: 'document.actions',
reducer: documentActionsReducer,
}),
badges: (partialContext) =>
resolveConfigProperty({
config,
context: {...context, ...partialContext},
initialValue: initialDocumentBadges,
propertyName: 'document.badges',
reducer: documentBadgesReducer,
}),
resolveProductionUrl: (partialContext) =>
resolveConfigProperty({
config,
context: {...context, ...partialContext},
initialValue: undefined,
propertyName: 'resolveProductionUrl',
asyncReducer: resolveProductionUrlReducer,
}),
resolveNewDocumentOptions,
unstable_languageFilter: (partialContext) =>
resolveConfigProperty({
config,
context: {...context, ...partialContext},
initialValue: initialLanguageFilter,
propertyName: 'document.unstable_languageFilter',
reducer: documentLanguageFilterReducer,
}),
},
form: {
file: {
assetSources: resolveConfigProperty({
config,
context,
initialValue: [FileSource],
propertyName: 'formBuilder.file.assetSources',
reducer: fileAssetSourceResolver,
}),
directUploads:
// TODO: consider refactoring this to `noDirectUploads` or similar
// default value for this is `true`
config.form?.file?.directUploads === undefined ? true : config.form.file.directUploads,
},
image: {
assetSources: resolveConfigProperty({
config,
context,
initialValue: [ImageSource],
propertyName: 'formBuilder.image.assetSources',
reducer: imageAssetSourceResolver,
}),
directUploads:
// TODO: consider refactoring this to `noDirectUploads` or similar
// default value for this is `true`
config.form?.file?.directUploads === undefined ? true : config.form.file.directUploads,
},
},
search: {
filters: filterDefinitions,
operators: operatorDefinitions,
// we will use this when we add search config to PluginOptions
/*filters: resolveConfigProperty({
config,
context: context,
initialValue: filterDefinitions,
propertyName: 'search.filters',
reducer: searchFilterReducer,
}),
operators: resolveConfigProperty({
config,
context: context,
initialValue: operatorDefinitions as SearchOperatorDefinition[],
propertyName: 'search.operators',
reducer: searchOperatorsReducer,
}),*/
},
__internal: {
bifur,
staticInitialValueTemplateItems,
options: config,
},
}
return source
}