@moku-labs/web 1.15.1 → 1.16.1

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.
@@ -871,7 +871,7 @@ type Api$1 = {
871
871
  composeTitle(head: HeadConfig | undefined): string;
872
872
  };
873
873
  declare namespace types_d_exports$4 {
874
- export { COMPONENT_HOOK_NAMES, ComponentContext, ComponentDef, ComponentHooks, ComponentInstance, ExtractApi, PageData, ResolvedSpaConfig, SpaApi, SpaConfig, SpaContext, SpaDataReader, SpaEmitFunction, SpaEvents, SpaKernel, SpaKernelDeps, SpaRequire, SpaState };
874
+ export { AnyVNode, COMPONENT_HOOK_NAMES, ComponentContext, ComponentDef, ComponentEventHandler, ComponentEvents, ComponentHooks, ComponentInstance, ComponentRender, ComponentRouteSlice, ComponentSpec, ComponentSpecExtras, ComponentStateFactory, ExtractApi, PageData, RenderResult, ResolvedSpaConfig, SpaApi, SpaConfig, SpaContext, SpaDataReader, SpaEmitFunction, SpaEvents, SpaKernel, SpaKernelDeps, SpaRequire, SpaState };
875
875
  }
876
876
  /** Payload map for the events `spa` emits, used to type the kernel's `emit` closure. */
