@entifix/service-shell 0.13.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/README.md +7 -7
  2. package/dist/auth/failures.d.ts +0 -12
  3. package/dist/auth/failures.d.ts.map +1 -1
  4. package/dist/auth/failures.js +0 -10
  5. package/dist/auth/failures.js.map +1 -1
  6. package/dist/auth/index.d.ts +0 -1
  7. package/dist/auth/index.d.ts.map +1 -1
  8. package/dist/auth/index.js +0 -1
  9. package/dist/auth/index.js.map +1 -1
  10. package/dist/auth/require-principal.d.ts +0 -16
  11. package/dist/auth/require-principal.d.ts.map +1 -1
  12. package/dist/auth/require-principal.js +1 -38
  13. package/dist/auth/require-principal.js.map +1 -1
  14. package/dist/auth/require-service-crossing.d.ts +2 -73
  15. package/dist/auth/require-service-crossing.d.ts.map +1 -1
  16. package/dist/auth/require-service-crossing.js +2 -117
  17. package/dist/auth/require-service-crossing.js.map +1 -1
  18. package/dist/auth/shared-token.d.ts +0 -15
  19. package/dist/auth/shared-token.d.ts.map +1 -1
  20. package/dist/auth/shared-token.js +0 -25
  21. package/dist/auth/shared-token.js.map +1 -1
  22. package/dist/http-api/build-api.d.ts.map +1 -1
  23. package/dist/http-api/build-api.js +1 -1
  24. package/dist/http-api/build-api.js.map +1 -1
  25. package/dist/http-api/entity-api.d.ts.map +1 -1
  26. package/dist/http-api/entity-api.js +6 -2
  27. package/dist/http-api/entity-api.js.map +1 -1
  28. package/dist/index.d.ts +0 -4
  29. package/dist/index.d.ts.map +1 -1
  30. package/dist/index.js +0 -4
  31. package/dist/index.js.map +1 -1
  32. package/dist/load-remote-configuration.d.ts +4 -4
  33. package/dist/load-remote-configuration.d.ts.map +1 -1
  34. package/dist/load-remote-configuration.js +7 -14
  35. package/dist/load-remote-configuration.js.map +1 -1
  36. package/dist/observability.d.ts +2 -2
  37. package/dist/observability.d.ts.map +1 -1
  38. package/dist/observability.js.map +1 -1
  39. package/dist/push/index.d.ts +9 -0
  40. package/dist/push/index.d.ts.map +1 -0
  41. package/dist/push/index.js +9 -0
  42. package/dist/push/index.js.map +1 -0
  43. package/dist/push/server-push.d.ts +82 -0
  44. package/dist/push/server-push.d.ts.map +1 -0
  45. package/dist/push/server-push.js +48 -0
  46. package/dist/push/server-push.js.map +1 -0
  47. package/dist/push/sse.d.ts +62 -0
  48. package/dist/push/sse.d.ts.map +1 -0
  49. package/dist/push/sse.js +120 -0
  50. package/dist/push/sse.js.map +1 -0
  51. package/dist/respond.d.ts +1 -7
  52. package/dist/respond.d.ts.map +1 -1
  53. package/dist/respond.js +1 -8
  54. package/dist/respond.js.map +1 -1
  55. package/package.json +23 -13
  56. package/dist/auth/require-organization.d.ts +0 -32
  57. package/dist/auth/require-organization.d.ts.map +0 -1
  58. package/dist/auth/require-organization.js +0 -52
  59. package/dist/auth/require-organization.js.map +0 -1
  60. package/dist/entity-facet-routes.d.ts +0 -44
  61. package/dist/entity-facet-routes.d.ts.map +0 -1
  62. package/dist/entity-facet-routes.js +0 -70
  63. package/dist/entity-facet-routes.js.map +0 -1
  64. package/dist/entity-metadata-route.d.ts +0 -25
  65. package/dist/entity-metadata-route.d.ts.map +0 -1
  66. package/dist/entity-metadata-route.js +0 -102
  67. package/dist/entity-metadata-route.js.map +0 -1
  68. package/dist/entity-route-guard.d.ts +0 -62
  69. package/dist/entity-route-guard.d.ts.map +0 -1
  70. package/dist/entity-route-guard.js +0 -35
  71. package/dist/entity-route-guard.js.map +0 -1
  72. package/dist/entity-routes.d.ts +0 -76
  73. package/dist/entity-routes.d.ts.map +0 -1
  74. package/dist/entity-routes.js +0 -267
  75. package/dist/entity-routes.js.map +0 -1
  76. package/dist/route-responses.d.ts +0 -44
  77. package/dist/route-responses.d.ts.map +0 -1
  78. package/dist/route-responses.js +0 -104
  79. package/dist/route-responses.js.map +0 -1
  80. package/dist/sse.d.ts +0 -43
  81. package/dist/sse.d.ts.map +0 -1
  82. package/dist/sse.js +0 -78
  83. package/dist/sse.js.map +0 -1
