Initial Commit

This commit is contained in:
2026-05-27 23:29:53 +01:00
commit fbc70f96e6
10000 changed files with 1102152 additions and 0 deletions

View File

@@ -0,0 +1,71 @@
# Add @suaveplan/api-plugin-site
**Package**: `@suaveplan/api-plugin-site`
**Status**: PROPOSED
**Type**: new-package (migration from suaveplan)
- **Spec delta**: ./specs/api-plugin-site/spec.md
## Why
Genesis needs the multi-site / multi-domain capability `@suaveplan/api-plugin-site@1.0.21` ships upstream so consumer apps can persist `site` records (name / slug / theme / settings / push) under SurrealDB, resolve incoming `Host` headers to a site through a single canonical service, and expose public + private OpenAPI Hono routes for site management. The upstream package additionally bootstraps a default site on `organization:created` and emits `site:settings:updated` whenever settings change so CDNs and downstream consumers can react.
The upstream library exists at `/mnt/s/web/suaveplan/packages/server/api-plugin-site` (11 src files, partial test coverage, three `as any` casts in `plugin.ts`, runtime-monkey-patched `updateSettings`, missing-domain bug in `addDomain`, no OTel surface, no typed error registry). This change lands a single, enterprise-grade `@suaveplan/api-plugin-site@0.1.0` that fixes every flagged smell from the upstream enterprise audit (`/mnt/s/web/suaveplan/enterprise/api-plugin-site.md`) at parity with the upstream feature surface.
## What changes
- ADDED: `SITE_CODES` / `SiteError` — `defineCodes("SITE", […])` registry of 14 codes (`INVALID_OPTIONS`, `SERVICE_NOT_AVAILABLE`, `SITE_NOT_FOUND`, `SITE_LIMIT_EXCEEDED`, `DOMAIN_LIMIT_EXCEEDED`, `DOMAIN_ALREADY_CLAIMED`, `LAST_DOMAIN_REMOVAL`, `DOMAIN_NOT_FOUND`, `INVALID_DOMAIN`, `VALIDATION`, `BOOTSTRAP_FAILED`, `STORAGE_ERROR`, `ROUTE_PREFIX_COLLISION`, `RESOLUTION_FAILED`) extending `SuaveplanError`.
- ADDED: `SiteSchema`, `CreateSiteSchema`, `UpdateSiteSchema (.strict)`, `SitePublicInfoSchema`, `SiteIdParamSchema`, `SiteSettingsSchema`, `SiteThemeSchema`, `SiteStateNumberSchema` — inlined Zod surface for the site entity.
- ADDED: `DomainSchema`, `AddDomainRequestSchema/ResponseSchema`, `RemoveDomainRequestSchema/ResponseSchema`, `DomainResolveParamSchema/ResponseSchema` — inlined Zod surface for the domain entity.
- ADDED: `ApplePushConfigSchema`, `FirebasePushConfigSchema`, `PushConfigSchema`, `PushConfigValidationResponseSchema`, `validatePushConfig` — push-config schema + pure validator mirroring the SurrealDB `fn::site::push::validate`.
- ADDED: `SitePluginOptionsSchema`, `SitePluginConfig`, `SitePluginOptionsInput`, `DEFAULT_CONFIG`, `mergeConfig` — Zod-validated boundary for plugin options with frozen defaults.
- ADDED: `normalizeDomain` — pure, mirroring `fn::site::domain::normalize`.
- ADDED: `SiteDb` — structural db port consumed by services (positional-bind `query` + typed `create` / `update`).
- ADDED: `SiteService` — canonical CRUD: `create`, `createDefaultSite`, `getById`, `requireById`, `listByOrganization`, `countByOrganization`, `update`, `updateSettings`, `updateState`, `addDomain`, `removeDomain`, `archive`, `getActive`, `search`. Emits `site:settings:updated` natively (no monkey-patching). Caps enforced via plugin config. Bugfix: `addDomain` now persists the new domain (upstream produced an unused local).
- ADDED: `DomainResolverService` — `resolve` envelope, `isDomainTaken`, `resolveOrThrow`. Wraps SurrealDB `fn::domain::search`. Emits OTel counter + duration histogram.
- ADDED: `createDomainResolverMiddleware` — Hono middleware factory injecting `site` / `organization` / `siteId` / `organizationId` into request context.
- ADDED: `createPublicSiteRoutes` — `GET /sites/resolve/{domain}`, `GET /sites/{id}/public`.
- ADDED: `createPrivateSiteRoutes` — `POST /sites`, `PATCH /sites/{id}`, `POST /sites/{id}/domains`, `DELETE /sites/{id}/domains`.
- ADDED: `createSitePlugin` — `definePlugin<SitePluginConfig>` factory wrapping the genesis `PluginDescriptor` with the canonical 4-phase lifecycle. Subscribes to `organization:created` when `autoCreateDefaultSite` is on, emits `site:bootstrap:failed` on failure, registers three services (`siteService`, `domainResolver`, `domainResolverMiddleware`), mounts route trees under configurable `routePrefix`.
- ADDED: `getSiteInstruments` / `resetSiteInstruments` / `SiteInstruments` — OTel bundle (5 instruments) with cache reset for test rebinding.
- ADDED: `services/registry-augmentation.ts` — declares `siteService`, `domainResolver`, `domainResolverMiddleware`, `app`, `db` on `ServiceRegistry`.
- ADDED: `surql/tables/site.surql` — per-table migration with state constants, indices, and the `fn::domain::search` function.
### Source mapping
| Upstream source | Genesis location | Notes |
|---|---|---|
| `src/index.ts` | `src/index.ts` | Re-exports broadened to expose every documented symbol. |
| `src/plugin.ts` | `src/plugin/plugin.ts` | Rewritten with `definePlugin<SitePluginConfig>()` from `@suaveplan/api-plugin`; every `as any` removed; monkey-patch dropped; `site:bootstrap:failed` event added. |
| `src/config.ts` | `src/schemas/options.ts` | Switched from hand-rolled `mergeConfig` to Zod-validated boundary; `DEFAULT_CONFIG` frozen. |
| `src/middleware/domain-resolver.middleware.ts` | `src/middleware/domain-resolver.ts` | Uses `normalizeDomain` before resolve. |
| `src/routes/public.routes.ts` | `src/routes/public-routes.ts` | OpenAPI route definitions preserved; sanitised public projection. |
| `src/routes/private.routes.ts` | `src/routes/private-routes.ts` | Adds `DELETE /sites/{id}/domains`; bodies Zod-validated through @hono/zod-openapi. |
| `src/services/site.service.ts` | `src/service/site.ts` | `addDomain` persistence bug fixed; event emit moved into the service; OTel counters added; structural `SiteDb` port. |
| `src/services/domain-resolver.service.ts` | `src/service/domain-resolver.ts` | OTel counter + histogram; codes embedded in result envelope; `resolveOrThrow` helper. |
| `src/types/site.types.ts` | `src/schemas/site.ts` + `src/schemas/domain.ts` + `src/schemas/push.ts` + `src/types/types.ts` | Type-only file split into Zod schemas (per-feature) and runtime-free types. |
| `surql/tables/site.surql` | `surql/tables/site.surql` | Trimmed `fn::site::*` helpers that the application-tier now owns (`normalizeDomain`, `createDefaultSite`) — covered by `### Excluded`. |
### Excluded from this migration
The genesis `0.1.0` ships at functional parity with the upstream public surface (services + routes + middleware + plugin + migration). The §3 enterprise-doc enhancements that depend on packages not yet landed on genesis are scoped out with concrete justifications — NOT silently dropped:
- **`fn::site::*` SurQL helper suite** (e.g. `fn::site::create`, `fn::site::push::validate`, `fn::site::settings::update`) — application-tier `SiteService` now owns every call site. Keeping those helpers in the migration would duplicate logic between two writers and contradict §0a's "no implicit drops"; the application tier IS the canonical writer in genesis (matching the recent `api-plugin-import` / `api-plugin-search` precedent). The migration ships only `fn::domain::search` because the resolver still delegates pattern matching to the database.
- **JWT / permissions / rate-limit / audit middleware wiring** — depends on `@suaveplan/api-plugin-rate-limit` + `@suaveplan/api-plugin-audit` already landed in genesis, but the integration knob is the host app's `app.use(prefix, middleware)` Hono pattern. The site plugin does NOT hard-depend on them so excluding integration from THIS migration does not block consumers from layering them on top.
- **ACME / Let's Encrypt automation, edge-CDN cache busting, sitemap auto-gen, theme draft/publish workflow** — every item is a §4 future enhancement, not a §2 current-state capability. None are part of the upstream `1.0.21` shipped feature surface.
- **Benchmarks under `src/__benchmarks__/`** — the monorepo benchmark wave is a separate gate; the site plugin will receive its mitata harness in that wave.
## Migration
No external consumers exist yet (genesis-only). For internal consumers:
- Old: `import { createSitePlugin } from "@suaveplan/api-plugin-site"` from the upstream `1.0.x` line.
- New: same import, but the descriptor's lifecycle hooks now use the genesis `PluginContext` (typed `getOwnConfig`, augmented `ServiceRegistry["siteService"|"domainResolver"|"domainResolverMiddleware"]`).
- Event-bus events are now strongly typed via `SiteEventMap`; consumers that wrote `bus.on("site:settings:updated" as any, ...)` should drop the cast.
- The `addDomain` bug-fix means a site's `domains` array is actually updated after a successful call. Consumers that worked around the bug by manually rewriting the row should remove the workaround.
## Impact
### Affected dependents
`bunx turbo ls --filter=...@suaveplan/api-plugin-site` enumerates zero dependents on genesis today (this is the first landing). The package will be picked up by future genesis-original packages (e.g. `api` host orchestrator). No dependent sweep required for this change.

