@venizia/ignis-connectors 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.
@@ -10,13 +10,15 @@ export interface IAuthToken {
10
10
  type?: string;
11
11
  provider?: string;
12
12
  }
13
- /** The request a hook is asked about: the repository `paths`, the method, and the final URL with its query. */
13
+ /** What `onUnauthorized` is told besides the request: `attempt` is 1 for the first 401, 2 for the retry's own. */
14
+ export interface IHttpUnauthorizedInfo {
15
+ attempt: number;
16
+ }
17
+ /** The request a hook is asked about, the SAME object for every hook and every send of one call (a session map may key on it): the repository `paths`, the method, and the final URL with its query. */
14
18
  export interface IHttpRequestContext {
15
19
  paths: Array<string>;
16
20
  method: string;
17
21
  url: string;
18
- /** 1 for the first send, 2 for the one after a refreshed 401. */
19
- attempt?: number;
20
22
  /** The call's own signal: a hook may stop waiting on it. A refresh shared by other calls should not be aborted by one. */
21
23
  signal?: AbortSignal;
22
24
  }
@@ -52,8 +54,8 @@ export interface IHttpDataSourceSettings {
52
54
  authToken?: IAuthToken;
53
55
  /** Run on every send, the 401 retry included. `undefined` means no token for this request. A throw fails the request with that error. */
54
56
  authTokenResolver?: (context: IHttpRequestContext) => IAuthToken | undefined;
55
- /** Runs on a 401: `true` retries once (re-resolving the token), `false` lets the 401 stand. */
56
- onUnauthorized?: (context: IHttpRequestContext) => Promise<boolean> | boolean;
57
+ /** Runs on a 401: `true` retries once (re-resolving the token), `false` lets the 401 stand. `context` is the object the resolvers got for this call; `info.attempt` says which send failed. */
58
+ onUnauthorized?: (context: IHttpRequestContext, info: IHttpUnauthorizedInfo) => Promise<boolean> | boolean;
57
59
  /** What sends a request: the platform `fetch` when unset. Name one to route through a test double, a proxy or an instrumented client. */
58
60
  fetch?: THttpFetch;
59
61
  }
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../src/http/common/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { TNativeFetchSender } from '@venizia/ignis-helpers/core';\n\n/** A credential the HTTP datasource attaches to a request: `Authorization: <type> <value>`, and `provider`, when set, as the `x-auth-provider` header. */\nexport interface IAuthToken {\n value: string;\n /**\n * The authorization scheme.\n *\n * @default 'Bearer'\n */\n type?: string;\n provider?: string;\n}\n\n/** The request a hook is asked about: the repository `paths`, the method, and the final URL with its query. */\nexport interface IHttpRequestContext {\n paths: Array<string>;\n method: string;\n url: string;\n /** 1 for the first send, 2 for the one after a refreshed 401. */\n attempt?: number;\n /** The call's own signal: a hook may stop waiting on it. A refresh shared by other calls should not be aborted by one. */\n signal?: AbortSignal;\n}\n\n/** Not `Record` alone: header names are case-insensitive, and an object merge appends two spellings. */\nexport type THttpHeaders = Headers | Array<[string, string]> | Record<string, string>;\n\n/**\n * A request body. A plain object or array goes out as JSON; a string, `Blob`, `FormData`,\n * `URLSearchParams`, `ArrayBuffer` or typed array goes out as it is. Never a stream: the 401 retry\n * sends the same body twice.\n */\nexport type THttpBody = string | object;\n\n/** The list-extras request and result types live with the server contract, in kernel. */\nexport type { TExtraRequest, TExtraResult } from '@venizia/ignis-kernel/repository';\n\n/** What one call may add: its own headers (they win over the configured ones) and a signal to abort it. */\nexport interface IHttpCallOptions {\n headers?: THttpHeaders;\n signal?: AbortSignal;\n}\n\n/** Settings of the HTTP datasource: where to send, which headers and token to attach, and what to do on a 401. */\nexport interface IHttpDataSourceSettings {\n /** An absolute URL, or a path from the page origin (`/api`). A path-relative one is refused. */\n baseUrl: string;\n\n /** The server's `error.rootKey`: an error envelope wrapped under it is unwrapped before it is read. */\n errorRootKey?: string;\n\n /** Sent on every request. `x-request-count` is refused - the connector owns it. */\n headers?: THttpHeaders;\n\n /**\n * Headers for this request, run on every send (the 401 retry included); wins over `headers`, a call's own win over it. A throw\n * fails the request; `x-request-count` is refused, and an `authorization` stands only when no token resolves.\n */\n headersResolver?: (context: IHttpRequestContext) => THttpHeaders | undefined;\n\n /** Wins over `authTokenResolver`, and is sent whatever the request. */\n authToken?: IAuthToken;\n\n /** Run on every send, the 401 retry included. `undefined` means no token for this request. A throw fails the request with that error. */\n authTokenResolver?: (context: IHttpRequestContext) => IAuthToken | undefined;\n\n /** Runs on a 401: `true` retries once (re-resolving the token), `false` lets the 401 stand. */\n onUnauthorized?: (context: IHttpRequestContext) => Promise<boolean> | boolean;\n\n /** What sends a request: the platform `fetch` when unset. Name one to route through a test double, a proxy or an instrumented client. */\n fetch?: THttpFetch;\n}\n\n/** What sends a request: a URL and its init, a `Response` back. The public name of the sender type. */\nexport type THttpFetch = TNativeFetchSender;\n\n/** A list with no `Content-Range` has no total - `hasRange` says so rather than using the page size. */\nexport interface IHttpReadResult<R> {\n data: R;\n hasRange: boolean;\n /** Raw header: tells a present-but-unreadable one from an absent one. */\n contentRange?: string;\n total?: number;\n skip?: number;\n dataLength: number;\n /** What a list answered beside its rows, when the server marked it with `x-response-extra`. */\n extra?: Record<string, unknown>;\n}\n\n/** What a write answers: the rows the server returned, and its `x-response-count`. */\nexport interface IHttpWriteResult<R> {\n data: R;\n count: number;\n /** What the route answered beside the rows, when the server marked it with `x-response-extra`. */\n extra?: Record<string, unknown>;\n}\n\n/** Query parameters a route takes beside `filter` or `where` - a keyword, a scope. The filter and `where` win over a key of the same name. */\nexport type THttpExtraQuery = Record<string, unknown>;\n\n/** What the IGNIS search route answers: the total as `found` (`isFoundExact` is false when it is an estimate) and the hits. */\nexport interface IHttpSearchResult<R> {\n found: number;\n isFoundExact: boolean;\n hits: Array<{ document: R; score?: number; highlight?: unknown; highlights?: Array<unknown> }>;\n}\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../src/http/common/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { TNativeFetchSender } from '@venizia/ignis-helpers/core';\n\n/** A credential the HTTP datasource attaches to a request: `Authorization: <type> <value>`, and `provider`, when set, as the `x-auth-provider` header. */\nexport interface IAuthToken {\n value: string;\n /**\n * The authorization scheme.\n *\n * @default 'Bearer'\n */\n type?: string;\n provider?: string;\n}\n\n/** What `onUnauthorized` is told besides the request: `attempt` is 1 for the first 401, 2 for the retry's own. */\nexport interface IHttpUnauthorizedInfo {\n attempt: number;\n}\n\n/** The request a hook is asked about, the SAME object for every hook and every send of one call (a session map may key on it): the repository `paths`, the method, and the final URL with its query. */\nexport interface IHttpRequestContext {\n paths: Array<string>;\n method: string;\n url: string;\n /** The call's own signal: a hook may stop waiting on it. A refresh shared by other calls should not be aborted by one. */\n signal?: AbortSignal;\n}\n\n/** Not `Record` alone: header names are case-insensitive, and an object merge appends two spellings. */\nexport type THttpHeaders = Headers | Array<[string, string]> | Record<string, string>;\n\n/**\n * A request body. A plain object or array goes out as JSON; a string, `Blob`, `FormData`,\n * `URLSearchParams`, `ArrayBuffer` or typed array goes out as it is. Never a stream: the 401 retry\n * sends the same body twice.\n */\nexport type THttpBody = string | object;\n\n/** The list-extras request and result types live with the server contract, in kernel. */\nexport type { TExtraRequest, TExtraResult } from '@venizia/ignis-kernel/repository';\n\n/** What one call may add: its own headers (they win over the configured ones) and a signal to abort it. */\nexport interface IHttpCallOptions {\n headers?: THttpHeaders;\n signal?: AbortSignal;\n}\n\n/** Settings of the HTTP datasource: where to send, which headers and token to attach, and what to do on a 401. */\nexport interface IHttpDataSourceSettings {\n /** An absolute URL, or a path from the page origin (`/api`). A path-relative one is refused. */\n baseUrl: string;\n\n /** The server's `error.rootKey`: an error envelope wrapped under it is unwrapped before it is read. */\n errorRootKey?: string;\n\n /** Sent on every request. `x-request-count` is refused - the connector owns it. */\n headers?: THttpHeaders;\n\n /**\n * Headers for this request, run on every send (the 401 retry included); wins over `headers`, a call's own win over it. A throw\n * fails the request; `x-request-count` is refused, and an `authorization` stands only when no token resolves.\n */\n headersResolver?: (context: IHttpRequestContext) => THttpHeaders | undefined;\n\n /** Wins over `authTokenResolver`, and is sent whatever the request. */\n authToken?: IAuthToken;\n\n /** Run on every send, the 401 retry included. `undefined` means no token for this request. A throw fails the request with that error. */\n authTokenResolver?: (context: IHttpRequestContext) => IAuthToken | undefined;\n\n /** Runs on a 401: `true` retries once (re-resolving the token), `false` lets the 401 stand. `context` is the object the resolvers got for this call; `info.attempt` says which send failed. */\n onUnauthorized?: (\n context: IHttpRequestContext,\n info: IHttpUnauthorizedInfo,\n ) => Promise<boolean> | boolean;\n\n /** What sends a request: the platform `fetch` when unset. Name one to route through a test double, a proxy or an instrumented client. */\n fetch?: THttpFetch;\n}\n\n/** What sends a request: a URL and its init, a `Response` back. The public name of the sender type. */\nexport type THttpFetch = TNativeFetchSender;\n\n/** A list with no `Content-Range` has no total - `hasRange` says so rather than using the page size. */\nexport interface IHttpReadResult<R> {\n data: R;\n hasRange: boolean;\n /** Raw header: tells a present-but-unreadable one from an absent one. */\n contentRange?: string;\n total?: number;\n skip?: number;\n dataLength: number;\n /** What a list answered beside its rows, when the server marked it with `x-response-extra`. */\n extra?: Record<string, unknown>;\n}\n\n/** What a write answers: the rows the server returned, and its `x-response-count`. */\nexport interface IHttpWriteResult<R> {\n data: R;\n count: number;\n /** What the route answered beside the rows, when the server marked it with `x-response-extra`. */\n extra?: Record<string, unknown>;\n}\n\n/** Query parameters a route takes beside `filter` or `where` - a keyword, a scope. The filter and `where` win over a key of the same name. */\nexport type THttpExtraQuery = Record<string, unknown>;\n\n/** What the IGNIS search route answers: the total as `found` (`isFoundExact` is false when it is an estimate) and the hits. */\nexport interface IHttpSearchResult<R> {\n found: number;\n isFoundExact: boolean;\n hits: Array<{ document: R; score?: number; highlight?: unknown; highlights?: Array<unknown> }>;\n}\n"]}
@@ -127,7 +127,7 @@ export class HttpDataSource extends DataSourceRoot {
127
127
  error.status !== HTTP.ResultCodes.RS_4.Unauthorized) {
128
128
  return false;
129
129
  }
