C6: Runtime kernel owns data, status, error — adapters subscribe

The kernel is no longer a blind refetch pipe. Each context entry has:
  { data, status: idle|loading|success|error, error }

registerContext() returns { getState, subscribe, refetch, unregister }.
Adapters subscribe to state changes via callbacks. The kernel does
the fetch and notifies subscribers with the new state.

React adapter uses useSyncExternalStore for tear-free reads.
Vue adapter uses ref + subscribe callback.
Svelte adapter uses readable store backed by kernel subscription.

All three adapters also get:
- Mutation hooks with { mutate, isPending, error } (fixes H5)
- Vue: onServerPrefetch for Nuxt SSR (fixes M9)
- Svelte: readable store auto-cleans up on unsubscribe (fixes H9)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-04-07 12:38:53 -04:00
parent 07f1c7842c
commit bb88fd984b
7 changed files with 586 additions and 361 deletions

View File

@@ -1,5 +1,8 @@
/**
* React Stage 2 — Generates hooks + context providers from Stage 1 output.
*
* Generated providers subscribe to the runtime kernel for state.
* The kernel owns data, status, and error. React just renders.
*/
function pascalCase(str) {
@@ -19,8 +22,8 @@ export function generateReactAdapter(schema) {
'',
'// AUTO-GENERATED by mizan — do not edit',
'',
"import { createContext, useContext, useState, useEffect, useCallback, type ReactNode } from 'react'",
"import { registerContext, mizanCall, mizanFetch } from '@mizan/runtime'",
"import { createContext, useContext, useState, useEffect, useCallback, useRef, useSyncExternalStore, type ReactNode } from 'react'",
"import { registerContext, mizanFetch, mizanCall, type ContextState } from '@mizan/runtime'",
'',
]
@@ -38,103 +41,114 @@ export function generateReactAdapter(schema) {
lines.push('')
}
// ── Global context hooks ────────────────────────────────────────────
// ── Helper hook: subscribe to kernel state ──────────────────────────
if (globalContexts.length > 0) {
const p = pascalCase('global')
lines.push('// Subscribe to kernel state via useSyncExternalStore')
lines.push('function useContextState<T>(')
lines.push(' name: string,')
lines.push(' params: Record<string, any>,')
lines.push(' fetchFn: () => Promise<T>,')
lines.push(' initialData?: T,')
lines.push('): ContextState<T> {')
lines.push(' const ref = useRef<ReturnType<typeof registerContext> | null>(null)')
lines.push('')
lines.push(' if (!ref.current) {')
lines.push(' ref.current = registerContext(name, params, fetchFn, initialData)')
lines.push(' }')
lines.push('')
lines.push(' const handle = ref.current')
lines.push('')
lines.push(' // Fetch on mount if no data')
lines.push(' useEffect(() => {')
lines.push(" if (handle.getState().status === 'idle') handle.refetch()")
lines.push(' return () => handle.unregister()')
lines.push(' }, [handle])')
lines.push('')
lines.push(' return useSyncExternalStore(')
lines.push(' handle.subscribe,')
lines.push(' handle.getState,')
lines.push(' handle.getState,')
lines.push(' )')
lines.push('}')
lines.push('')
lines.push(`// Global context — fetched once at app init`)
lines.push(`const GlobalCtx = createContext<${p}ContextData | null>(null)`)
lines.push('')
// ── Mutation hook helper ────────────────────────────────────────────
lines.push(`export function GlobalContextProvider({ children }: { children: ReactNode }) {`)
lines.push(` const [data, setData] = useState<${p}ContextData | null>(() => {`)
lines.push(` if (typeof window === 'undefined') return null`)
lines.push(` const ssr = (window as any).__MIZAN_SSR_DATA__`)
lines.push(` return ssr ?? null`)
lines.push(` })`)
lines.push('')
lines.push(` const refetch = useCallback(async () => {`)
lines.push(` const result = await fetch${p}Context({} as any)`)
lines.push(` setData(result)`)
lines.push(` }, [])`)
lines.push('')
lines.push(` useEffect(() => { if (!data) refetch() }, [data, refetch])`)
lines.push(` useEffect(() => registerContext('global', {}, refetch), [refetch])`)
lines.push('')
lines.push(` return <GlobalCtx.Provider value={data}>{children}</GlobalCtx.Provider>`)
lines.push('}')
lines.push('')
lines.push('// Mutation hook with loading/error state')
lines.push('function useMutation<TArgs, TResult>(')
lines.push(' callFn: (args: TArgs) => Promise<TResult>,')
lines.push('): { mutate: (args: TArgs) => Promise<TResult>; isPending: boolean; error: Error | null } {')
lines.push(' const [isPending, setIsPending] = useState(false)')
lines.push(' const [error, setError] = useState<Error | null>(null)')
lines.push('')
lines.push(' const mutate = useCallback(async (args: TArgs) => {')
lines.push(' setIsPending(true)')
lines.push(' setError(null)')
lines.push(' try {')
lines.push(' const result = await callFn(args)')
lines.push(' return result')
lines.push(' } catch (e) {')
lines.push(' setError(e as Error)')
lines.push(' throw e')
lines.push(' } finally {')
lines.push(' setIsPending(false)')
lines.push(' }')
lines.push(' }, [callFn])')
lines.push('')
lines.push(' return { mutate, isPending, error }')
lines.push('}')
lines.push('')
for (const fn of globalContexts) {
const hookPascal = pascalCase(fn.camelName)
lines.push(`export function use${hookPascal}(): ${fn.outputType} {`)
lines.push(` const ctx = useContext(GlobalCtx)`)
lines.push(` if (!ctx) throw new Error('use${hookPascal} requires GlobalContextProvider')`)
lines.push(` return ctx.${fn.name}`)
lines.push('}')
lines.push('')
}
}
// ── Context hooks ───────────────────────────────────────────────────
// ── Named context providers ─────────────────────────────────────────
for (const [ctxName, ctxMeta] of namedContexts) {
for (const [ctxName, ctxMeta] of Object.entries(contextGroups)) {
const p = pascalCase(ctxName)
const ctxFunctions = functions.filter(fn => fn.isContext === ctxName)
const paramEntries = Object.entries(ctxMeta.params || {})
lines.push(`// ${p} context`)
lines.push(`const ${p}Ctx = createContext<${p}ContextData | null>(null)`)
lines.push(`// ── ${p} Context ──`)
lines.push('')
// Provider
lines.push(`export function ${p}Context({ children, ...params }: ${p}ContextParams & { children: ReactNode }) {`)
lines.push(` const [data, setData] = useState<${p}ContextData | null>(() => {`)
lines.push(` if (typeof window === 'undefined') return null`)
lines.push(` const ssr = (window as any).__MIZAN_SSR_DATA__`)
if (ctxFunctions.length > 0) {
lines.push(` if (ssr?.${ctxFunctions[0].name} !== undefined) return ssr`)
// Hook that returns the full kernel state
if (paramEntries.length > 0) {
lines.push(`export function use${p}Context(params: ${p}ContextParams): ContextState<${p}ContextData> {`)
lines.push(` const ssrData = typeof window !== 'undefined' ? (window as any).__MIZAN_SSR_DATA__ : null`)
lines.push(` return useContextState('${ctxName}', params, () => fetch${p}Context(params), ssrData)`)
} else {
lines.push(`export function use${p}Context(): ContextState<${p}ContextData> {`)
lines.push(` const ssrData = typeof window !== 'undefined' ? (window as any).__MIZAN_SSR_DATA__ : null`)
lines.push(` return useContextState('${ctxName}', {}, () => fetch${p}Context({} as any), ssrData)`)
}
lines.push(` return null`)
lines.push(` })`)
lines.push('')
lines.push(` const refetch = useCallback(async () => {`)
lines.push(` const result = await fetch${p}Context(params)`)
lines.push(` setData(result)`)
const deps = paramEntries.map(([pName]) => `params.${pName}`)
lines.push(` }, [${deps.join(', ')}])`)
lines.push('')
lines.push(` useEffect(() => { if (!data) refetch() }, [data, refetch])`)
lines.push(` useEffect(() => registerContext('${ctxName}', params, refetch), [${deps.join(', ')}, refetch])`)
lines.push('')
lines.push(` return <${p}Ctx.Provider value={data}>{children}</${p}Ctx.Provider>`)
lines.push('}')
lines.push('')
// Hooks
// Convenience hooks for individual data fields
for (const fn of ctxFunctions) {
const hookPascal = pascalCase(fn.camelName)
lines.push(`export function use${hookPascal}(): ${fn.outputType} | null {`)
lines.push(` const ctx = useContext(${p}Ctx)`)
lines.push(` return ctx?.${fn.name} ?? null`)
if (paramEntries.length > 0) {
lines.push(`export function use${hookPascal}(params: ${p}ContextParams): ${fn.outputType} | null {`)
lines.push(` const state = use${p}Context(params)`)
} else {
lines.push(`export function use${hookPascal}(): ${fn.outputType} | null {`)
lines.push(` const state = use${p}Context()`)
}
lines.push(` return state.data?.${fn.name} ?? null`)
lines.push('}')
lines.push('')
}
}
// ── Mutation hooks ──────────────────────────────────────────────────
// ── Mutation hooks (with loading/error) ──────────────────────────────
for (const fn of mutations) {
const p = pascalCase(fn.camelName)
if (fn.hasInput) {
lines.push(`export function use${p}() {`)
lines.push(` return useCallback((args: Parameters<typeof call${p}>[0]) => call${p}(args), [])`)
lines.push(` return useMutation<Parameters<typeof call${p}>[0], Awaited<ReturnType<typeof call${p}>>>(call${p})`)
lines.push('}')
} else {
lines.push(`export function use${p}() {`)
lines.push(` return useCallback(() => call${p}(), [])`)
lines.push(` return useMutation<void, Awaited<ReturnType<typeof call${p}>>>(() => call${p}() as any)`)
lines.push('}')
}
lines.push('')
@@ -146,15 +160,21 @@ export function generateReactAdapter(schema) {
const p = pascalCase(fn.camelName)
if (fn.hasInput) {
lines.push(`export function use${p}() {`)
lines.push(` return useCallback((args: Parameters<typeof call${p}>[0]) => call${p}(args), [])`)
lines.push(` return useMutation<Parameters<typeof call${p}>[0], Awaited<ReturnType<typeof call${p}>>>(call${p})`)
lines.push('}')
} else {
lines.push(`export function use${p}() {`)
lines.push(` return useCallback(() => call${p}(), [])`)
lines.push(` return useMutation<void, Awaited<ReturnType<typeof call${p}>>>(() => call${p}() as any)`)
lines.push('}')
}
lines.push('')
}
// ── Re-export runtime types ─────────────────────────────────────────
lines.push("export type { ContextState } from '@mizan/runtime'")
lines.push("export { configure, initSession, MizanError } from '@mizan/runtime'")
lines.push('')
return lines.join('\n')
}

View File

@@ -1,5 +1,7 @@
/**
* Svelte Stage 2 — Generates stores from Stage 1 output.
*
* Subscribes to the kernel for state. Returns readable stores.
*/
function pascalCase(str) {
@@ -15,12 +17,11 @@ export function generateSvelteAdapter(schema) {
const lines = [
'// AUTO-GENERATED by mizan — do not edit',
'',
"import { writable, derived, type Readable } from 'svelte/store'",
"import { registerContext } from '@mizan/runtime'",
"import { readable, type Readable } from 'svelte/store'",
"import { registerContext, type ContextState } from '@mizan/runtime'",
'',
]
// Stage 1 imports
const stage1Imports = []
for (const [ctxName] of Object.entries(contextGroups)) {
const p = pascalCase(ctxName)
@@ -34,14 +35,11 @@ export function generateSvelteAdapter(schema) {
lines.push('')
}
// ── Context stores ──────────────────────────────────────────────────
for (const [ctxName, ctxMeta] of Object.entries(contextGroups)) {
const p = pascalCase(ctxName)
const ctxFunctions = functions.filter(fn => fn.isContext === ctxName)
const paramEntries = Object.entries(ctxMeta.params || {})
lines.push(`// ${p} context`)
const paramsArg = paramEntries.length > 0 ? 'params' : '{} as any'
if (paramEntries.length > 0) {
lines.push(`export function create${p}Context(params: ${p}ContextParams) {`)
@@ -49,49 +47,32 @@ export function generateSvelteAdapter(schema) {
lines.push(`export function create${p}Context() {`)
}
lines.push(` const data = writable<${p}ContextData | null>(null)`)
lines.push(` const loading = writable(true)`)
// Use readable store backed by kernel subscription
lines.push(` const store = readable<ContextState<${p}ContextData>>(`)
lines.push(` { data: null, status: 'idle', error: null },`)
lines.push(` (set) => {`)
lines.push(` const handle = registerContext('${ctxName}', ${paramsArg}, () => fetch${p}Context(${paramsArg}))`)
lines.push(` const unsub = handle.subscribe(() => set(handle.getState()))`)
lines.push(` handle.refetch()`)
lines.push(` return () => { unsub(); handle.unregister() }`)
lines.push(` },`)
lines.push(` )`)
lines.push('')
lines.push(` const refetch = async () => {`)
lines.push(` loading.set(true)`)
if (paramEntries.length > 0) {
lines.push(` const result = await fetch${p}Context(params)`)
} else {
lines.push(` const result = await fetch${p}Context({} as any)`)
}
lines.push(` data.set(result)`)
lines.push(` loading.set(false)`)
lines.push(` }`)
lines.push('')
lines.push(` refetch()`)
if (paramEntries.length > 0) {
lines.push(` const unregister = registerContext('${ctxName}', params, refetch)`)
} else {
lines.push(` const unregister = registerContext('${ctxName}', {}, refetch)`)
}
lines.push('')
// Derived stores for each function
lines.push(` return {`)
lines.push(` data,`)
lines.push(` loading,`)
for (const fn of ctxFunctions) {
const camel = fn.camelName
lines.push(` ${camel}: derived(data, $d => $d?.${fn.name} ?? null) as Readable<${fn.outputType} | null>,`)
}
lines.push(` destroy: unregister,`)
lines.push(` }`)
lines.push(` return store`)
lines.push('}')
lines.push('')
}
// ── Mutation + function exports ─────────────────────────────────────
// Re-export mutations as-is from Stage 1
for (const fn of [...mutations, ...plainFns]) {
const p = pascalCase(fn.camelName)
lines.push(`export { call${p} } from '../${fn.affects ? 'mutations' : 'functions'}/${fn.camelName}'`)
lines.push(`export { call${p} } from '../index'`)
}
lines.push('')
lines.push("export type { ContextState } from '@mizan/runtime'")
lines.push("export { configure, initSession, MizanError } from '@mizan/runtime'")
lines.push('')
return lines.join('\n')
}

View File

@@ -1,5 +1,7 @@
/**
* Vue Stage 2 — Generates composables from Stage 1 output.
*
* Subscribes to the kernel for state. Vue reactivity wraps kernel notifications.
*/
function pascalCase(str) {
@@ -15,12 +17,11 @@ export function generateVueAdapter(schema) {
const lines = [
'// AUTO-GENERATED by mizan — do not edit',
'',
"import { ref, computed, watch, onMounted, onUnmounted, provide, inject, type Ref, type ComputedRef, type InjectionKey } from 'vue'",
"import { registerContext } from '@mizan/runtime'",
"import { ref, computed, onMounted, onUnmounted, onServerPrefetch, type ComputedRef } from 'vue'",
"import { registerContext, type ContextState } from '@mizan/runtime'",
'',
]
// Stage 1 imports
const stage1Imports = []
for (const [ctxName] of Object.entries(contextGroups)) {
const p = pascalCase(ctxName)
@@ -34,72 +35,70 @@ export function generateVueAdapter(schema) {
lines.push('')
}
// ── Context composables ─────────────────────────────────────────────
for (const [ctxName, ctxMeta] of Object.entries(contextGroups)) {
const p = pascalCase(ctxName)
const ctxFunctions = functions.filter(fn => fn.isContext === ctxName)
const paramEntries = Object.entries(ctxMeta.params || {})
const paramsArg = paramEntries.length > 0 ? 'params' : '{} as any'
lines.push(`// ${p} context`)
lines.push(`const ${p}Key: InjectionKey<{ data: Ref<${p}ContextData | null>, loading: Ref<boolean> }> = Symbol('${ctxName}')`)
lines.push('')
if (paramEntries.length > 0) {
lines.push(`export function use${p}Context(params: ${p}ContextParams) {`)
} else {
lines.push(`export function use${p}Context() {`)
}
// Provider composable
if (paramEntries.length > 0) {
lines.push(`export function provide${p}Context(params: { ${paramEntries.map(([k, v]) => `${k}: ${v.type === 'integer' || v.type === 'number' ? 'number' : 'string'}`).join(', ')} }) {`)
} else {
lines.push(`export function provide${p}Context() {`)
}
lines.push(` const data = ref<${p}ContextData | null>(null)`)
lines.push(` const loading = ref(true)`)
lines.push(` const state = ref<ContextState<${p}ContextData>>({ data: null, status: 'idle', error: null })`)
lines.push(` let handle: ReturnType<typeof registerContext> | null = null`)
lines.push('')
lines.push(` const refetch = async () => {`)
lines.push(` loading.value = true`)
lines.push(` try {`)
if (paramEntries.length > 0) {
lines.push(` data.value = await fetch${p}Context(params as any)`)
} else {
lines.push(` data.value = await fetch${p}Context({} as any)`)
}
lines.push(` } catch (e) { console.error('[mizan] ${ctxName} fetch failed:', e) }`)
lines.push(` loading.value = false`)
lines.push(` }`)
lines.push('')
lines.push(` let unregister: (() => void) | null = null`)
lines.push(` onMounted(() => {`)
lines.push(` refetch()`)
if (paramEntries.length > 0) {
lines.push(` unregister = registerContext('${ctxName}', params, refetch)`)
} else {
lines.push(` unregister = registerContext('${ctxName}', {}, refetch)`)
}
lines.push(` handle = registerContext('${ctxName}', ${paramsArg}, () => fetch${p}Context(${paramsArg}))`)
lines.push(` handle.subscribe(() => { state.value = handle!.getState() })`)
lines.push(` handle.refetch()`)
lines.push(` })`)
lines.push(` onUnmounted(() => { unregister?.() })`)
lines.push('')
lines.push(` provide(${p}Key, { data, loading })`)
lines.push(` onServerPrefetch(async () => {`)
lines.push(` handle = registerContext('${ctxName}', ${paramsArg}, () => fetch${p}Context(${paramsArg}))`)
lines.push(` await handle.refetch()`)
lines.push(` state.value = handle.getState()`)
lines.push(` })`)
lines.push('')
lines.push(` onUnmounted(() => { handle?.unregister() })`)
lines.push('')
lines.push(` return {`)
lines.push(` state,`)
for (const fn of ctxFunctions) {
lines.push(` ${fn.camelName}: computed(() => state.value.data?.${fn.name} ?? null) as ComputedRef<${fn.outputType} | null>,`)
}
lines.push(` loading: computed(() => state.value.status === 'loading'),`)
lines.push(` error: computed(() => state.value.error),`)
lines.push(` }`)
lines.push('}')
lines.push('')
// Consumer composables
for (const fn of ctxFunctions) {
const hookPascal = pascalCase(fn.camelName)
lines.push(`export function use${hookPascal}(): ComputedRef<${fn.outputType} | null> {`)
lines.push(` const ctx = inject(${p}Key)`)
lines.push(` if (!ctx) throw new Error('use${hookPascal} requires provide${p}Context in a parent')`)
lines.push(` return computed(() => ctx.data.value?.${fn.name} ?? null)`)
lines.push('}')
lines.push('')
}
}
// ── Mutation composables ────────────────────────────────────────────
for (const fn of [...mutations, ...plainFns]) {
const p = pascalCase(fn.camelName)
lines.push(`export const use${p} = call${p}`)
lines.push(`export function use${p}() {`)
lines.push(` const isPending = ref(false)`)
lines.push(` const error = ref<Error | null>(null)`)
if (fn.hasInput) {
lines.push(` async function mutate(args: Parameters<typeof call${p}>[0]) {`)
} else {
lines.push(` async function mutate() {`)
}
lines.push(` isPending.value = true; error.value = null`)
lines.push(` try { return await call${p}(${fn.hasInput ? 'args' : ''}) }`)
lines.push(` catch (e) { error.value = e as Error; throw e }`)
lines.push(` finally { isPending.value = false }`)
lines.push(` }`)
lines.push(` return { mutate, isPending, error }`)
lines.push('}')
lines.push('')
}
lines.push("export type { ContextState } from '@mizan/runtime'")
lines.push("export { configure, initSession, MizanError } from '@mizan/runtime'")
lines.push('')
return lines.join('\n')
}