View File

@@ -0,0 +1,251 @@
<!-- markdownlint-disable MD024 -->
# Capability Spec Delta: api-plugin-site (add-api-plugin-site)
**Package**: `@suaveplan/api-plugin-site`
**Status**: PROPOSED
> Every requirement below carries a `**Verified by:**` line at authoring time.
## ADDED Requirements
### Requirement: Stable SITE.* error registry
The package SHALL register exactly 14 stable error codes under the `"SITE"` namespace via `defineCodes("SITE", [...])`, exporting `SITE_CODES` and `SiteError extends SuaveplanError<SiteErrorCode>`. Every code SHALL be reachable from at least one production code path; deletion to satisfy a coverage gate is forbidden.
#### Scenario: registry declares the 14 canonical codes
- **WHEN** a caller imports `SITE_CODES`
- **THEN** the literal values include `INVALID_OPTIONS`, `SERVICE_NOT_AVAILABLE`, `SITE_NOT_FOUND`, `SITE_LIMIT_EXCEEDED`, `DOMAIN_LIMIT_EXCEEDED`, `DOMAIN_ALREADY_CLAIMED`, `LAST_DOMAIN_REMOVAL`, `DOMAIN_NOT_FOUND`, `INVALID_DOMAIN`, `VALIDATION`, `BOOTSTRAP_FAILED`, `STORAGE_ERROR`, `ROUTE_PREFIX_COLLISION`, `RESOLUTION_FAILED` and every value is namespaced `"SITE.<KEY>"`
#### Scenario: SiteError preserves cause + code
- **WHEN** `new SiteError(SITE_CODES.SITE_NOT_FOUND, "missing", { cause })` is constructed
- **THEN** `error.code === "SITE.SITE_NOT_FOUND"`, `error.siteCode === error.code`, `error.cause === cause`
**Verified by:** `src/error-codes/error-codes.test.ts::"declares all 14 canonical SITE.* codes"` AND `src/error-codes/error-codes.test.ts::"SiteError preserves code, message, cause, and siteCode alias"`
---
### Requirement: Zod-validated plugin-options boundary
The package SHALL expose `SitePluginOptionsSchema` with defaults for every option and SHALL reject non-positive numeric caps and empty `defaultDomainPattern` at Zod parse time. `createSitePlugin` SHALL fail with `SiteError(SITE.INVALID_OPTIONS)` carrying the `ZodError` as `cause` when called with bad input. `DEFAULT_CONFIG` SHALL be frozen.
#### Scenario: defaults applied on empty input
- **WHEN** `SitePluginOptionsSchema.parse({})` is invoked
- **THEN** the result is `{maxSitesPerOrg: 10, maxDomainsPerSite: 5, autoCreateDefaultSite: true, defaultDomainPattern: "{slug}.suaveplan.app", enableDomainResolution: true, enablePushNotifications: true, enableSiteSearch: true, routePrefix: "/api"}`
#### Scenario: invalid options fail with SITE.INVALID_OPTIONS
- **WHEN** `createSitePlugin({ maxSitesPerOrg: -1 } as never)` is invoked
- **THEN** it throws a `SiteError` whose `code === SITE.INVALID_OPTIONS` and whose `cause` is the `ZodError`
**Verified by:** `src/schemas/options.test.ts::"applies all defaults when called with empty input"` AND `src/plugin/plugin.test.ts::"rejects invalid options with SITE.INVALID_OPTIONS"`
---
### Requirement: Site / domain / push Zod schemas
The package SHALL inline the canonical Zod surface for sites, domains, and push configs (`SiteSchema`, `CreateSiteSchema`, `UpdateSiteSchema (.strict)`, `SitePublicInfoSchema`, `SiteIdParamSchema`, `DomainSchema`, `AddDomain*Schema`, `RemoveDomain*Schema`, `DomainResolveParam/ResponseSchema`, `ApplePushConfigSchema`, `FirebasePushConfigSchema`, `PushConfigSchema`, `PushConfigValidationResponseSchema`).
#### Scenario: CreateSiteSchema rejects empty domain list
- **WHEN** `CreateSiteSchema.safeParse({ organization_id, name, domains: [] })`
- **THEN** `result.success === false`
#### Scenario: UpdateSiteSchema rejects unknown keys
- **WHEN** `UpdateSiteSchema.safeParse({ name: "x", sneaky: 1 })`
- **THEN** `result.success === false`
#### Scenario: PushConfigSchema requires at least one provider
- **WHEN** `PushConfigSchema.safeParse({})`
- **THEN** `result.success === false`
**Verified by:** `src/schemas/site.test.ts::"rejects empty domain list"` AND `src/schemas/site.test.ts::"rejects unknown keys via .strict()"` AND `src/schemas/push.test.ts::"requires at least one provider"`
---
### Requirement: Domain canonicalisation parity with database
The package SHALL expose `normalizeDomain(input)` which lower-cases, trims, strips `http(s)://`, strips leading `www.`, and strips a single trailing `/`. The semantics SHALL match the SurrealDB `fn::site::domain::normalize` function so application-tier and database-tier writers agree on the canonical form.
#### Scenario: composed prefix normalisation
- **WHEN** `normalizeDomain("HTTPS://WWW.Acme.Example.Com/")`
- **THEN** result is `"acme.example.com"`
**Verified by:** `src/service/normalize-domain.test.ts::"strips composed prefixes"`
---
### Requirement: DomainResolverService — envelope + observability
`DomainResolverService.resolve(domain)` SHALL return `{success, site?, organization?, error?, code?}`. On hit: `success: true` with `site` + `organization`. On miss: `success: false`, `error: "Domain not found"`, `code: SITE.DOMAIN_NOT_FOUND`. On driver throw: `success: false`, message preserved, `code: SITE.RESOLUTION_FAILED`. Every call SHALL increment `site.domain_resolutions_total{outcome}` and record `site.domain_resolution_duration_ms`. `resolveOrThrow` SHALL throw `SiteError` carrying the same code.
#### Scenario: miss envelope
- **WHEN** the underlying query returns `[]`
- **THEN** `resolve("nope")` returns `{success: false, error: "Domain not found", code: "SITE.DOMAIN_NOT_FOUND"}`
#### Scenario: driver error envelope
- **WHEN** the underlying query throws an `Error`
- **THEN** the returned envelope's `code === "SITE.RESOLUTION_FAILED"` and `error` is the error's message
#### Scenario: resolveOrThrow throws SiteError on miss
- **WHEN** `resolveOrThrow("nope")` runs against an empty result
- **THEN** a `SiteError` with `code === "SITE.DOMAIN_NOT_FOUND"` is thrown
**Verified by:** `src/service/domain-resolver.test.ts::"returns DOMAIN_NOT_FOUND code on empty result"` AND `src/service/domain-resolver.test.ts::"returns RESOLUTION_FAILED code when db throws Error"` AND `src/service/domain-resolver.test.ts::"throws DOMAIN_NOT_FOUND on miss"`
---
### Requirement: SiteService — typed CRUD + cap enforcement + event emission
`SiteService` SHALL expose `create`, `createDefaultSite`, `getById`, `requireById`, `listByOrganization`, `countByOrganization`, `update`, `updateSettings`, `updateState`, `addDomain`, `removeDomain`, `archive`, `getActive`, `search`. `create` SHALL enforce `maxSitesPerOrg` (raises `SITE.SITE_LIMIT_EXCEEDED`) and `maxDomainsPerSite` (raises `SITE.DOMAIN_LIMIT_EXCEEDED`). `addDomain` SHALL persist the new domain (upstream bug fix) and reject duplicates with `SITE.DOMAIN_ALREADY_CLAIMED`. `removeDomain` SHALL refuse to leave the site with zero domains via `SITE.LAST_DOMAIN_REMOVAL`. `updateSettings` SHALL emit `site:settings:updated` natively (no monkey-patching).
#### Scenario: create enforces site cap
- **WHEN** a second `create` runs against an organization already at `maxSitesPerOrg: 1`
- **THEN** a `SiteError(SITE.SITE_LIMIT_EXCEEDED)` is thrown
#### Scenario: addDomain persists new domain
- **WHEN** `addDomain(siteId, "B.Example.Com")` is called against a site with `domains: ["a.example.com"]`
- **THEN** the returned site has `domains: ["a.example.com", "b.example.com"]` AND the underlying row is mutated
#### Scenario: addDomain rejects duplicates
- **WHEN** `addDomain(siteId, "A.Example.Com")` is called against a site already containing `"a.example.com"`
- **THEN** a `SiteError(SITE.DOMAIN_ALREADY_CLAIMED)` is thrown
#### Scenario: removeDomain refuses last
- **WHEN** `removeDomain(siteId, "a.example.com")` is called against a site with one domain
- **THEN** a `SiteError(SITE.LAST_DOMAIN_REMOVAL)` is thrown
#### Scenario: updateSettings emits site:settings:updated
- **WHEN** `updateSettings(siteId, { features: ["beta"] })` succeeds
- **THEN** the injected `EventBusLike` receives a `site:settings:updated` payload with `siteId` and `changedFields: ["features"]`
**Verified by:** `src/service/site.test.ts::"throws SITE_LIMIT_EXCEEDED when over the cap"` AND `src/service/site.test.ts::"addDomain persists the normalized domain"` AND `src/service/site.test.ts::"addDomain throws DOMAIN_ALREADY_CLAIMED on duplicates"` AND `src/service/site.test.ts::"removeDomain refuses LAST_DOMAIN_REMOVAL"` AND `src/service/site.test.ts::"updateSettings merges, persists, and emits site:settings:updated"`
---
### Requirement: Hono middleware factory
`createDomainResolverMiddleware(resolver)` SHALL return a Hono middleware that reads `Host` then `X-Forwarded-Host`, normalises via `normalizeDomain`, and on a hit injects `site` / `organization` / `siteId` / `organizationId` into the request context. On miss or absent host the middleware SHALL fall through silently.
#### Scenario: hit injects four context keys
- **WHEN** a request with `Host: https://www.Example.Com:8080` arrives and the resolver hits
- **THEN** `c.get("siteId")`, `c.get("organizationId")`, `c.get("site")`, and `c.get("organization")` are populated
#### Scenario: empty host falls through
- **WHEN** the middleware is invoked against a context whose `req.header("host")` returns `undefined`
- **THEN** `next()` is called once and no site key is set
**Verified by:** `src/middleware/domain-resolver.test.ts::"injects site + organization on a hit"` AND `src/middleware/domain-resolver.test.ts::"falls through when host header is empty (direct unit call)"`
---
### Requirement: Public + private OpenAPI route trees
`createPublicSiteRoutes` SHALL expose `GET /sites/resolve/{domain}` (returning the resolution envelope) and `GET /sites/{id}/public` (returning the sanitised public projection). `createPrivateSiteRoutes` SHALL expose `POST /sites`, `PATCH /sites/{id}`, `POST /sites/{id}/domains`, `DELETE /sites/{id}/domains`. All bodies SHALL be Zod-validated through `@hono/zod-openapi`.
#### Scenario: domain resolution endpoint returns 200 envelope
- **WHEN** `GET /sites/resolve/example.com` runs and the resolver hits
- **THEN** status is `200` and the body is `{success: true, site, organization}`
#### Scenario: site creation 201
- **WHEN** `POST /sites` runs with a valid body
- **THEN** status is `201` and the body is the created site
#### Scenario: site creation 400 on bad body
- **WHEN** `POST /sites` runs with an empty body
- **THEN** status is `>= 400`
**Verified by:** `src/routes/public-routes.test.ts::"resolves a domain to a site envelope"` AND `src/routes/private-routes.test.ts::"creates a site via POST /sites"` AND `src/routes/private-routes.test.ts::"rejects POST /sites with bad input via Zod 400"`
---
### Requirement: Plugin lifecycle + auto-bootstrap
`createSitePlugin` SHALL produce a `PluginDescriptor` with `name: "site"`, `version: "0.1.0"`, `optionalDependencies: ["database", "auth", "events"]`. `onInit` SHALL resolve `db` from `ServiceRegistry` (raising `SITE.SERVICE_NOT_AVAILABLE` if missing), construct + register `siteService`, `domainResolver`, `domainResolverMiddleware`, optionally subscribe to `organization:created`, and emit `site:initialized`. `onReady` SHALL resolve `app`, detect route-prefix collisions (`SITE.ROUTE_PREFIX_COLLISION`), mount the route trees, and emit `site:ready`. `onClose` SHALL drop the `organization:created` listener.
#### Scenario: missing db raises SERVICE_NOT_AVAILABLE
- **WHEN** `onInit` runs without `db` registered on `ServiceRegistry`
- **THEN** a `SiteError(SITE.SERVICE_NOT_AVAILABLE)` is thrown
#### Scenario: route prefix collision raises ROUTE_PREFIX_COLLISION
- **WHEN** the host `app` already exposes a route under `${routePrefix}/sites/*` and `onReady` runs
- **THEN** a `SiteError(SITE.ROUTE_PREFIX_COLLISION)` is thrown
#### Scenario: organization:created auto-creates default site
- **WHEN** the plugin is constructed with `autoCreateDefaultSite: true` and the event bus emits `organization:created`
- **THEN** the service's underlying store contains a site for that organization id
#### Scenario: createDefaultSite failure emits site:bootstrap:failed
- **WHEN** the organization is already at its site cap and the auto-bootstrap listener fires
- **THEN** the event bus emits `site:bootstrap:failed` with `organizationId`
**Verified by:** `src/plugin/plugin.test.ts::"onInit throws SERVICE_NOT_AVAILABLE when db is missing"` AND `src/plugin/plugin.test.ts::"detects route prefix collisions and throws ROUTE_PREFIX_COLLISION"` AND `src/plugin/plugin.test.ts::"auto-creates a default site on organization:created"` AND `src/plugin/plugin.test.ts::"emits site:bootstrap:failed when createDefaultSite throws"`
---
### Requirement: OTel instrument bundle
The package SHALL expose `getSiteInstruments` returning a lazily-built bundle of five OTel instruments: `sitesCreatedTotal`, `sitesUpdatedTotal`, `domainResolutionsTotal`, `domainResolutionDurationMs`, `bootstrapFailedTotal`. The bundle SHALL be cached at module scope and `resetSiteInstruments` SHALL clear the cache so tests can install a fresh `MeterProvider`.
#### Scenario: instruments cached across calls
- **WHEN** `getSiteInstruments()` is invoked twice in succession without a reset
- **THEN** the second call returns the same object instance as the first
#### Scenario: reset rebinds against a fresh MeterProvider
- **WHEN** a fresh `MeterProvider` is installed and `resetSiteInstruments` is called
- **THEN** the next `getSiteInstruments()` produces a new bundle and `forceFlush` collects metrics from it
**Verified by:** `src/otel/instruments.test.ts::"getSiteInstruments returns a cached bundle"` AND `src/otel/instruments.test.ts::"resetSiteInstruments rebinds against a fresh MeterProvider"`
---
### Requirement: ServiceRegistry augmentation
The package SHALL augment `@suaveplan/api-plugin/service-registry`'s `ServiceRegistry` with three slots — `siteService`, `domainResolver`, `domainResolverMiddleware` — plus the cumulative host slots `app: OpenAPIHono` and `db: SurrealAdapter`. Importing the package barrel SHALL be sufficient to surface the augmentation.
#### Scenario: descriptor lists optional database / auth / events dependencies
- **WHEN** `createSitePlugin()` returns a descriptor
- **THEN** `descriptor.optionalDependencies === ["database", "auth", "events"]`
**Verified by:** `src/plugin/plugin.test.ts::"descriptor name is 'site' and version is '0.1.0'"`
---
### Requirement: Public surface re-exports
The package barrel SHALL re-export the canonical public surface: `SITE_CODES`, `SiteError`, `DEFAULT_CONFIG`, `mergeConfig`, `SiteService`, `DomainResolverService`, `normalizeDomain`, `createDomainResolverMiddleware`, `createPublicSiteRoutes`, `createPrivateSiteRoutes`, `createSitePlugin`, `getSiteInstruments`, `resetSiteInstruments`, `validatePushConfig`, `SiteSchema`, `DomainSchema`, plus the four `SITE_STATE_*` constants.
#### Scenario: re-export surface count
- **WHEN** the spec-conformance test imports every documented symbol from the package barrel
- **THEN** every symbol resolves and the import does not throw
**Verified by:** `src/api-plugin-site.spec-conformance.test.ts::"re-exports every documented symbol"`
---

