@seedcord/core 0.1.0-next.5 → 0.1.0-next.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/dist/{AutocompleteOptions-eB87SZ4a.d.mts → AutocompleteOptions-DLp_B8as.d.mts} +66 -124
  2. package/dist/HmrModuleHandler-3sNgKHdf.mjs +163 -0
  3. package/dist/HmrModuleHandler-3sNgKHdf.mjs.map +1 -0
  4. package/dist/HmrModuleHandler-CTBng7wV.cjs +170 -0
  5. package/dist/HmrModuleHandler-CTBng7wV.cjs.map +1 -0
  6. package/dist/Plugin-3rlH0uxH.d.mts +620 -0
  7. package/dist/Plugin-Cgp1a0uQ.cjs +123 -0
  8. package/dist/Plugin-Cgp1a0uQ.cjs.map +1 -0
  9. package/dist/Plugin-j9GYdroS.mjs +106 -0
  10. package/dist/Plugin-j9GYdroS.mjs.map +1 -0
  11. package/dist/{permissions-DQL5ViZn.cjs → Silence-DiP95iwD.cjs} +54 -305
  12. package/dist/Silence-DiP95iwD.cjs.map +1 -0
  13. package/dist/{permissions-SokZLJMj.mjs → Silence-dbC2slOB.mjs} +47 -238
  14. package/dist/Silence-dbC2slOB.mjs.map +1 -0
  15. package/dist/basic-D7bDlgSP.d.mts +10 -0
  16. package/dist/devChannel-CQU7hq7Q.mjs +14 -0
  17. package/dist/devChannel-CQU7hq7Q.mjs.map +1 -0
  18. package/dist/devChannel-CoCmAVDx.cjs +26 -0
  19. package/dist/devChannel-CoCmAVDx.cjs.map +1 -0
  20. package/dist/hmr.index.cjs +2 -164
  21. package/dist/hmr.index.mjs +2 -162
  22. package/dist/index-Dueqztyy.d.mts +142 -0
  23. package/dist/index.cjs +53 -72
  24. package/dist/index.cjs.map +1 -1
  25. package/dist/index.d.mts +7 -4
  26. package/dist/index.mjs +9 -35
  27. package/dist/index.mjs.map +1 -1
  28. package/dist/internal.index.cjs +267 -89
  29. package/dist/internal.index.cjs.map +1 -1
  30. package/dist/internal.index.d.mts +68 -3
  31. package/dist/internal.index.mjs +218 -48
  32. package/dist/internal.index.mjs.map +1 -1
  33. package/dist/node-internal.index.cjs +716 -0
  34. package/dist/node-internal.index.cjs.map +1 -0
  35. package/dist/node-internal.index.d.cts +1 -0
  36. package/dist/node-internal.index.d.mts +261 -0
  37. package/dist/node-internal.index.mjs +706 -0
  38. package/dist/node-internal.index.mjs.map +1 -0
  39. package/dist/phases-BfpAG6w3.mjs +31 -0
  40. package/dist/phases-BfpAG6w3.mjs.map +1 -0
  41. package/dist/phases-C_BGNyVo.cjs +43 -0
  42. package/dist/phases-C_BGNyVo.cjs.map +1 -0
  43. package/dist/plugin.index.cjs +4 -0
  44. package/dist/plugin.index.d.cts +1 -0
  45. package/dist/plugin.index.d.mts +3 -0
  46. package/dist/plugin.index.mjs +3 -0
  47. package/dist/publishDefault-CCf1azzW.mjs +264 -0
  48. package/dist/publishDefault-CCf1azzW.mjs.map +1 -0
  49. package/dist/publishDefault-l0NQ-SHo.cjs +353 -0
  50. package/dist/publishDefault-l0NQ-SHo.cjs.map +1 -0
  51. package/dist/subscribers-B1G6_LlK.cjs +517 -0
  52. package/dist/subscribers-B1G6_LlK.cjs.map +1 -0
  53. package/dist/subscribers-DYqFVP1X.mjs +480 -0
  54. package/dist/subscribers-DYqFVP1X.mjs.map +1 -0
  55. package/package.json +25 -13
  56. package/dist/hmr.index.cjs.map +0 -1
  57. package/dist/hmr.index.mjs.map +0 -1
  58. package/dist/is-never-Ddaba1Su.d.mts +0 -58
  59. package/dist/node.index.cjs +0 -521
  60. package/dist/node.index.cjs.map +0 -1
  61. package/dist/node.index.d.cts +0 -1
  62. package/dist/node.index.d.mts +0 -2391
  63. package/dist/node.index.mjs +0 -513
  64. package/dist/node.index.mjs.map +0 -1
  65. package/dist/permissions-DQL5ViZn.cjs.map +0 -1
  66. package/dist/permissions-SokZLJMj.mjs.map +0 -1
