aios-core 4.1.0 → 4.2.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.
Files changed (145) hide show
  1. package/.aios-core/.session/current-session.json +14 -0
  2. package/.aios-core/core/registry/registry-schema.json +166 -166
  3. package/.aios-core/core/registry/service-registry.json +6585 -6585
  4. package/.aios-core/data/entity-registry.yaml +208 -8
  5. package/.aios-core/data/registry-update-log.jsonl +165 -0
  6. package/.aios-core/development/scripts/approval-workflow.js +642 -642
  7. package/.aios-core/development/scripts/backup-manager.js +606 -606
  8. package/.aios-core/development/scripts/branch-manager.js +389 -389
  9. package/.aios-core/development/scripts/code-quality-improver.js +1311 -1311
  10. package/.aios-core/development/scripts/commit-message-generator.js +849 -849
  11. package/.aios-core/development/scripts/conflict-resolver.js +674 -674
  12. package/.aios-core/development/scripts/dependency-analyzer.js +637 -637
  13. package/.aios-core/development/scripts/diff-generator.js +351 -351
  14. package/.aios-core/development/scripts/elicitation-engine.js +384 -384
  15. package/.aios-core/development/scripts/elicitation-session-manager.js +299 -299
  16. package/.aios-core/development/scripts/git-wrapper.js +461 -461
  17. package/.aios-core/development/scripts/manifest-preview.js +244 -244
  18. package/.aios-core/development/scripts/metrics-tracker.js +775 -775
  19. package/.aios-core/development/scripts/modification-validator.js +554 -554
  20. package/.aios-core/development/scripts/pattern-learner.js +1224 -1224
  21. package/.aios-core/development/scripts/performance-analyzer.js +757 -757
  22. package/.aios-core/development/scripts/refactoring-suggester.js +1138 -1138
  23. package/.aios-core/development/scripts/rollback-handler.js +530 -530
  24. package/.aios-core/development/scripts/security-checker.js +358 -358
  25. package/.aios-core/development/scripts/template-engine.js +239 -239
  26. package/.aios-core/development/scripts/template-validator.js +278 -278
  27. package/.aios-core/development/scripts/test-generator.js +843 -843
  28. package/.aios-core/development/scripts/transaction-manager.js +589 -589
  29. package/.aios-core/development/scripts/usage-tracker.js +673 -673
  30. package/.aios-core/development/scripts/validate-filenames.js +226 -226
  31. package/.aios-core/development/scripts/version-tracker.js +526 -526
  32. package/.aios-core/development/scripts/yaml-validator.js +396 -396
  33. package/.aios-core/development/tasks/validate-next-story.md +99 -2
  34. package/.aios-core/development/templates/service-template/README.md.hbs +158 -158
  35. package/.aios-core/development/templates/service-template/__tests__/index.test.ts.hbs +237 -237
  36. package/.aios-core/development/templates/service-template/client.ts.hbs +403 -403
  37. package/.aios-core/development/templates/service-template/errors.ts.hbs +182 -182
  38. package/.aios-core/development/templates/service-template/index.ts.hbs +120 -120
  39. package/.aios-core/development/templates/service-template/package.json.hbs +87 -87
  40. package/.aios-core/development/templates/service-template/types.ts.hbs +145 -145
  41. package/.aios-core/development/templates/squad-template/LICENSE +21 -21
  42. package/.aios-core/docs/SHARD-TRANSLATION-GUIDE.md +335 -0
  43. package/.aios-core/docs/component-creation-guide.md +458 -0
  44. package/.aios-core/docs/session-update-pattern.md +307 -0
  45. package/.aios-core/docs/standards/AIOS-FRAMEWORK-MASTER.md +1963 -0
  46. package/.aios-core/docs/standards/AIOS-LIVRO-DE-OURO-V2.1-SUMMARY.md +1190 -0
  47. package/.aios-core/docs/standards/AIOS-LIVRO-DE-OURO-V2.1.md +439 -0
  48. package/.aios-core/docs/standards/AIOS-LIVRO-DE-OURO.md +5398 -0
  49. package/.aios-core/docs/standards/V3-ARCHITECTURAL-DECISIONS.md +523 -0
  50. package/.aios-core/docs/template-syntax.md +267 -0
  51. package/.aios-core/docs/troubleshooting-guide.md +625 -0
  52. package/.aios-core/infrastructure/templates/aios-sync.yaml.template +193 -193
  53. package/.aios-core/infrastructure/templates/coderabbit.yaml.template +279 -279
  54. package/.aios-core/infrastructure/templates/github-workflows/ci.yml.template +169 -169
  55. package/.aios-core/infrastructure/templates/github-workflows/pr-automation.yml.template +330 -330
  56. package/.aios-core/infrastructure/templates/github-workflows/release.yml.template +196 -196
  57. package/.aios-core/infrastructure/templates/gitignore/gitignore-aios-base.tmpl +63 -63
  58. package/.aios-core/infrastructure/templates/gitignore/gitignore-brownfield-merge.tmpl +18 -18
  59. package/.aios-core/infrastructure/templates/gitignore/gitignore-node.tmpl +85 -85
  60. package/.aios-core/infrastructure/templates/gitignore/gitignore-python.tmpl +145 -145
  61. package/.aios-core/infrastructure/tests/utilities-audit-results.json +501 -0
  62. package/.aios-core/install-manifest.yaml +101 -101
  63. package/.aios-core/local-config.yaml.template +70 -70
  64. package/.aios-core/manifests/agents.csv +29 -0
  65. package/.aios-core/manifests/schema/manifest-schema.json +190 -190
  66. package/.aios-core/manifests/tasks.csv +198 -0
  67. package/.aios-core/manifests/workers.csv +204 -0
  68. package/.aios-core/monitor/hooks/lib/__init__.py +1 -1
  69. package/.aios-core/monitor/hooks/lib/enrich.py +58 -58
  70. package/.aios-core/monitor/hooks/lib/send_event.py +47 -47
  71. package/.aios-core/monitor/hooks/notification.py +29 -29
  72. package/.aios-core/monitor/hooks/post_tool_use.py +45 -45
  73. package/.aios-core/monitor/hooks/pre_compact.py +29 -29
  74. package/.aios-core/monitor/hooks/pre_tool_use.py +40 -40
  75. package/.aios-core/monitor/hooks/stop.py +29 -29
  76. package/.aios-core/monitor/hooks/subagent_stop.py +29 -29
  77. package/.aios-core/monitor/hooks/user_prompt_submit.py +38 -38
  78. package/.aios-core/product/templates/adr.hbs +125 -125
  79. package/.aios-core/product/templates/component-react-tmpl.tsx +98 -98
  80. package/.aios-core/product/templates/dbdr.hbs +241 -241
  81. package/.aios-core/product/templates/engine/schemas/adr.schema.json +102 -102
  82. package/.aios-core/product/templates/engine/schemas/dbdr.schema.json +205 -205
  83. package/.aios-core/product/templates/engine/schemas/epic.schema.json +175 -175
  84. package/.aios-core/product/templates/engine/schemas/pmdr.schema.json +175 -175
  85. package/.aios-core/product/templates/engine/schemas/prd-v2.schema.json +300 -300
  86. package/.aios-core/product/templates/engine/schemas/prd.schema.json +152 -152
  87. package/.aios-core/product/templates/engine/schemas/story.schema.json +222 -222
  88. package/.aios-core/product/templates/engine/schemas/task.schema.json +154 -154
  89. package/.aios-core/product/templates/epic.hbs +212 -212
  90. package/.aios-core/product/templates/eslintrc-security.json +32 -32
  91. package/.aios-core/product/templates/github-actions-cd.yml +212 -212
  92. package/.aios-core/product/templates/github-actions-ci.yml +172 -172
  93. package/.aios-core/product/templates/pmdr.hbs +186 -186
  94. package/.aios-core/product/templates/prd-v2.0.hbs +216 -216
  95. package/.aios-core/product/templates/prd.hbs +201 -201
  96. package/.aios-core/product/templates/shock-report-tmpl.html +502 -502
  97. package/.aios-core/product/templates/story.hbs +263 -263
  98. package/.aios-core/product/templates/task.hbs +170 -170
  99. package/.aios-core/product/templates/tmpl-comment-on-examples.sql +158 -158
  100. package/.aios-core/product/templates/tmpl-migration-script.sql +91 -91
  101. package/.aios-core/product/templates/tmpl-rls-granular-policies.sql +104 -104
  102. package/.aios-core/product/templates/tmpl-rls-kiss-policy.sql +10 -10
  103. package/.aios-core/product/templates/tmpl-rls-roles.sql +135 -135
  104. package/.aios-core/product/templates/tmpl-rls-simple.sql +77 -77
  105. package/.aios-core/product/templates/tmpl-rls-tenant.sql +152 -152
  106. package/.aios-core/product/templates/tmpl-rollback-script.sql +77 -77
  107. package/.aios-core/product/templates/tmpl-seed-data.sql +140 -140
  108. package/.aios-core/product/templates/tmpl-smoke-test.sql +16 -16
  109. package/.aios-core/product/templates/tmpl-staging-copy-merge.sql +139 -139
  110. package/.aios-core/product/templates/tmpl-stored-proc.sql +140 -140
  111. package/.aios-core/product/templates/tmpl-trigger.sql +152 -152
  112. package/.aios-core/product/templates/tmpl-view-materialized.sql +133 -133
  113. package/.aios-core/product/templates/tmpl-view.sql +177 -177
  114. package/.aios-core/product/templates/token-exports-css-tmpl.css +240 -240
  115. package/.aios-core/quality/schemas/quality-metrics.schema.json +233 -233
  116. package/.aios-core/scripts/migrate-framework-docs.sh +300 -300
  117. package/.aios-core/scripts/pm.sh +0 -0
  118. package/.claude/hooks/enforce-architecture-first.py +196 -196
  119. package/.claude/hooks/mind-clone-governance.py +192 -192
  120. package/.claude/hooks/read-protection.py +151 -151
  121. package/.claude/hooks/slug-validation.py +176 -176
  122. package/.claude/hooks/sql-governance.py +182 -182
  123. package/.claude/hooks/write-path-validation.py +194 -194
  124. package/.claude/rules/agent-authority.md +105 -0
  125. package/.claude/rules/coderabbit-integration.md +93 -0
  126. package/.claude/rules/ids-principles.md +112 -0
  127. package/.claude/rules/story-lifecycle.md +139 -0
  128. package/.claude/rules/workflow-execution.md +150 -0
  129. package/LICENSE +48 -48
  130. package/bin/aios-minimal.js +0 -0
  131. package/bin/aios.js +0 -0
  132. package/package.json +1 -1
  133. package/packages/aios-install/bin/aios-install.js +0 -0
  134. package/packages/aios-install/bin/edmcp.js +0 -0
  135. package/packages/aios-pro-cli/bin/aios-pro.js +0 -0
  136. package/packages/installer/src/wizard/pro-setup.js +433 -49
  137. package/scripts/check-markdown-links.py +352 -352
  138. package/scripts/code-intel-health-check.js +343 -0
  139. package/scripts/dashboard-parallel-dev.sh +0 -0
  140. package/scripts/dashboard-parallel-phase3.sh +0 -0
  141. package/scripts/dashboard-parallel-phase4.sh +0 -0
  142. package/scripts/glue/README.md +355 -0
  143. package/scripts/glue/compose-agent-prompt.cjs +362 -0
  144. package/scripts/install-monitor-hooks.sh +0 -0
  145. package/.aios-core/lib/build.json +0 -1
@@ -1,403 +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}}
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}}