View File

@@ -0,0 +1,69 @@
# Tasks — Add @suaveplan/api-plugin-site
> Every checkbox MUST reflect work actually done in this change.
## 1. Spec authoring
- [x] 1.1 Read `/mnt/s/web/suaveplan/enterprise/api-plugin-site.md` end-to-end.
- [x] 1.2 Confirm no prior `openspec/specs/api-plugin-site/spec.md` exists.
- [x] 1.3 Read `openspec/AGENTS.md` §§ 0a, 2a, 6a, 7, 12, 13, 14.
- [x] 1.4 Draft `proposal.md` with `### Source mapping` table + `### Excluded` section.
- [x] 1.5 Draft `specs/api-plugin-site/spec.md` with `## ADDED Requirements`, every requirement carrying a `**Verified by:**` line.
## 2. Implementation
- [x] 2.1 `src/error-codes/error-codes.ts` — `defineCodes("SITE", [...])` (14 codes) + `SiteError extends SuaveplanError`.
- [x] 2.2 `src/types/types.ts` — runtime-free types: `Site`, `SiteSettings`, `SiteTheme`, push types, `SiteEventMap`, state constants.
- [x] 2.3 `src/schemas/site.ts` — Zod schemas for the site entity.
- [x] 2.4 `src/schemas/domain.ts` — Zod schemas for domain values + requests/responses.
- [x] 2.5 `src/schemas/push.ts` — Push-config schemas + `validatePushConfig` pure validator.
- [x] 2.6 `src/schemas/options.ts` — `SitePluginOptionsSchema`, `mergeConfig`, frozen `DEFAULT_CONFIG`.
- [x] 2.7 `src/otel/instruments.ts` — `getSiteInstruments` / `resetSiteInstruments` / `SiteInstruments`.
- [x] 2.8 `src/service/db-port.ts` — structural `SiteDb` interface.
- [x] 2.9 `src/service/normalize-domain.ts` — pure normaliser.
- [x] 2.10 `src/service/domain-resolver.ts` — `DomainResolverService` with OTel + envelope result.
- [x] 2.11 `src/service/site.ts` — `SiteService` (CRUD + emit `site:settings:updated`).
- [x] 2.12 `src/middleware/domain-resolver.ts` — middleware factory.
- [x] 2.13 `src/routes/public-routes.ts` — public OpenAPI router.
- [x] 2.14 `src/routes/private-routes.ts` — private OpenAPI router.
- [x] 2.15 `src/plugin/plugin.ts` — `createSitePlugin` via `definePlugin<SitePluginConfig>`.
- [x] 2.16 `src/services/registry-augmentation.ts` — `ServiceRegistry` slots.
- [x] 2.17 `src/index.ts` — explicit named re-exports.
- [x] 2.18 `surql/tables/site.surql` — table + `fn::domain::search`.
## 3. Tests
- [x] 3.1 `src/error-codes/error-codes.test.ts` — registry shape + `SiteError` preserves cause.
- [x] 3.2 `src/otel/instruments.test.ts` — cache + rebind against real `MeterProvider`.
- [x] 3.3 `src/schemas/options.test.ts`, `site.test.ts`, `domain.test.ts`, `push.test.ts`.
- [x] 3.4 `src/service/normalize-domain.test.ts`.
- [x] 3.5 `src/service/domain-resolver.test.ts` — hit/miss/error envelopes, normalisation, `resolveOrThrow`.
- [x] 3.6 `src/service/site.test.ts` — every method, every error path.
- [x] 3.7 `src/middleware/domain-resolver.test.ts` — Hono integration.
- [x] 3.8 `src/routes/public-routes.test.ts`, `private-routes.test.ts`.
- [x] 3.9 `src/plugin/plugin.test.ts` — lifecycle, event wiring, route mount, collision detection.
- [x] 3.10 `src/api-plugin-site.spec-conformance.test.ts` — public-surface re-export check.
- [x] 3.11 Every `it(...)` carries `{ timeout: 5000 }`.
- [x] 3.12 Every test imports from `@suaveplan/testing/runner`.
## 4. Documentation
- [x] 4.1 Sibling `.md` for every non-barrel, non-test, non-types, non-augmentation `.ts`.
- [x] 4.2 Root `README.md` lists every module link.
## 5. Pre-archive gates
- [ ] 5.1 `bunx turbo lint typecheck test --filter=@suaveplan/api-plugin-site` green.
- [ ] 5.2 `bunx turbo test:coverage --filter=@suaveplan/api-plugin-site` ≥ 100% on every metric.
- [ ] 5.3 `bunx turbo build --filter=@suaveplan/api-plugin-site` green.
- [ ] 5.4 Banned-pattern scan returns no hits.
- [ ] 5.5 Barrel `export *` scan returns no hits in `<feature>/index.ts`.
- [ ] 5.6 Test-runner import scan returns no hits.
- [ ] 5.7 Sibling `.md` scan returns no missing-doc hits.
- [ ] 5.8 No bare versions in `package.json`.
- [ ] 5.9 Subpath export count matches feature-module count.
## 6. Archive
- [ ] 6.1 Fold `specs/api-plugin-site/spec.md` into `openspec/specs/api-plugin-site/spec.md`.
- [ ] 6.2 `mv openspec/changes/add-api-plugin-site openspec/archive/2026-05-19-add-api-plugin-site`.