@entifix/service-shell 0.14.0 → 0.16.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.
@@ -1 +1 @@
1
- {"version":3,"file":"build-api.d.ts","sourceRoot":"","sources":["../../src/http-api/build-api.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,iBAAiB,EACjB,iBAAiB,EACjB,mBAAmB,EACnB,kBAAkB,EACnB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,KAAK,WAAW,EAGhB,KAAK,WAAW,EAGhB,KAAK,YAAY,EAKjB,KAAK,WAAW,EAEhB,OAAO,EAOR,MAAM,eAAe,CAAC;AACvB,OAAO,EAEL,KAAK,UAAU,EACf,KAAK,EACL,KAAK,IAAI,EAGV,MAAM,QAAQ,CAAC;AAChB,OAAO,KAAK,EAAE,IAAI,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAElE,OAAO,EACL,OAAO,EAGP,YAAY,EAEZ,iBAAiB,EAElB,MAAM,iBAAiB,CAAC;AAGzB,OAAO,EAEL,KAAK,aAAa,EAEnB,MAAM,eAAe,CAAC;AACvB,OAAO,EAKL,KAAK,aAAa,EAElB,KAAK,mBAAmB,EACzB,MAAM,aAAa,CAAC;AAGrB;;;;GAIG;AACH,MAAM,WAAW,aAAa,CAC5B,QAAQ,SAAS,WAAW,GAAG,WAAW,EAC1C,CAAC,GAAG,KAAK;IAET,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,SAAS,EAAE,aAAa,CAAC,WAAW,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,CAAC;CAC7D;AAED,8EAA8E;AAE9E,MAAM,MAAM,gBAAgB,GAAG,aAAa,CAAC,WAAW,EAAE,GAAG,CAAC,CAAC;AAG/D,KAAK,UAAU,CAAC,CAAC,IAAI,CAAC,SAAS,WAAW,CAAC,MAAM,CAAC,EAAE,GAAG,CAAC,GAAG,CAA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AAO,MAAM,QAAQ,GACnB,MAAM,MAAM,EACZ,QAAQ,aAAa,CAAC,gBAAgB,CAAC,EACvC,UAAS,UAAe,KACvB,OAAO,CAAC,GA+BV,CAAC;AAEF;;;;GAIG;AACH,eAAO,MAAM,QAAQ,GAAI,KAAK,CAAC,MAAM,SAAS,aAAa,CAAC,gBAAgB,CAAC,EAC3E,KAAK,OAAO,CAAC,GAAG,EAChB,QAAQ,MAAM,EACd,UAAS,UAAe,KACvB,KAAK,CAAC,KAAK,CAAC,KAAK,EAAE,KAAK,EAAE,kBAAkB,CAAC,MAAM,CAAC,GAAG,cAAc,CAsBvE,CAAC;AAEF,0EAA0E;AAC1E,eAAO,MAAM,cAAc,GACzB,KAAK,CAAC,MAAM,SAAS,aAAa,CAAC,gBAAgB,CAAC,EAEpD,MAAM,MAAM,EACZ,QAAQ,MAAM,EACd,UAAS,UAAe;;;CAIzB,CAAC"}
@@ -133,7 +133,7 @@ const toEndpoint = (descriptor, policy)=>{
133
133
  }, headers === undefined ? {} : {
134
134
  headers
135
135
  }, {
136
- success: descriptor.success,
136
+ success: descriptor.accepted === true ? HttpApiSchema.status(202)(descriptor.success) : descriptor.success,
137
137
  error: errorSchemas(descriptor, policy)
138
138
  })).annotate(EndpointGuardAnnotation, descriptor.guard);
