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:
@@ -2,117 +2,142 @@
|
|||||||
|
|
||||||
// AUTO-GENERATED by mizan — do not edit
|
// AUTO-GENERATED by mizan — do not edit
|
||||||
|
|
||||||
import { createContext, useContext, useState, useEffect, useCallback, type ReactNode } from 'react'
|
import { createContext, useContext, useState, useEffect, useCallback, useRef, useSyncExternalStore, type ReactNode } from 'react'
|
||||||
import { registerContext, mizanCall, mizanFetch } from '@mizan/runtime'
|
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'
|
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
|
// Subscribe to kernel state via useSyncExternalStore
|
||||||
const GlobalCtx = createContext<GlobalContextData | null>(null)
|
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 }) {
|
if (!ref.current) {
|
||||||
const [data, setData] = useState<GlobalContextData | null>(() => {
|
ref.current = registerContext(name, params, fetchFn, initialData)
|
||||||
if (typeof window === 'undefined') return null
|
|
||||||
const ssr = (window as any).__MIZAN_SSR_DATA__
|
|
||||||
return ssr ?? null
|
|
||||||
})
|
|
||||||
|
|
||||||
const refetch = useCallback(async () => {
|
|
||||||
const result = await fetchGlobalContext({} as any)
|
|
||||||
setData(result)
|
|
||||||
}, [])
|
|
||||||
|
|
||||||
useEffect(() => { if (!data) refetch() }, [data, refetch])
|
|
||||||
useEffect(() => registerContext('global', {}, refetch), [refetch])
|
|
||||||
|
|
||||||
return <GlobalCtx.Provider value={data}>{children}</GlobalCtx.Provider>
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useCurrentUser(): currentUserOutput {
|
const handle = ref.current
|
||||||
const ctx = useContext(GlobalCtx)
|
|
||||||
if (!ctx) throw new Error('useCurrentUser requires GlobalContextProvider')
|
// Fetch on mount if no data
|
||||||
return ctx.current_user
|
useEffect(() => {
|
||||||
|
if (handle.getState().status === 'idle') handle.refetch()
|
||||||
|
return () => handle.unregister()
|
||||||
|
}, [handle])
|
||||||
|
|
||||||
|
return useSyncExternalStore(
|
||||||
|
handle.subscribe,
|
||||||
|
handle.getState,
|
||||||
|
handle.getState,
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Local context
|
// Mutation hook with loading/error state
|
||||||
const LocalCtx = createContext<LocalContextData | null>(null)
|
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)
|
||||||
|
|
||||||
export function LocalContext({ children, ...params }: LocalContextParams & { children: ReactNode }) {
|
const mutate = useCallback(async (args: TArgs) => {
|
||||||
const [data, setData] = useState<LocalContextData | null>(() => {
|
setIsPending(true)
|
||||||
if (typeof window === 'undefined') return null
|
setError(null)
|
||||||
const ssr = (window as any).__MIZAN_SSR_DATA__
|
try {
|
||||||
if (ssr?.greet !== undefined) return ssr
|
const result = await callFn(args)
|
||||||
return null
|
return result
|
||||||
})
|
} catch (e) {
|
||||||
|
setError(e as Error)
|
||||||
|
throw e
|
||||||
|
} finally {
|
||||||
|
setIsPending(false)
|
||||||
|
}
|
||||||
|
}, [callFn])
|
||||||
|
|
||||||
const refetch = useCallback(async () => {
|
return { mutate, isPending, error }
|
||||||
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 useGreet(): greetOutput | null {
|
// ── Global Context ──
|
||||||
const ctx = useContext(LocalCtx)
|
|
||||||
return ctx?.greet ?? null
|
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 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() {
|
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() {
|
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() {
|
export function useWhoami() {
|
||||||
return useCallback(() => callWhoami(), [])
|
return useMutation<void, Awaited<ReturnType<typeof callWhoami>>>(() => callWhoami() as any)
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useHttpOnlyEcho() {
|
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() {
|
export function useStaffOnly() {
|
||||||
return useCallback(() => callStaffOnly(), [])
|
return useMutation<void, Awaited<ReturnType<typeof callStaffOnly>>>(() => callStaffOnly() as any)
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useSuperuserOnly() {
|
export function useSuperuserOnly() {
|
||||||
return useCallback(() => callSuperuserOnly(), [])
|
return useMutation<void, Awaited<ReturnType<typeof callSuperuserOnly>>>(() => callSuperuserOnly() as any)
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useVerifiedOnly() {
|
export function useVerifiedOnly() {
|
||||||
return useCallback(() => callVerifiedOnly(), [])
|
return useMutation<void, Awaited<ReturnType<typeof callVerifiedOnly>>>(() => callVerifiedOnly() as any)
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useMultiply() {
|
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() {
|
export function useNotImplementedFn() {
|
||||||
return useCallback(() => callNotImplementedFn(), [])
|
return useMutation<void, Awaited<ReturnType<typeof callNotImplementedFn>>>(() => callNotImplementedFn() as any)
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useBuggyFn() {
|
export function useBuggyFn() {
|
||||||
return useCallback(() => callBuggyFn(), [])
|
return useMutation<void, Awaited<ReturnType<typeof callBuggyFn>>>(() => callBuggyFn() as any)
|
||||||
}
|
}
|
||||||
|
|
||||||
export function usePermissionCheckFn() {
|
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() {
|
export function useWsWhoami() {
|
||||||
return useCallback(() => callWsWhoami(), [])
|
return useMutation<void, Awaited<ReturnType<typeof callWsWhoami>>>(() => callWsWhoami() as any)
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useJwtObtain() {
|
export function useJwtObtain() {
|
||||||
return useCallback(() => callJwtObtain(), [])
|
return useMutation<void, Awaited<ReturnType<typeof callJwtObtain>>>(() => callJwtObtain() as any)
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useJwtRefresh() {
|
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'
|
||||||
|
|||||||
@@ -1,67 +1,52 @@
|
|||||||
// AUTO-GENERATED by mizan — do not edit
|
// AUTO-GENERATED by mizan — do not edit
|
||||||
|
|
||||||
import { writable, derived, type Readable } from 'svelte/store'
|
import { readable, type Readable } from 'svelte/store'
|
||||||
import { registerContext } from '@mizan/runtime'
|
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'
|
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() {
|
export function createGlobalContext() {
|
||||||
const data = writable<GlobalContextData | null>(null)
|
const store = readable<ContextState<GlobalContextData>>(
|
||||||
const loading = writable(true)
|
{ 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 () => {
|
return store
|
||||||
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,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Local context
|
|
||||||
export function createLocalContext(params: LocalContextParams) {
|
export function createLocalContext(params: LocalContextParams) {
|
||||||
const data = writable<LocalContextData | null>(null)
|
const store = readable<ContextState<LocalContextData>>(
|
||||||
const loading = writable(true)
|
{ 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 () => {
|
return store
|
||||||
loading.set(true)
|
|
||||||
const result = await fetchLocalContext(params)
|
|
||||||
data.set(result)
|
|
||||||
loading.set(false)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
refetch()
|
export { callEcho } from '../index'
|
||||||
const unregister = registerContext('local', params, refetch)
|
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'
|
||||||
|
|
||||||
return {
|
export type { ContextState } from '@mizan/runtime'
|
||||||
data,
|
export { configure, initSession, MizanError } from '@mizan/runtime'
|
||||||
loading,
|
|
||||||
greet: derived(data, $d => $d?.greet ?? null) as Readable<greetOutput | null>,
|
|
||||||
destroy: unregister,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
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'
|
|
||||||
|
|||||||
@@ -1,96 +1,229 @@
|
|||||||
// AUTO-GENERATED by mizan — do not edit
|
// AUTO-GENERATED by mizan — do not edit
|
||||||
|
|
||||||
import { ref, computed, watch, onMounted, onUnmounted, provide, inject, type Ref, type ComputedRef, type InjectionKey } from 'vue'
|
import { ref, computed, onMounted, onUnmounted, onServerPrefetch, type ComputedRef } from 'vue'
|
||||||
import { registerContext } from '@mizan/runtime'
|
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'
|
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 useGlobalContext() {
|
||||||
const GlobalKey: InjectionKey<{ data: Ref<GlobalContextData | null>, loading: Ref<boolean> }> = Symbol('global')
|
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(() => {
|
onMounted(() => {
|
||||||
refetch()
|
handle = registerContext('global', {} as any, () => fetchGlobalContext({} as any))
|
||||||
unregister = registerContext('global', {}, refetch)
|
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()
|
||||||
|
})
|
||||||
|
|
||||||
|
onUnmounted(() => { handle?.unregister() })
|
||||||
|
|
||||||
|
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 useCurrentUser(): ComputedRef<currentUserOutput | null> {
|
export function useLocalContext(params: LocalContextParams) {
|
||||||
const ctx = inject(GlobalKey)
|
const state = ref<ContextState<LocalContextData>>({ data: null, status: 'idle', error: null })
|
||||||
if (!ctx) throw new Error('useCurrentUser requires provideGlobalContext in a parent')
|
let handle: ReturnType<typeof registerContext> | null = null
|
||||||
return computed(() => ctx.data.value?.current_user ?? null)
|
|
||||||
}
|
|
||||||
|
|
||||||
// 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
|
|
||||||
}
|
|
||||||
|
|
||||||
let unregister: (() => void) | null = null
|
|
||||||
onMounted(() => {
|
onMounted(() => {
|
||||||
refetch()
|
handle = registerContext('local', params, () => fetchLocalContext(params))
|
||||||
unregister = registerContext('local', params, refetch)
|
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> {
|
export function useEcho() {
|
||||||
const ctx = inject(LocalKey)
|
const isPending = ref(false)
|
||||||
if (!ctx) throw new Error('useGreet requires provideLocalContext in a parent')
|
const error = ref<Error | null>(null)
|
||||||
return computed(() => ctx.data.value?.greet ?? 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'
|
||||||
|
|||||||
@@ -1,5 +1,8 @@
|
|||||||
/**
|
/**
|
||||||
* React Stage 2 — Generates hooks + context providers from Stage 1 output.
|
* 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) {
|
function pascalCase(str) {
|
||||||
@@ -19,8 +22,8 @@ export function generateReactAdapter(schema) {
|
|||||||
'',
|
'',
|
||||||
'// AUTO-GENERATED by mizan — do not edit',
|
'// AUTO-GENERATED by mizan — do not edit',
|
||||||
'',
|
'',
|
||||||
"import { createContext, useContext, useState, useEffect, useCallback, type ReactNode } from 'react'",
|
"import { createContext, useContext, useState, useEffect, useCallback, useRef, useSyncExternalStore, type ReactNode } from 'react'",
|
||||||
"import { registerContext, mizanCall, mizanFetch } from '@mizan/runtime'",
|
"import { registerContext, mizanFetch, mizanCall, type ContextState } from '@mizan/runtime'",
|
||||||
'',
|
'',
|
||||||
]
|
]
|
||||||
|
|
||||||
@@ -38,103 +41,114 @@ export function generateReactAdapter(schema) {
|
|||||||
lines.push('')
|
lines.push('')
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Global context hooks ────────────────────────────────────────────
|
// ── Helper hook: subscribe to kernel state ──────────────────────────
|
||||||
|
|
||||||
if (globalContexts.length > 0) {
|
lines.push('// Subscribe to kernel state via useSyncExternalStore')
|
||||||
const p = pascalCase('global')
|
lines.push('function useContextState<T>(')
|
||||||
|
lines.push(' name: string,')
|
||||||
lines.push(`// Global context — fetched once at app init`)
|
lines.push(' params: Record<string, any>,')
|
||||||
lines.push(`const GlobalCtx = createContext<${p}ContextData | null>(null)`)
|
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('')
|
||||||
|
lines.push(' if (!ref.current) {')
|
||||||
lines.push(`export function GlobalContextProvider({ children }: { children: ReactNode }) {`)
|
lines.push(' ref.current = registerContext(name, params, fetchFn, initialData)')
|
||||||
lines.push(` const [data, setData] = useState<${p}ContextData | null>(() => {`)
|
lines.push(' }')
|
||||||
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('')
|
||||||
lines.push(` const refetch = useCallback(async () => {`)
|
lines.push(' const handle = ref.current')
|
||||||
lines.push(` const result = await fetch${p}Context({} as any)`)
|
|
||||||
lines.push(` setData(result)`)
|
|
||||||
lines.push(` }, [])`)
|
|
||||||
lines.push('')
|
lines.push('')
|
||||||
lines.push(` useEffect(() => { if (!data) refetch() }, [data, refetch])`)
|
lines.push(' // Fetch on mount if no data')
|
||||||
lines.push(` useEffect(() => registerContext('global', {}, refetch), [refetch])`)
|
lines.push(' useEffect(() => {')
|
||||||
|
lines.push(" if (handle.getState().status === 'idle') handle.refetch()")
|
||||||
|
lines.push(' return () => handle.unregister()')
|
||||||
|
lines.push(' }, [handle])')
|
||||||
lines.push('')
|
lines.push('')
|
||||||
lines.push(` return <GlobalCtx.Provider value={data}>{children}</GlobalCtx.Provider>`)
|
lines.push(' return useSyncExternalStore(')
|
||||||
|
lines.push(' handle.subscribe,')
|
||||||
|
lines.push(' handle.getState,')
|
||||||
|
lines.push(' handle.getState,')
|
||||||
|
lines.push(' )')
|
||||||
lines.push('}')
|
lines.push('}')
|
||||||
lines.push('')
|
lines.push('')
|
||||||
|
|
||||||
for (const fn of globalContexts) {
|
// ── Mutation hook helper ────────────────────────────────────────────
|
||||||
const hookPascal = pascalCase(fn.camelName)
|
|
||||||
lines.push(`export function use${hookPascal}(): ${fn.outputType} {`)
|
lines.push('// Mutation hook with loading/error state')
|
||||||
lines.push(` const ctx = useContext(GlobalCtx)`)
|
lines.push('function useMutation<TArgs, TResult>(')
|
||||||
lines.push(` if (!ctx) throw new Error('use${hookPascal} requires GlobalContextProvider')`)
|
lines.push(' callFn: (args: TArgs) => Promise<TResult>,')
|
||||||
lines.push(` return ctx.${fn.name}`)
|
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('}')
|
||||||
lines.push('')
|
lines.push('')
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── Named context providers ─────────────────────────────────────────
|
// ── Context hooks ───────────────────────────────────────────────────
|
||||||
|
|
||||||
for (const [ctxName, ctxMeta] of namedContexts) {
|
for (const [ctxName, ctxMeta] of Object.entries(contextGroups)) {
|
||||||
const p = pascalCase(ctxName)
|
const p = pascalCase(ctxName)
|
||||||
const ctxFunctions = functions.filter(fn => fn.isContext === ctxName)
|
const ctxFunctions = functions.filter(fn => fn.isContext === ctxName)
|
||||||
const paramEntries = Object.entries(ctxMeta.params || {})
|
const paramEntries = Object.entries(ctxMeta.params || {})
|
||||||
|
|
||||||
lines.push(`// ${p} context`)
|
lines.push(`// ── ${p} Context ──`)
|
||||||
lines.push(`const ${p}Ctx = createContext<${p}ContextData | null>(null)`)
|
|
||||||
lines.push('')
|
lines.push('')
|
||||||
|
|
||||||
// Provider
|
// Hook that returns the full kernel state
|
||||||
lines.push(`export function ${p}Context({ children, ...params }: ${p}ContextParams & { children: ReactNode }) {`)
|
if (paramEntries.length > 0) {
|
||||||
lines.push(` const [data, setData] = useState<${p}ContextData | null>(() => {`)
|
lines.push(`export function use${p}Context(params: ${p}ContextParams): ContextState<${p}ContextData> {`)
|
||||||
lines.push(` if (typeof window === 'undefined') return null`)
|
lines.push(` const ssrData = typeof window !== 'undefined' ? (window as any).__MIZAN_SSR_DATA__ : null`)
|
||||||
lines.push(` const ssr = (window as any).__MIZAN_SSR_DATA__`)
|
lines.push(` return useContextState('${ctxName}', params, () => fetch${p}Context(params), ssrData)`)
|
||||||
if (ctxFunctions.length > 0) {
|
} else {
|
||||||
lines.push(` if (ssr?.${ctxFunctions[0].name} !== undefined) return ssr`)
|
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('}')
|
||||||
lines.push('')
|
lines.push('')
|
||||||
|
|
||||||
// Hooks
|
// Convenience hooks for individual data fields
|
||||||
for (const fn of ctxFunctions) {
|
for (const fn of ctxFunctions) {
|
||||||
const hookPascal = pascalCase(fn.camelName)
|
const hookPascal = pascalCase(fn.camelName)
|
||||||
|
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(`export function use${hookPascal}(): ${fn.outputType} | null {`)
|
||||||
lines.push(` const ctx = useContext(${p}Ctx)`)
|
lines.push(` const state = use${p}Context()`)
|
||||||
lines.push(` return ctx?.${fn.name} ?? null`)
|
}
|
||||||
|
lines.push(` return state.data?.${fn.name} ?? null`)
|
||||||
lines.push('}')
|
lines.push('}')
|
||||||
lines.push('')
|
lines.push('')
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Mutation hooks ──────────────────────────────────────────────────
|
// ── Mutation hooks (with loading/error) ──────────────────────────────
|
||||||
|
|
||||||
for (const fn of mutations) {
|
for (const fn of mutations) {
|
||||||
const p = pascalCase(fn.camelName)
|
const p = pascalCase(fn.camelName)
|
||||||
if (fn.hasInput) {
|
if (fn.hasInput) {
|
||||||
lines.push(`export function use${p}() {`)
|
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('}')
|
lines.push('}')
|
||||||
} else {
|
} else {
|
||||||
lines.push(`export function use${p}() {`)
|
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('}')
|
||||||
}
|
}
|
||||||
lines.push('')
|
lines.push('')
|
||||||
@@ -146,15 +160,21 @@ export function generateReactAdapter(schema) {
|
|||||||
const p = pascalCase(fn.camelName)
|
const p = pascalCase(fn.camelName)
|
||||||
if (fn.hasInput) {
|
if (fn.hasInput) {
|
||||||
lines.push(`export function use${p}() {`)
|
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('}')
|
lines.push('}')
|
||||||
} else {
|
} else {
|
||||||
lines.push(`export function use${p}() {`)
|
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('}')
|
||||||
}
|
}
|
||||||
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')
|
return lines.join('\n')
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
/**
|
/**
|
||||||
* Svelte Stage 2 — Generates stores from Stage 1 output.
|
* Svelte Stage 2 — Generates stores from Stage 1 output.
|
||||||
|
*
|
||||||
|
* Subscribes to the kernel for state. Returns readable stores.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
function pascalCase(str) {
|
function pascalCase(str) {
|
||||||
@@ -15,12 +17,11 @@ export function generateSvelteAdapter(schema) {
|
|||||||
const lines = [
|
const lines = [
|
||||||
'// AUTO-GENERATED by mizan — do not edit',
|
'// AUTO-GENERATED by mizan — do not edit',
|
||||||
'',
|
'',
|
||||||
"import { writable, derived, type Readable } from 'svelte/store'",
|
"import { readable, type Readable } from 'svelte/store'",
|
||||||
"import { registerContext } from '@mizan/runtime'",
|
"import { registerContext, type ContextState } from '@mizan/runtime'",
|
||||||
'',
|
'',
|
||||||
]
|
]
|
||||||
|
|
||||||
// Stage 1 imports
|
|
||||||
const stage1Imports = []
|
const stage1Imports = []
|
||||||
for (const [ctxName] of Object.entries(contextGroups)) {
|
for (const [ctxName] of Object.entries(contextGroups)) {
|
||||||
const p = pascalCase(ctxName)
|
const p = pascalCase(ctxName)
|
||||||
@@ -34,14 +35,11 @@ export function generateSvelteAdapter(schema) {
|
|||||||
lines.push('')
|
lines.push('')
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Context stores ──────────────────────────────────────────────────
|
|
||||||
|
|
||||||
for (const [ctxName, ctxMeta] of Object.entries(contextGroups)) {
|
for (const [ctxName, ctxMeta] of Object.entries(contextGroups)) {
|
||||||
const p = pascalCase(ctxName)
|
const p = pascalCase(ctxName)
|
||||||
const ctxFunctions = functions.filter(fn => fn.isContext === ctxName)
|
const ctxFunctions = functions.filter(fn => fn.isContext === ctxName)
|
||||||
const paramEntries = Object.entries(ctxMeta.params || {})
|
const paramEntries = Object.entries(ctxMeta.params || {})
|
||||||
|
const paramsArg = paramEntries.length > 0 ? 'params' : '{} as any'
|
||||||
lines.push(`// ${p} context`)
|
|
||||||
|
|
||||||
if (paramEntries.length > 0) {
|
if (paramEntries.length > 0) {
|
||||||
lines.push(`export function create${p}Context(params: ${p}ContextParams) {`)
|
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(`export function create${p}Context() {`)
|
||||||
}
|
}
|
||||||
|
|
||||||
lines.push(` const data = writable<${p}ContextData | null>(null)`)
|
// Use readable store backed by kernel subscription
|
||||||
lines.push(` const loading = writable(true)`)
|
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('')
|
||||||
lines.push(` const refetch = async () => {`)
|
lines.push(` return store`)
|
||||||
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('}')
|
lines.push('}')
|
||||||
lines.push('')
|
lines.push('')
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Mutation + function exports ─────────────────────────────────────
|
// Re-export mutations as-is from Stage 1
|
||||||
|
|
||||||
for (const fn of [...mutations, ...plainFns]) {
|
for (const fn of [...mutations, ...plainFns]) {
|
||||||
const p = pascalCase(fn.camelName)
|
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('')
|
||||||
|
|
||||||
|
lines.push("export type { ContextState } from '@mizan/runtime'")
|
||||||
|
lines.push("export { configure, initSession, MizanError } from '@mizan/runtime'")
|
||||||
|
lines.push('')
|
||||||
|
|
||||||
return lines.join('\n')
|
return lines.join('\n')
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
/**
|
/**
|
||||||
* Vue Stage 2 — Generates composables from Stage 1 output.
|
* Vue Stage 2 — Generates composables from Stage 1 output.
|
||||||
|
*
|
||||||
|
* Subscribes to the kernel for state. Vue reactivity wraps kernel notifications.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
function pascalCase(str) {
|
function pascalCase(str) {
|
||||||
@@ -15,12 +17,11 @@ export function generateVueAdapter(schema) {
|
|||||||
const lines = [
|
const lines = [
|
||||||
'// AUTO-GENERATED by mizan — do not edit',
|
'// AUTO-GENERATED by mizan — do not edit',
|
||||||
'',
|
'',
|
||||||
"import { ref, computed, watch, onMounted, onUnmounted, provide, inject, type Ref, type ComputedRef, type InjectionKey } from 'vue'",
|
"import { ref, computed, onMounted, onUnmounted, onServerPrefetch, type ComputedRef } from 'vue'",
|
||||||
"import { registerContext } from '@mizan/runtime'",
|
"import { registerContext, type ContextState } from '@mizan/runtime'",
|
||||||
'',
|
'',
|
||||||
]
|
]
|
||||||
|
|
||||||
// Stage 1 imports
|
|
||||||
const stage1Imports = []
|
const stage1Imports = []
|
||||||
for (const [ctxName] of Object.entries(contextGroups)) {
|
for (const [ctxName] of Object.entries(contextGroups)) {
|
||||||
const p = pascalCase(ctxName)
|
const p = pascalCase(ctxName)
|
||||||
@@ -34,72 +35,70 @@ export function generateVueAdapter(schema) {
|
|||||||
lines.push('')
|
lines.push('')
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Context composables ─────────────────────────────────────────────
|
|
||||||
|
|
||||||
for (const [ctxName, ctxMeta] of Object.entries(contextGroups)) {
|
for (const [ctxName, ctxMeta] of Object.entries(contextGroups)) {
|
||||||
const p = pascalCase(ctxName)
|
const p = pascalCase(ctxName)
|
||||||
const ctxFunctions = functions.filter(fn => fn.isContext === ctxName)
|
const ctxFunctions = functions.filter(fn => fn.isContext === ctxName)
|
||||||
const paramEntries = Object.entries(ctxMeta.params || {})
|
const paramEntries = Object.entries(ctxMeta.params || {})
|
||||||
|
const paramsArg = paramEntries.length > 0 ? 'params' : '{} as any'
|
||||||
|
|
||||||
lines.push(`// ${p} context`)
|
if (paramEntries.length > 0) {
|
||||||
lines.push(`const ${p}Key: InjectionKey<{ data: Ref<${p}ContextData | null>, loading: Ref<boolean> }> = Symbol('${ctxName}')`)
|
lines.push(`export function use${p}Context(params: ${p}ContextParams) {`)
|
||||||
lines.push('')
|
} else {
|
||||||
|
lines.push(`export function use${p}Context() {`)
|
||||||
|
}
|
||||||
|
|
||||||
// Provider composable
|
lines.push(` const state = ref<ContextState<${p}ContextData>>({ data: null, status: 'idle', error: null })`)
|
||||||
if (paramEntries.length > 0) {
|
lines.push(` let handle: ReturnType<typeof registerContext> | null = null`)
|
||||||
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('')
|
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(` onMounted(() => {`)
|
||||||
lines.push(` refetch()`)
|
lines.push(` handle = registerContext('${ctxName}', ${paramsArg}, () => fetch${p}Context(${paramsArg}))`)
|
||||||
if (paramEntries.length > 0) {
|
lines.push(` handle.subscribe(() => { state.value = handle!.getState() })`)
|
||||||
lines.push(` unregister = registerContext('${ctxName}', params, refetch)`)
|
lines.push(` handle.refetch()`)
|
||||||
} else {
|
|
||||||
lines.push(` unregister = registerContext('${ctxName}', {}, refetch)`)
|
|
||||||
}
|
|
||||||
lines.push(` })`)
|
lines.push(` })`)
|
||||||
lines.push(` onUnmounted(() => { unregister?.() })`)
|
|
||||||
lines.push('')
|
lines.push('')
|
||||||
lines.push(` provide(${p}Key, { data, loading })`)
|
lines.push(` onServerPrefetch(async () => {`)
|
||||||
lines.push('}')
|
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('')
|
||||||
|
lines.push(` onUnmounted(() => { handle?.unregister() })`)
|
||||||
// Consumer composables
|
lines.push('')
|
||||||
|
lines.push(` return {`)
|
||||||
|
lines.push(` state,`)
|
||||||
for (const fn of ctxFunctions) {
|
for (const fn of ctxFunctions) {
|
||||||
const hookPascal = pascalCase(fn.camelName)
|
lines.push(` ${fn.camelName}: computed(() => state.value.data?.${fn.name} ?? null) as ComputedRef<${fn.outputType} | null>,`)
|
||||||
lines.push(`export function use${hookPascal}(): ComputedRef<${fn.outputType} | null> {`)
|
}
|
||||||
lines.push(` const ctx = inject(${p}Key)`)
|
lines.push(` loading: computed(() => state.value.status === 'loading'),`)
|
||||||
lines.push(` if (!ctx) throw new Error('use${hookPascal} requires provide${p}Context in a parent')`)
|
lines.push(` error: computed(() => state.value.error),`)
|
||||||
lines.push(` return computed(() => ctx.data.value?.${fn.name} ?? null)`)
|
lines.push(` }`)
|
||||||
lines.push('}')
|
lines.push('}')
|
||||||
lines.push('')
|
lines.push('')
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
// ── Mutation composables ────────────────────────────────────────────
|
|
||||||
|
|
||||||
for (const fn of [...mutations, ...plainFns]) {
|
for (const fn of [...mutations, ...plainFns]) {
|
||||||
const p = pascalCase(fn.camelName)
|
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('')
|
||||||
}
|
}
|
||||||
|
|
||||||
|
lines.push("export type { ContextState } from '@mizan/runtime'")
|
||||||
|
lines.push("export { configure, initSession, MizanError } from '@mizan/runtime'")
|
||||||
|
lines.push('')
|
||||||
|
|
||||||
return lines.join('\n')
|
return lines.join('\n')
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,11 +3,7 @@
|
|||||||
*
|
*
|
||||||
* Zero framework dependencies. React, Vue, Svelte — all import from here.
|
* Zero framework dependencies. React, Vue, Svelte — all import from here.
|
||||||
*
|
*
|
||||||
* Four concerns:
|
* The kernel owns the data. Adapters subscribe and render.
|
||||||
* 1. Configuration — baseUrl, auth headers, CSRF
|
|
||||||
* 2. Context registry — mounted providers register for invalidation
|
|
||||||
* 3. Invalidation — microtask-batched, scoped or broad
|
|
||||||
* 4. Fetch — mizanFetch (GET context bundles) + mizanCall (POST mutations)
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
// === Error ===
|
// === Error ===
|
||||||
@@ -54,12 +50,6 @@ function getCSRFToken(): string | null {
|
|||||||
|
|
||||||
let _sessionReady: Promise<void> | null = null
|
let _sessionReady: Promise<void> | null = null
|
||||||
|
|
||||||
/**
|
|
||||||
* Initialize a session (fetches CSRF cookie from GET /session/).
|
|
||||||
* Called automatically on first fetch if not called explicitly.
|
|
||||||
* No-op if a CSRF cookie already exists.
|
|
||||||
* Retries on failure — resets so next call tries again.
|
|
||||||
*/
|
|
||||||
export function initSession(): Promise<void> {
|
export function initSession(): Promise<void> {
|
||||||
if (_sessionReady) return _sessionReady
|
if (_sessionReady) return _sessionReady
|
||||||
|
|
||||||
@@ -76,39 +66,109 @@ export function initSession(): Promise<void> {
|
|||||||
if (attempt < 2) await new Promise(r => setTimeout(r, (attempt + 1) * 100))
|
if (attempt < 2) await new Promise(r => setTimeout(r, (attempt + 1) * 100))
|
||||||
}
|
}
|
||||||
|
|
||||||
// All retries failed — reset so next call tries again
|
|
||||||
_sessionReady = null
|
_sessionReady = null
|
||||||
})()
|
})()
|
||||||
|
|
||||||
return _sessionReady
|
return _sessionReady
|
||||||
}
|
}
|
||||||
|
|
||||||
// === Context Registry ===
|
// === Context State ===
|
||||||
|
|
||||||
export type RefetchFn = () => void
|
export type ContextStatus = 'idle' | 'loading' | 'success' | 'error'
|
||||||
|
|
||||||
|
export interface ContextState<T = any> {
|
||||||
|
data: T | null
|
||||||
|
status: ContextStatus
|
||||||
|
error: Error | null
|
||||||
|
}
|
||||||
|
|
||||||
|
type Listener = () => void
|
||||||
type ParamKey = string
|
type ParamKey = string
|
||||||
|
|
||||||
interface ContextEntry {
|
interface ContextEntry {
|
||||||
params: Record<string, any>
|
params: Record<string, any>
|
||||||
refetch: RefetchFn
|
state: ContextState
|
||||||
|
listeners: Set<Listener>
|
||||||
|
fetchFn: () => Promise<any>
|
||||||
}
|
}
|
||||||
|
|
||||||
const contexts: Map<string, Map<ParamKey, ContextEntry>> = new Map()
|
const contexts: Map<string, Map<ParamKey, ContextEntry>> = new Map()
|
||||||
|
|
||||||
/** Deterministic JSON key for params — sorted to avoid order-dependency */
|
|
||||||
function stableKey(params: Record<string, any>): string {
|
function stableKey(params: Record<string, any>): string {
|
||||||
return JSON.stringify(params, Object.keys(params).sort())
|
return JSON.stringify(params, Object.keys(params).sort())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Register a context instance. The kernel owns the fetch lifecycle.
|
||||||
|
*
|
||||||
|
* Returns { getState, subscribe, refetch, unregister }.
|
||||||
|
* Adapters call subscribe() to get notified on state changes.
|
||||||
|
*/
|
||||||
export function registerContext(
|
export function registerContext(
|
||||||
name: string,
|
name: string,
|
||||||
params: Record<string, any>,
|
params: Record<string, any>,
|
||||||
refetch: RefetchFn,
|
fetchFn: () => Promise<any>,
|
||||||
): () => void {
|
initialData?: any,
|
||||||
|
): {
|
||||||
|
getState: () => ContextState
|
||||||
|
subscribe: (listener: Listener) => () => void
|
||||||
|
refetch: () => Promise<void>
|
||||||
|
unregister: () => void
|
||||||
|
} {
|
||||||
if (!contexts.has(name)) contexts.set(name, new Map())
|
if (!contexts.has(name)) contexts.set(name, new Map())
|
||||||
const key = stableKey(params)
|
const key = stableKey(params)
|
||||||
contexts.get(name)!.set(key, { params, refetch })
|
const map = contexts.get(name)!
|
||||||
return () => contexts.get(name)?.delete(key)
|
|
||||||
|
// Reuse existing entry if same key is re-registered (React Strict Mode)
|
||||||
|
let entry = map.get(key)
|
||||||
|
if (!entry) {
|
||||||
|
entry = {
|
||||||
|
params,
|
||||||
|
state: {
|
||||||
|
data: initialData ?? null,
|
||||||
|
status: initialData ? 'success' : 'idle',
|
||||||
|
error: null,
|
||||||
|
},
|
||||||
|
listeners: new Set(),
|
||||||
|
fetchFn,
|
||||||
|
}
|
||||||
|
map.set(key, entry)
|
||||||
|
} else {
|
||||||
|
// Update fetchFn in case closure changed
|
||||||
|
entry.fetchFn = fetchFn
|
||||||
|
}
|
||||||
|
|
||||||
|
const self = entry
|
||||||
|
|
||||||
|
function notify() {
|
||||||
|
self.listeners.forEach(l => l())
|
||||||
|
}
|
||||||
|
|
||||||
|
async function refetch() {
|
||||||
|
self.state = { ...self.state, status: 'loading', error: null }
|
||||||
|
notify()
|
||||||
|
|
||||||
|
try {
|
||||||
|
const data = await self.fetchFn()
|
||||||
|
self.state = { data, status: 'success', error: null }
|
||||||
|
} catch (e) {
|
||||||
|
self.state = { ...self.state, status: 'error', error: e as Error }
|
||||||
|
}
|
||||||
|
notify()
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
getState: () => self.state,
|
||||||
|
subscribe: (listener: Listener) => {
|
||||||
|
self.listeners.add(listener)
|
||||||
|
return () => self.listeners.delete(listener)
|
||||||
|
},
|
||||||
|
refetch,
|
||||||
|
unregister: () => {
|
||||||
|
self.listeners.clear()
|
||||||
|
map.delete(key)
|
||||||
|
},
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// === Invalidation ===
|
// === Invalidation ===
|
||||||
@@ -130,18 +190,42 @@ export function invalidate(context: string, params?: Record<string, any>): void
|
|||||||
}
|
}
|
||||||
|
|
||||||
function flush(): void {
|
function flush(): void {
|
||||||
|
// Broad invalidations — refetch all instances
|
||||||
for (const name of pending) {
|
for (const name of pending) {
|
||||||
const entries = contexts.get(name)
|
const entries = contexts.get(name)
|
||||||
if (entries) entries.forEach(entry => entry.refetch())
|
if (entries) {
|
||||||
|
entries.forEach(entry => {
|
||||||
|
entry.state = { ...entry.state, status: 'loading', error: null }
|
||||||
|
entry.listeners.forEach(l => l())
|
||||||
|
entry.fetchFn().then(data => {
|
||||||
|
entry.state = { data, status: 'success', error: null }
|
||||||
|
entry.listeners.forEach(l => l())
|
||||||
|
}).catch(err => {
|
||||||
|
entry.state = { ...entry.state, status: 'error', error: err }
|
||||||
|
entry.listeners.forEach(l => l())
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Scoped invalidations — refetch matching params
|
||||||
for (const { context: name, params } of pendingScoped) {
|
for (const { context: name, params } of pendingScoped) {
|
||||||
if (pending.has(name)) continue
|
if (pending.has(name)) continue
|
||||||
const entries = contexts.get(name)
|
const entries = contexts.get(name)
|
||||||
if (!entries) continue
|
if (!entries) continue
|
||||||
const key = stableKey(params)
|
const key = stableKey(params)
|
||||||
const entry = entries.get(key)
|
const entry = entries.get(key)
|
||||||
if (entry) entry.refetch()
|
if (entry) {
|
||||||
|
entry.state = { ...entry.state, status: 'loading', error: null }
|
||||||
|
entry.listeners.forEach(l => l())
|
||||||
|
entry.fetchFn().then(data => {
|
||||||
|
entry.state = { data, status: 'success', error: null }
|
||||||
|
entry.listeners.forEach(l => l())
|
||||||
|
}).catch(err => {
|
||||||
|
entry.state = { ...entry.state, status: 'error', error: err }
|
||||||
|
entry.listeners.forEach(l => l())
|
||||||
|
})
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pending.clear()
|
pending.clear()
|
||||||
@@ -159,7 +243,6 @@ async function fetchWithRetry(
|
|||||||
for (let attempt = 0; ; attempt++) {
|
for (let attempt = 0; ; attempt++) {
|
||||||
try {
|
try {
|
||||||
const res = await fetch(input, init)
|
const res = await fetch(input, init)
|
||||||
// Don't retry client errors (4xx) — only server/network errors
|
|
||||||
if (res.ok || (res.status >= 400 && res.status < 500)) return res
|
if (res.ok || (res.status >= 400 && res.status < 500)) return res
|
||||||
if (attempt >= retries) return res
|
if (attempt >= retries) return res
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
@@ -209,7 +292,6 @@ export async function mizanCall(
|
|||||||
const headers = await resolveHeaders()
|
const headers = await resolveHeaders()
|
||||||
headers['Content-Type'] = 'application/json'
|
headers['Content-Type'] = 'application/json'
|
||||||
|
|
||||||
// Mutations are not retried — they are not idempotent
|
|
||||||
const res = await fetch(`${config.baseUrl}/call/`, {
|
const res = await fetch(`${config.baseUrl}/call/`, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers,
|
headers,
|
||||||
|
|||||||
Reference in New Issue
Block a user