UNPKG

@beignet/core

Version:

Core framework primitives for Beignet

577 lines (448 loc) 42.9 kB
# @beignet/core ## 0.0.48 ### Patch Changes - 2391a09: Harden provider failure semantics with isolated asynchronous instrumentation, level-aware Pino metadata redaction and owned-transport shutdown, bounded Upstash timeout policy and readiness, and validated Vercel Blob token/OIDC credential alternatives. ## 0.0.47 ### Patch Changes - 3847e21: Resolve trusted request metadata once per request from a server-level policy and share it with context factories, security hooks, rate limiting, and logging observers. ## 0.0.46 ### Patch Changes - 3184f87: Document and verify external TypeScript clients generated from Beignet OpenAPI documents. ## 0.0.45 ### Patch Changes - b9df150: Keep response validation, request parsing, client error classification, workflow transforms, idempotency mutations, webhook signatures, and ownership tokens correct at their edge cases. ## 0.0.44 ### Patch Changes - 07baa79: Modernize the package-shipped app architecture examples to use the current Zod UUID schema API. - 07baa79: Ship versioned Fetch runtime and devtools safety skills, teach core runtime safety conventions, keep Agent Auth guidance discoverable, and trust the new skills in generated apps. ## 0.0.43 ### Patch Changes - 19b9c52: Share storage-key validation, prefix composition, and public URL formatting across memory, local, S3, and Vercel Blob adapters. - 19b9c52: Default HTTP idempotency to actor scope with tenant isolation when present, authorize server uploads before reading file bytes, safely clean up failed pre-completion upload batches, and harden mail address formatting. - 19b9c52: Modernize generated Zod and Drizzle syntax, flush Pino logs during provider shutdown, strengthen shared credential redaction, add mail operation durations, and correct copied documentation examples. ## 0.0.42 ## 0.0.41 ## 0.0.40 ### Patch Changes - f7bcd30: Add push-assisted Next.js outbox draining after successful Unit of Work transactions while retaining cron recovery. ## 0.0.39 ## 0.0.38 ### Patch Changes - 443b9a1: Clarify post-commit delivery, listener ordering, cooperative job timeouts, stateless upload completion, and stable idempotency-key responsibilities. - 1081ac6: Harden HTTP response handling, synchronous upload cleanup, CLI path and registry diagnostics, provider context preservation, Redis subscription observability, and provider documentation. - d23b0b3: Continue versioned W3C trace context through outbox, event bus, BullMQ, and Inngest boundaries without making telemetry metadata part of delivery success. - 6bd52fc: Rename the canonical runtime port wiring file, value, and CLI config path to `infra/port-wiring.ts`, `initialPorts`, and `paths.portWiring`. - 7b918c4: Standardize bounded terminal-only runtime error reporting, structured Sentry metadata redaction, and isolated reporting across HTTP, jobs, schedules, tasks, listeners, and outbox drains. - 7e1a68e: Harden query transport, webhook timestamps, leases, idempotency, outbox drains, production devtools authorization, and transaction-scoped database execution. ## 0.0.37 ### Patch Changes - 7844a16: Add validated contract deprecation metadata, standards-based lifecycle response headers, and unique OpenAPI operation ID enforcement. ## 0.0.36 ### Patch Changes - 5c7f6bb: Harden agent capability execution with lazy Better Auth executors, runtime required-constraint checks, validated lifecycle data, and adapter test utilities. ## 0.0.35 ### Patch Changes - 2101386: Authorize agent capabilities against their exact parsed input and keep custom Agent Auth locations outside the Beignet execution bridge. - 2290c4a: Add typed, validated agent capability registries and execution, plus a Better Auth Agent Auth bridge with constraint-safe validation, verified principals, grants, and redacted protocol errors. - 42921da: Keep agent capability registries type-safe, observe pre-context failures, and preserve application error codes across Agent Auth execution modes. - 2a5b224: Preserve idempotency and outbox delivery guarantees on persistence and handler failures, enforce multipart limits from actual bytes, support Date and JSON query serialization, and add bounded MySQL deadlock backoff. - 74aad51: Replace the schedule-specific instrumentation sink with shared provider targets, serve bodyless HEAD responses from GET routes, improve missing JSON content-type diagnostics, and expose the auth error HTTP status. - db79263: Align route, listener, auth-provider, and webhook-integration APIs before 1.0. Route declarations now use an app-bound `createRoutes<AppContext>()` builder, listeners put their stable name first, Better Auth exports `createBetterAuthProvider(...)`, and vendor webhook verifiers live in `@beignet/webhooks-*` packages outside provider audits. - 397f106: Standardize framework-owned operational errors, degrade opaque OpenAPI path parameters safely, and add direct Redis, Pino, and Upstash adapters. - 40f4155: Refresh package-shipped agent guidance for app-bound route builders, configured route-builder paths, webhook integrations, and operational error responses. - d1c0efd: Make contract and contract-group OpenAPI metadata compose consistently across `meta()` and `openapi()` calls. - c403db2: Isolate use-case observers, authenticate operational routes before context creation, honor configured generated-test roots, correct feature-helper linting, preserve optional OpenAPI descriptions, and keep upload resets stable. - 4cc5254: Decompose the server runtime into focused internal modules while preserving the existing public API and request behavior. - 7d0c795: Expose stable named provider types while keeping private config schemas out of package declarations and preserving validated config and contributed-port inference. Drizzle's Postgres and MySQL config schema constants are now internal; use the exported config interfaces for validated shapes. ## 0.0.34 ### Patch Changes - 8226b4c: Isolate notification channel failures, add app-owned preference checks, provide independently retryable queued delivery through existing job dispatchers, and document the app structure for queued notification workers. - 9345cc9: Stabilize the pre-1.0 public surface around factory-only providers, canonical server and testing imports, consistent memory naming, and the removal of deprecated aliases. ## 0.0.33 ### Patch Changes - 379a351: Add outbox admin ports and CLI tooling to inspect, requeue, purge, and prune durable outbox messages. - c909142: Add per-attempt job timeouts, app-owned job execution hooks, and a locks-backed execution lease hook across inline, outbox-inline, BullMQ, and Inngest workers. - c514ffc: Document the Next.js cached request-context convention separately from React Query prefetching, and update generated agent guidance to use `lib/server-context.ts` for shared Server Component request state. - ae6d7f9: Document the Next.js server prefetch convention and teach generated agent guidance to preserve contract query keys while replacing server query functions with direct use-case calls. - efe16f4: Add active tracing spans and an OpenTelemetry provider with isolated, low-cardinality duration, failure, and provider-operation metrics. Background providers resolve lazy contexts inside real spans, and the task CLI now runs through the traced task executor. - 0c6c0ee: Make generated app test and database scripts package-manager neutral by using `tsx`, and refresh package testing docs to avoid Bun-specific snippets. - 450ce71: Add opt-in runtime integrity checks for workflow registries, teach the CLI a central listener registry, and document serverless-safe boot checks. - 2fe26a4: Add first-class security headers and CSRF server hooks, install the security headers baseline in generated apps, and warn when production apps omit it. - ab8b288: Refresh package-shipped skills with current tenancy and runtime-integrity conventions. - de3e0d2: Tighten tenant-scope enforcement in doctor and generated billing code. `beignet doctor --strict` now detects explicit raw `tenantId` repository boundaries in hand-authored Drizzle ports and checks scoped tenant/workspace predicates for `tenantScopeId(scope)` drift. The payments generator now uses `TenantScope` for billing tenant lookups. - 08e2d3e: Add a branded tenant scope primitive and generate tenant-scoped repositories that accept `TenantScope` instead of raw tenant IDs. - 4341860: Add trusted proxy request metadata helpers and wire rate-limit and CSRF hooks to the shared policy. - 3b0f288: Add locks-backed unique job declarations and a dispatcher wrapper that suppresses duplicate dispatches for a bounded TTL. - 61d9053: Harden uploads with supported content-type signature checks, optional SHA-256 checksums, and app-owned file verification hooks. - f263650: Harden generic webhook verification with strict unknown-event defaults and opt-in HMAC timestamp tolerance. ## 0.0.32 ### Patch Changes - 671b986: API coherence: definition kinds, app-bound uploads, honest inline retry, and deterministic memory adapters. - `FlagDef` now carries `kind: "flag"` as its definition discriminator, and the value type moves to `valueKind` (`FlagEvaluationDetails.kind` is also renamed `valueKind`; types `FlagKind` and `FlagKindForValue` are now `FlagValueKind` and `FlagValueKindForValue`). `defineWebhook` results carry `kind: "webhook"` and `defineSearchIndex` results carry `kind: "search-index"`, so every definition subsystem shares the same discriminator grammar. The OpenFeature provider and devtools flag panel follow the rename. - New `createUploads<AppContext>()` in `@beignet/core/uploads` returns an app-bound `defineUpload`, matching the jobs/schedules/tasks/notifications/ listeners factories. The bound builder infers the upload name, metadata schema, context, and `onComplete` result without explicit type arguments; apps create it once in `lib/uploads.ts`. - `createInlineJobDispatcher(...)` now honors a job's declared retry policy: failed dispatches retry in-process with the policy's delays (injectable `sleep` option for tests), payload validation failures never retry, and jobs without a policy run exactly once. - `createMemoryOutbox({ id, now })` and `createMemoryIdempotencyStore({ now })` accept injectable ID and clock factories instead of hardcoding `crypto.randomUUID()` and `new Date()`. - The BullMQ provider validates unsupported retry options (`maxDelay`, custom `factor`, `jitter`) eagerly at `createBullMQJobWorker(...)` creation instead of only at first dispatch or processing. - f759611: Retry policies now run in exactly one layer for outbox-delivered jobs. The inline job dispatcher exposes a single-attempt dispatch under a well-known symbol; `drainOutbox(...)` detects it and runs the handler once per pass, letting the outbox reschedule failures with the job's own policy instead of stacking in-process retries (and their real backoff sleeps) inside every delivery attempt. Durable providers are unaffected. The inline dispatcher also gains a `retry: false` option for callers that own retries themselves, and `createTestPorts(...)` now threads its frozen clock and ID generator into the memory idempotency store and outbox. - f759611: Provider factory options now resolve through one framework-owned rule: `ProviderConfigDef` gains an `overrides` map that merges defined values over env-derived input before validation, and every first-party provider factory uses it instead of hand-rolled schema defaults and setup-time fallbacks. The precedence is now uniform — defined factory options win over environment variables in all thirteen providers. This flips the previous env-wins behavior of `provider-cache-redis`, `provider-locks-redis`, and the storage, search, and blob providers; set the env var (or drop the option) if you relied on env winning. `installProviderForTest(...)` gains an `env` option that resolves config through the same loader, and unreachable missing-config guards in the pino and inngest factories are gone. - eb680ef: Provider naming now follows one implementation-first order matching the factories. `@beignet/provider-redis` is renamed `@beignet/provider-cache-redis` (the package fills the cache port; the raw client stays as the `ctx.ports.redis` escape hatch) with `redisCacheProvider`, `createRedisCacheProvider`, and provider name `cache-redis` matching `locks-redis`. Default consts flip to implementation-first: `loggerPinoProvider` is now `pinoLoggerProvider`, `mailResendProvider` is now `resendMailProvider`, and `mailSmtpProvider` is now `smtpMailProvider`. CLI starter templates and the `redis-cache` provider preset wire the new names. No aliases are kept. - 671b986: Remove the `defineDomainEvent` alias (and the `DomainEventDef`/ `InferEventPayload` re-exports) from `@beignet/core/domain`. Declare domain events with the canonical `defineEvent(name, { payload })` from `@beignet/core/events` — the alias returned the exact same `EventDef` and only differed by its positional signature. The structural `DomainEventDef` port type in `@beignet/core/ports` is unchanged. - 671b986: `defineEntity(...).methods((self) => ...)` now types `self` as the entity's base instance (validated props plus `with` and `toJSON`) instead of `any`, so method bodies are type-checked against the entity's own schema. The new `EntityBaseInstance` type is exported from `@beignet/core/domain`. - 671b986: Upload failures now throw condition-specific error classes matching the framework's class-per-condition convention: `UploadNotFoundError`, `InvalidUploadActionError`, `InvalidUploadMetadataError`, `InvalidUploadFileError`, `UnauthorizedUploadError`, `UploadObjectNotFoundError`, `UploadBodyTooLargeError`, and `InvalidUploadBodyError`. `UploadError` remains the shared base class (its constructor is now protected), so existing `instanceof UploadError` checks and `code`/`status` reads keep working unchanged. ## 0.0.31 ### Patch Changes - d77e367: New `@beignet/core/memo` subpath: `createMemo(fn)` deduplicates a lookup for the lifetime of one request — the first call runs, later calls with the same arguments (from context, policies, use cases) share the same value and in-flight promise. The server scopes every HTTP request and `runServiceContext(...)` execution automatically; the cache dies with the request, so there is no TTL, no invalidation policy, and no cross-request staleness. Mutations pair with `memoized.invalidate(...)`, `runMemoScope(fn)` scopes scripts and tests, and devtools records `memo.hit`/`memo.miss` events with fill durations. The generated CLAUDE/AGENTS capability index now points at it. ## 0.0.30 ### Patch Changes - 38d1770: Every published package now rebuilds in `prepack`, so publishing can never ship a stale `dist/` again (the 0.0.28 packaging incident). No runtime behavior changes. - b601494: Rate-limit denials now set a standard `Retry-After` header on 429 responses whenever the limiter reports a reset time, so generic HTTP clients can back off without parsing the error body. Powering this, `AppError` (and `createAppError` helpers) accept an optional `headers` option that the server merges onto the HTTP response when the error crosses the boundary. ## 0.0.29 ## 0.0.28 ### Patch Changes - 57504c5: Add `server.rawRoute(...)`: build handlers for routes that cannot be contracts — third-party callbacks, signature-verified webhooks, streaming endpoints — that still run the full pipeline (hooks, context creation, instrumentation, framework error mapping) with the request body left unconsumed. The Next.js webhook, payment webhook, schedule, and outbox drain route factories now run through this pipeline automatically when the server exposes `rawRoute`, with a new `pipeline` option for route identity and hook metadata. - 57504c5: Record a per-stage timing breakdown for every request — `onRequest` hooks, parsing, context creation, `beforeHandle` hooks, handler, and send. `afterSend` hooks receive it as `stages`, recorded `request` events carry it, and the devtools waterfall renders the stages as sub-bars under each request span so slow context creation or a slow handler is visible per request. - 3f4728d: Run route hooks before server beforeHandle hooks, store only final route-owned idempotency responses, and make idempotency scope keys collision-resistant. ## 0.0.27 ### Patch Changes - 88200a0: `beignet task run <name> --tenant <id|slug>` passes the tenant to the app's `createTaskContext` and `stopTaskContext` separately from task input, so tenant selection no longer has to live in task input schemas. `@beignet/core/tasks` exports the `TaskRunContextArgs` contract for those registry exports, and the task run result includes the tenant when one was passed. - 88200a0: Server hardening: `ip`-scoped rate limits now fail fast at startup when `createRateLimitHooks(...)` has no explicit `ipSource` (pass `ipSource: "none"` to keep the shared `ip:unknown` bucket), backed by a new optional `validate` phase on server hooks; `server.runServiceContext(...)` runs service work inside a scoped ambient context frame so seeds and one-off scripts stay safe under top-level await on Bun 1.3.x; the in-memory rate limiter now prunes expired windows instead of growing unbounded across distinct keys. - afbe1b3: The app-architecture skill now points at `server/seed.ts` as the usual app seed entrypoint, matching the CLI convention. - f2461a9: Add lazy Next route server loaders and update generated route files and package docs to avoid booting providers during production build imports. ## 0.0.26 ### Patch Changes - 104302c: Refresh package-shipped TanStack Intent skills and add package skills for Drizzle database providers, Better Auth, React Hook Form, and React uploads. ## 0.0.25 ### Patch Changes - 1f84b39: Add provider table metadata diagnostics, Drizzle operational schema exports, and `beignet db schema generate` for app-owned migration flows. - 7c83da7: Refresh package-shipped TanStack Intent skills to match current Beignet app structure, generators, route helpers, and React Query cache helpers. ## 0.0.24 ### Patch Changes - 9d518c0: Generate server-only boundary markers as side-effect imports so app linting can keep a consistent unused-import rule. - 91bc9b5: Harden framework security defaults for generated tenancy, auth secrets, CORS, body limits, uploads, devtools, OpenAPI, rate-limit IP sources, public storage, and Meilisearch query fields. ## 0.0.23 ### Patch Changes - 02f09fb: Add Drizzle audit log setup statements and `AuditLogPort` factories for SQLite, Postgres, and MySQL. ## 0.0.22 ### Patch Changes - Add app-owned readiness helpers, first-party provider health checks, generated `/api/ready` routes, and doctor readiness hints. ## 0.0.21 ### Patch Changes - Ship TanStack Intent agent skills with Beignet packages and scaffold generated apps with Intent skill-loading guidance. ## 0.0.20 ## 0.0.19 ## 0.0.18 ### Patch Changes - 622ed66: Expose Drizzle provider ports through `db.drizzle` while keeping `db.db` as a backwards-compatible alias, and update generated app wiring to use the clearer name. ## 0.0.17 ## 0.0.16 ### Patch Changes - 712fb3f: Clarify the canonical route story for payment webhooks versus generic inbound webhooks and document verifier package setup semantics. ## 0.0.15 ### Patch Changes - 73a682a: Make the type-preserving curried route-group form the canonical Beignet route API across generated apps, docs, READMEs, and examples. `beignet doctor` now warns when feature route groups use the direct generic form, and the direct overload is deprecated because TypeScript erases per-route contract output checks there. - 2a02469: Add `createErrorReportingHooks(...)` for capturing unexpected HTTP failures through `ctx.ports.errorReporter`, and wire generated apps to install the hook with a no-op local reporter by default. - 7d3c980: Add provider-neutral inbound webhook definitions, verifiers, HMAC verification, memory test verifier, and a generic Next.js webhook route adapter. ## 0.0.14 ### Patch Changes - 0b106c3: Add first-class error reporting primitives and a Sentry-backed error reporting provider. - 6828442: Add first-class feature flag primitives, an OpenFeature-backed flags provider, and devtools support for flag evaluation, exposure, and tracking events. - edf5ddc: Add first-class entitlement primitives for product access checks, devtools-ready entitlement decision observation, and doctor checks for entitlement wiring drift. Generated billing slices expose a billing-backed entitlements port. - bcd3864: Add lease-backed lock primitives and a Redis-backed locks provider. - d51a35f: Add the provider-neutral payments port, memory payments adapter, Stripe payments provider, Next.js payment webhook route helper, `beignet make payments`, and first-class payments devtools view. - 655c101: Add keyed authorization batch checks and best-effort policy decision observation, plus a first-class devtools watcher/view for policy decision events. - bcd3864: Add a provider-neutral search port, memory adapter, and Meilisearch provider. ## 0.0.13 ### Patch Changes - cac3d61: Align shared-domain, server context, and workflow-builder docs with current app conventions. - 7ccbab1: Generate idempotency keys without `crypto.randomUUID` when it is unavailable. In non-secure browser contexts — plain `http://` on any host other than `localhost`, such as a LAN IP or a Tailscale hostname — the Web Crypto API is not exposed, so `crypto.randomUUID()` threw and every mutation on a contract with idempotency metadata failed before sending. The client and the React Query integration now fall back to `crypto.getRandomValues` and then `Math.random`, so mutations work over plain HTTP. ## 0.0.12 ## 0.0.11 ## 0.0.10 ## 0.0.9 ### Patch Changes - 6ebec8c: Change the idempotency storage-key separator from NUL (`\u0000`) to the ASCII unit separator (`\u001f`) so storage keys can be persisted in Postgres, which rejects NUL bytes in text columns. Existing idempotency rows written with the old separator will not be matched after upgrading; expired rows clean themselves up, and in-flight keys can be cleared by truncating the idempotency table. - 6ebec8c: Provider packages can now declare `variants` in their `beignet.provider` manifest — one entry per selectable backend with its own env requirements and registration tokens. `beignet doctor` checks required env vars only for the variants an app actually registers, and reports a single registration hint listing all variants when none is wired. The Drizzle database provider uses this to describe its sqlite, postgres, and mysql backends. - 1bb42a3: Rename `@beignet/provider-drizzle-turso` to `@beignet/provider-db-drizzle`, with databases as subpath exports. Import from `@beignet/provider-db-drizzle/sqlite`; `DrizzleTurso*` symbols are now `DrizzleSqlite*`, the provider registers as `drizzle-sqlite`, and the connection env vars are `SQLITE_DB_URL` and `SQLITE_DB_AUTH_TOKEN` (the auth token applies to hosted libSQL such as Turso). Provider packages now follow `provider-<capability>-<implementation>` naming, and multi-backend implementations add backends as subpaths — `/postgres` and `/mysql` are planned next. ## 0.0.8 ### Patch Changes - 74a6859: Add dev-default provider factories for the mail and notifications ports. `createMemoryMailerProvider(options?)` from `@beignet/core/mail` contributes a memory-backed `mailer` port and records `mail.sent` devtools events. `createInlineNotificationsProvider(options?)` from `@beignet/core/notifications` contributes a `notifications` port backed by the inline dispatcher, building an app service context lazily on each send. - 74a6859: Validate upload prepare and complete request bodies. Malformed JSON, a missing or non-array `files` value, non-object file entries, and completed files without string `uploadId`/`key` fields now return a structured 400 `INVALID_UPLOAD_BODY` error with `details.issues` instead of crashing with a 500. `UPLOAD_NOT_FOUND` now lists the registered upload names and explains that routes resolve the `defineUpload(...)` name, not the `defineUploads({...})` registry key. `createUploadRouter(...)` now throws at construction when two upload definitions share the same name instead of silently keeping the last one. ## 0.0.7 ## 0.0.6 ## 0.0.5 ## 0.0.4 ### Patch Changes - 8bcb31f: Mark package READMEs with Beignet's experimental alpha status and 0.0.x stability expectations. - 5d5e303: Add a database test harness that coordinates app-owned database fixtures, factory sequence resets, seed execution, and cleanup. - 31c7e66: Deepen DB, outbox, and jobs devtools panels with domain-specific metrics, correlation fields, attempt/retry context, and richer row details. Provider instrumentation now adds provider names to typed provider events so those panels can group provider work consistently. - 8297c7c: Add contract, route, location, and status diagnostics to framework validation and response contract errors. - 4c1cb16: Formalize provider package manifest metadata with exported core types and validation, and have doctor warn on malformed installed provider metadata before using provider-derived diagnostics. - ac78cdf: Make `createAuthHooks` the single route-scoped auth hook API. The factory is now curried — `createAuthHooks<AppContext>()({ resolve })` — so added context fields are inferred from `resolve` instead of passed as a type argument, and a new optional `headers` schema validates the raw lowercase request header record before `resolve` runs, giving `resolve` typed credential headers without contract casts. On `required()` hooks a header schema failure returns a framework-owned 401; `optional()` hooks skip auth resolution; `public()` hooks never parse headers. `defineRouteHook` (and the `RouteHookBuilder` types) are removed — write non-auth route hooks as plain `RouteHook` object literals. - 2da5a05: Report installed-but-unregistered optional providers as informational doctor hints. Provider packages can declare `registration.severity: "hint"` in their `beignet.provider` manifest metadata, and `@beignet/devtools` now uses it, so removing `createDevtoolsProvider()` from `server/providers.ts` no longer fails `beignet doctor --strict`. - 780955c: Add Drizzle/Turso-backed durable idempotency storage with setup SQL, root and transaction-client ports, and Unit of Work rollback coverage for idempotency and outbox writes. - 1a79090: Emit Node-compatible ESM: all relative imports in published packages now carry explicit .js extensions, fixing ERR_MODULE_NOT_FOUND when running the CLI or importing package dist files under plain Node. - 7fe855b: Add OpenAPI schema converters and operation overrides for custom schemas, multipart uploads, binary responses, and streaming media. - 079bf59: Clarify unsupported catch-all contract path diagnostics and document that catch-all route files belong to runtime adapters, not individual contracts. - 82c48dc: Add canonical test port and context fixtures, and update generated tests to use them. - 5a51869: Add schedule run attempt metadata and align durable workflow retry, backoff, terminal failure, and dead-letter documentation. - 89390fe: Harden `createRateLimitHooks(...)` against client-controlled inputs. The denial response details no longer include the bucket key — clients now see only `scope`, `retryAfterSeconds`, and `resetAt`and each denial emits a `rateLimit.denied` instrumentation event with the key, scope, limit, and window so operators keep bucket visibility through the devtools `rateLimit` watcher. `ip`-scoped limits now default to the last `x-forwarded-for` entry (the address appended by the platform's trusted proxy) instead of the client-controlled first entry. The new `ipSource` option selects `"x-forwarded-for-last"` (default), `"x-forwarded-for-first"`, or a custom resolver function, replacing the previous `getClientIp` option. - 89390fe: Add `installProviderForTest(...)` to `@beignet/core/testing` for running provider setup against test ports with merged provider-contributed ports and start/stop lifecycle runners, and export the `AnyServiceProvider` type from `@beignet/core/providers`. - 303ba07: Define the public HTTP adapter contract and expose the Web Fetch adapter implementation. - 2da5a05: Reduce per-request work in server dispatch: the fallback 404/405 hook pipeline is now built once at server creation instead of per unmatched request, unmatched requests scan the route registry with a single pattern test per route, and the registry is re-sorted lazily before the next dispatch instead of on every registration. - 493d23b: Make the framework own context assembly with a server context blueprint and first-class service contexts. - `createServer(...)` (and the Next/Web adapters) replace the `createContext` option with `context`. Gate-less contexts keep the plain request-factory shorthand; contexts that declare a `gate` must use the blueprint form `{ gate: (ports) => ports.gate, request, service }`. Returning `gate` from a context factory or hook addition is now a compile error. - The gate port gains `gate.attach(ctx)`: it attaches a live, non-enumerable `ctx.gate` getter that re-binds against the receiving object on every access, so identity changes (including auth-hook elevation) can never authorize against a stale context, and spread copies drop the gate loudly instead of silently keeping stale identity. `bind(...)` remains the low-level primitive. - Servers expose `createRequestContext(req)` and `createServiceContext(input?)`; the optional `context.service` factory powers schedule, outbox, command, and background contexts. Provider `setup`, `start`, and `stop` receive a late-bound `createServiceContext` so infra providers no longer hand-build background contexts. - `createTestContextFactory(...)` now attaches the gate after all `extra` and override fields merge, fixing a stale-identity bug in tests. - CLI templates, generators, and doctor diagnostics emit and check the new context blueprint and service-context wrappers. - 493d23b: Fix `.errors()` on contract builders and contract groups to merge with previously declared catalog errors instead of replacing them. Contracts created from a group with shared catalog errors now keep the union of group and route errors at runtime and in inferred client error types, later declarations win when the same catalog key is declared twice, and multiple catalog codes can share one status across calls. Previously, route-level `.errors(...)` silently dropped group-declared errors from contract metadata, losing both server-side code enforcement and client error typing. - 44f1192: Move first-party provider diagnostics to package-owned `beignet.provider` manifest metadata and have doctor read installed provider package manifests. - 2aa77ca: Add static provider metadata and provider wiring diagnostics for generated apps. - eda7b59: Clarify that app-owned error details are public response data and should be mapped explicitly rather than automatically redacted by the framework. - 90c2e48: Add typed operational command definitions and a `beignet make command` generator for feature-owned app commands. - ac78cdf: Add `createScheduleRoute(...)` to `@beignet/next` for triggering one registered schedule from a serverless cron route, with the same fail-closed bearer auth and JSON envelope conventions as `createOutboxDrainRoute(...)`. Unknown schedule names throw when the route module loads. The inline schedule runner in `@beignet/core/schedules` now accepts `instrumentation` and `instrumentationContext` options and records `schedule` devtools events (`started`, `completed`, `failed`) itself. Recording failures are isolated from schedule execution and reported to `onHookError`. `createScheduleRoute(...)`, `beignet schedule run`, and generated cron routes use this instead of hand-rolled lifecycle hooks. Security: cron route bearer secrets in `createScheduleRoute(...)` and `createOutboxDrainRoute(...)` are now compared with a timing-safe SHA-256 digest comparison instead of `!==`. - 89390fe: Decouple devtools from app code with server-owned instrumentation. - `@beignet/core/tracing` is a new dependency-free subpath with the W3C trace primitives (`TraceContext`, `createTraceContext`, `createChildTraceContext`, `parseTraceparent`, `createTraceparent`, `createTraceId`, `createSpanId`). App context types now use `Partial<TraceContext>` instead of importing `DevtoolsTraceContext` from `@beignet/devtools`. - `createServer(...)` owns request instrumentation through a new `instrumentation` option (`ServerInstrumentationOptions | false`). The server resolves request IDs and trace context before user hooks and context creation, passes them to context factories as `requestId` and `trace`, writes `x-request-id`/`traceparent` response headers by default, and records request/error events into the instrumentation port resolved from final ports (`ports.instrumentation`, then `ports.devtools`). The ambient request context (`enterActiveRequestContext` and friends) moved into `@beignet/core/server`. - `createUseCase(...)` instruments runs by default, resolving the instrumentation port from `ctx.ports` per run; opt out with `instrumentation: false`. App `onRun` observers run in addition. - `createInstrumentedAuditLog({ audit, instrumentation })` in `@beignet/core/ports` replaces `createDevtoolsAuditLog`. - `createServer(...)` gains `validateResponses` (default `true`) to skip route-owned response validation, mirroring the client option. - Removed from `@beignet/devtools`: `createDevtoolsHooks`, `createDevtoolsUseCaseObserver`, `createDevtoolsAuditLog`, and the trace/request-context modules. Apps now only need `createDevtoolsProvider()` plus the devtools route; deleting both leaves the rest of the app compiling and running unchanged. - `@beignet/next` cron and upload helpers resolve their instrumentation sink with `resolveProviderInstrumentationPort(ctx.ports)` instead of hardcoding `ports.devtools`. - `beignet create` templates generate the decoupled shape. - 16cc113: Clarify the canonical route registration story and align generated starters on `app-context.ts`. - e9c3209: Add reusable actor, tenant, audit assertion, and default-header request helpers for production app tests. - ac78cdf: Split the client `validate` config flag into `validateInput` (default false) and `validateResponses` (default true). Client-side input validation failures now throw a client-source `ContractError` with code `INPUT_VALIDATION_ERROR` and no HTTP status instead of a synthetic 422 `VALIDATION_ERROR`. Setting `validateResponses: false` returns success bodies as-is and classifies non-2xx responses structurally while keeping `INVALID_JSON` transport errors. - cca08b1: Align generated apps and package docs around the canonical auth, policy, and AppContext model. - ac78cdf: Add server registration and dispatch guarantees. `createServer(...)` now fails at startup when a contract's `pathParams` object schema does not match the `:param` keys in its path template (non-introspectable Standard Schemas are skipped), and when two contracts register the same name, since typed clients, OpenAPI operations, and devtools key on contract names. Requests that match a registered path with an unregistered method now receive a framework-owned `405 METHOD_NOT_ALLOWED` response with an `Allow` header listing the registered methods instead of a `404`; `HEAD` is intentionally not mapped to `GET` handlers. The 405 flows through the same hook and error-ownership pipeline as the 404 fallback, so typed clients surface it as an HTTP error rather than contract drift. - a67c637: Add Beignet runtime boundary markers and extend `beignet lint` to catch client-safe roots that value-reach server-only code. - 7b0f708: Add first-class outbox instrumentation and devtools visibility for delivered, retried, and dead-lettered messages. - 246c66c: Add idempotency entry and provider instrumentation testing helpers for app and provider test suites. - 242f220: Add provider-focused testing helpers for recording jobs and schedules plus assertions for events, mail, notifications, storage, outbox workflows, and provider intent. - 493d23b: Add typed provider-contributed ports. `InferProviderPorts` (replacing `ProvidedPortsOfList`) merges the ports a provider list contributes so apps can type `ctx.ports` as `AppPorts & InferProviderPorts<typeof providers>` without casts. The curried `definePorts<AppPorts>()({ bound, deferred })` form replaces throwing stub boilerplate: deferred keys boot as descriptive placeholders and `createServer(...)` fails startup with the unbound key list (configurable via `onUnboundPorts: "error" | "warn" | "ignore"`). App-local providers can declare required ports, app context, and service-context input through the curried `createProvider<Requires, Context, ServiceInput>()` form, which types `setup({ ports, createServiceContext })` and lifecycle contexts end to end. CLI templates and `beignet make` generate and maintain the new forms. - 8063d38: Rename the contract front door to `defineContract`/`defineContractGroup`, rename operational commands to tasks (`@beignet/core/tasks`, `defineTasks`, `runTask`, `beignet task run`, `beignet make task`, `server/tasks.ts`, `features/<feature>/tasks/`, `paths.tasks`), and standardize context binding: context-free declarations stay top-level (`defineEvent`), while context-bound definitions come from per-capability factories (`createListeners`, `createJobs`, `createSchedules`, `createNotifications`, `createTasks`) called once in `lib/`. Top-level context-generic `defineListener`, `defineJob`, `defineSchedule`, and `defineNotification` are removed. - 905da0a: Audit ports can be wrapped with `createAmbientAuditLog` to fill actor, tenant, and correlation ids from the ambient request context at record time — including inside per-transaction port rebuilds — and `requireSession`, `requireUser`, `requireUserId`, `requireTenant`, and `requireTenantId` are now exported from `@beignet/core/ports`, throwing framework-owned 401/403 errors. - 192c6ad: Typed clients now attach idempotency keys automatically from contract metadata (override with `idempotencyKey`), React Query mutations keep the key stable across retry attempts, and the shared client error helpers `contractErrorMessage` and `rootFormError` are now exported by @beignet/core/client and @beignet/react-hook-form. - 192c6ad: Rename `defineFactory` to `createFactory` and `defineEnv` to `createEnvLoader` to match the naming convention: define declares things you register, create returns runtime objects you call. - 192c6ad: beforeSend hooks now run for native web Responses with a headers-only view (`native: true`), so CORS, request-id, and trace headers reach streamed responses; idempotency reservations are released for streamed responses instead of compensating in afterSend. - 192c6ad: Routes can bind a contract directly to a use case with `{ contract, useCase }` — status is inferred from a sole 2xx response, input defaults to merged path/query/body parts, and validated inputs are not re-parsed when the use case reuses the contract schema by reference. Full `handle` routes remain the escape hatch for headers, streaming, and multi-status responses. - 255527d: Add `createTestContext` for testing jobs, listeners, schedules, notifications, and tasks; make `createTestPorts` overrides accept typed partial ports without casts; default the test audit port to ambient enrichment; add `transaction.outbox` to flush buffered domain events on commit; add `defineServerContext` so apps can share one context blueprint between the server and tests. - ac78cdf: Enforce contract `meta.idempotency` at the HTTP boundary with the new `createIdempotencyHooks(...)` server hook. The hook reserves the client key after request parsing, replays completed matching responses with an `idempotency-replayed: true` header, and rejects in-progress and conflicting keys. The server now maps uncaught `IdempotencyConflictError` and `IdempotencyInProgressError` primitives to framework-owned `409` responses using the new `httpErrors.IdempotencyConflict` and `httpErrors.IdempotencyInProgress` catalog entries, so apps no longer need to re-map idempotency primitives to app-local catalog errors. `runIdempotently(...)` remains the workflow-level primitive for non-HTTP work. `beignet doctor` recognizes the new `httpErrors` catalog entries. ## 0.0.3 ### Patch Changes - 3160184: Add `beignet db generate|migrate|seed|reset`, scaffold standard seed/reset database entrypoints, and expose a factory reset helper for test data workflows. - 254ef6d: Add scoped route hooks for route and route-group policy, update auth hooks to expose public/optional/required route-hook factories, and teach CLI route inspection about curried route groups. - 4cb1784: Add first-class upload router primitives, a typed browser upload client, a React upload adapter, Next.js upload route helper, S3-compatible direct upload signing, devtools upload watcher support, an upload generator, and a first-class `beignet make feature` command with optional policy, event, job, and upload artifacts for the standard vertical slice. Add first-class job retry helpers, outbox retry policy integration, and job retry/dead-letter devtools events. Add a Next.js outbox drain route helper and doctor warnings for serverless background-work footguns. - 8bd9085: Add `@beignet/web` as a framework-neutral Web Fetch adapter, include a `@beignet/web/testing` route test harness, and have `@beignet/next` reuse the Web adapter for standard Request/Response handling. ## 0.0.2 ### Patch Changes - 90b29ad: Add pagination primitives and generate list responses with `items` and `page`. - 07fa19c: Add durable outbox primitives for transactionally recording events and jobs, plus a Drizzle/Turso outbox adapter. - 08bae67: Add test factory and seed primitives under `@beignet/core/testing`. - 730a818: Add idempotency primitives for retry-safe commands, webhooks, and jobs. - a79f60c: Add first-class notification primitives, devtools notification watcher support, and dependency-direction lint coverage for feature workflow folders. ## 0.0.1 - Initial Beignet release under the `@beignet` npm scope.