139
139
  // Order is outermost last: idempotency runs inside the guard, so it sees
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/http-api/build-api.ts"],"sourcesContent":["import type {\n IdempotencyKeyTag,\n OrganizationIdTag,\n RequestPrincipalTag,\n VerifiedContextTag,\n} from '@entifix/business';\nimport {\n type AnyEndpoint,\n bodyEncodingOf,\n Contention,\n type DeadlineTag,\n type EndpointSchema,\n type EntifixFailure,\n type FailureClass,\n Forbidden,\n IdempotencyKeyInFlight,\n IdempotencyKeyMissing,\n IdempotencyKeyReused,\n type Implemented,\n Internal,\n Invalid,\n Overloaded,\n ProtocolFailure,\n Timeout,\n Unauthenticated,\n Unavailable,\n UpstreamUnavailable,\n} from '@entifix/core';\nimport {\n Effect,\n type FileSystem,\n Layer,\n type Path,\n Schema,\n SchemaIssue,\n} from 'effect';\nimport type { Etag, HttpPlatform, HttpRouter } from 'effect/http';\nimport { HttpServerResponse } from 'effect/http';\nimport {\n HttpApi,\n HttpApiBuilder,\n HttpApiEndpoint,\n HttpApiError,\n HttpApiGroup,\n HttpApiMiddleware,\n HttpApiSchema,\n} from 'effect/http-api';\n\nimport { NoActiveOrganization } from '../auth/failures.js';\nimport {\n defaultFailurePolicy,\n type FailurePolicy,\n respond,\n} from '../respond.js';\nimport {\n EndpointGuardAnnotation,\n EndpointIdempotencyAnnotation,\n GUARD_MIDDLEWARE,\n guardLayers,\n type GuardServices,\n IdempotencyGuard,\n type IdempotencyServices,\n} from './guards.js';\nimport { problemCodec } from './problem-codec.js';\n\n/**\n * A named set of implemented endpoints — one `HttpApiGroup` once built. A slice\n * groups by entity or by concern; the name is what an OpenAPI document and a\n * client namespace it under.\n */\nexport interface EndpointGroup<\n Endpoint extends AnyEndpoint = AnyEndpoint,\n R = never,\n> {\n readonly name: string;\n readonly endpoints: ReadonlyArray<Implemented<Endpoint, R>>;\n}\n\n/** Any group, whatever its handlers need — the constraint a builder takes. */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- a constraint\nexport type AnyEndpointGroup = EndpointGroup<AnyEndpoint, any>;\n\n/* eslint-disable @typescript-eslint/no-explicit-any -- inference sites */\ntype EndpointOf<I> = I extends Implemented<infer D, any> ? D : never;\ntype RequirementsOf<I> = I extends Implemented<any, infer R> ? R : never;\n/* eslint-enable @typescript-eslint/no-explicit-any */\n\n/** Group implemented endpoints under one name. */\nexport const endpointGroup = <\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const Endpoints extends ReadonlyArray<Implemented<any, any>>,\n>(\n name: string,\n ...endpoints: Endpoints\n): EndpointGroup<\n EndpointOf<Endpoints[number]>,\n RequirementsOf<Endpoints[number]>\n> => ({\n name,\n endpoints: endpoints as never,\n});\n\n/** What the shell provides a handler: the verified request context. */\nexport type ProvidedToHandlers =\n | RequestPrincipalTag\n | OrganizationIdTag\n | IdempotencyKeyTag\n | VerifiedContextTag\n | DeadlineTag;\n\n/**\n * What serving `Groups` requires of the composition root: what the handlers\n * need beyond the request context, plus what each declared guard and\n * idempotency mode reads. A host that omits one does not compile.\n */\nexport type ServedRequirements<Groups extends ReadonlyArray<AnyEndpointGroup>> =\n GroupRequirements<Groups[number]>;\n\n// Distributive over the groups, and `never` for none.\ntype GroupRequirements<Group> =\n Group extends EndpointGroup<infer Endpoint, infer R>\n ? | Exclude<R, ProvidedToHandlers>\n | GuardServices<Endpoint['guard']['kind']>\n | IdempotencyServices<Endpoint['idempotent']>\n : never;\n\n/** What serving an API needs from the HTTP server itself. */\nexport type ServedPlatform =\n | HttpRouter.HttpRouter\n | Etag.Generator\n | FileSystem.FileSystem\n | HttpPlatform.HttpPlatform\n | Path.Path;\n\n/** `METHOD /path` for every endpoint — what a register diffs a service against. */\nexport const endpointsOf = (\n groups: ReadonlyArray<AnyEndpointGroup>,\n): readonly string[] =>\n groups.flatMap(group =>\n group.endpoints.map(\n ({ descriptor }) => `${descriptor.method} ${descriptor.path}`,\n ),\n );\n\n/** The failures every endpoint may answer, whether or not it declares them. */\nconst TECHNICAL: readonly FailureClass[] = [\n Invalid,\n Internal,\n Unavailable,\n UpstreamUnavailable,\n Timeout,\n Overloaded,\n Contention,\n ProtocolFailure,\n];\n\nconst GUARD_FAILURES: Readonly<\n Record<AnyEndpoint['guard']['kind'], readonly FailureClass[]>\n> = {\n public: [],\n session: [Unauthenticated],\n permission: [Unauthenticated, Forbidden],\n organization: [Unauthenticated, Forbidden, NoActiveOrganization],\n crossing: [Unauthenticated, Forbidden],\n fleet: [Unauthenticated],\n};\n\nconst IDEMPOTENCY_FAILURES: readonly FailureClass[] = [\n IdempotencyKeyMissing,\n IdempotencyKeyReused,\n IdempotencyKeyInFlight,\n];\n\n/** The status a failure class answers with under `policy`. */\nexport const statusForClass = (\n failureClass: FailureClass,\n policy: FailurePolicy,\n): number =>\n policy.tagStatus[failureClass.identifier] ??\n policy.categoryStatus[\n (failureClass.prototype as unknown as EntifixFailure).category\n ];\n\nconst errorSchemas = (descriptor: AnyEndpoint, policy: FailurePolicy) =>\n [\n ...new Set([\n ...descriptor.errors,\n ...GUARD_FAILURES[descriptor.guard.kind],\n ...(descriptor.idempotent === undefined ? [] : IDEMPOTENCY_FAILURES),\n ...TECHNICAL,\n ]),\n ].map(failureClass =>\n problemCodec(failureClass, statusForClass(failureClass, policy)),\n );\n\nconst toSchema = (schema: EndpointSchema | undefined) =>\n schema === undefined\n ? undefined\n : Schema.isSchema(schema)\n ? schema\n : Schema.Struct(schema);\n\n/** A payload on the wire it declared: JSON unless it said text or a form. */\nconst toPayload = (schema: EndpointSchema | undefined) => {\n const payload = toSchema(schema);\n if (payload === undefined) return undefined;\n const encoding = bodyEncodingOf(payload);\n switch (encoding?.kind) {\n case 'text':\n // A `textBody` is a string schema; the marker is what says so here.\n return (payload as Schema.String).pipe(\n HttpApiSchema.asText({ contentType: encoding.contentType }),\n );\n case 'form':\n return payload.pipe(\n HttpApiSchema.asFormUrlEncoded({ contentType: encoding.contentType }),\n );\n default:\n return payload;\n }\n};\n\n/**\n * The outermost middleware of every endpoint: `respond` under the API's\n * policy, after a schema error has become `invalid` with one entry per broken\n * field. A response that fails to encode is the service's own fault and stays\n * a defect.\n */\nexport class Respond extends HttpApiMiddleware.Service<Respond>()(\n '@entifix/service-shell/Respond',\n) {}\n\nconst formatIssues = SchemaIssue.makeFormatterStandardSchemaV1();\n\n/** The `invalid` failure a request that fails its schema answers with. */\nexport const invalidRequest = (\n error: HttpApiError.HttpApiSchemaError,\n): Invalid => {\n const where = error.kind.toLowerCase();\n const { issues } = formatIssues(error.cause.issue);\n return new Invalid({\n errors: issues.map(issue => ({\n // Effect's formatter always sets the path — `[]` for the part itself —\n // though the Standard Schema type it answers with leaves it optional.\n pointer: `/${[where, ...(issue.path as readonly PropertyKey[]).map(String)].join('/')}`,\n detail: issue.message,\n code: 'schema',\n })),\n });\n};\n\nconst REQUEST_PARTS: ReadonlySet<HttpApiError.HttpApiSchemaError['kind']> =\n new Set(['Params', 'Query', 'Payload', 'Headers']);\n\nconst respondLayer = (policy: FailurePolicy) =>\n Layer.succeed(Respond)(((httpEffect: Effect.Effect<never, unknown, never>) =>\n respond(\n httpEffect.pipe(\n Effect.catchIf(\n (error: unknown): error is HttpApiError.HttpApiSchemaError =>\n HttpApiError.HttpApiSchemaError.is(error) &&\n REQUEST_PARTS.has(error.kind),\n error => Effect.fail(invalidRequest(error)),\n ),\n ) as never,\n policy,\n ).pipe(Effect.map(uncachedByDefault))) as never);\n\n/**\n * Every answer `no-store` unless its endpoint chose a cache policy of its own.\n * An API answer carries a principal, a token or a tenant's records far more\n * often than anything a cache could share, and a token response must not be\n * stored at all (RFC 6749 §5.1) — so the safe default is the shell's, and an\n * endpoint that wants caching (an `ETag`ed metadata document) says so.\n */\nconst uncachedByDefault = (\n response: HttpServerResponse.HttpServerResponse,\n): HttpServerResponse.HttpServerResponse =>\n response.headers['cache-control'] === undefined\n ? HttpServerResponse.setHeader(response, 'cache-control', 'no-store')\n : response;\n\nconst toEndpoint = (descriptor: AnyEndpoint, policy: FailurePolicy) => {\n const params = toSchema(descriptor.params);\n const query = toSchema(descriptor.query);\n const payload = toPayload(descriptor.payload);\n const headers = toSchema(descriptor.headers);\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- assembled at runtime\n let endpoint: any = HttpApiEndpoint.make(descriptor.method)(\n descriptor.name,\n descriptor.path,\n {\n ...(params === undefined ? {} : { params }),\n ...(query === undefined ? {} : { query }),\n ...(payload === undefined ? {} : { payload }),\n ...(headers === undefined ? {} : { headers }),\n success: descriptor.success,\n error: errorSchemas(descriptor, policy),\n } as never,\n ).annotate(EndpointGuardAnnotation, descriptor.guard);\n // Order is outermost last: idempotency runs inside the guard, so it sees\n // the principal the guard verified; `Respond` wraps everything.\n if (descriptor.idempotent !== undefined)\n endpoint = endpoint\n .annotate(EndpointIdempotencyAnnotation, descriptor.idempotent)\n .middleware(IdempotencyGuard);\n const guard = GUARD_MIDDLEWARE[descriptor.guard.kind];\n if (guard !== undefined) endpoint = endpoint.middleware(guard);\n return endpoint.middleware(Respond);\n};\n\nexport interface ApiOptions {\n /** The status and log table; the framework's defaults when absent. */\n readonly policy?: FailurePolicy;\n}\n\n/**\n * The `HttpApi` a set of groups describes. Every endpoint's failures carry the\n * status the policy gives them, and two endpoints that share a method and\n * path throw here rather than shadowing each other at runtime.\n */\nexport const buildApi = (\n name: string,\n groups: ReadonlyArray<AnyEndpointGroup>,\n options: ApiOptions = {},\n): HttpApi.Top => {\n const policy = options.policy ?? defaultFailurePolicy;\n const seen = new Set<string>();\n for (const target of endpointsOf(groups)) {\n if (seen.has(target)) throw new Error(`'${name}' declares ${target} twice`);\n seen.add(target);\n }\n // A group serves its endpoints by name, so a second one under a name would\n // silently replace the first rather than fail.\n for (const group of groups) {\n const names = new Set<string>();\n for (const { descriptor } of group.endpoints) {\n if (names.has(descriptor.name))\n throw new Error(\n `'${name}' names two endpoints '${descriptor.name}' in '${group.name}'`,\n );\n names.add(descriptor.name);\n }\n }\n return groups.reduce<HttpApi.Top>(\n (api, group) =>\n api.add(\n group.endpoints.reduce(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- assembled at runtime\n (built: any, { descriptor }) =>\n built.add(toEndpoint(descriptor, policy)),\n HttpApiGroup.make(group.name),\n ),\n ) as HttpApi.Top,\n HttpApi.make(name) as unknown as HttpApi.Top,\n );\n};\n\n/**\n * Serve `groups` under one API: the routes, every guard, the respond\n * middleware. The layer requires what the handlers, guards and idempotency\n * modes read, plus the HTTP platform the server provides.\n */\nexport const serveApi = <const Groups extends ReadonlyArray<AnyEndpointGroup>>(\n api: HttpApi.Top,\n groups: Groups,\n options: ApiOptions = {},\n): Layer.Layer<never, never, ServedRequirements<Groups> | ServedPlatform> => {\n const handlers = groups.map(group =>\n HttpApiBuilder.group(\n api as never,\n group.name as never,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- assembled at runtime\n (handle: any) =>\n group.endpoints.reduce(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (built: any, { descriptor, handler }) =>\n built.handle(descriptor.name, handler),\n handle,\n ),\n ),\n );\n return HttpApiBuilder.layer(api as never).pipe(\n Layer.provide(\n Layer.mergeAll(...(handlers as unknown as [Layer.Layer<never>])),\n ),\n Layer.provide(guardLayers),\n Layer.provide(respondLayer(options.policy ?? defaultFailurePolicy)),\n ) as never;\n};\n\n/** Build and serve in one call, for a host that needs nothing between. */\nexport const serveEndpoints = <\n const Groups extends ReadonlyArray<AnyEndpointGroup>,\n>(\n name: string,\n groups: Groups,\n options: ApiOptions = {},\n) => {\n const api = buildApi(name, groups, options);\n return { api, layer: serveApi(api, groups, options) } as const;\n};\n"],"names":["bodyEncodingOf","Contention","Forbidden","IdempotencyKeyInFlight","IdempotencyKeyMissing","IdempotencyKeyReused","Internal","Invalid","Overloaded","ProtocolFailure","Timeout","Unauthenticated","Unavailable","UpstreamUnavailable","Effect","Layer","Schema","SchemaIssue","HttpServerResponse","HttpApi","HttpApiBuilder","HttpApiEndpoint","HttpApiError","HttpApiGroup","HttpApiMiddleware","HttpApiSchema","NoActiveOrganization","defaultFailurePolicy","respond","EndpointGuardAnnotation","EndpointIdempotencyAnnotation","GUARD_MIDDLEWARE","guardLayers","IdempotencyGuard","problemCodec","endpointGroup","name","endpoints","endpointsOf","groups","flatMap","group","map","descriptor","method","path","TECHNICAL","GUARD_FAILURES","public","session","permission","organization","crossing","fleet","IDEMPOTENCY_FAILURES","statusForClass","failureClass","policy","tagStatus","identifier","categoryStatus","prototype","category","errorSchemas","Set","errors","guard","kind","idempotent","undefined","toSchema","schema","isSchema","Struct","toPayload","payload","encoding","pipe","asText","contentType","asFormUrlEncoded","Respond","Service","formatIssues","makeFormatterStandardSchemaV1","invalidRequest","error","where","toLowerCase","issues","cause","issue","pointer","String","join","detail","message","code","REQUEST_PARTS","respondLayer","succeed","httpEffect","catchIf","HttpApiSchemaError","is","has","fail","uncachedByDefault","response","headers","setHeader","toEndpoint","params","query","endpoint","make","success","annotate","middleware","buildApi","options","seen","target","Error","add","names","reduce","api","built","serveApi","handlers","handle","handler","layer","provide","mergeAll","serveEndpoints"],"mappings":";AAMA,SAEEA,cAAc,EACdC,UAAU,EAKVC,SAAS,EACTC,sBAAsB,EACtBC,qBAAqB,EACrBC,oBAAoB,EAEpBC,QAAQ,EACRC,OAAO,EACPC,UAAU,EACVC,eAAe,EACfC,OAAO,EACPC,eAAe,EACfC,WAAW,EACXC,mBAAmB,QACd,gBAAgB;AACvB,SACEC,MAAM,EAENC,KAAK,EAELC,MAAM,EACNC,WAAW,QACN,SAAS;AAEhB,SAASC,kBAAkB,QAAQ,cAAc;AACjD,SACEC,OAAO,EACPC,cAAc,EACdC,eAAe,EACfC,YAAY,EACZC,YAAY,EACZC,iBAAiB,EACjBC,aAAa,QACR,kBAAkB;AAEzB,SAASC,oBAAoB,QAAQ,sBAAsB;AAC3D,SACEC,oBAAoB,EAEpBC,OAAO,QACF,gBAAgB;AACvB,SACEC,uBAAuB,EACvBC,6BAA6B,EAC7BC,gBAAgB,EAChBC,WAAW,EAEXC,gBAAgB,QAEX,cAAc;AACrB,SAASC,YAAY,QAAQ,qBAAqB;AAsBlD,oDAAoD,GAEpD,gDAAgD,GAChD,OAAO,MAAMC,gBAAgB,CAI3BC,MACA,GAAGC,YAIC,CAAA;QACJD;QACAC,WAAWA;IACb,CAAA,EAAG;AAkCH,iFAAiF,GACjF,OAAO,MAAMC,cAAc,CACzBC,SAEAA,OAAOC,OAAO,CAACC,CAAAA,QACbA,MAAMJ,SAAS,CAACK,GAAG,CACjB,CAAC,EAAEC,UAAU,EAAE,GAAK,GAAGA,WAAWC,MAAM,CAAC,CAAC,EAAED,WAAWE,IAAI,EAAE,GAE/D;AAEJ,6EAA6E,GAC7E,MAAMC,YAAqC;IACzCvC;IACAD;IACAM;IAC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,IAAKL,YAErBnH,MAAMuH,OAAO,CAACtG,cACdjB,MAAMuH,OAAO,CAACnC,cAAaqB,kBAAAA,QAAQ/D,MAAM,YAAd+D,kBAAkB7F;AAEjD,EAAE;AAEF,wEAAwE,GACxE,OAAO,MAAM6G,iBAAiB,CAG5BpG,MACAG,QACAiF,UAAsB,CAAC,CAAC;IAExB,MAAMO,MAAMR,SAASnF,MAAMG,QAAQiF;IACnC,OAAO;QAAEO;QAAKM,OAAOJ,SAASF,KAAKxF,QAAQiF;IAAS;AACtD,EAAE"}
1
+ {"version":3,"sources":["../../src/http-api/build-api.ts"],"sourcesContent":["import type {\n IdempotencyKeyTag,\n OrganizationIdTag,\n RequestPrincipalTag,\n VerifiedContextTag,\n} from '@entifix/business';\nimport {\n type AnyEndpoint,\n bodyEncodingOf,\n Contention,\n type DeadlineTag,\n type EndpointSchema,\n type EntifixFailure,\n type FailureClass,\n Forbidden,\n IdempotencyKeyInFlight,\n IdempotencyKeyMissing,\n IdempotencyKeyReused,\n type Implemented,\n Internal,\n Invalid,\n Overloaded,\n ProtocolFailure,\n Timeout,\n Unauthenticated,\n Unavailable,\n UpstreamUnavailable,\n} from '@entifix/core';\nimport {\n Effect,\n type FileSystem,\n Layer,\n type Path,\n Schema,\n SchemaIssue,\n} from 'effect';\nimport type { Etag, HttpPlatform, HttpRouter } from 'effect/http';\nimport { HttpServerResponse } from 'effect/http';\nimport {\n HttpApi,\n HttpApiBuilder,\n HttpApiEndpoint,\n HttpApiError,\n HttpApiGroup,\n HttpApiMiddleware,\n HttpApiSchema,\n} from 'effect/http-api';\n\nimport { NoActiveOrganization } from '../auth/failures.js';\nimport {\n defaultFailurePolicy,\n type FailurePolicy,\n respond,\n} from '../respond.js';\nimport {\n EndpointGuardAnnotation,\n EndpointIdempotencyAnnotation,\n GUARD_MIDDLEWARE,\n guardLayers,\n type GuardServices,\n IdempotencyGuard,\n type IdempotencyServices,\n} from './guards.js';\nimport { problemCodec } from './problem-codec.js';\n\n/**\n * A named set of implemented endpoints — one `HttpApiGroup` once built. A slice\n * groups by entity or by concern; the name is what an OpenAPI document and a\n * client namespace it under.\n */\nexport interface EndpointGroup<\n Endpoint extends AnyEndpoint = AnyEndpoint,\n R = never,\n> {\n readonly name: string;\n readonly endpoints: ReadonlyArray<Implemented<Endpoint, R>>;\n}\n\n/** Any group, whatever its handlers need — the constraint a builder takes. */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- a constraint\nexport type AnyEndpointGroup = EndpointGroup<AnyEndpoint, any>;\n\n/* eslint-disable @typescript-eslint/no-explicit-any -- inference sites */\ntype EndpointOf<I> = I extends Implemented<infer D, any> ? D : never;\ntype RequirementsOf<I> = I extends Implemented<any, infer R> ? R : never;\n/* eslint-enable @typescript-eslint/no-explicit-any */\n\n/** Group implemented endpoints under one name. */\nexport const endpointGroup = <\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const Endpoints extends ReadonlyArray<Implemented<any, any>>,\n>(\n name: string,\n ...endpoints: Endpoints\n): EndpointGroup<\n EndpointOf<Endpoints[number]>,\n RequirementsOf<Endpoints[number]>\n> => ({\n name,\n endpoints: endpoints as never,\n});\n\n/** What the shell provides a handler: the verified request context. */\nexport type ProvidedToHandlers =\n | RequestPrincipalTag\n | OrganizationIdTag\n | IdempotencyKeyTag\n | VerifiedContextTag\n | DeadlineTag;\n\n/**\n * What serving `Groups` requires of the composition root: what the handlers\n * need beyond the request context, plus what each declared guard and\n * idempotency mode reads. A host that omits one does not compile.\n */\nexport type ServedRequirements<Groups extends ReadonlyArray<AnyEndpointGroup>> =\n GroupRequirements<Groups[number]>;\n\n// Distributive over the groups, and `never` for none.\ntype GroupRequirements<Group> =\n Group extends EndpointGroup<infer Endpoint, infer R>\n ? | Exclude<R, ProvidedToHandlers>\n | GuardServices<Endpoint['guard']['kind']>\n | IdempotencyServices<Endpoint['idempotent']>\n : never;\n\n/** What serving an API needs from the HTTP server itself. */\nexport type ServedPlatform =\n | HttpRouter.HttpRouter\n | Etag.Generator\n | FileSystem.FileSystem\n | HttpPlatform.HttpPlatform\n | Path.Path;\n\n/** `METHOD /path` for every endpoint — what a register diffs a service against. */\nexport const endpointsOf = (\n groups: ReadonlyArray<AnyEndpointGroup>,\n): readonly string[] =>\n groups.flatMap(group =>\n group.endpoints.map(\n ({ descriptor }) => `${descriptor.method} ${descriptor.path}`,\n ),\n );\n\n/** The failures every endpoint may answer, whether or not it declares them. */\nconst TECHNICAL: readonly FailureClass[] = [\n Invalid,\n Internal,\n Unavailable,\n UpstreamUnavailable,\n Timeout,\n Overloaded,\n Contention,\n ProtocolFailure,\n];\n\nconst GUARD_FAILURES: Readonly<\n Record<AnyEndpoint['guard']['kind'], readonly FailureClass[]>\n> = {\n public: [],\n session: [Unauthenticated],\n permission: [Unauthenticated, Forbidden],\n organization: [Unauthenticated, Forbidden, NoActiveOrganization],\n crossing: [Unauthenticated, Forbidden],\n fleet: [Unauthenticated],\n};\n\nconst IDEMPOTENCY_FAILURES: readonly FailureClass[] = [\n IdempotencyKeyMissing,\n IdempotencyKeyReused,\n IdempotencyKeyInFlight,\n];\n\n/** The status a failure class answers with under `policy`. */\nexport const statusForClass = (\n failureClass: FailureClass,\n policy: FailurePolicy,\n): number =>\n policy.tagStatus[failureClass.identifier] ??\n policy.categoryStatus[\n (failureClass.prototype as unknown as EntifixFailure).category\n ];\n\nconst errorSchemas = (descriptor: AnyEndpoint, policy: FailurePolicy) =>\n [\n ...new Set([\n ...descriptor.errors,\n ...GUARD_FAILURES[descriptor.guard.kind],\n ...(descriptor.idempotent === undefined ? [] : IDEMPOTENCY_FAILURES),\n ...TECHNICAL,\n ]),\n ].map(failureClass =>\n problemCodec(failureClass, statusForClass(failureClass, policy)),\n );\n\nconst toSchema = (schema: EndpointSchema | undefined) =>\n schema === undefined\n ? undefined\n : Schema.isSchema(schema)\n ? schema\n : Schema.Struct(schema);\n\n/** A payload on the wire it declared: JSON unless it said text or a form. */\nconst toPayload = (schema: EndpointSchema | undefined) => {\n const payload = toSchema(schema);\n if (payload === undefined) return undefined;\n const encoding = bodyEncodingOf(payload);\n switch (encoding?.kind) {\n case 'text':\n // A `textBody` is a string schema; the marker is what says so here.\n return (payload as Schema.String).pipe(\n HttpApiSchema.asText({ contentType: encoding.contentType }),\n );\n case 'form':\n return payload.pipe(\n HttpApiSchema.asFormUrlEncoded({ contentType: encoding.contentType }),\n );\n default:\n return payload;\n }\n};\n\n/**\n * The outermost middleware of every endpoint: `respond` under the API's\n * policy, after a schema error has become `invalid` with one entry per broken\n * field. A response that fails to encode is the service's own fault and stays\n * a defect.\n */\nexport class Respond extends HttpApiMiddleware.Service<Respond>()(\n '@entifix/service-shell/Respond',\n) {}\n\nconst formatIssues = SchemaIssue.makeFormatterStandardSchemaV1();\n\n/** The `invalid` failure a request that fails its schema answers with. */\nexport const invalidRequest = (\n error: HttpApiError.HttpApiSchemaError,\n): Invalid => {\n const where = error.kind.toLowerCase();\n const { issues } = formatIssues(error.cause.issue);\n return new Invalid({\n errors: issues.map(issue => ({\n // Effect's formatter always sets the path — `[]` for the part itself —\n // though the Standard Schema type it answers with leaves it optional.\n pointer: `/${[where, ...(issue.path as readonly PropertyKey[]).map(String)].join('/')}`,\n detail: issue.message,\n code: 'schema',\n })),\n });\n};\n\nconst REQUEST_PARTS: ReadonlySet<HttpApiError.HttpApiSchemaError['kind']> =\n new Set(['Params', 'Query', 'Payload', 'Headers']);\n\nconst respondLayer = (policy: FailurePolicy) =>\n Layer.succeed(Respond)(((httpEffect: Effect.Effect<never, unknown, never>) =>\n respond(\n httpEffect.pipe(\n Effect.catchIf(\n (error: unknown): error is HttpApiError.HttpApiSchemaError =>\n HttpApiError.HttpApiSchemaError.is(error) &&\n REQUEST_PARTS.has(error.kind),\n error => Effect.fail(invalidRequest(error)),\n ),\n ) as never,\n policy,\n ).pipe(Effect.map(uncachedByDefault))) as never);\n\n/**\n * Every answer `no-store` unless its endpoint chose a cache policy of its own.\n * An API answer carries a principal, a token or a tenant's records far more\n * often than anything a cache could share, and a token response must not be\n * stored at all (RFC 6749 §5.1) — so the safe default is the shell's, and an\n * endpoint that wants caching (an `ETag`ed metadata document) says so.\n */\nconst uncachedByDefault = (\n response: HttpServerResponse.HttpServerResponse,\n): HttpServerResponse.HttpServerResponse =>\n response.headers['cache-control'] === undefined\n ? HttpServerResponse.setHeader(response, 'cache-control', 'no-store')\n : response;\n\nconst toEndpoint = (descriptor: AnyEndpoint, policy: FailurePolicy) => {\n const params = toSchema(descriptor.params);\n const query = toSchema(descriptor.query);\n const payload = toPayload(descriptor.payload);\n const headers = toSchema(descriptor.headers);\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- assembled at runtime\n let endpoint: any = HttpApiEndpoint.make(descriptor.method)(\n descriptor.name,\n descriptor.path,\n {\n ...(params === undefined ? {} : { params }),\n ...(query === undefined ? {} : { query }),\n ...(payload === undefined ? {} : { payload }),\n ...(headers === undefined ? {} : { headers }),\n success:\n descriptor.accepted === true\n ? HttpApiSchema.status(202)(descriptor.success)\n : descriptor.success,\n error: errorSchemas(descriptor, policy),\n } as never,\n ).annotate(EndpointGuardAnnotation, descriptor.guard);\n // Order is outermost last: idempotency runs inside the guard, so it sees\n // the principal the guard verified; `Respond` wraps everything.\n if (descriptor.idempotent !== undefined)\n endpoint = endpoint\n .annotate(EndpointIdempotencyAnnotation, descriptor.idempotent)\n .middleware(IdempotencyGuard);\n const guard = GUARD_MIDDLEWARE[descriptor.guard.kind];\n if (guard !== undefined) endpoint = endpoint.middleware(guard);\n return endpoint.middleware(Respond);\n};\n\nexport interface ApiOptions {\n /** The status and log table; the framework's defaults when absent. */\n readonly policy?: FailurePolicy;\n}\n\n/**\n * The `HttpApi` a set of groups describes. Every endpoint's failures carry the\n * status the policy gives them, and two endpoints that share a method and\n * path throw here rather than shadowing each other at runtime.\n */\nexport const buildApi = (\n name: string,\n groups: ReadonlyArray<AnyEndpointGroup>,\n options: ApiOptions = {},\n): HttpApi.Top => {\n const policy = options.policy ?? defaultFailurePolicy;\n const seen = new Set<string>();\n for (const target of endpointsOf(groups)) {\n if (seen.has(target)) throw new Error(`'${name}' declares ${target} twice`);\n seen.add(target);\n }\n // A group serves its endpoints by name, so a second one under a name would\n // silently replace the first rather than fail.\n for (const group of groups) {\n const names = new Set<string>();\n for (const { descriptor } of group.endpoints) {\n if (names.has(descriptor.name))\n throw new Error(\n `'${name}' names two endpoints '${descriptor.name}' in '${group.name}'`,\n );\n names.add(descriptor.name);\n }\n }\n return groups.reduce<HttpApi.Top>(\n (api, group) =>\n api.add(\n group.endpoints.reduce(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- assembled at runtime\n (built: any, { descriptor }) =>\n built.add(toEndpoint(descriptor, policy)),\n HttpApiGroup.make(group.name),\n ),\n ) as HttpApi.Top,\n HttpApi.make(name) as unknown as HttpApi.Top,\n );\n};\n\n/**\n * Serve `groups` under one API: the routes, every guard, the respond\n * middleware. The layer requires what the handlers, guards and idempotency\n * modes read, plus the HTTP platform the server provides.\n */\nexport const serveApi = <const Groups extends ReadonlyArray<AnyEndpointGroup>>(\n api: HttpApi.Top,\n groups: Groups,\n options: ApiOptions = {},\n): Layer.Layer<never, never, ServedRequirements<Groups> | ServedPlatform> => {\n const handlers = groups.map(group =>\n HttpApiBuilder.group(\n api as never,\n group.name as never,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- assembled at runtime\n (handle: any) =>\n group.endpoints.reduce(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (built: any, { descriptor, handler }) =>\n built.handle(descriptor.name, handler),\n handle,\n ),\n ),\n );\n return HttpApiBuilder.layer(api as never).pipe(\n Layer.provide(\n Layer.mergeAll(...(handlers as unknown as [Layer.Layer<never>])),\n ),\n Layer.provide(guardLayers),\n Layer.provide(respondLayer(options.policy ?? defaultFailurePolicy)),\n ) as never;\n};\n\n/** Build and serve in one call, for a host that needs nothing between. */\nexport const serveEndpoints = <\n const Groups extends ReadonlyArray<AnyEndpointGroup>,\n>(\n name: string,\n groups: Groups,\n options: ApiOptions = {},\n) => {\n const api = buildApi(name, groups, options);\n return { api, layer: serveApi(api, groups, options) } as const;\n};\n"],"names":["bodyEncodingOf","Contention","Forbidden","IdempotencyKeyInFlight","IdempotencyKeyMissing","IdempotencyKeyReused","Internal","Invalid","Overloaded","ProtocolFailure","Timeout","Unauthenticated","Unavailable","UpstreamUnavailable","Effect","Layer","Schema","SchemaIssue","HttpServerResponse","HttpApi","HttpApiBuilder","HttpApiEndpoint","HttpApiError","HttpApiGroup","HttpApiMiddleware","HttpApiSchema","NoActiveOrganization","defaultFailurePolicy","respond","EndpointGuardAnnotation","EndpointIdempotencyAnnotation","GUARD_MIDDLEWARE","guardLayers","IdempotencyGuard","problemCodec","endpointGroup","name","endpoints","endpointsOf","groups","flatMap","group","map","descriptor","method","path","TECHNICAL","GUARD_FAILURES","public","session","permission","organization","crossing","fleet","IDEMPOTENCY_FAILURES","statusForClass","failureClass","policy","tagStatus","identifier","categoryStatus","prototype","category","errorSchemas","Set","errors","guard","kind","idempotent","undefined","toSchema","schema","isSchema","Struct","toPayload","payload","encoding","pipe","asText","contentType","asFormUrlEncoded","Respond","Service","formatIssues","makeFormatterStandardSchemaV1","invalidRequest","error","where","toLowerCase","issues","cause","issue","pointer","String","join","detail","message","code","REQUEST_PARTS","respondLayer","succeed","httpEffect","catchIf","HttpApiSchemaError","is","has","fail","uncachedByDefault","response","headers","setHeader","toEndpoint","params","query","endpoint","make","success","accepted","status","annotate","middleware","buildApi","options","seen","target","Error","add","names","reduce","api","built","serveApi","handlers","handle","handler","layer","provide","mergeAll","serveEndpoints"],"mappings":";AAMA,SAEEA,cAAc,EACdC,UAAU,EAKVC,SAAS,EACTC,sBAAsB,EACtBC,qBAAqB,EACrBC,oBAAoB,EAEpBC,QAAQ,EACRC,OAAO,EACPC,UAAU,EACVC,eAAe,EACfC,OAAO,EACPC,eAAe,EACfC,WAAW,EACXC,mBAAmB,QACd,gBAAgB;AACvB,SACEC,MAAM,EAENC,KAAK,EAELC,MAAM,EACN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,IACT,WAAW,GAAG;IAChB,QAAQ,CAAC,KAAK,EAAE,OAAO,CAAC,aAAa,EAAE;QAAE,QAAQ,CAAC,IAAI,EAAE,IAAI,CAAA;KAAE,CAAC,CAAC;IAChE,QAAQ,CAAC,UAAU,CAAC,EAAE,WAAW,CAAC;CACnC,CAAC;AAEF,yEAAyE;AACzE,MAAM,WAAW,gBAAgB;IAC/B,mEAAmE;IACnE,QAAQ,CAAC,YAAY,CAAC,EAAE,oBAAoB,CAAC;CAC9C;AAED;;;;;;;;;;;;;;;GAeG;AACH,eAAO,MAAM,SAAS,GACpB,CAAC,SAAS,MAAM,EAChB,KAAK,CAAC,CAAC,SAAS,MAAM,EAEtB,KAAK,CAAC,CAAC,SAAS,gBAAgB,CAAC,CAAC,EAAE,GAAG,CAAC,EAExC,aAAa,oBAAoB,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,EAC1C,UAAS,gBAAqB,KAC7B,aAAa,CACd,cAAc,CAAC,gBAAgB,CAAC,CAAC,CAAC,EAAE,mBAAmB,CAAC,CAAC,CAAC,CAAC,EACzD,mBAAmB,CAAC,CAAC,CAAC,GACtB,0BAA0B,GAC1B,iBAAiB,GACjB,CAAC,CAAC,CAAC,QAAQ,CAAC,SAAS,IAAI,GAAG,4BAA4B,GAAG,KAAK,CAAC,CA8gBpE,CAAC"}
@@ -486,7 +486,9 @@ const cacheHeaders = (etag)=>({
486
486
  useCase: useCase.key
487
487
  }, verb.idempotent === undefined ? {} : {
488
488
  idempotent: verb.idempotent
489
- }));
489
+ }, verb.accepted === true ? {
490
+ accepted: true
491
+ } : {}));
490
492
  return implement(descriptor, (request)=>Effect.flatMap(context, (caller)=>verb.handler(request, caller)));
