import { C as Column, E as Entity, S as ShapeRecord, R as ReferenceArray, b as SelfMarker, O as OwnedShape, M as Mirror, c as OwnedArray, W as WeaveClient, a as ScopeDef, d as ClientOptions, I as InferEntity, e as OrderByInput, f as InferInsert, g as WhereInput, F as FetchLike } from './scope-BWyW8OO2.js'; export { A as AccumulateInput, h as AccumulateOp, i as Accumulator, j as AggOpts, k as AggregateInput, l as AggregateOutput, m as AggregateRow, n as EntityClient, o as Expr, p as ExprOperand, q as FacetInput, G as GroupExpr, r as InferRead, P as PageOpts, s as PageResult, t as PushScopesOptions, u as ReadOpts, v as ScopeEntityRule, w as ScopeRule, x as ScopeRuleConfig, V as Verb, y as add, z as avg, B as count, D as createClient, H as defineEntity, J as defineScope, K as distinct, L as div, N as first, Q as histogram, T as inc, U as max, X as min, Y as mirror, Z as mul, _ as owned, $ as percentile, a0 as pushScopes, a1 as reference, a2 as scopeRule, a3 as self, a4 as setOnInsert, a5 as sub, a6 as sum, a7 as timeBucket } from './scope-BWyW8OO2.js'; /** * Public column constructors — the shape-declaration surface. * * Each constructor returns a fresh, nullable {@link Column} over the matching * catalog type. Chain modifiers to refine it: `text().notNull().unique()`. */ declare const int2: () => Column; declare const int4: () => Column; declare const int8: () => Column; declare const numeric: () => Column; declare const float4: () => Column; declare const float8: () => Column; declare const text: () => Column; declare const varchar: () => Column; declare const bpchar: () => Column; declare const timestamptz: () => Column; declare const timestamp: () => Column; declare const date: () => Column; declare const time: () => Column; declare const interval: () => Column; declare const bool: () => Column; declare const uuid: () => Column; declare const json: () => Column; declare const jsonb: () => Column; declare const bytea: () => Column, false, false>; /** * `array(...)` is overloaded by what it wraps: * * - `array(text())` → a **scalar array column** (`text[]`). * - `array(cityEntity)` → an **N:N reference marker** for `reference(array(city))`. * - `array(() => city)` → **N:N lazy** (import circular / ciclo entre entities). * - `array(self())` → **N:N self-ref** (`reference(array(self()))`). * - `array({ ... })` → an **owned 1:N marker** for `owned(array({...}))`. * * Scalar arrays default to **`NOT NULL DEFAULT '{}'`** (you always get `[]`, * never `null`); opt out with `array(text()).nullable()`. */ declare function array(inner: Column): Column; declare function array>(target: T): ReferenceArray; declare function array(thunk: () => Entity): ReferenceArray>; declare function array(marker: SelfMarker): ReferenceArray>; declare function array(m: Mirror): OwnedArray; declare function array(shape: TShape): OwnedArray; interface ColumnIR { kind: "column"; /** Identidade estável do campo (UUID), garantida no back. Sobrevive a rename. */ id?: string; /** Nome do catálogo (`"text"`, `"int4"`, …). */ type: string; array?: boolean; notNull?: boolean; default?: unknown; unique?: boolean; index?: boolean; } interface ReferenceIR { kind: "reference"; /** Identidade estável do campo (UUID), garantida no back. Sobrevive a rename. */ id?: string; /** Nome da entidade alvo. */ target: string; cardinality: "one" | "many"; notNull?: boolean; } interface OwnedIR { kind: "owned"; /** Identidade estável do campo (UUID), garantida no back. Sobrevive a rename. */ id?: string; /** `false` = 1:1, `true` = 1:N. */ array: boolean; /** * Forma do owned. Sem `mirror`: é a forma inline completa. Com `mirror`: são os * **campos locais** (extras), anexados à forma espelhada (ex.: `quantidade` num * item de pedido que espelha `produto`). */ shape?: Record; /** Espelha a forma de outra entidade. Resolvido no sync; pode coexistir com `shape` (locais). */ mirror?: string; /** Override do nome da tabela filha. */ table?: string; } type FieldIR = ColumnIR | ReferenceIR | OwnedIR; interface EntityIR { irVersion: number; name: string; fields: Record; /** Grupos de UNIQUE composto (nomes lógicos de campo). Ver `EntityOptions`. */ unique?: string[][]; /** Grupos de índice composto (não-único). */ index?: string[][]; /** Partição RANGE por tempo: `field` (nome lógico) + `interval` (ex.: "1d"). */ partitionBy?: { field: string; interval: string; }; /** Retenção da partição (ex.: "30d") — dropa partições cujo topo já passou. */ retention?: string; } /** * Uma regra de dispatch: amarra um `scope` a um predicado `when(principal)` e a um * extrator `params(principal)`. `when`/`params` são PUROS e SÍNCRONOS sobre o principal * em memória (decisão de dispatch, roda a cada request — sem I/O/await). Dado que não * está no token (ex.: departmentIds) entra no principal na AUTENTICAÇÃO, não aqui. */ interface DispatchRule

