React wrapper-layer codegen — restore the idioms over the kernel
The harness was written against the MIZAN.md oracle (<MizanContext>,
provider-per-context, useMizan, etc.) but the codegen had been narrowed
to just hooks-direct-on-kernel after the kernel split. Restoring the
React-idiomatic layer on top of the kernel.
backends/mizan-django/generate/generator/lib/adapters/react.mjs:
- Emits <MizanContext baseUrl="…"> root provider that calls configure()
once and (if a global context is registered) wraps children in
<GlobalContextProvider>.
- Emits <GlobalContextProvider> + <{Name}Context> per named context —
kernel registration happens once per provider mount, not per hook
call. Consumers read from React Context.
- Base hooks: useGlobalContext() / use{Name}Context() return full
ContextState<T> (data + status + error).
- Convenience hooks per context-function (use{Fn}() returns data | null)
and per regular function/mutation (use{Fn}() returns
{ mutate, isPending, error }).
- useMizan() returns { call, fetch } as an imperative escape hatch
for test harnesses or rare cases where typed hooks don't fit.
- Re-exports MizanError, configure, initSession, ContextState from
@mizan/base.
backends/mizan-django/generate/generator/cli.mjs:
- After Stage 2, appends `export * from './<adapter>'` to index.ts so
`import { useEcho, MizanContext } from './api'` works as a barrel.
Bug fixes surfaced during integration:
- react.mjs was generating `from '../index'` (wrong path); flat layout
needs `./index`.
- harness django.config.mjs had `output: 'src/api/generated.ts'` which
the codegen treated as a directory; corrected to `output: 'src/api'`.
- example testapp/clients.py imported from the deleted
mizan.setup.registry path; routed through mizan.setup aggregator.
harness/package.json: adds @mizan/base dep so the generated react.tsx
can resolve its kernel imports.
harness/src/fixtures.tsx:
- DjangoError → MizanError (kernel error class, backend-agnostic).
- useChatChannel sourced from ./api/channels.hooks directly (not
re-exported from the unified index for now).
- Form fixtures removed — forms codegen deferred per Blazr scope.
Verified: harness `vite build` succeeds, 53 modules transformed.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -1,8 +1,23 @@
|
||||
/**
|
||||
* React Stage 2 — Generates hooks + context providers from Stage 1 output.
|
||||
* React Stage 2 — Generates idiomatic React providers + hooks on top of the kernel.
|
||||
*
|
||||
* Generated providers subscribe to the runtime kernel for state.
|
||||
* The kernel owns data, status, and error. React just renders.
|
||||
* The kernel (@mizan/base) owns data, status, error. This adapter wraps each
|
||||
* registered context in a React Provider component so kernel subscription happens
|
||||
* once per provider mount, and consumer hooks read from React Context.
|
||||
*
|
||||
* Output shape:
|
||||
* <MizanContext baseUrl="..."> root — calls configure(), auto-mounts global
|
||||
* <UserContext user_id={...}> per-named-context provider
|
||||
* <App />
|
||||
* </UserContext>
|
||||
* </MizanContext>
|
||||
*
|
||||
* useGlobalContext() full ContextState<GlobalContextData>
|
||||
* useCurrentUser() convenience: data field
|
||||
* useUserContext() full ContextState<UserContextData>
|
||||
* useUserProfile() convenience: data field
|
||||
* useEcho() mutation/plain — { mutate, isPending, error }
|
||||
* useMizan() escape hatch — { call, fetch }
|
||||
*/
|
||||
|
||||
function pascalCase(str) {
|
||||
@@ -13,21 +28,42 @@ export function generateReactAdapter(schema) {
|
||||
const functions = schema['x-mizan-functions'] || []
|
||||
const contextGroups = schema['x-mizan-contexts'] || {}
|
||||
const namedContexts = Object.entries(contextGroups).filter(([n]) => n !== 'global')
|
||||
const globalContexts = functions.filter(fn => fn.isContext === 'global')
|
||||
const hasGlobal = !!contextGroups.global
|
||||
const globalFns = functions.filter(fn => fn.isContext === 'global')
|
||||
const mutations = functions.filter(fn => !fn.isContext && !fn.isForm && fn.affects)
|
||||
const plainFns = functions.filter(fn => !fn.isContext && !fn.isForm && !fn.affects)
|
||||
|
||||
const lines = [
|
||||
const lines = []
|
||||
|
||||
// ── Header + imports ─────────────────────────────────────────────────
|
||||
|
||||
lines.push(
|
||||
"'use client'",
|
||||
'',
|
||||
'// AUTO-GENERATED by mizan — do not edit',
|
||||
'',
|
||||
"import { createContext, useContext, useState, useEffect, useCallback, useRef, useSyncExternalStore, type ReactNode } from 'react'",
|
||||
"import { registerContext, mizanFetch, mizanCall, type ContextState } from '@mizan/base'",
|
||||
"import {",
|
||||
" createContext,",
|
||||
" useCallback,",
|
||||
" useContext,",
|
||||
" useEffect,",
|
||||
" useRef,",
|
||||
" useState,",
|
||||
" useSyncExternalStore,",
|
||||
" type ReactNode,",
|
||||
"} from 'react'",
|
||||
"import {",
|
||||
" configure,",
|
||||
" initSession,",
|
||||
" mizanCall,",
|
||||
" mizanFetch,",
|
||||
" MizanError,",
|
||||
" registerContext,",
|
||||
" type ContextState,",
|
||||
"} from '@mizan/base'",
|
||||
'',
|
||||
]
|
||||
)
|
||||
|
||||
// Import from Stage 1
|
||||
const stage1Imports = []
|
||||
for (const [ctxName] of Object.entries(contextGroups)) {
|
||||
const p = pascalCase(ctxName)
|
||||
@@ -37,144 +73,226 @@ export function generateReactAdapter(schema) {
|
||||
stage1Imports.push(`call${pascalCase(fn.camelName)}`)
|
||||
}
|
||||
if (stage1Imports.length > 0) {
|
||||
lines.push(`import { ${stage1Imports.join(', ')} } from '../index'`)
|
||||
lines.push('')
|
||||
lines.push(`import { ${stage1Imports.join(', ')} } from './index'`, '')
|
||||
}
|
||||
|
||||
// ── Helper hook: subscribe to kernel state ──────────────────────────
|
||||
// ── Internal helper: subscribe to kernel state from a Provider ──────
|
||||
|
||||
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(
|
||||
'// Internal — runs inside a Provider, registers with the kernel exactly once.',
|
||||
'function useContextSubscription<T>(',
|
||||
' name: string,',
|
||||
' params: Record<string, any>,',
|
||||
' fetchFn: () => Promise<T>,',
|
||||
' initialData?: T,',
|
||||
'): ContextState<T> {',
|
||||
' const ref = useRef<ReturnType<typeof registerContext> | null>(null)',
|
||||
' if (!ref.current) {',
|
||||
' ref.current = registerContext(name, params, fetchFn, initialData)',
|
||||
' }',
|
||||
' const handle = ref.current',
|
||||
'',
|
||||
' useEffect(() => {',
|
||||
" if (handle.getState().status === 'idle') handle.refetch()",
|
||||
' return () => handle.unregister()',
|
||||
' }, [handle])',
|
||||
'',
|
||||
' return useSyncExternalStore(handle.subscribe, handle.getState, handle.getState)',
|
||||
'}',
|
||||
'',
|
||||
)
|
||||
|
||||
// ── Mutation hook helper ────────────────────────────────────────────
|
||||
// ── Internal helper: mutation wrapper ───────────────────────────────
|
||||
|
||||
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('')
|
||||
lines.push(
|
||||
'// Internal — wraps an imperative call() with isPending / error state.',
|
||||
'interface MutationHook<TArgs, TResult> {',
|
||||
' mutate: (args: TArgs) => Promise<TResult>',
|
||||
' isPending: boolean',
|
||||
' error: Error | null',
|
||||
'}',
|
||||
'',
|
||||
'function useMutation<TArgs, TResult>(',
|
||||
' callFn: (args: TArgs) => Promise<TResult>,',
|
||||
'): MutationHook<TArgs, TResult> {',
|
||||
' const [isPending, setIsPending] = useState(false)',
|
||||
' const [error, setError] = useState<Error | null>(null)',
|
||||
'',
|
||||
' const mutate = useCallback(async (args: TArgs) => {',
|
||||
' setIsPending(true)',
|
||||
' setError(null)',
|
||||
' try {',
|
||||
' return await callFn(args)',
|
||||
' } catch (e) {',
|
||||
' setError(e as Error)',
|
||||
' throw e',
|
||||
' } finally {',
|
||||
' setIsPending(false)',
|
||||
' }',
|
||||
' }, [callFn])',
|
||||
'',
|
||||
' return { mutate, isPending, error }',
|
||||
'}',
|
||||
'',
|
||||
)
|
||||
|
||||
// ── Context hooks ───────────────────────────────────────────────────
|
||||
// ── Global context provider + hooks ─────────────────────────────────
|
||||
|
||||
for (const [ctxName, ctxMeta] of Object.entries(contextGroups)) {
|
||||
if (hasGlobal) {
|
||||
lines.push(
|
||||
'// ── Global Context ──',
|
||||
'',
|
||||
'const GlobalCtx = createContext<ContextState<GlobalContextData> | null>(null)',
|
||||
'',
|
||||
'export function GlobalContextProvider({ children }: { children: ReactNode }) {',
|
||||
" const ssrData = typeof window !== 'undefined' ? (window as any).__MIZAN_SSR_DATA__ : undefined",
|
||||
" const state = useContextSubscription('global', {}, () => fetchGlobalContext({} as any), ssrData)",
|
||||
' return <GlobalCtx.Provider value={state}>{children}</GlobalCtx.Provider>',
|
||||
'}',
|
||||
'',
|
||||
'export function useGlobalContext(): ContextState<GlobalContextData> {',
|
||||
' const ctx = useContext(GlobalCtx)',
|
||||
" if (!ctx) throw new Error('useGlobalContext requires <MizanContext> or <GlobalContextProvider>')",
|
||||
' return ctx',
|
||||
'}',
|
||||
'',
|
||||
)
|
||||
|
||||
for (const fn of globalFns) {
|
||||
const p = pascalCase(fn.camelName)
|
||||
lines.push(
|
||||
`export function use${p}(): ${fn.outputType} | null {`,
|
||||
` return useGlobalContext().data?.${fn.name} ?? null`,
|
||||
'}',
|
||||
'',
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// ── Named context providers + hooks ─────────────────────────────────
|
||||
|
||||
for (const [ctxName, ctxMeta] of namedContexts) {
|
||||
const p = pascalCase(ctxName)
|
||||
const ctxFunctions = functions.filter(fn => fn.isContext === ctxName)
|
||||
const paramEntries = Object.entries(ctxMeta.params || {})
|
||||
const paramKeys = Object.keys(ctxMeta.params || {})
|
||||
const hasParams = paramKeys.length > 0
|
||||
|
||||
lines.push(`// ── ${p} Context ──`)
|
||||
lines.push('')
|
||||
lines.push(
|
||||
`// ── ${p} Context ──`,
|
||||
'',
|
||||
`const ${p}Ctx = createContext<ContextState<${p}ContextData> | null>(null)`,
|
||||
'',
|
||||
)
|
||||
|
||||
// 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)`)
|
||||
if (hasParams) {
|
||||
lines.push(
|
||||
`export function ${p}Context({ children, ...params }: ${p}ContextParams & { children: ReactNode }) {`,
|
||||
` const state = useContextSubscription('${ctxName}', params, () => fetch${p}Context(params))`,
|
||||
` return <${p}Ctx.Provider value={state}>{children}</${p}Ctx.Provider>`,
|
||||
'}',
|
||||
)
|
||||
} 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(
|
||||
`export function ${p}Context({ children }: { children: ReactNode }) {`,
|
||||
` const state = useContextSubscription('${ctxName}', {}, () => fetch${p}Context({} as any))`,
|
||||
` return <${p}Ctx.Provider value={state}>{children}</${p}Ctx.Provider>`,
|
||||
'}',
|
||||
)
|
||||
}
|
||||
lines.push('}')
|
||||
lines.push('')
|
||||
|
||||
// Convenience hooks for individual data fields
|
||||
lines.push(
|
||||
`export function use${p}Context(): ContextState<${p}ContextData> {`,
|
||||
` const ctx = useContext(${p}Ctx)`,
|
||||
` if (!ctx) throw new Error('use${p}Context requires <${p}Context>')`,
|
||||
' return ctx',
|
||||
'}',
|
||||
'',
|
||||
)
|
||||
|
||||
for (const fn of ctxFunctions) {
|
||||
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(` const state = use${p}Context()`)
|
||||
}
|
||||
lines.push(` return state.data?.${fn.name} ?? null`)
|
||||
lines.push('}')
|
||||
lines.push('')
|
||||
const fnPascal = pascalCase(fn.camelName)
|
||||
lines.push(
|
||||
`export function use${fnPascal}(): ${fn.outputType} | null {`,
|
||||
` return use${p}Context().data?.${fn.name} ?? null`,
|
||||
'}',
|
||||
'',
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// ── Mutation hooks (with loading/error) ──────────────────────────────
|
||||
// ── Mutation + plain function hooks ─────────────────────────────────
|
||||
|
||||
for (const fn of mutations) {
|
||||
for (const fn of [...mutations, ...plainFns]) {
|
||||
const p = pascalCase(fn.camelName)
|
||||
if (fn.hasInput) {
|
||||
lines.push(`export function use${p}() {`)
|
||||
lines.push(` return useMutation<Parameters<typeof call${p}>[0], Awaited<ReturnType<typeof call${p}>>>(call${p})`)
|
||||
lines.push('}')
|
||||
lines.push(
|
||||
`export function use${p}() {`,
|
||||
` return useMutation<Parameters<typeof call${p}>[0], Awaited<ReturnType<typeof call${p}>>>(call${p})`,
|
||||
'}',
|
||||
'',
|
||||
)
|
||||
} else {
|
||||
lines.push(`export function use${p}() {`)
|
||||
lines.push(` return useMutation<void, Awaited<ReturnType<typeof call${p}>>>(() => call${p}() as any)`)
|
||||
lines.push('}')
|
||||
lines.push(
|
||||
`export function use${p}() {`,
|
||||
` return useMutation<void, Awaited<ReturnType<typeof call${p}>>>(() => call${p}() as any)`,
|
||||
'}',
|
||||
'',
|
||||
)
|
||||
}
|
||||
lines.push('')
|
||||
}
|
||||
|
||||
// ── Plain function hooks ────────────────────────────────────────────
|
||||
// ── Root MizanContext provider ──────────────────────────────────────
|
||||
|
||||
for (const fn of plainFns) {
|
||||
const p = pascalCase(fn.camelName)
|
||||
if (fn.hasInput) {
|
||||
lines.push(`export function use${p}() {`)
|
||||
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 useMutation<void, Awaited<ReturnType<typeof call${p}>>>(() => call${p}() as any)`)
|
||||
lines.push('}')
|
||||
}
|
||||
lines.push('')
|
||||
lines.push(
|
||||
'// ── MizanContext root provider ──',
|
||||
'',
|
||||
'export interface MizanContextProps {',
|
||||
' /** Base URL for protocol endpoints. Defaults to "/api/mizan". */',
|
||||
' baseUrl?: string',
|
||||
' children: ReactNode',
|
||||
'}',
|
||||
'',
|
||||
'/**',
|
||||
" * Root provider — calls configure() once and mounts the global context (if defined).",
|
||||
' * Must wrap any component using Mizan-generated hooks.',
|
||||
' */',
|
||||
'export function MizanContext({ baseUrl, children }: MizanContextProps) {',
|
||||
' const configured = useRef(false)',
|
||||
' if (!configured.current) {',
|
||||
' if (baseUrl) configure({ baseUrl })',
|
||||
' configured.current = true',
|
||||
' }',
|
||||
)
|
||||
if (hasGlobal) {
|
||||
lines.push(' return <GlobalContextProvider>{children}</GlobalContextProvider>')
|
||||
} else {
|
||||
lines.push(' return <>{children}</>')
|
||||
}
|
||||
lines.push('}', '')
|
||||
|
||||
// ── Re-export runtime types ─────────────────────────────────────────
|
||||
// ── Escape hatch: useMizan ──────────────────────────────────────────
|
||||
|
||||
lines.push("export type { ContextState } from '@mizan/base'")
|
||||
lines.push("export { configure, initSession, MizanError } from '@mizan/base'")
|
||||
lines.push('')
|
||||
lines.push(
|
||||
'// ── Imperative escape hatch ──',
|
||||
'',
|
||||
'/**',
|
||||
' * Returns the imperative kernel API. For test harnesses or rare cases where',
|
||||
' * a typed generated hook does not fit. Most app code should use the typed hooks.',
|
||||
' */',
|
||||
'export function useMizan() {',
|
||||
' return { call: mizanCall, fetch: mizanFetch }',
|
||||
'}',
|
||||
'',
|
||||
)
|
||||
|
||||
// ── Re-exports ──────────────────────────────────────────────────────
|
||||
|
||||
lines.push(
|
||||
"export type { ContextState } from '@mizan/base'",
|
||||
"export { configure, initSession, MizanError } from '@mizan/base'",
|
||||
'',
|
||||
)
|
||||
|
||||
return lines.join('\n')
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user