491
493
  }),
492
494
  ...verbs.flatMap((verb)=>{
@@ -507,7 +509,9 @@ const cacheHeaders = (etag)=>({
507
509
  useCase: useCase.key
508
510
  }, verb.idempotent === undefined ? {} : {
509
511
  idempotent: verb.idempotent
510
- }));
512
+ }, verb.accepted === true ? {
513
+ accepted: true
514
+ } : {}));
511
515
  return [
512
516
  implement(descriptor, (request)=>Effect.flatMap(context, (caller)=>bulk(request, caller)))
513
517
  ];
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/http-api/entity-api.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\n\nimport {\n type Action,\n parsePermission,\n type Permission,\n permissionForEntity,\n permissionForUseCase,\n PolicyDecisionTag,\n} from '@entifix/authz';\nimport {\n deleteUCFactory,\n type EntityApiContext,\n type EntityApiDeclaration,\n type EntityApiGuard,\n type EntityApiLinks,\n type EntityApiOptions,\n type EntityApiRequest,\n type EntityApiVerb,\n EntityFacetCounterFactoryTag,\n EntityFacetCounterTag,\n EntityIdTag,\n EntityLoadRequestTag,\n EntityRepositoryFactoryTag,\n EntityRepositoryTag,\n EntityTag,\n facetCountsUCFactory,\n getUCFactory,\n loadUCFactory,\n type Narrowing,\n OrganizationIdTag,\n type RequestPrincipal,\n RequestPrincipalTag,\n saveUCFactory,\n type VerbEndpoint,\n VerifiedContextTag,\n} from '@entifix/business';\nimport {\n type AnyEndpoint,\n defineEndpoint,\n describeEntityUseCases,\n type EndpointGuard,\n type Entity,\n ENTITY_ACTIONS,\n type EntityConstructor,\n type EntityFacetCounts,\n type EntityFacetQuery,\n type EntityLoadRequest,\n type EntityMetadataDocument,\n Envelope,\n implement,\n type Implemented,\n InvalidQuery,\n JsonBody,\n makeEntityEnvelope,\n makeEntityFacetsEnvelope,\n makeEntityMetadataEnvelope,\n makeEntityPageEnvelope,\n NotFound,\n parseFacetQueryParams,\n parseLoadRequestParams,\n readEntityEnvelope,\n verbPath,\n} from '@entifix/core';\nimport { Effect, Option, Schema } from 'effect';\nimport { HttpServerRequest, HttpServerResponse } from 'effect/http';\n\nimport { resolveRequestPrincipal } from '../auth/require-principal.js';\nimport {\n assertCompositionsDeclared,\n compositionFor,\n type MetadataCompositions,\n} from '../metadata-composition.js';\nimport {\n narrowedByIdRequest,\n narrowingFor,\n narrowLoadRequest,\n} from '../narrowing.js';\nimport type { EndpointGroup } from './build-api.js';\n\n/** A collection verb's body: the selection, in its wire form. */\nconst SelectionBody = Schema.Struct({ selection: Schema.Unknown });\n\nconst ACTION: Record<EntityApiVerb, Action> = {\n list: 'read',\n get: 'read',\n create: 'write',\n update: 'write',\n delete: 'delete',\n};\n\nconst READS: ReadonlySet<EntityApiVerb> = new Set(['list', 'get']);\n\nconst METHOD = {\n list: 'GET',\n get: 'GET',\n create: 'POST',\n update: 'PUT',\n delete: 'DELETE',\n} as const;\n\n/** Any envelope: the entity codec reads `data`, so the wire stays open. */\nconst EnvelopeBody = Envelope.codec(Schema.Unknown);\n\nconst endpointGuardFor = (\n guard: EntityApiGuard,\n permission: () => Permission,\n): EndpointGuard => {\n switch (guard.kind) {\n case 'public':\n return { kind: 'public' };\n case 'crossing':\n return {\n kind: 'crossing',\n permission: permission(),\n organization: guard.organization,\n };\n default:\n return { kind: guard.kind, permission: permission() };\n }\n};\n\nconst endpointGuard = <T extends Entity>(\n entityConstructor: EntityConstructor<T>,\n guard: EntityApiGuard,\n action: Action,\n): EndpointGuard =>\n endpointGuardFor(guard, () => permissionForEntity(entityConstructor, action));\n\n/** The request context a guard provided, read without requiring it. */\nconst callerContext = Effect.gen(function* () {\n const organizationId = yield* Effect.serviceOption(OrganizationIdTag);\n const principal = yield* Effect.serviceOption(RequestPrincipalTag);\n const verified = yield* Effect.serviceOption(VerifiedContextTag);\n return {\n ...Option.match(organizationId, {\n onNone: () => ({}),\n onSome: value => ({ organizationId: value }),\n }),\n ...Option.match(principal, {\n onNone: () => ({}),\n onSome: value => ({ principal: value }),\n }),\n ...Option.match(verified, {\n onNone: () => ({}),\n onSome: value => ({ verified: value }),\n }),\n };\n});\n\n/** The search the request carried, for the RSQL parsers. */\nconst searchParams = Effect.map(\n HttpServerRequest.HttpServerRequest,\n request => new URL(request.url, 'http://localhost').searchParams,\n);\n\n// The RSQL parsers throw a build error naming what they refused.\nconst asInvalidQuery = (error: unknown) =>\n new InvalidQuery({ reason: (error as Error).message });\n\nconst cacheHeaders = (etag: string) => ({\n etag,\n 'cache-control': 'private, no-cache',\n vary: 'Cookie, Authorization',\n});\n\n/* eslint-disable @typescript-eslint/no-explicit-any -- type-level extraction */\ntype KindOf<G> = G extends { readonly kind: infer Kind }\n ? Kind\n : G extends { readonly read: infer Read; readonly write: infer Write }\n ? KindOf<Read> | KindOf<Write>\n : never;\n\ntype OverrideValues<O> = O extends { readonly override: infer Overrides }\n ? Overrides extends object\n ? NonNullable<Overrides[keyof Overrides]>\n : never\n : never;\n\n// Distributive over the overrides, so a group with none contributes nothing.\ntype OverrideGuardKinds<V> = V extends { readonly guard: infer G }\n ? KindOf<G>\n : never;\ntype OverrideIdempotency<V> = V extends { readonly idempotent: infer I }\n ? I\n : never;\n\ntype UseCaseValues<O> = O extends { readonly useCases: infer U }\n ? U extends ReadonlyArray<infer V>\n ? V\n : never\n : never;\n\n/** Every guard kind an entity group mounts: `$metadata` is a session. */\nexport type EntityGuardKinds<O> = Extract<\n | 'session'\n | KindOf<O extends { readonly guard: infer G } ? G : never>\n | OverrideGuardKinds<OverrideValues<O> | UseCaseValues<O>>,\n EndpointGuard['kind']\n>;\n\n/** Every idempotency mode an entity group's overrides and verbs declare. */\nexport type EntityIdempotencies<O> = OverrideIdempotency<\n OverrideValues<O> | UseCaseValues<O>\n>;\n\ntype ReturnRequirements<F> = F extends (\n ...args: any[]\n) => Effect.Effect<any, any, infer R>\n ? R\n : never;\ntype OverrideRequirements<V> = V extends { readonly handler: infer H }\n ? ReturnRequirements<H>\n : never;\n\n/** What the host's `prepare` and overrides need. */\nexport type OptionsRequirements<O> =\n | ReturnRequirements<O extends { readonly prepare: infer P } ? P : never>\n | OverrideRequirements<OverrideValues<O> | UseCaseValues<O>>;\n/* eslint-enable @typescript-eslint/no-explicit-any */\n\n/** An entity endpoint as its guard kinds and idempotency type it. */\nexport type EntityEndpoint<\n Kind extends EndpointGuard['kind'],\n Idempotency,\n> = AnyEndpoint & {\n readonly guard: Extract<EndpointGuard, { readonly kind: Kind }>;\n readonly idempotent?: Idempotency;\n};\n\n/** What the shell adds when it serves an entity's declared endpoints. */\nexport interface EntityApiServing {\n /** The compositions `$metadata` reports for the entity's verbs. */\n readonly compositions?: MetadataCompositions;\n}\n\n/**\n * The generic endpoints of an entity — list, get, create, update, delete,\n * `$metadata` and, when asked, `$facets` — as one group named for its key\n * ([ADR 0020](../../../../../docs/adr/0020-endpoints-are-descriptors-and-the-shell-builds-an-httpapi.md)).\n *\n * `$metadata` and `$facets` come before `/:id`, so neither is read as an id.\n * The list query is the entity's RSQL request, parsed against its own\n * `filterable`/`sortable` metadata: a member that is not queryable answers\n * `invalidQuery`. A narrowing is conjoined onto every read and count, never\n * substituted, and a reader it leaves with nothing gets an empty page and a\n * `404`, never a `403`.\n *\n * It serves a declaration the domain made with `defineEntityApi`; what the\n * shell alone knows — the recipes and variants `$metadata` resolves verbs\n * against — is added here.\n */\nexport const entityApi = <\n T extends Entity,\n const K extends string,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- inferred from the options\n const O extends EntityApiOptions<T, any>,\n>(\n declaration: EntityApiDeclaration<T, K, O>,\n serving: EntityApiServing = {},\n): EndpointGroup<\n EntityEndpoint<EntityGuardKinds<O>, EntityIdempotencies<O>>,\n | OptionsRequirements<O>\n | EntityRepositoryFactoryTag\n | PolicyDecisionTag\n | (O['facets'] extends true ? EntityFacetCounterFactoryTag : never)\n> => {\n const { entity: entityConstructor, key, options } = declaration;\n const base = `/api/${key}` as const;\n const record = `${base}/:id` as const;\n const mounted = new Set(options.verbs);\n const notFound = new NotFound({ entity: key });\n\n const compositions = serving.compositions ?? {};\n assertCompositionsDeclared(\n describeEntityUseCases(entityConstructor),\n compositions,\n );\n\n const verbs = options.useCases ?? [];\n // By key and binding: one key may be declared on a record and over a\n // selection, and serving one of the two must not pass for serving both.\n const unserved = describeEntityUseCases(entityConstructor)\n .filter(\n declared =>\n !verbs.some(\n verb =>\n verb.useCase.key === declared.key &&\n verb.useCase.binding === declared.binding,\n ),\n )\n .map(declared => declared.key);\n // A record-bound verb declared in a collection cell too is served there,\n // and only then: a bulk handler for a cell nobody declared is a stray.\n const inCollectionCell = (verb: VerbEndpoint<unknown>) =>\n verb.useCase.binding === 'entity' &&\n (verb.useCase.alsoAt ?? []).some(cell => cell.binding === 'collection');\n for (const verb of verbs) {\n if (inCollectionCell(verb) !== (verb.bulk !== undefined))\n throw new Error(\n `the '${key}' endpoints ` +\n (verb.bulk === undefined\n ? `serve no bulk handler for @useCase() '${verb.useCase.key}', declared in a collection cell`\n : `serve a bulk handler for @useCase() '${verb.useCase.key}', declared in no collection cell`) +\n '.',\n );\n }\n const strays = verbs.filter(\n verb => verb.useCase.entity !== entityConstructor,\n );\n if (unserved.length > 0 || strays.length > 0)\n throw new Error(\n `the '${key}' endpoints ` +\n [\n ...(unserved.length > 0\n ? [\n `serve no endpoint for @useCase() ${unserved.map(v => `'${v}'`).join(', ')}`,\n ]\n : []),\n ...(strays.length > 0\n ? [\n `serve ${strays.map(v => `'${v.useCase.key}'`).join(', ')}, declared on another entity`,\n ]\n : []),\n ].join(', and ') +\n '; a verb has exactly one endpoint, on its own entity.',\n );\n\n const linksFor = (allowed: ReadonlySet<string>): EntityApiLinks => ({\n record: id => {\n const href = `${base}/${String(id)}`;\n return [\n ...(mounted.has('get')\n ? [{ rel: 'self', href, method: 'GET' } as const]\n : []),\n ...(mounted.has('list')\n ? [{ rel: 'list', href: base, method: 'GET' } as const]\n : []),\n ...(mounted.has('update')\n ? [{ rel: 'update', href, method: 'PUT' } as const]\n : []),\n ...(mounted.has('delete')\n ? [{ rel: 'delete', href, method: 'DELETE' } as const]\n : []),\n ...verbs\n .filter(\n verb =>\n verb.useCase.binding === 'entity' &&\n allowed.has(verb.useCase.key),\n )\n .map(\n verb =>\n ({\n rel: verb.useCase.key,\n href: `${href}/${verb.useCase.key}`,\n method: 'POST',\n }) as const,\n ),\n ];\n },\n collection: () => [\n ...(mounted.has('list')\n ? [{ rel: 'self', href: base, method: 'GET' } as const]\n : []),\n ...(mounted.has('create')\n ? [{ rel: 'create', href: base, method: 'POST' } as const]\n : []),\n ...verbs\n .filter(\n verb =>\n (verb.useCase.binding !== 'entity' || verb.bulk !== undefined) &&\n allowed.has(verb.useCase.key),\n )\n .map(\n verb =>\n ({\n rel: verb.useCase.key,\n href: `${base}/${verb.useCase.key}`,\n method: 'POST',\n }) as const,\n ),\n ],\n });\n\n const guardFor = (verb: EntityApiVerb): EntityApiGuard => {\n const declared = options.override?.[verb]?.guard;\n if (declared !== undefined) return declared;\n const { guard } = options;\n return 'kind' in guard ? guard : READS.has(verb) ? guard.read : guard.write;\n };\n\n const verbGuard = (verb: VerbEndpoint<unknown>): EntityApiGuard =>\n verb.guard ?? guardFor('create');\n\n /**\n * The verbs this caller would be let through: a public verb for anybody, a\n * session verb for a principal the policy permits. A crossing verb is never\n * linked — no browser holds the token that reaches it.\n */\n const allowedVerbs = (principal: RequestPrincipal | undefined) =>\n Effect.gen(function* () {\n const policy = yield* PolicyDecisionTag;\n const allowed = new Set<string>();\n for (const verb of verbs) {\n const kind = verbGuard(verb).kind;\n if (kind === 'public') allowed.add(verb.useCase.key);\n else if (kind !== 'crossing' && principal !== undefined) {\n const { resource, action } = parsePermission(\n permissionForUseCase(entityConstructor, verb.useCase.key),\n );\n if (\n policy.decide({\n subject: { roles: principal.roles },\n resource,\n action,\n })\n )\n allowed.add(verb.useCase.key);\n }\n }\n return allowed;\n });\n\n const context = Effect.gen(function* () {\n const caller = yield* callerContext;\n // A public read verifies no session, but a signed-in caller reading it\n // still sees the verbs they may run: the links read the session, if any,\n // and never decide anything by it.\n const principal =\n caller.principal ?? Option.getOrUndefined(yield* resolveRequestPrincipal);\n const allowed = yield* allowedVerbs(principal);\n return { ...caller, links: linksFor(allowed) } as EntityApiContext;\n });\n\n const repository = (caller: EntityApiContext) =>\n Effect.flatMap(EntityRepositoryFactoryTag, factory =>\n factory.for(entityConstructor, {\n ...(caller.organizationId === undefined\n ? {}\n : { organizationId: caller.organizationId }),\n }),\n );\n\n const narrowingOf = (caller: EntityApiContext): Narrowing<T> | undefined =>\n options.narrowing === undefined || caller.verified === undefined\n ? undefined\n : narrowingFor(options.narrowing, caller.verified);\n\n const list = Effect.gen(function* () {\n const caller = yield* context;\n const search = yield* searchParams;\n const parsed = yield* Effect.try({\n try: () =>\n parseLoadRequestParams(\n entityConstructor,\n search,\n ) as unknown as EntityLoadRequest<T>,\n catch: asInvalidQuery,\n });\n const narrowing = narrowingOf(caller);\n // Still parsed: whether a query is well-formed must not depend on who\n // asked. `nothing` answers here without a query.\n if (narrowing === 'nothing')\n return makeEntityPageEnvelope(\n entityConstructor,\n { items: [], total: 0, request: parsed },\n caller.links.collection(),\n );\n const request =\n narrowing === undefined || narrowing === 'unscoped'\n ? parsed\n : narrowLoadRequest(parsed, narrowing);\n const page = yield* loadUCFactory<T>().pipe(\n Effect.provideService(EntityRepositoryTag, yield* repository(caller)),\n Effect.provideService(\n EntityLoadRequestTag,\n request as unknown as EntityLoadRequest,\n ),\n );\n return makeEntityPageEnvelope(\n entityConstructor,\n page,\n caller.links.collection(),\n );\n });\n\n const get = (id: string) =>\n Effect.gen(function* () {\n const caller = yield* context;\n const narrowing = narrowingOf(caller);\n if (narrowing === 'nothing') return yield* Effect.fail(notFound);\n // A filter narrowing reads by id as a narrowed load, so the read and the\n // list apply one rule.\n if (narrowing !== undefined && narrowing !== 'unscoped') {\n const page = yield* loadUCFactory<T>().pipe(\n Effect.provideService(EntityRepositoryTag, yield* repository(caller)),\n Effect.provideService(\n EntityLoadRequestTag,\n narrowedByIdRequest<T>(\n narrowing,\n id,\n ) as unknown as EntityLoadRequest,\n ),\n );\n const [only] = page.items;\n if (only === undefined) return yield* Effect.fail(notFound);\n return makeEntityEnvelope(\n entityConstructor,\n only,\n caller.links.record(id),\n );\n }\n const found = yield* getUCFactory<T>().pipe(\n Effect.provideService(EntityRepositoryTag, yield* repository(caller)),\n Effect.provideService(EntityIdTag, id),\n );\n return makeEntityEnvelope(\n entityConstructor,\n found,\n caller.links.record(id),\n );\n });\n\n const save = (verb: 'create' | 'update', body: unknown, id?: string) =>\n Effect.gen(function* () {\n const caller = yield* context;\n let entity = yield* readEntityEnvelope(entityConstructor, body);\n // On update the path is authoritative, so a record cannot be renamed\n // onto another one by editing its payload.\n if (id !== undefined) entity.id = id;\n if (options.prepare !== undefined)\n entity = yield* options.prepare(entity, { ...caller, verb });\n const saved = yield* saveUCFactory<T>().pipe(\n Effect.provideService(EntityRepositoryTag, yield* repository(caller)),\n Effect.provideService(EntityTag, entity),\n );\n return makeEntityEnvelope(\n entityConstructor,\n saved,\n caller.links.record(saved.id),\n );\n });\n\n const remove = (id: string) =>\n Effect.gen(function* () {\n const caller = yield* context;\n yield* deleteUCFactory<T>().pipe(\n Effect.provideService(EntityRepositoryTag, yield* repository(caller)),\n Effect.provideService(EntityIdTag, id),\n );\n // An envelope rather than a bare `204`: every message between entifix\n // artifacts is one.\n return {\n meta: { type: 'entity', entity: key, links: caller.links.collection() },\n data: { id },\n };\n });\n\n const metadata = Effect.gen(function* () {\n const principal = yield* RequestPrincipalTag;\n const verified = yield* VerifiedContextTag;\n const policy = yield* PolicyDecisionTag;\n const allows = (permission: Permission): boolean => {\n const { resource, action } = parsePermission(permission);\n return policy.decide({\n subject: { roles: principal.roles },\n resource,\n action,\n });\n };\n // SECURITY BOUNDARY. The document is a map of the model, so an entity the\n // caller may not read answers exactly as one this service does not host:\n // a `403` would make the endpoint an oracle.\n if (!allows(permissionForEntity(entityConstructor, 'read')))\n return yield* Effect.fail(notFound);\n\n const document: EntityMetadataDocument = {\n actions: ENTITY_ACTIONS.filter(action =>\n allows(permissionForEntity(entityConstructor, action)),\n ),\n useCases: describeEntityUseCases(entityConstructor)\n .filter(descriptor =>\n allows(permissionForUseCase(entityConstructor, descriptor.key)),\n )\n // A verb the caller resolves to nothing is omitted, like one they may\n // not invoke; the rest carry what they resolve to.\n .flatMap(descriptor => {\n const composition = compositionFor(\n descriptor,\n verified,\n compositions,\n );\n if (composition === 'unreachable') return [];\n return composition === undefined\n ? [descriptor]\n : [{ ...descriptor, composition }];\n }),\n };\n\n // The ETag hashes the computed document, not the model: two principals\n // with different grants get different documents from one model.\n const body = JSON.stringify(\n makeEntityMetadataEnvelope(entityConstructor, document),\n );\n const etag = `\"${createHash('sha256').update(body).digest('hex')}\"`;\n const request = yield* HttpServerRequest.HttpServerRequest;\n if (request.headers['if-none-match'] === etag)\n return HttpServerResponse.empty({ status: 304 }).pipe(\n HttpServerResponse.setHeaders(cacheHeaders(etag)),\n );\n return HttpServerResponse.text(body, {\n contentType: 'application/json',\n headers: cacheHeaders(etag),\n });\n });\n\n const facets = Effect.gen(function* () {\n const caller = yield* context;\n const search = yield* searchParams;\n const queries = yield* Effect.try({\n try: () => parseFacetQueryParams(entityConstructor, search),\n catch: asInvalidQuery,\n });\n const narrowing = narrowingOf(caller) ?? 'unscoped';\n if (narrowing === 'nothing') {\n const empty: EntityFacetCounts = Object.fromEntries(\n queries.map(({ member }) => [member, []]),\n );\n return makeEntityFacetsEnvelope(entityConstructor, empty);\n }\n const narrowed: EntityFacetQuery<T>[] =\n narrowing === 'unscoped'\n ? queries\n : queries.map(query => ({\n ...query,\n filtering: [...(query.filtering ?? []), narrowing],\n }));\n const factory = yield* EntityFacetCounterFactoryTag;\n const counter = yield* factory.for(entityConstructor, {\n ...(caller.organizationId === undefined\n ? {}\n : { organizationId: caller.organizationId }),\n });\n const counts = yield* facetCountsUCFactory<T>(narrowed).pipe(\n Effect.provideService(EntityFacetCounterTag, counter),\n );\n return makeEntityFacetsEnvelope(entityConstructor, counts);\n });\n\n const crudEndpoint = (verb: EntityApiVerb): Implemented => {\n const override = options.override?.[verb];\n const withId = verb !== 'list' && verb !== 'create';\n const takesBody = verb === 'create' || verb === 'update';\n const payload = takesBody\n ? (override?.payload ?? EnvelopeBody)\n : override?.payload;\n const descriptor = defineEndpoint({\n name: verb,\n method: METHOD[verb],\n path: withId ? record : base,\n ...(withId ? { params: { id: Schema.String } } : {}),\n ...(payload === undefined ? {} : { payload }),\n success: JsonBody,\n errors: [\n ...(verb === 'get' || verb === 'update' || verb === 'delete'\n ? [NotFound]\n : []),\n ...(verb === 'list' ? [InvalidQuery] : []),\n ...(takesBody ? (options.errors ?? []) : []),\n ...(override?.errors ?? []),\n ],\n guard: endpointGuard(entityConstructor, guardFor(verb), ACTION[verb]),\n ...(override?.idempotent === undefined\n ? {}\n : { idempotent: override.idempotent }),\n } as AnyEndpoint);\n\n return implement(descriptor, ((request: EntityApiRequest) => {\n if (override !== undefined)\n return Effect.flatMap(context, caller =>\n override.handler(request, caller),\n );\n const id = request.params?.id as string;\n switch (verb) {\n case 'list':\n return list;\n case 'get':\n return get(id);\n case 'create':\n return save('create', request.payload);\n case 'update':\n return save('update', request.payload, id);\n case 'delete':\n return remove(id);\n }\n }) as never) as Implemented;\n };\n\n const readGuard = guardFor('list');\n const endpoints: Implemented[] = [\n // Registered first, so neither is captured by `/:id`.\n implement(\n defineEndpoint({\n name: 'metadata',\n method: 'GET',\n path: `${base}/$metadata`,\n success: JsonBody,\n errors: [NotFound],\n guard: { kind: 'session' },\n }) as AnyEndpoint,\n (() => metadata) as never,\n ),\n ...(options.facets === true\n ? [\n implement(\n defineEndpoint({\n name: 'facets',\n method: 'GET',\n path: `${base}/$facets`,\n success: JsonBody,\n errors: [InvalidQuery],\n guard: endpointGuard(entityConstructor, readGuard, 'read'),\n }) as AnyEndpoint,\n (() => facets) as never,\n ),\n ]\n : []),\n ...options.verbs.map(crudEndpoint),\n ...verbs.map(verb => {\n const { useCase } = verb;\n const payload =\n useCase.payload ??\n (useCase.binding === 'collection' ? SelectionBody : undefined);\n const descriptor = defineEndpoint({\n // One key may be served both ways — `publish` on a record and over a\n // selection — under one permission, so a name carries the binding\n // whenever it is not the record's.\n name:\n useCase.binding === 'entity'\n ? useCase.key\n : `${useCase.key}-${useCase.binding}`,\n method: 'POST',\n path: verbPath(key, useCase.key, useCase.binding),\n ...(useCase.binding === 'entity'\n ? { params: { id: Schema.String } }\n : {}),\n ...(payload === undefined ? {} : { payload }),\n success: useCase.success ?? JsonBody,\n errors: [...(useCase.errors ?? [])],\n guard: endpointGuardFor(verbGuard(verb), () =>\n permissionForUseCase(entityConstructor, useCase.key),\n ),\n useCase: useCase.key,\n ...(verb.idempotent === undefined\n ? {}\n : { idempotent: verb.idempotent }),\n } as AnyEndpoint);\n return implement(descriptor, ((request: EntityApiRequest) =>\n Effect.flatMap(context, caller =>\n verb.handler(request, caller),\n )) as never) as Implemented;\n }),\n ...verbs.flatMap(verb => {\n const { bulk } = verb;\n if (bulk === undefined) return [];\n const { useCase } = verb;\n const descriptor = defineEndpoint({\n name: `${useCase.key}-collection`,\n method: 'POST',\n path: verbPath(key, useCase.key, 'collection'),\n payload: SelectionBody,\n success: JsonBody,\n errors: [...(useCase.errors ?? [])],\n guard: endpointGuardFor(verbGuard(verb), () =>\n permissionForUseCase(entityConstructor, useCase.key),\n ),\n useCase: useCase.key,\n ...(verb.idempotent === undefined\n ? {}\n : { idempotent: verb.idempotent }),\n } as AnyEndpoint);\n return [\n implement(descriptor, ((request: EntityApiRequest) =>\n Effect.flatMap(context, caller => bulk(request, caller))) as never),\n ] as Implemented[];\n }),\n ];\n\n return { name: key, endpoints } as never;\n};\n"],"names":["createHash","parsePermission","permissionForEntity","permissionForUseCase","PolicyDecisionTag","deleteUCFactory","EntityFacetCounterFactoryTag","EntityFacetCounterTag","EntityIdTag","EntityLoadRequestTag","EntityRepositoryFactoryTag","EntityRepositoryTag","EntityTag","facetCountsUCFactory","getUCFactory","loadUCFactory","OrganizationIdTag","RequestPrincipalTag","saveUCFactory","VerifiedContextTag","defineEndpoint","describeEntityUseCases","ENTITY_ACTIONS","Envelope","implement","InvalidQuery","JsonBody","makeEntityEnvelope","makeEntityFacetsEnvelope","makeEntityMetadataEnvelope","makeEntityPageEnvelope","NotFound","parseFacetQueryParams","parseLoadRequestParams","readEntityEnvelope","verbPath","Effect","Option","Schema","HttpServerRequest","HttpServerResponse","resolveRequestPrincipal","assertCompositionsDeclared","compositionFor","narrowedByIdRequest","narrowingFor","narrowLoadRequest","SelectionBody","Struct","selection","Unknown","ACTION","list","get","create","update","delete","READS","Set","METHOD","EnvelopeBody","codec","endpointGuardFor","guard","permission","kind","organization","endpointGuard","entityConstructor","action","callerContext","gen","organizationId","serviceOption","principal","verified","match","onNone","onSome","value","searchParams","map","request","URL","url","asInvalidQuery","error","reason","message","cacheHeaders","etag","vary","entityApi","declaration","serving","options","entity","key","base","record","mounted","verbs","notFound","compositions","useCases","unserved","filter","declared","some","verb","useCase","binding","inCollectionCell","alsoAt","cell","bulk","undefined","Error","strays","length","v","join","linksFor","allowed","id","href","String","has","rel","method","collection","guardFor","override","read","write","verbGuard","allowedVerbs","policy","add","resource","decide","subject","roles","context","caller","getOrUndefined","links","repository","flatMap","factory","for","narrowingOf","narrowing","search","parsed","try","catch","items","total","page","pipe","provideService","fail","only","found","save","body","prepare","saved","remove","meta","type","data","metadata","allows","document","actions","descriptor","composition","JSON","stringify","digest","headers","empty","status","setHeaders","text","contentType","facets","queries","Object","fromEntries","member","narrowed","query","filtering","counter","counts","crudEndpoint","withId","takesBody","payload","name","path","params","success","errors","idempotent","handler","readGuard","endpoints"],"mappings":";AAAA,SAASA,UAAU,QAAQ,cAAc;AAEzC,SAEEC,eAAe,EAEfC,mBAAmB,EACnBC,oBAAoB,EACpBC,iBAAiB,QACZ,iBAAiB;AACxB,SACEC,eAAe,EAQfC,4BAA4B,EAC5BC,qBAAqB,EACrBC,WAAW,EACXC,oBAAoB,EACpBC,0BAA0B,EAC1BC,mBAAmB,EACnBC,SAAS,EACTC,oBAAoB,EACpBC,YAAY,EACZC,aAAa,EAEbC,iBAAiB,EAEjBC,mBAAmB,EACnBC,aAAa,EAEbC,kBAAkB,QACb,oBAAoB;AAC3B,SAEEC,cAAc,EACdC,sBAAsB,EAGtBC,cAAc,EAMdC,QAAQ,EACRC,SAAS,EAET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OAAOD,iBAAiByE,UAAU1B,OAAO,IACvC1G,qBAAqBiE,mBAAmB0C,QAAQb,GAAG;gBAErDa,SAASA,QAAQb,GAAG;eAChBY,KAAKkG,UAAU,KAAK3F,YACpB,CAAC,IACD;gBAAE2F,YAAYlG,KAAKkG,UAAU;YAAC;YAEpC,OAAO;gBACLvL,UAAUyJ,YAAa,CAAC/F,UACtB9C,OAAOgH,OAAO,CAACL,SAASC,CAAAA,SAAU7B,KAAKjC,SAAS8D;aACnD;QACH;KACD;IAED,OAAO;QAAE0D,MAAMzG;QAAKiH;IAAU;AAChC,EAAE"}
1
+ {"version":3,"sources":["../../src/http-api/entity-api.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\n\nimport {\n type Action,\n parsePermission,\n type Permission,\n permissionForEntity,\n permissionForUseCase,\n PolicyDecisionTag,\n} from '@entifix/authz';\nimport {\n deleteUCFactory,\n type EntityApiContext,\n type EntityApiDeclaration,\n type EntityApiGuard,\n type EntityApiLinks,\n type EntityApiOptions,\n type EntityApiRequest,\n type EntityApiVerb,\n EntityFacetCounterFactoryTag,\n EntityFacetCounterTag,\n EntityIdTag,\n EntityLoadRequestTag,\n EntityRepositoryFactoryTag,\n EntityRepositoryTag,\n EntityTag,\n facetCountsUCFactory,\n getUCFactory,\n loadUCFactory,\n type Narrowing,\n OrganizationIdTag,\n type RequestPrincipal,\n RequestPrincipalTag,\n saveUCFactory,\n type VerbEndpoint,\n VerifiedContextTag,\n} from '@entifix/business';\nimport {\n type AnyEndpoint,\n defineEndpoint,\n describeEntityUseCases,\n type EndpointGuard,\n type Entity,\n ENTITY_ACTIONS,\n type EntityConstructor,\n type EntityFacetCounts,\n type EntityFacetQuery,\n type EntityLoadRequest,\n type EntityMetadataDocument,\n Envelope,\n implement,\n type Implemented,\n InvalidQuery,\n JsonBody,\n makeEntityEnvelope,\n makeEntityFacetsEnvelope,\n makeEntityMetadataEnvelope,\n makeEntityPageEnvelope,\n NotFound,\n parseFacetQueryParams,\n parseLoadRequestParams,\n readEntityEnvelope,\n verbPath,\n} from '@entifix/core';\nimport { Effect, Option, Schema } from 'effect';\nimport { HttpServerRequest, HttpServerResponse } from 'effect/http';\n\nimport { resolveRequestPrincipal } from '../auth/require-principal.js';\nimport {\n assertCompositionsDeclared,\n compositionFor,\n type MetadataCompositions,\n} from '../metadata-composition.js';\nimport {\n narrowedByIdRequest,\n narrowingFor,\n narrowLoadRequest,\n} from '../narrowing.js';\nimport type { EndpointGroup } from './build-api.js';\n\n/** A collection verb's body: the selection, in its wire form. */\nconst SelectionBody = Schema.Struct({ selection: Schema.Unknown });\n\nconst ACTION: Record<EntityApiVerb, Action> = {\n list: 'read',\n get: 'read',\n create: 'write',\n update: 'write',\n delete: 'delete',\n};\n\nconst READS: ReadonlySet<EntityApiVerb> = new Set(['list', 'get']);\n\nconst METHOD = {\n list: 'GET',\n get: 'GET',\n create: 'POST',\n update: 'PUT',\n delete: 'DELETE',\n} as const;\n\n/** Any envelope: the entity codec reads `data`, so the wire stays open. */\nconst EnvelopeBody = Envelope.codec(Schema.Unknown);\n\nconst endpointGuardFor = (\n guard: EntityApiGuard,\n permission: () => Permission,\n): EndpointGuard => {\n switch (guard.kind) {\n case 'public':\n return { kind: 'public' };\n case 'crossing':\n return {\n kind: 'crossing',\n permission: permission(),\n organization: guard.organization,\n };\n default:\n return { kind: guard.kind, permission: permission() };\n }\n};\n\nconst endpointGuard = <T extends Entity>(\n entityConstructor: EntityConstructor<T>,\n guard: EntityApiGuard,\n action: Action,\n): EndpointGuard =>\n endpointGuardFor(guard, () => permissionForEntity(entityConstructor, action));\n\n/** The request context a guard provided, read without requiring it. */\nconst callerContext = Effect.gen(function* () {\n const organizationId = yield* Effect.serviceOption(OrganizationIdTag);\n const principal = yield* Effect.serviceOption(RequestPrincipalTag);\n const verified = yield* Effect.serviceOption(VerifiedContextTag);\n return {\n ...Option.match(organizationId, {\n onNone: () => ({}),\n onSome: value => ({ organizationId: value }),\n }),\n ...Option.match(principal, {\n onNone: () => ({}),\n onSome: value => ({ principal: value }),\n }),\n ...Option.match(verified, {\n onNone: () => ({}),\n onSome: value => ({ verified: value }),\n }),\n };\n});\n\n/** The search the request carried, for the RSQL parsers. */\nconst searchParams = Effect.map(\n HttpServerRequest.HttpServerRequest,\n request => new URL(request.url, 'http://localhost').searchParams,\n);\n\n// The RSQL parsers throw a build error naming what they refused.\nconst asInvalidQuery = (error: unknown) =>\n new InvalidQuery({ reason: (error as Error).message });\n\nconst cacheHeaders = (etag: string) => ({\n etag,\n 'cache-control': 'private, no-cache',\n vary: 'Cookie, Authorization',\n});\n\n/* eslint-disable @typescript-eslint/no-explicit-any -- type-level extraction */\ntype KindOf<G> = G extends { readonly kind: infer Kind }\n ? Kind\n : G extends { readonly read: infer Read; readonly write: infer Write }\n ? KindOf<Read> | KindOf<Write>\n : never;\n\ntype OverrideValues<O> = O extends { readonly override: infer Overrides }\n ? Overrides extends object\n ? NonNullable<Overrides[keyof Overrides]>\n : never\n : never;\n\n// Distributive over the overrides, so a group with none contributes nothing.\ntype OverrideGuardKinds<V> = V extends { readonly guard: infer G }\n ? KindOf<G>\n : never;\ntype OverrideIdempotency<V> = V extends { readonly idempotent: infer I }\n ? I\n : never;\n\ntype UseCaseValues<O> = O extends { readonly useCases: infer U }\n ? U extends ReadonlyArray<infer V>\n ? V\n : never\n : never;\n\n/** Every guard kind an entity group mounts: `$metadata` is a session. */\nexport type EntityGuardKinds<O> = Extract<\n | 'session'\n | KindOf<O extends { readonly guard: infer G } ? G : never>\n | OverrideGuardKinds<OverrideValues<O> | UseCaseValues<O>>,\n EndpointGuard['kind']\n>;\n\n/** Every idempotency mode an entity group's overrides and verbs declare. */\nexport type EntityIdempotencies<O> = OverrideIdempotency<\n OverrideValues<O> | UseCaseValues<O>\n>;\n\ntype ReturnRequirements<F> = F extends (\n ...args: any[]\n) => Effect.Effect<any, any, infer R>\n ? R\n : never;\ntype OverrideRequirements<V> = V extends { readonly handler: infer H }\n ? ReturnRequirements<H>\n : never;\n\n/** What the host's `prepare` and overrides need. */\nexport type OptionsRequirements<O> =\n | ReturnRequirements<O extends { readonly prepare: infer P } ? P : never>\n | OverrideRequirements<OverrideValues<O> | UseCaseValues<O>>;\n/* eslint-enable @typescript-eslint/no-explicit-any */\n\n/** An entity endpoint as its guard kinds and idempotency type it. */\nexport type EntityEndpoint<\n Kind extends EndpointGuard['kind'],\n Idempotency,\n> = AnyEndpoint & {\n readonly guard: Extract<EndpointGuard, { readonly kind: Kind }>;\n readonly idempotent?: Idempotency;\n};\n\n/** What the shell adds when it serves an entity's declared endpoints. */\nexport interface EntityApiServing {\n /** The compositions `$metadata` reports for the entity's verbs. */\n readonly compositions?: MetadataCompositions;\n}\n\n/**\n * The generic endpoints of an entity — list, get, create, update, delete,\n * `$metadata` and, when asked, `$facets` — as one group named for its key\n * ([ADR 0020](../../../../../docs/adr/0020-endpoints-are-descriptors-and-the-shell-builds-an-httpapi.md)).\n *\n * `$metadata` and `$facets` come before `/:id`, so neither is read as an id.\n * The list query is the entity's RSQL request, parsed against its own\n * `filterable`/`sortable` metadata: a member that is not queryable answers\n * `invalidQuery`. A narrowing is conjoined onto every read and count, never\n * substituted, and a reader it leaves with nothing gets an empty page and a\n * `404`, never a `403`.\n *\n * It serves a declaration the domain made with `defineEntityApi`; what the\n * shell alone knows — the recipes and variants `$metadata` resolves verbs\n * against — is added here.\n */\nexport const entityApi = <\n T extends Entity,\n const K extends string,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- inferred from the options\n const O extends EntityApiOptions<T, any>,\n>(\n declaration: EntityApiDeclaration<T, K, O>,\n serving: EntityApiServing = {},\n): EndpointGroup<\n EntityEndpoint<EntityGuardKinds<O>, EntityIdempotencies<O>>,\n | OptionsRequirements<O>\n | EntityRepositoryFactoryTag\n | PolicyDecisionTag\n | (O['facets'] extends true ? EntityFacetCounterFactoryTag : never)\n> => {\n const { entity: entityConstructor, key, options } = declaration;\n const base = `/api/${key}` as const;\n const record = `${base}/:id` as const;\n const mounted = new Set(options.verbs);\n const notFound = new NotFound({ entity: key });\n\n const compositions = serving.compositions ?? {};\n assertCompositionsDeclared(\n describeEntityUseCases(entityConstructor),\n compositions,\n );\n\n const verbs = options.useCases ?? [];\n // By key and binding: one key may be declared on a record and over a\n // selection, and serving one of the two must not pass for serving both.\n const unserved = describeEntityUseCases(entityConstructor)\n .filter(\n declared =>\n !verbs.some(\n verb =>\n verb.useCase.key === declared.key &&\n verb.useCase.binding === declared.binding,\n ),\n )\n .map(declared => declared.key);\n // A record-bound verb declared in a collection cell too is served there,\n // and only then: a bulk handler for a cell nobody declared is a stray.\n const inCollectionCell = (verb: VerbEndpoint<unknown>) =>\n verb.useCase.binding === 'entity' &&\n (verb.useCase.alsoAt ?? []).some(cell => cell.binding === 'collection');\n for (const verb of verbs) {\n if (inCollectionCell(verb) !== (verb.bulk !== undefined))\n throw new Error(\n `the '${key}' endpoints ` +\n (verb.bulk === undefined\n ? `serve no bulk handler for @useCase() '${verb.useCase.key}', declared in a collection cell`\n : `serve a bulk handler for @useCase() '${verb.useCase.key}', declared in no collection cell`) +\n '.',\n );\n }\n const strays = verbs.filter(\n verb => verb.useCase.entity !== entityConstructor,\n );\n if (unserved.length > 0 || strays.length > 0)\n throw new Error(\n `the '${key}' endpoints ` +\n [\n ...(unserved.length > 0\n ? [\n `serve no endpoint for @useCase() ${unserved.map(v => `'${v}'`).join(', ')}`,\n ]\n : []),\n ...(strays.length > 0\n ? [\n `serve ${strays.map(v => `'${v.useCase.key}'`).join(', ')}, declared on another entity`,\n ]\n : []),\n ].join(', and ') +\n '; a verb has exactly one endpoint, on its own entity.',\n );\n\n const linksFor = (allowed: ReadonlySet<string>): EntityApiLinks => ({\n record: id => {\n const href = `${base}/${String(id)}`;\n return [\n ...(mounted.has('get')\n ? [{ rel: 'self', href, method: 'GET' } as const]\n : []),\n ...(mounted.has('list')\n ? [{ rel: 'list', href: base, method: 'GET' } as const]\n : []),\n ...(mounted.has('update')\n ? [{ rel: 'update', href, method: 'PUT' } as const]\n : []),\n ...(mounted.has('delete')\n ? [{ rel: 'delete', href, method: 'DELETE' } as const]\n : []),\n ...verbs\n .filter(\n verb =>\n verb.useCase.binding === 'entity' &&\n allowed.has(verb.useCase.key),\n )\n .map(\n verb =>\n ({\n rel: verb.useCase.key,\n href: `${href}/${verb.useCase.key}`,\n method: 'POST',\n }) as const,\n ),\n ];\n },\n collection: () => [\n ...(mounted.has('list')\n ? [{ rel: 'self', href: base, method: 'GET' } as const]\n : []),\n ...(mounted.has('create')\n ? [{ rel: 'create', href: base, method: 'POST' } as const]\n : []),\n ...verbs\n .filter(\n verb =>\n (verb.useCase.binding !== 'entity' || verb.bulk !== undefined) &&\n allowed.has(verb.useCase.key),\n )\n .map(\n verb =>\n ({\n rel: verb.useCase.key,\n href: `${base}/${verb.useCase.key}`,\n method: 'POST',\n }) as const,\n ),\n ],\n });\n\n const guardFor = (verb: EntityApiVerb): EntityApiGuard => {\n const declared = options.override?.[verb]?.guard;\n if (declared !== undefined) return declared;\n const { guard } = options;\n return 'kind' in guard ? guard : READS.has(verb) ? guard.read : guard.write;\n };\n\n const verbGuard = (verb: VerbEndpoint<unknown>): EntityApiGuard =>\n verb.guard ?? guardFor('create');\n\n /**\n * The verbs this caller would be let through: a public verb for anybody, a\n * session verb for a principal the policy permits. A crossing verb is never\n * linked — no browser holds the token that reaches it.\n */\n const allowedVerbs = (principal: RequestPrincipal | undefined) =>\n Effect.gen(function* () {\n const policy = yield* PolicyDecisionTag;\n const allowed = new Set<string>();\n for (const verb of verbs) {\n const kind = verbGuard(verb).kind;\n if (kind === 'public') allowed.add(verb.useCase.key);\n else if (kind !== 'crossing' && principal !== undefined) {\n const { resource, action } = parsePermission(\n permissionForUseCase(entityConstructor, verb.useCase.key),\n );\n if (\n policy.decide({\n subject: { roles: principal.roles },\n resource,\n action,\n })\n )\n allowed.add(verb.useCase.key);\n }\n }\n return allowed;\n });\n\n const context = Effect.gen(function* () {\n const caller = yield* callerContext;\n // A public read verifies no session, but a signed-in caller reading it\n // still sees the verbs they may run: the links read the session, if any,\n // and never decide anything by it.\n const principal =\n caller.principal ?? Option.getOrUndefined(yield* resolveRequestPrincipal);\n const allowed = yield* allowedVerbs(principal);\n return { ...caller, links: linksFor(allowed) } as EntityApiContext;\n });\n\n const repository = (caller: EntityApiContext) =>\n Effect.flatMap(EntityRepositoryFactoryTag, factory =>\n factory.for(entityConstructor, {\n ...(caller.organizationId === undefined\n ? {}\n : { organizationId: caller.organizationId }),\n }),\n );\n\n const narrowingOf = (caller: EntityApiContext): Narrowing<T> | undefined =>\n options.narrowing === undefined || caller.verified === undefined\n ? undefined\n : narrowingFor(options.narrowing, caller.verified);\n\n const list = Effect.gen(function* () {\n const caller = yield* context;\n const search = yield* searchParams;\n const parsed = yield* Effect.try({\n try: () =>\n parseLoadRequestParams(\n entityConstructor,\n search,\n ) as unknown as EntityLoadRequest<T>,\n catch: asInvalidQuery,\n });\n const narrowing = narrowingOf(caller);\n // Still parsed: whether a query is well-formed must not depend on who\n // asked. `nothing` answers here without a query.\n if (narrowing === 'nothing')\n return makeEntityPageEnvelope(\n entityConstructor,\n { items: [], total: 0, request: parsed },\n caller.links.collection(),\n );\n const request =\n narrowing === undefined || narrowing === 'unscoped'\n ? parsed\n : narrowLoadRequest(parsed, narrowing);\n const page = yield* loadUCFactory<T>().pipe(\n Effect.provideService(EntityRepositoryTag, yield* repository(caller)),\n Effect.provideService(\n EntityLoadRequestTag,\n request as unknown as EntityLoadRequest,\n ),\n );\n return makeEntityPageEnvelope(\n entityConstructor,\n page,\n caller.links.collection(),\n );\n });\n\n const get = (id: string) =>\n Effect.gen(function* () {\n const caller = yield* context;\n const narrowing = narrowingOf(caller);\n if (narrowing === 'nothing') return yield* Effect.fail(notFound);\n // A filter narrowing reads by id as a narrowed load, so the read and the\n // list apply one rule.\n if (narrowing !== undefined && narrowing !== 'unscoped') {\n const page = yield* loadUCFactory<T>().pipe(\n Effect.provideService(EntityRepositoryTag, yield* repository(caller)),\n Effect.provideService(\n EntityLoadRequestTag,\n narrowedByIdRequest<T>(\n narrowing,\n id,\n ) as unknown as EntityLoadRequest,\n ),\n );\n const [only] = page.items;\n if (only === undefined) return yield* Effect.fail(notFound);\n return makeEntityEnvelope(\n entityConstructor,\n only,\n caller.links.record(id),\n );\n }\n const found = yield* getUCFactory<T>().pipe(\n Effect.provideService(EntityRepositoryTag, yield* repository(caller)),\n Effect.provideService(EntityIdTag, id),\n );\n return makeEntityEnvelope(\n entityConstructor,\n found,\n caller.links.record(id),\n );\n });\n\n const save = (verb: 'create' | 'update', body: unknown, id?: string) =>\n Effect.gen(function* () {\n const caller = yield* context;\n let entity = yield* readEntityEnvelope(entityConstructor, body);\n // On update the path is authoritative, so a record cannot be renamed\n // onto another one by editing its payload.\n if (id !== undefined) entity.id = id;\n if (options.prepare !== undefined)\n entity = yield* options.prepare(entity, { ...caller, verb });\n const saved = yield* saveUCFactory<T>().pipe(\n Effect.provideService(EntityRepositoryTag, yield* repository(caller)),\n Effect.provideService(EntityTag, entity),\n );\n return makeEntityEnvelope(\n entityConstructor,\n saved,\n caller.links.record(saved.id),\n );\n });\n\n const remove = (id: string) =>\n Effect.gen(function* () {\n const caller = yield* context;\n yield* deleteUCFactory<T>().pipe(\n Effect.provideService(EntityRepositoryTag, yield* repository(caller)),\n Effect.provideService(EntityIdTag, id),\n );\n // An envelope rather than a bare `204`: every message between entifix\n // artifacts is one.\n return {\n meta: { type: 'entity', entity: key, links: caller.links.collection() },\n data: { id },\n };\n });\n\n const metadata = Effect.gen(function* () {\n const principal = yield* RequestPrincipalTag;\n const verified = yield* VerifiedContextTag;\n const policy = yield* PolicyDecisionTag;\n const allows = (permission: Permission): boolean => {\n const { resource, action } = parsePermission(permission);\n return policy.decide({\n subject: { roles: principal.roles },\n resource,\n action,\n });\n };\n // SECURITY BOUNDARY. The document is a map of the model, so an entity the\n // caller may not read answers exactly as one this service does not host:\n // a `403` would make the endpoint an oracle.\n if (!allows(permissionForEntity(entityConstructor, 'read')))\n return yield* Effect.fail(notFound);\n\n const document: EntityMetadataDocument = {\n actions: ENTITY_ACTIONS.filter(action =>\n allows(permissionForEntity(entityConstructor, action)),\n ),\n useCases: describeEntityUseCases(entityConstructor)\n .filter(descriptor =>\n allows(permissionForUseCase(entityConstructor, descriptor.key)),\n )\n // A verb the caller resolves to nothing is omitted, like one they may\n // not invoke; the rest carry what they resolve to.\n .flatMap(descriptor => {\n const composition = compositionFor(\n descriptor,\n verified,\n compositions,\n );\n if (composition === 'unreachable') return [];\n return composition === undefined\n ? [descriptor]\n : [{ ...descriptor, composition }];\n }),\n };\n\n // The ETag hashes the computed document, not the model: two principals\n // with different grants get different documents from one model.\n const body = JSON.stringify(\n makeEntityMetadataEnvelope(entityConstructor, document),\n );\n const etag = `\"${createHash('sha256').update(body).digest('hex')}\"`;\n const request = yield* HttpServerRequest.HttpServerRequest;\n if (request.headers['if-none-match'] === etag)\n return HttpServerResponse.empty({ status: 304 }).pipe(\n HttpServerResponse.setHeaders(cacheHeaders(etag)),\n );\n return HttpServerResponse.text(body, {\n contentType: 'application/json',\n headers: cacheHeaders(etag),\n });\n });\n\n const facets = Effect.gen(function* () {\n const caller = yield* context;\n const search = yield* searchParams;\n const queries = yield* Effect.try({\n try: () => parseFacetQueryParams(entityConstructor, search),\n catch: asInvalidQuery,\n });\n const narrowing = narrowingOf(caller) ?? 'unscoped';\n if (narrowing === 'nothing') {\n const empty: EntityFacetCounts = Object.fromEntries(\n queries.map(({ member }) => [member, []]),\n );\n return makeEntityFacetsEnvelope(entityConstructor, empty);\n }\n const narrowed: EntityFacetQuery<T>[] =\n narrowing === 'unscoped'\n ? queries\n : queries.map(query => ({\n ...query,\n filtering: [...(query.filtering ?? []), narrowing],\n }));\n const factory = yield* EntityFacetCounterFactoryTag;\n const counter = yield* factory.for(entityConstructor, {\n ...(caller.organizationId === undefined\n ? {}\n : { organizationId: caller.organizationId }),\n });\n const counts = yield* facetCountsUCFactory<T>(narrowed).pipe(\n Effect.provideService(EntityFacetCounterTag, counter),\n );\n return makeEntityFacetsEnvelope(entityConstructor, counts);\n });\n\n const crudEndpoint = (verb: EntityApiVerb): Implemented => {\n const override = options.override?.[verb];\n const withId = verb !== 'list' && verb !== 'create';\n const takesBody = verb === 'create' || verb === 'update';\n const payload = takesBody\n ? (override?.payload ?? EnvelopeBody)\n : override?.payload;\n const descriptor = defineEndpoint({\n name: verb,\n method: METHOD[verb],\n path: withId ? record : base,\n ...(withId ? { params: { id: Schema.String } } : {}),\n ...(payload === undefined ? {} : { payload }),\n success: JsonBody,\n errors: [\n ...(verb === 'get' || verb === 'update' || verb === 'delete'\n ? [NotFound]\n : []),\n ...(verb === 'list' ? [InvalidQuery] : []),\n ...(takesBody ? (options.errors ?? []) : []),\n ...(override?.errors ?? []),\n ],\n guard: endpointGuard(entityConstructor, guardFor(verb), ACTION[verb]),\n ...(override?.idempotent === undefined\n ? {}\n : { idempotent: override.idempotent }),\n } as AnyEndpoint);\n\n return implement(descriptor, ((request: EntityApiRequest) => {\n if (override !== undefined)\n return Effect.flatMap(context, caller =>\n override.handler(request, caller),\n );\n const id = request.params?.id as string;\n switch (verb) {\n case 'list':\n return list;\n case 'get':\n return get(id);\n case 'create':\n return save('create', request.payload);\n case 'update':\n return save('update', request.payload, id);\n case 'delete':\n return remove(id);\n }\n }) as never) as Implemented;\n };\n\n const readGuard = guardFor('list');\n const endpoints: Implemented[] = [\n // Registered first, so neither is captured by `/:id`.\n implement(\n defineEndpoint({\n name: 'metadata',\n method: 'GET',\n path: `${base}/$metadata`,\n success: JsonBody,\n errors: [NotFound],\n guard: { kind: 'session' },\n }) as AnyEndpoint,\n (() => metadata) as never,\n ),\n ...(options.facets === true\n ? [\n implement(\n defineEndpoint({\n name: 'facets',\n method: 'GET',\n path: `${base}/$facets`,\n success: JsonBody,\n errors: [InvalidQuery],\n guard: endpointGuard(entityConstructor, readGuard, 'read'),\n }) as AnyEndpoint,\n (() => facets) as never,\n ),\n ]\n : []),\n ...options.verbs.map(crudEndpoint),\n ...verbs.map(verb => {\n const { useCase } = verb;\n const payload =\n useCase.payload ??\n (useCase.binding === 'collection' ? SelectionBody : undefined);\n const descriptor = defineEndpoint({\n // One key may be served both ways — `publish` on a record and over a\n // selection — under one permission, so a name carries the binding\n // whenever it is not the record's.\n name:\n useCase.binding === 'entity'\n ? useCase.key\n : `${useCase.key}-${useCase.binding}`,\n method: 'POST',\n path: verbPath(key, useCase.key, useCase.binding),\n ...(useCase.binding === 'entity'\n ? { params: { id: Schema.String } }\n : {}),\n ...(payload === undefined ? {} : { payload }),\n success: useCase.success ?? JsonBody,\n errors: [...(useCase.errors ?? [])],\n guard: endpointGuardFor(verbGuard(verb), () =>\n permissionForUseCase(entityConstructor, useCase.key),\n ),\n useCase: useCase.key,\n ...(verb.idempotent === undefined\n ? {}\n : { idempotent: verb.idempotent }),\n ...(verb.accepted === true ? { accepted: true } : {}),\n } as AnyEndpoint);\n return implement(descriptor, ((request: EntityApiRequest) =>\n Effect.flatMap(context, caller =>\n verb.handler(request, caller),\n )) as never) as Implemented;\n }),\n ...verbs.flatMap(verb => {\n const { bulk } = verb;\n if (bulk === undefined) return [];\n const { useCase } = verb;\n const descriptor = defineEndpoint({\n name: `${useCase.key}-collection`,\n method: 'POST',\n path: verbPath(key, useCase.key, 'collection'),\n payload: SelectionBody,\n success: JsonBody,\n errors: [...(useCase.errors ?? [])],\n guard: endpointGuardFor(verbGuard(verb), () =>\n permissionForUseCase(entityConstructor, useCase.key),\n ),\n useCase: useCase.key,\n ...(verb.idempotent === undefined\n ? {}\n : { idempotent: verb.idempotent }),\n ...(verb.accepted === true ? { accepted: true } : {}),\n } as AnyEndpoint);\n return [\n implement(descriptor, ((request: EntityApiRequest) =>\n Effect.flatMap(context, caller => bulk(request, caller))) as never),\n ] as Implemented[];\n }),\n ];\n\n return { name: key, endpoints } as never;\n};\n"],"names":["createHash","parsePermission","permissionForEntity","permissionForUseCase","PolicyDecisionTag","deleteUCFactory","EntityFacetCounterFactoryTag","EntityFacetCounterTag","EntityIdTag","EntityLoadRequestTag","EntityRepositoryFactoryTag","EntityRepositoryTag","EntityTag","facetCountsUCFactory","getUCFactory","loadUCFactory","OrganizationIdTag","RequestPrincipalTag","saveUCFactory","VerifiedContextTag","defineEndpoint","describeEntityUseCases","ENTITY_ACTIONS","Envelope","implement","InvalidQuery","JsonBody","makeEntityEnvelope","makeEntityFacetsEnvelope","makeEntityMetadataEnvelope","makeEntityPageEnvelope","NotFound","parseFacetQueryParams","parseLoadRequestParams","readEntityEnvelope","verbPath","Effect","Option","Schema","HttpServerRequest","HttpServerResponse","resolveRequestPrincipal","assertCompositionsDeclared","compositionFor","narrowedByIdRequest","narrowingFor","narrowLoadRequest","SelectionBody","Struct","selection","Unknown","ACTION","list","get","create","update","delete","READS","Set","METHOD","EnvelopeBody","codec","endpointGuardFor","guard","permission","kind","organization","endpointGuard","entityConstructor","action","callerContext","gen","organizationId","serviceOption","principal","verified","match","onNone","onSome","value","searchParams","map","request","URL","url","asInvalidQuery","error","reason","message","cacheHeaders","etag","vary","entityApi","declaration","serving","options","entity","key","base","record","mounted","verbs","notFound","compositions","useCases","unserved","filter","declared","some","verb","useCase","binding","inCollectionCell","alsoAt","cell","bulk","undefined","Error","strays","length","v","join","linksFor","allowed","id","href","String","has","rel","method","collection","guardFor","override","read","write","verbGuard","allowedVerbs","policy","add","resource","decide","subject","roles","context","caller","getOrUndefined","links","repository","flatMap","factory","for","narrowingOf","narrowing","search","parsed","try","catch","items","total","page","pipe","provideService","fail","only","found","save","body","prepare","saved","remove","meta","type","data","metadata","allows","document","actions","descriptor","composition","JSON","stringify","digest","headers","empty","status","setHeaders","text","contentType","facets","queries","Object","fromEntries","member","narrowed","query","filtering","counter","counts","crudEndpoint","withId","takesBody","payload","name","path","params","success","errors","idempotent","handler","readGuard","endpoints","accepted"],"mappings":";AAAA,SAASA,UAAU,QAAQ,cAAc;AAEzC,SAEEC,eAAe,EAEfC,mBAAmB,EACnBC,oBAAoB,EACpBC,iBAAiB,QAC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AA;gBAUAC;YATf,MAAM,EAAEK,IAAI,EAAE,GAAGN;YACjB,IAAIM,SAASC,WAAW,OAAO,EAAE;YACjC,MAAM,EAAEN,OAAO,EAAE,GAAGD;YACpB,MAAMoE,aAAa7J,eAAe;gBAChCsL,MAAM,GAAG5F,QAAQb,GAAG,CAAC,WAAW,CAAC;gBACjCgC,QAAQ;gBACR0E,MAAMxK,SAAS8D,KAAKa,QAAQb,GAAG,EAAE;gBACjCwG,SAAS1J;gBACT8J,SAASnL;gBACToL,QAAQ;wBAAKhG,kBAAAA,QAAQgG,MAAM,YAAdhG,kBAAkB,EAAE;iBAAE;gBACnC/C,OAAOD,iBAAiByE,UAAU1B,OAAO,IACvC1G,qBAAqBiE,mBAAmB0C,QAAQb,GAAG;gBAErDa,SAASA,QAAQb,GAAG;eAChBY,KAAKkG,UAAU,KAAK3F,YACpB,CAAC,IACD;gBAAE2F,YAAYlG,KAAKkG,UAAU;YAAC,GAC9BlG,KAAKsG,QAAQ,KAAK,OAAO;gBAAEA,UAAU;YAAK,IAAI,CAAC;YAErD,OAAO;gBACL3L,UAAUyJ,YAAa,CAAC/F,UACtB9C,OAAOgH,OAAO,CAACL,SAASC,CAAAA,SAAU7B,KAAKjC,SAAS8D;aACnD;QACH;KACD;IAED,OAAO;QAAE0D,MAAMzG;QAAKiH;IAAU;AAChC,EAAE"}
package/dist/index.d.ts CHANGED
@@ -5,5 +5,4 @@ export * from './metadata-composition.js';
5
5
  export * from './narrowing.js';
