@webiny/app 6.6.0-alpha.0 → 6.6.0-alpha.10
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/App.js +6 -1
- package/App.js.map +1 -1
- package/components/Image.d.ts +1 -1
- package/errors/GraphQLOperationError.d.ts +10 -0
- package/errors/GraphQLOperationError.js +11 -0
- package/errors/GraphQLOperationError.js.map +1 -0
- package/errors/__tests__/GraphQLOperationError.test.d.ts +1 -0
- package/errors/__tests__/GraphQLOperationError.test.js +97 -0
- package/errors/__tests__/GraphQLOperationError.test.js.map +1 -0
- package/errors/index.d.ts +2 -0
- package/errors/index.js +1 -0
- package/exports/admin.d.ts +3 -0
- package/exports/admin.js +3 -0
- package/features/apiRequestHeaders/ApiRequestHeadersResolver.d.ts +13 -0
- package/features/apiRequestHeaders/ApiRequestHeadersResolver.js +15 -0
- package/features/apiRequestHeaders/ApiRequestHeadersResolver.js.map +1 -0
- package/features/apiRequestHeaders/ApiStreamClientDecorator.d.ts +12 -0
- package/features/apiRequestHeaders/ApiStreamClientDecorator.js +25 -0
- package/features/apiRequestHeaders/ApiStreamClientDecorator.js.map +1 -0
- package/features/apiRequestHeaders/GraphQLClientDecorator.d.ts +12 -0
- package/features/apiRequestHeaders/GraphQLClientDecorator.js +25 -0
- package/features/apiRequestHeaders/GraphQLClientDecorator.js.map +1 -0
- package/features/apiRequestHeaders/__tests__/ApiRequestHeaders.test.d.ts +1 -0
- package/features/apiRequestHeaders/__tests__/ApiRequestHeaders.test.js +199 -0
- package/features/apiRequestHeaders/__tests__/ApiRequestHeaders.test.js.map +1 -0
- package/features/apiRequestHeaders/abstractions.d.ts +26 -0
- package/features/apiRequestHeaders/abstractions.js +6 -0
- package/features/apiRequestHeaders/abstractions.js.map +1 -0
- package/features/apiRequestHeaders/feature.d.ts +6 -0
- package/features/apiRequestHeaders/feature.js +16 -0
- package/features/apiRequestHeaders/feature.js.map +1 -0
- package/features/apiRequestHeaders/index.d.ts +2 -0
- package/features/apiRequestHeaders/index.js +2 -0
- package/features/apiRequestHeaders/mergeHeaders.d.ts +13 -0
- package/features/apiRequestHeaders/mergeHeaders.js +20 -0
- package/features/apiRequestHeaders/mergeHeaders.js.map +1 -0
- package/features/apiStreamClient/FetchApiStreamClient.d.ts +9 -0
- package/features/apiStreamClient/FetchApiStreamClient.js +63 -0
- package/features/apiStreamClient/FetchApiStreamClient.js.map +1 -0
- package/features/apiStreamClient/__tests__/FetchApiStreamClient.test.d.ts +1 -0
- package/features/apiStreamClient/__tests__/FetchApiStreamClient.test.js +170 -0
- package/features/apiStreamClient/__tests__/FetchApiStreamClient.test.js.map +1 -0
- package/features/apiStreamClient/__tests__/readServerSentEvents.test.d.ts +1 -0
- package/features/apiStreamClient/__tests__/readServerSentEvents.test.js +160 -0
- package/features/apiStreamClient/__tests__/readServerSentEvents.test.js.map +1 -0
- package/features/apiStreamClient/abstractions.d.ts +44 -0
- package/features/apiStreamClient/abstractions.js +10 -0
- package/features/apiStreamClient/abstractions.js.map +1 -0
- package/features/apiStreamClient/feature.d.ts +3 -0
- package/features/apiStreamClient/feature.js +17 -0
- package/features/apiStreamClient/feature.js.map +1 -0
- package/features/apiStreamClient/index.d.ts +5 -0
- package/features/apiStreamClient/index.js +5 -0
- package/features/apiStreamClient/readServerSentEvents.d.ts +10 -0
- package/features/apiStreamClient/readServerSentEvents.js +29 -0
- package/features/apiStreamClient/readServerSentEvents.js.map +1 -0
- package/features/apiStreamClient/toPayloadHash.d.ts +14 -0
- package/features/apiStreamClient/toPayloadHash.js +7 -0
- package/features/apiStreamClient/toPayloadHash.js.map +1 -0
- package/features/graphqlClient/BatchingGraphQLClient.d.ts +3 -1
- package/features/graphqlClient/BatchingGraphQLClient.js +13 -3
- package/features/graphqlClient/BatchingGraphQLClient.js.map +1 -1
- package/features/graphqlClient/FetchGraphQLClient.d.ts +3 -0
- package/features/graphqlClient/FetchGraphQLClient.js +18 -4
- package/features/graphqlClient/FetchGraphQLClient.js.map +1 -1
- package/features/graphqlClient/GraphQLExtensionsEvent.d.ts +18 -0
- package/features/graphqlClient/GraphQLExtensionsEvent.js +13 -0
- package/features/graphqlClient/GraphQLExtensionsEvent.js.map +1 -0
- package/features/graphqlClient/__tests__/GraphQLClient.test.js +202 -0
- package/features/graphqlClient/__tests__/GraphQLClient.test.js.map +1 -1
- package/features/graphqlClient/abstractions.d.ts +7 -0
- package/features/graphqlClient/abstractions.js +2 -1
- package/features/graphqlClient/abstractions.js.map +1 -1
- package/features/graphqlClient/index.d.ts +3 -0
- package/features/graphqlClient/index.js +2 -1
- package/features/graphqlClient/publishExtensions.d.ts +13 -0
- package/features/graphqlClient/publishExtensions.js +16 -0
- package/features/graphqlClient/publishExtensions.js.map +1 -0
- package/features/router/HistoryRouterGateway.test.js +68 -0
- package/features/router/HistoryRouterGateway.test.js.map +1 -1
- package/features/router/Router.d.ts +9 -2
- package/features/router/Router.js +4 -5
- package/features/router/Router.js.map +1 -1
- package/package.json +17 -17
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { createAbstraction } from "@webiny/feature/admin";
|
|
2
|
+
const ApiRequestHeaders = createAbstraction("ApiRequestHeaders");
|
|
3
|
+
const ApiRequestHeadersResolver = createAbstraction("ApiRequestHeadersResolver");
|
|
4
|
+
export { ApiRequestHeaders, ApiRequestHeadersResolver };
|
|
5
|
+
|
|
6
|
+
//# sourceMappingURL=abstractions.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"features/apiRequestHeaders/abstractions.js","sources":["../../../src/features/apiRequestHeaders/abstractions.ts"],"sourcesContent":["import { createAbstraction } from \"@webiny/feature/admin\";\n\ntype IHeaders = Record<string, string | number | undefined>;\n\n/**\n * Extra headers for every request to Webiny's API (`GraphQLClient` and `ApiStreamClient`), read when\n * a request is sent. An extension registers one for a header the API needs on each request, e.g. a\n * scope its own decorators read. Headers the request sets itself (tenant, auth, …) win.\n *\n * Register it in the root container (as `RegisterFeature` does): the clients look providers up there.\n * Only for Webiny's API: requests to other hosts (storage uploads, identity providers) don't get them.\n */\nexport interface IApiRequestHeaders {\n getHeaders(): IHeaders | Promise<IHeaders>;\n}\n\nexport const ApiRequestHeaders = createAbstraction<IApiRequestHeaders>(\"ApiRequestHeaders\");\n\nexport namespace ApiRequestHeaders {\n export type Interface = IApiRequestHeaders;\n export type Headers = IHeaders;\n}\n\n/** The headers of every registered `ApiRequestHeaders`, collected for one request. */\nexport interface IApiRequestHeadersResolver {\n resolve(): Promise<IHeaders>;\n}\n\nexport const ApiRequestHeadersResolver = createAbstraction<IApiRequestHeadersResolver>(\n \"ApiRequestHeadersResolver\"\n);\n\nexport namespace ApiRequestHeadersResolver {\n export type Interface = IApiRequestHeadersResolver;\n}\n"],"names":["ApiRequestHeaders","createAbstraction","ApiRequestHeadersResolver"],"mappings":";AAgBO,MAAMA,oBAAoBC,kBAAsC;AAYhE,MAAMC,4BAA4BD,kBACrC"}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Adds every `ApiRequestHeaders` provider's headers to requests to Webiny's API. Register it after
|
|
3
|
+
* the clients and before the decorators that add the tenant and auth headers, so those wrap it and
|
|
4
|
+
* win over a provider's header of the same name.
|
|
5
|
+
*/
|
|
6
|
+
export declare const ApiRequestHeadersFeature: import("@webiny/feature/admin").FeatureDefinition<any, []>;
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { createFeature } from "@webiny/feature/admin";
|
|
2
|
+
import { ApiRequestHeadersResolver } from "./abstractions.js";
|
|
3
|
+
import { ApiRequestHeadersResolver as external_ApiRequestHeadersResolver_js_ApiRequestHeadersResolver } from "./ApiRequestHeadersResolver.js";
|
|
4
|
+
import { ApiStreamClientDecorator } from "./ApiStreamClientDecorator.js";
|
|
5
|
+
import { GraphQLClientDecorator } from "./GraphQLClientDecorator.js";
|
|
6
|
+
const ApiRequestHeadersFeature = createFeature({
|
|
7
|
+
name: "ApiRequestHeaders",
|
|
8
|
+
register (container) {
|
|
9
|
+
container.registerInstance(ApiRequestHeadersResolver, new external_ApiRequestHeadersResolver_js_ApiRequestHeadersResolver(container));
|
|
10
|
+
container.registerDecorator(GraphQLClientDecorator);
|
|
11
|
+
container.registerDecorator(ApiStreamClientDecorator);
|
|
12
|
+
}
|
|
13
|
+
});
|
|
14
|
+
export { ApiRequestHeadersFeature };
|
|
15
|
+
|
|
16
|
+
//# sourceMappingURL=feature.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"features/apiRequestHeaders/feature.js","sources":["../../../src/features/apiRequestHeaders/feature.ts"],"sourcesContent":["import { createFeature } from \"@webiny/feature/admin\";\nimport type { Container } from \"@webiny/di\";\nimport { ApiRequestHeadersResolver as ResolverAbstraction } from \"./abstractions.js\";\nimport { ApiRequestHeadersResolver } from \"./ApiRequestHeadersResolver.js\";\nimport { ApiStreamClientDecorator } from \"./ApiStreamClientDecorator.js\";\nimport { GraphQLClientDecorator } from \"./GraphQLClientDecorator.js\";\n\n/**\n * Adds every `ApiRequestHeaders` provider's headers to requests to Webiny's API. Register it after\n * the clients and before the decorators that add the tenant and auth headers, so those wrap it and\n * win over a provider's header of the same name.\n */\nexport const ApiRequestHeadersFeature = createFeature({\n name: \"ApiRequestHeaders\",\n register(container: Container) {\n container.registerInstance(ResolverAbstraction, new ApiRequestHeadersResolver(container));\n container.registerDecorator(GraphQLClientDecorator);\n container.registerDecorator(ApiStreamClientDecorator);\n }\n});\n"],"names":["ApiRequestHeadersFeature","createFeature","container","ResolverAbstraction","ApiRequestHeadersResolver","GraphQLClientDecorator","ApiStreamClientDecorator"],"mappings":";;;;;AAYO,MAAMA,2BAA2BC,cAAc;IAClD,MAAM;IACN,UAASC,SAAoB;QACzBA,UAAU,gBAAgB,CAACC,2BAAqB,IAAIC,gEAA0BF;QAC9EA,UAAU,iBAAiB,CAACG;QAC5BH,UAAU,iBAAiB,CAACI;IAChC;AACJ"}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { ApiRequestHeaders } from "./abstractions.js";
|
|
2
|
+
type Headers = ApiRequestHeaders.Headers;
|
|
3
|
+
/**
|
|
4
|
+
* The providers' headers merged in order: a later provider's value replaces an earlier one's, whatever
|
|
5
|
+
* the case of the name (header names are case-insensitive). An undefined value means "no header".
|
|
6
|
+
*/
|
|
7
|
+
export declare function mergeProviderHeaders(results: Array<Headers | undefined>): Headers;
|
|
8
|
+
/**
|
|
9
|
+
* The request's own headers (and those of the decorators around this one) win over the providers', whatever
|
|
10
|
+
* the case of the name.
|
|
11
|
+
*/
|
|
12
|
+
export declare function withProviderHeaders(provided: Headers, own: Headers | undefined): Headers;
|
|
13
|
+
export {};
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
function mergeProviderHeaders(results) {
|
|
2
|
+
const merged = new Map();
|
|
3
|
+
for (const result of results)for (const [name, value] of Object.entries(result ?? {}))if (void 0 !== value) merged.set(name.toLowerCase(), [
|
|
4
|
+
name,
|
|
5
|
+
value
|
|
6
|
+
]);
|
|
7
|
+
return Object.fromEntries(merged.values());
|
|
8
|
+
}
|
|
9
|
+
function withProviderHeaders(provided, own) {
|
|
10
|
+
const ownNames = new Set(Object.keys(own ?? {}).map((name)=>name.toLowerCase()));
|
|
11
|
+
const headers = {};
|
|
12
|
+
for (const [name, value] of Object.entries(provided))if (!ownNames.has(name.toLowerCase())) headers[name] = value;
|
|
13
|
+
return {
|
|
14
|
+
...headers,
|
|
15
|
+
...own
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
export { mergeProviderHeaders, withProviderHeaders };
|
|
19
|
+
|
|
20
|
+
//# sourceMappingURL=mergeHeaders.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"features/apiRequestHeaders/mergeHeaders.js","sources":["../../../src/features/apiRequestHeaders/mergeHeaders.ts"],"sourcesContent":["import type { ApiRequestHeaders } from \"./abstractions.js\";\n\ntype Headers = ApiRequestHeaders.Headers;\n\n/**\n * The providers' headers merged in order: a later provider's value replaces an earlier one's, whatever\n * the case of the name (header names are case-insensitive). An undefined value means \"no header\".\n */\nexport function mergeProviderHeaders(results: Array<Headers | undefined>): Headers {\n const merged = new Map<string, [string, string | number]>();\n for (const result of results) {\n for (const [name, value] of Object.entries(result ?? {})) {\n if (value !== undefined) {\n merged.set(name.toLowerCase(), [name, value]);\n }\n }\n }\n return Object.fromEntries(merged.values());\n}\n\n/**\n * The request's own headers (and those of the decorators around this one) win over the providers', whatever\n * the case of the name.\n */\nexport function withProviderHeaders(provided: Headers, own: Headers | undefined): Headers {\n const ownNames = new Set(Object.keys(own ?? {}).map(name => name.toLowerCase()));\n const headers: Headers = {};\n for (const [name, value] of Object.entries(provided)) {\n if (!ownNames.has(name.toLowerCase())) {\n headers[name] = value;\n }\n }\n return { ...headers, ...own };\n}\n"],"names":["mergeProviderHeaders","results","merged","Map","result","name","value","Object","undefined","withProviderHeaders","provided","own","ownNames","Set","headers"],"mappings":"AAQO,SAASA,qBAAqBC,OAAmC;IACpE,MAAMC,SAAS,IAAIC;IACnB,KAAK,MAAMC,UAAUH,QACjB,KAAK,MAAM,CAACI,MAAMC,MAAM,IAAIC,OAAO,OAAO,CAACH,UAAU,CAAC,GAClD,IAAIE,AAAUE,WAAVF,OACAJ,OAAO,GAAG,CAACG,KAAK,WAAW,IAAI;QAACA;QAAMC;KAAM;IAIxD,OAAOC,OAAO,WAAW,CAACL,OAAO,MAAM;AAC3C;AAMO,SAASO,oBAAoBC,QAAiB,EAAEC,GAAwB;IAC3E,MAAMC,WAAW,IAAIC,IAAIN,OAAO,IAAI,CAACI,OAAO,CAAC,GAAG,GAAG,CAACN,CAAAA,OAAQA,KAAK,WAAW;IAC5E,MAAMS,UAAmB,CAAC;IAC1B,KAAK,MAAM,CAACT,MAAMC,MAAM,IAAIC,OAAO,OAAO,CAACG,UACvC,IAAI,CAACE,SAAS,GAAG,CAACP,KAAK,WAAW,KAC9BS,OAAO,CAACT,KAAK,GAAGC;IAGxB,OAAO;QAAE,GAAGQ,OAAO;QAAE,GAAGH,GAAG;IAAC;AAChC"}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { ApiStreamClient } from "./abstractions.js";
|
|
2
|
+
import { EnvConfig } from "../../features/envConfig/index.js";
|
|
3
|
+
declare class ApiStreamClientImpl implements ApiStreamClient.Interface {
|
|
4
|
+
private readonly apiUrl;
|
|
5
|
+
constructor(envConfig: EnvConfig.Interface);
|
|
6
|
+
execute(params: ApiStreamClient.Request): Promise<ApiStreamClient.Response>;
|
|
7
|
+
}
|
|
8
|
+
export declare const FetchApiStreamClient: import("@webiny/di").Implementation<typeof ApiStreamClientImpl>;
|
|
9
|
+
export {};
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { createImplementation } from "@webiny/di";
|
|
2
|
+
import { ApiStreamClient, ApiStreamRequestError } from "./abstractions.js";
|
|
3
|
+
import { EnvConfig } from "../envConfig/index.js";
|
|
4
|
+
import { toPayloadHash } from "./toPayloadHash.js";
|
|
5
|
+
function toFetchHeaders(headers = {}) {
|
|
6
|
+
const result = {};
|
|
7
|
+
for (const [key, value] of Object.entries(headers))if (void 0 !== value) result[key] = String(value);
|
|
8
|
+
return result;
|
|
9
|
+
}
|
|
10
|
+
function joinUrl(base, path) {
|
|
11
|
+
return `${base.replace(/\/+$/, "")}/${path.replace(/^\/+/, "")}`;
|
|
12
|
+
}
|
|
13
|
+
async function toRequestError(response) {
|
|
14
|
+
let message = `Request failed with status ${response.status}.`;
|
|
15
|
+
let code;
|
|
16
|
+
try {
|
|
17
|
+
const json = await response.json();
|
|
18
|
+
if (json?.message) message = json.message;
|
|
19
|
+
if (json?.code) code = json.code;
|
|
20
|
+
} catch {}
|
|
21
|
+
return new ApiStreamRequestError(message, response.status, code);
|
|
22
|
+
}
|
|
23
|
+
class ApiStreamClientImpl {
|
|
24
|
+
constructor(envConfig){
|
|
25
|
+
this.apiUrl = envConfig.get("apiUrl");
|
|
26
|
+
}
|
|
27
|
+
async execute(params) {
|
|
28
|
+
const hasBody = void 0 !== params.body;
|
|
29
|
+
const headers = {
|
|
30
|
+
accept: "text/event-stream"
|
|
31
|
+
};
|
|
32
|
+
if (hasBody) headers["content-type"] = "application/json";
|
|
33
|
+
Object.assign(headers, toFetchHeaders(params.headers));
|
|
34
|
+
const body = hasBody ? JSON.stringify(params.body) : void 0;
|
|
35
|
+
const url = joinUrl(this.apiUrl, params.path);
|
|
36
|
+
if (void 0 !== body) headers["x-amz-content-sha256"] = await toPayloadHash(body);
|
|
37
|
+
let response;
|
|
38
|
+
try {
|
|
39
|
+
response = await fetch(url, {
|
|
40
|
+
method: "POST",
|
|
41
|
+
headers,
|
|
42
|
+
body,
|
|
43
|
+
signal: params.signal
|
|
44
|
+
});
|
|
45
|
+
} catch (err) {
|
|
46
|
+
if (err instanceof DOMException && "AbortError" === err.name) throw err;
|
|
47
|
+
throw new Error(`Network error: ${err.message}`);
|
|
48
|
+
}
|
|
49
|
+
if (!response.ok) throw await toRequestError(response);
|
|
50
|
+
if (!response.body) throw new ApiStreamRequestError("The response carried no readable body.", response.status);
|
|
51
|
+
return response;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
const FetchApiStreamClient = createImplementation({
|
|
55
|
+
abstraction: ApiStreamClient,
|
|
56
|
+
implementation: ApiStreamClientImpl,
|
|
57
|
+
dependencies: [
|
|
58
|
+
EnvConfig
|
|
59
|
+
]
|
|
60
|
+
});
|
|
61
|
+
export { FetchApiStreamClient };
|
|
62
|
+
|
|
63
|
+
//# sourceMappingURL=FetchApiStreamClient.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"features/apiStreamClient/FetchApiStreamClient.js","sources":["../../../src/features/apiStreamClient/FetchApiStreamClient.ts"],"sourcesContent":["import { createImplementation } from \"@webiny/di\";\nimport { ApiStreamClient, ApiStreamRequestError } from \"./abstractions.js\";\nimport { EnvConfig } from \"~/features/envConfig/index.js\";\nimport { toPayloadHash } from \"./toPayloadHash.js\";\n\nfunction toFetchHeaders(headers: ApiStreamClient.Headers = {}): Record<string, string> {\n const result: Record<string, string> = {};\n for (const [key, value] of Object.entries(headers)) {\n if (value !== undefined) {\n result[key] = String(value);\n }\n }\n return result;\n}\n\nfunction joinUrl(base: string, path: string): string {\n return `${base.replace(/\\/+$/, \"\")}/${path.replace(/^\\/+/, \"\")}`;\n}\n\n/**\n * Streaming routes answer with a normal JSON error for anything they detect BEFORE opening the\n * stream (unknown file, no permission, bad input), which is why those arrive here as a non-2xx\n * rather than as an in-stream event.\n */\nasync function toRequestError(response: Response): Promise<ApiStreamRequestError> {\n let message = `Request failed with status ${response.status}.`;\n let code: string | undefined;\n\n try {\n const json = await response.json();\n if (json?.message) {\n message = json.message;\n }\n if (json?.code) {\n code = json.code;\n }\n } catch {\n // Non-JSON error body — keep the status-based message.\n }\n\n return new ApiStreamRequestError(message, response.status, code);\n}\n\nclass ApiStreamClientImpl implements ApiStreamClient.Interface {\n private readonly apiUrl: string;\n\n constructor(envConfig: EnvConfig.Interface) {\n // The API root, not `graphqlApiUrl` — streaming routes live beside /graphql, not under it.\n this.apiUrl = envConfig.get(\"apiUrl\");\n }\n\n async execute(params: ApiStreamClient.Request): Promise<ApiStreamClient.Response> {\n const hasBody = params.body !== undefined;\n\n const headers: Record<string, string> = { accept: \"text/event-stream\" };\n if (hasBody) {\n headers[\"content-type\"] = \"application/json\";\n }\n Object.assign(headers, toFetchHeaders(params.headers));\n\n const body = hasBody ? JSON.stringify(params.body) : undefined;\n const url = joinUrl(this.apiUrl, params.path);\n\n /*\n * CloudFront's Origin Access Control signs this request but does not hash the body — it trusts\n * this header for the payload hash, and the Function URL's authorizer checks it against the\n * body it received. Without it a POST carrying a body is rejected with\n * `InvalidSignatureException`, while a bodyless one succeeds. Harmless on transports that do\n * not sign.\n */\n if (body !== undefined) {\n headers[\"x-amz-content-sha256\"] = await toPayloadHash(body);\n }\n\n let response: Response;\n try {\n // Always POST. A streaming route is an action, and POST keeps the parameters in a body\n // rather than a cacheable URL — CloudFront caches GET/HEAD.\n response = await fetch(url, {\n method: \"POST\",\n headers,\n body,\n signal: params.signal\n });\n } catch (err) {\n // Preserve an abort: it isn't a network failure and callers need to tell them apart.\n if (err instanceof DOMException && err.name === \"AbortError\") {\n throw err;\n }\n throw new Error(`Network error: ${(err as Error).message}`);\n }\n\n if (!response.ok) {\n throw await toRequestError(response);\n }\n\n if (!response.body) {\n throw new ApiStreamRequestError(\n \"The response carried no readable body.\",\n response.status\n );\n }\n\n return response;\n }\n}\n\nexport const FetchApiStreamClient = createImplementation({\n abstraction: ApiStreamClient,\n implementation: ApiStreamClientImpl,\n dependencies: [EnvConfig]\n});\n"],"names":["toFetchHeaders","headers","result","key","value","Object","undefined","String","joinUrl","base","path","toRequestError","response","message","code","json","ApiStreamRequestError","ApiStreamClientImpl","envConfig","params","hasBody","body","JSON","url","toPayloadHash","fetch","err","DOMException","Error","FetchApiStreamClient","createImplementation","ApiStreamClient","EnvConfig"],"mappings":";;;;AAKA,SAASA,eAAeC,UAAmC,CAAC,CAAC;IACzD,MAAMC,SAAiC,CAAC;IACxC,KAAK,MAAM,CAACC,KAAKC,MAAM,IAAIC,OAAO,OAAO,CAACJ,SACtC,IAAIG,AAAUE,WAAVF,OACAF,MAAM,CAACC,IAAI,GAAGI,OAAOH;IAG7B,OAAOF;AACX;AAEA,SAASM,QAAQC,IAAY,EAAEC,IAAY;IACvC,OAAO,GAAGD,KAAK,OAAO,CAAC,QAAQ,IAAI,CAAC,EAAEC,KAAK,OAAO,CAAC,QAAQ,KAAK;AACpE;AAOA,eAAeC,eAAeC,QAAkB;IAC5C,IAAIC,UAAU,CAAC,2BAA2B,EAAED,SAAS,MAAM,CAAC,CAAC,CAAC;IAC9D,IAAIE;IAEJ,IAAI;QACA,MAAMC,OAAO,MAAMH,SAAS,IAAI;QAChC,IAAIG,MAAM,SACNF,UAAUE,KAAK,OAAO;QAE1B,IAAIA,MAAM,MACND,OAAOC,KAAK,IAAI;IAExB,EAAE,OAAM,CA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vitest";
|
|
2
|
+
import { Container } from "@webiny/di";
|
|
3
|
+
import { ApiStreamClient, ApiStreamRequestError } from "../abstractions.js";
|
|
4
|
+
import { FetchApiStreamClient } from "../FetchApiStreamClient.js";
|
|
5
|
+
import { EnvConfig } from "../../envConfig/index.js";
|
|
6
|
+
import { __webpack_require__ } from "../../../rslib-runtime.js";
|
|
7
|
+
function okResponse() {
|
|
8
|
+
return {
|
|
9
|
+
ok: true,
|
|
10
|
+
status: 200,
|
|
11
|
+
body: new ReadableStream({
|
|
12
|
+
start (controller) {
|
|
13
|
+
controller.close();
|
|
14
|
+
}
|
|
15
|
+
})
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
describe("FetchApiStreamClient", ()=>{
|
|
19
|
+
let container;
|
|
20
|
+
let client;
|
|
21
|
+
beforeEach(()=>{
|
|
22
|
+
container = new Container();
|
|
23
|
+
container.registerInstance(EnvConfig, {
|
|
24
|
+
get: vi.fn((key)=>"apiUrl" === key ? "https://api.example.com/" : void 0)
|
|
25
|
+
});
|
|
26
|
+
container.register(FetchApiStreamClient).inSingletonScope();
|
|
27
|
+
client = container.resolve(ApiStreamClient);
|
|
28
|
+
});
|
|
29
|
+
it("should POST to the API root joined with the path", async ()=>{
|
|
30
|
+
__webpack_require__.g.fetch = vi.fn().mockResolvedValue(okResponse());
|
|
31
|
+
await client.execute({
|
|
32
|
+
path: "/stream/fm/files/abc/enrich"
|
|
33
|
+
});
|
|
34
|
+
expect(__webpack_require__.g.fetch).toHaveBeenCalledWith("https://api.example.com/stream/fm/files/abc/enrich", expect.objectContaining({
|
|
35
|
+
method: "POST"
|
|
36
|
+
}));
|
|
37
|
+
});
|
|
38
|
+
it("should send the body's payload hash so OAC signing matches", async ()=>{
|
|
39
|
+
__webpack_require__.g.fetch = vi.fn().mockResolvedValue(okResponse());
|
|
40
|
+
await client.execute({
|
|
41
|
+
path: "/stream/ai/chat",
|
|
42
|
+
body: {
|
|
43
|
+
prompt: "hi"
|
|
44
|
+
}
|
|
45
|
+
});
|
|
46
|
+
const init = __webpack_require__.g.fetch.mock.calls[0][1];
|
|
47
|
+
expect(init.headers["x-amz-content-sha256"]).toBe("14479f4e87d340fe0ca0d522d87a5b3a028ebb1af24fbb8d3ef4553044fc6db6");
|
|
48
|
+
});
|
|
49
|
+
it("should omit the payload hash when there is no body", async ()=>{
|
|
50
|
+
__webpack_require__.g.fetch = vi.fn().mockResolvedValue(okResponse());
|
|
51
|
+
await client.execute({
|
|
52
|
+
path: "/stream/fm/files/abc/enrich"
|
|
53
|
+
});
|
|
54
|
+
const init = __webpack_require__.g.fetch.mock.calls[0][1];
|
|
55
|
+
expect(init.headers).not.toHaveProperty("x-amz-content-sha256");
|
|
56
|
+
});
|
|
57
|
+
it("should not produce a double slash when joining", async ()=>{
|
|
58
|
+
__webpack_require__.g.fetch = vi.fn().mockResolvedValue(okResponse());
|
|
59
|
+
await client.execute({
|
|
60
|
+
path: "stream/thing"
|
|
61
|
+
});
|
|
62
|
+
expect(__webpack_require__.g.fetch).toHaveBeenCalledWith("https://api.example.com/stream/thing", expect.anything());
|
|
63
|
+
});
|
|
64
|
+
it("should request an event stream and stringify the body", async ()=>{
|
|
65
|
+
__webpack_require__.g.fetch = vi.fn().mockResolvedValue(okResponse());
|
|
66
|
+
await client.execute({
|
|
67
|
+
path: "/stream/x",
|
|
68
|
+
body: {
|
|
69
|
+
hello: "world"
|
|
70
|
+
}
|
|
71
|
+
});
|
|
72
|
+
const init = __webpack_require__.g.fetch.mock.calls[0][1];
|
|
73
|
+
expect(init.headers.accept).toBe("text/event-stream");
|
|
74
|
+
expect(init.headers["content-type"]).toBe("application/json");
|
|
75
|
+
expect(init.body).toBe(JSON.stringify({
|
|
76
|
+
hello: "world"
|
|
77
|
+
}));
|
|
78
|
+
});
|
|
79
|
+
it("should pass through caller headers and drop undefined ones", async ()=>{
|
|
80
|
+
__webpack_require__.g.fetch = vi.fn().mockResolvedValue(okResponse());
|
|
81
|
+
await client.execute({
|
|
82
|
+
path: "/stream/x",
|
|
83
|
+
headers: {
|
|
84
|
+
Authorization: "Bearer t",
|
|
85
|
+
"x-tenant": "root",
|
|
86
|
+
"x-skip": void 0
|
|
87
|
+
}
|
|
88
|
+
});
|
|
89
|
+
const { headers } = __webpack_require__.g.fetch.mock.calls[0][1];
|
|
90
|
+
expect(headers.Authorization).toBe("Bearer t");
|
|
91
|
+
expect(headers["x-tenant"]).toBe("root");
|
|
92
|
+
expect("x-skip" in headers).toBe(false);
|
|
93
|
+
});
|
|
94
|
+
it("should omit the body and its content-type when there is no body", async ()=>{
|
|
95
|
+
__webpack_require__.g.fetch = vi.fn().mockResolvedValue(okResponse());
|
|
96
|
+
await client.execute({
|
|
97
|
+
path: "/stream/x"
|
|
98
|
+
});
|
|
99
|
+
const init = __webpack_require__.g.fetch.mock.calls[0][1];
|
|
100
|
+
expect(init.body).toBeUndefined();
|
|
101
|
+
expect(init.headers["content-type"]).toBeUndefined();
|
|
102
|
+
});
|
|
103
|
+
it("should surface a JSON error body as ApiStreamRequestError", async ()=>{
|
|
104
|
+
__webpack_require__.g.fetch = vi.fn().mockResolvedValue({
|
|
105
|
+
ok: false,
|
|
106
|
+
status: 404,
|
|
107
|
+
json: async ()=>({
|
|
108
|
+
message: "File not found: abc",
|
|
109
|
+
code: "ENRICHMENT_FILE_NOT_FOUND"
|
|
110
|
+
})
|
|
111
|
+
});
|
|
112
|
+
const error = await client.execute({
|
|
113
|
+
path: "/stream/x"
|
|
114
|
+
}).catch((e)=>e);
|
|
115
|
+
expect(error).toBeInstanceOf(ApiStreamRequestError);
|
|
116
|
+
expect(error.message).toBe("File not found: abc");
|
|
117
|
+
expect(error.statusCode).toBe(404);
|
|
118
|
+
expect(error.code).toBe("ENRICHMENT_FILE_NOT_FOUND");
|
|
119
|
+
});
|
|
120
|
+
it("should fall back to a status message when the error body isn't JSON", async ()=>{
|
|
121
|
+
__webpack_require__.g.fetch = vi.fn().mockResolvedValue({
|
|
122
|
+
ok: false,
|
|
123
|
+
status: 502,
|
|
124
|
+
json: async ()=>{
|
|
125
|
+
throw new Error("not json");
|
|
126
|
+
}
|
|
127
|
+
});
|
|
128
|
+
const error = await client.execute({
|
|
129
|
+
path: "/stream/x"
|
|
130
|
+
}).catch((e)=>e);
|
|
131
|
+
expect(error).toBeInstanceOf(ApiStreamRequestError);
|
|
132
|
+
expect(error.message).toBe("Request failed with status 502.");
|
|
133
|
+
expect(error.statusCode).toBe(502);
|
|
134
|
+
});
|
|
135
|
+
it("should reject a 2xx response that carries no body", async ()=>{
|
|
136
|
+
__webpack_require__.g.fetch = vi.fn().mockResolvedValue({
|
|
137
|
+
ok: true,
|
|
138
|
+
status: 200,
|
|
139
|
+
body: null
|
|
140
|
+
});
|
|
141
|
+
await expect(client.execute({
|
|
142
|
+
path: "/stream/x"
|
|
143
|
+
})).rejects.toThrow("The response carried no readable body.");
|
|
144
|
+
});
|
|
145
|
+
it("should wrap a network failure", async ()=>{
|
|
146
|
+
__webpack_require__.g.fetch = vi.fn().mockRejectedValue(new Error("connection reset"));
|
|
147
|
+
await expect(client.execute({
|
|
148
|
+
path: "/stream/x"
|
|
149
|
+
})).rejects.toThrow("Network error: connection reset");
|
|
150
|
+
});
|
|
151
|
+
it("should rethrow an abort untouched", async ()=>{
|
|
152
|
+
__webpack_require__.g.fetch = vi.fn().mockRejectedValue(new DOMException("aborted", "AbortError"));
|
|
153
|
+
const error = await client.execute({
|
|
154
|
+
path: "/stream/x"
|
|
155
|
+
}).catch((e)=>e);
|
|
156
|
+
expect(error).toBeInstanceOf(DOMException);
|
|
157
|
+
expect(error.name).toBe("AbortError");
|
|
158
|
+
});
|
|
159
|
+
it("should forward the abort signal to fetch", async ()=>{
|
|
160
|
+
__webpack_require__.g.fetch = vi.fn().mockResolvedValue(okResponse());
|
|
161
|
+
const controller = new AbortController();
|
|
162
|
+
await client.execute({
|
|
163
|
+
path: "/stream/x",
|
|
164
|
+
signal: controller.signal
|
|
165
|
+
});
|
|
166
|
+
expect(__webpack_require__.g.fetch.mock.calls[0][1].signal).toBe(controller.signal);
|
|
167
|
+
});
|
|
168
|
+
});
|
|
169
|
+
|
|
170
|
+
//# sourceMappingURL=FetchApiStreamClient.test.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"features/apiStreamClient/__tests__/FetchApiStreamClient.test.js","sources":["../../../../src/features/apiStreamClient/__tests__/FetchApiStreamClient.test.ts"],"sourcesContent":["import { describe, it, expect, vi, beforeEach } from \"vitest\";\nimport { Container } from \"@webiny/di\";\nimport { ApiStreamClient, ApiStreamRequestError } from \"../abstractions.js\";\nimport { FetchApiStreamClient } from \"../FetchApiStreamClient.js\";\nimport { EnvConfig } from \"~/features/envConfig/index.js\";\n\nfunction okResponse() {\n return {\n ok: true,\n status: 200,\n body: new ReadableStream<Uint8Array>({\n start(controller) {\n controller.close();\n }\n })\n };\n}\n\ndescribe(\"FetchApiStreamClient\", () => {\n let container: Container;\n let client: ApiStreamClient.Interface;\n\n beforeEach(() => {\n container = new Container();\n container.registerInstance(EnvConfig, {\n get: vi.fn((key: string) => (key === \"apiUrl\" ? \"https://api.example.com/\" : undefined))\n } as any);\n container.register(FetchApiStreamClient).inSingletonScope();\n client = container.resolve(ApiStreamClient);\n });\n\n it(\"should POST to the API root joined with the path\", async () => {\n global.fetch = vi.fn().mockResolvedValue(okResponse());\n\n await client.execute({ path: \"/stream/fm/files/abc/enrich\" });\n\n expect(global.fetch).toHaveBeenCalledWith(\n \"https://api.example.com/stream/fm/files/abc/enrich\",\n expect.objectContaining({ method: \"POST\" })\n );\n });\n\n /*\n * CloudFront OAC signs the request but does not hash the body, so it takes the payload hash from\n * this header. Omit it and a POST carrying a body is rejected with InvalidSignatureException while\n * a bodyless one succeeds — a failure no existing route hit, because none sent a body.\n */\n it(\"should send the body's payload hash so OAC signing matches\", async () => {\n global.fetch = vi.fn().mockResolvedValue(okResponse());\n\n await client.execute({ path: \"/stream/ai/chat\", body: { prompt: \"hi\" } });\n\n const init = (global.fetch as any).mock.calls[0][1];\n // sha256 of {\"prompt\":\"hi\"}\n expect(init.headers[\"x-amz-content-sha256\"]).toBe(\n \"14479f4e87d340fe0ca0d522d87a5b3a028ebb1af24fbb8d3ef4553044fc6db6\"\n );\n });\n\n it(\"should omit the payload hash when there is no body\", async () => {\n global.fetch = vi.fn().mockResolvedValue(okResponse());\n\n await client.execute({ path: \"/stream/fm/files/abc/enrich\" });\n\n const init = (global.fetch as any).mock.calls[0][1];\n expect(init.headers).not.toHaveProperty(\"x-amz-content-sha256\");\n });\n\n it(\"should not produce a double slash when joining\", async () => {\n global.fetch = vi.fn().mockResolvedValue(okResponse());\n\n await client.execute({ path: \"stream/thing\" });\n\n expect(global.fetch).toHaveBeenCalledWith(\n \"https://api.example.com/stream/thing\",\n expect.anything()\n );\n });\n\n it(\"should request an event stream and stringify the body\", async () => {\n global.fetch = vi.fn().mockResolvedValue(okResponse());\n\n await client.execute({ path: \"/stream/x\", body: { hello: \"world\" } });\n\n const init = (global.fetch as any).mock.calls[0][1];\n expect(init.headers.accept).toBe(\"text/event-stream\");\n expect(init.headers[\"content-type\"]).toBe(\"application/json\");\n expect(init.body).toBe(JSON.stringify({ hello: \"world\" }));\n });\n\n it(\"should pass through caller headers and drop undefined ones\", async () => {\n global.fetch = vi.fn().mockResolvedValue(okResponse());\n\n await client.execute({\n path: \"/stream/x\",\n headers: { Authorization: \"Bearer t\", \"x-tenant\": \"root\", \"x-skip\": undefined }\n });\n\n const { headers } = (global.fetch as any).mock.calls[0][1];\n expect(headers.Authorization).toBe(\"Bearer t\");\n expect(headers[\"x-tenant\"]).toBe(\"root\");\n expect(\"x-skip\" in headers).toBe(false);\n });\n\n it(\"should omit the body and its content-type when there is no body\", async () => {\n global.fetch = vi.fn().mockResolvedValue(okResponse());\n\n await client.execute({ path: \"/stream/x\" });\n\n const init = (global.fetch as any).mock.calls[0][1];\n expect(init.body).toBeUndefined();\n expect(init.headers[\"content-type\"]).toBeUndefined();\n });\n\n it(\"should surface a JSON error body as ApiStreamRequestError\", async () => {\n global.fetch = vi.fn().mockResolvedValue({\n ok: false,\n status: 404,\n json: async () => ({\n message: \"File not found: abc\",\n code: \"ENRICHMENT_FILE_NOT_FOUND\"\n })\n });\n\n const error = await client.execute({ path: \"/stream/x\" }).catch(e => e);\n\n expect(error).toBeInstanceOf(ApiStreamRequestError);\n expect(error.message).toBe(\"File not found: abc\");\n expect(error.statusCode).toBe(404);\n expect(error.code).toBe(\"ENRICHMENT_FILE_NOT_FOUND\");\n });\n\n it(\"should fall back to a status message when the error body isn't JSON\", async () => {\n global.fetch = vi.fn().mockResolvedValue({\n ok: false,\n status: 502,\n json: async () => {\n throw new Error(\"not json\");\n }\n });\n\n const error = await client.execute({ path: \"/stream/x\" }).catch(e => e);\n\n expect(error).toBeInstanceOf(ApiStreamRequestError);\n expect(error.message).toBe(\"Request failed with status 502.\");\n expect(error.statusCode).toBe(502);\n });\n\n it(\"should reject a 2xx response that carries no body\", async () => {\n global.fetch = vi.fn().mockResolvedValue({ ok: true, status: 200, body: null });\n\n await expect(client.execute({ path: \"/stream/x\" })).rejects.toThrow(\n \"The response carried no readable body.\"\n );\n });\n\n it(\"should wrap a network failure\", async () => {\n global.fetch = vi.fn().mockRejectedValue(new Error(\"connection reset\"));\n\n await expect(client.execute({ path: \"/stream/x\" })).rejects.toThrow(\n \"Network error: connection reset\"\n );\n });\n\n it(\"should rethrow an abort untouched\", async () => {\n // Callers distinguish \"user cancelled\" from \"request failed\"; wrapping an abort in a generic\n // network error would erase that.\n global.fetch = vi.fn().mockRejectedValue(new DOMException(\"aborted\", \"AbortError\"));\n\n const error = await client.execute({ path: \"/stream/x\" }).catch(e => e);\n\n expect(error).toBeInstanceOf(DOMException);\n expect(error.name).toBe(\"AbortError\");\n });\n\n it(\"should forward the abort signal to fetch\", async () => {\n global.fetch = vi.fn().mockResolvedValue(okResponse());\n const controller = new AbortController();\n\n await client.execute({ path: \"/stream/x\", signal: controller.signal });\n\n expect((global.fetch as any).mock.calls[0][1].signal).toBe(controller.signal);\n });\n});\n"],"names":["okResponse","ReadableStream","controller","describe","container","client","beforeEach","Container","EnvConfig","vi","key","undefined","FetchApiStreamClient","ApiStreamClient","it","global","expect","init","JSON","headers","error","e","ApiStreamRequestError","Error","DOMException","AbortController"],"mappings":";;;;;;AAMA,SAASA;IACL,OAAO;QACH,IAAI;QACJ,QAAQ;QACR,MAAM,IAAIC,eAA2B;YACjC,OAAMC,UAAU;gBACZA,WAAW,KAAK;YACpB;QACJ;IACJ;AACJ;AAEAC,SAAS,wBAAwB;IAC7B,IAAIC;IACJ,IAAIC;IAEJC,WAAW;QACPF,YAAY,IAAIG;QAChBH,UAAU,gBAAgB,CAACI,WAAW;YAClC,KAAKC,GAAG,EAAE,CAAC,CAACC,MAAiBA,AAAQ,aAARA,MAAmB,6BAA6BC;QACjF;QACAP,UAAU,QAAQ,CAACQ,sBAAsB,gBAAgB;QACzDP,SAASD,UAAU,OAAO,CAACS;IAC/B;IAEAC,GAAG,oDAAoD;QACnDC,oBAAAA,CAAMA,CAAC,KAAK,GAAGN,GAAG,EAAE,GAAG,iBAAiB,CAACT;QAEzC,MAAMK,OAAO,OAAO,CAAC;YAAE,MAAM;QAA8B;QAE3DW,OAAOD,oBAAAA,CAAMA,CAAC,KAAK,EAAE,oBAAoB,CACrC,sDACAC,OAAO,gBAAgB,CAAC;YAAE,QAAQ;QAAO;IAEjD;IAOAF,GAAG,8DAA8D;QAC7DC,oBAAAA,CAAMA,CAAC,KAAK,GAAGN,GAAG,EAAE,GAAG,iBAAiB,CAACT;QAEzC,MAAMK,OAAO,OAAO,CAAC;YAAE,MAAM;YAAmB,MAAM;gBAAE,QAAQ;YAAK;QAAE;QAEvE,MAAMY,OAAQF,oBAAAA,CAAMA,CAAC,KAAK,CAAS,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,EAAE;QAEnDC,OAAOC,KAAK,OAAO,CAAC,uBAAuB,EAAE,IAAI,CAC7C;IAER;IAEAH,GAAG,sDAAsD;QACr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MAAM,EAAE,IAAI,CAACb,WAAW,MAAM;IAChF;AACJ"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
import { describe, expect, it } from "vitest";
|
|
2
|
+
import { readServerSentEvents } from "../readServerSentEvents.js";
|
|
3
|
+
const encoder = new TextEncoder();
|
|
4
|
+
function responseFrom(chunks) {
|
|
5
|
+
const stream = new ReadableStream({
|
|
6
|
+
start (controller) {
|
|
7
|
+
for (const chunk of chunks)controller.enqueue("string" == typeof chunk ? encoder.encode(chunk) : chunk);
|
|
8
|
+
controller.close();
|
|
9
|
+
}
|
|
10
|
+
});
|
|
11
|
+
return {
|
|
12
|
+
body: stream
|
|
13
|
+
};
|
|
14
|
+
}
|
|
15
|
+
async function collect(response) {
|
|
16
|
+
const events = [];
|
|
17
|
+
for await (const event of readServerSentEvents(response))events.push(event);
|
|
18
|
+
return events;
|
|
19
|
+
}
|
|
20
|
+
describe("readServerSentEvents", ()=>{
|
|
21
|
+
it("should parse one event per record", async ()=>{
|
|
22
|
+
const events = await collect(responseFrom([
|
|
23
|
+
'data: {"type":"start"}\n\n',
|
|
24
|
+
'data: {"type":"done"}\n\n'
|
|
25
|
+
]));
|
|
26
|
+
expect(events).toEqual([
|
|
27
|
+
{
|
|
28
|
+
type: "start"
|
|
29
|
+
},
|
|
30
|
+
{
|
|
31
|
+
type: "done"
|
|
32
|
+
}
|
|
33
|
+
]);
|
|
34
|
+
});
|
|
35
|
+
it("should parse multiple records arriving in a single chunk", async ()=>{
|
|
36
|
+
const events = await collect(responseFrom([
|
|
37
|
+
'data: {"n":1}\n\ndata: {"n":2}\n\ndata: {"n":3}\n\n'
|
|
38
|
+
]));
|
|
39
|
+
expect(events).toEqual([
|
|
40
|
+
{
|
|
41
|
+
n: 1
|
|
42
|
+
},
|
|
43
|
+
{
|
|
44
|
+
n: 2
|
|
45
|
+
},
|
|
46
|
+
{
|
|
47
|
+
n: 3
|
|
48
|
+
}
|
|
49
|
+
]);
|
|
50
|
+
});
|
|
51
|
+
it("should parse a record split across chunks", async ()=>{
|
|
52
|
+
const events = await collect(responseFrom([
|
|
53
|
+
'data: {"ty',
|
|
54
|
+
'pe":"partial"}',
|
|
55
|
+
"\n\n"
|
|
56
|
+
]));
|
|
57
|
+
expect(events).toEqual([
|
|
58
|
+
{
|
|
59
|
+
type: "partial"
|
|
60
|
+
}
|
|
61
|
+
]);
|
|
62
|
+
});
|
|
63
|
+
it("should handle CRLF line endings", async ()=>{
|
|
64
|
+
const events = await collect(responseFrom([
|
|
65
|
+
'data: {"ok":true}\r\n\r\n'
|
|
66
|
+
]));
|
|
67
|
+
expect(events).toEqual([
|
|
68
|
+
{
|
|
69
|
+
ok: true
|
|
70
|
+
}
|
|
71
|
+
]);
|
|
72
|
+
});
|
|
73
|
+
it("should ignore comments and non-data fields", async ()=>{
|
|
74
|
+
const events = await collect(responseFrom([
|
|
75
|
+
": heartbeat\n\n",
|
|
76
|
+
'event: message\nid: 7\nretry: 500\ndata: {"kept":true}\n\n'
|
|
77
|
+
]));
|
|
78
|
+
expect(events).toEqual([
|
|
79
|
+
{
|
|
80
|
+
kept: true
|
|
81
|
+
}
|
|
82
|
+
]);
|
|
83
|
+
});
|
|
84
|
+
it("should join multi-line data fields", async ()=>{
|
|
85
|
+
const events = await collect(responseFrom([
|
|
86
|
+
'data: {"a":1,\ndata: "b":2}\n\n'
|
|
87
|
+
]));
|
|
88
|
+
expect(events).toEqual([
|
|
89
|
+
{
|
|
90
|
+
a: 1,
|
|
91
|
+
b: 2
|
|
92
|
+
}
|
|
93
|
+
]);
|
|
94
|
+
});
|
|
95
|
+
it("should preserve multi-byte characters split across chunks", async ()=>{
|
|
96
|
+
const payload = encoder.encode('data: {"text":"café"}\n\n');
|
|
97
|
+
const split = 18;
|
|
98
|
+
const events = await collect(responseFrom([
|
|
99
|
+
payload.slice(0, split),
|
|
100
|
+
payload.slice(split)
|
|
101
|
+
]));
|
|
102
|
+
expect(events).toEqual([
|
|
103
|
+
{
|
|
104
|
+
text: "café"
|
|
105
|
+
}
|
|
106
|
+
]);
|
|
107
|
+
});
|
|
108
|
+
it("should drop a trailing record that never terminated", async ()=>{
|
|
109
|
+
const events = await collect(responseFrom([
|
|
110
|
+
'data: {"complete":true}\n\ndata: {"trunc'
|
|
111
|
+
]));
|
|
112
|
+
expect(events).toEqual([
|
|
113
|
+
{
|
|
114
|
+
complete: true
|
|
115
|
+
}
|
|
116
|
+
]);
|
|
117
|
+
});
|
|
118
|
+
it("should yield events as they arrive rather than after the stream closes", async ()=>{
|
|
119
|
+
let released;
|
|
120
|
+
const gate = new Promise((resolve)=>{
|
|
121
|
+
released = resolve;
|
|
122
|
+
});
|
|
123
|
+
const stream = new ReadableStream({
|
|
124
|
+
async start (controller) {
|
|
125
|
+
controller.enqueue(encoder.encode('data: {"n":1}\n\n'));
|
|
126
|
+
await gate;
|
|
127
|
+
controller.enqueue(encoder.encode('data: {"n":2}\n\n'));
|
|
128
|
+
controller.close();
|
|
129
|
+
}
|
|
130
|
+
});
|
|
131
|
+
const iterator = readServerSentEvents({
|
|
132
|
+
body: stream
|
|
133
|
+
});
|
|
134
|
+
expect((await iterator.next()).value).toEqual({
|
|
135
|
+
n: 1
|
|
136
|
+
});
|
|
137
|
+
released();
|
|
138
|
+
expect((await iterator.next()).value).toEqual({
|
|
139
|
+
n: 2
|
|
140
|
+
});
|
|
141
|
+
expect((await iterator.next()).done).toBe(true);
|
|
142
|
+
});
|
|
143
|
+
it("should throw when the response has no body", async ()=>{
|
|
144
|
+
await expect(collect({
|
|
145
|
+
body: null
|
|
146
|
+
})).rejects.toThrow("The response carried no readable body.");
|
|
147
|
+
});
|
|
148
|
+
it("should propagate a stream error", async ()=>{
|
|
149
|
+
const stream = new ReadableStream({
|
|
150
|
+
start (controller) {
|
|
151
|
+
controller.error(new Error("stream broke"));
|
|
152
|
+
}
|
|
153
|
+
});
|
|
154
|
+
await expect(collect({
|
|
155
|
+
body: stream
|
|
156
|
+
})).rejects.toThrow("stream broke");
|
|
157
|
+
});
|
|
158
|
+
});
|
|
159
|
+
|
|
160
|
+
//# sourceMappingURL=readServerSentEvents.test.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"features/apiStreamClient/__tests__/readServerSentEvents.test.js","sources":["../../../../src/features/apiStreamClient/__tests__/readServerSentEvents.test.ts"],"sourcesContent":["import { describe, it, expect } from \"vitest\";\nimport { readServerSentEvents } from \"../readServerSentEvents.js\";\n\nconst encoder = new TextEncoder();\n\nfunction responseFrom(chunks: (string | Uint8Array)[]): Response {\n const stream = new ReadableStream<Uint8Array>({\n start(controller) {\n for (const chunk of chunks) {\n controller.enqueue(typeof chunk === \"string\" ? encoder.encode(chunk) : chunk);\n }\n controller.close();\n }\n });\n\n return { body: stream } as Response;\n}\n\nasync function collect<T>(response: Response): Promise<T[]> {\n const events: T[] = [];\n for await (const event of readServerSentEvents<T>(response)) {\n events.push(event);\n }\n return events;\n}\n\ndescribe(\"readServerSentEvents\", () => {\n it(\"should parse one event per record\", async () => {\n const events = await collect(\n responseFrom(['data: {\"type\":\"start\"}\\n\\n', 'data: {\"type\":\"done\"}\\n\\n'])\n );\n\n expect(events).toEqual([{ type: \"start\" }, { type: \"done\" }]);\n });\n\n it(\"should parse multiple records arriving in a single chunk\", async () => {\n const events = await collect(\n responseFrom(['data: {\"n\":1}\\n\\ndata: {\"n\":2}\\n\\ndata: {\"n\":3}\\n\\n'])\n );\n\n expect(events).toEqual([{ n: 1 }, { n: 2 }, { n: 3 }]);\n });\n\n it(\"should parse a record split across chunks\", async () => {\n const events = await collect(responseFrom(['data: {\"ty', 'pe\":\"partial\"}', \"\\n\\n\"]));\n\n expect(events).toEqual([{ type: \"partial\" }]);\n });\n\n it(\"should handle CRLF line endings\", async () => {\n const events = await collect(responseFrom(['data: {\"ok\":true}\\r\\n\\r\\n']));\n\n expect(events).toEqual([{ ok: true }]);\n });\n\n it(\"should ignore comments and non-data fields\", async () => {\n const events = await collect(\n responseFrom([\n \": heartbeat\\n\\n\",\n 'event: message\\nid: 7\\nretry: 500\\ndata: {\"kept\":true}\\n\\n'\n ])\n );\n\n expect(events).toEqual([{ kept: true }]);\n });\n\n it(\"should join multi-line data fields\", async () => {\n const events = await collect(responseFrom(['data: {\"a\":1,\\ndata: \"b\":2}\\n\\n']));\n\n expect(events).toEqual([{ a: 1, b: 2 }]);\n });\n\n it(\"should preserve multi-byte characters split across chunks\", async () => {\n const payload = encoder.encode('data: {\"text\":\"café\"}\\n\\n');\n const split = 18;\n\n const events = await collect(responseFrom([payload.slice(0, split), payload.slice(split)]));\n\n expect(events).toEqual([{ text: \"café\" }]);\n });\n\n it(\"should drop a trailing record that never terminated\", async () => {\n // A truncated stream (server died mid-record) must not yield a half-parsed event.\n const events = await collect(responseFrom(['data: {\"complete\":true}\\n\\ndata: {\"trunc']));\n\n expect(events).toEqual([{ complete: true }]);\n });\n\n it(\"should yield events as they arrive rather than after the stream closes\", async () => {\n let released!: () => void;\n const gate = new Promise<void>(resolve => {\n released = resolve;\n });\n\n const stream = new ReadableStream<Uint8Array>({\n async start(controller) {\n controller.enqueue(encoder.encode('data: {\"n\":1}\\n\\n'));\n await gate;\n controller.enqueue(encoder.encode('data: {\"n\":2}\\n\\n'));\n controller.close();\n }\n });\n\n const iterator = readServerSentEvents<{ n: number }>({ body: stream } as Response);\n\n // Resolving before the gate opens proves events aren't buffered until close.\n expect((await iterator.next()).value).toEqual({ n: 1 });\n released();\n expect((await iterator.next()).value).toEqual({ n: 2 });\n expect((await iterator.next()).done).toBe(true);\n });\n\n it(\"should throw when the response has no body\", async () => {\n await expect(collect({ body: null } as Response)).rejects.toThrow(\n \"The response carried no readable body.\"\n );\n });\n\n it(\"should propagate a stream error\", async () => {\n const stream = new ReadableStream<Uint8Array>({\n start(controller) {\n controller.error(new Error(\"stream broke\"));\n }\n });\n\n await expect(collect({ body: stream } as Response)).rejects.toThrow(\"stream broke\");\n });\n});\n"],"names":["encoder","TextEncoder","responseFrom","chunks","stream","ReadableStream","controller","chunk","collect","response","events","event","readServerSentEvents","describe","it","expect","payload","split","released","gate","Promise","resolve","iterator","Error"],"mappings":";;AAGA,MAAMA,UAAU,IAAIC;AAEpB,SAASC,aAAaC,MAA+B;IACjD,MAAMC,SAAS,IAAIC,eAA2B;QAC1C,OAAMC,UAAU;YACZ,KAAK,MAAMC,SAASJ,OAChBG,WAAW,OAAO,CAAC,AAAiB,YAAjB,OAAOC,QAAqBP,QAAQ,MAAM,CAACO,SAASA;YAE3ED,WAAW,KAAK;QACpB;IACJ;IAEA,OAAO;QAAE,MAAMF;IAAO;AAC1B;AAEA,eAAeI,QAAWC,QAAkB;IACxC,MAAMC,SAAc,EAAE;IACtB,WAAW,MAAMC,SAASC,qBAAwBH,UAC9CC,OAAO,IAAI,CAACC;IAEhB,OAAOD;AACX;AAEAG,SAAS,wBAAwB;IAC7BC,GAAG,qCAAqC;QACpC,MAAMJ,SAAS,MAAMF,QACjBN,aAAa;YAAC;YAA8B;SAA4B;QAG5Ea,OAAOL,QAAQ,OAAO,CAAC;YAAC;gBAAE,MAAM;YAAQ;YAAG;gBAAE,MAAM;YAAO;SAAE;IAChE;IAEAI,GAAG,4DAA4D;QAC3D,MAAMJ,SAAS,MAAMF,QACjBN,aAAa;YAAC;SAAsD;QAGxEa,OAAOL,QAAQ,OAAO,CAAC;YAAC;gBAAE,GAAG;YAAE;YAAG;gBAAE,GAAG;YAAE;YAAG;gBAAE,GAAG;YAAE;SAAE;IACzD;IAEAI,GAAG,6CAA6C;QAC5C,MAAMJ,SAAS,MAAMF,QAAQN,aAAa;YAAC;YAAc;YAAkB;SAAO;QAElFa,OAAOL,QAAQ,OAAO,CAAC;YAAC;gBAAE,MAAM;YAAU;SAAE;IAChD;IAEAI,GAAG,mCAAmC;QAClC,MAAMJ,SAAS,MAAMF,QAAQN,aAAa;YAAC;SAA4B;QAEvEa,OAAOL,QAAQ,OAAO,CAAC;YAAC;gBAAE,IAAI;YAAK;S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AAE,OAAO,CAAC;YAAE,GAAG;QAAE;QACrDP,OAAQ,OAAMO,SAAS,IAAI,EAAC,EAAG,IAAI,EAAE,IAAI,CAAC;IAC9C;IAEAR,GAAG,8CAA8C;QAC7C,MAAMC,OAAOP,QAAQ;YAAE,MAAM;QAAK,IAAgB,OAAO,CAAC,OAAO,CAC7D;IAER;IAEAM,GAAG,mCAAmC;QAClC,MAAMV,SAAS,IAAIC,eAA2B;YAC1C,OAAMC,UAAU;gBACZA,WAAW,KAAK,CAAC,IAAIiB,MAAM;YAC/B;QACJ;QAEA,MAAMR,OAAOP,QAAQ;YAAE,MAAMJ;QAAO,IAAgB,OAAO,CAAC,OAAO,CAAC;IACxE;AACJ"}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
type IHeaders = Record<string, string | number | undefined>;
|
|
2
|
+
/**
|
|
3
|
+
* The raw `fetch` response, handed to the caller unread so it owns the read loop. Aliased through
|
|
4
|
+
* the abstraction so consumers name the contract rather than the DOM type it currently happens to
|
|
5
|
+
* be — and so `ApiStreamClient.Response` reads as the counterpart to `ApiStreamClient.Request`.
|
|
6
|
+
*/
|
|
7
|
+
type IApiStreamResponse = globalThis.Response;
|
|
8
|
+
export interface IApiStreamRequest {
|
|
9
|
+
/** Path relative to the API root, e.g. `/stream/fm/files/abc/enrich`. */
|
|
10
|
+
path: string;
|
|
11
|
+
/** Serialized as JSON when present. */
|
|
12
|
+
body?: unknown;
|
|
13
|
+
headers?: IHeaders;
|
|
14
|
+
/**
|
|
15
|
+
* Aborts the request AND the caller's read loop. Streaming responses stay open for as long as the
|
|
16
|
+
* producer runs, so without this a caller that navigates away or closes its UI would leave the
|
|
17
|
+
* connection open and keep consuming events into a component that no longer exists.
|
|
18
|
+
*/
|
|
19
|
+
signal?: AbortSignal;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Client for API endpoints that stream their response.
|
|
23
|
+
*
|
|
24
|
+
* Deliberately separate from `GraphQLClient`: that abstraction returns `Promise<TResult>` — a
|
|
25
|
+
* buffered contract by type — and Webiny's GraphQL layer (graphql-js 16) has no incremental
|
|
26
|
+
* delivery, so a streaming response can't travel through it. This returns the raw `Response` so the
|
|
27
|
+
* caller owns the read loop and can hand `response.body` to any stream consumer.
|
|
28
|
+
*/
|
|
29
|
+
export interface IApiStreamClient {
|
|
30
|
+
execute(params: IApiStreamRequest): Promise<IApiStreamResponse>;
|
|
31
|
+
}
|
|
32
|
+
export declare const ApiStreamClient: import("@webiny/di").Abstraction<IApiStreamClient>;
|
|
33
|
+
export declare namespace ApiStreamClient {
|
|
34
|
+
type Headers = IHeaders;
|
|
35
|
+
type Interface = IApiStreamClient;
|
|
36
|
+
type Request = IApiStreamRequest;
|
|
37
|
+
type Response = IApiStreamResponse;
|
|
38
|
+
}
|
|
39
|
+
export declare class ApiStreamRequestError extends Error {
|
|
40
|
+
readonly statusCode: number;
|
|
41
|
+
readonly code?: string | undefined;
|
|
42
|
+
constructor(message: string, statusCode: number, code?: string | undefined);
|
|
43
|
+
}
|
|
44
|
+
export {};
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { createAbstraction } from "@webiny/feature/admin";
|
|
2
|
+
const ApiStreamClient = createAbstraction("ApiStreamClient");
|
|
3
|
+
class ApiStreamRequestError extends Error {
|
|
4
|
+
constructor(message, statusCode, code){
|
|
5
|
+
super(message), this.statusCode = statusCode, this.code = code;
|
|
6
|
+
}
|
|
7
|
+
}
|
|
8
|
+
export { ApiStreamClient, ApiStreamRequestError };
|
|
9
|
+
|
|
10
|
+
//# sourceMappingURL=abstractions.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"features/apiStreamClient/abstractions.js","sources":["../../../src/features/apiStreamClient/abstractions.ts"],"sourcesContent":["import { createAbstraction } from \"@webiny/feature/admin\";\n\ntype IHeaders = Record<string, string | number | undefined>;\n\n/**\n * The raw `fetch` response, handed to the caller unread so it owns the read loop. Aliased through\n * the abstraction so consumers name the contract rather than the DOM type it currently happens to\n * be — and so `ApiStreamClient.Response` reads as the counterpart to `ApiStreamClient.Request`.\n */\ntype IApiStreamResponse = globalThis.Response;\n\nexport interface IApiStreamRequest {\n /** Path relative to the API root, e.g. `/stream/fm/files/abc/enrich`. */\n path: string;\n /** Serialized as JSON when present. */\n body?: unknown;\n headers?: IHeaders;\n /**\n * Aborts the request AND the caller's read loop. Streaming responses stay open for as long as the\n * producer runs, so without this a caller that navigates away or closes its UI would leave the\n * connection open and keep consuming events into a component that no longer exists.\n */\n signal?: AbortSignal;\n}\n\n/**\n * Client for API endpoints that stream their response.\n *\n * Deliberately separate from `GraphQLClient`: that abstraction returns `Promise<TResult>` — a\n * buffered contract by type — and Webiny's GraphQL layer (graphql-js 16) has no incremental\n * delivery, so a streaming response can't travel through it. This returns the raw `Response` so the\n * caller owns the read loop and can hand `response.body` to any stream consumer.\n */\nexport interface IApiStreamClient {\n execute(params: IApiStreamRequest): Promise<IApiStreamResponse>;\n}\n\nexport const ApiStreamClient = createAbstraction<IApiStreamClient>(\"ApiStreamClient\");\n\nexport namespace ApiStreamClient {\n export type Headers = IHeaders;\n export type Interface = IApiStreamClient;\n export type Request = IApiStreamRequest;\n export type Response = IApiStreamResponse;\n}\n\nexport class ApiStreamRequestError extends Error {\n constructor(\n message: string,\n readonly statusCode: number,\n readonly code?: string\n ) {\n super(message);\n }\n}\n"],"names":["ApiStreamClient","createAbstraction","ApiStreamRequestError","Error","message","statusCode","code"],"mappings":";AAqCO,MAAMA,kBAAkBC,kBAAoC;AAS5D,MAAMC,8BAA8BC;IACvC,YACIC,OAAe,EACNC,UAAkB,EAClBC,IAAa,CACxB;QACE,KAAK,CAACF,UAAAA,IAAAA,CAHGC,UAAU,GAAVA,YAAAA,IAAAA,CACAC,IAAI,GAAJA;IAGb;AACJ"}
|