@xrystal/core 3.55.16 → 3.55.59

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
@@ -257,9 +257,18 @@ bun run dev
257
257
  | `xry dev` | Watch `source/index.ts` + dev env | `source/index.ts` watch + dev env |
258
258
  | `xry build` | `tsc` full tree → dist (auto default) + alias/fix post-steps | `tsc` ile tüm `source/` → dist |
259
259
  | `xry start` | Run `x/dist` + prod env | `x/dist` + prod env |
260
+ ### Runtime env (k8s / Docker) — since 3.55.18
261
+
262
+ **EN:** `x/environments/.global.env` and `.dev.env` are for **local dev** and **Telepresence** only. They must not be copied into container images. In k8s, inject the same keys via Secret (`envFrom`); `xry start` / `Configs` read **`process.env`** only (detects `KUBERNETES_SERVICE_HOST`, `/.dockerenv`, or `XRY_RUNTIME=container`). Docker Compose: use `env_file:` at compose level — not `COPY x/environments` in the Dockerfile.
263
+
264
+ **TR:** `x/environments/*` yalnızca lokal dev + Telepresence. Image'a gömme. Cluster'da Secret inject; runtime dosya okumaz.
265
+
266
+ **Infra preflight:** Before Kafka/Redis/Mongo connect, TCP checks from tmp.yml + env. **Default fail-fast** (structured report, boot aborts on CONFIG/UNREACHABLE). Opt out locally: `STRICT_INFRA_PREFLIGHT=0`.
267
+
268
+ **Docker / Compose:** Image `CMD ["bun", "xry", "start"]` (dev: `xry dev`). Runtime skips `x/environments` when `/.dockerenv` or k8s is detected (optional override: `XRY_RUNTIME=container|docker|k8s`). Compose: `env_file:` on `x/docker/docker-compose*.yml` — not `COPY` env into the image.
260
269
  | `xry test` | Run `x/tests` | `x/tests` çalıştır |
261
270
  | `xry doctor` | CLI, runtime, package health | CLI, runtime, paket uyumu |
262
- | `xry tag` | Core release: tag + npm publish | Core release tag + npm |
271
+ | `xry tag` | **This repo only** — tag + npm publish (`@xrystal/core`) | **Sadece core** — servislerde çalışmaz / git tag yok |
263
272
 
264
273
  ---
265
274
 
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "author": "Yusuf Yasir KAYGUSUZ",
3
3
  "name": "@xrystal/core",
4
- "version": "3.55.16",
4
+ "version": "3.55.59",
5
5
  "description": "Runtime framework and CLI for API services, frontends, and multi-repo workspaces",