6
6
  export * from './redact-configuration.js';
7
7
  export * from './respond.js';
8
- export * from './sse.js';
9
8
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,iBAAiB,CAAC;AAChC,cAAc,qBAAqB,CAAC;AACpC,cAAc,kBAAkB,CAAC;AACjC,cAAc,2BAA2B,CAAC;AAC1C,cAAc,gBAAgB,CAAC;AAC/B,cAAc,2BAA2B,CAAC;AAC1C,cAAc,cAAc,CAAC;AAC7B,cAAc,UAAU,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,iBAAiB,CAAC;AAChC,cAAc,qBAAqB,CAAC;AACpC,cAAc,kBAAkB,CAAC;AACjC,cAAc,2BAA2B,CAAC;AAC1C,cAAc,gBAAgB,CAAC;AAC/B,cAAc,2BAA2B,CAAC;AAC1C,cAAc,cAAc,CAAC"}
package/dist/index.js CHANGED
@@ -5,6 +5,5 @@ export * from './metadata-composition.js';
5
5
  export * from './narrowing.js';
6
6
  export * from './redact-configuration.js';
7
7
  export * from './respond.js';
8
- export * from './sse.js';
9
8
 
10
9
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["export * from './auth/index.js';\nexport * from './http-api/index.js';\nexport * from './idempotency.js';\nexport * from './metadata-composition.js';\nexport * from './narrowing.js';\nexport * from './redact-configuration.js';\nexport * from './respond.js';\nexport * from './sse.js';\n"],"names":[],"mappings":"AAAA,cAAc,kBAAkB;AAChC,cAAc,sBAAsB;AACpC,cAAc,mBAAmB;AACjC,cAAc,4BAA4B;AAC1C,cAAc,iBAAiB;AAC/B,cAAc,4BAA4B;AAC1C,cAAc,eAAe;AAC7B,cAAc,WAAW"}
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["export * from './auth/index.js';\nexport * from './http-api/index.js';\nexport * from './idempotency.js';\nexport * from './metadata-composition.js';\nexport * from './narrowing.js';\nexport * from './redact-configuration.js';\nexport * from './respond.js';\n"],"names":[],"mappings":"AAAA,cAAc,kBAAkB;AAChC,cAAc,sBAAsB;AACpC,cAAc,mBAAmB;AACjC,cAAc,4BAA4B;AAC1C,cAAc,iBAAiB;AAC/B,cAAc,4BAA4B;AAC1C,cAAc,eAAe"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@entifix/service-shell",
3
- "version": "0.14.0",
3
+ "version": "0.16.0",
4
4
  "description": "Effect HTTP service skeleton: server layer, health and metadata routes, permission guards, remote configuration and OpenTelemetry.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -76,10 +76,10 @@
