@xylex-group/athena 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs ADDED
@@ -0,0 +1,248 @@
1
+ // src/gateway/client.ts
2
+ var DEFAULT_BASE_URL = "https://athena-db.com";
3
+ var DEFAULT_CLIENT = "railway_direct";
4
+ function parseResponseText(text) {
5
+ if (!text) return null;
6
+ try {
7
+ return JSON.parse(text);
8
+ } catch {
9
+ return text;
10
+ }
11
+ }
12
+ function normalizeHeaderValue(value) {
13
+ return value ? value : void 0;
14
+ }
15
+ function buildHeaders(config, options) {
16
+ const mergedStripNulls = options?.stripNulls ?? config.stripNulls ?? true;
17
+ const finalClient = options?.client ?? config.client ?? DEFAULT_CLIENT;
18
+ const finalApiKey = options?.apiKey ?? config.apiKey;
19
+ const finalSupabaseUrl = options?.supabaseUrl ?? config.supabaseUrl;
20
+ const finalSupabaseKey = options?.supabaseKey ?? config.supabaseKey;
21
+ const finalPublishEvent = options?.publishEvent ?? config.publishEvent;
22
+ const extraHeaders = {
23
+ ...config.headers ?? {},
24
+ ...options?.headers ?? {}
25
+ };
26
+ const headers = {
27
+ "Content-Type": "application/json"
28
+ };
29
+ if (options?.userId ?? config.userId) {
30
+ headers["X-User-Id"] = options?.userId ?? config.userId ?? "";
31
+ }
32
+ if (options?.companyId ?? config.companyId) {
33
+ headers["X-Company-Id"] = options?.companyId ?? config.companyId ?? "";
34
+ }
35
+ if (options?.organizationId ?? config.organizationId) {
36
+ headers["X-Organization-Id"] = options?.organizationId ?? config.organizationId ?? "";
37
+ }
38
+ if (finalClient) {
39
+ headers["X-Athena-Client"] = finalClient;
40
+ }
41
+ if (typeof mergedStripNulls === "boolean") {
42
+ headers["X-Strip-Nulls"] = mergedStripNulls ? "true" : "false";
43
+ }
44
+ if (finalPublishEvent) {
45
+ headers["X-Publish-Event"] = finalPublishEvent;
46
+ }
47
+ if (finalApiKey) {
48
+ headers["apikey"] = finalApiKey;
49
+ headers["x-api-key"] = headers["x-api-key"] ?? finalApiKey;
50
+ }
51
+ if (finalSupabaseUrl) {
52
+ headers["x-supabase-url"] = finalSupabaseUrl;
53
+ }
54
+ if (finalSupabaseKey) {
55
+ headers["x-supabase-key"] = finalSupabaseKey;
56
+ }
57
+ Object.entries(extraHeaders).forEach(([key, value]) => {
58
+ const normalized = normalizeHeaderValue(value);
59
+ if (normalized) {
60
+ headers[key] = normalized;
61
+ }
62
+ });
63
+ return headers;
64
+ }
65
+ async function callAthena(config, endpoint, method, payload, options) {
66
+ const baseUrl = (options?.baseUrl ?? config.baseUrl ?? DEFAULT_BASE_URL).replace(/\/$/, "");
67
+ const url = `${baseUrl}${endpoint}`;
68
+ const headers = buildHeaders(config, options);
69
+ try {
70
+ const response = await fetch(url, {
71
+ method,
72
+ headers,
73
+ body: JSON.stringify(payload)
74
+ });
75
+ const rawText = await response.text();
76
+ const parsed = parseResponseText(rawText ?? "");
77
+ const parsedPayload = parsed;
78
+ const parsedError = parsedPayload && typeof parsedPayload === "object" ? parsedPayload.error ?? parsedPayload.message : void 0;
79
+ const hasError = typeof parsedError === "string" && parsedError.length > 0 ? parsedError : void 0;
80
+ return {
81
+ ok: response.ok,
82
+ status: response.status,
83
+ data: parsed ?? null,
84
+ error: hasError,
85
+ raw: parsed
86
+ };
87
+ } catch (callError) {
88
+ const message = callError instanceof Error ? callError.message : String(callError);
89
+ return {
90
+ ok: false,
91
+ status: 0,
92
+ data: null,
93
+ error: message,
94
+ raw: null
95
+ };
96
+ }
97
+ }
98
+ function createAthenaGatewayClient(config = {}) {
99
+ return {
100
+ baseUrl: (config.baseUrl ?? DEFAULT_BASE_URL).replace(/\/$/, ""),
101
+ buildHeaders(options) {
102
+ return buildHeaders(config, options);
103
+ },
104
+ fetchGateway(payload, options) {
105
+ return callAthena(config, "/gateway/fetch", "POST", payload, options);
106
+ },
107
+ insertGateway(payload, options) {
108
+ return callAthena(config, "/gateway/insert", "PUT", payload, options);
109
+ },
110
+ updateGateway(payload, options) {
111
+ return callAthena(config, "/gateway/update", "POST", payload, options);
112
+ },
113
+ deleteGateway(payload, options) {
114
+ return callAthena(config, "/gateway/delete", "DELETE", payload, options);
115
+ }
116
+ };
117
+ }
118
+
119
+ // src/supabase.ts
120
+ function formatResult(response) {
121
+ return {
122
+ data: response.data ?? null,
123
+ error: response.error ?? null,
124
+ status: response.status,
125
+ raw: response.raw
126
+ };
127
+ }
128
+ function ensureConditionValue(value) {
129
+ return value;
130
+ }
131
+ function buildCondition(column, value) {
132
+ return {
133
+ eq_column: column,
134
+ eq_value: ensureConditionValue(value)
135
+ };
136
+ }
137
+ function getResourceId(state) {
138
+ const candidate = state.conditions.find(
139
+ (condition) => condition.eq_column === "resource_id" || condition.eq_column === "id"
140
+ );
141
+ return candidate?.eq_value?.toString();
142
+ }
143
+ function createTableBuilder(tableName, client) {
144
+ const state = {
145
+ conditions: []
146
+ };
147
+ const builder = {
148
+ reset() {
149
+ state.conditions = [];
150
+ state.limit = void 0;
151
+ state.offset = void 0;
152
+ return builder;
153
+ },
154
+ limit(count) {
155
+ state.limit = count;
156
+ return builder;
157
+ },
158
+ offset(count) {
159
+ state.offset = count;
160
+ return builder;
161
+ },
162
+ match(filters) {
163
+ Object.entries(filters).forEach(([column, value]) => {
164
+ state.conditions.push(buildCondition(column, value));
165
+ });
166
+ return builder;
167
+ },
168
+ eq(column, value) {
169
+ state.conditions.push(buildCondition(column, value));
170
+ return builder;
171
+ },
172
+ async select(columns = "*", options) {
173
+ const payload = {
174
+ table_name: tableName,
175
+ columns,
176
+ conditions: state.conditions.length ? [...state.conditions] : void 0,
177
+ limit: state.limit,
178
+ offset: state.offset,
179
+ strip_nulls: options?.stripNulls ?? true
180
+ };
181
+ const response = await client.fetchGateway(payload, options);
182
+ return formatResult(response);
183
+ },
184
+ async insert(values, options) {
185
+ const response = await client.insertGateway(
186
+ {
187
+ table_name: tableName,
188
+ insert_body: values
189
+ },
190
+ options
191
+ );
192
+ return formatResult(response);
193
+ },
194
+ async update(values, options) {
195
+ const payload = {
196
+ table_name: tableName,
197
+ update_body: values,
198
+ conditions: state.conditions.length ? [...state.conditions] : void 0,
199
+ strip_nulls: options?.stripNulls ?? true
200
+ };
201
+ const response = await client.updateGateway(payload, options);
202
+ return formatResult(response);
203
+ },
204
+ async delete(options) {
205
+ const resourceId = options?.resourceId ?? getResourceId(state);
206
+ if (!resourceId) {
207
+ throw new Error('delete requires a resource_id either via eq("resource_id", ...) or options.resourceId');
208
+ }
209
+ const response = await client.deleteGateway(
210
+ {
211
+ table_name: tableName,
212
+ resource_id: resourceId
213
+ },
214
+ options
215
+ );
216
+ return formatResult(response);
217
+ },
218
+ async single(columns, options) {
219
+ const response = await builder.select(columns, options);
220
+ const rows = Array.isArray(response.data) ? response.data : response.data ? [response.data] : [];
221
+ return {
222
+ ...response,
223
+ data: rows[0] ?? null
224
+ };
225
+ },
226
+ async maybeSingle(columns, options) {
227
+ return builder.single(columns ?? "*", options);
228
+ }
229
+ };
230
+ return builder;
231
+ }
232
+ function createClient(url, apiKey, options) {
233
+ const { baseUrl: optBaseUrl, apiKey: optApiKey, ...restOptions } = options ?? {};
234
+ const client = createAthenaGatewayClient({
235
+ baseUrl: optBaseUrl ?? url,
236
+ apiKey: optApiKey ?? apiKey,
237
+ ...restOptions
238
+ });
239
+ return {
240
+ from(table) {
241
+ return createTableBuilder(table, client);
242
+ }
243
+ };
244
+ }
245
+
246
+ export { createClient };
247
+ //# sourceMappingURL=index.mjs.map
248
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/gateway/client.ts","../src/supabase.ts"],"names":[],"mappings":";AAcA,IAAM,gBAAA,GAAmB,uBAAA;AACzB,IAAM,cAAA,GAAiB,gBAAA;AAEvB,SAAS,kBAAkB,IAAA,EAAc;AACvC,EAAA,IAAI,CAAC,MAAM,OAAO,IAAA;AAClB,EAAA,IAAI;AACF,IAAA,OAAO,IAAA,CAAK,MAAM,IAAI,CAAA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,EACA,MAAA,EACA,OAAA,EACgB;AAChB,EAAA,MAAM,EAAE,SAAS,UAAA,EAAY,MAAA,EAAQ,WAAW,GAAG,WAAA,EAAY,GAAI,OAAA,IAAW,EAAC;AAC/E,EAAA,MAAM,SAAS,yBAAA,CAA0B;AAAA,IACvC,SAAS,UAAA,IAAc,GAAA;AAAA,IACvB,QAAQ,SAAA,IAAa,MAAA;AAAA,IACrB,GAAG;AAAA,GACJ,CAAA;AAED,EAAA,OAAO;AAAA,IACL,KAAoB,KAAA,EAAe;AACjC,MAAA,OAAO,kBAAA,CAAwB,OAAO,MAAM,CAAA;AAAA,IAC9C;AAAA,GACF;AACF","file":"index.mjs","sourcesContent":["import type {\r\n AthenaGatewayBaseOptions,\r\n AthenaGatewayCallOptions,\r\n AthenaGatewayEndpointPath,\r\n AthenaGatewayMethod,\r\n AthenaGatewayResponse,\r\n} from './types.js'\r\nimport type {\r\n AthenaDeletePayload,\r\n AthenaFetchPayload,\r\n AthenaInsertPayload,\r\n AthenaUpdatePayload,\r\n} from './types.js'\r\n\r\nconst DEFAULT_BASE_URL = 'https://athena-db.com'\r\nconst DEFAULT_CLIENT = 'railway_direct'\r\n\r\nfunction parseResponseText(text: string) {\r\n if (!text) return null\r\n try {\r\n return JSON.parse(text)\r\n } catch {\r\n return text\r\n }\r\n}\r\n\r\nfunction normalizeHeaderValue(value?: string | null) {\r\n return value ? value : undefined\r\n}\r\n\r\nfunction buildHeaders(\r\n config: AthenaGatewayBaseOptions,\r\n options?: AthenaGatewayCallOptions,\r\n): Record<string, string> {\r\n const mergedStripNulls = options?.stripNulls ?? config.stripNulls ?? true\r\n const finalClient = options?.client ?? config.client ?? DEFAULT_CLIENT\r\n const finalApiKey = options?.apiKey ?? config.apiKey\r\n const finalSupabaseUrl = options?.supabaseUrl ?? config.supabaseUrl\r\n const finalSupabaseKey = options?.supabaseKey ?? config.supabaseKey\r\n const finalPublishEvent = options?.publishEvent ?? config.publishEvent\r\n const extraHeaders = {\r\n ...(config.headers ?? {}),\r\n ...(options?.headers ?? {}),\r\n }\r\n\r\n const headers: Record<string, string> = {\r\n 'Content-Type': 'application/json',\r\n }\r\n\r\n if (options?.userId ?? config.userId) {\r\n headers['X-User-Id'] = options?.userId ?? config.userId ?? ''\r\n }\r\n\r\n if (options?.companyId ?? config.companyId) {\r\n headers['X-Company-Id'] = options?.companyId ?? config.companyId ?? ''\r\n }\r\n\r\n if (options?.organizationId ?? config.organizationId) {\r\n headers['X-Organization-Id'] = options?.organizationId ?? config.organizationId ?? ''\r\n }\r\n\r\n if (finalClient) {\r\n headers['X-Athena-Client'] = finalClient\r\n }\r\n\r\n if (typeof mergedStripNulls === 'boolean') {\r\n headers['X-Strip-Nulls'] = mergedStripNulls ? 'true' : 'false'\r\n }\r\n\r\n if (finalPublishEvent) {\r\n headers['X-Publish-Event'] = finalPublishEvent\r\n }\r\n\r\n if (finalApiKey) {\r\n headers['apikey'] = finalApiKey\r\n headers['x-api-key'] = headers['x-api-key'] ?? finalApiKey\r\n }\r\n\r\n if (finalSupabaseUrl) {\r\n headers['x-supabase-url'] = finalSupabaseUrl\r\n }\r\n\r\n if (finalSupabaseKey) {\r\n headers['x-supabase-key'] = finalSupabaseKey\r\n }\r\n\r\n Object.entries(extraHeaders).forEach(([key, value]) => {\r\n const normalized = normalizeHeaderValue(value)\r\n if (normalized) {\r\n headers[key] = normalized\r\n }\r\n })\r\n\r\n return headers\r\n}\r\n\r\nasync function callAthena<T>(\r\n config: AthenaGatewayBaseOptions,\r\n endpoint: AthenaGatewayEndpointPath,\r\n method: AthenaGatewayMethod,\r\n payload: unknown,\r\n options?: AthenaGatewayCallOptions,\r\n): Promise<AthenaGatewayResponse<T>> {\r\n const baseUrl = (options?.baseUrl ?? config.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/$/, '')\r\n const url = `${baseUrl}${endpoint}`\r\n const headers = buildHeaders(config, options)\r\n\r\n try {\r\n const response = await fetch(url, {\r\n method,\r\n headers,\r\n body: JSON.stringify(payload),\r\n })\r\n\r\n const rawText = await response.text()\r\n const parsed = parseResponseText(rawText ?? '')\r\n const parsedPayload = parsed as Record<string, unknown> | null\r\n const parsedError =\r\n parsedPayload && typeof parsedPayload === 'object'\r\n ? ((parsedPayload.error as string | undefined) ?? (parsedPayload.message as string | undefined))\r\n : undefined\r\n const hasError = typeof parsedError === 'string' && parsedError.length > 0 ? parsedError : undefined\r\n\r\n return {\r\n ok: response.ok,\r\n status: response.status,\r\n data: (parsed as T) ?? null,\r\n error: hasError,\r\n raw: parsed,\r\n }\r\n } catch (callError) {\r\n const message = callError instanceof Error ? callError.message : String(callError)\r\n return {\r\n ok: false,\r\n status: 0,\r\n data: null,\r\n error: message,\r\n raw: null,\r\n }\r\n }\r\n}\r\n\r\nexport interface AthenaGatewayClient {\r\n baseUrl: string\r\n buildHeaders(options?: AthenaGatewayCallOptions): Record<string, string>\r\n fetchGateway<T>(payload: AthenaFetchPayload, options?: AthenaGatewayCallOptions): Promise<AthenaGatewayResponse<T>>\r\n insertGateway<T>(payload: AthenaInsertPayload, options?: AthenaGatewayCallOptions): Promise<AthenaGatewayResponse<T>>\r\n updateGateway<T>(payload: AthenaUpdatePayload, options?: AthenaGatewayCallOptions): Promise<AthenaGatewayResponse<T>>\r\n deleteGateway<T>(payload: AthenaDeletePayload, options?: AthenaGatewayCallOptions): Promise<AthenaGatewayResponse<T>>\r\n}\r\n\r\nexport function createAthenaGatewayClient(config: AthenaGatewayBaseOptions = {}): AthenaGatewayClient {\r\n return {\r\n baseUrl: (config.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/$/, ''),\r\n buildHeaders(options) {\r\n return buildHeaders(config, options)\r\n },\r\n fetchGateway(payload, options) {\r\n return callAthena(config, '/gateway/fetch', 'POST', payload, options)\r\n },\r\n insertGateway(payload, options) {\r\n return callAthena(config, '/gateway/insert', 'PUT', payload, options)\r\n },\r\n updateGateway(payload, options) {\r\n return callAthena(config, '/gateway/update', 'POST', payload, options)\r\n },\r\n deleteGateway(payload, options) {\r\n return callAthena(config, '/gateway/delete', 'DELETE', payload, options)\r\n },\r\n }\r\n}\r\n","import type {\r\n AthenaGatewayCallOptions,\r\n AthenaGatewayCondition,\r\n AthenaGatewayResponse,\r\n} from './gateway/types.js'\r\nimport { createAthenaGatewayClient } from './gateway/client.js'\r\n\r\ntype AthenaConditionValue = string | number | boolean | null\r\n\r\nexport interface SupabaseResult<T> {\r\n data: T | null\r\n error: string | null\r\n status: number\r\n raw: unknown\r\n}\r\n\r\ntype TableBuilderState = {\r\n conditions: AthenaGatewayCondition[]\r\n limit?: number\r\n offset?: number\r\n}\r\n\r\nfunction formatResult<T>(response: AthenaGatewayResponse<T>): SupabaseResult<T> {\r\n return {\r\n data: response.data ?? null,\r\n error: response.error ?? null,\r\n status: response.status,\r\n raw: response.raw,\r\n }\r\n}\r\n\r\nfunction ensureConditionValue(value: AthenaConditionValue): AthenaConditionValue {\r\n return value\r\n}\r\n\r\nfunction buildCondition(column: string, value: AthenaConditionValue): AthenaGatewayCondition {\r\n return {\r\n eq_column: column,\r\n eq_value: ensureConditionValue(value),\r\n }\r\n}\r\n\r\nexport interface TableQueryBuilder<Row> {\r\n select<T = Row>(columns?: string | string[], options?: AthenaGatewayCallOptions): Promise<SupabaseResult<T>>\r\n insert(values: Row | Row[], options?: AthenaGatewayCallOptions): Promise<SupabaseResult<Row | Row[]>>\r\n update(values: Partial<Row>, options?: AthenaGatewayCallOptions): Promise<SupabaseResult<Row[]>>\r\n delete(options?: AthenaGatewayCallOptions & { resourceId?: string }): Promise<SupabaseResult<null>>\r\n eq(column: string, value: AthenaConditionValue): TableQueryBuilder<Row>\r\n match(filters: Record<string, AthenaConditionValue>): TableQueryBuilder<Row>\r\n limit(count: number): TableQueryBuilder<Row>\r\n offset(count: number): TableQueryBuilder<Row>\r\n single<T = Row>(columns?: string | string[], options?: AthenaGatewayCallOptions): Promise<SupabaseResult<T | null>>\r\n maybeSingle<T = Row>(columns?: string | string[], options?: AthenaGatewayCallOptions): Promise<SupabaseResult<T | null>>\r\n reset(): TableQueryBuilder<Row>\r\n}\r\n\r\nfunction getResourceId(state: TableBuilderState): string | undefined {\r\n const candidate = state.conditions.find(\r\n condition => condition.eq_column === 'resource_id' || condition.eq_column === 'id',\r\n )\r\n return candidate?.eq_value?.toString()\r\n}\r\n\r\nfunction createTableBuilder<Row>(\r\n tableName: string,\r\n client: ReturnType<typeof createAthenaGatewayClient>,\r\n): TableQueryBuilder<Row> {\r\n const state: TableBuilderState = {\r\n conditions: [],\r\n }\r\n\r\n const builder: TableQueryBuilder<Row> = {\r\n reset() {\r\n state.conditions = []\r\n state.limit = undefined\r\n state.offset = undefined\r\n return builder\r\n },\r\n limit(count: number) {\r\n state.limit = count\r\n return builder\r\n },\r\n offset(count: number) {\r\n state.offset = count\r\n return builder\r\n },\r\n match(filters: Record<string, AthenaConditionValue>) {\r\n Object.entries(filters).forEach(([column, value]) => {\r\n state.conditions.push(buildCondition(column, value))\r\n })\r\n return builder\r\n },\r\n eq(column: string, value: AthenaConditionValue) {\r\n state.conditions.push(buildCondition(column, value))\r\n return builder\r\n },\r\n async select<T = Row>(columns: string | string[] = '*', options?: AthenaGatewayCallOptions) {\r\n const payload = {\r\n table_name: tableName,\r\n columns,\r\n conditions: state.conditions.length ? [...state.conditions] : undefined,\r\n limit: state.limit,\r\n offset: state.offset,\r\n strip_nulls: options?.stripNulls ?? true,\r\n }\r\n const response = await client.fetchGateway<T>(payload, options)\r\n return formatResult(response)\r\n },\r\n async insert(values: Row | Row[], options?: AthenaGatewayCallOptions) {\r\n const response = await client.insertGateway<Row | Row[]>(\r\n {\r\n table_name: tableName,\r\n insert_body: values as Record<string, unknown>,\r\n },\r\n options,\r\n )\r\n return formatResult(response)\r\n },\r\n async update(values: Partial<Row>, options?: AthenaGatewayCallOptions) {\r\n const payload = {\r\n table_name: tableName,\r\n update_body: values,\r\n conditions: state.conditions.length ? [...state.conditions] : undefined,\r\n strip_nulls: options?.stripNulls ?? true,\r\n }\r\n const response = await client.updateGateway<Row[]>(payload, options)\r\n return formatResult(response)\r\n },\r\n async delete(options?: AthenaGatewayCallOptions & { resourceId?: string }) {\r\n const resourceId = options?.resourceId ?? getResourceId(state)\r\n if (!resourceId) {\r\n throw new Error('delete requires a resource_id either via eq(\"resource_id\", ...) or options.resourceId')\r\n }\r\n const response = await client.deleteGateway<null>(\r\n {\r\n table_name: tableName,\r\n resource_id: resourceId,\r\n },\r\n options,\r\n )\r\n return formatResult(response)\r\n },\r\n async single<T = Row>(columns?: string | string[], options?: AthenaGatewayCallOptions) {\r\n const response = await builder.select<T[]>(columns, options)\r\n const rows = Array.isArray(response.data) ? response.data : response.data ? [response.data] : []\r\n return {\r\n ...response,\r\n data: (rows[0] ?? null) as unknown as T | null,\r\n }\r\n },\r\n async maybeSingle<T = Row>(columns?: string | string[], options?: AthenaGatewayCallOptions) {\r\n return builder.single<T | null>(columns ?? '*', options)\r\n },\r\n }\r\n\r\n return builder\r\n}\r\n\r\nexport interface SupabaseClient {\r\n from<Row = unknown>(table: string): TableQueryBuilder<Row>\r\n}\r\n\r\nexport function createClient(\r\n url: string,\r\n apiKey: string,\r\n options?: AthenaGatewayCallOptions,\r\n): SupabaseClient {\r\n const { baseUrl: optBaseUrl, apiKey: optApiKey, ...restOptions } = options ?? {}\r\n const client = createAthenaGatewayClient({\r\n baseUrl: optBaseUrl ?? url,\r\n apiKey: optApiKey ?? apiKey,\r\n ...restOptions,\r\n })\r\n\r\n return {\r\n from<Row = unknown>(table: string) {\r\n return createTableBuilder<Row>(table, client)\r\n },\r\n }\r\n}\r\n"]}
@@ -0,0 +1,6 @@
1
+ import { g as AthenaGatewayHookConfig, h as AthenaGatewayHookResult } from './types-DFvltfTX.mjs';
2
+ export { a as AthenaDeletePayload, b as AthenaFetchPayload, c as AthenaGatewayBaseOptions, d as AthenaGatewayCallLog, A as AthenaGatewayCallOptions, e as AthenaGatewayCondition, f as AthenaGatewayEndpointPath, i as AthenaGatewayMethod, j as AthenaGatewayResponse, k as AthenaGatewayResponseLog, l as AthenaInsertPayload, m as AthenaUpdatePayload } from './types-DFvltfTX.mjs';
3
+
4
+ declare function useAthenaGateway(config?: AthenaGatewayHookConfig): AthenaGatewayHookResult;
5
+
6
+ export { AthenaGatewayHookConfig, AthenaGatewayHookResult, useAthenaGateway };
@@ -0,0 +1,6 @@
1
+ import { g as AthenaGatewayHookConfig, h as AthenaGatewayHookResult } from './types-DFvltfTX.js';
2
+ export { a as AthenaDeletePayload, b as AthenaFetchPayload, c as AthenaGatewayBaseOptions, d as AthenaGatewayCallLog, A as AthenaGatewayCallOptions, e as AthenaGatewayCondition, f as AthenaGatewayEndpointPath, i as AthenaGatewayMethod, j as AthenaGatewayResponse, k as AthenaGatewayResponseLog, l as AthenaInsertPayload, m as AthenaUpdatePayload } from './types-DFvltfTX.js';
3
+
4
+ declare function useAthenaGateway(config?: AthenaGatewayHookConfig): AthenaGatewayHookResult;
5
+
6
+ export { AthenaGatewayHookConfig, AthenaGatewayHookResult, useAthenaGateway };
package/dist/react.js ADDED
@@ -0,0 +1,281 @@
1
+ 'use strict';
2
+
3
+ var react = require('react');
4
+
5
+ // src/gateway/use-athena-gateway.ts
6
+
7
+ // src/gateway/client.ts
8
+ var DEFAULT_BASE_URL = "https://athena-db.com";
9
+ var DEFAULT_CLIENT = "railway_direct";
10
+ function parseResponseText(text) {
11
+ if (!text) return null;
12
+ try {
13
+ return JSON.parse(text);
14
+ } catch {
15
+ return text;
16
+ }
17
+ }
18
+ function normalizeHeaderValue(value) {
19
+ return value ? value : void 0;
20
+ }
21
+ function buildHeaders(config, options) {
22
+ const mergedStripNulls = options?.stripNulls ?? config.stripNulls ?? true;
23
+ const finalClient = options?.client ?? config.client ?? DEFAULT_CLIENT;
24
+ const finalApiKey = options?.apiKey ?? config.apiKey;
25
+ const finalSupabaseUrl = options?.supabaseUrl ?? config.supabaseUrl;
26
+ const finalSupabaseKey = options?.supabaseKey ?? config.supabaseKey;
27
+ const finalPublishEvent = options?.publishEvent ?? config.publishEvent;
28
+ const extraHeaders = {
29
+ ...config.headers ?? {},
30
+ ...options?.headers ?? {}
31
+ };
32
+ const headers = {
33
+ "Content-Type": "application/json"
34
+ };
35
+ if (options?.userId ?? config.userId) {
36
+ headers["X-User-Id"] = options?.userId ?? config.userId ?? "";
37
+ }
38
+ if (options?.companyId ?? config.companyId) {
39
+ headers["X-Company-Id"] = options?.companyId ?? config.companyId ?? "";
40
+ }
41
+ if (options?.organizationId ?? config.organizationId) {
42
+ headers["X-Organization-Id"] = options?.organizationId ?? config.organizationId ?? "";
43
+ }
44
+ if (finalClient) {
45
+ headers["X-Athena-Client"] = finalClient;
46
+ }
47
+ if (typeof mergedStripNulls === "boolean") {
48
+ headers["X-Strip-Nulls"] = mergedStripNulls ? "true" : "false";
49
+ }
50
+ if (finalPublishEvent) {
51
+ headers["X-Publish-Event"] = finalPublishEvent;
52
+ }
53
+ if (finalApiKey) {
54
+ headers["apikey"] = finalApiKey;
55
+ headers["x-api-key"] = headers["x-api-key"] ?? finalApiKey;
56
+ }
57
+ if (finalSupabaseUrl) {
58
+ headers["x-supabase-url"] = finalSupabaseUrl;
59
+ }
60
+ if (finalSupabaseKey) {
61
+ headers["x-supabase-key"] = finalSupabaseKey;
62
+ }
63
+ Object.entries(extraHeaders).forEach(([key, value]) => {
64
+ const normalized = normalizeHeaderValue(value);
65
+ if (normalized) {
66
+ headers[key] = normalized;
67
+ }
68
+ });
69
+ return headers;
70
+ }
71
+ async function callAthena(config, endpoint, method, payload, options) {
72
+ const baseUrl = (options?.baseUrl ?? config.baseUrl ?? DEFAULT_BASE_URL).replace(/\/$/, "");
73
+ const url = `${baseUrl}${endpoint}`;
74
+ const headers = buildHeaders(config, options);
75
+ try {
76
+ const response = await fetch(url, {
77
+ method,
78
+ headers,
79
+ body: JSON.stringify(payload)
80
+ });
81
+ const rawText = await response.text();
82
+ const parsed = parseResponseText(rawText ?? "");
83
+ const parsedPayload = parsed;
84
+ const parsedError = parsedPayload && typeof parsedPayload === "object" ? parsedPayload.error ?? parsedPayload.message : void 0;
85
+ const hasError = typeof parsedError === "string" && parsedError.length > 0 ? parsedError : void 0;
86
+ return {
87
+ ok: response.ok,
88
+ status: response.status,
89
+ data: parsed ?? null,
90
+ error: hasError,
91
+ raw: parsed
92
+ };
93
+ } catch (callError) {
94
+ const message = callError instanceof Error ? callError.message : String(callError);
95
+ return {
96
+ ok: false,
97
+ status: 0,
98
+ data: null,
99
+ error: message,
100
+ raw: null
101
+ };
102
+ }
103
+ }
104
+ function createAthenaGatewayClient(config = {}) {
105
+ return {
106
+ baseUrl: (config.baseUrl ?? DEFAULT_BASE_URL).replace(/\/$/, ""),
107
+ buildHeaders(options) {
108
+ return buildHeaders(config, options);
109
+ },
110
+ fetchGateway(payload, options) {
111
+ return callAthena(config, "/gateway/fetch", "POST", payload, options);
112
+ },
113
+ insertGateway(payload, options) {
114
+ return callAthena(config, "/gateway/insert", "PUT", payload, options);
115
+ },
116
+ updateGateway(payload, options) {
117
+ return callAthena(config, "/gateway/update", "POST", payload, options);
118
+ },
119
+ deleteGateway(payload, options) {
120
+ return callAthena(config, "/gateway/delete", "DELETE", payload, options);
121
+ }
122
+ };
123
+ }
124
+
125
+ // src/gateway/use-athena-gateway.ts
126
+ function useAthenaGateway(config) {
127
+ const [isLoading, setIsLoading] = react.useState(false);
128
+ const [error, setError] = react.useState(null);
129
+ const [lastRequest, setLastRequest] = react.useState(
130
+ null
131
+ );
132
+ const [lastResponse, setLastResponse] = react.useState(null);
133
+ const client = react.useMemo(
134
+ () => createAthenaGatewayClient({
135
+ client: config?.client,
136
+ baseUrl: config?.baseUrl,
137
+ apiKey: config?.apiKey,
138
+ supabaseUrl: config?.supabaseUrl,
139
+ supabaseKey: config?.supabaseKey,
140
+ publishEvent: config?.publishEvent,
141
+ stripNulls: config?.stripNulls,
142
+ headers: config?.headers,
143
+ userId: config?.userId,
144
+ companyId: config?.companyId,
145
+ organizationId: config?.organizationId
146
+ }),
147
+ [
148
+ config?.baseUrl,
149
+ config?.client,
150
+ config?.apiKey,
151
+ config?.supabaseUrl,
152
+ config?.supabaseKey,
153
+ config?.publishEvent,
154
+ config?.stripNulls,
155
+ config?.headers,
156
+ config?.userId,
157
+ config?.companyId,
158
+ config?.organizationId
159
+ ]
160
+ );
161
+ const callWithLifecycle = react.useCallback(
162
+ async (fn, metadata) => {
163
+ const requestLog = {
164
+ endpoint: metadata.endpoint,
165
+ method: metadata.method,
166
+ payload: metadata.payload,
167
+ headers: client.buildHeaders(metadata.options),
168
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
169
+ };
170
+ setLastRequest(requestLog);
171
+ setIsLoading(true);
172
+ setError(null);
173
+ let response;
174
+ try {
175
+ response = await fn();
176
+ setLastResponse({ ...response, timestamp: (/* @__PURE__ */ new Date()).toISOString() });
177
+ if (!response.ok) {
178
+ const message = response.error || `Athena gateway ${metadata.method} ${metadata.endpoint} failed`;
179
+ setError(message);
180
+ throw new Error(message);
181
+ }
182
+ return response;
183
+ } catch (callError) {
184
+ const message = callError instanceof Error ? callError.message : String(callError);
185
+ setError(message);
186
+ setLastResponse({
187
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
188
+ status: response?.status ?? 0,
189
+ ok: false,
190
+ data: null,
191
+ raw: null,
192
+ error: message
193
+ });
194
+ throw callError;
195
+ } finally {
196
+ setIsLoading(false);
197
+ }
198
+ },
199
+ [client]
200
+ );
201
+ const normalizedConfigStripNulls = react.useMemo(
202
+ () => config?.stripNulls ?? true,
203
+ [config?.stripNulls]
204
+ );
205
+ const fetchGateway = react.useCallback(
206
+ (payload, options) => {
207
+ const normalizedPayload = {
208
+ ...payload,
209
+ conditions: payload.conditions ?? [],
210
+ strip_nulls: payload.strip_nulls ?? options?.stripNulls ?? normalizedConfigStripNulls
211
+ };
212
+ return callWithLifecycle(
213
+ () => client.fetchGateway(normalizedPayload, options),
214
+ {
215
+ endpoint: "/gateway/fetch",
216
+ method: "POST",
217
+ payload: normalizedPayload,
218
+ options
219
+ }
220
+ );
221
+ },
222
+ [callWithLifecycle, client, normalizedConfigStripNulls]
223
+ );
224
+ const insertGateway = react.useCallback(
225
+ (payload, options) => callWithLifecycle(() => client.insertGateway(payload, options), {
226
+ endpoint: "/gateway/insert",
227
+ method: "PUT",
228
+ payload,
229
+ options
230
+ }),
231
+ [callWithLifecycle, client]
232
+ );
233
+ const updateGateway = react.useCallback(
234
+ (payload, options) => {
235
+ const normalizedPayload = {
236
+ ...payload,
237
+ conditions: payload.conditions ?? [],
238
+ strip_nulls: payload.strip_nulls ?? options?.stripNulls ?? normalizedConfigStripNulls
239
+ };
240
+ return callWithLifecycle(
241
+ () => client.updateGateway(normalizedPayload, options),
242
+ {
243
+ endpoint: "/gateway/update",
244
+ method: "POST",
245
+ payload: normalizedPayload,
246
+ options
247
+ }
248
+ );
249
+ },
250
+ [callWithLifecycle, client, normalizedConfigStripNulls]
251
+ );
252
+ const deleteGateway = react.useCallback(
253
+ (payload, options) => {
254
+ if (!payload.resource_id) {
255
+ throw new Error(
256
+ "deleteGateway requires resource_id (the unique identifier of the record to delete)"
257
+ );
258
+ }
259
+ return callWithLifecycle(
260
+ () => client.deleteGateway(payload, options),
261
+ { endpoint: "/gateway/delete", method: "DELETE", payload, options }
262
+ );
263
+ },
264
+ [callWithLifecycle, client]
265
+ );
266
+ return {
267
+ fetchGateway,
268
+ insertGateway,
269
+ updateGateway,
270
+ deleteGateway,
271
+ isLoading,
272
+ error,
273
+ lastRequest,
274
+ lastResponse,
275
+ baseUrl: client.baseUrl
276
+ };
277
+ }
278
+
279
+ exports.useAthenaGateway = useAthenaGateway;
280
+ //# sourceMappingURL=react.js.map
281
+ //# sourceMappingURL=react.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/gateway/client.ts","../src/gateway/use-athena-gateway.ts"],"names":["useState","useMemo","useCallback"],"mappings":";;;;;;;AAcA,IAAM,gBAAA,GAAmB,uBAAA;AACzB,IAAM,cAAA,GAAiB,gBAAA;AAEvB,SAAS,kBAAkB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AAY,OAAA,CAAQ,UAAA,IAAc,EAAC;AAAA,QACnC,WAAA,EACE,OAAA,CAAQ,WAAA,IACR,OAAA,EAAS,UAAA,IACT;AAAA,OACJ;AACA,MAAA,OAAO,iBAAA;AAAA,QACL,MAAM,MAAA,CAAO,aAAA,CAAiB,iBAAA,EAAmB,OAAO,CAAA;AAAA,QACxD;AAAA,UACE,QAAA,EAAU,iBAAA;AAAA,UACV,MAAA,EAAQ,MAAA;AAAA,UACR,OAAA,EAAS,iBAAA;AAAA,UACT;AAAA;AACF,OACF;AAAA,IACF,CAAA;AAAA,IACA,CAAC,iBAAA,EAAmB,MAAA,EAAQ,0BAA0B;AAAA,GACxD;AAEA,EAAA,MAAM,aAAA,GAAgBA,iBAAA;AAAA,IACpB,CACE,SACA,OAAA,KACG;AACH,MAAA,IAAI,CAAC,QAAQ,WAAA,EAAa;AACxB,QAAA,MAAM,IAAI,KAAA;AAAA,UACR;AAAA,SACF;AAAA,MACF;AACA,MAAA,OAAO,iBAAA;AAAA,QACL,MAAM,MAAA,CAAO,aAAA,CAAiB,OAAA,EAAS,OAAO,CAAA;AAAA,QAC9C,EAAE,QAAA,EAAU,iBAAA,EAAmB,MAAA,EAAQ,QAAA,EAAU,SAAS,OAAA;AAAQ,OACpE;AAAA,IACF,CAAA;AAAA,IACA,CAAC,mBAAmB,MAAM;AAAA,GAC5B;AAEA,EAAA,OAAO;AAAA,IACL,YAAA;AAAA,IACA,aAAA;AAAA,IACA,aAAA;AAAA,IACA,aAAA;AAAA,IACA,SAAA;AAAA,IACA,KAAA;AAAA,IACA,WAAA;AAAA,IACA,YAAA;AAAA,IACA,SAAS,MAAA,CAAO;AAAA,GAClB;AACF","file":"react.js","sourcesContent":["import type {\r\n AthenaGatewayBaseOptions,\r\n AthenaGatewayCallOptions,\r\n AthenaGatewayEndpointPath,\r\n AthenaGatewayMethod,\r\n AthenaGatewayResponse,\r\n} from './types.js'\r\nimport type {\r\n AthenaDeletePayload,\r\n AthenaFetchPayload,\r\n AthenaInsertPayload,\r\n AthenaUpdatePayload,\r\n} from './types.js'\r\n\r\nconst DEFAULT_BASE_URL = 'https://athena-db.com'\r\nconst DEFAULT_CLIENT = 'railway_direct'\r\n\r\nfunction parseResponseText(text: string) {\r\n if (!text) return null\r\n try {\r\n return JSON.parse(text)\r\n } catch {\r\n return text\r\n }\r\n}\r\n\r\nfunction normalizeHeaderValue(value?: string | null) {\r\n return value ? value : undefined\r\n}\r\n\r\nfunction buildHeaders(\r\n config: AthenaGatewayBaseOptions,\r\n options?: AthenaGatewayCallOptions,\r\n): Record<string, string> {\r\n const mergedStripNulls = options?.stripNulls ?? config.stripNulls ?? true\r\n const finalClient = options?.client ?? config.client ?? DEFAULT_CLIENT\r\n const finalApiKey = options?.apiKey ?? config.apiKey\r\n const finalSupabaseUrl = options?.supabaseUrl ?? config.supabaseUrl\r\n const finalSupabaseKey = options?.supabaseKey ?? config.supabaseKey\r\n const finalPublishEvent = options?.publishEvent ?? config.publishEvent\r\n const extraHeaders = {\r\n ...(config.headers ?? {}),\r\n ...(options?.headers ?? {}),\r\n }\r\n\r\n const headers: Record<string, string> = {\r\n 'Content-Type': 'application/json',\r\n }\r\n\r\n if (options?.userId ?? config.userId) {\r\n headers['X-User-Id'] = options?.userId ?? config.userId ?? ''\r\n }\r\n\r\n if (options?.companyId ?? config.companyId) {\r\n headers['X-Company-Id'] = options?.companyId ?? config.companyId ?? ''\r\n }\r\n\r\n if (options?.organizationId ?? config.organizationId) {\r\n headers['X-Organization-Id'] = options?.organizationId ?? config.organizationId ?? ''\r\n }\r\n\r\n if (finalClient) {\r\n headers['X-Athena-Client'] = finalClient\r\n }\r\n\r\n if (typeof mergedStripNulls === 'boolean') {\r\n headers['X-Strip-Nulls'] = mergedStripNulls ? 'true' : 'false'\r\n }\r\n\r\n if (finalPublishEvent) {\r\n headers['X-Publish-Event'] = finalPublishEvent\r\n }\r\n\r\n if (finalApiKey) {\r\n headers['apikey'] = finalApiKey\r\n headers['x-api-key'] = headers['x-api-key'] ?? finalApiKey\r\n }\r\n\r\n if (finalSupabaseUrl) {\r\n headers['x-supabase-url'] = finalSupabaseUrl\r\n }\r\n\r\n if (finalSupabaseKey) {\r\n headers['x-supabase-key'] = finalSupabaseKey\r\n }\r\n\r\n Object.entries(extraHeaders).forEach(([key, value]) => {\r\n const normalized = normalizeHeaderValue(value)\r\n if (normalized) {\r\n headers[key] = normalized\r\n }\r\n })\r\n\r\n return headers\r\n}\r\n\r\nasync function callAthena<T>(\r\n config: AthenaGatewayBaseOptions,\r\n endpoint: AthenaGatewayEndpointPath,\r\n method: AthenaGatewayMethod,\r\n payload: unknown,\r\n options?: AthenaGatewayCallOptions,\r\n): Promise<AthenaGatewayResponse<T>> {\r\n const baseUrl = (options?.baseUrl ?? config.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/$/, '')\r\n const url = `${baseUrl}${endpoint}`\r\n const headers = buildHeaders(config, options)\r\n\r\n try {\r\n const response = await fetch(url, {\r\n method,\r\n headers,\r\n body: JSON.stringify(payload),\r\n })\r\n\r\n const rawText = await response.text()\r\n const parsed = parseResponseText(rawText ?? '')\r\n const parsedPayload = parsed as Record<string, unknown> | null\r\n const parsedError =\r\n parsedPayload && typeof parsedPayload === 'object'\r\n ? ((parsedPayload.error as string | undefined) ?? (parsedPayload.message as string | undefined))\r\n : undefined\r\n const hasError = typeof parsedError === 'string' && parsedError.length > 0 ? parsedError : undefined\r\n\r\n return {\r\n ok: response.ok,\r\n status: response.status,\r\n data: (parsed as T) ?? null,\r\n error: hasError,\r\n raw: parsed,\r\n }\r\n } catch (callError) {\r\n const message = callError instanceof Error ? callError.message : String(callError)\r\n return {\r\n ok: false,\r\n status: 0,\r\n data: null,\r\n error: message,\r\n raw: null,\r\n }\r\n }\r\n}\r\n\r\nexport interface AthenaGatewayClient {\r\n baseUrl: string\r\n buildHeaders(options?: AthenaGatewayCallOptions): Record<string, string>\r\n fetchGateway<T>(payload: AthenaFetchPayload, options?: AthenaGatewayCallOptions): Promise<AthenaGatewayResponse<T>>\r\n insertGateway<T>(payload: AthenaInsertPayload, options?: AthenaGatewayCallOptions): Promise<AthenaGatewayResponse<T>>\r\n updateGateway<T>(payload: AthenaUpdatePayload, options?: AthenaGatewayCallOptions): Promise<AthenaGatewayResponse<T>>\r\n deleteGateway<T>(payload: AthenaDeletePayload, options?: AthenaGatewayCallOptions): Promise<AthenaGatewayResponse<T>>\r\n}\r\n\r\nexport function createAthenaGatewayClient(config: AthenaGatewayBaseOptions = {}): AthenaGatewayClient {\r\n return {\r\n baseUrl: (config.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/$/, ''),\r\n buildHeaders(options) {\r\n return buildHeaders(config, options)\r\n },\r\n fetchGateway(payload, options) {\r\n return callAthena(config, '/gateway/fetch', 'POST', payload, options)\r\n },\r\n insertGateway(payload, options) {\r\n return callAthena(config, '/gateway/insert', 'PUT', payload, options)\r\n },\r\n updateGateway(payload, options) {\r\n return callAthena(config, '/gateway/update', 'POST', payload, options)\r\n },\r\n deleteGateway(payload, options) {\r\n return callAthena(config, '/gateway/delete', 'DELETE', payload, options)\r\n },\r\n }\r\n}\r\n","import { useCallback, useMemo, useState } from \"react\";\r\nimport type {\r\n AthenaDeletePayload,\r\n AthenaFetchPayload,\r\n AthenaGatewayCallLog,\r\n AthenaGatewayCallOptions,\r\n AthenaGatewayHookConfig,\r\n AthenaGatewayHookResult,\r\n AthenaGatewayResponse,\r\n AthenaGatewayResponseLog,\r\n AthenaInsertPayload,\r\n AthenaUpdatePayload,\r\n} from \"./types.js\";\r\nimport { createAthenaGatewayClient } from \"./client.js\";\r\n\r\nexport function useAthenaGateway(\r\n config?: AthenaGatewayHookConfig,\r\n): AthenaGatewayHookResult {\r\n const [isLoading, setIsLoading] = useState(false);\r\n const [error, setError] = useState<string | null>(null);\r\n const [lastRequest, setLastRequest] = useState<AthenaGatewayCallLog | null>(\r\n null,\r\n );\r\n const [lastResponse, setLastResponse] =\r\n useState<AthenaGatewayResponseLog | null>(null);\r\n\r\n const client = useMemo(\r\n () =>\r\n createAthenaGatewayClient({\r\n client: config?.client,\r\n baseUrl: config?.baseUrl,\r\n apiKey: config?.apiKey,\r\n supabaseUrl: config?.supabaseUrl,\r\n supabaseKey: config?.supabaseKey,\r\n publishEvent: config?.publishEvent,\r\n stripNulls: config?.stripNulls,\r\n headers: config?.headers,\r\n userId: config?.userId,\r\n companyId: config?.companyId,\r\n organizationId: config?.organizationId,\r\n }),\r\n [\r\n config?.baseUrl,\r\n config?.client,\r\n config?.apiKey,\r\n config?.supabaseUrl,\r\n config?.supabaseKey,\r\n config?.publishEvent,\r\n config?.stripNulls,\r\n config?.headers,\r\n config?.userId,\r\n config?.companyId,\r\n config?.organizationId,\r\n ],\r\n );\r\n\r\n const callWithLifecycle = useCallback(\r\n async <T>(\r\n fn: () => Promise<AthenaGatewayResponse<T>>,\r\n metadata: {\r\n endpoint: string;\r\n method: string;\r\n payload: unknown;\r\n options?: AthenaGatewayCallOptions;\r\n },\r\n ): Promise<AthenaGatewayResponse<T>> => {\r\n const requestLog: AthenaGatewayCallLog = {\r\n endpoint: metadata.endpoint as any,\r\n method: metadata.method as any,\r\n payload: metadata.payload,\r\n headers: client.buildHeaders(metadata.options),\r\n timestamp: new Date().toISOString(),\r\n };\r\n\r\n setLastRequest(requestLog);\r\n setIsLoading(true);\r\n setError(null);\r\n\r\n let response: AthenaGatewayResponse<T> | undefined;\r\n try {\r\n response = await fn();\r\n setLastResponse({ ...response, timestamp: new Date().toISOString() });\r\n\r\n if (!response.ok) {\r\n const message =\r\n response.error ||\r\n `Athena gateway ${metadata.method} ${metadata.endpoint} failed`;\r\n setError(message);\r\n throw new Error(message);\r\n }\r\n\r\n return response;\r\n } catch (callError) {\r\n const message =\r\n callError instanceof Error ? callError.message : String(callError);\r\n setError(message);\r\n setLastResponse({\r\n timestamp: new Date().toISOString(),\r\n status: response?.status ?? 0,\r\n ok: false,\r\n data: null,\r\n raw: null,\r\n error: message,\r\n });\r\n throw callError;\r\n } finally {\r\n setIsLoading(false);\r\n }\r\n },\r\n [client],\r\n );\r\n\r\n const normalizedConfigStripNulls = useMemo(\r\n () => config?.stripNulls ?? true,\r\n [config?.stripNulls],\r\n );\r\n\r\n const fetchGateway = useCallback(\r\n <T = unknown>(\r\n payload: AthenaFetchPayload,\r\n options?: AthenaGatewayCallOptions,\r\n ) => {\r\n const normalizedPayload: AthenaFetchPayload = {\r\n ...payload,\r\n conditions: payload.conditions ?? [],\r\n strip_nulls:\r\n payload.strip_nulls ??\r\n options?.stripNulls ??\r\n normalizedConfigStripNulls,\r\n };\r\n return callWithLifecycle<T>(\r\n () => client.fetchGateway<T>(normalizedPayload, options),\r\n {\r\n endpoint: \"/gateway/fetch\",\r\n method: \"POST\",\r\n payload: normalizedPayload,\r\n options,\r\n },\r\n );\r\n },\r\n [callWithLifecycle, client, normalizedConfigStripNulls],\r\n );\r\n\r\n const insertGateway = useCallback(\r\n <T = unknown>(\r\n payload: AthenaInsertPayload,\r\n options?: AthenaGatewayCallOptions,\r\n ) =>\r\n callWithLifecycle<T>(() => client.insertGateway<T>(payload, options), {\r\n endpoint: \"/gateway/insert\",\r\n method: \"PUT\",\r\n payload,\r\n options,\r\n }),\r\n [callWithLifecycle, client],\r\n );\r\n\r\n const updateGateway = useCallback(\r\n <T = unknown>(\r\n payload: AthenaUpdatePayload,\r\n options?: AthenaGatewayCallOptions,\r\n ) => {\r\n const normalizedPayload: AthenaUpdatePayload = {\r\n ...payload,\r\n conditions: payload.conditions ?? [],\r\n strip_nulls:\r\n payload.strip_nulls ??\r\n options?.stripNulls ??\r\n normalizedConfigStripNulls,\r\n };\r\n return callWithLifecycle<T>(\r\n () => client.updateGateway<T>(normalizedPayload, options),\r\n {\r\n endpoint: \"/gateway/update\",\r\n method: \"POST\",\r\n payload: normalizedPayload,\r\n options,\r\n },\r\n );\r\n },\r\n [callWithLifecycle, client, normalizedConfigStripNulls],\r\n );\r\n\r\n const deleteGateway = useCallback(\r\n <T = unknown>(\r\n payload: AthenaDeletePayload,\r\n options?: AthenaGatewayCallOptions,\r\n ) => {\r\n if (!payload.resource_id) {\r\n throw new Error(\r\n \"deleteGateway requires resource_id (the unique identifier of the record to delete)\",\r\n );\r\n }\r\n return callWithLifecycle<T>(\r\n () => client.deleteGateway<T>(payload, options),\r\n { endpoint: \"/gateway/delete\", method: \"DELETE\", payload, options },\r\n );\r\n },\r\n [callWithLifecycle, client],\r\n );\r\n\r\n return {\r\n fetchGateway,\r\n insertGateway,\r\n updateGateway,\r\n deleteGateway,\r\n isLoading,\r\n error,\r\n lastRequest,\r\n lastResponse,\r\n baseUrl: client.baseUrl,\r\n };\r\n}\r\n"]}