@bleedingdev/modern-js-bff-effect 3.8.3-ultramodern.2

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 (230) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +25 -0
  3. package/dist/cjs/data-platform/batch/protocol.js +130 -0
  4. package/dist/cjs/data-platform/batch/queue.js +623 -0
  5. package/dist/cjs/data-platform/batch/request.js +121 -0
  6. package/dist/cjs/data-platform/batch/response.js +65 -0
  7. package/dist/cjs/data-platform/batch/telemetry.js +71 -0
  8. package/dist/cjs/data-platform/batch/url.js +69 -0
  9. package/dist/cjs/data-platform/batch-transport.js +59 -0
  10. package/dist/cjs/data-platform/codec.js +155 -0
  11. package/dist/cjs/data-platform/index.js +124 -0
  12. package/dist/cjs/data-platform/invalidation.js +61 -0
  13. package/dist/cjs/data-platform/trace.js +73 -0
  14. package/dist/cjs/data-platform/types.js +48 -0
  15. package/dist/cjs/data-platform/validation.js +178 -0
  16. package/dist/cjs/effect/context.js +59 -0
  17. package/dist/cjs/effect/dispatch.js +101 -0
  18. package/dist/cjs/effect/edge-context.js +61 -0
  19. package/dist/cjs/effect/edge-dispatcher.js +354 -0
  20. package/dist/cjs/effect/edge.js +62 -0
  21. package/dist/cjs/effect/endpoint-contracts.js +121 -0
  22. package/dist/cjs/effect/entry-shape-registry.js +31 -0
  23. package/dist/cjs/effect/entry-shape.js +113 -0
  24. package/dist/cjs/effect/handler/batch-handler.js +270 -0
  25. package/dist/cjs/effect/handler/batch.js +170 -0
  26. package/dist/cjs/effect/handler/definition.js +99 -0
  27. package/dist/cjs/effect/handler/envelope.js +104 -0
  28. package/dist/cjs/effect/handler/http.js +107 -0
  29. package/dist/cjs/effect/handler/openapi.js +58 -0
  30. package/dist/cjs/effect/handler/routing.js +100 -0
  31. package/dist/cjs/effect/handler/rpc.js +63 -0
  32. package/dist/cjs/effect/handler/types.js +43 -0
  33. package/dist/cjs/effect/handler.js +173 -0
  34. package/dist/cjs/effect/index.js +137 -0
  35. package/dist/cjs/effect/module.js +118 -0
  36. package/dist/cjs/effect/operation-context.js +116 -0
  37. package/dist/cjs/effect/rpcSerialization.js +54 -0
  38. package/dist/cjs/effect-client/batch.js +73 -0
  39. package/dist/cjs/effect-client/envelope.js +145 -0
  40. package/dist/cjs/effect-client/guards.js +44 -0
  41. package/dist/cjs/effect-client/index.js +208 -0
  42. package/dist/cjs/effect-client/request-context.js +64 -0
  43. package/dist/cjs/effect-client/request.js +66 -0
  44. package/dist/cjs/effect-client/runtime.js +100 -0
  45. package/dist/cjs/effect-client/types.js +18 -0
  46. package/dist/cjs/headers.js +46 -0
  47. package/dist/cjs/index.js +83 -0
  48. package/dist/esm/data-platform/batch/protocol.mjs +71 -0
  49. package/dist/esm/data-platform/batch/queue.mjs +582 -0
  50. package/dist/esm/data-platform/batch/request.mjs +68 -0
  51. package/dist/esm/data-platform/batch/response.mjs +24 -0
  52. package/dist/esm/data-platform/batch/telemetry.mjs +27 -0
  53. package/dist/esm/data-platform/batch/url.mjs +25 -0
  54. package/dist/esm/data-platform/batch-transport.mjs +12 -0
  55. package/dist/esm/data-platform/codec.mjs +90 -0
  56. package/dist/esm/data-platform/index.mjs +7 -0
  57. package/dist/esm/data-platform/invalidation.mjs +20 -0
  58. package/dist/esm/data-platform/trace.mjs +29 -0
  59. package/dist/esm/data-platform/types.mjs +4 -0
  60. package/dist/esm/data-platform/validation.mjs +128 -0
  61. package/dist/esm/effect/context.mjs +12 -0
  62. package/dist/esm/effect/dispatch.mjs +63 -0
  63. package/dist/esm/effect/edge-context.mjs +14 -0
  64. package/dist/esm/effect/edge-dispatcher.mjs +115 -0
  65. package/dist/esm/effect/edge.mjs +1 -0
  66. package/dist/esm/effect/endpoint-contracts.mjs +68 -0
  67. package/dist/esm/effect/entry-shape-registry.mjs +17 -0
  68. package/dist/esm/effect/entry-shape.mjs +51 -0
  69. package/dist/esm/effect/handler/batch-handler.mjs +232 -0
  70. package/dist/esm/effect/handler/batch.mjs +105 -0
  71. package/dist/esm/effect/handler/definition.mjs +58 -0
  72. package/dist/esm/effect/handler/envelope.mjs +63 -0
  73. package/dist/esm/effect/handler/http.mjs +69 -0
  74. package/dist/esm/effect/handler/openapi.mjs +20 -0
  75. package/dist/esm/effect/handler/routing.mjs +50 -0
  76. package/dist/esm/effect/handler/rpc.mjs +22 -0
  77. package/dist/esm/effect/handler/types.mjs +5 -0
  78. package/dist/esm/effect/handler.mjs +13 -0
  79. package/dist/esm/effect/index.mjs +7 -0
  80. package/dist/esm/effect/module.mjs +80 -0
  81. package/dist/esm/effect/operation-context.mjs +75 -0
  82. package/dist/esm/effect/rpcSerialization.mjs +16 -0
  83. package/dist/esm/effect-client/batch.mjs +35 -0
  84. package/dist/esm/effect-client/envelope.mjs +104 -0
  85. package/dist/esm/effect-client/guards.mjs +3 -0
  86. package/dist/esm/effect-client/index.mjs +110 -0
  87. package/dist/esm/effect-client/request-context.mjs +23 -0
  88. package/dist/esm/effect-client/request.mjs +28 -0
  89. package/dist/esm/effect-client/runtime.mjs +62 -0
  90. package/dist/esm/effect-client/types.mjs +0 -0
  91. package/dist/esm/headers.mjs +8 -0
  92. package/dist/esm/index.mjs +4 -0
  93. package/dist/esm/rslib-runtime.mjs +18 -0
  94. package/dist/esm-node/data-platform/batch/protocol.mjs +72 -0
  95. package/dist/esm-node/data-platform/batch/queue.mjs +583 -0
  96. package/dist/esm-node/data-platform/batch/request.mjs +69 -0
  97. package/dist/esm-node/data-platform/batch/response.mjs +25 -0
  98. package/dist/esm-node/data-platform/batch/telemetry.mjs +28 -0
  99. package/dist/esm-node/data-platform/batch/url.mjs +26 -0
  100. package/dist/esm-node/data-platform/batch-transport.mjs +13 -0
  101. package/dist/esm-node/data-platform/codec.mjs +91 -0
  102. package/dist/esm-node/data-platform/index.mjs +8 -0
  103. package/dist/esm-node/data-platform/invalidation.mjs +21 -0
  104. package/dist/esm-node/data-platform/trace.mjs +30 -0
  105. package/dist/esm-node/data-platform/types.mjs +5 -0
  106. package/dist/esm-node/data-platform/validation.mjs +129 -0
  107. package/dist/esm-node/effect/context.mjs +13 -0
  108. package/dist/esm-node/effect/dispatch.mjs +64 -0
  109. package/dist/esm-node/effect/edge-context.mjs +15 -0
  110. package/dist/esm-node/effect/edge-dispatcher.mjs +116 -0
  111. package/dist/esm-node/effect/edge.mjs +2 -0
  112. package/dist/esm-node/effect/endpoint-contracts.mjs +69 -0
  113. package/dist/esm-node/effect/entry-shape-registry.mjs +18 -0
  114. package/dist/esm-node/effect/entry-shape.mjs +63 -0
  115. package/dist/esm-node/effect/handler/batch-handler.mjs +233 -0
  116. package/dist/esm-node/effect/handler/batch.mjs +106 -0
  117. package/dist/esm-node/effect/handler/definition.mjs +59 -0
  118. package/dist/esm-node/effect/handler/envelope.mjs +64 -0
  119. package/dist/esm-node/effect/handler/http.mjs +70 -0
  120. package/dist/esm-node/effect/handler/openapi.mjs +21 -0
  121. package/dist/esm-node/effect/handler/routing.mjs +51 -0
  122. package/dist/esm-node/effect/handler/rpc.mjs +23 -0
  123. package/dist/esm-node/effect/handler/types.mjs +6 -0
  124. package/dist/esm-node/effect/handler.mjs +14 -0
  125. package/dist/esm-node/effect/index.mjs +8 -0
  126. package/dist/esm-node/effect/module.mjs +81 -0
  127. package/dist/esm-node/effect/operation-context.mjs +76 -0
  128. package/dist/esm-node/effect/rpcSerialization.mjs +17 -0
  129. package/dist/esm-node/effect-client/batch.mjs +36 -0
  130. package/dist/esm-node/effect-client/envelope.mjs +105 -0
  131. package/dist/esm-node/effect-client/guards.mjs +4 -0
  132. package/dist/esm-node/effect-client/index.mjs +111 -0
  133. package/dist/esm-node/effect-client/request-context.mjs +24 -0
  134. package/dist/esm-node/effect-client/request.mjs +29 -0
  135. package/dist/esm-node/effect-client/runtime.mjs +63 -0
  136. package/dist/esm-node/effect-client/types.mjs +1 -0
  137. package/dist/esm-node/headers.mjs +9 -0
  138. package/dist/esm-node/index.mjs +5 -0
  139. package/dist/esm-node/rslib-runtime.mjs +19 -0
  140. package/dist/types/data-platform/batch/protocol.d.ts +9 -0
  141. package/dist/types/data-platform/batch/queue.d.ts +47 -0
  142. package/dist/types/data-platform/batch/request.d.ts +19 -0
  143. package/dist/types/data-platform/batch/response.d.ts +3 -0
  144. package/dist/types/data-platform/batch/telemetry.d.ts +4 -0
  145. package/dist/types/data-platform/batch/url.d.ts +4 -0
  146. package/dist/types/data-platform/batch-transport.d.ts +3 -0
  147. package/dist/types/data-platform/codec.d.ts +17 -0
  148. package/dist/types/data-platform/index.d.ts +8 -0
  149. package/dist/types/data-platform/invalidation.d.ts +8 -0
  150. package/dist/types/data-platform/trace.d.ts +4 -0
  151. package/dist/types/data-platform/types.d.ts +151 -0
  152. package/dist/types/data-platform/validation.d.ts +29 -0
  153. package/dist/types/effect/context.d.ts +5 -0
  154. package/dist/types/effect/dispatch.d.ts +13 -0
  155. package/dist/types/effect/edge-context.d.ts +5 -0
  156. package/dist/types/effect/edge-dispatcher.d.ts +37 -0
  157. package/dist/types/effect/edge.d.ts +1 -0
  158. package/dist/types/effect/endpoint-contracts.d.ts +67 -0
  159. package/dist/types/effect/entry-shape.d.ts +32 -0
  160. package/dist/types/effect/handler/batch-handler.d.ts +11 -0
  161. package/dist/types/effect/handler/batch.d.ts +15 -0
  162. package/dist/types/effect/handler/definition.d.ts +7 -0
  163. package/dist/types/effect/handler/envelope.d.ts +13 -0
  164. package/dist/types/effect/handler/http.d.ts +15 -0
  165. package/dist/types/effect/handler/openapi.d.ts +4 -0
  166. package/dist/types/effect/handler/routing.d.ts +5 -0
  167. package/dist/types/effect/handler/rpc.d.ts +7 -0
  168. package/dist/types/effect/handler/types.d.ts +153 -0
  169. package/dist/types/effect/handler.d.ts +13 -0
  170. package/dist/types/effect/index.d.ts +6 -0
  171. package/dist/types/effect/module.d.ts +36 -0
  172. package/dist/types/effect/operation-context.d.ts +15 -0
  173. package/dist/types/effect/rpcSerialization.d.ts +3 -0
  174. package/dist/types/effect-client/batch.d.ts +2 -0
  175. package/dist/types/effect-client/envelope.d.ts +15 -0
  176. package/dist/types/effect-client/guards.d.ts +2 -0
  177. package/dist/types/effect-client/index.d.ts +58 -0
  178. package/dist/types/effect-client/request-context.d.ts +3 -0
  179. package/dist/types/effect-client/request.d.ts +1 -0
  180. package/dist/types/effect-client/runtime.d.ts +5 -0
  181. package/dist/types/effect-client/types.d.ts +68 -0
  182. package/dist/types/headers.d.ts +1 -0
  183. package/dist/types/index.d.ts +3 -0
  184. package/package.json +164 -0
  185. package/src/data-platform/batch/protocol.ts +112 -0
  186. package/src/data-platform/batch/queue.ts +876 -0
  187. package/src/data-platform/batch/request.ts +130 -0
  188. package/src/data-platform/batch/response.ts +74 -0
  189. package/src/data-platform/batch/telemetry.ts +47 -0
  190. package/src/data-platform/batch/url.ts +54 -0
  191. package/src/data-platform/batch-transport.ts +22 -0
  192. package/src/data-platform/codec.ts +145 -0
  193. package/src/data-platform/index.ts +63 -0
  194. package/src/data-platform/invalidation.ts +57 -0
  195. package/src/data-platform/trace.ts +49 -0
  196. package/src/data-platform/types.ts +186 -0
  197. package/src/data-platform/validation.ts +303 -0
  198. package/src/effect/context.ts +37 -0
  199. package/src/effect/dispatch.ts +132 -0
  200. package/src/effect/edge-context.ts +51 -0
  201. package/src/effect/edge-dispatcher.ts +310 -0
  202. package/src/effect/edge.ts +1 -0
  203. package/src/effect/endpoint-contracts.ts +191 -0
  204. package/src/effect/entry-shape-registry.cjs +16 -0
  205. package/src/effect/entry-shape-registry.d.cts +6 -0
  206. package/src/effect/entry-shape.ts +155 -0
  207. package/src/effect/handler/batch-handler.ts +475 -0
  208. package/src/effect/handler/batch.ts +182 -0
  209. package/src/effect/handler/definition.ts +121 -0
  210. package/src/effect/handler/envelope.ts +133 -0
  211. package/src/effect/handler/http.ts +133 -0
  212. package/src/effect/handler/openapi.ts +45 -0
  213. package/src/effect/handler/routing.ts +91 -0
  214. package/src/effect/handler/rpc.ts +45 -0
  215. package/src/effect/handler/types.ts +255 -0
  216. package/src/effect/handler.ts +33 -0
  217. package/src/effect/index.ts +22 -0
  218. package/src/effect/module.ts +186 -0
  219. package/src/effect/operation-context.ts +144 -0
  220. package/src/effect/rpcSerialization.ts +20 -0
  221. package/src/effect-client/batch.ts +50 -0
  222. package/src/effect-client/envelope.ts +238 -0
  223. package/src/effect-client/guards.ts +6 -0
  224. package/src/effect-client/index.ts +325 -0
  225. package/src/effect-client/request-context.ts +54 -0
  226. package/src/effect-client/request.ts +51 -0
  227. package/src/effect-client/runtime.ts +122 -0
  228. package/src/effect-client/types.ts +84 -0
  229. package/src/headers.ts +7 -0
  230. package/src/index.ts +3 -0
