@hszrdm/create-commerce 1.9.0 → 1.10.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.
package/README.md CHANGED
@@ -39,6 +39,59 @@ my-shop/
39
39
 
40
40
  The `deploy/` directory and `ecosystem.config.cjs` are materialized automatically during the first `npm install`. If the generator is run with `--skip-install`, running `npm install` later creates them.
41
41
 
42
+ ## Existing customer webshop upgrades
43
+
44
+ An upgrade is **not** the same operation as redeploying an unchanged customer
45
+ repository. The generator owns shared dependencies and starter files; each
46
+ customer owns its business-specific code, styling, secrets and infrastructure.
47
+
48
+ After publishing the new matching `@hszrdm/core` and
49
+ `@hszrdm/create-commerce` versions, run **in the customer's Git checkout**
50
+ (not on the production VPS):
51
+
52
+ ```bash
53
+ # Preview changes; never writes to the repository or database:
54
+ npx @hszrdm/create-commerce@<new-version> upgrade --dir .
55
+
56
+ # After reviewing and resolving any conflicts:
57
+ npx @hszrdm/create-commerce@<new-version> upgrade --dir . --apply
58
+
59
+ # Confirm the regenerated complete npm dependency tree:
60
+ npm ci
61
+ npm run verify
62
+ git diff --check
63
+ git add package.json package-lock.json backend storefront deploy scripts ecosystem.config.cjs hszrdm-commerce.json hszrdm-managed.json
64
+ git commit -m "chore: upgrade HSZRDM Commerce"
65
+ git push
66
+ ```
67
+
68
+ Newly generated projects also expose `npm run upgrade:core` for the **dry run**
69
+ and `npm run upgrade:core -- --apply` to apply the latest released generator
70
+ templates. Use an explicit `@<new-version>` instead of `@latest` for
71
+ reproducible production change requests.
72
+
73
+ The updater synchronizes the canonical backend and storefront dependencies,
74
+ their scripts and shared template files, generated deployment utilities, PM2
75
+ configuration, and regenerates the **full transitive** `package-lock.json`.
76
+ It preserves customer-only package dependencies, routes, application code,
77
+ customized files, and secret-bearing `.env*` files. Nothing modifies the
78
+ database, running PM2 processes, or the live deployment during this operation.
79
+
80
+ To avoid losing customer changes, the updater keeps `hszrdm-managed.json`
81
+ with the last generated file hashes and dependency baseline. When a customer
82
+ has edited a managed file or dependency, it **blocks** and reports a conflict
83
+ to merge manually; it never silently overwrites such changes.
84
+
85
+ **Existing older shops:** Shops created before the managed-file manifest
86
+ cannot safely auto-merge older, customized starter files. A dry run lists
87
+ the conflicts. Resolve them explicitly and establish a reviewed baseline;
88
+ do not use the new-project `--force` option on an existing shop, because that
89
+ option deletes the destination.
90
+
91
+ The production deploy then checks out the committed customer release and
92
+ uses `npm ci` against its committed lockfile. Merely publishing a new Core
93
+ package does not update existing customer checkouts automatically.
94
+
42
95
  ## Production commands
43
96
 
44
97
  ### Fresh server install
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hszrdm/create-commerce",
3
- "version": "1.9.0",
3
+ "version": "1.10.0",
4
4
  "description": "Create a complete HSZRDM Commerce webshop project.",
5
5
  "license": "UNLICENSED",
6
6
  "type": "module",
package/src/cli.mjs CHANGED
@@ -12,6 +12,7 @@ import { dirname, join, resolve } from "node:path"
12
12
  import { fileURLToPath } from "node:url"
13
13
  import { createInterface } from "node:readline/promises"
14
14
  import { stdin as input, stdout as output } from "node:process"
15
+ import { generatedRootScripts, writeGeneratedManifest, upgradeFromArgs, renderEcosystemConfig } from "./upgrade.mjs"
15
16
 
16
17
  const packageRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..")
