@crosspost/sdk 0.1.2 → 0.1.4

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/dist/index.cjs CHANGED
@@ -1,9 +1,7 @@
1
1
  "use strict";
2
- var __create = Object.create;
3
2
  var __defProp = Object.defineProperty;
4
3
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
4
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
5
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
6
  var __export = (target, all) => {
9
7
  for (var name in all)
@@ -17,21 +15,11 @@ var __copyProps = (to, from, except, desc) => {
17
15
  }
18
16
  return to;
19
17
  };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
18
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
19
 
30
20
  // src/index.ts
31
21
  var index_exports = {};
32
22
  __export(index_exports, {
33
- AUTH_COOKIE_NAME: () => AUTH_COOKIE_NAME,
34
- AUTH_COOKIE_OPTIONS: () => AUTH_COOKIE_OPTIONS,
35
23
  AccountActivityEntrySchema: () => AccountActivityEntrySchema,
36
24
  AccountActivityParamsSchema: () => AccountActivityParamsSchema,
37
25
  AccountActivityQuerySchema: () => AccountActivityQuerySchema,
@@ -40,6 +28,9 @@ __export(index_exports, {
40
28
  AccountPostsParamsSchema: () => AccountPostsParamsSchema,
41
29
  AccountPostsQuerySchema: () => AccountPostsQuerySchema,
42
30
  AccountPostsResponseSchema: () => AccountPostsResponseSchema,
31
+ ActivityApi: () => ActivityApi,
32
+ ActivityLeaderboardQuerySchema: () => ActivityLeaderboardQuerySchema,
33
+ ActivityLeaderboardResponseSchema: () => ActivityLeaderboardResponseSchema,
43
34
  AllRateLimitsResponseSchema: () => AllRateLimitsResponseSchema,
44
35
  ApiError: () => ApiError,
45
36
  ApiErrorCode: () => ApiErrorCode,
@@ -52,8 +43,6 @@ __export(index_exports, {
52
43
  AuthStatusResponseSchema: () => AuthStatusResponseSchema,
53
44
  AuthUrlResponseSchema: () => AuthUrlResponseSchema,
54
45
  BaseError: () => BaseError,
55
- CSRF_COOKIE_NAME: () => CSRF_COOKIE_NAME,
56
- CSRF_HEADER_NAME: () => CSRF_HEADER_NAME,
57
46
  ConnectedAccountSchema: () => ConnectedAccountSchema,
58
47
  ConnectedAccountsResponseSchema: () => ConnectedAccountsResponseSchema,
59
48
  CreatePostRequestSchema: () => CreatePostRequestSchema,
@@ -65,14 +54,13 @@ __export(index_exports, {
65
54
  DeletePostRequestSchema: () => DeletePostRequestSchema,
66
55
  DeletePostResponseSchema: () => DeletePostResponseSchema,
67
56
  DeleteResultSchema: () => DeleteResultSchema,
57
+ ERROR_CATEGORIES: () => ERROR_CATEGORIES,
68
58
  EndpointRateLimitResponseSchema: () => EndpointRateLimitResponseSchema,
69
59
  EnhancedErrorResponseSchema: () => EnhancedErrorResponseSchema,
70
60
  EnhancedResponseMetaSchema: () => EnhancedResponseMetaSchema,
71
61
  EnhancedResponseSchema: () => EnhancedResponseSchema,
72
62
  ErrorDetailSchema: () => ErrorDetailSchema,
73
63
  ErrorResponseSchema: () => ErrorResponseSchema,
74
- LeaderboardQuerySchema: () => LeaderboardQuerySchema,
75
- LeaderboardResponseSchema: () => LeaderboardResponseSchema,
76
64
  LikePostRequestSchema: () => LikePostRequestSchema,
77
65
  LikePostResponseSchema: () => LikePostResponseSchema,
78
66
  LikeResultSchema: () => LikeResultSchema,
@@ -110,13 +98,17 @@ __export(index_exports, {
110
98
  ReplyToPostResponseSchema: () => ReplyToPostResponseSchema,
111
99
  RepostRequestSchema: () => RepostRequestSchema,
112
100
  RepostResponseSchema: () => RepostResponseSchema,
101
+ SUPPORTED_PLATFORMS: () => SUPPORTED_PLATFORMS,
113
102
  SuccessDetailSchema: () => SuccessDetailSchema,
103
+ SupportedPlatformSchema: () => SupportedPlatformSchema,
104
+ SystemApi: () => SystemApi,
114
105
  TargetSchema: () => TargetSchema,
106
+ TimePeriod: () => TimePeriod,
115
107
  UnlikePostRequestSchema: () => UnlikePostRequestSchema,
116
108
  UnlikePostResponseSchema: () => UnlikePostResponseSchema,
117
109
  UsageRateLimitSchema: () => UsageRateLimitSchema,
118
110
  UserProfileSchema: () => UserProfileSchema,
119
- clearAuthCookie: () => clearAuthCookie,
111
+ apiWrapper: () => apiWrapper,
120
112
  createApiResponse: () => createApiResponse,
121
113
  createEnhancedApiResponse: () => createEnhancedApiResponse,
122
114
  createEnhancedErrorResponse: () => createEnhancedErrorResponse,
@@ -125,10 +117,21 @@ __export(index_exports, {
125
117
  createMultiStatusResponse: () => createMultiStatusResponse,
126
118
  createNetworkError: () => createNetworkError,
127
119
  createSuccessDetail: () => createSuccessDetail,
128
- getAuthFromCookie: () => getAuthFromCookie,
129
- getCsrfToken: () => getCsrfToken,
120
+ enrichErrorWithContext: () => enrichErrorWithContext,
121
+ getErrorDetails: () => getErrorDetails,
122
+ getErrorMessage: () => getErrorMessage,
130
123
  handleErrorResponse: () => handleErrorResponse,
131
- storeAuthInCookie: () => storeAuthInCookie
124
+ isAuthError: () => isAuthError,
125
+ isContentError: () => isContentError,
126
+ isErrorOfCategory: () => isErrorOfCategory,
127
+ isMediaError: () => isMediaError,
128
+ isNetworkError: () => isNetworkError,
129
+ isPlatformError: () => isPlatformError,
130
+ isPlatformSupported: () => isPlatformSupported,
131
+ isPostError: () => isPostError,
132
+ isRateLimitError: () => isRateLimitError,
133
+ isRecoverableError: () => isRecoverableError,
134
+ isValidationError: () => isValidationError
132
135
  });
133
136
  module.exports = __toCommonJS(index_exports);
134
137
 
@@ -4193,19 +4196,22 @@ var z = /* @__PURE__ */ Object.freeze({
4193
4196
  });
4194
4197
 
4195
4198
  // ../types/dist/index.js
4196
- var PlatformSchema = z.enum([
4197
- "unknown",
4198
- "twitter"
4199
- // Add more platforms as they're implemented
4200
- // 'linkedin',
4201
- // 'facebook',
4202
- // 'instagram',
4203
- ]).describe("Social media platform");
4204
4199
  var Platform = /* @__PURE__ */ ((Platform2) => {
4205
4200
  Platform2["UNKNOWN"] = "unknown";
4206
4201
  Platform2["TWITTER"] = "twitter";
4207
4202
  return Platform2;
4208
4203
  })(Platform || {});
4204
+ var PlatformSchema = z.nativeEnum(Platform).describe("Social media platform");
4205
+ var SUPPORTED_PLATFORMS = [
4206
+ "twitter"
4207
+ /* TWITTER */
4208
+ // Add more platforms here as they're implemented
4209
+ ];
4210
+ var SupportedPlatformSchema = SUPPORTED_PLATFORMS.length > 0 ? z.enum(SUPPORTED_PLATFORMS) : z.never();
4211
+ SupportedPlatformSchema.describe("Currently supported social media platforms");
4212
+ function isPlatformSupported(platform) {
4213
+ return SUPPORTED_PLATFORMS.includes(platform);
4214
+ }
4209
4215
  var ApiResponseSchema = z.object({
4210
4216
  data: z.any().describe("Response data"),
4211
4217
  meta: z.object({
@@ -4813,13 +4819,21 @@ var EndpointRateLimitResponseSchema = z.object({
4813
4819
  endpoint: z.string().describe("API endpoint or action"),
4814
4820
  signerId: z.string().describe("NEAR account ID")
4815
4821
  }).describe("Endpoint rate limit response");
4816
- var LeaderboardQuerySchema = z.object({
4822
+ var TimePeriod = /* @__PURE__ */ ((TimePeriod2) => {
4823
+ TimePeriod2["ALL_TIME"] = "all";
4824
+ TimePeriod2["YEARLY"] = "yearly";
4825
+ TimePeriod2["MONTHLY"] = "monthly";
4826
+ TimePeriod2["WEEKLY"] = "weekly";
4827
+ TimePeriod2["DAILY"] = "daily";
4828
+ return TimePeriod2;
4829
+ })(TimePeriod || {});
4830
+ var ActivityLeaderboardQuerySchema = z.object({
4817
4831
  timeframe: z.enum(["day", "week", "month", "all"]).optional().describe(
4818
4832
  "Timeframe for the leaderboard"
4819
4833
  ),
4820
4834
  limit: z.string().optional().transform((val) => val ? parseInt(val, 10) : void 0).pipe(z.number().min(1).max(100).optional()).describe("Maximum number of results to return (1-100)"),
4821
4835
  offset: z.string().optional().transform((val) => val ? parseInt(val, 10) : void 0).pipe(z.number().min(0).optional()).describe("Offset for pagination")
4822
- }).describe("Leaderboard query");
4836
+ }).describe("Activity leaderboard query");
4823
4837
  var AccountActivityEntrySchema = z.object({
4824
4838
  signerId: z.string().describe("NEAR account ID"),
4825
4839
  totalPosts: z.number().describe("Total number of posts"),
@@ -4831,7 +4845,7 @@ var AccountActivityEntrySchema = z.object({
4831
4845
  rank: z.number().describe("Rank on the leaderboard"),
4832
4846
  lastActive: z.string().datetime().describe("Timestamp of last activity")
4833
4847
  }).describe("Account activity entry");
4834
- var LeaderboardResponseSchema = EnhancedResponseSchema(
4848
+ var ActivityLeaderboardResponseSchema = EnhancedResponseSchema(
4835
4849
  z.object({
4836
4850
  timeframe: z.enum(["day", "week", "month", "all"]).describe("Timeframe for the leaderboard"),
4837
4851
  entries: z.array(AccountActivityEntrySchema).describe("Leaderboard entries"),
@@ -4840,7 +4854,7 @@ var LeaderboardResponseSchema = EnhancedResponseSchema(
4840
4854
  offset: z.number().describe("Offset for pagination"),
4841
4855
  generatedAt: z.string().datetime().describe("Timestamp when the leaderboard was generated")
4842
4856
  })
4843
- ).describe("Leaderboard response");
4857
+ ).describe("Activity leaderboard response");
4844
4858
  var AccountActivityParamsSchema = z.object({
4845
4859
  signerId: z.string().describe("NEAR account ID")
4846
4860
  }).describe("Account activity params");
@@ -4936,6 +4950,168 @@ var ProfileRefreshResponseSchema = EnhancedResponseSchema(
4936
4950
  var import_near_sign_verify = require("near-sign-verify");
4937
4951
 
4938
4952
  // src/utils/error.ts
4953
+ var ERROR_CATEGORIES = {
4954
+ AUTH: [
4955
+ ApiErrorCode.UNAUTHORIZED,
4956
+ ApiErrorCode.FORBIDDEN
4957
+ ],
4958
+ VALIDATION: [
4959
+ ApiErrorCode.VALIDATION_ERROR,
4960
+ ApiErrorCode.INVALID_REQUEST
4961
+ ],
4962
+ NETWORK: [
4963
+ ApiErrorCode.NETWORK_ERROR
4964
+ ],
4965
+ PLATFORM: [
4966
+ ApiErrorCode.PLATFORM_ERROR,
4967
+ ApiErrorCode.PLATFORM_UNAVAILABLE
4968
+ ],
4969
+ CONTENT: [
4970
+ ApiErrorCode.CONTENT_POLICY_VIOLATION,
4971
+ ApiErrorCode.DUPLICATE_CONTENT
4972
+ ],
4973
+ RATE_LIMIT: [
4974
+ ApiErrorCode.RATE_LIMITED
4975
+ ],
4976
+ POST: [
4977
+ ApiErrorCode.POST_CREATION_FAILED,
4978
+ ApiErrorCode.THREAD_CREATION_FAILED,
4979
+ ApiErrorCode.POST_DELETION_FAILED,
4980
+ ApiErrorCode.POST_INTERACTION_FAILED
4981
+ ],
4982
+ MEDIA: [
4983
+ ApiErrorCode.MEDIA_UPLOAD_FAILED
4984
+ ]
4985
+ };
4986
+ function isErrorOfCategory(error, category) {
4987
+ if (error instanceof ApiError) {
4988
+ return category.includes(error.code);
4989
+ }
4990
+ if (error instanceof PlatformError) {
4991
+ return category.includes(error.code);
4992
+ }
4993
+ if (error && typeof error === "object" && "code" in error) {
4994
+ return category.includes(error.code);
4995
+ }
4996
+ return false;
4997
+ }
4998
+ function isAuthError(error) {
4999
+ return isErrorOfCategory(error, ERROR_CATEGORIES.AUTH);
5000
+ }
5001
+ function isValidationError(error) {
5002
+ return isErrorOfCategory(error, ERROR_CATEGORIES.VALIDATION);
5003
+ }
5004
+ function isNetworkError(error) {
5005
+ return isErrorOfCategory(error, ERROR_CATEGORIES.NETWORK);
5006
+ }
5007
+ function isPlatformError(error) {
5008
+ return isErrorOfCategory(error, ERROR_CATEGORIES.PLATFORM) || error instanceof PlatformError;
5009
+ }
5010
+ function isContentError(error) {
5011
+ return isErrorOfCategory(error, ERROR_CATEGORIES.CONTENT);
5012
+ }
5013
+ function isRateLimitError(error) {
5014
+ return isErrorOfCategory(error, ERROR_CATEGORIES.RATE_LIMIT);
5015
+ }
5016
+ function isPostError(error) {
5017
+ return isErrorOfCategory(error, ERROR_CATEGORIES.POST);
5018
+ }
5019
+ function isMediaError(error) {
5020
+ return isErrorOfCategory(error, ERROR_CATEGORIES.MEDIA);
5021
+ }
5022
+ function isRecoverableError(error) {
5023
+ if (error instanceof ApiError || error instanceof PlatformError) {
5024
+ return error.recoverable;
5025
+ }
5026
+ return false;
5027
+ }
5028
+ function getErrorMessage(error, defaultMessage = "An error occurred") {
5029
+ if (error instanceof Error) {
5030
+ return error.message || defaultMessage;
5031
+ }
5032
+ if (typeof error === "string") {
5033
+ return error;
5034
+ }
5035
+ if (error && typeof error === "object" && "message" in error) {
5036
+ return error.message || defaultMessage;
5037
+ }
5038
+ return defaultMessage;
5039
+ }
5040
+ function getErrorDetails(error) {
5041
+ if (error instanceof ApiError || error instanceof PlatformError) {
5042
+ return error.details;
5043
+ }
5044
+ if (error && typeof error === "object" && "details" in error) {
5045
+ return error.details;
5046
+ }
5047
+ return void 0;
5048
+ }
5049
+ function enrichErrorWithContext(error, context) {
5050
+ if (error instanceof ApiError) {
5051
+ return new ApiError(
5052
+ error.message,
5053
+ error.code,
5054
+ error.status,
5055
+ { ...error.details || {}, ...context },
5056
+ error.recoverable
5057
+ );
5058
+ }
5059
+ if (error instanceof PlatformError) {
5060
+ return new PlatformError(
5061
+ error.message,
5062
+ error.platform,
5063
+ error.code,
5064
+ error.recoverable,
5065
+ error.originalError,
5066
+ error.status,
5067
+ error.userId,
5068
+ { ...error.details || {}, ...context }
5069
+ );
5070
+ }
5071
+ const errorMessage = error instanceof Error ? error.message : String(error);
5072
+ return new ApiError(
5073
+ errorMessage || "An error occurred",
5074
+ ApiErrorCode.INTERNAL_ERROR,
5075
+ 500,
5076
+ { originalError: error, ...context },
5077
+ false
5078
+ );
5079
+ }
5080
+ async function apiWrapper(apiCall, context) {
5081
+ try {
5082
+ return await apiCall();
5083
+ } catch (error) {
5084
+ if (error instanceof Response) {
5085
+ try {
5086
+ const errorData = await error.json();
5087
+ throw enrichErrorWithContext(
5088
+ handleErrorResponse(errorData, error.status),
5089
+ context || {}
5090
+ );
5091
+ } catch (jsonError) {
5092
+ if (jsonError instanceof Error && jsonError.name === "SyntaxError") {
5093
+ throw enrichErrorWithContext(
5094
+ new ApiError(
5095
+ `API request failed with status ${error.status} and non-JSON response`,
5096
+ ApiErrorCode.NETWORK_ERROR,
5097
+ error.status,
5098
+ { originalResponse: error.statusText }
5099
+ ),
5100
+ context || {}
5101
+ );
5102
+ }
5103
+ throw jsonError;
5104
+ }
5105
+ }
5106
+ if (error instanceof ApiError || error instanceof PlatformError) {
5107
+ throw enrichErrorWithContext(error, context || {});
5108
+ }
5109
+ throw enrichErrorWithContext(
5110
+ error instanceof Error ? error : new Error(String(error)),
5111
+ context || {}
5112
+ );
5113
+ }
5114
+ }
4939
5115
  function handleErrorResponse(data, status) {
4940
5116
  const errorData = data?.error || {};
4941
5117
  const message = errorData?.message || data?.message || "An API error occurred";
@@ -4988,145 +5164,160 @@ function createNetworkError(error, url, timeout) {
4988
5164
  );
4989
5165
  }
4990
5166
 
4991
- // src/utils/cookie.ts
4992
- var import_js_cookie = __toESM(require("js-cookie"), 1);
4993
- var AUTH_COOKIE_NAME = "__crosspost_auth";
4994
- var CSRF_COOKIE_NAME = "XSRF-TOKEN";
4995
- var CSRF_HEADER_NAME = "X-CSRF-Token";
4996
- var AUTH_COOKIE_OPTIONS = {
4997
- secure: true,
4998
- sameSite: "lax",
4999
- // how could we make this none?
5000
- path: "/",
5001
- expires: 30
5002
- // 30 days
5003
- };
5004
- function getAuthFromCookie() {
5005
- try {
5006
- if (typeof document === "undefined") {
5007
- return void 0;
5008
- }
5009
- const cookieValue = import_js_cookie.default.get(AUTH_COOKIE_NAME);
5010
- if (!cookieValue) {
5011
- return void 0;
5167
+ // src/core/request.ts
5168
+ async function makeRequest(method, path, options, data, query) {
5169
+ let url = `${options.baseUrl}${path.startsWith("/") ? path : `/${path}`}`;
5170
+ if (query && Object.keys(query).length > 0) {
5171
+ const queryParams = new URLSearchParams();
5172
+ for (const [key, value] of Object.entries(query)) {
5173
+ if (value !== void 0 && value !== null) {
5174
+ queryParams.append(key, String(value));
5175
+ }
5012
5176
  }
5013
- return JSON.parse(cookieValue);
5014
- } catch (error) {
5015
- console.error("Failed to parse auth cookie:", error);
5016
- return void 0;
5017
- }
5018
- }
5019
- function storeAuthInCookie(authData) {
5020
- try {
5021
- if (typeof document === "undefined") {
5022
- return;
5177
+ const queryString = queryParams.toString();
5178
+ if (queryString) {
5179
+ url += `?${queryString}`;
5023
5180
  }
5024
- const cookieValue = JSON.stringify(authData);
5025
- import_js_cookie.default.set(AUTH_COOKIE_NAME, cookieValue, AUTH_COOKIE_OPTIONS);
5026
- } catch (error) {
5027
- console.error("Failed to store auth cookie:", error);
5028
- }
5029
- }
5030
- function clearAuthCookie() {
5031
- if (typeof document === "undefined") {
5032
- return;
5033
5181
  }
5034
- import_js_cookie.default.remove(AUTH_COOKIE_NAME, { path: AUTH_COOKIE_OPTIONS.path });
5035
- }
5036
- function getCsrfToken() {
5037
- if (typeof document === "undefined") {
5038
- return void 0;
5039
- }
5040
- return import_js_cookie.default.get(CSRF_COOKIE_NAME);
5041
- }
5042
-
5043
- // src/core/request.ts
5044
- async function makeRequest(method, path, options, data) {
5045
- const url = `${options.baseUrl}${path.startsWith("/") ? path : `/${path}`}`;
5046
- let lastError = null;
5047
- if (!options.signature) {
5182
+ if (!options.nearAuthData) {
5048
5183
  throw ApiError.unauthorized("Authentication required. Please provide NEAR signature.");
5049
5184
  }
5050
- for (let attempt = 0; attempt <= options.retries; attempt++) {
5051
- const controller = new AbortController();
5052
- const timeoutId = setTimeout(() => controller.abort(), options.timeout);
5053
- try {
5054
- const headers = {
5055
- "Content-Type": "application/json",
5056
- "Accept": "application/json",
5057
- "Authorization": `Bearer ${(0, import_near_sign_verify.createAuthToken)(options.signature)}`
5058
- };
5059
- if (method !== "GET") {
5060
- const csrfToken = getCsrfToken();
5061
- if (csrfToken) {
5062
- headers[CSRF_HEADER_NAME] = csrfToken;
5063
- }
5064
- }
5065
- const requestOptions = {
5066
- method,
5067
- headers,
5068
- body: method !== "GET" && data ? JSON.stringify(data) : void 0,
5069
- signal: controller.signal
5070
- };
5071
- const response = await fetch(url, requestOptions);
5072
- clearTimeout(timeoutId);
5073
- let responseData;
5185
+ const context = {
5186
+ method,
5187
+ path,
5188
+ url,
5189
+ retries: options.retries
5190
+ };
5191
+ return apiWrapper(async () => {
5192
+ let lastError = null;
5193
+ for (let attempt = 0; attempt <= options.retries; attempt++) {
5194
+ const controller = new AbortController();
5195
+ const timeoutId = setTimeout(() => controller.abort(), options.timeout);
5074
5196
  try {
5075
- responseData = await response.json();
5076
- } catch (jsonError) {
5077
- if (!response.ok) {
5197
+ const headers = {
5198
+ "Content-Type": "application/json",
5199
+ "Accept": "application/json",
5200
+ "Authorization": `Bearer ${(0, import_near_sign_verify.createAuthToken)(options.nearAuthData)}`
5201
+ };
5202
+ const requestOptions = {
5203
+ method,
5204
+ headers,
5205
+ body: method !== "GET" && data ? JSON.stringify(data) : void 0,
5206
+ signal: controller.signal
5207
+ };
5208
+ const response = await fetch(url, requestOptions);
5209
+ clearTimeout(timeoutId);
5210
+ let responseData;
5211
+ try {
5212
+ responseData = await response.json();
5213
+ } catch (jsonError) {
5214
+ if (!response.ok) {
5215
+ throw new ApiError(
5216
+ `API request failed with status ${response.status} and non-JSON response`,
5217
+ ApiErrorCode.NETWORK_ERROR,
5218
+ response.status,
5219
+ { originalStatusText: response.statusText }
5220
+ );
5221
+ }
5222
+ if (response.status === 204) return {};
5078
5223
  throw new ApiError(
5079
- `API request failed with status ${response.status} and non-JSON response`,
5080
- ApiErrorCode.NETWORK_ERROR,
5081
- // Or a more specific code
5082
- response.status,
5083
- { originalStatusText: response.statusText }
5224
+ `Failed to parse JSON response: ${jsonError instanceof Error ? jsonError.message : String(jsonError)}`,
5225
+ ApiErrorCode.INTERNAL_ERROR,
5226
+ response.status
5084
5227
  );
5085
5228
  }
5086
- if (response.status === 204) return {};
5087
- throw new ApiError(
5088
- `Failed to parse JSON response: ${jsonError instanceof Error ? jsonError.message : String(jsonError)}`,
5089
- ApiErrorCode.INTERNAL_ERROR,
5090
- // Or NETWORK_ERROR?
5091
- response.status
5092
- );
5093
- }
5094
- if (!response.ok) {
5095
- lastError = handleErrorResponse(responseData, response.status);
5096
- const shouldRetry = response.status >= 500 || lastError instanceof ApiError && lastError.recoverable;
5097
- if (shouldRetry && attempt < options.retries) {
5098
- await new Promise((resolve) => setTimeout(resolve, 1e3 * Math.pow(2, attempt)));
5099
- continue;
5229
+ if (!response.ok) {
5230
+ lastError = handleErrorResponse(responseData, response.status);
5231
+ const shouldRetry = response.status >= 500 || lastError instanceof ApiError && lastError.recoverable;
5232
+ if (shouldRetry && attempt < options.retries) {
5233
+ await new Promise((resolve) => setTimeout(resolve, 1e3 * Math.pow(2, attempt)));
5234
+ continue;
5235
+ }
5236
+ throw lastError;
5100
5237
  }
5101
- throw lastError;
5102
- }
5103
- if (responseData && typeof responseData === "object" && "success" in responseData && !responseData.success && responseData.error) {
5104
- lastError = handleErrorResponse(responseData, response.status);
5105
- const shouldRetry = lastError instanceof ApiError && lastError.recoverable;
5106
- if (shouldRetry && attempt < options.retries) {
5238
+ if (responseData && typeof responseData === "object" && "success" in responseData && !responseData.success && responseData.error) {
5239
+ lastError = handleErrorResponse(responseData, response.status);
5240
+ const shouldRetry = lastError instanceof ApiError && lastError.recoverable;
5241
+ if (shouldRetry && attempt < options.retries) {
5242
+ await new Promise((resolve) => setTimeout(resolve, 1e3 * Math.pow(2, attempt)));
5243
+ continue;
5244
+ }
5245
+ throw lastError;
5246
+ }
5247
+ return responseData;
5248
+ } catch (error) {
5249
+ clearTimeout(timeoutId);
5250
+ lastError = error instanceof Error ? error : new Error(String(error));
5251
+ const isNetworkError2 = error instanceof TypeError || error instanceof DOMException && error.name === "AbortError";
5252
+ if (isNetworkError2 && attempt < options.retries) {
5107
5253
  await new Promise((resolve) => setTimeout(resolve, 1e3 * Math.pow(2, attempt)));
5108
5254
  continue;
5109
5255
  }
5110
- throw lastError;
5111
- }
5112
- return responseData;
5113
- } catch (error) {
5114
- clearTimeout(timeoutId);
5115
- lastError = error;
5116
- const isNetworkError = error instanceof TypeError || error instanceof DOMException && error.name === "AbortError";
5117
- if (isNetworkError && attempt < options.retries) {
5118
- await new Promise((resolve) => setTimeout(resolve, 1e3 * Math.pow(2, attempt)));
5119
- continue;
5120
- }
5121
- if (!(error instanceof ApiError)) {
5122
- throw createNetworkError(error, url, options.timeout);
5256
+ if (!(error instanceof ApiError)) {
5257
+ throw createNetworkError(error, url, options.timeout);
5258
+ }
5259
+ throw error;
5123
5260
  }
5124
- throw error;
5125
5261
  }
5126
- }
5127
- throw lastError || new ApiError("Request failed after multiple retries", ApiErrorCode.INTERNAL_ERROR, 500);
5262
+ throw lastError || new ApiError("Request failed after multiple retries", ApiErrorCode.INTERNAL_ERROR, 500);
5263
+ }, context);
5128
5264
  }
5129
5265
 
5266
+ // src/api/activity.ts
5267
+ var ActivityApi = class {
5268
+ /**
5269
+ * Creates an instance of ActivityApi
5270
+ * @param options Request options
5271
+ */
5272
+ constructor(options) {
5273
+ this.options = options;
5274
+ }
5275
+ /**
5276
+ * Gets the global activity leaderboard
5277
+ * @param query Optional query parameters
5278
+ * @returns A promise resolving with the leaderboard response
5279
+ */
5280
+ async getLeaderboard(query) {
5281
+ return makeRequest(
5282
+ "GET",
5283
+ "/api/activity",
5284
+ this.options,
5285
+ void 0,
5286
+ query
5287
+ );
5288
+ }
5289
+ /**
5290
+ * Gets activity for a specific account
5291
+ * @param signerId The NEAR account ID
5292
+ * @param query Optional query parameters
5293
+ * @returns A promise resolving with the account activity response
5294
+ */
5295
+ async getAccountActivity(signerId, query) {
5296
+ return makeRequest(
5297
+ "GET",
5298
+ `/api/activity/${signerId}`,
5299
+ this.options,
5300
+ void 0,
5301
+ query
5302
+ );
5303
+ }
5304
+ /**
5305
+ * Gets posts for a specific account
5306
+ * @param signerId The NEAR account ID
5307
+ * @param query Optional query parameters
5308
+ * @returns A promise resolving with the account posts response
5309
+ */
5310
+ async getAccountPosts(signerId, query) {
5311
+ return makeRequest(
5312
+ "GET",
5313
+ `/api/activity/${signerId}/posts`,
5314
+ this.options,
5315
+ void 0,
5316
+ query
5317
+ );
5318
+ }
5319
+ };
5320
+
5130
5321
  // src/api/auth.ts
5131
5322
  var AuthApi = class {
5132
5323
  /**
@@ -5345,6 +5536,51 @@ var PostApi = class {
5345
5536
  }
5346
5537
  };
5347
5538
 
5539
+ // src/api/system.ts
5540
+ var SystemApi = class {
5541
+ /**
5542
+ * Creates an instance of SystemApi
5543
+ * @param options Request options
5544
+ */
5545
+ constructor(options) {
5546
+ this.options = options;
5547
+ }
5548
+ /**
5549
+ * Gets the current rate limit status
5550
+ * @returns A promise resolving with the rate limit response
5551
+ */
5552
+ async getRateLimits() {
5553
+ return makeRequest(
5554
+ "GET",
5555
+ "/api/rate-limit",
5556
+ this.options
5557
+ );
5558
+ }
5559
+ /**
5560
+ * Gets the rate limit status for a specific endpoint
5561
+ * @param endpoint The endpoint to get rate limit for
5562
+ * @returns A promise resolving with the endpoint rate limit response
5563
+ */
5564
+ async getEndpointRateLimit(endpoint) {
5565
+ return makeRequest(
5566
+ "GET",
5567
+ `/api/rate-limit/${endpoint}`,
5568
+ this.options
5569
+ );
5570
+ }
5571
+ /**
5572
+ * Gets the health status of the API
5573
+ * @returns A promise resolving with the health status
5574
+ */
5575
+ async getHealthStatus() {
5576
+ return makeRequest(
5577
+ "GET",
5578
+ "/health",
5579
+ this.options
5580
+ );
5581
+ }
5582
+ };
5583
+
5348
5584
  // src/core/config.ts
5349
5585
  var DEFAULT_CONFIG = {
5350
5586
  baseUrl: "https://open-crosspost-proxy.deno.dev/",
@@ -5362,29 +5598,35 @@ var CrosspostClient = class {
5362
5598
  const baseUrl = config.baseUrl || DEFAULT_CONFIG.baseUrl;
5363
5599
  const timeout = config.timeout || DEFAULT_CONFIG.timeout;
5364
5600
  const retries = config.retries ?? DEFAULT_CONFIG.retries;
5365
- const signature = config.signature || getAuthFromCookie();
5601
+ const nearAuthData = config.nearAuthData;
5366
5602
  this.options = {
5367
5603
  baseUrl,
5368
5604
  timeout,
5369
5605
  retries,
5370
- signature
5606
+ nearAuthData
5371
5607
  };
5372
5608
  this.auth = new AuthApi(this.options);
5373
5609
  this.post = new PostApi(this.options);
5610
+ this.activity = new ActivityApi(this.options);
5611
+ this.system = new SystemApi(this.options);
5612
+ }
5613
+ /**
5614
+ * Sets the authentication data (signature) for the client
5615
+ * @param nearAuthData The NEAR authentication data
5616
+ */
5617
+ setAuthentication(nearAuthData) {
5618
+ this.options.nearAuthData = nearAuthData;
5374
5619
  }
5375
5620
  /**
5376
- * Sets the authentication data (signature) for the client and stores it in a cookie
5621
+ * Checks if authentication data (signature) exists on client
5377
5622
  * @param signature The NEAR authentication data
5378
5623
  */
5379
- async setAuthentication(signature) {
5380
- this.options.signature = signature;
5381
- storeAuthInCookie(signature);
5624
+ isAuthenticated() {
5625
+ return !!this.options.nearAuthData;
5382
5626
  }
5383
5627
  };
5384
5628
  // Annotate the CommonJS export names for ESM import in node:
5385
5629
  0 && (module.exports = {
5386
- AUTH_COOKIE_NAME,
5387
- AUTH_COOKIE_OPTIONS,
5388
5630
  AccountActivityEntrySchema,
5389
5631
  AccountActivityParamsSchema,
5390
5632
  AccountActivityQuerySchema,
@@ -5393,6 +5635,9 @@ var CrosspostClient = class {
5393
5635
  AccountPostsParamsSchema,
5394
5636
  AccountPostsQuerySchema,
5395
5637
  AccountPostsResponseSchema,
5638
+ ActivityApi,
5639
+ ActivityLeaderboardQuerySchema,
5640
+ ActivityLeaderboardResponseSchema,
5396
5641
  AllRateLimitsResponseSchema,
5397
5642
  ApiError,
5398
5643
  ApiErrorCode,
@@ -5405,8 +5650,6 @@ var CrosspostClient = class {
5405
5650
  AuthStatusResponseSchema,
5406
5651
  AuthUrlResponseSchema,
5407
5652
  BaseError,
5408
- CSRF_COOKIE_NAME,
5409
- CSRF_HEADER_NAME,
5410
5653
  ConnectedAccountSchema,
5411
5654
  ConnectedAccountsResponseSchema,
5412
5655
  CreatePostRequestSchema,
@@ -5418,14 +5661,13 @@ var CrosspostClient = class {
5418
5661
  DeletePostRequestSchema,
5419
5662
  DeletePostResponseSchema,
5420
5663
  DeleteResultSchema,
5664
+ ERROR_CATEGORIES,
5421
5665
  EndpointRateLimitResponseSchema,
5422
5666
  EnhancedErrorResponseSchema,
5423
5667
  EnhancedResponseMetaSchema,
5424
5668
  EnhancedResponseSchema,
5425
5669
  ErrorDetailSchema,
5426
5670
  ErrorResponseSchema,
5427
- LeaderboardQuerySchema,
5428
- LeaderboardResponseSchema,
5429
5671
  LikePostRequestSchema,
5430
5672
  LikePostResponseSchema,
5431
5673
  LikeResultSchema,
@@ -5463,13 +5705,17 @@ var CrosspostClient = class {
5463
5705
  ReplyToPostResponseSchema,
5464
5706
  RepostRequestSchema,
5465
5707
  RepostResponseSchema,
5708
+ SUPPORTED_PLATFORMS,
5466
5709
  SuccessDetailSchema,
5710
+ SupportedPlatformSchema,
5711
+ SystemApi,
5467
5712
  TargetSchema,
5713
+ TimePeriod,
5468
5714
  UnlikePostRequestSchema,
5469
5715
  UnlikePostResponseSchema,
5470
5716
  UsageRateLimitSchema,
5471
5717
  UserProfileSchema,
5472
- clearAuthCookie,
5718
+ apiWrapper,
5473
5719
  createApiResponse,
5474
5720
  createEnhancedApiResponse,
5475
5721
  createEnhancedErrorResponse,
@@ -5478,8 +5724,19 @@ var CrosspostClient = class {
5478
5724
  createMultiStatusResponse,
5479
5725
  createNetworkError,
5480
5726
  createSuccessDetail,
5481
- getAuthFromCookie,
5482
- getCsrfToken,
5727
+ enrichErrorWithContext,
5728
+ getErrorDetails,
5729
+ getErrorMessage,
5483
5730
  handleErrorResponse,
5484
- storeAuthInCookie
5731
+ isAuthError,
5732
+ isContentError,
5733
+ isErrorOfCategory,
5734
+ isMediaError,
5735
+ isNetworkError,
5736
+ isPlatformError,
5737
+ isPlatformSupported,
5738
+ isPostError,
5739
+ isRateLimitError,
5740
+ isRecoverableError,
5741
+ isValidationError
5485
5742
  });