badmfck-api-server 6.0.11 → 6.0.13

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 (64) hide show
  1. package/CHANGELOG.md +86 -0
  2. package/README.md +247 -79
  3. package/dist/apiServer/APIService.d.ts +3 -1
  4. package/dist/apiServer/APIService.js +25 -1
  5. package/dist/apiServer/LogService.d.ts +2 -0
  6. package/dist/apiServer/LogService.js +10 -8
  7. package/dist/apiServer/MonitorService.d.ts +4 -1
  8. package/dist/apiServer/MonitorService.js +28 -5
  9. package/dist/apiServer/deployment/Activate.js +2 -6
  10. package/dist/apiServer/deployment/Backups.js +3 -2
  11. package/dist/apiServer/deployment/Bundler.d.ts +12 -0
  12. package/dist/apiServer/deployment/Bundler.js +178 -0
  13. package/dist/apiServer/deployment/ConfigService.d.ts +6 -0
  14. package/dist/apiServer/deployment/ConfigService.js +17 -1
  15. package/dist/apiServer/deployment/Deploy.js +101 -57
  16. package/dist/apiServer/deployment/DeployKeyWizard.d.ts +2 -0
  17. package/dist/apiServer/deployment/DeployKeyWizard.js +84 -0
  18. package/dist/apiServer/deployment/Deployer.d.ts +1 -0
  19. package/dist/apiServer/deployment/Deployer.js +7 -5
  20. package/dist/apiServer/deployment/DeployerService.d.ts +27 -2
  21. package/dist/apiServer/deployment/DeployerService.js +129 -30
  22. package/dist/apiServer/deployment/HashPassword.js +2 -2
  23. package/dist/apiServer/deployment/MigrateConfigsWizard.js +9 -5
  24. package/dist/apiServer/deployment/ProjectConfigWizard.js +4 -2
  25. package/dist/apiServer/deployment/Restore.js +9 -8
  26. package/dist/apiServer/deployment/SecretsInjector.js +2 -1
  27. package/dist/apiServer/deployment/SetupConfigWizard.js +38 -2
  28. package/dist/apiServer/deployment/Status.js +5 -8
  29. package/dist/apiServer/deployment/Watchdog.js +1 -1
  30. package/dist/apiServer/deployment/Wizards.js +16 -11
  31. package/dist/apiServer/deployment/cli.js +33 -14
  32. package/dist/apiServer/deployment/cliCommon.d.ts +13 -1
  33. package/dist/apiServer/deployment/cliCommon.js +50 -2
  34. package/dist/apiServer/deployment/resolveConfig.d.ts +4 -1
  35. package/dist/apiServer/deployment/resolveConfig.js +23 -2
  36. package/dist/apiServer/external/MicroserviceClient.d.ts +7 -2
  37. package/dist/apiServer/external/MicroserviceClient.js +90 -10
  38. package/dist/apiServer/external/MicroserviceHost.d.ts +35 -8
  39. package/dist/apiServer/external/MicroserviceHost.js +148 -55
  40. package/dist/apiServer/helper/AppDataPath.d.ts +9 -0
  41. package/dist/apiServer/helper/AppDataPath.js +81 -0
  42. package/dist/apiServer/helper/ClientIp.d.ts +1 -0
  43. package/dist/apiServer/helper/ClientIp.js +5 -0
  44. package/dist/apiServer/helper/Trace.d.ts +8 -0
  45. package/dist/apiServer/helper/Trace.js +30 -0
  46. package/dist/apiServer/helper/Validator.d.ts +1 -0
  47. package/dist/apiServer/helper/Validator.js +21 -18
  48. package/dist/apiServer/http/Http.d.ts +1 -0
  49. package/dist/apiServer/http/Http.js +5 -2
  50. package/dist/apiServer/interceptors/InterceptorSignedAuth.d.ts +40 -0
  51. package/dist/apiServer/interceptors/InterceptorSignedAuth.js +150 -0
  52. package/dist/apiServer/monitor/MonitorAuth.js +8 -5
  53. package/dist/apiServer/monitor/ThreatMonitor.d.ts +8 -0
  54. package/dist/apiServer/monitor/ThreatMonitor.js +87 -1
  55. package/dist/apiServer/monitor/index.html +66 -66
  56. package/dist/apiServer/security/BlockedIps.js +10 -14
  57. package/dist/apiServer/structures/Interfaces.d.ts +2 -0
  58. package/dist/index.d.ts +3 -0
  59. package/dist/index.js +5 -1
  60. package/package.json +21 -6
  61. package/bluegreen.help.md +0 -392
  62. package/cocroach.help.md +0 -191
  63. package/connections.help.md +0 -0
  64. package/monitoring.help.md +0 -350
@@ -60,12 +60,14 @@ const DocumentService_1 = require("./DocumentService");
60
60
  const Documentation_1 = require("./documentation/Documentation");
61
61
  const MicroserviceHostController_1 = require("./external/MicroserviceHostController");
