@geekmidas/cli 10.0.0-alpha.24 → 10.0.0-alpha.25
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/bin/adjacent-tsconfig.mjs +46 -8
- package/bin/gkm.mjs +2 -2
- package/dist/{config-DdKkoUE1.mjs → config-DBGpRTUy.mjs} +2 -2
- package/dist/{config-DdKkoUE1.mjs.map → config-DBGpRTUy.mjs.map} +1 -1
- package/dist/{config-DSXI480r.cjs → config-Dn9DW2Fz.cjs} +2 -2
- package/dist/{config-DSXI480r.cjs.map → config-Dn9DW2Fz.cjs.map} +1 -1
- package/dist/config.cjs +1 -1
- package/dist/config.mjs +1 -1
- package/dist/{credentials-D9TKJJZc.mjs → credentials-BpoOUa74.mjs} +17 -6
- package/dist/credentials-BpoOUa74.mjs.map +1 -0
- package/dist/{credentials-COrSpZfF.cjs → credentials-Dbyccl3A.cjs} +17 -6
- package/dist/credentials-Dbyccl3A.cjs.map +1 -0
- package/dist/deploy/sniffer-routes-worker.cjs +1 -1
- package/dist/deploy/sniffer-routes-worker.mjs +1 -1
- package/dist/{discover-CK-n3w6b.mjs → discover-0fhCbnk0.mjs} +3 -2
- package/dist/{discover-CK-n3w6b.mjs.map → discover-0fhCbnk0.mjs.map} +1 -1
- package/dist/{discover-BERGFg8v.cjs → discover-B_HtYJCr.cjs} +3 -2
- package/dist/{discover-BERGFg8v.cjs.map → discover-B_HtYJCr.cjs.map} +1 -1
- package/dist/{github-B4OQQZBV.mjs → github-BOaa3kQR.mjs} +3 -3
- package/dist/{github-B4OQQZBV.mjs.map → github-BOaa3kQR.mjs.map} +1 -1
- package/dist/{github-BpsnSDw2.cjs → github-CUjW3G91.cjs} +3 -3
- package/dist/{github-BpsnSDw2.cjs.map → github-CUjW3G91.cjs.map} +1 -1
- package/dist/index.cjs +1873 -1825
- package/dist/index.cjs.map +1 -1
- package/dist/index.mjs +1873 -1825
- package/dist/index.mjs.map +1 -1
- package/dist/{openapi-DeMqoLuJ.cjs → openapi-BAKQLho-.cjs} +4 -4
- package/dist/{openapi-DeMqoLuJ.cjs.map → openapi-BAKQLho-.cjs.map} +1 -1
- package/dist/{openapi-Co2Tv7zh.mjs → openapi-DHQlstv6.mjs} +4 -4
- package/dist/{openapi-Co2Tv7zh.mjs.map → openapi-DHQlstv6.mjs.map} +1 -1
- package/dist/openapi.cjs +1 -1
- package/dist/openapi.mjs +1 -1
- package/dist/reconcile/public.cjs +1 -1
- package/dist/reconcile/public.d.cts +7 -0
- package/dist/reconcile/public.d.cts.map +1 -1
- package/dist/reconcile/public.d.mts +7 -0
- package/dist/reconcile/public.d.mts.map +1 -1
- package/dist/reconcile/public.mjs +1 -1
- package/dist/{transfer-Bk5YlRyB.mjs → transfer-B88fTvnh.mjs} +2 -2
- package/dist/{transfer-Bk5YlRyB.mjs.map → transfer-B88fTvnh.mjs.map} +1 -1
- package/dist/{transfer-BZbyaV3I.cjs → transfer-D59M4aaR.cjs} +2 -2
- package/dist/{transfer-BZbyaV3I.cjs.map → transfer-D59M4aaR.cjs.map} +1 -1
- package/package.json +17 -12
- package/dist/credentials-COrSpZfF.cjs.map +0 -1
- package/dist/credentials-D9TKJJZc.mjs.map +0 -1
package/dist/index.mjs
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
#!/usr/bin/env -S npx tsx
|
|
2
2
|
import { n as __require, t as __exportAll } from "./rolldown-runtime-BhDjJH2R.mjs";
|
|
3
|
-
import { i as DEFAULT_CACHE, r as ConstructGenerator, s as isPartitionedRoutes, t as discover } from "./discover-
|
|
4
|
-
import { i as loadConfig, l as derivedApps, n as getAppNameFromCwd, o as loadWorkspaceConfig, r as loadAppConfig, s as parseModuleConfig } from "./config-
|
|
3
|
+
import { i as DEFAULT_CACHE, r as ConstructGenerator, s as isPartitionedRoutes, t as discover } from "./discover-0fhCbnk0.mjs";
|
|
4
|
+
import { i as loadConfig, l as derivedApps, n as getAppNameFromCwd, o as loadWorkspaceConfig, r as loadAppConfig, s as parseModuleConfig } from "./config-DBGpRTUy.mjs";
|
|
5
5
|
import { A as stripPublicPrefix, C as InvalidStages, D as stageProblems, E as deployedProblems, T as assertDeployedStage, a as getAppBuildOrder, k as getPublicEnvPrefix, o as getAppGkmConfig, s as getDependencyEnvVars, t as allConstructGlobs, v as getDeployTargetError, w as TEST_STAGE, y as isDeployTargetSupported } from "./workspace-Bu3xNCej.mjs";
|
|
6
|
-
import { C as providerOf, S as eventsBackendFor, _ as COMPOSE_PATH, a as loadEnvFiles, b as resourceName, c as resolveServicePorts, d as backendsOf, f as constructGlobs, h as usesConstructs, i as isPortAvailable, l as rewriteUrlsWithPorts, m as reconcileWorkspace, n as createEntryWrapper, o as loadSecretsForApp, p as derivedContainers, r as findAvailablePort, s as prepareEntryCredentials, t as createCredentialsPreload, u as startWorkspaceServices, v as LOCAL_CA_PATH, w as storageBackendFor, x as cacheBackendFor, y as applyPostgres } from "./credentials-
|
|
6
|
+
import { C as providerOf, S as eventsBackendFor, _ as COMPOSE_PATH, a as loadEnvFiles, b as resourceName, c as resolveServicePorts, d as backendsOf, f as constructGlobs, h as usesConstructs, i as isPortAvailable, l as rewriteUrlsWithPorts, m as reconcileWorkspace, n as createEntryWrapper, o as loadSecretsForApp, p as derivedContainers, r as findAvailablePort, s as prepareEntryCredentials, t as createCredentialsPreload, u as startWorkspaceServices, v as LOCAL_CA_PATH, w as storageBackendFor, x as cacheBackendFor, y as applyPostgres } from "./credentials-BpoOUa74.mjs";
|
|
7
7
|
import { a as generateServiceCredentials, i as generateSecurePassword, n as generateConnectionUrls, o as rotateServicePassword, t as createStageSecrets } from "./generator-LfZU7NlU.mjs";
|
|
8
8
|
import { c as getKeyPath, i as setCustomSecret, n as readStageSecrets, o as toEmbeddableSecrets, r as secretsExist, s as writeStageSecrets, t as maskPassword } from "./storage-TP0x118M.mjs";
|
|
9
|
-
import { a as openapiCommand, c as EndpointGenerator, l as runtimeFor, n as generateOpenApi, o as resolveOpenApiConfig,
|
|
9
|
+
import { a as openapiCommand, c as EndpointGenerator, l as runtimeFor, n as generateOpenApi, o as resolveOpenApiConfig, s as OpenApiTsGenerator, t as OPENAPI_OUTPUT_PATH$1 } from "./openapi-DHQlstv6.mjs";
|
|
10
10
|
import { i as withRoutes, r as withCompute } from "./emit-Bzq7JsMP.mjs";
|
|
11
11
|
import { i as writeDockerEnvFromSecrets, r as generateFullstackCustomSecrets } from "./reconcile-gb1lz1Dk.mjs";
|
|
12
|
-
import { a as isRemoteStore, n as pullStageSecrets, r as pushStageSecrets, t as NoStoredSecrets } from "./transfer-
|
|
12
|
+
import { a as isRemoteStore, n as pullStageSecrets, r as pushStageSecrets, t as NoStoredSecrets } from "./transfer-B88fTvnh.mjs";
|
|
13
13
|
import { createRequire } from "node:module";
|
|
14
14
|
import { Command } from "commander";
|
|
15
15
|
import { stdin, stdout } from "node:process";
|
|
@@ -28,18 +28,18 @@ import { ownerRole, readerRole, roleStatements } from "@geekmidas/db/pg/roles";
|
|
|
28
28
|
import { Client } from "pg";
|
|
29
29
|
import { promisify } from "node:util";
|
|
30
30
|
import { cacheTableStatements } from "@geekmidas/cache/postgres";
|
|
31
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
31
32
|
import { Cron } from "@geekmidas/constructs/crons";
|
|
32
33
|
import { Function } from "@geekmidas/constructs/functions";
|
|
33
34
|
import { Queue } from "@geekmidas/constructs/queue";
|
|
34
35
|
import { Subscriber } from "@geekmidas/constructs/subscribers";
|
|
35
36
|
import { Topic } from "@geekmidas/constructs/topic";
|
|
36
|
-
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
37
37
|
import { lookup } from "node:dns/promises";
|
|
38
38
|
import prompts from "prompts";
|
|
39
39
|
import { EnvironmentParser } from "@geekmidas/envkit";
|
|
40
40
|
import { serviceContext } from "@geekmidas/services";
|
|
41
41
|
//#region package.json
|
|
42
|
-
var version = "10.0.0-alpha.
|
|
42
|
+
var version = "10.0.0-alpha.25";
|
|
43
43
|
//#endregion
|
|
44
44
|
//#region src/auth/credentials.ts
|
|
45
45
|
/**
|
|
@@ -324,76 +324,6 @@ function maskToken(token) {
|
|
|
324
324
|
return `${token.slice(0, 4)}...${token.slice(-4)}`;
|
|
325
325
|
}
|
|
326
326
|
//#endregion
|
|
327
|
-
//#region src/build/owners.ts
|
|
328
|
-
/**
|
|
329
|
-
* What a generated entry imports its runtime from, read off the discovered
|
|
330
|
-
* constructs: the surface it serves, every construct a runnable can be built
|
|
331
|
-
* from, and the database Studio browses.
|
|
332
|
-
*
|
|
333
|
-
* `gkm build` and `gkm dev` both write entries that import the surface for its
|
|
334
|
-
* logger and environment parser, so both ask here. A dev server that skipped it
|
|
335
|
-
* had nothing to import them from.
|
|
336
|
-
*/
|
|
337
|
-
function ownersContext(options) {
|
|
338
|
-
const { declared, sources, workspaceRoot, appRoot, studio } = options;
|
|
339
|
-
const surfaces = restApis(declared);
|
|
340
|
-
const primary = servedSurface(declared, workspaceRoot, appRoot) ?? surfaces.find((d) => d.endpoints.length === 0) ?? surfaces[0];
|
|
341
|
-
const browsable = Object.entries(declared).find(([, d]) => d.kind === "database");
|
|
342
|
-
const browsableSource = browsable ? sources[browsable[0]] : void 0;
|
|
343
|
-
const owners = {};
|
|
344
|
-
for (const [id, declaration] of Object.entries(declared)) {
|
|
345
|
-
if (declaration.kind !== "rest-api" && declaration.kind !== "worker") continue;
|
|
346
|
-
const source = sources[id];
|
|
347
|
-
if (!source) continue;
|
|
348
|
-
owners[id] = {
|
|
349
|
-
specifier: source.file,
|
|
350
|
-
exportName: source.exportName
|
|
351
|
-
};
|
|
352
|
-
}
|
|
353
|
-
const primarySource = primary ? sources[primary.id] : void 0;
|
|
354
|
-
return {
|
|
355
|
-
owners,
|
|
356
|
-
...primary ? { surface: {
|
|
357
|
-
id: primary.id,
|
|
358
|
-
trustedOriginsKey: provideKey(primary.id, "trustedOrigins"),
|
|
359
|
-
...primary.cors ? { cors: primary.cors } : {},
|
|
360
|
-
...primarySource ? { module: {
|
|
361
|
-
specifier: primarySource.file,
|
|
362
|
-
exportName: primarySource.exportName
|
|
363
|
-
} } : {}
|
|
364
|
-
} } : {},
|
|
365
|
-
studio: studio && browsableSource ? {
|
|
366
|
-
...studio,
|
|
367
|
-
database: {
|
|
368
|
-
specifier: browsableSource.file,
|
|
369
|
-
exportName: browsableSource.exportName
|
|
370
|
-
}
|
|
371
|
-
} : studio
|
|
372
|
-
};
|
|
373
|
-
}
|
|
374
|
-
/**
|
|
375
|
-
* The endpoints one surface serves.
|
|
376
|
-
*
|
|
377
|
-
* One glob finds every surface's endpoints, wherever their files live. A build
|
|
378
|
-
* keeps the ones built from the surface it serves; one built from no surface at
|
|
379
|
-
* all has nowhere else to go.
|
|
380
|
-
*/
|
|
381
|
-
function servedBy(endpoints, surface) {
|
|
382
|
-
if (!surface) return endpoints;
|
|
383
|
-
return endpoints.filter(({ construct }) => !construct.surface || construct.surface.id === surface.id);
|
|
384
|
-
}
|
|
385
|
-
function restApis(declared) {
|
|
386
|
-
return Object.values(declared).filter((d) => d.kind === "rest-api");
|
|
387
|
-
}
|
|
388
|
-
/**
|
|
389
|
-
* The surface whose declared `path` is the directory being built — asked of
|
|
390
|
-
* every surface, because a workspace has several and each app's build serves
|
|
391
|
-
* exactly one.
|
|
392
|
-
*/
|
|
393
|
-
function servedSurface(declared, workspaceRoot, appRoot) {
|
|
394
|
-
return restApis(declared).find((d) => resolve(workspaceRoot, d.path) === resolve(appRoot));
|
|
395
|
-
}
|
|
396
|
-
//#endregion
|
|
397
327
|
//#region src/build/providerResolver.ts
|
|
398
328
|
/**
|
|
399
329
|
* Resolves provider configuration from the new simplified system
|
|
@@ -464,1399 +394,970 @@ function isEnabled(config) {
|
|
|
464
394
|
return config.enabled !== false;
|
|
465
395
|
}
|
|
466
396
|
//#endregion
|
|
467
|
-
//#region src/
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
397
|
+
//#region src/workspace/client-generator.ts
|
|
398
|
+
/**
|
|
399
|
+
* Normalize routes to an array of patterns.
|
|
400
|
+
* Handles string, string[], and PartitionedRoutes (extracts paths).
|
|
401
|
+
* @internal Exported for use in dev command
|
|
402
|
+
*/
|
|
403
|
+
function normalizeRoutes(routes) {
|
|
404
|
+
if (!routes) return [];
|
|
405
|
+
if (isPartitionedRoutes(routes)) return Array.isArray(routes.paths) ? routes.paths : [routes.paths];
|
|
406
|
+
return Array.isArray(routes) ? routes : [routes];
|
|
407
|
+
}
|
|
408
|
+
//#endregion
|
|
409
|
+
//#region src/exec/index.ts
|
|
410
|
+
const logger$12 = console;
|
|
411
|
+
/** `gkm exec` was given nothing to run. */
|
|
412
|
+
var NoCommandSpecified = class extends Error {
|
|
413
|
+
constructor() {
|
|
414
|
+
super("No command specified. Usage: gkm exec -- <command>");
|
|
415
|
+
this.name = "NoCommandSpecified";
|
|
416
|
+
}
|
|
417
|
+
};
|
|
418
|
+
/**
|
|
419
|
+
* Run a command with secrets injected into Credentials.
|
|
420
|
+
* Uses Node's --import flag to preload a script that populates Credentials
|
|
421
|
+
* before the command loads any modules that depend on them.
|
|
422
|
+
*
|
|
423
|
+
* @example
|
|
424
|
+
* ```bash
|
|
425
|
+
* gkm exec -- npx @better-auth/cli migrate
|
|
426
|
+
* gkm exec -- npx prisma migrate dev
|
|
427
|
+
* ```
|
|
428
|
+
*/
|
|
429
|
+
async function execCommand(commandArgs, options = {}) {
|
|
430
|
+
const cwd = options.cwd ?? process.cwd();
|
|
431
|
+
if (!commandArgs[0]) throw new NoCommandSpecified();
|
|
432
|
+
const defaultEnv = loadEnvFiles(".env");
|
|
433
|
+
if (defaultEnv.loaded.length > 0) logger$12.log(`📦 Loaded env: ${defaultEnv.loaded.join(", ")}`);
|
|
434
|
+
const { credentials, secretsJsonPath, appName } = await prepareEntryCredentials({
|
|
435
|
+
cwd,
|
|
436
|
+
resolveDockerPorts: "readonly"
|
|
437
|
+
});
|
|
438
|
+
if (appName) logger$12.log(`📦 App: ${appName}`);
|
|
439
|
+
const secretCount = Object.keys(credentials).filter((k) => k !== "PORT").length;
|
|
440
|
+
if (secretCount > 0) logger$12.log(`🔐 Loaded ${secretCount} secret(s)`);
|
|
441
|
+
const preloadDir = join(cwd, ".gkm");
|
|
442
|
+
await mkdir(preloadDir, { recursive: true });
|
|
443
|
+
const preloadPath = join(preloadDir, "credentials-preload.mjs");
|
|
444
|
+
await createCredentialsPreload(preloadPath, secretsJsonPath);
|
|
445
|
+
const [cmd, ...args] = commandArgs;
|
|
446
|
+
logger$12.log(`🚀 Running: ${[cmd, ...args].join(" ")}`);
|
|
447
|
+
const nodeOptions = [(process.env.NODE_OPTIONS ?? "").replace(/--import[= ]\S+/g, "").trim(), `--import=${preloadPath}`].filter(Boolean).join(" ");
|
|
448
|
+
const child = spawn(cmd, args, {
|
|
449
|
+
cwd,
|
|
450
|
+
stdio: "inherit",
|
|
451
|
+
env: {
|
|
452
|
+
...process.env,
|
|
453
|
+
...credentials,
|
|
454
|
+
NODE_OPTIONS: nodeOptions
|
|
493
455
|
}
|
|
494
|
-
|
|
456
|
+
});
|
|
457
|
+
const exitCode = await new Promise((resolve) => {
|
|
458
|
+
child.on("close", (code) => resolve(code ?? 0));
|
|
459
|
+
child.on("error", (error) => {
|
|
460
|
+
logger$12.error(`Failed to run command: ${error.message}`);
|
|
461
|
+
resolve(1);
|
|
462
|
+
});
|
|
463
|
+
});
|
|
464
|
+
if (exitCode !== 0) process.exit(exitCode);
|
|
465
|
+
}
|
|
466
|
+
//#endregion
|
|
467
|
+
//#region src/dev/index.ts
|
|
468
|
+
const logger$11 = console;
|
|
469
|
+
/**
|
|
470
|
+
* Normalize telescope configuration
|
|
471
|
+
* @internal Exported for testing
|
|
472
|
+
*/
|
|
473
|
+
function normalizeTelescopeConfig(config) {
|
|
474
|
+
if (config === false) return;
|
|
475
|
+
if (typeof config === "string") {
|
|
476
|
+
const { path: telescopePath, importPattern: telescopeImportPattern } = parseModuleConfig(config, "telescope");
|
|
477
|
+
return {
|
|
478
|
+
enabled: true,
|
|
479
|
+
telescopePath,
|
|
480
|
+
telescopeImportPattern,
|
|
481
|
+
path: "/__telescope",
|
|
482
|
+
ignore: [],
|
|
483
|
+
recordBody: true,
|
|
484
|
+
maxEntries: 1e3,
|
|
485
|
+
websocket: true
|
|
486
|
+
};
|
|
495
487
|
}
|
|
496
|
-
|
|
497
|
-
|
|
488
|
+
if (!(config === true || config === void 0 || config.enabled !== false)) return;
|
|
489
|
+
const telescopeConfig = typeof config === "object" ? config : {};
|
|
490
|
+
return {
|
|
491
|
+
enabled: true,
|
|
492
|
+
path: telescopeConfig.path ?? "/__telescope",
|
|
493
|
+
ignore: telescopeConfig.ignore ?? [],
|
|
494
|
+
recordBody: telescopeConfig.recordBody ?? true,
|
|
495
|
+
maxEntries: telescopeConfig.maxEntries ?? 1e3,
|
|
496
|
+
websocket: telescopeConfig.websocket ?? true
|
|
497
|
+
};
|
|
498
|
+
}
|
|
499
|
+
/**
|
|
500
|
+
* Normalize studio configuration
|
|
501
|
+
* @internal Exported for testing
|
|
502
|
+
*/
|
|
503
|
+
function normalizeStudioConfig(config) {
|
|
504
|
+
if (config === false) return;
|
|
505
|
+
if (typeof config === "string") {
|
|
506
|
+
const { path: studioPath, importPattern: studioImportPattern } = parseModuleConfig(config, "studio");
|
|
507
|
+
return {
|
|
508
|
+
enabled: true,
|
|
509
|
+
studioPath,
|
|
510
|
+
studioImportPattern,
|
|
511
|
+
path: "/__studio",
|
|
512
|
+
schema: "public"
|
|
513
|
+
};
|
|
498
514
|
}
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
* uses pg-boss, whose schedules live in the database — so a deployment
|
|
507
|
-
* running four replicas fires each job once, which is the thing a timer in
|
|
508
|
-
* every process gets wrong and does not report. With no database it falls
|
|
509
|
-
* back to timers and says plainly that it is doing so.
|
|
510
|
-
*/
|
|
511
|
-
async generateServerCronsFile(outputDir, crons) {
|
|
512
|
-
await mkdir(outputDir, { recursive: true });
|
|
513
|
-
const cronsPath = join(outputDir, "crons.ts");
|
|
514
|
-
const importsByFile = /* @__PURE__ */ new Map();
|
|
515
|
-
for (const { path, key } of crons) {
|
|
516
|
-
const importPath = relative(dirname(cronsPath), path.relative).replace(/\.ts$/, ".js");
|
|
517
|
-
if (!importsByFile.has(importPath)) importsByFile.set(importPath, []);
|
|
518
|
-
importsByFile.get(importPath)?.push(key);
|
|
519
|
-
}
|
|
520
|
-
const content = `/**
|
|
521
|
-
* Generated cron setup.
|
|
522
|
-
*
|
|
523
|
-
* Schedules every cron this app declares, in the process that serves it.
|
|
524
|
-
*
|
|
525
|
-
* The schedule lives in Postgres, through pg-boss, in the database the worker
|
|
526
|
-
* named with \`.database(db)\`. That is what makes running several replicas
|
|
527
|
-
* safe: each job fires once, where a timer in every process fires it once per
|
|
528
|
-
* replica and reports nothing.
|
|
529
|
-
*
|
|
530
|
-
* No connection string appears here. The construct that owns the database is
|
|
531
|
-
* the only thing that knows its key, and it is resolved through service
|
|
532
|
-
* discovery like any other dependency.
|
|
533
|
-
*/
|
|
534
|
-
import type { EnvironmentParser } from '@geekmidas/envkit';
|
|
535
|
-
import type { Logger } from '@geekmidas/logger';
|
|
536
|
-
import { toCronExpression } from '@geekmidas/constructs/crons';
|
|
537
|
-
import { ServiceDiscovery } from '@geekmidas/services';
|
|
538
|
-
${Array.from(importsByFile.entries()).map(([importPath, exports]) => `import { ${exports.join(", ")} } from '${importPath}';`).join("\n")}
|
|
539
|
-
|
|
540
|
-
const crons = [
|
|
541
|
-
${crons.map(({ key }) => ` { name: '${key}', cron: ${key} }`).join(",\n")}
|
|
542
|
-
];
|
|
543
|
-
|
|
544
|
-
type Stoppable = { stop: () => Promise<void> | void };
|
|
545
|
-
const running: Stoppable[] = [];
|
|
546
|
-
|
|
547
|
-
export async function setupCrons(
|
|
548
|
-
envParser: EnvironmentParser<any>,
|
|
549
|
-
logger: Logger,
|
|
550
|
-
): Promise<void> {
|
|
551
|
-
if (crons.length === 0) {
|
|
552
|
-
return;
|
|
553
|
-
}
|
|
554
|
-
|
|
555
|
-
const serviceDiscovery = ServiceDiscovery.getInstance(envParser);
|
|
556
|
-
|
|
557
|
-
// Resolved once per cron rather than per firing: registering services on
|
|
558
|
-
// every tick would reconnect a database every minute.
|
|
559
|
-
const prepared = [];
|
|
560
|
-
for (const { name, cron } of crons) {
|
|
561
|
-
try {
|
|
562
|
-
const schedule = toCronExpression(cron.schedule);
|
|
563
|
-
const services = cron.services.length > 0
|
|
564
|
-
? await serviceDiscovery.register(cron.services)
|
|
565
|
-
: {};
|
|
566
|
-
|
|
567
|
-
prepared.push({ name, cron, schedule, services });
|
|
568
|
-
} catch (error) {
|
|
569
|
-
// An unrepresentable schedule is a build-time mistake, and failing the
|
|
570
|
-
// process for it would take the HTTP server down with it.
|
|
571
|
-
logger.error({ error, cron: name }, 'Cron has no runnable schedule, skipping');
|
|
572
|
-
}
|
|
573
|
-
}
|
|
574
|
-
|
|
575
|
-
const run = async (entry: (typeof prepared)[number]) => {
|
|
576
|
-
try {
|
|
577
|
-
await entry.cron.handler({
|
|
578
|
-
input: undefined,
|
|
579
|
-
services: entry.services,
|
|
580
|
-
logger: entry.cron.logger,
|
|
581
|
-
});
|
|
582
|
-
} catch (error) {
|
|
583
|
-
logger.error({ error, cron: entry.name }, 'Cron failed');
|
|
584
|
-
}
|
|
585
|
-
};
|
|
586
|
-
|
|
587
|
-
// Declared once on the worker, carried onto every cron it built — so this
|
|
588
|
-
// reads it from any of them rather than from config or the environment.
|
|
589
|
-
const scheduleStore = prepared.find(({ cron }) => cron.scheduleStore)?.cron
|
|
590
|
-
.scheduleStore;
|
|
591
|
-
|
|
592
|
-
if (!scheduleStore) {
|
|
593
|
-
// Declared, not discovered. A worker says where its schedules live with
|
|
594
|
-
// \`.database(db)\`; inferring one from whatever database happened to be
|
|
595
|
-
// around would move the schedules the day an app declared a second.
|
|
596
|
-
logger.error(
|
|
597
|
-
{ crons: prepared.map(({ name }) => name) },
|
|
598
|
-
'These crons have nowhere to keep their schedule. A server fires its own ' +
|
|
599
|
-
'crons, and a process scheduling in memory fires each job once per ' +
|
|
600
|
-
'replica — so the schedule lives in Postgres. Say where with ' +
|
|
601
|
-
'\`new Worker(…).database(db)\`.',
|
|
602
|
-
);
|
|
603
|
-
return;
|
|
604
|
-
}
|
|
605
|
-
|
|
606
|
-
const [store] = await serviceDiscovery
|
|
607
|
-
.register([scheduleStore])
|
|
608
|
-
.then((s) => Object.values(s));
|
|
609
|
-
|
|
610
|
-
const { PgBoss } = await import('pg-boss');
|
|
611
|
-
// The pool the construct already opened — no connection string is read here,
|
|
612
|
-
// and none is named anywhere outside the construct that owns it.
|
|
613
|
-
const boss = new PgBoss({ db: store as never });
|
|
614
|
-
await boss.start();
|
|
615
|
-
|
|
616
|
-
// What this app declares now. Anything else under the prefix belonged to a
|
|
617
|
-
// cron since renamed or deleted, and would keep firing at a handler that has
|
|
618
|
-
// gone.
|
|
619
|
-
//
|
|
620
|
-
// The prefix is \`cron.\` rather than \`cron:\`: pg-boss accepts
|
|
621
|
-
// alphanumerics, underscores, hyphens, periods and slashes in a queue name,
|
|
622
|
-
// and rejects a colon outright.
|
|
623
|
-
const declared = new Set(prepared.map(({ name }) => \`cron.\${name}\`));
|
|
624
|
-
for (const existing of await boss.getSchedules()) {
|
|
625
|
-
if (existing.name.startsWith('cron.') && !declared.has(existing.name)) {
|
|
626
|
-
await boss.unschedule(existing.name);
|
|
627
|
-
logger.info({ cron: existing.name }, 'Removed a schedule nothing declares');
|
|
628
|
-
}
|
|
629
|
-
}
|
|
630
|
-
|
|
631
|
-
for (const entry of prepared) {
|
|
632
|
-
const queue = \`cron.\${entry.name}\`;
|
|
633
|
-
await boss.createQueue(queue);
|
|
634
|
-
// UTC, so this agrees with the schedule a deploy target would have made.
|
|
635
|
-
await boss.schedule(queue, entry.schedule, undefined, { tz: 'UTC' });
|
|
636
|
-
await boss.work(queue, () => run(entry));
|
|
637
|
-
|
|
638
|
-
logger.info({ cron: entry.name, schedule: entry.schedule }, 'Cron scheduled');
|
|
639
|
-
}
|
|
640
|
-
|
|
641
|
-
running.push({ stop: () => boss.stop() });
|
|
642
|
-
logger.info({ count: prepared.length }, 'Crons scheduled');
|
|
643
|
-
}
|
|
644
|
-
|
|
645
|
-
export async function stopCrons(): Promise<void> {
|
|
646
|
-
await Promise.all(running.map((r) => r.stop()));
|
|
647
|
-
running.length = 0;
|
|
515
|
+
if (!(config === true || config === void 0 || config.enabled !== false)) return;
|
|
516
|
+
const studioConfig = typeof config === "object" ? config : {};
|
|
517
|
+
return {
|
|
518
|
+
enabled: true,
|
|
519
|
+
path: studioConfig.path ?? "/__studio",
|
|
520
|
+
schema: studioConfig.schema ?? "public"
|
|
521
|
+
};
|
|
648
522
|
}
|
|
649
|
-
`;
|
|
650
|
-
await writeFile(cronsPath, content);
|
|
651
|
-
return cronsPath;
|
|
652
|
-
}
|
|
653
|
-
async generateCronHandler(outputDir, sourceFile, exportName, context, owner) {
|
|
654
|
-
const handlerFileName = `${exportName}.ts`;
|
|
655
|
-
const handlerPath = join(outputDir, handlerFileName);
|
|
656
|
-
const importPath = relative(dirname(handlerPath), sourceFile).replace(/\.ts$/, ".js");
|
|
657
|
-
const runtime = runtimeFor(context, dirname(handlerPath), owner);
|
|
658
|
-
const content = `import { AWSScheduledFunction } from '@geekmidas/constructs/aws';
|
|
659
|
-
import { ${exportName} } from '${importPath}';
|
|
660
|
-
${runtime.imports}
|
|
661
|
-
${runtime.bindings}
|
|
662
|
-
|
|
663
|
-
const adapter = new AWSScheduledFunction(envParser, ${exportName});
|
|
664
|
-
|
|
665
|
-
export const handler = adapter.handler;
|
|
666
|
-
`;
|
|
667
|
-
await writeFile(handlerPath, content);
|
|
668
|
-
return handlerPath;
|
|
669
|
-
}
|
|
670
|
-
};
|
|
671
|
-
//#endregion
|
|
672
|
-
//#region src/generators/drivers.ts
|
|
673
|
-
/**
|
|
674
|
-
* Driver registration for generated entry points.
|
|
675
|
-
*
|
|
676
|
-
* A construct declares that it needs object storage and is handed one URL; the
|
|
677
|
-
* scheme in that URL picks the driver that builds the client. Which drivers
|
|
678
|
-
* exist is therefore the *entry point's* decision, not the construct's and not
|
|
679
|
-
* the application's — an app that never talks to S3 should never resolve the AWS
|
|
680
|
-
* SDK, and application code that registers a driver has named a provider in the
|
|
681
|
-
* one layer this design keeps provider-free.
|
|
682
|
-
*
|
|
683
|
-
* So the generated entries register: `gkm dev`'s server for local development,
|
|
684
|
-
* and each Lambda handler for its own target. Registration is an explicit call
|
|
685
|
-
* rather than an import side effect, because a side-effecting module is exactly
|
|
686
|
-
* what a bundler is entitled to drop.
|
|
687
|
-
*/
|
|
688
|
-
/** The `s3://` driver, which serves MinIO locally and S3 deployed. */
|
|
689
|
-
const S3 = {
|
|
690
|
-
imports: `import { registerStorageDriver } from '@geekmidas/storage';\nimport { s3Driver } from '@geekmidas/storage/aws';`,
|
|
691
|
-
setup: "registerStorageDriver(s3Driver);"
|
|
692
|
-
};
|
|
693
|
-
const NONE = {
|
|
694
|
-
imports: "",
|
|
695
|
-
setup: ""
|
|
696
|
-
};
|
|
697
523
|
/**
|
|
698
|
-
*
|
|
699
|
-
*
|
|
700
|
-
* Keyed off the *backend* rather than off a dependency, because unlike storage
|
|
701
|
-
* the backend already says which driver is right: a project caching in Postgres
|
|
702
|
-
* resolves `pg` and never `ioredis`, and one caching in Upstash resolves
|
|
703
|
-
* neither. That is the whole reason the drivers live behind separate subpaths.
|
|
704
|
-
*
|
|
705
|
-
* Both HTTP schemes are registered for Upstash, because the local proxy speaks
|
|
706
|
-
* `http://` and Upstash speaks `https://`, and an entry that registered one
|
|
707
|
-
* would work in exactly one of the two places.
|
|
524
|
+
* Normalize hooks configuration
|
|
525
|
+
* @internal Exported for testing
|
|
708
526
|
*/
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
elasticache: {
|
|
715
|
-
imports: `import { registerCacheDriver } from '@geekmidas/cache';\nimport { redisCacheDriver, redissCacheDriver } from '@geekmidas/cache/redis';`,
|
|
716
|
-
setup: "registerCacheDriver(redisCacheDriver);\nregisterCacheDriver(redissCacheDriver);"
|
|
717
|
-
},
|
|
718
|
-
db: {
|
|
719
|
-
imports: `import { registerCacheDriver } from '@geekmidas/cache';\nimport { postgresCacheDriver } from '@geekmidas/cache/postgres';`,
|
|
720
|
-
setup: "registerCacheDriver(postgresCacheDriver);"
|
|
721
|
-
}
|
|
722
|
-
};
|
|
527
|
+
function normalizeHooksConfig(config, cwd = process.cwd()) {
|
|
528
|
+
if (!config?.server) return;
|
|
529
|
+
const serverPath = config.server.endsWith(".ts") ? config.server : `${config.server}.ts`;
|
|
530
|
+
return { serverHooksPath: resolve(cwd, serverPath) };
|
|
531
|
+
}
|
|
723
532
|
/**
|
|
724
|
-
*
|
|
725
|
-
*
|
|
726
|
-
* Merged here rather than threaded separately, because a generated file has one
|
|
727
|
-
* import block and one setup block whatever fills them.
|
|
533
|
+
* Normalize production configuration
|
|
534
|
+
* @internal Exported for testing
|
|
728
535
|
*/
|
|
729
|
-
function
|
|
730
|
-
|
|
731
|
-
const
|
|
732
|
-
if (parts.length === 0) return NONE;
|
|
536
|
+
function normalizeProductionConfig(cliProduction, configProduction) {
|
|
537
|
+
if (!cliProduction) return;
|
|
538
|
+
const config = configProduction ?? {};
|
|
733
539
|
return {
|
|
734
|
-
|
|
735
|
-
|
|
540
|
+
enabled: true,
|
|
541
|
+
bundle: config.bundle ?? true,
|
|
542
|
+
minify: config.minify ?? true,
|
|
543
|
+
healthCheck: config.healthCheck ?? "/health",
|
|
544
|
+
gracefulShutdown: config.gracefulShutdown ?? true,
|
|
545
|
+
external: config.external ?? [],
|
|
546
|
+
subscribers: config.subscribers ?? "exclude",
|
|
547
|
+
openapi: config.openapi ?? false,
|
|
548
|
+
optimizedHandlers: config.optimizedHandlers ?? true
|
|
736
549
|
};
|
|
737
550
|
}
|
|
738
551
|
/**
|
|
739
|
-
*
|
|
740
|
-
*
|
|
741
|
-
* The config answers this for a cache that named nowhere, and the *declaration*
|
|
742
|
-
* answers it for one that named a database — `orders.cache('Sessions')` is a
|
|
743
|
-
* statement about the application, so a deployment cannot move that cache and
|
|
744
|
-
* the entry cannot register a driver for somewhere else.
|
|
745
|
-
*
|
|
746
|
-
* Reading only the config is how an entry ends up registering the Upstash
|
|
747
|
-
* driver for a URL the target composed as `postgres://`, which fails at the
|
|
748
|
-
* first request with `UnregisteredCacheScheme` and a stack that points at the
|
|
749
|
-
* cache rather than at the config that disagreed.
|
|
750
|
-
*/
|
|
751
|
-
function cacheBackendsIn(manifest, configured) {
|
|
752
|
-
const caches = Object.values(manifest).filter((d) => d.kind === "cache");
|
|
753
|
-
return [...new Set(caches.map((c) => c.of ? "db" : configured))];
|
|
754
|
-
}
|
|
755
|
-
/**
|
|
756
|
-
* The drivers an app's entry points should register.
|
|
757
|
-
*
|
|
758
|
-
* Keyed off the dependency rather than off a declared bucket, because the entry
|
|
759
|
-
* is generated before discovery has run on the watcher's rebuild path — and an
|
|
760
|
-
* app that installed `@geekmidas/storage` has already paid for the SDK it would
|
|
761
|
-
* otherwise resolve lazily.
|
|
552
|
+
* Get production config from GkmConfig
|
|
553
|
+
* @internal
|
|
762
554
|
*/
|
|
763
|
-
function
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
function dependsOnStorage(appRoot) {
|
|
767
|
-
const manifest = join(appRoot, "package.json");
|
|
768
|
-
if (!existsSync(manifest)) return false;
|
|
769
|
-
try {
|
|
770
|
-
const pkg = JSON.parse(readFileSync(manifest, "utf8"));
|
|
771
|
-
return Boolean(pkg.dependencies?.["@geekmidas/storage"] ?? pkg.devDependencies?.["@geekmidas/storage"]);
|
|
772
|
-
} catch {
|
|
773
|
-
return false;
|
|
774
|
-
}
|
|
555
|
+
function getProductionConfigFromGkm(config) {
|
|
556
|
+
const serverConfig = config.providers?.server;
|
|
557
|
+
if (typeof serverConfig === "object") return serverConfig.production;
|
|
775
558
|
}
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
559
|
+
async function devCommand(options) {
|
|
560
|
+
if (options.entry) return entryDevCommand(options);
|
|
561
|
+
const defaultEnv = loadEnvFiles(".env");
|
|
562
|
+
if (defaultEnv.loaded.length > 0) logger$11.log(`📦 Loaded env: ${defaultEnv.loaded.join(", ")}`);
|
|
563
|
+
const appName = getAppNameFromCwd();
|
|
564
|
+
let config;
|
|
565
|
+
let appRoot = process.cwd();
|
|
566
|
+
let secretsRoot = process.cwd();
|
|
567
|
+
let workspaceAppName;
|
|
568
|
+
let workspaceAppPort;
|
|
569
|
+
let workspace;
|
|
570
|
+
if (appName) try {
|
|
571
|
+
const appConfig = await loadAppConfig();
|
|
572
|
+
config = appConfig.gkmConfig;
|
|
573
|
+
appRoot = appConfig.appRoot;
|
|
574
|
+
secretsRoot = appConfig.workspaceRoot;
|
|
575
|
+
workspaceAppName = appConfig.appName;
|
|
576
|
+
workspaceAppPort = appConfig.app.port;
|
|
577
|
+
workspace = appConfig.workspace;
|
|
578
|
+
logger$11.log(`📦 Running app: ${appConfig.appName} on port ${workspaceAppPort}`);
|
|
579
|
+
if (appConfig.app.entry) {
|
|
580
|
+
logger$11.log(`📄 Using entry point: ${appConfig.app.entry}`);
|
|
581
|
+
return entryDevCommand({
|
|
582
|
+
...options,
|
|
583
|
+
entry: appConfig.app.entry,
|
|
584
|
+
port: workspaceAppPort,
|
|
585
|
+
portExplicit: true
|
|
798
586
|
});
|
|
799
|
-
logger.log(`Generated function handler: ${key}`);
|
|
800
587
|
}
|
|
801
|
-
|
|
588
|
+
} catch {
|
|
589
|
+
const loadedConfig = await loadWorkspaceConfig();
|
|
590
|
+
if (loadedConfig.type === "workspace") {
|
|
591
|
+
logger$11.log("📦 Detected workspace configuration");
|
|
592
|
+
return workspaceDevCommand(loadedConfig.workspace, options);
|
|
593
|
+
}
|
|
594
|
+
config = loadedConfig.raw;
|
|
802
595
|
}
|
|
803
|
-
|
|
804
|
-
const
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
${runtime.bindings}
|
|
812
|
-
|
|
813
|
-
const adapter = new AWSLambdaFunction(envParser, ${exportName});
|
|
814
|
-
|
|
815
|
-
export const handler = adapter.handler;
|
|
816
|
-
`;
|
|
817
|
-
await writeFile(handlerPath, content);
|
|
818
|
-
return handlerPath;
|
|
596
|
+
else {
|
|
597
|
+
const loadedConfig = await loadWorkspaceConfig();
|
|
598
|
+
if (loadedConfig.type === "workspace") {
|
|
599
|
+
logger$11.log("📦 Detected workspace configuration");
|
|
600
|
+
return workspaceDevCommand(loadedConfig.workspace, options);
|
|
601
|
+
}
|
|
602
|
+
config = loadedConfig.raw;
|
|
603
|
+
workspace = loadedConfig.workspace;
|
|
819
604
|
}
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
* Generates the runtime for `q` queue workers.
|
|
825
|
-
*
|
|
826
|
-
* - **server** (`gkm dev`): a single `queues.ts` exposing `setupQueues()` that
|
|
827
|
-
* runs an in-process pg-boss poller alongside the Hono server — no SQS/Lambda.
|
|
828
|
-
* Each queue subscribes by its **name** on the shared event connection.
|
|
829
|
-
* - **aws-lambda**: one handler file per queue wrapping `AWSLambdaQueue`, backed
|
|
830
|
-
* by an SQS event-source mapping.
|
|
831
|
-
*/
|
|
832
|
-
var QueueGenerator = class extends ConstructGenerator {
|
|
833
|
-
isConstruct(value) {
|
|
834
|
-
return Queue.isQueue(value);
|
|
605
|
+
if (config.env) {
|
|
606
|
+
const { loaded, missing } = loadEnvFiles(config.env, appRoot);
|
|
607
|
+
if (loaded.length > 0) logger$11.log(`📦 Loaded env: ${loaded.join(", ")}`);
|
|
608
|
+
if (missing.length > 0) logger$11.warn(`⚠️ Missing env files: ${missing.join(", ")}`);
|
|
835
609
|
}
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
610
|
+
const resolved = resolveProviders(config, { provider: "server" });
|
|
611
|
+
logger$11.log("🚀 Starting development server...");
|
|
612
|
+
logger$11.log(`Loading constructs from: ${config.constructs}`);
|
|
613
|
+
const telescope = normalizeTelescopeConfig(config.telescope);
|
|
614
|
+
if (telescope) logger$11.log(`🔭 Telescope enabled at ${telescope.path}`);
|
|
615
|
+
const studio = normalizeStudioConfig(config.studio);
|
|
616
|
+
if (studio) logger$11.log(`🗄️ Studio enabled at ${studio.path}`);
|
|
617
|
+
const hooks = normalizeHooksConfig(config.hooks, appRoot);
|
|
618
|
+
if (hooks) logger$11.log(`🪝 Server hooks enabled from ${config.hooks?.server}`);
|
|
619
|
+
const enableOpenApi = resolveOpenApiConfig(config).enabled || resolved.enableOpenApi;
|
|
620
|
+
if (enableOpenApi) logger$11.log(`📄 OpenAPI output: ${OPENAPI_OUTPUT_PATH$1}`);
|
|
621
|
+
const build = (bustCache = false) => buildApp({
|
|
622
|
+
config,
|
|
623
|
+
workspaceRoot: workspace?.root ?? secretsRoot,
|
|
624
|
+
appRoot,
|
|
625
|
+
providers: ["server"],
|
|
626
|
+
enableOpenApi,
|
|
627
|
+
cacheBackend: cacheBackendFor(providerOf(workspace ?? config)),
|
|
628
|
+
telescope,
|
|
629
|
+
studio,
|
|
630
|
+
hooks,
|
|
631
|
+
skipBundle: true,
|
|
632
|
+
bustCache,
|
|
633
|
+
serveEmpty: true
|
|
634
|
+
});
|
|
635
|
+
const initial = await build();
|
|
636
|
+
const runtime = config.runtime ?? "node";
|
|
637
|
+
let secretsJsonPath;
|
|
638
|
+
const appSecrets = await loadSecretsForApp(secretsRoot, config.stages.local, workspaceAppName);
|
|
639
|
+
if (workspace && usesConstructs(workspace)) {
|
|
640
|
+
const reconciled = await reconcileWorkspace(workspace, { stage: workspace.stages.local });
|
|
641
|
+
if (reconciled.changed && reconciled.plan.containers.length > 0) {
|
|
642
|
+
logger$11.log(`🐳 Services: ${reconciled.plan.containers.join(", ")}`);
|
|
643
|
+
for (const [container, address] of Object.entries(reconciled.addresses)) logger$11.log(` ${container}: ${address}`);
|
|
844
644
|
}
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
const
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
handler: relative(process.cwd(), handlerFile).replace(/\.ts$/, ".handler"),
|
|
853
|
-
batchSize: construct.batchSize,
|
|
854
|
-
fifo: construct.fifo,
|
|
855
|
-
timeout: construct.timeout,
|
|
856
|
-
environment: await construct.getEnvironment({ markOptional: context.markOptional }),
|
|
857
|
-
dependencies: construct.constructs
|
|
858
|
-
});
|
|
859
|
-
logger.log(`Generated queue handler: ${key}`);
|
|
645
|
+
Object.assign(appSecrets, reconciled.env);
|
|
646
|
+
} else {
|
|
647
|
+
const resolvedPorts = await resolveServicePorts(secretsRoot);
|
|
648
|
+
if (Object.keys(resolvedPorts.ports).length > 0) {
|
|
649
|
+
const rewritten = rewriteUrlsWithPorts(appSecrets, resolvedPorts);
|
|
650
|
+
Object.assign(appSecrets, rewritten);
|
|
651
|
+
logger$11.log(`🔌 Applied ${Object.keys(resolvedPorts.ports).length} port mapping(s)`);
|
|
860
652
|
}
|
|
861
|
-
return queueInfos;
|
|
862
653
|
}
|
|
863
|
-
|
|
864
|
-
const
|
|
865
|
-
|
|
866
|
-
const runtime = runtimeFor(context, dirname(handlerPath), owner);
|
|
867
|
-
const content = `import { AWSLambdaQueue } from '@geekmidas/constructs/aws';
|
|
868
|
-
import { ${exportName} } from '${importPath}';
|
|
869
|
-
${runtime.imports}
|
|
870
|
-
${runtime.bindings}
|
|
871
|
-
|
|
872
|
-
const adapter = new AWSLambdaQueue(envParser, ${exportName});
|
|
873
|
-
|
|
874
|
-
export const handler = adapter.handler;
|
|
875
|
-
`;
|
|
876
|
-
await writeFile(handlerPath, content);
|
|
877
|
-
return handlerPath;
|
|
654
|
+
if (workspace && workspaceAppName) {
|
|
655
|
+
const depEnv = getDependencyEnvVars(workspace, workspaceAppName);
|
|
656
|
+
Object.assign(appSecrets, depEnv);
|
|
878
657
|
}
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
const
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
: {};
|
|
945
|
-
|
|
946
|
-
// A queue subscribes to a single "type" — its own name.
|
|
947
|
-
await eventSubscriber.subscribe([queue.name], async (message) => {
|
|
948
|
-
try {
|
|
949
|
-
const validation = await queue.messageSchema['~standard'].validate(message.payload);
|
|
950
|
-
if (validation.issues) {
|
|
951
|
-
logger.error({ issues: validation.issues, queue: queue.name }, 'Queue message failed validation');
|
|
952
|
-
return;
|
|
953
|
-
}
|
|
954
|
-
|
|
955
|
-
await queue.handler({
|
|
956
|
-
messages: [validation.value],
|
|
957
|
-
services: services,
|
|
958
|
-
logger: queue.logger,
|
|
959
|
-
});
|
|
960
|
-
|
|
961
|
-
logger.debug({ queue: queue.name }, 'Successfully processed queue message');
|
|
962
|
-
} catch (error) {
|
|
963
|
-
logger.error({ error, queue: queue.name }, 'Failed to process queue message');
|
|
964
|
-
// Message will become visible again for retry.
|
|
965
|
-
}
|
|
966
|
-
});
|
|
967
|
-
|
|
968
|
-
activeSubscribers.push(eventSubscriber);
|
|
969
|
-
logger.info({ queue: queue.name }, 'Queue worker started polling');
|
|
970
|
-
} catch (error) {
|
|
971
|
-
logger.error({ error, queue: queue.name }, 'Failed to setup queue worker');
|
|
972
|
-
}
|
|
973
|
-
}
|
|
974
|
-
|
|
975
|
-
const shutdown = () => {
|
|
976
|
-
logger.info('Stopping all queue workers');
|
|
977
|
-
for (const _ of activeSubscribers) {
|
|
978
|
-
connection.stop();
|
|
979
|
-
}
|
|
980
|
-
};
|
|
981
|
-
|
|
982
|
-
process.on('SIGTERM', shutdown);
|
|
983
|
-
process.on('SIGINT', shutdown);
|
|
658
|
+
if (Object.keys(appSecrets).length > 0) {
|
|
659
|
+
const secretsDir = join(secretsRoot, ".gkm");
|
|
660
|
+
await mkdir(secretsDir, { recursive: true });
|
|
661
|
+
const secretsFileName = workspaceAppName ? `dev-secrets-${workspaceAppName}.json` : "dev-secrets.json";
|
|
662
|
+
secretsJsonPath = join(secretsDir, secretsFileName);
|
|
663
|
+
await writeFile(secretsJsonPath, JSON.stringify(appSecrets, null, 2));
|
|
664
|
+
logger$11.log(`🔐 Loaded ${Object.keys(appSecrets).length} secret(s)`);
|
|
665
|
+
}
|
|
666
|
+
const devServer = new DevServer(resolved.providers[0], options.port ?? workspaceAppPort ?? 3e3, options.portExplicit ?? false, enableOpenApi, telescope, studio, runtime, appRoot, secretsJsonPath, initial.selfServing !== void 0);
|
|
667
|
+
await devServer.start();
|
|
668
|
+
const hooksFile = (config.hooks?.server?.split("#"))?.[0];
|
|
669
|
+
const normalizedPatterns = [config.constructs, ...hooksFile ? [hooksFile.endsWith(".ts") ? hooksFile : `${hooksFile}.ts`] : []].flat().filter((p) => typeof p === "string").map((p) => p.startsWith("./") ? p.slice(2) : p);
|
|
670
|
+
logger$11.log(`👀 Watching for changes in: ${normalizedPatterns.join(", ")}`);
|
|
671
|
+
const resolvedFiles = await fg(normalizedPatterns, {
|
|
672
|
+
cwd: appRoot,
|
|
673
|
+
absolute: false,
|
|
674
|
+
onlyFiles: true
|
|
675
|
+
});
|
|
676
|
+
const dirsToWatch = [...new Set(resolvedFiles.map((f) => {
|
|
677
|
+
return f.split("/").slice(0, -1).join("/");
|
|
678
|
+
}))];
|
|
679
|
+
logger$11.log(`📁 Found ${resolvedFiles.length} files in ${dirsToWatch.length} directories`);
|
|
680
|
+
const watcher = chokidar.watch([...resolvedFiles, ...dirsToWatch], {
|
|
681
|
+
ignored: /(^|[/\\])\../,
|
|
682
|
+
persistent: true,
|
|
683
|
+
ignoreInitial: true,
|
|
684
|
+
cwd: appRoot
|
|
685
|
+
});
|
|
686
|
+
watcher.on("ready", () => {
|
|
687
|
+
logger$11.log("🔍 File watcher ready");
|
|
688
|
+
});
|
|
689
|
+
watcher.on("error", (error) => {
|
|
690
|
+
logger$11.error("❌ Watcher error:", error);
|
|
691
|
+
});
|
|
692
|
+
let rebuildTimeout = null;
|
|
693
|
+
watcher.on("change", async (path) => {
|
|
694
|
+
logger$11.log(`📝 File changed: ${path}`);
|
|
695
|
+
if (rebuildTimeout) clearTimeout(rebuildTimeout);
|
|
696
|
+
rebuildTimeout = setTimeout(async () => {
|
|
697
|
+
try {
|
|
698
|
+
logger$11.log("🔄 Rebuilding...");
|
|
699
|
+
const rebuilt = await build(true);
|
|
700
|
+
logger$11.log("✅ Rebuild complete, restarting server...");
|
|
701
|
+
devServer.selfServing = rebuilt.selfServing !== void 0;
|
|
702
|
+
await devServer.restart();
|
|
703
|
+
} catch (error) {
|
|
704
|
+
const err = error;
|
|
705
|
+
logger$11.error(`❌ Rebuild failed: ${err.message}`);
|
|
706
|
+
if (err.stack) logger$11.error(err.stack);
|
|
707
|
+
}
|
|
708
|
+
}, 300);
|
|
709
|
+
});
|
|
710
|
+
let isShuttingDown = false;
|
|
711
|
+
const shutdown = () => {
|
|
712
|
+
if (isShuttingDown) return;
|
|
713
|
+
isShuttingDown = true;
|
|
714
|
+
logger$11.log("\n🛑 Shutting down...");
|
|
715
|
+
Promise.all([watcher.close(), devServer.stop()]).catch((err) => {
|
|
716
|
+
logger$11.error("Error during shutdown:", err);
|
|
717
|
+
}).finally(() => {
|
|
718
|
+
process.exit(0);
|
|
719
|
+
});
|
|
720
|
+
};
|
|
721
|
+
process.on("SIGINT", shutdown);
|
|
722
|
+
process.on("SIGTERM", shutdown);
|
|
984
723
|
}
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
724
|
+
/**
|
|
725
|
+
* Generate all dependency environment variables for all apps.
|
|
726
|
+
* Returns a flat object with all {APP_NAME}_URL variables.
|
|
727
|
+
* @internal Exported for testing
|
|
728
|
+
*/
|
|
729
|
+
function generateAllDependencyEnvVars(workspace, urlPrefix = "http://localhost") {
|
|
730
|
+
const env = {};
|
|
731
|
+
for (const appName of Object.keys(workspace.apps)) {
|
|
732
|
+
const appEnv = getDependencyEnvVars(workspace, appName, urlPrefix);
|
|
733
|
+
Object.assign(env, appEnv);
|
|
988
734
|
}
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
735
|
+
return env;
|
|
736
|
+
}
|
|
737
|
+
/**
|
|
738
|
+
* Check for port conflicts across all apps.
|
|
739
|
+
* Returns list of conflicts if any ports are duplicated.
|
|
740
|
+
* @internal Exported for testing
|
|
741
|
+
*/
|
|
742
|
+
function checkPortConflicts(workspace) {
|
|
743
|
+
const conflicts = [];
|
|
744
|
+
const portToApp = /* @__PURE__ */ new Map();
|
|
745
|
+
for (const [appName, app] of Object.entries(workspace.apps)) {
|
|
746
|
+
const existingApp = portToApp.get(app.port);
|
|
747
|
+
if (existingApp) conflicts.push({
|
|
748
|
+
app1: existingApp,
|
|
749
|
+
app2: appName,
|
|
750
|
+
port: app.port
|
|
751
|
+
});
|
|
752
|
+
else portToApp.set(app.port, appName);
|
|
995
753
|
}
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
754
|
+
return conflicts;
|
|
755
|
+
}
|
|
756
|
+
const FRONTEND_FRAMEWORKS = {
|
|
757
|
+
nextjs: {
|
|
758
|
+
displayName: "Next.js",
|
|
759
|
+
configFiles: [
|
|
760
|
+
"next.config.js",
|
|
761
|
+
"next.config.ts",
|
|
762
|
+
"next.config.mjs",
|
|
763
|
+
"next.config.cjs"
|
|
764
|
+
],
|
|
765
|
+
dependency: "next",
|
|
766
|
+
installCommand: "pnpm add next react react-dom"
|
|
767
|
+
},
|
|
768
|
+
remix: {
|
|
769
|
+
displayName: "Remix",
|
|
770
|
+
configFiles: [
|
|
771
|
+
"remix.config.js",
|
|
772
|
+
"remix.config.mjs",
|
|
773
|
+
"remix.config.ts",
|
|
774
|
+
"vite.config.js",
|
|
775
|
+
"vite.config.ts",
|
|
776
|
+
"vite.config.mjs",
|
|
777
|
+
"vite.config.cjs"
|
|
778
|
+
],
|
|
779
|
+
dependency: "@remix-run/dev",
|
|
780
|
+
installCommand: "pnpm add -D @remix-run/dev"
|
|
781
|
+
},
|
|
782
|
+
vite: {
|
|
783
|
+
displayName: "Vite",
|
|
784
|
+
configFiles: [
|
|
785
|
+
"vite.config.js",
|
|
786
|
+
"vite.config.ts",
|
|
787
|
+
"vite.config.mjs",
|
|
788
|
+
"vite.config.cjs"
|
|
789
|
+
],
|
|
790
|
+
dependency: "vite",
|
|
791
|
+
installCommand: "pnpm add -D vite"
|
|
792
|
+
},
|
|
793
|
+
"tanstack-start": {
|
|
794
|
+
displayName: "TanStack Start",
|
|
795
|
+
configFiles: [
|
|
796
|
+
"vite.config.js",
|
|
797
|
+
"vite.config.ts",
|
|
798
|
+
"vite.config.mjs",
|
|
799
|
+
"vite.config.cjs"
|
|
800
|
+
],
|
|
801
|
+
dependency: "@tanstack/react-start",
|
|
802
|
+
installCommand: "pnpm add @tanstack/react-start @tanstack/react-router"
|
|
803
|
+
},
|
|
804
|
+
expo: {
|
|
805
|
+
displayName: "Expo",
|
|
806
|
+
configFiles: [
|
|
807
|
+
"app.config.ts",
|
|
808
|
+
"app.config.js",
|
|
809
|
+
"app.json"
|
|
810
|
+
],
|
|
811
|
+
dependency: "expo",
|
|
812
|
+
installCommand: "pnpm add expo"
|
|
1027
813
|
}
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
814
|
+
};
|
|
815
|
+
/** Whether a configured framework is one this table knows how to start. */
|
|
816
|
+
function isClientFramework(framework) {
|
|
817
|
+
return framework !== void 0 && framework in FRONTEND_FRAMEWORKS;
|
|
818
|
+
}
|
|
819
|
+
/**
|
|
820
|
+
* Auto-detect the frontend framework by scanning package.json deps and config
|
|
821
|
+
* files. Dependency match wins over config file match because deps are more
|
|
822
|
+
* distinctive (a Remix app has both vite.config.ts AND @remix-run/dev).
|
|
823
|
+
*/
|
|
824
|
+
function detectFrontendFramework(fullPath, deps) {
|
|
825
|
+
const order = [
|
|
826
|
+
"expo",
|
|
827
|
+
"tanstack-start",
|
|
828
|
+
"nextjs",
|
|
829
|
+
"remix",
|
|
830
|
+
"vite"
|
|
831
|
+
];
|
|
832
|
+
for (const name of order) if (deps[FRONTEND_FRAMEWORKS[name].dependency]) return name;
|
|
833
|
+
for (const name of order) if (FRONTEND_FRAMEWORKS[name].configFiles.some((file) => existsSync(join(fullPath, file)))) return name;
|
|
834
|
+
}
|
|
835
|
+
/**
|
|
836
|
+
* Validate a frontend app configuration.
|
|
837
|
+
*
|
|
838
|
+
* If `framework` is provided, validates strictly against that framework's
|
|
839
|
+
* expected config file and dependency. Otherwise auto-detects the framework
|
|
840
|
+
* from package.json and config files. If no recognized framework is found, the
|
|
841
|
+
* app is allowed through with a warning provided it has a `dev` script.
|
|
842
|
+
*
|
|
843
|
+
* @internal Exported for testing
|
|
844
|
+
*/
|
|
845
|
+
async function validateFrontendApp(appName, appPath, workspaceRoot, framework) {
|
|
846
|
+
const errors = [];
|
|
847
|
+
const warnings = [];
|
|
848
|
+
const fullPath = join(workspaceRoot, appPath);
|
|
849
|
+
const packageJsonPath = join(fullPath, "package.json");
|
|
850
|
+
if (!existsSync(packageJsonPath)) {
|
|
851
|
+
errors.push(`package.json not found at ${appPath}. Run: pnpm init in the app directory.`);
|
|
852
|
+
return {
|
|
853
|
+
appName,
|
|
854
|
+
valid: false,
|
|
855
|
+
errors,
|
|
856
|
+
warnings
|
|
857
|
+
};
|
|
1044
858
|
}
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
*
|
|
1057
|
-
* ⚠️ WARNING: This is for LOCAL DEVELOPMENT ONLY
|
|
1058
|
-
* This uses event polling which is not suitable for production.
|
|
1059
|
-
*
|
|
1060
|
-
* For production, use AWS Lambda with SQS/SNS event source mappings.
|
|
1061
|
-
* Lambda automatically:
|
|
1062
|
-
* - Scales based on queue depth
|
|
1063
|
-
* - Handles batch processing and retries
|
|
1064
|
-
* - Manages dead letter queues
|
|
1065
|
-
* - Provides better cost optimization
|
|
1066
|
-
*
|
|
1067
|
-
* This polling implementation is useful for:
|
|
1068
|
-
* - Local development and testing
|
|
1069
|
-
* - Understanding event flow without Lambda deployment
|
|
1070
|
-
*
|
|
1071
|
-
* Supported connection strings:
|
|
1072
|
-
* - sqs://region/account-id/queue-name (SQS queue)
|
|
1073
|
-
* - sns://region/account-id/topic-name (SNS topic)
|
|
1074
|
-
* - rabbitmq://host:port/queue-name (RabbitMQ)
|
|
1075
|
-
* - pgboss://user:pass@host:port/database (pg-boss / PostgreSQL)
|
|
1076
|
-
* - basic://in-memory (In-memory for testing)
|
|
1077
|
-
*/
|
|
1078
|
-
import type { EnvironmentParser } from '@geekmidas/envkit';
|
|
1079
|
-
import type { Logger } from '@geekmidas/logger';
|
|
1080
|
-
import { EventConnectionFactory, Subscriber } from '@geekmidas/events';
|
|
1081
|
-
import type { EventConnection, EventSubscriber } from '@geekmidas/events';
|
|
1082
|
-
import { ServiceDiscovery } from '@geekmidas/services';
|
|
1083
|
-
${Array.from(importsByFile.entries()).map(([importPath, exports]) => `import { ${exports.join(", ")} } from '${importPath}';`).join("\n")}
|
|
1084
|
-
|
|
1085
|
-
const subscribers = [
|
|
1086
|
-
${subscribers.map(({ key }) => key).join(",\n ")}
|
|
1087
|
-
];
|
|
1088
|
-
|
|
1089
|
-
const activeSubscribers: EventSubscriber<any>[] = [];
|
|
1090
|
-
|
|
1091
|
-
export async function setupSubscribers(
|
|
1092
|
-
envParser: EnvironmentParser<any>,
|
|
1093
|
-
logger: Logger,
|
|
1094
|
-
): Promise<void> {
|
|
1095
|
-
if (subscribers.length === 0) {
|
|
1096
|
-
return;
|
|
1097
|
-
}
|
|
1098
|
-
|
|
1099
|
-
logger.info('Setting up subscribers in polling mode (local development)');
|
|
1100
|
-
|
|
1101
|
-
const config = envParser.create((get) => ({
|
|
1102
|
-
connectionString: get('EVENT_SUBSCRIBER_CONNECTION_STRING').string(),
|
|
1103
|
-
})).parse();
|
|
1104
|
-
|
|
1105
|
-
const serviceDiscovery = ServiceDiscovery.getInstance(envParser);
|
|
1106
|
-
|
|
1107
|
-
// Create connection once, outside the loop (more efficient)
|
|
1108
|
-
// EventConnectionFactory automatically determines the right connection type
|
|
1109
|
-
let connection: EventConnection;
|
|
1110
|
-
try {
|
|
1111
|
-
connection = await EventConnectionFactory.fromConnectionString(config.connectionString);
|
|
1112
|
-
|
|
1113
|
-
const connectionType = new URL(config.connectionString).protocol.replace(':', '');
|
|
1114
|
-
logger.info({ connectionType }, 'Created shared event connection');
|
|
1115
|
-
} catch (error) {
|
|
1116
|
-
logger.error({ error }, 'Failed to create event connection');
|
|
1117
|
-
return;
|
|
1118
|
-
}
|
|
1119
|
-
|
|
1120
|
-
for (const subscriber of subscribers) {
|
|
1121
|
-
try {
|
|
1122
|
-
// Create subscriber from shared connection
|
|
1123
|
-
const eventSubscriber = await Subscriber.fromConnection(connection);
|
|
1124
|
-
|
|
1125
|
-
// Register services
|
|
1126
|
-
const services = subscriber.services.length > 0
|
|
1127
|
-
? await serviceDiscovery.register(subscriber.services)
|
|
1128
|
-
: {};
|
|
1129
|
-
|
|
1130
|
-
// Subscribe to events
|
|
1131
|
-
const subscribedEvents = subscriber.subscribedEvents || [];
|
|
1132
|
-
|
|
1133
|
-
if (subscribedEvents.length === 0) {
|
|
1134
|
-
logger.warn({ subscriber: subscriber.constructor.name }, 'Subscriber has no subscribed events, skipping');
|
|
1135
|
-
continue;
|
|
1136
|
-
}
|
|
1137
|
-
|
|
1138
|
-
await eventSubscriber.subscribe(subscribedEvents, async (event) => {
|
|
1139
|
-
try {
|
|
1140
|
-
// Process single event (batch of 1)
|
|
1141
|
-
await subscriber.handler({
|
|
1142
|
-
events: [event],
|
|
1143
|
-
services: services as any,
|
|
1144
|
-
logger: subscriber.logger,
|
|
1145
|
-
});
|
|
1146
|
-
|
|
1147
|
-
logger.debug({ eventType: event.type }, 'Successfully processed event');
|
|
1148
|
-
} catch (error) {
|
|
1149
|
-
logger.error({ error, event }, 'Failed to process event');
|
|
1150
|
-
// Event will become visible again for retry
|
|
1151
|
-
}
|
|
1152
|
-
});
|
|
1153
|
-
|
|
1154
|
-
activeSubscribers.push(eventSubscriber);
|
|
1155
|
-
|
|
1156
|
-
logger.info(
|
|
1157
|
-
{
|
|
1158
|
-
events: subscribedEvents,
|
|
1159
|
-
},
|
|
1160
|
-
'Subscriber started polling'
|
|
1161
|
-
);
|
|
1162
|
-
} catch (error) {
|
|
1163
|
-
logger.error({ error, subscriber: subscriber.constructor.name }, 'Failed to setup subscriber');
|
|
1164
|
-
}
|
|
1165
|
-
}
|
|
1166
|
-
|
|
1167
|
-
// Setup graceful shutdown
|
|
1168
|
-
const shutdown = () => {
|
|
1169
|
-
logger.info('Stopping all subscribers');
|
|
1170
|
-
for (const eventSubscriber of activeSubscribers) {
|
|
1171
|
-
connection.stop();
|
|
1172
|
-
}
|
|
1173
|
-
};
|
|
1174
|
-
|
|
1175
|
-
process.on('SIGTERM', shutdown);
|
|
1176
|
-
process.on('SIGINT', shutdown);
|
|
1177
|
-
}
|
|
1178
|
-
`;
|
|
1179
|
-
await writeFile(subscribersPath, content);
|
|
1180
|
-
return subscribersPath;
|
|
859
|
+
let pkg;
|
|
860
|
+
try {
|
|
861
|
+
pkg = __require(packageJsonPath);
|
|
862
|
+
} catch {
|
|
863
|
+
errors.push(`Failed to read package.json at ${packageJsonPath}`);
|
|
864
|
+
return {
|
|
865
|
+
appName,
|
|
866
|
+
valid: false,
|
|
867
|
+
errors,
|
|
868
|
+
warnings
|
|
869
|
+
};
|
|
1181
870
|
}
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
|
|
871
|
+
const deps = {
|
|
872
|
+
...pkg.dependencies,
|
|
873
|
+
...pkg.devDependencies
|
|
874
|
+
};
|
|
875
|
+
const resolvedFramework = framework ?? detectFrontendFramework(fullPath, deps);
|
|
876
|
+
if (resolvedFramework) {
|
|
877
|
+
const spec = FRONTEND_FRAMEWORKS[resolvedFramework];
|
|
878
|
+
if (!spec.configFiles.some((file) => existsSync(join(fullPath, file)))) errors.push(`${spec.displayName} config file not found. Expected one of: ${spec.configFiles.join(", ")}`);
|
|
879
|
+
if (!deps[spec.dependency]) errors.push(`${spec.displayName} not found in dependencies. Run: ${spec.installCommand}`);
|
|
880
|
+
} else warnings.push("No recognized frontend framework detected (Next.js, Vite, Remix). The app will run via its \"dev\" script. Set `framework` in your app config to enable strict validation.");
|
|
881
|
+
if (!pkg.scripts?.dev) {
|
|
882
|
+
if (resolvedFramework) warnings.push("No \"dev\" script found in package.json. Turbo expects a \"dev\" script to run.");
|
|
883
|
+
else errors.push("No \"dev\" script found in package.json. Without a recognized framework or a dev script, there is nothing to run.");
|
|
884
|
+
}
|
|
885
|
+
return {
|
|
886
|
+
appName,
|
|
887
|
+
valid: errors.length === 0,
|
|
888
|
+
errors,
|
|
889
|
+
warnings
|
|
890
|
+
};
|
|
891
|
+
}
|
|
1185
892
|
/**
|
|
1186
|
-
*
|
|
1187
|
-
*
|
|
1188
|
-
*
|
|
1189
|
-
* producing construct) and subscribers bind via `s.topic(topic)`; this generator
|
|
1190
|
-
* only records the topic + its event contract so infra can provision the SNS
|
|
1191
|
-
* topic. Identical output for every provider (locally pg-boss routes by event
|
|
1192
|
-
* name, so there's nothing to run).
|
|
893
|
+
* Validate all frontend apps in the workspace.
|
|
894
|
+
* Returns validation results for each frontend app.
|
|
895
|
+
* @internal Exported for testing
|
|
1193
896
|
*/
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
const logger = console;
|
|
1200
|
-
const topicInfos = constructs.map(({ construct }) => ({
|
|
1201
|
-
name: construct.name,
|
|
1202
|
-
events: construct.eventTypes
|
|
1203
|
-
}));
|
|
1204
|
-
for (const topic of topicInfos) logger.log(`Discovered topic: ${topic.name}`);
|
|
1205
|
-
return topicInfos;
|
|
897
|
+
async function validateFrontendApps(workspace) {
|
|
898
|
+
const results = [];
|
|
899
|
+
for (const [appName, app] of Object.entries(workspace.apps)) if (app.type === "web") {
|
|
900
|
+
const result = await validateFrontendApp(appName, app.path, workspace.root, isClientFramework(app.framework) ? app.framework : void 0);
|
|
901
|
+
results.push(result);
|
|
1206
902
|
}
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
//#region src/workspace/client-generator.ts
|
|
903
|
+
return results;
|
|
904
|
+
}
|
|
1210
905
|
/**
|
|
1211
|
-
*
|
|
1212
|
-
*
|
|
1213
|
-
* @internal Exported for
|
|
906
|
+
* Load secrets for development stage.
|
|
907
|
+
* Returns env vars to inject, or empty object if secrets not configured/found.
|
|
908
|
+
* @internal Exported for testing
|
|
1214
909
|
*/
|
|
1215
|
-
function
|
|
1216
|
-
if (!
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
var NoCommandSpecified = class extends Error {
|
|
1225
|
-
constructor() {
|
|
1226
|
-
super("No command specified. Usage: gkm exec -- <command>");
|
|
1227
|
-
this.name = "NoCommandSpecified";
|
|
910
|
+
async function loadDevSecrets(workspace) {
|
|
911
|
+
if (!workspace.secrets.enabled) return {};
|
|
912
|
+
const stage = workspace.stages.local;
|
|
913
|
+
if (secretsExist(stage, workspace.root)) {
|
|
914
|
+
const secrets = await readStageSecrets(stage, workspace.root);
|
|
915
|
+
if (secrets) {
|
|
916
|
+
logger$11.log(`🔐 Loading secrets from stage: ${stage}`);
|
|
917
|
+
return toEmbeddableSecrets(secrets);
|
|
918
|
+
}
|
|
1228
919
|
}
|
|
1229
|
-
};
|
|
920
|
+
logger$11.warn(`⚠️ Secrets enabled but no "${stage}" secrets found. Run "gkm setup" to initialize the local stage`);
|
|
921
|
+
return {};
|
|
922
|
+
}
|
|
1230
923
|
/**
|
|
1231
|
-
*
|
|
1232
|
-
* Uses Node's --import flag to preload a script that populates Credentials
|
|
1233
|
-
* before the command loads any modules that depend on them.
|
|
924
|
+
* Workspace dev command - orchestrates multi-app development using Turbo.
|
|
1234
925
|
*
|
|
1235
|
-
*
|
|
1236
|
-
*
|
|
1237
|
-
*
|
|
1238
|
-
*
|
|
1239
|
-
*
|
|
926
|
+
* Flow:
|
|
927
|
+
* 1. Check for port conflicts
|
|
928
|
+
* 2. Start docker-compose services (db, cache, mail)
|
|
929
|
+
* 3. Generate dependency URLs ({APP_NAME}_URL)
|
|
930
|
+
* 4. Spawn turbo run dev with injected env vars
|
|
1240
931
|
*/
|
|
1241
|
-
async function
|
|
1242
|
-
const
|
|
1243
|
-
|
|
1244
|
-
const
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
});
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
|
|
932
|
+
async function workspaceDevCommand(workspace, options) {
|
|
933
|
+
const appCount = Object.keys(workspace.apps).length;
|
|
934
|
+
const backendApps = Object.entries(workspace.apps).filter(([_, app]) => app.type === "backend");
|
|
935
|
+
const frontendApps = Object.entries(workspace.apps).filter(([_, app]) => app.type === "web");
|
|
936
|
+
const mobileApps = Object.entries(workspace.apps).filter(([_, app]) => app.type === "mobile");
|
|
937
|
+
logger$11.log(`\n🚀 Starting workspace: ${workspace.name}`);
|
|
938
|
+
const counts = [`${backendApps.length} backend`, `${frontendApps.length} web`];
|
|
939
|
+
if (mobileApps.length > 0) counts.push(`${mobileApps.length} mobile`);
|
|
940
|
+
logger$11.log(` ${counts.join(", ")} app(s)`);
|
|
941
|
+
const conflicts = checkPortConflicts(workspace);
|
|
942
|
+
if (conflicts.length > 0) {
|
|
943
|
+
for (const conflict of conflicts) logger$11.error(`❌ Port conflict: Apps "${conflict.app1}" and "${conflict.app2}" both use port ${conflict.port}`);
|
|
944
|
+
throw new Error("Port conflicts detected. Please assign unique ports to each app.");
|
|
945
|
+
}
|
|
946
|
+
if (frontendApps.length > 0) {
|
|
947
|
+
logger$11.log("\n🔍 Validating frontend apps...");
|
|
948
|
+
const validationResults = await validateFrontendApps(workspace);
|
|
949
|
+
let hasErrors = false;
|
|
950
|
+
for (const result of validationResults) {
|
|
951
|
+
if (!result.valid) {
|
|
952
|
+
hasErrors = true;
|
|
953
|
+
logger$11.error(`\n❌ Frontend app "${result.appName}" validation failed:`);
|
|
954
|
+
for (const error of result.errors) logger$11.error(` • ${error}`);
|
|
955
|
+
}
|
|
956
|
+
for (const warning of result.warnings) logger$11.warn(` ⚠️ ${result.appName}: ${warning}`);
|
|
957
|
+
}
|
|
958
|
+
if (hasErrors) throw new Error("Frontend app validation failed. Fix the issues above and try again.");
|
|
959
|
+
logger$11.log("✅ Frontend apps validated");
|
|
960
|
+
}
|
|
961
|
+
const rawSecrets = await loadDevSecrets(workspace);
|
|
962
|
+
let secretsEnv;
|
|
963
|
+
if (usesConstructs(workspace)) {
|
|
964
|
+
const reconciled = await reconcileWorkspace(workspace, { stage: workspace.stages.local });
|
|
965
|
+
if (reconciled.changed && reconciled.plan.containers.length > 0) {
|
|
966
|
+
logger$11.log(`🐳 Services: ${reconciled.plan.containers.join(", ")}`);
|
|
967
|
+
for (const [container, address] of Object.entries(reconciled.addresses)) logger$11.log(` ${container}: ${address}`);
|
|
968
|
+
}
|
|
969
|
+
secretsEnv = {
|
|
970
|
+
...rawSecrets,
|
|
971
|
+
...reconciled.env
|
|
972
|
+
};
|
|
973
|
+
} else {
|
|
974
|
+
const resolvedPorts = await resolveServicePorts(workspace.root);
|
|
975
|
+
await startWorkspaceServices(workspace, resolvedPorts.dockerEnv, rawSecrets);
|
|
976
|
+
secretsEnv = rewriteUrlsWithPorts(rawSecrets, resolvedPorts);
|
|
977
|
+
}
|
|
978
|
+
if (Object.keys(secretsEnv).length > 0) logger$11.log(` Loaded ${Object.keys(secretsEnv).length} secret(s)`);
|
|
979
|
+
const dependencyEnv = generateAllDependencyEnvVars(workspace);
|
|
980
|
+
if (Object.keys(dependencyEnv).length > 0) {
|
|
981
|
+
logger$11.log("📡 Dependency URLs:");
|
|
982
|
+
for (const [key, value] of Object.entries(dependencyEnv)) logger$11.log(` ${key}=${value}`);
|
|
983
|
+
}
|
|
984
|
+
let turboFilter = [];
|
|
985
|
+
if (options.app) {
|
|
986
|
+
if (!workspace.apps[options.app]) {
|
|
987
|
+
const appNames = Object.keys(workspace.apps).join(", ");
|
|
988
|
+
throw new Error(`App "${options.app}" not found. Available apps: ${appNames}`);
|
|
989
|
+
}
|
|
990
|
+
turboFilter = ["--filter", appPackageName(workspace, options.app) ?? options.app];
|
|
991
|
+
logger$11.log(`\n🎯 Running single app: ${options.app}`);
|
|
992
|
+
} else if (options.filter) {
|
|
993
|
+
turboFilter = ["--filter", options.filter];
|
|
994
|
+
logger$11.log(`\n🔍 Using filter: ${options.filter}`);
|
|
995
|
+
} else {
|
|
996
|
+
const { filters, unpackaged } = turboFilters(workspace);
|
|
997
|
+
turboFilter = filters.flatMap((name) => ["--filter", name]);
|
|
998
|
+
if (unpackaged.length > 0) logger$11.warn(`⚠️ No package.json with a name for: ${unpackaged.join(", ")} — turbo cannot run ${unpackaged.length === 1 ? "it" : "them"}.`);
|
|
999
|
+
logger$11.log(`\n🎯 Running all ${appCount} apps`);
|
|
1000
|
+
}
|
|
1001
|
+
const buildOrder = getAppBuildOrder(workspace);
|
|
1002
|
+
logger$11.log("\n📋 Apps (in dependency order):");
|
|
1003
|
+
for (const appName of buildOrder) {
|
|
1004
|
+
const app = workspace.apps[appName];
|
|
1005
|
+
if (!app) continue;
|
|
1006
|
+
const deps = app.dependencies.length > 0 ? ` (depends on: ${app.dependencies.join(", ")})` : "";
|
|
1007
|
+
const icon = app.type === "backend" ? "🔧" : app.type === "mobile" ? "📱" : "🌐";
|
|
1008
|
+
logger$11.log(` ${icon} ${appName} → http://localhost:${app.port}${deps}`);
|
|
1009
|
+
}
|
|
1010
|
+
const configFiles = [
|
|
1011
|
+
"gkm.config.ts",
|
|
1012
|
+
"gkm.config.js",
|
|
1013
|
+
"gkm.config.json"
|
|
1014
|
+
];
|
|
1015
|
+
let configPath = "";
|
|
1016
|
+
for (const file of configFiles) {
|
|
1017
|
+
const fullPath = join(workspace.root, file);
|
|
1018
|
+
if (existsSync(fullPath)) {
|
|
1019
|
+
configPath = fullPath;
|
|
1020
|
+
break;
|
|
1267
1021
|
}
|
|
1022
|
+
}
|
|
1023
|
+
const turboEnv = {
|
|
1024
|
+
...process.env,
|
|
1025
|
+
...secretsEnv,
|
|
1026
|
+
...dependencyEnv,
|
|
1027
|
+
NODE_ENV: "development",
|
|
1028
|
+
...configPath ? { GKM_CONFIG_PATH: configPath } : {}
|
|
1029
|
+
};
|
|
1030
|
+
logger$11.log("\n🏃 Starting turbo run dev...\n");
|
|
1031
|
+
const turboProcess = spawn("pnpm", [
|
|
1032
|
+
"turbo",
|
|
1033
|
+
"run",
|
|
1034
|
+
"dev",
|
|
1035
|
+
...turboFilter
|
|
1036
|
+
], {
|
|
1037
|
+
cwd: workspace.root,
|
|
1038
|
+
stdio: "inherit",
|
|
1039
|
+
env: turboEnv,
|
|
1040
|
+
detached: true
|
|
1268
1041
|
});
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
|
|
1273
|
-
|
|
1042
|
+
let isShuttingDown = false;
|
|
1043
|
+
const shutdown = () => {
|
|
1044
|
+
if (isShuttingDown) return;
|
|
1045
|
+
isShuttingDown = true;
|
|
1046
|
+
logger$11.log("\n🛑 Shutting down workspace...");
|
|
1047
|
+
const pid = turboProcess.pid;
|
|
1048
|
+
if (pid) try {
|
|
1049
|
+
process.kill(-pid, "SIGTERM");
|
|
1050
|
+
} catch {
|
|
1051
|
+
try {
|
|
1052
|
+
process.kill(pid, "SIGTERM");
|
|
1053
|
+
} catch {}
|
|
1054
|
+
}
|
|
1055
|
+
setTimeout(() => {
|
|
1056
|
+
if (pid) try {
|
|
1057
|
+
process.kill(-pid, "SIGKILL");
|
|
1058
|
+
} catch {
|
|
1059
|
+
try {
|
|
1060
|
+
process.kill(pid, "SIGKILL");
|
|
1061
|
+
} catch {}
|
|
1062
|
+
}
|
|
1063
|
+
process.exit(0);
|
|
1064
|
+
}, 3e3);
|
|
1065
|
+
};
|
|
1066
|
+
process.on("SIGINT", shutdown);
|
|
1067
|
+
process.on("SIGTERM", shutdown);
|
|
1068
|
+
return new Promise((resolve, reject) => {
|
|
1069
|
+
turboProcess.on("error", (error) => {
|
|
1070
|
+
logger$11.error("❌ Turbo error:", error);
|
|
1071
|
+
reject(error);
|
|
1072
|
+
});
|
|
1073
|
+
turboProcess.on("exit", (code) => {
|
|
1074
|
+
if (code !== null && code !== 0) reject(/* @__PURE__ */ new Error(`Turbo exited with code ${code}`));
|
|
1075
|
+
else resolve();
|
|
1274
1076
|
});
|
|
1275
1077
|
});
|
|
1276
|
-
if (exitCode !== 0) process.exit(exitCode);
|
|
1277
1078
|
}
|
|
1278
|
-
//#endregion
|
|
1279
|
-
//#region src/dev/index.ts
|
|
1280
|
-
const logger$11 = console;
|
|
1281
1079
|
/**
|
|
1282
|
-
*
|
|
1283
|
-
*
|
|
1080
|
+
* Run any TypeScript file with secret injection.
|
|
1081
|
+
* Does not require gkm.config.ts.
|
|
1284
1082
|
*/
|
|
1285
|
-
function
|
|
1286
|
-
|
|
1287
|
-
if (
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
|
|
1083
|
+
async function entryDevCommand(options) {
|
|
1084
|
+
const { entry, watch = true } = options;
|
|
1085
|
+
if (!entry) throw new Error("--entry requires a file path");
|
|
1086
|
+
const entryPath = resolve(process.cwd(), entry);
|
|
1087
|
+
if (!existsSync(entryPath)) throw new Error(`Entry file not found: ${entryPath}`);
|
|
1088
|
+
const defaultEnv = loadEnvFiles(".env");
|
|
1089
|
+
if (defaultEnv.loaded.length > 0) logger$11.log(`📦 Loaded env: ${defaultEnv.loaded.join(", ")}`);
|
|
1090
|
+
const { credentials, resolvedPort, secretsJsonPath, appName } = await prepareEntryCredentials({ explicitPort: options.portExplicit ? options.port : void 0 });
|
|
1091
|
+
if (appName) logger$11.log(`📦 App: ${appName} (port ${resolvedPort})`);
|
|
1092
|
+
logger$11.log(`🚀 Starting entry file: ${entry} on port ${resolvedPort}`);
|
|
1093
|
+
if (Object.keys(credentials).length > 1) logger$11.log(`🔐 Loaded ${Object.keys(credentials).length - 1} secret(s) + PORT`);
|
|
1094
|
+
const wrapperDir = join(process.cwd(), ".gkm");
|
|
1095
|
+
await mkdir(wrapperDir, { recursive: true });
|
|
1096
|
+
const wrapperPath = join(wrapperDir, "entry-wrapper.ts");
|
|
1097
|
+
await createEntryWrapper(wrapperPath, entryPath, secretsJsonPath);
|
|
1098
|
+
const runner = new EntryRunner(wrapperPath, entryPath, watch, resolvedPort);
|
|
1099
|
+
await runner.start();
|
|
1100
|
+
let isShuttingDown = false;
|
|
1101
|
+
const shutdown = () => {
|
|
1102
|
+
if (isShuttingDown) return;
|
|
1103
|
+
isShuttingDown = true;
|
|
1104
|
+
logger$11.log("\n🛑 Shutting down...");
|
|
1105
|
+
runner.stop();
|
|
1106
|
+
process.exit(0);
|
|
1309
1107
|
};
|
|
1108
|
+
process.on("SIGINT", shutdown);
|
|
1109
|
+
process.on("SIGTERM", shutdown);
|
|
1110
|
+
await new Promise(() => {});
|
|
1310
1111
|
}
|
|
1311
1112
|
/**
|
|
1312
|
-
*
|
|
1313
|
-
* @internal Exported for testing
|
|
1113
|
+
* Runs and watches a TypeScript entry file using tsx.
|
|
1314
1114
|
*/
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
|
|
1325
|
-
|
|
1115
|
+
var EntryRunner = class {
|
|
1116
|
+
wrapperPath;
|
|
1117
|
+
entryPath;
|
|
1118
|
+
watch;
|
|
1119
|
+
port;
|
|
1120
|
+
childProcess = null;
|
|
1121
|
+
watcher = null;
|
|
1122
|
+
isRunning = false;
|
|
1123
|
+
constructor(wrapperPath, entryPath, watch, port) {
|
|
1124
|
+
this.wrapperPath = wrapperPath;
|
|
1125
|
+
this.entryPath = entryPath;
|
|
1126
|
+
this.watch = watch;
|
|
1127
|
+
this.port = port;
|
|
1326
1128
|
}
|
|
1327
|
-
|
|
1328
|
-
|
|
1329
|
-
|
|
1330
|
-
|
|
1331
|
-
|
|
1332
|
-
|
|
1333
|
-
|
|
1334
|
-
|
|
1335
|
-
/**
|
|
1336
|
-
* Normalize hooks configuration
|
|
1337
|
-
* @internal Exported for testing
|
|
1338
|
-
*/
|
|
1339
|
-
function normalizeHooksConfig(config, cwd = process.cwd()) {
|
|
1340
|
-
if (!config?.server) return;
|
|
1341
|
-
const serverPath = config.server.endsWith(".ts") ? config.server : `${config.server}.ts`;
|
|
1342
|
-
return { serverHooksPath: resolve(cwd, serverPath) };
|
|
1343
|
-
}
|
|
1344
|
-
/**
|
|
1345
|
-
* Normalize production configuration
|
|
1346
|
-
* @internal Exported for testing
|
|
1347
|
-
*/
|
|
1348
|
-
function normalizeProductionConfig(cliProduction, configProduction) {
|
|
1349
|
-
if (!cliProduction) return;
|
|
1350
|
-
const config = configProduction ?? {};
|
|
1351
|
-
return {
|
|
1352
|
-
enabled: true,
|
|
1353
|
-
bundle: config.bundle ?? true,
|
|
1354
|
-
minify: config.minify ?? true,
|
|
1355
|
-
healthCheck: config.healthCheck ?? "/health",
|
|
1356
|
-
gracefulShutdown: config.gracefulShutdown ?? true,
|
|
1357
|
-
external: config.external ?? [],
|
|
1358
|
-
subscribers: config.subscribers ?? "exclude",
|
|
1359
|
-
openapi: config.openapi ?? false,
|
|
1360
|
-
optimizedHandlers: config.optimizedHandlers ?? true
|
|
1361
|
-
};
|
|
1362
|
-
}
|
|
1363
|
-
/**
|
|
1364
|
-
* Get production config from GkmConfig
|
|
1365
|
-
* @internal
|
|
1366
|
-
*/
|
|
1367
|
-
function getProductionConfigFromGkm(config) {
|
|
1368
|
-
const serverConfig = config.providers?.server;
|
|
1369
|
-
if (typeof serverConfig === "object") return serverConfig.production;
|
|
1370
|
-
}
|
|
1371
|
-
async function devCommand(options) {
|
|
1372
|
-
if (options.entry) return entryDevCommand(options);
|
|
1373
|
-
const defaultEnv = loadEnvFiles(".env");
|
|
1374
|
-
if (defaultEnv.loaded.length > 0) logger$11.log(`📦 Loaded env: ${defaultEnv.loaded.join(", ")}`);
|
|
1375
|
-
const appName = getAppNameFromCwd();
|
|
1376
|
-
let config;
|
|
1377
|
-
let appRoot = process.cwd();
|
|
1378
|
-
let secretsRoot = process.cwd();
|
|
1379
|
-
let workspaceAppName;
|
|
1380
|
-
let workspaceAppPort;
|
|
1381
|
-
let workspace;
|
|
1382
|
-
if (appName) try {
|
|
1383
|
-
const appConfig = await loadAppConfig();
|
|
1384
|
-
config = appConfig.gkmConfig;
|
|
1385
|
-
appRoot = appConfig.appRoot;
|
|
1386
|
-
secretsRoot = appConfig.workspaceRoot;
|
|
1387
|
-
workspaceAppName = appConfig.appName;
|
|
1388
|
-
workspaceAppPort = appConfig.app.port;
|
|
1389
|
-
workspace = appConfig.workspace;
|
|
1390
|
-
logger$11.log(`📦 Running app: ${appConfig.appName} on port ${workspaceAppPort}`);
|
|
1391
|
-
if (appConfig.app.entry) {
|
|
1392
|
-
logger$11.log(`📄 Using entry point: ${appConfig.app.entry}`);
|
|
1393
|
-
return entryDevCommand({
|
|
1394
|
-
...options,
|
|
1395
|
-
entry: appConfig.app.entry,
|
|
1396
|
-
port: workspaceAppPort,
|
|
1397
|
-
portExplicit: true
|
|
1129
|
+
async start() {
|
|
1130
|
+
await this.runProcess();
|
|
1131
|
+
if (this.watch) {
|
|
1132
|
+
const watchDir = dirname(this.entryPath);
|
|
1133
|
+
this.watcher = chokidar.watch(watchDir, {
|
|
1134
|
+
ignored: /(^|[/\\])\../,
|
|
1135
|
+
persistent: true,
|
|
1136
|
+
ignoreInitial: true
|
|
1398
1137
|
});
|
|
1138
|
+
let restartTimeout = null;
|
|
1139
|
+
this.watcher.on("change", (path) => {
|
|
1140
|
+
logger$11.log(`📝 File changed: ${path}`);
|
|
1141
|
+
if (restartTimeout) clearTimeout(restartTimeout);
|
|
1142
|
+
restartTimeout = setTimeout(async () => {
|
|
1143
|
+
logger$11.log("🔄 Restarting...");
|
|
1144
|
+
await this.restart();
|
|
1145
|
+
}, 300);
|
|
1146
|
+
});
|
|
1147
|
+
logger$11.log(`👀 Watching for changes in: ${watchDir}`);
|
|
1399
1148
|
}
|
|
1400
|
-
} catch {
|
|
1401
|
-
const loadedConfig = await loadWorkspaceConfig();
|
|
1402
|
-
if (loadedConfig.type === "workspace") {
|
|
1403
|
-
logger$11.log("📦 Detected workspace configuration");
|
|
1404
|
-
return workspaceDevCommand(loadedConfig.workspace, options);
|
|
1405
|
-
}
|
|
1406
|
-
config = loadedConfig.raw;
|
|
1407
|
-
}
|
|
1408
|
-
else {
|
|
1409
|
-
const loadedConfig = await loadWorkspaceConfig();
|
|
1410
|
-
if (loadedConfig.type === "workspace") {
|
|
1411
|
-
logger$11.log("📦 Detected workspace configuration");
|
|
1412
|
-
return workspaceDevCommand(loadedConfig.workspace, options);
|
|
1413
|
-
}
|
|
1414
|
-
config = loadedConfig.raw;
|
|
1415
|
-
workspace = loadedConfig.workspace;
|
|
1416
|
-
}
|
|
1417
|
-
if (config.env) {
|
|
1418
|
-
const { loaded, missing } = loadEnvFiles(config.env, appRoot);
|
|
1419
|
-
if (loaded.length > 0) logger$11.log(`📦 Loaded env: ${loaded.join(", ")}`);
|
|
1420
|
-
if (missing.length > 0) logger$11.warn(`⚠️ Missing env files: ${missing.join(", ")}`);
|
|
1421
1149
|
}
|
|
1422
|
-
|
|
1423
|
-
|
|
1424
|
-
|
|
1425
|
-
|
|
1426
|
-
|
|
1427
|
-
|
|
1428
|
-
|
|
1429
|
-
|
|
1430
|
-
|
|
1431
|
-
|
|
1432
|
-
|
|
1433
|
-
|
|
1434
|
-
|
|
1435
|
-
|
|
1436
|
-
|
|
1437
|
-
|
|
1438
|
-
|
|
1439
|
-
|
|
1440
|
-
|
|
1441
|
-
|
|
1442
|
-
|
|
1443
|
-
|
|
1444
|
-
|
|
1445
|
-
const reconciled = await reconcileWorkspace(workspace, { stage: workspace.stages.local });
|
|
1446
|
-
if (reconciled.changed && reconciled.plan.containers.length > 0) {
|
|
1447
|
-
logger$11.log(`🐳 Services: ${reconciled.plan.containers.join(", ")}`);
|
|
1448
|
-
for (const [container, address] of Object.entries(reconciled.addresses)) logger$11.log(` ${container}: ${address}`);
|
|
1449
|
-
}
|
|
1450
|
-
Object.assign(appSecrets, reconciled.env);
|
|
1451
|
-
} else {
|
|
1452
|
-
const resolvedPorts = await resolveServicePorts(secretsRoot);
|
|
1453
|
-
if (Object.keys(resolvedPorts.ports).length > 0) {
|
|
1454
|
-
const rewritten = rewriteUrlsWithPorts(appSecrets, resolvedPorts);
|
|
1455
|
-
Object.assign(appSecrets, rewritten);
|
|
1456
|
-
logger$11.log(`🔌 Applied ${Object.keys(resolvedPorts.ports).length} port mapping(s)`);
|
|
1150
|
+
async runProcess() {
|
|
1151
|
+
const env = {
|
|
1152
|
+
...process.env,
|
|
1153
|
+
PORT: String(this.port)
|
|
1154
|
+
};
|
|
1155
|
+
this.childProcess = spawn("npx", ["tsx", this.wrapperPath], {
|
|
1156
|
+
stdio: "inherit",
|
|
1157
|
+
env,
|
|
1158
|
+
detached: true
|
|
1159
|
+
});
|
|
1160
|
+
this.isRunning = true;
|
|
1161
|
+
this.childProcess.on("error", (error) => {
|
|
1162
|
+
logger$11.error("❌ Process error:", error);
|
|
1163
|
+
});
|
|
1164
|
+
this.childProcess.on("exit", (code) => {
|
|
1165
|
+
if (code !== null && code !== 0 && code !== 143) logger$11.error(`❌ Process exited with code ${code}`);
|
|
1166
|
+
this.isRunning = false;
|
|
1167
|
+
});
|
|
1168
|
+
await new Promise((resolve) => setTimeout(resolve, 500));
|
|
1169
|
+
if (this.isRunning) {
|
|
1170
|
+
logger$11.log("");
|
|
1171
|
+
logger$11.log(` \x1b[32m✓ Ready\x1b[0m at \x1b[36mhttp://localhost:${this.port}\x1b[0m`);
|
|
1172
|
+
logger$11.log("");
|
|
1457
1173
|
}
|
|
1458
1174
|
}
|
|
1459
|
-
|
|
1460
|
-
|
|
1461
|
-
|
|
1175
|
+
async restart() {
|
|
1176
|
+
this.stopProcess();
|
|
1177
|
+
await new Promise((resolve) => setTimeout(resolve, 500));
|
|
1178
|
+
await this.runProcess();
|
|
1462
1179
|
}
|
|
1463
|
-
|
|
1464
|
-
|
|
1465
|
-
|
|
1466
|
-
const secretsFileName = workspaceAppName ? `dev-secrets-${workspaceAppName}.json` : "dev-secrets.json";
|
|
1467
|
-
secretsJsonPath = join(secretsDir, secretsFileName);
|
|
1468
|
-
await writeFile(secretsJsonPath, JSON.stringify(appSecrets, null, 2));
|
|
1469
|
-
logger$11.log(`🔐 Loaded ${Object.keys(appSecrets).length} secret(s)`);
|
|
1180
|
+
stop() {
|
|
1181
|
+
this.watcher?.close();
|
|
1182
|
+
this.stopProcess();
|
|
1470
1183
|
}
|
|
1471
|
-
|
|
1472
|
-
|
|
1473
|
-
|
|
1474
|
-
|
|
1475
|
-
|
|
1476
|
-
|
|
1477
|
-
|
|
1478
|
-
|
|
1479
|
-
|
|
1480
|
-
});
|
|
1481
|
-
const dirsToWatch = [...new Set(resolvedFiles.map((f) => {
|
|
1482
|
-
return f.split("/").slice(0, -1).join("/");
|
|
1483
|
-
}))];
|
|
1484
|
-
logger$11.log(`📁 Found ${resolvedFiles.length} files in ${dirsToWatch.length} directories`);
|
|
1485
|
-
const watcher = chokidar.watch([...resolvedFiles, ...dirsToWatch], {
|
|
1486
|
-
ignored: /(^|[/\\])\../,
|
|
1487
|
-
persistent: true,
|
|
1488
|
-
ignoreInitial: true,
|
|
1489
|
-
cwd: appRoot
|
|
1490
|
-
});
|
|
1491
|
-
watcher.on("ready", () => {
|
|
1492
|
-
logger$11.log("🔍 File watcher ready");
|
|
1493
|
-
});
|
|
1494
|
-
watcher.on("error", (error) => {
|
|
1495
|
-
logger$11.error("❌ Watcher error:", error);
|
|
1496
|
-
});
|
|
1497
|
-
let rebuildTimeout = null;
|
|
1498
|
-
watcher.on("change", async (path) => {
|
|
1499
|
-
logger$11.log(`📝 File changed: ${path}`);
|
|
1500
|
-
if (rebuildTimeout) clearTimeout(rebuildTimeout);
|
|
1501
|
-
rebuildTimeout = setTimeout(async () => {
|
|
1502
|
-
try {
|
|
1503
|
-
logger$11.log("🔄 Rebuilding...");
|
|
1504
|
-
await buildServer(config, buildContext, resolved.providers[0], enableOpenApi, appRoot, workspaceRoot, true);
|
|
1505
|
-
if (enableOpenApi) await generateOpenApiFrom(config.constructs, {
|
|
1506
|
-
openapi: config.openapi,
|
|
1507
|
-
silent: true,
|
|
1508
|
-
bustCache: true
|
|
1509
|
-
});
|
|
1510
|
-
logger$11.log("✅ Rebuild complete, restarting server...");
|
|
1511
|
-
await devServer.restart();
|
|
1512
|
-
} catch (error) {
|
|
1513
|
-
const err = error;
|
|
1514
|
-
logger$11.error(`❌ Rebuild failed: ${err.message}`);
|
|
1515
|
-
if (err.stack) logger$11.error(err.stack);
|
|
1184
|
+
stopProcess() {
|
|
1185
|
+
if (this.childProcess && this.isRunning) {
|
|
1186
|
+
const pid = this.childProcess.pid;
|
|
1187
|
+
if (pid) try {
|
|
1188
|
+
process.kill(-pid, "SIGTERM");
|
|
1189
|
+
} catch {
|
|
1190
|
+
try {
|
|
1191
|
+
process.kill(pid, "SIGTERM");
|
|
1192
|
+
} catch {}
|
|
1516
1193
|
}
|
|
1517
|
-
|
|
1518
|
-
|
|
1519
|
-
|
|
1520
|
-
const shutdown = () => {
|
|
1521
|
-
if (isShuttingDown) return;
|
|
1522
|
-
isShuttingDown = true;
|
|
1523
|
-
logger$11.log("\n🛑 Shutting down...");
|
|
1524
|
-
Promise.all([watcher.close(), devServer.stop()]).catch((err) => {
|
|
1525
|
-
logger$11.error("Error during shutdown:", err);
|
|
1526
|
-
}).finally(() => {
|
|
1527
|
-
process.exit(0);
|
|
1528
|
-
});
|
|
1529
|
-
};
|
|
1530
|
-
process.on("SIGINT", shutdown);
|
|
1531
|
-
process.on("SIGTERM", shutdown);
|
|
1532
|
-
}
|
|
1533
|
-
/**
|
|
1534
|
-
* Generate all dependency environment variables for all apps.
|
|
1535
|
-
* Returns a flat object with all {APP_NAME}_URL variables.
|
|
1536
|
-
* @internal Exported for testing
|
|
1537
|
-
*/
|
|
1538
|
-
function generateAllDependencyEnvVars(workspace, urlPrefix = "http://localhost") {
|
|
1539
|
-
const env = {};
|
|
1540
|
-
for (const appName of Object.keys(workspace.apps)) {
|
|
1541
|
-
const appEnv = getDependencyEnvVars(workspace, appName, urlPrefix);
|
|
1542
|
-
Object.assign(env, appEnv);
|
|
1194
|
+
this.childProcess = null;
|
|
1195
|
+
this.isRunning = false;
|
|
1196
|
+
}
|
|
1543
1197
|
}
|
|
1544
|
-
|
|
1545
|
-
}
|
|
1198
|
+
};
|
|
1546
1199
|
/**
|
|
1547
|
-
*
|
|
1548
|
-
*
|
|
1200
|
+
* Generate the content of the dev server entry file (server.ts).
|
|
1201
|
+
* Uses dynamic import for createApp so Credentials are populated
|
|
1202
|
+
* before any app modules evaluate.
|
|
1549
1203
|
* @internal Exported for testing
|
|
1550
1204
|
*/
|
|
1551
|
-
function
|
|
1552
|
-
const
|
|
1553
|
-
const
|
|
1554
|
-
|
|
1555
|
-
|
|
1556
|
-
|
|
1557
|
-
|
|
1558
|
-
|
|
1559
|
-
|
|
1560
|
-
|
|
1561
|
-
else portToApp.set(app.port, appName);
|
|
1562
|
-
}
|
|
1563
|
-
return conflicts;
|
|
1564
|
-
}
|
|
1565
|
-
const FRONTEND_FRAMEWORKS = {
|
|
1566
|
-
nextjs: {
|
|
1567
|
-
displayName: "Next.js",
|
|
1568
|
-
configFiles: [
|
|
1569
|
-
"next.config.js",
|
|
1570
|
-
"next.config.ts",
|
|
1571
|
-
"next.config.mjs",
|
|
1572
|
-
"next.config.cjs"
|
|
1573
|
-
],
|
|
1574
|
-
dependency: "next",
|
|
1575
|
-
installCommand: "pnpm add next react react-dom"
|
|
1576
|
-
},
|
|
1577
|
-
remix: {
|
|
1578
|
-
displayName: "Remix",
|
|
1579
|
-
configFiles: [
|
|
1580
|
-
"remix.config.js",
|
|
1581
|
-
"remix.config.mjs",
|
|
1582
|
-
"remix.config.ts",
|
|
1583
|
-
"vite.config.js",
|
|
1584
|
-
"vite.config.ts",
|
|
1585
|
-
"vite.config.mjs",
|
|
1586
|
-
"vite.config.cjs"
|
|
1587
|
-
],
|
|
1588
|
-
dependency: "@remix-run/dev",
|
|
1589
|
-
installCommand: "pnpm add -D @remix-run/dev"
|
|
1590
|
-
},
|
|
1591
|
-
vite: {
|
|
1592
|
-
displayName: "Vite",
|
|
1593
|
-
configFiles: [
|
|
1594
|
-
"vite.config.js",
|
|
1595
|
-
"vite.config.ts",
|
|
1596
|
-
"vite.config.mjs",
|
|
1597
|
-
"vite.config.cjs"
|
|
1598
|
-
],
|
|
1599
|
-
dependency: "vite",
|
|
1600
|
-
installCommand: "pnpm add -D vite"
|
|
1601
|
-
},
|
|
1602
|
-
"tanstack-start": {
|
|
1603
|
-
displayName: "TanStack Start",
|
|
1604
|
-
configFiles: [
|
|
1605
|
-
"vite.config.js",
|
|
1606
|
-
"vite.config.ts",
|
|
1607
|
-
"vite.config.mjs",
|
|
1608
|
-
"vite.config.cjs"
|
|
1609
|
-
],
|
|
1610
|
-
dependency: "@tanstack/react-start",
|
|
1611
|
-
installCommand: "pnpm add @tanstack/react-start @tanstack/react-router"
|
|
1612
|
-
},
|
|
1613
|
-
expo: {
|
|
1614
|
-
displayName: "Expo",
|
|
1615
|
-
configFiles: [
|
|
1616
|
-
"app.config.ts",
|
|
1617
|
-
"app.config.js",
|
|
1618
|
-
"app.json"
|
|
1619
|
-
],
|
|
1620
|
-
dependency: "expo",
|
|
1621
|
-
installCommand: "pnpm add expo"
|
|
1622
|
-
}
|
|
1623
|
-
};
|
|
1624
|
-
/** Whether a configured framework is one this table knows how to start. */
|
|
1625
|
-
function isClientFramework(framework) {
|
|
1626
|
-
return framework !== void 0 && framework in FRONTEND_FRAMEWORKS;
|
|
1627
|
-
}
|
|
1628
|
-
/**
|
|
1629
|
-
* Auto-detect the frontend framework by scanning package.json deps and config
|
|
1630
|
-
* files. Dependency match wins over config file match because deps are more
|
|
1631
|
-
* distinctive (a Remix app has both vite.config.ts AND @remix-run/dev).
|
|
1632
|
-
*/
|
|
1633
|
-
function detectFrontendFramework(fullPath, deps) {
|
|
1634
|
-
const order = [
|
|
1635
|
-
"expo",
|
|
1636
|
-
"tanstack-start",
|
|
1637
|
-
"nextjs",
|
|
1638
|
-
"remix",
|
|
1639
|
-
"vite"
|
|
1640
|
-
];
|
|
1641
|
-
for (const name of order) if (deps[FRONTEND_FRAMEWORKS[name].dependency]) return name;
|
|
1642
|
-
for (const name of order) if (FRONTEND_FRAMEWORKS[name].configFiles.some((file) => existsSync(join(fullPath, file)))) return name;
|
|
1205
|
+
function generateServerEntryContent(options) {
|
|
1206
|
+
const { secretsJsonPath, runtime = "node", enableOpenApi = false, appImportPath = "./app.js", selfServing = false } = options;
|
|
1207
|
+
const credentialsInjection = secretsJsonPath ? `import { existsSync, readFileSync } from 'node:fs';
|
|
1208
|
+
|
|
1209
|
+
// Inject dev secrets via globalThis (must happen before app import)
|
|
1210
|
+
const secretsPath = '${secretsJsonPath}';
|
|
1211
|
+
if (existsSync(secretsPath)) {
|
|
1212
|
+
const __secrets = JSON.parse(readFileSync(secretsPath, 'utf-8'));
|
|
1213
|
+
globalThis.__gkm_credentials__ = __secrets;
|
|
1214
|
+
Object.assign(process.env, __secrets);
|
|
1643
1215
|
}
|
|
1216
|
+
|
|
1217
|
+
` : "";
|
|
1218
|
+
const serveCode = runtime === "bun" ? `Bun.serve({
|
|
1219
|
+
port,
|
|
1220
|
+
fetch: app.fetch,
|
|
1221
|
+
});` : `const { serve } = await import('@hono/node-server');
|
|
1222
|
+
const server = serve({
|
|
1223
|
+
fetch: app.fetch,
|
|
1224
|
+
port,
|
|
1225
|
+
});
|
|
1226
|
+
// Inject WebSocket support if available
|
|
1227
|
+
const injectWs = (app as any).__injectWebSocket;
|
|
1228
|
+
if (injectWs) {
|
|
1229
|
+
injectWs(server);
|
|
1230
|
+
console.log('🔌 Telescope real-time updates enabled');
|
|
1231
|
+
}`;
|
|
1232
|
+
if (selfServing) return `#!/usr/bin/env node
|
|
1644
1233
|
/**
|
|
1645
|
-
*
|
|
1646
|
-
*
|
|
1647
|
-
|
|
1648
|
-
|
|
1649
|
-
|
|
1650
|
-
|
|
1651
|
-
|
|
1652
|
-
|
|
1653
|
-
|
|
1654
|
-
|
|
1655
|
-
|
|
1656
|
-
|
|
1657
|
-
|
|
1658
|
-
|
|
1659
|
-
|
|
1660
|
-
errors.push(`package.json not found at ${appPath}. Run: pnpm init in the app directory.`);
|
|
1661
|
-
return {
|
|
1662
|
-
appName,
|
|
1663
|
-
valid: false,
|
|
1664
|
-
errors,
|
|
1665
|
-
warnings
|
|
1666
|
-
};
|
|
1667
|
-
}
|
|
1668
|
-
let pkg;
|
|
1669
|
-
try {
|
|
1670
|
-
pkg = __require(packageJsonPath);
|
|
1671
|
-
} catch {
|
|
1672
|
-
errors.push(`Failed to read package.json at ${packageJsonPath}`);
|
|
1673
|
-
return {
|
|
1674
|
-
appName,
|
|
1675
|
-
valid: false,
|
|
1676
|
-
errors,
|
|
1677
|
-
warnings
|
|
1678
|
-
};
|
|
1679
|
-
}
|
|
1680
|
-
const deps = {
|
|
1681
|
-
...pkg.dependencies,
|
|
1682
|
-
...pkg.devDependencies
|
|
1683
|
-
};
|
|
1684
|
-
const resolvedFramework = framework ?? detectFrontendFramework(fullPath, deps);
|
|
1685
|
-
if (resolvedFramework) {
|
|
1686
|
-
const spec = FRONTEND_FRAMEWORKS[resolvedFramework];
|
|
1687
|
-
if (!spec.configFiles.some((file) => existsSync(join(fullPath, file)))) errors.push(`${spec.displayName} config file not found. Expected one of: ${spec.configFiles.join(", ")}`);
|
|
1688
|
-
if (!deps[spec.dependency]) errors.push(`${spec.displayName} not found in dependencies. Run: ${spec.installCommand}`);
|
|
1689
|
-
} else warnings.push("No recognized frontend framework detected (Next.js, Vite, Remix). The app will run via its \"dev\" script. Set `framework` in your app config to enable strict validation.");
|
|
1690
|
-
if (!pkg.scripts?.dev) {
|
|
1691
|
-
if (resolvedFramework) warnings.push("No \"dev\" script found in package.json. Turbo expects a \"dev\" script to run.");
|
|
1692
|
-
else errors.push("No \"dev\" script found in package.json. Without a recognized framework or a dev script, there is nothing to run.");
|
|
1693
|
-
}
|
|
1694
|
-
return {
|
|
1695
|
-
appName,
|
|
1696
|
-
valid: errors.length === 0,
|
|
1697
|
-
errors,
|
|
1698
|
-
warnings
|
|
1699
|
-
};
|
|
1700
|
-
}
|
|
1234
|
+
* Development server entry point for a surface that serves itself
|
|
1235
|
+
* This file is auto-generated by 'gkm dev'
|
|
1236
|
+
*/
|
|
1237
|
+
${credentialsInjection}
|
|
1238
|
+
const port = process.argv.includes('--port')
|
|
1239
|
+
? Number.parseInt(process.argv[process.argv.indexOf('--port') + 1])
|
|
1240
|
+
: 3000;
|
|
1241
|
+
|
|
1242
|
+
// Dynamic import so Credentials are populated before the surface evaluates
|
|
1243
|
+
const { app } = await import('${appImportPath}');
|
|
1244
|
+
|
|
1245
|
+
${serveCode.replace(/^ {4}/gm, "")}
|
|
1246
|
+
console.log(\`Server started on port \${port}\`);
|
|
1247
|
+
`;
|
|
1248
|
+
return `#!/usr/bin/env node
|
|
1701
1249
|
/**
|
|
1702
|
-
*
|
|
1703
|
-
*
|
|
1704
|
-
|
|
1705
|
-
|
|
1706
|
-
|
|
1707
|
-
|
|
1708
|
-
|
|
1709
|
-
|
|
1710
|
-
|
|
1711
|
-
|
|
1712
|
-
|
|
1250
|
+
* Development server entry point
|
|
1251
|
+
* This file is auto-generated by 'gkm dev'
|
|
1252
|
+
*/
|
|
1253
|
+
${credentialsInjection}
|
|
1254
|
+
const port = process.argv.includes('--port')
|
|
1255
|
+
? Number.parseInt(process.argv[process.argv.indexOf('--port') + 1])
|
|
1256
|
+
: 3000;
|
|
1257
|
+
|
|
1258
|
+
// Dynamic import so Credentials are populated before env.ts evaluates
|
|
1259
|
+
const { createApp } = await import('${appImportPath}');
|
|
1260
|
+
|
|
1261
|
+
// createApp is async to support optional WebSocket setup
|
|
1262
|
+
const { app, start } = await createApp(undefined, ${enableOpenApi});
|
|
1263
|
+
|
|
1264
|
+
// Start the server
|
|
1265
|
+
start({
|
|
1266
|
+
port,
|
|
1267
|
+
serve: async (app, port) => {
|
|
1268
|
+
${serveCode}
|
|
1269
|
+
},
|
|
1270
|
+
}).catch((error) => {
|
|
1271
|
+
console.error('Failed to start server:', error);
|
|
1272
|
+
process.exit(1);
|
|
1273
|
+
});
|
|
1274
|
+
`;
|
|
1713
1275
|
}
|
|
1714
|
-
|
|
1715
|
-
|
|
1716
|
-
|
|
1717
|
-
|
|
1718
|
-
|
|
1719
|
-
|
|
1720
|
-
|
|
1721
|
-
|
|
1722
|
-
|
|
1723
|
-
|
|
1724
|
-
|
|
1725
|
-
|
|
1726
|
-
|
|
1727
|
-
|
|
1276
|
+
var DevServer = class {
|
|
1277
|
+
provider;
|
|
1278
|
+
requestedPort;
|
|
1279
|
+
portExplicit;
|
|
1280
|
+
enableOpenApi;
|
|
1281
|
+
telescope;
|
|
1282
|
+
studio;
|
|
1283
|
+
runtime;
|
|
1284
|
+
appRoot;
|
|
1285
|
+
secretsJsonPath;
|
|
1286
|
+
selfServing;
|
|
1287
|
+
serverProcess = null;
|
|
1288
|
+
isRunning = false;
|
|
1289
|
+
actualPort;
|
|
1290
|
+
startTime = Date.now();
|
|
1291
|
+
constructor(provider, requestedPort, portExplicit, enableOpenApi, telescope, studio, runtime = "node", appRoot = process.cwd(), secretsJsonPath, selfServing = false) {
|
|
1292
|
+
this.provider = provider;
|
|
1293
|
+
this.requestedPort = requestedPort;
|
|
1294
|
+
this.portExplicit = portExplicit;
|
|
1295
|
+
this.enableOpenApi = enableOpenApi;
|
|
1296
|
+
this.telescope = telescope;
|
|
1297
|
+
this.studio = studio;
|
|
1298
|
+
this.runtime = runtime;
|
|
1299
|
+
this.appRoot = appRoot;
|
|
1300
|
+
this.secretsJsonPath = secretsJsonPath;
|
|
1301
|
+
this.selfServing = selfServing;
|
|
1302
|
+
this.actualPort = requestedPort;
|
|
1728
1303
|
}
|
|
1729
|
-
|
|
1730
|
-
|
|
1731
|
-
|
|
1732
|
-
|
|
1733
|
-
|
|
1734
|
-
|
|
1735
|
-
|
|
1736
|
-
|
|
1737
|
-
|
|
1738
|
-
* 3. Generate dependency URLs ({APP_NAME}_URL)
|
|
1739
|
-
* 4. Spawn turbo run dev with injected env vars
|
|
1740
|
-
*/
|
|
1741
|
-
async function workspaceDevCommand(workspace, options) {
|
|
1742
|
-
const appCount = Object.keys(workspace.apps).length;
|
|
1743
|
-
const backendApps = Object.entries(workspace.apps).filter(([_, app]) => app.type === "backend");
|
|
1744
|
-
const frontendApps = Object.entries(workspace.apps).filter(([_, app]) => app.type === "web");
|
|
1745
|
-
const mobileApps = Object.entries(workspace.apps).filter(([_, app]) => app.type === "mobile");
|
|
1746
|
-
logger$11.log(`\n🚀 Starting workspace: ${workspace.name}`);
|
|
1747
|
-
const counts = [`${backendApps.length} backend`, `${frontendApps.length} web`];
|
|
1748
|
-
if (mobileApps.length > 0) counts.push(`${mobileApps.length} mobile`);
|
|
1749
|
-
logger$11.log(` ${counts.join(", ")} app(s)`);
|
|
1750
|
-
const conflicts = checkPortConflicts(workspace);
|
|
1751
|
-
if (conflicts.length > 0) {
|
|
1752
|
-
for (const conflict of conflicts) logger$11.error(`❌ Port conflict: Apps "${conflict.app1}" and "${conflict.app2}" both use port ${conflict.port}`);
|
|
1753
|
-
throw new Error("Port conflicts detected. Please assign unique ports to each app.");
|
|
1754
|
-
}
|
|
1755
|
-
if (frontendApps.length > 0) {
|
|
1756
|
-
logger$11.log("\n🔍 Validating frontend apps...");
|
|
1757
|
-
const validationResults = await validateFrontendApps(workspace);
|
|
1758
|
-
let hasErrors = false;
|
|
1759
|
-
for (const result of validationResults) {
|
|
1760
|
-
if (!result.valid) {
|
|
1761
|
-
hasErrors = true;
|
|
1762
|
-
logger$11.error(`\n❌ Frontend app "${result.appName}" validation failed:`);
|
|
1763
|
-
for (const error of result.errors) logger$11.error(` • ${error}`);
|
|
1764
|
-
}
|
|
1765
|
-
for (const warning of result.warnings) logger$11.warn(` ⚠️ ${result.appName}: ${warning}`);
|
|
1766
|
-
}
|
|
1767
|
-
if (hasErrors) throw new Error("Frontend app validation failed. Fix the issues above and try again.");
|
|
1768
|
-
logger$11.log("✅ Frontend apps validated");
|
|
1769
|
-
}
|
|
1770
|
-
const rawSecrets = await loadDevSecrets(workspace);
|
|
1771
|
-
let secretsEnv;
|
|
1772
|
-
if (usesConstructs(workspace)) {
|
|
1773
|
-
const reconciled = await reconcileWorkspace(workspace, { stage: workspace.stages.local });
|
|
1774
|
-
if (reconciled.changed && reconciled.plan.containers.length > 0) {
|
|
1775
|
-
logger$11.log(`🐳 Services: ${reconciled.plan.containers.join(", ")}`);
|
|
1776
|
-
for (const [container, address] of Object.entries(reconciled.addresses)) logger$11.log(` ${container}: ${address}`);
|
|
1777
|
-
}
|
|
1778
|
-
secretsEnv = {
|
|
1779
|
-
...rawSecrets,
|
|
1780
|
-
...reconciled.env
|
|
1781
|
-
};
|
|
1782
|
-
} else {
|
|
1783
|
-
const resolvedPorts = await resolveServicePorts(workspace.root);
|
|
1784
|
-
await startWorkspaceServices(workspace, resolvedPorts.dockerEnv, rawSecrets);
|
|
1785
|
-
secretsEnv = rewriteUrlsWithPorts(rawSecrets, resolvedPorts);
|
|
1786
|
-
}
|
|
1787
|
-
if (Object.keys(secretsEnv).length > 0) logger$11.log(` Loaded ${Object.keys(secretsEnv).length} secret(s)`);
|
|
1788
|
-
const dependencyEnv = generateAllDependencyEnvVars(workspace);
|
|
1789
|
-
if (Object.keys(dependencyEnv).length > 0) {
|
|
1790
|
-
logger$11.log("📡 Dependency URLs:");
|
|
1791
|
-
for (const [key, value] of Object.entries(dependencyEnv)) logger$11.log(` ${key}=${value}`);
|
|
1792
|
-
}
|
|
1793
|
-
let turboFilter = [];
|
|
1794
|
-
if (options.app) {
|
|
1795
|
-
if (!workspace.apps[options.app]) {
|
|
1796
|
-
const appNames = Object.keys(workspace.apps).join(", ");
|
|
1797
|
-
throw new Error(`App "${options.app}" not found. Available apps: ${appNames}`);
|
|
1304
|
+
async start() {
|
|
1305
|
+
this.startTime = Date.now();
|
|
1306
|
+
if (this.isRunning) await this.stop();
|
|
1307
|
+
if (this.portExplicit) {
|
|
1308
|
+
if (!await isPortAvailable(this.requestedPort)) throw new Error(`Port ${this.requestedPort} is already in use. Either stop the process using that port or omit -p/--port to auto-select an available port.`);
|
|
1309
|
+
this.actualPort = this.requestedPort;
|
|
1310
|
+
} else {
|
|
1311
|
+
this.actualPort = await findAvailablePort(this.requestedPort);
|
|
1312
|
+
if (this.actualPort !== this.requestedPort) logger$11.log(`ℹ️ Port ${this.requestedPort} was in use, using port ${this.actualPort} instead`);
|
|
1798
1313
|
}
|
|
1799
|
-
|
|
1800
|
-
|
|
1801
|
-
|
|
1802
|
-
|
|
1803
|
-
|
|
1804
|
-
|
|
1805
|
-
|
|
1806
|
-
|
|
1807
|
-
|
|
1808
|
-
|
|
1809
|
-
|
|
1810
|
-
|
|
1811
|
-
|
|
1812
|
-
|
|
1813
|
-
|
|
1814
|
-
|
|
1815
|
-
|
|
1816
|
-
|
|
1817
|
-
|
|
1818
|
-
|
|
1819
|
-
|
|
1820
|
-
|
|
1821
|
-
|
|
1822
|
-
|
|
1823
|
-
|
|
1824
|
-
|
|
1314
|
+
const serverEntryPath = join(this.appRoot, ".gkm", this.provider, "server.ts");
|
|
1315
|
+
await this.createServerEntry();
|
|
1316
|
+
logger$11.log(`\n⏳ Starting server...`);
|
|
1317
|
+
this.serverProcess = spawn("npx", [
|
|
1318
|
+
"tsx",
|
|
1319
|
+
serverEntryPath,
|
|
1320
|
+
"--port",
|
|
1321
|
+
this.actualPort.toString()
|
|
1322
|
+
], {
|
|
1323
|
+
stdio: "inherit",
|
|
1324
|
+
env: {
|
|
1325
|
+
...process.env,
|
|
1326
|
+
NODE_ENV: "development"
|
|
1327
|
+
},
|
|
1328
|
+
detached: true
|
|
1329
|
+
});
|
|
1330
|
+
this.isRunning = true;
|
|
1331
|
+
this.serverProcess.on("error", (error) => {
|
|
1332
|
+
logger$11.error("❌ Server error:", error);
|
|
1333
|
+
});
|
|
1334
|
+
this.serverProcess.on("exit", (code, signal) => {
|
|
1335
|
+
if (code !== null && code !== 0 && signal !== "SIGTERM") logger$11.error(`❌ Server exited with code ${code}`);
|
|
1336
|
+
this.isRunning = false;
|
|
1337
|
+
});
|
|
1338
|
+
await new Promise((resolve) => setTimeout(resolve, 1e3));
|
|
1339
|
+
if (this.isRunning) {
|
|
1340
|
+
const base = `http://localhost:${this.actualPort}`;
|
|
1341
|
+
const lines = [` Local: ${base}`];
|
|
1342
|
+
if (this.enableOpenApi) lines.push(` API Docs: ${base}/__docs`);
|
|
1343
|
+
if (this.telescope) lines.push(` Telescope: ${base}${this.telescope.path}`);
|
|
1344
|
+
if (this.studio) lines.push(` Studio: ${base}${this.studio.path}`);
|
|
1345
|
+
const maxLen = Math.max(...lines.map((l) => l.length));
|
|
1346
|
+
const pad = (s) => s.padEnd(maxLen);
|
|
1347
|
+
const border = "─".repeat(maxLen + 2);
|
|
1348
|
+
logger$11.log("");
|
|
1349
|
+
logger$11.log(` \x1b[32m✓ Ready\x1b[0m in ${((Date.now() - this.startTime) / 1e3).toFixed(1)}s`);
|
|
1350
|
+
logger$11.log("");
|
|
1351
|
+
logger$11.log(` ┌${border}┐`);
|
|
1352
|
+
for (const line of lines) logger$11.log(` │ ${pad(line)} │`);
|
|
1353
|
+
logger$11.log(` └${border}┘`);
|
|
1354
|
+
logger$11.log("");
|
|
1825
1355
|
}
|
|
1826
1356
|
}
|
|
1827
|
-
|
|
1828
|
-
|
|
1829
|
-
|
|
1830
|
-
|
|
1831
|
-
NODE_ENV: "development",
|
|
1832
|
-
...configPath ? { GKM_CONFIG_PATH: configPath } : {}
|
|
1833
|
-
};
|
|
1834
|
-
logger$11.log("\n🏃 Starting turbo run dev...\n");
|
|
1835
|
-
const turboProcess = spawn("pnpm", [
|
|
1836
|
-
"turbo",
|
|
1837
|
-
"run",
|
|
1838
|
-
"dev",
|
|
1839
|
-
...turboFilter
|
|
1840
|
-
], {
|
|
1841
|
-
cwd: workspace.root,
|
|
1842
|
-
stdio: "inherit",
|
|
1843
|
-
env: turboEnv,
|
|
1844
|
-
detached: true
|
|
1845
|
-
});
|
|
1846
|
-
let isShuttingDown = false;
|
|
1847
|
-
const shutdown = () => {
|
|
1848
|
-
if (isShuttingDown) return;
|
|
1849
|
-
isShuttingDown = true;
|
|
1850
|
-
logger$11.log("\n🛑 Shutting down workspace...");
|
|
1851
|
-
const pid = turboProcess.pid;
|
|
1852
|
-
if (pid) try {
|
|
1853
|
-
process.kill(-pid, "SIGTERM");
|
|
1854
|
-
} catch {
|
|
1855
|
-
try {
|
|
1856
|
-
process.kill(pid, "SIGTERM");
|
|
1857
|
-
} catch {}
|
|
1858
|
-
}
|
|
1859
|
-
setTimeout(() => {
|
|
1357
|
+
async stop() {
|
|
1358
|
+
const port = this.actualPort;
|
|
1359
|
+
if (this.serverProcess && this.isRunning) {
|
|
1360
|
+
const pid = this.serverProcess.pid;
|
|
1860
1361
|
if (pid) try {
|
|
1861
1362
|
process.kill(-pid, "SIGKILL");
|
|
1862
1363
|
} catch {
|
|
@@ -1864,386 +1365,803 @@ async function workspaceDevCommand(workspace, options) {
|
|
|
1864
1365
|
process.kill(pid, "SIGKILL");
|
|
1865
1366
|
} catch {}
|
|
1866
1367
|
}
|
|
1867
|
-
|
|
1868
|
-
|
|
1869
|
-
|
|
1870
|
-
|
|
1871
|
-
process.on("SIGTERM", shutdown);
|
|
1872
|
-
return new Promise((resolve, reject) => {
|
|
1873
|
-
turboProcess.on("error", (error) => {
|
|
1874
|
-
logger$11.error("❌ Turbo error:", error);
|
|
1875
|
-
reject(error);
|
|
1876
|
-
});
|
|
1877
|
-
turboProcess.on("exit", (code) => {
|
|
1878
|
-
if (code !== null && code !== 0) reject(/* @__PURE__ */ new Error(`Turbo exited with code ${code}`));
|
|
1879
|
-
else resolve();
|
|
1880
|
-
});
|
|
1881
|
-
});
|
|
1882
|
-
}
|
|
1883
|
-
/**
|
|
1884
|
-
* What the app declares, or nothing when it declares in the old way.
|
|
1885
|
-
*
|
|
1886
|
-
* Discovery imports the application's construct modules, which is why this is
|
|
1887
|
-
* guarded rather than unconditional: a project with no `constructs` glob has
|
|
1888
|
-
* not adopted the model, and there is nothing to import.
|
|
1889
|
-
*/
|
|
1890
|
-
async function declaredConstructs(config, appRoot, sources) {
|
|
1891
|
-
const patterns = typeof config?.constructs === "string" || Array.isArray(config?.constructs) ? config.constructs : void 0;
|
|
1892
|
-
if (!patterns) return {};
|
|
1893
|
-
try {
|
|
1894
|
-
return await discover({
|
|
1895
|
-
patterns: (Array.isArray(patterns) ? patterns : [patterns]).map((p) => isAbsolute(p) ? p : join(appRoot, p)),
|
|
1896
|
-
cwd: appRoot,
|
|
1897
|
-
sources
|
|
1898
|
-
});
|
|
1899
|
-
} catch {
|
|
1900
|
-
return {};
|
|
1368
|
+
this.serverProcess = null;
|
|
1369
|
+
this.isRunning = false;
|
|
1370
|
+
}
|
|
1371
|
+
this.killProcessesOnPort(port);
|
|
1901
1372
|
}
|
|
1902
|
-
|
|
1903
|
-
|
|
1904
|
-
|
|
1905
|
-
|
|
1906
|
-
|
|
1907
|
-
|
|
1908
|
-
|
|
1909
|
-
|
|
1910
|
-
|
|
1911
|
-
|
|
1912
|
-
|
|
1913
|
-
|
|
1914
|
-
|
|
1915
|
-
|
|
1916
|
-
|
|
1917
|
-
|
|
1918
|
-
|
|
1919
|
-
|
|
1920
|
-
|
|
1921
|
-
|
|
1922
|
-
|
|
1923
|
-
|
|
1924
|
-
|
|
1925
|
-
|
|
1926
|
-
|
|
1927
|
-
|
|
1928
|
-
|
|
1929
|
-
|
|
1930
|
-
|
|
1931
|
-
|
|
1932
|
-
|
|
1933
|
-
|
|
1934
|
-
|
|
1935
|
-
|
|
1936
|
-
|
|
1937
|
-
|
|
1938
|
-
|
|
1939
|
-
|
|
1940
|
-
|
|
1941
|
-
|
|
1942
|
-
|
|
1943
|
-
|
|
1944
|
-
|
|
1945
|
-
|
|
1946
|
-
|
|
1947
|
-
|
|
1948
|
-
|
|
1949
|
-
|
|
1950
|
-
|
|
1951
|
-
|
|
1952
|
-
|
|
1953
|
-
|
|
1954
|
-
|
|
1955
|
-
|
|
1956
|
-
|
|
1957
|
-
|
|
1958
|
-
|
|
1959
|
-
|
|
1960
|
-
|
|
1961
|
-
|
|
1962
|
-
|
|
1963
|
-
|
|
1964
|
-
|
|
1965
|
-
|
|
1966
|
-
|
|
1967
|
-
|
|
1968
|
-
|
|
1969
|
-
|
|
1970
|
-
|
|
1971
|
-
|
|
1972
|
-
|
|
1973
|
-
|
|
1974
|
-
|
|
1975
|
-
|
|
1976
|
-
|
|
1977
|
-
|
|
1978
|
-
|
|
1979
|
-
|
|
1980
|
-
|
|
1981
|
-
|
|
1373
|
+
killProcessesOnPort(port) {
|
|
1374
|
+
try {
|
|
1375
|
+
execSync(`lsof -ti tcp:${port} -sTCP:LISTEN | xargs kill -9 2>/dev/null || true`, { stdio: "ignore" });
|
|
1376
|
+
} catch {}
|
|
1377
|
+
}
|
|
1378
|
+
async restart() {
|
|
1379
|
+
const portToReuse = this.actualPort;
|
|
1380
|
+
await this.stop();
|
|
1381
|
+
let attempts = 0;
|
|
1382
|
+
while (attempts < 30) {
|
|
1383
|
+
if (await isPortAvailable(portToReuse)) break;
|
|
1384
|
+
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
1385
|
+
attempts++;
|
|
1386
|
+
}
|
|
1387
|
+
this.requestedPort = portToReuse;
|
|
1388
|
+
await this.start();
|
|
1389
|
+
}
|
|
1390
|
+
async createServerEntry() {
|
|
1391
|
+
const { writeFile: fsWriteFile } = await import("node:fs/promises");
|
|
1392
|
+
await fsWriteFile(join(this.appRoot, ".gkm", this.provider, "server.ts"), generateServerEntryContent({
|
|
1393
|
+
secretsJsonPath: this.secretsJsonPath,
|
|
1394
|
+
runtime: this.runtime,
|
|
1395
|
+
enableOpenApi: this.enableOpenApi,
|
|
1396
|
+
selfServing: this.selfServing
|
|
1397
|
+
}));
|
|
1398
|
+
}
|
|
1399
|
+
};
|
|
1400
|
+
//#endregion
|
|
1401
|
+
//#region src/generators/CronGenerator.ts
|
|
1402
|
+
var CronGenerator = class extends ConstructGenerator {
|
|
1403
|
+
async build(context, constructs, outputDir, options) {
|
|
1404
|
+
const provider = options?.provider || "aws-lambda";
|
|
1405
|
+
const logger = console;
|
|
1406
|
+
const cronInfos = [];
|
|
1407
|
+
if (provider === "server") {
|
|
1408
|
+
await this.generateServerCronsFile(outputDir, constructs);
|
|
1409
|
+
logger.log(`Generated server crons file with ${constructs.length} crons`);
|
|
1410
|
+
return cronInfos;
|
|
1411
|
+
}
|
|
1412
|
+
if (constructs.length === 0 || provider !== "aws-lambda") return cronInfos;
|
|
1413
|
+
const cronsDir = join(outputDir, "crons");
|
|
1414
|
+
await mkdir(cronsDir, { recursive: true });
|
|
1415
|
+
for (const { key, construct, path } of constructs) {
|
|
1416
|
+
const handlerFile = await this.generateCronHandler(cronsDir, path.relative, key, context, construct.owner);
|
|
1417
|
+
cronInfos.push({
|
|
1418
|
+
name: key,
|
|
1419
|
+
handler: relative(process.cwd(), handlerFile).replace(/\.ts$/, ".handler"),
|
|
1420
|
+
schedule: construct.schedule || "rate(1 hour)",
|
|
1421
|
+
timeout: construct.timeout,
|
|
1422
|
+
memorySize: construct.memorySize,
|
|
1423
|
+
environment: await construct.getEnvironment({ markOptional: context.markOptional }),
|
|
1424
|
+
dependencies: construct.constructs
|
|
1425
|
+
});
|
|
1426
|
+
logger.log(`Generated cron handler: ${key}`);
|
|
1427
|
+
}
|
|
1428
|
+
return cronInfos;
|
|
1429
|
+
}
|
|
1430
|
+
isConstruct(value) {
|
|
1431
|
+
return Cron.isCron(value);
|
|
1432
|
+
}
|
|
1433
|
+
/**
|
|
1434
|
+
* The crons file a server entry imports.
|
|
1435
|
+
*
|
|
1436
|
+
* Shaped after `generateServerSubscribersFile`: one module, every cron, a
|
|
1437
|
+
* `setupCrons` the generated entry calls beside `setupSubscribers`.
|
|
1438
|
+
*
|
|
1439
|
+
* It picks its scheduler from what the process can reach. With a Postgres it
|
|
1440
|
+
* uses pg-boss, whose schedules live in the database — so a deployment
|
|
1441
|
+
* running four replicas fires each job once, which is the thing a timer in
|
|
1442
|
+
* every process gets wrong and does not report. With no database it falls
|
|
1443
|
+
* back to timers and says plainly that it is doing so.
|
|
1444
|
+
*/
|
|
1445
|
+
async generateServerCronsFile(outputDir, crons) {
|
|
1446
|
+
await mkdir(outputDir, { recursive: true });
|
|
1447
|
+
const cronsPath = join(outputDir, "crons.ts");
|
|
1448
|
+
const importsByFile = /* @__PURE__ */ new Map();
|
|
1449
|
+
for (const { path, key } of crons) {
|
|
1450
|
+
const importPath = relative(dirname(cronsPath), path.relative).replace(/\.ts$/, ".js");
|
|
1451
|
+
if (!importsByFile.has(importPath)) importsByFile.set(importPath, []);
|
|
1452
|
+
importsByFile.get(importPath)?.push(key);
|
|
1453
|
+
}
|
|
1454
|
+
const content = `/**
|
|
1455
|
+
* Generated cron setup.
|
|
1456
|
+
*
|
|
1457
|
+
* Schedules every cron this app declares, in the process that serves it.
|
|
1458
|
+
*
|
|
1459
|
+
* The schedule lives in Postgres, through pg-boss, in the database the worker
|
|
1460
|
+
* named with \`.database(db)\`. That is what makes running several replicas
|
|
1461
|
+
* safe: each job fires once, where a timer in every process fires it once per
|
|
1462
|
+
* replica and reports nothing.
|
|
1463
|
+
*
|
|
1464
|
+
* No connection string appears here. The construct that owns the database is
|
|
1465
|
+
* the only thing that knows its key, and it is resolved through service
|
|
1466
|
+
* discovery like any other dependency.
|
|
1467
|
+
*/
|
|
1468
|
+
import type { EnvironmentParser } from '@geekmidas/envkit';
|
|
1469
|
+
import type { Logger } from '@geekmidas/logger';
|
|
1470
|
+
import { toCronExpression } from '@geekmidas/constructs/crons';
|
|
1471
|
+
import { ServiceDiscovery } from '@geekmidas/services';
|
|
1472
|
+
${Array.from(importsByFile.entries()).map(([importPath, exports]) => `import { ${exports.join(", ")} } from '${importPath}';`).join("\n")}
|
|
1473
|
+
|
|
1474
|
+
const crons = [
|
|
1475
|
+
${crons.map(({ key }) => ` { name: '${key}', cron: ${key} }`).join(",\n")}
|
|
1476
|
+
];
|
|
1477
|
+
|
|
1478
|
+
type Stoppable = { stop: () => Promise<void> | void };
|
|
1479
|
+
const running: Stoppable[] = [];
|
|
1480
|
+
|
|
1481
|
+
export async function setupCrons(
|
|
1482
|
+
envParser: EnvironmentParser<any>,
|
|
1483
|
+
logger: Logger,
|
|
1484
|
+
): Promise<void> {
|
|
1485
|
+
if (crons.length === 0) {
|
|
1486
|
+
return;
|
|
1487
|
+
}
|
|
1488
|
+
|
|
1489
|
+
const serviceDiscovery = ServiceDiscovery.getInstance(envParser);
|
|
1490
|
+
|
|
1491
|
+
// Resolved once per cron rather than per firing: registering services on
|
|
1492
|
+
// every tick would reconnect a database every minute.
|
|
1493
|
+
const prepared = [];
|
|
1494
|
+
for (const { name, cron } of crons) {
|
|
1495
|
+
try {
|
|
1496
|
+
const schedule = toCronExpression(cron.schedule);
|
|
1497
|
+
const services = cron.services.length > 0
|
|
1498
|
+
? await serviceDiscovery.register(cron.services)
|
|
1499
|
+
: {};
|
|
1500
|
+
|
|
1501
|
+
prepared.push({ name, cron, schedule, services });
|
|
1502
|
+
} catch (error) {
|
|
1503
|
+
// An unrepresentable schedule is a build-time mistake, and failing the
|
|
1504
|
+
// process for it would take the HTTP server down with it.
|
|
1505
|
+
logger.error({ error, cron: name }, 'Cron has no runnable schedule, skipping');
|
|
1506
|
+
}
|
|
1507
|
+
}
|
|
1508
|
+
|
|
1509
|
+
const run = async (entry: (typeof prepared)[number]) => {
|
|
1510
|
+
try {
|
|
1511
|
+
await entry.cron.handler({
|
|
1512
|
+
input: undefined,
|
|
1513
|
+
services: entry.services,
|
|
1514
|
+
logger: entry.cron.logger,
|
|
1515
|
+
});
|
|
1516
|
+
} catch (error) {
|
|
1517
|
+
logger.error({ error, cron: entry.name }, 'Cron failed');
|
|
1518
|
+
}
|
|
1519
|
+
};
|
|
1520
|
+
|
|
1521
|
+
// The app's one pg-boss: the events broker's, as the broker's role, in the
|
|
1522
|
+
// broker's schema. A server fires its own crons, and a process scheduling in
|
|
1523
|
+
// memory fires each job once per replica — so the schedule lives in
|
|
1524
|
+
// Postgres. It used to be a second pg-boss on the worker's database, as the
|
|
1525
|
+
// runtime role, which can neither create a schema nor use the broker's.
|
|
1526
|
+
const { url } = envParser
|
|
1527
|
+
.create((get) => ({
|
|
1528
|
+
url: get('EVENT_SUBSCRIBER_CONNECTION_STRING').string().optional(),
|
|
1529
|
+
}))
|
|
1530
|
+
.parse();
|
|
1531
|
+
|
|
1532
|
+
if (!url?.startsWith('pgboss://')) {
|
|
1533
|
+
logger.error(
|
|
1534
|
+
{ crons: prepared.map(({ name }) => name) },
|
|
1535
|
+
'These crons have nowhere to keep their schedule. On a server they are ' +
|
|
1536
|
+
'scheduled through the pg-boss events broker ' +
|
|
1537
|
+
'(EVENT_SUBSCRIBER_CONNECTION_STRING), and ' +
|
|
1538
|
+
(url ? 'the broker configured is not pg-boss.' : 'none is configured.'),
|
|
1539
|
+
);
|
|
1540
|
+
return;
|
|
1541
|
+
}
|
|
1542
|
+
|
|
1543
|
+
const { PgBossConnection } = await import('@geekmidas/events/pgboss');
|
|
1544
|
+
const connection = await PgBossConnection.fromConnectionString(url);
|
|
1545
|
+
const boss = connection.instance!;
|
|
1546
|
+
|
|
1547
|
+
// What this app declares now. Anything else under the prefix belonged to a
|
|
1548
|
+
// cron since renamed or deleted, and would keep firing at a handler that has
|
|
1549
|
+
// gone.
|
|
1550
|
+
//
|
|
1551
|
+
// The prefix is \`cron.\` rather than \`cron:\`: pg-boss accepts
|
|
1552
|
+
// alphanumerics, underscores, hyphens, periods and slashes in a queue name,
|
|
1553
|
+
// and rejects a colon outright.
|
|
1554
|
+
const declared = new Set(prepared.map(({ name }) => \`cron.\${name}\`));
|
|
1555
|
+
for (const existing of await boss.getSchedules()) {
|
|
1556
|
+
if (existing.name.startsWith('cron.') && !declared.has(existing.name)) {
|
|
1557
|
+
await boss.unschedule(existing.name);
|
|
1558
|
+
logger.info({ cron: existing.name }, 'Removed a schedule nothing declares');
|
|
1559
|
+
}
|
|
1560
|
+
}
|
|
1561
|
+
|
|
1562
|
+
for (const entry of prepared) {
|
|
1563
|
+
const queue = \`cron.\${entry.name}\`;
|
|
1564
|
+
await boss.createQueue(queue);
|
|
1565
|
+
// UTC, so this agrees with the schedule a deploy target would have made.
|
|
1566
|
+
await boss.schedule(queue, entry.schedule, undefined, { tz: 'UTC' });
|
|
1567
|
+
await boss.work(queue, () => run(entry));
|
|
1568
|
+
|
|
1569
|
+
logger.info({ cron: entry.name, schedule: entry.schedule }, 'Cron scheduled');
|
|
1570
|
+
}
|
|
1571
|
+
|
|
1572
|
+
running.push({ stop: () => connection.close() });
|
|
1573
|
+
logger.info({ count: prepared.length }, 'Crons scheduled');
|
|
1574
|
+
}
|
|
1575
|
+
|
|
1576
|
+
export async function stopCrons(): Promise<void> {
|
|
1577
|
+
await Promise.all(running.map((r) => r.stop()));
|
|
1578
|
+
running.length = 0;
|
|
1579
|
+
}
|
|
1580
|
+
`;
|
|
1581
|
+
await writeFile(cronsPath, content);
|
|
1582
|
+
return cronsPath;
|
|
1583
|
+
}
|
|
1584
|
+
async generateCronHandler(outputDir, sourceFile, exportName, context, owner) {
|
|
1585
|
+
const handlerFileName = `${exportName}.ts`;
|
|
1586
|
+
const handlerPath = join(outputDir, handlerFileName);
|
|
1587
|
+
const importPath = relative(dirname(handlerPath), sourceFile).replace(/\.ts$/, ".js");
|
|
1588
|
+
const runtime = runtimeFor(context, dirname(handlerPath), owner);
|
|
1589
|
+
const content = `import { AWSScheduledFunction } from '@geekmidas/constructs/aws';
|
|
1590
|
+
import { ${exportName} } from '${importPath}';
|
|
1591
|
+
${runtime.imports}
|
|
1592
|
+
${runtime.bindings}
|
|
1593
|
+
|
|
1594
|
+
const adapter = new AWSScheduledFunction(envParser, ${exportName});
|
|
1595
|
+
|
|
1596
|
+
export const handler = adapter.handler;
|
|
1597
|
+
`;
|
|
1598
|
+
await writeFile(handlerPath, content);
|
|
1599
|
+
return handlerPath;
|
|
1600
|
+
}
|
|
1601
|
+
};
|
|
1602
|
+
//#endregion
|
|
1603
|
+
//#region src/generators/drivers.ts
|
|
1604
|
+
/**
|
|
1605
|
+
* Driver registration for generated entry points.
|
|
1606
|
+
*
|
|
1607
|
+
* A construct declares that it needs object storage and is handed one URL; the
|
|
1608
|
+
* scheme in that URL picks the driver that builds the client. Which drivers
|
|
1609
|
+
* exist is therefore the *entry point's* decision, not the construct's and not
|
|
1610
|
+
* the application's — an app that never talks to S3 should never resolve the AWS
|
|
1611
|
+
* SDK, and application code that registers a driver has named a provider in the
|
|
1612
|
+
* one layer this design keeps provider-free.
|
|
1613
|
+
*
|
|
1614
|
+
* So the generated entries register: `gkm dev`'s server for local development,
|
|
1615
|
+
* and each Lambda handler for its own target. Registration is an explicit call
|
|
1616
|
+
* rather than an import side effect, because a side-effecting module is exactly
|
|
1617
|
+
* what a bundler is entitled to drop.
|
|
1618
|
+
*/
|
|
1619
|
+
/** The `s3://` driver, which serves MinIO locally and S3 deployed. */
|
|
1620
|
+
const S3 = {
|
|
1621
|
+
imports: `import { registerStorageDriver } from '@geekmidas/storage';\nimport { s3Driver } from '@geekmidas/storage/aws';`,
|
|
1622
|
+
setup: "registerStorageDriver(s3Driver);"
|
|
1623
|
+
};
|
|
1624
|
+
const NONE = {
|
|
1625
|
+
imports: "",
|
|
1626
|
+
setup: ""
|
|
1627
|
+
};
|
|
1628
|
+
/**
|
|
1629
|
+
* The cache driver for a backend — exactly one, never all three.
|
|
1630
|
+
*
|
|
1631
|
+
* Keyed off the *backend* rather than off a dependency, because unlike storage
|
|
1632
|
+
* the backend already says which driver is right: a project caching in Postgres
|
|
1633
|
+
* resolves `pg` and never `ioredis`, and one caching in Upstash resolves
|
|
1634
|
+
* neither. That is the whole reason the drivers live behind separate subpaths.
|
|
1635
|
+
*
|
|
1636
|
+
* Both HTTP schemes are registered for Upstash, because the local proxy speaks
|
|
1637
|
+
* `http://` and Upstash speaks `https://`, and an entry that registered one
|
|
1638
|
+
* would work in exactly one of the two places.
|
|
1639
|
+
*/
|
|
1640
|
+
const CACHE_DRIVERS = {
|
|
1641
|
+
upstash: {
|
|
1642
|
+
imports: `import { registerCacheDriver } from '@geekmidas/cache';\nimport { upstashCacheDriver, upstashInsecureCacheDriver } from '@geekmidas/cache/upstash';`,
|
|
1643
|
+
setup: "registerCacheDriver(upstashCacheDriver);\nregisterCacheDriver(upstashInsecureCacheDriver);"
|
|
1644
|
+
},
|
|
1645
|
+
elasticache: {
|
|
1646
|
+
imports: `import { registerCacheDriver } from '@geekmidas/cache';\nimport { redisCacheDriver, redissCacheDriver } from '@geekmidas/cache/redis';`,
|
|
1647
|
+
setup: "registerCacheDriver(redisCacheDriver);\nregisterCacheDriver(redissCacheDriver);"
|
|
1648
|
+
},
|
|
1649
|
+
db: {
|
|
1650
|
+
imports: `import { registerCacheDriver } from '@geekmidas/cache';\nimport { postgresCacheDriver } from '@geekmidas/cache/postgres';`,
|
|
1651
|
+
setup: "registerCacheDriver(postgresCacheDriver);"
|
|
1652
|
+
}
|
|
1653
|
+
};
|
|
1654
|
+
/**
|
|
1655
|
+
* Everything a generated entry should register: object storage, and the cache.
|
|
1656
|
+
*
|
|
1657
|
+
* Merged here rather than threaded separately, because a generated file has one
|
|
1658
|
+
* import block and one setup block whatever fills them.
|
|
1659
|
+
*/
|
|
1660
|
+
function driversFor(options) {
|
|
1661
|
+
const backends = options.cache === false || options.cache === void 0 ? [] : typeof options.cache === "string" ? [options.cache] : options.cache;
|
|
1662
|
+
const parts = [storageDriversFor(options.appRoot), ...[...new Set(backends)].map((backend) => CACHE_DRIVERS[backend] ?? CACHE_DRIVERS[DEFAULT_CACHE.aws])].filter((part) => part.imports || part.setup);
|
|
1663
|
+
if (parts.length === 0) return NONE;
|
|
1664
|
+
return {
|
|
1665
|
+
imports: parts.map((part) => part.imports).join("\n"),
|
|
1666
|
+
setup: parts.map((part) => part.setup).join("\n")
|
|
1667
|
+
};
|
|
1668
|
+
}
|
|
1669
|
+
/**
|
|
1670
|
+
* Which cache backends an app's entry actually has to speak.
|
|
1671
|
+
*
|
|
1672
|
+
* The config answers this for a cache that named nowhere, and the *declaration*
|
|
1673
|
+
* answers it for one that named a database — `orders.cache('Sessions')` is a
|
|
1674
|
+
* statement about the application, so a deployment cannot move that cache and
|
|
1675
|
+
* the entry cannot register a driver for somewhere else.
|
|
1676
|
+
*
|
|
1677
|
+
* Reading only the config is how an entry ends up registering the Upstash
|
|
1678
|
+
* driver for a URL the target composed as `postgres://`, which fails at the
|
|
1679
|
+
* first request with `UnregisteredCacheScheme` and a stack that points at the
|
|
1680
|
+
* cache rather than at the config that disagreed.
|
|
1681
|
+
*/
|
|
1682
|
+
function cacheBackendsIn(manifest, configured) {
|
|
1683
|
+
const caches = Object.values(manifest).filter((d) => d.kind === "cache");
|
|
1684
|
+
return [...new Set(caches.map((c) => c.of ? "db" : configured))];
|
|
1685
|
+
}
|
|
1686
|
+
/**
|
|
1687
|
+
* The drivers an app's entry points should register.
|
|
1688
|
+
*
|
|
1689
|
+
* Keyed off the dependency rather than off a declared bucket, because the entry
|
|
1690
|
+
* is generated before discovery has run on the watcher's rebuild path — and an
|
|
1691
|
+
* app that installed `@geekmidas/storage` has already paid for the SDK it would
|
|
1692
|
+
* otherwise resolve lazily.
|
|
1693
|
+
*/
|
|
1694
|
+
function storageDriversFor(appRoot) {
|
|
1695
|
+
return dependsOnStorage(appRoot) ? S3 : NONE;
|
|
1696
|
+
}
|
|
1697
|
+
function dependsOnStorage(appRoot) {
|
|
1698
|
+
const manifest = join(appRoot, "package.json");
|
|
1699
|
+
if (!existsSync(manifest)) return false;
|
|
1700
|
+
try {
|
|
1701
|
+
const pkg = JSON.parse(readFileSync(manifest, "utf8"));
|
|
1702
|
+
return Boolean(pkg.dependencies?.["@geekmidas/storage"] ?? pkg.devDependencies?.["@geekmidas/storage"]);
|
|
1703
|
+
} catch {
|
|
1704
|
+
return false;
|
|
1705
|
+
}
|
|
1706
|
+
}
|
|
1707
|
+
//#endregion
|
|
1708
|
+
//#region src/generators/FunctionGenerator.ts
|
|
1709
|
+
var FunctionGenerator = class extends ConstructGenerator {
|
|
1710
|
+
isConstruct(value) {
|
|
1711
|
+
return Function.isFunction(value);
|
|
1712
|
+
}
|
|
1713
|
+
async build(context, constructs, outputDir, options) {
|
|
1714
|
+
const provider = options?.provider || "aws-lambda";
|
|
1715
|
+
const logger = console;
|
|
1716
|
+
const functionInfos = [];
|
|
1717
|
+
if (constructs.length === 0 || provider !== "aws-lambda") return functionInfos;
|
|
1718
|
+
const functionsDir = join(outputDir, "functions");
|
|
1719
|
+
await mkdir(functionsDir, { recursive: true });
|
|
1720
|
+
for (const { key, construct, path } of constructs) {
|
|
1721
|
+
const handlerFile = await this.generateFunctionHandler(functionsDir, path.relative, key, context, construct.owner);
|
|
1722
|
+
functionInfos.push({
|
|
1723
|
+
name: key,
|
|
1724
|
+
handler: relative(process.cwd(), handlerFile).replace(/\.ts$/, ".handler"),
|
|
1725
|
+
timeout: construct.timeout,
|
|
1726
|
+
memorySize: construct.memorySize,
|
|
1727
|
+
environment: await construct.getEnvironment({ markOptional: context.markOptional }),
|
|
1728
|
+
dependencies: construct.constructs
|
|
1729
|
+
});
|
|
1730
|
+
logger.log(`Generated function handler: ${key}`);
|
|
1731
|
+
}
|
|
1732
|
+
return functionInfos;
|
|
1733
|
+
}
|
|
1734
|
+
async generateFunctionHandler(outputDir, sourceFile, exportName, context, owner) {
|
|
1735
|
+
const handlerFileName = `${exportName}.ts`;
|
|
1736
|
+
const handlerPath = join(outputDir, handlerFileName);
|
|
1737
|
+
const importPath = relative(dirname(handlerPath), sourceFile).replace(/\.ts$/, ".js");
|
|
1738
|
+
const runtime = runtimeFor(context, dirname(handlerPath), owner);
|
|
1739
|
+
const content = `import { AWSLambdaFunction } from '@geekmidas/constructs/aws';
|
|
1740
|
+
import { ${exportName} } from '${importPath}';
|
|
1741
|
+
${runtime.imports}
|
|
1742
|
+
${runtime.bindings}
|
|
1743
|
+
|
|
1744
|
+
const adapter = new AWSLambdaFunction(envParser, ${exportName});
|
|
1745
|
+
|
|
1746
|
+
export const handler = adapter.handler;
|
|
1747
|
+
`;
|
|
1748
|
+
await writeFile(handlerPath, content);
|
|
1749
|
+
return handlerPath;
|
|
1750
|
+
}
|
|
1751
|
+
};
|
|
1752
|
+
//#endregion
|
|
1753
|
+
//#region src/generators/QueueGenerator.ts
|
|
1982
1754
|
/**
|
|
1983
|
-
*
|
|
1755
|
+
* Generates the runtime for `q` queue workers.
|
|
1756
|
+
*
|
|
1757
|
+
* - **server** (`gkm dev`): a single `queues.ts` exposing `setupQueues()` that
|
|
1758
|
+
* runs an in-process pg-boss poller alongside the Hono server — no SQS/Lambda.
|
|
1759
|
+
* Each queue subscribes by its **name** on the shared event connection.
|
|
1760
|
+
* - **aws-lambda**: one handler file per queue wrapping `AWSLambdaQueue`, backed
|
|
1761
|
+
* by an SQS event-source mapping.
|
|
1984
1762
|
*/
|
|
1985
|
-
var
|
|
1986
|
-
|
|
1987
|
-
|
|
1988
|
-
watch;
|
|
1989
|
-
port;
|
|
1990
|
-
childProcess = null;
|
|
1991
|
-
watcher = null;
|
|
1992
|
-
isRunning = false;
|
|
1993
|
-
constructor(wrapperPath, entryPath, watch, port) {
|
|
1994
|
-
this.wrapperPath = wrapperPath;
|
|
1995
|
-
this.entryPath = entryPath;
|
|
1996
|
-
this.watch = watch;
|
|
1997
|
-
this.port = port;
|
|
1763
|
+
var QueueGenerator = class extends ConstructGenerator {
|
|
1764
|
+
isConstruct(value) {
|
|
1765
|
+
return Queue.isQueue(value);
|
|
1998
1766
|
}
|
|
1999
|
-
async
|
|
2000
|
-
|
|
2001
|
-
|
|
2002
|
-
|
|
2003
|
-
|
|
2004
|
-
|
|
2005
|
-
|
|
2006
|
-
|
|
2007
|
-
|
|
2008
|
-
|
|
2009
|
-
|
|
2010
|
-
|
|
2011
|
-
|
|
2012
|
-
|
|
2013
|
-
|
|
2014
|
-
|
|
2015
|
-
|
|
1767
|
+
async build(context, constructs, outputDir, options) {
|
|
1768
|
+
const provider = options?.provider || "aws-lambda";
|
|
1769
|
+
const logger = console;
|
|
1770
|
+
const queueInfos = [];
|
|
1771
|
+
if (provider === "server") {
|
|
1772
|
+
await this.generateServerQueuesFile(outputDir, constructs);
|
|
1773
|
+
logger.log(`Generated server queues file with ${constructs.length} queues (polling mode)`);
|
|
1774
|
+
return queueInfos;
|
|
1775
|
+
}
|
|
1776
|
+
if (constructs.length === 0 || provider !== "aws-lambda") return queueInfos;
|
|
1777
|
+
const queuesDir = join(outputDir, "queues");
|
|
1778
|
+
await mkdir(queuesDir, { recursive: true });
|
|
1779
|
+
for (const { key, construct, path } of constructs) {
|
|
1780
|
+
const handlerFile = await this.generateQueueHandler(queuesDir, path.relative, key, context, construct.owner);
|
|
1781
|
+
queueInfos.push({
|
|
1782
|
+
name: construct.name,
|
|
1783
|
+
handler: relative(process.cwd(), handlerFile).replace(/\.ts$/, ".handler"),
|
|
1784
|
+
batchSize: construct.batchSize,
|
|
1785
|
+
fifo: construct.fifo,
|
|
1786
|
+
timeout: construct.timeout,
|
|
1787
|
+
environment: await construct.getEnvironment({ markOptional: context.markOptional }),
|
|
1788
|
+
dependencies: construct.constructs
|
|
2016
1789
|
});
|
|
2017
|
-
logger
|
|
1790
|
+
logger.log(`Generated queue handler: ${key}`);
|
|
1791
|
+
}
|
|
1792
|
+
return queueInfos;
|
|
1793
|
+
}
|
|
1794
|
+
async generateQueueHandler(outputDir, sourceFile, exportName, context, owner) {
|
|
1795
|
+
const handlerPath = join(outputDir, `${exportName}.ts`);
|
|
1796
|
+
const importPath = relative(dirname(handlerPath), sourceFile).replace(/\.ts$/, ".js");
|
|
1797
|
+
const runtime = runtimeFor(context, dirname(handlerPath), owner);
|
|
1798
|
+
const content = `import { AWSLambdaQueue } from '@geekmidas/constructs/aws';
|
|
1799
|
+
import { ${exportName} } from '${importPath}';
|
|
1800
|
+
${runtime.imports}
|
|
1801
|
+
${runtime.bindings}
|
|
1802
|
+
|
|
1803
|
+
const adapter = new AWSLambdaQueue(envParser, ${exportName});
|
|
1804
|
+
|
|
1805
|
+
export const handler = adapter.handler;
|
|
1806
|
+
`;
|
|
1807
|
+
await writeFile(handlerPath, content);
|
|
1808
|
+
return handlerPath;
|
|
1809
|
+
}
|
|
1810
|
+
async generateServerQueuesFile(outputDir, queues) {
|
|
1811
|
+
await mkdir(outputDir, { recursive: true });
|
|
1812
|
+
const queuesPath = join(outputDir, "queues.ts");
|
|
1813
|
+
if (queues.length === 0) {
|
|
1814
|
+
await writeFile(queuesPath, `/**
|
|
1815
|
+
* Generated queues setup — this app declares none.
|
|
1816
|
+
*/
|
|
1817
|
+
import type { EnvironmentParser } from '@geekmidas/envkit';
|
|
1818
|
+
import type { Logger } from '@geekmidas/logger';
|
|
1819
|
+
|
|
1820
|
+
export async function setupQueues(
|
|
1821
|
+
_envParser: EnvironmentParser<any>,
|
|
1822
|
+
_logger: Logger,
|
|
1823
|
+
): Promise<void> {}
|
|
1824
|
+
`);
|
|
1825
|
+
return queuesPath;
|
|
1826
|
+
}
|
|
1827
|
+
const importsByFile = /* @__PURE__ */ new Map();
|
|
1828
|
+
for (const { path, key } of queues) {
|
|
1829
|
+
const importPath = relative(dirname(queuesPath), path.relative).replace(/\.ts$/, ".js");
|
|
1830
|
+
if (!importsByFile.has(importPath)) importsByFile.set(importPath, []);
|
|
1831
|
+
importsByFile.get(importPath)?.push(key);
|
|
1832
|
+
}
|
|
1833
|
+
const content = `/**
|
|
1834
|
+
* Generated queue workers setup
|
|
1835
|
+
*
|
|
1836
|
+
* ⚠️ WARNING: This is for LOCAL DEVELOPMENT ONLY
|
|
1837
|
+
* This runs an in-process pg-boss poller alongside the HTTP server. Each queue
|
|
1838
|
+
* subscribes by its name on the shared event connection
|
|
1839
|
+
* (EVENT_SUBSCRIBER_CONNECTION_STRING), so producers using
|
|
1840
|
+
* <NAME>_PUBLISHER_CONNECTION_STRING (pgboss:// locally) reach it.
|
|
1841
|
+
*
|
|
1842
|
+
* For production, queues run as AWS Lambda with SQS event-source mappings.
|
|
1843
|
+
*/
|
|
1844
|
+
import type { EnvironmentParser } from '@geekmidas/envkit';
|
|
1845
|
+
import type { Logger } from '@geekmidas/logger';
|
|
1846
|
+
import { EventConnectionFactory, Subscriber } from '@geekmidas/events';
|
|
1847
|
+
import type { EventConnection, EventSubscriber } from '@geekmidas/events';
|
|
1848
|
+
import { ServiceDiscovery } from '@geekmidas/services';
|
|
1849
|
+
${Array.from(importsByFile.entries()).map(([importPath, exports]) => `import { ${exports.join(", ")} } from '${importPath}';`).join("\n")}
|
|
1850
|
+
|
|
1851
|
+
const queues = [
|
|
1852
|
+
${queues.map(({ key }) => key).join(",\n ")}
|
|
1853
|
+
];
|
|
1854
|
+
|
|
1855
|
+
const activeSubscribers: EventSubscriber<any>[] = [];
|
|
1856
|
+
|
|
1857
|
+
export async function setupQueues(
|
|
1858
|
+
envParser: EnvironmentParser<any>,
|
|
1859
|
+
logger: Logger,
|
|
1860
|
+
): Promise<void> {
|
|
1861
|
+
if (queues.length === 0) {
|
|
1862
|
+
return;
|
|
1863
|
+
}
|
|
1864
|
+
|
|
1865
|
+
logger.info('Setting up queue workers in polling mode (local development)');
|
|
1866
|
+
|
|
1867
|
+
const config = envParser.create((get) => ({
|
|
1868
|
+
connectionString: get('EVENT_SUBSCRIBER_CONNECTION_STRING').string(),
|
|
1869
|
+
})).parse();
|
|
1870
|
+
|
|
1871
|
+
const serviceDiscovery = ServiceDiscovery.getInstance(envParser);
|
|
1872
|
+
|
|
1873
|
+
let connection: EventConnection;
|
|
1874
|
+
try {
|
|
1875
|
+
connection = await EventConnectionFactory.fromConnectionString(config.connectionString);
|
|
1876
|
+
const connectionType = new URL(config.connectionString).protocol.replace(':', '');
|
|
1877
|
+
logger.info({ connectionType }, 'Created shared event connection for queues');
|
|
1878
|
+
} catch (error) {
|
|
1879
|
+
logger.error({ error }, 'Failed to create event connection for queues');
|
|
1880
|
+
return;
|
|
1881
|
+
}
|
|
1882
|
+
|
|
1883
|
+
for (const queue of queues) {
|
|
1884
|
+
try {
|
|
1885
|
+
const eventSubscriber = await Subscriber.fromConnection(connection);
|
|
1886
|
+
|
|
1887
|
+
const services = queue.services.length > 0
|
|
1888
|
+
? await serviceDiscovery.register(queue.services)
|
|
1889
|
+
: {};
|
|
1890
|
+
|
|
1891
|
+
// A queue subscribes to a single "type" — its own name.
|
|
1892
|
+
await eventSubscriber.subscribe([queue.name], async (message) => {
|
|
1893
|
+
try {
|
|
1894
|
+
const validation = await queue.messageSchema['~standard'].validate(message.payload);
|
|
1895
|
+
if (validation.issues) {
|
|
1896
|
+
logger.error({ issues: validation.issues, queue: queue.name }, 'Queue message failed validation');
|
|
1897
|
+
return;
|
|
1898
|
+
}
|
|
1899
|
+
|
|
1900
|
+
await queue.handler({
|
|
1901
|
+
messages: [validation.value],
|
|
1902
|
+
services: services,
|
|
1903
|
+
logger: queue.logger,
|
|
1904
|
+
});
|
|
1905
|
+
|
|
1906
|
+
logger.debug({ queue: queue.name }, 'Successfully processed queue message');
|
|
1907
|
+
} catch (error) {
|
|
1908
|
+
logger.error({ error, queue: queue.name }, 'Failed to process queue message');
|
|
1909
|
+
// Message will become visible again for retry.
|
|
1910
|
+
}
|
|
1911
|
+
});
|
|
1912
|
+
|
|
1913
|
+
activeSubscribers.push(eventSubscriber);
|
|
1914
|
+
logger.info({ queue: queue.name }, 'Queue worker started polling');
|
|
1915
|
+
} catch (error) {
|
|
1916
|
+
logger.error({ error, queue: queue.name }, 'Failed to setup queue worker');
|
|
1917
|
+
}
|
|
1918
|
+
}
|
|
1919
|
+
|
|
1920
|
+
const shutdown = () => {
|
|
1921
|
+
logger.info('Stopping all queue workers');
|
|
1922
|
+
for (const _ of activeSubscribers) {
|
|
1923
|
+
connection.stop();
|
|
1924
|
+
}
|
|
1925
|
+
};
|
|
1926
|
+
|
|
1927
|
+
process.on('SIGTERM', shutdown);
|
|
1928
|
+
process.on('SIGINT', shutdown);
|
|
1929
|
+
}
|
|
1930
|
+
`;
|
|
1931
|
+
await writeFile(queuesPath, content);
|
|
1932
|
+
return queuesPath;
|
|
1933
|
+
}
|
|
1934
|
+
};
|
|
1935
|
+
//#endregion
|
|
1936
|
+
//#region src/generators/SubscriberGenerator.ts
|
|
1937
|
+
var SubscriberGenerator = class extends ConstructGenerator {
|
|
1938
|
+
isConstruct(value) {
|
|
1939
|
+
return Subscriber.isSubscriber(value);
|
|
1940
|
+
}
|
|
1941
|
+
async build(context, constructs, outputDir, options) {
|
|
1942
|
+
const provider = options?.provider || "aws-lambda";
|
|
1943
|
+
const logger = console;
|
|
1944
|
+
const subscriberInfos = [];
|
|
1945
|
+
if (provider === "server") {
|
|
1946
|
+
await this.generateServerSubscribersFile(outputDir, constructs);
|
|
1947
|
+
logger.log(`Generated server subscribers file with ${constructs.length} subscribers (polling mode)`);
|
|
1948
|
+
return subscriberInfos;
|
|
2018
1949
|
}
|
|
2019
|
-
|
|
2020
|
-
|
|
2021
|
-
const
|
|
2022
|
-
|
|
2023
|
-
|
|
2024
|
-
|
|
2025
|
-
|
|
2026
|
-
|
|
2027
|
-
|
|
2028
|
-
|
|
2029
|
-
|
|
2030
|
-
|
|
2031
|
-
|
|
2032
|
-
|
|
2033
|
-
|
|
2034
|
-
|
|
2035
|
-
|
|
2036
|
-
|
|
2037
|
-
|
|
2038
|
-
|
|
2039
|
-
if (this.isRunning) {
|
|
2040
|
-
logger$11.log("");
|
|
2041
|
-
logger$11.log(` \x1b[32m✓ Ready\x1b[0m at \x1b[36mhttp://localhost:${this.port}\x1b[0m`);
|
|
2042
|
-
logger$11.log("");
|
|
1950
|
+
if (constructs.length === 0) return subscriberInfos;
|
|
1951
|
+
if (provider !== "aws-lambda") return subscriberInfos;
|
|
1952
|
+
const subscribersDir = join(outputDir, "subscribers");
|
|
1953
|
+
await mkdir(subscribersDir, { recursive: true });
|
|
1954
|
+
for (const { key, construct, path } of constructs) {
|
|
1955
|
+
const handlerFile = await this.generateSubscriberHandler(subscribersDir, path.relative, key, construct, context, construct.owner);
|
|
1956
|
+
subscriberInfos.push({
|
|
1957
|
+
name: key,
|
|
1958
|
+
handler: relative(process.cwd(), handlerFile).replace(/\.ts$/, ".handler"),
|
|
1959
|
+
subscribedEvents: construct.subscribedEvents || [],
|
|
1960
|
+
...construct.topicName ? {
|
|
1961
|
+
transport: "topic",
|
|
1962
|
+
topic: construct.topicName
|
|
1963
|
+
} : {},
|
|
1964
|
+
timeout: construct.timeout,
|
|
1965
|
+
memorySize: construct.memorySize,
|
|
1966
|
+
environment: await construct.getEnvironment({ markOptional: context.markOptional }),
|
|
1967
|
+
dependencies: construct.constructs
|
|
1968
|
+
});
|
|
1969
|
+
logger.log(`Generated subscriber handler: ${key}`);
|
|
2043
1970
|
}
|
|
1971
|
+
return subscriberInfos;
|
|
2044
1972
|
}
|
|
2045
|
-
async
|
|
2046
|
-
|
|
2047
|
-
|
|
2048
|
-
|
|
2049
|
-
|
|
2050
|
-
|
|
2051
|
-
|
|
2052
|
-
|
|
1973
|
+
async generateSubscriberHandler(outputDir, sourceFile, exportName, _subscriber, context, owner) {
|
|
1974
|
+
const handlerFileName = `${exportName}.ts`;
|
|
1975
|
+
const handlerPath = join(outputDir, handlerFileName);
|
|
1976
|
+
const importPath = relative(dirname(handlerPath), sourceFile).replace(/\.ts$/, ".js");
|
|
1977
|
+
const runtime = runtimeFor(context, dirname(handlerPath), owner);
|
|
1978
|
+
const content = `import { AWSLambdaSubscriber } from '@geekmidas/constructs/aws';
|
|
1979
|
+
import { ${exportName} } from '${importPath}';
|
|
1980
|
+
${runtime.imports}
|
|
1981
|
+
${runtime.bindings}
|
|
1982
|
+
|
|
1983
|
+
const adapter = new AWSLambdaSubscriber(envParser, ${exportName});
|
|
1984
|
+
|
|
1985
|
+
export const handler = adapter.handler;
|
|
1986
|
+
`;
|
|
1987
|
+
await writeFile(handlerPath, content);
|
|
1988
|
+
return handlerPath;
|
|
2053
1989
|
}
|
|
2054
|
-
|
|
2055
|
-
|
|
2056
|
-
|
|
2057
|
-
|
|
2058
|
-
|
|
2059
|
-
|
|
2060
|
-
|
|
2061
|
-
|
|
2062
|
-
|
|
2063
|
-
|
|
2064
|
-
|
|
2065
|
-
|
|
1990
|
+
async generateServerSubscribersFile(outputDir, subscribers) {
|
|
1991
|
+
await mkdir(outputDir, { recursive: true });
|
|
1992
|
+
const subscribersPath = join(outputDir, "subscribers.ts");
|
|
1993
|
+
if (subscribers.length === 0) {
|
|
1994
|
+
await writeFile(subscribersPath, `/**
|
|
1995
|
+
* Generated subscribers setup — this app declares none.
|
|
1996
|
+
*/
|
|
1997
|
+
import type { EnvironmentParser } from '@geekmidas/envkit';
|
|
1998
|
+
import type { Logger } from '@geekmidas/logger';
|
|
1999
|
+
|
|
2000
|
+
export async function setupSubscribers(
|
|
2001
|
+
_envParser: EnvironmentParser<any>,
|
|
2002
|
+
_logger: Logger,
|
|
2003
|
+
): Promise<void> {}
|
|
2004
|
+
`);
|
|
2005
|
+
return subscribersPath;
|
|
2066
2006
|
}
|
|
2067
|
-
|
|
2068
|
-
}
|
|
2069
|
-
|
|
2070
|
-
|
|
2071
|
-
|
|
2072
|
-
|
|
2073
|
-
|
|
2074
|
-
|
|
2075
|
-
|
|
2076
|
-
|
|
2077
|
-
|
|
2078
|
-
|
|
2079
|
-
*
|
|
2080
|
-
*
|
|
2007
|
+
const importsByFile = /* @__PURE__ */ new Map();
|
|
2008
|
+
for (const { path, key } of subscribers) {
|
|
2009
|
+
const importPath = relative(dirname(subscribersPath), path.relative).replace(/\.ts$/, ".js");
|
|
2010
|
+
if (!importsByFile.has(importPath)) importsByFile.set(importPath, []);
|
|
2011
|
+
importsByFile.get(importPath)?.push(key);
|
|
2012
|
+
}
|
|
2013
|
+
const content = `/**
|
|
2014
|
+
* Generated subscribers setup
|
|
2015
|
+
*
|
|
2016
|
+
* ⚠️ WARNING: This is for LOCAL DEVELOPMENT ONLY
|
|
2017
|
+
* This uses event polling which is not suitable for production.
|
|
2018
|
+
*
|
|
2019
|
+
* For production, use AWS Lambda with SQS/SNS event source mappings.
|
|
2020
|
+
* Lambda automatically:
|
|
2021
|
+
* - Scales based on queue depth
|
|
2022
|
+
* - Handles batch processing and retries
|
|
2023
|
+
* - Manages dead letter queues
|
|
2024
|
+
* - Provides better cost optimization
|
|
2025
|
+
*
|
|
2026
|
+
* This polling implementation is useful for:
|
|
2027
|
+
* - Local development and testing
|
|
2028
|
+
* - Understanding event flow without Lambda deployment
|
|
2029
|
+
*
|
|
2030
|
+
* Supported connection strings:
|
|
2031
|
+
* - sqs://region/account-id/queue-name (SQS queue)
|
|
2032
|
+
* - sns://region/account-id/topic-name (SNS topic)
|
|
2033
|
+
* - rabbitmq://host:port/queue-name (RabbitMQ)
|
|
2034
|
+
* - pgboss://user:pass@host:port/database (pg-boss / PostgreSQL)
|
|
2035
|
+
* - basic://in-memory (In-memory for testing)
|
|
2081
2036
|
*/
|
|
2082
|
-
|
|
2037
|
+
import type { EnvironmentParser } from '@geekmidas/envkit';
|
|
2038
|
+
import type { Logger } from '@geekmidas/logger';
|
|
2039
|
+
import { EventConnectionFactory, Subscriber } from '@geekmidas/events';
|
|
2040
|
+
import type { EventConnection, EventSubscriber } from '@geekmidas/events';
|
|
2041
|
+
import { ServiceDiscovery } from '@geekmidas/services';
|
|
2042
|
+
${Array.from(importsByFile.entries()).map(([importPath, exports]) => `import { ${exports.join(", ")} } from '${importPath}';`).join("\n")}
|
|
2083
2043
|
|
|
2084
|
-
|
|
2085
|
-
|
|
2086
|
-
|
|
2087
|
-
const __secrets = JSON.parse(readFileSync(secretsPath, 'utf-8'));
|
|
2088
|
-
globalThis.__gkm_credentials__ = __secrets;
|
|
2089
|
-
Object.assign(process.env, __secrets);
|
|
2090
|
-
}
|
|
2044
|
+
const subscribers = [
|
|
2045
|
+
${subscribers.map(({ key }) => key).join(",\n ")}
|
|
2046
|
+
];
|
|
2091
2047
|
|
|
2092
|
-
|
|
2093
|
-
const port = process.argv.includes('--port')
|
|
2094
|
-
? Number.parseInt(process.argv[process.argv.indexOf('--port') + 1])
|
|
2095
|
-
: 3000;
|
|
2048
|
+
const activeSubscribers: EventSubscriber<any>[] = [];
|
|
2096
2049
|
|
|
2097
|
-
|
|
2098
|
-
|
|
2050
|
+
export async function setupSubscribers(
|
|
2051
|
+
envParser: EnvironmentParser<any>,
|
|
2052
|
+
logger: Logger,
|
|
2053
|
+
): Promise<void> {
|
|
2054
|
+
if (subscribers.length === 0) {
|
|
2055
|
+
return;
|
|
2056
|
+
}
|
|
2099
2057
|
|
|
2100
|
-
|
|
2101
|
-
const { app, start } = await createApp(undefined, ${enableOpenApi});
|
|
2058
|
+
logger.info('Setting up subscribers in polling mode (local development)');
|
|
2102
2059
|
|
|
2103
|
-
|
|
2104
|
-
|
|
2105
|
-
|
|
2106
|
-
|
|
2107
|
-
|
|
2108
|
-
|
|
2109
|
-
|
|
2110
|
-
|
|
2111
|
-
|
|
2112
|
-
|
|
2113
|
-
|
|
2114
|
-
|
|
2115
|
-
|
|
2116
|
-
|
|
2117
|
-
|
|
2118
|
-
|
|
2119
|
-
|
|
2120
|
-
|
|
2121
|
-
|
|
2122
|
-
|
|
2123
|
-
|
|
2124
|
-
|
|
2125
|
-
|
|
2126
|
-
|
|
2060
|
+
const config = envParser.create((get) => ({
|
|
2061
|
+
connectionString: get('EVENT_SUBSCRIBER_CONNECTION_STRING').string(),
|
|
2062
|
+
})).parse();
|
|
2063
|
+
|
|
2064
|
+
const serviceDiscovery = ServiceDiscovery.getInstance(envParser);
|
|
2065
|
+
|
|
2066
|
+
// Create connection once, outside the loop (more efficient)
|
|
2067
|
+
// EventConnectionFactory automatically determines the right connection type
|
|
2068
|
+
let connection: EventConnection;
|
|
2069
|
+
try {
|
|
2070
|
+
connection = await EventConnectionFactory.fromConnectionString(config.connectionString);
|
|
2071
|
+
|
|
2072
|
+
const connectionType = new URL(config.connectionString).protocol.replace(':', '');
|
|
2073
|
+
logger.info({ connectionType }, 'Created shared event connection');
|
|
2074
|
+
} catch (error) {
|
|
2075
|
+
logger.error({ error }, 'Failed to create event connection');
|
|
2076
|
+
return;
|
|
2077
|
+
}
|
|
2078
|
+
|
|
2079
|
+
for (const subscriber of subscribers) {
|
|
2080
|
+
try {
|
|
2081
|
+
// Create subscriber from shared connection
|
|
2082
|
+
const eventSubscriber = await Subscriber.fromConnection(connection);
|
|
2083
|
+
|
|
2084
|
+
// Register services
|
|
2085
|
+
const services = subscriber.services.length > 0
|
|
2086
|
+
? await serviceDiscovery.register(subscriber.services)
|
|
2087
|
+
: {};
|
|
2088
|
+
|
|
2089
|
+
// Subscribe to events
|
|
2090
|
+
const subscribedEvents = subscriber.subscribedEvents || [];
|
|
2091
|
+
|
|
2092
|
+
if (subscribedEvents.length === 0) {
|
|
2093
|
+
logger.warn({ subscriber: subscriber.constructor.name }, 'Subscriber has no subscribed events, skipping');
|
|
2094
|
+
continue;
|
|
2095
|
+
}
|
|
2096
|
+
|
|
2097
|
+
await eventSubscriber.subscribe(subscribedEvents, async (event) => {
|
|
2098
|
+
try {
|
|
2099
|
+
// Process single event (batch of 1)
|
|
2100
|
+
await subscriber.handler({
|
|
2101
|
+
events: [event],
|
|
2102
|
+
services: services as any,
|
|
2103
|
+
logger: subscriber.logger,
|
|
2104
|
+
});
|
|
2105
|
+
|
|
2106
|
+
logger.debug({ eventType: event.type }, 'Successfully processed event');
|
|
2107
|
+
} catch (error) {
|
|
2108
|
+
logger.error({ error, event }, 'Failed to process event');
|
|
2109
|
+
// Event will become visible again for retry
|
|
2110
|
+
}
|
|
2111
|
+
});
|
|
2112
|
+
|
|
2113
|
+
activeSubscribers.push(eventSubscriber);
|
|
2114
|
+
|
|
2115
|
+
logger.info(
|
|
2116
|
+
{
|
|
2117
|
+
events: subscribedEvents,
|
|
2118
|
+
},
|
|
2119
|
+
'Subscriber started polling'
|
|
2120
|
+
);
|
|
2121
|
+
} catch (error) {
|
|
2122
|
+
logger.error({ error, subscriber: subscriber.constructor.name }, 'Failed to setup subscriber');
|
|
2123
|
+
}
|
|
2124
|
+
}
|
|
2125
|
+
|
|
2126
|
+
// Setup graceful shutdown
|
|
2127
|
+
const shutdown = () => {
|
|
2128
|
+
logger.info('Stopping all subscribers');
|
|
2129
|
+
for (const eventSubscriber of activeSubscribers) {
|
|
2130
|
+
connection.stop();
|
|
2131
|
+
}
|
|
2132
|
+
};
|
|
2133
|
+
|
|
2134
|
+
process.on('SIGTERM', shutdown);
|
|
2135
|
+
process.on('SIGINT', shutdown);
|
|
2127
2136
|
}
|
|
2128
|
-
|
|
2129
|
-
|
|
2130
|
-
|
|
2131
|
-
portExplicit;
|
|
2132
|
-
enableOpenApi;
|
|
2133
|
-
telescope;
|
|
2134
|
-
studio;
|
|
2135
|
-
runtime;
|
|
2136
|
-
appRoot;
|
|
2137
|
-
secretsJsonPath;
|
|
2138
|
-
serverProcess = null;
|
|
2139
|
-
isRunning = false;
|
|
2140
|
-
actualPort;
|
|
2141
|
-
startTime = Date.now();
|
|
2142
|
-
constructor(provider, requestedPort, portExplicit, enableOpenApi, telescope, studio, runtime = "node", appRoot = process.cwd(), secretsJsonPath) {
|
|
2143
|
-
this.provider = provider;
|
|
2144
|
-
this.requestedPort = requestedPort;
|
|
2145
|
-
this.portExplicit = portExplicit;
|
|
2146
|
-
this.enableOpenApi = enableOpenApi;
|
|
2147
|
-
this.telescope = telescope;
|
|
2148
|
-
this.studio = studio;
|
|
2149
|
-
this.runtime = runtime;
|
|
2150
|
-
this.appRoot = appRoot;
|
|
2151
|
-
this.secretsJsonPath = secretsJsonPath;
|
|
2152
|
-
this.actualPort = requestedPort;
|
|
2153
|
-
}
|
|
2154
|
-
async start() {
|
|
2155
|
-
this.startTime = Date.now();
|
|
2156
|
-
if (this.isRunning) await this.stop();
|
|
2157
|
-
if (this.portExplicit) {
|
|
2158
|
-
if (!await isPortAvailable(this.requestedPort)) throw new Error(`Port ${this.requestedPort} is already in use. Either stop the process using that port or omit -p/--port to auto-select an available port.`);
|
|
2159
|
-
this.actualPort = this.requestedPort;
|
|
2160
|
-
} else {
|
|
2161
|
-
this.actualPort = await findAvailablePort(this.requestedPort);
|
|
2162
|
-
if (this.actualPort !== this.requestedPort) logger$11.log(`ℹ️ Port ${this.requestedPort} was in use, using port ${this.actualPort} instead`);
|
|
2163
|
-
}
|
|
2164
|
-
const serverEntryPath = join(this.appRoot, ".gkm", this.provider, "server.ts");
|
|
2165
|
-
await this.createServerEntry();
|
|
2166
|
-
logger$11.log(`\n⏳ Starting server...`);
|
|
2167
|
-
this.serverProcess = spawn("npx", [
|
|
2168
|
-
"tsx",
|
|
2169
|
-
serverEntryPath,
|
|
2170
|
-
"--port",
|
|
2171
|
-
this.actualPort.toString()
|
|
2172
|
-
], {
|
|
2173
|
-
stdio: "inherit",
|
|
2174
|
-
env: {
|
|
2175
|
-
...process.env,
|
|
2176
|
-
NODE_ENV: "development"
|
|
2177
|
-
},
|
|
2178
|
-
detached: true
|
|
2179
|
-
});
|
|
2180
|
-
this.isRunning = true;
|
|
2181
|
-
this.serverProcess.on("error", (error) => {
|
|
2182
|
-
logger$11.error("❌ Server error:", error);
|
|
2183
|
-
});
|
|
2184
|
-
this.serverProcess.on("exit", (code, signal) => {
|
|
2185
|
-
if (code !== null && code !== 0 && signal !== "SIGTERM") logger$11.error(`❌ Server exited with code ${code}`);
|
|
2186
|
-
this.isRunning = false;
|
|
2187
|
-
});
|
|
2188
|
-
await new Promise((resolve) => setTimeout(resolve, 1e3));
|
|
2189
|
-
if (this.isRunning) {
|
|
2190
|
-
const base = `http://localhost:${this.actualPort}`;
|
|
2191
|
-
const lines = [` Local: ${base}`];
|
|
2192
|
-
if (this.enableOpenApi) lines.push(` API Docs: ${base}/__docs`);
|
|
2193
|
-
if (this.telescope) lines.push(` Telescope: ${base}${this.telescope.path}`);
|
|
2194
|
-
if (this.studio) lines.push(` Studio: ${base}${this.studio.path}`);
|
|
2195
|
-
const maxLen = Math.max(...lines.map((l) => l.length));
|
|
2196
|
-
const pad = (s) => s.padEnd(maxLen);
|
|
2197
|
-
const border = "─".repeat(maxLen + 2);
|
|
2198
|
-
logger$11.log("");
|
|
2199
|
-
logger$11.log(` \x1b[32m✓ Ready\x1b[0m in ${((Date.now() - this.startTime) / 1e3).toFixed(1)}s`);
|
|
2200
|
-
logger$11.log("");
|
|
2201
|
-
logger$11.log(` ┌${border}┐`);
|
|
2202
|
-
for (const line of lines) logger$11.log(` │ ${pad(line)} │`);
|
|
2203
|
-
logger$11.log(` └${border}┘`);
|
|
2204
|
-
logger$11.log("");
|
|
2205
|
-
}
|
|
2206
|
-
}
|
|
2207
|
-
async stop() {
|
|
2208
|
-
const port = this.actualPort;
|
|
2209
|
-
if (this.serverProcess && this.isRunning) {
|
|
2210
|
-
const pid = this.serverProcess.pid;
|
|
2211
|
-
if (pid) try {
|
|
2212
|
-
process.kill(-pid, "SIGKILL");
|
|
2213
|
-
} catch {
|
|
2214
|
-
try {
|
|
2215
|
-
process.kill(pid, "SIGKILL");
|
|
2216
|
-
} catch {}
|
|
2217
|
-
}
|
|
2218
|
-
this.serverProcess = null;
|
|
2219
|
-
this.isRunning = false;
|
|
2220
|
-
}
|
|
2221
|
-
this.killProcessesOnPort(port);
|
|
2222
|
-
}
|
|
2223
|
-
killProcessesOnPort(port) {
|
|
2224
|
-
try {
|
|
2225
|
-
execSync(`lsof -ti tcp:${port} | xargs kill -9 2>/dev/null || true`, { stdio: "ignore" });
|
|
2226
|
-
} catch {}
|
|
2137
|
+
`;
|
|
2138
|
+
await writeFile(subscribersPath, content);
|
|
2139
|
+
return subscribersPath;
|
|
2227
2140
|
}
|
|
2228
|
-
|
|
2229
|
-
|
|
2230
|
-
|
|
2231
|
-
|
|
2232
|
-
|
|
2233
|
-
|
|
2234
|
-
|
|
2235
|
-
|
|
2236
|
-
|
|
2237
|
-
|
|
2238
|
-
|
|
2141
|
+
};
|
|
2142
|
+
//#endregion
|
|
2143
|
+
//#region src/generators/TopicGenerator.ts
|
|
2144
|
+
/**
|
|
2145
|
+
* Discovers `t` topics into `manifest.topics`. A topic is a *resource*, not a
|
|
2146
|
+
* function — it has no handler to generate. Producers reach it via its derived
|
|
2147
|
+
* publisher (`topic.publisher`, whose connection string is sniffed onto the
|
|
2148
|
+
* producing construct) and subscribers bind via `s.topic(topic)`; this generator
|
|
2149
|
+
* only records the topic + its event contract so infra can provision the SNS
|
|
2150
|
+
* topic. Identical output for every provider (locally pg-boss routes by event
|
|
2151
|
+
* name, so there's nothing to run).
|
|
2152
|
+
*/
|
|
2153
|
+
var TopicGenerator = class extends ConstructGenerator {
|
|
2154
|
+
isConstruct(value) {
|
|
2155
|
+
return Topic.isTopic(value);
|
|
2239
2156
|
}
|
|
2240
|
-
async
|
|
2241
|
-
const
|
|
2242
|
-
|
|
2243
|
-
|
|
2244
|
-
|
|
2245
|
-
enableOpenApi: this.enableOpenApi
|
|
2157
|
+
async build(_context, constructs, _outputDir, _options) {
|
|
2158
|
+
const logger = console;
|
|
2159
|
+
const topicInfos = constructs.map(({ construct }) => ({
|
|
2160
|
+
name: construct.name,
|
|
2161
|
+
events: construct.eventTypes
|
|
2246
2162
|
}));
|
|
2163
|
+
for (const topic of topicInfos) logger.log(`Discovered topic: ${topic.name}`);
|
|
2164
|
+
return topicInfos;
|
|
2247
2165
|
}
|
|
2248
2166
|
};
|
|
2249
2167
|
//#endregion
|
|
@@ -2457,6 +2375,76 @@ function mapTopicMetadata(topics) {
|
|
|
2457
2375
|
for (const [partition, partitionTopics] of Object.entries(topics)) result[partition] = partitionTopics.map(mapFn);
|
|
2458
2376
|
return result;
|
|
2459
2377
|
}
|
|
2378
|
+
//#endregion
|
|
2379
|
+
//#region src/build/owners.ts
|
|
2380
|
+
/**
|
|
2381
|
+
* What a generated entry imports its runtime from, read off the discovered
|
|
2382
|
+
* constructs: the surface it serves, every construct a runnable can be built
|
|
2383
|
+
* from, and the database Studio browses.
|
|
2384
|
+
*
|
|
2385
|
+
* `gkm build` and `gkm dev` both write entries that import the surface for its
|
|
2386
|
+
* logger and environment parser, so both ask here. A dev server that skipped it
|
|
2387
|
+
* had nothing to import them from.
|
|
2388
|
+
*/
|
|
2389
|
+
function ownersContext(options) {
|
|
2390
|
+
const { declared, sources, workspaceRoot, appRoot, studio } = options;
|
|
2391
|
+
const surfaces = restApis(declared);
|
|
2392
|
+
const primary = servedSurface(declared, workspaceRoot, appRoot) ?? surfaces.find((d) => d.endpoints.length === 0) ?? surfaces[0];
|
|
2393
|
+
const browsable = Object.entries(declared).find(([, d]) => d.kind === "database");
|
|
2394
|
+
const browsableSource = browsable ? sources[browsable[0]] : void 0;
|
|
2395
|
+
const owners = {};
|
|
2396
|
+
for (const [id, declaration] of Object.entries(declared)) {
|
|
2397
|
+
if (declaration.kind !== "rest-api" && declaration.kind !== "worker") continue;
|
|
2398
|
+
const source = sources[id];
|
|
2399
|
+
if (!source) continue;
|
|
2400
|
+
owners[id] = {
|
|
2401
|
+
specifier: source.file,
|
|
2402
|
+
exportName: source.exportName
|
|
2403
|
+
};
|
|
2404
|
+
}
|
|
2405
|
+
const primarySource = primary ? sources[primary.id] : void 0;
|
|
2406
|
+
return {
|
|
2407
|
+
owners,
|
|
2408
|
+
...primary ? { surface: {
|
|
2409
|
+
id: primary.id,
|
|
2410
|
+
trustedOriginsKey: provideKey(primary.id, "trustedOrigins"),
|
|
2411
|
+
...primary.cors ? { cors: primary.cors } : {},
|
|
2412
|
+
...primarySource ? { module: {
|
|
2413
|
+
specifier: primarySource.file,
|
|
2414
|
+
exportName: primarySource.exportName
|
|
2415
|
+
} } : {}
|
|
2416
|
+
} } : {},
|
|
2417
|
+
studio: studio && browsableSource ? {
|
|
2418
|
+
...studio,
|
|
2419
|
+
database: {
|
|
2420
|
+
specifier: browsableSource.file,
|
|
2421
|
+
exportName: browsableSource.exportName
|
|
2422
|
+
}
|
|
2423
|
+
} : studio
|
|
2424
|
+
};
|
|
2425
|
+
}
|
|
2426
|
+
/**
|
|
2427
|
+
* The endpoints one surface serves.
|
|
2428
|
+
*
|
|
2429
|
+
* One glob finds every surface's endpoints, wherever their files live. A build
|
|
2430
|
+
* keeps the ones built from the surface it serves; one built from no surface at
|
|
2431
|
+
* all has nowhere else to go.
|
|
2432
|
+
*/
|
|
2433
|
+
function servedBy(endpoints, surface) {
|
|
2434
|
+
if (!surface) return endpoints;
|
|
2435
|
+
return endpoints.filter(({ construct }) => !construct.surface || construct.surface.id === surface.id);
|
|
2436
|
+
}
|
|
2437
|
+
function restApis(declared) {
|
|
2438
|
+
return Object.values(declared).filter((d) => d.kind === "rest-api");
|
|
2439
|
+
}
|
|
2440
|
+
/**
|
|
2441
|
+
* The surface whose declared `path` is the directory being built — asked of
|
|
2442
|
+
* every surface, because a workspace has several and each app's build serves
|
|
2443
|
+
* exactly one.
|
|
2444
|
+
*/
|
|
2445
|
+
function servedSurface(declared, workspaceRoot, appRoot) {
|
|
2446
|
+
return restApis(declared).find((d) => resolve(workspaceRoot, d.path) === resolve(appRoot));
|
|
2447
|
+
}
|
|
2460
2448
|
/**
|
|
2461
2449
|
* Check if any construct across the given arrays has a non-undefined partition.
|
|
2462
2450
|
* When true, the manifest should use the partitioned shape for that construct type.
|
|
@@ -2479,7 +2467,29 @@ function groupInfosByPartition(infos, constructs) {
|
|
|
2479
2467
|
return groups;
|
|
2480
2468
|
}
|
|
2481
2469
|
//#endregion
|
|
2482
|
-
//#region src/build/
|
|
2470
|
+
//#region src/build/surfaceEntry.ts
|
|
2471
|
+
/** Whether a construct serves itself, asked of the construct. */
|
|
2472
|
+
function servesItself(construct) {
|
|
2473
|
+
return typeof construct?.server === "function";
|
|
2474
|
+
}
|
|
2475
|
+
/**
|
|
2476
|
+
* The surface this app serves, when that surface serves itself.
|
|
2477
|
+
*
|
|
2478
|
+
* An auth server's routes are a wildcard the construct mounts, so a glob finds
|
|
2479
|
+
* nothing and the entry only has to start it. That used to be inferred —
|
|
2480
|
+
* "nothing found, and the surface declares routes" — which is a guess about
|
|
2481
|
+
* the construct from the outside. The construct can simply be asked.
|
|
2482
|
+
*/
|
|
2483
|
+
function selfServingSurface(options) {
|
|
2484
|
+
const { declared, sources, workspaceRoot, appRoot } = options;
|
|
2485
|
+
const served = servedSurface(declared, workspaceRoot, appRoot);
|
|
2486
|
+
const source = served ? sources[served.id] : void 0;
|
|
2487
|
+
if (!served || !source || !servesItself(source.construct)) return void 0;
|
|
2488
|
+
return {
|
|
2489
|
+
id: served.id,
|
|
2490
|
+
source
|
|
2491
|
+
};
|
|
2492
|
+
}
|
|
2483
2493
|
/**
|
|
2484
2494
|
* The entry for a surface that serves itself.
|
|
2485
2495
|
*
|
|
@@ -2513,6 +2523,8 @@ export const { app } = await surface.server({ envParser, context: snifferContext
|
|
|
2513
2523
|
export default app;
|
|
2514
2524
|
`);
|
|
2515
2525
|
}
|
|
2526
|
+
//#endregion
|
|
2527
|
+
//#region src/build/index.ts
|
|
2516
2528
|
const logger$9 = console;
|
|
2517
2529
|
/**
|
|
2518
2530
|
* What a build run at the workspace root reads.
|
|
@@ -2556,18 +2568,56 @@ async function buildCommand(options) {
|
|
|
2556
2568
|
if (studio) logger$9.log(`🗄️ Studio enabled at ${studio.path}`);
|
|
2557
2569
|
const hooks = normalizeHooksConfig(config.hooks);
|
|
2558
2570
|
if (hooks) logger$9.log(`🪝 Server hooks enabled`);
|
|
2571
|
+
return buildApp({
|
|
2572
|
+
config,
|
|
2573
|
+
workspaceRoot: loadedConfig.workspace.root,
|
|
2574
|
+
appRoot: process.cwd(),
|
|
2575
|
+
providers: resolved.providers,
|
|
2576
|
+
enableOpenApi: resolved.enableOpenApi,
|
|
2577
|
+
cacheBackend,
|
|
2578
|
+
production,
|
|
2579
|
+
telescope,
|
|
2580
|
+
studio,
|
|
2581
|
+
hooks,
|
|
2582
|
+
markOptional: options.markOptional ?? false,
|
|
2583
|
+
skipBundle: options.skipBundle ?? false,
|
|
2584
|
+
stage: options.stage
|
|
2585
|
+
});
|
|
2586
|
+
}
|
|
2587
|
+
/**
|
|
2588
|
+
* Turn one app's constructs into its generated entry.
|
|
2589
|
+
*
|
|
2590
|
+
* `gkm build` and `gkm dev` both run this. They used to be two copies of it,
|
|
2591
|
+
* and every time the build learned something about constructs — that the
|
|
2592
|
+
* entry takes its logger from the surface, that an auth server serves itself —
|
|
2593
|
+
* dev did not, and failed on exactly the apps the build had learned to handle.
|
|
2594
|
+
*/
|
|
2595
|
+
async function buildApp(input) {
|
|
2596
|
+
const { config, workspaceRoot, appRoot, providers, enableOpenApi, cacheBackend, production, telescope, studio, hooks, bustCache = false } = input;
|
|
2559
2597
|
const constructGlobs = typeof config.constructs === "string" || Array.isArray(config.constructs) ? config.constructs : void 0;
|
|
2560
2598
|
const constructSources = {};
|
|
2561
2599
|
const declared = constructGlobs ? await discover({
|
|
2562
2600
|
patterns: constructGlobs,
|
|
2563
|
-
cwd:
|
|
2601
|
+
cwd: appRoot,
|
|
2602
|
+
bustCache,
|
|
2564
2603
|
sources: constructSources
|
|
2565
2604
|
}) : {};
|
|
2605
|
+
const selfServing = selfServingSurface({
|
|
2606
|
+
declared,
|
|
2607
|
+
sources: constructSources,
|
|
2608
|
+
workspaceRoot,
|
|
2609
|
+
appRoot
|
|
2610
|
+
});
|
|
2611
|
+
if (selfServing) {
|
|
2612
|
+
await writeSurfaceEntry(join(appRoot, ".gkm", "server"), selfServing.source);
|
|
2613
|
+
logger$9.log(`Generated a server for ${selfServing.id} from its own declaration`);
|
|
2614
|
+
return { selfServing: selfServing.id };
|
|
2615
|
+
}
|
|
2566
2616
|
const derived = ownersContext({
|
|
2567
2617
|
declared,
|
|
2568
2618
|
sources: constructSources,
|
|
2569
|
-
workspaceRoot
|
|
2570
|
-
appRoot
|
|
2619
|
+
workspaceRoot,
|
|
2620
|
+
appRoot,
|
|
2571
2621
|
studio
|
|
2572
2622
|
});
|
|
2573
2623
|
const buildContext = {
|
|
@@ -2579,10 +2629,10 @@ async function buildCommand(options) {
|
|
|
2579
2629
|
cacheBackend,
|
|
2580
2630
|
emailBackend: "ses",
|
|
2581
2631
|
storageDrivers: driversFor({
|
|
2582
|
-
appRoot
|
|
2632
|
+
appRoot,
|
|
2583
2633
|
cache: cacheBackendsIn(declared, cacheBackend)
|
|
2584
2634
|
}),
|
|
2585
|
-
markOptional:
|
|
2635
|
+
markOptional: input.markOptional ?? false
|
|
2586
2636
|
};
|
|
2587
2637
|
const endpointGenerator = new EndpointGenerator();
|
|
2588
2638
|
const functionGenerator = new FunctionGenerator();
|
|
@@ -2592,12 +2642,12 @@ async function buildCommand(options) {
|
|
|
2592
2642
|
const topicGenerator = new TopicGenerator();
|
|
2593
2643
|
const code = constructGlobs;
|
|
2594
2644
|
const [loadedEndpoints, allFunctions, allCrons, allSubscribers, allQueues, allTopics] = await Promise.all([
|
|
2595
|
-
endpointGenerator.load(code),
|
|
2596
|
-
functionGenerator.load(code),
|
|
2597
|
-
cronGenerator.load(code),
|
|
2598
|
-
subscriberGenerator.load(code),
|
|
2599
|
-
queueGenerator.load(code),
|
|
2600
|
-
topicGenerator.load(code)
|
|
2645
|
+
endpointGenerator.load(code, appRoot, bustCache),
|
|
2646
|
+
functionGenerator.load(code, appRoot, bustCache),
|
|
2647
|
+
cronGenerator.load(code, appRoot, bustCache),
|
|
2648
|
+
subscriberGenerator.load(code, appRoot, bustCache),
|
|
2649
|
+
queueGenerator.load(code, appRoot, bustCache),
|
|
2650
|
+
topicGenerator.load(code, appRoot, bustCache)
|
|
2601
2651
|
]);
|
|
2602
2652
|
const allEndpoints = servedBy(loadedEndpoints, derived.surface);
|
|
2603
2653
|
logger$9.log(`Found ${allEndpoints.length} endpoints`);
|
|
@@ -2606,30 +2656,23 @@ async function buildCommand(options) {
|
|
|
2606
2656
|
logger$9.log(`Found ${allSubscribers.length} subscribers`);
|
|
2607
2657
|
logger$9.log(`Found ${allQueues.length} queues`);
|
|
2608
2658
|
logger$9.log(`Found ${allTopics.length} topics`);
|
|
2609
|
-
if (allEndpoints.length === 0 && allFunctions.length === 0 && allCrons.length === 0 && allSubscribers.length === 0 && allQueues.length === 0 && allTopics.length === 0) {
|
|
2610
|
-
const served = servedSurface(declared, loadedConfig.workspace.root, process.cwd());
|
|
2611
|
-
const selfServing = served && served.endpoints.length > 0 && constructSources[served.id] !== void 0 ? [served.id, served] : void 0;
|
|
2612
|
-
if (selfServing) {
|
|
2613
|
-
const [id] = selfServing;
|
|
2614
|
-
await writeSurfaceEntry(join(process.cwd(), ".gkm", "server"), constructSources[id]);
|
|
2615
|
-
logger$9.log(`Generated a server for ${id} from its own declaration`);
|
|
2616
|
-
return {};
|
|
2617
|
-
}
|
|
2659
|
+
if (!input.serveEmpty && allEndpoints.length === 0 && allFunctions.length === 0 && allCrons.length === 0 && allSubscribers.length === 0 && allQueues.length === 0 && allTopics.length === 0) {
|
|
2618
2660
|
logger$9.log("No endpoints, functions, crons, subscribers, queues, or topics found to process");
|
|
2619
2661
|
return {};
|
|
2620
2662
|
}
|
|
2621
|
-
const rootOutputDir = join(
|
|
2663
|
+
const rootOutputDir = join(appRoot, ".gkm");
|
|
2622
2664
|
await mkdir(rootOutputDir, { recursive: true });
|
|
2623
2665
|
let result = {};
|
|
2624
|
-
for (const provider of
|
|
2625
|
-
const providerResult = await buildForProvider(provider, buildContext,
|
|
2666
|
+
for (const provider of providers) {
|
|
2667
|
+
const providerResult = await buildForProvider(provider, buildContext, appRoot, declared, endpointGenerator, functionGenerator, cronGenerator, subscriberGenerator, queueGenerator, topicGenerator, allEndpoints, allFunctions, allCrons, allSubscribers, allQueues, allTopics, enableOpenApi, input.skipBundle ?? false, input.stage);
|
|
2626
2668
|
if (providerResult.masterKey) result = providerResult;
|
|
2627
2669
|
}
|
|
2628
2670
|
await generateOpenApi(allEndpoints.map(({ construct }) => construct), { openapi: config.openapi });
|
|
2629
2671
|
return result;
|
|
2630
2672
|
}
|
|
2631
|
-
async function buildForProvider(provider, context,
|
|
2632
|
-
const
|
|
2673
|
+
async function buildForProvider(provider, context, appRoot, discovered, endpointGenerator, functionGenerator, cronGenerator, subscriberGenerator, queueGenerator, topicGenerator, endpoints, functions, crons, subscribers, queues, topics, enableOpenApi, skipBundle, stage) {
|
|
2674
|
+
const rootOutputDir = join(appRoot, ".gkm");
|
|
2675
|
+
const outputDir = join(rootOutputDir, provider);
|
|
2633
2676
|
await mkdir(outputDir, { recursive: true });
|
|
2634
2677
|
logger$9.log(`\nGenerating handlers for provider: ${provider}`);
|
|
2635
2678
|
const [routes, functionInfos, cronInfos, subscriberInfos, queueInfos, topicInfos] = await Promise.all([
|
|
@@ -2645,10 +2688,6 @@ async function buildForProvider(provider, context, rootOutputDir, endpointGenera
|
|
|
2645
2688
|
]);
|
|
2646
2689
|
logger$9.log(`Generated ${routes.length} routes, ${functionInfos.length} functions, ${cronInfos.length} crons, ${subscriberInfos.length} subscribers, ${queueInfos.length} queues, ${topicInfos.length} topics for ${provider}`);
|
|
2647
2690
|
const manifestRoutes = assembleManifestField(routes, endpoints);
|
|
2648
|
-
const discovered = context.constructGlobs ? await discover({
|
|
2649
|
-
patterns: context.constructGlobs,
|
|
2650
|
-
cwd: process.cwd()
|
|
2651
|
-
}) : {};
|
|
2652
2691
|
const manifestFunctions = assembleManifestField(functionInfos, functions);
|
|
2653
2692
|
const manifestCrons = assembleManifestField(cronInfos, crons);
|
|
2654
2693
|
const manifestQueues = assembleManifestField(queueInfos, queues);
|
|
@@ -2662,8 +2701,8 @@ async function buildForProvider(provider, context, rootOutputDir, endpointGenera
|
|
|
2662
2701
|
authorizer: construct.authorizer?.name ?? "none"
|
|
2663
2702
|
}))), endpoints);
|
|
2664
2703
|
await generateServerManifest(rootOutputDir, {
|
|
2665
|
-
handler: relative(
|
|
2666
|
-
endpoints: relative(
|
|
2704
|
+
handler: relative(appRoot, join(outputDir, "app.ts")),
|
|
2705
|
+
endpoints: relative(appRoot, join(outputDir, "endpoints.ts"))
|
|
2667
2706
|
}, serverRouteField, manifestSubscribers, manifestQueues, manifestTopics);
|
|
2668
2707
|
let masterKey;
|
|
2669
2708
|
if (context.production?.bundle && !skipBundle) {
|
|
@@ -2742,14 +2781,9 @@ function getTurboCommand(pm, filters = []) {
|
|
|
2742
2781
|
function turboFilters(workspace) {
|
|
2743
2782
|
const filters = [];
|
|
2744
2783
|
const unpackaged = [];
|
|
2745
|
-
for (const
|
|
2746
|
-
const
|
|
2747
|
-
if (
|
|
2748
|
-
unpackaged.push(appName);
|
|
2749
|
-
continue;
|
|
2750
|
-
}
|
|
2751
|
-
const name = JSON.parse(readFileSync(pkgPath, "utf8")).name;
|
|
2752
|
-
if (typeof name === "string" && name.length > 0) filters.push(name);
|
|
2784
|
+
for (const appName of Object.keys(workspace.apps)) {
|
|
2785
|
+
const name = appPackageName(workspace, appName);
|
|
2786
|
+
if (name) filters.push(name);
|
|
2753
2787
|
else unpackaged.push(appName);
|
|
2754
2788
|
}
|
|
2755
2789
|
return {
|
|
@@ -2758,6 +2792,20 @@ function turboFilters(workspace) {
|
|
|
2758
2792
|
};
|
|
2759
2793
|
}
|
|
2760
2794
|
/**
|
|
2795
|
+
* The package name turbo knows an app by, from its own `package.json`.
|
|
2796
|
+
*
|
|
2797
|
+
* Not the app's key: `api` in the workspace is `@shop/api` to turbo, and a
|
|
2798
|
+
* filter naming the key matches nothing.
|
|
2799
|
+
*/
|
|
2800
|
+
function appPackageName(workspace, appName) {
|
|
2801
|
+
const app = workspace.apps[appName];
|
|
2802
|
+
if (!app) return void 0;
|
|
2803
|
+
const pkgPath = join(workspace.root, app.path, "package.json");
|
|
2804
|
+
if (!existsSync(pkgPath)) return void 0;
|
|
2805
|
+
const name = JSON.parse(readFileSync(pkgPath, "utf8")).name;
|
|
2806
|
+
return typeof name === "string" && name.length > 0 ? name : void 0;
|
|
2807
|
+
}
|
|
2808
|
+
/**
|
|
2761
2809
|
* Build all apps in a workspace using Turbo for dependency-ordered parallel builds.
|
|
2762
2810
|
* @internal Exported for testing
|
|
2763
2811
|
*/
|
|
@@ -8467,26 +8515,26 @@ function loadPackageJson() {
|
|
|
8467
8515
|
* Run: pnpm --filter @geekmidas/cli sync-versions
|
|
8468
8516
|
*/
|
|
8469
8517
|
const GEEKMIDAS_VERSIONS = {
|
|
8470
|
-
"@geekmidas/audit": "~10.0.0-alpha.
|
|
8471
|
-
"@geekmidas/auth": "~10.0.0-alpha.
|
|
8472
|
-
"@geekmidas/cache": "~10.0.0-alpha.
|
|
8473
|
-
"@geekmidas/client": "~10.0.0-alpha.
|
|
8474
|
-
"@geekmidas/cloud": "~10.0.0-alpha.
|
|
8475
|
-
"@geekmidas/constructs": "~10.0.0-alpha.
|
|
8476
|
-
"@geekmidas/db": "~10.0.0-alpha.
|
|
8477
|
-
"@geekmidas/emailkit": "~10.0.0-alpha.
|
|
8478
|
-
"@geekmidas/envkit": "~10.0.0-alpha.
|
|
8479
|
-
"@geekmidas/errors": "~10.0.0-alpha.
|
|
8480
|
-
"@geekmidas/events": "~10.0.0-alpha.
|
|
8481
|
-
"@geekmidas/logger": "~10.0.0-alpha.
|
|
8482
|
-
"@geekmidas/manifest": "~10.0.0-alpha.
|
|
8483
|
-
"@geekmidas/rate-limit": "~10.0.0-alpha.
|
|
8484
|
-
"@geekmidas/schema": "~10.0.0-alpha.
|
|
8485
|
-
"@geekmidas/services": "~10.0.0-alpha.
|
|
8486
|
-
"@geekmidas/storage": "~10.0.0-alpha.
|
|
8487
|
-
"@geekmidas/studio": "~10.0.0-alpha.
|
|
8488
|
-
"@geekmidas/telescope": "~10.0.0-alpha.
|
|
8489
|
-
"@geekmidas/testkit": "~10.0.0-alpha.
|
|
8518
|
+
"@geekmidas/audit": "~10.0.0-alpha.25",
|
|
8519
|
+
"@geekmidas/auth": "~10.0.0-alpha.25",
|
|
8520
|
+
"@geekmidas/cache": "~10.0.0-alpha.25",
|
|
8521
|
+
"@geekmidas/client": "~10.0.0-alpha.25",
|
|
8522
|
+
"@geekmidas/cloud": "~10.0.0-alpha.25",
|
|
8523
|
+
"@geekmidas/constructs": "~10.0.0-alpha.25",
|
|
8524
|
+
"@geekmidas/db": "~10.0.0-alpha.25",
|
|
8525
|
+
"@geekmidas/emailkit": "~10.0.0-alpha.25",
|
|
8526
|
+
"@geekmidas/envkit": "~10.0.0-alpha.25",
|
|
8527
|
+
"@geekmidas/errors": "~10.0.0-alpha.25",
|
|
8528
|
+
"@geekmidas/events": "~10.0.0-alpha.25",
|
|
8529
|
+
"@geekmidas/logger": "~10.0.0-alpha.25",
|
|
8530
|
+
"@geekmidas/manifest": "~10.0.0-alpha.25",
|
|
8531
|
+
"@geekmidas/rate-limit": "~10.0.0-alpha.25",
|
|
8532
|
+
"@geekmidas/schema": "~10.0.0-alpha.25",
|
|
8533
|
+
"@geekmidas/services": "~10.0.0-alpha.25",
|
|
8534
|
+
"@geekmidas/storage": "~10.0.0-alpha.25",
|
|
8535
|
+
"@geekmidas/studio": "~10.0.0-alpha.25",
|
|
8536
|
+
"@geekmidas/telescope": "~10.0.0-alpha.25",
|
|
8537
|
+
"@geekmidas/testkit": "~10.0.0-alpha.25",
|
|
8490
8538
|
"@geekmidas/cli": `~${loadPackageJson().version}`
|
|
8491
8539
|
};
|
|
8492
8540
|
//#endregion
|
|
@@ -15907,7 +15955,7 @@ program.command("dev").description("Reconcile constructs and start the dev serve
|
|
|
15907
15955
|
const globalOptions = program.opts();
|
|
15908
15956
|
if (globalOptions.cwd) process.chdir(globalOptions.cwd);
|
|
15909
15957
|
await devCommand({
|
|
15910
|
-
port: options.port ? Number.parseInt(options.port, 10) :
|
|
15958
|
+
port: options.port ? Number.parseInt(options.port, 10) : void 0,
|
|
15911
15959
|
portExplicit: !!options.port,
|
|
15912
15960
|
enableOpenApi: options.enableOpenapi ?? true,
|
|
15913
15961
|
entry: options.entry,
|
|
@@ -16060,7 +16108,7 @@ program.command("secrets:push").description("Send a deployed stage's secrets to
|
|
|
16060
16108
|
const globalOptions = program.opts();
|
|
16061
16109
|
if (globalOptions.cwd) process.chdir(globalOptions.cwd);
|
|
16062
16110
|
const { loadWorkspaceConfig } = await import("./config.mjs");
|
|
16063
|
-
const { pushStageSecrets } = await import("./transfer-
|
|
16111
|
+
const { pushStageSecrets } = await import("./transfer-B88fTvnh.mjs").then((n) => n.i);
|
|
16064
16112
|
const { workspace } = await loadWorkspaceConfig();
|
|
16065
16113
|
const { addedKeys } = await pushStageSecrets(workspace, options.stage, { profile: options.profile });
|
|
16066
16114
|
for (const key of addedKeys) console.log(` + ${key} (reconciled)`);
|
|
@@ -16075,7 +16123,7 @@ program.command("secrets:pull").description("Bring a deployed stage's secrets fr
|
|
|
16075
16123
|
const globalOptions = program.opts();
|
|
16076
16124
|
if (globalOptions.cwd) process.chdir(globalOptions.cwd);
|
|
16077
16125
|
const { loadWorkspaceConfig } = await import("./config.mjs");
|
|
16078
|
-
const { pullStageSecrets } = await import("./transfer-
|
|
16126
|
+
const { pullStageSecrets } = await import("./transfer-B88fTvnh.mjs").then((n) => n.i);
|
|
16079
16127
|
const { workspace } = await loadWorkspaceConfig();
|
|
16080
16128
|
const { addedKeys } = await pullStageSecrets(workspace, options.stage, { profile: options.profile });
|
|
16081
16129
|
for (const key of addedKeys) console.log(` + ${key} (reconciled)`);
|
|
@@ -16099,7 +16147,7 @@ program.command("secrets:reconcile").description("Backfill missing custom secret
|
|
|
16099
16147
|
console.error(`No secrets found for stage "${stage}". Run "gkm secrets:init --stage ${stage}" first.`);
|
|
16100
16148
|
process.exit(1);
|
|
16101
16149
|
}
|
|
16102
|
-
const { derivedContainers } = await import("./credentials-
|
|
16150
|
+
const { derivedContainers } = await import("./credentials-BpoOUa74.mjs").then((n) => n.g);
|
|
16103
16151
|
const result = reconcileMissingSecrets(secrets, workspace, await derivedContainers(workspace, stage));
|
|
16104
16152
|
if (!result) {
|
|
16105
16153
|
console.log(`\n✓ Secrets for stage "${stage}" are up-to-date`);
|
|
@@ -16158,7 +16206,7 @@ program.command("deploy:github").description("Let GitHub Actions deploy a stage:
|
|
|
16158
16206
|
try {
|
|
16159
16207
|
const globalOptions = program.opts();
|
|
16160
16208
|
if (globalOptions.cwd) process.chdir(globalOptions.cwd);
|
|
16161
|
-
const { deployGithubCommand } = await import("./github-
|
|
16209
|
+
const { deployGithubCommand } = await import("./github-BOaa3kQR.mjs");
|
|
16162
16210
|
await deployGithubCommand(options);
|
|
16163
16211
|
} catch (error) {
|
|
16164
16212
|
console.error(formatError(error));
|