@entifix/service-shell 0.10.2 → 0.11.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/dist/auth/index.d.ts +1 -0
- package/dist/auth/index.d.ts.map +1 -1
- package/dist/auth/index.js +1 -0
- package/dist/auth/index.js.map +1 -1
- package/dist/auth/require-principal.d.ts +6 -0
- package/dist/auth/require-principal.d.ts.map +1 -1
- package/dist/auth/require-principal.js +6 -2
- package/dist/auth/require-principal.js.map +1 -1
- package/dist/auth/verified-context.d.ts +25 -0
- package/dist/auth/verified-context.d.ts.map +1 -0
- package/dist/auth/verified-context.js +40 -0
- package/dist/auth/verified-context.js.map +1 -0
- package/dist/entity-facet-routes.d.ts +6 -0
- package/dist/entity-facet-routes.d.ts.map +1 -1
- package/dist/entity-facet-routes.js +8 -5
- package/dist/entity-facet-routes.js.map +1 -1
- package/dist/entity-metadata-route.d.ts +2 -1
- package/dist/entity-metadata-route.d.ts.map +1 -1
- package/dist/entity-metadata-route.js +20 -3
- package/dist/entity-metadata-route.js.map +1 -1
- package/dist/entity-route-guard.d.ts +4 -2
- package/dist/entity-route-guard.d.ts.map +1 -1
- package/dist/entity-route-guard.js +12 -6
- package/dist/entity-route-guard.js.map +1 -1
- package/dist/entity-routes.d.ts +13 -1
- package/dist/entity-routes.d.ts.map +1 -1
- package/dist/entity-routes.js +20 -6
- package/dist/entity-routes.js.map +1 -1
- package/dist/idempotency.d.ts +59 -0
- package/dist/idempotency.d.ts.map +1 -0
- package/dist/idempotency.js +107 -0
- package/dist/idempotency.js.map +1 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -1
- package/dist/metadata-composition.d.ts +28 -0
- package/dist/metadata-composition.d.ts.map +1 -0
- package/dist/metadata-composition.js +68 -0
- package/dist/metadata-composition.js.map +1 -0
- package/dist/narrowing.d.ts +27 -0
- package/dist/narrowing.d.ts.map +1 -0
- package/dist/narrowing.js +34 -0
- package/dist/narrowing.js.map +1 -0
- package/dist/sse.d.ts +7 -4
- package/dist/sse.d.ts.map +1 -1
- package/dist/sse.js +21 -5
- package/dist/sse.js.map +1 -1
- package/package.json +6 -6
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"entity-routes.d.ts","sourceRoot":"","sources":["../src/entity-routes.ts"],"names":[],"mappings":"AACA,OAAO,EAIL,0BAA0B,EAM3B,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,KAAK,iBAAiB,EACtB,KAAK,mBAAmB,EACxB,KAAK,MAAM,EACX,KAAK,iBAAiB,EACtB,KAAK,QAAQ,EASd,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAChC,OAAO,EAAE,UAAU,EAAqB,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAGhF,OAAO,EACL,KAAK,eAAe,EACpB,KAAK,kBAAkB,EACvB,KAAK,gBAAgB,EAGtB,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAEL,KAAK,aAAa,EAEnB,MAAM,cAAc,CAAC;AACtB,OAAO,EACL,KAAK,kBAAkB,EAEvB,YAAY,EACb,MAAM,sBAAsB,CAAC;AAE9B,oDAAoD;AACpD,MAAM,MAAM,UAAU,GAAG,MAAM,GAAG,KAAK,GAAG,QAAQ,GAAG,QAAQ,GAAG,QAAQ,CAAC;AAEzE,OAAO,EACL,KAAK,eAAe,EACpB,KAAK,kBAAkB,EACvB,KAAK,gBAAgB,GACtB,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAE1D,4EAA4E;AAC5E,MAAM,MAAM,mBAAmB,CAAC,CAAC,IAAI,CACnC,OAAO,EAAE,kBAAkB,EAC3B,KAAK,EAAE,gBAAgB,KACpB,MAAM,CAAC,MAAM,CAAC,kBAAkB,CAAC,kBAAkB,EAAE,OAAO,EAAE,CAAC,CAAC,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,QAAQ,CAAC,YAAY,CAAC,EAAE,oBAAoB,CAAC;IAC7C,gFAAgF;IAChF,QAAQ,CAAC,KAAK,CAAC,EAAE,CACf,OAAO,EAAE,kBAAkB,KACxB,MAAM,CAAC,MAAM,CAAC,eAAe,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC;IACjD;;;OAGG;IACH,QAAQ,CAAC,OAAO,CAAC,EAAE,CACjB,MAAM,EAAE,CAAC,EACT,OAAO,EAAE,kBAAkB,GAAG;QAAE,QAAQ,CAAC,IAAI,EAAE,QAAQ,GAAG,QAAQ,CAAA;KAAE,KACjE,MAAM,CAAC,MAAM,CAAC,CAAC,EAAE,kBAAkB,GAAG,iBAAiB,EAAE,CAAC,CAAC,CAAC;IACjE;;;;OAIG;IACH,QAAQ,CAAC,QAAQ,CAAC,EAAE,OAAO,CAAC,MAAM,CAAC,UAAU,EAAE,mBAAmB,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IACxE;;;OAGG;IACH,QAAQ,CAAC,MAAM,CAAC,EAAE,aAAa,CAAC;CACjC;AA6UD;;;;;;GAMG;AACH,OAAO,EAAE,YAAY,EAAE,CAAC;AAExB,eAAO,MAAM,gBAAgB,IA1T3B,CAAC,SAAS,MAAM,EAChB,CAAC,gBAOK,CAAC,SAAS,gBAAgB,6BAEb,iBAAiB,CAAC,CAAC,CAAC,WAC9B,mBAAmB,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC;;;UAiTlC,CAAC,QACD,CAAC,SAAS,MAAM,QAAQ,CAAC,SAAS,gBAAgB,qBAC9B,iBAAiB,CAAC,CAAC,CAAC,WAC9B,mBAAmB,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC;;;CAGzC,CAAC"}
|
package/dist/entity-routes.js
CHANGED
|
@@ -5,6 +5,7 @@ import { Effect } from 'effect';
|
|
|
5
5
|
import { HttpRouter, HttpServerRequest, HttpServerResponse } from 'effect/http';
|
|
6
6
|
import { entityMetadataRoute } from './entity-metadata-route.js';
|
|
7
7
|
import { guardRoute } from './entity-route-guard.js';
|
|
8
|
+
import { narrowedByIdRequest, narrowingFor, narrowLoadRequest } from './narrowing.js';
|
|
8
9
|
import { defaultFailurePolicy, respond } from './respond.js';
|
|
9
10
|
import { legacyAnswer, routeFailure } from './route-responses.js';
|
|
10
11
|
export { EntityRouteRefusal } from './route-responses.js';
|
|
@@ -34,7 +35,7 @@ const READS = new Set([
|
|
|
34
35
|
* A path that is not one of these verbs is written by hand beside it, and a
|
|
35
36
|
* verb whose generic form does not fit is replaced with `override`.
|
|
36
37
|
*/ const deriveEntityRoutes = (entityConstructor, options)=>{
|
|
37
|
-
var _options_basePath;
|
|
38
|
+
var _options_basePath, _options_compositions;
|
|
38
39
|
const key = envelopeEntityName(entityConstructor);
|
|
39
40
|
const base = (_options_basePath = options.basePath) != null ? _options_basePath : `/api/${key}`;
|
|
40
41
|
const mounted = new Set(options.verbs);
|
|
@@ -100,7 +101,9 @@ const READS = new Set([
|
|
|
100
101
|
organizationId: context.organizationId
|
|
101
102
|
}));
|
|
102
103
|
});
|
|
104
|
+
if (options.narrowing !== undefined && options.scope !== undefined) throw new Error(`the routes for '${extractMetaEntity(entityConstructor).key}' name both ` + '`narrowing` and `scope`; `narrowing` replaces `scope`, so name one.');
|
|
103
105
|
const scopeOf = (context)=>options.scope ? options.scope(context) : Effect.succeed('all');
|
|
106
|
+
/** The narrowing rules choose for this caller, or `undefined` without rules. */ const narrowingOf = (context)=>options.narrowing === undefined || context.verified === undefined ? undefined : narrowingFor(options.narrowing, context.verified);
|
|
104
107
|
const readLoadRequest = Effect.gen(function*() {
|
|
105
108
|
const request = yield* HttpServerRequest.HttpServerRequest;
|
|
106
109
|
const search = new URL(request.url, 'http://localhost').searchParams;
|
|
@@ -115,10 +118,11 @@ const READS = new Set([
|
|
|
115
118
|
const list = (context)=>Effect.gen(function*() {
|
|
116
119
|
var _parsed_filtering;
|
|
117
120
|
const parsed = yield* readLoadRequest;
|
|
118
|
-
const
|
|
121
|
+
const narrowing = narrowingOf(context);
|
|
122
|
+
const scope = narrowing === undefined ? yield* scopeOf(context) : narrowing === 'nothing' ? 'none' : 'all';
|
|
119
123
|
if (scope === 'none') {
|
|
120
124
|
// Still parsed: whether a query is well-formed must not depend on who
|
|
121
|
-
// asked.
|
|
125
|
+
// asked. `nothing` answers here without a query.
|
|
122
126
|
return yield* HttpServerResponse.json(makeEntityPageEnvelope(entityConstructor, {
|
|
123
127
|
items: [],
|
|
124
128
|
total: 0,
|
|
@@ -128,7 +132,7 @@ const READS = new Set([
|
|
|
128
132
|
// Conjoined, never substituted: the translator `$and`s every top-level
|
|
129
133
|
// element, so an added element can only narrow, and no `or` in a query
|
|
130
134
|
// string can escape it.
|
|
131
|
-
const request = scope === 'all' ? parsed : _extends({}, parsed, {
|
|
135
|
+
const request = narrowing !== undefined && narrowing !== 'nothing' ? narrowLoadRequest(parsed, narrowing) : scope === 'all' ? parsed : _extends({}, parsed, {
|
|
132
136
|
filtering: [
|
|
133
137
|
...(_parsed_filtering = parsed.filtering) != null ? _parsed_filtering : [],
|
|
134
138
|
scope.filter
|
|
@@ -139,7 +143,17 @@ const READS = new Set([
|
|
|
139
143
|
}).pipe(Effect.catch(legacyAnswer('invalidQuery')));
|
|
140
144
|
const get = (context)=>Effect.gen(function*() {
|
|
141
145
|
const params = yield* HttpRouter.params;
|
|
142
|
-
const
|
|
146
|
+
const narrowing = narrowingOf(context);
|
|
147
|
+
if (narrowing === 'nothing') return yield* notFound;
|
|
148
|
+
// A filter narrowing reads by id as a narrowed load, so the read and the
|
|
149
|
+
// list apply one rule: there is no second, in-memory predicate to drift.
|
|
150
|
+
if (narrowing !== undefined && narrowing !== 'unscoped') {
|
|
151
|
+
const page = yield* loadUCFactory().pipe(Effect.provideService(EntityRepositoryTag, (yield* repository(context))), Effect.provideService(EntityLoadRequestTag, narrowedByIdRequest(narrowing, params.id)));
|
|
152
|
+
const [only] = page.items;
|
|
153
|
+
if (only === undefined) return yield* notFound;
|
|
154
|
+
return yield* HttpServerResponse.json(makeEntityEnvelope(entityConstructor, only, links.record(params.id)));
|
|
155
|
+
}
|
|
156
|
+
const scope = narrowing === undefined ? yield* scopeOf(context) : 'all';
|
|
143
157
|
if (scope === 'none') return yield* notFound;
|
|
144
158
|
const found = yield* getUCFactory().pipe(Effect.provideService(EntityRepositoryTag, (yield* repository(context))), Effect.provideService(EntityIdTag, params.id), Effect.option);
|
|
145
159
|
// Out of scope answers exactly as absent does: a `403` would confirm the
|
|
@@ -235,7 +249,7 @@ const READS = new Set([
|
|
|
235
249
|
};
|
|
236
250
|
return HttpRouter.addAll([
|
|
237
251
|
// A literal, so it wins over `/:id` regardless of order.
|
|
238
|
-
HttpRouter.route('GET', `${base}/$metadata`, entityMetadataRoute(entityConstructor)),
|
|
252
|
+
HttpRouter.route('GET', `${base}/$metadata`, entityMetadataRoute(entityConstructor, (_options_compositions = options.compositions) != null ? _options_compositions : {})),
|
|
239
253
|
...options.verbs.map((verb)=>HttpRouter.route(ROUTES[verb].method, ROUTES[verb].path, handlerFor(verb)))
|
|
240
254
|
]);
|
|
241
255
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/entity-routes.ts"],"sourcesContent":["import type { Action } from '@entifix/authz';\nimport {\n deleteUCFactory,\n EntityIdTag,\n EntityLoadRequestTag,\n EntityRepositoryFactoryTag,\n EntityRepositoryTag,\n EntityTag,\n getUCFactory,\n loadUCFactory,\n saveUCFactory,\n} from '@entifix/business';\nimport {\n type EntifixBuildError,\n type EntifixEnvelopeLink,\n type Entity,\n type EntityConstructor,\n type EntityId,\n type EntityLoadRequest,\n envelopeEntityName,\n extractMetaEntity,\n makeEntityEnvelope,\n makeEntityPageEnvelope,\n NotFound,\n parseLoadRequestParams,\n readEntityEnvelope,\n} from '@entifix/core';\nimport { Effect } from 'effect';\nimport { HttpRouter, HttpServerRequest, HttpServerResponse } from 'effect/http';\n\nimport { entityMetadataRoute } from './entity-metadata-route.js';\nimport {\n type EntityReadScope,\n type EntityRouteContext,\n type EntityRouteGuard,\n guardRoute,\n type GuardServices,\n} from './entity-route-guard.js';\nimport {\n defaultFailurePolicy,\n type FailurePolicy,\n respond,\n} from './respond.js';\nimport {\n type EntityRouteRefusal,\n legacyAnswer,\n routeFailure,\n} from './route-responses.js';\n\n/** The five generic verbs a route set can mount. */\nexport type EntityVerb = 'list' | 'get' | 'create' | 'update' | 'delete';\n\nexport {\n type EntityReadScope,\n type EntityRouteContext,\n type EntityRouteGuard,\n} from './entity-route-guard.js';\nexport { EntityRouteRefusal } from './route-responses.js';\n\n/** A hand-written handler for one verb, mounted under the derived guard. */\nexport type EntityRouteOverride<R> = (\n context: EntityRouteContext,\n links: EntityRouteLinks,\n) => Effect.Effect<HttpServerResponse.HttpServerResponse, unknown, R>;\n\n/** The affordances a route set derives from the verbs it mounts. */\nexport interface EntityRouteLinks {\n readonly record: (id: EntityId) => EntifixEnvelopeLink[];\n readonly collection: () => EntifixEnvelopeLink[];\n}\n\nexport interface EntityRoutesOptions<\n T extends Entity,\n R,\n G extends EntityRouteGuard = EntityRouteGuard,\n> {\n readonly verbs: readonly EntityVerb[];\n /** One guard for every verb, or one for the reads and one for the writes. */\n readonly guard: G | { readonly read: G; readonly write: G };\n /** Defaults to `/api/<entity key>`. */\n readonly basePath?: `/${string}`;\n /** Narrows the reads to what this caller may see. */\n readonly scope?: (\n context: EntityRouteContext,\n ) => Effect.Effect<EntityReadScope<T>, never, R>;\n /**\n * Runs on every create and update, after the body is read and before the\n * save — and may change what is saved, or refuse it.\n */\n readonly prepare?: (\n entity: T,\n context: EntityRouteContext & { readonly verb: 'create' | 'update' },\n ) => Effect.Effect<T, EntityRouteRefusal | EntifixBuildError, R>;\n /**\n * A hand-written handler in place of the generic one for a verb. It keeps\n * the derived guard and receives the derived links, so the escape hatch\n * cannot drift from the rest of the set.\n */\n readonly override?: Partial<Record<EntityVerb, EntityRouteOverride<R>>>;\n /**\n * How every verb's failures are answered and logged. Defaults to\n * {@link defaultFailurePolicy}; a host passes its fleet policy.\n */\n readonly policy?: FailurePolicy;\n}\n\nconst ACTION: Record<EntityVerb, Action> = {\n list: 'read',\n get: 'read',\n create: 'write',\n update: 'write',\n delete: 'delete',\n};\n\nconst READS: ReadonlySet<EntityVerb> = new Set(['list', 'get']);\n\n/**\n * The generic routes for one entity — list, read, create, update, delete and\n * its `$metadata` — derived from the entity and bound to storage through the\n * host's {@link EntityRepositoryFactoryTag}.\n *\n * What a route set varies on is stated, not written: which verbs exist, who may\n * reach them, which records a reader sees, and what a save must pass. What it\n * never varies on is the wire: the load request is parsed against the entity's\n * own metadata (so a query can only name a member the entity declared\n * filterable or sortable), every answer is an envelope, and the links name\n * exactly the verbs mounted — never one that would `404`.\n *\n * A path that is not one of these verbs is written by hand beside it, and a\n * verb whose generic form does not fit is replaced with `override`.\n */\nconst deriveEntityRoutes = <\n T extends Entity,\n R = never,\n // `never`, not the whole union: TypeScript infers no type argument once a\n // caller names one, so `makeEntityRoutes<T, R>(…)` used to default `G` to\n // every guard. Then the crossing tags became requirements of a route that\n // guards on a session, and the error surfaced at the host's `Layer.provide`\n // instead of here. Defaulting to `never` refuses that call at the guard\n // itself; `makeEntityRoutes.for<R>()` is the way to name `R` alone.\n const G extends EntityRouteGuard = never,\n>(\n entityConstructor: EntityConstructor<T>,\n options: EntityRoutesOptions<T, R, G>,\n) => {\n const key = envelopeEntityName(entityConstructor);\n const base: `/${string}` = options.basePath ?? `/api/${key}`;\n const mounted = new Set(options.verbs);\n\n const links: EntityRouteLinks = {\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 ];\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 ],\n };\n\n const guardFor = (verb: EntityVerb): EntityRouteGuard => {\n const guard = options.guard as\n | EntityRouteGuard\n | { readonly read: EntityRouteGuard; readonly write: EntityRouteGuard };\n return 'kind' in guard ? guard : READS.has(verb) ? guard.read : guard.write;\n };\n\n const guarded = <A, E, RR>(\n verb: EntityVerb,\n use: (context: EntityRouteContext) => Effect.Effect<A, E, RR>,\n ) => guardRoute(entityConstructor, guardFor(verb), ACTION[verb], use);\n\n const repository = (context: EntityRouteContext) =>\n Effect.gen(function* () {\n const factory = yield* EntityRepositoryFactoryTag;\n return yield* factory.for(entityConstructor, {\n ...(context.organizationId === undefined\n ? {}\n : { organizationId: context.organizationId }),\n });\n });\n\n const scopeOf = (context: EntityRouteContext) =>\n options.scope ? options.scope(context) : Effect.succeed('all' as const);\n\n const readLoadRequest = Effect.gen(function* () {\n const request = yield* HttpServerRequest.HttpServerRequest;\n const search = new URL(request.url, 'http://localhost').searchParams;\n return yield* Effect.try({\n try: () =>\n parseLoadRequestParams(\n entityConstructor,\n search,\n ) as unknown as EntityLoadRequest<T>,\n catch: error => error as EntifixBuildError,\n });\n });\n\n const notFound = Effect.fail(\n new NotFound({ entity: extractMetaEntity(entityConstructor).key }),\n );\n\n const list = (context: EntityRouteContext) =>\n Effect.gen(function* () {\n const parsed = yield* readLoadRequest;\n const scope = yield* scopeOf(context);\n if (scope === 'none') {\n // Still parsed: whether a query is well-formed must not depend on who\n // asked.\n return yield* HttpServerResponse.json(\n makeEntityPageEnvelope(\n entityConstructor,\n { items: [], total: 0, request: parsed },\n links.collection(),\n ),\n );\n }\n // Conjoined, never substituted: the translator `$and`s every top-level\n // element, so an added element can only narrow, and no `or` in a query\n // string can escape it.\n const request: EntityLoadRequest<T> =\n scope === 'all'\n ? parsed\n : {\n ...parsed,\n filtering: [...(parsed.filtering ?? []), scope.filter],\n };\n const page = yield* loadUCFactory<T>().pipe(\n Effect.provideService(EntityRepositoryTag, yield* repository(context)),\n Effect.provideService(\n EntityLoadRequestTag,\n request as unknown as EntityLoadRequest,\n ),\n );\n return yield* HttpServerResponse.json(\n makeEntityPageEnvelope(entityConstructor, page, links.collection()),\n );\n }).pipe(Effect.catch(legacyAnswer('invalidQuery')));\n\n const get = (context: EntityRouteContext) =>\n Effect.gen(function* () {\n const params = yield* HttpRouter.params;\n const scope = yield* scopeOf(context);\n if (scope === 'none') return yield* notFound;\n const found = yield* getUCFactory<T>().pipe(\n Effect.provideService(EntityRepositoryTag, yield* repository(context)),\n Effect.provideService(EntityIdTag, params.id),\n Effect.option,\n );\n // Out of scope answers exactly as absent does: a `403` would confirm the\n // record exists to somebody who may not read it.\n if (\n found._tag === 'None' ||\n (scope !== 'all' && !scope.includes(found.value))\n ) {\n return yield* notFound;\n }\n return yield* HttpServerResponse.json(\n makeEntityEnvelope(\n entityConstructor,\n found.value,\n links.record(params.id),\n ),\n );\n }).pipe(Effect.catch(legacyAnswer('invalid')));\n\n const save = (verb: 'create' | 'update') => (context: EntityRouteContext) =>\n Effect.gen(function* () {\n const request = yield* HttpServerRequest.HttpServerRequest;\n const body = yield* request.json;\n let entity = yield* readEntityEnvelope(entityConstructor, body);\n\n // On update the URL is authoritative, so a record cannot be renamed\n // onto another one by editing its payload.\n if (verb === 'update') {\n const params = yield* HttpRouter.params;\n entity.id = params.id;\n }\n if (options.prepare) {\n entity = yield* options.prepare(entity, { ...context, verb });\n }\n\n const saved = yield* saveUCFactory<T>().pipe(\n Effect.provideService(EntityRepositoryTag, yield* repository(context)),\n Effect.provideService(EntityTag, entity),\n );\n return yield* HttpServerResponse.json(\n makeEntityEnvelope(entityConstructor, saved, links.record(saved.id)),\n );\n }).pipe(Effect.catch(legacyAnswer('invalidBody')));\n\n /**\n * Answers with an envelope rather than a bare `204`: every message between\n * entifix artifacts is one, and the fetch client parses every response as\n * JSON.\n */\n const remove = (context: EntityRouteContext) =>\n Effect.gen(function* () {\n const params = yield* HttpRouter.params;\n yield* deleteUCFactory<T>().pipe(\n Effect.provideService(EntityRepositoryTag, yield* repository(context)),\n Effect.provideService(EntityIdTag, params.id),\n );\n return yield* HttpServerResponse.json({\n meta: { type: 'entity', entity: key, links: links.collection() },\n data: { id: params.id },\n });\n }).pipe(Effect.catch(legacyAnswer('invalid')));\n\n const generic = (verb: EntityVerb, context: EntityRouteContext) => {\n switch (verb) {\n case 'list':\n return list(context);\n case 'get':\n return get(context);\n case 'create':\n return save('create')(context);\n case 'update':\n return save('update')(context);\n case 'delete':\n return remove(context);\n }\n };\n\n /**\n * Each guard asks for different services, so the branches do not unify on\n * their own; the cast states the union every guard this set can reach\n * actually needs.\n */\n const handlerFor = (verb: EntityVerb) =>\n respond(\n (\n guarded(verb, context => {\n const override = options.override?.[verb];\n return override ? override(context, links) : generic(verb, context);\n }) as Effect.Effect<\n HttpServerResponse.HttpServerResponse,\n unknown,\n | R\n | EntityRepositoryFactoryTag\n | GuardServices<G>\n | HttpServerRequest.HttpServerRequest\n | HttpRouter.RouteContext\n >\n ).pipe(Effect.catch(legacyAnswer('invalid'))),\n options.policy ?? defaultFailurePolicy,\n );\n\n const ROUTES: Record<\n EntityVerb,\n { method: 'GET' | 'POST' | 'PUT' | 'DELETE'; path: `/${string}` }\n > = {\n list: { method: 'GET', path: base },\n get: { method: 'GET', path: `${base}/:id` },\n create: { method: 'POST', path: base },\n update: { method: 'PUT', path: `${base}/:id` },\n delete: { method: 'DELETE', path: `${base}/:id` },\n };\n\n return HttpRouter.addAll([\n // A literal, so it wins over `/:id` regardless of order.\n HttpRouter.route(\n 'GET',\n `${base}/$metadata`,\n entityMetadataRoute(entityConstructor),\n ),\n ...options.verbs.map(verb =>\n HttpRouter.route(\n ROUTES[verb].method,\n ROUTES[verb].path,\n handlerFor(verb),\n ),\n ),\n ]);\n};\n\n/**\n * {@link deriveEntityRoutes}, with a curried form for a caller that has to\n * name the services its `override`, `scope` or `prepare` handlers need:\n * `makeEntityRoutes.for<R>()(Entity, options)` names `R` and still infers the\n * entity and the guard from the value, which a single call with explicit type\n * arguments cannot do.\n */\nexport { routeFailure };\n\nexport const makeEntityRoutes = Object.assign(deriveEntityRoutes, {\n for:\n <R>() =>\n <T extends Entity, const G extends EntityRouteGuard>(\n entityConstructor: EntityConstructor<T>,\n options: EntityRoutesOptions<T, R, G>,\n ) =>\n deriveEntityRoutes<T, R, G>(entityConstructor, options),\n});\n"],"names":["deleteUCFactory","EntityIdTag","EntityLoadRequestTag","EntityRepositoryFactoryTag","EntityRepositoryTag","EntityTag","getUCFactory","loadUCFactory","saveUCFactory","envelopeEntityName","extractMetaEntity","makeEntityEnvelope","makeEntityPageEnvelope","NotFound","parseLoadRequestParams","readEntityEnvelope","Effect","HttpRouter","HttpServerRequest","HttpServerResponse","entityMetadataRoute","guardRoute","defaultFailurePolicy","respond","legacyAnswer","routeFailure","EntityRouteRefusal","ACTION","list","get","create","update","delete","READS","Set","deriveEntityRoutes","entityConstructor","options","key","base","basePath","mounted","verbs","links","record","id","href","String","has","rel","method","collection","guardFor","verb","guard","read","write","guarded","use","repository","context","gen","factory","for","organizationId","undefined","scopeOf","scope","succeed","readLoadRequest","request","search","URL","url","searchParams","try","catch","error","notFound","fail","entity","parsed","json","items","total","filtering","filter","page","pipe","provideService","params","found","option","_tag","includes","value","save","body","prepare","saved","remove","meta","type","data","generic","handlerFor","override","policy","ROUTES","path","addAll","route","map","makeEntityRoutes","Object","assign"],"mappings":";AACA,SACEA,eAAe,EACfC,WAAW,EACXC,oBAAoB,EACpBC,0BAA0B,EAC1BC,mBAAmB,EACnBC,SAAS,EACTC,YAAY,EACZC,aAAa,EACbC,aAAa,QACR,oBAAoB;AAC3B,SAOEC,kBAAkB,EAClBC,iBAAiB,EACjBC,kBAAkB,EAClBC,sBAAsB,EACtBC,QAAQ,EACRC,sBAAsB,EACtBC,kBAAkB,QACb,gBAAgB;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;QAAC;QAC7CP,QAAQ;YAAEkB,QAAQ;YAAU2D,MAAM,GAAGtE,KAAK,IAAI,CAAC;QAAC;IAClD;IAEA,OAAOtB,WAAW6F,MAAM,CAAC;QACvB,yDAAyD;QACzD7F,WAAW8F,KAAK,CACd,OACA,GAAGxE,KAAK,UAAU,CAAC,EACnBnB,oBAAoBgB;WAEnBC,QAAQK,KAAK,CAACsE,GAAG,CAAC3D,CAAAA,OACnBpC,WAAW8F,KAAK,CACdH,MAAM,CAACvD,KAAK,CAACH,MAAM,EACnB0D,MAAM,CAACvD,KAAK,CAACwD,IAAI,EACjBJ,WAAWpD;KAGhB;AACH;AAEA;;;;;;CAMC,GACD,SAAS5B,YAAY,GAAG;AAExB,OAAO,MAAMwF,mBAAmBC,OAAOC,MAAM,CAAChF,oBAAoB;IAChE4B,KACE,IACA,CACE3B,mBACAC,UAEAF,mBAA4BC,mBAAmBC;AACrD,GAAG"}
|
|
1
|
+
{"version":3,"sources":["../src/entity-routes.ts"],"sourcesContent":["import type { Action } from '@entifix/authz';\nimport {\n deleteUCFactory,\n EntityIdTag,\n EntityLoadRequestTag,\n EntityRepositoryFactoryTag,\n EntityRepositoryTag,\n EntityTag,\n getUCFactory,\n loadUCFactory,\n saveUCFactory,\n} from '@entifix/business';\nimport {\n type EntifixBuildError,\n type EntifixEnvelopeLink,\n type Entity,\n type EntityConstructor,\n type EntityId,\n type EntityLoadRequest,\n envelopeEntityName,\n extractMetaEntity,\n makeEntityEnvelope,\n makeEntityPageEnvelope,\n NotFound,\n parseLoadRequestParams,\n readEntityEnvelope,\n} from '@entifix/core';\nimport { Effect } from 'effect';\nimport { HttpRouter, HttpServerRequest, HttpServerResponse } from 'effect/http';\n\nimport { entityMetadataRoute } from './entity-metadata-route.js';\nimport {\n type EntityReadScope,\n type EntityRouteContext,\n type EntityRouteGuard,\n guardRoute,\n type GuardServices,\n} from './entity-route-guard.js';\nimport type { MetadataCompositions } from './metadata-composition.js';\nimport {\n narrowedByIdRequest,\n narrowingFor,\n type NarrowingRules,\n narrowLoadRequest,\n} from './narrowing.js';\nimport {\n defaultFailurePolicy,\n type FailurePolicy,\n respond,\n} from './respond.js';\nimport {\n type EntityRouteRefusal,\n legacyAnswer,\n routeFailure,\n} from './route-responses.js';\n\n/** The five generic verbs a route set can mount. */\nexport type EntityVerb = 'list' | 'get' | 'create' | 'update' | 'delete';\n\nexport {\n type EntityReadScope,\n type EntityRouteContext,\n type EntityRouteGuard,\n} from './entity-route-guard.js';\nexport { EntityRouteRefusal } from './route-responses.js';\n\n/** A hand-written handler for one verb, mounted under the derived guard. */\nexport type EntityRouteOverride<R> = (\n context: EntityRouteContext,\n links: EntityRouteLinks,\n) => Effect.Effect<HttpServerResponse.HttpServerResponse, unknown, R>;\n\n/** The affordances a route set derives from the verbs it mounts. */\nexport interface EntityRouteLinks {\n readonly record: (id: EntityId) => EntifixEnvelopeLink[];\n readonly collection: () => EntifixEnvelopeLink[];\n}\n\nexport interface EntityRoutesOptions<\n T extends Entity,\n R,\n G extends EntityRouteGuard = EntityRouteGuard,\n> {\n readonly verbs: readonly EntityVerb[];\n /** One guard for every verb, or one for the reads and one for the writes. */\n readonly guard: G | { readonly read: G; readonly write: G };\n /** Defaults to `/api/<entity key>`. */\n readonly basePath?: `/${string}`;\n /**\n * Narrows the reads to what this caller may see, as resolver rules over the\n * verified context. Replaces `scope`; a route set naming both throws.\n */\n readonly narrowing?: NarrowingRules<T>;\n /**\n * The variant rules, recipes and catalog the entity's `@useCase()` verbs\n * name, so `$metadata` can report what each resolves to for the caller.\n */\n readonly compositions?: MetadataCompositions;\n /** Narrows the reads to what this caller may see. Superseded by `narrowing`. */\n readonly scope?: (\n context: EntityRouteContext,\n ) => Effect.Effect<EntityReadScope<T>, never, R>;\n /**\n * Runs on every create and update, after the body is read and before the\n * save — and may change what is saved, or refuse it.\n */\n readonly prepare?: (\n entity: T,\n context: EntityRouteContext & { readonly verb: 'create' | 'update' },\n ) => Effect.Effect<T, EntityRouteRefusal | EntifixBuildError, R>;\n /**\n * A hand-written handler in place of the generic one for a verb. It keeps\n * the derived guard and receives the derived links, so the escape hatch\n * cannot drift from the rest of the set.\n */\n readonly override?: Partial<Record<EntityVerb, EntityRouteOverride<R>>>;\n /**\n * How every verb's failures are answered and logged. Defaults to\n * {@link defaultFailurePolicy}; a host passes its fleet policy.\n */\n readonly policy?: FailurePolicy;\n}\n\nconst ACTION: Record<EntityVerb, Action> = {\n list: 'read',\n get: 'read',\n create: 'write',\n update: 'write',\n delete: 'delete',\n};\n\nconst READS: ReadonlySet<EntityVerb> = new Set(['list', 'get']);\n\n/**\n * The generic routes for one entity — list, read, create, update, delete and\n * its `$metadata` — derived from the entity and bound to storage through the\n * host's {@link EntityRepositoryFactoryTag}.\n *\n * What a route set varies on is stated, not written: which verbs exist, who may\n * reach them, which records a reader sees, and what a save must pass. What it\n * never varies on is the wire: the load request is parsed against the entity's\n * own metadata (so a query can only name a member the entity declared\n * filterable or sortable), every answer is an envelope, and the links name\n * exactly the verbs mounted — never one that would `404`.\n *\n * A path that is not one of these verbs is written by hand beside it, and a\n * verb whose generic form does not fit is replaced with `override`.\n */\nconst deriveEntityRoutes = <\n T extends Entity,\n R = never,\n // `never`, not the whole union: TypeScript infers no type argument once a\n // caller names one, so `makeEntityRoutes<T, R>(…)` used to default `G` to\n // every guard. Then the crossing tags became requirements of a route that\n // guards on a session, and the error surfaced at the host's `Layer.provide`\n // instead of here. Defaulting to `never` refuses that call at the guard\n // itself; `makeEntityRoutes.for<R>()` is the way to name `R` alone.\n const G extends EntityRouteGuard = never,\n>(\n entityConstructor: EntityConstructor<T>,\n options: EntityRoutesOptions<T, R, G>,\n) => {\n const key = envelopeEntityName(entityConstructor);\n const base: `/${string}` = options.basePath ?? `/api/${key}`;\n const mounted = new Set(options.verbs);\n\n const links: EntityRouteLinks = {\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 ];\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 ],\n };\n\n const guardFor = (verb: EntityVerb): EntityRouteGuard => {\n const guard = options.guard as\n | EntityRouteGuard\n | { readonly read: EntityRouteGuard; readonly write: EntityRouteGuard };\n return 'kind' in guard ? guard : READS.has(verb) ? guard.read : guard.write;\n };\n\n const guarded = <A, E, RR>(\n verb: EntityVerb,\n use: (context: EntityRouteContext) => Effect.Effect<A, E, RR>,\n ) => guardRoute(entityConstructor, guardFor(verb), ACTION[verb], use);\n\n const repository = (context: EntityRouteContext) =>\n Effect.gen(function* () {\n const factory = yield* EntityRepositoryFactoryTag;\n return yield* factory.for(entityConstructor, {\n ...(context.organizationId === undefined\n ? {}\n : { organizationId: context.organizationId }),\n });\n });\n\n if (options.narrowing !== undefined && options.scope !== undefined)\n throw new Error(\n `the routes for '${extractMetaEntity(entityConstructor).key}' name both ` +\n '`narrowing` and `scope`; `narrowing` replaces `scope`, so name one.',\n );\n\n const scopeOf = (context: EntityRouteContext) =>\n options.scope ? options.scope(context) : Effect.succeed('all' as const);\n\n /** The narrowing rules choose for this caller, or `undefined` without rules. */\n const narrowingOf = (context: EntityRouteContext) =>\n options.narrowing === undefined || context.verified === undefined\n ? undefined\n : narrowingFor(options.narrowing, context.verified);\n\n const readLoadRequest = Effect.gen(function* () {\n const request = yield* HttpServerRequest.HttpServerRequest;\n const search = new URL(request.url, 'http://localhost').searchParams;\n return yield* Effect.try({\n try: () =>\n parseLoadRequestParams(\n entityConstructor,\n search,\n ) as unknown as EntityLoadRequest<T>,\n catch: error => error as EntifixBuildError,\n });\n });\n\n const notFound = Effect.fail(\n new NotFound({ entity: extractMetaEntity(entityConstructor).key }),\n );\n\n const list = (context: EntityRouteContext) =>\n Effect.gen(function* () {\n const parsed = yield* readLoadRequest;\n const narrowing = narrowingOf(context);\n const scope =\n narrowing === undefined\n ? yield* scopeOf(context)\n : narrowing === 'nothing'\n ? ('none' as const)\n : ('all' as const);\n if (scope === 'none') {\n // Still parsed: whether a query is well-formed must not depend on who\n // asked. `nothing` answers here without a query.\n return yield* HttpServerResponse.json(\n makeEntityPageEnvelope(\n entityConstructor,\n { items: [], total: 0, request: parsed },\n links.collection(),\n ),\n );\n }\n // Conjoined, never substituted: the translator `$and`s every top-level\n // element, so an added element can only narrow, and no `or` in a query\n // string can escape it.\n const request: EntityLoadRequest<T> =\n narrowing !== undefined && narrowing !== 'nothing'\n ? narrowLoadRequest(parsed, narrowing)\n : scope === 'all'\n ? parsed\n : {\n ...parsed,\n filtering: [...(parsed.filtering ?? []), scope.filter],\n };\n const page = yield* loadUCFactory<T>().pipe(\n Effect.provideService(EntityRepositoryTag, yield* repository(context)),\n Effect.provideService(\n EntityLoadRequestTag,\n request as unknown as EntityLoadRequest,\n ),\n );\n return yield* HttpServerResponse.json(\n makeEntityPageEnvelope(entityConstructor, page, links.collection()),\n );\n }).pipe(Effect.catch(legacyAnswer('invalidQuery')));\n\n const get = (context: EntityRouteContext) =>\n Effect.gen(function* () {\n const params = yield* HttpRouter.params;\n const narrowing = narrowingOf(context);\n if (narrowing === 'nothing') return yield* notFound;\n // A filter narrowing reads by id as a narrowed load, so the read and the\n // list apply one rule: there is no second, in-memory predicate to drift.\n if (narrowing !== undefined && narrowing !== 'unscoped') {\n const page = yield* loadUCFactory<T>().pipe(\n Effect.provideService(\n EntityRepositoryTag,\n yield* repository(context),\n ),\n Effect.provideService(\n EntityLoadRequestTag,\n narrowedByIdRequest<T>(\n narrowing,\n params.id,\n ) as unknown as EntityLoadRequest,\n ),\n );\n const [only] = page.items;\n if (only === undefined) return yield* notFound;\n return yield* HttpServerResponse.json(\n makeEntityEnvelope(entityConstructor, only, links.record(params.id)),\n );\n }\n const scope = narrowing === undefined ? yield* scopeOf(context) : 'all';\n if (scope === 'none') return yield* notFound;\n const found = yield* getUCFactory<T>().pipe(\n Effect.provideService(EntityRepositoryTag, yield* repository(context)),\n Effect.provideService(EntityIdTag, params.id),\n Effect.option,\n );\n // Out of scope answers exactly as absent does: a `403` would confirm the\n // record exists to somebody who may not read it.\n if (\n found._tag === 'None' ||\n (scope !== 'all' && !scope.includes(found.value))\n ) {\n return yield* notFound;\n }\n return yield* HttpServerResponse.json(\n makeEntityEnvelope(\n entityConstructor,\n found.value,\n links.record(params.id),\n ),\n );\n }).pipe(Effect.catch(legacyAnswer('invalid')));\n\n const save = (verb: 'create' | 'update') => (context: EntityRouteContext) =>\n Effect.gen(function* () {\n const request = yield* HttpServerRequest.HttpServerRequest;\n const body = yield* request.json;\n let entity = yield* readEntityEnvelope(entityConstructor, body);\n\n // On update the URL is authoritative, so a record cannot be renamed\n // onto another one by editing its payload.\n if (verb === 'update') {\n const params = yield* HttpRouter.params;\n entity.id = params.id;\n }\n if (options.prepare) {\n entity = yield* options.prepare(entity, { ...context, verb });\n }\n\n const saved = yield* saveUCFactory<T>().pipe(\n Effect.provideService(EntityRepositoryTag, yield* repository(context)),\n Effect.provideService(EntityTag, entity),\n );\n return yield* HttpServerResponse.json(\n makeEntityEnvelope(entityConstructor, saved, links.record(saved.id)),\n );\n }).pipe(Effect.catch(legacyAnswer('invalidBody')));\n\n /**\n * Answers with an envelope rather than a bare `204`: every message between\n * entifix artifacts is one, and the fetch client parses every response as\n * JSON.\n */\n const remove = (context: EntityRouteContext) =>\n Effect.gen(function* () {\n const params = yield* HttpRouter.params;\n yield* deleteUCFactory<T>().pipe(\n Effect.provideService(EntityRepositoryTag, yield* repository(context)),\n Effect.provideService(EntityIdTag, params.id),\n );\n return yield* HttpServerResponse.json({\n meta: { type: 'entity', entity: key, links: links.collection() },\n data: { id: params.id },\n });\n }).pipe(Effect.catch(legacyAnswer('invalid')));\n\n const generic = (verb: EntityVerb, context: EntityRouteContext) => {\n switch (verb) {\n case 'list':\n return list(context);\n case 'get':\n return get(context);\n case 'create':\n return save('create')(context);\n case 'update':\n return save('update')(context);\n case 'delete':\n return remove(context);\n }\n };\n\n /**\n * Each guard asks for different services, so the branches do not unify on\n * their own; the cast states the union every guard this set can reach\n * actually needs.\n */\n const handlerFor = (verb: EntityVerb) =>\n respond(\n (\n guarded(verb, context => {\n const override = options.override?.[verb];\n return override ? override(context, links) : generic(verb, context);\n }) as Effect.Effect<\n HttpServerResponse.HttpServerResponse,\n unknown,\n | R\n | EntityRepositoryFactoryTag\n | GuardServices<G>\n | HttpServerRequest.HttpServerRequest\n | HttpRouter.RouteContext\n >\n ).pipe(Effect.catch(legacyAnswer('invalid'))),\n options.policy ?? defaultFailurePolicy,\n );\n\n const ROUTES: Record<\n EntityVerb,\n { method: 'GET' | 'POST' | 'PUT' | 'DELETE'; path: `/${string}` }\n > = {\n list: { method: 'GET', path: base },\n get: { method: 'GET', path: `${base}/:id` },\n create: { method: 'POST', path: base },\n update: { method: 'PUT', path: `${base}/:id` },\n delete: { method: 'DELETE', path: `${base}/:id` },\n };\n\n return HttpRouter.addAll([\n // A literal, so it wins over `/:id` regardless of order.\n HttpRouter.route(\n 'GET',\n `${base}/$metadata`,\n entityMetadataRoute(entityConstructor, options.compositions ?? {}),\n ),\n ...options.verbs.map(verb =>\n HttpRouter.route(\n ROUTES[verb].method,\n ROUTES[verb].path,\n handlerFor(verb),\n ),\n ),\n ]);\n};\n\n/**\n * {@link deriveEntityRoutes}, with a curried form for a caller that has to\n * name the services its `override`, `scope` or `prepare` handlers need:\n * `makeEntityRoutes.for<R>()(Entity, options)` names `R` and still infers the\n * entity and the guard from the value, which a single call with explicit type\n * arguments cannot do.\n */\nexport { routeFailure };\n\nexport const makeEntityRoutes = Object.assign(deriveEntityRoutes, {\n for:\n <R>() =>\n <T extends Entity, const G extends EntityRouteGuard>(\n entityConstructor: EntityConstructor<T>,\n options: EntityRoutesOptions<T, R, G>,\n ) =>\n deriveEntityRoutes<T, R, G>(entityConstructor, options),\n});\n"],"names":["deleteUCFactory","EntityIdTag","EntityLoadRequestTag","EntityRepositoryFactoryTag","EntityRepositoryTag","EntityTag","getUCFactory","loadUCFactory","saveUCFactory","envelopeEntityName","extractMetaEntity","makeEntityEnvelope","makeEntityPageEnvelope","NotFound","parseLoadRequestParams","readEntityEnvelope","Effect","HttpRouter","HttpServerRequest","HttpServerResponse","entityMetadataRoute","guardRoute","narrowedByIdRequest","narrowingFor","narrowLoadRequest","defaultFailurePolicy","respond","legacyAnswer","routeFailure","EntityRouteRefusal","ACTION","list","get","create","update","delete","READS","Set","deriveEntityRoutes","entityConstructor","options","key","base","basePath","mounted","verbs","links","record","id","href","String","has","rel","method","collection","guardFor","verb","guard","read","write","guarded","use","repository","context","gen","factory","for","organizationId","undefined","narrowing","scope","Error","scopeOf","succeed","narrowingOf","verified","readLoadRequest","request","search","URL","url","searchParams","try","catch","error","notFound","fail","entity","parsed","json","items","total","filtering","filter","page","pipe","provideService","params","only","found","option","_tag","includes","value","save","body","prepare","saved","remove","meta","type","data","generic","handlerFor","override","policy","ROUTES","path","addAll","route","compositions","map","makeEntityRoutes","Object","assign"],"mappings":";AACA,SACEA,eAAe,EACfC,WAAW,EACXC,oBAAoB,EACpBC,0BAA0B,EAC1BC,mBAAmB,EACnBC,SAAS,EACTC,YAAY,EACZC,aAAa,EACbC,aAAa,QACR,oBAAoB;AAC3B,SAOEC,kBAAkB,EAClBC,iBAAiB,EACjBC,kBAAkB,EAClBC,sBAAsB,EACtBC,QAAQ,EACRC,sBAAsB,EACtBC,kBAAkB,QACb,gBAAgB;AACvB,SAASC,MAAM,QAAQ,SAAS;AAChC,SAASC,UAAU,EAAEC,iBAAiB,EAAEC,kBAAkB,QAAQ,cAAc;AAEhF,SAASC,mBAAmB,QAAQ,6BAA6B;AACjE,SAIEC,UAAU,QAEL,0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AAK,CAAC4E,GAAG,CAACjE,CAAAA,OACnBvC,WAAWsG,KAAK,CACdH,MAAM,CAAC5D,KAAK,CAACH,MAAM,EACnB+D,MAAM,CAAC5D,KAAK,CAAC6D,IAAI,EACjBJ,WAAWzD;KAGhB;AACH;AAEA;;;;;;CAMC,GACD,SAAS5B,YAAY,GAAG;AAExB,OAAO,MAAM8F,mBAAmBC,OAAOC,MAAM,CAACtF,oBAAoB;IAChE4B,KACE,IACA,CACE3B,mBACAC,UAEAF,mBAA4BC,mBAAmBC;AACrD,GAAG"}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { IdempotencyStoreTag } from '@entifix/business';
|
|
2
|
+
import { Effect } from 'effect';
|
|
3
|
+
import { HttpServerRequest, HttpServerResponse } from 'effect/http';
|
|
4
|
+
/** Set on a response replayed from the store, so a caller can tell. */
|
|
5
|
+
export declare const IDEMPOTENT_REPLAY_HEADER = "idempotent-replayed";
|
|
6
|
+
/** Marks a handler as guarded, for {@link assertRetriedRoutesIdempotent}. */
|
|
7
|
+
declare const IDEMPOTENT: unique symbol;
|
|
8
|
+
/**
|
|
9
|
+
* The fingerprint of a request body: SHA-256 over its canonical JSON, or over
|
|
10
|
+
* the raw text when it is not JSON. It is what tells a retry from a different
|
|
11
|
+
* request that reused a key.
|
|
12
|
+
*/
|
|
13
|
+
export declare const requestFingerprint: (body: string) => string;
|
|
14
|
+
export interface IdempotencyKeyOptions {
|
|
15
|
+
/** The route's identity in the dedup key: `POST /api/payment`. */
|
|
16
|
+
readonly route: string;
|
|
17
|
+
/**
|
|
18
|
+
* Who is calling: the principal's id on a session route, the crossing caller
|
|
19
|
+
* on a participant route. Two callers choosing one key never collide.
|
|
20
|
+
*/
|
|
21
|
+
readonly caller: string;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Makes a write route idempotent on its `Idempotency-Key`
|
|
25
|
+
* (draft-ietf-httpapi-idempotency-key-header), with the store the composition
|
|
26
|
+
* root provides as {@link IdempotencyStoreTag}.
|
|
27
|
+
*
|
|
28
|
+
* - no key, or one that is not an RFC 9651 String → `400 idempotencyKeyMissing`;
|
|
29
|
+
* - a key in use with another body → `422 idempotencyKeyReused`;
|
|
30
|
+
* - a key whose first request has not finished → `409 idempotencyKeyInFlight`;
|
|
31
|
+
* - a key whose first request finished → that response, replayed.
|
|
32
|
+
*
|
|
33
|
+
* An answer — any response below `500` — is remembered. A `5xx`, a failure or a
|
|
34
|
+
* defect gives the key back, because none of them is an answer and the retry
|
|
35
|
+
* the key exists for must be allowed to try again.
|
|
36
|
+
*/
|
|
37
|
+
export declare const requireIdempotencyKey: (options: IdempotencyKeyOptions) => <E, R>(handler: Effect.Effect<HttpServerResponse.HttpServerResponse, E, R>) => Effect.Effect<HttpServerResponse.HttpServerResponse, import("@entifix/core").StoreFailure | import("effect/http/HttpServerError").HttpServerError | E, IdempotencyStoreTag | HttpServerRequest.HttpServerRequest | R> & {
|
|
38
|
+
[IDEMPOTENT]: true;
|
|
39
|
+
};
|
|
40
|
+
/** Whether a handler was built through {@link requireIdempotencyKey}. */
|
|
41
|
+
export declare const isIdempotentHandler: (handler: unknown) => boolean;
|
|
42
|
+
/** One route a service mounts, as the mount check sees it. */
|
|
43
|
+
export interface MountedRoute {
|
|
44
|
+
readonly method: string;
|
|
45
|
+
readonly path: string;
|
|
46
|
+
readonly handler: unknown;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Fails the build — throws at mount — when a route a flow Activity retries is
|
|
50
|
+
* not guarded by {@link requireIdempotencyKey}. A retried write without a key
|
|
51
|
+
* is a write that runs twice; finding that out from a duplicate capture is the
|
|
52
|
+
* outcome this check exists to prevent.
|
|
53
|
+
*/
|
|
54
|
+
export declare const assertRetriedRoutesIdempotent: (routes: readonly MountedRoute[], retried: readonly {
|
|
55
|
+
readonly method: string;
|
|
56
|
+
readonly path: string;
|
|
57
|
+
}[]) => void;
|
|
58
|
+
export {};
|
|
59
|
+
//# sourceMappingURL=idempotency.d.ts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AAI,EAAE,MAAM,CAAA;CAAE,EAAE,KACrE,IAcF,CAAC"}
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
import { IdempotencyStoreTag } from '@entifix/business';
|
|
4
|
+
import { IDEMPOTENCY_KEY_HEADER, IdempotencyKeyInFlight, IdempotencyKeyMissing, IdempotencyKeyReused, parseIdempotencyKey } from '@entifix/core';
|
|
5
|
+
import { Effect, Exit } from 'effect';
|
|
6
|
+
import { HttpServerRequest, HttpServerResponse } from 'effect/http';
|
|
7
|
+
import { problemResponse } from './respond.js';
|
|
8
|
+
/** Set on a response replayed from the store, so a caller can tell. */ export const IDEMPOTENT_REPLAY_HEADER = 'idempotent-replayed';
|
|
9
|
+
/** Marks a handler as guarded, for {@link assertRetriedRoutesIdempotent}. */ const IDEMPOTENT = Symbol.for('@entifix/service-shell/idempotent');
|
|
10
|
+
/** Sorted keys at every depth, so two equal bodies hash equally whatever their key order. */ const canonical = (value)=>Array.isArray(value) ? value.map(canonical) : value !== null && typeof value === 'object' ? Object.fromEntries(Object.keys(value).sort().map((key)=>[
|
|
11
|
+
key,
|
|
12
|
+
canonical(value[key])
|
|
13
|
+
])) : value;
|
|
14
|
+
/**
|
|
15
|
+
* The fingerprint of a request body: SHA-256 over its canonical JSON, or over
|
|
16
|
+
* the raw text when it is not JSON. It is what tells a retry from a different
|
|
17
|
+
* request that reused a key.
|
|
18
|
+
*/ export const requestFingerprint = (body)=>{
|
|
19
|
+
let text = body;
|
|
20
|
+
try {
|
|
21
|
+
text = JSON.stringify(canonical(JSON.parse(body)));
|
|
22
|
+
} catch (unused) {
|
|
23
|
+
// Not JSON: the bytes are the request.
|
|
24
|
+
}
|
|
25
|
+
return createHash('sha256').update(text).digest('hex');
|
|
26
|
+
};
|
|
27
|
+
/** A response as it can be stored; `undefined` for a body that cannot be replayed. */ const storable = (response)=>{
|
|
28
|
+
const { body } = response;
|
|
29
|
+
if (body._tag === 'Empty') return {
|
|
30
|
+
status: response.status,
|
|
31
|
+
body: ''
|
|
32
|
+
};
|
|
33
|
+
if (body._tag !== 'Uint8Array') return undefined;
|
|
34
|
+
return {
|
|
35
|
+
status: response.status,
|
|
36
|
+
contentType: body.contentType,
|
|
37
|
+
body: new TextDecoder().decode(body.body)
|
|
38
|
+
};
|
|
39
|
+
};
|
|
40
|
+
/**
|
|
41
|
+
* Makes a write route idempotent on its `Idempotency-Key`
|
|
42
|
+
* (draft-ietf-httpapi-idempotency-key-header), with the store the composition
|
|
43
|
+
* root provides as {@link IdempotencyStoreTag}.
|
|
44
|
+
*
|
|
45
|
+
* - no key, or one that is not an RFC 9651 String → `400 idempotencyKeyMissing`;
|
|
46
|
+
* - a key in use with another body → `422 idempotencyKeyReused`;
|
|
47
|
+
* - a key whose first request has not finished → `409 idempotencyKeyInFlight`;
|
|
48
|
+
* - a key whose first request finished → that response, replayed.
|
|
49
|
+
*
|
|
50
|
+
* An answer — any response below `500` — is remembered. A `5xx`, a failure or a
|
|
51
|
+
* defect gives the key back, because none of them is an answer and the retry
|
|
52
|
+
* the key exists for must be allowed to try again.
|
|
53
|
+
*/ export const requireIdempotencyKey = (options)=>(handler)=>{
|
|
54
|
+
const guarded = Effect.gen(function*() {
|
|
55
|
+
const request = yield* HttpServerRequest.HttpServerRequest;
|
|
56
|
+
const key = parseIdempotencyKey(request.headers[IDEMPOTENCY_KEY_HEADER]);
|
|
57
|
+
if (key === undefined) return problemResponse(new IdempotencyKeyMissing());
|
|
58
|
+
// The body is cached by the request, so the handler reads it again.
|
|
59
|
+
// A body that cannot be read cannot be fingerprinted: that failure is the
|
|
60
|
+
// transport's, and it travels as one.
|
|
61
|
+
const body = yield* request.text;
|
|
62
|
+
const fingerprint = requestFingerprint(body);
|
|
63
|
+
const dedupKey = `${options.caller}|${options.route}|${key}`;
|
|
64
|
+
const store = yield* IdempotencyStoreTag;
|
|
65
|
+
const claim = yield* store.claim(dedupKey, fingerprint);
|
|
66
|
+
if (claim._tag === 'existing') {
|
|
67
|
+
const { record } = claim;
|
|
68
|
+
if (record.fingerprint !== fingerprint) return problemResponse(new IdempotencyKeyReused());
|
|
69
|
+
if (record.state === 'inFlight' || record.response === undefined) return problemResponse(new IdempotencyKeyInFlight());
|
|
70
|
+
return HttpServerResponse.text(record.response.body, _extends({
|
|
71
|
+
status: record.response.status
|
|
72
|
+
}, record.response.contentType === undefined ? {} : {
|
|
73
|
+
contentType: record.response.contentType
|
|
74
|
+
}, {
|
|
75
|
+
headers: {
|
|
76
|
+
[IDEMPOTENT_REPLAY_HEADER]: 'true'
|
|
77
|
+
}
|
|
78
|
+
}));
|
|
79
|
+
}
|
|
80
|
+
const exit = yield* Effect.exit(handler);
|
|
81
|
+
if (Exit.isSuccess(exit)) {
|
|
82
|
+
const stored = storable(exit.value);
|
|
83
|
+
yield* stored === undefined || stored.status >= 500 ? store.release(dedupKey) : store.complete(dedupKey, stored);
|
|
84
|
+
return exit.value;
|
|
85
|
+
}
|
|
86
|
+
yield* store.release(dedupKey);
|
|
87
|
+
return yield* exit;
|
|
88
|
+
});
|
|
89
|
+
return Object.assign(guarded, {
|
|
90
|
+
[IDEMPOTENT]: true
|
|
91
|
+
});
|
|
92
|
+
};
|
|
93
|
+
/** Whether a handler was built through {@link requireIdempotencyKey}. */ export const isIdempotentHandler = (handler)=>typeof handler === 'object' && handler !== null && handler[IDEMPOTENT] === true;
|
|
94
|
+
/**
|
|
95
|
+
* Fails the build — throws at mount — when a route a flow Activity retries is
|
|
96
|
+
* not guarded by {@link requireIdempotencyKey}. A retried write without a key
|
|
97
|
+
* is a write that runs twice; finding that out from a duplicate capture is the
|
|
98
|
+
* outcome this check exists to prevent.
|
|
99
|
+
*/ export const assertRetriedRoutesIdempotent = (routes, retried)=>{
|
|
100
|
+
const unguarded = retried.filter((target)=>{
|
|
101
|
+
const route = routes.find((candidate)=>candidate.method.toUpperCase() === target.method.toUpperCase() && candidate.path === target.path);
|
|
102
|
+
return route === undefined || !isIdempotentHandler(route.handler);
|
|
103
|
+
});
|
|
104
|
+
if (unguarded.length > 0) throw new Error('these routes are retried by a flow and are not idempotent on an Idempotency-Key: ' + unguarded.map((route)=>`${route.method} ${route.path}`).join(', '));
|
|
105
|
+
};
|
|
106
|
+
|
|
107
|
+
//# sourceMappingURL=idempotency.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/idempotency.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\n\nimport { IdempotencyStoreTag, type StoredResponse } from '@entifix/business';\nimport {\n IDEMPOTENCY_KEY_HEADER,\n IdempotencyKeyInFlight,\n IdempotencyKeyMissing,\n IdempotencyKeyReused,\n parseIdempotencyKey,\n} from '@entifix/core';\nimport { Effect, Exit } from 'effect';\nimport { HttpServerRequest, HttpServerResponse } from 'effect/http';\n\nimport { problemResponse } from './respond.js';\n\n/** Set on a response replayed from the store, so a caller can tell. */\nexport const IDEMPOTENT_REPLAY_HEADER = 'idempotent-replayed';\n\n/** Marks a handler as guarded, for {@link assertRetriedRoutesIdempotent}. */\nconst IDEMPOTENT = Symbol.for('@entifix/service-shell/idempotent');\n\n/** Sorted keys at every depth, so two equal bodies hash equally whatever their key order. */\nconst canonical = (value: unknown): unknown =>\n Array.isArray(value)\n ? value.map(canonical)\n : value !== null && typeof value === 'object'\n ? Object.fromEntries(\n Object.keys(value)\n .sort()\n .map(key => [\n key,\n canonical((value as Record<string, unknown>)[key]),\n ]),\n )\n : value;\n\n/**\n * The fingerprint of a request body: SHA-256 over its canonical JSON, or over\n * the raw text when it is not JSON. It is what tells a retry from a different\n * request that reused a key.\n */\nexport const requestFingerprint = (body: string): string => {\n let text = body;\n try {\n text = JSON.stringify(canonical(JSON.parse(body)));\n } catch {\n // Not JSON: the bytes are the request.\n }\n return createHash('sha256').update(text).digest('hex');\n};\n\n/** A response as it can be stored; `undefined` for a body that cannot be replayed. */\nconst storable = (\n response: HttpServerResponse.HttpServerResponse,\n): StoredResponse | undefined => {\n const { body } = response;\n if (body._tag === 'Empty') return { status: response.status, body: '' };\n if (body._tag !== 'Uint8Array') return undefined;\n return {\n status: response.status,\n contentType: body.contentType,\n body: new TextDecoder().decode(body.body),\n };\n};\n\nexport interface IdempotencyKeyOptions {\n /** The route's identity in the dedup key: `POST /api/payment`. */\n readonly route: string;\n /**\n * Who is calling: the principal's id on a session route, the crossing caller\n * on a participant route. Two callers choosing one key never collide.\n */\n readonly caller: string;\n}\n\n/**\n * Makes a write route idempotent on its `Idempotency-Key`\n * (draft-ietf-httpapi-idempotency-key-header), with the store the composition\n * root provides as {@link IdempotencyStoreTag}.\n *\n * - no key, or one that is not an RFC 9651 String → `400 idempotencyKeyMissing`;\n * - a key in use with another body → `422 idempotencyKeyReused`;\n * - a key whose first request has not finished → `409 idempotencyKeyInFlight`;\n * - a key whose first request finished → that response, replayed.\n *\n * An answer — any response below `500` — is remembered. A `5xx`, a failure or a\n * defect gives the key back, because none of them is an answer and the retry\n * the key exists for must be allowed to try again.\n */\nexport const requireIdempotencyKey =\n (options: IdempotencyKeyOptions) =>\n <E, R>(\n handler: Effect.Effect<HttpServerResponse.HttpServerResponse, E, R>,\n ) => {\n const guarded = Effect.gen(function* () {\n const request = yield* HttpServerRequest.HttpServerRequest;\n const key = parseIdempotencyKey(request.headers[IDEMPOTENCY_KEY_HEADER]);\n if (key === undefined)\n return problemResponse(new IdempotencyKeyMissing());\n\n // The body is cached by the request, so the handler reads it again.\n // A body that cannot be read cannot be fingerprinted: that failure is the\n // transport's, and it travels as one.\n const body = yield* request.text;\n const fingerprint = requestFingerprint(body);\n const dedupKey = `${options.caller}|${options.route}|${key}`;\n const store = yield* IdempotencyStoreTag;\n\n const claim = yield* store.claim(dedupKey, fingerprint);\n if (claim._tag === 'existing') {\n const { record } = claim;\n if (record.fingerprint !== fingerprint)\n return problemResponse(new IdempotencyKeyReused());\n if (record.state === 'inFlight' || record.response === undefined)\n return problemResponse(new IdempotencyKeyInFlight());\n return HttpServerResponse.text(record.response.body, {\n status: record.response.status,\n ...(record.response.contentType === undefined\n ? {}\n : { contentType: record.response.contentType }),\n headers: { [IDEMPOTENT_REPLAY_HEADER]: 'true' },\n });\n }\n\n const exit = yield* Effect.exit(handler);\n if (Exit.isSuccess(exit)) {\n const stored = storable(exit.value);\n yield* stored === undefined || stored.status >= 500\n ? store.release(dedupKey)\n : store.complete(dedupKey, stored);\n return exit.value;\n }\n yield* store.release(dedupKey);\n return yield* exit;\n });\n return Object.assign(guarded, { [IDEMPOTENT]: true as const });\n };\n\n/** Whether a handler was built through {@link requireIdempotencyKey}. */\nexport const isIdempotentHandler = (handler: unknown): boolean =>\n typeof handler === 'object' &&\n handler !== null &&\n (handler as Record<symbol, unknown>)[IDEMPOTENT] === true;\n\n/** One route a service mounts, as the mount check sees it. */\nexport interface MountedRoute {\n readonly method: string;\n readonly path: string;\n readonly handler: unknown;\n}\n\n/**\n * Fails the build — throws at mount — when a route a flow Activity retries is\n * not guarded by {@link requireIdempotencyKey}. A retried write without a key\n * is a write that runs twice; finding that out from a duplicate capture is the\n * outcome this check exists to prevent.\n */\nexport const assertRetriedRoutesIdempotent = (\n routes: readonly MountedRoute[],\n retried: readonly { readonly method: string; readonly path: string }[],\n): void => {\n const unguarded = retried.filter(target => {\n const route = routes.find(\n candidate =>\n candidate.method.toUpperCase() === target.method.toUpperCase() &&\n candidate.path === target.path,\n );\n return route === undefined || !isIdempotentHandler(route.handler);\n });\n if (unguarded.length > 0)\n throw new Error(\n 'these routes are retried by a flow and are not idempotent on an Idempotency-Key: ' +\n unguarded.map(route => `${route.method} ${route.path}`).join(', '),\n );\n};\n"],"names":["createHash","IdempotencyStoreTag","IDEMPOTENCY_KEY_HEADER","IdempotencyKeyInFlight","IdempotencyKeyMissing","IdempotencyKeyReused","parseIdempotencyKey","Effect","Exit","HttpServerRequest","HttpServerResponse","problemResponse","IDEMPOTENT_REPLAY_HEADER","IDEMPOTENT","Symbol","for","canonical","value","Array","isArray","map","Object","fromEntries","keys","sort","key","requestFingerprint","body","text","JSON","stringify","parse","update","digest","storable","response","_tag","status","undefined","contentType","TextDecoder","decode","requireIdempotencyKey","options","handler","guarded","gen","request","headers","fingerprint","dedupKey","caller","route","store","claim","record","state","exit","isSuccess","stored","release","complete","assign","isIdempotentHandler","assertRetriedRoutesIdempotent","routes","retried","unguarded","filter","target","find","candidate","method","toUpperCase","path","length","Error","join"],"mappings":";AAAA,SAASA,UAAU,QAAQ,cAAc;AAEzC,SAASC,mBAAmB,QAA6B,oBAAoB;AAC7E,SACEC,sBAAsB,EACtBC,sBAAsB,EACtBC,qBAAqB,EACrBC,oBAAoB,EACpBC,mBAAmB,QACd,gBAAgB;AACvB,SAASC,MAAM,EAAEC,IAAI,QAAQ,SAAS;AACtC,SAASC,iBAAiB,EAAEC,kBAAkB,QAAQ,cAAc;AAEpE,SAASC,eAAe,QAAQ,eAAe;AAE/C,qEAAqE,GACrE,OAAO,MAAMC,2BAA2B,sBAAsB;AAE9D,2EAA2E,GAC3E,MAAMC,aAAaC,OAAOC,GAAG,CAAC;AAE9B,2FAA2F,GAC3F,MAAMC,YAAY,CAACC,QACjBC,MAAMC,OAAO,CAACF,SACVA,MAAMG,GAAG,CAACJ,aACVC,UAAU,QAAQ,OAAOA,UAAU,WACjCI,OAAOC,WAAW,CAChBD,OAAOE,IAAI,CAACN,OACTO,IAAI,GACJJ,GAAG,CAACK,CAAAA,MAAO;YACVA;YACAT,UAAU,AAACC,KAAiC,CAACQ,IAAI;SAClD,KAELR;AAER;;;;CAIC,GACD,OAAO,MAAMS,qBAAqB,CAACC;IACjC,IAAIC,OAAOD;IACX,IAAI;QACFC,OAAOC,KAAKC,SAAS,CAACd,UAAUa,KAAKE,KAAK,CAACJ;IAC7C,EAAE,eAAM;IACN,uCAAuC;IACzC;IACA,OAAO3B,WAAW,UAAUgC,MAAM,CAACJ,MAAMK,MAAM,CAAC;AAClD,EAAE;AAEF,oFAAoF,GACpF,MAAMC,WAAW,CACfC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EAAE,EAAEG,IAAI,CAAC;AAErE,EAAE"}
|
package/dist/index.d.ts
CHANGED
|
@@ -3,6 +3,9 @@ export * from './entity-facet-routes.js';
|
|
|
3
3
|
export * from './entity-metadata-route.js';
|
|
4
4
|
export * from './entity-routes.js';
|
|
5
5
|
export * from './health-routes.js';
|
|
6
|
+
export * from './idempotency.js';
|
|
7
|
+
export * from './metadata-composition.js';
|
|
8
|
+
export * from './narrowing.js';
|
|
6
9
|
export * from './redact-configuration.js';
|
|
7
10
|
export * from './respond.js';
|
|
8
11
|
export * from './service-description-route.js';
|
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,0BAA0B,CAAC;AACzC,cAAc,4BAA4B,CAAC;AAC3C,cAAc,oBAAoB,CAAC;AACnC,cAAc,oBAAoB,CAAC;AACnC,cAAc,2BAA2B,CAAC;AAC1C,cAAc,cAAc,CAAC;AAC7B,cAAc,gCAAgC,CAAC;AAC/C,cAAc,UAAU,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,iBAAiB,CAAC;AAChC,cAAc,0BAA0B,CAAC;AACzC,cAAc,4BAA4B,CAAC;AAC3C,cAAc,oBAAoB,CAAC;AACnC,cAAc,oBAAoB,CAAC;AACnC,cAAc,kBAAkB,CAAC;AACjC,cAAc,2BAA2B,CAAC;AAC1C,cAAc,gBAAgB,CAAC;AAC/B,cAAc,2BAA2B,CAAC;AAC1C,cAAc,cAAc,CAAC;AAC7B,cAAc,gCAAgC,CAAC;AAC/C,cAAc,UAAU,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -3,6 +3,9 @@ export * from './entity-facet-routes.js';
|
|
|
3
3
|
export * from './entity-metadata-route.js';
|
|
4
4
|
export * from './entity-routes.js';
|
|
5
5
|
export * from './health-routes.js';
|
|
6
|
+
export * from './idempotency.js';
|
|
7
|
+
export * from './metadata-composition.js';
|
|
8
|
+
export * from './narrowing.js';
|
|
6
9
|
export * from './redact-configuration.js';
|
|
7
10
|
export * from './respond.js';
|
|
8
11
|
export * from './service-description-route.js';
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["export * from './auth/index.js';\nexport * from './entity-facet-routes.js';\nexport * from './entity-metadata-route.js';\nexport * from './entity-routes.js';\nexport * from './health-routes.js';\nexport * from './redact-configuration.js';\nexport * from './respond.js';\nexport * from './service-description-route.js';\nexport * from './sse.js';\n"],"names":[],"mappings":"AAAA,cAAc,kBAAkB;AAChC,cAAc,2BAA2B;AACzC,cAAc,6BAA6B;AAC3C,cAAc,qBAAqB;AACnC,cAAc,qBAAqB;AACnC,cAAc,4BAA4B;AAC1C,cAAc,eAAe;AAC7B,cAAc,iCAAiC;AAC/C,cAAc,WAAW"}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["export * from './auth/index.js';\nexport * from './entity-facet-routes.js';\nexport * from './entity-metadata-route.js';\nexport * from './entity-routes.js';\nexport * from './health-routes.js';\nexport * from './idempotency.js';\nexport * from './metadata-composition.js';\nexport * from './narrowing.js';\nexport * from './redact-configuration.js';\nexport * from './respond.js';\nexport * from './service-description-route.js';\nexport * from './sse.js';\n"],"names":[],"mappings":"AAAA,cAAc,kBAAkB;AAChC,cAAc,2BAA2B;AACzC,cAAc,6BAA6B;AAC3C,cAAc,qBAAqB;AACnC,cAAc,qBAAqB;AACnC,cAAc,mBAAmB;AACjC,cAAc,4BAA4B;AAC1C,cAAc,iBAAiB;AAC/B,cAAc,4BAA4B;AAC1C,cAAc,eAAe;AAC7B,cAAc,iCAAiC;AAC/C,cAAc,WAAW"}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { type ResolutionRule, type VerifiedContext } from '@entifix/business';
|
|
2
|
+
import type { Recipe } from '@entifix/business/compose';
|
|
3
|
+
import { type FragmentCatalog } from '@entifix/business/flow';
|
|
4
|
+
import type { UseCaseComposition, UseCaseDescriptor } from '@entifix/core';
|
|
5
|
+
/**
|
|
6
|
+
* What a service can resolve its verbs against, by the names `@useCase()`
|
|
7
|
+
* gives: variant rules, recipes, and the catalog their fragments come from.
|
|
8
|
+
*/
|
|
9
|
+
export interface MetadataCompositions {
|
|
10
|
+
readonly variants?: Readonly<Record<string, readonly ResolutionRule<unknown>[]>>;
|
|
11
|
+
readonly recipes?: Readonly<Record<string, Recipe<any>>>;
|
|
12
|
+
readonly catalog?: FragmentCatalog;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Throws at mount when a descriptor names a variant set or a recipe the
|
|
16
|
+
* service was not given: a verb that cannot be resolved would otherwise be
|
|
17
|
+
* silently missing from every caller's document.
|
|
18
|
+
*/
|
|
19
|
+
export declare const assertCompositionsDeclared: (descriptors: readonly UseCaseDescriptor[], compositions: MetadataCompositions) => void;
|
|
20
|
+
/**
|
|
21
|
+
* What a verb resolves to for one caller: its composition, `undefined` for a
|
|
22
|
+
* verb that resolves nothing (no variants, no recipe), or `'unreachable'` when
|
|
23
|
+
* the caller is offered no variant — or the recipe needs a fragment whose
|
|
24
|
+
* requirements the caller does not meet, in a stage no gate can skip. An
|
|
25
|
+
* unreachable verb is omitted from the document.
|
|
26
|
+
*/
|
|
27
|
+
export declare const compositionFor: (descriptor: UseCaseDescriptor, context: VerifiedContext, compositions: MetadataCompositions) => UseCaseComposition | "unreachable" | undefined;
|
|
28
|
+
//# sourceMappingURL=metadata-composition.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"metadata-composition.d.ts","sourceRoot":"","sources":["../src/metadata-composition.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,KAAK,cAAc,EACnB,KAAK,eAAe,EACrB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,2BAA2B,CAAC;AACxD,OAAO,EACL,KAAK,eAAe,EAGrB,MAAM,wBAAwB,CAAC;AAChC,OAAO,KAAK,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAE3E;;;GAGG;AACH,MAAM,WAAW,oBAAoB;IACnC,QAAQ,CAAC,QAAQ,CAAC,EAAE,QAAQ,CAC1B,MAAM,CAAC,MAAM,EAAE,SAAS,cAAc,CAAC,OAAO,CAAC,EAAE,CAAC,CACnD,CAAC;IAGF,QAAQ,CAAC,OAAO,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;IACzD,QAAQ,CAAC,OAAO,CAAC,EAAE,eAAe,CAAC;CACpC;AAED;;;;GAIG;AACH,eAAO,MAAM,0BAA0B,GACrC,aAAa,SAAS,iBAAiB,EAAE,EACzC,cAAc,oBAAoB,KACjC,IAeF,CAAC;AAEF;;;;;;GAMG;AACH,eAAO,MAAM,cAAc,GACzB,YAAY,iBAAiB,EAC7B,SAAS,eAAe,EACxB,cAAc,oBAAoB,KACjC,kBAAkB,GAAG,aAAa,GAAG,SA+CvC,CAAC"}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { dryRun } from '@entifix/business';
|
|
2
|
+
import { SLIP_VERSION, unmetRequirements } from '@entifix/business/flow';
|
|
3
|
+
/**
|
|
4
|
+
* Throws at mount when a descriptor names a variant set or a recipe the
|
|
5
|
+
* service was not given: a verb that cannot be resolved would otherwise be
|
|
6
|
+
* silently missing from every caller's document.
|
|
7
|
+
*/ export const assertCompositionsDeclared = (descriptors, compositions)=>{
|
|
8
|
+
const missing = descriptors.flatMap((descriptor)=>{
|
|
9
|
+
var _compositions_variants, _compositions_recipes;
|
|
10
|
+
return [
|
|
11
|
+
...descriptor.variants !== undefined && ((_compositions_variants = compositions.variants) == null ? void 0 : _compositions_variants[descriptor.variants]) === undefined ? [
|
|
12
|
+
`variants '${descriptor.variants}' (${descriptor.key})`
|
|
13
|
+
] : [],
|
|
14
|
+
...descriptor.recipe !== undefined && ((_compositions_recipes = compositions.recipes) == null ? void 0 : _compositions_recipes[descriptor.recipe]) === undefined ? [
|
|
15
|
+
`recipe '${descriptor.recipe}' (${descriptor.key})`
|
|
16
|
+
] : []
|
|
17
|
+
];
|
|
18
|
+
});
|
|
19
|
+
if (missing.length > 0) throw new Error(`$metadata cannot resolve ${missing.join(', ')}: provide them to the route`);
|
|
20
|
+
};
|
|
21
|
+
/**
|
|
22
|
+
* What a verb resolves to for one caller: its composition, `undefined` for a
|
|
23
|
+
* verb that resolves nothing (no variants, no recipe), or `'unreachable'` when
|
|
24
|
+
* the caller is offered no variant — or the recipe needs a fragment whose
|
|
25
|
+
* requirements the caller does not meet, in a stage no gate can skip. An
|
|
26
|
+
* unreachable verb is omitted from the document.
|
|
27
|
+
*/ export const compositionFor = (descriptor, context, compositions)=>{
|
|
28
|
+
var _ref, _ref1, _ref2;
|
|
29
|
+
var _compositions_recipes;
|
|
30
|
+
if (descriptor.variants === undefined && descriptor.recipe === undefined) return undefined;
|
|
31
|
+
let variant;
|
|
32
|
+
if (descriptor.variants !== undefined) {
|
|
33
|
+
var _ref3;
|
|
34
|
+
var _compositions_variants;
|
|
35
|
+
const chosen = dryRun((_ref3 = (_compositions_variants = compositions.variants) == null ? void 0 : _compositions_variants[descriptor.variants]) != null ? _ref3 : [], context);
|
|
36
|
+
if (chosen === undefined) return 'unreachable';
|
|
37
|
+
variant = chosen.variant;
|
|
38
|
+
}
|
|
39
|
+
// No recipe means the verb named variants, so one was chosen above.
|
|
40
|
+
if (descriptor.recipe === undefined) return {
|
|
41
|
+
useCase: descriptor.key,
|
|
42
|
+
variant: variant
|
|
43
|
+
};
|
|
44
|
+
const recipe = (_compositions_recipes = compositions.recipes) == null ? void 0 : _compositions_recipes[descriptor.recipe];
|
|
45
|
+
for (const resolution of (_ref = recipe == null ? void 0 : recipe.resolve) != null ? _ref : []){
|
|
46
|
+
const chosen = dryRun(resolution.rules, context);
|
|
47
|
+
if (chosen === undefined) return 'unreachable';
|
|
48
|
+
variant != null ? variant : variant = chosen.variant;
|
|
49
|
+
}
|
|
50
|
+
const always = ((_ref1 = recipe == null ? void 0 : recipe.stages) != null ? _ref1 : []).filter((stage)=>stage.when === undefined).flatMap((stage)=>stage.steps.filter((step)=>step.when === undefined));
|
|
51
|
+
const blocked = always.some((step)=>{
|
|
52
|
+
var _compositions_catalog_get, _compositions_catalog;
|
|
53
|
+
const requires = (_compositions_catalog = compositions.catalog) == null ? void 0 : (_compositions_catalog_get = _compositions_catalog.get(step.ref)) == null ? void 0 : _compositions_catalog_get.requires;
|
|
54
|
+
return requires !== undefined && unmetRequirements(requires, context).length > 0;
|
|
55
|
+
});
|
|
56
|
+
if (blocked) return 'unreachable';
|
|
57
|
+
return {
|
|
58
|
+
useCase: descriptor.key,
|
|
59
|
+
variant: variant != null ? variant : 'default',
|
|
60
|
+
recipe: descriptor.recipe,
|
|
61
|
+
slipVersion: SLIP_VERSION,
|
|
62
|
+
fragments: [
|
|
63
|
+
...new Set(((_ref2 = recipe == null ? void 0 : recipe.stages) != null ? _ref2 : []).flatMap((stage)=>stage.steps.map((step)=>step.ref)))
|
|
64
|
+
]
|
|
65
|
+
};
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
//# sourceMappingURL=metadata-composition.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/metadata-composition.ts"],"sourcesContent":["import {\n dryRun,\n type ResolutionRule,\n type VerifiedContext,\n} from '@entifix/business';\nimport type { Recipe } from '@entifix/business/compose';\nimport {\n type FragmentCatalog,\n SLIP_VERSION,\n unmetRequirements,\n} from '@entifix/business/flow';\nimport type { UseCaseComposition, UseCaseDescriptor } from '@entifix/core';\n\n/**\n * What a service can resolve its verbs against, by the names `@useCase()`\n * gives: variant rules, recipes, and the catalog their fragments come from.\n */\nexport interface MetadataCompositions {\n readonly variants?: Readonly<\n Record<string, readonly ResolutionRule<unknown>[]>\n >;\n // A recipe's start input differs per recipe; the document reads none of it.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n readonly recipes?: Readonly<Record<string, Recipe<any>>>;\n readonly catalog?: FragmentCatalog;\n}\n\n/**\n * Throws at mount when a descriptor names a variant set or a recipe the\n * service was not given: a verb that cannot be resolved would otherwise be\n * silently missing from every caller's document.\n */\nexport const assertCompositionsDeclared = (\n descriptors: readonly UseCaseDescriptor[],\n compositions: MetadataCompositions,\n): void => {\n const missing = descriptors.flatMap(descriptor => [\n ...(descriptor.variants !== undefined &&\n compositions.variants?.[descriptor.variants] === undefined\n ? [`variants '${descriptor.variants}' (${descriptor.key})`]\n : []),\n ...(descriptor.recipe !== undefined &&\n compositions.recipes?.[descriptor.recipe] === undefined\n ? [`recipe '${descriptor.recipe}' (${descriptor.key})`]\n : []),\n ]);\n if (missing.length > 0)\n throw new Error(\n `$metadata cannot resolve ${missing.join(', ')}: provide them to the route`,\n );\n};\n\n/**\n * What a verb resolves to for one caller: its composition, `undefined` for a\n * verb that resolves nothing (no variants, no recipe), or `'unreachable'` when\n * the caller is offered no variant — or the recipe needs a fragment whose\n * requirements the caller does not meet, in a stage no gate can skip. An\n * unreachable verb is omitted from the document.\n */\nexport const compositionFor = (\n descriptor: UseCaseDescriptor,\n context: VerifiedContext,\n compositions: MetadataCompositions,\n): UseCaseComposition | 'unreachable' | undefined => {\n if (descriptor.variants === undefined && descriptor.recipe === undefined)\n return undefined;\n\n let variant: string | undefined;\n if (descriptor.variants !== undefined) {\n const chosen = dryRun(\n compositions.variants?.[descriptor.variants] ?? [],\n context,\n );\n if (chosen === undefined) return 'unreachable';\n variant = chosen.variant;\n }\n // No recipe means the verb named variants, so one was chosen above.\n if (descriptor.recipe === undefined)\n return { useCase: descriptor.key, variant: variant as string };\n\n const recipe = compositions.recipes?.[descriptor.recipe];\n for (const resolution of recipe?.resolve ?? []) {\n const chosen = dryRun(resolution.rules, context);\n if (chosen === undefined) return 'unreachable';\n variant ??= chosen.variant;\n }\n const always = (recipe?.stages ?? [])\n .filter(stage => stage.when === undefined)\n .flatMap(stage => stage.steps.filter(step => step.when === undefined));\n const blocked = always.some(step => {\n const requires = compositions.catalog?.get(step.ref)?.requires;\n return (\n requires !== undefined && unmetRequirements(requires, context).length > 0\n );\n });\n if (blocked) return 'unreachable';\n\n return {\n useCase: descriptor.key,\n variant: variant ?? 'default',\n recipe: descriptor.recipe,\n slipVersion: SLIP_VERSION,\n fragments: [\n ...new Set(\n (recipe?.stages ?? []).flatMap(stage =>\n stage.steps.map(step => step.ref),\n ),\n ),\n ],\n };\n};\n"],"names":["dryRun","SLIP_VERSION","unmetRequirements","assertCompositionsDeclared","descriptors","compositions","missing","flatMap","descriptor","variants","undefined","key","recipe","recipes","length","Error","join","compositionFor","context","variant","chosen","useCase","resolution","resolve","rules","always","stages","filter","stage","when","steps","step","blocked","some","requires","catalog","get","ref","slipVersion","fragments","Set","map"],"mappings":"AAAA,SACEA,MAAM,QAGD,oBAAoB;AAE3B,SAEEC,YAAY,EACZC,iBAAiB,QACZ,yBAAyB;AAiBhC;;;;CAIC,GACD,OAAO,MAAMC,6BAA6B,CACxCC,aACAC;IAEA,MAAMC,UAAUF,YAAYG,OAAO,CAACC,CAAAA;YAElCH,wBAIAA;eANgD;eAC5CG,WAAWC,QAAQ,KAAKC,aAC5BL,EAAAA,yBAAAA,aAAaI,QAAQ,qBAArBJ,sBAAuB,CAACG,WAAWC,QAAQ,CAAC,MAAKC,YAC7C;gBAAC,CAAC,UAAU,EAAEF,WAAWC,QAAQ,CAAC,GAAG,EAAED,WAAWG,GAAG,CAAC,CAAC,CAAC;aAAC,GACzD,EAAE;eACFH,WAAWI,MAAM,KAAKF,aAC1BL,EAAAA,wBAAAA,aAAaQ,OAAO,qBAApBR,qBAAsB,CAACG,WAAWI,MAAM,CAAC,MAAKF,YAC1C;gBAAC,CAAC,QAAQ,EAAEF,WA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AMsB,UAAUP,OAAOQ,IAAI,CAACF,CAAAA;YACT1B,2BAAAA;QAAjB,MAAM6B,YAAW7B,wBAAAA,aAAa8B,OAAO,sBAApB9B,4BAAAA,sBAAsB+B,GAAG,CAACL,KAAKM,GAAG,sBAAlChC,0BAAqC6B,QAAQ;QAC9D,OACEA,aAAaxB,aAAaR,kBAAkBgC,UAAUhB,SAASJ,MAAM,GAAG;IAE5E;IACA,IAAIkB,SAAS,OAAO;IAEpB,OAAO;QACLX,SAASb,WAAWG,GAAG;QACvBQ,OAAO,EAAEA,kBAAAA,UAAW;QACpBP,QAAQJ,WAAWI,MAAM;QACzB0B,aAAarC;QACbsC,WAAW;eACN,IAAIC,IACL,UAAC5B,0BAAAA,OAAQc,MAAM,oBAAI,EAAE,EAAEnB,OAAO,CAACqB,CAAAA,QAC7BA,MAAME,KAAK,CAACW,GAAG,CAACV,CAAAA,OAAQA,KAAKM,GAAG;SAGrC;IACH;AACF,EAAE"}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { type ResolutionRule, type VerifiedContext } from '@entifix/business';
|
|
2
|
+
import type { Entity, EntityId, EntityLoadRequest, FilterGroup } from '@entifix/core';
|
|
3
|
+
/**
|
|
4
|
+
* Which records of an entity a caller may see: every one, none, or those a
|
|
5
|
+
* filter keeps ([ADR 0015](../../../../docs/adr/0015-composed-flows-and-use-case-resolution.md)).
|
|
6
|
+
* A filter is conjoined onto the load request, so a query string can only
|
|
7
|
+
* narrow it further and no `or` in it can escape.
|
|
8
|
+
*/
|
|
9
|
+
export type Narrowing<T extends Entity> = 'unscoped' | 'nothing' | FilterGroup<T>;
|
|
10
|
+
/**
|
|
11
|
+
* A read's narrowing as ordered resolver rules over the verified context: the
|
|
12
|
+
* first variant the caller is entitled to and whose predicate holds builds the
|
|
13
|
+
* narrowing. A caller no rule matches sees **nothing** — the direction a
|
|
14
|
+
* missing rule must fail in.
|
|
15
|
+
*/
|
|
16
|
+
export type NarrowingRules<T extends Entity> = readonly ResolutionRule<(context: VerifiedContext) => Narrowing<T>>[];
|
|
17
|
+
/** The narrowing `rules` choose for `context`. */
|
|
18
|
+
export declare const narrowingFor: <T extends Entity>(rules: NarrowingRules<T>, context: VerifiedContext) => Narrowing<T>;
|
|
19
|
+
/** Conjoins a filter narrowing onto a load request; `unscoped` leaves it as it is. */
|
|
20
|
+
export declare const narrowLoadRequest: <T extends Entity>(request: EntityLoadRequest<T>, narrowing: Exclude<Narrowing<T>, "nothing">) => EntityLoadRequest<T>;
|
|
21
|
+
/**
|
|
22
|
+
* The by-id read under a narrowing: a load of the narrowing plus id equality,
|
|
23
|
+
* so a record out of the caller's sight answers exactly as an absent one does,
|
|
24
|
+
* and the list and the read can never disagree about which records those are.
|
|
25
|
+
*/
|
|
26
|
+
export declare const narrowedByIdRequest: <T extends Entity>(narrowing: FilterGroup<T>, id: EntityId) => EntityLoadRequest<T>;
|
|
27
|
+
//# sourceMappingURL=narrowing.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"narrowing.d.ts","sourceRoot":"","sources":["../src/narrowing.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,KAAK,cAAc,EACnB,KAAK,eAAe,EACrB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,KAAK,EACV,MAAM,EACN,QAAQ,EACR,iBAAiB,EACjB,WAAW,EACZ,MAAM,eAAe,CAAC;AAEvB;;;;;GAKG;AACH,MAAM,MAAM,SAAS,CAAC,CAAC,SAAS,MAAM,IACpC,UAAU,GAAG,SAAS,GAAG,WAAW,CAAC,CAAC,CAAC,CAAC;AAE1C;;;;;GAKG;AACH,MAAM,MAAM,cAAc,CAAC,CAAC,SAAS,MAAM,IAAI,SAAS,cAAc,CACpE,CAAC,OAAO,EAAE,eAAe,KAAK,SAAS,CAAC,CAAC,CAAC,CAC3C,EAAE,CAAC;AAEJ,kDAAkD;AAClD,eAAO,MAAM,YAAY,GAAI,CAAC,SAAS,MAAM,EAC3C,OAAO,cAAc,CAAC,CAAC,CAAC,EACxB,SAAS,eAAe,KACvB,SAAS,CAAC,CAAC,CAMb,CAAC;AAEF,sFAAsF;AACtF,eAAO,MAAM,iBAAiB,GAAI,CAAC,SAAS,MAAM,EAChD,SAAS,iBAAiB,CAAC,CAAC,CAAC,EAC7B,WAAW,OAAO,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,SAAS,CAAC,KAC1C,iBAAiB,CAAC,CAAC,CAGoD,CAAC;AAE3E;;;;GAIG;AACH,eAAO,MAAM,mBAAmB,GAAI,CAAC,SAAS,MAAM,EAClD,WAAW,WAAW,CAAC,CAAC,CAAC,EACzB,IAAI,QAAQ,KACX,iBAAiB,CAAC,CAAC,CAGiB,CAAC"}
|