-
Notifications
You must be signed in to change notification settings - Fork 3
/
helper.ts
420 lines (355 loc) · 10.2 KB
/
helper.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
import { readFileSync, lstatSync } from 'fs'
import { bold, cyan, green, red, yellow } from 'kleur/colors'
import { resolve } from 'path'
import { type Choice } from 'prompts'
import {
betterPrompts,
isValidPackageName,
promptName,
runCommand,
} from '../../utils'
import {
FieldType,
Scope,
StoryClientType,
StoryblokClient,
} from '../../storyblok/storyblok-client'
import { getErrorMessage } from '@storyblok/manifest-helper/src/utils'
import {
load,
Manifest,
MANIFEST_FILE_NAME,
ManifestOption,
} from '@storyblok/manifest-helper/src/manifest'
const packageNameMessage =
'How would you like to call the deployed field-plugin?\n (Lowercase alphanumeric and dash are allowed.)'
type UpsertFieldPluginFunc = (args: {
dir: string
packageName: string
skipPrompts?: boolean
token: string
output: string
scope: Scope
}) => Promise<{ id: number }>
type GetPackageName = (params: {
name?: string
skipPrompts: boolean
dir: string
}) => Promise<{ error: false; name: string } | { error: true }>
// TODO: move all side effects to the deploy function
export const upsertFieldPlugin: UpsertFieldPluginFunc = async (args) => {
const { packageName, skipPrompts, token, output, dir, scope } = args
const manifest = loadManifest()
printManifestOptions(manifest?.options)
const storyblokClient = StoryblokClient({ token, scope })
console.log(bold(cyan('[info] Checking existing field plugins...')))
const scopeFieldPlugins = await storyblokClient.fetchAllFieldTypes()
const fieldPluginFound = scopeFieldPlugins.find(
(fieldPlugin) => fieldPlugin.name === packageName,
)
if (fieldPluginFound) {
const mode = skipPrompts ? 'update' : await selectUpsertMode()
if (mode === 'create') {
const fieldPlugin = await createFieldPlugin(
storyblokClient,
'',
output,
manifest?.options,
dir,
scopeFieldPlugins,
skipPrompts,
)
return { id: fieldPlugin.id }
}
if (!skipPrompts) {
await confirmOptionsUpdate(manifest?.options)
}
await storyblokClient.updateFieldType({
id: fieldPluginFound.id,
publish: true,
field_type: {
body: output,
options: manifest?.options,
},
})
return { id: fieldPluginFound.id }
}
// create flow
const create = skipPrompts
? true
: await confirmCreatingFieldPlugin(packageName)
if (!create) {
console.log(cyan(bold('[info]')), 'Not creating a new field plugin.')
process.exit(1)
}
const fieldPlugin = await createFieldPlugin(
storyblokClient,
packageName,
output,
manifest?.options,
dir,
scopeFieldPlugins,
skipPrompts,
)
return { id: fieldPlugin.id }
}
export const getPackageName: GetPackageName = async ({
name,
skipPrompts,
dir,
}) => {
if (typeof name === 'string' && name !== '') {
return { error: false, name }
}
const packageJsonName = getPackageJsonName(dir)
if (skipPrompts === false) {
const nameFromPrompt = await promptName({
message: packageNameMessage,
initialValue: packageJsonName,
})
return {
error: false,
name: nameFromPrompt,
}
}
if (isValidPackageName(packageJsonName)) {
return { error: false, name: packageJsonName }
}
return { error: true }
}
export const getPackageJsonName = (path: string): string | undefined => {
if (!lstatSync(path).isDirectory()) {
return
}
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const json: { name: string } = JSON.parse(
readFileSync(resolve(path, 'package.json')).toString(),
)
if (!json.name) {
return
}
return json.name
}
export const selectUpsertMode = async () => {
const { mode } = await betterPrompts<{ mode: 'update' | 'create' }>([
{
type: 'select',
name: 'mode',
message: 'Update the existing field plugin?',
choices: [
{
title: 'Yes, update it.',
value: 'update',
},
{
title: 'No, create a new one.',
value: 'create',
},
],
},
])
return mode
}
export const confirmCreatingFieldPlugin = async (name: string) => {
const { create } = await betterPrompts<{ create: boolean }>({
type: 'confirm',
name: 'create',
message: `You want to deploy a new field plugin \`${name}\`?`,
initial: true,
})
return create
}
export const confirmUpdatingNameInPackageJson = async () => {
const { update } = await betterPrompts<{ update: boolean }>({
type: 'confirm',
name: 'update',
message: `Do you update the name in \`package.json\``,
initial: false,
})
return update
}
export const confirmNewName = async (currentName: string) => {
const { rename } = await betterPrompts<{ rename: boolean }>({
type: 'confirm',
name: 'rename',
message: `The current name '${currentName}' was already taken. Do you want to rename it?`,
initial: true,
})
return rename
}
export const promptNewName = async (scopeFieldPlugins: FieldType[]) => {
const { name } = await betterPrompts<{ name: string }>({
type: 'text',
name: 'name',
message: 'Enter the new name of the field plugin:',
validate: (name: string) => {
if (!isValidPackageName(name)) {
return false
}
return scopeFieldPlugins.every((plugin) => plugin.name !== name)
},
})
return name
}
export const confirmOptionsUpdate = async (
options: ManifestOption[] | undefined,
) => {
if (options === undefined) {
return
}
const message =
options.length === 0
? 'The plugin options will be reset because your manifest file contains an empty array for options. Do you want to proceed?'
: `The options found in your manifest file are going to replace the plugin options. Do you want to proceed?`
const { confirmed } = await betterPrompts<{
confirmed: boolean
}>({
type: 'confirm',
name: 'confirmed',
message: message,
initial: true,
})
if (!confirmed) {
console.log(cyan(bold('[info]')), 'Aborting plugin update.')
process.exit(1)
}
}
export const printManifestOptions = (options: ManifestOption[] | undefined) => {
if (options?.length === 0) {
return
}
const concatenatedOptions =
options !== undefined
? options?.map((option) => option.name).join(', ')
: ''
console.log(cyan(bold('[info] Options found:')), green(concatenatedOptions))
console.log(
yellow(
bold(
`[info] Please note that the option values will not be shared when this field plugin is added to a story. Only keys are configured for security reasons.\n` +
`[info] Learn more: https://www.storyblok.com/docs/plugins/field-plugins/storyblok-field-plugin#manifest-file-for-field-plugins`,
),
),
)
}
export const selectApiScope = async (
token: string,
): Promise<Scope | undefined> => {
const accessibleToMyPlugins = await StoryblokClient({
token,
scope: 'my-plugins',
}).isAuthenticated()
const accessibleToPartnerPortal = await StoryblokClient({
token,
scope: 'partner-portal',
}).isAuthenticated()
const accessibleToOrganizationPortal = await StoryblokClient({
token,
scope: 'organization',
}).isAuthenticated()
if (
!accessibleToMyPlugins &&
!accessibleToPartnerPortal &&
!accessibleToOrganizationPortal
) {
return undefined
}
const { scope } = await betterPrompts<{ scope: Scope }>([
{
type: 'select',
name: 'scope',
message: 'Where to deploy the plugin?',
choices: [
accessibleToMyPlugins && {
title: 'My Plugins',
value: 'my-plugins',
},
accessibleToPartnerPortal && {
title: 'Partner Portal',
value: 'partner-portal',
},
accessibleToOrganizationPortal && {
title: 'Organization',
value: 'organization',
},
].filter(Boolean) as Choice[],
},
])
return scope
}
export const getDeployBaseUrl = (scope: Scope): string => {
if (scope === 'organization') {
return 'https://app.storyblok.com/#/me/org/fields'
}
if (scope === 'partner-portal') {
return 'https://app.storyblok.com/#/partner/fields'
}
return 'https://app.storyblok.com/#/me/plugins'
}
export const createDefaultOutputPath = (dir: string) =>
resolve(dir, 'dist', 'index.js')
export const isOutputValid = (output?: string): output is string =>
typeof output === 'string' && output !== ''
export const loadManifest = (): Manifest | undefined => {
try {
console.log(bold(cyan('[info] Looking for a manifest file...')))
return load()
} catch (err) {
console.log(bold(red('[ERROR]')), `Error while loading the manifest file`)
console.log(`path: ${MANIFEST_FILE_NAME}`)
console.log(`error: ${getErrorMessage(err)}`)
return undefined
}
}
export const createFieldPlugin = async (
client: StoryClientType,
packageName: string,
content: string,
options: ManifestOption[] | undefined,
dir: string,
scopeFieldPlugins: FieldType[],
skipPrompts?: boolean,
): Promise<FieldType> => {
const name =
packageName !== '' ? packageName : await promptNewName(scopeFieldPlugins)
try {
const fieldPlugin = await client.createFieldType({
name,
body: content,
})
//since `options` and `publish` properties are only accepted during updates,
//we need to force an update call right after the creation.
//If no options is found, it's not going to be sent to the API since undefined
//properties are not encoded.
await client.updateFieldType({
id: fieldPlugin.id,
publish: true,
field_type: {
options,
},
})
if (!packageName && (await confirmUpdatingNameInPackageJson())) {
await runCommand(`npm pkg set name=${name}`, { cwd: dir })
}
return fieldPlugin
} catch (err) {
if (skipPrompts || getErrorMessage(err) !== 'DUPLICATED_NAME') {
// eslint-disable-next-line functional/no-throw-statement
throw err
}
const isRenamingConfirmed = await confirmNewName(name)
if (!isRenamingConfirmed) {
console.log(cyan(bold('[info]')), 'Aborting the deployment')
process.exit(1)
}
return await createFieldPlugin(
client,
'',
content,
options,
dir,
scopeFieldPlugins,
skipPrompts,
)
}
}