@venizia/ignis-kernel 0.5.0-0 → 0.5.0-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.
@@ -17,7 +17,6 @@ export { AbstractDataSource } from './base/datasources/abstract.js';
17
17
  export { DataSourceRoot } from './base/datasources/root.js';
18
18
  export type { ICreatableRepository, ICrudRepository, IDeletableRepository, IPersistableRepository, IReadableRepository, IRepository, IUpdatableRepository, } from './base/repositories/common/types/contracts.js';
19
19
  export { DataRangeUtility } from './base/repositories/common/types/results.js';
20
- export { HttpResponseReader } from './base/repositories/common/response-reader.js';
21
20
  export { HttpExtraRequest } from './base/repositories/common/extra-request.js';
22
21
  export type { TExtraRequest, TExtraResult } from './base/repositories/common/extra-request.js';
23
22
  export { DEFAULT_LIMIT, DEFAULT_MAX_LIMIT, RepositoryOperationScopes, RepositoryTypes, } from './base/repositories/common/constants.js';
@@ -18,7 +18,6 @@ export { DataSourceRoot } from './base/datasources/root.js';
18
18
  export { DataRangeUtility } from './base/repositories/common/types/results.js';
19
19
  // How a client reads what an IGNIS server answers - shared by the http connector and any client
20
20
  // that reads the same server without it.
21
- export { HttpResponseReader } from './base/repositories/common/response-reader.js';
22
21
  export { HttpExtraRequest } from './base/repositories/common/extra-request.js';
23
22
  // What a repository on any transport raises and bounds itself by - the constants, the error codes,
24
23
  // and the helper an engine that lacks an operation throws through.
