@oxog/dockcraft 1.1.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.cjs CHANGED
@@ -84,9 +84,12 @@ var NoPortAvailableError = class extends DockcraftError {
84
84
  }
85
85
  };
86
86
  var FileWriteError = class extends DockcraftError {
87
- constructor(path, code = "FILE_WRITE_ERROR") {
88
- super(`Failed to write file: ${path}`, code);
87
+ constructor(path, code = "FILE_WRITE_ERROR", cause) {
88
+ super(`Failed to write file: ${path}${cause instanceof Error ? ` (${cause.message})` : ""}`, code);
89
89
  this.name = "FileWriteError";
90
+ if (cause !== void 0) {
91
+ this.cause = cause;
92
+ }
90
93
  }
91
94
  };
92
95
  var PresetNotFoundError = class extends DockcraftError {
@@ -545,7 +548,7 @@ async function resolvePort(options = {}) {
545
548
  if (await isPortAvailable(preferred)) {
546
549
  return preferred;
547
550
  }
548
- throw new Error(`Port ${preferred} is already in use`);
551
+ throw new PortConflictError(preferred);
549
552
  case "range":
550
553
  if (range) {
551
554
  const [start, end = start + 100] = range;
@@ -553,7 +556,7 @@ async function resolvePort(options = {}) {
553
556
  if (port !== void 0) {
554
557
  return port;
555
558
  }
556
- throw new Error(`No available port in range ${start}-${end}`);
559
+ throw new NoPortAvailableError([start, end]);
557
560
  }
558
561
  // Fall through to auto if no range specified
559
562
  case "auto":
@@ -562,7 +565,7 @@ async function resolvePort(options = {}) {
562
565
  if (port !== void 0) {
563
566
  return port;
564
567
  }
565
- throw new Error(`No available port found starting from ${preferred}`);
568
+ throw new NoPortAvailableError([preferred, 65535]);
566
569
  }
567
570
  }
568
571
  }
@@ -1268,14 +1271,41 @@ function yamlScalar(str) {
1268
1271
  return JSON.stringify(str);
1269
1272
  }
1270
1273
 
1274
+ // src/generators/paths.ts
1275
+ var import_path = require("path");
1276
+ function currentDir() {
1277
+ return typeof process !== "undefined" && typeof process.cwd === "function" ? process.cwd() : "/";
1278
+ }
1279
+ function outputSubdir(dir) {
1280
+ if (!dir) {
1281
+ return void 0;
1282
+ }
1283
+ const root = currentDir();
1284
+ const subdir = (0, import_path.relative)(root, (0, import_path.isAbsolute)(dir) ? dir : (0, import_path.join)(root, dir)).replace(/\\/g, "/");
1285
+ if (subdir === "" || subdir === ".." || subdir.startsWith("../") || (0, import_path.isAbsolute)(subdir)) {
1286
+ return void 0;
1287
+ }
1288
+ return subdir;
1289
+ }
1290
+ function pathToRoot(subdir) {
1291
+ return subdir.split("/").map(() => "..").join("/");
1292
+ }
1293
+
1271
1294
  // src/generators/compose.ts
1272
1295
  function composeLiteral(value) {
1273
1296
  return value.replace(/\$/g, "$$$$");
1274
1297
  }
1298
+ function composeBuild(outputDir) {
1299
+ const subdir = outputSubdir(outputDir);
1300
+ if (subdir === void 0) {
1301
+ return ".";
1302
+ }
1303
+ return { context: pathToRoot(subdir), dockerfile: `${subdir}/Dockerfile` };
1304
+ }
1275
1305
  function generateCompose(config, _context) {
1276
1306
  const { app, services: services2 } = config;
1277
1307
  const appService = {
1278
- build: ".",
1308
+ build: composeBuild(config.output.dir),
1279
1309
  ports: [`${app.port}:${app.port}`],
1280
1310
  environment: generateAppEnvironment(config),
1281
1311
  depends_on: Object.keys(services2),
@@ -1294,13 +1324,20 @@ function generateCompose(config, _context) {
1294
1324
  composeServices[serviceName] = generateServiceConfig(serviceConfig);
1295
1325
  }
1296
1326
  const compose = {
1297
- version: "3.9",
1298
1327
  services: composeServices,
1299
1328
  volumes: generateVolumeDefinitions(config)
1300
1329
  };
1301
1330
  return `${toYaml(compose)}
1302
1331
  `;
1303
1332
  }
1333
+ function connectionStringVar(serviceName) {
1334
+ return `${serviceName.toUpperCase().replace(/[^A-Z0-9_]/g, "_")}_URL`;
1335
+ }
1336
+ function hasDatabaseUrlAlias(config) {
1337
+ return config.services.postgres !== void 0 && !Object.entries(config.services).some(
1338
+ ([name, service]) => Boolean(service.connectionString) && connectionStringVar(name) === "DATABASE_URL"
1339
+ );
1340
+ }
1304
1341
  function generateAppEnvironment(config) {
1305
1342
  const env = ["NODE_ENV=production", `PORT=${config.app.port}`];
1306
1343
  const add = (key, value) => {
@@ -1308,12 +1345,14 @@ function generateAppEnvironment(config) {
1308
1345
  };
1309
1346
  for (const [serviceName, serviceConfig] of Object.entries(config.services)) {
1310
1347
  if (serviceConfig.connectionString) {
1311
- const key = `${serviceName.toUpperCase().replace(/[^A-Z0-9_]/g, "_")}_URL`;
1312
- add(key, serviceConfig.connectionString);
1348
+ add(connectionStringVar(serviceName), serviceConfig.connectionString);
1313
1349
  }
1314
1350
  }
1315
1351
  if (config.services.postgres) {
1316
1352
  const pg = config.services.postgres;
1353
+ if (pg.connectionString && hasDatabaseUrlAlias(config)) {
1354
+ add("DATABASE_URL", pg.connectionString);
1355
+ }
1317
1356
  add("POSTGRES_HOST", pg.name);
1318
1357
  add("POSTGRES_PORT", pg.port);
1319
1358
  add("POSTGRES_USER", pg.env.POSTGRES_USER || "postgres");
@@ -1397,7 +1436,19 @@ function generateVolumeDefinitions(config) {
1397
1436
  }
1398
1437
 
1399
1438
  // src/generators/dockerignore.ts
1400
- function generateDockerignore(_config) {
1439
+ var DOCKERFILE_IGNORE_FILE = "Dockerfile.dockerignore";
1440
+ function dockerignoreFileName(outputDir) {
1441
+ return outputSubdir(outputDir) === void 0 ? ".dockerignore" : DOCKERFILE_IGNORE_FILE;
1442
+ }
1443
+ function outputDirPatterns(outputDir) {
1444
+ const subdir = outputSubdir(outputDir);
1445
+ if (subdir === void 0) {
1446
+ return "";
1447
+ }
1448
+ return ["Dockerfile", "docker-compose.yml", DOCKERFILE_IGNORE_FILE, ".env", ".env.*"].map((file) => `${subdir}/${file}
1449
+ `).join("");
1450
+ }
1451
+ function generateDockerignore(config) {
1401
1452
  return `# Dependencies
1402
1453
  node_modules/
1403
1454
  npm-debug.log*
@@ -1459,7 +1510,7 @@ temp/
1459
1510
  Dockerfile
1460
1511
  docker-compose.yml
1461
1512
  .dockerignore
1462
-
1513
+ ${outputDirPatterns(config.output.dir)}
1463
1514
  # Package manager lockfiles (optional - uncomment if you want to exclude)
1464
1515
  # package-lock.json
1465
1516
  # yarn.lock
@@ -1468,6 +1519,7 @@ docker-compose.yml
1468
1519
  }
1469
1520
 
1470
1521
  // src/generators/env.ts
1522
+ var BUILT_IN_SERVICES = /* @__PURE__ */ new Set(["postgres", "mysql", "mongo", "redis"]);
1471
1523
  function envValue(value) {
1472
1524
  if (/^[\w@%+=:,./?&-]*$/.test(value)) {
1473
1525
  return value;
@@ -1497,7 +1549,11 @@ PORT=${config.app.port}
1497
1549
  content += `
1498
1550
  # PostgreSQL
1499
1551
  `;
1500
- content += `DATABASE_URL=${envValue(String(pg.connectionString || ""))}
1552
+ if (hasDatabaseUrlAlias(config)) {
1553
+ content += `DATABASE_URL=${envValue(String(pg.connectionString || ""))}
1554
+ `;
1555
+ }
1556
+ content += `POSTGRES_URL=${envValue(String(pg.connectionString || ""))}
1501
1557
  `;
1502
1558
  content += `POSTGRES_HOST=${envValue(String(pg.name))}
1503
1559
  `;
@@ -1559,6 +1615,15 @@ PORT=${config.app.port}
1559
1615
  `;
1560
1616
  if (redis.env.REDIS_PASSWORD) {
1561
1617
  content += `REDIS_PASSWORD=${envValue(String(redis.env.REDIS_PASSWORD))}
1618
+ `;
1619
+ }
1620
+ }
1621
+ for (const [serviceName, service] of Object.entries(config.services)) {
1622
+ if (!BUILT_IN_SERVICES.has(serviceName) && service.connectionString) {
1623
+ content += `
1624
+ # ${serviceName}
1625
+ `;
1626
+ content += `${connectionStringVar(serviceName)}=${envValue(service.connectionString)}
1562
1627
  `;
1563
1628
  }
1564
1629
  }
@@ -1712,7 +1777,8 @@ function generateAll(config, context) {
1712
1777
  } else {
1713
1778
  const generator = GENERATORS[fileType];
1714
1779
  if (generator) {
1715
- result[generator.file] = generator.generate(config, context);
1780
+ const file = fileType === "dockerignore" ? dockerignoreFileName(config.output.dir) : generator.file;
1781
+ result[file] = generator.generate(config, context);
1716
1782
  }
1717
1783
  }
1718
1784
  }
@@ -1721,7 +1787,7 @@ function generateAll(config, context) {
1721
1787
 
1722
1788
  // src/utils/fs.ts
1723
1789
  var import_fs = require("fs");
1724
- var import_path = require("path");
1790
+ var import_path2 = require("path");
1725
1791
  async function ensureDir(path) {
1726
1792
  try {
1727
1793
  await import_fs.promises.mkdir(path, { recursive: true });
@@ -1733,10 +1799,17 @@ async function ensureDir(path) {
1733
1799
  }
1734
1800
  }
1735
1801
  async function writeFile(filePath, content, mode) {
1736
- const dir = (0, import_path.dirname)(filePath);
1802
+ try {
1803
+ await writeFileAtomic(filePath, content, mode);
1804
+ } catch (error) {
1805
+ throw new FileWriteError(filePath, "FILE_WRITE_ERROR", error);
1806
+ }
1807
+ }
1808
+ async function writeFileAtomic(filePath, content, mode) {
1809
+ const dir = (0, import_path2.dirname)(filePath);
1737
1810
  await ensureDir(dir);
1738
1811
  const suffix = `${process.pid}.${Date.now().toString(36)}.${Math.random().toString(36).slice(2)}`;
1739
- const tempPath = (0, import_path.join)(dir, `.${(0, import_path.basename)(filePath)}.${suffix}.tmp`);
1812
+ const tempPath = (0, import_path2.join)(dir, `.${(0, import_path2.basename)(filePath)}.${suffix}.tmp`);
1740
1813
  try {
1741
1814
  await import_fs.promises.writeFile(tempPath, content, { encoding: "utf8", mode });
1742
1815
  if (mode !== void 0) {
@@ -1759,7 +1832,7 @@ async function fileExists(filePath) {
1759
1832
  }
1760
1833
 
1761
1834
  // src/core/dockcraft.ts
1762
- var import_path2 = require("path");
1835
+ var import_path3 = require("path");
1763
1836
  function validationError(prefix, errors) {
1764
1837
  const errorMessages = errors.map((e) => ` - ${e.message}`).join("\n");
1765
1838
  return new ValidationError(`${prefix}:
@@ -1767,8 +1840,8 @@ ${errorMessages}`, errors);
1767
1840
  }
1768
1841
  function isSafeOutputPath(fileName) {
1769
1842
  if (typeof fileName !== "string" || fileName === "" || fileName.includes("\0")) return false;
1770
- if ((0, import_path2.isAbsolute)(fileName) || /^[a-zA-Z]:/.test(fileName) || fileName.startsWith("\\")) return false;
1771
- const normalized = (0, import_path2.normalize)(fileName.replace(/\\/g, "/"));
1843
+ if ((0, import_path3.isAbsolute)(fileName) || /^[a-zA-Z]:/.test(fileName) || fileName.startsWith("\\")) return false;
1844
+ const normalized = (0, import_path3.normalize)(fileName.replace(/\\/g, "/"));
1772
1845
  return !normalized.split(/[\\/]/).includes("..") && normalized !== ".";
1773
1846
  }
1774
1847
  async function dockcraft(config, options = {}) {
@@ -1813,7 +1886,7 @@ async function dockcraft(config, options = {}) {
1813
1886
  const outputDir = resolved.output.dir ?? "./";
1814
1887
  if (!options.dryRun) {
1815
1888
  for (const [fileName, content] of Object.entries(generated)) {
1816
- const filePath = (0, import_path2.join)(outputDir, fileName);
1889
+ const filePath = (0, import_path3.join)(outputDir, fileName);
1817
1890
  const exists = await fileExists(filePath);
1818
1891
  if (exists && !resolved.output.overwrite) {
1819
1892
  continue;