@@ -0,0 +1,716 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+ const require_rolldown_runtime = require('./rolldown-runtime-C_NdSu1c.cjs');
3
+ const require_publishDefault = require('./publishDefault-l0NQ-SHo.cjs');
4
+ const require_phases = require('./phases-C_BGNyVo.cjs');
5
+ const require_subscribers = require('./subscribers-B1G6_LlK.cjs');
6
+ const require_Plugin = require('./Plugin-Cgp1a0uQ.cjs');
7
+ const require_HmrModuleHandler = require('./HmrModuleHandler-CTBng7wV.cjs');
8
+ let _seedcord_errors = require("@seedcord/errors");
9
+ let _seedcord_errors_internal = require("@seedcord/errors/internal");
10
+ let _seedcord_logger = require("@seedcord/logger");
11
+ let chalk = require("chalk");
12
+ chalk = require_rolldown_runtime.__toESM(chalk, 1);
13
+ let envapt = require("envapt");
14
+ let node_http = require("node:http");
15
+ let _seedcord_utils_node = require("@seedcord/utils/node");
16
+
17
+ //#region src/node/Lifecycle/withTimeout.ts
18
+ async function raceTimer(work, timeoutMs, onTimeout) {
19
+ let timer;
20
+ try {
21
+ await Promise.race([work, new Promise((resolve, reject) => {
22
+ timer = setTimeout(() => onTimeout(resolve, reject), timeoutMs);
23
+ })]);
24
+ } finally {
25
+ if (timer) clearTimeout(timer);
26
+ }
27
+ }
28
+ /** @internal rejects with a `LifecycleTaskTimeout` when `run` outlasts the bound. */
29
+ function withTimeout(name, run, timeoutMs) {
30
+ return raceTimer(run(), timeoutMs, (_, reject) => {
31
+ reject(new _seedcord_errors_internal.SeedcordError(_seedcord_errors.SeedcordErrorCode.LifecycleTaskTimeout, [name, timeoutMs]));
32
+ });
33
+ }
34
+ /** @internal resolves when `work` settles or the bound elapses, whichever is first. */
35
+ function settleWithin(work, timeoutMs) {
36
+ return raceTimer(work, timeoutMs, (resolve) => resolve());
37
+ }
38
+
39
+ //#endregion
40
+ //#region src/node/Lifecycle/CoordinatedLifecycle.ts
41
+ /**
42
+ * Base for the startup and shutdown coordinators. Runs phase-ordered tasks off a per-phase map.
43
+ *
44
+ * @internal
45
+ */
46
+ var CoordinatedLifecycle = class {
47
+ phaseOrder;
48
+ phaseEnum;
49
+ logger;
50
+ tasksMap = /* @__PURE__ */ new Map();
51
+ constructor(loggerName, phaseOrder, phaseEnum) {
52
+ this.phaseOrder = phaseOrder;
53
+ this.phaseEnum = phaseEnum;
54
+ this.logger = new _seedcord_logger.Logger(loggerName, { channel: "lifecycle" });
55
+ this.phaseOrder.forEach((phase) => this.tasksMap.set(phase, []));
56
+ }
57
+ /**
58
+ * Adds a task to `phase`. Tasks run in phase order, each bounded by `timeoutMs`.
59
+ *
60
+ * @param phase - The lifecycle phase to add the task to
61
+ * @param taskName - Unique name for the task, used for logging and removal
62
+ * @param task - Async function to execute during the phase
63
+ * @param timeoutMs - Maximum time allowed for task execution in milliseconds
64
+ */
65
+ addTask(phase, taskName, task, timeoutMs) {
66
+ if (!this.canAddTask()) return;
67
+ const tasks = this.tasksMap.get(phase);
68
+ if (!tasks) throw new _seedcord_errors_internal.SeedcordError(_seedcord_errors.SeedcordErrorCode.LifecycleUnknownPhase, [phase]);
69
+ tasks.push({
70
+ name: taskName,
71
+ task,
72
+ timeout: timeoutMs
73
+ });
74
+ this.logger.debug(`${chalk.default.italic("Added")} ${this.getTaskType()} task ${chalk.default.bold.cyan(taskName)} to phase ${chalk.default.bold.magenta(this.phaseEnum[phase])}`);
75
+ }
76
+ /**
77
+ * Removes a lifecycle task from a specific phase.
78
+ *
79
+ * @param phase - The lifecycle phase to remove the task from
80
+ * @param taskName - Name of the task to remove
81
+ * @returns True if the task was found and removed, false otherwise
82
+ */
83
+ removeTask(phase, taskName) {
84
+ if (!this.canRemoveTask()) return false;
85
+ const tasks = this.tasksMap.get(phase);
86
+ if (!tasks) return false;
87
+ const initialLength = tasks.length;
88
+ const filteredTasks = tasks.filter((task) => task.name !== taskName);
89
+ this.tasksMap.set(phase, filteredTasks);
90
+ const removed = initialLength !== filteredTasks.length;
91
+ if (removed) this.logger.debug(`${chalk.default.italic("Removed")} ${this.getTaskType()} task ${chalk.default.bold.cyan(taskName)} from phase ${chalk.default.bold.magenta(this.phaseEnum[phase])}`);
92
+ return removed;
93
+ }
94
+ async runPhase(phase) {
95
+ const tasks = this.tasksMap.get(phase) ?? [];
96
+ if (tasks.length === 0) {
97
+ this.logger.debug(`No tasks to run in phase ${chalk.default.bold.magenta(this.phaseEnum[phase])}`);
98
+ return;
99
+ }
100
+ this.logger.info(`${chalk.default.bold.yellow("Running")} ${this.getTaskType()} phase ${chalk.default.bold.magenta(this.phaseEnum[phase])} with ${chalk.default.bold.cyan(tasks.length)} tasks`);
101
+ const failures = (await this.executeTasksInPhase(phase, tasks)).filter((r) => r.status === "rejected").length;
102
+ if (failures > 0) throw new _seedcord_errors_internal.SeedcordError(_seedcord_errors.SeedcordErrorCode.LifecyclePhaseFailures, [this.phaseEnum[phase], failures]);
103
+ this.logger.info(`Phase ${chalk.default.bold.magenta(this.phaseEnum[phase])} ${chalk.default.bold.green("completed successfully")}`);
104
+ }
105
+ async runTaskWithTimeout(phase, task) {
106
+ this.logger.info(`${chalk.default.italic("Starting")} task ${chalk.default.bold.cyan(task.name)} in phase ${chalk.default.bold.magenta(this.phaseEnum[phase])}`);
107
+ try {
108
+ await withTimeout(task.name, task.task, task.timeout);
109
+ this.logger.info(`${chalk.default.italic("Completed")} task ${chalk.default.bold.cyan(task.name)} in phase ${chalk.default.bold.magenta(this.phaseEnum[phase])}`);
110
+ } catch (error) {
111
+ this.logger.error(`${chalk.default.italic("Failed")} task ${chalk.default.bold.cyan(task.name)} in phase ${chalk.default.bold.magenta(this.phaseEnum[phase])}:`, error);
112
+ throw error;
113
+ }
114
+ }
115
+ };
116
+
117
+ //#endregion
118
+ //#region src/node/Lifecycle/CoordinatedShutdown.ts
119
+ const PHASE_ORDER$1 = [
120
+ 1,
121
+ 2,
122
+ 3,
123
+ 4
124
+ ];
125
+ const LOG_FLUSH_DELAY_MS = 3e3;
126
+ /**
127
+ * Runs registered shutdown tasks across `ShutdownPhase` in order. Registers SIGINT and SIGTERM
128
+ * handlers. Tasks within a phase run in parallel.
129
+ */
130
+ var CoordinatedShutdown = class extends CoordinatedLifecycle {
131
+ isShuttingDown = false;
132
+ hasShutdown = false;
133
+ exitCode = 0;
134
+ onSigTerm = null;
135
+ onSigInt = null;
136
+ startupGate;
137
+ constructor() {
138
+ super("Shutdown", PHASE_ORDER$1, require_phases.ShutdownPhase);
139
+ this.registerSignalHandlers();
140
+ }
141
+ canAddTask() {
142
+ return true;
143
+ }
144
+ canRemoveTask() {
145
+ return true;
146
+ }
147
+ getTaskType() {
148
+ return "shutdown";
149
+ }
150
+ async executeTasksInPhase(phase, tasks) {
151
+ const promises = tasks.map((task) => this.runTaskWithTimeout(phase, task));
152
+ return Promise.allSettled(promises);
153
+ }
154
+ registerSignalHandlers() {
155
+ this.onSigTerm = () => {
156
+ this.logger.info(`Received ${chalk.default.yellow.bold("SIGTERM")} signal`);
157
+ this.run(0);
158
+ };
159
+ this.onSigInt = () => {
160
+ this.logger.info(`Received ${chalk.default.yellow.bold("SIGINT")} signal`);
161
+ this.run(0);
162
+ };
163
+ process.on("SIGTERM", this.onSigTerm);
164
+ process.on("SIGINT", this.onSigInt);
165
+ }
166
+ /** @internal */
167
+ removeSignalHandlers() {
168
+ if (this.onSigTerm) {
169
+ process.off("SIGTERM", this.onSigTerm);
170
+ this.onSigTerm = null;
171
+ }
172
+ if (this.onSigInt) {
173
+ process.off("SIGINT", this.onSigInt);
174
+ this.onSigInt = null;
175
+ }
176
+ }
177
+ /** @internal run() awaits this so boot finishes registering its dispose tasks first */
178
+ gateOnStartup(settled) {
179
+ this.startupGate = settled;
180
+ }
181
+ /**
182
+ * Adds a shutdown-phase task.
183
+ *
184
+ * @param phase - The shutdown phase to run the task in.
185
+ * @param taskName - A descriptive name for the task.
186
+ * @param task - The async function to run.
187
+ * @param timeoutMs - Task timeout in ms. {@default `5000` }
188
+ */
189
+ addTask(phase, taskName, task, timeoutMs = 5e3) {
190
+ super.addTask(phase, taskName, task, timeoutMs);
191
+ }
192
+ /** Removes a shutdown-phase task, returning whether one was removed. */
193
+ removeTask(phase, taskName) {
194
+ return super.removeTask(phase, taskName);
195
+ }
196
+ /**
197
+ * Runs registered tasks across shutdown phases in `ShutdownPhase` order.
198
+ * Tasks within each phase run in parallel.
199
+ *
200
+ * @param exitCode - Process exit code. {@default `0` }
201
+ * @param exitProcess - Whether to exit the process after shutdown. {@default `true` }
202
+ * @example
203
+ * ```typescript
204
+ * shutdown.addTask(ShutdownPhase.Disconnect, 'database', () => db.disconnect(), 5000);
205
+ * await shutdown.run(0);
206
+ * ```
207
+ */
208
+ async run(exitCode = 0, exitProcess = true) {
209
+ this.removeSignalHandlers();
210
+ if (this.hasShutdown || this.isShuttingDown) {
211
+ this.logger.warn("Shutdown sequence already ran or is in progress");
212
+ return;
213
+ }
214
+ this.isShuttingDown = true;
215
+ this.exitCode = exitCode;
216
+ this.logger.info(`${chalk.default.bold.yellow("Starting")} coordinated shutdown with exit code ${chalk.default.bold.cyan(exitCode)}`);
217
+ try {
218
+ if (this.startupGate) await this.startupGate;
219
+ const failures = [];
220
+ for (const phase of PHASE_ORDER$1) try {
221
+ await this.runPhase(phase);
222
+ } catch (error) {
223
+ failures.push(error);
224
+ }
225
+ if (failures.length > 0) this.logger.error(`${chalk.default.bold.red("Coordinated shutdown failed")}`, ...failures);
226
+ else this.logger.info(`${chalk.default.bold.green("Coordinated shutdown completed")} successfully`);
227
+ } finally {
228
+ this.hasShutdown = true;
229
+ if (exitProcess) {
230
+ this.logger.info(`${chalk.default.bold.red("Exiting")} process with code ${chalk.default.bold.cyan(this.exitCode)}`);
231
+ setTimeout(() => {
232
+ process.exit(this.exitCode);
233
+ }, LOG_FLUSH_DELAY_MS);
234
+ } else {
235
+ this.logger.info(`${chalk.default.bold.yellow("Skipping")} process exit (dev mode)`);
236
+ this.isShuttingDown = false;
237
+ }
238
+ }
239
+ }
240
+ };
241
+
242
+ //#endregion
243
+ //#region src/node/Lifecycle/CoordinatedStartup.ts
244
+ const PHASE_ORDER = [
245
+ 1,
246
+ 2,
247
+ 3
248
+ ];
249
+ /**
250
+ * Runs registered startup tasks across `StartupPhase` in order. Tasks within a phase run in parallel.
251
+ */
252
+ var CoordinatedStartup = class extends CoordinatedLifecycle {
253
+ isStartingUp = false;
254
+ hasStarted = false;
255
+ constructor() {
256
+ super("Startup", PHASE_ORDER, require_phases.StartupPhase);
257
+ }
258
+ /**
259
+ * Adds a startup-phase task.
260
+ *
261
+ * @param phase - The startup phase to run the task in.
262
+ * @param taskName - A descriptive name for the task.
263
+ * @param task - The async function to run.
264
+ * @param timeoutMs - Task timeout in ms. {@default `10000` }
265
+ */
266
+ addTask(phase, taskName, task, timeoutMs = 1e4) {
267
+ super.addTask(phase, taskName, task, timeoutMs);
268
+ }
269
+ canAddTask() {
270
+ if (this.hasStarted) throw new _seedcord_errors_internal.SeedcordError(_seedcord_errors.SeedcordErrorCode.LifecycleAddAfterCompletion);
271
+ if (this.isStartingUp) throw new _seedcord_errors_internal.SeedcordError(_seedcord_errors.SeedcordErrorCode.LifecycleAddDuringRun);
272
+ return true;
273
+ }
274
+ canRemoveTask() {
275
+ if (this.isStartingUp) throw new _seedcord_errors_internal.SeedcordError(_seedcord_errors.SeedcordErrorCode.LifecycleRemoveDuringRun);
276
+ return true;
277
+ }
278
+ getTaskType() {
279
+ return "startup";
280
+ }
281
+ async executeTasksInPhase(phase, tasks) {
282
+ const promises = tasks.map((task) => this.runTaskWithTimeout(phase, task));
283
+ return Promise.allSettled(promises);
284
+ }
285
+ /**
286
+ * Runs the registered tasks across startup phases in `StartupPhase` order. Each phase completes
287
+ * before the next begins, and tasks within a phase run concurrently.
288
+ *
289
+ * @throws {@link SeedcordError} if a startup task throws.
290
+ */
291
+ async run() {
292
+ if (this.hasStarted) {
293
+ this.logger.warn("Startup sequence has already completed");
294
+ return;
295
+ }
296
+ if (this.isStartingUp) {
297
+ this.logger.warn("Startup sequence already in progress");
298
+ return;
299
+ }
300
+ this.isStartingUp = true;
301
+ this.logger.info(`${chalk.default.bold.green("Starting")} coordinated startup sequence`);
302
+ try {
303
+ for (const phase of PHASE_ORDER) {
304
+ if (!this.isStartingUp) {
305
+ this.logger.warn("Startup sequence aborted");
306
+ return;
307
+ }
308
+ await this.runPhase(phase);
309
+ }
310
+ this.hasStarted = true;
311
+ this.logger.info(`${chalk.default.bold.green("Coordinated startup completed")} successfully`);
312
+ } catch (error) {
313
+ if (!this.isStartingUp) {
314
+ this.logger.warn("Startup sequence aborted during error handling");
315
+ return;
316
+ }
317
+ this.logger.error(`${chalk.default.bold.red("Coordinated startup failed")}`);
318
+ throw error;
319
+ } finally {
320
+ this.isStartingUp = false;
321
+ }
322
+ }
323
+ async runTaskWithTimeout(phase, task) {
324
+ this.logger.info(`${chalk.default.italic("Starting")} task ${chalk.default.bold.cyan(task.name)} in phase ${chalk.default.bold.magenta(require_phases.StartupPhase[phase])}`);
325
+ try {
326
+ await withTimeout(task.name, task.task, task.timeout);
327
+ this.logger.info(`${chalk.default.italic("Completed")} task ${chalk.default.bold.cyan(task.name)} in phase ${chalk.default.bold.magenta(require_phases.StartupPhase[phase])}`);
328
+ } catch (error) {
329
+ if (!this.isStartingUp) return;
330
+ this.logger.error(`${chalk.default.italic("Failed")} task ${chalk.default.bold.cyan(task.name)} in phase ${chalk.default.bold.magenta(require_phases.StartupPhase[phase])}:`, error);
331
+ throw error;
332
+ }
333
+ }
334
+ /**
335
+ * Aborts the startup sequence if it is currently running.
336
+ */
337
+ abort() {
338
+ if (!this.isStartingUp) return;
339
+ this.isStartingUp = false;
340
+ this.logger.warn("Aborting coordinated startup sequence");
341
+ }
342
+ get isReady() {
343
+ return this.hasStarted;
344
+ }
345
+ get isRunning() {
346
+ return this.isStartingUp;
347
+ }
348
+ };
349
+
350
+ //#endregion
351
+ //#region src/node/HealthCheck.ts
352
+ const HTTP_OK = 200;
353
+ const HTTP_NOT_FOUND = 404;
354
+ const DEFAULT_HEALTH_CHECK_PORT = 6967;
355
+ const DEFAULT_HEALTH_CHECK_PATH = "/health";
356
+ /**
357
+ * HTTP server answering `GET` on the configured path with a JSON `{ status, timestamp }` body.
358
+ */
359
+ var HealthCheck = class HealthCheck {
360
+ /** @internal */
361
+ logger = new _seedcord_logger.Logger("HealthCheck", { channel: "health" });
362
+ port;
363
+ path;
364
+ host;
365
+ server;
366
+ constructor(shutdown, options) {
367
+ this.port = options?.port ?? DEFAULT_HEALTH_CHECK_PORT;
368
+ this.path = options?.path ?? DEFAULT_HEALTH_CHECK_PATH;
369
+ this.host = options?.host;
370
+ shutdown.addTask(2, "stop-healthcheck-server", () => this.stop());
371
+ }
372
+ /**
373
+ * Resolves the `healthCheck` option. `undefined` and `true` build the defaults, an object uses
374
+ * its config, `false` returns `undefined`.
375
+ */
376
+ static fromOption(shutdown, option) {
377
+ if (option === false) return void 0;
378
+ return new HealthCheck(shutdown, typeof option === "object" ? option : void 0);
379
+ }
380
+ /**
381
+ * Starts the health check server.
382
+ * @returns Promise that resolves when the server is listening
383
+ * @internal
384
+ */
385
+ async init() {
386
+ return new Promise((resolve, reject) => {
387
+ const server = (0, node_http.createServer)((req, res) => {
388
+ if (req.method === "GET" && req.url === this.path) {
389
+ res.writeHead(HTTP_OK, { "Content-Type": "application/json" });
390
+ res.end(JSON.stringify({
391
+ status: "ok",
392
+ timestamp: Date.now()
393
+ }));
394
+ } else {
395
+ res.writeHead(HTTP_NOT_FOUND, { "Content-Type": "application/json" });
396
+ res.end(JSON.stringify({ status: "not found" }));
397
+ }
398
+ });
399
+ this.server = server;
400
+ const onListenError = (err) => reject(err);
401
+ server.on("error", onListenError);
402
+ server.once("listening", () => {
403
+ server.removeListener("error", onListenError);
404
+ server.on("error", (err) => this.logger.error("Health check server error", err));
405
+ const address = this.host ?? "localhost";
406
+ this.logger.info(`${_seedcord_logger.paint.mint.bold("✔︎")} Health check server listening on ${_seedcord_logger.paint.sky(`http://${address}:${this.port}${this.path}`)}`);
407
+ resolve();
408
+ });
409
+ if (this.host) {
410
+ this.logger.debug(`Binding health check server to ${this.host}`);
411
+ server.listen(this.port, this.host);
412
+ } else {
413
+ this.logger.debug("Binding health check server to all interfaces");
414
+ server.listen(this.port);
415
+ }
416
+ });
417
+ }
418
+ /**
419
+ * Stops the health check server.
420
+ * @internal
421
+ */
422
+ stop() {
423
+ const server = this.server;
424
+ if (!server?.listening) return Promise.resolve();
425
+ return new Promise((resolve, reject) => {
426
+ server.close((err) => {
427
+ if (err) {
428
+ reject(err);
429
+ return;
430
+ }
431
+ this.logger.info(_seedcord_logger.paint.coral.bold("Health check server stopped"));
432
+ resolve();
433
+ });
434
+ });
435
+ }
436
+ };
437
+
438
+ //#endregion
439
+ //#region src/node/Pluggable.ts
440
+ const RESERVED_KEYS = new Set(_seedcord_logger.FRAMEWORK_CHANNELS);
441
+ /**
442
+ * Base class for objects that can have plugins attached.
443
+ *
444
+ * Plugins are attached during configuration and initialized during startup, sequentially in attach
445
+ * order within each phase. Not constructed directly, the host is a transport `Seedcord` class.
446
+ */
447
+ var Pluggable = class Pluggable {
448
+ /** @see {@link CoordinatedShutdown} */
449
+ shutdown;
450
+ /** @see {@link CoordinatedStartup} */
451
+ startup;
452
+ isInitialized = false;
453
+ startFailed = false;
454
+ plugins = [];
455
+ pluginLogger = new _seedcord_logger.Logger("Plugins", { channel: "plugins" });
456
+ attachments = [];
457
+ completedInits = /* @__PURE__ */ new Set();
458
+ disposePhases = /* @__PURE__ */ new Set();
459
+ pluginTasksRegistered = false;
460
+ static isInstantiated = false;
461
+ static liveShutdown;
462
+ constructor(shutdown, startup) {
463
+ if (Pluggable.isInstantiated) {
464
+ shutdown.removeSignalHandlers();
465
+ throw new _seedcord_errors_internal.SeedcordError(_seedcord_errors.SeedcordErrorCode.CoreSingletonViolation);
466
+ }
467
+ Pluggable.isInstantiated = true;
468
+ Pluggable.liveShutdown = shutdown;
469
+ this.shutdown = shutdown;
470
+ this.startup = startup;
471
+ }
472
+ /** @internal */
473
+ async init() {
474
+ if (this.isInitialized) return this;
475
+ if (this.startFailed) throw new _seedcord_errors_internal.SeedcordError(_seedcord_errors.SeedcordErrorCode.LifecycleRestartAfterFailure);
476
+ this.registerPluginTasks();
477
+ const startupSettled = Promise.withResolvers();
478
+ this.shutdown.gateOnStartup(startupSettled.promise);
479
+ try {
480
+ await this.startup.run();
481
+ } catch (caught) {
482
+ await this.rollback();
483
+ throw caught;
484
+ } finally {
485
+ startupSettled.resolve();
486
+ }
487
+ this.isInitialized = true;
488
+ return this;
489
+ }
490
+ pluginCapabilities() {
491
+ return {};
492
+ }
493
+ pluginStore() {
494
+ return this.config.store ?? this.rateLimiter;
495
+ }
496
+ /** @internal codegen reads these to emit the `Core` augmentation */
497
+ get pluginKeys() {
498
+ return this.attachments.map((attachment) => attachment.key);
499
+ }
500
+ /** @internal releases the signal handlers and clears the singleton so the next host can construct */
501
+ static reset() {
502
+ Pluggable.liveShutdown?.removeSignalHandlers();
503
+ Pluggable.liveShutdown = void 0;
504
+ Pluggable.isInstantiated = false;
505
+ }
506
+ /**
507
+ * Attaches a plugin to this instance.
508
+ *
509
+ * The plugin initializes during startup, after every plugin attached before it, and becomes
510
+ * available as a property on `core`. `seedcord codegen` writes the `Core` augmentation that
511
+ * types it.
512
+ *
513
+ * A plugin declaring a `transport` or `runtime` this host does not run is a compile error on
514
+ * this call. An edge host takes no plugins at all. A plugin constructor narrowing its first
515
+ * parameter past `CoreBase` is a compile error here too. Read the transport `Core` off `this.core`.
516
+ *
517
+ * @typeParam Key - The property name for accessing the plugin
518
+ * @typeParam Ctor - The plugin constructor type
519
+ * @param key - Property name to access the plugin instance
520
+ * @param Plugin - Plugin constructor class
521
+ * @param args - Additional arguments to pass to the plugin constructor
522
+ * @returns This instance with the plugin attached as a typed property
523
+ * @throws A **SeedcordError** When called after initialization or if key already exists or is reserved
524
+ * @example
525
+ * ```typescript
526
+ * seedcord.attach('db', Mongoose, { uri: 'mongodb://...', name: 'seedcord', dir: ... })
527
+ * ```
528
+ */
529
+ attach(key, Plugin, ...args) {
530
+ if (this.isInitialized) throw new _seedcord_errors_internal.SeedcordError(_seedcord_errors.SeedcordErrorCode.CorePluginAfterInit);
531
+ if (RESERVED_KEYS.has(key)) throw new _seedcord_errors_internal.SeedcordError(_seedcord_errors.SeedcordErrorCode.CorePluginReservedChannel, [key]);
532
+ if (key in this) throw new _seedcord_errors_internal.SeedcordError(_seedcord_errors.SeedcordErrorCode.CorePluginKeyExists, [key]);
533
+ const instance = new Plugin(this, ...args);
534
+ this.plugins.push(instance);
535
+ this.attachments.push({
536
+ key,
537
+ instance
538
+ });
539
+ this.finalizeContext(key, instance);
540
+ return Object.assign(this, { [key]: instance });
541
+ }
542
+ finalizeContext(key, instance) {
543
+ const caps = this.pluginCapabilities();
544
+ const readToken = () => this.pluginCapabilities().token;
545
+ instance.logger.setChannel(key);
546
+ require_Plugin.finalizePluginContext(instance, {
547
+ config: this.config,
548
+ store: this.pluginStore(),
549
+ client: caps.client,
550
+ get token() {
551
+ return readToken();
552
+ },
553
+ rest: caps.rest
554
+ });
555
+ }
556
+ registerPluginTasks() {
557
+ if (this.pluginTasksRegistered) return;
558
+ this.pluginTasksRegistered = true;
559
+ const groups = /* @__PURE__ */ new Map();
560
+ for (const attachment of this.attachments) {
561
+ const phase = require_Plugin.resolvedLifecycleSpecOf(attachment.instance).init.phase;
562
+ const group = groups.get(phase) ?? [];
563
+ group.push(attachment);
564
+ groups.set(phase, group);
565
+ }
566
+ for (const [phase, group] of groups) {
567
+ if (phase === 3) continue;
568
+ const budget = group.reduce((sum, a) => sum + require_Plugin.resolvedLifecycleSpecOf(a.instance).init.timeout, 0);
569
+ this.startup.addTask(phase, "plugins-init", () => this.runInits(group), budget);
570
+ }
571
+ this.registerReadyTask(groups.get(3) ?? []);
572
+ }
573
+ async runInits(group) {
574
+ for (const attachment of group) {
575
+ const { key, instance } = attachment;
576
+ const spec = require_Plugin.resolvedLifecycleSpecOf(instance);
577
+ instance.logger.utils.initialization(key, "start");
578
+ await withTimeout(`Plugin (${key})`, () => instance.init(), spec.init.timeout);
579
+ instance.logger.utils.initialization(key, "end");
580
+ this.completedInits.add(attachment);
581
+ if (instance.dispose) this.registerDisposeTask(spec.dispose.phase);
582
+ }
583
+ }
584
+ registerReadyTask(readyInits) {
585
+ const steps = this.attachments.reduce((acc, a) => {
586
+ const ready = a.instance.ready?.bind(a.instance);
587
+ if (ready) acc.push({
588
+ key: a.key,
589
+ run: ready,
590
+ timeout: require_Plugin.resolvedLifecycleSpecOf(a.instance).ready.timeout
591
+ });
592
+ return acc;
593
+ }, []);
594
+ if (readyInits.length === 0 && steps.length === 0) return;
595
+ const budget = readyInits.reduce((sum, a) => sum + require_Plugin.resolvedLifecycleSpecOf(a.instance).init.timeout, 0) + steps.reduce((sum, step) => sum + step.timeout, 0);
596
+ this.startup.addTask(3, "plugins-ready", async () => {
597
+ await this.runInits(readyInits);
598
+ for (const step of steps) await withTimeout(`Plugin:${step.key}:ready`, step.run, step.timeout);
599
+ }, budget);
600
+ }
601
+ registerDisposeTask(phase) {
602
+ if (this.disposePhases.has(phase)) return;
603
+ this.disposePhases.add(phase);
604
+ const budget = this.attachments.reduce((sum, a) => {
605
+ const spec = require_Plugin.resolvedLifecycleSpecOf(a.instance);
606
+ return a.instance.dispose && spec.dispose.phase === phase ? sum + spec.dispose.timeout : sum;
607
+ }, 0);
608
+ this.shutdown.addTask(phase, "plugins-dispose", () => this.runDisposals(phase), budget);
609
+ }
610
+ async runDisposals(phase) {
611
+ const failures = [];
612
+ await this.disposeCompleted(phase, (caught) => failures.push(caught));
613
+ if (failures.length === 1) throw failures[0];
614
+ if (failures.length > 1) throw new AggregateError(failures, "plugin dispose failures");
615
+ }
616
+ async disposeCompleted(phase, onError) {
617
+ for (const attachment of [...this.attachments].reverse()) {
618
+ if (!this.completedInits.has(attachment)) continue;
619
+ const dispose = attachment.instance.dispose?.bind(attachment.instance);
620
+ if (!dispose) continue;
621
+ const spec = require_Plugin.resolvedLifecycleSpecOf(attachment.instance);
622
+ if (phase !== void 0 && spec.dispose.phase !== phase) continue;
623
+ try {
624
+ await withTimeout(`Plugin:${attachment.key}:dispose`, dispose, spec.dispose.timeout);
625
+ } catch (caught) {
626
+ onError(caught);
627
+ }
628
+ }
629
+ }
630
+ async rollback() {
631
+ this.startFailed = true;
632
+ await this.disposeCompleted(void 0, (caught) => this.pluginLogger.warn("rollback dispose failed", caught));
633
+ this.completedInits.clear();
634
+ }
635
+ };
636
+
637
+ //#endregion
638
+ //#region src/node/subscribers/SubscriberLoader.ts
639
+ /**
640
+ * Loads subscribers off the filesystem into a {@link Bus} and stores their hot-reload wiring. Node
641
+ * only, a bundled isolate registers from the manifest instead.
642
+ *
643
+ * @internal
644
+ */
645
+ var SubscriberLoader = class {
646
+ bus;
647
+ directory;
648
+ isInitialized = false;
649
+ hmrHandler;
650
+ constructor(bus, directory) {
651
+ this.bus = bus;
652
+ this.directory = directory;
653
+ if (!this.directory) return;
654
+ if (!envapt.Envapter.isDevelopment && !envapt.Envapter.isTest) return;
655
+ this.hmrHandler = new require_HmrModuleHandler.HmrModuleHandler({
656
+ handlersDir: this.directory,
657
+ isHandler: this.isSubscriber.bind(this),
658
+ registerHandler: this.registerSubscriber.bind(this),
659
+ unregisterHandler: this.unregisterSubscriber.bind(this),
660
+ getArtifacts: this.getArtifacts.bind(this),
661
+ logger: this.bus.logger
662
+ });
663
+ }
664
+ /** @internal */
665
+ async init() {
666
+ if (this.isInitialized) return;
667
+ this.isInitialized = true;
668
+ this.bus.registerDefaults();
669
+ const { directory } = this;
670
+ if (directory) {
671
+ this.bus.logger.info(chalk.default.bold(directory));
672
+ await this.load(directory);
673
+ this.bus.logger.utils.list([`${chalk.default.bold.magenta(this.bus.registeredCount)} subscribers`], chalk.default.bold.green("Loaded"));
674
+ }
675
+ if (!envapt.Envapter.isTest) await this.bus.verifyWebhooks();
676
+ }
677
+ /** @internal */
678
+ async onHmr(event) {
679
+ if (this.hmrHandler) await this.hmrHandler.handle(event);
680
+ }
681
+ async load(dir) {
682
+ await (0, _seedcord_utils_node.traverseDirectory)(dir, (fullPath, relativePath, imported) => {
683
+ for (const exportName of Object.keys(imported)) {
684
+ const value = imported[exportName];
685
+ if (!this.isSubscriber(value)) continue;
686
+ this.registerSubscriber(value);
687
+ this.hmrHandler?.trackHandler(fullPath, value);
688
+ this.bus.logger.utils.registration(value.name, relativePath);
689
+ }
690
+ });
691
+ }
692
+ registerSubscriber(ctor) {
693
+ this.bus.register(require_subscribers.registrationFor(ctor));
694
+ }
695
+ unregisterSubscriber(ctor, artifacts) {
696
+ this.bus.unregister(ctor, artifacts);
697
+ }
698
+ getArtifacts(ctor) {
699
+ return [Reflect.getMetadata(require_publishDefault.SubscribeMetadataKey, ctor).subscriber];
700
+ }
701
+ isSubscriber(value) {
702
+ if (typeof value !== "function") return false;
703
+ return value.prototype instanceof require_subscribers.Subscriber && Reflect.hasMetadata(require_publishDefault.SubscribeMetadataKey, value);
704
+ }
705
+ };
706
+
707
+ //#endregion
708
+ exports.CoordinatedShutdown = CoordinatedShutdown;
709
+ exports.CoordinatedStartup = CoordinatedStartup;
710
+ exports.HealthCheck = HealthCheck;
711
+ exports.Pluggable = Pluggable;
712
+ exports.ShutdownPhase = require_phases.ShutdownPhase;
713
+ exports.StartupPhase = require_phases.StartupPhase;
714
+ exports.SubscriberLoader = SubscriberLoader;
715
+ exports.settleWithin = settleWithin;
716
+ //# sourceMappingURL=node-internal.index.cjs.map