@moku-labs/common 0.1.0

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.
package/dist/index.mjs ADDED
@@ -0,0 +1,994 @@
1
+ import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.mjs";
2
+ import { createCorePlugin } from "@moku-labs/core";
3
+ import { existsSync, readFileSync } from "node:fs";
4
+ //#region src/plugins/log/expect.ts
5
+ /**
6
+ * Named error thrown by `expect()` assertions when a trace condition fails.
7
+ *
8
+ * @example
9
+ * ```ts
10
+ * throw new LogExpectAssertionError("missing event build:complete");
11
+ * ```
12
+ */
13
+ var LogExpectAssertionError = class extends Error {
14
+ /**
15
+ * Construct a new assertion error with a descriptive failure message.
16
+ *
17
+ * @param message - Descriptive failure message (event name, partial, index).
18
+ * @example
19
+ * ```ts
20
+ * throw new LogExpectAssertionError("missing event build:complete");
21
+ * ```
22
+ */
23
+ constructor(message) {
24
+ super(message);
25
+ this.name = "LogExpectAssertionError";
26
+ }
27
+ };
28
+ /**
29
+ * Tests whether a value is a non-null, non-array plain object.
30
+ *
31
+ * @param value - The value to test.
32
+ * @returns `true` when `value` is a non-null object that is not an array.
33
+ * @example
34
+ * ```ts
35
+ * isPlainObject({ a: 1 }); // true
36
+ * isPlainObject([1]); // false
37
+ * ```
38
+ */
39
+ function isPlainObject$1(value) {
40
+ return typeof value === "object" && value !== null && !Array.isArray(value);
41
+ }
42
+ /**
43
+ * Tests whether `actual` is an array that recursively matches every element of
44
+ * the `partial` array (element-wise, with equal length).
45
+ *
46
+ * @param actual - The value to test against (must be an array of equal length).
47
+ * @param partial - The expected partial array shape.
48
+ * @returns `true` when `actual` is an equal-length array matching `partial` element-wise.
49
+ * @example
50
+ * ```ts
51
+ * matchesPartialArray([1, 2], [1, 2]); // true
52
+ * matchesPartialArray([1], [1, 2]); // false (length mismatch)
53
+ * ```
54
+ */
55
+ function matchesPartialArray(actual, partial) {
56
+ if (!Array.isArray(actual) || actual.length !== partial.length) return false;
57
+ return partial.every((value, index) => matchesPartial(actual[index], value));
58
+ }
59
+ /**
60
+ * Tests whether `actual` is a plain object in which every `partial` key
61
+ * recursively matches (extra `actual` keys are ignored).
62
+ *
63
+ * @param actual - The value to test against (must be a plain object).
64
+ * @param partial - The expected partial object shape.
65
+ * @returns `true` when every `partial` key exists in `actual` and matches recursively.
66
+ * @example
67
+ * ```ts
68
+ * matchesPartialObject({ a: 1, b: 2 }, { a: 1 }); // true
69
+ * matchesPartialObject({ a: 1 }, { b: 1 }); // false (missing key)
70
+ * ```
71
+ */
72
+ function matchesPartialObject(actual, partial) {
73
+ if (!isPlainObject$1(actual)) return false;
74
+ return Object.keys(partial).every((key) => key in actual && matchesPartial(actual[key], partial[key]));
75
+ }
76
+ /**
77
+ * Subset-equality matcher: is `partial` a recursive subset of `actual`?
78
+ *
79
+ * Fast path via `Object.is` (covers identical primitives/references and
80
+ * `null`/`NaN`); primitives compare with `Object.is`; arrays match element-wise
81
+ * with equal length; plain objects require every `partial` key to recursively
82
+ * match (extra `actual` keys ignored).
83
+ *
84
+ * @param actual - The value to test against (typically `entry.data`).
85
+ * @param partial - The expected partial shape.
86
+ * @returns `true` when `partial` is a recursive subset of `actual`.
87
+ * @example
88
+ * ```ts
89
+ * matchesPartial({ a: 1, b: 2 }, { a: 1 }); // true
90
+ * matchesPartial([1, 2], [1]); // false (length mismatch)
91
+ * ```
92
+ */
93
+ function matchesPartial(actual, partial) {
94
+ if (Object.is(actual, partial)) return true;
95
+ if (Array.isArray(partial)) return matchesPartialArray(actual, partial);
96
+ if (isPlainObject$1(partial)) return matchesPartialObject(actual, partial);
97
+ return false;
98
+ }
99
+ /**
100
+ * Tests whether an entry matches `event` and (when provided) `partial`.
101
+ *
102
+ * @param entry - The candidate trace entry.
103
+ * @param event - Required event name.
104
+ * @param partial - Optional partial data shape (subset-matched against `entry.data`).
105
+ * @returns `true` when the entry matches the event and optional partial.
106
+ * @example
107
+ * ```ts
108
+ * entryMatches({ level: "info", event: "a", data: { x: 1 }, ts: 0 }, "a", { x: 1 }); // true
109
+ * ```
110
+ */
111
+ function entryMatches(entry, event, partial) {
112
+ if (entry.event !== event) return false;
113
+ return partial === void 0 ? true : matchesPartial(entry.data, partial);
114
+ }
115
+ /**
116
+ * Render a `partial` for an error message, prefixed with a space when present.
117
+ *
118
+ * @param partial - Optional partial data shape.
119
+ * @returns A ` matching <json>` suffix, or an empty string when absent.
120
+ * @example
121
+ * ```ts
122
+ * describePartial({ ok: true }); // ' matching {"ok":true}'
123
+ * ```
124
+ */
125
+ function describePartial(partial) {
126
+ return partial === void 0 ? "" : ` matching ${JSON.stringify(partial)}`;
127
+ }
128
+ /**
129
+ * Find the first entry with `event` at or after `startIndex`, scanning forward.
130
+ *
131
+ * @param entries - The trace array to scan.
132
+ * @param event - Event name to find.
133
+ * @param startIndex - Index to begin scanning from (inclusive).
134
+ * @returns The index of the first match, or `-1` when none exists from `startIndex` on.
135
+ * @example
136
+ * ```ts
137
+ * findEventAtOrAfter([{ event: "a" }, { event: "b" }] as LogEntry[], "b", 0); // 1
138
+ * ```
139
+ */
140
+ function findEventAtOrAfter(entries, event, startIndex) {
141
+ for (let index = startIndex; index < entries.length; index++) if (entries[index]?.event === event) return index;
142
+ return -1;
143
+ }
144
+ /**
145
+ * Create a fluent assertion chain bound to the live `entries` array. Each method
146
+ * reads `entries` at call time, so assertions reflect later logging.
147
+ *
148
+ * @param entries - The live trace array (read on each assertion call).
149
+ * @returns A fresh {@link ExpectChain} backed by `entries`.
150
+ * @example
151
+ * ```ts
152
+ * createExpectChain(state.entries).toHaveEvent("build:complete");
153
+ * ```
154
+ */
155
+ function createExpectChain(entries) {
156
+ const chain = {
157
+ /**
158
+ * Assert at least one entry has `event`, optionally matching `partial`.
159
+ *
160
+ * @param event - Event name to find.
161
+ * @param partial - Optional partial data shape (subset-matched).
162
+ * @returns The same chain for chaining.
163
+ * @throws {LogExpectAssertionError} When no matching entry exists.
164
+ * @example
165
+ * ```ts
166
+ * chain.toHaveEvent("build:phase", { status: "start" });
167
+ * ```
168
+ */
169
+ toHaveEvent(event, partial) {
170
+ if (!entries.some((entry) => entryMatches(entry, event, partial))) throw new LogExpectAssertionError(`Expected trace to contain event "${event}"${describePartial(partial)}, but none was found.`);
171
+ return chain;
172
+ },
173
+ /**
174
+ * Assert all of `events` appear in the trace in the given relative order.
175
+ *
176
+ * @param events - Ordered list of event names (gaps allowed).
177
+ * @returns The same chain for chaining.
178
+ * @throws {LogExpectAssertionError} When the ordering cannot be satisfied.
179
+ * @example
180
+ * ```ts
181
+ * chain.toHaveEventInOrder(["build:phase", "build:complete"]);
182
+ * ```
183
+ */
184
+ toHaveEventInOrder(events) {
185
+ let cursor = 0;
186
+ for (const [position, event] of events.entries()) {
187
+ const matchIndex = findEventAtOrAfter(entries, event, cursor);
188
+ if (matchIndex === -1) throw new LogExpectAssertionError(`Expected events in order ${JSON.stringify(events)}, but "${event}" (index ${position}) was not found at or after position ${cursor}.`);
189
+ cursor = matchIndex + 1;
190
+ }
191
+ return chain;
192
+ },
193
+ /**
194
+ * Assert NO entry has `event` (optionally narrowed by `partial`).
195
+ *
196
+ * @param event - Event name that must be absent.
197
+ * @param partial - Optional partial data shape; only matching entries violate.
198
+ * @returns The same chain for chaining.
199
+ * @throws {LogExpectAssertionError} When a matching entry exists.
200
+ * @example
201
+ * ```ts
202
+ * chain.toNotHaveEvent("deploy:failed");
203
+ * ```
204
+ */
205
+ toNotHaveEvent(event, partial) {
206
+ const offending = entries.findIndex((entry) => entryMatches(entry, event, partial));
207
+ if (offending !== -1) throw new LogExpectAssertionError(`Expected trace to NOT contain event "${event}"${describePartial(partial)}, but found one at index ${offending}.`);
208
+ return chain;
209
+ }
210
+ };
211
+ return chain;
212
+ }
213
+ //#endregion
214
+ //#region src/plugins/log/api.ts
215
+ /**
216
+ * @file log plugin — API factory.
217
+ *
218
+ * Builds the `LogApi` over the plugin's `{ config, state }` core context:
219
+ * the leveled loggers (via a shared `append`), the frozen `trace()` snapshot,
220
+ * the live `expect()` chain, `addSink`, and `reset`.
221
+ */
222
+ /**
223
+ * Append a new entry to the trace and fan it out to every sink in order.
224
+ *
225
+ * @param state - The mutable log state to append to.
226
+ * @param level - Severity level for the entry.
227
+ * @param event - Event identifier.
228
+ * @param data - Optional structured payload.
229
+ * @example
230
+ * ```ts
231
+ * append(state, "info", "content:ready", { count: 12 });
232
+ * ```
233
+ */
234
+ function append(state, level, event, data) {
235
+ const entry = {
236
+ level,
237
+ event,
238
+ data,
239
+ ts: Date.now()
240
+ };
241
+ state.entries.push(entry);
242
+ for (const sink of state.sinks) sink.write(entry);
243
+ }
244
+ /**
245
+ * Tests whether a value is a non-null, non-array plain object.
246
+ *
247
+ * @param value - The value to test.
248
+ * @returns `true` when `value` is a non-null object that is not an array.
249
+ * @example
250
+ * ```ts
251
+ * isPlainObject({ a: 1 }); // true
252
+ * isPlainObject([1]); // false
253
+ * ```
254
+ */
255
+ function isPlainObject(value) {
256
+ return typeof value === "object" && value !== null && !Array.isArray(value);
257
+ }
258
+ /**
259
+ * Merge an `Error`'s `message`/`stack` into `data` under an `error` key. The
260
+ * `error` field is always preserved; only a plain object `data` contributes its
261
+ * keys. Non-plain-object `data` (arrays and primitives) is replaced by `{}` —
262
+ * its original value is not retained — so the merge target is always a record.
263
+ *
264
+ * @param data - Original payload (any shape).
265
+ * @param error - The originating error to merge.
266
+ * @returns A new object carrying any plain-object keys plus the `error` field.
267
+ * @example
268
+ * ```ts
269
+ * mergeError({ target: "cf" }, new Error("boom"));
270
+ * // { target: "cf", error: { message: "boom", stack: "..." } }
271
+ * ```
272
+ */
273
+ function mergeError(data, error) {
274
+ return {
275
+ ...isPlainObject(data) ? data : {},
276
+ error: {
277
+ message: error.message,
278
+ stack: error.stack
279
+ }
280
+ };
281
+ }
282
+ /**
283
+ * Create the log plugin API surface injected as `ctx.log` / `app.log`.
284
+ *
285
+ * @param ctx - Core plugin context (`{ config, state }`).
286
+ * @returns The {@link LogApi} bound to `ctx.state`.
287
+ * @example
288
+ * ```ts
289
+ * const log = createLogApi(ctx);
290
+ * log.info("content:ready", { articleCount: 12 });
291
+ * ```
292
+ */
293
+ function createLogApi(ctx) {
294
+ const { state } = ctx;
295
+ return {
296
+ /**
297
+ * Append an `info` entry and fan it out to every sink.
298
+ *
299
+ * @param event - Event identifier (convention: `domain:action`).
300
+ * @param data - Optional structured payload.
301
+ * @example
302
+ * ```ts
303
+ * log.info("content:ready", { count: 12 });
304
+ * ```
305
+ */
306
+ info(event, data) {
307
+ append(state, "info", event, data);
308
+ },
309
+ /**
310
+ * Append a `debug` entry and fan it out to every sink.
311
+ *
312
+ * @param event - Event identifier (convention: `domain:action`).
313
+ * @param data - Optional structured payload.
314
+ * @example
315
+ * ```ts
316
+ * log.debug("router:match", { path: "/blog/" });
317
+ * ```
318
+ */
319
+ debug(event, data) {
320
+ append(state, "debug", event, data);
321
+ },
322
+ /**
323
+ * Append a `warn` entry and fan it out to every sink.
324
+ *
325
+ * @param event - Event identifier (convention: `domain:action`).
326
+ * @param data - Optional structured payload.
327
+ * @example
328
+ * ```ts
329
+ * log.warn("build:skip", { reason: "no sitemap" });
330
+ * ```
331
+ */
332
+ warn(event, data) {
333
+ append(state, "warn", event, data);
334
+ },
335
+ /**
336
+ * Append an `error` entry. When `error` is provided, its `message`/`stack`
337
+ * are merged into `data` under an `error` key (existing keys preserved);
338
+ * otherwise `data` is recorded as-is.
339
+ *
340
+ * @param event - Event identifier (convention: `domain:action`).
341
+ * @param data - Optional structured payload.
342
+ * @param error - Optional originating Error to merge into `data`.
343
+ * @example
344
+ * ```ts
345
+ * log.error("deploy:failed", { target: "cf" }, err);
346
+ * ```
347
+ */
348
+ error(event, data, error) {
349
+ append(state, "error", event, error === void 0 ? data : mergeError(data, error));
350
+ },
351
+ /**
352
+ * Return a frozen snapshot (fresh copy) of the entries recorded so far.
353
+ *
354
+ * @returns A readonly, frozen copy of the recorded entries.
355
+ * @example
356
+ * ```ts
357
+ * const entries = log.trace();
358
+ * ```
359
+ */
360
+ trace() {
361
+ return Object.freeze([...state.entries]);
362
+ },
363
+ /**
364
+ * Return a fluent assertion chain bound to the live entries array.
365
+ *
366
+ * @returns A fresh {@link ExpectChain} reading `state.entries` live.
367
+ * @example
368
+ * ```ts
369
+ * log.expect().toHaveEvent("build:complete");
370
+ * ```
371
+ */
372
+ expect() {
373
+ return createExpectChain(state.entries);
374
+ },
375
+ /**
376
+ * Register an additional output sink at runtime.
377
+ *
378
+ * @param sink - The sink to add to the fan-out list.
379
+ * @example
380
+ * ```ts
381
+ * log.addSink({ write: (e) => stream.write(JSON.stringify(e)) });
382
+ * ```
383
+ */
384
+ addSink(sink) {
385
+ state.sinks.push(sink);
386
+ },
387
+ /**
388
+ * Clear all recorded entries while keeping registered sinks.
389
+ *
390
+ * @example
391
+ * ```ts
392
+ * log.reset();
393
+ * ```
394
+ */
395
+ reset() {
396
+ state.entries.length = 0;
397
+ }
398
+ };
399
+ }
400
+ //#endregion
401
+ //#region src/plugins/log/sinks.ts
402
+ /** Severity rank for threshold comparison (higher = more severe). */
403
+ const LEVEL_RANK = {
404
+ debug: 10,
405
+ info: 20,
406
+ warn: 30,
407
+ error: 40
408
+ };
409
+ /**
410
+ * Build the console sink: routes entries by channel — `error` → `console.error`,
411
+ * `warn` → `console.warn`, and `debug`/`info` → `console.log`. The full entry
412
+ * object is forwarded so the console serializes its `event` and `data`. Entries
413
+ * below `minLevel` are dropped (the in-memory trace still records everything).
414
+ *
415
+ * @param minLevel - Lowest severity to print. Defaults to `"debug"` (print all).
416
+ * @returns A {@link LogSink} that writes to the matching `console` channel.
417
+ * @example
418
+ * ```ts
419
+ * state.sinks.push(consoleSink("info")); // suppress debug spam
420
+ * ```
421
+ */
422
+ function consoleSink(minLevel = "debug") {
423
+ const threshold = LEVEL_RANK[minLevel];
424
+ return {
425
+ /**
426
+ * Route a single entry to the console channel matching its level.
427
+ *
428
+ * @param entry - The entry to emit.
429
+ * @example
430
+ * ```ts
431
+ * sink.write({ level: "warn", event: "build:skip", ts: Date.now() });
432
+ * ```
433
+ */
434
+ write(entry) {
435
+ if (LEVEL_RANK[entry.level] < threshold) return;
436
+ if (entry.level === "error") console.error(entry);
437
+ else if (entry.level === "warn") console.warn(entry);
438
+ else console.log(entry);
439
+ } };
440
+ }
441
+ /**
442
+ * Install mode-selected default sinks at onInit. The in-memory trace is always
443
+ * on (`state.entries`); the console sink is added only in dev/production. `dev`
444
+ * prints everything (debug+); `production` prints `info`+ only, so the per-phase
445
+ * `debug` events (build:bundle, build:pages, …) don't spam a prod build. Both
446
+ * modes still record all levels in the in-memory trace.
447
+ *
448
+ * @param ctx - Core plugin context (`{ config, state }`).
449
+ * @param ctx.config - Resolved log config (`{ mode }`).
450
+ * @param ctx.state - Mutable log state (`{ entries, sinks }`).
451
+ * @example
452
+ * ```ts
453
+ * // "dev" -> [consoleSink("debug")]; "production" -> [consoleSink("info")]; "test"/"silent" -> []
454
+ * ```
455
+ */
456
+ function installDefaultSinks(ctx) {
457
+ if (ctx.config.mode === "dev") ctx.state.sinks.push(consoleSink("debug"));
458
+ else if (ctx.config.mode === "production") ctx.state.sinks.push(consoleSink("info"));
459
+ }
460
+ //#endregion
461
+ //#region src/plugins/log/state.ts
462
+ /**
463
+ * Create fresh log state: an empty append-only trace and an empty sink list.
464
+ * No module-level singletons — guarantees per-`createApp` isolation (two
465
+ * `createApp` calls never share `entries` or `sinks`).
466
+ *
467
+ * @param _ctx - Core plugin context (`{ config }`); unused at construction.
468
+ * @returns A fresh `LogState` with empty `entries` and `sinks` arrays.
469
+ * @example
470
+ * ```ts
471
+ * const state = createLogState({ config: { mode: "test" } }); // { entries: [], sinks: [] }
472
+ * ```
473
+ */
474
+ function createLogState(_ctx) {
475
+ return {
476
+ entries: [],
477
+ sinks: []
478
+ };
479
+ }
480
+ /**
481
+ * Core logging plugin — always-on in-memory trace + `expect()` event-trace DSL.
482
+ * API injected as `ctx.log` on every regular plugin and surfaced as `app.log`.
483
+ * No depends / events / hooks (core plugin per spec/03 §5).
484
+ *
485
+ * @see README.md
486
+ */
487
+ const logPlugin = createCorePlugin("log", {
488
+ config: { mode: "production" },
489
+ createState: createLogState,
490
+ api: createLogApi,
491
+ onInit: installDefaultSinks
492
+ });
493
+ //#endregion
494
+ //#region src/plugins/env/api.ts
495
+ /** Error prefix for all env API failures. */
496
+ const ERROR_PREFIX$1 = "[web]";
497
+ /**
498
+ * Creates the env plugin API surface mounted at `ctx.env`. Closes over
499
+ * `ctx.state` ({@link EnvState}) and reads the frozen `resolved` / `publicMap`
500
+ * maps; closures never return a raw `ctx.state` reference.
501
+ *
502
+ * @param ctx - Core plugin context carrying the frozen env state.
503
+ * @param ctx.state - The resolved + public {@link EnvState} maps.
504
+ * @returns The {@link EnvApi} accessor surface mounted at `ctx.env`.
505
+ * @example
506
+ * ```ts
507
+ * const api = createEnvApi(ctx);
508
+ * api.get("PUBLIC_API_URL");
509
+ * ```
510
+ */
511
+ function createEnvApi(ctx) {
512
+ const { resolved, publicMap } = ctx.state;
513
+ return {
514
+ /**
515
+ * Reads a resolved variable.
516
+ *
517
+ * @param key - Variable name.
518
+ * @returns The value, or `undefined` if not present.
519
+ * @example
520
+ * ```ts
521
+ * api.get("PUBLIC_API_URL");
522
+ * ```
523
+ */
524
+ get(key) {
525
+ return resolved.get(key);
526
+ },
527
+ /**
528
+ * Reads a variable that must exist.
529
+ *
530
+ * @param key - Variable name.
531
+ * @returns The value.
532
+ * @throws {Error} If the variable is undefined.
533
+ * @example
534
+ * ```ts
535
+ * api.require("DEPLOY_TOKEN");
536
+ * ```
537
+ */
538
+ require(key) {
539
+ const value = resolved.get(key);
540
+ if (value === void 0) throw new Error(`${ERROR_PREFIX$1} env: required variable "${key}" is not defined.`);
541
+ return value;
542
+ },
543
+ /**
544
+ * Tests presence of a resolved variable.
545
+ *
546
+ * @param key - Variable name.
547
+ * @returns `true` if a value is present.
548
+ * @example
549
+ * ```ts
550
+ * api.has("PUBLIC_API_URL");
551
+ * ```
552
+ */
553
+ has(key) {
554
+ return resolved.has(key);
555
+ },
556
+ /**
557
+ * Returns all public variables as a frozen plain object — a fresh copy,
558
+ * never the raw state map.
559
+ *
560
+ * @returns A frozen `Record` of public variable names to values.
561
+ * @example
562
+ * ```ts
563
+ * const payload = { ...api.getPublic() };
564
+ * ```
565
+ */
566
+ getPublic() {
567
+ return Object.freeze(Object.fromEntries(publicMap));
568
+ },
569
+ /**
570
+ * Returns the already-frozen map of public variables.
571
+ *
572
+ * @returns The frozen public map.
573
+ * @example
574
+ * ```ts
575
+ * [...api.getPublicMap()];
576
+ * ```
577
+ */
578
+ getPublicMap() {
579
+ return publicMap;
580
+ }
581
+ };
582
+ }
583
+ //#endregion
584
+ //#region src/plugins/env/state.ts
585
+ /**
586
+ * Creates initial env plugin state: two empty, mutable maps that are populated
587
+ * and frozen by `validateSchema` (the `onInit`) at `createApp` time.
588
+ *
589
+ * @returns A fresh `EnvState` with empty `resolved` and `publicMap` maps.
590
+ * @example
591
+ * ```ts
592
+ * const state = createEnvState();
593
+ * state.resolved.size; // 0
594
+ * ```
595
+ */
596
+ function createEnvState() {
597
+ return {
598
+ resolved: /* @__PURE__ */ new Map(),
599
+ publicMap: /* @__PURE__ */ new Map()
600
+ };
601
+ }
602
+ //#endregion
603
+ //#region src/plugins/env/validate.ts
604
+ /** Error message thrown by every frozen-map mutator. */
605
+ const FROZEN_MESSAGE = "env: map is frozen and cannot be mutated";
606
+ /** Error prefix for all resolution-pipeline failures. */
607
+ const ERROR_PREFIX = "[web]";
608
+ /** The `Map` mutators redefined as throwers when a map is frozen. */
609
+ const FROZEN_METHODS = [
610
+ "set",
611
+ "clear",
612
+ "delete"
613
+ ];
614
+ /**
615
+ * Throws the canonical frozen-map error; installed as a map's `set`/`clear`/`delete`.
616
+ *
617
+ * @throws {TypeError} Always, signalling the map is frozen.
618
+ * @example
619
+ * ```ts
620
+ * frozenThrower(); // throws TypeError
621
+ * ```
622
+ */
623
+ function frozenThrower() {
624
+ throw new TypeError(FROZEN_MESSAGE);
625
+ }
626
+ /**
627
+ * Coerces a raw provider value to its effective presence: an empty string counts
628
+ * as "absent" so a `KEY=""` falls through to later providers.
629
+ *
630
+ * @param raw - The raw value a provider supplied for a key (possibly `undefined`).
631
+ * @returns The value, or `undefined` when it is missing or an empty string.
632
+ * @example
633
+ * ```ts
634
+ * coerceEmpty(""); // => undefined
635
+ * coerceEmpty("3000"); // => "3000"
636
+ * ```
637
+ */
638
+ function coerceEmpty(raw) {
639
+ return raw === "" ? void 0 : raw;
640
+ }
641
+ /**
642
+ * Merges providers in array order, coercing empty strings to `undefined` before
643
+ * precedence so a `KEY=""` falls through to later providers. First non-empty
644
+ * value wins.
645
+ *
646
+ * @param config - The resolved env config carrying the ordered providers.
647
+ * @returns A flat record of the first defined value found per key.
648
+ * @example
649
+ * ```ts
650
+ * mergeProviders({ providers: [a, b], schema: {}, publicPrefix: "PUBLIC_" });
651
+ * ```
652
+ */
653
+ function mergeProviders(config) {
654
+ const merged = {};
655
+ for (const provider of config.providers) for (const [key, raw] of Object.entries(provider.load())) {
656
+ const value = coerceEmpty(raw);
657
+ if (value !== void 0 && merged[key] === void 0) merged[key] = value;
658
+ }
659
+ return merged;
660
+ }
661
+ /**
662
+ * Bidirectionally enforces the `PUBLIC_` naming convention against each schema
663
+ * entry's `public` flag. Throws on either violation direction.
664
+ *
665
+ * @param config - The resolved env config carrying `schema` + `publicPrefix`.
666
+ * @throws {Error} If a public var lacks the prefix, or a prefixed var is not public.
667
+ * @example
668
+ * ```ts
669
+ * crossCheckPublicPrefix(config); // throws if PUBLIC_X is not public:true
670
+ * ```
671
+ */
672
+ function crossCheckPublicPrefix(config) {
673
+ const { schema, publicPrefix } = config;
674
+ for (const [key, spec] of Object.entries(schema)) {
675
+ const hasPrefix = key.startsWith(publicPrefix);
676
+ if (spec.public === true && !hasPrefix) throw new Error(`${ERROR_PREFIX} env: "${key}" is marked public but does not start with "${publicPrefix}".`);
677
+ if (hasPrefix && spec.public !== true) throw new Error(`${ERROR_PREFIX} env: "${key}" starts with "${publicPrefix}" but is not marked public:true.`);
678
+ }
679
+ }
680
+ /**
681
+ * Seals a map so `set`, `clear`, and `delete` throw, then `Object.freeze`s it
682
+ * for defense in depth. Closes the `Object.freeze`-on-`Map` mutability hole by
683
+ * redefining the mutators as non-writable, non-configurable throwers.
684
+ *
685
+ * @param map - The map to freeze in place.
686
+ * @example
687
+ * ```ts
688
+ * freezeMap(state.resolved); // resolved.set(...) now throws
689
+ * ```
690
+ */
691
+ function freezeMap(map) {
692
+ for (const method of FROZEN_METHODS) Object.defineProperty(map, method, {
693
+ value: frozenThrower,
694
+ writable: false,
695
+ configurable: false,
696
+ enumerable: false
697
+ });
698
+ Object.freeze(map);
699
+ }
700
+ /**
701
+ * Populates `state.publicMap` with the schema-driven public subset: every
702
+ * `public:true` schema key that resolved to a defined value. This map is the only
703
+ * sanctioned input to a browser-facing `define`, so it stays schema-scoped (never
704
+ * includes non-schema provider keys).
705
+ *
706
+ * @param schema - The per-variable schema from {@link EnvConfig}.
707
+ * @param merged - The merged provider values keyed by variable name.
708
+ * @param publicMap - The mutable public map to fill in place.
709
+ * @example
710
+ * ```ts
711
+ * populatePublicMap(config.schema, merged, state.publicMap);
712
+ * ```
713
+ */
714
+ function populatePublicMap(schema, merged, publicMap) {
715
+ for (const [key, spec] of Object.entries(schema)) {
716
+ const value = merged[key];
717
+ if (spec.public === true && value !== void 0) publicMap.set(key, value);
718
+ }
719
+ }
720
+ /**
721
+ * Populates `state.resolved` with EVERY merged key that carries a defined value
722
+ * (spec/02 Lifecycle §5), including non-schema provider keys so
723
+ * `ctx.env.require()` works for dynamic keys.
724
+ *
725
+ * @param merged - The merged provider values keyed by variable name.
726
+ * @param resolved - The mutable resolved map to fill in place.
727
+ * @example
728
+ * ```ts
729
+ * populateResolved(merged, state.resolved);
730
+ * ```
731
+ */
732
+ function populateResolved(merged, resolved) {
733
+ for (const [key, value] of Object.entries(merged)) resolved.set(key, value);
734
+ }
735
+ /**
736
+ * Resolves, validates, and freezes the environment table at `onInit`.
737
+ *
738
+ * Pipeline order: merge providers (with empty-string → undefined coercion) →
739
+ * `PUBLIC_` bidirectional cross-check → apply defaults → assert required →
740
+ * populate `state.resolved` / `state.publicMap` → freeze both via
741
+ * {@link freezeMap}. Fail-fast: any violation throws at `createApp` time.
742
+ *
743
+ * @param ctx - Core plugin context (`{ config, state }`).
744
+ * @param ctx.config - The resolved {@link EnvConfig}.
745
+ * @param ctx.state - The mutable {@link EnvState} to populate and freeze.
746
+ * @throws {Error} On a `PUBLIC_` cross-check violation or a missing required variable.
747
+ * @example
748
+ * ```ts
749
+ * validateSchema(ctx); // throws on missing required / PUBLIC_ violation
750
+ * ```
751
+ */
752
+ function validateSchema(ctx) {
753
+ const { config, state } = ctx;
754
+ const { schema } = config;
755
+ const merged = mergeProviders(config);
756
+ crossCheckPublicPrefix(config);
757
+ for (const [key, spec] of Object.entries(schema)) {
758
+ if (merged[key] === void 0 && spec.default !== void 0) merged[key] = spec.default;
759
+ if (merged[key] === void 0 && spec.required === true) throw new Error(`${ERROR_PREFIX} env: required variable "${key}" is not defined by any provider or default.`);
760
+ }
761
+ populatePublicMap(schema, merged, state.publicMap);
762
+ populateResolved(merged, state.resolved);
763
+ freezeMap(state.resolved);
764
+ freezeMap(state.publicMap);
765
+ }
766
+ //#endregion
767
+ //#region src/plugins/env/providers.browser.ts
768
+ /** Default `globalThis` property holding a runtime-injected public-env snapshot. */
769
+ const DEFAULT_GLOBAL_KEY = "__ENV__";
770
+ /**
771
+ * A browser-safe {@link EnvProvider} that reads `import.meta.env` and an optional
772
+ * `globalThis[globalKey]` snapshot, merging them with the runtime global winning.
773
+ * Contains zero `node:*` imports, so it is safe to include in the client bundle.
774
+ * Never throws on missing sources — each absent source resolves to `{}`.
775
+ *
776
+ * @param options - Optional settings.
777
+ * @param options.globalKey - `globalThis` key to read a public-env snapshot from. Defaults to `"__ENV__"`.
778
+ * @returns An {@link EnvProvider} named `browser-env`.
779
+ * @example
780
+ * ```ts
781
+ * const provider = browserEnv();
782
+ * provider.load(); // { PUBLIC_API_URL: "/api", ... }
783
+ * ```
784
+ */
785
+ function browserEnv(options) {
786
+ const globalKey = options?.globalKey ?? DEFAULT_GLOBAL_KEY;
787
+ return {
788
+ name: "browser-env",
789
+ /**
790
+ * Merges `import.meta.env` with `globalThis[globalKey]`, the runtime global
791
+ * winning. Each absent source resolves to `{}`; never throws.
792
+ *
793
+ * @returns The merged environment record.
794
+ * @example
795
+ * ```ts
796
+ * browserEnv().load();
797
+ * ```
798
+ */
799
+ load() {
800
+ const importEnv = import.meta.env ?? {};
801
+ const globalObject = globalThis[globalKey] ?? {};
802
+ return {
803
+ ...importEnv,
804
+ ...globalObject
805
+ };
806
+ }
807
+ };
808
+ }
809
+ /**
810
+ * Core plugin that resolves, validates, and freezes the environment at `onInit`,
811
+ * exposing a read-only accessor at `ctx.env`. No `onStart`/`onStop` — holds no resource.
812
+ *
813
+ * @example
814
+ * ```ts
815
+ * createApp({ pluginConfigs: { env: { schema: { PUBLIC_API_URL: { public: true } } } } });
816
+ * ```
817
+ */
818
+ const envPlugin = createCorePlugin("env", {
819
+ config: {
820
+ schema: {},
821
+ providers: [],
822
+ publicPrefix: "PUBLIC_"
823
+ },
824
+ createState: createEnvState,
825
+ api: createEnvApi,
826
+ onInit: validateSchema
827
+ });
828
+ //#endregion
829
+ //#region src/plugins/env/providers.ts
830
+ /**
831
+ * @file env plugin — built-in providers: dotenv, processEnv, cloudflareBindings.
832
+ */
833
+ /** Default dotenv file path: optional local overrides. */
834
+ const DEFAULT_DOTENV_PATH = ".env.local";
835
+ /** Property on `globalThis` that the consumer sets per Cloudflare request. */
836
+ const CLOUDFLARE_GLOBAL = "__CLOUDFLARE_ENV__";
837
+ /** `String.indexOf` sentinel meaning "no `=` separator on this line". */
838
+ const NO_SEPARATOR = -1;
839
+ /**
840
+ * Strips a single matching pair of surrounding double or single quotes from a
841
+ * value. Leaves unquoted values (and trailing inline comments) untouched.
842
+ *
843
+ * @param value - The already-trimmed raw value.
844
+ * @returns The value with one outer quote pair removed, if present.
845
+ * @example
846
+ * ```ts
847
+ * stripQuotes('"a"'); // "a"
848
+ * stripQuotes("plain # c"); // "plain # c"
849
+ * ```
850
+ */
851
+ function stripQuotes(value) {
852
+ if (value.length < 2) return value;
853
+ const first = value[0];
854
+ const last = value.at(-1);
855
+ if ((first === "\"" || first === "'") && first === last) return value.slice(1, -1);
856
+ return value;
857
+ }
858
+ /**
859
+ * Reports whether a trimmed line carries no assignment — a blank line or a
860
+ * full-line `#` comment — and should be skipped by the parser.
861
+ *
862
+ * @param trimmed - A whitespace-trimmed line from the dotenv text.
863
+ * @returns `true` when the line is empty or a comment.
864
+ * @example
865
+ * ```ts
866
+ * isIgnoredLine(""); // true
867
+ * isIgnoredLine("# note"); // true
868
+ * isIgnoredLine("A=1"); // false
869
+ * ```
870
+ */
871
+ function isIgnoredLine(trimmed) {
872
+ return trimmed === "" || trimmed.startsWith("#");
873
+ }
874
+ /**
875
+ * Parses `.env`-style text into a flat record. Handles CRLF/LF, blank lines,
876
+ * full-line `#` comments, first-`=` splitting, key/value trimming, and a single
877
+ * outer quote pair. Does not strip trailing inline comments on unquoted values.
878
+ *
879
+ * @param text - The raw file contents.
880
+ * @returns A flat record of parsed key/value pairs.
881
+ * @example
882
+ * ```ts
883
+ * parseDotenv('A=1\nB="two"'); // { A: "1", B: "two" }
884
+ * ```
885
+ */
886
+ function parseDotenv(text) {
887
+ const out = {};
888
+ for (const line of text.split(/\r?\n/)) {
889
+ const trimmed = line.trim();
890
+ if (isIgnoredLine(trimmed)) continue;
891
+ const eq = trimmed.indexOf("=");
892
+ if (eq === NO_SEPARATOR) continue;
893
+ const key = trimmed.slice(0, eq).trim();
894
+ out[key] = stripQuotes(trimmed.slice(eq + 1).trim());
895
+ }
896
+ return out;
897
+ }
898
+ /**
899
+ * A zero-dependency `.env`-style provider that re-reads and re-parses the file
900
+ * from disk on every `load()`. Missing file resolves to `{}` (optional
901
+ * overrides). Strips a single outer quote pair; does not strip trailing inline
902
+ * comments on unquoted values.
903
+ *
904
+ * @param path - Path to the dotenv file. Defaults to `.env.local`.
905
+ * @returns An {@link EnvProvider} named `dotenv:<path>` that reads fresh per call.
906
+ * @example
907
+ * ```ts
908
+ * const provider = dotenv(".env.local");
909
+ * provider.load(); // { PUBLIC_API_URL: "/api", ... }
910
+ * ```
911
+ */
912
+ function dotenv(path = DEFAULT_DOTENV_PATH) {
913
+ return {
914
+ name: `dotenv:${path}`,
915
+ /**
916
+ * Reads and parses the dotenv file fresh from disk; `{}` if it is missing.
917
+ *
918
+ * @returns The parsed environment record, or `{}` when the file is absent.
919
+ * @example
920
+ * ```ts
921
+ * dotenv(".env.local").load();
922
+ * ```
923
+ */
924
+ load() {
925
+ if (!existsSync(path)) return {};
926
+ return parseDotenv(readFileSync(path, "utf8"));
927
+ }
928
+ };
929
+ }
930
+ /**
931
+ * A provider that returns a shallow copy of `process.env` at `load()` time.
932
+ *
933
+ * @returns An {@link EnvProvider} named `process-env`.
934
+ * @example
935
+ * ```ts
936
+ * const provider = processEnv();
937
+ * provider.load().HOME; // current process value
938
+ * ```
939
+ */
940
+ function processEnv() {
941
+ return {
942
+ name: "process-env",
943
+ /**
944
+ * Returns a shallow copy of `process.env` at call time.
945
+ *
946
+ * @returns A fresh shallow copy of `process.env`.
947
+ * @example
948
+ * ```ts
949
+ * processEnv().load();
950
+ * ```
951
+ */
952
+ load() {
953
+ return { ...process.env };
954
+ }
955
+ };
956
+ }
957
+ /**
958
+ * A provider that reads live, per-request Cloudflare bindings from
959
+ * `globalThis.__CLOUDFLARE_ENV__` at `load()` time (`?? {}` when absent). Never
960
+ * caches the binding object; the consumer owns the global's request lifecycle.
961
+ *
962
+ * @returns An {@link EnvProvider} named `cloudflare`.
963
+ * @example
964
+ * ```ts
965
+ * globalThis.__CLOUDFLARE_ENV__ = env; // set by the request handler
966
+ * const provider = cloudflareBindings();
967
+ * provider.load(); // reads the current request's bindings
968
+ * ```
969
+ */
970
+ function cloudflareBindings() {
971
+ return {
972
+ name: "cloudflare",
973
+ /**
974
+ * Reads `globalThis.__CLOUDFLARE_ENV__` fresh, never caching the bindings.
975
+ *
976
+ * @returns The current Cloudflare bindings, or `{}` when the global is unset.
977
+ * @example
978
+ * ```ts
979
+ * cloudflareBindings().load();
980
+ * ```
981
+ */
982
+ load() {
983
+ return globalThis[CLOUDFLARE_GLOBAL] ?? {};
984
+ }
985
+ };
986
+ }
987
+ //#endregion
988
+ //#region src/plugins/log/types.ts
989
+ var types_exports$1 = /* @__PURE__ */ __exportAll({});
990
+ //#endregion
991
+ //#region src/plugins/env/types.ts
992
+ var types_exports = /* @__PURE__ */ __exportAll({});
993
+ //#endregion
994
+ export { types_exports as Env, types_exports$1 as Log, browserEnv, cloudflareBindings, dotenv, envPlugin, logPlugin, processEnv };