@oxog/dockcraft 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,1604 @@
1
+ /**
2
+ * @oxog/dockcraft - Zero-Dependency NPM Package
3
+ * GitHub: https://github.com/ersinkoc/dockcraft
4
+ * License: MIT
5
+ */
6
+
7
+ // src/presets/express-postgres.ts
8
+ var expressPostgresPreset = {
9
+ description: "Express application with PostgreSQL database",
10
+ app: {
11
+ port: 3e3,
12
+ node: "20-alpine",
13
+ workdir: "/app",
14
+ command: "npm start",
15
+ buildCommand: "npm run build",
16
+ multiStage: true,
17
+ healthcheck: "/health"
18
+ },
19
+ services: {
20
+ postgres: {
21
+ version: "16"
22
+ }
23
+ }
24
+ };
25
+
26
+ // src/presets/express-postgres-redis.ts
27
+ var expressPostgresRedisPreset = {
28
+ description: "Express application with PostgreSQL database and Redis cache",
29
+ app: {
30
+ port: 3e3,
31
+ node: "20-alpine",
32
+ workdir: "/app",
33
+ command: "npm start",
34
+ buildCommand: "npm run build",
35
+ multiStage: true,
36
+ healthcheck: "/health"
37
+ },
38
+ services: {
39
+ postgres: {
40
+ version: "16"
41
+ },
42
+ redis: {
43
+ version: "7-alpine"
44
+ }
45
+ }
46
+ };
47
+
48
+ // src/presets/express-mongo.ts
49
+ var expressMongoPreset = {
50
+ description: "Express application with MongoDB database",
51
+ app: {
52
+ port: 3e3,
53
+ node: "20-alpine",
54
+ workdir: "/app",
55
+ command: "npm start",
56
+ buildCommand: "npm run build",
57
+ multiStage: true,
58
+ healthcheck: "/health"
59
+ },
60
+ services: {
61
+ mongo: {
62
+ version: "7"
63
+ }
64
+ }
65
+ };
66
+
67
+ // src/presets/express-mongo-redis.ts
68
+ var expressMongoRedisPreset = {
69
+ description: "Express application with MongoDB database and Redis cache",
70
+ app: {
71
+ port: 3e3,
72
+ node: "20-alpine",
73
+ workdir: "/app",
74
+ command: "npm start",
75
+ buildCommand: "npm run build",
76
+ multiStage: true,
77
+ healthcheck: "/health"
78
+ },
79
+ services: {
80
+ mongo: {
81
+ version: "7"
82
+ },
83
+ redis: {
84
+ version: "7-alpine"
85
+ }
86
+ }
87
+ };
88
+
89
+ // src/presets/express-mysql.ts
90
+ var expressMysqlPreset = {
91
+ description: "Express application with MySQL database",
92
+ app: {
93
+ port: 3e3,
94
+ node: "20-alpine",
95
+ workdir: "/app",
96
+ command: "npm start",
97
+ buildCommand: "npm run build",
98
+ multiStage: true,
99
+ healthcheck: "/health"
100
+ },
101
+ services: {
102
+ mysql: {
103
+ version: "8"
104
+ }
105
+ }
106
+ };
107
+
108
+ // src/presets/express-mysql-redis.ts
109
+ var expressMysqlRedisPreset = {
110
+ description: "Express application with MySQL database and Redis cache",
111
+ app: {
112
+ port: 3e3,
113
+ node: "20-alpine",
114
+ workdir: "/app",
115
+ command: "npm start",
116
+ buildCommand: "npm run build",
117
+ multiStage: true,
118
+ healthcheck: "/health"
119
+ },
120
+ services: {
121
+ mysql: {
122
+ version: "8"
123
+ },
124
+ redis: {
125
+ version: "7-alpine"
126
+ }
127
+ }
128
+ };
129
+
130
+ // src/presets/fastify-postgres.ts
131
+ var fastifyPostgresPreset = {
132
+ description: "Fastify application with PostgreSQL database",
133
+ app: {
134
+ port: 3e3,
135
+ node: "20-alpine",
136
+ workdir: "/app",
137
+ command: "npm start",
138
+ buildCommand: "npm run build",
139
+ multiStage: true,
140
+ healthcheck: "/health"
141
+ },
142
+ services: {
143
+ postgres: {
144
+ version: "16"
145
+ }
146
+ }
147
+ };
148
+
149
+ // src/presets/fastify-postgres-redis.ts
150
+ var fastifyPostgresRedisPreset = {
151
+ description: "Fastify application with PostgreSQL database and Redis cache",
152
+ app: {
153
+ port: 3e3,
154
+ node: "20-alpine",
155
+ workdir: "/app",
156
+ command: "npm start",
157
+ buildCommand: "npm run build",
158
+ multiStage: true,
159
+ healthcheck: "/health"
160
+ },
161
+ services: {
162
+ postgres: {
163
+ version: "16"
164
+ },
165
+ redis: {
166
+ version: "7-alpine"
167
+ }
168
+ }
169
+ };
170
+
171
+ // src/presets/nest-postgres.ts
172
+ var nestPostgresPreset = {
173
+ description: "NestJS application with PostgreSQL database",
174
+ app: {
175
+ port: 3e3,
176
+ node: "20-alpine",
177
+ workdir: "/app",
178
+ command: "npm run start:prod",
179
+ buildCommand: "npm run build",
180
+ multiStage: true,
181
+ healthcheck: "/health"
182
+ },
183
+ services: {
184
+ postgres: {
185
+ version: "16"
186
+ }
187
+ }
188
+ };
189
+
190
+ // src/presets/nest-mongo.ts
191
+ var nestMongoPreset = {
192
+ description: "NestJS application with MongoDB database",
193
+ app: {
194
+ port: 3e3,
195
+ node: "20-alpine",
196
+ workdir: "/app",
197
+ command: "npm run start:prod",
198
+ buildCommand: "npm run build",
199
+ multiStage: true,
200
+ healthcheck: "/health"
201
+ },
202
+ services: {
203
+ mongo: {
204
+ version: "7"
205
+ }
206
+ }
207
+ };
208
+
209
+ // src/presets/node-minimal.ts
210
+ var nodeMinimalPreset = {
211
+ description: "Minimal Node.js application setup",
212
+ app: {
213
+ port: 3e3,
214
+ node: "20-alpine",
215
+ workdir: "/app",
216
+ command: "npm start",
217
+ multiStage: true
218
+ },
219
+ services: {}
220
+ };
221
+
222
+ // src/presets/index.ts
223
+ var presets = /* @__PURE__ */ new Map();
224
+ function registerPreset(name, config) {
225
+ presets.set(name, config);
226
+ }
227
+ function getPreset(name) {
228
+ return presets.get(name);
229
+ }
230
+ function listPresets() {
231
+ return Array.from(presets.keys());
232
+ }
233
+ registerPreset("express-postgres", expressPostgresPreset);
234
+ registerPreset("express-postgres-redis", expressPostgresRedisPreset);
235
+ registerPreset("express-mongo", expressMongoPreset);
236
+ registerPreset("express-mongo-redis", expressMongoRedisPreset);
237
+ registerPreset("express-mysql", expressMysqlPreset);
238
+ registerPreset("express-mysql-redis", expressMysqlRedisPreset);
239
+ registerPreset("fastify-postgres", fastifyPostgresPreset);
240
+ registerPreset("fastify-postgres-redis", fastifyPostgresRedisPreset);
241
+ registerPreset("nest-postgres", nestPostgresPreset);
242
+ registerPreset("nest-mongo", nestMongoPreset);
243
+ registerPreset("node-minimal", nodeMinimalPreset);
244
+
245
+ // src/services/postgres.ts
246
+ var postgresService = {
247
+ name: "postgres",
248
+ image: (version) => `postgres:${version}-alpine`,
249
+ defaultPort: 5432,
250
+ defaultVersion: "16",
251
+ env: {
252
+ POSTGRES_USER: "postgres",
253
+ POSTGRES_PASSWORD: "postgres",
254
+ POSTGRES_DB: "myapp"
255
+ },
256
+ volumes: ["postgres_data:/var/lib/postgresql/data"],
257
+ healthcheck: "pg_isready -U postgres",
258
+ ports: [],
259
+ connectionString: (config) => {
260
+ const user = config.env.POSTGRES_USER || "postgres";
261
+ const password = config.env.POSTGRES_PASSWORD || "postgres";
262
+ const database = config.env.POSTGRES_DB || "myapp";
263
+ const host = config.name;
264
+ const port = config.port;
265
+ return `postgres://${user}:${password}@${host}:${port}/${database}`;
266
+ }
267
+ };
268
+
269
+ // src/services/mysql.ts
270
+ var mysqlService = {
271
+ name: "mysql",
272
+ image: (version) => `mysql:${version}`,
273
+ defaultPort: 3306,
274
+ defaultVersion: "8",
275
+ env: {
276
+ MYSQL_ROOT_PASSWORD: "root",
277
+ MYSQL_DATABASE: "myapp",
278
+ MYSQL_USER: "mysql",
279
+ MYSQL_PASSWORD: "mysql"
280
+ },
281
+ volumes: ["mysql_data:/var/lib/mysql"],
282
+ healthcheck: "mysqladmin ping -h localhost",
283
+ ports: [],
284
+ connectionString: (config) => {
285
+ const user = config.env.MYSQL_USER || "root";
286
+ const password = config.env.MYSQL_PASSWORD || config.env.MYSQL_ROOT_PASSWORD || "root";
287
+ const database = config.env.MYSQL_DATABASE || "myapp";
288
+ const host = config.name;
289
+ const port = config.port;
290
+ return `mysql://${user}:${password}@${host}:${port}/${database}`;
291
+ }
292
+ };
293
+
294
+ // src/services/mongo.ts
295
+ var mongoService = {
296
+ name: "mongo",
297
+ image: (version) => `mongo:${version}`,
298
+ defaultPort: 27017,
299
+ defaultVersion: "7",
300
+ env: {
301
+ MONGO_INITDB_ROOT_USERNAME: "mongo",
302
+ MONGO_INITDB_ROOT_PASSWORD: "mongo",
303
+ MONGO_INITDB_DATABASE: "myapp"
304
+ },
305
+ volumes: ["mongo_data:/data/db"],
306
+ healthcheck: 'mongosh --eval "db.adminCommand({ ping: 1 })"',
307
+ ports: [],
308
+ connectionString: (config) => {
309
+ const user = config.env.MONGO_INITDB_ROOT_USERNAME || "mongo";
310
+ const password = config.env.MONGO_INITDB_ROOT_PASSWORD || "mongo";
311
+ const database = config.env.MONGO_INITDB_DATABASE || "myapp";
312
+ const host = config.name;
313
+ const port = config.port;
314
+ return `mongodb://${user}:${password}@${host}:${port}/${database}`;
315
+ }
316
+ };
317
+
318
+ // src/services/redis.ts
319
+ var redisService = {
320
+ name: "redis",
321
+ image: (version) => `redis:${version}-alpine`,
322
+ defaultPort: 6379,
323
+ defaultVersion: "7",
324
+ env: {},
325
+ volumes: ["redis_data:/data"],
326
+ healthcheck: "redis-cli ping",
327
+ ports: [],
328
+ connectionString: (config) => {
329
+ const host = config.name;
330
+ const port = config.port;
331
+ return `redis://${host}:${port}`;
332
+ }
333
+ };
334
+
335
+ // src/services/index.ts
336
+ var services = /* @__PURE__ */ new Map();
337
+ function registerService(def) {
338
+ services.set(def.name, def);
339
+ }
340
+ function getService(name) {
341
+ return services.get(name);
342
+ }
343
+ function listServices() {
344
+ return Array.from(services.keys());
345
+ }
346
+ registerService(postgresService);
347
+ registerService(mysqlService);
348
+ registerService(mongoService);
349
+ registerService(redisService);
350
+
351
+ // src/utils/merge.ts
352
+ function deepMerge(...objects) {
353
+ const result = {};
354
+ for (const obj of objects) {
355
+ if (obj === null || typeof obj !== "object") continue;
356
+ for (const [key, value] of Object.entries(obj)) {
357
+ if (value === void 0) continue;
358
+ if (value && typeof value === "object" && !Array.isArray(value) && result[key] && typeof result[key] === "object" && !Array.isArray(result[key])) {
359
+ result[key] = deepMerge(result[key], value);
360
+ } else {
361
+ result[key] = value;
362
+ }
363
+ }
364
+ }
365
+ return result;
366
+ }
367
+
368
+ // src/ports/scanner.ts
369
+ import { createServer } from "net";
370
+ async function isPortAvailable(port) {
371
+ return new Promise((resolve) => {
372
+ const server = createServer();
373
+ server.once("error", () => {
374
+ resolve(false);
375
+ });
376
+ server.once("listening", () => {
377
+ server.close(() => {
378
+ resolve(true);
379
+ });
380
+ });
381
+ server.listen(port, "127.0.0.1");
382
+ setTimeout(() => {
383
+ server.close();
384
+ resolve(false);
385
+ }, 1e3);
386
+ });
387
+ }
388
+ async function checkPorts(ports) {
389
+ const results = /* @__PURE__ */ new Map();
390
+ await Promise.all(
391
+ ports.map(async (port) => {
392
+ results.set(port, await isPortAvailable(port));
393
+ })
394
+ );
395
+ return results;
396
+ }
397
+ async function findNextAvailablePort(startPort, maxPort = 65535) {
398
+ for (let port = startPort; port <= maxPort; port++) {
399
+ if (await isPortAvailable(port)) {
400
+ return port;
401
+ }
402
+ }
403
+ return void 0;
404
+ }
405
+ async function findAvailablePortInRange(start, end) {
406
+ for (let port = start; port <= end; port++) {
407
+ if (await isPortAvailable(port)) {
408
+ return port;
409
+ }
410
+ }
411
+ return void 0;
412
+ }
413
+ async function resolvePort(options = {}) {
414
+ const {
415
+ preferred = 3e3,
416
+ strategy = "auto",
417
+ range
418
+ } = options;
419
+ switch (strategy) {
420
+ case "fixed":
421
+ if (await isPortAvailable(preferred)) {
422
+ return preferred;
423
+ }
424
+ throw new Error(`Port ${preferred} is already in use`);
425
+ case "range":
426
+ if (range) {
427
+ const [start, end = start + 100] = range;
428
+ const port2 = await findAvailablePortInRange(start, end);
429
+ if (port2 !== void 0) {
430
+ return port2;
431
+ }
432
+ throw new Error(`No available port in range ${start}-${end}`);
433
+ }
434
+ // Fall through to auto if no range specified
435
+ case "auto":
436
+ default:
437
+ const port = await findNextAvailablePort(preferred);
438
+ if (port !== void 0) {
439
+ return port;
440
+ }
441
+ throw new Error(`No available port found starting from ${preferred}`);
442
+ }
443
+ }
444
+
445
+ // src/core/config.ts
446
+ var DEFAULT_APP_CONFIG = {
447
+ port: 3e3,
448
+ node: "20-alpine",
449
+ workdir: "/app",
450
+ command: "npm start",
451
+ buildCommand: "npm run build",
452
+ env: [],
453
+ volumes: [],
454
+ multiStage: true
455
+ };
456
+ function normalizeAppConfig(config) {
457
+ return {
458
+ port: config.port === "auto" ? 3e3 : config.port,
459
+ node: config.node ?? DEFAULT_APP_CONFIG.node,
460
+ workdir: config.workdir ?? DEFAULT_APP_CONFIG.workdir,
461
+ command: config.command ?? DEFAULT_APP_CONFIG.command,
462
+ buildCommand: config.buildCommand ?? DEFAULT_APP_CONFIG.buildCommand,
463
+ env: config.env ?? DEFAULT_APP_CONFIG.env,
464
+ volumes: config.volumes ?? DEFAULT_APP_CONFIG.volumes,
465
+ multiStage: config.multiStage ?? DEFAULT_APP_CONFIG.multiStage,
466
+ healthcheck: config.healthcheck
467
+ };
468
+ }
469
+ function normalizeOutputConfig(config) {
470
+ return {
471
+ dir: config?.dir ?? "./",
472
+ files: config?.files ?? ["dockerfile", "compose", "dockerignore", "env"],
473
+ overwrite: config?.overwrite ?? false
474
+ };
475
+ }
476
+ function normalizeConfig(config) {
477
+ return {
478
+ name: config.name,
479
+ preset: config.preset,
480
+ app: config.app,
481
+ services: config.services ?? {},
482
+ output: normalizeOutputConfig(config.output),
483
+ plugins: config.plugins ?? []
484
+ };
485
+ }
486
+
487
+ // src/core/resolver.ts
488
+ function mergePreset(config, presetName) {
489
+ const preset = getPreset(presetName);
490
+ if (!preset) {
491
+ throw new Error(`Preset '${presetName}' not found`);
492
+ }
493
+ const merged = deepMerge(
494
+ {
495
+ name: config.name,
496
+ app: preset.app ?? {},
497
+ services: preset.services ?? {},
498
+ output: preset.output ?? {}
499
+ },
500
+ config
501
+ );
502
+ return merged;
503
+ }
504
+ async function resolveServiceConfig(name, config, projectName) {
505
+ if ("image" in config && config.image) {
506
+ return resolveCustomService(name, config);
507
+ }
508
+ const definition = getService(name);
509
+ 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;
527
+ }
528
+ const version = config.version ?? definition.defaultVersion;
529
+ const image = typeof definition.image === "function" ? definition.image(version) : definition.image;
530
+ const env = { ...definition.env, ...config.env };
531
+ if (name === "postgres") {
532
+ const pgConfig = config;
533
+ if (pgConfig.database) env.POSTGRES_DB = pgConfig.database;
534
+ if (pgConfig.user) env.POSTGRES_USER = pgConfig.user;
535
+ if (pgConfig.password) env.POSTGRES_PASSWORD = pgConfig.password;
536
+ if (!env.POSTGRES_DB) env.POSTGRES_DB = projectName;
537
+ } else if (name === "mysql") {
538
+ const mysqlConfig = config;
539
+ if (mysqlConfig.database) env.MYSQL_DATABASE = mysqlConfig.database;
540
+ if (mysqlConfig.user) env.MYSQL_USER = mysqlConfig.user;
541
+ if (mysqlConfig.password) env.MYSQL_PASSWORD = mysqlConfig.password;
542
+ if (mysqlConfig.rootPassword) env.MYSQL_ROOT_PASSWORD = mysqlConfig.rootPassword;
543
+ if (!env.MYSQL_DATABASE) env.MYSQL_DATABASE = projectName;
544
+ } else if (name === "mongo") {
545
+ const mongoConfig = config;
546
+ if (mongoConfig.database) env.MONGO_INITDB_DATABASE = mongoConfig.database;
547
+ if (mongoConfig.user) env.MONGO_INITDB_ROOT_USERNAME = mongoConfig.user;
548
+ if (mongoConfig.password) env.MONGO_INITDB_ROOT_PASSWORD = mongoConfig.password;
549
+ if (!env.MONGO_INITDB_DATABASE) env.MONGO_INITDB_DATABASE = projectName;
550
+ } else if (name === "redis") {
551
+ const redisConfig = config;
552
+ if (redisConfig.password) env.REDIS_PASSWORD = redisConfig.password;
553
+ }
554
+ const volumes = [...definition.volumes ?? [], ...config.volumes ?? []];
555
+ const resolvedConfig = {
556
+ name,
557
+ image,
558
+ port,
559
+ hostPort,
560
+ env,
561
+ volumes,
562
+ command: config.command,
563
+ healthcheck: definition.healthcheck,
564
+ ports: definition.ports
565
+ };
566
+ if (definition.connectionString) {
567
+ resolvedConfig.connectionString = definition.connectionString(resolvedConfig);
568
+ }
569
+ return resolvedConfig;
570
+ }
571
+ 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;
588
+ }
589
+ return {
590
+ name,
591
+ image: config.image,
592
+ port,
593
+ hostPort,
594
+ env: config.env ?? {},
595
+ volumes: config.volumes ?? [],
596
+ command: config.command,
597
+ healthcheck: config.command,
598
+ ports: []
599
+ };
600
+ }
601
+ async function resolveConfig(config) {
602
+ let finalConfig = config;
603
+ if (config.preset) {
604
+ finalConfig = mergePreset(config, config.preset);
605
+ }
606
+ 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 });
609
+ 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
+ }
619
+ }
620
+ }
621
+ return {
622
+ name: finalConfig.name,
623
+ app,
624
+ services: services2,
625
+ output: normalizeOutputConfig(finalConfig.output)
626
+ };
627
+ }
628
+
629
+ // src/utils/validation.ts
630
+ var MIN_PORT = 1;
631
+ var MAX_PORT = 65535;
632
+ function isPort(value) {
633
+ return typeof value === "number" && Number.isInteger(value) && value >= MIN_PORT && value <= MAX_PORT;
634
+ }
635
+ function isEnvVarName(value) {
636
+ if (typeof value !== "string") return false;
637
+ return /^[A-Z_][A-Z0-9_]*$/.test(value);
638
+ }
639
+ function isVersion(value) {
640
+ if (typeof value !== "string") return false;
641
+ if (value.length === 0) return false;
642
+ return /^[a-zA-Z0-9.\-]+$/.test(value);
643
+ }
644
+ function isProjectName(value) {
645
+ if (typeof value !== "string") return false;
646
+ if (value.length === 0 || value.length > 100) return false;
647
+ return /^[a-zA-Z][a-zA-Z0-9_-]*$/.test(value);
648
+ }
649
+
650
+ // src/core/validator.ts
651
+ 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;
662
+ }
663
+ function validateAppConfig(config) {
664
+ const errors = [];
665
+ if (config.port !== "auto" && !isPort(config.port)) {
666
+ errors.push({
667
+ code: "INVALID_PORT",
668
+ message: `Invalid app port '${String(config.port)}'. Must be a number between 1-65535 or 'auto'.`,
669
+ path: "app.port",
670
+ value: config.port
671
+ });
672
+ }
673
+ if (config.node !== void 0 && !isVersion(config.node)) {
674
+ errors.push({
675
+ code: "INVALID_VERSION",
676
+ message: `Invalid Node.js version '${config.node}'.`,
677
+ path: "app.node",
678
+ value: config.node
679
+ });
680
+ }
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
+ });
690
+ }
691
+ }
692
+ }
693
+ return errors;
694
+ }
695
+ function validateServiceConfig(name, config) {
696
+ const errors = [];
697
+ if (config.version !== void 0 && !isVersion(config.version)) {
698
+ errors.push({
699
+ code: "INVALID_VERSION",
700
+ message: `Invalid version '${config.version}' for service '${name}'.`,
701
+ path: `services.${name}.version`,
702
+ value: config.version
703
+ });
704
+ }
705
+ if (config.port !== void 0 && config.port !== "auto" && typeof config.port !== "number" && typeof config.port !== "object") {
706
+ 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
711
+ });
712
+ }
713
+ return errors;
714
+ }
715
+ function validateOutputConfig(config) {
716
+ const errors = [];
717
+ if (config?.files) {
718
+ const validFiles = ["dockerfile", "compose", "dockerignore", "env", "scripts", "makefile"];
719
+ for (const file of config.files) {
720
+ if (!validFiles.includes(file)) {
721
+ errors.push({
722
+ code: "INVALID_OUTPUT_FILE",
723
+ message: `Invalid output file '${file}'. Must be one of: ${validFiles.join(", ")}.`,
724
+ path: "output.files",
725
+ value: file
726
+ });
727
+ }
728
+ }
729
+ }
730
+ return errors;
731
+ }
732
+ function validateConfig(config) {
733
+ const errors = [];
734
+ errors.push(...validateProjectName(config.name));
735
+ if (config.app) {
736
+ errors.push(...validateAppConfig(config.app));
737
+ }
738
+ if (config.services) {
739
+ for (const [name, serviceConfig] of Object.entries(config.services)) {
740
+ if (serviceConfig) {
741
+ errors.push(...validateServiceConfig(name, serviceConfig));
742
+ }
743
+ }
744
+ }
745
+ if (config.output) {
746
+ errors.push(...validateOutputConfig(config.output));
747
+ }
748
+ return {
749
+ valid: errors.length === 0,
750
+ errors
751
+ };
752
+ }
753
+ function validateResolvedConfig(config) {
754
+ const errors = [];
755
+ const usedPorts = /* @__PURE__ */ new Set();
756
+ usedPorts.add(config.app.port);
757
+ 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
+ });
765
+ }
766
+ usedPorts.add(serviceConfig.port);
767
+ }
768
+ return {
769
+ valid: errors.length === 0,
770
+ errors
771
+ };
772
+ }
773
+
774
+ // src/generators/dockerfile.ts
775
+ function generateDockerfile(config, _context) {
776
+ const { app, name } = config;
777
+ const { node, workdir, command, buildCommand, multiStage, healthcheck } = app;
778
+ const port = app.port;
779
+ let dockerfile = "";
780
+ if (multiStage) {
781
+ dockerfile += `# Builder stage
782
+ `;
783
+ dockerfile += `FROM node:${node} AS builder
784
+
785
+ `;
786
+ dockerfile += `WORKDIR ${workdir}
787
+
788
+ `;
789
+ dockerfile += `# Copy package files
790
+ `;
791
+ dockerfile += `COPY package*.json ./
792
+
793
+ `;
794
+ dockerfile += `# Install dependencies
795
+ `;
796
+ dockerfile += `RUN npm ci && npm cache clean --force
797
+
798
+ `;
799
+ dockerfile += `# Copy source files
800
+ `;
801
+ dockerfile += `COPY . .
802
+
803
+ `;
804
+ dockerfile += `# Build application
805
+ `;
806
+ dockerfile += `RUN npm run build 2>/dev/null || true
807
+
808
+ `;
809
+ dockerfile += `# Production stage
810
+ `;
811
+ dockerfile += `FROM node:${node}
812
+
813
+ `;
814
+ dockerfile += `WORKDIR ${workdir}
815
+
816
+ `;
817
+ dockerfile += `ENV NODE_ENV=production
818
+
819
+ `;
820
+ dockerfile += `# Copy from builder
821
+ `;
822
+ dockerfile += `COPY --from=builder ${workdir}/node_modules ./node_modules
823
+ `;
824
+ dockerfile += `COPY --from=builder ${workdir}/dist ./dist
825
+ `;
826
+ dockerfile += `COPY --from=builder ${workdir}/package*.json ./
827
+
828
+ `;
829
+ } else {
830
+ dockerfile += `FROM node:${node}
831
+
832
+ `;
833
+ dockerfile += `WORKDIR ${workdir}
834
+
835
+ `;
836
+ dockerfile += `ENV NODE_ENV=production
837
+
838
+ `;
839
+ dockerfile += `# Copy package files
840
+ `;
841
+ dockerfile += `COPY package*.json ./
842
+
843
+ `;
844
+ dockerfile += `# Install dependencies
845
+ `;
846
+ dockerfile += `RUN npm ci --only=production && npm cache clean --force
847
+
848
+ `;
849
+ dockerfile += `# Copy source files
850
+ `;
851
+ dockerfile += `COPY . .
852
+
853
+ `;
854
+ }
855
+ dockerfile += `EXPOSE ${port}
856
+
857
+ `;
858
+ if (healthcheck) {
859
+ 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
861
+
862
+ `;
863
+ }
864
+ dockerfile += `CMD ["npm", "start"]
865
+ `;
866
+ return dockerfile;
867
+ }
868
+
869
+ // src/utils/yaml.ts
870
+ function toYaml(obj, indent = 0) {
871
+ const spaces = " ".repeat(indent);
872
+ if (obj === null) {
873
+ return "null";
874
+ }
875
+ if (typeof obj === "string") {
876
+ return quoteStringIfNeeded(obj);
877
+ }
878
+ if (typeof obj === "number" || typeof obj === "boolean") {
879
+ return String(obj);
880
+ }
881
+ if (Array.isArray(obj)) {
882
+ return arrayToYaml(obj, indent);
883
+ }
884
+ if (typeof obj === "object") {
885
+ return objectToYaml(obj, indent);
886
+ }
887
+ return String(obj);
888
+ }
889
+ function arrayToYaml(arr, indent) {
890
+ 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
+ const lines = [];
902
+ 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)}`);
906
+ } else {
907
+ lines.push(`${spaces}- ${value}`);
908
+ }
909
+ }
910
+ return lines.join("\n");
911
+ }
912
+ function objectToYaml(obj, indent) {
913
+ const keys = Object.keys(obj);
914
+ if (keys.length === 0) {
915
+ return "{}";
916
+ }
917
+ const spaces = " ".repeat(indent);
918
+ 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);
925
+ } else {
926
+ lines.push(`${spaces}${key}: ${valueStr}`);
927
+ }
928
+ }
929
+ return lines.join("\n");
930
+ }
931
+ function quoteStringIfNeeded(str) {
932
+ if (str === "" || str.startsWith('"') || str.startsWith("'")) {
933
+ return `"${escapeString(str)}"`;
934
+ }
935
+ if (/^[\-\?:\[\]{},&*#|!<>@%'"`]/.test(str)) {
936
+ return `"${escapeString(str)}"`;
937
+ }
938
+ if (/[:\s#]/.test(str)) {
939
+ return `"${escapeString(str)}"`;
940
+ }
941
+ if (/^(true|false|null|NaN|Infinity|\-?\d+(\.\d+)?)$/.test(str)) {
942
+ return `"${escapeString(str)}"`;
943
+ }
944
+ return escapeString(str);
945
+ }
946
+ function escapeString(str) {
947
+ return str.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t");
948
+ }
949
+
950
+ // 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)
965
+ };
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}`],
970
+ interval: "30s",
971
+ timeout: "3s",
972
+ retries: 3
973
+ };
974
+ }
975
+ for (const [serviceName, serviceConfig] of Object.entries(services2)) {
976
+ servicesRecord[serviceName] = generateServiceConfig(serviceName, serviceConfig);
977
+ }
978
+ return toYaml(compose);
979
+ }
980
+ function generateAppEnvironment(config, context) {
981
+ const env = ["NODE_ENV=production", `PORT=${config.app.port}`];
982
+ for (const [serviceName, serviceConfig] of Object.entries(config.services)) {
983
+ if (serviceConfig.connectionString) {
984
+ const key = `${serviceName.toUpperCase()}_URL`;
985
+ env.push(`${key}=${serviceConfig.connectionString}`);
986
+ }
987
+ }
988
+ if (config.services.postgres) {
989
+ 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}`);
995
+ }
996
+ if (config.services.mysql) {
997
+ 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}`);
1003
+ }
1004
+ if (config.services.mongo) {
1005
+ 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}`);
1011
+ }
1012
+ if (config.services.redis) {
1013
+ const redis = config.services.redis;
1014
+ env.push(`REDIS_HOST=${redis.name}`);
1015
+ env.push(`REDIS_PORT=${redis.port}`);
1016
+ }
1017
+ return env;
1018
+ }
1019
+ function generateServiceConfig(name, config) {
1020
+ const service = {
1021
+ image: config.image,
1022
+ ports: [],
1023
+ environment: config.env
1024
+ };
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
+ if (config.volumes.length > 0) {
1034
+ service.volumes = config.volumes;
1035
+ }
1036
+ if (config.command) {
1037
+ service.command = config.command;
1038
+ }
1039
+ if (config.healthcheck) {
1040
+ service.healthcheck = {
1041
+ test: ["CMD-SHELL", config.healthcheck],
1042
+ interval: "10s",
1043
+ timeout: "5s",
1044
+ retries: 5
1045
+ };
1046
+ }
1047
+ return service;
1048
+ }
1049
+ function generateVolumeDefinitions(services2) {
1050
+ 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
+ }
1059
+ }
1060
+ }
1061
+ return volumes;
1062
+ }
1063
+
1064
+ // src/generators/dockerignore.ts
1065
+ function generateDockerignore(_config) {
1066
+ return `# Dependencies
1067
+ node_modules/
1068
+ npm-debug.log*
1069
+ yarn-debug.log*
1070
+ yarn-error.log*
1071
+ pnpm-debug.log*
1072
+
1073
+ # Environment
1074
+ .env
1075
+ .env.local
1076
+ .env.*.local
1077
+
1078
+ # Git
1079
+ .git/
1080
+ .gitignore
1081
+ .gitattributes
1082
+
1083
+ # Documentation
1084
+ README.md
1085
+ CHANGELOG.md
1086
+ LICENSE
1087
+ SPECIFICATION.md
1088
+ IMPLEMENTATION.md
1089
+ TASKS.md
1090
+ docs/
1091
+
1092
+ # IDE
1093
+ .vscode/
1094
+ .idea/
1095
+ *.swp
1096
+ *.swo
1097
+ *~
1098
+ .DS_Store
1099
+
1100
+ # Testing
1101
+ coverage/
1102
+ .nyc_output/
1103
+ *.test.ts
1104
+ *.spec.ts
1105
+ tests/
1106
+ vitest.config.ts
1107
+
1108
+ # Build
1109
+ dist/
1110
+ build/
1111
+ *.tsbuildinfo
1112
+
1113
+ # Temporary
1114
+ *.log
1115
+ tmp/
1116
+ temp/
1117
+
1118
+ # CI/CD
1119
+ .github/
1120
+ .gitlab-ci.yml
1121
+ .travis.yml
1122
+
1123
+ # Docker
1124
+ Dockerfile
1125
+ docker-compose.yml
1126
+ .dockerignore
1127
+
1128
+ # Package manager lockfiles (optional - uncomment if you want to exclude)
1129
+ # package-lock.json
1130
+ # yarn.lock
1131
+ # pnpm-lock.yaml
1132
+ `;
1133
+ }
1134
+
1135
+ // src/generators/env.ts
1136
+ function generateEnvExample(config) {
1137
+ let content = `# Application Configuration
1138
+ NODE_ENV=production
1139
+ PORT=${config.app.port}
1140
+ `;
1141
+ if (config.app.env.length > 0) {
1142
+ content += `
1143
+ # Required Environment Variables
1144
+ `;
1145
+ for (const envVar of config.app.env) {
1146
+ content += `${envVar}=
1147
+ `;
1148
+ }
1149
+ }
1150
+ if (config.services.postgres) {
1151
+ const pg = config.services.postgres;
1152
+ content += `
1153
+ # PostgreSQL
1154
+ `;
1155
+ content += `DATABASE_URL=${pg.connectionString || ""}
1156
+ `;
1157
+ content += `POSTGRES_HOST=${pg.name}
1158
+ `;
1159
+ content += `POSTGRES_PORT=${pg.port}
1160
+ `;
1161
+ content += `POSTGRES_USER=${pg.env.POSTGRES_USER || "postgres"}
1162
+ `;
1163
+ content += `POSTGRES_PASSWORD=${pg.env.POSTGRES_PASSWORD || "postgres"}
1164
+ `;
1165
+ content += `POSTGRES_DB=${pg.env.POSTGRES_DB || config.name}
1166
+ `;
1167
+ }
1168
+ if (config.services.mysql) {
1169
+ const mysql = config.services.mysql;
1170
+ content += `
1171
+ # MySQL
1172
+ `;
1173
+ content += `MYSQL_URL=${mysql.connectionString || ""}
1174
+ `;
1175
+ content += `MYSQL_HOST=${mysql.name}
1176
+ `;
1177
+ content += `MYSQL_PORT=${mysql.port}
1178
+ `;
1179
+ content += `MYSQL_USER=${mysql.env.MYSQL_USER || "root"}
1180
+ `;
1181
+ content += `MYSQL_PASSWORD=${mysql.env.MYSQL_PASSWORD || mysql.env.MYSQL_ROOT_PASSWORD || "root"}
1182
+ `;
1183
+ content += `MYSQL_DATABASE=${mysql.env.MYSQL_DATABASE || config.name}
1184
+ `;
1185
+ }
1186
+ if (config.services.mongo) {
1187
+ const mongo = config.services.mongo;
1188
+ content += `
1189
+ # MongoDB
1190
+ `;
1191
+ content += `MONGO_URL=${mongo.connectionString || ""}
1192
+ `;
1193
+ content += `MONGO_HOST=${mongo.name}
1194
+ `;
1195
+ content += `MONGO_PORT=${mongo.port}
1196
+ `;
1197
+ content += `MONGO_USER=${mongo.env.MONGO_INITDB_ROOT_USERNAME || "mongo"}
1198
+ `;
1199
+ content += `MONGO_PASSWORD=${mongo.env.MONGO_INITDB_ROOT_PASSWORD || "mongo"}
1200
+ `;
1201
+ content += `MONGO_DATABASE=${mongo.env.MONGO_INITDB_DATABASE || config.name}
1202
+ `;
1203
+ }
1204
+ if (config.services.redis) {
1205
+ const redis = config.services.redis;
1206
+ content += `
1207
+ # Redis
1208
+ `;
1209
+ content += `REDIS_URL=${redis.connectionString || ""}
1210
+ `;
1211
+ content += `REDIS_HOST=${redis.name}
1212
+ `;
1213
+ content += `REDIS_PORT=${redis.port}
1214
+ `;
1215
+ if (redis.env.REDIS_PASSWORD) {
1216
+ content += `REDIS_PASSWORD=${redis.env.REDIS_PASSWORD}
1217
+ `;
1218
+ }
1219
+ }
1220
+ return content;
1221
+ }
1222
+
1223
+ // src/generators/scripts.ts
1224
+ function generateBuildScript(_config) {
1225
+ return `#!/bin/bash
1226
+ # Docker build script
1227
+
1228
+ set -e
1229
+
1230
+ echo "Building Docker image..."
1231
+ docker-compose build
1232
+
1233
+ echo "Build complete!"
1234
+ `;
1235
+ }
1236
+ function generateUpScript(config) {
1237
+ const services2 = ["app", ...Object.keys(config.services)];
1238
+ return `#!/bin/bash
1239
+ # Docker up script
1240
+
1241
+ set -e
1242
+
1243
+ echo "Starting services..."
1244
+ docker-compose up -d ${services2.join(" ")}
1245
+
1246
+ echo "Services started!"
1247
+ echo ""
1248
+ echo "App running at http://localhost:${config.app.port}"
1249
+ `;
1250
+ }
1251
+ function generateDownScript(_config) {
1252
+ return `#!/bin/bash
1253
+ # Docker down script
1254
+
1255
+ set -e
1256
+
1257
+ echo "Stopping services..."
1258
+ docker-compose down
1259
+
1260
+ echo "Services stopped!"
1261
+ `;
1262
+ }
1263
+ function generateLogsScript(_config) {
1264
+ return `#!/bin/bash
1265
+ # Docker logs script
1266
+
1267
+ set -e
1268
+
1269
+ if [ -n "$1" ]; then
1270
+ docker-compose logs -f "$1"
1271
+ else
1272
+ docker-compose logs -f
1273
+ fi
1274
+ `;
1275
+ }
1276
+ function generateScripts(config) {
1277
+ return {
1278
+ "docker-build.sh": generateBuildScript(config),
1279
+ "docker-up.sh": generateUpScript(config),
1280
+ "docker-down.sh": generateDownScript(config),
1281
+ "docker-logs.sh": generateLogsScript(config)
1282
+ };
1283
+ }
1284
+
1285
+ // src/generators/makefile.ts
1286
+ function generateMakefile(config) {
1287
+ const services2 = Object.keys(config.services);
1288
+ let content = `.PHONY: help build up down restart logs clean install shell
1289
+
1290
+ # Default target
1291
+ help:
1292
+ @echo "Available targets:"
1293
+ @echo " make build - Build Docker images"
1294
+ @echo " make up - Start all services"
1295
+ @echo " make down - Stop all services"
1296
+ @echo " make restart - Restart all services"
1297
+ @echo " make logs - Show logs from all services"
1298
+ @echo " make shell - Open shell in app container"
1299
+ @echo " make clean - Remove containers and volumes"
1300
+ @echo " make install - Install dependencies"
1301
+
1302
+ # Build Docker images
1303
+ build:
1304
+ docker-compose build
1305
+
1306
+ # Start all services
1307
+ up:
1308
+ docker-compose up -d
1309
+ @echo "App running at http://localhost:${config.app.port}"
1310
+
1311
+ # Stop all services
1312
+ down:
1313
+ docker-compose down
1314
+
1315
+ # Restart all services
1316
+ restart: down up
1317
+
1318
+ # Show logs from all services
1319
+ logs:
1320
+ docker-compose logs -f
1321
+ `;
1322
+ if (services2.length > 0) {
1323
+ content += "\n";
1324
+ for (const service of services2) {
1325
+ content += `
1326
+ logs-${service}:
1327
+ `;
1328
+ content += ` docker-compose logs -f ${service}
1329
+ `;
1330
+ }
1331
+ }
1332
+ content += `
1333
+ # Clean up containers and volumes
1334
+ clean:
1335
+ docker-compose down -v
1336
+ docker system prune -f
1337
+
1338
+ # Install dependencies (in running container)
1339
+ shell:
1340
+ docker-compose exec app sh
1341
+
1342
+ # Install dependencies
1343
+ install:
1344
+ docker-compose exec app npm install
1345
+ `;
1346
+ return content;
1347
+ }
1348
+
1349
+ // src/generators/index.ts
1350
+ var GENERATORS = {
1351
+ dockerfile: { file: "Dockerfile", generate: generateDockerfile },
1352
+ compose: { file: "docker-compose.yml", generate: generateCompose },
1353
+ dockerignore: { file: ".dockerignore", generate: generateDockerignore },
1354
+ env: { file: ".env.example", generate: generateEnvExample },
1355
+ scripts: { file: "scripts", generate: () => "" },
1356
+ // Special handling
1357
+ makefile: { file: "Makefile", generate: generateMakefile }
1358
+ };
1359
+ function generateAll(config, context) {
1360
+ const result = {};
1361
+ const filesToGenerate = config.output.files ?? Object.keys(GENERATORS);
1362
+ for (const fileType of filesToGenerate) {
1363
+ if (fileType === "scripts") {
1364
+ const scripts = generateScripts(config);
1365
+ for (const [name, content] of Object.entries(scripts)) {
1366
+ result[name] = content;
1367
+ }
1368
+ } else {
1369
+ const generator = GENERATORS[fileType];
1370
+ if (generator) {
1371
+ result[generator.file] = generator.generate(config, context);
1372
+ }
1373
+ }
1374
+ }
1375
+ return result;
1376
+ }
1377
+
1378
+ // src/utils/fs.ts
1379
+ import { promises as fs } from "fs";
1380
+ import { join, dirname, basename, extname, relative } from "path";
1381
+ async function ensureDir(path) {
1382
+ try {
1383
+ await fs.mkdir(path, { recursive: true });
1384
+ } catch (error) {
1385
+ const err = error;
1386
+ if (err.code !== "EEXIST") {
1387
+ throw error;
1388
+ }
1389
+ }
1390
+ }
1391
+ async function writeFile(filePath, content) {
1392
+ const dir = dirname(filePath);
1393
+ await ensureDir(dir);
1394
+ const tempPath = join(dir, `.${basename(filePath)}.tmp`);
1395
+ try {
1396
+ await fs.writeFile(tempPath, content, "utf8");
1397
+ await fs.rename(tempPath, filePath);
1398
+ } catch (error) {
1399
+ try {
1400
+ await fs.unlink(tempPath);
1401
+ } catch {
1402
+ }
1403
+ throw error;
1404
+ }
1405
+ }
1406
+ async function fileExists(filePath) {
1407
+ try {
1408
+ const stat = await fs.stat(filePath);
1409
+ return stat.isFile();
1410
+ } catch {
1411
+ return false;
1412
+ }
1413
+ }
1414
+
1415
+ // src/core/dockcraft.ts
1416
+ import { join as join2 } from "path";
1417
+ async function dockcraft(config, options = {}) {
1418
+ const validation = validateConfig(config);
1419
+ 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
+ );
1425
+ }
1426
+ const resolved = await resolveConfig(config);
1427
+ const resolvedValidation = validateResolvedConfig(resolved);
1428
+ 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
+ );
1434
+ }
1435
+ const context = {
1436
+ config: resolved,
1437
+ ports: new Map(
1438
+ Object.entries(resolved.services).map(([name, svc]) => [name, svc.port])
1439
+ ),
1440
+ strings: new Map(
1441
+ Object.entries(resolved.services).filter(([, svc]) => svc.connectionString).map(([name, svc]) => [name, svc.connectionString])
1442
+ )
1443
+ };
1444
+ context.ports.set("app", resolved.app.port);
1445
+ const generated = generateAll(resolved, context);
1446
+ const written = [];
1447
+ const outputDir = resolved.output.dir ?? "./";
1448
+ if (!options.dryRun) {
1449
+ for (const [fileName, content] of Object.entries(generated)) {
1450
+ if (!fileName) continue;
1451
+ const filePath = join2(outputDir, fileName);
1452
+ const exists = await fileExists(filePath);
1453
+ if (exists && !resolved.output.overwrite) {
1454
+ continue;
1455
+ }
1456
+ await writeFile(filePath, content);
1457
+ written.push(filePath);
1458
+ }
1459
+ }
1460
+ return {
1461
+ files: new Map(Object.entries(generated)),
1462
+ written,
1463
+ config: resolved
1464
+ };
1465
+ }
1466
+ function defineConfig(config) {
1467
+ return config;
1468
+ }
1469
+
1470
+ // src/plugins/api.ts
1471
+ function defineService(def) {
1472
+ return {
1473
+ name: def.name,
1474
+ services: {
1475
+ [def.name]: def
1476
+ }
1477
+ };
1478
+ }
1479
+
1480
+ // src/ports/defaults.ts
1481
+ var DEFAULT_PORTS = {
1482
+ postgres: 5432,
1483
+ mysql: 3306,
1484
+ mongo: 27017,
1485
+ mongodb: 27017,
1486
+ redis: 6379,
1487
+ elasticsearch: 9200,
1488
+ rabbitmq: 5672,
1489
+ memcached: 11211,
1490
+ nginx: 80,
1491
+ apache: 80
1492
+ };
1493
+ function getDefaultPort(service) {
1494
+ if (service in DEFAULT_PORTS) {
1495
+ return DEFAULT_PORTS[service];
1496
+ }
1497
+ return void 0;
1498
+ }
1499
+ function listDefaultPorts() {
1500
+ return { ...DEFAULT_PORTS };
1501
+ }
1502
+
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
+ // src/index.ts
1556
+ function getConnectionString(service, config) {
1557
+ 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}`;
1568
+ 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}`;
1576
+ default:
1577
+ throw new Error(`Unknown service: ${service}`);
1578
+ }
1579
+ }
1580
+ export {
1581
+ ConfigError,
1582
+ DockcraftError,
1583
+ FileWriteError,
1584
+ NoPortAvailableError,
1585
+ PortConflictError,
1586
+ PresetNotFoundError,
1587
+ ServiceNotFoundError,
1588
+ ValidationError as ValidationErrorClass,
1589
+ checkPorts,
1590
+ defineConfig,
1591
+ defineService,
1592
+ dockcraft,
1593
+ getConnectionString,
1594
+ getDefaultPort,
1595
+ getPreset,
1596
+ getService,
1597
+ isPortAvailable,
1598
+ listDefaultPorts,
1599
+ listPresets,
1600
+ listServices,
1601
+ registerService,
1602
+ resolvePort
1603
+ };
1604
+ //# sourceMappingURL=index.js.map