@sanity/assist 3.0.8 → 3.1.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.esm.js CHANGED
@@ -2,7 +2,7 @@ import { jsx, jsxs, Fragment } from "react/jsx-runtime";
2
2
  import { SyncIcon, PlayIcon, SparklesIcon, DocumentIcon, LinkIcon, ImageIcon, BlockContentIcon, OlistIcon, BlockquoteIcon, StringIcon, SearchIcon, ErrorOutlineIcon, CheckmarkCircleIcon, CloseCircleIcon, ClockIcon, RetryIcon, ArrowRightIcon, CloseIcon, CheckmarkIcon, ArrowLeftIcon, icons, TokenIcon, DocumentTextIcon, ThListIcon, CodeIcon, ComposeIcon, LockIcon, TranslateIcon, ControlsIcon } from "@sanity/icons";
3
3
  import { Card, Stack, Box, Button, Spinner, Flex, Label, focusFirstDescendant, Text, useToast, Dialog, Tooltip, TextArea, Container, Autocomplete, Breadcrumbs, useClickOutside, Popover, useLayer, useGlobalKeyDown, Badge, useTheme, rgba, Checkbox, Radio, ThemeProvider, ErrorBoundary, MenuButton, Menu, MenuItem, Switch } from "@sanity/ui";
4
4
  import { useState, useRef, useEffect, useMemo, useCallback, createContext, useContext, useId, createElement, useReducer, forwardRef } from "react";
5
- import { useClient, isArraySchemaType, typed, useSchema, isKeySegment, isDocumentSchemaType, pathToString, useDocumentStore, useDocumentPresence, createPatchChannel, FormBuilder, fromMutationPatches, useEditState, useCurrentUser, FormFieldHeaderText, PatchEvent, unset, isObjectSchemaType, stringToPath, StatusButton, PresenceOverlay, VirtualizerScrollInstanceProvider, useColorSchemeValue, useFormCallbacks, set, FormCallbacksProvider, FormInput, setIfMissing, insert, ObjectInputMember, isArrayOfObjectsSchemaType, defineType, defineField, defineArrayMember, getPublishedId, useSyncState, definePlugin } from "sanity";
5
+ import { useClient, isArraySchemaType, typed, useSchema, isKeySegment, isDocumentSchemaType, pathToString, useDocumentStore, useDocumentPresence, createPatchChannel, FormBuilder, fromMutationPatches, isVersionId, getVersionFromId, getPublishedId, useEditState, useCurrentUser, FormFieldHeaderText, PatchEvent, unset, isObjectSchemaType, stringToPath, StatusButton, PresenceOverlay, VirtualizerScrollInstanceProvider, useColorSchemeValue, useFormCallbacks, set, FormCallbacksProvider, FormInput, setIfMissing, insert, ObjectInputMember, isArrayOfObjectsSchemaType, defineType, defineField, defineArrayMember, useSyncState, getVersionId, getDraftId, definePlugin } from "sanity";
6
6
  import isEqual from "react-fast-compare";
7
7
  import { mergeMap, share, take, filter, distinctUntilChanged, catchError, tap } from "rxjs/operators";
8
8
  import { throwError, of, partition, merge, switchMap, delay, defer } from "rxjs";
@@ -71,16 +71,13 @@ function isImage(schemaType) {
71
71
  return isType(schemaType, "image");
72
72
  }
73
73
  function getDescriptionFieldOption(schemaType) {
74
- var _a, _b;
75
- return schemaType ? ((_b = (_a = schemaType.options) == null ? void 0 : _a.aiAssist) == null ? void 0 : _b.imageDescriptionField) || getDescriptionFieldOption(schemaType.type) : void 0;
74
+ return schemaType ? schemaType.options?.aiAssist?.imageDescriptionField || getDescriptionFieldOption(schemaType.type) : void 0;
76
75
  }
77
76
  function getImageInstructionFieldOption(schemaType) {
78
- var _a, _b;
79
- return schemaType ? ((_b = (_a = schemaType.options) == null ? void 0 : _a.aiAssist) == null ? void 0 : _b.imageInstructionField) || getImageInstructionFieldOption(schemaType.type) : void 0;
77
+ return schemaType ? schemaType.options?.aiAssist?.imageInstructionField || getImageInstructionFieldOption(schemaType.type) : void 0;
80
78
  }
81
79
  function isSchemaAssistEnabled(type) {
82
- var _a, _b;
83
- return !((_b = (_a = type.options) == null ? void 0 : _a.aiAssist) != null && _b.exclude);
80
+ return !type.options?.aiAssist?.exclude;
84
81
  }
85
82
  function isAssistSupported(type) {
86
83
  return !isSchemaAssistEnabled(type) || isDisabled(type) ? !1 : type.jsonType === "array" ? !type.of.every((t) => isDisabled(t)) : type.jsonType === "object" ? !type.fields.every((field) => isDisabled(field.type)) : !0;
@@ -89,8 +86,7 @@ function isDisabled(type) {
89
86
  return !isSchemaAssistEnabled(type) || isUnsupportedType(type);
90
87
  }
91
88
  function isUnsupportedType(type) {
92
- var _a, _b;
93
- return type.jsonType === "number" || type.name === "sanity.imageCrop" || type.name === "sanity.imageHotspot" || isType(type, "reference") && !((_b = (_a = type == null ? void 0 : type.options) == null ? void 0 : _a.aiAssist) != null && _b.embeddingsIndex) || isType(type, "crossDatasetReference") || isType(type, "slug") || isType(type, "url") || isType(type, "date") || isType(type, "datetime") || isType(type, "file");
89
+ return type.jsonType === "number" || type.name === "sanity.imageCrop" || type.name === "sanity.imageHotspot" || isType(type, "reference") && !type?.options?.aiAssist?.embeddingsIndex || isType(type, "crossDatasetReference") || isType(type, "slug") || isType(type, "url") || isType(type, "date") || isType(type, "datetime") || isType(type, "file");
94
90
  }
95
91
  const hiddenTypes = [
96
92
  "any",
@@ -128,18 +124,14 @@ const hiddenTypes = [
128
124
  ], inlineTypes = ["document", "object", "image", "file"];
129
125
  function serializeSchema(schema, options2) {
130
126
  const list = schema.getTypeNames().filter((t) => !(hiddenTypes.includes(t) || t.startsWith("sanity."))).map((t) => schema.get(t)).filter((t) => !!t).map((t) => getSchemaStub(t, schema, options2)).filter((t) => !("to" in t && t.to && !t.to.length || "of" in t && t.of && !t.of.length || "fields" in t && t.fields && !t.fields.length));
131
- return list.sort((a, b) => {
132
- var _a, _b;
133
- return ((_a = a == null ? void 0 : a.name) != null ? _a : "").localeCompare((_b = b == null ? void 0 : b.name) != null ? _b : "");
134
- }), list;
127
+ return list.sort((a, b) => (a?.name ?? "").localeCompare(b?.name ?? "")), list;
135
128
  }
136
129
  function getSchemaStub(schemaType, schema, options2) {
137
- var _a;
138
- if (!((_a = schemaType.type) != null && _a.name))
130
+ if (!schemaType.type?.name)
139
131
  throw console.error("Missing type name", schemaType.type), new Error("Type is missing name!");
140
132
  const baseSchema = {
141
133
  // we dont need type or id when we send using POST, so leave these out to save bandwidth
142
- ...options2 != null && options2.leanFormat ? {} : { _id: `${assistSchemaIdPrefix}${schemaType.name}`, _type: assistSerializedTypeName },
134
+ ...options2?.leanFormat ? {} : { _id: `${assistSchemaIdPrefix}${schemaType.name}`, _type: assistSerializedTypeName },
143
135
  name: schemaType.name,
144
136
  title: schemaType.title,
145
137
  type: schemaType.type.name,
@@ -148,18 +140,14 @@ function getSchemaStub(schemaType, schema, options2) {
148
140
  return removeUndef(baseSchema);
149
141
  }
150
142
  function getBaseFields(schema, type, typeName, options2) {
151
- var _a, _b, _c, _d, _e, _f;
152
143
  const schemaOptions = removeUndef({
153
- imagePromptField: (_b = (_a = type.options) == null ? void 0 : _a.aiAssist) == null ? void 0 : _b.imageInstructionField,
154
- embeddingsIndex: (_d = (_c = type.options) == null ? void 0 : _c.aiAssist) == null ? void 0 : _d.embeddingsIndex
144
+ imagePromptField: type.options?.aiAssist?.imageInstructionField,
145
+ embeddingsIndex: type.options?.aiAssist?.embeddingsIndex
155
146
  });
156
147
  return removeUndef({
157
148
  options: Object.keys(schemaOptions).length ? schemaOptions : void 0,
158
- values: Array.isArray((_e = type == null ? void 0 : type.options) == null ? void 0 : _e.list) ? (_f = type == null ? void 0 : type.options) == null ? void 0 : _f.list.map(
159
- (v) => {
160
- var _a2;
161
- return typeof v == "string" ? v : (_a2 = v.value) != null ? _a2 : `${v.title}`;
162
- }
149
+ values: Array.isArray(type?.options?.list) ? type?.options?.list.map(
150
+ (v) => typeof v == "string" ? v : v.value ?? `${v.title}`
163
151
  ) : void 0,
164
152
  of: "of" in type && typeName === "array" ? arrayOf(type, schema, options2) : void 0,
165
153
  to: "to" in type && typeName === "reference" ? refToTypeNames(type) : void 0,
@@ -182,16 +170,12 @@ function serializeFields(schema, schemaType, options2) {
182
170
  hidden: typeof fs.hidden == "function" ? fs.hidden : fs.hidden ? !0 : f.type.hidden
183
171
  }
184
172
  }))
185
- ) : schemaType.fields).filter((f) => {
186
- var _a, _b;
187
- return !["sanity.imageHotspot", "sanity.imageCrop"].includes((_b = (_a = f.type) == null ? void 0 : _a.name) != null ? _b : "");
188
- }).filter((f) => isAssistSupported(f.type)).map((field) => serializeMember(schema, field.type, field.name, options2));
173
+ ) : schemaType.fields).filter((f) => !["sanity.imageHotspot", "sanity.imageCrop"].includes(f.type?.name ?? "")).filter((f) => isAssistSupported(f.type)).map((field) => serializeMember(schema, field.type, field.name, options2));
189
174
  }
190
175
  function serializeMember(schema, type, name, options2) {
191
- var _a, _b;
192
- const typeName = schema.get(type == null ? void 0 : type.name) ? type.name : (_b = (_a = type.type) == null ? void 0 : _a.name) != null ? _b : "";
176
+ const typeName = schema.get(type?.name) ? type.name : type.type?.name ?? "";
193
177
  return removeUndef({
194
- ...options2 != null && options2.leanFormat ? {} : { _type: assistSerializedFieldTypeName },
178
+ ...options2?.leanFormat ? {} : { _type: assistSerializedFieldTypeName },
195
179
  name,
196
180
  type: typeName,
197
181
  title: type.title,
@@ -199,7 +183,7 @@ function serializeMember(schema, type, name, options2) {
199
183
  });
200
184
  }
201
185
  function serializeInlineOf(blockSchemaType, schema, options2) {
202
- const childrenField = blockSchemaType.fields.find((f) => f.name === "children"), childrenType = childrenField == null ? void 0 : childrenField.type;
186
+ const childrenType = blockSchemaType.fields.find((f) => f.name === "children")?.type;
203
187
  if (!(!childrenType || !isArraySchemaType(childrenType)))
204
188
  return arrayOf(
205
189
  {
@@ -211,7 +195,7 @@ function serializeInlineOf(blockSchemaType, schema, options2) {
211
195
  );
212
196
  }
213
197
  function serializeAnnotations(blockSchemaType, schema, options2) {
214
- const markDefs = blockSchemaType.fields.find((f) => f.name === "markDefs"), marksType = markDefs == null ? void 0 : markDefs.type;
198
+ const marksType = blockSchemaType.fields.find((f) => f.name === "markDefs")?.type;
215
199
  if (!(!marksType || !isArraySchemaType(marksType)))
216
200
  return arrayOf(marksType, schema, options2);
217
201
  }
@@ -265,7 +249,7 @@ function SchemaTypeTool() {
265
249
  ] }),
266
250
  /* @__PURE__ */ jsxs(Stack, { space: 2, children: [
267
251
  /* @__PURE__ */ jsx(Label, { children: "Stored schema" }),
268
- /* @__PURE__ */ jsx("ul", { children: (data != null ? data : NO_DATA).map((type) => /* @__PURE__ */ jsx("li", { children: /* @__PURE__ */ jsx(SchemaEntry, { schemaStub: type }) }, type.name)) })
252
+ /* @__PURE__ */ jsx("ul", { children: (data ?? NO_DATA).map((type) => /* @__PURE__ */ jsx("li", { children: /* @__PURE__ */ jsx(SchemaEntry, { schemaStub: type }) }, type.name)) })
269
253
  ] })
270
254
  ] })
271
255
  ] }) });
@@ -280,8 +264,7 @@ function getDocumentMembersFlat(doc, schemaType) {
280
264
  }
