sanity 6.8.0-next.2 → 6.8.0-next.21

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.
Files changed (141) hide show
  1. package/lib/{AddonDatasetProvider-DKjnqxwO.js → AddonDatasetProvider-Cp0gK33v.js} +2 -2
  2. package/lib/{AddonDatasetProvider-DKjnqxwO.js.map → AddonDatasetProvider-Cp0gK33v.js.map} +1 -1
  3. package/lib/{CalendarFilter-B5Bb9eze.js → CalendarFilter-Cgz5picy.js} +3 -3
  4. package/lib/{CalendarFilter-B5Bb9eze.js.map → CalendarFilter-Cgz5picy.js.map} +1 -1
  5. package/lib/{CommandList-Q4ua5avE.js → CommandList-BeDeX_Tr.js} +23 -6
  6. package/lib/CommandList-BeDeX_Tr.js.map +1 -0
  7. package/lib/{CommentsDocumentLayout-Brt2OR56.js → CommentsDocumentLayout-BJMRXrxl.js} +2 -2
  8. package/lib/{CommentsDocumentLayout-Brt2OR56.js.map → CommentsDocumentLayout-BJMRXrxl.js.map} +1 -1
  9. package/lib/{CommentsField-Cmmta6uT.js → CommentsField-DV6bhirZ.js} +3 -3
  10. package/lib/{CommentsField-Cmmta6uT.js.map → CommentsField-DV6bhirZ.js.map} +1 -1
  11. package/lib/{CommentsInput-C7Kq5XMu.js → CommentsInput-DQ4WCdZJ.js} +5 -5
  12. package/lib/{CommentsInput-C7Kq5XMu.js.map → CommentsInput-DQ4WCdZJ.js.map} +1 -1
  13. package/lib/{CommentsInspector-H5CpN_XH.js → CommentsInspector-PkVZw8uv.js} +5 -5
  14. package/lib/{CommentsInspector-H5CpN_XH.js.map → CommentsInspector-PkVZw8uv.js.map} +1 -1
  15. package/lib/{CommentsListItem-x7FKz_CM.js → CommentsListItem-BjWNEXPU.js} +3 -3
  16. package/lib/{CommentsListItem-x7FKz_CM.js.map → CommentsListItem-BjWNEXPU.js.map} +1 -1
  17. package/lib/{CommentsSelectedPathProvider-Bt8q7wL8.js → CommentsSelectedPathProvider-x5f1q0eW.js} +3 -3
  18. package/lib/{CommentsSelectedPathProvider-Bt8q7wL8.js.map → CommentsSelectedPathProvider-x5f1q0eW.js.map} +1 -1
  19. package/lib/{CommentsStudioLayout-BTJ8Jz1o.js → CommentsStudioLayout-CxZq2lGu.js} +4 -4
  20. package/lib/{CommentsStudioLayout-BTJ8Jz1o.js.map → CommentsStudioLayout-CxZq2lGu.js.map} +1 -1
  21. package/lib/{PaneContainer-D8iNUpZk.js → PaneContainer-B_cWaSSe.js} +8 -8
  22. package/lib/{PaneContainer-D8iNUpZk.js.map → PaneContainer-B_cWaSSe.js.map} +1 -1
  23. package/lib/{PresentationToolGrantsCheck-CxqDuu8I.js → PresentationToolGrantsCheck-CITNu5DG.js} +14 -6
  24. package/lib/PresentationToolGrantsCheck-CITNu5DG.js.map +1 -0
  25. package/lib/{ReleasesMetadataProvider-CZ8jrkBT.js → ReleasesMetadataProvider-CpYsTC5J.js} +2 -2
  26. package/lib/{ReleasesMetadataProvider-CZ8jrkBT.js.map → ReleasesMetadataProvider-CpYsTC5J.js.map} +1 -1
  27. package/lib/{ReleasesNav-BmGRLcrk.js → ReleasesNav-BuqDytPb.js} +59 -19
  28. package/lib/ReleasesNav-BuqDytPb.js.map +1 -0
  29. package/lib/{ReleasesStudioLayout-6V5oDb3h.js → ReleasesStudioLayout-mJZnbUum.js} +8 -8
  30. package/lib/{ReleasesStudioLayout-6V5oDb3h.js.map → ReleasesStudioLayout-mJZnbUum.js.map} +1 -1
  31. package/lib/{ReleasesTool-CMABMGcE.js → ReleasesTool-BFOV2VEc.js} +14 -14
  32. package/lib/{ReleasesTool-CMABMGcE.js.map → ReleasesTool-BFOV2VEc.js.map} +1 -1
  33. package/lib/{SchedulePublishingStudioLayout-BJDA4FBy.js → SchedulePublishingStudioLayout-D2ptE43I.js} +3 -3
  34. package/lib/{SchedulePublishingStudioLayout-BJDA4FBy.js.map → SchedulePublishingStudioLayout-D2ptE43I.js.map} +1 -1
  35. package/lib/{SchedulePublishingUpsellProvider-DfmpnFZz.js → SchedulePublishingUpsellProvider-DvCfqtdZ.js} +2 -2
  36. package/lib/{SchedulePublishingUpsellProvider-DfmpnFZz.js.map → SchedulePublishingUpsellProvider-DvCfqtdZ.js.map} +1 -1
  37. package/lib/{ScheduledPublishingEnabledProvider-C2jEx3t4.js → ScheduledPublishingEnabledProvider-B5yA7hHi.js} +3 -3
  38. package/lib/{ScheduledPublishingEnabledProvider-C2jEx3t4.js.map → ScheduledPublishingEnabledProvider-B5yA7hHi.js.map} +1 -1
  39. package/lib/{SearchProvider-Dk7IfeRS.js → SearchProvider-Cpl3WUyR.js} +25 -25
  40. package/lib/SearchProvider-Cpl3WUyR.js.map +1 -0
  41. package/lib/{SingleDocReleaseLayout-DW02L2zA.js → SingleDocReleaseLayout-CfPCP1Ur.js} +2 -2
  42. package/lib/{SingleDocReleaseLayout-DW02L2zA.js.map → SingleDocReleaseLayout-CfPCP1Ur.js.map} +1 -1
  43. package/lib/{SingleDocReleaseUpsellProvider-9OXN223n.js → SingleDocReleaseUpsellProvider-4ib7kMdI.js} +4 -4
  44. package/lib/{SingleDocReleaseUpsellProvider-9OXN223n.js.map → SingleDocReleaseUpsellProvider-4ib7kMdI.js.map} +1 -1
  45. package/lib/{TasksStudioActiveToolLayout-grF1qQvq.js → TasksStudioActiveToolLayout-lrH8y1Kh.js} +11 -11
  46. package/lib/{TasksStudioActiveToolLayout-grF1qQvq.js.map → TasksStudioActiveToolLayout-lrH8y1Kh.js.map} +1 -1
  47. package/lib/{TasksStudioLayout-Dq72bdM2.js → TasksStudioLayout-CITzoP_1.js} +5 -5
  48. package/lib/{TasksStudioLayout-Dq72bdM2.js.map → TasksStudioLayout-CITzoP_1.js.map} +1 -1
  49. package/lib/{Tool-DNTYDreC.js → Tool-DxqXi1AF.js} +12 -12
  50. package/lib/{Tool-DNTYDreC.js.map → Tool-DxqXi1AF.js.map} +1 -1
  51. package/lib/{UnpublishVersionDialog-B0kX1dt6.js → UnpublishVersionDialog-VZflky9U.js} +4 -4
  52. package/lib/{UnpublishVersionDialog-B0kX1dt6.js.map → UnpublishVersionDialog-VZflky9U.js.map} +1 -1
  53. package/lib/{UpsellDialog-B3IbZqLA.js → UpsellDialog-BmQSjdJg.js} +2 -2
  54. package/lib/{UpsellDialog-B3IbZqLA.js.map → UpsellDialog-BmQSjdJg.js.map} +1 -1
  55. package/lib/{VariantsStudioNavbar-N-cvStJh.js → VariantsStudioNavbar-HsA97lVy.js} +7 -27
  56. package/lib/VariantsStudioNavbar-HsA97lVy.js.map +1 -0
  57. package/lib/{VariantsTool-Bj3RjgBN.js → VariantsTool-rOcVMkln.js} +7 -7
  58. package/lib/{VariantsTool-Bj3RjgBN.js.map → VariantsTool-rOcVMkln.js.map} +1 -1
  59. package/lib/{WorkspaceLoader-BZD0-fj6.js → WorkspaceLoader-kepBjrsn.js} +25 -25
  60. package/lib/{WorkspaceLoader-BZD0-fj6.js.map → WorkspaceLoader-kepBjrsn.js.map} +1 -1
  61. package/lib/_createContext.js +1 -1
  62. package/lib/_singletons.d.ts +1 -1
  63. package/lib/{buildTextSelectionFromFragment-BXiSMql4.js → buildTextSelectionFromFragment-Dj_WBTDa.js} +3 -3
  64. package/lib/{buildTextSelectionFromFragment-BXiSMql4.js.map → buildTextSelectionFromFragment-Dj_WBTDa.js.map} +1 -1
  65. package/lib/{datastores-CFWEadl-.js → datastores-CrRYBoDP.js} +12 -2
  66. package/lib/datastores-CrRYBoDP.js.map +1 -0
  67. package/lib/desk.d.ts +1 -1
  68. package/lib/desk.js +2 -2
  69. package/lib/{index-Dhee2Ms1.d.ts → index-Bic9X2KM.d.ts} +43 -11
  70. package/lib/index.d.ts +2 -2
  71. package/lib/index.js +642 -258
  72. package/lib/index.js.map +1 -1
  73. package/lib/{inputResolver-BHxsuFDP.js → inputResolver-Czq6o5Gh.js} +4 -4
  74. package/lib/{inputResolver-BHxsuFDP.js.map → inputResolver-Czq6o5Gh.js.map} +1 -1
  75. package/lib/{list-CwENPuWS.js → list-BgF8Q_09.js} +2 -2
  76. package/lib/{list-CwENPuWS.js.map → list-BgF8Q_09.js.map} +1 -1
  77. package/lib/{navigation.telemetry-C6drHR5a.js → navigation.telemetry-DSG23KnM.js} +7 -7
  78. package/lib/{navigation.telemetry-C6drHR5a.js.map → navigation.telemetry-DSG23KnM.js.map} +1 -1
  79. package/lib/pane-BXoiwAkI.js +2 -0
  80. package/lib/pane-W85qO-M2.js +2 -0
  81. package/lib/{plugin-Cr5EXfrh.js → plugin-CLeQ5x8I.js} +4 -4
  82. package/lib/{plugin-Cr5EXfrh.js.map → plugin-CLeQ5x8I.js.map} +1 -1
  83. package/lib/{plugin-C1y-_vWr.js → plugin-CgIJubgG.js} +3 -3
  84. package/lib/{plugin-C1y-_vWr.js.map → plugin-CgIJubgG.js.map} +1 -1
  85. package/lib/{plugin-BHRmn24Q.js → plugin-CqWxiAAn.js} +6 -6
  86. package/lib/{plugin-BHRmn24Q.js.map → plugin-CqWxiAAn.js.map} +1 -1
  87. package/lib/{plugin-DkiEMpfN.js → plugin-DkdjF8sO.js} +5 -5
  88. package/lib/{plugin-DkiEMpfN.js.map → plugin-DkdjF8sO.js.map} +1 -1
  89. package/lib/presentation.js +1 -1
  90. package/lib/{scheduleItem-u5-b4stD.js → scheduleItem-CqReiIMI.js} +8 -8
  91. package/lib/{scheduleItem-u5-b4stD.js.map → scheduleItem-CqReiIMI.js.map} +1 -1
  92. package/lib/{schedules-D0WwNN6x.js → schedules-DoZXofxj.js} +3 -3
  93. package/lib/{schedules-D0WwNN6x.js.map → schedules-DoZXofxj.js.map} +1 -1
  94. package/lib/structure.js +2 -2
  95. package/lib/{structureTool-BCCGiqpF.js → structureTool-By2eJI8F.js} +60 -49
  96. package/lib/structureTool-By2eJI8F.js.map +1 -0
  97. package/lib/{structureTool-B5ch7u4I.js → structureTool-UGWPEr2I.js} +6 -6
  98. package/lib/{structureTool-B5ch7u4I.js.map → structureTool-UGWPEr2I.js.map} +1 -1
  99. package/lib/{studioClient-DvoDxN44.js → studioClient-DqAy4dnu.js} +2 -2
  100. package/lib/{studioClient-DvoDxN44.js.map → studioClient-DqAy4dnu.js.map} +1 -1
  101. package/lib/{useBundleDocuments-CWvP-dZI.js → useBundleDocuments-Dyop3VGZ.js} +15 -13
  102. package/lib/useBundleDocuments-Dyop3VGZ.js.map +1 -0
  103. package/lib/{useComments-KoRXRvW7.js → useComments-CzNBSPgQ.js} +3 -3
  104. package/lib/{useComments-KoRXRvW7.js.map → useComments-CzNBSPgQ.js.map} +1 -1
  105. package/lib/{useCommentsTelemetry-LlKtxi5d.js → useCommentsTelemetry-CkplhYJa.js} +3 -3
  106. package/lib/{useCommentsTelemetry-LlKtxi5d.js.map → useCommentsTelemetry-CkplhYJa.js.map} +1 -1
  107. package/lib/{useDocumentPreviewValues-DcVumcdT.js → useDocumentPreviewValues-BPzq1mWh.js} +3 -3
  108. package/lib/{useDocumentPreviewValues-DcVumcdT.js.map → useDocumentPreviewValues-BPzq1mWh.js.map} +1 -1
  109. package/lib/{useFeatureEnabled-D7BsN6xF.js → useFeatureEnabled-B_ywe2up.js} +2 -2
  110. package/lib/{useFeatureEnabled-D7BsN6xF.js.map → useFeatureEnabled-B_ywe2up.js.map} +1 -1
  111. package/lib/{useFieldActions-NrjLdjo8.js → useFieldActions-DbRTTr6-.js} +2 -2
  112. package/lib/{useFieldActions-NrjLdjo8.js.map → useFieldActions-DbRTTr6-.js.map} +1 -1
  113. package/lib/{useReleasesToolAvailable-Cki52QI6.js → useReleasesToolAvailable-CUvya3HF.js} +3 -3
  114. package/lib/{useReleasesToolAvailable-Cki52QI6.js.map → useReleasesToolAvailable-CUvya3HF.js.map} +1 -1
  115. package/lib/{useScheduledDraftMenuActions-DIa5I8rU.js → useScheduledDraftMenuActions-BBEMJkNE.js} +5 -5
  116. package/lib/{useScheduledDraftMenuActions-DIa5I8rU.js.map → useScheduledDraftMenuActions-BBEMJkNE.js.map} +1 -1
  117. package/lib/{useSetVariant-MvLHJC9A.js → useSetVariant-Cz8brFbQ.js} +3 -3
  118. package/lib/{useSetVariant-MvLHJC9A.js.map → useSetVariant-Cz8brFbQ.js.map} +1 -1
  119. package/lib/{useStudioUrl-DN_xMGIS.js → useStudioUrl-DFAbTA0R.js} +5 -5
  120. package/lib/{useStudioUrl-DN_xMGIS.js.map → useStudioUrl-DFAbTA0R.js.map} +1 -1
  121. package/lib/{useTimeZone-B5fBFjsR.js → useTimeZone-CNjAZCdC.js} +2 -2
  122. package/lib/{useTimeZone-B5fBFjsR.js.map → useTimeZone-CNjAZCdC.js.map} +1 -1
  123. package/lib/{userComponent-BQj9BWzn.js → userComponent-MPULaxdQ.js} +2 -2
  124. package/lib/{userComponent-BQj9BWzn.js.map → userComponent-MPULaxdQ.js.map} +1 -1
  125. package/lib/{validationUtils-RTzFL-p1.js → validationUtils-C9y0bJZd.js} +4 -4
  126. package/lib/{validationUtils-RTzFL-p1.js.map → validationUtils-C9y0bJZd.js.map} +1 -1
  127. package/lib/{version-CY300aPw.js → version-BZCsk4ue.js} +2 -2
  128. package/lib/{version-CY300aPw.js.map → version-BZCsk4ue.js.map} +1 -1
  129. package/package.json +12 -11
  130. package/lib/CommandList-Q4ua5avE.js.map +0 -1
  131. package/lib/Delay-DjgiAi06.js +0 -21
  132. package/lib/Delay-DjgiAi06.js.map +0 -1
  133. package/lib/PresentationToolGrantsCheck-CxqDuu8I.js.map +0 -1
  134. package/lib/ReleasesNav-BmGRLcrk.js.map +0 -1
  135. package/lib/SearchProvider-Dk7IfeRS.js.map +0 -1
  136. package/lib/VariantsStudioNavbar-N-cvStJh.js.map +0 -1
  137. package/lib/datastores-CFWEadl-.js.map +0 -1
  138. package/lib/pane-CEegQ2Kh.js +0 -2
  139. package/lib/pane-DHrjuFiG.js +0 -2
  140. package/lib/structureTool-BCCGiqpF.js.map +0 -1
  141. package/lib/useBundleDocuments-CWvP-dZI.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"datastores-CFWEadl-.js","names":["Schema","useSource","useSchema","schema","useSource","Template","useTemplates","templates","isRecord","value","Record","Boolean","Array","isArray","MAX_DOCUMENT_ID_CHUNK_SIZE","QuickLRU","concat","defer","EMPTY","map","Observable","of","OperatorFunction","tap","SWRCache","get","key","T","has","set","value","delete","createSWRCache","createLRUCache","createSWR","options","maxSize","cache","rxSwr","fromCache","input$","pipe","result","lru","entry","Error","WarningOutlineIcon","PreviewValue","INCLUDE_FIELDS_QUERY","INCLUDE_FIELDS","LISTENER_RESET_DELAY","AVAILABILITY_READABLE","available","reason","const","AVAILABILITY_PERMISSION_DENIED","AVAILABILITY_NOT_FOUND","AVAILABILITY_VERSION_DELETED","INVALID_PREVIEW_FALLBACK","title","subtitle","media","DOCUMENT_SYSTEM_FIELD","Observable","Subscriber","isNonNullable","QueueItem","args","observer","completed","debounceCollect","fn","Fn","wait","collectedArgs","TArgs","TReturnValue","timer","ReturnType","setTimeout","queue","Record","idx","debounced","obs","clearTimeout","flush","queueItem","id","currentlyFlushingQueue","queueItemIds","Object","keys","filter","length","map","subscribe","next","results","forEach","result","i","complete","entry","error","err","Error","SanityClient","StackablePerspective","flatten","keyBy","combineLatest","defer","from","Observable","of","distinctUntilChanged","map","mergeMap","reduce","switchMap","shallowEquals","MAX_DOCUMENT_ID_CHUNK_SIZE","getDraftId","getPublishedId","getVersionId","isRecord","createSWR","AVAILABILITY_NOT_FOUND","AVAILABILITY_PERMISSION_DENIED","AVAILABILITY_READABLE","AVAILABILITY_VERSION_DELETED","AvailabilityResponse","DocumentAvailability","DocumentStackAvailability","DraftsModelDocumentAvailability","ObservePathsFn","debounceCollect","swr","maxSize","chunkDocumentIds","documentIds","chunk","chunkSize","chunks","documentId","length","push","includes","mutConcat","array","T","createDocumentAvailabilityObserver","versionedClient","observePaths","id","fetchDocumentReadability","args","uniqueIds","Set","pipe","fetchDocumentReadabilityChunked","res","indexOf","ids","requestOptions","uri","getDataUrl","join","json","query","excludeContent","tag","observable","request","response","omitted","entry","omittedEntry","reason","Error","observeDocumentAvailability","_id","hasRev","Boolean","_rev","isDeleted","_system","delete","ev","value","ensurePublished","stack","concat","createDocumentStackAvailabilityObserver","perspective","versionId","availability","createPreviewAvailabilityObserver","observeDocumentPairAvailability","version","draftId","publishedId","undefined","draftReadability","publishedReadability","versionReadability","draft","published","finalize","merge","MonoTypeOperatorFunction","Observable","share","ShareConfig","tap","ShareReplayLatestConfig","T","predicate","value","shareReplayLatest","config","configOrPredicate","_shareReplayLatest","source","latest","emitted","shareConfig","wrapped","pipe","undefined","emitLatest","subscriber","next","complete","SanityClient","timer","LISTENER_RESET_DELAY","shareReplayLatest","createGlobalListener","client","listen","events","includeResult","includePreviousRevision","includeMutations","includeAllVersions","visibility","effectFormat","tag","pipe","predicate","event","type","resetOnRefCountZero","SanityDocument","applyPatch","RawPatch","omitRev","document","undefined","_rev","doc","applyMendozaPatch","T","patch","baseRev","Error","next","applyMutationEventEffects","event","effects","apply","previousRev","resultRev","MutationEvent","SanityClient","WelcomeEvent","SanityDocument","memoize","uniq","RawPatch","EMPTY","finalize","Observable","of","concatMap","map","scan","shareReplay","applyMutationEventEffects","debounceCollect","ListenerMutationEventLike","Pick","effects","apply","ObserveDocumentAPIConfig","dataset","projectId","apiVersion","createObserveDocument","mutationChannel","client","getBatchFetcher","apiConfig","_client","withConfig","batchFetchDocuments","ids","observable","fetch","flat","tag","pipe","result","id","find","r","_id","MEMO","Record","observeDocument","_apiConfig","config","fetchDocument","event","type","document","const","documentId","current","applyMutationEvent","Error","undefined","memoizedObserveDocument","key","JSON","stringify","bufferSize","refCount","previousRev","_rev","console","warn","resultRev","keysOf","value","T","Object","keys","combineLatest","from","observableFrom","isObservable","Observable","of","observableOf","map","mergeAll","scan","switchMap","keysOf","setKey","source","Record","key","value","Props","K","T","props","options","wait","observer","subscribe","pipe","object","keyObservables","val","pairs","reduce","acc","StackablePerspective","isCrossDatasetReference","isReference","uniq","Observable","of","observableOf","distinctUntilChanged","switchMap","isRecord","ApiConfig","FieldName","Previewable","PreviewPath","props","createEmpty","fields","reduce","result","Record","field","undefined","resolveMissingHeads","value","paths","filter","path","getDocumentId","_ref","_id","ObserveFieldsFn","id","apiConfig","perspective","observePaths","observeFields","currentValue","_type","_weak","_dataset","_projectId","_strengthenOnPublish","pathsWithMissingHeads","length","nextHeads","map","refApiConfig","projectId","dataset","pipe","prev","curr","_rev","snapshot","leads","forEach","head","tail","push","next","Object","keys","res","tails","Array","isArray","wait","normalizePaths","segment","split","createPathObserver","options","PreviewableType","PreviewPath","DEFAULT_PREVIEW_PATHS","getPreviewPaths","preview","selection","select","undefined","paths","Object","values","map","value","String","split","concat","isPortableTextSpan","isPortableTextTextBlock","PortableTextBlock","isPortableTextPreviewValue","value","Array","isArray","length","some","extractTextFromBlocks","blocks","firstBlock","find","children","filter","map","span","text","join","isTitledListValue","PrepareViewOptions","PreviewValue","SchemaType","TitledListValue","debounce","flatten","get","isPlainObject","pick","uniqBy","isRecord","INVALID_PREVIEW_FALLBACK","PreviewableType","keysOf","extractTextFromBlocks","isPortableTextPreviewValue","PRESERVE_KEYS","EMPTY","SelectedValue","Record","PrepareInvocationResult","selectedValue","returnValue","errors","Error","errorCollector","errorsByType","error","type","value","add","typeName","name","push","getAll","clear","reportErrors","uniqueErrors","Object","keys","map","entries","entry","message","errorCount","length","console","groupCollapsed","forEach","first","group","preview","uniqued","hasPrepare","prepare","log","groupEnd","isRenderable","fieldName","assignType","inspect","FIELD_NAME_VALIDATORS","media","title","subtitle","description","imageUrl","date","val","prefixType","ellipse","prefix","slice","join","Array","isArray","v","validateFieldValue","fieldValue","validator","assign","validatePreparedValue","preparedValue","reduce","acc","validateReturnedPreview","result","defaultPrepare","invokePrepare","viewOptions","withErrors","EnumListOptions","list","hasEnumListOptions","options","listOptions","getListOptions","undefined","option","prepareForPreview","rawValue","_createdAt","_updatedAt","hasCustomPrepare","selection","select","targetKeys","key","typeWithFields","targetFieldName","valueField","fields","find","f","selectedOption","opt","prepareResult","returnValueResult","StackablePerspective","isCrossDatasetReference","isCrossDatasetReferenceSchemaType","isReferenceSchemaType","PrepareViewOptions","isPlainObject","Observable","of","map","switchMap","ObserveForPreviewFn","ApiConfig","ObserveDocumentTypeFromIdFn","ObservePathsFn","PreparedSnapshot","Previewable","PreviewableType","getPreviewPaths","invokePrepare","prepareForPreview","isRecord","value","Record","isReference","_ref","createPreviewObserver","context","observeDocumentTypeFromId","observePaths","observeForPreview","type","options","viewOptions","apiConfig","perspective","snapshot","undefined","refApiConfig","projectId","_projectId","dataset","_dataset","pipe","typeName","refType","to","find","toType","name","paths","preview","returnValue","SanityDocument","combineLatest","Observable","of","map","switchMap","getIdPair","isRecord","DraftsModelDocument","ObserveDocumentAvailabilityFn","ObservePathsFn","PreviewPath","createObservePathsDocumentPair","options","observeDocumentPairAvailability","observePaths","id","paths","T","ALWAYS_INCLUDED_SNAPSHOT_PATHS","observePathsDocumentPair","version","draftId","publishedId","versionId","pipe","availability","draft","available","published","type","snapshot","undefined","snapshotPaths","_type","_ref","draftSnapshot","publishedSnapshot","versionSnapshot","QueryParams","SanityClient","sortedIndex","of","distinctUntilChanged","filter","map","mergeMap","scan","tap","SourceClientOptions","versionedClient","DocumentIdSetObserverState","status","documentIds","LiveDocumentIdSetOptions","insert","apiVersion","createDocumentIdSetObserver","client","observe","queryFilter","params","options","insertOption","query","fetchFilter","observable","fetch","tag","pipe","result","Array","isArray","Error","listen","visibility","events","includeResult","includeMutations","includeAllVersions","event","type","const","state","transition","documentId","id","undefined","array","T","element","strategy","index","length","toSpliced","ClientPerspective","SourceClientOptions","RELEASES_STUDIO_CLIENT_OPTIONS","apiVersion","isReleasePerspective","perspective","Array","isArray","hasEqualFields","fields","object","Record","otherObject","every","field","id","value","T","ItemSelector","element","isUniqueBy","array","Array","itemSelector","prevItem","currItem","i","length","SearchPathSegment","GROQ_KEYWORDS","VALID_FIELD","fieldNeedsEscape","fieldName","test","includes","escapeField","escapeFirst","isEmptyArray","value","Array","isArray","length","joinPath","pathArray","path","i","pathSegment","isFirst","needsEscape","identity","sortBy","values","escapeField","fieldNeedsEscape","INCLUDE_FIELDS_QUERY","FieldName","Id","Selection","CombinedSelection","ids","fields","map","Doc","_id","Result","combineSelections","selections","reduce","output","key","id","index","join","idx","length","stringifyId","JSON","stringify","maybeEscape","fieldName","toSubQuery","allFields","toQuery","combinedSelections","reassemble","queryResult","reprojected","subResult","forEach","resultIdx","i","found","find","doc","SanityClient","StackablePerspective","difference","flatten","memoize","combineLatest","concat","defer","EMPTY","from","fromEvent","merge","Observable","of","retry","timer","distinctUntilChanged","filter","map","mergeMap","reduce","share","shareReplay","startWith","switchMap","tap","RELEASES_STUDIO_CLIENT_OPTIONS","versionedClient","MAX_DOCUMENT_ID_CHUNK_SIZE","getPublishedId","idMatchesPerspective","isVersionId","INCLUDE_FIELDS","ApiConfig","FieldName","Id","InvalidationChannelEvent","Selection","debounceCollect","hasEqualFields","isUniqueBy","CombinedSelection","combineSelections","reassemble","toQuery","chunkCombinedSelections","combinedSelections","chunks","selection","chunk","chunkMap","chunkSize","i","ids","length","id","idSize","push","fields","CachedFieldObserver","changes$","Cache","ClientLike","withConfig","config","observable","fetch","query","params","Record","options","tag","createObserveFields","client","invalidationChannel","currentDatasetClient","fetchAllDocumentPathsWith","perspective","fetchAllDocumentPath","selections","useReleaseVersion","some","apiClient","apiVersion","undefined","selectionChunks","fetchChunk","pipe","delay","_","attempt","Math","min","result","totalSelections","merged","chunkResults","forEach","idx","Array","fill","batchFetchersCache","Map","getBatchFetchersForPerspective","key","join","has","get","batchFetchers","fast","slow","set","currentDatasetListenFields","documentId","fetchDocumentPathsFast","fetchDocumentPathsSlow","hasPerspective","fetchId","event","type","visibility","CACHE","getBatchFetcherForDataset","apiConfig","fetchAll","dataset","projectId","CROSS_DATASET_PREVIEW_POLL_INTERVAL","visiblePoll$","document","visibilityState","visible","crossDatasetListenFields","batchFetcher","createCachedFieldObserver","latest","T","v","refCount","bufferSize","cachedObserveFields","cacheKey","existingObservers","missingFields","cachedFieldObserver","cachedFieldObservers","observer","fieldName","includes","cached","snapshots","Boolean","snapshot","_rev","pickFrom","objects","value","getFirstFieldValue","object","SanityClient","isEqual","concat","from","Observable","of","OperatorFunction","retry","Subject","timer","bufferWhen","distinctUntilChanged","filter","finalize","map","mergeMap","shareReplay","switchMap","tap","toArray","RELEASES_STUDIO_CLIENT_OPTIONS","versionedClient","MAX_DOCUMENT_ID_CHUNK_SIZE","getPublishedId","InvalidationChannelEvent","debounceCollect","VERSION_OF_QUERY_OVERHEAD","length","MAX_CONCURRENT_BATCH_FETCHES","createObserveVersionDocumentIds","options","client","invalidationChannel","documentGroupId","releasesClient","apiVersion","fetchFast","collectedArgs","fetchVersionIdSets","fetchSlow","cache","Map","observeVersionDocumentIds","cachedInstance","get","instance","pipe","event","type","documentId","visibility","ids","maybeIndexPending","includes","delete","refCount","bufferSize","set","bufferByByteSize","byteSize","value","Type","maxBytes","source","closeBuffer","bufferedBytes","size","next","buildQuery","documentGroupIds","subQueries","id","JSON","stringify","join","fetchBatch","observable","fetch","tag","delay","_","attempt","Math","min","result","versionIds","sort","batch","index","settled","a","b","flatMap","MutationEvent","QueryParams","SanityClient","StackablePerspective","WelcomeEvent","DocumentSystem","PrepareViewOptions","SanityDocument","combineLatest","Observable","distinctUntilChanged","filter","map","isRecord","createDocumentStackAvailabilityObserver","createPreviewAvailabilityObserver","DOCUMENT_SYSTEM_FIELD","createGlobalListener","createObserveDocument","ObserveDocumentAPIConfig","createPathObserver","createPreviewObserver","createObservePathsDocumentPair","createDocumentIdSetObserver","DocumentIdSetObserverState","createObserveFields","createObserveVersionDocumentIds","ApiConfig","DocumentStackAvailability","DraftsModelDocument","DraftsModelDocumentAvailability","ObservePathsFn","PreparedSnapshot","Previewable","PreviewableType","PreviewPath","ObserveForPreviewFn","value","type","options","viewOptions","perspective","apiConfig","DocumentPreviewStore","observePaths","observeForPreview","observeDocumentTypeFromId","id","observeDocumentSystemFromId","unstable_observeDocumentPairAvailability","version","unstable_observeDocumentStackAvailability","perspectiveStack","unstable_observePathsDocumentPair","paths","T","unstable_observeDocumentIdSet","params","insert","apiVersion","unstable_observeVersionDocumentIds","publishedId","unstable_observeDocument","clientConfig","unstable_observeDocuments","ids","DocumentPreviewStoreOptions","client","createDocumentPreviewStore","versionedClient","withConfig","globalListener","pipe","event","invalidationChannel","const","observeDocument","mutationChannel","observeFields","_type","_ref","res","undefined","observeDocumentIdSet","observeVersionDocumentIds","observeDocumentStackAvailability","observeDocumentPairAvailability","observePathsDocumentPair","ClientError","isUnauthorizedError","err","statusCode","INVALID_SESSION_ERROR_CODES","isInvalidSessionError","code","getApiErrorCode","undefined","includes","fromResponse","readErrorCode","response","body","JSON","parse","responseBody","value","errorCode","ClientError","ServerError","isNativeNetworkError","getApiErrorCode","isInvalidSessionError","isUnauthorizedError","isTimeoutError","error","Error","code","isNetworkError","parseRetryAfter","err","headers","response","Record","value","undefined","test","trim","seconds","Number","isFinite","Math","ceil","dateMs","Date","parse","delta","now","RequestErrorClassification","type","retryAfterSeconds","classifyRequestError","statusCode","ConfigErrorClassification","NotFoundBody","attributes","notFoundBody","body","classifyConfigError","isClientRequestError","BehaviorSubject","isObservable","lastValueFrom","Observable","classifyRequestError","isInvalidSessionError","RequestErrorChannel","RequestErrorClaim","RequestErrorReportOptions","StudioErrorHandler","projectIdFromError","err","Error","url","response","request","undefined","host","URL","hostname","match","ParkedEntry","retry","createRequestErrorChannel","claimSubject","parked","tryClaim","options","entry","push","getValue","type","next","error","projectId","classification","retryable","Boolean","entries","handle","Promise","attempt","thunk","attemptNumber","PromiseLike","T","resolve","reject","tryOnce","then","n","result","claim$","asObservable","passthroughErrorHandler","useContext","StudioErrorHandlerContext","passthroughErrorHandler","StudioErrorHandler","useStudioErrorHandler","createNode","FrameMessages","WindowMessages","CapabilityRecord","ComlinkStore","Options","capabilities","SDK_CHANNEL_NAME","SDK_NODE_NAME","createComlinkStore","comlink","node","name","connectTo","start","Observable","OperatorFunction","catchError","tap","Selector","error","attemptNo","caught","T","K","catchWithCount","selector","input$","successiveErrorsCount","errorOp","err","pipe","BifurClient","observableCallback","concat","fromEvent","merge","NEVER","Observable","of","throwError","timer","map","mergeMapTo","startWith","take","takeUntil","catchWithCount","ConnectionStatusStore","connectionStatus$","ConnectionStatus","onOnline$","window","onOffline$","expBackoff","retryCount","Math","pow","ConnectingStatus","type","ErrorStatus","error","Error","attemptNo","isOffline","retryAt","Date","RetryingStatus","ConnectedStatus","lastHeartbeat","CONNECTING","_callback","onRetry$","onRetry","createErrorStatus","ConnectionStatusStoreOptions","bifur","createConnectionStatusStore","heartbeats","pipe","ts","successiveErrorsCount","caught","timeUntilRetry","min","getTime","expiry$","navigator","onLine","initialErrorStatus","triggerRetry$","defineEvent","DocumentDesynced","errorName","name","version","description","defineEvent","DocumentPairLoadingMeasuredData","durationMs","fromCache","hasPublished","hasDraft","hasVersion","DocumentPairLoadingMeasured","name","version","description","maxSampleRate","defineEvent","DocumentRebaseOccurred","remoteMutationCount","localMutationCount","name","version","description","defineEvent","Samples","latency","transactionId","shard","HighListenerLatencyOccurred","name","version","description","defineEvent","MutationPerformanceMeasured","transactionId","debounceMs","apiMs","callbackMs","shard","name","version","description","isDraftId","isVersionId","DocumentVariantType","getDocumentVariantType","documentId","BufferedDocument","Mutation","SanityDocument","BehaviorSubject","EMPTY","merge","Observable","Subject","distinctUntilChanged","filter","map","mergeMapTo","publishReplay","refCount","scan","share","take","tap","withLatestFrom","ListenerEvent","MutationEvent","DocumentMutationEvent","DocumentRebaseEvent","DocumentRemoteMutationEvent","MutationPayload","RemoteSnapshotEvent","SnapshotEvent","MutationAction","type","mutations","CommitAction","Action","CommitRequest","mutation","success","failure","error","Error","cancel","firstMutationReceivedAt","getUpdatedSnapshot","bufferedDocument","LOCAL","HEAD","document","_type","_rev","_updatedAt","Date","toISOString","toSnapshotEvent","getDocument","event","T","createObservableBufferedDocument","listenerEvent$","actions$","consistency$","mutations$","rebase$","remoteMutations","commitRequests","createInitialBufferedDocument","initialSnapshot","onMutation","remote","next","origin","onRemoteMutation","head","transactionId","timestamp","author","identity","effects","onRebase","edge","nextRemoteMutations","localMutations","onConsistencyChanged","isConsistent","undefined","now","commitHandler","commitArg","captured","currentBufferedDocument$","pipe","listenerEvent","commit","console","warn","NonNullable","snapshotAfterSync$","ev","mutationEvent","arrive","actionHandler$","action","add","emitAction","addMutations","addMutation","subscribe","snapshot$","remoteSnapshot$","updates$","commitRequest$","SanityDocument","Observable","ListenerEvent","CommitRequest","createObservableBufferedDocument","CommittedEvent","DocumentMutationEvent","DocumentRebaseEvent","MutationPayload","RemoteSnapshotEvent","SnapshotEvent","BufferedDocumentEvent","prepare","id","document","Partial","_id","_rev","_updatedAt","rest","BufferedDocumentWrapper","consistency$","remoteSnapshot$","events","commitRequest$","patch","patches","create","createIfNotExists","createOrReplace","delete","mutate","mutations","commit","createBufferedDocument","documentId","listenerEvent$","bufferedDocument","prepareDoc","DELETE","updates$","map","addMutations","createDebug","debug","TTLCache","MonoTypeOperatorFunction","Observable","mergeMap","scan","debug","ListenerEvent","DEFAULT_TTL","DEFAULT_MAX_ENTRIES","dedupeListenerEvents","ttl","max","T","input$","pipe","seen","emit","event","type","key","transactionId","documentId","has","set","state","MutationEvent","discardChainTo","chain","revision","revisionIndex","findIndex","event","resultRev","split","array","T","index","slice","toOrderedChains","previousRev","events","parents","Record","forEach","find","other","orphans","Object","entries","filter","parent","map","orphan","headRev","current","sortedList","push","partition","concat","Observable","of","switchMap","throwError","timer","mergeMap","scan","debug","ListenerEvent","MutationEvent","discardChainTo","toOrderedChains","ListenerSequenceState","base","revision","emitEvents","buffer","DEFAULT_MAX_BUFFER_SIZE","DEFAULT_DEADLINE_MS","EMPTY_ARRAY","sequentializeListenerEvents","options","maxBufferSize","resolveChainDeadline","input$","pipe","state","event","type","Error","document","_rev","orderedChains","map","chain","discarded","rest","length","resolvedChains","_nextBuffer","previousRev","nextBuffer","flat","toSorted","a","b","messageReceivedAt","localeCompare","lastMutation","at","nextBaseRevision","transition","undefined","resultRev","MaxBufferExceededError","brokenChainStartsAt","Date","nextDeadline","now","getTime","DeadlineExceededError","OutOfSyncError","constructor","message","name","SanityClient","SanityDocument","groupBy","defer","merge","Observable","of","throwError","catchError","concatMap","filter","map","mergeMap","scan","share","shareReplayLatest","RELEASES_STUDIO_CLIENT_OPTIONS","getVersionFromId","StoreRequestErrorHandler","debug","IdPair","MutationEvent","PendingMutationsEvent","ReconnectEvent","ResetEvent","WelcomeBackEvent","WelcomeEvent","dedupeListenerEvents","OutOfSyncError","sequentializeListenerEvents","Snapshots","draft","published","version","InitialSnapshotEvent","type","documentId","document","LatencyReportEvent","shard","latencyMs","transactionId","DocumentPairLoadedEvent","durationMs","fromCache","hasPublished","hasDraft","hasVersion","MutationPerformanceEvent","debounceMs","apiMs","callbackMs","DocumentRebaseTelemetryEvent","remoteMutationCount","localMutationCount","DocumentStoreExtraOptions","tag","snapshotFetchErrorHandler","onSyncErrorRecovery","error","onReportLatency","event","onSlowCommit","onDocumentPairLoaded","onReportMutationPerformance","onDocumentRebase","ListenerEvent","PENDING_START","phase","PENDING_END","isMutationEvent","msg","isMultiTransactionEvent","transactionTotalEvents","allPendingTransactionEventsReceived","listenerEvents","groupedMutations","ev","e","Object","values","every","mutations","length","getPairListener","_client","idPair","options","publishedId","draftId","versionId","client","withConfig","Error","sharedEvents","observable","listen","ids","id","includeResult","includeAllVersions","enableResume","events","effectFormat","pipe","messageReceivedAt","Date","toString","predicate","pairEvents$","shouldSyncDocument","fetchInitialDocumentSnapshots","createSnapshotEvent","acc","next","buffer","isBuffering","isMulti","concat","nextBuffer","v","draftEvents$","publishedEvents$","versionEvents$","err","caught$","name","console","fetchDocuments","getDocuments","attempt","retryable","SanityClient","RELEASES_STUDIO_CLIENT_OPTIONS","IdPair","ACTIONS_API_MINIMUM_VERSION","actionsApiClient","client","idPair","versionId","withConfig","apiVersion","SanityClient","RELEASES_STUDIO_CLIENT_OPTIONS","IdPair","operationsApiClient","client","idPair","versionId","withConfig","Action","MultipleActionResult","SanityClient","SingleMutationResult","Mutation","SanityDocument","omit","combineLatest","defer","EMPTY","from","merge","Observable","of","timer","catchError","distinctUntilChanged","filter","map","mergeMap","scan","share","shareReplay","startWith","switchMap","takeUntil","tap","withLatestFrom","isInvalidSessionError","DocumentVariantType","BufferedDocumentEvent","createBufferedDocument","CommitRequest","DocumentRebaseEvent","MutationPayload","RemoteSnapshotEvent","DocumentStoreExtraOptions","getPairListener","InitialSnapshotEvent","LatencyReportEvent","ListenerEvent","MutationPerformanceEvent","IdPair","MutationEvent","PendingMutationsEvent","ReconnectEvent","ResetEvent","WelcomeBackEvent","WelcomeEvent","actionsApiClient","operationsApiClient","FETCH_SHARD_TIMEOUT","PENDING_ENTRY_TTL","SLOW_COMMIT_TIMEOUT_MS","isMutationEventForDocId","id","event","type","documentId","WithVersion","T","version","DocumentVersionEvent","RemoteSnapshotVersionEvent","MutationResult","Omit","DocumentVersion","consistency$","remoteSnapshot$","events","patch","patches","create","document","Partial","createIfNotExists","createOrReplace","delete","mutate","mutations","commit","CommitError","error","Pair","transactionsPendingEvents$","commitError$","published","draft","setVersion","ev","requireId","_id","_type","value","Error","isLiveEditMutation","mutationParams","publishedId","resultRev","mutation","patchTargets","flatMap","mut","mutationPayloads","Object","values","length","every","target","toActions","idPair","actions","actionType","attributes","ifExists","draftId","versionId","unset","commitActions","client","commitMutations","observable","action","tag","transactionId","Promise","dataRequest","visibility","returnDocuments","skipCrossDatasetReferenceValidation","TERMINAL_COMMIT_STATUSES","Set","CommitAttemptResult","result","_perfTimings","PerfTimings","submitCommitRequest","request","params","pipe","next","success","statusCode","undefined","has","cancel","failure","firstMutationReceivedAt","apiRequestSentAt","apiResponseReceivedAt","LatencyTrackingEvent","submittedAt","Date","receivedAt","deltaMs","perfTimings","LatencyTrackingPendingEntry","timestamp","LatencyTrackingEntry","LatencyTrackingState","pending","checkoutPair","_serverActionsEnabled","options","onReportLatency","onSyncErrorRecovery","onSlowCommit","onReportMutationPerformance","onDocumentRebase","snapshotFetchErrorHandler","listenerEvents$","connectionChangeEvents$","commitRequests$","commitRequest$","commitAttemptResults$","commitRequest","now","attemptResult","commits$","Extract","consistent$","states","Boolean","isConsistent","bufferSize","refCount","pendingEnd$","phase","commitResolved$","slowCommitWarning$","rebaseEvents$","remoteMutationCount","remoteMutations","localMutationCount","localMutations","combinedEvents","reportLatency","shardInfo","fetch","getUrl","getDataUrl","signal","AbortSignal","timeout","then","response","shard","headers","get","arrayBuffer","catch","resolve","submittedMutations","const","receivedMutations","reconnectionResets","state","e","getTime","matchingIndex","findIndex","matching","submitEvent","receiveEvent","i","concat","latencyMs","listenerReceivedAt","debounceMs","Math","max","apiMs","callbackMs","Observable","memoize","args","fn","TFunction","keyGen","Parameters","MEMO","key","Object","create","memoizedFn","SanityClient","IdPair","memoizeKeyGen","client","idPair","typeName","config","dataset","projectId","publishedId","versionId","SanityClient","EMPTY","merge","Observable","of","ReplaySubject","share","timer","mergeMap","DocumentStoreExtraOptions","IdPair","memoize","checkoutPair","Pair","memoizeKeyGen","LISTENER_RESET_DELAY","memoizedPair","client","idPair","typeName","extraOptions","_typeName","pairListenerOptions","subscriber","pair","undefined","draft","events","pipe","published","version","subscribe","connector","resetOnComplete","resetOnRefCountZero","SanityClient","Observable","distinctUntilChanged","shareReplay","switchMap","DocumentStoreExtraOptions","IdPair","memoize","CommitError","memoizedPair","memoizeKeyGen","commitErrorStatus","client","idPair","typeName","extraOptions","pipe","pair","commitError$","bufferSize","refCount","SanityClient","combineLatest","of","Observable","distinctUntilChanged","map","publishReplay","refCount","switchMap","DocumentStoreExtraOptions","IdPair","memoize","memoizedPair","memoizeKeyGen","consistencyStatus","client","idPair","typeName","extraOptions","pipe","draft","published","version","consistency$","draftIsConsistent","publishedIsConsistent","versionIsConsistent","SanityClient","EMPTY","merge","Observable","switchMap","DocumentStoreExtraOptions","IdPair","memoize","DocumentVersionEvent","memoizedPair","memoizeKeyGen","documentEvents","client","idPair","typeName","pairListenerOptions","pipe","draft","published","version","events","SanityClient","SanityDocument","Observable","filter","map","publishReplay","refCount","BufferedDocumentEvent","MutationPayload","SnapshotEvent","DocumentStoreExtraOptions","IdPair","PendingMutationsEvent","ReconnectEvent","ResetEvent","WelcomeBackEvent","WelcomeEvent","memoize","DocumentVersion","memoizedPair","memoizeKeyGen","isSnapshotEvent","event","version","type","withSnapshots","pair","DocumentVersionSnapshots","snapshots$","events","pipe","document","patch","create","createIfNotExists","createOrReplace","delete","mutate","commit","patches","mutations","SnapshotPair","transactionsPendingEvents$","draft","published","snapshotPair","client","idPair","typeName","_serverActionsEnabled","pairListenerOptions","SanityClient","Schema","combineLatest","Observable","map","publishReplay","refCount","switchMap","HistoryStore","DocumentStoreExtraOptions","IdPair","memoize","memoizeKeyGen","OperationArgs","snapshotPair","operationArgs","ctx","client","historyStore","schema","pairListenerOptions","idPair","typeName","undefined","pipe","versions","draft","snapshots$","published","version","serverActionsEnabled","snapshots","SanityClient","getOperationStoreKey","client","config","projectId","dataset","Error","SanityDocument","VARIANT_VERSION_DISABLED","const","VariantVersionDisabledReason","disabledForVariantVersion","version","_system","variant","_ref","assertNotVariantVersion","operationName","Error","_id","Schema","isLiveEditEnabled","schema","typeName","get","liveEdit","assertNotVariantVersion","disabledForVariantVersion","VariantVersionDisabledReason","isLiveEditEnabled","operationsApiClient","OperationImpl","del","disabled","snapshots","variantDisabled","version","draft","published","execute","client","schema","idPair","typeName","tx","observable","transaction","delete","publishedId","commit","tag","draftId","skipCrossDatasetReferenceValidation","assertNotVariantVersion","disabledForVariantVersion","VariantVersionDisabledReason","operationsApiClient","OperationImpl","DisabledReason","discardChanges","disabled","snapshots","variantDisabled","version","draft","published","execute","client","idPair","observable","transaction","delete","draftId","commit","tag","SanityDocument","SanityDocumentLike","omit","getDraftId","getVersionFromId","getVersionId","isLiveEditEnabled","operationsApiClient","MapDocument","OperationImpl","omitProps","getDocumentToDuplicateId","versionSnapshot","dupeId","liveEdit","_system","variant","_ref","versionId","_id","mapDocumentNoop","document","duplicate","baseDocumentId","options","mapDocument","disabled","snapshots","published","draft","version","execute","schema","client","typeName","idPair","source","Error","observable","create","_type","tag","assertNotVariantVersion","disabledForVariantVersion","VariantVersionDisabledReason","isLiveEditEnabled","OperationImpl","patch","patches","initialDocument","Record","disabled","snapshots","version","execute","schema","idPair","draft","published","typeName","mutate","createIfNotExists","_type","_id","draftId","isReference","SanityDocument","omit","assertNotVariantVersion","disabledForVariantVersion","VariantVersionDisabledReason","isLiveEditEnabled","operationsApiClient","OperationImpl","PublishOptions","strengthenOnPublish","obj","T","_strengthenOnPublish","concat","weak","Array","isArray","map","Object","fromEntries","entries","key","value","const","DisabledReason","publish","options","disabled","schema","typeName","snapshots","variantDisabled","version","draft","published","execute","client","idPair","Error","tx","observable","transaction","patch","publishedId","unset","ifRevisionID","_rev","createOrReplace","_id","create","delete","commit","tag","visibility","DocumentRevision","assertNotVariantVersion","disabledForVariantVersion","isLiveEditEnabled","OperationImpl","restore","fromRevision","disabled","snapshots","version","execute","historyStore","schema","idPair","typeName","targetId","versionId","publishedId","draftId","omit","assertNotVariantVersion","disabledForVariantVersion","VariantVersionDisabledReason","isLiveEditEnabled","operationsApiClient","OperationImpl","DisabledReason","unpublish","disabled","schema","snapshots","typeName","variantDisabled","version","published","execute","client","idPair","tx","observable","transaction","delete","publishedId","createIfNotExists","_id","draftId","_type","commit","tag","visibility","skipCrossDatasetReferenceValidation","isPublishedId","OperationImpl","actionsApiClient","del","versions","disabled","snapshots","draft","published","version","execute","client","idPair","observable","action","map","versionId","actionType","skipCrossDatasetReferenceValidation","includeDrafts","filter","v","draftId","publishedId","tag","SourceClientOptions","VARIANT_DOCUMENT_TYPE","VARIANT_DOCUMENTS_PATH","VARIANTS_STUDIO_CLIENT_OPTIONS","apiVersion","isPortableTextBlock","toPlainText","DocumentSystem","PerspectiveBundle","DOCUMENT_SYSTEM_FIELD","VARIANT_DOCUMENTS_PATH","SystemVariant","VARIANT_ID_PREFIX","isPublishedBundleId","bundleId","undefined","isReleaseBundle","getVariantId","variantDocumentId","startsWith","slice","length","getVariantIdFromDocument","document","Record","system","variantRef","variant","_ref","getVariantTitle","title","metadata","trim","_id","getVariantConditionsText","conditions","Object","entries","map","key","value","JSON","stringify","join","decodeVariantIdFromRoute","variantIdRaw","decoded","decodeURIComponent","getVariantDescription","description","Array","isArray","every","filterVariantsForSearch","variants","searchTerm","normalizedSearchTerm","toLowerCase","filter","searchableValues","flat","some","includes","SanityDocument","getVariantId","VariantVersionInfo","variantId","bundleId","getVariantVersionInfo","version","variantRef","_system","variant","_ref","undefined","BaseActionOptions","ObservableSanityClient","SanityClient","SingleActionResult","SanityDocumentLike","Observable","PerspectiveBundle","EditableSystemVariant","VariantDefinitionActionResult","transactionId","VariantDocumentBundleId","Exclude","VariantDefinitionCreateAction","actionType","variantId","conditions","priority","metadata","VariantDefinitionEditAction","patch","set","Pick","Partial","unset","ifRevisionId","VariantDefinitionDeleteAction","VariantDefinitionAction","VariantDocumentCreateActionBase","publishedId","bundleId","VariantDocumentCreateFromDocumentAction","document","VariantDocumentCreateFromBaseAction","baseId","ifBaseRevisionId","VariantDocumentCreateAction","VariantDocumentPublishAction","ifSourceRevisionId","ifPublishedVariantRevisionId","VariantDocumentUnpublishAction","VariantDocumentDeleteAction","purge","VariantDocumentAction","VariantAction","ObservableSanityClientWithVariantsActions","Omit","action","options","SanityClientWithVariantsActions","Promise","observable","variantsClient","client","SanityClient","VARIANTS_STUDIO_CLIENT_OPTIONS","variantsClient","variantActionsApiClient","client","withConfig","getVariantVersionInfo","OperationImpl","actionsApiClient","variantActionsApiClient","DisabledReason","discardChanges","disabled","snapshots","draft","version","bundleId","execute","client","idPair","variantVersion","Error","observable","action","actionType","publishedId","variantId","tag","draftId","versionId","OperationImpl","isLiveEditEnabled","patch","patches","initialDocument","Record","disabled","execute","schema","snapshots","idPair","draft","published","version","typeName","patchMutation","ensureVersion","unset","create","_id","draftId","_type","mutate","mutations","createIfNotExists","createMutation","commit","getVariantVersionInfo","OperationImpl","PublishOptions","actionsApiClient","assertNotVariantVersion","isLiveEditEnabled","variantActionsApiClient","DisabledReason","publish","options","disabled","schema","typeName","snapshots","variantVersion","version","bundleId","_system","release","_ref","draft","published","execute","client","idPair","Error","versionId","observable","action","actionType","publishedId","variantId","ifPublishedVariantRevisionId","publishedRevisionId","tag","draftId","_id","ifPublishedRevisionId","_rev","DocumentRevision","OperationImpl","isLiveEditEnabled","restore","fromRevision","disabled","execute","snapshots","historyStore","schema","idPair","typeName","targetId","versionId","publishedId","draftId","fromDeleted","draft","published","useServerDocumentActions","getVariantVersionInfo","OperationImpl","actionsApiClient","assertNotVariantVersion","isLiveEditEnabled","variantActionsApiClient","DisabledReason","unpublish","disabled","schema","snapshots","typeName","variantVersion","version","bundleId","published","execute","client","idPair","Error","observable","action","actionType","publishedId","variantId","_system","tag","skipCrossDatasetReferenceValidation","draftId","SanityClient","Schema","asyncScheduler","defer","EMPTY","merge","Observable","of","Subject","timer","catchError","concatMap","filter","groupBy","last","map","mergeMap","mergeMapTo","share","switchMap","take","tap","throttleTime","HistoryStore","DocumentStoreExtraOptions","IdPair","memoize","consistencyStatus","getOperationStoreKey","operationArgs","commit","del","discardChanges","duplicate","patch","publish","restore","OperationArgs","OperationsAPI","unpublish","serverDel","serverDiscardChanges","serverPatch","serverPublish","serverRestore","serverUnpublish","ExecuteArgs","operationName","idPair","typeName","storeKey","extraArgs","maybeObservable","v","operationImpls","delete","const","serverOperationImpls","execute","operationArguments","operation","pipe","operationCalls$","emitOperation","next","REQUIRES_CONSISTENCY","OperationError","type","op","id","error","Error","OperationSuccess","IntermediarySuccess","args","IntermediaryError","operationEvents","ctx","client","historyStore","schema","serverActionsEnabled","extraOptions","result$","publishedId","groups$","requiresConsistency","includes","published","draft","version","isConsistent$","Boolean","ready$","err","AUTOCOMMIT_INTERVAL","autoCommit$","result","leading","trailing","window","SLOW","config","dataset","projectId","IdPair","getOperationStoreKey","emitOperation","del","serverDel","discardChanges","serverDiscardChanges","patch","serverPatch","publish","serverPublish","restore","serverRestore","unpublish","serverUnpublish","commit","duplicate","Operation","OperationArgs","OperationImpl","OperationsAPI","createOperationGuard","opName","disabled","execute","Error","GUARDED","delete","createTargetNotFoundOperation","TARGET_NOT_FOUND_OPERATIONS","createEmitter","operationName","idPair","typeName","storeKey","executeArgs","wrap","op","ExtraArgs","DisabledReason","operationArgs","client","createOperationsAPI","args","operations","targetVersionMissing","Boolean","versionId","snapshots","version","draft","published","SanityClient","Schema","concat","EMPTY","merge","Observable","of","map","mergeMap","shareReplay","HistoryStore","DocumentStoreExtraOptions","IdPair","memoize","memoizeKeyGen","operationArgs","operationEvents","createOperationsAPI","GUARDED","OperationsAPI","editOperations","ctx","client","historyStore","schema","pairListenerOptions","idPair","typeName","operationEvents$","operationArgs$","operations$","pipe","refCount","bufferSize","RELEASE_DOCUMENT_TYPE","RELEASE_DOCUMENTS_PATH","ReleaseId","RELEASE_DOCUMENTS_PATH","PATH_ID_PREFIX","getReleaseIdFromReleaseDocumentId","releaseDocumentId","startsWith","Error","releaseId","slice","length","MonoTypeOperatorFunction","tap","measureFirstEmission","onMeasured","durationMs","value","T","source","measured","startTime","pipe","subscribe","performance","now","next","measureFirstMatch","predicate","SanityClient","SanityDocument","Schema","combineLatest","Observable","of","ReplaySubject","timer","map","share","startWith","switchMap","getReleaseIdFromReleaseDocumentId","getVersionFromId","measureFirstEmission","createSWR","DocumentStoreExtraOptions","IdPair","PendingMutationsEvent","memoize","memoizeKeyGen","snapshotPair","isLiveEditEnabled","TransactionSyncLockState","enabled","swr","maxSize","EditStateFor","id","type","transactionSyncLock","draft","published","version","liveEdit","liveEditSchemaType","ready","release","scopeId","LOCKED","NOT_LOCKED","classifyRelease","versionSnapshot","_system","group","releaseRef","_ref","undefined","TEARDOWN_GRACE_PERIOD","editState","ctx","client","schema","serverActionsEnabled","extraOptions","idPair","typeName","versionId","pipe","versions","snapshots$","transactionsPendingEvents$","ev","phase","publishedId","draftId","durationMs","fromCache","value","draftSnapshot","publishedSnapshot","onDocumentPairLoaded","hasPublished","Boolean","hasDraft","hasVersion","connector","resetOnRefCountZero","isKeyedObject","Path","pathToString","path","reduce","target","segment","i","segmentType","separator","_key","Error","Path","ValidationError","ValidationMarker","ValidationContext","pathToString","isNonNullable","t","T","NonNullable","undefined","convertToValidationMarker","validatorResult","level","context","Error","Array","isArray","flatMap","child","filter","message","path","__internal_metadata","normalizedPaths","push","paths","length","item","map","concat","CustomValidatorResult","LocalizedValidationMessages","isPlainObject","LocaleSource","localizeMessage","message","i18n","currentLocale","locale","id","includes","language","split","en","isLocalizedMessages","deepEqualsIgnoreKey","a","b","Array","isArray","length","i","keys","Object","Date","getTime","RegExp","toString","prototype","hasOwnProperty","call","key","_toString","toString","builtIns","Object","Function","Array","String","Boolean","Number","Date","RegExp","Error","isBuiltIn","_constructor","i","length","typeString","obj","stringType","call","slice","undefined","toLowerCase","constructorType","constructor","name","ValidationMarker","Validators","LocaleSource","deepEqualsIgnoreKey","isLocalizedMessages","localizeMessage","pathToString","typeString","SLOW_VALIDATOR_TIMEOUT","formatValidationErrors","options","message","results","operation","i18n","length","t","messages","map","err","item","formatParams","style","type","genericValidators","expectedType","value","actualType","presence","expected","undefined","all","children","context","resolved","Promise","child","validate","flat","either","find","result","valid","allowedValues","actual","valueType","strValue","slice","some","replace","hint","custom","fn","slowTimer","setTimeout","environment","console","warn","path","clearTimeout","isArrayOfBlocksSchemaType","Path","PathSegment","Validators","deepEqualsIgnoreKey","genericValidators","arrayValidators","min","minLength","value","message","i18n","type","length","context","undefined","t","max","maxLength","wantedLength","presence","flag","valid","allowedValues","values","valueType","paths","i","some","expected","pathSegment","_key","push","sharedMessage","map","path","unique","_unused","dupeIndices","x","y","itemA","itemB","indexOf","idx","item","Validators","legacyDateFormat","genericValidators","isRecord","obj","Record","Array","isArray","isoDate","DateTimeOptions","dateFormat","timeFormat","getFormattedDate","type","value","Date","options","DEFAULT_DATE_FORMAT","DEFAULT_TIME_FORMAT","format","useUTC","parseDate","date","throwOnError","parsed","isInvalid","isNaN","getTime","Error","dateValidators","_unused","message","i18n","test","t","min","minDate","dateVal","minDateVal","dateTimeOptions","name","providedMinDate","max","maxDate","maxDateVal","providedMaxDate","Validators","genericValidators","precisionRx","numberValidators","integer","_unused","value","message","i18n","Number","isInteger","t","precision","limit","undefined","places","toString","match","decimals","Math","max","length","parseInt","min","minNumber","maxNumber","greaterThan","threshold","lessThan","Asset","MediaLibraryAsset","AssetInstanceDocument","CustomValidatorResult","isReference","Validators","getPublishedId","isLocalizedMessages","localizeMessage","pathToString","genericValidators","SLOW_VALIDATOR_TIMEOUT","metaKeys","objectValidators","presence","expected","value","message","i18n","keys","Object","filter","key","includes","undefined","length","t","context","reference","_unused","type","document","getDocumentExists","Error","weak","documentId","_id","_ref","exists","id","assetRequired","flag","asset","__internal_metadata","name","assetType","media","fn","slowTimer","setTimeout","environment","console","warn","path","result","libraryId","split","resourceConfig","resource","getClient","apiVersion","withConfig","fetch","currentVersion","err","error","String","cause","clearTimeout","validationErrorMetadata","Array","isArray","map","res","Validators","genericValidators","DUMMY_ORIGIN","isRelativeUrl","url","test","emailRegex","stringValidators","min","minLength","value","message","i18n","length","t","max","maxLength","wantedLength","strValue","uri","constraints","options","allowCredentials","relativeOnly","allowRelative","URL","origin","username","password","urlScheme","protocol","replace","isRelative","matchesAllowedScheme","scheme","some","stringCasing","casing","toLocaleUpperCase","toLocaleLowerCase","presence","flag","context","regex","pattern","name","invert","regName","toString","lastIndex","matches","email","_unused","trim","Rule","BaseRule","CustomValidator","IRule","RuleClass","SchemaType","ValidationMarker","Validator","get","convertToValidationMarker","isLocalizedMessages","localizeMessage","pathToString","arrayValidators","booleanValidators","dateValidators","genericValidators","numberValidators","objectValidators","stringValidators","typeValidators","Boolean","Number","String","Array","Object","Date","isFieldRef","constraint","type","path","Record","FIELD_REF","EMPTY_ARRAY","array","def","object","string","number","boolean","dateTime","clone","rule","_type","_message","_required","_rules","_level","_fieldRules","_typeDef","validate","value","__internal","context","Parameters","Promise","customValidationConcurrencyLimiter","valueIsEmpty","undefined","rules","filter","curr","flag","validators","results","all","map","Error","validator","forType","specConstraint","parent","bypassConcurrencyLimit","customValidator","args","ready","release","message","i18n","result","err","errorMessage","flat","CustomValidator","isKeyedObject","isSlug","Path","SlugIsUniqueValidator","SlugParent","SlugSchemaType","SlugValidationContext","memoize","DEFAULT_STUDIO_CLIENT_OPTIONS","getPublishedId","memoizedWarnOnArraySlug","warnOnArraySlug","serializePath","path","reduce","target","part","i","isIndex","isKey","separator","add","defaultIsUnique","slug","context","getClient","document","type","schemaOptions","options","Error","disableArrayWarning","docType","_type","atPath","concat","includes","environment","constraints","join","apiVersion","withConfig","perspective","fetch","published","_id","tag","serializedPath","console","warn","slugValidator","value","i18n","Array","isArray","t","current","trim","length","isUnique","slugContext","parent","wasUnique","Rule","RuleSpec","RuleTypeConstraint","SchemaType","ValidationContext","isEqual","RuleClass","slugValidator","ruleConstraintTypes","Lowercase","array","boolean","date","number","object","string","isRuleConstraint","typeString","getTypeChain","type","visited","Set","has","add","next","baseRuleReducer","inputRule","baseRule","jsonType","typeOptionsList","options","list","Array","isArray","valid","map","option","extractValueFromListOption","name","uri","custom","bypassConcurrencyLimit","reference","email","hasValueField","typeDef","fields","some","field","Record","value","undefined","isUriSpec","spec","Extract","flag","omitLeakedDefaultUri","rules","isUrlType","defaultUri","_rules","find","constraint","isDefaultUri","isCustomUri","someElementSetsScheme","rule","cleaned","clone","filter","normalizeValidationRules","context","validation","flatMap","i","Object","values","reduce","acc","Schema","SchemaType","SchemaValidationValue","normalizeValidationRules","inferFromSchemaType","typeDef","_schema","_visited","Set","traverse","visited","has","add","usesValidationContext","hasValidationContext","validation","field","fields","type","candidate","of","annotations","annotation","Array","isArray","some","length","signature","Function","prototype","toString","call","test","Schema","inferFromSchemaType","inferFromSchema","schema","typeNames","getLocalTypeNames","forEach","typeName","schemaType","get","ConditionalProperty","CurrentUser","Path","ConditionalPropertyCallbackContext","parent","document","Record","currentUser","Omit","value","path","resolveConditionalProperty","property","context","undefined","Boolean","defineLocalesResources","copyPasteLocalNamespace","LocaleResourceBundle","copyPasteLocaleStrings","copyPasteLocaleResources","locale","namespace","resources","defineLocalesResources","feedbackLocaleNamespace","LocaleResourceBundle","feedbackLocaleStrings","const","feedbackLocaleResources","locale","namespace","resources","defineLocalesResources","studioLocaleNamespace","LocaleResourceBundle","studioLocaleStrings","StudioLocaleResourceKeys","studioDefaultLocaleResources","locale","namespace","resources","defineLocalesResources","validationLocaleNamespace","LocaleResourceBundle","validationLocaleStrings","const","ValidationLocaleResourceKeys","validationLocaleResources","locale","namespace","resources","copyPasteLocaleResources","feedbackLocaleResources","studioDefaultLocaleResources","validationLocaleResources","defineLocale","usEnglishLocale","id","title","bundles","weekInfo","firstDay","weekend","defaultLocale","createInstance","Resource","memoize","isStaticResourceBundle","studioLocaleNamespace","defaultLocale","usEnglishLocale","LocaleSource","shouldEscape","window","document","fallbackLocales","getFallbackLocaleSource","i18n","getFallbackI18nInstance","init","currentLocale","locales","loadNamespaces","t","staticResources","id","staticBundles","bundles","filter","namespaces","Set","bundle","namespace","resources","add","ns","Array","from","defaultNS","initAsync","partialBundledLanguages","fallbackLng","lng","supportedLngs","debug","load","interpolation","escapeValue","SanityClient","ConcurrencyLimiter","bufferTime","filter","finalize","firstValueFrom","from","map","mergeMap","share","Subject","switchMap","AvailabilityResponse","BUFFER_TIME","MAX_BUFFER_SIZE","MAX_REQUEST_CONCURRENCY","createBatchedGetDocumentExists","client","options","id","Promise","id$","limiter","existence$","pipe","ids","Array","Set","ready","observable","request","uri","getDataUrl","join","json","query","excludeContent","tag","availability","release","omittedIds","omitted","reduce","Record","acc","next","reason","exists","getDocumentExists","result","requestIdleCallbackShim","window","requestIdleCallback","callback","_options","start","Date","now","globalThis","setTimeout","didTimeout","timeRemaining","Math","max","cancelIdleCallbackShim","cancelIdleCallback","handle","clearTimeout","win","undefined","CustomValidator","ObjectSchemaType","unknownFieldsValidator","type","value","fieldNames","Set","fields","map","field","name","unknownFields","Object","keys","filter","key","startsWith","has","unknownField","message","path","SanityClient","isKeyedObject","isTypedObject","CurrentUser","Rule","SanityDocument","Schema","SchemaType","ValidationMarker","createClientConcurrencyLimiter","ConcurrencyLimiter","flatten","uniqBy","concat","defer","from","lastValueFrom","merge","Observable","of","catchError","map","mergeAll","mergeMap","switchMap","toArray","SourceClientOptions","Workspace","resolveConditionalProperty","getFallbackLocaleSource","DEFAULT_STUDIO_CLIENT_OPTIONS","ValidationContext","createBatchedGetDocumentExists","getTypeChain","normalizeValidationRules","cancelIdleCallback","requestIdleCallback","typeString","unknownFieldsValidator","DEFAULT_MAX_FETCH_CONCURRENCY","DEFAULT_MAX_CUSTOM_VALIDATION_CONCURRENCY","_limitConcurrency","ReturnType","getConcurrencyLimiter","maxConcurrency","isRecord","maybeRecord","Record","Array","isArray","isNonNullable","value","T","NonNullable","undefined","extractFieldRulesFromRule","rule","results","_fieldRules","push","ruleSpec","_rules","flag","childRules","constraint","childRule","resolveTypeForArrayItem","item","candidates","length","itemType","_type","primitive","toLowerCase","find","candidate","jsonType","type","name","ValidateDocumentOptions","document","workspace","getDocumentExists","options","id","Promise","getClient","clientOptions","environment","maxCustomValidationConcurrency","maxFetchConcurrency","currentUser","Omit","validateDocument","limitConcurrency","getConcurrencyLimitedClient","validateDocumentObservable","i18n","schema","ValidateDocumentObservableOptions","Pick","apiVersion","customValidationConcurrencyLimiters","WeakMap","Error","documentType","get","console","warn","level","message","path","customValidationConcurrencyLimiter","set","validationOptions","ValidateItemOptions","parent","loadNamespaces","pipe","validateItemObservable","err","error","errorMarker","ExplicitUndefined","Required","P","hidden","validateItem","opts","restOfContext","ancestorHidden","resolveHiddenForType","schemaType","schemaValue","schemaParent","schemaPath","ancestorHiddenValue","addUnknownFieldsValidator","t","includes","custom","bypassConcurrencyLimit","warning","rules","selfChecks","validate","__internal","nestedChecks","selfIsRequired","some","isRequired","shouldRunNestedObjectValidation","fieldTypes","fields","reduce","acc","field","flatMap","fieldResults","Object","entries","validation","fieldType","subRule","nestedValue","nestedHidden","shouldRunNestedValidationForArrays","index","_key","validateNode","idle","JSON","stringify","timeout","observer","handle","complete","SanityClient","isGlobalDocumentReference","isReference","SanityDocument","Schema","ValidationContext","ValidationMarker","CurrentUser","reduce","reduceJSON","asyncScheduler","combineLatest","concat","defer","from","lastValueFrom","Observable","of","timer","exhaustMapWithTrailing","distinct","distinctUntilChanged","first","groupBy","map","mergeMap","scan","shareReplay","skip","throttleTime","shallowEquals","SourceClientOptions","LocaleSource","DocumentPreviewStore","getVersionFromId","validateDocumentObservable","ValidationStatus","isValidating","validation","revision","INITIAL_VALIDATION_STATUS","findReferenceIds","obj","Set","acc","node","add","_ref","EMPTY_VALIDATION","GetDocumentExists","NonNullable","listenDocumentExists","observeDocumentAvailability","id","versionId","version","pipe","published","available","reason","REF_UPDATE_DELAY","shareLatestWithRefCount","T","bufferSize","refCount","validateDocumentWithReferences","ctx","getClient","options","observeDocumentPairAvailability","schema","i18n","currentUser","Omit","document$","requirePublishedReferences","referenceIds$","document","ids","versionId$","referenceExistence$","_","referenceId","duration","refIds$","undefined","_id","result","const","Record","getDocumentExists","referenceExistence","referenceDocumentUpdates$","leading","trailing","_type","_rev","environment","validationMarkers","next","SanityClient","CurrentUser","Schema","omit","asyncScheduler","combineLatest","Observable","distinctUntilChanged","map","shareReplay","throttleTime","shallowEquals","SourceClientOptions","LocaleSource","DraftsModelDocumentAvailability","DocumentVariantType","validateDocumentWithReferences","ValidationStatus","DocumentStoreExtraOptions","IdPair","memoize","editState","memoizeKeyGen","DOC_UPDATE_DELAY","shareLatestWithRefCount","T","bufferSize","refCount","validation","ctx","client","getClient","options","observeDocumentPairAvailability","id","schema","i18n","serverActionsEnabled","pairListenerOptions","currentUser","Omit","draftId","publishedId","versionId","typeName","validationTarget","validatePublishedReferences","document$","pipe","state","version","draft","published","trailing","documentToValidate$","prev","next","_rev","documentRevision$","document","revision","validationStatus","idPair","documentId","userId","postTask","callback","Result","options","PostTaskOptions","Promise","window","scheduler","isPlainObject","isRecord","value","Record","isRecord","deepAssign","target","Record","source","result","Object","keys","forEach","key","sourceVal","targetVal","Schema","randomKey","toString","pathToString","Template","TemplateParameter","isRecord","ALLOWED_REF_PROPS","REQUIRED_TEMPLATE_PROPS","templateId","template","i","quote","id","title","str","length","validateTemplates","schema","templates","idMap","Map","forEach","key","values","value","Error","missing","filter","prop","join","parameters","Array","isArray","param","j","validateParameter","has","dupeIndex","get","dupe","set","validateInitialObjectValue","Record","T","contextError","msg","_type","schemaType","validateValue","err","message","path","parentIsArray","map","item","concat","initial","_key","_ref","validateReference","Object","keys","reduce","acc","parameter","index","name","type","disallowed","includes","plural","ArraySchemaType","InitialValueProperty","InitialValueResolver","InitialValueResolverContext","isArraySchemaType","isObjectSchemaType","ObjectSchemaType","Schema","SchemaType","isDeepEmpty","randomKey","resolveTypeName","postTask","Template","deepAssign","isRecord","validateInitialObjectValue","Serializeable","serialize","T","Options","useCache","isBuilder","template","cache","WeakMap","Record","Promise","resolveValue","initialValueOpt","Params","InitialValue","params","context","options","cached","get","key","JSON","stringify","projectId","dataset","currentUser","id","value","set","resolveInitialValue","schema","schemaType","schemaTypeName","Error","resolvedValue","Object","keys","length","_type","newValue","resolveInitialValueForType","DEFAULT_MAX_RECURSION_DEPTH","getItemType","arrayType","item","itemTypeName","of","find","memberType","name","RESOLVE_INITIAL_VALUE_TIMEOUT_MS","ResolveInitialValueForType","type","TParams","maxDepth","memoizeResolveInitialValueForType","fn","resolveInitialValueForTypeCache","Map","stableStringify","obj","Array","isArray","map","join","sort","hashParameters","schemaName","typeCache","hash","cachedResult","result","has","resolve","undefined","resolveInitialObjectValue","resolveInitialArrayValue","initialValue","initialArray","all","initialItem","itemType","_key","initialObject","fieldValues","fields","field","initialFieldValue","merged","InitialValueResolverContext","SanityDocumentLike","Schema","from","merge","Observable","of","catchError","debounceTime","distinctUntilChanged","filter","map","scan","startWith","switchMap","timeout","DocumentPreviewStore","RESOLVE_INITIAL_VALUE_TIMEOUT_MS","resolveInitialValue","Template","getDraftId","getPublishedId","InitialValueErrorMsg","InitialValueLoadingMsg","InitialValueMsg","InitialValueSuccessMsg","InitialValueOptions","documentId","documentType","templateName","templateParams","Record","LOADING_MSG","type","getInitialValueStream","schema","initialValueTemplates","documentPreviewStore","opts","context","draft$","observePaths","_type","_ref","published$","value$","pipe","draft","published","prev","res","next","Boolean","document","value","template","find","t","id","console","warn","resolved$","first","initialValue","resolveError","Error","group","error","groupEnd","msg","ClientPerspective","SanityClient","asyncScheduler","defer","merge","Observable","of","partition","throwError","timer","exhaustMapWithTrailing","filter","mergeMap","share","take","throttleTime","MutationEvent","ReconnectEvent","WelcomeEvent","ListenQueryParams","Record","ListenQueryOptions","tag","apiVersion","perspective","transitions","fetch","client","query","params","options","observable","filterResponse","listen","events","includeResult","visibility","includeAllVersions","isWelcomeEvent","event","type","listenQuery","fetchQuery","listenerQuery","events$","pipe","ev","i","isFirst","Error","welcome$","mutationAndReconnect$","isRelevantEvent","includes","transition","doFetch","leading","trailing","DocumentPairTarget","normalizeDocumentPairTarget","version","kind","scopeId","getPairTargetScopeId","target","undefined","SanityClient","Observable","of","getPublishedId","resolveTypeForDocument","client","id","specifiedType","query","observable","fetch","publishedId","tag","SanityClient","CurrentUser","InitialValueResolverContext","Schema","Observable","of","filter","map","SourceClientOptions","LocaleSource","DocumentPreviewStore","DEFAULT_STUDIO_CLIENT_OPTIONS","Template","getPublishedId","getVersionFromId","isDraftId","isVersionId","getIdPair","getDocumentVariantType","ValidationStatus","HistoryStore","checkoutPair","CommitError","DocumentVersionEvent","Pair","commitErrorStatus","consistencyStatus","documentEvents","editOperations","editState","EditStateFor","OperationError","operationEvents","OperationSuccess","GUARDED","TARGET_NOT_FOUND_OPERATIONS","OperationsAPI","validation","DocumentStoreExtraOptions","getInitialValueStream","InitialValueOptions","InitialValueMsg","listenQuery","ListenQueryOptions","getPairTargetScopeId","normalizeDocumentPairTarget","resolveTypeForDocument","DocumentPairTarget","IdPair","QueryParams","Record","getIdPairFromPublished","publishedId","version","Error","DocumentStore","idPair","initialValue","opts","context","query","fetch","listen","params","options","id","specifiedType","pair","type","validationTargetId","validatePublishedReferences","DocumentStoreOptions","getClient","documentPreviewStore","historyStore","schema","initialValueTemplates","i18n","serverActionsEnabled","extraOptions","currentUser","Omit","createDocumentStore","observeDocumentPairAvailability","unstable_observeDocumentPairAvailability","client","onSyncErrorRecovery","onReportLatency","onSlowCommit","onReportMutationPerformance","onDocumentRebase","ctx","undefined","listenQueryOptions","target","kind","edit","pipe","result","args","typeName","operationName","op","error","requirePublishedReferences","validationTarget","scan","switchMap","tap","concat","fromEvent","of","distinctUntilChanged","map","DEBUG_PREFIX","hashchange$","window","debugParams$","pipe","document","location","hash","slice","split","filter","p","toLowerCase","startsWith","param","length","debugRolesParam$","args","find","arg","r","trim","map","debugRolesParam$","Grant","grants","ExampleRoleName","DEBUG_ROLE_GRANTS_MAP","Record","administrator","editor","developer","contributor","viewer","restricted","requiresApproval","read","write","debugGrants$","pipe","roles","length","filter","value","Boolean","flatMap","roleName","SanityClient","CurrentUser","SanityDocument","evaluate","parse","defer","of","refCountDelay","distinctUntilChanged","publishReplay","switchMap","shallowEquals","StoreRequestErrorHandler","debugGrants$","DocumentValuePermission","EvaluationParams","Grant","GrantsStore","PermissionCheckResult","getDatasetGrants","client","projectId","dataset","errorHandler","Promise","fetchGrants","request","uri","tag","attempt","retryable","getParams","userId","params","identity","PARSED_FILTERS_MEMO","Map","matchesFilter","filter","document","has","set","parsed","get","evalParams","Record","data","length","GrantsStoreOptionsCurrentUser","currentUser","GrantsStoreOptionsUserId","GrantsStoreOptions","createGrantsStore","opts","versionedClient","withConfig","apiVersion","id","datasetGrants$","config","pipe","Error","currentUserDatasetGrants","debugGrants","checkDocumentPermission","permission","grants","grantsPermissionOn","granted","reason","matchingGrants","grant","push","foundMatch","some","permissions","p","MendozaEffectPair","MendozaPatch","Chunk","ChunkType","Transaction","canMergeEdit","type","CHUNK_WINDOW","isWithinMergeWindow","a","b","Date","parse","mergeChunk","left","right","end","start","Error","draftState","combineState","publishedState","endTimestamp","startTimestamp","authors","Set","author","add","index","id","ChunkState","getChunkState","effect","modified","Boolean","deleted","isDeletePatch","apply","getChunkType","transaction","draftEffect","publishedEffect","chunkFromTransaction","modifiedDraft","modifiedPublished","draftDeleted","publishedDeleted","timestamp","patch","Annotation","CombinedDocument","isSameAnnotation","a","b","author","timestamp","getAttrs","doc","Record","draft","published","ArrayInput","Diff","diffInput","Input","ObjectInput","StringInput","wrap","incremental","Annotation","Chunk","Timeline","isSameAnnotation","Meta","chunk","transactionIndex","AnnotationExtractor","fromValue","value","Value","T","fromMeta","meta","ArrayContentWrapper","type","const","length","annotation","extractor","content","ArrayContent","elements","constructor","at","idx","Error","input","wrapValue","annotationAt","metas","ObjectContentWrapper","Record","keys","ObjectContent","fields","Object","get","key","undefined","StringContentWrapper","StringContent","sliceAnnotation","start","end","text","result","push","lst","part","parts","subStart","Math","max","subEnd","min","slice","raw","extractAnnotationForFromInput","timeline","firstChunk","annotationForTransactionIndex","index","extractAnnotationForToInput","chunkIdx","tx","transactionByIndex","chunkByTransactionIndex","timestamp","author","diffValue","from","fromRaw","to","toRaw","fromInput","endMeta","toInput","startMeta","Merger","left","T","right","TwoEndedArray","index","_postive","_negative","addToEnd","elem","length","push","addToBeginning","mergeAtEnd","value","merger","idx","lastIdx","result","get","Array","isArray","set","mergeAtBeginning","firstIdx","removeFromEnd","shift","pop","has","last","first","Diff","TransactionLogEventWithEffects","applyPatch","incremental","Annotation","Chunk","chunkFromTransaction","mergeChunk","diffValue","Meta","TraceEvent","TwoEndedArray","CombinedDocument","DocumentRemoteMutationVersionEvent","Transaction","getAttrs","ParsedTimeRef","TimelineOptions","publishedId","enableTrace","Timeline","reachedEarliestEntry","draftId","_transactions","_chunks","_possiblePendingTransactions","Map","transaction","idx","_recreateTransactionsFrom","_trace","constructor","opts","push","type","window","__sanityTimelineTrace","chunkCount","length","mapChunks","mapper","chunk","T","result","firstIdx","lastIdx","get","reset","undefined","addRemoteMutation","entry","event","pending","transactionId","index","id","timestamp","toISOString","author","version","draftEffect","effects","publishedEffect","delete","_invalidateTransactionFrom","addToEnd","set","addTranslogEntry","addToBeginning","didReachEarliestEntry","updateChunks","_removeInvalidatedChunks","_addChunksFromTransactions","_createInitialChunk","last","end","removeFromEnd","nextTransactionToChunk","mergeAtEnd","firstTransactionChunked","first","start","mergeAtBeginning","firstTx","initialChunk","parseTimeId","idSegments","split","timestampStr","shift","chunkId","Number","Date","parse","endTimestamp","findLastPublishedBefore","chunkIdx","currentChunk","isLatestChunk","createTimeId","valueOf","lastChunk","transactionByIndex","has","chunkByTransactionIndex","startChunkIdx","Error","replayBackwardsBetween","doc","draft","published","revert","replayBackwardsUntil","calculateDiff","initialDoc","finalDoc","draftValue","wrap","publishedValue","initialValue","getValue","initialAttributes","firstChunk","meta","transactionIndex","preDraftValue","prePublishedValue","apply","didHaveDriaft","getType","haveDraft","havePublished","rebaseValue","finalValue","finalAttributes","Value","SanityDocument","TransactionLogEventWithEffects","applyPatch","RemoteSnapshotVersionEvent","Timeline","CombinedDocument","DocumentRemoteMutationVersionEvent","VersionState","id","hasAttrs","attrs","Record","rev","events","Array","aligned","emptyVersionState","align","history","state","idx","findIndex","evt","transactionId","startFromSnapshot","doc","_rev","Error","Aligner","timeline","earliestTransactionId","constructor","_states","draft","draftId","published","publishedId","appendRemoteSnapshotEvent","version","type","_maybeInvalidateHistory","document","_apply","addRemoteMutation","push","head","prependHistoryEvent","acceptsHistory","Object","values","_alignAtIndex","addTranslogEntry","didReachEarliestEntry","isAligned","every","_isComplete","currentDocument","mutEvt","slice","effects","apply","reset","TransactionLogEventWithMutations","TransactionLogEventWithEffects","DEFAULT_STUDIO_CLIENT_HEADERS","StreamResult","error","description","type","getJsonStream","url","token","Promise","ReadableStream","options","RequestInit","headers","Authorization","credentials","response","fetch","getStream","Response","body","Error","reader","ReadableStreamDefaultReader","Uint8Array","cancelled","start","controller","PromiseLike","getReader","decoder","TextDecoder","buffer","read","then","processResult","result","done","trim","length","close","enqueue","JSON","parse","decode","value","stream","lines","split","i","line","err","cancel","catch","Diff","Annotation","Chunk","Timeline","CombinedDocument","Reconstruction","timeline","start","end","doc","constructor","same","_startDocument","_endDocument","_diff","endAttributes","Record","getAttrs","endDocument","replayBackwardsUntil","startAttributes","startDocument","Error","replayBackwardsBetween","diff","calculateDiff","index","draft","published","SanityClient","Diff","ObjectDiff","Annotation","Chunk","RemoteSnapshotVersionEvent","Aligner","getJsonStream","Reconstruction","ParsedTimeRef","Timeline","TRANSLOG_ENTRY_LIMIT","TimelineControllerOptions","timeline","client","documentId","documentType","handler","err","Error","controller","TimelineController","SelectionState","version","selectionState","constructor","options","_aligner","markChange","_fetchMore","_fetchAtLeast","_isRunning","_isSuspended","_didErr","_since","_sinceTime","_rev","_revTime","_reconstruction","setHandler","clearRange","setRange","since","rev","setRevTime","setSinceTime","isAligned","targetRev","lastChunk","index","setReconstruction","start","setLoadMore","flag","sinceTime","revTime","isLoading","realRevChunk","onOlderRevision","Boolean","findRangeForNewRev","revTimeId","isLatestChunk","createTimeId","sinceChunk","findRangeForNewSince","revChunk","parseTimeId","findLastPublishedBefore","sinceAttributes","Record","startAttributes","displayed","endAttributes","same","currentDocument","currentDiff","diff","currentObjectDiff","type","handleRemoteMutation","ev","appendRemoteSnapshotEvent","acceptsHistory","tick","then","resume","suspend","shouldFetchMore","reachedEarliestEntry","chunkCount","fetchMoreTransactions","publishedId","draftId","clientConfig","config","limit","queryParams","tid","earliestTransactionId","transactionsUrl","getUrl","dataset","stream","token","reader","getReader","count","result","read","done","value","error","description","id","prependHistoryEvent","didReachEarliestEntry","updateChunks","Action","SanityClient","DocumentId","isDraftId","isVersionId","isReference","Reference","SanityDocument","TransactionLogEventWithMutations","reduce","jsonReduce","from","Observable","map","mergeMap","isDev","getDraftId","getPublishedId","getVersionFromId","getIdPair","isRecord","actionsApiClient","Timeline","TimelineController","DocumentRevision","HistoryStore","getDocumentAtRevision","documentId","revision","Promise","getHistory","documentIds","options","time","documents","getTransactions","restore","id","targetId","rev","RestoreOptions","getTimelineController","client","documentType","fromDeleted","useServerDocumentActions","documentRevisionCache","Record","Object","create","ids","Array","isArray","Error","dataset","config","url","join","timestamp","Date","toISOString","request","publishedId","draftId","versionId","undefined","idsToQuery","filter","Boolean","isLastRevision","cacheKey","cached","entry","tag","then","result","published","find","res","_id","draft","version","_rev","timeline","enableTrace","query","excludeContent","includeIdentifiedDocumentsOnly","transactions","toString","split","line","JSON","parse","getAllRefIds","doc","acc","node","includes","_ref","jsonMap","value","mapFn","item","keys","key","mappedValue","mapRefNodes","removeMissingReferences","existingIds","refNode","documentExists","targetDocumentId","pipe","documentAtRevision","existingIdsQuery","refId","observable","fetch","_updatedAt","document","restoredDraft","canUseServerAction","replaceDraftAction","actionType","attributes","action","ifExists","createOrReplace","visibility","HistoryStoreOptions","createHistoryStore","supportsLocalStorage","process","versions","node","key","localStorage","setItem","removeItem","KeyValueStoreValue","createMemoryStorage","DB","Object","create","getKey","key","setKey","value","supportsLocalStorage","KeyValueStoreValue","createMemoryStorage","tryParse","val","JSON","parse","err","console","warn","message","createLocalStoreStorage","getKey","key","localStorage","getItem","setKey","nextValue","removeItem","setItem","stringify","localStoreStorage","isEqual","merge","of","distinctUntilChanged","tap","localStoreStorage","KeyValueStore","KeyValueStoreValue","withLocalStorageSWR","wrappedStore","getKey","key","pipe","wrappedStoreValue","setKey","nextValue","SanityClient","DataLoader","DEFAULT_STUDIO_CLIENT_OPTIONS","KeyValueStoreValue","KeyValuePair","ServerStorageOptions","client","ServerStorage","getKey","key","Promise","setKey","nextValue","createServerStorage","_client","withConfig","keyValueLoader","keys","value","request","uri","join","catch","error","console","Array","length","fill","keyValuePairs","reduce","acc","next","Record","map","load","method","body","then","response","pair","clear","prime","SanityClient","isEqual","concat","Observable","Subject","distinctUntilChanged","filter","map","createServerStorage","KeyValueStore","KeyValueStoreValue","createServerKeyValueStore","client","serverStorage","events$","type","key","value","getKey","setKey","next","then","storedValue","pipe","event","SanityClient","withLocalStorageSWR","createServerKeyValueStore","createKeyValueStore","options","client","BifurClient","EMPTY","Observable","map","share","PresenceLocation","Transport","TransportEvent","TransportMessage","BifurStateMessage","type","i","m","sessionId","locations","BifurDisconnectMessage","session","RollCallEvent","IncomingBifurEvent","handleIncomingMessage","event","Location","userId","timestamp","Date","toISOString","Error","JSON","stringify","createBifurTransport","bifur","incomingEvents$","listen","pipe","dispatchMessage","message","request","data","sample","defer","timer","map","mergeMapTo","shareReplay","StateEvent","USERIDS","PATHS","_key","mock$","pipe","id","n","type","userId","sessionId","timestamp","Date","toISOString","locations","documentId","lastActiveAt","path","BifurClient","User","flatten","groupBy","isEqual","omit","uniq","nanoid","BehaviorSubject","combineLatest","defer","EMPTY","from","fromEvent","merge","NEVER","Observable","timer","auditTime","distinctUntilChanged","filter","map","mergeMapTo","scan","share","shareReplay","switchMap","switchMapTo","takeUntil","tap","withLatestFrom","documentIdEquals","ConnectionStatusStore","debugParams$","UserStore","createBifurTransport","DisconnectEvent","RollCallEvent","StateEvent","TransportEvent","mock$","DocumentPresence","GlobalPresence","PresenceLocation","Session","UserSessionPair","PresenceStore","documentPresence","documentId","options","excludeVersions","globalPresence$","reportLocations","locations","setLocation","nextLocation","debugPresenceParam$","KEY","generate","getSessionId","window","sessionStorage","getItem","setSessionId","id","setItem","SESSION_ID","createPresenceStore","context","bifur","connectionStatusStore","userStore","presenceEvents$","sendMessage","currentLocation$","locationChange$","pipe","next","type","requestRollCall","rollCallRequests$","event","sessionId","REPORT_MIN_INTERVAL","reportLocationInterval$","reportLocation$","myRollCall$","connectionChange$","connectionStatus$","status","statusType","args","find","arg","startsWith","split","r","trim","useMock$","includes","console","log","debugIntrospect$","syncEvent$","stateEventToSession","stateEvent","lastActiveAt","timestamp","userId","states$","keyed","allSessions$","keyedSessions","Object","values","sessions","userIds","sess","getUsers","users","session","user","res","userSessionPairHasUser","refCount","bufferSize","pair","Partial","Boolean","grouped","s","e","keys","userAndSessions","debugIntrospect","userAndSession","some","sort","a","b","localeCompare","location","path","reduce","prev","curr","concat","allDocumentsPresence$","flatMap","presence","selection","item","allPresence","SanityClient","catchError","distinctUntilChanged","map","Observable","of","repeat","ReplaySubject","scan","share","shareReplay","timer","memoize","ProjectData","ProjectGrants","ProjectStore","REFETCH_INTERVAL","getProjectOrg","client","observable","request","url","config","projectId","tag","query","includeMembers","includeFeatures","includeOrganization","pipe","delay","lastKnown","next","connector","resetOnComplete","resetOnRefCountZero","dataset","getOrganizationId","res","organizationId","getOrganizationData","organization","getProjectGrants","createProjectStore","context","versionedClient","withConfig","apiVersion","get","getDatasets","projectOrgData$","getGrants","Observable","BaseStudioRenderingContext","Record","PropertyKey","name","Name","metadata","Metadata","DefaultRenderingContext","CoreUiRenderingContext","environment","StudioRenderingContext","capabilities","const","Capability","CapabilityRecord","Partial","RenderingContextStore","renderingContext","isCoreUiRenderingContext","maybeCoreUiRenderingContext","catchError","distinctUntilChanged","map","of","OperatorFunction","pipe","switchMap","isCoreUiRenderingContext","StudioRenderingContext","INITIAL_URL_SEARCH","location","search","CORE_UI_MODE_NAME","CORE_UI_CONTEXT_SEARCH_PARAM","coreUiRenderingContext","urlSearch","renderingContext","URLSearchParams","get","serializedContext","undefined","mode","env","JSON","parse","coreUirenderingContext","name","metadata","environment","error","console","warn","map","OperatorFunction","DefaultRenderingContext","StudioRenderingContext","DEFAULT_RENDERING_CONTEXT","name","metadata","defaultRenderingContext","renderingContext","map","OperatorFunction","CapabilityRecord","StudioRenderingContext","capabilitiesByRenderingContext","Record","coreUi","globalUserMenu","globalWorkspaceControl","comlink","default","listCapabilities","renderingContext","name","of","shareReplay","coreUiRenderingContext","defaultRenderingContext","listCapabilities","RenderingContextStore","createRenderingContextStore","renderingContext","undefined","pipe","capabilities","MultiKeyWeakMapNode","type","value","next","WeakMap","MultiKeyWeakMap","get","keys","T","set","createMultiKeyWeakMap","rootMap","idCache","randomId","Array","from","length","map","Math","floor","random","toString","padStart","join","assignId","key","cachedId","id","arrangeKeys","Set","const","sort","a","b","localeCompare","getDeep","undefined","firstKey","restOfKeys","node","setDeep","ReactNode","useContext","useState","ResourceCacheContext","createMultiKeyWeakMap","MultiKeyWeakMap","ResourceCache","get","options","namespace","dependencies","T","set","value","ResourceCacheProviderProps","children","ResourceCacheProvider","t0","$","_c","resourceCache","_temp","t1","namespaces","Map","nullReplacer","emptyDependenciesReplacer","removeNullDependencies","length","map","dep","dependencies_0","dependenciesWithoutNull","namespaceMap","namespace_0","dependencies_1","namespaceMap_0","dependenciesWithoutNull_0","useResourceCache","cache","Error","useMemo","useObservable","concat","Observable","of","catchError","distinctUntilChanged","map","scan","switchMap","LoadingTuple","T","ReactHook","args","TArgs","TResult","createHookFromObservableFactory","observableFactory","arg","TArg","initialValue","initialLoadingTuple","initialResult","type","tuple","const","useLoadableFromCreateLoadable","observable","pipe","_arg","value","prevValue","next","prevIsLoading","nextValue","nextIsLoading","error","result","CurrentUser","User","useMemo","from","useSource","createHookFromObservableFactory","LoadingTuple","useUserStore","UserStore","useUserViaUserStore","userStore","userId","getUser","catch","err","console","error","useUser","$","_c","t0","useCurrentUser","currentUser","SanityClient","CurrentUser","User","DataLoader","raf","isRecord","UserStoreOptions","client","currentUser","INTERNAL_USER_IDS","id","displayName","imageUrl","UserStore","getUser","userId","Promise","getUsers","userIds","createUserStore","_client","withConfig","apiVersion","userLoader","value","request","uri","join","tag","response","Array","isArray","users","reduce","acc","next","Record","map","batchScheduleFn","cb","maxBatchSize","userFromCurrentUser","name","profileImage","prime","forEach","user","resolve","load","err","statusCode","results","loadMany","filter","result","SanityClient","useTelemetry","useToast","useCallback","useMemo","useObservable","useClient","useSchema","useTemplates","useTranslation","createDocumentPreviewStore","DocumentPreviewStore","useStudioErrorHandler","useSource","useWorkspace","DEFAULT_STUDIO_CLIENT_OPTIONS","createComlinkStore","ComlinkStore","ConnectionStatusStore","createConnectionStatusStore","DocumentDesynced","DocumentPairLoadingMeasured","DocumentRebaseOccurred","HighListenerLatencyOccurred","MutationPerformanceMeasured","createDocumentStore","DocumentStore","DocumentPairLoadedEvent","DocumentRebaseTelemetryEvent","LatencyReportEvent","MutationPerformanceEvent","OutOfSyncError","createGrantsStore","GrantsStore","createHistoryStore","HistoryStore","createKeyValueStore","KeyValueStore","createPresenceStore","PresenceStore","createProjectStore","ProjectStore","createRenderingContextStore","RenderingContextStore","useResourceCache","useCurrentUser","createUserStore","UserStore","IGNORE_LATENCY_BELOW_MS","SLOW_COMMIT_TOAST_COOLDOWN_MS","slowCommitCooldown","lastToastAt","useUserStore","$","_c","getClient","currentUser","resourceCache","t0","client","userStore","get","namespace","dependencies","set","value","useGrantsStore","errorHandler","grantsStore","userId","id","useHistoryStore","historyStore","useDocumentPreviewStore","documentPreviewStore","useDocumentStore","i18n","schema","templates","workspace","telemetry","toast","t","error","log","errorName","name","handleSyncErrorRecovery","t1","event","latencyMs","latency","shard","transactionId","handleReportLatency","t2","now","Date","push","title","description","status","handleSlowCommit","t3","event_0","durationMs","fromCache","hasPublished","hasDraft","hasVersion","handleDocumentPairLoaded","t4","event_1","handleReportMutationPerformance","t5","event_2","handleDocumentRebase","documentStore","initialValueTemplates","extraOptions","onReportLatency","onSyncErrorRecovery","onSlowCommit","onDocumentPairLoaded","onReportMutationPerformance","onDocumentRebase","snapshotFetchErrorHandler","useConnectionStatusStore","bifur","__internal","connectionStatusStore","usePresenceStore","presenceStore","useProjectStore","projectStore","keyValueStoreCache","Map","getKeyValueStoreCacheKey","config","projectId","apiHost","useKeyValueStore","bb0","cacheKey","cached","keyValueStore","useRenderingContextStore","renderingContextStore","useComlinkStore","renderingContext","Symbol","for","capabilities","comlinkStore"],"sources":["../src/core/hooks/useSchema.ts","../src/core/hooks/useTemplates.ts","../src/core/util/isRecord.ts","../src/core/util/const.ts","../src/core/util/rxSwr.ts","../src/core/preview/constants.tsx","../src/core/preview/utils/debounceCollect.ts","../src/core/preview/availability.ts","../src/core/preview/utils/shareReplayLatest.ts","../src/core/preview/createGlobalListener.ts","../src/core/preview/utils/applyMendozaPatch.ts","../src/core/preview/createObserveDocument.ts","../src/core/preview/utils/keysOf.ts","../src/core/preview/utils/props.ts","../src/core/preview/createPathObserver.ts","../src/core/preview/utils/getPreviewPaths.ts","../src/core/preview/utils/portableText.ts","../src/core/preview/utils/prepareForPreview.ts","../src/core/preview/createPreviewObserver.ts","../src/core/preview/documentPair.ts","../src/core/preview/liveDocumentIdSet.ts","../src/core/releases/util/releasesClient.ts","../src/core/preview/utils/hasEqualFields.ts","../src/core/preview/utils/isUniqueBy.ts","../src/core/util/searchUtils.ts","../src/core/preview/utils/optimizeQuery.ts","../src/core/preview/observeFields.ts","../src/core/preview/observeVersionDocumentIds.ts","../src/core/preview/documentPreviewStore.ts","../src/core/util/apiErrors.ts","../src/core/studio/requestErrors/classify.ts","../src/core/studio/requestErrors/createRequestErrorChannel.ts","../src/core/studio/requestErrors/useStudioErrorHandler.ts","../src/core/store/comlink/createComlinkStore.ts","../src/core/util/catchWithCount.ts","../src/core/store/connection-status/connection-status-store.ts","../src/core/store/document/__telemetry__/documentOutOfSyncEvents.telemetry.ts","../src/core/store/document/__telemetry__/documentPairLoading.telemetry.ts","../src/core/store/document/__telemetry__/documentRebase.telemetry.ts","../src/core/store/document/__telemetry__/listenerLatency.telemetry.ts","../src/core/store/document/__telemetry__/mutationPerformance.telemetry.ts","../src/core/util/getDocumentVariantType.ts","../src/core/store/document/buffered-doc/createObservableBufferedDocument.ts","../src/core/store/document/buffered-doc/createBufferedDocument.ts","../src/core/store/document/debug.ts","../src/core/store/document/utils/dedupeListenerEvents.ts","../src/core/store/document/utils/eventChainUtils.ts","../src/core/store/document/utils/sequentializeListenerEvents.ts","../src/core/store/document/getPairListener.ts","../src/core/store/document/document-pair/utils/actionsApiClient.ts","../src/core/store/document/document-pair/utils/operationsApiClient.ts","../src/core/store/document/document-pair/checkoutPair.ts","../src/core/store/document/utils/createMemoizer.ts","../src/core/store/document/document-pair/memoizeKeyGen.ts","../src/core/store/document/document-pair/memoizedPair.ts","../src/core/store/document/document-pair/commitErrorStatus.ts","../src/core/store/document/document-pair/consistencyStatus.ts","../src/core/store/document/document-pair/documentEvents.ts","../src/core/store/document/document-pair/snapshotPair.ts","../src/core/store/document/document-pair/operationArgs.ts","../src/core/store/document/document-pair/getOperationStoreKey.ts","../src/core/store/document/document-pair/operations/commit.ts","../src/core/store/document/document-pair/utils/assertNotVariantVersion.ts","../src/core/store/document/document-pair/utils/isLiveEditEnabled.ts","../src/core/store/document/document-pair/operations/delete.ts","../src/core/store/document/document-pair/operations/discardChanges.ts","../src/core/store/document/document-pair/operations/duplicate.ts","../src/core/store/document/document-pair/operations/patch.ts","../src/core/store/document/document-pair/operations/publish.ts","../src/core/store/document/document-pair/operations/restore.ts","../src/core/store/document/document-pair/operations/unpublish.ts","../src/core/store/document/document-pair/serverOperations/delete.ts","../src/core/variants/store/constants.ts","../src/core/variants/tool/util.ts","../src/core/variants/documents/getVariantVersionInfo.ts","../src/core/variants/store/variantsClient.ts","../src/core/store/document/document-pair/utils/variantActionsApiClient.ts","../src/core/store/document/document-pair/serverOperations/discardChanges.ts","../src/core/store/document/document-pair/serverOperations/patch.ts","../src/core/store/document/document-pair/serverOperations/publish.ts","../src/core/store/document/document-pair/serverOperations/restore.ts","../src/core/store/document/document-pair/serverOperations/unpublish.ts","../src/core/store/document/document-pair/operationEvents.ts","../src/core/store/document/document-pair/operations/helpers.ts","../src/core/store/document/document-pair/editOperations.ts","../src/core/releases/store/constants.ts","../src/core/releases/util/getReleaseIdFromReleaseDocumentId.ts","../src/core/util/measureFirstEmission.ts","../src/core/store/document/document-pair/editState.ts","../src/core/validation/util/pathToString.ts","../src/core/validation/util/convertToValidationMarker.ts","../src/core/validation/util/localizeMessage.ts","../src/core/validation/util/deepEqualsIgnoreKey.ts","../src/core/validation/util/typeString.ts","../src/core/validation/validators/genericValidator.ts","../src/core/validation/validators/arrayValidator.ts","../src/core/validation/validators/booleanValidator.ts","../src/core/validation/validators/dateValidator.ts","../src/core/validation/validators/numberValidator.ts","../src/core/validation/validators/objectValidator.ts","../src/core/validation/validators/stringValidator.ts","../src/core/validation/Rule.ts","../src/core/validation/validators/slugValidator.ts","../src/core/validation/util/normalizeValidationRules.ts","../src/core/validation/inferFromSchemaType.ts","../src/core/validation/inferFromSchema.ts","../src/core/form/store/conditional-property/resolveConditionalProperty.ts","../src/core/i18n/localeNamespaces.ts","../src/core/i18n/bundles/copy-paste.ts","../src/core/i18n/bundles/feedback.ts","../src/core/i18n/bundles/studio.ts","../src/core/i18n/bundles/validation.ts","../src/core/i18n/locales.ts","../src/core/i18n/fallback.ts","../src/core/validation/util/createBatchedGetDocumentExists.ts","../src/core/validation/util/requestIdleCallback.ts","../src/core/validation/validators/unknownFieldsValidator.ts","../src/core/validation/validateDocument.ts","../src/core/validation/validateDocumentWithReferences.ts","../src/core/store/document/document-pair/validation.ts","../src/core/util/postTask.ts","../src/core/templates/util/isRecord.ts","../src/core/templates/util/deepAssign.ts","../src/core/templates/validate.ts","../src/core/templates/resolve.ts","../src/core/store/document/initialValue/initialValue.ts","../src/core/store/document/listenQuery.ts","../src/core/store/document/normalizeDocumentPairTarget.ts","../src/core/store/document/resolveTypeForDocument.ts","../src/core/store/document/document-store.ts","../../../node_modules/.pnpm/rxjs-etc@10.6.2_rxjs@7.8.2/node_modules/rxjs-etc/dist/esm/operators/refCountDelay.js","../src/core/store/debugParams/debugParams.ts","../src/core/store/grants/debug/exampleGrants.ts","../src/core/store/grants/debug/roleGrants.ts","../src/core/store/grants/grantsStore.ts","../src/core/environment/index.ts","../src/core/store/history/history/chunker.ts","../src/core/store/history/history/utils.ts","../src/core/store/history/history/diffValue.ts","../src/core/store/history/history/TwoEndedArray.ts","../src/core/store/history/history/Timeline.ts","../src/core/store/history/history/Aligner.ts","../src/core/store/history/history/getJsonStream.ts","../src/core/store/history/history/Reconstruction.ts","../src/core/store/history/history/TimelineController.ts","../src/core/store/history/createHistoryStore.ts","../src/core/util/supportsLocalStorage.ts","../src/core/store/key-value/storage/memoryStorage.ts","../src/core/store/key-value/storage/localStoreStorage.ts","../src/core/store/key-value/localStorageSWR.ts","../src/core/store/key-value/storage/serverStorage.ts","../src/core/store/key-value/serverKeyValueStore.ts","../src/core/store/key-value/keyValueStore.ts","../src/core/store/presence/message-transports/bifurTransport.ts","../src/core/store/presence/mock-events.ts","../src/core/store/presence/presence-store.ts","../src/core/store/project/projectStore.ts","../src/core/store/renderingContext/types.ts","../src/core/store/renderingContext/coreUiRenderingContext.ts","../src/core/store/renderingContext/defaultRenderingContext.ts","../src/core/store/renderingContext/listCapabilities.ts","../src/core/store/renderingContext/createRenderingContextStore.ts","../src/core/store/createMultiKeyWeakMap.ts","../src/core/store/ResourceCacheProvider.tsx","../src/core/util/createHookFromObservableFactory.ts","../src/core/store/user/hooks.ts","../src/core/store/user/userStore.ts","../src/core/store/datastores.ts"],"sourcesContent":["import {type Schema} from '@sanity/types'\n\nimport {useSource} from '../studio/source'\n\n/**\n * React hook that returns the schema registry for the current project\n *\n * @public\n * @returns The schema registry for the current project\n * @example Using the `useSchema` hook\n * ```ts\n * function MyComponent() {\n * const schema = useSchema()\n * // ... do something with the schema ...\n * }\n * ```\n */\nexport function useSchema(): Schema {\n return useSource().schema\n}\n","import {useSource} from '../studio/source'\nimport {type Template} from '../templates/types'\n\n/**\n *\n * @hidden\n * @beta\n */\nexport function useTemplates(): Template[] {\n return useSource().templates\n}\n","/**\n * @internal\n */\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value) && typeof value === 'object' && !Array.isArray(value)\n}\n","/**\n * Maximum size in bytes for document IDs in a single query.\n * This matches the limit used in availability.ts and accounts for\n * the Sanity client's max query size with room for headers.\n */\nexport const MAX_DOCUMENT_ID_CHUNK_SIZE = 11164\n","import QuickLRU from 'quick-lru'\nimport {concat, defer, EMPTY, map, type Observable, of, type OperatorFunction} from 'rxjs'\nimport {tap} from 'rxjs/operators'\n\n/**\n * The interface that any caching layer must implement\n * @internal\n */\ninterface SWRCache<T> {\n /**\n * Note: This will throw if key does not exist. Always check for existence with `has` before calling\n */\n get(key: string): T\n has(key: string): boolean\n set(key: string, value: T): void\n delete(key: string): void\n}\n\nconst createSWRCache = createLRUCache\n\n/**\n *\n * Create an SWR (Stale While Revalidate) rxjs operator that will store the latest value in a cache and emit the last know value upon observable subscription\n * @param options - Options\n * @internal\n */\nexport function createSWR<T>(options: {maxSize: number}) {\n const cache = createSWRCache<T>(options)\n return function rxSwr(key: string): OperatorFunction<T, {fromCache: boolean; value: T}> {\n return (input$: Observable<T>) => {\n return concat(\n defer(() => (cache.has(key) ? of({fromCache: true, value: cache.get(key)}) : EMPTY)),\n input$.pipe(\n tap((result) => cache.set(key, result)),\n map((value) => ({\n fromCache: false,\n value: value,\n })),\n ),\n )\n }\n }\n}\n\n/**\n * For now, the only cache layer implemented is an in-memory LRU.\n * @param options - LRU options\n * @internal\n */\nfunction createLRUCache<T>(options: {maxSize: number}): SWRCache<T> {\n const lru = new QuickLRU<string, {value: T}>(options)\n return {\n get(key: string) {\n const entry = lru.get(key)\n if (!entry) {\n throw new Error(`Key not found in LRU cache: ${key}`)\n }\n return entry.value\n },\n set(key: string, value: T) {\n lru.set(key, {value})\n },\n delete(key: string) {\n lru.delete(key)\n },\n has(key: string) {\n return lru.has(key)\n },\n }\n}\n","import {WarningOutlineIcon} from '@sanity/icons/WarningOutline'\nimport {type PreviewValue} from '@sanity/types'\n\nexport const INCLUDE_FIELDS_QUERY = ['_id', '_rev', '_type']\nexport const INCLUDE_FIELDS = [...INCLUDE_FIELDS_QUERY, '_key']\n\n/**\n * How long to wait after the last subscriber has unsubscribed before resetting the observable and disconnecting the listener.\n * We want to keep the listener alive for a short while after the last subscriber has unsubscribed to avoid unnecessary reconnects.\n * Reduced from 10s to 5s to limit concurrent SSE connections during navigation-heavy sessions.\n */\nexport const LISTENER_RESET_DELAY = 5_000\n\nexport const AVAILABILITY_READABLE = {\n available: true,\n reason: 'READABLE',\n} as const\n\nexport const AVAILABILITY_PERMISSION_DENIED = {\n available: false,\n reason: 'PERMISSION_DENIED',\n} as const\n\nexport const AVAILABILITY_NOT_FOUND = {\n available: false,\n reason: 'NOT_FOUND',\n} as const\n\nexport const AVAILABILITY_VERSION_DELETED = {\n available: false,\n reason: 'VERSION_DELETED',\n} as const\n\nexport const INVALID_PREVIEW_FALLBACK: PreviewValue = {\n title: 'Invalid preview config',\n subtitle: 'Check the error log in the console',\n media: <WarningOutlineIcon />,\n}\n\n// oxlint-disable-next-line typescript/prefer-as-const\nexport const DOCUMENT_SYSTEM_FIELD: '_system' = '_system'\n","import {Observable, type Subscriber} from 'rxjs'\n\nimport {isNonNullable} from '../../util/isNonNullable'\n\ninterface QueueItem {\n args: any[]\n observer: Subscriber<any>\n completed: boolean\n}\n\n// Takes an observable returning function and returns a debounced function that, when called\n// collects its passed arguments until wait time has passed without receiving new calls.\n// When wait period is over, calls the original function with the collected arguments\nexport function debounceCollect<Fn extends (...args: any[]) => Observable<any[]>>(\n fn: Fn,\n wait: number,\n): Fn extends (collectedArgs: [...infer TArgs][]) => Observable<(infer TReturnValue)[]>\n ? (...args: TArgs) => Observable<TReturnValue>\n : never\nexport function debounceCollect(fn: any, wait: number) {\n let timer: ReturnType<typeof setTimeout>\n let queue: Record<number | string, QueueItem | undefined> = {}\n let idx = 0\n return function debounced(...args: any[]) {\n return new Observable((obs) => {\n clearTimeout(timer)\n timer = setTimeout(flush, wait)\n const queueItem: QueueItem = {\n args: args,\n observer: obs,\n completed: false,\n }\n const id = idx++\n queue[id] = queueItem\n return () => {\n // console.log('completed', queueItem.args)\n queueItem.completed = true\n }\n })\n }\n\n function flush() {\n const currentlyFlushingQueue = queue\n queue = {}\n\n const queueItemIds = Object.keys(currentlyFlushingQueue) // Todo: use debug\n // .map(id => {\n // if (currentlyFlushingQueue[id].completed) {\n // console.log('Dropped', currentlyFlushingQueue[id].args)\n // }\n // return id\n // })\n .filter((id) => {\n const queueItem = currentlyFlushingQueue[id]\n\n return queueItem && !queueItem.completed\n })\n\n if (queueItemIds.length === 0) {\n // nothing to do\n return\n }\n const collectedArgs = queueItemIds\n .map((id) => {\n const queueItem = currentlyFlushingQueue[id]\n\n return queueItem && queueItem.args\n })\n .filter(isNonNullable)\n fn(collectedArgs).subscribe({\n next(results: any[]) {\n results.forEach((result, i) => {\n const queueItem = currentlyFlushingQueue[queueItemIds[i]]\n if (queueItem && !queueItem.completed) {\n queueItem.observer.next(results[i])\n }\n })\n },\n complete() {\n queueItemIds.forEach((id) => {\n const entry = currentlyFlushingQueue[id]\n if (entry && !entry.completed) {\n entry.observer.complete()\n }\n })\n },\n error(err: Error) {\n queueItemIds.forEach((id) => {\n const entry = currentlyFlushingQueue[id]\n if (entry && !entry.completed) {\n entry.observer.error(err)\n }\n })\n },\n })\n }\n}\n","import {type SanityClient, type StackablePerspective} from '@sanity/client'\nimport flatten from 'lodash-es/flatten.js'\nimport keyBy from 'lodash-es/keyBy.js'\nimport {combineLatest, defer, from, type Observable, of} from 'rxjs'\nimport {distinctUntilChanged, map, mergeMap, reduce, switchMap} from 'rxjs/operators'\nimport shallowEquals from 'shallow-equals'\n\nimport {MAX_DOCUMENT_ID_CHUNK_SIZE} from '../util/const'\nimport {getDraftId, getPublishedId, getVersionId} from '../util/draftUtils'\nimport {isRecord} from '../util/isRecord'\nimport {createSWR} from '../util/rxSwr'\nimport {\n AVAILABILITY_NOT_FOUND,\n AVAILABILITY_PERMISSION_DENIED,\n AVAILABILITY_READABLE,\n AVAILABILITY_VERSION_DELETED,\n} from './constants'\nimport {\n type AvailabilityResponse,\n type DocumentAvailability,\n type DocumentStackAvailability,\n type DraftsModelDocumentAvailability,\n type ObservePathsFn,\n} from './types'\nimport {debounceCollect} from './utils/debounceCollect'\n/**\n * Create an SWR operator for document availability\n */\nconst swr = createSWR<DocumentAvailability>({maxSize: 1000})\n\n/**\n * Takes an array of document IDs and puts them into individual chunks.\n * Because document IDs can vary greatly in size, we want to chunk by the length of the\n * combined comma-separated ID set. We try to stay within 11164 bytes - this is about the\n * same length the Sanity client uses for max query size, and accounts for rather large\n * headers to be present - so this _should_ be safe.\n *\n * @param documentIds - Unique document IDs to chunk\n * @returns Array of document ID chunks\n */\nfunction chunkDocumentIds(documentIds: string[]): string[][] {\n let chunk: string[] = []\n let chunkSize = 0\n\n const chunks: string[][] = []\n\n for (const documentId of documentIds) {\n // Reached the max length? start a new chunk\n if (chunkSize + documentId.length + 1 >= MAX_DOCUMENT_ID_CHUNK_SIZE) {\n chunks.push(chunk)\n chunk = []\n chunkSize = 0\n }\n\n chunkSize += documentId.length + 1 // +1 is to account for a comma between IDs\n chunk.push(documentId)\n }\n\n if (!chunks.includes(chunk)) {\n chunks.push(chunk)\n }\n\n return chunks\n}\n\n/**\n * Mutative concat\n * @param array - the array to concat to\n * @param chunks - the items to concat to the array\n */\nfunction mutConcat<T>(array: T[], chunks: T[]) {\n array.push(...chunks)\n return array\n}\n\nfunction createDocumentAvailabilityObserver(\n versionedClient: SanityClient,\n observePaths: ObservePathsFn,\n): (id: string) => Observable<DocumentAvailability> {\n const fetchDocumentReadability = debounceCollect(function fetchDocumentReadability(\n args: string[][],\n ): Observable<DocumentAvailability[]> {\n const uniqueIds = [...new Set(flatten(args))]\n return from(chunkDocumentIds(uniqueIds)).pipe(\n mergeMap(fetchDocumentReadabilityChunked, 10),\n reduce<DocumentAvailability[], DocumentAvailability[]>(mutConcat, []),\n map((res) => args.map(([id]) => res[uniqueIds.indexOf(id)])),\n )\n }, 1)\n\n function fetchDocumentReadabilityChunked(ids: string[]): Observable<DocumentAvailability[]> {\n return defer(() => {\n const requestOptions = {\n uri: versionedClient.getDataUrl('doc', ids.join(',')),\n json: true,\n query: {excludeContent: 'true'},\n tag: 'preview.documents-availability',\n }\n return versionedClient.observable.request<AvailabilityResponse>(requestOptions).pipe(\n map((response) => {\n const omitted = keyBy(response.omitted || [], (entry) => entry.id)\n return ids.map((id) => {\n const omittedEntry = omitted[id]\n if (!omittedEntry) {\n // it's not omitted, so it exists and is readable\n return AVAILABILITY_READABLE\n }\n if (omittedEntry.reason === 'existence') {\n return AVAILABILITY_NOT_FOUND\n }\n if (omittedEntry.reason === 'permission') {\n // it's not omitted, so it exists and is readable\n return AVAILABILITY_PERMISSION_DENIED\n }\n throw new Error(`Unexpected reason for omission: \"${omittedEntry.reason}\"`)\n })\n }),\n )\n })\n }\n\n /**\n * Observable of metadata for the document with the given id\n * If we can't read a document it is either because it's not readable or because it doesn't exist\n *\n * @internal\n */\n return function observeDocumentAvailability(id: string): Observable<DocumentAvailability> {\n // check for existence first, observePaths is lightweight\n return observePaths({_id: id}, [['_rev'], ['_system']]).pipe(\n map((res) => ({\n hasRev: isRecord(res) && Boolean('_rev' in res && res?._rev),\n isDeleted: isRecord(res) && res._system?.delete === true,\n })),\n distinctUntilChanged(),\n switchMap(({hasRev, isDeleted}) => {\n if (isDeleted) {\n return of(AVAILABILITY_VERSION_DELETED)\n }\n\n return hasRev\n ? // short circuit: if we can read the _rev field we know it both exists and is readable\n of(AVAILABILITY_READABLE)\n : // we can't read the _rev field for two possible reasons: 1) the document isn't readable or 2) the document doesn't exist\n fetchDocumentReadability(id)\n }),\n swr(id),\n map((ev) => ev.value),\n )\n }\n}\n\nfunction ensurePublished(stack: StackablePerspective[]) {\n return stack.includes('published') ? stack : stack.concat(['published'])\n}\n\nexport function createDocumentStackAvailabilityObserver(\n versionedClient: SanityClient,\n observePaths: ObservePathsFn,\n): (id: string, perspective: StackablePerspective[]) => Observable<DocumentStackAvailability[]> {\n const observeDocumentAvailability = createDocumentAvailabilityObserver(\n versionedClient,\n observePaths,\n )\n\n return (id: string, stack: StackablePerspective[]) => {\n return combineLatest(\n // explicitly check availability for published id (we're not using perspective in the following fetch here)\n ensurePublished(stack).map((perspective) => {\n const versionId =\n perspective === 'drafts'\n ? getDraftId(id)\n : perspective === 'published'\n ? getPublishedId(id)\n : getVersionId(id, perspective)\n return observeDocumentAvailability(versionId).pipe(\n map((availability) => ({availability, id: versionId})),\n )\n }),\n )\n }\n}\n\nexport function createPreviewAvailabilityObserver(\n versionedClient: SanityClient,\n observePaths: ObservePathsFn,\n): (id: string) => Observable<DraftsModelDocumentAvailability> {\n const observeDocumentAvailability = createDocumentAvailabilityObserver(\n versionedClient,\n observePaths,\n )\n /**\n * Returns an observable of metadata for a given drafts model document\n */\n return function observeDocumentPairAvailability(\n id: string,\n {version}: {version?: string} = {},\n ): Observable<DraftsModelDocumentAvailability> {\n const draftId = getDraftId(id)\n const publishedId = getPublishedId(id)\n const versionId = version ? getVersionId(id, version) : undefined\n return combineLatest([\n observeDocumentAvailability(draftId),\n observeDocumentAvailability(publishedId),\n ...(versionId ? [observeDocumentAvailability(versionId)] : []),\n ]).pipe(\n distinctUntilChanged(shallowEquals),\n map(([draftReadability, publishedReadability, versionReadability]) => {\n return {\n draft: draftReadability,\n published: publishedReadability,\n ...(versionReadability\n ? {\n version: versionReadability,\n }\n : {}),\n }\n }),\n )\n }\n}\n","import {\n finalize,\n merge,\n type MonoTypeOperatorFunction,\n Observable,\n share,\n type ShareConfig,\n tap,\n} from 'rxjs'\n\nexport type ShareReplayLatestConfig<T> = ShareConfig<T> & {predicate: (value: T) => boolean}\n\n/**\n * A variant of share that takes a predicate function to determine which value to replay to new subscribers\n * @param predicate - Predicate function to determine which value to replay\n */\nexport function shareReplayLatest<T>(predicate: (value: T) => boolean): MonoTypeOperatorFunction<T>\n\n/**\n * A variant of share that takes a predicate function to determine which value to replay to new subscribers\n * @param config - ShareConfig with additional predicate function\n */\nexport function shareReplayLatest<T>(\n config: ShareReplayLatestConfig<T>,\n): MonoTypeOperatorFunction<T>\n\n/**\n * A variant of share that takes a predicate function to determine which value to replay to new subscribers\n * @param configOrPredicate - Predicate function to determine which value to replay\n * @param config - Optional ShareConfig\n */\nexport function shareReplayLatest<T>(\n configOrPredicate: ShareReplayLatestConfig<T> | ShareReplayLatestConfig<T>['predicate'],\n config?: ShareConfig<T>,\n) {\n return _shareReplayLatest(\n typeof configOrPredicate === 'function'\n ? {predicate: configOrPredicate, ...config}\n : configOrPredicate,\n )\n}\nfunction _shareReplayLatest<T>(config: ShareReplayLatestConfig<T>): MonoTypeOperatorFunction<T> {\n return (source: Observable<T>) => {\n let latest: T | undefined\n let emitted = false\n\n const {predicate, ...shareConfig} = config\n\n const wrapped = source.pipe(\n tap((value) => {\n if (config.predicate(value)) {\n emitted = true\n latest = value\n }\n }),\n finalize(() => {\n emitted = false\n latest = undefined\n }),\n share(shareConfig),\n )\n const emitLatest = new Observable<T>((subscriber) => {\n if (emitted) {\n subscriber.next(\n // this cast is safe because of the emitted check which asserts that we got T from the source\n latest as T,\n )\n }\n subscriber.complete()\n })\n return merge(wrapped, emitLatest)\n }\n}\n","import {type SanityClient} from '@sanity/client'\nimport {timer} from 'rxjs'\n\nimport {LISTENER_RESET_DELAY} from './constants'\nimport {shareReplayLatest} from './utils/shareReplayLatest'\n\n/**\n * @internal\n * Creates a listener that will emit 'welcome' for all new subscribers immediately, and thereafter emit at every mutation event\n */\nexport function createGlobalListener(client: SanityClient) {\n return client\n .listen(\n '*',\n {},\n {\n events: ['welcome', 'mutation', 'reconnect'],\n includeResult: false,\n includePreviousRevision: false,\n includeMutations: false,\n includeAllVersions: true,\n visibility: 'query',\n effectFormat: 'mendoza',\n tag: 'preview.global',\n },\n )\n .pipe(\n shareReplayLatest({\n predicate: (event) => event.type === 'welcome' || event.type === 'reconnect',\n resetOnRefCountZero: () => timer(LISTENER_RESET_DELAY),\n }),\n )\n}\n","import {type SanityDocument} from '@sanity/types'\nimport {applyPatch, type RawPatch} from 'mendoza'\n\nfunction omitRev(document: SanityDocument | undefined) {\n if (document === undefined) {\n return undefined\n }\n const {_rev, ...doc} = document\n return doc\n}\n\n/**\n *\n * @param document - The document to apply the patch to\n * @param patch - The mendoza patch to apply\n * @param baseRev - The revision of the document that the patch is calculated from. This is used to ensure that the patch is applied to the correct revision of the document\n */\nexport function applyMendozaPatch<T extends SanityDocument | undefined>(\n document: T,\n patch: RawPatch,\n baseRev: string,\n): T | undefined {\n if (baseRev !== document?._rev) {\n throw new Error(\n 'Invalid document revision. The provided patch is calculated from a different revision than the current document',\n )\n }\n const next = applyPatch(omitRev(document), patch)\n return next === null ? undefined : next\n}\n\nexport function applyMutationEventEffects(\n document: SanityDocument | undefined,\n event: {effects: {apply: RawPatch}; previousRev: string; resultRev: string},\n) {\n if (!event.effects) {\n throw new Error(\n 'Mutation event is missing effects. Is the listener set up with effectFormat=mendoza?',\n )\n }\n const next = applyMendozaPatch(document, event.effects.apply, event.previousRev)\n // next will be undefined in case of deletion\n return next ? {...next, _rev: event.resultRev} : undefined\n}\n","import {type MutationEvent, type SanityClient, type WelcomeEvent} from '@sanity/client'\nimport {type SanityDocument} from '@sanity/types'\nimport memoize from 'lodash-es/memoize.js'\nimport uniq from 'lodash-es/uniq.js'\nimport {type RawPatch} from 'mendoza'\nimport {EMPTY, finalize, type Observable, of} from 'rxjs'\nimport {concatMap, map, scan, shareReplay} from 'rxjs/operators'\n\nimport {applyMutationEventEffects} from './utils/applyMendozaPatch'\nimport {debounceCollect} from './utils/debounceCollect'\n\nexport type ListenerMutationEventLike = Pick<\n MutationEvent,\n 'type' | 'documentId' | 'previousRev' | 'resultRev'\n> & {\n effects?: {\n apply: unknown[]\n }\n}\nexport interface ObserveDocumentAPIConfig {\n dataset?: string\n projectId?: string\n apiVersion?: string\n}\n\nexport function createObserveDocument({\n mutationChannel,\n client,\n}: {\n client: SanityClient\n mutationChannel: Observable<WelcomeEvent | ListenerMutationEventLike>\n}) {\n const getBatchFetcher = memoize(\n function getBatchFetcher(apiConfig: {dataset: string; projectId: string; apiVersion: string}) {\n const _client = client.withConfig(apiConfig)\n\n function batchFetchDocuments(ids: [string][]) {\n return _client.observable\n .fetch(`*[_id in $ids]`, {ids: uniq(ids.flat())}, {tag: 'preview.observe-document'})\n .pipe(map((result) => ids.map(([id]) => result.find((r: {_id: string}) => r._id === id))))\n }\n return debounceCollect(batchFetchDocuments, 100)\n },\n (apiConfig) => apiConfig.dataset + apiConfig.projectId + apiConfig.apiVersion,\n )\n\n const MEMO: Record<string, Observable<SanityDocument | undefined>> = {}\n\n function observeDocument(id: string, apiConfig?: ObserveDocumentAPIConfig) {\n const _apiConfig = {\n dataset: apiConfig?.dataset || client.config().dataset!,\n projectId: apiConfig?.projectId || client.config().projectId!,\n apiVersion: apiConfig?.apiVersion || client.config().apiVersion,\n }\n const fetchDocument = getBatchFetcher(_apiConfig)\n return mutationChannel.pipe(\n concatMap((event) => {\n if (event.type === 'welcome') {\n return fetchDocument(id).pipe(map((document) => ({type: 'sync' as const, document})))\n }\n return event.documentId === id ? of(event) : EMPTY\n }),\n scan((current: SanityDocument | undefined, event) => {\n if (event.type === 'sync') {\n return event.document\n }\n if (event.type === 'mutation') {\n return applyMutationEvent(current, event)\n }\n //@ts-expect-error - this should never happen\n throw new Error(`Unexpected event type: \"${event.type}\"`)\n }, undefined),\n )\n }\n return function memoizedObserveDocument(id: string, apiConfig?: ObserveDocumentAPIConfig) {\n const key = apiConfig ? `${id}-${JSON.stringify(apiConfig)}` : id\n if (!(key in MEMO)) {\n MEMO[key] = observeDocument(id, apiConfig).pipe(\n finalize(() => delete MEMO[key]),\n shareReplay({bufferSize: 1, refCount: true}),\n )\n }\n return MEMO[key]\n }\n}\n\nfunction applyMutationEvent(current: SanityDocument | undefined, event: ListenerMutationEventLike) {\n if (event.previousRev !== current?._rev) {\n console.warn('Document out of sync, skipping mutation')\n return current\n }\n if (!event.effects) {\n throw new Error(\n 'Mutation event is missing effects. Is the listener set up with effectFormat=mendoza?',\n )\n }\n return applyMutationEventEffects(\n current,\n event as {effects: {apply: RawPatch}; previousRev: string; resultRev: string},\n )\n}\n","export function keysOf<T extends object>(value: T) {\n return Object.keys(value) as (keyof T)[]\n}\n","import {\n combineLatest,\n from as observableFrom,\n isObservable,\n Observable,\n of as observableOf,\n} from 'rxjs'\nimport {map, mergeAll, scan, switchMap} from 'rxjs/operators'\n\nimport {keysOf} from './keysOf'\n\nfunction setKey(source: Record<string, unknown>, key: any, value: unknown) {\n return {\n ...source,\n [key]: value,\n }\n}\n\ntype Props<K extends keyof any, T> = {\n [P in K]: T | Observable<T>\n}\n\nexport function props<K extends keyof any, T>(options: {wait?: boolean} = {}) {\n return (source: Observable<Props<K, T>>) => {\n return new Observable<Props<K, T>>((observer) => source.subscribe(observer)).pipe(\n switchMap((object) => {\n const keyObservables = keysOf(object).map((key) => {\n const value = object[key]\n return isObservable(value)\n ? observableFrom(value).pipe(map((val) => [key, val]))\n : observableOf([key, value])\n })\n\n return options.wait\n ? combineLatest(keyObservables).pipe(\n map((pairs) => pairs.reduce((acc, [key, value]) => setKey(acc, key, value), {})),\n )\n : observableFrom(keyObservables).pipe(\n mergeAll(),\n scan((acc, [key, value]) => setKey(acc, key, value), {}),\n )\n }),\n )\n }\n}\n","import {type StackablePerspective} from '@sanity/client'\nimport {isCrossDatasetReference, isReference} from '@sanity/types'\nimport uniq from 'lodash-es/uniq.js'\nimport {type Observable, of as observableOf} from 'rxjs'\nimport {distinctUntilChanged, switchMap} from 'rxjs/operators'\n\nimport {isRecord} from '../util/isRecord'\nimport {type ApiConfig, type FieldName, type Previewable, type PreviewPath} from './types'\nimport {props} from './utils/props'\n\nfunction createEmpty(fields: FieldName[]) {\n return fields.reduce((result: Record<string, undefined>, field) => {\n result[field] = undefined\n return result\n }, {})\n}\n\nfunction resolveMissingHeads(value: Record<string, unknown>, paths: string[][]) {\n return paths.filter((path) => !(path[0] in value))\n}\n\nfunction getDocumentId(value: Previewable) {\n if (isReference(value)) {\n return value._ref\n }\n return '_id' in value ? value._id : undefined\n}\n\ntype ObserveFieldsFn = (\n id: string,\n fields: FieldName[],\n apiConfig?: ApiConfig,\n perspective?: StackablePerspective[],\n) => Observable<Record<string, unknown> | null>\n\nfunction observePaths(\n value: Previewable,\n paths: PreviewPath[],\n observeFields: ObserveFieldsFn,\n apiConfig?: ApiConfig,\n perspective?: StackablePerspective[],\n): Observable<Record<string, unknown> | null> {\n if (!value || typeof value !== 'object') {\n // Reached a leaf. Return as is\n return observableOf(value as null) // @todo\n }\n\n const id = getDocumentId(value)\n\n const currentValue: Record<string, unknown> = id ? {...value, _id: id} : {...value}\n\n if (currentValue._type === 'reference') {\n delete currentValue._type\n delete currentValue._ref\n delete currentValue._weak\n delete currentValue._dataset\n delete currentValue._projectId\n delete currentValue._strengthenOnPublish\n }\n\n const pathsWithMissingHeads = resolveMissingHeads(currentValue, paths)\n\n if (id && pathsWithMissingHeads.length > 0) {\n // Reached a node that is either a document (with _id), or a reference (with _ref) that\n // needs to be \"materialized\"\n\n const nextHeads: string[] = uniq(pathsWithMissingHeads.map((path: string[]) => path[0]))\n\n const refApiConfig = isCrossDatasetReference(value)\n ? {projectId: value._projectId, dataset: value._dataset}\n : apiConfig\n\n return observeFields(id, nextHeads, refApiConfig, perspective).pipe(\n distinctUntilChanged((prev, curr) => prev?._rev === curr?._rev),\n switchMap((snapshot) => {\n if (snapshot === null) {\n return observableOf(null)\n }\n\n return observePaths(\n {\n ...createEmpty(nextHeads),\n ...(isReference(value) ? {...value, ...refApiConfig} : value),\n ...snapshot,\n } as Previewable,\n paths,\n observeFields,\n refApiConfig,\n perspective,\n )\n }),\n )\n }\n\n // We have all the fields needed already present on value\n const leads: Record<string, string[][]> = {}\n paths.forEach((path) => {\n const [head, ...tail] = path\n if (!leads[head]) {\n leads[head] = []\n }\n leads[head].push(tail)\n })\n\n const next = Object.keys(leads).reduce((res: Record<string, unknown>, head) => {\n const tails = leads[head].filter((tail) => tail.length > 0)\n if (tails.length === 0) {\n res[head] =\n isRecord(value) || Array.isArray(value)\n ? (value as Record<string, unknown>)[head]\n : undefined\n } else {\n res[head] = observePaths((value as any)[head], tails, observeFields, apiConfig, perspective)\n }\n return res\n }, currentValue)\n\n return observableOf(next).pipe(props({wait: true}))\n}\n\n// Normalizes path arguments so it supports both dot-paths and array paths, e.g.\n// - ['propA.propB', 'propA.propC']\n// - [['propA', 'propB'], ['propA', 'propC']]\nfunction normalizePaths(path: (FieldName | PreviewPath)[]): PreviewPath[] {\n return path.map((segment: FieldName | PreviewPath) =>\n typeof segment === 'string' ? segment.split('.') : segment,\n )\n}\n\n/**\n * Creates a function that allows observing nested paths on a document.\n * If the path includes a reference, the reference will be \"followed\", allowing for selecting paths within the referenced document.\n * @param options - Requires a function that can observe fields on a document\n * @internal\n */\nexport function createPathObserver(options: {observeFields: ObserveFieldsFn}) {\n const {observeFields} = options\n\n return (\n value: Previewable,\n paths: (FieldName | PreviewPath)[],\n apiConfig?: ApiConfig,\n perspective?: StackablePerspective[],\n ): Observable<Record<string, unknown> | null> => {\n return observePaths(value, normalizePaths(paths), observeFields, apiConfig, perspective)\n }\n}\n","import {type PreviewableType, type PreviewPath} from '../types'\n\nconst DEFAULT_PREVIEW_PATHS: PreviewPath[] = [['_createdAt'], ['_updatedAt']]\n\n/** @internal */\nexport function getPreviewPaths(preview: PreviewableType['preview']): PreviewPath[] | undefined {\n const selection = preview?.select\n\n if (!selection) return undefined\n\n // Transform the selection dot-notation paths into array paths.\n // Example: ['object.title', 'name'] => [['object', 'title'], ['name']]\n const paths = Object.values(selection).map((value) => String(value).split('.')) || []\n\n // Return the paths with the default preview paths appended.\n return paths.concat(DEFAULT_PREVIEW_PATHS)\n}\n","import {isPortableTextSpan, isPortableTextTextBlock, type PortableTextBlock} from '@sanity/types'\n\nexport function isPortableTextPreviewValue(value: unknown): value is PortableTextBlock[] {\n return Array.isArray(value) && (value.length === 0 || value.some(isPortableTextTextBlock))\n}\n\nexport function extractTextFromBlocks(blocks: unknown): string {\n const firstBlock = Array.isArray(blocks) && blocks.find(isPortableTextTextBlock)\n if (!firstBlock || !firstBlock.children) {\n return ''\n }\n\n return firstBlock.children\n .filter(isPortableTextSpan)\n .map((span) => span.text)\n .join('')\n}\n","import {\n isTitledListValue,\n type PrepareViewOptions,\n type PreviewValue,\n type SchemaType,\n type TitledListValue,\n} from '@sanity/types'\nimport debounce from 'lodash-es/debounce.js'\nimport flatten from 'lodash-es/flatten.js'\nimport get from 'lodash-es/get.js'\nimport isPlainObject from 'lodash-es/isPlainObject.js'\nimport pick from 'lodash-es/pick.js'\nimport uniqBy from 'lodash-es/uniqBy.js'\n\nimport {isRecord} from '../../util/isRecord'\nimport {INVALID_PREVIEW_FALLBACK} from '../constants'\nimport {type PreviewableType} from '../types'\nimport {keysOf} from './keysOf'\nimport {extractTextFromBlocks, isPortableTextPreviewValue} from './portableText'\n\nconst PRESERVE_KEYS = ['_id', '_type', '_upload', '_createdAt', '_updatedAt']\nconst EMPTY: never[] = []\n\ntype SelectedValue = Record<string, unknown>\n\nexport type PrepareInvocationResult = {\n selectedValue?: SelectedValue\n returnValue: null | PreviewValue\n errors: Error[]\n}\n\nconst errorCollector = (() => {\n let errorsByType: Record<string, {error: Error; type: PreviewableType; value: SelectedValue}[]> =\n {}\n\n return {\n add: (type: PreviewableType, value: SelectedValue, error: Error) => {\n // cross dataset referenced types have a `type` (string) property instead of `name`\n const typeName = 'name' in type ? type.name : type.type\n if (!errorsByType[typeName]) {\n errorsByType[typeName] = []\n }\n errorsByType[typeName].push({error: error, type: type, value})\n },\n getAll() {\n return errorsByType\n },\n clear() {\n errorsByType = {}\n },\n }\n})()\n\nconst reportErrors = debounce(() => {\n // oxlint-disable no-console\n const errorsByType = errorCollector.getAll()\n const uniqueErrors = flatten(\n Object.keys(errorsByType).map((typeName) => {\n const entries = errorsByType[typeName]\n return uniqBy(entries, (entry) => entry.error.message)\n }),\n )\n const errorCount = uniqueErrors.length\n if (errorCount === 0) {\n return\n }\n\n console.groupCollapsed(\n `%cHeads up! Got ${\n errorCount === 1 ? 'error' : `${errorCount} errors`\n } while preparing data for preview. Click for details.`,\n 'color: #ff7e7c',\n )\n\n Object.keys(errorsByType).forEach((typeName) => {\n const entries = errorsByType[typeName]\n const first = entries[0]\n console.group(`Check the preview config for schema type \"${typeName}\": %o`, first.type.preview)\n const uniqued = uniqBy(entries, (entry) => entry.error.message)\n uniqued.forEach((entry) => {\n if ((entry.error as any).type === 'returnValueError') {\n const hasPrepare = typeof entry.type.preview?.prepare === 'function'\n const {value, error} = entry\n console.log(\n `Encountered an invalid ${\n hasPrepare\n ? 'return value when calling prepare(%o)'\n : 'value targeted by preview.select'\n }:`,\n value,\n )\n console.error(error)\n }\n if ((entry.error as any).type === 'prepareError') {\n const {value, error} = entry\n console.log('Encountered an error when calling prepare(%o):', value)\n console.error(error)\n }\n })\n console.groupEnd()\n })\n console.groupEnd()\n errorCollector.clear()\n // oxlint-enable no-console\n}, 1000)\n\nconst isRenderable =\n (fieldName: string) =>\n (value: unknown): Error[] => {\n const type = typeof value\n if (\n value === null ||\n type === 'undefined' ||\n type === 'string' ||\n type === 'number' ||\n type === 'boolean'\n ) {\n return EMPTY\n }\n return [\n assignType(\n 'returnValueError',\n new Error(\n `The \"${fieldName}\" field should be a string, number, boolean, undefined or null, instead saw ${inspect(\n value,\n )}`,\n ),\n ),\n ]\n }\nconst FIELD_NAME_VALIDATORS: Record<string, (value: unknown) => Error[]> = {\n media: () => {\n // not sure how to validate media as it would possibly involve executing a function and check the\n // return value\n return EMPTY\n },\n title: isRenderable('title'),\n subtitle: isRenderable('subtitle'),\n description: isRenderable('description'),\n imageUrl: isRenderable('imageUrl'),\n date: isRenderable('date'),\n}\n\nfunction inspect(val: unknown, prefixType = true): string {\n if (isRecord(val)) {\n const keys = Object.keys(val)\n const ellipse = keys.length > 3 ? '...' : ''\n const prefix = `object with keys `\n return `${prefixType ? prefix : ''}{${keys.slice(0, 3).join(', ')}${ellipse}}`\n }\n if (Array.isArray(val)) {\n const ellipse = val.length > 3 ? '...' : ''\n const prefix = `array with `\n return `${prefixType ? prefix : ''}[${val.map((v) => inspect(v, false))}${ellipse}]`\n }\n return `the ${typeof val} ${val}`\n}\n\nfunction validateFieldValue(fieldName: string, fieldValue: unknown) {\n if (typeof fieldValue === 'undefined') {\n return EMPTY\n }\n const validator = FIELD_NAME_VALIDATORS[fieldName]\n return (validator && validator(fieldValue)) || EMPTY\n}\n\nfunction assignType(type: string, error: Error) {\n return Object.assign(error, {type})\n}\n\nfunction validatePreparedValue(preparedValue: PreviewValue | null) {\n if (!isPlainObject(preparedValue) || preparedValue === null) {\n return [\n assignType(\n 'returnValueError',\n new Error(\n `Invalid return value. Expected a plain object with at least a 'title' field, instead saw ${inspect(\n preparedValue,\n )}`,\n ),\n ),\n ]\n }\n\n return Object.entries(preparedValue).reduce<Error[]>((acc, [fieldName, fieldValue]) => {\n return [...acc, ...validateFieldValue(fieldName, fieldValue)]\n }, EMPTY)\n}\n\nfunction validateReturnedPreview(result: PrepareInvocationResult) {\n return {\n ...result,\n errors: [...(result.errors || []), ...validatePreparedValue(result.returnValue)],\n }\n}\n\nfunction defaultPrepare(value: SelectedValue) {\n return keysOf(value).reduce((acc: SelectedValue, fieldName: keyof SelectedValue) => {\n const val = value[fieldName]\n return {\n ...acc,\n [fieldName]: isPortableTextPreviewValue(val) ? extractTextFromBlocks(val) : val,\n }\n }, {})\n}\n\nexport function invokePrepare(\n type: PreviewableType,\n value: SelectedValue,\n viewOptions: PrepareViewOptions = {},\n): PrepareInvocationResult {\n const prepare = type.preview?.prepare\n try {\n return {\n returnValue: prepare\n ? (prepare(value, viewOptions) as Record<string, unknown>)\n : defaultPrepare(value),\n errors: EMPTY,\n }\n } catch (error) {\n return {\n returnValue: null,\n errors: [assignType('prepareError', error)],\n }\n }\n}\n\nfunction withErrors(\n result: {errors: Error[]},\n type: PreviewableType,\n selectedValue: SelectedValue,\n): PreviewValue {\n result.errors.forEach((error) => errorCollector.add(type, selectedValue, error))\n reportErrors()\n\n return INVALID_PREVIEW_FALLBACK\n}\n\ninterface EnumListOptions {\n list: TitledListValue[] | unknown[]\n}\n\nfunction hasEnumListOptions(\n type: SchemaType,\n): type is SchemaType & {options: SchemaType['options'] & EnumListOptions} {\n const options = type.options && typeof type.options === 'object' ? type.options : false\n if (!options || !('list' in options)) {\n return false\n }\n\n const listOptions = (options as EnumListOptions).list\n return Array.isArray(listOptions)\n}\n\nfunction getListOptions(type: SchemaType): TitledListValue[] | undefined {\n if (!hasEnumListOptions(type)) {\n return undefined\n }\n\n const listOptions = type.options.list as EnumListOptions['list']\n return listOptions.map((option) =>\n isTitledListValue(option) ? option : ({title: option, value: option} as TitledListValue),\n )\n}\n\n/** @internal */\nexport function prepareForPreview(\n rawValue: unknown,\n type: PreviewableType,\n viewOptions: PrepareViewOptions = {},\n): PreviewValue & {_createdAt?: string; _updatedAt?: string} {\n const hasCustomPrepare = typeof type.preview?.prepare === 'function'\n const selection: Record<string, string> = type.preview?.select || {}\n const targetKeys = Object.keys(selection)\n\n const selectedValue = targetKeys.reduce<Record<string, unknown>>((acc, key) => {\n // Find the field the value belongs to\n const typeWithFields = 'fields' in type ? type : null\n const targetFieldName = selection[key]\n const valueField = typeWithFields?.fields?.find((f) => f.name === targetFieldName)\n const listOptions = valueField && getListOptions(valueField.type)\n\n // If the user has _not_ specified a `prepare()` function for the preview, and the\n // field type has an `options.list`, we want to use the title of the selected item\n // as the preview value. If, however, there _is_ a custom `prepare()`, we leave this\n // mapping up to the user to perform should they want to. This is both to maintain\n // backwards compatiblity, but also to allow using the raw value for prepare operations\n if (!hasCustomPrepare && listOptions) {\n // Find the selected option that matches the raw value\n const selectedOption =\n listOptions && listOptions.find((opt) => opt.value === get(rawValue, selection[key]))\n acc[key] = selectedOption ? selectedOption.value : get(rawValue, selection[key])\n } else {\n acc[key] = get(rawValue, selection[key])\n }\n\n return acc\n }, {})\n\n const prepareResult = invokePrepare(type, selectedValue, viewOptions)\n if (prepareResult.errors.length > 0) {\n return withErrors(prepareResult, type, selectedValue)\n }\n\n const returnValueResult = validateReturnedPreview(prepareResult)\n return returnValueResult.errors.length > 0\n ? withErrors(returnValueResult, type, selectedValue)\n : {...pick(rawValue, PRESERVE_KEYS), ...prepareResult.returnValue}\n}\n","import {type StackablePerspective} from '@sanity/client'\nimport {\n isCrossDatasetReference,\n isCrossDatasetReferenceSchemaType,\n isReferenceSchemaType,\n type PrepareViewOptions,\n} from '@sanity/types'\nimport isPlainObject from 'lodash-es/isPlainObject.js'\nimport {type Observable, of} from 'rxjs'\nimport {map, switchMap} from 'rxjs/operators'\n\nimport {type ObserveForPreviewFn} from './documentPreviewStore'\nimport {\n type ApiConfig,\n type ObserveDocumentTypeFromIdFn,\n type ObservePathsFn,\n type PreparedSnapshot,\n type Previewable,\n type PreviewableType,\n} from './types'\nimport {getPreviewPaths} from './utils/getPreviewPaths'\nimport {invokePrepare, prepareForPreview} from './utils/prepareForPreview'\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return isPlainObject(value)\n}\n\nfunction isReference(value: unknown): value is {_ref: string} {\n return isPlainObject(value)\n}\n\n/**\n * Takes a value and its type and prepares a snapshot for it that can be passed to a preview component\n * @internal\n */\nexport function createPreviewObserver(context: {\n observeDocumentTypeFromId: ObserveDocumentTypeFromIdFn\n observePaths: ObservePathsFn\n}): ObserveForPreviewFn {\n const {observeDocumentTypeFromId, observePaths} = context\n\n return function observeForPreview(\n value: Previewable,\n type: PreviewableType,\n options: {\n viewOptions?: PrepareViewOptions\n apiConfig?: ApiConfig\n perspective?: StackablePerspective[]\n } = {},\n ): Observable<PreparedSnapshot> {\n const {viewOptions = {}, apiConfig, perspective} = options\n if (isCrossDatasetReferenceSchemaType(type)) {\n // if the value is of type crossDatasetReference, but has no _ref property, we cannot prepare any value for the preview\n // and the most appropriate thing to do is to return `undefined` for snapshot\n if (!isCrossDatasetReference(value)) {\n return of({snapshot: undefined})\n }\n\n const refApiConfig = {projectId: value._projectId, dataset: value._dataset}\n\n return observeDocumentTypeFromId(value._ref, refApiConfig, perspective).pipe(\n switchMap((typeName) => {\n if (typeName) {\n const refType = type.to.find((toType) => toType.type === typeName)\n if (refType) {\n return observeForPreview(value, refType, {\n apiConfig: refApiConfig,\n viewOptions,\n perspective,\n })\n }\n }\n return of({snapshot: undefined})\n }),\n )\n }\n if (isReferenceSchemaType(type)) {\n // if the value is of type reference, but has no _ref property, we cannot prepare any value for the preview\n // and the most appropriate thing to do is to return `undefined` for snapshot\n if (!isReference(value)) {\n return of({snapshot: undefined})\n }\n // Previewing references actually means getting the referenced value,\n // and preview using the preview config of its type\n // We do this since there's no way of knowing the type of the referenced value by looking at the reference value alone\n return observeDocumentTypeFromId(value._ref, undefined, perspective).pipe(\n switchMap((typeName) => {\n if (typeName) {\n const refType = type.to.find((toType) => toType.name === typeName)\n if (refType) {\n return observeForPreview(value, refType, {perspective})\n }\n }\n // todo: in case we can't read the document type, we can figure out the reason why e.g. whether it's because\n // the document doesn't exist or it's not readable due to lack of permission.\n // We can use the \"observeDocumentAvailability\" function\n // for this, but currently not sure if needed\n return of({snapshot: undefined})\n }),\n )\n }\n const paths = getPreviewPaths(type.preview)\n if (paths) {\n return observePaths(value, paths, apiConfig, perspective).pipe(\n map((snapshot) => ({\n type: type,\n snapshot: snapshot ? prepareForPreview(snapshot, type, viewOptions) : null,\n })),\n )\n }\n\n // Note: this case is typically rare (or non-existent) and occurs only if\n // the SchemaType doesn't have a `select` field. The schema compiler\n // provides a default `preview` implementation for `object`s, `image`s,\n // `file`s, and `document`s\n return of({\n type,\n snapshot:\n value && isRecord(value) ? invokePrepare(type, value, viewOptions).returnValue : null,\n })\n }\n}\n","import {type SanityDocument} from '@sanity/types'\nimport {combineLatest, type Observable, of} from 'rxjs'\nimport {map, switchMap} from 'rxjs/operators'\n\nimport {getIdPair} from '../util/draftUtils'\nimport {isRecord} from '../util/isRecord'\nimport {\n type DraftsModelDocument,\n type ObserveDocumentAvailabilityFn,\n type ObservePathsFn,\n type PreviewPath,\n} from './types'\n\nexport function createObservePathsDocumentPair(options: {\n observeDocumentPairAvailability: ObserveDocumentAvailabilityFn\n observePaths: ObservePathsFn\n}): <T extends SanityDocument = SanityDocument>(\n id: string,\n paths: PreviewPath[],\n) => Observable<DraftsModelDocument<T>> {\n const {observeDocumentPairAvailability, observePaths} = options\n\n const ALWAYS_INCLUDED_SNAPSHOT_PATHS: PreviewPath[] = [['_updatedAt'], ['_createdAt'], ['_type']]\n\n return function observePathsDocumentPair<T extends SanityDocument = SanityDocument>(\n id: string,\n paths: PreviewPath[],\n {version}: {version?: string} = {},\n ): Observable<DraftsModelDocument<T>> {\n const {draftId, publishedId, versionId} = getIdPair(id, {version})\n\n return observeDocumentPairAvailability(draftId, {version}).pipe(\n switchMap((availability) => {\n if (\n !availability.draft.available &&\n !availability.published.available &&\n !availability.version?.available\n ) {\n // short circuit, neither draft nor published is available so no point in trying to get a snapshot\n return of({\n id: publishedId,\n type: null,\n draft: {\n availability: availability.draft,\n snapshot: undefined,\n },\n published: {\n availability: availability.published,\n snapshot: undefined,\n },\n ...(availability.version\n ? {\n version: {\n availability: availability.version,\n snapshot: undefined,\n },\n }\n : {}),\n })\n }\n\n const snapshotPaths = [...paths, ...ALWAYS_INCLUDED_SNAPSHOT_PATHS]\n\n return combineLatest([\n observePaths({_type: 'reference', _ref: draftId}, snapshotPaths),\n observePaths({_type: 'reference', _ref: publishedId}, snapshotPaths),\n ...(version ? [observePaths({_type: 'reference', _ref: versionId}, snapshotPaths)] : []),\n ]).pipe(\n map(([draftSnapshot, publishedSnapshot, versionSnapshot]) => {\n // note: assume type is always the same\n const type =\n (isRecord(versionSnapshot) && '_type' in versionSnapshot && versionSnapshot._type) ||\n (isRecord(draftSnapshot) && '_type' in draftSnapshot && draftSnapshot._type) ||\n (isRecord(publishedSnapshot) &&\n '_type' in publishedSnapshot &&\n publishedSnapshot._type) ||\n null\n\n return {\n id: publishedId,\n type: typeof type === 'string' ? type : null,\n draft: {\n availability: availability.draft,\n snapshot: draftSnapshot as T,\n },\n published: {\n availability: availability.published,\n snapshot: publishedSnapshot as T,\n },\n ...(availability.version\n ? {\n version: {\n availability: availability.version,\n snapshot: versionSnapshot as T,\n },\n }\n : {}),\n }\n }),\n )\n }),\n )\n }\n}\n","import {type QueryParams, type SanityClient} from '@sanity/client'\nimport sortedIndex from 'lodash-es/sortedIndex.js'\nimport {of} from 'rxjs'\nimport {distinctUntilChanged, filter, map, mergeMap, scan, tap} from 'rxjs/operators'\n\nimport {type SourceClientOptions} from '../config/types'\nimport {versionedClient} from '../studioClient'\n\nexport type DocumentIdSetObserverState = {\n status: 'reconnecting' | 'connected'\n documentIds: string[]\n}\n\ninterface LiveDocumentIdSetOptions {\n insert?: 'sorted' | 'prepend' | 'append'\n apiVersion?: SourceClientOptions['apiVersion']\n}\n\nexport function createDocumentIdSetObserver(client: SanityClient) {\n return function observe(\n queryFilter: string,\n params?: QueryParams,\n options: LiveDocumentIdSetOptions = {},\n ) {\n const {insert: insertOption = 'sorted', apiVersion} = options\n\n const query = `*[${queryFilter}]._id`\n function fetchFilter() {\n return versionedClient(client, apiVersion)\n .observable.fetch(query, params, {\n tag: 'preview.observe-document-set.fetch',\n })\n .pipe(\n tap((result) => {\n if (!Array.isArray(result)) {\n throw new Error(\n `Expected query to return array of documents, but got ${typeof result}`,\n )\n }\n }),\n )\n }\n return versionedClient(client, apiVersion)\n .observable.listen(`*[${queryFilter}]`, params, {\n visibility: 'transaction',\n events: ['welcome', 'mutation', 'reconnect'],\n includeResult: false,\n includeMutations: false,\n includeAllVersions: true,\n tag: 'preview.observe-document-set.listen',\n })\n .pipe(\n mergeMap((event) => {\n return event.type === 'welcome'\n ? fetchFilter().pipe(map((result) => ({type: 'fetch' as const, result})))\n : of(event)\n }),\n scan(\n (\n state: DocumentIdSetObserverState | undefined,\n event,\n ): DocumentIdSetObserverState | undefined => {\n if (event.type === 'reconnect') {\n return {\n documentIds: state?.documentIds || [],\n ...state,\n status: 'reconnecting' as const,\n }\n }\n if (event.type === 'fetch') {\n return {...state, status: 'connected' as const, documentIds: event.result}\n }\n if (event.type === 'mutation') {\n if (event.transition === 'update') {\n // ignore updates, as we're only interested in documents appearing and disappearing from the set\n return state\n }\n if (event.transition === 'appear') {\n return {\n status: 'connected',\n documentIds: insert(state?.documentIds || [], event.documentId, insertOption),\n }\n }\n if (event.transition === 'disappear') {\n return {\n status: 'connected',\n documentIds: state?.documentIds\n ? state.documentIds.filter((id) => id !== event.documentId)\n : [],\n }\n }\n }\n return state\n },\n undefined,\n ),\n distinctUntilChanged(),\n filter(\n (state: DocumentIdSetObserverState | undefined): state is DocumentIdSetObserverState =>\n state !== undefined,\n ),\n )\n }\n}\n\nfunction insert<T>(array: T[], element: T, strategy: 'sorted' | 'prepend' | 'append') {\n let index\n if (strategy === 'prepend') {\n index = 0\n } else if (strategy === 'append') {\n index = array.length\n } else {\n index = sortedIndex(array, element)\n }\n\n return array.toSpliced(index, 0, element)\n}\n","import {type ClientPerspective} from '@sanity/client'\n\nimport {type SourceClientOptions} from '../../config/types'\n\n/**\n * @internal This is the client options used for the releases studio client, using the `X` API version for now\n * Will change to a specific version soon.\n * TODO: Remove after API version is stable and support releases\n */\nexport const RELEASES_STUDIO_CLIENT_OPTIONS: SourceClientOptions = {\n apiVersion: 'v2025-02-19',\n}\n\n/**\n * @internal Checks if the perspective is a release perspective\n * TODO: Remove after API version is stable and support releases\n */\nexport const isReleasePerspective = (\n perspective: ClientPerspective | undefined | string | string[],\n): boolean => {\n if (Array.isArray(perspective)) {\n return true\n }\n return false\n}\n","export function hasEqualFields(fields: string[]) {\n return (object: Record<string, any> | null, otherObject: Record<string, any> | null) => {\n if (object === otherObject) {\n return true\n }\n if (!object || !otherObject) {\n return false\n }\n if (typeof object !== 'object' || typeof otherObject !== 'object') {\n return false\n }\n return fields.every((field) => object[field] === otherObject[field])\n }\n}\n","const id = <T>(value: T): T => value\n\ntype ItemSelector<T> = (element: T) => any\n\n// Takes an array and checks if each item is unique,\n// optionally by specifying an itemSelector function that will be called with\n// each item, returning the value to compare for uniqueness\nexport function isUniqueBy<T>(array: Array<T>, itemSelector: ItemSelector<T> = id): boolean {\n let prevItem\n let currItem\n for (let i = 0; i < array.length; i++) {\n if (i === 0) {\n prevItem = itemSelector(array[i])\n continue\n }\n currItem = itemSelector(array[i])\n if (prevItem !== currItem) {\n return false\n }\n prevItem = currItem\n }\n return true\n}\n","type SearchPathSegment = string | number | []\n\nconst GROQ_KEYWORDS = ['match', 'in', 'asc', 'desc', 'true', 'false', 'null']\nconst VALID_FIELD = /^[a-zA-Z_][a-zA-Z0-9_]*$/\n\n/** @internal */\nexport const fieldNeedsEscape = (fieldName: string): boolean =>\n !VALID_FIELD.test(fieldName) || GROQ_KEYWORDS.includes(fieldName)\n\n/** @internal */\nexport const escapeField = (fieldName: string): string => `[\"${fieldName}\"]`\n\nconst escapeFirst = (fieldName: string): string => `@${escapeField(fieldName)}`\n\nconst isEmptyArray = (value: unknown): value is [] => Array.isArray(value) && value.length === 0\n\n/** @internal */\nexport const joinPath = (pathArray: SearchPathSegment[]): string => {\n let path = ''\n for (let i = 0; i < pathArray.length; i++) {\n const pathSegment = pathArray[i]\n if (isEmptyArray(pathSegment)) {\n path += `[]`\n continue\n }\n\n if (typeof pathSegment === 'number') {\n path += `[${pathSegment}]`\n continue\n }\n\n const isFirst = i === 0\n const needsEscape = fieldNeedsEscape(pathSegment)\n\n if (needsEscape) {\n path = isFirst ? escapeFirst(pathSegment) : `${path}${escapeField(pathSegment)}`\n } else {\n path = isFirst ? pathSegment : `${path}.${pathSegment}`\n }\n }\n\n return path\n}\n","import identity from 'lodash-es/identity.js'\nimport sortBy from 'lodash-es/sortBy.js'\nimport values from 'lodash-es/values.js'\n\nimport {escapeField, fieldNeedsEscape} from '../../util/searchUtils'\nimport {INCLUDE_FIELDS_QUERY} from '../constants'\nimport {type FieldName, type Id, type Selection} from '../types'\n\n/** @internal */\nexport type CombinedSelection = {\n ids: Id[]\n fields: FieldName[]\n map: number[]\n}\n\ntype Doc = {\n _id: string\n}\n\ntype Result = Doc[]\n\nexport function combineSelections(selections: Selection[]): CombinedSelection[] {\n return values(\n selections.reduce((output: {[key: string]: any}, [id, fields], index) => {\n const key = sortBy(fields.join(','), identity).join('.')\n if (!output[key]) {\n output[key] = {fields: fields, ids: [], map: []}\n }\n const idx = output[key].ids.length\n output[key].ids[idx] = id\n output[key].map[idx] = index\n return output\n }, {}),\n )\n}\n\nfunction stringifyId(id: string) {\n return JSON.stringify(id)\n}\n\nconst maybeEscape = (fieldName: string) =>\n fieldNeedsEscape(fieldName) ? `\"${fieldName}\": @${escapeField(fieldName)}` : fieldName\n\nfunction toSubQuery({ids, fields}: {ids: string[]; fields: string[]}) {\n const allFields = [...INCLUDE_FIELDS_QUERY, ...fields]\n return `*[_id in [${ids.map(stringifyId).join(',')}]][0...${ids.length}]{${allFields\n .map(maybeEscape)\n .join(',')}}`\n}\n\nexport function toQuery(combinedSelections: CombinedSelection[]): string {\n return `[${combinedSelections.map(toSubQuery).join(',')}][0...${combinedSelections.length}]`\n}\n\nexport function reassemble(\n queryResult: Result[],\n combinedSelections: CombinedSelection[],\n): (Doc | null)[] {\n return queryResult.reduce((reprojected: (Doc | null)[], subResult, index) => {\n const map = combinedSelections[index].map\n map.forEach((resultIdx, i) => {\n const id = combinedSelections[index].ids[i]\n const found = subResult.find((doc) => doc._id === id)\n reprojected[resultIdx] = found || null\n })\n return reprojected\n }, [])\n}\n","import {type SanityClient, type StackablePerspective} from '@sanity/client'\nimport difference from 'lodash-es/difference.js'\nimport flatten from 'lodash-es/flatten.js'\nimport memoize from 'lodash-es/memoize.js'\nimport {\n combineLatest,\n concat,\n defer,\n EMPTY,\n from,\n fromEvent,\n merge,\n type Observable,\n of,\n retry,\n timer,\n} from 'rxjs'\nimport {\n distinctUntilChanged,\n filter,\n map,\n mergeMap,\n reduce,\n share,\n shareReplay,\n startWith,\n switchMap,\n tap,\n} from 'rxjs/operators'\n\nimport {RELEASES_STUDIO_CLIENT_OPTIONS} from '../releases/util/releasesClient'\nimport {versionedClient} from '../studioClient'\nimport {MAX_DOCUMENT_ID_CHUNK_SIZE} from '../util/const'\nimport {getPublishedId, idMatchesPerspective, isVersionId} from '../util/draftUtils'\nimport {INCLUDE_FIELDS} from './constants'\nimport {\n type ApiConfig,\n type FieldName,\n type Id,\n type InvalidationChannelEvent,\n type Selection,\n} from './types'\nimport {debounceCollect} from './utils/debounceCollect'\nimport {hasEqualFields} from './utils/hasEqualFields'\nimport {isUniqueBy} from './utils/isUniqueBy'\nimport {type CombinedSelection, combineSelections, reassemble, toQuery} from './utils/optimizeQuery'\n\n/**\n * Chunks combined selections into smaller groups based on the total byte size of document IDs.\n * This prevents queries from becoming too large and timing out.\n *\n * Similar to chunkDocumentIds in availability.ts, but handles CombinedSelection structure.\n *\n * @param combinedSelections - The combined selections to chunk\n * @returns Array of chunked combined selections, each within the size limit\n * @internal\n */\nexport function chunkCombinedSelections(\n combinedSelections: CombinedSelection[],\n): CombinedSelection[][] {\n const chunks: CombinedSelection[][] = []\n\n for (const selection of combinedSelections) {\n let chunk: string[] = []\n let chunkMap: number[] = []\n let chunkSize = 0\n\n for (let i = 0; i < selection.ids.length; i++) {\n const id = selection.ids[i]\n // +3 accounts for quotes and comma in GROQ request structure: [\"id1\",\"id2\"]\n const idSize = id.length + 3\n\n // Reached the max length? Start a new chunk\n if (chunkSize + idSize >= MAX_DOCUMENT_ID_CHUNK_SIZE && chunk.length > 0) {\n chunks.push([{ids: chunk, fields: selection.fields, map: chunkMap}])\n chunk = []\n chunkMap = []\n chunkSize = 0\n }\n\n chunk.push(id)\n chunkMap.push(selection.map[i])\n chunkSize += idSize\n }\n\n // Push overflowing IDs to the last chunk\n // If there are any remaining IDs from the previous check\n if (chunk.length > 0) {\n chunks.push([{ids: chunk, fields: selection.fields, map: chunkMap}])\n }\n }\n\n return chunks\n}\n\ntype CachedFieldObserver = {\n id: Id\n fields: FieldName[]\n changes$: Observable<any>\n}\n\ntype Cache = {\n [id: string]: CachedFieldObserver[]\n}\n\n/**\n * Note: this should be the minimal interface createObserveFields needs to function\n * It should be kept compatible with the Sanity Client\n */\nexport interface ClientLike {\n withConfig(config: ApiConfig): ClientLike\n observable: {\n fetch: (\n query: string,\n params: Record<string, string>,\n options: {tag: string},\n ) => Observable<unknown>\n }\n}\n\n/**\n * Creates a function that allows observing individual fields on a document.\n * It will automatically debounce and batch requests, and maintain an in-memory cache of the latest field values\n * @param options - Options to use when creating the observer\n * @internal\n */\nexport function createObserveFields(options: {\n client: SanityClient\n invalidationChannel: Observable<InvalidationChannelEvent>\n}) {\n const {client: currentDatasetClient, invalidationChannel} = options\n\n function fetchAllDocumentPathsWith(client: SanityClient, perspective?: StackablePerspective[]) {\n return function fetchAllDocumentPath(selections: Selection[]) {\n const combinedSelections = combineSelections(selections)\n // If any document is a version document we need to use the release API version\n const useReleaseVersion =\n (perspective && perspective.length > 0) ||\n combinedSelections.some((selection) => selection.ids.some(isVersionId))\n\n const apiClient = versionedClient(\n client,\n useReleaseVersion ? RELEASES_STUDIO_CLIENT_OPTIONS.apiVersion : undefined,\n )\n\n // Chunk the selections to avoid massive queries that timeout\n const selectionChunks = chunkCombinedSelections(combinedSelections)\n\n // Helper to fetch a single chunk\n const fetchChunk = (chunk: CombinedSelection[]) =>\n apiClient.observable\n .fetch(toQuery(chunk), {}, {tag: 'preview.document-paths', perspective})\n .pipe(\n retry({\n delay: (_: unknown, attempt) => timer(Math.min(30_000, attempt * 1000)),\n }),\n map((result: any) => reassemble(result, chunk)),\n )\n\n // No chunks - return empty array early\n if (selectionChunks.length === 0) {\n return of([])\n }\n\n // Single chunk - no merging needed (most common case)\n // Kept for performance reasons, as it is the common case (no massive releases) and faster\n if (selectionChunks.length === 1) {\n return fetchChunk(selectionChunks[0])\n }\n\n // Multiple chunks - fetch in parallel and merge results\n // Each chunk's reassemble places results at their original map indices\n // We collect all results and build the final array at the end\n const totalSelections = selections.length\n return from(selectionChunks).pipe(\n mergeMap(fetchChunk, 10),\n reduce((merged: (Record<string, any> | null)[], chunkResults) => {\n chunkResults.forEach((result, idx) => {\n if (result !== null && result !== undefined) merged[idx] = result\n })\n return merged\n }, new Array(totalSelections).fill(null)),\n )\n }\n }\n const batchFetchersCache = new Map()\n function getBatchFetchersForPerspective(perspective?: StackablePerspective[]) {\n const key = perspective?.join('-') || 'raw'\n if (batchFetchersCache.has(key)) {\n return batchFetchersCache.get(key)\n }\n const batchFetchers = {\n fast: debounceCollect(fetchAllDocumentPathsWith(currentDatasetClient, perspective), 100),\n slow: debounceCollect(fetchAllDocumentPathsWith(currentDatasetClient, perspective), 1000),\n }\n batchFetchersCache.set(key, batchFetchers)\n return batchFetchers\n }\n\n function currentDatasetListenFields(\n documentId: Id,\n fields: FieldName[],\n perspective?: StackablePerspective[],\n ) {\n const {fast: fetchDocumentPathsFast, slow: fetchDocumentPathsSlow} =\n getBatchFetchersForPerspective(perspective)\n\n const hasPerspective = perspective && perspective.length > 0\n /**\n * Q: Why are we using published id if perspective is provided?\n * A: Normally, queries for fetching preview values will be based on the _id of the document,\n * for example `*[_id == \"drafts.foo\"]`. However, if a perspective passed, the query\n * `*[_id == \"drafts.foo\"]` will not match anything since the `_id` will always be the published id\n * Therefore, if perspective is provided, we need to refetch using the published id instead.\n */\n const fetchId = hasPerspective ? getPublishedId(documentId) : documentId\n\n return invalidationChannel.pipe(\n filter((event) => {\n // we always want to fetch when the listener just (re) connected\n if (event.type === 'connected') {\n return true\n }\n if (hasPerspective) {\n // With perspectives, refetch only when the mutated document is a\n // version of the observed document (same base/published id) AND that\n // version is relevant to the current perspective stack (e.g. drafts,\n // a specific release). This avoids refetching for unrelated documents\n // or versions outside the active perspective.\n return (\n getPublishedId(event.documentId) === getPublishedId(documentId) &&\n idMatchesPerspective(perspective, event.documentId)\n )\n }\n // if not using perspective, refetch previews for the document that was actually changed\n return event.documentId === documentId\n }),\n switchMap((event) => {\n if (event.type === 'connected' || event.visibility === 'query') {\n return fetchDocumentPathsFast(fetchId, fields).pipe(\n mergeMap((result) => {\n return concat(\n of(result),\n result === null // hack: if we get undefined as result here it can be because the document has\n ? // just been created and is not yet indexed. We therefore need to wait a bit\n // and then re-fetch.\n fetchDocumentPathsSlow(fetchId, fields)\n : [],\n )\n }),\n )\n }\n return fetchDocumentPathsSlow(fetchId, fields)\n }),\n )\n }\n\n const CACHE: Cache = {} // todo: use a LRU cache instead (e.g. hashlru or quick-lru)\n\n const getBatchFetcherForDataset = memoize(\n function getBatchFetcherForDataset(apiConfig: ApiConfig) {\n const client = currentDatasetClient.withConfig(apiConfig)\n const fetchAll = fetchAllDocumentPathsWith(client, ['drafts'])\n return debounceCollect(fetchAll, 10)\n },\n (apiConfig) => apiConfig.dataset + apiConfig.projectId,\n )\n\n const CROSS_DATASET_PREVIEW_POLL_INTERVAL = 10000\n // We want to poll for changes in the other dataset, but only when window/tab is visible\n // This sets up a shared stream that emits an event every `POLL_INTERVAL` milliseconds as long as the\n // document is visible. It starts emitting immediately (if the page is visible)\n const visiblePoll$ = fromEvent(document, 'visibilitychange').pipe(\n startWith(0),\n map(() => document.visibilityState === 'visible'),\n switchMap((visible) => (visible ? timer(0, CROSS_DATASET_PREVIEW_POLL_INTERVAL) : EMPTY)),\n share(),\n )\n\n function crossDatasetListenFields(id: Id, fields: FieldName[], apiConfig: ApiConfig) {\n return visiblePoll$.pipe(startWith(0)).pipe(\n switchMap(() => {\n const batchFetcher = getBatchFetcherForDataset(apiConfig)\n return batchFetcher(id, fields)\n }),\n )\n }\n\n function createCachedFieldObserver<T>(\n id: string,\n fields: FieldName[],\n apiConfig?: ApiConfig,\n perspective?: StackablePerspective[],\n ): CachedFieldObserver {\n // Note: `undefined` means the memo has not been set, while `null` means the memo is explicitly set to null (e.g. we did fetch, but got null back)\n let latest: T | undefined | null\n const changes$ = merge(\n defer(() => (latest === undefined ? EMPTY : of(latest))),\n (apiConfig\n ? (crossDatasetListenFields(id, fields, apiConfig) as any)\n : currentDatasetListenFields(id, fields, perspective)) as Observable<T>,\n ).pipe(\n tap((v: T | null) => (latest = v)),\n shareReplay({refCount: true, bufferSize: 1}),\n )\n\n return {id, fields, changes$}\n }\n\n function cachedObserveFields(\n id: Id,\n fields: FieldName[],\n apiConfig?: ApiConfig,\n perspective?: StackablePerspective[],\n ) {\n const cacheKey = apiConfig\n ? `${apiConfig.projectId}:${apiConfig.dataset}:${id}`\n : `$current$-${id}-${perspective?.join('-') || 'raw'}`\n\n if (!(cacheKey in CACHE)) {\n CACHE[cacheKey] = []\n }\n\n const existingObservers = CACHE[cacheKey]\n const missingFields = difference(\n fields,\n flatten(existingObservers.map((cachedFieldObserver) => cachedFieldObserver.fields)),\n )\n\n if (missingFields.length > 0) {\n existingObservers.push(createCachedFieldObserver(id, fields, apiConfig, perspective))\n }\n\n const cachedFieldObservers = existingObservers\n .filter((observer) => observer.fields.some((fieldName) => fields.includes(fieldName)))\n .map((cached) => cached.changes$)\n\n return combineLatest(cachedFieldObservers).pipe(\n // in the event that a document gets deleted, the cached values will be updated to store `undefined`\n // if this happens, we should not pick any fields from it, but rather just return null\n map((snapshots) => snapshots.filter(Boolean)), // make sure all snapshots agree on same revision\n filter((snapshots) => isUniqueBy(snapshots, (snapshot) => snapshot._rev)), // pass on value with the requested fields (or null if value is deleted)\n map((snapshots) => (snapshots.length === 0 ? null : pickFrom(snapshots, fields))), // emit values only if changed\n distinctUntilChanged(hasEqualFields(fields)),\n )\n }\n\n return cachedObserveFields\n\n function pickFrom(objects: Record<string, any>[], fields: string[]) {\n return [...INCLUDE_FIELDS, ...fields].reduce((result, fieldName) => {\n const value = getFirstFieldValue(objects, fieldName)\n if (value !== undefined) {\n ;(result as any)[fieldName] = value\n }\n return result\n }, {})\n }\n\n function getFirstFieldValue(objects: Record<string, any>[], fieldName: string) {\n let value\n objects.some((object) => {\n if (fieldName in object) {\n value = object[fieldName]\n return true\n }\n return false\n })\n return value\n }\n}\n","import {type SanityClient} from '@sanity/client'\nimport isEqual from 'lodash-es/isEqual.js'\nimport {concat, from, type Observable, of, type OperatorFunction, retry, Subject, timer} from 'rxjs'\nimport {\n bufferWhen,\n distinctUntilChanged,\n filter,\n finalize,\n map,\n mergeMap,\n shareReplay,\n switchMap,\n tap,\n toArray,\n} from 'rxjs/operators'\n\nimport {RELEASES_STUDIO_CLIENT_OPTIONS} from '../releases/util/releasesClient'\nimport {versionedClient} from '../studioClient'\nimport {MAX_DOCUMENT_ID_CHUNK_SIZE} from '../util/const'\nimport {getPublishedId} from '../util/draftUtils'\nimport {type InvalidationChannelEvent} from './types'\nimport {debounceCollect} from './utils/debounceCollect'\n\n/**\n * Approximate per-id overhead of a single document group member subquery.\n */\nconst VERSION_OF_QUERY_OVERHEAD = '*[sanity::versionOf(\"\")]._id,'.length\n\n/**\n * Maximum number of batch queries to keep in flight at once.\n */\nconst MAX_CONCURRENT_BATCH_FETCHES = 10\n\n/**\n * Create a function that observes the set of version and variant document ids\n * that exist for the provided document group id.\n *\n * Unlike `createDocumentIdSetObserver`, which opens a dedicated listener for\n * each document group id, this observer is driven by the shared global\n * `invalidationChannel`. It condenses the queries for all observed document\n * group ids into a single GROQ query (one `sanity::versionOf()` call per id),\n * batching the request if it exceeds `MAX_DOCUMENT_ID_BATCH_SIZE`.\n *\n * @internal\n */\nexport function createObserveVersionDocumentIds(options: {\n client: SanityClient\n invalidationChannel: Observable<InvalidationChannelEvent>\n}): (documentGroupId: string) => Observable<string[]> {\n const {client, invalidationChannel} = options\n const releasesClient = versionedClient(client, RELEASES_STUDIO_CLIENT_OPTIONS.apiVersion)\n\n const fetchFast = debounceCollect(\n (collectedArgs: [documentGroupId: string][]) =>\n fetchVersionIdSets(releasesClient, collectedArgs),\n 100,\n )\n\n const fetchSlow = debounceCollect(\n (collectedArgs: [documentGroupId: string][]) =>\n fetchVersionIdSets(releasesClient, collectedArgs),\n 1000,\n )\n\n const cache = new Map<string, Observable<string[]>>()\n\n return function observeVersionDocumentIds(documentGroupId: string): Observable<string[]> {\n const cachedInstance = cache.get(documentGroupId)\n\n if (cachedInstance) {\n return cachedInstance\n }\n\n const instance = invalidationChannel.pipe(\n filter(\n (event) =>\n event.type === 'connected' || getPublishedId(event.documentId) === documentGroupId,\n ),\n switchMap((event) => {\n if (event.type === 'connected' || event.visibility === 'query') {\n return fetchFast(documentGroupId).pipe(\n mergeMap((ids) => {\n // A newly created version may not be indexed yet when its mutation\n // event arrives. If the mutated document isn't reflected in the\n // fresh result, schedule a slow refetch to catch up (mirroring the\n // fast/slow fallback in `observeFields`).\n const maybeIndexPending =\n event.type === 'mutation' &&\n event.documentId !== documentGroupId &&\n !ids.includes(event.documentId)\n\n if (maybeIndexPending) {\n return concat(of(ids), fetchSlow(documentGroupId))\n }\n\n return of(ids)\n }),\n )\n }\n return fetchSlow(documentGroupId)\n }),\n distinctUntilChanged(isEqual),\n finalize(() => cache.delete(documentGroupId)),\n shareReplay({\n refCount: true,\n bufferSize: 1,\n }),\n )\n\n cache.set(documentGroupId, instance)\n return instance\n }\n}\n\n/**\n * Buffer source values into batches, closing the current batch just before a\n * value would push its cumulative byte size to or beyond `maxBytes`. The\n * overflowing value becomes the first entry of the next batch; a value whose\n * own size already meets the limit is emitted as a single-element batch.\n *\n * @internal\n */\nexport function bufferByByteSize<Type extends string>(\n byteSize: (value: Type) => number,\n maxBytes: number,\n): OperatorFunction<Type, Type[]> {\n return (source) => {\n const closeBuffer = new Subject<void>()\n let bufferedBytes = 0\n\n return source.pipe(\n tap((value) => {\n const size = byteSize(value)\n // Close the current (non-empty) buffer before this value would exceed\n // the limit, so the overflowing value becomes the first entry of the\n // next buffer instead.\n if (bufferedBytes > 0 && bufferedBytes + size >= maxBytes) {\n bufferedBytes = 0\n closeBuffer.next()\n }\n bufferedBytes += size\n }),\n bufferWhen(() => closeBuffer),\n )\n }\n}\n\nfunction buildQuery(documentGroupIds: string[]): string {\n const subQueries = documentGroupIds.map((id) => `*[sanity::versionOf(${JSON.stringify(id)})]._id`)\n return `[${subQueries.join(',')}]`\n}\n\nfunction fetchBatch(client: SanityClient, ids: string[]): Observable<string[][]> {\n return client.observable\n .fetch<string[][]>(buildQuery(ids), {}, {tag: 'preview.observe-version-ids'})\n .pipe(\n retry({delay: (_: unknown, attempt) => timer(Math.min(30_000, attempt * 1000))}),\n // Sort each set ascending so consumers get a stable order.\n map((result) => result.map((versionIds) => [...versionIds].sort())),\n )\n}\n\nfunction fetchVersionIdSets(\n client: SanityClient,\n collectedArgs: [documentGroupIds: string][],\n): Observable<string[][]> {\n const documentGroupIds = collectedArgs.map(([documentGroupId]) => documentGroupId)\n\n if (documentGroupIds.length === 0) {\n return of([])\n }\n\n return from(documentGroupIds).pipe(\n // Split into batches small enough that each combined query stays within the\n // max query size.\n bufferByByteSize((id) => id.length + VERSION_OF_QUERY_OVERHEAD, MAX_DOCUMENT_ID_CHUNK_SIZE),\n // Fetch batches in parallel, tracking each batch's position so results can\n // be reordered.\n mergeMap(\n (batch, index) => fetchBatch(client, batch).pipe(map((result) => ({index, result}))),\n MAX_CONCURRENT_BATCH_FETCHES,\n ),\n toArray(),\n // Restore source order (parallel fetches may settle out of order), and\n // flatten the batch results back into a single array aligned with\n // `documentGroupIds`.\n map((settled) => settled.sort((a, b) => a.index - b.index).flatMap(({result}) => result)),\n )\n}\n","import {\n type MutationEvent,\n type QueryParams,\n type SanityClient,\n type StackablePerspective,\n type WelcomeEvent,\n} from '@sanity/client'\nimport {type DocumentSystem, type PrepareViewOptions, type SanityDocument} from '@sanity/types'\nimport {combineLatest, type Observable} from 'rxjs'\nimport {distinctUntilChanged, filter, map} from 'rxjs/operators'\n\nimport {isRecord} from '../util/isRecord'\nimport {\n createDocumentStackAvailabilityObserver,\n createPreviewAvailabilityObserver,\n} from './availability'\nimport {DOCUMENT_SYSTEM_FIELD} from './constants'\nimport {createGlobalListener} from './createGlobalListener'\nimport {createObserveDocument, type ObserveDocumentAPIConfig} from './createObserveDocument'\nimport {createPathObserver} from './createPathObserver'\nimport {createPreviewObserver} from './createPreviewObserver'\nimport {createObservePathsDocumentPair} from './documentPair'\nimport {createDocumentIdSetObserver, type DocumentIdSetObserverState} from './liveDocumentIdSet'\nimport {createObserveFields} from './observeFields'\nimport {createObserveVersionDocumentIds} from './observeVersionDocumentIds'\nimport {\n type ApiConfig,\n type DocumentStackAvailability,\n type DraftsModelDocument,\n type DraftsModelDocumentAvailability,\n type ObservePathsFn,\n type PreparedSnapshot,\n type Previewable,\n type PreviewableType,\n type PreviewPath,\n} from './types'\n\n/**\n * @hidden\n * @beta */\nexport type ObserveForPreviewFn = (\n value: Previewable,\n type: PreviewableType,\n options?: {\n viewOptions?: PrepareViewOptions\n perspective?: StackablePerspective[]\n apiConfig?: ApiConfig\n },\n) => Observable<PreparedSnapshot>\n\n/**\n * The document preview store supports subscribing to content for previewing purposes.\n * Documents observed by this store will be kept in sync and receive real-time updates from all collaborators,\n * but has no support for optimistic updates, so any local edits will require a server round-trip before becoming visible,\n * which means this store is less suitable for real-time editing scenarios.\n *\n * @hidden\n * @beta */\nexport interface DocumentPreviewStore {\n observePaths: ObservePathsFn\n observeForPreview: ObserveForPreviewFn\n observeDocumentTypeFromId: (\n id: string,\n apiConfig?: ApiConfig,\n perspective?: StackablePerspective[],\n ) => Observable<string | undefined>\n observeDocumentSystemFromId: (\n id: string,\n apiConfig?: ApiConfig,\n perspective?: StackablePerspective[],\n ) => Observable<DocumentSystem | undefined>\n\n /**\n *\n * @hidden\n * @beta\n */\n unstable_observeDocumentPairAvailability: (\n id: string,\n options?: {version?: string},\n ) => Observable<DraftsModelDocumentAvailability>\n\n /**\n *\n * @hidden\n * @beta\n */\n unstable_observeDocumentStackAvailability: (\n id: string,\n perspectiveStack: StackablePerspective[],\n ) => Observable<DocumentStackAvailability[]>\n\n unstable_observePathsDocumentPair: <T extends SanityDocument = SanityDocument>(\n id: string,\n paths: PreviewPath[],\n options?: {version?: string},\n ) => Observable<DraftsModelDocument<T>>\n\n /**\n * Observes a set of document IDs that matches the given groq-filter. The document ids are returned in ascending order and will update in real-time\n * Whenever a document appears or disappears from the set, a new array with the updated set of IDs will be pushed to subscribers.\n * The query is performed once, initially, and thereafter the set of ids are patched based on the `appear` and `disappear`\n * transitions on the received listener events.\n * This provides a lightweight way of subscribing to a list of ids for simple cases where you just want to subscribe to a set of documents ids\n * that matches a particular filter.\n *\n * @hidden\n * @beta\n * @param filter - A groq filter to use for the document set\n * @param params - Parameters to use with the groq filter\n * @param options - Options for the observer\n * @param apiVersion - Specify the API version to use for the query\n */\n unstable_observeDocumentIdSet: (\n filter: string,\n params?: QueryParams,\n options?: {\n /**\n * Where to insert new items into the set. Defaults to 'sorted' which is based on the lexicographic order of the id\n */\n insert?: 'sorted' | 'prepend' | 'append'\n apiVersion?: string\n },\n ) => Observable<DocumentIdSetObserverState>\n\n /**\n * Observes the set of version and variant document ids that exist for a given\n * document group id.\n *\n * Unlike `unstable_observeDocumentIdSet`, this does not open a dedicated\n * real-time listener for each published id. Instead, it is driven by the\n * shared global listener and batches the discovery queries for all observed\n * document group ids into a single combined query, returning the ids in\n * ascending order.\n *\n * @hidden\n * @beta\n */\n unstable_observeVersionDocumentIds: (publishedId: string) => Observable<string[]>\n\n /**\n * Observe a complete document with the given ID\n *\n * @hidden\n * @beta\n */\n unstable_observeDocument: (\n id: string,\n clientConfig?: ObserveDocumentAPIConfig,\n ) => Observable<SanityDocument | undefined>\n\n /**\n * Observe a list of complete documents with the given IDs\n *\n * @hidden\n * @beta\n */\n unstable_observeDocuments: (\n ids: string[],\n clientConfig?: ObserveDocumentAPIConfig,\n ) => Observable<(SanityDocument | undefined)[]>\n}\n\n/** @internal */\nexport interface DocumentPreviewStoreOptions {\n client: SanityClient\n}\n\n/** @internal */\nexport function createDocumentPreviewStore({\n client,\n}: DocumentPreviewStoreOptions): DocumentPreviewStore {\n const versionedClient = client.withConfig({apiVersion: '2025-02-19'})\n const globalListener = createGlobalListener(versionedClient).pipe(\n filter(\n (event): event is MutationEvent | WelcomeEvent =>\n // ignore reconnect events for now until we've verified that downstream consumers can handle them\n event.type === 'mutation' || event.type === 'welcome',\n ),\n )\n const invalidationChannel = globalListener.pipe(\n map((event) => (event.type === 'welcome' ? {type: 'connected' as const} : event)),\n )\n\n const observeDocument = createObserveDocument({client, mutationChannel: globalListener})\n const observeFields = createObserveFields({client: versionedClient, invalidationChannel})\n const observePaths = createPathObserver({observeFields})\n\n function observeDocumentTypeFromId(\n id: string,\n apiConfig?: ApiConfig,\n perspective?: StackablePerspective[],\n ): Observable<string | undefined> {\n return observePaths({_type: 'reference', _ref: id}, ['_type'], apiConfig, perspective).pipe(\n map((res) => (isRecord(res) && typeof res._type === 'string' ? res._type : undefined)),\n distinctUntilChanged(),\n )\n }\n function observeDocumentSystemFromId(\n id: string,\n apiConfig?: ApiConfig,\n perspective?: StackablePerspective[],\n // TODO: This shouldn't be undefined once the documents are migrated.\n ): Observable<DocumentSystem | undefined> {\n return observePaths(\n {_type: 'reference', _ref: id},\n [DOCUMENT_SYSTEM_FIELD],\n apiConfig,\n perspective,\n ).pipe(\n map((res) =>\n isRecord(res) && isRecord(res[DOCUMENT_SYSTEM_FIELD])\n ? (res[DOCUMENT_SYSTEM_FIELD] as unknown as DocumentSystem)\n : undefined,\n ),\n distinctUntilChanged(),\n )\n }\n\n const observeDocumentIdSet = createDocumentIdSetObserver(versionedClient)\n\n const observeVersionDocumentIds = createObserveVersionDocumentIds({\n client: versionedClient,\n invalidationChannel,\n })\n\n const observeForPreview = createPreviewObserver({observeDocumentTypeFromId, observePaths})\n\n const observeDocumentStackAvailability = createDocumentStackAvailabilityObserver(\n versionedClient,\n observePaths,\n )\n const observeDocumentPairAvailability = createPreviewAvailabilityObserver(\n versionedClient,\n observePaths,\n )\n\n const observePathsDocumentPair = createObservePathsDocumentPair({\n observeDocumentPairAvailability,\n observePaths,\n })\n\n // @todo: explain why the API is like this now, and that it should not be like this in the future!\n\n return {\n observePaths,\n observeForPreview,\n observeDocumentTypeFromId,\n observeDocumentSystemFromId,\n unstable_observeDocumentIdSet: observeDocumentIdSet,\n unstable_observeVersionDocumentIds: observeVersionDocumentIds,\n unstable_observeDocument: observeDocument,\n unstable_observeDocuments: (ids: string[]) =>\n combineLatest(ids.map((id) => observeDocument(id))),\n unstable_observeDocumentPairAvailability: observeDocumentPairAvailability,\n unstable_observeDocumentStackAvailability: observeDocumentStackAvailability,\n unstable_observePathsDocumentPair: observePathsDocumentPair,\n }\n}\n","import {ClientError} from '@sanity/client'\n\n/** @internal */\nexport function isUnauthorizedError(err: unknown): err is ClientError {\n return err instanceof ClientError && err.statusCode === 401\n}\n\n/**\n * Error codes the API uses on 401s that positively signal an invalid session:\n * - `SIO-401-AEX`: the session has expired\n * - `SIO-401-ANF`: the token resolves to no session at all (\"Session not\n * found\" — revoked on another device, purged after expiry, or a stale/\n * corrupted stored token)\n *\n * Both mean no valid session exists, so both warrant a forced logout.\n */\nconst INVALID_SESSION_ERROR_CODES = ['SIO-401-AEX', 'SIO-401-ANF']\n\n/**\n * Whether a 401 positively signals an invalid session (see\n * {@link INVALID_SESSION_ERROR_CODES}). A 401 *without* one of these codes is\n * a resource-level denial (e.g. an authenticated user lacking a grant —\n * some endpoints answer those with 401, not 403) and must stay\n * caller-domain rather than force a logout; grant denials only happen with\n * a valid session, so they never carry these codes.\n *\n * @internal\n */\nexport function isInvalidSessionError(err: unknown): err is ClientError {\n if (!isUnauthorizedError(err)) return false\n const code = getApiErrorCode(err)\n return code !== undefined && INVALID_SESSION_ERROR_CODES.includes(code)\n}\n\n/**\n * The API's machine-readable `errorCode` from a client error response body\n * (e.g. `SIO-401-AEX` for an expired session), or `undefined` if absent. The\n * `ClientError` exposes the parsed body on `response.body` (typed `unknown`);\n * fall back to the stringified `responseBody` since older error shapes only\n * carry that.\n *\n * @internal\n */\nexport function getApiErrorCode(err: unknown): string | undefined {\n if (!(err instanceof ClientError)) return undefined\n const fromResponse = readErrorCode(err.response?.body)\n if (fromResponse) return fromResponse\n try {\n return readErrorCode(JSON.parse(err.responseBody ?? ''))\n } catch {\n return undefined\n }\n}\n\nfunction readErrorCode(value: unknown): string | undefined {\n if (typeof value !== 'object' || value === null || !('errorCode' in value)) return undefined\n const code = value.errorCode\n return typeof code === 'string' ? code : undefined\n}\n","import {ClientError, ServerError} from '@sanity/client'\nimport isNativeNetworkError from 'is-network-error'\n\n// These live in `util` so that non-studio code (e.g. the document store) can\n// depend on them without importing from `studio`; re-exported here to keep\n// the public API surface and existing import sites unchanged.\nexport {getApiErrorCode, isInvalidSessionError, isUnauthorizedError} from '../../util/apiErrors'\n\n/** @internal */\nexport function isTimeoutError(\n error: unknown,\n): error is Error & {code: 'ESOCKETTIMEDOUT' | 'ETIMEDOUT'} {\n return (\n typeof error === 'object' &&\n error !== null &&\n 'code' in error &&\n (error.code === 'ESOCKETTIMEDOUT' || error.code === 'ETIMEDOUT')\n )\n}\n\n/** @internal */\nexport function isNetworkError(error: unknown): error is Error {\n if (typeof error !== 'object' || error === null) return false\n // get-it v8 sets isNetworkError=true on connection errors\n // https://github.com/sanity-io/get-it/blob/9ffc7e0c2d41ffcfd3a33e7525d9d1f6b188f812/src/request/browser-request.ts#L194\n if ('isNetworkError' in error && error.isNetworkError === true) return true\n // get-it's connect/socket timeout path publishes a plain Error with a code\n // but does not set isNetworkError. Treat these timeouts as network errors\n // so they get the same treatment.\n if (isTimeoutError(error)) return true\n return isNativeNetworkError(error)\n}\n\n/**\n * Read the Retry-After header off a ClientError, if present. Per RFC 7231,\n * it's either a non-negative delta-seconds integer or an HTTP date.\n *\n * @internal\n */\nexport function parseRetryAfter(err: ClientError): number | undefined {\n const headers = (err as ClientError & {response?: {headers?: Record<string, string>}}).response\n ?.headers\n const value = headers?.['retry-after']\n if (!value) return undefined\n // Numeric-looking values go through the integer path even when out of\n // range, so negative numbers don't accidentally fall through to the date\n // parser (which can interpret them as historic dates).\n if (/^-?\\d+(\\.\\d+)?$/.test(value.trim())) {\n const seconds = Number(value)\n if (Number.isFinite(seconds) && seconds >= 0) return Math.ceil(seconds)\n return undefined\n }\n const dateMs = Date.parse(value)\n if (Number.isFinite(dateMs)) {\n const delta = Math.ceil((dateMs - Date.now()) / 1000)\n return delta > 0 ? delta : 0\n }\n return undefined\n}\n\n/**\n * Infrastructure-level error variants the studio's request-error UI knows\n * how to render. Everything else (4xx other than 429, parse errors, etc.)\n * is caller-domain and is never claimed by the studio.\n *\n * @internal\n */\nexport type RequestErrorClassification =\n | {type: 'networkError'; error: Error}\n | {type: 'serverError'; error: Error}\n | {type: 'rateLimited'; error: Error; retryAfterSeconds?: number}\n\n/**\n * Classify an error as an infrastructure-level request failure, or return\n * `null` when the error is caller-domain (validation errors, permission\n * denials, conflicts, 404s, ...) and should stay with the caller.\n *\n * Note: 401 is intentionally NOT classified here — whether a 401 means\n * \"invalid session\" (studio concern) or \"this resource refuses you\"\n * (caller concern) is decided by the API's explicit error code, which the\n * channel checks separately (see {@link isInvalidSessionError}).\n *\n * @internal\n */\nexport function classifyRequestError(err: unknown): RequestErrorClassification | null {\n if (err instanceof ClientError) {\n if (err.statusCode === 429) {\n return {type: 'rateLimited', error: err, retryAfterSeconds: parseRetryAfter(err)}\n }\n // 4xx other than 429 are caller-domain — they carry structured context\n // the caller is better positioned to render than a generic dialog.\n return null\n }\n if (err instanceof ServerError) return {type: 'serverError', error: err}\n if (isNetworkError(err)) return {type: 'networkError', error: err}\n return null\n}\n\n/**\n * A workspace-level configuration error: the project or dataset the\n * studio is pointed at doesn't exist. Unlike the infrastructure errors\n * above, these are not transient and not recoverable by retry — the user\n * has to fix `projectId`/`dataset` in their config (or create the missing\n * resource). The studio surfaces these as a full-screen takeover rather\n * than the retry/reload dialog.\n *\n * Which variant we can report depends on what the failing endpoint tells\n * us. Only the project/dataset management API carries a structured\n * discriminator; the generic `/data` 404 can't tell missing-project from\n * missing-dataset apart, so it isn't classified as a config error at all\n * (see {@link classifyConfigError}).\n *\n * @internal\n */\nexport type ConfigErrorClassification = {type: 'projectNotFound'} | {type: 'datasetNotFound'}\n\n/** Shape of the structured fields we read off a 404 response body. */\ninterface NotFoundBody {\n error?: unknown\n attributes?: {type?: unknown}\n}\n\nfunction notFoundBody(err: ClientError): NotFoundBody | undefined {\n const body = (err as ClientError & {response?: {body?: unknown}}).response?.body\n if (body && typeof body === 'object') return body as NotFoundBody\n return undefined\n}\n\n/**\n * Classify a 404 as a studio-configuration error — the project or dataset\n * the studio points at doesn't exist — using only structured response\n * fields (never message text, which isn't stable across endpoints).\n *\n * Recognized structured signals:\n * - `attributes.type === 'project'` → `projectNotFound`\n * (project management API)\n * - `error === 'Dataset not found'` → `datasetNotFound`\n * (dataset management API; a discrete error code, not free-form text)\n *\n * A 404 without one of these structured signals returns `null` and stays\n * caller-domain — including the generic `/data` 404s, which carry no\n * discriminator and so can't be safely attributed to a missing project or\n * dataset. This classifier only reports what the *response* proves.\n *\n * @internal\n */\nexport function classifyConfigError(err: unknown): ConfigErrorClassification | null {\n if (!(err instanceof ClientError) || err.statusCode !== 404) return null\n const body = notFoundBody(err)\n if (!body) return null\n\n // Project management API tags the response with `attributes.type`.\n if (body.attributes?.type === 'project') {\n return {type: 'projectNotFound'}\n }\n\n // Dataset management API returns a discrete `error` code. This is an\n // equality check on a structured field, not a match against free-form\n // `message` text.\n if (body.error === 'Dataset not found') {\n return {type: 'datasetNotFound'}\n }\n\n return null\n}\n\n/**\n * Whether an error originates from a Sanity client request — i.e. one a\n * plugin/customization could have delegated to the studio's error UI via\n * `useStudioErrorHandler()` rather than letting it reach an error\n * boundary. Used to surface a dev-only \"did you mean to opt in?\" tip.\n *\n * @internal\n */\nexport function isClientRequestError(err: unknown): boolean {\n return err instanceof ClientError || err instanceof ServerError || isNetworkError(err)\n}\n","import {BehaviorSubject, isObservable, lastValueFrom, type Observable} from 'rxjs'\n\nimport {classifyRequestError, isInvalidSessionError} from './classify'\nimport {\n type RequestErrorChannel,\n type RequestErrorClaim,\n type RequestErrorReportOptions,\n type StudioErrorHandler,\n} from './types'\n\n/**\n * Best-effort projectId extraction from an HTTP error's request URL\n * (`https://{projectId}.api.sanity.io/...`). Used to route a delegated\n * 401 to the right workspace's auth store for forced logout.\n */\nfunction projectIdFromError(err: Error): string | undefined {\n const url =\n (err as Error & {response?: {url?: string}}).response?.url ??\n (err as Error & {request?: {url?: string}}).request?.url\n if (!url) return undefined\n try {\n const host = new URL(url).hostname\n const match = host.match(/^([a-z0-9]+)\\.api\\.sanity\\.(?:io|work)$/)\n return match?.[1]\n } catch {\n return undefined\n }\n}\n\ninterface ParkedEntry {\n /** Re-runs the failed work. Absent for the `handle()` form. */\n retry?: () => void\n}\n\n/**\n * Create the studio's request-error channel. Framework-free — the React\n * side (context provider, dialog rendering) lives in `WorkspacesProvider`.\n *\n * See {@link StudioErrorHandler} for the call-site API and semantics.\n *\n * @internal\n */\nexport function createRequestErrorChannel(): RequestErrorChannel {\n const claimSubject = new BehaviorSubject<RequestErrorClaim | undefined>(undefined)\n let parked: ParkedEntry[] = []\n\n /**\n * Attempt to claim `err` for the studio UI. Returns `true` when claimed\n * (entry parked, dialog state set) and `false` when the error is\n * caller-domain and should be re-thrown by the caller of this function.\n */\n function tryClaim(err: unknown, options: RequestErrorReportOptions, entry: ParkedEntry): boolean {\n if (isInvalidSessionError(err)) {\n // The API positively signals an invalid session (expired or not found,\n // see INVALID_SESSION_ERROR_CODES) — force logout. A 401 *without* such\n // a code is a resource-level denial (some endpoints answer 401, not\n // 403, for authenticated users lacking a grant) and stays\n // caller-domain, same as a 403.\n parked.push(entry)\n // First invalid-session 401 owns the dialog + logout; concurrent\n // ones for the same teardown (including the logout request's own\n // 401) just park behind it rather than re-claiming.\n if (claimSubject.getValue()?.type !== 'unauthorized') {\n claimSubject.next({type: 'unauthorized', error: err, projectId: projectIdFromError(err)})\n }\n return true\n }\n\n const classification = classifyRequestError(err)\n if (!classification) return false\n\n parked.push(entry)\n // First claim owns the dialog; later concurrent failures just park —\n // their retries piggyback on the visible dialog's \"Try again\".\n if (!claimSubject.getValue()) {\n claimSubject.next({\n ...classification,\n retryable: Boolean(options.retryable && entry.retry),\n })\n }\n return true\n }\n\n function retry(): void {\n const entries = parked\n parked = []\n claimSubject.next(undefined)\n for (const entry of entries) {\n // Entries without a retry mechanism (the `handle()` form) stay\n // parked-forever by design: their promise chains were\n // fire-and-surface. Re-running is only possible where the caller\n // gave us something to run.\n entry.retry?.()\n }\n }\n\n async function handle(err: unknown): Promise<never> {\n // A rejection handler can't re-run the request (it already happened),\n // so handled errors are never retryable.\n if (!tryClaim(err, {retryable: false}, {})) throw err\n // Claimed: the dialog is up. Park the chain — there is nothing to\n // re-run, so it stays pending until the user reloads.\n return new Promise<never>(() => {})\n }\n\n function attempt<T>(\n thunk: (attemptNumber: number) => PromiseLike<T> | Observable<T>,\n options: RequestErrorReportOptions = {},\n ): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n let attemptNumber = 0\n const tryOnce = () => {\n attemptNumber += 1\n Promise.resolve(attemptNumber)\n .then((n) => {\n const result = thunk(n)\n // Single-shot request observables emit once then complete —\n // their last value is their value.\n return isObservable(result) ? lastValueFrom(result) : result\n })\n .then(resolve, (err) => {\n if (!tryClaim(err, options, {retry: tryOnce})) reject(err)\n })\n }\n tryOnce()\n })\n }\n\n return {\n attempt,\n handle,\n retry,\n claim$: claimSubject.asObservable(),\n }\n}\n\n/**\n * The {@link StudioErrorHandler} used when there is no studio error UI to\n * delegate to — outside a `WorkspacesProvider`, or in a standalone render\n * of a component that normally lives in a Studio.\n *\n * It has no dialog and no retry, so it just runs the work and lets the\n * caller's own error handling take over:\n * - `attempt()` runs the thunk once and resolves/rejects with its result\n * (an observable is drained to its last value, same as the real\n * channel).\n * - `handle()` re-throws, so the next `.catch` in the chain still sees the\n * error.\n *\n * This lets call sites use `useStudioErrorHandler()` unconditionally\n * instead of branching on whether a Studio is present.\n *\n * @internal\n */\nexport const passthroughErrorHandler: StudioErrorHandler = {\n attempt(thunk) {\n return Promise.resolve(1).then((n) => {\n const result = thunk(n)\n return isObservable(result) ? lastValueFrom(result) : result\n })\n },\n handle(err) {\n return Promise.reject(err)\n },\n}\n","import {useContext} from 'react'\nimport {StudioErrorHandlerContext} from 'sanity/_singletons'\n\nimport {passthroughErrorHandler} from './createRequestErrorChannel'\nimport {type StudioErrorHandler} from './types'\n\n/**\n * Access the studio's request-error reporter — the call-site API for\n * delegating unrecoverable request errors (network failures, 5xx, 429)\n * to the studio's built-in error UI.\n *\n * The studio never intercepts requests on its own: plugins and\n * customizations handle their own errors by default (inline errors,\n * toasts, fallbacks). Use this reporter for the failures your code\n * cannot recover from locally.\n *\n * Always returns a handler, so call sites never have to branch on whether\n * a Studio is present. Outside a `WorkspacesProvider` (e.g. a standalone\n * render of a component that normally lives in a Studio) it returns a\n * passthrough handler with no dialog and no retry: `attempt()` just runs\n * the work, and `handle()` re-throws to the caller's own `.catch`.\n *\n * @example\n * ```tsx\n * function MyPluginComponent() {\n * const client = useClient({apiVersion: '2025-02-19'})\n * const {attempt, handle} = useStudioErrorHandler()\n *\n * const loadSettings = useCallback(async () => {\n * // Retryable read: \"Try again\" in the studio dialog re-runs the thunk.\n * const settings = await attempt(\n * () => client.fetch('*[_id == \"myPlugin.settings\"][0]'),\n * {retryable: true},\n * )\n * return settings\n * }, [client, attempt])\n *\n * const save = useCallback(\n * (doc: SanityDocument) =>\n * client\n * .createOrReplace(doc)\n * // Fire-and-surface: a network/5xx failure shows the studio\n * // dialog (reload-only, conservative copy). Caller-domain errors\n * // (validation, permissions) are re-thrown to the next .catch.\n * .catch(handle)\n * .catch(showInlineValidationError),\n * [client, handle],\n * )\n * // ...\n * }\n * ```\n *\n * @beta\n */\nexport function useStudioErrorHandler(): StudioErrorHandler {\n return useContext(StudioErrorHandlerContext) ?? passthroughErrorHandler\n}\n","import {createNode} from '@sanity/comlink'\nimport {type FrameMessages, type WindowMessages} from '@sanity/message-protocol'\n\nimport {type CapabilityRecord} from '../renderingContext/types'\nimport {type ComlinkStore} from './types'\n\ninterface Options {\n capabilities: CapabilityRecord\n}\n\n// These values must match the bindings of the same name exported by `@sanity/message-protocol`.\n// We are currently unable to consume this package at runtime because of ESM issues.\n//\n// TODO: Consume `SDK_CHANNEL_NAME` and `SDK_NODE_NAME` from `@sanity/message-protocol`.\nconst SDK_CHANNEL_NAME = 'dashboard/channels/sdk'\nconst SDK_NODE_NAME = 'dashboard/nodes/sdk'\n\n/**\n * Create a Comlink node if Comlink is provided by the Studio rendering context.\n *\n * @internal\n */\nexport function createComlinkStore({capabilities}: Options): ComlinkStore {\n if (!capabilities.comlink) {\n return {}\n }\n\n const node = createNode<FrameMessages, WindowMessages>({\n name: SDK_NODE_NAME,\n connectTo: SDK_CHANNEL_NAME,\n })\n\n node.start()\n\n return {\n node,\n }\n}\n","import {type Observable, type OperatorFunction} from 'rxjs'\nimport {catchError, tap} from 'rxjs/operators'\n\ntype Selector<T, K> = (error: unknown, attemptNo: number, caught: Observable<T>) => Observable<K>\n\n/**\n * Like catchError, but passes the number of successive errors as the second argument to the selector function\n * @internal\n * @hidden\n */\nexport function catchWithCount<T, K = T>(selector: Selector<T, K>): OperatorFunction<T, K>\nexport function catchWithCount<T, K = T>(selector: Selector<T, K>) {\n return (input$: Observable<T>) => {\n let successiveErrorsCount = 0\n\n const errorOp: OperatorFunction<any, any> = catchError(\n (err: unknown, caught: Observable<T>) => {\n successiveErrorsCount++\n return selector(err, successiveErrorsCount, caught).pipe(errorOp)\n },\n )\n return input$.pipe(\n tap(() => {\n // Reset when source stream emits a value (i.e. not errors)\n successiveErrorsCount = 0\n }),\n errorOp,\n )\n }\n}\n","import {type BifurClient} from '@sanity/bifur-client'\nimport {observableCallback} from 'observable-callback'\nimport {concat, fromEvent, merge, NEVER, type Observable, of, throwError, timer} from 'rxjs'\nimport {map, mergeMapTo, startWith, take, takeUntil} from 'rxjs/operators'\n\nimport {catchWithCount} from '../../util/catchWithCount'\n\n/** @internal */\nexport interface ConnectionStatusStore {\n connectionStatus$: Observable<ConnectionStatus>\n}\n\nconst onOnline$ = typeof window === 'undefined' ? of({}) : fromEvent(window, 'online')\nconst onOffline$ = typeof window === 'undefined' ? of({}) : fromEvent(window, 'offline')\n\nconst expBackoff = (retryCount: number) => Math.pow(2, retryCount) * 100\n\n/** @internal */\nexport type ConnectingStatus = {\n type: 'connecting'\n}\n\n/** @internal */\nexport type ErrorStatus = {\n type: 'error'\n error: Error\n attemptNo: number\n isOffline: boolean\n retryAt: Date\n}\n\n/** @internal */\nexport type RetryingStatus = {\n type: 'retrying'\n}\n\n/** @internal */\nexport type ConnectedStatus = {type: 'connected'; lastHeartbeat: Date}\n\n/** @internal */\nexport const CONNECTING: ConnectingStatus = {type: 'connecting'}\n\n/** @internal */\nexport type ConnectionStatus = ConnectingStatus | ErrorStatus | ConnectedStatus | RetryingStatus\n\nconst _callback = observableCallback()\n\nconst onRetry$ = _callback[0]\n\n/** @internal */\nexport const onRetry = _callback[1]\n\nconst createErrorStatus = ({\n error,\n isOffline,\n attemptNo,\n retryAt,\n}: {\n error: Error\n isOffline: boolean\n attemptNo: number\n retryAt: Date\n}): ErrorStatus => ({\n type: 'error',\n error,\n attemptNo,\n isOffline,\n retryAt,\n})\n\n/** @internal */\nexport interface ConnectionStatusStoreOptions {\n bifur: BifurClient\n}\n\n/**\n * This is the beginning of what should be the data store tracking connection status in the Sanity studio.\n *\n * @internal\n */\nexport function createConnectionStatusStore({\n bifur,\n}: ConnectionStatusStoreOptions): ConnectionStatusStore {\n const connectionStatus$: Observable<ConnectionStatus> = merge(\n bifur.heartbeats,\n onOffline$.pipe(mergeMapTo(throwError(new Error('The browser went offline')))),\n ).pipe(\n map((ts): ConnectionStatus => ({type: 'connected', lastHeartbeat: ts})),\n catchWithCount((error, successiveErrorsCount, caught) => {\n const timeUntilRetry = Math.min(1000 * 240, expBackoff(successiveErrorsCount))\n const retryAt = new Date(new Date().getTime() + timeUntilRetry)\n const expiry$ = timer(retryAt)\n const isOffline = !navigator.onLine\n const initialErrorStatus = createErrorStatus({\n error: error as Error,\n retryAt,\n isOffline,\n attemptNo: successiveErrorsCount,\n })\n\n const triggerRetry$ = NEVER.pipe(\n takeUntil(isOffline ? onOnline$ : merge(expiry$, onOnline$, onRetry$)),\n )\n\n return concat(of(initialErrorStatus), triggerRetry$.pipe(take(1)), caught)\n }),\n startWith(CONNECTING),\n )\n\n return {connectionStatus$}\n}\n","import {defineEvent} from '@sanity/telemetry'\n\nexport const DocumentDesynced = defineEvent<{errorName: string}>({\n name: 'Document Desynced',\n version: 1,\n description:\n 'Occurs when a \"hole\" in events from the document pair listener is detected and recovered from.',\n})\n","import {defineEvent} from '@sanity/telemetry'\n\ninterface DocumentPairLoadingMeasuredData {\n /**\n * How long it took to load the document pair\n */\n durationMs: number\n\n /**\n * Whether the document pair was loaded from an in-memory cache\n */\n fromCache: boolean\n\n /**\n * Did we load the published document?\n */\n hasPublished: boolean\n\n /**\n * Did we load the draft document?\n */\n hasDraft: boolean\n\n /**\n * Did we load a version document?\n */\n hasVersion: boolean\n}\n\nexport const DocumentPairLoadingMeasured = defineEvent<DocumentPairLoadingMeasuredData>({\n name: 'Document Pair Load Time Measured',\n version: 1,\n description: 'Time from document pair subscription to first ready snapshot',\n maxSampleRate: 30_000,\n})\n","import {defineEvent} from '@sanity/telemetry'\n\nexport const DocumentRebaseOccurred = defineEvent<{\n remoteMutationCount: number\n localMutationCount: number\n}>({\n name: 'Document Rebase Occurred',\n version: 1,\n description:\n 'A remote mutation arrived while local mutations were pending, requiring a rebase of the optimistic state',\n})\n","import {defineEvent} from '@sanity/telemetry'\n\ntype Samples = {\n latency: number\n transactionId: string\n shard?: string\n}\nexport const HighListenerLatencyOccurred = defineEvent<Samples>({\n name: 'High Listener Latency Detected',\n version: 1,\n description: 'Emits when a high listener latency is detected',\n})\n","import {defineEvent} from '@sanity/telemetry'\n\nexport const MutationPerformanceMeasured = defineEvent<{\n transactionId: string\n debounceMs: number\n apiMs: number\n callbackMs: number\n shard?: string\n}>({\n name: 'Mutation Performance Measured',\n version: 1,\n description:\n 'Timing breakdown for mutation round-trip: debounce, API, and listener callback phases',\n})\n","import {isDraftId, isVersionId} from './draftUtils'\n\n/**\n * Indicates the type of document variant, either `draft`, `version` or `published`.\n * Draft documents are prefixed with `drafts.`.\n * Version documents are prefixed with `versions.<versionName>`\n * The rest are considered published documents.\n * @public\n */\nexport type DocumentVariantType = 'draft' | 'version' | 'published'\n\n/**\n * Takes a document id and returns the variant type for that document\n * If it's a document that starts with `version.` it's a `version` document.\n * If it's a document that starts with `drafts.` it's a `draft` document.\n * Otherwise, it's a `published` document.\n * @public\n * */\nexport function getDocumentVariantType(documentId: string): DocumentVariantType {\n if (isDraftId(documentId)) return 'draft'\n if (isVersionId(documentId)) return 'version'\n return 'published'\n}\n","import {BufferedDocument, Mutation} from '@sanity/mutator'\nimport {type SanityDocument} from '@sanity/types'\nimport {BehaviorSubject, EMPTY, merge, type Observable, Subject} from 'rxjs'\nimport {\n distinctUntilChanged,\n filter,\n map,\n mergeMapTo,\n publishReplay,\n refCount,\n scan,\n share,\n take,\n tap,\n withLatestFrom,\n} from 'rxjs/operators'\n\nimport {type ListenerEvent} from '../getPairListener'\nimport {type MutationEvent} from '../types'\nimport {\n type DocumentMutationEvent,\n type DocumentRebaseEvent,\n type DocumentRemoteMutationEvent,\n type MutationPayload,\n type RemoteSnapshotEvent,\n type SnapshotEvent,\n} from './types'\n\ninterface MutationAction {\n type: 'mutation'\n mutations: MutationPayload[]\n}\n\ninterface CommitAction {\n type: 'commit'\n}\n\ntype Action = MutationAction | CommitAction\n\n/**\n * Represents \"commit requests\" from the mutator.\n * These are emitted from the BufferedDocument instance's `requestHandler` callback\n *\n * @internal\n */\nexport interface CommitRequest {\n mutation: Mutation\n success: () => void\n failure: (error: Error) => void\n cancel: (error: Error) => void\n /** Timestamp (Date.now()) when the first local mutation in this commit batch was received */\n firstMutationReceivedAt?: number\n}\n\n// BufferedDocument.LOCAL never updates its revision due to its internal consistency checks\n// but we sometimes we need the most current _rev on the document in UI land, e.g.\n// in order to do optimistic locking on the edited document to make sure we publish the document the user\n// actually are looking at, and not the one currently at the server\n// Also - the mutator is not setting _updatedAt on patches applied optimistically or\n// when they are received from server\nconst getUpdatedSnapshot = (bufferedDocument: BufferedDocument) => {\n const LOCAL = bufferedDocument.LOCAL\n const HEAD = bufferedDocument.document.HEAD\n if (!LOCAL) {\n return LOCAL\n }\n\n return {\n ...LOCAL,\n _type: (HEAD || LOCAL)._type,\n _rev: (HEAD || LOCAL)._rev,\n _updatedAt: new Date().toISOString(),\n }\n}\n\nconst toSnapshotEvent = (document: any): SnapshotEvent => ({type: 'snapshot', document})\nconst getDocument = <T extends {document: any}>(event: T): T['document'] => event.document\n\n/** @internal */\n// This is an observable interface for BufferedDocument in an attempt\n// to make it easier to work with the api provided by it\nexport const createObservableBufferedDocument = (listenerEvent$: Observable<ListenerEvent>) => {\n // Incoming local actions (e.g. a request to mutate, a request to commit pending changes, etc.)\n const actions$ = new Subject<Action>()\n\n // Track when the first mutation in a batch arrives (for performance telemetry)\n let firstMutationReceivedAt: number | undefined\n\n // Stream of commit requests. Must be handled by a commit handler\n const consistency$ = new BehaviorSubject<boolean>(true)\n\n // Stream of mutations for this document\n // NOTE: this will *not* include remote mutations received over the listener\n // that has *already* applied locally/optimistically\n const mutations$ = new Subject<DocumentMutationEvent>()\n\n // a stream of rebase events emitted from the mutator\n const rebase$ = new Subject<DocumentRebaseEvent>()\n\n // a stream of remote mutations with effetcs\n const remoteMutations = new Subject<DocumentRemoteMutationEvent>()\n\n const commitRequests = new Subject<CommitRequest>()\n\n const createInitialBufferedDocument = (initialSnapshot: SanityDocument | null) => {\n const bufferedDocument = new BufferedDocument(initialSnapshot)\n bufferedDocument.onMutation = ({mutation, remote}: any) => {\n // this is called after either when:\n // 1) local mutations has been added, optimistically applied and queued for sending\n // 2) remote mutations originating from another client has arrived and been applied\n mutations$.next({\n type: 'mutation',\n document: getUpdatedSnapshot(bufferedDocument) as any,\n mutations: mutation.mutations,\n origin: remote ? 'remote' : 'local',\n })\n }\n bufferedDocument.onRemoteMutation = (mutation: any) => {\n remoteMutations.next({\n type: 'remoteMutation',\n head: bufferedDocument.document.HEAD as any,\n transactionId: mutation.transactionId,\n timestamp: mutation.timestamp,\n author: mutation.identity,\n effects: mutation.effects,\n })\n }\n\n bufferedDocument.onRebase = (edge: any, nextRemoteMutations: any, localMutations: any) => {\n rebase$.next({\n type: 'rebase',\n document: edge,\n remoteMutations: nextRemoteMutations,\n localMutations,\n })\n }\n\n bufferedDocument.onConsistencyChanged = (isConsistent) => {\n if (!isConsistent && firstMutationReceivedAt === undefined) {\n firstMutationReceivedAt = Date.now()\n }\n if (isConsistent) {\n firstMutationReceivedAt = undefined\n }\n consistency$.next(isConsistent)\n }\n\n bufferedDocument.commitHandler = (commitArg: CommitRequest) => {\n const captured = firstMutationReceivedAt\n // Reset so the next commit batch doesn't reuse a stale timestamp\n // from a previous batch when the document stays inconsistent\n firstMutationReceivedAt = undefined\n commitRequests.next({...commitArg, firstMutationReceivedAt: captured})\n }\n\n return bufferedDocument\n }\n\n const currentBufferedDocument$ = listenerEvent$.pipe(\n scan((bufferedDocument: BufferedDocument | null, listenerEvent) => {\n // consider renaming 'snapshot' to initial/welcome\n if (listenerEvent.type === 'snapshot') {\n if (bufferedDocument) {\n // we received a new snapshot and already got an old one. When we receive a snapshot again\n // it is usually because the connection has been down. Attempt to save pending changes (if any)\n void bufferedDocument.commit()\n }\n // mark as consistent when a new snapshot is received\n firstMutationReceivedAt = undefined\n consistency$.next(true)\n return createInitialBufferedDocument(listenerEvent.document || null)\n }\n if (bufferedDocument === null) {\n console.warn(\n 'Ignoring event of type \"%s\" since buffered document has not yet been set up with snapshot',\n listenerEvent.type,\n )\n return null\n }\n return bufferedDocument\n }, null),\n filter(\n <T>(bufferedDocument: T): bufferedDocument is NonNullable<T> => bufferedDocument !== null,\n ),\n distinctUntilChanged(),\n publishReplay(1),\n refCount(),\n )\n\n // this is a stream of document snapshots where each new snapshot are emitted after listener mutations\n // has been applied. Since the optimistic patches is not emitted on the mutation$ stream, we need this\n // in order to update the document with a new _rev (and _updatedAt)\n const snapshotAfterSync$ = listenerEvent$.pipe(\n filter((ev): ev is MutationEvent => ev.type === 'mutation'),\n withLatestFrom(currentBufferedDocument$),\n map(([mutationEvent, bufferedDocument]) => {\n bufferedDocument.arrive(new Mutation(mutationEvent))\n return getUpdatedSnapshot(bufferedDocument)\n }),\n )\n\n // this is where the side effects mandated by local actions actually happens\n const actionHandler$ = actions$.pipe(\n withLatestFrom(currentBufferedDocument$),\n tap(([action, bufferedDocument]: [Action, BufferedDocument]) => {\n if (action.type === 'mutation') {\n bufferedDocument.add(new Mutation({mutations: action.mutations}))\n }\n if (action.type === 'commit') {\n void bufferedDocument.commit()\n }\n }),\n // We subscribe to this only for the side effects\n mergeMapTo(EMPTY),\n share(),\n )\n\n const emitAction = (action: any) => actions$.next(action)\n\n const addMutations = (mutations: MutationPayload[]) => emitAction({type: 'mutation', mutations})\n const addMutation = (mutation: MutationPayload) => addMutations([mutation])\n\n const commit = () => {\n currentBufferedDocument$\n .pipe(\n take(1),\n tap((bufferedDocument) => bufferedDocument.commit()),\n )\n .subscribe()\n }\n\n // A stream of this document's snapshot\n const snapshot$ = merge(\n currentBufferedDocument$.pipe(map((bufferedDocument) => bufferedDocument.LOCAL)),\n mutations$.pipe(map(getDocument)),\n rebase$.pipe(map(getDocument)),\n snapshotAfterSync$,\n ).pipe(map(toSnapshotEvent), publishReplay(1), refCount())\n\n const remoteSnapshot$: Observable<RemoteSnapshotEvent> = merge(\n currentBufferedDocument$.pipe(\n map((bufferedDocument) => bufferedDocument.document.HEAD as any),\n map(toSnapshotEvent),\n ),\n remoteMutations,\n ).pipe(publishReplay(1), refCount())\n\n return {\n updates$: merge(snapshot$, actionHandler$, mutations$, rebase$),\n consistency$: consistency$.pipe(distinctUntilChanged(), publishReplay(1), refCount()),\n remoteSnapshot$,\n commitRequest$: commitRequests,\n addMutation,\n addMutations,\n commit,\n }\n}\n","import {type SanityDocument} from '@sanity/types'\nimport {type Observable} from 'rxjs'\n\nimport {type ListenerEvent} from '../getPairListener'\nimport {\n type CommitRequest,\n createObservableBufferedDocument,\n} from './createObservableBufferedDocument'\nimport {\n type CommittedEvent,\n type DocumentMutationEvent,\n type DocumentRebaseEvent,\n type MutationPayload,\n type RemoteSnapshotEvent,\n type SnapshotEvent,\n} from './types'\n\n/**\n * @hidden\n * @beta */\nexport type BufferedDocumentEvent =\n | SnapshotEvent\n | DocumentRebaseEvent\n | DocumentMutationEvent\n | CommittedEvent\n\nconst prepare = (id: string) => (document: Partial<SanityDocument>) => {\n const {_id, _rev, _updatedAt, ...rest} = document\n return {_id: id, ...rest}\n}\n\n/** @internal */\nexport interface BufferedDocumentWrapper {\n consistency$: Observable<boolean>\n remoteSnapshot$: Observable<RemoteSnapshotEvent>\n events: Observable<BufferedDocumentEvent>\n commitRequest$: Observable<CommitRequest>\n // helper functions\n patch: (patches: any[]) => MutationPayload[]\n create: (document: Partial<SanityDocument>) => MutationPayload\n createIfNotExists: (document: SanityDocument) => MutationPayload\n createOrReplace: (document: SanityDocument) => MutationPayload\n delete: () => MutationPayload\n\n mutate: (mutations: MutationPayload[]) => void\n commit: () => void\n}\n\n/** @internal */\nexport const createBufferedDocument = (\n documentId: string,\n // consider naming it remoteEvent$\n listenerEvent$: Observable<ListenerEvent>,\n): BufferedDocumentWrapper => {\n const bufferedDocument = createObservableBufferedDocument(listenerEvent$)\n\n const prepareDoc = prepare(documentId)\n\n const DELETE = {delete: {id: documentId}}\n\n return {\n events: bufferedDocument.updates$,\n consistency$: bufferedDocument.consistency$,\n remoteSnapshot$: bufferedDocument.remoteSnapshot$,\n commitRequest$: bufferedDocument.commitRequest$,\n\n patch: (patches) => patches.map((patch) => ({patch: {...patch, id: documentId}})),\n create: (document) => ({create: prepareDoc(document)}),\n createIfNotExists: (document) => ({createIfNotExists: prepareDoc(document)}),\n createOrReplace: (document) => ({createOrReplace: prepareDoc(document)}),\n delete: () => DELETE,\n\n mutate: (mutations: MutationPayload[]) => bufferedDocument.addMutations(mutations),\n commit: () => bufferedDocument.commit(),\n }\n}\n","import createDebug from 'debug'\n\nexport const debug = createDebug('sanity:document-store')\n","import {TTLCache} from '@isaacs/ttlcache'\nimport {type MonoTypeOperatorFunction, type Observable} from 'rxjs'\nimport {mergeMap, scan} from 'rxjs/operators'\n\nimport {debug} from '../debug'\nimport {type ListenerEvent} from '../getPairListener'\n\nconst DEFAULT_TTL = 120_000\nconst DEFAULT_MAX_ENTRIES = 1000\n\nexport function dedupeListenerEvents<T extends ListenerEvent>({\n ttl = DEFAULT_TTL,\n max = DEFAULT_MAX_ENTRIES,\n}: {\n ttl?: number\n max?: number\n} = {}): MonoTypeOperatorFunction<T> {\n return (input$: Observable<T>) =>\n input$.pipe(\n scan(\n ({seen}: {emit: T[]; seen: TTLCache<string, null>}, event: T) => {\n if (event.type !== 'mutation') {\n return {emit: [event], seen}\n }\n const key = `${event.transactionId}#${event.documentId}`\n if (seen.has(key)) {\n debug('Ignoring duplicate listener event: ', key)\n return {seen, emit: []}\n }\n seen.set(key, null)\n return {seen, emit: [event]}\n },\n {emit: [], seen: new TTLCache<string, null>({ttl, max})},\n ),\n mergeMap(\n (state) =>\n // note: if state.emit is an empty array, nothing will be emitted\n state.emit,\n ),\n )\n}\n","import {type MutationEvent} from '../types'\n\nexport function discardChainTo(chain: MutationEvent[], revision: string | undefined) {\n const revisionIndex = chain.findIndex((event) => event.resultRev === revision)\n\n return split(chain, revisionIndex + 1)\n}\n\nfunction split<T>(array: T[], index: number) {\n if (index < 0) {\n return [[], array]\n }\n return [array.slice(0, index), array.slice(index)]\n}\n\nexport function toOrderedChains<T extends {previousRev: string; resultRev: string}>(events: T[]) {\n const parents: Record<string, T | undefined> = {}\n\n events.forEach((event) => {\n parents[event.resultRev] = events.find((other) => other.resultRev === event.previousRev)\n })\n\n // get entries without a parent (if there's more than one, we have a problem)\n const orphans = Object.entries(parents).filter(([, parent]) => {\n return !parent\n })\n\n return orphans.map((orphan) => {\n const [headRev] = orphan\n\n let current = events.find((event) => event.resultRev === headRev)\n\n const sortedList: T[] = []\n while (current) {\n sortedList.push(current)\n current = events.find((event) => event.previousRev === current?.resultRev)\n }\n return sortedList\n })\n}\n","import partition from 'lodash-es/partition.js'\nimport {concat, type Observable, of, switchMap, throwError, timer} from 'rxjs'\nimport {mergeMap, scan} from 'rxjs/operators'\n\nimport {debug} from '../debug'\nimport {type ListenerEvent} from '../getPairListener'\nimport {type MutationEvent} from '../types'\nimport {discardChainTo, toOrderedChains} from './eventChainUtils'\n\ninterface ListenerSequenceState {\n /**\n * Tracks the latest revision from the server that can be applied locally\n * Once we receive a mutation event that has a `previousRev` that equals `base.revision`\n * we will move `base.revision` to the event's `resultRev`\n * `base.revision` will be undefined if document doesn't exist.\n * `base` is `undefined` until the snapshot event is received\n */\n base: {revision: string | undefined} | undefined\n /**\n * Array of events to pass on to the stream, e.g. when mutation applies to current head revision, or a chain is complete\n */\n emitEvents: ListenerEvent[]\n /**\n * Buffer to keep track of events that doesn't line up in a [previousRev, resultRev] -- [previousRev, resultRev] sequence\n * This can happen if events arrive out of order, or if an event in the middle for some reason gets lost\n */\n buffer: MutationEvent[]\n}\n\nconst DEFAULT_MAX_BUFFER_SIZE = 20\nconst DEFAULT_DEADLINE_MS = 30000\n\nconst EMPTY_ARRAY: never[] = []\n\n/**\n * Takes an input observable of listener events that might arrive out of order, and emits them in sequence\n * If we receive mutation events that doesn't line up in [previousRev, resultRev] pairs we'll put them in a buffer and\n * check if we have an unbroken chain every time we receive a new event\n *\n * If the buffer grows beyond `maxBufferSize`, or if `resolveChainDeadline` milliseconds passes before the chain resolves\n * an OutOfSyncError will be thrown on the stream\n *\n * @internal\n */\nexport function sequentializeListenerEvents(options?: {\n maxBufferSize?: number\n resolveChainDeadline?: number\n}) {\n const {resolveChainDeadline = DEFAULT_DEADLINE_MS, maxBufferSize = DEFAULT_MAX_BUFFER_SIZE} =\n options || {}\n\n return (input$: Observable<ListenerEvent>): Observable<ListenerEvent> => {\n return input$.pipe(\n scan(\n (state: ListenerSequenceState, event: ListenerEvent): ListenerSequenceState => {\n if (event.type === 'mutation' && !state.base) {\n throw new Error('Invalid state. Cannot create a sequence without a base')\n }\n if (event.type === 'snapshot') {\n // When receiving a new snapshot, we can safely discard the current orphaned and chainable buffers\n return {\n base: {revision: event.document?._rev},\n buffer: EMPTY_ARRAY,\n emitEvents: [event],\n }\n }\n\n if (event.type === 'mutation') {\n // Note: the buffer may have multiple holes in it (this is a worst case scenario, and probably not likely, but still),\n // so we need to consider all possible chains\n // `toOrderedChains` will return all detected chains and each of the returned chains will be orderered\n // Once we have a list of chains, we can then discard any chain that leads up to the current revision\n // since they are already applied on the document\n const orderedChains = toOrderedChains(state.buffer.concat(event)).map((chain) => {\n // in case the chain leads up to the current revision\n const [discarded, rest] = discardChainTo(chain, state.base!.revision)\n if (discarded.length > 0) {\n debug('Discarded %d mutations already applied to document', discarded.length)\n }\n return rest\n })\n\n const [resolvedChains, _nextBuffer] = partition(orderedChains, (chain) => {\n // note: there can be at most one applicable chain\n return state.base!.revision === chain[0]?.previousRev\n })\n\n const nextBuffer = _nextBuffer\n .flat()\n .toSorted((a, b) => a.messageReceivedAt.localeCompare(b.messageReceivedAt))\n\n if (resolvedChains.length > 1) {\n throw new Error('Expected at most one resolved chain')\n }\n if (resolvedChains.length > 0 && resolvedChains[0].length > 0) {\n // we now have a continuous chain that can apply on the base revision\n // Move current base revision to the last mutation event in the applicable chain\n const lastMutation = resolvedChains[0].at(-1)!\n const nextBaseRevision =\n // special case: if the mutation deletes the document it technically has no revision, despite\n // resultRev pointing at a transaction id.\n lastMutation.transition === 'disappear' ? undefined : lastMutation?.resultRev\n\n if (state.buffer.length > 0) {\n // we went from having unresolved chains to resolved\n debug(\n `Resolved chain: %s => %s`,\n resolvedChains[0][0].previousRev,\n resolvedChains[0].at(-1)?.resultRev,\n )\n if (nextBuffer.length > 0) {\n debug(`There are still %d unchainable mutations`, nextBuffer.length)\n } else {\n debug(`All chains were resolved`)\n }\n }\n return {\n base: {revision: nextBaseRevision},\n emitEvents: resolvedChains[0],\n buffer: nextBuffer,\n }\n }\n\n if (nextBuffer.length >= maxBufferSize) {\n throw new MaxBufferExceededError(\n `Too many unchainable mutation events: ${state.buffer.length}`,\n state,\n )\n }\n return {\n ...state,\n buffer: nextBuffer,\n emitEvents: EMPTY_ARRAY,\n }\n }\n // Any other event (e.g. 'reconnect' is passed on verbatim)\n return {...state, emitEvents: [event]}\n },\n {\n emitEvents: EMPTY_ARRAY,\n base: undefined,\n buffer: EMPTY_ARRAY,\n },\n ),\n switchMap((state) => {\n if (state.buffer.length > 0) {\n // note: buffer is sorted by messageReceivedAt – oldest first\n const brokenChainStartsAt = new Date(state.buffer[0].messageReceivedAt)\n const nextDeadline = resolveChainDeadline - (Date.now() - brokenChainStartsAt.getTime())\n debug(\n \"There are %d listener event(s) that can't be applied in sequence. This could be due to events arriving out of order. Will throw an error if chain can't be resolved within %dms\",\n state.buffer.length,\n nextDeadline,\n )\n debug('Buffered events: %O', state.buffer)\n return concat(\n of(state),\n timer(nextDeadline).pipe(\n mergeMap(() =>\n throwError(() => {\n return new DeadlineExceededError(\n `Did not resolve chain within a deadline of ${resolveChainDeadline}ms`,\n state,\n )\n }),\n ),\n ),\n )\n }\n return of(state)\n }),\n mergeMap((state) => {\n // this will simply flatten the list of events into individual emissions\n // if the flushEvents array is empty, nothing will be emitted\n return state.emitEvents\n }),\n )\n }\n}\n\nexport class OutOfSyncError extends Error {\n /**\n * Attach state to the error for debugging/reporting\n */\n state: ListenerSequenceState\n constructor(message: string, state: ListenerSequenceState) {\n super(message)\n this.name = 'OutOfSyncError'\n this.state = state\n }\n}\n\nexport class DeadlineExceededError extends OutOfSyncError {\n constructor(message: string, state: ListenerSequenceState) {\n super(message, state)\n this.name = 'DeadlineExceededError'\n }\n}\nexport class MaxBufferExceededError extends OutOfSyncError {\n constructor(message: string, state: ListenerSequenceState) {\n super(message, state)\n this.name = 'MaxBufferExceededError'\n }\n}\n","import {type SanityClient} from '@sanity/client'\nimport {type SanityDocument} from '@sanity/types'\nimport groupBy from 'lodash-es/groupBy.js'\nimport {defer, merge, type Observable, of, throwError} from 'rxjs'\nimport {catchError, concatMap, filter, map, mergeMap, scan, share} from 'rxjs/operators'\n\nimport {shareReplayLatest} from '../../preview/utils/shareReplayLatest'\nimport {RELEASES_STUDIO_CLIENT_OPTIONS} from '../../releases/util/releasesClient'\nimport {getVersionFromId} from '../../util/draftUtils'\nimport {type StoreRequestErrorHandler} from '../requestErrorHandler'\nimport {debug} from './debug'\nimport {\n type IdPair,\n type MutationEvent,\n type PendingMutationsEvent,\n type ReconnectEvent,\n type ResetEvent,\n type WelcomeBackEvent,\n type WelcomeEvent,\n} from './types'\nimport {dedupeListenerEvents} from './utils/dedupeListenerEvents'\nimport {OutOfSyncError, sequentializeListenerEvents} from './utils/sequentializeListenerEvents'\n\ninterface Snapshots {\n draft: SanityDocument | null\n published: SanityDocument | null\n version: SanityDocument | null\n}\n\n/** @internal */\nexport interface InitialSnapshotEvent {\n type: 'snapshot'\n documentId: string\n document: SanityDocument | null\n}\n\n/**\n * @internal\n */\nexport interface LatencyReportEvent {\n shard?: string\n latencyMs: number\n transactionId: string\n}\n\n/** @internal */\nexport interface DocumentPairLoadedEvent {\n durationMs: number\n fromCache: boolean\n hasPublished: boolean\n hasDraft: boolean\n hasVersion: boolean\n}\n\n/** @internal */\nexport interface MutationPerformanceEvent {\n transactionId: string\n debounceMs: number\n apiMs: number\n callbackMs: number\n shard?: string\n}\n\n/** @internal */\nexport interface DocumentRebaseTelemetryEvent {\n remoteMutationCount: number\n localMutationCount: number\n}\n\n/** @internal */\nexport interface DocumentStoreExtraOptions {\n tag?: string\n\n /**\n * Optional handler for failures of the initial document snapshot fetch —\n * the only request delegated here. Commit failures are routed through the\n * commit request's own failure/cancel channels, and listener drops\n * recover via reconnects. When omitted, fetch failures propagate to the\n * document event streams.\n */\n snapshotFetchErrorHandler?: StoreRequestErrorHandler\n\n /**\n * Called when we recover from sync error\n * Meant for error tracking / telemetry purposes\n * @param error - the {@link OutOfSyncError} recovered from\n */\n onSyncErrorRecovery?(error: OutOfSyncError): void\n onReportLatency?: (event: LatencyReportEvent) => void\n onSlowCommit?: () => void\n onDocumentPairLoaded?: (event: DocumentPairLoadedEvent) => void\n onReportMutationPerformance?: (event: MutationPerformanceEvent) => void\n onDocumentRebase?: (event: DocumentRebaseTelemetryEvent) => void\n}\n\n/** @internal */\nexport type ListenerEvent =\n | MutationEvent\n | ReconnectEvent\n | InitialSnapshotEvent\n | PendingMutationsEvent\n | WelcomeEvent\n | WelcomeBackEvent\n | ResetEvent\n\nconst PENDING_START: PendingMutationsEvent = {type: 'pending', phase: 'begin'}\nconst PENDING_END: PendingMutationsEvent = {type: 'pending', phase: 'end'}\n\nfunction isMutationEvent(msg: ListenerEvent): msg is MutationEvent {\n return msg.type === 'mutation'\n}\nfunction isMultiTransactionEvent(msg: MutationEvent) {\n return msg.transactionTotalEvents > 1\n}\n\nfunction allPendingTransactionEventsReceived(listenerEvents: ListenerEvent[]) {\n const groupedMutations = groupBy(\n listenerEvents.filter((ev): ev is MutationEvent => ev.type === 'mutation'),\n (e) => e.transactionId,\n )\n // Note: we can't assume that the events come in order, so instead of checking the counter attributes we check that we have actually received all\n return Object.values(groupedMutations).every(\n (mutations) => mutations.length === mutations[0].transactionTotalEvents,\n )\n}\n\n/** @internal */\nexport function getPairListener(\n _client: SanityClient,\n idPair: IdPair,\n options: DocumentStoreExtraOptions = {},\n): Observable<ListenerEvent> {\n const {publishedId, draftId, versionId} = idPair\n const client = idPair.versionId ? _client.withConfig(RELEASES_STUDIO_CLIENT_OPTIONS) : _client\n if (\n (idPair.versionId && getVersionFromId(idPair.versionId) === 'published') ||\n (idPair.versionId && getVersionFromId(idPair.versionId) === 'drafts')\n ) {\n throw new Error('VersionId cannot be \"published\" or \"drafts\"')\n }\n const sharedEvents = defer(() =>\n (\n client.observable.listen(\n `*[_id in $ids]`,\n {\n ids: [publishedId, draftId, versionId].filter((id) => typeof id !== 'undefined'),\n },\n {\n includeResult: false,\n includeAllVersions: true,\n enableResume: true,\n events: ['welcome', 'mutation', 'reconnect', 'reset', 'welcomeback'],\n effectFormat: 'mendoza',\n tag: options.tag || 'document.pair.listen',\n },\n ) as Observable<WelcomeEvent | MutationEvent | ReconnectEvent | WelcomeBackEvent | ResetEvent>\n ).pipe(\n dedupeListenerEvents(),\n map((event): WelcomeEvent | MutationEvent | ReconnectEvent | WelcomeBackEvent | ResetEvent =>\n event.type === 'mutation'\n ? {\n ...event,\n // client equivalent of `event.messageDispatchedAt`\n // note: consider moving this to client.listen()\n messageReceivedAt: new Date().toString(),\n }\n : event,\n ),\n shareReplayLatest({\n predicate: (event) =>\n event.type === 'welcome' ||\n event.type === 'reconnect' ||\n event.type === 'reset' ||\n event.type === 'welcomeback',\n }),\n ),\n )\n\n const pairEvents$ = sharedEvents.pipe(\n concatMap((event) => {\n const shouldSyncDocument =\n event.type === 'reset' ||\n // note: resumability may not be enabled – if so, treat welcome the same way as a reset\n event.type === 'welcome'\n return shouldSyncDocument\n ? fetchInitialDocumentSnapshots().pipe(\n mergeMap(({draft, published, version}) => [\n createSnapshotEvent(draftId, draft),\n createSnapshotEvent(publishedId, published),\n ...(versionId ? [createSnapshotEvent(versionId, version)] : []),\n ]),\n )\n : of(event)\n }),\n scan(\n (\n acc: {\n next: (InitialSnapshotEvent | ListenerEvent | WelcomeEvent)[]\n buffer: (InitialSnapshotEvent | ListenerEvent | WelcomeEvent)[]\n },\n msg,\n ) => {\n // we only care about mutation events\n if (!isMutationEvent(msg)) {\n return {next: [msg], buffer: []}\n }\n\n const isBuffering = acc.buffer.length > 0\n const isMulti = isMultiTransactionEvent(msg)\n if (!isMulti && !isBuffering) {\n // simple case, we have no buffer, and the event is a single-transaction event, so just pass it on\n return {next: [msg], buffer: []}\n }\n\n if (!isMulti) {\n // we have received a single transaction event while waiting for the rest of events from a multi transaction\n // put it in the buffer\n return {next: [], buffer: acc.buffer.concat(msg)}\n }\n\n const nextBuffer = acc.buffer.concat(msg)\n if (allPendingTransactionEventsReceived(nextBuffer)) {\n // we have received all pending transactions, emit the buffer, and signal end of buffer\n return {next: nextBuffer.concat(PENDING_END), buffer: []}\n }\n // if we get here, we are still waiting for more multi-transaction messages\n // if nextBuffer only has one element, we know we just started buffering\n return {next: nextBuffer.length === 1 ? [PENDING_START] : [], buffer: nextBuffer}\n },\n {next: [], buffer: []},\n ),\n // note: this flattens the array, and in the case of an empty array, no event will be pushed downstream\n mergeMap((v) => v.next),\n share(),\n )\n\n const draftEvents$ = pairEvents$.pipe(\n filter((event) =>\n event.type === 'mutation' || event.type === 'snapshot' ? event.documentId === draftId : true,\n ),\n sequentializeListenerEvents(),\n )\n\n const publishedEvents$ = pairEvents$.pipe(\n filter((event) =>\n event.type === 'mutation' || event.type === 'snapshot'\n ? event.documentId === publishedId\n : true,\n ),\n sequentializeListenerEvents(),\n )\n\n const versionEvents$ = pairEvents$.pipe(\n filter((event) =>\n event.type === 'mutation' || event.type === 'snapshot'\n ? event.documentId === versionId\n : true,\n ),\n sequentializeListenerEvents(),\n )\n\n return merge(draftEvents$, publishedEvents$, versionEvents$).pipe(\n catchError((err, caught$) => {\n if (err instanceof OutOfSyncError) {\n debug('Recovering from OutOfSyncError: %s', err.name)\n if (typeof options?.onSyncErrorRecovery === 'function') {\n options?.onSyncErrorRecovery(err)\n } else {\n console.error(err)\n }\n // this will retry immediately\n return caught$\n }\n return throwError(() => err)\n }),\n )\n\n function fetchInitialDocumentSnapshots(): Observable<Snapshots> {\n const fetchDocuments = () =>\n client.observable.getDocuments<SanityDocument>(\n [publishedId, draftId, versionId].filter((id): id is string => typeof id === 'string'),\n {tag: 'document.pair.fetch'},\n )\n\n // The pair cannot load without these snapshots, and there is no local\n // recovery if the fetch fails — delegate failures to the error handler\n // when one is provided. Retryable: it's an idempotent GET, safe to\n // re-run.\n //\n // While the handler holds a failed fetch for re-run, `pairEvents$`\n // buffers subsequent listener events behind this observable (concatMap)\n // on purpose: they must chain onto the snapshot once it arrives.\n // The buffer stays small — the listener only carries events for this\n // pair's documents — and tearing down the pair drops it.\n return defer(() =>\n options.snapshotFetchErrorHandler\n ? options.snapshotFetchErrorHandler.attempt(fetchDocuments, {retryable: true})\n : fetchDocuments(),\n ).pipe(\n map(([published, draft, version]) => ({\n draft,\n published,\n version,\n })),\n )\n }\n}\n\nfunction createSnapshotEvent(\n documentId: string,\n document: null | SanityDocument,\n): InitialSnapshotEvent {\n return {\n type: 'snapshot',\n documentId,\n document,\n }\n}\n","import {type SanityClient} from '@sanity/client'\n\nimport {RELEASES_STUDIO_CLIENT_OPTIONS} from '../../../../releases/util/releasesClient'\nimport {type IdPair} from '../../types'\n\nconst ACTIONS_API_MINIMUM_VERSION = '2025-02-19'\n\nexport function actionsApiClient(client: SanityClient, idPair: IdPair): SanityClient {\n if (idPair.versionId) {\n // TODO: Remove after API version is stable and support releases\n return client.withConfig(RELEASES_STUDIO_CLIENT_OPTIONS)\n }\n return client.withConfig({\n apiVersion: ACTIONS_API_MINIMUM_VERSION,\n })\n}\n","import {type SanityClient} from '@sanity/client'\n\nimport {RELEASES_STUDIO_CLIENT_OPTIONS} from '../../../../releases/util/releasesClient'\nimport {type IdPair} from '../../types'\n\nexport function operationsApiClient(client: SanityClient, idPair: IdPair): SanityClient {\n if (idPair.versionId) {\n // TODO: Remove after API version is stable and support releases\n return client.withConfig(RELEASES_STUDIO_CLIENT_OPTIONS)\n }\n return client\n}\n","import {\n type Action,\n type MultipleActionResult,\n type SanityClient,\n type SingleMutationResult,\n} from '@sanity/client'\nimport {type Mutation} from '@sanity/mutator'\nimport {type SanityDocument} from '@sanity/types'\nimport omit from 'lodash-es/omit.js'\nimport {combineLatest, defer, EMPTY, from, merge, type Observable, of, timer} from 'rxjs'\nimport {\n catchError,\n distinctUntilChanged,\n filter,\n map,\n mergeMap,\n scan,\n share,\n shareReplay,\n startWith,\n switchMap,\n takeUntil,\n tap,\n withLatestFrom,\n} from 'rxjs/operators'\n\nimport {isInvalidSessionError} from '../../../util/apiErrors'\nimport {type DocumentVariantType} from '../../../util/getDocumentVariantType'\nimport {\n type BufferedDocumentEvent,\n createBufferedDocument,\n} from '../buffered-doc/createBufferedDocument'\nimport {type CommitRequest} from '../buffered-doc/createObservableBufferedDocument'\nimport {\n type DocumentRebaseEvent,\n type MutationPayload,\n type RemoteSnapshotEvent,\n} from '../buffered-doc/types'\nimport {\n type DocumentStoreExtraOptions,\n getPairListener,\n type InitialSnapshotEvent,\n type LatencyReportEvent,\n type ListenerEvent,\n type MutationPerformanceEvent,\n} from '../getPairListener'\nimport {\n type IdPair,\n type MutationEvent,\n type PendingMutationsEvent,\n type ReconnectEvent,\n type ResetEvent,\n type WelcomeBackEvent,\n type WelcomeEvent,\n} from '../types'\nimport {actionsApiClient} from './utils/actionsApiClient'\nimport {operationsApiClient} from './utils/operationsApiClient'\n\n/** Timeout on request that fetches shard name before reporting latency */\nconst FETCH_SHARD_TIMEOUT = 20_000\n\n/** TTL for unmatched entries in the latency tracking pending array */\nconst PENDING_ENTRY_TTL = 60_000\n\n/** Duration after which a commit is considered slow and a warning is surfaced to the user */\nconst SLOW_COMMIT_TIMEOUT_MS = 50_000\n\nconst isMutationEventForDocId =\n (id: string) =>\n (event: ListenerEvent): event is MutationEvent | InitialSnapshotEvent => {\n return (event.type === 'snapshot' || event.type === 'mutation') && event.documentId === id\n }\n\n/**\n * @hidden\n * @beta */\nexport type WithVersion<T> = T & {version: DocumentVariantType}\n\n/**\n * @hidden\n * @beta */\nexport type DocumentVersionEvent = WithVersion<\n ReconnectEvent | BufferedDocumentEvent | WelcomeEvent | WelcomeBackEvent | ResetEvent\n>\n\n/**\n * @hidden\n * @beta */\nexport type RemoteSnapshotVersionEvent = WithVersion<RemoteSnapshotEvent>\n\n/**\n * @hidden\n * @beta\n * The SingleMutationResult type from `@sanity/client` doesn't reflect what we get back from POST /mutate\n */\nexport type MutationResult = Omit<SingleMutationResult, 'documentId'>\n\n/**\n * @hidden\n * @beta */\nexport interface DocumentVersion {\n consistency$: Observable<boolean>\n remoteSnapshot$: Observable<RemoteSnapshotVersionEvent>\n events: Observable<DocumentVersionEvent>\n\n patch: (patches: any[]) => MutationPayload[]\n create: (document: Partial<SanityDocument>) => MutationPayload\n createIfNotExists: (document: SanityDocument) => MutationPayload\n createOrReplace: (document: SanityDocument) => MutationPayload\n delete: () => MutationPayload\n\n mutate: (mutations: MutationPayload[]) => void\n commit: () => void\n}\n\n/**\n * The error thrown by the most recent failed commit attempt. Wrapped in an\n * object (rather than emitted raw) because a commit can reject with any\n * thrown value — including `undefined`, which would otherwise be\n * indistinguishable from the healthy state.\n *\n * @internal\n */\nexport type CommitError = {error: unknown}\n\n/**\n * @hidden\n * @beta */\nexport type Pair = {\n /** @internal */\n transactionsPendingEvents$: Observable<PendingMutationsEvent>\n /**\n * The error from the most recent commit attempt while it failed and is\n * being retried by the mutator, or `undefined` while commits are healthy.\n * Resets to `undefined` on the next successful (or terminally cancelled)\n * commit, and when the pair returns to a consistent state — i.e. the\n * buffered edits the failure was about no longer exist. Distinguishes\n * \"commits are failing\" from \"the backlog is merely slow\" — see\n * `useDocumentSyncState`.\n * @internal\n */\n commitError$: Observable<CommitError | undefined>\n published: DocumentVersion\n draft: DocumentVersion\n version?: DocumentVersion\n}\n\nfunction setVersion<T>(version: 'draft' | 'published' | 'version') {\n return (ev: T): T & {version: 'draft' | 'published' | 'version'} => ({...ev, version})\n}\n\nfunction requireId<T extends {_id?: string; _type: string}>(\n value: T,\n): asserts value is T & {_id: string} {\n if (!value._id) {\n throw new Error('Expected document to have an _id')\n }\n}\n\n//if we're patching a published document directly\n//then we're live editing and we should use raw mutations\n//rather than actions\nfunction isLiveEditMutation(mutationParams: Mutation['params'], publishedId: string) {\n const {resultRev, ...mutation} = mutationParams\n const patchTargets: string[] = mutation.mutations.flatMap((mut) => {\n const mutationPayloads = Object.values(mut)\n if (mutationPayloads.length > 1) {\n throw new Error('Did not expect multiple mutations in the same payload')\n }\n return mutationPayloads[0].id || mutationPayloads[0]._id\n })\n return patchTargets.every((target) => target === publishedId)\n}\n\nfunction toActions(idPair: IdPair, mutationParams: Mutation['params']): Action[] {\n const actions = mutationParams.mutations.flatMap<Action>((mutations) => {\n // This action is not always interoperable with the equivalent mutation. It will fail if the\n // published version of the document already exists.\n if (mutations.createIfNotExists) {\n // ignore all createIfNotExists, as these should be covered by the actions api and only be done locally\n return []\n }\n if (mutations.create) {\n // the actions API requires attributes._id to be set, while it's optional in the mutation API\n requireId(mutations.create)\n return {\n actionType: 'sanity.action.document.create',\n publishedId: idPair.publishedId,\n attributes: mutations.create,\n ifExists: 'fail',\n }\n }\n if (mutations.patch) {\n return {\n actionType: 'sanity.action.document.edit',\n draftId: idPair.versionId ?? idPair.draftId,\n publishedId: idPair.publishedId,\n patch: omit(mutations.patch, 'id'),\n }\n }\n throw new Error('Cannot map mutation to action')\n })\n\n // Empty action invocations are a noop; although Content Lake accepts them, no transaction will\n // be executed, causing Studio to become stuck in a pending state. To prevent this occurring, a\n // fake unset mutation is added whenever an empty set of actions would otherwise be executed.\n if (actions.length === 0) {\n return [\n {\n actionType: 'sanity.action.document.edit',\n draftId: idPair.draftId,\n publishedId: idPair.publishedId,\n patch: {\n unset: ['_empty_action_guard_pseudo_field_'],\n },\n },\n ]\n }\n\n return actions\n}\n\nfunction commitActions(client: SanityClient, idPair: IdPair, mutationParams: Mutation['params']) {\n if (isLiveEditMutation(mutationParams, idPair.publishedId)) {\n return commitMutations(client, idPair, mutationParams)\n }\n\n return actionsApiClient(client, idPair).observable.action(toActions(idPair, mutationParams), {\n tag: 'document.commit',\n transactionId: mutationParams.transactionId,\n })\n}\n\nfunction commitMutations(\n client: SanityClient,\n idPair: IdPair,\n mutationParams: Mutation['params'],\n): Promise<MutationResult> {\n const {resultRev, ...mutation} = mutationParams\n return operationsApiClient(client, idPair).dataRequest('mutate', mutation, {\n visibility: 'async',\n returnDocuments: false,\n tag: 'document.commit',\n // This makes sure the studio doesn't crash when a draft is crated\n // because someone deleted a referenced document in the target dataset\n skipCrossDatasetReferenceValidation: true,\n })\n}\n\n/**\n * The 4xx statuses we positively know are terminal for a commit: resubmitting\n * the same mutation can never succeed, so the buffered edits are cancelled\n * (rejected + reset to server HEAD) instead of retried. Opt-in by explicit\n * status rather than a blanket 4xx rule, because the buckets have opposite\n * failure modes: wrongly retrying a terminal error leaves the document\n * visibly stalled with the edits preserved (recoverable), while wrongly\n * cancelling a transient error silently destroys the user's work. Statuses\n * not listed here — including transient 4xx like 408/429 and any 4xx we\n * haven't classified — take the conservative retry path.\n *\n * 401 is terminal only for resource-level denials (e.g. a missing grant —\n * some endpoints answer those with 401, not 403). A 401 tagged as an invalid\n * session (`SIO-401-AEX` expired, `SIO-401-ANF` not found) is carved out\n * below: it says nothing about the mutation itself, and re-authenticating\n * can make the retry succeed, so the buffered edits must be preserved\n * rather than wiped mid-edit. The session itself is handled separately by\n * the force-logout flow.\n */\nconst TERMINAL_COMMIT_STATUSES = new Set([400, 401, 402, 403, 404, 409, 410, 412, 413, 422])\n\n/**\n * The result of a single commit attempt. Failures are routed to the mutator\n * (`request.failure` → retry with backoff, `request.cancel` → terminal\n * reset) *before* being emitted here, so this stream doubles as a\n * side-channel for observing commit health without erroring the document\n * event streams.\n */\ntype CommitAttemptResult =\n | {\n type: 'success'\n result: (MultipleActionResult | MutationResult) & {_perfTimings?: PerfTimings}\n }\n | {type: 'failure'; error: unknown}\n | {type: 'cancel'; error: unknown}\n\nfunction submitCommitRequest(\n client: SanityClient,\n idPair: IdPair,\n request: CommitRequest,\n): Observable<CommitAttemptResult> {\n return from(commitActions(client, idPair, request.mutation.params)).pipe(\n tap({\n next: () => request.success(),\n }),\n map((result): CommitAttemptResult => ({type: 'success', result})),\n // A failed commit is reported to the mutator via `request.cancel` /\n // `request.failure` (which rejects the corresponding commit promise so\n // the buffered document can retry/rebase on reconnect). After that, we\n // must NOT let the error propagate down this observable: it feeds\n // `commits$` → `combinedEvents` → the document `events` stream, and an\n // errored events stream is rethrown by `useObservable` (react-rx) when\n // `useEditState` reads it during render, crashing the document pane.\n // Emit the attempt result as a value instead — the failure has already\n // been routed through its proper channel.\n catchError((error) => {\n // A known-terminal client error cancels: the buffered mutations can't\n // succeed by retrying, so the commit is rejected and the buffer reset\n // to server HEAD (see TERMINAL_COMMIT_STATUSES for the rationale).\n // Everything else — 5xx, transient 4xx (408/429), unclassified 4xx,\n // session-expiry 401s, network errors — fails, so the mutator keeps\n // the buffer and retries with backoff.\n // `error` can be any thrown value — guard before using `in`, which\n // throws on primitives.\n const statusCode =\n typeof error === 'object' &&\n error !== null &&\n 'statusCode' in error &&\n typeof error.statusCode === 'number'\n ? error.statusCode\n : undefined\n if (\n statusCode !== undefined &&\n TERMINAL_COMMIT_STATUSES.has(statusCode) &&\n !isInvalidSessionError(error)\n ) {\n request.cancel(error)\n return of<CommitAttemptResult>({type: 'cancel', error})\n }\n request.failure(error)\n return of<CommitAttemptResult>({type: 'failure', error})\n }),\n )\n}\n\ntype PerfTimings = {\n firstMutationReceivedAt?: number\n apiRequestSentAt: number\n apiResponseReceivedAt: number\n}\n\ntype LatencyTrackingEvent = {\n transactionId: string\n submittedAt: Date\n receivedAt: Date\n deltaMs: number\n perfTimings?: PerfTimings\n}\n\ntype LatencyTrackingPendingEntry =\n | {type: 'submit'; transactionId: string; timestamp: Date; perfTimings?: PerfTimings}\n | {type: 'receive'; transactionId: string; timestamp: Date}\n\ntype LatencyTrackingEntry = LatencyTrackingPendingEntry | {type: 'reset'}\n\ntype LatencyTrackingState = {\n pending: LatencyTrackingPendingEntry[]\n event: LatencyTrackingEvent | undefined\n}\n\n/** @internal */\nexport function checkoutPair(\n client: SanityClient,\n idPair: IdPair,\n /**\n * @deprecated does nothing Preserved to avoid breaking changes\n * Will be removed in the next major version.\n */\n _serverActionsEnabled: Observable<boolean> | undefined,\n options: DocumentStoreExtraOptions = {},\n): Pair {\n const {publishedId, draftId, versionId} = idPair\n\n const {\n onReportLatency,\n onSyncErrorRecovery,\n onSlowCommit,\n onReportMutationPerformance,\n onDocumentRebase,\n snapshotFetchErrorHandler,\n tag,\n } = options\n\n const listenerEvents$ = getPairListener(client, idPair, {\n onSyncErrorRecovery,\n tag,\n snapshotFetchErrorHandler,\n }).pipe(share())\n\n const connectionChangeEvents$ = listenerEvents$.pipe(\n filter((ev) => ev.type === 'reconnect' || ev.type === 'welcome' || ev.type === 'welcomeback'),\n )\n\n const draft = createBufferedDocument(\n draftId,\n listenerEvents$.pipe(filter(isMutationEventForDocId(draftId))),\n )\n\n const version =\n typeof versionId === 'undefined'\n ? undefined\n : createBufferedDocument(\n versionId,\n listenerEvents$.pipe(filter(isMutationEventForDocId(versionId))),\n )\n\n const published = createBufferedDocument(\n publishedId,\n listenerEvents$.pipe(filter(isMutationEventForDocId(publishedId))),\n )\n\n // share commit handling between draft and published\n const transactionsPendingEvents$ = listenerEvents$.pipe(\n filter((ev): ev is PendingMutationsEvent => ev.type === 'pending'),\n )\n\n const commitRequests$ = merge(\n draft.commitRequest$,\n published.commitRequest$,\n version ? version.commitRequest$ : EMPTY,\n ).pipe(share())\n\n const commitAttemptResults$ = commitRequests$.pipe(\n mergeMap((commitRequest) => {\n const apiRequestSentAt = Date.now()\n return submitCommitRequest(client, idPair, commitRequest).pipe(\n map(\n (attemptResult): CommitAttemptResult =>\n attemptResult.type === 'success'\n ? {\n ...attemptResult,\n result: {\n ...attemptResult.result,\n _perfTimings: {\n firstMutationReceivedAt: commitRequest.firstMutationReceivedAt,\n apiRequestSentAt,\n apiResponseReceivedAt: Date.now(),\n },\n },\n }\n : attemptResult,\n ),\n )\n }),\n share(),\n )\n\n // The successful commits — failures/cancels have already been routed to the\n // mutator and must not reach the document event streams (see\n // `submitCommitRequest`).\n const commits$ = commitAttemptResults$.pipe(\n filter(\n (attemptResult): attemptResult is Extract<CommitAttemptResult, {type: 'success'}> =>\n attemptResult.type === 'success',\n ),\n map((attemptResult) => attemptResult.result),\n share(),\n )\n\n // Whether every buffered document in the pair is free of pending local\n // mutations — the pair-level version of the per-document `consistency$`.\n const consistent$ = combineLatest([\n draft.consistency$,\n published.consistency$,\n version ? version.consistency$ : of(true),\n ]).pipe(\n map((states) => states.every(Boolean)),\n distinctUntilChanged(),\n )\n\n // The error from the most recent commit attempt while the mutator is\n // retrying it on backoff, `undefined` while commits are healthy. Multicast\n // with replay so late subscribers (the sync-state hook mounts after the\n // pair is checked out) see the current value, not just future attempt\n // results — the silenced merge into `combinedEvents` below keeps it\n // recording for the pair's lifetime.\n const commitError$ = merge(\n commitAttemptResults$.pipe(\n map((attemptResult): CommitError | undefined =>\n attemptResult.type === 'failure' ? {error: attemptResult.error} : undefined,\n ),\n ),\n // Returning to consistency means the buffered edits the failure was\n // about are gone — drained, discarded, or reset to server HEAD by a\n // fresh snapshot — so nothing is being retried anymore. Note this is\n // deliberately NOT keyed on listener reconnects (welcome/welcome-back):\n // a live listener says nothing about commit health, and a reconnect\n // while still unsynced must not mask an ongoing failure.\n consistent$.pipe(\n filter((isConsistent) => isConsistent),\n map(() => undefined),\n ),\n ).pipe(startWith(undefined), distinctUntilChanged(), shareReplay({bufferSize: 1, refCount: true}))\n\n const pendingEnd$ = transactionsPendingEvents$.pipe(filter((ev) => ev.phase === 'end'))\n const commitResolved$ = merge(pendingEnd$, commits$)\n\n // Each new commit request restarts the timer via switchMap.\n // The timer is cancelled when the commit succeeds or pending mutations resolve.\n // Note: a *failed* commit does not emit on `commits$` (failures are filtered\n // out of `commitAttemptResults$` above), so `commitResolved$` does not fire for\n // it — a commit that fails after SLOW_COMMIT_TIMEOUT_MS still triggers\n // `onSlowCommit`. That's intentional: it was slow, and it's now failing.\n const slowCommitWarning$ = onSlowCommit\n ? commitRequests$.pipe(\n switchMap(() => timer(SLOW_COMMIT_TIMEOUT_MS).pipe(takeUntil(commitResolved$))),\n tap(() => onSlowCommit()),\n )\n : EMPTY\n\n const rebaseEvents$ = onDocumentRebase\n ? merge(draft.events, published.events, ...(version ? [version.events] : [])).pipe(\n filter((ev): ev is DocumentRebaseEvent & {type: 'rebase'} => ev.type === 'rebase'),\n tap((ev) => {\n try {\n onDocumentRebase({\n remoteMutationCount: ev.remoteMutations.length,\n localMutationCount: ev.localMutations.length,\n })\n } catch {\n // Telemetry callbacks must never kill the document pipeline\n }\n }),\n )\n : EMPTY\n\n // Note: we're only subscribing to this for the side-effect\n const combinedEvents = defer(() =>\n merge(\n onReportLatency || onReportMutationPerformance\n ? reportLatency({\n commits$: commits$,\n listenerEvents$: listenerEvents$,\n client,\n onReportLatency,\n onReportMutationPerformance,\n })\n : merge(commits$, listenerEvents$),\n slowCommitWarning$,\n rebaseEvents$,\n commitError$,\n ),\n ).pipe(\n mergeMap(() => EMPTY),\n share(),\n )\n\n return {\n transactionsPendingEvents$,\n commitError$,\n draft: {\n ...draft,\n events: merge(combinedEvents, connectionChangeEvents$, draft.events).pipe(\n map(setVersion('draft')),\n ),\n remoteSnapshot$: draft.remoteSnapshot$.pipe(map(setVersion('draft'))),\n },\n ...(typeof version === 'undefined'\n ? {}\n : {\n version: {\n ...version,\n events: merge(combinedEvents, connectionChangeEvents$, version.events).pipe(\n map(setVersion('version')),\n ),\n remoteSnapshot$: version.remoteSnapshot$.pipe(map(setVersion('version'))),\n },\n }),\n published: {\n ...published,\n events: merge(combinedEvents, connectionChangeEvents$, published.events).pipe(\n map(setVersion('published')),\n ),\n remoteSnapshot$: published.remoteSnapshot$.pipe(map(setVersion('published'))),\n },\n }\n}\n\nfunction reportLatency(options: {\n commits$: Observable<(MultipleActionResult | MutationResult) & {_perfTimings?: PerfTimings}>\n listenerEvents$: Observable<ListenerEvent>\n client: SanityClient\n onReportLatency?: (event: LatencyReportEvent) => void\n onReportMutationPerformance?: (event: MutationPerformanceEvent) => void\n}) {\n const {client, commits$, listenerEvents$, onReportLatency, onReportMutationPerformance} = options\n // Note: this request happens once and the result is then cached indefinitely\n let shardInfo: Promise<string | undefined>\n try {\n shardInfo = fetch(client.getUrl(client.getDataUrl('ping')), {\n signal: AbortSignal.timeout(FETCH_SHARD_TIMEOUT),\n })\n .then(async (response) => {\n const shard = response.headers.get('X-Sanity-Shard') || undefined\n\n // The ping response is tiny; consuming it lets the browser finish the\n // H2/H3 stream cleanly and avoids long pending receive/cancel timing.\n await response.arrayBuffer().catch(() => undefined)\n return shard\n })\n .catch(() => undefined)\n } catch {\n shardInfo = Promise.resolve(undefined)\n }\n\n const submittedMutations = commits$.pipe(\n map(\n (ev): LatencyTrackingEntry => ({\n type: 'submit' as const,\n transactionId: ev.transactionId,\n timestamp: new Date(),\n perfTimings: ev._perfTimings,\n }),\n ),\n share(),\n )\n\n const receivedMutations = listenerEvents$.pipe(\n filter((ev) => ev.type === 'mutation'),\n map(\n (ev): LatencyTrackingEntry => ({\n type: 'receive' as const,\n transactionId: ev.transactionId,\n timestamp: new Date(),\n }),\n ),\n share(),\n )\n\n // Clear pending entries on reconnection to avoid matching stale pre-reconnect\n // submit entries with post-reconnect listener events (which would produce\n // wildly inaccurate latency measurements).\n const reconnectionResets = listenerEvents$.pipe(\n filter((ev) => ev.type === 'reconnect' || ev.type === 'welcome' || ev.type === 'welcomeback'),\n map((): LatencyTrackingEntry => ({type: 'reset'})),\n )\n\n return merge(submittedMutations, receivedMutations, reconnectionResets).pipe(\n scan(\n (state: LatencyTrackingState, event): LatencyTrackingState => {\n if (event.type === 'reset') {\n return {event: undefined, pending: []}\n }\n\n // Evict stale entries to prevent unbounded growth from remote/duplicate mutations\n const now = Date.now()\n const pending = state.pending.filter((e) => now - e.timestamp.getTime() < PENDING_ENTRY_TTL)\n\n const matchingIndex = pending.findIndex(\n (e) => e.transactionId === event.transactionId && e.type !== event.type,\n )\n if (matchingIndex > -1) {\n const matching = pending[matchingIndex]\n const [submitEvent, receiveEvent] =\n matching.type === 'submit' ? [matching, event] : [event, matching]\n return {\n event: {\n transactionId: event.transactionId,\n submittedAt: submitEvent.timestamp,\n receivedAt: receiveEvent.timestamp,\n deltaMs: receiveEvent.timestamp.getTime() - submitEvent.timestamp.getTime(),\n perfTimings: submitEvent.type === 'submit' ? submitEvent.perfTimings : undefined,\n },\n // Remove the matched entry and any other entries with the same transactionId\n // (e.g., duplicate receive events from multi-document transactions)\n pending: pending.filter(\n (e, i) => i !== matchingIndex && e.transactionId !== event.transactionId,\n ),\n }\n }\n return {event: undefined, pending: pending.concat(event)}\n },\n {event: undefined, pending: []},\n ),\n map((state) => state.event),\n filter((event) => !!event),\n withLatestFrom(from(shardInfo).pipe(startWith(undefined))),\n tap(([event, shard]) => {\n try {\n onReportLatency?.({latencyMs: event.deltaMs, shard, transactionId: event.transactionId})\n } catch {\n // Telemetry callbacks must never kill the document pipeline\n }\n\n if (onReportMutationPerformance && event.perfTimings) {\n const {firstMutationReceivedAt, apiRequestSentAt, apiResponseReceivedAt} = event.perfTimings\n const listenerReceivedAt = event.receivedAt.getTime()\n\n if (firstMutationReceivedAt !== undefined) {\n try {\n onReportMutationPerformance({\n transactionId: event.transactionId,\n debounceMs: Math.max(0, apiRequestSentAt - firstMutationReceivedAt),\n apiMs: Math.max(0, apiResponseReceivedAt - apiRequestSentAt),\n // Listener and API response race each other — both are triggered\n // server-side after the mutation is committed. Measure callback from\n // when the request was sent, not when the HTTP response arrived.\n callbackMs: Math.max(0, listenerReceivedAt - apiRequestSentAt),\n shard,\n })\n } catch {\n // Telemetry callbacks must never kill the document pipeline\n }\n }\n }\n }),\n )\n}\n","import {type Observable} from 'rxjs'\n\nexport function memoize<TFunction extends (...args: any[]) => Observable<any>>(\n fn: TFunction,\n keyGen: (...args: Parameters<TFunction>) => string,\n): TFunction {\n const MEMO: {[key: string]: Observable<unknown>} = Object.create(null)\n const memoizedFn = (...args: Parameters<TFunction>): Observable<unknown> => {\n const key = keyGen(...args)\n if (!(key in MEMO)) {\n MEMO[key] = fn(...args)\n }\n return MEMO[key]\n }\n\n return memoizedFn as TFunction\n}\n","import {type SanityClient} from '@sanity/client'\n\nimport {type IdPair} from '../types'\n\nexport function memoizeKeyGen(client: SanityClient, idPair: IdPair, typeName: string) {\n const config = client.config()\n return `${config.dataset ?? ''}-${config.projectId ?? ''}-${idPair.publishedId}-${idPair.versionId ?? ''}-${typeName}`\n}\n","import {type SanityClient} from '@sanity/client'\nimport {EMPTY, merge, Observable, of, ReplaySubject, share, timer} from 'rxjs'\nimport {mergeMap} from 'rxjs/operators'\n\nimport {type DocumentStoreExtraOptions} from '../getPairListener'\nimport {type IdPair} from '../types'\nimport {memoize} from '../utils/createMemoizer'\nimport {checkoutPair, type Pair} from './checkoutPair'\nimport {memoizeKeyGen} from './memoizeKeyGen'\n\n// How long to keep listener connected for after last unsubscribe.\n// Reduced from 10s to 5s to limit concurrent SSE connections during\n// navigation-heavy sessions. 5s still covers most \"navigate away and back\"\n// patterns while cutting the stale connection window in half.\nconst LISTENER_RESET_DELAY = 5_000\n\nexport const memoizedPair: (\n client: SanityClient,\n idPair: IdPair,\n typeName: string,\n extraOptions?: DocumentStoreExtraOptions,\n) => Observable<Pair> = memoize(\n (\n client: SanityClient,\n idPair: IdPair,\n _typeName: string,\n pairListenerOptions?: DocumentStoreExtraOptions,\n ): Observable<Pair> => {\n return new Observable<Pair>((subscriber) => {\n const pair = checkoutPair(client, idPair, undefined, pairListenerOptions)\n return merge(\n of(pair),\n // merge in draft, published, and version events to makes sure they receive\n // the events they need for as long as the pair is subscribed to\n pair.draft.events.pipe(mergeMap(() => EMPTY)),\n pair.published.events.pipe(mergeMap(() => EMPTY)),\n pair.version?.events.pipe(mergeMap(() => EMPTY)) ?? EMPTY,\n ).subscribe(subscriber)\n }).pipe(\n share({\n connector: () => new ReplaySubject(1),\n resetOnComplete: true,\n resetOnRefCountZero: () => timer(LISTENER_RESET_DELAY),\n }),\n )\n },\n memoizeKeyGen,\n)\n","import {type SanityClient} from '@sanity/client'\nimport {type Observable} from 'rxjs'\nimport {distinctUntilChanged, shareReplay, switchMap} from 'rxjs/operators'\n\nimport {type DocumentStoreExtraOptions} from '../getPairListener'\nimport {type IdPair} from '../types'\nimport {memoize} from '../utils/createMemoizer'\nimport {type CommitError} from './checkoutPair'\nimport {memoizedPair} from './memoizedPair'\nimport {memoizeKeyGen} from './memoizeKeyGen'\n\n// The error from the most recent commit attempt for the document pair while\n// it failed and is being retried by the mutator, or `undefined` while\n// commits are healthy. Combined with consistency and connection state to\n// distinguish \"commits are failing\" from \"the backlog is merely slow\" — see\n// `useDocumentSyncState`.\nexport const commitErrorStatus: (\n client: SanityClient,\n idPair: IdPair,\n typeName: string,\n extraOptions?: DocumentStoreExtraOptions,\n) => Observable<CommitError | undefined> = memoize(\n (\n client: SanityClient,\n idPair: IdPair,\n typeName: string,\n extraOptions?: DocumentStoreExtraOptions,\n ) => {\n return memoizedPair(client, idPair, typeName, extraOptions).pipe(\n switchMap((pair) => pair.commitError$),\n distinctUntilChanged(),\n shareReplay({bufferSize: 1, refCount: true}),\n )\n },\n memoizeKeyGen,\n)\n","import {type SanityClient} from '@sanity/client'\nimport {combineLatest, of, type Observable} from 'rxjs'\nimport {distinctUntilChanged, map, publishReplay, refCount, switchMap} from 'rxjs/operators'\n\nimport {type DocumentStoreExtraOptions} from '../getPairListener'\nimport {type IdPair} from '../types'\nimport {memoize} from '../utils/createMemoizer'\nimport {memoizedPair} from './memoizedPair'\nimport {memoizeKeyGen} from './memoizeKeyGen'\n\n// A stream of all events related to either published or draft, each event comes with a 'target'\n// that specifies which version (draft|published) the event is about\nexport const consistencyStatus: (\n client: SanityClient,\n idPair: IdPair,\n typeName: string,\n extraOptions?: DocumentStoreExtraOptions,\n) => Observable<boolean> = memoize(\n (\n client: SanityClient,\n idPair: IdPair,\n typeName: string,\n extraOptions?: DocumentStoreExtraOptions,\n ) => {\n return memoizedPair(client, idPair, typeName, extraOptions).pipe(\n switchMap(({draft, published, version}) =>\n combineLatest([\n draft.consistency$,\n published.consistency$,\n version?.consistency$ ?? of(true),\n ]),\n ),\n map(\n ([draftIsConsistent, publishedIsConsistent, versionIsConsistent]) =>\n draftIsConsistent && publishedIsConsistent && versionIsConsistent,\n ),\n distinctUntilChanged(),\n publishReplay(1),\n refCount(),\n )\n },\n memoizeKeyGen,\n)\n","import {type SanityClient} from '@sanity/client'\nimport {EMPTY, merge, type Observable} from 'rxjs'\nimport {switchMap} from 'rxjs/operators'\n\nimport {type DocumentStoreExtraOptions} from '../getPairListener'\nimport {type IdPair} from '../types'\nimport {memoize} from '../utils/createMemoizer'\nimport {type DocumentVersionEvent} from './checkoutPair'\nimport {memoizedPair} from './memoizedPair'\nimport {memoizeKeyGen} from './memoizeKeyGen'\n\n// A stream of all events related to either published or draft, each event comes with a 'target'\n// that specifies which version (draft|published) the event is about\nexport const documentEvents = memoize(\n (\n client: SanityClient,\n idPair: IdPair,\n typeName: string,\n pairListenerOptions?: DocumentStoreExtraOptions,\n ): Observable<DocumentVersionEvent> => {\n return memoizedPair(client, idPair, typeName, pairListenerOptions).pipe(\n switchMap(({draft, published, version}) =>\n merge(draft.events, published.events, version?.events ?? EMPTY),\n ),\n )\n },\n memoizeKeyGen,\n)\n","import {type SanityClient} from '@sanity/client'\nimport {type SanityDocument} from '@sanity/types'\nimport {type Observable} from 'rxjs'\nimport {filter, map, publishReplay, refCount} from 'rxjs/operators'\n\nimport {type BufferedDocumentEvent} from '../buffered-doc/createBufferedDocument'\nimport {type MutationPayload, type SnapshotEvent} from '../buffered-doc/types'\nimport {type DocumentStoreExtraOptions} from '../getPairListener'\nimport {\n type IdPair,\n type PendingMutationsEvent,\n type ReconnectEvent,\n type ResetEvent,\n type WelcomeBackEvent,\n type WelcomeEvent,\n} from '../types'\nimport {memoize} from '../utils/createMemoizer'\nimport {type DocumentVersion} from './checkoutPair'\nimport {memoizedPair} from './memoizedPair'\nimport {memoizeKeyGen} from './memoizeKeyGen'\n\n// return true if the event comes with a document snapshot\nfunction isSnapshotEvent(\n event: BufferedDocumentEvent | ReconnectEvent | WelcomeEvent | WelcomeBackEvent | ResetEvent,\n): event is SnapshotEvent & {\n version: 'published' | 'draft'\n} {\n return event.type === 'snapshot'\n}\n\nfunction withSnapshots(pair: DocumentVersion): DocumentVersionSnapshots {\n return {\n snapshots$: pair.events.pipe(\n filter(isSnapshotEvent),\n map((event) => event.document),\n publishReplay(1),\n refCount(),\n ),\n\n patch: pair.patch,\n create: pair.create,\n createIfNotExists: pair.createIfNotExists,\n createOrReplace: pair.createOrReplace,\n delete: pair.delete,\n\n mutate: pair.mutate,\n commit: pair.commit,\n }\n}\n\n/** @internal */\nexport interface DocumentVersionSnapshots {\n snapshots$: Observable<SanityDocument>\n\n // helper functions\n patch: (patches: any[]) => MutationPayload[]\n create: (document: any) => MutationPayload\n createIfNotExists: (document: any) => MutationPayload\n createOrReplace: (document: any) => MutationPayload\n delete: () => MutationPayload\n\n mutate: (mutations: MutationPayload[]) => void\n commit: () => void\n}\n\n/** @internal */\ninterface SnapshotPair {\n transactionsPendingEvents$: Observable<PendingMutationsEvent>\n draft: DocumentVersionSnapshots\n published: DocumentVersionSnapshots\n version?: DocumentVersionSnapshots\n}\n\n/** @internal */\nexport const snapshotPair = memoize(\n (\n client: SanityClient,\n idPair: IdPair,\n typeName: string,\n /**\n * @deprecated does nothing\n * Preserved here to avoid breaking changes\n * Will be removed in the next major version.\n */\n _serverActionsEnabled?: Observable<boolean>,\n pairListenerOptions?: DocumentStoreExtraOptions,\n ): Observable<SnapshotPair> => {\n return memoizedPair(client, idPair, typeName, pairListenerOptions).pipe(\n map(({published, draft, version, transactionsPendingEvents$}): SnapshotPair => {\n return {\n transactionsPendingEvents$,\n published: withSnapshots(published),\n draft: withSnapshots(draft),\n ...(version ? {version: withSnapshots(version)} : {}),\n }\n }),\n publishReplay(1),\n refCount(),\n )\n },\n memoizeKeyGen,\n)\n","import {type SanityClient} from '@sanity/client'\nimport {type Schema} from '@sanity/types'\nimport {combineLatest, type Observable} from 'rxjs'\nimport {map, publishReplay, refCount, switchMap} from 'rxjs/operators'\n\nimport {type HistoryStore} from '../../history/createHistoryStore'\nimport {type DocumentStoreExtraOptions} from '../getPairListener'\nimport {type IdPair} from '../types'\nimport {memoize} from '../utils/createMemoizer'\nimport {memoizeKeyGen} from './memoizeKeyGen'\nimport {type OperationArgs} from './operations/types'\nimport {snapshotPair} from './snapshotPair'\n\nexport const operationArgs = memoize(\n (\n ctx: {\n client: SanityClient\n historyStore: HistoryStore\n schema: Schema\n pairListenerOptions?: DocumentStoreExtraOptions\n },\n idPair: IdPair,\n typeName: string,\n ): Observable<OperationArgs> => {\n return snapshotPair(ctx.client, idPair, typeName, undefined, ctx.pairListenerOptions).pipe(\n switchMap((versions) =>\n combineLatest([\n versions.draft.snapshots$,\n versions.published.snapshots$,\n ...(typeof versions.version === 'undefined' ? [] : [versions.version.snapshots$]),\n ]).pipe(\n map(\n ([draft, published, version]): OperationArgs => ({\n ...ctx,\n idPair,\n typeName,\n serverActionsEnabled: true,\n snapshots: {\n published,\n draft,\n ...(version\n ? {\n version,\n }\n : {}),\n },\n ...(versions.version\n ? {\n version: versions.version,\n }\n : {}),\n draft: versions.draft,\n published: versions.published,\n }),\n ),\n ),\n ),\n publishReplay(1),\n refCount(),\n )\n },\n (ctx, idPair, typeName) => {\n return memoizeKeyGen(ctx.client, idPair, typeName)\n },\n)\n","import {type SanityClient} from '@sanity/client'\n\nexport function getOperationStoreKey(client: SanityClient): string {\n const config = client.config()\n const {projectId, dataset} = config\n if (!projectId) {\n throw new Error('Client is missing projectId')\n }\n if (!dataset) {\n throw new Error('Client is missing dataset')\n }\n return `${projectId}-${dataset}`\n}\n","import {EMPTY} from 'rxjs'\n\nimport {type OperationImpl} from './types'\n\nexport const commit: OperationImpl = {\n disabled: (): false => false,\n execute: ({draft, published, version}) => {\n version?.commit()\n draft.commit()\n published.commit()\n // note: we might be able to connect with the outgoing commit request stream here\n return EMPTY\n },\n}\n","import {type SanityDocument} from '@sanity/types'\n\n/** @internal */\nexport const VARIANT_VERSION_DISABLED = 'VARIANT_VERSION' as const\n\n/** @internal */\nexport type VariantVersionDisabledReason = typeof VARIANT_VERSION_DISABLED\n\n/**\n * Legacy transaction-based operations in `operations/` are not supported for variant-scoped\n * versions. Variant documents route through `serverOperations/` and the variant document actions.\n *\n * @internal\n */\nexport function disabledForVariantVersion(\n version: SanityDocument | null | undefined,\n): VariantVersionDisabledReason | false {\n if (version?._system?.variant?._ref) {\n return VARIANT_VERSION_DISABLED\n }\n return false\n}\n\n/**\n * Corruption tripwire: the base/release document actions must never run against a variant-scoped\n * version. A base publish with a variant version in the `draftId` slot would publish variant\n * content INTO the base published document — data corruption, not a broken button. Operations\n * route variant versions to the variant document actions before reaching the base paths; this\n * assert is insurance that stays correct independently of that routing (e.g. through future\n * refactors or new call sites).\n *\n * @internal\n */\nexport function assertNotVariantVersion(\n version: SanityDocument | null | undefined,\n operationName: string,\n): void {\n if (version?._system?.variant?._ref) {\n throw new Error(\n `Cannot execute the base \"${operationName}\" operation against the variant-scoped version \"${version._id}\": this would write variant content into the base document. This is a bug in the operation routing — please report it.`,\n )\n }\n}\n","import {type Schema} from '@sanity/types'\n\nexport const isLiveEditEnabled = (schema: Schema, typeName: string): boolean =>\n schema.get(typeName)?.liveEdit === true\n","import {\n assertNotVariantVersion,\n disabledForVariantVersion,\n type VariantVersionDisabledReason,\n} from '../utils/assertNotVariantVersion'\nimport {isLiveEditEnabled} from '../utils/isLiveEditEnabled'\nimport {operationsApiClient} from '../utils/operationsApiClient'\nimport {type OperationImpl} from './types'\n\nexport const del: OperationImpl<[], 'NOTHING_TO_DELETE' | VariantVersionDisabledReason> = {\n disabled: ({snapshots}) => {\n // Legacy transaction delete. Variant-scoped versions are disabled here — use\n // `serverOperations/delete.ts` instead.\n const variantDisabled = disabledForVariantVersion(snapshots?.version)\n if (variantDisabled) {\n return variantDisabled\n }\n return snapshots.draft || snapshots.published ? false : 'NOTHING_TO_DELETE'\n },\n execute: ({client, schema, idPair, typeName, snapshots}) => {\n assertNotVariantVersion(snapshots.version, 'delete')\n const tx = operationsApiClient(client, idPair)\n .observable.transaction()\n .delete(idPair.publishedId)\n\n if (isLiveEditEnabled(schema, typeName)) {\n return tx.commit({tag: 'document.delete'})\n }\n\n return tx.delete(idPair.draftId).commit({\n tag: 'document.delete',\n // this disables referential integrity for cross-dataset references. we\n // have this set because we warn against deletes in the `ConfirmDeleteDialog`\n // UI. This operation is run when \"delete anyway\" is clicked\n skipCrossDatasetReferenceValidation: true,\n })\n },\n}\n","import {\n assertNotVariantVersion,\n disabledForVariantVersion,\n type VariantVersionDisabledReason,\n} from '../utils/assertNotVariantVersion'\nimport {operationsApiClient} from '../utils/operationsApiClient'\nimport {type OperationImpl} from './types'\n\ntype DisabledReason = 'NO_CHANGES' | 'NOT_PUBLISHED' | VariantVersionDisabledReason\n\nexport const discardChanges: OperationImpl<[], DisabledReason> = {\n disabled: ({snapshots}) => {\n // Legacy transaction discard-changes. Variant-scoped versions are disabled here — use\n // `serverOperations/discardChanges.ts` instead.\n const variantDisabled = disabledForVariantVersion(snapshots?.version)\n if (variantDisabled) {\n return variantDisabled\n }\n if (!snapshots.draft) {\n return 'NO_CHANGES'\n }\n if (!snapshots.published) {\n return 'NOT_PUBLISHED'\n }\n return false\n },\n execute: ({client, idPair, snapshots}) => {\n assertNotVariantVersion(snapshots.version, 'discardChanges')\n return operationsApiClient(client, idPair)\n .observable.transaction()\n .delete(idPair.draftId)\n .commit({tag: 'document.discard-changes'})\n },\n}\n","import {type SanityDocument, type SanityDocumentLike} from '@sanity/types'\nimport omit from 'lodash-es/omit.js'\n\nimport {getDraftId, getVersionFromId, getVersionId} from '../../../../util/draftUtils'\nimport {isLiveEditEnabled} from '../utils/isLiveEditEnabled'\nimport {operationsApiClient} from '../utils/operationsApiClient'\nimport {type MapDocument, type OperationImpl} from './types'\n\n// `_system` is authoritative, server-managed metadata (`group`/`scopeId`/`release`/`variant`\n// references of the SOURCE document): copying it onto the duplicate would attach the new\n// document to the source's group and scope.\nconst omitProps = ['_createdAt', '_updatedAt', '_system']\n\nconst getDocumentToDuplicateId = ({\n versionSnapshot,\n dupeId,\n liveEdit,\n}: {\n versionSnapshot?: SanityDocument | null | undefined\n dupeId: string\n liveEdit: boolean\n}) => {\n // When duplicating a version document we need to create it with a version id.\n // We get the version from the snapshot id and create a new version id for the duplicate.\n // Variant-scoped versions are the exception: their scope ids are opaque, server-generated\n // hashes that must never be fabricated client-side, so variant content duplicates into a new\n // base draft instead (product decision).\n if (versionSnapshot && !versionSnapshot._system?.variant?._ref) {\n const versionId = getVersionFromId(versionSnapshot._id)\n if (versionId) return getVersionId(dupeId, versionId)\n }\n\n if (liveEdit) {\n return dupeId\n }\n\n return getDraftId(dupeId)\n}\n\nconst mapDocumentNoop: MapDocument = (document) => document\n\nexport const duplicate: OperationImpl<\n [\n baseDocumentId: string,\n options?: {\n mapDocument?: MapDocument\n },\n ],\n 'NOTHING_TO_DUPLICATE'\n> = {\n disabled: ({snapshots}) => {\n return snapshots.published || snapshots.draft || snapshots.version\n ? false\n : 'NOTHING_TO_DUPLICATE'\n },\n execute: (\n {schema, client, snapshots, typeName, idPair},\n dupeId,\n {mapDocument = mapDocumentNoop} = {},\n ) => {\n const source = snapshots.version || snapshots.draft || snapshots.published\n\n if (!source) {\n throw new Error('cannot execute on empty document')\n }\n\n const _id = getDocumentToDuplicateId({\n versionSnapshot: snapshots.version,\n dupeId,\n liveEdit: isLiveEditEnabled(schema, typeName),\n })\n\n return operationsApiClient(client, idPair).observable.create(\n omit(\n mapDocument({\n ...source,\n _id,\n _type: source._type,\n }),\n omitProps,\n // Performing `Omit` on a type that has an index signature causes the known properties to\n // be lost.\n ) as SanityDocumentLike,\n {\n tag: 'document.duplicate',\n },\n )\n },\n}\n","import {\n assertNotVariantVersion,\n disabledForVariantVersion,\n type VariantVersionDisabledReason,\n} from '../utils/assertNotVariantVersion'\nimport {isLiveEditEnabled} from '../utils/isLiveEditEnabled'\nimport {type OperationImpl} from './types'\n\n// todo: we could also consider exposing 'mutate' directly\nexport const patch: OperationImpl<\n [patches: any[], initialDocument?: Record<string, any>],\n VariantVersionDisabledReason\n> = {\n // Legacy local patch. Variant-scoped versions are disabled here — use `serverOperations/patch.ts`\n // instead.\n disabled: ({snapshots}) => disabledForVariantVersion(snapshots?.version),\n execute: (\n {schema, snapshots, idPair, draft, published, version, typeName},\n patches = [],\n initialDocument,\n ): void => {\n assertNotVariantVersion(snapshots.version, 'patch')\n if (version) {\n // No drafting, so patch and commit the version document.\n version.mutate([\n version.createIfNotExists({\n _type: typeName,\n ...initialDocument,\n }),\n ...version.patch(patches),\n ])\n return\n }\n\n if (isLiveEditEnabled(schema, typeName)) {\n // No drafting, so patch and commit the published document\n published.mutate([\n published.createIfNotExists({\n _type: typeName,\n ...initialDocument,\n }),\n ...published.patch(patches),\n ])\n } else {\n draft.mutate([\n draft.createIfNotExists({\n ...initialDocument,\n ...snapshots.published,\n _id: idPair.draftId,\n _type: typeName,\n }),\n ...draft.patch(patches),\n ])\n }\n },\n}\n","import {isReference, type SanityDocument} from '@sanity/types'\nimport omit from 'lodash-es/omit.js'\n\nimport {\n assertNotVariantVersion,\n disabledForVariantVersion,\n type VariantVersionDisabledReason,\n} from '../utils/assertNotVariantVersion'\nimport {isLiveEditEnabled} from '../utils/isLiveEditEnabled'\nimport {operationsApiClient} from '../utils/operationsApiClient'\nimport {type OperationImpl, type PublishOptions} from './types'\n\nfunction strengthenOnPublish<T>(obj: T): T {\n if (isReference(obj)) {\n if (obj._strengthenOnPublish) {\n return omit(\n obj,\n ['_strengthenOnPublish'].concat(obj._strengthenOnPublish.weak ? [] : ['_weak']),\n ) as T\n }\n return obj\n }\n if (typeof obj !== 'object' || !obj) return obj\n if (Array.isArray(obj)) return obj.map(strengthenOnPublish) as T\n return Object.fromEntries(\n Object.entries(obj).map(([key, value]) => [key, strengthenOnPublish(value)] as const),\n ) as T\n}\n\ntype DisabledReason =\n | 'LIVE_EDIT_ENABLED'\n | 'ALREADY_PUBLISHED'\n | 'NO_CHANGES'\n | VariantVersionDisabledReason\n\nexport const publish: OperationImpl<[options?: PublishOptions], DisabledReason> = {\n disabled: ({schema, typeName, snapshots}) => {\n // Legacy transaction publish. Variant-scoped versions are disabled here — use\n // `serverOperations/publish.ts` instead.\n const variantDisabled = disabledForVariantVersion(snapshots?.version)\n if (variantDisabled) {\n return variantDisabled\n }\n if (isLiveEditEnabled(schema, typeName)) {\n return 'LIVE_EDIT_ENABLED'\n }\n if (!snapshots.draft && !snapshots.version) {\n return snapshots.published ? 'ALREADY_PUBLISHED' : 'NO_CHANGES'\n }\n return false\n },\n execute: ({client, idPair, snapshots}) => {\n if (!snapshots.draft && !snapshots.version) {\n throw new Error('cannot execute \"publish\" when draft or version is missing')\n }\n assertNotVariantVersion(snapshots.version, 'publish')\n\n const value = strengthenOnPublish(\n omit(snapshots.draft || snapshots.version, '_updatedAt') as SanityDocument,\n )\n const tx = operationsApiClient(client, idPair).observable.transaction()\n\n if (snapshots.published) {\n // If it exists already, we only want to update it if the revision on the remote server\n // matches what our local state thinks it's at\n tx.patch(idPair.publishedId, {\n // Hack until other mutations support revision locking\n unset: ['_revision_lock_pseudo_field_'],\n ifRevisionID: snapshots.published._rev,\n })\n\n tx.createOrReplace({\n ...value,\n _id: idPair.publishedId,\n })\n } else {\n // If the document has not been published, we want to create it - if it suddenly exists\n // before being created, we don't want to overwrite if, instead we want to yield an error\n tx.create({\n ...value,\n _id: idPair.publishedId,\n })\n }\n\n tx.delete(value._id)\n\n return tx.commit({tag: 'document.publish', visibility: 'async'})\n },\n}\n","import {type DocumentRevision} from '../../../history/createHistoryStore'\nimport {assertNotVariantVersion, disabledForVariantVersion} from '../utils/assertNotVariantVersion'\nimport {isLiveEditEnabled} from '../utils/isLiveEditEnabled'\nimport {type OperationImpl} from './types'\n\nexport const restore: OperationImpl<[fromRevision: DocumentRevision]> = {\n // Legacy restore. Variant-scoped versions are disabled here — use `serverOperations/restore.ts`\n // instead.\n disabled: ({snapshots}) => disabledForVariantVersion(snapshots?.version),\n execute: (\n {historyStore, schema, idPair, typeName, snapshots},\n fromRevision: DocumentRevision,\n ) => {\n assertNotVariantVersion(snapshots.version, 'restore')\n const targetId = idPair.versionId\n ? idPair.versionId\n : isLiveEditEnabled(schema, typeName)\n ? idPair.publishedId\n : idPair.draftId\n\n return historyStore.restore(idPair.publishedId, targetId, fromRevision)\n },\n}\n","import omit from 'lodash-es/omit.js'\n\nimport {\n assertNotVariantVersion,\n disabledForVariantVersion,\n type VariantVersionDisabledReason,\n} from '../utils/assertNotVariantVersion'\nimport {isLiveEditEnabled} from '../utils/isLiveEditEnabled'\nimport {operationsApiClient} from '../utils/operationsApiClient'\nimport {type OperationImpl} from './types'\n\ntype DisabledReason = 'LIVE_EDIT_ENABLED' | 'NOT_PUBLISHED' | VariantVersionDisabledReason\n\nexport const unpublish: OperationImpl<[], DisabledReason> = {\n disabled: ({schema, snapshots, typeName}) => {\n // Legacy transaction unpublish. Variant-scoped versions are disabled here — use\n // `serverOperations/unpublish.ts` instead.\n const variantDisabled = disabledForVariantVersion(snapshots?.version)\n if (variantDisabled) {\n return variantDisabled\n }\n if (isLiveEditEnabled(schema, typeName)) {\n return 'LIVE_EDIT_ENABLED'\n }\n return snapshots.published ? false : 'NOT_PUBLISHED'\n },\n execute: ({client, idPair, snapshots}) => {\n assertNotVariantVersion(snapshots.version, 'unpublish')\n\n let tx = operationsApiClient(client, idPair).observable.transaction().delete(idPair.publishedId)\n\n if (snapshots.published) {\n tx = tx.createIfNotExists({\n ...omit(snapshots.published, '_updatedAt'),\n _id: idPair.draftId,\n _type: snapshots.published._type,\n })\n }\n\n return tx.commit({\n tag: 'document.unpublish',\n visibility: 'async',\n // this disables referential integrity for cross-dataset references. we\n // have this set because we warn against unpublishes in the `ConfirmDeleteDialog`\n // UI. This operation is run when \"unpublish anyway\" is clicked\n skipCrossDatasetReferenceValidation: true,\n })\n },\n}\n","import {isPublishedId} from '@sanity/client/csm'\n\nimport {type OperationImpl} from '../operations/types'\nimport {actionsApiClient} from '../utils/actionsApiClient'\n\nexport const del: OperationImpl<[versions?: string[]], 'NOTHING_TO_DELETE'> = {\n disabled: ({snapshots}) =>\n snapshots.draft || snapshots.published || snapshots.version ? false : 'NOTHING_TO_DELETE',\n execute: ({client, idPair, snapshots}, versions = []) => {\n //the delete action requires a published doc -- discard versions if not present\n if (!snapshots.published) {\n return actionsApiClient(client, idPair).observable.action(\n versions.map((versionId) => ({\n actionType: 'sanity.action.document.version.discard',\n versionId,\n })),\n {\n skipCrossDatasetReferenceValidation: true,\n },\n )\n }\n\n return actionsApiClient(client, idPair).observable.action(\n {\n actionType: 'sanity.action.document.delete',\n includeDrafts: versions\n ? // if versions are provided, remove the published id from the list, all versions need to be included in order for the delete to work.\n versions.filter((v) => !isPublishedId(v))\n : snapshots.draft\n ? [idPair.draftId]\n : [],\n publishedId: idPair.publishedId,\n },\n {\n tag: 'document.delete',\n // this disables referential integrity for cross-dataset references. we\n // have this set because we warn against deletes in the `ConfirmDeleteDialog`\n // UI. This operation is run when \"delete anyway\" is clicked\n skipCrossDatasetReferenceValidation: true,\n },\n )\n },\n}\n","import {type SourceClientOptions} from '../../config/types'\n\n// api extractor take issues with 'as const' for literals\n// oxlint-disable-next-line prefer-as-const\nexport const VARIANT_DOCUMENT_TYPE: 'system.variant' = 'system.variant'\n// System path for variant definition document IDs.\n// IDs are built as `${VARIANT_DOCUMENTS_PATH}.<suffix>` (for example, `_.variants.Ab12cd34`).\n// oxlint-disable-next-line typescript/prefer-as-const\nexport const VARIANT_DOCUMENTS_PATH: '_.variants' = '_.variants'\n\n/**\n * @internal\n * This is the client options used for the variants studio client, using the `X` API version for now\n * TODO: Replace with a dated version once we have a stable API version\n */\nexport const VARIANTS_STUDIO_CLIENT_OPTIONS: SourceClientOptions = {\n apiVersion: 'X',\n}\n","import {isPortableTextBlock, toPlainText} from '@portabletext/toolkit'\nimport {type DocumentSystem} from '@sanity/types'\n\nimport {type PerspectiveBundle} from '../../perspective/types'\nimport {DOCUMENT_SYSTEM_FIELD} from '../../preview/constants'\nimport {VARIANT_DOCUMENTS_PATH} from '../store/constants'\nimport {type SystemVariant} from '../types'\n\nconst VARIANT_ID_PREFIX = `${VARIANT_DOCUMENTS_PATH}.`\n\n/**\n * Published documents omit `bundleId` on `_system`, but `PerspectiveBundle` also includes the\n * `'published'` literal. Call sites should treat both as published without rewriting the value.\n *\n * @internal\n */\nexport function isPublishedBundleId(bundleId: PerspectiveBundle | undefined): boolean {\n return bundleId === undefined || bundleId === 'published'\n}\n\n/**\n * @internal\n */\nexport function isReleaseBundle(bundleId: PerspectiveBundle | undefined): boolean {\n return !isPublishedBundleId(bundleId) && bundleId !== 'drafts'\n}\n\n/**\n * @internal\n */\nexport function getVariantId(variantDocumentId: string): string {\n return variantDocumentId.startsWith(VARIANT_ID_PREFIX)\n ? variantDocumentId.slice(VARIANT_ID_PREFIX.length)\n : variantDocumentId\n}\n\n/**\n * Returns the short variant id for sticky params from a document's `_system.variant._ref`.\n *\n * @internal\n */\nexport function getVariantIdFromDocument(document: Record<string, unknown>): string | undefined {\n const system = document[DOCUMENT_SYSTEM_FIELD] as DocumentSystem | undefined\n const variantRef = system?.variant?._ref\n\n return variantRef ? getVariantId(variantRef) : undefined\n}\n\n/**\n * @internal\n */\nexport function getVariantTitle(variant: SystemVariant): string {\n const title = variant.metadata?.title\n\n if (typeof title === 'string' && title.trim()) {\n return title\n }\n\n return getVariantId(variant._id)\n}\n\n/**\n * @internal\n */\nexport function getVariantConditionsText(conditions: SystemVariant['conditions']): string {\n return Object.entries(conditions)\n .map(([key, value]) => `${key}: ${JSON.stringify(value)}`)\n .join(', ')\n}\n\n/**\n * Decodes router state / URL path segments back to a variant document id.\n *\n * @internal\n */\nexport function decodeVariantIdFromRoute(variantIdRaw: string | undefined): string | undefined {\n if (!variantIdRaw) {\n return undefined\n }\n\n let decoded: string\n\n try {\n decoded = decodeURIComponent(variantIdRaw)\n } catch {\n decoded = variantIdRaw\n }\n\n if (decoded.startsWith(`${VARIANT_ID_PREFIX}`)) {\n return decoded\n }\n\n return `${VARIANT_ID_PREFIX}${decoded}`\n}\n\n/**\n * @internal\n */\nexport function getVariantDescription(variant: SystemVariant): string {\n const description = variant.metadata?.description\n\n if (!Array.isArray(description) || !description.every(isPortableTextBlock)) {\n return ''\n }\n\n return toPlainText(description).trim()\n}\n\n/**\n * @internal\n */\nexport function filterVariantsForSearch(\n variants: SystemVariant[],\n searchTerm: string,\n): SystemVariant[] {\n const normalizedSearchTerm = searchTerm.trim().toLowerCase()\n\n if (!normalizedSearchTerm) {\n return variants\n }\n\n return variants.filter((variant) => {\n const searchableValues = [\n getVariantTitle(variant),\n getVariantId(variant._id),\n ...Object.entries(variant.conditions).flat(),\n ]\n\n return searchableValues.some((value) => value.toLowerCase().includes(normalizedSearchTerm))\n })\n}\n","import {type SanityDocument} from '@sanity/types'\n\nimport {getVariantId} from '../tool/util'\n\n/**\n * The routing information of a variant-scoped version document, derived from its `_system`.\n *\n */\nexport interface VariantVersionInfo {\n /** The short variant name (the `_.variants.` prefix stripped from `_system.variant._ref`). */\n variantId: string\n /**\n * The bundle the variant document belongs to: `'drafts'`, a release id, or `'published'` for\n * the variant-of-published document (which carries no `_system.bundleId`).\n */\n bundleId: 'drafts' | 'published' | (string & {})\n}\n\n/**\n * Derives variant routing information from a version document snapshot's `_system`, or\n * `undefined` when the document is not variant-scoped.\n *\n * This is the single discriminator the document operations use to decide between the base and\n * variant action paths. The `_system` field is authoritative and always present on variant\n * documents — only pre-migration non-variant documents may lack it, and those can never be\n * variant-scoped.\n *\n */\nexport function getVariantVersionInfo(\n version: SanityDocument | null | undefined,\n): VariantVersionInfo | undefined {\n const variantRef = version?._system?.variant?._ref\n if (!variantRef) {\n return undefined\n }\n\n return {\n // Strip the `_.variants.` document path prefix to the short variant id. Kept local (instead\n // of `getVariantId` from `variants/tool/util`) to avoid pulling tool-level modules — and\n // their import cycles — into the document store's operations graph.\n variantId: getVariantId(variantRef),\n bundleId: version._system?.bundleId ?? 'published',\n }\n}\n","import {\n type BaseActionOptions,\n type ObservableSanityClient,\n type SanityClient,\n type SingleActionResult,\n} from '@sanity/client'\nimport {type SanityDocumentLike} from '@sanity/types'\nimport {type Observable} from 'rxjs'\n\nimport {type PerspectiveBundle} from '../../perspective/types'\nimport {type EditableSystemVariant} from '../types'\n\n/**\n * Variant definition actions resolve to the transaction id of the submitted\n * mutation, not the affected document.\n */\nexport interface VariantDefinitionActionResult {\n transactionId: string\n}\n\n/** Supported bundle targets for variant document creation. */\nexport type VariantDocumentBundleId = undefined | Exclude<PerspectiveBundle, 'published'>\n\n/**\n * Variant definition action payloads. See ../ACTIONS.md.\n *\n */\nexport interface VariantDefinitionCreateAction {\n actionType: 'sanity.action.variant.definition.create'\n variantId: string\n conditions?: EditableSystemVariant['conditions']\n priority?: number\n metadata?: EditableSystemVariant['metadata']\n}\n\nexport interface VariantDefinitionEditAction {\n actionType: 'sanity.action.variant.definition.edit'\n variantId: string\n patch: {\n set: Pick<EditableSystemVariant, 'conditions' | 'priority'> &\n Partial<Pick<EditableSystemVariant, 'metadata'>>\n unset?: ['metadata']\n }\n ifRevisionId?: string\n}\n\nexport interface VariantDefinitionDeleteAction {\n actionType: 'sanity.action.variant.definition.delete'\n variantId: string\n ifRevisionId?: string\n}\n\nexport type VariantDefinitionAction =\n | VariantDefinitionCreateAction\n | VariantDefinitionEditAction\n | VariantDefinitionDeleteAction\n\ninterface VariantDocumentCreateActionBase {\n actionType: 'sanity.action.document.variant.create'\n publishedId: string\n variantId: string\n bundleId?: VariantDocumentBundleId\n}\n\nexport interface VariantDocumentCreateFromDocumentAction extends VariantDocumentCreateActionBase {\n document: SanityDocumentLike\n}\n\nexport interface VariantDocumentCreateFromBaseAction extends VariantDocumentCreateActionBase {\n baseId: string\n ifBaseRevisionId?: string\n}\n\nexport type VariantDocumentCreateAction =\n | VariantDocumentCreateFromDocumentAction\n | VariantDocumentCreateFromBaseAction\n\n/**\n * Publishes a variant-scoped version into the variant-of-published document.\n * `bundleId` is the SOURCE bundle being published (`'drafts'` or a release name);\n * `'published'` is rejected by the API (target equals source).\n */\nexport interface VariantDocumentPublishAction {\n actionType: 'sanity.action.document.variant.publish'\n publishedId: string\n variantId: string\n bundleId: 'drafts' | (string & {})\n /**\n * Optimistic lock on the source variant document's revision.\n * Note: specced but not accepted by the deployed action yet (`json: unknown field`).\n */\n ifSourceRevisionId?: string\n /**\n * Optimistic lock on the variant-of-published target's revision.\n * Sourced from `publishedSibling._rev` (not the base published document).\n */\n ifPublishedVariantRevisionId?: string\n}\n\n/**\n * Unpublishes a variant document. `bundleId` addresses the variant version being unpublished:\n *\n * - `undefined` — the variant-of-published document: hard unpublish (the published variant is\n * deleted and its content recreated as the variant draft), mirroring base unpublish.\n * - a release name — a release-scoped variant: soft unpublish (`_system.delete: true` marker),\n * completed when the release is published.\n *\n * `'drafts'` is not a valid target: a drafts-scoped variant has nothing published to unpublish.\n * The explicit `undefined` (rather than an optional field) forces callers to consciously choose\n * the published variant. See CLDX-5781 / SAPP-4012.\n */\nexport interface VariantDocumentUnpublishAction {\n actionType: 'sanity.action.document.variant.unpublish'\n publishedId: string\n variantId: string\n bundleId: undefined | (string & {})\n}\n\n/**\n * Deletes a variant-scoped version document in the given bundle\n * (omitted `bundleId` targets the variant-of-published document).\n */\nexport interface VariantDocumentDeleteAction {\n actionType: 'sanity.action.document.variant.delete'\n publishedId: string\n variantId: string\n bundleId?: 'drafts' | (string & {})\n /** Also removes history from the translog. Defaults to false. */\n purge?: boolean\n}\n\nexport type VariantDocumentAction =\n | VariantDocumentCreateAction\n | VariantDocumentPublishAction\n | VariantDocumentUnpublishAction\n | VariantDocumentDeleteAction\n\nexport type VariantAction = VariantDefinitionAction | VariantDocumentAction\n\n/**\n * Temporary observable client typing until sanity/client exports variant actions.\n */\nexport interface ObservableSanityClientWithVariantsActions extends Omit<\n ObservableSanityClient,\n 'action'\n> {\n action(\n action: VariantDefinitionAction,\n options?: BaseActionOptions,\n ): Observable<VariantDefinitionActionResult>\n action(action: VariantDocumentAction, options?: BaseActionOptions): Observable<SingleActionResult>\n action(\n action: VariantAction,\n options?: BaseActionOptions,\n ): Observable<VariantDefinitionActionResult | SingleActionResult>\n}\n\n/**\n * Temporary client typing until sanity/client exports variant actions.\n */\nexport interface SanityClientWithVariantsActions extends Omit<\n SanityClient,\n 'action' | 'observable'\n> {\n action(\n action: VariantDefinitionAction,\n options?: BaseActionOptions,\n ): Promise<VariantDefinitionActionResult>\n action(action: VariantDocumentAction, options?: BaseActionOptions): Promise<SingleActionResult>\n action(\n action: VariantAction,\n options?: BaseActionOptions,\n ): Promise<VariantDefinitionActionResult | SingleActionResult>\n observable: ObservableSanityClientWithVariantsActions\n}\n\n/**\n * Returns a client whose `action` and `observable.action` methods accept variant actions.\n * Remove once sanity/client exports these action types.\n */\nexport function variantsClient(client: SanityClient): SanityClientWithVariantsActions {\n return client as unknown as SanityClientWithVariantsActions\n}\n","import {type SanityClient} from '@sanity/client'\n\nimport {VARIANTS_STUDIO_CLIENT_OPTIONS} from '../../../../variants/store/constants'\nimport {variantsClient} from '../../../../variants/store/variantsClient'\n\n/**\n * Returns a client configured for variant document actions (publish/unpublish/delete).\n * Mirrors `actionsApiClient`, which configures the base/release actions API version.\n *\n * The cast exists because `@sanity/client` does not export the variant action types yet — same\n * situation as `variantsClient` in `core/variants/store/variantsClient.ts`.\n */\nexport function variantActionsApiClient(client: SanityClient) {\n return variantsClient(client.withConfig(VARIANTS_STUDIO_CLIENT_OPTIONS))\n}\n","import {getVariantVersionInfo} from '../../../../variants/documents/getVariantVersionInfo'\nimport {type OperationImpl} from '../operations/types'\nimport {actionsApiClient} from '../utils/actionsApiClient'\nimport {variantActionsApiClient} from '../utils/variantActionsApiClient'\n\ntype DisabledReason = 'NO_CHANGES'\n\nexport const discardChanges: OperationImpl<[], DisabledReason> = {\n disabled: ({snapshots}) => {\n if (!snapshots.draft && !snapshots.version) {\n return 'NO_CHANGES'\n }\n // The variant-of-published document has no draft-ness to discard; removing the published\n // variant is unpublish's job.\n if (getVariantVersionInfo(snapshots.version)?.bundleId === 'published') {\n return 'NO_CHANGES'\n }\n return false\n },\n execute: ({client, idPair, snapshots}) => {\n const variantVersion = getVariantVersionInfo(snapshots.version)\n if (variantVersion) {\n if (variantVersion.bundleId === 'published') {\n throw new Error('Cannot discard changes of a published variant: unpublish it instead')\n }\n // Discarding a variant version (drafts- or release-scoped) is deleting the variant\n // document in that bundle. The generic `sanity.action.document.discard` addresses drafts\n // by raw id; the variant action addresses them by (publishedId, variantId, bundleId),\n // which is the supported surface for variant-scoped versions.\n return variantActionsApiClient(client).observable.action(\n {\n actionType: 'sanity.action.document.variant.delete',\n publishedId: idPair.publishedId,\n variantId: variantVersion.variantId,\n bundleId: variantVersion.bundleId,\n },\n {tag: 'document.discard-changes'},\n )\n }\n\n return actionsApiClient(client, idPair).observable.action(\n {\n actionType: 'sanity.action.document.discard',\n draftId: idPair.versionId || idPair.draftId,\n },\n {tag: 'document.discard-changes'},\n )\n },\n}\n","import {type OperationImpl} from '../operations/types'\nimport {isLiveEditEnabled} from '../utils/isLiveEditEnabled'\n\nexport const patch: OperationImpl<[patches: any[], initialDocument?: Record<string, any>]> = {\n disabled: (): false => false,\n execute: (\n {schema, snapshots, idPair, draft, published, version, typeName},\n patches = [],\n initialDocument,\n ): void => {\n if (version) {\n // No drafting, so patch and commit the version document.\n const patchMutation = version.patch(patches)\n // Note: if the document doesn't exist on the server yet, we need to create it first. We only want to do this if we can't see it locally\n // if it's been deleted on the server we want that to become a mutation error when submitting.\n const ensureVersion = snapshots.version\n ? version.patch([\n {\n unset: ['_empty_action_guard_pseudo_field_'],\n },\n ])\n : [\n version.create({\n ...initialDocument,\n _id: idPair.draftId,\n _type: typeName,\n }),\n ]\n // No drafting, so patch and commit the published document\n version.mutate([...ensureVersion, ...patchMutation])\n\n return\n }\n\n if (isLiveEditEnabled(schema, typeName)) {\n // No drafting, so patch and commit the published document\n const patchMutation = published.patch(patches)\n // Note: if the document doesn't exist on the server yet, we need to create it first. We only want to do this if we can't see it locally\n // if it's been deleted on the server we want that to become a mutation error when submitting.\n const mutations = snapshots.published\n ? patchMutation\n : [\n published.createIfNotExists({\n _type: typeName,\n ...initialDocument,\n }),\n ...patchMutation,\n ]\n // No drafting, so patch and commit the published document\n published.mutate(mutations)\n\n return\n }\n\n const patchMutation = draft.patch(patches)\n if (snapshots.draft) {\n draft.mutate([\n ...draft.patch([{unset: ['_empty_action_guard_pseudo_field_']}]),\n ...patchMutation,\n ])\n return\n }\n\n // At this point we don't have a draft, so we need to create it.\n // Only use the createMutation if the draft doesn't exist.\n // Creation will happen in a different transaction than the patch, to get the correct initial value for it.\n\n const createMutation = snapshots.published\n ? // If there's no draft, the user's edits will be based on the published document in the form in front of them\n // so before patching it we need to make sure it's created based on the current published version first.\n draft.createIfNotExists({\n ...initialDocument,\n ...snapshots.published,\n _id: idPair.draftId,\n _type: typeName,\n })\n : // If the published doesn't exist we need to trigger a `create` action, because we are internally\n // transforming the createIfNotExists action to a patch, which requires the published document to exist.\n // see checkoutPair.ts toActions function for more details.\n draft.create({\n ...initialDocument,\n _id: idPair.draftId,\n _type: typeName,\n })\n\n draft.mutate([createMutation])\n // Commit so we create the draft in a different transaction than the patch, and we get the correct initial value for it.\n draft.commit()\n // We do it in two steps to first create the draft with the copied version and then reflect the user edit to preserve the history.\n draft.mutate(patchMutation)\n },\n}\n","import {getVariantVersionInfo} from '../../../../variants/documents/getVariantVersionInfo'\nimport {type OperationImpl, type PublishOptions} from '../operations/types'\nimport {actionsApiClient} from '../utils/actionsApiClient'\nimport {assertNotVariantVersion} from '../utils/assertNotVariantVersion'\nimport {isLiveEditEnabled} from '../utils/isLiveEditEnabled'\nimport {variantActionsApiClient} from '../utils/variantActionsApiClient'\n\ntype DisabledReason = 'LIVE_EDIT_ENABLED' | 'ALREADY_PUBLISHED' | 'NO_CHANGES' | 'NOT_PUBLISHABLE'\n\nexport const publish: OperationImpl<[options?: PublishOptions], DisabledReason> = {\n disabled: ({schema, typeName, snapshots}) => {\n if (isLiveEditEnabled(schema, typeName)) {\n return 'LIVE_EDIT_ENABLED'\n }\n\n const variantVersion = getVariantVersionInfo(snapshots.version)\n if (variantVersion) {\n // The checked-out version IS the variant-of-published document: nothing to publish.\n if (variantVersion.bundleId === 'published') {\n return 'ALREADY_PUBLISHED'\n }\n // Release-scoped variant documents are published as part of their release, mirroring how\n // plain release versions are not publishable by this action.\n if (snapshots.version?._system?.release?._ref) {\n return 'NOT_PUBLISHABLE'\n }\n return false\n }\n\n if (!snapshots.draft && !snapshots.version) {\n return snapshots.published ? 'ALREADY_PUBLISHED' : 'NO_CHANGES'\n }\n return false\n },\n execute: ({client, idPair, snapshots}, options) => {\n // The editor must be able to see the draft they are choosing to publish.\n if (!snapshots.draft && !snapshots.version) {\n throw new Error('cannot execute \"publish\" when draft or version is missing')\n }\n if (idPair.versionId && !snapshots.version) {\n throw new Error('cannot execute \"publish\" when version is missing but versionId is provided')\n }\n\n const variantVersion = getVariantVersionInfo(snapshots.version)\n if (variantVersion) {\n if (variantVersion.bundleId === 'published') {\n throw new Error(\n 'cannot execute \"publish\" on a variant-of-published document: it is already published',\n )\n }\n\n // Publishes the variant document into the variant-of-published document. The base\n // published document is never touched.\n //\n // `publishedRevisionId` → `ifPublishedVariantRevisionId` locks on the\n // variant-of-published sibling revision (passed from PublishAction via\n // `publishedSibling._rev` — that sibling is not in any pair snapshot slot).\n // `ifSourceRevisionId` is still omitted: the deployed action rejects it\n // (`json: unknown field`).\n // TODO(SAPP): send `ifSourceRevisionId: snapshots.version?._rev` once the action supports it.\n return variantActionsApiClient(client).observable.action(\n {\n actionType: 'sanity.action.document.variant.publish',\n publishedId: idPair.publishedId,\n variantId: variantVersion.variantId,\n bundleId: variantVersion.bundleId,\n ifPublishedVariantRevisionId: options?.publishedRevisionId,\n },\n {tag: 'document.publish'},\n )\n }\n\n assertNotVariantVersion(snapshots.version, 'publish')\n\n return actionsApiClient(client, idPair).observable.action(\n {\n actionType: 'sanity.action.document.publish',\n draftId: (snapshots.version?._id || snapshots.draft?._id)!,\n publishedId: idPair.publishedId,\n // Optimistic locking using `ifPublishedRevisionId` ensures that concurrent publish action\n // invocations do not override each other. Prefer an explicit `publishedRevisionId` when\n // provided; otherwise fall back to the published snapshot (the normal draft path).\n //\n // Note: for custom publish actions, `snapshots.draft._rev` may be stale, which means the\n // `ifDraftRevisionId` optimistic lock cannot currently be used.\n ifPublishedRevisionId: options?.publishedRevisionId ?? snapshots.published?._rev,\n },\n {\n tag: 'document.publish',\n },\n )\n },\n}\n","import {type DocumentRevision} from '../../../history/createHistoryStore'\nimport {type OperationImpl} from '../operations/types'\nimport {isLiveEditEnabled} from '../utils/isLiveEditEnabled'\n\nexport const restore: OperationImpl<[fromRevision: DocumentRevision]> = {\n disabled: (): false => false,\n execute: (\n {snapshots, historyStore, schema, idPair, typeName},\n fromRevision: DocumentRevision,\n ) => {\n const targetId = idPair.versionId\n ? idPair.versionId\n : isLiveEditEnabled(schema, typeName)\n ? idPair.publishedId\n : idPair.draftId\n\n return historyStore.restore(idPair.publishedId, targetId, fromRevision, {\n fromDeleted: !snapshots.draft && !snapshots.published,\n useServerDocumentActions: true,\n })\n },\n}\n","import {getVariantVersionInfo} from '../../../../variants/documents/getVariantVersionInfo'\nimport {type OperationImpl} from '../operations/types'\nimport {actionsApiClient} from '../utils/actionsApiClient'\nimport {assertNotVariantVersion} from '../utils/assertNotVariantVersion'\nimport {isLiveEditEnabled} from '../utils/isLiveEditEnabled'\nimport {variantActionsApiClient} from '../utils/variantActionsApiClient'\n\ntype DisabledReason = 'LIVE_EDIT_ENABLED' | 'NOT_PUBLISHED'\n\nexport const unpublish: OperationImpl<[], DisabledReason> = {\n disabled: ({schema, snapshots, typeName}) => {\n if (isLiveEditEnabled(schema, typeName)) {\n return 'LIVE_EDIT_ENABLED'\n }\n\n const variantVersion = getVariantVersionInfo(snapshots.version)\n if (variantVersion) {\n // Unpublishable variant versions:\n // - the variant-of-published document itself (no bundleId), which is hard-unpublished\n // - a release-scoped variant, which is soft-unpublished as part of its release\n // A drafts-scoped variant has nothing published in its slot to unpublish.\n return variantVersion.bundleId !== 'drafts' ? false : 'NOT_PUBLISHED'\n }\n\n return snapshots.published ? false : 'NOT_PUBLISHED'\n },\n execute: ({client, idPair, snapshots}) => {\n const variantVersion = getVariantVersionInfo(snapshots.version)\n if (variantVersion) {\n if (variantVersion.bundleId === 'drafts') {\n throw new Error('Cannot unpublish a draft variant')\n }\n // `bundleId` is the version snapshot's own bundle:\n // - `undefined` (variant-of-published): hard unpublish — the backend deletes the published\n // variant and creates the variant draft from its content (mirror of base unpublish)\n // - a release id: soft unpublish — the backend marks the release-scoped variant with\n // `_system.delete: true`, completed when the release is published\n // The base published and draft documents are never touched either way.\n return variantActionsApiClient(client).observable.action(\n {\n actionType: 'sanity.action.document.variant.unpublish',\n publishedId: idPair.publishedId,\n variantId: variantVersion.variantId,\n bundleId: snapshots.version?._system?.bundleId,\n },\n {\n tag: 'document.unpublish',\n skipCrossDatasetReferenceValidation: true,\n },\n )\n }\n\n assertNotVariantVersion(snapshots.version, 'unpublish')\n\n return actionsApiClient(client, idPair).observable.action(\n {\n // This operation is run when \"unpublish anyway\" is clicked\n actionType: 'sanity.action.document.unpublish',\n draftId: idPair.draftId,\n publishedId: idPair.publishedId,\n },\n {\n tag: 'document.unpublish',\n // this disables referential integrity for cross-dataset references. we\n // have this set because we warn against unpublishes in the `ConfirmDeleteDialog`\n // UI.\n skipCrossDatasetReferenceValidation: true,\n },\n )\n },\n}\n","import {type SanityClient} from '@sanity/client'\nimport {type Schema} from '@sanity/types'\nimport {asyncScheduler, defer, EMPTY, merge, type Observable, of, Subject, timer} from 'rxjs'\nimport {\n catchError,\n concatMap,\n filter,\n groupBy,\n last,\n map,\n mergeMap,\n mergeMapTo,\n share,\n switchMap,\n take,\n tap,\n throttleTime,\n} from 'rxjs/operators'\n\nimport {type HistoryStore} from '../../history/createHistoryStore'\nimport {type DocumentStoreExtraOptions} from '../getPairListener'\nimport {type IdPair} from '../types'\nimport {memoize} from '../utils/createMemoizer'\nimport {consistencyStatus} from './consistencyStatus'\nimport {getOperationStoreKey} from './getOperationStoreKey'\nimport {operationArgs} from './operationArgs'\nimport {commit} from './operations/commit'\nimport {del} from './operations/delete'\nimport {discardChanges} from './operations/discardChanges'\nimport {duplicate} from './operations/duplicate'\nimport {patch} from './operations/patch'\nimport {publish} from './operations/publish'\nimport {restore} from './operations/restore'\nimport {type OperationArgs, type OperationsAPI} from './operations/types'\nimport {unpublish} from './operations/unpublish'\nimport {del as serverDel} from './serverOperations/delete'\nimport {discardChanges as serverDiscardChanges} from './serverOperations/discardChanges'\nimport {patch as serverPatch} from './serverOperations/patch'\nimport {publish as serverPublish} from './serverOperations/publish'\nimport {restore as serverRestore} from './serverOperations/restore'\nimport {unpublish as serverUnpublish} from './serverOperations/unpublish'\n\ninterface ExecuteArgs {\n operationName: keyof OperationsAPI\n idPair: IdPair\n typeName: string\n storeKey?: string\n extraArgs: any[]\n}\n\nfunction maybeObservable(v: void | Observable<any>) {\n return typeof v === 'undefined' ? of(null) : v\n}\n\nconst operationImpls = {\n del: del,\n delete: del,\n publish,\n patch,\n commit,\n discardChanges,\n unpublish,\n duplicate,\n restore,\n} as const\n\n//as we add server operations one by one, we can add them here\n// Note: Any changes must also be made to `createOperationsAPI`, which is defined in `packages/sanity/src/core/store/document/document-pair/operations/helpers.ts`.\nconst serverOperationImpls = {\n ...operationImpls,\n del: serverDel,\n delete: serverDel,\n discardChanges: serverDiscardChanges,\n patch: serverPatch,\n publish: serverPublish,\n unpublish: serverUnpublish,\n restore: serverRestore,\n}\n\nconst execute = (\n operationName: keyof typeof operationImpls,\n operationArguments: OperationArgs,\n extraArgs: any[],\n): Observable<any> => {\n const operation = serverOperationImpls[operationName]\n return defer(() =>\n merge(of(null), maybeObservable(operation.execute(operationArguments, ...extraArgs))),\n ).pipe(last())\n}\n\nconst operationCalls$ = new Subject<ExecuteArgs>()\n\n/** @internal */\nexport function emitOperation(\n operationName: keyof OperationsAPI,\n idPair: IdPair,\n typeName: string,\n extraArgs: any[],\n storeKey?: string,\n): void {\n operationCalls$.next({operationName, idPair, typeName, storeKey, extraArgs})\n}\n\n// These are the operations that cannot be performed while the document is in an inconsistent state\nconst REQUIRES_CONSISTENCY = ['publish', 'unpublish', 'discardChanges', 'delete']\n\n/**\n * @hidden\n * @beta */\nexport interface OperationError {\n type: 'error'\n /** @internal */\n op: keyof OperationsAPI\n id: string\n error: Error\n idPair: IdPair\n}\n\n/**\n * @hidden\n * @beta */\nexport interface OperationSuccess {\n type: 'success'\n /** @internal */\n op: keyof OperationsAPI\n id: string\n idPair: IdPair\n}\n\ninterface IntermediarySuccess {\n type: 'success'\n args: ExecuteArgs\n}\n\ninterface IntermediaryError {\n type: 'error'\n args: ExecuteArgs\n error: any\n}\n\n/** @internal */\nexport const operationEvents = memoize(\n (ctx: {\n client: SanityClient\n historyStore: HistoryStore\n schema: Schema\n /**\n * @deprecated Does nothing. Preserved to avoid breaking changes.\n * Will be removed in the next major version.\n */\n serverActionsEnabled?: Observable<boolean>\n extraOptions?: DocumentStoreExtraOptions\n }) => {\n const storeKey = getOperationStoreKey(ctx.client)\n const result$: Observable<IntermediarySuccess | IntermediaryError> = operationCalls$.pipe(\n filter((op) => op.storeKey === storeKey || !op.storeKey),\n groupBy((op) => op.idPair.publishedId),\n mergeMap((groups$) =>\n groups$.pipe(\n // although it might look like a bug, dropping pending async operations here is actually a feature\n // E.g. if the user types `publish` which is async and then starts patching (sync) then the publish\n // should be cancelled\n switchMap((args) =>\n operationArgs(ctx, args.idPair, args.typeName).pipe(\n take(1),\n switchMap((operationArguments) => {\n const requiresConsistency = REQUIRES_CONSISTENCY.includes(args.operationName)\n if (requiresConsistency) {\n operationArguments.published.commit()\n operationArguments.draft.commit()\n operationArguments.version?.commit()\n }\n const isConsistent$ = consistencyStatus(\n ctx.client,\n args.idPair,\n args.typeName,\n ctx.extraOptions,\n ).pipe(filter(Boolean))\n const ready$ = requiresConsistency ? isConsistent$.pipe(take(1)) : of(true)\n return ready$.pipe(\n switchMap(() => execute(args.operationName, operationArguments, args.extraArgs)),\n )\n }),\n map((): IntermediarySuccess => ({type: 'success', args})),\n catchError(\n (err): Observable<IntermediaryError> => of({type: 'error', args, error: err}),\n ),\n ),\n ),\n ),\n ),\n share(),\n )\n\n // this enables autocommit after patch operations\n const AUTOCOMMIT_INTERVAL = 1000\n const autoCommit$ = result$.pipe(\n filter((result) => result.type === 'success' && result.args.operationName === 'patch'),\n throttleTime(AUTOCOMMIT_INTERVAL, asyncScheduler, {leading: true, trailing: true}),\n concatMap((result) =>\n (window as any).SLOW ? timer(10000).pipe(map(() => result)) : of(result),\n ),\n tap((result) => {\n emitOperation('commit', result.args.idPair, result.args.typeName, [], result.args.storeKey)\n }),\n )\n\n return merge(result$, autoCommit$.pipe(mergeMapTo(EMPTY)))\n },\n (ctx) => {\n const config = ctx.client.config()\n // we only want one of these per dataset+projectid\n return `${config.dataset ?? ''}-${config.projectId ?? ''}`\n },\n)\n","import {type IdPair} from '../../types'\nimport {getOperationStoreKey} from '../getOperationStoreKey'\nimport {emitOperation} from '../operationEvents'\nimport {del as serverDel} from '../serverOperations/delete'\nimport {discardChanges as serverDiscardChanges} from '../serverOperations/discardChanges'\nimport {patch as serverPatch} from '../serverOperations/patch'\nimport {publish as serverPublish} from '../serverOperations/publish'\nimport {restore as serverRestore} from '../serverOperations/restore'\nimport {unpublish as serverUnpublish} from '../serverOperations/unpublish'\nimport {commit} from './commit'\nimport {duplicate} from './duplicate'\nimport {type Operation, type OperationArgs, type OperationImpl, type OperationsAPI} from './types'\n\nfunction createOperationGuard(opName: string): Operation<any[], 'NOT_READY'> {\n return {\n disabled: 'NOT_READY',\n execute: () => {\n throw new Error(`Called ${opName} before it was ready.`)\n },\n }\n}\n\n// This creates a version of the operations api that will throw if called.\n// Most operations depend on having the \"current document state\" available locally and if an action gets called\n// before we have the state available, we throw an error to signal \"premature\" invocation before ready\nexport const GUARDED: OperationsAPI = {\n commit: createOperationGuard('commit'),\n delete: createOperationGuard('delete'),\n del: createOperationGuard('del'),\n publish: createOperationGuard('publish'),\n patch: createOperationGuard('patch'),\n discardChanges: createOperationGuard('discardChanges'),\n unpublish: createOperationGuard('unpublish'),\n duplicate: createOperationGuard('duplicate'),\n restore: createOperationGuard('restore'),\n}\n\nfunction createTargetNotFoundOperation(opName: string): Operation<any[], 'TARGET_NOT_FOUND'> {\n return {\n disabled: 'TARGET_NOT_FOUND',\n execute: () => {\n throw new Error(\n `Cannot execute \"${opName}\": the selected target (release or variant) does not contain this document.`,\n )\n },\n }\n}\n\n// The operations api emitted when the declared target (release or variant) has no document.\n// Every operation is disabled and throws if executed anyway: falling back to the base\n// draft/published pair in this state is exactly the failure mode the guard exists to prevent.\nexport const TARGET_NOT_FOUND_OPERATIONS: OperationsAPI = {\n commit: createTargetNotFoundOperation('commit'),\n delete: createTargetNotFoundOperation('delete'),\n del: createTargetNotFoundOperation('del'),\n publish: createTargetNotFoundOperation('publish'),\n patch: createTargetNotFoundOperation('patch'),\n discardChanges: createTargetNotFoundOperation('discardChanges'),\n unpublish: createTargetNotFoundOperation('unpublish'),\n duplicate: createTargetNotFoundOperation('duplicate'),\n restore: createTargetNotFoundOperation('restore'),\n}\nconst createEmitter =\n (operationName: keyof OperationsAPI, idPair: IdPair, typeName: string, storeKey: string) =>\n (...executeArgs: any[]) =>\n emitOperation(operationName, idPair, typeName, executeArgs, storeKey)\n\nfunction wrap<ExtraArgs extends any[], DisabledReason extends string>(\n opName: keyof OperationsAPI,\n op: OperationImpl<ExtraArgs, DisabledReason>,\n operationArgs: OperationArgs,\n): Operation<ExtraArgs, DisabledReason> {\n const disabled = op.disabled(operationArgs)\n const storeKey = getOperationStoreKey(operationArgs.client)\n return {\n disabled,\n execute: createEmitter(opName, operationArgs.idPair, operationArgs.typeName, storeKey),\n }\n}\n\nexport function createOperationsAPI(args: OperationArgs): OperationsAPI {\n const operations: OperationsAPI = {\n commit: wrap('commit', commit, args),\n duplicate: wrap('duplicate', duplicate, args),\n delete: wrap('delete', serverDel, args),\n del: wrap('delete', serverDel, args),\n discardChanges: wrap('discardChanges', serverDiscardChanges, args),\n patch: wrap('patch', serverPatch, args),\n publish: wrap('publish', serverPublish, args),\n unpublish: wrap('unpublish', serverUnpublish, args),\n restore: wrap('restore', serverRestore, args),\n }\n\n // Self-derived target guard: a version was requested for an existing document, but the version\n // document doesn't exist. Mutating in this state would silently manifest the version out of\n // thin air (`patch` creates the version document) or operate on the base pair (`publish` would\n // publish the draft), so the mutating operations are disabled regardless of what the caller\n // declared. Deliberately excluded:\n // - New documents (no draft, published, or version snapshots): typing must still create the\n // release version locally via its deterministic id (create-on-first-edit).\n // - `restore` (history restore into a release) legitimately creates missing versions.\n // - `delete` / `duplicate` operate on the whole document group.\n const targetVersionMissing = Boolean(\n args.idPair.versionId &&\n !args.snapshots.version &&\n (args.snapshots.draft || args.snapshots.published),\n )\n\n if (!targetVersionMissing) {\n return operations\n }\n\n return {\n ...operations,\n commit: createTargetNotFoundOperation('commit'),\n patch: createTargetNotFoundOperation('patch'),\n publish: createTargetNotFoundOperation('publish'),\n unpublish: createTargetNotFoundOperation('unpublish'),\n discardChanges: createTargetNotFoundOperation('discardChanges'),\n }\n}\n","import {type SanityClient} from '@sanity/client'\nimport {type Schema} from '@sanity/types'\nimport {concat, EMPTY, merge, type Observable, of} from 'rxjs'\nimport {map, mergeMap, shareReplay} from 'rxjs/operators'\n\nimport {type HistoryStore} from '../../history/createHistoryStore'\nimport {type DocumentStoreExtraOptions} from '../getPairListener'\nimport {type IdPair} from '../types'\nimport {memoize} from '../utils/createMemoizer'\nimport {memoizeKeyGen} from './memoizeKeyGen'\nimport {operationArgs} from './operationArgs'\nimport {operationEvents} from './operationEvents'\nimport {createOperationsAPI, GUARDED} from './operations/helpers'\nimport {type OperationsAPI} from './operations/types'\n\nexport const editOperations = memoize(\n (\n ctx: {\n client: SanityClient\n historyStore: HistoryStore\n schema: Schema\n pairListenerOptions?: DocumentStoreExtraOptions\n },\n idPair: IdPair,\n typeName: string,\n ): Observable<OperationsAPI> => {\n const operationEvents$ = operationEvents(ctx)\n\n const operationArgs$ = operationArgs(ctx, idPair, typeName)\n const operations$ = operationArgs$.pipe(map(createOperationsAPI))\n\n // To makes sure we connect the stream that actually performs the operations\n return concat(\n of(GUARDED),\n merge(operationEvents$.pipe(mergeMap(() => EMPTY)), operations$),\n ).pipe(shareReplay({refCount: true, bufferSize: 1}))\n },\n (ctx, idPair, typeName) => memoizeKeyGen(ctx.client, idPair, typeName),\n)\n","// api extractor take issues with 'as const' for literals\n// oxlint-disable-next-line prefer-as-const\nexport const RELEASE_DOCUMENT_TYPE: 'system.release' = 'system.release'\nexport const RELEASE_DOCUMENTS_PATH = '_.releases'\n","import {type ReleaseId} from '../../perspective/types'\nimport {RELEASE_DOCUMENTS_PATH} from '../store/constants'\n\nconst PATH_ID_PREFIX = `${RELEASE_DOCUMENTS_PATH}.`\n\n/**\n * @internal\n * @param releaseDocumentId - the document id of the release\n */\nexport function getReleaseIdFromReleaseDocumentId(releaseDocumentId: string): ReleaseId {\n if (!releaseDocumentId.startsWith(PATH_ID_PREFIX)) {\n throw new Error(\n `Release document ID was ${releaseDocumentId} but should start with ${RELEASE_DOCUMENTS_PATH}`,\n )\n }\n const releaseId = releaseDocumentId.slice(PATH_ID_PREFIX.length)\n return releaseId\n}\n","import {type MonoTypeOperatorFunction} from 'rxjs'\nimport {tap} from 'rxjs/operators'\n\n/**\n * RxJS operator that measures the time from subscription to the first emission.\n * Calls `onMeasured` once with the elapsed duration in milliseconds and the emitted value.\n * Uses `tap()` internally so data flow is unchanged.\n *\n * Re-subscriptions (e.g. navigating between documents) naturally produce fresh measurements.\n *\n * @param onMeasured - Callback receiving the duration in ms and the first emitted value\n * @returns An RxJS operator\n * @internal\n */\nexport function measureFirstEmission<T>(\n onMeasured: (durationMs: number, value: T) => void,\n): MonoTypeOperatorFunction<T> {\n return (source) => {\n let measured = false\n let startTime: number\n\n return source.pipe(\n tap({\n subscribe: () => {\n measured = false\n startTime = performance.now()\n },\n next: (value) => {\n if (!measured) {\n measured = true\n onMeasured(performance.now() - startTime, value)\n }\n },\n }),\n )\n }\n}\n\n/**\n * RxJS operator that measures the time from subscription to the first emission\n * where the given predicate returns `true`.\n * Calls `onMeasured` once with the elapsed duration in milliseconds and the matching value.\n * Uses `tap()` internally so data flow is unchanged.\n *\n * @param predicate - Function that determines if the emitted value is a match\n * @param onMeasured - Callback receiving the duration in ms and the first matching value\n * @returns An RxJS operator\n * @internal\n */\nexport function measureFirstMatch<T>(\n predicate: (value: T) => boolean,\n onMeasured: (durationMs: number, value: T) => void,\n): MonoTypeOperatorFunction<T> {\n return (source) => {\n let measured = false\n let startTime: number\n\n return source.pipe(\n tap({\n subscribe: () => {\n measured = false\n startTime = performance.now()\n },\n next: (value) => {\n if (!measured && predicate(value)) {\n measured = true\n onMeasured(performance.now() - startTime, value)\n }\n },\n }),\n )\n }\n}\n","import {type SanityClient} from '@sanity/client'\nimport {type SanityDocument, type Schema} from '@sanity/types'\nimport {combineLatest, type Observable, of, ReplaySubject, timer} from 'rxjs'\nimport {map, share, startWith, switchMap} from 'rxjs/operators'\n\nimport {getReleaseIdFromReleaseDocumentId} from '../../../releases/util/getReleaseIdFromReleaseDocumentId'\nimport {getVersionFromId} from '../../../util/draftUtils'\nimport {measureFirstEmission} from '../../../util/measureFirstEmission'\nimport {createSWR} from '../../../util/rxSwr'\nimport {type DocumentStoreExtraOptions} from '../getPairListener'\nimport {type IdPair, type PendingMutationsEvent} from '../types'\nimport {memoize} from '../utils/createMemoizer'\nimport {memoizeKeyGen} from './memoizeKeyGen'\nimport {snapshotPair} from './snapshotPair'\nimport {isLiveEditEnabled} from './utils/isLiveEditEnabled'\n\ninterface TransactionSyncLockState {\n enabled: boolean\n}\n\nconst swr = createSWR<\n [SanityDocument, SanityDocument, TransactionSyncLockState, SanityDocument | null]\n>({maxSize: 50})\n\n/**\n * @hidden\n * @beta */\nexport interface EditStateFor {\n id: string\n type: string\n transactionSyncLock: TransactionSyncLockState | null\n draft: SanityDocument | null\n published: SanityDocument | null\n version: SanityDocument | null\n /**\n * Whether live edit is enabled. This may be true for various reasons:\n *\n * - The schema type has live edit enabled.\n * - A version of the document is checked out.\n */\n liveEdit: boolean\n /**\n * Whether the schema type has live edit enabled.\n */\n liveEditSchemaType: boolean\n ready: boolean\n /**\n * When editing a version, the short name of the release the document belongs to (or an agent /\n * anonymous bundle name), matched by consumers against active release names. Never an opaque\n * variant scope hash: documents carrying full `_system` metadata are classified from\n * `_system.release` (normalized from the `_.releases.<name>` reference), so drafts- and\n * published-scoped variants report `undefined` while release-scoped versions — variant or not —\n * report their release. Until the first snapshot arrives, the bundle segment is reported as-is.\n */\n release: string | undefined\n /**\n * When editing a version, the bundle segment of the version document id\n * (`versions.<scopeId>.<groupId>`): a release id, an agent/anonymous bundle name, or an opaque\n * variant scope hash. `undefined` when editing the base draft/published pair.\n */\n scopeId: string | undefined\n}\nconst LOCKED: TransactionSyncLockState = {enabled: true}\nconst NOT_LOCKED: TransactionSyncLockState = {enabled: false}\n\n/**\n * Classifies `EditStateFor.release` from a version snapshot.\n *\n * Documents carrying the full `_system` metadata (`_system.group` present) are classified from\n * `_system.release`, which is authoritative: a reference to the release document\n * (`_.releases.<name>`), normalized here to the short release name every consumer matches\n * against. Version documents without a release reference (e.g. drafts- or published-scoped\n * variants) report `undefined`.\n *\n * Unmigrated documents (no `_system.group`) can only be plain release versions, so the bundle\n * segment of their id (`scopeId`) is the release name.\n */\nfunction classifyRelease(\n versionSnapshot: SanityDocument | null,\n scopeId: string | undefined,\n): string | undefined {\n if (!versionSnapshot || !versionSnapshot._system?.group) {\n return scopeId\n }\n const releaseRef = versionSnapshot._system.release?._ref\n if (!releaseRef) {\n return undefined\n }\n return getReleaseIdFromReleaseDocumentId(releaseRef)\n}\n\n// How long to keep the pipeline alive after the last subscriber unsubscribes.\n// Subscriber churn (e.g. a React commit that unsubscribes every consumer before\n// the replacements subscribe) can momentarily drop the refcount to zero. A bare\n// teardown would make the next subscriber re-enter the cold-start path: the SWR\n// cache replays with `fromCache: true`, which emits `ready: false` and flips the\n// form read-only until fresh snapshots arrive — silently swallowing keystrokes\n// typed in that window. The invariant: a momentary zero-subscriber gap on a\n// warm, healthy document pair must never surface as `ready: false`.\nconst TEARDOWN_GRACE_PERIOD = 1_000\n\n/** @internal */\nexport const editState = memoize(\n (\n ctx: {\n client: SanityClient\n schema: Schema\n /**\n * @deprecated Does nothing. Preserved to avoid breaking changes.\n * Will be removed in the next major version.\n */\n serverActionsEnabled?: Observable<boolean>\n extraOptions?: DocumentStoreExtraOptions\n },\n idPair: IdPair,\n typeName: string,\n ): Observable<EditStateFor> => {\n const liveEditSchemaType = isLiveEditEnabled(ctx.schema, typeName)\n const liveEdit = typeof idPair.versionId !== 'undefined' || liveEditSchemaType\n const scopeId = idPair.versionId ? getVersionFromId(idPair.versionId) : undefined\n\n return snapshotPair(ctx.client, idPair, typeName, undefined, ctx.extraOptions).pipe(\n switchMap((versions) =>\n combineLatest([\n versions.draft.snapshots$,\n versions.published.snapshots$,\n versions.transactionsPendingEvents$.pipe(\n map((ev: PendingMutationsEvent) => (ev.phase === 'begin' ? LOCKED : NOT_LOCKED)),\n startWith(NOT_LOCKED),\n ),\n typeof versions.version === 'undefined' ? of(null) : versions.version.snapshots$,\n ]),\n ),\n swr(`${idPair.publishedId}-${idPair.draftId}-${idPair.versionId}`),\n measureFirstEmission(\n (durationMs, {fromCache, value: [draftSnapshot, publishedSnapshot, versionSnapshot]}) => {\n ctx.extraOptions?.onDocumentPairLoaded?.({\n durationMs,\n fromCache,\n hasPublished: Boolean(publishedSnapshot),\n hasDraft: Boolean(draftSnapshot),\n hasVersion: Boolean(versionSnapshot),\n })\n },\n ),\n // NOTE: `useEditState` deduplicates emissions downstream using shallow equality on\n // `draft`/`published`/`version` as well as `ready` and `transactionSyncLock`.\n // The map below preserves the snapshot identities and only allocates a new outer\n // wrapper while deriving those additional fields.\n //\n // A regression that clones any of these references — example. `draft: {...draftSnapshot}` — would silently\n // turn that dedupe into a no-op. We have regression tests for this.\n map(\n ({\n value: [draftSnapshot, publishedSnapshot, transactionSyncLock, versionSnapshot],\n fromCache,\n }) => ({\n id: idPair.publishedId,\n type: typeName,\n draft: draftSnapshot,\n published: publishedSnapshot,\n version: typeof idPair.versionId === 'undefined' ? null : versionSnapshot,\n liveEdit,\n liveEditSchemaType,\n ready: !fromCache,\n transactionSyncLock: fromCache ? null : transactionSyncLock,\n release: classifyRelease(versionSnapshot, scopeId),\n scopeId,\n }),\n ),\n startWith({\n id: idPair.publishedId,\n type: typeName,\n draft: null,\n published: null,\n version: null,\n liveEdit,\n liveEditSchemaType,\n ready: false,\n transactionSyncLock: null,\n release: scopeId,\n scopeId,\n }),\n // Unlike `publishReplay(1) + refCount()`, this resets the replay subject\n // when the pipeline is torn down, so a later cold subscriber won't get a\n // stale `ready: true` replayed before the cold-start emissions (and an\n // error won't be replayed forever).\n share({\n connector: () => new ReplaySubject(1),\n resetOnRefCountZero: () => timer(TEARDOWN_GRACE_PERIOD),\n }),\n )\n },\n (ctx, idPair, typeName) => memoizeKeyGen(ctx.client, idPair, typeName),\n)\n","import {isKeyedObject, type Path} from '@sanity/types'\n\nexport function pathToString(path: Path | undefined = []): string {\n return path.reduce<string>((target, segment, i) => {\n const segmentType = typeof segment\n if (segmentType === 'number') {\n return `${target}[${segment}]`\n }\n\n if (segmentType === 'string') {\n const separator = i === 0 ? '' : '.'\n return `${target}${separator}${segment}`\n }\n\n if (isKeyedObject(segment)) {\n return `${target}[_key==\"${segment._key}\"]`\n }\n\n throw new Error(`Unsupported path segment \"${segment}\"`)\n }, '')\n}\n","import {type Path, type ValidationError, type ValidationMarker} from '@sanity/types'\n\nimport {type ValidationContext} from '../types'\nimport {pathToString} from '../util/pathToString'\n\nfunction isNonNullable<T>(t: T): t is NonNullable<T> {\n return t !== null || t !== undefined\n}\n\nexport function convertToValidationMarker(\n validatorResult: true | true[] | string | string[] | ValidationError | ValidationError[],\n level: 'error' | 'warning' | 'info' | undefined,\n context: ValidationContext,\n): ValidationMarker[] {\n if (!context) {\n throw new Error('missing context')\n }\n\n if (validatorResult === true) return []\n\n if (Array.isArray(validatorResult)) {\n return validatorResult\n .flatMap((child) => convertToValidationMarker(child, level, context))\n .filter(isNonNullable)\n }\n\n if (typeof validatorResult === 'string') {\n return convertToValidationMarker({message: validatorResult}, level, context)\n }\n\n if (typeof validatorResult.message !== 'string') {\n // in order to accept the `ValidationError`, it at least needs to have a\n // `message` in the object\n throw new Error(\n `${pathToString(\n context.path,\n )}: Validator must return 'true' if valid or an error message as a string on errors`,\n )\n }\n\n const {message, __internal_metadata} = validatorResult\n\n const normalizedPaths: Path[] = []\n if (validatorResult.path) {\n normalizedPaths.push(validatorResult.path)\n }\n\n // legacy support for `paths`\n for (const path of validatorResult.paths || []) {\n normalizedPaths.push(path)\n }\n\n // the validator result does not include any item-level relative paths,\n // then just return the top-level path with the validation result\n if (!normalizedPaths.length) {\n return [\n {\n level: level || 'error',\n item: {message},\n message,\n path: context.path || [],\n __internal_metadata,\n },\n ]\n }\n\n // if the validator result did include item-level relative paths, then for\n // each item-level relative path, create a validation marker that concatenates\n // the relative path with the path from the validation context\n return normalizedPaths.map((path) => ({\n path: (context.path || []).concat(path),\n level: level || 'error',\n item: {message},\n message,\n __internal_metadata,\n }))\n}\n","import {type CustomValidatorResult, type LocalizedValidationMessages} from '@sanity/types'\nimport isPlainObject from 'lodash-es/isPlainObject.js'\n\nimport {type LocaleSource} from '../../i18n/types'\n\n/**\n * Extracts the correct localized validation message based on given locale source\n *\n * @param message - Localized messages to extract string from\n * @param i18n - Locale source, holding the current locale\n * @returns The localized string, or a fallback \"Unknown error\" if not found\n * @internal\n */\nexport function localizeMessage(message: LocalizedValidationMessages, i18n: LocaleSource): string {\n const {currentLocale} = i18n\n const locale = currentLocale.id\n\n // Obviously, try direct match first (`no-NB`)\n if (message[locale]) {\n return message[locale]\n }\n\n // In the case of composed languages (`en-US`, `no-NB` etc), fall back to base language (`en`)\n if (locale.includes('-')) {\n const language = locale.split('-', 1)[0]\n if (message[language]) {\n return message[language]\n }\n }\n\n // Try english as last resort\n return (\n message['en-US'] || message['en-GB'] || message.en || 'Unknown validation error (not localized)'\n )\n}\n\n/**\n * Check if passed message/result is a localized message object\n *\n * @param message - Message to check\n * @returns True if message is a localized message object, false otherwise\n * @internal\n */\nexport function isLocalizedMessages(\n message: CustomValidatorResult | undefined,\n): message is LocalizedValidationMessages {\n return (\n message !== true &&\n typeof message !== 'undefined' &&\n typeof message !== 'string' &&\n isPlainObject(message) &&\n !('message' in message)\n )\n}\n","/**\n * Modified version of fast-deep-equal (https://github.com/epoberezkin/fast-deep-equal)\n * MIT-licensed, copyright (c) 2017 Evgeny Poberezkin\n **/\n\n// NOTE: when converting to typescript, some of the checks were inlined (vs\n// having them in a variable) because the type predicate type narrowing only\n// works when type predicate is called inline in the condition that starts the\n// control flow branch.\n// see here: https://www.typescriptlang.org/docs/handbook/2/narrowing.html\nexport function deepEqualsIgnoreKey(a: unknown, b: unknown): boolean {\n if (a === b) {\n return true\n }\n\n if (Array.isArray(a) && Array.isArray(b)) {\n if (a.length != b.length) return false\n for (let i = 0; i < a.length; i++) {\n if (!deepEqualsIgnoreKey(a[i], b[i])) {\n return false\n }\n }\n return true\n }\n\n if (Array.isArray(a) != Array.isArray(b)) {\n return false\n }\n\n if (a && b && typeof a === 'object' && typeof b === 'object') {\n const keys = Object.keys(a)\n if (keys.length !== Object.keys(b).length) {\n return false\n }\n\n if (a instanceof Date && b instanceof Date) {\n return a.getTime() === b.getTime()\n }\n\n if (a instanceof Date != b instanceof Date) {\n return false\n }\n\n if (a instanceof RegExp && b instanceof RegExp) {\n return a.toString() == b.toString()\n }\n\n if (a instanceof RegExp != b instanceof RegExp) {\n return false\n }\n\n for (let i = 0; i < keys.length; i++) {\n if (keys[i] === '_key') {\n continue\n }\n\n if (!Object.prototype.hasOwnProperty.call(b, keys[i])) {\n return false\n }\n }\n\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i] as keyof typeof a\n if (key === '_key') {\n continue\n }\n\n if (!deepEqualsIgnoreKey(a[key], b[key])) {\n return false\n }\n }\n\n return true\n }\n\n return false\n}\n","// this file was adapted from a previous dependency `type-of-is`\n// https://github.com/stephenhandley/type-of-is/blob/7138a7e79f5af7c286bf8123f60843a91aaebf38/index.js\nconst _toString = {}.toString\n\nconst builtIns = [Object, Function, Array, String, Boolean, Number, Date, RegExp, Error]\n\nfunction isBuiltIn(_constructor: unknown) {\n for (let i = 0; i < builtIns.length; i++) {\n if (builtIns[i] === _constructor) return true\n }\n return false\n}\n\nexport function typeString(obj: unknown): string {\n // [object Blah] -> Blah\n const stringType = _toString.call(obj).slice(8, -1)\n if (obj === null || obj === undefined) return stringType.toLowerCase()\n\n const constructorType = (obj as object).constructor\n if (constructorType && !isBuiltIn(constructorType)) return constructorType.name\n return stringType\n}\n","import {type ValidationMarker, type Validators} from '@sanity/types'\n\nimport {type LocaleSource} from '../../i18n/types'\nimport {deepEqualsIgnoreKey} from '../util/deepEqualsIgnoreKey'\nimport {isLocalizedMessages, localizeMessage} from '../util/localizeMessage'\nimport {pathToString} from '../util/pathToString'\nimport {typeString} from '../util/typeString'\n\nexport const SLOW_VALIDATOR_TIMEOUT = 5000\n\nconst formatValidationErrors = (options: {\n message: string | undefined\n results: ValidationMarker[]\n operation: 'conjunction' | 'disjunction'\n i18n: LocaleSource\n}) => {\n if (options.message) return options.message\n if (options.results.length === 1) return options.results[0]?.message\n\n // Intentionally hard-coded to use locale conjunction/disjunctions\n return options.i18n.t('{{messages, list}}', {\n messages: options.results.map((err) => err.message || err.item?.message),\n formatParams: {messages: {style: 'long', type: options.operation}},\n })\n}\n\nexport const genericValidators: Validators = {\n type: (expectedType, value, message, {i18n}) => {\n const actualType = typeString(value)\n if (actualType !== expectedType && actualType !== 'undefined') {\n return message || i18n.t('validation:generic.incorrect-type', {actualType, expectedType})\n }\n\n return true\n },\n\n presence: (expected, value, message, {i18n}) => {\n if (value === undefined && expected === 'required') {\n return message || i18n.t('validation:generic.required')\n }\n\n return true\n },\n\n all: async (children, value, message, context) => {\n const resolved = await Promise.all(children.map((child) => child.validate(value, context)))\n const results = resolved.flat()\n\n if (results.length === 0) {\n return true\n }\n\n return formatValidationErrors({\n message,\n results,\n operation: 'conjunction',\n i18n: context.i18n,\n })\n },\n\n either: async (children, value, message, context) => {\n const resolved = await Promise.all(children.map((child) => child.validate(value, context)))\n const results = resolved.flat()\n\n // if one of the results is an empty array then at least one rule match\n if (resolved.find((result) => !result.length)) {\n return true\n }\n\n return formatValidationErrors({\n message,\n results,\n operation: 'disjunction',\n i18n: context.i18n,\n })\n },\n\n valid: (allowedValues, actual, message, {i18n}) => {\n const valueType = typeof actual\n if (valueType === 'undefined') {\n return true\n }\n\n const value = (valueType === 'number' || valueType === 'string') && `${actual}`\n const strValue = value && value.length > 30 ? `${value.slice(0, 30)}…` : value\n\n return allowedValues.some((expected) => deepEqualsIgnoreKey(expected, actual))\n ? true\n : message ||\n i18n.t(\n 'validation:generic.not-allowed',\n value ? {context: 'hint', replace: {hint: strValue}} : {},\n )\n },\n\n custom: async (fn, value, message, context) => {\n const slowTimer = setTimeout(() => {\n // only show this warning in the studio\n if (context.environment !== 'studio') return\n\n console.warn(\n `Custom validator at ${pathToString(\n context.path,\n )} has taken more than ${SLOW_VALIDATOR_TIMEOUT}ms to respond`,\n )\n }, SLOW_VALIDATOR_TIMEOUT)\n\n let result\n try {\n result = await fn(value, context)\n } finally {\n clearTimeout(slowTimer)\n }\n\n if (isLocalizedMessages(result)) {\n return localizeMessage(result, context.i18n)\n }\n\n if (typeof result === 'string') {\n return message || result\n }\n\n return result\n },\n}\n","import {\n isArrayOfBlocksSchemaType,\n type Path,\n type PathSegment,\n type Validators,\n} from '@sanity/types'\n\nimport {deepEqualsIgnoreKey} from '../util/deepEqualsIgnoreKey'\nimport {genericValidators} from './genericValidator'\n\nexport const arrayValidators: Validators = {\n ...genericValidators,\n\n min: (minLength, value, message, {i18n, type}) => {\n if (!value || value.length >= minLength) {\n return true\n }\n\n const context = isArrayOfBlocksSchemaType(type) ? 'blocks' : undefined\n return message || i18n.t('validation:array.minimum-length', {minLength, context})\n },\n\n max: (maxLength, value, message, {i18n, type}) => {\n if (!value || value.length <= maxLength) {\n return true\n }\n\n const context = isArrayOfBlocksSchemaType(type) ? 'blocks' : undefined\n return message || i18n.t('validation:array.maximum-length', {maxLength, context})\n },\n\n length: (wantedLength, value, message, {i18n, type}) => {\n if (!value || value.length === wantedLength) {\n return true\n }\n\n const context = isArrayOfBlocksSchemaType(type) ? 'blocks' : undefined\n return message || i18n.t('validation:array.exact-length', {wantedLength, context})\n },\n\n presence: (flag, value, message, {i18n}) => {\n if (flag === 'required' && !value) {\n return message || i18n.t('validation:generic.required', {context: 'array'})\n }\n\n return true\n },\n\n valid: (allowedValues, values, message, {i18n}) => {\n const valueType = typeof values\n if (valueType === 'undefined') {\n return true\n }\n\n const paths: Path[] = []\n for (let i = 0; i < values.length; i++) {\n const value = values[i]\n if (allowedValues.some((expected) => deepEqualsIgnoreKey(expected, value))) {\n continue\n }\n\n const pathSegment: PathSegment = value && value._key ? {_key: value._key} : i\n paths.push([pathSegment])\n }\n\n // we emit the same message for each path we find in this array\n const sharedMessage = message || i18n.t('validation:generic.not-allowed')\n\n return paths.map((path) => ({message: sharedMessage, path}))\n },\n\n unique: (_unused, value, message, {i18n}) => {\n const dupeIndices = []\n if (!value) {\n return true\n }\n\n for (let x = 0; x < value.length; x++) {\n for (let y = x + 1; y < value.length; y++) {\n const itemA = value[x]\n const itemB = value[y]\n\n if (!deepEqualsIgnoreKey(itemA, itemB)) {\n continue\n }\n\n if (dupeIndices.indexOf(x) === -1) {\n dupeIndices.push(x)\n }\n\n if (dupeIndices.indexOf(y) === -1) {\n dupeIndices.push(y)\n }\n }\n }\n\n const paths = dupeIndices.map((idx) => {\n const item = value[idx]\n const pathSegment = item && item._key ? {_key: item._key} : idx\n return [pathSegment]\n })\n\n // we emit the same message for each path we find in this array\n const sharedMessage = message || i18n.t('validation:array.item-duplicate')\n\n return paths.map((path) => ({message: sharedMessage, path}))\n },\n}\n","import {type Validators} from '@sanity/types'\n\nimport {genericValidators} from './genericValidator'\n\nexport const booleanValidators: Validators = {\n ...genericValidators,\n\n presence: (flag, value, message, {i18n}) => {\n if (flag === 'required' && typeof value !== 'boolean') {\n return message || i18n.t('validation:generic.required', {context: 'boolean'})\n }\n\n return true\n },\n}\n","import {type Validators} from '@sanity/types'\nimport * as legacyDateFormat from '@sanity/util/legacyDateFormat'\n\nimport {genericValidators} from './genericValidator'\n\nfunction isRecord(obj: unknown): obj is Record<string, unknown> {\n return typeof obj === 'object' && obj !== null && !Array.isArray(obj)\n}\n\nconst isoDate =\n /^(?:[-+]\\d{2})?(?:\\d{4}(?!\\d{2}\\b))(?:(-?)(?:(?:0[1-9]|1[0-2])(?:\\1(?:[12]\\d|0[1-9]|3[01]))?|W(?:[0-4]\\d|5[0-2])(?:-?[1-7])?|(?:00[1-9]|0[1-9]\\d|[12]\\d{2}|3(?:[0-5]\\d|6[1-6])))(?![T]$|[T][\\d]+Z$)(?:[T\\s](?:(?:(?:[01]\\d|2[0-3])(?:(:?)[0-5]\\d)?|24:?00)(?:[.,]\\d+(?!:))?)(?:\\2[0-5]\\d(?:[.,]\\d+)?)?(?:[Z]|(?:[+-])(?:[01]\\d|2[0-3])(?::?[0-5]\\d)?)?)?)?$/\n\n// TODO (eventually): move these to schema type package\ninterface DateTimeOptions {\n // @todo accept object representing `Intl.DateTimeFormatOptions`? how do we localize?\n dateFormat?: string\n timeFormat?: string\n}\n\nconst getFormattedDate = (type = '', value: Date, options?: DateTimeOptions) => {\n const dateFormat = options?.dateFormat || legacyDateFormat.DEFAULT_DATE_FORMAT\n const timeFormat = options?.timeFormat || legacyDateFormat.DEFAULT_TIME_FORMAT\n\n // adding the time information in the date only case causes timezone information to be kept\n // instead of it being assumed to be UTC. This was a problem because midnight UTC is the previous\n // day in many other timezones resulting in the date displayed to be the previous day.\n return legacyDateFormat.format(\n value,\n type === 'date' ? dateFormat : `${dateFormat} ${timeFormat}`,\n {useUTC: type === 'date'},\n )\n}\n\nfunction parseDate(date: unknown): Date | null\nfunction parseDate(date: unknown, throwOnError: true): Date\nfunction parseDate(date: unknown, throwOnError = false): Date | null {\n if (!date) return null\n if (date === 'now') return new Date()\n\n // oxlint-disable-next-line no-explicit-any\n const parsed = new Date(date as any)\n const isInvalid = isNaN(parsed.getTime())\n if (isInvalid && throwOnError) {\n throw new Error(`Unable to parse \"${date}\" to a date`)\n }\n\n return isInvalid ? null : parsed\n}\n\nexport const dateValidators: Validators = {\n ...genericValidators,\n\n type: (_unused, value, message, {i18n}) => {\n if (typeof value === 'undefined' || isoDate.test(`${value}`)) {\n return true\n }\n\n return message || i18n.t('validation:date.invalid-format')\n },\n\n min: (minDate, value, message, {type, i18n}) => {\n const dateVal = parseDate(value)\n const minDateVal = parseDate(minDate, true)\n\n if (!dateVal) {\n return true // `type()` should catch parse errors\n }\n\n if (!value || dateVal >= minDateVal) {\n return true\n }\n\n if (!type) {\n throw new Error(`\\`type\\` was not provided in validation context.`)\n }\n\n const dateTimeOptions: DateTimeOptions = isRecord(type.options)\n ? (type.options as DateTimeOptions)\n : {}\n\n return (\n message ||\n // Note that the `minDate` passed here is _formatted_, while the raw value provided to the\n // validator is available as `providedMinDate`. This because the formatted date is likely\n // what the developer wants to present to the user\n i18n.t('validation:date.minimum', {\n minDate: getFormattedDate(type.name, minDateVal, dateTimeOptions),\n providedMinDate: minDate,\n })\n )\n },\n\n max: (maxDate, value, message, {type, i18n}) => {\n const dateVal = parseDate(value)\n const maxDateVal = parseDate(maxDate, true)\n\n if (!dateVal) {\n return true // `type()` should catch parse errors\n }\n\n if (!value || dateVal <= maxDateVal) {\n return true\n }\n\n if (!type) {\n throw new Error(`\\`type\\` was not provided in validation context.`)\n }\n\n const dateTimeOptions: DateTimeOptions = isRecord(type.options)\n ? (type.options as DateTimeOptions)\n : {}\n\n return (\n message ||\n // Note that the `maxDate` passed here is _formatted_, while the raw value provided to the\n // validator is available as `providedMaxDate`. This because the formatted date is likely\n // what the developer wants to present to the user\n i18n.t('validation:date.maximum', {\n maxDate: getFormattedDate(type.name, maxDateVal, dateTimeOptions),\n providedMaxDate: maxDate,\n })\n )\n },\n}\n","import {type Validators} from '@sanity/types'\n\nimport {genericValidators} from './genericValidator'\n\nconst precisionRx = /(?:\\.(\\d+))?(?:[eE]([+-]?\\d+))?$/\n\nexport const numberValidators: Validators = {\n ...genericValidators,\n\n integer: (_unused, value, message, {i18n}) => {\n if (!Number.isInteger(value)) {\n return message || i18n.t('validation:number.non-integer')\n }\n\n return true\n },\n\n precision: (limit, value, message, {i18n}) => {\n if (value === undefined) return true\n\n const places = value.toString().match(precisionRx)\n const decimals = Math.max(\n (places[1] ? places[1].length : 0) - (places[2] ? parseInt(places[2], 10) : 0),\n 0,\n )\n\n if (decimals > limit) {\n return message || i18n.t('validation:number.maximum-precision', {limit})\n }\n\n return true\n },\n\n min: (minNumber, value, message, {i18n}) => {\n if (value >= minNumber) {\n return true\n }\n\n return message || i18n.t('validation:number.minimum', {minNumber})\n },\n\n max: (maxNumber, value, message, {i18n}) => {\n if (value <= maxNumber) {\n return true\n }\n\n return message || i18n.t('validation:number.maximum', {maxNumber})\n },\n\n greaterThan: (threshold, value, message, {i18n}) => {\n if (value > threshold) {\n return true\n }\n\n return message || i18n.t('validation:number.greater-than', {threshold})\n },\n\n lessThan: (threshold, value, message, {i18n}) => {\n if (value < threshold) {\n return true\n }\n\n return message || i18n.t('validation:number.less-than', {threshold})\n },\n}\n","import {\n type Asset as MediaLibraryAsset,\n type AssetInstanceDocument,\n} from '@sanity/media-library-types'\nimport {type CustomValidatorResult, isReference, type Validators} from '@sanity/types'\n\nimport {getPublishedId} from '../../util/draftUtils'\nimport {isLocalizedMessages, localizeMessage} from '../util/localizeMessage'\nimport {pathToString} from '../util/pathToString'\nimport {genericValidators, SLOW_VALIDATOR_TIMEOUT} from './genericValidator'\n\nconst metaKeys = ['_key', '_type', '_weak']\n\nexport const objectValidators: Validators = {\n ...genericValidators,\n\n presence: (expected, value, message, {i18n}) => {\n if (expected !== 'required') {\n return true\n }\n\n const keys = value && Object.keys(value).filter((key) => !metaKeys.includes(key))\n\n if (value === undefined || (keys && keys.length === 0)) {\n return message || i18n.t('validation:generic.required', {context: 'object'})\n }\n\n return true\n },\n\n reference: async (_unused, value: unknown, message, context) => {\n if (!value) {\n return true\n }\n\n const {type, document, getDocumentExists, i18n} = context\n\n if (!isReference(value)) {\n return message || i18n.t('validation:object.not-reference')\n }\n\n if (!type) {\n throw new Error(`\\`type\\` was not provided in validation context`)\n }\n\n if ('weak' in type && type.weak) {\n return true\n }\n\n if (!getDocumentExists) {\n throw new Error(`\\`getDocumentExists\\` was not provided in validation context`)\n }\n\n const documentId = document?._id\n if (documentId && value._ref == getPublishedId(documentId)) {\n // a document should be able to reference itself without first being published\n return true\n }\n const exists = await getDocumentExists({id: value._ref})\n if (!exists) {\n return i18n.t('validation:object.reference-not-published', {documentId: value._ref})\n }\n\n return true\n },\n\n assetRequired: (flag, value, message, {i18n}) => {\n if (!value || !value.asset || !value.asset._ref) {\n return {\n __internal_metadata: {\n name: 'assetRequired',\n },\n message:\n message || i18n.t('validation:object.asset-required', {context: flag.assetType || ''}),\n }\n }\n\n return true\n },\n\n media: async (fn, value, message, context) => {\n const slowTimer = setTimeout(() => {\n // only show this warning in the studio\n if (context.environment !== 'studio') return\n\n console.warn(\n `Media validator at ${pathToString(\n context.path,\n )} has taken more than ${SLOW_VALIDATOR_TIMEOUT}ms to respond`,\n )\n }, SLOW_VALIDATOR_TIMEOUT)\n\n // If no value is provided, we assume the validation passes. This should be handled by the 'isRequired' validator.\n if (!value) {\n return true\n }\n\n // If the value is not an object or does not have a media reference, we return an error message.\n // It should not be allowed to use regular dataset assets with this validator.\n if (!value || !value.media || !value.media._ref) {\n return context.i18n.t('validation:object.not-media-library-asset')\n }\n\n let result: CustomValidatorResult = true\n\n try {\n const [type, libraryId, documentId] = value.media._ref.split(':', 3)\n // TODO: replace this with stable resource config when available\n const resourceConfig = {resource: {type, id: libraryId}}\n const asset = await context\n .getClient({apiVersion: '2025-02-19'})\n .withConfig(resourceConfig)\n .fetch<(MediaLibraryAsset & {currentVersion: AssetInstanceDocument}) | null>(\n `*[_id == $id] { ..., 'currentVersion': @.currentVersion-> { ... } }[0]`,\n {\n id: documentId,\n },\n )\n if (!asset) {\n console.warn(\n `${context.i18n.t('validation:object.media-not-found')}\\nAsset ID: ${value.media._ref}`,\n )\n return context.i18n.t('validation:object.media-not-found')\n }\n\n result = await fn(\n {\n media: {\n asset,\n },\n value,\n },\n context,\n )\n } catch (err) {\n const error = new Error(\n `Media validator at ${pathToString(\n context.path,\n )} failed with an error: ${err instanceof Error ? err.message : String(err)}`,\n {cause: err},\n )\n throw error\n } finally {\n clearTimeout(slowTimer)\n }\n\n const validationErrorMetadata = {\n __internal_metadata: {\n name: 'media',\n },\n }\n\n // Valid, no errors\n if (result === true) {\n return result\n }\n\n // Ensure we always return ValidationMarker with metadata\n return Array.isArray(result)\n ? result\n : [result].map((res) => {\n if (typeof res === 'string') {\n return {...validationErrorMetadata, message: message || res}\n }\n if (isLocalizedMessages(res)) {\n return {\n ...validationErrorMetadata,\n message: message || localizeMessage(res, context.i18n),\n }\n }\n return {...validationErrorMetadata, ...res, message: message || res.message}\n })\n },\n}\n","import {type Validators} from '@sanity/types'\n\nimport {genericValidators} from './genericValidator'\n\nconst DUMMY_ORIGIN = 'http://sanity'\nconst isRelativeUrl = (url: string) => /^\\.*\\//.test(url)\nconst emailRegex =\n /^(([^<>()[\\]\\\\.,;:\\s@\"]+(\\.[^<>()[\\]\\\\.,;:\\s@\"]+)*)|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$/\n\nexport const stringValidators: Validators = {\n ...genericValidators,\n\n min: (minLength, value, message, {i18n}) => {\n if (!value || value.length >= minLength) {\n return true\n }\n\n return message || i18n.t('validation:string.minimum-length', {minLength})\n },\n\n max: (maxLength, value, message, {i18n}) => {\n if (!value || value.length <= maxLength) {\n return true\n }\n\n return message || i18n.t('validation:string.maximum-length', {maxLength})\n },\n\n length: (wantedLength, value, message, {i18n}) => {\n const strValue = value || ''\n if (strValue.length === wantedLength) {\n return true\n }\n\n return message || i18n.t('validation:string.exact-length', {wantedLength})\n },\n\n uri: (constraints, value, message, {i18n}) => {\n const strValue = value || ''\n if (!strValue) {\n return true // `presence()` should catch empty values\n }\n\n const {options} = constraints\n const {allowCredentials, relativeOnly} = options\n const allowRelative = options.allowRelative || relativeOnly\n\n let url\n try {\n // WARNING: Safari checks for a given `base` param by looking at the length of arguments passed\n // to new URL(str, base), and will fail if invoked with new URL(strValue, undefined)\n url = allowRelative ? new URL(strValue, DUMMY_ORIGIN) : new URL(strValue)\n } catch {\n return message || i18n.t('validation:string.url.invalid')\n }\n\n if (relativeOnly && url.origin !== DUMMY_ORIGIN) {\n return message || i18n.t('validation:string.url.not-relative')\n }\n\n if (!allowRelative && url.origin === DUMMY_ORIGIN && isRelativeUrl(strValue)) {\n return message || i18n.t('validation:string.url.not-absolute')\n }\n\n if (!allowCredentials && (url.username || url.password)) {\n return message || i18n.t('validation:string.url.includes-credentials')\n }\n\n const urlScheme = url.protocol.replace(/:$/, '')\n const isRelative = isRelativeUrl(strValue)\n const matchesAllowedScheme =\n isRelative || options.scheme.some((scheme) => scheme.test(urlScheme))\n if (!matchesAllowedScheme) {\n return message || i18n.t('validation:string.url.disallowed-scheme', {scheme: urlScheme})\n }\n\n return true\n },\n\n stringCasing: (casing, value, message, {i18n}) => {\n const strValue = value || ''\n if (casing === 'uppercase' && strValue !== strValue.toLocaleUpperCase()) {\n return message || i18n.t('validation:string.uppercase')\n }\n\n if (casing === 'lowercase' && strValue !== strValue.toLocaleLowerCase()) {\n return message || i18n.t('validation:string.lowercase')\n }\n\n return true\n },\n\n presence: (flag, value, message, {i18n}) => {\n if (flag === 'required' && !value) {\n return message || i18n.t('validation:generic.required', {context: 'string'})\n }\n\n return true\n },\n\n regex: (options, value, message, {i18n}) => {\n const {pattern, name, invert} = options\n const regName = name || `${pattern.toString()}`\n const strValue = value || ''\n // Regexes with global or sticky flags are stateful (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/lastIndex).\n // This resets the state stored from the previous check\n pattern.lastIndex = 0\n const matches = pattern.test(strValue)\n if ((!invert && !matches) || (invert && matches)) {\n if (message) {\n return message\n }\n\n return invert\n ? i18n.t('validation:string.regex-match', {name: regName})\n : i18n.t('validation:string.regex-does-not-match', {name: regName})\n }\n\n return true\n },\n\n email: (_unused, value, message, {i18n}) => {\n const strValue = `${value || ''}`.trim()\n if (!strValue || emailRegex.test(strValue)) {\n return true\n }\n\n return message || i18n.t('validation:string.email')\n },\n}\n","import {Rule as BaseRule} from '@sanity/schema'\nimport {\n type CustomValidator,\n type Rule as IRule,\n type RuleClass,\n type SchemaType,\n type ValidationMarker,\n type Validator,\n} from '@sanity/types'\nimport get from 'lodash-es/get.js'\n\nimport {convertToValidationMarker} from './util/convertToValidationMarker'\nimport {isLocalizedMessages, localizeMessage} from './util/localizeMessage'\nimport {pathToString} from './util/pathToString'\nimport {arrayValidators} from './validators/arrayValidator'\nimport {booleanValidators} from './validators/booleanValidator'\nimport {dateValidators} from './validators/dateValidator'\nimport {genericValidators} from './validators/genericValidator'\nimport {numberValidators} from './validators/numberValidator'\nimport {objectValidators} from './validators/objectValidator'\nimport {stringValidators} from './validators/stringValidator'\n\nconst typeValidators = {\n Boolean: booleanValidators,\n Number: numberValidators,\n String: stringValidators,\n Array: arrayValidators,\n Object: objectValidators,\n Date: dateValidators,\n}\n\nconst isFieldRef = (constraint: unknown): constraint is {type: symbol; path: string | string[]} => {\n if (typeof constraint !== 'object' || !constraint) return false\n return (constraint as Record<string, unknown>).type === Rule.FIELD_REF\n}\n\nconst EMPTY_ARRAY: unknown[] = []\n\n/**\n * Concrete Rule implementation with validation logic.\n * This extends the base Rule class from `@sanity/schema` and adds the validate method.\n *\n * Note: `RuleClass` and `Rule` are split to fit the current `@sanity/types`\n * setup. Classes are a bit weird in the `@sanity/types` package because classes\n * create an actual javascript class while simultaneously creating a type\n * definition.\n *\n * This implicitly creates two types:\n * 1. the instance type — `Rule` and\n * 2. the static/class type - `RuleClass`\n *\n * The `RuleClass` type contains the static methods and the `Rule` instance\n * contains the instance methods.\n *\n * This package exports the RuleClass as a value without implicitly exporting\n * an instance definition. This should help reminder downstream users to import\n * from the `@sanity/types` package.\n *\n * @internal\n */\n// export class Rule extends BaseRule implements IRule {\nexport const Rule: RuleClass = class Rule extends BaseRule implements IRule {\n static array = (def?: SchemaType): Rule => new Rule(def).type('Array')\n static object = (def?: SchemaType): Rule => new Rule(def).type('Object')\n static string = (def?: SchemaType): Rule => new Rule(def).type('String')\n static number = (def?: SchemaType): Rule => new Rule(def).type('Number')\n static boolean = (def?: SchemaType): Rule => new Rule(def).type('Boolean')\n static dateTime = (def?: SchemaType): Rule => new Rule(def).type('Date')\n\n clone(): Rule {\n const rule = new Rule()\n rule._type = this._type\n rule._message = this._message\n rule._required = this._required\n rule._rules = [...this._rules]\n rule._level = this._level\n rule._fieldRules = this._fieldRules\n rule._typeDef = this._typeDef\n return rule\n }\n\n async validate(\n value: unknown,\n {__internal = {}, ...context}: Parameters<IRule['validate']>[1],\n ): Promise<ValidationMarker[]> {\n const {customValidationConcurrencyLimiter} = __internal\n\n const valueIsEmpty = value === null || value === undefined\n\n // Short-circuit on optional, empty fields\n if (valueIsEmpty && this._required === 'optional') {\n return EMPTY_ARRAY as ValidationMarker[]\n }\n\n const rules =\n // Run only the _custom_ functions if the rule is not set to required or optional\n this._required === undefined && valueIsEmpty\n ? this._rules.filter((curr) => curr.flag === 'custom')\n : this._rules\n\n const validators = (this._type && typeValidators[this._type]) || genericValidators\n\n const results = await Promise.all(\n rules.map(async (curr) => {\n if (curr.flag === undefined) {\n throw new Error('Invalid rule, did not contain \"flag\"-property')\n }\n\n const validator: Validator | undefined = validators[curr.flag]\n if (!validator) {\n const forType = this._type ? `type \"${this._type}\"` : 'rule without declared type'\n throw new Error(`Validator for flag \"${curr.flag}\" not found for ${forType}`)\n }\n\n let specConstraint = 'constraint' in curr ? curr.constraint : null\n if (isFieldRef(specConstraint)) {\n specConstraint = get(context.parent, specConstraint.path)\n }\n\n if (\n curr.flag === 'custom' &&\n customValidationConcurrencyLimiter &&\n !(specConstraint as CustomValidator)?.bypassConcurrencyLimit\n ) {\n const customValidator = specConstraint as CustomValidator\n specConstraint = async (...args: Parameters<CustomValidator>) => {\n await customValidationConcurrencyLimiter.ready()\n try {\n return await customValidator(...args)\n } finally {\n customValidationConcurrencyLimiter.release()\n }\n }\n }\n\n const message = isLocalizedMessages(this._message)\n ? localizeMessage(this._message, context.i18n)\n : this._message\n\n try {\n const result = await validator(specConstraint, value, message, context)\n return convertToValidationMarker(result, this._level, context)\n } catch (err) {\n const errorMessage = `${pathToString(\n context.path,\n )}: Exception occurred while validating value: ${err.message}`\n\n return convertToValidationMarker({message: errorMessage}, 'error', context)\n }\n }),\n )\n\n return results.flat()\n }\n}\n","import {\n type CustomValidator,\n isKeyedObject,\n isSlug,\n type Path,\n type SlugIsUniqueValidator,\n type SlugParent,\n type SlugSchemaType,\n type SlugValidationContext,\n} from '@sanity/types'\nimport memoize from 'lodash-es/memoize.js'\n\nimport {DEFAULT_STUDIO_CLIENT_OPTIONS} from '../../studioClient'\nimport {getPublishedId} from '../../util/draftUtils'\n\nconst memoizedWarnOnArraySlug = memoize(warnOnArraySlug)\n\nfunction serializePath(path: Path): string {\n return path.reduce<string>((target, part, i) => {\n const isIndex = typeof part === 'number'\n const isKey = isKeyedObject(part)\n const separator = i === 0 ? '' : '.'\n const add = isIndex || isKey ? '[]' : `${separator}${part}`\n return `${target}${add}`\n }, '')\n}\n\nconst defaultIsUnique: SlugIsUniqueValidator = (slug, context) => {\n const {getClient, document, path, type} = context\n const schemaOptions = type?.options\n\n if (!document) {\n throw new Error(`\\`document\\` was not provided in validation context.`)\n }\n if (!path) {\n throw new Error(`\\`path\\` was not provided in validation context.`)\n }\n\n const disableArrayWarning = schemaOptions?.disableArrayWarning || false\n const docType = document._type\n const atPath = serializePath(path.concat('current'))\n\n if (!disableArrayWarning && atPath.includes('[]') && context.environment === 'studio') {\n memoizedWarnOnArraySlug(serializePath(path))\n }\n\n const constraints = [\n '_type == $docType',\n `!sanity::versionOf($published)`,\n `${atPath} == $slug`,\n ].join(' && ')\n\n return getClient({apiVersion: DEFAULT_STUDIO_CLIENT_OPTIONS.apiVersion})\n .withConfig({perspective: 'raw'})\n .fetch<boolean>(\n `!defined(*[${constraints}][0]._id)`,\n {\n docType,\n published: getPublishedId(document._id),\n slug,\n },\n {tag: 'validation.slug-is-unique'},\n )\n}\n\nfunction warnOnArraySlug(serializedPath: string) {\n console.warn(\n [\n `Slug field at path ${serializedPath} is within an array and cannot be automatically checked for uniqueness`,\n `If you need to check for uniqueness, provide your own \"isUnique\" method`,\n `To disable this message, set \\`disableArrayWarning: true\\` on the slug \\`options\\` field`,\n ].join('\\n'),\n )\n}\n\n/**\n * Validates slugs values by querying for uniqueness from the client.\n *\n * This is a custom rule implementation (e.g. `Rule.custom(slugValidator)`)\n * that's populated in `inferFromSchemaType` when the type name is `slug`\n */\nexport const slugValidator: CustomValidator = async (value, context) => {\n if (!value) {\n return true\n }\n\n const {i18n} = context\n\n if (typeof value !== 'object' || Array.isArray(value)) {\n return i18n.t('validation:slug.not-object')\n }\n\n if (!isSlug(value) || value.current.trim().length === 0) {\n return i18n.t('validation:slug.missing-current')\n }\n\n const options = context?.type?.options as {isUnique?: SlugIsUniqueValidator} | undefined\n const isUnique = options?.isUnique || defaultIsUnique\n\n const slugContext: SlugValidationContext = {\n ...context,\n parent: context.parent as SlugParent,\n type: context.type as SlugSchemaType,\n defaultIsUnique,\n }\n\n const wasUnique = await isUnique(value.current, slugContext)\n if (wasUnique) {\n return true\n }\n\n return i18n.t('validation:slug.not-unique', {slug: value.current})\n}\n","import {\n type Rule,\n type RuleSpec,\n type RuleTypeConstraint,\n type SchemaType,\n type ValidationContext,\n} from '@sanity/types'\nimport isEqual from 'lodash-es/isEqual.js'\n\nimport {Rule as RuleClass} from '../Rule'\nimport {slugValidator} from '../validators/slugValidator'\n\nconst ruleConstraintTypes: {[P in Lowercase<RuleTypeConstraint>]: true} = {\n array: true,\n boolean: true,\n date: true,\n number: true,\n object: true,\n string: true,\n}\n\nconst isRuleConstraint = (typeString: string): typeString is Lowercase<RuleTypeConstraint> =>\n typeString in ruleConstraintTypes\n\nexport function getTypeChain(\n type: SchemaType | undefined,\n visited: Set<SchemaType> = new Set(),\n): SchemaType[] {\n if (!type) return []\n if (visited.has(type)) return []\n\n visited.add(type)\n\n const next = type.type ? getTypeChain(type.type, visited) : []\n return [...next, type]\n}\n\nfunction baseRuleReducer(inputRule: Rule, type: SchemaType) {\n let baseRule = inputRule\n\n if (isRuleConstraint(type.jsonType)) {\n baseRule = baseRule.type(type.jsonType)\n }\n\n const typeOptionsList =\n // if type.options is truthy\n type?.options &&\n // and type.options is an object (non-null from the previous)\n typeof type.options === 'object' &&\n // and if `list` is in options\n 'list' in type.options &&\n // then finally access the list\n type.options.list\n\n if (Array.isArray(typeOptionsList)) {\n baseRule = baseRule.valid(\n typeOptionsList.map((option) => extractValueFromListOption(option, type)),\n )\n }\n\n if (type.name === 'datetime') return baseRule.type('Date')\n if (type.name === 'date') return baseRule.type('Date')\n if (type.name === 'url') return baseRule.uri()\n if (type.name === 'slug') return baseRule.custom(slugValidator, {bypassConcurrencyLimit: true})\n if (type.name === 'reference') return baseRule.reference()\n if (type.name === 'email') return baseRule.email()\n return baseRule\n}\n\nfunction hasValueField(typeDef: SchemaType | undefined): boolean {\n if (!typeDef) return false\n if (!('fields' in typeDef) && typeDef.type) return hasValueField(typeDef.type)\n if (!('fields' in typeDef)) return false\n if (!Array.isArray(typeDef.fields)) return false\n return typeDef.fields.some((field) => field.name === 'value')\n}\n\nfunction extractValueFromListOption(option: unknown, typeDef: SchemaType): unknown {\n // If you define a `list` option with object items, where the item has a `value` field,\n // we don't want to treat that as the value but rather the surrounding object\n // This differs from the case where you have a title/value pair setup for a string/number, for instance\n if (typeDef.jsonType === 'object' && hasValueField(typeDef)) return option\n\n return (option as Record<string, unknown>).value === undefined\n ? option\n : (option as Record<string, unknown>).value\n}\n\nconst isUriSpec = (spec: RuleSpec): spec is Extract<RuleSpec, {flag: 'uri'}> => spec.flag === 'uri'\n\n// A `url` type auto-injects the default `.uri()` onto every array element, so a\n// custom scheme on one element cannot override the default on its siblings (GH #3298).\nfunction omitLeakedDefaultUri(rules: Rule[], typeDef: SchemaType): Rule[] {\n const isUrlType = getTypeChain(typeDef).some((type) => type.name === 'url')\n if (!isUrlType) return rules\n\n const defaultUri = new RuleClass(typeDef).uri()._rules.find(isUriSpec)?.constraint\n const isDefaultUri = (spec: RuleSpec) => isUriSpec(spec) && isEqual(spec.constraint, defaultUri)\n const isCustomUri = (spec: RuleSpec) => isUriSpec(spec) && !isEqual(spec.constraint, defaultUri)\n\n const someElementSetsScheme = rules.some((rule) => rule._rules.some(isCustomUri))\n if (!someElementSetsScheme) return rules\n\n return rules.map((rule) => {\n if (!rule._rules.some(isDefaultUri)) return rule\n const cleaned = rule.clone()\n cleaned._rules = rule._rules.filter((spec) => !isDefaultUri(spec))\n return cleaned\n })\n}\n\nexport function normalizeValidationRules(\n typeDef: SchemaType | undefined,\n context?: ValidationContext,\n): Rule[] {\n if (!typeDef) {\n return []\n }\n\n const validation = typeDef.validation\n\n if (Array.isArray(validation)) {\n const rules = validation.flatMap((i) =>\n normalizeValidationRules(\n {\n ...typeDef,\n validation: i,\n },\n context,\n ),\n )\n return omitLeakedDefaultUri(rules, typeDef)\n }\n\n const baseRule =\n // using an object + Object.values to de-dupe the type chain by type name\n Object.values(\n getTypeChain(typeDef).reduce<Record<string, SchemaType>>((acc, type) => {\n acc[type.name] = type\n return acc\n }, {}),\n ).reduce(baseRuleReducer, new RuleClass(typeDef))\n\n if (validation && typeof validation === 'object') {\n return [validation]\n }\n\n if (!validation) {\n return [baseRule]\n }\n\n if (typeof validation === 'function') {\n return normalizeValidationRules(\n {\n ...typeDef,\n validation: validation(baseRule, context),\n },\n context,\n )\n }\n\n return [baseRule]\n}\n","import {type Schema, type SchemaType, type SchemaValidationValue} from '@sanity/types'\n\nimport {normalizeValidationRules} from './util/normalizeValidationRules'\n\n// NOTE: this overload is for TS API compatibility with a previous implementation\nexport function inferFromSchemaType(\n typeDef: SchemaType,\n // these are intentionally unused\n _schema: Schema,\n _visited?: Set<SchemaType>,\n): SchemaType\n// note: this seemingly redundant overload is required\nexport function inferFromSchemaType(typeDef: SchemaType): SchemaType\nexport function inferFromSchemaType(typeDef: SchemaType): SchemaType {\n traverse(typeDef, new Set())\n return typeDef\n}\n\nfunction traverse(typeDef: SchemaType, visited: Set<SchemaType>) {\n if (visited.has(typeDef)) {\n return\n }\n\n visited.add(typeDef)\n\n const usesValidationContext = hasValidationContext(typeDef.validation)\n\n // Only normalize validation at schema-compile time when it doesn't rely on runtime context.\n // Context-aware validation functions must be evaluated during validation, where context exists.\n if (!usesValidationContext) {\n typeDef.validation = normalizeValidationRules(typeDef)\n }\n\n if ('fields' in typeDef) {\n for (const field of typeDef.fields) {\n traverse(field.type, visited)\n }\n }\n\n if ('of' in typeDef) {\n for (const candidate of typeDef.of) {\n traverse(candidate, visited)\n }\n }\n\n // @ts-expect-error TODO (eventually): `annotations` does not exist on the SchemaType yet\n if (typeDef.annotations) {\n // @ts-expect-error TODO (eventually): `annotations` does not exist on the SchemaType yet\n for (const annotation of typeDef.annotations) {\n traverse(annotation, visited)\n }\n }\n}\n\n/**\n * Checks if a validation function uses the context parameter.\n *\n * Functions with 2+ parameters like `(rule, context) => ...` need runtime context\n * (e.g., `context.hidden`, `context.document`) and cannot be pre-evaluated at schema compile time.\n *\n * Functions with 1 parameter like `(rule) => rule.required()` don't need context\n * and can be normalized immediately for better performance.\n *\n * @internal\n */\nexport function hasValidationContext(validation: SchemaValidationValue | undefined): boolean {\n if (!validation) return false\n if (Array.isArray(validation)) {\n return validation.some(hasValidationContext)\n }\n if (typeof validation !== 'function') return false\n\n // Check declared parameter count first (most common case)\n if (validation.length >= 2) return true\n\n // Function.length doesn't count rest parameters, so check the signature for patterns like\n // `(rule, ...args)` which would have length === 1 but still expects context\n const signature = Function.prototype.toString.call(validation)\n return /\\(\\s*\\w+\\s*,\\s*\\.\\.\\./.test(signature)\n}\n","import {type Schema} from '@sanity/types'\n\nimport {inferFromSchemaType} from './inferFromSchemaType'\n\n// Note: Mutates schema. Refactor when @sanity/schema supports middlewares\nexport function inferFromSchema(schema: Schema): Schema {\n const typeNames = schema.getLocalTypeNames()\n\n typeNames.forEach((typeName) => {\n const schemaType = schema.get(typeName)\n\n if (schemaType) {\n inferFromSchemaType(schemaType)\n }\n })\n\n return schema\n}\n","import {type ConditionalProperty, type CurrentUser, type Path} from '@sanity/types'\n\n/**\n * @internal\n */\nexport interface ConditionalPropertyCallbackContext {\n parent?: unknown\n document?: Record<string, unknown>\n currentUser: Omit<CurrentUser, 'role'> | null\n value: unknown\n path: Path\n}\n\n/**\n * @internal\n */\nexport function resolveConditionalProperty(\n property: ConditionalProperty,\n context: ConditionalPropertyCallbackContext,\n) {\n const {currentUser, document, parent, value, path} = context\n\n if (typeof property === 'boolean' || property === undefined) {\n return Boolean(property)\n }\n\n return (\n // oxlint-disable-next-line no-unnecessary-boolean-literal-compare - we can't trust the return value here is actually a boolean at runtime\n property({\n document: document as any,\n parent,\n value,\n currentUser,\n path,\n }) === true // note: we can't strictly \"trust\" the return value here, so the conditional property should probably be typed as unknown\n )\n}\n","/**\n * The locale namespace for the studio core.\n *\n * @internal\n * @hidden\n */\nexport const studioLocaleNamespace = 'studio' as const\n\n/**\n * The namespace for validation messages.\n *\n * @internal\n * @hidden\n */\nexport const validationLocaleNamespace = 'validation' as const\n\n/**\n * The namespace for copy/paste messages.\n *\n * @internal\n * @hidden\n */\nexport const copyPasteLocalNamespace = 'copy-paste' as const\n\n/**\n * The namespace for feedback UI strings.\n *\n * @internal\n * @hidden\n */\nexport const feedbackLocaleNamespace = 'feedback' as const\n","import {defineLocalesResources} from '../helpers'\nimport {copyPasteLocalNamespace} from '../localeNamespaces'\nimport {type LocaleResourceBundle} from '../types'\n\n/**\n * The string resources for copy-paste.\n *\n * @internal\n * @hidden\n */\nconst copyPasteLocaleStrings = defineLocalesResources('copy-paste', {\n /** Text on the field action button to copy a document */\n 'copy-paste.field-action-copy-button.document.title': 'Copy document',\n /** Text on the field action button to copy a field */\n 'copy-paste.field-action-copy-button.field.title': 'Copy field',\n /** Text on the field action button to paste a document */\n 'copy-paste.field-action-paste-button.document.title': 'Paste document',\n /** Text on the field action button to paste a field */\n 'copy-paste.field-action-paste-button.field.title': 'Paste field',\n\n /** --- On paste --- */\n\n /** The validation message that is shown when pasting a value into a read-only target */\n 'copy-paste.on-paste.validation.read-only-target.description': 'The target is read-only',\n /** The validation message that is shown when read-only fields are skipped during document paste */\n 'copy-paste.on-paste.validation.read-only-fields-skipped.description':\n 'Skipped read-only fields: {{fieldNames}}',\n /** The validation message for skipped read-only fields when truncated */\n 'copy-paste.on-paste.validation.read-only-fields-skipped-truncated.description':\n 'Skipped read-only fields: {{fieldNames}} and {{count}} more',\n /** The validation message that is shown when the source and target schema types are incompatible */\n 'copy-paste.on-paste.validation.schema-type-incompatible.description':\n 'Source and target schema types are not compatible',\n /** The validation message that is shown when reference types are incompatible */\n 'copy-paste.on-paste.validation.reference-type-incompatible.description':\n 'References of type \"{{sourceReferenceType}}\" is not allowed in reference field that accepts types \"{{targetReferenceTypes}}\"',\n /** The validation message that is shown when reference is incompatible with filter */\n 'copy-paste.on-paste.validation.reference-filter-incompatible.description':\n 'Reference is not allowed in reference field according to filter',\n /** The validation message that is shown when reference does not exist */\n 'copy-paste.on-paste.validation.reference-validation-failed.description':\n 'The referenced document \"{{ref}}\" does not exist',\n /** The validation message that is shown when image files are incompatible */\n 'copy-paste.on-paste.validation.image-file-incompatible.description':\n 'A \"{{sourceSchemaType}}\" is not allowed in a \"{{targetSchemaType}}\"',\n /** The validation message that is shown when array types are incompatible */\n 'copy-paste.on-paste.validation.array-type-incompatible.description':\n 'Value of type \"{{type}}\" is not allowed in this array field',\n /** The validation message that is shown when array values are incompatible */\n 'copy-paste.on-paste.validation.array-value-incompatible.description':\n 'Value of type \"{{type}}\" is not allowed in this array field',\n /** The validation message that is shown when string values are incompatible */\n 'copy-paste.on-paste.validation.string-value-incompatible.description':\n 'Value \"{{value}}\" is not allowed in \"{{allowedStrings}}\"',\n /** The validation message that is shown when primitive types are incompatible */\n 'copy-paste.on-paste.validation.primitive-type-incompatible.description':\n 'Value of type \"{{type}}\" is not allowed in this field',\n\n /** The validation message that is shown when the clipboard is empty */\n 'copy-paste.on-paste.validation.clipboard-empty.title': 'Nothing to paste',\n /** The validation message that is shown when the clipboard item is invalid */\n 'copy-paste.on-paste.validation.clipboard-invalid.title': 'Invalid clipboard item',\n /** The validation message that is shown when schema types are incompatible */\n 'copy-paste.on-paste.validation.schema-type-incompatible.title':\n 'Could not resolve schema type for path: {{path}}',\n /** The warning message that is shown when not all values can be pasted */\n 'copy-paste.on-paste.validation.partial-warning.title': 'Could not paste all values',\n\n /** The error message that is shown when the MIME type is not accepted */\n 'copy-paste.on-paste.validation.mime-type-incompatible.description':\n 'MIME type \"{{mimeType}}\" is not accepted for this field',\n\n /** The error message that is shown when the MIME type validation fails */\n 'copy-paste.on-paste.validation.mime-type-validation-failed.description':\n 'MIME type validation failed',\n\n /** --- On copy --- */\n\n /** The error message that is shown when schema types are incompatible */\n 'copy-paste.on-copy.validation.schema-type-incompatible.title':\n 'Could not resolve schema type for path: {{path}}',\n /** The error message that is shown when there is no value to copy */\n 'copy-paste.on-copy.validation.no-value.title': 'Empty value, nothing to copy',\n /** The error message that is shown when the clipboard is not supported */\n 'copy-paste.on-copy.validation.clipboard-not-supported.description':\n 'Clipboard access required to copy this content. Allow clipboard permissions in your browser settings, then try copying again.',\n /** The error message that is shown when the clipboard is not supported */\n 'copy-paste.on-copy.validation.clipboard-not-supported.title': 'Clipboard access blocked',\n})\n\n/**\n * Locale resources for the copy/paste namespace, eg US English locale resources.\n *\n * @beta\n * @hidden\n */\nexport const copyPasteLocaleResources: LocaleResourceBundle = {\n locale: 'en-US',\n namespace: copyPasteLocalNamespace,\n resources: copyPasteLocaleStrings,\n}\n","/* eslint sort-keys: \"error\" */\nimport {defineLocalesResources} from '../helpers'\nimport {feedbackLocaleNamespace} from '../localeNamespaces'\nimport {type LocaleResourceBundle} from '../types'\n\n/**\n * The string resources for the feedback UI.\n *\n * @internal\n * @hidden\n */\nconst feedbackLocaleStrings = defineLocalesResources('feedback', {\n /** Browse button text */\n 'feedback.attachment.browse': 'Browse',\n /** Drop zone text for image attachment */\n 'feedback.attachment.drop-zone': 'Drag or paste file here',\n /** Error shown when attached image exceeds size limit */\n 'feedback.attachment.error.size': 'Image must be under 20 MB',\n /** Label for the image attachment section */\n 'feedback.attachment.label': 'Attach an image',\n /** Remove attached image button text */\n 'feedback.attachment.remove': 'Remove',\n /** Cancel button text */\n 'feedback.cancel': 'Cancel',\n /** Consent disclaimer shown when the user agrees to follow up */\n 'feedback.consent.disclaimer': `We'd love to learn more. Selecting yes shares your name and email with the Sanity team.`,\n /** Label for the contact consent toggle */\n 'feedback.consent.label': 'Can we follow up with you about this feedback?',\n /** Consent toggle: no */\n 'feedback.consent.no': 'No',\n /** Consent toggle: yes */\n 'feedback.consent.yes': 'Yes',\n /** Title of the feedback dialog */\n 'feedback.dialog.title': 'Share feedback with Sanity',\n /** Toast message after failed submission */\n 'feedback.error': 'Failed to submit feedback with error',\n /** Label for \"send feedback\" in the help resources menu */\n 'feedback.menu-item': 'Send feedback',\n /** Label for the message field */\n 'feedback.message.label': 'What is working? What could be better?',\n /** Placeholder for the message field */\n 'feedback.message.placeholder': 'Describe your issue or request...',\n /** Sentiment option: happy */\n 'feedback.sentiment.happy': 'Easy',\n /** Label for the sentiment question */\n 'feedback.sentiment.label': 'How easy or difficult is Sanity to use?',\n /** Sentiment option: neutral */\n 'feedback.sentiment.neutral': 'Not sure',\n /** Sentiment option: unhappy */\n 'feedback.sentiment.unhappy': 'Difficult',\n /** Submit button text */\n 'feedback.submit': 'Send feedback',\n /** Toast message after successful submission */\n 'feedback.success': 'Feedback submitted, thank you!',\n} as const)\n\n/**\n * Locale resources for the feedback namespace, eg US English locale resources.\n *\n * @beta\n * @hidden\n */\nexport const feedbackLocaleResources: LocaleResourceBundle = {\n locale: 'en-US',\n namespace: feedbackLocaleNamespace,\n resources: feedbackLocaleStrings,\n}\n","/* eslint sort-keys: \"error\" */\nimport {defineLocalesResources} from '../helpers'\nimport {studioLocaleNamespace} from '../localeNamespaces'\nimport {type LocaleResourceBundle} from '../types'\n\n/**\n * The string resources for the studio core.\n *\n * @internal\n * @hidden\n */\nexport const studioLocaleStrings = defineLocalesResources('studio', {\n /** \"Configuration issue\" header */\n 'about-dialog.configuration-issue.header': 'Configuration issue detected',\n /** Message shown if sanity.cli.ts is missing deployment.appId */\n 'about-dialog.configuration-issue.missing-appid':\n 'Auto updates is enabled, but no <code>deployment.appId</code> configured in <code>sanity.cli.ts</code>. This Studio is updating against the <strong>latest</strong>-channel.',\n /** \"View documentation\" link for auto-updating studios */\n 'about-dialog.configuration-issue.missing-appid.view-documentation': 'View documentation',\n /** \"Disabled\" status for auto-updates in About-dialog */\n 'about-dialog.version-info.auto-updates.disabled': 'Auto Updates not enabled',\n /** \"Enabled\" status for auto-updates in About-dialog */\n 'about-dialog.version-info.auto-updates.enabled': 'Auto Updates Enabled',\n /** @deprecated \"Auto Updates\" status header in About-dialog */\n 'about-dialog.version-info.auto-updates.header': 'Auto Updates',\n /** \"How to enable\" next to Disabled state for Auto updates in version info dialog */\n 'about-dialog.version-info.auto-updates.how-to-enable': 'Enable',\n /** \"Manage version\" link text */\n 'about-dialog.version-info.auto-updates.manage-version': 'Manage version',\n /** Text displayed on the \"Copy to clipboard\"-button after clicked */\n 'about-dialog.version-info.copy-to-clipboard-button.copied-text':\n 'Copied to Clipboard. Happy pasting!',\n /** \"Copy to Clipboard\" button text for copying version details from About-dialog */\n 'about-dialog.version-info.copy-to-clipboard-button.text': 'Copy to Clipboard',\n /** \"Current version\" header in version info dialog */\n 'about-dialog.version-info.current-version.header': 'Current version',\n /** @deprecated \"How to upgrade\" link text */\n 'about-dialog.version-info.how-to-upgrade': 'Update now',\n /** \"Latest version\" header in version info dialog */\n 'about-dialog.version-info.latest-version.header': 'Latest version',\n /** Info text when auto updates is enabled and a new version is available */\n 'about-dialog.version-info.new-auto-update-version-available': 'New version available',\n /** \"New version\" header in version info dialog - Note that this is not necessary a *higher* version compared to current:\n * It's a new version configured for auto updates which in some cases could even be a version below current */\n 'about-dialog.version-info.new-version.text': 'New version',\n /** \"Reload\"-button when auto updates is enabled and a new version is available */\n 'about-dialog.version-info.reload': 'Reload',\n /** \"Reload to update\"-tooltip when auto updates is enabled and a new version is available */\n 'about-dialog.version-info.reload-to-update': 'Reload Studio to update',\n /** \"Development\" tooltip in About-dialog */\n 'about-dialog.version-info.tooltip.development': 'Development',\n /** \"New version available\" tooltip in About-dialog */\n 'about-dialog.version-info.tooltip.new-version-available': 'New version available',\n /** \"Prerelease\" tooltip in About-dialog */\n 'about-dialog.version-info.tooltip.prerelease': 'Prerelease',\n /** \"Up to date\" tooltip in About-dialog */\n 'about-dialog.version-info.tooltip.up-to-date': 'Up to date',\n /** @deprecated \"Up to date\" status in About-dialog */\n 'about-dialog.version-info.up-to-date': 'Up to date',\n /** \"Upgrade\"-button text */\n 'about-dialog.version-info.update-button.text': 'Update',\n /** \"Upgrade\"-button tooltip text */\n 'about-dialog.version-info.update-button.tooltip': 'Learn how to update Sanity Studio',\n\n /** \"User agent\" header in About-dialog */\n 'about-dialog.version-info.user-agent.header': 'User agent',\n /** \"View on GitHub\" link from version info dialog */\n 'about-dialog.version-info.view-on-github': 'View on GitHub',\n /** The text used in the tooltip shown in the dialog close button */\n 'announcement.dialog.close': 'Close',\n /** Aria label to be used in the dialog close button */\n 'announcement.dialog.close-label': 'Close dialog',\n /**Text to be used in the tooltip in the button in the studio announcement card */\n 'announcement.floating-button.dismiss': 'Close',\n /**Aria label to be used in the floating button in the studio announcement card, to dismiss the card */\n 'announcement.floating-button.dismiss-label': 'Dismiss announcements',\n /**Aria label to be used in the floating button in the studio announcement card */\n 'announcement.floating-button.open-label': 'Open announcements',\n /** Menu item for deleting the asset */\n 'asset-source.asset-list.menu.delete': 'Delete',\n /** Menu item for showing where a particular asset is used */\n 'asset-source.asset-list.menu.show-usage': 'Show usage',\n /** Header in usage dialog for file assets */\n 'asset-source.asset-usage-dialog.header_file': 'Documents using file',\n /** Header in usage dialog for image assets */\n 'asset-source.asset-usage-dialog.header_image': 'Documents using image',\n /** Text shown in usage dialog when loading documents using the selected asset */\n 'asset-source.asset-usage-dialog.loading': 'Loading…',\n /** Browse button text */\n 'asset-source.browse-button.text': 'Select',\n /** Text for cancel action in delete-asset dialog */\n 'asset-source.delete-dialog.action.cancel': 'Cancel',\n /** Text for \"confirm delete\" action in delete-asset dialog */\n 'asset-source.delete-dialog.action.delete': 'Delete',\n /** Dialog header for delete-asset dialog when deleting a file */\n 'asset-source.delete-dialog.header_file': 'Delete file',\n /** Dialog header for delete-asset dialog when deleting an image */\n 'asset-source.delete-dialog.header_image': 'Delete image',\n /** Text shown in delete dialog when loading documents using the selected asset */\n 'asset-source.delete-dialog.loading': 'Loading…',\n /** Message confirming to delete *named* file */\n 'asset-source.delete-dialog.usage-list.confirm-delete-file_named':\n 'You are about to delete the file <strong>{{filename}}</strong> and its metadata. Are you sure?',\n /** Message confirming to delete *unnamed* file */\n 'asset-source.delete-dialog.usage-list.confirm-delete-file_unnamed':\n 'You are about to delete the file and its metadata. Are you sure?',\n /** Message confirming to delete *named* image */\n 'asset-source.delete-dialog.usage-list.confirm-delete-image_named':\n 'You are about to delete the image <strong>{{filename}}</strong> and its metadata. Are you sure?',\n /** Message confirming to delete *unnamed* image */\n 'asset-source.delete-dialog.usage-list.confirm-delete-image_unnamed':\n 'You are about to delete the image and its metadata. Are you sure?',\n /** Alt text showing on image preview in delete asset dialog */\n 'asset-source.delete-dialog.usage-list.image-preview-alt': 'Preview of image',\n /** Warning message showing when *named* file can't be deleted because it is in use */\n 'asset-source.delete-dialog.usage-list.warning-file-is-in-use_named':\n \"{{filename}} cannot be deleted because it's being used. In order to delete this file, you first need to remove all uses of it.\",\n /** Warning message showing when *unnamed* file can't be deleted because it is in use */\n 'asset-source.delete-dialog.usage-list.warning-file-is-in-use_unnamed':\n \"This file cannot be deleted because it's being used. In order to delete it, you first need to remove all uses of it.\",\n /** Warning message showing when *named* image can't be deleted because it is in use */\n 'asset-source.delete-dialog.usage-list.warning-image-is-in-use_named':\n \"{{filename}} cannot be deleted because it's being used. In order to delete this image, you first need to remove all uses of it.\",\n /** Warning message showing when *unnamed* image can't be deleted because it is in use */\n 'asset-source.delete-dialog.usage-list.warning-image-is-in-use_unnamed':\n \"This image cannot be deleted because it's being used. In order to delete it, you first need to remove all uses of it.\",\n /** Text shown when the list of assets only include a specific set of types */\n 'asset-source.dialog.accept-message':\n 'Only showing assets of accepted types: <strong>{{acceptTypes}}</strong>',\n /** Select asset dialog cancel-button */\n 'asset-source.dialog.button.cancel': 'Cancel',\n /** Select asset dialog select-button */\n 'asset-source.dialog.button.select': 'Select',\n /** Keys shared between both image asset source and file asset source */\n /** Insert asset error */\n 'asset-source.dialog.insert-asset-error':\n 'Error inserting asset. See the console for more information.',\n /** Toast title shown when the list of assets failed to load */\n 'asset-source.dialog.load-error': 'Failed to load assets',\n /** Select asset dialog load more items */\n 'asset-source.dialog.load-more': 'Load more',\n /** Text shown when selecting a file but there's no files to select from\n * @deprecated no longer in use\n */\n 'asset-source.dialog.no-assets_file': 'No files',\n /** Text shown when selecting an image but there's no images to select from\n * @deprecated no longer in use\n */\n 'asset-source.dialog.no-assets_image': 'No images',\n 'asset-source.file.asset-list.action.delete.disabled-cannot-delete-current-file':\n 'Cannot delete currently selected file',\n 'asset-source.file.asset-list.action.delete.text': 'Delete',\n 'asset-source.file.asset-list.action.delete.title': 'Delete file',\n 'asset-source.file.asset-list.action.select-file.title': 'Select the file {{filename}}',\n 'asset-source.file.asset-list.action.show-usage.title': 'Show usage',\n 'asset-source.file.asset-list.delete-failed': 'File could not be deleted',\n 'asset-source.file.asset-list.delete-successful': 'File was deleted',\n 'asset-source.file.asset-list.header.date-added': 'Date added',\n /** File asset source */\n 'asset-source.file.asset-list.header.filename': 'Filename',\n 'asset-source.file.asset-list.header.size': 'Size',\n 'asset-source.file.asset-list.header.type': 'Type',\n /** Text displayed on button or menu invoking the file asset source */\n 'asset-source.file.title': 'Uploaded files',\n 'asset-source.image.asset-list.delete-failed': 'Image could not be deleted',\n /** Image asset source */\n 'asset-source.image.asset-list.delete-successful': 'Image was deleted',\n /** Text displayed on button or menu invoking the image asset source */\n 'asset-source.image.title': 'Uploaded images',\n /** Built in asset source usage texts */\n 'asset-source.usage-list.documents-using-file_named_one':\n 'One document is using file <code>{{filename}}</code>',\n 'asset-source.usage-list.documents-using-file_named_other':\n '{{count}} documents are using file <code>{{filename}}</code>',\n /** Text shown in usage dialog for a file asset when there are zero, one or more documents using the *named* file **/\n 'asset-source.usage-list.documents-using-file_named_zero':\n 'No documents are using file <code>{{filename}}</code>',\n 'asset-source.usage-list.documents-using-file_unnamed_one': 'One document is using this file',\n 'asset-source.usage-list.documents-using-file_unnamed_other':\n '{{count}} documents are using this file',\n /** Text shown in usage dialog for a file asset when there are zero, one or more documents using the *unnamed* file **/\n 'asset-source.usage-list.documents-using-file_unnamed_zero': 'No documents are using this file',\n 'asset-source.usage-list.documents-using-image_named_one':\n 'One document is using image <code>{{filename}}</code>',\n 'asset-source.usage-list.documents-using-image_named_other':\n '{{count}} documents are using image <code>{{filename}}</code>',\n /** Text shown in usage dialog for an image asset when there are zero, one or more documents using the *named* image **/\n 'asset-source.usage-list.documents-using-image_named_zero':\n 'No documents are using image <code>{{filename}}</code>',\n 'asset-source.usage-list.documents-using-image_unnamed_one': 'One document is using this image',\n 'asset-source.usage-list.documents-using-image_unnamed_other':\n '{{count}} documents are using this image',\n /** Text shown in usage dialog for an image asset when there are zero, one or more documents using the *unnamed* image **/\n 'asset-source.usage-list.documents-using-image_unnamed_zero': 'No documents are using this image',\n\n /** Common (all) Asset Source texts. Note that all translation keys starting with 'asset-source.' is for the built in asset source. */\n 'asset-sources.common.uploader.upload-failed.description':\n 'See the console for more information.',\n 'asset-sources.common.uploader.upload-failed.title': 'Upload failed',\n\n /** Menu Items for Dataset Asset Source (will be replaced with workspace name by default) */\n 'asset-sources.dataset.file.title': 'Workspace files',\n 'asset-sources.dataset.image.title': 'Workspace images',\n\n /** Error messages for the Media Library Asset Source */\n 'asset-sources.media-library.error.library-could-not-be-resolved':\n 'Something went wrong trying to resolve the Media Library for this project.',\n\n /** Error message shown when no media library has been provisioned for the current organization */\n 'asset-sources.media-library.error.no-media-library-provisioned':\n 'No media library has been provisioned for this organization.',\n\n /** Menu Items for Media Library Asset Source */\n 'asset-sources.media-library.file.title': 'Media Library',\n 'asset-sources.media-library.image.title': 'Media Library',\n\n /** Done button text */\n 'asset-sources.media-library.open-in-source-dialog.button.done': 'Done',\n\n /** Select new asset button text with target title */\n 'asset-sources.media-library.open-in-source-dialog.button.select-new-asset':\n 'Select new asset for “{{targetTitle}}”',\n 'asset-sources.media-library.open-in-source-dialog.button.select-new-asset-fallback':\n 'Select new asset',\n\n /** Title for the open in source dialog */\n 'asset-sources.media-library.open-in-source-dialog.title': 'Edit asset',\n\n /** Title for the upload dialog (component mode) */\n 'asset-sources.media-library.upload-dialog.title': 'Upload to Media Library',\n\n /** Warning message shown when uploading already existing files to the Media Library Asset Source */\n 'asset-sources.media-library.warning.file-already-exist.description':\n 'Using the existing file found in the library.',\n 'asset-sources.media-library.warning.file-already-exist.title':\n \"File: '{{filename}}' already exists\",\n\n /** Label when a release has been deleted by a different user */\n 'banners.deleted-bundle-banner.text':\n \"The '<strong>{{title}}</strong>' release has been deleted.\",\n\n /** Action message for navigating to next month */\n 'calendar.action.go-to-next-month': 'Go to next month',\n /** Action message for navigating to next year */\n 'calendar.action.go-to-next-year': 'Go to next year',\n /** Action message for navigating to previous month */\n 'calendar.action.go-to-previous-month': 'Go to previous month',\n /** Action message for navigating to previous year */\n 'calendar.action.go-to-previous-year': 'Go to previous year',\n /* Label for navigating the calendar to \"today\", without _selecting_ today. Short form, eg `Today`, not `Go to today` */\n 'calendar.action.go-to-today': 'Today',\n /* Accessibility label for navigating the calendar to \"today\", without _selecting_ today */\n 'calendar.action.go-to-today-aria-label': 'Go to today',\n /* Label for navigating the calendar to \"tomorrow\", without _selecting_ tomorrow. Short form, eg `Tomorrow`, not `Go to tomorrow` */\n 'calendar.action.go-to-tomorrow': 'Tomorrow',\n /* Label for navigating the calendar to \"yesterday\", without _selecting_ yesterday. Short form, eg `Yesterday`, not `Go to yesterday` */\n 'calendar.action.go-to-yesterday': 'Yesterday',\n /** Label for switch that controls whether or not to include time in given timestamp */\n 'calendar.action.include-time-label': 'Include time',\n /** Action message for selecting the time */\n 'calendar.action.select-time': 'Select time',\n /** Action message for setting to the current time */\n 'calendar.action.set-to-current-time': 'Set to current time',\n /** Label for selecting an hour preset. Receives a `time` param as a string on hh:mm format and a `date` param as a Date instance denoting the preset date */\n 'calendar.action.set-to-time-preset': '{{time}} on {{date, datetime}}',\n /** Aria label for button to open date picker */\n 'calendar.button.aria-label': 'Open calendar',\n /** Tooltip content for button to open datetime input */\n 'calendar.button.tooltip-text': 'Select date',\n /** Error message displayed in calendar when entered date is not the correct format */\n 'calendar.error.must-be-in-format': 'Must be in the format: {{exampleDate}}',\n /** Month name for April */\n 'calendar.month-names.april': 'April',\n /** Month name for August */\n 'calendar.month-names.august': 'August',\n /** Month name for December */\n 'calendar.month-names.december': 'December',\n /** Month name for February */\n 'calendar.month-names.february': 'February',\n /** Month name for January */\n 'calendar.month-names.january': 'January',\n /** Month name for July */\n 'calendar.month-names.july': 'July',\n /** Month name for June */\n 'calendar.month-names.june': 'June',\n /** Month name for March */\n 'calendar.month-names.march': 'March',\n /** Month name for May */\n 'calendar.month-names.may': 'May',\n /** Month name for November */\n 'calendar.month-names.november': 'November',\n /** Month name for October */\n 'calendar.month-names.october': 'October',\n /** Month name for September */\n 'calendar.month-names.september': 'September',\n /** Short weekday name for Friday */\n 'calendar.weekday-names.short.friday': 'Fri',\n /** Short weekday name for Monday */\n 'calendar.weekday-names.short.monday': 'Mon',\n /** Short weekday name for Saturdayday */\n 'calendar.weekday-names.short.saturday': 'Sat',\n /** Short weekday name for Sunday */\n 'calendar.weekday-names.short.sunday': 'Sun',\n /** Short weekday name for Thursday */\n 'calendar.weekday-names.short.thursday': 'Thu',\n /** Short weekday name for Tuesday */\n 'calendar.weekday-names.short.tuesday': 'Tue',\n /** Short weekday name for Wednesday */\n 'calendar.weekday-names.short.wednesday': 'Wed',\n\n /** The name of Content Agent, the product. */\n 'content-agent': 'Content Agent',\n\n /** Label for the close button label in Review Changes pane */\n 'changes.action.close-label': 'Close history',\n /** Cancel label for revert button prompt action */\n 'changes.action.revert-all-cancel': 'Cancel',\n /** Revert all confirm label for revert button action - used on prompt button + review changes pane */\n 'changes.action.revert-all-confirm': 'Revert all',\n /** Prompt for reverting all changes in document in Review Changes pane. Includes a count of changes. */\n 'changes.action.revert-all-description': 'Are you sure you want to revert all {{count}} changes?',\n /** Prompt for confirming revert change (singular) label for field change action */\n 'changes.action.revert-changes-confirm-change_one': 'Revert change',\n /** Revert for confirming revert (plural) label for field change action */\n 'changes.action.revert-changes-confirm-change_other': 'Revert changes',\n /** Prompt for reverting changes for a field change */\n 'changes.action.revert-changes-description': 'Are you sure you want to revert the changes?',\n /** Prompt for reverting changes for a group change, eg multiple changes */\n 'changes.action.revert-changes-description_one': 'Are you sure you want to revert the change?',\n /** Label for when the action of the change was to set something that was previously empty, eg a field was given a value, an array item was added, an asset was selected or similar */\n 'changes.added-label': 'Added',\n /** Array diff: An item was added in a given position (`{{position}}`) */\n 'changes.array.item-added-in-position': 'Added in position {{position}}',\n 'changes.array.item-moved_down_one': 'Moved {{count}} position down',\n 'changes.array.item-moved_down_other': 'Moved {{count}} positions down',\n /**\n * Array diff: An item was moved within the array.\n * Receives `{{count}}` representing number of positions it moved.\n * Context is the direction of the move, either `up` or `down`.\n */\n 'changes.array.item-moved_up_one': 'Moved {{count}} position up',\n 'changes.array.item-moved_up_other': 'Moved {{count}} positions up',\n /** Array diff: An item was removed from a given position (`{{position}}`) */\n 'changes.array.item-removed-from-position': 'Removed from position {{position}}',\n /** Accessibility label for the \"change bar\" shown when there are edits on a field-level */\n 'changes.change-bar.aria-label': 'Review changes',\n /** Label for when the action of the change was _not_ an add/remove, eg a text field changed value, an image was changed from one asset to another or similar */\n 'changes.changed-label': 'Changed',\n /** Label and text for tooltip that indicates the authors of the changes */\n 'changes.changes-by-author': 'Changes by',\n /** Additional text shown in development mode when a diff component crashes during rendering */\n 'changes.error-boundary.developer-info': 'Check the developer console for more information',\n /** Text shown when a diff component crashes during rendering, triggering the error boundary */\n 'changes.error-boundary.title': 'Rendering the changes to this field caused an error',\n /* Error description when changes could not be loaded */\n 'changes.error-description': \"We're unable to load the changes for this document.\",\n /** Error title when changes could not be loaded */\n 'changes.error-title': 'Something went wrong',\n /** Error message shown when the value of a field is not the expected one */\n 'changes.error.incorrect-type-message':\n 'Value error: Value is of type \"<code>{{actualType}}</code>\", expected \"<code>{{expectedType}}</code>\"',\n /** File diff: Fallback title for the meta info section when there is no original filename to use */\n 'changes.file.meta-info-fallback-title': 'Untitled',\n /** Image diff: Text shown in tooltip when hovering hotspot that has changed in diff view */\n 'changes.image.crop-changed': 'Crop changed',\n /** Image diff: Text shown if the previous image asset was deleted (shouldn't theoretically happen) */\n 'changes.image.deleted': 'Image deleted',\n /** Image diff: Text shown if the image failed to be loaded when previewing it */\n 'changes.image.error-loading-image': 'Error loading image',\n /** Image diff: Text shown in tooltip when hovering hotspot that has changed in diff view */\n 'changes.image.hotspot-changed': 'Hotspot changed',\n /** Image diff: Fallback title for the meta info section when there is no original filename to use */\n 'changes.image.meta-info-fallback-title': 'Untitled',\n /** Image diff: Text shown if no asset has been set for the field (but has metadata changes) */\n 'changes.image.no-asset-set': 'Image not set',\n /** Image diff: Text shown when the from/to state has/had no image */\n 'changes.image.no-image-placeholder': '(no image)',\n /** Label for the \"from\" value in the change inspector */\n 'changes.inspector.from-label': 'From',\n /** Label for the \"meta\" (field path, action etc) information in the change inspector */\n 'changes.inspector.meta-label': 'Meta',\n /** Label for the \"to\" value in the change inspector */\n 'changes.inspector.to-label': 'To',\n /** Loading author of change in the differences tooltip in the review changes pane */\n 'changes.loading-author': 'Loading…',\n /** Loading changes in Review Changes Pane */\n 'changes.loading-changes': 'Loading changes…',\n /** Error message shown when the document revision could not be found */\n 'changes.missing-since-document-error':\n \"We couldn't find the document revision with id: <code>{{revisionId}}</code> you're trying to compare. <Break/> This is probably due to history retention policy of your plan. <Break/> Please select a different <strong>From</strong> entry.\",\n /** No Changes description in the Review Changes pane */\n 'changes.no-changes-description':\n 'Edit the document or select an older version in the timeline to see a list of changes appear in this panel.',\n /** No Changes title in the Review Changes pane */\n 'changes.no-changes-title': 'There are no changes',\n /* Label for the tooltip that shows when an action is not selectable*/\n 'changes.not-selectable': 'It is not possible to select this event',\n /** Portable Text diff: An annotation was added */\n 'changes.portable-text.annotation_added': 'Added annotation',\n /** Portable Text diff: An annotation was changed */\n 'changes.portable-text.annotation_changed': 'Changed annotation',\n /** Portable Text diff: An annotation was removed */\n 'changes.portable-text.annotation_removed': 'Removed annotation',\n /** Portable Text diff: An annotation was left unchanged */\n 'changes.portable-text.annotation_unchanged': 'Unchanged annotation',\n /** Portable Text diff: A block changed from one style to another (eg `normal` to `h1` or similar) */\n 'changes.portable-text.block-style-changed':\n 'Changed block style from \"{{fromStyle}}\" to \"{{toStyle}}\"',\n /** Portable Text diff: Change formatting of text (setting/unsetting marks, eg bold/italic etc) */\n 'changes.portable-text.changed-formatting': 'Changed formatting',\n /** Portable Text diff: An empty inline object is part of a change */\n 'changes.portable-text.empty-inline-object': 'Empty {{inlineObjectType}}',\n /** Portable Text diff: An empty object is the result of adding/removing an annotation */\n 'changes.portable-text.empty-object-annotation': 'Empty {{annotationType}}',\n /** Portable Text diff: Added a block containing no text (eg empty block) */\n 'changes.portable-text.empty-text_added': 'Added empty text',\n /** Portable Text diff: Changed a block that contained no text (eg empty block) */\n 'changes.portable-text.empty-text_changed': 'Changed empty text',\n /** Portable Text diff: Removed a block containing no text (eg empty block) */\n 'changes.portable-text.empty-text_removed': 'Removed empty text',\n /** Portable Text diff: An inline object was added */\n 'changes.portable-text.inline-object_added': 'Added inline object',\n /** Portable Text diff: An inline object was changed */\n 'changes.portable-text.inline-object_changed': 'Changed inline object',\n /** Portable Text diff: An inline object was removed */\n 'changes.portable-text.inline-object_removed': 'Removed inline object',\n /** Portable Text diff: An inline object was left unchanged */\n 'changes.portable-text.inline-object_unchanged': 'Unchanged inline object',\n /** Portable Text diff: Added a chunk of text */\n 'changes.portable-text.text_added': 'Added text',\n /** Portable Text diff: Removed a chunk of text */\n 'changes.portable-text.text_removed': 'Removed text',\n /** Portable Text diff: Annotation has an unknown schema type */\n 'changes.portable-text.unknown-annotation-schema-type': 'Unknown schema type',\n /** Portable Text diff: Inline object has an unknown schema type */\n 'changes.portable-text.unknown-inline-object-schema-type': 'Unknown schema type',\n /** Label for when the action of the change was a removal, eg a field was cleared, an array item was removed, an asset was deselected or similar */\n 'changes.removed-label': 'Removed',\n /** Same Revision Selected description in the Review Changes pane */\n 'changes.same-revision-selected-description':\n 'You have selected the same <strong>from</strong> and <strong>to</strong> revision, please select different revisions to compare the changes between them.',\n /** Same Revision Selected title in the Review Changes pane */\n 'changes.same-revision-selected-title': 'Same revision selected',\n /** Title for the Review Changes pane */\n 'changes.title': 'History',\n /** Shown above raw JSON diff for document fields that are not defined in the schema */\n 'changes.unknown-schema-field.description':\n 'This field is not defined in the schema. Values are shown as JSON.',\n /**The title that will be shown in the badge inside the events when the item is a draft */\n 'changes.versions.draft': 'Draft',\n\n /** --- Common components --- */\n /** Tooltip text for context menu buttons */\n 'common.context-menu-button.tooltip': 'Show more',\n\n /** Default text for dialog cancel button */\n 'common.dialog.cancel-button.text': 'Cancel',\n\n /** Default text for dialog confirm button */\n 'common.dialog.confirm-button.text': 'Confirm',\n\n /** Default text in shared loader text / spinner lockup */\n 'common.loading': 'Loading',\n\n /** The title of the reconnecting toast */\n 'common.reconnecting.toast.title': 'Trying to connect…',\n\n /** --- Configuration issues --- */\n\n /** Default label text on configuration issues button */\n 'configuration-issues.button.label': 'Configuration issues',\n /** Tooltip displayed on configuration issues button */\n 'configuration-issues.button.tooltip': 'Found configuration issues',\n\n /** The fallback title for an ordering menu item if no localized titles are provided. */\n 'default-menu-item.fallback-title': 'Sort by {{title}}',\n\n /** Title for the default ordering/SortOrder if no orderings are provided and the caption field is found */\n 'default-orderings.caption': 'Sort by Caption',\n /** Title for the default ordering/SortOrder if no orderings are provided and the description field is found */\n 'default-orderings.description': 'Sort by Description',\n /** Title for the default ordering/SortOrder if no orderings are provided and the header field is found */\n 'default-orderings.header': 'Sort by Header',\n /** Title for the default ordering/SortOrder if no orderings are provided and the heading field is found */\n 'default-orderings.heading': 'Sort by Heading',\n /** Title for the default ordering/SortOrder if no orderings are provided and the label field is found */\n 'default-orderings.label': 'Sort by Label',\n /** Title for the default ordering/SortOrder if no orderings are provided and the name field is found */\n 'default-orderings.name': 'Sort by Name',\n /** Title for the default ordering/SortOrder if no orderings are provided and the title field is found */\n 'default-orderings.title': 'Sort by Title',\n\n /** Label for action that closes divergence inspector */\n 'divergence.action.close.label': 'Close',\n /** Label for action that marks divergence as resolved */\n 'divergence.action.markResolved.label': 'Ignore',\n /** Label for action that moves inspector to the next divergence in the document */\n 'divergence.action.next.label': 'Next',\n /** Label for action that moves inspector to the previous divergence in the document */\n 'divergence.action.previous.label': 'Previous',\n /** Label for action that replaces the node's value in the current version with its latest value in the upstream version */\n 'divergence.action.takeFromUpstream.label': 'Copy from base',\n /** Verb to describe the node's value changed */\n 'divergence.effect.changed': 'changed',\n /** Summary of the change that occurred */\n 'divergence.effect.summary': '{{title}} {{effect}} in {{versionName}} version',\n /** Description of the position of the current divergence being inspected, compared to the total count of divergences */\n 'divergence.pagination': '{{position}} of {{count}}',\n /** Label for divergence in a single node */\n 'divergence.unresolved-divergence_one': 'Unresolved change in {{versionName}} version',\n /** Label for divergences in multiple nodes */\n 'divergence.unresolved-divergence_other':\n '{{count}} unresolved changes in {{versionName}} version',\n\n /** --- Document inventory --- */\n\n /** The label shown when dismissing the document group inventory */\n 'document-group-inventory.action.cancel': 'Cancel',\n /** The label used in the feedback dialog asking how easy the document group inventory is to use */\n 'document-group-inventory.feedback.sentiment-label':\n 'How easy or difficult is the new version inventory to use?',\n /** The label for the input that filters the variants in the document group inventory */\n 'document-group-inventory.filter-string.label': 'Filter {{subject}}',\n /** The document inventory title (singular) */\n 'document-group-inventory.title': '{{count}} {{subject}}',\n /** The document inventory title (plural) */\n 'document-group-inventory.title_one': '{{count}} {{subject}}',\n /** The document inventory title (plural) */\n 'document-group-inventory.title_other': '{{count}} {{subject}}',\n /** The label text that indicates an item in the document group inventory is currently being viewed */\n 'document-group-inventory.viewing-item-label': 'viewing',\n\n /** --- Document group --- */\n\n /** The label given to a document group's base variant */\n 'document-group.base-variant': 'All users (Default)',\n /** The text in the \"Cancel\" button in the confirm delete dialog that cancels the action */\n 'document-group.delete.cancel-button.text': 'Cancel',\n /** Used in `document-group.delete.cdr-summary.title` */\n 'document-group.delete.cdr-summary.document-count_one': '1 document',\n /** Used in `document-group.delete.cdr-summary.title` */\n 'document-group.delete.cdr-summary.document-count_other': '{{count}} documents',\n /** The text that appears in the subtitle `<summary>` that lists the datasets below the title */\n 'document-group.delete.cdr-summary.subtitle_one': 'Dataset: {{datasets}}',\n /** The text that appears in the subtitle `<summary>` that lists the datasets below the title */\n 'document-group.delete.cdr-summary.subtitle_other': 'Datasets: {{datasets}}',\n /** The text that appears in the subtitle `<summary>` that lists the datasets below the title */\n 'document-group.delete.cdr-summary.subtitle_unavailable_one': 'Unavailable dataset',\n /** The text that appears in the subtitle `<summary>` that lists the datasets below the title */\n 'document-group.delete.cdr-summary.subtitle_unavailable_other': 'Unavailable datasets',\n /** The text that appears in the title `<summary>` that includes the list of CDRs (singular) */\n 'document-group.delete.cdr-summary.title_one': '{{documentCount}} in another dataset',\n /** The text that appears in the title `<summary>` that includes the list of CDRs (plural) */\n 'document-group.delete.cdr-summary.title_other': '{{documentCount}} in {{count}} datasets',\n /** Appears when hovering over the copy button to copy */\n 'document-group.delete.cdr-table.copy-id-button.tooltip': 'Copy ID to clipboard',\n /** The header for the dataset column in the list of cross-dataset references found */\n 'document-group.delete.cdr-table.dataset.label': 'Dataset',\n /** The header for the document ID column in the list of cross-dataset references found */\n 'document-group.delete.cdr-table.document-id.label': 'Document ID',\n /** The toast title when the copy button has been clicked but copying failed */\n 'document-group.delete.cdr-table.id-copied-toast.title-failed': 'Failed to copy document ID',\n /** The header for the project ID column in the list of cross-dataset references found */\n 'document-group.delete.cdr-table.project-id.label': 'Project ID',\n /** The text in the \"Delete now\" button in the confirm delete dialog that confirms the action (singular) */\n 'document-group.delete.confirm-button.text_one': 'Delete (1)',\n /** The text in the \"Delete now\" button in the confirm delete dialog that confirms the action (plural) */\n 'document-group.delete.confirm-button.text_other': 'Delete ({{count}})',\n /** The message shown after deletion fails */\n 'document-group.delete.error.message':\n 'An error occurred while attempting to delete this document. This usually means that there are other documents that refer to it.',\n /** Shown if there are references to other documents but the user does not have the permission to see the relevant document IDs */\n 'document-group.delete.other-reference-count.title_one': '1 other reference not show',\n /** Shown if there are references to other documents but the user does not have the permission to see the relevant document IDs */\n 'document-group.delete.other-reference-count.title_other': '{{count}} other references not shown',\n /** Text in the tooltip of this component if hovering over the info icon */\n 'document-group.delete.other-reference-count.tooltip':\n \"We can't display metadata for these references due to a missing access token for the related datasets.\",\n /** Appears when unable to render a document preview in the referring document list */\n 'document-group.delete.preview-item.preview-unavailable.subtitle': 'ID: {{documentId}}',\n /** Appears when unable to render a document preview in the referring document list */\n 'document-group.delete.preview-item.preview-unavailable.title': 'Preview unavailable',\n /** Tells the user the count of how many other referring documents there are before listing them. (singular) */\n 'document-group.delete.referring-document-count.text_one':\n '1 document refers to “<DocumentTitle/>”',\n /** Tells the user the count of how many other referring documents there are before listing them. (plural) */\n 'document-group.delete.referring-document-count.text_other':\n '{{count}} documents refer to “<DocumentTitle/>”',\n /** Describes the list of documents that refer to the one trying to be deleted (delete) */\n 'document-group.delete.referring-documents-descriptor.text':\n 'You may not be able to delete “<DocumentTitle/>” because the following documents refer to it:',\n /** Header of the delete dialog. `count` controls pluralization; `subject` is a translated noun (see `document-group.subject.*`) (singular) */\n 'document-group.delete.title_one': 'Delete {{count}} {{subject}}',\n /** Header of the delete dialog. `count` controls pluralization; `subject` is a translated noun (see `document-group.subject.*`) (plural) */\n 'document-group.delete.title_other': 'Delete {{count}} {{subject}}',\n /** Translated noun used as the `{{subject}}` value in document group strings such as `document-group.delete.title` (singular) */\n 'document-group.subject.variant_one': 'variant',\n /** Translated noun used as the `{{subject}}` value in document group strings such as `document-group.delete.title` (plural) */\n 'document-group.subject.variant_other': 'variants',\n /** Translated noun used as the `{{subject}}` value in document group strings such as `document-group.delete.title` (singular) */\n 'document-group.subject.version_one': 'version',\n /** Translated noun used as the `{{subject}}` value in document group strings such as `document-group.delete.title` (plural) */\n 'document-group.subject.version_other': 'versions',\n\n /** Label to show in the document footer indicating the creation date of the document */\n 'document-status.created': 'Created {{date}}',\n\n /** Label to show in the document status indicating the date of the status */\n 'document-status.date': '{{date}}',\n /** Label to show in the document footer indicating the last edited date of the document */\n 'document-status.edited': 'Edited {{date}}',\n /** Label to show in the document footer status line when a document was last published */\n 'document-status.last-published': 'Last published',\n /** Label to show in the document footer indicating the document is not published*/\n 'document-status.not-published': 'Not published',\n /** Label to show in the document footer indicating the published date of the document */\n 'document-status.published': 'Edited {{date}}',\n /** Label to show in the document footer indicating the revision from date of the document */\n 'document-status.revision-from': 'Revision from <em>{{date}}</em>',\n\n /** Label to show in the document footer indicating that the revision was not found */\n 'document-status.revision-not-found': 'Revision not found',\n\n /** Toast description shown when saving changes is taking longer than expected */\n 'document-store.slow-commit.description': 'Your changes are still being saved.',\n /** Toast title shown when saving changes is taking longer than expected */\n 'document-store.slow-commit.title': 'Saving is taking longer than expected',\n\n /** Toast title shown when a document's initial value could not be resolved */\n 'document.initial-value.error.title': 'Could not resolve initial value',\n /**\n * Toast description shown when a document's initial value could not be\n * resolved. Includes the underlying error message.\n */\n 'document.initial-value.error.description':\n 'The document opened with an empty value. {{errorMessage}}',\n\n /** Label to indicate that a document type was not found */\n 'document.type.not-found': 'Document type \"{{type}}\" not found',\n\n /** Error message shown when an action cannot be performed */\n 'errors.unable-to-perform-action': 'Unable to perform this action',\n\n /** The value of the <code>_key</code> property must be a unique string. */\n 'form.error.duplicate-keys-alert.details.additional-description':\n 'The value of the <code>_key</code> property must be a unique string.',\n /** This usually happens when items are created using an API client, and the <code>_key</code> property of each elements has been generated non-uniquely. */\n 'form.error.duplicate-keys-alert.details.description':\n 'This usually happens when items are created using an API client, and the <code>_key</code> property of each elements has been generated non-uniquely.',\n /** Developer info */\n 'form.error.duplicate-keys-alert.details.title': 'Developer info',\n /** Generate unique keys */\n 'form.error.duplicate-keys-alert.generate-button.text': 'Generate unique keys',\n /** Several items in this list share the same identifier (key). Every item must have an unique identifier. */\n 'form.error.duplicate-keys-alert.summary':\n 'Several items in this list share the same identifier (key). Every item must have an unique identifier.',\n /** Non-unique keys */\n 'form.error.duplicate-keys-alert.title': 'Non-unique keys',\n /** Error text shown when a field with a given name cannot be found in the schema or is conditionally hidden but explicitly told to render */\n 'form.error.field-not-found':\n 'Field \"{{fieldName}}\" not found among members – verify that it is defined in the schema and that it has not been conditionally hidden.',\n /** Add missing keys */\n 'form.error.missing-keys-alert.add-button.text': 'Add missing keys',\n /** The value of the <code>_key</code> property must be a unique string. */\n 'form.error.missing-keys-alert.details.additional-description':\n 'The value of the <code>_key</code> property must be a unique string.',\n /** This usually happens when items are created using an API client, and the <code>_key</code> property has not been included. */\n 'form.error.missing-keys-alert.details.description':\n 'This usually happens when items are created using an API client, and the <code>_key</code> property has not been included.',\n /** Developer info */\n 'form.error.missing-keys-alert.details.title': 'Developer info',\n /** Some items in the list are missing their keys. This must be fixed in order to edit the list. */\n 'form.error.missing-keys-alert.summary':\n 'Some items in the list are missing their keys. This must be fixed in order to edit the list.',\n /** Missing keys */\n 'form.error.missing-keys-alert.title': 'Missing keys',\n /** This usually happens when items are created using an API client, or when a custom input component has added invalid data to the list. */\n 'form.error.mixed-array-alert.details.description':\n 'This usually happens when items are created using an API client, or when a custom input component has added invalid data to the list.',\n /** Developer info */\n 'form.error.mixed-array-alert.details.title': 'Developer info',\n /** Remove non-object values */\n 'form.error.mixed-array-alert.remove-button.text': 'Remove non-object values',\n /** Some items in this list are not objects. This must be fixed in order to edit the list. */\n 'form.error.mixed-array-alert.summary':\n 'Some items in this list are not objects. This must be fixed in order to edit the list.',\n /** Invalid list values */\n 'form.error.mixed-array-alert.title': 'Invalid list values',\n /** Error text shown when form is unable to find an array item at a given indexed path */\n 'form.error.no-array-item-at-index':\n 'No array item at index <code>{{index}}</code> found at path <code>{{path}}</code>',\n /** Error text shown when form is unable to find an array item at a given keyed path */\n 'form.error.no-array-item-at-key':\n 'No array item with `_key` <code>\"{{key}}\"</code> found at path <code>{{path}}</code>',\n /** The title above the error call stack output related to the crash */\n 'form.error.unhandled-runtime-error.call-stack.title': 'Call Stack:',\n /** The title above the error component stack provided by React's underlying ErrorBoundary component */\n 'form.error.unhandled-runtime-error.component-stack.title': 'Component Stack:',\n /** The error message for the unhandled error that crashed the Input component during render */\n 'form.error.unhandled-runtime-error.error-message': 'Error: {{message}}',\n /** The title for the error card rendered inside a field in place of a crashing input */\n 'form.error.unhandled-runtime-error.title': 'Unhandled Runtime Error',\n /** Form field deprecated label */\n 'form.field.deprecated-label': 'deprecated',\n /** Fallback title shown above field if it has no defined title */\n 'form.field.untitled-field-label': 'Untitled',\n /** Accessibility label for the icon that indicates the field has a validation error */\n 'form.validation.has-error-aria-label': 'Has error',\n /** Accessibility label for the icon that indicates the field has validation information */\n 'form.validation.has-info-aria-label': 'Has information',\n /** Accessibility label for the icon that indicates the field has a validation warning */\n 'form.validation.has-warning-aria-label': 'Has warning',\n /** Text shown when summarizing validation information, when the field has one or more errors */\n 'form.validation.summary.errors-count_one': '{{count}} error',\n 'form.validation.summary.errors-count_other': '{{count}} errors',\n /** Text shown when summarizing validation information, when the field has one or more warnings */\n 'form.validation.summary.warnings-count_one': '{{count}} warning',\n 'form.validation.summary.warnings-count_other': '{{count}} warnings',\n\n /** Tooltip for free trial navbar button indicating remaining days */\n 'free-trial.tooltip.days-count_one': '{{count}} day left in trial',\n 'free-trial.tooltip.days-count_other': '{{count}} days left in trial',\n /** Tooltip for free trial navbar button, once trial has ended */\n 'free-trial.tooltip.trial-finished': 'Upgrade your project',\n\n /**\n * Label for \"contact sales\" call to action\n * These are titles for fallback links in the event the help & resources endpoint isn't able to be fetched\n */\n 'help-resources.action.contact-sales': 'Contact sales',\n\n /**\n * Label for \"help and support\" call to action\n * These are titles for fallback links in the event the help & resources endpoint isn't able to be fetched\n */\n 'help-resources.action.help-and-support': 'Help and support',\n\n /**\n * Label for \"join our community\" call to action\n * These are titles for fallback links in the event the help & resources endpoint isn't able to be fetched\n */\n 'help-resources.action.join-our-community': 'Join our community',\n\n /** Information for what the latest sanity version is */\n 'help-resources.latest-sanity-version': 'Latest version is v{{latestVersion}}',\n\n /** Text for link to register a studio */\n 'help-resources.register-studio': 'Register studio',\n\n /** Name of the sanity studio */\n 'help-resources.studio': 'Sanity Studio',\n\n /** Menu item for registered studios (i.e. copies app id) */\n 'help-resources.studio-app-id': 'App id',\n\n /** Menu item for reloading Studio to update */\n 'help-resources.studio-auto-update-now': 'Reload to update to v{{newVersion}}',\n\n /** Information for what studio version the current studio is running */\n 'help-resources.studio-version': 'Sanity Studio v{{studioVersion}}',\n\n /** Title for help and resources menus */\n 'help-resources.title': 'Help and resources',\n\n /** Label for studio's which are up to date */\n 'help-resources.up-to-date': 'Up to date',\n\n /** Version text */\n 'help-resources.version': 'v{{version}}',\n /**Incoming references inspector title */\n 'incoming-references.title': 'Incoming references',\n\n /** Text for button to cancel an ongoing upload */\n 'input.files.common.cancel-upload': 'Cancel',\n /** Text for menuitem upload button default asset source */\n 'input.files.common.upload-placeholder.file-input-button.default-source.badge': 'Default',\n /** Text for file input button in upload placeholder */\n 'input.files.common.upload-placeholder.file-input-button.text': 'Upload',\n /** Uploading <FileName/> */\n 'input.files.common.upload-progress': 'Uploading <FileName/>',\n /** The referenced document cannot be opened, because the URL failed to be resolved */\n 'input.reference.document-cannot-be-opened.failed-to-resolve-url':\n 'This document cannot be opened (unable to resolve URL to Studio)',\n /** Label for adding item after a specific array item */\n 'inputs.array.action.add-after': 'Add item after',\n /** Label for adding item before a specific array item */\n 'inputs.array.action.add-before': 'Add item before',\n /** Label for adding array item action when the schema allows for only one schema type */\n 'inputs.array.action.add-item': 'Add item',\n /**\n * Label for adding one array item action when the schema allows for multiple schema types,\n * eg. will prompt the user to select a type once triggered\n */\n 'inputs.array.action.add-item-select-type': 'Add item...',\n /** Label for copying an array item */\n 'inputs.array.action.copy': 'Copy',\n /** Array drag handle button tooltip */\n 'inputs.array.action.drag.tooltip': 'Drag to re-order',\n /** Label for duplicating an array item */\n 'inputs.array.action.duplicate': 'Duplicate',\n /** Label for editing the item of a specific type, eg \"Edit Person\" */\n 'inputs.array.action.edit': 'Edit {{itemTypeTitle}}',\n /** Tooltip text explaining why adding items is disabled when array max is reached */\n 'inputs.array.action.max-reached': 'Maximum items reached',\n /** Label for removing an array item action */\n 'inputs.array.action.remove': 'Remove',\n /** Label for removing action when an array item has an error */\n 'inputs.array.action.remove-invalid-item': 'Remove',\n /** Label for viewing the item of a specific type, eg \"View Person\" */\n 'inputs.array.action.view': 'View {{itemTypeTitle}}',\n /** Error description for the array item tooltip that explains that the current item can still be moved or deleted but not edited since the schema definition is not found */\n 'inputs.array.error.can-delete-but-no-edit-description':\n 'You can still move or delete this item, but it cannot be edited since the schema definition for its type is nowhere to be found.',\n /** Error label for toast when array could not resolve the initial value */\n 'inputs.array.error.cannot-resolve-initial-value-title':\n 'Unable to resolve initial value for type: {{schemaTypeTitle}}: {{errorMessage}}.',\n /** Error label for toast when trying to upload one array item of a type that cannot be converted to array */\n 'inputs.array.error.cannot-upload-unable-to-convert_one':\n \"The following item can't be uploaded because there's no known conversion from content type to array item:\",\n /** Error label for toast when trying to upload multiple array items of a type that cannot be converted to array */\n 'inputs.array.error.cannot-upload-unable-to-convert_other':\n \"The following items can't be uploaded because there's no known conversion from content types to array item:\",\n /** Error description for the array item tooltip that explains that the current type item is not valid for the list */\n 'inputs.array.error.current-schema-not-declare-description':\n 'The current schema does not declare items of type <code>{{typeName}}</code> as valid for this list. This could mean that the type has been removed as a valid item type, or that someone else has added it to their own local schema that is not yet deployed.',\n /** Error description to show how the item is being represented in the json format */\n 'inputs.array.error.json-representation-description': 'JSON representation of this item:',\n /** Error description for the array item tooltip that explains what the error means with more context */\n 'inputs.array.error.type-is-incompatible-prompt':\n 'Item of type <code>{{typeName}}</code> not valid for this list',\n /** Error title for when an item type within an array input is incompatible, used in the tooltip */\n 'inputs.array.error.type-is-incompatible-title': 'Why is this happening?',\n /** Error label for unexpected errors in the Array Input */\n 'inputs.array.error.unexpected-error': 'Unexpected Error: {{error}}',\n /** Label for the array insert menu all items filter */\n 'inputs.array.insert-menu.filter.all-items': 'All',\n /** Label for when the array insert menu search shows no items */\n 'inputs.array.insert-menu.search.no-results': 'No items found',\n /** Placeholder for the array insert menu search field */\n 'inputs.array.insert-menu.search.placeholder': 'Search',\n /** Tooltip for the array insert menu grid view toggle */\n 'inputs.array.insert-menu.toggle-grid-view.tooltip': 'Toggle grid view',\n /** Tooltip for the array insert menu list view toggle */\n 'inputs.array.insert-menu.toggle-list-view.tooltip': 'Toggle list view',\n /** Label for when the array input doesn't have any items */\n 'inputs.array.no-items-label': 'No items',\n /** Label for read only array fields */\n 'inputs.array.read-only-label': 'This field is read-only',\n /** Label for when the array input is resolving the initial value for the item */\n 'inputs.array.resolving-initial-value': 'Resolving initial value…',\n /** Tooltip content when boolean input is disabled */\n 'inputs.boolean.disabled': 'Disabled',\n /** Warning label when selected datetime is in the past */\n 'inputs.dateTime.past-date-warning': 'Select a date in the future.',\n /** Placeholder value for datetime input */\n 'inputs.datetime.placeholder': 'e.g. {{example}}',\n /** Acessibility label for button to open file options menu */\n 'inputs.file.actions-menu.file-options.aria-label': 'Open file options menu',\n /** Unknown member kind: `{{kind}}` */\n 'inputs.file.error.unknown-member-kind': 'Unknown member kind: {{kind}}',\n /** The value of this field is not a valid file. Resetting this field will let you choose a new file. */\n 'inputs.file.invalid-file-warning.description':\n 'The value of this field is not a valid file. Resetting this field will let you choose a new file.',\n /** Reset value */\n 'inputs.file.invalid-file-warning.reset-button.text': 'Reset value',\n /** Invalid file value */\n 'inputs.file.invalid-file-warning.title': 'Invalid file value',\n /** The upload could not be completed at this time. */\n 'inputs.file.upload-failed.description': 'The upload could not be completed at this time.',\n /** Upload failed */\n 'inputs.file.upload-failed.title': 'Upload failed',\n /** Private access policy badge label */\n 'inputs.files.common.access-policy.private.label': 'Private asset',\n /** Private access policy badge tooltip */\n 'inputs.files.common.access-policy.private.tooltip': 'CDN access limited to signed URLs',\n /** Clear field */\n 'inputs.files.common.actions-menu.clear-field.label': 'Clear field',\n /** Copy URL */\n 'inputs.files.common.actions-menu.copy-url.label': 'Copy URL',\n /** Download */\n 'inputs.files.common.actions-menu.download.label': 'Download',\n /** The URL is copied to the clipboard */\n 'inputs.files.common.actions-menu.notification.url-copied': 'The URL is copied to the clipboard',\n /** Open in source */\n 'inputs.files.common.actions-menu.open-in-source.label': 'Open in {{sourceName}}',\n /** Replace */\n 'inputs.files.common.actions-menu.replace.label': 'Replace',\n /** Upload */\n 'inputs.files.common.actions-menu.upload.label': 'Upload',\n /** Drop to upload */\n 'inputs.files.common.drop-message.drop-to-upload': 'Drop to upload',\n /** Drop to upload `{{count}}` file */\n 'inputs.files.common.drop-message.drop-to-upload-multi_one': 'Drop to upload {{count}} file',\n /** Drop to upload `{{count}}` files */\n 'inputs.files.common.drop-message.drop-to-upload-multi_other': 'Drop to upload {{count}} files',\n /** Can't upload this file here */\n 'inputs.files.common.drop-message.drop-to-upload.no-accepted-file-message_one':\n \"Can't upload this file here\",\n /** Can't upload any of these files here */\n 'inputs.files.common.drop-message.drop-to-upload.no-accepted-file-message_other':\n \"Can't upload any of these files here\",\n /** `{{count}}` file can't be uploaded here */\n 'inputs.files.common.drop-message.drop-to-upload.rejected-file-message_one':\n \"{{count}} file can't be uploaded here\",\n /** `{{count}}` files can't be uploaded here */\n 'inputs.files.common.drop-message.drop-to-upload.rejected-file-message_other':\n \"{{count}} files can't be uploaded here\",\n /** Cannot upload `{{count}}` files */\n 'inputs.files.common.placeholder.cannot-upload-some-files_one': 'Cannot upload file',\n 'inputs.files.common.placeholder.cannot-upload-some-files_other': 'Cannot upload {{count}} files',\n /** Drag or paste type here */\n 'inputs.files.common.placeholder.drag-or-paste-to-upload_file': 'Drag or paste file here',\n /** Drag or paste image here */\n 'inputs.files.common.placeholder.drag-or-paste-to-upload_image': 'Drag or paste image here',\n /** Drop to upload file */\n 'inputs.files.common.placeholder.drop-to-upload_file': 'Drop to upload file',\n /** Drop to upload image */\n 'inputs.files.common.placeholder.drop-to-upload_image': 'Drop to upload image',\n /** Read only */\n 'inputs.files.common.placeholder.read-only': 'Read only',\n /** Select asset source destination for files to upload */\n 'inputs.files.common.placeholder.select-asset-source-upload-destination': 'Upload files to:',\n /** Can't upload files here */\n 'inputs.files.common.placeholder.upload-not-supported': \"Can't upload files here\",\n /** Clear upload */\n 'inputs.files.common.stale-upload-warning.clear': 'Clear upload',\n /** An upload has made no progress for at least `{{staleThresholdMinutes}}` minutes and likely got interrupted. You can safely clear the incomplete upload and try uploading again. */\n 'inputs.files.common.stale-upload-warning.description':\n 'An upload has made no progress for at least {{staleThresholdMinutes}} minutes and likely got interrupted. You can safely clear the incomplete upload and try uploading again.',\n /** Incomplete upload */\n 'inputs.files.common.stale-upload-warning.title': 'Incomplete upload',\n /** Select file */\n 'inputs.files.select-dialog.title': 'Select file for \"{{targetTitle}}\"',\n /** Tooltip text for action to crop image */\n 'inputs.image.actions-menu.crop-image-tooltip': 'Crop image',\n /** Accessibility label for button to open image edit dialog */\n 'inputs.image.actions-menu.edit-details.aria-label': 'Open image edit dialog',\n /** Accessibility label for button to open image options menu */\n 'inputs.image.actions-menu.options.aria-label': 'Open image options menu',\n /** Cannot upload this file here */\n 'inputs.image.drag-overlay.cannot-upload-here': 'Cannot upload this file here',\n /** Drop image to upload */\n 'inputs.image.drag-overlay.drop-to-upload-image': 'Drop image to upload',\n /** This field is read only */\n 'inputs.image.drag-overlay.this-field-is-read-only': 'This field is read only',\n /** Image could not be loaded due to possible access restrictions */\n 'inputs.image.error.possible-access-restriction':\n 'Could not load image. This may be due to access restrictions.',\n /** Unknown member kind: `{{kind}}` */\n 'inputs.image.error.unknown-member-kind': 'Unknown member kind: {{kind}}',\n /** Edit hotspot and crop */\n 'inputs.image.hotspot-dialog.title': 'Edit hotspot and crop',\n /** The value of this field is not a valid image. Resetting this field will let you choose a new image. */\n 'inputs.image.invalid-image-warning.description':\n 'The value of this field is not a valid image. Resetting this field will let you choose a new image.',\n /** Reset value */\n 'inputs.image.invalid-image-warning.reset-button.text': 'Reset value',\n /** Invalid image value */\n 'inputs.image.invalid-image-warning.title': 'Invalid image value',\n /** Preview of uploaded image */\n 'inputs.image.preview-uploaded-image': 'Preview of uploaded image',\n /** Select image */\n 'inputs.image.select-dialog.title': 'Select image for \"{{targetTitle}}\"',\n /** The upload could not be completed at this time. */\n 'inputs.image.upload-error.description': 'The upload could not be completed at this time.',\n /** Upload failed */\n 'inputs.image.upload-error.title': 'Upload failed',\n /** Adjust the rectangle to crop image. Adjust the circle to specify the area that should always be visible. */\n 'inputs.imagetool.description':\n 'Adjust the rectangle to crop image. Adjust the circle to specify the area that should always be visible.',\n /** Error: `{{errorMessage}}` */\n 'inputs.imagetool.load-error': 'Error: {{errorMessage}}',\n /** Hotspot & Crop */\n 'inputs.imagetool.title': 'Hotspot & Crop',\n /** Warnings displayed to developers when using the crop/hotspot tool on vector images, notifying them that crops/hotspot are not respected when serving the image in vector format. For the crop/hotspot to apply, images must be served in a raster format such as JPG or PNG, by appending eg `fm=jpg` to the image url, or calling `format('jpg')` if using `@sanity/image-url` */\n 'inputs.imagetool.vector-warning.developer-info': `The Asset Pipeline does not support hotspot and crop for vector formats. To enable hotspot & crop, output this image to any of the supported raster formats. For example: <code>fm=jpg</code> to the <ImageUrlDocumentationLink>image URL</ImageUrlDocumentationLink> or call <code>.format('png')</code> with <ImageUrlPackageDocumentationLink>@sanity/image-url</ImageUrlPackageDocumentationLink>.`,\n /** See developer info */\n 'inputs.imagetool.vector-warning.expand-developer-info': 'See developer info',\n /** Gotcha: Serving vector images with hotspot and crop from the Sanity Image API */\n 'inputs.imagetool.vector-warning.title':\n \"Warning: Hotspot and crop might not be applied to this image where it's presented.\",\n /** Convert to `{{targetType}}` */\n 'inputs.invalid-value.convert-button.text': 'Convert to {{targetType}}',\n /** The current value (<code>`{{actualType}}`</code>) */\n 'inputs.invalid-value.current-type': 'The current value (<code>{{actualType}}</code>)',\n /** The property value is stored as a value type that does not match the expected type. */\n 'inputs.invalid-value.description':\n 'The property value is stored as a value type that does not match the expected type.',\n /** The value of this property must be of type <code>`{{validType}}`</code> according to the schema. */\n 'inputs.invalid-value.details.description':\n 'The value of this property must be of type <code>{{validType}}</code> according to the schema.',\n /** Only the following types are valid here according to schema: */\n 'inputs.invalid-value.details.multi-type-description':\n 'Only the following types are valid here according to schema:',\n /** Mismatching value types typically occur when the schema has recently been changed. */\n 'inputs.invalid-value.details.possible-reason':\n 'Mismatching value types typically occur when the schema has recently been changed.',\n /** Developer info */\n 'inputs.invalid-value.details.title': 'Developer info',\n /** -- Invalid Value Input -- */\n /** Reset value */\n 'inputs.invalid-value.reset-button.text': 'Reset value',\n /** Invalid property value */\n 'inputs.invalid-value.title': 'Invalid property value',\n /** Title for the \"All fields\" field group */\n 'inputs.object.field-group-tabs.all-fields-title': 'All fields',\n /** Aria label for the \"Field groups\" select control on smaller screens */\n 'inputs.object.field-group-tabs.aria-label': 'Field groups',\n /** Text shown in field group select for a group with error validation */\n 'inputs.object.field-group-tabs.validation-error': 'error',\n /** Text shown in field group select for a group with info validation */\n 'inputs.object.field-group-tabs.validation-info': 'info',\n /** Text shown in field group select for a group with warning validation */\n 'inputs.object.field-group-tabs.validation-warning': 'warning',\n /** Read-only field description */\n 'inputs.object.unknown-fields.read-only.description':\n 'This field is <strong>read only</strong> according to the document’s schema and cannot be unset. If you want to be able to unset this in Studio, make sure you remove the <code>readOnly</code> field from the enclosing type in the schema.',\n /** Fallback description shown when the unknown reference preview cannot be loaded */\n 'inputs.object.unknown-fields.reference.preview.unavailable':\n 'Unable to load preview for reference \"{{documentId}}\".',\n /** Remove field */\n 'inputs.object.unknown-fields.remove-field-button.text': 'Remove field',\n /** Encountered `{{count}}` fields that are not defined in the schema. */\n 'inputs.object.unknown-fields.warning.description_one':\n 'Encountered a field that is not defined in the schema.',\n 'inputs.object.unknown-fields.warning.description_other':\n 'Encountered {{count}} fields that are not defined in the schema.',\n /** Detailed description of unknown field warning */\n 'inputs.object.unknown-fields.warning.details.description_one':\n 'This field is not defined in the schema, which could mean that the field definition has been removed or that someone else has added it to their own local project and have not deployed their changes yet.',\n 'inputs.object.unknown-fields.warning.details.description_other':\n 'These fields are not defined in the document’s schema, which could mean that the field definitions have been removed or that someone else has added them to their own local project and have not deployed their changes yet.',\n /** Developer info */\n 'inputs.object.unknown-fields.warning.details.title': 'Developer info',\n /** Unknown field found */\n 'inputs.object.unknown-fields.warning.title_one': 'Unknown field found',\n 'inputs.object.unknown-fields.warning.title_other': 'Unknown fields found',\n /** Collapse the editor to save screen space */\n 'inputs.portable-text.action.collapse-editor': 'Collapse editor',\n /** Aria label for action to edit an existing annotation */\n 'inputs.portable-text.action.edit-annotation-aria-label': 'Edit annotation',\n /** Expand the editor to give more editing space */\n 'inputs.portable-text.action.expand-editor': 'Expand editor',\n /** Label label for action to insert a block of a given type (`{{typeName}}`) */\n 'inputs.portable-text.action.insert-block': 'Insert {{typeName}}',\n /** Accessibility label for action to insert a block of a given type (`{{typeName}}`) */\n 'inputs.portable-text.action.insert-block-aria-label': 'Insert {{typeName}} (block)',\n /** Label for action to insert an inline object of a given type (`{{typeName}}`) */\n 'inputs.portable-text.action.insert-inline-object': 'Insert {{typeName}}',\n /** Accessibility label for action to insert an inline object of a given type (`{{typeName}}`) */\n 'inputs.portable-text.action.insert-inline-object-aria-label': 'Insert {{typeName}} (inline)',\n /** Aria label for action to remove an annotation */\n 'inputs.portable-text.action.remove-annotation-aria-label': 'Remove annotation',\n /** Label for activate on focus with context of click and not focused */\n 'inputs.portable-text.activate-on-focus-message_click': 'Click to activate',\n /** Label for activate on focus with context of click and focused */\n 'inputs.portable-text.activate-on-focus-message_click-focused':\n 'Click or press space to activate',\n /** Label for activate on focus with context of tap and not focused */\n 'inputs.portable-text.activate-on-focus-message_tap': 'Tap to activate',\n /** Aria label for the annotation object */\n 'inputs.portable-text.annotation-aria-label': 'Annotation object',\n /** Title for dialog that allows editing an annotation */\n 'inputs.portable-text.annotation-editor.title': 'Edit {{schemaType}}',\n /** Title of the default \"link\" annotation */\n 'inputs.portable-text.annotation.link': 'Link',\n /** Aria label for the block object */\n 'inputs.portable-text.block.aria-label': 'Block object',\n /** Label for action to edit a block item, in the case where it is editable */\n 'inputs.portable-text.block.edit': 'Edit',\n /** Accessibility label for the button that opens the actions menu on blocks */\n 'inputs.portable-text.block.open-menu-aria-label': 'Open menu',\n /** Label for action to open a reference, in the case of block-level reference types */\n 'inputs.portable-text.block.open-reference': 'Open reference',\n /** Label for action to remove a block item */\n 'inputs.portable-text.block.remove': 'Remove',\n /** Label for action to view a block item, in the case where it is read-only and thus cannot be edited */\n 'inputs.portable-text.block.view': 'View',\n /** Title of the \"code\" decorator */\n 'inputs.portable-text.decorator.code': 'Code',\n /** Title of the \"em\" (emphasis) decorator */\n 'inputs.portable-text.decorator.emphasis': 'Italic',\n /** Title of the \"strike-through\" decorator */\n 'inputs.portable-text.decorator.strike-through': 'Strike',\n /** Title of the \"strong\" decorator */\n 'inputs.portable-text.decorator.strong': 'Strong',\n /** Title of the \"underline\" decorator */\n 'inputs.portable-text.decorator.underline': 'Underline',\n /** Placeholder text for when the editor is empty */\n 'inputs.portable-text.empty-placeholder': 'Empty',\n /** Aria label for the block object */\n 'inputs.portable-text.inline-block.aria-label': 'Inline object',\n /** Label for action to edit an inline object item */\n 'inputs.portable-text.inline-object.edit': 'Edit object',\n /** Aria label for icon for action to edit an inline object item */\n 'inputs.portable-text.inline-object.edit-aria-label': 'Edit object',\n /** Label for action to remove an inline object item */\n 'inputs.portable-text.inline-object.remove': 'Remove object',\n /** Aria label for icon for action to remove an inline object item */\n 'inputs.portable-text.inline-object.remove-aria-label': 'Remove object',\n /** Disclaimer text shown on invalid Portable Text value, when an action is available to unblock the user, but it is not guaranteed to be safe */\n 'inputs.portable-text.invalid-value.action-disclaimer':\n 'NOTE: It’s generally safe to perform the action above, but if you are in doubt, get in touch with those responsible for configuring your studio.',\n /** Action presented when the Portable Text field value is invalid, when block with key `{{key}}` has a child with key `{{childKey}}` of type `{{childType}}` which is not allowed by the schema definition */\n 'inputs.portable-text.invalid-value.disallowed-child-type.action': 'Remove the object',\n /** Text explaining that the Portable Text field value is invalid, when block with key `{{key}}` has a child with key `{{childKey}}` of type `{{childType}}` which is not allowed by the schema definition */\n 'inputs.portable-text.invalid-value.disallowed-child-type.description':\n 'Child with key {{childKey}} of block with key <code>{{key}}</code> is of type <code>{{childType}}</code>, which is not allowed by the schema.',\n /** Action presented when the Portable Text field value is invalid, when child with key `{{key}}` has a type (`{{typeName}}`) that is not an allowed block type for this field */\n 'inputs.portable-text.invalid-value.disallowed-type.action': 'Remove the block',\n /** Text explaining that the Portable Text field value is invalid, when child with key `{{key}}` has a type (`{{typeName}}`) that is not an allowed block type for this field */\n 'inputs.portable-text.invalid-value.disallowed-type.description':\n 'Block with key <code>{{key}}</code> is of type <code>{{typeName}}</code>, which is not allowed by the schema.',\n /** Action presented when the Portable Text field value is invalid, when block with key `{{key}}` contains no children */\n 'inputs.portable-text.invalid-value.empty-children.action': 'Insert empty text span',\n /** Text explaining that the Portable Text field value is invalid, when block with key `{{key}}` contains no children */\n 'inputs.portable-text.invalid-value.empty-children.description':\n 'Text block with key <code>{{key}}</code> has no text spans.',\n /** Label for the button to ignore invalid values in the Portable Text editor */\n 'inputs.portable-text.invalid-value.ignore-button.text': 'Ignore',\n /** Action presented when the Portable Text field value is invalid, when child with key `{{key}}` has a `_type` property that is set to `block`, but the block type defined in schema has a different name (`{{expectedTypeName}}`) */\n 'inputs.portable-text.invalid-value.incorrect-block-type.action':\n 'Use type <code>{{expectedTypeName}}</code>',\n /** Text explaining that the Portable Text field value is invalid, when child with key `{{key}}` has a `_type` property that is set to `block`, but the block type defined in schema has a different name (`{{expectedTypeName}}`) */\n 'inputs.portable-text.invalid-value.incorrect-block-type.description':\n 'Block with key <code>{{key}}</code> has an invalid type name. According to the schema, it should be <code>{{expectedTypeName}}</code>.',\n /** Action presented when the Portable Text field value is invalid, when block with key `{{key}}` has a span with key `{{childKey}}` that has a missing or invalid `text` property */\n 'inputs.portable-text.invalid-value.invalid-span-text.action': 'Set empty text value',\n /** Text explaining that the Portable Text field value is invalid, when block with key `{{key}}` has a span with key `{{childKey}}` that has a missing or invalid `text` property */\n 'inputs.portable-text.invalid-value.invalid-span-text.description':\n 'Span with key {{childKey}} of block with key <code>{{key}}</code> has a missing or invalid <code>text</code> property.',\n /** Action presented when the Portable Text field value is invalid, when child with key `{{key}}` is missing a `_type` property, but seems to be a block of type `{{expectedTypeName}}` */\n 'inputs.portable-text.invalid-value.missing-block-type.action':\n 'Use type <code>{{expectedTypeName}}</code>',\n /** Text explaining that the Portable Text field value is invalid, when child with key `{{key}}` is missing a `_type` property, but seems to be a block of type `{{expectedTypeName}}` */\n 'inputs.portable-text.invalid-value.missing-block-type.description':\n 'Block with key <code>{{key}}</code> is missing a type name. According to the schema, it should be <code>{{expectedTypeName}}</code>.',\n /** Action presented when the Portable Text field value is invalid, when block with key `{{key}}` has a child at `{{index}}` which is missing `_key` property */\n 'inputs.portable-text.invalid-value.missing-child-key.action': 'Assign random key',\n /** Text explaining that the Portable Text field value is invalid, when block with key `{{key}}` has a child at `{{index}}` which is missing `_key` property */\n 'inputs.portable-text.invalid-value.missing-child-key.description':\n 'Child at index <code>{{index}}</code> of block with key <code>{{key}}</code> is missing <code>_key</code> property.',\n /** Action presented when the Portable Text field value is invalid, when block with key `{{key}}` has a child with key `{{childKey}}` which is missing a `_type` property */\n 'inputs.portable-text.invalid-value.missing-child-type.action': 'Remove the object',\n /** Text explaining that the Portable Text field value is invalid, when block with key `{{key}}` has a child with key `{{childKey}}` which is missing a `_type` property */\n 'inputs.portable-text.invalid-value.missing-child-type.description':\n 'Child with key {{childKey}} of block with key <code>{{key}}</code> is missing <code>_type</code> property.',\n /** Action presented when the Portable Text field value is invalid, when child at `{{index}}` is missing the required `_key` property */\n 'inputs.portable-text.invalid-value.missing-key.action': 'Assign random key',\n /** Text explaining that the Portable Text field value is invalid, when child at `{{index}}` is missing the required `_key` property */\n 'inputs.portable-text.invalid-value.missing-key.description':\n 'Block at index <code>{{index}}</code> is missing required <code>_key</code> property.',\n /** Action presented when the Portable Text field value is invalid, when child with key `{{key}}` has a missing or invalid `children` property */\n 'inputs.portable-text.invalid-value.missing-or-invalid-children.action': 'Remove the block',\n /** Text explaining that the Portable Text field value is invalid, when child with key `{{key}}` has a missing or invalid `children` property */\n 'inputs.portable-text.invalid-value.missing-or-invalid-children.description':\n 'Text block with key <code>{{key}}</code> has an invalid or missing `children` property.',\n /** Action presented when the Portable Text field value is invalid, when child with key `{{key}}` has a missing or invalid `markDefs` property */\n 'inputs.portable-text.invalid-value.missing-or-invalid-markdefs.action': 'Add property',\n /** Text explaining that the Portable Text field value is invalid, when child with key `{{key}}` has a missing or invalid `markDefs` property */\n 'inputs.portable-text.invalid-value.missing-or-invalid-markdefs.description':\n 'Text block with key <code>{{key}}</code> has an invalid or missing `markDefs` property.',\n /** Action presented when the Portable Text field value is invalid, when child with key `{{key}}` is missing a `_type` property */\n 'inputs.portable-text.invalid-value.missing-type.action': 'Remove the block',\n /** Text explaining that the Portable Text field value is invalid, when child with key `{{key}}` is missing a `_type` property */\n 'inputs.portable-text.invalid-value.missing-type.description':\n 'Block with key <code>{{key}}</code> is missing a type name.',\n /** Action presented when the Portable Text field value is invalid, when block with key `{{key}}` contains a non-object child at index `{{index}}` */\n 'inputs.portable-text.invalid-value.non-object-child.action': 'Remove the item',\n /** Text explaining that the Portable Text field value is invalid, when block with key `{{key}}` contains a non-object child at index `{{index}}` */\n 'inputs.portable-text.invalid-value.non-object-child.description':\n 'Child at index <code>{{index}}</code> of block with key <code>{{key}}</code> is not an object.',\n /** Action presented when the Portable Text field value is invalid, when the Portable Text field is not an array, or the array is empty */\n 'inputs.portable-text.invalid-value.not-an-array.action': 'Unset the value',\n /** Text explaining that the Portable Text field value is invalid, when the Portable Text field is not an array, or the array is empty */\n 'inputs.portable-text.invalid-value.not-an-array.description':\n 'Value must be an array of Portable Text blocks, or undefined.',\n /** Action presented when the Portable Text field value is invalid, when child at `{{index}}` is not an object */\n 'inputs.portable-text.invalid-value.not-an-object.action': 'Remove item',\n /** Text explaining that the Portable Text field value is invalid, when child at `{{index}}` is not an object */\n 'inputs.portable-text.invalid-value.not-an-object.description':\n 'Item at <code>{{index}}</code> is not an object,.',\n /** Action presented when the Portable Text field value is invalid, when block with key `{{key}}` contains marks (`{{orphanedMarks}}`) that are not supported by the current schema */\n 'inputs.portable-text.invalid-value.orphaned-marks.action': 'Remove disallowed marks',\n /** Text explaining that the Portable Text field value is invalid, when block with key `{{key}}` contains marks (`{{orphanedMarks}}`) that are not supported by the current schema */\n 'inputs.portable-text.invalid-value.orphaned-marks.description':\n 'Text block with key <code>{{key}}</code> contains marks <code>({{orphanedMarks, list}})</code> that are not allowed by the schema.',\n /** Title for the alert indicating that the Portable Text field has an invalid value */\n 'inputs.portable-text.invalid-value.title': 'Invalid Portable Text value',\n /** Title of \"bulleted\" list type */\n 'inputs.portable-text.list-type.bullet': 'Bulleted list',\n /** Title of numbered list type */\n 'inputs.portable-text.list-type.number': 'Numbered list',\n /** Title of the \"h1\" block style */\n 'inputs.portable-text.style.h1': 'Heading 1',\n /** Title of the \"h2\" block style */\n 'inputs.portable-text.style.h2': 'Heading 2',\n /** Title of the \"h3\" block style */\n 'inputs.portable-text.style.h3': 'Heading 3',\n /** Title of the \"h4\" block style */\n 'inputs.portable-text.style.h4': 'Heading 4',\n /** Title of the \"h5\" block style */\n 'inputs.portable-text.style.h5': 'Heading 5',\n /** Title of the \"h6\" block style */\n 'inputs.portable-text.style.h6': 'Heading 6',\n /** Title shown when multiple blocks of varying styles is selected */\n 'inputs.portable-text.style.multiple': 'Multiple',\n /** Title of fallback when no style is given for a block */\n 'inputs.portable-text.style.none': 'No style',\n /** Title of the \"normal\" block style */\n 'inputs.portable-text.style.normal': 'Normal',\n /** Title of the \"quote\" block style */\n 'inputs.portable-text.style.quote': 'Quote',\n /** Label for the table lane that appends a column */\n 'inputs.portable-text.table.add-column': 'Add column at end',\n /** Label for the table lane that appends a row */\n 'inputs.portable-text.table.add-row': 'Add row at end',\n /** Aria label for a table column's drag/select handle */\n 'inputs.portable-text.table.column-handle': 'Column handle',\n /** Label for the trash chip that deletes the selected column */\n 'inputs.portable-text.table.delete-column': 'Delete column',\n /** Label for the trash chip that deletes the selected row */\n 'inputs.portable-text.table.delete-row': 'Delete row',\n /** Label for the table menu item that deletes the table */\n 'inputs.portable-text.table.delete-table': 'Delete table',\n /** Label for the table menu's header row toggle */\n 'inputs.portable-text.table.header-row': 'Header row',\n /** Aria label for the dots that insert a row or column at a boundary */\n 'inputs.portable-text.table.insert-here': 'Insert here',\n /** Aria label for the table menu button */\n 'inputs.portable-text.table.menu-aria-label': 'Table options',\n /** Aria label for a table row's drag/select handle */\n 'inputs.portable-text.table.row-handle': 'Row handle',\n /** Label for the table menu item that selects the whole table */\n 'inputs.portable-text.table.select-table': 'Select table',\n /** Label for action to clear the current value of the reference field */\n 'inputs.reference.action.clear': 'Clear',\n /** Label for action to copy the current item (used within arrays) */\n 'inputs.reference.action.copy': 'Copy',\n /** Label for action to create a new document from the reference input */\n 'inputs.reference.action.create-new-document': 'Create',\n /** Label for action to create a new document from the reference input, when there are multiple templates or document types to choose from */\n 'inputs.reference.action.create-new-document-select': 'Create…',\n /** Label for action to duplicate the current item to a new item (used within arrays) */\n 'inputs.reference.action.duplicate': 'Duplicate',\n /** Label for action that opens the referenced document in a new tab */\n 'inputs.reference.action.open-in-new-tab': 'Open in new tab',\n /** Label for action to remove the reference from an array */\n 'inputs.reference.action.remove': 'Remove',\n /** Label for action to replace the current value of the field */\n 'inputs.reference.action.replace': 'Replace',\n /** Label for action to cancel a previously initiated replace action */\n 'inputs.reference.action.replace-cancel': 'Cancel replace',\n /** The cross-dataset reference field currently has a reference, but the feature has been disabled since it was created. This explains what can/cannot be done in its current state. */\n 'inputs.reference.cross-dataset.feature-disabled-actions':\n \"You can still clear this field's existing reference, but it cannot be changed to a different document as long as the feature is disabled.\",\n /** A cross-dataset reference field exists but the feature has been disabled. A <DocumentationLink> component is available. */\n 'inputs.reference.cross-dataset.feature-disabled-description':\n 'This feature has been disabled. Read how to enable it in <DocumentationLink>the documentation</DocumentationLink>.',\n /** Title for a warning telling the user that the current project does not have the \"cross dataset references\" feature */\n 'inputs.reference.cross-dataset.feature-unavailable-title':\n 'Unavailable feature: Cross dataset reference',\n /** The cross-dataset reference points to a document with an invalid type */\n 'inputs.reference.cross-dataset.invalid-type':\n 'The referenced document is of invalid type ({{typeName}}) <JsonValue/>',\n /** The referenced document will open in a new tab (due to external studio) */\n 'inputs.reference.document-opens-in-new-tab': 'This document opens in a new tab',\n /** Error title for when the document is unavailable (for any possible reason) */\n 'inputs.reference.error.document-unavailable-title': 'Document unavailable',\n /** Error title for when the referenced document failed to be loaded */\n 'inputs.reference.error.failed-to-load-document-title': 'Failed to load referenced document',\n /** Error title for when the reference search returned a document that is not an allowed type for the field */\n 'inputs.reference.error.invalid-search-result-type-title':\n 'Search returned a type that\\'s not valid for this reference: \"{{returnedType}}\"',\n /** Error description for when the document referenced is not one of the types declared as allowed target types in schema */\n 'inputs.reference.error.invalid-type-description':\n 'Referenced document (<code>{{documentId}}</code>) is of type <code>{{actualType}}</code>. According to the schema, referenced documents can only be of type <AllowedTypes/>.',\n /** Error title for when the document referenced is not one of the types declared as allowed target types in schema */\n 'inputs.reference.error.invalid-type-title': 'Document of invalid type',\n /** Error description for when the user does not have permissions to read the referenced document */\n 'inputs.reference.error.missing-read-permissions-description':\n 'The referenced document could not be accessed due to insufficient permissions',\n /** Error title for when the user does not have permissions to read the referenced document */\n 'inputs.reference.error.missing-read-permissions-title': 'Insufficient permissions',\n /** Error description for when the current reference value points to a document that does not exist (on weak references) */\n 'inputs.reference.error.nonexistent-document-description':\n 'The referenced document does not exist (ID: <code>{{documentId}}</code>). You can either remove the reference or replace it with another document.',\n /** Error title for when the current reference value points to a document that does not exist (on weak references) */\n 'inputs.reference.error.nonexistent-document-title': 'Not found',\n /** Label for button that clears the reference when it points to a document that does not exist (on weak references) */\n 'inputs.reference.error.nonexistent-document.clear-button-label': 'Clear',\n /** Error title for when the search for a reference failed. Note that the message sent by the backend may not be localized. */\n 'inputs.reference.error.search-failed-title': 'Reference search failed',\n /** Label for when the GDR points to an invalid type */\n 'inputs.reference.global.invalid-type':\n 'The referenced document is of invalid type ({{typeName}})',\n /** Alternative text for the image shown in cross-dataset reference input */\n 'inputs.reference.image-preview-alt-text': 'Image preview of referenced document',\n /** Description for alert shown when a reference in a live-edit document is marked as being weak, the referenced document exists, AND the reference is supposed to be have been strengthened on publish */\n 'inputs.reference.incomplete-reference.finalize-action-description':\n '<strong>{{referencedDocument}}</strong> is published and this reference should now be finalized.',\n /** Title for alert shown when a reference in a live-edit document is marked as being weak, the referenced document exists, AND the reference is supposed to be have been strengthened on publish */\n 'inputs.reference.incomplete-reference.finalize-action-title': 'Finalize reference',\n /** Description for alert shown when a reference in a live-edit document points to a document that exists and has been published, but the reference is still marked as weak */\n 'inputs.reference.incomplete-reference.strengthen-action-description':\n '<strong>{{referencedDocument}}</strong> is published and this reference should now be converted to a strong reference.',\n /** Title for alert shown when a reference in a live-edit document points to a document that exists and has been published, but the reference is still marked as weak */\n 'inputs.reference.incomplete-reference.strengthen-action-title': 'Convert to strong reference',\n /** Label for button that triggers the action that strengthen a reference */\n 'inputs.reference.incomplete-reference.strengthen-button-label': 'Convert to strong reference',\n /** Label for button that triggers a retry attempt for reference metadata */\n 'inputs.reference.metadata-error.retry-button-label': 'Retry',\n /** Title for alert shown when reference metadata fails to be loaded */\n 'inputs.reference.metadata-error.title': 'Unable to load reference metadata',\n /** Message shown when no documents were found that matched the given search string */\n 'inputs.reference.no-results-for-query': 'No results for <strong>“{{searchTerm}}”</strong>',\n /** Text for tooltip showing when a document was edited, using relative time (eg \"how long ago was it edited?\") */\n 'inputs.reference.preview.edited-at-time': 'Edited <RelativeTime/>',\n /** Accessibility label for icon indicating that document does _not_ have any unpublished changes */\n 'inputs.reference.preview.has-no-unpublished-changes-aria-label': 'No unpublished edits',\n /** Accessibility label for icon indicating that document has unpublished changes */\n 'inputs.reference.preview.has-unpublished-changes-aria-label': 'Edited',\n /** Accessibility label for icon indicating that document does _not_ have a published version */\n 'inputs.reference.preview.is-not-published-aria-label': 'Not published',\n /** Accessibility label for icon indicating that document has a published version */\n 'inputs.reference.preview.is-published-aria-label': 'Published',\n /** Text for tooltip indicating that a document has no unpublished edits */\n 'inputs.reference.preview.no-unpublished-edits': 'No unpublished edits',\n /** Text for tooltip indicating that a document has not yet been published */\n 'inputs.reference.preview.not-published': 'Not published',\n /** Text for tooltip showing when a document was published, using relative time (eg \"how long ago was it published?\") */\n 'inputs.reference.preview.published-at-time': 'Published <RelativeTime/>',\n /** The referenced document no longer exist and might have been deleted (for weak references) */\n 'inputs.reference.referenced-document-does-not-exist':\n 'The referenced document no longer exist and might have been deleted (document ID: <code>{{documentId}}</code>).',\n /** The referenced document could not be displayed to the user because of insufficient permissions */\n 'inputs.reference.referenced-document-insufficient-permissions':\n 'The referenced document could not be accessed due to insufficient permissions',\n /** Label for when the reference input is resolving the initial value for an item */\n 'inputs.reference.resolving-initial-value': 'Resolving initial value…',\n /** Placeholder shown in a reference input with no current value */\n 'inputs.reference.search-placeholder': 'Type to search',\n /** Explanation of the consequences of leaving the reference as strong instead of weak */\n 'inputs.reference.strength-mismatch.is-strong-consquences':\n 'It will not be possible to delete the reference document without first removing this reference or converting it to weak.',\n /** Description for alert shown when a reference is supposed to be weak, but the actual value is strong */\n 'inputs.reference.strength-mismatch.is-strong-description':\n 'This reference is <em>strong</em>, but according to the current schema it should be <em>weak</em>.',\n /** Explanation of the consequences of leaving the reference as weak instead of strong */\n 'inputs.reference.strength-mismatch.is-weak-consquences':\n 'This makes it possible to delete the referenced document without first deleting this reference, leaving this field referencing a nonexisting document.',\n /** Description for alert shown when a reference is supposed to be strong, but the actual value is weak */\n 'inputs.reference.strength-mismatch.is-weak-description':\n 'This reference is <em>weak</em>, but according to the current schema it should be <em>strong</em>.',\n /** Label for button that triggers the action that strengthens a reference on strength mismatch */\n 'inputs.reference.strength-mismatch.strengthen-button-label': 'Convert to strong reference',\n /** Title for alert shown when a reference is supposed to be weak/strong, but the actual value is the opposite of what it is supposed to be */\n 'inputs.reference.strength-mismatch.title': 'Reference strength mismatch',\n /** Label for button that triggers the action that weakens a reference on strength mismatch */\n 'inputs.reference.strength-mismatch.weaken-button-label': 'Convert to weak reference',\n /** Label for action to clear the current value of the select field */\n 'inputs.select.action.clear': 'Clear',\n /** Action message for generating the slug */\n 'inputs.slug.action.generate': 'Generate',\n /** Loading message for when the input is actively generating a slug */\n 'inputs.slug.action.generating': 'Generating…',\n /** Error message for when the source to generate a slug from is missing */\n 'inputs.slug.error.missing-source':\n 'Source is missing. Check source on type {{schemaType}} in schema',\n /** Placeholder for an empty tag input */\n 'inputs.tags.placeholder': 'Enter tag and press ENTER…',\n /** Placeholder for an empty tag input on touch devices */\n 'inputs.tags.placeholder_touch': 'Enter tag…',\n /** Convert to `{{targetType}}` */\n 'inputs.untyped-value.convert-button.text': 'Convert to {{targetType}}',\n /** Encountered an object value without a <code>_type</code> property. */\n 'inputs.untyped-value.description':\n 'Encountered an object value without a <code>_type</code> property.',\n /** Either remove the <code>name</code> property of the object declaration, or set <code>_type</code> property on items. */\n 'inputs.untyped-value.details.description':\n 'Either remove the <code>name</code> property of the object declaration, or set <code>_type</code> property on items.',\n /** Current value (<code>object</code>): */\n 'inputs.untyped-value.details.json-dump-prefix': 'Current value (<code>object</code>):',\n /** The following types are valid here according to schema: */\n 'inputs.untyped-value.details.multi-type-description':\n 'The following types are valid here according to schema:',\n /** Developer info */\n 'inputs.untyped-value.details.title': 'Developer info',\n /** Property value missing <code>_type</code> */\n 'inputs.untyped-value.title': 'Property value missing <code>_type</code>',\n /** Unset value */\n 'inputs.untyped-value.unset-item-button.text': 'Unset value',\n /** Select video */\n 'inputs.video.select-dialog.title': 'Select video for \"{{targetTitle}}\"',\n /** The fallback explanation if no context is provided */\n 'insufficient-permissions-message.not-authorized-explanation':\n 'You do not have permission to access this feature.',\n /** The explanation when unable to create any document at all */\n 'insufficient-permissions-message.not-authorized-explanation_create-any-document':\n 'You do not have permission to create a document.',\n /** The explanation when unable to create a particular document */\n 'insufficient-permissions-message.not-authorized-explanation_create-document':\n 'You do not have permission to create this document.',\n /** The explanation when unable to create a particular type of document */\n 'insufficient-permissions-message.not-authorized-explanation_create-document-type':\n 'You do not have permission to create this kind of document.',\n /** The explanation when unable to create a new reference in a document */\n 'insufficient-permissions-message.not-authorized-explanation_create-new-reference':\n 'You do not have permission to create a new reference.',\n\n /** The explanation when unable to delete a particular document */\n 'insufficient-permissions-message.not-authorized-explanation_delete-document':\n 'You do not have permission to delete this document.',\n /** The explanation when unable to delete a schedule on scheduled publishing */\n 'insufficient-permissions-message.not-authorized-explanation_delete-schedules':\n 'You do not have permission to delete schedules.',\n\n /** The explanation when unable to discard changes in a particular document */\n 'insufficient-permissions-message.not-authorized-explanation_discard-changes':\n 'You do not have permission to discard changes in this document.',\n /** The explanation when unable to duplicate a particular document */\n 'insufficient-permissions-message.not-authorized-explanation_duplicate-document':\n 'You do not have permission to duplicate this document.',\n /** The explanation when unable to edit a schedule on scheduled publishing */\n 'insufficient-permissions-message.not-authorized-explanation_edit-schedules':\n 'You do not have permission to edit schedules.',\n\n /** The explanation when unable to execute a schedule on scheduled publishing */\n 'insufficient-permissions-message.not-authorized-explanation_execute-schedules':\n 'You do not have permission to execute schedules.',\n /** The explanation when unable to publish a particular document */\n 'insufficient-permissions-message.not-authorized-explanation_publish-document':\n 'You do not have permission to publish this document.',\n /** The explanation when unable to unpublish a particular document */\n 'insufficient-permissions-message.not-authorized-explanation_unpublish-document':\n 'You do not have permission to unpublish this document.',\n /** Appears after the not-authorized message. Lists the current roles. */\n 'insufficient-permissions-message.roles': 'Your roles: <Roles/>',\n /** The title for the insufficient permissions message component */\n 'insufficient-permissions-message.title': 'Insufficient permissions',\n\n /** Body of the logged-out banner shown above the login form for an unknown reason */\n 'login.logged-out.generic': 'Your session is no longer valid. Please sign in again.',\n /** Body of the logged-out banner shown above the login form when the session expired */\n 'login.logged-out.session-expired': 'Your session expired. Please sign in again.',\n /** Title of the banner shown above the login form after the studio logs the user out */\n 'login.logged-out.title': \"You've been logged out\",\n\n /** Unexpected error: `{{error}}` */\n 'member-field-error.unexpected-error': 'Unexpected error: {{error}}',\n\n /** Text shown in warning when browser is using HTTP1 to communicate with the Sanity API */\n 'network-check.slow-protocol-warning.description':\n 'Your browser is using an outdated HTTP protocol to communicate with Sanity. This may result in substantially degraded performance.',\n /** Text for link that takes the user to the Sanity documentation to learn more about the HTTP1 issue */\n 'network-check.slow-protocol-warning.learn-more-button.text': 'Learn more',\n /** Text for link that takes the user to the Sanity documentation to learn more about the HTTP1 issue */\n 'network-check.slow-protocol-warning.snooze-button.text': \"Don't show again for this session\",\n /** Title text for the warning dialog when browser is using HTTP1 to communicate with the Sanity API */\n 'network-check.slow-protocol-warning.title': \"You've got your brakes on\",\n\n /** Button label for \"Create new document\" button */\n 'new-document.button': 'Create',\n /**\n * Tooltip message displayed when hovering/activating the \"Create new document\" action,\n * when there are templates/types available for creation\n */\n 'new-document.create-new-document-label': 'New document…',\n /** Placeholder for the \"filter\" input within the new document menu */\n 'new-document.filter-placeholder': 'Search document types',\n /** Loading indicator text within the new document menu */\n 'new-document.loading': 'Loading…',\n /** Accessibility label for the list displaying options in the new document menu */\n 'new-document.new-document-aria-label': 'New document',\n /** Message for when there are no document type options in the new document menu */\n 'new-document.no-document-types-found': 'No document types found',\n /**\n * Tooltip message displayed when hovering/activating the \"Create new document\" action,\n * when there are no templates/types to create from\n */\n 'new-document.no-document-types-label': 'No document types',\n /** Message for when no results are found for a specific search query in the new document menu */\n 'new-document.no-results': 'No results for <strong>{{searchQuery}}</strong>',\n /** Aria label for the button that opens the \"Create new document\" popover/dialog */\n 'new-document.open-dialog-aria-label': 'Create new document',\n /** Title for \"Create new document\" dialog */\n 'new-document.title': 'Create new document',\n /** @deprecated Label for button that will make the browser reload when users' studio version is out-of-date */\n 'package-version.new-package-available.reload-button': 'Push to reload',\n /** @deprecated Title of the alert for studio users when packages in their studio are out-of-date */\n 'package-version.new-package-available.title': 'Sanity Studio is ready to update!',\n /** Label for action to invite members to the current studio project */\n 'presence.action.manage-members': 'Invite members',\n /** Accessibility label for presence menu button */\n 'presence.aria-label': 'Global presence',\n /** Message description for when no one else is currently present */\n 'presence.no-one-else-description': 'Invite people to the project to see their online status.',\n /** Message title for when no one else is currently present */\n 'presence.no-one-else-title': 'No one else is here',\n /** Message for when a user is not in a document (displayed in the global presence menu) */\n 'presence.not-in-a-document': 'Not in a document',\n /** Tooltip content text for presence menu button */\n 'presence.tooltip-content': 'Who is here',\n\n /** Fallback title shown when a preview does not provide a title */\n 'preview.default.title-fallback': 'Untitled',\n /** Fallback preview value for types that have \"no value\" (eg null, undefined) */\n 'preview.fallback.no-value': '(no value)',\n /** Alternative text for image being shown while image is being uploaded, in previews */\n 'preview.image.file-is-being-uploaded.alt-text': 'The image currently being uploaded',\n\n /* Relative time, just now */\n 'relative-time.just-now': 'just now',\n\n /** Action message to add document to new release */\n 'release.action.add-to-new-release': 'Add to release',\n /** Action message to add document to release */\n 'release.action.add-to-release': 'Add to {{title}}',\n /** Tooltip message for document that is already added to release */\n 'release.action.already-exists-in-release': 'Document already exists in release',\n /** Action message for when document is already in release */\n 'release.action.already-in-release': 'Already in release {{title}}',\n /** Action message for when you click to view all versions you can copy the current document to */\n 'release.action.copy-to': 'Copy version to',\n /** Action message for creating new releases */\n 'release.action.create-new': 'New release',\n /** Description for toast when version creation failed */\n 'release.action.create-version.failure': 'Failed to create version',\n /** Action message for deleting a scheduled publish */\n 'release.action.delete-schedule': 'Delete schedule',\n /** Action message for when document is already in release */\n 'release.action.discard-version': 'Discard version',\n /** Description for toast when version discarding failed */\n 'release.action.discard-version.failure': 'Failed to discard version',\n /** Action message for editing the schedule of a scheduled publish */\n 'release.action.edit-schedule': 'Edit schedule',\n /** Action message for when a new release is created off an existing version, draft or published document */\n 'release.action.new-release': 'New release',\n /** Explanation provided when releases can't be created because the workspace release limit has been reached */\n 'release.action.new-release.limit-reached': 'This workspace is limited to {{count}} release',\n 'release.action.new-release.limit-reached_other':\n 'This workspace is limited to {{count}} releases',\n /** Tooltip message for not having permissions for creating new releases */\n 'release.action.permission.error': 'You do not have permission to perform this action',\n /** Action message for running a scheduled draft immediately */\n 'release.action.publish-now': 'Publish now',\n /** Error message description for when a version is reverted from being unpublished */\n 'release.action.revert-unpublish-version.failure.description':\n 'Please try again or check your connection. The document is still going to be unpublished upon release.',\n /** Error message title for when a version is reverted from being unpublished */\n 'release.action.revert-unpublish-version.failure.title':\n 'Failed to revert from setting to unpublish on release.',\n /** Action message description for when a version is reverted from being unpublished */\n 'release.action.revert-unpublish-version.success.description': 'You can now edit this version.',\n /** Action message title for when a version is reverted from being unpublished */\n 'release.action.revert-unpublish-version.success.title':\n 'Successfully reverted from setting to unpublish on release.',\n /** Action message for scheduling a paused draft */\n 'release.action.schedule-publish': 'Schedule publish',\n /** Error message for when a version is set to be unpublished */\n 'release.action.unpublish-version.failure': 'Failed to set version to be unpublished on release',\n /** Action message for when a version is set to be unpublished successfully */\n 'release.action.unpublish-version.success':\n 'Successfully set <strong>{{title}}</strong> to be unpublished on release',\n /** Action message for when the view release is pressed */\n 'release.action.view-release': 'View release',\n /** Action message for when the view scheduled drafts is pressed */\n 'release.action.view-scheduled-drafts': 'View scheduled drafts',\n /** Label for banner when release is scheduled */\n 'release.banner.scheduled-for-publishing-on': 'Scheduled to be published on {{date}}',\n\n /** Label for button to show other variants in the document perspective list */\n 'release.chip.button.other-variants_one': '+{{count}} variant',\n /** Label for button to show other variants in the document perspective list */\n 'release.chip.button.other-variants_other': '+{{count}} variants',\n\n /** Label for button to show other versions in the document perspective list*/\n 'release.chip.button.other-versions_one': '+{{count}} version',\n /** Label for button to show other versions in the document perspective list */\n 'release.chip.button.other-versions_other': '+{{count}} versions',\n /** Label for Draft chip in document header */\n 'release.chip.draft': 'Draft',\n /** Label for Draft chip in global header */\n 'release.chip.global.drafts': 'Drafts',\n /** Label for Published chip in document header */\n 'release.chip.published': 'Published',\n /** Label for tooltip in chip when document is in an archived release */\n 'release.chip.tooltip.archived': 'This release is archived and cannot be edited.',\n /** Label for tooltip in chip with the created date */\n 'release.chip.tooltip.created-date': 'Created {{date}}',\n /** Label for tooltip in draft chip when it's a live edit document */\n 'release.chip.tooltip.draft-disabled.live-edit':\n 'This document is in live edit mode, drafts are disabled',\n /** Label for tooltip in chip with the lasted edited date */\n 'release.chip.tooltip.edited-date': 'Edited {{date}}',\n /** Label for tooltip in chip when document is intended for a future release that hasn't been scheduled */\n 'release.chip.tooltip.intended-for-date': 'Intended for {{date}}',\n /** Label for tooltip in chip when there is no recent draft edits */\n 'release.chip.tooltip.no-edits': 'No edits',\n /** Label for tooltip in chip when document isn't published */\n 'release.chip.tooltip.not-published': 'Not published',\n 'release.chip.tooltip.other-variants_one': 'One variant',\n 'release.chip.tooltip.other-variants_other': '{{count}} variants',\n\n 'release.chip.tooltip.other-versions_one': 'One additional version outside of releases',\n 'release.chip.tooltip.other-versions_other': '{{count}} additional versions outside of releases',\n /** Label for tooltip in chip with the published date */\n 'release.chip.tooltip.published-date': 'Published {{date}}',\n /** Label for tooltip in chip when document is in a release that has been scheduled */\n 'release.chip.tooltip.scheduled-for-date': 'Scheduled for {{date}}',\n /** Label for tooltip in scheduled chip without a known date */\n 'release.chip.tooltip.unknown-date': 'Unknown date',\n /** Label for tooltip on deleted release */\n 'release.deleted-tooltip': 'This release has been deleted',\n /** Title for copying version to a new release dialog */\n 'release.dialog.copy-to-release.title': 'Copy version to new release',\n /** Title for action create a release */\n 'release.dialog.create.confirm': 'Create release',\n /** Title for creating releases dialog */\n 'release.dialog.create.title': 'New release',\n /** Body text when deleting scheduled draft and draft is already up to date */\n 'release.dialog.delete-schedule-draft.body-already-current':\n 'Delete this scheduled draft? Your draft is already up to date.',\n /** Body text when deleting scheduled draft and changes will be saved to draft */\n 'release.dialog.delete-schedule-draft.body-will-save-to-draft':\n 'Delete this scheduled draft? Your changes will be saved to draft.',\n /** Body text when deleting scheduled draft with checkbox shown for user choice */\n 'release.dialog.delete-schedule-draft.body-with-choice': 'Delete this scheduled draft?',\n /** Confirm button text for deleting a scheduled draft */\n 'release.dialog.delete-schedule-draft.confirm': 'Yes, delete schedule',\n /** Checkbox label for copying scheduled draft to draft before deletion */\n 'release.dialog.delete-schedule-draft.copy-checkbox':\n 'Keep my scheduled changes by copying them to draft (recommended)',\n /** Explanation text shown when scheduled draft has different changes than current draft */\n 'release.dialog.delete-schedule-draft.different-changes-explanation':\n 'Your scheduled draft has different changes than your current draft.',\n /** Header for the dialog confirming deletion of a scheduled draft */\n 'release.dialog.delete-schedule-draft.header': 'Delete scheduled draft',\n /** Body text for change schedule dialog */\n 'release.dialog.edit-schedule.body': 'Select a new date and time for the scheduled publish.',\n /** Confirm button text for change schedule dialog */\n 'release.dialog.edit-schedule.confirm': 'Update schedule',\n /** Header for change schedule dialog */\n 'release.dialog.edit-schedule.header': 'Change schedule',\n /** Body text for the dialog confirming running a scheduled draft immediately */\n 'release.dialog.publish-scheduled-draft.body':\n 'Are you sure you want to publish this scheduled draft immediately?',\n /** Confirm button text for running a scheduled draft immediately */\n 'release.dialog.publish-scheduled-draft.confirm': 'Yes, run now',\n /** Header for the dialog confirming running a scheduled draft immediately */\n 'release.dialog.publish-scheduled-draft.header': 'Publish draft now',\n /** Label for description in tooltip to explain release types */\n 'release.dialog.tooltip.description':\n \"This is only for planning, previews and hints about whether documents conflict. Setting a time here will not schedule your release. You'll still need to run or schedule the release once all documents are ready.\",\n /** Label for noting that a release time is not final */\n 'release.dialog.tooltip.note': 'You can always change it later.',\n /** Title for tooltip to explain release time */\n 'release.dialog.tooltip.title': 'Approximate time of release',\n /** The placeholder text when the release doesn't have a description */\n 'release.form.placeholder-describe-release': 'Describe the release…',\n /** Tooltip for button to hide release visibility */\n 'release.layer.hide': 'Hide release',\n /** Label for the release menu */\n 'release.menu.label': 'Release menu',\n /** Menu item label for scheduled drafts */\n 'release.menu.scheduled-drafts': 'View Scheduled Drafts',\n /** Tooltip for the release menu */\n 'release.menu.tooltip': 'Actions',\n /** Menu item label for viewing content releases */\n 'release.menu.view-releases': 'View Content Releases',\n /** Label for draft perspective in navbar */\n 'release.navbar.drafts': 'Drafts',\n /** Label for published releases in navbar */\n 'release.navbar.published': 'Published',\n /** Tooltip for releases navigation in navbar */\n 'release.navbar.tooltip': 'View scheduling',\n /** The placeholder text when the release doesn't have a title */\n 'release.placeholder-untitled-release': 'Untitled release',\n /** Description for warning that the published schedule time is in the past */\n 'release.schedule-dialog.publish-date-in-past-warning': 'Schedule for a future time and date.',\n /** Label for date picker when scheduling a release */\n 'release.schedule-dialog.select-publish-date-label': 'Publish on',\n /** The toast description that will be shown when the user has a release perspective which is now archived\n * @deprecated – no longer needed\n * */\n 'release.toast.archived-release.description': 'This release has been unpinned',\n /** The toast title that will be shown when the user has a release perspective which is now archived\n * @deprecated – no longer needed\n * */\n 'release.toast.archived-release.title': \"The '{{title}}' release was archived\",\n /** The toast title that will be shown the creating a release fails */\n 'release.toast.create-release-error.title': 'Failed to create release',\n /** Error toast for deleting a scheduled draft */\n 'release.toast.delete-schedule-draft.error':\n 'Failed to delete the scheduled draft document <strong>{{title}}</strong>: {{error}}',\n /** Success toast for deleting a scheduled draft */\n 'release.toast.delete-schedule-draft.success':\n 'The scheduled draft document <strong>{{title}}</strong> has been deleted.',\n /** The toast title that will be shown when the user has a release perspective which is now deleted\n * @deprecated – no longer needed\n * */\n 'release.toast.not-found-release.title': \"The '{{title}}' release could not be found\",\n /** Error toast for pausing a scheduled draft */\n 'release.toast.pause-scheduled-draft.error':\n 'Failed to pause the scheduled draft document <strong>{{title}}</strong>: {{error}}',\n /** Error toast for running a scheduled publish immediately */\n 'release.toast.publish-scheduled-draft.error':\n 'Failed to publish the scheduled draft document <strong>{{title}}</strong>: {{error}}',\n /** Success toast for running a scheduled publish immediately */\n 'release.toast.publish-scheduled-draft.success':\n 'The scheduled draft document <strong>{{title}}</strong> has been published.',\n /** The toast description that will be shown when the user has a release perspective which is now published\n * @deprecated – no longer needed\n **/\n 'release.toast.published-release.description': 'This release has been unpinned',\n /** The toast title that will be shown when the user has a release perspective which is now deleted\n * @deprecated – no longer needed\n **/\n 'release.toast.published-release.title': \"The '{{title}}' release was published\",\n /** Error toast for rescheduling a draft */\n 'release.toast.reschedule-scheduled-draft.error':\n 'Failed to reschedule the scheduled draft document <strong>{{title}}</strong>: {{error}}',\n /** Success toast for rescheduling a draft */\n 'release.toast.reschedule-scheduled-draft.success':\n 'The scheduled draft document <strong>{{title}}</strong> has been rescheduled.',\n /** Error toast for scheduling a paused draft */\n 'release.toast.schedule-publish.error': 'Failed to schedule draft: {{error}}',\n /** Success toast for scheduling a paused draft */\n 'release.toast.schedule-publish.success': 'Scheduled draft successfully',\n /** The toast title that will be shown when the user has a scheduled draft perspective which is now published\n * @deprecated – no longer needed\n * */\n 'release.toast.scheduled-draft-published.title': 'The scheduled draft was published',\n /** Label for when a version of a document has already been added to the release */\n 'release.tooltip.already-added': 'A version of this document has already been added',\n /** Label for when a release is scheduled / scheduling and a user can't add a document version to it */\n 'release.tooltip.locked': 'This release has been scheduled. Unschedule it to add more documents.',\n /** Label for the release type 'as soon as possible' */\n 'release.type.asap': 'As soon as possible',\n /** Label for the release type 'at time', meaning it's a release with a scheduled date */\n 'release.type.scheduled': 'At time',\n /** Label for the release type 'undecided' */\n 'release.type.undecided': 'Undecided',\n /** Tooltip for the dropdown to show all versions of document */\n 'release.version-list.tooltip': 'See all document versions',\n\n /** Button text for contacting support in the releases misconfiguration dialog */\n 'releases.upsell.misconfiguration.contact-support': 'Contact Support',\n /** Header for the releases misconfiguration dialog */\n 'releases.upsell.misconfiguration.header': 'Content releases configuration issue',\n /** Message shown in the releases misconfiguration dialog */\n 'releases.upsell.misconfiguration.message':\n 'Content releases are enabled for your project, but there appears to be a configuration issue with your release limits. Please contact support to have your content releases properly configured.',\n\n /** Confirm button text for the schedule publish dialog */\n 'schedule-publish-dialog.confirm': 'Schedule',\n /** Description for the schedule publish dialog */\n 'schedule-publish-dialog.description': 'Select when this document should be published.',\n /** Header for the schedule publish dialog */\n 'schedule-publish-dialog.header': 'Schedule draft for publishing',\n\n /** Title for a scheduled draft release */\n 'scheduled-drafts.release.title': 'Scheduled publish',\n\n /** Accessibility label to open search action when the search would go fullscreen (eg on narrower screens) */\n 'search.action-open-aria-label': 'Open search',\n /** Action label for adding a search filter */\n 'search.action.add-filter': 'Add filter',\n /** Action label for clearing search filters */\n 'search.action.clear-filters': 'Clear filters',\n /** Label for action to clear recent searches */\n 'search.action.clear-recent-searches': 'Clear recent searches',\n /** Accessibility label for action to clear all currently applied document type filters */\n 'search.action.clear-type-filters-aria-label': 'Clear checked filters',\n /** Label for action to clear all currently applied document type filters */\n 'search.action.clear-type-filters-label': 'Clear',\n /** Accessibility label for when the search is full screen (on narrow screens) and you want to close the search */\n 'search.action.close-search-aria-label': 'Close search',\n /** Accessibility label for filtering by document type */\n 'search.action.filter-by-document-type-aria-label': 'Filter by document type',\n /** Accessibility action label for removing an already applied search filter */\n 'search.action.remove-filter-aria-label': 'Remove filter',\n /**\n * Text displayed when either no document type(s) have been selected, or we need a fallback,\n * eg \"Search for all types\".\n */\n 'search.action.search-all-types': 'Search all documents',\n /**\n * Text displayed when we are able to determine one or more document types that will be used for\n * searching, and can fit within the space assigned by the design.\n */\n 'search.action.search-specific-types': 'Search for {{types, list}}',\n /**\n * Text displayed when we are able to determine one or more document types that will be used for\n * searching, but cannot list them all within the space assigned by the design, so we need an\n * additional \"and X more\" suffix. Allows using pluralization suffixes, eg `_one`, `_other` etc.\n */\n 'search.action.search-specific-types-truncated': 'Search for {{types, list}} +{{count}} more',\n /** Dialog title for action to select an asset of unknown type */\n 'search.action.select-asset': 'Select asset',\n /** Dialog title for action to select a file asset */\n 'search.action.select-asset_file': 'Select file',\n /** Dialog title for action to select an image asset */\n 'search.action.select-asset_image': 'Select image',\n /** Accessibility label for when the search is full screen (on narrow screens) and you want to hide filters */\n 'search.action.toggle-filters-aria-label_hide': 'Hide filters',\n /** Accessibility label for when the search is full screen (on narrow screens) and you want to show filters */\n 'search.action.toggle-filters-aria-label_show': 'Show filters',\n /** Label for when the search is full screen (on narrow screens) and you want to hide filters */\n 'search.action.toggle-filters-label_hide': 'Hide filters',\n /** Label for when the search is full screen (on narrow screens) and you want to show filters */\n 'search.action.toggle-filters-label_show': 'Show filters',\n\n /** Tooltip text for the global search button */\n 'search.button.tooltip': 'Search',\n\n /**\n * A list of provided types (use `list` formatter preferably).\n */\n 'search.document-type-list': '{{types, list}}',\n /**\n * In the context of a list of document types - no filtering selection has been done,\n * thus the default is \"all types\".\n */\n 'search.document-type-list-all-types': 'All types',\n /**\n * A list of provided types that has been truncated - more types are included but not displayed,\n * thus we need to indicate that there are more. Allows using pluralization suffixes,\n * eg `_one`, `_other` etc.\n */\n 'search.document-type-list-truncated': '{{types, list}} +{{count}} more',\n /** Accessibility label for list displaying the available document types */\n 'search.document-types-aria-label': 'Document types',\n /** Label for when no document types matching the filter are found */\n 'search.document-types-no-matches-found': 'No matches for {{filter}}',\n /** Description for error when a filter cannot be displayed, describes that you should check the schema */\n 'search.error.display-filter-description':\n 'This may indicate invalid options defined in your schema.',\n /** Title for error when a filter cannot be displayed (mainly a developer-oriented error) */\n 'search.error.display-filter-title': 'An error occurred whilst displaying this filter.',\n /** Description for error when no valid asset source is found, describes that you should check the the current studio config */\n 'search.error.no-valid-asset-source-check-config-description':\n \"Please ensure it's enabled in your studio configuration file.\",\n /** Description for error when no valid asset source is found, describes that only the default asset is supported */\n 'search.error.no-valid-asset-source-only-default-description':\n 'Currently, only the default asset source is supported.',\n /** Title for error when no valid asset sources found */\n 'search.error.no-valid-asset-source-title': 'No valid asset sources found.',\n /** Helpful description for when search returned an error that we are not able to describe in detail */\n 'search.error.unspecified-error-help-description': 'Please try again or check your connection',\n /** Title label for when search returned an error that we are not able to describe in detail */\n 'search.error.unspecified-error-title': 'Something went wrong while searching',\n /**\n * Label for \"All fields\", a label that appears above the list of available fields when filtering.\n * If one or more document type has been chosen as filter, this label is replaced with a group of\n * fields per selected document type\n */\n 'search.filter-all-fields-header': 'All fields',\n /** Label for the action of changing from one file to a different file in asset search filter */\n 'search.filter-asset-change_file': 'Change file',\n /** Label for the action of changing from one image to a different image in asset search filter */\n 'search.filter-asset-change_image': 'Change image',\n /** Label for the action of clearing the currently selected asset in an image/file filter */\n 'search.filter-asset-clear': 'Clear',\n /** Label for the action of selecting a file in asset search filter */\n 'search.filter-asset-select_file': 'Select file',\n /** Label for the action of selecting an image in asset search filter */\n 'search.filter-asset-select_image': 'Select image',\n /** Label for boolean filter - false */\n 'search.filter-boolean-false': 'False',\n /** Label for boolean filter - true */\n 'search.filter-boolean-true': 'True',\n /** Accessibility label for list that lets you filter fields by title, when adding a new filter in search */\n 'search.filter-by-title-aria-label': 'Filter by title',\n /** Accessibility label for date filter input */\n 'search.filter-date-aria-label': 'Date',\n /** Accessibility label for selecting end date on the date range search filter */\n 'search.filter-date-range-end-date-aria-label': 'End date',\n /** Accessibility label for selecting start date on the date range search filter */\n 'search.filter-date-range-start-date-aria-label': 'Start date',\n /** Accessibility label for selecting the unit (day/month/year) when adding \"X days ago\" search filter */\n 'search.filter-date-unit-aria-label': 'Select unit',\n /**\n * Label for \"Days\"/\"Months\"/\"Years\" when selecting it as unit in \"X days ago\" search filter.\n * Capitalized, as it would be listed in a dropdown.\n */\n 'search.filter-date-unit_days': 'Days',\n 'search.filter-date-unit_months': 'Months',\n 'search.filter-date-unit_years': 'Years',\n /** Accessibility label for the input value (days/months/years) when adding \"X days ago\" search filter */\n 'search.filter-date-value-aria-label': 'Unit value',\n /** Label for \"field description\" shown in tooltip when navigating list of possible fields to filter */\n 'search.filter-field-tooltip-description': 'Field description',\n /** Label for \"field name\" shown in tooltip when navigating list of possible fields to filter */\n 'search.filter-field-tooltip-name': 'Field name',\n /** Label for \"Used in document types\", a list of the document types a field appears in. Shown in tooltip when navigating list of possible fields to filter */\n 'search.filter-field-tooltip-used-in-document-types': 'Used in document types',\n /** Label for when no fields/filters are found for the given term */\n 'search.filter-no-matches-found': 'No matches for {{filter}}',\n /** Placeholder value for maximum numeric value filter */\n 'search.filter-number-max-value-placeholder': 'Max value',\n /** Placeholder value for minimum numeric value filter */\n 'search.filter-number-min-value-placeholder': 'Min value',\n /** Placeholder value for the number filter */\n 'search.filter-number-value-placeholder': 'Value',\n /** Placeholder for the \"Filter\" input, when narrowing possible fields/filters */\n 'search.filter-placeholder': 'Filter',\n /** Label for the action of clearing the currently selected document in a reference filter */\n 'search.filter-reference-clear': 'Clear',\n /**\n * Label for \"shared fields\", a label that appears above a list of fields that all filtered types\n * have in common, when adding a new filter. For instance, if \"book\" and \"employee\" both have a\n * \"title\" field, this field would be listed under \"shared fields\".\n * */\n 'search.filter-shared-fields-header': 'Shared fields',\n /** Placeholder value for the string filter */\n 'search.filter-string-value-placeholder': 'Value',\n /** Label/placeholder prompting user to select one of the predefined, allowed values for a string field */\n 'search.filter-string-value-select-predefined-value': 'Select…',\n /** Accessibility label for the \"Filters\" list, that is shown when using \"Add filter\" in search (singular) */\n 'search.filters-aria-label_one': 'Filter',\n /** Accessibility label for the \"Filters\" list, that is shown when using \"Add filter\" in search (plural) */\n 'search.filters-aria-label_other': 'Filters',\n /** Label for instructions on how to use the search - displayed when no recent searches are available */\n 'search.instructions': 'Use <ControlsIcon/> to refine your search',\n /** Helpful description for when no search results are found */\n 'search.no-results-help-description': 'Try another keyword or adjust your filters',\n /** Title label for when no search results are found */\n 'search.no-results-title': 'No results found',\n /**\n * Individual search operators.\n *\n * The `name` variant is the form we use when the user is building a query, and selecting from a\n * list of available operators for a field. Keep in mind that since the user knows what the field\n * represents, we do not need to contextualize too much, and that the user may not be a developer\n * eg prefer \"quantity is\" over \"array has length\". Additionally, (if applicable in language) use\n * lowercased names.\n *\n * The `description` variant is the form shown once the filter has enough information to apply,\n * and is shown in the list of applied filters. It is passed components that _should_ be used to\n * compose the filter string, and to format them correctly:\n *\n * `<Field/>` - eg \"Bird species\", \"Category\", \"Date of birth\"\n * `<Operator>operator text</Operator>` - eg \"has ≤\", \"includes\", \"is\"\n * `<Value>{{value}}</Value>` - eg \"Hawk\", \"Sparrow\", \"Eagle\"\n *\n * Where applicable, a `count` is passed, allowing you to pluralize where needed, by using\n * suffixes such as `_zero`, `_one`, `_other` etc.\n *\n * Prefer (reasonable) brevity since many filters may be applied. For instance:\n * `<Field/> has ≤ <Value/>` may be better than\n * `<Field/> has less than or equal to <Value/>`\n **/\n /* Array should have a count the given filter value */\n 'search.operator.array-count-equal.description_one':\n '<Field/> <Operator>has</Operator> <Value>{{count}} item</Value>',\n 'search.operator.array-count-equal.description_other':\n '<Field/> <Operator>has</Operator> <Value>{{count}} items</Value>',\n 'search.operator.array-count-equal.name': 'quantity is',\n /* Array should have a count greater than given filter value */\n 'search.operator.array-count-gt.description_one':\n '<Field/> <Operator>has ></Operator> <Value>{{count}} item</Value>',\n 'search.operator.array-count-gt.description_other':\n '<Field/> <Operator>has ></Operator> <Value>{{count}} items</Value>',\n 'search.operator.array-count-gt.name': 'quantity greater than',\n /* Array should have a count greater than or equal to the given filter value */\n 'search.operator.array-count-gte.description_one':\n '<Field/> <Operator>has ≥</Operator> <Value>{{count}} item</Value>',\n 'search.operator.array-count-gte.description_other':\n '<Field/> <Operator>has ≥</Operator> <Value>{{count}} items</Value>',\n 'search.operator.array-count-gte.name': 'quantity greater than or equal to',\n /* Array should have a count less than given filter value */\n 'search.operator.array-count-lt.description_one':\n '<Field/> <Operator>has <</Operator> <Value>{{count}} item</Value>',\n 'search.operator.array-count-lt.description_other':\n '<Field/> <Operator>has <</Operator> <Value>{{count}} items</Value>',\n 'search.operator.array-count-lt.name': 'quantity less than',\n /* Array should have a count less than or equal to the given filter value */\n 'search.operator.array-count-lte.description_one':\n '<Field/> <Operator>has ≤</Operator> <Value>{{count}} item</Value>',\n 'search.operator.array-count-lte.description_other':\n '<Field/> <Operator>has ≤</Operator> <Value>{{count}} items</Value>',\n 'search.operator.array-count-lte.name': 'quantity less than or equal to',\n /* Array should have a count that is not equal to the given filter value */\n 'search.operator.array-count-not-equal.description_one':\n '<Field/> <Operator>does not have</Operator> <Value>{{count}} item</Value>',\n 'search.operator.array-count-not-equal.description_other':\n '<Field/> <Operator>does not have</Operator> <Value>{{count}} items</Value>',\n 'search.operator.array-count-not-equal.name': 'quantity is not',\n /**\n * Array should have a count within the range of given filter values.\n * Gets passed `{{from}}` and `{{to}}` values.\n **/\n 'search.operator.array-count-range.description':\n '<Field/> <Operator>has between</Operator> <Value>{{from}} → {{to}} items</Value>',\n 'search.operator.array-count-range.name': 'quantity is between',\n /* Array should include the given value */\n 'search.operator.array-list-includes.description':\n '<Field/> <Operator>includes</Operator> <Value>{{value}}</Value>',\n 'search.operator.array-list-includes.name': 'includes',\n /* Array should not include the given value */\n 'search.operator.array-list-not-includes.description':\n '<Field/> <Operator>does not include</Operator> <Value>{{value}}</Value>',\n 'search.operator.array-list-not-includes.name': 'does not include',\n /* Array should include the given reference */\n 'search.operator.array-reference-includes.description':\n '<Field/> <Operator>includes</Operator> <Value>{{value}}</Value>',\n 'search.operator.array-reference-includes.name': 'includes',\n /* Array should not include the given reference */\n 'search.operator.array-reference-not-includes.description':\n '<Field/> <Operator>does not include</Operator> <Value>{{value}}</Value>',\n 'search.operator.array-reference-not-includes.name': 'does not include',\n /* Asset (file) should be the selected asset */\n 'search.operator.asset-file-equal.description':\n '<Field/> <Operator>is</Operator> <Value>{{value}}</Value>',\n 'search.operator.asset-file-equal.name': 'is',\n /* Asset (file) should not be the selected asset */\n 'search.operator.asset-file-not-equal.description':\n '<Field/> <Operator>is not</Operator> <Value>{{value}}</Value>',\n 'search.operator.asset-file-not-equal.name': 'is not',\n /* Asset (image) should be the selected asset */\n 'search.operator.asset-image-equal.description':\n '<Field/> <Operator>is</Operator> <Value>{{value}}</Value>',\n 'search.operator.asset-image-equal.name': 'is',\n /* Asset (image) should not be the selected asset */\n 'search.operator.asset-image-not-equal.description':\n '<Field/> <Operator>is not</Operator> <Value>{{value}}</Value>',\n 'search.operator.asset-image-not-equal.name': 'is not',\n /**\n * Boolean value should be the given filter value (true/false).\n * Context passed is `true` and `false`, allowing for more specific translations:\n * - `search.operator.boolean-equal.description_true`\n * - `search.operator.boolean-equal.description_false`\n */\n 'search.operator.boolean-equal.description':\n '<Field/> <Operator>is</Operator> <Value>{{value}}</Value>',\n 'search.operator.boolean-equal.name': 'is',\n /* Date should be after (later than) given filter value */\n 'search.operator.date-after.description':\n '<Field/> <Operator>is after</Operator> <Value>{{value}}</Value>',\n 'search.operator.date-after.name': 'after',\n /* Date should be before (earlier than) given filter value */\n 'search.operator.date-before.description':\n '<Field/> <Operator>is before</Operator> <Value>{{value}}</Value>',\n 'search.operator.date-before.name': 'before',\n /* Date should be the given filter value */\n 'search.operator.date-equal.description':\n '<Field/> <Operator>is</Operator> <Value>{{value}}</Value>',\n 'search.operator.date-equal.name': 'is',\n /* Date should be within the given filter value range (eg \"within the last X days\") */\n 'search.operator.date-last.description':\n '<Field/> <Operator>is in the last</Operator> <Value>{{value}}</Value>',\n 'search.operator.date-last.name': 'last',\n /* Date should not be the given filter value */\n 'search.operator.date-not-equal.description':\n '<Field/> <Operator>is not</Operator> <Value>{{value}}</Value>',\n 'search.operator.date-not-equal.name': 'is not',\n /* Date should be within the range of given filter values */\n 'search.operator.date-range.description': '<Field/> <Operator>is between</Operator> <Value/>',\n 'search.operator.date-range.name': 'is between',\n /* Date and time should be after (later than) given filter value */\n 'search.operator.date-time-after.description':\n '<Field/> <Operator>is after</Operator> <Value>{{value}}</Value>',\n 'search.operator.date-time-after.name': 'after',\n /* Date and time should be before (earlier than) given filter value */\n 'search.operator.date-time-before.description':\n '<Field/> <Operator>is before</Operator> <Value>{{value}}</Value>',\n 'search.operator.date-time-before.name': 'before',\n /* Date and time should be the given filter value */\n 'search.operator.date-time-equal.description':\n '<Field/> <Operator>is</Operator> <Value>{{value}}</Value>',\n 'search.operator.date-time-equal.name': 'is',\n /* Date and time should be within the given filter value range (eg \"within the last X days\") */\n 'search.operator.date-time-last.description':\n '<Field/> <Operator>is in the last</Operator> <Value>{{value}}</Value>',\n 'search.operator.date-time-last.name': 'last',\n /* Date and time should not be the given filter value */\n 'search.operator.date-time-not-equal.description':\n '<Field/> <Operator>is not</Operator> <Value>{{value}}</Value>',\n 'search.operator.date-time-not-equal.name': 'is not',\n /* Date and time should be within the range of given filter values */\n 'search.operator.date-time-range.description':\n '<Field/> <Operator>is between</Operator> <Value/>',\n 'search.operator.date-time-range.name': 'is between',\n /* Value should be defined */\n 'search.operator.defined.description':\n '<Field/> <Operator>is</Operator> <Value>not empty</Value>',\n 'search.operator.defined.name': 'not empty',\n /* Value should not be defined */\n 'search.operator.not-defined.description':\n '<Field/> <Operator>is</Operator> <Value>empty</Value>',\n 'search.operator.not-defined.name': 'empty',\n /* Number should be the given filter value */\n 'search.operator.number-equal.description':\n '<Field/> <Operator>is</Operator> <Value>{{value}}</Value>',\n 'search.operator.number-equal.name': 'is',\n /* Number should be greater than given filter value */\n 'search.operator.number-gt.description':\n '<Field/> <Operator>></Operator> <Value>{{value}}</Value>',\n 'search.operator.number-gt.name': 'greater than',\n /* Number should be greater than or the given filter value */\n 'search.operator.number-gte.description':\n '<Field/> <Operator>≥</Operator> <Value>{{value}}</Value>',\n 'search.operator.number-gte.name': 'greater than or equal to',\n /* Number should be less than given filter value */\n 'search.operator.number-lt.description':\n '<Field/> <Operator><</Operator> <Value>{{value}}</Value>',\n 'search.operator.number-lt.name': 'less than',\n /* Number should be less than or the given filter value */\n 'search.operator.number-lte.description':\n '<Field/> <Operator>≤</Operator> <Value>{{value}}</Value>',\n 'search.operator.number-lte.name': 'less than or equal to',\n /* Number should not be the given filter value */\n 'search.operator.number-not-equal.description':\n '<Field/> <Operator>is not</Operator> <Value>{{value}}</Value>',\n 'search.operator.number-not-equal.name': 'is not',\n /* Number should be within the range of given filter values */\n 'search.operator.number-range.description':\n '<Field/> <Operator>is between</Operator> <Value>{{from}} → {{to}}</Value>',\n 'search.operator.number-range.name': 'is between',\n /* Portable Text should contain the given filter value */\n 'search.operator.portable-text-contains.description':\n '<Field/> <Operator>contains</Operator> <Value>{{value}}</Value>',\n 'search.operator.portable-text-contains.name': 'contains',\n /* Portable Text should be the given filter value */\n 'search.operator.portable-text-equal.description':\n '<Field/> <Operator>is</Operator> <Value>{{value}}</Value>',\n 'search.operator.portable-text-equal.name': 'is',\n /* Portable Text should not contain the given filter value */\n 'search.operator.portable-text-not-contains.description':\n '<Field/> <Operator>does not contain</Operator> <Value>{{value}}</Value>',\n 'search.operator.portable-text-not-contains.name': 'does not contain',\n /* Portable Text should not be the given filter value */\n 'search.operator.portable-text-not-equal.description':\n '<Field/> <Operator>is not</Operator> <Value>{{value}}</Value>',\n 'search.operator.portable-text-not-equal.name': 'is not',\n /* References the given asset (file) */\n 'search.operator.reference-asset-file.description':\n '<Field/> <Operator>→</Operator> <Value>{{value}}</Value>',\n 'search.operator.reference-asset-file.name': 'file',\n /* References the given asset (image) */\n 'search.operator.reference-asset-image.description':\n '<Field/> <Operator>→</Operator> <Value>{{value}}</Value>',\n 'search.operator.reference-asset-image.name': 'image',\n /* References the given document */\n 'search.operator.reference-document.description':\n '<Field/> <Operator>→</Operator> <Value>{{value}}</Value>',\n 'search.operator.reference-document.name': 'document',\n /* Reference should be the given document */\n 'search.operator.reference-equal.description':\n '<Field/> <Operator>is</Operator> <Value>{{value}}</Value>',\n 'search.operator.reference-equal.name': 'is',\n /* Reference should not be the given document */\n 'search.operator.reference-not-equal.description':\n '<Field/> <Operator>is not</Operator> <Value>{{value}}</Value>',\n 'search.operator.reference-not-equal.name': 'is not',\n /* Slug contains the given value */\n 'search.operator.slug-contains.description':\n '<Field/> <Operator>contains</Operator> <Value>{{value}}</Value>',\n 'search.operator.slug-contains.name': 'contains',\n /* Slug equals the given filter value */\n 'search.operator.slug-equal.description':\n '<Field/> <Operator>is</Operator> <Value>{{value}}</Value>',\n 'search.operator.slug-equal.name': 'is',\n /* Slug does not contain the given value */\n 'search.operator.slug-not-contains.description':\n '<Field/> <Operator>does not contain</Operator> <Value>{{value}}</Value>',\n 'search.operator.slug-not-contains.name': 'does not contain',\n /* Slug does not equal the given filter value */\n 'search.operator.slug-not-equal.description':\n '<Field/> <Operator>is not</Operator> <Value>{{value}}</Value>',\n 'search.operator.slug-not-equal.name': 'is not',\n /* String contains the given filter value */\n 'search.operator.string-contains.description':\n '<Field/> <Operator>contains</Operator> <Value>{{value}}</Value>',\n 'search.operator.string-contains.name': 'contains',\n /* String equals the given filter value */\n 'search.operator.string-equal.description':\n '<Field/> <Operator>is</Operator> <Value>{{value}}</Value>',\n 'search.operator.string-equal.name': 'is',\n /* String equals one of the predefined allowed values */\n 'search.operator.string-list-equal.description':\n '<Field/> <Operator>is</Operator> <Value>{{value}}</Value>',\n 'search.operator.string-list-equal.name': 'is',\n /* String does not equal one of the predefined allowed values */\n 'search.operator.string-list-not-equal.description':\n '<Field/> <Operator>is not</Operator> <Value>{{value}}</Value>',\n 'search.operator.string-list-not-equal.name': 'is not',\n /* String does not contain the given filter value */\n 'search.operator.string-not-contains.description':\n '<Field/> <Operator>does not contain</Operator> <Value>{{value}}</Value>',\n 'search.operator.string-not-contains.name': 'does not contain',\n /* String does not equal the given filter value */\n 'search.operator.string-not-equal.description':\n '<Field/> <Operator>is not</Operator> <Value>{{value}}</Value>',\n 'search.operator.string-not-equal.name': 'is not',\n /** Label for the \"Best match\" search ordering type */\n 'search.ordering.best-match-label': 'Best match',\n /** Label for the \"Created: Oldest first\" search ordering type */\n 'search.ordering.created-ascending-label': 'Created: Oldest first',\n /** Label for the \"Created: Newest first\" search ordering type */\n 'search.ordering.created-descending-label': 'Created: Newest first',\n /** Label for the \"Updated: Oldest first\" search ordering type */\n 'search.ordering.updated-ascending-label': 'Updated: Oldest first',\n /** Label for the \"Updated: Newest first\" search ordering type */\n 'search.ordering.updated-descending-label': 'Updated: Newest first',\n /** Placeholder text for the global search input field */\n 'search.placeholder': 'Search',\n /** Accessibility label for the recent searches section, shown when no valid search terms has been given */\n 'search.recent-searches-aria-label': 'Recent searches',\n /** Label/heading shown for the recent searches section */\n 'search.recent-searches-label': 'Recent searches',\n /** Accessibility label for the search results section, shown when the user has typed valid terms */\n 'search.search-results-aria-label': 'Search results',\n /** Accessibility label for the navbar status button */\n 'status-button.aria-label': 'Configuration status',\n\n /* Time zone handling */\n 'time-zone.action.search-for-timezone-placeholder': 'Search for a city or time zone',\n /* Label for the local time zone button */\n 'time-zone.action.select-local-time-zone': 'Select local time zone',\n /* Dialog info for the time zone dialog */\n 'time-zone.dialog-info.content-releases':\n 'The selected time zone will change how dates are represented in content releases.',\n /* Dialog info for the time zone dialog */\n 'time-zone.dialog-info.input':\n 'The selected time zone will change how dates are represented only for this input in this document.',\n /* Dialog info for the time zone dialog */\n 'time-zone.dialog-info.scheduled-publishing':\n 'The selected time zone will change how dates are represented in schedules.',\n /* Label for the local time zone button */\n 'time-zone.local-time': 'local time',\n /* Label for the time zone button */\n 'time-zone.time-zone': 'Time zone',\n /* Tooltip content for the time zone dialog */\n 'time-zone.time-zone-tooltip-content-releases':\n 'Displaying releases in {{alternativeName}} GMT{{offset}}',\n /* Tooltip content for the time zone dialog */\n 'time-zone.time-zone-tooltip-input':\n 'Displaying <em>{{title}}</em> in {{alternativeName}} GMT{{offset}}',\n /* Tooltip content for the time zone dialog */\n 'time-zone.time-zone-tooltip-scheduled-publishing':\n 'Displaying schedules in {{alternativeName}} GMT{{offset}}',\n\n /** Title for the changes tooltip in the history inspector*/\n 'timeline.changes.title': 'Changes by',\n /** Description for error when the timeline for the given document can't be loaded */\n 'timeline.error.load-document-changes-description':\n 'Document history transactions have not been affected.',\n /** Title for error when the timeline for the given document can't be loaded */\n 'timeline.error.load-document-changes-title':\n 'An error occurred whilst retrieving document changes.',\n /** Description for error when the timeline for the given document can't be loaded */\n 'timeline.error.load-document-changes-version-description':\n 'Enable the events API through the Studio config to view document history.',\n /** Title for error when the timeline for the given version document can't be loaded */\n 'timeline.error.load-document-changes-version-title':\n 'Version documents history is only available through the Events API.',\n /** Error description for when the document doesn't have history */\n 'timeline.error.no-document-history-description':\n 'When changing the content of the document, the document versions will appear in this menu.',\n /** Error title for when the document doesn't have history */\n 'timeline.error.no-document-history-title': 'No document history',\n /** Error prompt when revision cannot be loaded */\n 'timeline.error.unable-to-load-revision': 'Unable to load revision',\n /** Label for when the timeline item is the latest in the history */\n 'timeline.latest': 'Latest',\n\n /** Label for latest revision for timeline menu dropdown */\n 'timeline.latest-revision': 'Latest revision',\n /**\n * Label for latest revision for timeline menu dropdown\n * @deprecated as of `v3.47.0` `timeline.latest-revision` should be used instead. Note: _usage_ of this key is deprecated, but Studios on `< v3.47.0` still require this key to be _defined_\n * */\n 'timeline.latest-version': 'Latest revision',\n /** The aria-label for the list of revisions in the timeline */\n 'timeline.list.aria-label': 'Document revisions',\n /** Label for loading history */\n 'timeline.loading-history': 'Loading history…',\n /* Label for when no previous since events are available*/\n 'timeline.no-previous-events': 'No previous events',\n /** Label shown in review changes timeline when a document has been created */\n 'timeline.operation.created': 'Created',\n /** Label shown in review changes timeline when a document was initially created */\n 'timeline.operation.created-initial': 'Created',\n /** Label shown in review changes timeline when a document was initially created, with a timestamp */\n 'timeline.operation.created-initial_timestamp': 'Created: {{timestamp, datetime}}',\n /** Label shown in review changes timeline when a document has been created, with a timestamp */\n 'timeline.operation.created_timestamp': 'Created: {{timestamp, datetime}}',\n /** Label shown in review changes timeline when a document has been deleted */\n 'timeline.operation.deleted': 'Deleted',\n /** Label shown in review changes timeline when a document has been deleted, with a timestamp */\n 'timeline.operation.deleted_timestamp': 'Deleted: {{timestamp, datetime}}',\n /** Label shown in review changes timeline when a draft document has been created*/\n 'timeline.operation.draft-created': 'Draft created',\n /** Label shown in review changes timeline when a draft document has been created, with a timestamp */\n 'timeline.operation.draft-created_timestamp': 'Draft created: {{timestamp, datetime}}',\n /** Label shown in review changes timeline when a draft has been discarded */\n 'timeline.operation.draft-discarded': 'Discarded draft',\n /** Label shown in review changes timeline when a draft has been discarded, with a timestamp */\n 'timeline.operation.draft-discarded_timestamp': 'Discarded draft: {{timestamp, datetime}}',\n /** Label shown in review changes timeline when a draft has been edited */\n 'timeline.operation.edited-draft': 'Edited',\n /** Label shown in review changes timeline when a draft has been edited, with a timestamp */\n 'timeline.operation.edited-draft_timestamp': 'Edited: {{timestamp, datetime}}',\n /** Label shown in review changes timeline when a document has been edited live */\n 'timeline.operation.edited-live': 'Live edited',\n /** Label shown in review changes timeline when a document has been edited live, with a timestamp */\n 'timeline.operation.edited-live_timestamp': 'Live edited: {{timestamp, datetime}}',\n /** Label shown in review changes timeline event when transactions have been deleted by retention policy */\n 'timeline.operation.history-cleared': 'Deleted by retention policy',\n /** Label shown in review changes timeline when a document was published */\n 'timeline.operation.published': 'Published',\n /** Label shown in review changes timeline when a document was published, with a timestamp */\n 'timeline.operation.published_timestamp': 'Published: {{timestamp, datetime}}',\n /** Label shown in review changes timeline when a document was unpublished */\n 'timeline.operation.unpublished': 'Unpublished',\n /** Label shown in review changes timeline when a document was unpublished, with a timestamp */\n 'timeline.operation.unpublished_timestamp': 'Unpublished: {{timestamp, datetime}}',\n\n /** Label shown in review changes timeline when a document version has been created */\n 'timeline.operation.version-created': 'Version created',\n /** Label shown in review changes timeline when a document version has been created, with a timestamp */\n 'timeline.operation.version-created_timestamp': 'Version created: {{timestamp, datetime}}',\n /** Label shown in review changes timeline when a document version has been discarded */\n 'timeline.operation.version-discarded': 'Version discarded',\n /** Label shown in review changes timeline when a document version has been discarded, with a timestamp */\n 'timeline.operation.version-discarded_timestamp': 'Version discarded: {{timestamp, datetime}}',\n /**\n * Label for determining since which version the changes for timeline menu dropdown are showing.\n * Receives the time label as a parameter (`timestamp`).\n */\n 'timeline.since': '{{timestamp, datetime}}',\n /** Label for missing change version for timeline menu dropdown are showing */\n 'timeline.since-version-missing': 'Since: unknown version',\n\n /** Aria label for the action buttons in the PTE toolbar */\n 'toolbar.portable-text.action-button-aria-label': '{{action}}',\n\n /** Accessibility label for the breadcrumb menu */\n 'tree-editing-dialog.breadcrumbs.menu': 'Breadcrumb menu',\n /** Title placeholder for search input in array of objects */\n 'tree-editing-dialog.search-placeholder': 'Search',\n /** Menu aria label for the search menu */\n 'tree-editing-dialog.search.menu-label': 'Search menu',\n /** Title label for when no search results are found on the tree of objects */\n 'tree-editing-dialog.search.no-results-title': 'No results found',\n /** Label to close the sidebar */\n 'tree-editing-dialog.sidebar.action.close': 'Close sidebar',\n /** Collapse label the menu item in the sidebar */\n 'tree-editing-dialog.sidebar.action.collapse': 'Collapse',\n /** Label to close the dialog */\n 'tree-editing-dialog.sidebar.action.done': 'Done',\n /** Exapnd label the menu item in the sidebar */\n 'tree-editing-dialog.sidebar.action.expand': 'Expand',\n /** Label to open the sidebar */\n 'tree-editing-dialog.sidebar.action.open': 'Open sidebar',\n /** Label for the button showed after trial ended */\n 'user-menu.action.free-trial-finished': 'Upgrade from free',\n /** Label for button showing the free trial days left */\n 'user-menu.action.free-trial_one': '{{count}} day left in trial',\n 'user-menu.action.free-trial_other': '{{count}} days left in trial',\n /** Label for action to invite members to the current sanity project */\n 'user-menu.action.invite-members': 'Invite members',\n /** Accessibility label for action to invite members to the current sanity project */\n 'user-menu.action.invite-members-aria-label': 'Invite members',\n /** Label for action to manage the current sanity project */\n 'user-menu.action.manage-project': 'Manage project',\n /** Accessibility label for the action to manage the current project */\n 'user-menu.action.manage-project-aria-label': 'Manage project',\n /** Tooltip helper text when portable text annotation is disabled for empty block*/\n 'user-menu.action.portable-text.annotation-disabled_empty-block':\n 'Cannot apply {{name}} to empty block',\n /** Tooltip helper text when portable text annotation is disabled for multiple blocks */\n 'user-menu.action.portable-text.annotation-disabled_multiple-blocks':\n 'Cannot apply {{name}} to multiple blocks',\n /** Label for action to sign out of the current sanity project */\n 'user-menu.action.sign-out': 'Sign out',\n /** Title for appearance section for the current studio (dark / light / system scheme) */\n 'user-menu.appearance-title': 'Appearance',\n /** Label for close menu button for user menu */\n 'user-menu.close-menu': 'Close menu',\n /** Description for using the \"dark theme\" in the appearance user menu */\n 'user-menu.color-scheme.dark-description': 'Use dark appearance',\n /** Title for using the \"dark theme\" in the appearance user menu */\n 'user-menu.color-scheme.dark-title': 'Dark',\n /** Description for using the \"light theme\" in the appearance user menu */\n 'user-menu.color-scheme.light-description': 'Use light appearance',\n /** Title for using the \"light theme\" in the appearance user menu */\n 'user-menu.color-scheme.light-title': 'Light',\n /** Description for using \"system apparence\" in the appearance user menu */\n 'user-menu.color-scheme.system-description': 'Use system appearance',\n /** Title for using system apparence in the appearance user menu */\n 'user-menu.color-scheme.system-title': 'System',\n /** Title for locale section for the current studio */\n 'user-menu.locale-title': 'Language',\n /** Label for tooltip to show which provider the currently logged in user is using */\n 'user-menu.login-provider': 'Signed in with {{providerTitle}}',\n /** Label for open menu button for user menu */\n 'user-menu.open-menu': 'Open menu',\n\n /** Label for other users' agent bundle versions */\n 'version.agent-bundle.agent-changes': 'Agent changes',\n /** Label for the current user's agent bundle versions */\n 'version.agent-bundle.proposed-changes': 'Proposed changes',\n\n /**\n * Label for action to add a workspace (currently a developer-oriented action, as this will\n * lead to the documentation on workspace configuration)\n */\n 'workspaces.action.add-workspace': 'Add workspace',\n /**\n * Label for action to choose a different workspace, in the case where you are not logged in,\n * have selected a workspace, and are faced with the authentication options for the selected\n * workspace. In other words, label for the action shown when you have reconsidered which\n * workspace to authenticate in.\n */\n 'workspaces.action.choose-another-workspace': 'Choose another workspace',\n /** Label for title to switch workspace before workspaces are listed */\n 'workspaces.action.switch-workspace': 'Switch workspace',\n /** Label for heading that indicates that you can choose your workspace */\n 'workspaces.choose-your-workspace-label': 'Choose your workspace',\n /** Label for the workspace menu */\n 'workspaces.select-workspace-aria-label': 'Select workspace',\n /** Button label for opening the workspace switcher */\n 'workspaces.select-workspace-label': 'Select workspace',\n /** Tooltip for the workspace menu */\n 'workspaces.select-workspace-tooltip': 'Select workspace',\n /** Title for Workplaces dropdown menu */\n 'workspaces.title': 'Workspaces',\n})\n\n/**\n * The i18n resource keys for the studio.\n *\n * @alpha\n * @hidden\n */\nexport type StudioLocaleResourceKeys = keyof typeof studioLocaleStrings\n\n/**\n * Locale resources for the core studio namespace, eg US English locale resources.\n *\n * @beta\n * @hidden\n */\nexport const studioDefaultLocaleResources: LocaleResourceBundle = {\n locale: 'en-US',\n namespace: studioLocaleNamespace,\n resources: studioLocaleStrings,\n}\n","/* eslint sort-keys: \"error\" */\nimport {defineLocalesResources} from '../helpers'\nimport {validationLocaleNamespace} from '../localeNamespaces'\nimport {type LocaleResourceBundle} from '../types'\n\n/**\n * The string resources for validation.\n *\n * @internal\n * @hidden\n */\nconst validationLocaleStrings = defineLocalesResources('validation', {\n /** Array must have exactly \"$wantedLength\" items, but has more/less */\n 'array.exact-length': 'Must have exactly {{wantedLength}} items',\n /** Portable Text array must have exactly \"$wantedLength\" blocks, but has more/less */\n 'array.exact-length_blocks': 'Must have exactly {{wantedLength}} blocks',\n /** Array item is a duplicate, but array wants only unique items */\n 'array.item-duplicate': \"Can't be a duplicate\",\n /** Array has more than the maximum of \"$maxLength\" items */\n 'array.maximum-length': 'Must have at most {{maxLength}} items',\n /** Portable Text array has more than the maximum of \"$maxLength\" items */\n 'array.maximum-length_blocks': 'Must have at most {{maxLength}} blocks',\n /** Array has less than the minimum of \"$minLength\" items */\n 'array.minimum-length': 'Must have at least {{minLength}} items',\n /** Portable Text array has less than the minimum of \"$minLength\" blocks */\n 'array.minimum-length_blocks': 'Must have at least {{minLength}} blocks',\n /** Date is not valid or not in the correct format (ISO-8601) */\n 'date.invalid-format': 'Must be a valid ISO-8601 formatted date string',\n /** Date is later than the given maximum date \"$maxDate\" */\n 'date.maximum': 'Must be at or before {{maxDate}}',\n /** Date is earlier than the given minimum date \"$minDate\" */\n 'date.minimum': 'Must be at or after {{minDate}}',\n /** A value of incorrect type is found, eg found `number` instead of `string` */\n 'generic.incorrect-type': 'Expected type \"{{expectedType}}\", got \"{{actualType}}\"',\n /** Value is not one of the values specifically allowed */\n 'generic.not-allowed': 'Value did not match any allowed values',\n /** Value \"$givenValue\" is not one of the values specifically allowed */\n 'generic.not-allowed_hint': 'Value \"{{hint}}\" did not match any allowed values',\n /** A value is expected, but none is provided */\n 'generic.required': 'Required',\n /** Number is less than the given minimum threshold value \"$threshold\" */\n 'number.greater-than': 'Must be greater than {{threshold}}',\n /** Number is greater than the given maximum threshold value \"$threshold\" */\n 'number.less-than': 'Must be less than {{threshold}}',\n /** Number is higher than the given maximum value \"$maxNumber\" */\n 'number.maximum': 'Must be lower than or equal to {{maxNumber}}',\n /** Number has more precision (decimals) than the allowed \"$limit\" */\n 'number.maximum-precision': 'Max precision is {{limit}}',\n /** Number is lower than the given minimum value \"$minNumber\" */\n 'number.minimum': 'Must be greater than or equal to {{minNumber}}',\n /** Number is not an integer (\"whole number\") */\n 'number.non-integer': 'Must be an integer',\n /** Object is missing a reference to an asset document in its `asset` field */\n 'object.asset-required': 'Asset is required',\n /** Object is missing a reference to a file asset document in its `asset` field */\n 'object.asset-required_file': 'File is required',\n /** Object is missing a reference to an image asset document in its `asset` field */\n 'object.asset-required_image': 'Image is required',\n /** Media can't be found in the Media Library */\n 'object.media-not-found': 'The asset could not be found in the Media Library',\n /** Media object is missing a reference to a document in its `_ref` field */\n 'object.not-media-library-asset': 'Must be a reference to a Media Library asset',\n /** Object is not a reference to a document (eg `{_ref: 'documentId'}`) */\n 'object.not-reference': 'Must be a reference to a document',\n /** Object references a document which is not published */\n 'object.reference-not-published': 'Referenced document must be published',\n /** Accessibility label for closing the validation panel */\n 'panel.close-button-aria-label': 'Close validation',\n /** Message shown when the validation panel is opened but there are no errors/warnings */\n 'panel.no-errors-message': 'No validation errors',\n /** Title for the actual \"Validation\" panel/feature */\n 'panel.title': 'Validation',\n /** Message shown when the validation panel is opened but the document is going to unpublish */\n 'panel.unpublish-message': 'Document is going to unpublish, no validation errors are shown',\n /** Slug is an object, but is missing a `current` string property */\n 'slug.missing-current': 'Slug must have a value',\n /** Slug is not an object (eg `{current: 'some-slug'}`) */\n 'slug.not-object': 'Slug must be an object',\n /** Slug is already in use somewhere else, but needs to be unique */\n 'slug.not-unique': 'Slug is already in use',\n /** String is not a valid email address */\n 'string.email': 'Must be a valid email address',\n /** String has a different character length than the exact number \"$wantedLength\" */\n 'string.exact-length': 'Must be exactly {{wantedLength}} characters long',\n /** String contains characters that are not in lowercase */\n 'string.lowercase': 'Must be all lowercase characters',\n /** String is longer than the limit of \"$maxLength\" characters */\n 'string.maximum-length': 'Must be at most {{maxLength}} characters long',\n /** String is shorter than the limit of \"$minLength\" characters */\n 'string.minimum-length': 'Must be at least {{minLength}} characters long',\n /** String does not match the given regular expression, but should */\n 'string.regex-does-not-match': 'Does not match \"{{name}}\"-pattern',\n /** String matches the given regular expression, but should not */\n 'string.regex-match': 'Should not match \"{{name}}\"-pattern',\n /** String contains characters that are not in uppercase */\n 'string.uppercase': 'Must be all uppercase characters',\n /** String contains a protocol/scheme that is not allowed, eg (`ftp`, `mailto`…) */\n 'string.url.disallowed-scheme': 'Does not match allowed protocols/schemes',\n /** String contains a URL with a username or password specified before the host */\n 'string.url.includes-credentials': 'Username/password not allowed',\n /** String is not a valid URL */\n 'string.url.invalid': 'Not a valid URL',\n /** String is not an absolute URL (eg it is missing a protocol/host) */\n 'string.url.not-absolute': 'Relative URLs are not allowed',\n /** String is not a relative URL (eg it contains a protocol/host) */\n 'string.url.not-relative': 'Only relative URLs are allowed',\n} as const)\n\n/**\n * The i18n resource keys for the validation.\n *\n * @alpha\n * @hidden\n */\nexport type ValidationLocaleResourceKeys = keyof typeof validationLocaleStrings\n\n/**\n * Locale resources for the validation namespace, eg US English locale resources.\n *\n * @beta\n * @hidden\n */\nexport const validationLocaleResources: LocaleResourceBundle = {\n locale: 'en-US',\n namespace: validationLocaleNamespace,\n resources: validationLocaleStrings,\n}\n","import {copyPasteLocaleResources} from './bundles/copy-paste'\nimport {feedbackLocaleResources} from './bundles/feedback'\nimport {studioDefaultLocaleResources} from './bundles/studio'\nimport {validationLocaleResources} from './bundles/validation'\nimport {defineLocale} from './helpers'\n\n/**\n * The default US English locale for the studio.\n *\n * @internal\n * @hidden\n */\nexport const usEnglishLocale = defineLocale({\n id: 'en-US',\n title: 'English (US)',\n bundles: [\n studioDefaultLocaleResources,\n validationLocaleResources,\n copyPasteLocaleResources,\n feedbackLocaleResources,\n ],\n\n weekInfo: {\n firstDay: 7, // Sunday\n weekend: [6, 7], // Saturday, Sunday\n },\n})\n\n/**\n * The default locale for the studio.\n *\n * @internal\n * @hidden\n */\n/** @alias */\nexport const defaultLocale = usEnglishLocale\n","/* oxlint-disable @sanity/i18n/no-i18next-import */\nimport {createInstance, type Resource} from 'i18next'\nimport memoize from 'lodash-es/memoize.js'\n\nimport {isStaticResourceBundle} from './helpers'\nimport {studioLocaleNamespace} from './localeNamespaces'\nimport {defaultLocale, usEnglishLocale} from './locales'\nimport {type LocaleSource} from './types'\n\nconst shouldEscape = typeof window === 'undefined' || typeof document === 'undefined'\nconst fallbackLocales: LocaleSource['locales'] = [defaultLocale]\n\n/**\n * Returns a fallback source for internationalization that can be used in cases where you need\n * access to the \"framework\" of translation, but do not have access to an actual source.\n *\n * Memoized - only initializes the i18n instance once, and maintains the identity of the source.\n *\n * ⚠️ NOTE: This will only have the base studio strings defined - no custom bundles or plugins.\n *\n * @returns The fallback source\n * @internal\n * @hidden\n */\nexport const getFallbackLocaleSource: () => LocaleSource = memoize(\n function getFallbackLocaleSource(): LocaleSource {\n const i18n = getFallbackI18nInstance()\n void i18n.init()\n return {\n currentLocale: defaultLocale,\n locales: fallbackLocales,\n loadNamespaces: i18n.loadNamespaces,\n t: i18n.t,\n }\n },\n)\n\nfunction getFallbackI18nInstance() {\n // Find all core locale resource bundles we can load synchronously\n const staticResources: Resource = {[defaultLocale.id]: {}}\n const staticBundles = usEnglishLocale.bundles?.filter(isStaticResourceBundle) || []\n const namespaces = new Set<string>()\n for (const bundle of staticBundles) {\n staticResources[defaultLocale.id][bundle.namespace] = bundle.resources\n namespaces.add(bundle.namespace)\n }\n\n return createInstance({\n ns: Array.from(namespaces),\n defaultNS: studioLocaleNamespace,\n initAsync: true,\n partialBundledLanguages: true,\n fallbackLng: defaultLocale.id,\n lng: defaultLocale.id,\n supportedLngs: [defaultLocale.id],\n debug: false,\n load: 'currentOnly',\n resources: staticResources,\n interpolation: {\n // If we're in a browser, assume this is running inside of the studio, eg a React app,\n // and that values returned will be escaped by the framework (eg React) automatically.\n escapeValue: shouldEscape,\n },\n })\n}\n","import {type SanityClient} from '@sanity/client'\nimport {ConcurrencyLimiter} from '@sanity/util/concurrency-limiter'\nimport {\n bufferTime,\n filter,\n finalize,\n firstValueFrom,\n from,\n map,\n mergeMap,\n share,\n Subject,\n switchMap,\n} from 'rxjs'\n\nimport {type AvailabilityResponse} from '../../preview/types'\n\n/**\n * The amount of time reserved for waiting for new IDs.\n */\nconst BUFFER_TIME = 250\n/**\n * The upper limit for IDs sent to the `doc` endpoint at once. From some manual\n * testing, 100 seems to be a safe amount.\n */\nexport const MAX_BUFFER_SIZE = 100\n/**\n * The max amount of inflight requests to the `doc` endpoint to check for\n * availability. Currently set to 1 because the endpoint is expensive\n *\n * From: https://www.sanity.io/docs/http-doc\n *\n * \"it is less scalable/performant than the other query-mechanisms, so should\n * be used sparingly*\n */\nexport const MAX_REQUEST_CONCURRENCY = 1\n\nexport function createBatchedGetDocumentExists(\n client: SanityClient,\n): (options: {id: string}) => Promise<boolean> {\n const id$ = new Subject<string>()\n const limiter = new ConcurrencyLimiter(MAX_REQUEST_CONCURRENCY)\n\n const existence$ = id$.pipe(\n bufferTime(BUFFER_TIME, null, MAX_BUFFER_SIZE),\n map((ids) => Array.from(new Set(ids))),\n mergeMap((ids) =>\n from(limiter.ready()).pipe(\n switchMap(() =>\n client.observable\n .request<AvailabilityResponse>({\n uri: client.getDataUrl('doc', ids.join(',')),\n json: true,\n query: {excludeContent: 'true'},\n tag: 'documents-availability',\n })\n .pipe(map((availability) => ({availability, ids}))),\n ),\n finalize(limiter.release),\n ),\n ),\n mergeMap(({availability, ids}) =>\n ids.map((id) => {\n const omittedIds = availability.omitted.reduce<Record<string, 'existence' | 'permission'>>(\n (acc, next) => {\n acc[next.id] = next.reason\n return acc\n },\n {},\n )\n\n // if not in the `omitted`, then it exists\n if (!omittedIds[id]) return {id, exists: true}\n // if in the `omitted` due to existence, then it does not exist\n if (omittedIds[id] === 'existence') return {id, exists: false}\n // otherwise, it must exist\n return {id, exists: true}\n }),\n ),\n share(),\n )\n\n return async function getDocumentExists(options) {\n // set up a promise/listener that waits for the result\n const result = firstValueFrom(existence$.pipe(filter(({id}) => id === options.id)))\n // send off the request to the stream for batching\n id$.next(options.id)\n\n const {exists} = await result\n return exists\n }\n}\n","/**\n * Simple requestIdleCallback polyfill\n * Can be removed when all browsers support requestIdleCallback: https://caniuse.com/requestidlecallback\n * @param callback -\n * @param options -\n */\nconst requestIdleCallbackShim: typeof window.requestIdleCallback = function requestIdleCallbackShim(\n callback,\n _options?,\n): number {\n const start = Date.now()\n return globalThis.setTimeout(() => {\n callback({\n didTimeout: false,\n timeRemaining() {\n return Math.max(0, Date.now() - start)\n },\n })\n }, 0) as unknown as number\n}\n\nconst cancelIdleCallbackShim: typeof window.cancelIdleCallback = function cancelIdleCallbackShim(\n handle: number,\n): void {\n return globalThis.clearTimeout(handle)\n}\n\nconst win = typeof window === 'undefined' ? undefined : window\n\nexport const requestIdleCallback = win?.requestIdleCallback || requestIdleCallbackShim\nexport const cancelIdleCallback = win?.cancelIdleCallback || cancelIdleCallbackShim\n","import {type CustomValidator, type ObjectSchemaType} from '@sanity/types'\n\n/**\n * Given a schema type, returns a custom validator used to warn users of unknown\n * fields found in an object.\n */\nexport const unknownFieldsValidator =\n (type: ObjectSchemaType): CustomValidator =>\n (value) => {\n if (typeof value !== 'object') return true\n if (!value) return true\n\n const fieldNames = new Set(type.fields?.map((field) => field.name))\n\n const unknownFields = Object.keys(value)\n .filter((key) => !key.startsWith('_'))\n .filter((key) => !fieldNames.has(key))\n\n return unknownFields.map((unknownField) => ({\n message: `Field '${unknownField}' does not exist on type '${type.name}'`,\n path: [unknownField],\n }))\n }\n","import {type SanityClient} from '@sanity/client'\nimport {\n isKeyedObject,\n isTypedObject,\n type CurrentUser,\n type Rule,\n type SanityDocument,\n type Schema,\n type SchemaType,\n type ValidationMarker,\n} from '@sanity/types'\nimport {createClientConcurrencyLimiter} from '@sanity/util/client'\nimport {ConcurrencyLimiter} from '@sanity/util/concurrency-limiter'\nimport flatten from 'lodash-es/flatten.js'\nimport uniqBy from 'lodash-es/uniqBy.js'\nimport {concat, defer, from, lastValueFrom, merge, Observable, of} from 'rxjs'\nimport {catchError, map, mergeAll, mergeMap, switchMap, toArray} from 'rxjs/operators'\n\nimport {type SourceClientOptions, type Workspace} from '../config/types'\nimport {resolveConditionalProperty} from '../form/store/conditional-property/resolveConditionalProperty'\nimport {getFallbackLocaleSource} from '../i18n/fallback'\nimport {DEFAULT_STUDIO_CLIENT_OPTIONS} from '../studioClient'\nimport {type ValidationContext} from './types'\nimport {createBatchedGetDocumentExists} from './util/createBatchedGetDocumentExists'\nimport {getTypeChain, normalizeValidationRules} from './util/normalizeValidationRules'\nimport {cancelIdleCallback, requestIdleCallback} from './util/requestIdleCallback'\nimport {typeString} from './util/typeString'\nimport {unknownFieldsValidator} from './validators/unknownFieldsValidator'\n\n// this is the number of requests allowed inflight at once. this is done to prevent\n// the validation library from overwhelming our backend.\n// NOTE: this was upped from 10 to prevent issues where many concurrency\n// `client.fetch` requests would \"clog\" custom validators from finishing due to\n// not enough concurrent requests being fulfilled\n//\n// NOTE: ensure to update the TSDoc and CLI help test if this is changed\nconst DEFAULT_MAX_FETCH_CONCURRENCY = 25\n\n// NOTE: ensure to update the TSDoc and CLI help test if this is changed\nconst DEFAULT_MAX_CUSTOM_VALIDATION_CONCURRENCY = 5\n\nlet _limitConcurrency: ReturnType<typeof createClientConcurrencyLimiter> | undefined\nconst getConcurrencyLimiter = (maxConcurrency: number) => {\n if (_limitConcurrency) return _limitConcurrency\n _limitConcurrency = createClientConcurrencyLimiter(maxConcurrency)\n return _limitConcurrency\n}\n\nconst isRecord = (maybeRecord: unknown): maybeRecord is Record<string, unknown> =>\n typeof maybeRecord === 'object' && maybeRecord !== null && !Array.isArray(maybeRecord)\n\nconst isNonNullable = <T>(value: T): value is NonNullable<T> =>\n value !== null && value !== undefined\n\n/**\n * Recursively extracts all `_fieldRules` from a rule and its nested constraints.\n * This handles cases where `Rule.fields()` is used inside `Rule.all()` or `Rule.either()`.\n */\nfunction extractFieldRulesFromRule(rule: Rule): NonNullable<Rule['_fieldRules']>[] {\n const results: NonNullable<Rule['_fieldRules']>[] = []\n\n // Add direct _fieldRules if present\n if (rule._fieldRules) {\n results.push(rule._fieldRules)\n }\n\n // Check for nested rules in 'all' or 'either' constraints\n for (const ruleSpec of rule._rules) {\n if (ruleSpec.flag === 'all' || ruleSpec.flag === 'either') {\n const childRules = ruleSpec.constraint\n if (Array.isArray(childRules)) {\n for (const childRule of childRules) {\n results.push(...extractFieldRulesFromRule(childRule))\n }\n }\n }\n }\n\n return results\n}\n\n/**\n * @internal\n */\nexport function resolveTypeForArrayItem(\n item: unknown,\n candidates: SchemaType[],\n): SchemaType | undefined {\n // if there is only one type available, assume that it's the correct one\n if (candidates.length === 1) return candidates[0]\n\n const itemType = isTypedObject(item) && item._type\n const primitive =\n item === undefined || item === null || (!itemType && typeString(item).toLowerCase())\n\n if (primitive && primitive !== 'object') {\n return candidates.find((candidate) => candidate.jsonType === primitive)\n }\n\n return (\n candidates.find((candidate) => candidate.type?.name === itemType) ||\n candidates.find((candidate) => candidate.name === itemType) ||\n candidates.find((candidate) => candidate.name === 'object' && primitive === 'object')\n )\n}\n\n/**\n * @beta\n */\nexport interface ValidateDocumentOptions {\n /**\n * The document to be validated\n */\n document: SanityDocument\n /**\n * The workspace instance (and associated schema) used to validate the given\n * document against.\n */\n workspace: Workspace\n\n /**\n * Function used to check if referenced documents exists (and is published).\n *\n * If you're validating many documents in bulk, you may want to query for all\n * document IDs first and provide your own implementation using those.\n *\n * If no function is provided a default one will be provided that will batch\n * call the `doc` endpoint to check for document existence.\n */\n getDocumentExists?: (options: {id: string}) => Promise<boolean>\n\n /**\n * The factory function used to get a sanity client used in custom validators.\n * If not provided, the one from the workspace will be used (preferred).\n *\n * @deprecated For internal use only\n */\n getClient?: (clientOptions: SourceClientOptions) => SanityClient\n\n /**\n * Specify the environment name. This will be passed down to the\n * `ValidationContext` and made available to custom validators.\n */\n environment?: 'cli' | 'studio'\n\n /**\n * The maximum amount of custom validation functions to be running\n * concurrently at once. This helps prevent custom validators from\n * overwhelming backend services (e.g. called via fetch) used in async,\n * user-defined validation functions. (i.e. `rule.custom(async() => {})`)\n *\n * Note that lowering this number may also help in cases where a custom\n * validator could potentially exhaust the fetch concurrency. This is 5 by\n * default.\n */\n maxCustomValidationConcurrency?: number\n\n /**\n * The amount of allowed inflight fetch requests at once. You may need to up\n * this value if you have complex custom validations that require many\n * `client.fetch` requests at once. It's possible for custom validator to\n * stall if there are not enough concurrent fetch requests available to\n * fullfil the custom validation. This is 25 by default.\n */\n maxFetchConcurrency?: number\n\n /**\n * The current user, when available. Used when resolving schema `hidden`\n * conditionals so validation matches what the form shows. If omitted, hidden\n * is resolved with no user (e.g. CLI or headless validation).\n */\n currentUser?: Omit<CurrentUser, 'role'> | null\n}\n\n/**\n * Validates a document against the schema in the given workspace. Returns an\n * array of validation markers with a path, message, and validation level.\n *\n * @beta\n */\nexport function validateDocument({\n document,\n workspace,\n environment = 'studio',\n maxFetchConcurrency,\n currentUser,\n ...options\n}: ValidateDocumentOptions): Promise<ValidationMarker[]> {\n const getClient = options.getClient || workspace.getClient\n const limitConcurrency = getConcurrencyLimiter(\n maxFetchConcurrency ?? DEFAULT_MAX_FETCH_CONCURRENCY,\n )\n const getConcurrencyLimitedClient = (clientOptions: SourceClientOptions) =>\n limitConcurrency(getClient(clientOptions))\n\n return lastValueFrom(\n validateDocumentObservable({\n document,\n getClient: getConcurrencyLimitedClient,\n i18n: workspace.i18n,\n schema: workspace.schema,\n getDocumentExists:\n options.getDocumentExists ||\n createBatchedGetDocumentExists(getClient(DEFAULT_STUDIO_CLIENT_OPTIONS)),\n environment,\n currentUser,\n }),\n )\n}\n\n/**\n * @internal\n */\nexport interface ValidateDocumentObservableOptions extends Pick<\n ValidationContext,\n 'getDocumentExists' | 'i18n'\n> {\n getClient: (options: {apiVersion: string}) => SanityClient\n document: SanityDocument\n schema: Schema\n environment: 'cli' | 'studio'\n maxCustomValidationConcurrency?: number\n currentUser?: Omit<CurrentUser, 'role'> | null\n}\n\nconst customValidationConcurrencyLimiters = new WeakMap<Schema, ConcurrencyLimiter>()\n\n/**\n * Validates a document against the given schema, returning an Observable\n * @internal\n */\nexport function validateDocumentObservable({\n document,\n getClient,\n i18n = getFallbackLocaleSource(),\n schema,\n getDocumentExists,\n environment,\n maxCustomValidationConcurrency,\n currentUser,\n}: ValidateDocumentObservableOptions): Observable<ValidationMarker[]> {\n if (typeof document?._type !== 'string') {\n throw new Error(`Tried to validated a value without a '_type'`)\n }\n\n const documentType = schema.get(document._type)\n\n if (!documentType) {\n if (environment === 'studio') {\n console.warn(\n 'Schema type for object type \"%s\" not found, skipping validation',\n document._type,\n )\n return of([])\n }\n\n return of([\n {\n level: 'warning',\n message: `Could not find schema type for type '${document._type}', skipping validation`,\n path: [],\n },\n ])\n }\n\n let customValidationConcurrencyLimiter = customValidationConcurrencyLimiters.get(schema)\n if (!customValidationConcurrencyLimiter) {\n customValidationConcurrencyLimiter = new ConcurrencyLimiter(\n maxCustomValidationConcurrency ?? DEFAULT_MAX_CUSTOM_VALIDATION_CONCURRENCY,\n )\n customValidationConcurrencyLimiters.set(schema, customValidationConcurrencyLimiter)\n }\n\n const validationOptions: ValidateItemOptions = {\n getClient,\n schema,\n parent: undefined,\n value: document,\n path: [],\n document: document,\n type: documentType,\n i18n,\n getDocumentExists,\n environment,\n customValidationConcurrencyLimiter,\n currentUser,\n }\n\n return from(i18n.loadNamespaces(['validation'])).pipe(\n switchMap(() => validateItemObservable(validationOptions)),\n catchError((err) => {\n console.error(err)\n\n const message = err?.message || 'Unknown error'\n const errorMarker: ValidationMarker = {\n level: 'error',\n message,\n item: {message},\n path: [],\n }\n\n return of([errorMarker])\n }),\n )\n}\n\n/**\n * this is used make optional properties required by replacing optionals with\n * `T[P] | undefined`. this is used to prevent errors in `validateItem` where\n * an option from a previous invocation would be incorrectly passed down.\n *\n * https://medium.com/terria/typescript-transforming-optional-properties-to-required-properties-that-may-be-undefined-7482cb4e1585\n */\ntype ExplicitUndefined<T> = {\n [P in keyof Required<T>]: Pick<T, P> extends Required<Pick<T, P>> ? T[P] : T[P] | undefined\n}\n\ntype ValidateItemOptions = {\n value: unknown\n customValidationConcurrencyLimiter?: ConcurrencyLimiter\n hidden?: boolean\n currentUser?: Omit<CurrentUser, 'role'> | null\n} & ExplicitUndefined<Omit<ValidationContext, 'hidden'>>\n\nexport function validateItem(opts: ValidateItemOptions): Promise<ValidationMarker[]> {\n return lastValueFrom(validateItemObservable(opts))\n}\n\nfunction validateItemObservable({\n value,\n type,\n path = [],\n parent,\n customValidationConcurrencyLimiter,\n environment,\n ...restOfContext\n}: ValidateItemOptions): Observable<ValidationMarker[]> {\n // Track whether any ancestor in the tree is hidden.\n // It will be true if this field OR any ancestor is hidden.\n // This allows validation rules to check `context.hidden` to skip validation for hidden fields,\n // without needing to know whether the field itself or an ancestor caused it to be hidden.\n const ancestorHidden = restOfContext.hidden === true\n const resolveHiddenForType = (\n schemaType: SchemaType | undefined,\n schemaValue: unknown,\n schemaParent: unknown,\n schemaPath: ValidationContext['path'],\n ancestorHiddenValue: boolean,\n ) => {\n // If there is no schema type, fall back to the ancestor's hidden state.\n if (!schemaType) {\n return ancestorHiddenValue\n }\n return (\n ancestorHiddenValue ||\n resolveConditionalProperty(schemaType.hidden, {\n ...restOfContext,\n parent: schemaParent,\n value: schemaValue,\n path: schemaPath || [],\n currentUser: restOfContext.currentUser ?? null,\n })\n )\n }\n const hidden = resolveHiddenForType(type, value, parent, path, ancestorHidden)\n\n // Note: this validator is added here because it's conditional based on the\n // environment.\n const addUnknownFieldsValidator = (rule: Rule) => {\n if (\n // if the schema type is an object type\n type?.jsonType === 'object' &&\n // and if somewhere in it's type chain, it inherits from object or document\n getTypeChain(type).find((t) => ['object', 'document', 'file', 'image'].includes(t.name)) &&\n // and the environment is not the studio\n environment !== 'studio'\n ) {\n // then add the validator for unknown fields\n return rule.custom(unknownFieldsValidator(type), {bypassConcurrencyLimit: true}).warning()\n }\n\n // otherwise, leave it unchanged\n return rule\n }\n\n const rules = normalizeValidationRules(type, {\n ...restOfContext,\n hidden,\n environment,\n parent,\n path,\n type,\n })\n // run validation for the current value\n const selfChecks = rules.map(addUnknownFieldsValidator).map((rule) =>\n defer(() =>\n rule.validate(value, {\n ...restOfContext,\n environment,\n hidden,\n parent,\n path,\n type,\n __internal: {customValidationConcurrencyLimiter},\n }),\n ),\n )\n\n // run validation for nested values (conditionally)\n let nestedChecks: Array<Observable<ValidationMarker[]>> = []\n\n const selfIsRequired = rules.some((rule) => rule.isRequired())\n const shouldRunNestedObjectValidation =\n // run nested validation for objects\n type?.jsonType === 'object' &&\n // if the value is truthy\n (!!value || // or\n // (the value is null or undefined) and the top-level value is required\n ((value === null || value === undefined) && selfIsRequired))\n\n if (shouldRunNestedObjectValidation) {\n const fieldTypes = type.fields.reduce<Record<string, SchemaType>>((acc, field) => {\n acc[field.name] = field.type\n return acc\n }, {})\n\n // Validation for rules set at the object level with `Rule.fields({/* ... */})`\n // Use extractFieldRulesFromRule to handle Rule.fields() inside Rule.all() or Rule.either()\n nestedChecks = nestedChecks.concat(\n rules\n .flatMap((rule) => extractFieldRulesFromRule(rule))\n .flatMap((fieldResults) => Object.entries(fieldResults))\n .flatMap(([name, validation]) => {\n const fieldType = fieldTypes[name]\n return normalizeValidationRules({...fieldType, validation})\n .map(addUnknownFieldsValidator)\n .map((subRule) => {\n const nestedValue = isRecord(value) ? value[name] : undefined\n const nestedHidden = resolveHiddenForType(\n fieldType,\n nestedValue,\n value,\n path.concat(name),\n hidden,\n )\n return defer(() =>\n subRule.validate(nestedValue, {\n ...restOfContext,\n parent: value,\n path: path.concat(name),\n type: fieldType,\n environment,\n hidden: nestedHidden,\n __internal: {customValidationConcurrencyLimiter},\n }),\n )\n })\n }),\n )\n\n // Validation from each field's schema `validation: Rule => {/* ... */}` function\n nestedChecks = nestedChecks.concat(\n type.fields.map((field) =>\n validateItemObservable({\n ...restOfContext,\n hidden,\n parent: value,\n value: isRecord(value) ? value[field.name] : undefined,\n path: path.concat(field.name),\n type: field.type,\n environment,\n customValidationConcurrencyLimiter,\n }),\n ),\n )\n }\n\n // note: unlike objects, arrays should not run nested validation for undefined\n // values because we won't have a valid path to put a marker (i.e. missing the\n // key or index in the path) and the downstream form builder won't have a\n // valid target component\n const shouldRunNestedValidationForArrays = type?.jsonType === 'array' && Array.isArray(value)\n\n if (shouldRunNestedValidationForArrays) {\n nestedChecks = nestedChecks.concat(\n value.map((item, index) =>\n validateItemObservable({\n ...restOfContext,\n hidden,\n parent: value,\n value: item,\n path: path.concat(isKeyedObject(item) ? {_key: item._key} : index),\n type: resolveTypeForArrayItem(item, type.of),\n environment,\n customValidationConcurrencyLimiter,\n }),\n ),\n )\n }\n\n return defer(() => merge([...selfChecks, ...nestedChecks])).pipe(\n mergeMap((validateNode) => concat(idle(), validateNode), 40),\n mergeAll(),\n toArray(),\n map(flatten),\n map((results) => {\n // run `uniqBy` if `_fieldRules` are present because they can\n // cause repeat markers (check recursively for nested rules)\n if (rules.some((rule) => extractFieldRulesFromRule(rule).length > 0)) {\n return uniqBy(results, (rule) => JSON.stringify(rule))\n }\n return results\n }),\n )\n}\n\nfunction idle(timeout?: number): Observable<never> {\n return new Observable<never>((observer) => {\n const handle = requestIdleCallback(\n () => {\n observer.complete()\n },\n timeout ? {timeout} : undefined,\n )\n\n return () => cancelIdleCallback(handle)\n })\n}\n","import {type SanityClient} from '@sanity/client'\nimport {\n isGlobalDocumentReference,\n isReference,\n type SanityDocument,\n type Schema,\n type ValidationContext,\n type ValidationMarker,\n type CurrentUser,\n} from '@sanity/types'\nimport {reduce as reduceJSON} from 'json-reduce'\nimport {\n asyncScheduler,\n combineLatest,\n concat,\n defer,\n from,\n lastValueFrom,\n type Observable,\n of,\n timer,\n} from 'rxjs'\nimport {exhaustMapWithTrailing} from 'rxjs-exhaustmap-with-trailing'\nimport {\n distinct,\n distinctUntilChanged,\n first,\n groupBy,\n map,\n mergeMap,\n scan,\n shareReplay,\n skip,\n throttleTime,\n} from 'rxjs/operators'\nimport shallowEquals from 'shallow-equals'\n\nimport {type SourceClientOptions} from '../config/types'\nimport {type LocaleSource} from '../i18n/types'\nimport {type DocumentPreviewStore} from '../preview/documentPreviewStore'\nimport {getVersionFromId} from '../util/draftUtils'\nimport {validateDocumentObservable} from './validateDocument'\n\n/**\n * @hidden\n * @beta */\nexport interface ValidationStatus {\n isValidating: boolean\n validation: ValidationMarker[]\n revision?: string\n}\n\nconst INITIAL_VALIDATION_STATUS: ValidationStatus = {\n isValidating: true,\n validation: [],\n}\n\nfunction findReferenceIds(obj: any): Set<string> {\n return reduceJSON(\n obj,\n (acc, node) => {\n if (isReference(node) && !isGlobalDocumentReference(node)) {\n acc.add(node._ref)\n }\n return acc\n },\n new Set<string>(),\n )\n}\n\nconst EMPTY_VALIDATION: ValidationMarker[] = []\n\ntype GetDocumentExists = NonNullable<ValidationContext['getDocumentExists']>\n\nconst listenDocumentExists = (\n observeDocumentAvailability: DocumentPreviewStore['unstable_observeDocumentPairAvailability'],\n id: string,\n versionId: string | undefined,\n): Observable<boolean> =>\n observeDocumentAvailability(id, {version: versionId}).pipe(\n map(({published, version}) => {\n if (!version?.available && version?.reason === 'VERSION_DELETED') {\n return false\n }\n\n return published.available || version?.available || false\n }),\n )\n\n// throttle delay for referenced document updates (i.e. time between responding to changes in referenced documents)\nconst REF_UPDATE_DELAY = 1000\n\nfunction shareLatestWithRefCount<T>() {\n return shareReplay<T>({bufferSize: 1, refCount: true})\n}\n\n/**\n * @internal\n * Takes an observable of a document and validates it, including any references in the document.\n * */\nexport function validateDocumentWithReferences(\n ctx: {\n getClient: (options: SourceClientOptions) => SanityClient\n observeDocumentPairAvailability: DocumentPreviewStore['unstable_observeDocumentPairAvailability']\n schema: Schema\n i18n: LocaleSource\n currentUser?: Omit<CurrentUser, 'role'> | null\n },\n document$: Observable<SanityDocument | null | undefined>,\n // whether to require all references to exist as published documents\n // set to false to allow references to versions as long they exist in the same bundle\n requirePublishedReferences: boolean,\n): Observable<ValidationStatus> {\n const referenceIds$ = document$.pipe(\n map((document) => findReferenceIds(document)),\n mergeMap((ids) => from(ids)),\n )\n\n const versionId$ = document$.pipe(distinctUntilChanged())\n\n // Note: we only use this to trigger a re-run of validation when a referenced document is published/unpublished\n const referenceExistence$ = combineLatest([versionId$, referenceIds$]).pipe(\n groupBy(([_, referenceId]) => referenceId, {duration: () => timer(1000 * 60 * 30)}),\n mergeMap((refIds$) =>\n refIds$.pipe(\n distinct(),\n mergeMap(([document, referenceId]) => {\n // listen for reference document existence\n // if we're require the referenced document to be published: pass undefined as version id\n // as that will check for existence of published document\n // Otherwise, pass the version of the referencing document\n // to validate that the version exists in the same bundle\n const versionId = requirePublishedReferences\n ? undefined\n : getVersionFromId(document?._id || '')\n return listenDocumentExists(\n ctx.observeDocumentPairAvailability,\n referenceId,\n versionId,\n ).pipe(map((result) => [referenceId, result] as const))\n }),\n ),\n ),\n scan((acc: Record<string, boolean>, [id, result]): Record<string, boolean> => {\n if (acc[id] === result) {\n return acc\n }\n return {...acc, [id]: result}\n }, {}),\n distinctUntilChanged(shallowEquals),\n shareLatestWithRefCount(),\n )\n\n // Provided to individual validation functions to support using existence of a weakly referenced document\n // as part of the validation rule (used by references in place)\n const getDocumentExists: GetDocumentExists = ({id}) =>\n lastValueFrom(\n referenceExistence$.pipe(\n // If the id is not present as key in the `referenceExistence` map it means it's existence status\n // isn't yet loaded, so we want to wait until it is\n first((referenceExistence) => id in referenceExistence),\n map((referenceExistence) => referenceExistence[id]),\n ),\n )\n\n const referenceDocumentUpdates$ = referenceExistence$.pipe(\n // we'll skip the first emission since the document already gets an initial validation pass\n // we're only interested in updates in referenced documents after that\n skip(1),\n throttleTime(REF_UPDATE_DELAY, asyncScheduler, {leading: true, trailing: true}),\n )\n\n return combineLatest([document$, concat(of(null), referenceDocumentUpdates$)]).pipe(\n map(([document]) => document),\n exhaustMapWithTrailing((document) => {\n return defer(() => {\n if (!document?._type) {\n return of({validation: EMPTY_VALIDATION, isValidating: false})\n }\n return concat(\n of({isValidating: true, revision: document._rev}),\n validateDocumentObservable({\n document,\n getClient: ctx.getClient,\n getDocumentExists,\n i18n: ctx.i18n,\n schema: ctx.schema,\n environment: 'studio',\n currentUser: ctx.currentUser,\n }).pipe(\n map((validationMarkers) => ({validation: validationMarkers, isValidating: false})),\n ),\n )\n })\n }),\n scan((acc, next) => ({...acc, ...next}), INITIAL_VALIDATION_STATUS),\n shareLatestWithRefCount(),\n )\n}\n","import {type SanityClient} from '@sanity/client'\nimport {type CurrentUser, type Schema} from '@sanity/types'\nimport omit from 'lodash-es/omit.js'\nimport {asyncScheduler, combineLatest, type Observable} from 'rxjs'\nimport {distinctUntilChanged, map, shareReplay, throttleTime} from 'rxjs/operators'\nimport shallowEquals from 'shallow-equals'\n\nimport {type SourceClientOptions} from '../../../config/types'\nimport {type LocaleSource} from '../../../i18n/types'\nimport {type DraftsModelDocumentAvailability} from '../../../preview/types'\nimport {type DocumentVariantType} from '../../../util/getDocumentVariantType'\nimport {validateDocumentWithReferences, type ValidationStatus} from '../../../validation'\nimport {type DocumentStoreExtraOptions} from '../getPairListener'\nimport {type IdPair} from '../types'\nimport {memoize} from '../utils/createMemoizer'\nimport {editState} from './editState'\nimport {memoizeKeyGen} from './memoizeKeyGen'\n\n// throttle delay for document updates (i.e. time between responding to changes in the current document)\nconst DOC_UPDATE_DELAY = 200\n\nfunction shareLatestWithRefCount<T>() {\n return shareReplay<T>({bufferSize: 1, refCount: true})\n}\n\n/** @internal */\nexport const validation = memoize(\n (\n ctx: {\n client: SanityClient\n getClient: (options: SourceClientOptions) => SanityClient\n observeDocumentPairAvailability: (id: string) => Observable<DraftsModelDocumentAvailability>\n schema: Schema\n i18n: LocaleSource\n /**\n * @deprecated Does nothing. Preserved to avoid breaking changes.\n * Will be removed in the next major version.\n */\n serverActionsEnabled?: Observable<boolean>\n pairListenerOptions?: DocumentStoreExtraOptions\n currentUser?: Omit<CurrentUser, 'role'> | null\n },\n {draftId, publishedId, versionId}: IdPair,\n typeName: string,\n validationTarget: DocumentVariantType,\n validatePublishedReferences: boolean,\n ): Observable<ValidationStatus> => {\n const document$ = editState(ctx, {draftId, publishedId, versionId}, typeName).pipe(\n map((state) => {\n const {version, draft, published} = state\n\n if (validationTarget === 'draft') return draft\n if (validationTarget === 'version') return version\n return published\n }),\n throttleTime(DOC_UPDATE_DELAY, asyncScheduler, {trailing: true}),\n )\n\n const documentToValidate$ = document$.pipe(\n distinctUntilChanged((prev, next) => {\n if (prev?._rev === next?._rev) {\n return true\n }\n // _rev and _updatedAt may change without other fields changing (due to a limitation in mutator)\n // so only pass on documents if _other_ attributes changes\n return shallowEquals(omit(prev, '_rev', '_updatedAt'), omit(next, '_rev', '_updatedAt'))\n }),\n shareLatestWithRefCount(),\n )\n\n /**\n * When a local mutation is applied, the document content updates immediately\n * but the `_rev` stays the same. When the server later confirms the\n * mutation, a new `_rev` arrives, but since the content hasn't changed (it was\n * already applied), `documentToValidate$` correctly skips re-validation due to\n * the `shallowEquals` check above.\n *\n * However, the `revision` field exposed in `ValidationStatus` must still reflect\n * the latest `_rev` from the server. If it doesn't, consumers that compare\n * `validationStatus.revision` against the current document `_rev` (e.g. the\n * publish action's scheduled-publish guard) will see a stale revision and may\n * never consider validation \"complete\" for the current document state.\n *\n * To fix this, we track `documentRevision$` separately from `documentToValidate$`\n * and always override the revision in the emitted validation status.\n */\n const documentRevision$ = document$.pipe(map((document) => document?._rev))\n\n return combineLatest([\n documentRevision$,\n validateDocumentWithReferences(ctx, documentToValidate$, validatePublishedReferences),\n ]).pipe(\n map(([revision, validationStatus]) => {\n return {...validationStatus, revision}\n }),\n )\n },\n (ctx, idPair, typeName, validationTarget, validatePublishedReferences) => {\n // Use the actual document ID being validated in the cache key for explicitness\n const documentId =\n validationTarget === 'draft'\n ? idPair.draftId\n : validationTarget === 'version'\n ? idPair.versionId\n : idPair.publishedId\n // Include the user id so an in-place user switch gets its own cache entry;\n // the module-level memo cache is never cleared, so without this a new user\n // would replay the previous user's validation result.\n const userId = ctx.currentUser?.id ?? ''\n return `${memoizeKeyGen(ctx.client, idPair, typeName)}-${documentId}-${validatePublishedReferences}-${userId}`\n },\n)\n","/**\n * Schedule the provided callback using `scheduler.postTask`, if it's available.\n * Otherwise, call it immediately.\n */\nexport function postTask<Result>(\n callback: () => Result,\n options: PostTaskOptions = {},\n): Result | Promise<Result> {\n if ('scheduler' in window && typeof window.scheduler?.postTask === 'function') {\n return window.scheduler.postTask(callback, options)\n }\n return callback()\n}\n","import isPlainObject from 'lodash-es/isPlainObject.js'\n\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return isPlainObject(value)\n}\n","import {isRecord} from './isRecord'\n\n// deep object assign for objects\n// note: doesn't mutate target\nexport default function deepAssign(\n target: Record<string, unknown>,\n source: Record<string, unknown>,\n): Record<string, unknown> {\n const result = {...target, ...source}\n\n Object.keys(result).forEach((key) => {\n const sourceVal = source[key]\n const targetVal = target[key]\n if (isRecord(sourceVal) && isRecord(targetVal)) {\n result[key] = deepAssign(targetVal, sourceVal)\n }\n })\n return result\n}\n","import {type Schema} from '@sanity/types'\nimport {randomKey} from '@sanity/util/content'\nimport {toString as pathToString} from '@sanity/util/paths'\n\nimport {type Template, type TemplateParameter} from './types'\nimport {isRecord} from './util/isRecord'\n\nconst ALLOWED_REF_PROPS = [\n '_dataset',\n '_projectId',\n '_strengthenOnPublish',\n '_key',\n '_ref',\n '_type',\n '_weak',\n]\nconst REQUIRED_TEMPLATE_PROPS: (keyof Template)[] = ['id', 'title', 'schemaType', 'value']\n\nfunction templateId(template: Template, i: number) {\n return quote(template.id || template.title) || (typeof i === 'number' && `at index ${i}`) || ''\n}\n\nfunction quote(str: string) {\n return str && str.length > 0 ? `\"${str}\"` : str\n}\n\nexport function validateTemplates(schema: Schema, templates: Template[]): Template[] {\n const idMap = new Map()\n\n templates.forEach((template, i) => {\n const id = templateId(template, i)\n\n if (typeof (template as {[key: string]: any}).values !== 'undefined' && !template.value) {\n throw new Error(`Template ${id} is missing \"value\" property, but contained \"values\". Typo?`)\n }\n\n const missing = REQUIRED_TEMPLATE_PROPS.filter((prop) => !template[prop])\n if (missing.length > 0) {\n throw new Error(`Template ${id} is missing required properties: ${missing.join(', ')}`)\n }\n\n if (typeof template.value !== 'function' && !isRecord(template.value)) {\n throw new Error(\n `Template ${id} has an invalid \"value\" property; should be a function or an object`,\n )\n }\n\n if (typeof template.parameters !== 'undefined') {\n if (Array.isArray(template.parameters)) {\n template.parameters.forEach((param, j) => validateParameter(schema, param, template, j))\n } else {\n throw new Error(`Template ${id} has an invalid \"parameters\" property; must be an array`)\n }\n }\n\n if (idMap.has(template.id)) {\n const dupeIndex = idMap.get(template.id)\n const dupe = `${quote(templates[dupeIndex].title)} at index ${dupeIndex}`\n throw new Error(\n `Template \"${template.title}\" at index ${i} has the same ID (\"${template.id}\") as template ${dupe}`,\n )\n }\n\n idMap.set(template.id, i)\n })\n\n return templates\n}\n\nexport function validateInitialObjectValue<T extends Record<string, unknown>>(\n value: T,\n template: Template,\n): T {\n const contextError = (msg: string) => `Template \"${template.id}\" initial value: ${msg}`\n\n if (!isRecord(value)) {\n throw new Error(contextError(`resolved to a non-object`))\n }\n\n if (value._type && template.schemaType !== value._type) {\n throw new Error(\n contextError(\n `includes \"_type\"-property (${value._type}) that does not match template (${template.schemaType})`,\n ),\n )\n }\n\n try {\n return validateValue(value)\n } catch (err) {\n err.message = contextError(err.message)\n throw err\n }\n}\n\nfunction validateValue(value: unknown, path: (string | number)[] = [], parentIsArray = false): any {\n if (Array.isArray(value)) {\n return value.map((item, i) => {\n if (Array.isArray(item)) {\n throw new Error(\n `multidimensional arrays are not supported (at path \"${pathToString(path)}\")`,\n )\n }\n\n return validateValue(item, path.concat(i), true)\n })\n }\n\n if (!isRecord(value)) {\n return value\n }\n\n // Apply missing keys is the parent is an array\n const initial: {[key: string]: any} = parentIsArray && !value._key ? {_key: randomKey()} : {}\n\n // Ensure non-root objects have _type\n if (path.length > 0 && !value._type) {\n if (value._ref) {\n // In the case of references, we know what the type should be, so apply it\n initial._type = 'reference'\n } else {\n // todo: consider if we need to re-instantiate this. It currently makes the valid case of having an initial object value for a field fail\n // throw new Error(`missing \"_type\" property at path \"${pathToString(path)}\"`)\n }\n }\n\n if (value._ref) {\n validateReference(value, path)\n }\n\n // Validate deeply\n return Object.keys(value).reduce((acc, key) => {\n acc[key] = validateValue(value[key], path.concat([key]))\n return acc\n }, initial)\n}\n\nfunction validateParameter(\n schema: Schema,\n parameter: TemplateParameter,\n template: Template,\n index: number,\n) {\n // const schema = getDefaultSchema()\n\n if (!parameter.name) {\n throw new Error(\n `Template ${template.id} has a parameter at index ${index} that is missing its \"name\"-property`,\n )\n }\n\n // I know, this is a weird one\n if (parameter.name === 'template') {\n throw new Error(\n `Template parameters cannot be named \"template\", see parameter #${index} for template ${template.id}`,\n )\n }\n\n if (!schema.get(parameter.type)) {\n throw new Error(\n `Template parameter \"${parameter.name}\" has an invalid/unknown type: \"${parameter.type}\"`,\n )\n }\n}\n\nfunction validateReference(\n value: {_type?: unknown; type?: unknown},\n path: (string | number)[] = [],\n) {\n if (!value._type && value.type) {\n throw new Error(\n `Reference is missing \"_type\", but has a \"type\" property at path \"${pathToString(path)}\"`,\n )\n }\n\n const disallowed = Object.keys(value).filter((key) => !ALLOWED_REF_PROPS.includes(key))\n if (disallowed.length > 0) {\n const plural = disallowed.length > 1 ? 'properties' : 'property'\n throw new Error(\n `Disallowed ${plural} found in reference: ${disallowed\n .map(quote)\n .join(', ')} at path \"${pathToString(path)}\"`,\n )\n }\n}\n","import {\n type ArraySchemaType,\n type InitialValueProperty,\n type InitialValueResolver,\n type InitialValueResolverContext,\n isArraySchemaType,\n isObjectSchemaType,\n type ObjectSchemaType,\n type Schema,\n type SchemaType,\n} from '@sanity/types'\nimport {isDeepEmpty, randomKey, resolveTypeName} from '@sanity/util/content'\n\nimport {postTask} from '../util/postTask'\nimport {type Template} from './types'\nimport deepAssign from './util/deepAssign'\nimport {isRecord} from './util/isRecord'\nimport {validateInitialObjectValue} from './validate'\n\n/** @internal */\nexport type Serializeable<T> = {\n serialize(): T\n}\n\ninterface Options {\n useCache?: boolean\n}\n\n/** @internal */\nexport function isBuilder(template: unknown): template is Serializeable<Template> {\n return isRecord(template) && typeof template.serialize === 'function'\n}\n\nconst cache = new WeakMap<\n InitialValueResolver<unknown, unknown>,\n Record<string, unknown | Promise<unknown>>\n>()\n\n/** @internal */\n// returns the \"resolved\" value from an initial value property (e.g. type.initialValue)\nexport async function resolveValue<Params, InitialValue>(\n initialValueOpt: InitialValueProperty<Params, InitialValue>,\n params: Params | undefined,\n context: InitialValueResolverContext,\n options?: Options,\n): Promise<InitialValue | undefined> {\n const useCache = options?.useCache\n\n if (typeof initialValueOpt === 'function') {\n const cached = cache.get(initialValueOpt as InitialValueResolver<unknown, unknown>)\n\n const key = JSON.stringify([\n params,\n context.projectId,\n context.dataset,\n context.currentUser?.id,\n ])\n\n if (useCache && cached?.[key]) {\n return cached[key] as InitialValue | Promise<InitialValue>\n }\n\n const value = (initialValueOpt as InitialValueResolver<Params, InitialValue>)(params, context)\n\n if (useCache) {\n cache.set(initialValueOpt as InitialValueResolver<unknown, unknown>, {\n ...cached,\n [key]: value,\n })\n }\n\n return value\n }\n\n return initialValueOpt\n}\n\n/** @internal */\nexport async function resolveInitialValue(\n schema: Schema,\n template: Template,\n params: {[key: string]: any} = {},\n context: InitialValueResolverContext,\n options?: Options,\n): Promise<{[key: string]: any}> {\n // Template builder?\n if (isBuilder(template)) {\n return resolveInitialValue(schema, template.serialize(), params, context, options)\n }\n\n const {id, schemaType: schemaTypeName, value} = template\n if (!value) {\n throw new Error(`Template \"${id}\" has invalid \"value\" property`)\n }\n\n let resolvedValue = await resolveValue(value, params, context, options)\n\n if (!isRecord(resolvedValue)) {\n throw new Error(\n `Template \"${id}\" has invalid \"value\" property - must be a plain object or a resolver function returning a plain object`,\n )\n }\n\n // Ensure _type is set on empty objects\n if (isRecord(resolvedValue) && !Object.keys(resolvedValue).length) {\n resolvedValue = {_type: schemaTypeName}\n }\n\n // validate default document initial values\n resolvedValue = validateInitialObjectValue(resolvedValue, template)\n\n // Get deep initial values from schema types (note: the initial value from template overrides the types)\n const schemaType = schema.get(schemaTypeName)\n if (!schemaType) {\n throw new Error(`Could not find schema type with name \"${schemaTypeName}\".`)\n }\n\n const newValue = deepAssign(\n (await resolveInitialValueForType(\n schemaType,\n params,\n DEFAULT_MAX_RECURSION_DEPTH,\n context,\n options,\n )) || {},\n resolvedValue as Record<string, unknown>,\n )\n\n // revalidate and return new initial values\n // todo: would be better to do validation as part of type resolution\n return validateInitialObjectValue(newValue, template)\n}\n\n/** @internal */\nfunction getItemType(arrayType: ArraySchemaType, item: unknown): SchemaType | undefined {\n const itemTypeName = resolveTypeName(item)\n\n return itemTypeName === 'object' && arrayType.of.length === 1\n ? arrayType.of[0]\n : arrayType.of.find((memberType) => memberType.name === itemTypeName)\n}\n\n/** @internal */\nexport const DEFAULT_MAX_RECURSION_DEPTH = 10\n\n/**\n * Backstop for an initial-value resolver whose request never settles — e.g.\n * a `client.fetch` parked by the studio's network/CORS error handling.\n * Without it the editor hangs in a loading state and the create-document menu\n * loads forever instead of surfacing the failure. Both call sites\n * (`getInitialValueStream`, `getTemplatePermissions`) time out on this bound.\n *\n * @internal\n */\nexport const RESOLVE_INITIAL_VALUE_TIMEOUT_MS = 10_000\n\ntype ResolveInitialValueForType = <TParams extends Record<string, unknown>>(\n /**\n * This is the name of the document.\n */ type: SchemaType,\n /**\n * Params is a sanity context object passed to every initial value function.\n */\n params: TParams,\n /**\n * Maximum recursion depth (default 9).\n */\n maxDepth: number,\n context: InitialValueResolverContext,\n options?: Options,\n) => Promise<any>\n\nconst memoizeResolveInitialValueForType: (\n fn: ResolveInitialValueForType,\n) => ResolveInitialValueForType = (fn) => {\n const resolveInitialValueForTypeCache = new WeakMap<SchemaType, Map<string, Promise<any>>>()\n\n const stableStringify = (obj: any): string => {\n if (obj !== null && typeof obj === 'object') {\n if (Array.isArray(obj)) {\n return `[${obj.map(stableStringify).join(',')}]`\n }\n const keys = Object.keys(obj).sort()\n return `{${keys\n .map((key) => `${JSON.stringify(key)}:${stableStringify(obj[key])}`)\n .join(',')}}`\n }\n return JSON.stringify(obj)\n }\n\n const hashParameters = (\n params: Record<string, unknown>,\n context: InitialValueResolverContext,\n ): string => {\n return stableStringify({\n params,\n context: {\n schemaName: context.schema.name,\n projectId: context.projectId,\n dataset: context.dataset,\n currentUser: context.currentUser?.id,\n },\n })\n }\n\n return async function resolveInitialValueForType(type, params, maxDepth, context, options) {\n if (!options?.useCache) return fn(type, params, maxDepth, context, options)\n\n let typeCache = resolveInitialValueForTypeCache.get(type)\n\n if (!typeCache) {\n typeCache = new Map<string, Promise<any>>()\n resolveInitialValueForTypeCache.set(type, typeCache)\n }\n\n const hash = hashParameters(params, context)\n\n const cachedResult = typeCache.get(hash)\n if (cachedResult) return cachedResult\n\n const result = await fn(type, params, maxDepth, context, options)\n\n // double check after the await\n if (!typeCache.has(hash)) {\n typeCache.set(hash, result)\n }\n return result\n }\n}\n\n/**\n * Resolve initial value for the given schema type (recursively)\n *\n * @internal\n */\nexport const resolveInitialValueForType = memoizeResolveInitialValueForType(\n (type, params, maxDepth = DEFAULT_MAX_RECURSION_DEPTH, context, options): Promise<any> => {\n if (maxDepth <= 0) {\n return Promise.resolve(undefined)\n }\n\n if (isObjectSchemaType(type)) {\n return postTask(() => resolveInitialObjectValue(type, params, maxDepth, context, options))\n }\n\n if (isArraySchemaType(type)) {\n return postTask(() => resolveInitialArrayValue(type, params, maxDepth, context, options))\n }\n\n return resolveValue(type.initialValue, params, context, options)\n },\n)\n\nasync function resolveInitialArrayValue<Params extends Record<string, unknown>>(\n type: SchemaType,\n params: Params,\n maxDepth: number,\n context: InitialValueResolverContext,\n options?: Options,\n): Promise<any> {\n const initialArray = await resolveValue(type.initialValue, undefined, context, options)\n\n if (!Array.isArray(initialArray)) {\n return undefined\n }\n\n return Promise.all(\n initialArray.map(async (initialItem) => {\n const itemType = getItemType(type as ArraySchemaType, initialItem)!\n return isObjectSchemaType(itemType)\n ? {\n // The initial value defined on the parent array field takes precedence over\n // initial values resolved from the array member type's own fields.\n ...deepAssign(\n (await resolveInitialValueForType(\n itemType,\n params,\n maxDepth - 1,\n context,\n options,\n )) || {},\n initialItem as Record<string, unknown>,\n ),\n _key: randomKey(),\n }\n : initialItem\n }),\n )\n}\n\n/** @internal */\nexport async function resolveInitialObjectValue<Params extends Record<string, unknown>>(\n type: ObjectSchemaType,\n params: Params,\n maxDepth: number,\n context: InitialValueResolverContext,\n options?: Options,\n): Promise<any> {\n const initialObject: Record<string, unknown> = {\n ...((await resolveValue(type.initialValue, params, context, options)) || {}),\n }\n\n const fieldValues: Record<string, any> = {}\n await Promise.all(\n type.fields.map(async (field) => {\n const initialFieldValue = await resolveInitialValueForType(\n field.type,\n params,\n maxDepth - 1,\n context,\n options,\n )\n if (initialFieldValue !== undefined && initialFieldValue !== null) {\n fieldValues[field.name] = initialFieldValue\n }\n }),\n )\n\n const merged = deepAssign(fieldValues, initialObject)\n\n if (isDeepEmpty(merged)) {\n return undefined\n }\n\n if (type.name !== 'object') {\n merged._type = type.name\n }\n\n return merged\n}\n","import {type InitialValueResolverContext, type SanityDocumentLike, type Schema} from '@sanity/types'\nimport {from, merge, type Observable, of} from 'rxjs'\nimport {\n catchError,\n debounceTime,\n distinctUntilChanged,\n filter,\n map,\n scan,\n startWith,\n switchMap,\n timeout,\n} from 'rxjs/operators'\n\nimport {type DocumentPreviewStore} from '../../../preview/documentPreviewStore'\nimport {RESOLVE_INITIAL_VALUE_TIMEOUT_MS, resolveInitialValue} from '../../../templates/resolve'\nimport {type Template} from '../../../templates/types'\nimport {getDraftId, getPublishedId} from '../../../util/draftUtils'\nimport {\n type InitialValueErrorMsg,\n type InitialValueLoadingMsg,\n type InitialValueMsg,\n type InitialValueSuccessMsg,\n} from './types'\n\n/**\n * @hidden\n * @beta */\nexport interface InitialValueOptions {\n documentId: string\n documentType: string\n templateName?: string\n templateParams?: Record<string, any>\n}\n\nconst LOADING_MSG: InitialValueLoadingMsg = {type: 'loading'}\n\n/**\n * @internal\n */\nexport function getInitialValueStream(\n schema: Schema,\n initialValueTemplates: Template[],\n documentPreviewStore: DocumentPreviewStore,\n opts: InitialValueOptions,\n context: InitialValueResolverContext,\n): Observable<InitialValueMsg> {\n const draft$ = documentPreviewStore.observePaths(\n {_type: 'reference', _ref: getDraftId(opts.documentId)},\n ['_type'],\n )\n\n const published$ = documentPreviewStore.observePaths(\n {_type: 'reference', _ref: getPublishedId(opts.documentId)},\n ['_type'],\n )\n\n const value$ = merge(\n draft$.pipe(map((draft) => ({draft}))),\n published$.pipe(map((published) => ({published}))),\n ).pipe(\n scan((prev, res) => ({...prev, ...res}), {}),\n // Wait until we know the state of both draft and published\n filter((res) => 'draft' in res && 'published' in res),\n map((res: any) => res.draft || res.published),\n // Only update if we didn't previously have a document but we now do\n distinctUntilChanged((prev, next) => Boolean(prev) !== Boolean(next)),\n // Prevent rapid re-resolving when transitioning between different templates\n debounceTime(25),\n )\n\n return value$.pipe(\n switchMap((document): Observable<InitialValueMsg> => {\n // Already exists, so no initial value is needed\n if (document) {\n return of({type: 'success', value: null})\n }\n\n if (!opts.templateName) {\n // @todo: Make sure this is the correct behavior\n return of({type: 'success', value: null})\n }\n\n const template = initialValueTemplates.find((t) => t.id === opts.templateName)\n\n if (!template) {\n console.warn('Template \"%s\" not defined, using empty initial value', opts.templateName)\n return of({type: 'success', value: null})\n }\n\n const resolved$ = from(\n resolveInitialValue(schema, template, opts.templateParams, context),\n ).pipe(\n // A resolver whose request is parked (network/CORS) never settles —\n // time it out so the failure surfaces rather than hanging the editor.\n timeout({first: RESOLVE_INITIAL_VALUE_TIMEOUT_MS}),\n map(\n (initialValue): InitialValueSuccessMsg => ({\n type: 'success',\n // The resolver returns an arbitrary record; by contract it's a\n // document-like value (the template's `_type` was merged in).\n value: initialValue as SanityDocumentLike,\n }),\n ),\n catchError((resolveError: Error) => {\n // oxlint-disable no-console\n console.group('Failed to resolve initial value')\n console.error(resolveError)\n console.error('Template ID: %s', opts.templateName)\n console.error('Parameters: %o', opts.templateParams)\n console.groupEnd()\n // oxlint-enable no-console\n\n // Carry the original error so the consumer can classify it\n // (a network/5xx failure in a resolver's `client.fetch` is\n // delegated to the studio's request-error dialog) and re-throwing\n // resolver bugs stay caller-domain.\n const msg: InitialValueErrorMsg = {type: 'error', error: resolveError}\n return of(msg)\n }),\n )\n\n return merge(of<InitialValueMsg>(LOADING_MSG), resolved$)\n }),\n\n startWith(LOADING_MSG),\n distinctUntilChanged(),\n )\n}\n","import {type ClientPerspective, type SanityClient} from '@sanity/client'\nimport {asyncScheduler, defer, merge, type Observable, of, partition, throwError, timer} from 'rxjs'\nimport {exhaustMapWithTrailing} from 'rxjs-exhaustmap-with-trailing'\nimport {filter, mergeMap, share, take, throttleTime} from 'rxjs/operators'\n\nimport {type MutationEvent, type ReconnectEvent, type WelcomeEvent} from './types'\n\n/** @internal */\nexport type ListenQueryParams = Record<string, string | number | boolean | string[]>\n\n/**\n * @hidden\n * @beta */\nexport interface ListenQueryOptions {\n tag?: string\n apiVersion?: string\n perspective?: ClientPerspective\n throttleTime?: number\n transitions?: ('update' | 'appear' | 'disappear')[]\n}\n\nconst fetch = (\n client: SanityClient,\n query: string,\n params: ListenQueryParams,\n options: ListenQueryOptions,\n) =>\n defer(() =>\n client.observable.fetch(query, params, {\n tag: options.tag,\n filterResponse: true,\n perspective: options.perspective,\n }),\n )\n\nconst listen = (\n client: SanityClient,\n query: string,\n params: ListenQueryParams,\n options: ListenQueryOptions,\n) =>\n defer(() =>\n client.listen(query, params, {\n events: ['welcome', 'mutation', 'reconnect'],\n includeResult: false,\n visibility: 'query',\n includeAllVersions: true,\n tag: options.tag,\n }),\n ) as Observable<ReconnectEvent | WelcomeEvent | MutationEvent>\n\nfunction isWelcomeEvent(\n event: MutationEvent | ReconnectEvent | WelcomeEvent,\n): event is WelcomeEvent {\n return event.type === 'welcome'\n}\n\n/** @internal */\nexport function listenQuery(\n client: SanityClient,\n query: string | {fetch: string; listen: string},\n params: ListenQueryParams = {},\n options: ListenQueryOptions = {},\n): Observable<any> {\n const fetchQuery = typeof query === 'string' ? query : query.fetch\n const listenerQuery = typeof query === 'string' ? query : query.listen\n\n const events$ = listen(client, listenerQuery, params, options).pipe(\n mergeMap((ev, i) => {\n const isFirst = i === 0\n if (isFirst && !isWelcomeEvent(ev)) {\n // if the first event is not welcome, it is most likely a reconnect and\n // if it's not a reconnect something is very wrong\n return throwError(\n () =>\n new Error(\n ev.type === 'reconnect'\n ? 'Could not establish EventSource connection'\n : `Received unexpected type of first event \"${ev.type}\"`,\n ),\n )\n }\n return of(ev)\n }),\n share(),\n )\n\n const [welcome$, mutationAndReconnect$] = partition(events$, isWelcomeEvent)\n const isRelevantEvent = (event: MutationEvent | ReconnectEvent | WelcomeEvent): boolean => {\n if (!options.transitions || event.type !== 'mutation') {\n return true\n }\n\n return options.transitions.includes(event.transition)\n }\n\n const doFetch = () => fetch(client, fetchQuery, params, options)\n\n return merge(\n welcome$.pipe(take(1)),\n mutationAndReconnect$.pipe(\n filter(isRelevantEvent),\n throttleTime(options.throttleTime || 1000, asyncScheduler, {leading: true, trailing: true}),\n ),\n ).pipe(\n exhaustMapWithTrailing((event) => {\n if (event.type === 'mutation' && event.visibility !== 'query') {\n // Even though the listener request specifies visibility=query, the events are not guaranteed to be delivered with visibility=query\n // If the event we are responding to arrives with visibility != query, we add a little delay to allow for the updated document to be available for queries\n // See https://www.sanity.io/docs/listening#visibility-c4786e55c3ff\n return timer(1200).pipe(mergeMap(doFetch))\n }\n return doFetch()\n }),\n )\n}\n","import {type DocumentPairTarget} from './types'\n\n/**\n * Normalizes the `version` parameter accepted by the document pair APIs\n * (`useDocumentOperation`, `pair.editOperations`) to a {@link DocumentPairTarget}.\n *\n * A bare string is back-compat shorthand for a plain version target — the scope id, i.e. the\n * `<scopeId>` segment of `versions.<scopeId>.<groupId>` (a release or agent/anonymous bundle\n * name); target objects pass through by reference, and `undefined` means the base\n * draft/published pair.\n *\n */\nexport function normalizeDocumentPairTarget(\n version: string | DocumentPairTarget | undefined,\n): DocumentPairTarget | undefined {\n if (typeof version === 'string') {\n return {kind: 'version', scopeId: version}\n }\n return version\n}\n\n/**\n * The scope id (the `<scopeId>` segment of `versions.<scopeId>.<groupId>`) the pair should check\n * out for a target, or `undefined` when the base draft/published pair applies. Guarded kinds\n * (`target-missing`, `unresolved`) never reach pair checkout and yield `undefined`.\n *\n */\nexport function getPairTargetScopeId(target: DocumentPairTarget | undefined): string | undefined {\n if (target?.kind === 'version' || target?.kind === 'variant') {\n return target.scopeId\n }\n return undefined\n}\n","import {type SanityClient} from '@sanity/client'\nimport {type Observable, of} from 'rxjs'\n\nimport {getPublishedId} from '../../util/draftUtils'\n\nexport function resolveTypeForDocument(\n client: SanityClient,\n id: string,\n specifiedType = '*',\n): Observable<string> {\n // if is resolved document type\n if (specifiedType && specifiedType !== '*') {\n return of(specifiedType)\n }\n\n const query = '*[sanity::versionOf($publishedId)][0]._type'\n\n return client.observable.fetch(\n query,\n {publishedId: getPublishedId(id)},\n {\n tag: 'document.resolve-type',\n },\n )\n}\n","import {type SanityClient} from '@sanity/client'\nimport {type CurrentUser, type InitialValueResolverContext, type Schema} from '@sanity/types'\nimport {type Observable, of} from 'rxjs'\nimport {filter, map} from 'rxjs/operators'\n\nimport {type SourceClientOptions} from '../../config/types'\nimport {type LocaleSource} from '../../i18n/types'\nimport {type DocumentPreviewStore} from '../../preview/documentPreviewStore'\nimport {DEFAULT_STUDIO_CLIENT_OPTIONS} from '../../studioClient'\nimport {type Template} from '../../templates/types'\nimport {\n getPublishedId,\n getVersionFromId,\n isDraftId,\n isVersionId,\n getIdPair,\n} from '../../util/draftUtils'\nimport {getDocumentVariantType} from '../../util/getDocumentVariantType'\nimport {type ValidationStatus} from '../../validation'\nimport {type HistoryStore} from '../history/createHistoryStore'\nimport {\n checkoutPair,\n type CommitError,\n type DocumentVersionEvent,\n type Pair,\n} from './document-pair/checkoutPair'\nimport {commitErrorStatus} from './document-pair/commitErrorStatus'\nimport {consistencyStatus} from './document-pair/consistencyStatus'\nimport {documentEvents} from './document-pair/documentEvents'\nimport {editOperations} from './document-pair/editOperations'\nimport {editState, type EditStateFor} from './document-pair/editState'\nimport {\n type OperationError,\n operationEvents,\n type OperationSuccess,\n} from './document-pair/operationEvents'\nimport {GUARDED, TARGET_NOT_FOUND_OPERATIONS} from './document-pair/operations/helpers'\nimport {type OperationsAPI} from './document-pair/operations/types'\nimport {validation} from './document-pair/validation'\nimport {type DocumentStoreExtraOptions} from './getPairListener'\nimport {getInitialValueStream, type InitialValueOptions} from './initialValue/initialValue'\nimport {type InitialValueMsg} from './initialValue/types'\nimport {listenQuery, type ListenQueryOptions} from './listenQuery'\nimport {getPairTargetScopeId, normalizeDocumentPairTarget} from './normalizeDocumentPairTarget'\nimport {resolveTypeForDocument} from './resolveTypeForDocument'\nimport {type DocumentPairTarget, type IdPair} from './types'\n\n/**\n * @hidden\n * @beta */\nexport type QueryParams = Record<string, string | number | boolean | string[]>\n\nfunction getIdPairFromPublished(publishedId: string, version?: string): IdPair {\n if (version === 'published' || version === 'drafts') {\n throw new Error('Version Id cannot be \"published\" or \"drafts\"')\n }\n if (isVersionId(publishedId)) {\n throw new Error('editOpsOf does not expect a version id.')\n }\n if (isDraftId(publishedId)) {\n throw new Error('editOpsOf does not expect a draft id.')\n }\n\n return getIdPair(publishedId, {version})\n}\n\n/**\n * @hidden\n * @beta */\nexport interface DocumentStore {\n /**\n * Checks out a document (with its published and draft version) for real-time editing.\n * Note that every call to this function will open a new listener to the server.\n * It's recommended to use the helper functions on `pair` below which will re-use a single connection.\n *\n * @internal\n **/\n checkoutPair: (idPair: IdPair) => Pair\n initialValue: (\n opts: InitialValueOptions,\n context: InitialValueResolverContext,\n ) => Observable<InitialValueMsg>\n listenQuery: (\n query: string | {fetch: string; listen: string},\n params: QueryParams,\n options: ListenQueryOptions,\n ) => Observable<any>\n resolveTypeForDocument: (id: string, specifiedType?: string) => Observable<string>\n\n pair: {\n /** @internal */\n commitErrorStatus: (\n publishedId: string,\n type: string,\n version?: string,\n ) => Observable<CommitError | undefined>\n consistencyStatus: (publishedId: string, type: string, version?: string) => Observable<boolean>\n /** @internal */\n documentEvents: (\n publishedId: string,\n type: string,\n version?: string,\n ) => Observable<DocumentVersionEvent>\n /**\n * @internal\n * `version` accepts either a plain version name (release/bundle) or a\n * {@link DocumentPairTarget}. The guarded target kinds (`unresolved`, `target-missing`) emit\n * a disabled operations API without checking out a pair, so operations can never reach the\n * base draft/published pair while a selected target is unresolved or has no document.\n */\n editOperations: (\n publishedId: string,\n type: string,\n version?: string | DocumentPairTarget,\n ) => Observable<OperationsAPI>\n editState: (publishedId: string, type: string, version?: string) => Observable<EditStateFor>\n operationEvents: (\n publishedId: string,\n type: string,\n ) => Observable<OperationSuccess | OperationError>\n validation: (\n validationTargetId: string,\n type: string,\n // Whether to require referenced documents to be published\n // if `true`, any reference to a document that's not published will yield a validation error\n // if `false`, any reference to a non-published document is ok as long as it's in the same bundle\n // as the document we're validating\n validatePublishedReferences: boolean,\n ) => Observable<ValidationStatus>\n }\n}\n\n/** @internal */\nexport interface DocumentStoreOptions {\n getClient: (options: SourceClientOptions) => SanityClient\n documentPreviewStore: DocumentPreviewStore\n historyStore: HistoryStore\n schema: Schema\n initialValueTemplates: Template[]\n i18n: LocaleSource\n /**\n * @deprecated Does nothing. Preserved to avoid breaking changes.\n * Will be removed in the next major version.\n */\n serverActionsEnabled?: Observable<boolean>\n extraOptions?: DocumentStoreExtraOptions\n currentUser?: Omit<CurrentUser, 'role'> | null\n}\n\n/** @internal */\nexport function createDocumentStore({\n getClient,\n documentPreviewStore,\n historyStore,\n initialValueTemplates,\n schema,\n i18n,\n extraOptions = {},\n currentUser,\n}: DocumentStoreOptions): DocumentStore {\n const observeDocumentPairAvailability =\n documentPreviewStore.unstable_observeDocumentPairAvailability\n\n // Note that we're both passing a shared `client` here which is used by the\n // internal operations, and a `getClient` method that we expose to user-land\n // for things like validations\n const client = getClient(DEFAULT_STUDIO_CLIENT_OPTIONS)\n\n const {\n onSyncErrorRecovery,\n onReportLatency,\n onSlowCommit,\n onReportMutationPerformance,\n onDocumentRebase,\n } = extraOptions\n const ctx = {\n client,\n getClient,\n observeDocumentPairAvailability,\n historyStore,\n schema,\n i18n,\n extraOptions,\n currentUser,\n }\n\n return {\n // Public API\n checkoutPair(idPair) {\n return checkoutPair(client, idPair, undefined, {\n onSyncErrorRecovery,\n onReportLatency,\n onSlowCommit,\n onReportMutationPerformance,\n onDocumentRebase,\n })\n },\n initialValue(opts, context) {\n return getInitialValueStream(\n schema,\n initialValueTemplates,\n documentPreviewStore,\n opts,\n context,\n )\n },\n listenQuery(query, params, listenQueryOptions) {\n return listenQuery(client, query, params, listenQueryOptions)\n },\n resolveTypeForDocument(id, specifiedType) {\n return resolveTypeForDocument(client, id, specifiedType)\n },\n pair: {\n commitErrorStatus(publishedId, type, version) {\n return commitErrorStatus(\n ctx.client,\n getIdPairFromPublished(publishedId, version),\n type,\n extraOptions,\n )\n },\n consistencyStatus(publishedId, type, version) {\n return consistencyStatus(\n ctx.client,\n getIdPairFromPublished(publishedId, version),\n type,\n extraOptions,\n )\n },\n documentEvents(publishedId, type, version) {\n return documentEvents(\n ctx.client,\n getIdPairFromPublished(publishedId, version),\n type,\n extraOptions,\n )\n },\n editOperations(publishedId, type, version) {\n const target = normalizeDocumentPairTarget(version)\n\n // Guarded targets never check out a pair. Branching here (before the memoized\n // `editOperations`) also keeps them out of `memoizeKeyGen`, which only keys on\n // `publishedId + versionId` and would collide these with the base pair.\n if (target?.kind === 'unresolved') {\n return of(GUARDED)\n }\n if (target?.kind === 'target-missing') {\n return of(TARGET_NOT_FOUND_OPERATIONS)\n }\n\n return editOperations(\n ctx,\n getIdPairFromPublished(publishedId, getPairTargetScopeId(target)),\n type,\n )\n },\n editState(publishedId, type, version) {\n const idPair = getIdPairFromPublished(publishedId, version)\n\n const edit = editState(ctx, idPair, type)\n return edit\n },\n operationEvents(publishedId, type) {\n return operationEvents({\n client,\n historyStore,\n schema,\n extraOptions,\n }).pipe(\n filter(\n (result) =>\n result.args.idPair.publishedId === publishedId && result.args.typeName === type,\n ),\n map((result): OperationSuccess | OperationError => {\n const {operationName, idPair} = result.args\n return result.type === 'success'\n ? {\n type: 'success',\n op: operationName,\n id: idPair.publishedId,\n idPair,\n }\n : {\n type: 'error',\n op: operationName,\n id: idPair.publishedId,\n error: result.error,\n idPair,\n }\n }),\n )\n },\n validation(validationTargetId, type, requirePublishedReferences) {\n const publishedId = getPublishedId(validationTargetId)\n const idPair = getIdPair(publishedId, {version: getVersionFromId(validationTargetId)})\n const validationTarget = getDocumentVariantType(validationTargetId)\n return validation(ctx, idPair, type, validationTarget, requirePublishedReferences)\n },\n },\n }\n}\n","import { asapScheduler, NEVER, Subject, timer, using, } from \"rxjs\";\r\nimport { scan, switchMap, tap } from \"rxjs/operators\";\r\nexport function refCountDelay(duration, scheduler = asapScheduler) {\r\n return (source) => {\r\n const connectable = source;\r\n let connectableSubscription = null;\r\n let connectorSubscription = null;\r\n const notifier = new Subject();\r\n const connector = notifier.pipe(scan((count, step) => count + step, 0), switchMap((count) => {\r\n if (count === 0) {\r\n return timer(duration, scheduler).pipe(tap(() => {\r\n if (connectableSubscription) {\r\n connectableSubscription.unsubscribe();\r\n connectableSubscription = null;\r\n }\r\n if (connectorSubscription) {\r\n connectorSubscription.unsubscribe();\r\n connectorSubscription = null;\r\n }\r\n }));\r\n }\r\n if (!connectableSubscription && count > 0) {\r\n return timer(0, scheduler).pipe(tap(() => {\r\n if (!connectableSubscription) {\r\n connectableSubscription = connectable.connect();\r\n }\r\n }));\r\n }\r\n return NEVER;\r\n }));\r\n return using(() => {\r\n if (!connectorSubscription) {\r\n connectorSubscription = connector.subscribe();\r\n }\r\n notifier.next(1);\r\n return { unsubscribe: () => notifier.next(-1) };\r\n }, () => source);\r\n };\r\n}\r\nexport const refCountAuditTime = refCountDelay;\r\n//# sourceMappingURL=refCountDelay.js.map","import {concat, fromEvent, of} from 'rxjs'\nimport {distinctUntilChanged, map} from 'rxjs/operators'\n\nconst DEBUG_PREFIX = '_debug_'\n\nconst hashchange$ = typeof window === 'undefined' ? of({}) : fromEvent(window, 'hashchange')\n\nexport const debugParams$ = concat(of(0), hashchange$).pipe(\n map(() => (typeof document === 'undefined' ? '#' : document.location.hash)),\n distinctUntilChanged(),\n map((hash) =>\n hash\n .slice(1)\n .split(';')\n .filter((p) => p.toLowerCase().startsWith(DEBUG_PREFIX))\n .map((param) => param.slice(DEBUG_PREFIX.length)),\n ),\n)\n\nexport const debugRolesParam$ = debugParams$.pipe(\n map((args) => args.find((arg) => arg.startsWith('roles='))),\n map(\n (arg) =>\n arg\n ?.split('roles=')[1]\n .split(',')\n .map((r) => r.trim()) || [],\n ),\n)\n","// NOTE: these example grants are used in other test files.\n// if you change this file, check to see if other files need to be updated too\nimport {type Grant} from '../types'\n\nexport const administrator: Grant[] = [\n {\n filter: '_id in path(\"**\")',\n permissions: ['read', 'create', 'history', 'update'],\n },\n]\n\nexport const editor: Grant[] = [\n {\n filter: '_id in path(\"**\")',\n permissions: ['read', 'create', 'history', 'update'],\n },\n]\n\nexport const developer: Grant[] = [\n {\n filter: '_id in path(\"**\")',\n permissions: ['read', 'create', 'history', 'update'],\n },\n]\n\nexport const contributor: Grant[] = [\n {\n filter: '_id in path(\"**\")',\n permissions: ['read'],\n },\n {\n filter: '_id in path(\"drafts.**\")',\n permissions: ['create', 'history', 'update'],\n },\n]\n\nexport const viewer: Grant[] = [\n {\n filter: '_id in path(\"**\")',\n permissions: ['read', 'history'],\n },\n]\n\nexport const requiresApproval: Grant[] = [\n {\n filter: '!locked',\n permissions: ['read', 'create', 'update'],\n },\n]\n\nexport const restricted: Grant[] = [\n {\n filter:\n '_id in path(\"drafts.**\") && _type in [\"stringsTest\", \"book\", \"author\", \"referenceTest\"]',\n permissions: ['read', 'create', 'history', 'update'],\n },\n {\n filter: '_id in path(\"**\")',\n permissions: ['read'],\n },\n]\n","import {map} from 'rxjs/operators'\n\nimport {debugRolesParam$} from '../../debugParams/debugParams'\nimport {type Grant} from '../types'\nimport * as grants from './exampleGrants'\nimport {type ExampleRoleName} from './exampleRoles'\n\nconst DEBUG_ROLE_GRANTS_MAP: Record<ExampleRoleName, Grant[]> = {\n // basic\n administrator: grants.administrator,\n editor: grants.editor,\n developer: grants.developer,\n contributor: grants.contributor,\n viewer: grants.viewer,\n\n // custom\n restricted: grants.restricted,\n requiresApproval: grants.requiresApproval,\n\n // legacy\n read: grants.viewer,\n write: grants.editor,\n}\n\n// todo: merge other resource keys(?)\nexport const debugGrants$ = debugRolesParam$.pipe(\n map((roles) => {\n if (!roles.length) return null\n\n return roles\n .filter((value) => Boolean(value) && value in DEBUG_ROLE_GRANTS_MAP)\n .flatMap((roleName: ExampleRoleName) => DEBUG_ROLE_GRANTS_MAP[roleName] || [])\n }),\n)\n","import {type SanityClient} from '@sanity/client'\nimport {type CurrentUser, type SanityDocument} from '@sanity/types'\nimport {evaluate, parse} from 'groq-js'\nimport {defer, of} from 'rxjs'\nimport {refCountDelay} from 'rxjs-etc/operators'\nimport {distinctUntilChanged, publishReplay, switchMap} from 'rxjs/operators'\nimport shallowEquals from 'shallow-equals'\n\nimport {type StoreRequestErrorHandler} from '../requestErrorHandler'\nimport {debugGrants$} from './debug'\nimport {\n type DocumentValuePermission,\n type EvaluationParams,\n type Grant,\n type GrantsStore,\n type PermissionCheckResult,\n} from './types'\n\nasync function getDatasetGrants(\n client: SanityClient,\n projectId: string,\n dataset: string,\n errorHandler: StoreRequestErrorHandler | undefined,\n): Promise<Grant[]> {\n // `acl` stands for access control list and returns a list of grants\n const fetchGrants = () =>\n client.request<Grant[]>({\n uri: `/projects/${projectId}/datasets/${dataset}/acl`,\n tag: 'acl.get',\n })\n\n // Every permission check depends on this read, so there is no local\n // recovery if it fails — delegate failures to the error handler when one\n // is provided. Retryable: it's an idempotent GET, safe to re-run.\n return errorHandler ? errorHandler.attempt(fetchGrants, {retryable: true}) : fetchGrants()\n}\n\nfunction getParams(userId: string | null): EvaluationParams {\n const params: EvaluationParams = {}\n\n if (userId !== null) {\n params.identity = userId\n }\n\n return params\n}\n\nconst PARSED_FILTERS_MEMO = new Map()\nasync function matchesFilter(userId: string | null, filter: string, document: SanityDocument) {\n if (!PARSED_FILTERS_MEMO.has(filter)) {\n // note: it might be tempting to also memoize the result of the evaluation here,\n // Currently these filters are typically evaluated whenever a document change, which means they will be evaluated\n // quite frequently with different versions of the document. There might be some gains in finding out which subset of document\n // properties to use as key (e.g. by looking at the parsed filter and see what properties the filter cares about)\n // But as always, it's worth considering if the complexity/memory usage is worth the potential perf gain…\n PARSED_FILTERS_MEMO.set(filter, parse(`*[${filter}]`))\n }\n const parsed = PARSED_FILTERS_MEMO.get(filter)\n\n const evalParams = getParams(userId)\n const {identity} = evalParams\n const params: Record<string, unknown> = {...evalParams}\n const data = await (await evaluate(parsed, {dataset: [document], identity, params})).get()\n return data?.length === 1\n}\ninterface GrantsStoreOptionsCurrentUser {\n client: SanityClient\n /**\n * Optional handler for failures of requests made by the store. When\n * omitted, request failures propagate to the permission streams.\n */\n errorHandler?: StoreRequestErrorHandler\n /**\n * @deprecated The `currentUser` option is deprecated. Use `userId` instead.\n */\n currentUser: CurrentUser | null\n}\n\ninterface GrantsStoreOptionsUserId {\n client: SanityClient\n /**\n * Optional handler for failures of requests made by the store. When\n * omitted, request failures propagate to the permission streams.\n */\n errorHandler?: StoreRequestErrorHandler\n userId: string | null\n}\n\n/** @internal */\nexport type GrantsStoreOptions = GrantsStoreOptionsCurrentUser | GrantsStoreOptionsUserId\n\n/** @internal */\nexport function createGrantsStore(opts: GrantsStoreOptions): GrantsStore {\n const {client, errorHandler} = opts\n const versionedClient = client.withConfig({apiVersion: '2021-06-07'})\n const userId = 'userId' in opts ? opts.userId : opts?.currentUser?.id || null\n\n const datasetGrants$ = defer(() => of(versionedClient.config())).pipe(\n switchMap(({projectId, dataset}) => {\n if (!projectId || !dataset) {\n throw new Error('Missing projectId or dataset')\n }\n return getDatasetGrants(versionedClient, projectId, dataset, errorHandler)\n }),\n )\n\n const currentUserDatasetGrants = debugGrants$.pipe(\n switchMap((debugGrants) => (debugGrants ? of(debugGrants) : datasetGrants$)),\n publishReplay(1),\n refCountDelay(1000),\n )\n\n return {\n checkDocumentPermission(permission: DocumentValuePermission, document: SanityDocument) {\n return currentUserDatasetGrants.pipe(\n switchMap((grants) => grantsPermissionOn(userId, grants, permission, document)),\n distinctUntilChanged(shallowEquals),\n )\n },\n }\n}\n\n/**\n * @internal\n * Takes a grants object, a permission and a document\n * checks whether the permission is granted for the given document\n */\nexport async function grantsPermissionOn(\n userId: string | null,\n grants: Grant[],\n permission: DocumentValuePermission,\n document: SanityDocument | null,\n): Promise<PermissionCheckResult> {\n if (!document) {\n // we say it's granted if null due to initial states\n return {granted: true, reason: 'Null document, nothing to check'}\n }\n\n if (!grants.length) {\n return {granted: false, reason: 'No document grants'}\n }\n\n const matchingGrants: Grant[] = []\n\n for (const grant of grants) {\n if (await matchesFilter(userId, grant.filter, document)) {\n matchingGrants.push(grant)\n }\n }\n\n const foundMatch = matchingGrants.some((grant) => grant.permissions.some((p) => p === permission))\n\n return {\n granted: foundMatch,\n reason: foundMatch ? `Matching grant` : `No matching grants found`,\n }\n}\n","/** @internal */\nexport const isDev = process.env.NODE_ENV !== 'production'\n\n/** @internal */\nexport const isProd = !isDev\n","import {type MendozaEffectPair, type MendozaPatch} from '@sanity/types'\n\nimport {type Chunk, type ChunkType} from '../../../field/types'\nimport {type Transaction} from './types'\n\nfunction canMergeEdit(type: ChunkType) {\n return type === 'create' || type === 'editDraft'\n}\n\nconst CHUNK_WINDOW = 5 * 60 * 1000 // 5 minutes\n\nfunction isWithinMergeWindow(a: string, b: string) {\n return Date.parse(b) - Date.parse(a) < CHUNK_WINDOW\n}\n\nexport function mergeChunk(left: Chunk, right: Chunk): Chunk | [Chunk, Chunk] {\n if (left.end !== right.start) throw new Error('chunks are not next to each other')\n\n // TODO: How to detect first squash/create\n\n const draftState = combineState(left.draftState, right.draftState)\n const publishedState = combineState(left.publishedState, right.publishedState)\n\n if (left.type === 'delete' && right.type === 'editDraft') {\n return [left, {...right, type: 'create', draftState, publishedState}]\n }\n\n // Convert deletes into either discardDraft or unpublish depending on what's been deleted.\n if (right.type === 'delete') {\n if (draftState === 'missing' && publishedState === 'present') {\n return [left, {...right, type: 'discardDraft', draftState, publishedState}]\n }\n\n if (draftState === 'present' && publishedState === 'missing') {\n return [left, {...right, type: 'unpublish', draftState, publishedState}]\n }\n }\n\n if (\n canMergeEdit(left.type) &&\n right.type === 'editDraft' &&\n isWithinMergeWindow(left.endTimestamp, right.startTimestamp)\n ) {\n const authors = new Set<string>()\n for (const author of left.authors) authors.add(author)\n for (const author of right.authors) authors.add(author)\n\n return {\n index: 0,\n id: right.id,\n type: left.type,\n start: left.start,\n end: right.end,\n startTimestamp: left.startTimestamp,\n endTimestamp: right.endTimestamp,\n authors,\n draftState,\n publishedState,\n }\n }\n\n return [left, {...right, draftState, publishedState}]\n}\n\ntype ChunkState = 'unedited' | 'deleted' | 'upsert'\nfunction getChunkState(effect?: MendozaEffectPair): ChunkState {\n const modified = Boolean(effect)\n const deleted = effect && isDeletePatch(effect?.apply)\n\n if (deleted) {\n return 'deleted'\n }\n\n if (modified) {\n return 'upsert'\n }\n\n return 'unedited'\n}\n\n/*\n * getChunkType tries to determine what effect the given transaction had on the document\n * More information about the logic can be found here https://github.com/sanity-io/sanity/pull/2633#issuecomment-886461812\n *\n * | | draft unedited | draft deleted | draft upsert |\n * |--------------------|----------------|---------------|--------------|\n * | published unedited | X | delete | editDraft |\n * | published deleted | delete | delete | delete |\n * | published upsert | liveEdit | publish | liveEdit |\n */\nfunction getChunkType(transaction: Transaction): ChunkType {\n const draftState = getChunkState(transaction.draftEffect)\n const publishedState = getChunkState(transaction.publishedEffect)\n\n if (publishedState === 'unedited') {\n if (draftState === 'deleted') {\n return 'delete'\n }\n\n if (draftState === 'upsert') {\n return 'editDraft'\n }\n }\n\n if (publishedState === 'deleted') {\n return 'delete'\n }\n\n if (publishedState === 'upsert') {\n if (draftState === 'unedited') {\n return 'editLive'\n }\n\n if (draftState === 'deleted') {\n return 'publish'\n }\n\n if (draftState === 'upsert') {\n return 'editLive'\n }\n }\n\n return 'editLive'\n}\n\nexport function chunkFromTransaction(transaction: Transaction): Chunk {\n const modifiedDraft = Boolean(transaction.draftEffect)\n const modifiedPublished = Boolean(transaction.publishedEffect)\n\n const draftDeleted = transaction.draftEffect && isDeletePatch(transaction.draftEffect.apply)\n const publishedDeleted =\n transaction.publishedEffect && isDeletePatch(transaction.publishedEffect.apply)\n\n const type = getChunkType(transaction)\n\n return {\n index: 0,\n id: transaction.id,\n type,\n start: transaction.index,\n end: transaction.index + 1,\n startTimestamp: transaction.timestamp,\n endTimestamp: transaction.timestamp,\n authors: new Set([transaction.author]),\n draftState: modifiedDraft ? (draftDeleted ? 'missing' : 'present') : 'unknown',\n publishedState: modifiedPublished ? (publishedDeleted ? 'missing' : 'present') : 'unknown',\n }\n}\n\nfunction combineState(\n left: 'present' | 'missing' | 'unknown',\n right: 'present' | 'missing' | 'unknown',\n) {\n return right === 'unknown' ? left : right\n}\n\nfunction isDeletePatch(patch: MendozaPatch): boolean {\n return patch[0] === 0 && patch[1] === null\n}\n","import {type Annotation} from '../../../field/types'\nimport {type CombinedDocument} from './types'\n\nexport function isSameAnnotation(a: Annotation, b: Annotation): boolean {\n if (a && b) {\n return a.author === b.author && a.timestamp === b.timestamp\n }\n\n if (!a && !b) {\n return true\n }\n\n return false\n}\n\nexport function getAttrs(doc: CombinedDocument): Record<string, unknown> | null {\n return doc.draft || doc.published\n}\n","import {\n type ArrayInput,\n type Diff,\n diffInput,\n type Input,\n type ObjectInput,\n type StringInput,\n wrap,\n} from '@sanity/diff'\nimport {type incremental} from 'mendoza'\n\nimport {type Annotation, type Chunk} from '../../../field/types'\nimport {type Timeline} from './Timeline'\nimport {isSameAnnotation} from './utils'\n\nexport type Meta = {chunk: Chunk; transactionIndex: number} | null\n\nexport type AnnotationExtractor<T> = {\n fromValue(value: incremental.Value<T>): Annotation\n fromMeta(meta: T): Annotation\n}\n\nclass ArrayContentWrapper<T> implements ArrayInput<Annotation> {\n type = 'array' as const\n value: unknown[]\n length: number\n annotation: Annotation\n extractor: AnnotationExtractor<T>\n\n private content: incremental.ArrayContent<T>\n private elements: Input<Annotation>[] = []\n\n constructor(\n content: incremental.ArrayContent<T>,\n value: unknown[],\n annotation: Annotation,\n extractor: AnnotationExtractor<T>,\n ) {\n this.content = content\n this.value = value\n this.annotation = annotation\n this.extractor = extractor\n this.length = content.elements.length\n }\n\n at(idx: number) {\n if (idx >= this.length) throw new Error('out of bounds')\n const input = this.elements[idx]\n if (input) {\n return input\n }\n return (this.elements[idx] = wrapValue(\n this.content.elements[idx],\n this.value[idx],\n this.extractor,\n ))\n }\n\n annotationAt(idx: number): Annotation {\n const meta = this.content.metas[idx]\n return this.extractor.fromMeta(meta)\n }\n}\n\nclass ObjectContentWrapper<T> implements ObjectInput<Annotation> {\n type = 'object' as const\n value: Record<string, unknown>\n keys: string[]\n annotation: Annotation\n extractor: AnnotationExtractor<T>\n\n private content: incremental.ObjectContent<T>\n private fields: Record<string, Input<Annotation>> = {}\n\n constructor(\n content: incremental.ObjectContent<T>,\n value: Record<string, unknown>,\n annotation: Annotation,\n extractor: AnnotationExtractor<T>,\n ) {\n this.content = content\n this.value = value\n this.annotation = annotation\n this.extractor = extractor\n this.keys = Object.keys(content.fields)\n }\n\n get(key: string) {\n const input = this.fields[key]\n if (input) {\n return input\n }\n const value = this.content.fields[key]\n if (!value) return undefined\n return (this.fields[key] = wrapValue(value, this.value[key], this.extractor))\n }\n}\n\nclass StringContentWrapper<T> implements StringInput<Annotation> {\n type = 'string' as const\n value: string\n annotation: Annotation\n extractor: AnnotationExtractor<T>\n\n private content: incremental.StringContent<T>\n\n constructor(\n content: incremental.StringContent<T>,\n value: string,\n annotation: Annotation,\n extractor: AnnotationExtractor<T>,\n ) {\n this.content = content\n this.value = value\n this.annotation = annotation\n this.extractor = extractor\n }\n\n sliceAnnotation(start: number, end: number): {text: string; annotation: Annotation}[] {\n const result: {text: string; annotation: Annotation}[] = []\n let idx = 0\n\n function push(text: string, annotation: Annotation) {\n if (result.length > 0) {\n const lst = result[result.length - 1]\n if (isSameAnnotation(lst.annotation, annotation)) {\n lst.text += text\n return\n }\n }\n\n result.push({text, annotation})\n }\n\n for (const part of this.content.parts) {\n const length = part.value.length\n\n const subStart = Math.max(0, start - idx)\n if (subStart < length) {\n // The start of the slice is inside this part somewhere.\n\n // Figure out where the end is:\n const subEnd = Math.min(length, end - idx)\n\n // If the end of the slice is before this part, then we're guaranteed\n // that there are no more parts.\n if (subEnd <= 0) break\n\n push(part.value.slice(subStart, subEnd), this.extractor.fromValue(part))\n }\n\n idx += length\n }\n\n return result\n }\n}\n\nexport function wrapValue<T>(\n value: incremental.Value<T>,\n raw: unknown,\n extractor: AnnotationExtractor<T>,\n): Input<Annotation> {\n const annotation = extractor.fromValue(value)\n\n if (value.content) {\n switch (value.content.type) {\n case 'array':\n return new ArrayContentWrapper<T>(value.content, raw as unknown[], annotation, extractor)\n case 'object':\n return new ObjectContentWrapper<T>(\n value.content,\n raw as Record<string, unknown>,\n annotation,\n extractor,\n )\n case 'string':\n return new StringContentWrapper<T>(value.content, raw as string, annotation, extractor)\n default:\n // do nothing\n }\n }\n\n return wrap(raw, annotation)\n}\n\nfunction extractAnnotationForFromInput(\n timeline: Timeline,\n firstChunk: Chunk | null,\n meta: Meta,\n): Annotation {\n if (meta) {\n // The next transaction is where it disappeared:\n return annotationForTransactionIndex(timeline, meta.transactionIndex + 1, meta.chunk.index)\n } else if (firstChunk) {\n return annotationForTransactionIndex(timeline, firstChunk.start, firstChunk.index)\n }\n\n return null\n}\n\nfunction extractAnnotationForToInput(timeline: Timeline, meta: Meta): Annotation {\n if (meta) {\n return annotationForTransactionIndex(timeline, meta.transactionIndex, meta.chunk.index)\n }\n\n return null\n}\n\nfunction annotationForTransactionIndex(timeline: Timeline, idx: number, chunkIdx?: number) {\n const tx = timeline.transactionByIndex(idx)\n if (!tx) return null\n\n const chunk = timeline.chunkByTransactionIndex(idx, chunkIdx)\n if (!chunk) return null\n\n return {\n chunk,\n timestamp: tx.timestamp,\n author: tx.author,\n }\n}\n\nexport function diffValue(\n timeline: Timeline,\n firstChunk: Chunk | null,\n from: incremental.Value<Meta>,\n fromRaw: unknown,\n to: incremental.Value<Meta>,\n toRaw: unknown,\n): Diff<Annotation> {\n const fromInput = wrapValue<Meta>(from, fromRaw, {\n fromValue(value) {\n return extractAnnotationForFromInput(timeline, firstChunk, value.endMeta)\n },\n fromMeta(meta) {\n return extractAnnotationForFromInput(timeline, firstChunk, meta)\n },\n })\n\n const toInput = wrapValue<Meta>(to, toRaw, {\n fromValue(value) {\n return extractAnnotationForToInput(timeline, value.startMeta)\n },\n fromMeta(meta) {\n return extractAnnotationForToInput(timeline, meta)\n },\n })\n return diffInput(fromInput, toInput)\n}\n","export type Merger<T> = (left: T, right: T) => T | [T, T]\n\n/**\n * The two ended array supports pushing both at the beginning and\n * at the end while preserving indicies.\n */\nexport class TwoEndedArray<T extends {index: number}> {\n private _postive: T[] = []\n private _negative: T[] = []\n\n addToEnd(elem: T): void {\n elem.index = this._postive.length\n this._postive.push(elem)\n }\n\n addToBeginning(elem: T): void {\n // Prefer to place things at the positive side if possible.\n if (this.length == 0) {\n this.addToEnd(elem)\n return\n }\n\n elem.index = -(this._negative.length + 1)\n this._negative.push(elem)\n }\n\n mergeAtEnd(value: T, merger: Merger<T>): void {\n if (this.length === 0) {\n this.addToEnd(value)\n return\n }\n\n const idx = this.lastIdx\n const result = merger(this.get(idx), value)\n if (Array.isArray(result)) {\n this.set(idx, result[0])\n this.addToEnd(result[1])\n } else {\n this.set(idx, result)\n }\n }\n\n mergeAtBeginning(value: T, merger: Merger<T>): void {\n if (this.length === 0) {\n this.addToEnd(value)\n return\n }\n\n const idx = this.firstIdx\n const result = merger(value, this.get(idx))\n if (Array.isArray(result)) {\n this.set(idx, result[1])\n this.addToBeginning(result[0])\n } else {\n this.set(idx, result)\n }\n }\n\n removeFromEnd(): void {\n if (this._postive.length === 0) {\n this._negative.shift()\n } else {\n this._postive.pop()\n }\n }\n\n has(idx: number): boolean {\n if (idx >= 0) {\n return idx < this._postive.length\n }\n\n return -(idx + 1) < this._negative.length\n }\n\n get(idx: number): T {\n if (idx >= 0) {\n return this._postive[idx]\n }\n\n return this._negative[-(idx + 1)]\n }\n\n set(idx: number, value: T): void {\n if (idx >= 0) {\n value.index = idx\n this._postive[idx] = value\n } else {\n value.index = idx\n this._negative[-(idx + 1)] = value\n }\n }\n\n get lastIdx(): number {\n // Note: This also works correctly when _positive is empty (it returns -1)\n return this._postive.length - 1\n }\n\n get last(): T {\n return this.get(this.lastIdx)\n }\n\n get firstIdx(): number {\n // Note: This also works correctly when _negative is empty (it returns 0)\n return -this._negative.length\n }\n\n get first(): T {\n return this.get(this.firstIdx)\n }\n\n get length(): number {\n return this._postive.length + this._negative.length\n }\n}\n","import {type Diff} from '@sanity/diff'\nimport {type TransactionLogEventWithEffects} from '@sanity/types'\nimport {applyPatch, incremental} from 'mendoza'\n\nimport {type Annotation, type Chunk} from '../../../field/types'\nimport {chunkFromTransaction, mergeChunk} from './chunker'\nimport {diffValue, type Meta} from './diffValue'\nimport {type TraceEvent} from './replay'\nimport {TwoEndedArray} from './TwoEndedArray'\nimport {\n type CombinedDocument,\n type DocumentRemoteMutationVersionEvent,\n type Transaction,\n} from './types'\nimport {getAttrs} from './utils'\n\n/**\n * @hidden\n * @beta */\nexport type ParsedTimeRef = Chunk | 'loading' | 'invalid'\n\n/**\n * @hidden\n * @beta */\nexport interface TimelineOptions {\n publishedId: string\n enableTrace?: boolean\n}\n\n/**\n * Timeline maintains information about the history of a document:\n * Grouping raw translog entries into sensible groups, replaying and\n * reconstructing different versions and abstract other details.\n *\n * Note that this class by itself is not capable of _fetching_ information,\n * but will only organize and structure the incoming translog entries.\n *\n *\n * @hidden\n * @beta\n */\nexport class Timeline {\n reachedEarliestEntry = false\n\n publishedId: string\n draftId: string\n private _transactions = new TwoEndedArray<Transaction>()\n private _chunks = new TwoEndedArray<Chunk>()\n\n // These two properties are here to handle the case\n private _possiblePendingTransactions = new Map<\n string,\n {\n transaction: Transaction\n idx: number\n }\n >()\n private _recreateTransactionsFrom?: number\n private _trace?: TraceEvent[]\n\n constructor(opts: TimelineOptions) {\n this.publishedId = opts.publishedId\n this.draftId = `drafts.${opts.publishedId}`\n\n if (opts.enableTrace) {\n this._trace = []\n this._trace.push({\n type: 'initial',\n publishedId: opts.publishedId,\n })\n ;(window as any).__sanityTimelineTrace = this._trace\n }\n }\n\n get chunkCount(): number {\n return this._chunks.length\n }\n\n /** Maps over the chunk from newest to oldest. */\n mapChunks<T>(mapper: (chunk: Chunk, idx: number) => T): T[] {\n const result: T[] = []\n\n const firstIdx = this._chunks.firstIdx\n const lastIdx = this._chunks.lastIdx\n\n for (let idx = lastIdx; idx >= firstIdx; idx--) {\n result.push(mapper(this._chunks.get(idx), idx))\n }\n\n return result\n }\n\n reset(): void {\n this._transactions = new TwoEndedArray()\n this._chunks = new TwoEndedArray()\n this._possiblePendingTransactions = new Map()\n this._recreateTransactionsFrom = undefined\n this.reachedEarliestEntry = false\n }\n\n /**\n * Adds a remote mutation to the timeline. This methods assumes that the remote mutations\n * come in correct order for their respective version, but has no ordering requirements\n * across draft/published.\n *\n * Example: [D1, D2, P1] (where D1 and P1 were mutations done to the draft and published\n * version in the same transaction) is a valid input. [P1, D2, D1] is _not_ valid since\n * the mutation for the draft is out of order.\n */\n addRemoteMutation(entry: DocumentRemoteMutationVersionEvent): void {\n if (this._trace) this._trace.push({type: 'addRemoteMutation', event: entry})\n\n const pending = this._possiblePendingTransactions.get(entry.transactionId)\n\n const transaction: Transaction = pending\n ? pending.transaction\n : {\n index: 0,\n id: entry.transactionId,\n timestamp: entry.timestamp.toISOString(),\n author: entry.author,\n }\n\n if (entry.version === 'draft') {\n transaction.draftEffect = entry.effects as any\n } else {\n transaction.publishedEffect = entry.effects as any\n }\n\n if (pending) {\n this._possiblePendingTransactions.delete(entry.transactionId)\n this._invalidateTransactionFrom(pending.idx)\n } else {\n this._transactions.addToEnd(transaction)\n this._possiblePendingTransactions.set(entry.transactionId, {\n transaction,\n idx: this._transactions.lastIdx,\n })\n }\n }\n\n addTranslogEntry(event: TransactionLogEventWithEffects): void {\n if (this._trace) this._trace.push({type: 'addTranslogEntry', event})\n\n this._transactions.addToBeginning({\n index: 0,\n id: event.id,\n author: event.author,\n timestamp: event.timestamp,\n draftEffect: event.effects[this.draftId],\n publishedEffect: event.effects[this.publishedId],\n })\n }\n\n /** Mark that we've reached the earliest entry. */\n didReachEarliestEntry(): void {\n if (this._trace) this._trace.push({type: 'didReachEarliestEntry'})\n\n this.reachedEarliestEntry = true\n }\n\n /**\n * updateChunks synchronizes the chunks to match the current state\n * of the transactions array. After calling this method you need\n * to invalidate all Chunks.\n */\n updateChunks(): void {\n if (this._trace) this._trace.push({type: 'updateChunks'})\n\n this._removeInvalidatedChunks()\n this._addChunksFromTransactions()\n this._createInitialChunk()\n }\n\n private _removeInvalidatedChunks() {\n if (this._recreateTransactionsFrom) {\n while (this._chunks.length > 0) {\n const chunk = this._chunks.last\n if (this._recreateTransactionsFrom < chunk.end) {\n this._chunks.removeFromEnd()\n } else {\n break\n }\n }\n this._recreateTransactionsFrom = undefined\n }\n }\n\n private _addChunksFromTransactions() {\n const firstIdx = this._transactions.firstIdx\n const lastIdx = this._transactions.lastIdx\n\n // Add transactions at the end:\n const nextTransactionToChunk = this._chunks.length > 0 ? this._chunks.last.end : firstIdx\n for (let idx = nextTransactionToChunk; idx <= lastIdx; idx++) {\n const transaction = this._transactions.get(idx)\n this._chunks.mergeAtEnd(chunkFromTransaction(transaction), mergeChunk)\n }\n\n // Add transactions at the beginning:\n if (this._chunks.length == 0) return\n\n const firstTransactionChunked = this._chunks.first.start\n\n for (let idx = firstTransactionChunked - 1; idx >= firstIdx; idx--) {\n const transaction = this._transactions.get(idx)\n this._chunks.mergeAtBeginning(chunkFromTransaction(transaction), mergeChunk)\n }\n }\n\n private _invalidateTransactionFrom(idx: number) {\n if (this._recreateTransactionsFrom === undefined || idx < this._recreateTransactionsFrom) {\n this._recreateTransactionsFrom = idx\n }\n }\n\n private _createInitialChunk() {\n if (this.reachedEarliestEntry) {\n if (this._chunks.first?.type === 'initial') return\n\n const firstTx = this._transactions.first\n if (!firstTx) return\n const initialChunk = chunkFromTransaction(firstTx)\n initialChunk.type = 'initial'\n initialChunk.id = '@initial'\n initialChunk.end = initialChunk.start\n this._chunks.addToBeginning(initialChunk)\n }\n }\n\n /**\n * Resolves a time reference.\n *\n * Note that the chunk returned is only valid if the timeline stays constant.\n * Once the timeline is updated, you must re-parse all references.\n */\n parseTimeId(id: string): ParsedTimeRef {\n if (this._chunks.length === 0) {\n return this.reachedEarliestEntry ? 'invalid' : 'loading'\n }\n\n // NOTE:\n // This was refactored from\n // ```\n // const [timestampStr, chunkId] = id.split('/', 3)\n // ```\n // in order to avoid issues with `@microsoft/api-extractor`.\n const idSegments = id.split('/', 3)\n const timestampStr = idSegments.shift()\n const chunkId = idSegments.shift()\n const timestamp = Number(timestampStr)\n\n for (let idx = this._chunks.lastIdx; idx >= this._chunks.firstIdx; idx--) {\n const chunk = this._chunks.get(idx)\n if (chunk.id === chunkId) {\n return chunk\n }\n\n if (Date.parse(chunk.endTimestamp) + 60 * 60 * 1000 < timestamp) {\n // The chunk ended _before_ the timestamp we're asking for. This means that there\n // is no point in looking further and the chunk is invalid.\n\n // We add 1 hour to allow some slack since transactions are not guaranteed to be in order.\n return 'invalid'\n }\n }\n\n return this.reachedEarliestEntry ? 'invalid' : 'loading'\n }\n\n findLastPublishedBefore(chunk: Chunk | null): ParsedTimeRef {\n for (\n let chunkIdx = chunk ? chunk.index - 1 : this._chunks.lastIdx;\n chunkIdx >= this._chunks.firstIdx;\n chunkIdx--\n ) {\n const currentChunk = this._chunks.get(chunkIdx)\n if (currentChunk.type === 'publish' || currentChunk.type === 'initial') {\n return currentChunk\n }\n }\n\n if (!this.reachedEarliestEntry) return 'loading'\n\n return this._chunks.first\n }\n\n isLatestChunk(chunk: Chunk): boolean {\n return chunk === this._chunks.last\n }\n\n createTimeId(chunk: Chunk): string {\n return `${chunk.endTimestamp.valueOf()}/${chunk.id}`\n }\n\n lastChunk(): Chunk {\n return this._chunks.last\n }\n\n transactionByIndex(idx: number): Transaction | null {\n if (!this._transactions.has(idx)) return null\n return this._transactions.get(idx)\n }\n\n chunkByTransactionIndex(idx: number, startChunkIdx = 0): Chunk {\n let chunkIdx = startChunkIdx\n for (;;) {\n const chunk = this._chunks.get(chunkIdx)\n if (!chunk) throw new Error('transaction does not belong in any chunk')\n\n if (idx >= chunk.end) {\n chunkIdx++\n } else if (idx < chunk.start) {\n chunkIdx--\n } else {\n return chunk\n }\n }\n }\n\n replayBackwardsBetween(\n firstIdx: number,\n lastIdx: number,\n doc: CombinedDocument,\n ): CombinedDocument {\n let draft = doc.draft\n let published = doc.published\n\n for (let idx = lastIdx; idx >= firstIdx; idx--) {\n const transaction = this._transactions.get(idx)\n\n if (transaction.draftEffect) {\n draft = applyPatch(draft, transaction.draftEffect.revert)\n }\n\n if (transaction.publishedEffect) {\n published = applyPatch(published, transaction.publishedEffect.revert)\n }\n }\n\n return {draft, published}\n }\n\n replayBackwardsUntil(firstIdx: number, doc: CombinedDocument): CombinedDocument {\n return this.replayBackwardsBetween(firstIdx, this._transactions.lastIdx, doc)\n }\n\n calculateDiff(\n initialDoc: CombinedDocument,\n finalDoc: CombinedDocument,\n firstIdx: number,\n lastIdx: number,\n ): Diff<Annotation> {\n let draftValue = incremental.wrap<Meta>(initialDoc.draft, null)\n let publishedValue = incremental.wrap<Meta>(initialDoc.published, null)\n\n const initialValue = getValue(draftValue, publishedValue)\n const initialAttributes = getAttrs(initialDoc)\n let firstChunk: Chunk | null = null\n\n // Loop over all of the chunks:\n for (let chunkIdx = firstIdx; chunkIdx <= lastIdx; chunkIdx++) {\n const chunk = this._chunks.get(chunkIdx)\n if (!firstChunk) firstChunk = chunk\n\n for (let idx = chunk.start; idx < chunk.end; idx++) {\n const transaction = this._transactions.get(idx)\n\n const meta = {\n chunk,\n transactionIndex: idx,\n }\n\n const preDraftValue = draftValue\n const prePublishedValue = publishedValue\n\n if (transaction.draftEffect) {\n draftValue = incremental.applyPatch(draftValue, transaction.draftEffect.apply, meta)\n }\n\n if (transaction.publishedEffect) {\n publishedValue = incremental.applyPatch(\n publishedValue,\n transaction.publishedEffect.apply,\n meta,\n )\n }\n\n const didHaveDriaft = incremental.getType(preDraftValue) !== 'null'\n const haveDraft = incremental.getType(draftValue) !== 'null'\n const havePublished = incremental.getType(publishedValue) !== 'null'\n\n if (havePublished && !haveDraft) {\n publishedValue = incremental.rebaseValue(preDraftValue, publishedValue)\n }\n\n if (haveDraft && !didHaveDriaft) {\n draftValue = incremental.rebaseValue(prePublishedValue, draftValue)\n }\n }\n }\n\n const finalValue = incremental.getType(draftValue) === 'null' ? publishedValue : draftValue\n const finalAttributes = getAttrs(finalDoc)\n\n return diffValue(this, firstChunk, initialValue, initialAttributes, finalValue, finalAttributes)\n }\n}\n\nfunction getValue(draftValue: incremental.Value<Meta>, publishedValue: incremental.Value<Meta>) {\n return incremental.getType(draftValue) === 'null' ? publishedValue : draftValue\n}\n","import {type SanityDocument, type TransactionLogEventWithEffects} from '@sanity/types'\nimport {applyPatch} from 'mendoza'\n\nimport {type RemoteSnapshotVersionEvent} from '../../document/document-pair/checkoutPair'\nimport {type Timeline} from './Timeline'\nimport {type CombinedDocument, type DocumentRemoteMutationVersionEvent} from './types'\n\ntype VersionState = {\n id: string\n hasAttrs: boolean\n attrs: Record<string, unknown> | null\n rev: string | null\n events: Array<DocumentRemoteMutationVersionEvent>\n aligned: boolean\n}\n\nfunction emptyVersionState(id: string): VersionState {\n return {\n id,\n hasAttrs: false,\n attrs: null,\n rev: null,\n events: [],\n aligned: false,\n }\n}\n\nfunction align(history: TransactionLogEventWithEffects, state: VersionState): number {\n const idx = state.events.findIndex((evt) => history.id === evt.transactionId)\n if (idx >= 0) {\n // Return the next event as we don't want this to be included.\n return idx + 1\n }\n\n if (state.rev) {\n return state.rev === history.id ? 0 : -1\n }\n\n // At this point the document doesn't exist and we were not able to match\n // it up with a received mutation. This is a bit unfortunate as we don't\n // have a _reliably_ way of aligning it. For now we just always assume\n // that it's consistent.\n\n return 0\n}\n\nfunction startFromSnapshot(state: VersionState, doc: SanityDocument) {\n state.hasAttrs = true\n\n if (doc) {\n state.attrs = {...doc}\n if (typeof state.attrs._rev != 'string') throw new Error('snapshot has no _rev')\n state.rev = state.attrs._rev\n delete state.attrs._rev\n } else {\n state.attrs = null\n state.rev = null\n }\n\n state.events = []\n}\n\n/**\n * The timeline consists of data from (1) the history, (2) live draft mutations, and\n * (3) live published mutations. It's critical for us that the chain of transactions\n * is complete and without holes. The following class can be used as a layer in front\n * of Timeline to ensure this:\n *\n * - Invoke `appendRemoteSnapshotEvent` when there's an incoming remote mutation.\n * These mutations are buffered internally and _not_ passed to the timeline quite yet.\n *\n * - Once we've received snapshots for both draft and published, then `acceptsHistory`\n * becomes true and the caller can fetch a chunk of the translog. The flag\n * `earliestTransactionId` can be used to figure out where to fetch transactions from.\n *\n * - The caller invokes `prependHistoryEvent` for each of the events. These history events\n * are always pushed to the timeline and it will become available immediately.\n *\n * - Internally this class will then try to align the history event to the received\n * mutations and then dispatch to the timeline.\n *\n * - The aligner also maintains the latest revision for both the draft and the published version.\n *\n *\n */\nexport class Aligner {\n timeline: Timeline\n earliestTransactionId: string | null = null\n\n constructor(timeline: Timeline) {\n this.timeline = timeline\n this._states = {\n draft: emptyVersionState(timeline.draftId),\n published: emptyVersionState(timeline.publishedId),\n }\n }\n\n private _states: {\n draft: VersionState\n published: VersionState\n }\n\n appendRemoteSnapshotEvent(evt: RemoteSnapshotVersionEvent): void {\n if (evt.version === 'version') {\n return\n }\n\n const state = this._states[evt.version]\n\n if (evt.type === 'snapshot') {\n this._maybeInvalidateHistory()\n\n startFromSnapshot(state, evt.document)\n return\n }\n\n if (evt.type === 'remoteMutation') {\n if (state.aligned) {\n this._apply(state, evt)\n this.timeline.addRemoteMutation(evt)\n } else if (state.hasAttrs) {\n state.events.push(evt)\n } else {\n startFromSnapshot(state, evt.head)\n }\n }\n }\n\n prependHistoryEvent(evt: TransactionLogEventWithEffects): void {\n if (!this.acceptsHistory) throw new Error('cannot prepend history at this point')\n\n for (const state of Object.values(this._states)) {\n if (!state.aligned) {\n const idx = align(evt, state)\n\n if (idx >= 0) {\n this._alignAtIndex(state, idx)\n }\n }\n }\n\n this.timeline.addTranslogEntry(evt)\n this.earliestTransactionId = evt.id\n }\n\n didReachEarliestEntry(): void {\n for (const state of Object.values(this._states)) {\n if (!state.aligned) {\n if (state.attrs !== null) throw new Error('unable to find translog entry to align to')\n this._alignAtIndex(state, 0)\n }\n }\n this.timeline.didReachEarliestEntry()\n }\n\n get isAligned(): boolean {\n return Object.values(this._states).every((state) => state.aligned)\n }\n\n get acceptsHistory(): boolean {\n return this._isComplete\n }\n\n get currentDocument(): CombinedDocument {\n return {draft: this._states.draft.attrs, published: this._states.published.attrs}\n }\n\n private _alignAtIndex(state: VersionState, idx: number) {\n // These we must only apply locally since they are present in the fetched translog.\n for (const mutEvt of state.events.slice(0, idx)) {\n this._apply(state, mutEvt)\n }\n\n // ... while these must also be pushed to the timeline:\n for (const mutEvt of state.events.slice(idx)) {\n this._apply(state, mutEvt)\n this.timeline.addRemoteMutation(mutEvt)\n }\n\n state.events = []\n state.aligned = true\n }\n\n private get _isComplete(): boolean {\n return Object.values(this._states).every((state) => state.hasAttrs)\n }\n\n private _apply(state: VersionState, evt: DocumentRemoteMutationVersionEvent) {\n state.attrs = applyPatch(state.attrs, evt.effects.apply as any)\n state.rev = evt.transactionId\n }\n\n private _maybeInvalidateHistory() {\n if (this._isComplete) {\n for (const state of Object.values(this._states)) {\n state.aligned = false\n }\n this.earliestTransactionId = null\n this.timeline.reset()\n }\n }\n}\n","import {\n type TransactionLogEventWithMutations,\n type TransactionLogEventWithEffects,\n} from '@sanity/types'\n\nimport {DEFAULT_STUDIO_CLIENT_HEADERS} from '../../../studioClient'\n\ntype StreamResult =\n | (TransactionLogEventWithEffects & TransactionLogEventWithMutations)\n | {error: {description?: string; type: string}}\n\nexport async function getJsonStream(\n url: string,\n token: string | undefined,\n): Promise<ReadableStream<StreamResult>> {\n const options: RequestInit = token\n ? {headers: {...DEFAULT_STUDIO_CLIENT_HEADERS, Authorization: `Bearer ${token}`}}\n : {credentials: 'include', headers: DEFAULT_STUDIO_CLIENT_HEADERS}\n const response = await fetch(url, options)\n return getStream(response)\n}\n\nfunction getStream(response: Response): ReadableStream<StreamResult> {\n const body = response.body\n if (!body) {\n throw new Error('Failed to read body from response')\n }\n\n let reader: ReadableStreamDefaultReader<Uint8Array>\n let cancelled = false\n\n return new ReadableStream<TransactionLogEventWithEffects & TransactionLogEventWithMutations>({\n start(controller): void | PromiseLike<void> {\n reader = body.getReader()\n const decoder = new TextDecoder()\n let buffer = ''\n\n reader\n .read()\n .then(function processResult(result): void | Promise<void> {\n if (result.done) {\n if (cancelled) {\n return\n }\n\n buffer = buffer.trim()\n if (buffer.length === 0) {\n controller.close()\n return\n }\n\n controller.enqueue(JSON.parse(buffer))\n controller.close()\n return\n }\n\n buffer += decoder.decode(result.value, {stream: true})\n const lines = buffer.split('\\n')\n\n for (let i = 0; i < lines.length - 1; ++i) {\n const line = lines[i].trim()\n if (line.length === 0) {\n continue\n }\n\n try {\n controller.enqueue(JSON.parse(line))\n } catch (err) {\n controller.error(err)\n cancelled = true\n void reader.cancel()\n return\n }\n }\n\n buffer = lines[lines.length - 1]\n\n return reader\n .read()\n .then(processResult)\n .catch((err) => controller.error(err))\n })\n .catch((err) => controller.error(err))\n },\n\n cancel(): void {\n cancelled = true\n void reader.cancel()\n },\n })\n}\n","import {type Diff} from '@sanity/diff'\n\nimport {type Annotation, type Chunk} from '../../../field/types'\nimport {type Timeline} from './Timeline'\nimport {type CombinedDocument} from './types'\n\n/**\n * A reconstruction represents a single reconstruction of a\n */\nexport class Reconstruction {\n timeline: Timeline\n start: Chunk | null\n end: Chunk\n doc: CombinedDocument\n\n constructor(timeline: Timeline, doc: CombinedDocument, start: Chunk | null, end: Chunk) {\n this.timeline = timeline\n this.start = start\n this.end = end\n this.doc = doc\n }\n\n same(start: Chunk | null, end: Chunk): boolean {\n return this.start === start && this.end === end\n }\n\n private _startDocument?: CombinedDocument\n private _endDocument?: CombinedDocument\n private _diff?: Diff<Annotation>\n\n /** Returns the attributes as seen at the end of the range. */\n endAttributes(): Record<string, unknown> | null {\n return getAttrs(this.endDocument())\n }\n\n endDocument(): CombinedDocument {\n if (!this._endDocument) {\n this._endDocument = this.timeline.replayBackwardsUntil(this.end.end, this.doc)\n }\n\n return this._endDocument\n }\n\n /** Returns the attributes as seen at the end of the range. */\n startAttributes(): Record<string, unknown> | null {\n return getAttrs(this.startDocument())\n }\n\n startDocument(): CombinedDocument {\n if (!this.start) throw new Error('start required')\n\n if (!this._startDocument) {\n this._startDocument = this.timeline.replayBackwardsBetween(\n this.start.end,\n this.end.end - 1,\n this.endDocument(),\n )\n }\n\n return this._startDocument\n }\n\n diff(): Diff<Annotation> {\n if (!this._diff) {\n if (!this.start) throw new Error('start required')\n\n this._diff = this.timeline.calculateDiff(\n this.startDocument(),\n this.endDocument(),\n this.start.index + 1,\n this.end.index,\n )\n }\n\n return this._diff\n }\n}\n\nfunction getAttrs(doc: CombinedDocument) {\n return doc.draft || doc.published\n}\n","import {type SanityClient} from '@sanity/client'\nimport {type Diff, type ObjectDiff} from '@sanity/diff'\n\nimport {type Annotation, type Chunk} from '../../../field/types'\nimport {type RemoteSnapshotVersionEvent} from '../../document/document-pair/checkoutPair'\nimport {Aligner} from './Aligner'\nimport {getJsonStream} from './getJsonStream'\nimport {Reconstruction} from './Reconstruction'\nimport {type ParsedTimeRef, type Timeline} from './Timeline'\n\nconst TRANSLOG_ENTRY_LIMIT = 50\n\n/**\n * @hidden\n * @beta */\nexport type TimelineControllerOptions = {\n timeline: Timeline\n client: SanityClient\n documentId: string\n documentType: string\n handler?: (err: Error | null, controller: TimelineController) => void\n}\n\n/**\n * @hidden\n * @beta */\nexport type SelectionState = 'inactive' | 'rev' | 'range' | 'loading' | 'invalid'\n\n/**\n * The controller is responsible for fetching information\n * about a document and maintaining a Timeline.\n *\n *\n * @hidden\n * @beta\n */\nexport class TimelineController {\n timeline: Timeline\n client: SanityClient\n handler: TimelineControllerOptions['handler']\n\n version = 0\n\n /**\n * The selection state represents the different states of the current selection:\n * - inactive: No selection is active.\n * - rev: A selection is active for a single revision.\n * - range: A selection is active for a range and we have all the data needed to render it.\n * - loading: A selection is active, but we don't have the entries yet.\n * - invalid: The selection picked is invalid.\n */\n selectionState: SelectionState = 'inactive'\n\n constructor(options: TimelineControllerOptions) {\n this.timeline = options.timeline\n this.client = options.client\n this.handler = options.handler\n this._aligner = new Aligner(this.timeline)\n\n this.markChange()\n }\n\n private _aligner: Aligner\n\n private _fetchMore = false\n private _fetchAtLeast = 0\n private _isRunning = false\n private _isSuspended = false\n private _didErr = false\n\n private _since: string | null = null\n private _sinceTime: ParsedTimeRef | null = null\n private _rev: string | null = null\n private _revTime: ParsedTimeRef | null = null\n\n private _reconstruction?: Reconstruction\n\n setHandler(handler: TimelineControllerOptions['handler']): void {\n this.handler = handler\n }\n\n clearRange(): void {\n this.setRange(null, null)\n }\n\n setRange(since: string | null, rev: string | null): void {\n if (rev !== this._rev) this.setRevTime(rev)\n if (since !== this._since) this.setSinceTime(since)\n\n let _fetchAtLeast = 10\n\n if (this._sinceTime === 'loading' || this._revTime === 'loading' || !this._aligner.isAligned) {\n this.selectionState = 'loading'\n } else if (this._sinceTime === 'invalid' || this._revTime === 'invalid') {\n this.selectionState = 'invalid'\n } else if (this._sinceTime) {\n this.selectionState = 'range'\n\n const targetRev = this._revTime || this.timeline.lastChunk()\n\n if (this._sinceTime.index > targetRev.index) {\n this._revTime = 'invalid'\n this.selectionState = 'invalid'\n } else {\n this.setReconstruction(this._sinceTime, targetRev)\n }\n } else if (this._revTime) {\n this.selectionState = 'rev'\n this.setReconstruction(null, this._revTime)\n } else {\n this.selectionState = 'inactive'\n _fetchAtLeast = 0\n }\n\n this._fetchAtLeast = _fetchAtLeast\n\n this.start()\n }\n\n setLoadMore(flag: boolean): void {\n this._fetchMore = flag\n this.start()\n }\n\n get sinceTime(): Chunk | null {\n return this._sinceTime && typeof this._sinceTime === 'object' ? this._sinceTime : null\n }\n\n get revTime(): Chunk | null {\n return this._revTime && typeof this._revTime === 'object' ? this._revTime : null\n }\n\n get isLoading(): boolean {\n return this._isRunning\n }\n\n get realRevChunk(): Chunk {\n return this.revTime || this.timeline.lastChunk()\n }\n\n /** Returns true when there's an older revision we want to render. */\n onOlderRevision(): boolean {\n return Boolean(this._rev) && (this.selectionState === 'range' || this.selectionState === 'rev')\n }\n\n findRangeForNewRev(rev: Chunk): [string | null, string | null] {\n const revTimeId = this.timeline.isLatestChunk(rev) ? null : this.timeline.createTimeId(rev)\n\n if (!this._since) {\n return [null, revTimeId]\n }\n\n const sinceChunk = this.sinceTime\n if (sinceChunk && sinceChunk.index < rev.index) {\n return [this._since, revTimeId]\n }\n\n return ['@lastPublished', revTimeId]\n }\n\n findRangeForNewSince(since: Chunk): [string, string | null] {\n const revChunk = this.revTime\n\n // If the the `since` timestamp is earlier than the `rev`, then we can\n // accept it. Otherwise we'll move the current revision to the current draft.\n\n if (revChunk && since.index < revChunk.index) {\n return [this.timeline.createTimeId(since), this._rev]\n }\n\n return [this.timeline.createTimeId(since), null]\n }\n\n setRevTime(rev: string | null): void {\n this._rev = rev\n this._revTime = rev ? this.timeline.parseTimeId(rev) : null\n\n if (this._since === '@lastPublished') {\n // Make sure we invalidate it since this depends on the _rev.\n this._since = null\n this._sinceTime = null\n }\n }\n\n setSinceTime(since: string | null): void {\n if (since === '@lastPublished') {\n if (typeof this._revTime === 'string') {\n this._sinceTime = this._revTime\n } else {\n this._sinceTime = this.timeline.findLastPublishedBefore(this._revTime)\n }\n } else {\n this._sinceTime = since ? this.timeline.parseTimeId(since) : null\n }\n\n this._since = since\n }\n\n sinceAttributes(): Record<string, unknown> | null {\n return this._sinceTime && this._reconstruction ? this._reconstruction.startAttributes() : null\n }\n\n displayed(): Record<string, unknown> | null {\n return this._revTime && this._reconstruction ? this._reconstruction.endAttributes() : null\n }\n\n setReconstruction(since: Chunk | null, rev: Chunk): void {\n if (this._reconstruction && this._reconstruction.same(since, rev)) return\n this._reconstruction = new Reconstruction(\n this.timeline,\n this._aligner.currentDocument,\n since,\n rev,\n )\n }\n\n currentDiff(): Diff<Annotation> | null {\n return this._reconstruction ? this._reconstruction.diff() : null\n }\n\n currentObjectDiff(): ObjectDiff<Annotation> | null {\n const diff = this.currentDiff()\n if (diff) {\n if (diff.type === 'null') return null\n if (diff.type !== 'object') throw new Error(`ObjectDiff expected, got ${diff.type}`)\n }\n\n return diff as ObjectDiff<Annotation>\n }\n\n handleRemoteMutation(ev: RemoteSnapshotVersionEvent): void {\n this._aligner.appendRemoteSnapshotEvent(ev)\n this.markChange()\n\n // Make sure we fetch history as soon as possible.\n if (this._aligner.acceptsHistory) this.start()\n }\n\n start(): void {\n if (this._didErr) return\n\n if (!this._isRunning) {\n this._isRunning = true\n\n void this.tick().then(() => {\n this._isRunning = false\n })\n }\n }\n\n resume(): void {\n this._isSuspended = false\n }\n\n suspend(): void {\n this._isSuspended = true\n }\n\n private async tick() {\n const shouldFetchMore =\n this._aligner.acceptsHistory &&\n !this.timeline.reachedEarliestEntry &&\n (this.selectionState === 'loading' ||\n this._fetchMore ||\n this.timeline.chunkCount <= this._fetchAtLeast) &&\n !this._isSuspended\n\n if (!shouldFetchMore) {\n this._isRunning = false\n return\n }\n\n try {\n await this.fetchMoreTransactions()\n } catch (err) {\n this._didErr = true\n this.handler?.(err, this)\n return\n }\n\n await this.tick()\n }\n\n private async fetchMoreTransactions() {\n const publishedId = this.timeline.publishedId\n const draftId = this.timeline.draftId\n const clientConfig = this.client.config()\n const limit = TRANSLOG_ENTRY_LIMIT\n\n let queryParams = `tag=sanity.studio.structure.history&effectFormat=mendoza&excludeContent=true&excludeMutations=true&includeIdentifiedDocumentsOnly=true&reverse=true&limit=${limit}`\n let tid = this._aligner.earliestTransactionId\n if (tid) {\n queryParams += `&toTransaction=${tid}`\n }\n\n const transactionsUrl = this.client.getUrl(\n `/data/history/${clientConfig.dataset}/transactions/${publishedId},${draftId}?${queryParams}`,\n )\n const stream = await getJsonStream(transactionsUrl, clientConfig.token)\n const reader = stream.getReader()\n let count = 0\n\n for (;;) {\n // oxlint-disable-next-line no-await-in-loop\n const result = await reader.read()\n if (result.done) break\n\n if ('error' in result.value) {\n throw new Error(result.value.error.description || result.value.error.type)\n }\n\n count++\n\n if (result.value.id === tid) {\n // toTransaction is inclusive so we must ignore it when we fetch the next page\n continue\n }\n\n // For some reason, the aligner is now interested in a different set of entries.\n // This can happen if a new snapshot comes in as we're streaming the translog.\n // In this case it's safe to abort, and the run-loop will re-schedule it correctly.\n if (this._aligner.earliestTransactionId !== tid || !this._aligner.acceptsHistory) {\n return\n }\n\n this._aligner.prependHistoryEvent(result.value)\n tid = this._aligner.earliestTransactionId\n }\n\n // Same consistency checking here:\n if (this._aligner.earliestTransactionId !== tid || !this._aligner.acceptsHistory) {\n return\n }\n\n if (count < limit) {\n this._aligner.didReachEarliestEntry()\n }\n\n this.markChange()\n }\n\n private markChange() {\n this.timeline.updateChunks()\n\n this.setRevTime(this._rev)\n this.setSinceTime(this._rev)\n\n this.version++\n this.handler?.(null, this)\n }\n}\n","import {type Action, type SanityClient} from '@sanity/client'\nimport {type DocumentId, isDraftId, isVersionId} from '@sanity/id-utils'\nimport {\n isReference,\n type Reference,\n type SanityDocument,\n type TransactionLogEventWithMutations,\n} from '@sanity/types'\nimport {reduce as jsonReduce} from 'json-reduce'\nimport {from, type Observable} from 'rxjs'\nimport {map, mergeMap} from 'rxjs/operators'\n\nimport {isDev} from '../../environment'\nimport {getDraftId, getPublishedId, getVersionFromId, getIdPair} from '../../util/draftUtils'\nimport {isRecord} from '../../util/isRecord'\nimport {actionsApiClient} from '../document/document-pair/utils/actionsApiClient'\nimport {Timeline} from './history/Timeline'\nimport {TimelineController} from './history/TimelineController'\n\n/**\n * Represents a document revision identifier.\n * Can be either a specific revision string\n * or 'lastRevision' to get the most recent revision.\n *\n * @beta\n */\nexport type DocumentRevision = string | 'lastRevision'\n\n/**\n * @hidden\n * @beta */\nexport interface HistoryStore {\n getDocumentAtRevision: (\n documentId: string,\n revision: DocumentRevision,\n ) => Promise<SanityDocument | undefined>\n\n getHistory: (\n documentIds: string[],\n options?: {time?: string; revision?: string},\n ) => Promise<{documents: SanityDocument[]}>\n\n getTransactions: (documentIds: string[]) => Promise<TransactionLogEventWithMutations[]>\n\n restore: (\n id: string,\n targetId: string,\n rev: DocumentRevision,\n options?: RestoreOptions,\n ) => Observable<void>\n\n /** @internal */\n getTimelineController: (options: {\n client: SanityClient\n documentId: string\n documentType: string\n }) => TimelineController\n}\n\ninterface RestoreOptions {\n fromDeleted: boolean\n useServerDocumentActions?: boolean\n}\n\nconst documentRevisionCache: Record<string, Promise<SanityDocument | undefined> | undefined> =\n Object.create(null)\n\nconst getHistory = (\n client: SanityClient,\n documentIds: string[],\n options: {time?: string; revision?: string} = {},\n): Promise<{documents: SanityDocument[]}> => {\n const ids = Array.isArray(documentIds) ? documentIds : [documentIds]\n const {time, revision} = options\n\n if (time && revision) {\n throw new Error(`getHistory can't handle both time and revision parameters`)\n }\n\n const dataset = client.config().dataset\n let url = `/data/history/${dataset}/documents/${ids.join(',')}`\n\n if (revision) {\n url = `${url}?revision=${revision}`\n } else {\n const timestamp = time || new Date().toISOString()\n\n url = `${url}?time=${timestamp}`\n }\n\n return client.request({url})\n}\n\nconst getDocumentAtRevision = (\n client: SanityClient,\n documentId: string,\n revision: DocumentRevision,\n): Promise<SanityDocument | undefined> => {\n const publishedId = getPublishedId(documentId)\n const draftId = getDraftId(documentId)\n const versionId = isVersionId(documentId as DocumentId) ? documentId : undefined\n const idsToQuery = [publishedId, draftId, versionId].filter(Boolean) as DocumentId[]\n\n const isLastRevision = revision === 'lastRevision'\n\n if (!isLastRevision) {\n const cacheKey = `${documentId}@${revision}`\n const cached = documentRevisionCache[cacheKey]\n if (cached) {\n return cached\n }\n }\n\n const dataset = client.config().dataset\n const url = `/data/history/${dataset}/documents/${idsToQuery.join(',')}?${\n isLastRevision ? 'lastRevision=true' : `revision=${revision}`\n }`\n\n const entry = client\n .request<{documents?: SanityDocument[]}>({url, tag: 'history-revision'})\n .then((result) => {\n const documents = result.documents || []\n const published = documents.find((res) => res._id === publishedId)\n const draft = documents.find((res) => res._id === draftId)\n const version = versionId ? documents.find((res) => res._id === versionId) : undefined\n\n if (revision !== 'lastRevision') {\n if (version?._rev === revision) return version\n if (draft?._rev === revision) return draft\n if (published?._rev === revision) return published\n return undefined\n }\n return version || draft || published\n })\n\n if (!isLastRevision) {\n const cacheKey = `${documentId}@${revision}`\n documentRevisionCache[cacheKey] = entry\n }\n\n return entry\n}\n\nconst getTimelineController = ({\n client,\n documentId,\n documentType,\n}: {\n client: SanityClient\n documentId: string\n documentType: string\n}): TimelineController => {\n const timeline = new Timeline({\n enableTrace: isDev,\n publishedId: documentId,\n })\n return new TimelineController({\n client,\n documentId,\n documentType,\n timeline,\n })\n}\n\nconst getTransactions = async (\n client: SanityClient,\n documentIds: string | string[],\n): Promise<TransactionLogEventWithMutations[]> => {\n const ids = Array.isArray(documentIds) ? documentIds : [documentIds]\n const dataset = client.config().dataset\n const query = {excludeContent: 'true', includeIdentifiedDocumentsOnly: 'true'}\n const url = `/data/history/${dataset}/transactions/${ids.join(',')}`\n const result = await client.request({url, query})\n const transactions = result\n .toString('utf8')\n .split('\\n')\n .filter(Boolean)\n .map((line: string) => JSON.parse(line))\n\n return transactions\n}\n\nconst getAllRefIds = (doc: SanityDocument): string[] =>\n jsonReduce(\n doc as any,\n (acc: any, node) => (isReference(node) && !acc.includes(node._ref) ? [...acc, node._ref] : acc),\n [],\n )\n\nfunction jsonMap(value: unknown, mapFn: any): any {\n if (Array.isArray(value)) {\n return mapFn(\n value.map((item) => jsonMap(item, mapFn)).filter((item) => typeof item !== 'undefined'),\n )\n }\n\n if (isRecord(value)) {\n return mapFn(\n Object.keys(value).reduce<Record<string, unknown>>((res, key) => {\n const mappedValue = jsonMap(value[key], mapFn)\n if (typeof mappedValue !== 'undefined') {\n res[key] = mappedValue\n }\n\n return res\n }, {}),\n )\n }\n\n return mapFn(value)\n}\n\nconst mapRefNodes = (doc: SanityDocument, mapFn: (node: Reference) => Reference | undefined) =>\n jsonMap(doc, (node: unknown) => (isReference(node) ? mapFn(node) : node))\n\n/** @internal */\nexport const removeMissingReferences = (\n doc: SanityDocument,\n existingIds: Record<string, boolean | undefined>,\n): SanityDocument =>\n mapRefNodes(doc, (refNode) => {\n const documentExists = existingIds[refNode._ref]\n return documentExists ? refNode : undefined\n })\n\nfunction restore(\n client: SanityClient,\n documentId: string,\n targetDocumentId: string,\n rev: DocumentRevision,\n options?: RestoreOptions,\n): Observable<void> {\n return from(getDocumentAtRevision(client, targetDocumentId, rev)).pipe(\n mergeMap((documentAtRevision) => {\n if (!documentAtRevision) {\n throw new Error(`Unable to find document with ID ${documentId} at revision ${rev}`)\n }\n if (rev !== 'lastRevision' && documentAtRevision?._rev !== rev) {\n throw new Error(\n `Restored revision ${documentAtRevision?._rev} does not match expected revision ${rev}`,\n )\n }\n\n const existingIdsQuery = getAllRefIds(documentAtRevision)\n .map((refId) => `\"${refId}\": defined(*[_id==\"${refId}\"]._id)`)\n .join(',')\n\n return client.observable\n .fetch<Record<string, boolean | undefined>>(`{${existingIdsQuery}}`)\n .pipe(map((existingIds) => removeMissingReferences(documentAtRevision, existingIds)))\n }),\n map((documentAtRevision) => {\n // Remove _updatedAt\n const {_updatedAt, ...document} = documentAtRevision\n return {...document, _id: targetDocumentId}\n }),\n mergeMap((restoredDraft) => {\n // `sanity.action.document.replaceDraft` requires `attributes._id` to be\n // prefixed with either `drafts.` or `versions.<bundleId>`. When it isn't\n // (e.g. restoring a live-edit document directly onto the published id),\n // fall back to the mutation API, matching the non-server-actions path.\n const canUseServerAction =\n isDraftId(targetDocumentId as DocumentId) || isVersionId(targetDocumentId as DocumentId)\n\n if (options?.useServerDocumentActions && canUseServerAction) {\n const replaceDraftAction: Action = {\n actionType: 'sanity.action.document.replaceDraft',\n publishedId: documentId,\n attributes: restoredDraft,\n }\n return actionsApiClient(\n client,\n // The pair derives from the *target* id: `documentId` is always the published group id\n // (its bundle segment is always undefined), while the target may be a version document\n // (release or variant scoped) whose actions require the versioned API client.\n getIdPair(documentId, {version: getVersionFromId(targetDocumentId)}),\n ).observable.action(\n options.fromDeleted\n ? [\n {\n actionType: 'sanity.action.document.create',\n publishedId: documentId,\n attributes: restoredDraft,\n // This will guard against a race where someone else restores a deleted document at the same time\n ifExists: 'fail',\n },\n replaceDraftAction,\n ]\n : replaceDraftAction,\n )\n }\n\n return client.observable.createOrReplace(restoredDraft, {visibility: 'async'})\n }),\n map(() => undefined),\n )\n}\n\n/** @internal */\nexport interface HistoryStoreOptions {\n client: SanityClient\n}\n\n/** @internal */\nexport function createHistoryStore({client}: HistoryStoreOptions): HistoryStore {\n return {\n getDocumentAtRevision: (documentId, revision) =>\n getDocumentAtRevision(client, documentId, revision),\n\n getHistory: (documentIds, options) => getHistory(client, documentIds, options),\n\n getTransactions: (documentIds) => getTransactions(client, documentIds),\n\n restore: (id, targetId, rev, options) => restore(client, id, targetId, rev, options),\n\n getTimelineController,\n }\n}\n","/**\n * Whether or not the current environment supports localStorage.\n * Checks that values can actually be set/removed, to trigger any privacy settings.\n *\n * @internal\n */\nexport const supportsLocalStorage = (() => {\n // Non-browser runtimes (Node.js 22+, Bun, Deno) may expose a built-in\n // `localStorage` global that either warns or behaves differently from the\n // browser implementation. Since this utility is only useful in real browsers,\n // bail out in non-browser environments — even if browser globals have been\n // mocked (e.g., jsdom in CLI commands/tests). `process.versions` is set by\n // all major server-side runtimes and is not faked by jsdom.\n // Note that `process.versions` may also be defined by frameworks.\n // E.g. Next.js/Turbopack polyfills it and sets it to an empty object\n if (\n typeof process !== 'undefined' &&\n typeof process.versions !== 'undefined' &&\n typeof process.versions.node !== 'undefined'\n ) {\n return false\n }\n\n const key = '__tmp_supports_local_storage'\n\n try {\n if (typeof localStorage === 'undefined') {\n return false\n }\n\n localStorage.setItem(key, '---')\n localStorage.removeItem(key)\n return true\n } catch {\n return false\n }\n})()\n","import {type KeyValueStoreValue} from '../types'\n\nexport function createMemoryStorage() {\n const DB = Object.create(null)\n return {\n getKey(key: string): KeyValueStoreValue | null {\n return DB[key] || null\n },\n setKey(key: string, value: KeyValueStoreValue) {\n DB[key] = value\n },\n }\n}\n","import {supportsLocalStorage} from '../../../util/supportsLocalStorage'\nimport {type KeyValueStoreValue} from '../types'\nimport {createMemoryStorage} from './memoryStorage'\n\nfunction tryParse(val: string) {\n try {\n return JSON.parse(val)\n } catch (err) {\n console.warn(`Failed to parse settings: ${err.message}`)\n return null\n }\n}\n\nfunction createLocalStoreStorage() {\n if (!supportsLocalStorage) {\n return createMemoryStorage()\n }\n\n function getKey(key: string): KeyValueStoreValue | null {\n const val = localStorage.getItem(key)\n\n return val === null ? null : tryParse(val)\n }\n\n const setKey = function (key: string, nextValue: KeyValueStoreValue) {\n // Can't stringify undefined, and nulls are what\n // `getItem` returns when key does not exist\n if (typeof nextValue === 'undefined' || nextValue === null) {\n localStorage.removeItem(key)\n } else {\n localStorage.setItem(key, JSON.stringify(nextValue))\n }\n }\n return {getKey, setKey}\n}\n\nexport const localStoreStorage = createLocalStoreStorage()\n","import isEqual from 'lodash-es/isEqual.js'\nimport {merge, of} from 'rxjs'\nimport {distinctUntilChanged, tap} from 'rxjs/operators'\n\nimport {localStoreStorage} from './storage/localStoreStorage'\nimport {type KeyValueStore, type KeyValueStoreValue} from './types'\n\n/**\n * Wraps a KeyValueStore and adds Stale-While-Revalidate (SWR) behavior to it\n */\nexport function withLocalStorageSWR(wrappedStore: KeyValueStore): KeyValueStore {\n function getKey(key: string) {\n return merge(\n of(localStoreStorage.getKey(key)),\n wrappedStore.getKey(key).pipe(\n tap((wrappedStoreValue) => {\n localStoreStorage.setKey(key, wrappedStoreValue)\n }),\n ),\n ).pipe(distinctUntilChanged(isEqual))\n }\n function setKey(key: string, nextValue: KeyValueStoreValue) {\n localStoreStorage.setKey(key, nextValue)\n return wrappedStore.setKey(key, nextValue)\n }\n return {\n getKey,\n setKey,\n }\n}\n","import {type SanityClient} from '@sanity/client'\nimport DataLoader from 'dataloader'\n\nimport {DEFAULT_STUDIO_CLIENT_OPTIONS} from '../../../studioClient'\nimport {type KeyValueStoreValue} from '../types'\nimport {type KeyValuePair} from './types'\n\n/** @internal */\nexport interface ServerStorageOptions {\n client: SanityClient\n}\n\nexport interface ServerStorage {\n getKey: (key: string) => Promise<KeyValueStoreValue | null>\n setKey: (key: string, nextValue: unknown) => Promise<KeyValueStoreValue>\n}\n\n/**\n * Backend uses the Sanity client to store and retrieve key-value pairs from the /users/me/keyvalue endpoint.\n * @internal\n */\nexport function createServerStorage({client: _client}: ServerStorageOptions): ServerStorage {\n const client = _client.withConfig(DEFAULT_STUDIO_CLIENT_OPTIONS)\n\n const keyValueLoader = new DataLoader<string, KeyValueStoreValue | null>(async (keys) => {\n const value = await client\n .request<KeyValuePair[]>({\n uri: `/users/me/keyvalue/${keys.join(',')}`,\n })\n .catch((error) => {\n console.error('Error fetching data:', error)\n return Array(keys.length).fill(null)\n })\n\n // there are instances where the valeu might be null\n const keyValuePairs = (value || []).reduce(\n (acc, next) => {\n if (next?.key) {\n acc[next.key] = next.value\n }\n return acc\n },\n {} as Record<string, KeyValueStoreValue | null>,\n )\n\n return keys.map((key) => keyValuePairs[key] || null)\n })\n\n const getKey = (key: string) => {\n return keyValueLoader.load(key)\n }\n\n const setKey = (key: string, nextValue: unknown) => {\n return client\n .request<KeyValuePair[]>({\n method: 'PUT',\n uri: `/users/me/keyvalue`,\n body: [{key, value: nextValue}],\n })\n .then(\n (response) => {\n const pair = response[0]\n keyValueLoader.clear(pair.key)\n keyValueLoader.prime(pair.key, pair.value)\n return pair.value\n },\n (error) => {\n console.error('Error setting data:', error)\n return null\n },\n )\n }\n\n return {\n getKey,\n setKey,\n }\n}\n","import {type SanityClient} from '@sanity/client'\nimport isEqual from 'lodash-es/isEqual.js'\nimport {concat, type Observable, Subject} from 'rxjs'\nimport {distinctUntilChanged, filter, map} from 'rxjs/operators'\n\nimport {createServerStorage} from './storage/serverStorage'\nimport {type KeyValueStore, type KeyValueStoreValue} from './types'\n\nexport function createServerKeyValueStore({client}: {client: SanityClient}): KeyValueStore {\n const serverStorage = createServerStorage({client})\n\n const events$ = new Subject<{\n type: 'optimistic' | 'commit'\n key: string\n value: KeyValueStoreValue\n }>()\n\n function getKey(key: string) {\n return serverStorage.getKey(key)\n }\n\n function setKey(key: string, value: KeyValueStoreValue) {\n events$.next({type: 'optimistic', key, value})\n\n /*\n * The backend returns the result of the set operation, so we can just pass that along.\n * Most utils do not use it (they will take advantage of local state first) but it reflects the\n * backend function and could be useful for debugging.\n */\n return serverStorage.setKey(key, value).then((storedValue) => {\n events$.next({type: 'commit', key, value: storedValue})\n return storedValue\n })\n }\n\n return {\n getKey(key: string): Observable<KeyValueStoreValue | null> {\n return concat(\n getKey(key),\n events$.pipe(\n filter((event) => event.key === key),\n map((event) => event.value),\n distinctUntilChanged(isEqual),\n ),\n )\n },\n setKey,\n }\n}\n","import {type SanityClient} from '@sanity/client'\n\nimport {withLocalStorageSWR} from './localStorageSWR'\nimport {createServerKeyValueStore} from './serverKeyValueStore'\n\n/** @internal */\nexport function createKeyValueStore(options: {client: SanityClient}) {\n return withLocalStorageSWR(createServerKeyValueStore(options))\n}\n","import {type BifurClient} from '@sanity/bifur-client'\nimport {EMPTY, type Observable} from 'rxjs'\nimport {map, share} from 'rxjs/operators'\n\nimport {type PresenceLocation} from '../types'\nimport {type Transport, type TransportEvent, type TransportMessage} from './transport'\n\ntype BifurStateMessage = {\n type: 'state'\n i: string\n m: {\n sessionId: string\n locations: PresenceLocation[]\n }\n}\n\ntype BifurDisconnectMessage = {\n type: 'disconnect'\n i: string\n m: {session: string}\n}\n\ntype RollCallEvent = {\n type: 'rollCall'\n i: string\n session: string\n}\n\ntype IncomingBifurEvent<T> = RollCallEvent | BifurStateMessage | BifurDisconnectMessage\n\nconst handleIncomingMessage = (event: IncomingBifurEvent<Location[]>): TransportEvent => {\n if (event.type === 'rollCall') {\n return {\n type: 'rollCall',\n userId: event.i,\n sessionId: event.session,\n }\n }\n if (event.type === 'state') {\n const {sessionId, locations} = event.m\n return {\n type: 'state',\n userId: event.i,\n sessionId: sessionId,\n timestamp: new Date().toISOString(),\n locations,\n }\n }\n\n if (event.type === 'disconnect') {\n return {\n type: 'disconnect',\n userId: event.i,\n sessionId: event.m.session,\n timestamp: new Date().toISOString(),\n }\n }\n\n throw new Error(`Got unknown presence event: ${JSON.stringify(event)}`)\n}\n\nexport const createBifurTransport = (bifur: BifurClient, sessionId: string): Transport => {\n const incomingEvents$: Observable<TransportEvent> = bifur\n .listen<IncomingBifurEvent<Location[]>>('presence')\n .pipe(map(handleIncomingMessage))\n\n const dispatchMessage = (message: TransportMessage): Observable<undefined> => {\n if (message.type === 'rollCall') {\n return bifur.request('presence_rollcall', {session: sessionId})\n }\n\n if (message.type === 'state') {\n return bifur.request('presence_announce', {\n data: {locations: message.locations, sessionId},\n })\n }\n\n if (message.type === 'disconnect') {\n return bifur.request('presence_disconnect', {session: sessionId})\n }\n\n return EMPTY\n }\n\n return [incomingEvents$.pipe(share()), dispatchMessage]\n}\n","import sample from 'lodash-es/sample.js'\nimport {defer, timer} from 'rxjs'\nimport {map, mergeMapTo, shareReplay} from 'rxjs/operators'\n\nimport {type StateEvent} from './message-transports/transport'\n\nconst USERIDS = [\n 'pqSMwf6hH',\n 'pnLYqNfv5',\n 'priDVVmy8',\n 'p0NFOU0j8',\n 'pTDl2jw8d',\n 'pHMeQnTse',\n 'pDQYzJbyS',\n 'pZyoPHKUs',\n 'p4Tyi2Be5',\n 'pb9vii060',\n 'pE8yhOisw',\n 'p7Fd2C6Cj',\n 'p3exSgYCx',\n 'pbIQRYViC',\n 'p8GJaTEhN',\n 'p27ewL8aM',\n 'pYg97z75S',\n 'pdLr4quHv',\n 'pkJXiDgg6',\n 'pkl4UAKcA',\n\n // Included to ensure we handle the case when a user profile cannot\n // be fetched due to insufficient privileges or similar\n 'pNoExists',\n]\n\nconst PATHS = [\n ['nested', 'first'],\n ['nested', 'second'],\n [\n 'nestedArray',\n {_key: '565c867c8dac'},\n 'arrayNo1',\n {_key: 'a645548a8f01'},\n 'arrayNo1',\n {_key: '1685e372c40f'},\n 'fieldNo0',\n ],\n ['nestedArray', {_key: '565c867c8dac'}, 'fieldNo0'],\n ['nestedArray', {_key: '565c867c8dac'}, 'arrayNo19', {_key: 'a02e7a93e2a2'}, 'fieldNo0'],\n ['nestedArray', {_key: '565c867c8dac'}, 'arrayNo19', {_key: 'a02e7a93e2a2'}, 'fieldNo19'],\n ['address', 'country'],\n ['address', 'street'],\n ['customInputWithDefaultPresence', 'row3', 'cell3'],\n]\n\nexport const mock$ = defer(() => timer(0, 10000)).pipe(\n mergeMapTo(USERIDS),\n map(\n (id, n): StateEvent => ({\n type: 'state',\n userId: id,\n sessionId: id + n,\n timestamp: new Date().toISOString(),\n locations: [\n {\n type: 'document',\n documentId: 'presence-debug',\n lastActiveAt: new Date().toISOString(),\n path: sample(PATHS),\n },\n ] as any,\n }),\n ),\n shareReplay(),\n)\n","import {type BifurClient} from '@sanity/bifur-client'\nimport {type User} from '@sanity/types'\nimport flatten from 'lodash-es/flatten.js'\nimport groupBy from 'lodash-es/groupBy.js'\nimport isEqual from 'lodash-es/isEqual.js'\nimport omit from 'lodash-es/omit.js'\nimport uniq from 'lodash-es/uniq.js'\nimport {nanoid} from 'nanoid'\nimport {\n BehaviorSubject,\n combineLatest,\n defer,\n EMPTY,\n from,\n fromEvent,\n merge,\n NEVER,\n type Observable,\n timer,\n} from 'rxjs'\nimport {\n auditTime,\n distinctUntilChanged,\n filter,\n map,\n mergeMapTo,\n scan,\n share,\n shareReplay,\n switchMap,\n switchMapTo,\n takeUntil,\n tap,\n withLatestFrom,\n} from 'rxjs/operators'\n\nimport {documentIdEquals} from '../../util/draftUtils'\nimport {type ConnectionStatusStore} from '../connection-status/connection-status-store'\nimport {debugParams$} from '../debugParams/debugParams'\nimport {type UserStore} from '../user/userStore'\nimport {createBifurTransport} from './message-transports/bifurTransport'\nimport {\n type DisconnectEvent,\n type RollCallEvent,\n type StateEvent,\n type TransportEvent,\n} from './message-transports/transport'\nimport {mock$} from './mock-events'\nimport {\n type DocumentPresence,\n type GlobalPresence,\n type PresenceLocation,\n type Session,\n type UserSessionPair,\n} from './types'\n\n/**\n * @hidden\n * @beta */\nexport interface PresenceStore {\n /**\n * @internal\n */\n documentPresence: (\n documentId: string,\n options?: {excludeVersions?: boolean},\n ) => Observable<DocumentPresence[]>\n\n /**\n * @internal\n */\n globalPresence$: Observable<GlobalPresence[]>\n\n /**\n * @internal\n */\n reportLocations: (locations: PresenceLocation[]) => Observable<void>\n\n /**\n * @internal\n */\n setLocation: (nextLocation: PresenceLocation[]) => void\n\n /**\n * @internal\n */\n debugPresenceParam$: Observable<string[]>\n}\n\nconst KEY = 'presence_session_id'\nconst generate = () => nanoid(16)\n\n// We're keeping the session id in sessionStorage as it will survive page reloads.\n// todo:\n// There's a potential issue with window.open(...) here as it inherits the top level session storage and thus will\n// re-use session ids:\n// > Opening a page in a new tab or window creates a new session with the value of the top-level browsing context,\n// which differs from how session cookies work.\n// More at https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage\n// This is _probably_ a quite marginal case and not going to be much of a issue in practice\nfunction getSessionId() {\n try {\n return window.sessionStorage.getItem(KEY)\n } catch {\n // We don't want to fail hard if session storage can't be accessed for some reason\n }\n return null\n}\n\nfunction setSessionId(id: string) {\n try {\n window.sessionStorage.setItem(KEY, id)\n } catch {\n // We don't want to fail hard if session storage can't be accessed for some reason\n }\n return id\n}\n\n/** @internal */\nexport const SESSION_ID = getSessionId() || setSessionId(generate())\n\n/** @internal */\nexport function createPresenceStore(context: {\n bifur: BifurClient\n connectionStatusStore: ConnectionStatusStore\n userStore: UserStore\n}): PresenceStore {\n const {bifur, connectionStatusStore, userStore} = context\n\n const [presenceEvents$, sendMessage] = createBifurTransport(bifur, SESSION_ID)\n\n const currentLocation$ = new BehaviorSubject<PresenceLocation[]>([])\n const locationChange$ = currentLocation$.pipe(distinctUntilChanged())\n\n // export\n const setLocation = (nextLocation: PresenceLocation[]) => {\n currentLocation$.next(nextLocation)\n }\n\n // export\n const reportLocations = (locations: PresenceLocation[]) =>\n sendMessage({type: 'state', locations: locations})\n\n const requestRollCall = () => sendMessage({type: 'rollCall'})\n\n const rollCallRequests$ = presenceEvents$.pipe(\n filter((event: TransportEvent): event is RollCallEvent => event.type === 'rollCall'),\n // do not respond to my own rollcall requests\n filter((event: RollCallEvent) => event.sessionId !== SESSION_ID),\n )\n\n const REPORT_MIN_INTERVAL = 30000\n\n // Interval to report my own location at\n const reportLocationInterval$ = timer(0, REPORT_MIN_INTERVAL)\n\n const reportLocation$ = defer(() => merge(locationChange$, rollCallRequests$)).pipe(\n switchMap(() => reportLocationInterval$),\n withLatestFrom(currentLocation$),\n map(([, locations]) => locations),\n auditTime(200),\n switchMap((locations) => reportLocations(locations)),\n mergeMapTo(EMPTY),\n share(),\n )\n\n // This represents my rollcall request to other clients\n // Note: We are requesting a rollcall whenever we (re)connect\n const myRollCall$ = defer(() => requestRollCall()).pipe(mergeMapTo(EMPTY))\n\n const connectionChange$ = connectionStatusStore.connectionStatus$.pipe(\n map((status) => status.type),\n filter((statusType) => statusType === 'connected' || statusType === 'error'),\n distinctUntilChanged(),\n )\n\n // export\n const debugPresenceParam$ = debugParams$.pipe(\n map((args) => args.find((arg) => arg.startsWith('presence='))),\n map(\n (arg) =>\n arg\n ?.split('presence=')[1]\n .split(',')\n .map((r) => r.trim()) || [],\n ),\n )\n\n const useMock$ = debugPresenceParam$.pipe(\n filter((args) => args.includes('fake_others')),\n tap(() => {\n // oxlint-disable-next-line no-console\n console.log(\n 'Faking other users present in the studio. They will hang out in the document with _type: \"presence\" and _id: \"presence-debug\"',\n )\n }),\n switchMapTo(mock$),\n )\n\n const debugIntrospect$ = debugPresenceParam$.pipe(map((args) => args.includes('show_own')))\n\n const syncEvent$ = merge(myRollCall$, presenceEvents$).pipe(\n filter(\n (event: TransportEvent): event is StateEvent | DisconnectEvent =>\n event.type === 'state' || event.type === 'disconnect',\n ),\n )\n\n const stateEventToSession = (stateEvent: StateEvent): Session => {\n return {\n lastActiveAt: stateEvent.timestamp,\n locations: stateEvent.locations,\n sessionId: stateEvent.sessionId,\n userId: stateEvent.userId,\n }\n }\n\n const states$: Observable<{[sessionId: string]: Session}> = merge(syncEvent$, useMock$).pipe(\n scan(\n (keyed, event: StateEvent | DisconnectEvent): {[sessionId: string]: Session} =>\n event.type === 'disconnect'\n ? omit(keyed, event.sessionId)\n : {...keyed, [event.sessionId]: stateEventToSession(event)},\n {},\n ),\n )\n\n const allSessions$: Observable<UserSessionPair[]> = connectionChange$.pipe(\n switchMap((status) => (status === 'connected' ? merge(states$, reportLocation$) : NEVER)),\n map((keyedSessions) => Object.values(keyedSessions)),\n switchMap((sessions) => {\n const userIds = uniq(sessions.map((sess) => sess.userId))\n return from(userStore.getUsers(userIds)).pipe(\n map((users) =>\n sessions\n .map((session) => ({\n user: users.find((res) => res.id === session.userId),\n session: session,\n }))\n // If we failed to find a user profile for a session, remove it\n .filter(userSessionPairHasUser),\n ),\n )\n }),\n takeUntil(\n fromEvent(window, 'beforeunload').pipe(switchMap(() => sendMessage({type: 'disconnect'}))),\n ),\n shareReplay({refCount: true, bufferSize: 1}),\n )\n\n function userSessionPairHasUser(pair: Partial<UserSessionPair>): pair is UserSessionPair {\n return Boolean(pair.user && pair.session)\n }\n\n // export\n const globalPresence$: Observable<GlobalPresence[]> = allSessions$.pipe(\n map((sessions): {user: User; sessions: Session[]}[] => {\n const grouped = groupBy(\n sessions.map((s) => s.session),\n (e) => e.userId,\n )\n\n return Object.keys(grouped).map((userId): {user: User; sessions: Session[]} => ({\n user: sessions.find((s) => s.user.id === userId)?.user as User,\n sessions: grouped[userId],\n }))\n }),\n withLatestFrom(debugIntrospect$),\n map(([userAndSessions, debugIntrospect]) =>\n userAndSessions.filter(\n (userAndSession) =>\n debugIntrospect || !userAndSession.sessions.some((sess) => sess.sessionId === SESSION_ID),\n ),\n ),\n map((userAndSessions) =>\n userAndSessions.map((userAndSession) => ({\n user: userAndSession.user,\n status: 'online',\n lastActiveAt: userAndSession.sessions.sort((a, b) =>\n b.lastActiveAt.localeCompare(a.lastActiveAt),\n )[0]?.lastActiveAt,\n locations: flatten(\n (userAndSession.sessions || []).map((session) => session.locations || []),\n )\n .map((location) => ({\n type: location.type,\n documentId: location.documentId,\n path: location.path,\n lastActiveAt: location.lastActiveAt,\n }))\n .reduce((prev, curr) => prev.concat(curr), [] as PresenceLocation[]),\n })),\n ),\n )\n\n // Create a single shared observable for all documents\n const allDocumentsPresence$ = combineLatest([allSessions$, debugIntrospect$]).pipe(\n map(([userAndSessions, debugIntrospect]) =>\n userAndSessions\n .flatMap((userAndSession) =>\n (userAndSession.session.locations || []).map((location) => ({\n documentId: location.documentId,\n presence: {\n user: userAndSession.user,\n lastActiveAt: userAndSession.session.lastActiveAt,\n path: location.path || [],\n sessionId: userAndSession.session.sessionId,\n selection: location?.selection,\n },\n })),\n )\n .filter((item) => debugIntrospect || item.presence.sessionId !== SESSION_ID),\n ),\n shareReplay(1),\n )\n\n /**\n * Returns document presence for the given documennt id\n * Presence are returned for all versions of the document\n */\n const documentPresence = (\n documentId: string,\n options?: {excludeVersions?: boolean},\n ): Observable<DocumentPresence[]> => {\n return allDocumentsPresence$.pipe(\n map((allPresence) =>\n allPresence\n .filter((item) =>\n options?.excludeVersions\n ? item.documentId === documentId\n : documentIdEquals(item.documentId, documentId),\n )\n .map((item) => ({\n ...item.presence,\n //documentId: getPublishedId(item.documentId),\n documentId: item.documentId,\n })),\n ),\n // Only emit if the presence has changed for this document id\n distinctUntilChanged((prev, curr) => isEqual(prev, curr)),\n )\n }\n\n return {setLocation, reportLocations, debugPresenceParam$, globalPresence$, documentPresence}\n}\n","import {type SanityClient} from '@sanity/client'\nimport {\n catchError,\n distinctUntilChanged,\n map,\n type Observable,\n of,\n repeat,\n ReplaySubject,\n scan,\n share,\n shareReplay,\n timer,\n} from 'rxjs'\n\nimport {memoize} from '../document/utils/createMemoizer'\nimport {type ProjectData, type ProjectGrants, type ProjectStore} from './types'\n\nconst REFETCH_INTERVAL = 5 * 60 * 1000 // 5 minutes\n\n/**\n * This value will be cached for 5 minutes, after that internal the cache will be refreshed.\n * If you need to be 100% sure the organizationId is up to date, you can call the `/projects/${projectId}` endpoint directly.\n */\nconst getProjectOrg = memoize(\n (client: SanityClient) => {\n return client.observable\n .request<ProjectData>({\n url: `/projects/${client.config().projectId}`,\n tag: 'get-project-org',\n query: {\n includeMembers: 'false',\n includeFeatures: 'false',\n includeOrganization: 'true',\n },\n })\n .pipe(\n catchError(() => {\n return of(null)\n }),\n repeat({delay: REFETCH_INTERVAL}),\n // A transient refetch failure emits `null`. Retain the last known\n // project data so a failed refetch does not clobber a previously-good\n // organization id (which would strip org_id from telemetry events\n // flushed during the refetch window). See SAPP-3824.\n scan<ProjectData | null, ProjectData | null>((lastKnown, next) => next ?? lastKnown, null),\n distinctUntilChanged(),\n share({\n connector: () => new ReplaySubject(1),\n resetOnComplete: true,\n // delay unsubscriptions a little to keep the observable active\n // during React effect setup and teardown due to rapidly changing deps\n resetOnRefCountZero: () => timer(1000),\n }),\n )\n },\n (client) => `${client.config().projectId}-${client.config().dataset}`,\n)\n\nconst getOrganizationId = memoize(\n (client: SanityClient) => getProjectOrg(client).pipe(map((res) => res?.organizationId ?? null)),\n (client) => `${client.config().projectId}-${client.config().dataset}`,\n)\n\nconst getOrganizationData = memoize(\n (client: SanityClient) => getProjectOrg(client).pipe(map((res) => res?.organization ?? null)),\n (client) => `${client.config().projectId}-${client.config().dataset}`,\n)\n\n/**\n * Fetches the project grants for the current user, shared and replayed so all\n * permission checks reuse a single request. Memoized so callers outside the\n * project store (e.g. the schema/manifest upload gate) hit the same cached\n * observable instead of issuing a duplicate `/grants` request.\n *\n * Keyed by `projectId-dataset`, matching the other memoized requests in this\n * module, so a client for a different project/dataset never reuses another's\n * grants.\n *\n * @internal\n */\nexport const getProjectGrants = memoize(\n (client: SanityClient): Observable<ProjectGrants> =>\n client.observable\n .request<ProjectGrants>({\n url: `/projects/${client.config().projectId}/grants`,\n tag: 'get-grants',\n })\n .pipe(shareReplay(1)),\n (client) => `${client.config().projectId}-${client.config().dataset}`,\n)\n\n/** @internal */\nexport function createProjectStore(context: {client: SanityClient}): ProjectStore {\n const {client} = context\n const projectId = client.config().projectId\n const versionedClient = client.withConfig({apiVersion: '2021-12-15'})\n\n function get(): Observable<ProjectData> {\n return versionedClient.observable.request({\n url: `/projects/${projectId}`,\n tag: 'get-project',\n })\n }\n\n function getDatasets() {\n return versionedClient.observable.request({\n url: `/projects/${projectId}/datasets`,\n tag: 'get-datasets',\n })\n }\n\n const projectOrgData$ = getProjectOrg(versionedClient)\n\n return {\n get,\n getDatasets,\n getGrants: () => getProjectGrants(versionedClient),\n getOrganizationData: () => projectOrgData$.pipe(map((res) => res?.organization ?? null)),\n getOrganizationId: () => projectOrgData$.pipe(map((res) => res?.organizationId ?? null)),\n }\n}\n","import {type Observable} from 'rxjs'\n\n/**\n * @internal\n */\nexport type BaseStudioRenderingContext<\n Name extends string = string,\n Metadata = Record<PropertyKey, never>,\n> = {\n name: Name\n metadata: Metadata\n}\n\n/**\n * @internal\n */\nexport type DefaultRenderingContext = BaseStudioRenderingContext<'default'>\n\n/**\n * @internal\n */\nexport type CoreUiRenderingContext = BaseStudioRenderingContext<\n 'coreUi',\n {\n environment: string\n }\n>\n\n/**\n * @internal\n */\nexport type StudioRenderingContext = DefaultRenderingContext | CoreUiRenderingContext\n\n/**\n * @internal\n */\nexport const capabilities = ['globalUserMenu', 'globalWorkspaceControl', 'comlink'] as const\n\n/**\n * @internal\n */\nexport type Capability = (typeof capabilities)[number]\n\n/**\n * @internal\n */\nexport type CapabilityRecord = Partial<Record<Capability, boolean>>\n\n/**\n * @internal\n */\nexport type RenderingContextStore = {\n renderingContext: Observable<StudioRenderingContext>\n capabilities: Observable<CapabilityRecord>\n}\n\n/**\n * Check whether the provided value satisfies the `CoreUiRenderingContext` type.\n *\n * @internal\n */\nexport function isCoreUiRenderingContext(\n maybeCoreUiRenderingContext: unknown,\n): maybeCoreUiRenderingContext is CoreUiRenderingContext {\n return (\n typeof maybeCoreUiRenderingContext === 'object' &&\n maybeCoreUiRenderingContext !== null &&\n 'name' in maybeCoreUiRenderingContext &&\n maybeCoreUiRenderingContext.name === 'coreUi' &&\n 'metadata' in maybeCoreUiRenderingContext &&\n typeof maybeCoreUiRenderingContext.metadata === 'object' &&\n maybeCoreUiRenderingContext.metadata !== null &&\n 'environment' in maybeCoreUiRenderingContext.metadata &&\n typeof maybeCoreUiRenderingContext.metadata.environment === 'string'\n )\n}\n","import {\n catchError,\n distinctUntilChanged,\n map,\n of,\n type OperatorFunction,\n pipe,\n switchMap,\n} from 'rxjs'\n\nimport {isCoreUiRenderingContext, type StudioRenderingContext} from './types'\n\n// Core UI Rendering Context is provided via the URL query string, and remains static the entire\n// duration Studio is rendered inside the Core UI iframe.\n//\n// However, the URL query string is liable to be lost during Studio's lifecycle (for example, when\n// the user navigates to a different tool). Therefore, the URL query string is captured as soon as\n// this code is evaluated, and later referenced when a consumer subscribes to the store.\nconst INITIAL_URL_SEARCH = typeof location === 'object' ? location.search : ''\n\nconst CORE_UI_MODE_NAME = 'core-ui'\nconst CORE_UI_CONTEXT_SEARCH_PARAM = '_context'\n\n/**\n * @internal\n */\nexport function coreUiRenderingContext(\n urlSearch: string = INITIAL_URL_SEARCH,\n): OperatorFunction<StudioRenderingContext | undefined, StudioRenderingContext | undefined> {\n return pipe(\n switchMap((renderingContext) => {\n if (renderingContext) {\n return of(renderingContext)\n }\n\n return of(urlSearch).pipe(\n distinctUntilChanged(),\n map((search) => new URLSearchParams(search).get(CORE_UI_CONTEXT_SEARCH_PARAM)),\n map((serializedContext) => {\n if (serializedContext === null) {\n return undefined\n }\n\n const {mode, env} = JSON.parse(serializedContext)\n\n const coreUirenderingContext = {\n name: mode === CORE_UI_MODE_NAME ? 'coreUi' : undefined,\n metadata: {\n environment: env,\n },\n }\n\n if (isCoreUiRenderingContext(coreUirenderingContext)) {\n return coreUirenderingContext\n }\n\n return undefined\n }),\n catchError((error) => {\n console.warn('Error parsing rendering context:', error)\n return of(undefined)\n }),\n )\n }),\n )\n}\n","import {map, type OperatorFunction} from 'rxjs'\n\nimport {type DefaultRenderingContext, type StudioRenderingContext} from './types'\n\nconst DEFAULT_RENDERING_CONTEXT: DefaultRenderingContext = {\n name: 'default',\n metadata: {},\n}\n\n/**\n * @internal\n */\nexport function defaultRenderingContext(): OperatorFunction<\n StudioRenderingContext | undefined,\n StudioRenderingContext\n> {\n return map((renderingContext) => renderingContext ?? DEFAULT_RENDERING_CONTEXT)\n}\n","import {map, type OperatorFunction} from 'rxjs'\n\nimport {type CapabilityRecord, type StudioRenderingContext} from './types'\n\nconst capabilitiesByRenderingContext: Record<StudioRenderingContext['name'], CapabilityRecord> = {\n coreUi: {\n globalUserMenu: true,\n globalWorkspaceControl: true,\n comlink: true,\n },\n default: {},\n}\n\n/**\n * @internal\n */\nexport function listCapabilities(): OperatorFunction<StudioRenderingContext, CapabilityRecord> {\n return map((renderingContext) => capabilitiesByRenderingContext[renderingContext.name])\n}\n","import {of, shareReplay} from 'rxjs'\n\nimport {coreUiRenderingContext} from './coreUiRenderingContext'\nimport {defaultRenderingContext} from './defaultRenderingContext'\nimport {listCapabilities} from './listCapabilities'\nimport {type RenderingContextStore} from './types'\n\n/**\n * Rendering Context Store provides information about where Studio is being rendered, and which\n * capabilities are provided by the rendering context.\n *\n * This can be used to adapt parts of the Studio UI that are provided by the rendering context,\n * such as the global user menu.\n *\n * @internal\n */\nexport function createRenderingContextStore(): RenderingContextStore {\n const renderingContext = of(undefined).pipe(\n coreUiRenderingContext(),\n defaultRenderingContext(),\n shareReplay(1),\n )\n\n const capabilities = renderingContext.pipe(listCapabilities(), shareReplay(1))\n\n return {\n renderingContext,\n capabilities,\n }\n}\n","interface MultiKeyWeakMapNode {\n type: 'multi-key-weak-map-node'\n value: unknown\n next: WeakMap<object, MultiKeyWeakMapNode>\n}\n\nexport interface MultiKeyWeakMap {\n get<T>(keys: object[]): T | undefined\n get(keys: object[]): unknown\n\n set(keys: object[], value: unknown): void\n}\n\nexport function createMultiKeyWeakMap(): MultiKeyWeakMap {\n const rootMap = new WeakMap<object, MultiKeyWeakMapNode>()\n const idCache = new WeakMap<object, string>()\n\n function randomId() {\n return Array.from({length: 10})\n .map(() =>\n Math.floor(Math.random() * 255)\n .toString(16)\n .padStart(2, '0'),\n )\n .join('')\n }\n\n function assignId(key: object) {\n const cachedId = idCache.get(key)\n if (cachedId) return cachedId\n const id = randomId()\n idCache.set(key, id)\n return id\n }\n\n function arrangeKeys(keys: object[]) {\n return Array.from(new Set(keys))\n .map((key) => [assignId(key), key] as const)\n .sort(([a], [b]) => a.localeCompare(b, 'en'))\n .map(([, key]) => key)\n }\n\n function getDeep(keys: object[], map: WeakMap<object, MultiKeyWeakMapNode>): unknown {\n if (!keys.length) return undefined\n const [firstKey, ...restOfKeys] = keys\n const node = map.get(firstKey)\n\n if (!node) return undefined\n if (!restOfKeys.length) return node.value\n return getDeep(restOfKeys, node.next)\n }\n\n function setDeep(\n keys: object[],\n map: WeakMap<object, MultiKeyWeakMapNode>,\n value: unknown,\n ): void {\n if (!keys.length) return\n\n const [firstKey, ...restOfKeys] = keys\n const node = map.get(firstKey) || {\n type: 'multi-key-weak-map-node',\n value: undefined,\n next: new WeakMap(),\n }\n map.set(firstKey, node)\n\n if (!restOfKeys.length) {\n node.value = value\n return\n }\n\n setDeep(restOfKeys, node.next, value)\n }\n\n function get<T>(keys: object[]): T | undefined\n function get(keys: object[]) {\n return getDeep(arrangeKeys(keys), rootMap)\n }\n\n function set(keys: object[], value: unknown) {\n setDeep(arrangeKeys(keys), rootMap, value)\n }\n\n return {get, set}\n}\n","import {type ReactNode, useContext, useState} from 'react'\nimport {ResourceCacheContext} from 'sanity/_singletons'\n\nimport {createMultiKeyWeakMap, type MultiKeyWeakMap} from './createMultiKeyWeakMap'\n\n/** @internal */\nexport interface ResourceCache {\n get<T = unknown>(options: {namespace: string; dependencies: (object | null)[]}): T | undefined\n set(options: {namespace: string; dependencies: (object | null)[]; value: unknown}): void\n}\n\n/** @internal */\nexport interface ResourceCacheProviderProps {\n children: ReactNode\n}\n\n/** @internal */\nexport function ResourceCacheProvider({children}: ResourceCacheProviderProps) {\n const [resourceCache] = useState((): ResourceCache => {\n const namespaces = new Map<string, MultiKeyWeakMap>()\n\n // this is used to replace the `null` values in any `dependencies` so that\n // they can be used in the `MultiKeyWeakMap` which doesn't accept null\n const nullReplacer = {}\n // this is used to replace `[]` dependencies to maintain the\n // same referential integrity in the weak map lookup\n const emptyDependenciesReplacer = [nullReplacer]\n\n const removeNullDependencies = (dependencies: (object | null)[]) =>\n dependencies.length\n ? dependencies.map((dep) => (dep === null ? nullReplacer : dep))\n : emptyDependenciesReplacer\n\n return {\n get: ({namespace, dependencies}) => {\n const dependenciesWithoutNull = removeNullDependencies(dependencies)\n const namespaceMap = namespaces.get(namespace)\n return namespaceMap?.get(dependenciesWithoutNull)\n },\n\n set: ({namespace, dependencies, value}) => {\n const namespaceMap = namespaces.get(namespace) || createMultiKeyWeakMap()\n const dependenciesWithoutNull = removeNullDependencies(dependencies)\n namespaces.set(namespace, namespaceMap)\n namespaceMap.set(dependenciesWithoutNull, value)\n },\n }\n })\n\n return (\n <ResourceCacheContext.Provider value={resourceCache}>{children}</ResourceCacheContext.Provider>\n )\n}\n\n/** @internal */\nexport function useResourceCache(): ResourceCache {\n const cache = useContext(ResourceCacheContext)\n if (!cache) throw new Error('Could not find `cache` context')\n return cache\n}\n","import {useMemo} from 'react'\nimport {useObservable} from 'react-rx'\nimport {concat, type Observable, of} from 'rxjs'\nimport {catchError, distinctUntilChanged, map, scan, switchMap} from 'rxjs/operators'\n\n/** @internal */\nexport type LoadingTuple<T> = [T, boolean]\n\n/** @internal */\nexport type ReactHook<TArgs, TResult> = (args: TArgs) => TResult\n\n/** @internal */\n// overloads to handle types where an initial value is passed\nexport function createHookFromObservableFactory<T, TArg = void>(\n observableFactory: (arg: TArg) => Observable<T>,\n initialValue: T,\n): ReactHook<TArg, LoadingTuple<T>>\n/** @internal */\nexport function createHookFromObservableFactory<T, TArg = void>(\n observableFactory: (arg: TArg) => Observable<T>,\n initialValue?: T,\n): ReactHook<TArg, LoadingTuple<T | undefined>>\n\n/**\n * A function that will create a hook from a function that returns an\n * observable. The parameters of the hook will be the parameters of the function\n * and the return of the hook will be a loading tuple with the value of the\n * observable at the first index and a boolean with the loading state as the\n * second index.\n *\n * The loading state will become true as soon as new incoming args are given and\n * will flip to false when the observable from the function emits the next\n * value.\n *\n * @internal\n */\nexport function createHookFromObservableFactory<T, TArg = void>(\n observableFactory: (arg: TArg) => Observable<T>,\n initialValue?: T,\n): ReactHook<TArg, LoadingTuple<T | undefined>> {\n const initialLoadingTuple: LoadingTuple<T | undefined> = [initialValue, true]\n const initialResult = {type: 'tuple', tuple: initialLoadingTuple} as const\n\n return function useLoadableFromCreateLoadable(arg: TArg) {\n const observable = useMemo(\n () =>\n of(arg).pipe(\n switchMap((_arg) =>\n concat(\n of({type: 'loading'} as const),\n observableFactory(_arg).pipe(map((value) => ({type: 'value', value}) as const)),\n ),\n ),\n scan(([prevValue], next): LoadingTuple<T | undefined> => {\n if (next.type === 'loading') return [prevValue, true]\n return [next.value, false]\n }, initialLoadingTuple),\n distinctUntilChanged(([prevValue, prevIsLoading], [nextValue, nextIsLoading]) => {\n if (prevValue !== nextValue) return false\n if (prevIsLoading !== nextIsLoading) return false\n return true\n }),\n map((tuple) => ({type: 'tuple', tuple}) as const),\n catchError((error) => of({type: 'error', error} as const)),\n ),\n [arg],\n )\n const result = useObservable(observable, initialResult)\n\n if (result.type === 'error') throw result.error\n\n return result.tuple\n }\n}\n","import {type CurrentUser, type User} from '@sanity/types'\nimport {useMemo} from 'react'\nimport {from} from 'rxjs'\n\nimport {useSource} from '../../studio/source'\nimport {\n createHookFromObservableFactory,\n type LoadingTuple,\n} from '../../util/createHookFromObservableFactory'\nimport {useUserStore} from '../datastores'\nimport {type UserStore} from './userStore'\n\nconst useUserViaUserStore = createHookFromObservableFactory(\n ([userStore, userId]: [UserStore, string]) => {\n return from(\n userStore.getUser(userId).catch((err) => {\n console.error(err)\n return null\n }),\n )\n },\n)\n\n/** @internal */\nexport function useUser(userId: string): LoadingTuple<User | null | undefined> {\n const userStore = useUserStore()\n return useUserViaUserStore(useMemo(() => [userStore, userId], [userId, userStore]))\n}\n\n/**\n * Retrieves information about the currently authenticated user.\n *\n * @returns The current user or null if not available.\n *\n * @public\n *\n * @example\n * ```ts\n * const currentUser = useCurrentUser()\n *\n * if (currentUser) {\n * console.log('Logged in as', currentUser.name)\n * const department = currentUser.attributes?.find((attr) => attr.key === 'department')\n * }\n * ```\n */\nexport function useCurrentUser(): CurrentUser | null {\n const {currentUser} = useSource()\n return currentUser\n}\n","import {type SanityClient} from '@sanity/client'\nimport {type CurrentUser, type User} from '@sanity/types'\nimport DataLoader from 'dataloader'\nimport raf from 'raf'\n\nimport {isRecord} from '../../util/isRecord'\n\n/** @internal */\nexport interface UserStoreOptions {\n client: SanityClient\n currentUser: CurrentUser | null\n}\n\nconst INTERNAL_USER_IDS: User[] = [\n {\n id: '<system>',\n displayName: 'Sanity',\n imageUrl: 'https://public.sanity.io/logos/favicon-192.png',\n },\n]\n\n/**\n * @hidden\n * @beta */\nexport interface UserStore {\n getUser(userId: string): Promise<User | null>\n getUsers(userIds: string[]): Promise<User[]>\n}\n\n/**\n * Given a `client` and a `currentUser` creates a datastore that handles\n * fetching, batch fetching, and caching users.\n *\n * @internal\n */\nexport function createUserStore({client: _client, currentUser}: UserStoreOptions): UserStore {\n const client = _client.withConfig({apiVersion: '2021-06-07'})\n\n const userLoader = new DataLoader<string, User | null>(\n async (userIds) => {\n const value = await client.request<(User | null)[]>({\n uri: `/users/${userIds.join(',')}`,\n tag: 'users.get',\n })\n const response = Array.isArray(value) ? value : [value]\n const users = response.reduce(\n (acc, next) => {\n if (next?.id) {\n acc[next.id] = next\n }\n return acc\n },\n {} as Record<string, User | null>,\n )\n return userIds.map((id) => users[id] || null)\n },\n {\n batchScheduleFn: (cb) => raf(cb),\n /**\n * User IDs are generally 9 bytes long, but external user IDs may be longer.\n * In order to keep the HTTP header size below ~8KB, we limit the batch size.\n * ~4kB for user IDs in paths should allow for plenty of headers, if need be.\n */\n maxBatchSize: 400,\n },\n )\n\n const userFromCurrentUser: User | null = currentUser && {\n id: currentUser.id,\n displayName: currentUser.name,\n imageUrl: currentUser.profileImage,\n }\n\n userLoader.prime('me', userFromCurrentUser)\n\n if (userFromCurrentUser?.id) {\n userLoader.prime(userFromCurrentUser.id, userFromCurrentUser)\n }\n\n INTERNAL_USER_IDS.forEach((user) => userLoader.prime(user.id, user))\n\n return {\n getUser: async (userId) => {\n if (!userId) return Promise.resolve(null)\n\n try {\n return await userLoader.load(userId)\n } catch (err) {\n /**\n * 403 Forbidden responses indicate that the current user doesn't have read access to project members.\n * In these instances, we don't throw and resolve `null` instead.\n * Components consuming this (such as `<UserAvatar>`) shouldn't render anything in these cases.\n */\n if (err.statusCode === 403) {\n return Promise.resolve(null)\n }\n // Throw all other errors\n throw err\n }\n },\n getUsers: async (userIds) => {\n const results = await userLoader.loadMany(userIds)\n /**\n * Unlike `load()`, DataLoader's `loadMany()` will always resolve even if it contains `Error` instances.\n * Here, we remove all Errors (or more specifically, only include records with valid IDs).\n */\n return results.filter(\n (result): result is User => isRecord(result) && typeof result.id === 'string',\n )\n },\n }\n}\n","import {type SanityClient} from '@sanity/client'\nimport {useTelemetry} from '@sanity/telemetry/react'\nimport {useToast} from '@sanity/ui'\nimport {useCallback, useMemo} from 'react'\nimport {useObservable} from 'react-rx'\n\nimport {useClient} from '../hooks/useClient'\nimport {useSchema} from '../hooks/useSchema'\nimport {useTemplates} from '../hooks/useTemplates'\nimport {useTranslation} from '../i18n/hooks/useTranslation'\nimport {\n createDocumentPreviewStore,\n type DocumentPreviewStore,\n} from '../preview/documentPreviewStore'\nimport {useStudioErrorHandler} from '../studio/requestErrors/useStudioErrorHandler'\nimport {useSource} from '../studio/source'\nimport {useWorkspace} from '../studio/workspace'\nimport {DEFAULT_STUDIO_CLIENT_OPTIONS} from '../studioClient'\nimport {createComlinkStore} from './comlink/createComlinkStore'\nimport {type ComlinkStore} from './comlink/types'\nimport {\n type ConnectionStatusStore,\n createConnectionStatusStore,\n} from './connection-status/connection-status-store'\nimport {DocumentDesynced} from './document/__telemetry__/documentOutOfSyncEvents.telemetry'\nimport {DocumentPairLoadingMeasured} from './document/__telemetry__/documentPairLoading.telemetry'\nimport {DocumentRebaseOccurred} from './document/__telemetry__/documentRebase.telemetry'\nimport {HighListenerLatencyOccurred} from './document/__telemetry__/listenerLatency.telemetry'\nimport {MutationPerformanceMeasured} from './document/__telemetry__/mutationPerformance.telemetry'\nimport {createDocumentStore, type DocumentStore} from './document/document-store'\nimport {\n type DocumentPairLoadedEvent,\n type DocumentRebaseTelemetryEvent,\n type LatencyReportEvent,\n type MutationPerformanceEvent,\n} from './document/getPairListener'\nimport {type OutOfSyncError} from './document/utils/sequentializeListenerEvents'\nimport {createGrantsStore} from './grants/grantsStore'\nimport {type GrantsStore} from './grants/types'\nimport {createHistoryStore, type HistoryStore} from './history/createHistoryStore'\nimport {createKeyValueStore} from './key-value/keyValueStore'\nimport {type KeyValueStore} from './key-value/types'\nimport {createPresenceStore, type PresenceStore} from './presence/presence-store'\nimport {createProjectStore} from './project/projectStore'\nimport {type ProjectStore} from './project/types'\nimport {createRenderingContextStore} from './renderingContext/createRenderingContextStore'\nimport {type RenderingContextStore} from './renderingContext/types'\nimport {useResourceCache} from './ResourceCacheProvider'\nimport {useCurrentUser} from './user/hooks'\nimport {createUserStore, type UserStore} from './user/userStore'\n\n/**\n * Latencies below this value will not be logged\n */\nconst IGNORE_LATENCY_BELOW_MS = 1000\n\n/** Minimum time between slow commit toast notifications */\nconst SLOW_COMMIT_TOAST_COOLDOWN_MS = 30_000\nconst slowCommitCooldown = {lastToastAt: 0}\n\n/**\n * @hidden\n * @beta */\nexport function useUserStore(): UserStore {\n const {getClient, currentUser} = useSource()\n const resourceCache = useResourceCache()\n const client = getClient(DEFAULT_STUDIO_CLIENT_OPTIONS)\n\n return useMemo(() => {\n const userStore =\n resourceCache.get<UserStore>({\n namespace: 'userStore',\n dependencies: [client, currentUser],\n }) || createUserStore({client, currentUser})\n\n resourceCache.set({\n namespace: 'userStore',\n dependencies: [client, currentUser],\n value: userStore,\n })\n\n return userStore\n }, [client, currentUser, resourceCache])\n}\n\n/**\n * @hidden\n * @beta */\nexport function useGrantsStore(): GrantsStore {\n const {getClient} = useSource()\n const client = getClient(DEFAULT_STUDIO_CLIENT_OPTIONS)\n const currentUser = useCurrentUser()\n const resourceCache = useResourceCache()\n const errorHandler = useStudioErrorHandler()\n\n return useMemo(() => {\n const grantsStore =\n resourceCache.get<GrantsStore>({\n namespace: 'grantsStore',\n dependencies: [client, currentUser, errorHandler],\n }) || createGrantsStore({client, userId: currentUser?.id || null, errorHandler})\n\n resourceCache.set({\n namespace: 'grantsStore',\n dependencies: [client, currentUser, errorHandler],\n value: grantsStore,\n })\n\n return grantsStore\n }, [client, currentUser, errorHandler, resourceCache])\n}\n\n/**\n * @hidden\n * @beta */\nexport function useHistoryStore(): HistoryStore {\n const client = useClient(DEFAULT_STUDIO_CLIENT_OPTIONS)\n const resourceCache = useResourceCache()\n\n return useMemo(() => {\n const historyStore =\n resourceCache.get<HistoryStore>({\n namespace: 'historyStore',\n dependencies: [client],\n }) || createHistoryStore({client})\n\n resourceCache.set({\n namespace: 'historyStore',\n dependencies: [client],\n value: historyStore,\n })\n\n return historyStore\n }, [client, resourceCache])\n}\n\n/**\n * @hidden\n * @beta */\nexport function useDocumentPreviewStore(): DocumentPreviewStore {\n const client = useClient(DEFAULT_STUDIO_CLIENT_OPTIONS)\n const resourceCache = useResourceCache()\n\n return useMemo(() => {\n const documentPreviewStore =\n resourceCache.get<DocumentPreviewStore>({\n namespace: 'documentPreviewStore',\n dependencies: [client],\n }) || createDocumentPreviewStore({client})\n\n resourceCache.set({\n namespace: 'documentPreviewStore',\n dependencies: [client],\n value: documentPreviewStore,\n })\n\n return documentPreviewStore\n }, [client, resourceCache])\n}\n\n/**\n * @hidden\n * @beta */\nexport function useDocumentStore(): DocumentStore {\n const {getClient, i18n, currentUser} = useSource()\n const schema = useSchema()\n const templates = useTemplates()\n const resourceCache = useResourceCache()\n const historyStore = useHistoryStore()\n const documentPreviewStore = useDocumentPreviewStore()\n const workspace = useWorkspace()\n const telemetry = useTelemetry()\n const toast = useToast()\n const {t} = useTranslation()\n const errorHandler = useStudioErrorHandler()\n\n const handleSyncErrorRecovery = useCallback(\n (error: OutOfSyncError) => {\n telemetry.log(DocumentDesynced, {errorName: error.name})\n },\n [telemetry],\n )\n\n const handleReportLatency = useCallback(\n (event: LatencyReportEvent) => {\n if (event.latencyMs > IGNORE_LATENCY_BELOW_MS) {\n telemetry.log(HighListenerLatencyOccurred, {\n latency: event.latencyMs,\n shard: event.shard,\n transactionId: event.transactionId,\n })\n }\n },\n [telemetry],\n )\n\n const handleSlowCommit = useCallback(() => {\n const now = Date.now()\n if (now - slowCommitCooldown.lastToastAt < SLOW_COMMIT_TOAST_COOLDOWN_MS) return\n slowCommitCooldown.lastToastAt = now\n toast.push({\n title: t('document-store.slow-commit.title'),\n description: t('document-store.slow-commit.description'),\n status: 'warning',\n })\n }, [toast, t])\n\n const handleDocumentPairLoaded = useCallback(\n (event: DocumentPairLoadedEvent) => {\n telemetry.log(DocumentPairLoadingMeasured, {\n durationMs: event.durationMs,\n fromCache: event.fromCache,\n hasPublished: event.hasPublished,\n hasDraft: event.hasDraft,\n hasVersion: event.hasVersion,\n })\n },\n [telemetry],\n )\n\n const handleReportMutationPerformance = useCallback(\n (event: MutationPerformanceEvent) => {\n telemetry.log(MutationPerformanceMeasured, event)\n },\n [telemetry],\n )\n\n const handleDocumentRebase = useCallback(\n (event: DocumentRebaseTelemetryEvent) => {\n telemetry.log(DocumentRebaseOccurred, event)\n },\n [telemetry],\n )\n\n return useMemo(() => {\n const documentStore =\n resourceCache.get<DocumentStore>({\n namespace: 'documentStore',\n dependencies: [\n getClient,\n documentPreviewStore,\n historyStore,\n schema,\n i18n,\n workspace,\n currentUser,\n errorHandler,\n ],\n }) ||\n createDocumentStore({\n getClient,\n documentPreviewStore,\n historyStore,\n initialValueTemplates: templates,\n schema,\n i18n,\n currentUser,\n extraOptions: {\n onReportLatency: handleReportLatency,\n onSyncErrorRecovery: handleSyncErrorRecovery,\n onSlowCommit: handleSlowCommit,\n onDocumentPairLoaded: handleDocumentPairLoaded,\n onReportMutationPerformance: handleReportMutationPerformance,\n onDocumentRebase: handleDocumentRebase,\n snapshotFetchErrorHandler: errorHandler,\n },\n })\n\n resourceCache.set({\n namespace: 'documentStore',\n dependencies: [\n getClient,\n documentPreviewStore,\n historyStore,\n schema,\n i18n,\n workspace,\n currentUser,\n errorHandler,\n ],\n value: documentStore,\n })\n\n return documentStore\n }, [\n resourceCache,\n getClient,\n documentPreviewStore,\n historyStore,\n schema,\n i18n,\n workspace,\n currentUser,\n templates,\n handleReportLatency,\n handleSyncErrorRecovery,\n handleSlowCommit,\n handleDocumentPairLoaded,\n handleReportMutationPerformance,\n handleDocumentRebase,\n errorHandler,\n ])\n}\n\n/** @internal */\nexport function useConnectionStatusStore(): ConnectionStatusStore {\n const {bifur} = useSource().__internal\n const resourceCache = useResourceCache()\n\n return useMemo(() => {\n const connectionStatusStore =\n resourceCache.get<ConnectionStatusStore>({\n namespace: 'connectionStatusStore',\n dependencies: [bifur],\n }) || createConnectionStatusStore({bifur})\n\n resourceCache.set({\n namespace: 'connectionStatusStore',\n dependencies: [bifur],\n value: connectionStatusStore,\n })\n\n return connectionStatusStore\n }, [bifur, resourceCache])\n}\n\n/**\n * @hidden\n * @beta */\nexport function usePresenceStore(): PresenceStore {\n const {\n __internal: {bifur},\n } = useSource()\n const resourceCache = useResourceCache()\n const userStore = useUserStore()\n const connectionStatusStore = useConnectionStatusStore()\n\n return useMemo(() => {\n const presenceStore =\n resourceCache.get<PresenceStore>({\n namespace: 'presenceStore',\n dependencies: [bifur, connectionStatusStore, userStore],\n }) || createPresenceStore({bifur, connectionStatusStore, userStore})\n\n resourceCache.set({\n namespace: 'presenceStore',\n dependencies: [bifur, connectionStatusStore, userStore],\n value: presenceStore,\n })\n\n return presenceStore\n }, [bifur, connectionStatusStore, resourceCache, userStore])\n}\n\n/**\n * @hidden\n * @beta */\nexport function useProjectStore(): ProjectStore {\n const client = useClient(DEFAULT_STUDIO_CLIENT_OPTIONS)\n const resourceCache = useResourceCache()\n\n return useMemo(() => {\n const projectStore =\n resourceCache.get<ProjectStore>({\n namespace: 'projectStore',\n dependencies: [client],\n }) || createProjectStore({client})\n\n resourceCache.set({\n namespace: 'projectStore',\n dependencies: [client],\n value: projectStore,\n })\n\n return projectStore\n }, [client, resourceCache])\n}\n\n/**\n * Module-level cache for KeyValueStore instances, keyed by project identity.\n * Uses a simple Map with string keys since the ResourceCache's WeakMap\n * doesn't support primitive-based cache keys.\n */\nconst keyValueStoreCache = new Map<string, KeyValueStore>()\n\n/**\n * Generates a cache key for KeyValueStore based on project identity.\n * The /users/me/keyvalue endpoint is project-scoped, so we only need\n * projectId and apiHost (not dataset) to identify unique stores.\n */\nfunction getKeyValueStoreCacheKey(client: SanityClient): string {\n const config = client.config()\n return `${config.projectId}:${config.apiHost || 'default'}`\n}\n\n/**\n * Returns a KeyValueStore instance for storing user preferences.\n *\n * The store is cached by project identity (projectId + apiHost) rather than\n * workspace, because the /users/me/keyvalue endpoint is project-scoped -\n * user preferences are shared across all datasets within a project.\n *\n * @internal\n */\nexport function useKeyValueStore(): KeyValueStore {\n const client = useClient(DEFAULT_STUDIO_CLIENT_OPTIONS)\n\n return useMemo(() => {\n const cacheKey = getKeyValueStoreCacheKey(client)\n const cached = keyValueStoreCache.get(cacheKey)\n if (cached) return cached\n\n const keyValueStore = createKeyValueStore({client})\n keyValueStoreCache.set(cacheKey, keyValueStore)\n return keyValueStore\n }, [client])\n}\n\n/** @internal */\nexport function useRenderingContextStore(): RenderingContextStore {\n const resourceCache = useResourceCache()\n\n return useMemo(() => {\n const renderingContextStore =\n resourceCache.get<RenderingContextStore>({\n dependencies: [],\n namespace: 'RenderingContextStore',\n }) || createRenderingContextStore()\n\n resourceCache.set({\n dependencies: [],\n namespace: 'RenderingContextStore',\n value: renderingContextStore,\n })\n\n return renderingContextStore\n }, [resourceCache])\n}\n\n/** @internal */\nexport function useComlinkStore(): ComlinkStore {\n const resourceCache = useResourceCache()\n const renderingContext = useRenderingContextStore()\n const capabilities = useObservable(renderingContext.capabilities, {})\n\n return useMemo(() => {\n const comlinkStore =\n resourceCache.get<ComlinkStore>({\n dependencies: [capabilities],\n namespace: 'ComlinkStore',\n }) || createComlinkStore({capabilities})\n\n resourceCache.set({\n dependencies: [capabilities],\n namespace: 'ComlinkStore',\n value: comlinkStore,\n })\n\n return comlinkStore\n }, [capabilities, resourceCache])\n}\n"],"x_google_ignoreList":[130],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiBA,SAAOE,YAAA;CAAA,OACED,UAAU,CAAC,CAAAE;AAAO;;;;;;ACV3B,SAAOG,eAAA;CAAA,OACEF,UAAU,CAAC,CAAAG;AAAU;;;;ACN9B,SAAgBC,WAASC,OAAkD;CACzE,OAAOE,EAAQF,SAAU,OAAOA,SAAU,YAAY,CAACG,MAAMC,QAAQJ,KAAK;AAC5E;;;;;;ACAA,MCaMuB,iBAAiBC;;;;;;;AAQvB,SAAgBC,UAAaC,S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