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:
@@ -148,6 +148,18 @@ async function generate(config, options = {}) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Append Stage 2 re-exports to index.ts so `import { useEcho, MizanContext } from './api'` works
|
||||||
|
const adapterExports = targets
|
||||||
|
.map(t => ({ react: 'react', vue: 'vue', svelte: 'svelte' })[t])
|
||||||
|
.filter(Boolean)
|
||||||
|
.map(name => `export * from './${name}'`)
|
||||||
|
.join('\n')
|
||||||
|
if (adapterExports) {
|
||||||
|
const indexPath = path.join(fullOutputDir, 'index.ts')
|
||||||
|
const existing = await fs.readFile(indexPath, 'utf8')
|
||||||
|
await writeOutput(indexPath, `${existing}\n// Stage 2 framework adapter\n${adapterExports}\n`)
|
||||||
|
}
|
||||||
|
|
||||||
// Schema JSON
|
// Schema JSON
|
||||||
await writeOutput(
|
await writeOutput(
|
||||||
path.join(fullOutputDir, 'schema.json'),
|
path.join(fullOutputDir, 'schema.json'),
|
||||||
|
|||||||
@@ -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 (@mizan/base) owns data, status, error. This adapter wraps each
|
||||||
* The kernel owns data, status, and error. React just renders.
|
* 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) {
|
function pascalCase(str) {
|
||||||
@@ -13,21 +28,42 @@ export function generateReactAdapter(schema) {
|
|||||||
const functions = schema['x-mizan-functions'] || []
|
const functions = schema['x-mizan-functions'] || []
|
||||||
const contextGroups = schema['x-mizan-contexts'] || {}
|
const contextGroups = schema['x-mizan-contexts'] || {}
|
||||||
const namedContexts = Object.entries(contextGroups).filter(([n]) => n !== 'global')
|
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 mutations = functions.filter(fn => !fn.isContext && !fn.isForm && fn.affects)
|
||||||
const plainFns = 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'",
|
"'use client'",
|
||||||
'',
|
'',
|
||||||
'// AUTO-GENERATED by mizan — do not edit',
|
'// AUTO-GENERATED by mizan — do not edit',
|
||||||
'',
|
'',
|
||||||
"import { createContext, useContext, useState, useEffect, useCallback, useRef, useSyncExternalStore, type ReactNode } from 'react'",
|
"import {",
|
||||||
"import { registerContext, mizanFetch, mizanCall, type ContextState } from '@mizan/base'",
|
" 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 = []
|
const stage1Imports = []
|
||||||
for (const [ctxName] of Object.entries(contextGroups)) {
|
for (const [ctxName] of Object.entries(contextGroups)) {
|
||||||
const p = pascalCase(ctxName)
|
const p = pascalCase(ctxName)
|
||||||
@@ -37,144 +73,226 @@ export function generateReactAdapter(schema) {
|
|||||||
stage1Imports.push(`call${pascalCase(fn.camelName)}`)
|
stage1Imports.push(`call${pascalCase(fn.camelName)}`)
|
||||||
}
|
}
|
||||||
if (stage1Imports.length > 0) {
|
if (stage1Imports.length > 0) {
|
||||||
lines.push(`import { ${stage1Imports.join(', ')} } from '../index'`)
|
lines.push(`import { ${stage1Imports.join(', ')} } from './index'`, '')
|
||||||
lines.push('')
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── 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(
|
||||||
lines.push('function useContextState<T>(')
|
'// Internal — runs inside a Provider, registers with the kernel exactly once.',
|
||||||
lines.push(' name: string,')
|
'function useContextSubscription<T>(',
|
||||||
lines.push(' params: Record<string, any>,')
|
' name: string,',
|
||||||
lines.push(' fetchFn: () => Promise<T>,')
|
' params: Record<string, any>,',
|
||||||
lines.push(' initialData?: T,')
|
' fetchFn: () => Promise<T>,',
|
||||||
lines.push('): ContextState<T> {')
|
' initialData?: T,',
|
||||||
lines.push(' const ref = useRef<ReturnType<typeof registerContext> | null>(null)')
|
'): ContextState<T> {',
|
||||||
lines.push('')
|
' const ref = useRef<ReturnType<typeof registerContext> | null>(null)',
|
||||||
lines.push(' if (!ref.current) {')
|
' if (!ref.current) {',
|
||||||
lines.push(' ref.current = registerContext(name, params, fetchFn, initialData)')
|
' ref.current = registerContext(name, params, fetchFn, initialData)',
|
||||||
lines.push(' }')
|
' }',
|
||||||
lines.push('')
|
' const handle = ref.current',
|
||||||
lines.push(' const handle = ref.current')
|
'',
|
||||||
lines.push('')
|
' useEffect(() => {',
|
||||||
lines.push(' // Fetch on mount if no data')
|
" if (handle.getState().status === 'idle') handle.refetch()",
|
||||||
lines.push(' useEffect(() => {')
|
' return () => handle.unregister()',
|
||||||
lines.push(" if (handle.getState().status === 'idle') handle.refetch()")
|
' }, [handle])',
|
||||||
lines.push(' return () => handle.unregister()')
|
'',
|
||||||
lines.push(' }, [handle])')
|
' return useSyncExternalStore(handle.subscribe, handle.getState, handle.getState)',
|
||||||
lines.push('')
|
'}',
|
||||||
lines.push(' return useSyncExternalStore(')
|
'',
|
||||||
lines.push(' handle.subscribe,')
|
)
|
||||||
lines.push(' handle.getState,')
|
|
||||||
lines.push(' handle.getState,')
|
|
||||||
lines.push(' )')
|
|
||||||
lines.push('}')
|
|
||||||
lines.push('')
|
|
||||||
|
|
||||||
// ── Mutation hook helper ────────────────────────────────────────────
|
// ── Internal helper: mutation wrapper ───────────────────────────────
|
||||||
|
|
||||||
lines.push('// Mutation hook with loading/error state')
|
lines.push(
|
||||||
lines.push('function useMutation<TArgs, TResult>(')
|
'// Internal — wraps an imperative call() with isPending / error state.',
|
||||||
lines.push(' callFn: (args: TArgs) => Promise<TResult>,')
|
'interface MutationHook<TArgs, TResult> {',
|
||||||
lines.push('): { mutate: (args: TArgs) => Promise<TResult>; isPending: boolean; error: Error | null } {')
|
' mutate: (args: TArgs) => Promise<TResult>',
|
||||||
lines.push(' const [isPending, setIsPending] = useState(false)')
|
' isPending: boolean',
|
||||||
lines.push(' const [error, setError] = useState<Error | null>(null)')
|
' error: Error | null',
|
||||||
lines.push('')
|
'}',
|
||||||
lines.push(' const mutate = useCallback(async (args: TArgs) => {')
|
'',
|
||||||
lines.push(' setIsPending(true)')
|
'function useMutation<TArgs, TResult>(',
|
||||||
lines.push(' setError(null)')
|
' callFn: (args: TArgs) => Promise<TResult>,',
|
||||||
lines.push(' try {')
|
'): MutationHook<TArgs, TResult> {',
|
||||||
lines.push(' const result = await callFn(args)')
|
' const [isPending, setIsPending] = useState(false)',
|
||||||
lines.push(' return result')
|
' const [error, setError] = useState<Error | null>(null)',
|
||||||
lines.push(' } catch (e) {')
|
'',
|
||||||
lines.push(' setError(e as Error)')
|
' const mutate = useCallback(async (args: TArgs) => {',
|
||||||
lines.push(' throw e')
|
' setIsPending(true)',
|
||||||
lines.push(' } finally {')
|
' setError(null)',
|
||||||
lines.push(' setIsPending(false)')
|
' try {',
|
||||||
lines.push(' }')
|
' return await callFn(args)',
|
||||||
lines.push(' }, [callFn])')
|
' } catch (e) {',
|
||||||
lines.push('')
|
' setError(e as Error)',
|
||||||
lines.push(' return { mutate, isPending, error }')
|
' throw e',
|
||||||
lines.push('}')
|
' } finally {',
|
||||||
lines.push('')
|
' 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 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 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 (hasParams) {
|
||||||
if (paramEntries.length > 0) {
|
lines.push(
|
||||||
lines.push(`export function use${p}Context(params: ${p}ContextParams): ContextState<${p}ContextData> {`)
|
`export function ${p}Context({ children, ...params }: ${p}ContextParams & { children: ReactNode }) {`,
|
||||||
lines.push(` const ssrData = typeof window !== 'undefined' ? (window as any).__MIZAN_SSR_DATA__ : null`)
|
` const state = useContextSubscription('${ctxName}', params, () => fetch${p}Context(params))`,
|
||||||
lines.push(` return useContextState('${ctxName}', params, () => fetch${p}Context(params), ssrData)`)
|
` return <${p}Ctx.Provider value={state}>{children}</${p}Ctx.Provider>`,
|
||||||
|
'}',
|
||||||
|
)
|
||||||
} else {
|
} else {
|
||||||
lines.push(`export function use${p}Context(): ContextState<${p}ContextData> {`)
|
lines.push(
|
||||||
lines.push(` const ssrData = typeof window !== 'undefined' ? (window as any).__MIZAN_SSR_DATA__ : null`)
|
`export function ${p}Context({ children }: { children: ReactNode }) {`,
|
||||||
lines.push(` return useContextState('${ctxName}', {}, () => fetch${p}Context({} as any), ssrData)`)
|
` const state = useContextSubscription('${ctxName}', {}, () => fetch${p}Context({} as any))`,
|
||||||
|
` return <${p}Ctx.Provider value={state}>{children}</${p}Ctx.Provider>`,
|
||||||
|
'}',
|
||||||
|
)
|
||||||
}
|
}
|
||||||
lines.push('}')
|
|
||||||
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) {
|
for (const fn of ctxFunctions) {
|
||||||
const hookPascal = pascalCase(fn.camelName)
|
const fnPascal = pascalCase(fn.camelName)
|
||||||
if (paramEntries.length > 0) {
|
lines.push(
|
||||||
lines.push(`export function use${hookPascal}(params: ${p}ContextParams): ${fn.outputType} | null {`)
|
`export function use${fnPascal}(): ${fn.outputType} | null {`,
|
||||||
lines.push(` const state = use${p}Context(params)`)
|
` return use${p}Context().data?.${fn.name} ?? null`,
|
||||||
} else {
|
'}',
|
||||||
lines.push(`export function use${hookPascal}(): ${fn.outputType} | null {`)
|
'',
|
||||||
lines.push(` const state = use${p}Context()`)
|
)
|
||||||
}
|
|
||||||
lines.push(` return state.data?.${fn.name} ?? null`)
|
|
||||||
lines.push('}')
|
|
||||||
lines.push('')
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Mutation hooks (with loading/error) ──────────────────────────────
|
// ── Mutation + plain function hooks ─────────────────────────────────
|
||||||
|
|
||||||
for (const fn of mutations) {
|
for (const fn of [...mutations, ...plainFns]) {
|
||||||
const p = pascalCase(fn.camelName)
|
const p = pascalCase(fn.camelName)
|
||||||
if (fn.hasInput) {
|
if (fn.hasInput) {
|
||||||
lines.push(`export function use${p}() {`)
|
lines.push(
|
||||||
lines.push(` return useMutation<Parameters<typeof call${p}>[0], Awaited<ReturnType<typeof call${p}>>>(call${p})`)
|
`export function use${p}() {`,
|
||||||
lines.push('}')
|
` return useMutation<Parameters<typeof call${p}>[0], Awaited<ReturnType<typeof call${p}>>>(call${p})`,
|
||||||
|
'}',
|
||||||
|
'',
|
||||||
|
)
|
||||||
} else {
|
} else {
|
||||||
lines.push(`export function use${p}() {`)
|
lines.push(
|
||||||
lines.push(` return useMutation<void, Awaited<ReturnType<typeof call${p}>>>(() => call${p}() as any)`)
|
`export function use${p}() {`,
|
||||||
lines.push('}')
|
` 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) {
|
lines.push(
|
||||||
const p = pascalCase(fn.camelName)
|
'// ── MizanContext root provider ──',
|
||||||
if (fn.hasInput) {
|
'',
|
||||||
lines.push(`export function use${p}() {`)
|
'export interface MizanContextProps {',
|
||||||
lines.push(` return useMutation<Parameters<typeof call${p}>[0], Awaited<ReturnType<typeof call${p}>>>(call${p})`)
|
' /** Base URL for protocol endpoints. Defaults to "/api/mizan". */',
|
||||||
lines.push('}')
|
' 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 {
|
} else {
|
||||||
lines.push(`export function use${p}() {`)
|
lines.push(' return <>{children}</>')
|
||||||
lines.push(` return useMutation<void, Awaited<ReturnType<typeof call${p}>>>(() => call${p}() as any)`)
|
|
||||||
lines.push('}')
|
|
||||||
}
|
|
||||||
lines.push('')
|
|
||||||
}
|
}
|
||||||
|
lines.push('}', '')
|
||||||
|
|
||||||
// ── Re-export runtime types ─────────────────────────────────────────
|
// ── Escape hatch: useMizan ──────────────────────────────────────────
|
||||||
|
|
||||||
lines.push("export type { ContextState } from '@mizan/base'")
|
lines.push(
|
||||||
lines.push("export { configure, initSession, MizanError } from '@mizan/base'")
|
'// ── Imperative escape hatch ──',
|
||||||
lines.push('')
|
'',
|
||||||
|
'/**',
|
||||||
|
' * 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')
|
return lines.join('\n')
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ from pydantic import BaseModel
|
|||||||
|
|
||||||
from mizan.client import ServerFunction, client
|
from mizan.client import ServerFunction, client
|
||||||
from mizan.channels import ReactChannel
|
from mizan.channels import ReactChannel
|
||||||
from mizan.setup.registry import register, register_form, register_as
|
from mizan.setup import register, register_form, register_as
|
||||||
from mizan.channels import register as register_channel
|
from mizan.channels import register as register_channel
|
||||||
from mizan.forms import mizanFormMixin, mizanFormMeta
|
from mizan.forms import mizanFormMixin, mizanFormMeta
|
||||||
from mizan.jwt import jwt_obtain, jwt_refresh
|
from mizan.jwt import jwt_obtain, jwt_refresh
|
||||||
|
|||||||
@@ -18,5 +18,5 @@ export default {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|
||||||
output: 'src/api/generated.ts',
|
output: 'src/api',
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,6 +7,7 @@
|
|||||||
"dev": "vite --port 5174"
|
"dev": "vite --port 5174"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"@mizan/base": "file:../../../frontends/mizan-base",
|
||||||
"@rythazhur/mizan": "file:../../../frontends/mizan-react",
|
"@rythazhur/mizan": "file:../../../frontends/mizan-react",
|
||||||
"react": "^19.0.0",
|
"react": "^19.0.0",
|
||||||
"react-dom": "^19.0.0",
|
"react-dom": "^19.0.0",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
// AUTO-GENERATED by mizan — do not edit
|
// AUTO-GENERATED by mizan — do not edit
|
||||||
|
|
||||||
import { mizanFetch } from '@mizan/runtime'
|
import { mizanFetch } from '@mizan/base'
|
||||||
|
|
||||||
import type { currentUserOutput } from '../types'
|
import type { currentUserOutput } from '../types'
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
// AUTO-GENERATED by mizan — do not edit
|
// AUTO-GENERATED by mizan — do not edit
|
||||||
|
|
||||||
import { mizanFetch } from '@mizan/runtime'
|
import { mizanFetch } from '@mizan/base'
|
||||||
|
|
||||||
import type { greetOutput } from '../types'
|
import type { greetOutput } from '../types'
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
// AUTO-GENERATED by mizan — do not edit
|
// AUTO-GENERATED by mizan — do not edit
|
||||||
|
|
||||||
import { mizanCall } from '@mizan/runtime'
|
import { mizanCall } from '@mizan/base'
|
||||||
|
|
||||||
import type { addInput, addOutput } from '../types'
|
import type { addInput, addOutput } from '../types'
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
// AUTO-GENERATED by mizan — do not edit
|
// AUTO-GENERATED by mizan — do not edit
|
||||||
|
|
||||||
import { mizanCall } from '@mizan/runtime'
|
import { mizanCall } from '@mizan/base'
|
||||||
|
|
||||||
import type { buggyFnOutput } from '../types'
|
import type { buggyFnOutput } from '../types'
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
// AUTO-GENERATED by mizan — do not edit
|
// AUTO-GENERATED by mizan — do not edit
|
||||||
|
|
||||||
import { mizanCall } from '@mizan/runtime'
|
import { mizanCall } from '@mizan/base'
|
||||||
|
|
||||||
import type { echoInput, echoOutput } from '../types'
|
import type { echoInput, echoOutput } from '../types'
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
// AUTO-GENERATED by mizan — do not edit
|
// AUTO-GENERATED by mizan — do not edit
|
||||||
|
|
||||||
import { mizanCall } from '@mizan/runtime'
|
import { mizanCall } from '@mizan/base'
|
||||||
|
|
||||||
import type { httpOnlyEchoInput, httpOnlyEchoOutput } from '../types'
|
import type { httpOnlyEchoInput, httpOnlyEchoOutput } from '../types'
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
// AUTO-GENERATED by mizan — do not edit
|
// AUTO-GENERATED by mizan — do not edit
|
||||||
|
|
||||||
import { mizanCall } from '@mizan/runtime'
|
import { mizanCall } from '@mizan/base'
|
||||||
|
|
||||||
import type { jwtObtainOutput } from '../types'
|
import type { jwtObtainOutput } from '../types'
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
// AUTO-GENERATED by mizan — do not edit
|
// AUTO-GENERATED by mizan — do not edit
|
||||||
|
|
||||||
import { mizanCall } from '@mizan/runtime'
|
import { mizanCall } from '@mizan/base'
|
||||||
|
|
||||||
import type { jwtRefreshInput, jwtRefreshOutput } from '../types'
|
import type { jwtRefreshInput, jwtRefreshOutput } from '../types'
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
// AUTO-GENERATED by mizan — do not edit
|
// AUTO-GENERATED by mizan — do not edit
|
||||||
|
|
||||||
import { mizanCall } from '@mizan/runtime'
|
import { mizanCall } from '@mizan/base'
|
||||||
|
|
||||||
import type { multiplyInput, multiplyOutput } from '../types'
|
import type { multiplyInput, multiplyOutput } from '../types'
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
// AUTO-GENERATED by mizan — do not edit
|
// AUTO-GENERATED by mizan — do not edit
|
||||||
|
|
||||||
import { mizanCall } from '@mizan/runtime'
|
import { mizanCall } from '@mizan/base'
|
||||||
|
|
||||||
import type { notImplementedFnOutput } from '../types'
|
import type { notImplementedFnOutput } from '../types'
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
// AUTO-GENERATED by mizan — do not edit
|
// AUTO-GENERATED by mizan — do not edit
|
||||||
|
|
||||||
import { mizanCall } from '@mizan/runtime'
|
import { mizanCall } from '@mizan/base'
|
||||||
|
|
||||||
import type { permissionCheckFnInput, permissionCheckFnOutput } from '../types'
|
import type { permissionCheckFnInput, permissionCheckFnOutput } from '../types'
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
// AUTO-GENERATED by mizan — do not edit
|
// AUTO-GENERATED by mizan — do not edit
|
||||||
|
|
||||||
import { mizanCall } from '@mizan/runtime'
|
import { mizanCall } from '@mizan/base'
|
||||||
|
|
||||||
import type { staffOnlyOutput } from '../types'
|
import type { staffOnlyOutput } from '../types'
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
// AUTO-GENERATED by mizan — do not edit
|
// AUTO-GENERATED by mizan — do not edit
|
||||||
|
|
||||||
import { mizanCall } from '@mizan/runtime'
|
import { mizanCall } from '@mizan/base'
|
||||||
|
|
||||||
import type { superuserOnlyOutput } from '../types'
|
import type { superuserOnlyOutput } from '../types'
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
// AUTO-GENERATED by mizan — do not edit
|
// AUTO-GENERATED by mizan — do not edit
|
||||||
|
|
||||||
import { mizanCall } from '@mizan/runtime'
|
import { mizanCall } from '@mizan/base'
|
||||||
|
|
||||||
import type { verifiedOnlyOutput } from '../types'
|
import type { verifiedOnlyOutput } from '../types'
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
// AUTO-GENERATED by mizan — do not edit
|
// AUTO-GENERATED by mizan — do not edit
|
||||||
|
|
||||||
import { mizanCall } from '@mizan/runtime'
|
import { mizanCall } from '@mizan/base'
|
||||||
|
|
||||||
import type { whoamiOutput } from '../types'
|
import type { whoamiOutput } from '../types'
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
// AUTO-GENERATED by mizan — do not edit
|
// AUTO-GENERATED by mizan — do not edit
|
||||||
|
|
||||||
import { mizanCall } from '@mizan/runtime'
|
import { mizanCall } from '@mizan/base'
|
||||||
|
|
||||||
import type { wsWhoamiOutput } from '../types'
|
import type { wsWhoamiOutput } from '../types'
|
||||||
|
|
||||||
|
|||||||
@@ -19,3 +19,6 @@ export { callPermissionCheckFn } from './functions/permissionCheckFn'
|
|||||||
export { callWsWhoami } from './functions/wsWhoami'
|
export { callWsWhoami } from './functions/wsWhoami'
|
||||||
export { callJwtObtain } from './functions/jwtObtain'
|
export { callJwtObtain } from './functions/jwtObtain'
|
||||||
export { callJwtRefresh } from './functions/jwtRefresh'
|
export { callJwtRefresh } from './functions/jwtRefresh'
|
||||||
|
|
||||||
|
// Stage 2 framework adapter
|
||||||
|
export * from './react'
|
||||||
|
|||||||
@@ -2,43 +2,59 @@
|
|||||||
|
|
||||||
// AUTO-GENERATED by mizan — do not edit
|
// AUTO-GENERATED by mizan — do not edit
|
||||||
|
|
||||||
import { createContext, useContext, useState, useEffect, useCallback, useRef, useSyncExternalStore, type ReactNode } from 'react'
|
import {
|
||||||
import { registerContext, mizanFetch, mizanCall, type ContextState } from '@mizan/runtime'
|
createContext,
|
||||||
|
useCallback,
|
||||||
|
useContext,
|
||||||
|
useEffect,
|
||||||
|
useRef,
|
||||||
|
useState,
|
||||||
|
useSyncExternalStore,
|
||||||
|
type ReactNode,
|
||||||
|
} from 'react'
|
||||||
|
import {
|
||||||
|
configure,
|
||||||
|
initSession,
|
||||||
|
mizanCall,
|
||||||
|
mizanFetch,
|
||||||
|
MizanError,
|
||||||
|
registerContext,
|
||||||
|
type ContextState,
|
||||||
|
} from '@mizan/base'
|
||||||
|
|
||||||
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'
|
||||||
|
|
||||||
// Subscribe to kernel state via useSyncExternalStore
|
// Internal — runs inside a Provider, registers with the kernel exactly once.
|
||||||
function useContextState<T>(
|
function useContextSubscription<T>(
|
||||||
name: string,
|
name: string,
|
||||||
params: Record<string, any>,
|
params: Record<string, any>,
|
||||||
fetchFn: () => Promise<T>,
|
fetchFn: () => Promise<T>,
|
||||||
initialData?: T,
|
initialData?: T,
|
||||||
): ContextState<T> {
|
): ContextState<T> {
|
||||||
const ref = useRef<ReturnType<typeof registerContext> | null>(null)
|
const ref = useRef<ReturnType<typeof registerContext> | null>(null)
|
||||||
|
|
||||||
if (!ref.current) {
|
if (!ref.current) {
|
||||||
ref.current = registerContext(name, params, fetchFn, initialData)
|
ref.current = registerContext(name, params, fetchFn, initialData)
|
||||||
}
|
}
|
||||||
|
|
||||||
const handle = ref.current
|
const handle = ref.current
|
||||||
|
|
||||||
// Fetch on mount if no data
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (handle.getState().status === 'idle') handle.refetch()
|
if (handle.getState().status === 'idle') handle.refetch()
|
||||||
return () => handle.unregister()
|
return () => handle.unregister()
|
||||||
}, [handle])
|
}, [handle])
|
||||||
|
|
||||||
return useSyncExternalStore(
|
return useSyncExternalStore(handle.subscribe, handle.getState, handle.getState)
|
||||||
handle.subscribe,
|
}
|
||||||
handle.getState,
|
|
||||||
handle.getState,
|
// Internal — wraps an imperative call() with isPending / error state.
|
||||||
)
|
interface MutationHook<TArgs, TResult> {
|
||||||
|
mutate: (args: TArgs) => Promise<TResult>
|
||||||
|
isPending: boolean
|
||||||
|
error: Error | null
|
||||||
}
|
}
|
||||||
|
|
||||||
// Mutation hook with loading/error state
|
|
||||||
function useMutation<TArgs, TResult>(
|
function useMutation<TArgs, TResult>(
|
||||||
callFn: (args: TArgs) => Promise<TResult>,
|
callFn: (args: TArgs) => Promise<TResult>,
|
||||||
): { mutate: (args: TArgs) => Promise<TResult>; isPending: boolean; error: Error | null } {
|
): MutationHook<TArgs, TResult> {
|
||||||
const [isPending, setIsPending] = useState(false)
|
const [isPending, setIsPending] = useState(false)
|
||||||
const [error, setError] = useState<Error | null>(null)
|
const [error, setError] = useState<Error | null>(null)
|
||||||
|
|
||||||
@@ -46,8 +62,7 @@ function useMutation<TArgs, TResult>(
|
|||||||
setIsPending(true)
|
setIsPending(true)
|
||||||
setError(null)
|
setError(null)
|
||||||
try {
|
try {
|
||||||
const result = await callFn(args)
|
return await callFn(args)
|
||||||
return result
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
setError(e as Error)
|
setError(e as Error)
|
||||||
throw e
|
throw e
|
||||||
@@ -61,26 +76,41 @@ function useMutation<TArgs, TResult>(
|
|||||||
|
|
||||||
// ── Global Context ──
|
// ── 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> {
|
export function useGlobalContext(): ContextState<GlobalContextData> {
|
||||||
const ssrData = typeof window !== 'undefined' ? (window as any).__MIZAN_SSR_DATA__ : null
|
const ctx = useContext(GlobalCtx)
|
||||||
return useContextState('global', {}, () => fetchGlobalContext({} as any), ssrData)
|
if (!ctx) throw new Error('useGlobalContext requires <MizanContext> or <GlobalContextProvider>')
|
||||||
|
return ctx
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useCurrentUser(): currentUserOutput | null {
|
export function useCurrentUser(): currentUserOutput | null {
|
||||||
const state = useGlobalContext()
|
return useGlobalContext().data?.current_user ?? null
|
||||||
return state.data?.current_user ?? null
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Local Context ──
|
// ── Local Context ──
|
||||||
|
|
||||||
export function useLocalContext(params: LocalContextParams): ContextState<LocalContextData> {
|
const LocalCtx = createContext<ContextState<LocalContextData> | null>(null)
|
||||||
const ssrData = typeof window !== 'undefined' ? (window as any).__MIZAN_SSR_DATA__ : null
|
|
||||||
return useContextState('local', params, () => fetchLocalContext(params), ssrData)
|
export function LocalContext({ children, ...params }: LocalContextParams & { children: ReactNode }) {
|
||||||
|
const state = useContextSubscription('local', params, () => fetchLocalContext(params))
|
||||||
|
return <LocalCtx.Provider value={state}>{children}</LocalCtx.Provider>
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useGreet(params: LocalContextParams): greetOutput | null {
|
export function useLocalContext(): ContextState<LocalContextData> {
|
||||||
const state = useLocalContext(params)
|
const ctx = useContext(LocalCtx)
|
||||||
return state.data?.greet ?? null
|
if (!ctx) throw new Error('useLocalContext requires <LocalContext>')
|
||||||
|
return ctx
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useGreet(): greetOutput | null {
|
||||||
|
return useLocalContext().data?.greet ?? null
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useEcho() {
|
export function useEcho() {
|
||||||
@@ -139,5 +169,36 @@ export function useJwtRefresh() {
|
|||||||
return useMutation<Parameters<typeof callJwtRefresh>[0], Awaited<ReturnType<typeof callJwtRefresh>>>(callJwtRefresh)
|
return useMutation<Parameters<typeof callJwtRefresh>[0], Awaited<ReturnType<typeof callJwtRefresh>>>(callJwtRefresh)
|
||||||
}
|
}
|
||||||
|
|
||||||
export type { ContextState } from '@mizan/runtime'
|
// ── MizanContext root provider ──
|
||||||
export { configure, initSession, MizanError } from '@mizan/runtime'
|
|
||||||
|
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
|
||||||
|
}
|
||||||
|
return <GlobalContextProvider>{children}</GlobalContextProvider>
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── 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 }
|
||||||
|
}
|
||||||
|
|
||||||
|
export type { ContextState } from '@mizan/base'
|
||||||
|
export { configure, initSession, MizanError } from '@mizan/base'
|
||||||
|
|||||||
@@ -1,52 +0,0 @@
|
|||||||
// AUTO-GENERATED by mizan — do not edit
|
|
||||||
|
|
||||||
import { readable, type Readable } from 'svelte/store'
|
|
||||||
import { registerContext, type ContextState } from '@mizan/runtime'
|
|
||||||
|
|
||||||
import { fetchGlobalContext, type GlobalContextData, type GlobalContextParams, fetchLocalContext, type LocalContextData, type LocalContextParams, callEcho, callAdd, callWhoami, callHttpOnlyEcho, callStaffOnly, callSuperuserOnly, callVerifiedOnly, callMultiply, callNotImplementedFn, callBuggyFn, callPermissionCheckFn, callWsWhoami, callJwtObtain, callJwtRefresh } from '../index'
|
|
||||||
|
|
||||||
export function createGlobalContext() {
|
|
||||||
const store = readable<ContextState<GlobalContextData>>(
|
|
||||||
{ data: null, status: 'idle', error: null },
|
|
||||||
(set) => {
|
|
||||||
const handle = registerContext('global', {} as any, () => fetchGlobalContext({} as any))
|
|
||||||
const unsub = handle.subscribe(() => set(handle.getState()))
|
|
||||||
handle.refetch()
|
|
||||||
return () => { unsub(); handle.unregister() }
|
|
||||||
},
|
|
||||||
)
|
|
||||||
|
|
||||||
return store
|
|
||||||
}
|
|
||||||
|
|
||||||
export function createLocalContext(params: LocalContextParams) {
|
|
||||||
const store = readable<ContextState<LocalContextData>>(
|
|
||||||
{ data: null, status: 'idle', error: null },
|
|
||||||
(set) => {
|
|
||||||
const handle = registerContext('local', params, () => fetchLocalContext(params))
|
|
||||||
const unsub = handle.subscribe(() => set(handle.getState()))
|
|
||||||
handle.refetch()
|
|
||||||
return () => { unsub(); handle.unregister() }
|
|
||||||
},
|
|
||||||
)
|
|
||||||
|
|
||||||
return store
|
|
||||||
}
|
|
||||||
|
|
||||||
export { callEcho } from '../index'
|
|
||||||
export { callAdd } from '../index'
|
|
||||||
export { callWhoami } from '../index'
|
|
||||||
export { callHttpOnlyEcho } from '../index'
|
|
||||||
export { callStaffOnly } from '../index'
|
|
||||||
export { callSuperuserOnly } from '../index'
|
|
||||||
export { callVerifiedOnly } from '../index'
|
|
||||||
export { callMultiply } from '../index'
|
|
||||||
export { callNotImplementedFn } from '../index'
|
|
||||||
export { callBuggyFn } from '../index'
|
|
||||||
export { callPermissionCheckFn } from '../index'
|
|
||||||
export { callWsWhoami } from '../index'
|
|
||||||
export { callJwtObtain } from '../index'
|
|
||||||
export { callJwtRefresh } from '../index'
|
|
||||||
|
|
||||||
export type { ContextState } from '@mizan/runtime'
|
|
||||||
export { configure, initSession, MizanError } from '@mizan/runtime'
|
|
||||||
@@ -1,229 +0,0 @@
|
|||||||
// AUTO-GENERATED by mizan — do not edit
|
|
||||||
|
|
||||||
import { ref, computed, onMounted, onUnmounted, onServerPrefetch, type ComputedRef } from 'vue'
|
|
||||||
import { registerContext, type ContextState } from '@mizan/runtime'
|
|
||||||
|
|
||||||
import { fetchGlobalContext, type GlobalContextData, type GlobalContextParams, fetchLocalContext, type LocalContextData, type LocalContextParams, callEcho, callAdd, callWhoami, callHttpOnlyEcho, callStaffOnly, callSuperuserOnly, callVerifiedOnly, callMultiply, callNotImplementedFn, callBuggyFn, callPermissionCheckFn, callWsWhoami, callJwtObtain, callJwtRefresh } from '../index'
|
|
||||||
|
|
||||||
export function useGlobalContext() {
|
|
||||||
const state = ref<ContextState<GlobalContextData>>({ data: null, status: 'idle', error: null })
|
|
||||||
let handle: ReturnType<typeof registerContext> | null = null
|
|
||||||
|
|
||||||
onMounted(() => {
|
|
||||||
handle = registerContext('global', {} as any, () => fetchGlobalContext({} as any))
|
|
||||||
handle.subscribe(() => { state.value = handle!.getState() })
|
|
||||||
handle.refetch()
|
|
||||||
})
|
|
||||||
|
|
||||||
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 useLocalContext(params: LocalContextParams) {
|
|
||||||
const state = ref<ContextState<LocalContextData>>({ data: null, status: 'idle', error: null })
|
|
||||||
let handle: ReturnType<typeof registerContext> | null = null
|
|
||||||
|
|
||||||
onMounted(() => {
|
|
||||||
handle = registerContext('local', params, () => fetchLocalContext(params))
|
|
||||||
handle.subscribe(() => { state.value = handle!.getState() })
|
|
||||||
handle.refetch()
|
|
||||||
})
|
|
||||||
|
|
||||||
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 useEcho() {
|
|
||||||
const isPending = ref(false)
|
|
||||||
const error = ref<Error | null>(null)
|
|
||||||
async function mutate(args: Parameters<typeof callEcho>[0]) {
|
|
||||||
isPending.value = true; error.value = null
|
|
||||||
try { return await callEcho(args) }
|
|
||||||
catch (e) { error.value = e as Error; throw e }
|
|
||||||
finally { isPending.value = false }
|
|
||||||
}
|
|
||||||
return { mutate, isPending, error }
|
|
||||||
}
|
|
||||||
|
|
||||||
export 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 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 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 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 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 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 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 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 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 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 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 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 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 type { ContextState } from '@mizan/runtime'
|
|
||||||
export { configure, initSession, MizanError } from '@mizan/runtime'
|
|
||||||
@@ -23,11 +23,10 @@ import {
|
|||||||
useBuggyFn,
|
useBuggyFn,
|
||||||
usePermissionCheckFn,
|
usePermissionCheckFn,
|
||||||
useCurrentUser,
|
useCurrentUser,
|
||||||
DjangoError,
|
MizanError,
|
||||||
useMizan,
|
useMizan,
|
||||||
useChatChannel,
|
|
||||||
} from './api'
|
} from './api'
|
||||||
import { useContactForm, useLoginForm } from './api/generated.forms'
|
import { useChatChannel } from './api/channels.hooks'
|
||||||
|
|
||||||
// ─── Fixture router ─────────────────────────────────────────────────────────
|
// ─── Fixture router ─────────────────────────────────────────────────────────
|
||||||
|
|
||||||
@@ -55,9 +54,7 @@ export function Fixtures() {
|
|||||||
case 'permission-error': return <PermissionError_ />
|
case 'permission-error': return <PermissionError_ />
|
||||||
case 'permission-success': return <PermissionSuccess />
|
case 'permission-success': return <PermissionSuccess />
|
||||||
case 'context-current-user': return <ContextCurrentUser />
|
case 'context-current-user': return <ContextCurrentUser />
|
||||||
case 'form-login-schema': return <FormLoginSchema />
|
// Form fixtures removed — forms codegen deferred per Blazr scope
|
||||||
case 'form-contact-schema': return <FormContactSchema />
|
|
||||||
case 'form-contact-submit': return <FormContactSubmit />
|
|
||||||
case 'channel-chat': return <ChannelChatFixture />
|
case 'channel-chat': return <ChannelChatFixture />
|
||||||
default: return <div data-testid="ready">Harness ready. Set #hash.</div>
|
default: return <div data-testid="ready">Harness ready. Set #hash.</div>
|
||||||
}
|
}
|
||||||
@@ -74,10 +71,10 @@ function Result({ data, error }: { data?: unknown; error?: unknown }) {
|
|||||||
{error !== undefined && error !== null && (
|
{error !== undefined && error !== null && (
|
||||||
<>
|
<>
|
||||||
<div data-testid="error-type">
|
<div data-testid="error-type">
|
||||||
{error instanceof DjangoError ? 'DjangoError' : 'Error'}
|
{error instanceof MizanError ? 'MizanError' : 'Error'}
|
||||||
</div>
|
</div>
|
||||||
<div data-testid="error-code">
|
<div data-testid="error-code">
|
||||||
{error instanceof DjangoError ? error.code : ''}
|
{error instanceof MizanError ? error.code : ''}
|
||||||
</div>
|
</div>
|
||||||
<pre data-testid="error-message">
|
<pre data-testid="error-message">
|
||||||
{error instanceof Error ? error.message : String(error)}
|
{error instanceof Error ? error.message : String(error)}
|
||||||
@@ -187,44 +184,6 @@ function ContextCurrentUser() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── Form fixtures (using generated form hooks) ─────────────────────────────
|
|
||||||
|
|
||||||
function FormLoginSchema() {
|
|
||||||
const form = useLoginForm()
|
|
||||||
if (form.loading) return <div>loading...</div>
|
|
||||||
return <pre data-testid="result">{JSON.stringify(form.schema)}</pre>
|
|
||||||
}
|
|
||||||
|
|
||||||
function FormContactSchema() {
|
|
||||||
const form = useContactForm()
|
|
||||||
if (form.loading) return <div>loading...</div>
|
|
||||||
return <pre data-testid="result">{JSON.stringify(form.schema)}</pre>
|
|
||||||
}
|
|
||||||
|
|
||||||
function FormContactSubmit() {
|
|
||||||
const form = useContactForm()
|
|
||||||
const [result, setResult] = useState<unknown>()
|
|
||||||
const [submitted, setSubmitted] = useState(false)
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (!form.loading && !submitted) {
|
|
||||||
form.set('name', 'Test User')
|
|
||||||
form.set('email', 'test@example.com')
|
|
||||||
form.set('message', 'Hello from e2e')
|
|
||||||
setSubmitted(true)
|
|
||||||
}
|
|
||||||
}, [form.loading, submitted, form])
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (submitted && !result) {
|
|
||||||
form.submit().then(setResult)
|
|
||||||
}
|
|
||||||
}, [submitted, result, form])
|
|
||||||
|
|
||||||
if (!result) return <div>loading...</div>
|
|
||||||
return <pre data-testid="result">{JSON.stringify(result)}</pre>
|
|
||||||
}
|
|
||||||
|
|
||||||
// ─── Channel fixtures ───────────────────────────────────────────────────────
|
// ─── Channel fixtures ───────────────────────────────────────────────────────
|
||||||
|
|
||||||
function ChannelChatFixture() {
|
function ChannelChatFixture() {
|
||||||
|
|||||||
Reference in New Issue
Block a user