@@ -0,0 +1,69 @@
1
+ import "node:module";
2
+ import { DEFAULT_DATA_BATCH_HEADER } from "../types.mjs";
3
+ import { encodeBatchBody } from "./protocol.mjs";
4
+ function toHeaderRecord(headers) {
5
+ if (!headers) return {};
6
+ if (headers instanceof Headers) {
7
+ const next = {};
8
+ headers.forEach((value, key)=>{
9
+ next[key.toLowerCase()] = value;
10
+ });
11
+ return next;
12
+ }
13
+ if (Array.isArray(headers)) return headers.reduce((acc, [key, value])=>{
14
+ acc[String(key).toLowerCase()] = String(value);
15
+ return acc;
16
+ }, {});
17
+ return Object.entries(headers).reduce((acc, [key, value])=>{
18
+ if (void 0 === value) return acc;
19
+ acc[String(key).toLowerCase()] = Array.isArray(value) ? value.join(', ') : String(value);
20
+ return acc;
21
+ }, {});
22
+ }
23
+ function measureTextBytes(value) {
24
+ if ("u" > typeof TextEncoder) return new TextEncoder().encode(value).length;
25
+ if ("u" > typeof Buffer) return Buffer.byteLength(value);
26
+ return value.length;
27
+ }
28
+ function createBatchId() {
29
+ const now = Date.now().toString(36);
30
+ const random = Math.random().toString(16).slice(2, 10);
31
+ return `batch_${now}_${random}`;
32
+ }
33
+ function normalizeMethod(method) {
34
+ return (method || 'GET').toUpperCase();
35
+ }
36
+ async function toRequestBody(initBody) {
37
+ if (null == initBody) return {
38
+ body: void 0,
39
+ inferredContentType: void 0,
40
+ batchable: true
41
+ };
42
+ if ("u" > typeof ReadableStream && initBody instanceof ReadableStream) return {
43
+ body: void 0,
44
+ inferredContentType: void 0,
45
+ batchable: false
46
+ };
47
+ try {
48
+ const response = new Response(initBody);
49
+ return {
50
+ body: encodeBatchBody(new Uint8Array(await response.arrayBuffer())),
51
+ inferredContentType: response.headers.get('content-type') || void 0,
52
+ batchable: true
53
+ };
54
+ } catch {
55
+ return {
56
+ body: void 0,
57
+ inferredContentType: void 0,
58
+ batchable: false
59
+ };
60
+ }
61
+ }
62
+ function shouldBatchRequest(input) {
63
+ if (input.requestUrl.href === input.batchEndpoint) return false;
64
+ if ('off' === input.headers[DEFAULT_DATA_BATCH_HEADER]) return false;
65
+ if (!input.allowedMethods.has(input.method)) return false;
66
+ if (void 0 !== input.body) return false;
67
+ return true;
68
+ }
69
+ export { createBatchId, measureTextBytes, normalizeMethod, shouldBatchRequest, toHeaderRecord, toRequestBody };
@@ -0,0 +1,25 @@
1
+ import "node:module";
2
+ import { isPlainObject } from "../codec.mjs";
3
+ import { isBatchBody, isBatchHeaderList, isNullBodyStatus } from "./protocol.mjs";
4
+ function isBatchResponseItem(value) {
5
+ return isPlainObject(value) && 'string' == typeof value.id && 'number' == typeof value.status && (void 0 === value.headers || isBatchHeaderList(value.headers)) && (void 0 === value.body || isBatchBody(value.body)) && !(isNullBodyStatus(value.status) && void 0 !== value.body);
6
+ }
7
+ function isBatchResponsePayload(value) {
8
+ return isPlainObject(value) && 2 === value.protocolVersion && 'string' == typeof value.batchId && 'number' == typeof value.receivedAt && Array.isArray(value.items) && value.items.every((item)=>isBatchResponseItem(item));
9
+ }
10
+ async function parseResponseLikeCreateRequest(response) {
11
+ const contentType = (response.headers.get('content-type') || '').toLowerCase();
12
+ if (!response.ok) {
13
+ let data = null;
14
+ data = contentType.includes('application/json') ? await response.json() : await response.text();
15
+ response.data = data;
16
+ throw response;
17
+ }
18
+ if (contentType.includes('application/json') || contentType.includes('text/json')) return response.json();
19
+ if (contentType.includes('text/html') || contentType.includes('text/plain')) return response.text();
20
+ if (contentType.includes('application/x-www-form-urlencoded') || contentType.includes('multipart/form-data')) return response.formData();
21
+ if (contentType.includes('application/octet-stream')) return response.arrayBuffer();
22
+ if (contentType.includes('image/png')) return response;
23
+ return response.text();
24
+ }
25
+ export { isBatchResponsePayload, parseResponseLikeCreateRequest };
@@ -0,0 +1,28 @@
1
+ import "node:module";
2
+ import { trace } from "@opentelemetry/api";
3
+ const DATA_BATCH_TRANSPORT_OTEL_EVENT = 'modernjs.data.batch';
4
+ function createDataBatchTransportTelemetryAttributes(event) {
5
+ return {
6
+ 'modernjs.data.batch.type': event.type,
7
+ 'modernjs.data.batch.endpoint': event.endpoint,
8
+ 'modernjs.data.batch.degraded': 'fallback' === event.type || 'disable' === event.type,
9
+ ...event.batchId ? {
10
+ 'modernjs.data.batch.id': event.batchId
11
+ } : {},
12
+ ...'number' == typeof event.size ? {
13
+ 'modernjs.data.batch.size': event.size
14
+ } : {},
15
+ ...event.reason ? {
16
+ 'modernjs.data.batch.reason': event.reason
17
+ } : {}
18
+ };
19
+ }
20
+ function emitDataBatchTransportEvent(onEvent, event) {
21
+ try {
22
+ onEvent?.(event);
23
+ } catch {}
24
+ try {
25
+ trace.getActiveSpan()?.addEvent(DATA_BATCH_TRANSPORT_OTEL_EVENT, createDataBatchTransportTelemetryAttributes(event));
26
+ } catch {}
27
+ }
28
+ export { DATA_BATCH_TRANSPORT_OTEL_EVENT, createDataBatchTransportTelemetryAttributes, emitDataBatchTransportEvent };
@@ -0,0 +1,26 @@
1
+ import "node:module";
2
+ import { DEFAULT_DATA_BATCH_ENDPOINT } from "../types.mjs";
3
+ function resolveRuntimeOrigin() {
4
+ if ("u" > typeof window && window.location && 'string' == typeof window.location.origin && window.location.origin) return window.location.origin;
5
+ if ("u" > typeof globalThis && globalThis.location && 'string' == typeof globalThis.location?.origin) return globalThis.location.origin;
6
+ return 'http://localhost';
7
+ }
8
+ function toAbsoluteUrl(input) {
9
+ if (input instanceof URL) return input;
10
+ if ("u" > typeof Request && input instanceof Request) return new URL(input.url);
11
+ const value = String(input);
12
+ try {
13
+ return new URL(value);
14
+ } catch {
15
+ return new URL(value, resolveRuntimeOrigin());
16
+ }
17
+ }
18
+ function normalizeBatchEndpoint(requestUrl, endpoint) {
19
+ const value = endpoint || DEFAULT_DATA_BATCH_ENDPOINT;
20
+ try {
21
+ return new URL(value);
22
+ } catch {
23
+ return new URL(value, requestUrl.origin);
24
+ }
25
+ }
26
+ export { normalizeBatchEndpoint, resolveRuntimeOrigin, toAbsoluteUrl };
@@ -0,0 +1,13 @@
1
+ import "node:module";
2
+ import { createBatchTransportQueue } from "./batch/queue.mjs";
3
+ function createDataBatchTransport(options = {}) {
4
+ const fallbackFetch = 'function' == typeof fetch ? fetch.bind(globalThis) : void 0;
5
+ const baseFetch = options.fetch || fallbackFetch;
6
+ if (!baseFetch) throw new Error('createDataBatchTransport requires a fetch implementation');
7
+ return createBatchTransportQueue({
8
+ options,
9
+ baseFetch
10
+ });
11
+ }
12
+ export { DATA_BATCH_TRANSPORT_OTEL_EVENT, createDataBatchTransportTelemetryAttributes, emitDataBatchTransportEvent } from "./batch/telemetry.mjs";
13
+ export { createDataBatchTransport };
@@ -0,0 +1,91 @@
1
+ import "node:module";
2
+ function isPlainObject(value) {
3
+ if ('object' != typeof value || null === value || Array.isArray(value)) return false;
4
+ const proto = Object.getPrototypeOf(value);
5
+ return proto === Object.prototype || null === proto;
6
+ }
7
+ function canonicalize(value) {
8
+ if (Array.isArray(value)) return value.map((item)=>canonicalize(item));
9
+ if (isPlainObject(value)) return Object.keys(value).sort().reduce((acc, key)=>{
10
+ acc[key] = canonicalize(value[key]);
11
+ return acc;
12
+ }, {});
13
+ return value;
14
+ }
15
+ function stableStringify(value) {
16
+ return JSON.stringify(canonicalize(value));
17
+ }
18
+ function encodeRequestEnvelopeHeader(envelope) {
19
+ return encodeURIComponent(stableStringify(envelope));
20
+ }
21
+ function isRequestEnvelopeShape(value) {
22
+ if (!isPlainObject(value)) return false;
23
+ return 1 === value.protocolVersion && 'string' == typeof value.operationId && 'string' == typeof value.appNamespace && 'string' == typeof value.origin && 'string' == typeof value.scopeKey && 'string' == typeof value.inputHash && 'number' == typeof value.timestamp;
24
+ }
25
+ function decodeRequestEnvelopeHeader(value) {
26
+ try {
27
+ const decoded = decodeURIComponent(value);
28
+ const parsed = JSON.parse(decoded);
29
+ if (!isRequestEnvelopeShape(parsed)) return null;
30
+ return parsed;
31
+ } catch {
32
+ return null;
33
+ }
34
+ }
35
+ function hashString(value) {
36
+ let hash = 0x811c9dc5;
37
+ for(let index = 0; index < value.length; index++){
38
+ hash ^= value.charCodeAt(index);
39
+ hash = Math.imul(hash, 0x01000193);
40
+ }
41
+ return (hash >>> 0).toString(16).padStart(8, '0');
42
+ }
43
+ function sanitizeSegment(segment) {
44
+ const normalized = segment.trim().replace(/[^a-zA-Z0-9_-]+/g, '_');
45
+ return normalized.length > 0 ? normalized : 'unknown';
46
+ }
47
+ function normalizeOrigin(origin) {
48
+ const normalized = origin.trim();
49
+ try {
50
+ const url = new URL(normalized);
51
+ return `${url.protocol}//${url.host}`.toLowerCase();
52
+ } catch {
53
+ return normalized.toLowerCase();
54
+ }
55
+ }
56
+ function normalizeOperationDescriptor(input) {
57
+ return {
58
+ appNamespace: sanitizeSegment(input.appNamespace),
59
+ apiId: sanitizeSegment(input.apiId),
60
+ group: sanitizeSegment(input.group),
61
+ endpoint: sanitizeSegment(input.endpoint),
62
+ schemaHash: input.schemaHash || null,
63
+ version: input.version ?? 1
64
+ };
65
+ }
66
+ function createOperationId(input) {
67
+ const descriptor = normalizeOperationDescriptor(input);
68
+ const readable = `${descriptor.appNamespace}.${descriptor.apiId}.${descriptor.group}.${descriptor.endpoint}.v${String(descriptor.version)}`;
69
+ return `${readable}:${hashString(stableStringify(descriptor))}`;
70
+ }
71
+ function buildScopeKey(scope) {
72
+ const canonical = {
73
+ appNamespace: sanitizeSegment(scope.appNamespace),
74
+ origin: normalizeOrigin(scope.origin),
75
+ tenantId: scope.tenantId ?? null,
76
+ userId: scope.userId ?? null,
77
+ sessionId: scope.sessionId ?? null
78
+ };
79
+ return `${canonical.appNamespace}:${hashString(stableStringify(canonical))}`;
80
+ }
81
+ function buildQueryKey(input) {
82
+ const canonical = {
83
+ operationId: input.operationId,
84
+ scopeKey: input.scopeKey,
85
+ requestMode: input.requestMode ?? 'cache-first',
86
+ requestInput: input.requestInput ?? null,
87
+ selectionPlan: input.selectionPlan ?? null
88
+ };
89
+ return `${input.operationId}:${hashString(stableStringify(canonical))}`;
90
+ }
91
+ export { buildQueryKey, buildScopeKey, createOperationId, decodeRequestEnvelopeHeader, encodeRequestEnvelopeHeader, hashString, isPlainObject, normalizeOrigin, sanitizeSegment, stableStringify };
@@ -0,0 +1,8 @@
1
+ import "node:module";
2
+ export { measureTextBytes, normalizeMethod } from "./batch/request.mjs";
3
+ export { DATA_BATCH_TRANSPORT_OTEL_EVENT, createDataBatchTransport, createDataBatchTransportTelemetryAttributes, emitDataBatchTransportEvent } from "./batch-transport.mjs";
4
+ export { buildQueryKey, buildScopeKey, createOperationId, decodeRequestEnvelopeHeader, encodeRequestEnvelopeHeader, isPlainObject, normalizeOrigin, stableStringify } from "./codec.mjs";
5
+ export { createInvalidationEvent, shouldApplyInvalidation } from "./invalidation.mjs";
6
+ export { deriveChildTraceContext, formatTraceparentHeader, parseTraceparentHeader } from "./trace.mjs";
7
+ export { DEFAULT_DATA_BATCH_ENDPOINT, DEFAULT_DATA_BATCH_HEADER, DEFAULT_DATA_ENVELOPE_HEADER } from "./types.mjs";
8
+ export { createHydrationEnvelope, createRequestEnvelope, validateHydrationEnvelope, validateRequestEnvelope, validateSelectionPlan } from "./validation.mjs";
@@ -0,0 +1,21 @@
1
+ import "node:module";
2
+ import { buildScopeKey, createOperationId, sanitizeSegment } from "./codec.mjs";
3
+ function createInvalidationEvent(input) {
4
+ return {
5
+ sourceNamespace: sanitizeSegment(input.sourceOperation.appNamespace),
6
+ sourceOperationId: createOperationId(input.sourceOperation),
7
+ scopeKey: buildScopeKey(input.sourceScope),
8
+ targetNamespaces: input.targetNamespaces?.map((namespace)=>sanitizeSegment(namespace)),
9
+ targetOperationIds: input.targetOperations?.map((operation)=>createOperationId(operation))
10
+ };
11
+ }
12
+ function shouldApplyInvalidation(event, subscriber) {
13
+ if (subscriber.scopeKey && subscriber.scopeKey !== event.scopeKey) return false;
14
+ const sameNamespace = subscriber.namespace === event.sourceNamespace;
15
+ const allowedCrossNamespace = true === subscriber.acceptCrossNamespace && event.targetNamespaces?.includes(subscriber.namespace) === true;
16
+ if (!sameNamespace && !allowedCrossNamespace) return false;
17
+ if (!subscriber.operationIds || 0 === subscriber.operationIds.length) return true;
18
+ if (!event.targetOperationIds || 0 === event.targetOperationIds.length) return true;
19
+ return subscriber.operationIds.some((operationId)=>event.targetOperationIds?.includes(operationId));
20
+ }
21
+ export { createInvalidationEvent, shouldApplyInvalidation };
@@ -0,0 +1,30 @@
1
+ import "node:module";
2
+ import { parseTraceparent } from "@modern-js/create-request";
3
+ function isAllZeroHex(value) {
4
+ return /^0+$/.test(value);
5
+ }
6
+ function isValidHex(value, length) {
7
+ return value.length === length && /^[0-9a-f]+$/.test(value);
8
+ }
9
+ function parseTraceparentHeader(header) {
10
+ return parseTraceparent(header) ?? null;
11
+ }
12
+ function formatTraceparentHeader(trace) {
13
+ const traceId = trace.traceId.toLowerCase();
14
+ const spanId = trace.spanId.toLowerCase();
15
+ if (!isValidHex(traceId, 32) || !isValidHex(spanId, 16)) throw new Error('Invalid trace context: traceId/spanId format mismatch');
16
+ if (isAllZeroHex(traceId) || isAllZeroHex(spanId)) throw new Error('Invalid trace context: traceId/spanId cannot be zero');
17
+ const flags = trace.sampled ? '01' : '00';
18
+ return `00-${traceId}-${spanId}-${flags}`;
19
+ }
20
+ function deriveChildTraceContext(parent, childSpanId) {
21
+ const normalizedSpanId = childSpanId.toLowerCase();
22
+ if (!isValidHex(normalizedSpanId, 16) || isAllZeroHex(normalizedSpanId)) throw new Error('Invalid child span id');
23
+ return {
24
+ traceId: parent.traceId.toLowerCase(),
25
+ spanId: normalizedSpanId,
26
+ sampled: parent.sampled,
27
+ parentSpanId: parent.spanId.toLowerCase()
28
+ };
29
+ }
30
+ export { deriveChildTraceContext, formatTraceparentHeader, parseTraceparentHeader };
@@ -0,0 +1,5 @@
1
+ import "node:module";
2
+ const DEFAULT_DATA_ENVELOPE_HEADER = 'x-modernjs-data-envelope';
3
+ const DEFAULT_DATA_BATCH_ENDPOINT = '/_data/batch';
4
+ const DEFAULT_DATA_BATCH_HEADER = 'x-modernjs-data-batch';
5
+ export { DEFAULT_DATA_BATCH_ENDPOINT, DEFAULT_DATA_BATCH_HEADER, DEFAULT_DATA_ENVELOPE_HEADER };
@@ -0,0 +1,129 @@
1
+ import "node:module";
2
+ import { buildScopeKey, createOperationId, hashString, isPlainObject, normalizeOrigin, sanitizeSegment, stableStringify } from "./codec.mjs";
3
+ import { formatTraceparentHeader, parseTraceparentHeader } from "./trace.mjs";
4
+ function validateSelectionPlan(plan, options = {}) {
5
+ const maxDepthLimit = options.maxDepth ?? 8;
6
+ const maxFieldsLimit = options.maxFields ?? 256;
7
+ const allowedLeafPaths = options.allowedLeafPaths ? new Set(options.allowedLeafPaths) : null;
8
+ const errors = [];
9
+ let maxDepth = 0;
10
+ let fieldCount = 0;
11
+ const walk = (node, path)=>{
12
+ if (!isPlainObject(node)) return void errors.push(`Selection node at "${path.join('.') || '<root>'}" must be an object`);
13
+ const keys = Object.keys(node);
14
+ if (0 === keys.length) return void errors.push(`Selection node at "${path.join('.') || '<root>'}" cannot be empty`);
15
+ for (const key of keys){
16
+ fieldCount += 1;
17
+ if (fieldCount > maxFieldsLimit) return void errors.push(`Selection has too many fields: ${String(fieldCount)} > ${String(maxFieldsLimit)}`);
18
+ const nextPath = [
19
+ ...path,
20
+ key
21
+ ];
22
+ const depth = nextPath.length;
23
+ if (depth > maxDepth) maxDepth = depth;
24
+ if (depth > maxDepthLimit) return void errors.push(`Selection exceeds maxDepth at "${nextPath.join('.')}" (${String(depth)} > ${String(maxDepthLimit)})`);
25
+ const value = node[key];
26
+ if (true === value) {
27
+ if (allowedLeafPaths && !allowedLeafPaths.has(nextPath.join('.'))) errors.push(`Unknown selected field "${nextPath.join('.')}"`);
28
+ continue;
29
+ }
30
+ if (!isPlainObject(value)) {
31
+ errors.push(`Invalid selection value at "${nextPath.join('.')}"; expected true or nested object`);
32
+ continue;
33
+ }
34
+ walk(value, nextPath);
35
+ }
36
+ };
37
+ walk(plan, []);
38
+ return {
39
+ ok: 0 === errors.length,
40
+ errors,
41
+ stats: {
42
+ maxDepth,
43
+ fieldCount
44
+ }
45
+ };
46
+ }
47
+ function createRequestEnvelope(input) {
48
+ if (input.requireTraceContext && !input.traceContext) throw new Error('Trace context is required for this request envelope');
49
+ const traceparent = input.traceContext ? formatTraceparentHeader(input.traceContext) : void 0;
50
+ const envelope = {
51
+ protocolVersion: input.protocolVersion ?? 1,
52
+ operationId: createOperationId(input.operation),
53
+ appNamespace: sanitizeSegment(input.scope.appNamespace),
54
+ origin: normalizeOrigin(input.scope.origin),
55
+ requestMode: input.requestMode ?? 'cache-first',
56
+ mutationMode: input.mutationMode,
57
+ scopeKey: buildScopeKey(input.scope),
58
+ input: input.requestInput,
59
+ inputHash: hashString(stableStringify(input.requestInput ?? null)),
60
+ selectionPlan: input.selectionPlan,
61
+ selectionHash: input.selectionPlan ? hashString(stableStringify(input.selectionPlan)) : void 0,
62
+ traceparent,
63
+ timestamp: input.timestamp ?? Date.now()
64
+ };
65
+ return envelope;
66
+ }
67
+ function validateRequestEnvelope(envelope, options = {}) {
68
+ const errors = [];
69
+ if (void 0 !== options.expectedProtocolVersion && envelope.protocolVersion !== options.expectedProtocolVersion) errors.push(`Protocol mismatch: expected ${String(options.expectedProtocolVersion)} but received ${String(envelope.protocolVersion)}`);
70
+ if (options.expectedNamespace && envelope.appNamespace !== options.expectedNamespace) errors.push(`Namespace mismatch: expected ${options.expectedNamespace} but received ${envelope.appNamespace}`);
71
+ if (options.expectedOrigin) {
72
+ const expectedOrigin = normalizeOrigin(options.expectedOrigin);
73
+ if (envelope.origin !== expectedOrigin) errors.push(`Origin mismatch: expected ${expectedOrigin} but received ${envelope.origin}`);
74
+ }
75
+ if (!envelope.operationId) errors.push('Missing operationId');
76
+ if (!envelope.scopeKey) errors.push('Missing scopeKey');
77
+ if (options.requireTraceContext && !envelope.traceparent) errors.push('Missing trace context');
78
+ if (envelope.traceparent && !parseTraceparentHeader(envelope.traceparent)) errors.push('Invalid traceparent header');
79
+ const computedInputHash = hashString(stableStringify(envelope.input ?? null));
80
+ if (computedInputHash !== envelope.inputHash) errors.push('Input hash mismatch');
81
+ if (envelope.selectionPlan) {
82
+ const computedSelectionHash = hashString(stableStringify(envelope.selectionPlan));
83
+ if (computedSelectionHash !== envelope.selectionHash) errors.push('Selection hash mismatch');
84
+ }
85
+ return {
86
+ ok: 0 === errors.length,
87
+ errors
88
+ };
89
+ }
90
+ function createHydrationEnvelope(input) {
91
+ const envelopeWithoutChecksum = {
92
+ protocolVersion: input.protocolVersion ?? 1,
93
+ runtimeVersion: input.runtimeVersion,
94
+ appNamespace: sanitizeSegment(input.scope.appNamespace),
95
+ origin: normalizeOrigin(input.scope.origin),
96
+ createdAt: input.createdAt ?? Date.now(),
97
+ payload: input.payload
98
+ };
99
+ const checksum = hashString(stableStringify(envelopeWithoutChecksum));
100
+ return {
101
+ ...envelopeWithoutChecksum,
102
+ checksum
103
+ };
104
+ }
105
+ function validateHydrationEnvelope(envelope, options = {}) {
106
+ const errors = [];
107
+ if (void 0 !== options.expectedProtocolVersion && envelope.protocolVersion !== options.expectedProtocolVersion) errors.push(`Protocol mismatch: expected ${String(options.expectedProtocolVersion)} but received ${String(envelope.protocolVersion)}`);
108
+ if (options.expectedNamespace && envelope.appNamespace !== options.expectedNamespace) errors.push(`Namespace mismatch: expected ${options.expectedNamespace} but received ${envelope.appNamespace}`);
109
+ if (options.expectedOrigin) {
110
+ const expectedOrigin = normalizeOrigin(options.expectedOrigin);
111
+ if (envelope.origin !== expectedOrigin) errors.push(`Origin mismatch: expected ${expectedOrigin} but received ${envelope.origin}`);
112
+ }
113
+ if (options.expectedRuntimeVersion && envelope.runtimeVersion !== options.expectedRuntimeVersion) errors.push(`Runtime version mismatch: expected ${options.expectedRuntimeVersion} but received ${envelope.runtimeVersion}`);
114
+ const checksumBase = {
115
+ protocolVersion: envelope.protocolVersion,
116
+ runtimeVersion: envelope.runtimeVersion,
117
+ appNamespace: envelope.appNamespace,
118
+ origin: envelope.origin,
119
+ createdAt: envelope.createdAt,
120
+ payload: envelope.payload
121
+ };
122
+ const checksum = hashString(stableStringify(checksumBase));
123
+ if (checksum !== envelope.checksum) errors.push('Hydration checksum mismatch');
124
+ return {
125
+ ok: 0 === errors.length,
126
+ errors
127
+ };
128
+ }
129
+ export { createHydrationEnvelope, createRequestEnvelope, validateHydrationEnvelope, validateRequestEnvelope, validateSelectionPlan };
@@ -0,0 +1,13 @@
1
+ import "node:module";
2
+ import { AsyncLocalStorage } from "node:async_hooks";
3
+ import { createEffectOperationContext, kEffectContextStorage } from "./operation-context.mjs";
4
+ const globalStore = globalThis;
5
+ const effectContextStorage = globalStore[kEffectContextStorage] ?? (globalStore[kEffectContextStorage] = new AsyncLocalStorage());
6
+ const runWithEffectContext = (context, cb)=>effectContextStorage.run(context, cb);
7
+ const useEffectContext = ()=>{
8
+ const context = effectContextStorage.getStore();
9
+ if (!context) throw new Error("Can't call useEffectContext out of Effect runtime scope");
10
+ return context;
11
+ };
12
+ const useOperationContext = ()=>useEffectContext().operationContext;
13
+ export { createEffectOperationContext, runWithEffectContext, useEffectContext, useOperationContext };
@@ -0,0 +1,64 @@
1
+ import "node:module";
2
+ import { createSafeFailureResponse } from "@modern-js/runtime-extensions/safe-failure";
3
+ import { createEffectOperationContext } from "./operation-context.mjs";
4
+ function normalizeEffectBffPrefix(prefix) {
5
+ if (!prefix || '/' === prefix) return '';
6
+ return prefix.endsWith('/') ? prefix.slice(0, -1) : prefix;
7
+ }
8
+ function removeEffectBffPrefixFromPath(pathname, prefix) {
9
+ const normalized = normalizeEffectBffPrefix(prefix);
10
+ if (!normalized || pathname !== normalized && !pathname.startsWith(`${normalized}/`)) return pathname;
11
+ const sliced = pathname.slice(normalized.length);
12
+ return sliced.startsWith('/') ? sliced : `/${sliced}`;
13
+ }
14
+ function matchesEffectBffPrefix(pathname, prefix) {
15
+ const normalized = normalizeEffectBffPrefix(prefix);
16
+ return !normalized || pathname === normalized || pathname.startsWith(`${normalized}/`);
17
+ }
18
+ function createEffectBffMountedRequest(req, prefix) {
19
+ const url = new URL(req.url);
20
+ const nextPath = removeEffectBffPrefixFromPath(url.pathname, prefix);
21
+ if (nextPath !== url.pathname) {
22
+ url.pathname = nextPath;
23
+ return new Request(url, req);
24
+ }
25
+ return req;
26
+ }
27
+ function createEffectBffDispatchContext(originalRequest, mountedRequest, options) {
28
+ const path = options.path ?? new URL(originalRequest.url).pathname;
29
+ const method = options.method ?? originalRequest.method;
30
+ const env = options.env ?? {};
31
+ return {
32
+ request: mountedRequest,
33
+ env,
34
+ path,
35
+ method,
36
+ operationContext: createEffectOperationContext({
37
+ request: mountedRequest,
38
+ env,
39
+ path,
40
+ method
41
+ })
42
+ };
43
+ }
44
+ async function dispatchEffectBffRequestWithContext(handler, request, options) {
45
+ const requestPath = new URL(request.url).pathname;
46
+ if (!matchesEffectBffPrefix(requestPath, options.prefix)) return new Response('', {
47
+ status: 404
48
+ });
49
+ const mountedRequest = createEffectBffMountedRequest(request, options.prefix);
50
+ const effectContext = createEffectBffDispatchContext(request, mountedRequest, options);
51
+ try {
52
+ const response = await options.runWithEffectContext(effectContext, ()=>handler(mountedRequest, effectContext));
53
+ if (!(response instanceof Response)) throw new Error('[BFF][Effect] Effect handler must return Response instance.');
54
+ return new Response(response.body, response);
55
+ } catch (error) {
56
+ if (error instanceof Response) return new Response(error.body, error);
57
+ if (options.onError) {
58
+ const errorResponse = await options.onError(error, effectContext);
59
+ if (errorResponse instanceof Response) return errorResponse;
60
+ }
61
+ return createSafeFailureResponse(error);
62
+ }
63
+ }
64
+ export { dispatchEffectBffRequestWithContext };
@@ -0,0 +1,15 @@
1
+ import "node:module";
2
+ import { createEffectOperationContext, kEffectContextStorage } from "./operation-context.mjs";
3
+ const globalStore = globalThis;
4
+ const asyncHooks = globalStore.process?.getBuiltinModule?.('node:async_hooks');
5
+ const AsyncLocalStorage = asyncHooks?.AsyncLocalStorage;
6
+ if ('function' != typeof AsyncLocalStorage) throw new Error('[BFF][Effect] The edge runtime must provide AsyncLocalStorage. Enable Node.js compatibility or the nodejs_als compatibility flag.');
7
+ const effectContextStorage = globalStore[kEffectContextStorage] ?? (globalStore[kEffectContextStorage] = new AsyncLocalStorage());
8
+ const runWithEffectContext = (context, cb)=>effectContextStorage.run(context, cb);
9
+ const useEffectContext = ()=>{
10
+ const context = effectContextStorage.getStore();
11
+ if (!context) throw new Error("Can't call useEffectContext out of Effect runtime scope");
12
+ return context;
13
+ };
14
+ const useOperationContext = ()=>useEffectContext().operationContext;
15
+ export { createEffectOperationContext, runWithEffectContext, useEffectContext, useOperationContext };