--- URL: "atscript.moost.org/" LLMS_URL: "atscript.moost.org/index.md" layout: "home" hero: name: "Atscript" text: "Universal Type & Metadata Language" tagline: "Define types once, generate code for any programming language*" image: src: "/logo.svg" alt: "Atscript" actions: - theme: "brand" text: "Get Started" link: "/guide/installation" - theme: "alt" text: "View on GitHub" link: "https://github.com/moostjs/atscript" features: - icon: "" title: "Single Source of Truth" details: "Define types, validation, database schemas, and UI metadata in one place - no more scattered definitions across your codebase" - icon: "" title: "Everything is an Annotation" details: "Attach any metadata to your types - from validation rules to database indexes to UI labels - all accessible at runtime" - icon: "" title: "Semantic Types" details: "'string.email', 'number.positive', 'mongo.objectId' - types that carry meaning and automatic validation" - icon: "" title: "Generate Everything" details: "From one .as file get TypeScript types, runtime validators, database schemas with indexes, and JSON Schema" - icon: "" title: "Runtime Metadata Access" details: "All annotations are preserved and accessible at runtime for dynamic UI generation, validation, and more" - icon: "" title: "Extensible by Design" details: "Add custom annotations, create semantic types, write plugins - make Atscript work for your domain" --- ::: info \* Language Support Currently, TypeScript/JavaScript code generation is supported. We welcome contributors to write plugins for other languages! ::: --- URL: "atscript.moost.org/advanced" LLMS_URL: "atscript.moost.org/advanced.md" --- --- URL: "atscript.moost.org/advanced/ast-manipulation" LLMS_URL: "atscript.moost.org/advanced/ast-manipulation.md" --- --- URL: "atscript.moost.org/advanced/best-practices" LLMS_URL: "atscript.moost.org/advanced/best-practices.md" --- --- URL: "atscript.moost.org/advanced/custom-annotations" LLMS_URL: "atscript.moost.org/advanced/custom-annotations.md" --- --- URL: "atscript.moost.org/advanced/migration-guide" LLMS_URL: "atscript.moost.org/advanced/migration-guide.md" --- --- URL: "atscript.moost.org/advanced/performance" LLMS_URL: "atscript.moost.org/advanced/performance.md" --- --- URL: "atscript.moost.org/advanced/plugin-development" LLMS_URL: "atscript.moost.org/advanced/plugin-development.md" --- --- URL: "atscript.moost.org/advanced/type-extensions" LLMS_URL: "atscript.moost.org/advanced/type-extensions.md" --- --- URL: "atscript.moost.org/api" LLMS_URL: "atscript.moost.org/api.md" --- --- URL: "atscript.moost.org/api/annotations" LLMS_URL: "atscript.moost.org/api/annotations.md" --- --- URL: "atscript.moost.org/api/core" LLMS_URL: "atscript.moost.org/api/core.md" --- --- URL: "atscript.moost.org/api/mongo" LLMS_URL: "atscript.moost.org/api/mongo.md" --- --- URL: "atscript.moost.org/api/types" LLMS_URL: "atscript.moost.org/api/types.md" --- --- URL: "atscript.moost.org/api/typescript" LLMS_URL: "atscript.moost.org/api/typescript.md" --- --- URL: "atscript.moost.org/concepts/annotation-system" LLMS_URL: "atscript.moost.org/concepts/annotation-system.md" --- --- URL: "atscript.moost.org/concepts/architecture" LLMS_URL: "atscript.moost.org/concepts/architecture.md" --- --- URL: "atscript.moost.org/concepts/code-generation" LLMS_URL: "atscript.moost.org/concepts/code-generation.md" --- --- URL: "atscript.moost.org/concepts/parser-ast" LLMS_URL: "atscript.moost.org/concepts/parser-ast.md" --- --- URL: "atscript.moost.org/concepts/philosophy" LLMS_URL: "atscript.moost.org/concepts/philosophy.md" --- --- URL: "atscript.moost.org/concepts/plugin-system" LLMS_URL: "atscript.moost.org/concepts/plugin-system.md" --- --- URL: "atscript.moost.org/concepts/type-system" LLMS_URL: "atscript.moost.org/concepts/type-system.md" --- --- URL: "atscript.moost.org/concepts/what-is-atscript" LLMS_URL: "atscript.moost.org/concepts/what-is-atscript.md" --- --- URL: "atscript.moost.org/examples" LLMS_URL: "atscript.moost.org/examples.md" --- --- URL: "atscript.moost.org/examples/basic-usage" LLMS_URL: "atscript.moost.org/examples/basic-usage.md" --- --- URL: "atscript.moost.org/examples/custom-plugin" LLMS_URL: "atscript.moost.org/examples/custom-plugin.md" --- --- URL: "atscript.moost.org/examples/full-stack-app" LLMS_URL: "atscript.moost.org/examples/full-stack-app.md" --- --- URL: "atscript.moost.org/examples/microservices" LLMS_URL: "atscript.moost.org/examples/microservices.md" --- --- URL: "atscript.moost.org/examples/mongodb-models" LLMS_URL: "atscript.moost.org/examples/mongodb-models.md" --- --- URL: "atscript.moost.org/examples/validation" LLMS_URL: "atscript.moost.org/examples/validation.md" --- --- URL: "atscript.moost.org/guide/annotations" LLMS_URL: "atscript.moost.org/guide/annotations.md" --- # Annotations Annotations are metadata declarations that provide additional information about types, interfaces, and properties. ## Purpose Annotations serve multiple purposes: - **UI metadata** - Labels, placeholders, descriptions for form generation - **Validation constraints** - Min/max values, patterns, length restrictions - **Database metadata** - Collection names, indexes, field strategies - **Documentation** - Descriptions and multi-line documentation - **Custom metadata** - Any domain-specific information ## Where to Apply Annotations can be applied anywhere: ```atscript @meta.description 'User entity' // Interface annotation export interface User { @meta.id // Property annotation id: string } @expect.minLength 3 // Type annotation export type Username = string ``` ## Annotation Inheritance ### Type to Property When a property uses a type with annotations, annotations merge with property having priority: ```atscript @expect.minLength 3 @expect.maxLength 20 export type Username = string export interface User { @expect.maxLength 15 // Overrides type's maxLength username: Username // Inherits minLength: 3, gets maxLength: 15 } ``` ### Property References When a property references another property, annotations merge in order: 1. Final type annotations 2. Referenced property annotations 3. Current property annotations (highest priority) ## Annotation Syntax ```atscript @meta.label 'User Name' // With argument @meta.sensitive // Flag (no argument) @expect.pattern "^[A-Z]", "i" // Multiple arguments @meta.documentation 'Line 1' // Can be repeated @meta.documentation 'Line 2' ``` Arguments can be optional. Annotations without arguments are flag annotations. ## Core Annotations Atscript provides common-purpose annotations: ### Meta Annotations (@meta.*) - `@meta.label 'text'` - Human-readable label - `@meta.id` or `@meta.id 'name'` - Marks identifier field - `@meta.description 'text'` - Field description - `@meta.documentation 'text'` - Multi-line docs (repeatable) - `@meta.placeholder 'text'` - UI placeholder text - `@meta.sensitive` - Marks sensitive data - `@meta.readonly` - Read-only field - `@meta.isKey` - Key field in arrays for lookups ### Validation Annotations (@expect.*) - `@expect.minLength 5` - Minimum string/array length - `@expect.maxLength 100` - Maximum string/array length - `@expect.min 0` - Minimum number value - `@expect.max 100` - Maximum number value - `@expect.int` - Must be integer - `@expect.pattern "regex", "flags", "message"` - Pattern validation (repeatable) ## Custom Annotations ### Unknown Annotations Support any user-specified annotations by setting in config: ```javascript // atscript.config.js export default { unknownAnnotation: 'allow' // or 'warn', 'error' (default) } ``` ### Defining Custom Annotations Add custom annotations with IntelliSense support: ```javascript // atscript.config.js import { defineConfig, AnnotationSpec } from '@atscript/core' export default defineConfig({ annotations: { ui: { hidden: new AnnotationSpec({ description: 'Hide field in UI', nodeType: ['prop'] }), column: new AnnotationSpec({ description: 'Table column width', argument: { name: 'width', type: 'number' } }) } } }) ``` Use in `.as` files: ```atscript export interface User { @ui.hidden internalId: string @ui.column 200 name: string } ``` Plugins can also provide custom annotations through their configuration. ## Next Steps - [Configuration](/guide/configuration) - Configure Atscript - [Build Setup](/guide/build-setup) - Integrate with build tools --- URL: "atscript.moost.org/guide/build-setup" LLMS_URL: "atscript.moost.org/guide/build-setup.md" --- # Build Setup Integrate Atscript into your build process using `unplugin-atscript`. This plugin automatically compiles `.as` files during the build process using your [configuration file](/guide/configuration). ## Installation ```bash npm install -D unplugin-atscript ``` ## Bundler Integration `unplugin-atscript` supports multiple build tools. The plugin automatically reads your `atscript.config.js` file and applies all configured plugins and settings. ### Vite ```javascript // vite.config.js import { defineConfig } from 'vite' import atscript from 'unplugin-atscript' export default defineConfig({ plugins: [atscript.vite()], }) ``` ### Rollup ```javascript // rollup.config.js import atscript from 'unplugin-atscript' export default { plugins: [atscript.rollup()], } ``` ### esbuild ```javascript // build.js import { build } from 'esbuild' import atscript from 'unplugin-atscript' build({ plugins: [atscript.esbuild()], entryPoints: ['src/index.ts'], bundle: true, outdir: 'dist', }) ``` ### Rolldown ```javascript // rolldown.config.js import atscript from 'unplugin-atscript' export default { plugins: [atscript.rolldown()], } ``` ## How It Works 1. **Config Discovery**: The plugin finds your `atscript.config.js` by searching upward from each `.as` file location 2. **Plugin Execution**: Runs all plugins defined in your configuration 3. **File Generation**: Generates output based on what the bundler needs (ignores `format` setting) 4. **Import Resolution**: Allows importing `.as` files directly in your TypeScript/JavaScript code ## Development vs Production The plugin works seamlessly in both development and production: - **Development**: Compiles on-demand with hot module replacement - **Production**: Pre-compiles during build for optimal performance ## Next Steps - [Quick Start](/guide/quick-start) - Review complete setup - [Interfaces & Types](/guide/interfaces-types) - Start building with Atscript --- URL: "atscript.moost.org/guide/configuration" LLMS_URL: "atscript.moost.org/guide/configuration.md" --- # Configuration Atscript uses a configuration file to control parsing, validation, and code generation. This configuration is automatically picked up by: - **VSCode extension** - For enhanced IntelliSense and real-time validation - **Build tools** - When using `unplugin-atscript` with Vite, Rollup, Rolldown, etc. - **CLI** - When running `asc` commands ## Configuration File Create `atscript.config.js` in your project root. Supported formats: - `atscript.config.js` - CommonJS - `atscript.config.mjs` - ESM module - `atscript.config.ts` - TypeScript (requires tsx/ts-node) - `atscript.config.mts` - TypeScript ESM ## Basic Example ```javascript // atscript.config.js import { defineConfig } from '@atscript/core' import ts from '@atscript/typescript' export default defineConfig({ rootDir: 'src', format: 'dts', unknownAnnotation: 'warn', plugins: [ts()] }) ``` ## defineConfig Helper The `defineConfig` helper provides type checking and IntelliSense: ```typescript import { defineConfig } from '@atscript/core' export default defineConfig({ // Full type checking and autocomplete }) ``` ## Configuration Options ### Input Options #### `rootDir` - **Type:** `string` - **Required:** Yes - **Description:** Root directory containing `.as` files ```javascript rootDir: 'src' // Look for .as files in src/ ``` #### `entries` - **Type:** `string[]` - **Default:** All `.as` files in rootDir - **Description:** Specific entry files to process ```javascript entries: ['types/user.as', 'types/product.as'] ``` #### `include` - **Type:** `string[]` - **Default:** `['**/*.as']` - **Description:** Glob patterns for files to include ```javascript include: ['**/*.as', '!**/*.test.as'] ``` #### `exclude` - **Type:** `string[]` - **Default:** `['**/node_modules/**']` - **Description:** Glob patterns for files to exclude ```javascript exclude: ['**/temp/**', '**/*.draft.as'] ``` #### `unknownAnnotation` - **Type:** `'allow' | 'warn' | 'error'` - **Default:** `'error'` - **Description:** How to handle unknown annotations ```javascript unknownAnnotation: 'allow' // Accept any annotation unknownAnnotation: 'warn' // Warn but continue unknownAnnotation: 'error' // Treat as error (strict) ``` #### `primitives` - **Type:** `Record` - **Description:** Custom primitive types and extensions ```javascript primitives: { string: { extensions: { url: { type: 'string', documentation: 'URL format', expect: { pattern: ['^https?://.+$', '', 'Invalid URL'] } } } } } ``` #### `annotations` - **Type:** `AnnotationsTree` - **Description:** Custom annotation definitions ```javascript import { AnnotationSpec } from '@atscript/core' annotations: { ui: { hidden: new AnnotationSpec({ description: 'Hide field in UI', nodeType: ['prop'] }) } } ``` #### `plugins` - **Type:** `Plugin[]` - **Description:** Active plugins for code generation ```javascript import ts from '@atscript/typescript' import mongo from '@atscript/mongo' plugins: [ ts(), mongo({ syncIndexes: true }) ] ``` ### Output Options #### `format` - **Type:** `string` - **Default:** `'dts'` - **Description:** Output format that plugins should generate ```javascript format: 'dts' // TypeScript plugin: Generate .d.ts files format: 'js' // TypeScript plugin: Generate .js files with metadata format: 'py' // Python plugin (hypothetical): Generate .py files ``` The format is an open string field - each plugin decides which formats to support: - **@atscript/typescript**: Supports `'dts'` and `'js'` - Other plugins define their own supported formats ::: info Format Usage - **VSCode extension**: Uses this setting to determine what files to generate on save - **asc CLI**: Uses this setting by default (overridden by `-f` flag if provided) - **unplugin-atscript**: Ignores this setting (always generates what the bundler needs) ::: #### `outDir` - **Type:** `string` - **Default:** Same as source directory - **Description:** Output directory for generated files ```javascript outDir: 'dist' // Output to dist/ instead of source location ``` ## Complete Example ```javascript // atscript.config.js import { defineConfig, AnnotationSpec } from '@atscript/core' import ts from '@atscript/typescript' import mongo from '@atscript/mongo' export default defineConfig({ // Input configuration rootDir: 'src', entries: undefined, // Process all .as files include: ['**/*.as'], exclude: ['**/*.test.as', '**/drafts/**'], // Validation unknownAnnotation: 'warn', // Custom primitives primitives: { string: { extensions: { objectId: { type: 'string', documentation: 'MongoDB ObjectId', expect: { pattern: ['^[0-9a-f]{24}$', 'i', 'Invalid ObjectId'] } } } } }, // Custom annotations annotations: { api: { endpoint: new AnnotationSpec({ description: 'API endpoint path', argument: { name: 'path', type: 'string' } }), method: new AnnotationSpec({ description: 'HTTP method', argument: { name: 'verb', type: 'string', values: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH'] } }) } }, // Plugins plugins: [ ts({ // TypeScript plugin options }), mongo({ // MongoDB plugin options syncIndexes: true, connectionUrl: process.env.MONGO_URL }) ], // Output configuration format: 'js', // Generate JavaScript with metadata outDir: undefined // Output alongside source files }) ``` ## TypeScript Configuration For TypeScript config files (`atscript.config.ts`): ```typescript // atscript.config.ts import { defineConfig } from '@atscript/core' import ts from '@atscript/typescript' export default defineConfig({ rootDir: 'src', plugins: [ts()] // Full type checking and autocomplete provided by defineConfig }) ``` Or without `defineConfig` (manually typed): ```typescript // atscript.config.ts import type { TAtscriptConfig } from '@atscript/core' import ts from '@atscript/typescript' const config: TAtscriptConfig = { rootDir: 'src', plugins: [ts()] } export default config ``` ## Integration Points ### VSCode Extension The VSCode extension automatically: 1. Detects configuration file changes 2. Updates IntelliSense for annotations 3. Validates annotations in real-time 4. Generates files based on format setting 5. Applies unknownAnnotation rules ### Build Tools (unplugin-atscript) When using `unplugin-atscript` with Vite, Rollup, or Rolldown: 1. Reads the configuration file 2. Applies all plugins defined in the config 3. Processes files according to include/exclude patterns 4. Generates output based on format settings 5. Respects all custom primitives and annotations ```javascript // vite.config.js import atscript from 'unplugin-atscript' export default { plugins: [ atscript.vite() // Uses atscript.config.js automatically ] } ``` ## Config File Lookup ### VSCode Extension Looks for the nearest config file starting from the `.as` file location: 1. Check the folder containing the `.as` file 2. Check parent folder 3. Continue up the directory tree until workspace root is reached ### Build Tools (unplugin-atscript) Similar lookup strategy: 1. Start from the `.as` file location 2. Search upward through parent directories 3. Stop at current working directory (cwd) This allows for monorepo setups where different packages can have their own Atscript configurations. ## Loading Priority When multiple config formats exist in the same directory: 1. `atscript.config.ts` / `atscript.config.mts` 2. `atscript.config.js` / `atscript.config.mjs` 3. Default configuration if no file found ## Next Steps - [Build Setup](/guide/build-setup) - Integrate with build tools - [Quick Start](/guide/quick-start) - Complete setup guide --- URL: "atscript.moost.org/guide/imports-exports" LLMS_URL: "atscript.moost.org/guide/imports-exports.md" --- # Imports & Exports Atscript imports and exports work similar to TypeScript with some specific limitations and rules. ## Key Limitations 1. **No default imports/exports** - Only named exports and imports are supported 2. **No namespace or rename syntax** - No `import * as`, `export * as`, or `import { a as b }` 3. **`.as` files can only import `.as` files** - Cannot import TypeScript or JavaScript 4. **TypeScript can import `.as` files** - Requires `.as.d.ts` files (generated by VSCode extension or `asc` CLI) ## Named Exports ```atscript // user.as - Named exports only export interface User { id: string name: string } export type UserID = string export type Status = 'active' | 'inactive' // Private (not exported) interface InternalConfig { debug: boolean } ``` ## Importing in Atscript Files In `.as` files, omit the file extension: ```atscript // app.as import { User, UserID, Status } from './user' import { Product } from '../models/product' import { validateEmail } from '../../utils/validators' export interface Order { user: User items: Product[] } ``` ## Importing in TypeScript Files TypeScript files **must** include the `.as` extension: ```typescript // app.ts import { User, UserID, Status } from './user.as' import { Product } from '../models/product.as' // Use as both type and runtime object const user: User = { id: '1', name: 'John' } const validator = User.validator() const metadata = User.metadata ``` ## Valid Import/Export Examples ### Basic Named Import/Export ```atscript // types.as export interface Person { name: string } export type ID = string ``` ```atscript // main.as import { Person, ID } from './types' export interface Employee extends Person { employeeId: ID } ``` ### Multiple Imports from Same File ```atscript // models.as export interface User { } export interface Product { } export interface Order { } export type Status = string ``` ```atscript // app.as import { User, Product, Order, Status } from './models' ``` ### Nested Directory Imports ```atscript // domain/user.as import { BaseEntity } from '../shared/base' import { Address } from './types/address' import { validate } from '../../utils/validation' ``` ## Invalid Syntax (Not Supported) ```atscript // ❌ Default exports export default interface User { } // ❌ Default imports import User from './user' // ❌ Namespace imports import * as models from './models' // ❌ Export namespace export * as utils from './utils' // ❌ Import with rename import { User as UserModel } from './user' // ❌ Re-exports export { User } from './user' // ❌ Importing non-.as files import { helper } from './helper.ts' ``` ## Setup for TypeScript Integration For TypeScript to import `.as` files: 1. **With VSCode Extension**: Automatically generates `.as.d.ts` files on save 2. **With CLI**: Run `asc -f dts` to generate TypeScript definitions 3. **With Bundler**: Use `unplugin-atscript` for automatic compilation Example generated structure: ``` src/ user.as # Source file user.as.js # Generated JavaScript (with asc -f js) user.as.d.ts # Generated TypeScript definitions app.ts # Can import from './user.as' ``` ## Next Steps - [Primitives](/guide/primitives) - Primitive types and extensions - [Annotations](/guide/annotations) - Metadata system --- URL: "atscript.moost.org/guide/installation" LLMS_URL: "atscript.moost.org/guide/installation.md" --- # Installation ::: info This installation guide is specific to TypeScript/JavaScript. Support for other languages is planned through community-contributed plugins. ::: ## Prerequisites - Node.js 16 or higher - npm, pnpm, yarn, or bun package manager ## Install Atscript To use Atscript in your project, install the core packages: ::: code-group ```bash [npm] npm install -D @atscript/core @atscript/typescript ``` ```bash [pnpm] pnpm add -D @atscript/core @atscript/typescript ``` ```bash [yarn] yarn add -D @atscript/core @atscript/typescript ``` ```bash [bun] bun add -D @atscript/core @atscript/typescript ``` ::: ## Package Overview ### Core Packages - **@atscript/core** - Core parser, AST, and plugin system - **@atscript/typescript** - TypeScript/JavaScript code generation and CLI (`asc` command) ### Optional Packages - **@atscript/mongo** - MongoDB integration with index syncing - **@atscript/moost-mongo** - Moost framework MongoDB integration - **@atscript/moost-validator** - Moost framework validation integration - **@atscript/unplugin** - Build tool integrations (Vite, Webpack, Rollup, etc.) ## Verify Installation After installation, verify that the `asc` compiler is available: ::: code-group ```bash [npx] npx asc --help ``` ```bash [pnpm] pnpm exec asc --help ``` ```bash [yarn] yarn asc --help ``` ```bash [bunx] bunx asc --help ``` ::: You should see the available command options: ``` Options: -c, --config Path to config file -f, --format Output format (dts or js) --help Show help ``` ## VSCode Extension (Recommended) For the best development experience, install the [Atscript VSCode extension](https://marketplace.visualstudio.com/items?itemName=moost.atscript-as): 1. Open VSCode 2. Go to Extensions (Cmd/Ctrl + Shift + X) 3. Search for "Atscript" 4. Install the extension by Moost Or install directly from the [Visual Studio Marketplace](https://marketplace.visualstudio.com/items?itemName=moost.atscript-as). The extension provides: - Syntax highlighting for `.as` files - IntelliSense support - Error checking - Auto-formatting ## Next Steps - [Quick Start](/guide/quick-start) - Create your first .as file - [Why Atscript?](/guide/why-atscript) - Understand the motivation --- URL: "atscript.moost.org/guide/interfaces-types" LLMS_URL: "atscript.moost.org/guide/interfaces-types.md" --- # Interfaces & Types Atscript provides TypeScript-like syntax with annotations and semantic types. ## Interfaces Basic object structure definition: ```atscript export interface User { id: string name: string age: number isActive: boolean } ``` ### Nested & Annotations ```atscript @mongo.collection 'users' export interface User { id: string profile: { name: string avatar?: string // Optional } settings: { theme: 'light' | 'dark' } } ``` ## Type Aliases Type aliases carry metadata and work as runtime objects: ```atscript @expect.minLength 3 @expect.maxLength 20 export type Username = string export type Status = 'pending' | 'success' | 'error' export type ID = string | number ``` In TypeScript, use them as both types and validators: ```typescript import { Username } from './types.as' const name: Username = 'john_doe' const validator = Username.validator() if (validator.validate(input, true)) { // input is Username } ``` ## Properties ### Optional & Dynamic ```atscript export interface Config { name: string bio?: string // Optional [*]: string // Wildcard - any string props [/^x-.*/]: string // Pattern - props starting with x- } ``` Common patterns: - `[/^REACT_APP_.*/]` - Environment variables - `[/.*_URL$/]` - URL configs - `[/^social_.*/]` - Social links ## Type References ```atscript import { Address } from './address' export interface User { address: Address friends: User[] // Self-reference manager?: User // Optional reference } ``` ## Arrays & Complex Types ```atscript export interface Data { tags: string[] // Array matrix: number[][] // 2D array tuple: [string, number] // Tuple coords: [number, number, number] // 3-tuple } ``` ## Intersection Types ```atscript interface Timestamped { createdAt: string } interface Post { title: string } & Timestamped // Has both title and createdAt ``` ## Comments ```atscript // Single-line comment /* Multi-line comment */ ``` ## Complete Example ```atscript import { Address } from './address' @mongo.collection 'users' export interface User { @meta.id _id: mongo.objectId username: string email: string.email profile: { bio?: string [/^social_.*/]: string // social_twitter, social_github, etc. } addresses: Address[] status: 'active' | 'inactive' createdAt: string.isoDate } export type UserStatus = User['status'] // Derived type ``` ## Next Steps - [Imports & Exports](/guide/imports-exports) - Module system - [Primitives](/guide/primitives) - Semantic types - [Annotations](/guide/annotations) - Metadata system --- URL: "atscript.moost.org/guide/primitives" LLMS_URL: "atscript.moost.org/guide/primitives.md" --- # Primitives Primitives are the basic types that map to fundamental types in virtually any programming language. While different languages may map some primitives to the same base type, each language plugin is responsible for determining how to map the set of primitives provided by Atscript core. ## Basic Primitive Types Atscript supports the following primitive types: - **`string`** - Text values - **`number`** - Numeric values (integers and floats) - **`boolean`** - True/false values - **`null`** - Null value - **`undefined`** - Undefined value (maps to void) - **`void`** - No value ```atscript export interface BasicTypes { text: string count: number isEnabled: boolean empty: null nothing: void } ``` ## Semantic Types (Primitive Extensions) Primitives can be extended using dot notation to create semantic types. These extensions serve two purposes: 1. **Type refinement** - Extensions help map to the most appropriate type in target languages. For example, `number.double` maps to `number` in TypeScript, but in languages with distinct int, single, and double types, it maps to the appropriate double-precision type. 2. **Implicit validation** - Extensions may automatically add annotations like `@expect.*` for validation constraints. ### String Extensions String types can be extended to represent specific formats: ```atscript export interface User { id: string.uuid // UUID format email: string.email // Email address phone: string.phone // Phone number birthDate: string.date // Date string createdAt: string.isoDate // ISO 8601 date } ``` #### Available String Extensions **`string.email`** - Validates email format - Pattern: `^[^\s@]+@[^\s@]+\.[^\s@]+$` - Example: `user@example.com` **`string.phone`** - Validates phone number format - Pattern: `^\+?[0-9\s-]{10,15}$` - Example: `+1 555-123-4567` **`string.date`** - Validates common date formats - Supports: `YYYY-MM-DD`, `MM/DD/YYYY`, `DD-MM-YYYY`, `D Month YYYY` - Examples: `2024-01-15`, `01/15/2024`, `15-01-2024`, `15 January 2024` **`string.isoDate`** - Validates ISO 8601 date format with time - Supports UTC and timezone offsets - Examples: `2024-01-15T10:30:00Z`, `2024-01-15T10:30:00+05:00` **`string.uuid`** - Validates UUID format - Pattern: `^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$` - Example: `123e4567-e89b-12d3-a456-426614174000` ### Number Extensions Number types can be extended to represent specific numeric constraints: ```atscript export interface Product { quantity: number.int // Integer only price: number.positive // >= 0 discount: number.negative // <= 0 weight: number.double // Double precision createdAt: number.timestamp // Unix timestamp } ``` #### Available Number Extensions **`number.int`** - Must be an integer (no decimals) - Implicitly adds `@expect.int` - Can be combined: `number.int.positive`, `number.int.negative` **`number.positive`** - Must be greater than or equal to 0 - Implicitly adds `@expect.min 0` - Can be combined: `number.positive.int`, `number.positive.double` **`number.negative`** - Must be less than or equal to 0 - Implicitly adds `@expect.max 0` - Can be combined: `number.negative.int`, `number.negative.single` **`number.single`** - Single-precision floating-point **`number.double`** - Double-precision floating-point **`number.timestamp`** - Unix timestamp (integer) - Typically seconds since epoch ### Boolean Extensions Boolean types can be extended for specific use cases: ```atscript export interface Settings { alwaysOn: boolean.true // Must be true disabled: boolean.false // Must be false toggle: boolean // Can be true or false } ``` ## Type Tags and Metadata When compiled, semantic types preserve their extensions as tags: ```typescript // Generated TypeScript export declare class User { email: string /* email */ age: number /* int */ // ... } // Runtime metadata access const emailProp = User.type.props.get('email') const emailTags = emailProp?.type.tags // ['email', 'string'] const ageProp = User.type.props.get('age') const ageTags = ageProp?.type.tags // ['int', 'number'] ``` These tags can be used by: - Validators to apply appropriate rules - UI generators to choose correct input types - API documentation generators - Database schema generators ## Custom Primitives Add custom primitives or extensions via configuration: ```javascript // atscript.config.js import { defineConfig } from '@atscript/core' export default defineConfig({ primitives: { string: { extensions: { url: { type: 'string', documentation: 'URL format', expect: { pattern: ['^https?://.+$', '', 'Invalid URL'] } }, slug: { type: 'string', documentation: 'URL-safe slug', expect: { pattern: ['^[a-z0-9-]+$', '', 'Invalid slug'] } } } }, number: { extensions: { percentage: { type: 'number', documentation: 'Percentage value', expect: { min: 0, max: 100 } } } } } }) ``` Use in `.as` files: ```atscript export interface Page { url: string.url slug: string.slug completeness: number.percentage } ``` Plugins can also provide custom primitives through their configuration. ## Best Practices 1. **Use semantic types** instead of plain primitives when the data has a specific format 2. **Let semantic types handle validation** - don't duplicate with `@expect` annotations 3. **Choose the right extension** - `string.date` vs `string.isoDate` based on your needs 4. **Combine extensions when needed** - `number.int.positive` for counting values, `number.double.negative` for losses ::: tip Combining Extensions Some extensions can be combined to create more specific types. For example: - `number.int.positive` - Positive integers only - `number.double.negative` - Negative double-precision numbers - `number.single.positive` - Positive single-precision numbers ::: ## Next Steps - [Annotations](/guide/annotations) - Add metadata to your types - [Configuration](/guide/configuration) - Configure Atscript --- URL: "atscript.moost.org/guide/quick-start" LLMS_URL: "atscript.moost.org/guide/quick-start.md" --- # Quick Start This guide will walk you through creating your first Atscript file and using it in a TypeScript project. ## Create Your First .as File Let's start with a simple product model. Create a file named `product.as`: ```atscript // product.as @meta.description 'Product in our catalog' export interface Product { @meta.id id: string.uuid @meta.label 'Product Name' @expect.minLength 3 @expect.maxLength 100 name: string @meta.label 'Price in USD' @expect.min 0 @expect.max 1000000 price: number.positive @meta.label 'In Stock' inStock: boolean createdAt: string.isoDate } ``` This concise example demonstrates: - Interface annotation (`@meta.description`) - Property metadata (`@meta.label`, `@meta.id`) - Validation rules (`@expect.minLength`, `@expect.min`) - Semantic types (`string.uuid`, `number.positive`, `string.isoDate`) ## Configuration Create an `atscript.config.js` file in your project root: ```javascript // atscript.config.js import { defineConfig } from '@atscript/core' import ts from '@atscript/typescript' export default defineConfig({ rootDir: 'src', format: 'dts', unknownAnnotation: 'error', plugins: [ts()], }) ``` ### Configuration Options - **`rootDir`** - Where your `.as` files are located - **`format`** - Default output format (`dts` or `js`) - **`unknownAnnotation`** - How to handle unknown annotations: - `'error'` - Treat as error (strict mode) - `'warn'` - Show warning but continue - `'allow'` - Accept any annotation (available in runtime) - **`plugins`** - Active plugins (TypeScript plugin for JS/TS generation) ### VSCode Extension Integration If you have the [Atscript VSCode extension](https://marketplace.visualstudio.com/items?itemName=moost.atscript-as) installed, it will: - Automatically pick up this config file - Generate `.d.ts` files for each `.as` file on save - Enable smooth TypeScript integration - Provide IntelliSense and error checking ## Manual Compilation (Alternative) If you're not using the VSCode extension, use the `asc` CLI from `@atscript/typescript`: ::: code-group ```bash [Generate TypeScript definitions] npx asc -f dts ``` ```bash [Generate JavaScript with metadata] npx asc -f js ``` ::: **Important**: Run `asc -f dts` at least once to generate `atscript.d.ts`. This file contains: - All annotation types with proper TypeScript definitions - Tag type definitions for IntelliSense - Even unknown annotations (if using `'allow'` mode) Add `atscript.d.ts` to your `tsconfig.json`: ```json { "include": [ "src/**/*", "atscript.d.ts" // Add this line ] } ``` ## Bundler Integration For build tools, install `unplugin-atscript`: ::: code-group ```bash [npm] npm install -D unplugin-atscript ``` ```bash [pnpm] pnpm add -D unplugin-atscript ``` ```bash [yarn] yarn add -D unplugin-atscript ``` ::: Then configure your bundler: ::: code-group ```javascript [Vite] // vite.config.js import { defineConfig } from 'vite' import atscript from 'unplugin-atscript' export default defineConfig({ plugins: [ atscript.vite(), // other plugins... ], }) ``` ```javascript [Rollup] // rollup.config.js import atscript from 'unplugin-atscript' export default { plugins: [ atscript.rollup(), // other plugins... ], } ``` ```javascript [esbuild] // build.js import { build } from 'esbuild' import atscript from 'unplugin-atscript' build({ plugins: [atscript.esbuild()], // other options... }) ``` ```javascript [Rolldown] // rolldown.config.js import atscript from 'unplugin-atscript' export default { plugins: [ atscript.rolldown(), // other plugins... ], } ``` ::: ## Using Atscript in TypeScript Import and use your Atscript types in TypeScript: ```typescript // app.ts import { Product } from './product.as' // 1. Use as a TypeScript type const laptop: Product = { id: '550e8400-e29b-41d4-a716-446655440000', name: 'Gaming Laptop', price: 1299.99, inStock: true, createdAt: '2024-01-15T10:30:00Z' } // 2. Access property metadata const nameProp = Product.type.props.get('name') const nameLabel = nameProp?.metadata.get('meta.label') console.log(nameLabel) // 'Product Name' // 3. Access type tags const idProp = Product.type.props.get('id') const idTags = idProp?.type.tags console.log(idTags) // ['uuid', 'string'] // 4. Runtime validation with type guard const validator = Product.validator() function processData(data: unknown) { // Safe validation - acts as type guard if (validator.validate(data, true)) { // TypeScript now knows 'data' is Product type console.log(`Product ${data.name} costs $${data.price}`) // data.name and data.price are fully typed! } else { console.log('Invalid product:', validator.errors) } } // 5. Unsafe validation (throws on error) try { validator.validate(someData) // If we reach here, someData is valid } catch (error) { console.error('Validation failed:', error.message) } ``` ### Key Points - **Type Guard**: Safe validation (`validate(data, true)`) acts as a TypeScript type guard - **Runtime Metadata**: All annotations are accessible at runtime - **Type Tags**: Semantic types are preserved as tags for runtime inspection - **Automatic Validation**: Semantic types like `string.email` automatically add validation rules ::: tip Semantic types automatically add validation. For example: - `string.email` adds email format validation - `number.positive` adds `@expect.min 0` - `string.uuid` adds UUID format validation Learn more on the [Primitives](/guide/primitives) page. ::: ## Next Steps - [Interfaces & Types](/guide/interfaces-types) - Define complex data structures - [Primitives](/guide/primitives) - Explore semantic types - [Annotations](/guide/annotations) - Learn the annotation system --- URL: "atscript.moost.org/guide/why-atscript" LLMS_URL: "atscript.moost.org/guide/why-atscript.md" --- # Why Atscript? ## The Problem: Scattered Data Definitions In modern software projects, especially business applications, data structure definitions are scattered across multiple layers and files: - **Type definitions** in your programming language (TypeScript interfaces, Go structs, Java classes) - **Validation rules** in separate validation libraries or schemas - **Database constraints** in migration files or ORM configurations - **UI metadata** like labels and descriptions in frontend components - **API documentation** in OpenAPI/Swagger files - **Database indexes** in database-specific DDL scripts This scattering leads to: - **Duplication** - The same information repeated in different formats - **Inconsistency** - Changes in one place not reflected in others - **Maintenance burden** - Multiple files to update for a single change - **No single source of truth** - Unclear which definition is authoritative ## The Solution: Unified Data Definition Atscript brings order to this chaos by providing a single place to define: ```atscript @mongo.collection 'users' @meta.description 'User entity for our application' export interface User { @meta.id @mongo.index.unique 'email_idx' @meta.label 'User Email' @meta.description 'Primary contact email' email: string.email @meta.label 'Full Name' @expect.minLength 2 @expect.maxLength 100 @mongo.index.text 5 name: string @meta.label 'Age' @expect.min 13 @expect.max 150 @expect.int age: number @meta.label 'Account Status' @meta.documentation 'Indicates if the user can access the system' @mongo.index.plain 'status_idx' isActive: boolean } ``` From this single definition, Atscript can generate: - TypeScript/JavaScript types with full type safety - Runtime validators with all constraints - Database schemas with indexes - JSON Schema for API documentation - UI metadata for form generation - And more via the plugin system ## Core Design Principles ### 1. Everything is Extensible - **Types are extensible**: Create semantic types like `string.email`, `number.positive` - **Annotations are extensible**: Add any metadata your project needs - **Plugins are powerful**: Generate code for any language or framework ### 2. Annotations for Everything Atscript uses annotations to attach any kind of metadata: - `@meta.*` - Human-readable information - `@expect.*` - Validation constraints - `@mongo.*` - Database-specific configuration - `@your.custom` - Whatever your project needs ### 3. Language Agnostic While currently supporting TypeScript/JavaScript, Atscript is designed to be universal: - Clean, TypeScript-like syntax that's familiar - Plugin system allows any language to be targeted - Community can contribute plugins for Python, Go, Rust, etc. ## Real-World Benefits ### For Development Teams - **Single source of truth** - One place to define data structures - **Consistency guaranteed** - All layers use the same definitions - **Faster development** - No need to maintain multiple schemas - **Type safety everywhere** - From database to UI ### For Business Logic - **Business rules in one place** - Validation constraints with the data - **Self-documenting** - Metadata makes code more readable - **Audit-friendly** - Clear data governance and constraints ### For System Architecture - **Microservices contracts** - Share types between services - **API-first design** - Generate OpenAPI from types - **Database migrations** - Generate schemas with constraints - **Cross-platform** - Same types for backend and frontend ## Example: Before and After ### Before Atscript (Scattered) ```typescript // types/user.ts interface User { email: string name: string age: number isActive: boolean } // validation/user-schema.ts const userSchema = z.object({ email: z.string().email(), name: z.string().min(2).max(100), age: z.number().int().min(13).max(150), isActive: z.boolean() }) // database/user.model.ts @Entity() class UserEntity { @Column({ unique: true }) @Index() email: string @Column() @Index({ fulltext: true }) name: string @Column('integer') age: number @Column() @Index() isActive: boolean } // ui/user-form-config.ts const userFormFields = { email: { label: 'User Email', type: 'email' }, name: { label: 'Full Name', minLength: 2, maxLength: 100 }, age: { label: 'Age', type: 'number', min: 13, max: 150 }, isActive: { label: 'Account Status', type: 'checkbox' } } ``` ### After Atscript (Unified) ```atscript // user.as - Everything in one place! @mongo.collection 'users' export interface User { @meta.label 'User Email' @mongo.index.unique 'email_idx' email: string.email @meta.label 'Full Name' @expect.minLength 2 @expect.maxLength 100 @mongo.index.text 5 name: string @meta.label 'Age' @expect.min 13 @expect.max 150 @expect.int age: number @meta.label 'Account Status' @mongo.index.plain 'status_idx' isActive: boolean } ``` Then use it everywhere: ```typescript import { User } from './user.as' // Type checking const user: User = { /* ... */ } // Validation const validator = User.validator() validator.validate(userData) // Access metadata for UI User.metadata.get('meta.label') // For form labels // Database schema is auto-generated // Indexes are auto-created // Documentation is auto-extracted ``` ## Who Benefits from Atscript? - **Full-stack developers** tired of maintaining duplicate schemas - **Teams** wanting consistency across their codebase - **Architects** designing type-safe microservices - **Projects** with complex validation requirements - **Applications** needing rich metadata for UI generation - **Systems** requiring database schema synchronization ## The Vision Atscript aims to become the universal language for data structure definition, where: - Every programming language can consume Atscript definitions via plugins - Complex business rules are expressed declaratively with annotations - Type safety and validation are guaranteed across all layers - Teams spend less time on boilerplate and more time on business logic ## Next Steps - [Installation](/guide/installation) - Install Atscript packages - [Quick Start](/guide/quick-start) - Create your first .as file --- URL: "atscript.moost.org/integrations" LLMS_URL: "atscript.moost.org/integrations.md" --- --- URL: "atscript.moost.org/integrations/express" LLMS_URL: "atscript.moost.org/integrations/express.md" --- --- URL: "atscript.moost.org/integrations/fastify" LLMS_URL: "atscript.moost.org/integrations/fastify.md" --- --- URL: "atscript.moost.org/integrations/graphql" LLMS_URL: "atscript.moost.org/integrations/graphql.md" --- --- URL: "atscript.moost.org/integrations/moost-framework" LLMS_URL: "atscript.moost.org/integrations/moost-framework.md" --- --- URL: "atscript.moost.org/integrations/nestjs" LLMS_URL: "atscript.moost.org/integrations/nestjs.md" --- --- URL: "atscript.moost.org/integrations/openapi" LLMS_URL: "atscript.moost.org/integrations/openapi.md" --- --- URL: "atscript.moost.org/packages/core" LLMS_URL: "atscript.moost.org/packages/core.md" --- --- URL: "atscript.moost.org/packages/core/annotation-spec" LLMS_URL: "atscript.moost.org/packages/core/annotation-spec.md" --- --- URL: "atscript.moost.org/packages/core/ast-nodes" LLMS_URL: "atscript.moost.org/packages/core/ast-nodes.md" --- --- URL: "atscript.moost.org/packages/core/configuration" LLMS_URL: "atscript.moost.org/packages/core/configuration.md" --- --- URL: "atscript.moost.org/packages/core/default-annotations" LLMS_URL: "atscript.moost.org/packages/core/default-annotations.md" --- --- URL: "atscript.moost.org/packages/core/document-api" LLMS_URL: "atscript.moost.org/packages/core/document-api.md" --- --- URL: "atscript.moost.org/packages/core/installation" LLMS_URL: "atscript.moost.org/packages/core/installation.md" --- --- URL: "atscript.moost.org/packages/core/parser-api" LLMS_URL: "atscript.moost.org/packages/core/parser-api.md" --- --- URL: "atscript.moost.org/packages/core/plugin-api" LLMS_URL: "atscript.moost.org/packages/core/plugin-api.md" --- --- URL: "atscript.moost.org/packages/mongo" LLMS_URL: "atscript.moost.org/packages/mongo.md" --- --- URL: "atscript.moost.org/packages/mongo/annotations-reference" LLMS_URL: "atscript.moost.org/packages/mongo/annotations-reference.md" --- --- URL: "atscript.moost.org/packages/mongo/collections" LLMS_URL: "atscript.moost.org/packages/mongo/collections.md" --- --- URL: "atscript.moost.org/packages/mongo/configuration" LLMS_URL: "atscript.moost.org/packages/mongo/configuration.md" --- --- URL: "atscript.moost.org/packages/mongo/indexes" LLMS_URL: "atscript.moost.org/packages/mongo/indexes.md" --- --- URL: "atscript.moost.org/packages/mongo/installation" LLMS_URL: "atscript.moost.org/packages/mongo/installation.md" --- --- URL: "atscript.moost.org/packages/mongo/patch-strategies" LLMS_URL: "atscript.moost.org/packages/mongo/patch-strategies.md" --- --- URL: "atscript.moost.org/packages/mongo/search-indexes" LLMS_URL: "atscript.moost.org/packages/mongo/search-indexes.md" --- --- URL: "atscript.moost.org/packages/mongo/validation" LLMS_URL: "atscript.moost.org/packages/mongo/validation.md" --- --- URL: "atscript.moost.org/packages/moost-mongo" LLMS_URL: "atscript.moost.org/packages/moost-mongo.md" --- --- URL: "atscript.moost.org/packages/moost-mongo/configuration" LLMS_URL: "atscript.moost.org/packages/moost-mongo/configuration.md" --- --- URL: "atscript.moost.org/packages/moost-mongo/controllers" LLMS_URL: "atscript.moost.org/packages/moost-mongo/controllers.md" --- --- URL: "atscript.moost.org/packages/moost-mongo/decorators" LLMS_URL: "atscript.moost.org/packages/moost-mongo/decorators.md" --- --- URL: "atscript.moost.org/packages/moost-mongo/dtos" LLMS_URL: "atscript.moost.org/packages/moost-mongo/dtos.md" --- --- URL: "atscript.moost.org/packages/moost-mongo/installation" LLMS_URL: "atscript.moost.org/packages/moost-mongo/installation.md" --- --- URL: "atscript.moost.org/packages/moost-validator" LLMS_URL: "atscript.moost.org/packages/moost-validator.md" --- --- URL: "atscript.moost.org/packages/moost-validator/configuration" LLMS_URL: "atscript.moost.org/packages/moost-validator/configuration.md" --- --- URL: "atscript.moost.org/packages/moost-validator/custom-validators" LLMS_URL: "atscript.moost.org/packages/moost-validator/custom-validators.md" --- --- URL: "atscript.moost.org/packages/moost-validator/error-handling" LLMS_URL: "atscript.moost.org/packages/moost-validator/error-handling.md" --- --- URL: "atscript.moost.org/packages/moost-validator/installation" LLMS_URL: "atscript.moost.org/packages/moost-validator/installation.md" --- --- URL: "atscript.moost.org/packages/moost-validator/validation-pipe" LLMS_URL: "atscript.moost.org/packages/moost-validator/validation-pipe.md" --- --- URL: "atscript.moost.org/packages/typescript" LLMS_URL: "atscript.moost.org/packages/typescript.md" --- --- URL: "atscript.moost.org/packages/typescript/cli" LLMS_URL: "atscript.moost.org/packages/typescript/cli.md" --- --- URL: "atscript.moost.org/packages/typescript/code-generation" LLMS_URL: "atscript.moost.org/packages/typescript/code-generation.md" --- --- URL: "atscript.moost.org/packages/typescript/configuration" LLMS_URL: "atscript.moost.org/packages/typescript/configuration.md" --- --- URL: "atscript.moost.org/packages/typescript/installation" LLMS_URL: "atscript.moost.org/packages/typescript/installation.md" --- --- URL: "atscript.moost.org/packages/typescript/metadata-export" LLMS_URL: "atscript.moost.org/packages/typescript/metadata-export.md" --- --- URL: "atscript.moost.org/packages/typescript/type-definitions" LLMS_URL: "atscript.moost.org/packages/typescript/type-definitions.md" --- --- URL: "atscript.moost.org/packages/typescript/validation" LLMS_URL: "atscript.moost.org/packages/typescript/validation.md" --- --- URL: "atscript.moost.org/packages/unplugin" LLMS_URL: "atscript.moost.org/packages/unplugin.md" --- --- URL: "atscript.moost.org/packages/unplugin/configuration" LLMS_URL: "atscript.moost.org/packages/unplugin/configuration.md" --- --- URL: "atscript.moost.org/packages/unplugin/esbuild" LLMS_URL: "atscript.moost.org/packages/unplugin/esbuild.md" --- --- URL: "atscript.moost.org/packages/unplugin/installation" LLMS_URL: "atscript.moost.org/packages/unplugin/installation.md" --- --- URL: "atscript.moost.org/packages/unplugin/rollup" LLMS_URL: "atscript.moost.org/packages/unplugin/rollup.md" --- --- URL: "atscript.moost.org/packages/unplugin/rspack" LLMS_URL: "atscript.moost.org/packages/unplugin/rspack.md" --- --- URL: "atscript.moost.org/packages/unplugin/vite" LLMS_URL: "atscript.moost.org/packages/unplugin/vite.md" --- --- URL: "atscript.moost.org/packages/unplugin/webpack" LLMS_URL: "atscript.moost.org/packages/unplugin/webpack.md" --- --- URL: "atscript.moost.org/packages/vscode" LLMS_URL: "atscript.moost.org/packages/vscode.md" --- --- URL: "atscript.moost.org/packages/vscode/configuration" LLMS_URL: "atscript.moost.org/packages/vscode/configuration.md" --- --- URL: "atscript.moost.org/packages/vscode/diagnostics" LLMS_URL: "atscript.moost.org/packages/vscode/diagnostics.md" --- --- URL: "atscript.moost.org/packages/vscode/features" LLMS_URL: "atscript.moost.org/packages/vscode/features.md" --- --- URL: "atscript.moost.org/packages/vscode/installation" LLMS_URL: "atscript.moost.org/packages/vscode/installation.md" --- --- URL: "atscript.moost.org/packages/vscode/intellisense" LLMS_URL: "atscript.moost.org/packages/vscode/intellisense.md" --- --- URL: "atscript.moost.org/packages/vscode/syntax-highlighting" LLMS_URL: "atscript.moost.org/packages/vscode/syntax-highlighting.md" ---