@sanity/personalization-plugin 2.3.0-launch-darkly.1 → 2.3.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.
package/dist/index.d.ts CHANGED
@@ -1,5 +1,4 @@
1
1
  import {ArrayOfObjectsInputProps} from 'sanity'
2
- import {Dispatch} from 'react'
3
2
  import {FieldDefinition} from 'sanity'
4
3
  import {ObjectField} from 'sanity'
5
4
  import {Path} from 'sanity'
@@ -7,7 +6,6 @@ import {Plugin as Plugin_2} from 'sanity'
7
6
  import {PreviewProps} from 'sanity'
8
7
  import {SanityClient} from 'sanity'
9
8
  import {SchemaType} from 'sanity'
10
- import {SetStateAction} from 'react'
11
9
 
12
10
  export declare type ArrayInputProps = ArrayOfObjectsInputProps & {
13
11
  variantName: string
@@ -17,8 +15,6 @@ export declare type ArrayInputProps = ArrayOfObjectsInputProps & {
17
15
 
18
16
  export declare type ExperimentContextProps = Required<FieldPluginConfig> & {
19
17
  experiments: ExperimentType[]
20
- setSecret: Dispatch<SetStateAction<string | undefined>>
21
- secret: string | undefined
22
18
  }
23
19
 
24
20
  export declare type ExperimentGeneric<T> = {
@@ -60,194 +56,192 @@ export declare type FieldPluginConfig = {
60
56
  */
61
57
  export declare function flattenSchemaType(schemaType: SchemaType): ObjectFieldWithPath[]
62
58
 
63
- export declare const launchDarklyFieldLevel: Plugin_2<LaunchDarklyFieldLevelConfig>
64
-
65
- export declare type LaunchDarklyFieldLevelConfig = {
66
- fields: (string | FieldDefinition)[]
67
- projectKey: string
68
- tags?: string[]
69
- }
70
-
71
- export declare type LaunchDarklyFlagItem = {
59
+ export declare type GrowthbookExperiment = {
60
+ id: string
61
+ dateCreated: string
62
+ dateUpdated: string
72
63
  name: string
73
- kind: string
74
- key: string
75
- _version: number
76
- creationDate: number
77
- variations: Array<{
78
- value: boolean
79
- _id: string
80
- name: string
81
- }>
82
- temporary: boolean
83
- tags: string[]
84
- _links: {
85
- parent: {
86
- href: string
87
- type: string
88
- }
89
- self: {
90
- href: string
91
- type: string
92
- }
93
- }
94
- experiments: {
95
- baselineIdx: number
96
- items: Array<{
97
- metricKey: string
98
- _metric: {
99
- _id: string
100
- _versionId: string
101
- key: string
102
- name: string
103
- kind: string
104
- _links: {
105
- parent: {
106
- href: string
107
- type: string
108
- }
109
- self: {
110
- href: string
111
- type: string
112
- }
64
+ project: string
65
+ hypothesis: string
66
+ description: string
67
+ tags: [string]
68
+ owner: string
69
+ archived: boolean
70
+ status: string
71
+ autoRefresh: boolean
72
+ hashAttribute: string
73
+ fallbackAttribute: string
74
+ hashVersion: number
75
+ disableStickyBucketing: boolean
76
+ bucketVersion: number
77
+ minBucketVersion: number
78
+ variations: [
79
+ {
80
+ variationId: string
81
+ key: string
82
+ name: string
83
+ description: string
84
+ screenshots: [string]
85
+ },
86
+ ]
87
+ phases: [
88
+ {
89
+ name: string
90
+ dateStarted: string
91
+ dateEnded: string
92
+ reasonForStopping: string
93
+ seed: string
94
+ coverage: 0
95
+ trafficSplit: [
96
+ {
97
+ variationId: string
98
+ weight: 0
99
+ },
100
+ ]
101
+ namespace: {
102
+ namespaceId: string
103
+ range: []
104
+ }
105
+ targetingCondition: string
106
+ savedGroupTargeting: [
107
+ {
108
+ matchType: string
109
+ savedGroups: [string]
110
+ },
111
+ ]
112
+ },
113
+ ]
114
+ settings: {
115
+ datasourceId: string
116
+ assignmentQueryId: string
117
+ experimentId: string
118
+ segmentId: string
119
+ queryFilter: string
120
+ inProgressConversions: string
121
+ attributionModel: string
122
+ statsEngine: string
123
+ regressionAdjustmentEnabled: boolean
124
+ goals: [
125
+ {
126
+ metricId: string
127
+ overrides: {
128
+ delayHours: 0
129
+ windowHours: 0
130
+ window: string
131
+ winRiskThreshold: 0
132
+ loseRiskThreshold: 0
113
133
  }
114
- tags: string[]
115
- _creationDate: number
116
- experimentCount: number
117
- metricGroupCount: number
118
- _attachedFlagCount: number
119
- maintainerId: string
120
- _maintainer: {
121
- _links: {
122
- self: {
123
- href: string
124
- type: string
125
- }
126
- }
127
- _id: string
128
- role: string
129
- email: string
130
- firstName: string
131
- lastName: string
134
+ },
135
+ ]
136
+ secondaryMetrics: [
137
+ {
138
+ metricId: string
139
+ overrides: {
140
+ delayHours: 0
141
+ windowHours: 0
142
+ window: string
143
+ winRiskThreshold: 0
144
+ loseRiskThreshold: 0
132
145
  }
133
- category: string
134
- isNumeric: boolean
135
- percentileValue: number
146
+ },
147
+ ]
148
+ guardrails: [
149
+ {
150
+ metricId: string
151
+ overrides: {
152
+ delayHours: 0
153
+ windowHours: 0
154
+ window: string
155
+ winRiskThreshold: 0
156
+ loseRiskThreshold: 0
157
+ }
158
+ },
159
+ ]
160
+ activationMetric: {
161
+ metricId: string
162
+ overrides: {
163
+ delayHours: 0
164
+ windowHours: 0
165
+ window: string
166
+ winRiskThreshold: 0
167
+ loseRiskThreshold: 0
136
168
  }
137
- }>
138
- }
139
- customProperties: {
140
- key: {
141
- name: string
142
- value: string[]
143
169
  }
144
170
  }
171
+ resultSummary: {
172
+ status: string
173
+ winner: string
174
+ conclusions: string
175
+ releasedVariationId: string
176
+ excludeFromPayload: boolean
177
+ }
178
+ }
179
+
180
+ export declare type GrowthbookFeature = {
181
+ id: string
182
+ dateCreated: string
183
+ dateUpdated: string
145
184
  archived: boolean
146
185
  description: string
147
- maintainerId: string
148
- _maintainer: {
149
- _links: {
150
- self: {
151
- href: string
152
- type: string
153
- }
154
- }
155
- _id: string
156
- role: string
157
- email: string
158
- firstName: string
159
- lastName: string
160
- }
161
- maintainerTeamKey: string
162
- _maintainerTeam: {
163
- key: string
164
- name: string
165
- _links: {
166
- parent: {
167
- href: string
168
- type: string
169
- }
170
- roles: {
171
- href: string
172
- type: string
173
- }
174
- self: {
175
- href: string
176
- type: string
177
- }
178
- }
179
- }
180
- archivedDate: number
181
- deprecated: boolean
182
- deprecatedDate: number
183
- defaults: {
184
- onVariation: number
185
- offVariation: number
186
- }
187
- _purpose: string
188
- migrationSettings: {
189
- contextKind: string
190
- stageCount: number
191
- }
186
+ owner: string
187
+ project: string
188
+ valueType: string
189
+ defaultValue: string
190
+ tags: string[]
192
191
  environments: {
193
192
  [key: string]: {
194
- on: boolean
195
- archived: boolean
196
- salt: string
197
- sel: string
198
- lastModified: number
199
- version: number
200
- _site: {
201
- href: string
193
+ enabled: boolean
194
+ defaultValue: string
195
+ rules: {
196
+ description: string
197
+ condition: string
198
+ savedGroupTargeting: {
199
+ matchType: string
200
+ savedGroups: string[]
201
+ }[]
202
+ id: string
203
+ enabled: boolean
202
204
  type: string
203
- }
204
- _environmentName: string
205
- trackEvents: boolean
206
- trackEventsFallthrough: boolean
207
- targets: Array<{
208
- values: string[]
209
- variation: number
210
- contextKind: string
211
- }>
212
- contextTargets: Array<{
213
- values: string[]
214
- variation: number
215
- contextKind: string
216
- }>
217
- rules: Array<{
218
- clauses: Array<{
219
- attribute: string
220
- op: string
221
- values: unknown[]
222
- negate: boolean
223
- }>
224
- trackEvents: boolean
225
- }>
226
- fallthrough: {
227
- variation: number
228
- }
229
- offVariation: number
230
- prerequisites: Array<{
231
- key: string
232
- variation: number
233
- }>
234
- _summary: {
205
+ value: string
235
206
  variations: {
236
- [key: string]: {
237
- rules: number
238
- nullRules: number
239
- targets: number
240
- contextTargets: number
241
- isFallthrough?: boolean
242
- isOff?: boolean
243
- }
244
- }
245
- prerequisites: number
207
+ value: string
208
+ variationId: string
209
+ }[]
210
+ }[]
211
+ definition: string
212
+ draft: {
213
+ enabled: boolean
214
+ defaultValue: string
215
+ rules: {
216
+ description: string
217
+ condition: string
218
+ savedGroupTargeting: {
219
+ matchType: string
220
+ savedGroups: string[]
221
+ }[]
222
+ id: string
223
+ enabled: boolean
224
+ type: string
225
+ value: string
226
+ variations: {
227
+ value: string
228
+ variationId: string
229
+ }[]
230
+ }[]
231
+ definition: string
246
232
  }
247
233
  }
248
234
  }
249
- includeInSnippet: boolean
250
- goalIds: string[]
235
+ prerequisites: {
236
+ parentId: string
237
+ parentCondition: string
238
+ }[]
239
+ revision: {
240
+ version: number
241
+ comment: string
242
+ date: string
243
+ publishedBy: string
244
+ }
251
245
  }
252
246
 
253
247
  export declare type ObjectFieldWithPath = ObjectField<SchemaType> & {
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: !0 });
3
- var jsxRuntime = require("react/jsx-runtime"), sanity = require("sanity"), ui = require("@sanity/ui"), uuid = require("@sanity/uuid"), react = require("react"), equal = require("fast-deep-equal"), suspendReact = require("suspend-react"), gi = require("react-icons/gi"), studioSecrets = require("@sanity/studio-secrets");
3
+ var jsxRuntime = require("react/jsx-runtime"), sanity = require("sanity"), ui = require("@sanity/ui"), uuid = require("@sanity/uuid"), react = require("react"), equal = require("fast-deep-equal"), suspendReact = require("suspend-react"), gi = require("react-icons/gi");
4
4
  function _interopDefaultCompat(e) {
5
5
  return e && typeof e == "object" && "default" in e ? e : { default: e };
6
6
  }
@@ -15,23 +15,20 @@ const CONFIG_DEFAULT = {
15
15
  experimentId: "experimentId"
16
16
  }, ExperimentContext = react.createContext({
17
17
  ...CONFIG_DEFAULT,
18
- experiments: [],
19
- setSecret: () => {
20
- },
21
- secret: void 0
18
+ experiments: []
22
19
  });
23
20
  function useExperimentContext() {
24
21
  return react.useContext(ExperimentContext);
25
22
  }
26
23
  function ExperimentProvider(props) {
27
- const { experimentFieldPluginConfig } = props, [secret, setSecret] = react.useState(), client = sanity.useClient({ apiVersion: experimentFieldPluginConfig.apiVersion }), workspace = sanity.useWorkspace(), experiments = Array.isArray(experimentFieldPluginConfig.experiments) ? experimentFieldPluginConfig.experiments : suspendReact.suspend(
24
+ const { experimentFieldPluginConfig } = props, client = sanity.useClient({ apiVersion: experimentFieldPluginConfig.apiVersion }), workspace = sanity.useWorkspace(), experiments = Array.isArray(experimentFieldPluginConfig.experiments) ? experimentFieldPluginConfig.experiments : suspendReact.suspend(
28
25
  // eslint-disable-next-line require-await
29
26
  async () => typeof experimentFieldPluginConfig.experiments == "function" ? experimentFieldPluginConfig.experiments(client) : experimentFieldPluginConfig.experiments,
30
- [workspace, secret],
27
+ [workspace],
31
28
  { equal: equal__default.default }
32
29
  ), context = react.useMemo(
33
- () => ({ ...experimentFieldPluginConfig, experiments, secret, setSecret }),
34
- [experimentFieldPluginConfig, experiments, secret, setSecret]
30
+ () => ({ ...experimentFieldPluginConfig, experiments }),
31
+ [experimentFieldPluginConfig, experiments]
35
32
  );
36
33
  return /* @__PURE__ */ jsxRuntime.jsx(ExperimentContext.Provider, { value: context, children: props.renderDefault(props) });
37
34
  }
@@ -6408,9 +6405,9 @@ const icons = {
6408
6405
  });
6409
6406
  Icon.displayName = "ForwardRef(Icon)";
6410
6407
  const useAddExperimentAction = (props) => {
6411
- const { onChange, experimentNameOverride } = props, handleAddAction = () => {
6412
- onChange([sanity.set(!0, ["active"])]);
6413
- };
6408
+ const { onChange, active, experimentNameOverride } = props, handleAddAction = react.useCallback(() => {
6409
+ onChange([sanity.set(!active, ["active"])]);
6410
+ }, [onChange, active]);
6414
6411
  return {
6415
6412
  title: `Add ${experimentNameOverride}`,
6416
6413
  type: "action",
@@ -6419,13 +6416,10 @@ const useAddExperimentAction = (props) => {
6419
6416
  renderAsButton: !0
6420
6417
  };
6421
6418
  }, useRemoveExperimentAction = (props) => {
6422
- const { onChange, experimentId, experimentNameOverride } = props, patchActiveFalseEvent = () => sanity.set(!1, ["active"]), patchClearEvent = () => {
6423
- const experiment = [experimentId], variants = [experimentNameOverride];
6424
- return [sanity.unset(experiment), sanity.unset(variants)];
6425
- }, handleClearAction = () => {
6426
- const clearEvents = patchClearEvent(), activeEvent = patchActiveFalseEvent();
6427
- onChange([activeEvent, ...clearEvents]);
6428
- };
6419
+ const { onChange, active, experimentId, experimentNameOverride, variantNameOverride } = props, handleClearAction = react.useCallback(() => {
6420
+ const activeId = ["active"], experiment = [experimentId], variants = [`${variantNameOverride}s`];
6421
+ onChange([sanity.set(!active, activeId), sanity.unset(experiment), sanity.unset(variants)]);
6422
+ }, [onChange, active, experimentId, variantNameOverride]);
6429
6423
  return {
6430
6424
  title: `Remove ${experimentNameOverride}`,
6431
6425
  type: "action",
@@ -6433,36 +6427,53 @@ const useAddExperimentAction = (props) => {
6433
6427
  onAction: handleClearAction,
6434
6428
  renderAsButton: !0
6435
6429
  };
6436
- }, newActions = ({
6430
+ }, createActions = ({
6437
6431
  onChange,
6438
6432
  inputId,
6439
6433
  active,
6440
6434
  experimentNameOverride,
6441
- experimentId
6435
+ experimentId,
6436
+ variantNameOverride
6442
6437
  }) => {
6443
6438
  const removeAction = sanity.defineDocumentFieldAction({
6444
6439
  name: `Remove ${experimentNameOverride}`,
6445
6440
  useAction: (props) => useRemoveExperimentAction({
6441
+ active: !0,
6446
6442
  onChange,
6447
6443
  experimentNameOverride,
6448
- experimentId
6444
+ experimentId,
6445
+ variantNameOverride
6449
6446
  })
6450
6447
  }), addAction = sanity.defineDocumentFieldAction({
6451
6448
  name: `Add ${experimentNameOverride}`,
6452
6449
  useAction: (props) => useAddExperimentAction({
6450
+ active: !1,
6453
6451
  onChange,
6454
6452
  experimentNameOverride
6455
6453
  })
6456
6454
  });
6457
6455
  return active ? removeAction : addAction;
6458
6456
  }, ExperimentField = (props) => {
6459
- const { onChange } = props.inputProps, { inputId, experimentNameOverride, experimentId } = props, active = props.value?.active, oldActions = props.actions || [], withActionProps = {
6460
- ...props,
6461
- actions: [
6462
- newActions({ onChange, inputId, active, experimentNameOverride, experimentId }),
6463
- ...oldActions
6464
- ]
6465
- };
6457
+ const { onChange } = props.inputProps, { inputId, experimentNameOverride, experimentId, variantNameOverride } = props, active = props.value?.active, actionProps = react.useMemo(
6458
+ () => ({
6459
+ onChange,
6460
+ inputId,
6461
+ active,
6462
+ experimentNameOverride,
6463
+ experimentId,
6464
+ variantNameOverride
6465
+ }),
6466
+ [onChange, inputId, active, experimentNameOverride, experimentId, variantNameOverride]
6467
+ ), memoizedActions = react.useMemo(() => {
6468
+ const oldActions = props.actions || [];
6469
+ return [createActions(actionProps), ...oldActions];
6470
+ }, [actionProps, props.actions]), withActionProps = react.useMemo(
6471
+ () => ({
6472
+ ...props,
6473
+ actions: memoizedActions
6474
+ }),
6475
+ [props, memoizedActions]
6476
+ );
6466
6477
  return props.renderDefault(withActionProps);
6467
6478
  }, Select = (props) => {
6468
6479
  const {
@@ -6493,20 +6504,20 @@ const useAddExperimentAction = (props) => {
6493
6504
  title: experiment.label,
6494
6505
  value: experiment.id
6495
6506
  })), ExperimentInput = (props) => {
6496
- const { experiments } = useExperimentContext(), id = sanity.useFormValue(["_id"]), aditionalChangePath = react.useMemo(
6497
- () => [...props.path.slice(0, -1), props.variantNameOverride],
6507
+ const { experiments } = useExperimentContext(), id = sanity.useFormValue(["_id"]), additionalChangePath = react.useMemo(
6508
+ () => [...props.path.slice(0, -1), `${props.variantNameOverride}s`],
6498
6509
  [props.variantNameOverride, props.path]
6499
- ), subValues = sanity.useFormValue(aditionalChangePath), { patch } = sanity.useDocumentOperation(id.replace("drafts.", ""), props.schemaType.name), handleChange = react.useCallback(
6510
+ ), subValues = sanity.useFormValue(additionalChangePath), { patch } = sanity.useDocumentOperation(sanity.getPublishedId(id), props.schemaType.name), handleChange = react.useCallback(
6500
6511
  (event, onChange) => {
6501
6512
  const inputValue = event.currentTarget.value;
6502
6513
  if (onChange(inputValue ? sanity.set(inputValue) : sanity.unset()), subValues) {
6503
6514
  const patchEvent = {
6504
- unset: [aditionalChangePath.join(".")]
6515
+ unset: [additionalChangePath.join(".")]
6505
6516
  };
6506
6517
  patch.execute([patchEvent]);
6507
6518
  }
6508
6519
  },
6509
- [patch, subValues, aditionalChangePath]
6520
+ [patch, subValues, additionalChangePath]
6510
6521
  );
6511
6522
  return experiments.length ? /* @__PURE__ */ jsxRuntime.jsx(Select, { ...props, listOptions: formatlistOptions(experiments), handleChange }) : /* @__PURE__ */ jsxRuntime.jsx(ui.Card, { padding: [3, 3, 4], radius: 2, shadow: 1, tone: "caution", children: /* @__PURE__ */ jsxRuntime.jsxs(ui.Text, { align: "center", size: [2, 2, 3], children: [
6512
6523
  "There are no defined ",
@@ -6586,7 +6597,8 @@ const createExperimentType = ({
6586
6597
  {
6587
6598
  ...props,
6588
6599
  experimentId,
6589
- experimentNameOverride
6600
+ experimentNameOverride,
6601
+ variantNameOverride
6590
6602
  }
6591
6603
  )
6592
6604
  },
@@ -6756,79 +6768,7 @@ const createExperimentType = ({
6756
6768
  }
6757
6769
  }
6758
6770
  };
6759
- }), pluginConfigKeys = [
6760
- {
6761
- key: "apiKey",
6762
- title: "Your secret API key"
6763
- }
6764
- ], Secrets = (props, namespace) => {
6765
- const { secrets, loading } = studioSecrets.useSecrets(namespace), { setSecret } = useExperimentContext(), [showSettings, setShowSettings] = react.useState(!1);
6766
- return react.useEffect(() => {
6767
- if (!loading)
6768
- return !secrets && !loading ? (setSecret(void 0), setShowSettings(!0)) : (setSecret(secrets.apiKey), setShowSettings(!1));
6769
- }, [secrets, loading, setSecret]), showSettings ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
6770
- /* @__PURE__ */ jsxRuntime.jsx(
6771
- studioSecrets.SettingsView,
6772
- {
6773
- title: `${namespace} api key`,
6774
- namespace,
6775
- keys: pluginConfigKeys,
6776
- onClose: () => {
6777
- setShowSettings(!1);
6778
- }
6779
- }
6780
- ),
6781
- props.renderDefault(props)
6782
- ] }) : props.renderDefault(props);
6783
- }, getExperiments = async ({
6784
- client,
6785
- projectKey,
6786
- tags
6787
- }) => {
6788
- const secret = await client.fetch("*[_id == 'secrets.launchdarkly'][0].secrets.apiKey");
6789
- if (!secret) return [];
6790
- const url = new URL(`https://app.launchdarkly.com/api/v2/flags/${projectKey}`);
6791
- tags && url.searchParams.set("filter", `tags:${tags.join("+")}`);
6792
- const featureExperiments = [];
6793
- let hasMore = !0;
6794
- const offset = 0, limit = 10;
6795
- for (; hasMore; ) {
6796
- url.searchParams.set("offset", offset.toString()), url.searchParams.set("limit", limit.toString());
6797
- const responseFlags = await fetch(url, {
6798
- headers: {
6799
- Authorization: secret
6800
- }
6801
- }), { items } = await responseFlags.json(), experiments = items.map((flag) => ({
6802
- id: flag.key,
6803
- label: flag.name,
6804
- variants: flag.variations.map((variation) => ({
6805
- id: variation.value,
6806
- label: variation.name ?? variation.value
6807
- }))
6808
- }));
6809
- featureExperiments.push(...experiments), items.length !== limit && (hasMore = !1);
6810
- }
6811
- return featureExperiments;
6812
- }, launchDarklyFieldLevel = sanity.definePlugin((config) => {
6813
- const { fields, projectKey, tags } = config;
6814
- return {
6815
- name: "sanity-growthbook-personalistaion-plugin-field-level-experiments",
6816
- plugins: [
6817
- fieldLevelExperiments({
6818
- fields,
6819
- experiments: (client) => getExperiments({ client, projectKey, tags })
6820
- })
6821
- ],
6822
- form: {
6823
- components: {
6824
- input: (props) => !(props.id === "root" && sanity.isObjectInputProps(props)) || !flattenSchemaType(props.schemaType).map(
6825
- (field) => field.type.name
6826
- ).some((name) => name.startsWith("experiment")) ? props.renderDefault(props) : Secrets(props, "launchdarkly")
6827
- }
6828
- }
6829
- };
6830
6771
  });
6831
6772
  exports.fieldLevelExperiments = fieldLevelExperiments;
6832
6773
  exports.flattenSchemaType = flattenSchemaType;
6833
- exports.launchDarklyFieldLevel = launchDarklyFieldLevel;
6834
6774
  //# sourceMappingURL=index.js.map