@singi-labs/sifa-sdk 0.22.0 → 0.23.1
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.map +1 -1
- package/dist/{follow-profile-CVcA2w1v.d.ts → follow-profile-CCL1tT1x.d.ts} +1 -1
- package/dist/{follow-profile-CgLLLQtJ.d.cts → follow-profile-RijPgyp-.d.cts} +1 -1
- package/dist/{index-DDh2RLvx.d.ts → index-Bcy443Qi.d.ts} +1 -1
- package/dist/{index-BQAKeEoj.d.cts → index-Ck5zdubP.d.cts} +1 -1
- package/dist/index.cjs +49 -7
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +11 -11
- package/dist/index.d.ts +11 -11
- package/dist/index.js +17 -1
- package/dist/index.js.map +1 -1
- package/dist/jsonld/index.d.cts +2 -2
- package/dist/jsonld/index.d.ts +2 -2
- package/dist/{network-map-2OKh3wSB.d.ts → network-map-BGO1feWW.d.ts} +4 -4
- package/dist/{network-map-DJonNOl0.d.cts → network-map-DBiloRce.d.cts} +4 -4
- package/dist/{org-settings-BShvhyFp.d.ts → org-settings-BliQdqbB.d.cts} +57 -1
- package/dist/{profile-investment-QSwX2GL5.d.cts → profile-investment-BmuXFlZw.d.cts} +2 -0
- package/dist/{profile-investment-QSwX2GL5.d.ts → profile-investment-BmuXFlZw.d.ts} +2 -0
- package/dist/{org-settings-C73Sin5E.d.cts → profile-self-D59D_rhI.d.ts} +57 -1
- package/dist/{profile-summary-DF8-evvA.d.ts → profile-summary-5jNVFUR9.d.ts} +1 -1
- package/dist/{profile-summary-BCOKt3qS.d.cts → profile-summary-DJVnLbFV.d.cts} +1 -1
- package/dist/publishing/index.cjs +31 -1
- package/dist/publishing/index.cjs.map +1 -1
- package/dist/query/client.js +20 -1
- package/dist/query/client.js.map +1 -1
- package/dist/query/fetchers/index.cjs +51 -2
- package/dist/query/fetchers/index.cjs.map +1 -1
- package/dist/query/fetchers/index.d.cts +9 -9
- package/dist/query/fetchers/index.d.ts +9 -9
- package/dist/query/fetchers/profile-mutations.js.map +1 -1
- package/dist/query/hooks/index.cjs +51 -2
- package/dist/query/hooks/index.cjs.map +1 -1
- package/dist/query/hooks/index.d.cts +7 -7
- package/dist/query/hooks/index.d.ts +7 -7
- package/dist/query/index.cjs +20 -1
- package/dist/query/index.cjs.map +1 -1
- package/dist/query/index.d.cts +12 -12
- package/dist/query/index.d.ts +12 -12
- package/dist/query/index.js.map +1 -1
- package/dist/resume/index.d.cts +2 -2
- package/dist/resume/index.d.ts +2 -2
- package/dist/schemas/index.cjs +48 -6
- package/dist/schemas/index.cjs.map +1 -1
- package/dist/schemas/index.d.cts +3 -3
- package/dist/schemas/index.d.ts +3 -3
- package/dist/schemas/index.js +16 -0
- package/dist/schemas/index.js.map +1 -1
- package/dist/schemas/profile-self.js +18 -6
- package/dist/schemas/profile-self.js.map +1 -1
- package/dist/schemas/shared.js +41 -1
- package/dist/schemas/shared.js.map +1 -1
- package/dist/schemas/write/index.cjs +43 -6
- package/dist/schemas/write/index.cjs.map +1 -1
- package/dist/schemas/write/index.d.cts +2 -45
- package/dist/schemas/write/index.d.ts +2 -45
- package/dist/schemas/write/index.js +5 -1
- package/dist/schemas/write/index.js.map +1 -1
- package/dist/schemas/write/profile-self.js +19 -5
- package/dist/schemas/write/profile-self.js.map +1 -1
- package/dist/testing/index.d.cts +2 -2
- package/dist/testing/index.d.ts +2 -2
- package/dist/{types-JydVIhN5.d.cts → types-4MZHuQif.d.cts} +15 -3
- package/dist/{types-CkomzDlY.d.ts → types-DJrmm7p0.d.ts} +15 -3
- package/dist/{use-user-settings-DQ6Dyby7.d.ts → use-user-settings-BfGwI4x3.d.ts} +11 -6
- package/dist/{use-user-settings-Bn6g8bgr.d.cts → use-user-settings-g8ATc9zm.d.cts} +11 -6
- package/dist/{user-settings-BdNrDa9O.d.ts → user-settings-C3_y8_8T.d.ts} +6 -11
- package/dist/{user-settings-C8JUD4DM.d.cts → user-settings-CuqhXuTE.d.cts} +6 -11
- package/dist/{verification-providers-DeyGqaoC.d.cts → verification-providers-Dq6ni6e-.d.cts} +58 -1
- package/dist/{verification-providers-DeyGqaoC.d.ts → verification-providers-Dq6ni6e-.d.ts} +58 -1
- package/package.json +4 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/schemas/shared.ts","../../src/publishing/schemas.ts","../../src/publishing/registry.ts","../../src/publishing/linkblog.ts","../../src/publishing/types.ts"],"names":["z"],"mappings":";;;;;AASO,SAAS,aAAa,GAAA,EAAa;AACxC,EAAA,OAAO,CAAC,KAAA,KAA2B;AACjC,IAAA,MAAM,SAAA,GAAY,IAAI,IAAA,CAAK,SAAA,CAAU,QAAW,EAAE,WAAA,EAAa,YAAY,CAAA;AAC3E,IAAA,IAAI,KAAA,GAAQ,CAAA;AACZ,IAAA,KAAA,MAAW,CAAA,IAAK,SAAA,CAAU,OAAA,CAAQ,KAAK,CAAA,EAAG;AACxC,MAAA,KAAA,EAAA;AACA,MAAA,IAAI,KAAA,GAAQ,KAAK,OAAO,KAAA;AAAA,IAC1B;AACA,IAAA,OAAO,IAAA;AAAA,EACT,CAAA;AACF;AAGO,IAAM,YAAYA,KAAA,CAAE,MAAA,EAAO,CAAE,KAAA,CAAM,kCAAkC,aAAa,CAAA;AAGlF,IAAM,cAAA,GAAiBA,MAAE,MAAA,EAAO,CAAE,SAAS,EAAE,MAAA,EAAQ,MAAM,CAAA;AAWjCA,KAAA,CAC9B,MAAA,EAAO,CACP,KAAA,CAAM,mCAAmC,mDAAmD;AAGxF,IAAM,cAAcA,KAAA,CAAE,MAAA,EAAO,CAAE,KAAA,CAAM,mBAAmB,gBAAgB,CAAA;AAGxE,IAAM,YAAYA,KAAA,CACtB,MAAA,EAAO,CACP,KAAA,CAAM,mDAAmD,aAAa,CAAA;AAGxCA,KAAA,CAC9B,MAAA,EAAO,CACP,KAAA,CAAM,uCAAuC,6BAA6B;AAGtE,IAAM,SAAA,GAAYA,KAAA,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AC,MAAM,mBAAA,CAAoB,CAAA,CAAE,GAAG,CAAC,CAAA;AACpD","file":"index.cjs","sourcesContent":["import { z } from 'zod';\n\n/**\n * Grapheme-aware refinement matching the AT Protocol lexicon `maxGraphemes`\n * constraint. JS strings are sequences of UTF-16 code units, but lexicon\n * `maxGraphemes` counts user-perceived characters (grapheme clusters), so\n * emoji sequences, regional indicators, ZWJ joins, and combining marks all\n * count as one unit each. We use `Intl.Segmenter` to enforce this correctly.\n */\nexport function maxGraphemes(max: number) {\n return (value: string): boolean => {\n const segmenter = new Intl.Segmenter(undefined, { granularity: 'grapheme' });\n let count = 0;\n for (const _ of segmenter.segment(value)) {\n count++;\n if (count > max) return false;\n }\n return true;\n };\n}\n\n/** Decentralized identifier, AT Protocol `format: did`. */\nexport const didSchema = z.string().regex(/^did:[a-z]+:[a-zA-Z0-9._:%-]+$/, 'Invalid DID');\n\n/** RFC 3339 datetime with timezone offset, AT Protocol `format: datetime`. */\nexport const datetimeSchema = z.string().datetime({ offset: true });\n\n/**\n * Freeform calendar date for user-facing profile dates (start/end, issued,\n * completed, awarded, published, etc.). Accepts a bare year, year-month,\n * year-month-day, or a full datetime (so a legacy record's RFC-3339 date maps\n * through on backfill without loss). NOT strict `datetime` -- users typically\n * remember only month/year, and LinkedIn-importer writes carry partial dates,\n * so the lexicons document these as freeform `YYYY-MM` / `YYYY-MM-DD`. Record\n * metadata like `createdAt` stays on `datetimeSchema`.\n */\nexport const partialDateSchema = z\n .string()\n .regex(/^\\d{4}(-\\d{2}(-\\d{2}(T.+)?)?)?$/, 'Expected YYYY, YYYY-MM, YYYY-MM-DD, or a datetime');\n\n/** Generic AT-URI, AT Protocol `format: at-uri`. */\nexport const atUriSchema = z.string().regex(/^at:\\/\\/[^\\s]+$/, 'Invalid AT-URI');\n\n/** Content identifier, AT Protocol `format: cid`. Loose validation -- accepts CIDv0 and CIDv1. */\nexport const cidSchema = z\n .string()\n .regex(/^(Qm[1-9A-HJ-NP-Za-km-z]{44}|b[A-Za-z0-9+/=]+)$/, 'Invalid CID');\n\n/** BCP 47 language tag, AT Protocol `format: language`. */\nexport const languageTagSchema = z\n .string()\n .regex(/^[a-zA-Z]{1,8}(-[a-zA-Z0-9]{1,8})*$/, 'Invalid BCP 47 language tag');\n\n/** Generic URI, AT Protocol `format: uri`. */\nexport const uriSchema = z.string().url();\n\n/**\n * StrongRef shape from `com.atproto.repo.strongRef` -- pins a record by both\n * AT-URI (identity) and CID (version).\n */\nexport const strongRefSchema = z.object({\n uri: atUriSchema,\n cid: cidSchema,\n});\n\n/**\n * Reference to an `id.sifa.profile.skill` record by AT-URI. Mirrors\n * `id.sifa.defs#skillRef`, which carries no CID at all: skills are mutable\n * records in the same user's repo, so the reference resolves live and tracks\n * edits to the target.\n */\nexport const skillRefSchema = z.object({\n uri: atUriSchema,\n});\n\n/**\n * Reference to a record by AT-URI, with an optional CID. Mirrors\n * `id.sifa.defs#externalRecordRef`. Unlike a strongRef the CID is optional:\n * consumers resolve the AT-URI live so the reference tracks edits to the\n * target, and the CID is a best-effort integrity hint only.\n */\nexport const externalRecordRefSchema = z.object({\n uri: atUriSchema,\n cid: cidSchema.optional(),\n});\n\n/**\n * Shared reference to an organization or person named by a record. Mirrors\n * `id.sifa.defs#agentRef`. `name` is a point-in-time snapshot label captured\n * when the record was saved; `did` and `entityRef` are the durable identity and\n * should be resolved live. `name` is required so an empty object cannot validate\n * as a no-op. `.passthrough()` (not `.strict()`): external apps may emit fields a\n * newer schema will define, and dropping them on a round-trip would silently\n * lose data.\n */\nexport const agentRefSchema = z\n .object({\n name: z.string().min(1).refine(maxGraphemes(256)).max(2560),\n did: didSchema.optional(),\n entityRef: uriSchema.optional(),\n })\n .passthrough();\n\nexport type AgentRef = z.infer<typeof agentRefSchema>;\n\n/**\n * Self-labels shape from `com.atproto.label.defs#selfLabels`. Modelled\n * permissively because clients rarely construct this directly; the AppView\n * handles label validation.\n */\nexport const selfLabelsSchema = z.object({\n $type: z.literal('com.atproto.label.defs#selfLabels').optional(),\n values: z.array(z.object({ val: z.string() })),\n});\n","import { z } from 'zod';\n\nimport {\n atUriSchema,\n datetimeSchema,\n didSchema,\n maxGraphemes,\n selfLabelsSchema,\n strongRefSchema,\n uriSchema,\n} from '../schemas/shared.js';\n\n/**\n * Zod schemas mirroring the canonical Standard.site lexicons that Sifa\n * consumes when rendering publication embeds.\n *\n * Canonical lexicons live at:\n * DID: did:plc:re3ebnp5v7ffagz6rb6xfei4\n * PDS: https://auriporia.us-west.host.bsky.network\n * Collection: com.atproto.lexicon.schema\n *\n * Sifa does NOT own these lexicons; we vendor the validation shapes so\n * clients can parse augmented embeds and (in Phase 4) write subscription\n * records to viewers' PDSes. Re-check against the canonical PDS on each\n * SDK release to detect schema drift.\n */\n\nconst rgbColorSchema = z.object({\n r: z.number().int().min(0).max(255),\n g: z.number().int().min(0).max(255),\n b: z.number().int().min(0).max(255),\n});\n\nexport type RgbColor = z.infer<typeof rgbColorSchema>;\n\n/** site.standard.theme.basic */\nexport const BasicThemeSchema = z.object({\n background: rgbColorSchema,\n foreground: rgbColorSchema,\n accent: rgbColorSchema,\n accentForeground: rgbColorSchema,\n});\n\nexport type BasicTheme = z.infer<typeof BasicThemeSchema>;\n\nconst blobRefSchema = z\n .object({\n $type: z.string().optional(),\n ref: z.unknown(),\n mimeType: z.string().optional(),\n size: z.number().optional(),\n })\n .passthrough();\n\n/** site.standard.publication */\nexport const StandardSitePublicationRecordSchema = z\n .object({\n url: uriSchema,\n name: z.string().min(1).refine(maxGraphemes(500)).max(5000),\n description: z.string().refine(maxGraphemes(3000)).max(30000).optional(),\n icon: blobRefSchema.optional(),\n basicTheme: BasicThemeSchema.optional(),\n labels: selfLabelsSchema.optional(),\n preferences: z\n .object({\n showInDiscover: z.boolean().optional(),\n })\n .partial()\n .optional(),\n })\n .passthrough();\n\nexport type StandardSitePublicationRecord = z.infer<typeof StandardSitePublicationRecordSchema>;\n\nconst contributorSchema = z\n .object({\n did: didSchema,\n role: z.string().refine(maxGraphemes(100)).max(1000).optional(),\n displayName: z.string().refine(maxGraphemes(100)).max(1000).optional(),\n })\n .passthrough();\n\n/** site.standard.document */\nexport const StandardSiteDocumentRecordSchema = z\n .object({\n site: z.string().min(1),\n title: z.string().min(1).refine(maxGraphemes(500)).max(5000),\n path: z.string().optional(),\n publishedAt: datetimeSchema,\n updatedAt: datetimeSchema.optional(),\n description: z.string().refine(maxGraphemes(3000)).max(30000).optional(),\n textContent: z.string().optional(),\n tags: z.array(z.string().refine(maxGraphemes(128)).max(1280)).optional(),\n coverImage: blobRefSchema.optional(),\n contributors: z.array(contributorSchema).optional(),\n bskyPostRef: strongRefSchema.optional(),\n labels: selfLabelsSchema.optional(),\n })\n .passthrough();\n\nexport type StandardSiteDocumentRecord = z.infer<typeof StandardSiteDocumentRecordSchema>;\n\n/**\n * site.standard.graph.subscription\n *\n * Authored by a viewer to declare a subscription to a publication. Used\n * by Phase 4 inline-subscribe path. Record key is a TID; the AT-URI\n * shape is `at://<viewer-did>/site.standard.graph.subscription/<rkey>`.\n */\nexport const StandardSiteSubscriptionRecordSchema = z.object({\n publication: atUriSchema,\n createdAt: datetimeSchema.optional(),\n});\n\nexport type StandardSiteSubscriptionRecord = z.infer<typeof StandardSiteSubscriptionRecordSchema>;\n\n/**\n * site.standard.graph.recommend\n *\n * Document-level \"like\" record. Same scope as subscription via the\n * site.standard.authSocial OAuth permission-set, so Phase 4 unlocks\n * inline likes alongside inline subscribes.\n */\nexport const StandardSiteRecommendRecordSchema = z.object({\n document: atUriSchema,\n createdAt: datetimeSchema,\n});\n\nexport type StandardSiteRecommendRecord = z.infer<typeof StandardSiteRecommendRecordSchema>;\n","/**\n * Publisher allowlist for the Standard.site rich embed.\n *\n * Mirrors `bluesky-social/social-app`\n * `src/components/Post/Embed/StandardSiteEmbed/publishers.ts`. The only\n * gate this provides is which publishers get the highlighted\n * \"Subscribe on {Publisher}\" CTA with a publisher icon vs the plain\n * \"View publication\" fallback — any Standard.site embed renders\n * regardless of allowlist membership.\n *\n * Sync policy: review additions against the upstream bsky list weekly;\n * Singi Labs reviews before merge.\n */\n\nexport interface Publisher {\n /** Lowercase host. Subdomains are matched via `hostMatches`. */\n host: string;\n /** Human-facing publisher name shown in CTA copy. */\n name: string;\n /**\n * Stable identifier used by clients to look up brand icons. The SDK\n * does not ship icon assets — sifa-web maintains them keyed by this\n * id so React Native vs web rendering can diverge.\n */\n iconKey: 'leaflet' | 'pckt' | 'offprint';\n}\n\nexport const STANDARD_SITE_PUBLISHERS: readonly Publisher[] = Object.freeze([\n { host: 'leaflet.pub', name: 'Leaflet', iconKey: 'leaflet' },\n { host: 'pckt.blog', name: 'pckt', iconKey: 'pckt' },\n { host: 'offprint.app', name: 'Offprint', iconKey: 'offprint' },\n]);\n\n/**\n * Returns true when `host` exactly matches `target` or is a subdomain of\n * it. Hosts are expected to be lowercase already.\n */\nexport function hostMatches(host: string, target: string): boolean {\n return host === target || host.endsWith('.' + target);\n}\n\nfunction hostFromUri(uri: string | undefined | null): string | null {\n if (!uri) return null;\n try {\n return new URL(uri).host.toLowerCase();\n } catch {\n return null;\n }\n}\n\n/**\n * Match a publisher by host. Returns the publisher when `host` is on the\n * allowlist (exact or subdomain match), null otherwise. Host should be\n * lowercase.\n */\nexport function matchPublisherByHost(host: string | null | undefined): Publisher | null {\n if (!host) return null;\n const lower = host.toLowerCase();\n return STANDARD_SITE_PUBLISHERS.find((p) => hostMatches(lower, p.host)) ?? null;\n}\n\n/**\n * Match a publisher by URI. Convenience wrapper around\n * `matchPublisherByHost` for callers that have a publication URL handy.\n */\nexport function matchPublisherByUri(uri: string | undefined | null): Publisher | null {\n return matchPublisherByHost(hostFromUri(uri));\n}\n","/**\n * Linkblog-share detection for the Standard.site document family.\n *\n * A \"linkblog\" (e.g. Skyreader) writes a `site.standard.document` to the\n * user's PDS for every *external* article they share. Those documents are\n * valid Standard.site posts, so they surface in Sifa's activity stream and\n * profile portfolio as if the user authored them — but the user only shared\n * someone else's writing (sifa-workspace#351).\n *\n * These predicates identify such shares so callers can exclude them, while\n * leaving genuinely authored Standard.site posts (Leaflet, pckt, Offprint\n * essays) untouched.\n *\n * Signals, most to least reliable:\n * 1. The Skyreader provenance marker on the document (`skyreaderLinkblog`).\n * 2. The document's parent publication is itself a linkblog (the marker\n * lives on the publication even when older documents lack their own).\n * Callers resolve the publication and pass `publicationIsLinkblog`.\n * 3. A `links` entry with `rel: \"repost\"` — a quote-reshare, inherently\n * not the user's own writing.\n * 4. Heuristic: a `links` entry with `rel: \"related\"` pointing to an\n * external host different from the document's own publication host —\n * the document's subject is an off-site article. Only applied when the\n * caller supplies the resolved `publicationHost`, so an authored post\n * that merely cites an external resource is never hidden on a guess.\n */\n\n/**\n * Discovery marker Skyreader stamps on every linkblog publication and on\n * link-share documents. Value is a fixed URL, not a per-user value.\n */\nexport const SKYREADER_LINKBLOG_MARKER_URL = 'https://skyreader.app/linkblog';\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\n/** A non-empty `skyreaderLinkblog` marker field. */\nfunction hasLinkblogMarker(record: Record<string, unknown>): boolean {\n const marker = record.skyreaderLinkblog;\n return typeof marker === 'string' && marker.length > 0;\n}\n\nfunction hostOf(uri: string): string | null {\n try {\n return new URL(uri).host.toLowerCase();\n } catch {\n return null;\n }\n}\n\n/**\n * True when a `site.standard.publication` record is a linkblog rather than an\n * authored publication — i.e. it carries the Skyreader provenance marker.\n */\nexport function isLinkblogPublication(record: unknown): boolean {\n return isRecord(record) && hasLinkblogMarker(record);\n}\n\nexport interface LinkblogShareOptions {\n /**\n * True when the document's parent publication has been resolved and is\n * itself a linkblog (see {@link isLinkblogPublication}). Catches shares\n * whose document predates the per-document marker.\n */\n publicationIsLinkblog?: boolean;\n /**\n * Resolved host of the document's parent publication, enabling the\n * external-subject heuristic. Omit when the publication (hence its host)\n * could not be resolved — the heuristic then stays off.\n */\n publicationHost?: string;\n}\n\n/**\n * True when a `site.standard.document` is a shared/linkblogged external\n * article rather than the user's own writing. See the module comment for the\n * signal order.\n */\nexport function isLinkblogShareDocument(record: unknown, opts: LinkblogShareOptions = {}): boolean {\n if (!isRecord(record)) return false;\n\n // 1. Provenance marker on the document itself.\n if (hasLinkblogMarker(record)) return true;\n\n // 2. Parent publication is a linkblog (caller-resolved).\n if (opts.publicationIsLinkblog === true) return true;\n\n const links = record.links;\n if (!Array.isArray(links)) return false;\n\n const pubHost = opts.publicationHost?.toLowerCase();\n for (const link of links) {\n if (!isRecord(link) || typeof link.rel !== 'string') continue;\n\n // 3. Reshare of another record.\n if (link.rel === 'repost') return true;\n\n // 4. External-subject heuristic (only with a known publication host).\n if (link.rel === 'related' && pubHost && typeof link.uri === 'string') {\n const linkHost = hostOf(link.uri);\n if (linkHost && linkHost !== pubHost) return true;\n }\n }\n\n return false;\n}\n","import type { BasicTheme } from './schemas.js';\n\n/**\n * Publication metadata embedded in the augmented activity view by\n * sifa-api when an external link card matches an indexed publication.\n *\n * `uri` is the publication's AT-URI (e.g.\n * `at://did:plc:abc/site.standard.publication/xyz`). `theme` carries\n * the publication's own colors when supplied — clients should apply a\n * WCAG min-contrast fallback before honoring them.\n *\n * `icon` is left as `unknown` here because its representation depends\n * on the surface: blob ref on the wire, CDN URL after resolution.\n */\nexport interface PublicationSource {\n uri: string;\n title: string;\n icon?: unknown;\n theme?: BasicTheme;\n}\n\n/**\n * Shape attached to activity items whose external link card URL matches\n * a Standard.site record. Mirrors the relevant fields of bsky's\n * `StandardSiteEmbed` view so a sifa-web renderer can be near-1:1.\n *\n * `associatedRefs` carries AT-URIs the client may use in Phase 4 to\n * query subscription state for the viewer.\n */\nexport interface StandardSiteEmbedView {\n uri: string;\n source: PublicationSource;\n associatedRefs: { uri: string }[];\n createdAt?: string;\n readingTime?: number;\n}\n\nexport const STANDARD_SITE_PUBLICATION_NSID = 'site.standard.publication' as const;\nexport const STANDARD_SITE_DOCUMENT_NSID = 'site.standard.document' as const;\nexport const STANDARD_SITE_SUBSCRIPTION_NSID = 'site.standard.graph.subscription' as const;\nexport const STANDARD_SITE_RECOMMEND_NSID = 'site.standard.graph.recommend' as const;\n\n/**\n * Pre-defined OAuth permission-set the consumer apps request to write\n * subscription + recommend records on behalf of the viewer. The actual\n * permission-set is published under\n * `at://did:plc:re3ebnp5v7ffagz6rb6xfei4/com.atproto.lexicon.schema/site.standard.authSocial`.\n */\nexport const STANDARD_SITE_AUTH_SOCIAL_NSID = 'site.standard.authSocial' as const;\n\nconst COLLECTION_SET = new Set<string>([\n STANDARD_SITE_PUBLICATION_NSID,\n STANDARD_SITE_DOCUMENT_NSID,\n STANDARD_SITE_SUBSCRIPTION_NSID,\n STANDARD_SITE_RECOMMEND_NSID,\n]);\n\n/**\n * True when the AT-URI's collection segment is a Standard.site\n * collection. Useful for detecting Standard.site embed augmentation on\n * arbitrary activity items.\n */\nexport function isStandardSiteAtUri(uri: string): boolean {\n if (!uri.startsWith('at://')) return false;\n const segments = uri.slice('at://'.length).split('/');\n const collection = segments[1];\n return collection !== undefined && COLLECTION_SET.has(collection);\n}\n\n/**\n * True when any `associatedRefs[].uri` is a Standard.site collection\n * AT-URI. The bsky client uses the same check to gate the\n * `StandardSiteEmbed` renderer.\n */\nexport function hasStandardSiteAssociatedRef(refs: { uri: string }[] | undefined): boolean {\n if (!refs) return false;\n return refs.some((r) => isStandardSiteAtUri(r.uri));\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/schemas/shared.ts","../../src/publishing/schemas.ts","../../src/publishing/registry.ts","../../src/publishing/linkblog.ts","../../src/publishing/types.ts"],"names":["z"],"mappings":";;;;;AASO,SAAS,aAAa,GAAA,EAAa;AACxC,EAAA,MAAM,SAAA,GAAY,IAAI,IAAA,CAAK,SAAA,CAAU,QAAW,EAAE,WAAA,EAAa,YAAY,CAAA;AAC3E,EAAA,OAAO,CAAC,KAAA,KAA2B;AACjC,IAAA,IAAI,KAAA,GAAQ,CAAA;AACZ,IAAA,KAAA,MAAW,CAAA,IAAK,SAAA,CAAU,OAAA,C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IAC/C;AAAA,EACF;AAEA,EAAA,OAAO,KAAA;AACT;;;ACrEO,IAAM,8BAAA,GAAiC;AACvC,IAAM,2BAAA,GAA8B;AACpC,IAAM,+BAAA,GAAkC;AACxC,IAAM,4BAAA,GAA+B;AAQrC,IAAM,8BAAA,GAAiC;AAE9C,IAAM,cAAA,uBAAqB,GAAA,CAAY;AAAA,EACrC,8BAAA;AAAA,EACA,2BAAA;AAAA,EACA,+BAAA;AAAA,EACA;AACF,CAAC,CAAA;AAOM,SAAS,oBAAoB,GAAA,EAAsB;AACxD,EAAA,IAAI,CAAC,GAAA,CAAI,UAAA,CAAW,OAAO,GAAG,OAAO,KAAA;AACrC,EAAA,MAAM,WAAW,GAAA,CAAI,KAAA,CAAM,QAAQ,MAAM,CAAA,CAAE,MAAM,GAAG,CAAA;AACpD,EAAA,MAAM,UAAA,GAAa,SAAS,CAAC,CAAA;AAC7B,EAAA,OAAO,UAAA,KAAe,MAAA,IAAa,cAAA,CAAe,GAAA,CAAI,UAAU,CAAA;AAClE;AAOO,SAAS,6BAA6B,IAAA,EAA8C;AACzF,EAAA,IAAI,CAAC,MAAM,OAAO,KAAA;AAClB,EAAA,OAAO,KAAK,IAAA,CAAK,CAAC,MAAM,mBAAA,CAAoB,CAAA,CAAE,GAAG,CAAC,CAAA;AACpD","file":"index.cjs","sourcesContent":["import { z } from 'zod';\n\n/**\n * Grapheme-aware refinement matching the AT Protocol lexicon `maxGraphemes`\n * constraint. JS strings are sequences of UTF-16 code units, but lexicon\n * `maxGraphemes` counts user-perceived characters (grapheme clusters), so\n * emoji sequences, regional indicators, ZWJ joins, and combining marks all\n * count as one unit each. We use `Intl.Segmenter` to enforce this correctly.\n */\nexport function maxGraphemes(max: number) {\n const segmenter = new Intl.Segmenter(undefined, { granularity: 'grapheme' });\n return (value: string): boolean => {\n let count = 0;\n for (const _ of segmenter.segment(value)) {\n count++;\n if (count > max) return false;\n }\n return true;\n };\n}\n\n/**\n * Byte-length refinement matching the AT Protocol lexicon string `maxLength`\n * constraint, which counts UTF-8 bytes (not UTF-16 code units). Uses\n * `TextEncoder` rather than `Buffer` so it also runs in browsers.\n */\nexport function maxBytes(max: number) {\n const encoder = new TextEncoder();\n return (value: string): boolean => {\n // UTF-8 uses at most 3 bytes per UTF-16 unit, so short strings cannot exceed `max`.\n if (value.length * 3 <= max) return true;\n return encoder.encode(value).length <= max;\n };\n}\n\n/**\n * A string capped by a lexicon `maxGraphemes` (user-perceived characters) and\n * `maxLength` (UTF-8 bytes) pair. The grapheme check aborts first, so an\n * over-long value reports only the character error.\n */\nexport function lexiconString(graphemes: number, bytes: number) {\n return z\n .string()\n .refine(maxGraphemes(graphemes), {\n message: `Must be at most ${graphemes} characters`,\n abort: true,\n })\n .refine(maxBytes(bytes), {\n message:\n 'This text is too long. Emoji and some scripts take more space, so shorten it a little.',\n });\n}\n\n/**\n * Lexicon limits for the `id.sifa.profile.self` text fields: `graphemes` is the\n * `maxGraphemes` cap (user-perceived characters), `bytes` the `maxLength` cap\n * (UTF-8 bytes). The field schemas below are built from these numbers, so\n * forms can show counters and caps without duplicating them.\n */\nexport const PROFILE_TEXT_LIMITS = {\n displayName: { graphemes: 64, bytes: 640 },\n givenName: { graphemes: 64, bytes: 640 },\n familyName: { graphemes: 64, bytes: 640 },\n namePronunciation: { graphemes: 64, bytes: 640 },\n pronouns: { graphemes: 20, bytes: 200 },\n headline: { graphemes: 120, bytes: 1200 },\n about: { graphemes: 5000, bytes: 50000 },\n} as const;\n\nfunction profileText(limit: { readonly graphemes: number; readonly bytes: number }) {\n return lexiconString(limit.graphemes, limit.bytes);\n}\n\n/**\n * Field schemas for `id.sifa.profile.self`, shared by the record schema and the\n * write schemas so the lexicon limits live in one place.\n */\nexport const profileDisplayNameSchema = profileText(PROFILE_TEXT_LIMITS.displayName);\nexport const profileNameSchema = profileText(PROFILE_TEXT_LIMITS.givenName);\nexport const profilePronounsSchema = profileText(PROFILE_TEXT_LIMITS.pronouns);\nexport const profileHeadlineSchema = profileText(PROFILE_TEXT_LIMITS.headline);\nexport const profileAboutSchema = profileText(PROFILE_TEXT_LIMITS.about);\n\n/** Decentralized identifier, AT Protocol `format: did`. */\nexport const didSchema = z.string().regex(/^did:[a-z]+:[a-zA-Z0-9._:%-]+$/, 'Invalid DID');\n\n/** RFC 3339 datetime with timezone offset, AT Protocol `format: datetime`. */\nexport const datetimeSchema = z.string().datetime({ offset: true });\n\n/**\n * Freeform calendar date for user-facing profile dates (start/end, issued,\n * completed, awarded, published, etc.). Accepts a bare year, year-month,\n * year-month-day, or a full datetime (so a legacy record's RFC-3339 date maps\n * through on backfill without loss). NOT strict `datetime` -- users typically\n * remember only month/year, and LinkedIn-importer writes carry partial dates,\n * so the lexicons document these as freeform `YYYY-MM` / `YYYY-MM-DD`. Record\n * metadata like `createdAt` stays on `datetimeSchema`.\n */\nexport const partialDateSchema = z\n .string()\n .regex(/^\\d{4}(-\\d{2}(-\\d{2}(T.+)?)?)?$/, 'Expected YYYY, YYYY-MM, YYYY-MM-DD, or a datetime');\n\n/** Generic AT-URI, AT Protocol `format: at-uri`. */\nexport const atUriSchema = z.string().regex(/^at:\\/\\/[^\\s]+$/, 'Invalid AT-URI');\n\n/** Content identifier, AT Protocol `format: cid`. Loose validation -- accepts CIDv0 and CIDv1. */\nexport const cidSchema = z\n .string()\n .regex(/^(Qm[1-9A-HJ-NP-Za-km-z]{44}|b[A-Za-z0-9+/=]+)$/, 'Invalid CID');\n\n/** BCP 47 language tag, AT Protocol `format: language`. */\nexport const languageTagSchema = z\n .string()\n .regex(/^[a-zA-Z]{1,8}(-[a-zA-Z0-9]{1,8})*$/, 'Invalid BCP 47 language tag');\n\n/** Generic URI, AT Protocol `format: uri`. */\nexport const uriSchema = z.string().url();\n\n/**\n * StrongRef shape from `com.atproto.repo.strongRef` -- pins a record by both\n * AT-URI (identity) and CID (version).\n */\nexport const strongRefSchema = z.object({\n uri: atUriSchema,\n cid: cidSchema,\n});\n\n/**\n * Reference to an `id.sifa.profile.skill` record by AT-URI. Mirrors\n * `id.sifa.defs#skillRef`, which carries no CID at all: skills are mutable\n * records in the same user's repo, so the reference resolves live and tracks\n * edits to the target.\n */\nexport const skillRefSchema = z.object({\n uri: atUriSchema,\n});\n\n/**\n * Reference to a record by AT-URI, with an optional CID. Mirrors\n * `id.sifa.defs#externalRecordRef`. Unlike a strongRef the CID is optional:\n * consumers resolve the AT-URI live so the reference tracks edits to the\n * target, and the CID is a best-effort integrity hint only.\n */\nexport const externalRecordRefSchema = z.object({\n uri: atUriSchema,\n cid: cidSchema.optional(),\n});\n\n/**\n * Shared reference to an organization or person named by a record. Mirrors\n * `id.sifa.defs#agentRef`. `name` is a point-in-time snapshot label captured\n * when the record was saved; `did` and `entityRef` are the durable identity and\n * should be resolved live. `name` is required so an empty object cannot validate\n * as a no-op. `.passthrough()` (not `.strict()`): external apps may emit fields a\n * newer schema will define, and dropping them on a round-trip would silently\n * lose data.\n */\nexport const agentRefSchema = z\n .object({\n name: z.string().min(1).refine(maxGraphemes(256)).max(2560),\n did: didSchema.optional(),\n entityRef: uriSchema.optional(),\n })\n .passthrough();\n\nexport type AgentRef = z.infer<typeof agentRefSchema>;\n\n/**\n * Self-labels shape from `com.atproto.label.defs#selfLabels`. Modelled\n * permissively because clients rarely construct this directly; the AppView\n * handles label validation.\n */\nexport const selfLabelsSchema = z.object({\n $type: z.literal('com.atproto.label.defs#selfLabels').optional(),\n values: z.array(z.object({ val: z.string() })),\n});\n","import { z } from 'zod';\n\nimport {\n atUriSchema,\n datetimeSchema,\n didSchema,\n maxGraphemes,\n selfLabelsSchema,\n strongRefSchema,\n uriSchema,\n} from '../schemas/shared.js';\n\n/**\n * Zod schemas mirroring the canonical Standard.site lexicons that Sifa\n * consumes when rendering publication embeds.\n *\n * Canonical lexicons live at:\n * DID: did:plc:re3ebnp5v7ffagz6rb6xfei4\n * PDS: https://auriporia.us-west.host.bsky.network\n * Collection: com.atproto.lexicon.schema\n *\n * Sifa does NOT own these lexicons; we vendor the validation shapes so\n * clients can parse augmented embeds and (in Phase 4) write subscription\n * records to viewers' PDSes. Re-check against the canonical PDS on each\n * SDK release to detect schema drift.\n */\n\nconst rgbColorSchema = z.object({\n r: z.number().int().min(0).max(255),\n g: z.number().int().min(0).max(255),\n b: z.number().int().min(0).max(255),\n});\n\nexport type RgbColor = z.infer<typeof rgbColorSchema>;\n\n/** site.standard.theme.basic */\nexport const BasicThemeSchema = z.object({\n background: rgbColorSchema,\n foreground: rgbColorSchema,\n accent: rgbColorSchema,\n accentForeground: rgbColorSchema,\n});\n\nexport type BasicTheme = z.infer<typeof BasicThemeSchema>;\n\nconst blobRefSchema = z\n .object({\n $type: z.string().optional(),\n ref: z.unknown(),\n mimeType: z.string().optional(),\n size: z.number().optional(),\n })\n .passthrough();\n\n/** site.standard.publication */\nexport const StandardSitePublicationRecordSchema = z\n .object({\n url: uriSchema,\n name: z.string().min(1).refine(maxGraphemes(500)).max(5000),\n description: z.string().refine(maxGraphemes(3000)).max(30000).optional(),\n icon: blobRefSchema.optional(),\n basicTheme: BasicThemeSchema.optional(),\n labels: selfLabelsSchema.optional(),\n preferences: z\n .object({\n showInDiscover: z.boolean().optional(),\n })\n .partial()\n .optional(),\n })\n .passthrough();\n\nexport type StandardSitePublicationRecord = z.infer<typeof StandardSitePublicationRecordSchema>;\n\nconst contributorSchema = z\n .object({\n did: didSchema,\n role: z.string().refine(maxGraphemes(100)).max(1000).optional(),\n displayName: z.string().refine(maxGraphemes(100)).max(1000).optional(),\n })\n .passthrough();\n\n/** site.standard.document */\nexport const StandardSiteDocumentRecordSchema = z\n .object({\n site: z.string().min(1),\n title: z.string().min(1).refine(maxGraphemes(500)).max(5000),\n path: z.string().optional(),\n publishedAt: datetimeSchema,\n updatedAt: datetimeSchema.optional(),\n description: z.string().refine(maxGraphemes(3000)).max(30000).optional(),\n textContent: z.string().optional(),\n tags: z.array(z.string().refine(maxGraphemes(128)).max(1280)).optional(),\n coverImage: blobRefSchema.optional(),\n contributors: z.array(contributorSchema).optional(),\n bskyPostRef: strongRefSchema.optional(),\n labels: selfLabelsSchema.optional(),\n })\n .passthrough();\n\nexport type StandardSiteDocumentRecord = z.infer<typeof StandardSiteDocumentRecordSchema>;\n\n/**\n * site.standard.graph.subscription\n *\n * Authored by a viewer to declare a subscription to a publication. Used\n * by Phase 4 inline-subscribe path. Record key is a TID; the AT-URI\n * shape is `at://<viewer-did>/site.standard.graph.subscription/<rkey>`.\n */\nexport const StandardSiteSubscriptionRecordSchema = z.object({\n publication: atUriSchema,\n createdAt: datetimeSchema.optional(),\n});\n\nexport type StandardSiteSubscriptionRecord = z.infer<typeof StandardSiteSubscriptionRecordSchema>;\n\n/**\n * site.standard.graph.recommend\n *\n * Document-level \"like\" record. Same scope as subscription via the\n * site.standard.authSocial OAuth permission-set, so Phase 4 unlocks\n * inline likes alongside inline subscribes.\n */\nexport const StandardSiteRecommendRecordSchema = z.object({\n document: atUriSchema,\n createdAt: datetimeSchema,\n});\n\nexport type StandardSiteRecommendRecord = z.infer<typeof StandardSiteRecommendRecordSchema>;\n","/**\n * Publisher allowlist for the Standard.site rich embed.\n *\n * Mirrors `bluesky-social/social-app`\n * `src/components/Post/Embed/StandardSiteEmbed/publishers.ts`. The only\n * gate this provides is which publishers get the highlighted\n * \"Subscribe on {Publisher}\" CTA with a publisher icon vs the plain\n * \"View publication\" fallback — any Standard.site embed renders\n * regardless of allowlist membership.\n *\n * Sync policy: review additions against the upstream bsky list weekly;\n * Singi Labs reviews before merge.\n */\n\nexport interface Publisher {\n /** Lowercase host. Subdomains are matched via `hostMatches`. */\n host: string;\n /** Human-facing publisher name shown in CTA copy. */\n name: string;\n /**\n * Stable identifier used by clients to look up brand icons. The SDK\n * does not ship icon assets — sifa-web maintains them keyed by this\n * id so React Native vs web rendering can diverge.\n */\n iconKey: 'leaflet' | 'pckt' | 'offprint';\n}\n\nexport const STANDARD_SITE_PUBLISHERS: readonly Publisher[] = Object.freeze([\n { host: 'leaflet.pub', name: 'Leaflet', iconKey: 'leaflet' },\n { host: 'pckt.blog', name: 'pckt', iconKey: 'pckt' },\n { host: 'offprint.app', name: 'Offprint', iconKey: 'offprint' },\n]);\n\n/**\n * Returns true when `host` exactly matches `target` or is a subdomain of\n * it. Hosts are expected to be lowercase already.\n */\nexport function hostMatches(host: string, target: string): boolean {\n return host === target || host.endsWith('.' + target);\n}\n\nfunction hostFromUri(uri: string | undefined | null): string | null {\n if (!uri) return null;\n try {\n return new URL(uri).host.toLowerCase();\n } catch {\n return null;\n }\n}\n\n/**\n * Match a publisher by host. Returns the publisher when `host` is on the\n * allowlist (exact or subdomain match), null otherwise. Host should be\n * lowercase.\n */\nexport function matchPublisherByHost(host: string | null | undefined): Publisher | null {\n if (!host) return null;\n const lower = host.toLowerCase();\n return STANDARD_SITE_PUBLISHERS.find((p) => hostMatches(lower, p.host)) ?? null;\n}\n\n/**\n * Match a publisher by URI. Convenience wrapper around\n * `matchPublisherByHost` for callers that have a publication URL handy.\n */\nexport function matchPublisherByUri(uri: string | undefined | null): Publisher | null {\n return matchPublisherByHost(hostFromUri(uri));\n}\n","/**\n * Linkblog-share detection for the Standard.site document family.\n *\n * A \"linkblog\" (e.g. Skyreader) writes a `site.standard.document` to the\n * user's PDS for every *external* article they share. Those documents are\n * valid Standard.site posts, so they surface in Sifa's activity stream and\n * profile portfolio as if the user authored them — but the user only shared\n * someone else's writing (sifa-workspace#351).\n *\n * These predicates identify such shares so callers can exclude them, while\n * leaving genuinely authored Standard.site posts (Leaflet, pckt, Offprint\n * essays) untouched.\n *\n * Signals, most to least reliable:\n * 1. The Skyreader provenance marker on the document (`skyreaderLinkblog`).\n * 2. The document's parent publication is itself a linkblog (the marker\n * lives on the publication even when older documents lack their own).\n * Callers resolve the publication and pass `publicationIsLinkblog`.\n * 3. A `links` entry with `rel: \"repost\"` — a quote-reshare, inherently\n * not the user's own writing.\n * 4. Heuristic: a `links` entry with `rel: \"related\"` pointing to an\n * external host different from the document's own publication host —\n * the document's subject is an off-site article. Only applied when the\n * caller supplies the resolved `publicationHost`, so an authored post\n * that merely cites an external resource is never hidden on a guess.\n */\n\n/**\n * Discovery marker Skyreader stamps on every linkblog publication and on\n * link-share documents. Value is a fixed URL, not a per-user value.\n */\nexport const SKYREADER_LINKBLOG_MARKER_URL = 'https://skyreader.app/linkblog';\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\n/** A non-empty `skyreaderLinkblog` marker field. */\nfunction hasLinkblogMarker(record: Record<string, unknown>): boolean {\n const marker = record.skyreaderLinkblog;\n return typeof marker === 'string' && marker.length > 0;\n}\n\nfunction hostOf(uri: string): string | null {\n try {\n return new URL(uri).host.toLowerCase();\n } catch {\n return null;\n }\n}\n\n/**\n * True when a `site.standard.publication` record is a linkblog rather than an\n * authored publication — i.e. it carries the Skyreader provenance marker.\n */\nexport function isLinkblogPublication(record: unknown): boolean {\n return isRecord(record) && hasLinkblogMarker(record);\n}\n\nexport interface LinkblogShareOptions {\n /**\n * True when the document's parent publication has been resolved and is\n * itself a linkblog (see {@link isLinkblogPublication}). Catches shares\n * whose document predates the per-document marker.\n */\n publicationIsLinkblog?: boolean;\n /**\n * Resolved host of the document's parent publication, enabling the\n * external-subject heuristic. Omit when the publication (hence its host)\n * could not be resolved — the heuristic then stays off.\n */\n publicationHost?: string;\n}\n\n/**\n * True when a `site.standard.document` is a shared/linkblogged external\n * article rather than the user's own writing. See the module comment for the\n * signal order.\n */\nexport function isLinkblogShareDocument(record: unknown, opts: LinkblogShareOptions = {}): boolean {\n if (!isRecord(record)) return false;\n\n // 1. Provenance marker on the document itself.\n if (hasLinkblogMarker(record)) return true;\n\n // 2. Parent publication is a linkblog (caller-resolved).\n if (opts.publicationIsLinkblog === true) return true;\n\n const links = record.links;\n if (!Array.isArray(links)) return false;\n\n const pubHost = opts.publicationHost?.toLowerCase();\n for (const link of links) {\n if (!isRecord(link) || typeof link.rel !== 'string') continue;\n\n // 3. Reshare of another record.\n if (link.rel === 'repost') return true;\n\n // 4. External-subject heuristic (only with a known publication host).\n if (link.rel === 'related' && pubHost && typeof link.uri === 'string') {\n const linkHost = hostOf(link.uri);\n if (linkHost && linkHost !== pubHost) return true;\n }\n }\n\n return false;\n}\n","import type { BasicTheme } from './schemas.js';\n\n/**\n * Publication metadata embedded in the augmented activity view by\n * sifa-api when an external link card matches an indexed publication.\n *\n * `uri` is the publication's AT-URI (e.g.\n * `at://did:plc:abc/site.standard.publication/xyz`). `theme` carries\n * the publication's own colors when supplied — clients should apply a\n * WCAG min-contrast fallback before honoring them.\n *\n * `icon` is left as `unknown` here because its representation depends\n * on the surface: blob ref on the wire, CDN URL after resolution.\n */\nexport interface PublicationSource {\n uri: string;\n title: string;\n icon?: unknown;\n theme?: BasicTheme;\n}\n\n/**\n * Shape attached to activity items whose external link card URL matches\n * a Standard.site record. Mirrors the relevant fields of bsky's\n * `StandardSiteEmbed` view so a sifa-web renderer can be near-1:1.\n *\n * `associatedRefs` carries AT-URIs the client may use in Phase 4 to\n * query subscription state for the viewer.\n */\nexport interface StandardSiteEmbedView {\n uri: string;\n source: PublicationSource;\n associatedRefs: { uri: string }[];\n createdAt?: string;\n readingTime?: number;\n}\n\nexport const STANDARD_SITE_PUBLICATION_NSID = 'site.standard.publication' as const;\nexport const STANDARD_SITE_DOCUMENT_NSID = 'site.standard.document' as const;\nexport const STANDARD_SITE_SUBSCRIPTION_NSID = 'site.standard.graph.subscription' as const;\nexport const STANDARD_SITE_RECOMMEND_NSID = 'site.standard.graph.recommend' as const;\n\n/**\n * Pre-defined OAuth permission-set the consumer apps request to write\n * subscription + recommend records on behalf of the viewer. The actual\n * permission-set is published under\n * `at://did:plc:re3ebnp5v7ffagz6rb6xfei4/com.atproto.lexicon.schema/site.standard.authSocial`.\n */\nexport const STANDARD_SITE_AUTH_SOCIAL_NSID = 'site.standard.authSocial' as const;\n\nconst COLLECTION_SET = new Set<string>([\n STANDARD_SITE_PUBLICATION_NSID,\n STANDARD_SITE_DOCUMENT_NSID,\n STANDARD_SITE_SUBSCRIPTION_NSID,\n STANDARD_SITE_RECOMMEND_NSID,\n]);\n\n/**\n * True when the AT-URI's collection segment is a Standard.site\n * collection. Useful for detecting Standard.site embed augmentation on\n * arbitrary activity items.\n */\nexport function isStandardSiteAtUri(uri: string): boolean {\n if (!uri.startsWith('at://')) return false;\n const segments = uri.slice('at://'.length).split('/');\n const collection = segments[1];\n return collection !== undefined && COLLECTION_SET.has(collection);\n}\n\n/**\n * True when any `associatedRefs[].uri` is a Standard.site collection\n * AT-URI. The bsky client uses the same check to gate the\n * `StandardSiteEmbed` renderer.\n */\nexport function hasStandardSiteAssociatedRef(refs: { uri: string }[] | undefined): boolean {\n if (!refs) return false;\n return refs.some((r) => isStandardSiteAtUri(r.uri));\n}\n"]}
|
package/dist/query/client.js
CHANGED
|
@@ -96,8 +96,26 @@ async function apiFetchOrNull(config, path, options = {}) {
|
|
|
96
96
|
throw e;
|
|
97
97
|
}
|
|
98
98
|
}
|
|
99
|
+
function parseWriteIssues(raw) {
|
|
100
|
+
if (!Array.isArray(raw)) return void 0;
|
|
101
|
+
const issues = [];
|
|
102
|
+
for (const entry of raw) {
|
|
103
|
+
if (!entry || typeof entry !== "object") continue;
|
|
104
|
+
const { path, message, code } = entry;
|
|
105
|
+
if (typeof message !== "string" || !Array.isArray(path)) continue;
|
|
106
|
+
const segments = path;
|
|
107
|
+
if (!segments.every((p) => typeof p === "string" || typeof p === "number")) continue;
|
|
108
|
+
issues.push({
|
|
109
|
+
path: segments,
|
|
110
|
+
message,
|
|
111
|
+
...typeof code === "string" ? { code } : {}
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
return issues;
|
|
115
|
+
}
|
|
99
116
|
function extractWriteError(e) {
|
|
100
117
|
const body = e.body && typeof e.body === "object" ? e.body : {};
|
|
118
|
+
const issues = parseWriteIssues(body.issues);
|
|
101
119
|
return {
|
|
102
120
|
// Fastify puts the detail in `message` and the status phrase in `error`;
|
|
103
121
|
// sifa-api's own handlers (and the rate limiter) only set `error`.
|
|
@@ -105,7 +123,8 @@ function extractWriteError(e) {
|
|
|
105
123
|
status: e.status,
|
|
106
124
|
...e.retryAfterSeconds !== void 0 ? { retryAfterSeconds: e.retryAfterSeconds } : {},
|
|
107
125
|
...body.pdsHost ? { pdsHost: body.pdsHost } : {},
|
|
108
|
-
...typeof body.code === "string" && body.code !== "" ? { code: body.code } : {}
|
|
126
|
+
...typeof body.code === "string" && body.code !== "" ? { code: body.code } : {},
|
|
127
|
+
...issues ? { issues } : {}
|
|
109
128
|
};
|
|
110
129
|
}
|
|
111
130
|
async function apiWrite(config, path, method, options = {}) {
|
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 /** 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 * Failed branch of a {@link WriteResult}.\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 WriteFailure {\n success: false;\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 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 * Stable, machine-readable error code from the response body (for example\n * `'CustomDomainRequired'`), when sifa-api sends one (sifa-workspace#736).\n * Branch on this instead of matching the `error` text, which can change.\n * Present only when the body carries a non-empty string `code`.\n */\n code?: string;\n}\n\n/**\n * Successful branch of a {@link WriteResult}: the response body fields\n * (`TExtra`) plus the optional failure fields. A body field that shares a name\n * with a failure field (e.g. a body `status`) keeps its body type here, so it\n * never collides with the HTTP status on the failure branch.\n */\nexport type WriteSuccess<TExtra extends object = Record<never, never>> = { success: true } & Omit<\n WriteFailure,\n 'success' | keyof TExtra\n> &\n TExtra;\n\n/**\n * Result returned by record-write mutations (create / update / delete),\n * discriminated on `success`. Narrow on `success` to read a body `status`\n * (success) or the HTTP `status` (failure). Other fields stay readable without\n * narrowing.\n */\nexport type WriteResult<TExtra extends object = Record<never, never>> =\n WriteSuccess<TExtra> | (WriteFailure & Partial<Omit<TExtra, keyof WriteFailure>>);\n\n/** Result returned by create mutations. Includes the newly created `rkey`. */\nexport type CreateResult = WriteResult<{ rkey?: string }>;\n\ninterface ApiErrorBody {\n message?: string;\n error?: string;\n pdsHost?: string;\n code?: unknown;\n}\n\nfunction extractWriteError(e: ApiError): Omit<WriteFailure, 'success'> {\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 ...(typeof body.code === 'string' && body.code !== '' ? { code: body.code } : {}),\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) and the `code` field when the AppView sends a\n * stable error code.\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, status?, retryAfterSeconds?,\n * pdsHost?, code? }`. 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) };\n }\n return { success: false, error: 'Network error' };\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<WriteResult<{ rkey?: string } & 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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IAGL,OAAO,KAAK,WAAW,KAAK,SAAS,mBAAmB,EAAE,MAAM;AAAA,IAChE,QAAQ,EAAE;AAAA,IACV,GAAI,EAAE,sBAAsB,SAAY,EAAE,mBAAmB,EAAE,kBAAkB,IAAI,CAAC;AAAA,IACtF,GAAI,KAAK,UAAU,EAAE,SAAS,KAAK,QAAQ,IAAI,CAAC;AAAA,IAChD,GAAI,OAAO,KAAK,SAAS,YAAY,KAAK,SAAS,KAAK,EAAE,MAAM,KAAK,KAAK,IAAI,CAAC;AAAA,EACjF;AACF;AAmBA,eAAsB,SACpB,QACA,MACA,QACA,UAA2C,CAAC,GACd;AAC9B,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,GACH;AAClD,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 * Failed branch of a {@link WriteResult}.\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 WriteFailure {\n success: false;\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 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 * Stable, machine-readable error code from the response body (for example\n * `'CustomDomainRequired'`), when sifa-api sends one (sifa-workspace#736).\n * Branch on this instead of matching the `error` text, which can change.\n * Present only when the body carries a non-empty string `code`.\n */\n code?: string;\n /**\n * Field-level validation problems from a 400 `ValidationError` body (the\n * Zod `error.issues` of sifa-api). Present only when the body carries an\n * array; malformed entries are dropped. `path` locates the field.\n */\n issues?: WriteIssue[];\n}\n\n/** One validation problem reported by sifa-api, shaped like a Zod issue. */\nexport interface WriteIssue {\n path: (string | number)[];\n message: string;\n code?: string;\n}\n\n/**\n * Successful branch of a {@link WriteResult}: the response body fields\n * (`TExtra`) plus the optional failure fields. A body field that shares a name\n * with a failure field (e.g. a body `status`) keeps its body type here, so it\n * never collides with the HTTP status on the failure branch.\n */\nexport type WriteSuccess<TExtra extends object = Record<never, never>> = { success: true } & Omit<\n WriteFailure,\n 'success' | keyof TExtra\n> &\n TExtra;\n\n/**\n * Result returned by record-write mutations (create / update / delete),\n * discriminated on `success`. Narrow on `success` to read a body `status`\n * (success) or the HTTP `status` (failure). Other fields stay readable without\n * narrowing.\n */\nexport type WriteResult<TExtra extends object = Record<never, never>> =\n WriteSuccess<TExtra> | (WriteFailure & Partial<Omit<TExtra, keyof WriteFailure>>);\n\n/** Result returned by create mutations. Includes the newly created `rkey`. */\nexport type CreateResult = WriteResult<{ rkey?: string }>;\n\ninterface ApiErrorBody {\n message?: string;\n error?: string;\n pdsHost?: string;\n code?: unknown;\n issues?: unknown;\n}\n\nfunction parseWriteIssues(raw: unknown): WriteIssue[] | undefined {\n if (!Array.isArray(raw)) return undefined;\n const issues: WriteIssue[] = [];\n for (const entry of raw as unknown[]) {\n if (!entry || typeof entry !== 'object') continue;\n const { path, message, code } = entry as { path?: unknown; message?: unknown; code?: unknown };\n if (typeof message !== 'string' || !Array.isArray(path)) continue;\n const segments: unknown[] = path;\n if (!segments.every((p) => typeof p === 'string' || typeof p === 'number')) continue;\n issues.push({\n path: segments,\n message,\n ...(typeof code === 'string' ? { code } : {}),\n });\n }\n return issues;\n}\n\nfunction extractWriteError(e: ApiError): Omit<WriteFailure, 'success'> {\n const body = (e.body && typeof e.body === 'object' ? e.body : {}) as ApiErrorBody;\n const issues = parseWriteIssues(body.issues);\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 ...(typeof body.code === 'string' && body.code !== '' ? { code: body.code } : {}),\n ...(issues ? { issues } : {}),\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) and the `code` field when the AppView sends a\n * stable error code.\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, status?, retryAfterSeconds?,\n * pdsHost?, code? }`. 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) };\n }\n return { success: false, error: 'Network error' };\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<WriteResult<{ rkey?: string } & 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;AAM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,UAAoD,CAAC,GACH;AAClD,SAAO,SAAqC,QAAQ,MAAM,QAAQ;AAAA,IAChE;AAAA,IACA,GAAG;AAAA,EACL,CAAC;AACH;","names":[]}
|
|
@@ -100,8 +100,26 @@ async function apiFetchOrNull(config, path, options = {}) {
|
|
|
100
100
|
throw e;
|
|
101
101
|
}
|
|
102
102
|
}
|
|
103
|
+
function parseWriteIssues(raw) {
|
|
104
|
+
if (!Array.isArray(raw)) return void 0;
|
|
105
|
+
const issues = [];
|
|
106
|
+
for (const entry of raw) {
|
|
107
|
+
if (!entry || typeof entry !== "object") continue;
|
|
108
|
+
const { path, message, code } = entry;
|
|
109
|
+
if (typeof message !== "string" || !Array.isArray(path)) continue;
|
|
110
|
+
const segments = path;
|
|
111
|
+
if (!segments.every((p) => typeof p === "string" || typeof p === "number")) continue;
|
|
112
|
+
issues.push({
|
|
113
|
+
path: segments,
|
|
114
|
+
message,
|
|
115
|
+
...typeof code === "string" ? { code } : {}
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
return issues;
|
|
119
|
+
}
|
|
103
120
|
function extractWriteError(e) {
|
|
104
121
|
const body = e.body && typeof e.body === "object" ? e.body : {};
|
|
122
|
+
const issues = parseWriteIssues(body.issues);
|
|
105
123
|
return {
|
|
106
124
|
// Fastify puts the detail in `message` and the status phrase in `error`;
|
|
107
125
|
// sifa-api's own handlers (and the rate limiter) only set `error`.
|
|
@@ -109,7 +127,8 @@ function extractWriteError(e) {
|
|
|
109
127
|
status: e.status,
|
|
110
128
|
...e.retryAfterSeconds !== void 0 ? { retryAfterSeconds: e.retryAfterSeconds } : {},
|
|
111
129
|
...body.pdsHost ? { pdsHost: body.pdsHost } : {},
|
|
112
|
-
...typeof body.code === "string" && body.code !== "" ? { code: body.code } : {}
|
|
130
|
+
...typeof body.code === "string" && body.code !== "" ? { code: body.code } : {},
|
|
131
|
+
...issues ? { issues } : {}
|
|
113
132
|
};
|
|
114
133
|
}
|
|
115
134
|
async function apiWrite(config, path, method, options = {}) {
|
|
@@ -2180,8 +2199,8 @@ var sifaQueryKeys = {
|
|
|
2180
2199
|
}
|
|
2181
2200
|
};
|
|
2182
2201
|
function maxGraphemes(max) {
|
|
2202
|
+
const segmenter = new Intl.Segmenter(void 0, { granularity: "grapheme" });
|
|
2183
2203
|
return (value) => {
|
|
2184
|
-
const segmenter = new Intl.Segmenter(void 0, { granularity: "grapheme" });
|
|
2185
2204
|
let count = 0;
|
|
2186
2205
|
for (const _ of segmenter.segment(value)) {
|
|
2187
2206
|
count++;
|
|
@@ -2190,6 +2209,36 @@ function maxGraphemes(max) {
|
|
|
2190
2209
|
return true;
|
|
2191
2210
|
};
|
|
2192
2211
|
}
|
|
2212
|
+
function maxBytes(max) {
|
|
2213
|
+
const encoder = new TextEncoder();
|
|
2214
|
+
return (value) => {
|
|
2215
|
+
if (value.length * 3 <= max) return true;
|
|
2216
|
+
return encoder.encode(value).length <= max;
|
|
2217
|
+
};
|
|
2218
|
+
}
|
|
2219
|
+
function lexiconString(graphemes, bytes) {
|
|
2220
|
+
return zod.z.string().refine(maxGraphemes(graphemes), {
|
|
2221
|
+
message: `Must be at most ${graphemes} characters`,
|
|
2222
|
+
abort: true
|
|
2223
|
+
}).refine(maxBytes(bytes), {
|
|
2224
|
+
message: "This text is too long. Emoji and some scripts take more space, so shorten it a little."
|
|
2225
|
+
});
|
|
2226
|
+
}
|
|
2227
|
+
var PROFILE_TEXT_LIMITS = {
|
|
2228
|
+
displayName: { graphemes: 64, bytes: 640 },
|
|
2229
|
+
givenName: { graphemes: 64, bytes: 640 },
|
|
2230
|
+
pronouns: { graphemes: 20, bytes: 200 },
|
|
2231
|
+
headline: { graphemes: 120, bytes: 1200 },
|
|
2232
|
+
about: { graphemes: 5e3, bytes: 5e4 }
|
|
2233
|
+
};
|
|
2234
|
+
function profileText(limit) {
|
|
2235
|
+
return lexiconString(limit.graphemes, limit.bytes);
|
|
2236
|
+
}
|
|
2237
|
+
profileText(PROFILE_TEXT_LIMITS.displayName);
|
|
2238
|
+
profileText(PROFILE_TEXT_LIMITS.givenName);
|
|
2239
|
+
profileText(PROFILE_TEXT_LIMITS.pronouns);
|
|
2240
|
+
profileText(PROFILE_TEXT_LIMITS.headline);
|
|
2241
|
+
profileText(PROFILE_TEXT_LIMITS.about);
|
|
2193
2242
|
var didSchema = zod.z.string().regex(/^did:[a-z]+:[a-zA-Z0-9._:%-]+$/, "Invalid DID");
|
|
2194
2243
|
var datetimeSchema = zod.z.string().datetime({ offset: true });
|
|
2195
2244
|
var partialDateSchema = zod.z.string().regex(/^\d{4}(-\d{2}(-\d{2}(T.+)?)?)?$/, "Expected YYYY, YYYY-MM, YYYY-MM-DD, or a datetime");
|