Skip to content

Commit 5deacfd

Browse files
committed
feat(sandbox): validating manifest, specifically option object and showing steps to correct
1 parent b39001d commit 5deacfd

File tree

1 file changed

+51
-5
lines changed

1 file changed

+51
-5
lines changed

packages/field-plugin/helpers/vite/src/sandbox.ts

Lines changed: 51 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
import * as querystring from 'querystring'
2-
import { bold } from './utils/text'
2+
import { bold, red } from './utils/text'
33
import { arrows } from './utils/arrows'
44
import { load, manifestExists, MANIFEST_FILE_NAME } from './manifest'
55
import type { Manifest } from './manifest'
6+
import { isFieldPluginOption } from '@storyblok/field-plugin'
67

78
export const SANDBOX_BASE_URL = `https://plugin-sandbox.storyblok.com/field-plugin`
89

@@ -11,16 +12,61 @@ export type SandboxQueryParams = {
1112
manifest: Manifest | null
1213
}
1314

15+
const areOptionsValid = (options: unknown): boolean => {
16+
if (!Array.isArray(options) || options.length === 0) {
17+
displayManifestErrorLoading(
18+
new Error('ERROR: Manifest options must be an array of objects'),
19+
)
20+
return false
21+
}
22+
23+
const incorrectValues: string[] = []
24+
25+
for (const option of options) {
26+
if (!isFieldPluginOption(option)) {
27+
incorrectValues.push(JSON.stringify(option))
28+
}
29+
}
30+
31+
if (incorrectValues.length > 0) {
32+
displayManifestErrorLoading(
33+
new Error(
34+
'ERROR: Each option must be an object with string properties "name" and "value". The following values need to be corrected: \n ' +
35+
incorrectValues.join(',\n '),
36+
),
37+
)
38+
return false
39+
}
40+
41+
return true
42+
}
43+
44+
const isManifestValid = (manifest: unknown): boolean => {
45+
if (typeof manifest !== 'object' || manifest === null) {
46+
return false
47+
}
48+
49+
if ('options' in manifest && manifest.options !== null) {
50+
return areOptionsValid(manifest.options)
51+
}
52+
53+
return true
54+
}
55+
1456
export const buildQueryString = (params: SandboxQueryParams) => {
1557
const queryParams: querystring.ParsedUrlQueryInput = {
1658
url: params.url,
1759
}
1860

19-
if (params.manifest !== null) {
20-
queryParams.manifest = JSON.stringify(params.manifest)
61+
if (params.manifest === null) {
62+
return querystring.stringify(queryParams)
63+
}
64+
65+
if (!isManifestValid(params.manifest)) {
66+
throw Error('Invalid manifest')
2167
}
2268

23-
return querystring.stringify(queryParams)
69+
queryParams.manifest = JSON.stringify(params.manifest)
2470
}
2571

2672
export const generateSandboxUrl = (fieldPluginUrl: string) => {
@@ -58,4 +104,4 @@ const displayManifestChecking = () => {
58104
}
59105

60106
const displayManifestErrorLoading = (err: Error) =>
61-
console.log(`${arrows.red} ${bold(`${err.message}`)}`)
107+
console.log(`${arrows.red} ${red(`${err.message}`)}`)

0 commit comments

Comments
 (0)