@oxog/dockcraft 1.0.0 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,8 +1,63 @@
1
1
  /**
2
- * @oxog/dockcraft - Zero-Dependency NPM Package
3
- * GitHub: https://github.com/ersinkoc/dockcraft
4
- * License: MIT
5
- */
2
+ * @oxog/dockcraft - Zero-Dependency NPM Package
3
+ * GitHub: https://github.com/ersinkoc/DockCraft
4
+ * License: MIT
5
+ */
6
+
7
+ // src/types.ts
8
+ var DockcraftError = class extends Error {
9
+ constructor(message, code) {
10
+ super(message);
11
+ this.code = code;
12
+ this.name = "DockcraftError";
13
+ }
14
+ };
15
+ var ConfigError = class extends DockcraftError {
16
+ constructor(message, code = "CONFIG_ERROR") {
17
+ super(message, code);
18
+ this.name = "ConfigError";
19
+ }
20
+ };
21
+ var ValidationError = class extends DockcraftError {
22
+ constructor(message, errors, code = "VALIDATION_ERROR") {
23
+ super(message, code);
24
+ this.errors = errors;
25
+ this.name = "ValidationError";
26
+ }
27
+ };
28
+ var PortConflictError = class extends DockcraftError {
29
+ constructor(port, code = "PORT_CONFLICT") {
30
+ super(`Port ${port} is already in use`, code);
31
+ this.name = "PortConflictError";
32
+ }
33
+ };
34
+ var NoPortAvailableError = class extends DockcraftError {
35
+ constructor(range, code = "NO_PORT_AVAILABLE") {
36
+ super(`No available port in range ${range[0]}-${range[1]}`, code);
37
+ this.name = "NoPortAvailableError";
38
+ }
39
+ };
40
+ var FileWriteError = class extends DockcraftError {
41
+ constructor(path, code = "FILE_WRITE_ERROR", cause) {
42
+ super(`Failed to write file: ${path}${cause instanceof Error ? ` (${cause.message})` : ""}`, code);
43
+ this.name = "FileWriteError";
44
+ if (cause !== void 0) {
45
+ this.cause = cause;
46
+ }
47
+ }
48
+ };
49
+ var PresetNotFoundError = class extends DockcraftError {
50
+ constructor(name, code = "PRESET_NOT_FOUND") {
51
+ super(`Preset '${name}' not found`, code);
52
+ this.name = "PresetNotFoundError";
53
+ }
54
+ };
55
+ var ServiceNotFoundError = class extends DockcraftError {
56
+ constructor(name, code = "SERVICE_NOT_FOUND") {
57
+ super(`Service '${name}' not found`, code);
58
+ this.name = "ServiceNotFoundError";
59
+ }
60
+ };
6
61
 
7
62
  // src/presets/express-postgres.ts
8
63
  var expressPostgresPreset = {
@@ -242,10 +297,24 @@ registerPreset("nest-postgres", nestPostgresPreset);
242
297
  registerPreset("nest-mongo", nestMongoPreset);
243
298
  registerPreset("node-minimal", nodeMinimalPreset);
244
299
 
300
+ // src/services/image.ts
301
+ function variantImage(repository, version, variant) {
302
+ if (version === "latest") {
303
+ return `${repository}:${variant}`;
304
+ }
305
+ if (version === variant || version.includes("-")) {
306
+ return `${repository}:${version}`;
307
+ }
308
+ return `${repository}:${version}-${variant}`;
309
+ }
310
+ function urlPart(value) {
311
+ return encodeURIComponent(value);
312
+ }
313
+
245
314
  // src/services/postgres.ts
246
315
  var postgresService = {
247
316
  name: "postgres",
248
- image: (version) => `postgres:${version}-alpine`,
317
+ image: (version) => variantImage("postgres", version, "alpine"),
249
318
  defaultPort: 5432,
250
319
  defaultVersion: "16",
251
320
  env: {
@@ -262,7 +331,7 @@ var postgresService = {
262
331
  const database = config.env.POSTGRES_DB || "myapp";
263
332
  const host = config.name;
264
333
  const port = config.port;
265
- return `postgres://${user}:${password}@${host}:${port}/${database}`;
334
+ return `postgres://${urlPart(user)}:${urlPart(password)}@${host}:${port}/${urlPart(database)}`;
266
335
  }
267
336
  };
268
337
 
@@ -287,7 +356,7 @@ var mysqlService = {
287
356
  const database = config.env.MYSQL_DATABASE || "myapp";
288
357
  const host = config.name;
289
358
  const port = config.port;
290
- return `mysql://${user}:${password}@${host}:${port}/${database}`;
359
+ return `mysql://${urlPart(user)}:${urlPart(password)}@${host}:${port}/${urlPart(database)}`;
291
360
  }
292
361
  };
293
362
 
@@ -311,14 +380,14 @@ var mongoService = {
311
380
  const database = config.env.MONGO_INITDB_DATABASE || "myapp";
312
381
  const host = config.name;
313
382
  const port = config.port;
314
- return `mongodb://${user}:${password}@${host}:${port}/${database}`;
383
+ return `mongodb://${urlPart(user)}:${urlPart(password)}@${host}:${port}/${urlPart(database)}?authSource=admin`;
315
384
  }
316
385
  };
317
386
 
318
387
  // src/services/redis.ts