17
18
  const packageVersion = clean(
@@ -19,6 +20,10 @@ const packageVersion = clean(
19
20
  )
20
21
 
21
22
  export async function main(argv = process.argv.slice(2)) {
23
+ if (argv[0] === "upgrade") {
24
+ upgradeFromArgs(argv.slice(1), packageVersion)
25
+ return
26
+ }
22
27
  const parsed = parseArgs(argv)
23
28
  if (parsed.flags.help || parsed.flags.h) {
24
29
  printHelp()
@@ -52,6 +57,7 @@ export async function main(argv = process.argv.slice(2)) {
52
57
  configureBackend(destination, settings)
53
58
  configureStorefront(destination, settings)
54
59
  writeMetadata(destination, settings)
60
+ writeGeneratedManifest(destination, packageVersion)
55
61
 
56
62
  if (!bool(parsed.flags["skip-install"])) {
57
63
  run("npm", ["install"], destination)
@@ -223,28 +229,31 @@ function configureProject(root, settings) {
223
229
  packageManager: "npm@10.9.4",
224
230
  engines: { node: "22.x" },
225
231
  workspaces: ["backend", "storefront"],
226
- scripts: {
227
- "dev:backend": "npm --workspace backend run dev",
228
- "dev:storefront": "npm --workspace storefront run dev",
229
- "typecheck": "npm --workspace backend run typecheck && npm --workspace storefront run typecheck",
230
- "test": "npm --workspace backend run test",
231
- "build": "npm --workspace backend run verify:build && npm --workspace storefront run build",
232
- "verify": "npm run typecheck && npm run test && npm run build",
233
- "db:migrate": "npm --workspace backend run db:migrate",
234
- "core:init": "npm --workspace backend run core:init --",
235
- "storefront:key": "npm --workspace backend run storefront:key --",
236
- "bootstrap:assert": "npm --workspace backend run bootstrap:assert",
237
- "docker:up": "docker compose --env-file .env.docker up -d --wait",
238
- "docker:down": "docker compose --env-file .env.docker down"
239
- },
232
+ scripts: generatedRootScripts(),
240
233
  }
241
234
  writeJson(join(root, "package.json"), rootPackage)
235
+ mkdirSync(join(root, "scripts"), { recursive: true })
236
+ cpSync(join(root, "backend", "scripts", "commerce-ops.mjs"),
237
+ join(root, "scripts", "commerce-ops.mjs"))
238
+ // Materialize generated operational assets before recording their baseline.
239
+ // Future Core upgrades can then replace only unchanged, Core-owned files.
240
+ mkdirSync(join(root, "deploy"), { recursive: true })
241
+ for (const name of ["install.sh", "deploy.sh", "backup.sh", "restore.sh"]) {
242
+ cpSync(join(root, "backend", "scripts", "production-assets", name),
243
+ join(root, "deploy", name))
244
+ }
245
+ writeFileSync(join(root, "ecosystem.config.cjs"), renderEcosystemConfig(settings))
246
+
242
247
  writeFileSync(join(root, ".nvmrc"), "22\n")
243
248
  writeFileSync(
244
249
  join(root, ".gitignore"),
245
250
  [
246
251
  "node_modules/",
247
252
  "backend/.env",
253
+ "backend/.env.production",
254
+ "backend/.env.staging",
255
+ "storefront/.env.staging",
256
+ "storefront/.env.production",
248
257
  "backend/.medusa/",
249
258
  "backend/src/api",
250
259
  "backend/src/jobs",
@@ -258,6 +267,7 @@ function configureProject(root, settings) {
258
267
  ".DS_Store",
259
268
  "*.log",
260
269
  "backups/",
270
+ ".core/deployment-environment",
261
271
  "",
262
272
  ].join("\n"),
263
273
  )
@@ -278,7 +288,18 @@ function configureProject(root, settings) {
278
288
 
279
289
  writeFileSync(
280
290
  join(root, "README.md"),
281
- `# ${settings.storeName}\n\nGenerated by @hszrdm/create-commerce.\n\n## Development\n\n\`npm run docker:up\`\n\`npm run dev:backend\`\n\`npm run dev:storefront\`\n\nProject-specific backend code belongs in \`backend/src/project/\`. Shared commerce behavior comes from \`@hszrdm/core\`.\n`,
291
+ `# ${settings.storeName}\n\nGenerated by @hszrdm/create-commerce.\n\n## Development\n\n\`npm run docker:up\`\n\`npm run dev:backend\`\n\`npm run dev:storefront\`\n\n## Environment operations
292
+
293
+ Development uses \`backend/.env\` and a separate development PostgreSQL database:
294
+ \`npm run install:dev\`, \`npm run deploy:dev\`, \`npm run backup:dev\`.
295
+ Production requires an independently configured \`backend/.env.production\` and PM2:
296
+ \`npm run install:prod\`, \`npm run deploy:prod\`, \`npm run backup:prod\`.
297
+ Restore is dry-run by default: \`npm run restore:dev -- --from backups/dev/<bundle>\`
298
+ or \`npm run restore:prod -- --from backups/prod/<bundle>\`.
299
+ Only add \`--yes\` after checking the target database; a restore can delete existing data.
300
+ Do not point any environments at the same PostgreSQL database. Use separate checkout directories for staging and production to avoid overwriting build files.
301
+
302
+ Project-specific backend code belongs in \`backend/src/project/\`. Shared commerce behavior comes from \`@hszrdm/core\`.\n`,
282
303
  )
283
304
  }
284
305
 
@@ -588,5 +609,5 @@ function bool(value) {
588
609
  }
589
610
 
590
611
  function printHelp() {
591
- console.log(`HSZRDM Commerce project generator\n\nHasználat:\n npx @hszrdm/create-commerce <project-name> [opciók]\n\nFő opciók:\n --name <név>\n --slug <slug>\n --locale hu-HU\n --country HU\n --currency HUF\n --backend-url http://localhost:9000\n --storefront-url http://localhost:3000\n --admin-email <email>\n --admin-password <password>\n --database-url postgres://...\n --redis-url redis://...\n --postgres-port <port>\n --redis-port <port>\n --core-version <verzió> (alapértelmezett: a generator package verziója)\n --non-interactive\n --force\n\nInfrastruktúra:\n Ha --database-url és --redis-url meg van adva, a generátor Dockert nem használ.\n Ha nincsenek megadva, Docker Compose a fallback.\n\nFejlesztői kapcsolók:\n --skip-install\n --skip-docker\n --skip-bootstrap\n --skip-verify\n --skip-git\n\nLokális Core package teszthez:\n HSZRDM_CORE_PACKAGE=/abs/path/to/packages/core npx @hszrdm/create-commerce test-shop\n`)
612
+ console.log(`HSZRDM Commerce project generator\n\nHasználat:\n npx @hszrdm/create-commerce <project-name> [opciók]\n npx @hszrdm/create-commerce@<verzió> upgrade --dir . [--apply]\n\nAz upgrade alapból dry-run: frissíti a kezelt függőségeket, közös forrásfájlokat, deploy-eszközöket és a teljes npm lockfile-t, de csak --apply használatakor ír a projektbe.\n\nFő opciók:\n --name <név>\n --slug <slug>\n --locale hu-HU\n --country HU\n --currency HUF\n --backend-url http://localhost:9000\n --storefront-url http://localhost:3000\n --admin-email <email>\n --admin-password <password>\n --database-url postgres://...\n --redis-url redis://...\n --postgres-port <port>\n --redis-port <port>\n --core-version <verzió> (alapértelmezett: a generator package verziója)\n --non-interactive\n --force\n\nInfrastruktúra:\n Ha --database-url és --redis-url meg van adva, a generátor Dockert nem használ.\n Ha nincsenek megadva, Docker Compose a fallback.\n\nFejlesztői kapcsolók:\n --skip-install\n --skip-docker\n --skip-bootstrap\n --skip-verify\n --skip-git\n\nLokális Core package teszthez:\n HSZRDM_CORE_PACKAGE=/abs/path/to/packages/core npx @hszrdm/create-commerce test-shop\n`)
592
613
  }
@@ -0,0 +1,345 @@
1
+ import { createHash } from "node:crypto"
2
+ import { execFileSync } from "node:child_process"
3
+ import { cpSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs"
4
+ import { tmpdir } from "node:os"
5
+ import { dirname, join, resolve } from "node:path"
6
+ import { fileURLToPath } from "node:url"
7
+
8
+ const PACKAGE_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..")
9
+ const MANIFEST = "hszrdm-managed.json"
10
+ const MANAGED_EXTRA_FILES = ["ecosystem.config.cjs", "scripts/commerce-ops.mjs", ...["install.sh", "deploy.sh", "backup.sh", "restore.sh"].map(name => "deploy/" + name)]
11
+ const SKIP_SEGMENTS = new Set(["node_modules", ".next", ".medusa", ".cache", ".git", "out", "static"])
12
+ const SKIP_FILES = new Set(["package.json", "package-lock.json", ".env", ".env.production", ".env.staging", ".env.local", ".env.docker"])
13
+
14
+ export function renderEcosystemConfig(settings) {
15
+ return `module.exports = {
16
+ apps: [
17
+ {
18
+ name: ${JSON.stringify(settings.slug + "-backend")},
19
+ cwd: __dirname,
20
+ script: "npm",
21
+ args: "--workspace backend run start:prod",
22
+ env_production: {
23
+ NODE_ENV: "production",
24
+ APP_ENV: "production",
25
+ PORT: ${JSON.stringify(new URL(settings.backendUrl).port || "9000")},
26
+ HOST: "127.0.0.1",
27
+ },
28
+ },
29
+ {
30
+ name: ${JSON.stringify(settings.slug + "-storefront")},
31
+ cwd: __dirname,
32
+ script: "npm",
33
+ args: "--workspace storefront run start",
34
+ env_production: {
35
+ NODE_ENV: "production",
36
+ APP_ENV: "production",
37
+ PORT: ${JSON.stringify(new URL(settings.storefrontUrl).port || "3000")},
38
+ HOSTNAME: "127.0.0.1",
39
+ },
40
+ },
41
+ {
42
+ name: ${JSON.stringify(settings.slug + "-staging-backend")},
43
+ cwd: __dirname,
44
+ script: "npm",
45
+ args: "--workspace backend run start:prod",
46
+ env_staging: {
47
+ NODE_ENV: "production",
48
+ APP_ENV: "staging",
49
+ PORT: "9101",
50
+ HOST: "127.0.0.1",
51
+ },
52
+ },
53
+ {
54
+ name: ${JSON.stringify(settings.slug + "-staging-storefront")},
55
+ cwd: __dirname,
56
+ script: "npm",
57
+ args: "--workspace storefront run start",
58
+ env_staging: {
59
+ NODE_ENV: "production",
60
+ APP_ENV: "staging",
61
+ PORT: "3101",
62
+ HOSTNAME: "127.0.0.1",
63
+ },
64
+ },
65
+ ],
66
+ }
67
+ `
68
+ }
69
+
70
+ export function generatedRootScripts() {
71
+ return {
72
+ "dev:backend": "npm --workspace backend run dev",
73
+ "dev:storefront": "npm --workspace storefront run dev",
74
+ "typecheck": "npm --workspace backend run typecheck && npm --workspace storefront run typecheck",
75
+ "test": "npm --workspace backend run test",
76
+ "build": "npm --workspace backend run verify:build && npm --workspace storefront run build",
77
+ "verify": "npm run typecheck && npm run test && npm run build",
78
+ "db:migrate": "npm --workspace backend run db:migrate",
79
+ "core:init": "npm --workspace backend run core:init --",
80
+ "storefront:key": "npm --workspace backend run storefront:key --",
81
+ "bootstrap:assert": "npm --workspace backend run bootstrap:assert",
82
+ "install:dev": "node ./scripts/commerce-ops.mjs install dev",
83
+ "install:prod": "node ./scripts/commerce-ops.mjs install prod",
84
+ "install:staging": "node ./scripts/commerce-ops.mjs install staging",
85
+ "deploy:dev": "node ./scripts/commerce-ops.mjs deploy dev",
86
+ "deploy:prod": "node ./scripts/commerce-ops.mjs deploy prod",
87
+ "deploy:staging": "node ./scripts/commerce-ops.mjs deploy staging",
88
+ "deploy:production": "npm run deploy:prod",
89
+ "backup:dev": "node ./scripts/commerce-ops.mjs backup dev",
90
+ "backup:prod": "node ./scripts/commerce-ops.mjs backup prod",
91
+ "backup:staging": "node ./scripts/commerce-ops.mjs backup staging",
92
+ "restore:dev": "node ./scripts/commerce-ops.mjs restore dev",
93
+ "restore:prod": "node ./scripts/commerce-ops.mjs restore prod",
94
+ "restore:staging": "node ./scripts/commerce-ops.mjs restore staging",
95
+ "docker:up": "docker compose --env-file .env.docker up -d --wait",
96
+ "docker:down": "docker compose --env-file .env.docker down",
97
+ "upgrade:core": "npx --yes @hszrdm/create-commerce@latest upgrade --dir .",
98
+ }
99
+ }
100
+
101
+ function readJson(path) { return JSON.parse(readFileSync(path, "utf8")) }
102
+ function json(value) { return JSON.stringify(value, null, 2) + "\n" }
103
+ function sha(data) { return createHash("sha256").update(data).digest("hex") }
104
+ function hashFile(path) { return sha(readFileSync(path)) }
105
+ function canonicalSource(path) {
106
+ if (path === "scripts/commerce-ops.mjs") return join(PACKAGE_ROOT, "templates", "backend", "scripts", "commerce-ops.mjs")
107
+ if (path.startsWith("deploy/")) return join(PACKAGE_ROOT, "templates", "backend", "scripts", "production-assets", path.slice("deploy/".length))
108
+ return join(PACKAGE_ROOT, "templates", path)
109
+ }
110
+ function walk(dir, prefix, result) {
111
+ if (!existsSync(dir)) return
112
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
113
+ if (SKIP_SEGMENTS.has(entry.name)) continue
114
+ const rel = prefix ? prefix + "/" + entry.name : entry.name
115
+ const abs = join(dir, entry.name)
116
+ if (entry.isSymbolicLink()) continue
117
+ if (entry.isDirectory()) walk(abs, rel, result)
118
+ else if (entry.isFile() && !SKIP_FILES.has(entry.name) && !rel.startsWith("backend/src/project/")) result.push(rel)
119
+ }
120
+ }
121
+ function managedPaths() {
122
+ const files = []
123
+ for (const name of ["backend", "storefront"]) walk(join(PACKAGE_ROOT, "templates", name), name, files)
124
+ return [...files, ...MANAGED_EXTRA_FILES].sort()
125
+ }
126
+ function packageDeps(pkg) {
127
+ const result = {}
128
+ for (const key of ["dependencies", "devDependencies", "optionalDependencies", "peerDependencies"]) {
129
+ result[key] = { ...(pkg[key] || {}) }
130
+ }
131
+ return result
132
+ }
133
+ function managedPackageState(root) {
134
+ const result = {}
135
+ for (const path of ["package.json", "backend/package.json", "storefront/package.json"]) {
136
+ const full = join(root, path)
137
+ if (!existsSync(full)) continue
138
+ const p = readJson(full)
139
+ result[path] = {
140
+ scripts: { ...(p.scripts || {}) },
141
+ deps: packageDeps(p),
142
+ }
143
+ }
144
+ return result
145
+ }
146
+ export function writeGeneratedManifest(root, version) {
147
+ const files = {}
148
+ for (const file of managedPaths()) {
149
+ const full = join(root, file)
150
+ if (existsSync(full)) files[file] = hashFile(full)
151
+ }
152
+ writeFileSync(join(root, MANIFEST), json({
153
+ schema_version: 1,
154
+ generator_version: version,
155
+ files,
156
+ packages: managedPackageState(root),
157
+ }))
158
+ }
159
+
160
+ function expectedPackage(path, version) {
161
+ if (path === "package.json") return { scripts: generatedRootScripts() }
162
+ const packagePath = join(PACKAGE_ROOT, "templates", path)
163
+ const pkg = readJson(packagePath)
164
+ if (path === "backend/package.json") {
165
+ pkg.dependencies ||= {}
166
+ pkg.dependencies["@hszrdm/core"] = version
167
+ pkg.scripts ||= {}
168
+ pkg.scripts.test = "npm run typecheck"
169
+ }
170
+ return pkg
171
+ }
172
+
173
+ /**
174
+ * Dry-run unless --apply. Three-way merge of generated files based on hashes
175
+ * captured at project generation or the previous successful upgrade.
176
+ * Customer additions and changes are never silently replaced.
177
+ */
178
+ export function planUpgrade(root, version) {
179
+ const metadataPath = join(root, "hszrdm-commerce.json")
180
+ if (!existsSync(metadataPath) || !existsSync(join(root, "backend/package.json")) ||
181
+ !existsSync(join(root, "storefront/package.json"))) {
182
+ throw new Error("This is not a generated HSZRDM Commerce project.")
183
+ }
184
+ const previous = existsSync(join(root, MANIFEST)) ? readJson(join(root, MANIFEST)) : null
185
+ if (previous && previous.schema_version !== 1) throw new Error("Unknown managed manifest version.")
186
+ const conflicts = [], changes = [], files = {}
187
+ const canonicalPaths = managedPaths()
188
+ const canonicalSet = new Set(canonicalPaths)
189
+ for (const path of canonicalPaths) {
190
+ const source = path === "ecosystem.config.cjs" ? null : canonicalSource(path)
191
+ const target = join(root, path)
192
+ const metadata = path === "ecosystem.config.cjs" ? readJson(metadataPath) : null
193
+ const desired = source ? readFileSync(source) : Buffer.from(renderEcosystemConfig({
194
+ slug: metadata.project.slug,
195
+ backendUrl: metadata.urls.backend,
196
+ storefrontUrl: metadata.urls.storefront,
197
+ }))
198
+ const desiredHash = sha(desired)
199
+ const targetStat = lstatSync(target, { throwIfNoEntry: false })
200
+ if (targetStat && !targetStat.isFile()) {
201
+ conflicts.push(path + " (not a regular file; refusing to overwrite)")
202
+ continue
203
+ }
204
+ const currentHash = targetStat ? hashFile(target) : null
205
+ const known = previous?.files?.[path]
206
+ if (currentHash === desiredHash) {
207
+ files[path] = currentHash
208
+ } else if (currentHash === null || (known && known === currentHash)) {
209
+ changes.push({ kind: "file", path, content: desired })
210
+ files[path] = desiredHash
211
+ } else {
212
+ conflicts.push(path + " (customer-modified or missing baseline)")
213
+ }
214
+ }
215
+
216
+ // Remove files retired from the canonical starter only when their original
217
+ // content is unchanged; never remove customer-modified files.
218
+ for (const [path, previousHash] of Object.entries(previous?.files || {})) {
219
+ if (canonicalSet.has(path)) continue
220
+ const target = join(root, path)
221
+ const stat = lstatSync(target, { throwIfNoEntry: false })
222
+ if (!stat) continue
223
+ if (stat.isFile() && hashFile(target) === previousHash) {
224
+ changes.push({ kind: "delete", path })
225
+ } else {
226
+ conflicts.push(path + " (obsolete file modified by customer)")
227
+ files[path] = previousHash
228
+ }
229
+ }
230
+
231
+ const packages = {}
232
+ for (const path of ["package.json", "backend/package.json", "storefront/package.json"]) {
233
+ const current = readJson(join(root, path))
234
+ const desired = expectedPackage(path, version)
235
+ const base = previous?.packages?.[path]
236
+ const merged = structuredClone(current)
237
+ merged.scripts ||= {}
238
+ for (const [key, nextValue] of Object.entries(desired.scripts || {})) {
239
+ const oldValue = base?.scripts?.[key]
240
+ if (current.scripts[key] !== nextValue && current.scripts[key] !== undefined &&
241
+ (!base || (oldValue !== undefined && current.scripts[key] !== oldValue))) {
242
+ conflicts.push(path + ":scripts." + key)
243
+ } else merged.scripts[key] = nextValue
244
+ }
245
+ for (const group of ["dependencies", "devDependencies", "optionalDependencies", "peerDependencies"]) {
246
+ merged[group] ||= {}
247
+ const managed = { ...(desired[group] || {}) }
248
+ for (const [key, nextValue] of Object.entries(managed)) {
249
+ const currentValue = current[group]?.[key]
250
+ const oldValue = base?.deps?.[group]?.[key]
251
+ if (currentValue !== nextValue && currentValue !== undefined &&
252
+ (!base || (oldValue !== undefined && currentValue !== oldValue))) {
253
+ conflicts.push(path + ":" + group + "." + key)
254
+ } else merged[group][key] = nextValue
255
+ }
256
+ // Remove dependencies dropped by the canonical starter only if untouched.
257
+ for (const [key, oldValue] of Object.entries(base?.deps?.[group] || {})) {
258
+ if (key in managed || !(key in merged[group])) continue
259
+ if (merged[group][key] === oldValue) delete merged[group][key]
260
+ else conflicts.push(path + ":obsolete " + group + "." + key)
261
+ }
262
+ }
263
+ const oldContent = readFileSync(join(root, path), "utf8")
264
+ if (json(merged) !== oldContent) changes.push({ kind: "json", path, content: json(merged) })
265
+ packages[path] = {
266
+ scripts: Object.fromEntries(Object.entries(desired.scripts || {}).map(([k]) => [k, merged.scripts[k]])),
267
+ deps: Object.fromEntries(["dependencies", "devDependencies", "optionalDependencies", "peerDependencies"].map(k => [
268
+ k, Object.fromEntries(Object.keys(desired[k] || {}).map(dep => [dep, merged[k][dep]])),
269
+ ])),
270
+ }
271
+ }
272
+
273
+ return { root, version, previous, changes, conflicts, nextManifest: {
274
+ schema_version: 1,
275
+ generator_version: version,
276
+ files: Object.fromEntries([
277
+ ...Object.entries(previous?.files || {}).filter(([path]) => canonicalSet.has(path)),
278
+ ...Object.entries(files),
279
+ ]),
280
+ packages,
281
+ } }
282
+ }
283
+
284
+ export function applyUpgrade(plan, { execute = true } = {}) {
285
+ if (plan.conflicts.length) throw new Error("Upgrade blocked by customer changes:\n- " + plan.conflicts.join("\n- "))
286
+ if (!execute) return plan
287
+ const staged = [...plan.changes, { kind: "json", path: MANIFEST, content: json(plan.nextManifest) }]
288
+ const metadataPath = join(plan.root, "hszrdm-commerce.json")
289
+ const metadata = readJson(metadataPath)
290
+ metadata.core_version = plan.version
291
+ staged.push({ kind: "json", path: "hszrdm-commerce.json", content: json(metadata) })
292
+ // Preserve the old full lock graph if npm resolution fails.
293
+ const lockPath = join(plan.root, "package-lock.json")
294
+ const lockExisted = existsSync(lockPath)
295
+ const oldLock = lockExisted ? readFileSync(lockPath) : null
296
+ const backupDir = mkdtempSync(join(tmpdir(), "hszrdm-upgrade-rollback-"))
297
+ const originals = []
298
+ try {
299
+ for (const change of staged) {
300
+ const full = join(plan.root, change.path)
301
+ if (existsSync(full)) {
302
+ if (!lstatSync(full).isFile()) throw new Error("Cannot overwrite non-regular file: " + change.path)
303
+ const old = join(backupDir, change.path)
304
+ mkdirSync(dirname(old), { recursive: true })
305
+ cpSync(full, old)
306
+ }
307
+ originals.push({ full, path: change.path, existed: existsSync(full) })
308
+ mkdirSync(dirname(full), { recursive: true })
309
+ if (change.kind === "delete") rmSync(full, { force: true })
310
+ else writeFileSync(full, change.content)
311
+ }
312
+ // This refreshes the full transitive dependency graph without executing
313
+ // install hooks or touching application secrets, DBs or running processes.
314
+ execFileSync(process.platform === "win32" ? "npm.cmd" : "npm",
315
+ ["install", "--package-lock-only", "--ignore-scripts", "--no-audit", "--no-fund"],
316
+ { cwd: plan.root, stdio: "inherit" })
317
+ console.log("Upgrade prepared; verify npm ci, typecheck, tests and build before deploying.")
318
+ } catch (error) {
319
+ if (lockExisted) writeFileSync(lockPath, oldLock)
320
+ else rmSync(lockPath, { force: true })
321
+ for (const item of originals.reverse()) {
322
+ if (item.existed) cpSync(join(backupDir, item.path), item.full)
323
+ else rmSync(item.full, { force: true })
324
+ }
325
+ throw error
326
+ } finally { rmSync(backupDir, { force: true, recursive: true }) }
327
+ return plan
328
+ }
329
+
330
+ export function upgradeFromArgs(args, version) {
331
+ const index = args.indexOf("--dir")
332
+ const inline = args.find(x => x.startsWith("--dir="))
333
+ const root = resolve(inline ? inline.slice(6) : index >= 0 ? args[index + 1] : ".")
334
+ const plan = planUpgrade(root, version)
335
+ console.log(`HSZRDM Commerce upgrade ${plan.previous?.generator_version || "legacy"} → ${version}`)
336
+ console.log(`Changes: ${plan.changes.length}; conflicts: ${plan.conflicts.length}`)
337
+ for (const c of plan.changes) console.log("UPDATE", c.path)
338
+ for (const c of plan.conflicts) console.error("CONFLICT", c)
339
+ if (!args.includes("--apply")) {
340
+ console.log("DRY RUN: no changes made. Use --apply after reviewing the plan.")
341
+ if (plan.conflicts.length) process.exitCode = 2
342
+ return plan
343
+ }
344
+ return applyUpgrade(plan)
345
+ }
@@ -80,16 +80,21 @@ OPENAI_BASE_URL=https://api.openai.com/v1
80
80
  # Email Center / transactional email
81
81
  # -----------------------------------------------------------------------------
82
82
  EMAIL_CENTER_ENABLED=true
83
- # Supported provider values: sendgrid, resend. Empty = local Medusa provider.
84
- EMAIL_PROVIDER=
85
- EMAIL_API_KEY=
86
- EMAIL_FROM=
87
- EMAIL_REPLY_TO=
88
- # Optional provider-specific fallbacks.
89
- RESEND_API_KEY=
90
- RESEND_FROM_EMAIL=
91
- SENDGRID_API_KEY=
92
- SENDGRID_FROM_EMAIL=
83
+ # SMTP is the only supported email transport. This legacy selector is optional.
84
+ EMAIL_PROVIDER=smtp
85
+ # New stores have no SMTP host yet; enable after configuring and verifying SMTP in Admin.
86
+ SMTP_ENABLED=false
87
+ EMAIL_FROM="Example Store <system@example.com>"
88
+ EMAIL_REPLY_TO=support@example.com
89
+ SMTP_HOST=
90
+ SMTP_PORT=587
91
+ # true for implicit TLS (typically 465), false for STARTTLS (typically 587)
92
+ SMTP_SECURE=false
93
+ SMTP_REQUIRE_TLS=true
94
+ SMTP_USER=
95
+ SMTP_PASSWORD=
96
+ SMTP_FROM="Example Store <system@example.com>"
97
+ SMTP_REPLY_TO=
93
98
 
94
99
  EMAIL_CUSTOMER_WELCOME_ENABLED=
95
100
  EMAIL_REGISTRATION_VERIFICATION_ENABLED=
@@ -104,6 +109,11 @@ EMAIL_FULFILLMENT_CREATED_ENABLED=
104
109
  EMAIL_SHIPMENT_CREATED_ENABLED=
105
110
  EMAIL_ORDER_CANCELED_ENABLED=
106
111
  EMAIL_PAYMENT_REFUNDED_ENABLED=
112
+ EMAIL_AFTER_SALES_SUBMITTED_ENABLED=
113
+ EMAIL_AFTER_SALES_APPROVED_ENABLED=
114
+ EMAIL_AFTER_SALES_REJECTED_ENABLED=
115
+ EMAIL_RETURN_INSTRUCTIONS_ENABLED=
116
+ EMAIL_RETURN_RECEIVED_ENABLED=
107
117
 
108
118
  EMAIL_LOGO_URL=
109
119
  EMAIL_TRACKING_ENABLED=true
@@ -22,7 +22,7 @@
22
22
  "start:prod": "cd .medusa/server && medusa start"
23
23
  },
24
24
  "dependencies": {
25
- "@hszrdm/core": "1.9.0",
25
+ "@hszrdm/core": "1.10.0",
26
26
  "@medusajs/admin-sdk": "2.22.2",
27
27
  "@medusajs/cli": "2.22.2",
28
28
  "@medusajs/draft-order": "2.22.2",