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

@@ -2,117 +2,142 @@
// 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'
import { fetchGlobalContext, type GlobalContextData, type GlobalContextParams, fetchLocalContext, type LocalContextData, type LocalContextParams, callEcho, callAdd, callWhoami, callHttpOnlyEcho, callStaffOnly, callSuperuserOnly, callVerifiedOnly, callMultiply, callNotImplementedFn, callBuggyFn, callPermissionCheckFn, callWsWhoami, callJwtObtain, callJwtRefresh } from '../index'
// Global context — fetched once at app init
const GlobalCtx = createContext<GlobalContextData | null>(null)
// Subscribe to kernel state via useSyncExternalStore
function useContextState<T>(
name: string,
params: Record<string, any>,
fetchFn: () => Promise<T>,
initialData?: T,
): ContextState<T> {
const ref = useRef<ReturnType<typeof registerContext> | null>(null)
export function GlobalContextProvider({ children }: { children: ReactNode }) {
const [data, setData] = useState<GlobalContextData | null>(() => {
if (typeof window === 'undefined') return null
const ssr = (window as any).__MIZAN_SSR_DATA__
return ssr ?? null
})
if (!ref.current) {
ref.current = registerContext(name, params, fetchFn, initialData)
}
const refetch = useCallback(async () => {
const result = await fetchGlobalContext({} as any)
setData(result)
}, [])
const handle = ref.current
useEffect(() => { if (!data) refetch() }, [data, refetch])
useEffect(() => registerContext('global', {}, refetch), [refetch])
// Fetch on mount if no data
useEffect(() => {
if (handle.getState().status === 'idle') handle.refetch()
return () => handle.unregister()
}, [handle])
return <GlobalCtx.Provider value={data}>{children}</GlobalCtx.Provider>
return useSyncExternalStore(
handle.subscribe,
handle.getState,
handle.getState,
)
}
export function useCurrentUser(): currentUserOutput {
const ctx = useContext(GlobalCtx)
if (!ctx) throw new Error('useCurrentUser requires GlobalContextProvider')
return ctx.current_user
// Mutation hook with loading/error state
function useMutation<TArgs, TResult>(
callFn: (args: TArgs) => Promise<TResult>,
): { mutate: (args: TArgs) => Promise<TResult>; isPending: boolean; error: Error | null } {
const [isPending, setIsPending] = useState(false)
const [error, setError] = useState<Error | null>(null)
const mutate = useCallback(async (args: TArgs) => {
setIsPending(true)
setError(null)
try {
const result = await callFn(args)
return result
} catch (e) {
setError(e as Error)
throw e
} finally {
setIsPending(false)
}
}, [callFn])
return { mutate, isPending, error }
}
// Local context
const LocalCtx = createContext<LocalContextData | null>(null)
// ── Global Context ──
export function LocalContext({ children, ...params }: LocalContextParams & { children: ReactNode }) {
const [data, setData] = useState<LocalContextData | null>(() => {
if (typeof window === 'undefined') return null
const ssr = (window as any).__MIZAN_SSR_DATA__
if (ssr?.greet !== undefined) return ssr
return null
})
const refetch = useCallback(async () => {
const result = await fetchLocalContext(params)
setData(result)
}, [params.name])
useEffect(() => { refetch() }, [refetch])
useEffect(() => registerContext('local', params, refetch), [params.name, refetch])
return <LocalCtx.Provider value={data}>{children}</LocalCtx.Provider>
export function useGlobalContext(): ContextState<GlobalContextData> {
const ssrData = typeof window !== 'undefined' ? (window as any).__MIZAN_SSR_DATA__ : null
return useContextState('global', {}, () => fetchGlobalContext({} as any), ssrData)
}
export function useGreet(): greetOutput | null {
const ctx = useContext(LocalCtx)
return ctx?.greet ?? null
export function useCurrentUser(): currentUserOutput | null {
const state = useGlobalContext()
return state.data?.current_user ?? null
}
// ── Local Context ──
export function useLocalContext(params: LocalContextParams): ContextState<LocalContextData> {
const ssrData = typeof window !== 'undefined' ? (window as any).__MIZAN_SSR_DATA__ : null
return useContextState('local', params, () => fetchLocalContext(params), ssrData)
}
export function useGreet(params: LocalContextParams): greetOutput | null {
const state = useLocalContext(params)
return state.data?.greet ?? null
}
export function useEcho() {
return useCallback((args: Parameters<typeof callEcho>[0]) => callEcho(args), [])
return useMutation<Parameters<typeof callEcho>[0], Awaited<ReturnType<typeof callEcho>>>(callEcho)
}
export function useAdd() {
return useCallback((args: Parameters<typeof callAdd>[0]) => callAdd(args), [])
return useMutation<Parameters<typeof callAdd>[0], Awaited<ReturnType<typeof callAdd>>>(callAdd)
}
export function useWhoami() {
return useCallback(() => callWhoami(), [])
return useMutation<void, Awaited<ReturnType<typeof callWhoami>>>(() => callWhoami() as any)
}
export function useHttpOnlyEcho() {
return useCallback((args: Parameters<typeof callHttpOnlyEcho>[0]) => callHttpOnlyEcho(args), [])
return useMutation<Parameters<typeof callHttpOnlyEcho>[0], Awaited<ReturnType<typeof callHttpOnlyEcho>>>(callHttpOnlyEcho)
}
export function useStaffOnly() {
return useCallback(() => callStaffOnly(), [])
return useMutation<void, Awaited<ReturnType<typeof callStaffOnly>>>(() => callStaffOnly() as any)
}
export function useSuperuserOnly() {
return useCallback(() => callSuperuserOnly(), [])
return useMutation<void, Awaited<ReturnType<typeof callSuperuserOnly>>>(() => callSuperuserOnly() as any)
}
export function useVerifiedOnly() {
return useCallback(() => callVerifiedOnly(), [])
return useMutation<void, Awaited<ReturnType<typeof callVerifiedOnly>>>(() => callVerifiedOnly() as any)
}
export function useMultiply() {
return useCallback((args: Parameters<typeof callMultiply>[0]) => callMultiply(args), [])
return useMutation<Parameters<typeof callMultiply>[0], Awaited<ReturnType<typeof callMultiply>>>(callMultiply)
}
export function useNotImplementedFn() {
return useCallback(() => callNotImplementedFn(), [])
return useMutation<void, Awaited<ReturnType<typeof callNotImplementedFn>>>(() => callNotImplementedFn() as any)
}
export function useBuggyFn() {
return useCallback(() => callBuggyFn(), [])
return useMutation<void, Awaited<ReturnType<typeof callBuggyFn>>>(() => callBuggyFn() as any)
}
export function usePermissionCheckFn() {
return useCallback((args: Parameters<typeof callPermissionCheckFn>[0]) => callPermissionCheckFn(args), [])
return useMutation<Parameters<typeof callPermissionCheckFn>[0], Awaited<ReturnType<typeof callPermissionCheckFn>>>(callPermissionCheckFn)
}
export function useWsWhoami() {
return useCallback(() => callWsWhoami(), [])
return useMutation<void, Awaited<ReturnType<typeof callWsWhoami>>>(() => callWsWhoami() as any)
}
export function useJwtObtain() {
return useCallback(() => callJwtObtain(), [])
return useMutation<void, Awaited<ReturnType<typeof callJwtObtain>>>(() => callJwtObtain() as any)
}
export function useJwtRefresh() {
return useCallback((args: Parameters<typeof callJwtRefresh>[0]) => callJwtRefresh(args), [])
return useMutation<Parameters<typeof callJwtRefresh>[0], Awaited<ReturnType<typeof callJwtRefresh>>>(callJwtRefresh)
}
export type { ContextState } from '@mizan/runtime'
export { configure, initSession, MizanError } from '@mizan/runtime'

View File

@@ -1,67 +1,52 @@
// 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'
import { fetchGlobalContext, type GlobalContextData, type GlobalContextParams, fetchLocalContext, type LocalContextData, type LocalContextParams, callEcho, callAdd, callWhoami, callHttpOnlyEcho, callStaffOnly, callSuperuserOnly, callVerifiedOnly, callMultiply, callNotImplementedFn, callBuggyFn, callPermissionCheckFn, callWsWhoami, callJwtObtain, callJwtRefresh } from '../index'
// Global context
export function createGlobalContext() {
const data = writable<GlobalContextData | null>(null)
const loading = writable(true)
const store = readable<ContextState<GlobalContextData>>(
{ data: null, status: 'idle', error: null },
(set) => {
const handle = registerContext('global', {} as any, () => fetchGlobalContext({} as any))
const unsub = handle.subscribe(() => set(handle.getState()))
handle.refetch()
return () => { unsub(); handle.unregister() }
},
)
const refetch = async () => {
loading.set(true)
const result = await fetchGlobalContext({} as any)
data.set(result)
loading.set(false)
}
refetch()
const unregister = registerContext('global', {}, refetch)
return {
data,
loading,
currentUser: derived(data, $d => $d?.current_user ?? null) as Readable<currentUserOutput | null>,
destroy: unregister,
}
return store
}
// Local context
export function createLocalContext(params: LocalContextParams) {
const data = writable<LocalContextData | null>(null)
const loading = writable(true)
const store = readable<ContextState<LocalContextData>>(
{ data: null, status: 'idle', error: null },
(set) => {
const handle = registerContext('local', params, () => fetchLocalContext(params))
const unsub = handle.subscribe(() => set(handle.getState()))
handle.refetch()
return () => { unsub(); handle.unregister() }
},
)
const refetch = async () => {
loading.set(true)
const result = await fetchLocalContext(params)
data.set(result)
loading.set(false)
}
refetch()
const unregister = registerContext('local', params, refetch)
return {
data,
loading,
greet: derived(data, $d => $d?.greet ?? null) as Readable<greetOutput | null>,
destroy: unregister,
}
return store
}
export { callEcho } from '../functions/echo'
export { callAdd } from '../functions/add'
export { callWhoami } from '../functions/whoami'
export { callHttpOnlyEcho } from '../functions/httpOnlyEcho'
export { callStaffOnly } from '../functions/staffOnly'
export { callSuperuserOnly } from '../functions/superuserOnly'
export { callVerifiedOnly } from '../functions/verifiedOnly'
export { callMultiply } from '../functions/multiply'
export { callNotImplementedFn } from '../functions/notImplementedFn'
export { callBuggyFn } from '../functions/buggyFn'
export { callPermissionCheckFn } from '../functions/permissionCheckFn'
export { callWsWhoami } from '../functions/wsWhoami'
export { callJwtObtain } from '../functions/jwtObtain'
export { callJwtRefresh } from '../functions/jwtRefresh'
export { callEcho } from '../index'
export { callAdd } from '../index'
export { callWhoami } from '../index'
export { callHttpOnlyEcho } from '../index'
export { callStaffOnly } from '../index'
export { callSuperuserOnly } from '../index'
export { callVerifiedOnly } from '../index'
export { callMultiply } from '../index'
export { callNotImplementedFn } from '../index'
export { callBuggyFn } from '../index'
export { callPermissionCheckFn } from '../index'
export { callWsWhoami } from '../index'
export { callJwtObtain } from '../index'
export { callJwtRefresh } from '../index'
export type { ContextState } from '@mizan/runtime'
export { configure, initSession, MizanError } from '@mizan/runtime'

View File

@@ -1,96 +1,229 @@
// 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'
import { fetchGlobalContext, type GlobalContextData, type GlobalContextParams, fetchLocalContext, type LocalContextData, type LocalContextParams, callEcho, callAdd, callWhoami, callHttpOnlyEcho, callStaffOnly, callSuperuserOnly, callVerifiedOnly, callMultiply, callNotImplementedFn, callBuggyFn, callPermissionCheckFn, callWsWhoami, callJwtObtain, callJwtRefresh } from '../index'
// Global context
const GlobalKey: InjectionKey<{ data: Ref<GlobalContextData | null>, loading: Ref<boolean> }> = Symbol('global')
export function useGlobalContext() {
const state = ref<ContextState<GlobalContextData>>({ data: null, status: 'idle', error: null })
let handle: ReturnType<typeof registerContext> | null = null
export function provideGlobalContext() {
const data = ref<GlobalContextData | null>(null)
const loading = ref(true)
const refetch = async () => {
loading.value = true
try {
data.value = await fetchGlobalContext({} as any)
} catch (e) { console.error('[mizan] global fetch failed:', e) }
loading.value = false
}
let unregister: (() => void) | null = null
onMounted(() => {
refetch()
unregister = registerContext('global', {}, refetch)
handle = registerContext('global', {} as any, () => fetchGlobalContext({} as any))
handle.subscribe(() => { state.value = handle!.getState() })
handle.refetch()
})
onUnmounted(() => { unregister?.() })
provide(GlobalKey, { data, loading })
}
onServerPrefetch(async () => {
handle = registerContext('global', {} as any, () => fetchGlobalContext({} as any))
await handle.refetch()
state.value = handle.getState()
})
export function useCurrentUser(): ComputedRef<currentUserOutput | null> {
const ctx = inject(GlobalKey)
if (!ctx) throw new Error('useCurrentUser requires provideGlobalContext in a parent')
return computed(() => ctx.data.value?.current_user ?? null)
}
onUnmounted(() => { handle?.unregister() })
// Local context
const LocalKey: InjectionKey<{ data: Ref<LocalContextData | null>, loading: Ref<boolean> }> = Symbol('local')
export function provideLocalContext(params: { name: string }) {
const data = ref<LocalContextData | null>(null)
const loading = ref(true)
const refetch = async () => {
loading.value = true
try {
data.value = await fetchLocalContext(params as any)
} catch (e) { console.error('[mizan] local fetch failed:', e) }
loading.value = false
return {
state,
currentUser: computed(() => state.value.data?.current_user ?? null) as ComputedRef<currentUserOutput | null>,
loading: computed(() => state.value.status === 'loading'),
error: computed(() => state.value.error),
}
}
export function useLocalContext(params: LocalContextParams) {
const state = ref<ContextState<LocalContextData>>({ data: null, status: 'idle', error: null })
let handle: ReturnType<typeof registerContext> | null = null
let unregister: (() => void) | null = null
onMounted(() => {
refetch()
unregister = registerContext('local', params, refetch)
handle = registerContext('local', params, () => fetchLocalContext(params))
handle.subscribe(() => { state.value = handle!.getState() })
handle.refetch()
})
onUnmounted(() => { unregister?.() })
provide(LocalKey, { data, loading })
onServerPrefetch(async () => {
handle = registerContext('local', params, () => fetchLocalContext(params))
await handle.refetch()
state.value = handle.getState()
})
onUnmounted(() => { handle?.unregister() })
return {
state,
greet: computed(() => state.value.data?.greet ?? null) as ComputedRef<greetOutput | null>,
loading: computed(() => state.value.status === 'loading'),
error: computed(() => state.value.error),
}
}
export function useGreet(): ComputedRef<greetOutput | null> {
const ctx = inject(LocalKey)
if (!ctx) throw new Error('useGreet requires provideLocalContext in a parent')
return computed(() => ctx.data.value?.greet ?? null)
export function useEcho() {
const isPending = ref(false)
const error = ref<Error | null>(null)
async function mutate(args: Parameters<typeof callEcho>[0]) {
isPending.value = true; error.value = null
try { return await callEcho(args) }
catch (e) { error.value = e as Error; throw e }
finally { isPending.value = false }
}
return { mutate, isPending, error }
}
export const useEcho = callEcho
export function useAdd() {
const isPending = ref(false)
const error = ref<Error | null>(null)
async function mutate(args: Parameters<typeof callAdd>[0]) {
isPending.value = true; error.value = null
try { return await callAdd(args) }
catch (e) { error.value = e as Error; throw e }
finally { isPending.value = false }
}
return { mutate, isPending, error }
}
export const useAdd = callAdd
export function useWhoami() {
const isPending = ref(false)
const error = ref<Error | null>(null)
async function mutate() {
isPending.value = true; error.value = null
try { return await callWhoami() }
catch (e) { error.value = e as Error; throw e }
finally { isPending.value = false }
}
return { mutate, isPending, error }
}
export const useWhoami = callWhoami
export function useHttpOnlyEcho() {
const isPending = ref(false)
const error = ref<Error | null>(null)
async function mutate(args: Parameters<typeof callHttpOnlyEcho>[0]) {
isPending.value = true; error.value = null
try { return await callHttpOnlyEcho(args) }
catch (e) { error.value = e as Error; throw e }
finally { isPending.value = false }
}
return { mutate, isPending, error }
}
export const useHttpOnlyEcho = callHttpOnlyEcho
export function useStaffOnly() {
const isPending = ref(false)
const error = ref<Error | null>(null)
async function mutate() {
isPending.value = true; error.value = null
try { return await callStaffOnly() }
catch (e) { error.value = e as Error; throw e }
finally { isPending.value = false }
}
return { mutate, isPending, error }
}
export const useStaffOnly = callStaffOnly
export function useSuperuserOnly() {
const isPending = ref(false)
const error = ref<Error | null>(null)
async function mutate() {
isPending.value = true; error.value = null
try { return await callSuperuserOnly() }
catch (e) { error.value = e as Error; throw e }
finally { isPending.value = false }
}
return { mutate, isPending, error }
}
export const useSuperuserOnly = callSuperuserOnly
export function useVerifiedOnly() {
const isPending = ref(false)
const error = ref<Error | null>(null)
async function mutate() {
isPending.value = true; error.value = null
try { return await callVerifiedOnly() }
catch (e) { error.value = e as Error; throw e }
finally { isPending.value = false }
}
return { mutate, isPending, error }
}
export const useVerifiedOnly = callVerifiedOnly
export function useMultiply() {
const isPending = ref(false)
const error = ref<Error | null>(null)
async function mutate(args: Parameters<typeof callMultiply>[0]) {
isPending.value = true; error.value = null
try { return await callMultiply(args) }
catch (e) { error.value = e as Error; throw e }
finally { isPending.value = false }
}
return { mutate, isPending, error }
}
export const useMultiply = callMultiply
export function useNotImplementedFn() {
const isPending = ref(false)
const error = ref<Error | null>(null)
async function mutate() {
isPending.value = true; error.value = null
try { return await callNotImplementedFn() }
catch (e) { error.value = e as Error; throw e }
finally { isPending.value = false }
}
return { mutate, isPending, error }
}
export const useNotImplementedFn = callNotImplementedFn
export function useBuggyFn() {
const isPending = ref(false)
const error = ref<Error | null>(null)
async function mutate() {
isPending.value = true; error.value = null
try { return await callBuggyFn() }
catch (e) { error.value = e as Error; throw e }
finally { isPending.value = false }
}
return { mutate, isPending, error }
}
export const useBuggyFn = callBuggyFn
export function usePermissionCheckFn() {
const isPending = ref(false)
const error = ref<Error | null>(null)
async function mutate(args: Parameters<typeof callPermissionCheckFn>[0]) {
isPending.value = true; error.value = null
try { return await callPermissionCheckFn(args) }
catch (e) { error.value = e as Error; throw e }
finally { isPending.value = false }
}
return { mutate, isPending, error }
}
export const usePermissionCheckFn = callPermissionCheckFn
export function useWsWhoami() {
const isPending = ref(false)
const error = ref<Error | null>(null)
async function mutate() {
isPending.value = true; error.value = null
try { return await callWsWhoami() }
catch (e) { error.value = e as Error; throw e }
finally { isPending.value = false }
}
return { mutate, isPending, error }
}
export const useWsWhoami = callWsWhoami
export function useJwtObtain() {
const isPending = ref(false)
const error = ref<Error | null>(null)
async function mutate() {
isPending.value = true; error.value = null
try { return await callJwtObtain() }
catch (e) { error.value = e as Error; throw e }
finally { isPending.value = false }
}
return { mutate, isPending, error }
}
export const useJwtObtain = callJwtObtain
export function useJwtRefresh() {
const isPending = ref(false)
const error = ref<Error | null>(null)
async function mutate(args: Parameters<typeof callJwtRefresh>[0]) {
isPending.value = true; error.value = null
try { return await callJwtRefresh(args) }
catch (e) { error.value = e as Error; throw e }
finally { isPending.value = false }
}
return { mutate, isPending, error }
}
export const useJwtRefresh = callJwtRefresh
export type { ContextState } from '@mizan/runtime'
export { configure, initSession, MizanError } from '@mizan/runtime'