877
877
  type SpaEvents = {
@@ -972,12 +972,83 @@ interface ResolvedSpaConfig {
972
972
  components: ComponentDef[];
973
973
  }
974
974
  /**
975
- * Context handed to every component lifecycle hook — the bound element + page data,
976
- * plus the matched route's `params`/`meta`/`locale` and a link builder, so an island
977
- * can read its route context (e.g. a `card` route's `ctx.meta.focus` + `ctx.params.id`)
978
- * directly, without the page bridging it through `data-*` attributes.
975
+ * What a component's `render` may return:
976
+ * - a Preact `VNode` committed into the host through the lazy Preact gate (`commitVNode`);
977
+ * - a `Node` replaces the host's children;
978
+ * - a `string` set as the host's `innerHTML`;
979
+ * - `void`/`undefined` — the render mutated the DOM itself (DOM-only islands → no Preact loaded).
979
980
  */
980
- interface ComponentContext {
981
+ type RenderResult = AnyVNode | Node | string | void;
982
+ /**
983
+ * A Preact `VNode` of ANY props shape. A render returns `h(Component, props)`, i.e. a
984
+ * `VNode<SomeProps>`; the props generic is invariant under `exactOptionalPropertyTypes`,
985
+ * so the only supertype that accepts every concrete `VNode<P>` is `VNode<any>`.
986
+ */
987
+ type AnyVNode = import("preact").VNode<any>;
988
+ /**
989
+ * Factory that builds a component's typed per-instance state (mirrors a plugin's
990
+ * `createState`). Called ONCE at mount; the returned object is stored on the
991
+ * {@link ComponentInstance} and exposed read-only as `ctx.state`.
992
+ *
993
+ * @param ctx - The component context for this instance (state is not yet set).
994
+ * @returns The initial per-instance state.
995
+ * @example
996
+ * state: (ctx): BoardState => ({ boardId: ctx.params.id ?? "", cards: [] })
997
+ */
998
+ type ComponentStateFactory<S extends object> = (ctx: ComponentContext<S>) => S;
999
+ /**
1000
+ * Pure render of `(state, ctx)` → {@link RenderResult}. Called after mount-state-init
1001
+ * and again (microtask-batched) after every `ctx.set`. Must be free of side effects
1002
+ * beyond producing its result.
1003
+ *
1004
+ * @param state - The current per-instance state (read-only).
1005
+ * @param ctx - The component context for this instance.
1006
+ * @returns The render result to commit into the host.
1007
+ * @example
1008
+ * render: (state) => h(BoardView, { snapshot: state.snapshot })
1009
+ */
1010
+ type ComponentRender<S extends object> = (state: Readonly<S>, ctx: ComponentContext<S>) => RenderResult;
1011
+ /**
1012
+ * A delegated DOM event handler. `target` is the element matched by the key's selector
1013
+ * (already resolved via `closest` — no `instanceof`/`closest` ceremony in the body).
1014
+ *
1015
+ * Typed `void` for ergonomics (the void-return rule accepts async handlers returning
1016
+ * `Promise<void>` too); the kernel ignores any returned value.
1017
+ *
1018
+ * @param ctx - The component context (carries the live per-instance `state`).
1019
+ * @param event - The raw DOM event.
1020
+ * @param target - The element matched by the selector (the host when no selector).
1021
+ * @returns void (a returned promise is ignored by the kernel).
1022
+ * @example
1023
+ * (ctx, event, button) => { event.preventDefault(); ctx.set({ open: true }); }
1024
+ */
1025
+ type ComponentEventHandler<S extends object> = (ctx: ComponentContext<S>, event: Event, target: Element) => void;
1026
+ /**
1027
+ * Declarative delegated event map. Each key is `"<type> <selector>"` (the selector is
1028
+ * optional → a host-level listener). ONE real listener per event TYPE is attached to
1029
+ * the host; dispatch walks `event.target.closest(selector)` within the host. All
1030
+ * listeners are auto-removed on destroy.
1031
+ *
1032
+ * @example
1033
+ * events: {
1034
+ * "click [data-action='delete']": (ctx, _e, btn) => ctx.set(removeCard(ctx.state, btn)),
1035
+ * "submit [data-add]": (ctx, e) => { e.preventDefault(); add(ctx); }
1036
+ * }
1037
+ */
1038
+ type ComponentEvents<S extends object> = Record<string, ComponentEventHandler<S>>;
1039
+ /**
1040
+ * Context handed to every component lifecycle hook, render, and event handler — the
1041
+ * bound element + page data, plus the matched route's `params`/`meta`/`locale` and a
1042
+ * link builder, so an island can read its route context (e.g. a `card` route's
1043
+ * `ctx.meta.focus` + `ctx.params.id`) directly, without the page bridging it through
1044
+ * `data-*` attributes.
1045
+ *
1046
+ * Generic over the per-instance state `S` (default `undefined` so every existing
1047
+ * hooks-only island still type-checks). The additive members (`state`/`set`/`flush`/
1048
+ * `cleanup`/`component`) are ALWAYS-PRESENT functions — never optional keys — so they
1049
+ * never trip `exactOptionalPropertyTypes`.
1050
+ */
1051
+ interface ComponentContext<S = undefined> {
981
1052
  /** The element the component instance is bound to. */
982
1053
  el: Element;
983
1054
  /** Page data extracted from the `script#__DATA__` payload. */
@@ -990,9 +1061,52 @@ interface ComponentContext {
990
1061
  readonly locale: string;
991
1062
  /** Build a link to a named route by pattern substitution (same output as `app.router.toUrl`). */
992
1063
  readonly url: (name: string, params?: Record<string, string>) => string;
1064
+ /** The live per-instance state (the object returned by `spec.state`). `undefined` for legacy hooks-only islands. */
1065
+ readonly state: S;
1066
+ /**
1067
+ * Merge a patch into the per-instance state, then schedule ONE batched render.
1068
+ * Accepts a partial object or an updater `(prev) => partial`. A no-op for legacy
1069
+ * islands with no `state`/`render`.
1070
+ *
1071
+ * @param patch - A partial state object, or an updater returning one.
1072
+ * @returns void
1073
+ * @example
1074
+ * ctx.set({ open: true });
1075
+ * ctx.set(prev => ({ count: prev.count + 1 }));
1076
+ */
1077
+ set(patch: Partial<S> | ((prev: Readonly<S>) => Partial<S>)): void;
1078
+ /**
1079
+ * Force a synchronous render now (drains any pending scheduled render). Rarely
1080
+ * needed in app code — `ctx.set` already schedules one; mainly a test seam.
1081
+ *
1082
+ * @returns void
1083
+ * @example
1084
+ * ctx.flush();
1085
+ */
1086
+ flush(): void;
1087
+ /**
1088
+ * Register a disposer run on `onDestroy` (subscriptions, timers, manual/global
1089
+ * listeners the declarative `events` map cannot cover). Disposers run LIFO.
1090
+ *
1091
+ * @param dispose - The teardown function.
1092
+ * @returns void
1093
+ * @example
1094
+ * ctx.cleanup(onPatch(p => applyPatch(ctx, p)));
1095
+ */
1096
+ cleanup(dispose: () => void): void;
1097
+ /**
1098
+ * Resolve another island's registered `api` by name. Returns `undefined` when no
1099
+ * provider is registered (optional-dependency semantics, mirroring `ctx.has`).
1100
+ *
1101
+ * @param name - The provider island's component name.
1102
+ * @returns The provider's api, or `undefined`.
1103
+ * @example
1104
+ * ctx.component<LightboxApi>("lightbox")?.open(slides, index);
1105
+ */
1106
+ component<T = unknown>(name: string): T | undefined;
993
1107
  }
994
- /** Lifecycle hooks a component may implement. */
995
- interface ComponentHooks {
1108
+ /** Lifecycle hooks a component may implement. Generic over the per-instance state `S`. */
1109
+ interface ComponentHooks<S = undefined> {
996
1110
  /**
997
1111
  * Called once when the instance is created (before DOM attach).
998
1112
  *
@@ -1001,7 +1115,7 @@ interface ComponentHooks {
1001
1115
  * @example
1002
1116
  * onCreate({ el }) { el.dataset.ready = "1"; }
1003
1117
  */
1004
- onCreate?(ctx: ComponentContext): void;
1118
+ onCreate?(ctx: ComponentContext<S>): void;
1005
1119
  /**
1006
1120
  * Called after the instance is attached to its element.
1007
1121
  *
@@ -1009,8 +1123,10 @@ interface ComponentHooks {
1009
1123
  * @returns void
1010
1124
  * @example
1011
1125
  * onMount({ el }) { el.textContent = "0"; }
1126
+ * @example
1127
+ * async onMount(ctx) { ctx.set({ items: await load() }); } // async is allowed; the harness awaits it via settle()
1012
1128
  */
1013
- onMount?(ctx: ComponentContext): void;
1129
+ onMount?(ctx: ComponentContext<S>): void;
1014
1130
  /**
1015
1131
  * Called when a navigation begins while this instance is mounted.
1016
1132
  *
@@ -1019,7 +1135,7 @@ interface ComponentHooks {
1019
1135
  * @example
1020
1136
  * onNavStart({ el }) { el.dataset.loading = ""; }
1021
1137
  */
1022
- onNavStart?(ctx: ComponentContext): void;
1138
+ onNavStart?(ctx: ComponentContext<S>): void;
1023
1139
  /**
1024
1140
  * Called when a navigation completes while this instance is mounted.
1025
1141
  *
@@ -1028,7 +1144,7 @@ interface ComponentHooks {
1028
1144
  * @example
1029
1145
  * onNavEnd({ el }) { delete el.dataset.loading; }
1030
1146
  */
1031
- onNavEnd?(ctx: ComponentContext): void;
1147
+ onNavEnd?(ctx: ComponentContext<S>): void;
1032
1148
  /**
1033
1149
  * Called before the instance is detached from its element.
1034
1150
  *
@@ -1037,7 +1153,7 @@ interface ComponentHooks {
1037
1153
  * @example
1038
1154
  * onUnMount({ el }) { el.replaceChildren(); }
1039
1155
  */
1040
- onUnMount?(ctx: ComponentContext): void;
1156
+ onUnMount?(ctx: ComponentContext<S>): void;
1041
1157
  /**
1042
1158
  * Called once when the instance is destroyed (after detach).
1043
1159
  *
@@ -1046,17 +1162,60 @@ interface ComponentHooks {
1046
1162
  * @example
1047
1163
  * onDestroy({ el }) { delete el.dataset.ready; }
1048
1164
  */
1049
- onDestroy?(ctx: ComponentContext): void;
1165
+ onDestroy?(ctx: ComponentContext<S>): void;
1050
1166
  }
1051
1167
  /** Allowed hook names — single source of truth for fail-fast validation. */
1052
1168
  declare const COMPONENT_HOOK_NAMES: readonly ["onCreate", "onMount", "onNavStart", "onNavEnd", "onUnMount", "onDestroy"];
1053
- /** A registered component definition. */
1169
+ /**
1170
+ * The plugin-mirror authoring form for {@link createComponent}: typed per-instance
1171
+ * `state`, `render`, declarative `events`, and a cross-island `api` on top of the
1172
+ * lifecycle hooks. All keys optional + additive; the presence of any spec-only key
1173
+ * (`state`/`render`/`events`/`api`) selects the spec overload of `createComponent`.
1174
+ *
1175
+ * @example
1176
+ * createComponent<{ boards: Board[] }>("board-list", {
1177
+ * state: () => ({ boards: [] }),
1178
+ * async onMount(ctx) { ctx.set({ boards: await ctx.component<Api>("api")!.list() }); },
1179
+ * render: (s) => h(BoardList, { boards: s.boards }),
1180
+ * events: { "submit [data-create]": (ctx, e) => { e.preventDefault(); create(ctx); } }
1181
+ * });
1182
+ */
1183
+ interface ComponentSpec<S extends object = object, A = unknown> extends ComponentHooks<S> {
1184
+ /** Build typed per-instance state at mount (stored on the instance, not a module WeakMap). */
1185
+ state?: ComponentStateFactory<S>;
1186
+ /** Pure render re-invoked (microtask-batched) on every `ctx.set`. */
1187
+ render?: ComponentRender<S>;
1188
+ /** Declarative delegated DOM events with auto-teardown. */
1189
+ events?: ComponentEvents<S>;
1190
+ /** Public api factory — registered under the component name; reached via `app.spa.component(name)`. */
1191
+ api?: (ctx: ComponentContext<S>) => A;
1192
+ }
1193
+ /**
1194
+ * The spec extras carried on a {@link ComponentDef}, type-erased to `object` state
1195
+ * (authors keep full `S` inference at the `createComponent` call site; the registry
1196
+ * stores the runtime-only erased form). Absent for legacy `(name, hooks)` defs.
1197
+ */
1198
+ interface ComponentSpecExtras {
1199
+ /** Per-instance state factory. */
1200
+ state?: ComponentStateFactory<object>;
1201
+ /** Render called on mount + after every `ctx.set`. */
1202
+ render?: ComponentRender<object>;
1203
+ /** Declarative delegated events. */
1204
+ events?: ComponentEvents<object>;
1205
+ /** Public api factory registered under the component name. */
1206
+ api?: (ctx: ComponentContext<object>) => unknown;
1207
+ }
1208
+ /** A registered component definition (an opaque token; author inference lives on `createComponent`). */
1054
1209
  interface ComponentDef {
1055
1210
  /** Unique component name (matched against `data-component`). */
1056
1211
  name: string;
1057
- /** Lifecycle hooks. */
1058
- hooks: ComponentHooks;
1212
+ /** Lifecycle hooks (the subset shared with the legacy form). */
1213
+ hooks: ComponentHooks<object>;
1214
+ /** Plugin-mirror extras (state/render/events/api). Absent for legacy `(name, hooks)` defs. */
1215
+ spec?: ComponentSpecExtras;
1059
1216
  }
1217
+ /** The matched-route slice carried on a live instance (params/meta/locale + link builder). */
1218
+ type ComponentRouteSlice = Pick<ComponentContext, "params" | "meta" | "locale" | "url">;
1060
1219
  /** A live, mounted component instance. */
1061
1220
  interface ComponentInstance {
1062
1221
  /** The definition this instance was created from. */
@@ -1069,6 +1228,26 @@ interface ComponentInstance {
1069
1228
  * page-specific: full unmount/destroy on every navigation.
1070
1229
  */
1071
1230
  persistent: boolean;
1231
+ /** The single per-instance context reused by every hook, event handler, and render. */
1232
+ ctx: ComponentContext<object>;
1233
+ /** Live per-instance state (the object returned by `spec.state`), or undefined for hooks-only islands. */
1234
+ state: object | undefined;
1235
+ /** This instance's public api (the object returned by `spec.api`), or undefined when none declared. */
1236
+ api: unknown;
1237
+ /** Current matched-route slice (updated on navigation; read by `ctx.params/meta/locale/url`). */
1238
+ route: ComponentRouteSlice;
1239
+ /** Current page data payload (updated on navigation; read by `ctx.data`). */
1240
+ data: PageData;
1241
+ /** Disposers from `ctx.cleanup` + the declarative `events` listeners — run LIFO on destroy. */
1242
+ cleanups: Array<() => void>;
1243
+ /** Synchronously drain a pending render (the `ctx.flush` implementation). */
1244
+ flush: () => void;
1245
+ /** True while a render is queued for the next microtask — coalesces multiple `set` calls. */
1246
+ renderScheduled: boolean;
1247
+ /** Re-entrancy depth guard for the render scheduler (a render that calls `ctx.set`). */
1248
+ renderDepth: number;
1249
+ /** onMount's returned promise (+ render-module load) — awaited by the test harness's `settle()`. */
1250
+ mountPromise: Promise<void> | undefined;
1072
1251
  }
1073
1252
  /** Page data payload parsed from the inline `script#__DATA__` element. */
1074
1253
  type PageData = Record<string, unknown>;
@@ -1152,6 +1331,8 @@ interface SpaState {
1152
1331
  registeredComponents: Map<string, ComponentDef>;
1153
1332
  /** Live component instances keyed by their bound element. */
1154
1333
  instances: Map<Element, ComponentInstance>;
1334
+ /** Registered island apis by component name (the cross-island `ctx.component`/`app.spa.component` seam). */
1335
+ componentApis: Map<string, unknown>;
1155
1336
  /** The current resolved URL (pathname + search). */
1156
1337
  currentUrl: string;
1157
1338
  /** Teardown handle for the attached router listeners (null when detached). */
@@ -1189,6 +1370,16 @@ type SpaApi = {
1189
1370
  * const url = app.spa.current(); // "/about"
1190
1371
  */
1191
1372
  current(): string;
1373
+ /**
1374
+ * Resolve a registered island's api by name (the cross-island seam). Returns
1375
+ * `undefined` when no provider with that name is currently registered.
1376
+ *
1377
+ * @param name - The provider island's component name.
1378
+ * @returns The provider's api, or `undefined`.
1379
+ * @example
1380
+ * app.spa.component<LightboxApi>("lightbox")?.open(slides, 0);
1381
+ */
1382
+ component<T = unknown>(name: string): T | undefined;
1192
1383
  };
1193
1384
  //#endregion
1194
1385
  //#region src/plugins/site/index.d.ts
@@ -1408,21 +1599,26 @@ declare const headPlugin: import("@moku-labs/core").PluginInstance<"head", Confi
1408
1599
  //#endregion
1409
1600
  //#region src/plugins/spa/components.d.ts
1410
1601
  /**
1411
- * Create a validated component definition. Validates hook names at registration
1412
- * for fail-fast typo detection (e.g. `onMout` throws immediately) and asserts
1413
- * each provided hook is a function.
1602
+ * Create a validated component definition. Accepts either the legacy hooks-only form
1603
+ * (`createComponent("counter", { onMount() {} })`) or the plugin-mirror spec form
1604
+ * (`createComponent("board", { state, render, events, api, ...hooks })`). Spec-only
1605
+ * keys (`state`/`render`/`events`/`api`) are partitioned out before hook-name
1606
+ * validation, so a real typo (e.g. `onMout`) still throws immediately while the spec
1607
+ * keys are accepted.
1414
1608
  *
1415
1609
  * @param name - Unique component name.
1416
- * @param hooks - Lifecycle hook implementations.
1610
+ * @param spec - Lifecycle hooks, or the `{ state, render, events, api, ...hooks }` spec.
1417
1611
  * @returns A `ComponentDef` ready to `register`.
1418
- * @throws {Error} If `name` is empty, any hook key is not in
1419
- * `COMPONENT_HOOK_NAMES`, or any provided hook value is not a function.
1612
+ * @throws {Error} If `name` is empty, a hook key is unknown, or an extra/hook value has the wrong shape.
1613
+ * @example
1614
+ * const counter = createComponent("counter", { onMount({ el }) { el.textContent = "0"; } });
1420
1615
  * @example
1421
- * const counter = createComponent("counter", {
1422
- * onMount({ el }) { el.textContent = "0"; }
1616
+ * const list = createComponent<{ items: string[] }>("list", {
1617
+ * state: () => ({ items: [] }),
1618
+ * render: (s) => h(List, { items: s.items })
1423
1619
  * });
1424
1620
  */
1425
- declare function createComponent(name: string, hooks: ComponentHooks): ComponentDef;
1621
+ declare function createComponent<S extends object = object, A = unknown>(name: string, spec: ComponentSpec<S, A>): ComponentDef;
1426
1622
  //#endregion
1427
1623
  //#region src/plugins/spa/lazy-embed.d.ts
1428
1624
  /**