# @vibeorm/parser

> Part of **[VibeORM](https://github.com/vibeorm/vibeorm)** — a type-safe TypeScript ORM for Bun and Node. Prisma-schema or TypeScript-DSL input, a canonical schema IR, a generated client, and a dialect-aware SQL layer over PostgreSQL, PGlite, SQLite and MySQL.

Prisma `.prisma` text to canonical `SchemaIR`. It is the front door of the schema pipeline and a separate package for that reason: everything downstream consumes the IR, so only this package ever sees schema text.

```bash
bun add @vibeorm/parser
```

> **Stable.** `2.0.0`, published under the `latest` dist-tag. The v1 line stays installable as `vibeorm@1`.

Most users never install this directly — it ships as a dependency of [`vibeorm`](https://www.npmjs.com/package/vibeorm). Reach for it when you are building tooling on the IR or SQL layer.

## Usage

Two functions, both returning a `SchemaIR` from [`@vibeorm/schema`](https://github.com/vibeorm/vibeorm/tree/master/packages/schema).

```ts
import { loadPrismaSchema, parsePrismaSchema } from "@vibeorm/parser";

const ir = parsePrismaSchema({
  source: `
    datasource db {
      provider = "pglite"
    }

    model User {
      id    Int    @id @default(autoincrement())
      email String @unique
      posts Post[]
    }

    model Post {
      id       String @id @default(uuid())
      title    String
      authorId Int
      author   User   @relation(fields: [authorId], references: [id], onDelete: Cascade)
    }
  `,
});

const fromDisk = await loadPrismaSchema({ path: "./prisma/schema.prisma" });
```

Both accept an optional `extensions` registry (`ExtensionRegistry`), which is what lets extension attributes and extension field types parse.

## What the parser accepts

- **Providers**: `postgresql` (alias `postgres`), `pglite`, `sqlite`, `mysql`. The `datasource` block is optional; without one the provider defaults to `postgresql`, so schema fragments still parse.
- **`env(...)` stays unresolved.** `url = env("DATABASE_URL")` is accepted and recorded as-is; the URL is resolved at connection time, not at parse time.
- **`generator` blocks are ignored.** Generation is configured in `vibeorm.config.ts`.
- **Directory sources.** `loadPrismaSchema` accepts a directory as well as a file: `.prisma` files are collected recursively, concatenated in sorted relative-path order, and path segments starting with `.` are skipped. The result is identical on every machine.
- **Blocks and attributes**: `model` and `view`, `enum` (values and `@@map`), every Prisma scalar plus enum references with `?` and `[]`, `@id`, `@unique`, `@updatedAt`, `@map` / `@@map`, `@default(...)` (`autoincrement`, `now`, `uuid`, `cuid`, `nanoid`, `ulid`, `dbgenerated`, literals, enum values), `@db.*` native types kept verbatim, `@@id`, `@@unique`, `@@index` (sort order, `type:`, `map:`; an `ops:` operator class is refused with `VIBE_UNSUPPORTED_CAPABILITY` because it cannot be kept as a qualified name, so declare operator classes in the TS DSL), `@relation` (positional or `name:`, `fields`, `references`, `onDelete`, `onUpdate`), and `///` documentation on models and fields.
- **`Unsupported("...")` columns are kept, never dropped.** They become a `FieldIR` with `isUnsupported: true`, a nominal `String` type and the raw database type verbatim in `nativeType` (parentheses and commas included). Migrations and `vibeorm convert` need that fidelity; downstream layers read `isUnsupported` to keep the column off the queryable surface.

## Relation resolution

Two relation fields pair if and only if they point at each other's model, are distinct fields, and their relation names match symmetrically — both unnamed, or both carrying the same name. The rule is structural and shared with migrate, so an introspected schema resolves like a hand-written one.

- Both sides lists with no `fields:` gives `manyToMany` (implicit join table). When both sides sit on the SAME model, structural validation refuses the schema (`implicit-self-many-to-many`): a self relation has one model name on both ends, so both fields would own join column `"A"`. Model a directed self relation with an explicit junction model.
- A list side otherwise gives `oneToMany`; a 1:N self-relation never becomes a phantom many-to-many.
- The FK side is `oneToOne` when its columns are unique, otherwise `manyToOne`.
- More than one candidate counterpart under the same name key is reported as `ambiguous-relation`.

## Errors

An invalid schema throws exactly one `VibeError` with code `VIBE_SCHEMA_INVALID`. Every problem is listed at once in `error.meta.issues`, so you do not fix one error to discover the next.

```ts
import { VibeError } from "@vibeorm/schema";

try {
  parsePrismaSchema({ source });
} catch (error) {
  if (error instanceof VibeError && error.code === "VIBE_SCHEMA_INVALID") {
    console.error(error.meta.issues);
  } else {
    throw error;
  }
}
```

Issues come from the shared structural rules (`validateSchemaIR`) plus the Prisma-specific ones: `ambiguous-relation`, `unknown-attribute`, `unknown-field-type`, `invalid-cascade-action`, `unsupported-provider`, `name-collision`, `syntax-error`.

## Links

- [Documentation](https://github.com/vibeorm/vibeorm/tree/master/docs)
- [Getting started](https://github.com/vibeorm/vibeorm/blob/master/docs/getting-started.md)
- [Repository and issues](https://github.com/vibeorm/vibeorm)
- MIT licensed