62
62
  const DeployerService_1 = require("./deployment/DeployerService");
63
+ const AppDataPath_1 = require("./helper/AppDataPath");
63
64
  const BlueGreenState_1 = require("./deployment/BlueGreenState");
64
65
  const ThreatMonitor_1 = require("./monitor/ThreatMonitor");
65
66
  const AccessStore_1 = require("./monitor/AccessStore");
66
67
  const BlockedIps_1 = require("./security/BlockedIps");
67
68
  const MonitorAuth_1 = require("./monitor/MonitorAuth");
68
69
  const ClientIp_1 = require("./helper/ClientIp");
70
+ const Trace_1 = require("./helper/Trace");
69
71
  const Deployer_1 = require("./deployment/Deployer");
70
72
  const Review_1 = require("./review/Review");
71
73
  const ws_1 = require("ws");
@@ -131,6 +133,10 @@ async function Initializer(services) {
131
133
  }
132
134
  }
133
135
  class APIService extends BaseService_1.BaseService {
136
+ async finishService() {
137
+ await super.finishService();
138
+ ThreatMonitor_1.ThreatMonitor.save();
139
+ }
134
140
  static getBlueGreenActiveState(opts) {
135
141
  return (0, BlueGreenState_1.getBlueGreenActiveState)(opts);
136
142
  }
@@ -186,7 +192,7 @@ class APIService extends BaseService_1.BaseService {
186
192
  }
187
193
  const plain = MonitorAuth_1.MonitorAuth.plaintextLogins(next.monitor ?? []);
188
194
  if (plain.length)
189
- (0, LogService_1.logError)(`Monitor: password stored as plain text for ${plain.map(l => '"' + l + '"').join(", ")} — these logins are refused; store a hash instead: npx badmfck hash-password`);
195
+ (0, LogService_1.logError)(`Monitor: password stored as plain text for ${plain.map(l => '"' + l + '"').join(", ")} — these logins are refused; store a hash instead: npx bmfk hash-password`);
190
196
  });
191
197
  exports.REQ_MONITOR_USERS.listener = async () => access.monitor;
192
198
  exports.REQ_DOC_USERS.listener = async () => access.documentation;
@@ -238,6 +244,12 @@ class APIService extends BaseService_1.BaseService {
238
244
  };
239
245
  const app = (0, express_1.default)();
240
246
  const trustedProxies = new Set(this.options.trustedProxies ?? ClientIp_1.DEFAULT_TRUSTED_PROXIES);
