@vicacha-devs/medusa-plugin-barcode 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (176) hide show
  1. package/.medusa/server/src/admin/index.cjs +3960 -0
  2. package/.medusa/server/src/admin/index.js +3938 -0
  3. package/.medusa/server/src/api/admin/barcodes/[barcode]/route.js +43 -0
  4. package/.medusa/server/src/api/admin/barcodes/batch/route.js +9 -0
  5. package/.medusa/server/src/api/admin/barcodes/bulk-generate/route.js +9 -0
  6. package/.medusa/server/src/api/admin/barcodes/cache/route.js +25 -0
  7. package/.medusa/server/src/api/admin/barcodes/count-sessions/[id]/apply/route.js +13 -0
  8. package/.medusa/server/src/api/admin/barcodes/count-sessions/[id]/scan/route.js +13 -0
  9. package/.medusa/server/src/api/admin/barcodes/count-sessions/route.js +27 -0
  10. package/.medusa/server/src/api/admin/barcodes/create-from-barcode/route.js +9 -0
  11. package/.medusa/server/src/api/admin/barcodes/lookup/route.js +12 -0
  12. package/.medusa/server/src/api/admin/barcodes/print/route.js +11 -0
  13. package/.medusa/server/src/api/admin/barcodes/route.js +27 -0
  14. package/.medusa/server/src/api/admin/barcodes/scan/route.js +23 -0
  15. package/.medusa/server/src/api/admin/barcodes/tags/[id]/route.js +28 -0
  16. package/.medusa/server/src/api/admin/barcodes/tags/route.js +25 -0
  17. package/.medusa/server/src/api/admin/barcodes/templates/route.js +40 -0
  18. package/.medusa/server/src/api/admin/plugin/route.js +4 -0
  19. package/.medusa/server/src/api/admin/variants/barcode/[code]/route.js +28 -0
  20. package/.medusa/server/src/api/middlewares.js +73 -0
  21. package/.medusa/server/src/api/store/barcodes/[code]/route.js +28 -0
  22. package/.medusa/server/src/api/store/barcodes/[code]/verify/route.js +20 -0
  23. package/.medusa/server/src/api/store/plugin/route.js +4 -0
  24. package/.medusa/server/src/api/store/variants/barcode/[code]/route.js +28 -0
  25. package/.medusa/server/src/api/validators.js +173 -0
  26. package/.medusa/server/src/hooks/index.js +202 -0
  27. package/.medusa/server/src/index.js +5 -0
  28. package/.medusa/server/src/jobs/purge-expired-barcode-cache.js +10 -0
  29. package/.medusa/server/src/modules/barcode/index.js +16 -0
  30. package/.medusa/server/src/modules/barcode/migrations/Migration20260522000000.js +165 -0
  31. package/.medusa/server/src/modules/barcode/models/index.js +162 -0
  32. package/.medusa/server/src/modules/barcode/operations/context.js +2 -0
  33. package/.medusa/server/src/modules/barcode/operations/data-service.js +10 -0
  34. package/.medusa/server/src/modules/barcode/operations/generation.js +33 -0
  35. package/.medusa/server/src/modules/barcode/operations/index.js +9 -0
  36. package/.medusa/server/src/modules/barcode/operations/labels.js +57 -0
  37. package/.medusa/server/src/modules/barcode/operations/lookup.js +135 -0
  38. package/.medusa/server/src/modules/barcode/operations/maintenance.js +37 -0
  39. package/.medusa/server/src/modules/barcode/operations/stock-count.js +129 -0
  40. package/.medusa/server/src/modules/barcode/operations/tags.js +298 -0
  41. package/.medusa/server/src/modules/barcode/providers/index.js +721 -0
  42. package/.medusa/server/src/modules/barcode/service.js +161 -0
  43. package/.medusa/server/src/modules/barcode/types.js +21 -0
  44. package/.medusa/server/src/modules/barcode/utils/barcode-parser.js +399 -0
  45. package/.medusa/server/src/modules/barcode/utils/label-printer.js +533 -0
  46. package/.medusa/server/src/modules/barcode/utils/normalize-product.js +443 -0
  47. package/.medusa/server/src/modules/barcode/utils/security.js +114 -0
  48. package/.medusa/server/src/modules/barcode/utils/svg-renderer.js +492 -0
  49. package/.medusa/server/src/rbac.js +130 -0
  50. package/.medusa/server/src/sdk/index.js +164 -0
  51. package/.medusa/server/src/subscribers/product-created.js +34 -0
  52. package/.medusa/server/src/types/index.js +2 -0
  53. package/.medusa/server/src/ui/index.js +138 -0
  54. package/.medusa/server/src/workflows/apply-inventory-count.js +68 -0
  55. package/.medusa/server/src/workflows/batch-barcode-import.js +153 -0
  56. package/.medusa/server/src/workflows/bulk-generate-variant-barcodes.js +143 -0
  57. package/.medusa/server/src/workflows/generate-barcode-tag.js +44 -0
  58. package/.medusa/server/src/workflows/helpers.js +15 -0
  59. package/.medusa/server/src/workflows/index.js +7 -0
  60. package/.medusa/server/src/workflows/lookup-and-create-product.js +215 -0
  61. package/.medusa/server/src/workflows/scan-inventory-count.js +15 -0
  62. package/LICENSE +21 -0
  63. package/README.md +844 -2
  64. package/package.json +134 -3
  65. package/src/__tests__/barcode.spec.ts +836 -0
  66. package/src/__tests__/medusa-shim.mjs +331 -0
  67. package/src/__tests__/register-ts-resolver.mjs +135 -0
  68. package/src/admin/README.md +134 -0
  69. package/src/admin/components/barcode-studio-header.tsx +73 -0
  70. package/src/admin/components/batch-import-section.tsx +99 -0
  71. package/src/admin/components/dynamic-qr-tag-drawer-form.tsx +230 -0
  72. package/src/admin/components/dynamic-qr-tag-form.tsx +129 -0
  73. package/src/admin/components/dynamic-qr-tags-table.tsx +136 -0
  74. package/src/admin/components/gtin-lookup-section.tsx +155 -0
  75. package/src/admin/components/index.tsx +14 -0
  76. package/src/admin/components/label-designer-section.tsx +151 -0
  77. package/src/admin/components/label-output-section.tsx +63 -0
  78. package/src/admin/components/overview-cards.tsx +98 -0
  79. package/src/admin/components/product-barcode-card.tsx +127 -0
  80. package/src/admin/components/providers-cache-table.tsx +61 -0
  81. package/src/admin/components/providers-overview-section.tsx +49 -0
  82. package/src/admin/components/rbac-guard.tsx +153 -0
  83. package/src/admin/components/stock-take-scanner-section.tsx +116 -0
  84. package/src/admin/components/stock-take-sessions-section.tsx +109 -0
  85. package/src/admin/hooks/use-barcode-studio.ts +466 -0
  86. package/src/admin/hooks/use-product-barcodes.ts +139 -0
  87. package/src/admin/i18n/README.md +130 -0
  88. package/src/admin/i18n/index.ts +36 -0
  89. package/src/admin/i18n/json/ar.json +157 -0
  90. package/src/admin/i18n/json/de.json +157 -0
  91. package/src/admin/i18n/json/en.json +157 -0
  92. package/src/admin/i18n/json/es.json +157 -0
  93. package/src/admin/i18n/json/fr.json +157 -0
  94. package/src/admin/i18n/json/it.json +157 -0
  95. package/src/admin/i18n/json/nl.json +157 -0
  96. package/src/admin/i18n/json/pl.json +157 -0
  97. package/src/admin/i18n/json/pt.json +157 -0
  98. package/src/admin/i18n/json/tr.json +157 -0
  99. package/src/admin/routes/barcodes/lookup/page.tsx +75 -0
  100. package/src/admin/routes/barcodes/page.tsx +212 -0
  101. package/src/admin/routes/barcodes/print/page.tsx +67 -0
  102. package/src/admin/routes/barcodes/providers/page.tsx +66 -0
  103. package/src/admin/routes/barcodes/stock-take/page.tsx +74 -0
  104. package/src/admin/routes/barcodes/tags/@create/page.tsx +56 -0
  105. package/src/admin/routes/barcodes/tags/page.tsx +72 -0
  106. package/src/admin/tsconfig.json +20 -0
  107. package/src/admin/vite-env.d.ts +1 -0
  108. package/src/admin/widgets/product-barcode-widget.tsx +43 -0
  109. package/src/api/README.md +117 -0
  110. package/src/api/admin/barcodes/[barcode]/route.ts +64 -0
  111. package/src/api/admin/barcodes/batch/route.ts +12 -0
  112. package/src/api/admin/barcodes/bulk-generate/route.ts +12 -0
  113. package/src/api/admin/barcodes/cache/route.ts +35 -0
  114. package/src/api/admin/barcodes/count-sessions/[id]/apply/route.ts +17 -0
  115. package/src/api/admin/barcodes/count-sessions/[id]/scan/route.ts +17 -0
  116. package/src/api/admin/barcodes/count-sessions/route.ts +43 -0
  117. package/src/api/admin/barcodes/create-from-barcode/route.ts +16 -0
  118. package/src/api/admin/barcodes/lookup/route.ts +19 -0
  119. package/src/api/admin/barcodes/print/route.ts +18 -0
  120. package/src/api/admin/barcodes/route.ts +36 -0
  121. package/src/api/admin/barcodes/scan/route.ts +32 -0
  122. package/src/api/admin/barcodes/tags/[id]/route.ts +41 -0
  123. package/src/api/admin/barcodes/tags/route.ts +36 -0
  124. package/src/api/admin/barcodes/templates/route.ts +51 -0
  125. package/src/api/admin/plugin/route.ts +5 -0
  126. package/src/api/admin/variants/barcode/[code]/route.ts +36 -0
  127. package/src/api/middlewares.ts +91 -0
  128. package/src/api/store/barcodes/[code]/route.ts +43 -0
  129. package/src/api/store/barcodes/[code]/verify/route.ts +35 -0
  130. package/src/api/store/plugin/route.ts +5 -0
  131. package/src/api/store/variants/barcode/[code]/route.ts +36 -0
  132. package/src/api/validators.ts +217 -0
  133. package/src/hooks/index.ts +270 -0
  134. package/src/index.ts +4 -0
  135. package/src/jobs/README.md +54 -0
  136. package/src/jobs/purge-expired-barcode-cache.ts +18 -0
  137. package/src/links/README.md +44 -0
  138. package/src/modules/README.md +85 -0
  139. package/src/modules/barcode/index.ts +18 -0
  140. package/src/modules/barcode/migrations/Migration20260522000000.ts +225 -0
  141. package/src/modules/barcode/models/index.ts +168 -0
  142. package/src/modules/barcode/operations/context.ts +14 -0
  143. package/src/modules/barcode/operations/data-service.ts +10 -0
  144. package/src/modules/barcode/operations/generation.ts +57 -0
  145. package/src/modules/barcode/operations/index.ts +8 -0
  146. package/src/modules/barcode/operations/labels.ts +90 -0
  147. package/src/modules/barcode/operations/lookup.ts +202 -0
  148. package/src/modules/barcode/operations/maintenance.ts +53 -0
  149. package/src/modules/barcode/operations/stock-count.ts +217 -0
  150. package/src/modules/barcode/operations/tags.ts +425 -0
  151. package/src/modules/barcode/providers/index.ts +958 -0
  152. package/src/modules/barcode/service.ts +243 -0
  153. package/src/modules/barcode/types.ts +297 -0
  154. package/src/modules/barcode/utils/barcode-parser.ts +453 -0
  155. package/src/modules/barcode/utils/label-printer.ts +641 -0
  156. package/src/modules/barcode/utils/normalize-product.ts +524 -0
  157. package/src/modules/barcode/utils/security.ts +136 -0
  158. package/src/modules/barcode/utils/svg-renderer.ts +574 -0
  159. package/src/providers/README.md +105 -0
  160. package/src/rbac.ts +144 -0
  161. package/src/sdk/index.ts +253 -0
  162. package/src/subscribers/README.md +73 -0
  163. package/src/subscribers/product-created.ts +45 -0
  164. package/src/types/index.ts +1 -0
  165. package/src/types/medusa-ui.d.ts +118 -0
  166. package/src/ui/index.tsx +311 -0
  167. package/src/workflows/README.md +56 -0
  168. package/src/workflows/apply-inventory-count.ts +115 -0
  169. package/src/workflows/batch-barcode-import.ts +218 -0
  170. package/src/workflows/bulk-generate-variant-barcodes.ts +214 -0
  171. package/src/workflows/generate-barcode-tag.ts +85 -0
  172. package/src/workflows/helpers.ts +21 -0
  173. package/src/workflows/index.ts +6 -0
  174. package/src/workflows/lookup-and-create-product.ts +298 -0
  175. package/src/workflows/scan-inventory-count.ts +45 -0
  176. package/tsconfig.json +40 -0
