@projectinvicta/nails 3.0.14 → 3.2.2

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.
Files changed (85) hide show
  1. package/.github/workflows/npm-publish.yml +33 -0
  2. package/.github/workflows/release.yml +64 -0
  3. package/README.md +72 -10
  4. package/bin/lib/init.js +63 -32
  5. package/bin/test/test_init.sh +28 -20
  6. package/dist/Nails.d.ts +13 -6
  7. package/dist/Nails.js +36 -44
  8. package/dist/Nails.js.map +1 -1
  9. package/dist/Server.d.ts +31 -0
  10. package/dist/Server.js +193 -0
  11. package/dist/Server.js.map +1 -0
  12. package/dist/types.d.ts +6 -0
  13. package/lib/Nails.ts +48 -51
  14. package/lib/Server.ts +216 -0
  15. package/lib/types.ts +12 -2
  16. package/package.json +3 -2
  17. package/templates/default/bin/console.js +17 -0
  18. package/templates/default/config/db.js +1 -1
  19. package/templates/default/package-lock.json +2726 -4217
  20. package/templates/default/package.json +19 -6
  21. package/templates/default/spec/User.test.js +1 -1
  22. package/templates/default/src/app.jsx +7 -3
  23. package/templates/mcp/bin/console.js +17 -0
  24. package/templates/mcp/bin/promote.sh +20 -0
  25. package/templates/mcp/bin/rollout.sh +74 -0
  26. package/templates/mcp/bin/server.js +6 -0
  27. package/templates/mcp/bin/start.sh +16 -0
  28. package/templates/mcp/common/readme_fetcher.js +4 -0
  29. package/templates/mcp/config/db.js +11 -0
  30. package/templates/mcp/config/mimes.js +40 -0
  31. package/templates/mcp/config/routes.js +20 -0
  32. package/templates/mcp/config/service.js +45 -0
  33. package/templates/mcp/config/ssl/certificate.pem +22 -0
  34. package/templates/mcp/config/ssl/csr.csr +17 -0
  35. package/templates/mcp/config/ssl/key.pem +28 -0
  36. package/templates/mcp/config/ssl/private_key.pem +30 -0
  37. package/templates/mcp/config/ssl/public_key.pem +9 -0
  38. package/templates/mcp/package-lock.json +8032 -0
  39. package/templates/mcp/package.json +64 -0
  40. package/templates/mcp/server/controllers/home_controller.js +34 -0
  41. package/templates/mcp/server/controllers/mcp_controller.js +87 -0
  42. package/templates/mcp/server/controllers/users_controller.js +29 -0
  43. package/templates/mcp/server/models/Dog.js +8 -0
  44. package/templates/mcp/server/models/User.js +18 -0
  45. package/templates/mcp/server/views/home/index.ejs +14 -0
  46. package/templates/mcp/server/views/partials/javascripts.ejs +1 -0
  47. package/templates/mcp/server/views/partials/reactapp.ejs +1 -0
  48. package/templates/mcp/server/views/partials/styles.ejs +3 -0
  49. package/templates/mcp/spec/User.test.js +22 -0
  50. package/templates/mcp/spec/home_controller.test.js +28 -0
  51. package/templates/mcp/spec/setupTests.js +0 -0
  52. package/templates/mcp/vite.config.ts +42 -0
  53. package/templates/mobile/bin/console.js +17 -0
  54. package/templates/mobile/bin/promote.sh +20 -0
  55. package/templates/mobile/bin/rollout.sh +74 -0
  56. package/templates/mobile/bin/server.js +7 -0
  57. package/templates/mobile/bin/start.sh +16 -0
  58. package/templates/mobile/capacitor.config.ts +27 -0
  59. package/templates/mobile/common/constants.js +6 -0
  60. package/templates/mobile/common/readme_fetcher.js +4 -0
  61. package/templates/mobile/config/db.js +19 -0
  62. package/templates/mobile/config/mimes.js +59 -0
  63. package/templates/mobile/config/routes.js +38 -0
  64. package/templates/mobile/config/service.js +45 -0
  65. package/templates/mobile/config/ssl/certificate.pem +22 -0
  66. package/templates/mobile/config/ssl/csr.csr +17 -0
  67. package/templates/mobile/config/ssl/key.pem +28 -0
  68. package/templates/mobile/config/ssl/private_key.pem +30 -0
  69. package/templates/mobile/config/ssl/public_key.pem +9 -0
  70. package/templates/mobile/package.json +72 -0
  71. package/templates/mobile/src/AboutPage.jsx +9 -0
  72. package/templates/mobile/src/HomePage.jsx +9 -0
  73. package/templates/mobile/src/Layout.jsx +78 -0
  74. package/templates/mobile/src/ReadmePage.jsx +7 -0
  75. package/templates/mobile/src/app.jsx +33 -0
  76. package/templates/mobile/src/components/ReadmeLoader.jsx +13 -0
  77. package/templates/mobile/src/index.html +52 -0
  78. package/templates/mobile/src/styles/appstyles.css +3 -0
  79. package/templates/mobile/vite-mobile.config.ts +31 -0
  80. package/tests/bin/init.spec.js +70 -2
  81. package/tests/healthz.spec.js +300 -0
  82. package/tests/nails.spec.js +5 -1
  83. package/tests/services/integration/config/db.ts +1 -1
  84. package/tests/services.integration.spec.js +5 -1
  85. package/vite.config.ts +1 -0
