@hszrdm/create-commerce 1.3.0 → 1.5.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 (30) hide show
  1. package/README.md +92 -1
  2. package/package.json +1 -1
  3. package/templates/backend/.env.example +271 -91
  4. package/templates/backend/README.md +4 -0
  5. package/templates/backend/package.json +6 -2
  6. package/templates/backend/scripts/core-backup.mjs +281 -0
  7. package/templates/backend/scripts/core-restore.mjs +179 -0
  8. package/templates/backend/scripts/lib/core-backup-common.mjs +237 -0
  9. package/templates/backend/scripts/materialize-production.mjs +37 -0
  10. package/templates/backend/scripts/production-assets/backup.sh +56 -0
  11. package/templates/backend/scripts/production-assets/deploy.sh +68 -0
  12. package/templates/backend/scripts/production-assets/ecosystem.config.cjs.tpl +24 -0
  13. package/templates/backend/scripts/production-assets/install.sh +201 -0
  14. package/templates/backend/scripts/production-assets/restore.sh +71 -0
  15. package/templates/backend/scripts/verify-env-contract.mjs +58 -0
  16. package/templates/backend/src/scripts/core-init.ts +3 -1
  17. package/templates/storefront/src/app/cart-recovery/page.tsx +35 -0
  18. package/templates/storefront/src/app/ertekeles/page.tsx +25 -0
  19. package/templates/storefront/src/app/fiok-aktivalas/page.tsx +35 -0
  20. package/templates/storefront/src/components/abandoned-cart-recovery.tsx +139 -0
  21. package/templates/storefront/src/components/account-activation-form.tsx +333 -0
  22. package/templates/storefront/src/components/add-to-cart.tsx +56 -0
  23. package/templates/storefront/src/components/analytics.tsx +15 -2
  24. package/templates/storefront/src/components/review-request-form.tsx +419 -0
  25. package/templates/storefront/src/lib/core/abandoned-cart.ts +47 -0
  26. package/templates/storefront/src/lib/core/account-activation.ts +75 -0
  27. package/templates/storefront/src/lib/core/back-in-stock.ts +25 -0
  28. package/templates/storefront/src/lib/core/reviews.ts +37 -5
  29. package/templates/storefront/src/lib/storefront-routes.ts +3 -0
  30. package/templates/storefront/src/proxy.ts +4 -0
