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