@@ -0,0 +1,31 @@
1
+ import { type Server as HttpsServer } from 'node:https';
2
+ import { type Server as HttpServer } from 'node:http';
3
+ import { type Request, type Response } from 'express';
4
+ import { type Application } from 'express-ws';
5
+ import type Router from './Router.js';
6
+ import { type Config } from './types.js';
7
+ export type HealthCheckFn = () => boolean | Promise<boolean>;
8
+ export default class Server {
9
+ private static activeServerByApp;
10
+ config: Config;
11
+ application: Application;
12
+ httpServer?: HttpServer;
13
+ httpsServer?: HttpsServer;
14
+ healthy: boolean;
15
+ isInitialized: boolean;
16
+ private healthCheck?;
17
+ private initialLameDuckMode;
18
+ private watchedFilePath?;
19
+ private watchFileListener?;
20
+ get lameDuckMode(): boolean;
21
+ set lameDuckMode(value: boolean);
22
+ constructor(config: Config, application?: Application, healthCheck?: HealthCheckFn);
23
+ private registerHealthzEndpoint;
24
+ isHealthy(): Promise<boolean>;
25
+ handleHealthz(_req: Request, res: Response): Promise<void>;
26
+ evaluateWatchFile(watchFile?: string): void;
27
+ private initializeRuntimeWatchFile;
28
+ stopWatchingRuntimeFile(): void;
29
+ start(router: Router): Promise<void>;
30
+ stop(): Promise<void>;
31
+ }
package/dist/Server.js ADDED
@@ -0,0 +1,193 @@
1
+ import fs from 'node:fs';
2
+ import https from 'node:https';
3
+ import expressApp from './application.js';
4
+ const DEFAULT_WATCH_FILE_DELAY = 5000;
5
+ export default class Server {
6
+ static activeServerByApp = new WeakMap();
7
+ config;
8
+ application;
9
+ httpServer;
10
+ httpsServer;
11
+ healthy = true;
12
+ isInitialized = false;
13
+ healthCheck;
14
+ initialLameDuckMode = false;
15
+ watchedFilePath;
16
+ watchFileListener;
17
+ get lameDuckMode() {
18
+ return Boolean(this.config.runtime?.lameDuckMode);
19
+ }
20
+ set lameDuckMode(value) {
21
+ if (!this.config.runtime) {
22
+ this.config.runtime = {};
23
+ }
24
+ this.config.runtime.lameDuckMode = value;
25
+ }
26
+ constructor(config, application = expressApp, healthCheck) {
27
+ this.config = config;
28
+ if (!this.config.runtime) {
29
+ this.config.runtime = {};
30
+ }
31
+ this.initialLameDuckMode = Boolean(this.config.runtime.lameDuckMode);
32
+ this.application = application;
33
+ this.healthCheck = healthCheck;
34
+ }
35
+ registerHealthzEndpoint() {
36
+ const alreadyRegistered = Server.activeServerByApp.has(this.application);
37
+ Server.activeServerByApp.set(this.application, this);
38
+ if (!alreadyRegistered) {
39
+ const app = this.application;
40
+ app.get('/healthz', (req, res) => {
41
+ const activeServer = Server.activeServerByApp.get(app);
42
+ if (activeServer) {
43
+ void activeServer.handleHealthz(req, res);
44
+ }
45
+ else {
46
+ res.status(503).json({ status: 'unhealthy', lameDuckMode: false });
47
+ }
48
+ });
49
+ }
50
+ }
51
+ async isHealthy() {
52
+ if (!this.isInitialized || !this.healthy) {
53
+ return false;
54
+ }
55
+ if (this.healthCheck) {
56
+ try {
57
+ return Boolean(await this.healthCheck());
58
+ }
59
+ catch (error) {
60
+ console.error('Health check failed:', error);
61
+ return false;
62
+ }
63
+ }
64
+ return true;
65
+ }
66
+ async handleHealthz(_req, res) {
67
+ try {
68
+ if (this.lameDuckMode) {
69
+ res.status(503).json({ status: 'lame_duck', lameDuckMode: true });
70
+ return;
71
+ }
72
+ const healthy = await this.isHealthy();
73
+ if (!healthy) {
74
+ res.status(503).json({ status: 'unhealthy', lameDuckMode: false });
75
+ return;
76
+ }
77
+ res.status(200).json({ status: 'ok', lameDuckMode: false });
78
+ }
79
+ catch (error) {
80
+ console.error('Health check error:', error);
81
+ res.status(503).json({ status: 'unhealthy', lameDuckMode: this.lameDuckMode });
82
+ }
83
+ }
84
+ evaluateWatchFile(watchFile) {
85
+ const filePath = watchFile ?? this.config.runtime?.WATCH_FILE;
86
+ if (!filePath)
87
+ return;
88
+ try {
89
+ const raw = fs.readFileSync(filePath, 'utf-8');
90
+ const parsed = JSON.parse(raw);
91
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
92
+ console.error(`Watch file must contain a JSON object: ${filePath}`);
93
+ return;
94
+ }
95
+ this.lameDuckMode = 'lameDuckMode' in parsed
96
+ ? Boolean(parsed.lameDuckMode)
97
+ : this.initialLameDuckMode;
98
+ }
99
+ catch (error) {
100
+ if (error?.code === 'ENOENT') {
101
+ console.warn(`Watch file not found: ${filePath}`);
102
+ this.lameDuckMode = this.initialLameDuckMode;
103
+ }
104
+ else {
105
+ console.error(`Failed to evaluate watch file ${filePath}:`, error);
106
+ }
107
+ }
108
+ }
109
+ initializeRuntimeWatchFile() {
110
+ this.stopWatchingRuntimeFile();
111
+ const watchFile = this.config.runtime?.WATCH_FILE;
112
+ if (!watchFile)
113
+ return;
114
+ this.evaluateWatchFile(watchFile);
115
+ const delay = this.config.runtime?.WATCH_FILE_DELAY ?? DEFAULT_WATCH_FILE_DELAY;
116
+ const listener = () => {
117
+ this.evaluateWatchFile(watchFile);
118
+ };
119
+ this.watchedFilePath = watchFile;
120
+ this.watchFileListener = listener;
121
+ fs.watchFile(watchFile, { persistent: false, interval: delay }, listener);
122
+ }
123
+ stopWatchingRuntimeFile() {
124
+ if (this.watchedFilePath && this.watchFileListener) {
125
+ fs.unwatchFile(this.watchedFilePath, this.watchFileListener);
126
+ this.watchedFilePath = undefined;
127
+ this.watchFileListener = undefined;
128
+ }
129
+ }
130
+ async start(router) {
131
+ this.registerHealthzEndpoint();
132
+ this.initializeRuntimeWatchFile();
133
+ // TODO: Use logging middleware.
134
+ // Use the router middleware.
135
+ this.application.use(router.expressRouter);
136
+ const host = this.config.service.HOST || 'localhost';
137
+ const port = this.config.service.PORT || 3000;
138
+ const startHttp = 'ENABLE_HTTP' in this.config.service && !!this.config.service.ENABLE_HTTP;
139
+ const startHttps = !!this.config.service.ENABLE_HTTPS;
140
+ if (!startHttp && !startHttps) {
141
+ console.error("Either ENABLE_HTTPS or ENABLE_HTTP must be set for nails to start");
142
+ }
143
+ let atLeastOneServerStarted = false;
144
+ return new Promise((resolve) => {
145
+ if (atLeastOneServerStarted)
146
+ return resolve();
147
+ const serverStartedCallback = () => {
148
+ console.log("Started");
149
+ atLeastOneServerStarted = true;
150
+ resolve();
151
+ };
152
+ if (startHttp) {
153
+ console.log("starting nails HTTP server. listening to ", host + ':' + port);
154
+ if (this.httpServer) {
155
+ console.warn("Attempted to recreate http server");
156
+ }
157
+ else {
158
+ this.httpServer = this.application.listen(port, host, serverStartedCallback);
159
+ console.log("Done starting HTTP server");
160
+ }
161
+ }
162
+ if (startHttps) {
163
+ if (this.httpsServer) {
164
+ console.warn("Attempted to recreate HTTPS server");
165
+ }
166
+ else {
167
+ console.log(`starting nails HTTPS server. Listening to ${host}:${this.config.service.SSL_PORT}`);
168
+ this.httpsServer = https.createServer({
169
+ key: this.config.service.PRIVATE_KEY,
170
+ cert: this.config.service.CERTIFICATE
171
+ }, this.application).listen(this.config.service.SSL_PORT, serverStartedCallback);
172
+ }
173
+ }
174
+ // TODO: Set a startup timeout and reject the promise so it does not hang forever;
175
+ });
176
+ }
177
+ async stop() {
178
+ this.stopWatchingRuntimeFile();
179
+ const closePromises = [];
180
+ if (this.httpServer) {
181
+ const server = this.httpServer;
182
+ this.httpServer = undefined;
183
+ closePromises.push(new Promise((resolve) => server.close(() => resolve())));
184
+ }
185
+ if (this.httpsServer) {
186
+ const server = this.httpsServer;
187
+ this.httpsServer = undefined;
188
+ closePromises.push(new Promise((resolve) => server.close(() => resolve())));
189
+ }
190
+ await Promise.all(closePromises);
191
+ }
192
+ }
193
+ //# sourceMappingURL=Server.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Server.js","sourceRoot":"","sources":["../lib/Server.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,SAAS,CAAC;AACzB,OAAO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AM,aAAa,GAAoB,EAAE,CAAC;QAC1C,IAAI,IAAI,CAAC,UAAU,EAAE,CAAC;YACpB,MAAM,MAAM,GAAG,IAAI,CAAC,UAAU,CAAC;YAC/B,IAAI,CAAC,UAAU,GAAG,SAAS,CAAC;YAC5B,aAAa,CAAC,IAAI,CAAC,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,MAAM,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC,CAAC;QAC9E,CAAC;QACD,IAAI,IAAI,CAAC,WAAW,EAAE,CAAC;YACrB,MAAM,MAAM,GAAG,IAAI,CAAC,WAAW,CAAC;YAChC,IAAI,CAAC,WAAW,GAAG,SAAS,CAAC;YAC7B,aAAa,CAAC,IAAI,CAAC,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,MAAM,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC,CAAC;QAC9E,CAAC;QACD,MAAM,OAAO,CAAC,GAAG,CAAC,aAAa,CAAC,CAAC;IACnC,CAAC"}
package/dist/types.d.ts CHANGED
@@ -37,6 +37,11 @@ export interface DbConfig {
37
37
  password?: string;
38
38
  options?: Options;
39
39
  }
