@pwfabric/runtime 1.2.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -7,7 +7,7 @@ re-exports `@pwfabric/contracts`.
7
7
  ## Install
8
8
 
9
9
  ```bash
10
- pnpm add @pwfabric/runtime zod@3 react react-dom
10
+ pnpm add @pwfabric/runtime zod@4 react react-dom
11
11
  ```
12
12
 
13
13
  ESM only: import it from an ES module (`"type": "module"` or `.mjs`). Node 22+. Peers: `react` and `react-dom` 18 or 19; `next` 14–16 only if you use the
@@ -265,7 +265,7 @@ export class HttpEntityConnector {
265
265
  return { success: true, data: {} };
266
266
  }
267
267
  const jsonData = await response.json();
268
- const data = z.record(z.unknown()).parse(jsonData);
268
+ const data = z.record(z.string(), z.unknown()).parse(jsonData);
269
269
  return { success: true, data };
270
270
  }
271
271
  catch (err) {
@@ -1 +1 @@
1
- {"version":3,"file":"http-connector.js","sourceRoot":"","sources":["../../src/entity/http-connector.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAA;AAkGvB,+DAA+D;AAC/D,WAAW;AACX,+DAA+D;AAE/D,MAAM,mBAAmB,GAAG,CAAC;KAC1B,MAAM,CAAC;IACN,KAAK,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC,QAAQ,EAAE;IACtC,KAAK,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;IAC5B,MAAM,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;IAC7B,KAAK,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;CAC7B,CAAC;KACD,WAAW,EAAE,CAAA;AAEhB;;;;GAIG;AACH,MAAM,mBAAmB,GAAG,CAAC;KAC1B,MAAM,CAAC;IACN,EAAE,EAAE,CAAC,CAAC,IA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AAC9C,CAAC","sourcesContent":["/**\n * HTTP Entity Connector\n *\n * REST API connector for entity data persistence and retrieval.\n * Implements the EntityConnector interface using fetch for HTTP communication.\n *\n * @module @pwfabric/runtime/entity/http-connector\n */\n\nimport { z } from 'zod'\nimport type {\n EntityTypeId,\n EntityInstanceId,\n EntityQuery,\n EntityAggregate,\n EntityAggregateResult,\n} from './types.js'\nimport type {\n EntityConnector,\n EntityConnectorType,\n ConnectorResult,\n ConnectorQueryResult,\n ConnectorAggregateResult,\n} from './connector.js'\n\n// ============================================================\n// CONFIGURATION\n// ============================================================\n\n/**\n * HTTP connector authentication configuration\n */\nexport interface HttpAuthConfig {\n readonly type: 'bearer' | 'api-key' | 'basic'\n /**\n * A fixed value, or a RESOLVER re-invoked on every request.\n *\n * A string or a resolver. A delegated PKCE token expires within about an\n * hour, so a fixed string cannot serve a session; an engine that needs a\n * live token passes a resolver instead of reimplementing the transport\n * (and losing retry, timeout and the result envelope on the way).\n *\n * A string is used as is; a resolver is awaited per request and its answer\n * is never cached here, which is the whole point.\n */\n readonly token?: string | (() => Promise<string | null>)\n readonly apiKey?: string\n readonly headerName?: string\n readonly username?: string\n readonly password?: string\n}\n\n/**\n * HTTP connector retry configuration\n */\nexport interface HttpRetryConfig {\n readonly maxRetries: number\n readonly baseDelay: number\n readonly maxDelay: number\n readonly retryableStatuses: readonly number[]\n}\n\n/**\n * HTTP connector configuration\n */\nexport interface HttpConnectorConfig {\n readonly baseUrl: string\n readonly headers?: Record<string, string>\n readonly timeout?: number\n readonly auth?: HttpAuthConfig\n /**\n * Fetch credentials mode. Set 'include' so cookie-authoritative APIs\n * receive the session cookie on cross-origin entity requests\n * the visitor facade has no bearer token to send.\n */\n readonly credentials?: RequestCredentials\n readonly retry?: HttpRetryConfig\n /**\n * Query parameters this API requires on every read.\n *\n * GENERIC, and the distinction matters because three vendor-shaped widenings\n * were proposed and reverted the same day. Azure wants `api-version`, plenty\n * of APIs want `format=json`, Graph wants `expand=fields`: \"this endpoint\n * takes constant parameters\" is a REST fact, not one provider's dance, and no\n * provider name appears here.\n *\n * It exists because the alternative is worse. A caller that put its constants\n * in `entityPathMapper` would produce `...?expand=fields?limit=50` the moment\n * a query carried pagination, and `...?expand=fields/1` on a delete — the URL\n * is assembled as `params ? url + '?' + params : url`.\n */\n readonly defaultQueryParams?: Readonly<Record<string, string>>\n readonly entityPathMapper?: (entityType: EntityTypeId) => string\n /**\n * Maps a vendor response body to the connector's query result shape\n * `entityPathMapper`'s response-side twin.\n *\n * `entityPathMapper` has always let a caller say how an entity type becomes a\n * URL path; nothing let it say how the answer comes back. So a vendor whose\n * body is its own shape — Graph replies `{ value: [{ id, fields }] }`, not\n * `{ items }` — could not use this class at all, and that was the other half\n * of why every Graph engine forked. Absent, the built-in shapes below apply\n * unchanged.\n */\n readonly responseMapper?: (raw: unknown) => { items: unknown[]; total?: number }\n}\n\n// ============================================================\n// DEFAULTS\n// ============================================================\n\nconst queryResponseSchema = z\n .object({\n items: z.array(z.unknown()).optional(),\n total: z.number().optional(),\n offset: z.number().optional(),\n limit: z.number().optional(),\n })\n .passthrough()\n\n/**\n * `{ data: { fn, field?, value, count, numericCount? }, meta }` is how the\n * platform answers (`routes/app-records.ts`); a bare `{ value, count }` body\n * is accepted too. `value` is null when a numeric fn had nothing to reduce.\n */\nconst aggregateBodySchema = z\n .object({\n fn: z.enum(['count', 'sum', 'avg']).optional(),\n field: z.string().optional(),\n value: z.number().nullable().optional(),\n count: z.number().optional(),\n })\n .passthrough()\n\nconst DEFAULT_TIMEOUT = 30_000\n\nconst DEFAULT_RETRY: HttpRetryConfig = {\n maxRetries: 3,\n baseDelay: 1000,\n maxDelay: 10_000,\n retryableStatuses: [408, 429, 500, 502, 503, 504],\n}\n\n// ============================================================\n// HTTP ENTITY CONNECTOR\n// ============================================================\n\n/**\n * HTTP/REST connector for entity data operations.\n * Maps entity CRUD operations to standard REST API endpoints.\n */\nexport class HttpEntityConnector implements EntityConnector {\n readonly name: string\n readonly type: EntityConnectorType = 'http'\n\n private readonly config: Required<Pick<HttpConnectorConfig, 'baseUrl' | 'timeout'>> &\n HttpConnectorConfig\n\n constructor(name: string, config: HttpConnectorConfig) {\n this.name = name\n this.config = {\n ...config,\n timeout: config.timeout ?? DEFAULT_TIMEOUT,\n }\n }\n\n async create(entityType: EntityTypeId, data: Record<string, unknown>): Promise<ConnectorResult> {\n const url = this.buildUrl(entityType)\n return this.request('POST', url, data)\n }\n\n async read(entityType: EntityTypeId, instanceId: EntityInstanceId): Promise<ConnectorResult> {\n const url = `${this.buildUrl(entityType)}/${instanceId}`\n return this.request('GET', url)\n }\n\n async update(\n entityType: EntityTypeId,\n instanceId: EntityInstanceId,\n data: Record<string, unknown>\n ): Promise<ConnectorResult> {\n const url = `${this.buildUrl(entityType)}/${instanceId}`\n return this.request('PATCH', url, data)\n }\n\n async delete(entityType: EntityTypeId, instanceId: EntityInstanceId): Promise<ConnectorResult> {\n const url = `${this.buildUrl(entityType)}/${instanceId}`\n return this.request('DELETE', url)\n }\n\n async query(entityType: EntityTypeId, query: EntityQuery): Promise<ConnectorQueryResult> {\n const url = this.buildUrl(entityType)\n const params = this.buildQueryParams(query)\n const fullUrl = params ? `${url}?${params}` : url\n\n const result = await this.request('GET', fullUrl)\n if (!result.success) {\n return { success: false, error: result.error }\n }\n\n // A vendor shape is mapped BEFORE the built-in schema runs — the mapper\n // exists precisely for bodies this schema would reject, so validating first\n // would refuse the very responses it was added to accept.\n if (this.config.responseMapper) {\n const mapped = this.config.responseMapper(result.data)\n const items = mapped.items as Record<string, unknown>[]\n const total = mapped.total ?? items.length\n const offset = query.pagination?.offset ?? 0\n return {\n success: true,\n result: {\n items,\n total,\n offset,\n limit: query.pagination?.limit ?? items.length,\n hasMore: total > offset + items.length,\n },\n }\n }\n\n const parsed = queryResponseSchema.safeParse(result.data)\n if (!parsed.success) {\n return { success: false, error: 'Invalid query response shape' }\n }\n const data = parsed.data as Record<string, unknown>\n\n // Accept both the connector contract ({items,total}) and the platform\n // entity-records envelope ({data:[...], meta:{total}}).\n const rawItems = ((data.items as unknown[]) ??\n (data.data as unknown[]) ??\n []) as Record<string, unknown>[]\n // Entity records store user fields under `.data` — flatten them to the top\n // level so expression/column bindings ({{id}}, column key 'name') resolve\n // against the fields, while keeping id/metadata available.\n const items = rawItems.map((r) =>\n r && typeof r === 'object' && r.data && typeof r.data === 'object'\n ? { ...r, ...(r.data as Record<string, unknown>) }\n : r\n )\n const meta = data.meta as Record<string, unknown> | undefined\n const total = (data.total as number) ?? (meta?.total as number) ?? items.length\n\n return {\n success: true,\n result: {\n items,\n total,\n offset: (data.offset as number) ?? query.pagination?.offset ?? 0,\n limit: (data.limit as number) ?? query.pagination?.limit ?? 50,\n hasMore: total > ((data.offset as number) ?? 0) + items.length,\n },\n }\n }\n\n /**\n * One number over the collection, computed by the server.\n *\n * `GET <base>/<type>/count[?filter=]` for a plain count and\n * `GET <base>/<type>/aggregate?fn=&field=&filter=` for the rest — the two\n * routes a host registers ahead of the read-one route.\n * Constants (`defaultQueryParams`) and `entityPathMapper` apply as on\n * every other read.\n */\n async aggregate(entityType: EntityTypeId, aggregate: EntityAggregate): Promise<ConnectorAggregateResult> {\n const plainCount = aggregate.fn === 'count' && !aggregate.field\n const params = new URLSearchParams()\n for (const [k, v] of Object.entries(this.config.defaultQueryParams ?? {})) params.set(k, v)\n if (!plainCount) {\n params.set('fn', aggregate.fn)\n if (aggregate.field) params.set('field', aggregate.field)\n }\n if (aggregate.filter) params.set('filter', JSON.stringify(aggregate.filter))\n const url = `${this.buildUrl(entityType)}/${plainCount ? 'count' : 'aggregate'}`\n const qs = params.toString()\n\n const result = await this.request('GET', qs ? `${url}?${qs}` : url)\n if (!result.success) return { success: false, error: result.error }\n\n const envelope = result.data\n const body = envelope.data && typeof envelope.data === 'object' ? envelope.data : envelope\n const parsed = aggregateBodySchema.safeParse(body)\n if (!parsed.success) return { success: false, error: 'Invalid aggregate response shape' }\n const d = parsed.data\n const field = d.field ?? aggregate.field\n const out: EntityAggregateResult = {\n fn: d.fn ?? aggregate.fn,\n ...(field ? { field } : {}),\n value: d.value ?? null,\n count: d.count ?? 0,\n }\n return { success: true, result: out }\n }\n\n // ============================================================\n // PRIVATE HELPERS\n // ============================================================\n\n private buildUrl(entityType: EntityTypeId): string {\n const path = this.config.entityPathMapper\n ? this.config.entityPathMapper(entityType)\n : `/${entityType}`\n return `${this.config.baseUrl}${path}`\n }\n\n private buildQueryParams(query: EntityQuery): string {\n const params = new URLSearchParams()\n\n // Constants first so a caller's own query can still override one.\n for (const [k, v] of Object.entries(this.config.defaultQueryParams ?? {})) {\n params.set(k, v)\n }\n\n if (query.pagination) {\n params.set('offset', String(query.pagination.offset))\n params.set('limit', String(query.pagination.limit))\n }\n\n if (query.sort && query.sort.length > 0) {\n params.set('sort', query.sort.map((s) => `${s.field}:${s.direction}`).join(','))\n }\n\n if (query.filter) {\n params.set('filter', JSON.stringify(query.filter))\n }\n\n if (query.include && query.include.length > 0) {\n params.set('include', query.include.join(','))\n }\n\n return params.toString()\n }\n\n private async buildHeaders(): Promise<Record<string, string>> {\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n ...this.config.headers,\n }\n\n if (this.config.auth) {\n const authHeader = await this.resolveAuthHeader(this.config.auth)\n if (authHeader) {\n Object.assign(headers, authHeader)\n }\n }\n\n return headers\n }\n\n private async resolveAuthHeader(auth: HttpAuthConfig): Promise<Record<string, string> | null> {\n switch (auth.type) {\n case 'bearer': {\n // Resolved per request, never cached — a session-length token is the\n // reason this accepts a function at all. A resolver that answers null\n // yields NO header: the server's own 401 is a truer error than a\n // client-side guess, and the panel's errorWhen already renders it.\n const token = typeof auth.token === 'function' ? await auth.token() : auth.token\n return token ? { Authorization: `Bearer ${token}` } : null\n }\n case 'api-key':\n return auth.apiKey ? { [auth.headerName ?? 'X-API-Key']: auth.apiKey } : null\n case 'basic':\n if (auth.username && auth.password) {\n const encoded = btoa(`${auth.username}:${auth.password}`)\n return { Authorization: `Basic ${encoded}` }\n }\n return null\n default:\n return null\n }\n }\n\n private async request(\n method: string,\n url: string,\n body?: Record<string, unknown>\n ): Promise<ConnectorResult> {\n const retryConfig = this.config.retry ?? DEFAULT_RETRY\n let lastError = ''\n\n for (let attempt = 0; attempt <= retryConfig.maxRetries; attempt++) {\n try {\n const controller = new AbortController()\n const timeoutId = setTimeout(() => controller.abort(), this.config.timeout)\n\n const response = await fetch(url, {\n method,\n headers: await this.buildHeaders(),\n body: body ? JSON.stringify(body) : null,\n signal: controller.signal,\n ...(this.config.credentials ? { credentials: this.config.credentials } : {}),\n })\n\n clearTimeout(timeoutId)\n\n if (!response.ok) {\n if (\n attempt < retryConfig.maxRetries &&\n retryConfig.retryableStatuses.includes(response.status)\n ) {\n const delay = Math.min(\n retryConfig.baseDelay * Math.pow(2, attempt),\n retryConfig.maxDelay\n )\n await this.sleep(delay)\n continue\n }\n\n const errorBody = await response.text().catch(() => '')\n lastError = `HTTP ${response.status}: ${errorBody || response.statusText}`\n return { success: false, error: lastError }\n }\n\n if (method === 'DELETE' && response.status === 204) {\n return { success: true, data: {} }\n }\n\n const jsonData = await response.json()\n const data = z.record(z.unknown()).parse(jsonData)\n return { success: true, data }\n } catch (err) {\n lastError = err instanceof Error ? err.message : String(err)\n\n if (attempt < retryConfig.maxRetries) {\n const delay = Math.min(retryConfig.baseDelay * Math.pow(2, attempt), retryConfig.maxDelay)\n await this.sleep(delay)\n continue\n }\n }\n }\n\n return { success: false, error: lastError }\n }\n\n private sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms))\n }\n}\n\n// ============================================================\n// FACTORY\n// ============================================================\n\n/**\n * Create an HTTP entity connector\n */\nexport function createHttpConnector(\n name: string,\n config: HttpConnectorConfig\n): HttpEntityConnector {\n return new HttpEntityConnector(name, config)\n}\n"]}
1
+ {"version":3,"file":"http-connector.js","sourceRoot":"","sources":["../../src/entity/http-connector.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,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CAAC,CAAC,EAAE,OAAO,CAAC,EAAE,WAAW,CAAC,QAAQ,CAAC,CAAA;oBAC1F,MAAM,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAA;oBACvB,SAAQ;gBACV,CAAC;YACH,CAAC;QACH,CAAC;QAED,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,SAAS,EAAE,CAAA;IAC7C,CAAC;IAEO,KAAK,CAAC,EAAU;QACtB,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,CAAA;IAC1D,CAAC;CACF;AAED,+DAA+D;AAC/D,UAAU;AACV,+DAA+D;AAE/D;;GAEG;AACH,MAAM,UAAU,mBAAmB,CACjC,IAAY,EACZ,MAA2B;IAE3B,OAAO,IAAI,mBAAmB,CAAC,IAAI,EAAE,MAAM,CAAC,CAAA;AAC9C,CAAC","sourcesContent":["/**\n * HTTP Entity Connector\n *\n * REST API connector for entity data persistence and retrieval.\n * Implements the EntityConnector interface using fetch for HTTP communication.\n *\n * @module @pwfabric/runtime/entity/http-connector\n */\n\nimport { z } from 'zod'\nimport type {\n EntityTypeId,\n EntityInstanceId,\n EntityQuery,\n EntityAggregate,\n EntityAggregateResult,\n} from './types.js'\nimport type {\n EntityConnector,\n EntityConnectorType,\n ConnectorResult,\n ConnectorQueryResult,\n ConnectorAggregateResult,\n} from './connector.js'\n\n// ============================================================\n// CONFIGURATION\n// ============================================================\n\n/**\n * HTTP connector authentication configuration\n */\nexport interface HttpAuthConfig {\n readonly type: 'bearer' | 'api-key' | 'basic'\n /**\n * A fixed value, or a RESOLVER re-invoked on every request.\n *\n * A string or a resolver. A delegated PKCE token expires within about an\n * hour, so a fixed string cannot serve a session; an engine that needs a\n * live token passes a resolver instead of reimplementing the transport\n * (and losing retry, timeout and the result envelope on the way).\n *\n * A string is used as is; a resolver is awaited per request and its answer\n * is never cached here, which is the whole point.\n */\n readonly token?: string | (() => Promise<string | null>)\n readonly apiKey?: string\n readonly headerName?: string\n readonly username?: string\n readonly password?: string\n}\n\n/**\n * HTTP connector retry configuration\n */\nexport interface HttpRetryConfig {\n readonly maxRetries: number\n readonly baseDelay: number\n readonly maxDelay: number\n readonly retryableStatuses: readonly number[]\n}\n\n/**\n * HTTP connector configuration\n */\nexport interface HttpConnectorConfig {\n readonly baseUrl: string\n readonly headers?: Record<string, string>\n readonly timeout?: number\n readonly auth?: HttpAuthConfig\n /**\n * Fetch credentials mode. Set 'include' so cookie-authoritative APIs\n * receive the session cookie on cross-origin entity requests\n * the visitor facade has no bearer token to send.\n */\n readonly credentials?: RequestCredentials\n readonly retry?: HttpRetryConfig\n /**\n * Query parameters this API requires on every read.\n *\n * GENERIC, and the distinction matters because three vendor-shaped widenings\n * were proposed and reverted the same day. Azure wants `api-version`, plenty\n * of APIs want `format=json`, Graph wants `expand=fields`: \"this endpoint\n * takes constant parameters\" is a REST fact, not one provider's dance, and no\n * provider name appears here.\n *\n * It exists because the alternative is worse. A caller that put its constants\n * in `entityPathMapper` would produce `...?expand=fields?limit=50` the moment\n * a query carried pagination, and `...?expand=fields/1` on a delete — the URL\n * is assembled as `params ? url + '?' + params : url`.\n */\n readonly defaultQueryParams?: Readonly<Record<string, string>>\n readonly entityPathMapper?: (entityType: EntityTypeId) => string\n /**\n * Maps a vendor response body to the connector's query result shape\n * `entityPathMapper`'s response-side twin.\n *\n * `entityPathMapper` has always let a caller say how an entity type becomes a\n * URL path; nothing let it say how the answer comes back. So a vendor whose\n * body is its own shape — Graph replies `{ value: [{ id, fields }] }`, not\n * `{ items }` — could not use this class at all, and that was the other half\n * of why every Graph engine forked. Absent, the built-in shapes below apply\n * unchanged.\n */\n readonly responseMapper?: (raw: unknown) => { items: unknown[]; total?: number }\n}\n\n// ============================================================\n// DEFAULTS\n// ============================================================\n\nconst queryResponseSchema = z\n .object({\n items: z.array(z.unknown()).optional(),\n total: z.number().optional(),\n offset: z.number().optional(),\n limit: z.number().optional(),\n })\n .passthrough()\n\n/**\n * `{ data: { fn, field?, value, count, numericCount? }, meta }` is how the\n * platform answers (`routes/app-records.ts`); a bare `{ value, count }` body\n * is accepted too. `value` is null when a numeric fn had nothing to reduce.\n */\nconst aggregateBodySchema = z\n .object({\n fn: z.enum(['count', 'sum', 'avg']).optional(),\n field: z.string().optional(),\n value: z.number().nullable().optional(),\n count: z.number().optional(),\n })\n .passthrough()\n\nconst DEFAULT_TIMEOUT = 30_000\n\nconst DEFAULT_RETRY: HttpRetryConfig = {\n maxRetries: 3,\n baseDelay: 1000,\n maxDelay: 10_000,\n retryableStatuses: [408, 429, 500, 502, 503, 504],\n}\n\n// ============================================================\n// HTTP ENTITY CONNECTOR\n// ============================================================\n\n/**\n * HTTP/REST connector for entity data operations.\n * Maps entity CRUD operations to standard REST API endpoints.\n */\nexport class HttpEntityConnector implements EntityConnector {\n readonly name: string\n readonly type: EntityConnectorType = 'http'\n\n private readonly config: Required<Pick<HttpConnectorConfig, 'baseUrl' | 'timeout'>> &\n HttpConnectorConfig\n\n constructor(name: string, config: HttpConnectorConfig) {\n this.name = name\n this.config = {\n ...config,\n timeout: config.timeout ?? DEFAULT_TIMEOUT,\n }\n }\n\n async create(entityType: EntityTypeId, data: Record<string, unknown>): Promise<ConnectorResult> {\n const url = this.buildUrl(entityType)\n return this.request('POST', url, data)\n }\n\n async read(entityType: EntityTypeId, instanceId: EntityInstanceId): Promise<ConnectorResult> {\n const url = `${this.buildUrl(entityType)}/${instanceId}`\n return this.request('GET', url)\n }\n\n async update(\n entityType: EntityTypeId,\n instanceId: EntityInstanceId,\n data: Record<string, unknown>\n ): Promise<ConnectorResult> {\n const url = `${this.buildUrl(entityType)}/${instanceId}`\n return this.request('PATCH', url, data)\n }\n\n async delete(entityType: EntityTypeId, instanceId: EntityInstanceId): Promise<ConnectorResult> {\n const url = `${this.buildUrl(entityType)}/${instanceId}`\n return this.request('DELETE', url)\n }\n\n async query(entityType: EntityTypeId, query: EntityQuery): Promise<ConnectorQueryResult> {\n const url = this.buildUrl(entityType)\n const params = this.buildQueryParams(query)\n const fullUrl = params ? `${url}?${params}` : url\n\n const result = await this.request('GET', fullUrl)\n if (!result.success) {\n return { success: false, error: result.error }\n }\n\n // A vendor shape is mapped BEFORE the built-in schema runs — the mapper\n // exists precisely for bodies this schema would reject, so validating first\n // would refuse the very responses it was added to accept.\n if (this.config.responseMapper) {\n const mapped = this.config.responseMapper(result.data)\n const items = mapped.items as Record<string, unknown>[]\n const total = mapped.total ?? items.length\n const offset = query.pagination?.offset ?? 0\n return {\n success: true,\n result: {\n items,\n total,\n offset,\n limit: query.pagination?.limit ?? items.length,\n hasMore: total > offset + items.length,\n },\n }\n }\n\n const parsed = queryResponseSchema.safeParse(result.data)\n if (!parsed.success) {\n return { success: false, error: 'Invalid query response shape' }\n }\n const data = parsed.data as Record<string, unknown>\n\n // Accept both the connector contract ({items,total}) and the platform\n // entity-records envelope ({data:[...], meta:{total}}).\n const rawItems = ((data.items as unknown[]) ??\n (data.data as unknown[]) ??\n []) as Record<string, unknown>[]\n // Entity records store user fields under `.data` — flatten them to the top\n // level so expression/column bindings ({{id}}, column key 'name') resolve\n // against the fields, while keeping id/metadata available.\n const items = rawItems.map((r) =>\n r && typeof r === 'object' && r.data && typeof r.data === 'object'\n ? { ...r, ...(r.data as Record<string, unknown>) }\n : r\n )\n const meta = data.meta as Record<string, unknown> | undefined\n const total = (data.total as number) ?? (meta?.total as number) ?? items.length\n\n return {\n success: true,\n result: {\n items,\n total,\n offset: (data.offset as number) ?? query.pagination?.offset ?? 0,\n limit: (data.limit as number) ?? query.pagination?.limit ?? 50,\n hasMore: total > ((data.offset as number) ?? 0) + items.length,\n },\n }\n }\n\n /**\n * One number over the collection, computed by the server.\n *\n * `GET <base>/<type>/count[?filter=]` for a plain count and\n * `GET <base>/<type>/aggregate?fn=&field=&filter=` for the rest — the two\n * routes a host registers ahead of the read-one route.\n * Constants (`defaultQueryParams`) and `entityPathMapper` apply as on\n * every other read.\n */\n async aggregate(entityType: EntityTypeId, aggregate: EntityAggregate): Promise<ConnectorAggregateResult> {\n const plainCount = aggregate.fn === 'count' && !aggregate.field\n const params = new URLSearchParams()\n for (const [k, v] of Object.entries(this.config.defaultQueryParams ?? {})) params.set(k, v)\n if (!plainCount) {\n params.set('fn', aggregate.fn)\n if (aggregate.field) params.set('field', aggregate.field)\n }\n if (aggregate.filter) params.set('filter', JSON.stringify(aggregate.filter))\n const url = `${this.buildUrl(entityType)}/${plainCount ? 'count' : 'aggregate'}`\n const qs = params.toString()\n\n const result = await this.request('GET', qs ? `${url}?${qs}` : url)\n if (!result.success) return { success: false, error: result.error }\n\n const envelope = result.data\n const body = envelope.data && typeof envelope.data === 'object' ? envelope.data : envelope\n const parsed = aggregateBodySchema.safeParse(body)\n if (!parsed.success) return { success: false, error: 'Invalid aggregate response shape' }\n const d = parsed.data\n const field = d.field ?? aggregate.field\n const out: EntityAggregateResult = {\n fn: d.fn ?? aggregate.fn,\n ...(field ? { field } : {}),\n value: d.value ?? null,\n count: d.count ?? 0,\n }\n return { success: true, result: out }\n }\n\n // ============================================================\n // PRIVATE HELPERS\n // ============================================================\n\n private buildUrl(entityType: EntityTypeId): string {\n const path = this.config.entityPathMapper\n ? this.config.entityPathMapper(entityType)\n : `/${entityType}`\n return `${this.config.baseUrl}${path}`\n }\n\n private buildQueryParams(query: EntityQuery): string {\n const params = new URLSearchParams()\n\n // Constants first so a caller's own query can still override one.\n for (const [k, v] of Object.entries(this.config.defaultQueryParams ?? {})) {\n params.set(k, v)\n }\n\n if (query.pagination) {\n params.set('offset', String(query.pagination.offset))\n params.set('limit', String(query.pagination.limit))\n }\n\n if (query.sort && query.sort.length > 0) {\n params.set('sort', query.sort.map((s) => `${s.field}:${s.direction}`).join(','))\n }\n\n if (query.filter) {\n params.set('filter', JSON.stringify(query.filter))\n }\n\n if (query.include && query.include.length > 0) {\n params.set('include', query.include.join(','))\n }\n\n return params.toString()\n }\n\n private async buildHeaders(): Promise<Record<string, string>> {\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n ...this.config.headers,\n }\n\n if (this.config.auth) {\n const authHeader = await this.resolveAuthHeader(this.config.auth)\n if (authHeader) {\n Object.assign(headers, authHeader)\n }\n }\n\n return headers\n }\n\n private async resolveAuthHeader(auth: HttpAuthConfig): Promise<Record<string, string> | null> {\n switch (auth.type) {\n case 'bearer': {\n // Resolved per request, never cached — a session-length token is the\n // reason this accepts a function at all. A resolver that answers null\n // yields NO header: the server's own 401 is a truer error than a\n // client-side guess, and the panel's errorWhen already renders it.\n const token = typeof auth.token === 'function' ? await auth.token() : auth.token\n return token ? { Authorization: `Bearer ${token}` } : null\n }\n case 'api-key':\n return auth.apiKey ? { [auth.headerName ?? 'X-API-Key']: auth.apiKey } : null\n case 'basic':\n if (auth.username && auth.password) {\n const encoded = btoa(`${auth.username}:${auth.password}`)\n return { Authorization: `Basic ${encoded}` }\n }\n return null\n default:\n return null\n }\n }\n\n private async request(\n method: string,\n url: string,\n body?: Record<string, unknown>\n ): Promise<ConnectorResult> {\n const retryConfig = this.config.retry ?? DEFAULT_RETRY\n let lastError = ''\n\n for (let attempt = 0; attempt <= retryConfig.maxRetries; attempt++) {\n try {\n const controller = new AbortController()\n const timeoutId = setTimeout(() => controller.abort(), this.config.timeout)\n\n const response = await fetch(url, {\n method,\n headers: await this.buildHeaders(),\n body: body ? JSON.stringify(body) : null,\n signal: controller.signal,\n ...(this.config.credentials ? { credentials: this.config.credentials } : {}),\n })\n\n clearTimeout(timeoutId)\n\n if (!response.ok) {\n if (\n attempt < retryConfig.maxRetries &&\n retryConfig.retryableStatuses.includes(response.status)\n ) {\n const delay = Math.min(\n retryConfig.baseDelay * Math.pow(2, attempt),\n retryConfig.maxDelay\n )\n await this.sleep(delay)\n continue\n }\n\n const errorBody = await response.text().catch(() => '')\n lastError = `HTTP ${response.status}: ${errorBody || response.statusText}`\n return { success: false, error: lastError }\n }\n\n if (method === 'DELETE' && response.status === 204) {\n return { success: true, data: {} }\n }\n\n const jsonData = await response.json()\n const data = z.record(z.string(), z.unknown()).parse(jsonData)\n return { success: true, data }\n } catch (err) {\n lastError = err instanceof Error ? err.message : String(err)\n\n if (attempt < retryConfig.maxRetries) {\n const delay = Math.min(retryConfig.baseDelay * Math.pow(2, attempt), retryConfig.maxDelay)\n await this.sleep(delay)\n continue\n }\n }\n }\n\n return { success: false, error: lastError }\n }\n\n private sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms))\n }\n}\n\n// ============================================================\n// FACTORY\n// ============================================================\n\n/**\n * Create an HTTP entity connector\n */\nexport function createHttpConnector(\n name: string,\n config: HttpConnectorConfig\n): HttpEntityConnector {\n return new HttpEntityConnector(name, config)\n}\n"]}
@@ -62,7 +62,7 @@ export class InMemoryEntityRegistry {
62
62
  };
63
63
  }
64
64
  const errors = result.error.issues.map((issue) => ({
65
- field: issue.path.join('.') || '_root',
65
+ field: issue.path.map(String).join('.') || '_root',
66
66
  message: issue.message,
67
67
  code: issue.code,
68
68
  }));
@@ -1 +1 @@
1
- {"version":3,"file":"registry.js","sourceRoot":"","sources":["../../src/entity/registry.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAsDH,+DAA+D;AAC/D,4BAA4B;AAC5B,+DAA+D;AAE/D;;GAEG;AACH,MAAM,OAAO,sBAAsB;IAChB,WAAW,GAAG,IAAI,GAAG,EAAkC,CAAA;IAExE,QAAQ,CAAC,UAA4B;QACnC,IAAI,CAAC,UAAU,CAAC,EAAE,EAAE,CAAC;YACnB,MAAM,IAAI,KAAK,CAAC,mCAAmC,CAAC,CAAA;QACtD,CAAC;QAED,IAAI,CAAC,UAAU,CAAC,IAAI,EAAE,CAAC;YACrB,MAAM,IAAI,KAAK,CAAC,oCAAoC,CAAC,CAAA;QACvD,CAAC;QAED,IAAI,CAAC,UAAU,CAAC,MAAM,EAAE,CAAC;YACvB,MAAM,IAAI,KAAK,CAAC,sCAAsC,CAAC,CAAA;Q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AA+B;aAC7C,CAAA;QACH,CAAC;QAED,MAAM,MAAM,GAA4B,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;YAC1E,KAAK,EAAE,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,OAAO;YACtC,OAAO,EAAE,KAAK,CAAC,OAAO;YACtB,IAAI,EAAE,KAAK,CAAC,IAAI;SACjB,CAAC,CAAC,CAAA;QAEH,OAAO;YACL,KAAK,EAAE,KAAK;YACZ,MAAM;SACP,CAAA;IACH,CAAC;IAED,UAAU,CAAC,EAAgB;QACzB,OAAO,IAAI,CAAC,WAAW,CAAC,MAAM,CAAC,EAAE,CAAC,CAAA;IACpC,CAAC;IAED,KAAK;QACH,IAAI,CAAC,WAAW,CAAC,KAAK,EAAE,CAAA;IAC1B,CAAC;CACF;AAED,+DAA+D;AAC/D,mBAAmB;AACnB,+DAA+D;AAE/D;;GAEG;AACH,MAAM,UAAU,oBAAoB;IAClC,OAAO,IAAI,sBAAsB,EAAE,CAAA;AACrC,CAAC","sourcesContent":["/**\n * Entity Registry\n *\n * Registration and lookup of entity definitions with Zod-based validation.\n *\n * @module @pwfabric/runtime/entity/registry\n */\n\nimport type {\n EntityTypeId,\n EntityDefinition,\n EntityValidationResult,\n EntityValidationError,\n} from './types.js'\n\n// ============================================================\n// ENTITY REGISTRY INTERFACE\n// ============================================================\n\n/**\n * Registry for entity type definitions\n */\nexport interface EntityRegistry {\n /**\n * Register an entity definition\n * @throws Error if definition with the same id is already registered\n */\n register(definition: EntityDefinition): void\n\n /**\n * Get an entity definition by id\n */\n get(id: EntityTypeId): EntityDefinition | undefined\n\n /**\n * Check if an entity definition is registered\n */\n has(id: EntityTypeId): boolean\n\n /**\n * List all registered entity type ids\n */\n list(): readonly EntityTypeId[]\n\n /**\n * Validate data against an entity definition's Zod schema\n */\n validate(id: EntityTypeId, data: unknown): EntityValidationResult\n\n /**\n * Remove an entity definition\n */\n unregister(id: EntityTypeId): boolean\n\n /**\n * Remove all entity definitions\n */\n clear(): void\n}\n\n// ============================================================\n// IN-MEMORY ENTITY REGISTRY\n// ============================================================\n\n/**\n * In-memory implementation of EntityRegistry\n */\nexport class InMemoryEntityRegistry implements EntityRegistry {\n private readonly definitions = new Map<EntityTypeId, EntityDefinition>()\n\n register(definition: EntityDefinition): void {\n if (!definition.id) {\n throw new Error('Entity definition must have an id')\n }\n\n if (!definition.name) {\n throw new Error('Entity definition must have a name')\n }\n\n if (!definition.schema) {\n throw new Error('Entity definition must have a schema')\n }\n\n if (!definition.primaryKey) {\n throw new Error('Entity definition must have a primaryKey')\n }\n\n if (this.definitions.has(definition.id)) {\n throw new Error(`Entity type '${definition.id}' is already registered`)\n }\n\n this.definitions.set(definition.id, definition)\n }\n\n get(id: EntityTypeId): EntityDefinition | undefined {\n return this.definitions.get(id)\n }\n\n has(id: EntityTypeId): boolean {\n return this.definitions.has(id)\n }\n\n list(): readonly EntityTypeId[] {\n return Array.from(this.definitions.keys())\n }\n\n validate(id: EntityTypeId, data: unknown): EntityValidationResult {\n const definition = this.definitions.get(id)\n if (!definition) {\n return {\n valid: false,\n errors: [\n {\n field: '_entity',\n message: `Entity type '${id}' is not registered`,\n code: 'entity_not_found',\n },\n ],\n }\n }\n\n const result = definition.schema.safeParse(data)\n\n if (result.success) {\n return {\n valid: true,\n data: result.data as Record<string, unknown>,\n }\n }\n\n const errors: EntityValidationError[] = result.error.issues.map((issue) => ({\n field: issue.path.join('.') || '_root',\n message: issue.message,\n code: issue.code,\n }))\n\n return {\n valid: false,\n errors,\n }\n }\n\n unregister(id: EntityTypeId): boolean {\n return this.definitions.delete(id)\n }\n\n clear(): void {\n this.definitions.clear()\n }\n}\n\n// ============================================================\n// FACTORY FUNCTION\n// ============================================================\n\n/**\n * Create an entity registry\n */\nexport function createEntityRegistry(): EntityRegistry {\n return new InMemoryEntityRegistry()\n}\n"]}
1
+ {"version":3,"file":"registry.js","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BAAsB,EAAE,CAAA;AACrC,CAAC","sourcesContent":["/**\n * Entity Registry\n *\n * Registration and lookup of entity definitions with Zod-based validation.\n *\n * @module @pwfabric/runtime/entity/registry\n */\n\nimport type {\n EntityTypeId,\n EntityDefinition,\n EntityValidationResult,\n EntityValidationError,\n} from './types.js'\n\n// ============================================================\n// ENTITY REGISTRY INTERFACE\n// ============================================================\n\n/**\n * Registry for entity type definitions\n */\nexport interface EntityRegistry {\n /**\n * Register an entity definition\n * @throws Error if definition with the same id is already registered\n */\n register(definition: EntityDefinition): void\n\n /**\n * Get an entity definition by id\n */\n get(id: EntityTypeId): EntityDefinition | undefined\n\n /**\n * Check if an entity definition is registered\n */\n has(id: EntityTypeId): boolean\n\n /**\n * List all registered entity type ids\n */\n list(): readonly EntityTypeId[]\n\n /**\n * Validate data against an entity definition's Zod schema\n */\n validate(id: EntityTypeId, data: unknown): EntityValidationResult\n\n /**\n * Remove an entity definition\n */\n unregister(id: EntityTypeId): boolean\n\n /**\n * Remove all entity definitions\n */\n clear(): void\n}\n\n// ============================================================\n// IN-MEMORY ENTITY REGISTRY\n// ============================================================\n\n/**\n * In-memory implementation of EntityRegistry\n */\nexport class InMemoryEntityRegistry implements EntityRegistry {\n private readonly definitions = new Map<EntityTypeId, EntityDefinition>()\n\n register(definition: EntityDefinition): void {\n if (!definition.id) {\n throw new Error('Entity definition must have an id')\n }\n\n if (!definition.name) {\n throw new Error('Entity definition must have a name')\n }\n\n if (!definition.schema) {\n throw new Error('Entity definition must have a schema')\n }\n\n if (!definition.primaryKey) {\n throw new Error('Entity definition must have a primaryKey')\n }\n\n if (this.definitions.has(definition.id)) {\n throw new Error(`Entity type '${definition.id}' is already registered`)\n }\n\n this.definitions.set(definition.id, definition)\n }\n\n get(id: EntityTypeId): EntityDefinition | undefined {\n return this.definitions.get(id)\n }\n\n has(id: EntityTypeId): boolean {\n return this.definitions.has(id)\n }\n\n list(): readonly EntityTypeId[] {\n return Array.from(this.definitions.keys())\n }\n\n validate(id: EntityTypeId, data: unknown): EntityValidationResult {\n const definition = this.definitions.get(id)\n if (!definition) {\n return {\n valid: false,\n errors: [\n {\n field: '_entity',\n message: `Entity type '${id}' is not registered`,\n code: 'entity_not_found',\n },\n ],\n }\n }\n\n const result = definition.schema.safeParse(data)\n\n if (result.success) {\n return {\n valid: true,\n data: result.data as Record<string, unknown>,\n }\n }\n\n const errors: EntityValidationError[] = result.error.issues.map((issue) => ({\n field: issue.path.map(String).join('.') || '_root',\n message: issue.message,\n code: issue.code,\n }))\n\n return {\n valid: false,\n errors,\n }\n }\n\n unregister(id: EntityTypeId): boolean {\n return this.definitions.delete(id)\n }\n\n clear(): void {\n this.definitions.clear()\n }\n}\n\n// ============================================================\n// FACTORY FUNCTION\n// ============================================================\n\n/**\n * Create an entity registry\n */\nexport function createEntityRegistry(): EntityRegistry {\n return new InMemoryEntityRegistry()\n}\n"]}
@@ -169,7 +169,7 @@ export function validateWithZod(values, schema) {
169
169
  function formatZodErrors(error) {
170
170
  const errors = {};
171
171
  for (const issue of error.issues) {
172
- const path = issue.path.join('.');
172
+ const path = issue.path.map(String).join('.');
173
173
  if (!errors[path]) {
174
174
  errors[path] = [];
175
175
  }
@@ -1 +1 @@
1
- {"version":3,"file":"validator.js","sourceRoot":"","sources":["../../src/forms/validator.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAE,CAAC,EAA+B,MAAM,KAAK,CAAA;AAQpD,OAAO,EAAE,2BAA2B,EAAE,MAAM,YAAY,CAAA;AAExD,+DAA+D;AAC/D,yBAAyB;AACzB,+DAA+D;AAE/D;;GAEG;AACH,MAAM,OAAO,oBAAoB;IACd,QAAQ,CAAoB;IAE7C,YAAY,iBAA8C,EAAE;QAC1D,IAAI,CAAC,QAAQ,GAAG,EAAE,GAAG,2BAA2B,EAAE,GAAG,cAAc,EAAE,CAAA;IACvE,CAAC;IAED,aAAa,CAAC,KAAc,EAAE,KAAgB;QAC5C,MAAM,MAAM,GAAa,EAAE,C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AAC,oCAAoC,CAAC;IAE7D;;OAEG;IACH,cAAc,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,EAAE,wBAAwB,CAAC;IAE3D;;OAEG;IACH,GAAG,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,0BAA0B,CAAC;IAE/C;;OAEG;IACH,KAAK,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,KAAK,CAAC,iBAAiB,EAAE,mCAAmC,CAAC;IAE/E;;OAEG;IACH,QAAQ,EAAE,CAAC;SACR,MAAM,EAAE;SACR,GAAG,CAAC,CAAC,EAAE,wCAAwC,CAAC;SAChD,KAAK,CAAC,UAAU,EAAE,2CAA2C,CAAC;SAC9D,KAAK,CAAC,OAAO,EAAE,2CAA2C,CAAC;CAC/D,CAAA;AAED;;GAEG;AACH,MAAM,UAAU,mBAAmB,CAAC,cAA4C;IAC9E,OAAO,IAAI,oBAAoB,CAAC,cAAc,CAAC,CAAA;AACjD,CAAC","sourcesContent":["/**\n * Form Validator\n *\n * Form validation implementation\n *\n * @module @pwfabric/runtime/forms/validator\n */\n\nimport { z, type ZodType, type ZodError } from 'zod'\nimport type {\n FormValidator,\n FormField,\n ValidationRule,\n FormValidationResult,\n ValidationMessages,\n} from './types.js'\nimport { DEFAULT_VALIDATION_MESSAGES } from './types.js'\n\n// ============================================================\n// DEFAULT FORM VALIDATOR\n// ============================================================\n\n/**\n * Default form validator implementation\n */\nexport class DefaultFormValidator implements FormValidator {\n private readonly messages: ValidationMessages\n\n constructor(customMessages: Partial<ValidationMessages> = {}) {\n this.messages = { ...DEFAULT_VALIDATION_MESSAGES, ...customMessages }\n }\n\n validateField(value: unknown, field: FormField): string[] {\n const errors: string[] = []\n\n // Check required\n if (field.required && this.isEmpty(value)) {\n errors.push(this.messages.required)\n return errors // Return early if required and empty\n }\n\n // Skip other validations if value is empty and not required\n if (this.isEmpty(value) && !field.required) {\n return errors\n }\n\n // Run custom validation rules\n if (field.validation) {\n for (const rule of field.validation) {\n const error = this.validateRule(value, rule)\n if (error) {\n errors.push(error)\n }\n }\n }\n\n return errors\n }\n\n validateAll(values: Record<string, unknown>, fields: readonly FormField[]): FormValidationResult {\n const errors: Record<string, string[]> = {}\n let hasErrors = false\n\n for (const field of fields) {\n const value = values[field.name]\n const fieldErrors = this.validateField(value, field)\n\n if (fieldErrors.length > 0) {\n errors[field.name] = fieldErrors\n hasErrors = true\n }\n }\n\n return {\n valid: !hasErrors,\n errors,\n }\n }\n\n private validateRule(value: unknown, rule: ValidationRule): string | null {\n switch (rule.type) {\n case 'required':\n return this.isEmpty(value) ? rule.message : null\n\n case 'email':\n return this.validateEmail(value, rule.message)\n\n case 'url':\n return this.validateUrl(value, rule.message)\n\n case 'minLength':\n return this.validateMinLength(value, rule.value as number, rule.message)\n\n case 'maxLength':\n return this.validateMaxLength(value, rule.value as number, rule.message)\n\n case 'min':\n return this.validateMin(value, rule.value as number, rule.message)\n\n case 'max':\n return this.validateMax(value, rule.value as number, rule.message)\n\n case 'pattern':\n return this.validatePattern(value, rule.value as string | RegExp, rule.message)\n\n case 'custom':\n // Custom validation function is expected to be in rule.value\n if (typeof rule.value === 'function') {\n const isValid = (rule.value as (v: unknown) => boolean)(value)\n return isValid ? null : rule.message\n }\n return null\n\n default:\n return null\n }\n }\n\n private isEmpty(value: unknown): boolean {\n if (value === null || value === undefined) return true\n if (typeof value === 'string') return value.trim() === ''\n if (Array.isArray(value)) return value.length === 0\n return false\n }\n\n private validateEmail(value: unknown, message: string): string | null {\n if (typeof value !== 'string') return message\n\n // Basic email regex - covers most common cases\n const emailRegex = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/\n return emailRegex.test(value) ? null : message\n }\n\n private validateUrl(value: unknown, message: string): string | null {\n if (typeof value !== 'string') return message\n\n try {\n new URL(value)\n return null\n } catch {\n return message\n }\n }\n\n private validateMinLength(value: unknown, minLength: number, message: string): string | null {\n if (typeof value !== 'string') return message\n return value.length >= minLength ? null : this.formatMessage(message, minLength)\n }\n\n private validateMaxLength(value: unknown, maxLength: number, message: string): string | null {\n if (typeof value !== 'string') return message\n return value.length <= maxLength ? null : this.formatMessage(message, maxLength)\n }\n\n private validateMin(value: unknown, min: number, message: string): string | null {\n const num = Number(value)\n if (Number.isNaN(num)) return message\n return num >= min ? null : this.formatMessage(message, min)\n }\n\n private validateMax(value: unknown, max: number, message: string): string | null {\n const num = Number(value)\n if (Number.isNaN(num)) return message\n return num <= max ? null : this.formatMessage(message, max)\n }\n\n private validatePattern(\n value: unknown,\n pattern: string | RegExp,\n message: string\n ): string | null {\n if (typeof value !== 'string') return message\n\n const regex = typeof pattern === 'string' ? new RegExp(pattern) : pattern\n return regex.test(value) ? null : message\n }\n\n private formatMessage(message: string, value: unknown): string {\n return message.replace('{value}', String(value))\n }\n}\n\n// ============================================================\n// ZOD SCHEMA VALIDATOR\n// ============================================================\n\n/**\n * Validate values using a Zod schema\n */\nexport function validateWithZod<T>(\n values: Record<string, unknown>,\n schema: ZodType<T>\n): FormValidationResult {\n const result = schema.safeParse(values)\n\n if (result.success) {\n return {\n valid: true,\n errors: {},\n }\n }\n\n return {\n valid: false,\n errors: formatZodErrors(result.error),\n }\n}\n\n/**\n * Convert Zod errors to FormValidationResult format\n */\nfunction formatZodErrors(error: ZodError): Record<string, string[]> {\n const errors: Record<string, string[]> = {}\n\n for (const issue of error.issues) {\n const path = issue.path.join('.')\n if (!errors[path]) {\n errors[path] = []\n }\n errors[path].push(issue.message)\n }\n\n return errors\n}\n\n// ============================================================\n// BUILT-IN ZOD SCHEMAS\n// ============================================================\n\n/**\n * Common Zod schemas for form validation\n */\nexport const FormSchemas = {\n /**\n * Email validation schema\n */\n email: z.string().email('Please enter a valid email address'),\n\n /**\n * Required string schema\n */\n requiredString: z.string().min(1, 'This field is required'),\n\n /**\n * URL validation schema\n */\n url: z.string().url('Please enter a valid URL'),\n\n /**\n * Phone number schema (basic)\n */\n phone: z.string().regex(/^\\+?[\\d\\s-()]+$/, 'Please enter a valid phone number'),\n\n /**\n * Password schema (min 8 chars, at least one number and letter)\n */\n password: z\n .string()\n .min(8, 'Password must be at least 8 characters')\n .regex(/[a-zA-Z]/, 'Password must contain at least one letter')\n .regex(/[0-9]/, 'Password must contain at least one number'),\n}\n\n/**\n * Create a form validator\n */\nexport function createFormValidator(customMessages?: Partial<ValidationMessages>): FormValidator {\n return new DefaultFormValidator(customMessages)\n}\n"]}
1
+ {"version":3,"file":"validator.js","sourceRoot":"","sources":["../../src/forms/validator.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAE,CAAC,EAA+B,MAAM,KAAK,CAAA;AAQpD,OAAO,EAAE,2BAA2B,EAAE,MAAM,YAAY,CAAA;AAExD,+DAA+D;AAC/D,yBAAyB;AACzB,+DAA+D;AAE/D;;GAEG;AACH,MAAM,OAAO,oBAAoB;IACd,QAAQ,CAAoB;IAE7C,YAAY,iBAA8C,EAAE;QAC1D,IAAI,CAAC,QAAQ,GAAG,EAAE,GAAG,2BAA2B,EAAE,GAAG,cAAc,EAAE,CAAA;IACvE,CAAC;IAED,aAAa,CAAC,KAAc,EAAE,KAAgB;QAC5C,MAAM,MAAM,GAAa,EAAE,CAAA;QAE3B,iBAAiB;QACjB,IAAI,KAAK,CAAC,QAAQ,IAAI,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;YAC1C,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAA;YACnC,OAAO,MAAM,CAAA,CAAC,qCAAqC;QACrD,CAAC;QAED,4DAA4D;QAC5D,IAAI,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,QAAQ,EAAE,CAAC;YAC3C,OAAO,MAAM,CAAA;QACf,CAAC;QAED,8BAA8B;QAC9B,IAAI,KAAK,CAAC,UAAU,EAAE,CAAC;YACrB,KAAK,MAAM,IAAI,IAAI,KAAK,CAAC,UAAU,EAAE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SAC9D,KAAK,CAAC,OAAO,EAAE,2CAA2C,CAAC;CAC/D,CAAA;AAED;;GAEG;AACH,MAAM,UAAU,mBAAmB,CAAC,cAA4C;IAC9E,OAAO,IAAI,oBAAoB,CAAC,cAAc,CAAC,CAAA;AACjD,CAAC","sourcesContent":["/**\n * Form Validator\n *\n * Form validation implementation\n *\n * @module @pwfabric/runtime/forms/validator\n */\n\nimport { z, type ZodType, type ZodError } from 'zod'\nimport type {\n FormValidator,\n FormField,\n ValidationRule,\n FormValidationResult,\n ValidationMessages,\n} from './types.js'\nimport { DEFAULT_VALIDATION_MESSAGES } from './types.js'\n\n// ============================================================\n// DEFAULT FORM VALIDATOR\n// ============================================================\n\n/**\n * Default form validator implementation\n */\nexport class DefaultFormValidator implements FormValidator {\n private readonly messages: ValidationMessages\n\n constructor(customMessages: Partial<ValidationMessages> = {}) {\n this.messages = { ...DEFAULT_VALIDATION_MESSAGES, ...customMessages }\n }\n\n validateField(value: unknown, field: FormField): string[] {\n const errors: string[] = []\n\n // Check required\n if (field.required && this.isEmpty(value)) {\n errors.push(this.messages.required)\n return errors // Return early if required and empty\n }\n\n // Skip other validations if value is empty and not required\n if (this.isEmpty(value) && !field.required) {\n return errors\n }\n\n // Run custom validation rules\n if (field.validation) {\n for (const rule of field.validation) {\n const error = this.validateRule(value, rule)\n if (error) {\n errors.push(error)\n }\n }\n }\n\n return errors\n }\n\n validateAll(values: Record<string, unknown>, fields: readonly FormField[]): FormValidationResult {\n const errors: Record<string, string[]> = {}\n let hasErrors = false\n\n for (const field of fields) {\n const value = values[field.name]\n const fieldErrors = this.validateField(value, field)\n\n if (fieldErrors.length > 0) {\n errors[field.name] = fieldErrors\n hasErrors = true\n }\n }\n\n return {\n valid: !hasErrors,\n errors,\n }\n }\n\n private validateRule(value: unknown, rule: ValidationRule): string | null {\n switch (rule.type) {\n case 'required':\n return this.isEmpty(value) ? rule.message : null\n\n case 'email':\n return this.validateEmail(value, rule.message)\n\n case 'url':\n return this.validateUrl(value, rule.message)\n\n case 'minLength':\n return this.validateMinLength(value, rule.value as number, rule.message)\n\n case 'maxLength':\n return this.validateMaxLength(value, rule.value as number, rule.message)\n\n case 'min':\n return this.validateMin(value, rule.value as number, rule.message)\n\n case 'max':\n return this.validateMax(value, rule.value as number, rule.message)\n\n case 'pattern':\n return this.validatePattern(value, rule.value as string | RegExp, rule.message)\n\n case 'custom':\n // Custom validation function is expected to be in rule.value\n if (typeof rule.value === 'function') {\n const isValid = (rule.value as (v: unknown) => boolean)(value)\n return isValid ? null : rule.message\n }\n return null\n\n default:\n return null\n }\n }\n\n private isEmpty(value: unknown): boolean {\n if (value === null || value === undefined) return true\n if (typeof value === 'string') return value.trim() === ''\n if (Array.isArray(value)) return value.length === 0\n return false\n }\n\n private validateEmail(value: unknown, message: string): string | null {\n if (typeof value !== 'string') return message\n\n // Basic email regex - covers most common cases\n const emailRegex = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/\n return emailRegex.test(value) ? null : message\n }\n\n private validateUrl(value: unknown, message: string): string | null {\n if (typeof value !== 'string') return message\n\n try {\n new URL(value)\n return null\n } catch {\n return message\n }\n }\n\n private validateMinLength(value: unknown, minLength: number, message: string): string | null {\n if (typeof value !== 'string') return message\n return value.length >= minLength ? null : this.formatMessage(message, minLength)\n }\n\n private validateMaxLength(value: unknown, maxLength: number, message: string): string | null {\n if (typeof value !== 'string') return message\n return value.length <= maxLength ? null : this.formatMessage(message, maxLength)\n }\n\n private validateMin(value: unknown, min: number, message: string): string | null {\n const num = Number(value)\n if (Number.isNaN(num)) return message\n return num >= min ? null : this.formatMessage(message, min)\n }\n\n private validateMax(value: unknown, max: number, message: string): string | null {\n const num = Number(value)\n if (Number.isNaN(num)) return message\n return num <= max ? null : this.formatMessage(message, max)\n }\n\n private validatePattern(\n value: unknown,\n pattern: string | RegExp,\n message: string\n ): string | null {\n if (typeof value !== 'string') return message\n\n const regex = typeof pattern === 'string' ? new RegExp(pattern) : pattern\n return regex.test(value) ? null : message\n }\n\n private formatMessage(message: string, value: unknown): string {\n return message.replace('{value}', String(value))\n }\n}\n\n// ============================================================\n// ZOD SCHEMA VALIDATOR\n// ============================================================\n\n/**\n * Validate values using a Zod schema\n */\nexport function validateWithZod<T>(\n values: Record<string, unknown>,\n schema: ZodType<T>\n): FormValidationResult {\n const result = schema.safeParse(values)\n\n if (result.success) {\n return {\n valid: true,\n errors: {},\n }\n }\n\n return {\n valid: false,\n errors: formatZodErrors(result.error),\n }\n}\n\n/**\n * Convert Zod errors to FormValidationResult format\n */\nfunction formatZodErrors(error: ZodError): Record<string, string[]> {\n const errors: Record<string, string[]> = {}\n\n for (const issue of error.issues) {\n const path = issue.path.map(String).join('.')\n if (!errors[path]) {\n errors[path] = []\n }\n errors[path].push(issue.message)\n }\n\n return errors\n}\n\n// ============================================================\n// BUILT-IN ZOD SCHEMAS\n// ============================================================\n\n/**\n * Common Zod schemas for form validation\n */\nexport const FormSchemas = {\n /**\n * Email validation schema\n */\n email: z.string().email('Please enter a valid email address'),\n\n /**\n * Required string schema\n */\n requiredString: z.string().min(1, 'This field is required'),\n\n /**\n * URL validation schema\n */\n url: z.string().url('Please enter a valid URL'),\n\n /**\n * Phone number schema (basic)\n */\n phone: z.string().regex(/^\\+?[\\d\\s-()]+$/, 'Please enter a valid phone number'),\n\n /**\n * Password schema (min 8 chars, at least one number and letter)\n */\n password: z\n .string()\n .min(8, 'Password must be at least 8 characters')\n .regex(/[a-zA-Z]/, 'Password must contain at least one letter')\n .regex(/[0-9]/, 'Password must contain at least one number'),\n}\n\n/**\n * Create a form validator\n */\nexport function createFormValidator(customMessages?: Partial<ValidationMessages>): FormValidator {\n return new DefaultFormValidator(customMessages)\n}\n"]}
@@ -37,7 +37,7 @@ export function createWebOutput(options) {
37
37
  if (!dataResult.success) {
38
38
  return {
39
39
  success: false,
40
- errors: dataResult.error.issues.map((i) => `data.${i.path.join('.')}: ${i.message}`),
40
+ errors: dataResult.error.issues.map((i) => `data.${i.path.map(String).join('.')}: ${i.message}`),
41
41
  };
42
42
  }
43
43
  const data = {
@@ -63,7 +63,7 @@ export function createApiOutput(options) {
63
63
  if (!dataResult.success) {
64
64
  return {
65
65
  success: false,
66
- errors: dataResult.error.issues.map((i) => `data.${i.path.join('.')}: ${i.message}`),
66
+ errors: dataResult.error.issues.map((i) => `data.${i.path.map(String).join('.')}: ${i.message}`),
67
67
  };
68
68
  }
69
69
  const data = {
@@ -89,7 +89,7 @@ export function createCliOutput(options) {
89
89
  if (!dataResult.success) {
90
90
  return {
91
91
  success: false,
92
- errors: dataResult.error.issues.map((i) => `data.${i.path.join('.')}: ${i.message}`),
92
+ errors: dataResult.error.issues.map((i) => `data.${i.path.map(String).join('.')}: ${i.message}`),
93
93
  };
94
94
  }
95
95
  const output = {
@@ -1 +1 @@
1
- {"version":3,"file":"output.js","sourceRoot":"","sources":["../../src/surface/output.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAA;AAsCvB,+DAA+D;AAC/D,cAAc;AACd,+DAA+D;AAE/D,MAAM,mBAAmB,GAAG,CAAC,CAAC,MAAM,CAAC;IACnC,IAAI,EAAE,CAAC,CAAC,MAAM,EAAE;IAChB,GAAG,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;IAC1B,IAAI,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;CAC5B,CAAC,CAAA;AAEF,MAAM,mBAAmB,GAAG,CAAC,CAAC,MAAM,CAAC;IACnC,IAAI,EAAE,CAAC,CAAC,OAAO,EAAE;IACjB,MAAM,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC;CAC3C,CAAC,CAAA;AAEF,MAAM,mBAAmB,GAAG,CAAC,CAAC,MAAM,CAAC;IACnC,SAAS,EAAE,CAAC,CAAC,MAAM,EAAE;IACrB,G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,CAAC;QACxB,OAAO;YACL,OAAO,EAAE,KAAK;YACd,MAAM,EAAE,UAAU,CAAC,KAAK,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,QAAQ,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,OAAO,EAAE,CAAC;SACrF,CAAA;IACH,CAAC;IAED,MAAM,MAAM,GAAmB;QAC7B,IAAI,EAAE,KAAK;QACX,IAAI,EAAE,UAAU,CAAC,IAAI;QACrB,QAAQ,EAAE,OAAO,CAAC,QAAQ;QAC1B,GAAG,CAAC,OAAO,CAAC,MAAM,KAAK,SAAS,IAAI,EAAE,MAAM,EAAE,OAAO,CAAC,MAAM,EAAE,CAAC;QAC/D,GAAG,CAAC,OAAO,CAAC,MAAM,KAAK,SAAS,IAAI,EAAE,MAAM,EAAE,OAAO,CAAC,MAAM,EAAE,CAAC;KAChE,CAAA;IAED,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,CAAA;AAClC,CAAC","sourcesContent":["/**\n * Typed Output Factories\n *\n * Typed wrappers for BaseSurfaceOutput.data.\n * These do NOT modify @pwfabric/contracts. They extend the contract types\n * with narrowed data fields and provide factory functions that validate.\n *\n * @module @pwfabric/runtime/surface/output\n */\n\nimport { z } from 'zod'\nimport type { WebSurfaceOutput, ApiSurfaceOutput, CliSurfaceOutput } from '@pwfabric/contracts'\n\n// ============================================================\n// TYPED OUTPUT INTERFACES\n// ============================================================\n\n/**\n * Web output with narrowed data type\n */\nexport interface TypedWebOutput extends WebSurfaceOutput {\n readonly data: {\n readonly html: string\n readonly css?: string\n readonly head?: string\n }\n}\n\n/**\n * API output with narrowed data type\n */\nexport interface TypedApiOutput extends ApiSurfaceOutput {\n readonly data: {\n readonly json: unknown\n readonly status: number\n }\n}\n\n/**\n * CLI output with narrowed data type\n */\nexport interface TypedCliOutput extends CliSurfaceOutput {\n readonly data: {\n readonly formatted: string\n readonly raw?: unknown\n }\n}\n\n// ============================================================\n// ZOD SCHEMAS\n// ============================================================\n\nconst webOutputDataSchema = z.object({\n html: z.string(),\n css: z.string().optional(),\n head: z.string().optional(),\n})\n\nconst apiOutputDataSchema = z.object({\n json: z.unknown(),\n status: z.number().int().min(100).max(599),\n})\n\nconst cliOutputDataSchema = z.object({\n formatted: z.string(),\n raw: z.unknown().optional(),\n})\n\n// ============================================================\n// VALIDATION RESULT\n// ============================================================\n\n/**\n * Result of creating a typed output\n */\nexport type OutputFactoryResult<T> =\n | { readonly success: true; readonly output: T }\n | { readonly success: false; readonly errors: readonly string[] }\n\n// ============================================================\n// FACTORY FUNCTIONS\n// ============================================================\n\n/**\n * Create a validated TypedWebOutput.\n *\n * Validates the data shape and returns a typed output or errors.\n */\nexport function createWebOutput(options: {\n readonly data: { readonly html: string; readonly css?: string; readonly head?: string }\n readonly component?: unknown\n readonly html?: string\n}): OutputFactoryResult<TypedWebOutput> {\n const dataResult = webOutputDataSchema.safeParse(options.data)\n\n if (!dataResult.success) {\n return {\n success: false,\n errors: dataResult.error.issues.map((i) => `data.${i.path.join('.')}: ${i.message}`),\n }\n }\n\n const data: TypedWebOutput['data'] = {\n html: dataResult.data.html,\n ...(dataResult.data.css !== undefined ? { css: dataResult.data.css } : {}),\n ...(dataResult.data.head !== undefined ? { head: dataResult.data.head } : {}),\n }\n\n const output: TypedWebOutput = {\n type: 'web',\n data,\n ...(options.component !== undefined ? { component: options.component } : {}),\n ...(options.html !== undefined ? { html: options.html } : {}),\n }\n\n return { success: true, output }\n}\n\n/**\n * Create a validated TypedApiOutput.\n *\n * Validates the data shape and returns a typed output or errors.\n */\nexport function createApiOutput(options: {\n readonly data: { readonly json: unknown; readonly status: number }\n readonly status: number\n readonly headers?: Record<string, string>\n readonly body?: unknown\n}): OutputFactoryResult<TypedApiOutput> {\n const dataResult = apiOutputDataSchema.safeParse(options.data)\n\n if (!dataResult.success) {\n return {\n success: false,\n errors: dataResult.error.issues.map((i) => `data.${i.path.join('.')}: ${i.message}`),\n }\n }\n\n const data: TypedApiOutput['data'] = {\n json: dataResult.data.json,\n status: dataResult.data.status,\n }\n\n const output: TypedApiOutput = {\n type: 'api',\n data,\n status: options.status,\n body: options.body ?? null,\n ...(options.headers ? { headers: options.headers } : {}),\n }\n\n return { success: true, output }\n}\n\n/**\n * Create a validated TypedCliOutput.\n *\n * Validates the data shape and returns a typed output or errors.\n */\nexport function createCliOutput(options: {\n readonly data: { readonly formatted: string; readonly raw?: unknown }\n readonly exitCode: number\n readonly stdout?: string\n readonly stderr?: string\n}): OutputFactoryResult<TypedCliOutput> {\n const dataResult = cliOutputDataSchema.safeParse(options.data)\n\n if (!dataResult.success) {\n return {\n success: false,\n errors: dataResult.error.issues.map((i) => `data.${i.path.join('.')}: ${i.message}`),\n }\n }\n\n const output: TypedCliOutput = {\n type: 'cli',\n data: dataResult.data,\n exitCode: options.exitCode,\n ...(options.stdout !== undefined && { stdout: options.stdout }),\n ...(options.stderr !== undefined && { stderr: options.stderr }),\n }\n\n return { success: true, output }\n}\n"]}
1
+ {"version":3,"file":"output.js","sourceRoot":"","sources":["../../src/surface/output.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAA;AAsCvB,+DAA+D;AAC/D,cAAc;AACd,+DAA+D;AAE/D,MAAM,mBAAmB,GAAG,CAAC,CAAC,MAAM,CAAC;IACnC,IAAI,EAAE,CAAC,CAAC,MAAM,EAAE;IAChB,GAAG,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;IAC1B,IAAI,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;CAC5B,CAAC,CAAA;AAEF,MAAM,mBAAmB,GAAG,CAAC,CAAC,MAAM,CAAC;IACnC,IAAI,EAAE,CAAC,CAAC,OAAO,EAAE;IACjB,MAAM,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,CAAC,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,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,CAAA;AAClC,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,eAAe,CAAC,OAK/B;IACC,MAAM,UAAU,GAAG,mBAAmB,CAAC,SAAS,CAAC,OAAO,CAAC,IAAI,CAAC,CAAA;IAE9D,IAAI,CAAC,UAAU,CAAC,OAAO,EAAE,CAAC;QACxB,OAAO;YACL,OAAO,EAAE,KAAK;YACd,MAAM,EAAE,UAAU,CAAC,KAAK,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,QAAQ,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,OAAO,EAAE,CAAC;SACjG,CAAA;IACH,CAAC;IAED,MAAM,MAAM,GAAmB;QAC7B,IAAI,EAAE,KAAK;QACX,IAAI,EAAE,UAAU,CAAC,IAAI;QACrB,QAAQ,EAAE,OAAO,CAAC,QAAQ;QAC1B,GAAG,CAAC,OAAO,CAAC,MAAM,KAAK,SAAS,IAAI,EAAE,MAAM,EAAE,OAAO,CAAC,MAAM,EAAE,CAAC;QAC/D,GAAG,CAAC,OAAO,CAAC,MAAM,KAAK,SAAS,IAAI,EAAE,MAAM,EAAE,OAAO,CAAC,MAAM,EAAE,CAAC;KAChE,CAAA;IAED,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,CAAA;AAClC,CAAC","sourcesContent":["/**\n * Typed Output Factories\n *\n * Typed wrappers for BaseSurfaceOutput.data.\n * These do NOT modify @pwfabric/contracts. They extend the contract types\n * with narrowed data fields and provide factory functions that validate.\n *\n * @module @pwfabric/runtime/surface/output\n */\n\nimport { z } from 'zod'\nimport type { WebSurfaceOutput, ApiSurfaceOutput, CliSurfaceOutput } from '@pwfabric/contracts'\n\n// ============================================================\n// TYPED OUTPUT INTERFACES\n// ============================================================\n\n/**\n * Web output with narrowed data type\n */\nexport interface TypedWebOutput extends WebSurfaceOutput {\n readonly data: {\n readonly html: string\n readonly css?: string\n readonly head?: string\n }\n}\n\n/**\n * API output with narrowed data type\n */\nexport interface TypedApiOutput extends ApiSurfaceOutput {\n readonly data: {\n readonly json: unknown\n readonly status: number\n }\n}\n\n/**\n * CLI output with narrowed data type\n */\nexport interface TypedCliOutput extends CliSurfaceOutput {\n readonly data: {\n readonly formatted: string\n readonly raw?: unknown\n }\n}\n\n// ============================================================\n// ZOD SCHEMAS\n// ============================================================\n\nconst webOutputDataSchema = z.object({\n html: z.string(),\n css: z.string().optional(),\n head: z.string().optional(),\n})\n\nconst apiOutputDataSchema = z.object({\n json: z.unknown(),\n status: z.number().int().min(100).max(599),\n})\n\nconst cliOutputDataSchema = z.object({\n formatted: z.string(),\n raw: z.unknown().optional(),\n})\n\n// ============================================================\n// VALIDATION RESULT\n// ============================================================\n\n/**\n * Result of creating a typed output\n */\nexport type OutputFactoryResult<T> =\n | { readonly success: true; readonly output: T }\n | { readonly success: false; readonly errors: readonly string[] }\n\n// ============================================================\n// FACTORY FUNCTIONS\n// ============================================================\n\n/**\n * Create a validated TypedWebOutput.\n *\n * Validates the data shape and returns a typed output or errors.\n */\nexport function createWebOutput(options: {\n readonly data: { readonly html: string; readonly css?: string; readonly head?: string }\n readonly component?: unknown\n readonly html?: string\n}): OutputFactoryResult<TypedWebOutput> {\n const dataResult = webOutputDataSchema.safeParse(options.data)\n\n if (!dataResult.success) {\n return {\n success: false,\n errors: dataResult.error.issues.map((i) => `data.${i.path.map(String).join('.')}: ${i.message}`),\n }\n }\n\n const data: TypedWebOutput['data'] = {\n html: dataResult.data.html,\n ...(dataResult.data.css !== undefined ? { css: dataResult.data.css } : {}),\n ...(dataResult.data.head !== undefined ? { head: dataResult.data.head } : {}),\n }\n\n const output: TypedWebOutput = {\n type: 'web',\n data,\n ...(options.component !== undefined ? { component: options.component } : {}),\n ...(options.html !== undefined ? { html: options.html } : {}),\n }\n\n return { success: true, output }\n}\n\n/**\n * Create a validated TypedApiOutput.\n *\n * Validates the data shape and returns a typed output or errors.\n */\nexport function createApiOutput(options: {\n readonly data: { readonly json: unknown; readonly status: number }\n readonly status: number\n readonly headers?: Record<string, string>\n readonly body?: unknown\n}): OutputFactoryResult<TypedApiOutput> {\n const dataResult = apiOutputDataSchema.safeParse(options.data)\n\n if (!dataResult.success) {\n return {\n success: false,\n errors: dataResult.error.issues.map((i) => `data.${i.path.map(String).join('.')}: ${i.message}`),\n }\n }\n\n const data: TypedApiOutput['data'] = {\n json: dataResult.data.json,\n status: dataResult.data.status,\n }\n\n const output: TypedApiOutput = {\n type: 'api',\n data,\n status: options.status,\n body: options.body ?? null,\n ...(options.headers ? { headers: options.headers } : {}),\n }\n\n return { success: true, output }\n}\n\n/**\n * Create a validated TypedCliOutput.\n *\n * Validates the data shape and returns a typed output or errors.\n */\nexport function createCliOutput(options: {\n readonly data: { readonly formatted: string; readonly raw?: unknown }\n readonly exitCode: number\n readonly stdout?: string\n readonly stderr?: string\n}): OutputFactoryResult<TypedCliOutput> {\n const dataResult = cliOutputDataSchema.safeParse(options.data)\n\n if (!dataResult.success) {\n return {\n success: false,\n errors: dataResult.error.issues.map((i) => `data.${i.path.map(String).join('.')}: ${i.message}`),\n }\n }\n\n const output: TypedCliOutput = {\n type: 'cli',\n data: dataResult.data,\n exitCode: options.exitCode,\n ...(options.stdout !== undefined && { stdout: options.stdout }),\n ...(options.stderr !== undefined && { stderr: options.stderr }),\n }\n\n return { success: true, output }\n}\n"]}
@@ -14,7 +14,16 @@ import type { SurfaceJSON, LayoutJSON, BindingJSON } from './types.js';
14
14
  /**
15
15
  * Valid environment types for surfaces
16
16
  */
17
- export declare const environmentSchema: z.ZodEnum<["web", "api", "cli", "worker", "edge", "node", "native", "test"]>;
17
+ export declare const environmentSchema: z.ZodEnum<{
18
+ web: "web";
19
+ api: "api";
20
+ cli: "cli";
21
+ worker: "worker";
22
+ edge: "edge";
23
+ node: "node";
24
+ native: "native";
25
+ test: "test";
26
+ }>;
18
27
  /**
19
28
  * Zod schema for BindingJSON
20
29
  *
@@ -29,28 +38,8 @@ export declare const bindingJsonSchema: z.ZodObject<{
29
38
  transform: z.ZodOptional<z.ZodObject<{
30
39
  input: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
31
40
  output: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
32
- }, "strip", z.ZodTypeAny, {
33
- input?: Record<string, unknown> | undefined;
34
- output?: Record<string, unknown> | undefined;
35
- }, {
36
- input?: Record<string, unknown> | undefined;
37
- output?: Record<string, unknown> | undefined;
38
- }>>;
39
- }, "strip", z.ZodTypeAny, {
40
- capability: string;
41
- alias?: string | undefined;
42
- transform?: {
43
- input?: Record<string, unknown> | undefined;
44
- output?: Record<string, unknown> | undefined;
45
- } | undefined;
46
- }, {
47
- capability: string;
48
- alias?: string | undefined;
49
- transform?: {
50
- input?: Record<string, unknown> | undefined;
51
- output?: Record<string, unknown> | undefined;
52
- } | undefined;
53
- }>;
41
+ }, z.core.$strip>>;
42
+ }, z.core.$strip>;
54
43
  /**
55
44
  * Zod schema for LayoutJSON
56
45
  *
@@ -79,88 +68,31 @@ export declare const surfaceJsonSchema: z.ZodObject<{
79
68
  $schema: z.ZodOptional<z.ZodString>;
80
69
  id: z.ZodString;
81
70
  version: z.ZodString;
82
- environment: z.ZodEnum<["web", "api", "cli", "worker", "edge", "node", "native", "test"]>;
71
+ environment: z.ZodEnum<{
72
+ web: "web";
73
+ api: "api";
74
+ cli: "cli";
75
+ worker: "worker";
76
+ edge: "edge";
77
+ node: "node";
78
+ native: "native";
79
+ test: "test";
80
+ }>;
83
81
  metadata: z.ZodOptional<z.ZodObject<{
84
82
  name: z.ZodOptional<z.ZodString>;
85
83
  description: z.ZodOptional<z.ZodString>;
86
- tags: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
87
- }, "strip", z.ZodTypeAny, {
88
- description?: string | undefined;
89
- name?: string | undefined;
90
- tags?: string[] | undefined;
91
- }, {
92
- description?: string | undefined;
93
- name?: string | undefined;
94
- tags?: string[] | undefined;
95
- }>>;
84
+ tags: z.ZodOptional<z.ZodArray<z.ZodString>>;
85
+ }, z.core.$strip>>;
96
86
  bindings: z.ZodOptional<z.ZodArray<z.ZodObject<{
97
87
  capability: z.ZodString;
98
88
  alias: z.ZodOptional<z.ZodString>;
99
89
  transform: z.ZodOptional<z.ZodObject<{
100
90
  input: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
101
91
  output: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
102
- }, "strip", z.ZodTypeAny, {
103
- input?: Record<string, unknown> | undefined;
104
- output?: Record<string, unknown> | undefined;
105
- }, {
106
- input?: Record<string, unknown> | undefined;
107
- output?: Record<string, unknown> | undefined;
108
- }>>;
109
- }, "strip", z.ZodTypeAny, {
110
- capability: string;
111
- alias?: string | undefined;
112
- transform?: {
113
- input?: Record<string, unknown> | undefined;
114
- output?: Record<string, unknown> | undefined;
115
- } | undefined;
116
- }, {
117
- capability: string;
118
- alias?: string | undefined;
119
- transform?: {
120
- input?: Record<string, unknown> | undefined;
121
- output?: Record<string, unknown> | undefined;
122
- } | undefined;
123
- }>, "many">>;
124
- layout: z.ZodType<any, z.ZodTypeDef, any>;
125
- }, "strip", z.ZodTypeAny, {
126
- id: string;
127
- version: string;
128
- environment: "web" | "api" | "cli" | "worker" | "edge" | "node" | "native" | "test";
129
- metadata?: {
130
- description?: string | undefined;
131
- name?: string | undefined;
132
- tags?: string[] | undefined;
133
- } | undefined;
134
- $schema?: string | undefined;
135
- bindings?: {
136
- capability: string;
137
- alias?: string | undefined;
138
- transform?: {
139
- input?: Record<string, unknown> | undefined;
140
- output?: Record<string, unknown> | undefined;
141
- } | undefined;
142
- }[] | undefined;
143
- layout?: any;
144
- }, {
145
- id: string;
146
- version: string;
147
- environment: "web" | "api" | "cli" | "worker" | "edge" | "node" | "native" | "test";
148
- metadata?: {
149
- description?: string | undefined;
150
- name?: string | undefined;
151
- tags?: string[] | undefined;
152
- } | undefined;
153
- $schema?: string | undefined;
154
- bindings?: {
155
- capability: string;
156
- alias?: string | undefined;
157
- transform?: {
158
- input?: Record<string, unknown> | undefined;
159
- output?: Record<string, unknown> | undefined;
160
- } | undefined;
161
- }[] | undefined;
162
- layout?: any;
163
- }>;
92
+ }, z.core.$strip>>;
93
+ }, z.core.$strip>>>;
94
+ layout: z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>;
95
+ }, z.core.$strip>;
164
96
  /**
165
97
  * Type guard for SurfaceJSON
166
98
  *
@@ -42,8 +42,8 @@ export const bindingJsonSchema = z.object({
42
42
  alias: z.string().optional(),
43
43
  transform: z
44
44
  .object({
45
- input: z.record(z.unknown()).optional(),
46
- output: z.record(z.unknown()).optional(),
45
+ input: z.record(z.string(), z.unknown()).optional(),
46
+ output: z.record(z.string(), z.unknown()).optional(),
47
47
  })
48
48
  .optional(),
49
49
  });
@@ -66,7 +66,7 @@ export const bindingJsonSchema = z.object({
66
66
  // schema variable to exist at the point of self-reference in children.
67
67
  export const layoutJsonSchema = z.lazy(() => z.object({
68
68
  type: z.string().min(1, 'Layout must have a type'),
69
- props: z.record(z.unknown()).optional(),
69
+ props: z.record(z.string(), z.unknown()).optional(),
70
70
  children: z.array(layoutJsonSchema).optional(),
71
71
  slot: z.string().optional(),
72
72
  if: z.string().optional(),
@@ -1 +1 @@
1
- {"version":3,"file":"schemas.js","sourceRoot":"","sources":["../../src/surface/schemas.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAA;AAGvB,+DAA+D;AAC/D,qBAAqB;AACrB,+DAA+D;AAE/D;;GAEG;AACH,MAAM,CAAC,MAAM,iBAAiB,GAAG,CAAC,CAAC,IAAI,CAAC;IACtC,KAAK;IACL,KAAK;IACL,KAAK;IACL,QAAQ;IACR,MAAM;IACN,MAAM;IACN,QAAQ;IAC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C,SAAS,CAAC,IAAI,CAAC,CAAC,OAAO,CAAA;AAClD,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,YAAY,CAAC,IAAa;IACxC,OAAO,gBAAgB,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,OAAO,CAAA;AACjD,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,aAAa,CAAC,IAAa;IACzC,OAAO,iBAAiB,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,OAAO,CAAA;AAClD,CAAC","sourcesContent":["/**\n * Surface JSON Zod Schemas\n *\n * Zod validation schemas for Surface JSON definitions\n *\n * Provides schema-based validation to replace manual string-based\n * validation in the interpreter. Ensures SurfaceJSON, LayoutJSON,\n * and BindingJSON conform to their TypeScript interfaces.\n *\n * @module @pwfabric/runtime/surface/schemas\n */\n\nimport { z } from 'zod'\nimport type { SurfaceJSON, LayoutJSON, BindingJSON } from './types.js'\n\n// ============================================================\n// ENVIRONMENT SCHEMA\n// ============================================================\n\n/**\n * Valid environment types for surfaces\n */\nexport const environmentSchema = z.enum([\n 'web',\n 'api',\n 'cli',\n 'worker',\n 'edge',\n 'node',\n 'native',\n 'test',\n])\n\n// ============================================================\n// BINDING JSON SCHEMA\n// ============================================================\n\n/**\n * Zod schema for BindingJSON\n *\n * Validates capability bindings in surface definitions.\n * - capability: required string identifying the capability\n * - alias: optional string alias for the binding\n * - transform: optional input/output transform configuration\n */\nexport const bindingJsonSchema = z.object({\n capability: z.string().min(1, 'Binding capability must be a non-empty string'),\n alias: z.string().optional(),\n transform: z\n .object({\n input: z.record(z.unknown()).optional(),\n output: z.record(z.unknown()).optional(),\n })\n .optional(),\n})\n\n// ============================================================\n// LAYOUT JSON SCHEMA (RECURSIVE)\n// ============================================================\n\n/**\n * Zod schema for LayoutJSON\n *\n * Uses z.lazy() for recursive children validation.\n * - type: required string identifying the layout element type\n * - props: optional record of properties\n * - children: optional array of nested LayoutJSON (recursive)\n * - slot: optional named slot reference\n * - if: optional conditional expression\n * - each: optional loop configuration (items, as, key)\n */\n// Recursive schema uses z.lazy() with a forward-declared type variable.\n// The explicit ZodType cast is required because z.lazy() needs the\n// schema variable to exist at the point of self-reference in children.\nexport const layoutJsonSchema: z.ZodType = z.lazy(() =>\n z.object({\n type: z.string().min(1, 'Layout must have a type'),\n props: z.record(z.unknown()).optional(),\n children: z.array(layoutJsonSchema).optional(),\n slot: z.string().optional(),\n if: z.string().optional(),\n each: z\n .object({\n items: z.string().min(1, 'Loop layout must have items expression'),\n as: z.string().min(1, 'Loop layout must have as variable name'),\n key: z.string().optional(),\n })\n .optional(),\n })\n)\n\n// ============================================================\n// SURFACE JSON SCHEMA\n// ============================================================\n\n/**\n * Metadata schema for surface definitions\n */\nconst metadataSchema = z\n .object({\n name: z.string().optional(),\n description: z.string().optional(),\n tags: z.array(z.string()).optional(),\n })\n .optional()\n\n/**\n * Zod schema for SurfaceJSON\n *\n * Validates the top-level surface definition structure.\n * - id: required non-empty string\n * - version: required non-empty string (semver)\n * - environment: required enum of valid environment types\n * - $schema: optional schema reference\n * - metadata: optional name, description, tags\n * - bindings: optional array of capability bindings\n * - layout: required recursive layout definition\n */\nexport const surfaceJsonSchema = z.object({\n $schema: z.string().optional(),\n id: z.string().min(1, 'Surface must have a string id'),\n version: z.string().min(1, 'Surface must have a string version'),\n environment: environmentSchema,\n metadata: metadataSchema,\n bindings: z.array(bindingJsonSchema).optional(),\n layout: layoutJsonSchema,\n})\n\n// ============================================================\n// TYPE GUARDS\n// ============================================================\n\n/**\n * Type guard for SurfaceJSON\n *\n * Returns true if the provided data conforms to the SurfaceJSON schema.\n */\nexport function isSurfaceJSON(data: unknown): data is SurfaceJSON {\n return surfaceJsonSchema.safeParse(data).success\n}\n\n/**\n * Type guard for LayoutJSON\n *\n * Returns true if the provided data conforms to the LayoutJSON schema.\n */\nexport function isLayoutJSON(data: unknown): data is LayoutJSON {\n return layoutJsonSchema.safeParse(data).success\n}\n\n/**\n * Type guard for BindingJSON\n *\n * Returns true if the provided data conforms to the BindingJSON schema.\n */\nexport function isBindingJSON(data: unknown): data is BindingJSON {\n return bindingJsonSchema.safeParse(data).success\n}\n"]}
1
+ {"version":3,"file":"schemas.js","sourceRoot":"","sources":["../../src/surface/schemas.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAA;AAGvB,+DAA+D;AAC/D,qBAAqB;AACrB,+DAA+D;AAE/D;;GAEG;AACH,MAAM,CAAC,MAAM,iBAAiB,GAAG,CAAC,CAAC,IAAI,CAAC;IACtC,KAAK;IACL,KAAK;IACL,KAAK;IACL,QAAQ;IACR,MAAM;IACN,MAAM;IACN,QAAQ;IACR,MAAM;CACP,CAAC,CAAA;AAEF,+DAA+D;AAC/D,sBAAsB;AACtB,+DAA+D;AAE/D;;;;;;;GAOG;AACH,MAAM,CAAC,MAAM,iBAAiB,GAAG,CAAC,CAAC,MAAM,CAAC;IACxC,UAAU,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,EAAE,+CAA+C,CAAC;IAC9E,KAAK,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;IAC5B,SAAS,EAAE,CAAC;SACT,MAAM,CAAC;QACN,KAAK,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC,QAAQ,EAAE;QACnD,MAAM,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC,QAAQ,EAAE;KACrD,CAAC;SACD,QAAQ,EAAE;CACd,CAAC,CAAA;AAEF,+DAA+D;AAC/D,iCAAiC;AACjC,+DAA+D;AAE/D;;;;;;;;;;GAUG;AACH,wEAAwE;AACxE,mEAAmE;AACnE,uEAAuE;AACvE,MAAM,CAAC,MAAM,gBAAgB,GAAc,CAAC,CAAC,I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IACxC,OAAO,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;IAC9B,EAAE,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,EAAE,+BAA+B,CAAC;IACtD,OAAO,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,EAAE,oCAAoC,CAAC;IAChE,WAAW,EAAE,iBAAiB;IAC9B,QAAQ,EAAE,cAAc;IACxB,QAAQ,EAAE,CAAC,CAAC,KAAK,CAAC,iBAAiB,CAAC,CAAC,QAAQ,EAAE;IAC/C,MAAM,EAAE,gBAAgB;CACzB,CAAC,CAAA;AAEF,+DAA+D;AAC/D,cAAc;AACd,+DAA+D;AAE/D;;;;GAIG;AACH,MAAM,UAAU,aAAa,CAAC,IAAa;IACzC,OAAO,iBAAiB,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,OAAO,CAAA;AAClD,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,YAAY,CAAC,IAAa;IACxC,OAAO,gBAAgB,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,OAAO,CAAA;AACjD,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,aAAa,CAAC,IAAa;IACzC,OAAO,iBAAiB,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,OAAO,CAAA;AAClD,CAAC","sourcesContent":["/**\n * Surface JSON Zod Schemas\n *\n * Zod validation schemas for Surface JSON definitions\n *\n * Provides schema-based validation to replace manual string-based\n * validation in the interpreter. Ensures SurfaceJSON, LayoutJSON,\n * and BindingJSON conform to their TypeScript interfaces.\n *\n * @module @pwfabric/runtime/surface/schemas\n */\n\nimport { z } from 'zod'\nimport type { SurfaceJSON, LayoutJSON, BindingJSON } from './types.js'\n\n// ============================================================\n// ENVIRONMENT SCHEMA\n// ============================================================\n\n/**\n * Valid environment types for surfaces\n */\nexport const environmentSchema = z.enum([\n 'web',\n 'api',\n 'cli',\n 'worker',\n 'edge',\n 'node',\n 'native',\n 'test',\n])\n\n// ============================================================\n// BINDING JSON SCHEMA\n// ============================================================\n\n/**\n * Zod schema for BindingJSON\n *\n * Validates capability bindings in surface definitions.\n * - capability: required string identifying the capability\n * - alias: optional string alias for the binding\n * - transform: optional input/output transform configuration\n */\nexport const bindingJsonSchema = z.object({\n capability: z.string().min(1, 'Binding capability must be a non-empty string'),\n alias: z.string().optional(),\n transform: z\n .object({\n input: z.record(z.string(), z.unknown()).optional(),\n output: z.record(z.string(), z.unknown()).optional(),\n })\n .optional(),\n})\n\n// ============================================================\n// LAYOUT JSON SCHEMA (RECURSIVE)\n// ============================================================\n\n/**\n * Zod schema for LayoutJSON\n *\n * Uses z.lazy() for recursive children validation.\n * - type: required string identifying the layout element type\n * - props: optional record of properties\n * - children: optional array of nested LayoutJSON (recursive)\n * - slot: optional named slot reference\n * - if: optional conditional expression\n * - each: optional loop configuration (items, as, key)\n */\n// Recursive schema uses z.lazy() with a forward-declared type variable.\n// The explicit ZodType cast is required because z.lazy() needs the\n// schema variable to exist at the point of self-reference in children.\nexport const layoutJsonSchema: z.ZodType = z.lazy(() =>\n z.object({\n type: z.string().min(1, 'Layout must have a type'),\n props: z.record(z.string(), z.unknown()).optional(),\n children: z.array(layoutJsonSchema).optional(),\n slot: z.string().optional(),\n if: z.string().optional(),\n each: z\n .object({\n items: z.string().min(1, 'Loop layout must have items expression'),\n as: z.string().min(1, 'Loop layout must have as variable name'),\n key: z.string().optional(),\n })\n .optional(),\n })\n)\n\n// ============================================================\n// SURFACE JSON SCHEMA\n// ============================================================\n\n/**\n * Metadata schema for surface definitions\n */\nconst metadataSchema = z\n .object({\n name: z.string().optional(),\n description: z.string().optional(),\n tags: z.array(z.string()).optional(),\n })\n .optional()\n\n/**\n * Zod schema for SurfaceJSON\n *\n * Validates the top-level surface definition structure.\n * - id: required non-empty string\n * - version: required non-empty string (semver)\n * - environment: required enum of valid environment types\n * - $schema: optional schema reference\n * - metadata: optional name, description, tags\n * - bindings: optional array of capability bindings\n * - layout: required recursive layout definition\n */\nexport const surfaceJsonSchema = z.object({\n $schema: z.string().optional(),\n id: z.string().min(1, 'Surface must have a string id'),\n version: z.string().min(1, 'Surface must have a string version'),\n environment: environmentSchema,\n metadata: metadataSchema,\n bindings: z.array(bindingJsonSchema).optional(),\n layout: layoutJsonSchema,\n})\n\n// ============================================================\n// TYPE GUARDS\n// ============================================================\n\n/**\n * Type guard for SurfaceJSON\n *\n * Returns true if the provided data conforms to the SurfaceJSON schema.\n */\nexport function isSurfaceJSON(data: unknown): data is SurfaceJSON {\n return surfaceJsonSchema.safeParse(data).success\n}\n\n/**\n * Type guard for LayoutJSON\n *\n * Returns true if the provided data conforms to the LayoutJSON schema.\n */\nexport function isLayoutJSON(data: unknown): data is LayoutJSON {\n return layoutJsonSchema.safeParse(data).success\n}\n\n/**\n * Type guard for BindingJSON\n *\n * Returns true if the provided data conforms to the BindingJSON schema.\n */\nexport function isBindingJSON(data: unknown): data is BindingJSON {\n return bindingJsonSchema.safeParse(data).success\n}\n"]}
@@ -64,47 +64,21 @@ export type TypedTransformConfig = {
64
64
  export declare const mapTransformConfigSchema: z.ZodObject<{
65
65
  field: z.ZodString;
66
66
  mapper: z.ZodString;
67
- }, "strip", z.ZodTypeAny, {
68
- field: string;
69
- mapper: string;
70
- }, {
71
- field: string;
72
- mapper: string;
73
- }>;
67
+ }, z.core.$strip>;
74
68
  export declare const filterTransformConfigSchema: z.ZodObject<{
75
69
  field: z.ZodString;
76
70
  predicate: z.ZodString;
77
- }, "strip", z.ZodTypeAny, {
78
- field: string;
79
- predicate: string;
80
- }, {
81
- field: string;
82
- predicate: string;
83
- }>;
71
+ }, z.core.$strip>;
84
72
  export declare const pickTransformConfigSchema: z.ZodObject<{
85
- fields: z.ZodArray<z.ZodString, "many">;
86
- }, "strip", z.ZodTypeAny, {
87
- fields: string[];
88
- }, {
89
- fields: string[];
90
- }>;
73
+ fields: z.ZodArray<z.ZodString>;
74
+ }, z.core.$strip>;
91
75
  export declare const omitTransformConfigSchema: z.ZodObject<{
92
- fields: z.ZodArray<z.ZodString, "many">;
93
- }, "strip", z.ZodTypeAny, {
94
- fields: string[];
95
- }, {
96
- fields: string[];
97
- }>;
76
+ fields: z.ZodArray<z.ZodString>;
77
+ }, z.core.$strip>;
98
78
  export declare const customTransformConfigSchema: z.ZodObject<{
99
79
  handler: z.ZodString;
100
80
  params: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
101
- }, "strip", z.ZodTypeAny, {
102
- handler: string;
103
- params?: Record<string, unknown> | undefined;
104
- }, {
105
- handler: string;
106
- params?: Record<string, unknown> | undefined;
107
- }>;
81
+ }, z.core.$strip>;
108
82
  /**
109
83
  * Result of validating a transform config
110
84
  */
@@ -27,7 +27,7 @@ export const omitTransformConfigSchema = z.object({
27
27
  });
28
28
  export const customTransformConfigSchema = z.object({
29
29
  handler: z.string().min(1),
30
- params: z.record(z.unknown()).optional(),
30
+ params: z.record(z.string(), z.unknown()).optional(),
31
31
  });
32
32
  /**
33
33
  * Map of transform types to their Zod schemas
@@ -54,7 +54,7 @@ export function validateTransformConfig(type, config) {
54
54
  }
55
55
  return {
56
56
  valid: false,
57
- errors: result.error.issues.map((i) => `${i.path.join('.')}: ${i.message}`),
57
+ errors: result.error.issues.map((i) => `${i.path.map(String).join('.')}: ${i.message}`),
58
58
  };
59
59
  }
60
60
  // ============================================================
@@ -1 +1 @@
1
- {"version":3,"file":"transforms.js","sourceRoot":"","sources":["../../src/surface/transforms.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAA;AAuDvB,+DAA+D;AAC/D,cAAc;AACd,+DAA+D;AAE/D,MAAM,CAAC,MAAM,wBAAwB,GAAG,CAAC,CAAC,MAAM,CAAC;IAC/C,KAAK,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC;IACxB,MAAM,EAAE,CAAC,CAAC,MAAM,EAAE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,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,CAAA;AACxC,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,qBAAqB,CAAC,MAA6B;IACjE,MAAM,MAAM,GAAG,2BAA2B,CAAC,KAAK,CAAC,MAAM,CAAC,CAAA;IACxD,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,CAAA;AAC3C,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,mBAAmB,CAAC,MAA2B;IAC7D,MAAM,MAAM,GAAG,yBAAyB,CAAC,KAAK,CAAC,MAAM,CAAC,CAAA;IACtD,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,EAAE,GAAG,MAAM,EAAE,MAAM,EAAE,CAAC,GAAG,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,CAAA;AAC5E,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,mBAAmB,CAAC,MAA2B;IAC7D,MAAM,MAAM,GAAG,yBAAyB,CAAC,KAAK,CAAC,MAAM,CAAC,CAAA;IACtD,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,EAAE,GAAG,MAAM,EAAE,MAAM,EAAE,CAAC,GAAG,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,CAAA;AAC5E,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,qBAAqB,CAAC,MAA6B;IACjE,MAAM,MAAM,GAAG,2BAA2B,CAAC,KAAK,CAAC,MAAM,CAAC,CAAA;IACxD,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,CAAA;AAC3C,CAAC","sourcesContent":["/**\n * Typed Transform Wrappers\n *\n * Typed runtime wrappers for TransformDescriptor.config.\n * These do NOT modify @pwfabric/contracts. They provide typed alternatives\n * that narrow the opaque Record<string, unknown> config.\n *\n * @module @pwfabric/runtime/surface/transforms\n */\n\nimport { z } from 'zod'\nimport type { TransformDescriptor } from '@pwfabric/contracts'\n\n// ============================================================\n// TYPED TRANSFORM CONFIG INTERFACES\n// ============================================================\n\n/**\n * Config for 'map' transforms\n */\nexport interface MapTransformConfig {\n readonly field: string\n readonly mapper: string\n}\n\n/**\n * Config for 'filter' transforms\n */\nexport interface FilterTransformConfig {\n readonly field: string\n readonly predicate: string\n}\n\n/**\n * Config for 'pick' transforms\n */\nexport interface PickTransformConfig {\n readonly fields: readonly string[]\n}\n\n/**\n * Config for 'omit' transforms\n */\nexport interface OmitTransformConfig {\n readonly fields: readonly string[]\n}\n\n/**\n * Config for 'custom' transforms\n */\nexport interface CustomTransformConfig {\n readonly handler: string\n readonly params?: Record<string, unknown>\n}\n\n/**\n * Discriminated union of all typed transform configs\n */\nexport type TypedTransformConfig =\n | { readonly type: 'map'; readonly config: MapTransformConfig }\n | { readonly type: 'filter'; readonly config: FilterTransformConfig }\n | { readonly type: 'pick'; readonly config: PickTransformConfig }\n | { readonly type: 'omit'; readonly config: OmitTransformConfig }\n | { readonly type: 'custom'; readonly config: CustomTransformConfig }\n\n// ============================================================\n// ZOD SCHEMAS\n// ============================================================\n\nexport const mapTransformConfigSchema = z.object({\n field: z.string().min(1),\n mapper: z.string().min(1),\n})\n\nexport const filterTransformConfigSchema = z.object({\n field: z.string().min(1),\n predicate: z.string().min(1),\n})\n\nexport const pickTransformConfigSchema = z.object({\n fields: z.array(z.string().min(1)).min(1),\n})\n\nexport const omitTransformConfigSchema = z.object({\n fields: z.array(z.string().min(1)).min(1),\n})\n\nexport const customTransformConfigSchema = z.object({\n handler: z.string().min(1),\n params: z.record(z.unknown()).optional(),\n})\n\n/**\n * Map of transform types to their Zod schemas\n */\nconst transformConfigSchemas = {\n map: mapTransformConfigSchema,\n filter: filterTransformConfigSchema,\n pick: pickTransformConfigSchema,\n omit: omitTransformConfigSchema,\n custom: customTransformConfigSchema,\n} as const\n\n// ============================================================\n// VALIDATION TYPES\n// ============================================================\n\n/**\n * Result of validating a transform config\n */\nexport interface TransformValidationResult {\n readonly valid: boolean\n readonly errors: readonly string[]\n}\n\n// ============================================================\n// VALIDATION FUNCTION\n// ============================================================\n\n/**\n * Validate a transform descriptor's config against the typed schema\n * for the given transform type.\n */\nexport function validateTransformConfig(\n type: TransformDescriptor['type'],\n config: Record<string, unknown>\n): TransformValidationResult {\n const schema = transformConfigSchemas[type]\n\n const result = schema.safeParse(config)\n\n if (result.success) {\n return { valid: true, errors: [] }\n }\n\n return {\n valid: false,\n errors: result.error.issues.map((i) => `${i.path.join('.')}: ${i.message}`),\n }\n}\n\n// ============================================================\n// TYPE GUARD\n// ============================================================\n\n/**\n * Type guard that narrows an opaque TransformDescriptor into\n * a TypedTransformConfig if the config passes validation.\n */\nexport function narrowTransformDescriptor(\n descriptor: TransformDescriptor\n): TypedTransformConfig | null {\n if (!descriptor.config) {\n return null\n }\n\n const schema = transformConfigSchemas[descriptor.type]\n const result = schema.safeParse(descriptor.config)\n\n if (!result.success) {\n return null\n }\n\n // The type assertion is safe because Zod validated the config shape\n return {\n type: descriptor.type,\n config: result.data,\n } as TypedTransformConfig\n}\n\n// ============================================================\n// FACTORY FUNCTIONS\n// ============================================================\n\n/**\n * Create a typed 'map' transform descriptor\n */\nexport function createMapTransform(config: MapTransformConfig): TransformDescriptor {\n const parsed = mapTransformConfigSchema.parse(config)\n return { type: 'map', config: parsed }\n}\n\n/**\n * Create a typed 'filter' transform descriptor\n */\nexport function createFilterTransform(config: FilterTransformConfig): TransformDescriptor {\n const parsed = filterTransformConfigSchema.parse(config)\n return { type: 'filter', config: parsed }\n}\n\n/**\n * Create a typed 'pick' transform descriptor\n */\nexport function createPickTransform(config: PickTransformConfig): TransformDescriptor {\n const parsed = pickTransformConfigSchema.parse(config)\n return { type: 'pick', config: { ...parsed, fields: [...parsed.fields] } }\n}\n\n/**\n * Create a typed 'omit' transform descriptor\n */\nexport function createOmitTransform(config: OmitTransformConfig): TransformDescriptor {\n const parsed = omitTransformConfigSchema.parse(config)\n return { type: 'omit', config: { ...parsed, fields: [...parsed.fields] } }\n}\n\n/**\n * Create a typed 'custom' transform descriptor\n */\nexport function createCustomTransform(config: CustomTransformConfig): TransformDescriptor {\n const parsed = customTransformConfigSchema.parse(config)\n return { type: 'custom', config: parsed }\n}\n"]}
1
+ {"version":3,"file":"transforms.js","sourceRoot":"","sources":["../../src/surface/transforms.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAA;AAuDvB,+DAA+D;AAC/D,cAAc;AACd,+DAA+D;AAE/D,MAAM,CAAC,MAAM,wBAAwB,GAAG,CAAC,CAAC,MAAM,CAAC;IAC/C,KAAK,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC;IACxB,MAAM,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC;CAC1B,CAAC,CAAA;AAEF,MAAM,CAAC,MAAM,2BAA2B,GAAG,CAAC,CAAC,MAAM,CAAC;IAClD,KAAK,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC;IACxB,SAAS,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC;CAC7B,CAAC,CAAA;AAEF,MAAM,CAAC,MAAM,yBAAyB,GAAG,CAAC,CAAC,MAAM,CAAC;IAChD,MAAM,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;CAC1C,CAAC,CAAA;AAEF,MAAM,CAAC,MAAM,yBAAyB,GAAG,CAAC,CAAC,MAAM,CAAC;IAChD,MAAM,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;CAC1C,CAAC,CAAA;AAEF,MAAM,CAAC,MAA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tD,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,EAAE,GAAG,MAAM,EAAE,MAAM,EAAE,CAAC,GAAG,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,CAAA;AAC5E,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,qBAAqB,CAAC,MAA6B;IACjE,MAAM,MAAM,GAAG,2BAA2B,CAAC,KAAK,CAAC,MAAM,CAAC,CAAA;IACxD,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,CAAA;AAC3C,CAAC","sourcesContent":["/**\n * Typed Transform Wrappers\n *\n * Typed runtime wrappers for TransformDescriptor.config.\n * These do NOT modify @pwfabric/contracts. They provide typed alternatives\n * that narrow the opaque Record<string, unknown> config.\n *\n * @module @pwfabric/runtime/surface/transforms\n */\n\nimport { z } from 'zod'\nimport type { TransformDescriptor } from '@pwfabric/contracts'\n\n// ============================================================\n// TYPED TRANSFORM CONFIG INTERFACES\n// ============================================================\n\n/**\n * Config for 'map' transforms\n */\nexport interface MapTransformConfig {\n readonly field: string\n readonly mapper: string\n}\n\n/**\n * Config for 'filter' transforms\n */\nexport interface FilterTransformConfig {\n readonly field: string\n readonly predicate: string\n}\n\n/**\n * Config for 'pick' transforms\n */\nexport interface PickTransformConfig {\n readonly fields: readonly string[]\n}\n\n/**\n * Config for 'omit' transforms\n */\nexport interface OmitTransformConfig {\n readonly fields: readonly string[]\n}\n\n/**\n * Config for 'custom' transforms\n */\nexport interface CustomTransformConfig {\n readonly handler: string\n readonly params?: Record<string, unknown>\n}\n\n/**\n * Discriminated union of all typed transform configs\n */\nexport type TypedTransformConfig =\n | { readonly type: 'map'; readonly config: MapTransformConfig }\n | { readonly type: 'filter'; readonly config: FilterTransformConfig }\n | { readonly type: 'pick'; readonly config: PickTransformConfig }\n | { readonly type: 'omit'; readonly config: OmitTransformConfig }\n | { readonly type: 'custom'; readonly config: CustomTransformConfig }\n\n// ============================================================\n// ZOD SCHEMAS\n// ============================================================\n\nexport const mapTransformConfigSchema = z.object({\n field: z.string().min(1),\n mapper: z.string().min(1),\n})\n\nexport const filterTransformConfigSchema = z.object({\n field: z.string().min(1),\n predicate: z.string().min(1),\n})\n\nexport const pickTransformConfigSchema = z.object({\n fields: z.array(z.string().min(1)).min(1),\n})\n\nexport const omitTransformConfigSchema = z.object({\n fields: z.array(z.string().min(1)).min(1),\n})\n\nexport const customTransformConfigSchema = z.object({\n handler: z.string().min(1),\n params: z.record(z.string(), z.unknown()).optional(),\n})\n\n/**\n * Map of transform types to their Zod schemas\n */\nconst transformConfigSchemas = {\n map: mapTransformConfigSchema,\n filter: filterTransformConfigSchema,\n pick: pickTransformConfigSchema,\n omit: omitTransformConfigSchema,\n custom: customTransformConfigSchema,\n} as const\n\n// ============================================================\n// VALIDATION TYPES\n// ============================================================\n\n/**\n * Result of validating a transform config\n */\nexport interface TransformValidationResult {\n readonly valid: boolean\n readonly errors: readonly string[]\n}\n\n// ============================================================\n// VALIDATION FUNCTION\n// ============================================================\n\n/**\n * Validate a transform descriptor's config against the typed schema\n * for the given transform type.\n */\nexport function validateTransformConfig(\n type: TransformDescriptor['type'],\n config: Record<string, unknown>\n): TransformValidationResult {\n const schema = transformConfigSchemas[type]\n\n const result = schema.safeParse(config)\n\n if (result.success) {\n return { valid: true, errors: [] }\n }\n\n return {\n valid: false,\n errors: result.error.issues.map((i) => `${i.path.map(String).join('.')}: ${i.message}`),\n }\n}\n\n// ============================================================\n// TYPE GUARD\n// ============================================================\n\n/**\n * Type guard that narrows an opaque TransformDescriptor into\n * a TypedTransformConfig if the config passes validation.\n */\nexport function narrowTransformDescriptor(\n descriptor: TransformDescriptor\n): TypedTransformConfig | null {\n if (!descriptor.config) {\n return null\n }\n\n const schema = transformConfigSchemas[descriptor.type]\n const result = schema.safeParse(descriptor.config)\n\n if (!result.success) {\n return null\n }\n\n // The type assertion is safe because Zod validated the config shape\n return {\n type: descriptor.type,\n config: result.data,\n } as TypedTransformConfig\n}\n\n// ============================================================\n// FACTORY FUNCTIONS\n// ============================================================\n\n/**\n * Create a typed 'map' transform descriptor\n */\nexport function createMapTransform(config: MapTransformConfig): TransformDescriptor {\n const parsed = mapTransformConfigSchema.parse(config)\n return { type: 'map', config: parsed }\n}\n\n/**\n * Create a typed 'filter' transform descriptor\n */\nexport function createFilterTransform(config: FilterTransformConfig): TransformDescriptor {\n const parsed = filterTransformConfigSchema.parse(config)\n return { type: 'filter', config: parsed }\n}\n\n/**\n * Create a typed 'pick' transform descriptor\n */\nexport function createPickTransform(config: PickTransformConfig): TransformDescriptor {\n const parsed = pickTransformConfigSchema.parse(config)\n return { type: 'pick', config: { ...parsed, fields: [...parsed.fields] } }\n}\n\n/**\n * Create a typed 'omit' transform descriptor\n */\nexport function createOmitTransform(config: OmitTransformConfig): TransformDescriptor {\n const parsed = omitTransformConfigSchema.parse(config)\n return { type: 'omit', config: { ...parsed, fields: [...parsed.fields] } }\n}\n\n/**\n * Create a typed 'custom' transform descriptor\n */\nexport function createCustomTransform(config: CustomTransformConfig): TransformDescriptor {\n const parsed = customTransformConfigSchema.parse(config)\n return { type: 'custom', config: parsed }\n}\n"]}
@@ -43,7 +43,7 @@ export function validateBlockProps(type, props, options = {}) {
43
43
  }
44
44
  return {
45
45
  valid: false,
46
- errors: result.error.issues.map((i) => `${i.path.join('.')}: ${i.message}`),
46
+ errors: result.error.issues.map((i) => `${i.path.map(String).join('.')}: ${i.message}`),
47
47
  };
48
48
  }
49
49
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"validation.js","sourceRoot":"","sources":["../../src/surface/validation.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AA6CH,+DAA+D;AAC/D,uBAAuB;AACvB,+DAA+D;AAE/D;;;;;;GAMG;AACH,MAAM,UAAU,kBAAkB,CAChC,IAAY,EACZ,KAA8B,EAC9B,UAAuC,EAAE;IAEzC,MAAM,EAAE,MAAM,GAAG,KAAK,EAAE,OAAO,EAAE,GAAG,OAAO,C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AC,IAAI,EAAE,MAAM,CAAC,KAAK,EAAE,SAAS,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,IAAI,CAAC,CAAA;IAC9F,IAAI,MAAM,CAAC,QAAQ,EAAE,CAAC;QACpB,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC,KAAK,EAAE,CAAC,EAAE,EAAE;YACnC,IAAI,KAAK;gBAAE,GAAG,CAAC,IAAI,CAAC,GAAG,oBAAoB,CAAC,KAAK,EAAE,SAAS,EAAE,GAAG,IAAI,aAAa,CAAC,GAAG,CAAC,CAAC,CAAA;QAC1F,CAAC,CAAC,CAAA;IACJ,CAAC;IACD,OAAO,GAAG,CAAA;AACZ,CAAC","sourcesContent":["/**\n * Block Props Validation\n *\n * Runtime validation of block props using injected Zod schemas.\n * the legacy `blockSchemas` map is gone — production\n * callers supply a schema map sourced from the install pipeline (per-atom\n * `manifest.definition.props[*].jsonSchema` rebuilt into Zod). Without a\n * schema map the validator runs in lenient mode and passes everything\n * through.\n *\n * @module @pwfabric/runtime/surface/validation\n */\n\nimport type { ZodSchema } from 'zod'\n\n/** Map of block type → Zod schema. Supply via options to enable strict checks. */\nexport type BlockSchemaMap = Readonly<Record<string, ZodSchema>>\n\n// ============================================================\n// VALIDATION TYPES\n// ============================================================\n\n/**\n * Options for block props validation\n */\nexport interface BlockPropsValidationOptions {\n /**\n * When true, unknown block types cause validation failure.\n * When false (default), unknown block types pass through.\n */\n readonly strict?: boolean\n /**\n * Per-block-type Zod schemas. the runtime no longer\n * ships a built-in schema map — callers that want prop validation\n * supply their own (typically rebuilt from\n * each installed block manifest's `definition.props[*].jsonSchema`).\n * Omitting the map yields lenient pass-through behaviour.\n */\n readonly schemas?: BlockSchemaMap\n /**\n * Per-block-type manifest props. When supplied, props a manifest\n * does not declare and templates on `bindable: false` props are reported as\n * WARNINGS (`manifestPropFindings`); they never fail validation.\n */\n readonly manifests?: BlockManifestPropsMap\n}\n\n/**\n * Result of validating block props against the schema\n */\nexport interface BlockPropsValidationResult {\n readonly valid: boolean\n readonly errors: readonly string[]\n readonly coerced?: Record<string, unknown>\n}\n\n// ============================================================\n// VALIDATION FUNCTIONS\n// ============================================================\n\n/**\n * Validate block props against the known Zod schema for the given block type.\n *\n * - Known block types are validated against the schema from @pwfabric/core.\n * - Unknown block types pass through in lenient mode (default) and fail in strict mode.\n * - On success, returns coerced data (with defaults applied by Zod).\n */\nexport function validateBlockProps(\n type: string,\n props: Record<string, unknown>,\n options: BlockPropsValidationOptions = {}\n): BlockPropsValidationResult {\n const { strict = false, schemas } = options\n\n const schema = schemas?.[type]\n\n if (!schema) {\n if (strict) {\n return {\n valid: false,\n errors: [`Unknown block type: ${type}`],\n }\n }\n // Lenient mode: unknown / unsupplied types pass through\n return { valid: true, errors: [] }\n }\n\n const result = schema.safeParse(props)\n\n if (result.success) {\n return {\n valid: true,\n errors: [],\n coerced: result.data as Record<string, unknown>,\n }\n }\n\n return {\n valid: false,\n errors: result.error.issues.map(\n (i: { path: (string | number)[]; message: string }) => `${i.path.join('.')}: ${i.message}`\n ),\n }\n}\n\n/**\n * Layout node shape for recursive validation.\n * Matches LayoutJSON structure without importing it to avoid circular deps.\n */\ninterface LayoutNode {\n readonly type: string\n readonly props?: Record<string, unknown>\n readonly children?: readonly LayoutNode[]\n}\n\n/**\n * A single validation issue with path context\n */\nexport interface LayoutPropsIssue {\n readonly path: string\n readonly type: string\n readonly errors: readonly string[]\n}\n\n/**\n * Validate all block props in a layout tree recursively.\n *\n * Returns a flat list of validation issues with path context.\n */\nexport function validateLayoutProps(\n layout: LayoutNode,\n options: BlockPropsValidationOptions = {},\n path = 'root'\n): readonly LayoutPropsIssue[] {\n const issues: LayoutPropsIssue[] = []\n\n const result = validateBlockProps(layout.type, layout.props ?? {}, options)\n if (!result.valid) {\n issues.push({\n path,\n type: layout.type,\n errors: result.errors,\n })\n }\n\n if (layout.children) {\n for (let i = 0; i < layout.children.length; i++) {\n const child = layout.children[i]\n if (child) {\n const childIssues = validateLayoutProps(child, options, `${path}.children[${i}]`)\n issues.push(...childIssues)\n }\n }\n }\n\n return issues\n}\n\n// ============================================================\n// PACK MANIFEST ENFORCEMENT\n// ============================================================\n\n/**\n * One prop a pack manifest declares: `manifest.definition.props[*]`. Only the\n * two fields the check reads; a full manifest entry passes as it is.\n */\nexport interface ManifestPropSpec {\n readonly name: string\n /** `false` = the prop takes a literal only; a `{{ }}` template is not resolved for it. */\n readonly bindable?: boolean\n}\n\n/** Block type → the props its manifest declares. */\nexport type BlockManifestPropsMap = Readonly<Record<string, readonly ManifestPropSpec[]>>\n\nexport type ManifestPropFindingCode = 'UNKNOWN_PROP' | 'TEMPLATE_ON_UNBINDABLE'\n\n/**\n * A prop that does not match its block's manifest. Always a WARNING:\n * existing apps carry such props and must keep rendering; a caller\n * decides whether to show, count or (later) refuse them.\n */\nexport interface ManifestPropFinding {\n readonly path: string\n readonly type: string\n readonly prop: string\n readonly code: ManifestPropFindingCode\n readonly severity: 'warning'\n readonly message: string\n}\n\nfunction carriesTemplate(value: unknown, depth = 0): boolean {\n if (depth > 8) return false\n if (typeof value === 'string') return value.includes('{{')\n if (Array.isArray(value)) return value.some((v) => carriesTemplate(v, depth + 1))\n if (value && typeof value === 'object') {\n return Object.values(value as Record<string, unknown>).some((v) => carriesTemplate(v, depth + 1))\n }\n return false\n}\n\n/**\n * The props of ONE block that its manifest does not allow.\n *\n * WHY: a prop the manifest does not declare was\n * accepted silently. The schema check rebuilds each prop's JSON schema into a\n * passthrough object, so a misspelt or invented prop (`tone` on a block that\n * has none, `paddingY` where the block reads `padding`) validated clean and\n * did nothing on screen. And a `{{ }}` template on a `bindable: false` prop was\n * shown to the visitor as literal braces. Both are now named.\n *\n * @param specs the block's declared props; `undefined` (block not in the map)\n * yields nothing, because an unknown block type is a different finding.\n */\nexport function blockManifestPropFindings(\n type: string,\n props: Record<string, unknown> | undefined,\n specs: readonly ManifestPropSpec[] | undefined,\n path = 'root'\n): ManifestPropFinding[] {\n if (!specs || !props) return []\n const byName = new Map(specs.map((s) => [s.name, s]))\n const out: ManifestPropFinding[] = []\n for (const [prop, value] of Object.entries(props)) {\n if (value === undefined) continue\n const spec = byName.get(prop)\n if (!spec) {\n out.push({\n path,\n type,\n prop,\n code: 'UNKNOWN_PROP',\n severity: 'warning',\n message: `\"${prop}\" is not a prop of ${type}; the block ignores it.`,\n })\n continue\n }\n if (spec.bindable === false && carriesTemplate(value)) {\n out.push({\n path,\n type,\n prop,\n code: 'TEMPLATE_ON_UNBINDABLE',\n severity: 'warning',\n message: `\"${prop}\" on ${type} takes a literal value; its {{ }} template is shown as written.`,\n })\n }\n }\n return out\n}\n\n/**\n * Every manifest finding in a layout tree, with path context. Blocks whose\n * type is not in `manifests` are skipped.\n */\nexport function manifestPropFindings(\n layout: LayoutNode,\n manifests: BlockManifestPropsMap,\n path = 'root'\n): ManifestPropFinding[] {\n const out = blockManifestPropFindings(layout.type, layout.props, manifests[layout.type], path)\n if (layout.children) {\n layout.children.forEach((child, i) => {\n if (child) out.push(...manifestPropFindings(child, manifests, `${path}.children[${i}]`))\n })\n }\n return out\n}\n"]}
1
+ {"version":3,"file":"validation.js","sourceRoot":"","sources":["../../src/surface/validation.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AA6CH,+DAA+D;AAC/D,uBAAuB;AACvB,+DAA+D;AAE/D;;;;;;GAMG;AACH,MAAM,UAAU,kBAAkB,CAChC,IAAY,EACZ,KAA8B,EAC9B,UAAuC,EAAE;IAEzC,MAAM,EAAE,MAAM,GAAG,KAAK,EAAE,OAAO,EAAE,GAAG,OAAO,CAAA;IAE3C,MAAM,MAAM,GAAG,OAAO,EAAE,CAAC,IAAI,CAAC,CAAA;IAE9B,IAAI,CAAC,MAAM,EAAE,CAAC;QACZ,IAAI,MAAM,EAAE,CAAC;YACX,OAAO;gBACL,KAAK,EAAE,KAAK;gBACZ,MAAM,EAAE,CAAC,uBAAuB,IAAI,EAAE,CAAC;aACxC,CAAA;QACH,CAAC;QACD,w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E;YACnC,IAAI,KAAK;gBAAE,GAAG,CAAC,IAAI,CAAC,GAAG,oBAAoB,CAAC,KAAK,EAAE,SAAS,EAAE,GAAG,IAAI,aAAa,CAAC,GAAG,CAAC,CAAC,CAAA;QAC1F,CAAC,CAAC,CAAA;IACJ,CAAC;IACD,OAAO,GAAG,CAAA;AACZ,CAAC","sourcesContent":["/**\n * Block Props Validation\n *\n * Runtime validation of block props using injected Zod schemas.\n * the legacy `blockSchemas` map is gone — production\n * callers supply a schema map sourced from the install pipeline (per-atom\n * `manifest.definition.props[*].jsonSchema` rebuilt into Zod). Without a\n * schema map the validator runs in lenient mode and passes everything\n * through.\n *\n * @module @pwfabric/runtime/surface/validation\n */\n\nimport type { ZodSchema } from 'zod'\n\n/** Map of block type → Zod schema. Supply via options to enable strict checks. */\nexport type BlockSchemaMap = Readonly<Record<string, ZodSchema>>\n\n// ============================================================\n// VALIDATION TYPES\n// ============================================================\n\n/**\n * Options for block props validation\n */\nexport interface BlockPropsValidationOptions {\n /**\n * When true, unknown block types cause validation failure.\n * When false (default), unknown block types pass through.\n */\n readonly strict?: boolean\n /**\n * Per-block-type Zod schemas. the runtime no longer\n * ships a built-in schema map — callers that want prop validation\n * supply their own (typically rebuilt from\n * each installed block manifest's `definition.props[*].jsonSchema`).\n * Omitting the map yields lenient pass-through behaviour.\n */\n readonly schemas?: BlockSchemaMap\n /**\n * Per-block-type manifest props. When supplied, props a manifest\n * does not declare and templates on `bindable: false` props are reported as\n * WARNINGS (`manifestPropFindings`); they never fail validation.\n */\n readonly manifests?: BlockManifestPropsMap\n}\n\n/**\n * Result of validating block props against the schema\n */\nexport interface BlockPropsValidationResult {\n readonly valid: boolean\n readonly errors: readonly string[]\n readonly coerced?: Record<string, unknown>\n}\n\n// ============================================================\n// VALIDATION FUNCTIONS\n// ============================================================\n\n/**\n * Validate block props against the known Zod schema for the given block type.\n *\n * - Known block types are validated against the schema from @pwfabric/core.\n * - Unknown block types pass through in lenient mode (default) and fail in strict mode.\n * - On success, returns coerced data (with defaults applied by Zod).\n */\nexport function validateBlockProps(\n type: string,\n props: Record<string, unknown>,\n options: BlockPropsValidationOptions = {}\n): BlockPropsValidationResult {\n const { strict = false, schemas } = options\n\n const schema = schemas?.[type]\n\n if (!schema) {\n if (strict) {\n return {\n valid: false,\n errors: [`Unknown block type: ${type}`],\n }\n }\n // Lenient mode: unknown / unsupplied types pass through\n return { valid: true, errors: [] }\n }\n\n const result = schema.safeParse(props)\n\n if (result.success) {\n return {\n valid: true,\n errors: [],\n coerced: result.data as Record<string, unknown>,\n }\n }\n\n return {\n valid: false,\n errors: result.error.issues.map(\n (i) => `${i.path.map(String).join('.')}: ${i.message}`\n ),\n }\n}\n\n/**\n * Layout node shape for recursive validation.\n * Matches LayoutJSON structure without importing it to avoid circular deps.\n */\ninterface LayoutNode {\n readonly type: string\n readonly props?: Record<string, unknown>\n readonly children?: readonly LayoutNode[]\n}\n\n/**\n * A single validation issue with path context\n */\nexport interface LayoutPropsIssue {\n readonly path: string\n readonly type: string\n readonly errors: readonly string[]\n}\n\n/**\n * Validate all block props in a layout tree recursively.\n *\n * Returns a flat list of validation issues with path context.\n */\nexport function validateLayoutProps(\n layout: LayoutNode,\n options: BlockPropsValidationOptions = {},\n path = 'root'\n): readonly LayoutPropsIssue[] {\n const issues: LayoutPropsIssue[] = []\n\n const result = validateBlockProps(layout.type, layout.props ?? {}, options)\n if (!result.valid) {\n issues.push({\n path,\n type: layout.type,\n errors: result.errors,\n })\n }\n\n if (layout.children) {\n for (let i = 0; i < layout.children.length; i++) {\n const child = layout.children[i]\n if (child) {\n const childIssues = validateLayoutProps(child, options, `${path}.children[${i}]`)\n issues.push(...childIssues)\n }\n }\n }\n\n return issues\n}\n\n// ============================================================\n// PACK MANIFEST ENFORCEMENT\n// ============================================================\n\n/**\n * One prop a pack manifest declares: `manifest.definition.props[*]`. Only the\n * two fields the check reads; a full manifest entry passes as it is.\n */\nexport interface ManifestPropSpec {\n readonly name: string\n /** `false` = the prop takes a literal only; a `{{ }}` template is not resolved for it. */\n readonly bindable?: boolean\n}\n\n/** Block type → the props its manifest declares. */\nexport type BlockManifestPropsMap = Readonly<Record<string, readonly ManifestPropSpec[]>>\n\nexport type ManifestPropFindingCode = 'UNKNOWN_PROP' | 'TEMPLATE_ON_UNBINDABLE'\n\n/**\n * A prop that does not match its block's manifest. Always a WARNING:\n * existing apps carry such props and must keep rendering; a caller\n * decides whether to show, count or (later) refuse them.\n */\nexport interface ManifestPropFinding {\n readonly path: string\n readonly type: string\n readonly prop: string\n readonly code: ManifestPropFindingCode\n readonly severity: 'warning'\n readonly message: string\n}\n\nfunction carriesTemplate(value: unknown, depth = 0): boolean {\n if (depth > 8) return false\n if (typeof value === 'string') return value.includes('{{')\n if (Array.isArray(value)) return value.some((v) => carriesTemplate(v, depth + 1))\n if (value && typeof value === 'object') {\n return Object.values(value as Record<string, unknown>).some((v) => carriesTemplate(v, depth + 1))\n }\n return false\n}\n\n/**\n * The props of ONE block that its manifest does not allow.\n *\n * WHY: a prop the manifest does not declare was\n * accepted silently. The schema check rebuilds each prop's JSON schema into a\n * passthrough object, so a misspelt or invented prop (`tone` on a block that\n * has none, `paddingY` where the block reads `padding`) validated clean and\n * did nothing on screen. And a `{{ }}` template on a `bindable: false` prop was\n * shown to the visitor as literal braces. Both are now named.\n *\n * @param specs the block's declared props; `undefined` (block not in the map)\n * yields nothing, because an unknown block type is a different finding.\n */\nexport function blockManifestPropFindings(\n type: string,\n props: Record<string, unknown> | undefined,\n specs: readonly ManifestPropSpec[] | undefined,\n path = 'root'\n): ManifestPropFinding[] {\n if (!specs || !props) return []\n const byName = new Map(specs.map((s) => [s.name, s]))\n const out: ManifestPropFinding[] = []\n for (const [prop, value] of Object.entries(props)) {\n if (value === undefined) continue\n const spec = byName.get(prop)\n if (!spec) {\n out.push({\n path,\n type,\n prop,\n code: 'UNKNOWN_PROP',\n severity: 'warning',\n message: `\"${prop}\" is not a prop of ${type}; the block ignores it.`,\n })\n continue\n }\n if (spec.bindable === false && carriesTemplate(value)) {\n out.push({\n path,\n type,\n prop,\n code: 'TEMPLATE_ON_UNBINDABLE',\n severity: 'warning',\n message: `\"${prop}\" on ${type} takes a literal value; its {{ }} template is shown as written.`,\n })\n }\n }\n return out\n}\n\n/**\n * Every manifest finding in a layout tree, with path context. Blocks whose\n * type is not in `manifests` are skipped.\n */\nexport function manifestPropFindings(\n layout: LayoutNode,\n manifests: BlockManifestPropsMap,\n path = 'root'\n): ManifestPropFinding[] {\n const out = blockManifestPropFindings(layout.type, layout.props, manifests[layout.type], path)\n if (layout.children) {\n layout.children.forEach((child, i) => {\n if (child) out.push(...manifestPropFindings(child, manifests, `${path}.children[${i}]`))\n })\n }\n return out\n}\n"]}
package/dist/validator.js CHANGED
@@ -92,7 +92,7 @@ export function isValidationFailure(result) {
92
92
  export function formatValidationErrors(errors) {
93
93
  return errors
94
94
  .map((e) => {
95
- const path = e.path.length > 0 ? `${e.path.join('.')}: ` : '';
95
+ const path = e.path.length > 0 ? `${e.path.map(String).join('.')}: ` : '';
96
96
  return `${path}${e.message} (${e.code})`;
97
97
  })
98
98
  .join('\n');
@@ -1 +1 @@
1
- {"version":3,"file":"validator.js","sourceRoot":"","sources":["../src/validator.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAGH,OAAO,EAAE,EAAE,EAAE,GAAG,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAA;AA0B9D,+DAA+D;AAC/D,mCAAmC;AACnC,+DAA+D;AAE/D;;GAEG;AACH,MAAM,OAAO,wBAAwB;IACnC,aAAa,CAAI,QAA8B,EAAE,IAAa;QAC5D,IAAI,CAAC;YACH,OAAO,QAAQ,CAAC,aAAa,CAAC,IAAI,CAAC,CAAA;QACrC,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,MAAM,MAAM,GAAsB;gBAChC,eAAe,CACb,EAAE,EACF,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,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CAAA;QAC7D,OAAO,GAAG,IAAI,GAAG,CAAC,CAAC,OAAO,KAAK,CAAC,CAAC,IAAI,GAAG,CAAA;IAC1C,CAAC,CAAC;SACD,IAAI,CAAC,IAAI,CAAC,CAAA;AACf,CAAC","sourcesContent":["/**\n * Contract Validator\n *\n * Runtime validation for contracts\n *\n * @module @pwfabric/runtime/validator\n */\n\nimport type { Contract, Capability, ValidationResult, ValidationError } from '@pwfabric/contracts'\nimport { ok, err, validationError } from '@pwfabric/contracts'\n\n// ============================================================\n// VALIDATOR INTERFACE\n// ============================================================\n\n/**\n * Contract validator interface\n */\nexport interface ContractValidator {\n /**\n * Validate input against a contract\n */\n validateInput<T>(contract: Contract<T, unknown>, data: unknown): ValidationResult<T>\n\n /**\n * Validate output against a contract\n */\n validateOutput<T>(contract: Contract<unknown, T>, data: unknown): ValidationResult<T>\n\n /**\n * Validate a capability's contract\n */\n validateCapability(capability: Capability): ValidationResult<void>\n}\n\n// ============================================================\n// RUNTIME VALIDATOR IMPLEMENTATION\n// ============================================================\n\n/**\n * Runtime contract validator\n */\nexport class RuntimeContractValidator implements ContractValidator {\n validateInput<T>(contract: Contract<T, unknown>, data: unknown): ValidationResult<T> {\n try {\n return contract.validateInput(data)\n } catch (error) {\n const errors: ValidationError[] = [\n validationError(\n [],\n error instanceof Error ? error.message : 'Unknown validation error',\n 'validation_error'\n ),\n ]\n return err(errors)\n }\n }\n\n validateOutput<T>(contract: Contract<unknown, T>, data: unknown): ValidationResult<T> {\n try {\n return contract.validateOutput(data)\n } catch (error) {\n const errors: ValidationError[] = [\n validationError(\n [],\n error instanceof Error ? error.message : 'Unknown validation error',\n 'validation_error'\n ),\n ]\n return err(errors)\n }\n }\n\n validateCapability(capability: Capability): ValidationResult<void> {\n const errors: ValidationError[] = []\n\n // Validate capability has required fields\n if (!capability.id) {\n errors.push(validationError(['id'], 'Capability ID is required', 'required'))\n }\n\n if (!capability.version) {\n errors.push(validationError(['version'], 'Capability version is required', 'required'))\n }\n\n if (!capability.contract) {\n errors.push(validationError(['contract'], 'Capability contract is required', 'required'))\n }\n\n if (!capability.execute) {\n errors.push(\n validationError(['execute'], 'Capability execute function is required', 'required')\n )\n }\n\n // Validate contract exists and has required methods\n if (capability.contract) {\n if (!capability.contract.validateInput) {\n errors.push(\n validationError(\n ['contract', 'validateInput'],\n 'Contract validateInput method is required',\n 'required'\n )\n )\n }\n\n if (!capability.contract.validateOutput) {\n errors.push(\n validationError(\n ['contract', 'validateOutput'],\n 'Contract validateOutput method is required',\n 'required'\n )\n )\n }\n }\n\n if (errors.length > 0) {\n return err(errors)\n }\n\n return ok(undefined)\n }\n}\n\n// ============================================================\n// VALIDATION UTILITIES\n// ============================================================\n\n/**\n * Create a contract validator\n */\nexport function createValidator(): ContractValidator {\n return new RuntimeContractValidator()\n}\n\n/**\n * Validation result type guard\n */\nexport function isValidationSuccess<T>(\n result: ValidationResult<T>\n): result is { success: true; data: T } {\n return result.success === true\n}\n\n/**\n * Validation result type guard for errors\n */\nexport function isValidationFailure<T>(\n result: ValidationResult<T>\n): result is { success: false; error: ValidationError[] } {\n return result.success === false\n}\n\n/**\n * Format validation errors as a string\n */\nexport function formatValidationErrors(errors: ValidationError[]): string {\n return errors\n .map((e) => {\n const path = e.path.length > 0 ? `${e.path.join('.')}: ` : ''\n return `${path}${e.message} (${e.code})`\n })\n .join('\\n')\n}\n"]}
1
+ {"version":3,"file":"validator.js","sourceRoot":"","sources":["../src/validator.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAGH,OAAO,EAAE,EAAE,EAAE,GAAG,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAA;AA0B9D,+DAA+D;AAC/D,mCAAmC;AACnC,+DAA+D;AAE/D;;GAEG;AACH,MAAM,OAAO,wBAAwB;IACnC,aAAa,CAAI,QAA8B,EAAE,IAAa;QAC5D,IAAI,CAAC;YACH,OAAO,QAAQ,CAAC,aAAa,CAAC,IAAI,CAAC,CAAA;QACrC,CAAC;QAAC,OAAO,KA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C,CAAC,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAA;QACzE,OAAO,GAAG,IAAI,GAAG,CAAC,CAAC,OAAO,KAAK,CAAC,CAAC,IAAI,GAAG,CAAA;IAC1C,CAAC,CAAC;SACD,IAAI,CAAC,IAAI,CAAC,CAAA;AACf,CAAC","sourcesContent":["/**\n * Contract Validator\n *\n * Runtime validation for contracts\n *\n * @module @pwfabric/runtime/validator\n */\n\nimport type { Contract, Capability, ValidationResult, ValidationError } from '@pwfabric/contracts'\nimport { ok, err, validationError } from '@pwfabric/contracts'\n\n// ============================================================\n// VALIDATOR INTERFACE\n// ============================================================\n\n/**\n * Contract validator interface\n */\nexport interface ContractValidator {\n /**\n * Validate input against a contract\n */\n validateInput<T>(contract: Contract<T, unknown>, data: unknown): ValidationResult<T>\n\n /**\n * Validate output against a contract\n */\n validateOutput<T>(contract: Contract<unknown, T>, data: unknown): ValidationResult<T>\n\n /**\n * Validate a capability's contract\n */\n validateCapability(capability: Capability): ValidationResult<void>\n}\n\n// ============================================================\n// RUNTIME VALIDATOR IMPLEMENTATION\n// ============================================================\n\n/**\n * Runtime contract validator\n */\nexport class RuntimeContractValidator implements ContractValidator {\n validateInput<T>(contract: Contract<T, unknown>, data: unknown): ValidationResult<T> {\n try {\n return contract.validateInput(data)\n } catch (error) {\n const errors: ValidationError[] = [\n validationError(\n [],\n error instanceof Error ? error.message : 'Unknown validation error',\n 'validation_error'\n ),\n ]\n return err(errors)\n }\n }\n\n validateOutput<T>(contract: Contract<unknown, T>, data: unknown): ValidationResult<T> {\n try {\n return contract.validateOutput(data)\n } catch (error) {\n const errors: ValidationError[] = [\n validationError(\n [],\n error instanceof Error ? error.message : 'Unknown validation error',\n 'validation_error'\n ),\n ]\n return err(errors)\n }\n }\n\n validateCapability(capability: Capability): ValidationResult<void> {\n const errors: ValidationError[] = []\n\n // Validate capability has required fields\n if (!capability.id) {\n errors.push(validationError(['id'], 'Capability ID is required', 'required'))\n }\n\n if (!capability.version) {\n errors.push(validationError(['version'], 'Capability version is required', 'required'))\n }\n\n if (!capability.contract) {\n errors.push(validationError(['contract'], 'Capability contract is required', 'required'))\n }\n\n if (!capability.execute) {\n errors.push(\n validationError(['execute'], 'Capability execute function is required', 'required')\n )\n }\n\n // Validate contract exists and has required methods\n if (capability.contract) {\n if (!capability.contract.validateInput) {\n errors.push(\n validationError(\n ['contract', 'validateInput'],\n 'Contract validateInput method is required',\n 'required'\n )\n )\n }\n\n if (!capability.contract.validateOutput) {\n errors.push(\n validationError(\n ['contract', 'validateOutput'],\n 'Contract validateOutput method is required',\n 'required'\n )\n )\n }\n }\n\n if (errors.length > 0) {\n return err(errors)\n }\n\n return ok(undefined)\n }\n}\n\n// ============================================================\n// VALIDATION UTILITIES\n// ============================================================\n\n/**\n * Create a contract validator\n */\nexport function createValidator(): ContractValidator {\n return new RuntimeContractValidator()\n}\n\n/**\n * Validation result type guard\n */\nexport function isValidationSuccess<T>(\n result: ValidationResult<T>\n): result is { success: true; data: T } {\n return result.success === true\n}\n\n/**\n * Validation result type guard for errors\n */\nexport function isValidationFailure<T>(\n result: ValidationResult<T>\n): result is { success: false; error: ValidationError[] } {\n return result.success === false\n}\n\n/**\n * Format validation errors as a string\n */\nexport function formatValidationErrors(errors: ValidationError[]): string {\n return errors\n .map((e) => {\n const path = e.path.length > 0 ? `${e.path.map(String).join('.')}: ` : ''\n return `${path}${e.message} (${e.code})`\n })\n .join('\\n')\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pwfabric/runtime",
3
- "version": "1.2.0",
3
+ "version": "2.0.0",
4
4
  "description": "PWFabric runtime and execution engine",
5
5
  "type": "module",
6
6
  "license": "BUSL-1.1",
@@ -69,12 +69,12 @@
69
69
  "node": ">=22"
70
70
  },
71
71
  "dependencies": {
72
- "@pwfabric/contracts": "1.2.0",
73
- "@pwfabric/core": "1.2.0"
72
+ "@pwfabric/contracts": "2.0.0",
73
+ "@pwfabric/core": "2.0.0"
74
74
  },
75
75
  "peerDependencies": {
76
76
  "react": "^18.0.0 || ^19.0.0",
77
- "zod": "^3.23.0"
77
+ "zod": "^4.6.6"
78
78
  },
79
79
  "devDependencies": {
80
80
  "@testing-library/jest-dom": "^6.9.1",
@@ -83,14 +83,14 @@
83
83
  "@types/node": "^22.0.0",
84
84
  "@types/react": "^19.0.0",
85
85
  "@types/react-dom": "^19.0.0",
86
- "@vitest/coverage-v8": "^2.1.9",
86
+ "@vitest/coverage-v8": "^4.1.12",
87
87
  "jsdom": "^26.0.0",
88
- "next": "^16.1.5",
88
+ "next": "^16.4.6",
89
89
  "react": "^19.0.0",
90
90
  "react-dom": "^19.0.0",
91
91
  "typescript": "^5.4.0",
92
- "vitest": "^2.0.0",
93
- "zod": "^3.25.76"
92
+ "vitest": "^4.1.12",
93
+ "zod": "^4.6.7"
94
94
  },
95
95
  "publishConfig": {
96
96
  "access": "public"