@sanity/cross-dataset-duplicator 1.1.0 → 1.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1063 @@
1
+ import { useClient, useSchema, useWorkspaces, Preview, definePlugin } from 'sanity';
2
+ import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
3
+ import React, { useState, useEffect, useCallback, createContext, useContext } from 'react';
4
+ import { ArrowRightIcon, SearchIcon, LaunchIcon } from '@sanity/icons';
5
+ import { useSecrets, SettingsView } from '@sanity/studio-secrets';
6
+ import { Card, Flex, Button, Badge, Tooltip, Box, Text, useTheme, Container, Stack, Label, Select, Checkbox, Grid, TextInput, Spinner } from '@sanity/ui';
7
+ import mapLimit from 'async/mapLimit';
8
+ import asyncify from 'async/asyncify';
9
+ import { extractWithPath } from '@sanity/mutator';
10
+ import { dset } from 'dset';
11
+ import { isAssetId, isSanityFileAsset } from '@sanity/asset-utils';
12
+ function createInitialMessage() {
13
+ let docCount = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
14
+ let refsCount = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
15
+ const message = [docCount === 1 ? "This Document contains" : "These ".concat(docCount, " Documents contain"), refsCount === 1 ? "1 Reference." : "".concat(refsCount, " References."), refsCount === 1 ? "That Document" : "Those Documents", "may have References too. If referenced Documents do not exist at the target Destination, this transaction will fail."];
16
+ return message.join(" ");
17
+ }
18
+ const stickyStyles = function () {
19
+ let isDarkMode = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
20
+ return {
21
+ position: "sticky",
22
+ top: 0,
23
+ zIndex: 100,
24
+ backgroundColor: isDarkMode ? "rgba(10,10,10,0.95)" : "rgba(255,255,255,0.95)"
25
+ };
26
+ };
27
+ async function getDocumentsInArray(options) {
28
+ const {
29
+ fetchIds,
30
+ client,
31
+ pluginConfig,
32
+ currentIds,
33
+ projection
34
+ } = options;
35
+ const collection = [];
36
+ const filter = ["_id in $fetchIds", pluginConfig.filter].filter(Boolean).join(" && ");
37
+ const query = "*[".concat(filter, "]").concat(projection != null ? projection : "");
38
+ const data = await client.fetch(query, {
39
+ fetchIds: fetchIds != null ? fetchIds : []
40
+ });
41
+ if (!(data == null ? void 0 : data.length)) {
42
+ return [];
43
+ }
44
+ const localCurrentIds = currentIds != null ? currentIds : /* @__PURE__ */new Set();
45
+ const newDataIds = new Set(data.map(dataDoc => dataDoc._id).filter(id => (currentIds == null ? void 0 : currentIds.size) ? !localCurrentIds.has(id) : Boolean(id)));
46
+ if (newDataIds.size) {
47
+ collection.push(...data);
48
+ localCurrentIds.add(...newDataIds);
49
+ await Promise.all(data.map(async doc => {
50
+ const expr = ".._ref";
51
+ const references = extractWithPath(expr, doc).map(ref => ref.value);
52
+ if (references.length) {
53
+ const newReferenceIds = new Set(references.filter(ref => !localCurrentIds.has(ref)));
54
+ if (newReferenceIds.size) {
55
+ const referenceDocs = await getDocumentsInArray({
56
+ fetchIds: Array.from(newReferenceIds),
57
+ currentIds: localCurrentIds,
58
+ client,
59
+ pluginConfig
60
+ });
61
+ if (referenceDocs == null ? void 0 : referenceDocs.length) {
62
+ collection.push(...referenceDocs);
63
+ }
64
+ }
65
+ }
66
+ }));
67
+ }
68
+ const uniqueCollection = collection.filter(Boolean).reduce((acc, cur) => {
69
+ if (acc.some(doc => doc._id === cur._id)) {
70
+ return acc;
71
+ }
72
+ return [...acc, cur];
73
+ }, []);
74
+ return uniqueCollection;
75
+ }
76
+ const buttons = ["All", "None", null, "New", "Existing", "Older", null, "Documents", "Assets"];
77
+ function SelectButtons(props) {
78
+ const {
79
+ payload,
80
+ setPayload
81
+ } = props;
82
+ const [disabledActions, setDisabledActions] = useState([]);
83
+ useEffect(() => {
84
+ if (!(disabledActions == null ? void 0 : disabledActions.length) && payload.every(item => item.include)) {
85
+ setDisabledActions(["ALL"]);
86
+ }
87
+ }, [disabledActions == null ? void 0 : disabledActions.length, payload]);
88
+ function handleSelectButton(action) {
89
+ if (!action || !payload.length) return;
90
+ const newPayload = [...payload];
91
+ switch (action) {
92
+ case "ALL":
93
+ newPayload.map(item => item.include = true);
94
+ break;
95
+ case "NONE":
96
+ newPayload.map(item => item.include = false);
97
+ break;
98
+ case "NEW":
99
+ newPayload.map(item => item.include = Boolean(item.status === "CREATE"));
100
+ break;
101
+ case "EXISTING":
102
+ newPayload.map(item => item.include = Boolean(item.status === "EXISTS"));
103
+ break;
104
+ case "OLDER":
105
+ newPayload.map(item => item.include = Boolean(item.status === "OVERWRITE"));
106
+ break;
107
+ case "ASSETS":
108
+ newPayload.map(item => item.include = isAssetId(item.doc._id));
109
+ break;
110
+ case "DOCUMENTS":
111
+ newPayload.map(item => item.include = !isAssetId(item.doc._id));
112
+ break;
113
+ }
114
+ setDisabledActions([action]);
115
+ setPayload(newPayload);
116
+ }
117
+ return /* @__PURE__ */jsx(Card, {
118
+ padding: 1,
119
+ radius: 3,
120
+ shadow: 1,
121
+ children: /* @__PURE__ */jsx(Flex, {
122
+ gap: 2,
123
+ children: buttons.map((action, actionIndex) => action ? /* @__PURE__ */jsx(Button, {
124
+ fontSize: 1,
125
+ mode: "bleed",
126
+ padding: 2,
127
+ text: action,
128
+ disabled: disabledActions.includes(action.toUpperCase()),
129
+ onClick: () => handleSelectButton(action.toUpperCase())
130
+ }, action) :
131
+ // eslint-disable-next-line react/no-array-index-key
132
+ /* @__PURE__ */
133
+ jsx(Card, {
134
+ borderLeft: true
135
+ }, "divider-".concat(actionIndex)))
136
+ })
137
+ });
138
+ }
139
+ const documentTones = {
140
+ EXISTS: "primary",
141
+ OVERWRITE: "critical",
142
+ UPDATE: "caution",
143
+ CREATE: "positive",
144
+ UNPUBLISHED: "caution"
145
+ };
146
+ const assetTones = {
147
+ EXISTS: "critical",
148
+ OVERWRITE: "critical",
149
+ UPDATE: "critical",
150
+ CREATE: "positive",
151
+ UNPUBLISHED: "default"
152
+ };
153
+ const documentMessages = {
154
+ // Only happens once document is copied the first time, and _updatedAt is the same
155
+ EXISTS: "This document already exists at the Destination with the same ID with the same Updated time.",
156
+ // Is true immediately after transaction as _updatedAt is updated by API after mutation
157
+ // Is also true if the document at the destination has been manually modified
158
+ // Presently, the plugin doesn't actually compare the two documents
159
+ OVERWRITE: "A newer version of this document exists at the Destination, and it will be overwritten with this version.",
160
+ // Document at destination is older
161
+ UPDATE: "An older version of this document exists at the Destination, and it will be overwritten with this version.",
162
+ // Document at destination doesn't exist
163
+ CREATE: "This document will be created at the destination.",
164
+ UNPUBLISHED: "A Draft version of this Document exists in this Dataset, but only the Published version will be duplicated to the destination."
165
+ };
166
+ const assetMessages = {
167
+ EXISTS: "This Asset already exists at the Destination",
168
+ OVERWRITE: "This Asset already exists at the Destination",
169
+ UPDATE: "This Asset already exists at the Destination",
170
+ CREATE: "This Asset does not yet exist at the Destination",
171
+ UNPUBLISHED: ""
172
+ };
173
+ const assetStatus = {
174
+ EXISTS: "RE-UPLOAD",
175
+ OVERWRITE: "RE-UPLOAD",
176
+ UPDATE: "RE-UPLOAD",
177
+ CREATE: "UPLOAD",
178
+ UNPUBLISHED: ""
179
+ };
180
+ function StatusBadge(props) {
181
+ const {
182
+ status,
183
+ isAsset
184
+ } = props;
185
+ if (!status) {
186
+ return null;
187
+ }
188
+ const badgeTone = isAsset ? assetTones[status] : documentTones[status];
189
+ if (!badgeTone) {
190
+ return /* @__PURE__ */jsx(Badge, {
191
+ muted: true,
192
+ padding: 2,
193
+ fontSize: 1,
194
+ mode: "outline",
195
+ children: "Checking..."
196
+ });
197
+ }
198
+ const badgeText = isAsset ? assetMessages[status] : documentMessages[status];
199
+ const badgeStatus = isAsset ? assetStatus[status] : status;
200
+ return /* @__PURE__ */jsx(Tooltip, {
201
+ content: /* @__PURE__ */jsx(Box, {
202
+ padding: 3,
203
+ style: {
204
+ maxWidth: 200
205
+ },
206
+ children: /* @__PURE__ */jsx(Text, {
207
+ size: 1,
208
+ children: badgeText
209
+ })
210
+ }),
211
+ fallbackPlacements: ["right", "left"],
212
+ placement: "top",
213
+ portal: true,
214
+ children: /* @__PURE__ */jsx(Badge, {
215
+ muted: true,
216
+ padding: 2,
217
+ fontSize: 1,
218
+ tone: badgeTone,
219
+ mode: "outline",
220
+ children: badgeStatus
221
+ })
222
+ });
223
+ }
224
+ function Feedback(props) {
225
+ const {
226
+ children,
227
+ tone = "caution"
228
+ } = props;
229
+ return /* @__PURE__ */jsx(Card, {
230
+ padding: 3,
231
+ radius: 2,
232
+ shadow: 1,
233
+ tone,
234
+ children: /* @__PURE__ */jsx(Text, {
235
+ size: 1,
236
+ children
237
+ })
238
+ });
239
+ }
240
+ const clientConfig = {
241
+ apiVersion: "2021-05-19"
242
+ };
243
+ function Duplicator(props) {
244
+ var _a, _b, _c;
245
+ const {
246
+ docs,
247
+ token,
248
+ pluginConfig,
249
+ onDuplicated
250
+ } = props;
251
+ const isDarkMode = useTheme().sanity.color.dark;
252
+ const originClient = useClient(clientConfig);
253
+ const schema = useSchema();
254
+ const workspaces = useWorkspaces();
255
+ const workspacesOptions = workspaces.map(workspace => ({
256
+ ...workspace,
257
+ disabled: workspace.dataset === originClient.config().dataset
258
+ }));
259
+ const [destination, setDestination] = useState(workspaces.length ? (_a = workspacesOptions.find(space => !space.disabled)) != null ? _a : null : null);
260
+ const [message, setMessage] = useState(null);
261
+ const [payload, setPayload] = useState([]);
262
+ const [hasReferences, setHasReferences] = useState(false);
263
+ const [isDuplicating, setIsDuplicating] = useState(false);
264
+ const [isGathering, setIsGathering] = useState(false);
265
+ const [progress, setProgress] = useState([0, 0]);
266
+ useEffect(() => {
267
+ const expr = ".._ref";
268
+ const initialRefs = [];
269
+ const initialPayload = [];
270
+ docs.forEach(doc => {
271
+ const refs = extractWithPath(expr, doc).map(ref => ref.value);
272
+ initialRefs.push(...refs);
273
+ initialPayload.push({
274
+ include: true,
275
+ doc
276
+ });
277
+ });
278
+ setPayload(initialPayload);
279
+ const docCount = docs.length;
280
+ const refsCount = initialRefs.length;
281
+ if (initialRefs.length) {
282
+ setHasReferences(true);
283
+ setMessage({
284
+ tone: "caution",
285
+ text: createInitialMessage(docCount, refsCount)
286
+ });
287
+ }
288
+ }, [docs]);
289
+ useEffect(() => {
290
+ updatePayloadStatuses();
291
+ }, [destination]);
292
+ async function updatePayloadStatuses() {
293
+ let newPayload = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
294
+ const payloadActual = newPayload.length ? newPayload : payload;
295
+ if (!payloadActual.length || !(destination == null ? void 0 : destination.name)) {
296
+ return;
297
+ }
298
+ const payloadIds = payloadActual.map(_ref => {
299
+ let {
300
+ doc
301
+ } = _ref;
302
+ return doc._id;
303
+ });
304
+ const destinationClient = originClient.withConfig({
305
+ ...clientConfig,
306
+ dataset: destination.dataset,
307
+ projectId: destination.projectId
308
+ });
309
+ const destinationData = await destinationClient.fetch("*[_id in $payloadIds]{ _id, _updatedAt }", {
310
+ payloadIds
311
+ });
312
+ const updatedPayload = payloadActual.map(item => {
313
+ var _a2;
314
+ const existingDoc = destinationData.find(doc => doc._id === item.doc._id);
315
+ if ((existingDoc == null ? void 0 : existingDoc._updatedAt) && ((_a2 = item == null ? void 0 : item.doc) == null ? void 0 : _a2._updatedAt)) {
316
+ if (existingDoc._updatedAt === item.doc._updatedAt) {
317
+ item.status = "EXISTS";
318
+ } else if (existingDoc._updatedAt && item.doc._updatedAt) {
319
+ item.status = new Date(existingDoc._updatedAt) > new Date(item.doc._updatedAt) ? // Document at destination is newer
320
+ "OVERWRITE" : // Document at destination is older
321
+ "UPDATE";
322
+ }
323
+ } else {
324
+ item.status = "CREATE";
325
+ }
326
+ return item;
327
+ });
328
+ setPayload(updatedPayload);
329
+ }
330
+ function handleCheckbox(_id) {
331
+ const updatedPayload = payload.map(item => {
332
+ if (item.doc._id === _id) {
333
+ item.include = !item.include;
334
+ }
335
+ return item;
336
+ });
337
+ setPayload(updatedPayload);
338
+ }
339
+ async function handleReferences() {
340
+ setIsGathering(true);
341
+ const docIds = docs.map(doc => doc._id);
342
+ const payloadDocs = await getDocumentsInArray({
343
+ fetchIds: docIds,
344
+ client: originClient,
345
+ pluginConfig
346
+ });
347
+ const draftDocs = await getDocumentsInArray({
348
+ fetchIds: docIds.map(id => "drafts.".concat(id)),
349
+ client: originClient,
350
+ projection: "{_id}",
351
+ pluginConfig
352
+ });
353
+ const draftDocsIds = new Set(draftDocs.map(_ref2 => {
354
+ let {
355
+ _id
356
+ } = _ref2;
357
+ return _id;
358
+ }));
359
+ const payloadShaped = payloadDocs.map(doc => ({
360
+ doc,
361
+ // Include this in the transaction?
362
+ include: true,
363
+ // Does it exist at the destination?
364
+ status: void 0,
365
+ // Does it have any drafts?
366
+ hasDraft: draftDocsIds.has("drafts.".concat(doc._id))
367
+ }));
368
+ setPayload(payloadShaped);
369
+ updatePayloadStatuses(payloadShaped);
370
+ setIsGathering(false);
371
+ }
372
+ async function handleDuplicate() {
373
+ if (!destination) {
374
+ return;
375
+ }
376
+ setIsDuplicating(true);
377
+ const assetsCount = payload.filter(_ref3 => {
378
+ let {
379
+ doc,
380
+ include
381
+ } = _ref3;
382
+ return include && isAssetId(doc._id);
383
+ }).length;
384
+ let currentProgress = 0;
385
+ setProgress([currentProgress, assetsCount]);
386
+ setMessage({
387
+ text: "Duplicating...",
388
+ tone: "default"
389
+ });
390
+ const destinationClient = originClient.withConfig({
391
+ ...clientConfig,
392
+ dataset: destination.dataset,
393
+ projectId: destination.projectId
394
+ });
395
+ const transactionDocs = [];
396
+ const svgMaps = [];
397
+ async function fetchDoc(doc) {
398
+ if (isAssetId(doc._id)) {
399
+ const typeIsFile = isSanityFileAsset(doc);
400
+ const downloadUrl = typeIsFile ? doc.url : "".concat(doc.url, "?dlRaw=true");
401
+ const downloadConfig = typeIsFile ? {} : {
402
+ headers: {
403
+ Authorization: "Bearer ".concat(token)
404
+ }
405
+ };
406
+ await fetch(downloadUrl, downloadConfig).then(async res => {
407
+ const assetData = await res.blob();
408
+ const options = {
409
+ filename: doc.originalFilename
410
+ };
411
+ const assetDoc = await destinationClient.assets.upload(typeIsFile ? "file" : "image", assetData, options);
412
+ if ((doc == null ? void 0 : doc.extension) === "svg") {
413
+ svgMaps.push({
414
+ old: doc._id,
415
+ new: assetDoc._id
416
+ });
417
+ }
418
+ transactionDocs.push(assetDoc);
419
+ });
420
+ currentProgress += 1;
421
+ setMessage({
422
+ text: "Duplicating ".concat(currentProgress, "/").concat(assetsCount, " ").concat(assetsCount === 1 ? "Assets" : "Assets"),
423
+ tone: "default"
424
+ });
425
+ setProgress([currentProgress, assetsCount]);
426
+ }
427
+ return transactionDocs.push(doc);
428
+ }
429
+ const result = new Promise((resolve, reject) => {
430
+ const payloadIncludedDocs = payload.filter(item => item.include).map(item => item.doc);
431
+ mapLimit(payloadIncludedDocs, 3, asyncify(fetchDoc), err => {
432
+ if (err) {
433
+ setIsDuplicating(false);
434
+ setMessage({
435
+ tone: "critical",
436
+ text: "Duplication Failed"
437
+ });
438
+ console.error(err);
439
+ reject(new Error("Duplication Failed"));
440
+ }
441
+ resolve();
442
+ });
443
+ });
444
+ await result;
445
+ const transactionDocsMapped = transactionDocs.map(doc => {
446
+ const expr = ".._ref";
447
+ const references = extractWithPath(expr, doc);
448
+ if (!references.length) {
449
+ return doc;
450
+ }
451
+ references.forEach(ref => {
452
+ var _a2;
453
+ const newRefValue = (_a2 = svgMaps.find(asset => asset.old === ref.value)) == null ? void 0 : _a2.new;
454
+ if (newRefValue) {
455
+ const refPath = ref.path.join(".");
456
+ dset(doc, refPath, newRefValue);
457
+ }
458
+ });
459
+ return doc;
460
+ });
461
+ const transaction = destinationClient.transaction();
462
+ transactionDocsMapped.forEach(doc => {
463
+ transaction.createOrReplace(doc);
464
+ });
465
+ await transaction.commit().then(res => {
466
+ setMessage({
467
+ tone: "positive",
468
+ text: "Duplication complete!"
469
+ });
470
+ updatePayloadStatuses();
471
+ }).catch(err => {
472
+ setMessage({
473
+ tone: "critical",
474
+ text: err.details.description
475
+ });
476
+ });
477
+ setIsDuplicating(false);
478
+ setProgress([0, 0]);
479
+ if (onDuplicated) {
480
+ try {
481
+ await onDuplicated();
482
+ } catch (error) {
483
+ setMessage({
484
+ tone: "critical",
485
+ text: "Error in onDuplicated hook: ".concat(error)
486
+ });
487
+ }
488
+ }
489
+ }
490
+ function handleChange(e) {
491
+ if (!workspacesOptions.length) {
492
+ return;
493
+ }
494
+ const targeted = workspacesOptions.find(space => space.name === e.currentTarget.value);
495
+ if (targeted) {
496
+ setDestination(targeted);
497
+ }
498
+ }
499
+ const payloadCount = payload.length;
500
+ const firstSvgIndex = payload.findIndex(_ref4 => {
501
+ let {
502
+ doc
503
+ } = _ref4;
504
+ return doc.extension === "svg";
505
+ });
506
+ const selectedDocumentsCount = payload.filter(item => item.include && !isAssetId(item.doc._id)).length;
507
+ const selectedAssetsCount = payload.filter(item => item.include && isAssetId(item.doc._id)).length;
508
+ const selectedTotal = selectedDocumentsCount + selectedAssetsCount;
509
+ const destinationTitle = (_b = destination == null ? void 0 : destination.title) != null ? _b : destination == null ? void 0 : destination.name;
510
+ const hasMultipleProjectIds = new Set(workspacesOptions.map(space => space == null ? void 0 : space.projectId).filter(Boolean)).size > 1;
511
+ const headingText = [selectedTotal, "/", payloadCount, "Documents and Assets selected"].join(" ");
512
+ const buttonText = React.useMemo(() => {
513
+ const text = ["Duplicate"];
514
+ if (selectedDocumentsCount > 1) {
515
+ text.push(String(selectedDocumentsCount), selectedDocumentsCount === 1 ? "Document" : "Documents");
516
+ }
517
+ if (selectedAssetsCount > 1) {
518
+ text.push("and", String(selectedAssetsCount), selectedAssetsCount === 1 ? "Asset" : "Assets");
519
+ }
520
+ if (originClient.config().projectId !== (destination == null ? void 0 : destination.projectId)) {
521
+ text.push("between Projects");
522
+ }
523
+ text.push("to", String(destinationTitle));
524
+ return text.join(" ");
525
+ }, [selectedDocumentsCount, selectedAssetsCount, originClient, destination == null ? void 0 : destination.projectId, destinationTitle]);
526
+ if (workspacesOptions.length < 2) {
527
+ return /* @__PURE__ */jsxs(Feedback, {
528
+ tone: "critical",
529
+ children: [/* @__PURE__ */jsx("code", {
530
+ children: "sanity.config.ts"
531
+ }), " must contain at least two Workspaces to use this plugin."]
532
+ });
533
+ }
534
+ return /* @__PURE__ */jsx(Container, {
535
+ width: 1,
536
+ children: /* @__PURE__ */jsx(Card, {
537
+ border: true,
538
+ children: /* @__PURE__ */jsx(Stack, {
539
+ children: /* @__PURE__ */jsxs(Fragment, {
540
+ children: [/* @__PURE__ */jsx(Card, {
541
+ borderBottom: true,
542
+ padding: 4,
543
+ style: stickyStyles(isDarkMode),
544
+ children: /* @__PURE__ */jsxs(Stack, {
545
+ space: 4,
546
+ children: [/* @__PURE__ */jsxs(Flex, {
547
+ gap: 3,
548
+ children: [/* @__PURE__ */jsxs(Stack, {
549
+ style: {
550
+ flex: 1
551
+ },
552
+ space: 3,
553
+ children: [/* @__PURE__ */jsx(Label, {
554
+ children: "Duplicate from"
555
+ }), /* @__PURE__ */jsx(Select, {
556
+ readOnly: true,
557
+ value: (_c = workspacesOptions.find(space => space.disabled)) == null ? void 0 : _c.name,
558
+ children: workspacesOptions.filter(space => space.disabled).map(space => {
559
+ var _a2;
560
+ return /* @__PURE__ */jsxs("option", {
561
+ value: space.name,
562
+ disabled: space.disabled,
563
+ children: [(_a2 = space.title) != null ? _a2 : space.name, hasMultipleProjectIds ? " (".concat(space.projectId, ")") : ""]
564
+ }, space.name);
565
+ })
566
+ })]
567
+ }), /* @__PURE__ */jsx(Box, {
568
+ padding: 4,
569
+ paddingTop: 5,
570
+ paddingBottom: 0,
571
+ children: /* @__PURE__ */jsx(Text, {
572
+ size: 3,
573
+ children: /* @__PURE__ */jsx(ArrowRightIcon, {})
574
+ })
575
+ }), /* @__PURE__ */jsxs(Stack, {
576
+ style: {
577
+ flex: 1
578
+ },
579
+ space: 3,
580
+ children: [/* @__PURE__ */jsx(Label, {
581
+ children: "To Destination"
582
+ }), /* @__PURE__ */jsx(Select, {
583
+ onChange: handleChange,
584
+ children: workspacesOptions.map(space => {
585
+ var _a2;
586
+ return /* @__PURE__ */jsxs("option", {
587
+ value: space.name,
588
+ disabled: space.disabled,
589
+ children: [(_a2 = space.title) != null ? _a2 : space.name, hasMultipleProjectIds ? " (".concat(space.projectId, ")") : "", space.disabled ? " (Current)" : ""]
590
+ }, space.name);
591
+ })
592
+ })]
593
+ })]
594
+ }), isDuplicating && /* @__PURE__ */jsx(Card, {
595
+ border: true,
596
+ radius: 2,
597
+ children: /* @__PURE__ */jsx(Card, {
598
+ style: {
599
+ width: "100%",
600
+ transform: "scaleX(".concat(progress[0] / progress[1], ")"),
601
+ transformOrigin: "left",
602
+ transition: "transform .2s ease",
603
+ boxSizing: "border-box"
604
+ },
605
+ padding: 1,
606
+ tone: "positive"
607
+ })
608
+ }), payload.length > 0 && /* @__PURE__ */jsxs(Fragment, {
609
+ children: [/* @__PURE__ */jsx(Label, {
610
+ children: headingText
611
+ }), /* @__PURE__ */jsx(SelectButtons, {
612
+ payload,
613
+ setPayload
614
+ })]
615
+ })]
616
+ })
617
+ }), message && /* @__PURE__ */jsx(Box, {
618
+ paddingX: 4,
619
+ paddingTop: 4,
620
+ children: /* @__PURE__ */jsx(Card, {
621
+ padding: 3,
622
+ radius: 2,
623
+ shadow: 1,
624
+ tone: message.tone,
625
+ children: /* @__PURE__ */jsx(Text, {
626
+ size: 1,
627
+ children: message.text
628
+ })
629
+ })
630
+ }), payload.length > 0 && /* @__PURE__ */jsx(Stack, {
631
+ padding: 4,
632
+ space: 3,
633
+ children: payload.map((_ref5, index) => {
634
+ let {
635
+ doc,
636
+ include,
637
+ status,
638
+ hasDraft
639
+ } = _ref5;
640
+ const schemaType = schema.get(doc._type);
641
+ return /* @__PURE__ */jsxs(React.Fragment, {
642
+ children: [/* @__PURE__ */jsxs(Flex, {
643
+ align: "center",
644
+ children: [/* @__PURE__ */jsx(Checkbox, {
645
+ checked: include,
646
+ onChange: () => handleCheckbox(doc._id)
647
+ }), /* @__PURE__ */jsx(Box, {
648
+ flex: 1,
649
+ paddingX: 3,
650
+ children: schemaType ? /* @__PURE__ */jsx(Preview, {
651
+ value: doc,
652
+ schemaType
653
+ }) : /* @__PURE__ */jsx(Card, {
654
+ tone: "caution",
655
+ children: "Invalid schema type"
656
+ })
657
+ }), /* @__PURE__ */jsxs(Flex, {
658
+ align: "center",
659
+ gap: 2,
660
+ children: [hasDraft ? /* @__PURE__ */jsx(StatusBadge, {
661
+ status: "UNPUBLISHED",
662
+ isAsset: false
663
+ }) : null, /* @__PURE__ */jsx(StatusBadge, {
664
+ status,
665
+ isAsset: isAssetId(doc._id)
666
+ })]
667
+ })]
668
+ }), (doc == null ? void 0 : doc.extension) === "svg" && index === firstSvgIndex && /* @__PURE__ */jsx(Card, {
669
+ padding: 3,
670
+ radius: 2,
671
+ shadow: 1,
672
+ tone: "caution",
673
+ children: /* @__PURE__ */jsxs(Text, {
674
+ size: 1,
675
+ children: ["Due to how SVGs are sanitized after first uploaded, duplicated SVG assets may have new ", /* @__PURE__ */jsx("code", {
676
+ children: "_id"
677
+ }), "'s at the destination. The newly generated ", /* @__PURE__ */jsx("code", {
678
+ children: "_id"
679
+ }), " will be the same in each duplication, but it will never be the same ", /* @__PURE__ */jsx("code", {
680
+ children: "_id"
681
+ }), " as the first time this Asset was uploaded. References to the asset will be updated to use the new", " ", /* @__PURE__ */jsx("code", {
682
+ children: "_id"
683
+ }), "."]
684
+ })
685
+ })]
686
+ }, doc._id);
687
+ })
688
+ }), /* @__PURE__ */jsxs(Stack, {
689
+ space: 2,
690
+ padding: 4,
691
+ paddingTop: 0,
692
+ children: [hasReferences && /* @__PURE__ */jsx(Button, {
693
+ fontSize: 2,
694
+ padding: 4,
695
+ tone: "positive",
696
+ mode: "ghost",
697
+ icon: SearchIcon,
698
+ onClick: handleReferences,
699
+ text: "Gather References",
700
+ disabled: isDuplicating || !selectedTotal || isGathering
701
+ }), /* @__PURE__ */jsx(Button, {
702
+ fontSize: 2,
703
+ padding: 4,
704
+ tone: "positive",
705
+ icon: LaunchIcon,
706
+ onClick: handleDuplicate,
707
+ text: buttonText,
708
+ disabled: isDuplicating || !selectedTotal || isGathering
709
+ })]
710
+ })]
711
+ })
712
+ })
713
+ })
714
+ });
715
+ }
716
+ function DuplicatorQuery(props) {
717
+ var _a, _b;
718
+ const {
719
+ token,
720
+ pluginConfig
721
+ } = props;
722
+ const originClient = useClient(clientConfig);
723
+ const schema = useSchema();
724
+ const schemaTypes = schema.getTypeNames();
725
+ const [value, setValue] = useState("");
726
+ const [initialData, setInitialData] = useState({
727
+ docs: []
728
+ // draftIds: []
729
+ });
730
+
731
+ function handleSubmit(e) {
732
+ if (e) e.preventDefault();
733
+ originClient.fetch(value).then(res => {
734
+ const registeredAndPublishedDocs = res.length ? res.filter(doc => schemaTypes.includes(doc._type)).filter(doc => !doc._id.startsWith("drafts.")) : [];
735
+ setInitialData({
736
+ docs: registeredAndPublishedDocs
737
+ // draftIds: initialDraftIds
738
+ });
739
+ }).catch(err => console.error(err));
740
+ }
741
+ useEffect(() => {
742
+ var _a2;
743
+ if (!((_a2 = initialData.docs) == null ? void 0 : _a2.length) && value) {
744
+ handleSubmit();
745
+ }
746
+ }, []);
747
+ return /* @__PURE__ */jsx(Container, {
748
+ width: [1, 1, 1, 3],
749
+ padding: [0, 0, 0, 5],
750
+ children: /* @__PURE__ */jsxs(Grid, {
751
+ columns: [1, 1, 1, 2],
752
+ gap: [1, 1, 1, 4],
753
+ children: [/* @__PURE__ */jsx(Box, {
754
+ padding: [2, 2, 2, 0],
755
+ children: /* @__PURE__ */jsx(Card, {
756
+ padding: 4,
757
+ radius: 3,
758
+ border: true,
759
+ children: /* @__PURE__ */jsxs(Stack, {
760
+ space: 4,
761
+ children: [/* @__PURE__ */jsx(Box, {
762
+ children: /* @__PURE__ */jsx(Label, {
763
+ children: "Initial Documents Query"
764
+ })
765
+ }), /* @__PURE__ */jsx(Box, {
766
+ children: /* @__PURE__ */jsx(Text, {
767
+ children: "Start with a valid GROQ query to load initial documents. The query will need to return an Array of Objects. Drafts will be removed from the results."
768
+ })
769
+ }), /* @__PURE__ */jsx("form", {
770
+ onSubmit: handleSubmit,
771
+ children: /* @__PURE__ */jsxs(Flex, {
772
+ children: [/* @__PURE__ */jsx(Box, {
773
+ flex: 1,
774
+ paddingRight: 2,
775
+ children: /* @__PURE__ */jsx(TextInput, {
776
+ style: {
777
+ fontFamily: "monospace"
778
+ },
779
+ fontSize: 2,
780
+ onChange: event => setValue(event.currentTarget.value),
781
+ padding: 4,
782
+ placeholder: "*[_type == \"article\"]",
783
+ value: value != null ? value : ""
784
+ })
785
+ }), /* @__PURE__ */jsx(Button, {
786
+ padding: 2,
787
+ paddingX: 4,
788
+ tone: "primary",
789
+ onClick: handleSubmit,
790
+ text: "Query",
791
+ disabled: !value
792
+ })]
793
+ })
794
+ })]
795
+ })
796
+ })
797
+ }), !((_a = initialData.docs) == null ? void 0 : _a.length) || initialData.docs.length < 1 && /* @__PURE__ */jsx(Container, {
798
+ width: 1,
799
+ children: /* @__PURE__ */jsx(Card, {
800
+ padding: 5,
801
+ children: value ? "No Documents registered to the Schema match this query" : "Start with a valid GROQ query"
802
+ })
803
+ }), ((_b = initialData.docs) == null ? void 0 : _b.length) > 0 && /* @__PURE__ */jsx(Duplicator, {
804
+ docs: initialData.docs,
805
+ token,
806
+ pluginConfig
807
+ })]
808
+ })
809
+ });
810
+ }
811
+ function DuplicatorWrapper(props) {
812
+ const {
813
+ docs,
814
+ token,
815
+ pluginConfig,
816
+ onDuplicated
817
+ } = props;
818
+ const [inbound, setInbound] = useState([]);
819
+ const {
820
+ follow = []
821
+ } = pluginConfig;
822
+ const [mode, setMode] = useState(follow.length === 1 ? follow[0] : "outbound");
823
+ const client = useClient(clientConfig);
824
+ useEffect(() => {
825
+ (async () => {
826
+ if (follow.includes("inbound")) {
827
+ const inboundReferences = await client.fetch("*[references($id)]", {
828
+ id: docs[0]._id
829
+ });
830
+ setInbound([...props.docs, ...inboundReferences]);
831
+ }
832
+ })();
833
+ }, []);
834
+ return /* @__PURE__ */jsxs(Container, {
835
+ children: [follow.length > 1 && (follow.includes("inbound") || follow.includes("outbound")) ? /* @__PURE__ */jsx(Card, {
836
+ paddingX: 4,
837
+ paddingBottom: 4,
838
+ marginBottom: 4,
839
+ borderBottom: true,
840
+ children: /* @__PURE__ */jsxs(Grid, {
841
+ columns: 2,
842
+ gap: 4,
843
+ children: [follow.includes("outbound") ? /* @__PURE__ */jsx(Button, {
844
+ mode: "ghost",
845
+ tone: "primary",
846
+ selected: mode === "outbound",
847
+ onClick: () => setMode("outbound"),
848
+ text: "Outbound"
849
+ }) : null, follow.includes("inbound") ? /* @__PURE__ */jsx(Button, {
850
+ mode: "ghost",
851
+ tone: "primary",
852
+ selected: mode === "inbound",
853
+ onClick: () => setMode("inbound"),
854
+ disabled: inbound.length === 0,
855
+ text: inbound.length > 0 ? "Inbound (".concat(inbound.length, ")") : "No inbound references"
856
+ }) : null]
857
+ })
858
+ }) : null, /* @__PURE__ */jsx(Duplicator, {
859
+ docs: mode === "outbound" ? docs : inbound,
860
+ token,
861
+ pluginConfig,
862
+ onDuplicated
863
+ })]
864
+ });
865
+ }
866
+ const SECRET_NAMESPACE = "CrossDatasetDuplicator";
867
+ const DEFAULT_CONFIG = {
868
+ tool: true,
869
+ types: [],
870
+ filter: "",
871
+ follow: ["outbound"]
872
+ };
873
+ function ResetSecret() {
874
+ const client = useClient(clientConfig);
875
+ const handleClick = useCallback(() => {
876
+ client.delete({
877
+ query: "*[_id == \"secrets.".concat(SECRET_NAMESPACE, "\"]")
878
+ });
879
+ }, [client]);
880
+ return /* @__PURE__ */jsx(Flex, {
881
+ align: "center",
882
+ justify: "flex-end",
883
+ paddingX: [2, 2, 2, 5],
884
+ paddingY: 5,
885
+ children: /* @__PURE__ */jsx(Button, {
886
+ text: "Reset Secret",
887
+ onClick: handleClick,
888
+ mode: "ghost",
889
+ tone: "critical",
890
+ fontSize: 1,
891
+ padding: 2
892
+ })
893
+ });
894
+ }
895
+ const CrossDatasetDuplicatorContext = createContext(DEFAULT_CONFIG);
896
+ function useCrossDatasetDuplicatorConfig() {
897
+ const pluginConfig = useContext(CrossDatasetDuplicatorContext);
898
+ return pluginConfig;
899
+ }
900
+ function ConfigProvider(props) {
901
+ const {
902
+ pluginConfig,
903
+ ...rest
904
+ } = props;
905
+ return /* @__PURE__ */jsx(CrossDatasetDuplicatorContext.Provider, {
906
+ value: pluginConfig,
907
+ children: props.renderDefault(rest)
908
+ });
909
+ }
910
+ const secretConfigKeys = [{
911
+ key: "bearerToken",
912
+ title: "An API token with Viewer permissions is required to duplicate the original files of assets, and will be used for all Duplications. Create one at sanity.io/manage",
913
+ description: ""
914
+ }];
915
+ function CrossDatasetDuplicator(props) {
916
+ const {
917
+ mode = "tool",
918
+ docs = [],
919
+ onDuplicated
920
+ } = props != null ? props : {};
921
+ const pluginConfig = useCrossDatasetDuplicatorConfig();
922
+ const {
923
+ loading,
924
+ secrets
925
+ } = useSecrets(SECRET_NAMESPACE);
926
+ const [showSecretsPrompt, setShowSecretsPrompt] = useState(false);
927
+ useEffect(() => {
928
+ if (secrets) {
929
+ setShowSecretsPrompt(!(secrets == null ? void 0 : secrets.bearerToken));
930
+ }
931
+ }, [secrets]);
932
+ if (loading) {
933
+ return /* @__PURE__ */jsx(Flex, {
934
+ justify: "center",
935
+ align: "center",
936
+ children: /* @__PURE__ */jsx(Box, {
937
+ padding: 5,
938
+ children: /* @__PURE__ */jsx(Spinner, {})
939
+ })
940
+ });
941
+ }
942
+ if (!loading && showSecretsPrompt || !(secrets == null ? void 0 : secrets.bearerToken)) {
943
+ return /* @__PURE__ */jsx(SettingsView, {
944
+ title: "Token Required",
945
+ namespace: SECRET_NAMESPACE,
946
+ keys: secretConfigKeys,
947
+ onClose: () => setShowSecretsPrompt(false)
948
+ });
949
+ }
950
+ if (mode === "tool" && pluginConfig) {
951
+ return /* @__PURE__ */jsxs(Fragment, {
952
+ children: [/* @__PURE__ */jsx(DuplicatorQuery, {
953
+ token: secrets == null ? void 0 : secrets.bearerToken,
954
+ pluginConfig
955
+ }), /* @__PURE__ */jsx(ResetSecret, {})]
956
+ });
957
+ }
958
+ if (!(docs == null ? void 0 : docs.length)) {
959
+ return /* @__PURE__ */jsx(Feedback, {
960
+ children: "No docs passed into Duplicator Tool"
961
+ });
962
+ }
963
+ if (!pluginConfig) {
964
+ return /* @__PURE__ */jsx(Feedback, {
965
+ children: "No plugin config"
966
+ });
967
+ }
968
+ return /* @__PURE__ */jsx(DuplicatorWrapper, {
969
+ docs,
970
+ token: secrets == null ? void 0 : secrets.bearerToken,
971
+ pluginConfig,
972
+ onDuplicated
973
+ });
974
+ }
975
+ function CrossDatasetDuplicatorAction(props) {
976
+ const {
977
+ docs = [],
978
+ onDuplicated
979
+ } = props;
980
+ return /* @__PURE__ */jsx(CrossDatasetDuplicator, {
981
+ mode: "action",
982
+ docs,
983
+ onDuplicated
984
+ });
985
+ }
986
+ const DuplicateToAction = props => {
987
+ const {
988
+ draft,
989
+ published,
990
+ onComplete
991
+ } = props;
992
+ const [dialogOpen, setDialogOpen] = useState(false);
993
+ return {
994
+ disabled: draft,
995
+ title: draft ? "Document must be Published to begin" : null,
996
+ label: "Duplicate to...",
997
+ dialog: dialogOpen && published && {
998
+ type: "modal",
999
+ title: "Cross Dataset Duplicator",
1000
+ content: /* @__PURE__ */jsx(CrossDatasetDuplicatorAction, {
1001
+ docs: [published]
1002
+ }),
1003
+ onClose: () => {
1004
+ onComplete();
1005
+ setDialogOpen(false);
1006
+ }
1007
+ },
1008
+ onHandle: () => setDialogOpen(true),
1009
+ icon: LaunchIcon
1010
+ };
1011
+ };
1012
+ DuplicateToAction.action = "duplicateTo";
1013
+ function CrossDatasetDuplicatorTool(props) {
1014
+ var _a;
1015
+ const {
1016
+ docs = []
1017
+ } = (_a = props.tool.options) != null ? _a : {};
1018
+ return /* @__PURE__ */jsx(CrossDatasetDuplicator, {
1019
+ mode: "tool",
1020
+ docs
1021
+ });
1022
+ }
1023
+ const crossDatasetDuplicatorTool = () => ({
1024
+ title: "Duplicator",
1025
+ name: "duplicator",
1026
+ icon: LaunchIcon,
1027
+ component: CrossDatasetDuplicatorTool,
1028
+ options: {
1029
+ docs: []
1030
+ }
1031
+ });
1032
+ const crossDatasetDuplicator = definePlugin(function () {
1033
+ let config = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
1034
+ const pluginConfig = {
1035
+ ...DEFAULT_CONFIG,
1036
+ ...config
1037
+ };
1038
+ const {
1039
+ types
1040
+ } = pluginConfig;
1041
+ return {
1042
+ name: "@sanity/cross-dataset-duplicator",
1043
+ tools: prev => pluginConfig.tool ? [...prev, crossDatasetDuplicatorTool()] : prev,
1044
+ studio: {
1045
+ components: {
1046
+ layout: props => ConfigProvider({
1047
+ ...props,
1048
+ pluginConfig
1049
+ })
1050
+ }
1051
+ },
1052
+ document: {
1053
+ actions: (prev, _ref6) => {
1054
+ let {
1055
+ schemaType
1056
+ } = _ref6;
1057
+ return types && types.includes(schemaType) ? [...prev, DuplicateToAction] : prev;
1058
+ }
1059
+ }
1060
+ };
1061
+ });
1062
+ export { CrossDatasetDuplicatorAction, DuplicateToAction, crossDatasetDuplicator, useCrossDatasetDuplicatorConfig };
1063
+ //# sourceMappingURL=index.esm.js.map