@@ -1 +1 @@
1
- {"version":3,"file":"repository.js","sourceRoot":"","sources":["../../src/repository.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,OAAO,EAAE,kBAAkB,EAAE,MAAM,mCAAmC,CAAC;AACvE,OAAO,EAAE,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;AACjE,OAAO,EAAE,cAAc,EAAE,MAAM,yBAAyB,CAAC;AAYzD,OAAO,EAAE,gBAAgB,EAAE,MAAM,0CAA0C,CAAC;AAE5E,gGAAgG;AAChG,yCAAyC;AACzC,OAAO,EAAE,kBAAkB,EAAE,MAAM,4CAA4C,CAAC;AAChF,OAAO,EAAE,gBAAgB,EAAE,MAAM,0CAA0C,CAAC;AAG5E,mGAAmG;AACnG,mEAAmE;AACnE,OAAO,EACL,aAAa,EACb,iBAAiB,EACjB,yBAAyB,EACzB,eAAe,GAChB,MAAM,sCAAsC,CAAC;AAE9C,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AACxE,OAAO,EAAE,mBAAmB,EAAE,MAAM,mCAAmC,CAAC;AAKxE,mGAAmG;AACnG,qFAAqF;AACrF,OAAO,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AACpD,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,gCAAgC,CAAC;AAc1E,oGAAoG;AACpG,OAAO,EAAE,kBAAkB,EAAE,MAAM,iDAAiD,CAAC","sourcesContent":["/**\n * The persistence contract, and nothing about how a row is served or validated.\n *\n * A repository talks to a datasource. `AbstractDataSource` is engine-neutral - its only required\n * member is `configure()` - so \"an HTTP request to another server\" is a datasource in the same sense\n * Drizzle-over-Postgres is one: same role, different transport. This entry exists so a consumer can\n * implement that without taking the OpenAPI layer, which `base/repositories` reaches through\n * `query-schemas` and `result-schemas`.\n *\n * Both halves already speak `@venizia/ignis-filter`, so a consumer on another transport shares the\n * query vocabulary rather than translating into one.\n *\n * Weight is a contract, checked by `src/__tests__/bundle/browser-weight.test.ts`.\n */\n\nexport { AbstractRepository } from '@/base/repositories/core/abstract';\nexport { AbstractDataSource } from '@/base/datasources/abstract';\nexport { DataSourceRoot } from '@/base/datasources/root';\n\nexport type {\n ICreatableRepository,\n ICrudRepository,\n IDeletableRepository,\n IPersistableRepository,\n IReadableRepository,\n IRepository,\n IUpdatableRepository,\n} from '@/base/repositories/common/types/contracts';\n\nexport { DataRangeUtility } from '@/base/repositories/common/types/results';\n\n// How a client reads what an IGNIS server answers - shared by the http connector and any client\n// that reads the same server without it.\nexport { HttpResponseReader } from '@/base/repositories/common/response-reader';\nexport { HttpExtraRequest } from '@/base/repositories/common/extra-request';\nexport type { TExtraRequest, TExtraResult } from '@/base/repositories/common/extra-request';\n\n// What a repository on any transport raises and bounds itself by - the constants, the error codes,\n// and the helper an engine that lacks an operation throws through.\nexport {\n DEFAULT_LIMIT,\n DEFAULT_MAX_LIMIT,\n RepositoryOperationScopes,\n RepositoryTypes,\n} from '@/base/repositories/common/constants';\nexport type { TRepositoryType } from '@/base/repositories/common/constants';\nexport { CoreErrorCodes, SearchErrorCodes } from '@/common/error-codes';\nexport { NotSupportedUtility } from '@/utilities/not-supported.utility';\nexport type { TCount, TDataRange, TDataWithRange } from '@/base/repositories/common/types/results';\n\nexport type { IDataSource } from '@/base/datasources/common/types';\n\n// `IRepository` names an entity, so a consumer implementing the contract needs the base to extend.\n// Engine-neutral like the datasource: a name, `getSchema({ type })`, and an id type.\nexport { AbstractEntity } from '@/base/models/base';\nexport { AuditFields, SchemaTypes } from '@/base/models/common/constants';\nexport type { TIdSchemaType, TSchemaType } from '@/base/models/common';\n\n// The query vocabulary both transports share.\nexport type {\n TByIdFilter,\n TFields,\n TFilter,\n TInclusion,\n TRow,\n TSelectedRow,\n TWhere,\n} from '@venizia/ignis-filter';\n\n// What a repository on any transport needs to refuse a request filter that names a hidden property.\nexport { RequestFilterParts } from '@/base/repositories/common/request-filter-guard';\nexport type {\n IRequestFilterJudge,\n IRequestFilterShape,\n TRequestFilterPart,\n TRequestFilterPiece,\n} from '@/base/repositories/common/request-filter-guard';\n"]}
1
+ {"version":3,"file":"repository.js","sourceRoot":"","sources":["../../src/repository.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,OAAO,EAAE,kBAAkB,EAAE,MAAM,mCAAmC,CAAC;AACvE,OAAO,EAAE,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;AACjE,OAAO,EAAE,cAAc,EAAE,MAAM,yBAAyB,CAAC;AAYzD,OAAO,EAAE,gBAAgB,EAAE,MAAM,0CAA0C,CAAC;AAE5E,gGAAgG;AAChG,yCAAyC;AACzC,OAAO,EAAE,gBAAgB,EAAE,MAAM,0CAA0C,CAAC;AAG5E,mGAAmG;AACnG,mEAAmE;AACnE,OAAO,EACL,aAAa,EACb,iBAAiB,EACjB,yBAAyB,EACzB,eAAe,GAChB,MAAM,sCAAsC,CAAC;AAE9C,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AACxE,OAAO,EAAE,mBAAmB,EAAE,MAAM,mCAAmC,CAAC;AAKxE,mGAAmG;AACnG,qFAAqF;AACrF,OAAO,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AACpD,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,gCAAgC,CAAC;AAc1E,oGAAoG;AACpG,OAAO,EAAE,kBAAkB,EAAE,MAAM,iDAAiD,CAAC","sourcesContent":["/**\n * The persistence contract, and nothing about how a row is served or validated.\n *\n * A repository talks to a datasource. `AbstractDataSource` is engine-neutral - its only required\n * member is `configure()` - so \"an HTTP request to another server\" is a datasource in the same sense\n * Drizzle-over-Postgres is one: same role, different transport. This entry exists so a consumer can\n * implement that without taking the OpenAPI layer, which `base/repositories` reaches through\n * `query-schemas` and `result-schemas`.\n *\n * Both halves already speak `@venizia/ignis-filter`, so a consumer on another transport shares the\n * query vocabulary rather than translating into one.\n *\n * Weight is a contract, checked by `src/__tests__/bundle/browser-weight.test.ts`.\n */\n\nexport { AbstractRepository } from '@/base/repositories/core/abstract';\nexport { AbstractDataSource } from '@/base/datasources/abstract';\nexport { DataSourceRoot } from '@/base/datasources/root';\n\nexport type {\n ICreatableRepository,\n ICrudRepository,\n IDeletableRepository,\n IPersistableRepository,\n IReadableRepository,\n IRepository,\n IUpdatableRepository,\n} from '@/base/repositories/common/types/contracts';\n\nexport { DataRangeUtility } from '@/base/repositories/common/types/results';\n\n// How a client reads what an IGNIS server answers - shared by the http connector and any client\n// that reads the same server without it.\nexport { HttpExtraRequest } from '@/base/repositories/common/extra-request';\nexport type { TExtraRequest, TExtraResult } from '@/base/repositories/common/extra-request';\n\n// What a repository on any transport raises and bounds itself by - the constants, the error codes,\n// and the helper an engine that lacks an operation throws through.\nexport {\n DEFAULT_LIMIT,\n DEFAULT_MAX_LIMIT,\n RepositoryOperationScopes,\n RepositoryTypes,\n} from '@/base/repositories/common/constants';\nexport type { TRepositoryType } from '@/base/repositories/common/constants';\nexport { CoreErrorCodes, SearchErrorCodes } from '@/common/error-codes';\nexport { NotSupportedUtility } from '@/utilities/not-supported.utility';\nexport type { TCount, TDataRange, TDataWithRange } from '@/base/repositories/common/types/results';\n\nexport type { IDataSource } from '@/base/datasources/common/types';\n\n// `IRepository` names an entity, so a consumer implementing the contract needs the base to extend.\n// Engine-neutral like the datasource: a name, `getSchema({ type })`, and an id type.\nexport { AbstractEntity } from '@/base/models/base';\nexport { AuditFields, SchemaTypes } from '@/base/models/common/constants';\nexport type { TIdSchemaType, TSchemaType } from '@/base/models/common';\n\n// The query vocabulary both transports share.\nexport type {\n TByIdFilter,\n TFields,\n TFilter,\n TInclusion,\n TRow,\n TSelectedRow,\n TWhere,\n} from '@venizia/ignis-filter';\n\n// What a repository on any transport needs to refuse a request filter that names a hidden property.\nexport { RequestFilterParts } from '@/base/repositories/common/request-filter-guard';\nexport type {\n IRequestFilterJudge,\n IRequestFilterShape,\n TRequestFilterPart,\n TRequestFilterPiece,\n} from '@/base/repositories/common/request-filter-guard';\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@venizia/ignis-kernel",
3
- "version": "0.5.0-0",
3
+ "version": "0.5.0-2",
4
4
  "description": "Browser-pure kernel of the IGNIS framework: dependency injection, lifecycle, REST controllers, repository and datasource abstractions, and the authentication and authorization seams. No node builtin and no server-only peer, so the same kernel serves a Bun server and a browser Worker.",
5
5
  "keywords": [
6
6
  "authentication",
@@ -74,13 +74,13 @@
74
74
  },
75
75
  "dependencies": {
76
76
  "@venizia/ignis-filter": "0.5.0-0",
77
- "@venizia/ignis-helpers": "0.5.0-0",
77
+ "@venizia/ignis-helpers": "0.5.0-1",
78
78
  "@venizia/ignis-inversion": "0.5.0-0",
79
79
  "reflect-metadata": "^0.2.2"
80
80
  },
81
81
  "devDependencies": {
82
- "@types/bun": "^1.4.3",
83
- "@venizia/dev-configs": "0.5.0-0",
82
+ "@types/bun": "^1.4.5",
83
+ "@venizia/dev-configs": "0.5.0-2",
84
84
  "casbin": "^5.51.1",
85
85
  "eslint": "^10.13.0",
86
86
  "oxlint": "1.89.0",
@@ -1,107 +0,0 @@
1
- import type { TJsonValue } from '@venizia/ignis-helpers/common';
2
- import type { ApplicationError, TResponsedError, UrlFetchError } from '@venizia/ignis-helpers/core';
3
- /**
4
- * What an IGNIS server answers - `Content-Range`, the error envelope - read once, here, for every
5
- * client of that server: the http connector, and a client that reads it without the connector.
6
- */
7
- export declare class HttpResponseReader {
8
- /** A content type that names JSON: `application/json`, `application/problem+json`, `application/ld+json`. */
9
- static readonly JSON_CONTENT_TYPE_PATTERN: RegExp;
10
- static isPlainObject(value: unknown): value is Record<string, unknown>;
11
- /** An empty string reads as absent, so a fallback still applies. */
12
- static toText(value: unknown): string | undefined;
13
- /**
14
- * A `Content-Range` header as the IGNIS server writes it: `records 0-24/137` -> skip 0, total 137;
15
- * an empty page, `records *\/137` -> total 137. Anything else, including an absent header or an
16
- * unknown total, is `undefined`.
17
- */
18
- static parseContentRange(opts: {
19
- header?: string | null;
20
- }): {
21
- skip?: number;
22
- total: number;
23
- } | undefined;
24
- /**
25
- * The IGNIS error envelope - `{ message, statusCode, normalized: { text, code, args }, requestId,
26
- * extra, details }` - read off a parsed response body. A server configured with `error.rootKey`
27
- * wraps it under that key; pass the same `rootKey` to unwrap it. A body without that key, or with a
28
- * non-object under it (a proxy's `{ error: 'Bad Gateway' }`), is read as it stands.
29
- *
30
- * A body that is not a plain object yields `{}`; any other body yields its known fields, each
31
- * `undefined` when absent or mistyped. An empty string reads as absent.
32
- */
33
- static readErrorEnvelope(opts: {
34
- body: unknown;
35
- rootKey?: string;
36
- }): TResponsedError;
37
- /** A failed response's envelope. A body that is not JSON yields `{}`, and the status alone still describes it. */
38
- static readError(opts: {
39
- response: Response;
40
- rootKey?: string;
41
- }): Promise<TResponsedError>;
42
- /**
43
- * A failed response as the error the server threw: its status, code, args and text, and its
44
- * `extra` with the `requestId` added. `message` is `context` plus the server's text, for logs;
45
- * `normalized.text` stays the server's, for display - `HTTP <status>` when the server sent none.
46
- * `cause` is the server's `details.cause` - a 422's per-field issues, `{ path, message, code }`.
47
- *
48
- * `requestId` names the request this client made. A relaying server's `extra` carries the id of
49
- * the request it made upstream: it joins `upstreamRequestIds`, nearest first, at every hop.
50
- */
51
- static toApplicationError(opts: {
52
- response: Response;
53
- /** Where it failed, for logs - e.g. `[HttpDataSource][read] 404 | /tickets`. */
54
- context: string;
55
- rootKey?: string;
56
- }): Promise<ApplicationError>;
57
- /**
58
- * `toApplicationError` for a fetcher's refused answer: it reads the body the `UrlFetchError` kept (the first 64 KiB),
59
- * and an error that carries none is described by its status alone.
60
- */
61
- static fromFetchError(opts: {
62
- error: UrlFetchError<Response>;
63
- context: string;
64
- rootKey?: string;
65
- }): Promise<ApplicationError>;
66
- /**
67
- * The body as text: `''` for a 204 or an empty body. `response.json()` throws on those, and each client
68
- * that reads a response has copied the guard.
69
- */
70
- static readText(opts: {
71
- response: Response;
72
- }): Promise<string>;
73
- /**
74
- * The body of a success answer, by what it says it is: `null` for a 204 or an empty body, the parsed
75
- * value when the content type names JSON (`application/json`, `application/problem+json`), the text itself
76
- * for any other type (`text/plain`, `text/csv`). A body that claims JSON and is not is a `502` that names
77
- * `context` (where it happened, e.g. `[Client][read] 200 | /tickets`), its size and its content type; its
78
- * content stays out of the message, which a relaying server may pass to its own clients.
79
- */
80
- static readBody(opts: {
81
- response: Response;
82
- context: string;
83
- }): Promise<TJsonValue>;
84
- /**
85
- * The body as JSON whatever its content type says, `null` for a 204 or an empty body: for a route that
86
- * answers JSON under a type a proxy rewrote. Errors as `readBody` does.
87
- */
88
- static readJson(opts: {
89
- response: Response;
90
- context: string;
91
- }): Promise<TJsonValue>;
92
- private static parseJson;
93
- /**
94
- * A body the server marked with `x-response-extra` carries `extra` beside its rows. `body` is what
95
- * the route answers without extras: the `{ count, data }` envelope when the count was asked for in
96
- * the body, the rows otherwise. Any other body is returned as it stands - an unmarked object is
97
- * never unwrapped, so a row that has `data` and `extra` columns of its own is never misread.
98
- */
99
- static readExtra(opts: {
100
- body: unknown;
101
- headers: Pick<Headers, 'has'>;
102
- }): {
103
- body: unknown;
104
- extra?: Record<string, unknown>;
105
- };
106
- }
107
- //# sourceMappingURL=response-reader.d.ts.map
@@ -1,206 +0,0 @@
1
- import { HTTP } from '@venizia/ignis-helpers/common';
2
- import { getError, ResponseReader } from '@venizia/ignis-helpers/core';
3
- /**
4
- * What an IGNIS server answers - `Content-Range`, the error envelope - read once, here, for every
5
- * client of that server: the http connector, and a client that reads it without the connector.
6
- */
7
- export class HttpResponseReader {
8
- /** A content type that names JSON: `application/json`, `application/problem+json`, `application/ld+json`. */
9
- static { this.JSON_CONTENT_TYPE_PATTERN = /json/i; }
10
- static isPlainObject(value) {
11
- return (!!value && typeof value === 'object' && Object.getPrototypeOf(value) === Object.prototype);
12
- }
13
- /** An empty string reads as absent, so a fallback still applies. */
14
- static toText(value) {
15
- return typeof value === 'string' && value !== '' ? value : undefined;
16
- }
17
- /**
18
- * A `Content-Range` header as the IGNIS server writes it: `records 0-24/137` -> skip 0, total 137;
19
- * an empty page, `records *\/137` -> total 137. Anything else, including an absent header or an
20
- * unknown total, is `undefined`.
21
- */
22
- static parseContentRange(opts) {
23
- const { header } = opts;
24
- if (!header) {
25
- return undefined;
26
- }
27
- const range = header.match(/(\d+)\s*-\s*(\d+)\s*\/\s*(\d+)/);
28
- if (range) {
29
- return { skip: Number(range[1]), total: Number(range[3]) };
30
- }
31
- const unsatisfied = header.match(/\*\s*\/\s*(\d+)/);
32
- if (unsatisfied) {
33
- return { total: Number(unsatisfied[1]) };
34
- }
35
- return undefined;
36
- }
37
- /**
38
- * The IGNIS error envelope - `{ message, statusCode, normalized: { text, code, args }, requestId,
39
- * extra, details }` - read off a parsed response body. A server configured with `error.rootKey`
40
- * wraps it under that key; pass the same `rootKey` to unwrap it. A body without that key, or with a
41
- * non-object under it (a proxy's `{ error: 'Bad Gateway' }`), is read as it stands.
42
- *
43
- * A body that is not a plain object yields `{}`; any other body yields its known fields, each
44
- * `undefined` when absent or mistyped. An empty string reads as absent.
45
- */
46
- static readErrorEnvelope(opts) {
47
- const { body, rootKey } = opts;
48
- const wrapped = rootKey && HttpResponseReader.isPlainObject(body) ? body[rootKey] : undefined;
49
- const envelope = HttpResponseReader.isPlainObject(wrapped) ? wrapped : body;
50
- if (!HttpResponseReader.isPlainObject(envelope)) {
51
- return {};
52
- }
53
- const { message, statusCode, normalized, requestId, extra, details } = envelope;
54
- const normalizedRecord = HttpResponseReader.isPlainObject(normalized) ? normalized : {};
55
- const { text, code, args } = normalizedRecord;
56
- return {
57
- message: HttpResponseReader.toText(message),
58
- statusCode: typeof statusCode === 'number' ? statusCode : undefined,
59
- normalized: {
60
- text: HttpResponseReader.toText(text),
61
- code: HttpResponseReader.toText(code),
62
- args: HttpResponseReader.isPlainObject(args) ? { ...args } : undefined,
63
- },
64
- requestId: HttpResponseReader.toText(requestId),
65
- extra: HttpResponseReader.isPlainObject(extra) ? { ...extra } : undefined,
66
- details: HttpResponseReader.isPlainObject(details) ? { ...details } : undefined,
67
- };
68
- }
69
- /** A failed response's envelope. A body that is not JSON yields `{}`, and the status alone still describes it. */
70
- static async readError(opts) {
71
- let text;
72
- try {
73
- const result = await opts.response.text();
74
- text = result;
75
- // eslint-disable-next-line venizia/no-silent-catch -- an unreadable body is read as no text; the status alone still describes the failure
76
- }
77
- catch {
78
- text = '';
79
- }
80
- let body;
81
- try {
82
- body = text ? JSON.parse(text) : undefined;
83
- // eslint-disable-next-line venizia/no-silent-catch -- a body that is not JSON yields `{}`; the status alone still describes the failure
84
- }
85
- catch {
86
- return {};
87
- }
88
- return HttpResponseReader.readErrorEnvelope({ body, rootKey: opts.rootKey });
89
- }
90
- /**
91
- * A failed response as the error the server threw: its status, code, args and text, and its
92
- * `extra` with the `requestId` added. `message` is `context` plus the server's text, for logs;
93
- * `normalized.text` stays the server's, for display - `HTTP <status>` when the server sent none.
94
- * `cause` is the server's `details.cause` - a 422's per-field issues, `{ path, message, code }`.
95
- *
96
- * `requestId` names the request this client made. A relaying server's `extra` carries the id of
97
- * the request it made upstream: it joins `upstreamRequestIds`, nearest first, at every hop.
98
- */
99
- static async toApplicationError(opts) {
100
- const { response, context, rootKey } = opts;
101
- const server = await HttpResponseReader.readError({ response, rootKey });
102
- const serverText = server.normalized?.text ?? server.message;
103
- const displayText = serverText ?? `HTTP ${response.status}`;
104
- const extra = { ...server.extra };
105
- if (server.requestId) {
106
- const upstreamRequestId = extra.requestId;
107
- extra.requestId = server.requestId;
108
- if (upstreamRequestId !== undefined && upstreamRequestId !== server.requestId) {
109
- const known = Array.isArray(extra.upstreamRequestIds) ? extra.upstreamRequestIds : [];
110
- extra.upstreamRequestIds = [upstreamRequestId, ...known];
111
- }
112
- }
113
- return getError({
114
- statusCode: response.status,
115
- message: serverText ? `${context} | ${serverText}` : context,
116
- messageCode: server.normalized?.code,
117
- messageArgs: server.normalized?.args,
118
- extra: Object.keys(extra).length > 0 ? extra : undefined,
119
- cause: server.details?.cause,
120
- transform: ({ message }) => ({ ...message, text: displayText }),
121
- });
122
- }
123
- /**
124
- * `toApplicationError` for a fetcher's refused answer: it reads the body the `UrlFetchError` kept (the first 64 KiB),
125
- * and an error that carries none is described by its status alone.
126
- */
127
- static async fromFetchError(opts) {
128
- const { error, context, rootKey } = opts;
129
- // A hand-built error may carry a status a `Response` refuses (below 200 or above 599, e.g. 0): that is a bad gateway.
130
- const isResponseStatus = error.status >= 200 && error.status <= 599;
131
- const response = error.response ??
132
- new Response(null, {
133
- status: isResponseStatus ? error.status : HTTP.ResultCodes.RS_5.BadGateway,
134
- headers: error.headers,
135
- });
136
- return HttpResponseReader.toApplicationError({ response, context, rootKey });
137
- }
138
- /**
139
- * The body as text: `''` for a 204 or an empty body. `response.json()` throws on those, and each client
140
- * that reads a response has copied the guard.
141
- */
142
- static async readText(opts) {
143
- return ResponseReader.readText(opts);
144
- }
145
- /**
146
- * The body of a success answer, by what it says it is: `null` for a 204 or an empty body, the parsed
147
- * value when the content type names JSON (`application/json`, `application/problem+json`), the text itself
148
- * for any other type (`text/plain`, `text/csv`). A body that claims JSON and is not is a `502` that names
149
- * `context` (where it happened, e.g. `[Client][read] 200 | /tickets`), its size and its content type; its
150
- * content stays out of the message, which a relaying server may pass to its own clients.
151
- */
152
- static async readBody(opts) {
153
- const { response, context } = opts;
154
- const text = await HttpResponseReader.readText({ response });
155
- if (!text) {
156
- return null;
157
- }
158
- if (!HttpResponseReader.JSON_CONTENT_TYPE_PATTERN.test(response.headers.get(HTTP.Headers.CONTENT_TYPE) ?? '')) {
159
- return text;
160
- }
161
- return HttpResponseReader.parseJson({ text, response, context });
162
- }
163
- /**
164
- * The body as JSON whatever its content type says, `null` for a 204 or an empty body: for a route that
165
- * answers JSON under a type a proxy rewrote. Errors as `readBody` does.
166
- */
167
- static async readJson(opts) {
168
- const { response, context } = opts;
169
- const text = await HttpResponseReader.readText({ response });
170
- if (!text) {
171
- return null;
172
- }
173
- return HttpResponseReader.parseJson({ text, response, context });
174
- }
175
- static parseJson(opts) {
176
- const { text, response, context } = opts;
177
- try {
178
- return JSON.parse(text);
179
- }
180
- catch {
181
- const contentType = response.headers.get(HTTP.Headers.CONTENT_TYPE) ?? 'none';
182
- throw getError({
183
- statusCode: HTTP.ResultCodes.RS_5.BadGateway,
184
- message: `${context} | The response body is not JSON (${text.length} chars, content-type: ${contentType})`,
185
- });
186
- }
187
- }
188
- /**
189
- * A body the server marked with `x-response-extra` carries `extra` beside its rows. `body` is what
190
- * the route answers without extras: the `{ count, data }` envelope when the count was asked for in
191
- * the body, the rows otherwise. Any other body is returned as it stands - an unmarked object is
192
- * never unwrapped, so a row that has `data` and `extra` columns of its own is never misread.
193
- */
194
- static readExtra(opts) {
195
- const { body, headers } = opts;
196
- const isMarked = headers.has(HTTP.Headers.RESPONSE_EXTRA);
197
- if (!isMarked ||
198
- !HttpResponseReader.isPlainObject(body) ||
199
- !HttpResponseReader.isPlainObject(body.extra)) {
200
- return { body };
201
- }
202
- const { extra, ...envelope } = body;
203
- return { body: 'count' in envelope ? envelope : envelope.data, extra: { ...extra } };
204
- }
205
- }
206
- //# sourceMappingURL=response-reader.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"response-reader.js","sourceRoot":"","sources":["../../../../../src/base/repositories/common/response-reader.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,+BAA+B,CAAC;AAErD,OAAO,EAAE,QAAQ,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAC;AAGvE;;;GAGG;AACH,MAAM,OAAO,kBAAkB;IAC7B,6GAA6G;aAC7F,8BAAyB,GAAG,OAAO,CAAC;IAEpD,MAAM,CAAC,aAAa,CAAC,KAAc;QACjC,OAAO,CACL,CAAC,CAAC,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,MAAM,CAAC,cAAc,CAAC,KAAK,CAAC,KAAK,MAAM,CAAC,SAAS,CAC1F,CAAC;IACJ,CAAC;IAED,oEAAoE;IACpE,MAAM,CAAC,MAAM,CAAC,KAAc;QAC1B,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC;IACvE,CAAC;IAED;;;;OAIG;IACH,MAAM,CAAC,iBAAiB,CAAC,IAExB;QACC,MAAM,EAAE,MAAM,EAAE,GAAG,IAAI,CAAC;QAExB,IAAI,CAAC,MAAM,EAAE,CAAC;YACZ,OAAO,SAAS,CAAC;QACnB,CAAC;QAED,M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CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,YAAY,CAAC,IAAI,MAAM,CAAC;YAE9E,MAAM,QAAQ,CAAC;gBACb,UAAU,EAAE,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,UAAU;gBAC5C,OAAO,EAAE,GAAG,OAAO,qCAAqC,IAAI,CAAC,MAAM,yBAAyB,WAAW,GAAG;aAC3G,CAAC,CAAC;QACL,CAAC;IACH,CAAC;IAED;;;;;OAKG;IACH,MAAM,CAAC,SAAS,CAAC,IAAsD;QAIrE,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,GAAG,IAAI,CAAC;QAC/B,MAAM,QAAQ,GAAG,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,cAAc,CAAC,CAAC;QAE1D,IACE,CAAC,QAAQ;YACT,CAAC,kBAAkB,CAAC,aAAa,CAAC,IAAI,CAAC;YACvC,CAAC,kBAAkB,CAAC,aAAa,CAAC,IAAI,CAAC,KAAK,CAAC,EAC7C,CAAC;YACD,OAAO,EAAE,IAAI,EAAE,CAAC;QAClB,CAAC;QAED,MAAM,EAAE,KAAK,EAAE,GAAG,QAAQ,EAAE,GAAG,IAAI,CAAC;QAEpC,OAAO,EAAE,IAAI,EAAE,OAAO,IAAI,QAAQ,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,QAAQ,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,GAAG,KAAK,EAAE,EAAE,CAAC;IACvF,CAAC","sourcesContent":["import { HTTP } from '@venizia/ignis-helpers/common';\nimport type { TJsonValue } from '@venizia/ignis-helpers/common';\nimport { getError, ResponseReader } from '@venizia/ignis-helpers/core';\nimport type { ApplicationError, TResponsedError, UrlFetchError } from '@venizia/ignis-helpers/core';\n\n/**\n * What an IGNIS server answers - `Content-Range`, the error envelope - read once, here, for every\n * client of that server: the http connector, and a client that reads it without the connector.\n */\nexport class HttpResponseReader {\n /** A content type that names JSON: `application/json`, `application/problem+json`, `application/ld+json`. */\n static readonly JSON_CONTENT_TYPE_PATTERN = /json/i;\n\n static isPlainObject(value: unknown): value is Record<string, unknown> {\n return (\n !!value && typeof value === 'object' && Object.getPrototypeOf(value) === Object.prototype\n );\n }\n\n /** An empty string reads as absent, so a fallback still applies. */\n static toText(value: unknown): string | undefined {\n return typeof value === 'string' && value !== '' ? value : undefined;\n }\n\n /**\n * A `Content-Range` header as the IGNIS server writes it: `records 0-24/137` -> skip 0, total 137;\n * an empty page, `records *\\/137` -> total 137. Anything else, including an absent header or an\n * unknown total, is `undefined`.\n */\n static parseContentRange(opts: {\n header?: string | null;\n }): { skip?: number; total: number } | undefined {\n const { header } = opts;\n\n if (!header) {\n return undefined;\n }\n\n const range = header.match(/(\\d+)\\s*-\\s*(\\d+)\\s*\\/\\s*(\\d+)/);\n\n if (range) {\n return { skip: Number(range[1]), total: Number(range[3]) };\n }\n\n const unsatisfied = header.match(/\\*\\s*\\/\\s*(\\d+)/);\n\n if (unsatisfied) {\n return { total: Number(unsatisfied[1]) };\n }\n\n return undefined;\n }\n\n /**\n * The IGNIS error envelope - `{ message, statusCode, normalized: { text, code, args }, requestId,\n * extra, details }` - read off a parsed response body. A server configured with `error.rootKey`\n * wraps it under that key; pass the same `rootKey` to unwrap it. A body without that key, or with a\n * non-object under it (a proxy's `{ error: 'Bad Gateway' }`), is read as it stands.\n *\n * A body that is not a plain object yields `{}`; any other body yields its known fields, each\n * `undefined` when absent or mistyped. An empty string reads as absent.\n */\n static readErrorEnvelope(opts: { body: unknown; rootKey?: string }): TResponsedError {\n const { body, rootKey } = opts;\n\n const wrapped = rootKey && HttpResponseReader.isPlainObject(body) ? body[rootKey] : undefined;\n const envelope = HttpResponseReader.isPlainObject(wrapped) ? wrapped : body;\n\n if (!HttpResponseReader.isPlainObject(envelope)) {\n return {};\n }\n\n const { message, statusCode, normalized, requestId, extra, details } = envelope;\n const normalizedRecord = HttpResponseReader.isPlainObject(normalized) ? normalized : {};\n const { text, code, args } = normalizedRecord;\n\n return {\n message: HttpResponseReader.toText(message),\n statusCode: typeof statusCode === 'number' ? statusCode : undefined,\n normalized: {\n text: HttpResponseReader.toText(text),\n code: HttpResponseReader.toText(code),\n args: HttpResponseReader.isPlainObject(args) ? { ...args } : undefined,\n },\n requestId: HttpResponseReader.toText(requestId),\n extra: HttpResponseReader.isPlainObject(extra) ? { ...extra } : undefined,\n details: HttpResponseReader.isPlainObject(details) ? { ...details } : undefined,\n };\n }\n\n /** A failed response's envelope. A body that is not JSON yields `{}`, and the status alone still describes it. */\n static async readError(opts: { response: Response; rootKey?: string }): Promise<TResponsedError> {\n let text;\n\n try {\n const result = await opts.response.text();\n text = result;\n // eslint-disable-next-line venizia/no-silent-catch -- an unreadable body is read as no text; the status alone still describes the failure\n } catch {\n text = '';\n }\n\n let body: unknown;\n\n try {\n body = text ? JSON.parse(text) : undefined;\n // eslint-disable-next-line venizia/no-silent-catch -- a body that is not JSON yields `{}`; the status alone still describes the failure\n } catch {\n return {};\n }\n\n return HttpResponseReader.readErrorEnvelope({ body, rootKey: opts.rootKey });\n }\n\n /**\n * A failed response as the error the server threw: its status, code, args and text, and its\n * `extra` with the `requestId` added. `message` is `context` plus the server's text, for logs;\n * `normalized.text` stays the server's, for display - `HTTP <status>` when the server sent none.\n * `cause` is the server's `details.cause` - a 422's per-field issues, `{ path, message, code }`.\n *\n * `requestId` names the request this client made. A relaying server's `extra` carries the id of\n * the request it made upstream: it joins `upstreamRequestIds`, nearest first, at every hop.\n */\n static async toApplicationError(opts: {\n response: Response;\n /** Where it failed, for logs - e.g. `[HttpDataSource][read] 404 | /tickets`. */\n context: string;\n rootKey?: string;\n }): Promise<ApplicationError> {\n const { response, context, rootKey } = opts;\n const server = await HttpResponseReader.readError({ response, rootKey });\n const serverText = server.normalized?.text ?? server.message;\n const displayText = serverText ?? `HTTP ${response.status}`;\n\n const extra: Record<string, unknown> = { ...server.extra };\n\n if (server.requestId) {\n const upstreamRequestId = extra.requestId;\n extra.requestId = server.requestId;\n\n if (upstreamRequestId !== undefined && upstreamRequestId !== server.requestId) {\n const known = Array.isArray(extra.upstreamRequestIds) ? extra.upstreamRequestIds : [];\n extra.upstreamRequestIds = [upstreamRequestId, ...known];\n }\n }\n\n return getError({\n statusCode: response.status,\n message: serverText ? `${context} | ${serverText}` : context,\n messageCode: server.normalized?.code,\n messageArgs: server.normalized?.args,\n extra: Object.keys(extra).length > 0 ? extra : undefined,\n cause: server.details?.cause,\n transform: ({ message }) => ({ ...message, text: displayText }),\n });\n }\n\n /**\n * `toApplicationError` for a fetcher's refused answer: it reads the body the `UrlFetchError` kept (the first 64 KiB),\n * and an error that carries none is described by its status alone.\n */\n static async fromFetchError(opts: {\n error: UrlFetchError<Response>;\n context: string;\n rootKey?: string;\n }): Promise<ApplicationError> {\n const { error, context, rootKey } = opts;\n // A hand-built error may carry a status a `Response` refuses (below 200 or above 599, e.g. 0): that is a bad gateway.\n const isResponseStatus = error.status >= 200 && error.status <= 599;\n const response =\n error.response ??\n new Response(null, {\n status: isResponseStatus ? error.status : HTTP.ResultCodes.RS_5.BadGateway,\n headers: error.headers,\n });\n\n return HttpResponseReader.toApplicationError({ response, context, rootKey });\n }\n\n /**\n * The body as text: `''` for a 204 or an empty body. `response.json()` throws on those, and each client\n * that reads a response has copied the guard.\n */\n static async readText(opts: { response: Response }): Promise<string> {\n return ResponseReader.readText(opts);\n }\n\n /**\n * The body of a success answer, by what it says it is: `null` for a 204 or an empty body, the parsed\n * value when the content type names JSON (`application/json`, `application/problem+json`), the text itself\n * for any other type (`text/plain`, `text/csv`). A body that claims JSON and is not is a `502` that names\n * `context` (where it happened, e.g. `[Client][read] 200 | /tickets`), its size and its content type; its\n * content stays out of the message, which a relaying server may pass to its own clients.\n */\n static async readBody(opts: { response: Response; context: string }): Promise<TJsonValue> {\n const { response, context } = opts;\n const text = await HttpResponseReader.readText({ response });\n\n if (!text) {\n return null;\n }\n\n if (\n !HttpResponseReader.JSON_CONTENT_TYPE_PATTERN.test(\n response.headers.get(HTTP.Headers.CONTENT_TYPE) ?? '',\n )\n ) {\n return text;\n }\n\n return HttpResponseReader.parseJson({ text, response, context });\n }\n\n /**\n * The body as JSON whatever its content type says, `null` for a 204 or an empty body: for a route that\n * answers JSON under a type a proxy rewrote. Errors as `readBody` does.\n */\n static async readJson(opts: { response: Response; context: string }): Promise<TJsonValue> {\n const { response, context } = opts;\n const text = await HttpResponseReader.readText({ response });\n\n if (!text) {\n return null;\n }\n\n return HttpResponseReader.parseJson({ text, response, context });\n }\n\n private static parseJson(opts: {\n text: string;\n response: Response;\n context: string;\n }): TJsonValue {\n const { text, response, context } = opts;\n\n try {\n return JSON.parse(text);\n } catch {\n const contentType = response.headers.get(HTTP.Headers.CONTENT_TYPE) ?? 'none';\n\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.BadGateway,\n message: `${context} | The response body is not JSON (${text.length} chars, content-type: ${contentType})`,\n });\n }\n }\n\n /**\n * A body the server marked with `x-response-extra` carries `extra` beside its rows. `body` is what\n * the route answers without extras: the `{ count, data }` envelope when the count was asked for in\n * the body, the rows otherwise. Any other body is returned as it stands - an unmarked object is\n * never unwrapped, so a row that has `data` and `extra` columns of its own is never misread.\n */\n static readExtra(opts: { body: unknown; headers: Pick<Headers, 'has'> }): {\n body: unknown;\n extra?: Record<string, unknown>;\n } {\n const { body, headers } = opts;\n const isMarked = headers.has(HTTP.Headers.RESPONSE_EXTRA);\n\n if (\n !isMarked ||\n !HttpResponseReader.isPlainObject(body) ||\n !HttpResponseReader.isPlainObject(body.extra)\n ) {\n return { body };\n }\n\n const { extra, ...envelope } = body;\n\n return { body: 'count' in envelope ? envelope : envelope.data, extra: { ...extra } };\n }\n}\n"]}