281
265
  function extractPaths(doc, schemaType, path, maxDepth2) {
282
266
  return path.length >= maxDepth2 ? [] : schemaType.fields.reduce((acc, field) => {
283
- var _a, _b;
284
- const fieldPath = [...path, field.name], fieldSchema = field.type, { value } = (_a = extractWithPath(pathToString(fieldPath), doc)[0]) != null ? _a : {};
267
+ const fieldPath = [...path, field.name], fieldSchema = field.type, { value } = extractWithPath(pathToString(fieldPath), doc)[0] ?? {};
285
268
  if (!value)
286
269
  return acc;
287
270
  const thisFieldWithPath = {
@@ -294,9 +277,9 @@ function extractPaths(doc, schemaType, path, maxDepth2) {
294
277
  const innerFields = extractPaths(doc, fieldSchema, fieldPath, maxDepth2);
295
278
  return [...acc, thisFieldWithPath, ...innerFields];
296
279
  } else if (fieldSchema.jsonType === "array" && fieldSchema.of.length && fieldSchema.of.some((item) => "fields" in item)) {
297
- const { value: arrayValue } = (_b = extractWithPath(pathToString(fieldPath), doc)[0]) != null ? _b : {};
280
+ const { value: arrayValue } = extractWithPath(pathToString(fieldPath), doc)[0] ?? {};
298
281
  let arrayPaths = [];
299
- if (arrayValue != null && arrayValue.length)
282
+ if (arrayValue?.length)
300
283
  for (const item of arrayValue) {
301
284
  const itemPath = [...fieldPath, { _key: item._key }];
302
285
  let itemSchema = fieldSchema.of.find((t) => t.name === item._type);
@@ -342,15 +325,14 @@ const defaultLanguageOutputs = function(member, enclosingType, translateFromLang
342
325
  })) : void 0;
343
326
  };
344
327
  function getFieldLanguageMap(documentSchema, documentMembers, translateFromLanguageId, outputLanguageIds, langFn) {
345
- var _a, _b, _c;
346
328
  const translationMaps = [];
347
329
  for (const member of documentMembers) {
348
- const parentPath = member.path.slice(0, -1), enclosingType = (_b = (_a = documentMembers.find((m) => pathToString(m.path) === pathToString(parentPath))) == null ? void 0 : _a.schemaType) != null ? _b : documentSchema, translations = (_c = langFn(
330
+ const parentPath = member.path.slice(0, -1), enclosingType = documentMembers.find((m) => pathToString(m.path) === pathToString(parentPath))?.schemaType ?? documentSchema, translations = langFn(
349
331
  member,
350
332
  enclosingType,
351
333
  translateFromLanguageId,
352
334
  outputLanguageIds
353
- )) == null ? void 0 : _c.filter((translation) => translation.id !== translateFromLanguageId);
335
+ )?.filter((translation) => translation.id !== translateFromLanguageId);
354
336
  translations && translationMaps.push({
355
337
  inputLanguageId: translateFromLanguageId,
356
338
  inputPath: member.path,
@@ -361,7 +343,6 @@ function getFieldLanguageMap(documentSchema, documentMembers, translateFromLangu
361
343
  }
362
344
  const releaseAnnouncementUrl = "https://www.sanity.io/blog/sanity-ai-assist-announcement?utm_source=sanity-assist-plugin&utm_medium=organic_social&utm_campaign=ai-assist&utm_content=", instructionGuideUrl = "https://sanity.io/guides/getting-started-with-ai-assist-instructions?utm_source=sanity-assist-plugin&utm_medium=organic_social&utm_campaign=ai-assist&utm_content=", giveFeedbackUrl = "https://forms.gle/Kwz7CThxGeA2GiEU8", salesUrl = "https://www.sanity.io/contact/sales?utm_source=sanity-assist-plugin&utm_medium=organic_social&utm_campaign=ai-assist&utm_content=", packageName = "@sanity/assist", pluginTitle = "Sanity AI Assist", pluginTitleShort = "AI Assist", maxHistoryVisibilityMs = minutesToMilliseconds(30), assistFormId = "assist", preventDefault = (ev) => ev.preventDefault();
363
345
  function DocumentForm(props) {
364
- var _a;
365
346
  const {
366
347
  collapsedFieldSets,
367
348
  collapsedPaths,
@@ -379,7 +360,7 @@ function DocumentForm(props) {
379
360
  onSetCollapsedPath,
380
361
  ready,
381
362
  validation
382
- } = useDocumentPane(), documentStore = useDocumentStore(), presence = useDocumentPresence(documentId), patchChannel = useMemo(() => createPatchChannel(), []), isLocked = (_a = editState == null ? void 0 : editState.transactionSyncLock) == null ? void 0 : _a.enabled;
363
+ } = useDocumentPane(), documentStore = useDocumentStore(), presence = useDocumentPresence(documentId), patchChannel = useMemo(() => createPatchChannel(), []), isLocked = editState?.transactionSyncLock?.enabled;
383
364
  useEffect(() => {
384
365
  const sub = documentStore.pair.documentEvents(documentId, documentType).pipe(
385
366
  tap((event) => {
@@ -390,7 +371,7 @@ function DocumentForm(props) {
390
371
  sub.unsubscribe();
391
372
  };
392
373
  }, [documentId, documentStore, documentType, patchChannel]);
393
- const hasRev = !!(value != null && value._rev);
374
+ const hasRev = !!value?._rev;
394
375
  useEffect(() => {
395
376
  hasRev && patchChannel.publish({
396
377
  type: "mutation",
@@ -483,14 +464,11 @@ function prepareRebaseEvent(event) {
483
464
  };
484
465
  }
485
466
  const AssistTypeContext = createContext({}), illegalIdChars = /[^a-zA-Z0-9._-]/g;
486
- function publicId(id) {
487
- return id.replace("drafts.", "");
488
- }
489
467
  function assistDocumentId(documentType) {
490
468
  return `${assistDocumentIdPrefix}${documentType}`.replace(illegalIdChars, "_");
491
469
  }
492
470
  function assistTasksStatusId(documentId) {
493
- return `${assistDocumentStatusIdPrefix}${publicId(documentId)}`;
471
+ return isVersionId(documentId) ? `${assistDocumentStatusIdPrefix}${getVersionFromId(documentId)}.${getPublishedId(documentId)}` : `${assistDocumentStatusIdPrefix}${getPublishedId(documentId)}`;
494
472
  }
495
473
  function useDocumentState(id, docType) {
496
474
  const state = useEditState(id, docType);
@@ -505,7 +483,7 @@ function useStudioAssistDocument({
505
483
  assistDocumentId(documentTypeName),
506
484
  assistDocumentTypeName
507
485
  ), assistTasksStatus = useDocumentState(
508
- assistTasksStatusId(documentId != null ? documentId : ""),
486
+ assistTasksStatusId(documentId ?? ""),
509
487
  assistTasksStatusTypeName
510
488
  ), client = useClient({ apiVersion: "2023-01-01" });
511
489
  return useEffect(() => {
@@ -515,22 +493,17 @@ function useStudioAssistDocument({
515
493
  }).catch(() => {
516
494
  });
517
495
  }, [client, assistDocument, documentTypeName, initDoc]), useMemo(() => {
518
- var _a, _b;
519
496
  if (!assistDocument)
520
497
  return;
521
- const tasks = (_a = assistTasksStatus == null ? void 0 : assistTasksStatus.tasks) != null ? _a : [], fields = ((_b = assistDocument == null ? void 0 : assistDocument.fields) != null ? _b : []).map((assistField) => {
522
- var _a2;
523
- return {
524
- ...assistField,
525
- tasks: tasks.filter((task) => task.path === assistField.path),
526
- instructions: (_a2 = assistField.instructions) == null ? void 0 : _a2.filter((p) => !p.userId || p.userId === (currentUser == null ? void 0 : currentUser.id)).map((instruction2) => asStudioInstruction(instruction2, tasks))
527
- };
528
- });
498
+ const tasks = assistTasksStatus?.tasks ?? [], fields = (assistDocument?.fields ?? []).map((assistField) => ({
499
+ ...assistField,
500
+ tasks: tasks.filter((task) => task.path === assistField.path),
501
+ instructions: assistField.instructions?.filter((p) => !p.userId || p.userId === currentUser?.id).map((instruction2) => asStudioInstruction(instruction2, tasks))
502
+ }));
529
503
  return typed({
530
504
  ...assistDocument,
531
- tasks: tasks == null ? void 0 : tasks.map((task) => {
532
- var _a2, _b2;
533
- const instruction2 = (_b2 = (_a2 = fields.find((f) => f.path === task.path)) == null ? void 0 : _a2.instructions) == null ? void 0 : _b2.find((i) => i._key === task.instructionKey);
505
+ tasks: tasks?.map((task) => {
506
+ const instruction2 = fields.find((f) => f.path === task.path)?.instructions?.find((i) => i._key === task.instructionKey);
534
507
  return {
535
508
  ...task,
536
509
  instruction: instruction2
@@ -555,12 +528,11 @@ function getPathKey(path) {
555
528
  return path.length ? Array.isArray(path) ? pathToString(path) : path : documentRootKey;
556
529
  }
557
530
  function getInstructionTitle(instruction2) {
558
- var _a;
559
- return (_a = instruction2 == null ? void 0 : instruction2.title) != null ? _a : "Untitled";
531
+ return instruction2?.title ?? "Untitled";
560
532
  }
561
533
  const basePath = "/assist/tasks/instruction";
562
534
  function canUseAssist(status) {
563
- return (status == null ? void 0 : status.enabled) && status.initialized && status.validToken;
535
+ return status?.enabled && status.initialized && status.validToken;
564
536
  }
565
537
  function useApiClient(customApiClient) {
566
538
  const client = useClient({ apiVersion: "2023-06-05" });
@@ -587,7 +559,7 @@ function useTranslate(apiClient) {
587
559
  fieldLanguageMap,
588
560
  conditionalMembers,
589
561
  translatePath: translatePath.length === 0 ? documentRootKey : pathToString(translatePath),
590
- userId: user == null ? void 0 : user.id
562
+ userId: user?.id
591
563
  }
592
564
  }).catch((e) => {
593
565
  throw toast.push({
@@ -619,7 +591,7 @@ function useGenerateCaption(apiClient) {
619
591
  path,
620
592
  documentId,
621
593
  types,
622
- userId: user == null ? void 0 : user.id
594
+ userId: user?.id
623
595
  }
624
596
  }).catch((e) => {
625
597
  throw toast.push({
@@ -651,7 +623,7 @@ function useGenerateImage(apiClient) {
651
623
  path,
652
624
  documentId,
653
625
  types,
654
- userId: user == null ? void 0 : user.id
626
+ userId: user?.id
655
627
  }
656
628
  }).catch((e) => {
657
629
  throw toast.push({
@@ -712,7 +684,7 @@ function useRunInstructionApi(apiClient) {
712
684
  body: {
713
685
  ...request,
714
686
  types,
715
- userId: user == null ? void 0 : user.id
687
+ userId: user?.id
716
688
  }
717
689
  }).catch((e) => {
718
690
  throw toast.push({
@@ -741,8 +713,7 @@ function useAiAssistanceConfig() {
741
713
  return context;
742
714
  }
743
715
  function AiAssistanceConfigProvider(props) {
744
- var _a;
745
- const [status, setStatus] = useState(), [error, setError] = useState(), apiClient = useApiClient((_a = props.config) == null ? void 0 : _a.__customApiClient), { getInstructStatus, loading: statusLoading } = useGetInstructStatus(apiClient), { initInstruct, loading: initLoading } = useInitInstruct(apiClient);
716
+ const [status, setStatus] = useState(), [error, setError] = useState(), apiClient = useApiClient(props.config?.__customApiClient), { getInstructStatus, loading: statusLoading } = useGetInstructStatus(apiClient), { initInstruct, loading: initLoading } = useInitInstruct(apiClient);
746
717
  useEffect(() => {
747
718
  getInstructStatus().then((s) => setStatus(s)).catch((e) => {
748
719
  console.error(e), setError(e);
@@ -779,16 +750,14 @@ function isUserInputBlock(block) {
779
750
  return block._type === userInputTypeName;
780
751
  }
781
752
  function RunInstructionProvider(props) {
782
- var _a;
783
- const { config } = useAiAssistanceConfig(), apiClient = useApiClient(config == null ? void 0 : config.__customApiClient), { runInstruction: runInstructionRequest, loading } = useRunInstructionApi(apiClient), id = useId(), [inputs, setInputs] = useState(NO_INPUT), [runRequest, setRunRequest] = useState(), runInstruction = useCallback(
753
+ const { config } = useAiAssistanceConfig(), apiClient = useApiClient(config?.__customApiClient), { runInstruction: runInstructionRequest, loading } = useRunInstructionApi(apiClient), id = useId(), [inputs, setInputs] = useState(NO_INPUT), [runRequest, setRunRequest] = useState(), runInstruction = useCallback(
784
754
  (req) => {
785
- var _a2;
786
755
  if (loading)
787
756
  return;
788
- const { instruction: instruction2, ...request } = req, instructionKey = instruction2._key, userInputBlocks = (_a2 = instruction2 == null ? void 0 : instruction2.prompt) == null ? void 0 : _a2.flatMap(
757
+ const { instruction: instruction2, ...request } = req, instructionKey = instruction2._key, userInputBlocks = instruction2?.prompt?.flatMap(
789
758
  (block) => block._type === "block" ? block.children.filter(isUserInputBlock) : [block]
790
759
  ).filter(isUserInputBlock);
791
- if (!(userInputBlocks != null && userInputBlocks.length)) {
760
+ if (!userInputBlocks?.length) {
792
761
  runInstructionRequest({
793
762
  ...request,
794
763
  instructionKey,
@@ -818,11 +787,8 @@ function RunInstructionProvider(props) {
818
787
  }
819
788
  close();
820
789
  }, [close, runInstructionRequest, runRequest, inputs]), open = !!runRequest, runDisabled = useMemo(
821
- () => {
822
- var _a2, _b;
823
- return ((_b = (_a2 = runRequest == null ? void 0 : runRequest.userInputBlocks) == null ? void 0 : _a2.length) != null ? _b : 0) > Object.entries(inputs).filter(([, value]) => !!value).length;
824
- },
825
- [runRequest == null ? void 0 : runRequest.userInputBlocks, inputs]
790
+ () => (runRequest?.userInputBlocks?.length ?? 0) > Object.entries(inputs).filter(([, value]) => !!value).length,
791
+ [runRequest?.userInputBlocks, inputs]
826
792
  ), runButton = /* @__PURE__ */ jsx(
827
793
  Button,
828
794
  {
@@ -845,7 +811,7 @@ function RunInstructionProvider(props) {
845
811
  open,
846
812
  onClose: close,
847
813
  width: 1,
848
- header: getInstructionTitle(runRequest == null ? void 0 : runRequest.instruction),
814
+ header: getInstructionTitle(runRequest?.instruction),
849
815
  footer: /* @__PURE__ */ jsx(Flex, { justify: "space-between", padding: 2, flex: 1, children: runDisabled ? /* @__PURE__ */ jsx(
850
816
  Tooltip,
851
817
  {
@@ -854,7 +820,7 @@ function RunInstructionProvider(props) {
854
820
  children: /* @__PURE__ */ jsx(Flex, { flex: 1, children: runButton })
855
821
  }
856
822
  ) : runButton }),
857
- children: /* @__PURE__ */ jsx(Stack, { padding: 4, space: 2, children: (_a = runRequest == null ? void 0 : runRequest.userInputBlocks) == null ? void 0 : _a.map((block, i) => /* @__PURE__ */ jsx(
823
+ children: /* @__PURE__ */ jsx(Stack, { padding: 4, space: 2, children: runRequest?.userInputBlocks?.map((block, i) => /* @__PURE__ */ jsx(
858
824
  UserInput,
859
825
  {
860
826
  block,
@@ -870,29 +836,22 @@ function RunInstructionProvider(props) {
870
836
  ] });
871
837
  }
872
838
  function UserInput(props) {
873
- var _a;
874
839
  const { block, autoFocus, setInputs, inputs } = props, key = block._key, textAreaRef = useRef(null), onChange = useCallback(
875
840
  (e) => {
876
- setInputs((current) => {
877
- var _a2;
878
- return {
879
- ...current,
880
- [key]: ((_a2 = e.currentTarget) != null ? _a2 : e.target).value
881
- };
882
- });
841
+ setInputs((current) => ({
842
+ ...current,
843
+ [key]: (e.currentTarget ?? e.target).value
844
+ }));
883
845
  },
884
846
  [key, setInputs]
885
847
  ), value = useMemo(() => inputs[key], [inputs, key]);
886
848
  return useEffect(() => {
887
- autoFocus && setTimeout(() => {
888
- var _a2;
889
- return (_a2 = textAreaRef.current) == null ? void 0 : _a2.focus();
890
- }, 0);
849
+ autoFocus && setTimeout(() => textAreaRef.current?.focus(), 0);
891
850
  }, [autoFocus]), /* @__PURE__ */ jsxs(Stack, { padding: 2, space: 3, children: [
892
851
  /* @__PURE__ */ jsx(
893
852
  FormFieldHeaderText,
894
853
  {
895
- title: (_a = block == null ? void 0 : block.message) != null ? _a : "Provide more context",
854
+ title: block?.message ?? "Provide more context",
896
855
  description: block.description
897
856
  }
898
857
  ),
@@ -911,10 +870,6 @@ function UserInput(props) {
911
870
  function isDocAssistable(documentSchemaType, published, draft) {
912
871
  return !!(documentSchemaType.liveEdit ? published : draft);
913
872
  }
914
- function getAssistableDocId(documentSchemaType, documentId) {
915
- const baseId = publicId(documentId);
916
- return documentSchemaType.liveEdit ? baseId : `drafts.${baseId}`;
917
- }
918
873
  function useRequestRunInstruction(args) {
919
874
  const { runInstruction, instructionLoading } = useRunInstruction(), requestRunInstruction = useDraftDelayedTask({
920
875
  ...args,
@@ -959,7 +914,6 @@ function conditionalState(memberState) {
959
914
  }
960
915
  function extractConditionalPaths(node, maxDepth2) {
961
916
  return node.path.length >= maxDepth2 ? [] : node.members.reduce((acc, member) => {
962
- var _a, _b;
963
917
  if (member.kind === "error")
964
918
  return acc;
965
919
  if (member.kind === "field") {
@@ -984,12 +938,12 @@ function extractConditionalPaths(node, maxDepth2) {
984
938
  }
985
939
  return [...acc, conditionalState(member.field)];
986
940
  } else if (member.kind === "fieldSet") {
987
- const conditionalFieldset = !!((_b = (_a = node.schemaType) == null ? void 0 : _a.fieldsets) != null && _b.some(
941
+ const conditionalFieldset = !!node.schemaType?.fieldsets?.some(
988
942
  (f) => !f.single && f.name === member.fieldSet.name && typeof f.hidden == "function"
989
- )), innerFields = extractConditionalPaths(member.fieldSet, maxDepth2).map((f) => ({
943
+ ), innerFields = extractConditionalPaths(member.fieldSet, maxDepth2).map((f) => ({
990
944
  ...f,
991
945
  // if fieldset is conditional, visible fields must also be considered conditional
992
- conditional: conditionalFieldset != null ? conditionalFieldset : f.conditional
946
+ conditional: conditionalFieldset ?? f.conditional
993
947
  }));
994
948
  return [...acc, ...innerFields];
995
949
  }
@@ -1046,19 +1000,17 @@ const SelectedFieldContext = createContext(void 0), SelectedFieldContextProvider
1046
1000
  function getTypeIcon(schemaType) {
1047
1001
  let t = schemaType;
1048
1002
  for (; t; ) {
1049
- if (t.icon)
1050
- return t.icon;
1003
+ if (t.icon) return t.icon;
1051
1004
  t = t.type;
1052
1005
  }
1053
1006
  return isType(schemaType, "slug") ? LinkIcon : isType(schemaType, "image") ? ImageIcon : schemaType.jsonType === "array" && isPortableTextArray(schemaType) ? BlockContentIcon : schemaType.jsonType === "array" ? OlistIcon : schemaType.jsonType === "object" ? BlockquoteIcon : schemaType.jsonType === "string" ? StringIcon : DocumentIcon;
1054
1007
  }
1055
1008
  function getFieldRefsWithDocument(schemaType) {
1056
- var _a;
1057
1009
  const fields = getFieldRefs(schemaType);
1058
1010
  return [
1059
1011
  {
1060
1012
  key: documentRootKey,
1061
- icon: (_a = schemaType.icon) != null ? _a : DocumentIcon,
1013
+ icon: schemaType.icon ?? DocumentIcon,
1062
1014
  title: "The entire document",
1063
1015
  path: [],
1064
1016
  schemaType
@@ -1068,8 +1020,7 @@ function getFieldRefsWithDocument(schemaType) {
1068
1020
  }
1069
1021
  function getFieldRefs(schemaType, parent, depth = 0) {
1070
1022
  return depth >= maxDepth ? [] : schemaType.fields.filter((f) => !f.name.startsWith("_")).flatMap((field) => {
1071
- var _a;
1072
- const path = parent ? [...parent.path, field.name] : [field.name], title = (_a = field.type.title) != null ? _a : field.name, fieldRef = {
1023
+ const path = parent ? [...parent.path, field.name] : [field.name], title = field.type.title ?? field.name, fieldRef = {
1073
1024
  key: patchableKey(pathToString(path)),
1074
1025
  path,
1075
1026
  title: parent ? [parent.title, title].join(" / ") : title,
@@ -1081,11 +1032,10 @@ function getFieldRefs(schemaType, parent, depth = 0) {
1081
1032
  }
1082
1033
  function getSyntheticFields(schemaType, parent, depth = 0) {
1083
1034
  return depth >= maxDepth ? [] : schemaType.of.filter((itemType) => !isType(itemType, "block")).flatMap((itemType) => {
1084
- var _a;
1085
- const segment = { _key: itemType.name }, title = (_a = itemType.title) != null ? _a : itemType.name, path = parent ? [...parent.path, segment] : [segment], fieldRef = {
1035
+ const segment = { _key: itemType.name }, title = itemType.title ?? itemType.name, path = [...parent.path, segment], fieldRef = {
1086
1036
  key: patchableKey(pathToString(path)),
1087
1037
  path,
1088
- title: parent ? [parent.title, title].join(" / ") : title,
1038
+ title: [parent.title, title].join(" / "),
1089
1039
  schemaType: itemType,
1090
1040
  icon: getTypeIcon(itemType),
1091
1041
  synthetic: !0
@@ -1100,7 +1050,7 @@ function getTypePath(doc, pathString) {
1100
1050
  let valid = !0;
1101
1051
  const syntheticPath = path.map((segment) => {
1102
1052
  if (currentPath.push(segment), isKeySegment(segment)) {
1103
- const match = extractWithPath(pathToString(currentPath), doc)[0], value = match == null ? void 0 : match.value;
1053
+ const match = extractWithPath(pathToString(currentPath), doc)[0], value = match?.value;
1104
1054
  if (match && value && typeof value == "object" && "_type" in value)
1105
1055
  return { _key: value._type };
1106
1056
  valid = !1;
@@ -1120,20 +1070,16 @@ function useSelectedField(documentSchemaType, path) {
1120
1070
  () => documentSchemaType && isObjectSchemaType(documentSchemaType) ? getFieldRefsWithDocument(documentSchemaType) : [],
1121
1071
  [documentSchemaType]
1122
1072
  );
1123
- return useMemo(() => path ? selectableFields == null ? void 0 : selectableFields.find((f) => f.key === path) : void 0, [selectableFields, path]);
1073
+ return useMemo(() => path ? selectableFields?.find((f) => f.key === path) : void 0, [selectableFields, path]);
1124
1074
  }
1125
1075
  function getFieldTitle(field) {
1126
- var _a, _b, _c;
1127
- const schemaType = field == null ? void 0 : field.schemaType;
1128
- return (_c = (_b = (_a = field == null ? void 0 : field.title) != null ? _a : schemaType == null ? void 0 : schemaType.title) != null ? _b : schemaType == null ? void 0 : schemaType.name) != null ? _c : "Untitled";
1076
+ const schemaType = field?.schemaType;
1077
+ return field?.title ?? schemaType?.title ?? schemaType?.name ?? "Untitled";
1129
1078
  }
1130
1079
  function useAiPaneRouter() {
1131
1080
  const paneRouter = usePaneRouter();
1132
1081
  return useMemo(
1133
- () => {
1134
- var _a;
1135
- return { ...paneRouter, params: (_a = paneRouter.params) != null ? _a : {} };
1136
- },
1082
+ () => ({ ...paneRouter, params: paneRouter.params ?? {} }),
1137
1083
  [paneRouter]
1138
1084
  );
1139
1085
  }
@@ -1150,13 +1096,9 @@ function FieldAutocomplete(props) {
1150
1096
  /* @__PURE__ */ jsx(Text, { size: 1, children: createElement(field.icon) }),
1151
1097
  /* @__PURE__ */ jsx(FieldTitle, { field })
1152
1098
  ] }) }) : /* @__PURE__ */ jsx(Card, { as: "button", padding: 3, radius: 1, children: /* @__PURE__ */ jsx(Text, { accent: !0, size: 1, children: option.value }) });
1153
- }, []), renderValue = useCallback((value, option) => {
1154
- var _a;
1155
- return (_a = option == null ? void 0 : option.field.title) != null ? _a : value;
1156
- }, []), filterOption = useCallback((query, option) => {
1157
- var _a, _b, _c;
1099
+ }, []), renderValue = useCallback((value, option) => option?.field.title ?? value, []), filterOption = useCallback((query, option) => {
1158
1100
  const lQuery = query.toLowerCase();
1159
- return ((_a = option == null ? void 0 : option.value) == null ? void 0 : _a.toLowerCase().includes(lQuery)) || ((_c = (_b = option == null ? void 0 : option.field) == null ? void 0 : _b.title) == null ? void 0 : _c.toLowerCase().includes(lQuery));
1101
+ return option?.value?.toLowerCase().includes(lQuery) || option?.field?.title?.toLowerCase().includes(lQuery);
1160
1102
  }, []);
1161
1103
  return /* @__PURE__ */ jsx(
1162
1104
  Autocomplete,
@@ -1171,7 +1113,7 @@ function FieldAutocomplete(props) {
1171
1113
  radius: 2,
1172
1114
  renderOption,
1173
1115
  renderValue,
1174
- value: currentField == null ? void 0 : currentField.key,
1116
+ value: currentField?.key,
1175
1117
  filterOption
1176
1118
  }
1177
1119
  );
@@ -1258,22 +1200,17 @@ function InstructionTaskHistoryButton(props) {
1258
1200
  },
1259
1201
  [client, documentId]
1260
1202
  ), titledTasks = useMemo(() => {
1261
- var _a;
1262
- const t = (_a = tasks == null ? void 0 : tasks.filter(
1203
+ const t = tasks?.filter(
1263
1204
  (task) => task.started && (/* @__PURE__ */ new Date()).getTime() - new Date(task.started).getTime() < maxHistoryVisibilityMs
1264
1205
  ).map((task) => {
1265
- var _a2;
1266
- const instruction2 = instructions == null ? void 0 : instructions.find((i) => i._key === task.instructionKey);
1206
+ const instruction2 = instructions?.find((i) => i._key === task.instructionKey);
1267
1207
  return {
1268
1208
  ...task,
1269
- title: showTitles ? (_a2 = task.title) != null ? _a2 : getInstructionTitle(instruction2) : void 0,
1209
+ title: showTitles ? task.title ?? getInstructionTitle(instruction2) : void 0,
1270
1210
  cancel: () => cancelRun(task._key)
1271
1211
  };
1272
- })) != null ? _a : [];
1273
- return t.sort((a, b) => {
1274
- var _a2, _b;
1275
- return new Date((_a2 = b.started) != null ? _a2 : "").getTime() - new Date((_b = a.started) != null ? _b : "").getTime();
1276
- }), t;
1212
+ }) ?? [];
1213
+ return t.sort((a, b) => new Date(b.started ?? "").getTime() - new Date(a.started ?? "").getTime()), t;
1277
1214
  }, [tasks, instructions, cancelRun, showTitles]), isRunning = useMemo(() => titledTasks.some((r) => !r.ended), [titledTasks]), hasErrors = useMemo(
1278
1215
  () => titledTasks.some((r) => r.reason === "error" || r.reason === "timeout"),
1279
1216
  [titledTasks]
@@ -1282,14 +1219,14 @@ function InstructionTaskHistoryButton(props) {
1282
1219
  }, []);
1283
1220
  useClickOutside(handleClickOutside, [button, popover]);
1284
1221
  const handleEscape = useCallback(() => {
1285
- setOpen(!1), button == null || button.focus();
1222
+ setOpen(!1), button?.focus();
1286
1223
  }, [button]);
1287
1224
  return /* @__PURE__ */ jsx(
1288
1225
  Popover,
1289
1226
  {
1290
1227
  constrainSize: !0,
1291
1228
  content: /* @__PURE__ */ jsx(TaskList, { onEscape: handleEscape, tasks: titledTasks }),
1292
- open: open && !!(titledTasks != null && titledTasks.length),
1229
+ open: open && !!titledTasks?.length,
1293
1230
  placement: "top",
1294
1231
  portal: !0,
1295
1232
  ref: setPopover,
@@ -1297,7 +1234,7 @@ function InstructionTaskHistoryButton(props) {
1297
1234
  children: /* @__PURE__ */ jsx(
1298
1235
  TaskStatusButton,
1299
1236
  {
1300
- disabled: !(titledTasks != null && titledTasks.length),
1237
+ disabled: !titledTasks?.length,
1301
1238
  hasErrors,
1302
1239
  isRunning,
1303
1240
  onClick: toggleOpen,
@@ -1340,9 +1277,8 @@ function TaskList(props) {
1340
1277
  ), /* @__PURE__ */ jsx(Stack, { padding: 1, space: 1, children: tasks.map((task) => /* @__PURE__ */ jsx(TaskItem, { task }, task._key)) });
1341
1278
  }
1342
1279
  function TaskItem(props) {
1343
- var _a;
1344
1280
  const { task } = props, taskType = task.reason && TASK_CONFIG[task.reason];
1345
- return /* @__PURE__ */ jsx(Card, { radius: 2, tone: taskType && (taskType == null ? void 0 : taskType.tone), children: /* @__PURE__ */ jsxs(Flex, { align: "center", gap: 1, children: [
1281
+ return /* @__PURE__ */ jsx(Card, { radius: 2, tone: taskType && taskType?.tone, children: /* @__PURE__ */ jsxs(Flex, { align: "center", gap: 1, children: [
1346
1282
  /* @__PURE__ */ jsxs(Flex, { align: "flex-start", flex: 1, gap: 3, padding: 3, children: [
1347
1283
  /* @__PURE__ */ jsx(Box, { flex: "none", children: /* @__PURE__ */ jsxs(Text, { size: 1, children: [
1348
1284
  taskType && createElement(taskType.icon),
@@ -1357,12 +1293,21 @@ function TaskItem(props) {
1357
1293
  ] })
1358
1294
  ] }),
1359
1295
  task.message ? /* @__PURE__ */ jsx(Text, { size: 1, children: task.message }) : null,
1360
- /* @__PURE__ */ jsx(Text, { muted: !0, size: 1, children: /* @__PURE__ */ jsx(TimeAgo, { date: (_a = task.ended) != null ? _a : task.started }) })
1296
+ /* @__PURE__ */ jsx(Text, { muted: !0, size: 1, children: /* @__PURE__ */ jsx(TimeAgo, { date: task.ended ?? task.started }) })
1361
1297
  ] })
1362
1298
  ] }),
1363
1299
  !task.ended && /* @__PURE__ */ jsx(Box, { flex: "none", padding: 1, children: /* @__PURE__ */ jsx(Button, { fontSize: 1, mode: "bleed", onClick: task.cancel, text: "Cancel" }) })
1364
1300
  ] }) });
1365
1301
  }
1302
+ const AssistDocumentContext = createContext(
1303
+ void 0
1304
+ );
1305
+ function useAssistDocumentContext() {
1306
+ const context = useContext(AssistDocumentContext);
1307
+ if (!context)
1308
+ throw new Error("AssistDocumentContext value is missing");
1309
+ return context;
1310
+ }
1366
1311
  const CardWithShadowBelow = styled(Card)`
1367
1312
  position: relative;
1368
1313
 
@@ -1404,7 +1349,7 @@ function AssistInspectorWrapper(props) {
1404
1349
  ] })
1405
1350
  ] }) });
1406
1351
  const status = context.status;
1407
- return status != null && status.enabled ? !(status != null && status.initialized) || !status.validToken ? /* @__PURE__ */ jsxs(Flex, { direction: "column", height: "fill", children: [
1352
+ return status?.enabled ? !status?.initialized || !status.validToken ? /* @__PURE__ */ jsxs(Flex, { direction: "column", height: "fill", children: [
1408
1353
  /* @__PURE__ */ jsx(
1409
1354
  DocumentInspectorHeader,
1410
1355
  {
@@ -1418,16 +1363,16 @@ function AssistInspectorWrapper(props) {
1418
1363
  "Failed to start ",
1419
1364
  pluginTitle
1420
1365
  ] }) : null,
1421
- !context.error && !(status != null && status.initialized) ? /* @__PURE__ */ jsxs(Text, { size: 1, weight: "semibold", children: [
1366
+ !context.error && !status?.initialized ? /* @__PURE__ */ jsxs(Text, { size: 1, weight: "semibold", children: [
1422
1367
  pluginTitle,
1423
1368
  " is not enabled"
1424
1369
  ] }) : null,
1425
- !context.error && status != null && status.initialized && !status.validToken ? /* @__PURE__ */ jsxs(Fragment, { children: [
1370
+ !context.error && status?.initialized && !status.validToken ? /* @__PURE__ */ jsxs(Fragment, { children: [
1426
1371
  /* @__PURE__ */ jsx(Text, { size: 1, weight: "semibold", children: "Invalid token" }),
1427
1372
  /* @__PURE__ */ jsx(Text, { muted: !0, size: 1, children: "The token used by the AI Assistant is not valid and has to be regenerated." })
1428
1373
  ] }) : null,
1429
1374
  context.error && /* @__PURE__ */ jsx(Text, { muted: !0, size: 1, children: "Something went wrong. See console for details." }),
1430
- !context.error && !(status != null && status.initialized) && /* @__PURE__ */ jsxs(Text, { size: 1, muted: !0, children: [
1375
+ !context.error && !status?.initialized && /* @__PURE__ */ jsxs(Text, { size: 1, muted: !0, children: [
1431
1376
  "Please enable ",
1432
1377
  pluginTitle,
1433
1378
  "."
@@ -1437,7 +1382,7 @@ function AssistInspectorWrapper(props) {
1437
1382
  {
1438
1383
  fontSize: 1,
1439
1384
  icon: context.initLoading ? /* @__PURE__ */ jsx(Box, { marginTop: 1, children: /* @__PURE__ */ jsx(Spinner, {}) }) : context.error ? RetryIcon : void 0,
1440
- text: context.error ? "Retry" : status != null && status.initialized && !status.validToken ? `Restore ${pluginTitle}` : `Enable ${pluginTitle} now`,
1385
+ text: context.error ? "Retry" : status?.initialized && !status.validToken ? `Restore ${pluginTitle}` : `Enable ${pluginTitle} now`,
1441
1386
  tone: "primary",
1442
1387
  onClick: context.init,
1443
1388
  disabled: context.initLoading
@@ -1473,40 +1418,29 @@ function AssistInspectorWrapper(props) {
1473
1418
  ] });
1474
1419
  }
1475
1420
  function AssistInspector(props) {
1476
- var _a, _b;
1477
- const { params } = useAiPaneRouter(), boundary = useRef(null), pathKey = params == null ? void 0 : params[fieldPathParam], instructionKey = params == null ? void 0 : params[instructionParam], documentPane = useDocumentPane(), {
1421
+ const { params } = useAiPaneRouter(), boundary = useRef(null), pathKey = params?.[fieldPathParam], instructionKey = params?.[instructionParam], documentPane = useDocumentPane(), {
1478
1422
  documentId,
1479
1423
  documentType,
1480
1424
  value: docValue,
1481
1425
  schemaType,
1482
1426
  onChange: documentOnChange,
1483
1427
  formState
1484
- } = documentPane, { published, draft } = useEditState(documentId, documentType, "low"), formStateRef = useRef(formState);
1428
+ } = documentPane, { assistableDocumentId, documentIsAssistable } = useAssistDocumentContext(), formStateRef = useRef(formState);
1485
1429
  formStateRef.current = formState;
1486
- const assistableDocId = getAssistableDocId(schemaType, documentId), { instructionLoading, requestRunInstruction } = useRequestRunInstruction({
1430
+ const { instructionLoading, requestRunInstruction } = useRequestRunInstruction({
1487
1431
  documentOnChange,
1488
- isDocAssistable: isDocAssistable(schemaType, published, draft)
1489
- }), typePath = useTypePath(docValue, pathKey != null ? pathKey : ""), selectedField = useSelectedField(schemaType, typePath), aiDocId = assistDocumentId(documentType), assistDocument = useStudioAssistDocument({ documentId, schemaType, initDoc: !0 }), assistField = (_a = assistDocument == null ? void 0 : assistDocument.fields) == null ? void 0 : _a.find((f) => f.path === typePath), instruction2 = (_b = assistField == null ? void 0 : assistField.instructions) == null ? void 0 : _b.find((i) => i._key === instructionKey), tasks = useMemo(
1490
- () => {
1491
- var _a2;
1492
- return (_a2 = assistDocument == null ? void 0 : assistDocument.tasks) == null ? void 0 : _a2.filter((i) => !instructionKey || i.instructionKey === instructionKey);
1493
- },
1494
- [assistDocument == null ? void 0 : assistDocument.tasks, instructionKey]
1432
+ isDocAssistable: documentIsAssistable
1433
+ }), typePath = useTypePath(docValue, pathKey ?? ""), selectedField = useSelectedField(schemaType, typePath), aiDocId = assistDocumentId(documentType), assistDocument = useStudioAssistDocument({ documentId, schemaType, initDoc: !0 }), instruction2 = assistDocument?.fields?.find((f) => f.path === typePath)?.instructions?.find((i) => i._key === instructionKey), tasks = useMemo(
1434
+ () => assistDocument?.tasks?.filter((i) => !instructionKey || i.instructionKey === instructionKey),
1435
+ [assistDocument?.tasks, instructionKey]
1495
1436
  ), instructions = useMemo(
1496
- () => {
1497
- var _a2;
1498
- return (_a2 = assistDocument == null ? void 0 : assistDocument.fields) == null ? void 0 : _a2.flatMap((f) => {
1499
- var _a3;
1500
- return (_a3 = f.instructions) != null ? _a3 : [];
1501
- });
1502
- },
1503
- [assistDocument == null ? void 0 : assistDocument.fields]
1504
- ), promptValue = instruction2 == null ? void 0 : instruction2.prompt, isEmptyPrompt = useMemo(() => {
1505
- var _a2, _b2;
1506
- if (!(promptValue != null && promptValue.length))
1437
+ () => assistDocument?.fields?.flatMap((f) => f.instructions ?? []),
1438
+ [assistDocument?.fields]
1439
+ ), promptValue = instruction2?.prompt, isEmptyPrompt = useMemo(() => {
1440
+ if (!promptValue?.length)
1507
1441
  return !0;
1508
- const firstBlock = promptValue[0], children = firstBlock == null ? void 0 : firstBlock.children;
1509
- return promptValue.length == 1 && (children == null ? void 0 : children.length) === 1 && !((_b2 = (_a2 = children == null ? void 0 : children[0]) == null ? void 0 : _a2.text) != null && _b2.length);
1442
+ const children = promptValue[0]?.children;
1443
+ return promptValue.length == 1 && children?.length === 1 && !children?.[0]?.text?.length;
1510
1444
  }, [promptValue]), paneNode = useMemo(
1511
1445
  () => ({
1512
1446
  type: "document",
@@ -1520,14 +1454,14 @@ function AssistInspector(props) {
1520
1454
  [aiDocId]
1521
1455
  ), runCurrentInstruction = useCallback(
1522
1456
  () => instruction2 && pathKey && typePath && requestRunInstruction({
1523
- documentId: assistableDocId,
1457
+ documentId: assistableDocumentId,
1524
1458
  path: pathKey,
1525
1459
  typePath,
1526
1460
  assistDocumentId: assistDocumentId(documentType),
1527
1461
  instruction: instruction2,
1528
1462
  conditionalMembers: formStateRef.current ? getConditionalMembers(formStateRef.current) : []
1529
1463
  }),
1530
- [pathKey, instruction2, typePath, documentType, assistableDocId, requestRunInstruction]
1464
+ [pathKey, instruction2, typePath, documentType, assistableDocumentId, requestRunInstruction]
1531
1465
  ), Region = useCallback((_props) => /* @__PURE__ */ jsx("div", { ..._props, style: { height: "100%", flex: 1, overflow: "auto" } }), []), assistTypeContext = useMemo(() => ({ typePath, documentType }), [typePath, documentType]);
1532
1466
  return !documentId || !schemaType || schemaType.jsonType !== "object" ? /* @__PURE__ */ jsx(Card, { flex: 1, padding: 4, children: /* @__PURE__ */ jsx(Text, { children: "Document not ready yet." }) }) : /* @__PURE__ */ jsxs(
1533
1467
  Flex,
@@ -1560,6 +1494,11 @@ function AssistInspector(props) {
1560
1494
  index: documentPane.index,
1561
1495
  itemId: "ai",
1562
1496
  pane: paneNode,
1497
+ forcedVersion: {
1498
+ isReleaseLocked: !1,
1499
+ selectedPerspectiveName: "published",
1500
+ selectedReleaseId: void 0
1501
+ },
1563
1502
  children: /* @__PURE__ */ jsx(DocumentForm, {})
1564
1503
  }
1565
1504
  )
@@ -1584,7 +1523,7 @@ function AssistInspector(props) {
1584
1523
  ] }) })
1585
1524
  ] }) }),
1586
1525
  /* @__PURE__ */ jsx(CardWithShadowAbove, { flex: "none", paddingX: 4, paddingY: 3, style: { justifySelf: "flex-end" }, children: /* @__PURE__ */ jsxs(Flex, { gap: 2, flex: 1, justify: "flex-end", children: [
1587
- (schemaType == null ? void 0 : schemaType.name) && pathKey && instructionKey && /* @__PURE__ */ jsx(Stack, { flex: 1, children: /* @__PURE__ */ jsx(
1526
+ schemaType?.name && pathKey && instructionKey && /* @__PURE__ */ jsx(Stack, { flex: 1, children: /* @__PURE__ */ jsx(
1588
1527
  Button,
1589
1528
  {
1590
1529
  mode: "ghost",
@@ -1599,7 +1538,7 @@ function AssistInspector(props) {
1599
1538
  /* @__PURE__ */ jsx(
1600
1539
  InstructionTaskHistoryButton,
1601
1540
  {
1602
- documentId: assistableDocId,
1541
+ documentId: assistableDocumentId,
1603
1542
  tasks,
1604
1543
  instructions,
1605
1544
  showTitles: !instructionKey
@@ -1697,7 +1636,7 @@ function FirstAssistedPathProvider(props) {
1697
1636
  const firstAssisted = members.find(
1698
1637
  (member) => member.kind === "field" && isAssistSupported(member.field.schemaType)
1699
1638
  );
1700
- return firstAssisted != null && firstAssisted.field.path ? pathToString(firstAssisted == null ? void 0 : firstAssisted.field.path) : void 0;
1639
+ return firstAssisted?.field.path ? pathToString(firstAssisted?.field.path) : void 0;
1701
1640
  }, [members]);
1702
1641
  return /* @__PURE__ */ jsx(FirstAssistedPathContext.Provider, { value: firstAssistedPath, children: props.children });
1703
1642
  }
@@ -1845,24 +1784,11 @@ function AiFieldPresence(props) {
1845
1784
  }
1846
1785
  ) });
1847
1786
  }
1848
- const AssistDocumentContext = createContext(
1849
- void 0
1850
- );
1851
- function useAssistDocumentContext() {
1852
- const context = useContext(AssistDocumentContext);
1853
- if (!context)
1854
- throw new Error("AssistDocumentContext value is missing");
1855
- return context;
1856
- }
1857
1787
  const NO_PRESENCE = [];
1858
1788
  function useAssistPresence(path, showFocusWithin) {
1859
- const context = useAssistDocumentContext(), assistDocument = context && "assistDocument" in context ? context.assistDocument : void 0, tasks = assistDocument == null ? void 0 : assistDocument.tasks;
1789
+ const context = useAssistDocumentContext(), tasks = (context && "assistDocument" in context ? context.assistDocument : void 0)?.tasks;
1860
1790
  return useMemo(() => {
1861
- var _a, _b;
1862
- const activePresence = (_b = (_a = tasks == null ? void 0 : tasks.filter((task) => !task.ended)) == null ? void 0 : _a.flatMap((task) => {
1863
- var _a2;
1864
- return (_a2 = task.presence) != null ? _a2 : [];
1865
- })) == null ? void 0 : _b.filter(
1791
+ const activePresence = tasks?.filter((task) => !task.ended)?.flatMap((task) => task.presence ?? [])?.filter(
1866
1792
  (p) => p.started && (/* @__PURE__ */ new Date()).getTime() - new Date(p.started).getTime() < maxHistoryVisibilityMs
1867
1793
  ).filter((presence) => {
1868
1794
  if (!presence.path || !path.length)
@@ -1873,11 +1799,10 @@ function useAssistPresence(path, showFocusWithin) {
1873
1799
  return typeof pathSegment == "string" ? pathSegment === statusSegment : isKeySegment(pathSegment) && isKeySegment(statusSegment) ? pathSegment._key === statusSegment._key : !1;
1874
1800
  });
1875
1801
  });
1876
- return activePresence != null && activePresence.length ? activePresence.map((status) => aiPresence(status, path)) : NO_PRESENCE;
1802
+ return activePresence?.length ? activePresence.map((status) => aiPresence(status, path)) : NO_PRESENCE;
1877
1803
  }, [showFocusWithin, tasks, path]);
1878
1804
  }
1879
1805
  function aiPresence(presence, path, title) {
1880
- var _a;
1881
1806
  return {
1882
1807
  user: {
1883
1808
  id: `sanity-assistant_${presence._key}`,
@@ -1885,7 +1810,7 @@ function aiPresence(presence, path, title) {
1885
1810
  },
1886
1811
  path,
1887
1812
  sessionId: "not-available",
1888
- lastActiveAt: (_a = presence == null ? void 0 : presence.started) != null ? _a : (/* @__PURE__ */ new Date()).toISOString()
1813
+ lastActiveAt: presence?.started ?? (/* @__PURE__ */ new Date()).toISOString()
1889
1814
  };
1890
1815
  }
1891
1816
  function AssistFieldWrapper(props) {
@@ -1920,14 +1845,13 @@ function useRegionRects() {
1920
1845
  const ref = useRef(null), [relativeBoundsRect, setRelativeBoundsRect] = useState(null), [relativeElementRect, setRelativeElementRect] = useState(null), [boundsScroll, setBoundsScroll] = useState({ x: 0, y: 0 }), [scroll, setScroll] = useState({ x: 0, y: 0 }), boundsScrollXRef = useRef(0), boundsScrollYRef = useRef(0), elementScrollXRef = useRef(0), elementScrollYRef = useRef(0);
1921
1846
  useEffect(() => {
1922
1847
  const el = ref.current;
1923
- if (!el)
1924
- return;
1848
+ if (!el) return;
1925
1849
  const scrollParents = [];
1926
1850
  let parent = el.parentElement;
1927
1851
  for (; parent && parent !== document.body; )
1928
1852
  hasOverflowScroll(parent) && scrollParents.push(parent), parent = parent.parentElement;
1929
1853
  function handleResize() {
1930
- const scrollParent = scrollParents[0], boundsRect = (scrollParent == null ? void 0 : scrollParent.getBoundingClientRect()) || {
1854
+ const boundsRect = scrollParents[0]?.getBoundingClientRect() || {
1931
1855
  x: 0,
1932
1856
  y: 0,
1933
1857
  width: window.innerWidth,
@@ -1950,7 +1874,7 @@ function useRegionRects() {
1950
1874
  for (const scrollParent2 of scrollParents)
1951
1875
  scrollX += scrollParent2.scrollLeft, scrollY += scrollParent2.scrollTop;
1952
1876
  const scrollParent = scrollParents[0];
1953
- boundsScrollXRef.current = scrollX - ((scrollParent == null ? void 0 : scrollParent.scrollLeft) || window.scrollX), boundsScrollYRef.current = scrollY - ((scrollParent == null ? void 0 : scrollParent.scrollTop) || window.scrollY), setBoundsScroll({
1877
+ boundsScrollXRef.current = scrollX - (scrollParent?.scrollLeft || window.scrollX), boundsScrollYRef.current = scrollY - (scrollParent?.scrollTop || window.scrollY), setBoundsScroll({
1954
1878
  x: boundsScrollXRef.current,
1955
1879
  y: boundsScrollYRef.current
1956
1880
  }), elementScrollXRef.current = scrollX, elementScrollYRef.current = scrollY, setScroll({ x: scrollX, y: scrollY });
@@ -1989,7 +1913,7 @@ function useRegionRects() {
1989
1913
  function ConnectorRegion(props) {
1990
1914
  const { children, onRectsChange, ...restProps } = props, { bounds, element, ref } = useRegionRects();
1991
1915
  return useEffect(() => {
1992
- onRectsChange == null || onRectsChange(bounds && element ? { bounds, element } : null);
1916
+ onRectsChange?.(bounds && element ? { bounds, element } : null);
1993
1917
  }, [bounds, element, onRectsChange]), /* @__PURE__ */ jsx("div", { ...restProps, ref, children });
1994
1918
  }
1995
1919
  const ConnectorsStoreContext = createContext(null);
@@ -2290,7 +2214,7 @@ const getLanguageParams = (select, document2) => {
2290
2214
  for (const [key, path] of Object.entries(selection)) {
2291
2215
  let value = get(document2, path);
2292
2216
  Array.isArray(value) && (value = value.filter(
2293
- (item) => typeof item == "object" ? (item == null ? void 0 : item._type) !== "reference" || "_ref" in item : !0
2217
+ (item) => typeof item == "object" ? item?._type !== "reference" || "_ref" in item : !0
2294
2218
  )), selectedValue[key] = value;
2295
2219
  }
2296
2220
  return selectedValue;
@@ -2313,34 +2237,32 @@ function useFieldTranslation() {
2313
2237
  return useContext(FieldTranslationContext);
2314
2238
  }
2315
2239
  function hasValuesToTranslate(fieldLanguageMaps, fromLanguage, basePath2) {
2316
- return fieldLanguageMaps == null ? void 0 : fieldLanguageMaps.some(
2317
- (map) => map.inputLanguageId === (fromLanguage == null ? void 0 : fromLanguage.id) && map.inputPath && pathToString(map.inputPath).startsWith(pathToString(basePath2))
2240
+ return fieldLanguageMaps?.some(
2241
+ (map) => map.inputLanguageId === fromLanguage?.id && map.inputPath && pathToString(map.inputPath).startsWith(pathToString(basePath2))
2318
2242
  );
2319
2243
  }
2320
2244
  function FieldTranslationProvider(props) {
2321
- var _a, _b, _c;
2322
- const { config: assistConfig } = useAiAssistanceConfig(), apiClient = useApiClient(assistConfig.__customApiClient), config = (_a = assistConfig.translate) == null ? void 0 : _a.field, { translate: runTranslate } = useTranslate(apiClient), [dialogOpen, setDialogOpen] = useState(!1), [fieldTranslationParams, setFieldTranslationParams] = useState(), [languages, setLanguages] = useState(), [fromLanguage, setFromLanguage] = useState(void 0), [toLanguages, setToLanguages] = useState(void 0), [fieldLanguageMaps, setFieldLanguageMaps] = useState(), close = useCallback(() => {
2245
+ const { config: assistConfig } = useAiAssistanceConfig(), apiClient = useApiClient(assistConfig.__customApiClient), config = assistConfig.translate?.field, { translate: runTranslate } = useTranslate(apiClient), [dialogOpen, setDialogOpen] = useState(!1), [fieldTranslationParams, setFieldTranslationParams] = useState(), [languages, setLanguages] = useState(), [fromLanguage, setFromLanguage] = useState(void 0), [toLanguages, setToLanguages] = useState(void 0), [fieldLanguageMaps, setFieldLanguageMaps] = useState(), close = useCallback(() => {
2323
2246
  setDialogOpen(!1), setLanguages(void 0), setFieldTranslationParams(void 0);
2324
- }, []), languageClient = useClient({ apiVersion: (_b = config == null ? void 0 : config.apiVersion) != null ? _b : "2022-11-27" }), documentId = (_c = fieldTranslationParams == null ? void 0 : fieldTranslationParams.document) == null ? void 0 : _c._id, id = useId(), selectFromLanguage = useCallback(
2247
+ }, []), languageClient = useClient({ apiVersion: config?.apiVersion ?? "2022-11-27" }), documentId = fieldTranslationParams?.document?._id, id = useId(), selectFromLanguage = useCallback(
2325
2248
  (from, languages2, params) => {
2326
- var _a2, _b2;
2327
- const { document: document2, documentSchema } = params != null ? params : {};
2249
+ const { document: document2, documentSchema } = params ?? {};
2328
2250
  if (setFromLanguage(from), !document2 || !documentSchema || !params || !languages2) {
2329
2251
  setFieldLanguageMaps(void 0);
2330
2252
  return;
2331
2253
  }
2332
- const preferred = getPreferredToFieldLanguages(from.id), allToLanguages = languages2.filter((l) => l.id !== (from == null ? void 0 : from.id)), filteredToLanguages = allToLanguages.filter(
2254
+ const preferred = getPreferredToFieldLanguages(from.id), allToLanguages = languages2.filter((l) => l.id !== from?.id), filteredToLanguages = allToLanguages.filter(
2333
2255
  (l) => !preferred.length || preferred.includes(l.id)
2334
2256
  );
2335
2257
  setToLanguages(filteredToLanguages);
2336
- const fromId = from == null ? void 0 : from.id, allToIds = (_a2 = allToLanguages == null ? void 0 : allToLanguages.map((l) => l.id)) != null ? _a2 : [], docMembers = getDocumentMembersFlat(document2, documentSchema);
2337
- if (fromId && allToIds != null && allToIds.length) {
2258
+ const fromId = from?.id, allToIds = allToLanguages?.map((l) => l.id) ?? [], docMembers = getDocumentMembersFlat(document2, documentSchema);
2259
+ if (fromId && allToIds?.length) {
2338
2260
  const transMap = getFieldLanguageMap(
2339
2261
  documentSchema,
2340
2262
  docMembers,
2341
2263
  fromId,
2342
2264
  allToIds.filter((toId) => fromId !== toId),
2343
- (_b2 = config == null ? void 0 : config.translationOutputs) != null ? _b2 : defaultLanguageOutputs
2265
+ config?.translationOutputs ?? defaultLanguageOutputs
2344
2266
  );
2345
2267
  setFieldLanguageMaps(transMap);
2346
2268
  } else
@@ -2351,10 +2273,10 @@ function FieldTranslationProvider(props) {
2351
2273
  (toggledLang, toLanguages2, languages2) => {
2352
2274
  if (!languages2 || !fromLanguage)
2353
2275
  return;
2354
- const wasSelected = !!(toLanguages2 != null && toLanguages2.find((l) => l.id === toggledLang.id)), newToLangs = languages2.filter(
2355
- (anyLang) => !!(toLanguages2 != null && toLanguages2.find(
2276
+ const wasSelected = !!toLanguages2?.find((l) => l.id === toggledLang.id), newToLangs = languages2.filter(
2277
+ (anyLang) => !!toLanguages2?.find(
2356
2278
  (selectedLang) => toggledLang.id !== selectedLang.id && selectedLang.id === anyLang.id
2357
- )) || toggledLang.id === anyLang.id && !wasSelected
2279
+ ) || toggledLang.id === anyLang.id && !wasSelected
2358
2280
  );
2359
2281
  setToLanguages(newToLangs), setPreferredToFieldLanguages(
2360
2282
  fromLanguage.id,
@@ -2365,26 +2287,26 @@ function FieldTranslationProvider(props) {
2365
2287
  ), openFieldTranslation = useCallback(
2366
2288
  async (params) => {
2367
2289
  setDialogOpen(!0);
2368
- const languageParams = getLanguageParams(config == null ? void 0 : config.selectLanguageParams, params.document), languages2 = await (typeof (config == null ? void 0 : config.languages) == "function" ? config == null ? void 0 : config.languages(languageClient, languageParams) : Promise.resolve(config == null ? void 0 : config.languages));
2290
+ const languageParams = getLanguageParams(config?.selectLanguageParams, params.document), languages2 = await (typeof config?.languages == "function" ? config?.languages(languageClient, languageParams) : Promise.resolve(config?.languages));
2369
2291
  setLanguages(languages2), setFieldTranslationParams(params);
2370
- const fromLanguage2 = languages2 == null ? void 0 : languages2[0];
2292
+ const fromLanguage2 = languages2?.[0];
2371
2293
  fromLanguage2 ? selectFromLanguage(fromLanguage2, languages2, params) : console.error("No languages available for selected language params", languageParams);
2372
2294
  },
2373
2295
  [selectFromLanguage, config, languageClient]
2374
2296
  ), contextValue = useMemo(() => ({
2375
2297
  openFieldTranslation,
2376
2298
  translationLoading: !1
2377
- }), [openFieldTranslation]), runDisabled = !fromLanguage || !(toLanguages != null && toLanguages.length) || !(fieldLanguageMaps != null && fieldLanguageMaps.length) || !documentId || !hasValuesToTranslate(fieldLanguageMaps, fromLanguage, fieldTranslationParams.translatePath), onRunTranslation = useCallback(() => {
2378
- const translatePath = fieldTranslationParams == null ? void 0 : fieldTranslationParams.translatePath;
2299
+ }), [openFieldTranslation]), runDisabled = !fromLanguage || !toLanguages?.length || !fieldLanguageMaps?.length || !documentId || !hasValuesToTranslate(fieldLanguageMaps, fromLanguage, fieldTranslationParams.translatePath), onRunTranslation = useCallback(() => {
2300
+ const translatePath = fieldTranslationParams?.translatePath;
2379
2301
  fieldLanguageMaps && documentId && translatePath && runTranslate({
2380
2302
  documentId,
2381
2303
  translatePath,
2382
2304
  fieldLanguageMap: fieldLanguageMaps.map((map) => ({
2383
2305
  ...map,
2384
2306
  // eslint-disable-next-line max-nested-callbacks
2385
- outputs: map.outputs.filter((out) => !!(toLanguages != null && toLanguages.find((l) => l.id === out.id)))
2307
+ outputs: map.outputs.filter((out) => !!toLanguages?.find((l) => l.id === out.id))
2386
2308
  })),
2387
- conditionalMembers: fieldTranslationParams == null ? void 0 : fieldTranslationParams.conditionalMembers
2309
+ conditionalMembers: fieldTranslationParams?.conditionalMembers
2388
2310
  }), close();
2389
2311
  }, [
2390
2312
  fieldLanguageMaps,
@@ -2392,8 +2314,8 @@ function FieldTranslationProvider(props) {
2392
2314
  runTranslate,
2393
2315
  close,
2394
2316
  toLanguages,
2395
- fieldTranslationParams == null ? void 0 : fieldTranslationParams.translatePath,
2396
- fieldTranslationParams == null ? void 0 : fieldTranslationParams.conditionalMembers
2317
+ fieldTranslationParams?.translatePath,
2318
+ fieldTranslationParams?.conditionalMembers
2397
2319
  ]), runButton = /* @__PURE__ */ jsx(
2398
2320
  Button,
2399
2321
  {
@@ -2425,7 +2347,7 @@ function FieldTranslationProvider(props) {
2425
2347
  children: languages ? /* @__PURE__ */ jsxs(Flex, { padding: 4, gap: 5, align: "flex-start", justify: "center", children: [
2426
2348
  /* @__PURE__ */ jsxs(Stack, { space: 2, children: [
2427
2349
  /* @__PURE__ */ jsx(Box, { marginBottom: 2, children: /* @__PURE__ */ jsx(Text, { weight: "semibold", children: "From" }) }),
2428
- languages == null ? void 0 : languages.map((radioLanguage) => /* @__PURE__ */ jsx(
2350
+ languages?.map((radioLanguage) => /* @__PURE__ */ jsx(
2429
2351
  FromLanguageRadio,
2430
2352
  {
2431
2353
  radioLanguage,
@@ -2461,7 +2383,6 @@ function FieldTranslationProvider(props) {
2461
2383
  ] });
2462
2384
  }
2463
2385
  function ToLanguageCheckbox(props) {
2464
- var _a;
2465
2386
  const { checkboxLanguage, fromLanguage, toLanguages, toggleToLanguage, languages } = props, langId = checkboxLanguage.id, onChange = useCallback(
2466
2387
  () => toggleToLanguage(checkboxLanguage, toLanguages, languages),
2467
2388
  [toggleToLanguage, checkboxLanguage, toLanguages, languages]
@@ -2472,26 +2393,25 @@ function ToLanguageCheckbox(props) {
2472
2393
  gap: 3,
2473
2394
  align: "center",
2474
2395
  as: "label",
2475
- style: langId === (fromLanguage == null ? void 0 : fromLanguage.id) ? { opacity: 0.5 } : void 0,
2396
+ style: langId === fromLanguage?.id ? { opacity: 0.5 } : void 0,
2476
2397
  children: [
2477
2398
  /* @__PURE__ */ jsx(
2478
2399
  Checkbox,
2479
2400
  {
2480
2401
  name: "toLang",
2481
2402
  value: langId,
2482
- checked: langId !== (fromLanguage == null ? void 0 : fromLanguage.id) && !!(toLanguages != null && toLanguages.find((tl) => tl.id === langId)),
2403
+ checked: langId !== fromLanguage?.id && !!toLanguages?.find((tl) => tl.id === langId),
2483
2404
  onChange,
2484
- disabled: langId === (fromLanguage == null ? void 0 : fromLanguage.id)
2405
+ disabled: langId === fromLanguage?.id
2485
2406
  }
2486
2407
  ),
2487
- /* @__PURE__ */ jsx(Text, { muted: langId === (fromLanguage == null ? void 0 : fromLanguage.id), children: (_a = checkboxLanguage.title) != null ? _a : langId })
2408
+ /* @__PURE__ */ jsx(Text, { muted: langId === fromLanguage?.id, children: checkboxLanguage.title ?? langId })
2488
2409
  ]
2489
2410
  },
2490
2411
  langId
2491
2412
  );
2492
2413
  }
2493
2414
  function FromLanguageRadio(props) {
2494
- var _a;
2495
2415
  const { languages, radioLanguage, selectFromLanguage, fromLanguage, fieldTranslationParams } = props, langId = radioLanguage.id, onChange = useCallback(
2496
2416
  () => selectFromLanguage(radioLanguage, languages, fieldTranslationParams),
2497
2417
  [selectFromLanguage, radioLanguage, languages, fieldTranslationParams]
@@ -2502,11 +2422,11 @@ function FromLanguageRadio(props) {
2502
2422
  {
2503
2423
  name: "fromLang",
2504
2424
  value: langId,
2505
- checked: langId === (fromLanguage == null ? void 0 : fromLanguage.id),
2425
+ checked: langId === fromLanguage?.id,
2506
2426
  onChange
2507
2427
  }
2508
2428
  ),
2509
- /* @__PURE__ */ jsx(Text, { children: (_a = radioLanguage.title) != null ? _a : radioLanguage.id })
2429
+ /* @__PURE__ */ jsx(Text, { children: radioLanguage.title ?? radioLanguage.id })
2510
2430
  ] }, langId);
2511
2431
  }
2512
2432
  function AssistLayout(props) {
@@ -2590,10 +2510,9 @@ function AssistDocumentForm(props) {
2590
2510
  return props.readOnly ? /* @__PURE__ */ jsx(Card, { border: !0, tone: "caution", padding: 2, children: /* @__PURE__ */ jsx(Text, { size: 1, children: " You do not have sufficient permissions to manage instructions." }) }) : /* @__PURE__ */ jsx(AssistDocumentFormEditable, { ...props });
2591
2511
  }
2592
2512
  function AssistDocumentFormEditable(props) {
2593
- const { onChange } = props, value = props.value, id = value == null ? void 0 : value._id, fields = value == null ? void 0 : value.fields, { params, setParams } = useAiPaneRouter(), pathKey = params[fieldPathParam], { typePath, documentType: targetDocumentType } = useContext(AssistTypeContext), instruction2 = params[instructionParam], activeKey = useMemo(() => {
2594
- var _a;
2513
+ const { onChange } = props, value = props.value, id = value?._id, fields = value?.fields, { params, setParams } = useAiPaneRouter(), pathKey = params[fieldPathParam], { typePath, documentType: targetDocumentType } = useContext(AssistTypeContext), instruction2 = params[instructionParam], activeKey = useMemo(() => {
2595
2514
  if (typePath)
2596
- return (_a = (fields != null ? fields : EMPTY_FIELDS).find((f) => f.path === typePath)) == null ? void 0 : _a._key;
2515
+ return (fields ?? EMPTY_FIELDS).find((f) => f.path === typePath)?._key;
2597
2516
  }, [fields, typePath]), activePath = useMemo(() => {
2598
2517
  if (!activeKey)
2599
2518
  return;
@@ -2605,23 +2524,21 @@ function AssistDocumentFormEditable(props) {
2605
2524
  }, [schema, targetDocumentType]), fieldSchema = useSelectedSchema(pathKey, documentSchema), context = useMemo(
2606
2525
  () => ({
2607
2526
  documentSchema,
2608
- fieldSchema: fieldSchema != null ? fieldSchema : documentSchema
2527
+ fieldSchema: fieldSchema ?? documentSchema
2609
2528
  }),
2610
2529
  [fieldSchema, documentSchema]
2611
- ), title = value == null ? void 0 : value.title;
2530
+ ), title = value?.title;
2612
2531
  useEffect(() => {
2613
- var _a;
2614
- !title && documentSchema && !(id != null && id.startsWith("drafts.")) && onChange(set((_a = documentSchema.title) != null ? _a : documentSchema.name, ["title"]));
2532
+ !title && documentSchema && !id?.startsWith("drafts.") && onChange(set(documentSchema.title ?? documentSchema.name, ["title"]));
2615
2533
  }, [title, documentSchema, onChange, id]);
2616
2534
  const { onPathOpen, ...formCallbacks } = useFormCallbacks(), newCallbacks = useMemo(
2617
2535
  () => ({
2618
2536
  ...formCallbacks,
2619
2537
  onPathOpen: (path) => {
2620
- var _a;
2621
2538
  !instruction2 && path.length === 4 && path[2] === "instructions" ? (setParams(
2622
2539
  typed({
2623
2540
  ...params,
2624
- [instructionParam]: (_a = path[3]) == null ? void 0 : _a._key
2541
+ [instructionParam]: path[3]?._key
2625
2542
  })
2626
2543
  ), onPathOpen([])) : setTimeout(() => onPathOpen(path), 0);
2627
2544
  }
@@ -2656,7 +2573,7 @@ function useSelectedSchema(fieldPath, documentSchema) {
2656
2573
  const path = stringToPath(fieldPath);
2657
2574
  let currentSchema = documentSchema;
2658
2575
  for (let i = 0; i < path.length; i++) {
2659
- const segment = path[i], field = currentSchema == null ? void 0 : currentSchema.fields.find((f) => f.name === segment);
2576
+ const segment = path[i], field = currentSchema?.fields.find((f) => f.name === segment);
2660
2577
  if (!field)
2661
2578
  return;
2662
2579
  if (i === path.length - 1)
@@ -2677,18 +2594,16 @@ function FieldsInitializer({
2677
2594
  }) {
2678
2595
  const {
2679
2596
  config: { __presets: presets }
2680
- } = useAiAssistanceConfig(), existingField = fields == null ? void 0 : fields.find((f) => f._key === pathKey), documentPresets = !!(documentSchema != null && documentSchema.name) && (presets == null ? void 0 : presets[documentSchema == null ? void 0 : documentSchema.name]), missingPresetInstructions = useMemo(() => {
2681
- var _a, _b;
2597
+ } = useAiAssistanceConfig(), existingField = fields?.find((f) => f._key === pathKey), documentPresets = !!documentSchema?.name && presets?.[documentSchema?.name], missingPresetInstructions = useMemo(() => {
2682
2598
  if (!documentPresets || !pathKey)
2683
2599
  return;
2684
- const existingInstructions = existingField == null ? void 0 : existingField.instructions, presetField = (_a = documentPresets.fields) == null ? void 0 : _a.find((f) => f.path === pathKey);
2685
- return (_b = presetField == null ? void 0 : presetField.instructions) == null ? void 0 : _b.filter(
2686
- (i) => !(existingInstructions != null && existingInstructions.some((ei) => ei._key === i._key))
2600
+ const existingInstructions = existingField?.instructions;
2601
+ return documentPresets.fields?.find((f) => f.path === pathKey)?.instructions?.filter(
2602
+ (i) => !existingInstructions?.some((ei) => ei._key === i._key)
2687
2603
  );
2688
2604
  }, [documentPresets, pathKey, existingField]), initialized = useRef(!1);
2689
2605
  return useEffect(() => {
2690
- var _a;
2691
- if (initialized.current || !pathKey || existingField && !(missingPresetInstructions != null && missingPresetInstructions.length))
2606
+ if (initialized.current || !pathKey || existingField && !missingPresetInstructions?.length)
2692
2607
  return;
2693
2608
  let event = PatchEvent.from([setIfMissing([], ["fields"])]);
2694
2609
  existingField || (event = event.append(
@@ -2704,17 +2619,14 @@ function FieldsInitializer({
2704
2619
  "after",
2705
2620
  ["fields", -1]
2706
2621
  )
2707
- )), (_a = existingField == null ? void 0 : existingField.instructions) != null && _a.length || (event = event.append([setIfMissing([], ["fields", { _key: pathKey }, "instructions"])])), missingPresetInstructions != null && missingPresetInstructions.length && (event = event.append(
2622
+ )), existingField?.instructions?.length || (event = event.append([setIfMissing([], ["fields", { _key: pathKey }, "instructions"])])), missingPresetInstructions?.length && (event = event.append(
2708
2623
  insert(
2709
2624
  missingPresetInstructions.map(
2710
- (preset) => {
2711
- var _a2;
2712
- return {
2713
- ...preset,
2714
- _type: "sanity.assist.instruction",
2715
- prompt: (_a2 = preset.prompt) == null ? void 0 : _a2.map((p) => ({ markDefs: [], ...p }))
2716
- };
2717
- }
2625
+ (preset) => ({
2626
+ ...preset,
2627
+ _type: "sanity.assist.instruction",
2628
+ prompt: preset.prompt?.map((p) => ({ markDefs: [], ...p }))
2629
+ })
2718
2630
  ),
2719
2631
  "after",
2720
2632
  ["fields", { _key: pathKey }, "instructions", -1]
@@ -2727,11 +2639,10 @@ function AssistInlineFormBlock(props) {
2727
2639
  return /* @__PURE__ */ jsx(InlineBlockValueContext.Provider, { value: props.value, children: /* @__PURE__ */ jsx(Fragment, { children: props.renderDefault(props) }) });
2728
2640
  }
2729
2641
  function FieldRefPreview(props) {
2730
- var _a, _b, _c, _d;
2731
- const documentSchema = (_a = useContext(SelectedFieldContext)) == null ? void 0 : _a.documentSchema, path = (_c = (_b = useContext(InlineBlockValueContext)) == null ? void 0 : _b.path) != null ? _c : props.path, selectedField = useSelectedField(documentSchema, path);
2642
+ const { actions } = props, documentSchema = useContext(SelectedFieldContext)?.documentSchema, path = useContext(InlineBlockValueContext)?.path ?? props.path, selectedField = useSelectedField(documentSchema, path);
2732
2643
  return /* @__PURE__ */ jsxs(Flex, { gap: 2, align: "center", style: { width: "100%" }, children: [
2733
- /* @__PURE__ */ jsx(Flex, { flex: 1, gap: 2, align: "center", paddingY: 3, paddingX: 1, children: /* @__PURE__ */ jsx(Box, { children: /* @__PURE__ */ jsx(Text, { size: 1, textOverflow: "ellipsis", children: (_d = selectedField == null ? void 0 : selectedField.title) != null ? _d : "Select field" }) }) }),
2734
- /* @__PURE__ */ jsx(Fragment, { children: props.actions })
2644
+ /* @__PURE__ */ jsx(Flex, { flex: 1, gap: 2, align: "center", paddingY: 3, paddingX: 1, children: /* @__PURE__ */ jsx(Box, { children: /* @__PURE__ */ jsx(Text, { size: 1, textOverflow: "ellipsis", children: selectedField?.title ?? "Select field" }) }) }),
2645
+ actions
2735
2646
  ] });
2736
2647
  }
2737
2648
  function HiddenFieldTitle(props) {
@@ -2761,13 +2672,11 @@ function IconItem({
2761
2672
  return /* @__PURE__ */ jsx(MenuItem, { icon, title: key, text: key, onClick });
2762
2673
  }
2763
2674
  function getIcon(iconName) {
2764
- var _a, _b;
2765
- return (_b = (_a = Object.entries(icons).find(([key]) => key === iconName)) == null ? void 0 : _a[1]) != null ? _b : icons.sparkles;
2675
+ return Object.entries(icons).find(([key]) => key === iconName)?.[1] ?? icons.sparkles;
2766
2676
  }
2767
2677
  function InstructionVisibility(props) {
2768
2678
  const { value, onChange } = props, user = useCurrentUser(), handleChange = useCallback(() => {
2769
- var _a;
2770
- const newValue = value ? "" : (_a = user == null ? void 0 : user.id) != null ? _a : "";
2679
+ const newValue = value ? "" : user?.id ?? "";
2771
2680
  onChange(newValue ? set(newValue) : unset());
2772
2681
  }, [onChange, user, value]), id = useId();
2773
2682
  return /* @__PURE__ */ jsx(Card, { children: /* @__PURE__ */ jsxs(Flex, { gap: 2, align: "flex-start", children: [
@@ -2786,11 +2695,9 @@ function InstructionVisibility(props) {
2786
2695
  ] }) });
2787
2696
  }
2788
2697
  function FieldRefPathInput(props) {
2789
- var _a;
2790
- const documentSchema = (_a = useContext(SelectedFieldContext)) == null ? void 0 : _a.documentSchema, { typePath } = useContext(AssistTypeContext), ref = useRef(null), id = useId(), { onChange } = props;
2698
+ const documentSchema = useContext(SelectedFieldContext)?.documentSchema, { typePath } = useContext(AssistTypeContext), ref = useRef(null), id = useId(), { onChange } = props;
2791
2699
  useEffect(() => {
2792
- var _a2, _b;
2793
- (_b = (_a2 = ref.current) == null ? void 0 : _a2.querySelector("input")) == null || _b.focus();
2700
+ ref.current?.querySelector("input")?.focus();
2794
2701
  }, []);
2795
2702
  const onSelect = useCallback((path) => onChange(set(path)), [onChange]), filter2 = useCallback(
2796
2703
  (field) => {
@@ -2838,15 +2745,14 @@ function ObjectMember({ fieldName, ...props }) {
2838
2745
  }
2839
2746
  const NONE = [];
2840
2747
  function NameField(props) {
2841
- var _a;
2842
- const fieldsetMember = findFieldsetMember(props.members, "appearance"), titleId = useId(), members = (_a = fieldsetMember == null ? void 0 : fieldsetMember.fieldSet.members) != null ? _a : NONE, iconMember = findFieldMember(members, "icon"), titleMember = findFieldMember(members, "title"), titlePlaceholder = "Untitled", moddedTitleMember = useMemo(() => {
2748
+ const fieldsetMember = findFieldsetMember(props.members, "appearance"), titleId = useId(), members = fieldsetMember?.fieldSet.members ?? NONE, iconMember = findFieldMember(members, "icon"), titleMember = findFieldMember(members, "title"), titlePlaceholder = "Untitled", moddedTitleMember = useMemo(() => {
2843
2749
  if (titleMember)
2844
2750
  return titleMember.kind === "error" ? titleMember : {
2845
2751
  ...titleMember,
2846
2752
  field: {
2847
- ...titleMember == null ? void 0 : titleMember.field,
2753
+ ...titleMember?.field,
2848
2754
  schemaType: {
2849
- ...titleMember == null ? void 0 : titleMember.field.schemaType,
2755
+ ...titleMember?.field.schemaType,
2850
2756
  placeholder: titlePlaceholder
2851
2757
  }
2852
2758
  }
@@ -2862,21 +2768,18 @@ function NameField(props) {
2862
2768
  ] }) });
2863
2769
  }
2864
2770
  function ShareField(props) {
2865
- var _a;
2866
- const fieldsetMember = findFieldsetMember(props.members, "appearance"), members = (_a = fieldsetMember == null ? void 0 : fieldsetMember.fieldSet.members) != null ? _a : NONE, visibilityMember = findFieldMember(members, "userId");
2771
+ const members = findFieldsetMember(props.members, "appearance")?.fieldSet.members ?? NONE, visibilityMember = findFieldMember(members, "userId");
2867
2772
  return /* @__PURE__ */ jsx(Fragment, { children: visibilityMember && /* @__PURE__ */ jsx(ObjectInputMember, { ...props, member: visibilityMember }) });
2868
2773
  }
2869
2774
  function InstructionOutputField(props) {
2870
- var _a;
2871
- const { fieldSchema } = (_a = useContext(SelectedFieldContext)) != null ? _a : {};
2775
+ const { fieldSchema } = useContext(SelectedFieldContext) ?? {};
2872
2776
  return !fieldSchema || !(isObjectSchemaType(fieldSchema) || isArrayOfObjectsSchemaType(fieldSchema)) ? null : /* @__PURE__ */ jsx(EnabledOutputField, { ...props, fieldSchema, children: props.children });
2873
2777
  }
2874
2778
  function EnabledOutputField({
2875
2779
  fieldSchema,
2876
2780
  ...props
2877
2781
  }) {
2878
- var _a;
2879
- const [open, setOpen] = useState(!!((_a = props.value) != null && _a.length)), onExpand = useCallback(() => setOpen(!0), []), onCollapse = useCallback(() => setOpen(!1), []);
2782
+ const [open, setOpen] = useState(!!props.value?.length), onExpand = useCallback(() => setOpen(!0), []), onCollapse = useCallback(() => setOpen(!1), []);
2880
2783
  return props.renderDefault({
2881
2784
  ...props,
2882
2785
  collapsible: !0,
@@ -2888,18 +2791,16 @@ function EnabledOutputField({
2888
2791
  });
2889
2792
  }
2890
2793
  function InstructionOutputInput(props) {
2891
- var _a;
2892
- const { fieldSchema } = (_a = useContext(SelectedFieldContext)) != null ? _a : {};
2794
+ const { fieldSchema } = useContext(SelectedFieldContext) ?? {};
2893
2795
  return fieldSchema ? isObjectSchemaType(fieldSchema) ? /* @__PURE__ */ jsx(ObjectOutputInput, { ...props, fieldSchema }) : isArrayOfObjectsSchemaType(fieldSchema) ? /* @__PURE__ */ jsx(ArrayOutputInput, { ...props, fieldSchema }) : null : null;
2894
2796
  }
2895
2797
  function useEmptySelectAllValue(value, allowedValues, onChange) {
2896
2798
  useEffect(() => {
2897
- var _a, _b;
2898
- const validValues = value == null ? void 0 : value.filter(
2799
+ const validValues = value?.filter(
2899
2800
  (v) => allowedValues.find(
2900
2801
  (f) => f.name === (v._type === outputFieldTypeName ? v.relativePath : v.type)
2901
2802
  )
2902
- ), valueLength = (_a = value == null ? void 0 : value.length) != null ? _a : 0, validLength = (_b = validValues == null ? void 0 : validValues.length) != null ? _b : 0;
2803
+ ), valueLength = value?.length ?? 0, validLength = validValues?.length ?? 0;
2903
2804
  (!validLength && valueLength || validLength >= allowedValues.length) && onChange(PatchEvent.from([unset()]));
2904
2805
  }, [allowedValues, value, onChange]);
2905
2806
  }
@@ -2915,7 +2816,7 @@ function ObjectOutputInput({
2915
2816
  const onSelectChange = useCallback(
2916
2817
  (checked, selectedValue) => {
2917
2818
  if (checked)
2918
- if (value != null && value.length)
2819
+ if (value?.length)
2919
2820
  onChange(PatchEvent.from(unset([{ _key: selectedValue }])));
2920
2821
  else {
2921
2822
  const items = fields.filter((f) => f.name !== selectedValue).map(
@@ -2938,18 +2839,15 @@ function ObjectOutputInput({
2938
2839
  },
2939
2840
  [onChange, value, fields]
2940
2841
  );
2941
- return /* @__PURE__ */ jsx(Stack, { space: 2, children: fields.map((field) => {
2942
- var _a;
2943
- return /* @__PURE__ */ jsx(Flex, { align: "center", gap: 2, children: /* @__PURE__ */ jsx(
2944
- Selectable,
2945
- {
2946
- value: field.name,
2947
- title: (_a = field.type.title) != null ? _a : field.name,
2948
- arrayValue: value,
2949
- onChange: onSelectChange
2950
- }
2951
- ) }, field.name);
2952
- }) });
2842
+ return /* @__PURE__ */ jsx(Stack, { space: 2, children: fields.map((field) => /* @__PURE__ */ jsx(Flex, { align: "center", gap: 2, children: /* @__PURE__ */ jsx(
2843
+ Selectable,
2844
+ {
2845
+ value: field.name,
2846
+ title: field.type.title ?? field.name,
2847
+ arrayValue: value,
2848
+ onChange: onSelectChange
2849
+ }
2850
+ ) }, field.name)) });
2953
2851
  }
2954
2852
  function ArrayOutputInput({
2955
2853
  fieldSchema,
@@ -2963,7 +2861,7 @@ function ArrayOutputInput({
2963
2861
  const onSelectChange = useCallback(
2964
2862
  (checked, selectedValue) => {
2965
2863
  if (checked)
2966
- if (value != null && value.length)
2864
+ if (value?.length)
2967
2865
  onChange(PatchEvent.from(unset([{ _key: selectedValue }])));
2968
2866
  else {
2969
2867
  const items = ofItems.filter((f) => f.name !== selectedValue).map(
@@ -2986,18 +2884,15 @@ function ArrayOutputInput({
2986
2884
  },
2987
2885
  [onChange, value, ofItems]
2988
2886
  );
2989
- return /* @__PURE__ */ jsx(Stack, { space: 2, children: ofItems.map((itemType) => {
2990
- var _a;
2991
- return /* @__PURE__ */ jsx(Flex, { children: /* @__PURE__ */ jsx(
2992
- Selectable,
2993
- {
2994
- value: itemType.name,
2995
- title: isType(itemType, "block") ? "Text" : (_a = itemType.title) != null ? _a : itemType.name,
2996
- arrayValue: value,
2997
- onChange: onSelectChange
2998
- }
2999
- ) }, itemType.name);
3000
- }) });
2887
+ return /* @__PURE__ */ jsx(Stack, { space: 2, children: ofItems.map((itemType) => /* @__PURE__ */ jsx(Flex, { children: /* @__PURE__ */ jsx(
2888
+ Selectable,
2889
+ {
2890
+ value: itemType.name,
2891
+ title: isType(itemType, "block") ? "Text" : itemType.title ?? itemType.name,
2892
+ arrayValue: value,
2893
+ onChange: onSelectChange
2894
+ }
2895
+ ) }, itemType.name)) });
3001
2896
  }
3002
2897
  function Selectable({
3003
2898
  title,
@@ -3005,7 +2900,7 @@ function Selectable({
3005
2900
  value,
3006
2901
  onChange
3007
2902
  }) {
3008
- const checked = !(arrayValue != null && arrayValue.length) || !!(arrayValue != null && arrayValue.find((v) => v._key === value)), handleChange = useCallback(() => onChange(checked, value), [onChange, checked, value]);
2903
+ const checked = !arrayValue?.length || !!arrayValue?.find((v) => v._key === value), handleChange = useCallback(() => onChange(checked, value), [onChange, checked, value]);
3009
2904
  return /* @__PURE__ */ jsxs(Flex, { gap: 2, align: "flex-start", children: [
3010
2905
  /* @__PURE__ */ jsx(Checkbox, { checked, onChange: handleChange }),
3011
2906
  /* @__PURE__ */ jsx(Card, { marginTop: 1, onClick: handleChange, children: /* @__PURE__ */ jsx(Text, { style: { cursor: "default" }, size: 1, children: title }) })
@@ -3052,9 +2947,8 @@ function PromptInput(props) {
3052
2947
  }
3053
2948
  function useOnlyInlineBlocks(props) {
3054
2949
  useEffect(() => {
3055
- var _a;
3056
2950
  let needsFix = !1;
3057
- const val = ((_a = props.value) != null ? _a : []).map((block) => block._type === "block" ? block : (needsFix = !0, typed({
2951
+ const val = (props.value ?? []).map((block) => block._type === "block" ? block : (needsFix = !0, typed({
3058
2952
  _key: randomKey(12),
3059
2953
  _type: "block",
3060
2954
  level: 0,
@@ -3073,15 +2967,14 @@ function InstructionsArrayField(props) {
3073
2967
  }
3074
2968
  function InstructionsArrayInput(props) {
3075
2969
  const user = useCurrentUser(), originalValue = props.value, originalMembers = props.members, value = useMemo(
3076
- () => (originalValue != null ? originalValue : []).filter((v) => !v.userId || v.userId === (user == null ? void 0 : user.id)),
2970
+ () => (originalValue ?? []).filter((v) => !v.userId || v.userId === user?.id),
3077
2971
  [originalValue, user]
3078
2972
  ), members = useMemo(
3079
- () => (originalMembers != null ? originalMembers : []).filter((v) => {
3080
- var _a;
2973
+ () => (originalMembers ?? []).filter((v) => {
3081
2974
  if (v.kind === "error")
3082
2975
  return !0;
3083
- const value2 = (_a = v == null ? void 0 : v.item) == null ? void 0 : _a.value;
3084
- return !value2.userId || value2.userId === (user == null ? void 0 : user.id);
2976
+ const value2 = v?.item?.value;
2977
+ return !value2.userId || value2.userId === user?.id;
3085
2978
  }),
3086
2979
  [originalMembers, user]
3087
2980
  );
@@ -3090,8 +2983,7 @@ function InstructionsArrayInput(props) {
3090
2983
  function HideReferenceChangedBannerInput(props) {
3091
2984
  const ref = useRef(null);
3092
2985
  return useEffect(() => {
3093
- var _a;
3094
- const parent = (_a = ref.current) == null ? void 0 : _a.closest('[data-testid="pane-content"]');
2986
+ const parent = ref.current?.closest('[data-testid="pane-content"]');
3095
2987
  if (!parent)
3096
2988
  return;
3097
2989
  const style = document.createElement("style"), parentId = `id-${Math.random()}`.replace(".", "-");
@@ -3138,11 +3030,7 @@ const contextDocumentSchema = defineType({
3138
3030
  context: "context"
3139
3031
  },
3140
3032
  prepare({ title, context }) {
3141
- var _a;
3142
- const text = context == null ? void 0 : context.flatMap((block) => block == null ? void 0 : block.children).flatMap((child) => {
3143
- var _a2;
3144
- return (_a2 = child == null ? void 0 : child.text) == null ? void 0 : _a2.split(" ");
3145
- }).filter(Boolean), words = (_a = text == null ? void 0 : text.length) != null ? _a : 0;
3033
+ const words = context?.flatMap((block) => block?.children).flatMap((child) => child?.text?.split(" ")).filter(Boolean)?.length ?? 0;
3146
3034
  return {
3147
3035
  title,
3148
3036
  subtitle: `Words: ${words}`,
@@ -3164,11 +3052,10 @@ const contextDocumentSchema = defineType({
3164
3052
  input: FieldRefPathInput
3165
3053
  },
3166
3054
  validation: (rule) => rule.custom((value, context) => {
3167
- var _a;
3168
3055
  if (!value)
3169
3056
  return "Please select a field";
3170
3057
  try {
3171
- const docId = (_a = context.document) == null ? void 0 : _a._id;
3058
+ const docId = context.document?._id;
3172
3059
  if (!docId)
3173
3060
  return "Field reference cannot be used outside document inspector context. Could not resolve document id.";
3174
3061
  const targetDocType = docId.replace(new RegExp(`^${assistDocumentIdPrefix}`), ""), schema = context.schema.get(targetDocType);
@@ -3259,8 +3146,7 @@ const contextDocumentSchema = defineType({
3259
3146
  context: "reference.context"
3260
3147
  },
3261
3148
  prepare(select) {
3262
- var _a, _b, _c, _d;
3263
- return select.ref ? (_d = (_c = (_b = (_a = contextDocumentSchema) == null ? void 0 : _a.preview) == null ? void 0 : _b.prepare) == null ? void 0 : _c.call(_b, select)) != null ? _d : select : { title: "No reference selected", media: contextDocumentSchema.icon };
3149
+ return select.ref ? contextDocumentSchema?.preview?.prepare?.(select) ?? select : { title: "No reference selected", media: contextDocumentSchema.icon };
3264
3150
  }
3265
3151
  },
3266
3152
  options: {
@@ -3407,14 +3293,8 @@ const contextDocumentSchema = defineType({
3407
3293
  field: HiddenFieldTitle,
3408
3294
  input: InstructionVisibility
3409
3295
  },
3410
- initialValue: (params, context) => {
3411
- var _a, _b;
3412
- return (_b = (_a = context.currentUser) == null ? void 0 : _a.id) != null ? _b : "";
3413
- },
3414
- readOnly: (context) => {
3415
- var _a, _b, _c;
3416
- return !!((_a = context.parent) != null && _a.createdById && ((_b = context.parent) == null ? void 0 : _b.createdById) !== ((_c = context.currentUser) == null ? void 0 : _c.id));
3417
- }
3296
+ initialValue: (params, context) => context.currentUser?.id ?? "",
3297
+ readOnly: (context) => !!(context.parent?.createdById && context.parent?.createdById !== context.currentUser?.id)
3418
3298
  }),
3419
3299
  defineField({
3420
3300
  type: "string",
@@ -3422,10 +3302,7 @@ const contextDocumentSchema = defineType({
3422
3302
  title: "Created by",
3423
3303
  hidden: !0,
3424
3304
  fieldset: "appearance",
3425
- initialValue: (params, context) => {
3426
- var _a, _b;
3427
- return (_b = (_a = context.currentUser) == null ? void 0 : _a.id) != null ? _b : "";
3428
- }
3305
+ initialValue: (params, context) => context.currentUser?.id ?? ""
3429
3306
  }),
3430
3307
  defineField({
3431
3308
  type: "array",
@@ -3547,8 +3424,7 @@ const contextDocumentSchema = defineType({
3547
3424
  ]
3548
3425
  });
3549
3426
  function excludeComments(type) {
3550
- var _a, _b, _c;
3551
- const existingRender = (_a = type == null ? void 0 : type.components) == null ? void 0 : _a.field;
3427
+ const existingRender = type?.components?.field;
3552
3428
  return {
3553
3429
  ...type,
3554
3430
  ..."components" in type ? {
@@ -3562,11 +3438,11 @@ function excludeComments(type) {
3562
3438
  } : {},
3563
3439
  ..."fields" in type ? {
3564
3440
  // recursively disable comments in fields
3565
- fields: (_b = type.fields) == null ? void 0 : _b.map((field) => excludeComments(field))
3441
+ fields: type.fields?.map((field) => excludeComments(field))
3566
3442
  } : {},
3567
3443
  ..."of" in type ? {
3568
3444
  // recursively disable comments in array items
3569
- of: (_c = type.of) == null ? void 0 : _c.map((arrayItemType) => excludeComments(arrayItemType))
3445
+ of: type.of?.map((arrayItemType) => excludeComments(arrayItemType))
3570
3446
  } : {}
3571
3447
  };
3572
3448
  }
@@ -3586,61 +3462,19 @@ const instructionForm = [
3586
3462
  instructionTask,
3587
3463
  contextDocumentSchema
3588
3464
  ];
3589
- function useAssistDocumentContextValue(documentId, documentSchemaType) {
3590
- const { published, draft } = useEditState(
3591
- getPublishedId(documentId),
3592
- documentSchemaType.name,
3593
- "low"
3594
- ), assistableDocumentId = (draft == null ? void 0 : draft._id) || (published == null ? void 0 : published._id) || documentId, documentIsNew = !(draft != null && draft._id) && !(published != null && published._id), documentIsAssistable = isDocAssistable(documentSchemaType, published, draft), { params } = useAiPaneRouter(), selectedPath = params[fieldPathParam], { openInspector, closeInspector, inspector, onChange: documentOnChange } = useDocumentPane(), assistDocument = useStudioAssistDocument({
3595
- documentId,
3596
- schemaType: documentSchemaType
3597
- });
3598
- return useMemo(() => {
3599
- const base = {
3600
- documentId,
3601
- assistableDocumentId,
3602
- documentSchemaType,
3603
- documentIsNew,
3604
- documentIsAssistable,
3605
- openInspector,
3606
- closeInspector,
3607
- inspector,
3608
- documentOnChange,
3609
- selectedPath
3610
- };
3611
- return assistDocument ? {
3612
- ...base,
3613
- loading: !1,
3614
- assistDocument
3615
- } : { ...base, loading: !0, assistDocument: void 0 };
3616
- }, [
3617
- assistDocument,
3618
- documentIsAssistable,
3619
- documentId,
3620
- assistableDocumentId,
3621
- documentSchemaType,
3622
- documentIsNew,
3623
- openInspector,
3624
- closeInspector,
3625
- inspector,
3626
- documentOnChange,
3627
- selectedPath
3628
- ]);
3629
- }
3630
3465
  function useAssistSupported(path, schemaType) {
3631
3466
  return useMemo(() => isAssistSupported(schemaType), [schemaType]);
3632
3467
  }
3633
3468
  const translateActions = {
3634
3469
  name: "sanity-assist-translate",
3635
3470
  useAction(props) {
3636
- var _a, _b, _c, _d, _e, _f, _g, _h;
3637
- const { config, status } = useAiAssistanceConfig(), apiClient = useApiClient(config == null ? void 0 : config.__customApiClient), {
3471
+ const { config, status } = useAiAssistanceConfig(), apiClient = useApiClient(config?.__customApiClient), {
3638
3472
  schemaType: fieldSchemaType,
3639
3473
  path,
3640
3474
  documentId,
3641
3475
  documentSchemaType,
3642
3476
  documentIsAssistable
3643
- } = props, isDocumentLevel = path.length === 0, readOnly = fieldSchemaType.readOnly === !0, docTransTypes = (_b = (_a = config.translate) == null ? void 0 : _a.document) == null ? void 0 : _b.documentTypes, options2 = fieldSchemaType == null ? void 0 : fieldSchemaType.options, addFieldAction = isDocumentLevel || ((_c = options2 == null ? void 0 : options2.aiAssist) == null ? void 0 : _c.translateAction), fieldTransEnabled = addFieldAction && documentSchemaType && ((_f = (_e = (_d = config.translate) == null ? void 0 : _d.field) == null ? void 0 : _e.documentTypes) == null ? void 0 : _f.includes(documentSchemaType.name)), documentTranslationEnabled = addFieldAction && documentSchemaType && (!docTransTypes && isAssistSupported(fieldSchemaType) || (docTransTypes == null ? void 0 : docTransTypes.includes(documentSchemaType.name)));
3477
+ } = props, isDocumentLevel = path.length === 0, readOnly = fieldSchemaType.readOnly === !0, docTransTypes = config.translate?.document?.documentTypes, options2 = fieldSchemaType?.options, addFieldAction = isDocumentLevel || options2?.aiAssist?.translateAction, fieldTransEnabled = addFieldAction && documentSchemaType && config.translate?.field?.documentTypes?.includes(documentSchemaType.name), documentTranslationEnabled = addFieldAction && documentSchemaType && (!docTransTypes && isAssistSupported(fieldSchemaType) || docTransTypes?.includes(documentSchemaType.name));
3644
3478
  if (documentSchemaType && (documentTranslationEnabled || fieldTransEnabled)) {
3645
3479
  const { value: documentValue, onChange: documentOnChange, formState } = useDocumentPane(), docRef = useRef(documentValue);
3646
3480
  docRef.current = documentValue;
@@ -3648,9 +3482,9 @@ const translateActions = {
3648
3482
  formStateRef.current = formState;
3649
3483
  const translationApi = useTranslate(apiClient), translate = useDraftDelayedTask({
3650
3484
  documentOnChange,
3651
- isDocAssistable: documentIsAssistable != null ? documentIsAssistable : !1,
3485
+ isDocAssistable: documentIsAssistable ?? !1,
3652
3486
  task: translationApi.translate
3653
- }), languagePath = (_h = (_g = config.translate) == null ? void 0 : _g.document) == null ? void 0 : _h.languageField, translateDocumentAction = useMemo(() => {
3487
+ }), languagePath = config.translate?.document?.languageField, translateDocumentAction = useMemo(() => {
3654
3488
  if (!languagePath || !documentTranslationEnabled)
3655
3489
  return;
3656
3490
  const title = path.length ? "Translate" : "Translate document";
@@ -3662,7 +3496,7 @@ const translateActions = {
3662
3496
  translationApi.loading || !languagePath || !documentId || translate({
3663
3497
  languagePath,
3664
3498
  translatePath: path,
3665
- documentId: documentId != null ? documentId : "",
3499
+ documentId: documentId ?? "",
3666
3500
  conditionalMembers: formStateRef.current ? getConditionalMembers(formStateRef.current) : []
3667
3501
  });
3668
3502
  },
@@ -3679,7 +3513,7 @@ const translateActions = {
3679
3513
  readOnly
3680
3514
  ]), fieldTranslate = useFieldTranslation(), openFieldTranslation = useDraftDelayedTask({
3681
3515
  documentOnChange,
3682
- isDocAssistable: documentIsAssistable != null ? documentIsAssistable : !1,
3516
+ isDocAssistable: documentIsAssistable ?? !1,
3683
3517
  task: fieldTranslate.openFieldTranslation
3684
3518
  }), translateFieldsAction = useMemo(
3685
3519
  () => fieldTransEnabled ? {
@@ -3708,7 +3542,7 @@ const translateActions = {
3708
3542
  ]
3709
3543
  );
3710
3544
  return useMemo(() => {
3711
- if (status != null && status.initialized)
3545
+ if (status?.initialized)
3712
3546
  return {
3713
3547
  type: "group",
3714
3548
  icon: () => null,
@@ -3723,17 +3557,29 @@ const translateActions = {
3723
3557
  }
3724
3558
  }, ImageContext = createContext({});
3725
3559
  function ImageContextProvider(props) {
3726
- var _a, _b;
3727
- const { schemaType, path, value, readOnly } = props, assetRef = (_a = value == null ? void 0 : value.asset) == null ? void 0 : _a._ref, [assetRefState, setAssetRefState] = useState(assetRef), { documentId, documentSchemaType } = useAssistDocumentContext(), { config, status } = useAiAssistanceConfig(), apiClient = useApiClient(config == null ? void 0 : config.__customApiClient), { generateCaption } = useGenerateCaption(apiClient), { isSyncing } = useSyncState(publicId(documentId), documentSchemaType.name), isShowingOlderRevision = !!((_b = usePaneRouter().params) != null && _b.rev);
3560
+ const { schemaType, path, value, readOnly } = props, assetRef = value?.asset?._ref, {
3561
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
3562
+ // @ts-ignore this is a valid option available in `corel` - Remove after corel is merged to next
3563
+ selectedReleaseId
3564
+ } = useDocumentPane(), [assetRefState, setAssetRefState] = useState(assetRef), { assistableDocumentId, documentSchemaType } = useAssistDocumentContext(), { config, status } = useAiAssistanceConfig(), apiClient = useApiClient(config?.__customApiClient), { generateCaption } = useGenerateCaption(apiClient), { isSyncing } = useSyncState(
3565
+ getPublishedId(assistableDocumentId),
3566
+ documentSchemaType.name,
3567
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
3568
+ // @ts-ignore this is a valid option available in `corel` - Remove after corel is merged to next
3569
+ selectedReleaseId ? { version: selectedReleaseId } : void 0
3570
+ ), isShowingOlderRevision = !!usePaneRouter().params?.rev;
3728
3571
  useEffect(() => {
3729
3572
  const descriptionField = getDescriptionFieldOption(schemaType);
3730
- assetRef && documentId && descriptionField && assetRef !== assetRefState && !isSyncing && !isShowingOlderRevision && !readOnly && (setAssetRefState(assetRef), canUseAssist(status) && generateCaption({ path: pathToString([...path, descriptionField]), documentId }));
3573
+ assetRef && assistableDocumentId && descriptionField && assetRef !== assetRefState && !isSyncing && !isShowingOlderRevision && !readOnly && (setAssetRefState(assetRef), canUseAssist(status) && generateCaption({
3574
+ path: pathToString([...path, descriptionField]),
3575
+ documentId: assistableDocumentId
3576
+ }));
3731
3577
  }, [
3732
3578
  schemaType,
3733
3579
  path,
3734
3580
  assetRef,
3735
3581
  assetRefState,
3736
- documentId,
3582
+ assistableDocumentId,
3737
3583
  generateCaption,
3738
3584
  isSyncing,
3739
3585
  status,
@@ -3753,9 +3599,9 @@ function ImageContextProvider(props) {
3753
3599
  const generateCaptionsActions = {
3754
3600
  name: "sanity-assist-generate-captions",
3755
3601
  useAction(props) {
3756
- const pathKey = usePathKey(props.path), { openInspector } = useDocumentPane(), { config, status } = useAiAssistanceConfig(), apiClient = useApiClient(config == null ? void 0 : config.__customApiClient), { generateCaption, loading } = useGenerateCaption(apiClient), imageContext = useContext(ImageContext);
3757
- if (imageContext && pathKey === (imageContext == null ? void 0 : imageContext.imageDescriptionPath)) {
3758
- const { documentId } = useAssistDocumentContext();
3602
+ const pathKey = usePathKey(props.path), { openInspector } = useDocumentPane(), { config, status } = useAiAssistanceConfig(), apiClient = useApiClient(config?.__customApiClient), { generateCaption, loading } = useGenerateCaption(apiClient), imageContext = useContext(ImageContext);
3603
+ if (imageContext && pathKey === imageContext?.imageDescriptionPath) {
3604
+ const { assistableDocumentId } = useAssistDocumentContext();
3759
3605
  return useMemo(() => ({
3760
3606
  type: "action",
3761
3607
  icon: loading ? () => /* @__PURE__ */ jsx(Box, { style: { height: 17 }, children: /* @__PURE__ */ jsx(Spinner, { style: { transform: "translateY(6px)" } }) }) : ImageIcon,
@@ -3769,31 +3615,39 @@ const generateCaptionsActions = {
3769
3615
  });
3770
3616
  return;
3771
3617
  }
3772
- generateCaption({ path: pathKey, documentId: documentId != null ? documentId : "" });
3618
+ generateCaption({ path: pathKey, documentId: assistableDocumentId });
3773
3619
  }
3774
3620
  },
3775
3621
  renderAsButton: !0,
3776
3622
  disabled: loading,
3777
3623
  hidden: !imageContext.assetRef
3778
- }), [generateCaption, pathKey, documentId, loading, imageContext, status, openInspector]);
3624
+ }), [
3625
+ generateCaption,
3626
+ pathKey,
3627
+ assistableDocumentId,
3628
+ loading,
3629
+ imageContext,
3630
+ status,
3631
+ openInspector
3632
+ ]);
3779
3633
  }
3780
3634
  }
3781
3635
  }, generateImagActions = {
3782
3636
  name: "sanity-assist-generate-image",
3783
3637
  useAction(props) {
3784
- const pathKey = usePathKey(props.path), { config } = useAiAssistanceConfig(), apiClient = useApiClient(config == null ? void 0 : config.__customApiClient), { generateImage, loading } = useGenerateImage(apiClient), imageContext = useContext(ImageContext);
3785
- if (imageContext && pathKey === (imageContext == null ? void 0 : imageContext.imageInstructionPath)) {
3786
- const { documentId } = useAssistDocumentContext();
3638
+ const pathKey = usePathKey(props.path), { config } = useAiAssistanceConfig(), apiClient = useApiClient(config?.__customApiClient), { generateImage, loading } = useGenerateImage(apiClient), imageContext = useContext(ImageContext);
3639
+ if (imageContext && pathKey === imageContext?.imageInstructionPath) {
3640
+ const { assistableDocumentId } = useAssistDocumentContext();
3787
3641
  return useMemo(() => ({
3788
3642
  type: "action",
3789
3643
  icon: loading ? () => /* @__PURE__ */ jsx(Box, { style: { height: 17 }, children: /* @__PURE__ */ jsx(Spinner, { style: { transform: "translateY(6px)" } }) }) : ImageIcon,
3790
3644
  title: "Generate image from prompt",
3791
3645
  onAction: () => {
3792
- loading || generateImage({ path: pathKey, documentId: documentId != null ? documentId : "" });
3646
+ loading || generateImage({ path: pathKey, documentId: assistableDocumentId });
3793
3647
  },
3794
3648
  renderAsButton: !0,
3795
3649
  disabled: loading
3796
- }), [generateImage, pathKey, documentId, loading]);
3650
+ }), [generateImage, pathKey, assistableDocumentId, loading]);
3797
3651
  }
3798
3652
  }
3799
3653
  };
@@ -3813,7 +3667,7 @@ function PrivateIcon() {
3813
3667
  const assistFieldActions = {
3814
3668
  name: "sanity-assist-actions",
3815
3669
  useAction(props) {
3816
- const { schemaType } = props, isDocumentLevel = props.path.length === 0, {
3670
+ const { schemaType } = props, {
3817
3671
  assistDocument,
3818
3672
  documentIsNew,
3819
3673
  documentIsAssistable,
@@ -3822,33 +3676,19 @@ const assistFieldActions = {
3822
3676
  inspector,
3823
3677
  documentOnChange,
3824
3678
  documentSchemaType,
3825
- documentId,
3826
3679
  selectedPath,
3827
3680
  assistableDocumentId
3828
- } = (
3829
- // document field actions do not have access to the document context
3830
- // conditional hook _should_ be safe here since the logical path will be stable
3831
- isDocumentLevel ? (
3832
- // eslint-disable-next-line react-hooks/rules-of-hooks
3833
- useAssistDocumentContextValue(props.documentId, schemaType)
3834
- ) : (
3835
- // eslint-disable-next-line react-hooks/rules-of-hooks
3836
- useAssistDocumentContext()
3837
- )
3838
- ), { value: docValue, formState } = useDocumentPane(), formStateRef = useRef(formState);
3681
+ } = useAssistDocumentContext(), { value: docValue, formState } = useDocumentPane(), formStateRef = useRef(formState);
3839
3682
  formStateRef.current = formState;
3840
- const currentUser = useCurrentUser(), isHidden = !assistDocument, pathKey = usePathKey(props.path), typePath = useTypePath(docValue, pathKey), assistDocumentId2 = assistDocument == null ? void 0 : assistDocument._id, assistableDocId = getAssistableDocId(documentSchemaType, documentId), { requestRunInstruction } = useRequestRunInstruction({
3683
+ const currentUser = useCurrentUser(), isHidden = !assistDocument, pathKey = usePathKey(props.path), typePath = useTypePath(docValue, pathKey), assistDocumentId2 = assistDocument?._id, { requestRunInstruction } = useRequestRunInstruction({
3841
3684
  documentOnChange,
3842
- isDocAssistable: documentIsAssistable != null ? documentIsAssistable : !1
3685
+ isDocAssistable: documentIsAssistable ?? !1
3843
3686
  }), isSelectable = !!useSelectedField(documentSchemaType, typePath), assistSupported = useAssistSupported(props.path, schemaType) && isSelectable && isSchemaAssistEnabled(documentSchemaType) && schemaType.readOnly !== !0, fieldAssist = useMemo(
3844
- () => {
3845
- var _a;
3846
- return ((_a = assistDocument == null ? void 0 : assistDocument.fields) != null ? _a : []).find(
3847
- (f) => f.path === typePath || pathKey === documentRootKey && f.path === pathKey
3848
- );
3849
- },
3850
- [assistDocument == null ? void 0 : assistDocument.fields, pathKey, typePath]
3851
- ), fieldAssistKey = fieldAssist == null ? void 0 : fieldAssist._key, isSelected = (inspector == null ? void 0 : inspector.name) === aiInspectorId && pathKey === selectedPath, imageCaptionAction = generateCaptionsActions.useAction(props), imageGenAction = generateImagActions.useAction(props), translateAction = translateActions.useAction(
3687
+ () => (assistDocument?.fields ?? []).find(
3688
+ (f) => f.path === typePath || pathKey === documentRootKey && f.path === pathKey
3689
+ ),
3690
+ [assistDocument?.fields, pathKey, typePath]
3691
+ ), fieldAssistKey = fieldAssist?._key, isSelected = inspector?.name === aiInspectorId && pathKey === selectedPath, imageCaptionAction = generateCaptionsActions.useAction(props), imageGenAction = generateImagActions.useAction(props), translateAction = translateActions.useAction(
3852
3692
  typed({
3853
3693
  ...props,
3854
3694
  documentId: assistableDocumentId,
@@ -3863,8 +3703,8 @@ const assistFieldActions = {
3863
3703
  [openInspector, closeInspector, isSelected, pathKey]
3864
3704
  ), onInstructionAction = useCallback(
3865
3705
  (instruction2) => {
3866
- !pathKey || !fieldAssistKey || !assistDocumentId2 || !assistableDocId || requestRunInstruction({
3867
- documentId: assistableDocId,
3706
+ !pathKey || !fieldAssistKey || !assistDocumentId2 || !assistableDocumentId || requestRunInstruction({
3707
+ documentId: assistableDocumentId,
3868
3708
  assistDocumentId: assistDocumentId2,
3869
3709
  path: pathKey,
3870
3710
  typePath,
@@ -3872,44 +3712,45 @@ const assistFieldActions = {
3872
3712
  conditionalMembers: formStateRef.current ? getConditionalMembers(formStateRef.current) : []
3873
3713
  });
3874
3714
  },
3875
- [requestRunInstruction, assistableDocId, pathKey, typePath, assistDocumentId2, fieldAssistKey]
3715
+ [
3716
+ requestRunInstruction,
3717
+ assistableDocumentId,
3718
+ pathKey,
3719
+ typePath,
3720
+ assistDocumentId2,
3721
+ fieldAssistKey
3722
+ ]
3876
3723
  ), privateInstructions = useMemo(
3877
- () => {
3878
- var _a;
3879
- return ((_a = fieldAssist == null ? void 0 : fieldAssist.instructions) == null ? void 0 : _a.filter((i) => i.userId && i.userId === (currentUser == null ? void 0 : currentUser.id))) || [];
3880
- },
3881
- [fieldAssist == null ? void 0 : fieldAssist.instructions, currentUser]
3724
+ () => fieldAssist?.instructions?.filter((i) => i.userId && i.userId === currentUser?.id) || [],
3725
+ [fieldAssist?.instructions, currentUser]
3882
3726
  ), sharedInstructions = useMemo(
3883
- () => {
3884
- var _a;
3885
- return ((_a = fieldAssist == null ? void 0 : fieldAssist.instructions) == null ? void 0 : _a.filter((i) => !i.userId)) || [];
3886
- },
3887
- [fieldAssist == null ? void 0 : fieldAssist.instructions]
3727
+ () => fieldAssist?.instructions?.filter((i) => !i.userId) || [],
3728
+ [fieldAssist?.instructions]
3888
3729
  ), instructions = useMemo(
3889
3730
  () => [...privateInstructions, ...sharedInstructions],
3890
3731
  [privateInstructions, sharedInstructions]
3891
- ), runInstructionsGroup = useMemo(() => instructions != null && instructions.length || imageCaptionAction || translateAction || imageGenAction ? {
3732
+ ), runInstructionsGroup = useMemo(() => instructions?.length || imageCaptionAction || translateAction || imageGenAction ? {
3892
3733
  type: "group",
3893
3734
  icon: () => null,
3894
3735
  title: "Run instructions",
3895
3736
  children: [
3896
- ...(instructions == null ? void 0 : instructions.map(
3737
+ ...instructions?.map(
3897
3738
  (instruction2) => instructionItem({
3898
3739
  instruction: instruction2,
3899
- isPrivate: !!(instruction2.userId && instruction2.userId === (currentUser == null ? void 0 : currentUser.id)),
3740
+ isPrivate: !!(instruction2.userId && instruction2.userId === currentUser?.id),
3900
3741
  onInstructionAction,
3901
3742
  hidden: isHidden,
3902
3743
  documentIsNew: !!documentIsNew,
3903
3744
  assistSupported
3904
3745
  })
3905
- )) || [],
3746
+ ) || [],
3906
3747
  imageCaptionAction,
3907
3748
  imageGenAction
3908
3749
  ].filter((a) => !!a),
3909
3750
  expanded: !0
3910
3751
  } : void 0, [
3911
3752
  instructions,
3912
- currentUser == null ? void 0 : currentUser.id,
3753
+ currentUser?.id,
3913
3754
  onInstructionAction,
3914
3755
  isHidden,
3915
3756
  documentIsNew,
@@ -3917,7 +3758,7 @@ const assistFieldActions = {
3917
3758
  imageCaptionAction,
3918
3759
  translateAction,
3919
3760
  imageGenAction
3920
- ]), instructionsLength = (instructions == null ? void 0 : instructions.length) || 0, manageInstructionsItem = useMemo(
3761
+ ]), instructionsLength = instructions?.length || 0, manageInstructionsItem = useMemo(
3921
3762
  () => ({
3922
3763
  type: "action",
3923
3764
  icon: ControlsIcon,
@@ -3976,30 +3817,24 @@ function instructionItem(props) {
3976
3817
  hidden
3977
3818
  };
3978
3819
  }
3979
- function AssistDocumentContextProvider(props) {
3980
- const { documentId, schemaType } = props, value = useAssistDocumentContextValue(documentId, schemaType);
3981
- return /* @__PURE__ */ jsx(AssistDocumentContext.Provider, { value, children: props.children });
3982
- }
3983
3820
  const NO_TASKS = [];
3984
3821
  function useInstructionToaster(documentId, documentSchemaType) {
3985
- const assistDocument = useStudioAssistDocument({ documentId, schemaType: documentSchemaType }), assistDocLoaded = !!assistDocument, currentUser = useCurrentUser(), toast = useToast(), tasks = assistDocument == null ? void 0 : assistDocument.tasks, previousTasks = useRef("initial");
3822
+ const assistDocument = useStudioAssistDocument({ documentId, schemaType: documentSchemaType }), assistDocLoaded = !!assistDocument, currentUser = useCurrentUser(), toast = useToast(), tasks = assistDocument?.tasks, previousTasks = useRef("initial");
3986
3823
  useEffect(() => {
3987
- var _a;
3988
3824
  if (assistDocLoaded) {
3989
3825
  if (previousTasks.current !== "initial") {
3990
3826
  const prevTaskByKey = Object.fromEntries(
3991
- ((_a = previousTasks.current) != null ? _a : NO_TASKS).map((run) => [run._key, run])
3992
- ), endedTasks = tasks == null ? void 0 : tasks.filter((task) => task.startedByUserId === (currentUser == null ? void 0 : currentUser.id)).filter((task) => {
3827
+ (previousTasks.current ?? NO_TASKS).map((run) => [run._key, run])
3828
+ );
3829
+ tasks?.filter((task) => task.startedByUserId === currentUser?.id).filter((task) => {
3993
3830
  const prevTask = prevTaskByKey[task._key];
3994
- return !prevTask && task.ended || !(prevTask != null && prevTask.ended) && task.ended;
3995
- }).filter((task) => task.ended && isAfter(addSeconds(new Date(task.ended), 30), /* @__PURE__ */ new Date()));
3996
- endedTasks == null || endedTasks.forEach((task) => {
3997
- var _a2, _b;
3998
- const title = (_a2 = task.title) != null ? _a2 : getInstructionTitle(task.instruction);
3831
+ return !prevTask && task.ended || !prevTask?.ended && task.ended;
3832
+ }).filter((task) => task.ended && isAfter(addSeconds(new Date(task.ended), 30), /* @__PURE__ */ new Date()))?.forEach((task) => {
3833
+ const title = task.title ?? getInstructionTitle(task.instruction);
3999
3834
  task.reason === "error" ? toast.push({
4000
3835
  title: `Failed: ${title}`,
4001
3836
  status: "error",
4002
- description: `Instruction failed. ${(_b = task.message) != null ? _b : ""}`,
3837
+ description: `Instruction failed. ${task.message ?? ""}`,
4003
3838
  closable: !0,
4004
3839
  duration: 1e4
4005
3840
  }) : task.reason === "timeout" ? toast.push({
@@ -4025,10 +3860,9 @@ function useInstructionToaster(documentId, documentSchemaType) {
4025
3860
  }, [tasks, previousTasks, toast, currentUser, assistDocLoaded]);
4026
3861
  }
4027
3862
  function AssistDocumentInputWrapper(props) {
4028
- var _a;
4029
3863
  if (!isType(props.schemaType, "document") && props.id !== "root" && props.id !== assistFormId)
4030
3864
  return /* @__PURE__ */ jsx(AssistInput, { ...props });
4031
- const documentId = (_a = props.value) == null ? void 0 : _a._id;
3865
+ const documentId = props.value?._id;
4032
3866
  return documentId ? /* @__PURE__ */ jsx(AssistDocumentInput, { ...props, documentId }) : props.renderDefault(props);
4033
3867
  }
4034
3868
  function AssistDocumentInput({ documentId, ...props }) {
@@ -4041,33 +3875,23 @@ function AssistDocumentInput({ documentId, ...props }) {
4041
3875
  name: "document"
4042
3876
  }
4043
3877
  }, [props.schemaType]);
4044
- return /* @__PURE__ */ jsx(FirstAssistedPathProvider, { members: props.members, children: /* @__PURE__ */ jsx(AssistDocumentContextProvider, { schemaType, documentId, children: props.renderDefault({
4045
- ...props,
4046
- schemaType
4047
- }) }) });
3878
+ return /* @__PURE__ */ jsx(FirstAssistedPathProvider, { members: props.members, children: props.renderDefault({ ...props, schemaType }) });
4048
3879
  }
4049
3880
  function AssistInput(props) {
4050
3881
  const { zIndex } = useLayer(), { paneKey } = useDocumentPane(), pathKey = usePathKey(props.path);
4051
3882
  return /* @__PURE__ */ jsx(ConnectFromRegion, { _key: `${paneKey}_${pathKey}`, zIndex, style: { minWidth: 0 }, children: props.renderDefault(props) });
4052
3883
  }
4053
- function createAssistDocumentPresence(documentId, schemaType) {
3884
+ function createAssistDocumentPresence(documentId) {
4054
3885
  return function() {
4055
- return documentId ? /* @__PURE__ */ jsx(AssistDocumentPresence, { documentId, schemaType }) : null;
3886
+ return documentId ? /* @__PURE__ */ jsx(AssistDocumentPresence, {}) : null;
4056
3887
  };
4057
3888
  }
4058
- function AssistDocumentPresence(props) {
4059
- const { assistDocument } = useAssistDocumentContextValue(
4060
- props.documentId,
4061
- props.schemaType
4062
- ), anyPresence = useMemo(() => {
4063
- var _a, _b, _c, _d;
4064
- const anyPresence2 = (_b = (_a = assistDocument == null ? void 0 : assistDocument.tasks) == null ? void 0 : _a.filter((run) => !run.ended && !run.reason)) == null ? void 0 : _b.flatMap((run) => {
4065
- var _a2;
4066
- return (_a2 = run.presence) != null ? _a2 : [];
4067
- }).find((f) => f.started && (/* @__PURE__ */ new Date()).getTime() - new Date(f.started).getTime() < 3e4);
3889
+ function AssistDocumentPresence() {
3890
+ const { assistDocument } = useAssistDocumentContext(), anyPresence = useMemo(() => {
3891
+ const anyPresence2 = assistDocument?.tasks?.filter((run) => !run.ended && !run.reason)?.flatMap((run) => run.presence ?? []).find((f) => f.started && (/* @__PURE__ */ new Date()).getTime() - new Date(f.started).getTime() < 3e4);
4068
3892
  if (anyPresence2)
4069
3893
  return aiPresence(anyPresence2, []);
4070
- const anyRun = (_d = (_c = assistDocument == null ? void 0 : assistDocument.tasks) == null ? void 0 : _c.filter((run) => !run.ended && !run.reason)) == null ? void 0 : _d.find((f) => f.started && (/* @__PURE__ */ new Date()).getTime() - new Date(f.started).getTime() < 3e4);
3894
+ const anyRun = assistDocument?.tasks?.filter((run) => !run.ended && !run.reason)?.find((f) => f.started && (/* @__PURE__ */ new Date()).getTime() - new Date(f.started).getTime() < 3e4);
4071
3895
  return anyRun ? aiPresence(
4072
3896
  {
4073
3897
  started: anyRun.started,
@@ -4077,11 +3901,71 @@ function AssistDocumentPresence(props) {
4077
3901
  },
4078
3902
  []
4079
3903
  ) : void 0;
4080
- }, [assistDocument == null ? void 0 : assistDocument.tasks]);
3904
+ }, [assistDocument?.tasks]);
4081
3905
  return /* @__PURE__ */ jsx(Card, { children: /* @__PURE__ */ jsx(Flex, { flex: 1, justify: "flex-end", children: /* @__PURE__ */ jsx(Flex, { gap: 2, align: "center", children: anyPresence && /* @__PURE__ */ jsx(AiFieldPresence, { presence: anyPresence }) }) }) });
4082
3906
  }
3907
+ function useAssistDocumentContextValue(documentId, documentType) {
3908
+ const schema = useSchema(), documentSchemaType = useMemo(() => {
3909
+ const schemaType = schema.get(documentType);
3910
+ if (!schemaType)
3911
+ throw new Error(`Schema type "${documentType}" not found`);
3912
+ return schemaType;
3913
+ }, [documentType, schema]), {
3914
+ openInspector,
3915
+ closeInspector,
3916
+ inspector,
3917
+ onChange: documentOnChange,
3918
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
3919
+ // @ts-ignore this is a valid option available in `corel` - Remove after corel is merged to next
3920
+ selectedReleaseId,
3921
+ editState
3922
+ } = useDocumentPane(), { draft, published, version } = editState || {};
3923
+ let assistableDocumentId = version?._id || draft?._id || published?._id;
3924
+ assistableDocumentId || (assistableDocumentId = selectedReleaseId ? getVersionId(documentId, selectedReleaseId) : documentSchemaType.liveEdit ? documentId : getDraftId(documentId));
3925
+ const documentIsNew = selectedReleaseId ? !version?._id : !draft?._id && !published?._id, documentIsAssistable = selectedReleaseId ? !!version : isDocAssistable(documentSchemaType, published, draft), { params } = useAiPaneRouter(), selectedPath = params[fieldPathParam], assistDocument = useStudioAssistDocument({
3926
+ documentId: assistableDocumentId,
3927
+ schemaType: documentSchemaType
3928
+ });
3929
+ return useMemo(() => {
3930
+ const base = {
3931
+ assistableDocumentId,
3932
+ documentSchemaType,
3933
+ documentIsNew,
3934
+ documentIsAssistable,
3935
+ openInspector,
3936
+ closeInspector,
3937
+ inspector,
3938
+ documentOnChange,
3939
+ selectedPath
3940
+ };
3941
+ return assistDocument ? {
3942
+ ...base,
3943
+ loading: !1,
3944
+ assistDocument
3945
+ } : { ...base, loading: !0, assistDocument: void 0 };
3946
+ }, [
3947
+ assistDocument,
3948
+ documentIsAssistable,
3949
+ assistableDocumentId,
3950
+ documentSchemaType,
3951
+ documentIsNew,
3952
+ openInspector,
3953
+ closeInspector,
3954
+ inspector,
3955
+ documentOnChange,
3956
+ selectedPath
3957
+ ]);
3958
+ }
3959
+ function AssistDocumentContextProvider(props) {
3960
+ const { documentId, documentType } = props, value = useAssistDocumentContextValue(documentId, documentType);
3961
+ return /* @__PURE__ */ jsx(AssistDocumentContext.Provider, { value, children: props.children });
3962
+ }
3963
+ function AssistDocumentLayout(props) {
3964
+ const { documentId, documentType } = props;
3965
+ return /* @__PURE__ */ jsx(AssistDocumentContextProvider, { documentType, documentId, children: props.renderDefault(props) });
3966
+ }
4083
3967
  const assist = definePlugin((config) => {
4084
- const configWithDefaults = config != null ? config : {};
3968
+ const configWithDefaults = config ?? {};
4085
3969
  return {
4086
3970
  name: packageName,
4087
3971
  schema: {
@@ -4105,7 +3989,10 @@ const assist = definePlugin((config) => {
4105
3989
  if (schemaType === assistDocumentTypeName)
4106
3990
  return [];
4107
3991
  const docSchema = schema.get(schemaType);
4108
- return docSchema && isObjectSchemaType(docSchema) && isSchemaAssistEnabled(docSchema) ? [...prev, createAssistDocumentPresence(documentId, docSchema)] : prev;
3992
+ return docSchema && isObjectSchemaType(docSchema) && isSchemaAssistEnabled(docSchema) ? [...prev, createAssistDocumentPresence(documentId)] : prev;
3993
+ },
3994
+ components: {
3995
+ unstable_layout: AssistDocumentLayout
4109
3996
  }
4110
3997
  },
4111
3998
  studio: {