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

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 (44) hide show
  1. package/dist/{AutocompleteOptions-eB87SZ4a.d.mts → AutocompleteOptions-eKhIe6Qt.d.mts} +9 -16
  2. package/dist/Plugin-C2-VHrsX.cjs +114 -0
  3. package/dist/Plugin-C2-VHrsX.cjs.map +1 -0
  4. package/dist/Plugin-CNyRKDHT.d.mts +226 -0
  5. package/dist/Plugin-PcdPjAzc.mjs +97 -0
  6. package/dist/Plugin-PcdPjAzc.mjs.map +1 -0
  7. package/dist/devChannel-CQU7hq7Q.mjs +14 -0
  8. package/dist/devChannel-CQU7hq7Q.mjs.map +1 -0
  9. package/dist/devChannel-CoCmAVDx.cjs +26 -0
  10. package/dist/devChannel-CoCmAVDx.cjs.map +1 -0
  11. package/dist/index.cjs +5 -2
  12. package/dist/index.cjs.map +1 -1
  13. package/dist/index.d.mts +3 -2
  14. package/dist/index.mjs +4 -3
  15. package/dist/index.mjs.map +1 -1
  16. package/dist/internal.index.cjs +7 -17
  17. package/dist/internal.index.cjs.map +1 -1
  18. package/dist/internal.index.d.mts +3 -2
  19. package/dist/internal.index.mjs +4 -15
  20. package/dist/internal.index.mjs.map +1 -1
  21. package/dist/node-internal.index.cjs +645 -0
  22. package/dist/node-internal.index.cjs.map +1 -0
  23. package/dist/node-internal.index.d.cts +1 -0
  24. package/dist/{node.index.d.mts → node-internal.index.d.mts} +104 -143
  25. package/dist/node-internal.index.mjs +636 -0
  26. package/dist/node-internal.index.mjs.map +1 -0
  27. package/dist/{permissions-DQL5ViZn.cjs → permissions-DSW_EZfN.cjs} +19 -1
  28. package/dist/{permissions-DQL5ViZn.cjs.map → permissions-DSW_EZfN.cjs.map} +1 -1
  29. package/dist/{permissions-SokZLJMj.mjs → permissions-RVCBhL2n.mjs} +14 -2
  30. package/dist/{permissions-SokZLJMj.mjs.map → permissions-RVCBhL2n.mjs.map} +1 -1
  31. package/dist/phases-BfpAG6w3.mjs +31 -0
  32. package/dist/phases-BfpAG6w3.mjs.map +1 -0
  33. package/dist/phases-C_BGNyVo.cjs +43 -0
  34. package/dist/phases-C_BGNyVo.cjs.map +1 -0
  35. package/dist/plugin.index.cjs +4 -0
  36. package/dist/plugin.index.d.cts +1 -0
  37. package/dist/plugin.index.d.mts +3 -0
  38. package/dist/plugin.index.mjs +3 -0
  39. package/package.json +24 -13
  40. package/dist/node.index.cjs +0 -521
  41. package/dist/node.index.cjs.map +0 -1
  42. package/dist/node.index.d.cts +0 -1
  43. package/dist/node.index.mjs +0 -513
  44. package/dist/node.index.mjs.map +0 -1