76
76
  },
77
77
  "dependencies": {
78
78
  "@swc/helpers": "0.5.23",
79
- "@entifix/authz": "0.14.0",
80
- "@entifix/business": "0.14.0",
81
- "@entifix/core": "0.14.0",
82
- "@entifix/tooling": "0.14.0"
79
+ "@entifix/authz": "0.16.0",
80
+ "@entifix/business": "0.16.0",
81
+ "@entifix/core": "0.16.0",
82
+ "@entifix/tooling": "0.16.0"
83
83
  },
84
84
  "devDependencies": {
85
85
  "@effect/opentelemetry": "4.0.7",
@@ -91,8 +91,8 @@
91
91
  "@opentelemetry/sdk-metrics": "2.12.0",
92
92
  "@opentelemetry/sdk-trace-base": "2.12.0",
93
93
  "effect": "4.0.7",
94
- "@entifix/rest": "0.14.0",
95
- "@entifix/testing-unit": "0.14.0"
94
+ "@entifix/rest": "0.16.0",
95
+ "@entifix/testing-unit": "0.16.0"
96
96
  },
97
97
  "peerDependencies": {
98
98
  "@effect/opentelemetry": "^4.0.7",
package/dist/sse.d.ts DELETED
@@ -1,43 +0,0 @@
1
- import { type DomainEvent, type EntityChangeEvent } from '@entifix/core';
2
- import { Stream } from 'effect';
3
- import { HttpServerResponse } from 'effect/http';
4
- /**
5
- * One `EventSource` frame.
6
- *
7
- * `id:` carries the message's own id — `<transactionId>:<step>` for a
8
- * transaction event — so the `Last-Event-ID` a browser re-sends on reconnect
9
- * names a message that actually exists, rather than a counter invented for the
10
- * wire. The server does not replay it; the client reconciles by
11
- * re-reading the record.
12
- *
13
- * `data:` is a full `event` envelope, which is what keeps the stream from
14
- * becoming a fourth framing: the same bytes a bus consumer would read. It is
15
- * encoded through the entity-change schema, the one shape this stream carries;
16
- * an event that does not encode is no frame at all (`undefined`), because a
17
- * browser would drop it on decode anyway.
18
- */
19
- export declare const sseFrame: (event: DomainEvent<EntityChangeEvent>) => string | undefined;
20
- export interface SseResponseOptions {
21
- /**
22
- * Unix seconds at which to close the connection — the verified token's `exp`.
23
- *
24
- * A held-open response has no next request to fail verification, so the bound
25
- * every REST route gets implicitly has to be applied explicitly here. The
26
- * browser reconnects with the cookie the app refreshed in the meantime
27
- *. Omitted, the stream runs until the client goes away.
28
- */
29
- readonly expiresAt?: number;
30
- /** Injectable for tests; defaults to the wall clock. */
31
- readonly now?: () => number;
32
- }
33
- /**
34
- * Serves a stream of domain events as `text/event-stream`.
35
- *
36
- * `cache-control: no-store` is not politeness — a cached event stream is served
37
- * to whoever asks next, and this one is scoped to a single principal. The
38
- * response is deliberately *not* rebuilt anywhere downstream: the Next proxy has
39
- * a pass-through arm for exactly this content type, because reading the body to
40
- * completion first holds the request open forever and delivers nothing.
41
- */
42
- export declare const sseResponse: (events: Stream.Stream<DomainEvent<EntityChangeEvent>>, { expiresAt, now }?: SseResponseOptions) => HttpServerResponse.HttpServerResponse;
43
- //# sourceMappingURL=sse.d.ts.map
package/dist/sse.d.ts.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"sse.d.ts","sourceRoot":"","sources":["../src/sse.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,WAAW,EAEhB,KAAK,iBAAiB,EACvB,MAAM,eAAe,CAAC;AACvB,OAAO,EAAkC,MAAM,EAAE,MAAM,QAAQ,CAAC;AAChE,OAAO,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAcjD;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,QAAQ,GACnB,OAAO,WAAW,CAAC,iBAAiB,CAAC,KACpC,MAAM,GAAG,SASX,CAAC;AAEF,MAAM,WAAW,kBAAkB;IACjC;;;;;;;OAOG;IACH,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC;IAC5B,wDAAwD;IACxD,QAAQ,CAAC,GAAG,CAAC,EAAE,MAAM,MAAM,CAAC;CAC7B;AAED;;;;;;;;GAQG;AACH,eAAO,MAAM,WAAW,GACtB,QAAQ,MAAM,CAAC,MAAM,CAAC,WAAW,CAAC,iBAAiB,CAAC,CAAC,EACrD,qBAA+B,kBAAuB,KACrD,kBAAkB,CAAC,kBA+CrB,CAAC"}
package/dist/sse.js DELETED
@@ -1,78 +0,0 @@
1
- import { _ as _object_without_properties_loose } from "@swc/helpers/_/_object_without_properties_loose";
2
- import { EntityChangeEnvelope } from '@entifix/core';
3
- import { Duration, Effect, Exit, Schema, Stream } from 'effect';
4
- import { HttpServerResponse } from 'effect/http';
5
- /**
6
- * How often an idle connection emits a comment frame.
7
- *
8
- * An SSE connection that sends nothing for minutes is indistinguishable from a
9
- * dead one to anything between the browser and the service, and a proxy that
10
- * decides it is dead closes it with no error either side can report. A comment
11
- * (`:` and nothing else) is ignored by `EventSource` and costs three bytes.
12
- */ const KEEPALIVE = Duration.seconds(20);
13
- const encoder = new TextEncoder();
14
- /**
15
- * One `EventSource` frame.
16
- *
17
- * `id:` carries the message's own id — `<transactionId>:<step>` for a
18
- * transaction event — so the `Last-Event-ID` a browser re-sends on reconnect
19
- * names a message that actually exists, rather than a counter invented for the
20
- * wire. The server does not replay it; the client reconciles by
21
- * re-reading the record.
22
- *
23
- * `data:` is a full `event` envelope, which is what keeps the stream from
24
- * becoming a fourth framing: the same bytes a bus consumer would read. It is
25
- * encoded through the entity-change schema, the one shape this stream carries;
26
- * an event that does not encode is no frame at all (`undefined`), because a
27
- * browser would drop it on decode anyway.
28
- */ export const sseFrame = (event)=>{
29
- const { data } = event, meta = _object_without_properties_loose(event, [
30
- "data"
31
- ]);
32
- const encoded = Schema.encodeUnknownExit(EntityChangeEnvelope)({
33
- meta: {
34
- type: 'event',
35
- event: meta
36
- },
37
- data
38
- });
39
- return Exit.isSuccess(encoded) ? `id: ${event.id}\ndata: ${JSON.stringify(encoded.value)}\n\n` : undefined;
40
- };
41
- /**
42
- * Serves a stream of domain events as `text/event-stream`.
43
- *
44
- * `cache-control: no-store` is not politeness — a cached event stream is served
45
- * to whoever asks next, and this one is scoped to a single principal. The
46
- * response is deliberately *not* rebuilt anywhere downstream: the Next proxy has
47
- * a pass-through arm for exactly this content type, because reading the body to
48
- * completion first holds the request open forever and delivers nothing.
49
- */ export const sseResponse = (events, { expiresAt, now = Date.now } = {})=>{
50
- const keepalive = Stream.fromEffectRepeat(Effect.as(Effect.sleep(KEEPALIVE), ': keepalive\n\n'));
51
- const frames = Stream.merge(Stream.filter(Stream.map(events, sseFrame), (frame)=>frame !== undefined), keepalive, {
52
- haltStrategy: 'left'
53
- });
54
- // An opening comment, emitted before anything has happened.
55
- //
56
- // Not cosmetic: a chunked response writes its headers with its first chunk,
57
- // so a stream that stays silent until something occurs leaves the client in
58
- // `CONNECTING` — indefinitely, since a stream whose whole purpose is to be
59
- // idle most of the time may have nothing to say for hours. Measured: without
60
- // it, `fetch` against this route does not resolve at all.
61
- const opened = Stream.concat(Stream.make(': open\n\n'), frames);
62
- const bounded = expiresAt === undefined ? opened : Stream.interruptWhen(opened, // Never negative: an already-expired token closes at once rather than
63
- // scheduling a sleep into the past, which `Effect.sleep` treats as
64
- // zero anyway but reads as an oversight.
65
- Effect.sleep(Duration.millis(Math.max(0, expiresAt * 1000 - now()))));
66
- return HttpServerResponse.stream(Stream.map(bounded, (frame)=>encoder.encode(frame)), {
67
- contentType: 'text/event-stream',
68
- headers: {
69
- 'cache-control': 'no-store',
70
- connection: 'keep-alive',
71
- // nginx buffers a proxied response by default, which would hold every
72
- // frame until the stream ends — that is, forever.
73
- 'x-accel-buffering': 'no'
74
- }
75
- });
76
- };
77
-
78
- //# sourceMappingURL=sse.js.map
package/dist/sse.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/sse.ts"],"sourcesContent":["import {\n type DomainEvent,\n EntityChangeEnvelope,\n type EntityChangeEvent,\n} from '@entifix/core';\nimport { Duration, Effect, Exit, Schema, Stream } from 'effect';\nimport { HttpServerResponse } from 'effect/http';\n\n/**\n * How often an idle connection emits a comment frame.\n *\n * An SSE connection that sends nothing for minutes is indistinguishable from a\n * dead one to anything between the browser and the service, and a proxy that\n * decides it is dead closes it with no error either side can report. A comment\n * (`:` and nothing else) is ignored by `EventSource` and costs three bytes.\n */\nconst KEEPALIVE = Duration.seconds(20);\n\nconst encoder = new TextEncoder();\n\n/**\n * One `EventSource` frame.\n *\n * `id:` carries the message's own id — `<transactionId>:<step>` for a\n * transaction event — so the `Last-Event-ID` a browser re-sends on reconnect\n * names a message that actually exists, rather than a counter invented for the\n * wire. The server does not replay it; the client reconciles by\n * re-reading the record.\n *\n * `data:` is a full `event` envelope, which is what keeps the stream from\n * becoming a fourth framing: the same bytes a bus consumer would read. It is\n * encoded through the entity-change schema, the one shape this stream carries;\n * an event that does not encode is no frame at all (`undefined`), because a\n * browser would drop it on decode anyway.\n */\nexport const sseFrame = (\n event: DomainEvent<EntityChangeEvent>,\n): string | undefined => {\n const { data, ...meta } = event;\n const encoded = Schema.encodeUnknownExit(EntityChangeEnvelope)({\n meta: { type: 'event', event: meta },\n data,\n });\n return Exit.isSuccess(encoded)\n ? `id: ${event.id}\\ndata: ${JSON.stringify(encoded.value)}\\n\\n`\n : undefined;\n};\n\nexport interface SseResponseOptions {\n /**\n * Unix seconds at which to close the connection — the verified token's `exp`.\n *\n * A held-open response has no next request to fail verification, so the bound\n * every REST route gets implicitly has to be applied explicitly here. The\n * browser reconnects with the cookie the app refreshed in the meantime\n *. Omitted, the stream runs until the client goes away.\n */\n readonly expiresAt?: number;\n /** Injectable for tests; defaults to the wall clock. */\n readonly now?: () => number;\n}\n\n/**\n * Serves a stream of domain events as `text/event-stream`.\n *\n * `cache-control: no-store` is not politeness — a cached event stream is served\n * to whoever asks next, and this one is scoped to a single principal. The\n * response is deliberately *not* rebuilt anywhere downstream: the Next proxy has\n * a pass-through arm for exactly this content type, because reading the body to\n * completion first holds the request open forever and delivers nothing.\n */\nexport const sseResponse = (\n events: Stream.Stream<DomainEvent<EntityChangeEvent>>,\n { expiresAt, now = Date.now }: SseResponseOptions = {},\n): HttpServerResponse.HttpServerResponse => {\n const keepalive = Stream.fromEffectRepeat(\n Effect.as(Effect.sleep(KEEPALIVE), ': keepalive\\n\\n'),\n );\n\n const frames = Stream.merge(\n Stream.filter(\n Stream.map(events, sseFrame),\n (frame): frame is string => frame !== undefined,\n ),\n keepalive,\n { haltStrategy: 'left' },\n );\n\n // An opening comment, emitted before anything has happened.\n //\n // Not cosmetic: a chunked response writes its headers with its first chunk,\n // so a stream that stays silent until something occurs leaves the client in\n // `CONNECTING` — indefinitely, since a stream whose whole purpose is to be\n // idle most of the time may have nothing to say for hours. Measured: without\n // it, `fetch` against this route does not resolve at all.\n const opened = Stream.concat(Stream.make(': open\\n\\n'), frames);\n\n const bounded =\n expiresAt === undefined\n ? opened\n : Stream.interruptWhen(\n opened,\n // Never negative: an already-expired token closes at once rather than\n // scheduling a sleep into the past, which `Effect.sleep` treats as\n // zero anyway but reads as an oversight.\n Effect.sleep(Duration.millis(Math.max(0, expiresAt * 1000 - now()))),\n );\n\n return HttpServerResponse.stream(\n Stream.map(bounded, frame => encoder.encode(frame)),\n {\n contentType: 'text/event-stream',\n headers: {\n 'cache-control': 'no-store',\n connection: 'keep-alive',\n // nginx buffers a proxied response by default, which would hold every\n // frame until the stream ends — that is, forever.\n 'x-accel-buffering': 'no',\n },\n },\n );\n};\n"],"names":["EntityChangeEnvelope","Duration","Effect","Exit","Schema","Stream","HttpServerResponse","KEEPALIVE","seconds","encoder","TextEncoder","sseFrame","event","data","meta","encoded","encodeUnknownExit","type","isSuccess","id","JSON","stringify","value","undefined","sseResponse","events","expiresAt","now","Date","keepalive","fromEffectRepeat","as","sleep","frames","merge","filter","map","frame","haltStrategy","opened","concat","make","bounded","interruptWhen","millis","Math","max","stream","encode","contentType","headers","connection"],"mappings":";AAAA,SAEEA,oBAAoB,QAEf,gBAAgB;AACvB,SAASC,QAAQ,EAAEC,MAAM,EAAEC,IAAI,EAAEC,MAA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