medusa-product-helper 0.0.3 → 0.0.5

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.
@@ -1,6 +1,1012 @@
1
1
  "use strict";
2
+ const jsxRuntime = require("react/jsx-runtime");
3
+ const adminSdk = require("@medusajs/admin-sdk");
4
+ const ui = require("@medusajs/ui");
5
+ const react = require("react");
6
+ const reactQuery = require("@tanstack/react-query");
7
+ const METADATA_FIELD_TYPES = ["number", "text", "file", "bool"];
8
+ const VALID_FIELD_TYPES = new Set(METADATA_FIELD_TYPES);
9
+ function normalizeMetadataDescriptors(input) {
10
+ if (!Array.isArray(input)) {
11
+ return [];
12
+ }
13
+ const seenKeys = /* @__PURE__ */ new Set();
14
+ const normalized = [];
15
+ for (const item of input) {
16
+ if (!item || typeof item !== "object") {
17
+ continue;
18
+ }
19
+ const key = getNormalizedKey(item.key);
20
+ if (!key || seenKeys.has(key)) {
21
+ continue;
22
+ }
23
+ const type = getNormalizedType(item.type);
24
+ if (!type) {
25
+ continue;
26
+ }
27
+ const label = getNormalizedLabel(item.label);
28
+ const filterable = typeof item.filterable === "boolean" ? item.filterable : Boolean(item.filterable);
29
+ normalized.push({
30
+ key,
31
+ type,
32
+ ...label ? { label } : {},
33
+ ...filterable ? { filterable: true } : {}
34
+ });
35
+ seenKeys.add(key);
36
+ }
37
+ return normalized;
38
+ }
39
+ function buildInitialFormState(descriptors, metadata) {
40
+ return descriptors.reduce(
41
+ (acc, descriptor) => {
42
+ const currentValue = metadata && typeof metadata === "object" ? metadata[descriptor.key] : void 0;
43
+ acc[descriptor.key] = normalizeFormValue(descriptor, currentValue);
44
+ return acc;
45
+ },
46
+ {}
47
+ );
48
+ }
49
+ function buildMetadataPayload({
50
+ descriptors,
51
+ values,
52
+ originalMetadata
53
+ }) {
54
+ const base = originalMetadata && typeof originalMetadata === "object" ? { ...originalMetadata } : {};
55
+ descriptors.forEach((descriptor) => {
56
+ const rawValue = values[descriptor.key];
57
+ const coerced = coerceMetadataValue(descriptor, rawValue);
58
+ if (typeof coerced === "undefined") {
59
+ delete base[descriptor.key];
60
+ return;
61
+ }
62
+ base[descriptor.key] = coerced;
63
+ });
64
+ return base;
65
+ }
66
+ function hasMetadataChanges({
67
+ descriptors,
68
+ values,
69
+ originalMetadata
70
+ }) {
71
+ const next = buildMetadataPayload({ descriptors, values, originalMetadata });
72
+ const prev = originalMetadata && typeof originalMetadata === "object" ? originalMetadata : {};
73
+ return descriptors.some((descriptor) => {
74
+ const prevValue = prev[descriptor.key];
75
+ const nextValue = next[descriptor.key];
76
+ return !isDeepEqual(prevValue, nextValue);
77
+ });
78
+ }
79
+ function validateValueForDescriptor(descriptor, value) {
80
+ if (descriptor.type === "number") {
81
+ if (value === "" || value === null || typeof value === "undefined") {
82
+ return void 0;
83
+ }
84
+ const numericValue = typeof value === "number" ? value : Number(String(value).trim());
85
+ if (Number.isNaN(numericValue)) {
86
+ return "Enter a valid number";
87
+ }
88
+ }
89
+ if (descriptor.type === "file") {
90
+ if (!value) {
91
+ return void 0;
92
+ }
93
+ try {
94
+ new URL(String(value).trim());
95
+ } catch (err) {
96
+ return "Enter a valid URL";
97
+ }
98
+ }
99
+ return void 0;
100
+ }
101
+ function normalizeFormValue(descriptor, currentValue) {
102
+ if (descriptor.type === "bool") {
103
+ return Boolean(currentValue);
104
+ }
105
+ if ((descriptor.type === "number" || descriptor.type === "text") && typeof currentValue === "number") {
106
+ return currentValue.toString();
107
+ }
108
+ if (typeof currentValue === "string" || typeof currentValue === "number") {
109
+ return String(currentValue);
110
+ }
111
+ return "";
112
+ }
113
+ function coerceMetadataValue(descriptor, value) {
114
+ if (value === "" || value === null || typeof value === "undefined") {
115
+ return void 0;
116
+ }
117
+ if (descriptor.type === "bool") {
118
+ if (typeof value === "boolean") {
119
+ return value;
120
+ }
121
+ if (typeof value === "number") {
122
+ return value !== 0;
123
+ }
124
+ if (typeof value === "string") {
125
+ const normalized = value.trim().toLowerCase();
126
+ if (!normalized) {
127
+ return void 0;
128
+ }
129
+ if (["true", "1", "yes", "y", "on"].includes(normalized)) {
130
+ return true;
131
+ }
132
+ if (["false", "0", "no", "n", "off"].includes(normalized)) {
133
+ return false;
134
+ }
135
+ }
136
+ return Boolean(value);
137
+ }
138
+ if (descriptor.type === "number") {
139
+ if (typeof value === "number") {
140
+ return value;
141
+ }
142
+ const parsed = Number(String(value).trim());
143
+ return Number.isNaN(parsed) ? void 0 : parsed;
144
+ }
145
+ return String(value).trim();
146
+ }
147
+ function getNormalizedKey(value) {
148
+ if (typeof value !== "string") {
149
+ return null;
150
+ }
151
+ const trimmed = value.trim();
152
+ return trimmed.length ? trimmed : null;
153
+ }
154
+ function getNormalizedType(value) {
155
+ if (typeof value !== "string") {
156
+ return null;
157
+ }
158
+ const type = value.trim().toLowerCase();
159
+ return VALID_FIELD_TYPES.has(type) ? type : null;
160
+ }
161
+ function getNormalizedLabel(value) {
162
+ if (typeof value !== "string") {
163
+ return void 0;
164
+ }
165
+ const trimmed = value.trim();
166
+ return trimmed.length ? trimmed : void 0;
167
+ }
168
+ function isDeepEqual(a, b) {
169
+ if (a === b) {
170
+ return true;
171
+ }
172
+ if (typeof a === "object" && typeof b === "object" && a !== null && b !== null) {
173
+ const aKeys = Object.keys(a);
174
+ const bKeys = Object.keys(b);
175
+ if (aKeys.length !== bKeys.length) {
176
+ return false;
177
+ }
178
+ return aKeys.every(
179
+ (key) => isDeepEqual(
180
+ a[key],
181
+ b[key]
182
+ )
183
+ );
184
+ }
185
+ return false;
186
+ }
187
+ const CONFIG_ENDPOINT = "/admin/product-metadata-config";
188
+ const QUERY_KEY = ["medusa-product-helper", "metadata-config"];
189
+ const useMetadataConfig = (entity) => {
190
+ return reactQuery.useQuery({
191
+ queryKey: [...QUERY_KEY, entity],
192
+ queryFn: async () => {
193
+ const response = await fetch(`${CONFIG_ENDPOINT}?entity=${entity}`, {
194
+ credentials: "include"
195
+ });
196
+ if (!response.ok) {
197
+ throw new Error("Unable to load metadata configuration");
198
+ }
199
+ const payload = await response.json();
200
+ return normalizeMetadataDescriptors(payload.metadataDescriptors);
201
+ },
202
+ staleTime: 5 * 60 * 1e3
203
+ });
204
+ };
205
+ const useProductMetadataConfig = () => useMetadataConfig("product");
206
+ const useCategoryMetadataConfig = () => useMetadataConfig("category");
207
+ const CONFIG_DOCS_URL$1 = "https://docs.medusajs.com/admin/extension-points/widgets#product-category-details";
208
+ const CategoryMetadataTableWidget = ({ data }) => {
209
+ const { data: descriptors = [], isPending, isError } = useCategoryMetadataConfig();
210
+ const metadata = (data == null ? void 0 : data.metadata) ?? {};
211
+ const [baselineMetadata, setBaselineMetadata] = react.useState(metadata);
212
+ const queryClient = reactQuery.useQueryClient();
213
+ react.useEffect(() => {
214
+ setBaselineMetadata(metadata);
215
+ }, [metadata]);
216
+ const initialState = react.useMemo(
217
+ () => buildInitialFormState(descriptors, baselineMetadata),
218
+ [descriptors, baselineMetadata]
219
+ );
220
+ const [values, setValues] = react.useState(
221
+ initialState
222
+ );
223
+ const [isSaving, setIsSaving] = react.useState(false);
224
+ react.useEffect(() => {
225
+ setValues(initialState);
226
+ }, [initialState]);
227
+ const errors = react.useMemo(() => {
228
+ return descriptors.reduce((acc, descriptor) => {
229
+ const error = validateValueForDescriptor(descriptor, values[descriptor.key]);
230
+ if (error) {
231
+ acc[descriptor.key] = error;
232
+ }
233
+ return acc;
234
+ }, {});
235
+ }, [descriptors, values]);
236
+ const hasErrors = Object.keys(errors).length > 0;
237
+ const isDirty = react.useMemo(() => {
238
+ return hasMetadataChanges({
239
+ descriptors,
240
+ values,
241
+ originalMetadata: baselineMetadata
242
+ });
243
+ }, [descriptors, values, baselineMetadata]);
244
+ const handleStringChange = (key, nextValue) => {
245
+ setValues((prev) => ({
246
+ ...prev,
247
+ [key]: nextValue
248
+ }));
249
+ };
250
+ const handleBooleanChange = (key, nextValue) => {
251
+ setValues((prev) => ({
252
+ ...prev,
253
+ [key]: nextValue
254
+ }));
255
+ };
256
+ const handleReset = () => {
257
+ setValues(initialState);
258
+ };
259
+ const handleSubmit = async () => {
260
+ if (!(data == null ? void 0 : data.id) || !descriptors.length) {
261
+ return;
262
+ }
263
+ setIsSaving(true);
264
+ try {
265
+ const metadataPayload = buildMetadataPayload({
266
+ descriptors,
267
+ values,
268
+ originalMetadata: baselineMetadata
269
+ });
270
+ const response = await fetch(`/admin/product-categories/${data.id}`, {
271
+ method: "POST",
272
+ credentials: "include",
273
+ headers: {
274
+ "Content-Type": "application/json"
275
+ },
276
+ body: JSON.stringify({
277
+ metadata: metadataPayload
278
+ })
279
+ });
280
+ if (!response.ok) {
281
+ const payload = await response.json().catch(() => null);
282
+ throw new Error((payload == null ? void 0 : payload.message) ?? "Unable to save metadata");
283
+ }
284
+ const updated = await response.json();
285
+ const nextMetadata = updated.product_category.metadata;
286
+ setBaselineMetadata(nextMetadata);
287
+ setValues(buildInitialFormState(descriptors, nextMetadata));
288
+ ui.toast.success("Metadata saved");
289
+ await queryClient.invalidateQueries({
290
+ queryKey: ["product-categories"]
291
+ });
292
+ } catch (error) {
293
+ ui.toast.error(error instanceof Error ? error.message : "Save failed");
294
+ } finally {
295
+ setIsSaving(false);
296
+ }
297
+ };
298
+ return /* @__PURE__ */ jsxRuntime.jsxs(ui.Container, { className: "flex flex-col gap-y-4", children: [
299
+ /* @__PURE__ */ jsxRuntime.jsxs("header", { className: "flex flex-col gap-y-1", children: [
300
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-x-3", children: [
301
+ /* @__PURE__ */ jsxRuntime.jsx(ui.Heading, { level: "h2", children: "Metadata" }),
302
+ /* @__PURE__ */ jsxRuntime.jsx(ui.Badge, { size: "2xsmall", rounded: "full", children: descriptors.length })
303
+ ] }),
304
+ /* @__PURE__ */ jsxRuntime.jsx(ui.Text, { className: "text-ui-fg-subtle", children: "Structured metadata mapped to the keys you configured in the plugin options." })
305
+ ] }),
306
+ isPending ? /* @__PURE__ */ jsxRuntime.jsx(ui.Skeleton, { className: "h-[160px] w-full" }) : isError ? /* @__PURE__ */ jsxRuntime.jsxs(ui.InlineTip, { variant: "error", label: "Configuration unavailable", children: [
307
+ "Unable to load metadata configuration for this plugin. Confirm that the plugin is registered with options in ",
308
+ /* @__PURE__ */ jsxRuntime.jsx("code", { children: "medusa-config.ts" }),
309
+ "."
310
+ ] }) : !descriptors.length ? /* @__PURE__ */ jsxRuntime.jsxs(ui.InlineTip, { variant: "info", label: "No configured metadata keys", children: [
311
+ "Provide a ",
312
+ /* @__PURE__ */ jsxRuntime.jsx("code", { children: "metadataDescriptors" }),
313
+ " array in the plugin options to control which keys show up here.",
314
+ " ",
315
+ /* @__PURE__ */ jsxRuntime.jsx(
316
+ "a",
317
+ {
318
+ className: "text-ui-fg-interactive underline",
319
+ href: CONFIG_DOCS_URL$1,
320
+ target: "_blank",
321
+ rel: "noreferrer",
322
+ children: "Learn how to configure it."
323
+ }
324
+ )
325
+ ] }) : /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
326
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "overflow-hidden rounded-lg border border-ui-border-base", children: /* @__PURE__ */ jsxRuntime.jsxs("table", { className: "min-w-full divide-y divide-ui-border-base", children: [
327
+ /* @__PURE__ */ jsxRuntime.jsx("thead", { className: "bg-ui-bg-subtle", children: /* @__PURE__ */ jsxRuntime.jsxs("tr", { children: [
328
+ /* @__PURE__ */ jsxRuntime.jsx(
329
+ "th",
330
+ {
331
+ scope: "col",
332
+ className: "txt-compact-xsmall-plus text-left uppercase tracking-wide text-ui-fg-muted px-4 py-3",
333
+ children: "Label"
334
+ }
335
+ ),
336
+ /* @__PURE__ */ jsxRuntime.jsx(
337
+ "th",
338
+ {
339
+ scope: "col",
340
+ className: "txt-compact-xsmall-plus text-left uppercase tracking-wide text-ui-fg-muted px-4 py-3",
341
+ children: "Value"
342
+ }
343
+ )
344
+ ] }) }),
345
+ /* @__PURE__ */ jsxRuntime.jsx("tbody", { className: "divide-y divide-ui-border-subtle bg-ui-bg-base", children: descriptors.map((descriptor) => {
346
+ const value = values[descriptor.key];
347
+ const error = errors[descriptor.key];
348
+ return /* @__PURE__ */ jsxRuntime.jsxs("tr", { children: [
349
+ /* @__PURE__ */ jsxRuntime.jsx(
350
+ "th",
351
+ {
352
+ scope: "row",
353
+ className: "txt-compact-medium text-ui-fg-base align-top px-4 py-4",
354
+ children: /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex flex-col gap-y-1", children: [
355
+ /* @__PURE__ */ jsxRuntime.jsx("span", { children: descriptor.label ?? descriptor.key }),
356
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "txt-compact-xsmall-plus text-ui-fg-muted uppercase tracking-wide", children: descriptor.type })
357
+ ] })
358
+ }
359
+ ),
360
+ /* @__PURE__ */ jsxRuntime.jsx("td", { className: "align-top px-4 py-4", children: /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex flex-col gap-y-2", children: [
361
+ /* @__PURE__ */ jsxRuntime.jsx(
362
+ ValueField$1,
363
+ {
364
+ descriptor,
365
+ value,
366
+ onStringChange: handleStringChange,
367
+ onBooleanChange: handleBooleanChange
368
+ }
369
+ ),
370
+ error && /* @__PURE__ */ jsxRuntime.jsx(ui.Text, { className: "txt-compact-small text-ui-fg-error", children: error })
371
+ ] }) })
372
+ ] }, descriptor.key);
373
+ }) })
374
+ ] }) }),
375
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex flex-col gap-y-3 border-t border-ui-border-subtle pt-3 md:flex-row md:items-center md:justify-between", children: [
376
+ /* @__PURE__ */ jsxRuntime.jsx(ui.Text, { className: "text-ui-fg-muted", children: "Changes are stored on the category metadata object. Clearing a field removes the corresponding key on save." }),
377
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-x-2", children: [
378
+ /* @__PURE__ */ jsxRuntime.jsx(
379
+ ui.Button,
380
+ {
381
+ variant: "secondary",
382
+ size: "small",
383
+ disabled: !isDirty || isSaving,
384
+ onClick: handleReset,
385
+ children: "Reset"
386
+ }
387
+ ),
388
+ /* @__PURE__ */ jsxRuntime.jsx(
389
+ ui.Button,
390
+ {
391
+ size: "small",
392
+ onClick: handleSubmit,
393
+ disabled: !isDirty || hasErrors || isSaving,
394
+ isLoading: isSaving,
395
+ children: "Save metadata"
396
+ }
397
+ )
398
+ ] })
399
+ ] })
400
+ ] })
401
+ ] });
402
+ };
403
+ const ValueField$1 = ({
404
+ descriptor,
405
+ value,
406
+ onStringChange,
407
+ onBooleanChange
408
+ }) => {
409
+ const fileInputRef = react.useRef(null);
410
+ const [isUploading, setIsUploading] = react.useState(false);
411
+ const handleFileUpload = async (event) => {
412
+ var _a;
413
+ const file = (_a = event.target.files) == null ? void 0 : _a[0];
414
+ if (!file) {
415
+ return;
416
+ }
417
+ setIsUploading(true);
418
+ try {
419
+ const formData = new FormData();
420
+ formData.append("files", file);
421
+ const response = await fetch("/admin/uploads", {
422
+ method: "POST",
423
+ credentials: "include",
424
+ body: formData
425
+ });
426
+ if (!response.ok) {
427
+ const payload = await response.json().catch(() => null);
428
+ throw new Error((payload == null ? void 0 : payload.message) ?? "File upload failed");
429
+ }
430
+ const result = await response.json();
431
+ if (result.files && result.files.length > 0) {
432
+ const uploadedFile = result.files[0];
433
+ const fileUrl = uploadedFile.url || uploadedFile.key;
434
+ if (fileUrl) {
435
+ onStringChange(descriptor.key, fileUrl);
436
+ ui.toast.success("File uploaded successfully");
437
+ } else {
438
+ throw new Error("File upload succeeded but no URL returned");
439
+ }
440
+ } else {
441
+ throw new Error("File upload failed - no files returned");
442
+ }
443
+ } catch (error) {
444
+ ui.toast.error(
445
+ error instanceof Error ? error.message : "Failed to upload file"
446
+ );
447
+ } finally {
448
+ setIsUploading(false);
449
+ if (fileInputRef.current) {
450
+ fileInputRef.current.value = "";
451
+ }
452
+ }
453
+ };
454
+ if (descriptor.type === "bool") {
455
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-x-2", children: [
456
+ /* @__PURE__ */ jsxRuntime.jsx(
457
+ ui.Switch,
458
+ {
459
+ checked: Boolean(value),
460
+ onCheckedChange: (checked) => onBooleanChange(descriptor.key, Boolean(checked)),
461
+ "aria-label": `Toggle ${descriptor.label ?? descriptor.key}`
462
+ }
463
+ ),
464
+ /* @__PURE__ */ jsxRuntime.jsx(ui.Text, { className: "txt-compact-small text-ui-fg-muted", children: Boolean(value) ? "True" : "False" })
465
+ ] });
466
+ }
467
+ if (descriptor.type === "text") {
468
+ return /* @__PURE__ */ jsxRuntime.jsx(
469
+ ui.Textarea,
470
+ {
471
+ value: value ?? "",
472
+ placeholder: "Enter text",
473
+ rows: 3,
474
+ onChange: (event) => onStringChange(descriptor.key, event.target.value)
475
+ }
476
+ );
477
+ }
478
+ if (descriptor.type === "number") {
479
+ return /* @__PURE__ */ jsxRuntime.jsx(
480
+ ui.Input,
481
+ {
482
+ type: "text",
483
+ inputMode: "decimal",
484
+ placeholder: "0.00",
485
+ value: value ?? "",
486
+ onChange: (event) => onStringChange(descriptor.key, event.target.value)
487
+ }
488
+ );
489
+ }
490
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex flex-col gap-y-2", children: [
491
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-x-2", children: [
492
+ /* @__PURE__ */ jsxRuntime.jsx(
493
+ ui.Input,
494
+ {
495
+ type: "url",
496
+ placeholder: "https://example.com/file",
497
+ value: value ?? "",
498
+ onChange: (event) => onStringChange(descriptor.key, event.target.value),
499
+ className: "flex-1"
500
+ }
501
+ ),
502
+ /* @__PURE__ */ jsxRuntime.jsx(
503
+ "input",
504
+ {
505
+ ref: fileInputRef,
506
+ type: "file",
507
+ className: "hidden",
508
+ onChange: handleFileUpload,
509
+ disabled: isUploading,
510
+ "aria-label": `Upload file for ${descriptor.label ?? descriptor.key}`
511
+ }
512
+ ),
513
+ /* @__PURE__ */ jsxRuntime.jsx(
514
+ ui.Button,
515
+ {
516
+ type: "button",
517
+ variant: "secondary",
518
+ size: "small",
519
+ onClick: () => {
520
+ var _a;
521
+ return (_a = fileInputRef.current) == null ? void 0 : _a.click();
522
+ },
523
+ disabled: isUploading,
524
+ isLoading: isUploading,
525
+ children: isUploading ? "Uploading..." : "Upload"
526
+ }
527
+ )
528
+ ] }),
529
+ typeof value === "string" && value && /* @__PURE__ */ jsxRuntime.jsx(
530
+ "a",
531
+ {
532
+ className: "txt-compact-small-plus text-ui-fg-interactive underline",
533
+ href: value,
534
+ target: "_blank",
535
+ rel: "noreferrer",
536
+ children: "View file"
537
+ }
538
+ )
539
+ ] });
540
+ };
541
+ adminSdk.defineWidgetConfig({
542
+ zone: "product_category.details.after"
543
+ });
544
+ const HideCategoryDefaultMetadataWidget = () => {
545
+ react.useEffect(() => {
546
+ const hideMetadataSection = () => {
547
+ const headings = document.querySelectorAll("h2");
548
+ headings.forEach((heading) => {
549
+ var _a;
550
+ if (((_a = heading.textContent) == null ? void 0 : _a.trim()) === "Metadata") {
551
+ let container = heading.parentElement;
552
+ while (container && container !== document.body) {
553
+ const hasContainerClass = container.classList.toString().includes("Container");
554
+ const isInSidebar = container.closest('[class*="Sidebar"]') || container.closest('[class*="sidebar"]');
555
+ if (hasContainerClass || isInSidebar) {
556
+ const editLink = container.querySelector('a[href*="metadata/edit"]');
557
+ const badge = container.querySelector('div[class*="Badge"]');
558
+ if (editLink && badge) {
559
+ container.style.display = "none";
560
+ container.setAttribute("data-category-metadata-hidden", "true");
561
+ return;
562
+ }
563
+ }
564
+ container = container.parentElement;
565
+ }
566
+ }
567
+ });
568
+ };
569
+ const runHide = () => {
570
+ setTimeout(hideMetadataSection, 100);
571
+ };
572
+ runHide();
573
+ const observer = new MutationObserver(() => {
574
+ const alreadyHidden = document.querySelector(
575
+ '[data-category-metadata-hidden="true"]'
576
+ );
577
+ if (!alreadyHidden) {
578
+ runHide();
579
+ }
580
+ });
581
+ observer.observe(document.body, {
582
+ childList: true,
583
+ subtree: true
584
+ });
585
+ return () => {
586
+ observer.disconnect();
587
+ const hidden = document.querySelector(
588
+ '[data-category-metadata-hidden="true"]'
589
+ );
590
+ if (hidden) {
591
+ hidden.style.display = "";
592
+ hidden.removeAttribute("data-category-metadata-hidden");
593
+ }
594
+ };
595
+ }, []);
596
+ return null;
597
+ };
598
+ adminSdk.defineWidgetConfig({
599
+ zone: "product_category.details.side.before"
600
+ });
601
+ const HideDefaultMetadataWidget = () => {
602
+ react.useEffect(() => {
603
+ const hideMetadataSection = () => {
604
+ const headings = document.querySelectorAll("h2");
605
+ headings.forEach((heading) => {
606
+ var _a;
607
+ if (((_a = heading.textContent) == null ? void 0 : _a.trim()) === "Metadata") {
608
+ let container = heading.parentElement;
609
+ while (container && container !== document.body) {
610
+ const hasContainerClass = container.classList.toString().includes("Container");
611
+ const isInSidebar = container.closest('[class*="Sidebar"]') || container.closest('[class*="sidebar"]');
612
+ if (hasContainerClass || isInSidebar) {
613
+ const editLink = container.querySelector('a[href*="metadata/edit"]');
614
+ const badge = container.querySelector('div[class*="Badge"]');
615
+ if (editLink && badge) {
616
+ container.style.display = "none";
617
+ container.setAttribute("data-metadata-hidden", "true");
618
+ return;
619
+ }
620
+ }
621
+ container = container.parentElement;
622
+ }
623
+ }
624
+ });
625
+ };
626
+ const runHide = () => {
627
+ setTimeout(hideMetadataSection, 100);
628
+ };
629
+ runHide();
630
+ const observer = new MutationObserver(() => {
631
+ const alreadyHidden = document.querySelector('[data-metadata-hidden="true"]');
632
+ if (!alreadyHidden) {
633
+ runHide();
634
+ }
635
+ });
636
+ observer.observe(document.body, {
637
+ childList: true,
638
+ subtree: true
639
+ });
640
+ return () => {
641
+ observer.disconnect();
642
+ const hidden = document.querySelector('[data-metadata-hidden="true"]');
643
+ if (hidden) {
644
+ hidden.style.display = "";
645
+ hidden.removeAttribute("data-metadata-hidden");
646
+ }
647
+ };
648
+ }, []);
649
+ return null;
650
+ };
651
+ adminSdk.defineWidgetConfig({
652
+ zone: "product.details.side.before"
653
+ });
654
+ const CONFIG_DOCS_URL = "https://docs.medusajs.com/admin/extension-points/widgets#product-details";
655
+ const ProductMetadataTableWidget = ({ data }) => {
656
+ const { data: descriptors = [], isPending, isError } = useProductMetadataConfig();
657
+ const metadata = (data == null ? void 0 : data.metadata) ?? {};
658
+ const [baselineMetadata, setBaselineMetadata] = react.useState(metadata);
659
+ const queryClient = reactQuery.useQueryClient();
660
+ react.useEffect(() => {
661
+ setBaselineMetadata(metadata);
662
+ }, [metadata]);
663
+ const initialState = react.useMemo(
664
+ () => buildInitialFormState(descriptors, baselineMetadata),
665
+ [descriptors, baselineMetadata]
666
+ );
667
+ const [values, setValues] = react.useState(
668
+ initialState
669
+ );
670
+ const [isSaving, setIsSaving] = react.useState(false);
671
+ react.useEffect(() => {
672
+ setValues(initialState);
673
+ }, [initialState]);
674
+ const errors = react.useMemo(() => {
675
+ return descriptors.reduce((acc, descriptor) => {
676
+ const error = validateValueForDescriptor(descriptor, values[descriptor.key]);
677
+ if (error) {
678
+ acc[descriptor.key] = error;
679
+ }
680
+ return acc;
681
+ }, {});
682
+ }, [descriptors, values]);
683
+ const hasErrors = Object.keys(errors).length > 0;
684
+ const isDirty = react.useMemo(() => {
685
+ return hasMetadataChanges({
686
+ descriptors,
687
+ values,
688
+ originalMetadata: baselineMetadata
689
+ });
690
+ }, [descriptors, values, baselineMetadata]);
691
+ const handleStringChange = (key, nextValue) => {
692
+ setValues((prev) => ({
693
+ ...prev,
694
+ [key]: nextValue
695
+ }));
696
+ };
697
+ const handleBooleanChange = (key, nextValue) => {
698
+ setValues((prev) => ({
699
+ ...prev,
700
+ [key]: nextValue
701
+ }));
702
+ };
703
+ const handleReset = () => {
704
+ setValues(initialState);
705
+ };
706
+ const handleSubmit = async () => {
707
+ if (!(data == null ? void 0 : data.id) || !descriptors.length) {
708
+ return;
709
+ }
710
+ setIsSaving(true);
711
+ try {
712
+ const metadataPayload = buildMetadataPayload({
713
+ descriptors,
714
+ values,
715
+ originalMetadata: baselineMetadata
716
+ });
717
+ const response = await fetch(`/admin/products/${data.id}`, {
718
+ method: "POST",
719
+ credentials: "include",
720
+ headers: {
721
+ "Content-Type": "application/json"
722
+ },
723
+ body: JSON.stringify({
724
+ metadata: metadataPayload
725
+ })
726
+ });
727
+ if (!response.ok) {
728
+ const payload = await response.json().catch(() => null);
729
+ throw new Error((payload == null ? void 0 : payload.message) ?? "Unable to save metadata");
730
+ }
731
+ const updated = await response.json();
732
+ const nextMetadata = updated.product.metadata;
733
+ setBaselineMetadata(nextMetadata);
734
+ setValues(buildInitialFormState(descriptors, nextMetadata));
735
+ ui.toast.success("Metadata saved");
736
+ await queryClient.invalidateQueries({
737
+ queryKey: ["products"]
738
+ });
739
+ } catch (error) {
740
+ ui.toast.error(error instanceof Error ? error.message : "Save failed");
741
+ } finally {
742
+ setIsSaving(false);
743
+ }
744
+ };
745
+ return /* @__PURE__ */ jsxRuntime.jsxs(ui.Container, { className: "flex flex-col gap-y-4", children: [
746
+ /* @__PURE__ */ jsxRuntime.jsxs("header", { className: "flex flex-col gap-y-1", children: [
747
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-x-3", children: [
748
+ /* @__PURE__ */ jsxRuntime.jsx(ui.Heading, { level: "h2", children: "Metadata" }),
749
+ /* @__PURE__ */ jsxRuntime.jsx(ui.Badge, { size: "2xsmall", rounded: "full", children: descriptors.length })
750
+ ] }),
751
+ /* @__PURE__ */ jsxRuntime.jsx(ui.Text, { className: "text-ui-fg-subtle", children: "Structured metadata mapped to the keys you configured in the plugin options." })
752
+ ] }),
753
+ isPending ? /* @__PURE__ */ jsxRuntime.jsx(ui.Skeleton, { className: "h-[160px] w-full" }) : isError ? /* @__PURE__ */ jsxRuntime.jsxs(ui.InlineTip, { variant: "error", label: "Configuration unavailable", children: [
754
+ "Unable to load metadata configuration for this plugin. Confirm that the plugin is registered with options in ",
755
+ /* @__PURE__ */ jsxRuntime.jsx("code", { children: "medusa-config.ts" }),
756
+ "."
757
+ ] }) : !descriptors.length ? /* @__PURE__ */ jsxRuntime.jsxs(ui.InlineTip, { variant: "info", label: "No configured metadata keys", children: [
758
+ "Provide a ",
759
+ /* @__PURE__ */ jsxRuntime.jsx("code", { children: "metadataDescriptors" }),
760
+ " array in the plugin options to control which keys show up here.",
761
+ " ",
762
+ /* @__PURE__ */ jsxRuntime.jsx(
763
+ "a",
764
+ {
765
+ className: "text-ui-fg-interactive underline",
766
+ href: CONFIG_DOCS_URL,
767
+ target: "_blank",
768
+ rel: "noreferrer",
769
+ children: "Learn how to configure it."
770
+ }
771
+ )
772
+ ] }) : /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
773
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "overflow-hidden rounded-lg border border-ui-border-base", children: /* @__PURE__ */ jsxRuntime.jsxs("table", { className: "min-w-full divide-y divide-ui-border-base", children: [
774
+ /* @__PURE__ */ jsxRuntime.jsx("thead", { className: "bg-ui-bg-subtle", children: /* @__PURE__ */ jsxRuntime.jsxs("tr", { children: [
775
+ /* @__PURE__ */ jsxRuntime.jsx(
776
+ "th",
777
+ {
778
+ scope: "col",
779
+ className: "txt-compact-xsmall-plus text-left uppercase tracking-wide text-ui-fg-muted px-4 py-3",
780
+ children: "Label"
781
+ }
782
+ ),
783
+ /* @__PURE__ */ jsxRuntime.jsx(
784
+ "th",
785
+ {
786
+ scope: "col",
787
+ className: "txt-compact-xsmall-plus text-left uppercase tracking-wide text-ui-fg-muted px-4 py-3",
788
+ children: "Value"
789
+ }
790
+ )
791
+ ] }) }),
792
+ /* @__PURE__ */ jsxRuntime.jsx("tbody", { className: "divide-y divide-ui-border-subtle bg-ui-bg-base", children: descriptors.map((descriptor) => {
793
+ const value = values[descriptor.key];
794
+ const error = errors[descriptor.key];
795
+ return /* @__PURE__ */ jsxRuntime.jsxs("tr", { children: [
796
+ /* @__PURE__ */ jsxRuntime.jsx(
797
+ "th",
798
+ {
799
+ scope: "row",
800
+ className: "txt-compact-medium text-ui-fg-base align-top px-4 py-4",
801
+ children: /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex flex-col gap-y-1", children: [
802
+ /* @__PURE__ */ jsxRuntime.jsx("span", { children: descriptor.label ?? descriptor.key }),
803
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "txt-compact-xsmall-plus text-ui-fg-muted uppercase tracking-wide", children: descriptor.type })
804
+ ] })
805
+ }
806
+ ),
807
+ /* @__PURE__ */ jsxRuntime.jsx("td", { className: "align-top px-4 py-4", children: /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex flex-col gap-y-2", children: [
808
+ /* @__PURE__ */ jsxRuntime.jsx(
809
+ ValueField,
810
+ {
811
+ descriptor,
812
+ value,
813
+ onStringChange: handleStringChange,
814
+ onBooleanChange: handleBooleanChange
815
+ }
816
+ ),
817
+ error && /* @__PURE__ */ jsxRuntime.jsx(ui.Text, { className: "txt-compact-small text-ui-fg-error", children: error })
818
+ ] }) })
819
+ ] }, descriptor.key);
820
+ }) })
821
+ ] }) }),
822
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex flex-col gap-y-3 border-t border-ui-border-subtle pt-3 md:flex-row md:items-center md:justify-between", children: [
823
+ /* @__PURE__ */ jsxRuntime.jsx(ui.Text, { className: "text-ui-fg-muted", children: "Changes are stored on the product metadata object. Clearing a field removes the corresponding key on save." }),
824
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-x-2", children: [
825
+ /* @__PURE__ */ jsxRuntime.jsx(
826
+ ui.Button,
827
+ {
828
+ variant: "secondary",
829
+ size: "small",
830
+ disabled: !isDirty || isSaving,
831
+ onClick: handleReset,
832
+ children: "Reset"
833
+ }
834
+ ),
835
+ /* @__PURE__ */ jsxRuntime.jsx(
836
+ ui.Button,
837
+ {
838
+ size: "small",
839
+ onClick: handleSubmit,
840
+ disabled: !isDirty || hasErrors || isSaving,
841
+ isLoading: isSaving,
842
+ children: "Save metadata"
843
+ }
844
+ )
845
+ ] })
846
+ ] })
847
+ ] })
848
+ ] });
849
+ };
850
+ const ValueField = ({
851
+ descriptor,
852
+ value,
853
+ onStringChange,
854
+ onBooleanChange
855
+ }) => {
856
+ const fileInputRef = react.useRef(null);
857
+ const [isUploading, setIsUploading] = react.useState(false);
858
+ const handleFileUpload = async (event) => {
859
+ var _a;
860
+ const file = (_a = event.target.files) == null ? void 0 : _a[0];
861
+ if (!file) {
862
+ return;
863
+ }
864
+ setIsUploading(true);
865
+ try {
866
+ const formData = new FormData();
867
+ formData.append("files", file);
868
+ const response = await fetch("/admin/uploads", {
869
+ method: "POST",
870
+ credentials: "include",
871
+ body: formData
872
+ });
873
+ if (!response.ok) {
874
+ const payload = await response.json().catch(() => null);
875
+ throw new Error((payload == null ? void 0 : payload.message) ?? "File upload failed");
876
+ }
877
+ const result = await response.json();
878
+ if (result.files && result.files.length > 0) {
879
+ const uploadedFile = result.files[0];
880
+ const fileUrl = uploadedFile.url || uploadedFile.key;
881
+ if (fileUrl) {
882
+ onStringChange(descriptor.key, fileUrl);
883
+ ui.toast.success("File uploaded successfully");
884
+ } else {
885
+ throw new Error("File upload succeeded but no URL returned");
886
+ }
887
+ } else {
888
+ throw new Error("File upload failed - no files returned");
889
+ }
890
+ } catch (error) {
891
+ ui.toast.error(
892
+ error instanceof Error ? error.message : "Failed to upload file"
893
+ );
894
+ } finally {
895
+ setIsUploading(false);
896
+ if (fileInputRef.current) {
897
+ fileInputRef.current.value = "";
898
+ }
899
+ }
900
+ };
901
+ if (descriptor.type === "bool") {
902
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-x-2", children: [
903
+ /* @__PURE__ */ jsxRuntime.jsx(
904
+ ui.Switch,
905
+ {
906
+ checked: Boolean(value),
907
+ onCheckedChange: (checked) => onBooleanChange(descriptor.key, Boolean(checked)),
908
+ "aria-label": `Toggle ${descriptor.label ?? descriptor.key}`
909
+ }
910
+ ),
911
+ /* @__PURE__ */ jsxRuntime.jsx(ui.Text, { className: "txt-compact-small text-ui-fg-muted", children: Boolean(value) ? "True" : "False" })
912
+ ] });
913
+ }
914
+ if (descriptor.type === "text") {
915
+ return /* @__PURE__ */ jsxRuntime.jsx(
916
+ ui.Textarea,
917
+ {
918
+ value: value ?? "",
919
+ placeholder: "Enter text",
920
+ rows: 3,
921
+ onChange: (event) => onStringChange(descriptor.key, event.target.value)
922
+ }
923
+ );
924
+ }
925
+ if (descriptor.type === "number") {
926
+ return /* @__PURE__ */ jsxRuntime.jsx(
927
+ ui.Input,
928
+ {
929
+ type: "text",
930
+ inputMode: "decimal",
931
+ placeholder: "0.00",
932
+ value: value ?? "",
933
+ onChange: (event) => onStringChange(descriptor.key, event.target.value)
934
+ }
935
+ );
936
+ }
937
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex flex-col gap-y-2", children: [
938
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-x-2", children: [
939
+ /* @__PURE__ */ jsxRuntime.jsx(
940
+ ui.Input,
941
+ {
942
+ type: "url",
943
+ placeholder: "https://example.com/file",
944
+ value: value ?? "",
945
+ onChange: (event) => onStringChange(descriptor.key, event.target.value),
946
+ className: "flex-1"
947
+ }
948
+ ),
949
+ /* @__PURE__ */ jsxRuntime.jsx(
950
+ "input",
951
+ {
952
+ ref: fileInputRef,
953
+ type: "file",
954
+ className: "hidden",
955
+ onChange: handleFileUpload,
956
+ disabled: isUploading,
957
+ "aria-label": `Upload file for ${descriptor.label ?? descriptor.key}`
958
+ }
959
+ ),
960
+ /* @__PURE__ */ jsxRuntime.jsx(
961
+ ui.Button,
962
+ {
963
+ type: "button",
964
+ variant: "secondary",
965
+ size: "small",
966
+ onClick: () => {
967
+ var _a;
968
+ return (_a = fileInputRef.current) == null ? void 0 : _a.click();
969
+ },
970
+ disabled: isUploading,
971
+ isLoading: isUploading,
972
+ children: isUploading ? "Uploading..." : "Upload"
973
+ }
974
+ )
975
+ ] }),
976
+ typeof value === "string" && value && /* @__PURE__ */ jsxRuntime.jsx(
977
+ "a",
978
+ {
979
+ className: "txt-compact-small-plus text-ui-fg-interactive underline",
980
+ href: value,
981
+ target: "_blank",
982
+ rel: "noreferrer",
983
+ children: "View file"
984
+ }
985
+ )
986
+ ] });
987
+ };
988
+ adminSdk.defineWidgetConfig({
989
+ zone: "product.details.after"
990
+ });
2
991
  const i18nTranslations0 = {};
3
- const widgetModule = { widgets: [] };
992
+ const widgetModule = { widgets: [
993
+ {
994
+ Component: CategoryMetadataTableWidget,
995
+ zone: ["product_category.details.after"]
996
+ },
997
+ {
998
+ Component: HideCategoryDefaultMetadataWidget,
999
+ zone: ["product_category.details.side.before"]
1000
+ },
1001
+ {
1002
+ Component: HideDefaultMetadataWidget,
1003
+ zone: ["product.details.side.before"]
1004
+ },
1005
+ {
1006
+ Component: ProductMetadataTableWidget,
1007
+ zone: ["product.details.after"]
1008
+ }
1009
+ ] };
4
1010
  const routeModule = {
5
1011
  routes: []
6
1012
  };