@sanity/personalization-plugin 2.1.0 → 2.2.0-launch-darkly.1

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sanity/personalization-plugin",
3
- "version": "2.1.0",
3
+ "version": "2.2.0-launch-darkly.1",
4
4
  "description": "Plugin to help with personalization, a/b testing when using Sanity",
5
5
  "keywords": [
6
6
  "sanity",
@@ -45,6 +45,7 @@
45
45
  },
46
46
  "dependencies": {
47
47
  "@sanity/incompatible-plugin": "^1.0.4",
48
+ "@sanity/studio-secrets": "^3.0.1",
48
49
  "@sanity/ui": "^2.8.19",
49
50
  "@sanity/uuid": "^3.0.2",
50
51
  "fast-deep-equal": "^3.1.3",
@@ -1,5 +1,5 @@
1
1
  import equal from 'fast-deep-equal'
2
- import {createContext, useContext, useMemo} from 'react'
2
+ import {createContext, useContext, useMemo, useState} from 'react'
3
3
  import {type ObjectInputProps, useClient, useWorkspace} from 'sanity'
4
4
  import {suspend} from 'suspend-react'
5
5
 
@@ -21,6 +21,8 @@ export const CONFIG_DEFAULT = {
21
21
  export const ExperimentContext = createContext<ExperimentContextProps>({
22
22
  ...CONFIG_DEFAULT,
23
23
  experiments: [],
24
+ setSecret: () => undefined,
25
+ secret: undefined,
24
26
  })
25
27
 
26
28
  export function useExperimentContext() {
@@ -33,6 +35,7 @@ type ExperimentProps = ObjectInputProps & {
33
35
 
34
36
  export function ExperimentProvider(props: ExperimentProps) {
35
37
  const {experimentFieldPluginConfig} = props
38
+ const [secret, setSecret] = useState<string | undefined>()
36
39
 
37
40
  const client = useClient({apiVersion: experimentFieldPluginConfig.apiVersion})
38
41
  const workspace = useWorkspace()
@@ -48,13 +51,13 @@ export function ExperimentProvider(props: ExperimentProps) {
48
51
  }
49
52
  return experimentFieldPluginConfig.experiments
50
53
  },
51
- [workspace],
54
+ [workspace, secret],
52
55
  {equal},
53
56
  )
54
57
 
55
58
  const context = useMemo(
56
- () => ({...experimentFieldPluginConfig, experiments}),
57
- [experimentFieldPluginConfig, experiments],
59
+ () => ({...experimentFieldPluginConfig, experiments, secret, setSecret}),
60
+ [experimentFieldPluginConfig, experiments, secret, setSecret],
58
61
  )
59
62
 
60
63
  return (
@@ -0,0 +1,45 @@
1
+ import {SettingsView, useSecrets} from '@sanity/studio-secrets'
2
+ import {useEffect, useState} from 'react'
3
+ import {ObjectInputProps} from 'sanity'
4
+
5
+ import {useExperimentContext} from './ExperimentContext'
6
+
7
+ const pluginConfigKeys = [
8
+ {
9
+ key: 'apiKey',
10
+ title: 'Your secret API key',
11
+ },
12
+ ]
13
+
14
+ export const Secrets = (props: ObjectInputProps, namespace: string) => {
15
+ const {secrets, loading} = useSecrets(namespace) as {secrets: {apiKey: string}; loading: boolean}
16
+ const {setSecret} = useExperimentContext()
17
+ const [showSettings, setShowSettings] = useState<boolean>(false)
18
+
19
+ useEffect(() => {
20
+ if (loading) return undefined
21
+ if (!secrets && !loading) {
22
+ setSecret(undefined)
23
+ return setShowSettings(true)
24
+ }
25
+ setSecret(secrets.apiKey)
26
+ return setShowSettings(false)
27
+ }, [secrets, loading, setSecret])
28
+
29
+ if (!showSettings) {
30
+ return props.renderDefault(props)
31
+ }
32
+ return (
33
+ <>
34
+ <SettingsView
35
+ title={`${namespace} api key`}
36
+ namespace={namespace}
37
+ keys={pluginConfigKeys}
38
+ onClose={() => {
39
+ setShowSettings(false)
40
+ }}
41
+ />
42
+ {props.renderDefault(props)}
43
+ </>
44
+ )
45
+ }
package/src/index.ts CHANGED
@@ -1,3 +1,4 @@
1
1
  export * from './fieldExperiments'
2
+ export * from './launchDarklyExperiments'
2
3
  export * from './types'
3
4
  export * from './utils/flattenSchemaType'
@@ -0,0 +1,48 @@
1
+ import {definePlugin, FieldDefinition, isObjectInputProps} from 'sanity'
2
+
3
+ import {Secrets} from './components/Secrets'
4
+ import {fieldLevelExperiments} from './fieldExperiments'
5
+ import {flattenSchemaType} from './utils/flattenSchemaType'
6
+ import {getExperiments} from './utils/launchDarkly'
7
+
8
+ export type LaunchDarklyFieldLevelConfig = {
9
+ fields: (string | FieldDefinition)[]
10
+ projectKey: string
11
+ tags?: string[]
12
+ }
13
+
14
+ export const launchDarklyFieldLevel = definePlugin<LaunchDarklyFieldLevelConfig>((config) => {
15
+ const {fields, projectKey, tags} = config
16
+ return {
17
+ name: 'sanity-growthbook-personalistaion-plugin-field-level-experiments',
18
+ plugins: [
19
+ fieldLevelExperiments({
20
+ fields,
21
+ experiments: (client) => getExperiments({client, projectKey, tags}),
22
+ }),
23
+ ],
24
+
25
+ form: {
26
+ components: {
27
+ input: (props) => {
28
+ const isRootInput = props.id === 'root' && isObjectInputProps(props)
29
+
30
+ if (!isRootInput) {
31
+ return props.renderDefault(props)
32
+ }
33
+
34
+ const flatFieldTypeNames = flattenSchemaType(props.schemaType).map(
35
+ (field) => field.type.name,
36
+ )
37
+
38
+ const hasExperiment = flatFieldTypeNames.some((name) => name.startsWith('experiment'))
39
+
40
+ if (!hasExperiment) {
41
+ return props.renderDefault(props)
42
+ }
43
+ return Secrets(props, 'launchdarkly')
44
+ },
45
+ },
46
+ },
47
+ }
48
+ })
package/src/types.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import {Dispatch, SetStateAction} from 'react'
1
2
  import {
2
3
  ArrayOfObjectsInputProps,
3
4
  FieldDefinition,
@@ -37,6 +38,8 @@ export type VariantPreviewProps = Omit<PreviewProps, 'SchemaType'> & {
37
38
 
38
39
  export type ExperimentContextProps = Required<FieldPluginConfig> & {
39
40
  experiments: ExperimentType[]
41
+ setSecret: Dispatch<SetStateAction<string | undefined>>
42
+ secret: string | undefined
40
43
  }
41
44
 
42
45
  export type ArrayInputProps = ArrayOfObjectsInputProps & {
@@ -67,3 +70,185 @@ export type ExperimentGeneric<T> = {
67
70
  | T
68
71
  | undefined
69
72
  }
73
+
74
+ export type LaunchDarklyFlagItem = {
75
+ name: string
76
+ kind: string
77
+ key: string
78
+ _version: number
79
+ creationDate: number
80
+ variations: Array<{
81
+ value: boolean
82
+ _id: string
83
+ name: string
84
+ }>
85
+ temporary: boolean
86
+ tags: string[]
87
+ _links: {
88
+ parent: {
89
+ href: string
90
+ type: string
91
+ }
92
+ self: {
93
+ href: string
94
+ type: string
95
+ }
96
+ }
97
+ experiments: {
98
+ baselineIdx: number
99
+ items: Array<{
100
+ metricKey: string
101
+ _metric: {
102
+ _id: string
103
+ _versionId: string
104
+ key: string
105
+ name: string
106
+ kind: string
107
+ _links: {
108
+ parent: {
109
+ href: string
110
+ type: string
111
+ }
112
+ self: {
113
+ href: string
114
+ type: string
115
+ }
116
+ }
117
+ tags: string[]
118
+ _creationDate: number
119
+ experimentCount: number
120
+ metricGroupCount: number
121
+ _attachedFlagCount: number
122
+ maintainerId: string
123
+ _maintainer: {
124
+ _links: {
125
+ self: {
126
+ href: string
127
+ type: string
128
+ }
129
+ }
130
+ _id: string
131
+ role: string
132
+ email: string
133
+ firstName: string
134
+ lastName: string
135
+ }
136
+ category: string
137
+ isNumeric: boolean
138
+ percentileValue: number
139
+ }
140
+ }>
141
+ }
142
+ customProperties: {
143
+ key: {
144
+ name: string
145
+ value: string[]
146
+ }
147
+ }
148
+ archived: boolean
149
+ description: string
150
+ maintainerId: string
151
+ _maintainer: {
152
+ _links: {
153
+ self: {
154
+ href: string
155
+ type: string
156
+ }
157
+ }
158
+ _id: string
159
+ role: string
160
+ email: string
161
+ firstName: string
162
+ lastName: string
163
+ }
164
+ maintainerTeamKey: string
165
+ _maintainerTeam: {
166
+ key: string
167
+ name: string
168
+ _links: {
169
+ parent: {
170
+ href: string
171
+ type: string
172
+ }
173
+ roles: {
174
+ href: string
175
+ type: string
176
+ }
177
+ self: {
178
+ href: string
179
+ type: string
180
+ }
181
+ }
182
+ }
183
+ archivedDate: number
184
+ deprecated: boolean
185
+ deprecatedDate: number
186
+ defaults: {
187
+ onVariation: number
188
+ offVariation: number
189
+ }
190
+ _purpose: string
191
+ migrationSettings: {
192
+ contextKind: string
193
+ stageCount: number
194
+ }
195
+ environments: {
196
+ [key: string]: {
197
+ on: boolean
198
+ archived: boolean
199
+ salt: string
200
+ sel: string
201
+ lastModified: number
202
+ version: number
203
+ _site: {
204
+ href: string
205
+ type: string
206
+ }
207
+ _environmentName: string
208
+ trackEvents: boolean
209
+ trackEventsFallthrough: boolean
210
+ targets: Array<{
211
+ values: string[]
212
+ variation: number
213
+ contextKind: string
214
+ }>
215
+ contextTargets: Array<{
216
+ values: string[]
217
+ variation: number
218
+ contextKind: string
219
+ }>
220
+ rules: Array<{
221
+ clauses: Array<{
222
+ attribute: string
223
+ op: string
224
+ values: unknown[]
225
+ negate: boolean
226
+ }>
227
+ trackEvents: boolean
228
+ }>
229
+ fallthrough: {
230
+ variation: number
231
+ }
232
+ offVariation: number
233
+ prerequisites: Array<{
234
+ key: string
235
+ variation: number
236
+ }>
237
+ _summary: {
238
+ variations: {
239
+ [key: string]: {
240
+ rules: number
241
+ nullRules: number
242
+ targets: number
243
+ contextTargets: number
244
+ isFallthrough?: boolean
245
+ isOff?: boolean
246
+ }
247
+ }
248
+ prerequisites: number
249
+ }
250
+ }
251
+ }
252
+ includeInSnippet: boolean
253
+ goalIds: string[]
254
+ }
@@ -0,0 +1,54 @@
1
+ import {SanityClient} from 'sanity'
2
+
3
+ import {LaunchDarklyFieldLevelConfig} from '../launchDarklyExperiments'
4
+ import {ExperimentType, LaunchDarklyFlagItem} from '../types'
5
+
6
+ export const getExperiments = async ({
7
+ client,
8
+ projectKey,
9
+ tags,
10
+ }: Omit<LaunchDarklyFieldLevelConfig, 'fields'> & {client: SanityClient}): Promise<
11
+ ExperimentType[]
12
+ > => {
13
+ const query = `*[_id == 'secrets.launchdarkly'][0].secrets.apiKey`
14
+
15
+ const secret = await client.fetch(query) // secret is stored in the content lake using @sanity/studio-secrets
16
+ if (!secret) return []
17
+
18
+ const url = new URL(`https://app.launchdarkly.com/api/v2/flags/${projectKey}`)
19
+
20
+ if (tags) {
21
+ url.searchParams.set('filter', `tags:${tags.join('+')}`)
22
+ }
23
+
24
+ const featureExperiments: ExperimentType[] = []
25
+ let hasMore = true
26
+ const offset = 0
27
+ const limit = 10
28
+
29
+ while (hasMore) {
30
+ url.searchParams.set('offset', offset.toString())
31
+ url.searchParams.set('limit', limit.toString())
32
+ const responseFlags = await fetch(url, {
33
+ headers: {
34
+ Authorization: secret,
35
+ },
36
+ })
37
+
38
+ const {items} = await responseFlags.json()
39
+ const experiments = items.map((flag: LaunchDarklyFlagItem) => ({
40
+ id: flag.key,
41
+ label: flag.name,
42
+ variants: flag.variations.map((variation) => ({
43
+ id: variation.value,
44
+ label: variation.name,
45
+ })),
46
+ }))
47
+ featureExperiments.push(...experiments)
48
+ if (items.length !== limit) {
49
+ hasMore = false
50
+ }
51
+ }
52
+
53
+ return featureExperiments
54
+ }