@@ -1,104 +0,0 @@
1
- import { _ as _extends } from "@swc/helpers/_/_extends";
2
- import { defaultStatus, EntifixBuildError, EntifixConnError, failureTypeUri, isFailure, PROBLEM_CONTENT_TYPE, Unavailable } from '@entifix/core';
3
- import { Effect } from 'effect';
4
- import { HttpServerResponse } from 'effect/http';
5
- /**
6
- * A save refused by a rule the entity's own deserializer does not make — a
7
- * closed set, a rule over the other records — answered as `status` with
8
- * `code`, which is what a client translates.
9
- */ export class EntityRouteRefusal {
10
- constructor(status, code, detail){
11
- this.status = status;
12
- this.code = code;
13
- this.detail = detail;
14
- this._tag = 'EntityRouteRefusal';
15
- }
16
- }
17
- /**
18
- * The `500` for anything a route did not anticipate.
19
- *
20
- * @deprecated A route mounted through `mountRoutes` answers through `respond`,
21
- * which never writes `String(error)`. Kept for a host's unmigrated routes and
22
- * removed with the class tree.
23
- */ export const routeFailure = (error)=>HttpServerResponse.json({
24
- error: 'request failed',
25
- code: 'unexpected',
26
- detail: String(error)
27
- }, {
28
- status: 500
29
- });
30
- /**
31
- * A domain error may carry its own code (`mediaNotHttps`), so the client can
32
- * say which rule failed rather than "invalid body".
33
- */ const refusalCode = (error)=>'code' in error && typeof error.code === 'string' ? error.code : undefined;
34
- /**
35
- * @deprecated A route mounted through `mountRoutes` fails with typed failures
36
- * and lets `respond` answer them. Kept for a host's unmigrated routes and
37
- * removed with the class tree.
38
- *
39
- * The answer to a request the route refused: a `400` for what the client sent
40
- * wrong, the refusal's own status for a rule a save broke, a business-family
41
- * failure's category status, and a `500` for anything else.
42
- */ export const invalid = (error, label, code)=>{
43
- var _refusalCode;
44
- return isFailure(error) && error.family === 'business' ? HttpServerResponse.json(_extends({
45
- error: label,
46
- // A body that is not an envelope is the route's own refusal, named
47
- // by the route as it always was; any other failure names itself.
48
- code: error._tag === 'InvalidEnvelope' ? code : error.code
49
- }, error.message === '' ? {} : {
50
- detail: error.message
51
- }), {
52
- status: defaultStatus(error.category)
53
- }) : error instanceof EntifixBuildError ? HttpServerResponse.json({
54
- error: label,
55
- code: (_refusalCode = refusalCode(error)) != null ? _refusalCode : code,
56
- detail: error.message
57
- }, {
58
- status: 400
59
- }) : error instanceof EntityRouteRefusal ? HttpServerResponse.json(_extends({
60
- error: 'the record cannot be saved',
61
- code: error.code
62
- }, error.detail === undefined ? {} : {
63
- detail: error.detail
64
- }), {
65
- status: error.status
66
- }) : routeFailure(error);
67
- };
68
- const LEGACY_CATEGORY = {
69
- 400: 'invalid',
70
- 409: 'conflict',
71
- 422: 'declined'
72
- };
73
- /**
74
- * A problem body for a refusal whose code no failure class registered — a
75
- * host's `EntityRouteRefusal`, a domain `EntifixBuildError` carrying its own
76
- * code. Written by hand because there is no class to encode it through; a
77
- * client that decodes it sees an unknown code until the refusal becomes a
78
- * failure of its own.
79
- */ const legacyProblem = (status, code, detail)=>HttpServerResponse.text(JSON.stringify(_extends({
80
- type: failureTypeUri(code),
81
- title: code,
82
- status,
83
- code,
84
- category: LEGACY_CATEGORY[status]
85
- }, detail === undefined ? {} : {
86
- detail
87
- })), {
88
- status,
89
- contentType: PROBLEM_CONTENT_TYPE
90
- });
91
- /**
92
- * What a framework route's errors mean, while some still arrive as the old
93
- * class tree: a typed failure passes through to `respond`, a refusal answers
94
- * as its own problem body, an unreachable store becomes `Unavailable`, and
95
- * anything else is a defect — the opaque `500`, logged where `respond`
96
- * catches it.
97
- *
98
- * @param fallbackCode the code a domain error carrying none answers with.
99
- */ export const legacyAnswer = (fallbackCode)=>(error)=>{
100
- var _refusalCode;
101
- return isFailure(error) ? Effect.fail(error) : error instanceof EntityRouteRefusal ? Effect.succeed(legacyProblem(error.status, error.code, error.detail)) : error instanceof EntifixBuildError ? Effect.succeed(legacyProblem(400, (_refusalCode = refusalCode(error)) != null ? _refusalCode : fallbackCode, error.message)) : error instanceof EntifixConnError ? Effect.fail(new Unavailable({})) : Effect.die(error);
102
- };
103
-
104
- //# sourceMappingURL=route-responses.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/route-responses.ts"],"sourcesContent":["import {\n defaultStatus,\n EntifixBuildError,\n EntifixConnError,\n type EntifixFailure,\n failureTypeUri,\n isFailure,\n PROBLEM_CONTENT_TYPE,\n Unavailable,\n} from '@entifix/core';\nimport { Effect } from 'effect';\nimport { HttpServerResponse } from 'effect/http';\n\n/**\n * A save refused by a rule the entity's own deserializer does not make — a\n * closed set, a rule over the other records — answered as `status` with\n * `code`, which is what a client translates.\n */\nexport class EntityRouteRefusal {\n readonly _tag = 'EntityRouteRefusal';\n\n constructor(\n readonly status: 400 | 409 | 422,\n readonly code: string,\n readonly detail?: string,\n ) {}\n}\n\n/**\n * The `500` for anything a route did not anticipate.\n *\n * @deprecated A route mounted through `mountRoutes` answers through `respond`,\n * which never writes `String(error)`. Kept for a host's unmigrated routes and\n * removed with the class tree.\n */\nexport const routeFailure = (error: unknown) =>\n HttpServerResponse.json(\n { error: 'request failed', code: 'unexpected', detail: String(error) },\n { status: 500 },\n );\n\n/**\n * A domain error may carry its own code (`mediaNotHttps`), so the client can\n * say which rule failed rather than \"invalid body\".\n */\nconst refusalCode = (error: EntifixBuildError): string | undefined =>\n 'code' in error && typeof error.code === 'string' ? error.code : undefined;\n\n/**\n * @deprecated A route mounted through `mountRoutes` fails with typed failures\n * and lets `respond` answer them. Kept for a host's unmigrated routes and\n * removed with the class tree.\n *\n * The answer to a request the route refused: a `400` for what the client sent\n * wrong, the refusal's own status for a rule a save broke, a business-family\n * failure's category status, and a `500` for anything else.\n */\nexport const invalid = (error: unknown, label: string, code: string) =>\n isFailure(error) && error.family === 'business'\n ? HttpServerResponse.json(\n {\n error: label,\n // A body that is not an envelope is the route's own refusal, named\n // by the route as it always was; any other failure names itself.\n code: error._tag === 'InvalidEnvelope' ? code : error.code,\n ...(error.message === '' ? {} : { detail: error.message }),\n },\n { status: defaultStatus(error.category) },\n )\n : error instanceof EntifixBuildError\n ? HttpServerResponse.json(\n {\n error: label,\n code: refusalCode(error) ?? code,\n detail: error.message,\n },\n { status: 400 },\n )\n : error instanceof EntityRouteRefusal\n ? HttpServerResponse.json(\n {\n error: 'the record cannot be saved',\n code: error.code,\n ...(error.detail === undefined ? {} : { detail: error.detail }),\n },\n { status: error.status },\n )\n : routeFailure(error);\n\nconst LEGACY_CATEGORY: Record<\n EntityRouteRefusal['status'],\n 'invalid' | 'conflict' | 'declined'\n> = {\n 400: 'invalid',\n 409: 'conflict',\n 422: 'declined',\n};\n\n/**\n * A problem body for a refusal whose code no failure class registered — a\n * host's `EntityRouteRefusal`, a domain `EntifixBuildError` carrying its own\n * code. Written by hand because there is no class to encode it through; a\n * client that decodes it sees an unknown code until the refusal becomes a\n * failure of its own.\n */\nconst legacyProblem = (\n status: EntityRouteRefusal['status'],\n code: string,\n detail?: string,\n) =>\n HttpServerResponse.text(\n JSON.stringify({\n type: failureTypeUri(code),\n title: code,\n status,\n code,\n category: LEGACY_CATEGORY[status],\n ...(detail === undefined ? {} : { detail }),\n }),\n { status, contentType: PROBLEM_CONTENT_TYPE },\n );\n\n/**\n * What a framework route's errors mean, while some still arrive as the old\n * class tree: a typed failure passes through to `respond`, a refusal answers\n * as its own problem body, an unreachable store becomes `Unavailable`, and\n * anything else is a defect — the opaque `500`, logged where `respond`\n * catches it.\n *\n * @param fallbackCode the code a domain error carrying none answers with.\n */\nexport const legacyAnswer =\n (fallbackCode: string) =>\n (\n error: unknown,\n ): Effect.Effect<HttpServerResponse.HttpServerResponse, EntifixFailure> =>\n isFailure(error)\n ? Effect.fail(error)\n : error instanceof EntityRouteRefusal\n ? Effect.succeed(legacyProblem(error.status, error.code, error.detail))\n : error instanceof EntifixBuildError\n ? Effect.succeed(\n legacyProblem(\n 400,\n refusalCode(error) ?? fallbackCode,\n error.message,\n ),\n )\n : error instanceof EntifixConnError\n ? Effect.fail(new Unavailable({}))\n : Effect.die(error);\n"],"names":["defaultStatus","EntifixBuildError","EntifixConnError","failureTypeUri","isFailure","PROBLEM_CONTENT_TYPE","Unavailable","Effect","HttpServerResponse","EntityRouteRefusal","status","code","detail","_tag","routeFailure","error","json","String","refusalCode","undefined","invalid","label","family","message","category","LEGACY_CATEGORY","legacyProblem","text","JSON","stringify","type","title","contentType","legacyAnswer","fallbackCode","fail","succeed","die"],"mappings":";AAAA,SACEA,aAAa,EACbC,iBAAiB,EACjBC,gBAAgB,EAEhBC,cAAc,EACdC,SAAS,EACTC,oBAAoB,EACpBC,WAAW,QACN,gBAAgB;AACvB,SAASC,MAAM,QAAQ,SAAS;AAChC,SAASC,kBAAkB,QAAQ,cAAc;AAEjD;;;;CAIC,GACD,OAAO,MAAMC;IAGX,YACE,AAASC,MAAuB,EAChC,AAASC,IAAY,EACrB,AAASC,MAAe,CACxB;aAHSF,SAAAA;aACAC,OAAAA;aACAC,SAAAA;aALFC,OAAO;IAMb;AACL;AAEA;;;;;;CAMC,GACD,OAAO,MAAMC,eAAe,CAACC,QAC3BP,mBAAmBQ,IAAI,CACrB;QAAED,OAAO;QAAkBJ,MAAM;QAAcC,QAAQK,OAAOF;IAAO,GACrE;QAAEL,QAAQ;IAAI,GACd;AAEJ;;;CAGC,GACD,MAAMQ,cAAc,CAACH,QACnB,UAAUA,SAAS,OAAOA,MAAMJ,IAAI,KAAK,WAAWI,MAAMJ,IAAI,GAAGQ;AAEnE;;;;;;;;CAQC,GACD,OAAO,MAAMC,UAAU,CAACL,OAAgBM,OAAeV;QAgBrCO;WAfhBd,UAAUW,UAAUA,MAAMO,MAAM,KAAK,aACjCd,mBAAmBQ,IAAI,CACrB;QACED,OAAOM;QACP,mEAAmE;QACnE,iEAAiE;QACjEV,MAAMI,MAAMF,IAAI,KAAK,oBAAoBF,OAAOI,MAAMJ,IAAI;OACtDI,MAAMQ,OAAO,KAAK,KAAK,CAAC,IAAI;QAAEX,QAAQG,MAAMQ,OAAO;IAAC,IAE1D;QAAEb,QAAQV,cAAce,MAAMS,QAAQ;IAAE,KAE1CT,iBAAiBd,oBACfO,mBAAmBQ,IAAI,CACrB;QACED,OAAOM;QACPV,IAAI,GAAEO,eAAAA,YAAYH,kBAAZG,eAAsBP;QAC5BC,QAAQG,MAAMQ,OAAO;IACvB,GACA;QAAEb,QAAQ;IAAI,KAEhBK,iBAAiBN,qBACfD,mBAAmBQ,IAAI,CACrB;QACED,OAAO;QACPJ,MAAMI,MAAMJ,IAAI;OACZI,MAAMH,MAAM,KAAKO,YAAY,CAAC,IAAI;QAAEP,QAAQG,MAAMH,MAAM;IAAC,IAE/D;QAAEF,QAAQK,MAAML,MAAM;IAAC,KAEzBI,aAAaC;EAAO;AAE9B,MAAMU,kBAGF;IACF,KAAK;IACL,KAAK;IACL,KAAK;AACP;AAEA;;;;;;CAMC,GACD,MAAMC,gBAAgB,CACpBhB,QACAC,MACAC,SAEAJ,mBAAmBmB,IAAI,CACrBC,KAAKC,SAAS,CAAC;QACbC,MAAM3B,eAAeQ;QACrBoB,OAAOpB;QACPD;QACAC;QACAa,UAAUC,eAAe,CAACf,OAAO;OAC7BE,WAAWO,YAAY,CAAC,IAAI;QAAEP;IAAO,KAE3C;QAAEF;QAAQsB,aAAa3B;IAAqB;AAGhD;;;;;;;;CAQC,GACD,OAAO,MAAM4B,eACX,CAACC,eACD,CACEnB;YAUYG;eARZd,UAAUW,SACNR,OAAO4B,IAAI,CAACpB,SACZA,iBAAiBN,qBACfF,OAAO6B,OAAO,CAACV,cAAcX,MAAML,MAAM,EAAEK,MAAMJ,IAAI,EAAEI,MAAMH,MAAM,KACnEG,iBAAiBd,oBACfM,OAAO6B,OAAO,CACZV,cACE,MACAR,eAAAA,YAAYH,kBAAZG,eAAsBgB,cACtBnB,MAAMQ,OAAO,KAGjBR,iBAAiBb,mBACfK,OAAO4B,IAAI,CAAC,IAAI7B,YAAY,CAAC,MAC7BC,OAAO8B,GAAG,CAACtB;MAAO"}
package/dist/sse.d.ts DELETED
@@ -1,43 +0,0 @@
1
- import { type DomainEvent, type EntityChangeEvent } from '@entifix/core';
2
- import { Stream } from 'effect';
3
- import { HttpServerResponse } from 'effect/http';
4
- /**
5
- * One `EventSource` frame.
6
- *
7
- * `id:` carries the message's own id — `<transactionId>:<step>` for a
8
- * transaction event — so the `Last-Event-ID` a browser re-sends on reconnect
9
- * names a message that actually exists, rather than a counter invented for the
10
- * wire. The server does not replay it; the client reconciles by
11
- * re-reading the record.
12
- *
13
- * `data:` is a full `event` envelope, which is what keeps the stream from
14
- * becoming a fourth framing: the same bytes a bus consumer would read. It is
15
- * encoded through the entity-change schema, the one shape this stream carries;
16
- * an event that does not encode is no frame at all (`undefined`), because a
17
- * browser would drop it on decode anyway.
18
- */
19
- export declare const sseFrame: (event: DomainEvent<EntityChangeEvent>) => string | undefined;
20
- export interface SseResponseOptions {
21
- /**
22
- * Unix seconds at which to close the connection — the verified token's `exp`.
23
- *
24
- * A held-open response has no next request to fail verification, so the bound
25
- * every REST route gets implicitly has to be applied explicitly here. The
26
- * browser reconnects with the cookie the app refreshed in the meantime
27
- *. Omitted, the stream runs until the client goes away.
28
- */
29
- readonly expiresAt?: number;
30
- /** Injectable for tests; defaults to the wall clock. */
31
- readonly now?: () => number;
32
- }
33
- /**
34
- * Serves a stream of domain events as `text/event-stream`.
35
- *
36
- * `cache-control: no-store` is not politeness — a cached event stream is served
37
- * to whoever asks next, and this one is scoped to a single principal. The
38
- * response is deliberately *not* rebuilt anywhere downstream: the Next proxy has
39
- * a pass-through arm for exactly this content type, because reading the body to
40
- * completion first holds the request open forever and delivers nothing.
41
- */
42
- export declare const sseResponse: (events: Stream.Stream<DomainEvent<EntityChangeEvent>>, { expiresAt, now }?: SseResponseOptions) => HttpServerResponse.HttpServerResponse;
43
- //# sourceMappingURL=sse.d.ts.map
package/dist/sse.d.ts.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"sse.d.ts","sourceRoot":"","sources":["../src/sse.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,WAAW,EAEhB,KAAK,iBAAiB,EACvB,MAAM,eAAe,CAAC;AACvB,OAAO,EAAkC,MAAM,EAAE,MAAM,QAAQ,CAAC;AAChE,OAAO,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAcjD;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,QAAQ,GACnB,OAAO,WAAW,CAAC,iBAAiB,CAAC,KACpC,MAAM,GAAG,SASX,CAAC;AAEF,MAAM,WAAW,kBAAkB;IACjC;;;;;;;OAOG;IACH,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC;IAC5B,wDAAwD;IACxD,QAAQ,CAAC,GAAG,CAAC,EAAE,MAAM,MAAM,CAAC;CAC7B;AAED;;;;;;;;GAQG;AACH,eAAO,MAAM,WAAW,GACtB,QAAQ,MAAM,CAAC,MAAM,CAAC,WAAW,CAAC,iBAAiB,CAAC,CAAC,EACrD,qBAA+B,kBAAuB,KACrD,kBAAkB,CAAC,kBA+CrB,CAAC"}
package/dist/sse.js DELETED
@@ -1,78 +0,0 @@
1
- import { _ as _object_without_properties_loose } from "@swc/helpers/_/_object_without_properties_loose";
2
- import { EntityChangeEnvelope } from '@entifix/core';
3
- import { Duration, Effect, Exit, Schema, Stream } from 'effect';
4
- import { HttpServerResponse } from 'effect/http';
5
- /**
6
- * How often an idle connection emits a comment frame.
7
- *
8
- * An SSE connection that sends nothing for minutes is indistinguishable from a
9
- * dead one to anything between the browser and the service, and a proxy that
10
- * decides it is dead closes it with no error either side can report. A comment
11
- * (`:` and nothing else) is ignored by `EventSource` and costs three bytes.
12
- */ const KEEPALIVE = Duration.seconds(20);
13
- const encoder = new TextEncoder();
14
- /**
15
- * One `EventSource` frame.
16
- *
17
- * `id:` carries the message's own id — `<transactionId>:<step>` for a
18
- * transaction event — so the `Last-Event-ID` a browser re-sends on reconnect
19
- * names a message that actually exists, rather than a counter invented for the
20
- * wire. The server does not replay it; the client reconciles by
21
- * re-reading the record.
22
- *
23
- * `data:` is a full `event` envelope, which is what keeps the stream from
24
- * becoming a fourth framing: the same bytes a bus consumer would read. It is
25
- * encoded through the entity-change schema, the one shape this stream carries;
26
- * an event that does not encode is no frame at all (`undefined`), because a
27
- * browser would drop it on decode anyway.
28
- */ export const sseFrame = (event)=>{
29
- const { data } = event, meta = _object_without_properties_loose(event, [
30
- "data"
31
- ]);
32
- const encoded = Schema.encodeUnknownExit(EntityChangeEnvelope)({
33
- meta: {
34
- type: 'event',
35
- event: meta
36
- },
37
- data
38
- });
39
- return Exit.isSuccess(encoded) ? `id: ${event.id}\ndata: ${JSON.stringify(encoded.value)}\n\n` : undefined;
40
- };
41
- /**
42
- * Serves a stream of domain events as `text/event-stream`.
43
- *
44
- * `cache-control: no-store` is not politeness — a cached event stream is served
45
- * to whoever asks next, and this one is scoped to a single principal. The
46
- * response is deliberately *not* rebuilt anywhere downstream: the Next proxy has
47
- * a pass-through arm for exactly this content type, because reading the body to
48
- * completion first holds the request open forever and delivers nothing.
49
- */ export const sseResponse = (events, { expiresAt, now = Date.now } = {})=>{
50
- const keepalive = Stream.fromEffectRepeat(Effect.as(Effect.sleep(KEEPALIVE), ': keepalive\n\n'));
51
- const frames = Stream.merge(Stream.filter(Stream.map(events, sseFrame), (frame)=>frame !== undefined), keepalive, {
52
- haltStrategy: 'left'
53
- });
54
- // An opening comment, emitted before anything has happened.
55
- //
56
- // Not cosmetic: a chunked response writes its headers with its first chunk,
57
- // so a stream that stays silent until something occurs leaves the client in
58
- // `CONNECTING` — indefinitely, since a stream whose whole purpose is to be
59
- // idle most of the time may have nothing to say for hours. Measured: without
60
- // it, `fetch` against this route does not resolve at all.
61
- const opened = Stream.concat(Stream.make(': open\n\n'), frames);
62
- const bounded = expiresAt === undefined ? opened : Stream.interruptWhen(opened, // Never negative: an already-expired token closes at once rather than
63
- // scheduling a sleep into the past, which `Effect.sleep` treats as
64
- // zero anyway but reads as an oversight.
65
- Effect.sleep(Duration.millis(Math.max(0, expiresAt * 1000 - now()))));
66
- return HttpServerResponse.stream(Stream.map(bounded, (frame)=>encoder.encode(frame)), {
67
- contentType: 'text/event-stream',
68
- headers: {
69
- 'cache-control': 'no-store',
70
- connection: 'keep-alive',
71
- // nginx buffers a proxied response by default, which would hold every
72
- // frame until the stream ends — that is, forever.
73
- 'x-accel-buffering': 'no'
74
- }
75
- });
76
- };
77
-
78
- //# sourceMappingURL=sse.js.map
package/dist/sse.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/sse.ts"],"sourcesContent":["import {\n type DomainEvent,\n EntityChangeEnvelope,\n type EntityChangeEvent,\n} from '@entifix/core';\nimport { Duration, Effect, Exit, Schema, Stream } from 'effect';\nimport { HttpServerResponse } from 'effect/http';\n\n/**\n * How often an idle connection emits a comment frame.\n *\n * An SSE connection that sends nothing for minutes is indistinguishable from a\n * dead one to anything between the browser and the service, and a proxy that\n * decides it is dead closes it with no error either side can report. A comment\n * (`:` and nothing else) is ignored by `EventSource` and costs three bytes.\n */\nconst KEEPALIVE = Duration.seconds(20);\n\nconst encoder = new TextEncoder();\n\n/**\n * One `EventSource` frame.\n *\n * `id:` carries the message's own id — `<transactionId>:<step>` for a\n * transaction event — so the `Last-Event-ID` a browser re-sends on reconnect\n * names a message that actually exists, rather than a counter invented for the\n * wire. The server does not replay it; the client reconciles by\n * re-reading the record.\n *\n * `data:` is a full `event` envelope, which is what keeps the stream from\n * becoming a fourth framing: the same bytes a bus consumer would read. It is\n * encoded through the entity-change schema, the one shape this stream carries;\n * an event that does not encode is no frame at all (`undefined`), because a\n * browser would drop it on decode anyway.\n */\nexport const sseFrame = (\n event: DomainEvent<EntityChangeEvent>,\n): string | undefined => {\n const { data, ...meta } = event;\n const encoded = Schema.encodeUnknownExit(EntityChangeEnvelope)({\n meta: { type: 'event', event: meta },\n data,\n });\n return Exit.isSuccess(encoded)\n ? `id: ${event.id}\\ndata: ${JSON.stringify(encoded.value)}\\n\\n`\n : undefined;\n};\n\nexport interface SseResponseOptions {\n /**\n * Unix seconds at which to close the connection — the verified token's `exp`.\n *\n * A held-open response has no next request to fail verification, so the bound\n * every REST route gets implicitly has to be applied explicitly here. The\n * browser reconnects with the cookie the app refreshed in the meantime\n *. Omitted, the stream runs until the client goes away.\n */\n readonly expiresAt?: number;\n /** Injectable for tests; defaults to the wall clock. */\n readonly now?: () => number;\n}\n\n/**\n * Serves a stream of domain events as `text/event-stream`.\n *\n * `cache-control: no-store` is not politeness — a cached event stream is served\n * to whoever asks next, and this one is scoped to a single principal. The\n * response is deliberately *not* rebuilt anywhere downstream: the Next proxy has\n * a pass-through arm for exactly this content type, because reading the body to\n * completion first holds the request open forever and delivers nothing.\n */\nexport const sseResponse = (\n events: Stream.Stream<DomainEvent<EntityChangeEvent>>,\n { expiresAt, now = Date.now }: SseResponseOptions = {},\n): HttpServerResponse.HttpServerResponse => {\n const keepalive = Stream.fromEffectRepeat(\n Effect.as(Effect.sleep(KEEPALIVE), ': keepalive\\n\\n'),\n );\n\n const frames = Stream.merge(\n Stream.filter(\n Stream.map(events, sseFrame),\n (frame): frame is string => frame !== undefined,\n ),\n keepalive,\n { haltStrategy: 'left' },\n );\n\n // An opening comment, emitted before anything has happened.\n //\n // Not cosmetic: a chunked response writes its headers with its first chunk,\n // so a stream that stays silent until something occurs leaves the client in\n // `CONNECTING` — indefinitely, since a stream whose whole purpose is to be\n // idle most of the time may have nothing to say for hours. Measured: without\n // it, `fetch` against this route does not resolve at all.\n const opened = Stream.concat(Stream.make(': open\\n\\n'), frames);\n\n const bounded =\n expiresAt === undefined\n ? opened\n : Stream.interruptWhen(\n opened,\n // Never negative: an already-expired token closes at once rather than\n // scheduling a sleep into the past, which `Effect.sleep` treats as\n // zero anyway but reads as an oversight.\n Effect.sleep(Duration.millis(Math.max(0, expiresAt * 1000 - now()))),\n );\n\n return HttpServerResponse.stream(\n Stream.map(bounded, frame => encoder.encode(frame)),\n {\n contentType: 'text/event-stream',\n headers: {\n 'cache-control': 'no-store',\n connection: 'keep-alive',\n // nginx buffers a proxied response by default, which would hold every\n // frame until the stream ends — that is, forever.\n 'x-accel-buffering': 'no',\n },\n },\n );\n};\n"],"names":["EntityChangeEnvelope","Duration","Effect","Exit","Schema","Stream","HttpServerResponse","KEEPALIVE","seconds","encoder","TextEncoder","sseFrame","event","data","meta","encoded","encodeUnknownExit","type","isSuccess","id","JSON","stringify","value","undefined","sseResponse","events","expiresAt","now","Date","keepalive","fromEffectRepeat","as","sleep","frames","merge","filter","map","frame","haltStrategy","opened","concat","make","bounded","interruptWhen","millis","Math","max","stream","encode","contentType","headers","connection"],"mappings":";AAAA,SAEEA,oBAAoB,QAEf,gBAAgB;AACvB,SAASC,QAAQ,EAAEC,MAAM,EAAEC,IAAI,EAAEC,MAAM,EAAEC,MAAM,QAAQ,SAAS;AAChE,SAASC,kBAAkB,QAAQ,cAAc;AAEjD;;;;;;;CAOC,GACD,MAAMC,YAAYN,SAASO,OAAO,CAAC;AAEnC,MAAMC,UAAU,IAAIC;AAEpB;;;;;;;;;;;;;;CAcC,GACD,OAAO,MAAMC,WAAW,CACtBC;IAEA,MAAM,EAAEC,IAAI,EAAW,GAAGD,OAATE,wCAASF;;;IAC1B,MAAMG,UAAUX,OAAOY,iBAAiB,CAAChB,sBAAsB;QAC7Dc,MAAM;YAAEG,MAAM;YAASL,OAAOE;QAAK;QACnCD;IACF;IACA,OAAOV,KAAKe,SAAS,CAACH,WAClB,CAAC,IAAI,EAAEH,MAAMO,EAAE,CAAC,QAAQ,EAAEC,KAAKC,SAAS,CAACN,QAAQO,KAAK,EAAE,IAAI,CAAC,GAC7DC;AACN,EAAE;AAgBF;;;;;;;;CAQC,GACD,OAAO,MAAMC,cAAc,CACzBC,QACA,EAAEC,SAAS,EAAEC,MAAMC,KAAKD,GAAG,EAAsB,GAAG,CAAC,CAAC;IAEtD,MAAME,YAAYxB,OAAOyB,gBAAgB,CACvC5B,OAAO6B,EAAE,CAAC7B,OAAO8B,KAAK,CAACzB,YAAY;IAGrC,MAAM0B,SAAS5B,OAAO6B,KAAK,CACzB7B,OAAO8B,MAAM,CACX9B,OAAO+B,GAAG,CAACX,QAAQd,WACnB,CAAC0B,QAA2BA,UAAUd,YAExCM,WACA;QAAES,cAAc;IAAO;IAGzB,4DAA4D;IAC5D,EAAE;IACF,4EAA4E;IAC5E,4EAA4E;IAC5E,2EAA2E;IAC3E,6EAA6E;IAC7E,0DAA0D;IAC1D,MAAMC,SAASlC,OAAOmC,MAAM,CAACnC,OAAOoC,IAAI,CAAC,eAAeR;IAExD,MAAMS,UACJhB,cAAcH,YACVgB,SACAlC,OAAOsC,aAAa,CAClBJ,QACA,sEAAsE;IACtE,mEAAmE;IACnE,yCAAyC;IACzCrC,OAAO8B,KAAK,CAAC/B,SAAS2C,MAAM,CAACC,KAAKC,GAAG,CAAC,GAAGpB,YAAY,OAAOC;IAGpE,OAAOrB,mBAAmByC,MAAM,CAC9B1C,OAAO+B,GAAG,CAACM,SAASL,CAAAA,QAAS5B,QAAQuC,MAAM,CAACX,SAC5C;QACEY,aAAa;QACbC,SAAS;YACP,iBAAiB;YACjBC,YAAY;YACZ,sEAAsE;YACtE,kDAAkD;YAClD,qBAAqB;QACvB;IACF;AAEJ,EAAE"}