@entifix/service-shell 0.10.2 → 0.12.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.
Files changed (103) hide show
  1. package/README.md +1 -4
  2. package/dist/auth/index.d.ts +1 -0
  3. package/dist/auth/index.d.ts.map +1 -1
  4. package/dist/auth/index.js +1 -0
  5. package/dist/auth/index.js.map +1 -1
  6. package/dist/auth/require-organization.d.ts +1 -1
  7. package/dist/auth/require-organization.d.ts.map +1 -1
  8. package/dist/auth/require-organization.js.map +1 -1
  9. package/dist/auth/require-principal.d.ts +9 -49
  10. package/dist/auth/require-principal.d.ts.map +1 -1
  11. package/dist/auth/require-principal.js +21 -15
  12. package/dist/auth/require-principal.js.map +1 -1
  13. package/dist/auth/require-service-crossing.d.ts.map +1 -1
  14. package/dist/auth/require-service-crossing.js +3 -13
  15. package/dist/auth/require-service-crossing.js.map +1 -1
  16. package/dist/auth/shared-token.d.ts +2 -0
  17. package/dist/auth/shared-token.d.ts.map +1 -1
  18. package/dist/auth/shared-token.js +2 -2
  19. package/dist/auth/shared-token.js.map +1 -1
  20. package/dist/auth/verified-context.d.ts +24 -0
  21. package/dist/auth/verified-context.d.ts.map +1 -0
  22. package/dist/auth/verified-context.js +40 -0
  23. package/dist/auth/verified-context.js.map +1 -0
  24. package/dist/entity-facet-routes.d.ts +7 -1
  25. package/dist/entity-facet-routes.d.ts.map +1 -1
  26. package/dist/entity-facet-routes.js +8 -5
  27. package/dist/entity-facet-routes.js.map +1 -1
  28. package/dist/entity-metadata-route.d.ts +2 -1
  29. package/dist/entity-metadata-route.d.ts.map +1 -1
  30. package/dist/entity-metadata-route.js +20 -3
  31. package/dist/entity-metadata-route.js.map +1 -1
  32. package/dist/entity-route-guard.d.ts +5 -3
  33. package/dist/entity-route-guard.d.ts.map +1 -1
  34. package/dist/entity-route-guard.js +12 -6
  35. package/dist/entity-route-guard.js.map +1 -1
  36. package/dist/entity-routes.d.ts +13 -1
  37. package/dist/entity-routes.d.ts.map +1 -1
  38. package/dist/entity-routes.js +20 -6
  39. package/dist/entity-routes.js.map +1 -1
  40. package/dist/http-api/build-api.d.ts +78 -0
  41. package/dist/http-api/build-api.d.ts.map +1 -0
  42. package/dist/http-api/build-api.js +189 -0
  43. package/dist/http-api/build-api.js.map +1 -0
  44. package/dist/http-api/entity-api.d.ts +69 -0
  45. package/dist/http-api/entity-api.d.ts.map +1 -0
  46. package/dist/http-api/entity-api.js +522 -0
  47. package/dist/http-api/entity-api.js.map +1 -0
  48. package/dist/http-api/guards.d.ts +92 -0
  49. package/dist/http-api/guards.d.ts.map +1 -0
  50. package/dist/http-api/guards.js +131 -0
  51. package/dist/http-api/guards.js.map +1 -0
  52. package/dist/http-api/index.d.ts +6 -0
  53. package/dist/http-api/index.d.ts.map +1 -0
  54. package/dist/http-api/index.js +7 -0
  55. package/dist/http-api/index.js.map +1 -0
  56. package/dist/http-api/problem-codec.d.ts +14 -0
  57. package/dist/http-api/problem-codec.d.ts.map +1 -0
  58. package/dist/http-api/problem-codec.js +26 -0
  59. package/dist/http-api/problem-codec.js.map +1 -0
  60. package/dist/http-api/service-group.d.ts +74 -0
  61. package/dist/http-api/service-group.d.ts.map +1 -0
  62. package/dist/http-api/service-group.js +168 -0
  63. package/dist/http-api/service-group.js.map +1 -0
  64. package/dist/idempotency.d.ts +64 -0
  65. package/dist/idempotency.d.ts.map +1 -0
  66. package/dist/idempotency.js +112 -0
  67. package/dist/idempotency.js.map +1 -0
  68. package/dist/index.d.ts +4 -2
  69. package/dist/index.d.ts.map +1 -1
  70. package/dist/index.js +4 -2
  71. package/dist/index.js.map +1 -1
  72. package/dist/make-service.d.ts +39 -6
  73. package/dist/make-service.d.ts.map +1 -1
  74. package/dist/make-service.js +54 -16
  75. package/dist/make-service.js.map +1 -1
  76. package/dist/metadata-composition.d.ts +28 -0
  77. package/dist/metadata-composition.d.ts.map +1 -0
  78. package/dist/metadata-composition.js +68 -0
  79. package/dist/metadata-composition.js.map +1 -0
  80. package/dist/narrowing.d.ts +13 -0
  81. package/dist/narrowing.d.ts.map +1 -0
  82. package/dist/narrowing.js +34 -0
  83. package/dist/narrowing.js.map +1 -0
  84. package/dist/respond.d.ts +6 -4
  85. package/dist/respond.d.ts.map +1 -1
  86. package/dist/respond.js +11 -7
  87. package/dist/respond.js.map +1 -1
  88. package/dist/serve-test-service.d.ts +2 -1
  89. package/dist/serve-test-service.d.ts.map +1 -1
  90. package/dist/serve-test-service.js.map +1 -1
  91. package/dist/sse.d.ts +7 -4
  92. package/dist/sse.d.ts.map +1 -1
  93. package/dist/sse.js +21 -5
  94. package/dist/sse.js.map +1 -1
  95. package/package.json +7 -6
  96. package/dist/health-routes.d.ts +0 -24
  97. package/dist/health-routes.d.ts.map +0 -1
  98. package/dist/health-routes.js +0 -86
  99. package/dist/health-routes.js.map +0 -1
  100. package/dist/service-description-route.d.ts +0 -66
  101. package/dist/service-description-route.d.ts.map +0 -1
  102. package/dist/service-description-route.js +0 -60
  103. package/dist/service-description-route.js.map +0 -1
