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