130
- const isRefreshed = await onUnauthorized({ ...context, attempt });
130
+ const isRefreshed = await onUnauthorized(context, { attempt });
131
131
  // The second 401 stands: the hook hears of it, its answer is ignored, and nothing is sent a third time.
132
132
  return attempt === 1 && isRefreshed;
133
133
  },
@@ -1 +1 @@
1
-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MAAM,MAAM,CAAC;QACf,CAAC;QAED,gEAAgE;QAChE,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,YAAY,CAAC,EAAE,QAAQ,EAAE,GAAG,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC,CAAC;QACzE,MAAM,EAAE,KAAK,EAAE,GAAG,kBAAkB,CAAC,SAAS,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,QAAQ,CAAC,OAAO,EAAE,CAAC,CAAC;QAC5F,gFAAgF;QAChF,MAAM,IAAI,GAAG,CAAC,KAAK,IAAI,kBAAkB,CAAC,aAAa,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,MAAM,CAAM,CAAC;QAE7F,MAAM,WAAW,GAAG,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,mBAAmB,CAAC,CAAC;QAC3E,MAAM,OAAO,GAAG,WAAW,KAAK,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC;QAExE,OAAO;YACL,IAAI;YACJ,KAAK,EAAE,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC;gBAC7B,CAAC,CAAC,OAAO;gBACT,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC;oBACnB,CAAC,CAAC,IAAI,CAAC,MAAM;oBACb,CAAC,CAAC,IAAI,KAAK,IAAI;wBACb,CAAC,CAAC,CAAC;wBACH,CAAC,CAAC,CAAC;YACT,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;SAC5B,CAAC;IACJ,CAAC;CACF","sourcesContent":["import { HttpReadShapes, HttpWireHeaders, type THttpReadShape } from './common/constants';\nimport { DataSourceRoot } from '@venizia/ignis-kernel/repository';\nimport { HTTP } from '@venizia/ignis-helpers/common';\nimport { NativeFetcher, UrlBuilder, UrlFetchError } from '@venizia/ignis-helpers/core';\nimport { HttpResponseReader } from './common/readers';\nimport type {\n IAuthToken,\n IHttpCallOptions,\n IHttpDataSourceSettings,\n TExtraRequest,\n IHttpReadResult,\n IHttpRequestContext,\n IHttpWriteResult,\n THttpBody,\n} from './common/types';\nimport { HttpWire } from './common/wire';\n\n/** Reads an IGNIS REST server through the repository contract. Targets IGNIS, not any REST API. */\nexport class HttpDataSource extends DataSourceRoot<IHttpDataSourceSettings> {\n override name: string;\n override settings: IHttpDataSourceSettings;\n override schema = {} as never;\n\n /** Normalised once: every request copies these, never re-parses `settings.headers`. */\n protected configuredHeaders: Array<[string, string]>;\n\n constructor(opts: IHttpDataSourceSettings & { name?: string }) {\n super({ scope: opts.name ?? HttpDataSource.name });\n\n const { name = 'http', ...settings } = opts;\n\n const configured = HttpWire.toHeaderEntries({ headers: settings.headers });\n HttpWire.assertNoRequestCountHeader({ entries: configured, name });\n\n UrlBuilder.assertBase({ baseUrl: settings.baseUrl, scope: name });\n\n this.configuredHeaders = configured;\n this.name = name;\n this.settings = settings;\n }\n\n async configure(): Promise<void> {}\n\n override getCapabilities() {\n return { transactions: false };\n }\n\n protected resolveAuthToken(opts: { context: IHttpRequestContext }): IAuthToken | undefined {\n return this.settings.authToken ?? this.settings.authTokenResolver?.(opts.context);\n }\n\n /** Re-run on every send, so a header the app changed since the last request is the one sent. */\n protected resolveHeaders(opts: { context: IHttpRequestContext }): Array<[string, string]> {\n const resolver = this.settings.headersResolver;\n\n if (!resolver) {\n return [];\n }\n\n const entries = HttpWire.toHeaderEntries({ headers: resolver(opts.context) });\n HttpWire.assertNoRequestCountHeader({ entries, name: this.name });\n\n return entries;\n }\n\n protected buildHeaders(opts: {\n token?: IAuthToken;\n requestHeaders?: Array<[string, string]>;\n isJsonBody?: boolean;\n isFormDataBody?: boolean;\n }): Headers {\n const { token, requestHeaders, isJsonBody, isFormDataBody } = opts;\n const headers = new Headers(this.configuredHeaders);\n\n // A request's own headers win over the configured ones; the connector's below win over both.\n for (const [name, value] of requestHeaders ?? []) {\n headers.set(name, value);\n }\n\n if (isJsonBody && !headers.has(HTTP.Headers.CONTENT_TYPE)) {\n headers.set(HTTP.Headers.CONTENT_TYPE, HTTP.HeaderValues.APPLICATION_JSON);\n }\n\n // Only `fetch` knows the multipart boundary; any other content-type here would drop it.\n if (isFormDataBody) {\n headers.delete(HTTP.Headers.CONTENT_TYPE);\n }\n\n // Set last: under the envelope a record read answers `{ count, data }`.\n headers.set(HTTP.Headers.REQUEST_COUNT_DATA, 'false');\n\n if (!token) {\n return headers;\n }\n\n headers.set(HTTP.Headers.AUTHORIZATION, `${token.type ?? 'Bearer'} ${token.value}`);\n\n // Unconditionally it would send the string \"undefined\".\n if (token.provider) {\n headers.set(HttpWireHeaders.AUTH_PROVIDER, token.provider);\n }\n\n return headers;\n }\n\n buildUrl(opts: { paths: Array<string>; query?: Record<string, unknown> }): string {\n const { paths, query } = opts;\n const url = UrlBuilder.join({ baseUrl: this.settings.baseUrl, paths, scope: this.name });\n\n const parameters = Object.entries(query ?? {});\n\n for (const [key, value] of parameters) {\n if (value === undefined) {\n continue;\n }\n\n url.searchParams.set(\n key,\n typeof value === 'string'\n ? value\n : HttpWire.toJson({ value, label: `[${this.name}] Query parameter '${key}'` }),\n );\n }\n\n return url.toString();\n }\n\n /**\n * The raw `Response`, on any method - for what the repository verbs do not cover, like an export\n * or a PUT to a hand-written route. Auth and the 401 retry apply; the retry resends the same body.\n */\n async request(\n opts: {\n paths: Array<string>;\n query?: Record<string, unknown>;\n method?: string;\n body?: THttpBody;\n } & IHttpCallOptions,\n ): Promise<Response> {\n return this.sendRequest({ ...opts, url: this.buildUrl(opts) });\n }\n\n /** `request` on a URL already built: `read` and `write` serialise a long query once, not per use. */\n protected async sendRequest(\n opts: {\n paths: Array<string>;\n url: string;\n method?: string;\n body?: THttpBody;\n } & IHttpCallOptions,\n ): Promise<Response> {\n const { url, signal } = opts;\n const requestHeaders = HttpWire.toHeaderEntries({ headers: opts.headers });\n HttpWire.assertNoRequestCountHeader({ entries: requestHeaders, name: this.name });\n\n const method = opts.method ?? HTTP.Methods.GET;\n const context: IHttpRequestContext = { paths: opts.paths, method, url, signal };\n const { payload, isJson, isFormData } = HttpWire.toRequestBody({ body: opts.body });\n const { onUnauthorized } = this.settings;\n\n // One fetcher per call: its hooks close over this call's context. Both resolvers run in `onRequest`, so the retry sends what they answer after the refresh.\n const fetcher = new NativeFetcher({\n name: this.name,\n fetch: this.settings.fetch,\n hooks: {\n onRequest: ({ headers }) => {\n const built = this.buildHeaders({\n token: this.resolveAuthToken({ context }),\n // Resolved first, so the call's own headers win over them.\n requestHeaders: [...this.resolveHeaders({ context }), ...requestHeaders],\n isJsonBody: isJson,\n isFormDataBody: isFormData,\n });\n\n for (const name of [...headers.keys()]) {\n headers.delete(name);\n }\n\n built.forEach((value, name) => headers.set(name, value));\n },\n },\n });\n\n try {\n const response = await fetcher.send({\n url,\n method,\n body: payload,\n signal,\n // Every status is an answer the data source reads itself; a 401 with a refresh hook throws once so the retry can see it.\n acceptStatus: (status) => !onUnauthorized || status !== HTTP.ResultCodes.RS_4.Unauthorized,\n retry: onUnauthorized\n ? {\n maxAttempts: 2,\n backoff: { initialDelayMs: 0, maxDelayMs: 0 },\n shouldRetry: async ({ error, attempt }) => {\n if (\n !UrlFetchError.is(error) ||\n error.status !== HTTP.ResultCodes.RS_4.Unauthorized\n ) {\n return false;\n }\n\n const isRefreshed = await onUnauthorized({ ...context, attempt });\n\n // The second 401 stands: the hook hears of it, its answer is ignored, and nothing is sent a third time.\n return attempt === 1 && isRefreshed;\n },\n }\n : undefined,\n });\n\n return response;\n } catch (error) {\n // The 401 that stands is the answer: the data source reads its body into its own error.\n if (\n error instanceof UrlFetchError &&\n error.status === HTTP.ResultCodes.RS_4.Unauthorized &&\n error.response instanceof Response\n ) {\n return error.response;\n }\n\n throw error;\n }\n }\n\n /**\n * The body as JSON, `null` when there is none; a body that is not JSON is the server's fault, named\n * as such. Its content stays out of the message, which a relaying server may pass to its clients.\n */\n protected async readJsonBody(opts: { response: Response; url: string; verb: string }) {\n const { response, url, verb } = opts;\n\n return HttpResponseReader.readJson({\n response,\n context: `[${this.name}][${verb}] ${response.status} | ${HttpWire.describeUrl({ url, status: response.status })}`,\n });\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` adds where it failed, for logs; `normalized.text`\n * stays the server's, for display - `HTTP <status>` when the server sent none. `cause` is the server's `details.cause` - a 422's per-field\n * issues, `{ path, message, code }`.\n */\n protected async toResponseError(opts: { response: Response; url: string; verb: string }) {\n const { response, url, verb } = opts;\n const described = HttpWire.describeUrl({ url, status: response.status });\n\n return HttpResponseReader.toApplicationError({\n response,\n rootKey: this.settings.errorRootKey,\n context: `[${this.name}][${verb}] ${response.status} | ${described}`,\n });\n }\n\n /**\n * Rows plus the total from `Content-Range`, reported absent when the header is. A GET unless told\n * otherwise: `method` and `body` reach a list route a service wrote to take its filter in a body.\n */\n async read<R>(\n opts: {\n paths: Array<string>;\n query?: Record<string, unknown>;\n shape?: THttpReadShape;\n method?: string;\n body?: THttpBody;\n /** Extras the route offers beside its rows, asked for by name (`x-request-extra`). */\n extra?: TExtraRequest;\n /** The rows alone: every default extra off (`-*`), for a read that only counts or probes. */\n isEveryDefaultOff?: boolean;\n } & IHttpCallOptions,\n ): Promise<IHttpReadResult<R>> {\n const url = this.buildUrl(opts);\n const headers = HttpWire.withExtraHeader({\n headers: opts.headers,\n extra: opts.extra,\n isEveryDefaultOff: opts.isEveryDefaultOff,\n });\n const response = await this.sendRequest({ ...opts, url, headers });\n\n if (!response.ok) {\n const result = await this.toResponseError({ response, url, verb: 'read' });\n throw result;\n }\n\n // A 204 or an empty body is no row; a list asked for of it still throws below.\n const parsed = await this.readJsonBody({ response, url, verb: 'read' });\n const { body, extra } = HttpResponseReader.readExtra({\n body: parsed,\n headers: response.headers,\n });\n const contentRange = response.headers.get(HTTP.Headers.CONTENT_RANGE) ?? undefined;\n const range = HttpResponseReader.parseContentRange({ header: contentRange });\n const data = HttpWire.unwrapRows<R>({ body, shape: opts.shape ?? HttpReadShapes.LIST, url });\n\n return {\n data,\n hasRange: range !== undefined,\n contentRange,\n total: range?.total,\n skip: range?.skip,\n dataLength: Array.isArray(data) ? data.length : data === null ? 0 : 1,\n extra,\n };\n }\n\n /**\n * A write, and what it answered: the body as the rows, the count from `x-response-count`. The\n * connector asks for bare rows, so an IGNIS write answers the row or the rows, never the envelope.\n */\n async write<R>(\n opts: {\n paths: Array<string>;\n query?: Record<string, unknown>;\n method: string;\n body?: THttpBody;\n /** Extras the route answers beside its rows, asked for by name (`x-request-extra`). */\n extra?: TExtraRequest;\n } & IHttpCallOptions,\n ): Promise<IHttpWriteResult<R>> {\n const url = this.buildUrl(opts);\n const headers = HttpWire.withExtraHeader({ headers: opts.headers, extra: opts.extra });\n const response = await this.sendRequest({ ...opts, url, headers });\n\n if (!response.ok) {\n const result = await this.toResponseError({ response, url, verb: 'write' });\n throw result;\n }\n\n // A 204, or a route that answers nothing, has no body to parse.\n const parsed = await this.readJsonBody({ response, url, verb: 'write' });\n const { extra } = HttpResponseReader.readExtra({ body: parsed, headers: response.headers });\n // `extra` is only read off an object body, which carries the rows under `data`.\n const data = (extra && HttpResponseReader.isPlainObject(parsed) ? parsed.data : parsed) as R;\n\n const countHeader = response.headers.get(HTTP.Headers.RESPONSE_COUNT_DATA);\n const counted = countHeader === null ? Number.NaN : Number(countHeader);\n\n return {\n data,\n count: Number.isFinite(counted)\n ? counted\n : Array.isArray(data)\n ? data.length\n : data === null\n ? 0\n : 1,\n ...(extra ? { extra } : {}),\n };\n }\n}\n"]}
1
+ {"version":3,"file":"datasource.js","sourceRoot":"","sources":["../../../src/http/datasource.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,eAAe,EAAuB,MAAM,oBAAoB,CAAC;AAC1F,OAAO,EAAE,cAAc,EAAE,MAAM,kC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,EAAE,KAAK,EAAE,GAAG,kBAAkB,CAAC,SAAS,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,QAAQ,CAAC,OAAO,EAAE,CAAC,CAAC;QAC5F,gFAAgF;QAChF,MAAM,IAAI,GAAG,CAAC,KAAK,IAAI,kBAAkB,CAAC,aAAa,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,MAAM,CAAM,CAAC;QAE7F,MAAM,WAAW,GAAG,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,mBAAmB,CAAC,CAAC;QAC3E,MAAM,OAAO,GAAG,WAAW,KAAK,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC;QAExE,OAAO;YACL,IAAI;YACJ,KAAK,EAAE,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC;gBAC7B,CAAC,CAAC,OAAO;gBACT,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC;oBACnB,CAAC,CAAC,IAAI,CAAC,MAAM;oBACb,CAAC,CAAC,IAAI,KAAK,IAAI;wBACb,CAAC,CAAC,CAAC;wBACH,CAAC,CAAC,CAAC;YACT,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;SAC5B,CAAC;IACJ,CAAC;CACF","sourcesContent":["import { HttpReadShapes, HttpWireHeaders, type THttpReadShape } from './common/constants';\nimport { DataSourceRoot } from '@venizia/ignis-kernel/repository';\nimport { HTTP } from '@venizia/ignis-helpers/common';\nimport { NativeFetcher, UrlBuilder, UrlFetchError } from '@venizia/ignis-helpers/core';\nimport { HttpResponseReader } from './common/readers';\nimport type {\n IAuthToken,\n IHttpCallOptions,\n IHttpDataSourceSettings,\n TExtraRequest,\n IHttpReadResult,\n IHttpRequestContext,\n IHttpWriteResult,\n THttpBody,\n} from './common/types';\nimport { HttpWire } from './common/wire';\n\n/** Reads an IGNIS REST server through the repository contract. Targets IGNIS, not any REST API. */\nexport class HttpDataSource extends DataSourceRoot<IHttpDataSourceSettings> {\n override name: string;\n override settings: IHttpDataSourceSettings;\n override schema = {} as never;\n\n /** Normalised once: every request copies these, never re-parses `settings.headers`. */\n protected configuredHeaders: Array<[string, string]>;\n\n constructor(opts: IHttpDataSourceSettings & { name?: string }) {\n super({ scope: opts.name ?? HttpDataSource.name });\n\n const { name = 'http', ...settings } = opts;\n\n const configured = HttpWire.toHeaderEntries({ headers: settings.headers });\n HttpWire.assertNoRequestCountHeader({ entries: configured, name });\n\n UrlBuilder.assertBase({ baseUrl: settings.baseUrl, scope: name });\n\n this.configuredHeaders = configured;\n this.name = name;\n this.settings = settings;\n }\n\n async configure(): Promise<void> {}\n\n override getCapabilities() {\n return { transactions: false };\n }\n\n protected resolveAuthToken(opts: { context: IHttpRequestContext }): IAuthToken | undefined {\n return this.settings.authToken ?? this.settings.authTokenResolver?.(opts.context);\n }\n\n /** Re-run on every send, so a header the app changed since the last request is the one sent. */\n protected resolveHeaders(opts: { context: IHttpRequestContext }): Array<[string, string]> {\n const resolver = this.settings.headersResolver;\n\n if (!resolver) {\n return [];\n }\n\n const entries = HttpWire.toHeaderEntries({ headers: resolver(opts.context) });\n HttpWire.assertNoRequestCountHeader({ entries, name: this.name });\n\n return entries;\n }\n\n protected buildHeaders(opts: {\n token?: IAuthToken;\n requestHeaders?: Array<[string, string]>;\n isJsonBody?: boolean;\n isFormDataBody?: boolean;\n }): Headers {\n const { token, requestHeaders, isJsonBody, isFormDataBody } = opts;\n const headers = new Headers(this.configuredHeaders);\n\n // A request's own headers win over the configured ones; the connector's below win over both.\n for (const [name, value] of requestHeaders ?? []) {\n headers.set(name, value);\n }\n\n if (isJsonBody && !headers.has(HTTP.Headers.CONTENT_TYPE)) {\n headers.set(HTTP.Headers.CONTENT_TYPE, HTTP.HeaderValues.APPLICATION_JSON);\n }\n\n // Only `fetch` knows the multipart boundary; any other content-type here would drop it.\n if (isFormDataBody) {\n headers.delete(HTTP.Headers.CONTENT_TYPE);\n }\n\n // Set last: under the envelope a record read answers `{ count, data }`.\n headers.set(HTTP.Headers.REQUEST_COUNT_DATA, 'false');\n\n if (!token) {\n return headers;\n }\n\n headers.set(HTTP.Headers.AUTHORIZATION, `${token.type ?? 'Bearer'} ${token.value}`);\n\n // Unconditionally it would send the string \"undefined\".\n if (token.provider) {\n headers.set(HttpWireHeaders.AUTH_PROVIDER, token.provider);\n }\n\n return headers;\n }\n\n buildUrl(opts: { paths: Array<string>; query?: Record<string, unknown> }): string {\n const { paths, query } = opts;\n const url = UrlBuilder.join({ baseUrl: this.settings.baseUrl, paths, scope: this.name });\n\n const parameters = Object.entries(query ?? {});\n\n for (const [key, value] of parameters) {\n if (value === undefined) {\n continue;\n }\n\n url.searchParams.set(\n key,\n typeof value === 'string'\n ? value\n : HttpWire.toJson({ value, label: `[${this.name}] Query parameter '${key}'` }),\n );\n }\n\n return url.toString();\n }\n\n /**\n * The raw `Response`, on any method - for what the repository verbs do not cover, like an export\n * or a PUT to a hand-written route. Auth and the 401 retry apply; the retry resends the same body.\n */\n async request(\n opts: {\n paths: Array<string>;\n query?: Record<string, unknown>;\n method?: string;\n body?: THttpBody;\n } & IHttpCallOptions,\n ): Promise<Response> {\n return this.sendRequest({ ...opts, url: this.buildUrl(opts) });\n }\n\n /** `request` on a URL already built: `read` and `write` serialise a long query once, not per use. */\n protected async sendRequest(\n opts: {\n paths: Array<string>;\n url: string;\n method?: string;\n body?: THttpBody;\n } & IHttpCallOptions,\n ): Promise<Response> {\n const { url, signal } = opts;\n const requestHeaders = HttpWire.toHeaderEntries({ headers: opts.headers });\n HttpWire.assertNoRequestCountHeader({ entries: requestHeaders, name: this.name });\n\n const method = opts.method ?? HTTP.Methods.GET;\n const context: IHttpRequestContext = { paths: opts.paths, method, url, signal };\n const { payload, isJson, isFormData } = HttpWire.toRequestBody({ body: opts.body });\n const { onUnauthorized } = this.settings;\n\n // One fetcher per call: its hooks close over this call's context. Both resolvers run in `onRequest`, so the retry sends what they answer after the refresh.\n const fetcher = new NativeFetcher({\n name: this.name,\n fetch: this.settings.fetch,\n hooks: {\n onRequest: ({ headers }) => {\n const built = this.buildHeaders({\n token: this.resolveAuthToken({ context }),\n // Resolved first, so the call's own headers win over them.\n requestHeaders: [...this.resolveHeaders({ context }), ...requestHeaders],\n isJsonBody: isJson,\n isFormDataBody: isFormData,\n });\n\n for (const name of [...headers.keys()]) {\n headers.delete(name);\n }\n\n built.forEach((value, name) => headers.set(name, value));\n },\n },\n });\n\n try {\n const response = await fetcher.send({\n url,\n method,\n body: payload,\n signal,\n // Every status is an answer the data source reads itself; a 401 with a refresh hook throws once so the retry can see it.\n acceptStatus: (status) => !onUnauthorized || status !== HTTP.ResultCodes.RS_4.Unauthorized,\n retry: onUnauthorized\n ? {\n maxAttempts: 2,\n backoff: { initialDelayMs: 0, maxDelayMs: 0 },\n shouldRetry: async ({ error, attempt }) => {\n if (\n !UrlFetchError.is(error) ||\n error.status !== HTTP.ResultCodes.RS_4.Unauthorized\n ) {\n return false;\n }\n\n const isRefreshed = await onUnauthorized(context, { attempt });\n\n // The second 401 stands: the hook hears of it, its answer is ignored, and nothing is sent a third time.\n return attempt === 1 && isRefreshed;\n },\n }\n : undefined,\n });\n\n return response;\n } catch (error) {\n // The 401 that stands is the answer: the data source reads its body into its own error.\n if (\n error instanceof UrlFetchError &&\n error.status === HTTP.ResultCodes.RS_4.Unauthorized &&\n error.response instanceof Response\n ) {\n return error.response;\n }\n\n throw error;\n }\n }\n\n /**\n * The body as JSON, `null` when there is none; a body that is not JSON is the server's fault, named\n * as such. Its content stays out of the message, which a relaying server may pass to its clients.\n */\n protected async readJsonBody(opts: { response: Response; url: string; verb: string }) {\n const { response, url, verb } = opts;\n\n return HttpResponseReader.readJson({\n response,\n context: `[${this.name}][${verb}] ${response.status} | ${HttpWire.describeUrl({ url, status: response.status })}`,\n });\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` adds where it failed, for logs; `normalized.text`\n * stays the server's, for display - `HTTP <status>` when the server sent none. `cause` is the server's `details.cause` - a 422's per-field\n * issues, `{ path, message, code }`.\n */\n protected async toResponseError(opts: { response: Response; url: string; verb: string }) {\n const { response, url, verb } = opts;\n const described = HttpWire.describeUrl({ url, status: response.status });\n\n return HttpResponseReader.toApplicationError({\n response,\n rootKey: this.settings.errorRootKey,\n context: `[${this.name}][${verb}] ${response.status} | ${described}`,\n });\n }\n\n /**\n * Rows plus the total from `Content-Range`, reported absent when the header is. A GET unless told\n * otherwise: `method` and `body` reach a list route a service wrote to take its filter in a body.\n */\n async read<R>(\n opts: {\n paths: Array<string>;\n query?: Record<string, unknown>;\n shape?: THttpReadShape;\n method?: string;\n body?: THttpBody;\n /** Extras the route offers beside its rows, asked for by name (`x-request-extra`). */\n extra?: TExtraRequest;\n /** The rows alone: every default extra off (`-*`), for a read that only counts or probes. */\n isEveryDefaultOff?: boolean;\n } & IHttpCallOptions,\n ): Promise<IHttpReadResult<R>> {\n const url = this.buildUrl(opts);\n const headers = HttpWire.withExtraHeader({\n headers: opts.headers,\n extra: opts.extra,\n isEveryDefaultOff: opts.isEveryDefaultOff,\n });\n const response = await this.sendRequest({ ...opts, url, headers });\n\n if (!response.ok) {\n const result = await this.toResponseError({ response, url, verb: 'read' });\n throw result;\n }\n\n // A 204 or an empty body is no row; a list asked for of it still throws below.\n const parsed = await this.readJsonBody({ response, url, verb: 'read' });\n const { body, extra } = HttpResponseReader.readExtra({\n body: parsed,\n headers: response.headers,\n });\n const contentRange = response.headers.get(HTTP.Headers.CONTENT_RANGE) ?? undefined;\n const range = HttpResponseReader.parseContentRange({ header: contentRange });\n const data = HttpWire.unwrapRows<R>({ body, shape: opts.shape ?? HttpReadShapes.LIST, url });\n\n return {\n data,\n hasRange: range !== undefined,\n contentRange,\n total: range?.total,\n skip: range?.skip,\n dataLength: Array.isArray(data) ? data.length : data === null ? 0 : 1,\n extra,\n };\n }\n\n /**\n * A write, and what it answered: the body as the rows, the count from `x-response-count`. The\n * connector asks for bare rows, so an IGNIS write answers the row or the rows, never the envelope.\n */\n async write<R>(\n opts: {\n paths: Array<string>;\n query?: Record<string, unknown>;\n method: string;\n body?: THttpBody;\n /** Extras the route answers beside its rows, asked for by name (`x-request-extra`). */\n extra?: TExtraRequest;\n } & IHttpCallOptions,\n ): Promise<IHttpWriteResult<R>> {\n const url = this.buildUrl(opts);\n const headers = HttpWire.withExtraHeader({ headers: opts.headers, extra: opts.extra });\n const response = await this.sendRequest({ ...opts, url, headers });\n\n if (!response.ok) {\n const result = await this.toResponseError({ response, url, verb: 'write' });\n throw result;\n }\n\n // A 204, or a route that answers nothing, has no body to parse.\n const parsed = await this.readJsonBody({ response, url, verb: 'write' });\n const { extra } = HttpResponseReader.readExtra({ body: parsed, headers: response.headers });\n // `extra` is only read off an object body, which carries the rows under `data`.\n const data = (extra && HttpResponseReader.isPlainObject(parsed) ? parsed.data : parsed) as R;\n\n const countHeader = response.headers.get(HTTP.Headers.RESPONSE_COUNT_DATA);\n const counted = countHeader === null ? Number.NaN : Number(countHeader);\n\n return {\n data,\n count: Number.isFinite(counted)\n ? counted\n : Array.isArray(data)\n ? data.length\n : data === null\n ? 0\n : 1,\n ...(extra ? { extra } : {}),\n };\n }\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@venizia/ignis-connectors",
3
- "version": "0.5.0-0",
3
+ "version": "0.5.0-2",
4
4
  "description": "Datasource and repository connectors for the IGNIS framework: the engine-neutral relational and search tiers, plus Postgres, SQLite, PGlite, Typesense and Meilisearch behind sub-paths.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -100,13 +100,13 @@
100
100
  "@venizia/ignis-filter": "0.5.0-0",
101
101
  "@venizia/ignis-helpers": "0.5.0-0",
102
102
  "@venizia/ignis-inversion": "0.5.0-0",
103
- "@venizia/ignis-kernel": "0.5.0-0",
103
+ "@venizia/ignis-kernel": "0.5.0-1",
104
104
  "zod": "^4.6.7"
105
105
  },
106
106
  "devDependencies": {
107
107
  "@types/bun": "^1.4.3",
108
108
  "@types/pg": "^8.23.1",
109
- "@venizia/dev-configs": "0.5.0-0",
109
+ "@venizia/dev-configs": "0.5.0-1",
110
110
  "eslint": "^10.13.0",
111
111
  "oxlint": "1.89.0",
112
112
  "oxlint-tsgolint": "7.0.2004",