61 lines
2.7 KiB
TypeScript
61 lines
2.7 KiB
TypeScript
import {
|
|
registerIntegrationAdapter,
|
|
type AdapterResult,
|
|
type AdapterSyncOutcome,
|
|
type AdapterTokenRefresh,
|
|
type IntegrationAdapter,
|
|
} from "@hivegrid/foundation";
|
|
|
|
import { KWP_APP_ID, KwpError, probeKwpHealth, refreshKwpAccessToken, type KwpCredentials } from "./client.js";
|
|
|
|
function healthFromError(error: unknown): AdapterResult {
|
|
if (error instanceof KwpError) {
|
|
switch (error.code) {
|
|
case "auth_token_invalid":
|
|
return { ok: false, health: "broken", messageKey: "integrations.kwp.health.tokenInvalid" };
|
|
case "auth_scope_missing":
|
|
return { ok: false, health: "broken", messageKey: "integrations.kwp.health.scopeMissing" };
|
|
case "rate_limit_exceeded":
|
|
// Existing connections may be marked degraded by healthCheck, but a
|
|
// fresh OAuth callback must not persist credentials without one proven
|
|
// Resource-API response. `ok: false` keeps validation fail-closed.
|
|
return { ok: false, health: "degraded", messageKey: "integrations.kwp.health.rateLimited" };
|
|
case "provider_outage":
|
|
return { ok: false, health: "degraded", messageKey: "integrations.kwp.health.providerOutage" };
|
|
case "relay_host_invalid":
|
|
case "relay_not_found":
|
|
return { ok: false, health: "broken", messageKey: "integrations.kwp.health.relayInvalid" };
|
|
case "invalid_credentials":
|
|
return { ok: false, health: "broken", messageKey: "integrations.kwp.health.credentialsInvalid" };
|
|
case "mandant_unconfirmed":
|
|
return { ok: false, health: "broken", messageKey: "integrations.kwp.health.mandantUnconfirmed" };
|
|
default:
|
|
return { ok: false, health: "broken", messageKey: "integrations.kwp.health.unknown" };
|
|
}
|
|
}
|
|
return { ok: false, health: "broken", messageKey: "integrations.kwp.health.unknown" };
|
|
}
|
|
|
|
async function probe(credentials: KwpCredentials): Promise<AdapterResult> {
|
|
try {
|
|
await probeKwpHealth(credentials);
|
|
return { ok: true, health: "active", messageKey: "integrations.kwp.health.active" };
|
|
} catch (error) {
|
|
return healthFromError(error);
|
|
}
|
|
}
|
|
|
|
export const kwpAdapter: IntegrationAdapter<KwpCredentials> = registerIntegrationAdapter<KwpCredentials>({
|
|
key: KWP_APP_ID,
|
|
connectionType: "oauth2",
|
|
validateConnection: probe,
|
|
healthCheck: probe,
|
|
refreshToken: async (credentials: KwpCredentials): Promise<AdapterTokenRefresh<KwpCredentials>> => {
|
|
const next = await refreshKwpAccessToken(credentials);
|
|
return { creds: next, expiresAt: new Date(next.expiresAt) };
|
|
},
|
|
// Sync/outbox delivery remains in the later VR-P32a slice. Reject explicitly
|
|
// so an accidental generic invocation cannot record a false green no-op run.
|
|
sync: (): Promise<AdapterSyncOutcome> => Promise.reject(new Error("kwp_sync_not_available")),
|
|
});
|