Two-stage codegen: React + Vue + Svelte from one schema
Stage 1 (framework-agnostic):
types.ts — OpenAPI interfaces
contexts/<name>.ts — fetchXxxContext(params) using mizanFetch
mutations/<name>.ts — callXxx(args) using mizanCall
functions/<name>.ts — callXxx(args) using mizanCall
index.ts — re-exports
Stage 2 (per framework):
react.tsx — hooks + context providers + SSR hydration
vue.ts — composables with provide/inject + ref/computed
svelte.ts — writable/derived store factories
New packages:
mizan-runtime — the kernel (~200 lines, zero framework deps)
configure(), initSession(), registerContext(), invalidate(),
mizanFetch(), mizanCall(), MizanError
mizan-vue — Vue adapter (package.json, codegen template)
mizan-svelte — Svelte adapter (package.json, codegen template)
CLI: mizan-generate --target react,vue,svelte
Config: target: 'react' (default) in django.config.mjs
Verified: codegen produces 33 functions across 2 contexts,
14 plain functions, 0 mutations, generating all three Stage 2
outputs from one schema fetch.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,15 @@
|
|||||||
|
// AUTO-GENERATED by mizan — do not edit
|
||||||
|
|
||||||
|
import { mizanFetch } from '@mizan/runtime'
|
||||||
|
|
||||||
|
import type { currentUserOutput } from '../types'
|
||||||
|
|
||||||
|
export interface GlobalContextData {
|
||||||
|
current_user: currentUserOutput
|
||||||
|
}
|
||||||
|
|
||||||
|
export type GlobalContextParams = Record<string, never>
|
||||||
|
|
||||||
|
export function fetchGlobalContext(params: GlobalContextParams): Promise<GlobalContextData> {
|
||||||
|
return mizanFetch('global', params)
|
||||||
|
}
|
||||||
17
examples/django-react-site/harness/src/api/contexts/local.ts
Normal file
17
examples/django-react-site/harness/src/api/contexts/local.ts
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
// AUTO-GENERATED by mizan — do not edit
|
||||||
|
|
||||||
|
import { mizanFetch } from '@mizan/runtime'
|
||||||
|
|
||||||
|
import type { greetOutput } from '../types'
|
||||||
|
|
||||||
|
export interface LocalContextData {
|
||||||
|
greet: greetOutput
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface LocalContextParams {
|
||||||
|
name: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export function fetchLocalContext(params: LocalContextParams): Promise<LocalContextData> {
|
||||||
|
return mizanFetch('local', params)
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
// AUTO-GENERATED by mizan — do not edit
|
||||||
|
|
||||||
|
import { mizanCall } from '@mizan/runtime'
|
||||||
|
|
||||||
|
import type { addInput, addOutput } from '../types'
|
||||||
|
|
||||||
|
export function callAdd(args: addInput): Promise<addOutput> {
|
||||||
|
return mizanCall('add', args)
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
// AUTO-GENERATED by mizan — do not edit
|
||||||
|
|
||||||
|
import { mizanCall } from '@mizan/runtime'
|
||||||
|
|
||||||
|
import type { buggyFnOutput } from '../types'
|
||||||
|
|
||||||
|
export function callBuggyFn(): Promise<buggyFnOutput> {
|
||||||
|
return mizanCall('buggy_fn', {})
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
// AUTO-GENERATED by mizan — do not edit
|
||||||
|
|
||||||
|
import { mizanCall } from '@mizan/runtime'
|
||||||
|
|
||||||
|
import type { echoInput, echoOutput } from '../types'
|
||||||
|
|
||||||
|
export function callEcho(args: echoInput): Promise<echoOutput> {
|
||||||
|
return mizanCall('echo', args)
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
// AUTO-GENERATED by mizan — do not edit
|
||||||
|
|
||||||
|
import { mizanCall } from '@mizan/runtime'
|
||||||
|
|
||||||
|
import type { httpOnlyEchoInput, httpOnlyEchoOutput } from '../types'
|
||||||
|
|
||||||
|
export function callHttpOnlyEcho(args: httpOnlyEchoInput): Promise<httpOnlyEchoOutput> {
|
||||||
|
return mizanCall('http_only_echo', args)
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
// AUTO-GENERATED by mizan — do not edit
|
||||||
|
|
||||||
|
import { mizanCall } from '@mizan/runtime'
|
||||||
|
|
||||||
|
import type { jwtObtainOutput } from '../types'
|
||||||
|
|
||||||
|
export function callJwtObtain(): Promise<jwtObtainOutput> {
|
||||||
|
return mizanCall('jwt_obtain', {})
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
// AUTO-GENERATED by mizan — do not edit
|
||||||
|
|
||||||
|
import { mizanCall } from '@mizan/runtime'
|
||||||
|
|
||||||
|
import type { jwtRefreshInput, jwtRefreshOutput } from '../types'
|
||||||
|
|
||||||
|
export function callJwtRefresh(args: jwtRefreshInput): Promise<jwtRefreshOutput> {
|
||||||
|
return mizanCall('jwt_refresh', args)
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
// AUTO-GENERATED by mizan — do not edit
|
||||||
|
|
||||||
|
import { mizanCall } from '@mizan/runtime'
|
||||||
|
|
||||||
|
import type { multiplyInput, multiplyOutput } from '../types'
|
||||||
|
|
||||||
|
export function callMultiply(args: multiplyInput): Promise<multiplyOutput> {
|
||||||
|
return mizanCall('multiply', args)
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
// AUTO-GENERATED by mizan — do not edit
|
||||||
|
|
||||||
|
import { mizanCall } from '@mizan/runtime'
|
||||||
|
|
||||||
|
import type { notImplementedFnOutput } from '../types'
|
||||||
|
|
||||||
|
export function callNotImplementedFn(): Promise<notImplementedFnOutput> {
|
||||||
|
return mizanCall('not_implemented_fn', {})
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
// AUTO-GENERATED by mizan — do not edit
|
||||||
|
|
||||||
|
import { mizanCall } from '@mizan/runtime'
|
||||||
|
|
||||||
|
import type { permissionCheckFnInput, permissionCheckFnOutput } from '../types'
|
||||||
|
|
||||||
|
export function callPermissionCheckFn(args: permissionCheckFnInput): Promise<permissionCheckFnOutput> {
|
||||||
|
return mizanCall('permission_check_fn', args)
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
// AUTO-GENERATED by mizan — do not edit
|
||||||
|
|
||||||
|
import { mizanCall } from '@mizan/runtime'
|
||||||
|
|
||||||
|
import type { staffOnlyOutput } from '../types'
|
||||||
|
|
||||||
|
export function callStaffOnly(): Promise<staffOnlyOutput> {
|
||||||
|
return mizanCall('staff_only', {})
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
// AUTO-GENERATED by mizan — do not edit
|
||||||
|
|
||||||
|
import { mizanCall } from '@mizan/runtime'
|
||||||
|
|
||||||
|
import type { superuserOnlyOutput } from '../types'
|
||||||
|
|
||||||
|
export function callSuperuserOnly(): Promise<superuserOnlyOutput> {
|
||||||
|
return mizanCall('superuser_only', {})
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
// AUTO-GENERATED by mizan — do not edit
|
||||||
|
|
||||||
|
import { mizanCall } from '@mizan/runtime'
|
||||||
|
|
||||||
|
import type { verifiedOnlyOutput } from '../types'
|
||||||
|
|
||||||
|
export function callVerifiedOnly(): Promise<verifiedOnlyOutput> {
|
||||||
|
return mizanCall('verified_only', {})
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
// AUTO-GENERATED by mizan — do not edit
|
||||||
|
|
||||||
|
import { mizanCall } from '@mizan/runtime'
|
||||||
|
|
||||||
|
import type { whoamiOutput } from '../types'
|
||||||
|
|
||||||
|
export function callWhoami(): Promise<whoamiOutput> {
|
||||||
|
return mizanCall('whoami', {})
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
// AUTO-GENERATED by mizan — do not edit
|
||||||
|
|
||||||
|
import { mizanCall } from '@mizan/runtime'
|
||||||
|
|
||||||
|
import type { wsWhoamiOutput } from '../types'
|
||||||
|
|
||||||
|
export function callWsWhoami(): Promise<wsWhoamiOutput> {
|
||||||
|
return mizanCall('ws_whoami', {})
|
||||||
|
}
|
||||||
@@ -1,268 +0,0 @@
|
|||||||
{
|
|
||||||
"openapi": "3.1.0",
|
|
||||||
"info": {
|
|
||||||
"title": "mizan Channels",
|
|
||||||
"version": "1.0.0",
|
|
||||||
"description": "Auto-generated schema for mizan channels"
|
|
||||||
},
|
|
||||||
"paths": {
|
|
||||||
"/channels/chat/params": {
|
|
||||||
"post": {
|
|
||||||
"operationId": "chatParams",
|
|
||||||
"summary": "Chat channel params",
|
|
||||||
"parameters": [],
|
|
||||||
"responses": {
|
|
||||||
"200": {
|
|
||||||
"description": "OK",
|
|
||||||
"content": {
|
|
||||||
"application/json": {
|
|
||||||
"schema": {
|
|
||||||
"$ref": "#/components/schemas/BaseModel"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"requestBody": {
|
|
||||||
"content": {
|
|
||||||
"application/json": {
|
|
||||||
"schema": {
|
|
||||||
"$ref": "#/components/schemas/ChatParams"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"required": true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"/channels/chat/react": {
|
|
||||||
"post": {
|
|
||||||
"operationId": "chatReactMessage",
|
|
||||||
"summary": "Chat React→Django message",
|
|
||||||
"parameters": [],
|
|
||||||
"responses": {
|
|
||||||
"200": {
|
|
||||||
"description": "OK",
|
|
||||||
"content": {
|
|
||||||
"application/json": {
|
|
||||||
"schema": {
|
|
||||||
"$ref": "#/components/schemas/BaseModel"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"requestBody": {
|
|
||||||
"content": {
|
|
||||||
"application/json": {
|
|
||||||
"schema": {
|
|
||||||
"$ref": "#/components/schemas/ChatReactMessage"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"required": true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"/channels/chat/django": {
|
|
||||||
"post": {
|
|
||||||
"operationId": "chatDjangoMessage",
|
|
||||||
"summary": "Chat Django→React message",
|
|
||||||
"parameters": [],
|
|
||||||
"responses": {
|
|
||||||
"200": {
|
|
||||||
"description": "OK",
|
|
||||||
"content": {
|
|
||||||
"application/json": {
|
|
||||||
"schema": {
|
|
||||||
"$ref": "#/components/schemas/ChatDjangoMessage"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"/channels/notifications/django": {
|
|
||||||
"post": {
|
|
||||||
"operationId": "notificationsDjangoMessage",
|
|
||||||
"summary": "Notifications Django→React message",
|
|
||||||
"parameters": [],
|
|
||||||
"responses": {
|
|
||||||
"200": {
|
|
||||||
"description": "OK",
|
|
||||||
"content": {
|
|
||||||
"application/json": {
|
|
||||||
"schema": {
|
|
||||||
"$ref": "#/components/schemas/NotificationsDjangoMessage"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"/channels/presence/django": {
|
|
||||||
"post": {
|
|
||||||
"operationId": "presenceDjangoMessage",
|
|
||||||
"summary": "Presence Django→React message",
|
|
||||||
"parameters": [],
|
|
||||||
"responses": {
|
|
||||||
"200": {
|
|
||||||
"description": "OK",
|
|
||||||
"content": {
|
|
||||||
"application/json": {
|
|
||||||
"schema": {
|
|
||||||
"$ref": "#/components/schemas/PresenceDjangoMessage"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"/channels/private/django": {
|
|
||||||
"post": {
|
|
||||||
"operationId": "privateDjangoMessage",
|
|
||||||
"summary": "Private Django→React message",
|
|
||||||
"parameters": [],
|
|
||||||
"responses": {
|
|
||||||
"200": {
|
|
||||||
"description": "OK",
|
|
||||||
"content": {
|
|
||||||
"application/json": {
|
|
||||||
"schema": {
|
|
||||||
"$ref": "#/components/schemas/PrivateDjangoMessage"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"components": {
|
|
||||||
"schemas": {
|
|
||||||
"BaseModel": {
|
|
||||||
"properties": {},
|
|
||||||
"title": "BaseModel",
|
|
||||||
"type": "object"
|
|
||||||
},
|
|
||||||
"ChatParams": {
|
|
||||||
"properties": {
|
|
||||||
"room": {
|
|
||||||
"title": "Room",
|
|
||||||
"type": "string"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"required": [
|
|
||||||
"room"
|
|
||||||
],
|
|
||||||
"title": "ChatParams",
|
|
||||||
"type": "object"
|
|
||||||
},
|
|
||||||
"ChatReactMessage": {
|
|
||||||
"properties": {
|
|
||||||
"text": {
|
|
||||||
"title": "Text",
|
|
||||||
"type": "string"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"required": [
|
|
||||||
"text"
|
|
||||||
],
|
|
||||||
"title": "ChatReactMessage",
|
|
||||||
"type": "object"
|
|
||||||
},
|
|
||||||
"ChatDjangoMessage": {
|
|
||||||
"properties": {
|
|
||||||
"text": {
|
|
||||||
"title": "Text",
|
|
||||||
"type": "string"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"required": [
|
|
||||||
"text"
|
|
||||||
],
|
|
||||||
"title": "ChatDjangoMessage",
|
|
||||||
"type": "object"
|
|
||||||
},
|
|
||||||
"NotificationsDjangoMessage": {
|
|
||||||
"properties": {
|
|
||||||
"text": {
|
|
||||||
"title": "Text",
|
|
||||||
"type": "string"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"required": [
|
|
||||||
"text"
|
|
||||||
],
|
|
||||||
"title": "NotificationsDjangoMessage",
|
|
||||||
"type": "object"
|
|
||||||
},
|
|
||||||
"PresenceDjangoMessage": {
|
|
||||||
"properties": {
|
|
||||||
"value": {
|
|
||||||
"title": "Value",
|
|
||||||
"type": "integer"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"required": [
|
|
||||||
"value"
|
|
||||||
],
|
|
||||||
"title": "PresenceDjangoMessage",
|
|
||||||
"type": "object"
|
|
||||||
},
|
|
||||||
"PrivateDjangoMessage": {
|
|
||||||
"properties": {
|
|
||||||
"text": {
|
|
||||||
"title": "Text",
|
|
||||||
"type": "string"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"required": [
|
|
||||||
"text"
|
|
||||||
],
|
|
||||||
"title": "PrivateDjangoMessage",
|
|
||||||
"type": "object"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"servers": [],
|
|
||||||
"x-mizan-channels": [
|
|
||||||
{
|
|
||||||
"name": "chat",
|
|
||||||
"pascalName": "Chat",
|
|
||||||
"hasParams": true,
|
|
||||||
"hasReactMessage": true,
|
|
||||||
"hasDjangoMessage": true,
|
|
||||||
"paramsType": "ChatParams",
|
|
||||||
"reactMessageType": "ChatReactMessage",
|
|
||||||
"djangoMessageType": "ChatDjangoMessage"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "notifications",
|
|
||||||
"pascalName": "Notifications",
|
|
||||||
"hasParams": false,
|
|
||||||
"hasReactMessage": false,
|
|
||||||
"hasDjangoMessage": true,
|
|
||||||
"djangoMessageType": "NotificationsDjangoMessage"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "presence",
|
|
||||||
"pascalName": "Presence",
|
|
||||||
"hasParams": false,
|
|
||||||
"hasReactMessage": false,
|
|
||||||
"hasDjangoMessage": true,
|
|
||||||
"djangoMessageType": "PresenceDjangoMessage"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "private",
|
|
||||||
"pascalName": "Private",
|
|
||||||
"hasParams": false,
|
|
||||||
"hasReactMessage": false,
|
|
||||||
"hasDjangoMessage": true,
|
|
||||||
"djangoMessageType": "PrivateDjangoMessage"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
@@ -1,226 +0,0 @@
|
|||||||
'use client'
|
|
||||||
|
|
||||||
// AUTO-GENERATED by mizan - do not edit manually
|
|
||||||
// Regenerate with: npm run schemas
|
|
||||||
|
|
||||||
// Typed form hooks with Zod validation.
|
|
||||||
// Zod schemas are generated from Django form field definitions.
|
|
||||||
// Client-side validation matches Django constraints (required, max_length, email, etc.)
|
|
||||||
|
|
||||||
import { z } from 'zod'
|
|
||||||
import {
|
|
||||||
useDjangoFormCore,
|
|
||||||
useDjangoFormsetCore,
|
|
||||||
type DjangoFormState,
|
|
||||||
type DjangoFormsetState,
|
|
||||||
type FormOptions,
|
|
||||||
} from 'mizan'
|
|
||||||
|
|
||||||
// ============================================================================
|
|
||||||
// Zod Schemas
|
|
||||||
// ============================================================================
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Zod schema for login form
|
|
||||||
* Generated from Django form field definitions
|
|
||||||
*/
|
|
||||||
export const LoginSchema = z.object({
|
|
||||||
})
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Zod schema for signup form
|
|
||||||
* Generated from Django form field definitions
|
|
||||||
*/
|
|
||||||
export const SignupSchema = z.object({
|
|
||||||
})
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Zod schema for add_email form
|
|
||||||
* Generated from Django form field definitions
|
|
||||||
*/
|
|
||||||
export const AddEmailSchema = z.object({
|
|
||||||
})
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Zod schema for contact form
|
|
||||||
* Generated from Django form field definitions
|
|
||||||
*/
|
|
||||||
export const ContactSchema = z.object({
|
|
||||||
name: z.string().max(100),
|
|
||||||
email: z.string().email('Invalid email address').max(320),
|
|
||||||
message: z.string(),
|
|
||||||
})
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Zod schema for item form
|
|
||||||
* Generated from Django form field definitions
|
|
||||||
*/
|
|
||||||
export const ItemSchema = z.object({
|
|
||||||
label: z.string().max(50),
|
|
||||||
quantity: z.number().int().min(1),
|
|
||||||
})
|
|
||||||
|
|
||||||
// ============================================================================
|
|
||||||
// Form Data Types (inferred from Zod schemas)
|
|
||||||
// ============================================================================
|
|
||||||
|
|
||||||
/** Form data type for login, inferred from Zod schema */
|
|
||||||
export type LoginFormData = z.infer<typeof LoginSchema>
|
|
||||||
|
|
||||||
/** Form data type for signup, inferred from Zod schema */
|
|
||||||
export type SignupFormData = z.infer<typeof SignupSchema>
|
|
||||||
|
|
||||||
/** Form data type for add_email, inferred from Zod schema */
|
|
||||||
export type AddEmailFormData = z.infer<typeof AddEmailSchema>
|
|
||||||
|
|
||||||
/** Form data type for contact, inferred from Zod schema */
|
|
||||||
export type ContactFormData = z.infer<typeof ContactSchema>
|
|
||||||
|
|
||||||
/** Form data type for item, inferred from Zod schema */
|
|
||||||
export type ItemFormData = z.infer<typeof ItemSchema>
|
|
||||||
|
|
||||||
// ============================================================================
|
|
||||||
// Form Hooks
|
|
||||||
// ============================================================================
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Typed form hook for login
|
|
||||||
*
|
|
||||||
* Features:
|
|
||||||
* - Full TypeScript inference for form fields
|
|
||||||
* - Client-side Zod validation (instant feedback)
|
|
||||||
* - Server-side Django validation (authoritative)
|
|
||||||
*/
|
|
||||||
export function useLoginForm(
|
|
||||||
options?: FormOptions
|
|
||||||
): DjangoFormState<LoginFormData> {
|
|
||||||
return useDjangoFormCore<LoginFormData>({
|
|
||||||
name: 'login',
|
|
||||||
zodSchema: LoginSchema,
|
|
||||||
options,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Typed form hook for signup
|
|
||||||
*
|
|
||||||
* Features:
|
|
||||||
* - Full TypeScript inference for form fields
|
|
||||||
* - Client-side Zod validation (instant feedback)
|
|
||||||
* - Server-side Django validation (authoritative)
|
|
||||||
*/
|
|
||||||
export function useSignupForm(
|
|
||||||
options?: FormOptions
|
|
||||||
): DjangoFormState<SignupFormData> {
|
|
||||||
return useDjangoFormCore<SignupFormData>({
|
|
||||||
name: 'signup',
|
|
||||||
zodSchema: SignupSchema,
|
|
||||||
options,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Typed form hook for add_email
|
|
||||||
*
|
|
||||||
* Features:
|
|
||||||
* - Full TypeScript inference for form fields
|
|
||||||
* - Client-side Zod validation (instant feedback)
|
|
||||||
* - Server-side Django validation (authoritative)
|
|
||||||
*/
|
|
||||||
export function useAddEmailForm(
|
|
||||||
options?: FormOptions
|
|
||||||
): DjangoFormState<AddEmailFormData> {
|
|
||||||
return useDjangoFormCore<AddEmailFormData>({
|
|
||||||
name: 'add_email',
|
|
||||||
zodSchema: AddEmailSchema,
|
|
||||||
options,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Typed form hook for contact
|
|
||||||
*
|
|
||||||
* Features:
|
|
||||||
* - Full TypeScript inference for form fields
|
|
||||||
* - Client-side Zod validation (instant feedback)
|
|
||||||
* - Server-side Django validation (authoritative)
|
|
||||||
*/
|
|
||||||
export function useContactForm(
|
|
||||||
options?: FormOptions
|
|
||||||
): DjangoFormState<ContactFormData> {
|
|
||||||
return useDjangoFormCore<ContactFormData>({
|
|
||||||
name: 'contact',
|
|
||||||
zodSchema: ContactSchema,
|
|
||||||
options,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Typed form hook for item
|
|
||||||
*
|
|
||||||
* Features:
|
|
||||||
* - Full TypeScript inference for form fields
|
|
||||||
* - Client-side Zod validation (instant feedback)
|
|
||||||
* - Server-side Django validation (authoritative)
|
|
||||||
*/
|
|
||||||
export function useItemForm(
|
|
||||||
options?: FormOptions
|
|
||||||
): DjangoFormState<ItemFormData> {
|
|
||||||
return useDjangoFormCore<ItemFormData>({
|
|
||||||
name: 'item',
|
|
||||||
zodSchema: ItemSchema,
|
|
||||||
options,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Typed formset hook for item
|
|
||||||
*/
|
|
||||||
export function useItemFormset(
|
|
||||||
initialCount?: number,
|
|
||||||
liveValidation?: boolean
|
|
||||||
): DjangoFormsetState<ItemFormData> {
|
|
||||||
return useDjangoFormsetCore<ItemFormData>({
|
|
||||||
name: 'item',
|
|
||||||
zodSchema: ItemSchema,
|
|
||||||
initialCount,
|
|
||||||
liveValidation,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// ============================================================================
|
|
||||||
// Form Registry
|
|
||||||
// ============================================================================
|
|
||||||
|
|
||||||
export const MIZAN_FORMS = {
|
|
||||||
login: {
|
|
||||||
name: 'login',
|
|
||||||
schema: LoginSchema,
|
|
||||||
hook: 'useLoginForm',
|
|
||||||
hasFormset: false,
|
|
||||||
},
|
|
||||||
signup: {
|
|
||||||
name: 'signup',
|
|
||||||
schema: SignupSchema,
|
|
||||||
hook: 'useSignupForm',
|
|
||||||
hasFormset: false,
|
|
||||||
},
|
|
||||||
addEmail: {
|
|
||||||
name: 'add_email',
|
|
||||||
schema: AddEmailSchema,
|
|
||||||
hook: 'useAddEmailForm',
|
|
||||||
hasFormset: false,
|
|
||||||
},
|
|
||||||
contact: {
|
|
||||||
name: 'contact',
|
|
||||||
schema: ContactSchema,
|
|
||||||
hook: 'useContactForm',
|
|
||||||
hasFormset: false,
|
|
||||||
},
|
|
||||||
item: {
|
|
||||||
name: 'item',
|
|
||||||
schema: ItemSchema,
|
|
||||||
hook: 'useItemForm',
|
|
||||||
hasFormset: true,
|
|
||||||
},
|
|
||||||
} as const
|
|
||||||
@@ -1,97 +1,21 @@
|
|||||||
/**
|
// AUTO-GENERATED by mizan — do not edit
|
||||||
* mizan API - Consolidated Exports
|
|
||||||
*
|
|
||||||
* Import everything from here:
|
|
||||||
*
|
|
||||||
* @example
|
|
||||||
* ```tsx
|
|
||||||
* import {
|
|
||||||
* MizanContext,
|
|
||||||
* useCurrentUser,
|
|
||||||
* useEcho,
|
|
||||||
* useChatChannel,
|
|
||||||
* } from '@/api'
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
|
|
||||||
// AUTO-GENERATED by mizan - do not edit manually
|
export * from './types'
|
||||||
// Regenerate with: npm run schemas
|
|
||||||
|
|
||||||
// =============================================================================
|
export { fetchGlobalContext, type GlobalContextData, type GlobalContextParams } from './contexts/global'
|
||||||
// mizan Provider & Hooks
|
export { fetchLocalContext, type LocalContextData, type LocalContextParams } from './contexts/local'
|
||||||
// =============================================================================
|
|
||||||
|
|
||||||
export {
|
export { callEcho } from './functions/echo'
|
||||||
getMizanHydration,
|
export { callAdd } from './functions/add'
|
||||||
getDjangoHydration,
|
export { callWhoami } from './functions/whoami'
|
||||||
type MizanHydrationData,
|
export { callHttpOnlyEcho } from './functions/httpOnlyEcho'
|
||||||
type DjangoHydration,
|
export { callStaffOnly } from './functions/staffOnly'
|
||||||
} from './generated.server'
|
export { callSuperuserOnly } from './functions/superuserOnly'
|
||||||
|
export { callVerifiedOnly } from './functions/verifiedOnly'
|
||||||
export {
|
export { callMultiply } from './functions/multiply'
|
||||||
// Provider
|
export { callNotImplementedFn } from './functions/notImplementedFn'
|
||||||
MizanContext,
|
export { callBuggyFn } from './functions/buggyFn'
|
||||||
type MizanContextProps,
|
export { callPermissionCheckFn } from './functions/permissionCheckFn'
|
||||||
DjangoContext,
|
export { callWsWhoami } from './functions/wsWhoami'
|
||||||
type DjangoContextProps,
|
export { callJwtObtain } from './functions/jwtObtain'
|
||||||
|
export { callJwtRefresh } from './functions/jwtRefresh'
|
||||||
// Global context hooks
|
|
||||||
useCurrentUser,
|
|
||||||
|
|
||||||
// Refresh hooks
|
|
||||||
useMizanRefresh,
|
|
||||||
useDjangoRefresh,
|
|
||||||
|
|
||||||
// Named context providers
|
|
||||||
LocalContext,
|
|
||||||
useGreet,
|
|
||||||
|
|
||||||
// Function hooks
|
|
||||||
useEcho,
|
|
||||||
useAdd,
|
|
||||||
useWhoami,
|
|
||||||
useHttpOnlyEcho,
|
|
||||||
useStaffOnly,
|
|
||||||
useSuperuserOnly,
|
|
||||||
useVerifiedOnly,
|
|
||||||
useMultiply,
|
|
||||||
useNotImplementedFn,
|
|
||||||
useBuggyFn,
|
|
||||||
usePermissionCheckFn,
|
|
||||||
useWsWhoami,
|
|
||||||
useJwtObtain,
|
|
||||||
useJwtRefresh,
|
|
||||||
|
|
||||||
// Re-exports from mizan library
|
|
||||||
useMizan,
|
|
||||||
useMizanStatus,
|
|
||||||
usePush,
|
|
||||||
DjangoError,
|
|
||||||
type ConnectionStatus,
|
|
||||||
type PushMessage,
|
|
||||||
type PushListener,
|
|
||||||
} from './generated.provider'
|
|
||||||
|
|
||||||
// =============================================================================
|
|
||||||
// Channel Hooks
|
|
||||||
// =============================================================================
|
|
||||||
|
|
||||||
export {
|
|
||||||
useChatChannel,
|
|
||||||
useNotificationsChannel,
|
|
||||||
usePresenceChannel,
|
|
||||||
usePrivateChannel,
|
|
||||||
} from './generated.channels.hooks'
|
|
||||||
|
|
||||||
// =============================================================================
|
|
||||||
// Channel Types
|
|
||||||
// =============================================================================
|
|
||||||
|
|
||||||
export type {
|
|
||||||
ChatParams,
|
|
||||||
ChatReactMessage,
|
|
||||||
ChatDjangoMessage,
|
|
||||||
NotificationsDjangoMessage,
|
|
||||||
PresenceDjangoMessage,
|
|
||||||
PrivateDjangoMessage,
|
|
||||||
} from './generated.channels'
|
|
||||||
|
|||||||
118
examples/django-react-site/harness/src/api/react.tsx
Normal file
118
examples/django-react-site/harness/src/api/react.tsx
Normal file
@@ -0,0 +1,118 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
// AUTO-GENERATED by mizan — do not edit
|
||||||
|
|
||||||
|
import { createContext, useContext, useState, useEffect, useCallback, type ReactNode } from 'react'
|
||||||
|
import { registerContext, mizanCall, mizanFetch } from '@mizan/runtime'
|
||||||
|
|
||||||
|
import { fetchGlobalContext, type GlobalContextData, type GlobalContextParams, fetchLocalContext, type LocalContextData, type LocalContextParams, callEcho, callAdd, callWhoami, callHttpOnlyEcho, callStaffOnly, callSuperuserOnly, callVerifiedOnly, callMultiply, callNotImplementedFn, callBuggyFn, callPermissionCheckFn, callWsWhoami, callJwtObtain, callJwtRefresh } from '../index'
|
||||||
|
|
||||||
|
// Global context — fetched once at app init
|
||||||
|
const GlobalCtx = createContext<GlobalContextData | null>(null)
|
||||||
|
|
||||||
|
export function GlobalContextProvider({ children }: { children: ReactNode }) {
|
||||||
|
const [data, setData] = useState<GlobalContextData | null>(() => {
|
||||||
|
if (typeof window === 'undefined') return null
|
||||||
|
const ssr = (window as any).__MIZAN_SSR_DATA__
|
||||||
|
return ssr ?? null
|
||||||
|
})
|
||||||
|
|
||||||
|
const refetch = useCallback(async () => {
|
||||||
|
const result = await fetchGlobalContext({} as any)
|
||||||
|
setData(result)
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
useEffect(() => { if (!data) refetch() }, [data, refetch])
|
||||||
|
useEffect(() => registerContext('global', {}, refetch), [refetch])
|
||||||
|
|
||||||
|
return <GlobalCtx.Provider value={data}>{children}</GlobalCtx.Provider>
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useCurrentUser(): currentUserOutput {
|
||||||
|
const ctx = useContext(GlobalCtx)
|
||||||
|
if (!ctx) throw new Error('useCurrentUser requires GlobalContextProvider')
|
||||||
|
return ctx.current_user
|
||||||
|
}
|
||||||
|
|
||||||
|
// Local context
|
||||||
|
const LocalCtx = createContext<LocalContextData | null>(null)
|
||||||
|
|
||||||
|
export function LocalContext({ children, ...params }: LocalContextParams & { children: ReactNode }) {
|
||||||
|
const [data, setData] = useState<LocalContextData | null>(() => {
|
||||||
|
if (typeof window === 'undefined') return null
|
||||||
|
const ssr = (window as any).__MIZAN_SSR_DATA__
|
||||||
|
if (ssr?.greet !== undefined) return ssr
|
||||||
|
return null
|
||||||
|
})
|
||||||
|
|
||||||
|
const refetch = useCallback(async () => {
|
||||||
|
const result = await fetchLocalContext(params)
|
||||||
|
setData(result)
|
||||||
|
}, [params.name])
|
||||||
|
|
||||||
|
useEffect(() => { refetch() }, [refetch])
|
||||||
|
useEffect(() => registerContext('local', params, refetch), [params.name, refetch])
|
||||||
|
|
||||||
|
return <LocalCtx.Provider value={data}>{children}</LocalCtx.Provider>
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useGreet(): greetOutput | null {
|
||||||
|
const ctx = useContext(LocalCtx)
|
||||||
|
return ctx?.greet ?? null
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useEcho() {
|
||||||
|
return useCallback((args: Parameters<typeof callEcho>[0]) => callEcho(args), [])
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useAdd() {
|
||||||
|
return useCallback((args: Parameters<typeof callAdd>[0]) => callAdd(args), [])
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useWhoami() {
|
||||||
|
return useCallback(() => callWhoami(), [])
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useHttpOnlyEcho() {
|
||||||
|
return useCallback((args: Parameters<typeof callHttpOnlyEcho>[0]) => callHttpOnlyEcho(args), [])
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useStaffOnly() {
|
||||||
|
return useCallback(() => callStaffOnly(), [])
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useSuperuserOnly() {
|
||||||
|
return useCallback(() => callSuperuserOnly(), [])
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useVerifiedOnly() {
|
||||||
|
return useCallback(() => callVerifiedOnly(), [])
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useMultiply() {
|
||||||
|
return useCallback((args: Parameters<typeof callMultiply>[0]) => callMultiply(args), [])
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useNotImplementedFn() {
|
||||||
|
return useCallback(() => callNotImplementedFn(), [])
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useBuggyFn() {
|
||||||
|
return useCallback(() => callBuggyFn(), [])
|
||||||
|
}
|
||||||
|
|
||||||
|
export function usePermissionCheckFn() {
|
||||||
|
return useCallback((args: Parameters<typeof callPermissionCheckFn>[0]) => callPermissionCheckFn(args), [])
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useWsWhoami() {
|
||||||
|
return useCallback(() => callWsWhoami(), [])
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useJwtObtain() {
|
||||||
|
return useCallback(() => callJwtObtain(), [])
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useJwtRefresh() {
|
||||||
|
return useCallback((args: Parameters<typeof callJwtRefresh>[0]) => callJwtRefresh(args), [])
|
||||||
|
}
|
||||||
2678
examples/django-react-site/harness/src/api/schema.json
Normal file
2678
examples/django-react-site/harness/src/api/schema.json
Normal file
File diff suppressed because it is too large
Load Diff
67
examples/django-react-site/harness/src/api/svelte.ts
Normal file
67
examples/django-react-site/harness/src/api/svelte.ts
Normal file
@@ -0,0 +1,67 @@
|
|||||||
|
// AUTO-GENERATED by mizan — do not edit
|
||||||
|
|
||||||
|
import { writable, derived, type Readable } from 'svelte/store'
|
||||||
|
import { registerContext } from '@mizan/runtime'
|
||||||
|
|
||||||
|
import { fetchGlobalContext, type GlobalContextData, type GlobalContextParams, fetchLocalContext, type LocalContextData, type LocalContextParams, callEcho, callAdd, callWhoami, callHttpOnlyEcho, callStaffOnly, callSuperuserOnly, callVerifiedOnly, callMultiply, callNotImplementedFn, callBuggyFn, callPermissionCheckFn, callWsWhoami, callJwtObtain, callJwtRefresh } from '../index'
|
||||||
|
|
||||||
|
// Global context
|
||||||
|
export function createGlobalContext() {
|
||||||
|
const data = writable<GlobalContextData | null>(null)
|
||||||
|
const loading = writable(true)
|
||||||
|
|
||||||
|
const refetch = async () => {
|
||||||
|
loading.set(true)
|
||||||
|
const result = await fetchGlobalContext({} as any)
|
||||||
|
data.set(result)
|
||||||
|
loading.set(false)
|
||||||
|
}
|
||||||
|
|
||||||
|
refetch()
|
||||||
|
const unregister = registerContext('global', {}, refetch)
|
||||||
|
|
||||||
|
return {
|
||||||
|
data,
|
||||||
|
loading,
|
||||||
|
currentUser: derived(data, $d => $d?.current_user ?? null) as Readable<currentUserOutput | null>,
|
||||||
|
destroy: unregister,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Local context
|
||||||
|
export function createLocalContext(params: LocalContextParams) {
|
||||||
|
const data = writable<LocalContextData | null>(null)
|
||||||
|
const loading = writable(true)
|
||||||
|
|
||||||
|
const refetch = async () => {
|
||||||
|
loading.set(true)
|
||||||
|
const result = await fetchLocalContext(params)
|
||||||
|
data.set(result)
|
||||||
|
loading.set(false)
|
||||||
|
}
|
||||||
|
|
||||||
|
refetch()
|
||||||
|
const unregister = registerContext('local', params, refetch)
|
||||||
|
|
||||||
|
return {
|
||||||
|
data,
|
||||||
|
loading,
|
||||||
|
greet: derived(data, $d => $d?.greet ?? null) as Readable<greetOutput | null>,
|
||||||
|
destroy: unregister,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export { callEcho } from '../functions/echo'
|
||||||
|
export { callAdd } from '../functions/add'
|
||||||
|
export { callWhoami } from '../functions/whoami'
|
||||||
|
export { callHttpOnlyEcho } from '../functions/httpOnlyEcho'
|
||||||
|
export { callStaffOnly } from '../functions/staffOnly'
|
||||||
|
export { callSuperuserOnly } from '../functions/superuserOnly'
|
||||||
|
export { callVerifiedOnly } from '../functions/verifiedOnly'
|
||||||
|
export { callMultiply } from '../functions/multiply'
|
||||||
|
export { callNotImplementedFn } from '../functions/notImplementedFn'
|
||||||
|
export { callBuggyFn } from '../functions/buggyFn'
|
||||||
|
export { callPermissionCheckFn } from '../functions/permissionCheckFn'
|
||||||
|
export { callWsWhoami } from '../functions/wsWhoami'
|
||||||
|
export { callJwtObtain } from '../functions/jwtObtain'
|
||||||
|
export { callJwtRefresh } from '../functions/jwtRefresh'
|
||||||
1908
examples/django-react-site/harness/src/api/types.ts
Normal file
1908
examples/django-react-site/harness/src/api/types.ts
Normal file
File diff suppressed because it is too large
Load Diff
96
examples/django-react-site/harness/src/api/vue.ts
Normal file
96
examples/django-react-site/harness/src/api/vue.ts
Normal file
@@ -0,0 +1,96 @@
|
|||||||
|
// AUTO-GENERATED by mizan — do not edit
|
||||||
|
|
||||||
|
import { ref, computed, watch, onMounted, onUnmounted, provide, inject, type Ref, type ComputedRef, type InjectionKey } from 'vue'
|
||||||
|
import { registerContext } from '@mizan/runtime'
|
||||||
|
|
||||||
|
import { fetchGlobalContext, type GlobalContextData, type GlobalContextParams, fetchLocalContext, type LocalContextData, type LocalContextParams, callEcho, callAdd, callWhoami, callHttpOnlyEcho, callStaffOnly, callSuperuserOnly, callVerifiedOnly, callMultiply, callNotImplementedFn, callBuggyFn, callPermissionCheckFn, callWsWhoami, callJwtObtain, callJwtRefresh } from '../index'
|
||||||
|
|
||||||
|
// Global context
|
||||||
|
const GlobalKey: InjectionKey<{ data: Ref<GlobalContextData | null>, loading: Ref<boolean> }> = Symbol('global')
|
||||||
|
|
||||||
|
export function provideGlobalContext() {
|
||||||
|
const data = ref<GlobalContextData | null>(null)
|
||||||
|
const loading = ref(true)
|
||||||
|
|
||||||
|
const refetch = async () => {
|
||||||
|
loading.value = true
|
||||||
|
try {
|
||||||
|
data.value = await fetchGlobalContext({} as any)
|
||||||
|
} catch (e) { console.error('[mizan] global fetch failed:', e) }
|
||||||
|
loading.value = false
|
||||||
|
}
|
||||||
|
|
||||||
|
let unregister: (() => void) | null = null
|
||||||
|
onMounted(() => {
|
||||||
|
refetch()
|
||||||
|
unregister = registerContext('global', {}, refetch)
|
||||||
|
})
|
||||||
|
onUnmounted(() => { unregister?.() })
|
||||||
|
|
||||||
|
provide(GlobalKey, { data, loading })
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useCurrentUser(): ComputedRef<currentUserOutput | null> {
|
||||||
|
const ctx = inject(GlobalKey)
|
||||||
|
if (!ctx) throw new Error('useCurrentUser requires provideGlobalContext in a parent')
|
||||||
|
return computed(() => ctx.data.value?.current_user ?? null)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Local context
|
||||||
|
const LocalKey: InjectionKey<{ data: Ref<LocalContextData | null>, loading: Ref<boolean> }> = Symbol('local')
|
||||||
|
|
||||||
|
export function provideLocalContext(params: { name: string }) {
|
||||||
|
const data = ref<LocalContextData | null>(null)
|
||||||
|
const loading = ref(true)
|
||||||
|
|
||||||
|
const refetch = async () => {
|
||||||
|
loading.value = true
|
||||||
|
try {
|
||||||
|
data.value = await fetchLocalContext(params as any)
|
||||||
|
} catch (e) { console.error('[mizan] local fetch failed:', e) }
|
||||||
|
loading.value = false
|
||||||
|
}
|
||||||
|
|
||||||
|
let unregister: (() => void) | null = null
|
||||||
|
onMounted(() => {
|
||||||
|
refetch()
|
||||||
|
unregister = registerContext('local', params, refetch)
|
||||||
|
})
|
||||||
|
onUnmounted(() => { unregister?.() })
|
||||||
|
|
||||||
|
provide(LocalKey, { data, loading })
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useGreet(): ComputedRef<greetOutput | null> {
|
||||||
|
const ctx = inject(LocalKey)
|
||||||
|
if (!ctx) throw new Error('useGreet requires provideLocalContext in a parent')
|
||||||
|
return computed(() => ctx.data.value?.greet ?? null)
|
||||||
|
}
|
||||||
|
|
||||||
|
export const useEcho = callEcho
|
||||||
|
|
||||||
|
export const useAdd = callAdd
|
||||||
|
|
||||||
|
export const useWhoami = callWhoami
|
||||||
|
|
||||||
|
export const useHttpOnlyEcho = callHttpOnlyEcho
|
||||||
|
|
||||||
|
export const useStaffOnly = callStaffOnly
|
||||||
|
|
||||||
|
export const useSuperuserOnly = callSuperuserOnly
|
||||||
|
|
||||||
|
export const useVerifiedOnly = callVerifiedOnly
|
||||||
|
|
||||||
|
export const useMultiply = callMultiply
|
||||||
|
|
||||||
|
export const useNotImplementedFn = callNotImplementedFn
|
||||||
|
|
||||||
|
export const useBuggyFn = callBuggyFn
|
||||||
|
|
||||||
|
export const usePermissionCheckFn = callPermissionCheckFn
|
||||||
|
|
||||||
|
export const useWsWhoami = callWsWhoami
|
||||||
|
|
||||||
|
export const useJwtObtain = callJwtObtain
|
||||||
|
|
||||||
|
export const useJwtRefresh = callJwtRefresh
|
||||||
@@ -2,282 +2,222 @@
|
|||||||
/**
|
/**
|
||||||
* mizan Code Generator CLI
|
* mizan Code Generator CLI
|
||||||
*
|
*
|
||||||
* Generate TypeScript types, React provider, and hooks from Django schemas.
|
* Two-stage codegen:
|
||||||
|
* Stage 1: Framework-agnostic types + fetch/mutation functions
|
||||||
|
* Stage 2: Framework-specific wrappers (React hooks, Vue composables, Svelte stores)
|
||||||
*
|
*
|
||||||
* Usage:
|
* Usage:
|
||||||
* npx mizan-generate # Run once
|
* npx mizan-generate # React (default)
|
||||||
* npx mizan-generate --watch # Watch mode
|
* npx mizan-generate --target vue # Vue
|
||||||
|
* npx mizan-generate --target react,vue,svelte # All three
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { promises as fs } from 'fs'
|
import { promises as fs } from 'fs'
|
||||||
import path from 'path'
|
import path from 'path'
|
||||||
import { fetchChannelsSchema, fetchMizanSchema } from './lib/fetch.mjs'
|
import { fetchChannelsSchema, fetchMizanSchema } from './lib/fetch.mjs'
|
||||||
import { generateMizanFiles } from './lib/mizan.mjs'
|
import { generateTypes, generateContextFile, generateMutationFile, generateFunctionFile, generateStage1Index } from './lib/stage1.mjs'
|
||||||
|
import { generateReactAdapter } from './lib/adapters/react.mjs'
|
||||||
|
import { generateVueAdapter } from './lib/adapters/vue.mjs'
|
||||||
|
import { generateSvelteAdapter } from './lib/adapters/svelte.mjs'
|
||||||
import { generateChannelsFiles } from './lib/channels.mjs'
|
import { generateChannelsFiles } from './lib/channels.mjs'
|
||||||
import { generateIndex } from './lib/index.mjs'
|
|
||||||
|
|
||||||
// Use cwd — the script runs via `npx mizan-generate` from the frontend root
|
|
||||||
const frontendDir = process.cwd()
|
const frontendDir = process.cwd()
|
||||||
|
|
||||||
/**
|
|
||||||
* Load configuration from django.config.mjs
|
|
||||||
*/
|
|
||||||
async function loadConfig(configPath) {
|
async function loadConfig(configPath) {
|
||||||
const fullPath = path.resolve(frontendDir, configPath)
|
const fullPath = path.resolve(frontendDir, configPath)
|
||||||
|
try { await fs.access(fullPath) } catch { throw new Error(`Config not found: ${fullPath}`) }
|
||||||
try {
|
const fileUrl = new URL(`file://${fullPath.replace(/\\/g, '/')}`)
|
||||||
await fs.access(fullPath)
|
|
||||||
} catch {
|
|
||||||
throw new Error(`Config file not found: ${fullPath}`)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Convert to file:// URL for Windows compatibility
|
|
||||||
const fileUrl = new URL(`file://${fullPath.replace(/\\/g, '/')}`)
|
|
||||||
|
|
||||||
if (configPath.endsWith('.mjs') || configPath.endsWith('.js')) {
|
|
||||||
const module = await import(fileUrl)
|
const module = await import(fileUrl)
|
||||||
return module.default
|
return module.default
|
||||||
}
|
|
||||||
|
|
||||||
if (configPath.endsWith('.ts')) {
|
|
||||||
try {
|
|
||||||
const module = await import(fileUrl)
|
|
||||||
return module.default
|
|
||||||
} catch {
|
|
||||||
throw new Error(
|
|
||||||
`Cannot load TypeScript config directly. Either:\n` +
|
|
||||||
` 1. Install tsx: npm install -D tsx\n` +
|
|
||||||
` 2. Use django.config.mjs instead`
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
throw new Error(`Unsupported config file format: ${configPath}`)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Write generated code to file.
|
|
||||||
*/
|
|
||||||
async function writeOutput(filePath, content) {
|
async function writeOutput(filePath, content) {
|
||||||
const dir = path.dirname(filePath)
|
const dir = path.dirname(filePath)
|
||||||
await fs.mkdir(dir, { recursive: true })
|
await fs.mkdir(dir, { recursive: true })
|
||||||
await fs.writeFile(filePath, content, 'utf8')
|
await fs.writeFile(filePath, content, 'utf8')
|
||||||
|
}
|
||||||
|
|
||||||
|
function pascalCase(str) {
|
||||||
|
return str.split(/[.\-_]/).map(p => p.charAt(0).toUpperCase() + p.slice(1)).join('')
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Run schema generation.
|
|
||||||
*/
|
|
||||||
async function generate(config, options = {}) {
|
async function generate(config, options = {}) {
|
||||||
const { output } = options
|
const { output, target: targetFlag } = options
|
||||||
|
const outputDir = output || config.output || 'src/api'
|
||||||
|
const targets = (targetFlag || config.target || 'react').split(',').map(t => t.trim())
|
||||||
|
|
||||||
console.log('[mizan] Starting schema generation...')
|
console.log(`[mizan] Starting generation (targets: ${targets.join(', ')})...`)
|
||||||
|
|
||||||
const outputPath = output || config.output || 'src/api/generated.ts'
|
const fullOutputDir = path.resolve(frontendDir, outputDir)
|
||||||
|
let mizanSchema = null
|
||||||
|
let channelsSchema = null
|
||||||
|
|
||||||
let channelsSchema = null
|
// ── Channels (React-only for now) ───────────────────────────────────
|
||||||
let mizanSchema = null
|
|
||||||
|
|
||||||
// Fetch and generate channels if available
|
|
||||||
try {
|
|
||||||
console.log('[mizan] Fetching channels schema...')
|
|
||||||
channelsSchema = await fetchChannelsSchema(config.source, frontendDir)
|
|
||||||
|
|
||||||
const channelCount = channelsSchema['x-mizan-channels']?.length || 0
|
|
||||||
if (channelCount > 0) {
|
|
||||||
console.log(`[mizan] Found ${channelCount} channels`)
|
|
||||||
|
|
||||||
const channelsTypesPath = outputPath.replace(/\.ts$/, '.channels.ts')
|
|
||||||
const fullChannelsTypesPath = path.resolve(frontendDir, channelsTypesPath)
|
|
||||||
const channelsHooksPath = outputPath.replace(/\.ts$/, '.channels.hooks.tsx')
|
|
||||||
const fullChannelsHooksPath = path.resolve(frontendDir, channelsHooksPath)
|
|
||||||
const channelsSchemaPath = outputPath.replace(/\.ts$/, '.channels.schema.json')
|
|
||||||
const fullChannelsSchemaPath = path.resolve(frontendDir, channelsSchemaPath)
|
|
||||||
|
|
||||||
const { types: channelsTypes, hooks: channelsHooks } = await generateChannelsFiles(channelsSchema)
|
|
||||||
|
|
||||||
console.log(`[mizan] Generating -> ${channelsTypesPath}`)
|
|
||||||
await writeOutput(fullChannelsTypesPath, channelsTypes)
|
|
||||||
|
|
||||||
if (channelsHooks) {
|
|
||||||
console.log(`[mizan] Generating -> ${channelsHooksPath}`)
|
|
||||||
await writeOutput(fullChannelsHooksPath, channelsHooks)
|
|
||||||
}
|
|
||||||
|
|
||||||
console.log(`[mizan] Generating -> ${channelsSchemaPath}`)
|
|
||||||
await writeOutput(fullChannelsSchemaPath, JSON.stringify(channelsSchema, null, 2))
|
|
||||||
} else {
|
|
||||||
console.log('[mizan] No channels registered, skipping channels generation')
|
|
||||||
}
|
|
||||||
} catch (err) {
|
|
||||||
console.log(`[mizan] Channels schema not available: ${err.message}`)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Fetch and generate mizan files
|
|
||||||
try {
|
|
||||||
console.log('[mizan] Fetching mizan schema...')
|
|
||||||
mizanSchema = await fetchMizanSchema(config.source, frontendDir)
|
|
||||||
|
|
||||||
const functionCount = mizanSchema['x-mizan-functions']?.length || 0
|
|
||||||
if (functionCount > 0) {
|
|
||||||
console.log(`[mizan] Found ${functionCount} mizan functions`)
|
|
||||||
|
|
||||||
const mizanTypesPath = outputPath.replace(/\.ts$/, '.mizan.ts')
|
|
||||||
const fullMizanTypesPath = path.resolve(frontendDir, mizanTypesPath)
|
|
||||||
const mizanProviderPath = outputPath.replace(/\.ts$/, '.provider.tsx')
|
|
||||||
const fullMizanProviderPath = path.resolve(frontendDir, mizanProviderPath)
|
|
||||||
const mizanServerPath = outputPath.replace(/\.ts$/, '.server.ts')
|
|
||||||
const fullMizanServerPath = path.resolve(frontendDir, mizanServerPath)
|
|
||||||
const mizanFormsPath = outputPath.replace(/\.ts$/, '.forms.ts')
|
|
||||||
const fullMizanFormsPath = path.resolve(frontendDir, mizanFormsPath)
|
|
||||||
const mizanSchemaPath = outputPath.replace(/\.ts$/, '.mizan.schema.json')
|
|
||||||
const fullMizanSchemaPath = path.resolve(frontendDir, mizanSchemaPath)
|
|
||||||
|
|
||||||
const hasChannels = (channelsSchema?.['x-mizan-channels']?.length || 0) > 0
|
|
||||||
const { types: mizanTypes, provider: mizanProvider, server: mizanServer, forms: mizanForms } = await generateMizanFiles(mizanSchema, { hasChannels })
|
|
||||||
|
|
||||||
console.log(`[mizan] Generating -> ${mizanTypesPath}`)
|
|
||||||
await writeOutput(fullMizanTypesPath, mizanTypes)
|
|
||||||
|
|
||||||
if (mizanProvider) {
|
|
||||||
console.log(`[mizan] Generating -> ${mizanProviderPath}`)
|
|
||||||
await writeOutput(fullMizanProviderPath, mizanProvider)
|
|
||||||
}
|
|
||||||
|
|
||||||
if (mizanServer) {
|
|
||||||
console.log(`[mizan] Generating -> ${mizanServerPath}`)
|
|
||||||
await writeOutput(fullMizanServerPath, mizanServer)
|
|
||||||
}
|
|
||||||
|
|
||||||
if (mizanForms) {
|
|
||||||
console.log(`[mizan] Generating -> ${mizanFormsPath}`)
|
|
||||||
await writeOutput(fullMizanFormsPath, mizanForms)
|
|
||||||
}
|
|
||||||
|
|
||||||
console.log(`[mizan] Generating -> ${mizanSchemaPath}`)
|
|
||||||
await writeOutput(fullMizanSchemaPath, JSON.stringify(mizanSchema, null, 2))
|
|
||||||
} else {
|
|
||||||
console.log('[mizan] No mizan functions registered, skipping mizan generation')
|
|
||||||
}
|
|
||||||
} catch (err) {
|
|
||||||
console.log(`[mizan] mizan schema not available: ${err.message}`)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Generate consolidated index.ts
|
|
||||||
const indexPath = path.dirname(outputPath) + '/index.ts'
|
|
||||||
const fullIndexPath = path.resolve(frontendDir, indexPath)
|
|
||||||
|
|
||||||
console.log(`[mizan] Generating -> ${indexPath}`)
|
|
||||||
const indexContent = generateIndex({
|
|
||||||
channelsSchema,
|
|
||||||
mizanSchema,
|
|
||||||
})
|
|
||||||
await writeOutput(fullIndexPath, indexContent)
|
|
||||||
|
|
||||||
console.log('[mizan] Generation complete!')
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Watch for changes and regenerate.
|
|
||||||
*/
|
|
||||||
async function watch(config, options) {
|
|
||||||
const debounce = config.watch?.debounce || 1000
|
|
||||||
let timeout = null
|
|
||||||
let running = false
|
|
||||||
|
|
||||||
async function runGenerate() {
|
|
||||||
if (running) {
|
|
||||||
timeout = setTimeout(runGenerate, debounce)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
running = true
|
|
||||||
try {
|
try {
|
||||||
await generate(config, options)
|
console.log('[mizan] Fetching channels schema...')
|
||||||
|
channelsSchema = await fetchChannelsSchema(config.source, frontendDir)
|
||||||
|
const channelCount = channelsSchema['x-mizan-channels']?.length || 0
|
||||||
|
if (channelCount > 0 && targets.includes('react')) {
|
||||||
|
console.log(`[mizan] Found ${channelCount} channels`)
|
||||||
|
const { types, hooks } = await generateChannelsFiles(channelsSchema)
|
||||||
|
await writeOutput(path.join(fullOutputDir, 'channels.ts'), types)
|
||||||
|
if (hooks) await writeOutput(path.join(fullOutputDir, 'channels.hooks.tsx'), hooks)
|
||||||
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error('[mizan] Generation failed:', err.message)
|
console.log(`[mizan] Channels not available: ${err.message}`)
|
||||||
} finally {
|
|
||||||
running = false
|
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
await runGenerate()
|
// ── Mizan functions ─────────────────────────────────────────────────
|
||||||
|
|
||||||
console.log('[mizan] Watching for changes (press Ctrl+C to stop)...')
|
try {
|
||||||
|
console.log('[mizan] Fetching mizan schema...')
|
||||||
|
mizanSchema = await fetchMizanSchema(config.source, frontendDir)
|
||||||
|
|
||||||
if (config.source.django) {
|
const functions = mizanSchema['x-mizan-functions'] || []
|
||||||
const { watch: chokidarWatch } = await import('chokidar')
|
const contextGroups = mizanSchema['x-mizan-contexts'] || {}
|
||||||
const djangoDir = path.resolve(frontendDir, path.dirname(config.source.django.managePath))
|
|
||||||
|
|
||||||
const watcher = chokidarWatch([
|
if (functions.length === 0) {
|
||||||
path.join(djangoDir, '**/*.py'),
|
console.log('[mizan] No functions registered')
|
||||||
], {
|
return
|
||||||
ignored: [
|
}
|
||||||
'**/node_modules/**',
|
|
||||||
'**/__pycache__/**',
|
|
||||||
'**/migrations/**',
|
|
||||||
'**/.venv/**',
|
|
||||||
],
|
|
||||||
ignoreInitial: true,
|
|
||||||
})
|
|
||||||
|
|
||||||
watcher.on('change', (filePath) => {
|
console.log(`[mizan] Found ${functions.length} functions`)
|
||||||
console.log(`[mizan] Detected change: ${path.relative(djangoDir, filePath)}`)
|
|
||||||
if (timeout) clearTimeout(timeout)
|
|
||||||
timeout = setTimeout(runGenerate, debounce)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
process.on('SIGINT', () => {
|
// ── Stage 1: Framework-agnostic ─────────────────────────────────
|
||||||
console.log('\n[mizan] Stopping watch mode...')
|
|
||||||
process.exit(0)
|
// Types
|
||||||
})
|
const types = await generateTypes(mizanSchema)
|
||||||
|
await writeOutput(path.join(fullOutputDir, 'types.ts'), types)
|
||||||
|
console.log('[mizan] Stage 1 -> types.ts')
|
||||||
|
|
||||||
|
// Context files
|
||||||
|
await fs.mkdir(path.join(fullOutputDir, 'contexts'), { recursive: true })
|
||||||
|
for (const [ctxName, ctxMeta] of Object.entries(contextGroups)) {
|
||||||
|
const content = generateContextFile(ctxName, ctxMeta, functions)
|
||||||
|
await writeOutput(path.join(fullOutputDir, 'contexts', `${ctxName}.ts`), content)
|
||||||
|
console.log(`[mizan] Stage 1 -> contexts/${ctxName}.ts`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Mutation + function files
|
||||||
|
const regularFns = functions.filter(fn => !fn.isContext && !fn.isForm)
|
||||||
|
if (regularFns.length > 0) {
|
||||||
|
await fs.mkdir(path.join(fullOutputDir, 'mutations'), { recursive: true })
|
||||||
|
await fs.mkdir(path.join(fullOutputDir, 'functions'), { recursive: true })
|
||||||
|
|
||||||
|
for (const fn of regularFns) {
|
||||||
|
const dir = fn.affects ? 'mutations' : 'functions'
|
||||||
|
const content = fn.affects ? generateMutationFile(fn) : generateFunctionFile(fn)
|
||||||
|
await writeOutput(path.join(fullOutputDir, dir, `${fn.camelName}.ts`), content)
|
||||||
|
console.log(`[mizan] Stage 1 -> ${dir}/${fn.camelName}.ts`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Stage 1 index
|
||||||
|
const stage1Index = generateStage1Index(mizanSchema)
|
||||||
|
await writeOutput(path.join(fullOutputDir, 'index.ts'), stage1Index)
|
||||||
|
console.log('[mizan] Stage 1 -> index.ts')
|
||||||
|
|
||||||
|
// ── Stage 2: Framework-specific ─────────────────────────────────
|
||||||
|
|
||||||
|
for (const target of targets) {
|
||||||
|
let content
|
||||||
|
let filename
|
||||||
|
|
||||||
|
switch (target) {
|
||||||
|
case 'react':
|
||||||
|
content = generateReactAdapter(mizanSchema)
|
||||||
|
filename = 'react.tsx'
|
||||||
|
break
|
||||||
|
case 'vue':
|
||||||
|
content = generateVueAdapter(mizanSchema)
|
||||||
|
filename = 'vue.ts'
|
||||||
|
break
|
||||||
|
case 'svelte':
|
||||||
|
content = generateSvelteAdapter(mizanSchema)
|
||||||
|
filename = 'svelte.ts'
|
||||||
|
break
|
||||||
|
default:
|
||||||
|
console.warn(`[mizan] Unknown target: ${target}`)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
if (content) {
|
||||||
|
await writeOutput(path.join(fullOutputDir, filename), content)
|
||||||
|
console.log(`[mizan] Stage 2 -> ${filename}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Schema JSON
|
||||||
|
await writeOutput(
|
||||||
|
path.join(fullOutputDir, 'schema.json'),
|
||||||
|
JSON.stringify(mizanSchema, null, 2),
|
||||||
|
)
|
||||||
|
|
||||||
|
} catch (err) {
|
||||||
|
console.log(`[mizan] Schema not available: ${err.message}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('[mizan] Generation complete!')
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Main entry point.
|
|
||||||
*/
|
|
||||||
async function main() {
|
async function main() {
|
||||||
const args = process.argv.slice(2)
|
const args = process.argv.slice(2)
|
||||||
|
|
||||||
let configPath = 'django.config.mjs'
|
let configPath = 'django.config.mjs'
|
||||||
let watchMode = false
|
let watchMode = false
|
||||||
let output = null
|
let output = null
|
||||||
|
let target = null
|
||||||
|
|
||||||
for (let i = 0; i < args.length; i++) {
|
for (let i = 0; i < args.length; i++) {
|
||||||
if (args[i] === '--config' || args[i] === '-c') {
|
if (args[i] === '--config' || args[i] === '-c') configPath = args[++i]
|
||||||
configPath = args[++i]
|
else if (args[i] === '--watch' || args[i] === '-w') watchMode = true
|
||||||
} else if (args[i] === '--watch' || args[i] === '-w') {
|
else if (args[i] === '--output' || args[i] === '-o') output = args[++i]
|
||||||
watchMode = true
|
else if (args[i] === '--target' || args[i] === '-t') target = args[++i]
|
||||||
} else if (args[i] === '--output' || args[i] === '-o') {
|
else if (args[i] === '--help' || args[i] === '-h') {
|
||||||
output = args[++i]
|
console.log(`
|
||||||
} else if (args[i] === '--help' || args[i] === '-h') {
|
mizan Code Generator
|
||||||
console.log(`
|
|
||||||
mizan Code Generator - Generate TypeScript from Django schemas
|
|
||||||
|
|
||||||
Usage:
|
Usage:
|
||||||
npx mizan-generate [options]
|
npx mizan-generate [options]
|
||||||
|
|
||||||
Options:
|
Options:
|
||||||
-c, --config <path> Config file path (default: django.config.mjs)
|
-c, --config <path> Config file (default: django.config.mjs)
|
||||||
-w, --watch Watch mode - regenerate on changes
|
-t, --target <targets> Comma-separated: react,vue,svelte (default: react)
|
||||||
-o, --output <path> Output file path (overrides config)
|
-o, --output <dir> Output directory (default: src/api)
|
||||||
-h, --help Show this help message
|
-w, --watch Watch mode
|
||||||
`)
|
-h, --help Show help
|
||||||
process.exit(0)
|
`)
|
||||||
|
process.exit(0)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
const config = await loadConfig(configPath)
|
const config = await loadConfig(configPath)
|
||||||
const options = { output }
|
const options = { output, target }
|
||||||
|
|
||||||
if (watchMode) {
|
if (watchMode) {
|
||||||
await watch(config, options)
|
await generate(config, options)
|
||||||
} else {
|
console.log('[mizan] Watching for changes...')
|
||||||
await generate(config, options)
|
const { watch: chokidarWatch } = await import('chokidar')
|
||||||
}
|
if (config.source.django) {
|
||||||
|
const djangoDir = path.resolve(frontendDir, path.dirname(config.source.django.managePath))
|
||||||
|
let timeout = null
|
||||||
|
const watcher = chokidarWatch([path.join(djangoDir, '**/*.py')], {
|
||||||
|
ignored: ['**/node_modules/**', '**/__pycache__/**', '**/migrations/**'],
|
||||||
|
ignoreInitial: true,
|
||||||
|
})
|
||||||
|
watcher.on('change', () => {
|
||||||
|
if (timeout) clearTimeout(timeout)
|
||||||
|
timeout = setTimeout(() => generate(config, options), 1000)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
process.on('SIGINT', () => process.exit(0))
|
||||||
|
} else {
|
||||||
|
await generate(config, options)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
main().catch(err => {
|
main().catch(err => {
|
||||||
console.error('[mizan] Error:', err.message)
|
console.error('[mizan] Error:', err.message)
|
||||||
process.exit(1)
|
process.exit(1)
|
||||||
})
|
})
|
||||||
|
|||||||
160
packages/mizan-django/generate/generator/lib/adapters/react.mjs
Normal file
160
packages/mizan-django/generate/generator/lib/adapters/react.mjs
Normal file
@@ -0,0 +1,160 @@
|
|||||||
|
/**
|
||||||
|
* React Stage 2 — Generates hooks + context providers from Stage 1 output.
|
||||||
|
*/
|
||||||
|
|
||||||
|
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 globalContexts = 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 = [
|
||||||
|
"'use client'",
|
||||||
|
'',
|
||||||
|
'// AUTO-GENERATED by mizan — do not edit',
|
||||||
|
'',
|
||||||
|
"import { createContext, useContext, useState, useEffect, useCallback, type ReactNode } from 'react'",
|
||||||
|
"import { registerContext, mizanCall, mizanFetch } from '@mizan/runtime'",
|
||||||
|
'',
|
||||||
|
]
|
||||||
|
|
||||||
|
// Import from Stage 1
|
||||||
|
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('')
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Global context hooks ────────────────────────────────────────────
|
||||||
|
|
||||||
|
if (globalContexts.length > 0) {
|
||||||
|
const p = pascalCase('global')
|
||||||
|
|
||||||
|
lines.push(`// Global context — fetched once at app init`)
|
||||||
|
lines.push(`const GlobalCtx = createContext<${p}ContextData | null>(null)`)
|
||||||
|
lines.push('')
|
||||||
|
|
||||||
|
lines.push(`export function GlobalContextProvider({ children }: { children: ReactNode }) {`)
|
||||||
|
lines.push(` const [data, setData] = useState<${p}ContextData | null>(() => {`)
|
||||||
|
lines.push(` if (typeof window === 'undefined') return null`)
|
||||||
|
lines.push(` const ssr = (window as any).__MIZAN_SSR_DATA__`)
|
||||||
|
lines.push(` return ssr ?? null`)
|
||||||
|
lines.push(` })`)
|
||||||
|
lines.push('')
|
||||||
|
lines.push(` const refetch = useCallback(async () => {`)
|
||||||
|
lines.push(` const result = await fetch${p}Context({} as any)`)
|
||||||
|
lines.push(` setData(result)`)
|
||||||
|
lines.push(` }, [])`)
|
||||||
|
lines.push('')
|
||||||
|
lines.push(` useEffect(() => { if (!data) refetch() }, [data, refetch])`)
|
||||||
|
lines.push(` useEffect(() => registerContext('global', {}, refetch), [refetch])`)
|
||||||
|
lines.push('')
|
||||||
|
lines.push(` return <GlobalCtx.Provider value={data}>{children}</GlobalCtx.Provider>`)
|
||||||
|
lines.push('}')
|
||||||
|
lines.push('')
|
||||||
|
|
||||||
|
for (const fn of globalContexts) {
|
||||||
|
const hookPascal = pascalCase(fn.camelName)
|
||||||
|
lines.push(`export function use${hookPascal}(): ${fn.outputType} {`)
|
||||||
|
lines.push(` const ctx = useContext(GlobalCtx)`)
|
||||||
|
lines.push(` if (!ctx) throw new Error('use${hookPascal} requires GlobalContextProvider')`)
|
||||||
|
lines.push(` return ctx.${fn.name}`)
|
||||||
|
lines.push('}')
|
||||||
|
lines.push('')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Named context providers ─────────────────────────────────────────
|
||||||
|
|
||||||
|
for (const [ctxName, ctxMeta] of namedContexts) {
|
||||||
|
const p = pascalCase(ctxName)
|
||||||
|
const ctxFunctions = functions.filter(fn => fn.isContext === ctxName)
|
||||||
|
const paramEntries = Object.entries(ctxMeta.params || {})
|
||||||
|
|
||||||
|
lines.push(`// ${p} context`)
|
||||||
|
lines.push(`const ${p}Ctx = createContext<${p}ContextData | null>(null)`)
|
||||||
|
lines.push('')
|
||||||
|
|
||||||
|
// Provider
|
||||||
|
lines.push(`export function ${p}Context({ children, ...params }: ${p}ContextParams & { children: ReactNode }) {`)
|
||||||
|
lines.push(` const [data, setData] = useState<${p}ContextData | null>(() => {`)
|
||||||
|
lines.push(` if (typeof window === 'undefined') return null`)
|
||||||
|
lines.push(` const ssr = (window as any).__MIZAN_SSR_DATA__`)
|
||||||
|
if (ctxFunctions.length > 0) {
|
||||||
|
lines.push(` if (ssr?.${ctxFunctions[0].name} !== undefined) return ssr`)
|
||||||
|
}
|
||||||
|
lines.push(` return null`)
|
||||||
|
lines.push(` })`)
|
||||||
|
lines.push('')
|
||||||
|
lines.push(` const refetch = useCallback(async () => {`)
|
||||||
|
lines.push(` const result = await fetch${p}Context(params)`)
|
||||||
|
lines.push(` setData(result)`)
|
||||||
|
|
||||||
|
const deps = paramEntries.map(([pName]) => `params.${pName}`)
|
||||||
|
lines.push(` }, [${deps.join(', ')}])`)
|
||||||
|
lines.push('')
|
||||||
|
lines.push(` useEffect(() => { refetch() }, [refetch])`)
|
||||||
|
lines.push(` useEffect(() => registerContext('${ctxName}', params, refetch), [${deps.join(', ')}, refetch])`)
|
||||||
|
lines.push('')
|
||||||
|
lines.push(` return <${p}Ctx.Provider value={data}>{children}</${p}Ctx.Provider>`)
|
||||||
|
lines.push('}')
|
||||||
|
lines.push('')
|
||||||
|
|
||||||
|
// Hooks
|
||||||
|
for (const fn of ctxFunctions) {
|
||||||
|
const hookPascal = pascalCase(fn.camelName)
|
||||||
|
lines.push(`export function use${hookPascal}(): ${fn.outputType} | null {`)
|
||||||
|
lines.push(` const ctx = useContext(${p}Ctx)`)
|
||||||
|
lines.push(` return ctx?.${fn.name} ?? null`)
|
||||||
|
lines.push('}')
|
||||||
|
lines.push('')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Mutation hooks ──────────────────────────────────────────────────
|
||||||
|
|
||||||
|
for (const fn of mutations) {
|
||||||
|
const p = pascalCase(fn.camelName)
|
||||||
|
if (fn.hasInput) {
|
||||||
|
lines.push(`export function use${p}() {`)
|
||||||
|
lines.push(` return useCallback((args: Parameters<typeof call${p}>[0]) => call${p}(args), [])`)
|
||||||
|
lines.push('}')
|
||||||
|
} else {
|
||||||
|
lines.push(`export function use${p}() {`)
|
||||||
|
lines.push(` return useCallback(() => call${p}(), [])`)
|
||||||
|
lines.push('}')
|
||||||
|
}
|
||||||
|
lines.push('')
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Plain function hooks ────────────────────────────────────────────
|
||||||
|
|
||||||
|
for (const fn of plainFns) {
|
||||||
|
const p = pascalCase(fn.camelName)
|
||||||
|
if (fn.hasInput) {
|
||||||
|
lines.push(`export function use${p}() {`)
|
||||||
|
lines.push(` return useCallback((args: Parameters<typeof call${p}>[0]) => call${p}(args), [])`)
|
||||||
|
lines.push('}')
|
||||||
|
} else {
|
||||||
|
lines.push(`export function use${p}() {`)
|
||||||
|
lines.push(` return useCallback(() => call${p}(), [])`)
|
||||||
|
lines.push('}')
|
||||||
|
}
|
||||||
|
lines.push('')
|
||||||
|
}
|
||||||
|
|
||||||
|
return lines.join('\n')
|
||||||
|
}
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
/**
|
||||||
|
* Svelte Stage 2 — Generates stores from Stage 1 output.
|
||||||
|
*/
|
||||||
|
|
||||||
|
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 { writable, derived, type Readable } from 'svelte/store'",
|
||||||
|
"import { registerContext } from '@mizan/runtime'",
|
||||||
|
'',
|
||||||
|
]
|
||||||
|
|
||||||
|
// Stage 1 imports
|
||||||
|
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('')
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Context stores ──────────────────────────────────────────────────
|
||||||
|
|
||||||
|
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 || {})
|
||||||
|
|
||||||
|
lines.push(`// ${p} context`)
|
||||||
|
|
||||||
|
if (paramEntries.length > 0) {
|
||||||
|
lines.push(`export function create${p}Context(params: ${p}ContextParams) {`)
|
||||||
|
} else {
|
||||||
|
lines.push(`export function create${p}Context() {`)
|
||||||
|
}
|
||||||
|
|
||||||
|
lines.push(` const data = writable<${p}ContextData | null>(null)`)
|
||||||
|
lines.push(` const loading = writable(true)`)
|
||||||
|
lines.push('')
|
||||||
|
lines.push(` const refetch = async () => {`)
|
||||||
|
lines.push(` loading.set(true)`)
|
||||||
|
if (paramEntries.length > 0) {
|
||||||
|
lines.push(` const result = await fetch${p}Context(params)`)
|
||||||
|
} else {
|
||||||
|
lines.push(` const result = await fetch${p}Context({} as any)`)
|
||||||
|
}
|
||||||
|
lines.push(` data.set(result)`)
|
||||||
|
lines.push(` loading.set(false)`)
|
||||||
|
lines.push(` }`)
|
||||||
|
lines.push('')
|
||||||
|
lines.push(` refetch()`)
|
||||||
|
if (paramEntries.length > 0) {
|
||||||
|
lines.push(` const unregister = registerContext('${ctxName}', params, refetch)`)
|
||||||
|
} else {
|
||||||
|
lines.push(` const unregister = registerContext('${ctxName}', {}, refetch)`)
|
||||||
|
}
|
||||||
|
lines.push('')
|
||||||
|
|
||||||
|
// Derived stores for each function
|
||||||
|
lines.push(` return {`)
|
||||||
|
lines.push(` data,`)
|
||||||
|
lines.push(` loading,`)
|
||||||
|
for (const fn of ctxFunctions) {
|
||||||
|
const camel = fn.camelName
|
||||||
|
lines.push(` ${camel}: derived(data, $d => $d?.${fn.name} ?? null) as Readable<${fn.outputType} | null>,`)
|
||||||
|
}
|
||||||
|
lines.push(` destroy: unregister,`)
|
||||||
|
lines.push(` }`)
|
||||||
|
lines.push('}')
|
||||||
|
lines.push('')
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Mutation + function exports ─────────────────────────────────────
|
||||||
|
|
||||||
|
for (const fn of [...mutations, ...plainFns]) {
|
||||||
|
const p = pascalCase(fn.camelName)
|
||||||
|
lines.push(`export { call${p} } from '../${fn.affects ? 'mutations' : 'functions'}/${fn.camelName}'`)
|
||||||
|
}
|
||||||
|
lines.push('')
|
||||||
|
|
||||||
|
return lines.join('\n')
|
||||||
|
}
|
||||||
105
packages/mizan-django/generate/generator/lib/adapters/vue.mjs
Normal file
105
packages/mizan-django/generate/generator/lib/adapters/vue.mjs
Normal file
@@ -0,0 +1,105 @@
|
|||||||
|
/**
|
||||||
|
* Vue Stage 2 — Generates composables from Stage 1 output.
|
||||||
|
*/
|
||||||
|
|
||||||
|
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, watch, onMounted, onUnmounted, provide, inject, type Ref, type ComputedRef, type InjectionKey } from 'vue'",
|
||||||
|
"import { registerContext } from '@mizan/runtime'",
|
||||||
|
'',
|
||||||
|
]
|
||||||
|
|
||||||
|
// Stage 1 imports
|
||||||
|
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('')
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Context composables ─────────────────────────────────────────────
|
||||||
|
|
||||||
|
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 || {})
|
||||||
|
|
||||||
|
lines.push(`// ${p} context`)
|
||||||
|
lines.push(`const ${p}Key: InjectionKey<{ data: Ref<${p}ContextData | null>, loading: Ref<boolean> }> = Symbol('${ctxName}')`)
|
||||||
|
lines.push('')
|
||||||
|
|
||||||
|
// Provider composable
|
||||||
|
if (paramEntries.length > 0) {
|
||||||
|
lines.push(`export function provide${p}Context(params: { ${paramEntries.map(([k, v]) => `${k}: ${v.type === 'integer' || v.type === 'number' ? 'number' : 'string'}`).join(', ')} }) {`)
|
||||||
|
} else {
|
||||||
|
lines.push(`export function provide${p}Context() {`)
|
||||||
|
}
|
||||||
|
lines.push(` const data = ref<${p}ContextData | null>(null)`)
|
||||||
|
lines.push(` const loading = ref(true)`)
|
||||||
|
lines.push('')
|
||||||
|
lines.push(` const refetch = async () => {`)
|
||||||
|
lines.push(` loading.value = true`)
|
||||||
|
lines.push(` try {`)
|
||||||
|
if (paramEntries.length > 0) {
|
||||||
|
lines.push(` data.value = await fetch${p}Context(params as any)`)
|
||||||
|
} else {
|
||||||
|
lines.push(` data.value = await fetch${p}Context({} as any)`)
|
||||||
|
}
|
||||||
|
lines.push(` } catch (e) { console.error('[mizan] ${ctxName} fetch failed:', e) }`)
|
||||||
|
lines.push(` loading.value = false`)
|
||||||
|
lines.push(` }`)
|
||||||
|
lines.push('')
|
||||||
|
lines.push(` let unregister: (() => void) | null = null`)
|
||||||
|
lines.push(` onMounted(() => {`)
|
||||||
|
lines.push(` refetch()`)
|
||||||
|
if (paramEntries.length > 0) {
|
||||||
|
lines.push(` unregister = registerContext('${ctxName}', params, refetch)`)
|
||||||
|
} else {
|
||||||
|
lines.push(` unregister = registerContext('${ctxName}', {}, refetch)`)
|
||||||
|
}
|
||||||
|
lines.push(` })`)
|
||||||
|
lines.push(` onUnmounted(() => { unregister?.() })`)
|
||||||
|
lines.push('')
|
||||||
|
lines.push(` provide(${p}Key, { data, loading })`)
|
||||||
|
lines.push('}')
|
||||||
|
lines.push('')
|
||||||
|
|
||||||
|
// Consumer composables
|
||||||
|
for (const fn of ctxFunctions) {
|
||||||
|
const hookPascal = pascalCase(fn.camelName)
|
||||||
|
lines.push(`export function use${hookPascal}(): ComputedRef<${fn.outputType} | null> {`)
|
||||||
|
lines.push(` const ctx = inject(${p}Key)`)
|
||||||
|
lines.push(` if (!ctx) throw new Error('use${hookPascal} requires provide${p}Context in a parent')`)
|
||||||
|
lines.push(` return computed(() => ctx.data.value?.${fn.name} ?? null)`)
|
||||||
|
lines.push('}')
|
||||||
|
lines.push('')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Mutation composables ────────────────────────────────────────────
|
||||||
|
|
||||||
|
for (const fn of [...mutations, ...plainFns]) {
|
||||||
|
const p = pascalCase(fn.camelName)
|
||||||
|
lines.push(`export const use${p} = call${p}`)
|
||||||
|
lines.push('')
|
||||||
|
}
|
||||||
|
|
||||||
|
return lines.join('\n')
|
||||||
|
}
|
||||||
198
packages/mizan-django/generate/generator/lib/stage1.mjs
Normal file
198
packages/mizan-django/generate/generator/lib/stage1.mjs
Normal file
@@ -0,0 +1,198 @@
|
|||||||
|
/**
|
||||||
|
* Stage 1 Codegen — Framework-agnostic TypeScript output.
|
||||||
|
*
|
||||||
|
* Produces:
|
||||||
|
* types.ts — interfaces from OpenAPI schema
|
||||||
|
* contexts/<name>.ts — fetchXxxContext(params) per context group
|
||||||
|
* mutations/<name>.ts — callXxx(args) per mutation
|
||||||
|
* functions/<name>.ts — callXxx(args) per plain function
|
||||||
|
* index.ts — re-exports
|
||||||
|
*/
|
||||||
|
|
||||||
|
import openapiTS, { astToString } from 'openapi-typescript'
|
||||||
|
|
||||||
|
// ─── Helpers ────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
function pascalCase(str) {
|
||||||
|
return str
|
||||||
|
.split(/[.\-_]/)
|
||||||
|
.map(part => part.charAt(0).toUpperCase() + part.slice(1))
|
||||||
|
.join('')
|
||||||
|
}
|
||||||
|
|
||||||
|
function camelCase(str) {
|
||||||
|
const p = pascalCase(str)
|
||||||
|
return p.charAt(0).toLowerCase() + p.slice(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
// TypeScript SyntaxKind values for openapi-typescript AST
|
||||||
|
const SyntaxKind = {
|
||||||
|
InterfaceDeclaration: 265,
|
||||||
|
PropertySignature: 172,
|
||||||
|
Identifier: 80,
|
||||||
|
}
|
||||||
|
|
||||||
|
function idName(node) {
|
||||||
|
return node?.kind === SyntaxKind.Identifier ? node.escapedText : undefined
|
||||||
|
}
|
||||||
|
|
||||||
|
function getSchemaNamesFromAst(ast) {
|
||||||
|
if (!Array.isArray(ast)) return []
|
||||||
|
const componentsNode = ast.find(
|
||||||
|
n => n?.kind === SyntaxKind.InterfaceDeclaration && idName(n?.name) === 'components'
|
||||||
|
)
|
||||||
|
if (!componentsNode?.members) return []
|
||||||
|
const schemasProp = componentsNode.members.find(
|
||||||
|
m => m?.kind === SyntaxKind.PropertySignature && idName(m?.name) === 'schemas' && Array.isArray(m?.type?.members)
|
||||||
|
)
|
||||||
|
if (!schemasProp) return []
|
||||||
|
return schemasProp.type.members
|
||||||
|
.map(m => m?.kind === SyntaxKind.PropertySignature ? idName(m.name) : undefined)
|
||||||
|
.filter(n => typeof n === 'string')
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Types ──────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export async function generateTypes(schema) {
|
||||||
|
const ast = await openapiTS(schema)
|
||||||
|
const schemaNames = getSchemaNamesFromAst(ast)
|
||||||
|
const typesCode = astToString(ast)
|
||||||
|
|
||||||
|
const lines = [
|
||||||
|
'// AUTO-GENERATED by mizan — do not edit',
|
||||||
|
'',
|
||||||
|
typesCode,
|
||||||
|
'',
|
||||||
|
'// Convenience type exports',
|
||||||
|
...schemaNames.map(name => `export type ${name} = components["schemas"]["${name}"]`),
|
||||||
|
'',
|
||||||
|
]
|
||||||
|
|
||||||
|
return lines.join('\n')
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Context Files ──────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export function generateContextFile(ctxName, ctxMeta, functions) {
|
||||||
|
const pascal = pascalCase(ctxName)
|
||||||
|
const ctxFunctions = functions.filter(fn => fn.isContext === ctxName)
|
||||||
|
|
||||||
|
const lines = [
|
||||||
|
'// AUTO-GENERATED by mizan — do not edit',
|
||||||
|
'',
|
||||||
|
"import { mizanFetch } from '@mizan/runtime'",
|
||||||
|
'',
|
||||||
|
]
|
||||||
|
|
||||||
|
// Import output types
|
||||||
|
const typeImports = ctxFunctions.map(fn => fn.outputType).filter(Boolean)
|
||||||
|
if (typeImports.length > 0) {
|
||||||
|
lines.push(`import type { ${[...new Set(typeImports)].join(', ')} } from '../types'`)
|
||||||
|
lines.push('')
|
||||||
|
}
|
||||||
|
|
||||||
|
// Data interface
|
||||||
|
lines.push(`export interface ${pascal}ContextData {`)
|
||||||
|
for (const fn of ctxFunctions) {
|
||||||
|
lines.push(` ${fn.name}: ${fn.outputType}`)
|
||||||
|
}
|
||||||
|
lines.push('}')
|
||||||
|
lines.push('')
|
||||||
|
|
||||||
|
// Params interface (from x-mizan-contexts)
|
||||||
|
const params = ctxMeta?.params || {}
|
||||||
|
const paramEntries = Object.entries(params)
|
||||||
|
|
||||||
|
if (paramEntries.length > 0) {
|
||||||
|
lines.push(`export interface ${pascal}ContextParams {`)
|
||||||
|
for (const [pName, pMeta] of paramEntries) {
|
||||||
|
const tsType = pMeta.type === 'integer' || pMeta.type === 'number' ? 'number' : pMeta.type === 'boolean' ? 'boolean' : 'string'
|
||||||
|
const optional = pMeta.required ? '' : '?'
|
||||||
|
lines.push(` ${pName}${optional}: ${tsType}`)
|
||||||
|
}
|
||||||
|
lines.push('}')
|
||||||
|
} else {
|
||||||
|
lines.push(`export type ${pascal}ContextParams = Record<string, never>`)
|
||||||
|
}
|
||||||
|
lines.push('')
|
||||||
|
|
||||||
|
// Fetch function
|
||||||
|
lines.push(`export function fetch${pascal}Context(params: ${pascal}ContextParams): Promise<${pascal}ContextData> {`)
|
||||||
|
lines.push(` return mizanFetch('${ctxName}', params)`)
|
||||||
|
lines.push('}')
|
||||||
|
lines.push('')
|
||||||
|
|
||||||
|
return lines.join('\n')
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Mutation Files ─────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export function generateMutationFile(fn) {
|
||||||
|
const pascal = pascalCase(fn.camelName)
|
||||||
|
|
||||||
|
const lines = [
|
||||||
|
'// AUTO-GENERATED by mizan — do not edit',
|
||||||
|
'',
|
||||||
|
"import { mizanCall } from '@mizan/runtime'",
|
||||||
|
'',
|
||||||
|
]
|
||||||
|
|
||||||
|
// Import types
|
||||||
|
const typeImports = []
|
||||||
|
if (fn.hasInput && fn.inputType) typeImports.push(fn.inputType)
|
||||||
|
if (fn.outputType) typeImports.push(fn.outputType)
|
||||||
|
if (typeImports.length > 0) {
|
||||||
|
lines.push(`import type { ${[...new Set(typeImports)].join(', ')} } from '../types'`)
|
||||||
|
lines.push('')
|
||||||
|
}
|
||||||
|
|
||||||
|
// Call function
|
||||||
|
if (fn.hasInput) {
|
||||||
|
lines.push(`export function call${pascal}(args: ${fn.inputType}): Promise<${fn.outputType}> {`)
|
||||||
|
} else {
|
||||||
|
lines.push(`export function call${pascal}(): Promise<${fn.outputType}> {`)
|
||||||
|
}
|
||||||
|
lines.push(` return mizanCall('${fn.name}', ${fn.hasInput ? 'args' : '{}'})`)
|
||||||
|
lines.push('}')
|
||||||
|
lines.push('')
|
||||||
|
|
||||||
|
return lines.join('\n')
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Function Files (plain, no context, no affects) ─────────────────────────
|
||||||
|
|
||||||
|
export function generateFunctionFile(fn) {
|
||||||
|
// Same shape as mutation, just different semantics
|
||||||
|
return generateMutationFile(fn)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Index ──────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export function generateStage1Index(schema) {
|
||||||
|
const functions = schema['x-mizan-functions'] || []
|
||||||
|
const contextGroups = schema['x-mizan-contexts'] || {}
|
||||||
|
|
||||||
|
const lines = [
|
||||||
|
'// AUTO-GENERATED by mizan — do not edit',
|
||||||
|
'',
|
||||||
|
"export * from './types'",
|
||||||
|
'',
|
||||||
|
]
|
||||||
|
|
||||||
|
// Context exports
|
||||||
|
for (const ctxName of Object.keys(contextGroups)) {
|
||||||
|
const pascal = pascalCase(ctxName)
|
||||||
|
lines.push(`export { fetch${pascal}Context, type ${pascal}ContextData, type ${pascal}ContextParams } from './contexts/${ctxName}'`)
|
||||||
|
}
|
||||||
|
if (Object.keys(contextGroups).length > 0) lines.push('')
|
||||||
|
|
||||||
|
// Mutation + function exports
|
||||||
|
const regularFns = functions.filter(fn => !fn.isContext && !fn.isForm)
|
||||||
|
for (const fn of regularFns) {
|
||||||
|
const pascal = pascalCase(fn.camelName)
|
||||||
|
lines.push(`export { call${pascal} } from './${fn.affects ? 'mutations' : 'functions'}/${fn.camelName}'`)
|
||||||
|
}
|
||||||
|
if (regularFns.length > 0) lines.push('')
|
||||||
|
|
||||||
|
return lines.join('\n')
|
||||||
|
}
|
||||||
11
packages/mizan-runtime/package.json
Normal file
11
packages/mizan-runtime/package.json
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
{
|
||||||
|
"name": "@mizan/runtime",
|
||||||
|
"version": "0.1.0",
|
||||||
|
"description": "Mizan client runtime — context registry, invalidation, fetch. Zero framework dependencies.",
|
||||||
|
"type": "module",
|
||||||
|
"main": "src/index.ts",
|
||||||
|
"exports": {
|
||||||
|
".": "./src/index.ts"
|
||||||
|
},
|
||||||
|
"license": "MIT"
|
||||||
|
}
|
||||||
204
packages/mizan-runtime/src/index.ts
Normal file
204
packages/mizan-runtime/src/index.ts
Normal file
@@ -0,0 +1,204 @@
|
|||||||
|
/**
|
||||||
|
* @mizan/runtime — The client state kernel.
|
||||||
|
*
|
||||||
|
* Zero framework dependencies. React, Vue, Svelte — all import from here.
|
||||||
|
*
|
||||||
|
* Four concerns:
|
||||||
|
* 1. Configuration — baseUrl, auth headers, CSRF
|
||||||
|
* 2. Context registry — mounted providers register for invalidation
|
||||||
|
* 3. Invalidation — microtask-batched, scoped or broad
|
||||||
|
* 4. Fetch — mizanFetch (GET context bundles) + mizanCall (POST mutations)
|
||||||
|
*/
|
||||||
|
|
||||||
|
// === Error ===
|
||||||
|
|
||||||
|
export class MizanError extends Error {
|
||||||
|
constructor(public status: number, public body: string) {
|
||||||
|
super(`Mizan call failed (${status})`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// === Configuration ===
|
||||||
|
|
||||||
|
interface MizanConfig {
|
||||||
|
baseUrl: string
|
||||||
|
getHeaders: () => Record<string, string> | Promise<Record<string, string>>
|
||||||
|
csrfCookieName: string
|
||||||
|
csrfHeaderName: string
|
||||||
|
}
|
||||||
|
|
||||||
|
const config: MizanConfig = {
|
||||||
|
baseUrl: '/api/mizan',
|
||||||
|
getHeaders: () => ({}),
|
||||||
|
csrfCookieName: 'csrftoken',
|
||||||
|
csrfHeaderName: 'X-CSRFToken',
|
||||||
|
}
|
||||||
|
|
||||||
|
export function configure(opts: Partial<MizanConfig>): void {
|
||||||
|
Object.assign(config, opts)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getConfig(): Readonly<MizanConfig> {
|
||||||
|
return config
|
||||||
|
}
|
||||||
|
|
||||||
|
// === CSRF ===
|
||||||
|
|
||||||
|
function getCSRFToken(): string | null {
|
||||||
|
if (typeof document === 'undefined') return null
|
||||||
|
const match = document.cookie.match(new RegExp(`${config.csrfCookieName}=([^;]+)`))
|
||||||
|
return match?.[1] ?? null
|
||||||
|
}
|
||||||
|
|
||||||
|
// === Session Init ===
|
||||||
|
|
||||||
|
let _sessionReady: Promise<void> | null = null
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Initialize a session (fetches CSRF cookie from GET /session/).
|
||||||
|
* Called automatically on first fetch if not called explicitly.
|
||||||
|
* No-op if a CSRF cookie already exists.
|
||||||
|
*/
|
||||||
|
export function initSession(): Promise<void> {
|
||||||
|
if (_sessionReady) return _sessionReady
|
||||||
|
|
||||||
|
_sessionReady = (async () => {
|
||||||
|
// If we already have a CSRF token, skip
|
||||||
|
if (getCSRFToken()) return
|
||||||
|
|
||||||
|
try {
|
||||||
|
await fetch(`${config.baseUrl}/session/`, { credentials: 'include' })
|
||||||
|
} catch (e) {
|
||||||
|
console.error('[mizan] Session init failed:', e)
|
||||||
|
}
|
||||||
|
})()
|
||||||
|
|
||||||
|
return _sessionReady
|
||||||
|
}
|
||||||
|
|
||||||
|
// === Context Registry ===
|
||||||
|
|
||||||
|
export type RefetchFn = () => void
|
||||||
|
type ParamKey = string
|
||||||
|
|
||||||
|
interface ContextEntry {
|
||||||
|
params: Record<string, any>
|
||||||
|
refetch: RefetchFn
|
||||||
|
}
|
||||||
|
|
||||||
|
const contexts: Map<string, Map<ParamKey, ContextEntry>> = new Map()
|
||||||
|
|
||||||
|
export function registerContext(
|
||||||
|
name: string,
|
||||||
|
params: Record<string, any>,
|
||||||
|
refetch: RefetchFn,
|
||||||
|
): () => void {
|
||||||
|
if (!contexts.has(name)) contexts.set(name, new Map())
|
||||||
|
const key = JSON.stringify(params)
|
||||||
|
contexts.get(name)!.set(key, { params, refetch })
|
||||||
|
return () => contexts.get(name)!.delete(key)
|
||||||
|
}
|
||||||
|
|
||||||
|
// === Invalidation ===
|
||||||
|
|
||||||
|
const pending: Set<string> = new Set()
|
||||||
|
const pendingScoped: Map<string, Record<string, any>> = new Map()
|
||||||
|
let scheduled = false
|
||||||
|
|
||||||
|
export function invalidate(context: string, params?: Record<string, any>): void {
|
||||||
|
if (params) {
|
||||||
|
pendingScoped.set(context, params)
|
||||||
|
} else {
|
||||||
|
pending.add(context)
|
||||||
|
}
|
||||||
|
if (!scheduled) {
|
||||||
|
scheduled = true
|
||||||
|
queueMicrotask(flush)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function flush(): void {
|
||||||
|
for (const name of pending) {
|
||||||
|
const entries = contexts.get(name)
|
||||||
|
if (entries) entries.forEach(entry => entry.refetch())
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const [name, params] of pendingScoped) {
|
||||||
|
if (pending.has(name)) continue
|
||||||
|
const entries = contexts.get(name)
|
||||||
|
if (!entries) continue
|
||||||
|
const key = JSON.stringify(params)
|
||||||
|
const entry = entries.get(key)
|
||||||
|
if (entry) entry.refetch()
|
||||||
|
}
|
||||||
|
|
||||||
|
pending.clear()
|
||||||
|
pendingScoped.clear()
|
||||||
|
scheduled = false
|
||||||
|
}
|
||||||
|
|
||||||
|
// === Fetch ===
|
||||||
|
|
||||||
|
async function resolveHeaders(): Promise<Record<string, string>> {
|
||||||
|
await initSession()
|
||||||
|
|
||||||
|
const custom = await config.getHeaders()
|
||||||
|
const csrf = getCSRFToken()
|
||||||
|
|
||||||
|
return {
|
||||||
|
...custom,
|
||||||
|
...(csrf ? { [config.csrfHeaderName]: csrf } : {}),
|
||||||
|
'Accept': 'application/json',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function mizanFetch(
|
||||||
|
contextName: string,
|
||||||
|
params?: Record<string, any>,
|
||||||
|
): Promise<any> {
|
||||||
|
const url = new URL(
|
||||||
|
`${config.baseUrl}/ctx/${contextName}/`,
|
||||||
|
typeof globalThis.location !== 'undefined' ? globalThis.location.origin : 'http://localhost',
|
||||||
|
)
|
||||||
|
if (params) {
|
||||||
|
for (const [k, v] of Object.entries(params)) {
|
||||||
|
url.searchParams.set(k, String(v))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const headers = await resolveHeaders()
|
||||||
|
const res = await fetch(url.toString(), { headers, credentials: 'same-origin' })
|
||||||
|
if (!res.ok) throw new MizanError(res.status, await res.text())
|
||||||
|
return res.json()
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function mizanCall(
|
||||||
|
functionName: string,
|
||||||
|
args: Record<string, any>,
|
||||||
|
): Promise<any> {
|
||||||
|
const headers = await resolveHeaders()
|
||||||
|
headers['Content-Type'] = 'application/json'
|
||||||
|
|
||||||
|
const res = await fetch(`${config.baseUrl}/call/`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers,
|
||||||
|
credentials: 'same-origin',
|
||||||
|
body: JSON.stringify({ fn: functionName, args }),
|
||||||
|
})
|
||||||
|
if (!res.ok) throw new MizanError(res.status, await res.text())
|
||||||
|
|
||||||
|
const data = await res.json()
|
||||||
|
|
||||||
|
// Server-driven invalidation
|
||||||
|
if (data.invalidate) {
|
||||||
|
for (const entry of data.invalidate) {
|
||||||
|
if (typeof entry === 'string') {
|
||||||
|
invalidate(entry)
|
||||||
|
} else {
|
||||||
|
invalidate(entry.context, entry.params)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return data.result
|
||||||
|
}
|
||||||
11
packages/mizan-svelte/package.json
Normal file
11
packages/mizan-svelte/package.json
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
{
|
||||||
|
"name": "@mizan/svelte",
|
||||||
|
"version": "0.1.0",
|
||||||
|
"description": "Mizan Svelte adapter — stores generated from @mizan/runtime.",
|
||||||
|
"type": "module",
|
||||||
|
"peerDependencies": {
|
||||||
|
"svelte": ">=4",
|
||||||
|
"@mizan/runtime": ">=0.1.0"
|
||||||
|
},
|
||||||
|
"license": "MIT"
|
||||||
|
}
|
||||||
11
packages/mizan-vue/package.json
Normal file
11
packages/mizan-vue/package.json
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
{
|
||||||
|
"name": "@mizan/vue",
|
||||||
|
"version": "0.1.0",
|
||||||
|
"description": "Mizan Vue adapter — composables generated from @mizan/runtime.",
|
||||||
|
"type": "module",
|
||||||
|
"peerDependencies": {
|
||||||
|
"vue": ">=3",
|
||||||
|
"@mizan/runtime": ">=0.1.0"
|
||||||
|
},
|
||||||
|
"license": "MIT"
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user