40
+ export interface RuntimeConfig {
41
+ WATCH_FILE?: string;
42
+ WATCH_FILE_DELAY?: number;
43
+ lameDuckMode?: boolean;
44
+ }
40
45
  interface AppConfig {
41
46
  APP_ROOT: string;
42
47
  PUBLIC_ROOT: string;
@@ -57,5 +62,6 @@ export interface Config {
57
62
  routes: RoutesConfig;
58
63
  mimes: MimesConfig;
59
64
  db: DbConfig;
65
+ runtime?: RuntimeConfig;
60
66
  }
61
67
  export {};
package/lib/Nails.ts CHANGED
@@ -1,13 +1,11 @@
1
-
2
1
  import fs from 'node:fs';
3
2
  import path from 'node:path';
4
- import https, {type Server as HttpsServer} from 'node:https';
5
- import {type Server as HttpServer} from 'node:http';
6
3
 
7
4
  import { type Application } from 'express-ws';
8
- import { type InitOptions, Model, Sequelize, type ModelAttributes, type ModelStatic } from 'sequelize';
5
+ import { Model, Sequelize } from 'sequelize';
9
6
  import expressApp from './application.js';
10
7
  import Router from './Router.js';
8
+ import Server from './Server.js';
11
9
 
12
10
  import { type Config } from './types.js';
13
11
  import Controller from './Controller.js';
@@ -32,6 +30,10 @@ export default class Nails {
32
30
  return this.instance.application;
33
31
  }
34
32
 
33
+ static get server() {
34
+ return this.instance.server;
35
+ }
36
+
35
37
  static get httpServer() {
36
38
  return this.instance.httpServer;
37
39
  }
@@ -40,6 +42,14 @@ export default class Nails {
40
42
  return this.instance.httpsServer;
41
43
  }
42
44
 
45
+ static get lameDuckMode() {
46
+ return this.instance.lameDuckMode;
47
+ }
48
+
49
+ static set lameDuckMode(value: boolean) {
50
+ this.instance.lameDuckMode = value;
51
+ }
52
+
43
53
  // static initModel<T extends Model>(modelClass: ModelStatic<T>, attributes: ModelAttributes, options?: InitOptions) {
44
54
  // const actualOptions = {...options, sequelize: this.sequelize}
45
55
  // modelClass.init(attributes, actualOptions);
@@ -52,14 +62,37 @@ export default class Nails {
52
62
  declare sequelize: Sequelize;
53
63
  declare initialized: Promise<void>;
54
64
  declare router: Router;
65
+ declare server: Server;
55
66
  declare Model: Model;
56
67
  declare Models: Record<string, typeof Model>;
57
- declare httpServer: HttpServer;
58
- declare httpsServer: HttpsServer;
59
68
 
60
69
  private modelFinalizations: (() => Promise<void>)[] = [];
61
70
  private modelMigrations: (() => Promise<void>)[] = [];
62
71
 
72
+ get httpServer() {
73
+ return this.server.httpServer;
74
+ }
75
+
76
+ get httpsServer() {
77
+ return this.server.httpsServer;
78
+ }
79
+
80
+ get lameDuckMode(): boolean {
81
+ return this.server.lameDuckMode;
82
+ }
83
+
84
+ set lameDuckMode(value: boolean) {
85
+ this.server.lameDuckMode = value;
86
+ }
87
+
88
+ get healthy(): boolean {
89
+ return this.server.healthy;
90
+ }
91
+
92
+ set healthy(value: boolean) {
93
+ this.server.healthy = value;
94
+ }
95
+
63
96
  constructor(appConfig: Config) {
64
97
  Nails.instance = this;
65
98
  this.config = appConfig;
@@ -72,6 +105,12 @@ export default class Nails {
72
105
  this.config.db.options)
73
106
  : new Sequelize(this.config.db.address);
74
107
  this.router = new Router([]);
108
+ this.server = new Server(this.config, this.application, async () => {
109
+ if (this.sequelize) {
110
+ await this.sequelize.authenticate();
111
+ }
112
+ return true;
113
+ });
75
114
  this.initialized = this.configure();
76
115
  }
77
116
 
@@ -95,62 +134,20 @@ export default class Nails {
95
134
  Controller.setRouter(this.router);
96
135
  await this.initializeControllers();
97
136
  this.router.addRoutes(this.config.routes);
137
+ this.server.isInitialized = true;
98
138
  }
99
139
 
100
140
  async initializeModels() {
101
141
  await this.loadModels(this.config.service.MODELS_ROOT);
102
142
  await Promise.all(this.modelFinalizations.map((finalization) => finalization()));
103
143
  // TODO: Implement a migration strategy
104
- await this.sequelize.sync({alter: {drop: false}});
144
+ await this.sequelize.sync({ alter: { drop: false } });
105
145
  }
106
146
 
107
147
  async startServer() {
108
148
  await this.initialized;
109
149
  console.log("CONFIGURATION COMPLETE");
110
- // TODO: Use logging middleware.
111
- // Use the router middleware.
112
- expressApp.use(this.router.expressRouter);
113
- var host = this.config.service.HOST || 'localhost';
114
- var port = this.config.service.PORT || 3000;
115
-
116
- let startHttp = 'ENABLE_HTTP' in this.config.service && !!this.config.service.ENABLE_HTTP;
117
- let startHttps = !!this.config.service.ENABLE_HTTPS;
118
-
119
- if (!startHttp && !startHttps) {
120
- console.error("Either ENABLE_HTTPS or ENABLE_HTTP must be set for nails to start");
121
- }
122
-
123
- let atLeastOneServerStarted = false;
124
- return new Promise<void>((resolve, reject) => {
125
- if (atLeastOneServerStarted) return resolve();
126
- let serverStartedCallback = () => {
127
- console.log("Started");
128
- atLeastOneServerStarted = true;
129
- resolve();
130
- }
131
-
132
- if (startHttp) {
133
- console.log("starting nails HTTP server. listening to ", host + ':' + port);
134
- if (this.httpServer) {
135
- console.warn("Attempted to recreate http server");
136
- } else {
137
- this.httpServer = expressApp.listen(port, host, serverStartedCallback);
138
- console.log("Done starting HTTP server");
139
- }
140
- }
141
- if (startHttps) {
142
- if (this.httpsServer) {
143
- console.warn("Attempted to recreate HTTPS server");
144
- } else {
145
- console.log(`starting nails HTTPS server. Listening to ${host}:${this.config.service.SSL_PORT}`);
146
- this.httpsServer = https.createServer({
147
- key: this.config.service.PRIVATE_KEY,
148
- cert: this.config.service.CERTIFICATE
149
- }, expressApp).listen(this.config.service.SSL_PORT, serverStartedCallback);
150
- }
151
- }
152
- // TODO: Set a startup timeout and reject the promise so it does not hang forever;
153
- });
150
+ return this.server.start(this.router);
154
151
  }
155
152
 
156
153
  async loadModels(absolutePath: string) {
package/lib/Server.ts ADDED
@@ -0,0 +1,216 @@
1
+ import fs from 'node:fs';
2
+ import https, { type Server as HttpsServer } from 'node:https';
3
+ import { type Server as HttpServer } from 'node:http';
4
+
5
+ import { type Request, type Response } from 'express';
6
+ import { type Application } from 'express-ws';
7
+ import expressApp from './application.js';
8
+ import type Router from './Router.js';
9
+ import { type Config, type RuntimeConfig } from './types.js';
10
+
11
+ const DEFAULT_WATCH_FILE_DELAY = 5000;
12
+
13
+ export type HealthCheckFn = () => boolean | Promise<boolean>;
14
+
15
+ export default class Server {
16
+ private static activeServerByApp = new WeakMap<Application, Server>();
17
+
18
+ public config: Config;
19
+ public application: Application;
20
+ public httpServer?: HttpServer;
21
+ public httpsServer?: HttpsServer;
22
+ public healthy: boolean = true;
23
+ public isInitialized: boolean = false;
24
+
25
+ private healthCheck?: HealthCheckFn;
26
+ private initialLameDuckMode: boolean = false;
27
+ private watchedFilePath?: string;
28
+ private watchFileListener?: (curr: fs.Stats, prev: fs.Stats) => void;
29
+
30
+ get lameDuckMode(): boolean {
31
+ return Boolean(this.config.runtime?.lameDuckMode);
32
+ }
33
+
34
+ set lameDuckMode(value: boolean) {
35
+ if (!this.config.runtime) {
36
+ this.config.runtime = {};
37
+ }
38
+ this.config.runtime.lameDuckMode = value;
39
+ }
40
+
41
+ constructor(
42
+ config: Config,
43
+ application: Application = expressApp,
44
+ healthCheck?: HealthCheckFn
45
+ ) {
46
+ this.config = config;
47
+ if (!this.config.runtime) {
48
+ this.config.runtime = {};
49
+ }
50
+ this.initialLameDuckMode = Boolean(this.config.runtime.lameDuckMode);
51
+ this.application = application;
52
+ this.healthCheck = healthCheck;
53
+ }
54
+
55
+ private registerHealthzEndpoint(): void {
56
+ const alreadyRegistered = Server.activeServerByApp.has(this.application);
57
+ Server.activeServerByApp.set(this.application, this);
58
+ if (!alreadyRegistered) {
59
+ const app = this.application;
60
+ app.get('/healthz', (req: Request, res: Response) => {
61
+ const activeServer = Server.activeServerByApp.get(app);
62
+ if (activeServer) {
63
+ void activeServer.handleHealthz(req, res);
64
+ } else {
65
+ res.status(503).json({ status: 'unhealthy', lameDuckMode: false });
66
+ }
67
+ });
68
+ }
69
+ }
70
+
71
+ async isHealthy(): Promise<boolean> {
72
+ if (!this.isInitialized || !this.healthy) {
73
+ return false;
74
+ }
75
+ if (this.healthCheck) {
76
+ try {
77
+ return Boolean(await this.healthCheck());
78
+ } catch (error) {
79
+ console.error('Health check failed:', error);
80
+ return false;
81
+ }
82
+ }
83
+ return true;
84
+ }
85
+
86
+ async handleHealthz(_req: Request, res: Response): Promise<void> {
87
+ try {
88
+ if (this.lameDuckMode) {
89
+ res.status(503).json({ status: 'lame_duck', lameDuckMode: true });
90
+ return;
91
+ }
92
+ const healthy = await this.isHealthy();
93
+ if (!healthy) {
94
+ res.status(503).json({ status: 'unhealthy', lameDuckMode: false });
95
+ return;
96
+ }
97
+ res.status(200).json({ status: 'ok', lameDuckMode: false });
98
+ } catch (error) {
99
+ console.error('Health check error:', error);
100
+ res.status(503).json({ status: 'unhealthy', lameDuckMode: this.lameDuckMode });
101
+ }
102
+ }
103
+
104
+ evaluateWatchFile(watchFile?: string): void {
105
+ const filePath = watchFile ?? this.config.runtime?.WATCH_FILE;
106
+ if (!filePath) return;
107
+
108
+ try {
109
+ const raw = fs.readFileSync(filePath, 'utf-8');
110
+ const parsed = JSON.parse(raw) as Partial<RuntimeConfig>;
111
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
112
+ console.error(`Watch file must contain a JSON object: ${filePath}`);
113
+ return;
114
+ }
115
+ this.lameDuckMode = 'lameDuckMode' in parsed
116
+ ? Boolean(parsed.lameDuckMode)
117
+ : this.initialLameDuckMode;
118
+ } catch (error: any) {
119
+ if (error?.code === 'ENOENT') {
120
+ console.warn(`Watch file not found: ${filePath}`);
121
+ this.lameDuckMode = this.initialLameDuckMode;
122
+ } else {
123
+ console.error(`Failed to evaluate watch file ${filePath}:`, error);
124
+ }
125
+ }
126
+ }
127
+
128
+ private initializeRuntimeWatchFile(): void {
129
+ this.stopWatchingRuntimeFile();
130
+ const watchFile = this.config.runtime?.WATCH_FILE;
131
+ if (!watchFile) return;
132
+
133
+ this.evaluateWatchFile(watchFile);
134
+
135
+ const delay = this.config.runtime?.WATCH_FILE_DELAY ?? DEFAULT_WATCH_FILE_DELAY;
136
+ const listener = () => {
137
+ this.evaluateWatchFile(watchFile);
138
+ };
139
+ this.watchedFilePath = watchFile;
140
+ this.watchFileListener = listener;
141
+ fs.watchFile(watchFile, { persistent: false, interval: delay }, listener);
142
+ }
143
+
144
+ stopWatchingRuntimeFile(): void {
145
+ if (this.watchedFilePath && this.watchFileListener) {
146
+ fs.unwatchFile(this.watchedFilePath, this.watchFileListener);
147
+ this.watchedFilePath = undefined;
148
+ this.watchFileListener = undefined;
149
+ }
150
+ }
151
+
152
+ async start(router: Router): Promise<void> {
153
+ this.registerHealthzEndpoint();
154
+ this.initializeRuntimeWatchFile();
155
+ // TODO: Use logging middleware.
156
+ // Use the router middleware.
157
+ this.application.use(router.expressRouter);
158
+ const host = this.config.service.HOST || 'localhost';
159
+ const port = this.config.service.PORT || 3000;
160
+
161
+ const startHttp = 'ENABLE_HTTP' in this.config.service && !!this.config.service.ENABLE_HTTP;
162
+ const startHttps = !!this.config.service.ENABLE_HTTPS;
163
+
164
+ if (!startHttp && !startHttps) {
165
+ console.error("Either ENABLE_HTTPS or ENABLE_HTTP must be set for nails to start");
166
+ }
167
+
168
+ let atLeastOneServerStarted = false;
169
+ return new Promise<void>((resolve) => {
170
+ if (atLeastOneServerStarted) return resolve();
171
+ const serverStartedCallback = () => {
172
+ console.log("Started");
173
+ atLeastOneServerStarted = true;
174
+ resolve();
175
+ };
176
+
177
+ if (startHttp) {
178
+ console.log("starting nails HTTP server. listening to ", host + ':' + port);
179
+ if (this.httpServer) {
180
+ console.warn("Attempted to recreate http server");
181
+ } else {
182
+ this.httpServer = this.application.listen(port, host, serverStartedCallback);
183
+ console.log("Done starting HTTP server");
184
+ }
185
+ }
186
+ if (startHttps) {
187
+ if (this.httpsServer) {
188
+ console.warn("Attempted to recreate HTTPS server");
189
+ } else {
190
+ console.log(`starting nails HTTPS server. Listening to ${host}:${this.config.service.SSL_PORT}`);
191
+ this.httpsServer = https.createServer({
192
+ key: this.config.service.PRIVATE_KEY,
193
+ cert: this.config.service.CERTIFICATE
194
+ }, this.application).listen(this.config.service.SSL_PORT, serverStartedCallback);
195
+ }
196
+ }
197
+ // TODO: Set a startup timeout and reject the promise so it does not hang forever;
198
+ });
199
+ }
200
+
201
+ async stop(): Promise<void> {
202
+ this.stopWatchingRuntimeFile();
203
+ const closePromises: Promise<void>[] = [];
204
+ if (this.httpServer) {
205
+ const server = this.httpServer;
206
+ this.httpServer = undefined;
207
+ closePromises.push(new Promise((resolve) => server.close(() => resolve())));
208
+ }
209
+ if (this.httpsServer) {
210
+ const server = this.httpsServer;
211
+ this.httpsServer = undefined;
212
+ closePromises.push(new Promise((resolve) => server.close(() => resolve())));
213
+ }
214
+ await Promise.all(closePromises);
215
+ }
216
+ }
package/lib/types.ts CHANGED
@@ -1,4 +1,4 @@
1
- import {type Options } from "sequelize";
1
+ import { type Options } from "sequelize";
2
2
  import { type NextFunction, type Request, type Response } from "express";
3
3
 
4
4
  export interface ControllerDoRouteParams {
@@ -33,7 +33,7 @@ type HttpMethod = 'get' | 'post' | 'put' | 'delete' | 'ws';
33
33
 
34
34
  export type RouteDefinition = [HttpMethod, RouteMatcher, RouteOptions?];
35
35
 
36
- export interface RoutesConfig extends Array<RouteDefinition> {}
36
+ export interface RoutesConfig extends Array<RouteDefinition> { }
37
37
 
38
38
  interface MimesConfig {
39
39
  [key: string]: any;
@@ -46,6 +46,15 @@ export interface DbConfig {
46
46
  options?: Options;
47
47
  }
48
48
 
49
+ export interface RuntimeConfig {
50
+ WATCH_FILE?: string;
51
+ WATCH_FILE_DELAY?: number;
52
+ lameDuckMode?: boolean;
53
+ // TODO(Stanton): allow features to be rolled out to specific users/roles
54
+ // May want to put this in its own config file so feature resolution can be done dynamically.
55
+ // features?: Map<string, boolean>;
56
+ }
57
+
49
58
  interface AppConfig {
50
59
  APP_ROOT: string;
51
60
  PUBLIC_ROOT: string;
@@ -71,4 +80,5 @@ export interface Config {
71
80
  routes: RoutesConfig;
72
81
  mimes: MimesConfig;
73
82
  db: DbConfig;
83
+ runtime?: RuntimeConfig;
74
84
  }