@singi-labs/sifa-sdk 0.19.53 → 0.19.54
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/badge/index.cjs +18 -2
- package/dist/badge/index.cjs.map +1 -1
- package/dist/index.cjs +2 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +3 -3
- package/dist/index.d.ts +3 -3
- package/dist/index.js +1 -1
- package/dist/{network-map-C-p-k3gB.d.cts → network-map-Bj-s4akz.d.cts} +2 -2
- package/dist/{network-map-CnVlBE0G.d.ts → network-map-v_4bPC5p.d.ts} +2 -2
- package/dist/{org-Bp4mNT8K.d.ts → org-DTHVhan9.d.ts} +1 -1
- package/dist/{org-CFzRg61Q.d.cts → org-mUwICoPr.d.cts} +1 -1
- package/dist/{profile-summary-Qtfk-52i.d.ts → profile-summary-BXG--PFN.d.ts} +1 -1
- package/dist/{profile-summary-C_wdHGj6.d.cts → profile-summary-D-Z_C6ZC.d.cts} +1 -1
- package/dist/query/client.js +26 -6
- package/dist/query/client.js.map +1 -1
- package/dist/query/fetchers/index.cjs +26 -6
- package/dist/query/fetchers/index.cjs.map +1 -1
- package/dist/query/fetchers/index.d.cts +5 -5
- package/dist/query/fetchers/index.d.ts +5 -5
- package/dist/query/hooks/index.cjs +26 -6
- package/dist/query/hooks/index.cjs.map +1 -1
- package/dist/query/hooks/index.d.cts +3 -3
- package/dist/query/hooks/index.d.ts +3 -3
- package/dist/query/index.cjs +26 -6
- package/dist/query/index.cjs.map +1 -1
- package/dist/query/index.d.cts +8 -8
- package/dist/query/index.d.ts +8 -8
- package/dist/roadmap/index.js +1 -1
- package/dist/roadmap/index.js.map +1 -1
- package/dist/schemas/write/external-account.js +2 -1
- package/dist/schemas/write/external-account.js.map +1 -1
- package/dist/schemas/write/index.cjs +2 -1
- package/dist/schemas/write/index.cjs.map +1 -1
- package/dist/schemas/write/index.d.cts +1 -1
- package/dist/schemas/write/index.d.ts +1 -1
- package/dist/{types-DAGqE0b9.d.cts → types-BeEuVVBo.d.cts} +11 -1
- package/dist/{types-CK8KgdqA.d.ts → types-Dblq-u-n.d.ts} +11 -1
- package/dist/{use-org-notification-emails-Dk084Rrw.d.cts → use-org-notification-emails-C8Z0U5rH.d.cts} +2 -2
- package/dist/{use-org-notification-emails-CJ0hKqco.d.ts → use-org-notification-emails-CgEZnFTp.d.ts} +2 -2
- package/package.json +1 -1
package/dist/index.d.cts
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import { P as ProfileSkill, a as ProfilePresentationDelivery, L as LocationValue, b as PdsProviderInfo, c as Profile, A as AccountFacetMode, d as ProfilePosition, e as ProfileCertification, f as ProfileEducation, g as ProfileHonor, h as ProfileLanguage, i as ProfileProject, j as ProfilePublication, k as ProfileInvolvement, R as RelatedIdentifier } from './index-DmlIG8sJ.cjs';
|
|
2
2
|
export { l as ActiveApp, m as ActorCard, n as AuthorSuggestion, C as CoSpeaker, E as Endorsement, o as EndorsementData, p as ExternalAccount, q as ExternalAccountKeytraceClaim, F as FeedItem, r as LanguageProficiency, O as OrgAddressView, s as OrgFloorVerdict, t as OrgLinkView, u as OrgProfileView, v as PROJECT_ROLES, w as PresentationLinkView, x as ProfileCourse, y as ProfileIndustry, z as ProfileInvestment, B as ProfileInvestmentLink, D as ProfileInvolvementLink, G as ProfileLocation, H as ProfileOverrideSource, I as ProfilePresentation, J as ProfileVolunteering, K as ProjectMemberCard, M as ProjectRole, N as PublicationContributor, Q as RecognizedEntity, S as SkillRef, T as SkillSuggestion, U as TrustStat, V as VerifiedAccount } from './index-DmlIG8sJ.cjs';
|
|
3
|
-
import { S as SearchFilters } from './types-
|
|
4
|
-
export { A as ADULT_CONTENT_LABELS, a as ActiveAppView, b as ActivityLabel, c as AdultContentLabel, d as AtfundLinkView, C as CertificationView, e as CoSpeakerView, f as ContributorView, g as CourseView, D as DurationView, E as EducationView, h as ExternalAccountView, H as HonorView, I as IndustryDomain, i as InvolvementLinkView, j as InvolvementView, L as LanguageView, P as PositionView, k as PresentationDeliveryView, l as PresentationView, m as ProfileLocationView, n as ProfileView, o as ProjectMemberView, p as ProjectView, q as PublicationView, R as RepoCollectionGroup, r as RepoDeleteOutcome, s as RepoDeleteRecordResult, t as RepoDeleteResult, u as RepoGroupDefinition, v as RepoGroupId, w as RepoInventory, x as RepoRecordLabel, y as RepoRecordSummary, z as SIFA_REPO_GROUPS, B as SkillView, V as VolunteeringView, F as describeSifaRecord, G as hasAdultContent, J as repoGroupForCollection } from './types-
|
|
3
|
+
import { S as SearchFilters } from './types-BeEuVVBo.cjs';
|
|
4
|
+
export { A as ADULT_CONTENT_LABELS, a as ActiveAppView, b as ActivityLabel, c as AdultContentLabel, d as AtfundLinkView, C as CertificationView, e as CoSpeakerView, f as ContributorView, g as CourseView, D as DurationView, E as EducationView, h as ExternalAccountView, H as HonorView, I as IndustryDomain, i as InvolvementLinkView, j as InvolvementView, L as LanguageView, P as PositionView, k as PresentationDeliveryView, l as PresentationView, m as ProfileLocationView, n as ProfileView, o as ProjectMemberView, p as ProjectView, q as PublicationView, R as RepoCollectionGroup, r as RepoDeleteOutcome, s as RepoDeleteRecordResult, t as RepoDeleteResult, u as RepoGroupDefinition, v as RepoGroupId, w as RepoInventory, x as RepoRecordLabel, y as RepoRecordSummary, z as SIFA_REPO_GROUPS, B as SkillView, V as VolunteeringView, F as describeSifaRecord, G as hasAdultContent, J as repoGroupForCollection } from './types-BeEuVVBo.cjs';
|
|
5
5
|
import { P as PresentationDuration, a as ProfilePresentationDeliveryRecord, b as ProfilePresentationRecord, O as OrgProfileRecord } from './profile-investment-BiHM7C5q.cjs';
|
|
6
6
|
export { A as ArtifactLink, c as ArtifactLinkSchema, d as AtmosphereFeedItem, e as AtmosphereFeedItemSchema, B as BlobRef, f as BlobRefSchema, E as EndorsementConfirmationRecord, g as EndorsementConfirmationRecordSchema, h as EndorsementRecord, i as EndorsementRecordSchema, F as FeedActor, j as FeedActorSchema, k as FeedCursor, l as FollowFeedItem, m as FollowFeedItemSchema, n as FollowFeedPage, o as FollowFeedPageSchema, G as GraphFollowRecord, p as GraphFollowRecordSchema, I as InvestmentAmountSchema, q as OrgEmploymentAttestationRecord, r as OrgEmploymentAttestationRecordSchema, s as OrgProfileRecordSchema, t as PROFILE_INVESTMENT_NSID, u as PROFILE_INVOLVEMENT_NSID, v as PresentationDurationSchema, w as PresentationLink, x as PresentationLinkSchema, y as ProfileCertificationRecord, z as ProfileCertificationRecordSchema, C as ProfileCourseRecord, D as ProfileCourseRecordSchema, H as ProfileEducationRecord, J as ProfileEducationRecordSchema, K as ProfileExternalAccountRecord, L as ProfileExternalAccountRecordSchema, M as ProfileHonorRecord, N as ProfileHonorRecordSchema, Q as ProfileInvestmentRecordSchema, R as ProfileInvolvementRecord, S as ProfileInvolvementRecordSchema, T as ProfileLanguageRecord, U as ProfileLanguageRecordSchema, V as ProfilePositionRecord, W as ProfilePositionRecordSchema, X as ProfilePresentationDeliveryRecordSchema, Y as ProfilePresentationRecordSchema, Z as ProfileProjectRecord, _ as ProfileProjectRecordSchema, $ as ProfilePublicationRecord, a0 as ProfilePublicationRecordSchema, a1 as ProfileSelfRecord, a2 as ProfileSelfRecordSchema, a3 as ProfileSkillRecord, a4 as ProfileSkillRecordSchema, a5 as ProfileVolunteeringRecord, a6 as ProfileVolunteeringRecordSchema, a7 as PublicationAuthor, a8 as PublicationAuthorSchema, a9 as RelatedIdentifierSchema, aa as SifaFeedItem, ab as SifaFeedItemSchema, ac as decodeFeedCursor, ad as encodeFeedCursor, ae as makeGraphFollowRecordSchema } from './profile-investment-BiHM7C5q.cjs';
|
|
7
7
|
import { z } from 'zod';
|
|
8
|
-
export { P as ProfileSummary, S as SummarizeProfileViewOptions, s as summarizeProfileView } from './profile-summary-
|
|
8
|
+
export { P as ProfileSummary, S as SummarizeProfileViewOptions, s as summarizeProfileView } from './profile-summary-D-Z_C6ZC.cjs';
|
|
9
9
|
import { E as EntitySearchResult } from './follow-profile-D1l6pulB.cjs';
|
|
10
10
|
export { a as EntityImportSearchResponse, b as EntityImportSearchResponseSchema, c as EntityMintDomainResponse, d as EntityMintDomainResponseSchema, e as EntityResolveDomainRequest, f as EntityResolveDomainRequestSchema, g as EntityResolveDomainResponse, h as EntityResolveDomainResponseSchema, i as EntitySearchResponse, j as EntitySearchResponseSchema, k as EntitySearchResultSchema, l as EntitySelectRequest, m as EntitySelectRequestSchema, n as EntitySelectResponse, o as EntitySelectResponseSchema, F as FEATURE_FLAGS, p as FeatureAllowlistEntry, q as FeatureAllowlistEntrySchema, r as FeatureFlag, s as FollowProfileItem, t as FollowProfilePage, u as FollowProfilePageSchema, v as FollowProfileSchema } from './follow-profile-D1l6pulB.cjs';
|
|
11
11
|
import { A as AgentRef } from './shared-v0vl5hov.cjs';
|
package/dist/index.d.ts
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import { P as ProfileSkill, a as ProfilePresentationDelivery, L as LocationValue, b as PdsProviderInfo, c as Profile, A as AccountFacetMode, d as ProfilePosition, e as ProfileCertification, f as ProfileEducation, g as ProfileHonor, h as ProfileLanguage, i as ProfileProject, j as ProfilePublication, k as ProfileInvolvement, R as RelatedIdentifier } from './index-D9GC0u__.js';
|
|
2
2
|
export { l as ActiveApp, m as ActorCard, n as AuthorSuggestion, C as CoSpeaker, E as Endorsement, o as EndorsementData, p as ExternalAccount, q as ExternalAccountKeytraceClaim, F as FeedItem, r as LanguageProficiency, O as OrgAddressView, s as OrgFloorVerdict, t as OrgLinkView, u as OrgProfileView, v as PROJECT_ROLES, w as PresentationLinkView, x as ProfileCourse, y as ProfileIndustry, z as ProfileInvestment, B as ProfileInvestmentLink, D as ProfileInvolvementLink, G as ProfileLocation, H as ProfileOverrideSource, I as ProfilePresentation, J as ProfileVolunteering, K as ProjectMemberCard, M as ProjectRole, N as PublicationContributor, Q as RecognizedEntity, S as SkillRef, T as SkillSuggestion, U as TrustStat, V as VerifiedAccount } from './index-D9GC0u__.js';
|
|
3
|
-
import { S as SearchFilters } from './types-
|
|
4
|
-
export { A as ADULT_CONTENT_LABELS, a as ActiveAppView, b as ActivityLabel, c as AdultContentLabel, d as AtfundLinkView, C as CertificationView, e as CoSpeakerView, f as ContributorView, g as CourseView, D as DurationView, E as EducationView, h as ExternalAccountView, H as HonorView, I as IndustryDomain, i as InvolvementLinkView, j as InvolvementView, L as LanguageView, P as PositionView, k as PresentationDeliveryView, l as PresentationView, m as ProfileLocationView, n as ProfileView, o as ProjectMemberView, p as ProjectView, q as PublicationView, R as RepoCollectionGroup, r as RepoDeleteOutcome, s as RepoDeleteRecordResult, t as RepoDeleteResult, u as RepoGroupDefinition, v as RepoGroupId, w as RepoInventory, x as RepoRecordLabel, y as RepoRecordSummary, z as SIFA_REPO_GROUPS, B as SkillView, V as VolunteeringView, F as describeSifaRecord, G as hasAdultContent, J as repoGroupForCollection } from './types-
|
|
3
|
+
import { S as SearchFilters } from './types-Dblq-u-n.js';
|
|
4
|
+
export { A as ADULT_CONTENT_LABELS, a as ActiveAppView, b as ActivityLabel, c as AdultContentLabel, d as AtfundLinkView, C as CertificationView, e as CoSpeakerView, f as ContributorView, g as CourseView, D as DurationView, E as EducationView, h as ExternalAccountView, H as HonorView, I as IndustryDomain, i as InvolvementLinkView, j as InvolvementView, L as LanguageView, P as PositionView, k as PresentationDeliveryView, l as PresentationView, m as ProfileLocationView, n as ProfileView, o as ProjectMemberView, p as ProjectView, q as PublicationView, R as RepoCollectionGroup, r as RepoDeleteOutcome, s as RepoDeleteRecordResult, t as RepoDeleteResult, u as RepoGroupDefinition, v as RepoGroupId, w as RepoInventory, x as RepoRecordLabel, y as RepoRecordSummary, z as SIFA_REPO_GROUPS, B as SkillView, V as VolunteeringView, F as describeSifaRecord, G as hasAdultContent, J as repoGroupForCollection } from './types-Dblq-u-n.js';
|
|
5
5
|
import { P as PresentationDuration, a as ProfilePresentationDeliveryRecord, b as ProfilePresentationRecord, O as OrgProfileRecord } from './profile-investment-BiHM7C5q.js';
|
|
6
6
|
export { A as ArtifactLink, c as ArtifactLinkSchema, d as AtmosphereFeedItem, e as AtmosphereFeedItemSchema, B as BlobRef, f as BlobRefSchema, E as EndorsementConfirmationRecord, g as EndorsementConfirmationRecordSchema, h as EndorsementRecord, i as EndorsementRecordSchema, F as FeedActor, j as FeedActorSchema, k as FeedCursor, l as FollowFeedItem, m as FollowFeedItemSchema, n as FollowFeedPage, o as FollowFeedPageSchema, G as GraphFollowRecord, p as GraphFollowRecordSchema, I as InvestmentAmountSchema, q as OrgEmploymentAttestationRecord, r as OrgEmploymentAttestationRecordSchema, s as OrgProfileRecordSchema, t as PROFILE_INVESTMENT_NSID, u as PROFILE_INVOLVEMENT_NSID, v as PresentationDurationSchema, w as PresentationLink, x as PresentationLinkSchema, y as ProfileCertificationRecord, z as ProfileCertificationRecordSchema, C as ProfileCourseRecord, D as ProfileCourseRecordSchema, H as ProfileEducationRecord, J as ProfileEducationRecordSchema, K as ProfileExternalAccountRecord, L as ProfileExternalAccountRecordSchema, M as ProfileHonorRecord, N as ProfileHonorRecordSchema, Q as ProfileInvestmentRecordSchema, R as ProfileInvolvementRecord, S as ProfileInvolvementRecordSchema, T as ProfileLanguageRecord, U as ProfileLanguageRecordSchema, V as ProfilePositionRecord, W as ProfilePositionRecordSchema, X as ProfilePresentationDeliveryRecordSchema, Y as ProfilePresentationRecordSchema, Z as ProfileProjectRecord, _ as ProfileProjectRecordSchema, $ as ProfilePublicationRecord, a0 as ProfilePublicationRecordSchema, a1 as ProfileSelfRecord, a2 as ProfileSelfRecordSchema, a3 as ProfileSkillRecord, a4 as ProfileSkillRecordSchema, a5 as ProfileVolunteeringRecord, a6 as ProfileVolunteeringRecordSchema, a7 as PublicationAuthor, a8 as PublicationAuthorSchema, a9 as RelatedIdentifierSchema, aa as SifaFeedItem, ab as SifaFeedItemSchema, ac as decodeFeedCursor, ad as encodeFeedCursor, ae as makeGraphFollowRecordSchema } from './profile-investment-BiHM7C5q.js';
|
|
7
7
|
import { z } from 'zod';
|
|
8
|
-
export { P as ProfileSummary, S as SummarizeProfileViewOptions, s as summarizeProfileView } from './profile-summary-
|
|
8
|
+
export { P as ProfileSummary, S as SummarizeProfileViewOptions, s as summarizeProfileView } from './profile-summary-BXG--PFN.js';
|
|
9
9
|
import { E as EntitySearchResult } from './follow-profile-D1l6pulB.js';
|
|
10
10
|
export { a as EntityImportSearchResponse, b as EntityImportSearchResponseSchema, c as EntityMintDomainResponse, d as EntityMintDomainResponseSchema, e as EntityResolveDomainRequest, f as EntityResolveDomainRequestSchema, g as EntityResolveDomainResponse, h as EntityResolveDomainResponseSchema, i as EntitySearchResponse, j as EntitySearchResponseSchema, k as EntitySearchResultSchema, l as EntitySelectRequest, m as EntitySelectRequestSchema, n as EntitySelectResponse, o as EntitySelectResponseSchema, F as FEATURE_FLAGS, p as FeatureAllowlistEntry, q as FeatureAllowlistEntrySchema, r as FeatureFlag, s as FollowProfileItem, t as FollowProfilePage, u as FollowProfilePageSchema, v as FollowProfileSchema } from './follow-profile-D1l6pulB.js';
|
|
11
11
|
import { A as AgentRef } from './shared-v0vl5hov.js';
|
package/dist/index.js
CHANGED
|
@@ -350,7 +350,7 @@ import {
|
|
|
350
350
|
roadmapIssueUrl
|
|
351
351
|
} from "./roadmap/index.js";
|
|
352
352
|
import { SIFA_REPO_GROUPS, describeSifaRecord, repoGroupForCollection } from "./repo/index.js";
|
|
353
|
-
var SIFA_SDK_VERSION = "0.19.
|
|
353
|
+
var SIFA_SDK_VERSION = "0.19.54";
|
|
354
354
|
export {
|
|
355
355
|
ACTIVITY_TIERS,
|
|
356
356
|
ACTIVITY_VERBS,
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { c as Profile, d as ProfilePosition, S as SkillRef, w as PresentationLinkView } from './index-DmlIG8sJ.cjs';
|
|
2
|
-
import { K as SifaApiConfig, M as ApiFetchOptions, n as ProfileView, N as CreateResult, W as WriteResult } from './types-
|
|
3
|
-
import { S as SummarizeProfileViewOptions, P as ProfileSummary } from './profile-summary-
|
|
2
|
+
import { K as SifaApiConfig, M as ApiFetchOptions, n as ProfileView, N as CreateResult, W as WriteResult } from './types-BeEuVVBo.cjs';
|
|
3
|
+
import { S as SummarizeProfileViewOptions, P as ProfileSummary } from './profile-summary-D-Z_C6ZC.cjs';
|
|
4
4
|
import { i as EntitySearchResponse, E as EntitySearchResult, c as EntityMintDomainResponse, g as EntityResolveDomainResponse, l as EntitySelectRequest, n as EntitySelectResponse } from './follow-profile-D1l6pulB.cjs';
|
|
5
5
|
import { z } from 'zod';
|
|
6
6
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { c as Profile, d as ProfilePosition, S as SkillRef, w as PresentationLinkView } from './index-D9GC0u__.js';
|
|
2
|
-
import { K as SifaApiConfig, M as ApiFetchOptions, n as ProfileView, N as CreateResult, W as WriteResult } from './types-
|
|
3
|
-
import { S as SummarizeProfileViewOptions, P as ProfileSummary } from './profile-summary-
|
|
2
|
+
import { K as SifaApiConfig, M as ApiFetchOptions, n as ProfileView, N as CreateResult, W as WriteResult } from './types-Dblq-u-n.js';
|
|
3
|
+
import { S as SummarizeProfileViewOptions, P as ProfileSummary } from './profile-summary-BXG--PFN.js';
|
|
4
4
|
import { i as EntitySearchResponse, E as EntitySearchResult, c as EntityMintDomainResponse, g as EntityResolveDomainResponse, l as EntitySelectRequest, n as EntitySelectResponse } from './follow-profile-D1l6pulB.js';
|
|
5
5
|
import { z } from 'zod';
|
|
6
6
|
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { W as WriteResult, K as SifaApiConfig, M as ApiFetchOptions, N as CreateResult, b as ActivityLabel, t as RepoDeleteResult, w as RepoInventory } from './types-
|
|
1
|
+
import { W as WriteResult, K as SifaApiConfig, M as ApiFetchOptions, N as CreateResult, b as ActivityLabel, t as RepoDeleteResult, w as RepoInventory } from './types-Dblq-u-n.js';
|
|
2
2
|
import { p as ExternalAccount } from './index-D9GC0u__.js';
|
|
3
3
|
import { s as FollowProfileItem, p as FeatureAllowlistEntry, r as FeatureFlag } from './follow-profile-D1l6pulB.js';
|
|
4
4
|
import { z } from 'zod';
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { W as WriteResult, K as SifaApiConfig, M as ApiFetchOptions, N as CreateResult, b as ActivityLabel, t as RepoDeleteResult, w as RepoInventory } from './types-
|
|
1
|
+
import { W as WriteResult, K as SifaApiConfig, M as ApiFetchOptions, N as CreateResult, b as ActivityLabel, t as RepoDeleteResult, w as RepoInventory } from './types-BeEuVVBo.cjs';
|
|
2
2
|
import { p as ExternalAccount } from './index-DmlIG8sJ.cjs';
|
|
3
3
|
import { s as FollowProfileItem, p as FeatureAllowlistEntry, r as FeatureFlag } from './follow-profile-D1l6pulB.cjs';
|
|
4
4
|
import { z } from 'zod';
|
package/dist/query/client.js
CHANGED
|
@@ -2,16 +2,27 @@
|
|
|
2
2
|
var ApiError = class extends Error {
|
|
3
3
|
status;
|
|
4
4
|
body;
|
|
5
|
-
|
|
5
|
+
/** Seconds until a rate limit resets, read from the headers of a 429. */
|
|
6
|
+
retryAfterSeconds;
|
|
7
|
+
constructor(message, status, body, retryAfterSeconds) {
|
|
6
8
|
super(message);
|
|
7
9
|
this.name = "ApiError";
|
|
8
10
|
this.status = status;
|
|
9
11
|
this.body = body;
|
|
12
|
+
if (retryAfterSeconds !== void 0) this.retryAfterSeconds = retryAfterSeconds;
|
|
10
13
|
}
|
|
11
14
|
};
|
|
12
15
|
var DEFAULT_TIMEOUT_MS = 1e4;
|
|
13
16
|
var MAX_RATE_LIMIT_RETRIES = 3;
|
|
14
17
|
var RATE_LIMIT_RETRY_CAP_SECONDS = 3;
|
|
18
|
+
var RATE_LIMIT_RESET_HEADERS = ["retry-after", "x-ratelimit-reset"];
|
|
19
|
+
function parseRetryAfterSeconds(headers) {
|
|
20
|
+
for (const name of RATE_LIMIT_RESET_HEADERS) {
|
|
21
|
+
const seconds = Number.parseInt(headers.get(name) ?? "", 10);
|
|
22
|
+
if (Number.isFinite(seconds) && seconds > 0) return seconds;
|
|
23
|
+
}
|
|
24
|
+
return void 0;
|
|
25
|
+
}
|
|
15
26
|
function encodeIdentifier(value) {
|
|
16
27
|
let decoded = value;
|
|
17
28
|
try {
|
|
@@ -63,7 +74,12 @@ async function apiFetch(config, path, options = {}) {
|
|
|
63
74
|
errBody = void 0;
|
|
64
75
|
}
|
|
65
76
|
}
|
|
66
|
-
throw new ApiError(
|
|
77
|
+
throw new ApiError(
|
|
78
|
+
`Sifa API ${res.status} on ${path}`,
|
|
79
|
+
res.status,
|
|
80
|
+
errBody,
|
|
81
|
+
res.status === 429 ? parseRetryAfterSeconds(res.headers) : void 0
|
|
82
|
+
);
|
|
67
83
|
}
|
|
68
84
|
if (res.status === 204 || res.status === 205) {
|
|
69
85
|
return void 0;
|
|
@@ -80,10 +96,14 @@ async function apiFetchOrNull(config, path, options = {}) {
|
|
|
80
96
|
throw e;
|
|
81
97
|
}
|
|
82
98
|
}
|
|
83
|
-
function extractWriteError(
|
|
84
|
-
const body =
|
|
99
|
+
function extractWriteError(e) {
|
|
100
|
+
const body = e.body && typeof e.body === "object" ? e.body : {};
|
|
85
101
|
return {
|
|
86
|
-
|
|
102
|
+
// Fastify puts the detail in `message` and the status phrase in `error`;
|
|
103
|
+
// sifa-api's own handlers (and the rate limiter) only set `error`.
|
|
104
|
+
error: body.message ?? body.error ?? `Request failed (${e.status})`,
|
|
105
|
+
status: e.status,
|
|
106
|
+
...e.retryAfterSeconds !== void 0 ? { retryAfterSeconds: e.retryAfterSeconds } : {},
|
|
87
107
|
...body.pdsHost ? { pdsHost: body.pdsHost } : {}
|
|
88
108
|
};
|
|
89
109
|
}
|
|
@@ -97,7 +117,7 @@ async function apiWrite(config, path, method, options = {}) {
|
|
|
97
117
|
return { success: true, ...data ?? {} };
|
|
98
118
|
} catch (e) {
|
|
99
119
|
if (e instanceof ApiError) {
|
|
100
|
-
return { success: false, ...extractWriteError(e
|
|
120
|
+
return { success: false, ...extractWriteError(e) };
|
|
101
121
|
}
|
|
102
122
|
return { success: false, error: "Network error" };
|
|
103
123
|
}
|
package/dist/query/client.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/query/client.ts"],"sourcesContent":["/**\n * Foundation HTTP client for talking to the Sifa AppView.\n *\n * Stateless. Consumers supply a {@link SifaApiConfig} per call (the React\n * hooks read it from context; non-React consumers pass it explicitly). No\n * singletons, no module-level state.\n */\n\n/** Configuration passed to every fetcher. */\nexport interface SifaApiConfig {\n /** Base URL of the sifa-api AppView, e.g. `https://api.sifa.id`. No trailing slash. */\n baseUrl: string;\n /**\n * Optional fetch implementation. Defaults to {@link globalThis.fetch}.\n * Lets Next.js consumers pass their cache-enhanced fetch; node/Expo\n * consumers can leave this unset.\n */\n fetch?: typeof fetch;\n /**\n * Optional per-request auth-token minter for auth-required reads. The NATIVE\n * app supplies this (it has no sifa-api session cookie): given a method NSID\n * (`lxm`), it mints a short-lived AT Protocol service-auth JWT on the user's\n * PDS (see the SDK's `/atproto` `mintServiceAuthToken`) and returns it; the\n * fetcher attaches it as `Authorization: Bearer`. Web omits this and relies on\n * its session cookie (`credentials: 'include'`). Return `null` to send no\n * token. See `sifa-api` `createIdentityMiddleware`.\n */\n getAuthToken?: (lxm: string) => Promise<string | null>;\n}\n\n/** Options accepted by {@link apiFetch}. */\nexport interface ApiFetchOptions {\n method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';\n /** Request body. Serialized to JSON automatically. */\n body?: unknown;\n /** AbortSignal. Defaults to `AbortSignal.timeout(timeoutMs)` if `timeoutMs` is set. */\n signal?: AbortSignal;\n /** Per-call timeout in milliseconds. Default: 10_000. Ignored if `signal` is provided. */\n timeoutMs?: number;\n /** Retry on HTTP 429 up to 3 times with the server's `Retry-After` delay (capped at 3s). */\n retryOn429?: boolean;\n /** Additional headers. `Content-Type: application/json` is set automatically when `body` is present. */\n headers?: Record<string, string>;\n credentials?: RequestCredentials;\n cache?: RequestCache;\n /**\n * Next.js-specific cache hints. Ignored on non-Next runtimes. Passed\n * through transparently as part of {@link RequestInit}.\n */\n next?: { revalidate?: number | false; tags?: string[] };\n}\n\n/** Error thrown by {@link apiFetch} on non-2xx responses. */\nexport class ApiError extends Error {\n readonly status: number;\n readonly body: unknown;\n\n constructor(message: string, status: number, body?: unknown) {\n super(message);\n this.name = 'ApiError';\n this.status = status;\n this.body = body;\n }\n}\n\nconst DEFAULT_TIMEOUT_MS = 10_000;\nconst MAX_RATE_LIMIT_RETRIES = 3;\nconst RATE_LIMIT_RETRY_CAP_SECONDS = 3;\n\n/**\n * Encode a handle or DID for safe interpolation into a request path,\n * idempotently.\n *\n * Plain {@link encodeURIComponent} double-encodes an already-encoded\n * identifier: Next.js hands route params to RSC pages percent-encoded on a\n * hard navigation (`did%3Aplc%3A...`) but decoded on client-side navigation\n * (`did:plc:...`). Encoding the former again turns `%` into `%25`, so the\n * AppView reads `did%3A...` as a literal handle, finds no match, and 404s —\n * which is why DID profile links broke on direct visits but worked when\n * clicked within the app.\n *\n * AT identifiers (handles are domain names, DIDs are `did:method:...`) never\n * contain a literal `%`, so decoding a decoded value is a no-op. A malformed\n * percent sequence (lone `%`) makes {@link decodeURIComponent} throw; in that\n * case we keep the original value so behaviour matches the prior bare\n * `encodeURIComponent`.\n */\nexport function encodeIdentifier(value: string): string {\n let decoded = value;\n try {\n decoded = decodeURIComponent(value);\n } catch {\n // Malformed percent-encoding — fall back to the raw value.\n }\n return encodeURIComponent(decoded);\n}\n\n/**\n * Generic fetcher used by all SDK query and mutation functions.\n *\n * Returns parsed JSON typed as `T`. Throws {@link ApiError} on non-2xx\n * responses. Use {@link apiFetchOrNull} when 404 should resolve to `null`\n * instead.\n */\nexport async function apiFetch<T = unknown>(\n config: SifaApiConfig,\n path: string,\n options: ApiFetchOptions = {},\n): Promise<T> {\n const fetchFn = config.fetch ?? globalThis.fetch;\n const url = `${config.baseUrl}${path}`;\n const maxRetries = options.retryOn429 ? MAX_RATE_LIMIT_RETRIES : 0;\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n const signal = options.signal ?? AbortSignal.timeout(options.timeoutMs ?? DEFAULT_TIMEOUT_MS);\n\n const headers: Record<string, string> = { ...(options.headers ?? {}) };\n let body: BodyInit | undefined;\n if (options.body !== undefined) {\n headers['Content-Type'] ??= 'application/json';\n body = JSON.stringify(options.body);\n }\n\n // `next` is a Next.js extension to RequestInit; cast through.\n const init = {\n method: options.method ?? 'GET',\n headers,\n body,\n signal,\n credentials: options.credentials,\n cache: options.cache,\n ...(options.next ? { next: options.next } : {}),\n } as RequestInit;\n\n const res = await fetchFn(url, init);\n\n if (res.status === 429 && attempt < maxRetries) {\n const retryAfterRaw = res.headers.get('retry-after');\n const retryAfter = retryAfterRaw ? Number.parseInt(retryAfterRaw, 10) : 2;\n const waitSeconds = Math.min(\n Number.isFinite(retryAfter) ? retryAfter : 2,\n RATE_LIMIT_RETRY_CAP_SECONDS,\n );\n await new Promise((r) => setTimeout(r, waitSeconds * 1000));\n continue;\n }\n\n if (!res.ok) {\n let errBody: unknown;\n try {\n errBody = (await res.json()) as unknown;\n } catch {\n try {\n errBody = await res.text();\n } catch {\n errBody = undefined;\n }\n }\n throw new ApiError(`Sifa API ${res.status} on ${path}`, res.status, errBody);\n }\n\n // 204 and 205 are defined to carry no body, so res.json() throws on them.\n // apiWrite treats that throw as a failed write, which turned every\n // successful no-content response (roadmap unvote, remove reaction,\n // dismiss endorsement) into a reported error.\n if (res.status === 204 || res.status === 205) {\n return undefined as T;\n }\n\n return (await res.json()) as T;\n }\n\n throw new ApiError(`Sifa API exhausted retries on ${path}`, 429);\n}\n\n/**\n * Variant of {@link apiFetch} that resolves to `null` on HTTP 404 instead\n * of throwing. Useful for \"fetch by handle\" reads where missing is\n * expected (e.g. unknown profile).\n */\nexport async function apiFetchOrNull<T>(\n config: SifaApiConfig,\n path: string,\n options: ApiFetchOptions = {},\n): Promise<T | null> {\n try {\n return await apiFetch<T>(config, path, options);\n } catch (e) {\n if (e instanceof ApiError && e.status === 404) return null;\n throw e;\n }\n}\n\n/**\n * Result returned by record-write mutations (create / update / delete).\n *\n * Never throws -- writes against the user's PDS can fail in many ways\n * (network, PDS unreachable, rate limit) and the UI needs structured\n * results to render appropriate messages.\n */\nexport interface WriteResult {\n success: boolean;\n error?: string;\n /**\n * PDS hostname returned by sifa-api when a write failed at the user's\n * Personal Data Server (issue #167). Lets the UI render\n * \"Your data server (eurosky.social) isn't responding\" instead of a\n * generic \"Request failed (500)\".\n */\n pdsHost?: string;\n}\n\n/** Result returned by create mutations. Includes the newly created `rkey`. */\nexport interface CreateResult extends WriteResult {\n rkey?: string;\n}\n\ninterface ApiErrorBody {\n message?: string;\n pdsHost?: string;\n}\n\nfunction extractWriteError(data: unknown, status: number): { error: string; pdsHost?: string } {\n const body = (data ?? {}) as ApiErrorBody;\n return {\n error: body.message ?? `Request failed (${status})`,\n ...(body.pdsHost ? { pdsHost: body.pdsHost } : {}),\n };\n}\n\n/**\n * Write mutation against the Sifa AppView. Wraps {@link apiFetch} with the\n * never-throws contract used by all sifa-web mutations: returns a\n * structured {@link WriteResult} on both success and failure, and\n * preserves the `pdsHost` field when the AppView reports a PDS-side\n * failure (issue #167).\n *\n * On success: returns `{ success: true, ...payload }` where `payload` is\n * whatever the server returned in JSON (or `{}` for 204).\n *\n * On failure: returns `{ success: false, error, pdsHost? }`. Never throws.\n *\n * Use {@link apiWriteCreate} when you specifically need the `rkey` from a\n * create response folded into the result shape.\n */\nexport async function apiWrite<TExtra extends object = Record<never, never>>(\n config: SifaApiConfig,\n path: string,\n method: 'POST' | 'PUT' | 'DELETE' | 'PATCH',\n options: Omit<ApiFetchOptions, 'method'> = {},\n): Promise<WriteResult & TExtra> {\n try {\n const data = await apiFetch<TExtra>(config, path, {\n method,\n credentials: 'include',\n ...options,\n });\n return { success: true, ...(data ?? ({} as TExtra)) };\n } catch (e) {\n if (e instanceof ApiError) {\n return { success: false, ...extractWriteError(e.body, e.status) } as WriteResult & TExtra;\n }\n return { success: false, error: 'Network error' } as WriteResult & TExtra;\n }\n}\n\n/**\n * Write mutation that expects the server to return a record key (`rkey`)\n * in its response body. Wraps {@link apiWrite} and folds the `rkey` into\n * the result shape so consumers get `{ success, rkey?, error?, pdsHost? }`.\n *\n * If the server returns additional fields (e.g. `feedUrl` from external\n * account creation), pass them via the `TExtra` generic to keep them\n * typed.\n */\nexport function apiWriteCreate<TExtra extends object = Record<never, never>>(\n config: SifaApiConfig,\n path: string,\n body: unknown,\n options: Omit<ApiFetchOptions, 'method' | 'body'> = {},\n): Promise<CreateResult & TExtra> {\n return apiWrite<{ rkey?: string } & TExtra>(config, path, 'POST', {\n body,\n ...options,\n });\n}\n"],"mappings":";AAqDO,IAAM,WAAN,cAAuB,MAAM;AAAA,EACzB;AAAA,EACA;AAAA,EAET,YAAY,SAAiB,QAAgB,MAAgB;AAC3D,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,SAAS;AACd,SAAK,OAAO;AAAA,EACd;AACF;AAEA,IAAM,qBAAqB;AAC3B,IAAM,yBAAyB;AAC/B,IAAM,+BAA+B;AAoB9B,SAAS,iBAAiB,OAAuB;AACtD,MAAI,UAAU;AACd,MAAI;AACF,cAAU,mBAAmB,KAAK;AAAA,EACpC,QAAQ;AAAA,EAER;AACA,SAAO,mBAAmB,OAAO;AACnC;AASA,eAAsB,SACpB,QACA,MACA,UAA2B,CAAC,GAChB;AACZ,QAAM,UAAU,OAAO,SAAS,WAAW;AAC3C,QAAM,MAAM,GAAG,OAAO,OAAO,GAAG,IAAI;AACpC,QAAM,aAAa,QAAQ,aAAa,yBAAyB;AAEjE,WAAS,UAAU,GAAG,WAAW,YAAY,WAAW;AACtD,UAAM,SAAS,QAAQ,UAAU,YAAY,QAAQ,QAAQ,aAAa,kBAAkB;AAE5F,UAAM,UAAkC,EAAE,GAAI,QAAQ,WAAW,CAAC,EAAG;AACrE,QAAI;AACJ,QAAI,QAAQ,SAAS,QAAW;AAC9B,cAAQ,cAAc,MAAM;AAC5B,aAAO,K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WAAW,IAAK,QAAO;AACtD,UAAM;AAAA,EACR;AACF;AA+BA,SAAS,kBAAkB,MAAe,QAAqD;AAC7F,QAAM,OAAQ,QAAQ,CAAC;AACvB,SAAO;AAAA,IACL,OAAO,KAAK,WAAW,mBAAmB,MAAM;AAAA,IAChD,GAAI,KAAK,UAAU,EAAE,SAAS,KAAK,QAAQ,IAAI,CAAC;AAAA,EAClD;AACF;AAiBA,eAAsB,SACpB,QACA,MACA,QACA,UAA2C,CAAC,GACb;AAC/B,MAAI;AACF,UAAM,OAAO,MAAM,SAAiB,QAAQ,MAAM;AAAA,MAChD;AAAA,MACA,aAAa;AAAA,MACb,GAAG;AAAA,IACL,CAAC;AACD,WAAO,EAAE,SAAS,MAAM,GAAI,QAAS,CAAC,EAAc;AAAA,EACtD,SAAS,GAAG;AACV,QAAI,aAAa,UAAU;AACzB,aAAO,EAAE,SAAS,OAAO,GAAG,kBAAkB,EAAE,MAAM,EAAE,MAAM,EAAE;AAAA,IAClE;AACA,WAAO,EAAE,SAAS,OAAO,OAAO,gBAAgB;AAAA,EAClD;AACF;AAWO,SAAS,eACd,QACA,MACA,MACA,UAAoD,CAAC,GACrB;AAChC,SAAO,SAAqC,QAAQ,MAAM,QAAQ;AAAA,IAChE;AAAA,IACA,GAAG;AAAA,EACL,CAAC;AACH;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/query/client.ts"],"sourcesContent":["/**\n * Foundation HTTP client for talking to the Sifa AppView.\n *\n * Stateless. Consumers supply a {@link SifaApiConfig} per call (the React\n * hooks read it from context; non-React consumers pass it explicitly). No\n * singletons, no module-level state.\n */\n\n/** Configuration passed to every fetcher. */\nexport interface SifaApiConfig {\n /** Base URL of the sifa-api AppView, e.g. `https://api.sifa.id`. No trailing slash. */\n baseUrl: string;\n /**\n * Optional fetch implementation. Defaults to {@link globalThis.fetch}.\n * Lets Next.js consumers pass their cache-enhanced fetch; node/Expo\n * consumers can leave this unset.\n */\n fetch?: typeof fetch;\n /**\n * Optional per-request auth-token minter for auth-required reads. The NATIVE\n * app supplies this (it has no sifa-api session cookie): given a method NSID\n * (`lxm`), it mints a short-lived AT Protocol service-auth JWT on the user's\n * PDS (see the SDK's `/atproto` `mintServiceAuthToken`) and returns it; the\n * fetcher attaches it as `Authorization: Bearer`. Web omits this and relies on\n * its session cookie (`credentials: 'include'`). Return `null` to send no\n * token. See `sifa-api` `createIdentityMiddleware`.\n */\n getAuthToken?: (lxm: string) => Promise<string | null>;\n}\n\n/** Options accepted by {@link apiFetch}. */\nexport interface ApiFetchOptions {\n method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';\n /** Request body. Serialized to JSON automatically. */\n body?: unknown;\n /** AbortSignal. Defaults to `AbortSignal.timeout(timeoutMs)` if `timeoutMs` is set. */\n signal?: AbortSignal;\n /** Per-call timeout in milliseconds. Default: 10_000. Ignored if `signal` is provided. */\n timeoutMs?: number;\n /** Retry on HTTP 429 up to 3 times with the server's `Retry-After` delay (capped at 3s). */\n retryOn429?: boolean;\n /** Additional headers. `Content-Type: application/json` is set automatically when `body` is present. */\n headers?: Record<string, string>;\n credentials?: RequestCredentials;\n cache?: RequestCache;\n /**\n * Next.js-specific cache hints. Ignored on non-Next runtimes. Passed\n * through transparently as part of {@link RequestInit}.\n */\n next?: { revalidate?: number | false; tags?: string[] };\n}\n\n/** Error thrown by {@link apiFetch} on non-2xx responses. */\nexport class ApiError extends Error {\n readonly status: number;\n readonly body: unknown;\n /** Seconds until a rate limit resets, read from the headers of a 429. */\n readonly retryAfterSeconds?: number;\n\n constructor(message: string, status: number, body?: unknown, retryAfterSeconds?: number) {\n super(message);\n this.name = 'ApiError';\n this.status = status;\n this.body = body;\n if (retryAfterSeconds !== undefined) this.retryAfterSeconds = retryAfterSeconds;\n }\n}\n\nconst DEFAULT_TIMEOUT_MS = 10_000;\nconst MAX_RATE_LIMIT_RETRIES = 3;\nconst RATE_LIMIT_RETRY_CAP_SECONDS = 3;\n\n/**\n * Headers sifa-api (`@fastify/rate-limit`) sets on a 429, in preference order.\n * Both carry an integer count of seconds until the limit resets.\n */\nconst RATE_LIMIT_RESET_HEADERS = ['retry-after', 'x-ratelimit-reset'] as const;\n\n/**\n * Seconds to wait before retrying a rate-limited response, or `undefined` when\n * no header carries a positive integer (`Retry-After` may also be an HTTP\n * date, which sifa-api never sends).\n */\nfunction parseRetryAfterSeconds(headers: Headers): number | undefined {\n for (const name of RATE_LIMIT_RESET_HEADERS) {\n const seconds = Number.parseInt(headers.get(name) ?? '', 10);\n if (Number.isFinite(seconds) && seconds > 0) return seconds;\n }\n return undefined;\n}\n\n/**\n * Encode a handle or DID for safe interpolation into a request path,\n * idempotently.\n *\n * Plain {@link encodeURIComponent} double-encodes an already-encoded\n * identifier: Next.js hands route params to RSC pages percent-encoded on a\n * hard navigation (`did%3Aplc%3A...`) but decoded on client-side navigation\n * (`did:plc:...`). Encoding the former again turns `%` into `%25`, so the\n * AppView reads `did%3A...` as a literal handle, finds no match, and 404s —\n * which is why DID profile links broke on direct visits but worked when\n * clicked within the app.\n *\n * AT identifiers (handles are domain names, DIDs are `did:method:...`) never\n * contain a literal `%`, so decoding a decoded value is a no-op. A malformed\n * percent sequence (lone `%`) makes {@link decodeURIComponent} throw; in that\n * case we keep the original value so behaviour matches the prior bare\n * `encodeURIComponent`.\n */\nexport function encodeIdentifier(value: string): string {\n let decoded = value;\n try {\n decoded = decodeURIComponent(value);\n } catch {\n // Malformed percent-encoding — fall back to the raw value.\n }\n return encodeURIComponent(decoded);\n}\n\n/**\n * Generic fetcher used by all SDK query and mutation functions.\n *\n * Returns parsed JSON typed as `T`. Throws {@link ApiError} on non-2xx\n * responses. Use {@link apiFetchOrNull} when 404 should resolve to `null`\n * instead.\n */\nexport async function apiFetch<T = unknown>(\n config: SifaApiConfig,\n path: string,\n options: ApiFetchOptions = {},\n): Promise<T> {\n const fetchFn = config.fetch ?? globalThis.fetch;\n const url = `${config.baseUrl}${path}`;\n const maxRetries = options.retryOn429 ? MAX_RATE_LIMIT_RETRIES : 0;\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n const signal = options.signal ?? AbortSignal.timeout(options.timeoutMs ?? DEFAULT_TIMEOUT_MS);\n\n const headers: Record<string, string> = { ...(options.headers ?? {}) };\n let body: BodyInit | undefined;\n if (options.body !== undefined) {\n headers['Content-Type'] ??= 'application/json';\n body = JSON.stringify(options.body);\n }\n\n // `next` is a Next.js extension to RequestInit; cast through.\n const init = {\n method: options.method ?? 'GET',\n headers,\n body,\n signal,\n credentials: options.credentials,\n cache: options.cache,\n ...(options.next ? { next: options.next } : {}),\n } as RequestInit;\n\n const res = await fetchFn(url, init);\n\n if (res.status === 429 && attempt < maxRetries) {\n const retryAfterRaw = res.headers.get('retry-after');\n const retryAfter = retryAfterRaw ? Number.parseInt(retryAfterRaw, 10) : 2;\n const waitSeconds = Math.min(\n Number.isFinite(retryAfter) ? retryAfter : 2,\n RATE_LIMIT_RETRY_CAP_SECONDS,\n );\n await new Promise((r) => setTimeout(r, waitSeconds * 1000));\n continue;\n }\n\n if (!res.ok) {\n let errBody: unknown;\n try {\n errBody = (await res.json()) as unknown;\n } catch {\n try {\n errBody = await res.text();\n } catch {\n errBody = undefined;\n }\n }\n throw new ApiError(\n `Sifa API ${res.status} on ${path}`,\n res.status,\n errBody,\n res.status === 429 ? parseRetryAfterSeconds(res.headers) : undefined,\n );\n }\n\n // 204 and 205 are defined to carry no body, so res.json() throws on them.\n // apiWrite treats that throw as a failed write, which turned every\n // successful no-content response (roadmap unvote, remove reaction,\n // dismiss endorsement) into a reported error.\n if (res.status === 204 || res.status === 205) {\n return undefined as T;\n }\n\n return (await res.json()) as T;\n }\n\n throw new ApiError(`Sifa API exhausted retries on ${path}`, 429);\n}\n\n/**\n * Variant of {@link apiFetch} that resolves to `null` on HTTP 404 instead\n * of throwing. Useful for \"fetch by handle\" reads where missing is\n * expected (e.g. unknown profile).\n */\nexport async function apiFetchOrNull<T>(\n config: SifaApiConfig,\n path: string,\n options: ApiFetchOptions = {},\n): Promise<T | null> {\n try {\n return await apiFetch<T>(config, path, options);\n } catch (e) {\n if (e instanceof ApiError && e.status === 404) return null;\n throw e;\n }\n}\n\n/**\n * Result returned by record-write mutations (create / update / delete).\n *\n * Never throws -- writes against the user's PDS can fail in many ways\n * (network, PDS unreachable, rate limit) and the UI needs structured\n * results to render appropriate messages.\n */\nexport interface WriteResult {\n success: boolean;\n error?: string;\n /**\n * PDS hostname returned by sifa-api when a write failed at the user's\n * Personal Data Server (issue #167). Lets the UI render\n * \"Your data server (eurosky.social) isn't responding\" instead of a\n * generic \"Request failed (500)\".\n */\n pdsHost?: string;\n /** HTTP status of a failed write. Absent on success and on network errors. */\n status?: number;\n /**\n * Seconds until the rate limit resets, when a write was rejected with 429\n * and the server said how long to wait (sifa-workspace#533). Lets the UI say\n * \"try again in N seconds\" instead of a generic failure.\n */\n retryAfterSeconds?: number;\n}\n\n/** Result returned by create mutations. Includes the newly created `rkey`. */\nexport interface CreateResult extends WriteResult {\n rkey?: string;\n}\n\ninterface ApiErrorBody {\n message?: string;\n error?: string;\n pdsHost?: string;\n}\n\nfunction extractWriteError(\n e: ApiError,\n): Pick<WriteResult, 'error' | 'pdsHost' | 'status' | 'retryAfterSeconds'> {\n const body = (e.body && typeof e.body === 'object' ? e.body : {}) as ApiErrorBody;\n return {\n // Fastify puts the detail in `message` and the status phrase in `error`;\n // sifa-api's own handlers (and the rate limiter) only set `error`.\n error: body.message ?? body.error ?? `Request failed (${e.status})`,\n status: e.status,\n ...(e.retryAfterSeconds !== undefined ? { retryAfterSeconds: e.retryAfterSeconds } : {}),\n ...(body.pdsHost ? { pdsHost: body.pdsHost } : {}),\n };\n}\n\n/**\n * Write mutation against the Sifa AppView. Wraps {@link apiFetch} with the\n * never-throws contract used by all sifa-web mutations: returns a\n * structured {@link WriteResult} on both success and failure, and\n * preserves the `pdsHost` field when the AppView reports a PDS-side\n * failure (issue #167).\n *\n * On success: returns `{ success: true, ...payload }` where `payload` is\n * whatever the server returned in JSON (or `{}` for 204).\n *\n * On failure: returns `{ success: false, error, pdsHost? }`. Never throws.\n *\n * Use {@link apiWriteCreate} when you specifically need the `rkey` from a\n * create response folded into the result shape.\n */\nexport async function apiWrite<TExtra extends object = Record<never, never>>(\n config: SifaApiConfig,\n path: string,\n method: 'POST' | 'PUT' | 'DELETE' | 'PATCH',\n options: Omit<ApiFetchOptions, 'method'> = {},\n): Promise<WriteResult & TExtra> {\n try {\n const data = await apiFetch<TExtra>(config, path, {\n method,\n credentials: 'include',\n ...options,\n });\n return { success: true, ...(data ?? ({} as TExtra)) };\n } catch (e) {\n if (e instanceof ApiError) {\n return { success: false, ...extractWriteError(e) } as WriteResult & TExtra;\n }\n return { success: false, error: 'Network error' } as WriteResult & TExtra;\n }\n}\n\n/**\n * Write mutation that expects the server to return a record key (`rkey`)\n * in its response body. Wraps {@link apiWrite} and folds the `rkey` into\n * the result shape so consumers get `{ success, rkey?, error?, pdsHost? }`.\n *\n * If the server returns additional fields (e.g. `feedUrl` from external\n * account creation), pass them via the `TExtra` generic to keep them\n * typed.\n */\nexport function apiWriteCreate<TExtra extends object = Record<never, never>>(\n config: SifaApiConfig,\n path: string,\n body: unknown,\n options: Omit<ApiFetchOptions, 'method' | 'body'> = {},\n): Promise<CreateResult & TExtra> {\n return apiWrite<{ rkey?: string } & TExtra>(config, path, 'POST', {\n body,\n ...options,\n });\n}\n"],"mappings":";AAqDO,IAAM,WAAN,cAAuB,MAAM;AAAA,EACzB;AAAA,EACA;AAAA;AAAA,EAEA;AAAA,EAET,YAAY,SAAiB,QAAgB,MAAgB,mBAA4B;AACvF,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,SAAS;AACd,SAAK,OAAO;AACZ,QAAI,sBAAsB,OAAW,MAAK,oBAAoB;AAAA,EAChE;AACF;AAEA,IAAM,qBAAqB;AAC3B,IAAM,yBAAyB;AAC/B,IAAM,+BAA+B;AAMrC,IAAM,2BAA2B,CAAC,eAAe,mBAAmB;AAOpE,SAAS,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AAI,CAAC;AAAA,EAClD;AACF;AAiBA,eAAsB,SACpB,QACA,MACA,QACA,UAA2C,CAAC,GACb;AAC/B,MAAI;AACF,UAAM,OAAO,MAAM,SAAiB,QAAQ,MAAM;AAAA,MAChD;AAAA,MACA,aAAa;AAAA,MACb,GAAG;AAAA,IACL,CAAC;AACD,WAAO,EAAE,SAAS,MAAM,GAAI,QAAS,CAAC,EAAc;AAAA,EACtD,SAAS,GAAG;AACV,QAAI,aAAa,UAAU;AACzB,aAAO,EAAE,SAAS,OAAO,GAAG,kBAAkB,CAAC,EAAE;AAAA,IACnD;AACA,WAAO,EAAE,SAAS,OAAO,OAAO,gBAAgB;AAAA,EAClD;AACF;AAWO,SAAS,eACd,QACA,MACA,MACA,UAAoD,CAAC,GACrB;AAChC,SAAO,SAAqC,QAAQ,MAAM,QAAQ;AAAA,IAChE;AAAA,IACA,GAAG;AAAA,EACL,CAAC;AACH;","names":[]}
|
|
@@ -6,16 +6,27 @@ var zod = require('zod');
|
|
|
6
6
|
var ApiError = class extends Error {
|
|
7
7
|
status;
|
|
8
8
|
body;
|
|
9
|
-
|
|
9
|
+
/** Seconds until a rate limit resets, read from the headers of a 429. */
|
|
10
|
+
retryAfterSeconds;
|
|
11
|
+
constructor(message, status, body, retryAfterSeconds) {
|
|
10
12
|
super(message);
|
|
11
13
|
this.name = "ApiError";
|
|
12
14
|
this.status = status;
|
|
13
15
|
this.body = body;
|
|
16
|
+
if (retryAfterSeconds !== void 0) this.retryAfterSeconds = retryAfterSeconds;
|
|
14
17
|
}
|
|
15
18
|
};
|
|
16
19
|
var DEFAULT_TIMEOUT_MS = 1e4;
|
|
17
20
|
var MAX_RATE_LIMIT_RETRIES = 3;
|
|
18
21
|
var RATE_LIMIT_RETRY_CAP_SECONDS = 3;
|
|
22
|
+
var RATE_LIMIT_RESET_HEADERS = ["retry-after", "x-ratelimit-reset"];
|
|
23
|
+
function parseRetryAfterSeconds(headers) {
|
|
24
|
+
for (const name of RATE_LIMIT_RESET_HEADERS) {
|
|
25
|
+
const seconds = Number.parseInt(headers.get(name) ?? "", 10);
|
|
26
|
+
if (Number.isFinite(seconds) && seconds > 0) return seconds;
|
|
27
|
+
}
|
|
28
|
+
return void 0;
|
|
29
|
+
}
|
|
19
30
|
function encodeIdentifier(value) {
|
|
20
31
|
let decoded = value;
|
|
21
32
|
try {
|
|
@@ -67,7 +78,12 @@ async function apiFetch(config, path, options = {}) {
|
|
|
67
78
|
errBody = void 0;
|
|
68
79
|
}
|
|
69
80
|
}
|
|
70
|
-
throw new ApiError(
|
|
81
|
+
throw new ApiError(
|
|
82
|
+
`Sifa API ${res.status} on ${path}`,
|
|
83
|
+
res.status,
|
|
84
|
+
errBody,
|
|
85
|
+
res.status === 429 ? parseRetryAfterSeconds(res.headers) : void 0
|
|
86
|
+
);
|
|
71
87
|
}
|
|
72
88
|
if (res.status === 204 || res.status === 205) {
|
|
73
89
|
return void 0;
|
|
@@ -84,10 +100,14 @@ async function apiFetchOrNull(config, path, options = {}) {
|
|
|
84
100
|
throw e;
|
|
85
101
|
}
|
|
86
102
|
}
|
|
87
|
-
function extractWriteError(
|
|
88
|
-
const body =
|
|
103
|
+
function extractWriteError(e) {
|
|
104
|
+
const body = e.body && typeof e.body === "object" ? e.body : {};
|
|
89
105
|
return {
|
|
90
|
-
|
|
106
|
+
// Fastify puts the detail in `message` and the status phrase in `error`;
|
|
107
|
+
// sifa-api's own handlers (and the rate limiter) only set `error`.
|
|
108
|
+
error: body.message ?? body.error ?? `Request failed (${e.status})`,
|
|
109
|
+
status: e.status,
|
|
110
|
+
...e.retryAfterSeconds !== void 0 ? { retryAfterSeconds: e.retryAfterSeconds } : {},
|
|
91
111
|
...body.pdsHost ? { pdsHost: body.pdsHost } : {}
|
|
92
112
|
};
|
|
93
113
|
}
|
|
@@ -101,7 +121,7 @@ async function apiWrite(config, path, method, options = {}) {
|
|
|
101
121
|
return { success: true, ...data ?? {} };
|
|
102
122
|
} catch (e) {
|
|
103
123
|
if (e instanceof ApiError) {
|
|
104
|
-
return { success: false, ...extractWriteError(e
|
|
124
|
+
return { success: false, ...extractWriteError(e) };
|
|
105
125
|
}
|
|
106
126
|
return { success: false, error: "Network error" };
|
|
107
127
|
}
|