@entifix/service-shell 0.13.0 → 0.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -7
- package/dist/auth/failures.d.ts +0 -12
- package/dist/auth/failures.d.ts.map +1 -1
- package/dist/auth/failures.js +0 -10
- package/dist/auth/failures.js.map +1 -1
- package/dist/auth/index.d.ts +0 -1
- package/dist/auth/index.d.ts.map +1 -1
- package/dist/auth/index.js +0 -1
- package/dist/auth/index.js.map +1 -1
- package/dist/auth/require-principal.d.ts +0 -16
- package/dist/auth/require-principal.d.ts.map +1 -1
- package/dist/auth/require-principal.js +1 -38
- package/dist/auth/require-principal.js.map +1 -1
- package/dist/auth/require-service-crossing.d.ts +2 -73
- package/dist/auth/require-service-crossing.d.ts.map +1 -1
- package/dist/auth/require-service-crossing.js +2 -117
- package/dist/auth/require-service-crossing.js.map +1 -1
- package/dist/auth/shared-token.d.ts +0 -15
- package/dist/auth/shared-token.d.ts.map +1 -1
- package/dist/auth/shared-token.js +0 -25
- package/dist/auth/shared-token.js.map +1 -1
- package/dist/http-api/build-api.d.ts.map +1 -1
- package/dist/http-api/build-api.js +1 -1
- package/dist/http-api/build-api.js.map +1 -1
- package/dist/http-api/entity-api.d.ts.map +1 -1
- package/dist/http-api/entity-api.js +6 -2
- package/dist/http-api/entity-api.js.map +1 -1
- package/dist/index.d.ts +0 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +0 -4
- package/dist/index.js.map +1 -1
- package/dist/load-remote-configuration.d.ts +4 -4
- package/dist/load-remote-configuration.d.ts.map +1 -1
- package/dist/load-remote-configuration.js +7 -14
- package/dist/load-remote-configuration.js.map +1 -1
- package/dist/observability.d.ts +2 -2
- package/dist/observability.d.ts.map +1 -1
- package/dist/observability.js.map +1 -1
- package/dist/push/index.d.ts +9 -0
- package/dist/push/index.d.ts.map +1 -0
- package/dist/push/index.js +9 -0
- package/dist/push/index.js.map +1 -0
- package/dist/push/server-push.d.ts +82 -0
- package/dist/push/server-push.d.ts.map +1 -0
- package/dist/push/server-push.js +48 -0
- package/dist/push/server-push.js.map +1 -0
- package/dist/push/sse.d.ts +62 -0
- package/dist/push/sse.d.ts.map +1 -0
- package/dist/push/sse.js +120 -0
- package/dist/push/sse.js.map +1 -0
- package/dist/respond.d.ts +1 -7
- package/dist/respond.d.ts.map +1 -1
- package/dist/respond.js +1 -8
- package/dist/respond.js.map +1 -1
- package/package.json +23 -13
- package/dist/auth/require-organization.d.ts +0 -32
- package/dist/auth/require-organization.d.ts.map +0 -1
- package/dist/auth/require-organization.js +0 -52
- package/dist/auth/require-organization.js.map +0 -1
- package/dist/entity-facet-routes.d.ts +0 -44
- package/dist/entity-facet-routes.d.ts.map +0 -1
- package/dist/entity-facet-routes.js +0 -70
- package/dist/entity-facet-routes.js.map +0 -1
- package/dist/entity-metadata-route.d.ts +0 -25
- package/dist/entity-metadata-route.d.ts.map +0 -1
- package/dist/entity-metadata-route.js +0 -102
- package/dist/entity-metadata-route.js.map +0 -1
- package/dist/entity-route-guard.d.ts +0 -62
- package/dist/entity-route-guard.d.ts.map +0 -1
- package/dist/entity-route-guard.js +0 -35
- package/dist/entity-route-guard.js.map +0 -1
- package/dist/entity-routes.d.ts +0 -76
- package/dist/entity-routes.d.ts.map +0 -1
- package/dist/entity-routes.js +0 -267
- package/dist/entity-routes.js.map +0 -1
- package/dist/route-responses.d.ts +0 -44
- package/dist/route-responses.d.ts.map +0 -1
- package/dist/route-responses.js +0 -104
- package/dist/route-responses.js.map +0 -1
- package/dist/sse.d.ts +0 -43
- package/dist/sse.d.ts.map +0 -1
- package/dist/sse.js +0 -78
- package/dist/sse.js.map +0 -1
|
@@ -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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AAa4F,IAAI,CAAC1E,MAAML,IAAI,KAGlCjB,QAAQgG,IAAI,CAAC/E;AAEjB,EAAE;AAEF;;;;CAIC,GACD,OAAO,MAAM6F,WAAW,CACtBF,KACAxF,QACAiF,UAAsB,CAAC,CAAC;QAqBKA;IAnB7B,MAAMU,WAAW3F,OAAOG,GAAG,CAACD,CAAAA,QAC1BrB,eAAeqB,KAAK,CAClBsF,KACAtF,MAAML,IAAI,EACV,sFAAsF;QACtF,CAAC+F,SACC1F,MAAMJ,SAAS,CAACyF,MAAM,CACpB,8DAA8D;YAC9D,CAACE,OAAY,EAAErF,UAAU,EAAEyF,OAAO,EAAE,GAClCJ,MAAMG,MAAM,CAACxF,WAAWP,IAAI,EAAEgG,UAChCD;IAIR,OAAO/G,eAAeiH,KAAK,CAACN,KAAclD,IAAI,CAC5C9D,MAAMuH,OAAO,CACXvH,MAAMwH,QAAQ,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,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,M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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,EAETC,YAAY,EACZC,QAAQ,EACRC,kBAAkB,EAClBC,wBAAwB,EACxBC,0BAA0B,EAC1BC,sBAAsB,EACtBC,QAAQ,EACRC,qBAAqB,EACrBC,sBAAsB,EACtBC,kBAAkB,EAClBC,QAAQ,QACH,gBAAgB;AACvB,SAASC,MAAM,EAAEC,MAAM,EAAEC,MAAM,QAAQ,SAAS;AAChD,SAASC,iBAAiB,EAAEC,kBAAkB,QAAQ,cAAc;AAEpE,SAASC,uBAAuB,QAAQ,+BAA+B;AACvE,SACEC,0BAA0B,EAC1BC,cAAc,QAET,6BAA6B;AACpC,SACEC,mBAAmB,EACnBC,YAAY,EACZC,iBAAiB,QACZ,kBAAkB;AAGzB,+DAA+D,GAC/D,MAAMC,gBAAgBT,OAAOU,MAAM,CAAC;IAAEC,WAAWX,OAAOY,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,OAAO,IACvC1G,qBAAqBiE,mBAAmB0C,QAAQb,GAAG;gBAErDa,SAASA,QAAQb,GAAG;eAChBY,KAAKkG,UAAU,KAAK3F,YACpB,CAAC,IACD;gBAAE2F,YAAYlG,KAAKkG,UAAU;YAAC;YAEpC,OAAOvL,UAAUyJ,YAAa,CAAC/F,UAC7B9C,OAAOgH,OAAO,CAACL,SAASC,CAAAA,SACtBnC,KAAKmG,OAAO,CAAC9H,SAAS8D;QAE5B;WACG3C,MAAM+C,OAAO,CAACvC,CAAAA;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;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,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,EAETC,YAAY,EACZC,QAAQ,EACRC,kBAAkB,EAClBC,wBAAwB,EACxBC,0BAA0B,EAC1BC,sBAAsB,EACtBC,QAAQ,EACRC,qBAAqB,EACrBC,sBAAsB,EACtBC,kBAAkB,EAClBC,QAAQ,QACH,gBAAgB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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
|
@@ -1,12 +1,8 @@
|
|
|
1
1
|
export * from './auth/index.js';
|
|
2
|
-
export * from './entity-facet-routes.js';
|
|
3
|
-
export * from './entity-metadata-route.js';
|
|
4
|
-
export * from './entity-routes.js';
|
|
5
2
|
export * from './http-api/index.js';
|
|
6
3
|
export * from './idempotency.js';
|
|
7
4
|
export * from './metadata-composition.js';
|
|
8
5
|
export * from './narrowing.js';
|
|
9
6
|
export * from './redact-configuration.js';
|
|
10
7
|
export * from './respond.js';
|
|
11
|
-
export * from './sse.js';
|
|
12
8
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,iBAAiB,CAAC;AAChC,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
|
@@ -1,13 +1,9 @@
|
|
|
1
1
|
export * from './auth/index.js';
|
|
2
|
-
export * from './entity-facet-routes.js';
|
|
3
|
-
export * from './entity-metadata-route.js';
|
|
4
|
-
export * from './entity-routes.js';
|
|
5
2
|
export * from './http-api/index.js';
|
|
6
3
|
export * from './idempotency.js';
|
|
7
4
|
export * from './metadata-composition.js';
|
|
8
5
|
export * from './narrowing.js';
|
|
9
6
|
export * from './redact-configuration.js';
|
|
10
7
|
export * from './respond.js';
|
|
11
|
-
export * from './sse.js';
|
|
12
8
|
|
|
13
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 './
|
|
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"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { ConfigurationClientInMemory, ConfigurationPlain,
|
|
1
|
+
import { ConfigurationClientInMemory, ConfigurationPlain, Unavailable } from '@entifix/core';
|
|
2
2
|
import { Context, Effect, Schedule } from 'effect';
|
|
3
3
|
declare const LoadedConfigurationTag_base: Context.ServiceClass<LoadedConfigurationTag, "LoadedConfigurationTag", ConfigurationPlain>;
|
|
4
4
|
/**
|
|
@@ -72,18 +72,18 @@ export interface RemoteConfigurationSource {
|
|
|
72
72
|
* their own parameters (e.g. `mongo.uri`) instead of hardcoding them.
|
|
73
73
|
*
|
|
74
74
|
* Uses Node's global `fetch` (same transport approach as the REST client); any
|
|
75
|
-
* network/parse/non-2xx failure becomes an {@link
|
|
75
|
+
* network/parse/non-2xx failure becomes an {@link Unavailable}. Each
|
|
76
76
|
* attempt is deadlined ({@link defaultConfigAttemptTimeoutMs}) and the fetch is
|
|
77
77
|
* retried on a bounded schedule ({@link defaultConfigRetrySchedule}), so a
|
|
78
78
|
* dependent that boots before config-service is HTTP-ready waits it out — and
|
|
79
79
|
* one that reaches a socket nobody is answering gives up rather than hanging.
|
|
80
80
|
*/
|
|
81
|
-
export declare const loadRemoteConfiguration: (source: RemoteConfigurationSource, options?: LoadRemoteConfigurationOptions) => Effect.Effect<ConfigurationPlain,
|
|
81
|
+
export declare const loadRemoteConfiguration: (source: RemoteConfigurationSource, options?: LoadRemoteConfigurationOptions) => Effect.Effect<ConfigurationPlain, Unavailable>;
|
|
82
82
|
/**
|
|
83
83
|
* Convenience: load the remote configuration and wrap it in a
|
|
84
84
|
* {@link ConfigurationClientInMemory}, to read the service's own parameters via
|
|
85
85
|
* `.in(group).getString(key)` or to hand to an adapter that is built with one.
|
|
86
86
|
*/
|
|
87
|
-
export declare const loadRemoteConfigurationClient: (source: RemoteConfigurationSource, options?: LoadRemoteConfigurationOptions) => Effect.Effect<ConfigurationClientInMemory,
|
|
87
|
+
export declare const loadRemoteConfigurationClient: (source: RemoteConfigurationSource, options?: LoadRemoteConfigurationOptions) => Effect.Effect<ConfigurationClientInMemory, Unavailable>;
|
|
88
88
|
export {};
|
|
89
89
|
//# sourceMappingURL=load-remote-configuration.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"load-remote-configuration.d.ts","sourceRoot":"","sources":["../src/load-remote-configuration.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,2BAA2B,EAC3B,kBAAkB,EAClB,
|
|
1
|
+
{"version":3,"file":"load-remote-configuration.d.ts","sourceRoot":"","sources":["../src/load-remote-configuration.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,2BAA2B,EAC3B,kBAAkB,EAClB,WAAW,EACZ,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,QAAQ,CAAC;;AAEnD;;;GAGG;AACH,qBAAa,sBAAuB,SAAQ,2BAGf;CAAG;AAEhC;;;;;;;;;GASG;AACH,eAAO,MAAM,0BAA0B,EAAE,QAAQ,CAAC,QAAQ,CAAC,OAAO,EAAE,OAAO,CACR,CAAC;AAEpE;;;;;;;;;;;;;;;;;GAiBG;AACH,eAAO,MAAM,6BAA6B,OAAQ,CAAC;AAEnD,mDAAmD;AACnD,MAAM,WAAW,8BAA8B;IAC7C;;;;;OAKG;IACH,QAAQ,CAAC,aAAa,CAAC,EAAE,QAAQ,CAAC,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;IAC7D;;;;OAIG;IACH,QAAQ,CAAC,gBAAgB,CAAC,EAAE,MAAM,CAAC;CACpC;AAED;;;;;;;GAOG;AACH,MAAM,WAAW,yBAAyB;IACxC,wEAAwE;IACxE,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;IACrB,QAAQ,CAAC,OAAO,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;CACrD;AAED;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,uBAAuB,GAClC,QAAQ,yBAAyB,EACjC,UAAS,8BAAmC,KAC3C,MAAM,CAAC,MAAM,CAAC,kBAAkB,EAAE,WAAW,CAwB/C,CAAC;AAEF;;;;GAIG;AACH,eAAO,MAAM,6BAA6B,GACxC,QAAQ,yBAAyB,EACjC,UAAS,8BAAmC,KAC3C,MAAM,CAAC,MAAM,CAAC,2BAA2B,EAAE,WAAW,CAGtD,CAAC"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { ConfigurationClientInMemory,
|
|
1
|
+
import { ConfigurationClientInMemory, Unavailable } from '@entifix/core';
|
|
2
2
|
import { Context, Effect, Schedule } from 'effect';
|
|
3
3
|
/**
|
|
4
4
|
* DI tag carrying the raw {@link ConfigurationPlain} a service loaded at boot,
|
|
@@ -42,7 +42,7 @@ import { Context, Effect, Schedule } from 'effect';
|
|
|
42
42
|
* their own parameters (e.g. `mongo.uri`) instead of hardcoding them.
|
|
43
43
|
*
|
|
44
44
|
* Uses Node's global `fetch` (same transport approach as the REST client); any
|
|
45
|
-
* network/parse/non-2xx failure becomes an {@link
|
|
45
|
+
* network/parse/non-2xx failure becomes an {@link Unavailable}. Each
|
|
46
46
|
* attempt is deadlined ({@link defaultConfigAttemptTimeoutMs}) and the fetch is
|
|
47
47
|
* retried on a bounded schedule ({@link defaultConfigRetrySchedule}), so a
|
|
48
48
|
* dependent that boots before config-service is HTTP-ready waits it out — and
|
|
@@ -57,21 +57,14 @@ import { Context, Effect, Schedule } from 'effect';
|
|
|
57
57
|
cache: 'no-store',
|
|
58
58
|
headers: source.headers,
|
|
59
59
|
signal: AbortSignal.timeout(attemptTimeoutMs)
|
|
60
|
-
}).catch((error)=>{
|
|
61
|
-
// Rewritten because the raw abort says `This operation was aborted`,
|
|
62
|
-
// which reads like a bug in the caller rather than a silent peer.
|
|
63
|
-
if (error instanceof Error && error.name === 'TimeoutError') {
|
|
64
|
-
throw new Error(`the configuration source did not answer within ${attemptTimeoutMs}ms at ${url}`);
|
|
65
|
-
}
|
|
66
|
-
throw error;
|
|
67
60
|
});
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
}
|
|
61
|
+
// Any answer but a success is the source failing to serve, the same as
|
|
62
|
+
// a timeout or a dropped connection: one `Unavailable`, retried.
|
|
63
|
+
if (!response.ok) throw new Error(`status ${response.status}`);
|
|
71
64
|
return await response.json();
|
|
72
65
|
},
|
|
73
|
-
catch: (
|
|
74
|
-
url
|
|
66
|
+
catch: ()=>new Unavailable({
|
|
67
|
+
dependency: url
|
|
75
68
|
})
|
|
76
69
|
});
|
|
77
70
|
return Effect.retry(fetchOnce, (_options_retrySchedule = options.retrySchedule) != null ? _options_retrySchedule : defaultConfigRetrySchedule);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/load-remote-configuration.ts"],"sourcesContent":["import {\n ConfigurationClientInMemory,\n ConfigurationPlain,\n
|
|
1
|
+
{"version":3,"sources":["../src/load-remote-configuration.ts"],"sourcesContent":["import {\n ConfigurationClientInMemory,\n ConfigurationPlain,\n Unavailable,\n} from '@entifix/core';\nimport { Context, Effect, Schedule } from 'effect';\n\n/**\n * DI tag carrying the raw {@link ConfigurationPlain} a service loaded at boot,\n * so a `GET /api/config` introspection route can expose it (redacted).\n */\nexport class LoadedConfigurationTag extends Context.Service<\n LoadedConfigurationTag,\n ConfigurationPlain\n>()('LoadedConfigurationTag') {}\n\n/**\n * Default boot-fetch retry policy: 20 attempts spaced 1s apart (~20s window).\n *\n * A dependent service `dev` target `dependsOn config-service:dev`, but Nx\n * considers a *continuous* dependency \"ready\" the moment its process starts —\n * not when its HTTP server is listening and its table is seeded. So a fast\n * backend can fire its boot fetch before config-service answers and, without a\n * retry, would crash with `fetch failed` (connection refused). Retrying a\n * bounded window lets the fleet come up in any order.\n */\nexport const defaultConfigRetrySchedule: Schedule.Schedule<unknown, unknown> =\n Schedule.max([Schedule.spaced('1 seconds'), Schedule.recurs(20)]);\n\n/**\n * Deadline for a single boot-fetch attempt.\n *\n * **The retry above only helps if an attempt can fail.** `fetch` has no timeout\n * of its own, so a connection that is accepted but never answered — a previous\n * listener dying mid-flight, a half-open socket — leaves it waiting forever.\n * The schedule never sees a failure, never retries, and the service hangs in its\n * boot layer with its port bound and nothing served: measured twice on\n * 2026-08-14, on two different services, and recovered only by recreating the\n * datastores.\n *\n * So an attempt is deadlined, for the same reason a readiness probe is: a check\n * that hangs is a check that failed. The ordinary race this retry was written\n * for — config-service not listening yet — still fails instantly with\n * `ECONNREFUSED` and costs nothing, so this bounds the pathological case only:\n * 20 retries × (5s deadline + 1s spacing) ≈ 2 minutes before the service exits\n * loudly instead of hanging silently.\n */\nexport const defaultConfigAttemptTimeoutMs = 5_000;\n\n/** Options for {@link loadRemoteConfiguration}. */\nexport interface LoadRemoteConfigurationOptions {\n /**\n * Retry policy for the boot fetch. Defaults to\n * {@link defaultConfigRetrySchedule}. Pass `Schedule.stop` to fail fast (a\n * single attempt, no retry) — used by tests and callers that want the error\n * immediately.\n */\n readonly retrySchedule?: Schedule.Schedule<unknown, unknown>;\n /**\n * Deadline for one attempt, in milliseconds. Defaults to\n * {@link defaultConfigAttemptTimeoutMs}. There is deliberately no way to\n * disable it — an attempt that cannot time out is the bug this exists for.\n */\n readonly attemptTimeoutMs?: number;\n}\n\n/**\n * Where a service's configuration is fetched from, and what the request\n * carries.\n *\n * Both are the host's: the path a configuration service answers on and the\n * credential it asks for are that deployment's protocol, so the framework takes\n * the finished URL and headers rather than composing either.\n */\nexport interface RemoteConfigurationSource {\n /** The full URL, e.g. `http://config:3190/api/config/order-service`. */\n readonly url: string;\n readonly headers?: Readonly<Record<string, string>>;\n}\n\n/**\n * Fetches a service's configuration from a configuration service and returns\n * it as a {@link ConfigurationPlain}. Backends call this at boot to resolve\n * their own parameters (e.g. `mongo.uri`) instead of hardcoding them.\n *\n * Uses Node's global `fetch` (same transport approach as the REST client); any\n * network/parse/non-2xx failure becomes an {@link Unavailable}. Each\n * attempt is deadlined ({@link defaultConfigAttemptTimeoutMs}) and the fetch is\n * retried on a bounded schedule ({@link defaultConfigRetrySchedule}), so a\n * dependent that boots before config-service is HTTP-ready waits it out — and\n * one that reaches a socket nobody is answering gives up rather than hanging.\n */\nexport const loadRemoteConfiguration = (\n source: RemoteConfigurationSource,\n options: LoadRemoteConfigurationOptions = {},\n): Effect.Effect<ConfigurationPlain, Unavailable> => {\n const { url } = source;\n const attemptTimeoutMs =\n options.attemptTimeoutMs ?? defaultConfigAttemptTimeoutMs;\n\n const fetchOnce = Effect.tryPromise({\n try: async () => {\n const response = await fetch(url, {\n cache: 'no-store',\n headers: source.headers,\n signal: AbortSignal.timeout(attemptTimeoutMs),\n });\n // Any answer but a success is the source failing to serve, the same as\n // a timeout or a dropped connection: one `Unavailable`, retried.\n if (!response.ok) throw new Error(`status ${response.status}`);\n return (await response.json()) as ConfigurationPlain;\n },\n catch: () => new Unavailable({ dependency: url }),\n });\n\n return Effect.retry(\n fetchOnce,\n options.retrySchedule ?? defaultConfigRetrySchedule,\n );\n};\n\n/**\n * Convenience: load the remote configuration and wrap it in a\n * {@link ConfigurationClientInMemory}, to read the service's own parameters via\n * `.in(group).getString(key)` or to hand to an adapter that is built with one.\n */\nexport const loadRemoteConfigurationClient = (\n source: RemoteConfigurationSource,\n options: LoadRemoteConfigurationOptions = {},\n): Effect.Effect<ConfigurationClientInMemory, Unavailable> =>\n loadRemoteConfiguration(source, options).pipe(\n Effect.map(plain => new ConfigurationClientInMemory(plain)),\n );\n"],"names":["ConfigurationClientInMemory","Unavailable","Context","Effect","Schedule","LoadedConfigurationTag","Service","defaultConfigRetrySchedule","max","spaced","recurs","defaultConfigAttemptTimeoutMs","loadRemoteConfiguration","source","options","url","attemptTimeoutMs","fetchOnce","tryPromise","try","response","fetch","cache","headers","signal","AbortSignal","timeout","ok","Error","status","json","catch","dependency","retry","retrySchedule","loadRemoteConfigurationClient","pipe","map","plain"],"mappings":"AAAA,SACEA,2BAA2B,EAE3BC,WAAW,QACN,gBAAgB;AACvB,SAASC,OAAO,EAAEC,MAAM,EAAEC,QAAQ,QAAQ,SAAS;AAEnD;;;CAGC,GACD,OAAO,MAAMC,+BAA+BH,QAAQI,OAAO,GAGvD;AAA2B;AAE/B;;;;;;;;;CASC,GACD,OAAO,MAAMC,6BACXH,SAASI,GAAG,CAAC;IAACJ,SAASK,MAAM,CAAC;IAAcL,SAASM,MAAM,CAAC;CAAI,EAAE;AAEpE;;;;;;;;;;;;;;;;;CAiBC,GACD,OAAO,MAAMC,gCAAgC,KAAM;AAiCnD;;;;;;;;;;;CAWC,GACD,OAAO,MAAMC,0BAA0B,CACrCC,QACAC,UAA0C,CAAC,CAAC;QAI1CA,2BAmBAA;IArBF,MAAM,EAAEC,GAAG,EAAE,GAAGF;IAChB,MAAMG,oBACJF,4BAAAA,QAAQE,gBAAgB,YAAxBF,4BAA4BH;IAE9B,MAAMM,YAAYd,OAAOe,UAAU,CAAC;QAClCC,KAAK;YACH,MAAMC,WAAW,MAAMC,MAAMN,KAAK;gBAChCO,OAAO;gBACPC,SAASV,OAAOU,OAAO;gBACvBC,QAAQC,YAAYC,OAAO,CAACV;YAC9B;YACA,uEAAuE;YACvE,iEAAiE;YACjE,IAAI,CAACI,SAASO,EAAE,EAAE,MAAM,IAAIC,MAAM,CAAC,OAAO,EAAER,SAASS,MAAM,EAAE;YAC7D,OAAQ,MAAMT,SAASU,IAAI;QAC7B;QACAC,OAAO,IAAM,IAAI9B,YAAY;gBAAE+B,YAAYjB;YAAI;IACjD;IAEA,OAAOZ,OAAO8B,KAAK,CACjBhB,YACAH,yBAAAA,QAAQoB,aAAa,YAArBpB,yBAAyBP;AAE7B,EAAE;AAEF;;;;CAIC,GACD,OAAO,MAAM4B,gCAAgC,CAC3CtB,QACAC,UAA0C,CAAC,CAAC,GAE5CF,wBAAwBC,QAAQC,SAASsB,IAAI,CAC3CjC,OAAOkC,GAAG,CAACC,CAAAA,QAAS,IAAItC,4BAA4BsC,SACpD"}
|
package/dist/observability.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { ConfigurationClient,
|
|
1
|
+
import type { ConfigurationClient, Unavailable } from '@entifix/core';
|
|
2
2
|
import { type LogLevel, type LogRecord, type LogSink } from '@entifix/tooling/logging';
|
|
3
3
|
import { type MetricReader, type ResourceMetrics } from '@opentelemetry/sdk-metrics';
|
|
4
4
|
import { type ReadableSpan, type SpanProcessor } from '@opentelemetry/sdk-trace-base';
|
|
@@ -114,5 +114,5 @@ export declare const makeInMemoryObservabilityLayer: (serviceName: string) => In
|
|
|
114
114
|
* the one service that cannot fetch its configuration over HTTP, because it is
|
|
115
115
|
* the thing being fetched from.
|
|
116
116
|
*/
|
|
117
|
-
export declare const observabilityFromConfiguration: (store: ConfigurationClient, serviceName: string) => Effect.Effect<ReturnType<typeof makeObservabilityLayer>,
|
|
117
|
+
export declare const observabilityFromConfiguration: (store: ConfigurationClient, serviceName: string) => Effect.Effect<ReturnType<typeof makeObservabilityLayer>, Unavailable>;
|
|
118
118
|
//# sourceMappingURL=observability.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"observability.d.ts","sourceRoot":"","sources":["../src/observability.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,mBAAmB,EAAE,
|
|
1
|
+
{"version":3,"file":"observability.d.ts","sourceRoot":"","sources":["../src/observability.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,mBAAmB,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AACtE,OAAO,EAIL,KAAK,QAAQ,EACb,KAAK,SAAS,EACd,KAAK,OAAO,EAGb,MAAM,0BAA0B,CAAC;AAKlC,OAAO,EAGL,KAAK,YAAY,EAEjB,KAAK,eAAe,EACrB,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAGL,KAAK,YAAY,EAEjB,KAAK,aAAa,EACnB,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,MAAM,EAAE,KAAK,EAAsB,MAAM,QAAQ,CAAC;AAG3D,kFAAkF;AAClF,MAAM,WAAW,mBAAmB;IAClC,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,QAAQ,CAAC,KAAK,EAAE,QAAQ,CAAC;IACzB,mFAAmF;IACnF,QAAQ,CAAC,IAAI,EAAE,QAAQ,GAAG,MAAM,CAAC;IACjC;;;;;;;;;OASG;IACH,QAAQ,CAAC,YAAY,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAC3C;;;;;;;;;OASG;IACH,QAAQ,CAAC,gBAAgB,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;CAChD;AA0JD,gEAAgE;AAChE,MAAM,WAAW,yBAAyB;IACxC,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,QAAQ,CAAC,K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