@@ -0,0 +1,281 @@
1
+ #!/usr/bin/env node
2
+
3
+ import {
4
+ existsSync,
5
+ mkdirSync,
6
+ readFileSync,
7
+ readdirSync,
8
+ renameSync,
9
+ statSync,
10
+ writeFileSync,
11
+ } from "node:fs"
12
+ import { dirname, isAbsolute, join, resolve } from "node:path"
13
+ import { spawnSync } from "node:child_process"
14
+ import process from "node:process"
15
+
16
+ import {
17
+ CORE_DB_MODULES,
18
+ backendProjectDir,
19
+ backupFileSources,
20
+ backupTimestamp,
21
+ copyBackupSource,
22
+ loadRuntimeEnv,
23
+ pgEnvironment,
24
+ portableConfig,
25
+ portableEnvText,
26
+ sha256File,
27
+ sha256Tree,
28
+ } from "./lib/core-backup-common.mjs"
29
+
30
+ const args = parseArgs(process.argv.slice(2))
31
+ if (args.help) {
32
+ printHelp()
33
+ process.exit(0)
34
+ }
35
+
36
+ const projectDir = resolve(args["project-dir"] || process.cwd())
37
+ const env = loadRuntimeEnv(projectDir)
38
+ const databaseUrl = String(args["database-url"] || env.DATABASE_URL || "").trim()
39
+ const outputRoot = resolvePath(
40
+ projectDir,
41
+ args.output || env.CORE_BACKUP_DIR || "backups",
42
+ )
43
+ const stateDir = resolvePath(
44
+ projectDir,
45
+ env.CORE_RUNTIME_STATE_DIR || ".core",
46
+ )
47
+ const statusPath = resolvePath(
48
+ projectDir,
49
+ args["status-file"] || env.CORE_BACKUP_STATUS_FILE || join(stateDir, "backup-status.json"),
50
+ )
51
+ const storeSlug = safePart(env.STORE_SLUG || "webshop")
52
+ const bundleName = String(args.name || `${storeSlug}-${backupTimestamp()}`).trim()
53
+ const bundleDir = join(outputRoot, bundleName)
54
+ const startedAt = new Date().toISOString()
55
+
56
+ writeBackupStatus({
57
+ schema_version: 1,
58
+ status: "running",
59
+ started_at: startedAt,
60
+ finished_at: null,
61
+ bundle_name: bundleName,
62
+ bundle_dir: bundleDir,
63
+ created_at: null,
64
+ size_bytes: null,
65
+ database_dump: false,
66
+ manifest_path: null,
67
+ error: null,
68
+ })
69
+
70
+ try {
71
+ runBackup()
72
+ } catch (error) {
73
+ const message = error instanceof Error ? error.message : String(error)
74
+ writeBackupStatus({
75
+ schema_version: 1,
76
+ status: "failed",
77
+ started_at: startedAt,
78
+ finished_at: new Date().toISOString(),
79
+ bundle_name: bundleName,
80
+ bundle_dir: bundleDir,
81
+ created_at: null,
82
+ size_bytes: existsSync(bundleDir) ? directorySize(bundleDir) : null,
83
+ database_dump: existsSync(join(bundleDir, "database.dump")),
84
+ manifest_path: existsSync(join(bundleDir, "manifest.json"))
85
+ ? join(bundleDir, "manifest.json")
86
+ : null,
87
+ error: message,
88
+ })
89
+ console.error(`\n❌ Backup sikertelen: ${message}`)
90
+ process.exitCode = 1
91
+ }
92
+
93
+ function runBackup() {
94
+ if (existsSync(bundleDir)) {
95
+ throw new Error(`A backup cél már létezik: ${bundleDir}`)
96
+ }
97
+ mkdirSync(bundleDir, { recursive: true, mode: 0o700 })
98
+
99
+ const pg = pgEnvironment(databaseUrl, env)
100
+ const dumpPath = join(bundleDir, "database.dump")
101
+ console.log(`\nMEDUSA WEBSHOP CORE backup: ${bundleName}`)
102
+ console.log("- PostgreSQL custom dump készítése...")
103
+ run("pg_dump", ["--format=custom", "--no-owner", "--no-acl", `--file=${dumpPath}`], pg.env)
104
+
105
+ const portable = portableConfig(env)
106
+ const portableJsonPath = join(bundleDir, "portable-config.json")
107
+ const portableEnvPath = join(bundleDir, "portable-config.env")
108
+ writeFileSync(
109
+ portableJsonPath,
110
+ `${JSON.stringify({ schema_version: 1, values: portable }, null, 2)}\n`,
111
+ { encoding: "utf8", mode: 0o600 },
112
+ )
113
+ writeFileSync(portableEnvPath, portableEnvText(portable), { encoding: "utf8", mode: 0o600 })
114
+
115
+ const bootstrapSource = join(backendProjectDir(projectDir), ".core", "webshop-bootstrap.json")
116
+ if (existsSync(bootstrapSource)) {
117
+ writeFileSync(
118
+ join(bundleDir, "webshop-bootstrap.json"),
119
+ readFileSync(bootstrapSource),
120
+ { mode: 0o600 },
121
+ )
122
+ }
123
+
124
+ const copiedFiles = []
125
+ for (const item of backupFileSources(projectDir, env)) {
126
+ console.log(`- ${item.key} mentése...`)
127
+ const target = copyBackupSource(bundleDir, item)
128
+ copiedFiles.push({ ...item, target })
129
+ }
130
+
131
+ const artifacts = [
132
+ artifact(bundleDir, "database.dump", "file"),
133
+ artifact(bundleDir, "portable-config.json", "file"),
134
+ artifact(bundleDir, "portable-config.env", "file"),
135
+ ]
136
+ if (existsSync(join(bundleDir, "webshop-bootstrap.json"))) {
137
+ artifacts.push(artifact(bundleDir, "webshop-bootstrap.json", "file"))
138
+ }
139
+ for (const item of copiedFiles) {
140
+ artifacts.push(
141
+ artifact(
142
+ bundleDir,
143
+ item.relative,
144
+ statSync(item.target).isDirectory() ? "directory" : "file",
145
+ item.key,
146
+ ),
147
+ )
148
+ }
149
+
150
+ const packageJson = JSON.parse(readFileSync(join(projectDir, "package.json"), "utf8"))
151
+ const createdAt = new Date().toISOString()
152
+ const manifest = {
153
+ schema_version: 1,
154
+ created_at: createdAt,
155
+ store_slug: env.STORE_SLUG || null,
156
+ store_name: env.STORE_NAME || null,
157
+ database_name: pg.database,
158
+ core_release: env.RELEASE_SHA || process.env.RELEASE_SHA || "unknown",
159
+ package_version: packageJson.version || null,
160
+ node_version: process.version,
161
+ database_format: "postgres-custom",
162
+ core_database_modules: CORE_DB_MODULES,
163
+ portable_config: "portable-config.json",
164
+ requires_integration_encryption_key: true,
165
+ encryption_key_included: false,
166
+ secret_plaintext_exported: false,
167
+ artifacts,
168
+ restore_notes: [
169
+ "Az eredeti INTEGRATION_SETTINGS_ENCRYPTION_KEY külön secret store-ból szükséges.",
170
+ "A cél PostgreSQL adatbázist a restore előtt létre kell hozni.",
171
+ "Ajánlott ugyanarra a Core release-re visszaállítani, majd migrációval frissíteni.",
172
+ ],
173
+ }
174
+ const manifestPath = join(bundleDir, "manifest.json")
175
+ writeFileSync(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`, {
176
+ encoding: "utf8",
177
+ mode: 0o600,
178
+ })
179
+
180
+ const sizeBytes = directorySize(bundleDir)
181
+ writeBackupStatus({
182
+ schema_version: 1,
183
+ status: "success",
184
+ started_at: startedAt,
185
+ finished_at: new Date().toISOString(),
186
+ bundle_name: bundleName,
187
+ bundle_dir: bundleDir,
188
+ created_at: createdAt,
189
+ size_bytes: sizeBytes,
190
+ database_dump: existsSync(dumpPath),
191
+ manifest_path: manifestPath,
192
+ error: null,
193
+ })
194
+
195
+ console.log("\n✅ Backup kész.")
196
+ console.log(`- bundle: ${bundleDir}`)
197
+ console.log(`- DB: ${pg.database}`)
198
+ console.log(`- artifactok: ${artifacts.length}`)
199
+ console.log(`- méret: ${sizeBytes} byte`)
200
+ console.log("- plaintext provider secret: NEM exportálva")
201
+ console.log("- encryption key: NINCS a backupban")
202
+ }
203
+
204
+ function artifact(root, relative, kind, role) {
205
+ const path = join(root, relative)
206
+ return {
207
+ path: relative,
208
+ kind,
209
+ ...(role ? { role } : {}),
210
+ sha256: kind === "directory" ? sha256Tree(path) : sha256File(path),
211
+ }
212
+ }
213
+
214
+ function run(command, commandArgs, commandEnv) {
215
+ const result = spawnSync(command, commandArgs, {
216
+ env: commandEnv,
217
+ stdio: "inherit",
218
+ })
219
+ if (result.error?.code === "ENOENT") {
220
+ throw new Error(`${command} nem található. Telepítsd a PostgreSQL klienseszközöket.`)
221
+ }
222
+ if (result.error) throw result.error
223
+ if (result.status !== 0) throw new Error(`${command} hibával leállt (${result.status}).`)
224
+ }
225
+
226
+ function writeBackupStatus(payload) {
227
+ mkdirSync(dirname(statusPath), { recursive: true, mode: 0o700 })
228
+ const temp = `${statusPath}.${process.pid}.tmp`
229
+ writeFileSync(temp, `${JSON.stringify(payload, null, 2)}\n`, {
230
+ encoding: "utf8",
231
+ mode: 0o600,
232
+ })
233
+ renameSync(temp, statusPath)
234
+ }
235
+
236
+ function directorySize(path) {
237
+ if (!existsSync(path)) return 0
238
+ const stat = statSync(path)
239
+ if (stat.isFile()) return stat.size
240
+ if (!stat.isDirectory()) return 0
241
+ return readdirSync(path).reduce(
242
+ (sum, entry) => sum + directorySize(join(path, entry)),
243
+ 0,
244
+ )
245
+ }
246
+
247
+ function resolvePath(root, value) {
248
+ const raw = String(value || "").trim()
249
+ return isAbsolute(raw) ? raw : resolve(root, raw)
250
+ }
251
+
252
+ function safePart(value) {
253
+ return String(value || "webshop")
254
+ .toLowerCase()
255
+ .replace(/[^a-z0-9_-]+/g, "-")
256
+ .replace(/^-+|-+$/g, "") || "webshop"
257
+ }
258
+
259
+ function parseArgs(tokens) {
260
+ const result = {}
261
+ for (let index = 0; index < tokens.length; index++) {
262
+ const raw = tokens[index]
263
+ if (!raw.startsWith("--")) continue
264
+ const token = raw.slice(2)
265
+ const eq = token.indexOf("=")
266
+ if (eq >= 0) {
267
+ result[token.slice(0, eq)] = token.slice(eq + 1)
268
+ continue
269
+ }
270
+ const next = tokens[index + 1]
271
+ if (next && !next.startsWith("--")) {
272
+ result[token] = next
273
+ index++
274
+ } else result[token] = true
275
+ }
276
+ return result
277
+ }
278
+
279
+ function printHelp() {
280
+ console.log(`MEDUSA WEBSHOP CORE backup\n\nHasználat:\n npm run core:backup -- [--output backups] [--name nightly] [--database-url ...] [--status-file .core/backup-status.json]\n\nA backup állapotát a Rendszerfelügyelet számára státuszfájlba írja. Plaintext provider secretet vagy encryption key-t továbbra sem exportál.\n`)
281
+ }
@@ -0,0 +1,179 @@
1
+ #!/usr/bin/env node
2
+
3
+ import {
4
+ cpSync,
5
+ existsSync,
6
+ mkdirSync,
7
+ readFileSync,
8
+ writeFileSync,
9
+ } from "node:fs"
10
+ import { dirname, isAbsolute, join, resolve } from "node:path"
11
+ import { spawnSync } from "node:child_process"
12
+ import process from "node:process"
13
+
14
+ import {
15
+ backendProjectDir,
16
+ integrationSnapshotPath,
17
+ loadRuntimeEnv,
18
+ pgEnvironment,
19
+ requireEncryptionKeyWhenNeeded,
20
+ verifyManifest,
21
+ } from "./lib/core-backup-common.mjs"
22
+
23
+ const args = parseArgs(process.argv.slice(2))
24
+ if (args.help) {
25
+ printHelp()
26
+ process.exit(0)
27
+ }
28
+
29
+ const projectDir = resolve(args["project-dir"] || process.cwd())
30
+ const bundleDir = resolve(required(args.from, "--from"))
31
+ const manifestPath = join(bundleDir, "manifest.json")
32
+ if (!existsSync(manifestPath)) throw new Error(`manifest.json nem található: ${bundleDir}`)
33
+
34
+ const manifest = JSON.parse(readFileSync(manifestPath, "utf8"))
35
+ if (manifest.schema_version !== 1) {
36
+ throw new Error(`Nem támogatott backup schema: ${manifest.schema_version}`)
37
+ }
38
+
39
+ console.log(`\nMEDUSA WEBSHOP CORE restore ellenőrzés`)
40
+ console.log(`- backup: ${bundleDir}`)
41
+ console.log(`- létrehozva: ${manifest.created_at || "ismeretlen"}`)
42
+ console.log(`- Core release: ${manifest.core_release || "ismeretlen"}`)
43
+ console.log("- checksumok ellenőrzése...")
44
+ verifyManifest(bundleDir, manifest)
45
+ console.log("✅ Backup integritása rendben.")
46
+
47
+ const env = loadRuntimeEnv(projectDir)
48
+ requireEncryptionKeyWhenNeeded(manifest, env)
49
+ const databaseUrl = String(args["database-url"] || env.DATABASE_URL || "").trim()
50
+ const pg = pgEnvironment(databaseUrl, env)
51
+
52
+ console.log(`- cél adatbázis: ${pg.database}`)
53
+ console.log("- Integration Settings encryption key: jelen van (érték nincs kiírva)")
54
+
55
+ if (!args.yes) {
56
+ console.log("\nDRY RUN: adatbázist és fájlt nem módosítottam.")
57
+ console.log("A tényleges, destruktív restore-hoz futtasd újra --yes kapcsolóval.")
58
+ process.exit(0)
59
+ }
60
+
61
+ const dumpPath = join(bundleDir, "database.dump")
62
+ console.log("\n- PostgreSQL visszaállítása (--clean --if-exists)...")
63
+ run(
64
+ "pg_restore",
65
+ [
66
+ "--clean",
67
+ "--if-exists",
68
+ "--no-owner",
69
+ "--no-acl",
70
+ `--dbname=${pg.database}`,
71
+ dumpPath,
72
+ ],
73
+ pg.env,
74
+ )
75
+
76
+ const restoredCoreDir = join(projectDir, ".core")
77
+ mkdirSync(restoredCoreDir, { recursive: true, mode: 0o700 })
78
+ const portableSource = join(bundleDir, "portable-config.env")
79
+ if (existsSync(portableSource)) {
80
+ const target = join(restoredCoreDir, "restored-portable.env")
81
+ writeFileSync(target, readFileSync(portableSource), { mode: 0o600 })
82
+ console.log(`- portable config kiírva: ${target}`)
83
+ console.log(" (szándékosan nincs automatikusan bemásolva a production .env-be)")
84
+ }
85
+
86
+ restoreFiles({ projectDir, bundleDir, env, overwrite: Boolean(args["overwrite-files"]) })
87
+
88
+ if (args.migrate) {
89
+ console.log("- Core migrációk futtatása...")
90
+ runNpm(projectDir, ["run", "db:migrate"], env)
91
+ }
92
+
93
+ console.log("\n✅ Restore kész.")
94
+ console.log("Következő lépések:")
95
+ console.log("1. Ellenőrizd/merge-eld a .core/restored-portable.env értékeket a cél .env-be.")
96
+ console.log("2. Ellenőrizd, hogy az eredeti INTEGRATION_SETTINGS_ENCRYPTION_KEY van használatban.")
97
+ console.log("3. Indítsd a backendet, majd futtasd a Production readiness ellenőrzést.")
98
+ console.log("4. Futtasd az E2E/smoke tesztet egy staging restore-on production indítás előtt.")
99
+
100
+ function restoreFiles({ projectDir, bundleDir, env, overwrite }) {
101
+ const snapshotSource = join(bundleDir, "files", "integration-settings.enc")
102
+ if (existsSync(snapshotSource)) {
103
+ const target = integrationSnapshotPath(projectDir, env)
104
+ copyWithGuard(snapshotSource, target, overwrite)
105
+ console.log(`- Integration Settings runtime snapshot visszaállítva: ${target}`)
106
+ }
107
+
108
+ const localStaticSource = join(bundleDir, "files", "local-static")
109
+ if (existsSync(localStaticSource)) {
110
+ const target = join(backendProjectDir(projectDir), "static")
111
+ copyWithGuard(localStaticSource, target, overwrite)
112
+ console.log(`- lokális file storage visszaállítva: ${target}`)
113
+ }
114
+
115
+ const uploadSource = join(bundleDir, "files", "file-upload-dir")
116
+ if (existsSync(uploadSource)) {
117
+ const configured = String(env.FILE_UPLOAD_DIR || "").trim()
118
+ if (!configured || !isAbsolute(configured)) {
119
+ throw new Error(
120
+ "A backup külön FILE_UPLOAD_DIR tartalmat is tartalmaz. Állíts be abszolút FILE_UPLOAD_DIR értéket a cél környezetben, majd futtasd újra a restore-t.",
121
+ )
122
+ }
123
+ copyWithGuard(uploadSource, configured, overwrite)
124
+ console.log(`- FILE_UPLOAD_DIR visszaállítva: ${configured}`)
125
+ }
126
+ }
127
+
128
+ function copyWithGuard(source, target, overwrite) {
129
+ if (existsSync(target) && !overwrite) {
130
+ throw new Error(
131
+ `A restore célfájl/könyvtár már létezik: ${target}. Tudatos felülíráshoz add meg a --overwrite-files kapcsolót.`,
132
+ )
133
+ }
134
+ mkdirSync(dirname(target), { recursive: true })
135
+ cpSync(source, target, { recursive: true, force: overwrite, errorOnExist: !overwrite })
136
+ }
137
+
138
+ function run(command, commandArgs, commandEnv) {
139
+ const result = spawnSync(command, commandArgs, { env: commandEnv, stdio: "inherit" })
140
+ if (result.error?.code === "ENOENT") {
141
+ throw new Error(`${command} nem található. Telepítsd a PostgreSQL klienseszközöket.`)
142
+ }
143
+ if (result.error) throw result.error
144
+ if (result.status !== 0) throw new Error(`${command} hibával leállt (${result.status}).`)
145
+ }
146
+
147
+ function runNpm(cwd, commandArgs, commandEnv) {
148
+ run(process.platform === "win32" ? "npm.cmd" : "npm", commandArgs, commandEnv)
149
+ }
150
+
151
+ function required(value, flag) {
152
+ const text = String(value || "").trim()
153
+ if (!text) throw new Error(`${flag} kötelező.`)
154
+ return text
155
+ }
156
+
157
+ function parseArgs(tokens) {
158
+ const result = {}
159
+ for (let index = 0; index < tokens.length; index++) {
160
+ const raw = tokens[index]
161
+ if (!raw.startsWith("--")) continue
162
+ const token = raw.slice(2)
163
+ const eq = token.indexOf("=")
164
+ if (eq >= 0) {
165
+ result[token.slice(0, eq)] = raw.slice(raw.indexOf("=") + 1)
166
+ continue
167
+ }
168
+ const next = tokens[index + 1]
169
+ if (next && !next.startsWith("--")) {
170
+ result[token] = next
171
+ index++
172
+ } else result[token] = true
173
+ }
174
+ return result
175
+ }
176
+
177
+ function printHelp() {
178
+ console.log(`MEDUSA WEBSHOP CORE restore\n\nEllenőrzés / dry run:\n npm run core:restore -- --from backups/<bundle>\n\nTényleges restore:\n npm run core:restore -- --from backups/<bundle> --yes --overwrite-files [--migrate]\n\nA restore destruktív PostgreSQL --clean műveletet használ, ezért --yes nélkül soha nem módosít adatot.\n`)
179
+ }
@@ -0,0 +1,237 @@
1
+ import { createHash } from "node:crypto"
2
+ import {
3
+ cpSync,
4
+ existsSync,
5
+ mkdirSync,
6
+ readFileSync,
7
+ readdirSync,
8
+ statSync,
9
+ } from "node:fs"
10
+ import { dirname, isAbsolute, join, resolve } from "node:path"
11
+
12
+ export const PORTABLE_ENV_KEYS = [
13
+ "MEDUSA_BACKEND_URL",
14
+ "STOREFRONT_URL",
15
+ "MEDUSA_ADMIN_PATH",
16
+ "STORE_CORS",
17
+ "ADMIN_CORS",
18
+ "AUTH_CORS",
19
+ "STORE_NAME",
20
+ "STORE_SLUG",
21
+ "STORE_LOCALE",
22
+ "STORE_DEFAULT_CURRENCY",
23
+ "STORE_DEFAULT_COUNTRY",
24
+ "VITE_ADMIN_BRAND_NAME",
25
+ "ORDER_EMAIL",
26
+ "SUPPORT_EMAIL",
27
+ "BILLING_EMAIL",
28
+ "SYSTEM_EMAIL",
29
+ "AFTER_SALES_ENABLED",
30
+ "AFTER_SALES_RETURNS_ENABLED",
31
+ "AFTER_SALES_EXCHANGES_ENABLED",
32
+ "AFTER_SALES_CLAIMS_ENABLED",
33
+ "AFTER_SALES_POLICY_URL",
34
+ "AFTER_SALES_RETURN_INSTRUCTIONS",
35
+ "SEO_STOREFRONT_URL",
36
+ "SEO_STORE_NAME",
37
+ "SEO_ORGANIZATION_NAME",
38
+ "SEO_ORGANIZATION_LOGO_URL",
39
+ "SEO_DEFAULT_COUNTRY",
40
+ "SEO_DEFAULT_CURRENCY",
41
+ "SEO_PRODUCT_PATH_TEMPLATE",
42
+ "SEO_CATEGORY_PATH_TEMPLATE",
43
+ "SEO_ALLOW_INDEXING",
44
+ "SEO_ROBOTS_DISALLOW",
45
+ ]
46
+
47
+ export const CORE_DB_MODULES = [
48
+ "medusa_native",
49
+ "integration_settings",
50
+ "integration_operation",
51
+ "core_audit",
52
+ "legal_consent",
53
+ "seo",
54
+ ]
55
+
56
+ export function backendProjectDir(projectDir) {
57
+ const monorepoBackend = join(projectDir, "apps", "backend")
58
+ if (existsSync(monorepoBackend)) return monorepoBackend
59
+
60
+ const generatedBackend = join(projectDir, "backend")
61
+ if (existsSync(generatedBackend)) return generatedBackend
62
+
63
+ return projectDir
64
+ }
65
+
66
+ export function loadRuntimeEnv(projectDir, overrides = process.env) {
67
+ const file = join(backendProjectDir(projectDir), ".env")
68
+ const fromFile = existsSync(file) ? parseEnv(readFileSync(file, "utf8")) : {}
69
+ const explicitOverrides = Object.fromEntries(
70
+ Object.entries(overrides).filter(([, value]) => value != null && String(value).trim() !== ""),
71
+ )
72
+ return { ...fromFile, ...explicitOverrides }
73
+ }
74
+
75
+ export function parseEnv(source) {
76
+ const result = {}
77
+ for (const rawLine of String(source).split(/\r?\n/)) {
78
+ const line = rawLine.trim()
79
+ if (!line || line.startsWith("#")) continue
80
+ const eq = line.indexOf("=")
81
+ if (eq <= 0) continue
82
+ const key = line.slice(0, eq).trim()
83
+ let value = line.slice(eq + 1).trim()
84
+ if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {
85
+ value = value.slice(1, -1)
86
+ }
87
+ result[key] = value
88
+ }
89
+ return result
90
+ }
91
+
92
+ export function portableConfig(env) {
93
+ const values = {}
94
+ for (const key of PORTABLE_ENV_KEYS) {
95
+ const value = String(env[key] ?? "").trim()
96
+ if (value) values[key] = value
97
+ }
98
+ return values
99
+ }
100
+
101
+ export function portableEnvText(values) {
102
+ return `${Object.entries(values)
103
+ .map(([key, value]) => `${key}=${quoteEnv(value)}`)
104
+ .join("\n")}\n`
105
+ }
106
+
107
+ export function pgEnvironment(databaseUrl, base = process.env) {
108
+ const url = new URL(required(databaseUrl, "DATABASE_URL"))
109
+ if (!["postgres:", "postgresql:"].includes(url.protocol)) {
110
+ throw new Error("DATABASE_URL csak postgres/postgresql URL lehet.")
111
+ }
112
+ const database = decodeURIComponent(url.pathname.replace(/^\//, ""))
113
+ if (!database) throw new Error("DATABASE_URL adatbázisneve hiányzik.")
114
+
115
+ return {
116
+ database,
117
+ env: {
118
+ ...base,
119
+ PGHOST: url.hostname,
120
+ PGPORT: url.port || "5432",
121
+ PGUSER: decodeURIComponent(url.username || ""),
122
+ PGPASSWORD: decodeURIComponent(url.password || ""),
123
+ PGDATABASE: database,
124
+ ...(url.searchParams.get("sslmode") ? { PGSSLMODE: url.searchParams.get("sslmode") } : {}),
125
+ },
126
+ }
127
+ }
128
+
129
+ export function integrationSnapshotPath(projectDir, env) {
130
+ const backendDir = backendProjectDir(projectDir)
131
+ const configured = String(env.INTEGRATION_SETTINGS_FILE || "").trim()
132
+ if (configured) return isAbsolute(configured) ? configured : resolve(backendDir, configured)
133
+
134
+ const uploadDir = String(env.FILE_UPLOAD_DIR || "").trim()
135
+ if (uploadDir && isAbsolute(uploadDir)) {
136
+ return join(dirname(uploadDir), "integration-settings.enc")
137
+ }
138
+
139
+ return join(backendDir, ".core", "integration-settings.enc")
140
+ }
141
+
142
+ export function backupFileSources(projectDir, env) {
143
+ const sources = []
144
+ const backendDir = backendProjectDir(projectDir)
145
+ const snapshot = integrationSnapshotPath(projectDir, env)
146
+ if (existsSync(snapshot)) {
147
+ sources.push({ key: "integration_snapshot", source: snapshot, relative: "files/integration-settings.enc" })
148
+ }
149
+
150
+ const localStatic = join(backendDir, "static")
151
+ if (existsSync(localStatic)) {
152
+ sources.push({ key: "local_static", source: localStatic, relative: "files/local-static" })
153
+ }
154
+
155
+ const configuredUpload = String(env.FILE_UPLOAD_DIR || "").trim()
156
+ if (configuredUpload && isAbsolute(configuredUpload) && existsSync(configuredUpload)) {
157
+ sources.push({ key: "file_upload_dir", source: configuredUpload, relative: "files/file-upload-dir" })
158
+ }
159
+ return sources
160
+ }
161
+
162
+ export function copyBackupSource(bundleDir, item) {
163
+ const target = join(bundleDir, item.relative)
164
+ mkdirSync(dirname(target), { recursive: true })
165
+ cpSync(item.source, target, { recursive: true, force: true })
166
+ return target
167
+ }
168
+
169
+ export function sha256File(path) {
170
+ const hash = createHash("sha256")
171
+ hash.update(readFileSync(path))
172
+ return hash.digest("hex")
173
+ }
174
+
175
+ export function sha256Tree(path) {
176
+ const hash = createHash("sha256")
177
+ hashDirectory(hash, path, path)
178
+ return hash.digest("hex")
179
+ }
180
+
181
+ export function verifyManifest(bundleDir, manifest) {
182
+ const failures = []
183
+ for (const artifact of manifest.artifacts || []) {
184
+ const path = join(bundleDir, artifact.path)
185
+ if (!existsSync(path)) {
186
+ failures.push(`${artifact.path}: hiányzik`)
187
+ continue
188
+ }
189
+ const actual = artifact.kind === "directory" ? sha256Tree(path) : sha256File(path)
190
+ if (actual !== artifact.sha256) failures.push(`${artifact.path}: checksum eltérés`)
191
+ }
192
+ if (failures.length) {
193
+ throw new Error(`A backup integritásellenőrzése sikertelen:\n- ${failures.join("\n- ")}`)
194
+ }
195
+ }
196
+
197
+ export function backupTimestamp(date = new Date()) {
198
+ return date.toISOString().replace(/[-:]/g, "").replace(/\.\d{3}Z$/, "Z")
199
+ }
200
+
201
+ export function requireEncryptionKeyWhenNeeded(manifest, env) {
202
+ if (!manifest.requires_integration_encryption_key) return
203
+ const key = String(env.INTEGRATION_SETTINGS_ENCRYPTION_KEY || "").trim()
204
+ if (key.length < 32) {
205
+ throw new Error(
206
+ "A backup titkosított Integration Settings adatot tartalmaz. A visszaállításhoz add meg az eredeti, legalább 32 karakteres INTEGRATION_SETTINGS_ENCRYPTION_KEY értéket; a kulcs szándékosan nincs a backupban.",
207
+ )
208
+ }
209
+ }
210
+
211
+ function hashDirectory(hash, root, current) {
212
+ const entries = readdirSync(current).sort((a, b) => a.localeCompare(b))
213
+ for (const name of entries) {
214
+ const full = join(current, name)
215
+ const relative = full.slice(root.length + 1)
216
+ const stat = statSync(full)
217
+ if (stat.isDirectory()) {
218
+ hash.update(`D:${relative}\n`)
219
+ hashDirectory(hash, root, full)
220
+ } else if (stat.isFile()) {
221
+ hash.update(`F:${relative}:${stat.size}\n`)
222
+ hash.update(readFileSync(full))
223
+ }
224
+ }
225
+ }
226
+
227
+ function quoteEnv(value) {
228
+ const text = String(value)
229
+ if (!/[\s#'"\\]/.test(text)) return text
230
+ return JSON.stringify(text)
231
+ }
232
+
233
+ function required(value, label) {
234
+ const text = String(value || "").trim()
235
+ if (!text) throw new Error(`${label} kötelező.`)
236
+ return text
237
+ }