@qaick/http-executor 0.1.0-alpha.4 → 0.1.0-alpha.6

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.
@@ -2,7 +2,7 @@ import type { ActionExecutionContext, ActionExecutionResult, ActionExecutor } fr
2
2
  export interface HttpResponse {
3
3
  status: number;
4
4
  body: unknown;
5
- headers?: Record<string, string>;
5
+ headers?: Record<string, string | string[]>;
6
6
  }
7
7
  export interface HttpTransport {
8
8
  request(url: string, init: {
@@ -13,36 +13,6 @@ export interface HttpTransport {
13
13
  timeoutMs?: number;
14
14
  }): Promise<HttpResponse>;
15
15
  }
16
- /** Internal Runtime-to-HTTP execution key. It is not part of persisted Action data. */
17
- export declare const HTTP_EXECUTION_ID_KEY = "__qaick_execution_id";
18
- export interface HttpCookie {
19
- name: string;
20
- value: string;
21
- domain: string;
22
- path: string;
23
- hostOnly: boolean;
24
- secure: boolean;
25
- expiresAt?: number;
26
- }
27
- /** Cookie state shared by HTTP Actions during one execution. */
28
- export declare class HttpCookieJar {
29
- private readonly cookies;
30
- store(url: string, setCookie: string | string[] | undefined): void;
31
- header(url: string): string | undefined;
32
- }
33
- /** HTTP-specific session boundary. One instance must be created per QAick execution. */
34
- export declare class HttpExecutionSession implements HttpTransport {
35
- private readonly transport;
36
- readonly cookies: HttpCookieJar;
37
- constructor(transport: HttpTransport, cookies?: HttpCookieJar);
38
- request(url: string, init: {
39
- method: string;
40
- body?: unknown;
41
- headers?: Record<string, string>;
42
- signal: AbortSignal;
43
- timeoutMs?: number;
44
- }): Promise<HttpResponse>;
45
- }
46
16
  export type HttpActionErrorCode = 'HTTP_INVALID_URL' | 'HTTP_REQUEST_CONSTRUCTION_ERROR' | 'HTTP_ABORTED' | 'HTTP_TIMEOUT' | 'HTTP_NETWORK_ERROR' | 'HTTP_RESPONSE_PARSE_ERROR' | 'HTTP_STATUS_ERROR';
47
17
  export declare class HttpActionError extends Error {
48
18
  readonly code: HttpActionErrorCode;
@@ -60,9 +30,7 @@ export declare class FetchHttpTransport implements HttpTransport {
60
30
  }
61
31
  export declare class HttpActionExecutor implements ActionExecutor {
62
32
  private readonly transport;
63
- private readonly sessions;
64
33
  constructor(transport: HttpTransport);
65
34
  supports(action: string): boolean;
66
35
  execute(context: ActionExecutionContext): Promise<ActionExecutionResult>;
67
- private sessionFor;
68
36
  }
@@ -1,76 +1,3 @@
1
- /** Internal Runtime-to-HTTP execution key. It is not part of persisted Action data. */
2
- export const HTTP_EXECUTION_ID_KEY = '__qaick_execution_id';
3
- /** Cookie state shared by HTTP Actions during one execution. */
4
- export class HttpCookieJar {
5
- cookies = new Map();
6
- store(url, setCookie) {
7
- if (!setCookie)
8
- return;
9
- const parsedUrl = new URL(url);
10
- for (const header of (Array.isArray(setCookie) ? setCookie : splitSetCookieHeader(setCookie))) {
11
- const cookie = parseSetCookie(header, parsedUrl);
12
- if (!cookie)
13
- continue;
14
- const key = cookieKey(cookie);
15
- if (cookie.expiresAt !== undefined && cookie.expiresAt <= Date.now())
16
- this.cookies.delete(key);
17
- else
18
- this.cookies.set(key, cookie);
19
- }
20
- }
21
- header(url) {
22
- const parsedUrl = new URL(url);
23
- const now = Date.now();
24
- const applicable = [];
25
- for (const [key, cookie] of this.cookies) {
26
- if (cookie.expiresAt !== undefined && cookie.expiresAt <= now) {
27
- this.cookies.delete(key);
28
- continue;
29
- }
30
- if (!cookieMatches(cookie, parsedUrl))
31
- continue;
32
- applicable.push(cookie);
33
- }
34
- applicable.sort((left, right) => right.path.length - left.path.length);
35
- return applicable.length ? applicable.map(cookie => `${cookie.name}=${cookie.value}`).join('; ') : undefined;
36
- }
37
- }
38
- /** HTTP-specific session boundary. One instance must be created per QAick execution. */
39
- export class HttpExecutionSession {
40
- transport;
41
- cookies;
42
- constructor(transport, cookies = new HttpCookieJar()) {
43
- this.transport = transport;
44
- this.cookies = cookies;
45
- }
46
- async request(url, init) {
47
- let currentUrl = url;
48
- let currentInit = { ...init };
49
- for (let redirect = 0; redirect <= 10; redirect += 1) {
50
- const headers = { ...(currentInit.headers ?? {}) };
51
- const cookieHeader = headerName(headers, 'cookie');
52
- const managed = this.cookies.header(currentUrl);
53
- const merged = mergeCookieHeaders(cookieHeader ? headers[cookieHeader] : undefined, managed);
54
- if (merged)
55
- headers[cookieHeader ?? 'cookie'] = merged;
56
- const response = await this.transport.request(currentUrl, { ...currentInit, headers });
57
- const setCookie = response.headers && headerValue(response.headers, 'set-cookie');
58
- this.cookies.store(currentUrl, setCookie);
59
- if (!isRedirect(response.status) || !response.headers)
60
- return response;
61
- const location = headerValue(response.headers, 'location');
62
- if (!location)
63
- return response;
64
- if (redirect === 10)
65
- return response;
66
- const nextUrl = new URL(location, currentUrl).toString();
67
- const nextMethod = response.status === 303 || ((response.status === 301 || response.status === 302) && currentInit.method.toUpperCase() === 'POST') ? 'GET' : currentInit.method;
68
- currentUrl = nextUrl;
69
- currentInit = nextMethod === 'GET' ? { ...currentInit, method: nextMethod, body: undefined } : { ...currentInit, method: nextMethod };
70
- }
71
- throw new Error('HTTP redirect limit exceeded.');
72
- }
73
- }
74
1
  export class HttpActionError extends Error {
75
2
  code;
76
3
  details;
@@ -81,84 +8,6 @@ export class HttpActionError extends Error {
81
8
  this.name = 'HttpActionError';
82
9
  }
83
10
  }
84
- function headerName(headers, expected) {
85
- return Object.keys(headers).find(name => name.toLowerCase() === expected);
86
- }
87
- function headerValue(headers, expected) {
88
- const name = Object.keys(headers).find(key => key.toLowerCase() === expected);
89
- return name ? headers[name] : undefined;
90
- }
91
- function isRedirect(status) { return status === 301 || status === 302 || status === 303 || status === 307 || status === 308; }
92
- function mergeCookieHeaders(explicit, managed) {
93
- const cookies = new Map();
94
- for (const value of [managed, explicit]) {
95
- for (const item of value?.split(';') ?? []) {
96
- const separator = item.indexOf('=');
97
- if (separator <= 0)
98
- continue;
99
- cookies.set(item.slice(0, separator).trim(), item.slice(separator + 1).trim());
100
- }
101
- }
102
- return cookies.size ? [...cookies.entries()].map(([name, value]) => `${name}=${value}`).join('; ') : undefined;
103
- }
104
- function splitSetCookieHeader(value) {
105
- return value.split(/\r?\n|,(?=\s*[^;,=\s]+=[^;,]*)/).map(item => item.trim()).filter(Boolean);
106
- }
107
- function parseSetCookie(header, requestUrl) {
108
- const parts = header.split(';').map(part => part.trim());
109
- const pair = parts.shift();
110
- if (!pair)
111
- return undefined;
112
- const separator = pair.indexOf('=');
113
- if (separator <= 0)
114
- return undefined;
115
- const name = pair.slice(0, separator).trim();
116
- const value = pair.slice(separator + 1).trim();
117
- let domain = requestUrl.hostname.toLowerCase();
118
- let hostOnly = true;
119
- let path = defaultCookiePath(requestUrl.pathname);
120
- let secure = false;
121
- let expiresAt;
122
- for (const attribute of parts) {
123
- const [rawName, ...rawValue] = attribute.split('=');
124
- const attributeName = rawName.trim().toLowerCase();
125
- const attributeValue = rawValue.join('=').trim();
126
- if (attributeName === 'domain' && attributeValue) {
127
- domain = attributeValue.replace(/^\./, '').toLowerCase();
128
- hostOnly = false;
129
- }
130
- else if (attributeName === 'path' && attributeValue.startsWith('/'))
131
- path = attributeValue;
132
- else if (attributeName === 'secure')
133
- secure = true;
134
- else if (attributeName === 'max-age') {
135
- const seconds = Number(attributeValue);
136
- if (Number.isFinite(seconds))
137
- expiresAt = Date.now() + seconds * 1000;
138
- }
139
- else if (attributeName === 'expires') {
140
- const timestamp = Date.parse(attributeValue);
141
- if (Number.isFinite(timestamp))
142
- expiresAt = timestamp;
143
- }
144
- }
145
- return { name, value, domain, path, hostOnly, secure, ...(expiresAt !== undefined ? { expiresAt } : {}) };
146
- }
147
- function defaultCookiePath(pathname) {
148
- if (!pathname || !pathname.startsWith('/'))
149
- return '/';
150
- const lastSlash = pathname.lastIndexOf('/');
151
- return lastSlash <= 0 ? '/' : pathname.slice(0, lastSlash);
152
- }
153
- function cookieMatches(cookie, url) {
154
- if (cookie.secure && url.protocol !== 'https:')
155
- return false;
156
- const host = url.hostname.toLowerCase();
157
- if (cookie.hostOnly ? host !== cookie.domain : !(host === cookie.domain || host.endsWith(`.${cookie.domain}`)))
158
- return false;
159
- return url.pathname === cookie.path || url.pathname.startsWith(cookie.path.endsWith('/') ? cookie.path : `${cookie.path}/`);
160
- }
161
- function cookieKey(cookie) { return `${cookie.name};${cookie.domain};${cookie.path}`; }
162
11
  export class FetchHttpTransport {
163
12
  async request(url, init) {
164
13
  const headers = { ...init.headers };
@@ -176,7 +25,7 @@ export class FetchHttpTransport {
176
25
  const timeout = init.timeoutMs === undefined ? undefined : setTimeout(() => controller.abort(), init.timeoutMs);
177
26
  let response;
178
27
  try {
179
- response = await fetch(url, { method: init.method, headers, body, signal: controller.signal, credentials: 'include' });
28
+ response = await fetch(url, { method: init.method, headers, body, signal: controller.signal });
180
29
  }
181
30
  catch (error) {
182
31
  if (init.signal.aborted)
@@ -205,7 +54,6 @@ export class FetchHttpTransport {
205
54
  }
206
55
  export class HttpActionExecutor {
207
56
  transport;
208
- sessions = new Map();
209
57
  constructor(transport) {
210
58
  this.transport = transport;
211
59
  }
@@ -220,7 +68,7 @@ export class HttpActionExecutor {
220
68
  url: appendQuery(url, substituteTemplateValue(context.inputs.query, context.inputs)),
221
69
  method: substituteTemplate(String(context.inputs.method ?? 'GET'), context.inputs),
222
70
  ...(context.inputs.body !== undefined ? { body: substituteTemplateValue(context.inputs.body, context.inputs) } : {}),
223
- ...(isRecord(context.inputs.headers) ? { headers: Object.fromEntries(Object.entries(substituteTemplateValue(context.inputs.headers, context.inputs)).map(([name, value]) => [name, String(value)])) } : {}),
71
+ ...(isRecord(context.inputs.headers) || isRecord(context.inputs.cookies) ? { headers: renderHeaders(context.inputs.headers, context.inputs.cookies, context.inputs) } : {}),
224
72
  };
225
73
  }
226
74
  catch (error) {
@@ -228,14 +76,14 @@ export class HttpActionExecutor {
228
76
  throw new HttpActionError('HTTP_REQUEST_CONSTRUCTION_ERROR', `HTTP Action request could not be constructed. ${detail}`);
229
77
  }
230
78
  const timeoutMs = typeof context.step.adapterConfig?.timeoutMs === 'number' ? context.step.adapterConfig.timeoutMs : undefined;
231
- const executionId = typeof context.runtimeValues[HTTP_EXECUTION_ID_KEY] === 'string' ? context.runtimeValues[HTTP_EXECUTION_ID_KEY] : undefined;
232
- const transport = executionId ? this.sessionFor(executionId) : this.transport;
233
- const response = await transport.request(request.url, { ...request, signal: context.signal, ...(timeoutMs !== undefined ? { timeoutMs } : {}) });
79
+ const response = await this.transport.request(request.url, { ...request, signal: context.signal, ...(timeoutMs !== undefined ? { timeoutMs } : {}) });
80
+ const outputs = { status: response.status, body: response.body, ...(response.headers ? { headers: response.headers } : {}), cookies: responseCookies(response.headers) };
81
+ const responseHeadersName = context.step.adapterConfig?.responseHeadersName;
82
+ if (typeof responseHeadersName === 'string')
83
+ outputs[responseHeadersName] = response.headers ?? {};
234
84
  if (response.status < 200 || response.status >= 300) {
235
- const serializedBody = typeof response.body === 'string' ? response.body : JSON.stringify(response.body) ?? '';
236
- throw new HttpActionError('HTTP_STATUS_ERROR', `HTTP Action returned status ${response.status}.${serializedBody ? ` Response: ${serializedBody.slice(0, 500)}` : ''}`, { status: response.status });
85
+ throw new HttpActionError('HTTP_STATUS_ERROR', `HTTP Action returned status ${response.status}. ${requestDiagnostics(request, response)}`, { status: response.status });
237
86
  }
238
- const outputs = { status: response.status, body: response.body, ...(response.headers ? { headers: response.headers } : {}) };
239
87
  const responseFields = isRecord(context.step.adapterConfig?.responseFields) ? context.step.adapterConfig.responseFields : undefined;
240
88
  if (responseFields)
241
89
  for (const [name, path] of Object.entries(responseFields))
@@ -246,15 +94,65 @@ export class HttpActionExecutor {
246
94
  const finishedAt = new Date().toISOString();
247
95
  return { outputs, evidence: { request: { url: request.url, method: request.method, headers: request.headers }, response: { status: response.status, headers: response.headers, body: response.body } }, timing: { startedAt, finishedAt, durationMs: Date.now() - startedMs } };
248
96
  }
249
- sessionFor(executionId) {
250
- let session = this.sessions.get(executionId);
251
- if (!session) {
252
- session = new HttpExecutionSession(this.transport);
253
- this.sessions.set(executionId, session);
254
- }
255
- return session;
97
+ }
98
+ function requestDiagnostics(request, response) {
99
+ const parsed = tryParseUrl(request.url);
100
+ const body = request.body === undefined ? undefined : typeof request.body === 'string' ? request.body : JSON.stringify(request.body) ?? '';
101
+ const responseBody = typeof response.body === 'string' ? response.body : JSON.stringify(response.body) ?? '';
102
+ return `Request diagnostics: method=${request.method} path=${parsed?.pathname ?? '(invalid)'} bodyBytes=${byteLength(body)} requestHeaderNames=${headerNames(request.headers).join(',') || '(none)'} responseHeaderNames=${headerNames(response.headers).join(',') || '(none)'} responseBodyBytes=${byteLength(responseBody)}.`;
103
+ }
104
+ function tryParseUrl(value) {
105
+ try {
106
+ return new URL(value);
107
+ }
108
+ catch {
109
+ return undefined;
256
110
  }
257
111
  }
112
+ function headerNames(headers) {
113
+ return Object.keys(headers ?? {}).map(name => name.toLowerCase()).sort();
114
+ }
115
+ function byteLength(value) {
116
+ return value === undefined ? 0 : new TextEncoder().encode(value).byteLength;
117
+ }
118
+ function responseCookies(headers) {
119
+ const raw = headers && Object.entries(headers).find(([name]) => name.toLowerCase() === 'set-cookie')?.[1];
120
+ const values = Array.isArray(raw) ? raw : raw ? raw.split(/\r?\n|,(?=\s*[^;,=\s]+=[^;,]*)/).map(item => item.trim()).filter(Boolean) : [];
121
+ return Object.fromEntries(values.flatMap(header => {
122
+ const [pair, ...parts] = header.split(';').map(item => item.trim());
123
+ const separator = pair?.indexOf('=') ?? -1;
124
+ if (!pair || separator <= 0)
125
+ return [];
126
+ const name = pair.slice(0, separator).trim();
127
+ const value = pair.slice(separator + 1).trim();
128
+ const attributes = {};
129
+ for (const part of parts) {
130
+ const equals = part.indexOf('=');
131
+ if (equals > 0)
132
+ attributes[part.slice(0, equals).trim().toLowerCase()] = part.slice(equals + 1).trim();
133
+ else if (part)
134
+ attributes[part.toLowerCase()] = true;
135
+ }
136
+ return [[name, { value, attributes }]];
137
+ }));
138
+ }
139
+ function renderHeaders(headersInput, cookiesInput, templateInputs) {
140
+ const headers = isRecord(headersInput)
141
+ ? Object.fromEntries(Object.entries(substituteTemplateValue(headersInput, templateInputs)).map(([name, value]) => [name, String(value)]))
142
+ : {};
143
+ if (!isRecord(cookiesInput) || Object.keys(headers).some(name => name.toLowerCase() === 'cookie'))
144
+ return headers;
145
+ const cookies = Object.entries(cookiesInput).flatMap(([name, value]) => {
146
+ if (isRecord(value) && typeof value.value === 'string')
147
+ return [`${name}=${value.value}`];
148
+ if (typeof value === 'string')
149
+ return [`${name}=${value}`];
150
+ return [];
151
+ });
152
+ if (cookies.length)
153
+ headers.Cookie = cookies.join('; ');
154
+ return headers;
155
+ }
258
156
  function appendQuery(url, query) {
259
157
  if (query === undefined || query === null)
260
158
  return url;
@@ -76,7 +76,7 @@ export class NodeHttpTransport {
76
76
  }
77
77
  }
78
78
  function normalizeHeaders(headers) {
79
- return Object.fromEntries(Object.entries(headers).map(([name, value]) => [name, Array.isArray(value) ? value.join(', ') : value ?? '']));
79
+ return Object.fromEntries(Object.entries(headers).map(([name, value]) => [name, Array.isArray(value) ? value : value ?? '']));
80
80
  }
81
81
  function headerValue(headers, name) {
82
82
  const value = headers[name];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@qaick/http-executor",
3
- "version": "0.1.0-alpha.4",
3
+ "version": "0.1.0-alpha.6",
4
4
  "description": "Reusable QAick HTTP Action execution with browser and native Node transports.",
5
5
  "keywords": [
6
6
  "qaick",
@@ -42,7 +42,7 @@
42
42
  "@qaick/executor": ">=0.1.0-alpha.1 <0.2.0"
43
43
  },
44
44
  "devDependencies": {
45
- "@qaick/executor": "0.1.0-alpha.1",
45
+ "@qaick/executor": "0.1.0-alpha.2",
46
46
  "@types/node": "^24.13.3",
47
47
  "typescript": "~6.0.2",
48
48
  "vitest": "^5.0.1"