@@ -0,0 +1,524 @@
1
+ import type {
2
+ CreateProductPayload,
3
+ NormalizedBarcodeProduct,
4
+ VariantPriceInput,
5
+ } from "../types"
6
+
7
+ export const CATEGORY_ALIASES: Record<string, string> = {
8
+ food: "Food & Beverages",
9
+ beverage: "Food & Beverages",
10
+ beverages: "Food & Beverages",
11
+ drink: "Food & Beverages",
12
+ drinks: "Food & Beverages",
13
+ grocery: "Food & Beverages",
14
+ electronics: "Electronics",
15
+ electronic: "Electronics",
16
+ health: "Health & Beauty",
17
+ beauty: "Health & Beauty",
18
+ cosmetics: "Health & Beauty",
19
+ "personal care": "Health & Beauty",
20
+ cleaning: "Home & Garden",
21
+ home: "Home & Garden",
22
+ garden: "Home & Garden",
23
+ clothing: "Apparel",
24
+ apparel: "Apparel",
25
+ fashion: "Apparel",
26
+ toys: "Toys & Games",
27
+ games: "Toys & Games",
28
+ sports: "Sports & Outdoors",
29
+ outdoors: "Sports & Outdoors",
30
+ automotive: "Automotive",
31
+ office: "Office Supplies",
32
+ pet: "Pet Supplies",
33
+ book: "Books & Media",
34
+ books: "Books & Media",
35
+ }
36
+
37
+ function toTitleCase(input: string): string {
38
+ return input
39
+ .trim()
40
+ .split(/\s+/)
41
+ .filter(Boolean)
42
+ .map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
43
+ .join(" ")
44
+ }
45
+
46
+ /**
47
+ * Normalizes a raw category string into a canonical retail category or title-cased label.
48
+ */
49
+ export function normalizeCategory(raw: string): string {
50
+ const trimmed = String(raw ?? "").trim()
51
+ if (!trimmed) {
52
+ return ""
53
+ }
54
+ const cleanPrefix = trimmed
55
+ .replace(/^[a-z]{2}:/i, "")
56
+ .replace(/-/g, " ")
57
+ .trim()
58
+ const lower = cleanPrefix.toLowerCase()
59
+ for (const [key, canonical] of Object.entries(CATEGORY_ALIASES)) {
60
+ if (lower.includes(key)) {
61
+ return canonical
62
+ }
63
+ }
64
+ return toTitleCase(cleanPrefix)
65
+ }
66
+
67
+ /**
68
+ * Parses a human-readable weight or volume string into integer grams.
69
+ * Examples: "400g" -> 400, "1.5 kg" -> 1500, "500ml" -> 500, "16 oz" -> 454, "2 lb" -> 907
70
+ */
71
+ export function parseWeightGrams(raw: unknown): number | null {
72
+ if (typeof raw === "number" && Number.isFinite(raw) && raw > 0) {
73
+ return Math.round(raw)
74
+ }
75
+ if (typeof raw !== "string") {
76
+ return null
77
+ }
78
+ const trimmed = raw.trim()
79
+ if (!trimmed) {
80
+ return null
81
+ }
82
+
83
+ const unitMatch =
84
+ /(\d+(?:[.,]\d+)?)\s*(kg|kilograms?|g|grams?|mg|milligrams?|lb|lbs|pounds?|oz|ounces?|ml|milliliters?|cl|centiliters?|l|liters?)\b/i.exec(
85
+ trimmed
86
+ )
87
+ if (unitMatch) {
88
+ const val = Number.parseFloat((unitMatch[1] || "0").replace(",", "."))
89
+ if (!Number.isFinite(val) || val <= 0) {
90
+ return null
91
+ }
92
+ const unit = (unitMatch[2] || "g").toLowerCase()
93
+ if (
94
+ unit === "kg" ||
95
+ unit.startsWith("kilogram") ||
96
+ unit === "l" ||
97
+ unit.startsWith("liter")
98
+ ) {
99
+ return Math.round(val * 1000)
100
+ }
101
+ if (
102
+ unit === "g" ||
103
+ unit.startsWith("gram") ||
104
+ unit === "ml" ||
105
+ unit.startsWith("milliliter")
106
+ ) {
107
+ return Math.round(val)
108
+ }
109
+ if (unit === "cl" || unit.startsWith("centiliter")) {
110
+ return Math.round(val * 10)
111
+ }
112
+ if (unit === "mg" || unit.startsWith("milligram")) {
113
+ return Math.max(1, Math.round(val / 1000))
114
+ }
115
+ if (unit === "lb" || unit === "lbs" || unit.startsWith("pound")) {
116
+ return Math.round(val * 453.59237)
117
+ }
118
+ if (unit === "oz" || unit.startsWith("ounce")) {
119
+ return Math.round(val * 28.34952)
120
+ }
121
+ }
122
+
123
+ if (/^\d+(?:[.,]\d+)?$/.test(trimmed)) {
124
+ const num = Number.parseFloat(trimmed.replace(",", "."))
125
+ if (Number.isFinite(num) && num > 0) {
126
+ return Math.round(num)
127
+ }
128
+ }
129
+
130
+ return null
131
+ }
132
+
133
+ /**
134
+ * Parses a human-readable 3D dimension string into millimeters (`{ length, width, height }`).
135
+ * Examples: "10 x 5 x 20 cm" -> { length: 100, width: 50, height: 200 }, "4 x 2 x 8 in" -> { length: 102, width: 51, height: 203 }
136
+ */
137
+ export function parseDimensionMm(raw: unknown): {
138
+ length: number | null
139
+ width: number | null
140
+ height: number | null
141
+ } {
142
+ if (typeof raw !== "string" || !raw.trim()) {
143
+ return { length: null, width: null, height: null }
144
+ }
145
+ const match =
146
+ /(\d+(?:[.,]\d+)?)\s*(?:mm|cm|m|in|inch|inches|")?\s*[x×*]\s*(\d+(?:[.,]\d+)?)\s*(?:mm|cm|m|in|inch|inches|")?\s*[x×*]\s*(\d+(?:[.,]\d+)?)\s*(mm|millimeters?|cm|centimeters?|m|meters?|in|inch|inches|")?/i.exec(
147
+ raw
148
+ )
149
+ if (!match) {
150
+ return { length: null, width: null, height: null }
151
+ }
152
+
153
+ const d1 = Number.parseFloat((match[1] || "0").replace(",", "."))
154
+ const d2 = Number.parseFloat((match[2] || "0").replace(",", "."))
155
+ const d3 = Number.parseFloat((match[3] || "0").replace(",", "."))
156
+ if (
157
+ !Number.isFinite(d1) ||
158
+ !Number.isFinite(d2) ||
159
+ !Number.isFinite(d3) ||
160
+ d1 <= 0 ||
161
+ d2 <= 0 ||
162
+ d3 <= 0
163
+ ) {
164
+ return { length: null, width: null, height: null }
165
+ }
166
+
167
+ const unit = (match[4] || "mm").toLowerCase()
168
+ let factor = 1
169
+ if (unit === "cm" || unit.startsWith("centimeter")) {
170
+ factor = 10
171
+ } else if (unit === "m" || unit.startsWith("meter")) {
172
+ factor = 1000
173
+ } else if (unit === "in" || unit.startsWith("inch") || unit === '"') {
174
+ factor = 25.4
175
+ }
176
+
177
+ return {
178
+ length: Math.round(d1 * factor),
179
+ width: Math.round(d2 * factor),
180
+ height: Math.round(d3 * factor),
181
+ }
182
+ }
183
+
184
+ /**
185
+ * Generates a URL-safe product handle from a product name and barcode.
186
+ */
187
+ export function slugifyProductHandle(name: string, barcode: string): string {
188
+ const base = name
189
+ .toLowerCase()
190
+ .replace(/[^a-z0-9]+/g, "-")
191
+ .replace(/^-+|-+$/g, "")
192
+ .slice(0, 60)
193
+
194
+ const suffix = barcode
195
+ .replace(/[^a-zA-Z0-9]/g, "")
196
+ .slice(-8)
197
+ .toLowerCase()
198
+
199
+ if (!base) {
200
+ return `item-${suffix || "barcode"}`
201
+ }
202
+ return suffix ? `${base}-${suffix}` : base
203
+ }
204
+
205
+ /**
206
+ * Normalizes raw category arrays/strings into a clean deduplicated array.
207
+ */
208
+ export function normalizeStringArray(input: unknown): string[] {
209
+ if (!input) return []
210
+ if (Array.isArray(input)) {
211
+ return Array.from(
212
+ new Set(
213
+ input
214
+ .map((item) => String(item ?? "").trim())
215
+ .filter((item) => item.length > 0)
216
+ )
217
+ )
218
+ }
219
+ if (typeof input === "string") {
220
+ return Array.from(
221
+ new Set(
222
+ input
223
+ .split(/[,;>|]+/)
224
+ .map((item) => item.trim())
225
+ .filter((item) => item.length > 0)
226
+ )
227
+ )
228
+ }
229
+ return []
230
+ }
231
+
232
+ /**
233
+ * Deep-merges multiple `NormalizedBarcodeProduct` results from the provider chain.
234
+ * Priority is ordered from first to last; missing fields in earlier providers are
235
+ * backfilled from lower-priority providers, and image/category/author lists are deduplicated.
236
+ */
237
+ export function mergeNormalizedProducts(
238
+ products: NormalizedBarcodeProduct[]
239
+ ): NormalizedBarcodeProduct | null {
240
+ if (products.length === 0) {
241
+ return null
242
+ }
243
+ if (products.length === 1) {
244
+ return products[0]
245
+ }
246
+
247
+ const primary = products[0]
248
+ const mergedCategories = new Set<string>(primary.categories)
249
+ const mergedImages = new Set<string>(primary.images)
250
+ const mergedAuthors = new Set<string>(primary.authors)
251
+ const mergedLabels = new Set<string>(primary.labels || [])
252
+ const mergedProviders: string[] = [primary.provider]
253
+ const mergedRawData: Record<string, unknown> = {
254
+ [primary.provider]: primary.raw_data,
255
+ }
256
+
257
+ let description = primary.description
258
+ let brand = primary.brand
259
+ let manufacturer = primary.manufacturer
260
+ let weight = primary.weight
261
+ let weightUnit = primary.weight_unit
262
+ let dimensions = primary.dimensions
263
+ let length = primary.length ?? null
264
+ let width = primary.width ?? null
265
+ let height = primary.height ?? null
266
+ let quantityLabel = primary.quantity_label
267
+ let ingredients = primary.ingredients
268
+ let nutrition = primary.nutrition
269
+ let countryOfOrigin = primary.country_of_origin
270
+ let suggestedPrice = primary.suggested_price
271
+ let currencyCode = primary.currency_code
272
+ let isbn = primary.isbn
273
+ let publisher = primary.publisher
274
+ let publishedDate = primary.published_date
275
+ let pageCount = primary.page_count
276
+
277
+ for (let i = 1; i < products.length; i++) {
278
+ const next = products[i]
279
+ mergedProviders.push(next.provider)
280
+ mergedRawData[next.provider] = next.raw_data
281
+
282
+ for (const cat of next.categories) mergedCategories.add(cat)
283
+ for (const img of next.images) mergedImages.add(img)
284
+ for (const author of next.authors) mergedAuthors.add(author)
285
+ for (const lbl of next.labels || []) mergedLabels.add(lbl)
286
+
287
+ if (
288
+ !description ||
289
+ (next.description && next.description.length > description.length)
290
+ ) {
291
+ description = next.description
292
+ }
293
+ if (!brand && next.brand) brand = next.brand
294
+ if (!manufacturer && next.manufacturer) manufacturer = next.manufacturer
295
+ if (weight === null && next.weight !== null) {
296
+ weight = next.weight
297
+ weightUnit = next.weight_unit
298
+ }
299
+ if (!dimensions && next.dimensions) dimensions = next.dimensions
300
+ if (length === null && next.length != null) length = next.length
301
+ if (width === null && next.width != null) width = next.width
302
+ if (height === null && next.height != null) height = next.height
303
+ if (!quantityLabel && next.quantity_label)
304
+ quantityLabel = next.quantity_label
305
+ if (!ingredients && next.ingredients) ingredients = next.ingredients
306
+ if (!nutrition && next.nutrition) nutrition = next.nutrition
307
+ if (!countryOfOrigin && next.country_of_origin) {
308
+ countryOfOrigin = next.country_of_origin
309
+ }
310
+ if (suggestedPrice === null && next.suggested_price !== null) {
311
+ suggestedPrice = next.suggested_price
312
+ currencyCode = next.currency_code || currencyCode
313
+ }
314
+ if (!isbn && next.isbn) isbn = next.isbn
315
+ if (!publisher && next.publisher) publisher = next.publisher
316
+ if (!publishedDate && next.published_date)
317
+ publishedDate = next.published_date
318
+ if (pageCount === null && next.page_count !== null)
319
+ pageCount = next.page_count
320
+ }
321
+
322
+ return {
323
+ ...primary,
324
+ description,
325
+ brand,
326
+ manufacturer,
327
+ categories: Array.from(mergedCategories),
328
+ images: Array.from(mergedImages),
329
+ weight,
330
+ weight_unit: weightUnit,
331
+ dimensions,
332
+ length,
333
+ width,
334
+ height,
335
+ labels: mergedLabels.size > 0 ? Array.from(mergedLabels) : primary.labels,
336
+ quantity_label: quantityLabel,
337
+ ingredients,
338
+ nutrition,
339
+ country_of_origin: countryOfOrigin,
340
+ suggested_price: suggestedPrice,
341
+ currency_code: currencyCode,
342
+ isbn,
343
+ authors: Array.from(mergedAuthors),
344
+ publisher,
345
+ published_date: publishedDate,
346
+ page_count: pageCount,
347
+ provider: mergedProviders.join("+"),
348
+ raw_data: mergedRawData,
349
+ }
350
+ }
351
+
352
+ /**
353
+ * Maps a `NormalizedBarcodeProduct` into a Medusa v2 `CreateProductPayload`
354
+ * with synced `barcode`, `ean`, and `upc` variant fields.
355
+ */
356
+ export function mapToMedusaCreateProduct(
357
+ normalized: NormalizedBarcodeProduct,
358
+ options: {
359
+ status?: "draft" | "published"
360
+ publishImmediately?: boolean
361
+ skuPrefix?: string
362
+ defaultCurrencyCode?: string
363
+ overrideTitle?: string
364
+ overrideDescription?: string
365
+ overridePrice?: number
366
+ currencyCode?: string
367
+ prices?: VariantPriceInput[]
368
+ salesChannelIds?: string[]
369
+ categoryIds?: string[]
370
+ collectionId?: string
371
+ } = {}
372
+ ): CreateProductPayload {
373
+ const title = (
374
+ options.overrideTitle ||
375
+ normalized.name ||
376
+ `Product ${normalized.barcode}`
377
+ ).trim()
378
+ const description =
379
+ options.overrideDescription ??
380
+ normalized.description ??
381
+ (normalized.ingredients ? `Ingredients: ${normalized.ingredients}` : null)
382
+
383
+ const handle = slugifyProductHandle(title, normalized.barcode)
384
+ const skuPrefix = options.skuPrefix || "GTIN"
385
+ const sku = `${skuPrefix}-${normalized.barcode}`
386
+
387
+ const cleanDigits = normalized.barcode.replace(/\D/g, "")
388
+ const ean = cleanDigits.length === 13 ? cleanDigits : null
389
+ const upc =
390
+ cleanDigits.length === 12
391
+ ? cleanDigits
392
+ : cleanDigits.length === 13 && cleanDigits.startsWith("0")
393
+ ? cleanDigits.slice(1)
394
+ : null
395
+
396
+ const priceAmount =
397
+ typeof options.overridePrice === "number"
398
+ ? options.overridePrice
399
+ : typeof normalized.suggested_price === "number" &&
400
+ normalized.suggested_price > 0
401
+ ? normalized.suggested_price
402
+ : 0
403
+
404
+ const currencyCode = (
405
+ options.currencyCode ||
406
+ normalized.currency_code ||
407
+ options.defaultCurrencyCode ||
408
+ "usd"
409
+ ).toLowerCase()
410
+
411
+ const variantPrices: Array<{ amount: number; currency_code: string }> = []
412
+ if (Array.isArray(options.prices) && options.prices.length > 0) {
413
+ for (const p of options.prices) {
414
+ if (
415
+ p &&
416
+ typeof p.amount === "number" &&
417
+ p.amount >= 0 &&
418
+ p.currency_code
419
+ ) {
420
+ variantPrices.push({
421
+ amount: p.amount,
422
+ currency_code: p.currency_code.toLowerCase(),
423
+ })
424
+ }
425
+ }
426
+ }
427
+ if (variantPrices.length === 0 && priceAmount > 0) {
428
+ variantPrices.push({ amount: priceAmount, currency_code: currencyCode })
429
+ }
430
+
431
+ const resolvedWeight =
432
+ normalized.weight ?? parseWeightGrams(normalized.quantity_label)
433
+ const parsedDims = parseDimensionMm(normalized.dimensions)
434
+ const resolvedLength = normalized.length ?? parsedDims.length
435
+ const resolvedWidth = normalized.width ?? parsedDims.width
436
+ const resolvedHeight = normalized.height ?? parsedDims.height
437
+
438
+ const normalizedCategories = Array.from(
439
+ new Set(
440
+ normalized.categories
441
+ .map((c) => normalizeCategory(c))
442
+ .filter((c) => c.length > 0)
443
+ )
444
+ )
445
+
446
+ const variantTitle = normalized.quantity_label || "Default"
447
+ const resolvedStatus: "draft" | "published" = options.publishImmediately
448
+ ? "published"
449
+ : options.status || "draft"
450
+
451
+ const payload: CreateProductPayload = {
452
+ title,
453
+ subtitle: normalized.brand || normalized.publisher || null,
454
+ description,
455
+ handle,
456
+ status: resolvedStatus,
457
+ thumbnail: normalized.images[0] || null,
458
+ images: normalized.images.map((url) => ({ url })),
459
+ weight: resolvedWeight,
460
+ length: resolvedLength,
461
+ width: resolvedWidth,
462
+ height: resolvedHeight,
463
+ origin_country: normalized.country_of_origin
464
+ ? normalized.country_of_origin.slice(0, 2).toLowerCase()
465
+ : null,
466
+ options: [
467
+ {
468
+ title: "Format",
469
+ values: [variantTitle],
470
+ },
471
+ ],
472
+ variants: [
473
+ {
474
+ title: variantTitle,
475
+ sku,
476
+ barcode: normalized.barcode,
477
+ ean,
478
+ upc,
479
+ weight: resolvedWeight,
480
+ length: resolvedLength,
481
+ width: resolvedWidth,
482
+ height: resolvedHeight,
483
+ manage_inventory: true,
484
+ options: {
485
+ Format: variantTitle,
486
+ },
487
+ prices: variantPrices,
488
+ },
489
+ ],
490
+ metadata: {
491
+ barcode: normalized.barcode,
492
+ barcode_type: normalized.barcode_type,
493
+ barcode_provider: normalized.provider,
494
+ brand: normalized.brand,
495
+ manufacturer: normalized.manufacturer,
496
+ categories: normalized.categories,
497
+ normalized_categories: normalizedCategories,
498
+ labels: normalized.labels ?? [],
499
+ quantity_label: normalized.quantity_label,
500
+ ingredients: normalized.ingredients,
501
+ nutrition: normalized.nutrition,
502
+ isbn: normalized.isbn,
503
+ authors: normalized.authors,
504
+ publisher: normalized.publisher,
505
+ published_date: normalized.published_date,
506
+ page_count: normalized.page_count,
507
+ },
508
+ }
509
+
510
+ if (options.collectionId) {
511
+ payload.collection_id = options.collectionId
512
+ }
513
+ if (Array.isArray(options.categoryIds) && options.categoryIds.length > 0) {
514
+ payload.categories = options.categoryIds.map((id) => ({ id }))
515
+ }
516
+ if (
517
+ Array.isArray(options.salesChannelIds) &&
518
+ options.salesChannelIds.length > 0
519
+ ) {
520
+ payload.sales_channels = options.salesChannelIds.map((id) => ({ id }))
521
+ }
522
+
523
+ return payload
524
+ }
@@ -0,0 +1,136 @@
1
+ import crypto from "node:crypto"
2
+
3
+ let ephemeralFallbackSecret: string | null = null
4
+
5
+ /**
6
+ * Resolves the HMAC secret used for anti-counterfeit QR/barcode signatures.
7
+ * Uses explicit option -> `MEDUSA_BARCODE_HMAC_SECRET` -> `JWT_SECRET` -> per-process CSPRNG fallback.
8
+ */
9
+ export function getBarcodeHmacSecret(explicitSecret?: string): string {
10
+ if (explicitSecret && explicitSecret.trim().length >= 16) {
11
+ return explicitSecret.trim()
12
+ }
13
+ const envSecret =
14
+ process.env.MEDUSA_BARCODE_HMAC_SECRET || process.env.JWT_SECRET
15
+ if (envSecret && envSecret.trim().length >= 16) {
16
+ return envSecret.trim()
17
+ }
18
+ if (!ephemeralFallbackSecret) {
19
+ ephemeralFallbackSecret = crypto.randomBytes(32).toString("hex")
20
+ }
21
+ return ephemeralFallbackSecret
22
+ }
23
+
24
+ export interface AuthenticityPayloadInput {
25
+ code: string
26
+ targetId: string
27
+ serialNumber?: string | null
28
+ batchLot?: string | null
29
+ }
30
+
31
+ /**
32
+ * Generates an HMAC-SHA256 hex digest for anti-counterfeit barcode/QR verification.
33
+ */
34
+ export function createAuthenticityHmac(
35
+ payload: AuthenticityPayloadInput,
36
+ secret?: string
37
+ ): string {
38
+ const key = getBarcodeHmacSecret(secret)
39
+ const canonical = [
40
+ payload.code.trim(),
41
+ payload.targetId.trim(),
42
+ (payload.serialNumber ?? "").trim(),
43
+ (payload.batchLot ?? "").trim(),
44
+ ].join("|")
45
+
46
+ return crypto
47
+ .createHmac("sha256", key)
48
+ .update(canonical, "utf8")
49
+ .digest("hex")
50
+ }
51
+
52
+ /**
53
+ * Constant-time HMAC-SHA256 verification to prevent timing side-channel attacks.
54
+ */
55
+ export function verifyAuthenticityHmac(
56
+ payload: AuthenticityPayloadInput,
57
+ providedSignature: string,
58
+ secret?: string
59
+ ): boolean {
60
+ if (!providedSignature || typeof providedSignature !== "string") {
61
+ return false
62
+ }
63
+ const cleanSig = providedSignature.trim().toLowerCase()
64
+ if (!/^[0-9a-f]{64}$/.test(cleanSig)) {
65
+ return false
66
+ }
67
+ const expected = createAuthenticityHmac(payload, secret).toLowerCase()
68
+ const expectedBuf = new Uint8Array(Buffer.from(expected, "hex"))
69
+ const providedBuf = new Uint8Array(Buffer.from(cleanSig, "hex"))
70
+ if (expectedBuf.length !== providedBuf.length) {
71
+ return false
72
+ }
73
+ return crypto.timingSafeEqual(expectedBuf, providedBuf)
74
+ }
75
+
76
+ /**
77
+ * Generates a URL-safe short scan token using CSPRNG (`crypto.randomBytes`).
78
+ */
79
+ export function generateShortScanCode(prefix = "mpb"): string {
80
+ const randomPart = crypto.randomBytes(6).toString("base64url")
81
+ return `${prefix}_${randomPart}`
82
+ }
83
+
84
+ /**
85
+ * Strict HTML/XML attribute & text escaping to prevent XSS in SVG and printable HTML labels.
86
+ */
87
+ export function escapeHtml(input: unknown): string {
88
+ if (input === null || input === undefined) {
89
+ return ""
90
+ }
91
+ return String(input)
92
+ .replace(/&/g, "&amp;")
93
+ .replace(/</g, "&lt;")
94
+ .replace(/>/g, "&gt;")
95
+ .replace(/"/g, "&quot;")
96
+ .replace(/'/g, "&#39;")
97
+ }
98
+
99
+ const PRIVATE_IP_PATTERNS = [
100
+ /^localhost$/i,
101
+ /^127\./,
102
+ /^10\./,
103
+ /^192\.168\./,
104
+ /^169\.254\./,
105
+ /^172\.(1[6-9]|2\d|3[0-1])\./,
106
+ /^0\./,
107
+ /^\[?::1\]?$/,
108
+ /^\[?fe80:/i,
109
+ /^\[?fc00:/i,
110
+ /^\[?fd00:/i,
111
+ /\.local$/i,
112
+ /\.internal$/i,
113
+ ]
114
+
115
+ /**
116
+ * Validates external image URLs before server-side fetching to prevent SSRF attacks.
117
+ * Only permits `https:` URLs to public hosts.
118
+ */
119
+ export function validateExternalImageUrl(rawUrl: string): string | null {
120
+ if (!rawUrl || typeof rawUrl !== "string") {
121
+ return null
122
+ }
123
+ try {
124
+ const parsed = new URL(rawUrl.trim())
125
+ if (parsed.protocol !== "https:") {
126
+ return null
127
+ }
128
+ const hostname = parsed.hostname.toLowerCase()
129
+ if (!hostname || PRIVATE_IP_PATTERNS.some((re) => re.test(hostname))) {
130
+ return null
131
+ }
132
+ return parsed.toString()
133
+ } catch {
134
+ return null
135
+ }
136
+ }