319
388
  var redisService = {
320
389
  name: "redis",
321
- image: (version) => `redis:${version}-alpine`,
390
+ image: (version) => variantImage("redis", version, "alpine"),
322
391
  defaultPort: 6379,
323
392
  defaultVersion: "7",
324
393
  env: {},
@@ -328,7 +397,9 @@ var redisService = {
328
397
  connectionString: (config) => {
329
398
  const host = config.name;
330
399
  const port = config.port;
331
- return `redis://${host}:${port}`;
400
+ const password = config.env.REDIS_PASSWORD;
401
+ const auth = password ? `:${urlPart(password)}@` : "";
402
+ return `redis://${auth}${host}:${port}`;
332
403
  }
333
404
  };
334
405
 
@@ -349,12 +420,13 @@ registerService(mongoService);
349
420
  registerService(redisService);
350
421
 
351
422
  // src/utils/merge.ts
423
+ var UNSAFE_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
352
424
  function deepMerge(...objects) {
353
425
  const result = {};
354
426
  for (const obj of objects) {
355
427
  if (obj === null || typeof obj !== "object") continue;
356
428
  for (const [key, value] of Object.entries(obj)) {
357
- if (value === void 0) continue;
429
+ if (value === void 0 || UNSAFE_KEYS.has(key)) continue;
358
430
  if (value && typeof value === "object" && !Array.isArray(value) && result[key] && typeof result[key] === "object" && !Array.isArray(result[key])) {
359
431
  result[key] = deepMerge(result[key], value);
360
432
  } else {
@@ -368,21 +440,30 @@ function deepMerge(...objects) {
368
440
  // src/ports/scanner.ts
369
441
  import { createServer } from "net";
370
442
  async function isPortAvailable(port) {
443
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
444
+ throw new RangeError(`Invalid port: ${String(port)}. Must be an integer between 1 and 65535.`);
445
+ }
371
446
  return new Promise((resolve) => {
372
447
  const server = createServer();
448
+ let settled = false;
449
+ const finish = (available) => {
450
+ if (settled) return;
451
+ settled = true;
452
+ clearTimeout(timer);
453
+ resolve(available);
454
+ };
455
+ const timer = setTimeout(() => {
456
+ server.close();
457
+ finish(false);
458
+ }, 1e3);
459
+ timer.unref();
373
460
  server.once("error", () => {
374
- resolve(false);
461
+ finish(false);
375
462
  });
376
463
  server.once("listening", () => {
377
- server.close(() => {
378
- resolve(true);
379
- });
464
+ server.close(() => finish(true));
380
465
  });
381
466
  server.listen(port, "127.0.0.1");
382
- setTimeout(() => {
383
- server.close();
384
- resolve(false);
385
- }, 1e3);
386
467
  });
387
468
  }
388
469
  async function checkPorts(ports) {
@@ -421,24 +502,25 @@ async function resolvePort(options = {}) {
421
502
  if (await isPortAvailable(preferred)) {
422
503
  return preferred;
423
504
  }
424
- throw new Error(`Port ${preferred} is already in use`);
505
+ throw new PortConflictError(preferred);
425
506
  case "range":
426
507
  if (range) {
427
508
  const [start, end = start + 100] = range;
428
- const port2 = await findAvailablePortInRange(start, end);
429
- if (port2 !== void 0) {
430
- return port2;
509
+ const port = await findAvailablePortInRange(start, end);
510
+ if (port !== void 0) {
511
+ return port;
431
512
  }
432
- throw new Error(`No available port in range ${start}-${end}`);
513
+ throw new NoPortAvailableError([start, end]);
433
514
  }
434
515
  // Fall through to auto if no range specified
435
516
  case "auto":
436
- default:
517
+ default: {
437
518
  const port = await findNextAvailablePort(preferred);
438
519
  if (port !== void 0) {
439
520
  return port;
440
521
  }
441
- throw new Error(`No available port found starting from ${preferred}`);
522
+ throw new NoPortAvailableError([preferred, 65535]);
523
+ }
442
524
  }
443
525
  }
444
526
 
@@ -453,9 +535,9 @@ var DEFAULT_APP_CONFIG = {
453
535
  volumes: [],
454
536
  multiStage: true
455
537
  };
456
- function normalizeAppConfig(config) {
538
+ function normalizeAppConfig(config = {}) {
457
539
  return {
458
- port: config.port === "auto" ? 3e3 : config.port,
540
+ port: typeof config.port === "number" ? config.port : DEFAULT_APP_CONFIG.port,
459
541
  node: config.node ?? DEFAULT_APP_CONFIG.node,
460
542
  workdir: config.workdir ?? DEFAULT_APP_CONFIG.workdir,
461
543
  command: config.command ?? DEFAULT_APP_CONFIG.command,
@@ -477,7 +559,7 @@ function normalizeConfig(config) {
477
559
  return {
478
560
  name: config.name,
479
561
  preset: config.preset,
480
- app: config.app,
562
+ app: config.app ?? {},
481
563
  services: config.services ?? {},
482
564
  output: normalizeOutputConfig(config.output),
483
565
  plugins: config.plugins ?? []
@@ -485,10 +567,11 @@ function normalizeConfig(config) {
485
567
  }
486
568
 
487
569
  // src/core/resolver.ts
570
+ var REDIS_AUTH_COMMAND = `sh -c 'exec redis-server --requirepass "$$REDIS_PASSWORD"'`;
488
571
  function mergePreset(config, presetName) {
489
572
  const preset = getPreset(presetName);
490
573
  if (!preset) {
491
- throw new Error(`Preset '${presetName}' not found`);
574
+ throw new PresetNotFoundError(presetName);
492
575
  }
493
576
  const merged = deepMerge(
494
577
  {
@@ -501,55 +584,65 @@ function mergePreset(config, presetName) {
501
584
  );
502
585
  return merged;
503
586
  }
504
- async function resolveServiceConfig(name, config, projectName) {
587
+ async function resolveServicePorts(portConfig, containerPort) {
588
+ if (portConfig === "auto") {
589
+ return {
590
+ port: containerPort,
591
+ hostPort: await resolvePort({ preferred: containerPort, strategy: "auto" })
592
+ };
593
+ }
594
+ if (typeof portConfig === "number") {
595
+ return { port: containerPort, hostPort: portConfig };
596
+ }
597
+ if (portConfig && typeof portConfig === "object") {
598
+ const startPort = portConfig.start ?? containerPort;
599
+ const endPort = portConfig.end ?? startPort + 100;
600
+ return {
601
+ port: containerPort,
602
+ hostPort: await resolvePort({ preferred: startPort, strategy: "range", range: [startPort, endPort] })
603
+ };
604
+ }
605
+ return { port: containerPort };
606
+ }
607
+ async function resolveServiceConfig(name, config, projectName, definitions) {
505
608
  if ("image" in config && config.image) {
506
609
  return resolveCustomService(name, config);
507
610
  }
508
- const definition = getService(name);
611
+ const definition = definitions?.get(name) ?? getService(name);
509
612
  if (!definition) {
510
- throw new Error(`Unknown service: ${name}`);
511
- }
512
- const defaultPort = definition.defaultPort;
513
- let port = defaultPort;
514
- let hostPort;
515
- if (config.port === "auto") {
516
- port = await resolvePort({ preferred: defaultPort, strategy: "auto" });
517
- hostPort = port;
518
- } else if (typeof config.port === "number") {
519
- port = config.port;
520
- hostPort = config.port;
521
- } else if (config.port && typeof config.port === "object") {
522
- const { start, end } = config.port;
523
- const startPort = start ?? defaultPort;
524
- const endPort = end ?? startPort + 100;
525
- port = await resolvePort({ preferred: startPort, strategy: "range", range: [startPort, endPort] });
526
- hostPort = port;
613
+ throw new ServiceNotFoundError(name);
527
614
  }
615
+ const { port, hostPort } = await resolveServicePorts(config.port, definition.defaultPort);
528
616
  const version = config.version ?? definition.defaultVersion;
529
617
  const image = typeof definition.image === "function" ? definition.image(version) : definition.image;
530
618
  const env = { ...definition.env, ...config.env };
619
+ let command = config.command;
531
620
  if (name === "postgres") {
532
621
  const pgConfig = config;
533
622
  if (pgConfig.database) env.POSTGRES_DB = pgConfig.database;
534
623
  if (pgConfig.user) env.POSTGRES_USER = pgConfig.user;
535
624
  if (pgConfig.password) env.POSTGRES_PASSWORD = pgConfig.password;
536
- if (!env.POSTGRES_DB) env.POSTGRES_DB = projectName;
625
+ if (!pgConfig.database && !config.env?.POSTGRES_DB) env.POSTGRES_DB = projectName;
537
626
  } else if (name === "mysql") {
538
627
  const mysqlConfig = config;
539
628
  if (mysqlConfig.database) env.MYSQL_DATABASE = mysqlConfig.database;
540
629
  if (mysqlConfig.user) env.MYSQL_USER = mysqlConfig.user;
541
630
  if (mysqlConfig.password) env.MYSQL_PASSWORD = mysqlConfig.password;
542
631
  if (mysqlConfig.rootPassword) env.MYSQL_ROOT_PASSWORD = mysqlConfig.rootPassword;
543
- if (!env.MYSQL_DATABASE) env.MYSQL_DATABASE = projectName;
632
+ if (!mysqlConfig.database && !config.env?.MYSQL_DATABASE) env.MYSQL_DATABASE = projectName;
544
633
  } else if (name === "mongo") {
545
634
  const mongoConfig = config;
546
635
  if (mongoConfig.database) env.MONGO_INITDB_DATABASE = mongoConfig.database;
547
636
  if (mongoConfig.user) env.MONGO_INITDB_ROOT_USERNAME = mongoConfig.user;
548
637
  if (mongoConfig.password) env.MONGO_INITDB_ROOT_PASSWORD = mongoConfig.password;
549
- if (!env.MONGO_INITDB_DATABASE) env.MONGO_INITDB_DATABASE = projectName;
638
+ if (!mongoConfig.database && !config.env?.MONGO_INITDB_DATABASE) env.MONGO_INITDB_DATABASE = projectName;
550
639
  } else if (name === "redis") {
551
640
  const redisConfig = config;
552
641
  if (redisConfig.password) env.REDIS_PASSWORD = redisConfig.password;
642
+ if (env.REDIS_PASSWORD) {
643
+ env.REDISCLI_AUTH = env.REDIS_PASSWORD;
644
+ command ??= REDIS_AUTH_COMMAND;
645
+ }
553
646
  }
554
647
  const volumes = [...definition.volumes ?? [], ...config.volumes ?? []];
555
648
  const resolvedConfig = {
@@ -559,7 +652,7 @@ async function resolveServiceConfig(name, config, projectName) {
559
652
  hostPort,
560
653
  env,
561
654
  volumes,
562
- command: config.command,
655
+ command,
563
656
  healthcheck: definition.healthcheck,
564
657
  ports: definition.ports
565
658
  };
@@ -569,53 +662,53 @@ async function resolveServiceConfig(name, config, projectName) {
569
662
  return resolvedConfig;
570
663
  }
571
664
  async function resolveCustomService(name, config) {
572
- const imageMatch = config.image.match(/:(\d+)$/);
573
- const defaultPort = imageMatch && imageMatch[1] ? parseInt(imageMatch[1], 10) : 80;
574
- let port = defaultPort;
575
- let hostPort;
576
- if (config.port === "auto") {
577
- port = await resolvePort({ preferred: defaultPort, strategy: "auto" });
578
- hostPort = port;
579
- } else if (typeof config.port === "number") {
580
- port = config.port;
581
- hostPort = config.port;
582
- } else if (config.port && typeof config.port === "object") {
583
- const { start, end } = config.port;
584
- const startPort = start ?? defaultPort;
585
- const endPort = end ?? startPort + 100;
586
- port = await resolvePort({ preferred: startPort, strategy: "range", range: [startPort, endPort] });
587
- hostPort = port;
665
+ let containerPort = 80;
666
+ if (typeof config.port === "number") {
667
+ containerPort = config.port;
668
+ } else if (config.port && typeof config.port === "object" && config.port.start) {
669
+ containerPort = config.port.start;
588
670
  }
671
+ const { port, hostPort } = await resolveServicePorts(config.port, containerPort);
589
672
  return {
590
673
  name,
591
674
  image: config.image,
592
675
  port,
593
676
  hostPort,
594
- env: config.env ?? {},
595
- volumes: config.volumes ?? [],
677
+ env: { ...config.env },
678
+ volumes: [...config.volumes ?? []],
596
679
  command: config.command,
597
- healthcheck: config.command,
680
+ healthcheck: config.healthcheck,
598
681
  ports: []
599
682
  };
600
683
  }
684
+ function pluginServiceDefinitions(plugins) {
685
+ const definitions = /* @__PURE__ */ new Map();
686
+ for (const plugin of plugins ?? []) {
687
+ for (const [name, def] of Object.entries(plugin.services ?? {})) {
688
+ definitions.set(name, { ...def, name });
689
+ }
690
+ }
691
+ return definitions;
692
+ }
601
693
  async function resolveConfig(config) {
602
694
  let finalConfig = config;
603
695
  if (config.preset) {
604
696
  finalConfig = mergePreset(config, config.preset);
605
697
  }
606
698
  finalConfig = normalizeConfig(finalConfig);
607
- const appPort = finalConfig.app.port === "auto" ? await resolvePort({ preferred: 3e3, strategy: "auto" }) : finalConfig.app.port;
608
- const app = normalizeAppConfig({ ...finalConfig.app, port: appPort });
699
+ const appConfig = finalConfig.app ?? {};
700
+ const appPort = appConfig.port === "auto" ? await resolvePort({ preferred: 3e3, strategy: "auto" }) : appConfig.port;
701
+ const app = normalizeAppConfig({ ...appConfig, port: appPort });
702
+ const definitions = pluginServiceDefinitions(finalConfig.plugins);
609
703
  const services2 = {};
610
- if (finalConfig.services) {
611
- for (const [name, serviceConfig] of Object.entries(finalConfig.services)) {
612
- if (serviceConfig) {
613
- services2[name] = await resolveServiceConfig(
614
- name,
615
- serviceConfig,
616
- finalConfig.name
617
- );
618
- }
704
+ for (const [name, serviceConfig] of Object.entries(finalConfig.services ?? {})) {
705
+ if (serviceConfig) {
706
+ services2[name] = await resolveServiceConfig(
707
+ name,
708
+ serviceConfig,
709
+ finalConfig.name,
710
+ definitions
711
+ );
619
712
  }
620
713
  }
621
714
  return {
@@ -638,31 +731,73 @@ function isEnvVarName(value) {
638
731
  }
639
732
  function isVersion(value) {
640
733
  if (typeof value !== "string") return false;
641
- if (value.length === 0) return false;
642
- return /^[a-zA-Z0-9.\-]+$/.test(value);
734
+ return /^\w[\w.-]{0,127}$/.test(value);
643
735
  }
644
736
  function isProjectName(value) {
645
737
  if (typeof value !== "string") return false;
646
738
  if (value.length === 0 || value.length > 100) return false;
647
739
  return /^[a-zA-Z][a-zA-Z0-9_-]*$/.test(value);
648
740
  }
741
+ function isComposeServiceName(value) {
742
+ if (typeof value !== "string") return false;
743
+ return /^[a-zA-Z0-9][\w.-]{0,62}$/.test(value);
744
+ }
745
+ var DOMAIN_COMPONENT = "(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9])";
746
+ var DOMAIN = `${DOMAIN_COMPONENT}(?:\\.${DOMAIN_COMPONENT})*(?::[0-9]+)?`;
747
+ var PATH_COMPONENT = "[a-z0-9]+(?:(?:[._]|__|[-]+)[a-z0-9]+)*";
748
+ var TAG = "\\w[\\w.-]{0,127}";
749
+ var DIGEST = "[A-Za-z][A-Za-z0-9]*(?:[-_+.][A-Za-z][A-Za-z0-9]*)*:[0-9a-fA-F]{32,}";
750
+ var IMAGE_REFERENCE = new RegExp(
751
+ `^(?:${DOMAIN}/)?${PATH_COMPONENT}(?:/${PATH_COMPONENT})*(?::${TAG})?(?:@${DIGEST})?$`
752
+ );
753
+ function isDockerImage(value) {
754
+ if (typeof value !== "string") return false;
755
+ if (value.length === 0 || value.length > 255) return false;
756
+ return IMAGE_REFERENCE.test(value);
757
+ }
758
+ function isHealthcheckPath(value) {
759
+ if (typeof value !== "string") return false;
760
+ return value.length <= 2048 && /^\/[\w\-.~%/?=&+,;:@]*$/.test(value);
761
+ }
762
+ function isSingleLine(value) {
763
+ return typeof value === "string" && !/[\r\n\0]/.test(value);
764
+ }
765
+ function isContainerPath(value) {
766
+ return typeof value === "string" && /^\/[\w./-]*$/.test(value);
767
+ }
768
+ function namedVolume(spec) {
769
+ const index = spec.indexOf(":");
770
+ if (index <= 0) return void 0;
771
+ const source = spec.slice(0, index);
772
+ return /^[a-zA-Z0-9][\w.-]*$/.test(source) ? source : void 0;
773
+ }
649
774
 
650
775
  // src/core/validator.ts
776
+ var VALID_OUTPUT_FILES = ["dockerfile", "compose", "dockerignore", "env", "scripts", "makefile"];
651
777
  function validateProjectName(name) {
652
- const errors = [];
653
- if (!isProjectName(name)) {
654
- errors.push({
655
- code: "INVALID_NAME",
656
- message: `Invalid project name '${name}'. Must start with a letter and contain only letters, numbers, hyphens, and underscores.`,
657
- path: "name",
658
- value: name
659
- });
660
- }
661
- return errors;
778
+ if (isProjectName(name)) return [];
779
+ return [{
780
+ code: "INVALID_NAME",
781
+ message: `Invalid project name '${String(name)}'. Must start with a letter and contain only letters, numbers, hyphens, and underscores.`,
782
+ path: "name",
783
+ value: name
784
+ }];
785
+ }
786
+ function validateStringList(value, path) {
787
+ if (value === void 0) return [];
788
+ if (!Array.isArray(value)) {
789
+ return [{ code: "INVALID_TYPE", message: `'${path}' must be an array of strings.`, path, value }];
790
+ }
791
+ return value.filter((item) => !isSingleLine(item) || item === "").map((item) => ({
792
+ code: "INVALID_VALUE",
793
+ message: `Invalid entry ${JSON.stringify(item)} in '${path}'. Entries must be non-empty single-line strings.`,
794
+ path,
795
+ value: item
796
+ }));
662
797
  }
663
798
  function validateAppConfig(config) {
664
799
  const errors = [];
665
- if (config.port !== "auto" && !isPort(config.port)) {
800
+ if (config.port !== void 0 && config.port !== "auto" && !isPort(config.port)) {
666
801
  errors.push({
667
802
  code: "INVALID_PORT",
668
803
  message: `Invalid app port '${String(config.port)}'. Must be a number between 1-65535 or 'auto'.`,
@@ -673,54 +808,163 @@ function validateAppConfig(config) {
673
808
  if (config.node !== void 0 && !isVersion(config.node)) {
674
809
  errors.push({
675
810
  code: "INVALID_VERSION",
676
- message: `Invalid Node.js version '${config.node}'.`,
811
+ message: `Invalid Node.js version '${String(config.node)}'. Must be a valid Docker image tag.`,
677
812
  path: "app.node",
678
813
  value: config.node
679
814
  });
680
815
  }
681
- if (config.env) {
682
- for (const envVar of config.env) {
683
- if (!isEnvVarName(envVar)) {
684
- errors.push({
685
- code: "INVALID_ENV_VAR",
686
- message: `Invalid environment variable name '${envVar}'. Must be uppercase letters, numbers, and underscores.`,
687
- path: "app.env",
688
- value: envVar
689
- });
816
+ if (config.workdir !== void 0 && !isContainerPath(config.workdir)) {
817
+ errors.push({
818
+ code: "INVALID_WORKDIR",
819
+ message: `Invalid workdir '${String(config.workdir)}'. Must be an absolute path made of letters, numbers, '.', '_', '-' and '/'.`,
820
+ path: "app.workdir",
821
+ value: config.workdir
822
+ });
823
+ }
824
+ for (const key of ["command", "buildCommand"]) {
825
+ const value = config[key];
826
+ if (value !== void 0 && !isSingleLine(value)) {
827
+ errors.push({
828
+ code: "INVALID_COMMAND",
829
+ message: `Invalid app.${key}: must be a single-line string.`,
830
+ path: `app.${key}`,
831
+ value
832
+ });
833
+ }
834
+ }
835
+ if (config.command !== void 0 && config.command.trim() === "") {
836
+ errors.push({
837
+ code: "INVALID_COMMAND",
838
+ message: "Invalid app.command: must not be empty.",
839
+ path: "app.command",
840
+ value: config.command
841
+ });
842
+ }
843
+ if (config.healthcheck !== void 0 && !isHealthcheckPath(config.healthcheck)) {
844
+ errors.push({
845
+ code: "INVALID_HEALTHCHECK",
846
+ message: `Invalid health check path '${String(config.healthcheck)}'. Must start with '/' and contain only URL path characters (no quotes, spaces, '$' or backslashes).`,
847
+ path: "app.healthcheck",
848
+ value: config.healthcheck
849
+ });
850
+ }
851
+ if (config.env !== void 0) {
852
+ if (!Array.isArray(config.env)) {
853
+ errors.push({ code: "INVALID_TYPE", message: `'app.env' must be an array of variable names.`, path: "app.env", value: config.env });
854
+ } else {
855
+ for (const envVar of config.env) {
856
+ if (!isEnvVarName(envVar)) {
857
+ errors.push({
858
+ code: "INVALID_ENV_VAR",
859
+ message: `Invalid environment variable name '${String(envVar)}'. Must be uppercase letters, numbers, and underscores.`,
860
+ path: "app.env",
861
+ value: envVar
862
+ });
863
+ }
690
864
  }
691
865
  }
692
866
  }
867
+ errors.push(...validateStringList(config.volumes, "app.volumes"));
693
868
  return errors;
694
869
  }
870
+ function validateServicePort(name, port) {
871
+ if (port === void 0 || port === "auto" || isPort(port)) return [];
872
+ if (port && typeof port === "object" && !Array.isArray(port)) {
873
+ const { start, end } = port;
874
+ if (isPort(start) && (end === void 0 || isPort(end) && end >= start)) {
875
+ return [];
876
+ }
877
+ }
878
+ return [{
879
+ code: "INVALID_PORT",
880
+ message: `Invalid port configuration for service '${name}'. Must be a port number (1-65535), 'auto', or a range { start, end } with start <= end.`,
881
+ path: `services.${name}.port`,
882
+ value: port
883
+ }];
884
+ }
695
885
  function validateServiceConfig(name, config) {
696
886
  const errors = [];
697
- if (config.version !== void 0 && !isVersion(config.version)) {
887
+ if (!isComposeServiceName(name)) {
888
+ errors.push({
889
+ code: "INVALID_SERVICE_NAME",
890
+ message: `Invalid service name '${name}'. Must start with a letter or digit and contain only letters, digits, '.', '_' and '-'.`,
891
+ path: `services.${name}`,
892
+ value: name
893
+ });
894
+ }
895
+ if (typeof config !== "object" || config === null || Array.isArray(config)) {
896
+ errors.push({
897
+ code: "INVALID_TYPE",
898
+ message: `Service '${name}' must be configured with an object.`,
899
+ path: `services.${name}`,
900
+ value: config
901
+ });
902
+ return errors;
903
+ }
904
+ const svc = config;
905
+ if (svc.version !== void 0 && !isVersion(svc.version)) {
698
906
  errors.push({
699
907
  code: "INVALID_VERSION",
700
- message: `Invalid version '${config.version}' for service '${name}'.`,
908
+ message: `Invalid version '${String(svc.version)}' for service '${name}'. Must be a valid Docker image tag.`,
701
909
  path: `services.${name}.version`,
702
- value: config.version
910
+ value: svc.version
703
911
  });
704
912
  }
705
- if (config.port !== void 0 && config.port !== "auto" && typeof config.port !== "number" && typeof config.port !== "object") {
913
+ if (svc.image !== void 0 && !isDockerImage(svc.image)) {
706
914
  errors.push({
707
- code: "INVALID_PORT",
708
- message: `Invalid port configuration for service '${name}'. Must be a number, 'auto', or a range object.`,
709
- path: `services.${name}.port`,
710
- value: config.port
915
+ code: "INVALID_IMAGE",
916
+ message: `Invalid image '${String(svc.image)}' for service '${name}'. Must be a Docker image reference such as 'elasticsearch:8.11.0'.`,
917
+ path: `services.${name}.image`,
918
+ value: svc.image
711
919
  });
712
920
  }
921
+ errors.push(...validateServicePort(name, svc.port));
922
+ if (svc.env !== void 0) {
923
+ if (typeof svc.env !== "object" || svc.env === null || Array.isArray(svc.env)) {
924
+ errors.push({ code: "INVALID_TYPE", message: `'services.${name}.env' must be an object of strings.`, path: `services.${name}.env`, value: svc.env });
925
+ } else {
926
+ for (const [key, value] of Object.entries(svc.env)) {
927
+ if (key === "" || /[=\s]/.test(key) || typeof value !== "string") {
928
+ errors.push({
929
+ code: "INVALID_ENV_VAR",
930
+ message: `Invalid environment variable '${key}' for service '${name}'. Names must not be empty or contain '=' or whitespace, and values must be strings.`,
931
+ path: `services.${name}.env.${key}`,
932
+ value
933
+ });
934
+ }
935
+ }
936
+ }
937
+ }
938
+ for (const key of ["user", "password", "database", "rootPassword", "command", "healthcheck"]) {
939
+ const value = svc[key];
940
+ if (value !== void 0 && typeof value !== "string") {
941
+ errors.push({
942
+ code: "INVALID_TYPE",
943
+ message: `'services.${name}.${key}' must be a string.`,
944
+ path: `services.${name}.${key}`,
945
+ value
946
+ });
947
+ }
948
+ }
949
+ errors.push(...validateStringList(svc.volumes, `services.${name}.volumes`));
713
950
  return errors;
714
951
  }
715
952
  function validateOutputConfig(config) {
716
953
  const errors = [];
717
- if (config?.files) {
718
- const validFiles = ["dockerfile", "compose", "dockerignore", "env", "scripts", "makefile"];
954
+ if (config.dir !== void 0 && (typeof config.dir !== "string" || config.dir === "" || config.dir.includes("\0"))) {
955
+ errors.push({
956
+ code: "INVALID_OUTPUT_DIR",
957
+ message: "output.dir must be a non-empty path.",
958
+ path: "output.dir",
959
+ value: config.dir
960
+ });
961
+ }
962
+ if (config.files) {
719
963
  for (const file of config.files) {
720
- if (!validFiles.includes(file)) {
964
+ if (!VALID_OUTPUT_FILES.includes(file)) {
721
965
  errors.push({
722
966
  code: "INVALID_OUTPUT_FILE",
723
- message: `Invalid output file '${file}'. Must be one of: ${validFiles.join(", ")}.`,
967
+ message: `Invalid output file '${String(file)}'. Must be one of: ${VALID_OUTPUT_FILES.join(", ")}.`,
724
968
  path: "output.files",
725
969
  value: file
726
970
  });
@@ -731,13 +975,19 @@ function validateOutputConfig(config) {
731
975
  }
732
976
  function validateConfig(config) {
733
977
  const errors = [];
978
+ if (typeof config !== "object" || config === null) {
979
+ return {
980
+ valid: false,
981
+ errors: [{ code: "INVALID_CONFIG", message: "Configuration must be an object.", value: config }]
982
+ };
983
+ }
734
984
  errors.push(...validateProjectName(config.name));
735
985
  if (config.app) {
736
986
  errors.push(...validateAppConfig(config.app));
737
987
  }
738
988
  if (config.services) {
739
989
  for (const [name, serviceConfig] of Object.entries(config.services)) {
740
- if (serviceConfig) {
990
+ if (serviceConfig !== void 0) {
741
991
  errors.push(...validateServiceConfig(name, serviceConfig));
742
992
  }
743
993
  }
@@ -752,18 +1002,23 @@ function validateConfig(config) {
752
1002
  }
753
1003
  function validateResolvedConfig(config) {
754
1004
  const errors = [];
755
- const usedPorts = /* @__PURE__ */ new Set();
756
- usedPorts.add(config.app.port);
1005
+ const usedPorts = /* @__PURE__ */ new Map();
1006
+ usedPorts.set(config.app.port, "app");
757
1007
  for (const [serviceName, serviceConfig] of Object.entries(config.services)) {
758
- if (usedPorts.has(serviceConfig.port)) {
759
- errors.push({
760
- code: "PORT_CONFLICT",
761
- message: `Port ${serviceConfig.port} is already in use by ${serviceName}.`,
762
- path: `services.${serviceName}.port`,
763
- value: serviceConfig.port
764
- });
1008
+ const published = [serviceConfig.hostPort ?? serviceConfig.port, ...serviceConfig.ports ?? []];
1009
+ for (const port of published) {
1010
+ const owner = usedPorts.get(port);
1011
+ if (owner !== void 0) {
1012
+ errors.push({
1013
+ code: "PORT_CONFLICT",
1014
+ message: `Host port ${port} of service '${serviceName}' is already published by '${owner}'.`,
1015
+ path: `services.${serviceName}.port`,
1016
+ value: port
1017
+ });
1018
+ } else {
1019
+ usedPorts.set(port, serviceName);
1020
+ }
765
1021
  }
766
- usedPorts.add(serviceConfig.port);
767
1022
  }
768
1023
  return {
769
1024
  valid: errors.length === 0,
@@ -771,11 +1026,24 @@ function validateResolvedConfig(config) {
771
1026
  };
772
1027
  }
773
1028
 
1029
+ // src/generators/healthcheck.ts
1030
+ function nodeHealthcheckScript(port, path) {
1031
+ return `require('http').get('http://localhost:${port}${path}', (r) => process.exit(r.statusCode >= 200 && r.statusCode < 300 ? 0 : 1)).on('error', () => process.exit(1)).setTimeout(2000, () => process.exit(1))`;
1032
+ }
1033
+
774
1034
  // src/generators/dockerfile.ts
1035
+ function dockerCmd(command) {
1036
+ const words = command.trim().split(/\s+/);
1037
+ if (words.every((word) => /^[\w@%+=:,./-]+$/.test(word))) {
1038
+ return `CMD ${JSON.stringify(words).replace(/","/g, '", "')}`;
1039
+ }
1040
+ return `CMD ${command.trim()}`;
1041
+ }
775
1042
  function generateDockerfile(config, _context) {
776
- const { app, name } = config;
1043
+ const { app } = config;
777
1044
  const { node, workdir, command, buildCommand, multiStage, healthcheck } = app;
778
1045
  const port = app.port;
1046
+ const hasBuild = buildCommand.trim() !== "";
779
1047
  let dockerfile = "";
780
1048
  if (multiStage) {
781
1049
  dockerfile += `# Builder stage
@@ -801,11 +1069,13 @@ function generateDockerfile(config, _context) {
801
1069
  dockerfile += `COPY . .
802
1070
 
803
1071
  `;
804
- dockerfile += `# Build application
1072
+ if (hasBuild) {
1073
+ dockerfile += `# Build application
805
1074
  `;
806
- dockerfile += `RUN npm run build 2>/dev/null || true
1075
+ dockerfile += `RUN ${buildCommand.trim()}
807
1076
 
808
1077
  `;
1078
+ }
809
1079
  dockerfile += `# Production stage
810
1080
  `;
811
1081
  dockerfile += `FROM node:${node}
@@ -819,13 +1089,19 @@ function generateDockerfile(config, _context) {
819
1089
  `;
820
1090
  dockerfile += `# Copy from builder
821
1091
  `;
822
- dockerfile += `COPY --from=builder ${workdir}/node_modules ./node_modules
1092
+ if (hasBuild) {
1093
+ dockerfile += `COPY --from=builder ${workdir}/node_modules ./node_modules
1094
+ `;
1095
+ dockerfile += `COPY --from=builder ${workdir}/dist ./dist
823
1096
  `;
824
- dockerfile += `COPY --from=builder ${workdir}/dist ./dist
1097
+ dockerfile += `COPY --from=builder ${workdir}/package*.json ./
1098
+
825
1099
  `;
826
- dockerfile += `COPY --from=builder ${workdir}/package*.json ./
1100
+ } else {
1101
+ dockerfile += `COPY --from=builder ${workdir} ./
827
1102
 
828
1103
  `;
1104
+ }
829
1105
  } else {
830
1106
  dockerfile += `FROM node:${node}
831
1107
 
@@ -856,180 +1132,232 @@ function generateDockerfile(config, _context) {
856
1132
 
857
1133
  `;
858
1134
  if (healthcheck) {
1135
+ const script = JSON.stringify(nodeHealthcheckScript(port, healthcheck));
859
1136
  dockerfile += `HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \\
860
- CMD node -e "require('http').get('http://localhost:${port}${healthcheck}', (r) => {process.exit(r.statusCode === 200 ? 0 : 1)})" || exit 1
1137
+ `;
1138
+ dockerfile += ` CMD ["node", "-e", ${script}]
861
1139
 
862
1140
  `;
863
1141
  }
864
- dockerfile += `CMD ["npm", "start"]
1142
+ dockerfile += `${dockerCmd(command)}
865
1143
  `;
866
1144
  return dockerfile;
867
1145
  }
868
1146
 
869
1147
  // src/utils/yaml.ts
1148
+ var PLAIN_SCALAR = /^[A-Za-z_/.][\w./=@+~-]*$/;
1149
+ var NUMBER_LIKE = /^\.(?:\d|inf$|nan$)/i;
1150
+ var DURATION = /^\d+(?:\.\d+)?(?:ns|us|ms|s|m|h)$/;
1151
+ var RESERVED_WORD = /^(?:y|n|yes|no|on|off|true|false|null)$/i;
870
1152
  function toYaml(obj, indent = 0) {
871
- const spaces = " ".repeat(indent);
872
- if (obj === null) {
1153
+ if (isInline(obj)) {
1154
+ return inlineValue(obj);
1155
+ }
1156
+ if (Array.isArray(obj)) {
1157
+ return arrayToYaml(obj, indent);
1158
+ }
1159
+ return objectToYaml(obj, indent);
1160
+ }
1161
+ function isInline(value) {
1162
+ if (value === null || typeof value !== "object") {
1163
+ return true;
1164
+ }
1165
+ if (Array.isArray(value)) {
1166
+ return value.every((item) => item === null || item === void 0 || typeof item !== "object");
1167
+ }
1168
+ return Object.values(value).every((item) => item === void 0);
1169
+ }
1170
+ function inlineValue(value) {
1171
+ if (value === null || value === void 0) {
873
1172
  return "null";
874
1173
  }
875
- if (typeof obj === "string") {
876
- return quoteStringIfNeeded(obj);
1174
+ if (typeof value === "string") {
1175
+ return yamlScalar(value);
877
1176
  }
878
- if (typeof obj === "number" || typeof obj === "boolean") {
879
- return String(obj);
1177
+ if (typeof value === "number") {
1178
+ if (Number.isFinite(value)) return String(value);
1179
+ if (Number.isNaN(value)) return ".nan";
1180
+ return value > 0 ? ".inf" : "-.inf";
880
1181
  }
881
- if (Array.isArray(obj)) {
882
- return arrayToYaml(obj, indent);
1182
+ if (typeof value === "boolean") {
1183
+ return String(value);
883
1184
  }
884
- if (typeof obj === "object") {
885
- return objectToYaml(obj, indent);
1185
+ if (Array.isArray(value)) {
1186
+ return `[${value.map((item) => inlineValue(item)).join(", ")}]`;
886
1187
  }
887
- return String(obj);
1188
+ if (typeof value === "object") {
1189
+ return "{}";
1190
+ }
1191
+ return JSON.stringify(String(value));
888
1192
  }
889
1193
  function arrayToYaml(arr, indent) {
890
1194
  const spaces = " ".repeat(indent);
891
- const innerSpaces = " ".repeat(indent + 2);
892
- if (arr.length === 0) {
893
- return "[]";
894
- }
895
- if (arr.every(
896
- (item) => typeof item === "string" || typeof item === "number" || typeof item === "boolean" || item === null
897
- )) {
898
- const items = arr.map((item) => toYaml(item, 0)).join(", ");
899
- return `[${items}]`;
900
- }
901
1195
  const lines = [];
902
1196
  for (const item of arr) {
903
- const value = toYaml(item, indent + 2);
904
- if (value.includes("\n")) {
905
- lines.push(`${spaces}- ${value.slice(indent + 2)}`);
1197
+ if (isInline(item)) {
1198
+ lines.push(`${spaces}- ${inlineValue(item)}`);
906
1199
  } else {
907
- lines.push(`${spaces}- ${value}`);
1200
+ const block = toYaml(item, indent + 2);
1201
+ lines.push(`${spaces}- ${block.slice(indent + 2)}`);
908
1202
  }
909
1203
  }
910
1204
  return lines.join("\n");
911
1205
  }
912
1206
  function objectToYaml(obj, indent) {
913
- const keys = Object.keys(obj);
914
- if (keys.length === 0) {
915
- return "{}";
916
- }
917
1207
  const spaces = " ".repeat(indent);
918
1208
  const lines = [];
919
- for (const key of keys) {
920
- const value = obj[key];
921
- const valueStr = toYaml(value, indent + 2);
922
- if (valueStr.includes("\n")) {
923
- lines.push(`${spaces}${key}:`);
924
- lines.push(valueStr);
1209
+ for (const [key, value] of Object.entries(obj)) {
1210
+ if (value === void 0) continue;
1211
+ const yamlKey = yamlScalar(key);
1212
+ if (isInline(value)) {
1213
+ lines.push(`${spaces}${yamlKey}: ${inlineValue(value)}`);
925
1214
  } else {
926
- lines.push(`${spaces}${key}: ${valueStr}`);
1215
+ lines.push(`${spaces}${yamlKey}:`);
1216
+ lines.push(toYaml(value, indent + 2));
927
1217
  }
928
1218
  }
929
1219
  return lines.join("\n");
930
1220
  }
931
- function quoteStringIfNeeded(str) {
932
- if (str === "" || str.startsWith('"') || str.startsWith("'")) {
933
- return `"${escapeString(str)}"`;
934
- }
935
- if (/^[\-\?:\[\]{},&*#|!<>@%'"`]/.test(str)) {
936
- return `"${escapeString(str)}"`;
1221
+ function yamlScalar(str) {
1222
+ if ((PLAIN_SCALAR.test(str) || DURATION.test(str)) && !RESERVED_WORD.test(str) && !NUMBER_LIKE.test(str)) {
1223
+ return str;
937
1224
  }
938
- if (/[:\s#]/.test(str)) {
939
- return `"${escapeString(str)}"`;
1225
+ return JSON.stringify(str);
1226
+ }
1227
+
1228
+ // src/generators/paths.ts
1229
+ import { isAbsolute, join, relative } from "path";
1230
+ function currentDir() {
1231
+ return typeof process !== "undefined" && typeof process.cwd === "function" ? process.cwd() : "/";
1232
+ }
1233
+ function outputSubdir(dir) {
1234
+ if (!dir) {
1235
+ return void 0;
940
1236
  }
941
- if (/^(true|false|null|NaN|Infinity|\-?\d+(\.\d+)?)$/.test(str)) {
942
- return `"${escapeString(str)}"`;
1237
+ const root = currentDir();
1238
+ const subdir = relative(root, isAbsolute(dir) ? dir : join(root, dir)).replace(/\\/g, "/");
1239
+ if (subdir === "" || subdir === ".." || subdir.startsWith("../") || isAbsolute(subdir)) {
1240
+ return void 0;
943
1241
  }
944
- return escapeString(str);
1242
+ return subdir;
945
1243
  }
946
- function escapeString(str) {
947
- return str.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t");
1244
+ function pathToRoot(subdir) {
1245
+ return subdir.split("/").map(() => "..").join("/");
948
1246
  }
949
1247
 
950
1248
  // src/generators/compose.ts
951
- function generateCompose(config, context) {
952
- const { name, app, services: services2 } = config;
953
- const compose = {
954
- version: "3.9",
955
- services: {
956
- app: {
957
- build: ".",
958
- ports: [`${app.port}:${app.port}`],
959
- environment: generateAppEnvironment(config, context),
960
- depends_on: Object.keys(services2),
961
- volumes: app.volumes.length > 0 ? app.volumes : void 0
962
- }
963
- },
964
- volumes: generateVolumeDefinitions(services2)
1249
+ function composeLiteral(value) {
1250
+ return value.replace(/\$/g, "$$$$");
1251
+ }
1252
+ function composeBuild(outputDir) {
1253
+ const subdir = outputSubdir(outputDir);
1254
+ if (subdir === void 0) {
1255
+ return ".";
1256
+ }
1257
+ return { context: pathToRoot(subdir), dockerfile: `${subdir}/Dockerfile` };
1258
+ }
1259
+ function generateCompose(config, _context) {
1260
+ const { app, services: services2 } = config;
1261
+ const appService = {
1262
+ build: composeBuild(config.output.dir),
1263
+ ports: [`${app.port}:${app.port}`],
1264
+ environment: generateAppEnvironment(config),
1265
+ depends_on: Object.keys(services2),
1266
+ volumes: app.volumes.length > 0 ? app.volumes : void 0
965
1267
  };
966
- const servicesRecord = compose.services;
967
- if (app.healthcheck && servicesRecord.app) {
968
- servicesRecord.app.healthcheck = {
969
- test: [`CMD`, `curl`, `-f`, `http://localhost:${app.port}${app.healthcheck}`],
1268
+ if (app.healthcheck) {
1269
+ appService.healthcheck = {
1270
+ test: ["CMD", "node", "-e", nodeHealthcheckScript(app.port, app.healthcheck)],
970
1271
  interval: "30s",
971
1272
  timeout: "3s",
972
1273
  retries: 3
973
1274
  };
974
1275
  }
1276
+ const composeServices = { app: appService };
975
1277
  for (const [serviceName, serviceConfig] of Object.entries(services2)) {
976
- servicesRecord[serviceName] = generateServiceConfig(serviceName, serviceConfig);
1278
+ composeServices[serviceName] = generateServiceConfig(serviceConfig);
977
1279
  }
978
- return toYaml(compose);
1280
+ const compose = {
1281
+ services: composeServices,
1282
+ volumes: generateVolumeDefinitions(config)
1283
+ };
1284
+ return `${toYaml(compose)}
1285
+ `;
1286
+ }
1287
+ function connectionStringVar(serviceName) {
1288
+ return `${serviceName.toUpperCase().replace(/[^A-Z0-9_]/g, "_")}_URL`;
1289
+ }
1290
+ function hasDatabaseUrlAlias(config) {
1291
+ return config.services.postgres !== void 0 && !Object.entries(config.services).some(
1292
+ ([name, service]) => Boolean(service.connectionString) && connectionStringVar(name) === "DATABASE_URL"
1293
+ );
979
1294
  }
980
- function generateAppEnvironment(config, context) {
1295
+ function generateAppEnvironment(config) {
981
1296
  const env = ["NODE_ENV=production", `PORT=${config.app.port}`];
1297
+ const add = (key, value) => {
1298
+ env.push(`${key}=${composeLiteral(String(value))}`);
1299
+ };
982
1300
  for (const [serviceName, serviceConfig] of Object.entries(config.services)) {
983
1301
  if (serviceConfig.connectionString) {
984
- const key = `${serviceName.toUpperCase()}_URL`;
985
- env.push(`${key}=${serviceConfig.connectionString}`);
1302
+ add(connectionStringVar(serviceName), serviceConfig.connectionString);
986
1303
  }
987
1304
  }
988
1305
  if (config.services.postgres) {
989
1306
  const pg = config.services.postgres;
990
- env.push(`POSTGRES_HOST=${pg.name}`);
991
- env.push(`POSTGRES_PORT=${pg.port}`);
992
- env.push(`POSTGRES_USER=${pg.env.POSTGRES_USER || "postgres"}`);
993
- env.push(`POSTGRES_PASSWORD=${pg.env.POSTGRES_PASSWORD || "postgres"}`);
994
- env.push(`POSTGRES_DB=${pg.env.POSTGRES_DB || config.name}`);
1307
+ if (pg.connectionString && hasDatabaseUrlAlias(config)) {
1308
+ add("DATABASE_URL", pg.connectionString);
1309
+ }
1310
+ add("POSTGRES_HOST", pg.name);
1311
+ add("POSTGRES_PORT", pg.port);
1312
+ add("POSTGRES_USER", pg.env.POSTGRES_USER || "postgres");
1313
+ add("POSTGRES_PASSWORD", pg.env.POSTGRES_PASSWORD || "postgres");
1314
+ add("POSTGRES_DB", pg.env.POSTGRES_DB || config.name);
995
1315
  }
996
1316
  if (config.services.mysql) {
997
1317
  const mysql = config.services.mysql;
998
- env.push(`MYSQL_HOST=${mysql.name}`);
999
- env.push(`MYSQL_PORT=${mysql.port}`);
1000
- env.push(`MYSQL_USER=${mysql.env.MYSQL_USER || "root"}`);
1001
- env.push(`MYSQL_PASSWORD=${mysql.env.MYSQL_PASSWORD || mysql.env.MYSQL_ROOT_PASSWORD || "root"}`);
1002
- env.push(`MYSQL_DATABASE=${mysql.env.MYSQL_DATABASE || config.name}`);
1318
+ add("MYSQL_HOST", mysql.name);
1319
+ add("MYSQL_PORT", mysql.port);
1320
+ add("MYSQL_USER", mysql.env.MYSQL_USER || "root");
1321
+ add("MYSQL_PASSWORD", mysql.env.MYSQL_PASSWORD || mysql.env.MYSQL_ROOT_PASSWORD || "root");
1322
+ add("MYSQL_DATABASE", mysql.env.MYSQL_DATABASE || config.name);
1003
1323
  }
1004
1324
  if (config.services.mongo) {
1005
1325
  const mongo = config.services.mongo;
1006
- env.push(`MONGO_HOST=${mongo.name}`);
1007
- env.push(`MONGO_PORT=${mongo.port}`);
1008
- env.push(`MONGO_USER=${mongo.env.MONGO_INITDB_ROOT_USERNAME || "mongo"}`);
1009
- env.push(`MONGO_PASSWORD=${mongo.env.MONGO_INITDB_ROOT_PASSWORD || "mongo"}`);
1010
- env.push(`MONGO_DATABASE=${mongo.env.MONGO_INITDB_DATABASE || config.name}`);
1326
+ add("MONGO_HOST", mongo.name);
1327
+ add("MONGO_PORT", mongo.port);
1328
+ add("MONGO_USER", mongo.env.MONGO_INITDB_ROOT_USERNAME || "mongo");
1329
+ add("MONGO_PASSWORD", mongo.env.MONGO_INITDB_ROOT_PASSWORD || "mongo");
1330
+ add("MONGO_DATABASE", mongo.env.MONGO_INITDB_DATABASE || config.name);
1011
1331
  }
1012
1332
  if (config.services.redis) {
1013
1333
  const redis = config.services.redis;
1014
- env.push(`REDIS_HOST=${redis.name}`);
1015
- env.push(`REDIS_PORT=${redis.port}`);
1334
+ add("REDIS_HOST", redis.name);
1335
+ add("REDIS_PORT", redis.port);
1336
+ if (redis.env.REDIS_PASSWORD) {
1337
+ add("REDIS_PASSWORD", redis.env.REDIS_PASSWORD);
1338
+ }
1339
+ }
1340
+ for (const name of config.app.env) {
1341
+ if (!env.some((entry) => entry.startsWith(`${name}=`))) {
1342
+ env.push(name);
1343
+ }
1016
1344
  }
1017
1345
  return env;
1018
1346
  }
1019
- function generateServiceConfig(name, config) {
1347
+ function generateServiceConfig(config) {
1348
+ const environment = {};
1349
+ for (const [key, value] of Object.entries(config.env)) {
1350
+ environment[key] = composeLiteral(value);
1351
+ }
1352
+ const portMappings = [`${config.hostPort ?? config.port}:${config.port}`];
1353
+ for (const extraPort of config.ports ?? []) {
1354
+ portMappings.push(`${extraPort}:${extraPort}`);
1355
+ }
1020
1356
  const service = {
1021
1357
  image: config.image,
1022
- ports: [],
1023
- environment: config.env
1358
+ ports: portMappings,
1359
+ environment
1024
1360
  };
1025
- const portMappings = [];
1026
- portMappings.push(`${config.hostPort ?? config.port}:${config.port}`);
1027
- if (config.ports) {
1028
- for (const extraPort of config.ports) {
1029
- portMappings.push(`${extraPort}:${extraPort}`);
1030
- }
1031
- }
1032
- service.ports = portMappings;
1033
1361
  if (config.volumes.length > 0) {
1034
1362
  service.volumes = config.volumes;
1035
1363
  }
@@ -1046,23 +1374,35 @@ function generateServiceConfig(name, config) {
1046
1374
  }
1047
1375
  return service;
1048
1376
  }
1049
- function generateVolumeDefinitions(services2) {
1377
+ function generateVolumeDefinitions(config) {
1050
1378
  const volumes = {};
1051
- for (const serviceConfig of Object.values(services2)) {
1052
- for (const volume of serviceConfig.volumes) {
1053
- if (volume.includes(":")) {
1054
- const [name] = volume.split(":");
1055
- if (name) {
1056
- volumes[name] = null;
1057
- }
1058
- }
1379
+ const specs = [
1380
+ ...config.app.volumes,
1381
+ ...Object.values(config.services).flatMap((service) => service.volumes)
1382
+ ];
1383
+ for (const spec of specs) {
1384
+ const name = namedVolume(spec);
1385
+ if (name) {
1386
+ volumes[name] = {};
1059
1387
  }
1060
1388
  }
1061
1389
  return volumes;
1062
1390
  }
1063
1391
 
1064
1392
  // src/generators/dockerignore.ts
1065
- function generateDockerignore(_config) {
1393
+ var DOCKERFILE_IGNORE_FILE = "Dockerfile.dockerignore";
1394
+ function dockerignoreFileName(outputDir) {
1395
+ return outputSubdir(outputDir) === void 0 ? ".dockerignore" : DOCKERFILE_IGNORE_FILE;
1396
+ }
1397
+ function outputDirPatterns(outputDir) {
1398
+ const subdir = outputSubdir(outputDir);
1399
+ if (subdir === void 0) {
1400
+ return "";
1401
+ }
1402
+ return ["Dockerfile", "docker-compose.yml", DOCKERFILE_IGNORE_FILE, ".env", ".env.*"].map((file) => `${subdir}/${file}
1403
+ `).join("");
1404
+ }
1405
+ function generateDockerignore(config) {
1066
1406
  return `# Dependencies
1067
1407
  node_modules/
1068
1408
  npm-debug.log*
@@ -1070,10 +1410,10 @@ yarn-debug.log*
1070
1410
  yarn-error.log*
1071
1411
  pnpm-debug.log*
1072
1412
 
1073
- # Environment
1413
+ # Environment (secrets must never be copied into the image)
1074
1414
  .env
1075
- .env.local
1076
- .env.*.local
1415
+ .env.*
1416
+ !.env.example
1077
1417
 
1078
1418
  # Git
1079
1419
  .git/
@@ -1124,7 +1464,7 @@ temp/
1124
1464
  Dockerfile
1125
1465
  docker-compose.yml
1126
1466
  .dockerignore
1127
-
1467
+ ${outputDirPatterns(config.output.dir)}
1128
1468
  # Package manager lockfiles (optional - uncomment if you want to exclude)
1129
1469
  # package-lock.json
1130
1470
  # yarn.lock
@@ -1133,6 +1473,17 @@ docker-compose.yml
1133
1473
  }
1134
1474
 
1135
1475
  // src/generators/env.ts
1476
+ var BUILT_IN_SERVICES = /* @__PURE__ */ new Set(["postgres", "mysql", "mongo", "redis"]);
1477
+ function envValue(value) {
1478
+ if (/^[\w@%+=:,./?&-]*$/.test(value)) {
1479
+ return value;
1480
+ }
1481
+ if (!/['\r\n]/.test(value)) {
1482
+ return `'${value}'`;
1483
+ }
1484
+ const escaped = value.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n").replace(/\r/g, "\\r");
1485
+ return `"${escaped}"`;
1486
+ }
1136
1487
  function generateEnvExample(config) {
1137
1488
  let content = `# Application Configuration
1138
1489
  NODE_ENV=production
@@ -1152,17 +1503,21 @@ PORT=${config.app.port}
1152
1503
  content += `
1153
1504
  # PostgreSQL
1154
1505
  `;
1155
- content += `DATABASE_URL=${pg.connectionString || ""}
1506
+ if (hasDatabaseUrlAlias(config)) {
1507
+ content += `DATABASE_URL=${envValue(String(pg.connectionString || ""))}
1508
+ `;
1509
+ }
1510
+ content += `POSTGRES_URL=${envValue(String(pg.connectionString || ""))}
1156
1511
  `;
1157
- content += `POSTGRES_HOST=${pg.name}
1512
+ content += `POSTGRES_HOST=${envValue(String(pg.name))}
1158
1513
  `;
1159
- content += `POSTGRES_PORT=${pg.port}
1514
+ content += `POSTGRES_PORT=${envValue(String(pg.port))}
1160
1515
  `;
1161
- content += `POSTGRES_USER=${pg.env.POSTGRES_USER || "postgres"}
1516
+ content += `POSTGRES_USER=${envValue(String(pg.env.POSTGRES_USER || "postgres"))}
1162
1517
  `;
1163
- content += `POSTGRES_PASSWORD=${pg.env.POSTGRES_PASSWORD || "postgres"}
1518
+ content += `POSTGRES_PASSWORD=${envValue(String(pg.env.POSTGRES_PASSWORD || "postgres"))}
1164
1519
  `;
1165
- content += `POSTGRES_DB=${pg.env.POSTGRES_DB || config.name}
1520
+ content += `POSTGRES_DB=${envValue(String(pg.env.POSTGRES_DB || config.name))}
1166
1521
  `;
1167
1522
  }
1168
1523
  if (config.services.mysql) {
@@ -1170,17 +1525,17 @@ PORT=${config.app.port}
1170
1525
  content += `
1171
1526
  # MySQL
1172
1527
  `;
1173
- content += `MYSQL_URL=${mysql.connectionString || ""}
1528
+ content += `MYSQL_URL=${envValue(String(mysql.connectionString || ""))}
1174
1529
  `;
1175
- content += `MYSQL_HOST=${mysql.name}
1530
+ content += `MYSQL_HOST=${envValue(String(mysql.name))}
1176
1531
  `;
1177
- content += `MYSQL_PORT=${mysql.port}
1532
+ content += `MYSQL_PORT=${envValue(String(mysql.port))}
1178
1533
  `;
1179
- content += `MYSQL_USER=${mysql.env.MYSQL_USER || "root"}
1534
+ content += `MYSQL_USER=${envValue(String(mysql.env.MYSQL_USER || "root"))}
1180
1535
  `;
1181
- content += `MYSQL_PASSWORD=${mysql.env.MYSQL_PASSWORD || mysql.env.MYSQL_ROOT_PASSWORD || "root"}
1536
+ content += `MYSQL_PASSWORD=${envValue(String(mysql.env.MYSQL_PASSWORD || mysql.env.MYSQL_ROOT_PASSWORD || "root"))}
1182
1537
  `;
1183
- content += `MYSQL_DATABASE=${mysql.env.MYSQL_DATABASE || config.name}
1538
+ content += `MYSQL_DATABASE=${envValue(String(mysql.env.MYSQL_DATABASE || config.name))}
1184
1539
  `;
1185
1540
  }
1186
1541
  if (config.services.mongo) {
@@ -1188,17 +1543,17 @@ PORT=${config.app.port}
1188
1543
  content += `
1189
1544
  # MongoDB
1190
1545
  `;
1191
- content += `MONGO_URL=${mongo.connectionString || ""}
1546
+ content += `MONGO_URL=${envValue(String(mongo.connectionString || ""))}
1192
1547
  `;
1193
- content += `MONGO_HOST=${mongo.name}
1548
+ content += `MONGO_HOST=${envValue(String(mongo.name))}
1194
1549
  `;
1195
- content += `MONGO_PORT=${mongo.port}
1550
+ content += `MONGO_PORT=${envValue(String(mongo.port))}
1196
1551
  `;
1197
- content += `MONGO_USER=${mongo.env.MONGO_INITDB_ROOT_USERNAME || "mongo"}
1552
+ content += `MONGO_USER=${envValue(String(mongo.env.MONGO_INITDB_ROOT_USERNAME || "mongo"))}
1198
1553
  `;
1199
- content += `MONGO_PASSWORD=${mongo.env.MONGO_INITDB_ROOT_PASSWORD || "mongo"}
1554
+ content += `MONGO_PASSWORD=${envValue(String(mongo.env.MONGO_INITDB_ROOT_PASSWORD || "mongo"))}
1200
1555
  `;
1201
- content += `MONGO_DATABASE=${mongo.env.MONGO_INITDB_DATABASE || config.name}
1556
+ content += `MONGO_DATABASE=${envValue(String(mongo.env.MONGO_INITDB_DATABASE || config.name))}
1202
1557
  `;
1203
1558
  }
1204
1559
  if (config.services.redis) {
@@ -1206,14 +1561,23 @@ PORT=${config.app.port}
1206
1561
  content += `
1207
1562
  # Redis
1208
1563
  `;
1209
- content += `REDIS_URL=${redis.connectionString || ""}
1564
+ content += `REDIS_URL=${envValue(String(redis.connectionString || ""))}
1210
1565
  `;
1211
- content += `REDIS_HOST=${redis.name}
1566
+ content += `REDIS_HOST=${envValue(String(redis.name))}
1212
1567
  `;
1213
- content += `REDIS_PORT=${redis.port}
1568
+ content += `REDIS_PORT=${envValue(String(redis.port))}
1214
1569
  `;
1215
1570
  if (redis.env.REDIS_PASSWORD) {
1216
- content += `REDIS_PASSWORD=${redis.env.REDIS_PASSWORD}
1571
+ content += `REDIS_PASSWORD=${envValue(String(redis.env.REDIS_PASSWORD))}
1572
+ `;
1573
+ }
1574
+ }
1575
+ for (const [serviceName, service] of Object.entries(config.services)) {
1576
+ if (!BUILT_IN_SERVICES.has(serviceName) && service.connectionString) {
1577
+ content += `
1578
+ # ${serviceName}
1579
+ `;
1580
+ content += `${connectionStringVar(serviceName)}=${envValue(service.connectionString)}
1217
1581
  `;
1218
1582
  }
1219
1583
  }
@@ -1228,7 +1592,7 @@ function generateBuildScript(_config) {
1228
1592
  set -e
1229
1593
 
1230
1594
  echo "Building Docker image..."
1231
- docker-compose build
1595
+ docker compose build
1232
1596
 
1233
1597
  echo "Build complete!"
1234
1598
  `;
@@ -1241,7 +1605,7 @@ function generateUpScript(config) {
1241
1605
  set -e
1242
1606
 
1243
1607
  echo "Starting services..."
1244
- docker-compose up -d ${services2.join(" ")}
1608
+ docker compose up -d ${services2.join(" ")}
1245
1609
 
1246
1610
  echo "Services started!"
1247
1611
  echo ""
@@ -1255,7 +1619,7 @@ function generateDownScript(_config) {
1255
1619
  set -e
1256
1620
 
1257
1621
  echo "Stopping services..."
1258
- docker-compose down
1622
+ docker compose down
1259
1623
 
1260
1624
  echo "Services stopped!"
1261
1625
  `;
@@ -1267,9 +1631,9 @@ function generateLogsScript(_config) {
1267
1631
  set -e
1268
1632
 
1269
1633
  if [ -n "$1" ]; then
1270
- docker-compose logs -f "$1"
1634
+ docker compose logs -f "$1"
1271
1635
  else
1272
- docker-compose logs -f
1636
+ docker compose logs -f
1273
1637
  fi
1274
1638
  `;
1275
1639
  }
@@ -1296,28 +1660,28 @@ help:
1296
1660
  @echo " make restart - Restart all services"
1297
1661
  @echo " make logs - Show logs from all services"
1298
1662
  @echo " make shell - Open shell in app container"
1299
- @echo " make clean - Remove containers and volumes"
1663
+ @echo " make clean - Remove this project's containers and volumes"
1300
1664
  @echo " make install - Install dependencies"
1301
1665
 
1302
1666
  # Build Docker images
1303
1667
  build:
1304
- docker-compose build
1668
+ docker compose build
1305
1669
 
1306
1670
  # Start all services
1307
1671
  up:
1308
- docker-compose up -d
1672
+ docker compose up -d
1309
1673
  @echo "App running at http://localhost:${config.app.port}"
1310
1674
 
1311
1675
  # Stop all services
1312
1676
  down:
1313
- docker-compose down
1677
+ docker compose down
1314
1678
 
1315
1679
  # Restart all services
1316
1680
  restart: down up
1317
1681
 
1318
1682
  # Show logs from all services
1319
1683
  logs:
1320
- docker-compose logs -f
1684
+ docker compose logs -f
1321
1685
  `;
1322
1686
  if (services2.length > 0) {
1323
1687
  content += "\n";
@@ -1325,23 +1689,22 @@ logs:
1325
1689
  content += `
1326
1690
  logs-${service}:
1327
1691
  `;
1328
- content += ` docker-compose logs -f ${service}
1692
+ content += ` docker compose logs -f ${service}
1329
1693
  `;
1330
1694
  }
1331
1695
  }
1332
1696
  content += `
1333
- # Clean up containers and volumes
1697
+ # Remove this project's containers, networks and volumes
1334
1698
  clean:
1335
- docker-compose down -v
1336
- docker system prune -f
1699
+ docker compose down -v --remove-orphans
1337
1700
 
1338
1701
  # Install dependencies (in running container)
1339
1702
  shell:
1340
- docker-compose exec app sh
1703
+ docker compose exec app sh
1341
1704
 
1342
1705
  # Install dependencies
1343
1706
  install:
1344
- docker-compose exec app npm install
1707
+ docker compose exec app npm install
1345
1708
  `;
1346
1709
  return content;
1347
1710
  }
@@ -1368,7 +1731,8 @@ function generateAll(config, context) {
1368
1731
  } else {
1369
1732
  const generator = GENERATORS[fileType];
1370
1733
  if (generator) {
1371
- result[generator.file] = generator.generate(config, context);
1734
+ const file = fileType === "dockerignore" ? dockerignoreFileName(config.output.dir) : generator.file;
1735
+ result[file] = generator.generate(config, context);
1372
1736
  }
1373
1737
  }
1374
1738
  }
@@ -1377,7 +1741,7 @@ function generateAll(config, context) {
1377
1741
 
1378
1742
  // src/utils/fs.ts
1379
1743
  import { promises as fs } from "fs";
1380
- import { join, dirname, basename, extname, relative } from "path";
1744
+ import { join as join2, dirname, basename, extname, relative as relative2 } from "path";
1381
1745
  async function ensureDir(path) {
1382
1746
  try {
1383
1747
  await fs.mkdir(path, { recursive: true });
@@ -1388,18 +1752,27 @@ async function ensureDir(path) {
1388
1752
  }
1389
1753
  }
1390
1754
  }
1391
- async function writeFile(filePath, content) {
1755
+ async function writeFile(filePath, content, mode) {
1756
+ try {
1757
+ await writeFileAtomic(filePath, content, mode);
1758
+ } catch (error) {
1759
+ throw new FileWriteError(filePath, "FILE_WRITE_ERROR", error);
1760
+ }
1761
+ }
1762
+ async function writeFileAtomic(filePath, content, mode) {
1392
1763
  const dir = dirname(filePath);
1393
1764
  await ensureDir(dir);
1394
- const tempPath = join(dir, `.${basename(filePath)}.tmp`);
1765
+ const suffix = `${process.pid}.${Date.now().toString(36)}.${Math.random().toString(36).slice(2)}`;
1766
+ const tempPath = join2(dir, `.${basename(filePath)}.${suffix}.tmp`);
1395
1767
  try {
1396
- await fs.writeFile(tempPath, content, "utf8");
1768
+ await fs.writeFile(tempPath, content, { encoding: "utf8", mode });
1769
+ if (mode !== void 0) {
1770
+ await fs.chmod(tempPath, mode);
1771
+ }
1397
1772
  await fs.rename(tempPath, filePath);
1398
1773
  } catch (error) {
1399
- try {
1400
- await fs.unlink(tempPath);
1401
- } catch {
1402
- }
1774
+ await fs.unlink(tempPath).catch(() => {
1775
+ });
1403
1776
  throw error;
1404
1777
  }
1405
1778
  }
@@ -1413,24 +1786,27 @@ async function fileExists(filePath) {
1413
1786
  }
1414
1787
 
1415
1788
  // src/core/dockcraft.ts
1416
- import { join as join2 } from "path";
1789
+ import { isAbsolute as isAbsolute2, join as join3, normalize } from "path";
1790
+ function validationError(prefix, errors) {
1791
+ const errorMessages = errors.map((e) => ` - ${e.message}`).join("\n");
1792
+ return new ValidationError(`${prefix}:
1793
+ ${errorMessages}`, errors);
1794
+ }
1795
+ function isSafeOutputPath(fileName) {
1796
+ if (typeof fileName !== "string" || fileName === "" || fileName.includes("\0")) return false;
1797
+ if (isAbsolute2(fileName) || /^[a-zA-Z]:/.test(fileName) || fileName.startsWith("\\")) return false;
1798
+ const normalized = normalize(fileName.replace(/\\/g, "/"));
1799
+ return !normalized.split(/[\\/]/).includes("..") && normalized !== ".";
1800
+ }
1417
1801
  async function dockcraft(config, options = {}) {
1418
1802
  const validation = validateConfig(config);
1419
1803
  if (!validation.valid) {
1420
- const errorMessages = validation.errors.map((e) => ` - ${e.message}`).join("\n");
1421
- throw new Error(
1422
- `Configuration validation failed:
1423
- ${errorMessages}`
1424
- );
1804
+ throw validationError("Configuration validation failed", validation.errors);
1425
1805
  }
1426
1806
  const resolved = await resolveConfig(config);
1427
1807
  const resolvedValidation = validateResolvedConfig(resolved);
1428
1808
  if (!resolvedValidation.valid) {
1429
- const errorMessages = resolvedValidation.errors.map((e) => ` - ${e.message}`).join("\n");
1430
- throw new Error(
1431
- `Resolved configuration validation failed:
1432
- ${errorMessages}`
1433
- );
1809
+ throw validationError("Resolved configuration validation failed", resolvedValidation.errors);
1434
1810
  }
1435
1811
  const context = {
1436
1812
  config: resolved,
@@ -1438,22 +1814,38 @@ ${errorMessages}`
1438
1814
  Object.entries(resolved.services).map(([name, svc]) => [name, svc.port])
1439
1815
  ),
1440
1816
  strings: new Map(
1441
- Object.entries(resolved.services).filter(([, svc]) => svc.connectionString).map(([name, svc]) => [name, svc.connectionString])
1817
+ Object.entries(resolved.services).filter((entry) => Boolean(entry[1].connectionString)).map(([name, svc]) => [name, svc.connectionString])
1442
1818
  )
1443
1819
  };
1444
1820
  context.ports.set("app", resolved.app.port);
1445
1821
  const generated = generateAll(resolved, context);
1822
+ for (const plugin of config.plugins ?? []) {
1823
+ for (const output of plugin.outputs ?? []) {
1824
+ if (!isSafeOutputPath(output.file)) {
1825
+ throw new ConfigError(
1826
+ `Plugin '${plugin.name}' output '${output.name}' has an unsafe file name '${output.file}'. Use a relative path inside the output directory.`,
1827
+ "UNSAFE_OUTPUT_PATH"
1828
+ );
1829
+ }
1830
+ if (output.file in generated) {
1831
+ throw new ConfigError(
1832
+ `Plugin '${plugin.name}' output '${output.name}' would overwrite generated file '${output.file}'.`,
1833
+ "DUPLICATE_OUTPUT"
1834
+ );
1835
+ }
1836
+ generated[output.file] = output.generate(resolved, context);
1837
+ }
1838
+ }
1446
1839
  const written = [];
1447
1840
  const outputDir = resolved.output.dir ?? "./";
1448
1841
  if (!options.dryRun) {
1449
1842
  for (const [fileName, content] of Object.entries(generated)) {
1450
- if (!fileName) continue;
1451
- const filePath = join2(outputDir, fileName);
1843
+ const filePath = join3(outputDir, fileName);
1452
1844
  const exists = await fileExists(filePath);
1453
1845
  if (exists && !resolved.output.overwrite) {
1454
1846
  continue;
1455
1847
  }
1456
- await writeFile(filePath, content);
1848
+ await writeFile(filePath, content, fileName.endsWith(".sh") ? 493 : void 0);
1457
1849
  written.push(filePath);
1458
1850
  }
1459
1851
  }
@@ -1500,79 +1892,37 @@ function listDefaultPorts() {
1500
1892
  return { ...DEFAULT_PORTS };
1501
1893
  }
1502
1894
 
1503
- // src/types.ts
1504
- var DockcraftError = class extends Error {
1505
- constructor(message, code) {
1506
- super(message);
1507
- this.code = code;
1508
- this.name = "DockcraftError";
1509
- }
1510
- };
1511
- var ConfigError = class extends DockcraftError {
1512
- constructor(message, code = "CONFIG_ERROR") {
1513
- super(message, code);
1514
- this.name = "ConfigError";
1515
- }
1516
- };
1517
- var ValidationError = class extends DockcraftError {
1518
- constructor(message, errors, code = "VALIDATION_ERROR") {
1519
- super(message, code);
1520
- this.errors = errors;
1521
- this.name = "ValidationError";
1522
- }
1523
- };
1524
- var PortConflictError = class extends DockcraftError {
1525
- constructor(port, code = "PORT_CONFLICT") {
1526
- super(`Port ${port} is already in use`, code);
1527
- this.name = "PortConflictError";
1528
- }
1529
- };
1530
- var NoPortAvailableError = class extends DockcraftError {
1531
- constructor(range, code = "NO_PORT_AVAILABLE") {
1532
- super(`No available port in range ${range[0]}-${range[1]}`, code);
1533
- this.name = "NoPortAvailableError";
1534
- }
1535
- };
1536
- var FileWriteError = class extends DockcraftError {
1537
- constructor(path, code = "FILE_WRITE_ERROR") {
1538
- super(`Failed to write file: ${path}`, code);
1539
- this.name = "FileWriteError";
1540
- }
1541
- };
1542
- var PresetNotFoundError = class extends DockcraftError {
1543
- constructor(name, code = "PRESET_NOT_FOUND") {
1544
- super(`Preset '${name}' not found`, code);
1545
- this.name = "PresetNotFoundError";
1546
- }
1547
- };
1548
- var ServiceNotFoundError = class extends DockcraftError {
1549
- constructor(name, code = "SERVICE_NOT_FOUND") {
1550
- super(`Service '${name}' not found`, code);
1551
- this.name = "ServiceNotFoundError";
1552
- }
1553
- };
1554
-
1555
1895
  // src/index.ts
1556
1896
  function getConnectionString(service, config) {
1897
+ const enc = encodeURIComponent;
1898
+ const { host, port } = config;
1557
1899
  switch (service) {
1558
- case "postgres":
1559
- const pgUser = config.user ?? "postgres";
1560
- const pgPass = config.password ?? "postgres";
1561
- const pgDb = config.database ?? "myapp";
1562
- return `postgres://${pgUser}:${pgPass}@${config.host}:${config.port}/${pgDb}`;
1563
- case "mysql":
1564
- const mysqlUser = config.user ?? "root";
1565
- const mysqlPass = config.password ?? "root";
1566
- const mysqlDb = config.database ?? "myapp";
1567
- return `mysql://${mysqlUser}:${mysqlPass}@${config.host}:${config.port}/${mysqlDb}`;
1900
+ case "postgres": {
1901
+ const user = config.user ?? "postgres";
1902
+ const password = config.password ?? "postgres";
1903
+ const database = config.database ?? "myapp";
1904
+ return `postgres://${enc(user)}:${enc(password)}@${host}:${port}/${enc(database)}`;
1905
+ }
1906
+ case "mysql": {
1907
+ const user = config.user ?? "root";
1908
+ const password = config.password ?? "root";
1909
+ const database = config.database ?? "myapp";
1910
+ return `mysql://${enc(user)}:${enc(password)}@${host}:${port}/${enc(database)}`;
1911
+ }
1568
1912
  case "mongo":
1569
- case "mongodb":
1570
- const mongoUser = config.user ?? "mongo";
1571
- const mongoPass = config.password ?? "mongo";
1572
- const mongoDb = config.database ?? "myapp";
1573
- return `mongodb://${mongoUser}:${mongoPass}@${config.host}:${config.port}/${mongoDb}`;
1574
- case "redis":
1575
- return `redis://${config.host}:${config.port}`;
1913
+ case "mongodb": {
1914
+ const user = config.user ?? "mongo";
1915
+ const password = config.password ?? "mongo";
1916
+ const database = config.database ?? "myapp";
1917
+ return `mongodb://${enc(user)}:${enc(password)}@${host}:${port}/${enc(database)}?authSource=admin`;
1918
+ }
1919
+ case "redis": {
1920
+ if (config.password === void 0 || config.password === "") {
1921
+ return `redis://${host}:${port}`;
1922
+ }
1923
+ const user = config.user ? enc(config.user) : "";
1924
+ return `redis://${user}:${enc(config.password)}@${host}:${port}`;
1925
+ }
1576
1926
  default:
1577
1927
  throw new Error(`Unknown service: ${service}`);
1578
1928
  }