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