247
+ app.use((req, res, next) => {
248
+ const incoming = req.get(Trace_1.TRACE_HEADER);
249
+ const traceId = Trace_1.Trace.isValid(incoming) && (0, ClientIp_1.fromTrustedProxy)(req, trustedProxies) ? incoming : Trace_1.Trace.newId();
250
+ res.setHeader("X-Request-Id", traceId);
251
+ Trace_1.Trace.run(traceId, next);
252
+ });
241
253
  if (this.options.blockedIps !== false) {
242
254
  const message = this.options.blockedIps?.message || "Access from your address is blocked";
243
255
  app.use((req, res, next) => {
@@ -249,6 +261,8 @@ class APIService extends BaseService_1.BaseService {
249
261
  });
250
262
  }
251
263
  if (this.options.threatMonitoring !== false) {
264
+ const dataDir = AppDataPath_1.AppData.dir("");
265
+ ThreatMonitor_1.ThreatMonitor.configure(dataDir ? path_1.default.join(dataDir, "threats.json") : (0, AppDataPath_1.appDataPath)("threats", ".json"));
252
266
  app.use((req, res, next) => {
253
267
  res.on("finish", () => {
254
268
  try {
@@ -410,6 +424,7 @@ class APIService extends BaseService_1.BaseService {
410
424
  files: req.files ?? null,
411
425
  referer: req.get("Referer"),
412
426
  ip: (0, ClientIp_1.clientIp)(req, trustedProxies),
427
+ traceId: Trace_1.Trace.current() ?? undefined,
413
428
  };
414
429
  let ignoreHttpLogging = j.ignoreHttpLogging ?? false;
415
430
  if (!ignoreHttpLogging && typeof j.handler === "object") {
@@ -552,6 +567,7 @@ class APIService extends BaseService_1.BaseService {
552
567
  time = +new Date() - created;
553
568
  const logItem = {
554
569
  id: nextLogID++,
570
+ traceId: req?.traceId,
555
571
  created: created,
556
572
  time: time,
557
573
  request: {
@@ -667,6 +683,14 @@ class APIService extends BaseService_1.BaseService {
667
683
  if (DefaultErrors_1.ErrorUtils.isError(data))
668
684
  data = { error: data, data: null };
669
685
  data.responseTime = (+new Date()) - requestTime;
686
+ const traceId = Trace_1.Trace.current() ?? req?.traceId;
687
+ if (traceId) {
688
+ data.traceId = traceId;
689
+ if (req)
690
+ req.traceId = traceId;
691
+ if (!res.headersSent)
692
+ res.setHeader("X-Request-Id", traceId);
693
+ }
670
694
  data.core = this.version;
671
695
  data.endpoint = endpoint ?? "no_endpoint";
672
696
  if (this.options.appVersion)
@@ -17,6 +17,7 @@ export interface ILogItem {
17
17
  date: string;
18
18
  source: string;
19
19
  repeat: number;
20
+ traceId?: string;
20
21
  }
21
22
  export interface ILogServiceOptions {
22
23
  output?: (data: ILogItem) => void;
@@ -35,6 +36,7 @@ export declare const logAPI: (message: any, ...optional: any[]) => void;
35
36
  export declare const S_LOG: Signal<{
36
37
  level: LOG_LEVEL;
37
38
  data: any[];
39
+ traceId?: string;
38
40
  }>;
39
41
  export declare const S_LOG_CREATED: Signal<ILogItem>;
40
42
  export declare const S_LOG_CHANGE_LEVEL: Signal<LOG_LEVEL>;
@@ -36,6 +36,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.LogService = exports.REQ_LOG_UNIQUE_SERVICES = exports.REQ_LOG = exports.S_LOG_SET_TEXT_LIMIT = exports.S_LOG_REMOVE_SERVICE_FROM_WATCH = exports.S_LOG_ADD_SERVICE_TO_WATCH = exports.S_LOG_FLUSH = exports.REQ_CURRENT_LOG_LEVEL = exports.S_LOG_CHANGE_LEVEL = exports.S_LOG_CREATED = exports.S_LOG = exports.logAPI = exports.logDB = exports.logError = exports.logCrit = exports.logWarn = exports.logInfo = exports.getDefaultLogOptions = exports.LOG_LEVEL = void 0;
37
37
  const badmfck_signal_1 = __importStar(require("badmfck-signal"));
38
38
  const BaseService_1 = require("./BaseService");
39
+ const Trace_1 = require("./helper/Trace");
39
40
  var LOG_LEVEL;
40
41
  (function (LOG_LEVEL) {
41
42
  LOG_LEVEL[LOG_LEVEL["ALL"] = 10] = "ALL";
@@ -55,27 +56,27 @@ const getDefaultLogOptions = () => {
55
56
  };
56
57
  exports.getDefaultLogOptions = getDefaultLogOptions;
57
58
  const logInfo = (message, ...optional) => {
58
- exports.S_LOG.invoke({ level: LOG_LEVEL.INFO, data: [message, optional] });
59
+ exports.S_LOG.invoke({ level: LOG_LEVEL.INFO, data: [message, optional], traceId: Trace_1.Trace.current() ?? undefined });
59
60
  };
60
61
  exports.logInfo = logInfo;
61
62
  const logWarn = (message, ...optional) => {
62
- exports.S_LOG.invoke({ level: LOG_LEVEL.WARN, data: [message, optional] });
63
+ exports.S_LOG.invoke({ level: LOG_LEVEL.WARN, data: [message, optional], traceId: Trace_1.Trace.current() ?? undefined });
63
64
  };
64
65
  exports.logWarn = logWarn;
65
66
  const logCrit = (message, ...optional) => {
66
- exports.S_LOG.invoke({ level: LOG_LEVEL.CRIT, data: [message, optional] });
67
+ exports.S_LOG.invoke({ level: LOG_LEVEL.CRIT, data: [message, optional], traceId: Trace_1.Trace.current() ?? undefined });
67
68
  };
68
69
  exports.logCrit = logCrit;
69
70
  const logError = (message, ...optional) => {
70
- exports.S_LOG.invoke({ level: LOG_LEVEL.ERROR, data: [message, optional] });
71
+ exports.S_LOG.invoke({ level: LOG_LEVEL.ERROR, data: [message, optional], traceId: Trace_1.Trace.current() ?? undefined });
71
72
  };
72
73
  exports.logError = logError;
73
74
  const logDB = (message, ...optional) => {
74
- exports.S_LOG.invoke({ level: LOG_LEVEL.DB, data: [message, optional] });
75
+ exports.S_LOG.invoke({ level: LOG_LEVEL.DB, data: [message, optional], traceId: Trace_1.Trace.current() ?? undefined });
75
76
  };
76
77
  exports.logDB = logDB;
77
78
  const logAPI = (message, ...optional) => {
78
- exports.S_LOG.invoke({ level: LOG_LEVEL.API, data: [message, optional] });
79
+ exports.S_LOG.invoke({ level: LOG_LEVEL.API, data: [message, optional], traceId: Trace_1.Trace.current() ?? undefined });
79
80
  };
80
81
  exports.logAPI = logAPI;
81
82
  exports.S_LOG = new badmfck_signal_1.default();
@@ -182,14 +183,15 @@ class LogService extends BaseService_1.BaseService {
182
183
  time: d.getTime(),
183
184
  date: this.createDate(d),
184
185
  source: source,
185
- repeat: 0
186
+ repeat: 0,
187
+ traceId: log.traceId
186
188
  };
187
189
  if (this.options.output) {
188
190
  this.options.output(logitem);
189
191
  }
190
192
  if (this.log.length > 0) {
191
193
  const lastLogItem = this.log[this.log.length - 1];
192
- if (lastLogItem && lastLogItem.text === logitem.text && lastLogItem.source === logitem.source && lastLogItem.level === logitem.level) {
194
+ if (lastLogItem && lastLogItem.text === logitem.text && lastLogItem.source === logitem.source && lastLogItem.level === logitem.level && lastLogItem.traceId === logitem.traceId) {
193
195
  lastLogItem.repeat++;
194
196
  lastLogItem.time = logitem.time;
195
197
  lastLogItem.date = logitem.date;
@@ -56,13 +56,16 @@ export declare class MonitorService extends BaseService {
56
56
  lastCpuUsage: NodeJS.CpuUsage | null;
57
57
  lastTimestamp: number | null;
58
58
  private metricsDir;
59
+ private _live;
59
60
  private static MAX_WEEKS;
60
61
  private static SCHEMA_VERSION;
61
62
  private _persistReady;
62
63
  private _flushedUpTo;
63
64
  private _lastSeenWeekKey;
64
- constructor(metricsDir?: string | null);
65
+ constructor(metricsDir?: string | null | false);
66
+ private static defaultDir;
65
67
  init(): Promise<void>;
68
+ private followLive;
66
69
  finishService(): Promise<void>;
67
70
  getEPStat(req: {
68
71
  range: "week" | "day" | "hour";
@@ -44,6 +44,7 @@ const LogService_1 = require("./LogService");
44
44
  const os_1 = __importDefault(require("os"));
45
45
  const promises_1 = __importDefault(require("fs/promises"));
46
46
  const path_1 = __importDefault(require("path"));
47
+ const AppDataPath_1 = require("./helper/AppDataPath");
47
48
  exports.S_STAT_REGISTRATE_REQUEST = new badmfck_signal_1.default();
48
49
  exports.S_STAT_REGISTRATE_CUSTOM_EVENT = new badmfck_signal_1.default();
49
50
  exports.S_STAT_REGISTRATE_SERVICE = new badmfck_signal_1.default();
@@ -59,6 +60,7 @@ class MonitorService extends BaseService_1.BaseService {
59
60
  lastCpuUsage = null;
60
61
  lastTimestamp = null;
61
62
  metricsDir;
63
+ _live = false;
62
64
  static MAX_WEEKS = 10;
63
65
  static SCHEMA_VERSION = 2;
64
66
  _persistReady = false;
@@ -66,9 +68,19 @@ class MonitorService extends BaseService_1.BaseService {
66
68
  _lastSeenWeekKey = null;
67
69
  constructor(metricsDir) {
68
70
  super("MonitorService");
69
- this.metricsDir = metricsDir && metricsDir.length > 0 ? metricsDir : null;
71
+ this.metricsDir = metricsDir === false || metricsDir === null ? null
72
+ : metricsDir && metricsDir.length > 0 ? metricsDir
73
+ : MonitorService.defaultDir();
70
74
  setInterval(() => this.collectUsage(), this.intervalMs);
71
75
  }
76
+ static defaultDir() {
77
+ const dir = AppDataPath_1.AppData.dir("metrics");
78
+ if (dir)
79
+ return dir;
80
+ const fallback = (0, AppDataPath_1.appDataPath)("metrics");
81
+ (0, LogService_1.logWarn)(`Metrics persistence: can't create ${AppDataPath_1.AppData.root()}/${AppDataPath_1.AppData.project()}/metrics (create ${AppDataPath_1.AppData.root()} and give the app user write access, or set ${AppDataPath_1.APP_DATA_ROOT_ENV}) — using ${fallback}`);
82
+ return fallback;
83
+ }
72
84
  async init() {
73
85
  super.init();
74
86
  exports.REQ_STAT.listener = async (req) => this.getEPStat(req);
@@ -79,7 +91,7 @@ class MonitorService extends BaseService_1.BaseService {
79
91
  exports.S_STAT_REGISTRATE_SQL_REQUEST.subscribe((data) => this.onSQLRequestRegistrate(data));
80
92
  exports.S_STAT_REGISTRATE_REQUEST.subscribe((data) => this.onStatRegistrate(data));
81
93
  if (!this.metricsDir) {
82
- (0, LogService_1.logInfo)("Metrics persistence: OFF — history is in memory only and lost on restart. Set the APIService option metricsDir to keep it (sm/metricsWeeks).", "MonitorService");
94
+ (0, LogService_1.logInfo)("Metrics persistence: OFF (metricsDir: false) — history is in memory only and lost on restart.", "MonitorService");
83
95
  }
84
96
  else {
85
97
  this.metricsDir = path_1.default.resolve(this.metricsDir);
@@ -100,14 +112,25 @@ class MonitorService extends BaseService_1.BaseService {
100
112
  }
101
113
  if (this.metricsDir) {
102
114
  await this.hydrate();
103
- await this.rotate();
104
115
  this._lastSeenWeekKey = this.weekKey(new Date());
105
116
  this._persistReady = true;
117
+ this.followLive();
106
118
  }
107
119
  }
120
+ followLive() {
121
+ const canWrite = (0, AppDataPath_1.onWriterChange)(live => {
122
+ if (live === this._live)
123
+ return;
124
+ this._live = live;
125
+ if (live)
126
+ this.hydrate().then(() => this.rotate()).catch(() => { });
127
+ });
128
+ if (!canWrite)
129
+ (0, LogService_1.logInfo)(`Metrics persistence: pm2 worker ${process.env.NODE_APP_INSTANCE} — only instance 0 writes ${this.metricsDir}`, "MonitorService");
130
+ }
108
131
  async finishService() {
109
132
  await super.finishService();
110
- if (this.metricsDir && this._persistReady)
133
+ if (this.metricsDir && this._persistReady && this._live)
111
134
  await this.persistTick(true).catch(() => { });
112
135
  }
113
136
  async getEPStat(req) {
@@ -220,7 +243,7 @@ class MonitorService extends BaseService_1.BaseService {
220
243
  heapTotal: Math.round(mem.heapTotal / 1024 / 1024),
221
244
  external: Math.round(mem.external / 1024 / 1024),
222
245
  };
223
- if (this.metricsDir && this._persistReady)
246
+ if (this.metricsDir && this._persistReady && this._live)
224
247
  await this.persistTick().catch(() => { });
225
248
  }
226
249
  static MAX_SLOT_KEYS = 100;
@@ -1,12 +1,9 @@
1
1
  "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
2
  Object.defineProperty(exports, "__esModule", { value: true });
6
3
  exports.Activate = Activate;
7
- const crypto_1 = __importDefault(require("crypto"));
8
4
  const __1 = require("../..");
9
5
  const resolveConfig_1 = require("./resolveConfig");
6
+ const cliCommon_1 = require("./cliCommon");
10
7
  async function Activate(opt, scheme) {
11
8
  opt = await (0, resolveConfig_1.resolveConfig)(opt);
12
9
  if (scheme && scheme !== "blue" && scheme !== "green") {
@@ -23,14 +20,13 @@ async function Activate(opt, scheme) {
23
20
  throw new Error(`Cannot derive switch URL from host "${opt.host}". ` +
24
21
  `Either add "switch_host" to config, or make sure "host" ends with /add.`);
25
22
  }
26
- const authToken = crypto_1.default.createHash("sha256").update(opt.username + ":" + opt.password).digest("hex");
27
23
  const requestBody = { name: opt.name, token: opt.token };
28
24
  if (scheme)
29
25
  requestBody.scheme = scheme;
30
26
  console.log(`Activating${scheme ? ` slot=${scheme}` : " (auto: lastDeployed)"} for ${opt.name} at ${switchUrl}`);
31
27
  const startedAt = Date.now();
32
28
  const response = await __1.Http.post(switchUrl, requestBody, {
33
- headers: { authorization: `Bearer ${authToken}`, "x-deployer-login": String(opt.username) },
29
+ headers: (0, cliCommon_1.deployerHeaders)(opt, switchUrl, requestBody),
34
30
  timeoutMs: 60 * 1000,
35
31
  retry: { enabled: false },
36
32
  });
@@ -7,8 +7,9 @@ const cliCommon_1 = require("./cliCommon");
7
7
  async function Backups(opt) {
8
8
  opt = await (0, resolveConfig_1.resolveConfig)(opt);
9
9
  const { red, yellow, blue, green, dim, bold } = (0, cliCommon_1.palette)();
10
- const r = await __1.Http.post((0, cliCommon_1.deployerUrl)(opt, "backups"), { name: opt.name }, {
11
- headers: (0, cliCommon_1.deployerHeaders)(opt), timeoutMs: 30000, retry: { enabled: false },
10
+ const url = (0, cliCommon_1.deployerUrl)(opt, "backups"), body = { name: opt.name };
11
+ const r = await __1.Http.post(url, body, {
12
+ headers: (0, cliCommon_1.deployerHeaders)(opt, url, body), timeoutMs: 30000, retry: { enabled: false },
12
13
  });
13
14
  const err = (0, cliCommon_1.responseError)(r);
14
15
  if (err) {
@@ -0,0 +1,12 @@
1
+ export interface IBundleOptions {
2
+ entry?: string;
3
+ sourcemap?: boolean;
4
+ minify?: boolean;
5
+ }
6
+ export interface IBundleResult {
7
+ stageDir: string;
8
+ outFile: string;
9
+ modules: number;
10
+ warnings: string[];
11
+ }
12
+ export declare function Bundle(opt: boolean | IBundleOptions, pkg: any): Promise<IBundleResult>;
@@ -0,0 +1,178 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.Bundle = Bundle;
7
+ const fs_1 = __importDefault(require("fs"));
8
+ const path_1 = __importDefault(require("path"));
9
+ const os_1 = __importDefault(require("os"));
10
+ const SRC_EXT = /\.(c|m)?(t|j)sx?$/;
11
+ async function Bundle(opt, pkg) {
12
+ const o = typeof opt === "object" && opt ? opt : {};
13
+ if (!fs_1.default.existsSync("bin"))
14
+ throw new Error("bundle: ./bin not found — bundle replaces the tsc output in ./bin, so the project must build there");
15
+ const main = typeof pkg.main === "string" && pkg.main.length > 0 ? norm(pkg.main) : null;
16
+ const entry = o.entry ? norm(o.entry) : guessEntry(main);
17
+ if (!entry)
18
+ throw new Error(`bundle: can't tell the entry file from package.json "main" (${main ?? "missing"}) — set "bundle": { "entry": "src/Main.ts" } in deploy.json`);
19
+ if (!fs_1.default.existsSync(entry))
20
+ throw new Error(`bundle: entry file not found: ${entry}`);
21
+ const outFile = main ?? "bin/" + entry.replace(/^src\//, "").replace(SRC_EXT, ".js");
22
+ if (!outFile.startsWith("bin/") || outFile.split("/").includes(".."))
23
+ throw new Error(`bundle: package.json "main" must point inside ./bin (it is "${main}") — that is the file pm2 starts`);
24
+ let esbuild;
25
+ let parse;
26
+ try {
27
+ esbuild = require("esbuild");
28
+ parse = require("@babel/parser").parse;
29
+ }
30
+ catch (e) {
31
+ throw new Error("bundle: install the bundler in this project — npm i -D esbuild @babel/parser (" + (e?.message ?? e) + ")");
32
+ }
33
+ const result = await esbuild.build({
34
+ entryPoints: [entry],
35
+ outfile: path_1.default.resolve(outFile),
36
+ bundle: true,
37
+ platform: "node",
38
+ format: "cjs",
39
+ packages: "external",
40
+ keepNames: true,
41
+ minify: o.minify === true,
42
+ sourcemap: o.sourcemap !== false,
43
+ sourcesContent: false,
44
+ metafile: true,
45
+ write: false,
46
+ logLevel: "warning",
47
+ });
48
+ const inputs = Object.keys(result.metafile.inputs).map(norm).filter(f => !f.startsWith("node_modules/"));
49
+ const dropped = new Set();
50
+ for (const f of inputs) {
51
+ if (!f.startsWith("src/") || !SRC_EXT.test(f))
52
+ continue;
53
+ const base = "bin/" + f.slice(4).replace(SRC_EXT, "");
54
+ for (const ext of [".js", ".js.map", ".d.ts", ".d.ts.map"])
55
+ dropped.add(base + ext);
56
+ }
57
+ const stageDir = fs_1.default.mkdtempSync(path_1.default.join(os_1.default.tmpdir(), "bmfk-bundle-"));
58
+ try {
59
+ fs_1.default.cpSync("bin", path_1.default.join(stageDir, "bin"), {
60
+ recursive: true,
61
+ filter: src => !dropped.has(norm(path_1.default.relative(process.cwd(), src))),
62
+ });
63
+ for (const file of result.outputFiles) {
64
+ const target = path_1.default.join(stageDir, path_1.default.relative(process.cwd(), file.path));
65
+ fs_1.default.mkdirSync(path_1.default.dirname(target), { recursive: true });
66
+ fs_1.default.writeFileSync(target, file.contents);
67
+ }
68
+ const warnings = scanSources(inputs, entry, parse);
69
+ const leftovers = listFiles(path_1.default.join(stageDir, "bin"))
70
+ .map(f => "bin/" + norm(path_1.default.relative(path_1.default.join(stageDir, "bin"), f)))
71
+ .filter(f => f.endsWith(".js") && f !== outFile);
72
+ if (leftovers.length) {
73
+ const shown = leftovers.slice(0, 10).join(", ") + (leftovers.length > 10 ? `, … (${leftovers.length} in all)` : "");
74
+ warnings.push(`${leftovers.length} .js file(s) in ./bin are not in the bundle and ship as they are: ${shown} — `
75
+ + `if one of them requires the project's own modules it will fail on the server (they exist only inside the bundle now)`);
76
+ }
77
+ return { stageDir, outFile, modules: inputs.length, warnings };
78
+ }
79
+ catch (e) {
80
+ fs_1.default.rmSync(stageDir, { recursive: true, force: true });
81
+ throw e;
82
+ }
83
+ }
84
+ function guessEntry(main) {
85
+ if (!main || !main.startsWith("bin/"))
86
+ return null;
87
+ const base = "src/" + main.slice(4).replace(/\.(c|m)?js$/, "");
88
+ for (const ext of [".ts", ".tsx", ".mts", ".js"])
89
+ if (fs_1.default.existsSync(base + ext))
90
+ return base + ext;
91
+ return null;
92
+ }
93
+ function scanSources(files, entry, parse) {
94
+ const warnings = [];
95
+ const entryBase = path_1.default.resolve(entry).replace(SRC_EXT, "");
96
+ for (const file of files) {
97
+ if (file === entry || !SRC_EXT.test(file) || file.endsWith(".d.ts"))
98
+ continue;
99
+ let ast;
100
+ try {
101
+ ast = parse(fs_1.default.readFileSync(file, "utf-8"), {
102
+ sourceType: "module",
103
+ plugins: ["typescript", "decorators-legacy", ...(file.endsWith("x") ? ["jsx"] : [])],
104
+ });
105
+ }
106
+ catch (e) {
107
+ warnings.push(`${file} — not checked, can't parse: ${e?.message ?? e}`);
108
+ continue;
109
+ }
110
+ const fromEntry = new Set();
111
+ for (const st of ast.program.body) {
112
+ if (st.type !== "ImportDeclaration" || st.importKind === "type" || !st.source.value.startsWith("."))
113
+ continue;
114
+ const target = path_1.default.resolve(path_1.default.dirname(path_1.default.resolve(file)), st.source.value);
115
+ if (target.replace(SRC_EXT, "") !== entryBase && path_1.default.join(target, "index") !== entryBase)
116
+ continue;
117
+ for (const s of st.specifiers)
118
+ if (s.type !== "ImportSpecifier" || s.importKind !== "type")
119
+ fromEntry.add(s.local.name);
120
+ }
121
+ const reported = new Set();
122
+ const report = (msg) => { if (!reported.has(msg)) {
123
+ reported.add(msg);
124
+ warnings.push(msg);
125
+ } };
126
+ const visit = (node, loading) => {
127
+ if (!node || typeof node.type !== "string" || NOT_RUN.has(node.type))
128
+ return;
129
+ if (node.type === "Identifier") {
130
+ const line = node.loc?.start.line ?? 0;
131
+ if (node.name === "__dirname" || node.name === "__filename")
132
+ report(`${file}:${line} — __dirname/__filename: in the bundle this is the folder of the bundle (bin/), not of ${file}`);
133
+ else if (loading && fromEntry.has(node.name))
134
+ report(`${file}:${line} — "${node.name}" from ${entry} is read while modules load, before ${entry} has run: `
135
+ + `in the bundle that is undefined or a "Cannot access before initialization" crash — read it inside a function`);
136
+ return;
137
+ }
138
+ if (FUNCTIONS.has(node.type) || (CLASS_FIELDS.has(node.type) && !node.static))
139
+ loading = false;
140
+ for (const key of Object.keys(node)) {
141
+ if (NOT_CODE_KEYS.has(key))
142
+ continue;
143
+ if (!node.computed && (key === "key" || (key === "property" && MEMBER_ACCESS.has(node.type))))
144
+ continue;
145
+ const v = node[key];
146
+ if (Array.isArray(v))
147
+ for (const c of v)
148
+ visit(c, loading);
149
+ else if (v && typeof v === "object")
150
+ visit(v, loading);
151
+ }
152
+ };
153
+ for (const st of ast.program.body)
154
+ visit(st, true);
155
+ }
156
+ return warnings;
157
+ }
158
+ const NOT_RUN = new Set(["ImportDeclaration", "ExportSpecifier", "TSInterfaceDeclaration", "TSTypeAliasDeclaration",
159
+ "TSDeclareFunction", "TSDeclareMethod", "TSTypeAnnotation"]);
160
+ const NOT_CODE_KEYS = new Set(["loc", "start", "end", "range", "extra", "leadingComments", "trailingComments", "innerComments",
161
+ "typeAnnotation", "returnType", "typeParameters", "superTypeParameters", "typeArguments", "implements", "label"]);
162
+ const FUNCTIONS = new Set(["FunctionDeclaration", "FunctionExpression", "ArrowFunctionExpression", "ObjectMethod", "ClassMethod", "ClassPrivateMethod"]);
163
+ const CLASS_FIELDS = new Set(["ClassProperty", "ClassPrivateProperty", "ClassAccessorProperty"]);
164
+ const MEMBER_ACCESS = new Set(["MemberExpression", "OptionalMemberExpression"]);
165
+ function listFiles(dir) {
166
+ const out = [];
167
+ for (const e of fs_1.default.readdirSync(dir, { withFileTypes: true })) {
168
+ const full = path_1.default.join(dir, e.name);
169
+ if (e.isDirectory())
170
+ out.push(...listFiles(full));
171
+ else
172
+ out.push(full);
173
+ }
174
+ return out;
175
+ }
176
+ function norm(p) {
177
+ return p.replace(/\\/g, "/").replace(/^\.\//, "");
178
+ }
@@ -27,6 +27,8 @@ declare const _TConfig: {
27
27
  readonly ignoreDirectoryClean: false;
28
28
  readonly backup: true;
29
29
  readonly install: true;
30
+ readonly omitDev: false;
31
+ readonly $__omitDev_optional: true;
30
32
  readonly migrate: false;
31
33
  readonly $__migrate_optional: true;
32
34
  readonly pm2: true;
@@ -80,6 +82,7 @@ declare const _TConfig: {
80
82
  readonly $__secrets_optional: true;
81
83
  };
82
84
  export type IConfig = ValidationModel<typeof _TConfig>;
85
+ export declare function projectNameProblem(name: unknown): string | null;
83
86
  export declare const PROJECT_CONFIG_MODEL: {
84
87
  readonly name: "";
85
88
  readonly destination: "";
@@ -89,6 +92,8 @@ export declare const PROJECT_CONFIG_MODEL: {
89
92
  readonly ignoreDirectoryClean: false;
90
93
  readonly backup: true;
91
94
  readonly install: true;
95
+ readonly omitDev: false;
96
+ readonly $__omitDev_optional: true;
92
97
  readonly migrate: false;
93
98
  readonly $__migrate_optional: true;
94
99
  readonly pm2: true;
@@ -150,6 +155,7 @@ export declare const REQ_DEPLOYMENT_CONFIG: Req<void, Map<string, {
150
155
  ignoreDirectoryClean: boolean;
151
156
  backup: boolean;
152
157
  install: boolean;
158
+ omitDev?: boolean | undefined;
153
159
  migrate?: boolean | undefined;
154
160
  pm2: boolean;
155
161
  pm2_attributes?: string[] | undefined;
@@ -37,6 +37,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
37
37
  };
38
38
  Object.defineProperty(exports, "__esModule", { value: true });
39
39
  exports.ConfigService = exports.S_CONFIG_UPDATED = exports.REQ_DEPLOYMENT_CONFIG = exports.PROJECT_CONFIG_MODEL = void 0;
40
+ exports.projectNameProblem = projectNameProblem;
40
41
  const fs_1 = __importDefault(require("fs"));
41
42
  const path_1 = __importDefault(require("path"));
42
43
  const crypto_1 = __importDefault(require("crypto"));
@@ -69,6 +70,8 @@ const _TConfig = {
69
70
  ignoreDirectoryClean: false,
70
71
  backup: true,
71
72
  install: true,
73
+ omitDev: false,
74
+ $__omitDev_optional: true,
72
75
  migrate: false,
73
76
  $__migrate_optional: true,
74
77
  pm2: true,
@@ -121,6 +124,14 @@ const _TConfig = {
121
124
  },
122
125
  $__secrets_optional: true,
123
126
  };
127
+ const PROJECT_NAME = /^[a-z0-9][a-z0-9._-]{0,99}$/;
128
+ function projectNameProblem(name) {
129
+ if (typeof name !== "string" || name.length === 0)
130
+ return "the project has no \"name\"";
131
+ if (!PROJECT_NAME.test(name))
132
+ return `project name "${name}" is not allowed — lowercase letters, digits, ".", "_" and "-" only, starting with a letter or digit, up to 100 characters (e.g. "api.gateway.example.com")`;
133
+ return null;
134
+ }
124
135
  exports.PROJECT_CONFIG_MODEL = _TConfig;
125
136
  exports.REQ_DEPLOYMENT_CONFIG = new badmfck_signal_1.Req();
126
137
  exports.S_CONFIG_UPDATED = new badmfck_signal_1.default();
@@ -170,6 +181,11 @@ class ConfigService extends BaseService_1.BaseService {
170
181
  try {
171
182
  const file = fs_1.default.readFileSync(path_1.default.resolve(this.dir, f));
172
183
  const config = JSON.parse(file.toString());
184
+ const nameProblem = projectNameProblem(config?.name);
185
+ if (nameProblem) {
186
+ (0, LogService_1.logError)(`Deployer: ${f} ignored — ${nameProblem}`);
187
+ continue;
188
+ }
173
189
  temp.set(config.name, config);
174
190
  }
175
191
  catch (e) {
@@ -188,7 +204,7 @@ class ConfigService extends BaseService_1.BaseService {
188
204
  (0, LogService_1.logWarn)("Configurations updated");
189
205
  const plain = Array.from(temp.values()).filter((c) => c?.name && !PasswordHash_1.PasswordHash.isHash(c.token)).map((c) => c.name);
190
206
  if (plain.length)
191
- (0, LogService_1.logError)(`Deployer: project token stored as plain text for ${plain.map(n => '"' + n + '"').join(", ")} — these projects can't be deployed; store a hash instead: npx badmfck project-token --hash`);
207
+ (0, LogService_1.logError)(`Deployer: project token stored as plain text for ${plain.map(n => '"' + n + '"').join(", ")} — these projects can't be deployed; store a hash instead: npx bmfk project-token --hash`);
192
208
  }
193
209
  }
194
210
  }