+
+ The .idea file format is a declarative schema definition
+ language designed to simplify application development by
+ providing a single source of truth for data structures,
+ relationships, and code generation.
+
+
+
+
+ >
+ )
+}
\ No newline at end of file
diff --git a/packages/www/plugins/app/components/landing-page/AudienceSection.tsx b/packages/www/plugins/app/components/landing-page/AudienceSection.tsx
new file mode 100644
index 0000000..3558038
--- /dev/null
+++ b/packages/www/plugins/app/components/landing-page/AudienceSection.tsx
@@ -0,0 +1,103 @@
+//modules
+import { Translate, useLanguage } from 'r22n';
+
+export default function AudienceSection() {
+ //hooks
+ const { _ } = useLanguage();
+ return (
+ <>
+ {/* Audience Section Content */}
+
+
+ {_('Who Should Use This?')}
+
+
+
+
+
+
+
+
+
+ {_('Junior Developers')}
+
+
+
+
+
+ Easy-to-understand syntax with examples
+
+
+
+
+ Rapid prototyping without deep framework knowledge
+
+
+
+
+
+
+
+
+
+
+
+ {_('Senior Developers')}
+
+
+
+
+
+ Powerful features for complex apps
+
+
+
+
+ Extensible plugin system
+
+
+
+
+ Cross-platform code generation
+
+
+
+
+
+
+
+
+
+
+
+ {_('CTOs & Leaders')}
+
+
+
+
+
+ Reduce dev time by 60–80%
+
+
+
+
+ Improve code consistency across teams
+
+
+
+
+ Lower maintenance costs
+
+
+
+
+ Accelerate time-to-market
+
+
+
+
+
+
+ >
+ )
+}
\ No newline at end of file
diff --git a/packages/www/plugins/app/components/landing-page/BenefitsSection.tsx b/packages/www/plugins/app/components/landing-page/BenefitsSection.tsx
new file mode 100644
index 0000000..a7a0f0e
--- /dev/null
+++ b/packages/www/plugins/app/components/landing-page/BenefitsSection.tsx
@@ -0,0 +1,97 @@
+//modules
+import { Translate, useLanguage } from 'r22n';
+import clsx from 'clsx';
+
+//benefit cards data
+//--------------------------------------------------------------------//
+
+const benefitCards = [
+ {
+ title: 'Single Source of Truth',
+ desc: 'One schema powers DB, types, APIs, docs, and forms.',
+ icon: 'fa-bullseye',
+ color: 'text-green-400'
+ },
+ {
+ title: 'Type Safety Everywhere',
+ desc: 'Consistent, type‑safe code across languages and frameworks.',
+ icon: 'fa-shield-halved',
+ color: 'text-blue-400'
+ },
+ {
+ title: 'Rapid Development',
+ desc: 'Generate boilerplate, forms, and docs in seconds.',
+ icon: 'fa-bolt',
+ color: 'text-purple-400'
+ },
+ {
+ title: 'Perfect Consistency',
+ desc: 'Update the schema once—everything stays in sync.',
+ icon: 'fa-arrows-rotate',
+ color: 'text-yellow-400'
+ },
+ {
+ title: 'Extensible by Plugins',
+ desc: 'Target any framework or language with custom generators.',
+ icon: 'fa-plug',
+ color: 'text-pink-400'
+ },
+ {
+ title: 'AI‑to‑Code Bridge',
+ desc: 'Describe your model, generate production‑ready code.',
+ icon: 'fa-robot',
+ color: 'text-teal-400'
+ }
+];
+
+//--------------------------------------------------------------------//
+
+export default function BenefitsSection() {
+ //hooks
+ const { _ } = useLanguage();
+ return (
+ <>
+ {/* Benefits Section Content */}
+
+
+
+ Advanced features extend the basic API client functionality with
+ sophisticated authentication, error handling, request management,
+ and customization options. These features enable production-ready
+ API clients that can handle complex scenarios and enterprise
+ requirements.
+
+
+
+
{_('7.1. Authentication Strategies')}
+
+ {authenticationStrategies}
+
+
+
{_('7.2. Error Handling Strategies')}
+
+
+ Error handling strategies determine how the API client responds
+ to and manages different types of errors. The plugin supports
+ multiple approaches including returning errors in responses,
+ throwing exceptions, and using callback functions for flexible
+ error management.
+
+
+
+ {errorHandlingStrategies}
+
+
+
{_('7.3. Request Cancellation')}
+
+
+ Request cancellation allows you to abort ongoing API requests
+ when they are no longer needed. This is essential for preventing
+ unnecessary network traffic and improving application performance,
+ especially in scenarios with user navigation or component
+ unmounting.
+
+
+
+ {requestCancellation}
+
+
+
{_('7.4. Custom Headers')}
+
+
+ Custom headers allow you to add additional metadata to requests,
+ such as localization preferences, custom authentication tokens, or
+ API versioning information. The generated client supports flexible
+ header management for each request.
+
+
+
+ Following best practices ensures your API client is maintainable,
+ performant, and robust. These patterns have been proven in
+ production environments and help avoid common pitfalls when
+ working with generated API clients.
+
+
+
+
{_('8.1. Type Safety')}
+
+
+ Leverage TypeScript's type system to catch errors at compile time
+ and improve developer experience. Always use the generated types
+ and interfaces to maintain type safety throughout your application.
+
+
+
+ {typeSafety}
+
+
+
{_('8.2. Error Handling')}
+
+
+ Implement consistent error handling patterns across your
+ application. Create centralized error handling utilities to avoid
+ code duplication and ensure consistent error presentation to users.
+
+
+
+ {errorHandlingPattern}
+
+
+
{_('8.3. Client Extension')}
+
+
+ Extend the generated client for custom functionality while
+ maintaining the generated code's integrity. Use inheritance and
+ composition patterns to add logging, metrics, or custom behavior.
+
+
+
+ {clientExtension}
+
+
+
{_('8.4. Caching Strategies')}
+
+
+ Implement appropriate caching strategies to improve performance
+ and reduce server load. Consider using in-memory caches for
+ frequently accessed data and implement cache invalidation
+ strategies.
+
+
+
+ The implementation section covers the core plugin function and
+ supporting utilities that handle API client generation. This
+ includes configuration validation, content generation, file
+ writing, and error handling throughout the generation process.
+
+
+
+
{_('4.1. Core Plugin Function')}
+
+
+ The core plugin function serves as the main entry point for API
+ client generation. It orchestrates the entire process from
+ configuration validation through content generation to file
+ output, ensuring proper error handling and logging throughout.
+
+
+
+ {corePluginFunction}
+
+
+
{_('4.2. Generation Functions')}
+
+
+ The generation functions handle the creation of specific parts of
+ the API client code. These utility functions generate file headers,
+ imports, type definitions, base client classes, and model-specific
+ client methods, ensuring consistent code structure and proper
+ TypeScript typing.
+
+
+
+ {headerAndImports}
+
+
+ {typeGeneration}
+
+
+ {baseClientGeneration}
+
+
+ {restClientGeneration}
+
+
+ >
+ );
+}
\ No newline at end of file
diff --git a/packages/www/plugins/docs/components/api-client-plugin/Introduction.tsx b/packages/www/plugins/docs/components/api-client-plugin/Introduction.tsx
new file mode 100644
index 0000000..8aa70a8
--- /dev/null
+++ b/packages/www/plugins/docs/components/api-client-plugin/Introduction.tsx
@@ -0,0 +1,26 @@
+//modules
+import { useLanguage, Translate } from 'r22n';
+//local
+import { H1, P, C } from '../../../docs/components/index.js';
+
+export default function Introduction() {
+ //hooks
+ const { _ } = useLanguage();
+
+ return (
+ <>
+ {/* API Client Generator Plugin Tutorial */}
+
+
{_('API Client Generator Plugin Tutorial')}
+
+
+ This tutorial demonstrates how to create a plugin that
+ generates REST and GraphQL API clients from .idea
+ schema files. The plugin will transform your schema models
+ into type-safe API client libraries with full CRUD operations.
+
+
+
+ >
+ );
+}
\ No newline at end of file
diff --git a/packages/www/plugins/docs/components/api-client-plugin/Overview.tsx b/packages/www/plugins/docs/components/api-client-plugin/Overview.tsx
new file mode 100644
index 0000000..43b5cb4
--- /dev/null
+++ b/packages/www/plugins/docs/components/api-client-plugin/Overview.tsx
@@ -0,0 +1,45 @@
+//modules
+import { useLanguage, Translate } from 'r22n';
+//local
+import { H1, P } from '../../../docs/components/index.js';
+
+export default function Overview() {
+ //hooks
+ const { _ } = useLanguage();
+
+ return (
+ <>
+ {/* Overview Section Content */}
+
+
{_('1. Overview')}
+
+
+ API clients provide a convenient interface for interacting with
+ backend services. This plugin generates type-safe API clients
+ from your schema, including:
+
+
+
+ The plugin structure defines the core architecture and
+ configuration interface for the API client generator. This
+ includes the main plugin function, configuration types, and
+ the overall organization of the generated client code.
+
+
+
+ {pluginStructureExample}
+
+
+ >
+ );
+}
\ No newline at end of file
diff --git a/packages/www/plugins/docs/components/api-client-plugin/Prerequisites.tsx b/packages/www/plugins/docs/components/api-client-plugin/Prerequisites.tsx
new file mode 100644
index 0000000..cd67ba7
--- /dev/null
+++ b/packages/www/plugins/docs/components/api-client-plugin/Prerequisites.tsx
@@ -0,0 +1,43 @@
+//modules
+import { useLanguage, Translate } from 'r22n';
+//local
+import { H1, P } from '../../../docs/components/index.js';
+
+export default function Prerequisites() {
+ //hooks
+ const { _ } = useLanguage();
+
+ return (
+ <>
+ {/* Prerequisites Section Content */}
+
+
{_('2. Prerequisites')}
+
+
+ Before implementing the API client generator plugin, ensure you
+ have the necessary development environment and dependencies. This
+ section covers the essential requirements and setup needed to
+ successfully create and use the plugin.
+
+
+
+
+ Node.js and npm/yarn package manager
+
+
+ Basic understanding of TypeScript and API design
+
+
+ >
+ );
+}
\ No newline at end of file
diff --git a/packages/www/plugins/docs/components/api-client-plugin/Troubleshooting.tsx b/packages/www/plugins/docs/components/api-client-plugin/Troubleshooting.tsx
new file mode 100644
index 0000000..5018b97
--- /dev/null
+++ b/packages/www/plugins/docs/components/api-client-plugin/Troubleshooting.tsx
@@ -0,0 +1,163 @@
+//modules
+import { useLanguage, Translate } from 'r22n';
+//local
+import { H1, H2, P } from '../../../docs/components/index.js';
+import Code from '../../../docs/components/Code.js';
+
+//code examples
+//--------------------------------------------------------------------//
+
+const corsIssues =
+`// Ensure your API server allows CORS
+// Add appropriate headers in your API configuration
+
+// For development, you might need to proxy requests
+const client = new APIClient('/api/proxy');`;
+
+//--------------------------------------------------------------------//
+
+const authenticationIssues =
+`// Check token format and expiration
+function isTokenValid(token: string): boolean {
+ try {
+ const payload = JSON.parse(atob(token.split('.')[1]));
+ return payload.exp * 1000 > Date.now();
+ } catch {
+ return false;
+ }
+}
+
+// Refresh token automatically
+client.setAuthToken(await refreshToken());`;
+
+//--------------------------------------------------------------------//
+
+const networkIssues =
+`// Implement retry logic
+async function withRetry(
+ operation: () => Promise>,
+ maxRetries: number = 3
+): Promise> {
+ for (let i = 0; i < maxRetries; i++) {
+ try {
+ const result = await operation();
+ if (result.success) return result;
+
+ if (i === maxRetries - 1) return result;
+ await new Promise(resolve => setTimeout(resolve, 1000 * (i + 1)));
+ } catch (error) {
+ if (i === maxRetries - 1) throw error;
+ }
+ }
+
+ throw new Error('Max retries exceeded');
+}`;
+
+//--------------------------------------------------------------------//
+
+const debuggingTips =
+`// Add to base client
+private logRequest(method: string, url: string, data?: any) {
+ if (process.env.NODE_ENV === 'development') {
+ console.group(\`API \${method} \${url}\`);
+ if (data) console.log('Data:', data);
+ console.groupEnd();
+ }
+}`;
+
+//--------------------------------------------------------------------//
+
+const responseValidation =
+`// Validate response structure
+function validateResponse(response: any): response is APIResponse {
+ return (
+ typeof response === 'object' &&
+ typeof response.success === 'boolean' &&
+ (response.success ? 'data' in response : 'error' in response)
+ );
+}`;
+
+//--------------------------------------------------------------------//
+
+export default function Troubleshooting() {
+ //hooks
+ const { _ } = useLanguage();
+
+ return (
+ <>
+ {/* Troubleshooting Section Content */}
+
+
{_('9. Troubleshooting')}
+
+
+ This section covers common issues you might encounter when
+ using the generated API client and provides solutions and
+ debugging strategies to resolve them quickly.
+
+
+
+
{_('9.1. CORS Issues')}
+
+
+ Cross-Origin Resource Sharing (CORS) issues are common
+ when making API requests from web applications. Ensure
+ your server is properly configured to handle CORS or use
+ appropriate proxy settings during development.
+
+
+
+ {corsIssues}
+
+
+
{_('9.2. Authentication Problems')}
+
+
+ Authentication issues often stem from expired tokens, incorrect
+ formats, or missing headers. Implement proper token validation
+ and refresh mechanisms to handle these scenarios gracefully.
+
+
+
+ {authenticationIssues}
+
+
+
{_('9.3. Network Issues')}
+
+
+ Network connectivity problems require robust retry logic
+ and proper error handling. Implement exponential backoff
+ strategies for transient failures and provide meaningful
+ feedback to users.
+
+
+
+ {networkIssues}
+
+
+
{_('9.4. Debugging Tips')}
+
+
+ Enable comprehensive logging during development to track request
+ flows and identify issues. Use browser developer tools and server
+ logs to diagnose problems effectively.
+
+
+
+ {debuggingTips}
+
+
+
{_('9.5. Response Validation')}
+
+
+ Validate API responses to ensure they match expected formats.
+ This helps catch schema mismatches and API changes that could
+ break your application.
+
+
+
+ {responseValidation}
+
+
+ >
+ );
+}
\ No newline at end of file
diff --git a/packages/www/plugins/docs/components/api-client-plugin/UsageExamples.tsx b/packages/www/plugins/docs/components/api-client-plugin/UsageExamples.tsx
new file mode 100644
index 0000000..d11c5ed
--- /dev/null
+++ b/packages/www/plugins/docs/components/api-client-plugin/UsageExamples.tsx
@@ -0,0 +1,143 @@
+//local
+import { H1, H2, P } from '../../../docs/components/index.js';
+import Code from '../../../docs/components/Code.js';
+//modules
+import { useLanguage, Translate } from 'r22n';
+
+//code examples
+//--------------------------------------------------------------------//
+
+const basicSchemaExample =
+`enum UserRole {
+ ADMIN "admin"
+ USER "user"
+ GUEST "guest"
+}
+
+model User {
+ id String @id @default("nanoid()")
+ email String @unique @required
+ name String @required
+ role UserRole @default("USER")
+ active Boolean @default(true)
+ createdAt Date @default("now()")
+}
+
+model Post {
+ id String @id @default("nanoid()")
+ title String @required
+ content String @required
+ authorId String @required
+ published Boolean @default(false)
+ createdAt Date @default("now()")
+}
+
+plugin "./plugins/api-client.js" {
+ output "./api-client.ts"
+ clientType "rest"
+ httpLibrary "fetch"
+ baseUrl "/api/v1"
+ generateTypes true
+}`
+
+//--------------------------------------------------------------------//
+
+const generatedClientUsageExample =
+`import APIClient from './api-client';
+
+// Initialize client
+const client = new APIClient('https://api.example.com');
+
+// Set authentication token
+client.setAuthToken('your-jwt-token');
+
+// Use the client
+async function example() {
+ // Get all users with pagination
+ const usersResponse = await client.user.getAll({
+ page: 1,
+ limit: 10,
+ search: 'john'
+ });
+
+ if (usersResponse.success) {
+ console.log('Users:', usersResponse.data);
+ console.log('Total:', usersResponse.total);
+ }
+
+ // Get user by ID
+ const userResponse = await client.user.getById('user-123');
+
+ if (userResponse.success) {
+ console.log('User:', userResponse.data);
+ }
+
+ // Create new user
+ const newUserResponse = await client.user.create({
+ email: 'john@example.com',
+ name: 'John Doe',
+ role: UserRole.USER
+ });
+
+ if (newUserResponse.success) {
+ console.log('Created user:', newUserResponse.data);
+ }
+
+ // Update user
+ const updateResponse = await client.user.update('user-123', {
+ name: 'John Smith'
+ });
+
+ // Delete user
+ const deleteResponse = await client.user.delete('user-123');
+}`
+
+//--------------------------------------------------------------------//
+
+export default function UsageExamples() {
+ //hooks
+ const { _ } = useLanguage();
+
+ return (
+ <>
+ {/* Usage Examples Section Content */}
+
+
{_('6. Usage Examples')}
+
+
+ This section demonstrates practical usage of the API client
+ generator plugin with real-world examples. The examples show how to
+ configure the plugin in schema files and how to use the generated
+ client code in applications.
+
+
+
+
{_('6.1. Basic Schema')}
+
+
+ A basic schema example shows the fundamental structure needed to
+ generate API clients. This includes model definitions with proper
+ attributes, enum declarations, and plugin configuration that
+ produces a functional REST API client.
+
+
+
+ {basicSchemaExample}
+
+
+
{_('6.2. Generated Client Usage')}
+
+
+ The generated client provides a type-safe interface for interacting
+ with your API endpoints. This example demonstrates how to initialize
+ the client, set authentication, and perform common CRUD operations
+ with proper error handling and TypeScript support.
+
+
+
+ {generatedClientUsageExample}
+
+
+ >
+ );
+}
\ No newline at end of file
diff --git a/packages/www/plugins/docs/components/api-client-plugin/index.tsx b/packages/www/plugins/docs/components/api-client-plugin/index.tsx
new file mode 100644
index 0000000..fa590ad
--- /dev/null
+++ b/packages/www/plugins/docs/components/api-client-plugin/index.tsx
@@ -0,0 +1,11 @@
+//exporting all components to have multiple imports from a single file
+export { default as AdvancedFeatures } from './AdvancedFeatures.js';
+export { default as BestPractices } from './BestPractices.js';
+export { default as Implementation } from './Implementation.js';
+export { default as Introduction } from './Introduction.js';
+export { default as Overview } from './Overview.js';
+export { default as PluginStructure } from './PluginStructure.js';
+export { default as Prerequisites } from './Prerequisites.js';
+export { default as SchemaConfiguration } from './SchemaConfiguration.js';
+export { default as Troubleshooting } from './Troubleshooting.js';
+export { default as UsageExamples } from './UsageExamples.js';
\ No newline at end of file
diff --git a/packages/www/plugins/docs/components/graphql-schema-plugin/AdvancedFeatures.tsx b/packages/www/plugins/docs/components/graphql-schema-plugin/AdvancedFeatures.tsx
new file mode 100644
index 0000000..65e6fd3
--- /dev/null
+++ b/packages/www/plugins/docs/components/graphql-schema-plugin/AdvancedFeatures.tsx
@@ -0,0 +1,120 @@
+//modules
+import { useLanguage, Translate } from 'r22n';
+//local
+import { H1, P, Code, H2 } from '../../../docs/components/index.js';
+
+//code examples
+//--------------------------------------------------------------------//
+
+const customScalarTypesExample =
+`// In your plugin configuration
+customScalars: {
+ Email: "String",
+ URL: "String",
+ PhoneNumber: "String",
+ BigInt: "String"
+}`;
+
+//--------------------------------------------------------------------//
+
+const relationshipHandlingExample =
+`function handleRelationships(column: any, models: Record): string {
+ // Check if the column type is another model
+ if (models[column.type]) {
+ let type = column.type;
+
+ if (column.multiple) {
+ type = \`[\${type}]\`;
+ }
+
+ if (column.required) {
+ type += '!';
+ }
+
+ return type;
+ }
+
+ return formatFieldType(column);
+}`
+
+//--------------------------------------------------------------------//
+
+const directiveSupportExample =
+`function generateDirectives(column: any): string {
+ const directives: string[] = [];
+
+ if (column.attributes?.unique) {
+ directives.push('@unique');
+ }
+
+ if (column.attributes?.deprecated) {
+ directives.push('@deprecated(reason: "Use alternative field")');
+ }
+
+ return directives.length > 0 ? \` \${directives.join(' ')}\` : '';
+}`;
+
+//--------------------------------------------------------------------//
+
+export default function AdvancedFeatures() {
+ //hooks
+ const { _ } = useLanguage();
+
+ return (
+ <>
+ {/* Advanced Features Section Content */}
+
+
{_('7. Advanced Features')}
+
+
+ Advanced features extend the basic GraphQL schema generation
+ with sophisticated type handling, relationship management,
+ directive support, and custom scalar types. These features
+ enable production-ready GraphQL schemas that handle complex
+ requirements.
+
+
+
+
{_('Custom Scalar Types')}
+
+
+ Custom scalar types allow you to define specialized data
+ types that map to specific validation or formatting requirements.
+ This feature enables the creation of domain-specific types
+ that enhance type safety and API clarity.
+
+
+
+ {customScalarTypesExample}
+
+
+
{_('Relationship Handling')}
+
+
+ Relationship handling manages references between different
+ types and models in your schema. This ensures that type
+ relationships are properly represented in the generated
+ GraphQL schema with correct type references and nullability
+ handling.
+
+
+
+ {relationshipHandlingExample}
+
+
+
{_('Directive Support')}
+
+
+ Directive support enables the addition of GraphQL directives
+ to fields and types, providing metadata and behavior hints
+ for GraphQL servers and tools. This feature enhances schema
+ expressiveness and enables advanced GraphQL features.
+
+
+
+ Best practices ensure your generated GraphQL schemas are
+ maintainable, performant, and follow GraphQL conventions.
+ These guidelines cover type safety, error handling, configuration
+ validation, and performance optimization.
+
+
+
+
{_('Type Safety')}
+
+
+ Type safety is crucial for preventing runtime errors and
+ ensuring reliable GraphQL schema generation. Always validate
+ input data and use proper TypeScript types throughout the
+ plugin implementation to ensure consistent output.
+
+
+
+ {typeSafetyExample}
+
+
+
{_('Error Handling')}
+
+
+ Proper error handling ensures that schema generation failures
+ provide clear, actionable feedback to developers. Implement
+ comprehensive error handling patterns and meaningful error
+ messages to improve the debugging experience.
+
+
+
+ {errorHandlingExample}
+
+
+
{_('Configuration Validation')}
+
+
+ Configuration validation ensures that plugin settings are
+ correct and complete before schema generation begins. This
+ prevents runtime errors and provides early feedback about
+ configuration issues.
+
+
+
+ {configurationValidationExample}
+
+
+
{_('Performance Optimization')}
+
+
+ Performance optimization techniques help maintain reasonable
+ generation times when working with large schemas. Implement
+ caching strategies and efficient algorithms to ensure the
+ plugin scales well with complex type hierarchies.
+
+
+
+ {performanceOptimizationExample}
+
+
+ >
+ );
+}
\ No newline at end of file
diff --git a/packages/www/plugins/docs/components/graphql-schema-plugin/Conclusion.tsx b/packages/www/plugins/docs/components/graphql-schema-plugin/Conclusion.tsx
new file mode 100644
index 0000000..39184dc
--- /dev/null
+++ b/packages/www/plugins/docs/components/graphql-schema-plugin/Conclusion.tsx
@@ -0,0 +1,27 @@
+//modules
+import { useLanguage, Translate } from 'r22n';
+//local
+import { H1, P, C } from '../../../docs/components/index.js';
+
+export default function Conclusion() {
+ //hooks
+ const { _ } = useLanguage();
+
+ return (
+ <>
+ {/* Conclusion Section Content */}
+
+
{_('10. Conclusion')}
+
+
+ This tutorial provides a comprehensive foundation for
+ creating GraphQL schema generators from .idea
+ files. The generated schemas can be used with any GraphQL
+ server implementation like Apollo Server, GraphQL Yoga,
+ or others.
+
+
+
+ The implementation section covers the core plugin function
+ and supporting utilities that handle GraphQL schema generation.
+ This includes configuration validation, content generation,
+ file writing, and error handling throughout the generation
+ process.
+
+
+
+
{_('Core Plugin Function')}
+
+
+ The core plugin function serves as the main entry point for
+ GraphQL schema generation. It orchestrates the entire process
+ from configuration validation through content generation to
+ file output, ensuring proper error handling and logging
+ throughout.
+
+
+
+ {corePluginFunctionExample}
+
+
+
{_('Type Mapping Functions')}
+
+
+ Type mapping functions handle the conversion of .idea
+ schema types to their GraphQL equivalents. These functions
+ ensure proper type safety and handle complex scenarios like
+ arrays, required fields, and custom scalar types.
+
+
+
+ {typeMappingFunctionsExample}
+
+
+
{_('Schema Generation Functions')}
+
+
+ Schema generation functions create specific parts of the
+ GraphQL schema including custom scalars, enums, types, input
+ types, and root operation types. These functions handle proper
+ GraphQL syntax construction and type relationships.
+
+
+
+ {customScalarsExample}
+
+
+ {enumsAndTypesExample}
+
+
+ {inputTypesAndQueriesExample}
+
+
+ >
+ );
+}
\ No newline at end of file
diff --git a/packages/www/plugins/docs/components/graphql-schema-plugin/Introduction.tsx b/packages/www/plugins/docs/components/graphql-schema-plugin/Introduction.tsx
new file mode 100644
index 0000000..18958f4
--- /dev/null
+++ b/packages/www/plugins/docs/components/graphql-schema-plugin/Introduction.tsx
@@ -0,0 +1,24 @@
+//modules
+import { useLanguage, Translate } from 'r22n';
+//local
+import { H1, P, C } from '../../../docs/components/index.js';
+
+export default function Introduction() {
+ //hooks
+ const { _ } = useLanguage();
+
+ return (
+ <>
+ {/* GraphQL Schema Generator Plugin Tutorial */}
+
{_('GraphQL Schema Generator Plugin Tutorial')}
+
+
+ This tutorial demonstrates how to create a plugin that
+ generates GraphQL type definitions from .idea schema
+ files. The plugin will transform your schema models, types,
+ and enums into proper GraphQL schema definitions.
+
+
+ >
+ );
+}
\ No newline at end of file
diff --git a/packages/www/plugins/docs/components/graphql-schema-plugin/Overview.tsx b/packages/www/plugins/docs/components/graphql-schema-plugin/Overview.tsx
new file mode 100644
index 0000000..4e15477
--- /dev/null
+++ b/packages/www/plugins/docs/components/graphql-schema-plugin/Overview.tsx
@@ -0,0 +1,60 @@
+//modules
+import { useLanguage, Translate } from 'r22n';
+//local
+import { H1, P, C, SS } from '../../../docs/components/index.js';
+
+export default function Overview() {
+ //hooks
+ const { _ } = useLanguage();
+
+ return (
+ <>
+ {/* Overview Section Content */}
+
+
{_('1. Overview')}
+
+
+ GraphQL is a query language and runtime for APIs that provides a
+ complete and understandable description of the data in your API.
+ This plugin transforms your .idea schema definitions into
+ comprehensive GraphQL type definitions that enable type-safe API
+ development with excellent tooling support.
+
+
+
+
+ This plugin generates GraphQL type definitions from your
+ .idea schema, including:
+
+
+
+ The plugin structure defines the core architecture and
+ configuration interface for the GraphQL schema generator.
+ This includes the main plugin function, configuration types,
+ and the overall organization of the generated GraphQL schema
+ definitions.
+
+
+
+ {pluginStructureExample}
+
+
+ >
+ );
+}
\ No newline at end of file
diff --git a/packages/www/plugins/docs/components/graphql-schema-plugin/Prerequisites.tsx b/packages/www/plugins/docs/components/graphql-schema-plugin/Prerequisites.tsx
new file mode 100644
index 0000000..f07ed6b
--- /dev/null
+++ b/packages/www/plugins/docs/components/graphql-schema-plugin/Prerequisites.tsx
@@ -0,0 +1,49 @@
+//modules
+import { useLanguage, Translate } from 'r22n';
+//local
+import { H1, P, C } from '../../../docs/components/index.js';
+
+export default function Prerequisites() {
+ //hooks
+ const { _ } = useLanguage();
+
+ return (
+ <>
+ {/* Prerequisites Section Content */}
+
+
{_('2. Prerequisites')}
+
+
+ Before implementing the GraphQL schema generator plugin,
+ ensure you have the necessary development environment and
+ knowledge. This section covers the essential requirements
+ for successful plugin creation and GraphQL integration.
+
+
+
+
+
+ Node.js 16+ and npm/yarn
+
+
+
+
+ Basic understanding of GraphQL
+
+
+
+
+ Familiarity with the @stackpress/idea-transformer
+ library
+
+
+
+ Schema configuration demonstrates how to integrate the
+ GraphQL schema generator into your .idea schema
+ files. This section covers plugin configuration options
+ and their effects on the generated GraphQL schema definitions.
+
+
+
+
+ Add the GraphQL plugin to your .idea schema file:
+
+
+
+ {schemaConfigurationExample}
+
+
+
{_('Configuration Options')}
+
+
+ Configuration options control how GraphQL schema definitions
+ are generated, including operation types, input generation,
+ and custom scalar handling. Understanding these options helps
+ you customize the plugin to meet your specific GraphQL
+ requirements.
+
+
+
+ >
+ );
+}
\ No newline at end of file
diff --git a/packages/www/plugins/docs/components/graphql-schema-plugin/Troubleshooting.tsx b/packages/www/plugins/docs/components/graphql-schema-plugin/Troubleshooting.tsx
new file mode 100644
index 0000000..fcb82eb
--- /dev/null
+++ b/packages/www/plugins/docs/components/graphql-schema-plugin/Troubleshooting.tsx
@@ -0,0 +1,169 @@
+//modules
+import { useLanguage, Translate } from 'r22n';
+//local
+import { H1, H2, P, Code } from '../../../docs/components/index.js';
+
+//code examples
+//--------------------------------------------------------------------//
+
+const invalidGraphQLNamesExample =
+`function sanitizeGraphQLName(name: string): string {
+ // GraphQL names must match /^[_A-Za-z][_0-9A-Za-z]*$/
+ return name.replace(/[^_A-Za-z0-9]/g, '_').replace(/^[0-9]/, '_$&');
+}`;
+
+//--------------------------------------------------------------------//
+
+const circularDependenciesExample =
+`function detectCircularDependencies(models: Record): string[] {
+ const visited = new Set();
+ const recursionStack = new Set();
+ const cycles: string[] = [];
+
+ // Implementation for cycle detection...
+
+ return cycles;
+}`;
+
+//--------------------------------------------------------------------//
+
+const missingRequiredFieldsExample =
+`function validateRequiredFields(model: any): void {
+ if (!model.columns || model.columns.length === 0) {
+ throw new Error(\`Model must have at least one column\`);
+ }
+}`;
+
+//--------------------------------------------------------------------//
+
+const verboseLoggingExample =
+`const DEBUG = process.env.DEBUG === 'true';
+
+function debugLog(message: string, data?: any) {
+ if (DEBUG) {
+ console.log(\`[GraphQL Plugin] \${message}\`, data || '');
+ }
+}`;
+
+//--------------------------------------------------------------------//
+
+const validateGeneratedSchemaExample =
+`import { buildSchema } from 'graphql';
+
+function validateGeneratedSchema(schemaContent: string): void {
+ try {
+ buildSchema(schemaContent);
+ console.log('✅ Generated GraphQL schema is valid');
+ } catch (error) {
+ throw new Error(\`Invalid GraphQL schema: \${error.message}\`);
+ }
+}`;
+
+//--------------------------------------------------------------------//
+
+export default function Troubleshooting() {
+ //hooks
+ const { _ } = useLanguage();
+
+ return (
+ <>
+ {/* Troubleshooting Section Content */}
+
+
{_('9. Troubleshooting')}
+
+
+ This section addresses common issues encountered when
+ generating GraphQL schemas and provides solutions for
+ debugging and resolving problems. Understanding these
+ troubleshooting techniques helps ensure reliable schema
+ generation.
+
+
+
+
{_('Common Issues')}
+
+
+ Common issues include invalid GraphQL identifiers, circular
+ dependencies, and missing required fields. These problems
+ typically arise from schema complexity or naming conflicts
+ that can be resolved with proper validation and sanitization.
+
+
+
+
{_('Invalid GraphQL Names')}
+
+
+ Invalid GraphQL names occur when schema identifiers contain
+ characters that are not valid in GraphQL. The plugin should
+ validate and sanitize names to ensure they conform to GraphQL
+ naming conventions.
+
+
+
+ {invalidGraphQLNamesExample}
+
+
+
{_('Circular Dependencies')}
+
+
+ Circular dependencies can cause infinite loops during
+ generation or invalid GraphQL schemas. Detecting and
+ handling these scenarios is essential for robust schema
+ generation, especially with complex type relationships.
+
+
+
+ {circularDependenciesExample}
+
+
+
{_('Missing Required Fields')}
+
+
+ Missing required fields can result in invalid GraphQL
+ types that fail validation. Ensure all models have proper
+ field definitions and handle edge cases where schema
+ definitions might be incomplete.
+
+
+
+ {missingRequiredFieldsExample}
+
+
+
{_('Debugging Tips')}
+
+
+ Debugging tips help identify and resolve issues during
+ GraphQL schema generation. These techniques provide visibility
+ into the generation process and help diagnose problems with
+ schema logic or output formatting.
+
+
+
+
{_('Enable Verbose Logging')}
+
+
+ Verbose logging provides detailed information about the
+ schema generation process, helping identify where issues
+ occur and what data is being processed at each step.
+
+
+
+ {verboseLoggingExample}
+
+
+
{_('Validate Generated Schema')}
+
+
+ Validating the generated GraphQL schema ensures that the
+ output is syntactically correct and will work with GraphQL
+ servers and tools. This validation step catches generation
+ errors before deployment.
+
+
+
+ Usage examples demonstrate practical applications of the
+ GraphQL schema generator with real-world scenarios. These
+ examples show how to configure the plugin for different
+ use cases and how the generated GraphQL schemas integrate
+ into development workflows.
+
+
+
+
{_('Basic Schema')}
+
+
+ A basic schema example shows the fundamental structure
+ needed to generate GraphQL type definitions. This includes
+ model definitions with proper attributes, enum declarations,
+ and plugin configuration that produces comprehensive GraphQL
+ schemas.
+
+
+
+ {basicSchemaExample}
+
+
+
{_('Generated Output')}
+
+
+ The generated output demonstrates the GraphQL schema
+ produced by the plugin from the basic schema example.
+ This shows how schema definitions are transformed into
+ proper GraphQL type definitions with full type safety and
+ operation support.
+
+
+
+ {generatedOutputExample}
+
+
+ >
+ );
+}
\ No newline at end of file
diff --git a/packages/www/plugins/docs/components/graphql-schema-plugin/index.tsx b/packages/www/plugins/docs/components/graphql-schema-plugin/index.tsx
new file mode 100644
index 0000000..b52a632
--- /dev/null
+++ b/packages/www/plugins/docs/components/graphql-schema-plugin/index.tsx
@@ -0,0 +1,12 @@
+//exporting all components to have multiple imports from a single file
+export { default as AdvancedFeatures } from './AdvancedFeatures.js';
+export { default as BestPractices } from './BestPractices.js';
+export { default as Conclusion } from './Conclusion.js';
+export { default as Implementation } from './Implementation.js';
+export { default as Introduction } from './Introduction.js';
+export { default as Overview } from './Overview.js';
+export { default as PluginStructure } from './PluginStructure.js';
+export { default as Prerequisites } from './Prerequisites.js';
+export { default as SchemaConfiguration } from './SchemaConfiguration.js';
+export { default as Troubleshooting } from './Troubleshooting.js';
+export { default as UsageExamples } from './UsageExamples.js';
\ No newline at end of file
diff --git a/packages/www/plugins/docs/components/html-form-plugin/CreatePluginStructure.tsx b/packages/www/plugins/docs/components/html-form-plugin/CreatePluginStructure.tsx
new file mode 100644
index 0000000..c6ca1c4
--- /dev/null
+++ b/packages/www/plugins/docs/components/html-form-plugin/CreatePluginStructure.tsx
@@ -0,0 +1,89 @@
+//modules
+import { useLanguage, Translate } from 'r22n';
+//local
+import { H1, P, C } from '../../../docs/components/index.js';
+import Code from '../../../docs/components/Code.js';
+
+//code examples
+//--------------------------------------------------------------------//
+
+const pluginStructureExample =
+ `import type { PluginProps } from '@stackpress/idea-transformer/types';
+import fs from 'fs/promises';
+import path from 'path';
+
+interface HTMLFormConfig {
+ output: string;
+ title?: string;
+ theme?: 'bootstrap' | 'tailwind' | 'custom';
+ layout?: 'vertical' | 'horizontal' | 'inline';
+ includeCSS?: boolean;
+ includeJS?: boolean;
+ submitUrl?: string;
+ method?: 'GET' | 'POST';
+}
+
+export default async function htmlFormPlugin(
+ props: PluginProps<{ config: HTMLFormConfig }>
+) {
+ const { config, schema, transformer, cwd } = props;
+
+ // Validate configuration
+ if (!config.output) {
+ throw new Error('HTML Form Plugin requires "output" configuration');
+ }
+
+ // Set defaults
+ const options = {
+ title: config.title || 'Generated Form',
+ theme: config.theme || 'bootstrap',
+ layout: config.layout || 'vertical',
+ includeCSS: config.includeCSS !== false,
+ includeJS: config.includeJS !== false,
+ submitUrl: config.submitUrl || '#',
+ method: config.method || 'POST',
+ ...config
+ };
+
+ // Generate HTML content
+ const htmlContent = generateHTML(schema, options);
+
+ // Write to output file
+ const outputPath = await transformer.loader.absolute(config.output);
+ await fs.mkdir(path.dirname(outputPath), { recursive: true });
+ await fs.writeFile(outputPath, htmlContent, 'utf8');
+
+ console.log(\`✅ HTML form generated: \${outputPath}\`);
+}`;
+
+//--------------------------------------------------------------------//
+
+export default function CreatePluginStructure() {
+ //hooks
+ const { _ } = useLanguage();
+
+ return (
+ <>
+ {/* Create the Plugin Structure Section Content */}
+
+
{_('4. Create the Plugin Structure')}
+
+
+ The plugin structure provides the foundation for the HTML
+ form generator. This section covers the main plugin function,
+ configuration interface, and the basic workflow for
+ processing schemas and generating HTML output.
+
+
+
+
+ Create a new file
+ html-form-plugin.js:
+
+
+ {pluginStructureExample}
+
+
+ >
+ );
+}
\ No newline at end of file
diff --git a/packages/www/plugins/docs/components/html-form-plugin/ErrorHandlingAndBestPractices.tsx b/packages/www/plugins/docs/components/html-form-plugin/ErrorHandlingAndBestPractices.tsx
new file mode 100644
index 0000000..0d9b9cf
--- /dev/null
+++ b/packages/www/plugins/docs/components/html-form-plugin/ErrorHandlingAndBestPractices.tsx
@@ -0,0 +1,91 @@
+//modules
+import { useLanguage, Translate } from 'r22n';
+//local
+import { H1, P } from '../../../docs/components/index.js';
+import Code from '../../../docs/components/Code.js';
+
+//code examples
+//--------------------------------------------------------------------//
+
+const errorHandlingExample =
+ `export default async function htmlFormPlugin(props: PluginProps<{}>) {
+ const { config, schema, transformer, cwd } = props;
+
+ try {
+ // Validate configuration
+ validateConfig(config);
+
+ // Validate schema has models
+ if (!schema.model || Object.keys(schema.model).length === 0) {
+ console.warn('⚠️ No models found in schema. Skipping HTML form generation.');
+ return;
+ }
+
+ // Generate HTML
+ const htmlContent = generateHTML(schema, config);
+
+ // Ensure output directory exists
+ const outputPath = await transformer.loader.absolute(config.output);
+ await fs.mkdir(path.dirname(outputPath), { recursive: true });
+
+ // Write file
+ await fs.writeFile(outputPath, htmlContent, 'utf8');
+
+ console.log(\`✅ HTML form generated: \${outputPath}\`);
+ console.log(\`📊 Generated forms for \${Object.keys(schema.model).length} model(s)\`);
+
+ } catch (error) {
+ console.error(\`❌ HTML Form Plugin failed: \${error.message}\`);
+ throw error;
+ }
+}
+
+function validateConfig(config: any): void {
+ if (!config.output) {
+ throw new Error('HTML Form Plugin requires "output" configuration');
+ }
+
+ if (config.theme && !['bootstrap', 'tailwind', 'custom'].includes(config.theme)) {
+ throw new Error(\`Unsupported theme: \${config.theme}\`);
+ }
+
+ if (config.layout && !['vertical', 'horizontal', 'inline'].includes(config.layout)) {
+ throw new Error(\`Unsupported layout: \${config.layout}\`);
+ }
+
+ if (config.method && !['GET', 'POST'].includes(config.method)) {
+ throw new Error(\`Unsupported HTTP method: \${config.method}\`);
+ }
+}`;
+
+//--------------------------------------------------------------------//
+
+export default function ErrorHandlingAndBestPractices() {
+ //hooks
+ const { _ } = useLanguage();
+
+ return (
+ <>
+ {/* Error Handling and Best Practices Section Content */}
+
+
{_('10. Error Handling and Best Practices')}
+
+
+ Proper error handling and following best practices ensure
+ that your plugin is robust and reliable. This section covers
+ validation techniques, error reporting, and recommended
+ patterns for plugin development.
+
+
+
+
+ Add proper error handling and validation:
+
+
+
+ {errorHandlingExample}
+
+
+ >
+ );
+}
\ No newline at end of file
diff --git a/packages/www/plugins/docs/components/html-form-plugin/GenerateCompleteHtmlDocument.tsx b/packages/www/plugins/docs/components/html-form-plugin/GenerateCompleteHtmlDocument.tsx
new file mode 100644
index 0000000..357b678
--- /dev/null
+++ b/packages/www/plugins/docs/components/html-form-plugin/GenerateCompleteHtmlDocument.tsx
@@ -0,0 +1,178 @@
+//modules
+import { useLanguage, Translate } from 'r22n';
+//local
+import { H1, P } from '../../../docs/components/index.js';
+import Code from '../../../docs/components/Code.js';
+
+//code examples
+//--------------------------------------------------------------------//
+
+const htmlGenerationExample =
+ `function generateHTML(schema: any, options: any): string {
+ let html = generateHTMLHeader(options);
+
+ // Generate forms for each model
+ if (schema.model) {
+ for (const [modelName, model] of Object.entries(schema.model)) {
+ html += generateFormHTML(modelName, model, schema, options);
+ html += '\\n';
+ }
+ }
+
+ html += generateHTMLFooter(options);
+
+ return html;
+}
+
+function generateHTMLHeader(options: any): string {
+ let html = '\\n';
+ html += '\\n';
+ html += '\\n';
+ html += ' \\n';
+ html += ' \\n';
+ html += \` \${escapeHtml(options.title)}\\n\`;
+
+ // Include CSS
+ if (options.includeCSS) {
+ html += generateCSS(options);
+ }
+
+ html += '\\n';
+ html += '\\n';
+ html += '
+
+ Generating a complete HTML document involves combining all
+ form elements into a properly structured HTML page. This
+ section shows how to create the HTML structure, include
+ necessary CSS and JavaScript files, and generate forms for
+ multiple models within a single document.
+
+
+
+
+ Implement the main HTML generation function:
+
+
+
+ {htmlGenerationExample}
+
+
+ >
+ );
+}
\ No newline at end of file
diff --git a/packages/www/plugins/docs/components/html-form-plugin/GeneratedOutput.tsx b/packages/www/plugins/docs/components/html-form-plugin/GeneratedOutput.tsx
new file mode 100644
index 0000000..869c312
--- /dev/null
+++ b/packages/www/plugins/docs/components/html-form-plugin/GeneratedOutput.tsx
@@ -0,0 +1,157 @@
+//modules
+import { useLanguage, Translate } from 'r22n';
+//local
+import { H1, P } from '../../../docs/components/index.js';
+import Code from '../../../docs/components/Code.js';
+
+//code examples
+//--------------------------------------------------------------------//
+
+const generatedOutputExample =
+ `
+
+
+
+
+ User Registration Form
+
+
+
+
+
+ The generated output section shows examples of the HTML code
+ that the plugin produces. This helps you understand what to
+ expect from the plugin and how the various configuration
+ options affect the final output.
+
+
+
+ Form element generation is the core functionality of the
+ plugin. This section demonstrates how to create functions
+ that generate different types of HTML form elements based
+ on schema column definitions, including inputs, textareas,
+ selects, checkboxes, radio buttons, and file inputs.
+
+
+
+
+ Create functions to generate different form elements:
+
+
+
+ Form layout and styling ensure that generated forms are
+ visually appealing and work well with different CSS
+ frameworks. This section covers how to implement support
+ for Bootstrap, Tailwind CSS, and custom styling, along with
+ different layout options like vertical, horizontal, and
+ inline forms.
+
+
+
+
+ Create functions for different themes and layouts:
+
+
+
+ {formLayoutExample}
+
+
+ >
+ );
+}
\ No newline at end of file
diff --git a/packages/www/plugins/docs/components/html-form-plugin/Introduction.tsx b/packages/www/plugins/docs/components/html-form-plugin/Introduction.tsx
new file mode 100644
index 0000000..a1c8bc9
--- /dev/null
+++ b/packages/www/plugins/docs/components/html-form-plugin/Introduction.tsx
@@ -0,0 +1,27 @@
+//modules
+import { useLanguage, Translate } from 'r22n';
+//local
+import { H1, P, C } from '../../../docs/components/index.js';
+
+export default function Introduction() {
+ //hooks
+ const { _ } = useLanguage();
+
+ return (
+ <>
+ {/* Creating an HTML Form Plugin */}
+
+
{_('Creating an HTML Form Plugin')}
+
+
+ This tutorial will guide you through creating a plugin that
+ generates HTML forms from a processed .idea schema.
+ You'll learn how to parse schema models, generate appropriate
+ form elements, handle validation, and create responsive forms
+ with multiple CSS framework support.
+
+
+
+ This section provides an overview of what the HTML Form
+ Plugin accomplishes and its key features. The plugin
+ transforms schema definitions into fully functional HTML
+ forms with proper validation, styling, and accessibility
+ features.
+
+
+
+
+ The HTML Form Plugin will:
+
+
+
+
+
+ Parse schema models and their columns
+
+
+
+
+ Generate HTML form elements based on field types and
+ attributes
+
+
+
+
+ Include validation attributes and constraints
+
+
+
+
+ Create responsive, accessible forms with proper styling
+
+
+
+
+ Support different form layouts and themes
+
+
+
+
+ >
+ );
+}
\ No newline at end of file
diff --git a/packages/www/plugins/docs/components/html-form-plugin/Prerequisites.tsx b/packages/www/plugins/docs/components/html-form-plugin/Prerequisites.tsx
new file mode 100644
index 0000000..a830c6b
--- /dev/null
+++ b/packages/www/plugins/docs/components/html-form-plugin/Prerequisites.tsx
@@ -0,0 +1,45 @@
+//modules
+import { useLanguage, Translate } from 'r22n';
+//local
+import { H1, P, SS, C } from '../../../docs/components/index.js';
+
+export default function Prerequisites() {
+ //hooks
+ const { _ } = useLanguage();
+
+ return (
+ <>
+ {/* Prerequisites Section Content */}
+
+
{_('2. Prerequisites')}
+
+
+ Before starting this tutorial, ensure you have the necessary
+ knowledge and tools to successfully implement the HTML Form
+ Plugin. These prerequisites will help you understand the
+ concepts and follow along with the implementation.
+
+
+
+
+
+ Basic understanding of
+ TypeScript/JavaScript
+
+
+
+ Familiarity with HTML forms and CSS
+
+
+
+
+ Understanding of the
+ idea-transformer
+ plugin system
+
+
+
+ Understanding how schema attributes map to form elements is
+ crucial for creating effective form generation. This section
+ explains the processed schema structure and how different
+ field types and attributes translate into HTML form elements.
+
+
+
+
+ Before creating the plugin, let's understand how schema
+ attributes map to form elements:
+
+
+
+ {schemaExample}
+
+
+ >
+ );
+}
\ No newline at end of file
diff --git a/packages/www/plugins/docs/components/html-form-plugin/UsageInSchema.tsx b/packages/www/plugins/docs/components/html-form-plugin/UsageInSchema.tsx
new file mode 100644
index 0000000..6bf39b5
--- /dev/null
+++ b/packages/www/plugins/docs/components/html-form-plugin/UsageInSchema.tsx
@@ -0,0 +1,71 @@
+//modules
+import { useLanguage, Translate } from 'r22n';
+//local
+import { H1, P, C } from '../../../docs/components/index.js';
+import Code from '../../../docs/components/Code.js';
+
+//code examples
+//--------------------------------------------------------------------//
+
+const usageExample =
+ `// schema.idea
+plugin "./plugins/html-form-plugin.js" {
+ output "./forms/user-form.html"
+ title "User Registration Form"
+ theme "bootstrap"
+ layout "vertical"
+ includeCSS true
+ includeJS true
+ submitUrl "/api/users"
+ method "POST"
+}
+
+model User {
+ name String @label("Full Name") @field.input(Text) @is.required @is.minLength(2) @is.maxLength(50)
+ email String @label("Email Address") @field.input(Email) @is.required @is.email
+ age Number @label("Age") @field.number @is.min(18) @is.max(100)
+ role UserRole @label("User Role") @field.select @default("USER")
+ bio String @label("Biography") @field.textarea @is.maxLength(500)
+ active Boolean @label("Active Account") @field.checkbox @default(true)
+ created Date @label("Registration Date") @field.date @default("now()")
+}
+
+enum UserRole {
+ ADMIN "Administrator"
+ USER "Regular User"
+ GUEST "Guest User"
+}`;
+
+//--------------------------------------------------------------------//
+
+export default function UsageInSchema() {
+ //hooks
+ const { _ } = useLanguage();
+
+ return (
+ <>
+ {/* Usage in Schema Section Content */}
+
+
{_('8. Usage in Schema')}
+
+
+ This section demonstrates how to configure and use the HTML
+ Form Plugin within your
+ .idea
+ schema files. You'll learn about the available configuration
+ options and how to set up your schema to generate the desired
+ form output.
+
+
+
+
+ To use this plugin in your schema file:
+
+
+
+ {usageExample}
+
+
+ >
+ );
+}
\ No newline at end of file
diff --git a/packages/www/plugins/docs/components/html-form-plugin/index.tsx b/packages/www/plugins/docs/components/html-form-plugin/index.tsx
new file mode 100644
index 0000000..b203a2e
--- /dev/null
+++ b/packages/www/plugins/docs/components/html-form-plugin/index.tsx
@@ -0,0 +1,12 @@
+//exporting all components to have multiple imports from a single file
+export { default as CreatePluginStructure } from './CreatePluginStructure.js';
+export { default as ErrorHandlingAndBestPractices } from './ErrorHandlingAndBestPractices.js';
+export { default as GenerateCompleteHtmlDocument } from './GenerateCompleteHtmlDocument.js';
+export { default as GeneratedOutput } from './GeneratedOutput.js';
+export { default as ImplementFormElementGeneration } from './ImplementFormElementGeneration.js';
+export { default as ImplementFormLayoutAndStyling } from './ImplementFormLayoutAndStyling.js';
+export { default as Introduction } from './Introduction.js';
+export { default as Overview } from './Overview.js';
+export { default as Prerequisites } from './Prerequisites.js';
+export { default as UnderstandingSchemaStructure } from './UnderstandingSchemaStructure.js';
+export { default as UsageInSchema } from './UsageInSchema.js';
\ No newline at end of file
diff --git a/packages/www/plugins/docs/components/index.tsx b/packages/www/plugins/docs/components/index.tsx
new file mode 100644
index 0000000..f56aef1
--- /dev/null
+++ b/packages/www/plugins/docs/components/index.tsx
@@ -0,0 +1,220 @@
+import type { ReactNode } from 'react';
+import { useEffect, useState } from 'react';
+import SyntaxHighlighter from 'react-syntax-highlighter';
+import { atomOneDark } from 'react-syntax-highlighter/dist/cjs/styles/hljs';
+import { notify, useLanguage, Translate } from 'stackpress/view/client';
+import Alert from 'frui/element/Alert';
+import CodeView from './Code.js';
+import Editor from './Editor.js';
+import Layout from './Layout.js';
+
+export type { File, Folder } from './Editor.js';
+
+export { Editor, Layout };
+
+export function Header1({ children }: { children: string }) {
+ const { _ } = useLanguage();
+ return (
+
+
+ Support multiple output formats (single file vs.
+ multiple files)
+
+
+
+
+ Include examples, cross-references, and detailed
+ attribute information
+
+
+
+
+ Provide flexible configuration options for different
+ documentation needs
+
+
+
+
+
+ The plugin is highly customizable and can be extended to
+ support additional features like custom templates, diagram
+ generation, and integration with documentation platforms.
+
+
+
+ Create a new file markdown-docs-plugin.js:
+
+
+
+ {pluginStructureExample}
+
+
+ >
+ )
+}
\ No newline at end of file
diff --git a/packages/www/plugins/docs/components/markdown-documentation-plugin/ErrorHandlingAndBestPractices.tsx b/packages/www/plugins/docs/components/markdown-documentation-plugin/ErrorHandlingAndBestPractices.tsx
new file mode 100644
index 0000000..32fa3ce
--- /dev/null
+++ b/packages/www/plugins/docs/components/markdown-documentation-plugin/ErrorHandlingAndBestPractices.tsx
@@ -0,0 +1,53 @@
+//modules
+import { useLanguage, Translate } from 'r22n';
+//local
+import { H1, P } from '../../../docs/components/index.js';
+import Code from '../../../docs/components/Code.js';
+
+//code examples
+//--------------------------------------------------------------------//
+
+const errorHandlingExample =
+ `function validateConfig(config: any): void {
+ if (!config.output) {
+ throw new Error('Markdown Documentation Plugin requires "output" configuration');
+ }
+
+ if (config.format && !['single', 'multiple'].includes(config.format)) {
+ throw new Error(\`Unsupported format: \${config.format}\`);
+ }
+
+ if (config.template && !['default', 'api', 'guide'].includes(config.template)) {
+ throw new Error(\`Unsupported template: \${config.template}\`);
+ }
+}`;
+
+//--------------------------------------------------------------------//
+
+export default function ErrorHandlingAndBestPractices() {
+ //hooks
+ const { _ } = useLanguage();
+
+ return (
+ <>
+ {/* Error Handling and Best Practices Section Content */}
+
+
{_('11. Error Handling and Best Practices')}
+
+
+ Add proper error handling and validation:
+
+
+
+ {errorHandlingExample}
+
+
+
+ Always validate configuration parameters and provide meaningful
+ error messages to help users troubleshoot issues.
+
+
+
+ >
+ )
+}
\ No newline at end of file
diff --git a/packages/www/plugins/docs/components/markdown-documentation-plugin/GenerateModelsDocumentation.tsx b/packages/www/plugins/docs/components/markdown-documentation-plugin/GenerateModelsDocumentation.tsx
new file mode 100644
index 0000000..c62d702
--- /dev/null
+++ b/packages/www/plugins/docs/components/markdown-documentation-plugin/GenerateModelsDocumentation.tsx
@@ -0,0 +1,44 @@
+//modules
+import { useLanguage, Translate } from 'r22n';
+//local
+import { H1, P } from '../../../docs/components/index.js';
+import Code from '../../../docs/components/Code.js';
+
+//code examples
+//--------------------------------------------------------------------//
+
+const modelsGenerationExample =
+ `function generateModelsSection(models: any, schema: any, options: any): string {
+ let content = '## Models\\n\\n';
+ content += 'Models represent the main data structures in your application.\\n\\n';
+
+ for (const [modelName, model] of Object.entries(models)) {
+ content += generateModelDocumentation(modelName, model, schema, options);
+ }
+
+ return content;
+}`;
+
+//--------------------------------------------------------------------//
+
+export default function GenerateModelsDocumentation() {
+ //hooks
+ const { _ } = useLanguage();
+
+ return (
+ <>
+ {/* Generate Models Documentation Section Content */}
+
+
{_('6. Generate Models Documentation')}
+
+
+ Implement model documentation generation:
+
+
+
+ {modelsGenerationExample}
+
+
+ >
+ )
+}
\ No newline at end of file
diff --git a/packages/www/plugins/docs/components/markdown-documentation-plugin/GenerateTypesEnumsProps.tsx b/packages/www/plugins/docs/components/markdown-documentation-plugin/GenerateTypesEnumsProps.tsx
new file mode 100644
index 0000000..b0a5f24
--- /dev/null
+++ b/packages/www/plugins/docs/components/markdown-documentation-plugin/GenerateTypesEnumsProps.tsx
@@ -0,0 +1,32 @@
+//modules
+import { useLanguage, Translate } from 'r22n';
+//local
+import { H1, P } from '../../../docs/components/index.js';
+
+export default function GenerateTypesEnumsProps() {
+ //hooks
+ const { _ } = useLanguage();
+
+ return (
+ <>
+ {/* Generate Types, Enums, and Props Section Content */}
+
+
{_('7. Generate Types, Enums, and Props')}
+
+
+ Similar to models, you can implement generation functions for
+ types, enums, and props. Each follows the same pattern of
+ creating markdown sections with tables and descriptions.
+
+
+
+
+ Types define reusable data structures, enums define sets of
+ named constants, and props define reusable property
+ configurations for form fields and validation.
+
+
+
+ >
+ )
+}
\ No newline at end of file
diff --git a/packages/www/plugins/docs/components/markdown-documentation-plugin/GeneratedOutput.tsx b/packages/www/plugins/docs/components/markdown-documentation-plugin/GeneratedOutput.tsx
new file mode 100644
index 0000000..d50f2a5
--- /dev/null
+++ b/packages/www/plugins/docs/components/markdown-documentation-plugin/GeneratedOutput.tsx
@@ -0,0 +1,86 @@
+//modules
+import { useLanguage, Translate } from 'r22n';
+//local
+import { H1, P } from '../../../docs/components/index.js';
+import Code from '../../../docs/components/Code.js';
+
+//code examples
+//--------------------------------------------------------------------//
+
+const generatedOutputExample =
+ `# My Application Schema
+
+API Reference documentation for the schema definitions.
+
+## Overview
+
+This document provides comprehensive API documentation for all schema
+elements including models, types, enums, and properties.
+
+Generated on: 2024-01-15T10:30:00.000Z
+
+## Table of Contents
+
+- [Models](#models)
+ - [User](#user)
+- [Enums](#enums)
+ - [UserRole](#userrole)
+
+## Models
+
+Models represent the main data structures in your application.
+
+### User
+
+**Mutability:** Immutable
+
+#### Columns
+
+| Name | Type | Required | Multiple | Description |
+|------|------|----------|----------|-------------|
+| id | \`String\` | ✓ | ✗ | Unique identifier for the user |
+| email | \`String\` | ✓ | ✗ | User email address for authentication |
+| name | \`String\` | ✓ | ✗ | Full name of the user |
+| role | [UserRole](#userrole) | ✓ | ✗ | User's role in the system |
+
+## Enums
+
+Enums define sets of named constants with associated values.
+
+### UserRole
+
+#### Values
+
+| Key | Value | Description |
+|-----|-------|-----------|
+| ADMIN | Administrator | - |
+| USER | Regular User | - |
+| GUEST | Guest User | - |
+
+---
+
+*Documentation generated on 1/15/2024, 10:30:00 AM*`;
+
+//--------------------------------------------------------------------//
+
+export default function GeneratedOutput() {
+ //hooks
+ const { _ } = useLanguage();
+
+ return (
+ <>
+ {/* Generated Output Section Content */}
+
+
{_('10. Generated Output')}
+
+
+ The plugin will generate markdown documentation like this:
+
+
+
+ {generatedOutputExample}
+
+
+ >
+ )
+}
\ No newline at end of file
diff --git a/packages/www/plugins/docs/components/markdown-documentation-plugin/ImplementDocumentationGeneration.tsx b/packages/www/plugins/docs/components/markdown-documentation-plugin/ImplementDocumentationGeneration.tsx
new file mode 100644
index 0000000..95bdb29
--- /dev/null
+++ b/packages/www/plugins/docs/components/markdown-documentation-plugin/ImplementDocumentationGeneration.tsx
@@ -0,0 +1,76 @@
+//modules
+import { useLanguage, Translate } from 'r22n';
+//local
+import { H1, P } from '../../../docs/components/index.js';
+import Code from '../../../docs/components/Code.js';
+
+//code examples
+//--------------------------------------------------------------------//
+
+const documentationGenerationExample =
+ `async function generateSingleFile(schema: any, options: any, transformer: any): Promise {
+ let content = generateHeader(options);
+
+ // Generate table of contents
+ if (options.includeIndex) {
+ content += generateTableOfContents(schema, options);
+ }
+
+ // Generate sections
+ for (const section of options.sections) {
+ switch (section) {
+ case 'models':
+ if (schema.model) {
+ content += generateModelsSection(schema.model, schema, options);
+ }
+ break;
+ case 'types':
+ if (schema.type) {
+ content += generateTypesSection(schema.type, schema, options);
+ }
+ break;
+ case 'enums':
+ if (schema.enum) {
+ content += generateEnumsSection(schema.enum, options);
+ }
+ break;
+ case 'props':
+ if (schema.prop) {
+ content += generatePropsSection(schema.prop, options);
+ }
+ break;
+ }
+ }
+
+ // Add footer
+ content += generateFooter(options);
+
+ // Write to file
+ const outputPath = await transformer.loader.absolute(options.output);
+ await fs.mkdir(path.dirname(outputPath), { recursive: true });
+ await fs.writeFile(outputPath, content, 'utf8');
+}`;
+
+//--------------------------------------------------------------------//
+
+export default function ImplementDocumentationGeneration() {
+ //hooks
+ const { _ } = useLanguage();
+
+ return (
+ <>
+ {/* Implement Documentation Generation Section Content */}
+
+
{_('5. Implement Documentation Generation')}
+
+
+ Create functions to generate different sections of documentation:
+
+
+
+ {documentationGenerationExample}
+
+
+ >
+ )
+}
\ No newline at end of file
diff --git a/packages/www/plugins/docs/components/markdown-documentation-plugin/Introduction.tsx b/packages/www/plugins/docs/components/markdown-documentation-plugin/Introduction.tsx
new file mode 100644
index 0000000..10fb7d7
--- /dev/null
+++ b/packages/www/plugins/docs/components/markdown-documentation-plugin/Introduction.tsx
@@ -0,0 +1,27 @@
+//modules
+import { useLanguage, Translate } from 'r22n';
+//local
+import { H1, P, C } from '../../../docs/components/index.js';
+
+export default function Introduction() {
+ //hooks
+ const { _ } = useLanguage();
+
+ return (
+ <>
+ {/* Creating a Markdown Documentation Plugin */}
+
+
{_('Creating a Markdown Documentation Plugin')}
+
+
+ This tutorial will guide you through creating a plugin that
+ generates comprehensive markdown documentation from a processed
+ .idea schema. You'll learn how to parse schema models,
+ types, enums, and props to create structured documentation with
+ examples and cross-references.
+
+
+
+ >
+ )
+}
\ No newline at end of file
diff --git a/packages/www/plugins/docs/components/markdown-documentation-plugin/Overview.tsx b/packages/www/plugins/docs/components/markdown-documentation-plugin/Overview.tsx
new file mode 100644
index 0000000..6df5410
--- /dev/null
+++ b/packages/www/plugins/docs/components/markdown-documentation-plugin/Overview.tsx
@@ -0,0 +1,50 @@
+//modules
+import { useLanguage, Translate } from 'r22n';
+//local
+import { H1, P } from '../../../docs/components/index.js';
+
+export default function Overview() {
+ //hooks
+ const { _ } = useLanguage();
+
+ return (
+ <>
+ {/* Overview Section Content */}
+
+
+
+ Create a new file mysql-tables-plugin.js. This will be
+ the main entry point for our plugin that handles configuration
+ validation and orchestrates the SQL generation process.
+
+
+
+ Implement the main SQL generation function. This section
+ contains the core logic for creating MySQL CREATE TABLE
+ statements from the processed schema.
+
+
+
+
{_('6.1. Main SQL Generation')}
+
+ {mainSQLGeneration}
+
+
+
{_('6.2. Table SQL Generation')}
+
+ {tableSQLGeneration}
+
+
+
{_('6.3. Column Definition Generation')}
+
+ {columnDefinitionGeneration}
+
+
+
{_('6.4. Foreign Key Generation')}
+
+ {foreignKeyGeneration}
+
+
+ >
+ );
+}
\ No newline at end of file
diff --git a/packages/www/plugins/docs/components/mysql-table-plugin/GeneratedOutput.tsx b/packages/www/plugins/docs/components/mysql-table-plugin/GeneratedOutput.tsx
new file mode 100644
index 0000000..4db034c
--- /dev/null
+++ b/packages/www/plugins/docs/components/mysql-table-plugin/GeneratedOutput.tsx
@@ -0,0 +1,61 @@
+//modules
+import { useLanguage, Translate } from 'r22n';
+//local
+import { H1, H2, P } from '../../../docs/components/index.js';
+import Code from '../../../docs/components/Code.js';
+
+//code examples
+//--------------------------------------------------------------------//
+
+const generatedOutputExample =
+ `-- Generated MySQL Tables
+-- Database: my_app
+-- Generated at: 2024-01-15T10:30:00.000Z
+
+CREATE DATABASE IF NOT EXISTS \`my_app\`;
+USE \`my_app\`;
+
+CREATE TABLE \`User\` (
+ \`id\` VARCHAR(255) NOT NULL COMMENT 'ID',
+ \`email\` VARCHAR(255) NOT NULL COMMENT 'Email',
+ \`name\` VARCHAR(255) NOT NULL COMMENT 'Name',
+ \`age\` TINYINT UNSIGNED NULL COMMENT 'Age',
+ \`role\` ENUM('admin', 'user') NOT NULL DEFAULT 'user' COMMENT 'Role',
+ \`active\` BOOLEAN NOT NULL DEFAULT true COMMENT 'Active',
+ \`created\` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Created',
+ \`updated\` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT 'Updated',
+ PRIMARY KEY (\`id\`),
+ UNIQUE KEY \`uk_User_email\` (\`email\`),
+ KEY \`idx_User_age\` (\`age\`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;`;
+
+//--------------------------------------------------------------------//
+
+export default function GeneratedOutput() {
+ //hooks
+ const { _ } = useLanguage();
+
+ return (
+ <>
+ {/* Generated Output Section Content */}
+
+
{_('8. Generated Output')}
+
+
+ The plugin will generate SQL like this. The output includes
+ proper MySQL syntax with constraints, indexes, and foreign
+ keys.
+
+
+
+ Create a function to map schema types to MySQL types. This
+ function handles the conversion between idea schema types and
+ their corresponding MySQL data types.
+
+
+
{_('Type Mapping Function')}
+
+ {typeMappingFunction}
+
+
+ >
+ );
+}
\ No newline at end of file
diff --git a/packages/www/plugins/docs/components/mysql-table-plugin/Introduction.tsx b/packages/www/plugins/docs/components/mysql-table-plugin/Introduction.tsx
new file mode 100644
index 0000000..c8baca9
--- /dev/null
+++ b/packages/www/plugins/docs/components/mysql-table-plugin/Introduction.tsx
@@ -0,0 +1,25 @@
+//modules
+import { useLanguage, Translate } from 'r22n';
+//local
+import { H1, P } from '../../../docs/components/index.js';
+
+export default function Introduction() {
+ //hooks
+ const { _ } = useLanguage();
+
+ return (
+ <>
+ {/* Creating a MySQL Tables Plugin */}
+
+
{_('Creating a MySQL Tables Plugin')}
+
+
+ This tutorial will guide you through creating a plugin
+ that generates MySQL CREATE TABLE statements from a
+ processed .idea schema.
+
+
+
+ >
+ );
+}
\ No newline at end of file
diff --git a/packages/www/plugins/docs/components/mysql-table-plugin/Overview.tsx b/packages/www/plugins/docs/components/mysql-table-plugin/Overview.tsx
new file mode 100644
index 0000000..509a428
--- /dev/null
+++ b/packages/www/plugins/docs/components/mysql-table-plugin/Overview.tsx
@@ -0,0 +1,52 @@
+
+//modules
+import { useLanguage, Translate } from 'r22n';
+//local
+import { H1, P } from '../../../docs/components/index.js';
+
+export default function Overview() {
+ //hooks
+ const { _ } = useLanguage();
+
+ return (
+ <>
+ {/* Overview Section Content */}
+
+
+
+ Before creating the plugin, let's understand what a processed
+ schema looks like. The schema structure contains models, enums,
+ and other configuration data that our plugin will process.
+
+
+
{_('Example Schema Structure')}
+
+ {schemaStructureExample}
+
+
+ >
+ );
+}
\ No newline at end of file
diff --git a/packages/www/plugins/docs/components/mysql-table-plugin/UsageInSchema.tsx b/packages/www/plugins/docs/components/mysql-table-plugin/UsageInSchema.tsx
new file mode 100644
index 0000000..192b531
--- /dev/null
+++ b/packages/www/plugins/docs/components/mysql-table-plugin/UsageInSchema.tsx
@@ -0,0 +1,64 @@
+//modules
+import { useLanguage, Translate } from 'r22n';
+//local
+import { H1, H2, P } from '../../../docs/components/index.js';
+import Code from '../../../docs/components/Code.js';
+
+//code examples
+//--------------------------------------------------------------------//
+
+const schemaUsageExample =
+ `// schema.idea
+plugin "./plugins/mysql-tables-plugin.js" {
+ output "./database/tables.sql"
+ database "my_app"
+ engine "InnoDB"
+ charset "utf8mb4"
+ collation "utf8mb4_unicode_ci"
+}
+
+model User {
+ id String @id @default("nanoid()")
+ email String @unique @field.input(Email)
+ name String @field.input(Text)
+ age Number @unsigned @min(0) @max(150)
+ role UserRole @default("USER")
+ active Boolean @default(true)
+ created Date @default("now()")
+ updated Date @default("updated()")
+}
+
+enum UserRole {
+ ADMIN "admin"
+ USER "user"
+}`;
+
+//--------------------------------------------------------------------//
+
+export default function UsageInSchema() {
+ //hooks
+ const { _ } = useLanguage();
+
+ return (
+ <>
+ {/* Usage In Schema Section Content */}
+
+
{_('7. Usage in Schema')}
+
+
+ To use this plugin in your schema file, add the plugin
+ declaration with appropriate configuration options.
+
+
+
{_('Schema Configuration')}
+
+ {schemaUsageExample}
+
+
+ >
+ );
+}
\ No newline at end of file
diff --git a/packages/www/plugins/docs/components/mysql-table-plugin/index.tsx b/packages/www/plugins/docs/components/mysql-table-plugin/index.tsx
new file mode 100644
index 0000000..7ae20ca
--- /dev/null
+++ b/packages/www/plugins/docs/components/mysql-table-plugin/index.tsx
@@ -0,0 +1,12 @@
+//exporting all components to have multiple imports from a single file
+export { default as BestPractices } from './BestPractices.js';
+export { default as Conclusion } from './Conclusion.js';
+export { default as CreatePluginStructure } from './CreatePluginStructure.js';
+export { default as GeneratedOutput } from './GeneratedOutput.js';
+export { default as GenerateSqlStatements } from './GenerateSqlStatements.js';
+export { default as ImplementTypeMapping } from './ImplementTypeMapping.js';
+export { default as Introduction } from './Introduction.js';
+export { default as Overview } from './Overview.js';
+export { default as Prerequisites } from './Prerequisites.js';
+export { default as UnderstandingSchemaStructure } from './UnderstandingSchemaStructure.js';
+export { default as UsageInSchema } from './UsageInSchema.js';
\ No newline at end of file
diff --git a/packages/www/plugins/docs/components/openapi-specification-plugin/AdvancedFeatures.tsx b/packages/www/plugins/docs/components/openapi-specification-plugin/AdvancedFeatures.tsx
new file mode 100644
index 0000000..238ec9b
--- /dev/null
+++ b/packages/www/plugins/docs/components/openapi-specification-plugin/AdvancedFeatures.tsx
@@ -0,0 +1,305 @@
+//modules
+import { useLanguage, Translate } from 'r22n';
+//local
+import { H1, H2, P } from '../../../docs/components/index.js';
+import Code from '../../../docs/components/Code.js';
+
+//code examples
+//--------------------------------------------------------------------//
+
+const advancedConfigExample =
+ `interface AdvancedOpenAPIConfig extends OpenAPIConfig {
+ formats?: ('json' | 'yaml' | 'html')[];
+ validation?: {
+ strict?: boolean;
+ examples?: boolean;
+ };
+ documentation?: {
+ includeExamples?: boolean;
+ includeSchemas?: boolean;
+ customTemplates?: string;
+ };
+}
+
+export default async function generateAdvancedOpenAPISpec(
+ props: PluginProps<{ config: AdvancedOpenAPIConfig }>
+) {
+ const { config, schema, transformer } = props;
+
+ const spec = generateSpecification(schema, config);
+
+ // Add validation and examples
+ if (config.validation?.examples) {
+ addExamples(spec, schema);
+ }
+
+ if (config.validation?.strict) {
+ validateSpecification(spec);
+ }
+
+ // Generate multiple formats
+ const formats = config.formats || ['json'];
+ const outputBase = config.output.replace(/\\.[^.]+$/, '');
+
+ for (const format of formats) {
+ await generateFormat(spec, format, outputBase, transformer);
+ }
+}`;
+
+//--------------------------------------------------------------------//
+
+const formatGenerationExample =
+ `async function generateFormat(
+ spec: any,
+ format: string,
+ outputBase: string,
+ transformer: any
+): Promise {
+ let content: string;
+ let extension: string;
+
+ switch (format) {
+ case 'json':
+ content = JSON.stringify(spec, null, 2);
+ extension = '.json';
+ break;
+ case 'yaml':
+ const yaml = await import('yaml');
+ content = yaml.stringify(spec);
+ extension = '.yaml';
+ break;
+ case 'html':
+ content = generateHTMLDocumentation(spec);
+ extension = '.html';
+ break;
+ default:
+ throw new Error(\`Unsupported format: \${format}\`);
+ }
+
+ const outputPath = await transformer.loader.absolute(\`\${outputBase}\${extension}\`);
+ await fs.writeFile(outputPath, content, 'utf8');
+ console.log(\`✅ Generated \${format.toUpperCase()} specification: \${outputPath}\`);
+}`;
+
+//--------------------------------------------------------------------//
+
+const exampleGenerationExample =
+ `function addExamples(spec: any, schema: any): void {
+ // Add examples to schemas
+ for (const [name, schemaObj] of Object.entries(spec.components.schemas)) {
+ if (schemaObj.type === 'object') {
+ schemaObj.example = generateExample(schemaObj, schema);
+ }
+ }
+
+ // Add examples to endpoints
+ for (const [path, pathObj] of Object.entries(spec.paths)) {
+ for (const [method, operation] of Object.entries(pathObj)) {
+ if (operation.requestBody?.content?.['application/json']?.schema) {
+ const schema = operation.requestBody.content['application/json'].schema;
+ if (!schema.example) {
+ schema.example = generateExample(schema, schema);
+ }
+ }
+ }
+ }
+}
+
+function generateExample(schemaObj: any, fullSchema: any): any {
+ if (schemaObj.$ref) {
+ const refName = schemaObj.$ref.split('/').pop();
+ return generateExample(fullSchema.components?.schemas?.[refName] || {}, fullSchema);
+ }
+
+ if (schemaObj.type === 'object') {
+ const example: any = {};
+ for (const [propName, propSchema] of Object.entries(schemaObj.properties || {})) {
+ example[propName] = generatePropertyExample(propSchema);
+ }
+ return example;
+ }
+
+ if (schemaObj.type === 'array') {
+ return [generateExample(schemaObj.items, fullSchema)];
+ }
+
+ return generatePropertyExample(schemaObj);
+}
+
+function generatePropertyExample(propSchema: any): any {
+ if (propSchema.example !== undefined) {
+ return propSchema.example;
+ }
+
+ if (propSchema.enum) {
+ return propSchema.enum[0];
+ }
+
+ switch (propSchema.type) {
+ case 'string':
+ if (propSchema.format === 'email') return 'user@example.com';
+ if (propSchema.format === 'date-time') return new Date().toISOString();
+ if (propSchema.format === 'date') return new Date().toISOString().split('T')[0];
+ return 'string';
+ case 'number':
+ return 42.5;
+ case 'integer':
+ return 42;
+ case 'boolean':
+ return true;
+ case 'array':
+ return [generatePropertyExample(propSchema.items)];
+ case 'object':
+ return {};
+ default:
+ return null;
+ }
+}`;
+
+//--------------------------------------------------------------------//
+
+const validationExample =
+ `function validateSpecification(spec: any): void {
+ // Basic validation
+ if (!spec.openapi) {
+ throw new Error('OpenAPI version is required');
+ }
+
+ if (!spec.info?.title) {
+ throw new Error('API title is required');
+ }
+
+ if (!spec.info?.version) {
+ throw new Error('API version is required');
+ }
+
+ // Validate paths
+ for (const [path, pathObj] of Object.entries(spec.paths)) {
+ if (!path.startsWith('/')) {
+ throw new Error(\`Path must start with '/': \${path}\`);
+ }
+
+ for (const [method, operation] of Object.entries(pathObj)) {
+ if (!operation.responses) {
+ throw new Error(\`Operation \${method.toUpperCase()} \${path} must have responses\`);
+ }
+ }
+ }
+
+ console.log('✅ OpenAPI specification validation passed');
+}`;
+
+//--------------------------------------------------------------------//
+
+const htmlGenerationExample =
+ `function generateHTMLDocumentation(spec: any): string {
+ return \`
+
+
+
+
+
+ \${spec.info.title} - API Documentation
+
+
+
+
+
+
+
+
+
+\`;
+}`;
+
+//--------------------------------------------------------------------//
+
+export default function AdvancedFeatures() {
+ //hooks
+ const { _ } = useLanguage();
+
+ return (
+ <>
+ {/* Advanced Features Section Content */}
+
+
{_('5. Advanced Features')}
+
+
{_('5.1. Multiple Output Formats')}
+
+
+ Multiple output formats allow you to generate OpenAPI
+ specifications in JSON, YAML, and HTML formats. This
+ flexibility ensures compatibility with different tools
+ and enables both machine-readable specifications and
+ human-friendly documentation.
+
+
+
+ The basic implementation provides the foundation for
+ generating OpenAPI specifications from .idea
+ schema files. This section covers the core plugin
+ structure, configuration interface, and essential
+ generation functions needed to create functional API
+ documentation.
+
+
+
+
+ Let's start with a basic OpenAPI specification generator:
+
+
+
+
{_('2.1. Plugin Structure')}
+
+
+ The plugin structure defines the main entry point and
+ configuration interface for the OpenAPI generator. This
+ includes type definitions for configuration options, the
+ primary plugin function, and the core specification
+ generation logic.
+
+
+
+ Schema generation transforms
+ .idea
+ model and type definitions into OpenAPI-compliant schema
+ objects. This process includes mapping data types, handling
+ validation rules, and creating proper JSON Schema structures
+ that integrate with OpenAPI tooling.
+
+
+
+ Best practices ensure your generated OpenAPI specifications
+ are comprehensive, maintainable, and follow industry
+ standards. These guidelines cover documentation quality,
+ error handling, security implementation, and validation
+ strategies.
+
+
+
+
{_('7.1. Comprehensive Documentation')}
+
+
+ Comprehensive documentation practices ensure your API
+ specifications provide clear, detailed information for both
+ human readers and automated tools. This includes proper
+ descriptions, examples, and consistent formatting throughout
+ the specification.
+
+
+
+ {documentationBestPracticesExample}
+
+
+
{_('7.2. Consistent Error Responses')}
+
+
+ Consistent error responses provide standardized error
+ handling across your API endpoints. This approach ensures
+ predictable error formats that client applications can
+ handle reliably, improving the overall developer experience.
+
+
+
+ {errorResponsesExample}
+
+
+
{_('7.3. Security Best Practices')}
+
+
+ Security best practices ensure your API documentation
+ properly represents authentication and authorization
+ requirements. This includes applying appropriate security
+ schemes to endpoints and documenting access control patterns.
+
+
+
+ {securityBestPracticesExample}
+
+
+
{_('7.4. Validation and Testing')}
+
+
+ Validation and testing practices ensure your generated
+ OpenAPI specifications are accurate and functional. This
+ includes adding validation examples, testing request/response
+ formats, and verifying specification compliance.
+
+
+
+ {validationExamplesExample}
+
+
+ >
+ );
+}
\ No newline at end of file
diff --git a/packages/www/plugins/docs/components/openapi-specification-plugin/Conclusion.tsx b/packages/www/plugins/docs/components/openapi-specification-plugin/Conclusion.tsx
new file mode 100644
index 0000000..9b83a13
--- /dev/null
+++ b/packages/www/plugins/docs/components/openapi-specification-plugin/Conclusion.tsx
@@ -0,0 +1,114 @@
+//modules
+import { useLanguage, Translate } from 'r22n';
+//local
+import { H1, H2, P, C, SS } from '../../../docs/components/index.js';
+
+export default function Conclusion() {
+ //hooks
+ const { _ } = useLanguage();
+
+ return (
+ <>
+ {/* Conclusion Section Content */}
+
+
{_('Conclusion')}
+
+
+ This OpenAPI Specification Generator plugin provides a
+ comprehensive solution for generating API documentation from
+ .idea schema files. Key features include:
+
+
+ Multiple Output Formats:
+
+ JSON, YAML, and HTML documentation
+
+
+
+ Validation and Examples:
+
+ Includes request/response examples and validation
+
+
+
+ Extensible Configuration:
+
+ Highly customizable for different use cases
+
+
+
+
+
+
+ The plugin follows TypeScript best practices and provides
+ comprehensive error handling, making it suitable for
+ production use in API development workflows.
+
+
+
+
{_('Next Steps')}
+
+
+ Extend Schema Mapping:
+
+ Add support for more complex schema relationships
+
+
+ Plugin Ecosystem:
+
+ Create complementary plugins for API testing and
+ client generation
+
+
+
+
+
+
+ This tutorial provides a solid foundation for generating
+ professional API documentation that can be used with tools
+ like Swagger UI, Postman, and various code generators.
+
+
+
+ Configuration options control how the OpenAPI specification
+ is generated, including output formats, API metadata, server
+ definitions, and security schemes. Proper configuration
+ ensures the generated documentation meets your specific
+ requirements and integrates with your development workflow.
+
+
+
+ {configurationExample}
+
+
+ >
+ );
+}
\ No newline at end of file
diff --git a/packages/www/plugins/docs/components/openapi-specification-plugin/Introduction.tsx b/packages/www/plugins/docs/components/openapi-specification-plugin/Introduction.tsx
new file mode 100644
index 0000000..cb8b353
--- /dev/null
+++ b/packages/www/plugins/docs/components/openapi-specification-plugin/Introduction.tsx
@@ -0,0 +1,27 @@
+//modules
+import { useLanguage, Translate } from 'r22n';
+//local
+import { H1, P, C } from '../../../docs/components/index.js';
+
+export default function Introduction() {
+ //hooks
+ const { _ } = useLanguage();
+
+ return (
+ <>
+ {/* Creating an OpenAPI Specification Generator Plugin */}
+
+
+
+ This tutorial demonstrates how to create a plugin for
+ @stackpress/idea-transformer that generates OpenAPI
+ 3.0 specifications from .idea schema files. The
+ plugin will create comprehensive API documentation with
+ endpoints, schemas, and validation rules.
+
+
+
+ >
+ );
+}
\ No newline at end of file
diff --git a/packages/www/plugins/docs/components/openapi-specification-plugin/Overview.tsx b/packages/www/plugins/docs/components/openapi-specification-plugin/Overview.tsx
new file mode 100644
index 0000000..2503334
--- /dev/null
+++ b/packages/www/plugins/docs/components/openapi-specification-plugin/Overview.tsx
@@ -0,0 +1,102 @@
+//modules
+import { useLanguage, Translate } from 'r22n';
+//local
+import { H1, H2, P, C } from '../../../docs/components/index.js';
+
+export default function Overview() {
+ //hooks
+ const { _ } = useLanguage();
+
+ return (
+ <>
+ {/* Overview Section Content */}
+
+
{_('1. Overview')}
+
+
+ OpenAPI (formerly Swagger) specifications provide a
+ standard way to document REST APIs. This plugin transforms
+ your .idea schema definitions into comprehensive
+ API documentation that follows industry standards and
+ integrates seamlessly with existing API development
+ workflows.
+
+
+
+ Generate security schemes and authentication
+
+
+
+
+
{_('What You\'ll Learn')}
+
+
+ This section outlines the key concepts and skills you'll
+ acquire through this tutorial. Understanding these fundamentals
+ will enable you to create robust API documentation that serves
+ both developers and automated tooling.
+
+
+
+
+
+ Processing idea schemas for API documentation
+
+
+
+ Schema processing handles the transformation of .idea
+ definitions into OpenAPI components and endpoints. This
+ includes generating security schemes, creating CRUD endpoints
+ for models, and handling complex schema relationships and
+ validations.
+
+
+
+ This section addresses common issues encountered when
+ generating OpenAPI specifications and provides solutions
+ for debugging and resolving problems. Understanding these
+ troubleshooting techniques helps ensure reliable
+ specification generation.
+
+
+
+
{_('8.1. Common Issues')}
+
+
+ Common issues include schema reference errors, validation
+ failures, and performance problems with large specifications.
+ These problems typically arise from circular references,
+ invalid configurations, or missing dependencies.
+
+
+
+
{_('8.1.1. Schema Reference Errors')}
+
+
+ Schema reference errors occur when the generator encounters
+ circular dependencies or invalid references between schema
+ components. These issues can break the specification
+ generation process and require careful handling of schema
+ relationships.
+
+
+
+ {circularReferencesExample}
+
+
+
{_('8.1.2. Invalid OpenAPI Format')}
+
+
+ Invalid OpenAPI format errors occur when the generated
+ specification doesn't conform to OpenAPI standards. These
+ validation failures can prevent the specification from
+ working with OpenAPI tools and require comprehensive
+ validation during generation.
+
+
+
+ {validationErrorsExample}
+
+
+
{_('8.1.3. Missing Dependencies')}
+
+
+ Missing dependencies can cause the plugin to fail during
+ execution or limit available features. Ensuring all required
+ packages are installed and properly configured is essential
+ for reliable operation.
+
+
+
+ {dependenciesExample}
+
+
+
{_('8.1.4. Performance Issues')}
+
+
+ Performance issues can occur when generating specifications
+ for large schemas with many models and complex relationships.
+ Optimization techniques help maintain reasonable generation
+ times and manageable output file sizes.
+
+
+
+ {performanceOptimizationExample}
+
+
+
{_('8.2. Debug Mode')}
+
+
+ Debug mode provides detailed logging and diagnostic
+ information during specification generation. This feature
+ helps identify issues, understand the generation process,
+ and optimize plugin configuration for better results.
+
+
+
+ Usage examples demonstrate practical applications of the
+ OpenAPI generator plugin with real-world scenarios. These
+ examples show how to configure the plugin for different
+ use cases and integrate the generated documentation into
+ your development workflow.
+
+
+
+
{_('6.1. Basic Usage')}
+
+
+ Basic usage examples show the fundamental configuration
+ needed to generate OpenAPI specifications from simple
+ .idea
+ schemas. This includes model definitions, plugin
+ configuration, and the resulting API documentation structure.
+
+
+
+ {basicUsageExample}
+
+
+
{_('6.2. Advanced Configuration')}
+
+
+ Advanced configuration demonstrates comprehensive plugin
+ setup with multiple output formats, detailed API metadata,
+ custom endpoints, and security schemes. This example shows
+ how to create production-ready API documentation with full
+ feature coverage.
+
+
+
+ {advancedUsageExample}
+
+
+
{_('6.3. CLI Integration')}
+
+
+ CLI integration shows how to incorporate the OpenAPI
+ generator into your development workflow using command-line
+ tools. This includes generating specifications, serving
+ documentation locally, and integrating with API development
+ tools.
+
+
+
+ {cliIntegrationExample}
+
+
+ >
+ );
+}
\ No newline at end of file
diff --git a/packages/www/plugins/docs/components/openapi-specification-plugin/index.tsx b/packages/www/plugins/docs/components/openapi-specification-plugin/index.tsx
new file mode 100644
index 0000000..5f7ebb2
--- /dev/null
+++ b/packages/www/plugins/docs/components/openapi-specification-plugin/index.tsx
@@ -0,0 +1,11 @@
+//exporting all components to have multiple imports from a single file
+export { default as AdvancedFeatures } from './AdvancedFeatures.js';
+export { default as BasicImplementation } from './BasicImplementation.js';
+export { default as BestPractices } from './BestPractices.js';
+export { default as Conclusion } from './Conclusion.js';
+export { default as ConfigurationOptions } from './ConfigurationOptions.js';
+export { default as Introduction } from './Introduction.js';
+export { default as Overview } from './Overview.js';
+export { default as SchemaProcessing } from './SchemaProcessing.js';
+export { default as Troubleshooting } from './Troubleshooting.js';
+export { default as UsageExamples } from './UsageExamples.js';
\ No newline at end of file
diff --git a/packages/www/plugins/docs/components/specifications/data-types/Enums.tsx b/packages/www/plugins/docs/components/specifications/data-types/Enums.tsx
new file mode 100644
index 0000000..e20ac34
--- /dev/null
+++ b/packages/www/plugins/docs/components/specifications/data-types/Enums.tsx
@@ -0,0 +1,152 @@
+//modules
+import { useLanguage, Translate } from 'r22n';
+//local
+import { H1, H2, P, SS } from '../../../../docs/components/index.js';
+import Code from '../../../../docs/components/Code.js';
+
+//code examples
+//--------------------------------------------------------------------//
+
+const enumsExamples = [
+ `enum EnumName {
+ KEY1 "Display Value 1"
+ KEY2 "Display Value 2"
+ KEY3 "Display Value 3"
+}`,
+
+ //------------------------------------------------------------------//
+
+ `enum UserRole {
+ ADMIN "Administrator"
+ MODERATOR "Moderator"
+ USER "Regular User"
+ GUEST "Guest User"
+}
+
+enum OrderStatus {
+ PENDING "Pending Payment"
+ PAID "Payment Confirmed"
+ SHIPPED "Order Shipped"
+ DELIVERED "Order Delivered"
+ CANCELLED "Order Cancelled"
+}
+
+enum Priority {
+ LOW "Low Priority"
+ MEDIUM "Medium Priority"
+ HIGH "High Priority"
+ URGENT "Urgent"
+}`,
+
+ //------------------------------------------------------------------//
+
+ `export enum UserRole {
+ ADMIN = "Administrator",
+ MODERATOR = "Moderator",
+ USER = "Regular User",
+ GUEST = "Guest User"
+}`,
+
+ //------------------------------------------------------------------//
+
+ `{
+ "enum": {
+ "UserRole": {
+ "ADMIN": "Administrator",
+ "MODERATOR": "Moderator",
+ "USER": "Regular User",
+ "GUEST": "Guest User"
+ }
+ }
+}`
+];
+
+//--------------------------------------------------------------------//
+
+export default function Enums() {
+ //hooks
+ const { _ } = useLanguage();
+
+ return (
+ <>
+ {/* Enums Section Content */}
+
+
{_('Enums')}
+
+
+
+ Enums define a set of named constants with associated values,
+ perfect for representing fixed sets of options like user roles,
+ status values, or categories.
+
+
+
+
{_('Syntax')}
+
+
+ {enumsExamples[0]}
+
+
+
{_('Structure')}
+
+
+ {_('EnumName: ')}
+
+ The identifier used to reference this enum
+
+
+
+ {_('KEY: ')}
+
+ The constant name (typically uppercase)
+
+
+
+ {_('"Display Value": ')}
+
+ Human-readable label for the constant
+
+
+
+
+
{_('Example')}
+
+
+ {enumsExamples[1]}
+
+
+
{_('Generate Output')}
+
+
+
+ When processed, enums generate language-specific constants:
+
+
+
+
{_('TypeScript:')}
+
+
+ {enumsExamples[2]}
+
+
+
{_('JSON:')}
+
+
+ {enumsExamples[3]}
+
+
+ >
+ )
+}
diff --git a/packages/www/plugins/docs/components/specifications/data-types/Models.tsx b/packages/www/plugins/docs/components/specifications/data-types/Models.tsx
new file mode 100644
index 0000000..e5d940f
--- /dev/null
+++ b/packages/www/plugins/docs/components/specifications/data-types/Models.tsx
@@ -0,0 +1,189 @@
+//modules
+import { useLanguage, Translate } from 'r22n';
+//local
+import { H1, H2, P, SS, C } from '../../../../docs/components/index.js';
+import Code from '../../../../docs/components/Code.js';
+
+//code examples
+//--------------------------------------------------------------------//
+
+const modelsExamples = [
+ `model ModelName {
+ columnName DataType @attribute1 @attribute2
+ relationColumn RelatedModel @relation
+}
+
+model ModelName! { // Mutable model
+ // columns...
+}`,
+
+ //------------------------------------------------------------------//
+
+ `// base-schema.idea
+model User {
+ id String @id
+ name String @required
+}
+
+// extended-schema.idea
+use "./base-schema.idea"
+
+// This will merge with the imported User model
+model User {
+ email String @required
+ created Date @default("now()")
+}
+
+// This will NOT merge - it completely replaces the imported User
+model User! {
+ id String @id
+ username String @required
+ password String @required
+}`,
+
+ //------------------------------------------------------------------//
+
+ `model User! {
+ id String @id @default("nanoid()")
+ email String @unique @required @field.input(Email)
+ username String @unique @required @field.input(Text)
+ password String @required @field.input(Password)
+ profile UserProfile?
+ role UserRole @default("USER")
+ active Boolean @default(true)
+ lastLogin Date?
+ created Date @default("now()")
+ updated Date @default("updated()")
+}
+
+model UserProfile {
+ id String @id @default("nanoid()")
+ userId String @relation(User.id)
+ firstName String @required @field.input(Text)
+ lastName String @required @field.input(Text)
+ bio String @field.textarea
+ avatar String @field.upload
+ address Address
+ contact ContactInfo
+ preferences {
+ theme String @default("light")
+ language String @default("en")
+ notifications Boolean @default(true)
+ }
+}
+
+model Post {
+ id String @id @default("nanoid()")
+ title String @required @field.input(Text)
+ slug String @unique @generated
+ content String @required @field.richtext
+ excerpt String @field.textarea
+ authorId String @relation(User.id)
+ author User @relation(User, authorId)
+ status PostStatus @default("DRAFT")
+ tags String[] @field.tags
+ publishedAt Date?
+ created Date @default("now()")
+ updated Date @default("updated()")
+}
+
+enum PostStatus {
+ DRAFT "Draft"
+ PUBLISHED "Published"
+ ARCHIVED "Archived"
+}`
+];
+
+//--------------------------------------------------------------------//
+
+export default function Models() {
+ //hooks
+ const { _ } = useLanguage();
+
+ return (
+ <>
+ {/* Models Section Content */}
+
+
{_('Models')}
+
+
+
+ Models represent the core entities in your application,
+ typically corresponding to database tables or API
+ resources. They define the structure, relationships, and
+ behavior of your data.
+
+
+
+
+
{_('Syntax')}
+
+ {modelsExamples[0]}
+
+
+
{_('Structure')}
+
+
+ {_('ModelName: ')}
+ The identifier for this model
+
+
+ !:
+
+ Optional non-mergeable indicator prevents automatic
+ merging when using use directives
+
+
+
+ {_('columnName: ')}
+ The field name within the model
+
+ {_('@attribute: ')}
+
+ Attributes for validation, relationships, UI, etc.
+
+
+
+
+
{_('Merging Behavior')}
+
+
+
+ By default, when importing schemas with use directives,
+ models with the same name are automatically merged. The !
+ suffix prevents this behavior:
+
+
+
+ Props are reusable property configurations that define common
+ field behaviors, validation rules, and UI components. They
+ promote consistency and reduce duplication across your schema.
+
+
+
+
{_('Syntax')}
+
+ {propsExamples[0]}
+
+
+
{_('Structure')}
+
+
+
+ {_('PropName:')}
+
+ The identifier used to reference this prop
+
+
+
+ Types define custom data structures with multiple columns,
+ similar to objects or structs in programming languages. They
+ are perfect for representing complex data that doesn't warrant
+ a full model.
+
+
+
+
{_('Syntax')}
+
+ {typeExamples[0]}
+
+
+
{_('Structure')}
+
+
+
+ {_('TypeName: ')}
+
+ The identifier used to reference this type
+
+
+
+ {_('columnName: ')}
+ The field name within the type
+
+
+ {_('DataType: ')}
+
+ The data type (String, Number, Boolean, Date, etc.)
+
+
+
+ {_('attribute: ')}
+
+ Optional attributes for validation, UI, or behavior
+
+
+
+ The plugin directive configures code generation
+ plugins that process your schema and generate various
+ outputs like TypeScript interfaces, database schemas, API
+ documentation, and more.
+
+
+
+ Plugins are JavaScript/TypeScript modules that export a
+ default function:
+
+
+
+ {pluginExamples[4]}
+
+
+
+ >
+ );
+}
diff --git a/packages/www/plugins/docs/components/specifications/schema-directives/Use.tsx b/packages/www/plugins/docs/components/specifications/schema-directives/Use.tsx
new file mode 100644
index 0000000..3609c94
--- /dev/null
+++ b/packages/www/plugins/docs/components/specifications/schema-directives/Use.tsx
@@ -0,0 +1,252 @@
+//modules
+import { useLanguage, Translate } from 'r22n';
+//local
+import { H1, H2, P, SS, C } from '../../../../docs/components/index.js';
+import Code from '../../../../docs/components/Code.js';
+
+//code examples
+//--------------------------------------------------------------------//
+
+const useExamples = [
+ `use "package/to/schema.idea"
+use "./relative/path/schema.idea"
+use "../parent/directory/schema.idea"`,
+
+ //------------------------------------------------------------------//
+
+ `// Common types used across multiple schemas
+type Address {
+ street String @required
+ city String @required
+ country String @default("US")
+}
+
+enum Status {
+ ACTIVE "Active"
+ INACTIVE "Inactive"
+}
+
+prop Email {
+ type "email"
+ validation {
+ required true
+ format "email"
+ }
+}`,
+
+ //------------------------------------------------------------------//
+
+ `// Import common definitions
+use "../shared/common.idea"
+
+// Extend the Status enum (will merge with imported one)
+enum Status {
+ PENDING "Pending Approval"
+ SUSPENDED "Temporarily Suspended"
+}
+
+// Use imported types and props
+model User {
+ id String @id @default("nanoid()")
+ email String @field.input(Email)
+ address Address
+ status Status @default("PENDING")
+}`,
+
+ //------------------------------------------------------------------//
+
+ `// The Status enum now contains all values
+enum Status {
+ ACTIVE "Active" // From common.idea
+ INACTIVE "Inactive" // From common.idea
+ PENDING "Pending Approval" // From user-schema.idea
+ SUSPENDED "Temporarily Suspended" // From user-schema.idea
+}`,
+
+ //------------------------------------------------------------------//
+
+ `enum UserRole {
+ USER "Regular User"
+ ADMIN "Administrator"
+}`,
+
+ //------------------------------------------------------------------//
+
+ `use "./base-schema.idea"
+
+// This will NOT merge with the imported UserRole
+// Instead, it will override it completely
+enum UserRole! {
+ GUEST "Guest User"
+ MEMBER "Member"
+ MODERATOR "Moderator"
+ ADMIN "Administrator"
+}`,
+
+ //------------------------------------------------------------------//
+
+ `// ✅ Good - organize by domain
+use "./shared/common-types.idea"
+use "./auth/user-types.idea"
+use "./commerce/product-types.idea"
+
+// ✅ Good - clear file naming
+use "./enums/status-enums.idea"
+use "./types/address-types.idea"
+use "./props/form-props.idea"
+
+// ❌ Avoid - unclear imports
+use "./stuff.idea"
+use "./misc.idea"`
+];
+
+//--------------------------------------------------------------------//
+
+export default function Use() {
+ //hooks
+ const { _ } = useLanguage();
+
+ return (
+ <>
+ {/* Use Section Content */}
+
+
{_('Use')}
+
+
+ The use directive imports definitions from other{' '}
+ .idea files, enabling modular schema organization and{' '}
+ reusability. When importing, data types with the same name are{' '}
+ automatically merged unless the ! (non-mergeable){' '}
+ indicator is used.
+
+
+ {_('Shared Types:')}{' '}
+ {_('Define common types once and reuse across multiple schemas')}
+
+
+ {_('Modular Organization:')}{' '}
+ {_('Split large schemas into manageable, focused files')}
+
+
+ {_('Team Collaboration:')}{' '}
+ {_('Different teams can work on separate schema files')}
+
+
+ {_('Environment-Specific:')}{' '}
+ {_('Override certain definitions for different environments')}
+
+
+
+
+ {/* Best Practices Section Content */}
+
+
{_('Best Practices')}
+
+ {useExamples[6]}
+
+
+
+ >
+ );
+}
diff --git a/packages/www/plugins/docs/components/specifications/schema-directives/index.tsx b/packages/www/plugins/docs/components/specifications/schema-directives/index.tsx
new file mode 100644
index 0000000..78056b1
--- /dev/null
+++ b/packages/www/plugins/docs/components/specifications/schema-directives/index.tsx
@@ -0,0 +1,3 @@
+//exporting all components to have multiple imports from a single file
+export { default as Plugin } from './Plugin.js';
+export { default as Use } from './Use.js';
\ No newline at end of file
diff --git a/packages/www/plugins/docs/components/test-data-plugin/Conclusion.tsx b/packages/www/plugins/docs/components/test-data-plugin/Conclusion.tsx
new file mode 100644
index 0000000..12b336e
--- /dev/null
+++ b/packages/www/plugins/docs/components/test-data-plugin/Conclusion.tsx
@@ -0,0 +1,26 @@
+//modules
+import { useLanguage, Translate } from 'r22n';
+//local
+import { H1, P } from '../../../docs/components/index.js';
+
+export default function Conclusion() {
+ //hooks
+ const { _ } = useLanguage();
+
+ return (
+ <>
+ {/* Conclusion Section Content */}
+
+
{_('Conclusion')}
+
+
+ This tutorial provides a comprehensive foundation for
+ creating test data generation plugins that can handle
+ complex schemas and generate realistic, useful test data
+ for development and testing workflows.
+
+
+
+ >
+ );
+}
\ No newline at end of file
diff --git a/packages/www/plugins/docs/components/test-data-plugin/CorePluginFunction.tsx b/packages/www/plugins/docs/components/test-data-plugin/CorePluginFunction.tsx
new file mode 100644
index 0000000..b6f2fed
--- /dev/null
+++ b/packages/www/plugins/docs/components/test-data-plugin/CorePluginFunction.tsx
@@ -0,0 +1,142 @@
+//modules
+import { useLanguage, Translate } from 'r22n';
+//local
+import { H1, H2, P } from '../../../docs/components/index.js';
+import Code from '../../../docs/components/Code.js';
+
+//code examples
+//--------------------------------------------------------------------//
+
+const corePluginExample =
+`export default async function generateTestData(
+ props: PluginProps<{ config: TestDataConfig }>
+) {
+ const { config, schema, transformer } = props;
+
+ try {
+ // Validate configuration
+ validateConfig(config);
+
+ // Generate test data content
+ let content = '';
+
+ // Add file header and imports
+ content += generateFileHeader(config);
+ content += generateImports(config);
+
+ // Generate data factories if requested
+ if (config.generateFactories) {
+ content += generateFactories(schema, config);
+ }
+
+ // Generate mock data
+ if (schema.model) {
+ content += generateMockData(schema.model, config);
+ }
+
+ // Generate fixtures if requested
+ if (config.generateFixtures) {
+ content += generateFixtures(schema, config);
+ }
+
+ // Generate main export
+ content += generateMainExport(schema, config);
+
+ // Write to output file
+ const outputPath = await transformer.loader.absolute(config.output);
+ await fs.mkdir(path.dirname(outputPath), { recursive: true });
+ await fs.writeFile(outputPath, content, 'utf8');
+
+ console.log(\`✅ Test data generated: \${outputPath}\`);
+
+ } catch (error) {
+ console.error('❌ Test data generation failed:', error.message);
+ throw error;
+ }
+}`;
+
+//--------------------------------------------------------------------//
+
+const headerAndImportsExample =
+`function generateFileHeader(config: TestDataConfig): string {
+ const timestamp = new Date().toISOString();
+ return \`/**
+ * Generated Test Data and Fixtures
+ * Generated at: \${timestamp}
+ * Format: \${config.format}
+ * Count: \${config.count || 10}
+ * Seed: \${config.seed || 'random'}
+ *
+ * This file is auto-generated. Do not edit manually.
+ */
+
+\`;
+}
+
+function generateImports(config: TestDataConfig): string {
+ let imports = '';
+
+ if (config.format === 'typescript' || config.format === 'javascript') {
+ imports += \`import { faker } from '@faker-js/faker';\\n\\n\`;
+
+ if (config.seed) {
+ imports += \`// Set seed for reproducible data\\nfaker.seed(\${config.seed});\\n\\n\`;
+ }
+
+ if (config.locale && config.locale !== 'en') {
+ imports += \`// Set locale\\nfaker.setLocale('\${config.locale}');\\n\\n\`;
+ }
+ }
+
+ return imports;
+}`;
+
+//--------------------------------------------------------------------//
+
+export default function CorePluginFunction() {
+ //hooks
+ const { _ } = useLanguage();
+
+ return (
+ <>
+ {/* Implementation Section Content */}
+
+
{_('4. Implementation')}
+
+
+ The implementation section covers the core plugin function
+ and supporting utilities that handle test data generation.
+ This includes the main plugin entry point, data generation
+ functions, and configuration validation.
+
+
+
+
{_('4.1. Core Plugin Function')}
+
+
+ The core plugin function serves as the main entry point for
+ test data generation. It orchestrates the entire process from
+ configuration validation to file output, handling different
+ formats and generation options.
+
+
+
+ {corePluginExample}
+
+
+
{_('4.2. Generation Functions')}
+
+
+ The generation functions provide the core logic for creating
+ different types of test data content. These utility functions
+ handle file headers, imports, data factories, and various data
+ generation patterns based on schema definitions.
+
+
+
+ {headerAndImportsExample}
+
+
+ >
+ );
+}
\ No newline at end of file
diff --git a/packages/www/plugins/docs/components/test-data-plugin/GenerationFunctions.tsx b/packages/www/plugins/docs/components/test-data-plugin/GenerationFunctions.tsx
new file mode 100644
index 0000000..0becec7
--- /dev/null
+++ b/packages/www/plugins/docs/components/test-data-plugin/GenerationFunctions.tsx
@@ -0,0 +1,520 @@
+//local
+import Code from '../../../docs/components/Code.js';
+
+//code examples
+//--------------------------------------------------------------------//
+
+const factoriesExample =
+ `function generateFactories(schema: any, config: TestDataConfig): string {
+ let content = '// Data Factories\\n';
+
+ // Generate enum factories
+ if (schema.enum) {
+ for (const [enumName, enumDef] of Object.entries(schema.enum)) {
+ content += generateEnumFactory(enumName, enumDef, config);
+ }
+ }
+
+ // Generate model factories
+ if (schema.model) {
+ for (const [modelName, model] of Object.entries(schema.model)) {
+ content += generateModelFactory(modelName, model, config);
+ }
+ }
+
+ return content + '\\n';
+}
+
+function generateEnumFactory(enumName: string, enumDef: any, config: TestDataConfig): string {
+ const values = Object.values(enumDef);
+ const valuesArray = values.map(v => \`"\${v}"\`).join(', ');
+
+ return \`export function generate\${enumName}(): string {
+ return faker.helpers.arrayElement([\${valuesArray}]);
+}
+
+\`;
+}
+
+function generateModelFactory(modelName: string, model: any, config: TestDataConfig): string {
+ let content = \`export function generate\${modelName}(overrides: Partial<\${modelName}> = {}): \${modelName} {
+ return {
+\`;
+
+ for (const column of model.columns || []) {
+ const generator = generateFieldGenerator(column, config);
+ content += \` \${column.name}: \${generator},\\n\`;
+ }
+
+ content += \` ...overrides,
+ };
+}
+
+export function generate\${modelName}Array(count: number = \${config.count || 10}): \${modelName}[] {
+ return Array.from({ length: count }, () => generate\${modelName}());
+}
+
+\`;
+
+ return content;
+}`;
+
+//--------------------------------------------------------------------//
+
+const fieldGeneratorExample =
+ `function generateFieldGenerator(column: any, config: TestDataConfig): string {
+ // Check for custom generators first
+ if (config.customGenerators && config.customGenerators[column.type]) {
+ return config.customGenerators[column.type];
+ }
+
+ // Handle arrays
+ if (column.multiple) {
+ const baseGenerator = getBaseGenerator(column, config);
+ const arraySize = column.attributes?.minLength || 1;
+ const maxSize = column.attributes?.maxLength || 5;
+ return \`faker.helpers.multiple(() => \${baseGenerator}, { count: { min: \${arraySize}, max: \${maxSize} } })\`;
+ }
+
+ return getBaseGenerator(column, config);
+}
+
+function getBaseGenerator(column: any, config: TestDataConfig): string {
+ const { type, attributes = {} } = column;
+
+ // Handle custom field types based on attributes
+ if (attributes.email) {
+ return 'faker.internet.email()';
+ }
+
+ if (attributes.url) {
+ return 'faker.internet.url()';
+ }
+
+ if (attributes.uuid) {
+ return 'faker.string.uuid()';
+ }
+
+ if (attributes.phone) {
+ return 'faker.phone.number()';
+ }
+
+ if (attributes.color) {
+ return 'faker.internet.color()';
+ }
+
+ // Handle based on field name patterns
+ const fieldName = column.name.toLowerCase();
+
+ if (fieldName.includes('email')) {
+ return 'faker.internet.email()';
+ }
+
+ if (fieldName.includes('name')) {
+ if (fieldName.includes('first')) return 'faker.person.firstName()';
+ if (fieldName.includes('last')) return 'faker.person.lastName()';
+ if (fieldName.includes('full')) return 'faker.person.fullName()';
+ return 'faker.person.fullName()';
+ }
+
+ if (fieldName.includes('address')) {
+ return 'faker.location.streetAddress()';
+ }
+
+ if (fieldName.includes('city')) {
+ return 'faker.location.city()';
+ }
+
+ if (fieldName.includes('country')) {
+ return 'faker.location.country()';
+ }
+
+ if (fieldName.includes('phone')) {
+ return 'faker.phone.number()';
+ }
+
+ if (fieldName.includes('company')) {
+ return 'faker.company.name()';
+ }
+
+ if (fieldName.includes('title')) {
+ return 'faker.lorem.sentence()';
+ }
+
+ if (fieldName.includes('description') || fieldName.includes('content')) {
+ return 'faker.lorem.paragraphs()';
+ }
+
+ if (fieldName.includes('image') || fieldName.includes('avatar')) {
+ return 'faker.image.url()';
+ }
+
+ if (fieldName.includes('price') || fieldName.includes('amount')) {
+ return 'faker.commerce.price()';
+ }
+
+ // Handle based on schema type
+ switch (type) {
+ case 'String':
+ if (attributes.min && attributes.max) {
+ return \`faker.lorem.words({ min: \${attributes.min}, max: \${attributes.max} })\`;
+ }
+ return 'faker.lorem.words()';
+
+ case 'Number':
+ case 'Integer':
+ const min = attributes.min || 1;
+ const max = attributes.max || 1000;
+ return \`faker.number.int({ min: \${min}, max: \${max} })\`;
+
+ case 'Boolean':
+ return 'faker.datatype.boolean()';
+
+ case 'Date':
+ if (fieldName.includes('birth')) {
+ return 'faker.date.birthdate()';
+ }
+ if (fieldName.includes('future')) {
+ return 'faker.date.future()';
+ }
+ if (fieldName.includes('past')) {
+ return 'faker.date.past()';
+ }
+ return 'faker.date.recent()';
+
+ case 'JSON':
+ return 'faker.datatype.json()';
+
+ case 'ID':
+ return 'faker.string.uuid()';
+
+ default:
+ // Check if it's an enum or custom type
+ if (type.endsWith('Role') || type.endsWith('Status') || type.endsWith('Type')) {
+ return \`generate\${type}()\`;
+ }
+ return 'faker.lorem.word()';
+ }
+}`;
+
+//--------------------------------------------------------------------//
+
+const mockDataExample =
+ `function generateMockData(models: Record, config: TestDataConfig): string {
+ if (config.format === 'json') {
+ return generateJSONMockData(models, config);
+ }
+
+ let content = '// Mock Data\\n';
+
+ for (const [modelName, model] of Object.entries(models)) {
+ content += \`export const mock\${modelName}Data = generate\${modelName}Array(\${config.count || 10});\\n\`;
+ }
+
+ return content + '\\n';
+}
+
+function generateJSONMockData(models: Record, config: TestDataConfig): string {
+ let content = '';
+ const mockData: Record = {};
+
+ for (const [modelName, model] of Object.entries(models)) {
+ const data = [];
+ for (let i = 0; i < (config.count || 10); i++) {
+ const item: Record = {};
+
+ for (const column of model.columns || []) {
+ item[column.name] = generateMockValue(column, config);
+ }
+
+ data.push(item);
+ }
+
+ mockData[modelName.toLowerCase()] = data;
+ }
+
+ return JSON.stringify(mockData, null, 2);
+}
+
+function generateMockValue(column: any, config: TestDataConfig): any {
+ const { type, attributes = {} } = column;
+
+ // Simple mock value generation for JSON format
+ switch (type) {
+ case 'String':
+ if (attributes.email) return 'user@example.com';
+ if (attributes.url) return 'https://example.com';
+ if (column.name.toLowerCase().includes('name')) return 'John Doe';
+ return 'Sample Text';
+
+ case 'Number':
+ case 'Integer':
+ return Math.floor(Math.random() * 1000) + 1;
+
+ case 'Boolean':
+ return Math.random() > 0.5;
+
+ case 'Date':
+ return new Date().toISOString();
+
+ case 'ID':
+ return \`id_\${Math.random().toString(36).substr(2, 9)}\`;
+
+ default:
+ return 'mock_value';
+ }
+}`;
+
+//--------------------------------------------------------------------//
+
+const fixturesExample =
+ `function generateFixtures(schema: any, config: TestDataConfig): string {
+ let content = '// Test Fixtures\\n';
+
+ if (schema.model) {
+ for (const [modelName, model] of Object.entries(schema.model)) {
+ content += generateModelFixtures(modelName, model, config);
+ }
+ }
+
+ return content;
+}
+
+function generateModelFixtures(modelName: string, model: any, config: TestDataConfig): string {
+ const lowerName = modelName.toLowerCase();
+
+ return \`export const \${lowerName}Fixtures = {
+ valid: generate\${modelName}({
+ // Override with specific test values
+ }),
+
+ minimal: generate\${modelName}({
+ // Minimal required fields only
+ \${generateMinimalFields(model)}
+ }),
+
+ invalid: {
+ // Invalid data for negative testing
+ \${generateInvalidFields(model)}
+ },
+
+ edge: generate\${modelName}({
+ // Edge case values
+ \${generateEdgeCaseFields(model)}
+ }),
+};
+
+\`;
+}`;
+
+//--------------------------------------------------------------------//
+
+const fixtureUtilsExample =
+ `function generateMinimalFields(model: any): string {
+ const requiredFields = model.columns?.filter((col: any) =>
+ col.required && !col.attributes?.id && !col.attributes?.default
+ ) || [];
+
+ return requiredFields.map((col: any) => {
+ const value = getMinimalValue(col);
+ return \`\${col.name}: \${value}\`;
+ }).join(',\\n ');
+}
+
+function generateInvalidFields(model: any): string {
+ const fields = model.columns?.slice(0, 3) || []; // First 3 fields for example
+
+ return fields.map((col: any) => {
+ const invalidValue = getInvalidValue(col);
+ return \`\${col.name}: \${invalidValue}\`;
+ }).join(',\\n ');
+}
+
+function generateEdgeCaseFields(model: any): string {
+ const fields = model.columns?.slice(0, 3) || []; // First 3 fields for example
+
+ return fields.map((col: any) => {
+ const edgeValue = getEdgeCaseValue(col);
+ return \`\${col.name}: \${edgeValue}\`;
+ }).join(',\\n ');
+}`;
+
+//--------------------------------------------------------------------//
+
+const valueGeneratorsExample =
+ `function getMinimalValue(column: any): string {
+ switch (column.type) {
+ case 'String':
+ return '"a"';
+ case 'Number':
+ case 'Integer':
+ return column.attributes?.min || '1';
+ case 'Boolean':
+ return 'true';
+ case 'Date':
+ return 'new Date()';
+ default:
+ return '""';
+ }
+}
+
+function getInvalidValue(column: any): string {
+ switch (column.type) {
+ case 'String':
+ if (column.attributes?.email) return '"invalid-email"';
+ if (column.attributes?.min) return '""'; // Too short
+ return 'null';
+ case 'Number':
+ case 'Integer':
+ return '"not-a-number"';
+ case 'Boolean':
+ return '"not-boolean"';
+ case 'Date':
+ return '"invalid-date"';
+ default:
+ return 'null';
+ }
+}
+
+function getEdgeCaseValue(column: any): string {
+ switch (column.type) {
+ case 'String':
+ if (column.attributes?.max) {
+ return \`"\${'a'.repeat(column.attributes.max)}"\`;
+ }
+ return '"very long string that might cause issues with processing or display"';
+ case 'Number':
+ case 'Integer':
+ return column.attributes?.max || '999999';
+ case 'Boolean':
+ return 'false';
+ case 'Date':
+ return 'new Date("1900-01-01")';
+ default:
+ return '""';
+ }
+}`;
+
+//--------------------------------------------------------------------//
+
+const mainExportExample =
+ `function generateMainExport(schema: any, config: TestDataConfig): string {
+ if (config.format === 'json') {
+ return ''; // JSON format doesn't need exports
+ }
+
+ let content = '// Main Export\\nexport const testData = {\\n';
+
+ // Export factories
+ if (config.generateFactories && schema.model) {
+ content += ' factories: {\\n';
+ for (const modelName of Object.keys(schema.model)) {
+ content += \` \${modelName}: generate\${modelName},\\n\`;
+ content += \` \${modelName}Array: generate\${modelName}Array,\\n\`;
+ }
+ content += ' },\\n';
+ }
+
+ // Export mock data
+ if (schema.model) {
+ content += ' mockData: {\\n';
+ for (const modelName of Object.keys(schema.model)) {
+ content += \` \${modelName.toLowerCase()}: mock\${modelName}Data,\\n\`;
+ }
+ content += ' },\\n';
+ }
+
+ // Export fixtures
+ if (config.generateFixtures && schema.model) {
+ content += ' fixtures: {\\n';
+ for (const modelName of Object.keys(schema.model)) {
+ content += \` \${modelName.toLowerCase()}: \${modelName.toLowerCase()}Fixtures,\\n\`;
+ }
+ content += ' },\\n';
+ }
+
+ content += '};\\n\\nexport default testData;\\n';
+
+ return content;
+}
+
+function validateConfig(config: any): asserts config is TestDataConfig {
+ if (!config.output || typeof config.output !== 'string') {
+ throw new Error('Test Data plugin requires "output" configuration as string');
+ }
+
+ if (!config.format || !['json', 'typescript', 'javascript'].includes(config.format)) {
+ throw new Error('format must be one of: json, typescript, javascript');
+ }
+
+ if (config.count && (typeof config.count !== 'number' || config.count < 1)) {
+ throw new Error('count must be a positive number');
+ }
+}`;
+
+//--------------------------------------------------------------------//
+
+export default function GenerationFunctions() {
+ return (
+ <>
+ {/* Generation Functions Section Content */}
+
+
+ {factoriesExample}
+
+
+
+ {fieldGeneratorExample}
+
+
+
+ {mockDataExample}
+
+
+
+ {fixturesExample}
+
+
+
+ {fixtureUtilsExample}
+
+
+
+ {valueGeneratorsExample}
+
+
+
+ {mainExportExample}
+
+
+ >
+ );
+}
\ No newline at end of file
diff --git a/packages/www/plugins/docs/components/test-data-plugin/Overview.tsx b/packages/www/plugins/docs/components/test-data-plugin/Overview.tsx
new file mode 100644
index 0000000..c8a84ac
--- /dev/null
+++ b/packages/www/plugins/docs/components/test-data-plugin/Overview.tsx
@@ -0,0 +1,65 @@
+//modules
+import { useLanguage, Translate } from 'r22n';
+//local
+import { H1, P, SS } from '../../../docs/components/index.js';
+
+export default function Overview() {
+ //hooks
+ const { _ } = useLanguage();
+
+ return (
+ <>
+ {/* Creating a Test Data Generator Plugin */}
+
+
{_('Test Data Generator Plugin Tutorial')}
+
+
+ This tutorial demonstrates how to create a plugin that
+ generates mock data and test fixtures from .idea schema
+ files. The plugin will transform your schema models into
+ realistic test data for development, testing, and prototyping.
+
+
+
+
+ {/* Overview Section Content */}
+
+
{_('1. Overview')}
+
+
+ Test data generation is crucial for development and testing
+ workflows. This plugin generates realistic mock data from your
+ .idea schema, including:
+
+
+
+
+ Mock Data:
+ Realistic test data based on schema types
+
+
+
+ Fixtures:
+ Predefined test datasets for consistent testing
+
+
+
+ Factories:
+ Data generation functions for dynamic testing
+
+
+
+ Relationships:
+ Proper handling of model relationships
+
+
+
+ Customization:
+ Custom data generators and constraints
+
+
+
+ The schema configuration section demonstrates how to
+ integrate the test data plugin into your .idea schema
+ files. This includes plugin declaration syntax, configuration
+ options, and examples of how to customize the plugin
+ behavior for different use cases.
+
+
+
+
+ Add the Test Data plugin to your .idea schema file:
+
+
+
+ {schemaConfigExample}
+
+
+
{_('5.1. Configuration Options')}
+
+
+ The following options will be processed by the test data
+ plugin in this tutorial.
+
+
+
+
+
+ Option
+ Type
+ Default
+ Description
+
+
+ output
+ string
+ Required
+
+
+ Output file path for test data
+
+
+
+
+ format
+ 'json'|'typescript'|'javascript'
+ Required
+
+
+ Output format
+
+
+
+
+ count
+ number
+ 10
+
+
+ Number of records to generate per model
+
+
+
+
+ seed
+ number
+ undefined
+
+
+ Seed for reproducible data generation
+
+
+
+
+ locale
+ string
+ 'en'
+
+
+ Locale for faker.js data generation
+
+
+
+
+ generateFactories
+ boolean
+ true
+
+
+ Generate data factory functions
+
+
+
+
+ generateFixtures
+ boolean
+ true
+
+
+ Generate test fixtures
+
+
+
+
+ customGenerators
+ object
+ {`{}`}
+
+
+ Custom data generators for specific types
+
+
+
+
+ relationships
+ boolean
+ false
+
+
+ Handle model relationships
+
+
+
+
+
+ Advanced ts-morph features enable sophisticated code
+ generation scenarios including decorators, complex type
+ systems, module declarations, and code manipulation.
+ These features are essential for building production-ready
+ plugins that handle enterprise-level requirements.
+
+
+
+
{_('6.1. Working with Decorators')}
+
+
+ Decorators are essential for modern TypeScript applications,
+ especially when working with frameworks like Angular, NestJS,
+ or TypeORM. ts-morph provides comprehensive support for
+ generating classes and methods with decorators.
+
+
+
+ {examples[0]}
+
+
+
{_('6.2. Generating Complex Types')}
+
+
+ Complex type generation includes mapped types, conditional
+ types, and template literal types that leverage TypeScript's
+ advanced type system. These features enable the creation
+ of sophisticated type-safe APIs and utility types.
+
+
+
+ {examples[1]}
+
+
+
{_('6.3. Working with Modules')}
+
+
+ Module declarations and ambient modules are crucial for
+ creating type definitions and extending existing libraries.
+ This section covers both namespace-style modules and modern
+ ES module patterns.
+
+
+
+ {examples[2]}
+
+
+
{_('6.4. Manipulating Existing Code')}
+
+
+ Code manipulation capabilities allow plugins to modify
+ existing TypeScript files, add new functionality, and
+ refactor code structures. This is particularly useful
+ for migration tools and code modernization plugins.
+
+
+
+ Following best practices ensures your plugins are maintainable,
+ performant, and reliable in production environments. These
+ guidelines cover type safety, error handling, performance
+ optimization, and code organization strategies.
+
+
+
+
{_('8.1. Type Safety')}
+
+
+ Type safety is fundamental to building reliable plugins
+ that catch errors at compile time rather than runtime.
+ Always use TypeScript interfaces and proper type validation
+ throughout your plugin implementation.
+
+
+
+
+ Always use TypeScript interfaces for your plugin
+ configuration and data structures:
+
+
+
+ {examples[0]}
+
+
+
{_('8.2. Error Handling')}
+
+
+ Comprehensive error handling provides clear feedback to
+ users and helps with debugging when things go wrong.
+ Implement custom error types and meaningful error
+ messages to improve the developer experience.
+
+
+
+
+ Implement comprehensive error handling:
+
+
+
+ {examples[1]}
+
+
+
{_('8.3. Performance Optimization')}
+
+
+ Performance optimization becomes crucial when dealing
+ with large schemas or generating substantial amounts of
+ code. Implement caching strategies and batch processing
+ to maintain reasonable execution times.
+
+
+
+
+ For large schemas, optimize performance:
+
+
+
+ {examples[2]}
+
+
+
{_('8.4. Code Organization')}
+
+
+ Proper code organization makes your plugin easier to
+ maintain, test, and extend. Separate concerns into focused
+ classes and modules that each handle specific aspects of
+ the generation process.
+
+
+
+
+ Structure your plugin code for maintainability:
+
+
+
+ {examples[3]}
+
+
+
{_('8.5. Documentation Generation')}
+
+
+ Documentation generation ensures your generated code is
+ self-documenting and provides valuable context for developers.
+ Implement comprehensive JSDoc comment generation with examples
+ and type information.
+
+
+
+ Creating your first plugin with ts-morph involves
+ understanding the complete workflow from schema processing
+ to code generation. This comprehensive example demonstrates
+ building a TypeScript interface generator that transforms
+ JSON schemas into properly typed interfaces with full feature
+ support.
+
+
+
+
+ Let's create a plugin that generates TypeScript interfaces
+ from JSON schema definitions. This will demonstrate the core
+ concepts of using ts-morph for code generation.
+
+
+
+
{_('5.1. Define the Plugin Interface')}
+
+
+ Defining clear interfaces for your plugin ensures type safety
+ and provides a solid foundation for implementation. This
+ section establishes the data structures and configuration
+ options that will guide the entire plugin development process.
+
+
+
+
+ First, let's define the types for our plugin:
+
+
+
+ {examples[0]}
+
+
+
{_('5.2. Core Plugin Implementation')}
+
+
+ The core plugin implementation orchestrates the entire code
+ generation process, from loading input schemas to generating and
+ saving TypeScript files. This comprehensive class demonstrates
+ best practices for plugin architecture and error handling.
+
+
+
+ {examples[1]}
+
+
+
{_('5.3. Plugin Entry Point')}
+
+
+ The plugin entry point provides a clean API for consumers and
+ handles CLI integration. This section shows how to create both
+ programmatic and command-line interfaces for your plugin, making
+ it accessible in different usage scenarios.
+
+
+
+ {examples[2]}
+
+
+
{_('5.4. Example Usage')}
+
+
+ Example usage demonstrates the plugin in action with
+ realistic data structures. This comprehensive example
+ shows how the plugin processes complex schemas with
+ various property types, relationships, and validation
+ rules.
+
+
+
+ Before starting with ts-morph plugin development,
+ ensure you have the necessary tools and knowledge. This
+ section outlines the essential requirements for successful
+ plugin creation and provides installation guidance.
+
+
+
+
+
+ Before starting, ensure you have:
+
+
+
+
+
+ {_('Node.js 16+')}
+
+ and npm/yarn installed
+
+
+
+ {_('TypeScript 4.0+')}
+
+ knowledge
+
+
+
+
+ Basic understanding of Abstract Syntax Trees (AST)
+
+
+
+
+ Familiarity with TypeScript interfaces, classes, and
+ modules
+
+
+
+
+
+
+ Installing ts-morph is straightforward and can be
+ done using your preferred package manager. The library is
+ available through npm, yarn, and even Deno for different
+ development environments.
+
+
{_('Creating Plugins with ts-morph: A Comprehensive Guide')}
+
+
+ This guide demonstrates how to create powerful code
+ generation plugins using ts-morph, a TypeScript library
+ that provides an easier way to programmatically navigate
+ and manipulate TypeScript and JavaScript code. We'll walk
+ through creating a complete plugin that generates TypeScript
+ interfaces from schema definitions.
+
+
+
+
{_('1. Introduction')}
+
+
+ ts-morph is a powerful TypeScript library that
+ wraps the TypeScript Compiler API, making it much easier
+ to work with TypeScript Abstract Syntax Trees (AST). This
+ introduction covers the fundamental concepts and advantages
+ of using ts-morph for plugin development.
+
+
+
+ Understanding the advantages of ts-morph over
+ traditional code generation approaches helps you make
+ informed decisions about plugin architecture. This
+ comparison highlights the key benefits that make ts-
+ morph an excellent choice for TypeScript code
+ generation.
+
+
+
+
+ Traditional code generation often involves:
+
+
+
+ This section provides comprehensive resources for continued
+ learning and development with ts-morph. These references
+ include official documentation, community resources, and
+ related tools that enhance the plugin development experience.
+
+
+
+
+ {/* Official Documentation */}
+
+
{_('10.1. Official Documentation')}
+
+
+ Official documentation provides authoritative information
+ about ts-morph APIs, TypeScript compiler internals, and AST
+ manipulation techniques.
+
+
+
+ Additional resources provide practical examples, community
+ insights, and tools that complement the official documentation
+ for comprehensive plugin development.
+
+
+
+ This comprehensive guide provides everything you need
+ to create powerful code generation plugins using ts-morph.
+ The library's type-safe approach to code manipulation
+ makes it an excellent choice for building robust, maintainable
+ code generators that produce high-quality TypeScript output.
+
+
+
+ Setting up a proper project structure is crucial for
+ maintainable plugin development. This section guides you
+ through creating a well-organized TypeScript project with
+ all necessary configurations and dependencies
+
+
+
+
+ Let's create a new TypeScript project for our plugin:
+
+
+
+ Comprehensive testing ensures your plugin works correctly
+ across different scenarios and maintains reliability as
+ it evolves. This section covers unit testing, integration
+ testing, and validation strategies for ts-morph plugins.
+
+
+
+
+
+ Create comprehensive tests for your plugin:
+
+
+
+ Troubleshooting guides help developers quickly identify
+ and resolve common issues encountered during plugin
+ development. This section covers validation, debugging
+ techniques, and solutions for typical problems.
+
+
+
+
+ {/* Common Issues Section Content */}
+
+
{_('9.1. Common Issues')}
+
+
+ Common issues in ts-morph plugin development typically
+ involve syntax validation, circular references, and
+ memory management. Understanding these patterns helps
+ prevent and resolve problems efficiently.
+
+
+
+
{_('9.1.1. Invalid TypeScript Syntax')}
+
+
+ Invalid TypeScript syntax can break the compilation
+ process and prevent your plugin from generating usable
+ code. Implement validation checks to catch syntax errors
+ early in the generation process.
+
+
+
+ {examples[0]}
+
+
+
{_('9.1.2. Circular Type References')}
+
+
+ Circular type references can cause infinite loops and
+ compilation errors. Detecting and handling these scenarios
+ is crucial for plugins that work with complex, interconnected
+ data structures.
+
+
+
+ {examples[1]}
+
+
+
{_('9.1.3. Memory Issues with Large Schemas')}
+
+
+ Memory management becomes important when processing large
+ schemas or generating substantial amounts of code. Implement
+ streaming and batching strategies to handle large-scale
+ generation efficiently.
+
+
+
+ Effective debugging techniques help identify issues
+ quickly and understand the plugin's behavior during
+ development. These tools and strategies provide visibility
+ into the generation process.
+
+
+
+
{_('9.2.1. Enable Verbose Logging')}
+
+
+ Verbose logging provides detailed information about the
+ plugin's execution flow, helping identify where issues
+ occur and what data is being processed at each step.
+
+
+
+ {examples[3]}
+
+
+
{_('9.2.2. Save Intermediate Results')}
+
+
+ Saving intermediate results allows you to inspect the
+ code generation process at different stages, making it
+ easier to identify where problems occur and verify that
+ each step produces the expected output.
+
+
+
+ {examples[4]}
+
+
+
{_('9.2.3. Validate Each Step')}
+
+
+ Step-by-step validation ensures that each phase of the
+ generation process produces valid TypeScript code, helping
+ catch issues early before they compound into larger problems.
+
+
+
+ Understanding the fundamental concepts of ts-morph is
+ essential for effective plugin development. This section covers
+ the core APIs, project management, source file manipulation,
+ and code generation patterns that form the foundation of all
+ ts-morph operations.
+
+
+
+ The Project class is the entry point for all ts-morph
+ operations, providing methods to create, load, and manage
+ TypeScript source files. Understanding how to work with projects
+ and source files is fundamental to building effective code
+ generation plugins.
+
+
+
+ ts-morph provides comprehensive APIs for adding various
+ TypeScript constructs including imports, classes, functions,
+ types, and enums. This section demonstrates the most commonly
+ used patterns for generating different types of TypeScript code.
+
+
+
+ {examples[1]}
+
+
+
+ {/* Exporting a Class Section Content */}
+
+
{_('4.3. Exporting a Class')}
+
+
+ Creating and exporting classes is a common requirement in
+ TypeScript code generation. This example demonstrates the basic
+ pattern for generating classes with methods, including proper
+ export declarations and method implementations.
+
+
+
+
+ A simple example of how to create a new TypeScript file with a
+ class and a method using ts-morph looks like the
+ following:
+
+
+
+ {examples[2]}
+
+
+
+
+ This code will create a new TypeScript file newFile.ts
+ with the following content:
+
+
+
+ {examples[3]}
+
+
+
+ You can use isExported or isDefaultExport to
+ export or export default respectively. Also
+ statements can be a string or an array of strings
+ (string[]).
+
+
+
+
+ {/* Exporting a Function Section Content */}
+
+
{_('4.4. Exporting a Function')}
+
+
+ Function generation at the source file level provides flexibility
+ for creating utility functions, API endpoints, and standalone
+ operations. This section shows how to create functions with
+ various configurations including async operations, parameters,
+ and return types.
+
+
+
+
+ Similar to adding a method to a class, you can use
+ addFunction to add a function at the source file level.
+ An example of how to use addFunction to add a function
+ with arguments and a body looks like the following:
+
+
+
+ {examples[4]}
+
+
+
+ In the above example, myFunction takes two parameters,
+ param1 of type string and param2 of type number.
+ The function body contains two console.log statements.
+
+
+
+
+ After running the above code, the content of newFile.ts
+ would look like the following:
+
+
+
+ Constant declarations are essential for defining configuration
+ values, default settings, and immutable data structures. The
+ addVariableStatement method provides flexible options for
+ creating various types of variable declarations with proper export
+ handling.
+
+
+
+
+ To export a constant in ts-morph, you can utilize the
+ addVariableStatement method on a SourceFile object.
+ This method allows you to add a variable declaration to the file,
+ including the capability to export the declaration.
+
+
+
+ {examples[6]}
+
+
+
+ The provided ts-morph script will generate the following
+ code in the source file.
+
+
+
+ Export declarations provide a clean way to re-export multiple
+ entities from other modules or to export collections of related
+ functionality. This pattern is commonly used in index files and
+ module aggregation scenarios.
+
+
+
+
+ To generate an export statement that directly exports multiple
+ imported entities in a single line using ts-morph, you
+ don't need to declare them as variables first. Instead, you can
+ use the addExportDeclaration method directly after your
+ imports. This approach is more straightforward and aligns with
+ typical TypeScript import-export patterns.
+
+
+
+ Type exports are crucial for creating reusable type definitions
+ that can be consumed by other modules. ts-morph provides
+ dedicated methods for creating both type aliases and interfaces
+ with proper export configurations.
+
+
+
+
+ To export a single type, you can use the addTypeAlias or
+ addInterface method (depending on whether you are defining
+ an alias or an interface), and set the isExported property
+ to true. An example of exporting a type alias looks like the
+ following:
+
+
+
+ {examples[9]}
+
+
+
+ This will generate a file with the following content:
+
+
+
+ {examples[10]}
+
+
+
+ To export multiple types at the same time, you can add multiple
+ type declarations (either type aliases or interfaces) with the
+ isExported property set to true for each. Alternatively,
+ you can use the addExportDeclaration method to export
+ previously declared types. An example of declaring and exporting
+ multiple types looks like the following:
+
+
+
+ {examples[11]}
+
+
+
+ This will generate a file with the following content:
+
+
+
+ Import declarations are essential for bringing external
+ dependencies and modules into your generated code. The
+ addImportDeclaration method provides comprehensive options
+ for creating various types of import statements including named
+ imports, default imports, and type imports.
+
+
+
+
+ To import a set of values from a module in ts-morph, you
+ can use the addImportDeclaration method on a
+ SourceFile object. This method allows you to add an import
+ declaration to the code file you are working with. Here's how to
+ use this method to import specific values from the react
+ module:
+
+
+
+ {examples[13]}
+
+
+
+ The provided ts-morph script will generate the following
+ code in the source file:
+
+
+
+ {examples[14]}
+
+
+
+ You can also import types like the following:
+
+
+
+ Default imports are commonly used for importing the main export
+ from a module, such as React components or utility libraries. The
+ same addImportDeclaration method handles default imports
+ with a slightly different configuration.
+
+
+
+
+ To import a default from a module in ts-morph, you can
+ also use the addImportDeclaration method:
+
+
+
+ {examples[17]}
+
+
+
+ This would create the following code:
+
+
+
+ {examples[18]}
+
+
+
+ {/* Working with Existing Code Section Content */}
+
+
{_('4.10. Working with Existing Code')}
+
+
+ Working with existing code is a powerful feature of
+ ts-morph that allows you to modify, extend, and refactor
+ existing TypeScript files. This capability is essential for
+ plugins that need to augment or update existing codebases rather
+ than generating new files from scratch.
+
+
+
+ {examples[19]}
+
+
+ >
+ )
+}
diff --git a/packages/www/plugins/docs/components/ts-morph-plugin-guide/index.tsx b/packages/www/plugins/docs/components/ts-morph-plugin-guide/index.tsx
new file mode 100644
index 0000000..60dd4e3
--- /dev/null
+++ b/packages/www/plugins/docs/components/ts-morph-plugin-guide/index.tsx
@@ -0,0 +1,11 @@
+//exporting all components to have multiple imports from a single file
+export { default as AdvanceTsMorphPlugin } from './AdvanceTsMorphPlugin.js';
+export { default as BestPractices } from './BestPractices.js';
+export { default as CreateFirstPlugin } from './CreateFirstPlugin.js';
+export { default as Installation } from './Installation.js';
+export { default as Introduction } from './Introduction.js';
+export { default as References } from './References.js';
+export { default as SettingUpProject } from './SettingUpProject.js';
+export { default as TestingYourPlugin } from './TestingYourPlugin.js';
+export { default as Troubleshooting } from './Troubleshooting.js';
+export { default as UnderstandingTsMorphBasics } from './UnderstandingTsMorphBasics.js';
\ No newline at end of file
diff --git a/packages/www/plugins/docs/components/typescript-interface-plugin/AdvancedFeatures.tsx b/packages/www/plugins/docs/components/typescript-interface-plugin/AdvancedFeatures.tsx
new file mode 100644
index 0000000..ed6a252
--- /dev/null
+++ b/packages/www/plugins/docs/components/typescript-interface-plugin/AdvancedFeatures.tsx
@@ -0,0 +1,207 @@
+//modules
+import { useLanguage, Translate } from 'r22n';
+//local
+import { H1, H2, P, Code } from '../../../docs/components/index.js';
+
+//code examples
+//--------------------------------------------------------------------//
+
+const namespaceConfigurationExample =
+ `// With namespace configuration
+namespace: "MyApp"
+exportType: "namespace"`;
+
+const namespaceOutputExample =
+ `// Generated output:
+export namespace MyApp {
+ export enum UserRole {
+ ADMIN = "admin",
+ USER = "user",
+ }
+
+ export interface User {
+ id: string;
+ name: string;
+ role: UserRole;
+ }
+}`;
+
+//--------------------------------------------------------------------//
+
+const standardEnumExample =
+ `// Standard enum (default)
+enumType: "enum"
+export enum UserRole {
+ ADMIN = "admin",
+ USER = "user",
+}`;
+
+//--------------------------------------------------------------------//
+
+const unionTypeExample =
+ `// Union type
+enumType: "union"
+export type UserRole = "admin" | "user";`;
+
+//--------------------------------------------------------------------//
+
+const constAssertionExample =
+ `// Const assertion
+enumType: "const"
+export const UserRole = {
+ ADMIN: "admin",
+ USER: "user",
+} as const;
+export type UserRole = typeof UserRole[keyof typeof UserRole];`;
+
+//--------------------------------------------------------------------//
+
+const relationshipHandlingExample =
+ `function handleRelationships(
+ column: any,
+ config: TypeScriptConfig,
+ availableTypes: Set
+): string {
+ // Check if the column type is another model/type
+ if (availableTypes.has(column.type)) {
+ let type = column.type;
+
+ if (column.multiple) {
+ type = \`\${type}[]\`;
+ }
+
+ if (!column.required && config.strictNullChecks) {
+ type = \`\${type} | null\`;
+ }
+
+ return type;
+ }
+
+ return formatPropertyType(column, config, availableTypes);
+}`;
+
+//--------------------------------------------------------------------//
+
+const genericTypeSupportExample =
+ `function generateGenericTypes(
+ models: Record,
+ config: TypeScriptConfig
+): string {
+ let content = '// Generic Types\\n';
+
+ // Generate paginated response type
+ content += \`export interface PaginatedResponse {
+ data: T[];
+ total: number;
+ page: number;
+ limit: number;
+}\\n\\n\`;
+
+ // Generate API response type
+ content += \`export interface ApiResponse {
+ success: boolean;
+ data?: T;
+ error?: string;
+ errors?: Record;
+}\\n\\n\`;
+
+ return content;
+}`;
+
+//--------------------------------------------------------------------//
+
+export default function AdvancedFeatures() {
+ //hooks
+ const { _ } = useLanguage();
+
+ return (
+ <>
+ {/* Advanced Features Section Content */}
+
+
{_('7. Advanced Features')}
+
+
+ Advanced features extend the basic TypeScript interface
+ generation with sophisticated organization, multiple enum
+ types, relationship handling, and generic type support.
+ These features enable production-ready TypeScript definitions
+ that handle complex scenarios.
+
+
+
+ Namespace support allows you to organize generated types within
+ TypeScript namespaces, preventing naming conflicts and providing
+ better code organization. This feature is particularly useful
+ for large projects with multiple schema files.
+
+
+
+ Different enum types provide flexibility in how enumerations
+ are represented in TypeScript. The plugin supports standard
+ enums, union types, and const assertions, each with different
+ runtime characteristics and use cases.
+
+
+
+ Relationship handling manages references between different types
+ and models in your schema. This ensures that type relationships
+ are properly represented in the generated TypeScript code with
+ correct type references and nullability handling.
+
+
+
+ {relationshipHandlingExample}
+
+
+
+ {/* Generic Type Support Section Content */}
+
+
{_('Generic Type Support')}
+
+
+ Generic type support enables the generation of reusable type
+ definitions that work with multiple data types. This includes
+ common patterns like paginated responses and API response
+ wrappers that enhance type safety across your application.
+
+
+
+ Best practices ensure your generated TypeScript interfaces
+ are maintainable, reliable, and follow industry standards.
+ These guidelines cover type safety, naming conventions,
+ documentation generation, and performance optimization.
+
+
+
+
+ {/* Type Safety Section Content */}
+
+
{_('Type Safety')}
+
+
+ Type safety is crucial for preventing runtime errors and
+ improving developer experience. Always validate input data
+ and use proper TypeScript types throughout the plugin
+ implementation to ensure reliable code generation.
+
+
+
+ Naming conventions ensure that generated TypeScript identifiers
+ are valid and follow established patterns. Proper naming improves
+ code readability and prevents conflicts with reserved keywords
+ or invalid characters.
+
+
+
+ Documentation generation creates comprehensive JSDoc
+ comments that provide context and examples for the generated
+ types. This improves the developer experience by providing
+ inline documentation in IDEs and code editors.
+
+
+
+ {jsDocGeneration}
+
+
+
+
+
{_('Performance Optimization')}
+
+
+ Performance optimization techniques help maintain reasonable
+ generation times when working with large schemas. Caching
+ strategies and efficient algorithms ensure the plugin scales
+ well with complex type hierarchies.
+
+
+
+ The implementation section covers the core plugin function and
+ supporting utilities that handle TypeScript interface generation.
+ This includes configuration validation, content generation, file
+ writing, and error handling throughout the generation process.
+
+
+
+
{_('Core Plugin Function')}
+
+
+ The core plugin function serves as the main entry point for
+ TypeScript interface generation. It orchestrates the entire
+ process from configuration validation through content generation
+ to file output, ensuring proper error handling and logging
+ throughout.
+
+
+
+ {corePluginFunctionExample}
+
+
+
{_('Type Mapping Functions')}
+
+
+ Type mapping functions handle the conversion of .idea
+ schema types to their TypeScript equivalents. These functions
+ ensure proper type safety and handle complex scenarios like
+ nullable types, arrays, and custom type references.
+
+
+
+ {typeMappingFunctionsExample}
+
+
+
{_('Generation Functions')}
+
+
+ Generation functions create specific parts of the TypeScript output
+ including enums, interfaces, and utility types. These functions
+ handle formatting, documentation generation, and proper TypeScript
+ syntax construction.
+
+
+
+ {generationFunctionsExample}
+
+
+
{_('Validation Functions')}
+
+
+ Validation functions ensure that the plugin configuration is correct
+ and that the generated TypeScript code meets quality standards.
+ These functions catch configuration errors early and prevent invalid
+ output generation.
+
+
+
+ {validationFunctionsExample}
+
+
+ >
+ );
+}
\ No newline at end of file
diff --git a/packages/www/plugins/docs/components/typescript-interface-plugin/Introduction.tsx b/packages/www/plugins/docs/components/typescript-interface-plugin/Introduction.tsx
new file mode 100644
index 0000000..35d0bf1
--- /dev/null
+++ b/packages/www/plugins/docs/components/typescript-interface-plugin/Introduction.tsx
@@ -0,0 +1,25 @@
+//modules
+import { useLanguage, Translate } from 'r22n';
+//local
+import { H1, P, C } from '../../../docs/components/index.js';
+
+export default function Introduction() {
+ //hooks
+ const { _ } = useLanguage();
+
+ return (
+ <>
+ {/* TypeScript Interface Generator Plugin Tutorial */}
+
+
+ This tutorial demonstrates how to create a plugin that
+ generates TypeScript interfaces and types from .idea
+ schema files. The plugin will transform your schema models,
+ types, and enums into proper TypeScript definitions with
+ full type safety.
+
+
+ >
+ );
+}
\ No newline at end of file
diff --git a/packages/www/plugins/docs/components/typescript-interface-plugin/Overview.tsx b/packages/www/plugins/docs/components/typescript-interface-plugin/Overview.tsx
new file mode 100644
index 0000000..9fbbbe0
--- /dev/null
+++ b/packages/www/plugins/docs/components/typescript-interface-plugin/Overview.tsx
@@ -0,0 +1,65 @@
+//modules
+import { useLanguage, Translate } from 'r22n';
+//local
+import { H1, P, C, SS } from '../../../docs/components/index.js';
+
+export default function Overview() {
+ //hooks
+ const { _ } = useLanguage();
+
+ return (
+ <>
+ {/* Overview Section Content */}
+
+
{_('1. Overview')}
+
+
+ TypeScript interfaces provide compile-time type checking
+ and excellent IDE support. This plugin transforms your
+ .idea schema definitions into comprehensive Type
+ Script type definitions that integrate seamlessly with
+ your development workflow and provide robust type safety
+ throughout your application.
+
+
+
+
+ This plugin generates TypeScript definitions from your
+ .idea schema, including:
+
+
+
+ The plugin structure defines the core architecture and
+ configuration interface for the TypeScript interface generator.
+ This includes the main plugin function, configuration types,
+ and the overall organization of the generated TypeScript code.
+
+
+
+ {pluginStructureExample}
+
+
+ >
+ );
+}
\ No newline at end of file
diff --git a/packages/www/plugins/docs/components/typescript-interface-plugin/Prerequisites.tsx b/packages/www/plugins/docs/components/typescript-interface-plugin/Prerequisites.tsx
new file mode 100644
index 0000000..01cff4f
--- /dev/null
+++ b/packages/www/plugins/docs/components/typescript-interface-plugin/Prerequisites.tsx
@@ -0,0 +1,49 @@
+//modules
+import { useLanguage, Translate } from 'r22n';
+//local
+import { H1, P, C } from '../../../docs/components/index.js';
+
+export default function Prerequisites() {
+ //hooks
+ const { _ } = useLanguage();
+
+ return (
+ <>
+ {/* Prerequisites Section Content */}
+
+
{_('2. Prerequisites')}
+
+
+ Before implementing the TypeScript interface generator plugin,
+ ensure you have the necessary development environment and
+ knowledge. This section covers the essential requirements for
+ successful plugin creation and TypeScript integration.
+
+
+
+
+
+ Node.js 16+ and npm/yarn
+
+
+
+
+ TypeScript 4.0+ development experience
+
+
+
+
+ Familiarity with the @stackpress/idea-transformer
+ library
+
+
+
+ Schema configuration demonstrates how to integrate the
+ TypeScript interface generator into your .idea
+ schema files. This section covers plugin configuration
+ options and their effects on the generated TypeScript output.
+
+
+
+
+ Add the TypeScript plugin to your .idea schema file:
+
+
+
+ {basicConfigurationExample}
+
+
+
{_('Configuration Options')}
+
+
+ Configuration options control how TypeScript interfaces are
+ generated, including output formatting, type handling, and
+ feature enablement. Understanding these options helps you
+ customize the plugin to meet your specific project requirements.
+
+
+
+ This section addresses common issues encountered when
+ generating TypeScript interfaces from .idea files
+ and provides solutions for debugging and resolving problems.
+ Understanding these troubleshooting techniques helps ensure
+ reliable TypeScript interface generation.
+
+
+
+
+ {/* Common Issues Section Content */}
+
+
{_('Common Issues')}
+
+
+ Common issues include invalid TypeScript identifiers, circular
+ type references, and missing dependencies. These problems
+ typically arise from schema complexity or configuration
+ mismatches that can be resolved with proper validation and
+ error handling.
+
+
+
+
+
{_('Invalid TypeScript Names')}
+
+
+ Invalid TypeScript names occur when schema identifiers
+ contain characters that are not valid in TypeScript. The
+ plugin should validate and sanitize names to ensure they
+ conform to TypeScript identifier rules.
+
+
+
+ Circular type references can cause infinite loops during
+ generation or compilation errors in the generated TypeScript
+ code. Detecting and handling these scenarios is essential for
+ robust type generation.
+
+
+
+ Missing type dependencies occur when a type references
+ another type that doesn't exist in the schema. Validating
+ type dependencies ensures all references are resolvable
+ and prevents compilation errors.
+
+
+
+ Debugging tips help identify and resolve issues during TypeScript
+ interface generation. These techniques provide visibility into
+ the generation process and help diagnose problems with schema
+ processing or output generation.
+
+
+
+ Verbose output provides detailed logging during the generation
+ process, helping identify where issues occur and what data is
+ being processed at each step.
+
+
+
+ Validating generated TypeScript ensures that the output is
+ syntactically correct and will compile successfully. This
+ validation step catches generation errors before the code is
+ used in development.
+
+
+
+ This tutorial provides a comprehensive foundation for creating
+ TypeScript interface generators from .idea files. The
+ generated types can be used throughout your TypeScript projects
+ for compile-time type checking and enhanced IDE support.
+
+
+
+ >
+ );
+}
\ No newline at end of file
diff --git a/packages/www/plugins/docs/components/typescript-interface-plugin/UsageExamples.tsx b/packages/www/plugins/docs/components/typescript-interface-plugin/UsageExamples.tsx
new file mode 100644
index 0000000..c9925e7
--- /dev/null
+++ b/packages/www/plugins/docs/components/typescript-interface-plugin/UsageExamples.tsx
@@ -0,0 +1,155 @@
+//modules
+import { useLanguage, Translate } from 'r22n';
+//local
+import { H1, H2, P } from '../../../docs/components/index.js';
+import Code from '../../../docs/components/Code.js';
+
+//code examples
+//--------------------------------------------------------------------//
+
+const basicSchemaExample =
+ `enum UserRole {
+ ADMIN "admin"
+ USER "user"
+ GUEST "guest"
+}
+
+type Address {
+ street String @required
+ city String @required
+ country String @required
+ postal String
+}
+
+model User {
+ id String @id @default("nanoid()")
+ email String @unique @required
+ name String @required
+ role UserRole @default("USER")
+ address Address?
+ active Boolean @default(true)
+ createdAt Date @default("now()")
+}
+
+plugin "./plugins/typescript-interfaces.js" {
+ output "./types.ts"
+ generateUtilityTypes true
+ includeComments true
+}`;
+
+//--------------------------------------------------------------------//
+
+const generatedOutputExample =
+ `/**
+ * Generated TypeScript interfaces
+ * Generated at: 2024-01-15T10:30:00.000Z
+ *
+ * This file is auto-generated. Do not edit manually.
+ */
+
+// Enums
+/**
+ * UserRole enumeration
+ */
+export enum UserRole {
+ ADMIN = "admin",
+ USER = "user",
+ GUEST = "guest",
+}
+
+// Custom Types
+/**
+ * Address type definition
+ */
+export interface Address {
+ street: string;
+ city: string;
+ country: string;
+ postal?: string | null;
+}
+
+// Model Interfaces
+/**
+ * User model interface
+ */
+export interface User {
+ /** Default: nanoid() */
+ id: string;
+ email: string;
+ name: string;
+ /** Default: USER */
+ role: UserRole;
+ address?: Address | null;
+ /** Default: true */
+ active: boolean;
+ /** Default: now() */
+ createdAt: Date;
+}
+
+// Utility Types
+export type CreateUserInput = Omit;
+
+export type UpdateUserInput = Partial;
+
+export type AnyModel = User;
+
+export type UserKeys = keyof User;`;
+
+//--------------------------------------------------------------------//
+
+export default function UsageExamples() {
+ //hooks
+ const { _ } = useLanguage();
+
+ return (
+ <>
+ {/* Usage Examples Section Content */}
+
+
{_('6. Usage Examples')}
+
+
+ Usage examples demonstrate practical applications of the
+ TypeScript interface generator with real-world scenarios.
+ These examples show how to configure the plugin for different
+ use cases and how the generated TypeScript code integrates
+ into development workflows.
+
+
+
+
{_('Basic Schema')}
+
+
+ A basic schema example shows the fundamental structure
+ needed to generate TypeScript interfaces. This includes
+ model definitions with proper attributes, enum declarations,
+ and plugin configuration that produces clean, type-safe
+ TypeScript code.
+
+
+
+ {basicSchemaExample}
+
+
+
{_('Generated Output')}
+
+
+ The generated output demonstrates the TypeScript code
+ produced by the plugin from the basic schema example.
+ This shows how schema definitions are transformed into
+ proper TypeScript interfaces with full type safety and
+ documentation.
+
+
+
+ {generatedOutputExample}
+
+
+ >
+ );
+}
\ No newline at end of file
diff --git a/packages/www/plugins/docs/components/typescript-interface-plugin/index.tsx b/packages/www/plugins/docs/components/typescript-interface-plugin/index.tsx
new file mode 100644
index 0000000..fa590ad
--- /dev/null
+++ b/packages/www/plugins/docs/components/typescript-interface-plugin/index.tsx
@@ -0,0 +1,11 @@
+//exporting all components to have multiple imports from a single file
+export { default as AdvancedFeatures } from './AdvancedFeatures.js';
+export { default as BestPractices } from './BestPractices.js';
+export { default as Implementation } from './Implementation.js';
+export { default as Introduction } from './Introduction.js';
+export { default as Overview } from './Overview.js';
+export { default as PluginStructure } from './PluginStructure.js';
+export { default as Prerequisites } from './Prerequisites.js';
+export { default as SchemaConfiguration } from './SchemaConfiguration.js';
+export { default as Troubleshooting } from './Troubleshooting.js';
+export { default as UsageExamples } from './UsageExamples.js';
\ No newline at end of file
diff --git a/packages/www/plugins/docs/components/validation-plugin/AdvancedFeatures.tsx b/packages/www/plugins/docs/components/validation-plugin/AdvancedFeatures.tsx
new file mode 100644
index 0000000..73bc4ff
--- /dev/null
+++ b/packages/www/plugins/docs/components/validation-plugin/AdvancedFeatures.tsx
@@ -0,0 +1,160 @@
+//modules
+import { useLanguage, Translate } from 'r22n';
+//local
+import { H1, H2, P } from '../../../docs/components/index.js';
+import Code from '../../../docs/components/Code.js';
+
+//code examples
+//--------------------------------------------------------------------//
+
+const customValidatorsExample =
+`// In plugin configuration
+customValidators: {
+ Email: "z.string().email().transform(val => val.toLowerCase())",
+ Password: "z.string().min(8).regex(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)/)",
+ Slug: "z.string().regex(/^[a-z0-9-]+$/)",
+ Color: "z.string().regex(/^#[0-9A-F]{6}$/i)",
+ JSON: "z.string().transform(val => JSON.parse(val))"
+}`
+
+//--------------------------------------------------------------------//
+
+const conditionalValidationExample =
+`// Generated schema with conditional validation
+export const UserSchema = z.object({
+ id: z.string(),
+ email: z.string().email(),
+ role: UserRoleSchema,
+ adminCode: z.string().optional(),
+}).refine((data) => {
+ // Admin users must have admin code
+ if (data.role === 'admin' && !data.adminCode) {
+ return false;
+ }
+ return true;
+}, {
+ message: "Admin users must provide an admin code",
+ path: ["adminCode"],
+});`
+
+//--------------------------------------------------------------------//
+
+const transformPreprocessExample =
+`// Add transforms to generated schemas
+function addTransforms(schema: string, column: any): string {
+ if (column.attributes?.transform) {
+ switch (column.attributes.transform) {
+ case 'lowercase':
+ return schema + '.transform(val => val.toLowerCase())';
+ case 'uppercase':
+ return schema + '.transform(val => val.toUpperCase())';
+ case 'trim':
+ return schema + '.transform(val => val.trim())';
+ case 'slug':
+ return schema + '.transform(val => val.toLowerCase().replace(/\\s+/g, "-"))';
+ }
+ }
+
+ return schema;
+}`
+
+//--------------------------------------------------------------------//
+
+const asyncValidationExample =
+`// Generate async validation schemas
+export const UserSchemaAsync = UserSchema.extend({
+ email: z.string().email().refine(async (email) => {
+ // Check if email is unique
+ const exists = await checkEmailExists(email);
+ return !exists;
+ }, {
+ message: "Email already exists",
+ }),
+});
+
+// Usage
+const validateUserAsync = async (data: unknown) => {
+ try {
+ const user = await UserSchemaAsync.parseAsync(data);
+ return { success: true, data: user };
+ } catch (error) {
+ return { success: false, errors: error.errors };
+ }
+};`
+
+//--------------------------------------------------------------------//
+
+export default function AdvancedFeatures() {
+ //hooks
+ const { _ } = useLanguage();
+
+ return (
+ <>
+ {/* Advanced Features Section Content */}
+
+
{_('7. Advanced Features')}
+
+
+ Advanced features extend basic Zod schema generation, adding
+ validation patterns, conditional logic, data transformation,
+ and async validation. These features enable production-ready
+ validation for complex business requirements.
+
+
+
+
{_('7.1. Custom Validators')}
+
+
+ Custom validators let you define specialized validation logic for
+ certain data types or business rules. This feature lets you create
+ reusable validation patterns that can be used across many
+ schema definitions.
+
+
+
+ {customValidatorsExample}
+
+
+
{_('7.2. Conditional Validation')}
+
+
+ Conditional validation enables complex validation logic that
+ depends on the values of other fields. This feature is
+ essential for implementing business rules that require
+ cross-field validation and context-dependent constraints.
+
+
+
+ {conditionalValidationExample}
+
+
+
{_('7.3. Transform and Preprocess')}
+
+
+ Transform and preprocess capabilities allow you to modify data
+ during validation. This enables data normalization, formatting,
+ and cleanup. Using this feature ensures data consistency and
+ proper formatting before validation occurs.
+
+
+
+ {transformPreprocessExample}
+
+
+
{_('7.4. Async Validation')}
+
+
+ Async validation enables validation rules that require
+ external data sources or API calls, such as checking for
+ unique values or validating against external services.
+ This feature is crucial for comprehensive data validation
+ in real applications.
+
+
+
+ Best practices ensure your generated Zod validation schemas are
+ maintainable, performant, and provide excellent developer experience.
+ These guidelines cover error handling, schema composition, type safety,
+ and API integration patterns.
+
+
+
+
{_('8.1. Error Handling')}
+
+
+ Proper error handling ensures that validation failures provide clear,
+ actionable feedback to users and developers. Implement centralized error
+ handling patterns and meaningful error messages to improve the overall
+ user experience.
+
+
+
+ {errorHandlingExample}
+
+
+
{_('8.2. Schema Composition')}
+
+
+ Schema composition enables the creation of reusable validation components
+ that can be combined to build complex validation schemas. This approach
+ promotes code reuse and maintains consistency across your validation logic.
+
+
+
+ {schemaCompositionExample}
+
+
+
{_('8.3. Type Guards')}
+
+
+ Type guards provide runtime type checking that integrates seamlessly
+ with TypeScript's type system. Generated type guards enable safe type
+ narrowing and improve code reliability by ensuring data conforms to
+ expected types.
+
+
+
+ {typeGuardsExample}
+
+
+
{_('8.4. API Integration')}
+
+
+ API integration patterns show how to use generated Zod schemas for
+ request validation in web applications. This includes middleware creation,
+ error response formatting, and type-safe request handling.
+
+
+
+ The implementation section covers the core plugin function and
+ supporting utilities that handle Zod schema generation. This
+ includes configuration validation, content generation, file writing,
+ and error handling throughout the generation process.
+
+
+
+
{_('4.1. Core Plugin Function')}
+
+
+ The core plugin function serves as the main entry point for Zod
+ schema generation. It orchestrates the entire process from
+ configuration validation through content generation to file output,
+ ensuring proper error handling and logging throughout.
+
+
+
+ {corePluginFunction}
+
+
+
{_('4.2. Generation Functions')}
+
+
+ Generation functions create specific parts of the Zod validation
+ output including enum schemas, type schemas, model schemas, and
+ utility schemas. These functions handle proper Zod syntax
+ construction and validation rule application.
+
+
+
+ This tutorial guides you through building a plugin that creates
+ Zod validation schemas from .idea schema files. With this
+ plugin, your schema models become type-safe validation schemas
+ with complete validation rules.
+
+
+
+ >
+ );
+}
\ No newline at end of file
diff --git a/packages/www/plugins/docs/components/validation-plugin/Overview.tsx b/packages/www/plugins/docs/components/validation-plugin/Overview.tsx
new file mode 100644
index 0000000..d7b4d2b
--- /dev/null
+++ b/packages/www/plugins/docs/components/validation-plugin/Overview.tsx
@@ -0,0 +1,65 @@
+//modules
+import { useLanguage, Translate } from 'r22n';
+//local
+import { H1, P, C, SS } from '../../../docs/components/index.js';
+
+export default function Overview() {
+ //hooks
+ const { _ } = useLanguage();
+
+ return (
+ <>
+ {/* Overview Section Content */}
+
+
{_('1. Overview')}
+
+
+ Zod is a TypeScript-first schema validation library that
+ provides runtime type checking and validation. This plugin
+ transforms your .idea schema definitions into
+ comprehensive Zod validation schemas that offer robust
+ runtime validation with excellent TypeScript integration.
+
+
+
+
+ This plugin generates Zod schemas from your .idea
+ schema, including:
+
+
+
+
+
+ Schema Validation: Zod schemas for all models
+ and types
+
+
+
+
+ Type Inference: TypeScript types inferred from
+ Zod schemas
+
+
+
+
+ Custom Validators: Support for custom validation
+ rules
+
+
+
+ The plugin structure defines the core architecture and
+ configuration interface for the Zod validation schema
+ generator. This includes the main plugin function,
+ configuration types, and the overall organization of
+ the generated validation code.
+
+
+
+ {pluginStructureExample}
+
+
+ >
+ );
+}
\ No newline at end of file
diff --git a/packages/www/plugins/docs/components/validation-plugin/Prerequisites.tsx b/packages/www/plugins/docs/components/validation-plugin/Prerequisites.tsx
new file mode 100644
index 0000000..bef276c
--- /dev/null
+++ b/packages/www/plugins/docs/components/validation-plugin/Prerequisites.tsx
@@ -0,0 +1,53 @@
+//modules
+import { useLanguage, Translate } from 'r22n';
+//local
+import { H1, P, C } from '../../../docs/components/index.js';
+
+export default function Prerequisites() {
+ //hooks
+ const { _ } = useLanguage();
+
+ return (
+ <>
+ {/* Prerequisites Section Content */}
+
+
{_('2. Prerequisites')}
+
+
+ Before implementing the Zod validation schema generator
+ plugin, ensure you have the necessary development environment
+ and knowledge. This section covers the essential requirements
+ for successful plugin creation and Zod integration.
+
+
+
+
+ Node.js 16+ and npm/yarn
+
+
+ TypeScript 4.0+
+
+
+ Zod 3.0+
+
+
+
+ Basic understanding of validation concepts
+
+
+
+
+ Familiarity with the @stackpress/idea-transformer
+ library
+
+
+
+ Schema configuration shows how to use the Zod validation
+ generator with your .idea schema files. This section covers
+ the plugin configuration options and how they affect the
+ generated validation schemas.
+
+
+
+
+
+ Add the Zod validation plugin to your .idea schema file:
+
+
+
+ {basicConfiguration}
+
+
+
{_('Configuration Options')}
+
+
+ Configuration options control how Zod validation schemas are
+ generated, including output formatting, validation strictness,
+ and feature enablement. Understanding these options helps you
+ customize the plugin to meet your specific validation
+ requirements.
+
+
+
+ >
+ );
+}
\ No newline at end of file
diff --git a/packages/www/plugins/docs/components/validation-plugin/Troubleshooting.tsx b/packages/www/plugins/docs/components/validation-plugin/Troubleshooting.tsx
new file mode 100644
index 0000000..bf34981
--- /dev/null
+++ b/packages/www/plugins/docs/components/validation-plugin/Troubleshooting.tsx
@@ -0,0 +1,205 @@
+//modules
+import { useLanguage, Translate } from 'r22n';
+//local
+import { H1, H2, P } from '../../../docs/components/index.js';
+import Code from '../../../docs/components/Code.js';
+
+//code examples
+//--------------------------------------------------------------------//
+
+const circularDependenciesExample =
+ `// Handle circular references with lazy evaluation
+const UserSchema: z.ZodSchema = z.lazy(() => z.object({
+ id: z.string(),
+ posts: z.array(PostSchema),
+}));
+
+const PostSchema: z.ZodSchema = z.lazy(() => z.object({
+ id: z.string(),
+ author: UserSchema,
+}));`;
+
+//--------------------------------------------------------------------//
+
+const complexValidationExample =
+ `// Use refinements for complex validation
+const PasswordSchema = z.string()
+ .min(8, "Password must be at least 8 characters")
+ .refine((password) => /[A-Z]/.test(password), {
+ message: "Password must contain at least one uppercase letter",
+ })
+ .refine((password) => /[a-z]/.test(password), {
+ message: "Password must contain at least one lowercase letter",
+ })
+ .refine((password) => /\\d/.test(password), {
+ message: "Password must contain at least one number",
+ });`;
+
+//--------------------------------------------------------------------//
+
+const performanceOptimizationExample =
+ `// Use preprocess for expensive operations
+const OptimizedSchema = z.preprocess(
+ (data) => {
+ // Expensive preprocessing
+ return normalizeData(data);
+ },
+ z.object({
+ // Schema definition
+ })
+);`;
+
+//--------------------------------------------------------------------//
+
+const schemaTestingExample =
+ `// Test schemas with various inputs
+describe('UserSchema', () => {
+ it('should validate valid user data', () => {
+ const validData = {
+ email: 'test@example.com',
+ name: 'Test User',
+ age: 25
+ };
+
+ expect(() => UserSchema.parse(validData)).not.toThrow();
+ });
+
+ it('should reject invalid email', () => {
+ const invalidData = {
+ email: 'invalid-email',
+ name: 'Test User',
+ age: 25
+ };
+
+ expect(() => UserSchema.parse(invalidData)).toThrow();
+ });
+});`;
+
+//--------------------------------------------------------------------//
+
+const errorCustomizationExample =
+ `// Customize error messages for better UX
+const UserSchema = z.object({
+ email: z.string().email("Please enter a valid email address"),
+ age: z.number().min(18, "You must be at least 18 years old"),
+});`;
+
+//--------------------------------------------------------------------//
+
+export default function Troubleshooting() {
+ //hooks
+ const { _ } = useLanguage();
+
+ return (
+ <>
+ {/* Troubleshooting Section Content */}
+
+
{_('9. Troubleshooting')}
+
+
+ This section addresses common issues that you may find when
+ generating Zod validation schemas. It also provides solutions
+ for debugging and resolving problems. By learning these
+ troubleshooting techniques, you can help ensure that your
+ validation schema generation is reliable.
+
+
+
+
{_('9.1. Common Issues')}
+
+
+ Common issues include circular dependencies, complex
+ validation rules, and performance problems with large
+ schemas. These problems typically arise from schema
+ complexity or validation requirements that need specialized
+ handling.
+
+
+
+
{_('9.1.1. Circular Dependencies')}
+
+
+ Circular dependencies occur when schemas reference each
+ other in a way that creates infinite loops. Zod provides
+ lazy evaluation to handle these scenarios while maintaining
+ type safety and validation integrity.
+
+
+
+ {circularDependenciesExample}
+
+
+
{_('9.1.2. Complex Validation Rules')}
+
+
+ Complex validation rules require sophisticated logic that
+ goes beyond simple type checking. Use Zod's refinement
+ capabilities to implement business rules and cross-field
+ validation while maintaining clear error messages.
+
+
+
+ {complexValidationExample}
+
+
+
{_('9.1.3. Performance Issues')}
+
+
+ Performance issues can arise when validation schemas are
+ complex or when handling large datasets. Improve validation
+ performance by using preprocessing, caching, and designing
+ efficient schemas with optimal patterns.
+
+
+
+ {performanceOptimizationExample}
+
+
+
{_('9.2. Debugging Tips')}
+
+
+ Debugging tips help identify and resolve issues during Zod
+ schema generation and usage. These techniques provide
+ visibility into validation behavior and help diagnose
+ problems with schema logic or performance.
+
+
+
+
{_('9.2.1. Schema Testing')}
+
+
+ Schema testing ensures your validation works in all situations
+ by verifying logic against many scenarios. Comprehensive tests
+ catch edge cases and guarantee validation acts as expected
+ in production.
+
+
+
+ {schemaTestingExample}
+
+
+
{_('9.2.2. Error Message Customization')}
+
+
+ Error message customization makes the user experience better by
+ giving clear, actionable feedback when validation fails. Good
+ error messages help users understand what went wrong and what
+ steps to take to fix it.
+
+
+
+ {errorCustomizationExample}
+
+
+
+
+ This tutorial provides a comprehensive foundation for creating
+ Zod validation schemas from .idea files. The generated schemas
+ provide runtime type checking and validation with excellent
+ TypeScript integration.
+
+
+
+ >
+ );
+}
\ No newline at end of file
diff --git a/packages/www/plugins/docs/components/validation-plugin/UsageExamples.tsx b/packages/www/plugins/docs/components/validation-plugin/UsageExamples.tsx
new file mode 100644
index 0000000..19504a7
--- /dev/null
+++ b/packages/www/plugins/docs/components/validation-plugin/UsageExamples.tsx
@@ -0,0 +1,189 @@
+//modules
+import { useLanguage, Translate } from 'r22n';
+//local
+import { H1, H2, P } from '../../../docs/components/index.js';
+import Code from '../../../docs/components/Code.js';
+
+//code examples
+//--------------------------------------------------------------------//
+
+const basicSchemaExample =
+`enum UserRole {
+ ADMIN "admin"
+ USER "user"
+ GUEST "guest"
+}
+
+model User {
+ id String @id @default("nanoid()")
+ email String @email @required
+ name String @min(2) @max(50) @required
+ age Number @min(18) @max(120)
+ role UserRole @default("USER")
+ active Boolean @default(true)
+ createdAt Date @default("now()")
+}
+
+plugin "./plugins/zod-validation.js" {
+ output "./validation.ts"
+ generateTypes true
+ strictMode true
+}`
+
+//--------------------------------------------------------------------//
+
+const generatedValidationUsage = `import {
+ UserSchema,
+ CreateUserSchema,
+ UpdateUserSchema,
+ UserRole
+} from './validation';
+
+// Validate complete user object
+const validateUser = (data: unknown) => {
+ try {
+ const user = UserSchema.parse(data);
+ console.log('Valid user:', user);
+ return { success: true, data: user };
+ } catch (error) {
+ console.error('Validation failed:', error.errors);
+ return { success: false, errors: error.errors };
+ }
+};
+
+// Validate user creation data
+const validateCreateUser = (data: unknown) => {
+ const result = CreateUserSchema.safeParse(data);
+
+ if (result.success) {
+ console.log('Valid create data:', result.data);
+ return result.data;
+ } else {
+ console.error('Validation errors:', result.error.errors);
+ throw new Error('Invalid user data');
+ }
+};
+
+// Validate user update data
+const validateUpdateUser = (data: unknown) => {
+ return UpdateUserSchema.parse(data);
+};
+
+// Example usage
+const userData = {
+ email: 'john@example.com',
+ name: 'John Doe',
+ age: 30,
+ role: 'user' as UserRole
+};
+
+const validUser = validateCreateUser(userData);`
+
+//--------------------------------------------------------------------//
+
+const formValidationExample =
+`import { CreateUserSchema } from './validation';
+
+// React form validation
+function UserForm() {
+ const [errors, setErrors] = useState>({});
+
+ const handleSubmit = (formData: FormData) => {
+ const data = Object.fromEntries(formData);
+
+ const result = CreateUserSchema.safeParse(data);
+
+ if (!result.success) {
+ const fieldErrors: Record = {};
+
+ result.error.errors.forEach((error) => {
+ const field = error.path[0] as string;
+ fieldErrors[field] = error.message;
+ });
+
+ setErrors(fieldErrors);
+ return;
+ }
+
+ // Submit valid data
+ submitUser(result.data);
+ };
+
+ return (
+
+ );
+}`
+
+//--------------------------------------------------------------------//
+
+export default function UsageExamples() {
+ //hooks
+ const { _ } = useLanguage();
+
+ return (
+ <>
+ {/* Usage Examples Section Content */}
+
+
{_('6. Usage Examples')}
+
+
+ Usage examples demonstrate practical applications of the Zod
+ validation generator with real-world scenarios. These examples
+ show how to configure the plugin for different use cases and
+ how the generated validation schemas integrate into development
+ workflows.
+
+
+
+
{_('6.1. Basic Schema')}
+
+
+ A basic schema example shows the fundamental structure needed
+ to generate Zod validation schemas. This includes model
+ definitions with proper validation attributes and plugin
+ configuration that produces comprehensive validation rules.
+
+
+
+ {basicSchemaExample}
+
+
+
{_('6.2. Generated Validation Usage')}
+
+
+ The generated validation usage demonstrates how to use the Zod
+ schemas produced by the plugin in real applications. This shows
+ practical patterns for data validation, error handling, and
+ type safety in TypeScript applications.
+
+
+
+ {generatedValidationUsage}
+
+
+
{_('6.3. Form Validation Example')}
+
+
+ Zod schemas with frontend frameworks for user input validation.
+ This demonstrates real-world usage patterns for form handling
+ and user feedback.
+
+
+
+ {formValidationExample}
+
+
+ >
+ );
+}
diff --git a/packages/www/plugins/docs/components/validation-plugin/index.tsx b/packages/www/plugins/docs/components/validation-plugin/index.tsx
new file mode 100644
index 0000000..fa590ad
--- /dev/null
+++ b/packages/www/plugins/docs/components/validation-plugin/index.tsx
@@ -0,0 +1,11 @@
+//exporting all components to have multiple imports from a single file
+export { default as AdvancedFeatures } from './AdvancedFeatures.js';
+export { default as BestPractices } from './BestPractices.js';
+export { default as Implementation } from './Implementation.js';
+export { default as Introduction } from './Introduction.js';
+export { default as Overview } from './Overview.js';
+export { default as PluginStructure } from './PluginStructure.js';
+export { default as Prerequisites } from './Prerequisites.js';
+export { default as SchemaConfiguration } from './SchemaConfiguration.js';
+export { default as Troubleshooting } from './Troubleshooting.js';
+export { default as UsageExamples } from './UsageExamples.js';
\ No newline at end of file
diff --git a/packages/www/plugins/docs/plugin.ts b/packages/www/plugins/docs/plugin.ts
new file mode 100644
index 0000000..79f6614
--- /dev/null
+++ b/packages/www/plugins/docs/plugin.ts
@@ -0,0 +1,102 @@
+//stackpress
+import type { Server, Response } from 'stackpress/server';
+//view
+import type { ViewConfig, BrandConfig, LanguageConfig } from 'stackpress';
+
+export function setServerProps(server: Server, res: Response) {
+ //get the view, brand and auth config
+ const view = server.config.path('view', {});
+ const brand = server.config.path('brand', {});
+ const language = server.config.path('language', {
+ key: 'locale',
+ locale: 'en_US',
+ languages: {}
+ });
+ //set data for template layer
+ res.data.set('view', {
+ base: view.base || '/',
+ props: view.props || {}
+ });
+ res.data.set('brand', {
+ name: brand.name || 'Stackpress',
+ logo: brand.logo || '/logo.png',
+ icon: brand.icon || '/icon.png',
+ favicon: brand.favicon || '/favicon.ico',
+ });
+ res.data.set('language', {
+ key: language.key || 'locale',
+ locale: language.locale || 'en_US',
+ languages: language.languages || {}
+ });
+}
+
+export default function plugin(server: Server) {
+ //on route, add docs routes
+ server.on('route', _ => {
+ server.get('/docs', (_req, res, ctx) => setServerProps(ctx, res));
+ server.get('/docs/**', (_req, res, ctx) => setServerProps(ctx, res));
+ server.get('/docs', '@/plugins/docs/views/index', -100);
+ server.get('/docs/introduction', '@/plugins/docs/views/index', -100);
+
+ //other routes
+ [
+ 'getting-started',
+ //specifications
+ 'specifications/introduction',
+ 'specifications/syntax-overview',
+ 'specifications/data-types',
+ 'specifications/schema-elements',
+ 'specifications/schema-structure',
+ 'specifications/schema-directives',
+ 'specifications/processing-flow',
+ 'specifications/plugin-system',
+ 'specifications/complete-examples',
+ 'specifications/best-practices',
+ 'specifications/error-handling',
+ //parser
+ 'parser/installation',
+ 'parser/core-concepts',
+ 'parser/api-reference',
+ 'parser/examples',
+ 'parser/best-practices',
+ 'parser/api-references/compiler',
+ 'parser/api-references/lexer',
+ 'parser/api-references/ast',
+ 'parser/api-references/tokens',
+ 'parser/api-references/exception-handling',
+ //transformers
+ 'transformers/introduction',
+ 'transformers/api-reference',
+ 'transformers/architecture',
+ 'transformers/usage-patterns',
+ 'transformers/common-use-cases',
+ 'transformers/examples',
+ 'transformers/error-handling',
+ 'transformers/best-practices',
+ 'transformers/api-references/transformer',
+ 'transformers/api-references/terminal',
+ //plugins
+ 'plugin-development/plugin-development-guide',
+ 'plugin-development/plugin-examples',
+ 'plugin-development/plugin-configuration',
+ 'plugin-development/error-handling',
+ 'plugin-development/best-practices',
+ 'plugin-development/available-tutorials',
+ 'plugin-development/advanced-tutorials',
+ 'plugin-development/getting-started',
+ //tutorials
+ 'tutorials/tsmorph-plugin-guide',
+ 'tutorials/mysql-table-plugin',
+ 'tutorials/html-form-plugin',
+ 'tutorials/markdown-documentation-plugin',
+ 'tutorials/graphql-schema-plugin',
+ 'tutorials/typescript-interface-plugin',
+ 'tutorials/api-client-plugin',
+ 'tutorials/validation-plugin',
+ 'tutorials/test-data-plugin',
+ 'tutorials/openapi-specification-plugin',
+ ].map(route => {
+ server.get(`/docs/${route}`, `@/plugins/docs/views/${route}`, -100);
+ });
+ });
+};
\ No newline at end of file
diff --git a/packages/www/plugins/docs/styles/styles.css b/packages/www/plugins/docs/styles/styles.css
new file mode 100644
index 0000000..84da1e6
--- /dev/null
+++ b/packages/www/plugins/docs/styles/styles.css
@@ -0,0 +1,3 @@
+@import url('https://fonts.googleapis.com/css2?family=Poppins:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&display=swap');
+
+* { font-family: 'Poppins', sans-serif; }
\ No newline at end of file
diff --git a/packages/www/plugins/docs/views/getting-started.tsx b/packages/www/plugins/docs/views/getting-started.tsx
new file mode 100644
index 0000000..983e880
--- /dev/null
+++ b/packages/www/plugins/docs/views/getting-started.tsx
@@ -0,0 +1,235 @@
+//modules
+import type {
+ ServerConfigProps,
+ ServerPageProps
+} from 'stackpress/view/client';
+import { useState } from 'react';
+import { useLanguage, Translate } from 'r22n';
+import clsx from 'clsx';
+//local
+import { H1, P, C, Nav } from '../components/index.js';
+import Code from '../components/Code.js';
+import Layout from '../components/Layout.js';
+
+//code examples
+//--------------------------------------------------------------------//
+
+const npmInstallCommand = 'npm i -D @stackpress/idea';
+
+//--------------------------------------------------------------------//
+
+const yarnInstallCommand = 'yarn add --dev @stackpress/idea';
+
+//--------------------------------------------------------------------//
+
+const schemaExample =
+`model User {
+ id String @id @default("nanoid()")
+ name String @required
+ email String @unique @required
+ created Date @default("now()")
+}
+
+plugin "./plugins/typescript-generator.js" {
+ output "./generated/types.ts"
+}`;
+
+//--------------------------------------------------------------------//
+
+const generateCommand = 'npx idea transform --input schema.idea';
+
+//styles
+//--------------------------------------------------------------------//
+
+const packageStyle = clsx(
+ 'bg-yellow-800',
+ 'text-white'
+);
+
+//--------------------------------------------------------------------//
+
+export function Head(props: ServerPageProps) {
+ //props
+ const { request, styles = [] } = props;
+ //hooks
+ const { _ } = useLanguage();
+ //variables
+ const title = _('Getting Started');
+ const description = _('describe');
+ return (
+ <>
+ {title}
+
+
+
+
+
+
+
+
+
+
+
+
+ {styles.map((href, index) => (
+
+ ))}
+ >
+ );
+}
+
+export function Body() {
+ //hooks
+ const [install, setInstall] = useState('npm');
+ const { _ } = useLanguage();
+
+ return (
+
+ {/* Getting Started Section Content */}
+
+
{_('Getting Started')}
+
+
+ The following is a guide to get you started with Idea.
+
+
+
+ Check the generated files in your output directories!
+
+
+
+
+ {/* Page Navigation */}
+
+
+ );
+}
+
+export default function Page(props: ServerPageProps) {
+ const { data, session, request, response } = props;
+ return (
+
+
+
+ );
+}
\ No newline at end of file
diff --git a/packages/www/plugins/docs/views/index.tsx b/packages/www/plugins/docs/views/index.tsx
new file mode 100644
index 0000000..a50c049
--- /dev/null
+++ b/packages/www/plugins/docs/views/index.tsx
@@ -0,0 +1,360 @@
+//modules
+import type {
+ ServerConfigProps,
+ ServerPageProps
+} from 'stackpress/view/client';
+import { useLanguage, Translate } from 'r22n';
+import clsx from 'clsx';
+//local
+import { H1, H2, P, Nav } from '../components/index.js';
+import Layout from '../components/Layout.js';
+import Code from '../components/Code.js';
+
+//code example
+//--------------------------------------------------------------------//
+
+const schemaExample =
+`// schema.idea
+enum UserRole {
+ ADMIN "Administrator"
+ CUSTOMER "Customer"
+}
+
+model User {
+ id String @id @default("nanoid()")
+ email String @unique @required
+ name String @required
+ role UserRole @default("CUSTOMER")
+ orders Order[] @relation(Order.userId)
+}
+
+model Product {
+ id String @id @default("nanoid()")
+ name String @required
+ price Number @required
+ inStock Boolean @default(true)
+}
+
+model Order {
+ id String @id @default("nanoid()")
+ userId String @relation(User.id)
+ total Number @required
+ status String @default("PENDING")
+}
+
+// Generate everything with plugins
+plugin "./plugins/typescript-generator.js" {
+ output "./src/types/schema.ts"
+}
+
+plugin "./plugins/database-generator.js" {
+ output "./database/schema.sql"
+ dialect "postgresql"
+}
+
+plugin "./plugins/react-forms.js" {
+ output "./src/components/forms/"
+ framework "react"
+ styling "tailwind"
+}
+
+plugin "./plugins/api-generator.js" {
+ output "./src/api/"
+ framework "express"
+ includeValidation true
+}`;
+
+//--------------------------------------------------------------------//
+
+//styles
+//--------------------------------------------------------------------//
+
+const iconStyle = clsx(
+ 'fa-circle-check',
+ 'fa-solid',
+ 'mx-2',
+ 'text-green-500'
+);
+
+//--------------------------------------------------------------------//
+
+export function DocumentationHead(props: ServerPageProps) {
+ //props
+ const { request, styles = [] } = props;
+ //hooks
+ const { _ } = useLanguage();
+ //variables
+ const url = request.url?.pathname || '/docs';
+ const title = _('What is .idea?');
+ const description = _(
+ 'The .idea file format is a declarative schema definition language' +
+ 'designed to simplify application development by providing a single' +
+ 'source of truth for data structures, relationships, and code generation.'
+ );
+ return (
+ <>
+ {title}
+
+
+
+
+
+
+
+
+
+
+
+
+ {styles.map((href, index) => (
+
+ ))}
+ >
+ )
+}
+
+export function DocumentationBody() {
+ //hooks
+ const { _ } = useLanguage();
+
+ return (
+
+ {/* Introduction */}
+
+
{_('What is .idea?')}
+
+
+
+ The .idea file format is a declarative schema definition
+ language designed to simplify application development by
+ providing a single source of truth for data structures,
+ relationships, and code generation. It enables developers
+ to define their application's data model once and generate
+ multiple outputs including database schemas, TypeScript
+ interfaces, API documentation, forms, and more.
+
+
+
+
+
+ Think of it as the bridge between AI prompting and full-
+ stack code generation - where a simple schema definition can
+ automatically generate everything from database tables to
+ React components, API endpoints to documentation sites.
+
+
+
+ The library uses a custom Exception class that extends the
+ standard Exception class for better error reporting.
+
+
+ {exceptionExample}
+
+
+
+ {/* Page Navigation */}
+
+
+ );
+}
+
+export default function Page(props: ServerPageProps) {
+ const { data, session, request, response } = props;
+ return (
+ }
+ >
+
+
+ );
+}
diff --git a/packages/www/plugins/docs/views/parser/api-references/ast.tsx b/packages/www/plugins/docs/views/parser/api-references/ast.tsx
new file mode 100644
index 0000000..e80f6e4
--- /dev/null
+++ b/packages/www/plugins/docs/views/parser/api-references/ast.tsx
@@ -0,0 +1,1536 @@
+//modules
+import type {
+ ServerConfigProps,
+ ServerPageProps
+} from 'stackpress/view/client';
+import { Table, Thead, Trow, Tcol } from 'frui/element/Table';
+import { useLanguage, Translate } from 'r22n';
+import clsx from 'clsx';
+//local
+import { H1, H2, C, SS, Nav, P } from '../../../components/index.js';
+import Code from '../../../components/Code.js';
+import Layout from '../../../components/Layout.js';
+
+//code examples
+//--------------------------------------------------------------------//
+
+const examples = [
+ `import {
+ SchemaTree,
+ EnumTree,
+ ModelTree,
+ TypeTree,
+ PropTree,
+ PluginTree,
+ UseTree
+} from '@stackpress/idea-parser';`,
+
+ //---------------------------------------------------------------
+
+ `import { SchemaTree, Lexer } from '@stackpress/idea-parser';
+
+const lexer = new Lexer();
+SchemaTree.definitions(lexer);
+
+// Lexer now has definitions for all schema constructs:
+// enum, prop, type, model, plugin, use keywords and structures`,
+
+ //---------------------------------------------------------------
+
+ `import { SchemaTree } from '@stackpress/idea-parser';
+
+const schemaCode = \`
+plugin "./database" {
+ provider "postgresql"
+}
+
+enum Status {
+ ACTIVE "Active"
+ INACTIVE "Inactive"
+}
+
+prop Text { type "text" }
+
+model User {
+ id String @id
+ name String @field.input(Text)
+ status Status
+}
+\`;
+
+const ast = SchemaTree.parse(schemaCode);
+console.log(ast.type); // 'Program'
+console.log(ast.kind); // 'schema'
+console.log(ast.body.length); // 4 (plugin, enum, prop, model)`,
+
+ //---------------------------------------------------------------
+
+ `import { SchemaTree } from '@stackpress/idea-parser';
+
+const tree = new SchemaTree();
+const schemaCode = 'enum Status { ACTIVE "Active" }';
+
+const result = tree.parse(schemaCode, 0);
+console.log(result.body[0].kind); // 'enum'`,
+
+ //---------------------------------------------------------------
+
+ `import { EnumTree, Lexer } from '@stackpress/idea-parser';
+
+const lexer = new Lexer();
+EnumTree.definitions(lexer);
+
+// Adds 'EnumWord' token definition for 'enum' keyword`,
+
+ //---------------------------------------------------------------
+
+ `import { EnumTree } from '@stackpress/idea-parser';
+
+const enumCode = \`enum Roles {
+ ADMIN "Admin"
+ MANAGER "Manager"
+ USER "User"
+}\`;
+
+const ast = EnumTree.parse(enumCode);
+console.log(ast.kind); // 'enum'
+console.log(ast.declarations[0].id.name); // 'Roles'
+console.log(ast.declarations[0].init.properties.length); // 3
+console.log(ast.declarations[0].init.properties[0].key.name); // 'ADMIN'
+console.log(ast.declarations[0].init.properties[0].value.value); // 'Admin'`,
+
+ //---------------------------------------------------------------
+
+ `const tree = new EnumTree();
+tree._lexer.load('enum Status { ACTIVE "Active" INACTIVE "Inactive" }');
+
+const enumToken = tree.enum();
+console.log(enumToken.declarations[0].id.name); // 'Status'
+console.log(enumToken.declarations[0].init.properties[0].key.name); // 'ACTIVE'
+console.log(enumToken.declarations[0].init.properties[0].value.value); // 'Active'`,
+
+ //---------------------------------------------------------------
+
+ `// Inside enum parsing, after opening brace
+const property = tree.property();
+console.log(property.key.name); // e.g., 'ADMIN'
+console.log(property.value.value); // e.g., 'Admin'`,
+ //---------------------------------------------------------------
+
+ `import { ModelTree } from '@stackpress/idea-parser';
+
+const modelCode = \`model User @label("User" "Users") {
+ id String @label("ID") @id @default("nanoid(20)")
+ username String @label("Username") @searchable @field.input(Text) @is.required
+ password String @label("Password") @field.password @is.clt(80) @is.cgt(8) @is.required @list.hide @view.hide
+ role Roles @label("Role") @filterable @field.select @list.text(Uppercase) @view.text(Uppercase)
+ address Address? @label("Address") @list.hide
+ age Number @label("Age") @unsigned @filterable @sortable @field.number(Age) @is.gt(0) @is.lt(150)
+ active Boolean @label("Active") @default(true) @filterable @field.switch @list.yesno @view.yesno
+ created Date @label("Created") @default("now()") @filterable @sortable @list.date(Pretty)
+}\`;
+
+const ast = ModelTree.parse(modelCode);
+console.log(ast.kind); // 'model'
+console.log(ast.mutable); // false (because of '!' modifier)
+console.log(ast.declarations[0].id.name); // 'User'`,
+
+ //---------------------------------------------------------------
+
+ `const tree = new ModelTree();
+tree._lexer.load('model User { id String @id }');
+
+const modelToken = tree.model();
+console.log(modelToken.kind); // 'model'
+console.log(modelToken.mutable); // false (immutable due to '!')`,
+
+ //---------------------------------------------------------------
+
+ `import { TypeTree } from '@stackpress/idea-parser';
+
+const typeCode = \`type Address @label("Address" "Addresses") {
+ street String @field.input @is.required
+ city String @field.input @is.required
+ country String @field.select
+ postal String @field.input
+}\`;
+
+const ast = TypeTree.parse(typeCode);
+console.log(ast.kind); // 'type'
+console.log(ast.mutable); // true (mutable by default)
+console.log(ast.declarations[0].id.name); // 'Address'`,
+
+ //---------------------------------------------------------------
+
+ `const tree = new TypeTree();
+tree._lexer.load('type Address { street String city String }');
+
+const typeToken = tree.type();
+console.log(typeToken.kind); // 'type'
+console.log(typeToken.mutable); // true (default for types)`,
+
+ //---------------------------------------------------------------
+
+ `// Inside type parsing
+const property = tree.property();
+console.log(property.key.name); // e.g., 'street'
+console.log(property.value); // Object containing type and attributes`,
+
+ //---------------------------------------------------------------
+
+ `// For parsing generic type parameters
+const parameter = tree.parameter();
+console.log(parameter.key.name); // Parameter name
+console.log(parameter.value); // Parameter type/constraint`,
+
+ //---------------------------------------------------------------
+
+ `import { PropTree } from '@stackpress/idea-parser';
+
+const propCode = \`prop EmailInput {
+ type "email"
+ format "email"
+ placeholder "Enter your email"
+ required true
+}\`;
+
+const ast = PropTree.parse(propCode);
+console.log(ast.kind); // 'prop'
+console.log(ast.declarations[0].id.name); // 'EmailInput'`,
+
+ //---------------------------------------------------------------
+
+ `const tree = new PropTree();
+tree._lexer.load('prop Text { type "text" format "lowercase" }');
+
+const propToken = tree.prop();
+console.log(propToken.kind); // 'prop'
+console.log(propToken.declarations[0].id.name); // 'Text'`,
+
+ //---------------------------------------------------------------
+
+ `import { PluginTree } from '@stackpress/idea-parser';
+
+const pluginCode = \`plugin "./database-plugin" {
+ provider "postgresql"
+ url env("DATABASE_URL")
+ previewFeatures ["fullTextSearch"]
+}\`;
+
+const ast = PluginTree.parse(pluginCode);
+console.log(ast.kind); // 'plugin'
+console.log(ast.declarations[0].id.name); // './database-plugin'`,
+
+ //---------------------------------------------------------------
+
+ `const tree = new PluginTree();
+tree._lexer.load('plugin "./custom" { provider "custom-provider" }');
+
+const pluginToken = tree.plugin();
+console.log(pluginToken.kind); // 'plugin'
+console.log(pluginToken.declarations[0].id.name); // './custom'`,
+
+ //---------------------------------------------------------------
+
+ `import { UseTree } from '@stackpress/idea-parser';
+
+const useCode = 'use "./shared/types.idea"';
+
+const ast = UseTree.parse(useCode);
+console.log(ast.type); // 'ImportDeclaration'
+console.log(ast.source.value); // './shared/types.idea'`,
+
+ //---------------------------------------------------------------
+
+ `const tree = new UseTree();
+tree._lexer.load('use "./another.idea"');
+
+const useToken = tree.use();
+console.log(useToken.type); // 'ImportDeclaration'
+console.log(useToken.source.value); // './another.idea'`,
+
+ //---------------------------------------------------------------
+
+ `import { EnumTree, ModelTree, TypeTree } from '@stackpress/idea-parser';
+
+// Parse individual enum
+const enumAST = EnumTree.parse(\`enum Roles {
+ ADMIN "Admin"
+ MANAGER "Manager"
+ USER "User"
+}\`);
+
+// Parse individual model
+const modelAST = ModelTree.parse(\`model User {
+ id String @id
+ username String @is.required
+}\`);
+
+// Parse individual type
+const typeAST = TypeTree.parse(\`type Address {
+ street String
+ city String
+}\`);`,
+
+ //---------------------------------------------------------------
+
+ `import { EnumTree, Compiler } from '@stackpress/idea-parser';
+
+// Parse and compile in one step
+const enumAST = EnumTree.parse(\`enum Status {
+ ACTIVE "Active"
+ INACTIVE "Inactive"
+}\`);
+const [enumName, enumConfig] = Compiler.enum(enumAST);
+
+console.log(enumName); // 'Status'
+console.log(enumConfig); // { ACTIVE: 'Active', INACTIVE: 'Inactive' }`,
+
+ //---------------------------------------------------------------
+
+ `import { AbstractTree, Lexer } from '@stackpress/idea-parser';
+import type { DeclarationToken } from '@stackpress/idea-parser';
+
+class CustomTree extends AbstractTree {
+ static definitions(lexer: Lexer) {
+ super.definitions(lexer);
+ // Add custom token definitions
+ lexer.define('CustomKeyword', (code, index) => {
+ // Custom token reader implementation
+ });
+ return lexer;
+ }
+
+ static parse(code: string, start = 0) {
+ return new this().parse(code, start);
+ }
+
+ parse(code: string, start = 0): DeclarationToken {
+ this._lexer.load(code, start);
+ return this.customDeclaration();
+ }
+
+ customDeclaration(): DeclarationToken {
+ // Custom parsing logic
+ const keyword = this._lexer.expect('CustomKeyword');
+ // ... more parsing logic
+
+ return {
+ type: 'VariableDeclaration',
+ kind: 'custom',
+ start: keyword.start,
+ end: this._lexer.index,
+ declarations: [/* ... */]
+ };
+ }
+}`,
+
+ //---------------------------------------------------------------
+
+ `import { SchemaTree, Exception } from '@stackpress/idea-parser';
+
+try {
+ // Invalid syntax - missing closing brace
+ SchemaTree.parse('enum Status { ACTIVE "Active"');
+} catch (error) {
+ if (error instanceof Exception) {
+ console.log('Parse error:', error.message);
+ console.log('Position:', error.start, '-', error.end);
+ }
+}`,
+
+ //---------------------------------------------------------------
+
+ `try {
+ // Invalid - 'enum' keyword expected but found 'model'
+ EnumTree.parse('model User { id String }');
+} catch (error) {
+ console.log('Expected enum but found model');
+}`,
+
+ //---------------------------------------------------------------
+
+ `import { EnumTree } from '@stackpress/idea-parser';
+
+try {
+ // Empty string will throw an error
+ EnumTree.parse('');
+} catch (error) {
+ console.log('Error:', error.message); // 'Unexpected end of input'
+}`,
+
+ //---------------------------------------------------------------
+
+ `import { ModelTree } from '@stackpress/idea-parser';
+
+try {
+ // Invalid - model names must be capitalized
+ ModelTree.parse('model user { id String }');
+} catch (error) {
+ console.log('Expected CapitalIdentifier but got something else');
+}`,
+
+ //---------------------------------------------------------------
+
+ `// This is what happens internally:
+import { SchemaTree, Compiler } from '@stackpress/idea-parser';
+
+export function parse(code: string) {
+ const ast = SchemaTree.parse(code); // Parse to AST
+ return Compiler.schema(ast); // Compile to JSON
+}
+
+export function final(code: string) {
+ const ast = SchemaTree.parse(code); // Parse to AST
+ return Compiler.final(ast); // Compile and clean up
+}`,
+
+ //---------------------------------------------------------------
+
+ `import { Lexer, SchemaTree } from '@stackpress/idea-parser';
+
+// Create and configure lexer once
+const lexer = new Lexer();
+SchemaTree.definitions(lexer);
+
+// Reuse for multiple parses
+const tree = new SchemaTree(lexer);
+
+const result1 = tree.parse(code1);
+const result2 = tree.parse(code2);
+const result3 = tree.parse(code3);`,
+
+ //---------------------------------------------------------------
+
+ `// Inside tree parsing methods
+const checkpoint = this._lexer.clone();
+
+try {
+ // Try to parse optional structure
+ return this.parseOptionalStructure();
+} catch (error) {
+ // Restore lexer state and continue
+ this._lexer = checkpoint;
+ return this.parseAlternativeStructure();
+}`,
+
+ //---------------------------------------------------------------
+
+ `const enumCode = \`enum Roles {
+ ADMIN "Admin"
+ MANAGER "Manager"
+ USER "User"
+}\`;
+
+const ast = EnumTree.parse(enumCode);
+// Produces a complete AST with all three enum values`,
+
+ //---------------------------------------------------------------
+
+ `const modelCode = \`model User @label("User" "Users") {
+ id String @label("ID") @id @default("nanoid(20)")
+ username String @label("Username") @searchable @field.input(Text) @is.required
+ password String @label("Password") @field.password @is.clt(80) @is.cgt(8) @is.required @list.hide @view.hide
+ role Roles @label("Role") @filterable @field.select @list.text(Uppercase) @view.text(Uppercase)
+ address Address? @label("Address") @list.hide
+ age Number @label("Age") @unsigned @filterable @sortable @field.number(Age) @is.gt(0) @is.lt(150)
+ balance Number[] @label("Balance") @filterable @sortable @field.number() @list.number() @view.number
+ active Boolean @label("Active") @default(true) @filterable @field.switch @list.yesno @view.yesno
+ created Date @label("Created") @default("now()") @filterable @sortable @list.date(Pretty)
+ updated Date @label("Updated") @default("updated()") @filterable @sortable @list.date(Pretty)
+ company Company? @label("My Company")
+}\`;
+
+const ast = ModelTree.parse(modelCode);
+// Produces a complete model AST with all columns and attributes`
+];
+
+//--------------------------------------------------------------------//
+
+//styles
+//--------------------------------------------------------------------//
+
+const anchorStyles = clsx(
+ 'cursor-pointer',
+ 'hover:text-blue-700',
+ 'text-blue-500'
+);
+
+//--------------------------------------------------------------------//
+
+export function Head(props: ServerPageProps) {
+ //props
+ const { request, styles = [] } = props;
+ //hooks
+ const { _ } = useLanguage();
+ //variables
+ const title = _('Syntax Trees');
+ const description = _(
+ 'The AST classes are responsible for parsing specific parts ' +
+ 'of schema code into Abstract Syntax Trees (ASTs). Each AST ' +
+ 'class handles a different type of declaration or construct ' +
+ 'in the schema language.'
+ );
+ return (
+ <>
+ {title}
+
+
+
+
+
+
+
+
+
+
+
+ {styles.map((href, index) => (
+
+ ))}
+ >
+ )
+}
+
+export function Right() {
+ //hooks
+ const { _ } = useLanguage();
+
+ return (
+
+ );
+}
+
+export function Body() {
+ //hooks
+ const { _ } = useLanguage();
+
+ return (
+
+ {/* Syntax Trees Section Content */}
+
+
{_('Syntax Trees')}
+
+ The AST classes are responsible for parsing specific parts
+ of schema code into Abstract Syntax Trees (ASTs). Each AST
+ class handles a different type of declaration or construct
+ in the schema language.
+
+
+ {examples[0]}
+
+
+
+ {/* Horizontal Rule */}
+
+
+ {/* SchemaTree Section Content */}
+
+
+
+ The Compiler class provides static methods for converting
+ Abstract Syntax Tree (AST) tokens into structured JSON
+ configurations. It serves as the bridge between parsed
+ tokens and the final JSON output.
+
+
+
+ The Exception class extends the Exception class from
+ @stackpress/lib to provide enhanced error handling specific
+ to the idea parser library. It includes position information
+ and better error reporting for parsing failures.
+
+
+
+ Exception is a specialized error class that extends the
+ base Exception class with additional functionality for
+ parser-specific error handling. It automatically includes
+ position information when parsing fails, making it easier
+ to identify and fix syntax errors in schema files.
+
+
+
+ {/* Horizontal Rule */}
+
+
+ {/* Usage Examples Section Content */}
+
+
{_('Usage Examples')}
+
+
{_('Basic Error Handling')}
+
+ {examples[1]}
+
+
+
{_('Position Information')}
+
+ Exception includes position information to help locate
+ errors in the source code:
+
+
+ {examples[2]}
+
+
+
+
+ While Exception indicates parsing failure, you can
+ implement error recovery strategies:
+
+
+ {examples[8]}
+
+
+
+ {/* Horizontal Rule */}
+
+
+ {/* Language Server Integration Section Content */}
+
+
{_('Language Server Integration')}
+
+ Exception's position information makes it ideal for language
+ server implementations:
+
+
+ {examples[9]}
+
+
+
+ {/* Horizontal Rule */}
+
+
+ {/* Inherited Features Section Content */}
+
+
{_('Inherited Features')}
+
+ Since Exception extends the base Exception class from
+ @stackpress/lib, it inherits all the enhanced error handling
+ features:
+
+
+
{_('Template-based error messages')}
+
{_('Enhanced stack trace parsing')}
+
{_('Position information support')}
+
{_('HTTP status code integration')}
+
{_('Validation error aggregation')}
+
+
+ For more details on the base Exception functionality, refer to the
+
+ {' '}@stackpress/lib Exception documentation
+ .
+
+
+
+ {/* Horizontal Rule */}
+
+
+ {/* Best Practices Section Content */}
+
+
{_('Best Practices')}
+
+
{_('Always Check Error Type')}
+
+ {examples[10]}
+
+
+
{_('Use Position Information')}
+
+ {examples[11]}
+
+
+
{_('Provide Helpful Error Messages')}
+
+ {examples[12]}
+
+
+
+ {/* Page Navigation */}
+
+
+ );
+}
+
+export default function Page(props: ServerPageProps) {
+ const { data, session, request, response } = props;
+ return (
+ }
+ >
+
+
+ );
+}
diff --git a/packages/www/plugins/docs/views/parser/api-references/lexer.tsx b/packages/www/plugins/docs/views/parser/api-references/lexer.tsx
new file mode 100644
index 0000000..edd1f21
--- /dev/null
+++ b/packages/www/plugins/docs/views/parser/api-references/lexer.tsx
@@ -0,0 +1,1278 @@
+//modules
+import type {
+ ServerConfigProps,
+ ServerPageProps
+} from 'stackpress/view/client';
+import { useLanguage, Translate } from 'r22n';
+import clsx from 'clsx';
+//local
+import { H1, H2, P, C, Nav, SS } from '../../../components/index.js';
+import Code from '../../../components/Code.js';
+import Layout from '../../../components/Layout.js';
+import { Table, Thead, Trow, Tcol } from 'frui/element/Table';
+
+//code examples
+//--------------------------------------------------------------------//
+
+const examples = [
+ `import { Lexer } from '@stackpress/idea-parser';`,
+
+ //------------------------------------------------------------------//
+
+ `import { Lexer } from '@stackpress/idea-parser';
+
+const lexer = new Lexer();
+lexer.load('enum Status { ACTIVE "Active" }');
+lexer.define('enum', enumReader);
+
+// Clone preserves code, index position, and all definitions
+const clonedLexer = lexer.clone();
+console.log(clonedLexer.index); // Same index as original
+console.log(clonedLexer.dictionary); // Same definitions as original`,
+
+ //------------------------------------------------------------------//
+
+ `import { Lexer } from '@stackpress/idea-parser';
+import definitions from '@stackpress/idea-parser/definitions';
+
+const lexer = new Lexer();
+
+// Load all predefined token definitions
+Object.keys(definitions).forEach((key) => {
+ lexer.define(key, definitions[key]);
+});
+
+// Define a custom token
+lexer.define('customKeyword', (code, start, lexer) => {
+ if (code.substring(start, start + 6) === 'custom') {
+ return {
+ type: 'Keyword',
+ value: 'custom',
+ start: start,
+ end: start + 6
+ };
+ }
+ return undefined;
+});`,
+
+ //------------------------------------------------------------------//
+
+ `import { Lexer } from '@stackpress/idea-parser';
+import definitions, { data } from '@stackpress/idea-parser/definitions';
+
+const lexer = new Lexer();
+Object.keys(definitions).forEach((key) => {
+ lexer.define(key, definitions[key]);
+});
+
+// Parse a float literal
+lexer.load('4.4');
+const floatToken = lexer.expect('Float');
+console.log(floatToken.value); // 4.4
+console.log(floatToken.start); // 0
+console.log(floatToken.end); // 3
+
+// Parse any data type (scalar, object, or array)
+lexer.load('"hello world"');
+const stringToken = lexer.expect(data);
+console.log(stringToken.value); // 'hello world'
+
+// Expect one of multiple token types
+lexer.load('true');
+const booleanToken = lexer.expect(['Boolean', 'String', 'Integer']);
+console.log(booleanToken.value); // true`,
+
+ //------------------------------------------------------------------//
+
+ `import { Lexer } from '@stackpress/idea-parser';
+
+const lexer = new Lexer();
+lexer.define('String', definitions['String']);
+
+const definition = lexer.get('String');
+if (definition) {
+ console.log('Definition key:', definition.key); // 'String'
+ console.log('Reader function:', typeof definition.reader); // 'function'
+} else {
+ console.log('Definition not found');
+}`,
+
+ //------------------------------------------------------------------//
+
+ `import { Lexer } from '@stackpress/idea-parser';
+
+const lexer = new Lexer();
+
+// Load code from the beginning
+lexer.load('enum Status { ACTIVE "Active" }');
+console.log(lexer.index); // 0
+
+// Load code starting from a specific position
+lexer.load('enum Status { ACTIVE "Active" }', 5);
+console.log(lexer.index); // 5
+console.log(lexer.substring(5, 11)); // 'Status'`,
+
+ //------------------------------------------------------------------//
+
+ `import { Lexer } from '@stackpress/idea-parser';
+
+const lexer = new Lexer();
+lexer.define('literal', (code, start) => {
+ if (code.startsWith('42', start)) {
+ return { type: 'Literal', value: 42, start, end: start + 2 };
+ }
+ return undefined;
+});
+
+const code = '42';
+
+// Match against specific token types
+const match = lexer.match(code, 0, ['literal']);
+if (match) {
+ console.log('Matched:', match.type); // 'Literal'
+ console.log('Value:', match.value); // 42
+}
+
+// Match against all available definitions (pass undefined for keys)
+const match2 = lexer.match('42', 0, undefined);
+if (match2) {
+ console.log('Matched:', match2.type); // 'Literal'
+}`,
+
+ //------------------------------------------------------------------//
+
+ `import { Lexer } from '@stackpress/idea-parser';
+import definitions from '@stackpress/idea-parser/definitions';
+
+const lexer = new Lexer();
+Object.keys(definitions).forEach((key) => {
+ lexer.define(key, definitions[key]);
+});
+
+lexer.load('enum Status { ACTIVE "Active" }');
+
+// Test if next token matches (doesn't advance index)
+if (lexer.next('AnyIdentifier')) {
+ console.log('Next token is an identifier');
+ console.log(lexer.index); // Still 0
+}
+
+// Test for multiple possible tokens
+if (lexer.next(['String', 'Integer', 'Boolean'])) {
+ console.log('Next token is a literal value');
+}`,
+
+ //------------------------------------------------------------------//
+
+ `import { Lexer } from '@stackpress/idea-parser';
+import definitions from '@stackpress/idea-parser/definitions';
+
+const lexer = new Lexer();
+Object.keys(definitions).forEach((key) => {
+ lexer.define(key, definitions[key]);
+});
+
+lexer.load('/* some comment */ enum Status');
+
+// Try to parse optional whitespace/comments
+const comment = lexer.optional('note');
+if (comment) {
+ console.log('Found comment:', comment.value); // '/* some comment */'
+}
+
+// Skip optional whitespace
+lexer.optional('whitespace');
+
+// Now parse the enum keyword
+const enumToken = lexer.expect('AnyIdentifier');
+console.log(enumToken.name); // 'enum'`,
+
+ //------------------------------------------------------------------//
+
+ `import { Lexer } from '@stackpress/idea-parser';
+
+const lexer = new Lexer();
+lexer.load(''); // Empty string
+
+// Read the next token (tries all definitions)
+const nextToken = lexer.read();
+console.log(nextToken); // undefined (no tokens in empty string)
+
+lexer.load('42');
+lexer.define('Integer', definitions['Integer']);
+
+const token = lexer.read();
+if (token) {
+ console.log('Token type:', token.type); // 'Literal'
+ console.log('Token value:', token.value); // 42
+}`,
+
+ //------------------------------------------------------------------//
+
+ `import { Lexer } from '@stackpress/idea-parser';
+
+const lexer = new Lexer();
+lexer.load('some code');
+
+// Extract specific portions of code
+const substring = lexer.substring(5, 9);
+console.log(substring); // 'code'
+
+// Return empty string when start and end are the same
+const empty = lexer.substring(5, 5);
+console.log(empty); // ''`,
+
+ //------------------------------------------------------------------//
+
+ `import { Lexer } from '@stackpress/idea-parser';
+
+const lexer = new Lexer();
+lexer.load('enum Status { ACTIVE "Active" }');
+
+// Find next space from current position
+const spaceIndex = lexer.nextSpace();
+console.log(spaceIndex); // 4 (position of space after 'enum')
+
+// If no space found, returns code length
+lexer.load('enumStatus');
+const endIndex = lexer.nextSpace();
+console.log(endIndex); // 10 (length of code)`,
+
+ //------------------------------------------------------------------//
+
+ `import { Lexer } from '@stackpress/idea-parser';
+import { Compiler } from '@stackpress/idea-parser';
+import definitions, { data } from '@stackpress/idea-parser/definitions';
+
+const lexer = new Lexer();
+Object.keys(definitions).forEach((key) => {
+ lexer.define(key, definitions[key]);
+});
+
+// Parse a simple object
+lexer.load('{ foo "bar" bar 4.4 }');
+const objectToken = lexer.expect('Object');
+const compiled = Compiler.object(objectToken);
+console.log(compiled); // { foo: 'bar', bar: 4.4 }
+
+// Parse nested objects
+lexer.load('{ foo "bar" zoo { foo false bar null } }');
+const nestedToken = lexer.expect('Object');
+const nestedCompiled = Compiler.object(nestedToken);
+console.log(nestedCompiled.zoo.foo); // false
+console.log(nestedCompiled.zoo.bar); // null`,
+
+ //------------------------------------------------------------------//
+
+ `// Parse a simple array
+lexer.load('[ 4.4 "bar" false null ]');
+const arrayToken = lexer.expect('Array');
+const compiledArray = Compiler.array(arrayToken);
+console.log(compiledArray); // [4.4, 'bar', false, null]
+
+// Parse nested arrays
+lexer.load('[ 4.4 "bar" [ 4 true ] ]');
+const nestedArrayToken = lexer.expect('Array');
+const nestedArray = Compiler.array(nestedArrayToken);
+console.log(nestedArray[2]); // [4, true]
+
+// Parse array of objects
+lexer.load('[ { label "US" value "United States" } { label "CA" value "Canada" } ]');
+const objectArrayToken = lexer.expect('Array');
+const objectArray = Compiler.array(objectArrayToken);
+console.log(objectArray[0].label); // 'US'
+console.log(objectArray[1].value); // 'Canada'`,
+
+ //------------------------------------------------------------------//
+
+ `// Parse block comments
+lexer.load('/* some comment */');
+const noteToken = lexer.expect('note');
+console.log(noteToken.type); // '_Note'
+console.log(noteToken.value); // '/* some comment */'
+
+// Parse line comments
+lexer.load('//some comment');
+const commentToken = lexer.expect('comment');
+console.log(commentToken.type); // '_Comment'
+console.log(commentToken.value); // '//some comment'
+
+// Parse multiline block comments
+lexer.load("/*
+ some
+ // comment
+*/");
+const multilineToken = lexer.expect('note');
+console.log(multilineToken.value); // Contains newlines and nested //`,
+
+ //------------------------------------------------------------------//
+
+ `const lexer = new Lexer();
+
+// Throws: "Unknown definition unknownKey"
+try {
+ lexer.expect('unknownKey');
+} catch (error) {
+ console.log(error.message); // "Unknown definition unknownKey"
+}
+
+// Throws: "Unknown definition missingKey"
+try {
+ lexer.match('some code', 0, ['missingKey']);
+} catch (error) {
+ console.log(error.message); // "Unknown definition missingKey"
+}`,
+
+ //------------------------------------------------------------------//
+
+ `import { Exception } from '@stackpress/idea-parser';
+
+const lexer = new Lexer();
+lexer.define('String', definitions['String']);
+lexer.load('42'); // Number, not string
+
+try {
+ lexer.expect('String'); // Expecting string but found number
+} catch (error) {
+ if (error instanceof Exception) {
+ console.log(error.message); // "Unexpected 42 expecting String"
+ console.log(error.start); // Position where error occurred
+ console.log(error.end); // End position for error highlighting
+ }
+}`,
+
+ //------------------------------------------------------------------//
+
+ `import { Lexer, EnumTree } from '@stackpress/idea-parser';
+
+// AST classes configure lexers with appropriate definitions
+const lexer = new Lexer();
+EnumTree.definitions(lexer); // Adds enum-specific token definitions
+
+lexer.load('enum Status { ACTIVE "Active" INACTIVE "Inactive" }');
+
+const enumTree = new EnumTree(lexer);
+const result = enumTree.enum(); // Parse enum using configured lexer`,
+
+ //------------------------------------------------------------------//
+
+ `// Save current state for potential backtracking
+const checkpoint = lexer.clone();
+
+try {
+ // Try to parse complex structure
+ const result = parseComplexStructure(lexer);
+ return result;
+} catch (error) {
+ // Restore state and try alternative parsing
+ const restoredLexer = checkpoint;
+ return parseAlternativeStructure(restoredLexer);
+}`,
+
+ //------------------------------------------------------------------//
+
+ `// Parse different types based on lookahead
+if (lexer.next('AnyIdentifier')) {
+ const identifier = lexer.expect('AnyIdentifier');
+ if (identifier.name === 'enum') {
+ // Parse enum declaration
+ } else if (identifier.name === 'model') {
+ // Parse model declaration
+ }
+}`,
+
+ //------------------------------------------------------------------//
+ `import type { Reader } from '@stackpress/idea-parser';
+
+const customReader: Reader = (code, start, lexer) => {
+ // Check if pattern matches at current position
+ if (!code.startsWith('custom', start)) {
+ return undefined; // No match
+ }
+
+ // Calculate end position
+ const end = start + 6;
+
+ // Return token object
+ return {
+ type: 'CustomToken',
+ value: 'custom',
+ start: start,
+ end: end
+ };
+};
+
+// Register the custom reader
+lexer.define('custom', customReader);`
+];
+
+//--------------------------------------------------------------------//
+
+//styles
+//--------------------------------------------------------------------//
+
+const anchorStyles = clsx(
+ 'cursor-pointer',
+ 'hover:text-blue-700',
+ 'text-blue-500',
+);
+
+//--------------------------------------------------------------------//
+
+export function Head(props: ServerPageProps) {
+ //props
+ const { request, styles = [] } = props;
+ //hooks
+ const { _ } = useLanguage();
+ //variables
+ const title = _('Lexer');
+ const description = _(
+ 'The Lexer class implements the Parser interface and provides ' +
+ 'tokenization and parsing utilities for schema code. It manages ' +
+ 'a dictionary of token definitions and handles the parsing ' +
+ 'process by matching patterns against the input code.'
+ );
+ return (
+ <>
+ {title}
+
+
+
+
+
+
+
+
+
+
+
+ {styles.map((href, index) => (
+
+ ))}
+ >
+ )
+}
+
+export function Right() {
+ //hooks
+ const { _ } = useLanguage();
+
+ return (
+
+ );
+}
+
+export function Body() {
+ //hooks
+ const { _ } = useLanguage();
+
+ return (
+
+ {/* Lexer Section Content */}
+
+
{_('Lexer')}
+
+ The Lexer class implements the Parser interface and provides
+ tokenization and parsing utilities for schema code. It manages
+ a dictionary of token definitions and handles the parsing
+ process by matching patterns against the input code.
+
+
+ {examples[0]}
+
+
+
+ {/* Horizontal Rule */}
+
+
+ {/* Properties Section Content */}
+
+
{_('1. Properties')}
+
+
+ The following properties are available when instantiating a Lexer.
+
+
+
+
+ {_('Property')}
+ {_('Type')}
+ {_('Description')}
+
+ dictionary
+ Record‹string, Definition› {_(
+ 'Shallow copy of all token definitions'
+ )}
+ {_('The current index position in the code')}
+
+
+ index
+ number
+ {_('Current parsing position in the code')}
+
+
+
+ The following example shows how to register token
+ definitions for parsing.
+
+
+
+ {examples[2]}
+
+
+
{_('Parameters')}
+
+ {_('Parameter')}
+ {_('Type')}
+ {_('Description')}
+
+ key
+ string
+ {_('Unique identifier for the token definition')}
+
+
+ reader
+ Reader
+
+
+ Function that attempts to match and parse the token
+
+
+
+
+
+ {_('Returns')}
+
+
+ Void (modifies the lexer's internal dictionary).
+
+
+
+ The following example shows how to extract portions
+ of the source code.
+
+
+
+ {examples[10]}
+
+
+
{_('Parameters')}
+
+ {_('Parameter')}
+ {_('Type')}
+ {_('Description')}
+
+ start
+ number
+ {_('Starting position in the code')}
+
+
+ end
+ number
+ {_('Ending position in the code')}
+
+
+
+ {_('Returns')}
+
+
+ The substring of code between start and end positions.
+
+
+
+
+ {/* Finding Next Space Section Content */}
+
+
{_('2.11 Finding Next Space')}
+
+
+ The following example shows how to find the next
+ whitespace character (useful for error reporting).
+
+
+
+ {examples[11]}
+
+
+ {_('Returns')}
+
+
+ The index of the next space character, or the code
+ length if no space is found.
+
+
+
+ Token types define the Abstract Syntax Tree (AST) structures
+ used by the idea parser to represent parsed schema code.
+ These types form the foundation of the parsing system,
+ providing type-safe representations of schema elements.
+
+
+ {examples[0]}
+
+
+
+ {/* Horizontal Rule */}
+
+
+ {/* Core Token Types */}
+
+
{_('1. Core Token Types')}
+
+
+ The following types define the fundamental token
+ structures used throughout the parsing system.
+
+
+
+ {/* UnknownToken Section Content */}
+
+
{_('1.1 UnknownToken')}
+
+
+ Base token structure for unrecognized or generic
+ tokens during parsing.
+
+
+
+ {examples[1]}
+
+
+
{_('Properties')}
+
+ Property
+ Type
+ Description
+
+ type
+ string
+
+
+ Token type identifier
+
+
+
+
+ start
+ number
+
+
+ Starting character position in source code
+
+
+
+
+ end
+ number
+
+
+ Ending character position in source code
+
+
+
+
+ value
+ any
+
+
+ Parsed value of the token
+
+
+
+
+ raw
+ string
+
+
+ Raw text from source code
+
+
+
+
+
+ {_('Usage')}
+
+ Used as a fallback for tokens that don't match specific
+ patterns and as a base structure for other token types.
+
+
+
+ {/* IdentifierToken Section Content */}
+
+
{_('1.2 IdentifierToken')}
+
+ Represents identifiers such as variable names, type names,
+ and property keys.
+
+
+ {examples[2]}
+
+
+
{_('Properties')}
+
+ Property
+ Type
+ Description
+
+ type
+ 'Identifier'
+
+
+ Always 'Identifier' for identifier tokens
+
+
+
+
+ name
+ string
+
+
+ The identifier name
+
+
+
+
+ start
+ number
+
+
+ Starting character position
+
+
+
+
+ end
+ number
+
+
+ Ending character position
+
+
+
+
+
+ {_('Usage')}
+ Used throughout the parser for:
+
+
+ Represents literal values such as strings, numbers,
+ booleans, and null.
+
+
+ {examples[4]}
+
+
+
{_('Properties')}
+
+ Property
+ Type
+ Description
+
+ type
+ 'Literal'
+ Always 'Literal' for literal tokens
+
+
+ start
+ number
+ Starting character position
+
+
+ end
+ number
+ Ending character position
+
+
+ value
+ any
+ The parsed literal value
+
+
+ raw
+ string
+ Raw text representation from source
+
+
+
+ {_('Usage')}
+
+ Used for all scalar values in schema definitions:
+
+
+ Attribute parameters:
+ @field.input({ type "text" })
+
+
+
+ {_('Examples from Tests')}
+
+ The enum fixture shows an ObjectToken containing three
+ PropertyTokens for ADMIN, MANAGER, and USER enum values.
+
+
+
+ {/* ArrayToken Section Content */}
+
+
+
+ {_('Examples from Tests')}
+
+ From the enum fixture, each enum value is represented
+ as a PropertyToken with an IdentifierToken key and
+ LiteralToken value.
+
+
+
+
+ {/* Horizontal Rule */}
+
+
+ {/* Declaration Tokens Section Content*/}
+
+
{_('2. Declaration Tokens')}
+
+ The following types represent top-level declarations in
+ schema files.
+
+
+ {/* DeclarationToken Section Content */}
+
+
{_('2.1 DeclarationToken')}
+
+ Represents variable declarations for enums, props,
+ types, models, and plugins.
+
+
+ {examples[9]}
+
+
+
{_('Properties')}
+
+ Property
+ Type
+ Description
+
+ type
+ 'VariableDeclaration'
+
+
+ Always 'VariableDeclaration' for declarations
+
+
+
+
+ kind
+ string
+
+ Declaration type: 'enum', 'prop', 'type', 'model',
+ 'plugin'
+
+
+
+ mutable
+ boolean
+
+
+ Optional mutability flag (for types and models)
+
+
+
+
+ start
+ number
+
+
+ Starting character position
+
+
+
+
+ end
+ number
+
+
+ Ending character position
+
+
+
+
+ declarations
+ [DeclaratorToken]
+
+
+ Array with single declarator token
+
+
+
+
+
+ {_('Usage')}
+
+ Used by all tree parsers (EnumTree, PropTree, TypeTree,
+ ModelTree, PluginTree) to represent their respective
+ declarations. The kind property determines how
+ the Compiler processes the declaration.
+
+
+ {_('Examples from Tests')}
+
+ The enum fixture shows a complete DeclarationToken with
+ kind 'enum' containing the Roles enum definition.
+
+
+
+ {/* DeclaratorToken Section Content */}
+
+
{_('2.2 DeclaratorToken')}
+
+ Represents the declarator part of a variable declaration,
+ containing the identifier and initialization.
+
+
+ {examples[10]}
+
+
+
{_('Properties')}
+
+ Property
+ Type
+ Description
+
+ type
+ 'VariableDeclarator'
+
+
+ Always 'VariableDeclarator' for declarators
+
+
+
+
+ start
+ number
+
+
+ Starting character position
+
+
+
+
+ end
+ number
+
+
+ Ending character position
+
+
+
+
+ id
+ IdentifierToken
+
+
+ Declaration identifier (name)
+
+
+
+
+ init
+ ObjectToken
+
+
+ Initialization object containing the declaration
+ body
+
+
+
+
+
+ {_('Usage')}
+
+ Used within DeclarationTokens to separate the declaration
+ name from its body. The id contains the name
+ (e.g., "Roles", "User") and init contains the
+ definition object.
+
+
+
+ {/* ImportToken Section Content */}
+
+
{_('2.3 ImportToken')}
+
+ Represents use statements for importing other schema files.
+
+
+ {examples[11]}
+
+
+
{_('Properties')}
+
+ Property
+ Type
+ Description
+
+ type
+ 'ImportDeclaration'
+
+
+ Always 'ImportDeclaration' for imports
+
+
+
+
+ start
+ number
+
+
+ Starting character position
+
+
+
+
+ end
+ number
+
+
+ Ending character position
+
+
+
+
+ specifiers
+ []
+
+
+ Always empty array (not used for named imports)
+
+
+
+
+ source
+ LiteralToken
+
+
+ Source file path as literal token
+
+
+
+
+
+ {_('Usage')}
+
+ Used by UseTree to represent use "./path/to/file.idea"
+ statements. The Compiler extracts the source path for
+ dependency resolution.
+
+
+
+ {/* SchemaToken Section Content */}
+
+
{_('2.4 SchemaToken')}
+
+ Represents the complete parsed schema file containing all
+ declarations and imports.
+
+
+ {examples[12]}
+
+
+
{_('Properties')}
+
+ Property
+ Type
+ Description
+
+ type
+ 'Program'
+
+
+ Always 'Program' for complete schemas
+
+
+
+
+ kind
+ 'schema'
+
+
+ Always 'schema' for schema files
+
+
+
+
+ start
+ number
+
+
+ Starting character position (usually 0)
+
+
+
+
+ end
+ number
+
+
+ Ending character position
+
+
+
+
+ body
+ (DeclarationToken|ImportToken)[]
+
+
+ Array of all declarations and imports
+
+
+
+
+
+ {_('Usage')}
+
+
+ Used by SchemaTree as the root token representing the
+ entire parsed schema file. The Compiler processes the
+ body array to generate the final schema configuration.
+
+
+
+ The following types provide flexible token handling for
+ different contexts.
+
+
+ {/* Token Section Content */}
+
+
{_('3.1 Token')}
+
+ Union type for all possible token types that can be
+ returned by readers.
+
+
+ {examples[13]}
+
+
+ {_('Usage')}
+
+ Used as the return type for lexer operations and reader
+ functions. Allows handling both recognized data tokens
+ and unknown tokens.
+
+
+
+ {/* Data Token Section */}
+
+
{_('3.2 DataToken')}
+
+ Union type for tokens representing data values.
+
+
+ {examples[14]}
+
+
+ {_('Usage')}
+
+ Used throughout the Compiler for processing data values.
+ These tokens can be converted to actual JavaScript values
+ using Compiler.data().
+
+
+
+
+ {/* Horizontal Rule */}
+
+
+ {/* Parser Interface Section Content */}
+
+
{_('4. Parser Interface')}
+
+ The following types define the parser interface and reader
+ functions.
+
+
+
+ {/* Reader Function Section */}
+
+
{_('4.1 Reader')}
+
+ Function type for token readers that attempt to parse
+ specific patterns.
+
+
+ {examples[15]}
+
+
+
{_('Parameters')}
+
+ Parameter
+ Type
+ Description
+
+ code
+ string
+
+
+ Source code being parsed
+
+
+
+
+ start
+ number
+
+
+ Starting position to attempt parsing
+
+
+
+
+ lexer
+ Parser
+
+
+ Parser instance for recursive parsing
+
+
+
+
+
+ {_('Returns')}
+
+ Token object if pattern matches, undefined otherwise.
+
+
+ {_('Usage')}
+
+ Used to define token recognition patterns in the definitions
+ system. Each token type has a corresponding reader function.
+
+
+
+ {/* Token Definition Section */}
+
+
{_('4.2 Definition')}
+
+ Pairs a token key with its reader function for lexer
+ registration.
+
+
+ {examples[16]}
+
+
+
{_('Properties')}
+
+ Property
+ Type
+ Description
+
+ key
+ string
+
+
+ Unique identifier for the token type
+
+
+
+
+ reader
+ Reader
+
+
+ Function that attempts to parse the token
+
+
+
+
+
+ Usage
+
+ Used by the Lexer to register and manage token definitions.
+ The key identifies the token type, and the reader attempts
+ to parse it.
+
+
+
+ {/* Parser Interface Section */}
+
+
{_('4.3 Parser')}
+
+ Interface defining the contract for parser implementations.
+
+
+ {examples[17]}
+
+
+ Usage
+
+ Implemented by the Lexer class to provide consistent
+ parsing operations across all tree parsers.
+
+
+
+
+ {/* Horizontal Rule */}
+
+
+ {/* Reference Types Section Content */}
+
+
{_('5. Reference Types')}
+
+ The following types handle reference resolution and data
+ processing.
+
+
+ {/* UseReferences Section Content */}
+
+
{_('5.1 UseReferences')}
+
+ Type for managing prop and type references during
+ compilation.
+
+
+ {examples[18]}
+
+
+ {_('Usage')}
+
+ Used by the Compiler to resolve identifier references:
+
+
+
+ false: Return template strings like
+ ${PropName}
+
+
+ Record<string, any>: Resolve identifiers
+ to actual values
+
+
+ Union type for primitive values that can be stored in
+ schema configurations.
+
+
+ {examples[19]}
+
+
+ {_('Usage')}
+
+ Used in enum configurations and other places where only
+ primitive values are allowed.
+
+
+
+ {/* Data Section Content */}
+
+
{_('5.3 Data')}
+
+ Recursive type for nested data structures in schema
+ configurations.
+
+
+ {examples[20]}
+
+
+ {_('Usage')}
+
+ Used throughout the system for representing complex nested
+ data structures in plugin configurations, attributes, and
+ other schema elements.
+
+
+
+
+ {/* Horizontal Rule */}
+
+
+ {/* Usage Examples Section Content */}
+
+
+
+
+
+
+
+
+
+ );
+}
+
+export default function Page(props: ServerPageProps) {
+ const { data, session, request, response } = props;
+ return (
+
+
+
+ );
+}
diff --git a/packages/www/plugins/docs/views/parser/examples.tsx b/packages/www/plugins/docs/views/parser/examples.tsx
new file mode 100644
index 0000000..e248092
--- /dev/null
+++ b/packages/www/plugins/docs/views/parser/examples.tsx
@@ -0,0 +1,186 @@
+//modules
+import type {
+ ServerConfigProps,
+ ServerPageProps
+} from 'stackpress/view/client';
+import { Translate, useLanguage } from 'r22n';
+//local
+import { H1, H2, Nav, P } from '../../components/index.js';
+import Code from '../../components/Code.js';
+import Layout from '../../components/Layout.js';
+
+//code examples
+//--------------------------------------------------------------------//
+
+const completeSchemaExamples =
+`import { final } from '@stackpress/idea-parser';
+
+const schemaCode = \`
+plugin "./database-plugin" {
+ provider "postgresql"
+ url env("DATABASE_URL")
+}
+
+prop Text { type "text" }
+prop Email { type "email" format "email" }
+
+enum UserRole {
+ ADMIN "Administrator"
+ USER "Regular User"
+ GUEST "Guest User"
+}
+
+type Address {
+ street String @field.input(Text) @is.required
+ city String @field.input(Text) @is.required
+ country String @field.select
+ postal String @field.input(Text)
+}
+
+model User! {
+ id String @id @default("nanoid()")
+ email String @field.input(Email) @is.required @is.unique
+ name String @field.input(Text) @is.required
+ role UserRole @default("USER")
+ address Address?
+ active Boolean @default(true)
+ created Date @default("now()")
+ updated Date @default("updated()")
+}
+\`;
+
+const result = final(schemaCode);
+console.log(JSON.stringify(result, null, 2));`;
+
+//--------------------------------------------------------------------//
+
+const individualComponentsExample =
+`import { Compiler, EnumTree, ModelTree } from '@stackpress/idea-parser';
+
+// Parse individual enum
+const enumCode = \`enum Status { ACTIVE "Active" INACTIVE "Inactive" }\`;
+const enumAST = EnumTree.parse(enumCode);
+const [enumName, enumConfig] = Compiler.enum(enumAST);
+
+// Parse individual model
+const modelCode = \`model User { id String @id name String }\`;
+const modelAST = ModelTree.parse(modelCode);
+const [modelName, modelConfig] = Compiler.model(modelAST);`;
+
+//--------------------------------------------------------------------//
+
+export function Head(props: ServerPageProps) {
+ //props
+ const { request, styles = [] } = props;
+ //hooks
+ const { _ } = useLanguage();
+ //variables
+ const title = _('Examples');
+ const description = _(
+ 'Practical examples showing how to use the Idea Parser ' +
+ 'library for parsing schema files and working with ' +
+ 'individual components.'
+ );
+ return (
+ <>
+ {title}
+
+
+
+
+
+
+
+
+
+
+
+ {styles.map((href, index) => (
+
+ ))}
+ >
+ )
+}
+
+export function Body() {
+ //hooks
+ const { _ } = useLanguage();
+
+ return (
+
+
{_('Examples')}
+
+
+ Explore practical examples demonstrating how to use the
+ parser library for common tasks such as parsing complete
+ schema files and working with individual components.
+
+
+
+ {individualComponentsExample}
+
+
+
+ {/* Page Navigation */}
+
+
+ );
+}
+
+export default function Page(props: ServerPageProps) {
+ const { data, session, request, response } = props;
+ return (
+
+
+
+ );
+}
diff --git a/packages/www/plugins/docs/views/parser/installation.tsx b/packages/www/plugins/docs/views/parser/installation.tsx
new file mode 100644
index 0000000..2670a54
--- /dev/null
+++ b/packages/www/plugins/docs/views/parser/installation.tsx
@@ -0,0 +1,196 @@
+//modules
+import type {
+ ServerConfigProps,
+ ServerPageProps
+} from 'stackpress/view/client';
+import { useLanguage, Translate } from 'stackpress/view/client';
+//locals
+import { H1, H2, P, C, Nav } from '../../components/index.js';
+import Code from '../../components/Code.js';
+import Layout from '../../components/Layout.js';
+
+//code examples
+//--------------------------------------------------------------------//
+
+const installCommand = `npm install @stackpress/idea-parser`;
+
+//--------------------------------------------------------------------//
+
+const usageExample =
+`import { parse, final } from '@stackpress/idea-parser';
+
+// Parse a schema file into JSON (includes references)
+const schemaCode = \`
+prop Text { type "text" }
+enum Roles {
+ ADMIN "Admin"
+ USER "User"
+}
+model User {
+ id String @id
+ name String @field.input(Text)
+ role Roles
+}
+\`;
+
+// Parse with references intact
+const parsedSchema = parse(schemaCode);
+
+// Parse and clean up references (final version)
+const finalSchema = final(schemaCode);`;
+
+//--------------------------------------------------------------------//
+
+export function Head(props: ServerPageProps) {
+ //props
+ const { request, styles = [] } = props;
+ //hooks
+ const { _ } = useLanguage();
+ //variables
+ const title = _('Installation');
+ const description = _(
+ 'A TypeScript library for parsing .idea schema files into ' +
+ 'Abstract Syntax Trees (AST) and converting them to readable ' +
+ 'JSON configurations. This library is designed to help ' +
+ 'developers work with schema definitions in a structured and ' +
+ 'type-safe manner.'
+ );
+ return (
+ <>
+ {title}
+
+
+
+
+
+
+
+
+
+
+
+ {styles.map((href, index) => (
+
+ ))}
+ >
+ )
+}
+
+export function Body() {
+ //hooks
+ const { _ } = useLanguage();
+
+ return (
+
+ {/* Idea Parser Section Content */}
+
+
{_('Idea Parser')}
+
+ A TypeScript library for parsing .idea schema files into
+ Abstract Syntax Trees (AST) and converting them to readable
+ JSON configurations. This library is designed to help
+ developers work with schema definitions in a structured
+ and type-safe manner.
+
+
+
+ {/* Horizontal Rule */}
+
+
+ {/* Installation Section Content */}
+
+
+
+ This section covers advanced plugin development topics for
+ developers who need to create sophisticated code generation
+ tools. These tutorials demonstrate complex patterns and
+ integration techniques for building enterprise-grade plugins.
+
+
+
+
+ {/* API Development Plugins Section */}
+
+
{_('7.1. API Development Plugins')}
+
+
{_('7.1.1. GraphQL Schema Plugin')}
+
+
+ The
+ GraphQL Schema Plugin
+ tutorial teaches you how to create a plugin that
+ generates GraphQL type definitions and schemas from your
+ schema.
+
+
+
+
{_("What you'll learn:")}
+
+
+
+ Generate GraphQL type definitions from models and types
+
+
+
+
+ Create queries, mutations, and subscriptions
+
+
+
+
+ Support for custom scalars and directives
+
+
+
+
+ Handle relationships and nested types
+
+
+
+
+ Generate complete GraphQL schema files
+
+
+
+
+
+
+ Generated Output: GraphQL schema files with
+ type definitions, queries, and mutations
+
+
+
+
{_('7.1.2. TypeScript Interface Plugin')}
+
+
+ The
+ TypeScript Interface Plugin
+ tutorial demonstrates how to create a plugin that
+ generates TypeScript interfaces and types from your schema.
+
+
+
+
{_("What you'll learn:")}
+
+
+
+ Generate TypeScript interfaces from models and types
+
+
+
+
+ Create enums and utility types
+
+
+
+
+ Support for namespaces and modules
+
+
+
+
+ Handle optional and array types
+
+
+
+
+ Generate comprehensive type definitions
+
+
+
+
+
+
+ Generated Output: TypeScript definition files
+ with interfaces, types, and enums
+
+
+
+
{_('7.1.3. API Client Plugin')}
+
+
+ The
+ API Client Plugin
+ tutorial shows how to create a plugin that generates
+ API client libraries from your schema.
+
+
+
+
{_("What you'll learn:")}
+
+
+
+ Generate REST and GraphQL API clients
+
+
+
+
+ Support multiple authentication strategies
+
+
+
+
+ Create type-safe client methods
+
+
+
+
+ Handle request/response transformations
+
+
+
+
+ Generate both JavaScript and TypeScript clients
+
+
+
+
+
+
+ Generated Output: Complete API client
+ libraries with methods and types
+
+
+
+ Validation and testing plugins help ensure data quality and
+ application reliability by generating validation schemas and
+ test data. These plugins are essential for building robust
+ applications that can handle edge cases and maintain data
+ integrity across different environments.
+
+
+
+
{_('7.2.1. Validation Plugin')}
+
+
+ The
+ Validation Plugin
+ tutorial teaches you how to create a plugin that
+ generates Zod validation schemas from your schema.
+
+
+
+
{_("What you'll learn:")}
+
+
+
+ Generate Zod schemas from models and types
+
+
+
+
+ Create custom validators and transformations
+
+
+
+ This section provides links to comprehensive tutorials for
+ creating specific types of plugins. Each tutorial includes
+ step-by-step instructions, complete code examples, and
+ explanations of key concepts for building production-ready
+ plugins.
+
+
+
+
{_('6.1. Meta Coding With TSMorph')}
+
+
+ The
+ TSMorph Plugin Guide
+ demonstrates how to create powerful code generation
+ plugins using ts-morph, a TypeScript library that
+ provides an easier way to programmatically navigate and
+ manipulate TypeScript and JavaScript code. This guide is
+ essential for developers who need to generate complex
+ TypeScript code with proper syntax and formatting.
+
+
+
+ The
+ Markdown Documentation Plugin
+ tutorial shows how to create a plugin that generates
+ comprehensive markdown documentation from your schema.
+
+
+
+
{_("What you'll learn:")}
+
+
+
+ Parse all schema elements (models, types, enums, props)
+
+
+
+
+ Generate structured documentation with navigation
+
+
+
+
+ Include examples and cross-references
+
+
+
+
+ Support multiple documentation formats and templates
+
+
+
+
+ Create both single-file and multi-file documentation
+
+
+
+ This section outlines essential best practices for plugin
+ development, covering type safety, configuration validation,
+ file operations, and CLI integration. Following these practices
+ ensures that plugins are reliable, maintainable, and provide
+ excellent developer experiences.
+
+
+
+
{_('5.1. Type Safety')}
+
+
+ Type safety is crucial for creating reliable plugins that
+ catch errors at compile time rather than runtime. This section
+ demonstrates how to use TypeScript effectively in plugin
+ development, including proper typing for configuration objects
+ and plugin properties.
+
+
+
+ Configuration validation ensures that plugins receive valid
+ configuration options and fail early with clear error messages
+ when configuration is invalid. This approach prevents runtime
+ errors and provides better debugging experiences for plugin
+ users.
+
+
+
+ File operations in plugins should follow consistent patterns
+ for path resolution, directory creation, and error handling.
+ This section demonstrates best practices for working with files
+ and directories in a way that's compatible with the idea
+ transformer system.
+
+
+
+ CLI integration enables plugins to provide rich command-line
+ experiences by adapting behavior based on the execution context.
+ This section shows how to use CLI properties effectively and
+ create plugins that work well in both programmatic and
+ interactive environments.
+
+
+
+ Proper error handling is essential for creating robust plugins
+ that provide clear feedback when issues occur. This section
+ covers error handling strategies, validation patterns, and
+ techniques for graceful failure recovery in plugin development.
+
+
+
+
+ {/* Plugin Error Handling Section */}
+
+
{_('4.1. Plugin Error Handling')}
+
+
+ Plugin error handling demonstrates how to implement
+ comprehensive error checking and reporting in plugins. This
+ approach ensures that plugins fail gracefully with meaningful
+ error messages, helping users quickly identify and resolve
+ configuration or schema issues.
+
+
+
+ Graceful error recovery shows how plugins can implement
+ fallback mechanisms and continue operation even when primary
+ functionality fails. This approach improves plugin reliability
+ and provides better user experiences by attempting alternative
+ approaches when errors occur.
+
+
+
+ This section provides essential information for developers who
+ are new to plugin development. It covers prerequisites, basic
+ concepts, and step-by-step guidance for creating your first
+ plugin.
+
+
+
+ {/* Prerequisites Section */}
+
+
{_('8.1. Prerequisites')}
+
+ Before starting plugin development, ensure you have the
+ necessary knowledge and tools. These prerequisites will help
+ you understand the examples and successfully implement your
+ own plugins.
+
+
+
+ Before starting these tutorials, make sure you have:
+
+
+
+
+
+ Basic understanding of TypeScript/JavaScript
+
+
+
+
+ Familiarity with the idea-transformer plugin system
+
+
+
+
+ Understanding of the target technology
+ (MySQL, HTML/CSS, Markdown)
+
+
+
+ Plugin development follows consistent patterns that make it
+ easy to create new plugins once you understand the core
+ concepts. This section outlines the fundamental steps and
+ patterns used across all plugin types.
+
+
+
+ All plugins in the idea-transformer system follow a
+ similar pattern:
+
+
+
+
+
+ Import Types: Use the provided TypeScript
+ types for type safety
+
+
+
+
+ Define Configuration: Specify what
+ configuration options your plugin accepts
+
+
+
+
+ Validate Input: Check that required
+ configuration is provided
+
+
+
+
+ Process Schema: Parse the schema and
+ extract relevant information
+
+
+
+
+ Generate Output: Create the target files
+ or content
+
+
+
+
+ Handle Errors: Provide meaningful error
+ messages and graceful failure
+
+
+
+ The common plugin structure provides a template that can be
+ adapted for any type of code generation. This structure
+ ensures consistency across plugins and includes all essential
+ components for robust plugin development.
+
+
+
+ {commonPluginStructureExample}
+
+
+
+ {/* Schema Structure Section */}
+
+
{_('8.4. Schema Structure')}
+
+ Understanding the schema structure is crucial for plugin
+ development. The processed schema provides a standardized
+ format that plugins can rely on, regardless of the original
+ .idea file structure.
+
+
+
+ All plugins receive a processed schema with this structure:
+
+
+
+ {schemaStructureExample}
+
+
+
+ {/* Implementation Guidelines Section */}
+
+
{_('8.5. Implementation Guidelines')}
+
+ These implementation guidelines help ensure that your plugins
+ are reliable, maintainable, and follow established patterns.
+ Following these guidelines will make your plugins easier to
+ debug and extend.
+
+
+
+
{_('8.5.1. Type Safety')}
+
+ Type safety prevents runtime errors and provides better
+ development experiences through IDE support and compile-time
+ error checking.
+
+
+
+ Always use the provided TypeScript types:
+
+
+
+ {typeSafetyExample}
+
+
+
+
+
{_('8.5.2. Configuration Validation')}
+
+ Configuration validation ensures that plugins receive valid
+ input and fail early with clear error messages when
+ configuration is incorrect.
+
+
+
+ Validate all required configuration upfront:
+
+
+
+ {configurationValidationExample}
+
+
+
+
+
{_('8.5.3. File Operations')}
+
+ File operations should follow consistent patterns for path
+ resolution, directory creation, and error handling to ensure
+ compatibility with the idea transformer system.
+
+
+
+ Use the transformer's file loader for consistent path
+ resolution:
+
+
+
+ {fileOperationsExample}
+
+
+
+
+
{_('8.5.4. Error Handling')}
+
+ Comprehensive error handling provides better user experiences
+ and makes plugins more reliable in production environments.
+
+
+
+ Provide meaningful error messages and handle edge cases:
+
+
+
+ {errorHandlingExample}
+
+
+
+
+
{_('8.5.5. Schema Processing')}
+
+ Schema processing should handle optional elements gracefully
+ and provide meaningful defaults to ensure plugins work with
+ various schema configurations.
+
+
+
+ Handle optional schema elements gracefully:
+
+
+
+ {schemaProcessingExample}
+
+
+
+
+ {/* Usage in Schema Files Section */}
+
+
{_('8.6. Usage in Schema Files')}
+
+ This section demonstrates how to use plugins within
+ .idea schema files, showing the declarative syntax
+ for plugin configuration and how multiple plugins can work
+ together to generate comprehensive outputs.
+
+
+
+ To use any of these plugins in your schema file:
+
+
+
+ {usageInSchemaFilesExample}
+
+
+
+ {/* Next Steps Section */}
+
+
{_('8.7. Next Steps')}
+
+ After completing the getting started section, you'll be ready
+ to dive into specific tutorials and start building your own
+ plugins. These next steps will guide you toward becoming
+ proficient in plugin development.
+
+
+
+
+
+ Choose a Tutorial: Start with the tutorial
+ that matches your immediate needs
+
+
+
+
+ Follow Along: Each tutorial provides
+ step-by-step instructions with complete code examples
+
+
+
+
+ Customize: Adapt the examples to your
+ specific requirements
+
+
+
+
+ Extend: Use the patterns learned to
+ create your own custom plugins
+
+
+
+ Beyond the provided tutorials, there are many other types of
+ plugins you can create using the patterns and techniques
+ covered in this documentation:
+
+
+
+
+
+ Database Migration Generator: Create
+ migration files for various databases
+
+
+
+ Plugin configuration enables developers to customize plugin
+ behavior through schema declarations. This section covers
+ how to define configuration options in schema files, access
+ configuration within plugins, and implement flexible plugin
+ behavior based on user preferences.
+
+
+
+ Schema plugin definitions specify how plugins are declared
+ and configured within .idea schema files. This declarative
+ approach allows users to configure multiple plugins with
+ different settings while maintaining clean, readable schema
+ files.
+
+
+
+ Plugin configuration access demonstrates how plugins can
+ read and utilize configuration options provided in schema
+ files. This section shows how to access both simple and
+ nested configuration values, provide defaults, and implement
+ conditional behavior based on configuration settings.
+
+
+
+ The following documentation explains how to develop plugins
+ for .idea files. This comprehensive guide covers everything
+ from basic plugin structure to advanced development patterns,
+ providing developers with the knowledge needed to create
+ powerful code generation plugins for the idea ecosystem.
+
+
+
+ This section covers the fundamental concepts and structures
+ needed to create effective plugins for the idea ecosystem.
+ Plugins are JavaScript or TypeScript modules that process
+ schema definitions and generate various outputs like code,
+ documentation, or configuration files.
+
+
+
+
+
+ Creating a plugin involves just exporting a function like the
+ example below:
+
+
+
+ The basic plugin structure provides the foundation for all
+ idea plugins. This structure ensures consistency across
+ plugins and provides access to essential functionality like
+ schema processing, file operations, and configuration
+ management.
+
+
+
+
+ {basicPluginStructureExample}
+
+
+
{_('Properties')}
+
+
+ The PluginProps contains the following properties.
+
+
+
+
+
+ Property
+ Type
+ Description
+
+
+ config
+ PluginConfig
+
+
+ Plugin-specific configuration from the schema
+
+
+
+
+ schema
+ SchemaConfig
+
+
+ Complete processed schema configuration
+
+
+
+
+ transformer
+ Transformer<{}>
+
+
+ The transformer instance executing the plugin
+
+
+
+
+ cwd
+ string
+
+
+ Current working directory for file operations
+
+
+
+
+
+
+ {/* CLI-Aware Plugin Structure */}
+
+
{_('1.2. CLI-Aware Plugin Structure')}
+
+
+ CLI-aware plugins extend the basic plugin structure to
+ include command-line interface capabilities. These plugins
+ can interact with the terminal, access CLI-specific
+ properties, and provide enhanced user experiences through
+ interactive features and detailed logging.
+
+
+
+
+ {cliPluginExample}
+
+
+
{_('Properties')}
+
+
+ The PluginWithCLIProps contains the following properties.
+
+
+
+
+
+ Property
+ Type
+ Description
+
+
+ config
+ PluginConfig
+
+
+ Plugin-specific configuration from the schema
+
+
+
+
+ schema
+ SchemaConfig
+
+
+ Complete processed schema configuration
+
+
+
+
+ transformer
+ Transformer<{}>
+
+
+ The transformer instance executing the plugin
+
+
+
+
+ cwd
+ string
+
+
+ Current working directory for file operations
+
+
+
+
+ cli
+ Terminal
+
+
+ Terminal instance for CLI interactions
+
+
+
+
+
+
+ {/* Custom Plugin Props */}
+
+
{_('1.3. Custom Plugin Props')}
+
+
+ Custom plugin props allow developers to extend the base
+ plugin functionality with additional properties and
+ configuration options. This feature enables plugins to
+ receive custom data, maintain state, and implement
+ specialized behaviors beyond the standard plugin interface.
+
+
+
+
+
+ You can extend the base plugin props with custom properties:
+
+
+
+ This section provides practical examples of common plugin
+ implementations. These examples demonstrate real-world
+ patterns and best practices for creating plugins that
+ generate TypeScript interfaces, enums, and interactive
+ CLI tools.
+
+
+
+ The TypeScript interface generator demonstrates how to
+ create a plugin that processes schema models and types to
+ generate TypeScript interface definitions. This example
+ shows how to handle type mapping, optional properties, and
+ namespace organization.
+
+
+
+ The enum generator plugin shows how to process schema enum
+ definitions and convert them into TypeScript enum
+ declarations. This example demonstrates simple schema
+ processing and file generation patterns that can be adapted
+ for other output formats.
+
+
+
+ The CLI-interactive plugin demonstrates how to create
+ plugins that provide rich command-line experiences. This
+ example shows how to use the CLI properties for user
+ interaction, progress reporting, and adaptive behavior
+ based on the execution context.
+
+
+
+
+
+ {/* Page Navigation */}
+
+
+ );
+}
+
+export default function Page(props: ServerPageProps) {
+ const { data, session, request, response } = props;
+ return (
+
+
+
+ );
+}
diff --git a/packages/www/plugins/docs/views/specifications/schema-directives.tsx b/packages/www/plugins/docs/views/specifications/schema-directives.tsx
new file mode 100644
index 0000000..332f56b
--- /dev/null
+++ b/packages/www/plugins/docs/views/specifications/schema-directives.tsx
@@ -0,0 +1,150 @@
+//modules
+import type {
+ ServerConfigProps,
+ ServerPageProps
+} from 'stackpress/view/client';
+import { useLanguage, Translate } from 'r22n';
+import clsx from 'clsx';
+//local
+import { H1, P, Nav } from '../../components/index.js';
+import Layout from '../../components/Layout.js';
+//multiple components
+import {
+ Plugin,
+ Use
+} from '../../components/specifications/schema-directives/index.js';
+
+//styles
+//--------------------------------------------------------------------//
+
+const anchorStyles = clsx(
+ 'cursor-pointer',
+ 'hover:text-blue-700',
+ 'text-blue-500'
+);
+
+//--------------------------------------------------------------------//
+
+export function Head(props: ServerPageProps) {
+ //props
+ const { request, styles = [] } = props;
+ //hooks
+ const { _ } = useLanguage();
+ //variables
+ const title = _('Schema Directives');
+ const description = _(
+ 'Schema directives are special declarations that control how ' +
+ 'the schema is processed and what outputs are generated.'
+ );
+ return (
+ <>
+ {title}
+
+
+
+
+
+
+
+
+
+
+
+ {styles.map((href, index) => (
+
+ ))}
+ >
+ )
+}
+
+export function Right() {
+ const { _ } = useLanguage();
+ return (
+
+ );
+}
+
+export function Body() {
+ //hooks
+ const { _ } = useLanguage();
+
+ return (
+
+ {/* Schema Directives Content */}
+
+
{_('Schema Directives')}
+
+
+ Schema directives are special declarations that control
+ how the schema is processed and what outputs are generated.
+
+
+
+
+ {/* Horizontal Rule */}
+
+
+ {/* Use, Plugin Content */}
+
+ {/* Use Section */}
+
+
+ {/* Horizontal Rule */}
+
+
+ {/* Plugin Section */}
+
+
+
+ {/* Page Navigation */}
+
+
+ );
+}
+
+export default function Page(props: ServerPageProps) {
+ const { data, session, request, response } = props;
+ return (
+ }
+ >
+
+
+ );
+}
diff --git a/packages/www/plugins/docs/views/specifications/schema-elements.tsx b/packages/www/plugins/docs/views/specifications/schema-elements.tsx
new file mode 100644
index 0000000..60ad8c0
--- /dev/null
+++ b/packages/www/plugins/docs/views/specifications/schema-elements.tsx
@@ -0,0 +1,356 @@
+//modules
+import type {
+ ServerConfigProps,
+ ServerPageProps
+} from 'stackpress/view/client';
+import { useLanguage, Translate } from 'r22n';
+//locals
+import { H1, H2, P, C, H, Nav, SS } from '../../components/index.js';
+import Code from '../../components/Code.js';
+import Layout from '../../components/Layout.js';
+import { Table, Thead, Trow, Tcol } from 'frui/element/Table';
+
+//code examples
+//--------------------------------------------------------------------//
+
+const examples = [
+ `// Simple boolean attribute (sets value to true)
+@filterable
+
+// Function with single argument
+@label("Name")
+
+// Function with multiple arguments
+@is.cgt(3 "Name should be more than 3 characters")
+
+// Function with object argument
+@view.image({ width 100 height 100 })
+
+// Nested attribute names using periods
+@field.input(Email)
+@validation.required
+@ui.component("CustomInput")`,
+
+ //------------------------------------------------------------------//
+
+ `// Boolean (implicit true)
+@required
+@unique
+@filterable
+
+// String values
+@label("User Name")
+@placeholder("Enter your name")
+@description("This field is required")
+
+// Number values
+@min(0)
+@max(100)
+@precision(2)
+
+// Object values
+@validation({ required true minLength 3 })
+@ui({ component "Input" placeholder "Enter text" })
+@options({ multiple true searchable false })
+
+// Array values
+@tags(["admin" "user" "guest"])
+@options(["small" "medium" "large"])
+@toolbar(["bold" "italic" "underline"])
+
+// Mixed arguments
+@between(1 100 "Value must be between 1 and 100")
+@pattern("^[a-zA-Z]+$" "Only letters allowed")`,
+
+ //------------------------------------------------------------------//
+
+ `// Model-level attributes
+model User @table("users") @index(["email" "created"]) {
+ // Column-level attributes
+ id String @id @default("nanoid()")
+ name String @required @minLength(2)
+}
+
+// Type-level attributes
+type Address @serializable @cacheable(3600) {
+ street String @required
+ city String @required
+}`,
+
+ //------------------------------------------------------------------//
+
+ `model User {
+ name String // Required string
+ bio String? // Optional string
+ tags String[] // Array of strings
+ addresses Address[] // Array of custom types
+ metadata JSON? // Optional JSON
+}`,
+
+ //------------------------------------------------------------------//
+
+ `model User {
+ profile {
+ firstName String
+ lastName String
+ social {
+ twitter String?
+ github String?
+ }
+ }
+ settings {
+ theme String @default("light")
+ notifications Boolean @default(true)
+ }
+}`
+];
+
+//--------------------------------------------------------------------//
+
+export function Head(props: ServerPageProps) {
+ //props
+ const { request, styles = [] } = props;
+ //hooks
+ const { _ } = useLanguage();
+ //variables
+ const title = _('Schema Elements');
+ const description = _(
+ 'Schema elements are the building blocks of your application schema.'
+ );
+ return (
+ <>
+ {title}
+
+
+
+
+
+
+
+
+
+
+
+
+ {styles.map((href, index) => (
+
+ ))}
+ >
+ )
+}
+
+
+export function Body() {
+ //hooks
+ const { _ } = useLanguage();
+
+ return (
+
+
{_('Schema Elements')}
+
+ {/* Attributes Content */}
+
+
{_('Attributes (@)')}
+
+
+ Attributes provide metadata and configuration for columns,
+ types, and models. They define validation rules, UI
+ components, relationships, and behavior. Attributes can
+ be attached to any schema element and are processed by
+ plugins according to their specific needs.
+
+
+
+
+ {_('Note:')}
+
+ There are no reserved or pre-defined attributes in idea.
+ You can define any arbitrary attributes in your schema.
+ It\'s up to the plugins to recognize and process them.
+
+
+
+
{_('Attribute Syntax')}
+
+
+ Attributes always start with the at symbol (@) followed
+ by letters, numbers, and periods. They can be expressed
+ in several forms.
+
+
+
+ {examples[0]}
+
+
+
{_('Attribute Value Types')}
+
+
+ Attributes can hold different types of values:
+
+
+
+ {examples[1]}
+
+
+
{_('Attribute Scope')}
+
+
+ Attributes can be applied to different schema elements:
+
+
+
+ Columns define the individual fields within models and
+ types, specifying their data type, constraints, and behavior.
+
+
+
+
+ Types
+ Description
+ Example
+
+
+ String
+
+ Text data
+ name String
+
+
+
+ Number
+
+ Numeric data
+ age Number
+
+
+
+ Boolean
+
+ True or false values
+ active Boolean
+
+
+
+ Date
+
+ Date/time values
+ created Date
+
+
+
+ JSON
+
+ JSON Objects
+ metadata JSON
+
+
+
+ CustomType
+
+ User-defined types
+ address Address
+
+
+
+ EnumType
+
+ Enum values
+ role UserRole
+
+
+
+
{_('Optional and Array Types')}
+
+ {examples[3]}
+
+
+
{_('Nested Types')}
+
+ {examples[4]}
+
+
+
+
+
+
+ );
+}
+
+export default function Page(props: ServerPageProps) {
+ const { data, session, request, response } = props;
+ return (
+
+
+
+ );
+}
diff --git a/packages/www/plugins/docs/views/specifications/schema-structure.tsx b/packages/www/plugins/docs/views/specifications/schema-structure.tsx
new file mode 100644
index 0000000..7b5ce9f
--- /dev/null
+++ b/packages/www/plugins/docs/views/specifications/schema-structure.tsx
@@ -0,0 +1,157 @@
+//modules
+import type {
+ ServerConfigProps,
+ ServerPageProps
+} from 'stackpress/view/client';
+import { useLanguage, Translate } from 'r22n';
+//local
+import { H1, P, C, Nav } from '../../components/index.js';
+import Code from '../../components/Code.js';
+import Layout from '../../components/Layout.js';
+
+//code example
+//--------------------------------------------------------------------//
+
+const schemaExample =
+`// 1. Plugin declarations
+plugin "./plugins/generate-types.js" {
+ output "./generated/types.ts"
+}
+
+plugin "./plugins/generate-database.js" {
+ output "./database/schema.sql"
+ dialect "postgresql"
+}
+
+// 2. Use statements (imports)
+use "./shared/common-types.idea"
+use "./auth/user-types.idea"
+
+// 3. Prop definitions
+prop Email {
+ type "email"
+ validation { required true }
+}
+
+prop Text {
+ type "text"
+ validation { maxLength 255 }
+}
+
+// 4. Enum definitions
+enum UserRole {
+ ADMIN "Administrator"
+ USER "Regular User"
+}
+
+// 5. Type definitions
+type Address {
+ street String @required
+ city String @required
+ country String @default("US")
+}
+
+// 6. Model definitions
+model User! {
+ id String @id @default("nanoid()")
+ email String @unique @field.input(Email)
+ name String @field.input(Text)
+ role UserRole @default("USER")
+ address Address?
+ active Boolean @default(true)
+ created Date @default("now()")
+}`;
+
+//--------------------------------------------------------------------//
+
+export function Head(props: ServerPageProps) {
+ //props
+ const { request, styles = [] } = props;
+ //hooks
+ const { _ } = useLanguage();
+ //variables
+ const title = _('Schema Structure');
+ const description = _(
+ 'A complete .idea schema file can contain multiple elements ' +
+ 'organized in a specific structure.'
+ );
+ return (
+ <>
+ {title}
+
+
+
+
+
+
+
+
+
+
+
+ {styles.map((href, index) => (
+
+ ))}
+ >
+ )
+}
+
+export function Body() {
+ //hooks
+ const { _ } = useLanguage();
+
+ return (
+
+ {/* Schema Structure Content */}
+
+
{_('Schema Structure')}
+
+
+ A complete .idea schema file can contain multiple
+ elements organized in a specific structure:
+
+
+
+
+ {schemaExample}
+
+
+
+
+ {/* Page Navigation */}
+
+
+ );
+}
+
+export default function Page(props: ServerPageProps) {
+ const { data, session, request, response } = props;
+ return (
+
+
+
+ );
+}
diff --git a/packages/www/plugins/docs/views/specifications/syntax-overview.tsx b/packages/www/plugins/docs/views/specifications/syntax-overview.tsx
new file mode 100644
index 0000000..773370d
--- /dev/null
+++ b/packages/www/plugins/docs/views/specifications/syntax-overview.tsx
@@ -0,0 +1,278 @@
+//modules
+import type {
+ ServerConfigProps,
+ ServerPageProps
+} from 'stackpress/view/client';
+import { useLanguage, Translate } from 'r22n';
+//local
+import { H1, P, Nav, SS } from '../../components/index.js';
+import Code from '../../components/Code.js';
+import Layout from '../../components/Layout.js';
+
+//code examples
+//--------------------------------------------------------------------//
+
+const examples = [`
+// JavaScript object
+{ foo: "bar", bar: "foo" }
+
+// JavaScript array
+[ "foo", "bar" ]
+[ "foo", "bar" ]
+
+// Nested structure
+{
+ user: {
+ name: "John",
+ age: 30,
+ active: true
+ },
+ tags: ["admin", "user"]
+}`,
+
+ //------------------------------------------------------------------//
+
+ `// Object structure
+{ foo "bar" bar "foo" }
+
+// Array structure
+[ "foo" "bar" ]
+
+// Nested structure
+{
+ user {
+ name "John"
+ age 30
+ active true
+ }
+ tags ["admin" "user"]
+}`,
+
+ //------------------------------------------------------------------//
+
+ `// Strings - always use double quotes
+name "John Doe"
+description "A comprehensive user management system"
+
+// Numbers - no quotes needed
+age 30
+price 99.99
+count -5
+
+// Booleans - no quotes needed
+active true
+verified false
+
+// Arrays - space-separated values
+tags ["admin" "user" "moderator"]
+numbers [1 2 3 4 5]
+mixed ["text" 123 true]
+
+// Objects - nested key-value pairs
+profile {
+ firstName "John"
+ lastName "Doe"
+ settings {
+ theme "dark"
+ notifications true
+ }
+}`,
+
+ //------------------------------------------------------------------//
+
+ `// This is a single-line comment
+model User {
+ id String @id // Inline comment
+ name String @required
+ // Another comment
+ email String @unique
+}
+
+/*
+ Multi-line comments are also supported
+ for longer explanations
+*/`
+];
+
+//--------------------------------------------------------------------//
+
+export function Head(props: ServerPageProps) {
+ //props
+ const { request, styles = [] } = props;
+ //hooks
+ const { _ } = useLanguage();
+ //variables
+ const title = _('Syntax Overview');
+ const description = _(
+ 'The .idea file format uses a simplified syntax that eliminates ' +
+ 'the need for traditional separators like commas (,) and ' +
+ 'colons (:) found in JSON or JavaScript. The parser can ' +
+ 'logically determine separations, making the syntax cleaner ' +
+ 'and more readable.'
+ );
+ return (
+ <>
+ {title}
+
+
+
+
+
+
+
+
+
+
+
+
+ {styles.map((href, index) => (
+
+ ))}
+ >
+ )
+}
+
+export function Body() {
+ //hooks
+ const { _ } = useLanguage();
+
+ return (
+
+ {/* Syntax Overview Content */}
+
+
{_('Syntax Overview')}
+
+
+ The .idea file format uses a simplified syntax that
+ eliminates the need for traditional separators like
+ commas (,) and colons (:) found in JSON or
+ JavaScript. The parser can logically determine separations,
+ making the syntax cleaner and more readable.
+
+
+
+
+ {/* Key Syntax Rules Content */}
+
+
{_('Key Syntax Rules')}
+
+
+ {_('No Separators Required:')}
+
+ The parser intelligently determines where values begin
+ and end
+
+
+
+ {_('Double Quotes Only:')}
+
+ All strings must use double quotes (") - single quotes
+ are not supported
+
+
+
+ {_('Context Awareness:')}
+
+ The parser understands context and can differentiate
+ between keys, values, and nested structures
+
+
+
+ The API reference provides detailed documentation for all
+ components and interfaces available in the idea-transformer
+ library. This section covers the main classes and their
+ methods for schema processing and plugin execution.
+
+
+
+ The core components form the foundation of the transformation
+ system, providing the main classes and interfaces you'll
+ use to process schemas and execute plugins.
+
+
+
+ The idea-transformer library offers several key features
+ that make schema processing and code generation efficient
+ and reliable. These features work together to provide a
+ comprehensive transformation solution.
+
+
+
+ The transformer provides robust schema loading capabilities
+ that handle complex schema structures and dependencies.
+ This includes support for modular schemas and intelligent
+ merging strategies.
+
+
+
+
+
+
+ Support for both .idea and .json schema
+ files
+
+
+
+
+ Automatic dependency resolution with use directives
+
+
+
+
+ Intelligent schema merging based on mutability rules
+
+
+
+
+ Comprehensive error handling and validation
+
+
+
+ The plugin system enables extensible code generation
+ through a type-safe and flexible architecture. Plugins
+ can access the complete schema context and generate any
+ type of output.
+
+
+
+
+
+
+ Type-safe plugin development with PluginProps and
+ PluginWithCLIProps
+
+
+
+
+ Access to complete schema configuration and transformation
+ context
+
+
+
+ The CLI provides convenient command-line access for
+ integrating schema processing into build pipelines and
+ development workflows. It supports various configuration
+ options and batch processing capabilities.
+
+
+
+
+
+
+ Simple CLI for processing schemas in build pipelines
+
+
+
+
+ Configurable working directories and file extensions
+
+
+
+
+ Integration with npm scripts and build tools
+
+
+
+
+ Support for batch processing multiple schemas
+
+
+
+ A command-line interface for processing schema files and
+ executing transformations through terminal commands. The
+ Terminal class provides a comprehensive CLI interface for
+ the idea-transformer library, enabling developers to process
+ schema files and execute transformations from the command
+ line.
+
+
+
+ The Terminal class provides a command-line interface for
+ processing schema files and executing transformations. This
+ section outlines the core capabilities and features of the
+ Terminal class, which extends the base Terminal functionality
+ to provide schema-specific command-line operations.
+
+
+
+
+
+ The Terminal class (exported as Terminal) extends the base
+ Terminal class from stackpress to provide command-line
+ functionality for the idea-transformer library. It handles:
+
+
+
+ The load method creates a new Terminal instance from
+ command-line arguments and optional configuration. This is
+ the primary way to create a terminal instance for processing
+ schema files from the command line.
+
+
+
+
+
+ The following example shows how to create a new Terminal
+ instance from command-line arguments.
+
+
+
+ The properties section describes the instance variables
+ available on Terminal objects. These properties provide
+ access to configuration details and runtime information
+ needed for command-line operations.
+
+
+
+
+
+ The following properties are available when instantiating
+ a Terminal.
+
+
+
+
+
+ Property
+ Type
+ Description
+
+
+ cwd
+ string
+
+
+ Current working directory for file operations
+
+
+
+
+ extname
+ string
+
+
+ Default file extension for schema files ' +
+ '(default: \'.idea\')
+
+
+
+
+
+ The run method executes the configured terminal command and
+ processes the specified schema file. This method handles the
+ complete workflow from command parsing to schema
+ transformation execution.
+
+
+
+
+
+ The Terminal automatically sets up event handlers for
+ processing commands. The main command supported is transform.
+
+
+
+
+ {runExample}
+
+
+
{_('Command Structure')}
+
+
+ The terminal expects commands in the following format:
+
+
+
+ This section provides practical examples of how to use the
+ Terminal class in various scenarios. These examples demonstrate
+ common patterns and use cases for command-line schema processing.
+
+
+
+
{_('Basic Command Execution')}
+
+
+ Basic command execution demonstrates the fundamental workflow
+ for processing schema files through the Terminal interface.
+ This example shows the simplest way to transform a schema file
+ using command-line arguments.
+
+
+
+
+ {basicCommandExecutionExample}
+
+
+
{_('Using Short Flag Syntax')}
+
+
+ Short flag syntax provides convenient aliases for common
+ command-line options. This example shows how to use abbreviated
+ flags to make command-line usage more efficient.
+
+
+
+
+ {shortFlagExample}
+
+
+
{_('Custom Working Directory')}
+
+
+ Custom working directory configuration allows you to specify
+ where the Terminal should operate. This is useful when
+ processing schema files from different locations or when
+ integrating with build systems.
+
+
+
+
+ {customWorkingDirectoryExample}
+
+
+
{_('Custom File Extension')}
+
+
+ Custom file extension support enables the Terminal to work
+ with schema files that use non-standard extensions. This
+ flexibility allows integration with different naming
+ conventions and file organization strategies.
+
+
+
+
+ {customFileExtensionExample}
+
+
+
{_('Custom Brand/Label')}
+
+
+ Custom brand configuration allows you to customize the
+ Terminal's display name and branding. This is useful when
+ building custom CLI tools based on the idea-transformer
+ library.
+
+
+
+ This section demonstrates how to integrate the Terminal class
+ with actual command-line environments and build systems.
+ These examples show practical applications for creating CLI
+ tools and automating schema processing.
+
+
+
+
{_('Direct Command-Line Usage')}
+
+
+ Direct command-line usage shows how to invoke the Terminal
+ functionality from shell commands. This section provides
+ examples of the actual command syntax and available options.
+
+
+
+
+ {directCommandLineExample}
+
+
+
{_('CLI Script Example')}
+
+
+ CLI script examples demonstrate how to create executable
+ scripts that use the Terminal class. This pattern is useful
+ for creating standalone CLI tools and integrating with package
+ managers.
+
+
+
+
+ {cliScriptExample}
+
+
+
{_('Package.json Integration')}
+
+
+ Package.json integration shows how to configure npm scripts
+ and binary commands using the Terminal class. This enables
+ seamless integration with Node.js project workflows and package
+ distribution.
+
+
+
+ This section explains the default behavior and conventions
+ used by the Terminal class. Understanding these defaults helps
+ developers predict how the Terminal will behave in different
+ scenarios and configure it appropriately.
+
+
+
+
{_('File Path Resolution')}
+
+
+ File path resolution describes how the Terminal determines
+ which schema file to process when no explicit path is provided.
+ This automatic resolution simplifies common use cases while
+ maintaining flexibility.
+
+
+
+
+
+ When no input file is specified, the terminal uses a default
+ path:
+
+
+
+
+ {defaultPathExample}
+
+
+
{_('Flag Processing')}
+
+
+ Flag processing explains how the Terminal parses and
+ prioritizes command-line flags. Understanding this order
+ of precedence helps developers use the most appropriate
+ flag syntax for their needs.
+
+
+
+
+
+ The terminal processes the following flags in order of
+ preference:
+
+
+
+ This section covers common error conditions that can occur
+ when using the Terminal class. Understanding these error
+ scenarios helps developers implement proper error handling
+ and provide better user experiences.
+
+
+
+
{_('Missing Schema File')}
+
+
+ Missing schema file errors occur when the specified schema
+ file doesn't exist or isn't accessible. This section shows
+ how these errors are reported and how to handle them
+ appropriately in CLI applications.
+
+
+
+
+ {missingSchemaFileExample}
+
+
+
{_('Invalid Command')}
+
+
+ Invalid command errors occur when unsupported commands are
+ passed to the Terminal. This section explains how the
+ Terminal handles unknown commands and provides guidance
+ for error recovery.
+
+
+
+
+ {invalidCommandExample}
+
+
+
{_('Plugin Errors')}
+
+
+ Plugin errors can occur during the transformation process
+ when plugins fail to execute properly. This section covers
+ how to handle and debug plugin-related issues in CLI
+ environments.
+
+
+
+ This section covers advanced patterns and techniques for
+ using the Terminal class in complex scenarios. These
+ examples demonstrate sophisticated use cases and integration
+ patterns for power users.
+
+
+
+
{_('Custom Event Handlers')}
+
+
+ Custom event handlers allow you to extend the Terminal's
+ functionality with additional commands and behaviors. This
+ pattern enables building specialized CLI tools with custom
+ functionality.
+
+
+
+
+ {customEventHandlersExample}
+
+
+
{_('Programmatic CLI Building')}
+
+
+ Programmatic CLI building demonstrates how to construct
+ command-line arguments dynamically in code. This approach is
+ useful for building tools that generate CLI commands based on
+ configuration or user input.
+
+
+
+
+ {programmaticCLIExample}
+
+
+
{_('Batch Processing')}
+
+
+ Batch processing shows how to use the Terminal class to
+ process multiple schema files in sequence. This pattern is
+ essential for build systems and automation tools that need to
+ handle multiple schemas.
+
+
+
+
+ {batchProcessingExample}
+
+
+
{_('Environment-Based Configuration')}
+
+
+ Environment-based configuration demonstrates how to use
+ environment variables to configure Terminal behavior. This
+ approach enables flexible deployment and configuration
+ management across different environments.
+
+
+
+ This section demonstrates how to integrate the Terminal class
+ with popular build tools and development workflows. These
+ examples show practical applications for automating schema
+ processing in development and deployment pipelines.
+
+
+
+
{_('Webpack Plugin')}
+
+
+ Webpack plugin integration shows how to incorporate schema
+ transformation into Webpack build processes. This enables
+ automatic schema processing as part of the application build
+ pipeline.
+
+
+
+
+ {webpackPluginExample}
+
+
+
{_('Gulp Task')}
+
+
+ Gulp task integration demonstrates how to create Gulp
+ tasks that use the Terminal class for schema processing.
+ This pattern is useful for projects that use Gulp as their
+ primary build tool.
+
+
+
+
+ {gulpTaskExample}
+
+
+
{_('NPM Scripts')}
+
+
+ NPM scripts integration shows how to configure package.json
+ scripts that use the Terminal class. This approach enables
+ easy schema processing through standard npm commands and
+ supports development workflows.
+
+
+
+ This section covers testing strategies and patterns for
+ applications that use the Terminal class. These examples
+ demonstrate how to write effective tests for CLI functionality
+ and ensure reliable schema processing.
+
+
+
+
{_('Unit Testing')}
+
+
+ Unit testing examples show how to test Terminal functionality
+ in isolation. These tests verify that the Terminal class
+ behaves correctly with different command-line arguments
+ and configuration options.
+
+
+
+
+ {unitTestingExample}
+
+
+
{_('Integration Testing')}
+
+
+ Integration testing demonstrates how to test the complete
+ workflow from command-line input to generated output files.
+ These tests ensure that the entire transformation pipeline
+ works correctly in realistic scenarios.
+
+
+
+ This section outlines recommended approaches for using the
+ Terminal class effectively. Following these practices helps
+ ensure reliable, maintainable, and user-friendly CLI
+ applications.
+
+
+
+
{_('Error Handling')}
+
+
+ Error handling best practices ensure that CLI applications
+ provide clear feedback when issues occur. This section
+ demonstrates patterns for implementing robust error handling
+ and user-friendly error messages.
+
+
+
+
+ {errorHandlingBestPracticeExample}
+
+
+
{_('Configuration Management')}
+
+
+ Configuration management best practices help maintain clean,
+ reusable configuration patterns. This section provides
+ guidance on organizing configuration options and providing
+ sensible defaults.
+
+
+
+
+ {configurationManagementExample}
+
+
+
{_('Logging and Debugging')}
+
+
+ Logging and debugging practices help developers troubleshoot
+ issues and understand Terminal behavior. This section
+ demonstrates effective logging strategies and debugging
+ techniques for CLI applications.
+
+
+
+ A class for loading, processing, and transforming schema
+ files with plugin support and schema merging capabilities.
+ The Transformer class serves as the core component of the
+ idea-transformer library, providing comprehensive functionality
+ for schema processing, plugin execution, and file management.
+
+
+
+ The Transformer class provides a comprehensive solution for
+ processing schema files and executing transformations. This
+ section outlines the core capabilities and responsibilities of
+ the Transformer class within the idea-transformer ecosystem.
+
+
+
+
+
+ The Transformer class is the core component of the
+ idea-transformer library. It handles:
+
+
+
+ The load method creates a new Transformer instance configured
+ with the specified input file and options. This is the primary
+ way to create a transformer and begin working with schema files.
+
+
+
+
+
+ The following example shows how to create a new Transformer
+ instance.
+
+
+
+
+ {loadExample}
+
+
+
{_('Parameters')}
+
+
+
+ Parameter
+ Type
+ Description
+
+
+ input
+ string
+
+
+ Path to the schema file to load
+
+
+
+
+ options
+ LoaderOptions
+
+
+ Optional configuration for the file loader
+
+
+
+
+
+
{_('Returns')}
+
+
+ A promise that resolves to a new Transformer instance
+ configured with the specified input file and options.
+
+
+
+ The properties section describes the instance variables
+ available on Transformer objects. These properties provide
+ access to the underlying file system operations and
+ configuration details needed for schema processing.
+
+
+
+
+
+ The following properties are available when instantiating
+ a Transformer.
+
+
+
+
+
+ Property
+ Type
+ Description
+
+
+ loader
+ FileLoader
+
+
+ File system loader for handling file operations
+
+
+
+
+ input
+ string
+
+
+ Absolute path to the input schema file
+
+
+
+
+
+ The methods section covers the instance methods available
+ on Transformer objects. These methods provide the core
+ functionality for loading schema configurations, processing
+ dependencies, and executing plugin transformations.
+
+
+
+
{_('Loading Schema Configuration')}
+
+
+ The schema method loads and processes the complete schema
+ configuration, including all dependencies and imports. This
+ method handles the complex process of merging multiple
+ schema files and resolving all references.
+
+
+
+
+
+ The following example shows how to load and process the
+ schema configuration.
+
+
+
+
+ {schemaExample}
+
+
+
{_('Returns')}
+
+
+ A promise that resolves to a SchemaConfig object containing
+ all processed schema definitions.
+
+
+
+
{_('Features')}
+
+
+
+ File Format Support: Automatically detects and
+ handles both .idea and .json schema files
+
+
+
+
+ Dependency Resolution: Processes use directives
+ to import and merge external schema files
+
+
+
+
+ Schema Merging: Intelligently merges child schemas
+ into parent schemas based on mutability rules
+
+
+
+
+ Caching: Caches the processed schema to avoid
+ redundant processing
+
+
+
+
+
{_('Schema Merging Rules')}
+
+
+ When processing use directives, the transformer applies
+ these merging rules:
+
+
+
+
+
+ Props and Enums:
+
+ Simple merge where parent takes precedence
+
+
+
+ Types and Models:
+
+
+
+ If parent doesn't exist or is immutable: child is added
+
+
+
+
+ If parent is mutable: attributes and columns are merged
+
+
+
+
+ Child columns are prepended to parent columns
+
+
+
+
+ Parent attributes take precedence over child attributes
+
+
+
+
+
+
+
{_('Transforming with Plugins')}
+
+
+ The transform method executes all plugins defined in the
+ schema configuration. This method coordinates the plugin
+ execution process, providing each plugin with the necessary
+ context and handling any errors that occur during
+ transformation.
+
+
+
+
+
+ The following example shows how to execute all plugins
+ defined in the schema.
+
+
+
+
+ {transformExample}
+
+
+
{_('Parameters')}
+
+
+
+ Parameter
+ Type
+ Description
+
+
+ extras
+ T
+
+
+ Optional additional context to pass to plugins
+
+
+
+
+
+
{_('Returns')}
+
+
+ A promise that resolves when all plugins have been executed.
+
+
+
+
{_('Plugin Execution Process')}
+
+
+
+ Validation: Ensures plugins are defined in the
+ schema
+
+
+
+
+ Module Resolution: Resolves plugin file paths
+ relative to the schema file
+
+
+
+ This section provides practical examples of how to use the
+ Transformer class in various scenarios. These examples
+ demonstrate common patterns and best practices for working
+ with schema files, plugins, and transformations.
+
+
+
+
{_('Basic Schema Loading')}
+
+
+ Basic schema loading demonstrates the fundamental workflow
+ for loading and accessing schema configurations. This
+ example shows how to create a transformer instance and
+ retrieve different parts of the processed schema.
+
+
+
+
+ {basicSchemaLoadingExample}
+
+
+
{_('Working with Multiple Schema Files')}
+
+
+ Working with multiple schema files shows how the Transformer
+ handles complex schema hierarchies with imports and
+ dependencies. This example demonstrates how the use
+ directive enables modular schema organization.
+
+
+
+
+ {multipleSchemaFilesExample}
+
+
+
{_('Plugin Development and Execution')}
+
+
+ Plugin development and execution demonstrates how to create
+ and use plugins with the Transformer. This example shows
+ both the schema configuration and plugin implementation,
+ illustrating the complete plugin workflow.
+
+
+
+
+ {pluginDevelopmentExample}
+
+
+
{_('Error Handling')}
+
+
+ Error handling examples show how to properly catch and
+ handle different types of errors that can occur during
+ schema processing and transformation. This includes both
+ expected errors from the idea-parser and unexpected
+ runtime errors.
+
+
+
+
+ {errorHandlingExample}
+
+
+
{_('Custom File System')}
+
+
+ Custom file system usage demonstrates how to configure the
+ Transformer to work with different file system
+ implementations. This is useful for testing, custom
+ storage backends, or specialized deployment scenarios.
+
+
+
+ This section covers common error conditions that can occur
+ when using the Transformer class. Understanding these
+ scenarios helps developers implement proper error handling
+ and debugging strategies.
+
+
+
+
{_('File Not Found')}
+
+
+ File not found errors occur when the specified schema file
+ doesn't exist or isn't accessible. This section shows how
+ these errors are reported and how to handle them
+ appropriately.
+
+
+
+
+ {fileNotFoundExample}
+
+
+
{_('No Plugins Defined')}
+
+
+ No plugins defined errors occur when attempting to execute
+ transformations on schemas that don't have any plugin
+ configurations. This section explains when this error
+ occurs and how to handle it.
+
+
+
+
+ {noPluginsExample}
+
+
+
{_('Invalid Plugin Module')}
+
+
+ Invalid plugin module scenarios occur when plugin files
+ exist but don't export the expected function interface.
+ This section covers how the Transformer handles these
+ situations and what developers should expect.
+
+
+
+ This section outlines recommended approaches for using the
+ Transformer class effectively. Following these practices
+ helps ensure reliable, maintainable, and efficient schema
+ processing workflows.
+
+
+
+
{_('Schema Organization')}
+
+
+ Schema organization best practices help maintain clean,
+ modular, and reusable schema files. This section provides
+ guidance on structuring schema hierarchies and managing
+ dependencies effectively.
+
+
+
+
+ {schemaOrganizationExample}
+
+
+
{_('Plugin Development')}
+
+
+ Plugin development best practices ensure that plugins are
+ robust, reliable, and integrate well with the Transformer
+ ecosystem. This section covers validation, error handling,
+ and proper use of the plugin context.
+
+
+
+ This section demonstrates how to integrate the Transformer
+ class with other development tools and workflows. These
+ examples show practical applications in build systems,
+ testing frameworks, and development environments.
+
+
+
+
{_('Build Systems')}
+
+
+ Build system integration shows how to incorporate schema
+ transformation into automated build processes. This
+ enables continuous generation of code, documentation,
+ and other artifacts from schema definitions.
+
+
+
+
+ {buildSystemIntegrationExample}
+
+
+
{_('Testing')}
+
+
+ Testing integration demonstrates how to write tests for
+ schema transformations and validate that schemas are
+ processed correctly. This is essential for maintaining
+ schema quality and catching regressions.
+
+
+
+ The idea-transformer follows a clear architectural pattern
+ that separates concerns between schema loading, processing,
+ and output generation. This design enables flexible plugin
+ development and maintainable code generation workflows.
+
+
+
+ Following best practices ensures maintainable, scalable, and
+ reliable schema processing workflows. These guidelines help you
+ avoid common pitfalls and optimize your development experience.
+
+
+
+ Organize your schemas for maintainability and clarity to
+ support team collaboration and long-term project success.
+ Proper organization makes schemas easier to understand
+ and modify.
+
+
+
+
+
+ {_('Use ')} {_('use')}
+ {_(' directives to split large schemas into manageable files')}
+
+
+ {_('Organize shared types and enums in separate files')}
+
+
+ {_('Follow consistent naming conventions across schemas')}
+
+
+ {_('Document complex relationships and business rules')}
+
+
+ Follow these guidelines when developing plugins to ensure
+ reliability, maintainability, and type safety. Good plugin
+ development practices lead to more robust code generation.
+
+
+
+
+
+ {_('Always validate plugin configuration')}
+
+
+ {_('Use TypeScript for type safety')}
+
+
+ {_('Handle errors gracefully with meaningful messages')}
+
+
+ {_('Use the transformer\'s file loader for consistent path ' +
+ 'resolution')}
+
+
+ Integrate schema processing effectively into your
+ workflow to maximize productivity and maintain consistency
+ across environments. Proper build integration ensures
+ reliable code generation.
+
+
+
+
+
+ {_('Add schema generation to your build process')}
+
+
+ {_('Use watch mode during development')}
+
+
+ {_('Version control generated files when appropriate')}
+
+
+ {_('Document the generation process for team members')}
+
+
+
+
+ {/* Page Navigation */}
+
+
+ );
+}
+
+export default function Page(props: ServerPageProps) {
+ const { data, session, request, response } = props;
+ return (
+
+
+
+ );
+}
\ No newline at end of file
diff --git a/packages/www/plugins/docs/views/transformers/common-use-cases.tsx b/packages/www/plugins/docs/views/transformers/common-use-cases.tsx
new file mode 100644
index 0000000..5ece968
--- /dev/null
+++ b/packages/www/plugins/docs/views/transformers/common-use-cases.tsx
@@ -0,0 +1,213 @@
+//modules
+import type {
+ ServerConfigProps,
+ ServerPageProps
+} from 'stackpress/view/client';
+import { useLanguage, Translate } from 'r22n';
+//local
+import { H1, P, C, Nav } from '../../components/index.js';
+import Layout from '../../components/Layout.js';
+
+export function Head(props: ServerPageProps) {
+ //props
+ const { request, styles = [] } = props;
+ //hooks
+ const { _ } = useLanguage();
+ //variables
+ const title = _('Common Use Cases');
+ const description = _(
+ 'Various use cases for code generation and schema processing with ' +
+ 'the idea-transformer library'
+ );
+ return (
+ <>
+ {title}
+
+
+
+
+
+
+
+
+
+
+
+ {styles.map((href, index) => (
+
+ ))}
+ >
+ )
+}
+
+export function Body() {
+ //hooks
+ const { _ } = useLanguage();
+
+ return (
+
+ {/* Common Use Cases Section Content */}
+
+
{_('Common Use Cases')}
+
+
+ The idea-transformer library supports a wide variety of
+ use cases for code generation and schema processing.
+ These use cases demonstrate the flexibility and power
+ of the transformation system.
+
+
+
+ Generate various code artifacts from your schema
+ definitions to maintain consistency across your
+ application. This use case covers the most common
+ code generation scenarios.
+
+
+
+
+
+ {_('Generate TypeScript interfaces from schema models')}
+
+
+ {_('Create enum definitions from schema enums')}
+
+
+ {_('Build API client libraries from schema definitions')}
+
+
+ Create comprehensive documentation from your schemas to
+ improve developer experience and API usability. This use
+ case focuses on generating human-readable documentation.
+
+
+
+ Build validation systems from your schema definitions to
+ ensure data integrity across your application. This use
+ case covers various validation library integrations.
+
+
+
+ Integrate schema processing into your build pipeline for
+ automated code generation and consistent development work
+ flows. This use case covers various build system integrations.
+
+
+
+
+
+ {_('Integrate with webpack, rollup, or other bundlers')}
+
+
+ {_('Add to npm scripts for automated generation')}
+
+
+ {_('Use in CI/CD pipelines for consistent builds')}
+
+
+ {_('Create watch mode for development workflows')}
+
+
+ The idea-transformer library provides comprehensive error
+ handling to help you identify and resolve issues during
+ schema processing. This section covers error types and
+ handling strategies.
+
+
+
+
+
+ The library provides comprehensive error handling with
+ detailed error messages:
+
+
+
+ This section provides practical examples of using the
+ idea-transformer library for common code generation tasks.
+ These examples demonstrate real-world usage patterns and
+ best practices.
+
+
+
+ This example shows how to create a plugin that generates
+ TypeScript interfaces from schema models. The example includes
+ both the schema definition and the plugin implementation.
+
+
+
+ This example demonstrates how to integrate the idea-transformer
+ CLI into your npm scripts for automated code generation during
+ the build process.
+
+
+
+ The idea-transformer library provides a complete solution for
+ processing schema files and generating code through a flexible
+ plugin system. This library serves as the core transformation
+ engine that bridges schema definitions with code generation.
+
+
+
+
+
+ The idea-transformer library provides a complete solution for:
+
+
+
+
+ {/* Horizontal Rule */}
+
+
+ {/* Features List Section Content */}
+
+
+
+ {_('Schema Processing:')}
+
+ Load and parse .idea schema files with support for
+ 'imports and merging
+
+
+
+ {_('Plugin System:')}
+
+ Execute transformation plugins that generate code,
+ documentation, or other outputs
+
+
+
+ {_('CLI Integration:')}
+
+ Command-line interface for processing schemas in
+ build pipelines
+
+
+
+ {_('Type Safety:')}
+
+ Full TypeScript support with comprehensive type
+ definitions
+
+
+
+
+
+ {/* Quick Start Section Content */}
+
+
{_('Quick Start')}
+
+
+ Get started with the idea-transformer library in just a few
+ steps. This section shows you how to install the library and
+ perform basic schema transformation operations.
+
+
+
+ This section demonstrates common usage patterns for the
+ idea-transformer library. These patterns show how to integrate
+ the transformer into different development workflows and use
+ cases.
+
+
+
+ The most common usage pattern involves loading a schema file
+ and executing all configured plugins. This pattern is suitable
+ for most build processes and automated workflows.
+
+
+
+ The command-line interface provides a simple way to process
+ schemas from build scripts or CI/CD pipelines. This pattern is
+ ideal for integrating schema processing into existing build
+ workflows.
+
+
+
+ Creating custom plugins allows you to extend the transformer
+ with domain-specific code generation. This pattern shows the
+ basic structure for developing type-safe plugins.
+
+