{ scope: ScopeDef; when: (principal: P) => boolean; params?: (principal: P) => Record; } /** Client escopado: `runAs`/`runAsGod`/`god`/`dispatcher` + entities resolvidos pelo ALS (deny fora). */ type ScopedClient>> = WeaveClient & { /** O client god cru (auth PRÉ-scope, boot, ETL, scripts) — não passa pelo ALS. */ readonly god: WeaveClient; /** Estabelece o scope pro callback (sync/async), devolve o retorno de `fn`. Params * exigidos/tipados quando o scope infere `{ param }`; scope sem params dispensa o objeto. */ runAs

(scope: ScopeDef

, ...rest: [P] extends [never] ? [fn: () => R] : [params: { [K in P]: unknown; }, fn: () => R]): R; /** God EXPLÍCITO pro callback (master, ou uma op cross-tenant consciente dentro de request). */ runAsGod(fn: () => R): R; /** * Constrói um dispatcher a partir de uma tabela `[{ scope, when, params? }]`: devolve um * callable `(principal, fn)` que roda `fn` sob o **1º** scope cujo `when(principal)` é true * (params via `params(principal)`). **First-match pela ordem** — overlaps são intencionais * e resolvem por ordem (mais específico primeiro; ex.: `department` acima de `admin`). * Nenhum casa → **deny** (`WeaveScopeError`, fail-closed). A tabela mora no APP (config sua, * gen-safe) e é tipada pelo principal `P` — mata o if-chain de role→scope sem nada * client-side no arquivo que o gen sobrescreve. */ dispatcher

(rules: ReadonlyArray>): (principal: P, fn: () => R) => R; }; /** * Cria um client ESCOPADO. Aceita um client god JÁ criado (`createScopedClient(weave)` — * COMPARTILHA a base, então `scopedWeave.god === weave`) ou as options (cria a base). Os * entities resolvem pelo client escopado ativo (setado por `runAs`/`runAsGod` via * AsyncLocalStorage); FORA de qualquer run → DENY (throw), nunca god. */ declare function createScopedClient>>(base: WeaveClient | ClientOptions): ScopedClient; /** O objeto como ele VOLTA da leitura (sem expand). `Infer`. */ type Infer> = InferEntity; /** O filtro do 1º argumento (find/update/delete). `InferWhere`. */ type InferWhere> = WhereInput; /** O patch de `updateOne`/`updateMany` — `InferInsert` com tudo opcional. `InferPatch`. */ type InferPatch> = Partial>; /** A ordenação (`opts.orderBy`). `InferOrderBy`. */ type InferOrderBy> = OrderByInput; /** @deprecated nome antigo de {@link InferPatch}. */ type InferUpdate> = InferPatch; interface PushOptions { /** Base URL do Weave. */ url: string; /** API key (`x-api-key`). */ key: string; /** Transporte. Default: `globalThis.fetch`. Nos testes: `app.hono.fetch`. */ fetch?: FetchLike; /** Caminhos confirmados (drops destrutivos), por nome de entidade. */ confirm?: Record; /** Valores de backfill (caminho → valor), por nome de entidade. */ fill?: Record>; /** * Renames de campo, por entidade: `{ entidade: { nomeAntigo: nomeNovo } }`. * Sem isso, renomear no código vira drop+add (com gate); aqui injetamos o id * existente no campo novo → o servidor detecta um RENAME (dado preservado). */ renames?: Record>; } /** Uma mudança no plano de migração (em vocabulário de objeto, nunca SQL). */ interface PlanChange { op: string; path: string; /** `auto` 🟢 · `confirm` 🔴 · `needsValue` 🟡 · `blocked` ⛔ */ risk: string; } interface MigrationPlan { changes: PlanChange[]; } interface PushResult { /** Entidades aplicadas (criadas/migradas). */ applied: string[]; /** Entidades que precisam de revisão (com o plano por risco). */ review: { name: string; plan: MigrationPlan; }[]; } /** * Empurra o entities-as-code pro Weave: serializa cada entidade (`toIR`) e aplica via * `/admin/entities` (plan/apply seguro). Aplica em **ordem de dependência** (a * entidade referida antes da que referencia). Devolve o que foi aplicado e o que * precisa de revisão (com o plano por risco) — em vocabulário de objeto, sem SQL. * * `confirm`/`fill` (por entidade) destravam drops confirmados e backfills. */ declare function pushEntities(entities: Record>, options: PushOptions): Promise; interface PushAllOptions { url: string; key: string; /** Entities já carregadas — `import * as entities from "weave/entities/index.js"`. */ entities: Record>; /** Scopes já carregados. Ausente/`{}` → nenhum scope a empurrar (muitos projetos não têm). * `ScopeDef` (não o default ``) pra aceitar scopes COM params inferidos. */ scopes?: Record>; fetch?: FetchLike; /** Drops confirmados / backfills, por entidade (resolução não-interativa). */ confirm?: Record; fill?: Record>; /** Origem, pro pending: "boot" | "cli" | "gui". */ source?: string; } interface PushAllResult extends PushResult { /** Scopes empurrados (só quando as entities convergiram; senão vazio). */ scopes: string[]; } declare function pushAll(opts: PushAllOptions): Promise; interface WeaveConfig { /** * Pasta onde o `weave gen` materializa tudo (`entities/`, `scopes/`, `index.ts`). * Default: `"weave"` na raiz do projeto. Ex.: `"app/weave"`. */ dir?: string; } /** Helper tipado pro `weave.config.ts` (igual `defineConfig` do Vite/Drizzle). */ declare function defineConfig(config?: WeaveConfig): WeaveConfig; interface IrToSourceOptions { /** Emitir `.$id(...)` em cada campo (estável, rename-safe). Default: false. */ withId?: boolean; /** * Predicado de ciclo `(from, to) → boolean`: a reference dessa entity (`from`) pro * alvo `to` está num ciclo e deve sair como thunk lazy (`() => to`). Ausente = tudo * eager (o `genProject` passa o predicado real; chamadas avulsas ficam eager). */ isLazyRef?: (from: string, to: string) => boolean; } /** Gera o source `export default defineEntity(...)` de UMA entidade (com imports). */ declare function irToSource(ir: EntityIR, options?: IrToSourceOptions): string; interface StoredCondition { path: string[]; op: string; value?: unknown; } type StoredFilter = StoredCondition | { and: StoredFilter[]; } | { or: StoredFilter[]; }; interface StoredProjection { mode: "include" | "exclude"; paths: string[][]; } interface StoredRule { verbs: string[]; rows: StoredFilter | null; fields: StoredProjection | null; } interface StoredScope { name: string; entities: Record; } /** Gera o source `export default defineScope(...)` de UM scope: cada regra amarrada à * entity por referência (`scopeRule(, …)`) + o import da entity. Resolve * id→nome nos paths. Normaliza a chave guardada (snake OU camel) pro nome lógico. */ declare function scopeToSource(scope: StoredScope, byName: Map): string; interface GenOptions { url: string; key: string; fetch?: FetchLike; } interface GenProject { /** Caminho relativo (dentro da pasta `weave/`) → conteúdo. */ files: Record; entities: string[]; scopes: string[]; } /** * Predicado `(from, to) → está num ciclo?`: a aresta `from → to` é cíclica sse `to` * consegue voltar em `from` por qualquer cadeia de references. Self-loops (`A → A`) * são tratados pelo `self()` à parte, então saem da adjacência. Alcançabilidade * memoizada por nó (schemas são pequenos). */ declare function buildLazyRefPredicate(irs: EntityIR[]): (from: string, to: string) => boolean; /** * Busca o estado do servidor (entidades + scopes) e gera a árvore de arquivos da * pasta `weave/`: `entities/.ts` (com `$id`) + barrel, `scopes/.ts` + * barrel, e `index.ts` (client). O CLI limpa a pasta e escreve isto. */ declare function genProject(options: GenOptions): Promise; interface PullOptions { url: string; key: string; fetch?: FetchLike; } /** Puxa os IRs remotos e gera o source de cada entidade. Devolve `nome.ts → conteúdo`. */ declare function pullEntities(options: PullOptions): Promise<{ files: Record; names: string[]; }>; declare class WeaveError extends Error { readonly status: number; constructor(message: string, status: number); } /** 401 — a API key falta ou é inválida. */ declare class WeaveAuthError extends WeaveError { constructor(message: string); } /** 403 — o scope nega o verbo/linha/campo. */ declare class WeaveScopeError extends WeaveError { constructor(message: string); } /** 404 — objeto inexistente (ou fora do alcance do scope). */ declare class WeaveNotFoundError extends WeaveError { constructor(message: string); } /** 400 — payload inválido (validação de borda). */ declare class WeaveValidationError extends WeaveError { constructor(message: string); } export { ClientOptions, Entity, FetchLike, type GenOptions, type GenProject, type Infer, InferEntity, InferInsert, type InferOrderBy, type InferPatch, type InferUpdate, type InferWhere, type IrToSourceOptions, type MigrationPlan, OrderByInput, type PlanChange, type PullOptions, type PushAllOptions, type PushAllResult, type PushOptions, type PushResult, ScopeDef, type ScopedClient, WeaveAuthError, WeaveClient, type WeaveConfig, WeaveError, WeaveNotFoundError, WeaveScopeError, WeaveValidationError, WhereInput, array, bool, bpchar, buildLazyRefPredicate, bytea, createScopedClient, date, defineConfig, float4, float8, genProject, int2, int4, int8, interval, irToSource, json, jsonb, numeric, pullEntities, pushAll, pushEntities, scopeToSource, text, time, timestamp, timestamptz, uuid, varchar };