@solid-stack/builder 1.1.5 → 1.1.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -96,6 +96,28 @@ builder service up test-e2e
96
96
 
97
97
  ---
98
98
 
99
+ ### Export the application environment (`builder service export env [stage]`)
100
+
101
+ ```bash
102
+ # Export all four stages into the service directory
103
+ builder service export env
104
+
105
+ # Export one stage only
106
+ builder service export env dev
107
+ builder service export env prod
108
+ builder service export env test
109
+ builder service export env e2e -C ./services/backend
110
+
111
+ # Match full/integrated development mode
112
+ builder service export env dev --full
113
+ ```
114
+
115
+ The default output names are `env.dev`, `env.prod`, `env.test`, and `env.e2e` (without a leading dot). These snapshots do not replace the `.env.<stage>` input files automatically. If an output file exists, Builder asks whether to overwrite it. Declining prompts for a new filename relative to the service directory; an existing replacement filename also requires confirmation. Existing files require an interactive terminal.
116
+
117
+ Exports use the same stage compilation as service startup, including Compose environment files, overrides, Builder URL templates, and `build.json.envOverrides`. All requested stages are compiled before any files are written. Only the application service's resolved runtime environment is exported, not build arguments, dependencies, or tester settings. E2E runs the application using the production configuration, so `env.e2e` reflects that app environment plus any E2E app overrides; it does not merge the tester's `.env.e2e` into the app.
118
+
119
+ The command requires Docker Compose 2.24 or newer, but does not require a running Docker daemon or start/build containers. Image-only `ENV` defaults and values added by application startup code cannot be determined by configuration simulation and are outside the export. New files use owner-only permissions and contain the actual values. Values follow [Compose dotenv quoting rules](https://docs.docker.com/compose/how-tos/environment-variables/variable-interpolation/) to preserve literal dollars and multiline strings.
120
+
99
121
  ## 🛠️ Options
100
122
 
101
123
  | Flag | Description |
package/dist/bin.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
- import { Command } from 'commander';
2
+ import { Command, Argument } from 'commander';
3
3
  import pc22 from 'picocolors';
4
- import fs, { existsSync, readFileSync, unlinkSync, mkdirSync, writeFileSync, statSync } from 'fs';
4
+ import fs, { existsSync, readFileSync, mkdirSync, writeFileSync, unlinkSync, statSync } from 'fs';
5
5
  import path13 from 'path';
6
6
  import { spawnSync, spawn } from 'child_process';
7
7
  import { parseAllDocuments, parse, stringify } from 'yaml';
@@ -10,6 +10,7 @@ import 'crypto';
10
10
  import os from 'os';
11
11
  import net from 'net';
12
12
  import { fileURLToPath } from 'url';
13
+ import { createInterface } from 'readline/promises';
13
14
  import { createRequire } from 'module';
14
15
 
15
16
  // src/errors/ScriptError.ts
@@ -380,7 +381,7 @@ function checkInfra(projectDir = process.cwd()) {
380
381
  checkComposeContract(buildJson, absProjectDir);
381
382
  console.log(pc22.green("\n\u2705 All infrastructure and contract checks passed.\n"));
382
383
  }
383
- function checkDependencies() {
384
+ function checkComposeAvailability() {
384
385
  const composeCheck = spawnSync(
385
386
  "docker",
386
387
  ["compose", "version", "--short"],
@@ -403,6 +404,9 @@ function checkDependencies() {
403
404
  `Error: Docker Compose version >= 2.24.0 is required (found ${rawVersion}). Please upgrade Docker Compose to support optional env_file syntax.`
404
405
  );
405
406
  }
407
+ }
408
+ function checkDependencies() {
409
+ checkComposeAvailability();
406
410
  const daemonCheck = spawnSync("docker", ["info"], {
407
411
  stdio: "pipe",
408
412
  encoding: "utf-8"
@@ -1232,12 +1236,13 @@ function compileMeshEnvironment(mode, rawMeshDir = process.cwd(), options = {})
1232
1236
  let overrideVolumes = [];
1233
1237
  let overrideHealthcheck = void 0;
1234
1238
  let overrideCommand = void 0;
1239
+ let overrideApp = void 0;
1235
1240
  const stageOverride = serviceOverrides[mode];
1236
1241
  if (stageOverride && existsSync(stageOverride.path)) {
1237
1242
  try {
1238
1243
  const overrideYaml = parse(readFileSync(stageOverride.path, "utf-8"));
1239
1244
  mergeTopLevelResources(overrideYaml);
1240
- const overrideApp = overrideYaml?.services?.app || overrideYaml?.services?.[serviceName];
1245
+ overrideApp = overrideYaml?.services?.app || overrideYaml?.services?.[serviceName];
1241
1246
  if (!overrideApp && overrideYaml?.services && Object.keys(overrideYaml.services).length > 0) {
1242
1247
  throw new ScriptError(
1243
1248
  `Override file "${stageOverride.path}" must define service "app" or "${serviceName}".`
@@ -1277,16 +1282,41 @@ function compileMeshEnvironment(mode, rawMeshDir = process.cwd(), options = {})
1277
1282
  }
1278
1283
  }
1279
1284
  environment.PORT = String(INTERNAL_PORT);
1285
+ const buildArgs = {};
1286
+ if (overrideApp?.build?.args) {
1287
+ if (Array.isArray(overrideApp.build.args)) {
1288
+ for (const item of overrideApp.build.args) {
1289
+ if (typeof item === "string") {
1290
+ const eqIdx = item.indexOf("=");
1291
+ if (eqIdx !== -1) {
1292
+ buildArgs[item.slice(0, eqIdx)] = item.slice(eqIdx + 1);
1293
+ } else {
1294
+ buildArgs[item] = process.env[item] ?? null;
1295
+ }
1296
+ }
1297
+ }
1298
+ } else if (typeof overrideApp.build.args === "object") {
1299
+ Object.assign(buildArgs, overrideApp.build.args);
1300
+ }
1301
+ }
1302
+ if (serviceBuildJson.envOverrides) {
1303
+ for (const [k, v] of Object.entries(serviceBuildJson.envOverrides)) {
1304
+ buildArgs[k] = interpolateEnvTemplates(v, `Service build.json: ${serviceName}`);
1305
+ }
1306
+ }
1280
1307
  if (serviceConfig.envOverrides) {
1281
1308
  for (const [k, v] of Object.entries(serviceConfig.envOverrides)) {
1282
- environment[k] = interpolateEnvTemplates(v, `Service: ${serviceName}`);
1309
+ const interpolated = interpolateEnvTemplates(v, `Service: ${serviceName}`);
1310
+ environment[k] = interpolated;
1311
+ buildArgs[k] = interpolated;
1283
1312
  }
1284
1313
  }
1285
1314
  const serviceDef = {
1286
1315
  build: {
1287
1316
  context: relServiceDir,
1288
1317
  dockerfile,
1289
- target: mode
1318
+ target: mode,
1319
+ ...Object.keys(buildArgs).length > 0 ? { args: buildArgs } : {}
1290
1320
  },
1291
1321
  init: true,
1292
1322
  logging: {
@@ -2794,16 +2824,51 @@ ${explanation}`);
2794
2824
  serviceConfig.environment = {};
2795
2825
  }
2796
2826
  };
2827
+ const normalizeBuildArgs = (serviceConfig) => {
2828
+ if (typeof serviceConfig.build === "string") {
2829
+ serviceConfig.build = {
2830
+ context: serviceConfig.build
2831
+ };
2832
+ }
2833
+ if (serviceConfig.build && typeof serviceConfig.build === "object") {
2834
+ if (Array.isArray(serviceConfig.build.args)) {
2835
+ const argsObj = {};
2836
+ for (const item of serviceConfig.build.args) {
2837
+ if (typeof item === "string") {
2838
+ const eqIdx = item.indexOf("=");
2839
+ if (eqIdx !== -1) {
2840
+ argsObj[item.slice(0, eqIdx)] = item.slice(eqIdx + 1);
2841
+ } else {
2842
+ argsObj[item] = process.env[item] ?? null;
2843
+ }
2844
+ }
2845
+ }
2846
+ serviceConfig.build.args = argsObj;
2847
+ } else if (!serviceConfig.build.args || typeof serviceConfig.build.args !== "object") {
2848
+ serviceConfig.build.args = {};
2849
+ }
2850
+ }
2851
+ };
2797
2852
  if (buildJson.envOverrides && yml.services && yml.services.app) {
2798
2853
  normalizeEnvironment(yml.services.app);
2854
+ normalizeBuildArgs(yml.services.app);
2799
2855
  for (const [k, v] of Object.entries(buildJson.envOverrides)) {
2800
- yml.services.app.environment[k] = interpolateEnv(v, "App EnvOverrides");
2856
+ const val = interpolateEnv(v, "App EnvOverrides");
2857
+ yml.services.app.environment[k] = val;
2858
+ if (yml.services.app.build?.args) {
2859
+ yml.services.app.build.args[k] = val;
2860
+ }
2801
2861
  }
2802
2862
  }
2803
2863
  if (buildJson.tester?.envOverrides && yml.services && yml.services.tester) {
2804
2864
  normalizeEnvironment(yml.services.tester);
2865
+ normalizeBuildArgs(yml.services.tester);
2805
2866
  for (const [k, v] of Object.entries(buildJson.tester.envOverrides)) {
2806
- yml.services.tester.environment[k] = interpolateEnv(v, "Tester EnvOverrides");
2867
+ const val = interpolateEnv(v, "Tester EnvOverrides");
2868
+ yml.services.tester.environment[k] = val;
2869
+ if (yml.services.tester.build?.args) {
2870
+ yml.services.tester.build.args[k] = val;
2871
+ }
2807
2872
  }
2808
2873
  }
2809
2874
  if (yml.services) {
@@ -3567,11 +3632,127 @@ Examples:
3567
3632
  }
3568
3633
  );
3569
3634
  };
3635
+ function compileApplicationEnv(stage, projectDir, options = {}) {
3636
+ const dir = resolveProjectDir(projectDir);
3637
+ const yaml = compileEnvironment(stage, dir, options);
3638
+ const result = spawnSync("docker", [
3639
+ "compose",
3640
+ "--project-directory",
3641
+ dir,
3642
+ "-f",
3643
+ "-",
3644
+ "config",
3645
+ "--format",
3646
+ "json"
3647
+ ], { cwd: dir, encoding: "utf-8", input: yaml });
3648
+ if (result.error || result.status !== 0) {
3649
+ throw new ScriptError(`Failed to resolve ${stage} application environment: ${result.error?.message || result.stderr || result.stdout}`);
3650
+ }
3651
+ const config = JSON.parse(result.stdout);
3652
+ if (!config.services?.app) {
3653
+ throw new ScriptError(`The ${stage} configuration has no application service ('app').`);
3654
+ }
3655
+ const environment = {};
3656
+ for (const [key, value] of Object.entries(config.services.app.environment ?? {})) {
3657
+ if (value !== null && value !== void 0) {
3658
+ environment[key] = String(value).replace(/\$\$/g, "$");
3659
+ }
3660
+ }
3661
+ return environment;
3662
+ }
3663
+ function serializeApplicationEnv(environment) {
3664
+ return Object.keys(environment).sort().map((key) => {
3665
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) {
3666
+ throw new ScriptError(`Cannot export invalid environment variable name: ${key}`);
3667
+ }
3668
+ const value = environment[key];
3669
+ if (value.includes("\0")) throw new ScriptError(`Cannot export a NUL character in ${key}.`);
3670
+ const quoted = /'|\\$|\r/.test(value) ? `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t").replace(/\$/g, () => "$$")}"` : `'${value}'`;
3671
+ return `${key}=${quoted}`;
3672
+ }).join("\n") + "\n";
3673
+ }
3674
+
3675
+ // src/commands/service/commands/export/handler.ts
3676
+ var STAGES = ["dev", "prod", "test", "e2e"];
3677
+ async function handleExportEnv(rawStage, options = {}) {
3678
+ const stage = rawStage?.toLowerCase();
3679
+ if (stage !== void 0 && !STAGES.includes(stage)) {
3680
+ throw new ScriptError(`Unknown environment stage: "${rawStage}". Supported stages: ${STAGES.join(", ")}`);
3681
+ }
3682
+ const projectDir = resolveProjectDir(options.projectDir);
3683
+ const stages = stage === void 0 ? STAGES : [stage];
3684
+ const snapshots = stages.map((stage2) => ({
3685
+ stage: stage2,
3686
+ content: serializeApplicationEnv(compileApplicationEnv(stage2, projectDir, options))
3687
+ }));
3688
+ let reader;
3689
+ const ask = async (question) => {
3690
+ if (options.prompt) return options.prompt(question);
3691
+ if (!process.stdin.isTTY || !process.stdout.isTTY) {
3692
+ throw new ScriptError("An existing export needs confirmation. Run this command in an interactive terminal to overwrite it or choose another filename.");
3693
+ }
3694
+ reader ??= createInterface({ input: process.stdin, output: process.stdout });
3695
+ return reader.question(question);
3696
+ };
3697
+ const files = [];
3698
+ try {
3699
+ for (const snapshot of snapshots) {
3700
+ let filename = path13.join(projectDir, `env.${snapshot.stage}`);
3701
+ while (true) {
3702
+ let overwrite = false;
3703
+ if (existsSync(filename)) {
3704
+ const answer = (await ask(`${filename} already exists. Overwrite? [y/N] `)).trim().toLowerCase();
3705
+ overwrite = answer === "y" || answer === "yes";
3706
+ if (!overwrite) {
3707
+ const name = (await ask(`New filename for ${snapshot.stage} (relative to the service directory): `)).trim();
3708
+ if (!name) continue;
3709
+ filename = path13.resolve(projectDir, name);
3710
+ continue;
3711
+ }
3712
+ }
3713
+ mkdirSync(path13.dirname(filename), { recursive: true });
3714
+ try {
3715
+ writeFileSync(filename, snapshot.content, { encoding: "utf-8", flag: overwrite ? "w" : "wx", mode: 384 });
3716
+ } catch (error) {
3717
+ if (!overwrite && error.code === "EEXIST") continue;
3718
+ throw error;
3719
+ }
3720
+ files.push(filename);
3721
+ console.log(pc22.green(`Exported ${snapshot.stage} application environment to ${filename}`));
3722
+ break;
3723
+ }
3724
+ }
3725
+ } finally {
3726
+ reader?.close();
3727
+ }
3728
+ return files;
3729
+ }
3730
+
3731
+ // src/commands/service/commands/export/command.ts
3732
+ function registerExportCommand(service) {
3733
+ const command = service.command("export").description("Export service configuration");
3734
+ command.command("env").description("Export the application's resolved environment for one or all stages").addArgument(new Argument("[stage]", "Stage to export (defaults to all four)").choices(["dev", "prod", "test", "e2e"])).option("-C, --project-dir <dir>", "Service project directory (defaults to cwd)").option("--full", "Export dev with mock dependencies and integrated infra mode").option("--integrated", "Alias for --full").option("--silence-warnings", "Silence non-critical URL templating warnings").addHelpText("after", `
3735
+ Examples:
3736
+ $ builder service export env
3737
+ $ builder service export env dev
3738
+ $ builder service export env e2e -C ./services/backend
3739
+ $ builder service export env dev --full`).action(async (stage, options) => {
3740
+ await handleExportEnv(stage, {
3741
+ projectDir: options.projectDir,
3742
+ full: Boolean(options.full || options.integrated),
3743
+ silenceWarnings: options.silenceWarnings
3744
+ });
3745
+ });
3746
+ }
3570
3747
 
3571
3748
  // src/commands/service/command.ts
3572
3749
  var registerServiceCommand = (cmd) => {
3573
3750
  const service = cmd.command("service").description("Manage and run services");
3574
3751
  service.hook("preAction", async (_thisCommand, actionCommand) => {
3752
+ if (actionCommand.name() === "env" && actionCommand.parent?.name() === "export") {
3753
+ checkComposeAvailability();
3754
+ return;
3755
+ }
3575
3756
  checkDependencies();
3576
3757
  if (actionCommand.name() === "up") {
3577
3758
  const options = actionCommand.opts();
@@ -3587,6 +3768,7 @@ var registerServiceCommand = (cmd) => {
3587
3768
  });
3588
3769
  registerUpCommand(service);
3589
3770
  registerDownCommand(service);
3771
+ registerExportCommand(service);
3590
3772
  };
3591
3773
  var require2 = createRequire(import.meta.url);
3592
3774
  var pkg = require2("../package.json");