aios-core 3.5.0 → 3.7.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.
@@ -0,0 +1,237 @@
1
+ /**
2
+ * Tests for {{pascalCase serviceName}} service.
3
+ * @module @aios/{{kebabCase serviceName}}/tests
4
+ * @story {{storyId}}
5
+ */
6
+
7
+ import {
8
+ create{{pascalCase serviceName}}Service,
9
+ {{pascalCase serviceName}}Error,
10
+ {{pascalCase serviceName}}ErrorCode,
11
+ } from '../index';
12
+ import type { {{pascalCase serviceName}}Config, {{pascalCase serviceName}}Service } from '../types';
13
+
14
+ describe('{{pascalCase serviceName}}Service', () => {
15
+ // ─────────────────────────────────────────────────────────────────────────────
16
+ // Test Configuration
17
+ // ─────────────────────────────────────────────────────────────────────────────
18
+
19
+ const validConfig: {{pascalCase serviceName}}Config = {
20
+ {{#each envVars}}
21
+ {{camelCase this.name}}: 'test-{{kebabCase this.name}}',
22
+ {{/each}}
23
+ };
24
+
25
+ // ─────────────────────────────────────────────────────────────────────────────
26
+ // Factory Function Tests
27
+ // ─────────────────────────────────────────────────────────────────────────────
28
+
29
+ describe('create{{pascalCase serviceName}}Service', () => {
30
+ it('should create a service instance with valid config', () => {
31
+ const service = create{{pascalCase serviceName}}Service(validConfig);
32
+
33
+ expect(service).toBeDefined();
34
+ expect(typeof service.execute).toBe('function');
35
+ expect(typeof service.getConfig).toBe('function');
36
+ expect(typeof service.healthCheck).toBe('function');
37
+ });
38
+
39
+ it('should throw on null config', () => {
40
+ expect(() => {
41
+ create{{pascalCase serviceName}}Service(null as unknown as {{pascalCase serviceName}}Config);
42
+ }).toThrow({{pascalCase serviceName}}Error);
43
+ });
44
+
45
+ it('should throw on undefined config', () => {
46
+ expect(() => {
47
+ create{{pascalCase serviceName}}Service(undefined as unknown as {{pascalCase serviceName}}Config);
48
+ }).toThrow({{pascalCase serviceName}}Error);
49
+ });
50
+
51
+ {{#each envVars}}
52
+ {{#if this.required}}
53
+ it('should throw when {{this.name}} is missing', () => {
54
+ const configWithoutField = { ...validConfig };
55
+ delete (configWithoutField as Record<string, unknown>).{{camelCase this.name}};
56
+
57
+ expect(() => {
58
+ create{{pascalCase serviceName}}Service(configWithoutField as {{pascalCase serviceName}}Config);
59
+ }).toThrow(expect.objectContaining({
60
+ code: {{pascalCase serviceName}}ErrorCode.CONFIGURATION_ERROR,
61
+ }));
62
+ });
63
+
64
+ {{/if}}
65
+ {{/each}}
66
+ });
67
+
68
+ // ─────────────────────────────────────────────────────────────────────────────
69
+ // Configuration Tests
70
+ // ─────────────────────────────────────────────────────────────────────────────
71
+
72
+ describe('getConfig', () => {
73
+ let service: {{pascalCase serviceName}}Service;
74
+
75
+ beforeEach(() => {
76
+ service = create{{pascalCase serviceName}}Service(validConfig);
77
+ });
78
+
79
+ it('should return configuration without sensitive values', () => {
80
+ const config = service.getConfig();
81
+
82
+ expect(config).toBeDefined();
83
+ expect(typeof config).toBe('object');
84
+ });
85
+
86
+ it('should not expose sensitive configuration', () => {
87
+ const config = service.getConfig();
88
+
89
+ // Verify sensitive fields are not exposed
90
+ {{#each envVars}}
91
+ {{#if this.sensitive}}
92
+ expect(config.{{camelCase this.name}}).toBeUndefined();
93
+ {{/if}}
94
+ {{/each}}
95
+ });
96
+ });
97
+
98
+ // ─────────────────────────────────────────────────────────────────────────────
99
+ // Service Method Tests
100
+ // ─────────────────────────────────────────────────────────────────────────────
101
+
102
+ describe('execute', () => {
103
+ let service: {{pascalCase serviceName}}Service;
104
+
105
+ beforeEach(() => {
106
+ service = create{{pascalCase serviceName}}Service(validConfig);
107
+ });
108
+
109
+ it('should throw NOT_IMPLEMENTED for unimplemented execute', async () => {
110
+ await expect(service.execute()).rejects.toThrow(expect.objectContaining({
111
+ code: {{pascalCase serviceName}}ErrorCode.NOT_IMPLEMENTED,
112
+ }));
113
+ });
114
+ });
115
+
116
+ describe('healthCheck', () => {
117
+ let service: {{pascalCase serviceName}}Service;
118
+
119
+ beforeEach(() => {
120
+ service = create{{pascalCase serviceName}}Service(validConfig);
121
+ });
122
+
123
+ it('should return boolean', async () => {
124
+ const result = await service.healthCheck();
125
+
126
+ expect(typeof result).toBe('boolean');
127
+ });
128
+ });
129
+
130
+ // ─────────────────────────────────────────────────────────────────────────────
131
+ // Error Handling Tests
132
+ // ─────────────────────────────────────────────────────────────────────────────
133
+
134
+ describe('{{pascalCase serviceName}}Error', () => {
135
+ it('should have correct name', () => {
136
+ const error = new {{pascalCase serviceName}}Error('Test error');
137
+
138
+ expect(error.name).toBe('{{pascalCase serviceName}}Error');
139
+ });
140
+
141
+ it('should have default error code', () => {
142
+ const error = new {{pascalCase serviceName}}Error('Test error');
143
+
144
+ expect(error.code).toBe({{pascalCase serviceName}}ErrorCode.UNKNOWN_ERROR);
145
+ });
146
+
147
+ it('should accept custom error code', () => {
148
+ const error = new {{pascalCase serviceName}}Error(
149
+ 'Config error',
150
+ {{pascalCase serviceName}}ErrorCode.CONFIGURATION_ERROR
151
+ );
152
+
153
+ expect(error.code).toBe({{pascalCase serviceName}}ErrorCode.CONFIGURATION_ERROR);
154
+ });
155
+
156
+ it('should include error details', () => {
157
+ const details = { field: 'test', reason: 'invalid' };
158
+ const error = new {{pascalCase serviceName}}Error(
159
+ 'Validation error',
160
+ {{pascalCase serviceName}}ErrorCode.CONFIGURATION_ERROR,
161
+ { details }
162
+ );
163
+
164
+ expect(error.details).toEqual(details);
165
+ });
166
+
167
+ it('should preserve cause error', () => {
168
+ const cause = new Error('Original error');
169
+ const error = new {{pascalCase serviceName}}Error(
170
+ 'Wrapped error',
171
+ {{pascalCase serviceName}}ErrorCode.NETWORK_ERROR,
172
+ { cause }
173
+ );
174
+
175
+ expect(error.cause).toBe(cause);
176
+ });
177
+
178
+ it('should serialize to JSON correctly', () => {
179
+ const error = new {{pascalCase serviceName}}Error(
180
+ 'Test error',
181
+ {{pascalCase serviceName}}ErrorCode.CONFIGURATION_ERROR,
182
+ { details: { key: 'value' } }
183
+ );
184
+
185
+ const json = error.toJSON();
186
+
187
+ expect(json.name).toBe('{{pascalCase serviceName}}Error');
188
+ expect(json.code).toBe({{pascalCase serviceName}}ErrorCode.CONFIGURATION_ERROR);
189
+ expect(json.message).toBe('Test error');
190
+ expect(json.details).toEqual({ key: 'value' });
191
+ });
192
+ });
193
+ });
194
+
195
+ {{#if isApiIntegration}}
196
+ // ─────────────────────────────────────────────────────────────────────────────
197
+ // API Client Tests (API Integrations Only)
198
+ // ─────────────────────────────────────────────────────────────────────────────
199
+
200
+ describe('{{pascalCase serviceName}}Client', () => {
201
+ // Import client for API integration testing
202
+ const { {{pascalCase serviceName}}Client } = require('../client');
203
+
204
+ const clientConfig: {{pascalCase serviceName}}Config = {
205
+ ...validConfig,
206
+ baseUrl: 'https://api.example.com',
207
+ timeout: 5000,
208
+ maxRetries: 2,
209
+ debug: false,
210
+ };
211
+
212
+ describe('constructor', () => {
213
+ it('should create client with config', () => {
214
+ const client = new {{pascalCase serviceName}}Client(clientConfig);
215
+
216
+ expect(client).toBeDefined();
217
+ });
218
+
219
+ it('should use default values for optional config', () => {
220
+ const client = new {{pascalCase serviceName}}Client(validConfig);
221
+
222
+ expect(client).toBeDefined();
223
+ });
224
+ });
225
+
226
+ describe('getRateLimit', () => {
227
+ it('should return null initially', () => {
228
+ const client = new {{pascalCase serviceName}}Client(clientConfig);
229
+
230
+ expect(client.getRateLimit()).toBeNull();
231
+ });
232
+ });
233
+
234
+ // Note: Additional client tests require mocking fetch/network
235
+ // These should be added based on specific API requirements
236
+ });
237
+ {{/if}}
@@ -0,0 +1,403 @@
1
+ /**
2
+ * HTTP client for {{pascalCase serviceName}} API integration.
3
+ * Includes rate limiting, retry logic with exponential backoff, and request logging.
4
+ * @module @aios/{{kebabCase serviceName}}/client
5
+ * @story {{storyId}}
6
+ */
7
+
8
+ {{#if isApiIntegration}}
9
+ import type {
10
+ {{pascalCase serviceName}}Config,
11
+ {{pascalCase serviceName}}ApiResponse,
12
+ {{pascalCase serviceName}}RequestOptions,
13
+ {{pascalCase serviceName}}RateLimit,
14
+ } from './types';
15
+ import {
16
+ {{pascalCase serviceName}}Error,
17
+ {{pascalCase serviceName}}ErrorCode,
18
+ {{pascalCase serviceName}}Errors,
19
+ } from './errors';
20
+
21
+ /**
22
+ * Default configuration values.
23
+ */
24
+ const DEFAULTS = {
25
+ baseUrl: '{{apiBaseUrl}}',
26
+ timeout: 30000,
27
+ maxRetries: 3,
28
+ retryBaseDelay: 1000,
29
+ retryMaxDelay: 30000,
30
+ debug: false,
31
+ };
32
+
33
+ /**
34
+ * HTTP client for {{pascalCase serviceName}} API.
35
+ */
36
+ export class {{pascalCase serviceName}}Client {
37
+ private readonly config: Required<Pick<{{pascalCase serviceName}}Config, 'baseUrl' | 'timeout' | 'maxRetries' | 'debug'>> & {{pascalCase serviceName}}Config;
38
+ private rateLimit: {{pascalCase serviceName}}RateLimit | null = null;
39
+
40
+ constructor(config: {{pascalCase serviceName}}Config) {
41
+ this.config = {
42
+ ...config,
43
+ baseUrl: config.baseUrl ?? DEFAULTS.baseUrl,
44
+ timeout: config.timeout ?? DEFAULTS.timeout,
45
+ maxRetries: config.maxRetries ?? DEFAULTS.maxRetries,
46
+ debug: config.debug ?? DEFAULTS.debug,
47
+ };
48
+ }
49
+
50
+ /**
51
+ * Make an API request with automatic retry and rate limiting.
52
+ */
53
+ async request<T>(
54
+ endpoint: string,
55
+ options: {{pascalCase serviceName}}RequestOptions = {}
56
+ ): Promise<{{pascalCase serviceName}}ApiResponse<T>> {
57
+ const {
58
+ method = 'GET',
59
+ headers = {},
60
+ body,
61
+ params,
62
+ timeout = this.config.timeout,
63
+ noRetry = false,
64
+ } = options;
65
+
66
+ // Build URL with query parameters
67
+ const url = this.buildUrl(endpoint, params);
68
+
69
+ // Wait for rate limit if necessary
70
+ await this.waitForRateLimit();
71
+
72
+ const requestHeaders: Record<string, string> = {
73
+ 'Content-Type': 'application/json',
74
+ 'Accept': 'application/json',
75
+ ...this.getAuthHeaders(),
76
+ ...headers,
77
+ };
78
+
79
+ const requestInit: RequestInit = {
80
+ method,
81
+ headers: requestHeaders,
82
+ body: body ? JSON.stringify(body) : undefined,
83
+ };
84
+
85
+ // Retry logic
86
+ const maxAttempts = noRetry ? 1 : this.config.maxRetries + 1;
87
+ let lastError: Error | null = null;
88
+
89
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
90
+ try {
91
+ this.debug(`Request attempt ${attempt}/${maxAttempts}: ${method} ${url}`);
92
+
93
+ const response = await this.fetchWithTimeout(url, requestInit, timeout);
94
+
95
+ // Update rate limit info from headers
96
+ this.updateRateLimit(response.headers);
97
+
98
+ // Handle rate limiting (429)
99
+ if (response.status === 429) {
100
+ const retryAfter = this.getRetryAfter(response.headers);
101
+ if (attempt < maxAttempts) {
102
+ this.debug(`Rate limited, waiting ${retryAfter}ms before retry`);
103
+ await this.sleep(retryAfter);
104
+ continue;
105
+ }
106
+ throw {{pascalCase serviceName}}Errors.rateLimitError(
107
+ Math.ceil(retryAfter / 1000),
108
+ this.rateLimit ?? { remaining: 0, reset: Date.now() + retryAfter }
109
+ );
110
+ }
111
+
112
+ // Parse response
113
+ const data = await this.parseResponse<T>(response);
114
+
115
+ // Handle error responses
116
+ if (!response.ok) {
117
+ throw this.handleErrorResponse(response.status, data);
118
+ }
119
+
120
+ return {
121
+ success: true,
122
+ data: data as T,
123
+ meta: {
124
+ requestId: response.headers.get('x-request-id') ?? undefined,
125
+ rateLimit: this.rateLimit ?? undefined,
126
+ },
127
+ };
128
+ } catch (error) {
129
+ lastError = error as Error;
130
+
131
+ // Don't retry on certain errors
132
+ if (
133
+ error instanceof {{pascalCase serviceName}}Error &&
134
+ [
135
+ {{pascalCase serviceName}}ErrorCode.AUTHENTICATION_ERROR,
136
+ {{pascalCase serviceName}}ErrorCode.AUTHORIZATION_ERROR,
137
+ {{pascalCase serviceName}}ErrorCode.CONFIGURATION_ERROR,
138
+ ].includes(error.code)
139
+ ) {
140
+ throw error;
141
+ }
142
+
143
+ // Retry with exponential backoff
144
+ if (attempt < maxAttempts) {
145
+ const delay = this.calculateBackoff(attempt);
146
+ this.debug(`Request failed, retrying in ${delay}ms: ${(error as Error).message}`);
147
+ await this.sleep(delay);
148
+ }
149
+ }
150
+ }
151
+
152
+ // All retries exhausted
153
+ throw lastError instanceof {{pascalCase serviceName}}Error
154
+ ? lastError
155
+ : {{pascalCase serviceName}}Errors.networkError(
156
+ `Request failed after ${maxAttempts} attempts`,
157
+ lastError ?? undefined
158
+ );
159
+ }
160
+
161
+ /**
162
+ * Convenience method for GET requests.
163
+ */
164
+ async get<T>(endpoint: string, params?: Record<string, string | number | boolean>): Promise<T> {
165
+ const response = await this.request<T>(endpoint, { method: 'GET', params });
166
+ return response.data as T;
167
+ }
168
+
169
+ /**
170
+ * Convenience method for POST requests.
171
+ */
172
+ async post<T>(endpoint: string, body?: unknown): Promise<T> {
173
+ const response = await this.request<T>(endpoint, { method: 'POST', body });
174
+ return response.data as T;
175
+ }
176
+
177
+ /**
178
+ * Convenience method for PUT requests.
179
+ */
180
+ async put<T>(endpoint: string, body?: unknown): Promise<T> {
181
+ const response = await this.request<T>(endpoint, { method: 'PUT', body });
182
+ return response.data as T;
183
+ }
184
+
185
+ /**
186
+ * Convenience method for DELETE requests.
187
+ */
188
+ async delete<T>(endpoint: string): Promise<T> {
189
+ const response = await this.request<T>(endpoint, { method: 'DELETE' });
190
+ return response.data as T;
191
+ }
192
+
193
+ /**
194
+ * Health check / ping endpoint.
195
+ */
196
+ async ping(): Promise<boolean> {
197
+ try {
198
+ await this.get('/ping');
199
+ return true;
200
+ } catch {
201
+ return false;
202
+ }
203
+ }
204
+
205
+ /**
206
+ * Get current rate limit status.
207
+ */
208
+ getRateLimit(): {{pascalCase serviceName}}RateLimit | null {
209
+ return this.rateLimit;
210
+ }
211
+
212
+ // ─────────────────────────────────────────────────────────────────────────────
213
+ // Private Methods
214
+ // ─────────────────────────────────────────────────────────────────────────────
215
+
216
+ /**
217
+ * Build full URL with query parameters.
218
+ */
219
+ private buildUrl(
220
+ endpoint: string,
221
+ params?: Record<string, string | number | boolean>
222
+ ): string {
223
+ const baseUrl = this.config.baseUrl.replace(/\/$/, '');
224
+ const path = endpoint.startsWith('/') ? endpoint : `/${endpoint}`;
225
+ const url = new URL(`${baseUrl}${path}`);
226
+
227
+ if (params) {
228
+ Object.entries(params).forEach(([key, value]) => {
229
+ if (value !== undefined && value !== null) {
230
+ url.searchParams.append(key, String(value));
231
+ }
232
+ });
233
+ }
234
+
235
+ return url.toString();
236
+ }
237
+
238
+ /**
239
+ * Get authentication headers.
240
+ */
241
+ private getAuthHeaders(): Record<string, string> {
242
+ const headers: Record<string, string> = {};
243
+
244
+ {{#each envVars}}
245
+ {{#if this.isAuthHeader}}
246
+ if (this.config.{{camelCase this.name}}) {
247
+ headers['{{this.headerName}}'] = {{#if this.headerPrefix}}`{{this.headerPrefix}} ${this.config.{{camelCase this.name}}}`{{else}}this.config.{{camelCase this.name}}{{/if}};
248
+ }
249
+ {{/if}}
250
+ {{/each}}
251
+
252
+ return headers;
253
+ }
254
+
255
+ /**
256
+ * Fetch with timeout support.
257
+ */
258
+ private async fetchWithTimeout(
259
+ url: string,
260
+ init: RequestInit,
261
+ timeout: number
262
+ ): Promise<Response> {
263
+ const controller = new AbortController();
264
+ const timeoutId = setTimeout(() => controller.abort(), timeout);
265
+
266
+ try {
267
+ const response = await fetch(url, {
268
+ ...init,
269
+ signal: controller.signal,
270
+ });
271
+ return response;
272
+ } catch (error) {
273
+ if ((error as Error).name === 'AbortError') {
274
+ throw {{pascalCase serviceName}}Errors.timeoutError(`Request timed out after ${timeout}ms`);
275
+ }
276
+ throw error;
277
+ } finally {
278
+ clearTimeout(timeoutId);
279
+ }
280
+ }
281
+
282
+ /**
283
+ * Parse response body.
284
+ */
285
+ private async parseResponse<T>(response: Response): Promise<T | null> {
286
+ const contentType = response.headers.get('content-type');
287
+
288
+ if (contentType?.includes('application/json')) {
289
+ try {
290
+ return await response.json();
291
+ } catch {
292
+ return null;
293
+ }
294
+ }
295
+
296
+ return null;
297
+ }
298
+
299
+ /**
300
+ * Handle error response.
301
+ */
302
+ private handleErrorResponse(status: number, data: unknown): {{pascalCase serviceName}}Error {
303
+ const errorData = data as { error?: { message?: string; code?: string } } | null;
304
+ const message = errorData?.error?.message ?? `Request failed with status ${status}`;
305
+
306
+ switch (status) {
307
+ case 401:
308
+ return {{pascalCase serviceName}}Errors.authenticationError(message);
309
+ case 403:
310
+ return {{pascalCase serviceName}}Errors.authorizationError(message);
311
+ default:
312
+ return {{pascalCase serviceName}}Errors.apiError(status, message, errorData ?? undefined);
313
+ }
314
+ }
315
+
316
+ /**
317
+ * Update rate limit from response headers.
318
+ */
319
+ private updateRateLimit(headers: Headers): void {
320
+ const limit = headers.get('x-ratelimit-limit');
321
+ const remaining = headers.get('x-ratelimit-remaining');
322
+ const reset = headers.get('x-ratelimit-reset');
323
+
324
+ if (limit && remaining && reset) {
325
+ const parsedLimit = parseInt(limit, 10);
326
+ const parsedRemaining = parseInt(remaining, 10);
327
+ const parsedReset = parseInt(reset, 10);
328
+
329
+ if (isNaN(parsedLimit) || isNaN(parsedRemaining) || isNaN(parsedReset)) {
330
+ this.debug('Invalid rate limit headers received');
331
+ return;
332
+ }
333
+
334
+ this.rateLimit = {
335
+ limit: parsedLimit,
336
+ remaining: parsedRemaining,
337
+ reset: parsedReset * 1000, // Convert to milliseconds
338
+ };
339
+ }
340
+ }
341
+
342
+ /**
343
+ * Wait if rate limited.
344
+ */
345
+ private async waitForRateLimit(): Promise<void> {
346
+ if (this.rateLimit && this.rateLimit.remaining <= 0) {
347
+ const waitTime = Math.max(0, this.rateLimit.reset - Date.now());
348
+ if (waitTime > 0) {
349
+ this.debug(`Rate limit reached, waiting ${waitTime}ms`);
350
+ await this.sleep(waitTime);
351
+ }
352
+ }
353
+ }
354
+
355
+ /**
356
+ * Get retry-after delay from headers.
357
+ */
358
+ private getRetryAfter(headers: Headers): number {
359
+ const retryAfter = headers.get('retry-after');
360
+ if (retryAfter) {
361
+ // Could be seconds or HTTP date
362
+ const seconds = parseInt(retryAfter, 10);
363
+ if (!isNaN(seconds)) {
364
+ return seconds * 1000;
365
+ }
366
+ const date = new Date(retryAfter);
367
+ if (!isNaN(date.getTime())) {
368
+ return Math.max(0, date.getTime() - Date.now());
369
+ }
370
+ }
371
+ return DEFAULTS.retryBaseDelay;
372
+ }
373
+
374
+ /**
375
+ * Calculate exponential backoff delay.
376
+ */
377
+ private calculateBackoff(attempt: number): number {
378
+ const delay = DEFAULTS.retryBaseDelay * Math.pow(2, attempt - 1);
379
+ // Add jitter (±25%)
380
+ const jitter = delay * 0.25 * (Math.random() * 2 - 1);
381
+ return Math.min(delay + jitter, DEFAULTS.retryMaxDelay);
382
+ }
383
+
384
+ /**
385
+ * Sleep for specified milliseconds.
386
+ */
387
+ private sleep(ms: number): Promise<void> {
388
+ return new Promise((resolve) => setTimeout(resolve, ms));
389
+ }
390
+
391
+ /**
392
+ * Debug logging.
393
+ */
394
+ private debug(message: string): void {
395
+ if (this.config.debug) {
396
+ console.debug(`[{{pascalCase serviceName}}Client] ${message}`);
397
+ }
398
+ }
399
+ }
400
+ {{else}}
401
+ // This file is only generated for API integrations (isApiIntegration: true)
402
+ export {};
403
+ {{/if}}