@revenium/perplexity 2.0.4 → 2.0.5
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/CHANGELOG.md +32 -33
- package/README.md +120 -101
- package/SECURITY.md +34 -0
- package/dist/cjs/constants/models.js +38 -0
- package/dist/cjs/constants/models.js.map +1 -0
- package/dist/cjs/core/client/index.js +13 -0
- package/dist/cjs/core/client/index.js.map +1 -0
- package/dist/cjs/core/client/manager.js +85 -0
- package/dist/cjs/core/client/manager.js.map +1 -0
- package/dist/cjs/core/config/index.js +21 -0
- package/dist/cjs/core/config/index.js.map +1 -0
- package/dist/cjs/core/config/loader.js +48 -0
- package/dist/cjs/core/config/loader.js.map +1 -0
- package/dist/cjs/core/config/manager.js +77 -0
- package/dist/cjs/core/config/manager.js.map +1 -0
- package/dist/cjs/core/config/validator.js +45 -0
- package/dist/cjs/core/config/validator.js.map +1 -0
- package/dist/cjs/core/middleware/index.js +14 -0
- package/dist/cjs/core/middleware/index.js.map +1 -0
- package/dist/cjs/core/middleware/interfaces.js +94 -0
- package/dist/cjs/core/middleware/interfaces.js.map +1 -0
- package/dist/cjs/core/middleware/revenium-client.js +44 -0
- package/dist/cjs/core/middleware/revenium-client.js.map +1 -0
- package/dist/cjs/core/middleware/streaming-wrapper.js +80 -0
- package/dist/cjs/core/middleware/streaming-wrapper.js.map +1 -0
- package/dist/cjs/core/providers/detector.js +38 -0
- package/dist/cjs/core/providers/detector.js.map +1 -0
- package/dist/cjs/core/providers/index.js +14 -0
- package/dist/cjs/core/providers/index.js.map +1 -0
- package/dist/cjs/core/tracking/api-client.js +67 -0
- package/dist/cjs/core/tracking/api-client.js.map +1 -0
- package/dist/cjs/core/tracking/index.js +21 -0
- package/dist/cjs/core/tracking/index.js.map +1 -0
- package/dist/cjs/core/tracking/payload-builder.js +95 -0
- package/dist/cjs/core/tracking/payload-builder.js.map +1 -0
- package/dist/cjs/core/tracking/usage-tracker.js +83 -0
- package/dist/cjs/core/tracking/usage-tracker.js.map +1 -0
- package/dist/cjs/index.js +60 -59
- package/dist/cjs/index.js.map +1 -1
- package/dist/cjs/types/function-parameters.js +14 -0
- package/dist/cjs/types/function-parameters.js.map +1 -0
- package/dist/cjs/types/index.js +20 -1
- package/dist/cjs/types/index.js.map +1 -1
- package/dist/cjs/utils/constants.js +20 -0
- package/dist/cjs/utils/constants.js.map +1 -0
- package/dist/cjs/utils/error-handler.js +194 -0
- package/dist/cjs/utils/error-handler.js.map +1 -0
- package/dist/cjs/utils/metadata-builder.js +191 -0
- package/dist/cjs/utils/metadata-builder.js.map +1 -0
- package/dist/cjs/utils/stop-reason-mapper.js +74 -0
- package/dist/cjs/utils/stop-reason-mapper.js.map +1 -0
- package/dist/cjs/utils/transaction-id.js +19 -0
- package/dist/cjs/utils/transaction-id.js.map +1 -0
- package/dist/cjs/utils/url-builder.js +57 -0
- package/dist/cjs/utils/url-builder.js.map +1 -0
- package/dist/esm/constants/models.js +35 -0
- package/dist/esm/constants/models.js.map +1 -0
- package/dist/esm/core/client/index.js +5 -0
- package/dist/esm/core/client/index.js.map +1 -0
- package/dist/esm/core/client/manager.js +78 -0
- package/dist/esm/core/client/manager.js.map +1 -0
- package/dist/esm/core/config/index.js +11 -0
- package/dist/esm/core/config/index.js.map +1 -0
- package/dist/esm/core/config/loader.js +45 -0
- package/dist/esm/core/config/loader.js.map +1 -0
- package/dist/esm/core/config/manager.js +70 -0
- package/dist/esm/core/config/manager.js.map +1 -0
- package/dist/esm/core/config/validator.js +42 -0
- package/dist/esm/core/config/validator.js.map +1 -0
- package/dist/esm/core/middleware/index.js +7 -0
- package/dist/esm/core/middleware/index.js.map +1 -0
- package/dist/esm/core/middleware/interfaces.js +89 -0
- package/dist/esm/core/middleware/interfaces.js.map +1 -0
- package/dist/esm/core/middleware/revenium-client.js +37 -0
- package/dist/esm/core/middleware/revenium-client.js.map +1 -0
- package/dist/esm/core/middleware/streaming-wrapper.js +76 -0
- package/dist/esm/core/middleware/streaming-wrapper.js.map +1 -0
- package/dist/esm/core/providers/detector.js +34 -0
- package/dist/esm/core/providers/detector.js.map +1 -0
- package/dist/esm/core/providers/index.js +9 -0
- package/dist/esm/core/providers/index.js.map +1 -0
- package/dist/esm/core/tracking/api-client.js +64 -0
- package/dist/esm/core/tracking/api-client.js.map +1 -0
- package/dist/esm/core/tracking/index.js +13 -0
- package/dist/esm/core/tracking/index.js.map +1 -0
- package/dist/esm/core/tracking/payload-builder.js +92 -0
- package/dist/esm/core/tracking/payload-builder.js.map +1 -0
- package/dist/esm/core/tracking/usage-tracker.js +79 -0
- package/dist/esm/core/tracking/usage-tracker.js.map +1 -0
- package/dist/esm/index.js +46 -39
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/types/function-parameters.js +13 -0
- package/dist/esm/types/function-parameters.js.map +1 -0
- package/dist/esm/types/index.js +6 -2
- package/dist/esm/types/index.js.map +1 -1
- package/dist/esm/utils/constants.js +17 -0
- package/dist/esm/utils/constants.js.map +1 -0
- package/dist/esm/utils/error-handler.js +182 -0
- package/dist/esm/utils/error-handler.js.map +1 -0
- package/dist/esm/utils/metadata-builder.js +183 -0
- package/dist/esm/utils/metadata-builder.js.map +1 -0
- package/dist/esm/utils/stop-reason-mapper.js +69 -0
- package/dist/esm/utils/stop-reason-mapper.js.map +1 -0
- package/dist/esm/utils/transaction-id.js +16 -0
- package/dist/esm/utils/transaction-id.js.map +1 -0
- package/dist/esm/utils/url-builder.js +53 -0
- package/dist/esm/utils/url-builder.js.map +1 -0
- package/dist/types/constants/models.d.ts +39 -0
- package/dist/types/constants/models.d.ts.map +1 -0
- package/dist/types/core/client/index.d.ts +5 -0
- package/dist/types/core/client/index.d.ts.map +1 -0
- package/dist/types/core/client/manager.d.ts +44 -0
- package/dist/types/core/client/manager.d.ts.map +1 -0
- package/dist/types/core/config/index.d.ts +10 -0
- package/dist/types/core/config/index.d.ts.map +1 -0
- package/dist/types/core/config/loader.d.ts +13 -0
- package/dist/types/core/config/loader.d.ts.map +1 -0
- package/dist/types/core/config/manager.d.ts +28 -0
- package/dist/types/core/config/manager.d.ts.map +1 -0
- package/dist/types/core/config/validator.d.ts +12 -0
- package/dist/types/core/config/validator.d.ts.map +1 -0
- package/dist/types/core/middleware/index.d.ts +7 -0
- package/dist/types/core/middleware/index.d.ts.map +1 -0
- package/dist/types/core/middleware/interfaces.d.ts +35 -0
- package/dist/types/core/middleware/interfaces.d.ts.map +1 -0
- package/dist/types/core/middleware/revenium-client.d.ts +25 -0
- package/dist/types/core/middleware/revenium-client.d.ts.map +1 -0
- package/dist/types/core/middleware/streaming-wrapper.d.ts +21 -0
- package/dist/types/core/middleware/streaming-wrapper.d.ts.map +1 -0
- package/dist/types/core/providers/detector.d.ts +24 -0
- package/dist/types/core/providers/detector.d.ts.map +1 -0
- package/dist/types/core/providers/index.d.ts +8 -0
- package/dist/types/core/providers/index.d.ts.map +1 -0
- package/dist/types/core/tracking/api-client.d.ts +17 -0
- package/dist/types/core/tracking/api-client.d.ts.map +1 -0
- package/dist/types/core/tracking/index.d.ts +11 -0
- package/dist/types/core/tracking/index.d.ts.map +1 -0
- package/dist/types/core/tracking/payload-builder.d.ts +24 -0
- package/dist/types/core/tracking/payload-builder.d.ts.map +1 -0
- package/dist/types/core/tracking/usage-tracker.d.ts +30 -0
- package/dist/types/core/tracking/usage-tracker.d.ts.map +1 -0
- package/dist/types/index.d.ts +56 -27
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/types/function-parameters.d.ts +185 -0
- package/dist/types/types/function-parameters.d.ts.map +1 -0
- package/dist/types/types/index.d.ts +108 -129
- package/dist/types/types/index.d.ts.map +1 -1
- package/dist/types/utils/constants.d.ts +9 -0
- package/dist/types/utils/constants.d.ts.map +1 -0
- package/dist/types/utils/error-handler.d.ts +95 -0
- package/dist/types/utils/error-handler.d.ts.map +1 -0
- package/dist/types/utils/metadata-builder.d.ts +65 -0
- package/dist/types/utils/metadata-builder.d.ts.map +1 -0
- package/dist/types/utils/stop-reason-mapper.d.ts +29 -0
- package/dist/types/utils/stop-reason-mapper.d.ts.map +1 -0
- package/dist/types/utils/transaction-id.d.ts +14 -0
- package/dist/types/utils/transaction-id.d.ts.map +1 -0
- package/dist/types/utils/url-builder.d.ts +22 -0
- package/dist/types/utils/url-builder.d.ts.map +1 -0
- package/examples/README.md +124 -220
- package/examples/advanced.ts +123 -0
- package/examples/basic.ts +32 -37
- package/examples/getting_started.ts +26 -49
- package/examples/metadata.ts +51 -48
- package/examples/stream.ts +53 -0
- package/package.json +9 -10
- package/dist/cjs/constants.js +0 -70
- package/dist/cjs/constants.js.map +0 -1
- package/dist/cjs/core/config/perplexity-config.js +0 -45
- package/dist/cjs/core/config/perplexity-config.js.map +0 -1
- package/dist/cjs/core/config/revenium-config.js +0 -80
- package/dist/cjs/core/config/revenium-config.js.map +0 -1
- package/dist/cjs/core/tracking/metering.js +0 -211
- package/dist/cjs/core/tracking/metering.js.map +0 -1
- package/dist/cjs/core/wrapper/perplexity-client.js +0 -187
- package/dist/cjs/core/wrapper/perplexity-client.js.map +0 -1
- package/dist/cjs/utils/logger.js +0 -23
- package/dist/cjs/utils/logger.js.map +0 -1
- package/dist/esm/constants.js +0 -67
- package/dist/esm/constants.js.map +0 -1
- package/dist/esm/core/config/perplexity-config.js +0 -40
- package/dist/esm/core/config/perplexity-config.js.map +0 -1
- package/dist/esm/core/config/revenium-config.js +0 -72
- package/dist/esm/core/config/revenium-config.js.map +0 -1
- package/dist/esm/core/tracking/metering.js +0 -206
- package/dist/esm/core/tracking/metering.js.map +0 -1
- package/dist/esm/core/wrapper/perplexity-client.js +0 -180
- package/dist/esm/core/wrapper/perplexity-client.js.map +0 -1
- package/dist/esm/utils/logger.js +0 -20
- package/dist/esm/utils/logger.js.map +0 -1
- package/dist/types/constants.d.ts +0 -67
- package/dist/types/constants.d.ts.map +0 -1
- package/dist/types/core/config/perplexity-config.d.ts +0 -24
- package/dist/types/core/config/perplexity-config.d.ts.map +0 -1
- package/dist/types/core/config/revenium-config.d.ts +0 -37
- package/dist/types/core/config/revenium-config.d.ts.map +0 -1
- package/dist/types/core/tracking/metering.d.ts +0 -31
- package/dist/types/core/tracking/metering.d.ts.map +0 -1
- package/dist/types/core/wrapper/perplexity-client.d.ts +0 -32
- package/dist/types/core/wrapper/perplexity-client.d.ts.map +0 -1
- package/dist/types/utils/logger.d.ts +0 -10
- package/dist/types/utils/logger.d.ts.map +0 -1
- package/examples/advanced-features.ts +0 -148
- package/examples/chat.ts +0 -73
- package/examples/streaming.ts +0 -50
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Payload Builder Module
|
|
4
|
+
*
|
|
5
|
+
* Handles construction of Revenium API payloads.
|
|
6
|
+
* Extracted from tracking.ts for single responsibility.
|
|
7
|
+
*/
|
|
8
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
9
|
+
exports.buildPayload = buildPayload;
|
|
10
|
+
const crypto_1 = require("crypto");
|
|
11
|
+
const index_js_1 = require("../config/index.js");
|
|
12
|
+
const stop_reason_mapper_js_1 = require("../../utils/stop-reason-mapper.js");
|
|
13
|
+
const metadata_builder_js_1 = require("../../utils/metadata-builder.js");
|
|
14
|
+
const index_js_2 = require("../providers/index.js");
|
|
15
|
+
// Global logger
|
|
16
|
+
const logger = (0, index_js_1.getLogger)();
|
|
17
|
+
/**
|
|
18
|
+
* Build payload for Revenium API
|
|
19
|
+
*
|
|
20
|
+
* This shared payload builder eliminates payload duplication.
|
|
21
|
+
* Handles CHAT operation type for Perplexity.
|
|
22
|
+
*
|
|
23
|
+
* @param operationType - Type of operation (CHAT)
|
|
24
|
+
* @param response - API response from Perplexity
|
|
25
|
+
* @param request - Original request parameters
|
|
26
|
+
* @param startTime - Request start timestamp
|
|
27
|
+
* @param duration - Request duration in milliseconds
|
|
28
|
+
* @param providerInfo - Provider information (always Perplexity)
|
|
29
|
+
* @param timeToFirstToken - Time to first token in milliseconds (for streaming)
|
|
30
|
+
* @returns Constructed payload for Revenium API
|
|
31
|
+
*/
|
|
32
|
+
function buildPayload(operationType, response, request, startTime, duration, providerInfo, timeToFirstToken) {
|
|
33
|
+
const now = new Date().toISOString();
|
|
34
|
+
const requestTime = new Date(startTime).toISOString();
|
|
35
|
+
const usage = response.usage;
|
|
36
|
+
if (!usage) {
|
|
37
|
+
throw new Error("Response usage data is missing");
|
|
38
|
+
}
|
|
39
|
+
const modelName = response.model;
|
|
40
|
+
// Get provider metadata (always Perplexity)
|
|
41
|
+
const providerMetadata = providerInfo
|
|
42
|
+
? (0, index_js_2.getProviderMetadata)()
|
|
43
|
+
: { provider: "Perplexity", modelSource: "PERPLEXITY" };
|
|
44
|
+
// Build metadata fields using utility (eliminates repetitive spreading)
|
|
45
|
+
const metadataFields = (0, metadata_builder_js_1.buildMetadataFields)(request.usageMetadata);
|
|
46
|
+
// Map Perplexity cost object to Revenium cost fields
|
|
47
|
+
const costFields = usage.cost
|
|
48
|
+
? {
|
|
49
|
+
inputTokenCost: usage.cost.input_tokens_cost,
|
|
50
|
+
outputTokenCost: usage.cost.output_tokens_cost,
|
|
51
|
+
totalCost: usage.cost.total_cost,
|
|
52
|
+
}
|
|
53
|
+
: {
|
|
54
|
+
// Let Revenium calculate costs if not provided
|
|
55
|
+
inputTokenCost: undefined,
|
|
56
|
+
outputTokenCost: undefined,
|
|
57
|
+
totalCost: undefined,
|
|
58
|
+
};
|
|
59
|
+
// Common fields for all operations
|
|
60
|
+
const commonPayload = {
|
|
61
|
+
costType: "AI",
|
|
62
|
+
model: modelName,
|
|
63
|
+
responseTime: now,
|
|
64
|
+
requestDuration: duration,
|
|
65
|
+
provider: providerMetadata.provider,
|
|
66
|
+
modelSource: providerMetadata.modelSource,
|
|
67
|
+
requestTime,
|
|
68
|
+
completionStartTime: now,
|
|
69
|
+
// Common token counts
|
|
70
|
+
inputTokenCount: usage.prompt_tokens,
|
|
71
|
+
totalTokenCount: usage.total_tokens,
|
|
72
|
+
// Metadata fields (processed by utility)
|
|
73
|
+
...metadataFields,
|
|
74
|
+
// Fixed middleware source identifier (spec format: revenium-{provider}-{language})
|
|
75
|
+
middlewareSource: "revenium-perplexity-node",
|
|
76
|
+
// Cost fields from Perplexity
|
|
77
|
+
...costFields,
|
|
78
|
+
};
|
|
79
|
+
// Chat-specific fields
|
|
80
|
+
return {
|
|
81
|
+
...commonPayload,
|
|
82
|
+
operationType: "CHAT",
|
|
83
|
+
transactionId: response.id || `chat-${(0, crypto_1.randomUUID)()}`,
|
|
84
|
+
outputTokenCount: usage.completion_tokens || 0,
|
|
85
|
+
// Perplexity doesn't support reasoning or caching
|
|
86
|
+
reasoningTokenCount: undefined,
|
|
87
|
+
cacheCreationTokenCount: undefined,
|
|
88
|
+
cacheReadTokenCount: undefined,
|
|
89
|
+
stopReason: (0, stop_reason_mapper_js_1.mapStopReason)(response.choices?.[0]?.finish_reason, logger),
|
|
90
|
+
isStreamed: Boolean(request.stream),
|
|
91
|
+
// Time to first token (for streaming requests)
|
|
92
|
+
timeToFirstToken: timeToFirstToken,
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
//# sourceMappingURL=payload-builder.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"payload-builder.js","sourceRoot":"","sources":["../../../../src/core/tracking/payload-builder.ts"],"names":[],"mappings":";AAAA;;;;;GAKG;;AAgCH,oCAoFC;AAlHD,mCAAoC;AAOpC,iDAA+C;AAC/C,6EAAkE;AAClE,yEAAsE;AACtE,oDAA4D;AAE5D,gBAAgB;AAChB,MAAM,MAAM,GAAG,IAAA,oBAAS,GAAE,CAAC;AAE3B;;;;;;;;;;;;;;GAcG;AACH,SAAgB,YAAY,CAC1B,aAAqB,EACrB,QAA4B,EAC5B,OAA8B,EAC9B,SAAiB,EACjB,QAAgB,EAChB,YAA2B,EAC3B,gBAAyB;IAEzB,MAAM,GAAG,GAAG,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC;IACrC,MAAM,WAAW,GAAG,IAA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B,mFAAmF;QACnF,gBAAgB,EAAE,0BAA0B;QAE5C,8BAA8B;QAC9B,GAAG,UAAU;KACd,CAAC;IAEF,uBAAuB;IACvB,OAAO;QACL,GAAG,aAAa;QAChB,aAAa,EAAE,MAAM;QACrB,aAAa,EAAE,QAAQ,CAAC,EAAE,IAAI,QAAQ,IAAA,mBAAU,GAAE,EAAE;QACpD,gBAAgB,EAAE,KAAK,CAAC,iBAAiB,IAAI,CAAC;QAC9C,kDAAkD;QAClD,mBAAmB,EAAE,SAAS;QAC9B,uBAAuB,EAAE,SAAS;QAClC,mBAAmB,EAAE,SAAS;QAC9B,UAAU,EAAE,IAAA,qCAAa,EACvB,QAAQ,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC,EAAE,aAAa,EACpC,MAAM,CACP;QACD,UAAU,EAAE,OAAO,CAAC,OAAO,CAAC,MAAM,CAAC;QACnC,+CAA+C;QAC/C,gBAAgB,EAAE,gBAAgB;KACnC,CAAC;AACJ,CAAC"}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Usage Tracker Module
|
|
4
|
+
*
|
|
5
|
+
* High-level tracking functions that combine payload building and API communication.
|
|
6
|
+
* Extracted from tracking.ts for better organization.
|
|
7
|
+
*/
|
|
8
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
9
|
+
exports.sendReveniumMetrics = sendReveniumMetrics;
|
|
10
|
+
exports.trackUsageAsync = trackUsageAsync;
|
|
11
|
+
const index_js_1 = require("../config/index.js");
|
|
12
|
+
const api_client_js_1 = require("./api-client.js");
|
|
13
|
+
const payload_builder_js_1 = require("./payload-builder.js");
|
|
14
|
+
const error_handler_js_1 = require("../../utils/error-handler.js");
|
|
15
|
+
// Global logger
|
|
16
|
+
const logger = (0, index_js_1.getLogger)();
|
|
17
|
+
/**
|
|
18
|
+
* Chat completions tracking - thin wrapper
|
|
19
|
+
*/
|
|
20
|
+
async function sendReveniumMetrics(response, request, startTime, duration, providerInfo, timeToFirstToken) {
|
|
21
|
+
await (0, error_handler_js_1.safeAsyncOperation)(async () => {
|
|
22
|
+
const payload = (0, payload_builder_js_1.buildPayload)("CHAT", response, request, startTime, duration, providerInfo, timeToFirstToken);
|
|
23
|
+
await (0, api_client_js_1.sendToRevenium)(payload);
|
|
24
|
+
}, "Chat completion tracking", {
|
|
25
|
+
logError: true,
|
|
26
|
+
rethrow: false, // Don't rethrow to maintain fire-and-forget behavior
|
|
27
|
+
messagePrefix: "Chat completion tracking failed: ",
|
|
28
|
+
}, logger);
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Fire-and-forget wrapper for chat completions
|
|
32
|
+
* Constructs DTO objects from simple tracking data to call sendReveniumMetrics
|
|
33
|
+
*/
|
|
34
|
+
function trackUsageAsync(trackingData) {
|
|
35
|
+
// Build DTO response object from tracking data
|
|
36
|
+
const dtoResponse = {
|
|
37
|
+
id: trackingData.requestId,
|
|
38
|
+
model: trackingData.model,
|
|
39
|
+
object: "chat.completion",
|
|
40
|
+
created: Math.floor(Date.now() / 1000),
|
|
41
|
+
usage: {
|
|
42
|
+
prompt_tokens: trackingData.promptTokens,
|
|
43
|
+
completion_tokens: trackingData.completionTokens,
|
|
44
|
+
total_tokens: trackingData.totalTokens,
|
|
45
|
+
cost: trackingData.cost,
|
|
46
|
+
},
|
|
47
|
+
choices: [
|
|
48
|
+
{
|
|
49
|
+
index: 0,
|
|
50
|
+
finish_reason: trackingData.finishReason,
|
|
51
|
+
message: {
|
|
52
|
+
role: "assistant",
|
|
53
|
+
content: "",
|
|
54
|
+
},
|
|
55
|
+
},
|
|
56
|
+
],
|
|
57
|
+
};
|
|
58
|
+
// Build DTO request object from tracking data
|
|
59
|
+
const dtoRequest = {
|
|
60
|
+
model: trackingData.model,
|
|
61
|
+
messages: [],
|
|
62
|
+
usageMetadata: trackingData.usageMetadata,
|
|
63
|
+
stream: trackingData.isStreamed,
|
|
64
|
+
};
|
|
65
|
+
const startTime = Date.now() - trackingData.duration;
|
|
66
|
+
sendReveniumMetrics(dtoResponse, dtoRequest, startTime, trackingData.duration, trackingData.providerInfo, trackingData.timeToFirstToken)
|
|
67
|
+
.then(() => {
|
|
68
|
+
logger.debug("Usage tracking completed successfully", {
|
|
69
|
+
requestId: trackingData.requestId,
|
|
70
|
+
model: trackingData.model,
|
|
71
|
+
totalTokens: trackingData.totalTokens,
|
|
72
|
+
isStreamed: trackingData.isStreamed,
|
|
73
|
+
});
|
|
74
|
+
})
|
|
75
|
+
.catch((error) => {
|
|
76
|
+
logger.warn("Usage tracking failed", {
|
|
77
|
+
error: error instanceof Error ? error.message : String(error),
|
|
78
|
+
requestId: trackingData.requestId,
|
|
79
|
+
model: trackingData.model,
|
|
80
|
+
});
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
//# sourceMappingURL=usage-tracker.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"usage-tracker.js","sourceRoot":"","sources":["../../../../src/core/tracking/usage-tracker.ts"],"names":[],"mappings":";AAAA;;;;;GAKG;;AAoBH,kDA6BC;AAMD,0CAuEC;AArHD,iDAA+C;AAC/C,mDAAiD;AACjD,6DAAoD;AACpD,mEAAkE;AAElE,gBAAgB;AAChB,MAAM,MAAM,GAAG,IAAA,oBAAS,GAAE,CAAC;AAE3B;;GAEG;AACI,KAAK,UAAU,mBAAmB,CACvC,QAA4B,EAC5B,OAA8B,EAC9B,SAAiB,EACjB,QAAgB,EAChB,YAA2B,EAC3B,gBAAyB;IAEzB,MAAM,IAAA,qCAAkB,EACtB,KAAK,IAAI,EAAE;QACT,MAAM,OAAO,GAAG,IAAA,iCAAY,EAC1B,MAAM,EACN,QAAQ,EACR,OAAO,EACP,SAAS,EACT,QAAQ,EACR,YAAY,EACZ,gBAAgB,CACjB,CAAC;QACF,MAAM,IAAA,8BAAc,EAAC,OAAO,CAAC,CAAC;IAChC,CAAC,EACD,0BAA0B,EAC1B;QACE,QAAQ,EAAE,IAAI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,KAAK,EAAE,YAAY,CAAC,KAAK;YACzB,WAAW,EAAE,YAAY,CAAC,WAAW;YACrC,UAAU,EAAE,YAAY,CAAC,UAAU;SACpC,CAAC,CAAC;IACL,CAAC,CAAC;SACD,KAAK,CAAC,CAAC,KAAK,EAAE,EAAE;QACf,MAAM,CAAC,IAAI,CAAC,uBAAuB,EAAE;YACnC,KAAK,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC;YAC7D,SAAS,EAAE,YAAY,CAAC,SAAS;YACjC,KAAK,EAAE,YAAY,CAAC,KAAK;SAC1B,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACP,CAAC"}
|
package/dist/cjs/index.js
CHANGED
|
@@ -1,69 +1,70 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
/**
|
|
3
|
-
* Revenium Middleware for
|
|
3
|
+
* Revenium Perplexity Middleware for TypeScript
|
|
4
4
|
*
|
|
5
|
-
*
|
|
5
|
+
* This middleware tracks Perplexity AI usage and sends metrics to Revenium.
|
|
6
|
+
* Uses Go-aligned API pattern with Initialize/GetClient.
|
|
6
7
|
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
* initializePerplexityFromEnv,
|
|
12
|
-
* createChatCompletion,
|
|
13
|
-
* } from '@revenium/perplexity';
|
|
8
|
+
* Environment Variables:
|
|
9
|
+
* REVENIUM_METERING_API_KEY=hak_your_api_key
|
|
10
|
+
* REVENIUM_METERING_BASE_URL=https://api.revenium.ai (optional)
|
|
11
|
+
* PERPLEXITY_API_KEY=pplx_your_perplexity_key
|
|
14
12
|
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
* initializePerplexityFromEnv();
|
|
13
|
+
* Usage:
|
|
14
|
+
* import { Initialize, GetClient } from "@revenium/perplexity";
|
|
18
15
|
*
|
|
19
|
-
* //
|
|
20
|
-
*
|
|
21
|
-
*
|
|
22
|
-
*
|
|
23
|
-
*
|
|
16
|
+
* // Initialize from environment
|
|
17
|
+
* Initialize();
|
|
18
|
+
*
|
|
19
|
+
* // Get client
|
|
20
|
+
* const client = GetClient();
|
|
24
21
|
*
|
|
25
|
-
*
|
|
26
|
-
*
|
|
22
|
+
* // Use client
|
|
23
|
+
* const response = await client.chat().completions().create({
|
|
24
|
+
* model: "sonar",
|
|
25
|
+
* messages: [{ role: "user", content: "Hello!" }]
|
|
26
|
+
* }, {
|
|
27
|
+
* organizationId: "my-org",
|
|
28
|
+
* productId: "my-app",
|
|
29
|
+
* subscriber: {
|
|
30
|
+
* id: "user-123",
|
|
31
|
+
* email: "user@my-org.com"
|
|
32
|
+
* }
|
|
33
|
+
* });
|
|
27
34
|
*/
|
|
28
35
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
29
|
-
exports.
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
Object.defineProperty(exports, "
|
|
37
|
-
Object.defineProperty(exports, "
|
|
38
|
-
Object.defineProperty(exports, "
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
var
|
|
43
|
-
Object.defineProperty(exports, "
|
|
44
|
-
Object.defineProperty(exports, "
|
|
45
|
-
Object.defineProperty(exports, "
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
Object.defineProperty(exports, "
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
Object.defineProperty(exports, "
|
|
63
|
-
Object.defineProperty(exports, "MIDDLEWARE_INFO", { enumerable: true, get: function () { return constants_1.MIDDLEWARE_INFO; } });
|
|
64
|
-
// ============================================================================
|
|
65
|
-
// Utilities
|
|
66
|
-
// ============================================================================
|
|
67
|
-
var logger_1 = require("./utils/logger");
|
|
68
|
-
Object.defineProperty(exports, "logger", { enumerable: true, get: function () { return logger_1.logger; } });
|
|
36
|
+
exports.PERPLEXITY_MODELS = exports.getProviderMetadata = exports.detectProvider = exports.trackUsageAsync = exports.StreamingWrapper = exports.CompletionsInterface = exports.ChatInterface = exports.ReveniumPerplexity = exports.Configure = exports.Reset = exports.IsInitialized = exports.GetClient = exports.Initialize = void 0;
|
|
37
|
+
/**
|
|
38
|
+
* Main API - Go-aligned pattern
|
|
39
|
+
*/
|
|
40
|
+
var index_js_1 = require("./core/client/index.js");
|
|
41
|
+
Object.defineProperty(exports, "Initialize", { enumerable: true, get: function () { return index_js_1.Initialize; } });
|
|
42
|
+
Object.defineProperty(exports, "GetClient", { enumerable: true, get: function () { return index_js_1.GetClient; } });
|
|
43
|
+
Object.defineProperty(exports, "IsInitialized", { enumerable: true, get: function () { return index_js_1.IsInitialized; } });
|
|
44
|
+
Object.defineProperty(exports, "Reset", { enumerable: true, get: function () { return index_js_1.Reset; } });
|
|
45
|
+
Object.defineProperty(exports, "Configure", { enumerable: true, get: function () { return index_js_1.Configure; } });
|
|
46
|
+
/**
|
|
47
|
+
* Middleware classes
|
|
48
|
+
*/
|
|
49
|
+
var index_js_2 = require("./core/middleware/index.js");
|
|
50
|
+
Object.defineProperty(exports, "ReveniumPerplexity", { enumerable: true, get: function () { return index_js_2.ReveniumPerplexity; } });
|
|
51
|
+
Object.defineProperty(exports, "ChatInterface", { enumerable: true, get: function () { return index_js_2.ChatInterface; } });
|
|
52
|
+
Object.defineProperty(exports, "CompletionsInterface", { enumerable: true, get: function () { return index_js_2.CompletionsInterface; } });
|
|
53
|
+
Object.defineProperty(exports, "StreamingWrapper", { enumerable: true, get: function () { return index_js_2.StreamingWrapper; } });
|
|
54
|
+
/**
|
|
55
|
+
* Tracking functions (for advanced use cases)
|
|
56
|
+
*/
|
|
57
|
+
var index_js_3 = require("./core/tracking/index.js");
|
|
58
|
+
Object.defineProperty(exports, "trackUsageAsync", { enumerable: true, get: function () { return index_js_3.trackUsageAsync; } });
|
|
59
|
+
/**
|
|
60
|
+
* Provider detection functions
|
|
61
|
+
*/
|
|
62
|
+
var index_js_4 = require("./core/providers/index.js");
|
|
63
|
+
Object.defineProperty(exports, "detectProvider", { enumerable: true, get: function () { return index_js_4.detectProvider; } });
|
|
64
|
+
Object.defineProperty(exports, "getProviderMetadata", { enumerable: true, get: function () { return index_js_4.getProviderMetadata; } });
|
|
65
|
+
/**
|
|
66
|
+
* Model constants
|
|
67
|
+
*/
|
|
68
|
+
var models_js_1 = require("./constants/models.js");
|
|
69
|
+
Object.defineProperty(exports, "PERPLEXITY_MODELS", { enumerable: true, get: function () { return models_js_1.PERPLEXITY_MODELS; } });
|
|
69
70
|
//# sourceMappingURL=index.js.map
|
package/dist/cjs/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";AAAA
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;;;AA8BH;;GAEG;AACH,mDAMgC;AAL9B,sGAAA,UAAU,OAAA;AACV,qGAAA,SAAS,OAAA;AACT,yGAAA,aAAa,OAAA;AACb,iGAAA,KAAK,OAAA;AACL,qGAAA,SAAS,OAAA;AAGX;;GAEG;AACH,uDAKoC;AAJlC,8GAAA,kBAAkB,OAAA;AAClB,yGAAA,aAAa,OAAA;AACb,gHAAA,oBAAoB,OAAA;AACpB,4GAAA,gBAAgB,OAAA;AAGlB;;GAEG;AACH,qDAA2D;AAAlD,2GAAA,eAAe,OAAA;AAExB;;GAEG;AACH,sDAAgF;AAAvE,0GAAA,cAAc,OAAA;AAAE,+GAAA,mBAAmB,OAAA;AAE5C;;GAEG;AACH,mDAA0D;AAAjD,8GAAA,iBAAiB,OAAA"}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Function Parameter Types
|
|
4
|
+
*
|
|
5
|
+
* Comprehensive type definitions for function parameters throughout the middleware.
|
|
6
|
+
* These interfaces provide type safety by replacing 'any' types with proper,
|
|
7
|
+
* well-documented interfaces that match Perplexity API structures and internal requirements.
|
|
8
|
+
*
|
|
9
|
+
* @fileoverview Type-safe function parameter definitions
|
|
10
|
+
* @author Revenium
|
|
11
|
+
* @since 2.0.0
|
|
12
|
+
*/
|
|
13
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
14
|
+
//# sourceMappingURL=function-parameters.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"function-parameters.js","sourceRoot":"","sources":["../../../src/types/function-parameters.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;GAUG"}
|
package/dist/cjs/types/index.js
CHANGED
|
@@ -1,6 +1,25 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
/**
|
|
3
|
-
*
|
|
3
|
+
* Core Types Module
|
|
4
|
+
*
|
|
5
|
+
* Central type definitions for the Revenium Perplexity middleware.
|
|
6
|
+
* This module exports all core types used throughout the application.
|
|
4
7
|
*/
|
|
8
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
9
|
+
if (k2 === undefined) k2 = k;
|
|
10
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
11
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
12
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
13
|
+
}
|
|
14
|
+
Object.defineProperty(o, k2, desc);
|
|
15
|
+
}) : (function(o, m, k, k2) {
|
|
16
|
+
if (k2 === undefined) k2 = k;
|
|
17
|
+
o[k2] = m[k];
|
|
18
|
+
}));
|
|
19
|
+
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
20
|
+
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
21
|
+
};
|
|
5
22
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
23
|
+
// Re-export function parameter types
|
|
24
|
+
__exportStar(require("./function-parameters.js"), exports);
|
|
6
25
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/types/index.ts"],"names":[],"mappings":";AAAA
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/types/index.ts"],"names":[],"mappings":";AAAA;;;;;GAKG;;;;;;;;;;;;;;;;AAEH,qCAAqC;AACrC,2DAAyC"}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.ERROR_MESSAGE_PATTERNS_TYPE_CONFIG = exports.MESSAGE_PATTERNS_TYPE_NETWORK = void 0;
|
|
4
|
+
/**
|
|
5
|
+
* Error message patterns for network-related errors
|
|
6
|
+
*/
|
|
7
|
+
exports.MESSAGE_PATTERNS_TYPE_NETWORK = [
|
|
8
|
+
"network",
|
|
9
|
+
"timeout",
|
|
10
|
+
"ECONNRESET",
|
|
11
|
+
];
|
|
12
|
+
/**
|
|
13
|
+
* Error message patterns for configuration-related errors
|
|
14
|
+
*/
|
|
15
|
+
exports.ERROR_MESSAGE_PATTERNS_TYPE_CONFIG = [
|
|
16
|
+
"config",
|
|
17
|
+
"key",
|
|
18
|
+
"unauthorized",
|
|
19
|
+
];
|
|
20
|
+
//# sourceMappingURL=constants.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"constants.js","sourceRoot":"","sources":["../../../src/utils/constants.ts"],"names":[],"mappings":";;;AAAA;;GAEG;AACU,QAAA,6BAA6B,GAAG;IAC3C,SAAS;IACT,SAAS;IACT,YAAY;CACb,CAAC;AAEF;;GAEG;AACU,QAAA,kCAAkC,GAAG;IAChD,QAAQ;IACR,KAAK;IACL,cAAc;CACf,CAAC"}
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Error Handler Utilities
|
|
4
|
+
*
|
|
5
|
+
* Centralized error handling patterns to eliminate repetitive try/catch blocks
|
|
6
|
+
* and provide consistent error logging and recovery strategies.
|
|
7
|
+
*/
|
|
8
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
9
|
+
exports.NetworkError = exports.ConfigurationError = exports.ValidationError = void 0;
|
|
10
|
+
exports.safeAsyncOperation = safeAsyncOperation;
|
|
11
|
+
exports.safeSyncOperation = safeSyncOperation;
|
|
12
|
+
exports.validateOrThrow = validateOrThrow;
|
|
13
|
+
exports.validateOrUndefined = validateOrUndefined;
|
|
14
|
+
exports.withRetry = withRetry;
|
|
15
|
+
exports.classifyError = classifyError;
|
|
16
|
+
const constants_js_1 = require("./constants.js");
|
|
17
|
+
/**
|
|
18
|
+
* Default error handling strategy
|
|
19
|
+
*/
|
|
20
|
+
const DEFAULT_STRATEGY = {
|
|
21
|
+
logError: true,
|
|
22
|
+
rethrow: true,
|
|
23
|
+
messagePrefix: '',
|
|
24
|
+
fallbackValue: undefined,
|
|
25
|
+
transformError: (error) => (error instanceof Error ? error : new Error(String(error))),
|
|
26
|
+
};
|
|
27
|
+
/**
|
|
28
|
+
* Safe async operation wrapper with comprehensive error handling
|
|
29
|
+
*
|
|
30
|
+
* @param operation - The async operation to execute
|
|
31
|
+
* @param context - Context information for logging
|
|
32
|
+
* @param strategy - Error handling strategy
|
|
33
|
+
* @param logger - Logger instance
|
|
34
|
+
* @returns Promise with result or fallback value
|
|
35
|
+
*/
|
|
36
|
+
async function safeAsyncOperation(operation, context, strategy = {}, logger) {
|
|
37
|
+
const config = { ...DEFAULT_STRATEGY, ...strategy };
|
|
38
|
+
try {
|
|
39
|
+
return await operation();
|
|
40
|
+
}
|
|
41
|
+
catch (error) {
|
|
42
|
+
const transformedError = config.transformError(error);
|
|
43
|
+
if (config.logError && logger) {
|
|
44
|
+
logger.error(`${config.messagePrefix}${context}`, {
|
|
45
|
+
error: transformedError.message,
|
|
46
|
+
stack: transformedError.stack,
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
if (config.rethrow)
|
|
50
|
+
throw transformedError;
|
|
51
|
+
return config.fallbackValue;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Safe sync operation wrapper
|
|
56
|
+
*
|
|
57
|
+
* @param operation - The sync operation to execute
|
|
58
|
+
* @param context - Context information for logging
|
|
59
|
+
* @param strategy - Error handling strategy
|
|
60
|
+
* @param logger - Logger instance
|
|
61
|
+
* @returns Result or fallback value
|
|
62
|
+
*/
|
|
63
|
+
function safeSyncOperation(operation, context, strategy = {}, logger) {
|
|
64
|
+
const config = { ...DEFAULT_STRATEGY, ...strategy };
|
|
65
|
+
try {
|
|
66
|
+
return operation();
|
|
67
|
+
}
|
|
68
|
+
catch (error) {
|
|
69
|
+
const transformedError = config.transformError(error);
|
|
70
|
+
if (config.logError && logger) {
|
|
71
|
+
logger.error(`${config.messagePrefix}${context}`, {
|
|
72
|
+
error: transformedError.message,
|
|
73
|
+
stack: transformedError.stack,
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
if (config.rethrow)
|
|
77
|
+
throw transformedError;
|
|
78
|
+
return config.fallbackValue;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Validation wrapper that provides clear error messages
|
|
83
|
+
*
|
|
84
|
+
* @param value - Value to validate
|
|
85
|
+
* @param validator - Validation function
|
|
86
|
+
* @param errorMessage - Error message if validation fails
|
|
87
|
+
* @returns Validated value
|
|
88
|
+
*/
|
|
89
|
+
function validateOrThrow(value, validator, errorMessage) {
|
|
90
|
+
if (!validator(value))
|
|
91
|
+
throw new Error(errorMessage);
|
|
92
|
+
return value;
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Validation wrapper that returns undefined on failure
|
|
96
|
+
*
|
|
97
|
+
* @param value - Value to validate
|
|
98
|
+
* @param validator - Validation function
|
|
99
|
+
* @param logger - Optional logger for warnings
|
|
100
|
+
* @param context - Context for logging
|
|
101
|
+
* @returns Validated value or undefined
|
|
102
|
+
*/
|
|
103
|
+
function validateOrUndefined(value, validator, logger, context) {
|
|
104
|
+
if (!validator(value)) {
|
|
105
|
+
if (logger && context) {
|
|
106
|
+
logger.warn(`Validation failed: ${context}`, { value });
|
|
107
|
+
}
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
return value;
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Create a retry wrapper for operations that might fail temporarily
|
|
114
|
+
*
|
|
115
|
+
* @param operation - Operation to retry
|
|
116
|
+
* @param maxRetries - Maximum number of retries
|
|
117
|
+
* @param delayMs - Delay between retries in milliseconds
|
|
118
|
+
* @param logger - Logger for retry attempts
|
|
119
|
+
* @returns Promise with operation result
|
|
120
|
+
*/
|
|
121
|
+
async function withRetry(operation, maxRetries = 3, delayMs = 1000, logger) {
|
|
122
|
+
let lastError;
|
|
123
|
+
for (let attempt = 1; attempt <= maxRetries; attempt++) {
|
|
124
|
+
try {
|
|
125
|
+
return await operation();
|
|
126
|
+
}
|
|
127
|
+
catch (error) {
|
|
128
|
+
lastError = error instanceof Error ? error : new Error(String(error));
|
|
129
|
+
if (attempt === maxRetries) {
|
|
130
|
+
break;
|
|
131
|
+
}
|
|
132
|
+
if (logger) {
|
|
133
|
+
logger.warn(`Operation failed, retrying (${attempt}/${maxRetries})`, {
|
|
134
|
+
error: lastError.message,
|
|
135
|
+
nextRetryIn: delayMs,
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
await new Promise(resolve => setTimeout(resolve, delayMs));
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
// eslint-disable-next-line no-throw-literal
|
|
142
|
+
throw lastError;
|
|
143
|
+
}
|
|
144
|
+
/**
|
|
145
|
+
* Common error types for better error handling
|
|
146
|
+
*/
|
|
147
|
+
class ValidationError extends Error {
|
|
148
|
+
constructor(message, context) {
|
|
149
|
+
super(message);
|
|
150
|
+
this.context = context;
|
|
151
|
+
this.name = 'ValidationError';
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
exports.ValidationError = ValidationError;
|
|
155
|
+
class ConfigurationError extends Error {
|
|
156
|
+
constructor(message, context) {
|
|
157
|
+
super(message);
|
|
158
|
+
this.context = context;
|
|
159
|
+
this.name = 'ConfigurationError';
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
exports.ConfigurationError = ConfigurationError;
|
|
163
|
+
class NetworkError extends Error {
|
|
164
|
+
constructor(message, context) {
|
|
165
|
+
super(message);
|
|
166
|
+
this.context = context;
|
|
167
|
+
this.name = 'NetworkError';
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
exports.NetworkError = NetworkError;
|
|
171
|
+
/**
|
|
172
|
+
* Error classification utility
|
|
173
|
+
*/
|
|
174
|
+
function classifyError(error) {
|
|
175
|
+
if (error instanceof ValidationError) {
|
|
176
|
+
return { type: 'validation', message: error.message, isRetryable: false };
|
|
177
|
+
}
|
|
178
|
+
if (error instanceof ConfigurationError) {
|
|
179
|
+
return { type: 'configuration', message: error.message, isRetryable: false };
|
|
180
|
+
}
|
|
181
|
+
if (error instanceof NetworkError) {
|
|
182
|
+
return { type: 'network', message: error.message, isRetryable: true };
|
|
183
|
+
}
|
|
184
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
185
|
+
// Classify based on message patterns
|
|
186
|
+
if (constants_js_1.MESSAGE_PATTERNS_TYPE_NETWORK.some(pattern => message.includes(pattern))) {
|
|
187
|
+
return { type: 'network', message, isRetryable: true };
|
|
188
|
+
}
|
|
189
|
+
if (constants_js_1.ERROR_MESSAGE_PATTERNS_TYPE_CONFIG.some(pattern => message.includes(pattern))) {
|
|
190
|
+
return { type: 'configuration', message, isRetryable: false };
|
|
191
|
+
}
|
|
192
|
+
return { type: 'unknown', message, isRetryable: false };
|
|
193
|
+
}
|
|
194
|
+
//# sourceMappingURL=error-handler.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"error-handler.js","sourceRoot":"","sources":["../../../src/utils/error-handler.ts"],"names":[],"mappings":";AAAA;;;;;GAKG;;;AAyCH,gDAuBC;AAWD,8CAuBC;AAUD,0CAOC;AAWD,kDAaC;AAWD,8BA6BC;AAsCD,sCA4BC;AAlPD,iDAAmG;AAkBnG;;GAEG;AACH,MAAM,gBAAgB,GAAoC;IACxD,QAAQ,EAAE,IAAI;IACd,OAAO,EAAE,IAAI;IACb,aAAa,EAAE,EAAE;IACjB,aAAa,EAAE,SAAS;IACxB,cAAc,EAAE,CAAC,KAAc,EAAE,EAAE,CAAC,CAAC,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;CAChG,CAAC;AAEF;;;;;;;;GAQG;AACI,KAAK,UAAU,kBAAkB,CACtC,SAA2B,EAC3B,OAAe,EACf,WAAkC,EAAE,EACpC,MAAe;IAEf,MAAM,MAAM,GAAG,EAAE,GAAG,gBAAgB,EAAE,GAAG,QAAQ,EAAE,CAAC;IAEpD,IAAI,CAAC;QACH,OAAO,MAAM,SAAS,EAAE,CAAC;IAC3B,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,gBAAgB,GAAG,MAAM,CAAC,cAAc,CAAC,KAAK,CAAC,CAAC;QAEtD,IAAI,MAAM,CAAC,QAAQ,IAAI,MAAM,EAAE,CAAC;YAC9B,MAAM,CAAC,KAAK,CAAC,GAAG,MAAM,CAAC,aAAa,GAAG,OAAO,EAAE,EAAE;gBAChD,KAAK,EAAE,gBAAgB,CAAC,OAAO;gBAC/B,KAAK,EAAE,gBAAgB,CAAC,KAAK;aAC9B,CAA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