@@ -0,0 +1,645 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+ const require_rolldown_runtime = require('./rolldown-runtime-C_NdSu1c.cjs');
3
+ const require_phases = require('./phases-C_BGNyVo.cjs');
4
+ const require_Plugin = require('./Plugin-C2-VHrsX.cjs');
5
+ let _seedcord_errors = require("@seedcord/errors");
6
+ let _seedcord_errors_internal = require("@seedcord/errors/internal");
7
+ let _seedcord_logger = require("@seedcord/logger");
8
+ let chalk = require("chalk");
9
+ chalk = require_rolldown_runtime.__toESM(chalk, 1);
10
+ let _seedcord_event_emitter = require("@seedcord/event-emitter");
11
+ let node_http = require("node:http");
12
+
13
+ //#region src/node/Lifecycle/withTimeout.ts
14
+ async function raceTimer(work, timeoutMs, onTimeout) {
15
+ let timer;
16
+ try {
17
+ await Promise.race([work, new Promise((resolve, reject) => {
18
+ timer = setTimeout(() => onTimeout(resolve, reject), timeoutMs);
19
+ })]);
20
+ } finally {
21
+ if (timer) clearTimeout(timer);
22
+ }
23
+ }
24
+ /** @internal rejects with a `LifecycleTaskTimeout` when `run` outlasts the bound. */
25
+ function withTimeout(name, run, timeoutMs) {
26
+ return raceTimer(run(), timeoutMs, (_, reject) => {
27
+ reject(new _seedcord_errors_internal.SeedcordError(_seedcord_errors.SeedcordErrorCode.LifecycleTaskTimeout, [name, timeoutMs]));
28
+ });
29
+ }
30
+ /** @internal resolves when `work` settles or the bound elapses, whichever is first. */
31
+ function settleWithin(work, timeoutMs) {
32
+ return raceTimer(work, timeoutMs, (resolve) => resolve());
33
+ }
34
+
35
+ //#endregion
36
+ //#region src/node/Lifecycle/CoordinatedLifecycle.ts
37
+ /**
38
+ * Base for the startup and shutdown coordinators. Runs phase-ordered tasks off a per-phase map.
39
+ *
40
+ * @internal
41
+ */
42
+ var CoordinatedLifecycle = class extends _seedcord_event_emitter.TypedEventEmitter {
43
+ phaseOrder;
44
+ phaseEnum;
45
+ logger;
46
+ tasksMap = /* @__PURE__ */ new Map();
47
+ constructor(loggerName, phaseOrder, phaseEnum) {
48
+ super();
49
+ this.phaseOrder = phaseOrder;
50
+ this.phaseEnum = phaseEnum;
51
+ this.logger = new _seedcord_logger.Logger(loggerName);
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 _seedcord_errors_internal.SeedcordError(_seedcord_errors.SeedcordErrorCode.LifecycleUnknownPhase, [phase]);
66
+ tasks.push({
67
+ name: taskName,
68
+ task,
69
+ timeout: timeoutMs
70
+ });
71
+ this.logger.debug(`${chalk.default.italic("Added")} ${this.getTaskType()} task ${chalk.default.bold.cyan(taskName)} to phase ${chalk.default.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.default.italic("Removed")} ${this.getTaskType()} task ${chalk.default.bold.cyan(taskName)} from phase ${chalk.default.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.default.bold.magenta(this.phaseEnum[phase])}`);
95
+ return;
96
+ }
97
+ 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`);
98
+ this.emitPhase(phase, "start");
99
+ const failures = (await this.executeTasksInPhase(phase, tasks)).filter((r) => r.status === "rejected").length;
100
+ if (failures > 0) throw new _seedcord_errors_internal.SeedcordError(_seedcord_errors.SeedcordErrorCode.LifecyclePhaseFailures, [this.phaseEnum[phase], failures]);
101
+ this.logger.info(`Phase ${chalk.default.bold.magenta(this.phaseEnum[phase])} ${chalk.default.bold.green("completed successfully")}`);
102
+ this.emitPhase(phase, "complete");
103
+ }
104
+ async runTaskWithTimeout(phase, task) {
105
+ this.logger.info(`${chalk.default.italic("Starting")} task ${chalk.default.bold.cyan(task.name)} in phase ${chalk.default.bold.magenta(this.phaseEnum[phase])}`);
106
+ try {
107
+ await withTimeout(task.name, task.task, task.timeout);
108
+ this.logger.info(`${chalk.default.italic("Completed")} task ${chalk.default.bold.cyan(task.name)} in phase ${chalk.default.bold.magenta(this.phaseEnum[phase])}`);
109
+ } catch (error) {
110
+ this.logger.error(`${chalk.default.italic("Failed")} task ${chalk.default.bold.cyan(task.name)} in phase ${chalk.default.bold.magenta(this.phaseEnum[phase])}:`, error);
111
+ throw error;
112
+ }
113
+ }
114
+ emitPhase(phase, action) {
115
+ this.emitSafeRaw(`phase:${phase}:${action}`);
116
+ }
117
+ onListenerError(error, event) {
118
+ this.logger.error(`listener for ${String(event)} threw`, error);
119
+ }
120
+ };
121
+
122
+ //#endregion
123
+ //#region src/node/Lifecycle/CoordinatedShutdown.ts
124
+ const PHASE_ORDER$1 = [
125
+ 1,
126
+ 2,
127
+ 3,
128
+ 4
129
+ ];
130
+ const LOG_FLUSH_DELAY_MS = 3e3;
131
+ /**
132
+ * Runs registered shutdown tasks across `ShutdownPhase` in order. Registers SIGINT and SIGTERM
133
+ * handlers. Tasks within a phase run in parallel.
134
+ */
135
+ var CoordinatedShutdown = class extends CoordinatedLifecycle {
136
+ isShuttingDown = false;
137
+ hasShutdown = false;
138
+ exitCode = 0;
139
+ onSigTerm = null;
140
+ onSigInt = null;
141
+ startupGate;
142
+ constructor() {
143
+ super("Shutdown", PHASE_ORDER$1, require_phases.ShutdownPhase);
144
+ this.registerSignalHandlers();
145
+ }
146
+ canAddTask() {
147
+ return true;
148
+ }
149
+ canRemoveTask() {
150
+ return true;
151
+ }
152
+ getTaskType() {
153
+ return "shutdown";
154
+ }
155
+ async executeTasksInPhase(phase, tasks) {
156
+ const promises = tasks.map((task) => this.runTaskWithTimeout(phase, task));
157
+ return Promise.allSettled(promises);
158
+ }
159
+ registerSignalHandlers() {
160
+ this.onSigTerm = () => {
161
+ this.logger.info(`Received ${chalk.default.yellow.bold("SIGTERM")} signal`);
162
+ this.run(0);
163
+ };
164
+ this.onSigInt = () => {
165
+ this.logger.info(`Received ${chalk.default.yellow.bold("SIGINT")} signal`);
166
+ this.run(0);
167
+ };
168
+ process.on("SIGTERM", this.onSigTerm);
169
+ process.on("SIGINT", this.onSigInt);
170
+ }
171
+ /** @internal */
172
+ removeSignalHandlers() {
173
+ if (this.onSigTerm) {
174
+ process.off("SIGTERM", this.onSigTerm);
175
+ this.onSigTerm = null;
176
+ }
177
+ if (this.onSigInt) {
178
+ process.off("SIGINT", this.onSigInt);
179
+ this.onSigInt = null;
180
+ }
181
+ }
182
+ /** @internal run() awaits this so a shutdown during startup waits for startup to register its dispose tasks */
183
+ gateOnStartup(settled) {
184
+ this.startupGate = settled;
185
+ }
186
+ /** Adds a shutdown-phase task. @param timeoutMs - Task timeout in ms. {@default 5000} */
187
+ addTask(phase, taskName, task, timeoutMs = 5e3) {
188
+ super.addTask(phase, taskName, task, timeoutMs);
189
+ }
190
+ /** Removes a shutdown-phase task, returning whether one was removed. */
191
+ removeTask(phase, taskName) {
192
+ return super.removeTask(phase, taskName);
193
+ }
194
+ /**
195
+ * Runs registered tasks across shutdown phases in `ShutdownPhase` order.
196
+ * Tasks within each phase run in parallel.
197
+ *
198
+ * @param exitCode - Process exit code. {@default `0`}
199
+ * @param exitProcess - Whether to exit the process after shutdown. {@default `true`}
200
+ * @example
201
+ * ```typescript
202
+ * shutdown.addTask(ShutdownPhase.Disconnect, 'database', () => db.disconnect(), 5000);
203
+ * await shutdown.run(0);
204
+ * ```
205
+ */
206
+ async run(exitCode = 0, exitProcess = true) {
207
+ this.removeSignalHandlers();
208
+ if (this.hasShutdown || this.isShuttingDown) {
209
+ this.logger.warn("Shutdown sequence already ran or is in progress");
210
+ return;
211
+ }
212
+ this.isShuttingDown = true;
213
+ this.exitCode = exitCode;
214
+ this.logger.info(`${chalk.default.bold.yellow("Starting")} coordinated shutdown with exit code ${chalk.default.bold.cyan(exitCode)}`);
215
+ this.emitSafe("shutdown:start");
216
+ try {
217
+ if (this.startupGate) await this.startupGate;
218
+ const failures = [];
219
+ for (const phase of PHASE_ORDER$1) try {
220
+ await this.runPhase(phase);
221
+ } catch (error) {
222
+ failures.push(error);
223
+ }
224
+ if (failures.length > 0) this.emitFailures(failures);
225
+ else {
226
+ this.logger.info(`${chalk.default.bold.green("Coordinated shutdown completed")} successfully`);
227
+ this.emitSafe("shutdown:complete");
228
+ }
229
+ } finally {
230
+ this.hasShutdown = true;
231
+ if (exitProcess) {
232
+ this.logger.info(`${chalk.default.bold.red("Exiting")} process with code ${chalk.default.bold.cyan(this.exitCode)}`);
233
+ setTimeout(() => {
234
+ process.exit(this.exitCode);
235
+ }, LOG_FLUSH_DELAY_MS);
236
+ } else {
237
+ this.logger.info(`${chalk.default.bold.yellow("Skipping")} process exit (dev mode)`);
238
+ this.isShuttingDown = false;
239
+ }
240
+ }
241
+ }
242
+ emitFailures(failures) {
243
+ this.logger.error(`${chalk.default.bold.red("Coordinated shutdown failed")}`);
244
+ const error = failures.length === 1 ? failures[0] : new AggregateError(failures, "shutdown phase failures");
245
+ this.emitSafe("shutdown:error", error);
246
+ }
247
+ };
248
+
249
+ //#endregion
250
+ //#region src/node/Lifecycle/CoordinatedStartup.ts
251
+ const PHASE_ORDER = [
252
+ 1,
253
+ 2,
254
+ 3
255
+ ];
256
+ /**
257
+ * Runs registered startup tasks across `StartupPhase` in order. Tasks within a phase run in parallel.
258
+ */
259
+ var CoordinatedStartup = class extends CoordinatedLifecycle {
260
+ isStartingUp = false;
261
+ hasStarted = false;
262
+ constructor() {
263
+ super("Startup", PHASE_ORDER, require_phases.StartupPhase);
264
+ }
265
+ /** Adds a startup-phase task. @param timeoutMs - Task timeout in ms. {@default 10000} */
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
+ this.emitSafe("startup:start");
303
+ try {
304
+ for (const phase of PHASE_ORDER) {
305
+ if (!this.isStartingUp) {
306
+ this.logger.warn("Startup sequence aborted");
307
+ return;
308
+ }
309
+ await this.runPhase(phase);
310
+ }
311
+ this.hasStarted = true;
312
+ this.logger.info(`${chalk.default.bold.green("Coordinated startup completed")} successfully`);
313
+ this.emitSafe("startup:complete");
314
+ } catch (error) {
315
+ if (!this.isStartingUp) {
316
+ this.logger.warn("Startup sequence aborted during error handling");
317
+ return;
318
+ }
319
+ this.logger.error(`${chalk.default.bold.red("Coordinated startup failed")}`);
320
+ this.emitSafe("startup:error", error);
321
+ throw error;
322
+ } finally {
323
+ this.isStartingUp = false;
324
+ }
325
+ }
326
+ async runTaskWithTimeout(phase, task) {
327
+ this.logger.info(`${chalk.default.italic("Starting")} task ${chalk.default.bold.cyan(task.name)} in phase ${chalk.default.bold.magenta(require_phases.StartupPhase[phase])}`);
328
+ try {
329
+ await withTimeout(task.name, task.task, task.timeout);
330
+ this.logger.info(`${chalk.default.italic("Completed")} task ${chalk.default.bold.cyan(task.name)} in phase ${chalk.default.bold.magenta(require_phases.StartupPhase[phase])}`);
331
+ } catch (error) {
332
+ if (!this.isStartingUp) return;
333
+ 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);
334
+ throw error;
335
+ }
336
+ }
337
+ /**
338
+ * Aborts the startup sequence if it is currently running.
339
+ */
340
+ abort() {
341
+ if (!this.isStartingUp) return;
342
+ this.isStartingUp = false;
343
+ this.logger.warn("Aborting coordinated startup sequence");
344
+ }
345
+ get isReady() {
346
+ return this.hasStarted;
347
+ }
348
+ get isRunning() {
349
+ return this.isStartingUp;
350
+ }
351
+ };
352
+
353
+ //#endregion
354
+ //#region src/node/HealthCheck.ts
355
+ const HTTP_OK = 200;
356
+ const HTTP_NOT_FOUND = 404;
357
+ const DEFAULT_HEALTH_CHECK_PORT = 6967;
358
+ const DEFAULT_HEALTH_CHECK_PATH = "/health";
359
+ /**
360
+ * HTTP server answering `GET` on the configured path with a JSON `{ status, timestamp }` body.
361
+ */
362
+ var HealthCheck = class HealthCheck {
363
+ /** @internal */
364
+ logger = new _seedcord_logger.Logger("HealthCheck");
365
+ port;
366
+ path;
367
+ host;
368
+ server;
369
+ constructor(shutdown, options) {
370
+ this.port = options?.port ?? DEFAULT_HEALTH_CHECK_PORT;
371
+ this.path = options?.path ?? DEFAULT_HEALTH_CHECK_PATH;
372
+ this.host = options?.host;
373
+ shutdown.addTask(2, "stop-healthcheck-server", () => this.stop());
374
+ }
375
+ /**
376
+ * Resolves the `healthCheck` option. `undefined` and `true` build the defaults, an object uses
377
+ * its config, `false` returns `undefined`.
378
+ */
379
+ static fromOption(shutdown, option) {
380
+ if (option === false) return void 0;
381
+ return new HealthCheck(shutdown, typeof option === "object" ? option : void 0);
382
+ }
383
+ /**
384
+ * Starts the health check server.
385
+ * @returns Promise that resolves when the server is listening
386
+ * @internal
387
+ */
388
+ async init() {
389
+ return new Promise((resolve, reject) => {
390
+ const server = (0, node_http.createServer)((req, res) => {
391
+ if (req.method === "GET" && req.url === this.path) {
392
+ res.writeHead(HTTP_OK, { "Content-Type": "application/json" });
393
+ res.end(JSON.stringify({
394
+ status: "ok",
395
+ timestamp: Date.now()
396
+ }));
397
+ } else {
398
+ res.writeHead(HTTP_NOT_FOUND, { "Content-Type": "application/json" });
399
+ res.end(JSON.stringify({ status: "not found" }));
400
+ }
401
+ });
402
+ this.server = server;
403
+ const onListenError = (err) => reject(err);
404
+ server.on("error", onListenError);
405
+ server.once("listening", () => {
406
+ server.removeListener("error", onListenError);
407
+ server.on("error", (err) => this.logger.error("Health check server error", err));
408
+ const address = this.host ?? "localhost";
409
+ this.logger.info(`${_seedcord_logger.paint.mint.bold("✓")} Health check server listening on ${_seedcord_logger.paint.sky(`http://${address}:${this.port}${this.path}`)}`);
410
+ resolve();
411
+ });
412
+ if (this.host) {
413
+ this.logger.debug(`Binding health check server to ${this.host}`);
414
+ server.listen(this.port, this.host);
415
+ } else {
416
+ this.logger.debug("Binding health check server to all interfaces");
417
+ server.listen(this.port);
418
+ }
419
+ });
420
+ }
421
+ /**
422
+ * Stops the health check server.
423
+ * @internal
424
+ */
425
+ stop() {
426
+ const server = this.server;
427
+ if (!server?.listening) return Promise.resolve();
428
+ return new Promise((resolve, reject) => {
429
+ server.close((err) => {
430
+ if (err) {
431
+ reject(err);
432
+ return;
433
+ }
434
+ this.logger.info(_seedcord_logger.paint.coral.bold("Health check server stopped"));
435
+ resolve();
436
+ });
437
+ });
438
+ }
439
+ };
440
+
441
+ //#endregion
442
+ //#region src/node/Pluggable.ts
443
+ /**
444
+ * Base class for objects that can have plugins attached.
445
+ *
446
+ * Plugins are attached during configuration and initialized during startup, sequentially in attach
447
+ * order within each phase. Not constructed directly, the host is a transport `Seedcord` class.
448
+ */
449
+ var Pluggable = class Pluggable extends _seedcord_event_emitter.TypedEventEmitter {
450
+ isInitialized = false;
451
+ startFailed = false;
452
+ shutdown;
453
+ startup;
454
+ plugins = [];
455
+ pluginLogger = new _seedcord_logger.Logger("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
+ super();
468
+ Pluggable.isInstantiated = true;
469
+ Pluggable.liveShutdown = shutdown;
470
+ this.shutdown = shutdown;
471
+ this.startup = startup;
472
+ }
473
+ /** @internal */
474
+ async init() {
475
+ if (this.isInitialized) return this;
476
+ if (this.startFailed) throw new _seedcord_errors_internal.SeedcordError(_seedcord_errors.SeedcordErrorCode.LifecycleRestartAfterFailure);
477
+ this.registerPluginTasks();
478
+ const startupSettled = Promise.withResolvers();
479
+ this.shutdown.gateOnStartup(startupSettled.promise);
480
+ try {
481
+ await this.startup.run();
482
+ } catch (caught) {
483
+ await this.rollback();
484
+ throw caught;
485
+ } finally {
486
+ startupSettled.resolve();
487
+ }
488
+ this.isInitialized = true;
489
+ return this;
490
+ }
491
+ pluginCapabilities() {
492
+ return {};
493
+ }
494
+ pluginStore() {
495
+ return this.config.store ?? this.rateLimiter;
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`. Augment the transport's `Core` interface with the plugin
508
+ * type for intellisense.
509
+ *
510
+ * @typeParam Key - The property name for accessing the plugin
511
+ * @typeParam Ctor - The plugin constructor type
512
+ * @param key - Property name to access the plugin instance
513
+ * @param Plugin - Plugin constructor class
514
+ * @param args - Additional arguments to pass to the plugin constructor
515
+ * @returns This instance with the plugin attached as a typed property
516
+ * @throws A **SeedcordError** When called after initialization or if key already exists
517
+ * @example
518
+ * ```typescript
519
+ * seedcord.attach('db', Mongo, { uri: 'mongodb://...', name: 'seedcord', dir: ... })
520
+ * ```
521
+ */
522
+ attach(key, Plugin, ...args) {
523
+ if (this.isInitialized) throw new _seedcord_errors_internal.SeedcordError(_seedcord_errors.SeedcordErrorCode.CorePluginAfterInit);
524
+ if (key in this) throw new _seedcord_errors_internal.SeedcordError(_seedcord_errors.SeedcordErrorCode.CorePluginKeyExists, [key]);
525
+ const instance = new Plugin(this, ...args);
526
+ this.plugins.push(instance);
527
+ this.attachments.push({
528
+ key,
529
+ instance
530
+ });
531
+ this.finalizeContext(key, instance);
532
+ return Object.assign(this, { [key]: instance });
533
+ }
534
+ finalizeContext(key, instance) {
535
+ const caps = this.pluginCapabilities();
536
+ const readToken = () => this.pluginCapabilities().token;
537
+ require_Plugin.finalizePluginContext(instance, {
538
+ logger: new _seedcord_logger.Logger(key),
539
+ config: this.config,
540
+ store: this.pluginStore(),
541
+ client: caps.client,
542
+ get token() {
543
+ return readToken();
544
+ },
545
+ rest: caps.rest
546
+ });
547
+ }
548
+ registerPluginTasks() {
549
+ if (this.pluginTasksRegistered) return;
550
+ this.pluginTasksRegistered = true;
551
+ const groups = /* @__PURE__ */ new Map();
552
+ for (const attachment of this.attachments) {
553
+ const phase = require_Plugin.resolvedLifecycleSpecOf(attachment.instance).init.phase;
554
+ const group = groups.get(phase) ?? [];
555
+ group.push(attachment);
556
+ groups.set(phase, group);
557
+ }
558
+ for (const [phase, group] of groups) {
559
+ if (phase === 3) continue;
560
+ const budget = group.reduce((sum, a) => sum + require_Plugin.resolvedLifecycleSpecOf(a.instance).init.timeout, 0);
561
+ this.startup.addTask(phase, "Plugins:init", () => this.runInits(group), budget);
562
+ }
563
+ this.registerReadyTask(groups.get(3) ?? []);
564
+ }
565
+ async runInits(group) {
566
+ for (const attachment of group) {
567
+ const { key, instance } = attachment;
568
+ const spec = require_Plugin.resolvedLifecycleSpecOf(instance);
569
+ instance.logger.utils.initialization(key, "start");
570
+ await withTimeout(`Plugin:${key}`, () => instance.init(), spec.init.timeout);
571
+ instance.logger.utils.initialization(key, "end");
572
+ this.completedInits.add(attachment);
573
+ if (instance.dispose) this.registerDisposeTask(spec.dispose.phase);
574
+ }
575
+ }
576
+ registerReadyTask(readyInits) {
577
+ const steps = this.attachments.reduce((acc, a) => {
578
+ const ready = a.instance.ready?.bind(a.instance);
579
+ if (ready) acc.push({
580
+ key: a.key,
581
+ run: ready,
582
+ timeout: require_Plugin.resolvedLifecycleSpecOf(a.instance).ready.timeout
583
+ });
584
+ return acc;
585
+ }, []);
586
+ if (readyInits.length === 0 && steps.length === 0) return;
587
+ const budget = readyInits.reduce((sum, a) => sum + require_Plugin.resolvedLifecycleSpecOf(a.instance).init.timeout, 0) + steps.reduce((sum, step) => sum + step.timeout, 0);
588
+ this.startup.addTask(3, "Plugins", async () => {
589
+ await this.runInits(readyInits);
590
+ for (const step of steps) await withTimeout(`Plugin:${step.key}:ready`, step.run, step.timeout);
591
+ }, budget);
592
+ }
593
+ registerDisposeTask(phase) {
594
+ if (this.disposePhases.has(phase)) return;
595
+ this.disposePhases.add(phase);
596
+ const budget = this.attachments.reduce((sum, a) => {
597
+ const spec = require_Plugin.resolvedLifecycleSpecOf(a.instance);
598
+ return a.instance.dispose && spec.dispose.phase === phase ? sum + spec.dispose.timeout : sum;
599
+ }, 0);
600
+ this.shutdown.addTask(phase, "Plugins:dispose", () => this.runDisposals(phase), budget);
601
+ }
602
+ async runDisposals(phase) {
603
+ const failures = [];
604
+ await this.disposeCompleted(phase, (caught) => failures.push(caught));
605
+ if (failures.length === 1) throw failures[0];
606
+ if (failures.length > 1) throw new AggregateError(failures, "plugin dispose failures");
607
+ }
608
+ async disposeCompleted(phase, onError) {
609
+ for (const attachment of [...this.attachments].reverse()) {
610
+ if (!this.completedInits.has(attachment)) continue;
611
+ const dispose = attachment.instance.dispose?.bind(attachment.instance);
612
+ if (!dispose) continue;
613
+ const spec = require_Plugin.resolvedLifecycleSpecOf(attachment.instance);
614
+ if (phase !== void 0 && spec.dispose.phase !== phase) continue;
615
+ try {
616
+ await withTimeout(`Plugin:${attachment.key}:dispose`, dispose, spec.dispose.timeout);
617
+ } catch (caught) {
618
+ onError(caught);
619
+ }
620
+ }
621
+ }
622
+ async rollback() {
623
+ this.startFailed = true;
624
+ await this.disposeCompleted(void 0, (caught) => this.pluginLogger.warn("rollback dispose failed", caught));
625
+ this.completedInits.clear();
626
+ }
627
+ /** @internal */
628
+ removeListener(event, listener) {
629
+ return super.removeListener(event, listener);
630
+ }
631
+ /** @internal */
632
+ removeAllListeners(event) {
633
+ return super.removeAllListeners(event);
634
+ }
635
+ };
636
+
637
+ //#endregion
638
+ exports.CoordinatedShutdown = CoordinatedShutdown;
639
+ exports.CoordinatedStartup = CoordinatedStartup;
640
+ exports.HealthCheck = HealthCheck;
641
+ exports.Pluggable = Pluggable;
642
+ exports.ShutdownPhase = require_phases.ShutdownPhase;
643
+ exports.StartupPhase = require_phases.StartupPhase;
644
+ exports.settleWithin = settleWithin;
645
+ //# sourceMappingURL=node-internal.index.cjs.map