6
6
  "publishConfig": {
7
7
  "access": "public",
@@ -11,9 +11,9 @@ import {
11
11
  buildRuntimeStartArgv,
12
12
  buildRuntimeWatchArgv,
13
13
  resolveDevEntry,
14
- resolveDevEnvFileNames,
14
+ resolveDevRunnerEnvFiles,
15
15
  resolveDistEntryAbs,
16
- resolveEnvFiles,
16
+ resolveStartEnvFiles,
17
17
  resolvePackageScriptRunner,
18
18
  resolveRuntimeRunner,
19
19
  resolveServiceBuildSteps,
@@ -55,10 +55,7 @@ export function registerProjectCommands(cli, { cliName = CLI_PRIMARY_NAME } = {}
55
55
  runWithServiceRoot((root) => {
56
56
  const { layout, runtime } = readTmpBuildContext(root)
57
57
  const entry = resolveDevEntry(root, layout)
58
- const envFiles = resolveEnvFiles(
59
- layout.pathsAbs.environments,
60
- resolveDevEnvFileNames(layout.pathsAbs.environments),
61
- )
58
+ const envFiles = resolveDevRunnerEnvFiles(layout.pathsAbs.environments)
62
59
  const { runner, argv } = buildRuntimeWatchArgv(runtime, entry, envFiles)
63
60
 
64
61
  printCommandHeader({ cliName, command: 'dev', version: readCliPackageJson().version })
@@ -131,13 +128,18 @@ export function registerProjectCommands(cli, { cliName = CLI_PRIMARY_NAME } = {}
131
128
  }
132
129
 
133
130
  const entry = relativeFromRoot(root, entryAbs)
134
- const envFiles = resolveEnvFiles(layout.pathsAbs.environments, ['.global.env', '.prod.env'])
131
+ const envFiles = resolveStartEnvFiles(layout.pathsAbs.environments)
135
132
  const { runner, argv } = buildRuntimeStartArgv(runtime, entry, envFiles)
136
133
 
137
134
  printCommandHeader({ cliName, command: 'start', version: readCliPackageJson().version })
138
135
  console.log(chalk.gray(` root: ${root}`))
139
136
  console.log(chalk.gray(` runtime: ${runtime}`))
140
- console.log(chalk.gray(` entry: ${entry} (.js)\n`))
137
+ console.log(chalk.gray(` entry: ${entry} (.js)`))
138
+ if (envFiles.length) {
139
+ console.log(chalk.gray(` env: ${envFiles.map((f) => path.relative(root, f)).join(' · ')}\n`))
140
+ } else {
141
+ console.log('')
142
+ }
141
143
  runRunner(root, runner, argv)
142
144
  }, { cliName, command: 'start' })
143
145
  })
@@ -1,20 +1,33 @@
1
1
  import chalk from 'chalk'
2
2
  import { readCliPackageJson, readProjectPackageJson } from '../helpers/project-root.mjs'
3
- import { requireServiceRoot, exitOnCliContextError } from '../helpers/cli-context-guard.mjs'
3
+ import { requireServiceRoot, exitOnCliContextError, CliContextError } from '../helpers/cli-context-guard.mjs'
4
4
  import { compareSemver, getVersionState, resolveVersionBaseline, runTagRelease } from '../scripts/version-check.mjs'
5
- import { CLI_PRIMARY_NAME, PACKAGE_NAME } from '../helpers/cli-identity.mjs'
5
+ import { isCorePackageProject } from '../scripts/release-prepare.mjs'
6
6
  import { packageDefaults } from '../helpers/package-defaults.mjs'
7
+ import { CLI_PRIMARY_NAME, PACKAGE_NAME } from '../helpers/cli-identity.mjs'
7
8
 
8
9
  export function registerTagCommand(cli, { cliName = CLI_PRIMARY_NAME } = {}) {
9
10
  cli
10
11
  .command('tag')
11
- .description('Git tag from package.json (+ npm publish for core)')
12
+ .description(`Git tag + npm publish (${packageDefaults.packageName} repo only)`)
12
13
  .option('--dry-run', 'Print commands without executing')
13
14
  .option('--strict-clean', 'Require fully clean working tree (default: only package.json must be committed)')
14
15
  .option('--skip-prepare', 'Skip lint, test, and build:prod (core only)')
15
16
  .action(async (options) => {
16
17
  try {
17
18
  const { root } = requireServiceRoot(process.cwd(), { cliName, command: 'tag' })
19
+ if (!isCorePackageProject(root)) {
20
+ throw new CliContextError(
21
+ `\`xry tag\` is only for ${packageDefaults.packageName} (library). Services do not create git tags here.`,
22
+ {
23
+ hints: [
24
+ 'cd to -xrystal-core and bump package.json → commit → xry tag',
25
+ 'Service images: CalVer via platform release (see infra versioning.mdc)',
26
+ `${cliName} version — check package.json in this repo`,
27
+ ],
28
+ },
29
+ )
30
+ }
18
31
  await runTagRelease({
19
32
  dryRun: options.dryRun,
20
33
  requireClean: options.strictClean,
@@ -52,7 +65,12 @@ export function registerVersionCommand(cli, { cliName = CLI_PRIMARY_NAME } = {})
52
65
  console.log(` name: ${chalk.bold(projectPkg.name)}`)
53
66
  console.log(` package.json (disk): ${chalk.bold(state.disk.version)}`)
54
67
  console.log(` package.json (HEAD): ${chalk.bold(state.committed.version)}`)
55
- console.log(` git tag name: ${chalk.bold(`v${state.committed.version}`)}`)
68
+ const isCore = isCorePackageProject(root)
69
+ if (isCore) {
70
+ console.log(` git tag name: ${chalk.bold(`v${state.committed.version}`)}`)
71
+ } else {
72
+ console.log(` service image tag: ${chalk.gray('N/A — CalVer via platform CI (infra versioning.mdc)')}`)
73
+ }
56
74
  console.log(` branch: ${state.branch}`)
57
75
  console.log(` version match: ${state.versionMatch ? chalk.green('yes') : chalk.red('no')}`)
58
76
  console.log(` package.json committed: ${state.isPackageJsonClean ? chalk.green('yes') : chalk.red('no')}`)
@@ -463,6 +463,33 @@ export function resolveEnvFiles(envDir, names) {
463
463
  .filter((file) => fs.existsSync(file))
464
464
  }
465
465
 
466
+ /** k8s Secret / Compose env_file / Docker inject — do not pass bun --env-file for baked x/environments. */
467
+ export function isProcessEnvInjectedRuntime() {
468
+ const explicit = (process.env.XRY_RUNTIME ?? '').trim().toLowerCase()
469
+ if (['container', 'k8s', 'kubernetes', 'docker'].includes(explicit)) return true
470
+ if (process.env.KUBERNETES_SERVICE_HOST) return true
471
+ try {
472
+ if (fs.existsSync('/.dockerenv')) return true
473
+ } catch {
474
+ /* ignore */
475
+ }
476
+ return false
477
+ }
478
+
479
+ /** Prod dist run: local uses x/environments/*.env; containers use process env only. */
480
+ export function resolveStartEnvFiles(envDir) {
481
+ if (isProcessEnvInjectedRuntime()) return []
482
+ const files = resolveEnvFiles(envDir, ['.global.env', '.prod.env'])
483
+ if (files.length === 0 && (process.env.PORT ?? '').trim()) return []
484
+ return files
485
+ }
486
+
487
+ /** Dev watch: optional file env when not in injected runtime. */
488
+ export function resolveDevRunnerEnvFiles(envDir) {
489
+ if (isProcessEnvInjectedRuntime()) return []
490
+ return resolveEnvFiles(envDir, resolveDevEnvFileNames(envDir))
491
+ }
492
+
466
493
  /** Dev env load order — telepresence cluster env last when present. */
467
494
  export function resolveDevEnvFileNames(envDir) {
468
495
  const names = ['.global.env', '.dev.env']
@@ -3,6 +3,7 @@ import Configs from "./configs";
3
3
  import KafkaForCore from "./kafka";
4
4
  import RedisForCore from "./redis";
5
5
  import MongoForCore from "./mongo";
6
+ import InfraPreflight from "./infra-preflight";
6
7
  import Logger from "./logger";
7
8
  import Events from "./events";
8
9
  import Localizations from "./localizations";
@@ -10,4 +11,4 @@ import DtoRuntime from "./dto";
10
11
  import Controller from "./controller";
11
12
  import Service from "./service";
12
13
  import Clients from "./clients";
13
- export { System, Configs, Logger, Events, Localizations, DtoRuntime, Controller, Service, Clients, KafkaForCore, RedisForCore, MongoForCore };
14
+ export { System, Configs, Logger, Events, Localizations, DtoRuntime, Controller, Service, Clients, KafkaForCore, RedisForCore, MongoForCore, InfraPreflight };
@@ -3,6 +3,7 @@ import Configs from "./configs/index.js";
3
3
  import KafkaForCore from "./kafka/index.js";
4
4
  import RedisForCore from "./redis/index.js";
5
5
  import MongoForCore from "./mongo/index.js";
6
+ import InfraPreflight from "./infra-preflight/index.js";
6
7
  import Logger from "./logger/index.js";
7
8
  import Events from "./events/index.js";
8
9
  import Localizations from "./localizations/index.js";
@@ -10,4 +11,4 @@ import DtoRuntime from "./dto/index.js";
10
11
  import Controller from "./controller/index.js";
11
12
  import Service from "./service/index.js";
12
13
  import Clients from "./clients/index.js";
13
- export { System, Configs, Logger, Events, Localizations, DtoRuntime, Controller, Service, Clients, KafkaForCore, RedisForCore, MongoForCore };
14
+ export { System, Configs, Logger, Events, Localizations, DtoRuntime, Controller, Service, Clients, KafkaForCore, RedisForCore, MongoForCore, InfraPreflight };
@@ -0,0 +1,9 @@
1
+ import Configs from '../../loader/configs';
2
+ import { IProvide } from '../../utils/models/classes/class.interfaces';
3
+ export default class InfraPreflight implements IProvide<void> {
4
+ #private;
5
+ constructor({ configs }: {
6
+ configs: Configs;
7
+ });
8
+ onInit: () => Promise<void>;
9
+ }
@@ -0,0 +1,10 @@
1
+ import { runInfraPreflight } from '../../utils/helpers/infra-preflight/index.js';
2
+ export default class InfraPreflight {
3
+ #configs;
4
+ constructor({ configs }) {
5
+ this.#configs = configs;
6
+ }
7
+ onInit = async () => {
8
+ await runInfraPreflight(this.#configs.all);
9
+ };
10
+ }
@@ -1,6 +1,6 @@
1
1
  import path from 'path';
2
2
  import { fileURLToPath } from 'node:url';
3
- import { System, Configs, Logger, Events, Localizations, DtoRuntime, Clients, Controller, KafkaForCore, RedisForCore, MongoForCore, } from '../loader/index.js';
3
+ import { System, Configs, Logger, Events, Localizations, DtoRuntime, Clients, Controller, KafkaForCore, RedisForCore, MongoForCore, InfraPreflight, } from '../loader/index.js';
4
4
  import { Constants, getCore, x } from '../utils/index.js';
5
5
  import { ensureCoreTmpEntry, isCorePackageRoot } from '../utils/helpers/core/tmp-layout.js';
6
6
  import { getTmpSnapshot } from '../utils/helpers/tmp/tmp-loader.js';
@@ -24,6 +24,7 @@ function buildLoaderInitList(plan, coreRef) {
24
24
  const entries = [
25
25
  { service: System, props: { core: coreRef } },
26
26
  { service: Configs, props: {} },
27
+ { service: InfraPreflight, props: {} },
27
28
  ];
28
29
  if (isInfraLoaderEnabled(plan, InfraLoaderEnum.KAFKA))
29
30
  entries.push({ service: KafkaForCore, props: {} });
@@ -26,3 +26,4 @@ export * from '../../utils/helpers/handlers';
26
26
  export * from '../../utils/helpers/runtime';
27
27
  export * from '../../utils/helpers/node-env';
28
28
  export * from '../../utils/helpers/workspace';
29
+ export * from '../../utils/helpers/infra-preflight';
@@ -26,3 +26,4 @@ export * from '../../utils/helpers/handlers/index.js';
26
26
  export * from '../../utils/helpers/runtime/index.js';
27
27
  export * from '../../utils/helpers/node-env/index.js';
28
28
  export * from '../../utils/helpers/workspace/index.js';
29
+ export * from '../../utils/helpers/infra-preflight/index.js';
@@ -0,0 +1,28 @@
1
+ import type { IConfig } from '../../../loader/configs';
2
+ import { type LoaderBootPlan } from '../../../utils/helpers/tmp/loader-boot-plan';
3
+ export type InfraEndpoint = {
4
+ service: string;
5
+ label: string;
6
+ host: string;
7
+ port: number;
8
+ envKey: string;
9
+ };
10
+ export type InfraProbeResult = {
11
+ endpoint: InfraEndpoint;
12
+ ok: boolean;
13
+ error?: string;
14
+ };
15
+ type PreflightRow = {
16
+ service: string;
17
+ envKey: string;
18
+ target: string;
19
+ result: 'OK' | 'UNREACHABLE' | 'CONFIG' | 'INVALID';
20
+ detail?: string;
21
+ };
22
+ /** Default: fail-fast. Set STRICT_INFRA_PREFLIGHT=0|false|no|off to warn only (local edge cases). */
23
+ export declare function isStrictInfraPreflight(): boolean;
24
+ export declare function collectInfraEndpoints(plan: LoaderBootPlan, config: IConfig): InfraEndpoint[];
25
+ export declare function collectInfraConfigGaps(plan: LoaderBootPlan, config: IConfig): PreflightRow[];
26
+ export declare function probeInfraEndpoints(endpoints: InfraEndpoint[]): Promise<InfraProbeResult[]>;
27
+ export declare function runInfraPreflight(config: IConfig, plan?: LoaderBootPlan): Promise<void>;
28
+ export {};
@@ -0,0 +1,266 @@
1
+ import fs from 'node:fs';
2
+ import net from 'node:net';
3
+ import { parseRedisUri } from '../../../loader/redis/parse-uri.js';
4
+ import { InfraLoaderEnum } from '../../../utils/models/enums/index.js';
5
+ import { isInfraLoaderEnabled, resolveLoaderBootPlan, } from '../../../utils/helpers/tmp/loader-boot-plan.js';
6
+ import { resolveTmpRuntimeConfigs } from '../../../utils/helpers/tmp/tmp-schema.js';
7
+ import { getTmpSnapshot } from '../../../utils/helpers/tmp/tmp-loader.js';
8
+ const PROBE_TIMEOUT_MS = 2500;
9
+ const RULE = '─'.repeat(72);
10
+ /** Default: fail-fast. Set STRICT_INFRA_PREFLIGHT=0|false|no|off to warn only (local edge cases). */
11
+ export function isStrictInfraPreflight() {
12
+ const raw = (process.env.STRICT_INFRA_PREFLIGHT ?? '').trim().toLowerCase();
13
+ if (!raw)
14
+ return true;
15
+ if (raw === '0' || raw === 'false' || raw === 'no' || raw === 'off')
16
+ return false;
17
+ return true;
18
+ }
19
+ function runtimeContextHint() {
20
+ if (process.env.KUBERNETES_SERVICE_HOST) {
21
+ return 'Kubernetes: verify Service DNS, namespace, and Secret envFrom keys.';
22
+ }
23
+ try {
24
+ if (fs.existsSync('/.dockerenv')) {
25
+ return 'Docker: URIs must resolve from inside the container (Tailscale IP, host gateway, not host-only 127.0.0.1).';
26
+ }
27
+ }
28
+ catch {
29
+ /* ignore */
30
+ }
31
+ return 'Local: verify VPN/Tailscale and that env hosts match this process.';
32
+ }
33
+ function parseMongoEndpoints(uri) {
34
+ const trimmed = uri.trim();
35
+ if (!trimmed)
36
+ return [];
37
+ if (trimmed.startsWith('mongodb+srv://')) {
38
+ const host = trimmed.replace(/^mongodb\+srv:\/\//, '').split('/')[0]?.split('?')[0] ?? '';
39
+ return [{
40
+ service: 'MongoDB',
41
+ label: 'mongodb+srv',
42
+ host: host || '(srv)',
43
+ port: 27017,
44
+ envKey: 'MONGODB_URI',
45
+ }];
46
+ }
47
+ const withoutScheme = trimmed.replace(/^mongodb:\/\//, '');
48
+ const authority = withoutScheme.split('/')[0] ?? '';
49
+ const hostsCsv = authority.includes('@') ? authority.split('@').pop() ?? '' : authority;
50
+ return hostsCsv
51
+ .split(',')
52
+ .map((part) => part.trim())
53
+ .filter(Boolean)
54
+ .map((part, index) => {
55
+ const colon = part.lastIndexOf(':');
56
+ const host = colon === -1 ? part : part.slice(0, colon);
57
+ const port = colon === -1 ? 27017 : Number.parseInt(part.slice(colon + 1), 10);
58
+ return {
59
+ service: 'MongoDB',
60
+ label: index === 0 ? 'primary' : `host-${index + 1}`,
61
+ host,
62
+ port: Number.isFinite(port) ? port : 27017,
63
+ envKey: 'MONGODB_URI',
64
+ };
65
+ });
66
+ }
67
+ function parseKafkaEndpoints(brokers) {
68
+ return brokers
69
+ .split(',')
70
+ .map((part) => part.trim())
71
+ .filter(Boolean)
72
+ .map((part, index) => {
73
+ const colon = part.lastIndexOf(':');
74
+ const host = colon === -1 ? part : part.slice(0, colon);
75
+ const port = colon === -1 ? 9092 : Number.parseInt(part.slice(colon + 1), 10);
76
+ return {
77
+ service: 'Kafka',
78
+ label: index === 0 ? 'broker' : `broker-${index + 1}`,
79
+ host,
80
+ port: Number.isFinite(port) ? port : 9092,
81
+ envKey: 'KAFKA_BROKERS',
82
+ };
83
+ });
84
+ }
85
+ function probeTcp(host, port, timeoutMs = PROBE_TIMEOUT_MS) {
86
+ if (host === '(srv)' || host === '_srv_') {
87
+ return Promise.resolve({ ok: true });
88
+ }
89
+ return new Promise((resolve) => {
90
+ const socket = net.connect({ host, port });
91
+ let settled = false;
92
+ const finish = (ok, error) => {
93
+ if (settled)
94
+ return;
95
+ settled = true;
96
+ socket.destroy();
97
+ resolve({ ok, error });
98
+ };
99
+ socket.setTimeout(timeoutMs);
100
+ socket.on('connect', () => finish(true));
101
+ socket.on('timeout', () => finish(false, 'connection timed out'));
102
+ socket.on('error', (err) => finish(false, err.code ?? err.message));
103
+ });
104
+ }
105
+ export function collectInfraEndpoints(plan, config) {
106
+ const endpoints = [];
107
+ if (isInfraLoaderEnabled(plan, InfraLoaderEnum.KAFKA) && !config.isKafkaPassive && config.kafkaBrokers?.trim()) {
108
+ endpoints.push(...parseKafkaEndpoints(config.kafkaBrokers));
109
+ }
110
+ if (isInfraLoaderEnabled(plan, InfraLoaderEnum.REDIS) && !config.isRedisPassive && config.redisUri?.trim()) {
111
+ try {
112
+ const parsed = parseRedisUri(config.redisUri);
113
+ for (const [index, ep] of parsed.endpoints.entries()) {
114
+ endpoints.push({
115
+ service: 'Redis',
116
+ label: parsed.useSentinel ? `sentinel-${index + 1}` : 'data',
117
+ host: ep.host,
118
+ port: ep.port,
119
+ envKey: 'REDIS_URI',
120
+ });
121
+ }
122
+ }
123
+ catch {
124
+ endpoints.push({
125
+ service: 'Redis',
126
+ label: 'uri',
127
+ host: '(invalid REDIS_URI)',
128
+ port: 6379,
129
+ envKey: 'REDIS_URI',
130
+ });
131
+ }
132
+ }
133
+ if (isInfraLoaderEnabled(plan, InfraLoaderEnum.MONGO) && !config.isMongoPassive && config.mongodbUri?.trim()) {
134
+ endpoints.push(...parseMongoEndpoints(config.mongodbUri));
135
+ }
136
+ if (config.isRegistryEnabled && config.registryMongodbUri?.trim()) {
137
+ for (const ep of parseMongoEndpoints(config.registryMongodbUri)) {
138
+ endpoints.push({ ...ep, service: 'Registry MongoDB', envKey: 'REGISTRY_MONGODB_URI' });
139
+ }
140
+ }
141
+ return endpoints;
142
+ }
143
+ export function collectInfraConfigGaps(plan, config) {
144
+ const rows = [];
145
+ if (isInfraLoaderEnabled(plan, InfraLoaderEnum.KAFKA) && !config.isKafkaPassive && !config.kafkaBrokers?.trim()) {
146
+ rows.push({
147
+ service: 'Kafka',
148
+ envKey: 'KAFKA_BROKERS',
149
+ target: '(not set)',
150
+ result: 'CONFIG',
151
+ detail: 'loader enabled in tmp.yml',
152
+ });
153
+ }
154
+ if (isInfraLoaderEnabled(plan, InfraLoaderEnum.REDIS) && !config.isRedisPassive && !config.redisUri?.trim()) {
155
+ rows.push({
156
+ service: 'Redis',
157
+ envKey: 'REDIS_URI',
158
+ target: '(not set)',
159
+ result: 'CONFIG',
160
+ detail: 'loader enabled in tmp.yml',
161
+ });
162
+ }
163
+ if (isInfraLoaderEnabled(plan, InfraLoaderEnum.MONGO) && !config.isMongoPassive && !config.mongodbUri?.trim()) {
164
+ rows.push({
165
+ service: 'MongoDB',
166
+ envKey: 'MONGODB_URI',
167
+ target: '(not set)',
168
+ result: 'CONFIG',
169
+ detail: 'loader enabled in tmp.yml',
170
+ });
171
+ }
172
+ if (config.isRegistryEnabled && !config.registryMongodbUri?.trim()) {
173
+ rows.push({
174
+ service: 'Registry MongoDB',
175
+ envKey: 'REGISTRY_MONGODB_URI',
176
+ target: '(not set)',
177
+ result: 'CONFIG',
178
+ detail: 'IS_REGISTRY_ENABLED=true',
179
+ });
180
+ }
181
+ return rows;
182
+ }
183
+ export async function probeInfraEndpoints(endpoints) {
184
+ const unique = new Map();
185
+ for (const ep of endpoints) {
186
+ if (ep.host.startsWith('('))
187
+ continue;
188
+ unique.set(`${ep.service}|${ep.host}|${ep.port}`, ep);
189
+ }
190
+ const results = [];
191
+ await Promise.all([...unique.values()].map(async (endpoint) => {
192
+ const { ok, error } = await probeTcp(endpoint.host, endpoint.port);
193
+ results.push({ endpoint, ok, error });
194
+ }));
195
+ return results;
196
+ }
197
+ function pad(value, width) {
198
+ if (value.length >= width)
199
+ return value.slice(0, width);
200
+ return value + ' '.repeat(width - value.length);
201
+ }
202
+ function formatReport(outcome, rows, context, action) {
203
+ const lines = [
204
+ 'Infrastructure preflight',
205
+ RULE,
206
+ outcome,
207
+ RULE,
208
+ `${pad('Service', 14)} ${pad('Env', 22)} ${pad('Target', 22)} Result`,
209
+ RULE,
210
+ ];
211
+ for (const row of rows) {
212
+ const detail = row.detail ? ` ${row.detail}` : '';
213
+ lines.push(`${pad(row.service, 14)} ${pad(row.envKey, 22)} ${pad(row.target, 22)} ${row.result}${detail}`);
214
+ }
215
+ lines.push(RULE, `Context ${context}`);
216
+ if (action)
217
+ lines.push(`Action ${action}`);
218
+ lines.push(RULE);
219
+ return lines.join('\n');
220
+ }
221
+ function buildFailureAction(strict) {
222
+ if (strict)
223
+ return 'Boot aborted. Set STRICT_INFRA_PREFLIGHT=0 only for warn-only local runs.';
224
+ return 'Boot continues (lenient mode). Fix connectivity before relying on infra loaders.';
225
+ }
226
+ export async function runInfraPreflight(config, plan) {
227
+ const strict = isStrictInfraPreflight();
228
+ const bootPlan = plan ?? resolveLoaderBootPlan(resolveTmpRuntimeConfigs(getTmpSnapshot()));
229
+ const rows = [...collectInfraConfigGaps(bootPlan, config)];
230
+ const endpoints = collectInfraEndpoints(bootPlan, config);
231
+ for (const ep of endpoints.filter((e) => e.host.startsWith('('))) {
232
+ rows.push({
233
+ service: ep.service,
234
+ envKey: ep.envKey,
235
+ target: '(invalid uri)',
236
+ result: 'INVALID',
237
+ detail: 'could not parse host',
238
+ });
239
+ }
240
+ const probeTargets = endpoints.filter((ep) => !ep.host.startsWith('('));
241
+ const results = probeTargets.length ? await probeInfraEndpoints(probeTargets) : [];
242
+ for (const { endpoint, ok, error } of results) {
243
+ rows.push({
244
+ service: endpoint.service,
245
+ envKey: endpoint.envKey,
246
+ target: `${endpoint.host}:${endpoint.port}`,
247
+ result: ok ? 'OK' : 'UNREACHABLE',
248
+ detail: ok ? undefined : error,
249
+ });
250
+ }
251
+ if (rows.length === 0)
252
+ return;
253
+ const failed = rows.filter((r) => r.result !== 'OK');
254
+ const passed = rows.filter((r) => r.result === 'OK');
255
+ if (failed.length === 0) {
256
+ const names = [...new Set(passed.map((r) => r.service))].join(', ');
257
+ console.log(`Infrastructure preflight: passed (${passed.length} checks: ${names})`);
258
+ return;
259
+ }
260
+ const outcome = `Outcome FAILED | ${failed.length} issue(s), ${passed.length} passed`;
261
+ const report = formatReport(outcome, rows, runtimeContextHint(), buildFailureAction(strict));
262
+ console.error(report);
263
+ if (strict) {
264
+ throw new Error(`Infrastructure preflight failed.\n${report}`);
265
+ }
266
+ }
@@ -0,0 +1,40 @@
1
+ FROM oven/bun:1.1-alpine AS builder
2
+ ARG SERVICE_PATH
3
+ WORKDIR /app
4
+
5
+ COPY ${SERVICE_PATH}/package.json ${SERVICE_PATH}/bun.lockb* ./
6
+ COPY ${SERVICE_PATH}/tsconfig.json ./
7
+
8
+ RUN bun install --frozen-lockfile
9
+
10
+ COPY ${SERVICE_PATH} .
11
+
12
+ ARG OUTPUT_DIR=x
13
+ ENV ROOT_FOLDER_PATH=${OUTPUT_DIR}
14
+ RUN bun run build
15
+
16
+ FROM oven/bun:1.1-alpine
17
+ ARG OUTPUT_DIR=x
18
+ ENV ROOT_FOLDER_PATH=${OUTPUT_DIR}
19
+ WORKDIR /app
20
+
21
+ COPY --from=builder /app/${ROOT_FOLDER_PATH}/dist ./${ROOT_FOLDER_PATH}/dist
22
+ COPY --from=builder /app/package.json ./package.json
23
+ COPY --from=builder /app/node_modules ./node_modules
24
+ COPY --from=builder /app/tsconfig.json ./
25
+
26
+ COPY --from=builder /app/${ROOT_FOLDER_PATH}/tmp.yml ./${ROOT_FOLDER_PATH}/tmp.yml
27
+ COPY --from=builder /app/${ROOT_FOLDER_PATH}/assets/ ./${ROOT_FOLDER_PATH}/assets/
28
+ COPY --from=builder /app/${ROOT_FOLDER_PATH}/certificates/ ./${ROOT_FOLDER_PATH}/certificates/
29
+ COPY --from=builder /app/${ROOT_FOLDER_PATH}/public/ ./${ROOT_FOLDER_PATH}/public/
30
+
31
+ RUN addgroup -S nodeuser && adduser -S nodeuser -G nodeuser
32
+ RUN chown -R nodeuser:nodeuser /app
33
+ USER nodeuser
34
+
35
+ EXPOSE 3000
36
+
37
+ HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
38
+ CMD wget --no-verbose --tries=1 --spider http://127.0.0.1:3000/health || exit 1
39
+
40
+ CMD ["bun", "xry", "start"]
@@ -0,0 +1,34 @@
1
+ ARG SERVICE_PATH
2
+
3
+ FROM oven/bun:1.1-alpine AS base
4
+ ARG SERVICE_PATH
5
+ WORKDIR /app
6
+
7
+ COPY ${SERVICE_PATH}/package.json ${SERVICE_PATH}/bun.lockb* ./
8
+
9
+ RUN --mount=type=cache,id=bun,target=/root/.bun/install/cache \
10
+ bun install
11
+
12
+ FROM oven/bun:1.1-alpine AS release
13
+ ARG SERVICE_PATH
14
+ WORKDIR /app
15
+
16
+ COPY --from=base /app/node_modules ./node_modules
17
+
18
+ COPY ${SERVICE_PATH}/package.json ./
19
+
20
+ COPY ${SERVICE_PATH}/source ./source
21
+ COPY ${SERVICE_PATH}/x ./x
22
+ COPY ${SERVICE_PATH}/tsconfig.json ./
23
+ COPY ${SERVICE_PATH}/bunfig.toml* ./
24
+
25
+ RUN addgroup -S nodeuser && adduser -S nodeuser -G nodeuser
26
+ RUN chown -R nodeuser:nodeuser /app
27
+ USER nodeuser
28
+
29
+ EXPOSE 3000
30
+
31
+ HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
32
+ CMD wget --no-verbose --tries=1 --spider http://127.0.0.1:3000/health || exit 1
33
+
34
+ CMD ["bun", "xry", "dev"]
@@ -0,0 +1,14 @@
1
+ # Local dev image — env via compose (not COPY x/environments into the image).
2
+ # Run from repo root: docker compose -f x/docker/docker-compose.dev.yml up --build
3
+ services:
4
+ app:
5
+ build:
6
+ context: ../..
7
+ dockerfile: x/docker/Dockerfile.dev
8
+ args:
9
+ SERVICE_PATH: .
10
+ env_file:
11
+ - ../environments/.global.env
12
+ - ../environments/.dev.env
13
+ ports:
14
+ - "${PORT:-3000}:3000"
@@ -0,0 +1,17 @@
1
+ # Prod-like dist image — env via compose (same keys as k8s Secret inject).
2
+ # Run from repo root: docker compose -f x/docker/docker-compose.yml up --build
3
+ services:
4
+ app:
5
+ build:
6
+ context: ../..
7
+ dockerfile: x/docker/Dockerfile
8
+ args:
9
+ SERVICE_PATH: .
10
+ OUTPUT_DIR: x
11
+ env_file:
12
+ - ../environments/.global.env
13
+ - ../environments/.prod.env
14
+ environment:
15
+ NODE_ENV: production
16
+ ports:
17
+ - "${PORT:-3000}:3000"