@oxog/dockcraft 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2095 +0,0 @@
1
- /**
2
- * @oxog/dockcraft - Zero-Dependency NPM Package
3
- * GitHub: https://github.com/ersinkoc/dockcraft
4
- * License: MIT
5
- */
6
- "use strict";
7
- var __defProp = Object.defineProperty;
8
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
9
- var __getOwnPropNames = Object.getOwnPropertyNames;
10
- var __hasOwnProp = Object.prototype.hasOwnProperty;
11
- var __export = (target, all) => {
12
- for (var name in all)
13
- __defProp(target, name, { get: all[name], enumerable: true });
14
- };
15
- var __copyProps = (to, from, except, desc) => {
16
- if (from && typeof from === "object" || typeof from === "function") {
17
- for (let key of __getOwnPropNames(from))
18
- if (!__hasOwnProp.call(to, key) && key !== except)
19
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
20
- }
21
- return to;
22
- };
23
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
24
-
25
- // src/cli/index.ts
26
- var cli_exports = {};
27
- __export(cli_exports, {
28
- main: () => main
29
- });
30
- module.exports = __toCommonJS(cli_exports);
31
-
32
- // node_modules/tsup/assets/cjs_shims.js
33
- var getImportMetaUrl = () => typeof document === "undefined" ? new URL(`file:${__filename}`).href : document.currentScript && document.currentScript.tagName.toUpperCase() === "SCRIPT" ? document.currentScript.src : new URL("main.js", document.baseURI).href;
34
- var importMetaUrl = /* @__PURE__ */ getImportMetaUrl();
35
-
36
- // src/cli/parser.ts
37
- function parseArgs(args) {
38
- const result = {
39
- command: "",
40
- flags: /* @__PURE__ */ new Set(),
41
- options: /* @__PURE__ */ new Map(),
42
- positionals: []
43
- };
44
- let i = 0;
45
- while (i < args.length) {
46
- const arg = args[i];
47
- if (!arg) {
48
- i++;
49
- continue;
50
- }
51
- if (arg.startsWith("--")) {
52
- const name = arg.slice(2);
53
- if (name.includes("=")) {
54
- const parts = name.split("=");
55
- const key = parts[0];
56
- const value = parts.slice(1).join("=");
57
- if (key) result.options.set(key, value);
58
- } else {
59
- const nextIndex = i + 1;
60
- if (nextIndex < args.length) {
61
- const nextArg = args[nextIndex];
62
- if (nextArg && !nextArg.startsWith("-")) {
63
- result.options.set(name, nextArg);
64
- i++;
65
- } else {
66
- result.flags.add(name);
67
- }
68
- } else {
69
- result.flags.add(name);
70
- }
71
- }
72
- } else if (arg.startsWith("-")) {
73
- const shorts = arg.slice(1);
74
- if (shorts.length === 1) {
75
- const nextIndex = i + 1;
76
- if (nextIndex < args.length) {
77
- const nextArg = args[nextIndex];
78
- if (nextArg && !nextArg.startsWith("-")) {
79
- result.options.set(shorts, nextArg);
80
- i++;
81
- } else {
82
- result.flags.add(shorts);
83
- }
84
- } else {
85
- result.flags.add(shorts);
86
- }
87
- } else {
88
- for (const s of shorts) {
89
- result.flags.add(s);
90
- }
91
- }
92
- } else if (!result.command) {
93
- result.command = arg;
94
- } else {
95
- result.positionals.push(arg);
96
- }
97
- i++;
98
- }
99
- return result;
100
- }
101
- function hasFlag(args, flag) {
102
- if (args.flags.has(flag)) return true;
103
- const firstChar = flag[0];
104
- return firstChar !== void 0 && args.flags.has(firstChar);
105
- }
106
- function getOption(args, option, defaultValue = "") {
107
- const value = args.options.get(option);
108
- if (value !== void 0) return value;
109
- const firstChar = option[0];
110
- if (firstChar !== void 0) {
111
- const shortValue = args.options.get(firstChar);
112
- if (shortValue !== void 0) return shortValue;
113
- }
114
- return defaultValue;
115
- }
116
- function getBooleanFlag(args, flag) {
117
- return hasFlag(args, flag) || getOption(args, flag, "") === "true";
118
- }
119
- function parseList(args, option) {
120
- const value = getOption(args, option);
121
- if (!value) return [];
122
- return value.split(",").map((s) => s.trim()).filter(Boolean);
123
- }
124
-
125
- // src/cli/output.ts
126
- var Colors = {
127
- reset: "\x1B[0m",
128
- bright: "\x1B[1m",
129
- dim: "\x1B[2m",
130
- black: "\x1B[30m",
131
- red: "\x1B[31m",
132
- green: "\x1B[32m",
133
- yellow: "\x1B[33m",
134
- blue: "\x1B[34m",
135
- magenta: "\x1B[35m",
136
- cyan: "\x1B[36m",
137
- white: "\x1B[37m",
138
- bgBlack: "\x1B[40m",
139
- bgRed: "\x1B[41m",
140
- bgGreen: "\x1B[42m",
141
- bgYellow: "\x1B[43m",
142
- bgBlue: "\x1B[44m"
143
- };
144
- function useColors() {
145
- return process.env.NO_COLOR === void 0 && process.stdout.isTTY && process.env.TERM !== "dumb";
146
- }
147
- function color(text, colorCode) {
148
- if (useColors()) {
149
- return `${colorCode}${text}${Colors.reset}`;
150
- }
151
- return text;
152
- }
153
- function success(message) {
154
- console.log(color("\u2713", Colors.green), color(message, Colors.bright));
155
- }
156
- function error(message) {
157
- console.error(color("\u2717", Colors.red), color(message, Colors.bright));
158
- }
159
- function info(message) {
160
- console.log(color("\u2139", Colors.blue), color(message, Colors.bright));
161
- }
162
- function title(message) {
163
- console.log("");
164
- console.log(color(message, Colors.bright));
165
- console.log(color("=".repeat(message.length), Colors.dim));
166
- }
167
- function subtitle(message) {
168
- console.log("");
169
- console.log(color(message, Colors.bright));
170
- }
171
- function table(headers, rows) {
172
- const widths = headers.map((h, i) => {
173
- const maxRowWidth = rows.length > 0 ? Math.max(...rows.map((r) => (r[i] ?? "").length)) : 0;
174
- return Math.max(h.length, maxRowWidth);
175
- });
176
- const headerRow = headers.map((h, i) => h.padEnd(widths[i] ?? 0)).join(" | ");
177
- console.log(color(headerRow, Colors.bright));
178
- const separator = widths.map((w) => "-".repeat(w ?? 0)).join("-+-");
179
- console.log(color(separator, Colors.dim));
180
- for (const row of rows) {
181
- const rowStr = headers.map((_, i) => (row[i] ?? "").padEnd(widths[i] ?? 0)).join(" | ");
182
- console.log(rowStr);
183
- }
184
- }
185
- function json(data) {
186
- console.log(JSON.stringify(data, null, 2));
187
- }
188
- function list(items) {
189
- for (const item of items) {
190
- console.log(` ${color("\u2022", Colors.cyan)} ${item}`);
191
- }
192
- }
193
- function kv(pairs) {
194
- const maxKeyLen = Math.max(...Object.keys(pairs).map((k) => k.length));
195
- for (const [key, value] of Object.entries(pairs)) {
196
- console.log(` ${color(key.padEnd(maxKeyLen), Colors.cyan)} : ${value}`);
197
- }
198
- }
199
-
200
- // src/cli/prompts.ts
201
- var import_readline = require("readline");
202
- async function prompt(question, defaultValue = "") {
203
- if (process.argv.includes("-y") || process.argv.includes("--yes")) {
204
- return defaultValue;
205
- }
206
- const rl = (0, import_readline.createInterface)({
207
- input: process.stdin,
208
- output: process.stdout
209
- });
210
- const query = defaultValue ? `${question} (${defaultValue}): ` : `${question}: `;
211
- return new Promise((resolve) => {
212
- rl.question(query, (answer) => {
213
- rl.close();
214
- resolve(answer || defaultValue);
215
- });
216
- });
217
- }
218
- async function confirm(question) {
219
- if (process.argv.includes("-y") || process.argv.includes("--yes")) {
220
- return true;
221
- }
222
- const rl = (0, import_readline.createInterface)({
223
- input: process.stdin,
224
- output: process.stdout
225
- });
226
- const query = `${question} (y/N): `;
227
- return new Promise((resolve) => {
228
- rl.question(query, (answer) => {
229
- rl.close();
230
- resolve(answer.toLowerCase() === "y" || answer.toLowerCase() === "yes");
231
- });
232
- });
233
- }
234
- async function select(question, options) {
235
- if (process.argv.includes("-y") || process.argv.includes("--yes")) {
236
- return options[0] ?? "";
237
- }
238
- const rl = (0, import_readline.createInterface)({
239
- input: process.stdin,
240
- output: process.stdout
241
- });
242
- console.log("");
243
- console.log(question);
244
- for (let i = 0; i < options.length; i++) {
245
- console.log(` ${i + 1}. ${options[i]}`);
246
- }
247
- console.log("");
248
- return new Promise((resolve) => {
249
- rl.question(`Select (1-${options.length}): `, (answer) => {
250
- rl.close();
251
- const index = parseInt(answer ?? "0", 10) - 1;
252
- if (index >= 0 && index < options.length) {
253
- resolve(options[index] ?? "");
254
- } else {
255
- resolve(options[0] ?? "");
256
- }
257
- });
258
- });
259
- }
260
- async function multiselect(question, options) {
261
- if (process.argv.includes("-y") || process.argv.includes("--yes")) {
262
- return options;
263
- }
264
- const rl = (0, import_readline.createInterface)({
265
- input: process.stdin,
266
- output: process.stdout
267
- });
268
- console.log("");
269
- console.log(question);
270
- console.log(" (comma-separated, e.g., 1,3,5)");
271
- for (let i = 0; i < options.length; i++) {
272
- console.log(` ${i + 1}. ${options[i]}`);
273
- }
274
- console.log("");
275
- return new Promise((resolve) => {
276
- rl.question(`Select (1-${options.length}): `, (answer) => {
277
- rl.close();
278
- const indices = (answer ?? "").split(",").map((s) => parseInt(s.trim(), 10) - 1);
279
- const selected = indices.filter((i) => i >= 0 && i < options.length).map((i) => options[i]).filter((s) => s !== void 0);
280
- resolve(selected.length > 0 ? selected : [options[0] ?? ""]);
281
- });
282
- });
283
- }
284
-
285
- // src/utils/fs.ts
286
- var import_fs = require("fs");
287
- var import_path = require("path");
288
- async function ensureDir(path) {
289
- try {
290
- await import_fs.promises.mkdir(path, { recursive: true });
291
- } catch (error3) {
292
- const err = error3;
293
- if (err.code !== "EEXIST") {
294
- throw error3;
295
- }
296
- }
297
- }
298
- async function writeFile(filePath, content) {
299
- const dir = (0, import_path.dirname)(filePath);
300
- await ensureDir(dir);
301
- const tempPath = (0, import_path.join)(dir, `.${(0, import_path.basename)(filePath)}.tmp`);
302
- try {
303
- await import_fs.promises.writeFile(tempPath, content, "utf8");
304
- await import_fs.promises.rename(tempPath, filePath);
305
- } catch (error3) {
306
- try {
307
- await import_fs.promises.unlink(tempPath);
308
- } catch {
309
- }
310
- throw error3;
311
- }
312
- }
313
- async function fileExists(filePath) {
314
- try {
315
- const stat = await import_fs.promises.stat(filePath);
316
- return stat.isFile();
317
- } catch {
318
- return false;
319
- }
320
- }
321
-
322
- // src/presets/express-postgres.ts
323
- var expressPostgresPreset = {
324
- description: "Express application with PostgreSQL database",
325
- app: {
326
- port: 3e3,
327
- node: "20-alpine",
328
- workdir: "/app",
329
- command: "npm start",
330
- buildCommand: "npm run build",
331
- multiStage: true,
332
- healthcheck: "/health"
333
- },
334
- services: {
335
- postgres: {
336
- version: "16"
337
- }
338
- }
339
- };
340
-
341
- // src/presets/express-postgres-redis.ts
342
- var expressPostgresRedisPreset = {
343
- description: "Express application with PostgreSQL database and Redis cache",
344
- app: {
345
- port: 3e3,
346
- node: "20-alpine",
347
- workdir: "/app",
348
- command: "npm start",
349
- buildCommand: "npm run build",
350
- multiStage: true,
351
- healthcheck: "/health"
352
- },
353
- services: {
354
- postgres: {
355
- version: "16"
356
- },
357
- redis: {
358
- version: "7-alpine"
359
- }
360
- }
361
- };
362
-
363
- // src/presets/express-mongo.ts
364
- var expressMongoPreset = {
365
- description: "Express application with MongoDB database",
366
- app: {
367
- port: 3e3,
368
- node: "20-alpine",
369
- workdir: "/app",
370
- command: "npm start",
371
- buildCommand: "npm run build",
372
- multiStage: true,
373
- healthcheck: "/health"
374
- },
375
- services: {
376
- mongo: {
377
- version: "7"
378
- }
379
- }
380
- };
381
-
382
- // src/presets/express-mongo-redis.ts
383
- var expressMongoRedisPreset = {
384
- description: "Express application with MongoDB database and Redis cache",
385
- app: {
386
- port: 3e3,
387
- node: "20-alpine",
388
- workdir: "/app",
389
- command: "npm start",
390
- buildCommand: "npm run build",
391
- multiStage: true,
392
- healthcheck: "/health"
393
- },
394
- services: {
395
- mongo: {
396
- version: "7"
397
- },
398
- redis: {
399
- version: "7-alpine"
400
- }
401
- }
402
- };
403
-
404
- // src/presets/express-mysql.ts
405
- var expressMysqlPreset = {
406
- description: "Express application with MySQL database",
407
- app: {
408
- port: 3e3,
409
- node: "20-alpine",
410
- workdir: "/app",
411
- command: "npm start",
412
- buildCommand: "npm run build",
413
- multiStage: true,
414
- healthcheck: "/health"
415
- },
416
- services: {
417
- mysql: {
418
- version: "8"
419
- }
420
- }
421
- };
422
-
423
- // src/presets/express-mysql-redis.ts
424
- var expressMysqlRedisPreset = {
425
- description: "Express application with MySQL database and Redis cache",
426
- app: {
427
- port: 3e3,
428
- node: "20-alpine",
429
- workdir: "/app",
430
- command: "npm start",
431
- buildCommand: "npm run build",
432
- multiStage: true,
433
- healthcheck: "/health"
434
- },
435
- services: {
436
- mysql: {
437
- version: "8"
438
- },
439
- redis: {
440
- version: "7-alpine"
441
- }
442
- }
443
- };
444
-
445
- // src/presets/fastify-postgres.ts
446
- var fastifyPostgresPreset = {
447
- description: "Fastify application with PostgreSQL database",
448
- app: {
449
- port: 3e3,
450
- node: "20-alpine",
451
- workdir: "/app",
452
- command: "npm start",
453
- buildCommand: "npm run build",
454
- multiStage: true,
455
- healthcheck: "/health"
456
- },
457
- services: {
458
- postgres: {
459
- version: "16"
460
- }
461
- }
462
- };
463
-
464
- // src/presets/fastify-postgres-redis.ts
465
- var fastifyPostgresRedisPreset = {
466
- description: "Fastify application with PostgreSQL database and Redis cache",
467
- app: {
468
- port: 3e3,
469
- node: "20-alpine",
470
- workdir: "/app",
471
- command: "npm start",
472
- buildCommand: "npm run build",
473
- multiStage: true,
474
- healthcheck: "/health"
475
- },
476
- services: {
477
- postgres: {
478
- version: "16"
479
- },
480
- redis: {
481
- version: "7-alpine"
482
- }
483
- }
484
- };
485
-
486
- // src/presets/nest-postgres.ts
487
- var nestPostgresPreset = {
488
- description: "NestJS application with PostgreSQL database",
489
- app: {
490
- port: 3e3,
491
- node: "20-alpine",
492
- workdir: "/app",
493
- command: "npm run start:prod",
494
- buildCommand: "npm run build",
495
- multiStage: true,
496
- healthcheck: "/health"
497
- },
498
- services: {
499
- postgres: {
500
- version: "16"
501
- }
502
- }
503
- };
504
-
505
- // src/presets/nest-mongo.ts
506
- var nestMongoPreset = {
507
- description: "NestJS application with MongoDB database",
508
- app: {
509
- port: 3e3,
510
- node: "20-alpine",
511
- workdir: "/app",
512
- command: "npm run start:prod",
513
- buildCommand: "npm run build",
514
- multiStage: true,
515
- healthcheck: "/health"
516
- },
517
- services: {
518
- mongo: {
519
- version: "7"
520
- }
521
- }
522
- };
523
-
524
- // src/presets/node-minimal.ts
525
- var nodeMinimalPreset = {
526
- description: "Minimal Node.js application setup",
527
- app: {
528
- port: 3e3,
529
- node: "20-alpine",
530
- workdir: "/app",
531
- command: "npm start",
532
- multiStage: true
533
- },
534
- services: {}
535
- };
536
-
537
- // src/presets/index.ts
538
- var presets = /* @__PURE__ */ new Map();
539
- function registerPreset(name, config) {
540
- presets.set(name, config);
541
- }
542
- function getPreset(name) {
543
- return presets.get(name);
544
- }
545
- function listPresets() {
546
- return Array.from(presets.keys());
547
- }
548
- registerPreset("express-postgres", expressPostgresPreset);
549
- registerPreset("express-postgres-redis", expressPostgresRedisPreset);
550
- registerPreset("express-mongo", expressMongoPreset);
551
- registerPreset("express-mongo-redis", expressMongoRedisPreset);
552
- registerPreset("express-mysql", expressMysqlPreset);
553
- registerPreset("express-mysql-redis", expressMysqlRedisPreset);
554
- registerPreset("fastify-postgres", fastifyPostgresPreset);
555
- registerPreset("fastify-postgres-redis", fastifyPostgresRedisPreset);
556
- registerPreset("nest-postgres", nestPostgresPreset);
557
- registerPreset("nest-mongo", nestMongoPreset);
558
- registerPreset("node-minimal", nodeMinimalPreset);
559
-
560
- // src/cli/commands/init.ts
561
- async function init(args) {
562
- title("Dockcraft Init");
563
- const name = getOption(args, "name") || await prompt("Project name");
564
- const preset = getOption(args, "preset");
565
- const servicesOption = getOption(args, "services");
566
- const port = getOption(args, "port") || await prompt("App port", "3000");
567
- const outputDir = getOption(args, "output") || await prompt("Output directory", "./");
568
- const skipPrompts = getBooleanFlag(args, "yes");
569
- info(`Creating config for "${name}"`);
570
- let selectedPreset = preset;
571
- if (!selectedPreset && !skipPrompts) {
572
- const presets3 = listPresets();
573
- const usePreset = await confirm("Use a preset?");
574
- if (usePreset) {
575
- const presetName = await select("Select preset:", presets3);
576
- selectedPreset = presetName;
577
- }
578
- }
579
- let selectedServices = [];
580
- if (servicesOption) {
581
- selectedServices = parseList(args, "services");
582
- } else if (!skipPrompts && !selectedPreset) {
583
- const availableServices = ["postgres", "mysql", "mongo", "redis"];
584
- selectedServices = await multiselect("Select services:", availableServices);
585
- }
586
- const config = generateConfig(name, selectedPreset, selectedServices, port);
587
- const configPath = `${outputDir}/dockcraft.config.ts`;
588
- await writeFile(configPath, config);
589
- success(`Config file created: ${configPath}`);
590
- info('Run "dockcraft generate" to generate Docker files');
591
- }
592
- function generateConfig(name, preset, services2, port) {
593
- let content = `import { dockcraft } from '@oxog/dockcraft';
594
-
595
- `;
596
- content += `await dockcraft({
597
- `;
598
- content += ` name: '${name}',
599
- `;
600
- if (preset) {
601
- content += ` preset: '${preset}',
602
- `;
603
- }
604
- content += ` app: {
605
- `;
606
- content += ` port: ${port},
607
- `;
608
- content += ` },
609
- `;
610
- if (services2.length > 0) {
611
- content += ` services: {
612
- `;
613
- for (const service of services2) {
614
- content += ` ${service}: {},
615
- `;
616
- }
617
- content += ` },
618
- `;
619
- }
620
- content += `});
621
- `;
622
- return content;
623
- }
624
-
625
- // src/services/postgres.ts
626
- var postgresService = {
627
- name: "postgres",
628
- image: (version) => `postgres:${version}-alpine`,
629
- defaultPort: 5432,
630
- defaultVersion: "16",
631
- env: {
632
- POSTGRES_USER: "postgres",
633
- POSTGRES_PASSWORD: "postgres",
634
- POSTGRES_DB: "myapp"
635
- },
636
- volumes: ["postgres_data:/var/lib/postgresql/data"],
637
- healthcheck: "pg_isready -U postgres",
638
- ports: [],
639
- connectionString: (config) => {
640
- const user = config.env.POSTGRES_USER || "postgres";
641
- const password = config.env.POSTGRES_PASSWORD || "postgres";
642
- const database = config.env.POSTGRES_DB || "myapp";
643
- const host = config.name;
644
- const port = config.port;
645
- return `postgres://${user}:${password}@${host}:${port}/${database}`;
646
- }
647
- };
648
-
649
- // src/services/mysql.ts
650
- var mysqlService = {
651
- name: "mysql",
652
- image: (version) => `mysql:${version}`,
653
- defaultPort: 3306,
654
- defaultVersion: "8",
655
- env: {
656
- MYSQL_ROOT_PASSWORD: "root",
657
- MYSQL_DATABASE: "myapp",
658
- MYSQL_USER: "mysql",
659
- MYSQL_PASSWORD: "mysql"
660
- },
661
- volumes: ["mysql_data:/var/lib/mysql"],
662
- healthcheck: "mysqladmin ping -h localhost",
663
- ports: [],
664
- connectionString: (config) => {
665
- const user = config.env.MYSQL_USER || "root";
666
- const password = config.env.MYSQL_PASSWORD || config.env.MYSQL_ROOT_PASSWORD || "root";
667
- const database = config.env.MYSQL_DATABASE || "myapp";
668
- const host = config.name;
669
- const port = config.port;
670
- return `mysql://${user}:${password}@${host}:${port}/${database}`;
671
- }
672
- };
673
-
674
- // src/services/mongo.ts
675
- var mongoService = {
676
- name: "mongo",
677
- image: (version) => `mongo:${version}`,
678
- defaultPort: 27017,
679
- defaultVersion: "7",
680
- env: {
681
- MONGO_INITDB_ROOT_USERNAME: "mongo",
682
- MONGO_INITDB_ROOT_PASSWORD: "mongo",
683
- MONGO_INITDB_DATABASE: "myapp"
684
- },
685
- volumes: ["mongo_data:/data/db"],
686
- healthcheck: 'mongosh --eval "db.adminCommand({ ping: 1 })"',
687
- ports: [],
688
- connectionString: (config) => {
689
- const user = config.env.MONGO_INITDB_ROOT_USERNAME || "mongo";
690
- const password = config.env.MONGO_INITDB_ROOT_PASSWORD || "mongo";
691
- const database = config.env.MONGO_INITDB_DATABASE || "myapp";
692
- const host = config.name;
693
- const port = config.port;
694
- return `mongodb://${user}:${password}@${host}:${port}/${database}`;
695
- }
696
- };
697
-
698
- // src/services/redis.ts
699
- var redisService = {
700
- name: "redis",
701
- image: (version) => `redis:${version}-alpine`,
702
- defaultPort: 6379,
703
- defaultVersion: "7",
704
- env: {},
705
- volumes: ["redis_data:/data"],
706
- healthcheck: "redis-cli ping",
707
- ports: [],
708
- connectionString: (config) => {
709
- const host = config.name;
710
- const port = config.port;
711
- return `redis://${host}:${port}`;
712
- }
713
- };
714
-
715
- // src/services/index.ts
716
- var services = /* @__PURE__ */ new Map();
717
- function registerService(def) {
718
- services.set(def.name, def);
719
- }
720
- function getService(name) {
721
- return services.get(name);
722
- }
723
- registerService(postgresService);
724
- registerService(mysqlService);
725
- registerService(mongoService);
726
- registerService(redisService);
727
-
728
- // src/utils/merge.ts
729
- function deepMerge(...objects) {
730
- const result = {};
731
- for (const obj of objects) {
732
- if (obj === null || typeof obj !== "object") continue;
733
- for (const [key, value] of Object.entries(obj)) {
734
- if (value === void 0) continue;
735
- if (value && typeof value === "object" && !Array.isArray(value) && result[key] && typeof result[key] === "object" && !Array.isArray(result[key])) {
736
- result[key] = deepMerge(result[key], value);
737
- } else {
738
- result[key] = value;
739
- }
740
- }
741
- }
742
- return result;
743
- }
744
-
745
- // src/ports/scanner.ts
746
- var import_net = require("net");
747
- async function isPortAvailable(port) {
748
- return new Promise((resolve) => {
749
- const server = (0, import_net.createServer)();
750
- server.once("error", () => {
751
- resolve(false);
752
- });
753
- server.once("listening", () => {
754
- server.close(() => {
755
- resolve(true);
756
- });
757
- });
758
- server.listen(port, "127.0.0.1");
759
- setTimeout(() => {
760
- server.close();
761
- resolve(false);
762
- }, 1e3);
763
- });
764
- }
765
- async function checkPorts(ports2) {
766
- const results = /* @__PURE__ */ new Map();
767
- await Promise.all(
768
- ports2.map(async (port) => {
769
- results.set(port, await isPortAvailable(port));
770
- })
771
- );
772
- return results;
773
- }
774
- async function findNextAvailablePort(startPort, maxPort = 65535) {
775
- for (let port = startPort; port <= maxPort; port++) {
776
- if (await isPortAvailable(port)) {
777
- return port;
778
- }
779
- }
780
- return void 0;
781
- }
782
- async function findAvailablePortInRange(start, end) {
783
- for (let port = start; port <= end; port++) {
784
- if (await isPortAvailable(port)) {
785
- return port;
786
- }
787
- }
788
- return void 0;
789
- }
790
- async function resolvePort(options = {}) {
791
- const {
792
- preferred = 3e3,
793
- strategy = "auto",
794
- range
795
- } = options;
796
- switch (strategy) {
797
- case "fixed":
798
- if (await isPortAvailable(preferred)) {
799
- return preferred;
800
- }
801
- throw new Error(`Port ${preferred} is already in use`);
802
- case "range":
803
- if (range) {
804
- const [start, end = start + 100] = range;
805
- const port2 = await findAvailablePortInRange(start, end);
806
- if (port2 !== void 0) {
807
- return port2;
808
- }
809
- throw new Error(`No available port in range ${start}-${end}`);
810
- }
811
- // Fall through to auto if no range specified
812
- case "auto":
813
- default:
814
- const port = await findNextAvailablePort(preferred);
815
- if (port !== void 0) {
816
- return port;
817
- }
818
- throw new Error(`No available port found starting from ${preferred}`);
819
- }
820
- }
821
-
822
- // src/core/config.ts
823
- var DEFAULT_APP_CONFIG = {
824
- port: 3e3,
825
- node: "20-alpine",
826
- workdir: "/app",
827
- command: "npm start",
828
- buildCommand: "npm run build",
829
- env: [],
830
- volumes: [],
831
- multiStage: true
832
- };
833
- function normalizeAppConfig(config) {
834
- return {
835
- port: config.port === "auto" ? 3e3 : config.port,
836
- node: config.node ?? DEFAULT_APP_CONFIG.node,
837
- workdir: config.workdir ?? DEFAULT_APP_CONFIG.workdir,
838
- command: config.command ?? DEFAULT_APP_CONFIG.command,
839
- buildCommand: config.buildCommand ?? DEFAULT_APP_CONFIG.buildCommand,
840
- env: config.env ?? DEFAULT_APP_CONFIG.env,
841
- volumes: config.volumes ?? DEFAULT_APP_CONFIG.volumes,
842
- multiStage: config.multiStage ?? DEFAULT_APP_CONFIG.multiStage,
843
- healthcheck: config.healthcheck
844
- };
845
- }
846
- function normalizeOutputConfig(config) {
847
- return {
848
- dir: config?.dir ?? "./",
849
- files: config?.files ?? ["dockerfile", "compose", "dockerignore", "env"],
850
- overwrite: config?.overwrite ?? false
851
- };
852
- }
853
- function normalizeConfig(config) {
854
- return {
855
- name: config.name,
856
- preset: config.preset,
857
- app: config.app,
858
- services: config.services ?? {},
859
- output: normalizeOutputConfig(config.output),
860
- plugins: config.plugins ?? []
861
- };
862
- }
863
- async function loadConfig(configPath) {
864
- try {
865
- const module2 = await import(configPath.toString());
866
- const config = module2.default ?? module2;
867
- return config;
868
- } catch (error3) {
869
- throw new Error(
870
- `Failed to load config from ${configPath}: ${error3 instanceof Error ? error3.message : String(error3)}`
871
- );
872
- }
873
- }
874
-
875
- // src/core/resolver.ts
876
- function mergePreset(config, presetName) {
877
- const preset = getPreset(presetName);
878
- if (!preset) {
879
- throw new Error(`Preset '${presetName}' not found`);
880
- }
881
- const merged = deepMerge(
882
- {
883
- name: config.name,
884
- app: preset.app ?? {},
885
- services: preset.services ?? {},
886
- output: preset.output ?? {}
887
- },
888
- config
889
- );
890
- return merged;
891
- }
892
- async function resolveServiceConfig(name, config, projectName) {
893
- if ("image" in config && config.image) {
894
- return resolveCustomService(name, config);
895
- }
896
- const definition = getService(name);
897
- if (!definition) {
898
- throw new Error(`Unknown service: ${name}`);
899
- }
900
- const defaultPort = definition.defaultPort;
901
- let port = defaultPort;
902
- let hostPort;
903
- if (config.port === "auto") {
904
- port = await resolvePort({ preferred: defaultPort, strategy: "auto" });
905
- hostPort = port;
906
- } else if (typeof config.port === "number") {
907
- port = config.port;
908
- hostPort = config.port;
909
- } else if (config.port && typeof config.port === "object") {
910
- const { start, end } = config.port;
911
- const startPort = start ?? defaultPort;
912
- const endPort = end ?? startPort + 100;
913
- port = await resolvePort({ preferred: startPort, strategy: "range", range: [startPort, endPort] });
914
- hostPort = port;
915
- }
916
- const version = config.version ?? definition.defaultVersion;
917
- const image = typeof definition.image === "function" ? definition.image(version) : definition.image;
918
- const env = { ...definition.env, ...config.env };
919
- if (name === "postgres") {
920
- const pgConfig = config;
921
- if (pgConfig.database) env.POSTGRES_DB = pgConfig.database;
922
- if (pgConfig.user) env.POSTGRES_USER = pgConfig.user;
923
- if (pgConfig.password) env.POSTGRES_PASSWORD = pgConfig.password;
924
- if (!env.POSTGRES_DB) env.POSTGRES_DB = projectName;
925
- } else if (name === "mysql") {
926
- const mysqlConfig = config;
927
- if (mysqlConfig.database) env.MYSQL_DATABASE = mysqlConfig.database;
928
- if (mysqlConfig.user) env.MYSQL_USER = mysqlConfig.user;
929
- if (mysqlConfig.password) env.MYSQL_PASSWORD = mysqlConfig.password;
930
- if (mysqlConfig.rootPassword) env.MYSQL_ROOT_PASSWORD = mysqlConfig.rootPassword;
931
- if (!env.MYSQL_DATABASE) env.MYSQL_DATABASE = projectName;
932
- } else if (name === "mongo") {
933
- const mongoConfig = config;
934
- if (mongoConfig.database) env.MONGO_INITDB_DATABASE = mongoConfig.database;
935
- if (mongoConfig.user) env.MONGO_INITDB_ROOT_USERNAME = mongoConfig.user;
936
- if (mongoConfig.password) env.MONGO_INITDB_ROOT_PASSWORD = mongoConfig.password;
937
- if (!env.MONGO_INITDB_DATABASE) env.MONGO_INITDB_DATABASE = projectName;
938
- } else if (name === "redis") {
939
- const redisConfig = config;
940
- if (redisConfig.password) env.REDIS_PASSWORD = redisConfig.password;
941
- }
942
- const volumes = [...definition.volumes ?? [], ...config.volumes ?? []];
943
- const resolvedConfig = {
944
- name,
945
- image,
946
- port,
947
- hostPort,
948
- env,
949
- volumes,
950
- command: config.command,
951
- healthcheck: definition.healthcheck,
952
- ports: definition.ports
953
- };
954
- if (definition.connectionString) {
955
- resolvedConfig.connectionString = definition.connectionString(resolvedConfig);
956
- }
957
- return resolvedConfig;
958
- }
959
- async function resolveCustomService(name, config) {
960
- const imageMatch = config.image.match(/:(\d+)$/);
961
- const defaultPort = imageMatch && imageMatch[1] ? parseInt(imageMatch[1], 10) : 80;
962
- let port = defaultPort;
963
- let hostPort;
964
- if (config.port === "auto") {
965
- port = await resolvePort({ preferred: defaultPort, strategy: "auto" });
966
- hostPort = port;
967
- } else if (typeof config.port === "number") {
968
- port = config.port;
969
- hostPort = config.port;
970
- } else if (config.port && typeof config.port === "object") {
971
- const { start, end } = config.port;
972
- const startPort = start ?? defaultPort;
973
- const endPort = end ?? startPort + 100;
974
- port = await resolvePort({ preferred: startPort, strategy: "range", range: [startPort, endPort] });
975
- hostPort = port;
976
- }
977
- return {
978
- name,
979
- image: config.image,
980
- port,
981
- hostPort,
982
- env: config.env ?? {},
983
- volumes: config.volumes ?? [],
984
- command: config.command,
985
- healthcheck: config.command,
986
- ports: []
987
- };
988
- }
989
- async function resolveConfig(config) {
990
- let finalConfig = config;
991
- if (config.preset) {
992
- finalConfig = mergePreset(config, config.preset);
993
- }
994
- finalConfig = normalizeConfig(finalConfig);
995
- const appPort = finalConfig.app.port === "auto" ? await resolvePort({ preferred: 3e3, strategy: "auto" }) : finalConfig.app.port;
996
- const app = normalizeAppConfig({ ...finalConfig.app, port: appPort });
997
- const services2 = {};
998
- if (finalConfig.services) {
999
- for (const [name, serviceConfig] of Object.entries(finalConfig.services)) {
1000
- if (serviceConfig) {
1001
- services2[name] = await resolveServiceConfig(
1002
- name,
1003
- serviceConfig,
1004
- finalConfig.name
1005
- );
1006
- }
1007
- }
1008
- }
1009
- return {
1010
- name: finalConfig.name,
1011
- app,
1012
- services: services2,
1013
- output: normalizeOutputConfig(finalConfig.output)
1014
- };
1015
- }
1016
-
1017
- // src/utils/validation.ts
1018
- var MIN_PORT = 1;
1019
- var MAX_PORT = 65535;
1020
- function isPort(value) {
1021
- return typeof value === "number" && Number.isInteger(value) && value >= MIN_PORT && value <= MAX_PORT;
1022
- }
1023
- function isEnvVarName(value) {
1024
- if (typeof value !== "string") return false;
1025
- return /^[A-Z_][A-Z0-9_]*$/.test(value);
1026
- }
1027
- function isVersion(value) {
1028
- if (typeof value !== "string") return false;
1029
- if (value.length === 0) return false;
1030
- return /^[a-zA-Z0-9.\-]+$/.test(value);
1031
- }
1032
- function isProjectName(value) {
1033
- if (typeof value !== "string") return false;
1034
- if (value.length === 0 || value.length > 100) return false;
1035
- return /^[a-zA-Z][a-zA-Z0-9_-]*$/.test(value);
1036
- }
1037
-
1038
- // src/core/validator.ts
1039
- function validateProjectName(name) {
1040
- const errors = [];
1041
- if (!isProjectName(name)) {
1042
- errors.push({
1043
- code: "INVALID_NAME",
1044
- message: `Invalid project name '${name}'. Must start with a letter and contain only letters, numbers, hyphens, and underscores.`,
1045
- path: "name",
1046
- value: name
1047
- });
1048
- }
1049
- return errors;
1050
- }
1051
- function validateAppConfig(config) {
1052
- const errors = [];
1053
- if (config.port !== "auto" && !isPort(config.port)) {
1054
- errors.push({
1055
- code: "INVALID_PORT",
1056
- message: `Invalid app port '${String(config.port)}'. Must be a number between 1-65535 or 'auto'.`,
1057
- path: "app.port",
1058
- value: config.port
1059
- });
1060
- }
1061
- if (config.node !== void 0 && !isVersion(config.node)) {
1062
- errors.push({
1063
- code: "INVALID_VERSION",
1064
- message: `Invalid Node.js version '${config.node}'.`,
1065
- path: "app.node",
1066
- value: config.node
1067
- });
1068
- }
1069
- if (config.env) {
1070
- for (const envVar of config.env) {
1071
- if (!isEnvVarName(envVar)) {
1072
- errors.push({
1073
- code: "INVALID_ENV_VAR",
1074
- message: `Invalid environment variable name '${envVar}'. Must be uppercase letters, numbers, and underscores.`,
1075
- path: "app.env",
1076
- value: envVar
1077
- });
1078
- }
1079
- }
1080
- }
1081
- return errors;
1082
- }
1083
- function validateServiceConfig(name, config) {
1084
- const errors = [];
1085
- if (config.version !== void 0 && !isVersion(config.version)) {
1086
- errors.push({
1087
- code: "INVALID_VERSION",
1088
- message: `Invalid version '${config.version}' for service '${name}'.`,
1089
- path: `services.${name}.version`,
1090
- value: config.version
1091
- });
1092
- }
1093
- if (config.port !== void 0 && config.port !== "auto" && typeof config.port !== "number" && typeof config.port !== "object") {
1094
- errors.push({
1095
- code: "INVALID_PORT",
1096
- message: `Invalid port configuration for service '${name}'. Must be a number, 'auto', or a range object.`,
1097
- path: `services.${name}.port`,
1098
- value: config.port
1099
- });
1100
- }
1101
- return errors;
1102
- }
1103
- function validateOutputConfig(config) {
1104
- const errors = [];
1105
- if (config?.files) {
1106
- const validFiles = ["dockerfile", "compose", "dockerignore", "env", "scripts", "makefile"];
1107
- for (const file of config.files) {
1108
- if (!validFiles.includes(file)) {
1109
- errors.push({
1110
- code: "INVALID_OUTPUT_FILE",
1111
- message: `Invalid output file '${file}'. Must be one of: ${validFiles.join(", ")}.`,
1112
- path: "output.files",
1113
- value: file
1114
- });
1115
- }
1116
- }
1117
- }
1118
- return errors;
1119
- }
1120
- function validateConfig(config) {
1121
- const errors = [];
1122
- errors.push(...validateProjectName(config.name));
1123
- if (config.app) {
1124
- errors.push(...validateAppConfig(config.app));
1125
- }
1126
- if (config.services) {
1127
- for (const [name, serviceConfig] of Object.entries(config.services)) {
1128
- if (serviceConfig) {
1129
- errors.push(...validateServiceConfig(name, serviceConfig));
1130
- }
1131
- }
1132
- }
1133
- if (config.output) {
1134
- errors.push(...validateOutputConfig(config.output));
1135
- }
1136
- return {
1137
- valid: errors.length === 0,
1138
- errors
1139
- };
1140
- }
1141
- function validateResolvedConfig(config) {
1142
- const errors = [];
1143
- const usedPorts = /* @__PURE__ */ new Set();
1144
- usedPorts.add(config.app.port);
1145
- for (const [serviceName, serviceConfig] of Object.entries(config.services)) {
1146
- if (usedPorts.has(serviceConfig.port)) {
1147
- errors.push({
1148
- code: "PORT_CONFLICT",
1149
- message: `Port ${serviceConfig.port} is already in use by ${serviceName}.`,
1150
- path: `services.${serviceName}.port`,
1151
- value: serviceConfig.port
1152
- });
1153
- }
1154
- usedPorts.add(serviceConfig.port);
1155
- }
1156
- return {
1157
- valid: errors.length === 0,
1158
- errors
1159
- };
1160
- }
1161
-
1162
- // src/generators/dockerfile.ts
1163
- function generateDockerfile(config, _context) {
1164
- const { app, name } = config;
1165
- const { node, workdir, command, buildCommand, multiStage, healthcheck } = app;
1166
- const port = app.port;
1167
- let dockerfile = "";
1168
- if (multiStage) {
1169
- dockerfile += `# Builder stage
1170
- `;
1171
- dockerfile += `FROM node:${node} AS builder
1172
-
1173
- `;
1174
- dockerfile += `WORKDIR ${workdir}
1175
-
1176
- `;
1177
- dockerfile += `# Copy package files
1178
- `;
1179
- dockerfile += `COPY package*.json ./
1180
-
1181
- `;
1182
- dockerfile += `# Install dependencies
1183
- `;
1184
- dockerfile += `RUN npm ci && npm cache clean --force
1185
-
1186
- `;
1187
- dockerfile += `# Copy source files
1188
- `;
1189
- dockerfile += `COPY . .
1190
-
1191
- `;
1192
- dockerfile += `# Build application
1193
- `;
1194
- dockerfile += `RUN npm run build 2>/dev/null || true
1195
-
1196
- `;
1197
- dockerfile += `# Production stage
1198
- `;
1199
- dockerfile += `FROM node:${node}
1200
-
1201
- `;
1202
- dockerfile += `WORKDIR ${workdir}
1203
-
1204
- `;
1205
- dockerfile += `ENV NODE_ENV=production
1206
-
1207
- `;
1208
- dockerfile += `# Copy from builder
1209
- `;
1210
- dockerfile += `COPY --from=builder ${workdir}/node_modules ./node_modules
1211
- `;
1212
- dockerfile += `COPY --from=builder ${workdir}/dist ./dist
1213
- `;
1214
- dockerfile += `COPY --from=builder ${workdir}/package*.json ./
1215
-
1216
- `;
1217
- } else {
1218
- dockerfile += `FROM node:${node}
1219
-
1220
- `;
1221
- dockerfile += `WORKDIR ${workdir}
1222
-
1223
- `;
1224
- dockerfile += `ENV NODE_ENV=production
1225
-
1226
- `;
1227
- dockerfile += `# Copy package files
1228
- `;
1229
- dockerfile += `COPY package*.json ./
1230
-
1231
- `;
1232
- dockerfile += `# Install dependencies
1233
- `;
1234
- dockerfile += `RUN npm ci --only=production && npm cache clean --force
1235
-
1236
- `;
1237
- dockerfile += `# Copy source files
1238
- `;
1239
- dockerfile += `COPY . .
1240
-
1241
- `;
1242
- }
1243
- dockerfile += `EXPOSE ${port}
1244
-
1245
- `;
1246
- if (healthcheck) {
1247
- dockerfile += `HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \\
1248
- CMD node -e "require('http').get('http://localhost:${port}${healthcheck}', (r) => {process.exit(r.statusCode === 200 ? 0 : 1)})" || exit 1
1249
-
1250
- `;
1251
- }
1252
- dockerfile += `CMD ["npm", "start"]
1253
- `;
1254
- return dockerfile;
1255
- }
1256
-
1257
- // src/utils/yaml.ts
1258
- function toYaml(obj, indent = 0) {
1259
- const spaces = " ".repeat(indent);
1260
- if (obj === null) {
1261
- return "null";
1262
- }
1263
- if (typeof obj === "string") {
1264
- return quoteStringIfNeeded(obj);
1265
- }
1266
- if (typeof obj === "number" || typeof obj === "boolean") {
1267
- return String(obj);
1268
- }
1269
- if (Array.isArray(obj)) {
1270
- return arrayToYaml(obj, indent);
1271
- }
1272
- if (typeof obj === "object") {
1273
- return objectToYaml(obj, indent);
1274
- }
1275
- return String(obj);
1276
- }
1277
- function arrayToYaml(arr, indent) {
1278
- const spaces = " ".repeat(indent);
1279
- const innerSpaces = " ".repeat(indent + 2);
1280
- if (arr.length === 0) {
1281
- return "[]";
1282
- }
1283
- if (arr.every(
1284
- (item) => typeof item === "string" || typeof item === "number" || typeof item === "boolean" || item === null
1285
- )) {
1286
- const items = arr.map((item) => toYaml(item, 0)).join(", ");
1287
- return `[${items}]`;
1288
- }
1289
- const lines = [];
1290
- for (const item of arr) {
1291
- const value = toYaml(item, indent + 2);
1292
- if (value.includes("\n")) {
1293
- lines.push(`${spaces}- ${value.slice(indent + 2)}`);
1294
- } else {
1295
- lines.push(`${spaces}- ${value}`);
1296
- }
1297
- }
1298
- return lines.join("\n");
1299
- }
1300
- function objectToYaml(obj, indent) {
1301
- const keys = Object.keys(obj);
1302
- if (keys.length === 0) {
1303
- return "{}";
1304
- }
1305
- const spaces = " ".repeat(indent);
1306
- const lines = [];
1307
- for (const key of keys) {
1308
- const value = obj[key];
1309
- const valueStr = toYaml(value, indent + 2);
1310
- if (valueStr.includes("\n")) {
1311
- lines.push(`${spaces}${key}:`);
1312
- lines.push(valueStr);
1313
- } else {
1314
- lines.push(`${spaces}${key}: ${valueStr}`);
1315
- }
1316
- }
1317
- return lines.join("\n");
1318
- }
1319
- function quoteStringIfNeeded(str) {
1320
- if (str === "" || str.startsWith('"') || str.startsWith("'")) {
1321
- return `"${escapeString(str)}"`;
1322
- }
1323
- if (/^[\-\?:\[\]{},&*#|!<>@%'"`]/.test(str)) {
1324
- return `"${escapeString(str)}"`;
1325
- }
1326
- if (/[:\s#]/.test(str)) {
1327
- return `"${escapeString(str)}"`;
1328
- }
1329
- if (/^(true|false|null|NaN|Infinity|\-?\d+(\.\d+)?)$/.test(str)) {
1330
- return `"${escapeString(str)}"`;
1331
- }
1332
- return escapeString(str);
1333
- }
1334
- function escapeString(str) {
1335
- return str.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t");
1336
- }
1337
-
1338
- // src/generators/compose.ts
1339
- function generateCompose(config, context) {
1340
- const { name, app, services: services2 } = config;
1341
- const compose = {
1342
- version: "3.9",
1343
- services: {
1344
- app: {
1345
- build: ".",
1346
- ports: [`${app.port}:${app.port}`],
1347
- environment: generateAppEnvironment(config, context),
1348
- depends_on: Object.keys(services2),
1349
- volumes: app.volumes.length > 0 ? app.volumes : void 0
1350
- }
1351
- },
1352
- volumes: generateVolumeDefinitions(services2)
1353
- };
1354
- const servicesRecord = compose.services;
1355
- if (app.healthcheck && servicesRecord.app) {
1356
- servicesRecord.app.healthcheck = {
1357
- test: [`CMD`, `curl`, `-f`, `http://localhost:${app.port}${app.healthcheck}`],
1358
- interval: "30s",
1359
- timeout: "3s",
1360
- retries: 3
1361
- };
1362
- }
1363
- for (const [serviceName, serviceConfig] of Object.entries(services2)) {
1364
- servicesRecord[serviceName] = generateServiceConfig(serviceName, serviceConfig);
1365
- }
1366
- return toYaml(compose);
1367
- }
1368
- function generateAppEnvironment(config, context) {
1369
- const env = ["NODE_ENV=production", `PORT=${config.app.port}`];
1370
- for (const [serviceName, serviceConfig] of Object.entries(config.services)) {
1371
- if (serviceConfig.connectionString) {
1372
- const key = `${serviceName.toUpperCase()}_URL`;
1373
- env.push(`${key}=${serviceConfig.connectionString}`);
1374
- }
1375
- }
1376
- if (config.services.postgres) {
1377
- const pg = config.services.postgres;
1378
- env.push(`POSTGRES_HOST=${pg.name}`);
1379
- env.push(`POSTGRES_PORT=${pg.port}`);
1380
- env.push(`POSTGRES_USER=${pg.env.POSTGRES_USER || "postgres"}`);
1381
- env.push(`POSTGRES_PASSWORD=${pg.env.POSTGRES_PASSWORD || "postgres"}`);
1382
- env.push(`POSTGRES_DB=${pg.env.POSTGRES_DB || config.name}`);
1383
- }
1384
- if (config.services.mysql) {
1385
- const mysql = config.services.mysql;
1386
- env.push(`MYSQL_HOST=${mysql.name}`);
1387
- env.push(`MYSQL_PORT=${mysql.port}`);
1388
- env.push(`MYSQL_USER=${mysql.env.MYSQL_USER || "root"}`);
1389
- env.push(`MYSQL_PASSWORD=${mysql.env.MYSQL_PASSWORD || mysql.env.MYSQL_ROOT_PASSWORD || "root"}`);
1390
- env.push(`MYSQL_DATABASE=${mysql.env.MYSQL_DATABASE || config.name}`);
1391
- }
1392
- if (config.services.mongo) {
1393
- const mongo = config.services.mongo;
1394
- env.push(`MONGO_HOST=${mongo.name}`);
1395
- env.push(`MONGO_PORT=${mongo.port}`);
1396
- env.push(`MONGO_USER=${mongo.env.MONGO_INITDB_ROOT_USERNAME || "mongo"}`);
1397
- env.push(`MONGO_PASSWORD=${mongo.env.MONGO_INITDB_ROOT_PASSWORD || "mongo"}`);
1398
- env.push(`MONGO_DATABASE=${mongo.env.MONGO_INITDB_DATABASE || config.name}`);
1399
- }
1400
- if (config.services.redis) {
1401
- const redis = config.services.redis;
1402
- env.push(`REDIS_HOST=${redis.name}`);
1403
- env.push(`REDIS_PORT=${redis.port}`);
1404
- }
1405
- return env;
1406
- }
1407
- function generateServiceConfig(name, config) {
1408
- const service = {
1409
- image: config.image,
1410
- ports: [],
1411
- environment: config.env
1412
- };
1413
- const portMappings = [];
1414
- portMappings.push(`${config.hostPort ?? config.port}:${config.port}`);
1415
- if (config.ports) {
1416
- for (const extraPort of config.ports) {
1417
- portMappings.push(`${extraPort}:${extraPort}`);
1418
- }
1419
- }
1420
- service.ports = portMappings;
1421
- if (config.volumes.length > 0) {
1422
- service.volumes = config.volumes;
1423
- }
1424
- if (config.command) {
1425
- service.command = config.command;
1426
- }
1427
- if (config.healthcheck) {
1428
- service.healthcheck = {
1429
- test: ["CMD-SHELL", config.healthcheck],
1430
- interval: "10s",
1431
- timeout: "5s",
1432
- retries: 5
1433
- };
1434
- }
1435
- return service;
1436
- }
1437
- function generateVolumeDefinitions(services2) {
1438
- const volumes = {};
1439
- for (const serviceConfig of Object.values(services2)) {
1440
- for (const volume of serviceConfig.volumes) {
1441
- if (volume.includes(":")) {
1442
- const [name] = volume.split(":");
1443
- if (name) {
1444
- volumes[name] = null;
1445
- }
1446
- }
1447
- }
1448
- }
1449
- return volumes;
1450
- }
1451
-
1452
- // src/generators/dockerignore.ts
1453
- function generateDockerignore(_config) {
1454
- return `# Dependencies
1455
- node_modules/
1456
- npm-debug.log*
1457
- yarn-debug.log*
1458
- yarn-error.log*
1459
- pnpm-debug.log*
1460
-
1461
- # Environment
1462
- .env
1463
- .env.local
1464
- .env.*.local
1465
-
1466
- # Git
1467
- .git/
1468
- .gitignore
1469
- .gitattributes
1470
-
1471
- # Documentation
1472
- README.md
1473
- CHANGELOG.md
1474
- LICENSE
1475
- SPECIFICATION.md
1476
- IMPLEMENTATION.md
1477
- TASKS.md
1478
- docs/
1479
-
1480
- # IDE
1481
- .vscode/
1482
- .idea/
1483
- *.swp
1484
- *.swo
1485
- *~
1486
- .DS_Store
1487
-
1488
- # Testing
1489
- coverage/
1490
- .nyc_output/
1491
- *.test.ts
1492
- *.spec.ts
1493
- tests/
1494
- vitest.config.ts
1495
-
1496
- # Build
1497
- dist/
1498
- build/
1499
- *.tsbuildinfo
1500
-
1501
- # Temporary
1502
- *.log
1503
- tmp/
1504
- temp/
1505
-
1506
- # CI/CD
1507
- .github/
1508
- .gitlab-ci.yml
1509
- .travis.yml
1510
-
1511
- # Docker
1512
- Dockerfile
1513
- docker-compose.yml
1514
- .dockerignore
1515
-
1516
- # Package manager lockfiles (optional - uncomment if you want to exclude)
1517
- # package-lock.json
1518
- # yarn.lock
1519
- # pnpm-lock.yaml
1520
- `;
1521
- }
1522
-
1523
- // src/generators/env.ts
1524
- function generateEnvExample(config) {
1525
- let content = `# Application Configuration
1526
- NODE_ENV=production
1527
- PORT=${config.app.port}
1528
- `;
1529
- if (config.app.env.length > 0) {
1530
- content += `
1531
- # Required Environment Variables
1532
- `;
1533
- for (const envVar of config.app.env) {
1534
- content += `${envVar}=
1535
- `;
1536
- }
1537
- }
1538
- if (config.services.postgres) {
1539
- const pg = config.services.postgres;
1540
- content += `
1541
- # PostgreSQL
1542
- `;
1543
- content += `DATABASE_URL=${pg.connectionString || ""}
1544
- `;
1545
- content += `POSTGRES_HOST=${pg.name}
1546
- `;
1547
- content += `POSTGRES_PORT=${pg.port}
1548
- `;
1549
- content += `POSTGRES_USER=${pg.env.POSTGRES_USER || "postgres"}
1550
- `;
1551
- content += `POSTGRES_PASSWORD=${pg.env.POSTGRES_PASSWORD || "postgres"}
1552
- `;
1553
- content += `POSTGRES_DB=${pg.env.POSTGRES_DB || config.name}
1554
- `;
1555
- }
1556
- if (config.services.mysql) {
1557
- const mysql = config.services.mysql;
1558
- content += `
1559
- # MySQL
1560
- `;
1561
- content += `MYSQL_URL=${mysql.connectionString || ""}
1562
- `;
1563
- content += `MYSQL_HOST=${mysql.name}
1564
- `;
1565
- content += `MYSQL_PORT=${mysql.port}
1566
- `;
1567
- content += `MYSQL_USER=${mysql.env.MYSQL_USER || "root"}
1568
- `;
1569
- content += `MYSQL_PASSWORD=${mysql.env.MYSQL_PASSWORD || mysql.env.MYSQL_ROOT_PASSWORD || "root"}
1570
- `;
1571
- content += `MYSQL_DATABASE=${mysql.env.MYSQL_DATABASE || config.name}
1572
- `;
1573
- }
1574
- if (config.services.mongo) {
1575
- const mongo = config.services.mongo;
1576
- content += `
1577
- # MongoDB
1578
- `;
1579
- content += `MONGO_URL=${mongo.connectionString || ""}
1580
- `;
1581
- content += `MONGO_HOST=${mongo.name}
1582
- `;
1583
- content += `MONGO_PORT=${mongo.port}
1584
- `;
1585
- content += `MONGO_USER=${mongo.env.MONGO_INITDB_ROOT_USERNAME || "mongo"}
1586
- `;
1587
- content += `MONGO_PASSWORD=${mongo.env.MONGO_INITDB_ROOT_PASSWORD || "mongo"}
1588
- `;
1589
- content += `MONGO_DATABASE=${mongo.env.MONGO_INITDB_DATABASE || config.name}
1590
- `;
1591
- }
1592
- if (config.services.redis) {
1593
- const redis = config.services.redis;
1594
- content += `
1595
- # Redis
1596
- `;
1597
- content += `REDIS_URL=${redis.connectionString || ""}
1598
- `;
1599
- content += `REDIS_HOST=${redis.name}
1600
- `;
1601
- content += `REDIS_PORT=${redis.port}
1602
- `;
1603
- if (redis.env.REDIS_PASSWORD) {
1604
- content += `REDIS_PASSWORD=${redis.env.REDIS_PASSWORD}
1605
- `;
1606
- }
1607
- }
1608
- return content;
1609
- }
1610
-
1611
- // src/generators/scripts.ts
1612
- function generateBuildScript(_config) {
1613
- return `#!/bin/bash
1614
- # Docker build script
1615
-
1616
- set -e
1617
-
1618
- echo "Building Docker image..."
1619
- docker-compose build
1620
-
1621
- echo "Build complete!"
1622
- `;
1623
- }
1624
- function generateUpScript(config) {
1625
- const services2 = ["app", ...Object.keys(config.services)];
1626
- return `#!/bin/bash
1627
- # Docker up script
1628
-
1629
- set -e
1630
-
1631
- echo "Starting services..."
1632
- docker-compose up -d ${services2.join(" ")}
1633
-
1634
- echo "Services started!"
1635
- echo ""
1636
- echo "App running at http://localhost:${config.app.port}"
1637
- `;
1638
- }
1639
- function generateDownScript(_config) {
1640
- return `#!/bin/bash
1641
- # Docker down script
1642
-
1643
- set -e
1644
-
1645
- echo "Stopping services..."
1646
- docker-compose down
1647
-
1648
- echo "Services stopped!"
1649
- `;
1650
- }
1651
- function generateLogsScript(_config) {
1652
- return `#!/bin/bash
1653
- # Docker logs script
1654
-
1655
- set -e
1656
-
1657
- if [ -n "$1" ]; then
1658
- docker-compose logs -f "$1"
1659
- else
1660
- docker-compose logs -f
1661
- fi
1662
- `;
1663
- }
1664
- function generateScripts(config) {
1665
- return {
1666
- "docker-build.sh": generateBuildScript(config),
1667
- "docker-up.sh": generateUpScript(config),
1668
- "docker-down.sh": generateDownScript(config),
1669
- "docker-logs.sh": generateLogsScript(config)
1670
- };
1671
- }
1672
-
1673
- // src/generators/makefile.ts
1674
- function generateMakefile(config) {
1675
- const services2 = Object.keys(config.services);
1676
- let content = `.PHONY: help build up down restart logs clean install shell
1677
-
1678
- # Default target
1679
- help:
1680
- @echo "Available targets:"
1681
- @echo " make build - Build Docker images"
1682
- @echo " make up - Start all services"
1683
- @echo " make down - Stop all services"
1684
- @echo " make restart - Restart all services"
1685
- @echo " make logs - Show logs from all services"
1686
- @echo " make shell - Open shell in app container"
1687
- @echo " make clean - Remove containers and volumes"
1688
- @echo " make install - Install dependencies"
1689
-
1690
- # Build Docker images
1691
- build:
1692
- docker-compose build
1693
-
1694
- # Start all services
1695
- up:
1696
- docker-compose up -d
1697
- @echo "App running at http://localhost:${config.app.port}"
1698
-
1699
- # Stop all services
1700
- down:
1701
- docker-compose down
1702
-
1703
- # Restart all services
1704
- restart: down up
1705
-
1706
- # Show logs from all services
1707
- logs:
1708
- docker-compose logs -f
1709
- `;
1710
- if (services2.length > 0) {
1711
- content += "\n";
1712
- for (const service of services2) {
1713
- content += `
1714
- logs-${service}:
1715
- `;
1716
- content += ` docker-compose logs -f ${service}
1717
- `;
1718
- }
1719
- }
1720
- content += `
1721
- # Clean up containers and volumes
1722
- clean:
1723
- docker-compose down -v
1724
- docker system prune -f
1725
-
1726
- # Install dependencies (in running container)
1727
- shell:
1728
- docker-compose exec app sh
1729
-
1730
- # Install dependencies
1731
- install:
1732
- docker-compose exec app npm install
1733
- `;
1734
- return content;
1735
- }
1736
-
1737
- // src/generators/index.ts
1738
- var GENERATORS = {
1739
- dockerfile: { file: "Dockerfile", generate: generateDockerfile },
1740
- compose: { file: "docker-compose.yml", generate: generateCompose },
1741
- dockerignore: { file: ".dockerignore", generate: generateDockerignore },
1742
- env: { file: ".env.example", generate: generateEnvExample },
1743
- scripts: { file: "scripts", generate: () => "" },
1744
- // Special handling
1745
- makefile: { file: "Makefile", generate: generateMakefile }
1746
- };
1747
- function generateAll(config, context) {
1748
- const result = {};
1749
- const filesToGenerate = config.output.files ?? Object.keys(GENERATORS);
1750
- for (const fileType of filesToGenerate) {
1751
- if (fileType === "scripts") {
1752
- const scripts = generateScripts(config);
1753
- for (const [name, content] of Object.entries(scripts)) {
1754
- result[name] = content;
1755
- }
1756
- } else {
1757
- const generator = GENERATORS[fileType];
1758
- if (generator) {
1759
- result[generator.file] = generator.generate(config, context);
1760
- }
1761
- }
1762
- }
1763
- return result;
1764
- }
1765
-
1766
- // src/core/dockcraft.ts
1767
- var import_path2 = require("path");
1768
- async function dockcraft(config, options = {}) {
1769
- const validation = validateConfig(config);
1770
- if (!validation.valid) {
1771
- const errorMessages = validation.errors.map((e) => ` - ${e.message}`).join("\n");
1772
- throw new Error(
1773
- `Configuration validation failed:
1774
- ${errorMessages}`
1775
- );
1776
- }
1777
- const resolved = await resolveConfig(config);
1778
- const resolvedValidation = validateResolvedConfig(resolved);
1779
- if (!resolvedValidation.valid) {
1780
- const errorMessages = resolvedValidation.errors.map((e) => ` - ${e.message}`).join("\n");
1781
- throw new Error(
1782
- `Resolved configuration validation failed:
1783
- ${errorMessages}`
1784
- );
1785
- }
1786
- const context = {
1787
- config: resolved,
1788
- ports: new Map(
1789
- Object.entries(resolved.services).map(([name, svc]) => [name, svc.port])
1790
- ),
1791
- strings: new Map(
1792
- Object.entries(resolved.services).filter(([, svc]) => svc.connectionString).map(([name, svc]) => [name, svc.connectionString])
1793
- )
1794
- };
1795
- context.ports.set("app", resolved.app.port);
1796
- const generated = generateAll(resolved, context);
1797
- const written = [];
1798
- const outputDir = resolved.output.dir ?? "./";
1799
- if (!options.dryRun) {
1800
- for (const [fileName, content] of Object.entries(generated)) {
1801
- if (!fileName) continue;
1802
- const filePath = (0, import_path2.join)(outputDir, fileName);
1803
- const exists = await fileExists(filePath);
1804
- if (exists && !resolved.output.overwrite) {
1805
- continue;
1806
- }
1807
- await writeFile(filePath, content);
1808
- written.push(filePath);
1809
- }
1810
- }
1811
- return {
1812
- files: new Map(Object.entries(generated)),
1813
- written,
1814
- config: resolved
1815
- };
1816
- }
1817
-
1818
- // src/cli/commands/generate.ts
1819
- async function generate(args) {
1820
- title("Dockcraft Generate");
1821
- const configPath = getOption(args, "config", "./dockcraft.config.ts");
1822
- const dryRun = getBooleanFlag(args, "dry-run");
1823
- const force = getBooleanFlag(args, "force");
1824
- const outputDir = getOption(args, "output", "./");
1825
- try {
1826
- subtitle(`Loading config from: ${configPath}`);
1827
- const config = await loadConfig(configPath);
1828
- if (force) {
1829
- config.output = config.output ?? {};
1830
- config.output.overwrite = true;
1831
- }
1832
- if (outputDir !== "./") {
1833
- config.output = config.output ?? {};
1834
- config.output.dir = outputDir;
1835
- }
1836
- const result = await dockcraft(config, { dryRun });
1837
- if (dryRun) {
1838
- subtitle("Preview (dry-run mode):");
1839
- for (const [fileName, content] of result.files) {
1840
- console.log("");
1841
- console.log(`File: ${fileName}`);
1842
- console.log("\u2500".repeat(50));
1843
- console.log(content);
1844
- console.log("\u2500".repeat(50));
1845
- }
1846
- } else {
1847
- success(`Generated ${result.written.length} files:`);
1848
- list(result.written);
1849
- console.log("");
1850
- success('Done! Run "docker-compose up -d" to start services');
1851
- }
1852
- } catch (err) {
1853
- error(err instanceof Error ? err.message : String(err));
1854
- process.exit(1);
1855
- }
1856
- }
1857
-
1858
- // src/ports/defaults.ts
1859
- var DEFAULT_PORTS = {
1860
- postgres: 5432,
1861
- mysql: 3306,
1862
- mongo: 27017,
1863
- mongodb: 27017,
1864
- redis: 6379,
1865
- elasticsearch: 9200,
1866
- rabbitmq: 5672,
1867
- memcached: 11211,
1868
- nginx: 80,
1869
- apache: 80
1870
- };
1871
- function listDefaultPorts() {
1872
- return { ...DEFAULT_PORTS };
1873
- }
1874
-
1875
- // src/cli/commands/ports.ts
1876
- async function ports(args) {
1877
- title("Port Utilities");
1878
- const checkOption = getOption(args, "check");
1879
- const rangeOption = getOption(args, "range");
1880
- const asJson = getBooleanFlag(args, "json");
1881
- if (checkOption) {
1882
- const portsToCheck = checkOption.split(",").map((s) => parseInt(s.trim(), 10));
1883
- const results = await checkPorts(portsToCheck);
1884
- if (asJson) {
1885
- json(Object.fromEntries(results));
1886
- } else {
1887
- table(["Port", "Status"], [
1888
- ...Array.from(results.entries()).map(([port, available]) => [
1889
- String(port),
1890
- available ? "\u2713 Available" : "\u2717 In use"
1891
- ])
1892
- ]);
1893
- }
1894
- return;
1895
- }
1896
- if (rangeOption) {
1897
- const match = rangeOption.match(/^(\d+)-(\d+)$/);
1898
- if (!match || !match[1] || !match[2]) {
1899
- throw new Error("Invalid range format. Use: --range START-END (e.g., 3000-3010)");
1900
- }
1901
- const start = parseInt(match[1], 10);
1902
- const end = parseInt(match[2], 10);
1903
- if (asJson) {
1904
- const port = await findAvailablePortInRange(start, end);
1905
- json({ available: port });
1906
- } else {
1907
- const port = await findAvailablePortInRange(start, end);
1908
- if (port) {
1909
- success(`Found available port: ${port} in range ${start}-${end}`);
1910
- } else {
1911
- console.log(`No available port in range ${start}-${end}`);
1912
- }
1913
- }
1914
- return;
1915
- }
1916
- const defaults = listDefaultPorts();
1917
- if (asJson) {
1918
- json(defaults);
1919
- } else {
1920
- subtitle("Default service ports:");
1921
- table(["Service", "Port"], [
1922
- ...Object.entries(defaults).map(([service, port]) => [service, String(port)])
1923
- ]);
1924
- }
1925
- }
1926
-
1927
- // src/cli/commands/presets.ts
1928
- function presets2(args) {
1929
- const presetName = args.positionals[0];
1930
- if (presetName) {
1931
- const preset = getPreset(presetName);
1932
- if (!preset) {
1933
- console.log(`Preset '${presetName}' not found`);
1934
- return;
1935
- }
1936
- title(`Preset: ${presetName}`);
1937
- if (preset.description) {
1938
- subtitle("Description");
1939
- console.log(` ${preset.description}`);
1940
- }
1941
- if (preset.app) {
1942
- subtitle("App Configuration");
1943
- const appConfig = {};
1944
- if (preset.app.port) appConfig.port = String(preset.app.port);
1945
- if (preset.app.node) appConfig.node = preset.app.node;
1946
- if (preset.app.command) appConfig.command = preset.app.command;
1947
- kv(appConfig);
1948
- }
1949
- if (preset.services && Object.keys(preset.services).length > 0) {
1950
- subtitle("Services");
1951
- list(Object.keys(preset.services));
1952
- }
1953
- } else {
1954
- title("Available Presets");
1955
- const presets3 = listPresets();
1956
- list(presets3);
1957
- console.log("");
1958
- console.log('Run "dockcraft presets <name>" to see preset details');
1959
- }
1960
- }
1961
-
1962
- // src/cli/index.ts
1963
- var VERSION = "1.0.0";
1964
- var commands = /* @__PURE__ */ new Map();
1965
- commands.set("init", init);
1966
- commands.set("generate", generate);
1967
- commands.set("ports", ports);
1968
- commands.set("presets", presets2);
1969
- function showHelp(command) {
1970
- if (command) {
1971
- showCommandHelp(command);
1972
- } else {
1973
- showGeneralHelp();
1974
- }
1975
- }
1976
- function showGeneralHelp() {
1977
- console.log(`
1978
- @oxog/dockcraft - Zero-Dependency Docker Orchestration Toolkit
1979
-
1980
- VERSION:
1981
- ${VERSION}
1982
-
1983
- USAGE:
1984
- dockcraft <command> [options]
1985
-
1986
- COMMANDS:
1987
- init Initialize a new dockcraft configuration
1988
- generate Generate Docker files from config
1989
- ports Check port availability
1990
- presets List available presets
1991
-
1992
- GLOBAL OPTIONS:
1993
- -h, --help Show this help message
1994
- -v, --version Show version information
1995
-
1996
- Run "dockcraft <command> --help" for command-specific help.
1997
- `);
1998
- }
1999
- function showCommandHelp(command) {
2000
- switch (command) {
2001
- case "init":
2002
- console.log(`
2003
- USAGE:
2004
- dockcraft init [options]
2005
-
2006
- OPTIONS:
2007
- --preset <name> Use a preset configuration
2008
- --name <name> Project name
2009
- --port <port> App port
2010
- --services <list> Comma-separated service list
2011
- --output <dir> Output directory
2012
- -y, --yes Skip prompts, use defaults
2013
- `);
2014
- break;
2015
- case "generate":
2016
- console.log(`
2017
- USAGE:
2018
- dockcraft generate [options]
2019
-
2020
- OPTIONS:
2021
- --config <file> Config file path (default: dockcraft.config.ts)
2022
- --dry-run Preview without writing
2023
- --force Overwrite existing files
2024
- --output <dir> Output directory
2025
- `);
2026
- break;
2027
- case "ports":
2028
- console.log(`
2029
- USAGE:
2030
- dockcraft ports [options]
2031
-
2032
- OPTIONS:
2033
- --check <ports> Check specific ports (comma-separated)
2034
- --range <start-end> Scan port range
2035
- --json Output as JSON
2036
- `);
2037
- break;
2038
- case "presets":
2039
- console.log(`
2040
- USAGE:
2041
- dockcraft presets [name]
2042
-
2043
- ARGUMENTS:
2044
- name Preset name to show details
2045
- `);
2046
- break;
2047
- default:
2048
- console.log(`Unknown command: ${command}`);
2049
- }
2050
- }
2051
- function showVersion() {
2052
- console.log(`@oxog/dockcraft v${VERSION}`);
2053
- }
2054
- async function main(cliArgs = process.argv.slice(2)) {
2055
- const args = parseArgs(cliArgs);
2056
- if (!args.command) {
2057
- if (args.flags.has("version") || args.flags.has("v")) {
2058
- showVersion();
2059
- return;
2060
- }
2061
- showHelp();
2062
- return;
2063
- }
2064
- if (args.flags.has("help") || args.flags.has("h")) {
2065
- showHelp(args.command);
2066
- return;
2067
- }
2068
- if (args.flags.has("version") || args.flags.has("v")) {
2069
- showVersion();
2070
- return;
2071
- }
2072
- const handler = commands.get(args.command);
2073
- if (!handler) {
2074
- error(`Unknown command: ${args.command}`);
2075
- console.log('Run "dockcraft --help" for usage information.');
2076
- process.exit(1);
2077
- }
2078
- try {
2079
- await handler(args);
2080
- } catch (err) {
2081
- error(err instanceof Error ? err.message : String(err));
2082
- process.exit(1);
2083
- }
2084
- }
2085
- if (importMetaUrl === `file://${process.argv[1]}`) {
2086
- main().catch((err) => {
2087
- error(err instanceof Error ? err.message : String(err));
2088
- process.exit(1);
2089
- });
2090
- }
2091
- // Annotate the CommonJS export names for ESM import in node:
2092
- 0 && (module.exports = {
2093
- main
2094
- });
2095
- //# sourceMappingURL=index.cjs.map