← Files RivetARCHIVED FILE
node_modules/rivet-design/dist/services/IntegrationsClient.js
21.4 KB · Nov 7, 2026 · 13:16 UTC
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.IntegrationsClient = exports.isIntegrationProvider = void 0;
const authUpdate_1 = require("./authUpdate");
const zod_1 = require("zod");
const reference_connectors_1 = require("../types/reference-connectors");
const reference_pages_1 = require("../types/reference-pages");
const x_bookmarks_1 = require("../types/x-bookmarks");
const cosmos_1 = require("../types/cosmos");
const logger_1 = require("../utils/logger");
const cosmos_profile_1 = require("../types/cosmos-profile");
const ProviderRateLimit_1 = require("../utils/ProviderRateLimit");
const ConfigManager_1 = require("./ConfigManager");
const AuthService_1 = require("./AuthService");
const accessTokenRefresh_1 = require("./accessTokenRefresh");
const RequestAuthContext_1 = require("./RequestAuthContext");
const errorMessage_1 = require("../utils/errorMessage");
const log = (0, logger_1.createLogger)('IntegrationsClient');
const REQUEST_TIMEOUT_MS = 30_000;
const NormalizedPinSchema = zod_1.z.object({
id: zod_1.z.string(),
image_urls: zod_1.z.array(zod_1.z.string()),
dominant_color: zod_1.z.string().nullable(),
title: zod_1.z.string().nullable(),
description: zod_1.z.string().nullable(),
alt_text: zod_1.z.string().nullable(),
link: zod_1.z.string().nullable(),
local_path: zod_1.z.string().optional(),
});
const NormalizedBoardSchema = zod_1.z.object({
id: zod_1.z.string(),
name: zod_1.z.string().nullable(),
description: zod_1.z.string().nullable(),
privacy: zod_1.z.string().nullable(),
});
const PinterestFetchResultSchema = zod_1.z.union([
zod_1.z.object({
status: zod_1.z.literal('ok'),
type: zod_1.z.literal('pin'),
pins: zod_1.z.array(NormalizedPinSchema),
}),
zod_1.z.object({
status: zod_1.z.literal('ok'),
type: zod_1.z.literal('board'),
board: NormalizedBoardSchema,
pins: zod_1.z.array(NormalizedPinSchema),
page: zod_1.z
.object({ nextCursor: zod_1.z.string().nullable(), isComplete: zod_1.z.boolean() })
.optional(),
}),
zod_1.z.object({ status: zod_1.z.literal('not_connected') }),
zod_1.z.object({
status: zod_1.z.literal('error'),
message: zod_1.z.string(),
reason: zod_1.z
.enum([
'pin_not_accessible',
'unsupported_url',
'board_not_owned',
'board_owner_unverified',
'board_not_found',
'rate_limited',
])
.optional(),
retryAfterMs: zod_1.z.number().optional(),
}),
]);
const NormalizedAreNaContentSchema = zod_1.z.object({
id: zod_1.z.string(),
kind: zod_1.z.enum(['block', 'channel']),
block_type: zod_1.z.string().nullable(),
title: zod_1.z.string().nullable(),
description: zod_1.z.string().nullable(),
content: zod_1.z.string().nullable(),
source_url: zod_1.z.string().nullable(),
image_urls: zod_1.z.array(zod_1.z.string()),
attachment_url: zod_1.z.string().nullable(),
embed_url: zod_1.z.string().nullable(),
alt_text: zod_1.z.string().nullable(),
});
const AreNaFetchResultSchema = zod_1.z.union([
zod_1.z.object({
status: zod_1.z.literal('ok'),
type: zod_1.z.literal('channel'),
channel: zod_1.z.object({
id: zod_1.z.string(),
title: zod_1.z.string().nullable(),
slug: zod_1.z.string().nullable(),
visibility: zod_1.z.string().nullable(),
description: zod_1.z.string().nullable(),
owner_name: zod_1.z.string().nullable(),
owner_slug: zod_1.z.string().nullable(),
contents_count: zod_1.z.number().nullable(),
}),
contents: zod_1.z.array(NormalizedAreNaContentSchema),
meta: zod_1.z
.object({
current_page: zod_1.z.number().nullable(),
per_page: zod_1.z.number().nullable(),
total_pages: zod_1.z.number().nullable(),
total_count: zod_1.z.number().nullable(),
has_more_pages: zod_1.z.boolean().nullable(),
})
.nullable(),
}),
zod_1.z.object({
status: zod_1.z.literal('ok'),
type: zod_1.z.literal('block'),
contents: zod_1.z.array(NormalizedAreNaContentSchema),
}),
zod_1.z.object({ status: zod_1.z.literal('not_connected') }),
zod_1.z.object({
status: zod_1.z.literal('error'),
message: zod_1.z.string(),
reason: zod_1.z.literal('rate_limited').optional(),
retryAfterMs: zod_1.z.number().optional(),
}),
]);
const IntegrationListBodySchema = zod_1.z.object({
integrations: zod_1.z
.array(zod_1.z.object({
provider: zod_1.z.unknown().optional(),
status: zod_1.z.unknown().optional(),
externalAccountId: zod_1.z.unknown().optional(),
externalUsername: zod_1.z.unknown().optional(),
connectedAt: zod_1.z.unknown().optional(),
}))
.optional(),
});
const IntegrationConnectBodySchema = zod_1.z.object({
authUrl: zod_1.z.string().min(1).optional(),
message: zod_1.z.string().optional(),
error: zod_1.z.string().optional(),
});
const INTEGRATION_PROVIDERS = [
'pinterest',
'arena',
'x',
];
const isIntegrationProvider = (value) => INTEGRATION_PROVIDERS.includes(value);
exports.isIntegrationProvider = isIntegrationProvider;
class IntegrationsClient {
proxyUrl;
configManager = (0, ConfigManager_1.getConfigManager)();
authService;
constructor(options) {
this.proxyUrl = options?.proxyUrl || this.configManager.getProxyUrl();
this.authService = options?.authService ?? new AuthService_1.AuthService(this.proxyUrl);
}
async getBearerToken() {
const requestContext = (0, RequestAuthContext_1.getRequestAuthContext)();
let token = requestContext?.token ?? this.configManager.getAuthToken();
if (token) {
return token;
}
const profile = await this.authService.getValidatedProfile();
token = (0, RequestAuthContext_1.getRequestAuthContext)()?.token ?? this.configManager.getAuthToken();
if (!profile || !token) {
return null;
}
return token;
}
async requestWithBearer(request) {
const token = await this.getBearerToken();
if (!token) {
return null;
}
const updateAuth = (0, authUpdate_1.captureAuthUpdate)(this.configManager);
const requestContext = (0, RequestAuthContext_1.getRequestAuthContext)();
const refreshToken = requestContext?.refreshToken ?? this.configManager.getRefreshToken();
const response = await request(token);
if (response.status !== 401) {
return response;
}
if (!refreshToken) {
return response;
}
const refreshed = await (0, accessTokenRefresh_1.refreshAccessTokenViaProxy)({
refreshToken,
proxyUrl: this.proxyUrl,
});
if (!refreshed) {
return response;
}
updateAuth(refreshed);
return request(refreshed.token);
}
async fetchPinterest(url, pagination, cancellation) {
const post = async (bearer) => fetch(`${this.proxyUrl}/api/integrations/pinterest/fetch`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${bearer}`,
},
body: JSON.stringify({ url, ...(pagination ? { pagination } : {}) }),
signal: cancellation
? AbortSignal.any([
cancellation,
AbortSignal.timeout(REQUEST_TIMEOUT_MS),
])
: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
});
try {
const response = await this.requestWithBearer(post);
if (!response) {
return { status: 'error', message: 'Not authenticated' };
}
await (0, ProviderRateLimit_1.throwIfRateLimited)(response);
if (!response.ok) {
const text = await response.text().catch(() => '');
return {
status: 'error',
message: `Pinterest fetch failed (${response.status}): ${text.slice(0, 200)}`,
};
}
return PinterestFetchResultSchema.parse(await response.json());
}
catch (error) {
if (error instanceof ProviderRateLimit_1.ProviderRateLimit)
return {
status: 'error',
reason: 'rate_limited',
retryAfterMs: error.retryAfterMs,
message: error.message,
};
log.warn('Pinterest fetch error:', error);
return {
status: 'error',
message: (0, errorMessage_1.errorMessage)(error, 'Unknown error'),
};
}
}
async fetchArena(url, page, cancellation) {
const post = async (bearer) => fetch(`${this.proxyUrl}/api/integrations/arena/fetch`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${bearer}`,
},
body: JSON.stringify({ url, ...(page !== undefined ? { page } : {}) }),
signal: cancellation
? AbortSignal.any([
cancellation,
AbortSignal.timeout(REQUEST_TIMEOUT_MS),
])
: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
});
try {
const response = await this.requestWithBearer(post);
if (!response) {
return { status: 'error', message: 'Not authenticated' };
}
await (0, ProviderRateLimit_1.throwIfRateLimited)(response);
if (!response.ok) {
const text = await response.text().catch(() => '');
return {
status: 'error',
message: `Are.na fetch failed (${response.status}): ${text.slice(0, 200)}`,
};
}
return AreNaFetchResultSchema.parse(await response.json());
}
catch (error) {
if (error instanceof ProviderRateLimit_1.ProviderRateLimit)
return {
status: 'error',
reason: 'rate_limited',
retryAfterMs: error.retryAfterMs,
message: error.message,
};
log.warn('Are.na fetch error:', error);
return {
status: 'error',
message: (0, errorMessage_1.errorMessage)(error, 'Unknown error'),
};
}
}
async referenceRequest({ provider, path, expectedAccountId, cursor, signal, }) {
signal?.throwIfAborted();
const query = new URLSearchParams({
...(expectedAccountId ? { expectedAccountId } : {}),
...(cursor ? { cursor } : {}),
});
const response = await this.requestWithBearer((bearer) => fetch(`${this.proxyUrl}/api/integrations/references/${provider}/${path}?${query}`, {
headers: { Authorization: `Bearer ${bearer}` },
signal: AbortSignal.any([
AbortSignal.timeout(REQUEST_TIMEOUT_MS),
...(signal ? [signal] : []),
]),
}));
if (!response)
throw new Error('Sign in to Rivet to connect design references');
await (0, ProviderRateLimit_1.throwIfRateLimited)(response);
const data = await response.json();
if (!response.ok) {
const failure = zod_1.z
.object({ reason: zod_1.z.enum(['not_connected', 'account_changed']) })
.safeParse(data);
if (failure.success)
throw new reference_pages_1.ReferenceConnectionError(failure.data.reason);
throw new Error('Reference collections are unavailable. Check the connection and update the Rivet proxy.');
}
return data;
}
async discoverReferenceCollections(input) {
return reference_connectors_1.ReferenceCatalogPageSchema.parse(await this.referenceRequest({ ...input, path: 'collections' }));
}
async readReferenceCollection(input) {
return reference_pages_1.ReferenceContentsPageSchema.parse(await this.referenceRequest({
...input,
path: `collections/${encodeURIComponent(input.collectionId)}/references`,
}));
}
async referenceAccount(input) {
return reference_connectors_1.ReferenceProfileSchema.parse(await this.referenceRequest({ ...input, path: 'account' }));
}
async discoverCosmos({ url, cursor, signal, }) {
signal?.throwIfAborted();
const query = new URLSearchParams({ url });
if (cursor)
query.set('cursor', cursor);
const response = await this.requestWithBearer((bearer) => fetch(`${this.proxyUrl}/api/integrations/cosmos/profiles?${query}`, {
headers: { Authorization: `Bearer ${bearer}` },
signal: AbortSignal.any([
AbortSignal.timeout(REQUEST_TIMEOUT_MS),
...(signal ? [signal] : []),
]),
}));
if (!response)
throw new Error('Sign in to Rivet to discover a public Cosmos profile');
await (0, ProviderRateLimit_1.throwIfRateLimited)(response);
const data = await response.json();
if (!response.ok) {
const message = data &&
typeof data === 'object' &&
'message' in data &&
typeof data.message === 'string'
? data.message
: 'Cosmos profile discovery is unavailable; update the Rivet proxy and retry';
throw new Error(message);
}
return cosmos_profile_1.CosmosProfilePageSchema.parse(data);
}
async fetchCosmos({ url, collectionId, cursor, signal, }) {
try {
const route = collectionId
? `/collections/${encodeURIComponent(collectionId)}/elements`
: '/collections';
const query = new URLSearchParams(collectionId ? {} : { url });
if (cursor)
query.set('cursor', cursor);
const response = await this.requestWithBearer((bearer) => fetch(`${this.proxyUrl}/api/integrations/cosmos${route}?${query}`, {
headers: { Authorization: `Bearer ${bearer}` },
signal: AbortSignal.any([
AbortSignal.timeout(REQUEST_TIMEOUT_MS),
...(signal ? [signal] : []),
]),
}));
if (!response)
return { status: 'error', message: 'Not authenticated' };
await (0, ProviderRateLimit_1.throwIfRateLimited)(response);
const parsed = cosmos_1.CosmosResultSchema.safeParse(await response.json());
if (!parsed.success || (!response.ok && parsed.data.status !== 'error'))
throw new Error('Invalid Cosmos response');
return parsed.data;
}
catch (error) {
signal?.throwIfAborted();
if (error instanceof ProviderRateLimit_1.ProviderRateLimit)
return {
status: 'error',
reason: 'rate_limited',
message: error.message,
retryAfterMs: error.retryAfterMs,
};
return {
status: 'error',
reason: 'provider_unavailable',
message: 'Cosmos collections could not be loaded. Check the public collection URL and retry.',
};
}
}
async fetchXBookmarks({ expectedAccountId, cursor, signal, }) {
try {
const response = await this.requestWithBearer((bearer) => fetch(`${this.proxyUrl}/api/integrations/x/fetch`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${bearer}`,
},
body: JSON.stringify({
expectedAccountId,
...(cursor ? { cursor } : {}),
}),
signal: signal
? AbortSignal.any([signal, AbortSignal.timeout(REQUEST_TIMEOUT_MS)])
: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
}));
if (!response)
return { status: 'error', message: 'Not authenticated' };
await (0, ProviderRateLimit_1.throwIfRateLimited)(response);
const parsed = x_bookmarks_1.XBookmarksResultSchema.safeParse(await response.json());
if (!parsed.success || (!response.ok && parsed.data.status !== 'error'))
throw new Error('Invalid X bookmark response');
return parsed.data;
}
catch (error) {
signal?.throwIfAborted();
if (error instanceof ProviderRateLimit_1.ProviderRateLimit)
return {
status: 'error',
reason: 'rate_limited',
retryAfterMs: error.retryAfterMs,
message: error.message,
};
return {
status: 'error',
message: 'X bookmarks could not be loaded. Check the X connection in Rivet and retry.',
};
}
}
async listIntegrations() {
const get = async (bearer) => fetch(`${this.proxyUrl}/api/integrations`, {
method: 'GET',
headers: { Authorization: `Bearer ${bearer}` },
});
try {
const response = await this.requestWithBearer(get);
if (!response) {
return { status: 'error', message: 'Not authenticated' };
}
if (!response.ok) {
const text = await response.text().catch(() => '');
return {
status: 'error',
message: `Integration status failed (${response.status}): ${text.slice(0, 200)}`,
};
}
const body = IntegrationListBodySchema.parse(await response.json());
return {
status: 'ok',
integrations: (body.integrations ?? []).map((integration) => ({
provider: String(integration.provider ?? ''),
status: String(integration.status ?? ''),
externalAccountId: typeof integration.externalAccountId === 'string'
? integration.externalAccountId
: null,
externalUsername: typeof integration.externalUsername === 'string'
? integration.externalUsername
: null,
connectedAt: String(integration.connectedAt ?? ''),
})),
};
}
catch (error) {
log.warn('Integration status error:', error);
return {
status: 'error',
message: (0, errorMessage_1.errorMessage)(error, 'Unknown error'),
};
}
}
async connect(provider) {
const post = async (bearer) => fetch(`${this.proxyUrl}/api/integrations/${provider}/connect`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${bearer}`,
},
body: JSON.stringify({ flow: 'popup' }),
});
try {
const response = await this.requestWithBearer(post);
if (!response) {
return { status: 'error', message: 'Not authenticated' };
}
const parsed = IntegrationConnectBodySchema.safeParse(await response.json().catch(() => ({})));
const body = parsed.success ? parsed.data : {};
if (!response.ok || !body.authUrl) {
const message = (typeof body.message === 'string' && body.message) ||
(typeof body.error === 'string' && body.error) ||
`Could not start ${provider} connect (${response.status})`;
return { status: 'error', message };
}
return { status: 'ok', authUrl: body.authUrl };
}
catch (error) {
log.warn('Integration connect error:', error);
return {
status: 'error',
message: (0, errorMessage_1.errorMessage)(error, 'Unknown error'),
};
}
}
async disconnect(provider) {
const del = async (bearer) => fetch(`${this.proxyUrl}/api/integrations/${provider}`, {
method: 'DELETE',
headers: { Authorization: `Bearer ${bearer}` },
});
try {
const response = await this.requestWithBearer(del);
if (!response) {
return { status: 'error', message: 'Not authenticated' };
}
if (!response.ok) {
const text = await response.text().catch(() => '');
return {
status: 'error',
message: `Disconnect failed (${response.status}): ${text.slice(0, 200)}`,
};
}
return { status: 'ok' };
}
catch (error) {
log.warn('Integration disconnect error:', error);
return {
status: 'error',
message: (0, errorMessage_1.errorMessage)(error, 'Unknown error'),
};
}
}
}
exports.IntegrationsClient = IntegrationsClient;
//# sourceMappingURL=IntegrationsClient.js.mapSHA-256: dad15289015f5aab342819bc9ac306de0bed295207cb9fe2214c0a0016f4b63b