@@ -0,0 +1,78 @@
1
+ import type { IdempotencyKeyTag, OrganizationIdTag, RequestPrincipalTag, VerifiedContextTag } from '@entifix/business';
2
+ import { type AnyEndpoint, type DeadlineTag, type FailureClass, type Implemented, Invalid } from '@entifix/core';
3
+ import { type FileSystem, Layer, type Path } from 'effect';
4
+ import type { Etag, HttpPlatform, HttpRouter } from 'effect/http';
5
+ import { HttpApi, HttpApiError, HttpApiMiddleware } from 'effect/http-api';
6
+ import { type FailurePolicy } from '../respond.js';
7
+ import { type GuardServices, type IdempotencyServices } from './guards.js';
8
+ /**
9
+ * A named set of implemented endpoints — one `HttpApiGroup` once built. A slice
10
+ * groups by entity or by concern; the name is what an OpenAPI document and a
11
+ * client namespace it under.
12
+ */
13
+ export interface EndpointGroup<Endpoint extends AnyEndpoint = AnyEndpoint, R = never> {
14
+ readonly name: string;
15
+ readonly endpoints: ReadonlyArray<Implemented<Endpoint, R>>;
16
+ }
17
+ /** Any group, whatever its handlers need — the constraint a builder takes. */
18
+ export type AnyEndpointGroup = EndpointGroup<AnyEndpoint, any>;
19
+ type EndpointOf<I> = I extends Implemented<infer D, any> ? D : never;
20
+ type RequirementsOf<I> = I extends Implemented<any, infer R> ? R : never;
21
+ /** Group implemented endpoints under one name. */
22
+ export declare const endpointGroup: <const Endpoints extends ReadonlyArray<Implemented<any, any>>>(name: string, ...endpoints: Endpoints) => EndpointGroup<EndpointOf<Endpoints[number]>, RequirementsOf<Endpoints[number]>>;
23
+ /** What the shell provides a handler: the verified request context. */
24
+ export type ProvidedToHandlers = RequestPrincipalTag | OrganizationIdTag | IdempotencyKeyTag | VerifiedContextTag | DeadlineTag;
25
+ /**
26
+ * What serving `Groups` requires of the composition root: what the handlers
27
+ * need beyond the request context, plus what each declared guard and
28
+ * idempotency mode reads. A host that omits one does not compile.
29
+ */
30
+ export type ServedRequirements<Groups extends ReadonlyArray<AnyEndpointGroup>> = GroupRequirements<Groups[number]>;
31
+ type GroupRequirements<Group> = Group extends EndpointGroup<infer Endpoint, infer R> ? Exclude<R, ProvidedToHandlers> | GuardServices<Endpoint['guard']['kind']> | IdempotencyServices<Endpoint['idempotent']> : never;
32
+ /** What serving an API needs from the HTTP server itself. */
33
+ export type ServedPlatform = HttpRouter.HttpRouter | Etag.Generator | FileSystem.FileSystem | HttpPlatform.HttpPlatform | Path.Path;
34
+ /** `METHOD /path` for every endpoint — what a register diffs a service against. */
35
+ export declare const endpointsOf: (groups: ReadonlyArray<AnyEndpointGroup>) => readonly string[];
36
+ /** The status a failure class answers with under `policy`. */
37
+ export declare const statusForClass: (failureClass: FailureClass, policy: FailurePolicy) => number;
38
+ declare const Respond_base: HttpApiMiddleware.ServiceClass<Respond, "@entifix/service-shell/Respond", {
39
+ requires: never;
40
+ provides: never;
41
+ error: never;
42
+ clientError: never;
43
+ requiredForClient: false;
44
+ security: never;
45
+ }, HttpApiMiddleware.HttpApiMiddleware<never, never, never>>;
46
+ /**
47
+ * The outermost middleware of every endpoint: `respond` under the API's
48
+ * policy, after a schema error has become `invalid` with one entry per broken
49
+ * field. A response that fails to encode is the service's own fault and stays
50
+ * a defect.
51
+ */
52
+ export declare class Respond extends Respond_base {
53
+ }
54
+ /** The `invalid` failure a request that fails its schema answers with. */
55
+ export declare const invalidRequest: (error: HttpApiError.HttpApiSchemaError) => Invalid;
56
+ export interface ApiOptions {
57
+ /** The status and log table; the framework's defaults when absent. */
58
+ readonly policy?: FailurePolicy;
59
+ }
60
+ /**
61
+ * The `HttpApi` a set of groups describes. Every endpoint's failures carry the
62
+ * status the policy gives them, and two endpoints that share a method and
63
+ * path throw here rather than shadowing each other at runtime.
64
+ */
65
+ export declare const buildApi: (name: string, groups: ReadonlyArray<AnyEndpointGroup>, options?: ApiOptions) => HttpApi.Top;
66
+ /**
67
+ * Serve `groups` under one API: the routes, every guard, the respond
68
+ * middleware. The layer requires what the handlers, guards and idempotency
69
+ * modes read, plus the HTTP platform the server provides.
70
+ */
71
+ export declare const serveApi: <const Groups extends ReadonlyArray<AnyEndpointGroup>>(api: HttpApi.Top, groups: Groups, options?: ApiOptions) => Layer.Layer<never, never, ServedRequirements<Groups> | ServedPlatform>;
72
+ /** Build and serve in one call, for a host that needs nothing between. */
73
+ export declare const serveEndpoints: <const Groups extends ReadonlyArray<AnyEndpointGroup>>(name: string, groups: Groups, options?: ApiOptions) => {
74
+ readonly api: HttpApi.Top;
75
+ readonly layer: Layer.Layer<never, never, ServedPlatform | GroupRequirements<Groups[number]>>;
76
+ };
77
+ export {};
78
+ //# sourceMappingURL=build-api.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"build-api.d.ts","sourceRoot":"","sources":["../../src/http-api/build-api.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,iBAAiB,EACjB,iBAAiB,EACjB,mBAAmB,EACnB,kBAAkB,EACnB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,KAAK,WAAW,EAGhB,KAAK,WAAW,EAGhB,KAAK,YAAY,EA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C;AAED;;;;GAIG;AACH,eAAO,MAAM,QAAQ,GACnB,MAAM,MAAM,EACZ,QAAQ,aAAa,CAAC,gBAAgB,CAAC,EACvC,UAAS,UAAe,KACvB,OAAO,CAAC,GA+BV,CAAC;AAEF;;;;GAIG;AACH,eAAO,MAAM,QAAQ,GAAI,KAAK,CAAC,MAAM,SAAS,aAAa,CAAC,gBAAgB,CAAC,EAC3E,KAAK,OAAO,CAAC,GAAG,EAChB,QAAQ,MAAM,EACd,UAAS,UAAe,KACvB,KAAK,CAAC,KAAK,CAAC,KAAK,EAAE,KAAK,EAAE,kBAAkB,CAAC,MAAM,CAAC,GAAG,cAAc,CAsBvE,CAAC;AAEF,0EAA0E;AAC1E,eAAO,MAAM,cAAc,GACzB,KAAK,CAAC,MAAM,SAAS,aAAa,CAAC,gBAAgB,CAAC,EAEpD,MAAM,MAAM,EACZ,QAAQ,MAAM,EACd,UAAS,UAAe;;;CAIzB,CAAC"}
@@ -0,0 +1,189 @@
1
+ import { _ as _extends } from "@swc/helpers/_/_extends";
2
+ import { bodyEncodingOf, Contention, Forbidden, IdempotencyKeyInFlight, IdempotencyKeyMissing, IdempotencyKeyReused, Internal, Invalid, Overloaded, ProtocolFailure, Timeout, Unauthenticated, Unavailable, UpstreamUnavailable } from '@entifix/core';
3
+ import { Effect, Layer, Schema, SchemaIssue } from 'effect';
4
+ import { HttpServerResponse } from 'effect/http';
5
+ import { HttpApi, HttpApiBuilder, HttpApiEndpoint, HttpApiError, HttpApiGroup, HttpApiMiddleware, HttpApiSchema } from 'effect/http-api';
6
+ import { NoActiveOrganization } from '../auth/failures.js';
7
+ import { defaultFailurePolicy, respond } from '../respond.js';
8
+ import { EndpointGuardAnnotation, EndpointIdempotencyAnnotation, GUARD_MIDDLEWARE, guardLayers, IdempotencyGuard } from './guards.js';
9
+ import { problemCodec } from './problem-codec.js';
10
+ /* eslint-enable @typescript-eslint/no-explicit-any */ /** Group implemented endpoints under one name. */ export const endpointGroup = (name, ...endpoints)=>({
11
+ name,
12
+ endpoints: endpoints
13
+ });
14
+ /** `METHOD /path` for every endpoint — what a register diffs a service against. */ export const endpointsOf = (groups)=>groups.flatMap((group)=>group.endpoints.map(({ descriptor })=>`${descriptor.method} ${descriptor.path}`));
15
+ /** The failures every endpoint may answer, whether or not it declares them. */ const TECHNICAL = [
16
+ Invalid,
17
+ Internal,
18
+ Unavailable,
19
+ UpstreamUnavailable,
20
+ Timeout,
21
+ Overloaded,
22
+ Contention,
23
+ ProtocolFailure
24
+ ];
25
+ const GUARD_FAILURES = {
26
+ public: [],
27
+ session: [
28
+ Unauthenticated
29
+ ],
30
+ permission: [
31
+ Unauthenticated,
32
+ Forbidden
33
+ ],
34
+ organization: [
35
+ Unauthenticated,
36
+ Forbidden,
37
+ NoActiveOrganization
38
+ ],
39
+ crossing: [
40
+ Unauthenticated,
41
+ Forbidden
42
+ ],
43
+ fleet: [
44
+ Unauthenticated
45
+ ]
46
+ };
47
+ const IDEMPOTENCY_FAILURES = [
48
+ IdempotencyKeyMissing,
49
+ IdempotencyKeyReused,
50
+ IdempotencyKeyInFlight
51
+ ];
52
+ /** The status a failure class answers with under `policy`. */ export const statusForClass = (failureClass, policy)=>{
53
+ var _policy_tagStatus_failureClass_identifier;
54
+ return (_policy_tagStatus_failureClass_identifier = policy.tagStatus[failureClass.identifier]) != null ? _policy_tagStatus_failureClass_identifier : policy.categoryStatus[failureClass.prototype.category];
55
+ };
56
+ const errorSchemas = (descriptor, policy)=>[
57
+ ...new Set([
58
+ ...descriptor.errors,
59
+ ...GUARD_FAILURES[descriptor.guard.kind],
60
+ ...descriptor.idempotent === undefined ? [] : IDEMPOTENCY_FAILURES,
61
+ ...TECHNICAL
62
+ ])
63
+ ].map((failureClass)=>problemCodec(failureClass, statusForClass(failureClass, policy)));
64
+ const toSchema = (schema)=>schema === undefined ? undefined : Schema.isSchema(schema) ? schema : Schema.Struct(schema);
65
+ /** A payload on the wire it declared: JSON unless it said text or a form. */ const toPayload = (schema)=>{
66
+ const payload = toSchema(schema);
67
+ if (payload === undefined) return undefined;
68
+ const encoding = bodyEncodingOf(payload);
69
+ switch(encoding == null ? void 0 : encoding.kind){
70
+ case 'text':
71
+ // A `textBody` is a string schema; the marker is what says so here.
72
+ return payload.pipe(HttpApiSchema.asText({
73
+ contentType: encoding.contentType
74
+ }));
75
+ case 'form':
76
+ return payload.pipe(HttpApiSchema.asFormUrlEncoded({
77
+ contentType: encoding.contentType
78
+ }));
79
+ default:
80
+ return payload;
81
+ }
82
+ };
83
+ /**
84
+ * The outermost middleware of every endpoint: `respond` under the API's
85
+ * policy, after a schema error has become `invalid` with one entry per broken
86
+ * field. A response that fails to encode is the service's own fault and stays
87
+ * a defect.
88
+ */ export class Respond extends HttpApiMiddleware.Service()('@entifix/service-shell/Respond') {
89
+ }
90
+ const formatIssues = SchemaIssue.makeFormatterStandardSchemaV1();
91
+ /** The `invalid` failure a request that fails its schema answers with. */ export const invalidRequest = (error)=>{
92
+ const where = error.kind.toLowerCase();
93
+ const { issues } = formatIssues(error.cause.issue);
94
+ return new Invalid({
95
+ errors: issues.map((issue)=>({
96
+ // Effect's formatter always sets the path — `[]` for the part itself —
97
+ // though the Standard Schema type it answers with leaves it optional.
98
+ pointer: `/${[
99
+ where,
100
+ ...issue.path.map(String)
101
+ ].join('/')}`,
102
+ detail: issue.message,
103
+ code: 'schema'
104
+ }))
105
+ });
106
+ };
107
+ const REQUEST_PARTS = new Set([
108
+ 'Params',
109
+ 'Query',
110
+ 'Payload',
111
+ 'Headers'
112
+ ]);
113
+ const respondLayer = (policy)=>Layer.succeed(Respond)((httpEffect)=>respond(httpEffect.pipe(Effect.catchIf((error)=>HttpApiError.HttpApiSchemaError.is(error) && REQUEST_PARTS.has(error.kind), (error)=>Effect.fail(invalidRequest(error)))), policy).pipe(Effect.map(uncachedByDefault)));
114
+ /**
115
+ * Every answer `no-store` unless its endpoint chose a cache policy of its own.
116
+ * An API answer carries a principal, a token or a tenant's records far more
117
+ * often than anything a cache could share, and a token response must not be
118
+ * stored at all (RFC 6749 §5.1) — so the safe default is the shell's, and an
119
+ * endpoint that wants caching (an `ETag`ed metadata document) says so.
120
+ */ const uncachedByDefault = (response)=>response.headers['cache-control'] === undefined ? HttpServerResponse.setHeader(response, 'cache-control', 'no-store') : response;
121
+ const toEndpoint = (descriptor, policy)=>{
122
+ const params = toSchema(descriptor.params);
123
+ const query = toSchema(descriptor.query);
124
+ const payload = toPayload(descriptor.payload);
125
+ const headers = toSchema(descriptor.headers);
126
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- assembled at runtime
127
+ let endpoint = HttpApiEndpoint.make(descriptor.method)(descriptor.name, descriptor.path, _extends({}, params === undefined ? {} : {
128
+ params
129
+ }, query === undefined ? {} : {
130
+ query
131
+ }, payload === undefined ? {} : {
132
+ payload
133
+ }, headers === undefined ? {} : {
134
+ headers
135
+ }, {
136
+ success: descriptor.success,
137
+ error: errorSchemas(descriptor, policy)
138
+ })).annotate(EndpointGuardAnnotation, descriptor.guard);
139
+ // Order is outermost last: idempotency runs inside the guard, so it sees
140
+ // the principal the guard verified; `Respond` wraps everything.
141
+ if (descriptor.idempotent !== undefined) endpoint = endpoint.annotate(EndpointIdempotencyAnnotation, descriptor.idempotent).middleware(IdempotencyGuard);
142
+ const guard = GUARD_MIDDLEWARE[descriptor.guard.kind];
143
+ if (guard !== undefined) endpoint = endpoint.middleware(guard);
144
+ return endpoint.middleware(Respond);
145
+ };
146
+ /**
147
+ * The `HttpApi` a set of groups describes. Every endpoint's failures carry the
148
+ * status the policy gives them, and two endpoints that share a method and
149
+ * path throw here rather than shadowing each other at runtime.
150
+ */ export const buildApi = (name, groups, options = {})=>{
151
+ var _options_policy;
152
+ const policy = (_options_policy = options.policy) != null ? _options_policy : defaultFailurePolicy;
153
+ const seen = new Set();
154
+ for (const target of endpointsOf(groups)){
155
+ if (seen.has(target)) throw new Error(`'${name}' declares ${target} twice`);
156
+ seen.add(target);
157
+ }
158
+ // A group serves its endpoints by name, so a second one under a name would
159
+ // silently replace the first rather than fail.
160
+ for (const group of groups){
161
+ const names = new Set();
162
+ for (const { descriptor } of group.endpoints){
163
+ if (names.has(descriptor.name)) throw new Error(`'${name}' names two endpoints '${descriptor.name}' in '${group.name}'`);
164
+ names.add(descriptor.name);
165
+ }
166
+ }
167
+ return groups.reduce((api, group)=>api.add(group.endpoints.reduce(// eslint-disable-next-line @typescript-eslint/no-explicit-any -- assembled at runtime
168
+ (built, { descriptor })=>built.add(toEndpoint(descriptor, policy)), HttpApiGroup.make(group.name))), HttpApi.make(name));
169
+ };
170
+ /**
171
+ * Serve `groups` under one API: the routes, every guard, the respond
172
+ * middleware. The layer requires what the handlers, guards and idempotency
173
+ * modes read, plus the HTTP platform the server provides.
174
+ */ export const serveApi = (api, groups, options = {})=>{
175
+ var _options_policy;
176
+ const handlers = groups.map((group)=>HttpApiBuilder.group(api, group.name, // eslint-disable-next-line @typescript-eslint/no-explicit-any -- assembled at runtime
177
+ (handle)=>group.endpoints.reduce(// eslint-disable-next-line @typescript-eslint/no-explicit-any
178
+ (built, { descriptor, handler })=>built.handle(descriptor.name, handler), handle)));
179
+ return HttpApiBuilder.layer(api).pipe(Layer.provide(Layer.mergeAll(...handlers)), Layer.provide(guardLayers), Layer.provide(respondLayer((_options_policy = options.policy) != null ? _options_policy : defaultFailurePolicy)));
180
+ };
181
+ /** Build and serve in one call, for a host that needs nothing between. */ export const serveEndpoints = (name, groups, options = {})=>{
182
+ const api = buildApi(name, groups, options);
183
+ return {
184
+ api,
185
+ layer: serveApi(api, groups, options)
186
+ };
187
+ };
188
+
189
+ //# sourceMappingURL=build-api.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/http-api/build-api.ts"],"sourcesContent":["import type {\n IdempotencyKeyTag,\n OrganizationIdTag,\n RequestPrincipalTag,\n VerifiedContextTag,\n} from '@entifix/business';\nimport {\n type AnyEndpoint,\n bodyEncodingOf,\n Contention,\n type DeadlineTag,\n type EndpointSchema,\n type EntifixFailure,\n type FailureClass,\n Forbidden,\n IdempotencyKeyInFlight,\n IdempotencyKeyMissing,\n IdempotencyKeyReused,\n type Implemented,\n Internal,\n Invalid,\n Overloaded,\n ProtocolFailure,\n Timeout,\n Unauthenticated,\n Unavailable,\n UpstreamUnavailable,\n} from '@entifix/core';\nimport {\n Effect,\n type FileSystem,\n Layer,\n type Path,\n Schema,\n SchemaIssue,\n} from 'effect';\nimport type { Etag, HttpPlatform, HttpRouter } from 'effect/http';\nimport { HttpServerResponse } from 'effect/http';\nimport {\n HttpApi,\n HttpApiBuilder,\n HttpApiEndpoint,\n HttpApiError,\n HttpApiGroup,\n HttpApiMiddleware,\n HttpApiSchema,\n} from 'effect/http-api';\n\nimport { NoActiveOrganization } from '../auth/failures.js';\nimport {\n defaultFailurePolicy,\n type FailurePolicy,\n respond,\n} from '../respond.js';\nimport {\n EndpointGuardAnnotation,\n EndpointIdempotencyAnnotation,\n GUARD_MIDDLEWARE,\n guardLayers,\n type GuardServices,\n IdempotencyGuard,\n type IdempotencyServices,\n} from './guards.js';\nimport { problemCodec } from './problem-codec.js';\n\n/**\n * A named set of implemented endpoints — one `HttpApiGroup` once built. A slice\n * groups by entity or by concern; the name is what an OpenAPI document and a\n * client namespace it under.\n */\nexport interface EndpointGroup<\n Endpoint extends AnyEndpoint = AnyEndpoint,\n R = never,\n> {\n readonly name: string;\n readonly endpoints: ReadonlyArray<Implemented<Endpoint, R>>;\n}\n\n/** Any group, whatever its handlers need — the constraint a builder takes. */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- a constraint\nexport type AnyEndpointGroup = EndpointGroup<AnyEndpoint, any>;\n\n/* eslint-disable @typescript-eslint/no-explicit-any -- inference sites */\ntype EndpointOf<I> = I extends Implemented<infer D, any> ? D : never;\ntype RequirementsOf<I> = I extends Implemented<any, infer R> ? R : never;\n/* eslint-enable @typescript-eslint/no-explicit-any */\n\n/** Group implemented endpoints under one name. */\nexport const endpointGroup = <\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const Endpoints extends ReadonlyArray<Implemented<any, any>>,\n>(\n name: string,\n ...endpoints: Endpoints\n): EndpointGroup<\n EndpointOf<Endpoints[number]>,\n RequirementsOf<Endpoints[number]>\n> => ({\n name,\n endpoints: endpoints as never,\n});\n\n/** What the shell provides a handler: the verified request context. */\nexport type ProvidedToHandlers =\n | RequestPrincipalTag\n | OrganizationIdTag\n | IdempotencyKeyTag\n | VerifiedContextTag\n | DeadlineTag;\n\n/**\n * What serving `Groups` requires of the composition root: what the handlers\n * need beyond the request context, plus what each declared guard and\n * idempotency mode reads. A host that omits one does not compile.\n */\nexport type ServedRequirements<Groups extends ReadonlyArray<AnyEndpointGroup>> =\n GroupRequirements<Groups[number]>;\n\n// Distributive over the groups, and `never` for none.\ntype GroupRequirements<Group> =\n Group extends EndpointGroup<infer Endpoint, infer R>\n ? | Exclude<R, ProvidedToHandlers>\n | GuardServices<Endpoint['guard']['kind']>\n | IdempotencyServices<Endpoint['idempotent']>\n : never;\n\n/** What serving an API needs from the HTTP server itself. */\nexport type ServedPlatform =\n | HttpRouter.HttpRouter\n | Etag.Generator\n | FileSystem.FileSystem\n | HttpPlatform.HttpPlatform\n | Path.Path;\n\n/** `METHOD /path` for every endpoint — what a register diffs a service against. */\nexport const endpointsOf = (\n groups: ReadonlyArray<AnyEndpointGroup>,\n): readonly string[] =>\n groups.flatMap(group =>\n group.endpoints.map(\n ({ descriptor }) => `${descriptor.method} ${descriptor.path}`,\n ),\n );\n\n/** The failures every endpoint may answer, whether or not it declares them. */\nconst TECHNICAL: readonly FailureClass[] = [\n Invalid,\n Internal,\n Unavailable,\n UpstreamUnavailable,\n Timeout,\n Overloaded,\n Contention,\n ProtocolFailure,\n];\n\nconst GUARD_FAILURES: Readonly<\n Record<AnyEndpoint['guard']['kind'], readonly FailureClass[]>\n> = {\n public: [],\n session: [Unauthenticated],\n permission: [Unauthenticated, Forbidden],\n organization: [Unauthenticated, Forbidden, NoActiveOrganization],\n crossing: [Unauthenticated, Forbidden],\n fleet: [Unauthenticated],\n};\n\nconst IDEMPOTENCY_FAILURES: readonly FailureClass[] = [\n IdempotencyKeyMissing,\n IdempotencyKeyReused,\n IdempotencyKeyInFlight,\n];\n\n/** The status a failure class answers with under `policy`. */\nexport const statusForClass = (\n failureClass: FailureClass,\n policy: FailurePolicy,\n): number =>\n policy.tagStatus[failureClass.identifier] ??\n policy.categoryStatus[\n (failureClass.prototype as unknown as EntifixFailure).category\n ];\n\nconst errorSchemas = (descriptor: AnyEndpoint, policy: FailurePolicy) =>\n [\n ...new Set([\n ...descriptor.errors,\n ...GUARD_FAILURES[descriptor.guard.kind],\n ...(descriptor.idempotent === undefined ? [] : IDEMPOTENCY_FAILURES),\n ...TECHNICAL,\n ]),\n ].map(failureClass =>\n problemCodec(failureClass, statusForClass(failureClass, policy)),\n );\n\nconst toSchema = (schema: EndpointSchema | undefined) =>\n schema === undefined\n ? undefined\n : Schema.isSchema(schema)\n ? schema\n : Schema.Struct(schema);\n\n/** A payload on the wire it declared: JSON unless it said text or a form. */\nconst toPayload = (schema: EndpointSchema | undefined) => {\n const payload = toSchema(schema);\n if (payload === undefined) return undefined;\n const encoding = bodyEncodingOf(payload);\n switch (encoding?.kind) {\n case 'text':\n // A `textBody` is a string schema; the marker is what says so here.\n return (payload as Schema.String).pipe(\n HttpApiSchema.asText({ contentType: encoding.contentType }),\n );\n case 'form':\n return payload.pipe(\n HttpApiSchema.asFormUrlEncoded({ contentType: encoding.contentType }),\n );\n default:\n return payload;\n }\n};\n\n/**\n * The outermost middleware of every endpoint: `respond` under the API's\n * policy, after a schema error has become `invalid` with one entry per broken\n * field. A response that fails to encode is the service's own fault and stays\n * a defect.\n */\nexport class Respond extends HttpApiMiddleware.Service<Respond>()(\n '@entifix/service-shell/Respond',\n) {}\n\nconst formatIssues = SchemaIssue.makeFormatterStandardSchemaV1();\n\n/** The `invalid` failure a request that fails its schema answers with. */\nexport const invalidRequest = (\n error: HttpApiError.HttpApiSchemaError,\n): Invalid => {\n const where = error.kind.toLowerCase();\n const { issues } = formatIssues(error.cause.issue);\n return new Invalid({\n errors: issues.map(issue => ({\n // Effect's formatter always sets the path — `[]` for the part itself —\n // though the Standard Schema type it answers with leaves it optional.\n pointer: `/${[where, ...(issue.path as readonly PropertyKey[]).map(String)].join('/')}`,\n detail: issue.message,\n code: 'schema',\n })),\n });\n};\n\nconst REQUEST_PARTS: ReadonlySet<HttpApiError.HttpApiSchemaError['kind']> =\n new Set(['Params', 'Query', 'Payload', 'Headers']);\n\nconst respondLayer = (policy: FailurePolicy) =>\n Layer.succeed(Respond)(((httpEffect: Effect.Effect<never, unknown, never>) =>\n respond(\n httpEffect.pipe(\n Effect.catchIf(\n (error: unknown): error is HttpApiError.HttpApiSchemaError =>\n HttpApiError.HttpApiSchemaError.is(error) &&\n REQUEST_PARTS.has(error.kind),\n error => Effect.fail(invalidRequest(error)),\n ),\n ) as never,\n policy,\n ).pipe(Effect.map(uncachedByDefault))) as never);\n\n/**\n * Every answer `no-store` unless its endpoint chose a cache policy of its own.\n * An API answer carries a principal, a token or a tenant's records far more\n * often than anything a cache could share, and a token response must not be\n * stored at all (RFC 6749 §5.1) — so the safe default is the shell's, and an\n * endpoint that wants caching (an `ETag`ed metadata document) says so.\n */\nconst uncachedByDefault = (\n response: HttpServerResponse.HttpServerResponse,\n): HttpServerResponse.HttpServerResponse =>\n response.headers['cache-control'] === undefined\n ? HttpServerResponse.setHeader(response, 'cache-control', 'no-store')\n : response;\n\nconst toEndpoint = (descriptor: AnyEndpoint, policy: FailurePolicy) => {\n const params = toSchema(descriptor.params);\n const query = toSchema(descriptor.query);\n const payload = toPayload(descriptor.payload);\n const headers = toSchema(descriptor.headers);\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- assembled at runtime\n let endpoint: any = HttpApiEndpoint.make(descriptor.method)(\n descriptor.name,\n descriptor.path,\n {\n ...(params === undefined ? {} : { params }),\n ...(query === undefined ? {} : { query }),\n ...(payload === undefined ? {} : { payload }),\n ...(headers === undefined ? {} : { headers }),\n success: descriptor.success,\n error: errorSchemas(descriptor, policy),\n } as never,\n ).annotate(EndpointGuardAnnotation, descriptor.guard);\n // Order is outermost last: idempotency runs inside the guard, so it sees\n // the principal the guard verified; `Respond` wraps everything.\n if (descriptor.idempotent !== undefined)\n endpoint = endpoint\n .annotate(EndpointIdempotencyAnnotation, descriptor.idempotent)\n .middleware(IdempotencyGuard);\n const guard = GUARD_MIDDLEWARE[descriptor.guard.kind];\n if (guard !== undefined) endpoint = endpoint.middleware(guard);\n return endpoint.middleware(Respond);\n};\n\nexport interface ApiOptions {\n /** The status and log table; the framework's defaults when absent. */\n readonly policy?: FailurePolicy;\n}\n\n/**\n * The `HttpApi` a set of groups describes. Every endpoint's failures carry the\n * status the policy gives them, and two endpoints that share a method and\n * path throw here rather than shadowing each other at runtime.\n */\nexport const buildApi = (\n name: string,\n groups: ReadonlyArray<AnyEndpointGroup>,\n options: ApiOptions = {},\n): HttpApi.Top => {\n const policy = options.policy ?? defaultFailurePolicy;\n const seen = new Set<string>();\n for (const target of endpointsOf(groups)) {\n if (seen.has(target)) throw new Error(`'${name}' declares ${target} twice`);\n seen.add(target);\n }\n // A group serves its endpoints by name, so a second one under a name would\n // silently replace the first rather than fail.\n for (const group of groups) {\n const names = new Set<string>();\n for (const { descriptor } of group.endpoints) {\n if (names.has(descriptor.name))\n throw new Error(\n `'${name}' names two endpoints '${descriptor.name}' in '${group.name}'`,\n );\n names.add(descriptor.name);\n }\n }\n return groups.reduce<HttpApi.Top>(\n (api, group) =>\n api.add(\n group.endpoints.reduce(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- assembled at runtime\n (built: any, { descriptor }) =>\n built.add(toEndpoint(descriptor, policy)),\n HttpApiGroup.make(group.name),\n ),\n ) as HttpApi.Top,\n HttpApi.make(name) as unknown as HttpApi.Top,\n );\n};\n\n/**\n * Serve `groups` under one API: the routes, every guard, the respond\n * middleware. The layer requires what the handlers, guards and idempotency\n * modes read, plus the HTTP platform the server provides.\n */\nexport const serveApi = <const Groups extends ReadonlyArray<AnyEndpointGroup>>(\n api: HttpApi.Top,\n groups: Groups,\n options: ApiOptions = {},\n): Layer.Layer<never, never, ServedRequirements<Groups> | ServedPlatform> => {\n const handlers = groups.map(group =>\n HttpApiBuilder.group(\n api as never,\n group.name as never,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- assembled at runtime\n (handle: any) =>\n group.endpoints.reduce(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (built: any, { descriptor, handler }) =>\n built.handle(descriptor.name, handler),\n handle,\n ),\n ),\n );\n return HttpApiBuilder.layer(api as never).pipe(\n Layer.provide(\n Layer.mergeAll(...(handlers as unknown as [Layer.Layer<never>])),\n ),\n Layer.provide(guardLayers),\n Layer.provide(respondLayer(options.policy ?? defaultFailurePolicy)),\n ) as never;\n};\n\n/** Build and serve in one call, for a host that needs nothing between. */\nexport const serveEndpoints = <\n const Groups extends ReadonlyArray<AnyEndpointGroup>,\n>(\n name: string,\n groups: Groups,\n options: ApiOptions = {},\n) => {\n const api = buildApi(name, groups, options);\n return { api, layer: serveApi(api, groups, options) } as const;\n};\n"],"names":["bodyEncodingOf","Contention","Forbidden","IdempotencyKeyInFlight","IdempotencyKeyMissing","IdempotencyKeyReused","Internal","Invalid","Overloaded","ProtocolFailure","Timeout","Unauthenticated","Unavailable","UpstreamUnavailable","Effect","Layer","Schema","SchemaIssue","HttpServerResponse","HttpApi","HttpApiBuilder","HttpApiEndpoint","HttpApiError","HttpApiGroup","HttpApiMiddleware","HttpApiSchema","NoActiveOrganization","defaultFailurePolicy","respond","EndpointGuardAnnotation","EndpointIdempotencyAnnotation","GUARD_MIDDLEWARE","guardLayers","IdempotencyGuard","problemCodec","endpointGroup","name","endpoints","endpointsOf","groups","flatMap","group","map","descriptor","method","path","TECHNICAL","GUARD_FAILURES","public","session","permission","organization","crossing","fleet","IDEMPOTENCY_FAILURES","statusForClass","failureClass","policy","tagStatus","identifier","categoryStatus","prototype","category","errorSchemas","Set","errors","guard","kind","idempotent","undefined","toSchema","schema","isSchema","Struct","toPayload","payload","encoding","pipe","asText","contentType","asFormUrlEncoded","Respond","Service","formatIssues","makeFormatterStandardSchemaV1","invalidRequest","error","where","toLowerCase","issues","cause","issue","pointer","String","join","detail","message","code","REQUEST_PARTS","respondLayer","succeed","httpEffect","catchIf","HttpApiSchemaError","is","has","fail","uncachedByDefault","response","headers","setHeader","toEndpoint","params","query","endpoint","make","success","annotate","middleware","buildApi","options","seen","target","Error","add","names","reduce","api","built","serveApi","handlers","handle","handler","layer","provide","mergeAll","serveEndpoints"],"mappings":";AAMA,SAEEA,cAAc,EACdC,UAAU,EAKVC,SAAS,EACTC,sBAAsB,EACtBC,qBAAqB,EACrBC,oBAAoB,EAEpBC,QAAQ,EACRC,OAAO,EACPC,UAAU,EACVC,eAAe,EACfC,OAAO,EACPC,eAAe,EACfC,WAAW,EACXC,mBAAmB,QACd,gBAAgB;AACvB,SACEC,MAAM,EAENC,KAAK,EAELC,MAAM,EACNC,WAAW,QACN,SAAS;AAEhB,SAASC,kBAAkB,QAAQ,cAAc;AACjD,SACEC,OAAO,EACPC,cAAc,EACdC,eAAe,EACfC,YAAY,EACZC,YAAY,EACZC,iBAAiB,EACjBC,aAAa,QACR,kBAAkB;AAEzB,SAASC,oBAAoB,QAAQ,sBAAsB;AAC3D,SACEC,oBAAoB,EAEpBC,OAAO,QACF,gBAAgB;AACvB,SACEC,uBAAuB,EACvBC,6BAA6B,EAC7BC,gBAAgB,EAChBC,WAAW,EAEXC,gBAAgB,QAEX,cAAc;AACrB,SAASC,YAAY,QAAQ,qBAAqB;AAsBlD,oDAAoD,GAEpD,gDAAgD,GAChD,OAAO,MAAMC,gBAAgB,CAI3BC,MACA,GAAGC,YAIC,CAAA;QACJD;QACAC,WAAWA;IACb,CAAA,EAAG;AAkCH,iFAAiF,GACjF,OAAO,MAAMC,cAAc,CACzBC,SAEAA,OAAOC,OAAO,CAACC,CAAAA,QACbA,MAAMJ,SAAS,C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,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"}
@@ -0,0 +1,69 @@
1
+ import { PolicyDecisionTag } from '@entifix/authz';
2
+ import { type EntityApiDeclaration, type EntityApiOptions, EntityFacetCounterFactoryTag, EntityRepositoryFactoryTag } from '@entifix/business';
3
+ import { type AnyEndpoint, type EndpointGuard, type Entity } from '@entifix/core';
4
+ import { Effect } from 'effect';
5
+ import { type MetadataCompositions } from '../metadata-composition.js';
6
+ import type { EndpointGroup } from './build-api.js';
7
+ type KindOf<G> = G extends {
8
+ readonly kind: infer Kind;
9
+ } ? Kind : G extends {
10
+ readonly read: infer Read;
11
+ readonly write: infer Write;
12
+ } ? KindOf<Read> | KindOf<Write> : never;
13
+ type OverrideValues<O> = O extends {
14
+ readonly override: infer Overrides;
15
+ } ? Overrides extends object ? NonNullable<Overrides[keyof Overrides]> : never : never;
16
+ type OverrideGuardKinds<V> = V extends {
17
+ readonly guard: infer G;
18
+ } ? KindOf<G> : never;
19
+ type OverrideIdempotency<V> = V extends {
20
+ readonly idempotent: infer I;
21
+ } ? I : never;
22
+ type UseCaseValues<O> = O extends {
23
+ readonly useCases: infer U;
24
+ } ? U extends ReadonlyArray<infer V> ? V : never : never;
25
+ /** Every guard kind an entity group mounts: `$metadata` is a session. */
26
+ export type EntityGuardKinds<O> = Extract<'session' | KindOf<O extends {
27
+ readonly guard: infer G;
28
+ } ? G : never> | OverrideGuardKinds<OverrideValues<O> | UseCaseValues<O>>, EndpointGuard['kind']>;
29
+ /** Every idempotency mode an entity group's overrides and verbs declare. */
30
+ export type EntityIdempotencies<O> = OverrideIdempotency<OverrideValues<O> | UseCaseValues<O>>;
31
+ type ReturnRequirements<F> = F extends (...args: any[]) => Effect.Effect<any, any, infer R> ? R : never;
32
+ type OverrideRequirements<V> = V extends {
33
+ readonly handler: infer H;
34
+ } ? ReturnRequirements<H> : never;
35
+ /** What the host's `prepare` and overrides need. */
36
+ export type OptionsRequirements<O> = ReturnRequirements<O extends {
37
+ readonly prepare: infer P;
38
+ } ? P : never> | OverrideRequirements<OverrideValues<O> | UseCaseValues<O>>;
39
+ /** An entity endpoint as its guard kinds and idempotency type it. */
40
+ export type EntityEndpoint<Kind extends EndpointGuard['kind'], Idempotency> = AnyEndpoint & {
41
+ readonly guard: Extract<EndpointGuard, {
42
+ readonly kind: Kind;
43
+ }>;
44
+ readonly idempotent?: Idempotency;
45
+ };
46
+ /** What the shell adds when it serves an entity's declared endpoints. */
47
+ export interface EntityApiServing {
48
+ /** The compositions `$metadata` reports for the entity's verbs. */
49
+ readonly compositions?: MetadataCompositions;
50
+ }
51
+ /**
52
+ * The generic endpoints of an entity — list, get, create, update, delete,
53
+ * `$metadata` and, when asked, `$facets` — as one group named for its key
54
+ * ([ADR 0020](../../../../../docs/adr/0020-endpoints-are-descriptors-and-the-shell-builds-an-httpapi.md)).
55
+ *
56
+ * `$metadata` and `$facets` come before `/:id`, so neither is read as an id.
57
+ * The list query is the entity's RSQL request, parsed against its own
58
+ * `filterable`/`sortable` metadata: a member that is not queryable answers
59
+ * `invalidQuery`. A narrowing is conjoined onto every read and count, never
60
+ * substituted, and a reader it leaves with nothing gets an empty page and a
61
+ * `404`, never a `403`.
62
+ *
63
+ * It serves a declaration the domain made with `defineEntityApi`; what the
64
+ * shell alone knows — the recipes and variants `$metadata` resolves verbs
65
+ * against — is added here.
66
+ */
67
+ export declare const entityApi: <T extends Entity, const K extends string, const O extends EntityApiOptions<T, any>>(declaration: EntityApiDeclaration<T, K, O>, serving?: EntityApiServing) => EndpointGroup<EntityEndpoint<EntityGuardKinds<O>, EntityIdempotencies<O>>, OptionsRequirements<O> | EntityRepositoryFactoryTag | PolicyDecisionTag | (O["facets"] extends true ? EntityFacetCounterFactoryTag : never)>;
68
+ export {};
69
+ //# sourceMappingURL=entity-api.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"entity-api.d.ts","sourceRoot":"","sources":["../../src/http-api/entity-api.ts"],"names":[],"mappings":"AAEA,OAAO,EAML,iBAAiB,EAClB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAGL,KAAK,oBAAoB,EAGzB,KAAK,gBAAgB,EAGrB,4BAA4B,EAI5B,0BAA0B,EAa3B,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,KAAK,WAAW,EAGhB,KAAK,aAAa,EAClB,KAAK,MAAM,EAqBZ,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,MAAM,EAAkB,MAAM,QAAQ,CAAC;AAIhD,OAAO,EAGL,KAAK,oBAAoB,EAC1B,MAAM,4BAA4B,CAAC;AAMpC,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAyFpD,KAAK,MAAM,CAAC,CAAC,IAAI,CAAC,SAAS;IAAE,QAAQ,CAAC,IAAI,EAAE,MAAM,IAAI,CAAA;CAAE,GACpD,IAAI,GACJ,CAAC,SAAS;IAAE,QAAQ,CAAC,IAAI,EAAE,MAAM,IAAI,CAAC;IAAC,QAAQ,CAAC,KAAK,EAAE,MAAM,KAAK,CAAA;CAAE,GAClE,MAAM,CAAC,IAAI,CAAC,GAAG,MAAM,CAAC,KAAK,CAAC,GAC5B,KAAK,CAAC;AAEZ,KAAK,cAAc,CAAC,CAAC,I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