Move codegen out of mizan-django: protocol/mizan-generate/
The codegen consumes a schema from any backend and emits typed client code for any frontend — it doesn't belong inside a backend adapter. That placement was historical sediment from when there was only a Django backend; it predates the AFI generalization. New top-level slot: `protocol/` for protocol-level tooling. Tree is now: backends/ server protocol adapters frontends/ client kernel + per-framework adapters cores/ shared language-level primitives protocol/ protocol-level tooling workers/ runtime workers / bridges Codegen moves to `protocol/mizan-generate/`. Same file layout under `generator/` (cli.mjs, lib/), preserved via git mv. Package metadata cleaned up: - name: "generate" (placeholder) → "mizan-generate" - description filled in - type: module (cli.mjs is .mjs ESM, was previously declared "commonjs") - bin entry added so `npx mizan-generate --config <config.mjs>` works once the package is published, instead of `node path/to/cli.mjs`. Path-reference fixups: - backends/mizan-django/README.md: `node path/to/...` → `npx mizan-generate` - backends/mizan-fastapi/README.md: same - ISSUES.md: file paths in three issue entries - CLAUDE.md: codegen description + Package Layout section refreshed (added protocol/, mizan-fastapi entry, mizan-python entry) - docs/AFI_ARCHITECTURE.md: Package Layout refreshed identically Verified codegen runs from new location: regenerated the FastAPI example harness's api/ output, identical to pre-move. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
298
protocol/mizan-generate/generator/lib/adapters/react.mjs
Normal file
298
protocol/mizan-generate/generator/lib/adapters/react.mjs
Normal file
@@ -0,0 +1,298 @@
|
||||
/**
|
||||
* React Stage 2 — Generates idiomatic React providers + hooks on top of the kernel.
|
||||
*
|
||||
* 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) {
|
||||
return str.split(/[.\-_]/).map(p => p.charAt(0).toUpperCase() + p.slice(1)).join('')
|
||||
}
|
||||
|
||||
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 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 = []
|
||||
|
||||
// ── Header + imports ─────────────────────────────────────────────────
|
||||
|
||||
lines.push(
|
||||
"'use client'",
|
||||
'',
|
||||
'// AUTO-GENERATED by mizan — do not edit',
|
||||
'',
|
||||
"import {",
|
||||
" createContext,",
|
||||
" useCallback,",
|
||||
" useContext,",
|
||||
" useEffect,",
|
||||
" useRef,",
|
||||
" useState,",
|
||||
" useSyncExternalStore,",
|
||||
" type ReactNode,",
|
||||
"} from 'react'",
|
||||
"import {",
|
||||
" configure,",
|
||||
" initSession,",
|
||||
" mizanCall,",
|
||||
" mizanFetch,",
|
||||
" MizanError,",
|
||||
" registerContext,",
|
||||
" type ContextState,",
|
||||
"} from '@mizan/base'",
|
||||
'',
|
||||
)
|
||||
|
||||
const stage1Imports = []
|
||||
for (const [ctxName] of Object.entries(contextGroups)) {
|
||||
const p = pascalCase(ctxName)
|
||||
stage1Imports.push(`fetch${p}Context`, `type ${p}ContextData`, `type ${p}ContextParams`)
|
||||
}
|
||||
for (const fn of [...mutations, ...plainFns]) {
|
||||
stage1Imports.push(`call${pascalCase(fn.camelName)}`)
|
||||
}
|
||||
if (stage1Imports.length > 0) {
|
||||
lines.push(`import { ${stage1Imports.join(', ')} } from './index'`, '')
|
||||
}
|
||||
|
||||
// ── Internal helper: subscribe to kernel state from a Provider ──────
|
||||
|
||||
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)',
|
||||
'}',
|
||||
'',
|
||||
)
|
||||
|
||||
// ── Internal helper: mutation wrapper ───────────────────────────────
|
||||
|
||||
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 }',
|
||||
'}',
|
||||
'',
|
||||
)
|
||||
|
||||
// ── Global context provider + hooks ─────────────────────────────────
|
||||
|
||||
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 paramKeys = Object.keys(ctxMeta.params || {})
|
||||
const hasParams = paramKeys.length > 0
|
||||
|
||||
lines.push(
|
||||
`// ── ${p} Context ──`,
|
||||
'',
|
||||
`const ${p}Ctx = createContext<ContextState<${p}ContextData> | null>(null)`,
|
||||
'',
|
||||
)
|
||||
|
||||
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 ${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(
|
||||
`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 fnPascal = pascalCase(fn.camelName)
|
||||
lines.push(
|
||||
`export function use${fnPascal}(): ${fn.outputType} | null {`,
|
||||
` return use${p}Context().data?.${fn.name} ?? null`,
|
||||
'}',
|
||||
'',
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// ── Mutation + plain function hooks ─────────────────────────────────
|
||||
|
||||
for (const fn of [...mutations, ...plainFns]) {
|
||||
const p = pascalCase(fn.camelName)
|
||||
if (fn.hasInput) {
|
||||
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}() {`,
|
||||
` return useMutation<void, Awaited<ReturnType<typeof call${p}>>>(() => call${p}() as any)`,
|
||||
'}',
|
||||
'',
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// ── Root MizanContext provider ──────────────────────────────────────
|
||||
|
||||
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('}', '')
|
||||
|
||||
// ── Escape hatch: useMizan ──────────────────────────────────────────
|
||||
|
||||
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')
|
||||
}
|
||||
78
protocol/mizan-generate/generator/lib/adapters/svelte.mjs
Normal file
78
protocol/mizan-generate/generator/lib/adapters/svelte.mjs
Normal file
@@ -0,0 +1,78 @@
|
||||
/**
|
||||
* Svelte Stage 2 — Generates stores from Stage 1 output.
|
||||
*
|
||||
* Subscribes to the kernel for state. Returns readable stores.
|
||||
*/
|
||||
|
||||
function pascalCase(str) {
|
||||
return str.split(/[.\-_]/).map(p => p.charAt(0).toUpperCase() + p.slice(1)).join('')
|
||||
}
|
||||
|
||||
export function generateSvelteAdapter(schema) {
|
||||
const functions = schema['x-mizan-functions'] || []
|
||||
const contextGroups = schema['x-mizan-contexts'] || {}
|
||||
const mutations = functions.filter(fn => !fn.isContext && !fn.isForm && fn.affects)
|
||||
const plainFns = functions.filter(fn => !fn.isContext && !fn.isForm && !fn.affects)
|
||||
|
||||
const lines = [
|
||||
'// AUTO-GENERATED by mizan — do not edit',
|
||||
'',
|
||||
"import { readable, type Readable } from 'svelte/store'",
|
||||
"import { registerContext, type ContextState } from '@mizan/base'",
|
||||
'',
|
||||
]
|
||||
|
||||
const stage1Imports = []
|
||||
for (const [ctxName] of Object.entries(contextGroups)) {
|
||||
const p = pascalCase(ctxName)
|
||||
stage1Imports.push(`fetch${p}Context`, `type ${p}ContextData`, `type ${p}ContextParams`)
|
||||
}
|
||||
for (const fn of [...mutations, ...plainFns]) {
|
||||
stage1Imports.push(`call${pascalCase(fn.camelName)}`)
|
||||
}
|
||||
if (stage1Imports.length > 0) {
|
||||
lines.push(`import { ${stage1Imports.join(', ')} } from '../index'`)
|
||||
lines.push('')
|
||||
}
|
||||
|
||||
for (const [ctxName, ctxMeta] of Object.entries(contextGroups)) {
|
||||
const p = pascalCase(ctxName)
|
||||
const ctxFunctions = functions.filter(fn => fn.isContext === ctxName)
|
||||
const paramEntries = Object.entries(ctxMeta.params || {})
|
||||
const paramsArg = paramEntries.length > 0 ? 'params' : '{} as any'
|
||||
|
||||
if (paramEntries.length > 0) {
|
||||
lines.push(`export function create${p}Context(params: ${p}ContextParams) {`)
|
||||
} else {
|
||||
lines.push(`export function create${p}Context() {`)
|
||||
}
|
||||
|
||||
// Use readable store backed by kernel subscription
|
||||
lines.push(` const store = readable<ContextState<${p}ContextData>>(`)
|
||||
lines.push(` { data: null, status: 'idle', error: null },`)
|
||||
lines.push(` (set) => {`)
|
||||
lines.push(` const handle = registerContext('${ctxName}', ${paramsArg}, () => fetch${p}Context(${paramsArg}))`)
|
||||
lines.push(` const unsub = handle.subscribe(() => set(handle.getState()))`)
|
||||
lines.push(` handle.refetch()`)
|
||||
lines.push(` return () => { unsub(); handle.unregister() }`)
|
||||
lines.push(` },`)
|
||||
lines.push(` )`)
|
||||
lines.push('')
|
||||
lines.push(` return store`)
|
||||
lines.push('}')
|
||||
lines.push('')
|
||||
}
|
||||
|
||||
// Re-export mutations as-is from Stage 1
|
||||
for (const fn of [...mutations, ...plainFns]) {
|
||||
const p = pascalCase(fn.camelName)
|
||||
lines.push(`export { call${p} } from '../index'`)
|
||||
}
|
||||
lines.push('')
|
||||
|
||||
lines.push("export type { ContextState } from '@mizan/base'")
|
||||
lines.push("export { configure, initSession, MizanError } from '@mizan/base'")
|
||||
lines.push('')
|
||||
|
||||
return lines.join('\n')
|
||||
}
|
||||
104
protocol/mizan-generate/generator/lib/adapters/vue.mjs
Normal file
104
protocol/mizan-generate/generator/lib/adapters/vue.mjs
Normal file
@@ -0,0 +1,104 @@
|
||||
/**
|
||||
* Vue Stage 2 — Generates composables from Stage 1 output.
|
||||
*
|
||||
* Subscribes to the kernel for state. Vue reactivity wraps kernel notifications.
|
||||
*/
|
||||
|
||||
function pascalCase(str) {
|
||||
return str.split(/[.\-_]/).map(p => p.charAt(0).toUpperCase() + p.slice(1)).join('')
|
||||
}
|
||||
|
||||
export function generateVueAdapter(schema) {
|
||||
const functions = schema['x-mizan-functions'] || []
|
||||
const contextGroups = schema['x-mizan-contexts'] || {}
|
||||
const mutations = functions.filter(fn => !fn.isContext && !fn.isForm && fn.affects)
|
||||
const plainFns = functions.filter(fn => !fn.isContext && !fn.isForm && !fn.affects)
|
||||
|
||||
const lines = [
|
||||
'// AUTO-GENERATED by mizan — do not edit',
|
||||
'',
|
||||
"import { ref, computed, onMounted, onUnmounted, onServerPrefetch, type ComputedRef } from 'vue'",
|
||||
"import { registerContext, type ContextState } from '@mizan/base'",
|
||||
'',
|
||||
]
|
||||
|
||||
const stage1Imports = []
|
||||
for (const [ctxName] of Object.entries(contextGroups)) {
|
||||
const p = pascalCase(ctxName)
|
||||
stage1Imports.push(`fetch${p}Context`, `type ${p}ContextData`, `type ${p}ContextParams`)
|
||||
}
|
||||
for (const fn of [...mutations, ...plainFns]) {
|
||||
stage1Imports.push(`call${pascalCase(fn.camelName)}`)
|
||||
}
|
||||
if (stage1Imports.length > 0) {
|
||||
lines.push(`import { ${stage1Imports.join(', ')} } from '../index'`)
|
||||
lines.push('')
|
||||
}
|
||||
|
||||
for (const [ctxName, ctxMeta] of Object.entries(contextGroups)) {
|
||||
const p = pascalCase(ctxName)
|
||||
const ctxFunctions = functions.filter(fn => fn.isContext === ctxName)
|
||||
const paramEntries = Object.entries(ctxMeta.params || {})
|
||||
const paramsArg = paramEntries.length > 0 ? 'params' : '{} as any'
|
||||
|
||||
if (paramEntries.length > 0) {
|
||||
lines.push(`export function use${p}Context(params: ${p}ContextParams) {`)
|
||||
} else {
|
||||
lines.push(`export function use${p}Context() {`)
|
||||
}
|
||||
|
||||
lines.push(` const state = ref<ContextState<${p}ContextData>>({ data: null, status: 'idle', error: null })`)
|
||||
lines.push(` let handle: ReturnType<typeof registerContext> | null = null`)
|
||||
lines.push('')
|
||||
lines.push(` onMounted(() => {`)
|
||||
lines.push(` handle = registerContext('${ctxName}', ${paramsArg}, () => fetch${p}Context(${paramsArg}))`)
|
||||
lines.push(` handle.subscribe(() => { state.value = handle!.getState() })`)
|
||||
lines.push(` handle.refetch()`)
|
||||
lines.push(` })`)
|
||||
lines.push('')
|
||||
lines.push(` onServerPrefetch(async () => {`)
|
||||
lines.push(` handle = registerContext('${ctxName}', ${paramsArg}, () => fetch${p}Context(${paramsArg}))`)
|
||||
lines.push(` await handle.refetch()`)
|
||||
lines.push(` state.value = handle.getState()`)
|
||||
lines.push(` })`)
|
||||
lines.push('')
|
||||
lines.push(` onUnmounted(() => { handle?.unregister() })`)
|
||||
lines.push('')
|
||||
lines.push(` return {`)
|
||||
lines.push(` state,`)
|
||||
for (const fn of ctxFunctions) {
|
||||
lines.push(` ${fn.camelName}: computed(() => state.value.data?.${fn.name} ?? null) as ComputedRef<${fn.outputType} | null>,`)
|
||||
}
|
||||
lines.push(` loading: computed(() => state.value.status === 'loading'),`)
|
||||
lines.push(` error: computed(() => state.value.error),`)
|
||||
lines.push(` }`)
|
||||
lines.push('}')
|
||||
lines.push('')
|
||||
}
|
||||
|
||||
for (const fn of [...mutations, ...plainFns]) {
|
||||
const p = pascalCase(fn.camelName)
|
||||
lines.push(`export function use${p}() {`)
|
||||
lines.push(` const isPending = ref(false)`)
|
||||
lines.push(` const error = ref<Error | null>(null)`)
|
||||
if (fn.hasInput) {
|
||||
lines.push(` async function mutate(args: Parameters<typeof call${p}>[0]) {`)
|
||||
} else {
|
||||
lines.push(` async function mutate() {`)
|
||||
}
|
||||
lines.push(` isPending.value = true; error.value = null`)
|
||||
lines.push(` try { return await call${p}(${fn.hasInput ? 'args' : ''}) }`)
|
||||
lines.push(` catch (e) { error.value = e as Error; throw e }`)
|
||||
lines.push(` finally { isPending.value = false }`)
|
||||
lines.push(` }`)
|
||||
lines.push(` return { mutate, isPending, error }`)
|
||||
lines.push('}')
|
||||
lines.push('')
|
||||
}
|
||||
|
||||
lines.push("export type { ContextState } from '@mizan/base'")
|
||||
lines.push("export { configure, initSession, MizanError } from '@mizan/base'")
|
||||
lines.push('')
|
||||
|
||||
return lines.join('\n')
|
||||
}
|
||||
Reference in New Issue
Block a user