@stacksjs/socials 0.75.706 → 0.75.707

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.
@@ -58,9 +58,15 @@ declare interface FacetCandidate {
58
58
  type: 'link' | 'tag' | 'mention'
59
59
  value: string
60
60
  }
61
+ export declare interface BlueskyPostReference {
62
+ uri: string
63
+ cid: string
64
+ }
61
65
  /** What only Bluesky takes, as the third argument to `publish`. */
62
66
  export declare interface BlueskyPublishOptions {
63
67
  rkey?: string
68
+ quote?: BlueskyPostReference
69
+ selfLabels?: readonly string[]
64
70
  }
65
71
  export declare class BlueskyApiError extends SocialApiError {
66
72
  constructor(message: string, status: number, body: string, options?: SocialApiErrorOptions);
@@ -77,6 +83,7 @@ export declare class BlueskyPublishingDriver implements SocialPublishingDriver,
77
83
  createSession(credentials: BlueskySessionCredentials): Promise<BlueskySession>;
78
84
  protected signIn(identifier: string, password: string): Promise<CreateSessionResponse>;
79
85
  refreshSession(refreshToken: string): Promise<BlueskySession>;
86
+ resolveQuote(identity: SocialIdentityCredentials, address: string): Promise<BlueskyPostReference>;
80
87
  publish(identity: SocialIdentityCredentials, post: PublishPostInput, options?: BlueskyPublishOptions): Promise<PublishedPost>;
81
88
  metrics(identity: SocialIdentityCredentials, uris: string[]): Promise<PostMetrics[]>;
82
89
  postMetrics(identity: SocialIdentityCredentials, uris: string[]): Promise<Array<{ uri: string, likeCount: number, repostCount: number, replyCount: number }>>;
@@ -11,18 +11,34 @@ export declare interface MastodonAccount {
11
11
  displayName?: string
12
12
  url: string
13
13
  }
14
+ export declare interface MastodonPoll {
15
+ options: readonly string[]
16
+ expiresIn: number
17
+ multiple?: boolean
18
+ hideTotals?: boolean
19
+ }
20
+ export declare interface MastodonPollLimits {
21
+ maxOptions: number
22
+ maxCharactersPerOption: number
23
+ minExpiration: number
24
+ maxExpiration: number
25
+ }
14
26
  /** What only Mastodon takes, as the third argument to `publish`. */
15
27
  export declare interface MastodonPublishOptions {
16
28
  idempotencyKey?: string
17
29
  visibility?: MastodonVisibility
18
30
  spoilerText?: string
19
31
  language?: string
32
+ poll?: MastodonPoll
33
+ quotedStatusId?: string
20
34
  }
21
35
  /** One instance's posting limits, from `/api/v2/instance`. */
22
36
  export declare interface MastodonLimits {
23
37
  characters: number
24
38
  charactersPerUrl: number
25
39
  mediaAttachments: number
40
+ poll?: MastodonPollLimits
41
+ quotePosts?: true
26
42
  }
27
43
  export type MastodonVisibility = 'public' | 'unlisted' | 'private' | 'direct';
28
44
  export declare class MastodonApiError extends SocialApiError {
@@ -49,6 +65,7 @@ export declare class MastodonPublishingDriver implements SocialPublishingDriver,
49
65
  protected instanceOf(identity: SocialIdentityCredentials): string;
50
66
  protected tokenOf(identity: SocialIdentityCredentials): string;
51
67
  verifyCredentials(identity: SocialIdentityCredentials): Promise<MastodonAccount>;
68
+ resolvePostId(identity: SocialIdentityCredentials, permalink: string): Promise<string>;
52
69
  uploadMedia(identity: SocialIdentityCredentials, bytes: Uint8Array, mimeType: string, altText?: string): Promise<string>;
53
70
  publish(identity: SocialIdentityCredentials, post: PublishPostInput, options?: MastodonPublishOptions): Promise<PublishedPost>;
54
71
  timeline(_identity: SocialIdentityCredentials, _query?: TimelineQuery): Promise<TimelineResult>;
package/dist/index.js CHANGED
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- var Ke=import.meta.require;import{Buffer as N}from"buffer";class w{clientId;clientSecret;redirectUrl;parameters={};_scopes=[];scopeSeparator=",";_stateless=!1;_usesPKCE=!1;_codeVerifier=null;_state=null;user=null;constructor(e){this.clientId=e.clientId,this.clientSecret=e.clientSecret,this.redirectUrl=e.redirectUrl}async getCodeFields(e=null){let t={client_id:this.clientId,redirect_uri:this.redirectUrl,scope:this.formatScopes(this.getScopes(),this.scopeSeparator),response_type:"code"};if(this.usesState())t.state=e;return{...t,...await this.pkceFields(),...this.parameters}}formatScopes(e,t){return e.join(t)}async userFromToken(e){return{...await this.getUserByToken(e),token:e}}scopes(e){let t=Array.isArray(e)?e:[e];return this._scopes=[...new Set([...this._scopes,...t])],this}setScopes(e){let t=Array.isArray(e)?e:[e];return this._scopes=[...new Set(t)],this}getScopes(){return this._scopes}setRedirectUrl(e){if(typeof e!=="string"||e.length===0)throw Error("[socials] setRedirectUrl requires a non-empty string");let t;try{t=new URL(e)}catch{throw Error(`[socials] setRedirectUrl: invalid URL: ${e}`)}if(t.protocol!=="https:"&&t.protocol!=="http:")throw Error(`[socials] setRedirectUrl protocol must be http(s)://, got ${t.protocol}`);return this.redirectUrl=e,this}withState(e){if(typeof e!=="string"||e.length===0)throw Error("[socials] withState requires a non-empty string");return this._state=e,this}resolveState(){return this._state??this.getState()}usesState(){return!this._stateless}validateState(e,t){if(typeof e!=="string"||typeof t!=="string")return!1;if(e.length===0||t.length===0)return!1;if(e.length!==t.length)return!1;try{let{timingSafeEqual:r}=Ke("crypto");return r(N.from(e,"utf8"),N.from(t,"utf8"))}catch{let r=0;for(let i=0;i<e.length;i++)r|=e.charCodeAt(i)^t.charCodeAt(i);return r===0}}isStateless(){return this._stateless}stateless(){return this._stateless=!0,this}getState(){let e=new Uint8Array(32);return crypto.getRandomValues(e),Array.from(e).map((t)=>t.toString(16).padStart(2,"0")).join("")}usesPKCE(){return this._usesPKCE}enablePKCE(){return this._usesPKCE=!0,this}getCodeVerifier(){if(this._codeVerifier===null){let e=new Uint8Array(32);crypto.getRandomValues(e),this._codeVerifier=N.from(e).toString("base64url")}return this._codeVerifier}getPkceVerifier(){return this._codeVerifier}withCodeVerifier(e){if(!e)throw Error("A PKCE code verifier must be a non-empty string");return this._usesPKCE=!0,this._codeVerifier=e,this}async pkceFields(){if(!this.usesPKCE())return{};return{code_challenge:await this.getCodeChallenge(),code_challenge_method:this.getCodeChallengeMethod()}}pkceTokenFields(){if(!this.usesPKCE())return{};if(this._codeVerifier===null)throw Error("PKCE is enabled but no code verifier is known for this exchange. Pass the one from getPkceVerifier() back with withCodeVerifier().");return{code_verifier:this._codeVerifier}}async getCodeChallenge(){let t=new TextEncoder().encode(this.getCodeVerifier()),r=await crypto.subtle.digest("SHA-256",t);return N.from(new Uint8Array(r)).toString("base64url")}getCodeChallengeMethod(){return"S256"}with(e){return this.parameters=e,this}async buildAuthUrlFromBase(e,t){let r=new URLSearchParams(await this.getCodeFields(t));return`${e}?${r.toString()}`}}import{Buffer as Se}from"buffer";import{createPrivateKey as Ze,sign as et}from"crypto";import{config as _}from"@stacksjs/config";class Xe extends Error{constructor(e="Invalid state"){super(e);this.name="InvalidStateException"}}class h extends Error{constructor(e){super(e);this.name="ConfigException"}}import{Buffer as ee}from"buffer";var ke=new Map,Qe=600000,We=60000;async function we(e,t){let r=await fetch(e);if(!r.ok)throw Error(`id_token verification failed: could not fetch signing keys from ${e} (HTTP ${r.status})`);let i=await r.json(),s=Array.isArray(i.keys)?i.keys:[];return ke.set(e,{keys:s,fetchedAt:t}),s}async function Ye(e,t,r){let i=ke.get(e),s=i!==void 0&&r-i.fetchedAt<Qe,n=s?i.keys:await we(e,r),o=n.find((a)=>a.kid===t);if(!o&&s&&r-i.fetchedAt>=We)n=await we(e,r),o=n.find((a)=>a.kid===t);if(!o)throw Error(`id_token verification failed: no signing key matches kid "${t}"`);if(o.kty!=="RSA")throw Error(`id_token verification failed: signing key "${t}" is ${o.kty}, expected RSA`);return o}function ye(e,t){try{return JSON.parse(ee.from(e,"base64url").toString("utf8"))}catch{throw Error(`id_token verification failed: ${t} is not valid JSON`)}}async function F(e,t){let r=e.split(".");if(r.length!==3)throw Error("id_token verification failed: malformed token");let[i,s,n]=r,o=ye(i,"header");if(o.alg!=="RS256")throw Error(`id_token verification failed: unsupported algorithm ${JSON.stringify(o.alg)}, expected RS256`);if(typeof o.kid!=="string"||o.kid==="")throw Error("id_token verification failed: header has no kid");let a=t.now??Date.now(),c=await Ye(t.jwksUrl,o.kid,a),d=await crypto.subtle.importKey("jwk",{kty:"RSA",n:c.n,e:c.e,alg:"RS256",ext:!0},{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!1,["verify"]);if(!await crypto.subtle.verify("RSASSA-PKCS1-v1_5",d,ee.from(n,"base64url"),ee.from(`${i}.${s}`)))throw Error("id_token verification failed: signature does not match the issuer's key");let u=ye(s,"payload"),p=(t.clockSkewSeconds??60)*1000,g=Array.isArray(t.issuer)?t.issuer:[t.issuer];if(!g.includes(u.iss))throw Error(`id_token verification failed: issuer is ${JSON.stringify(u.iss)}, expected ${g.map((Z)=>JSON.stringify(Z)).join(" or ")}`);let v=Array.isArray(t.audience)?t.audience:[t.audience];if(!(Array.isArray(u.aud)?u.aud:[u.aud]).some((Z)=>v.includes(Z)))throw Error("id_token verification failed: token is addressed to a different client");if(typeof u.exp!=="number"||u.exp*1000+p<=a)throw Error("id_token verification failed: token has expired");if(typeof u.iat==="number"&&u.iat*1000-p>a)throw Error("id_token verification failed: token was issued in the future");if(typeof u.nbf==="number"&&u.nbf*1000-p>a)throw Error("id_token verification failed: token is not valid yet");if(t.nonce!==void 0&&u.nonce!==t.nonce)throw Error("id_token verification failed: nonce does not match");if(typeof u.sub!=="string"||u.sub==="")throw Error("id_token verification failed: token has no subject");return u}class te extends w{baseUrl="https://appleid.apple.com";teamId="";keyId="";privateKey="";native=!1;constructor(e){super(e);this.teamId=e.teamId??"",this.keyId=e.keyId??"",this.privateKey=e.privateKey??"",this.native=e.native===!0}getConfig(){let e={clientId:this.clientId||(_.services.apple?.clientId??""),teamId:this.teamId||(_.services.apple?.teamId??""),keyId:this.keyId||(_.services.apple?.keyId??""),privateKey:(this.privateKey||(_.services.apple?.privateKey??"")).replace(/\\n/g,`
3
- `),redirectUrl:this.native?"":this.redirectUrl||(_.services.apple?.redirectUrl??""),scopes:this._scopes.length>0?this._scopes:_.services.apple?.scopes??["name","email"]};return this.setScopes(e.scopes),e}async getAuthUrl(){if(this.native)throw new h("A native Apple provider redeems the app's codes; the web flow needs the Service ID");let e=this.resolveState(),{clientId:t,redirectUrl:r,scopes:i}=this.getConfig();this.validateConfig();let s={client_id:t,redirect_uri:r,scope:i.join(" "),state:e,response_type:"code",...this.parameters};if(i.length>0)s.response_mode="form_post";return`${this.baseUrl}/auth/authorize?${new URLSearchParams(s).toString()}`}async getAccessToken(e){let{clientId:t,redirectUrl:r}=this.getConfig();this.validateConfig();let i=await fetch(`${this.baseUrl}/auth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:e,...this.native?{}:{redirect_uri:r},client_id:t,client_secret:this.generateClientSecret()})}),s=await i.json();if(!i.ok||s.error)throw Error(`Apple OAuth error: ${s.error_description??s.error??`HTTP ${i.status}`}`);if(!s.id_token)throw Error("Apple OAuth error: token response contained no id_token");return s.id_token}async getUserByToken(e,t={}){let{clientId:r}=this.getConfig(),i;try{i=await F(e,{jwksUrl:`${this.baseUrl}/auth/keys`,issuer:this.baseUrl,audience:r,nonce:t.nonce})}catch(o){throw Error(`Apple OAuth error: ${o instanceof Error?o.message:String(o)}`)}let s=typeof i.email==="string"?i.email:null,n=null;if(i.email_verified===!0||i.email_verified==="true")n=!0;else if(i.email_verified===!1||i.email_verified==="false")n=!1;return{id:String(i.sub),nickname:null,name:"",email:s,emailVerified:n,avatar:null,token:e,raw:i}}generateClientSecret(){let{clientId:e,teamId:t,keyId:r,privateKey:i}=this.getConfig(),s=Math.floor(Date.now()/1000),n={alg:"ES256",kid:r,typ:"JWT"},o={iss:t,iat:s,exp:s+3600,aud:this.baseUrl,sub:e},a=`${this.base64urlJson(n)}.${this.base64urlJson(o)}`,c;try{c=Ze(i)}catch(l){throw new h(`Apple private key could not be parsed: ${l instanceof Error?l.message:String(l)}`)}let d=et("sha256",Se.from(a),{key:c,dsaEncoding:"ieee-p1363"});return`${a}.${d.toString("base64url")}`}base64urlJson(e){return Se.from(JSON.stringify(e)).toString("base64url")}validateConfig(){let{clientId:e,teamId:t,keyId:r,privateKey:i,redirectUrl:s}=this.getConfig();if(!e)throw new h(this.native?"Apple client ID (the app's bundle ID) not provided":"Apple client ID (Service ID) not provided");if(!t)throw new h("Apple team ID not provided");if(!r)throw new h("Apple key ID not provided");if(!i)throw new h("Apple private key not provided");if(!s&&!this.native)throw new h("Apple redirect URL not provided")}getTokenUrl(){return`${this.baseUrl}/auth/token`}}import{fetchPublicUrl as ct}from"@stacksjs/security";var Cr=23,tt=/\bhttps?:\/\/[^\s<>]+|(?<![@\w.-])(?:[a-z0-9-]+\.)+(?:com|org|net|io|dev|app|co|social|blog|ai|me|info|xyz|tv|fm|us|uk|de|fr|jp|ca|au|nl|ch|se|no|es|it)\b(?:\/[^\s<>]*)?/gi,rt=/[.,;:!?)\]}'"]+$/,be;function xe(){return be??=new Intl.Segmenter(void 0,{granularity:"grapheme"}),be}function Pe(e){let t=0;for(let r of xe().segment(e))t++;return t}function ve(e){let t=[],r=0;for(let i of e.matchAll(tt)){let s=i[0].replace(rt,"");if(!s)continue;let n=i.index;if(n>r)t.push({link:!1,value:e.slice(r,n)});t.push({link:!0,value:s}),r=n+s.length}if(r<e.length)t.push({link:!1,value:e.slice(r)});return t}function it(e){return e<=4351||e>=8192&&e<=8205||e>=8208&&e<=8223||e>=8242&&e<=8247}function st(e){let t=0;for(let{segment:r}of xe().segment(e.normalize("NFC"))){if(/\p{Extended_Pictographic}|\p{Regional_Indicator}/u.test(r)){t+=2;continue}for(let i of r)t+=it(i.codePointAt(0))?1:2}return t}function nt(e,t,r={}){let i=String(t??"");switch(e){case"twitter":return ve(i).reduce((s,n)=>s+(n.link?23:st(n.value)),0);case"mastodon":{let s=r.linkLength??23;return ve(i).reduce((n,o)=>{if(o.link)return n+s;return n+Pe(o.value.replace(/(^|[^\w/])(@[\w.-]+)@[\w.-]+\.[a-z]{2,}/gi,"$1$2"))},0)}case"bluesky":case"threads":return Pe(i);default:return i.length}}function S(e,t,r,i={}){return r>0&&nt(e,t,i)>r}function z(e){let t;try{t=typeof e==="string"?JSON.parse(e):e}catch{return""}if(!t||typeof t!=="object")return"";let r=Array.isArray(t.errors)?t.errors[0]:void 0,i=[t.detail,t.error?.error_user_msg,t.error?.message,t.message,t.error_description,t.error_message,r?.detail,r?.message,typeof t.error==="string"?t.error:void 0];for(let s of i){let n=typeof s==="string"?s.replace(/\s+/g," ").trim():"";if(n&&n.length<=200&&n.includes(" ")&&!/[{}<>]/.test(n))return n.replace(/[.!]+$/,"")}return""}function ot(e,t){let r=(i)=>i.test(t);if(e===429||r(/rate.?limit|too many requests|usage cap|throttl|request limit reached/i))return"rate-limited";if(r(/duplicate|already (?:posted|published|exists)|DUPLICATE_POST/i))return"duplicate";if(e===401||r(/invalid.?token|expired.?token|token (?:has )?(?:expired|been revoked)|session has (?:expired|been invalidated)|OAuthException.*(?:expired|invalid)|REVOKED_ACCESS_TOKEN/i))return"expired";if(e===413||r(/media|image|video|attachment|aspect ratio|file size|unsupported (?:format|type)|blob/i))return"media";if(e===403||r(/permission|scope|not (?:allowed|authorized|permitted)|forbidden|ACCESS_DENIED|insufficient/i))return"permission";if(e===408||e>=500)return"temporary";if(e===400||e===404||e===409||e===422)return"content";if(r(/fetch failed|network|ENOTFOUND|ECONNREFUSED|ECONNRESET|EAI_AGAIN|timed? ?out|socket|aborted/i))return"temporary";return"unknown"}function q(e){let t=e??{},r=Number(t.status)||0,i=String(t.message??e??""),s=z(t.body),n=typeof t.body==="string"?t.body.slice(0,2000):"";return{kind:ot(r,`${s} ${n} ${r?"":i}`),status:r,reason:s}}function Ur(e){return q(e).kind==="expired"}class y extends Error{network;status;body;retryAfterMs;constructor(e,t,r,i,s={}){super(t);this.network=e;this.status=r;this.body=i;if(this.name="SocialApiError",s.retryAfterMs!==void 0)this.retryAfterMs=s.retryAfterMs}get kind(){return q(this).kind}get reason(){return z(this.body)}}function Ie(e,t){let r=e.trim();if(!r)return;if(/^\d+(?:\.\d+)?$/.test(r)){let s=Number(r);return s>1e9?Math.max(0,Math.round(s*1000-t)):Math.round(s*1000)}let i=Date.parse(r);return Number.isNaN(i)?void 0:Math.max(0,i-t)}function at(e,t){let r=t.now??Date.now(),i=e.get("retry-after");if(i){let n=Ie(i,r);if(n!==void 0)return n}if(!t.rateLimited)return;for(let n of["x-rate-limit-reset","ratelimit-reset","x-ratelimit-reset"]){let o=e.get(n),a=o?Ie(o,r):void 0;if(a!==void 0)return a}let s=0;for(let n of["x-business-use-case-usage","x-app-usage"]){let o=e.get(n);if(!o)continue;try{let a=JSON.parse(o),c=Array.isArray(a)?a:Object.values(a??{}).flat();for(let d of[a,...c]){let l=Number(d?.estimated_time_to_regain_access);if(Number.isFinite(l)&&l>s)s=l}}catch{}}return s>0?s*60000:void 0}function m(e,t,r){let i=z(r)||t.statusText||"no reason given",s=at(t.headers,{rateLimited:q({status:t.status,body:r}).kind==="rate-limited"});return[`${e} failed (${t.status}): ${i}`,t.status,r,s===void 0?{}:{retryAfterMs:s}]}var re="app.bsky.feed.post";function lt(e){let t=/^at:\/\/([^/]+)\/([^/]+)\/([^/]+)$/.exec(String(e||"").trim());if(!t)throw Error(`"${e}" is not a Bluesky post URI.`);return{repo:t[1],collection:t[2],rkey:t[3]}}class O extends y{constructor(e,t,r,i={}){super("bluesky",e,t,r,i);this.name="BlueskyApiError"}get isAuthError(){if(this.status===401||this.status===403)return!0;if(this.status!==400)return!1;try{return dt.includes(String(JSON.parse(this.body)?.error))}catch{return!1}}}var dt=["ExpiredToken","InvalidToken"],_e=1e6,ut=4,pt=3;function Mr(e){return e instanceof O&&e.isAuthError}var ht=new TextEncoder;function x(e){return ht.encode(e).length}function gt(e){let t=[],r=/https?:\/\/[^\s<>"']+/g;for(let o of e.matchAll(r)){let a=o[0].replace(/[),.;!?]+$/,"");t.push({byteStart:x(e.slice(0,o.index)),byteEnd:x(e.slice(0,o.index))+x(a),type:"link",value:a})}let i=(o,a)=>t.some((c)=>c.type==="link"&&o<c.byteEnd&&a>c.byteStart),s=/(^|\s)([#\uFF03])([^\s\u00AD\u2060\u200A-\u200D\u20E2]+)/gu;for(let o of e.matchAll(s)){let a=o[1],c=o[2],d=o[3];if(a===void 0||c===void 0||d===void 0)continue;let l=d.replace(/\p{P}+$/u,"");if(!l||!/[^\d\p{P}]/u.test(l)||[...l].length>64)continue;let u=(o.index??0)+a.length,p=x(e.slice(0,u)),g=p+x(c+l);if(i(p,g))continue;t.push({byteStart:p,byteEnd:g,type:"tag",value:l})}let n=/(^|\s)(@[a-z0-9][a-z0-9.-]*\.[a-z]{2,})/gi;for(let o of e.matchAll(n)){let a=o[1],c=o[2];if(a===void 0||c===void 0)continue;let d=(o.index??0)+a.length,l=x(e.slice(0,d)),u=l+x(c);if(i(l,u))continue;t.push({byteStart:l,byteEnd:u,type:"mention",value:c.slice(1).replace(/\.+$/,"")})}return t.sort((o,a)=>o.byteStart-a.byteStart)}async function mt(e,t={}){let r=(t.entryway??"https://bsky.social").replace(/\/+$/,""),i=(t.directory??"https://plc.directory").replace(/\/+$/,""),s=t.fetchJson??(async(n)=>{let a=n.startsWith(`${r}/`)||n.startsWith(`${i}/`)?await fetch(n,{redirect:"error"}):await ct(n,{},{maxRedirects:0,timeoutMs:1e4,maxBytes:262144});if(!a.ok)throw Error(`${a.status}`);return await a.json()});try{let n=e.trim(),o=n.startsWith("did:")?void 0:n.replace(/^@/,"").toLowerCase();if(o!==void 0){let p=await s(`${r}/xrpc/com.atproto.identity.resolveHandle?handle=${encodeURIComponent(o)}`);if(typeof p?.did!=="string")return;n=p.did}let a;if(/^did:plc:[a-z0-9]+$/i.test(n))a=`${i}/${n}`;else if(/^did:web:[a-z0-9.-]+$/i.test(n))a=`https://${n.slice(8)}/.well-known/did.json`;else return;let c=await s(a);if(c?.id!==n)return;let d=c.alsoKnownAs?.find((p)=>typeof p==="string"&&p.startsWith("at://"));if(o!==void 0&&d!==`at://${o}`)return;let l=(c.service??[]).find((p)=>(p?.id==="#atproto_pds"||p?.id===`${n}#atproto_pds`)&&p.type==="AtprotoPersonalDataServer");if(typeof l?.serviceEndpoint!=="string")return;let u=new URL(l.serviceEndpoint);if(u.protocol!=="https:"||u.username||u.password||u.search||u.hash)return;return u.href.replace(/\/+$/,"")}catch{return}}var ft="234567abcdefghijklmnopqrstuvwxyz";function Nr(e=Date.now(),t=Math.floor(Math.random()*1024)){let r=BigInt(Math.floor(e))*1000n<<10n|BigInt(t&1023),i="";for(let s=0;s<13;s++)i=ft[Number(r&31n)]+i,r>>=5n;return i}class H{provider="bluesky";characterLimit=300;service;configuredService;fetcher;constructor(e={}){this.service=e.service||"https://bsky.social",this.configuredService=Boolean(e.service),this.fetcher=e.fetcher}async createSession(e){let t=e.identifier.trim(),r=e.password.trim();if(!t)throw Error("Bluesky identifier is required.");if(!r)throw Error("Bluesky app password is required.");let i=await this.signIn(t,r),s=await this.getProfile({did:i.did,handle:i.handle,accessToken:i.accessJwt,refreshToken:i.refreshJwt}).catch(()=>{return});return{did:i.did,handle:i.handle,displayName:s?.displayName,accessJwt:i.accessJwt,refreshJwt:i.refreshJwt,service:this.service}}async signIn(e,t){let r=()=>this.post("/xrpc/com.atproto.server.createSession",{identifier:e,password:t});try{return await r()}catch(i){if(!(i instanceof O&&(i.status===400||i.status===401))||this.configuredService)throw i;let n=await mt(e,{entryway:this.service});if(!n||n===this.service)throw i;return this.service=n,await r()}}async refreshSession(e){if(!e)throw Error("Bluesky refresh token is required.");let t=await this.post("/xrpc/com.atproto.server.refreshSession",void 0,{authorization:`Bearer ${e}`});return{did:t.did,handle:t.handle,accessJwt:t.accessJwt,refreshJwt:t.refreshJwt}}async publish(e,t,r={}){let i=e.did||e.handle;if(!e.accessToken)throw Error("Bluesky access token is missing for this identity.");if(!i)throw Error("Bluesky identity DID or handle is required.");if(S("bluesky",t.text,this.characterLimit))throw Error(`Bluesky posts must be ${this.characterLimit} characters or fewer.`);let s={$type:"app.bsky.feed.post",text:t.text,createdAt:t.scheduledAt||new Date().toISOString()};if(t.langs?.length)s.langs=t.langs.slice(0,pt);if(t.reply)s.reply=t.reply;let n=t.facets??await this.buildFacets(t.text);if(n.length)s.facets=n;let o=[],a=(t.media||[]).filter((d)=>d.bytes?.length).slice(0,ut);if(a.length){let d=[];for(let l of a){let u=await this.uploadBlob(e,l.bytes,l.mimeType||"image/jpeg");d.push({image:u,alt:l.altText||""})}if(s.embed={$type:"app.bsky.embed.images",images:d},t.external)o.push("A Bluesky post holds one attachment, so the images went out and the link card did not. The link in the text still works.")}else if(t.external){let d={uri:t.external.uri,title:t.external.title,description:t.external.description||""},l=t.external.thumb;if(l?.bytes?.length)if(l.bytes.length>_e)o.push("The link card's picture is larger than Bluesky takes, so the card went out without it.");else try{d.thumb=await this.uploadBlob(e,l.bytes,l.mimeType)}catch{o.push("Bluesky did not take the link card's picture, so the card went out without it.")}s.embed={$type:"app.bsky.embed.external",external:d}}let c=await this.createPostRecord(e,i,s,r.rkey);return{provider:this.provider,uri:c.uri,cid:c.cid,url:this.toPostUrl(e.handle,c.uri),...o.length?{warnings:o}:{}}}async metrics(e,t){if(!e.accessToken)throw Error("Bluesky access token is missing for this identity.");let r=[];for(let i=0;i<t.length;i+=25){let s=new URL(`${this.service}/xrpc/app.bsky.feed.getPosts`);for(let o of t.slice(i,i+25))s.searchParams.append("uris",o);let n=await this.request(s,{headers:{authorization:`Bearer ${e.accessToken}`}});for(let o of n.posts||[])r.push({uri:o.uri,likes:o.likeCount??0,reposts:o.repostCount??0,replies:o.replyCount??0,quotes:o.quoteCount??0})}return r}async postMetrics(e,t){if(!e.accessToken)throw Error("Bluesky access token is missing for this identity.");if(t.length===0)return[];let r=new URL(`${this.service}/xrpc/app.bsky.feed.getPosts`);for(let s of t.slice(0,25))r.searchParams.append("uris",s);return((await this.request(r,{headers:{authorization:`Bearer ${e.accessToken}`}})).posts||[]).map((s)=>({uri:s.uri,likeCount:s.likeCount||0,repostCount:s.repostCount||0,replyCount:s.replyCount||0}))}async timeline(e,t={}){if(!e.accessToken)throw Error("Bluesky access token is missing for this identity.");let r=new URL(`${this.service}/xrpc/app.bsky.feed.getTimeline`);if(r.searchParams.set("limit",String(Math.min(Math.max(t.limit||30,1),100))),t.cursor)r.searchParams.set("cursor",t.cursor);let i=await this.request(r,{headers:{authorization:`Bearer ${e.accessToken}`}});return{cursor:i.cursor,items:(i.feed||[]).flatMap((s)=>{let n=s.post;if(!n?.uri||!n.author?.handle)return[];return[{uri:n.uri,authorHandle:n.author.handle,authorName:n.author.displayName,authorAvatar:n.author.avatar,postUrl:this.toPostUrl(n.author.handle,n.uri),body:n.record?.text||"",postedAt:n.record?.createdAt||new Date().toISOString(),likeCount:n.likeCount||0,repostCount:n.repostCount||0,replyCount:n.replyCount||0}]})}}async getProfile(e){if(!e.accessToken)throw Error("Bluesky access token is missing for this identity.");let t=e.did||e.handle;if(!t)throw Error("Bluesky identity DID or handle is required.");let r=new URL(`${this.service}/xrpc/app.bsky.actor.getProfile`);return r.searchParams.set("actor",t),await this.request(r,{headers:{authorization:`Bearer ${e.accessToken}`}})}async buildFacets(e){let t=[];for(let r of gt(e)){let i=null;if(r.type==="link")i={$type:"app.bsky.richtext.facet#link",uri:r.value};else if(r.type==="tag")i={$type:"app.bsky.richtext.facet#tag",tag:r.value};else if(r.type==="mention"){let s=await this.resolveHandle(r.value);if(s)i={$type:"app.bsky.richtext.facet#mention",did:s}}if(i)t.push({index:{byteStart:r.byteStart,byteEnd:r.byteEnd},features:[i]})}return t}async resolveHandle(e){try{let t=new URL(`${this.service}/xrpc/com.atproto.identity.resolveHandle`);return t.searchParams.set("handle",e),(await this.request(t,{})).did||null}catch{return null}}async uploadBlob(e,t,r){if(!e.accessToken)throw Error("Bluesky access token is missing for this identity.");if(t.length>_e)throw Error("Bluesky images must be 1MB or smaller.");return(await this.request(new URL(`${this.service}/xrpc/com.atproto.repo.uploadBlob`),{method:"POST",headers:{"content-type":r,authorization:`Bearer ${e.accessToken}`},body:new Uint8Array(t)})).blob}async listAuthoredPosts(e,t={}){let r=e.did||e.handle;if(!e.accessToken)throw Error("Bluesky access token is missing for this identity.");if(!r)throw Error("Bluesky identity DID or handle is required.");let i=new URL(`${this.service}/xrpc/com.atproto.repo.listRecords`);if(i.searchParams.set("repo",r),i.searchParams.set("collection",re),i.searchParams.set("limit",String(Math.min(Math.max(t.limit||100,1),100))),t.cursor)i.searchParams.set("cursor",t.cursor);let s=await this.request(i,{headers:{authorization:`Bearer ${e.accessToken}`}});return{cursor:s.cursor,posts:(s.records||[]).filter((n)=>n?.uri).map((n)=>({uri:n.uri,cid:n.cid,text:n.value?.text,postedAt:n.value?.createdAt,url:e.handle?this.toPostUrl(e.handle,n.uri):void 0}))}}async createPostRecord(e,t,r,i){let s=`Bearer ${e.accessToken}`;try{return await this.post("/xrpc/com.atproto.repo.createRecord",{repo:t,collection:re,...i?{rkey:i}:{},record:r},{authorization:s})}catch(n){if(!i||!(n instanceof O)||n.status>=500)throw n;let o=new URL(`${this.service}/xrpc/com.atproto.repo.getRecord`);o.searchParams.set("repo",t),o.searchParams.set("collection",re),o.searchParams.set("rkey",i);let a=await this.request(o,{headers:{authorization:s}}).catch(()=>{return});if(a?.uri&&a.cid&&a.value?.text===r.text)return{uri:a.uri,cid:a.cid};throw n}}async deletePost(e,t){if(!e.accessToken)throw Error("Bluesky access token is missing for this identity.");let{repo:r,collection:i,rkey:s}=lt(t.uri);await this.post("/xrpc/com.atproto.repo.deleteRecord",{repo:r,collection:i,rkey:s},{authorization:`Bearer ${e.accessToken}`})}async post(e,t,r={}){return await this.request(new URL(`${this.service}${e}`),{method:"POST",headers:{...t===void 0?{}:{"content-type":"application/json"},...r},...t===void 0?{}:{body:JSON.stringify(t)}})}async request(e,t){let r=await(this.fetcher??fetch)(e,{...t,redirect:"error"}),i=await r.text();if(!r.ok)throw new O(...m("Bluesky API",r,i));return i?JSON.parse(i):{}}toPostUrl(e,t){let r=t.split("/").pop();return`https://bsky.app/profile/${e}/post/${r}`}}import{fetcher as Te}from"@stacksjs/api";import{config as L}from"@stacksjs/config";var j="v24.0";function V(e){try{let t=JSON.parse(String(e?.body??""));return t.error?.code===100&&/does not exist/i.test(String(t.error.message))}catch{return!1}}class ie extends w{baseUrl="https://www.facebook.com";apiUrl="https://graph.facebook.com";get graphVersion(){return L.services.facebook?.graphVersion??j}getConfig(){let e={clientId:this.clientId||(L.services.facebook?.clientId??""),clientSecret:this.clientSecret||(L.services.facebook?.clientSecret??""),redirectUrl:this.redirectUrl||(L.services.facebook?.redirectUrl??""),scopes:L.services.facebook?.scopes??["email","public_profile"]};return this.setScopes(e.scopes),e}async getAuthUrl(){let e=this.resolveState(),{clientId:t,redirectUrl:r,scopes:i}=this.getConfig();return this.validateConfig(),`${this.baseUrl}/${this.graphVersion}/dialog/oauth?${new URLSearchParams({client_id:t,redirect_uri:r,scope:i.join(","),response_type:"code",...await this.pkceFields(),...this.parameters,state:e}).toString()}`}async getAccessToken(e){let{clientId:t,clientSecret:r,redirectUrl:i}=this.getConfig();this.validateConfig();let s=await Te.get(`${this.apiUrl}/${this.graphVersion}/oauth/access_token?${new URLSearchParams({client_id:t,client_secret:r,redirect_uri:i,code:e,...this.pkceTokenFields()}).toString()}`);if(s.data.error)throw Error(`Facebook OAuth error: ${s.data.error.message}`);return s.data.access_token}async getUserByToken(e){let t=await Te.withHeaders({Authorization:`Bearer ${e}`}).get(`${this.apiUrl}/${this.graphVersion}/me?${new URLSearchParams({fields:"id,name,email,picture"}).toString()}`);return{id:t.data.id,nickname:null,name:t.data.name,email:t.data.email??null,avatar:t.data.picture?.data.url??null,token:e,raw:t.data}}validateConfig(){let{clientId:e,clientSecret:t,redirectUrl:r}=this.getConfig();if(!e)throw new h("Facebook client ID not provided");if(!t)throw new h("Facebook client secret not provided");if(!r)throw new h("Facebook redirect URL not provided")}getTokenUrl(){return`${this.apiUrl}/${this.graphVersion}/oauth/access_token`}}import{fetcher as se}from"@stacksjs/api";import{config as G}from"@stacksjs/config";class ne extends w{baseUrl="https://github.com";apiUrl="https://api.github.com";getConfig(){let e={clientId:this.clientId||(G.services.github?.clientId??""),clientSecret:this.clientSecret||(G.services.github?.clientSecret??""),redirectUrl:this.redirectUrl||(G.services.github?.redirectUrl??""),scopes:this._scopes.length>0?this._scopes:G.services.github?.scopes??["read:user","user:email"]};return this.setScopes(e.scopes),e}async getAuthUrl(){let e=this.resolveState(),{clientId:t,redirectUrl:r,scopes:i}=this.getConfig();return this.validateConfig(),`${this.baseUrl}/login/oauth/authorize?${new URLSearchParams({client_id:t,redirect_uri:r,scope:i.join(" "),state:e,response_type:"code",...await this.pkceFields(),...this.parameters}).toString()}`}async getAccessToken(e){let{clientId:t,clientSecret:r,redirectUrl:i}=this.getConfig();this.validateConfig();let s=await se.post(`${this.baseUrl}/login/oauth/access_token`,{client_id:t,client_secret:r,code:e,redirect_uri:i,...this.pkceTokenFields()});if(s.data.error)throw Error(`GitHub OAuth error: ${s.data.error_description}`);return s.data.access_token}async getUserByToken(e){let[t,r]=await Promise.all([se.withHeaders({Accept:"application/vnd.github.v3+json",Authorization:`token ${e}`}).get(`${this.apiUrl}/user`),se.withHeaders({Accept:"application/vnd.github.v3+json",Authorization:`token ${e}`}).get(`${this.apiUrl}/user/emails`)]),i=this.pickEmail(r.data);return{id:t.data.id.toString(),nickname:t.data.login,name:t.data.name??t.data.login,email:i?.email??t.data.email??null,emailVerified:i?i.verified:null,avatar:t.data.avatar_url,token:e,raw:t.data}}pickEmail(e){if(!Array.isArray(e)||e.length===0)return null;let t=e.find((i)=>i.primary&&i.verified),r=e.find((i)=>i.verified);return t??r??e.find((i)=>i.primary)??e[0]??null}getEmail(e){return this.pickEmail(e)?.email??null}validateConfig(){let{clientId:e,clientSecret:t,redirectUrl:r}=this.getConfig();if(!e)throw new h("GitHub client ID not provided");if(!t)throw new h("GitHub client secret not provided");if(!r)throw new h("GitHub redirect URL not provided")}getTokenUrl(){return`${this.baseUrl}/login/oauth/access_token`}}import{fetcher as Ae}from"@stacksjs/api";import{config as J}from"@stacksjs/config";class oe extends w{baseUrl="https://accounts.google.com";apiUrl="https://www.googleapis.com";tokenUrl="https://oauth2.googleapis.com/token";tokenInfoUrl="https://oauth2.googleapis.com/tokeninfo";certsUrl="https://www.googleapis.com/oauth2/v3/certs";issuers=["https://accounts.google.com","accounts.google.com"];getConfig(){let e={clientId:this.clientId||(J.services.google?.clientId??""),clientSecret:this.clientSecret||(J.services.google?.clientSecret??""),redirectUrl:this.redirectUrl||(J.services.google?.redirectUrl??""),scopes:this._scopes.length>0?this._scopes:J.services.google?.scopes??["openid","email"]};return this.setScopes(e.scopes),e}async getAuthUrl(){let e=this.resolveState(),{clientId:t,redirectUrl:r,scopes:i}=this.getConfig();return this.validateConfig(),`${this.baseUrl}/o/oauth2/v2/auth?${new URLSearchParams({client_id:t,redirect_uri:r,scope:i.join(" "),state:e,response_type:"code",access_type:"offline",prompt:"consent",...await this.pkceFields(),...this.parameters}).toString()}`}async getAccessToken(e){let{clientId:t,clientSecret:r,redirectUrl:i}=this.getConfig();this.validateConfig();let s=await Ae.post(this.tokenUrl,{client_id:t,client_secret:r,code:e,redirect_uri:i,grant_type:"authorization_code",...this.pkceTokenFields()});if(s.data.error)throw Error(`Google OAuth error: ${s.data.error_description}`);return s.data.access_token}async getUserByToken(e){await this.assertTokenWasIssuedToUs(e);let t=await Ae.withHeaders({Authorization:`Bearer ${e}`}).get(`${this.apiUrl}/oauth2/v2/userinfo`);return{id:t.data.id,nickname:t.data.given_name,name:t.data.name,email:t.data.email,emailVerified:typeof t.data.verified_email==="boolean"?t.data.verified_email:null,avatar:t.data.picture,token:e,raw:t.data}}async getUserByIdToken(e,t={}){let{clientId:r}=this.getConfig(),i;try{i=await F(e,{jwksUrl:this.certsUrl,issuer:this.issuers,audience:r,nonce:t.nonce})}catch(n){throw Error(`Google OAuth error: ${n instanceof Error?n.message:String(n)}`)}let s=typeof i.email==="string"?i.email:"";return{id:String(i.sub),nickname:typeof i.given_name==="string"?i.given_name:null,name:typeof i.name==="string"?i.name:"",email:s,emailVerified:typeof i.email_verified==="boolean"?i.email_verified:i.email_verified==="true"?!0:i.email_verified==="false"?!1:null,avatar:typeof i.picture==="string"?i.picture:null,token:e,raw:i}}async assertTokenWasIssuedToUs(e){let{clientId:t}=this.getConfig(),r=await fetch(`${this.tokenInfoUrl}?access_token=${encodeURIComponent(e)}`);if(!r.ok)throw Error(`Google OAuth error: access token was not accepted by tokeninfo (HTTP ${r.status})`);let i=await r.json();if(i.error)throw Error(`Google OAuth error: ${i.error_description??i.error}`);let s=i.aud??i.audience;if(!s)throw Error("Google OAuth error: tokeninfo did not report an audience for the access token");if(s!==t)throw Error("Google OAuth error: access token was issued to a different client")}validateConfig(){let{clientId:e,clientSecret:t,redirectUrl:r}=this.getConfig();if(!e)throw new h("Google client ID not provided");if(!t)throw new h("Google client secret not provided");if(!r)throw new h("Google redirect URL not provided")}getTokenUrl(){return this.tokenUrl}}var wt=10,yt=1000,kt=20,Ce={likes:"likes",comments:"replies",shares:"shares",saved:"saves",reach:"reach",views:"views"};class k extends y{constructor(e,t,r,i={}){super("instagram",e,t,r,i);this.name="InstagramApiError"}get isAuthError(){return this.status===401||this.status===403||this.status===190}}class ae{provider="instagram";characterLimit=2200;maxImages=wt;containerTimeoutMs=300000;graphVersion;authBase;graphBase;constructor(e={}){this.graphVersion=e.graphVersion||j,this.authBase=e.authBase||"https://www.facebook.com",this.graphBase=e.graphBase||"https://graph.facebook.com"}getAuthUrl(e){let t=new URLSearchParams({client_id:e.clientId,redirect_uri:e.redirectUrl,scope:e.scopes.join(","),state:e.state,response_type:"code"});return`${this.authBase}/${this.graphVersion}/dialog/oauth?${t.toString()}`}async exchangeCode(e){let t=await this.graph("/oauth/access_token",{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:e.clientId,client_secret:e.clientSecret,redirect_uri:e.redirectUrl,code:e.code}).toString()});if(!t.access_token)throw new k("Facebook did not return an access token.",400,JSON.stringify(t));return{accessToken:t.access_token,expiresIn:t.expires_in}}async resolveAccount(e){for await(let t of this.pageAccounts(e))return{igUserId:t.igUserId,username:t.username,pageAccessToken:t.pageAccessToken};throw new k("No Instagram Business account is linked to your Facebook Pages.",400,"")}async listAccounts(e){let t=new Map;for await(let r of this.pageAccounts(e))if(r.pageId&&!t.has(r.pageId))t.set(r.pageId,{...r,pageId:r.pageId});return[...t.values()]}async*pageAccounts(e){let r=`/me/accounts?${new URLSearchParams({fields:"id,name,access_token,instagram_business_account{id,username}"}).toString()}`;for(let i=0;r&&i<kt;i++){let s=await this.graph(r,{method:"GET"},e);for(let n of s.data??[]){let o=n.instagram_business_account;if(o?.id&&n.access_token)yield{pageId:n.id,pageName:n.name,igUserId:o.id,username:o.username,pageAccessToken:n.access_token}}r=s.paging?.next}}async exchangeLongLivedUserToken(e,t,r){let i=await this.graph("/oauth/access_token",{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"fb_exchange_token",client_id:e,client_secret:t,fb_exchange_token:r}).toString()});if(!i.access_token)throw new k("Facebook did not return a long-lived token.",400,JSON.stringify(i));return{accessToken:i.access_token,expiresIn:i.expires_in}}async publish(e,t){if(!e.accessToken)throw Error("Instagram access token is missing for this identity.");let r=e.did;if(!r)throw Error("Instagram account id is required to publish.");let i=(t.media??[]).slice(0,this.maxImages);if(!i.length)throw Error("Instagram requires an image to post.");if(i.some((l)=>!l.url))throw new k("Instagram fetches images from a public address, and this image has none.",422,"");if(i.some((l)=>l.mimeType&&!/^image\/jpe?g$/i.test(l.mimeType)))throw new k("Instagram only publishes JPEG images, and this image is not one.",422,"");if(S("instagram",t.text,this.characterLimit))throw Error(`Instagram captions must be ${this.characterLimit} characters or fewer.`);let s=e.accessToken,n=async(l)=>{let u=await this.graph(`/${r}/media`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams(l).toString()},s);if(!u.id)throw new k("Instagram did not return a media container id.",400,JSON.stringify(u));return u.id},o=(l)=>({image_url:l.url,...l.altText?.trim()?{alt_text:l.altText.trim().slice(0,yt)}:{}}),a;if(i.length>1){let l=[];for(let u of i)l.push(await n({...o(u),is_carousel_item:"true"}));a=await n({media_type:"CAROUSEL",children:l.join(","),caption:t.text})}else a=await n({...o(i[0]),caption:t.text});await this.waitForContainer(a,s);let c=await this.graph(`/${r}/media_publish`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({creation_id:a}).toString()},s);if(!c.id)throw new k("Instagram did not return a published post id.",400,JSON.stringify(c));let d=await this.graph(`/${c.id}?fields=permalink`,{method:"GET"},s).catch(()=>{return});return{provider:this.provider,uri:c.id,url:d?.permalink}}async waitForContainer(e,t){let r=0,i=1000;for(;;){let s=await this.graph(`/${e}?fields=status_code,status`,{method:"GET"},t),n=s.status_code;if(n==="FINISHED"||n==="PUBLISHED"||n===void 0)return;if(n==="ERROR"||n==="EXPIRED")throw new k(`Instagram could not prepare this post (${n}${s.status?`: ${s.status}`:""}).`,422,JSON.stringify(s));if(r>=this.containerTimeoutMs)throw new k(`Instagram was still processing this post after ${Math.round(r/1000)} seconds, so it was not published.`,504,JSON.stringify(s));let o=Math.min(i,60000,Math.max(this.containerTimeoutMs-r,0));await this.sleep(o),r+=o,i*=2}}sleep(e){return new Promise((t)=>setTimeout(t,e))}async timeline(e,t={}){return{items:[]}}async metrics(e,t){let r=e.accessToken;if(!r)throw Error("Instagram access token is missing for this identity.");let i=[];for(let s of t){let n=String(s||"").trim();if(!n)continue;let o;try{o=await this.graph(`/${encodeURIComponent(n)}/insights?metric=${Object.keys(Ce).join(",")}`,{method:"GET"},r)}catch(c){if(c instanceof k&&V(c))continue;throw c}let a={uri:s};for(let c of o.data||[]){let d=Ce[String(c.name)],l=Number(c.values?.[0]?.value);if(d&&Number.isFinite(l))a[d]=l}i.push(a)}return i}graphUrl(e){if(!/^https?:\/\//i.test(e))return`${this.graphBase}/${this.graphVersion}${e}`;let t=new URL(e);if(t.origin!==new URL(this.graphBase).origin||t.username||t.password)throw new k("Instagram returned a paging address on another host, so it was not followed.",502,"");return t.searchParams.delete("access_token"),t.href}async graph(e,t,r){let i=new Headers(t.headers);if(r)i.set("authorization",`Bearer ${r}`);let s=await fetch(this.graphUrl(e),{...t,headers:i}),n=await s.text(),o={};try{o=n?JSON.parse(n):{}}catch{o={}}if(!s.ok||o?.error)throw new k(...m("Instagram API",s,n));return o}}import{fetchPublicUrl as St}from"@stacksjs/security";var bt=10485760;function Re(e){if(e.length>=3&&e[0]===255&&e[1]===216&&e[2]===255)return"image/jpeg";if(e.length>=8&&e[0]===137&&e[1]===80&&e[2]===78&&e[3]===71)return"image/png";if(e.length>=6&&e[0]===71&&e[1]===73&&e[2]===70&&e[3]===56)return"image/gif";if(e.length>=12&&e[0]===82&&e[1]===73&&e[2]===70&&e[3]===70&&e[8]===87&&e[9]===69&&e[10]===66&&e[11]===80)return"image/webp";return null}async function T(e,t={}){try{let r=await St(e,{},{allowHttp:!0,timeoutMs:15000,maxBytes:bt,...t});if(!r.ok)return null;let i=new Uint8Array(await r.arrayBuffer()),s=Re(i);return s?{bytes:i,mimeType:s}:null}catch{return null}}class Ue extends Error{url;status=422;body="";constructor(e){super(`Could not read the image at ${e}.`);this.url=e;this.name="PostImageError"}}async function A(e,t){if(e.bytes?.length)return{bytes:e.bytes,mimeType:e.mimeType||Re(e.bytes)||"image/jpeg"};if(!e.url)return;let r=await t(e.url);if(!r)throw new Ue(e.url);return r}var $e="202611";function Pt(e){let t=Number(e.slice(0,4)),r=Number(e.slice(4,6));return new Date(Date.UTC(t+1,r-1,15))}function vt(e,t=Date.now()){let r=String(e??"").trim();if(!/^\d{6}$/.test(r))return $e;return Pt(r).getTime()>t?r:$e}var xt=20,It=4086,_t=["ADMINISTRATOR","DIRECT_SPONSORED_CONTENT_POSTER","CONTENT_ADMINISTRATOR","CONTENT_ADMIN"],C="2.0.0";class f extends y{constructor(e,t,r,i={}){super("linkedin",e,t,r,i);this.name="LinkedInApiError"}get isAuthError(){return this.status===401||this.status===403}}class ce{provider="linkedin";characterLimit=3000;maxImages=xt;fetchImage=T;organizationPageSize=100;apiVersion;authBase;apiBase;constructor(e={}){this.apiVersion=vt(e.apiVersion),this.authBase=e.authBase||"https://www.linkedin.com",this.apiBase=e.apiBase||"https://api.linkedin.com"}getAuthUrl(e){let t=new URLSearchParams({response_type:"code",client_id:e.clientId,redirect_uri:e.redirectUrl,scope:e.scopes.join(" "),state:e.state});return`${this.authBase}/oauth/v2/authorization?${t.toString()}`}async exchangeCode(e){let t=new URLSearchParams({grant_type:"authorization_code",code:e.code,redirect_uri:e.redirectUrl,client_id:e.clientId,client_secret:e.clientSecret});return this.tokenRequest(t,"LinkedIn did not return an access token.")}async refreshAccessToken(e){return this.tokenRequest(new URLSearchParams({grant_type:"refresh_token",refresh_token:e.refreshToken,client_id:e.clientId,client_secret:e.clientSecret}),"LinkedIn did not return a refreshed access token.")}async tokenRequest(e,t){let r=await this.request(`${this.authBase}/oauth/v2/accessToken`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:e.toString()});if(!r.access_token)throw new f(t,400,JSON.stringify(r));return{accessToken:r.access_token,expiresIn:r.expires_in,scope:r.scope,refreshToken:r.refresh_token,refreshTokenExpiresIn:r.refresh_token_expires_in}}async getProfile(e){if(!e)throw Error("LinkedIn access token is required.");let t=await this.request(`${this.apiBase}/v2/userinfo`,{headers:{authorization:`Bearer ${e}`}});if(!t.sub)throw new f("LinkedIn profile is missing a subject id.",400,JSON.stringify(t));return{sub:t.sub,name:t.name,picture:t.picture}}async uploadImage(e,t,r,i){let s=await this.request(`${this.apiBase}/rest/images?action=initializeUpload`,{method:"POST",headers:{authorization:`Bearer ${e}`,"content-type":"application/json","linkedin-version":this.apiVersion,"x-restli-protocol-version":C},body:JSON.stringify({initializeUploadRequest:{owner:t}})}),n=s.value?.uploadUrl,o=s.value?.image;if(!n||!o)throw new f("LinkedIn did not return an image upload URL.",400,JSON.stringify(s));let a=await fetch(n,{method:"PUT",headers:{authorization:`Bearer ${e}`,"content-type":i||"image/jpeg"},body:new Uint8Array(r)});if(!a.ok){let c=await a.text().catch(()=>"");throw new f(...m("LinkedIn image upload",a,c))}return o}async publish(e,t){if(!e.accessToken)throw Error("LinkedIn access token is missing for this identity.");let r=e.did;if(!r)throw Error("LinkedIn author URN is required to publish.");if(S("linkedin",t.text,this.characterLimit))throw Error(`LinkedIn posts must be ${this.characterLimit} characters or fewer.`);let i=[];for(let c of(t.media??[]).slice(0,this.maxImages)){let d=await A(c,(p)=>this.fetchImage(p));if(!d)continue;let l=await this.uploadImage(e.accessToken,r,d.bytes,d.mimeType),u=c.altText?.trim();i.push({id:l,...u?{altText:u.slice(0,It)}:{}})}let s={author:r,commentary:Tt(t.text),visibility:"PUBLIC",distribution:{feedDistribution:"MAIN_FEED",targetEntities:[],thirdPartyDistributionChannels:[]},lifecycleState:"PUBLISHED",isReshareDisabledByAuthor:!1};if(i.length===1)s.content={media:i[0]};else if(i.length>1)s.content={multiImage:{images:i}};else if(t.external)s.content={article:{source:t.external.uri,title:t.external.title,description:t.external.description||""}};let n=await fetch(`${this.apiBase}/rest/posts`,{method:"POST",headers:{authorization:`Bearer ${e.accessToken}`,"content-type":"application/json","linkedin-version":this.apiVersion,"x-restli-protocol-version":C},body:JSON.stringify(s)}),o=await n.text();if(!n.ok)throw new f(...m("LinkedIn API",n,o));let a=n.headers.get("x-restli-id")||n.headers.get("x-linkedin-id")||"";return{provider:this.provider,uri:a,url:a?`https://www.linkedin.com/feed/update/${a}`:void 0}}async timeline(e,t={}){return{items:[]}}async listAuthoredPosts(e,t={}){if(!e.accessToken)throw Error("LinkedIn access token is missing for this identity.");let r=e.did;if(!r)throw Error("LinkedIn author URN is required to list posts.");let i=r.startsWith("urn:li:organization:")?"r_organization_social":"r_member_social",s=Math.min(Math.max(t.limit||50,1),100),n=Number(t.cursor||0)||0,o=new URL(`${this.apiBase}/rest/posts`);o.searchParams.set("q","author"),o.searchParams.set("author",r),o.searchParams.set("count",String(s)),o.searchParams.set("start",String(n));let a;try{a=await this.request(o.toString(),{headers:{authorization:`Bearer ${e.accessToken}`,"linkedin-version":this.apiVersion,"x-restli-protocol-version":C}})}catch(d){if(d instanceof f&&(d.status===401||d.status===403))throw new f(`LinkedIn will not list this account's posts - the Posts author finder needs the ${i} permission, which this app does not hold.`,d.status,d.body);throw d}let c=(a.elements||[]).filter((d)=>d?.id).map((d)=>({uri:String(d.id),text:d.commentary,postedAt:d.createdAt?new Date(d.createdAt).toISOString():void 0,url:`https://www.linkedin.com/feed/update/${d.id}`}));return{cursor:c.length===s?String(n+s):void 0,posts:c}}async metrics(e,t){if(!e.accessToken)throw Error("LinkedIn access token is missing for this identity.");let r=String(e.did||"").startsWith("urn:li:organization:")?"r_organization_social_feed":"r_member_social_feed",i=[...new Set(t.map((n)=>String(n||"").trim()).filter(Boolean))],s=[];for(let n=0;n<i.length;n+=20){let o=i.slice(n,n+20),a=`${this.apiBase}/rest/socialMetadata?ids=List(${o.map((l)=>encodeURIComponent(l)).join(",")})`,c;try{c=await this.request(a,{headers:{authorization:`Bearer ${e.accessToken}`,"linkedin-version":this.apiVersion,"x-restli-protocol-version":C}})}catch(l){if(l instanceof f&&l.status===403)throw new f(`LinkedIn will not show this account's reactions and comments - that needs the ${r} permission, which this app does not hold.`,l.status,l.body,l.retryAfterMs===void 0?{}:{retryAfterMs:l.retryAfterMs});throw l}let d=c.results||{};for(let l of o){let u=d[l]??d[encodeURIComponent(l)];if(!u)continue;let p=Object.values(u.reactionSummaries||{}).reduce((g,v)=>g+(Number(v?.count)||0),0);s.push({uri:l,likes:p,...typeof u.commentSummary?.count==="number"?{replies:u.commentSummary.count}:{}})}}return s}async listOrganizations(e){if(!e)throw Error("LinkedIn access token is required to list organizations.");let t={authorization:`Bearer ${e}`,"linkedin-version":this.apiVersion,"x-restli-protocol-version":C},r=new Map,i=Math.max(1,this.organizationPageSize);for(let n=0,o=0;o<50;n+=i,o++){let a=new URL(`${this.apiBase}/rest/organizationAcls`);a.searchParams.set("q","roleAssignee"),a.searchParams.set("state","APPROVED"),a.searchParams.set("start",String(n)),a.searchParams.set("count",String(i));let c;try{c=await this.request(a.toString(),{headers:t})}catch(u){if(u instanceof f&&(u.status===401||u.status===403))throw new f("LinkedIn will not list this member's Pages - that needs the rw_organization_admin (or r_organization_admin) permission, which this token does not hold.",u.status,u.body);throw u}let d=c.elements||[];for(let u of d){let p=u.organizationTarget||u.organization,g=u.role||"";if(!p?.startsWith("urn:li:organization:")||!_t.includes(g)||r.has(p))continue;r.set(p,{urn:p,id:p.slice(20),role:g})}let l=c.paging?.total;if(d.length<i||typeof l==="number"&&n+i>=l)break}let s=[...r.values()];for(let n of s){let o=await this.request(`${this.apiBase}/rest/organizations/${encodeURIComponent(n.id)}`,{headers:t}).then((a)=>a.localizedName,()=>{return});if(o)n.name=o}return s}async deletePost(e,t){if(!e.accessToken)throw Error("LinkedIn access token is missing for this identity.");let r=String(t.uri||"").trim();if(!r)throw Error("A LinkedIn post URN is required to delete a post.");let i=await fetch(`${this.apiBase}/rest/posts/${encodeURIComponent(r)}`,{method:"DELETE",headers:{authorization:`Bearer ${e.accessToken}`,"linkedin-version":this.apiVersion,"x-restli-protocol-version":C}});if(!i.ok&&i.status!==404){let s=await i.text().catch(()=>"");throw new f(...m("LinkedIn API",i,s))}}async request(e,t){let r=await fetch(e,t),i=await r.text();if(!r.ok)throw new f(...m("LinkedIn API",r,i));return i?JSON.parse(i):{}}}function Tt(e){return e.replace(/[\\|{}@[\]()<>#*_~]/g,(t,r)=>{if(t==="#"&&At(e,r))return t;return`\\${t}`})}function At(e,t){let r=t===0?"":e[t-1];if(r&&/[\p{L}\p{N}_#&/]/u.test(r))return!1;let i=/^[\p{L}\p{N}_]+/u.exec(e.slice(t+1))?.[0];return Boolean(i&&/\p{L}/u.test(i))}function Ee(e){return e instanceof le&&e.status===404}class le extends y{constructor(e,t,r,i={}){super("mastodon",e,t,r,i);this.name="MastodonApiError"}get isAuthError(){return this.status===401||this.status===403}}var R={characters:500,charactersPerUrl:23,mediaAttachments:4},Ct=3600000,Rt=60000;function Ut(e){let t=String(e||"").trim().replace(/\/+$/,"");if(!t)throw Error("Mastodon instance URL is required.");let r=/^https?:\/\//i.test(t)?t:`https://${t}`;try{let i=new URL(r);return`${i.protocol}//${i.host}`}catch{throw Error("Mastodon instance URL is invalid.")}}class de{provider="mastodon";characterLimit=R.characters;fetchImage=T;limits=new Map;async instanceLimits(e){let t=this.instanceOf(e),r=this.limits.get(t);if(r&&Date.now()<r.expires)return r.value;try{let i=await fetch(`${t}/api/v2/instance`,{signal:AbortSignal.timeout(5000)});if(!i.ok)throw Error(`HTTP ${i.status}`);let n=(await i.json()).configuration?.statuses??{},o=(c,d)=>Number(c)>0?Math.floor(Number(c)):d,a={characters:o(n.max_characters,R.characters),charactersPerUrl:o(n.characters_reserved_per_url,R.charactersPerUrl),mediaAttachments:o(n.max_media_attachments,R.mediaAttachments)};return this.limits.set(t,{value:a,expires:Date.now()+Ct}),a}catch{return this.limits.set(t,{value:R,expires:Date.now()+Rt}),R}}instanceOf(e){return Ut(e.did||"")}tokenOf(e){if(!e.accessToken)throw Error("Mastodon access token is missing for this identity.");return e.accessToken}async verifyCredentials(e){let t=await this.request(`${this.instanceOf(e)}/api/v1/accounts/verify_credentials`,{headers:{authorization:`Bearer ${this.tokenOf(e)}`}});return{accountId:t.id,username:t.username,displayName:t.display_name||void 0,url:t.url}}async uploadMedia(e,t,r,i){let s=new FormData;if(s.set("file",new Blob([new Uint8Array(t)],{type:r||"image/jpeg"}),"upload"),i?.trim())s.set("description",i.trim().slice(0,1500));return(await this.request(`${this.instanceOf(e)}/api/v2/media`,{method:"POST",headers:{authorization:`Bearer ${this.tokenOf(e)}`},body:s})).id}async publish(e,t,r={}){let i=this.instanceOf(e),s=this.tokenOf(e),n=await this.instanceLimits(e);if(S("mastodon",t.text,n.characters,{linkLength:n.charactersPerUrl}))throw Error(`Mastodon posts on this instance must be ${n.characters} characters or fewer.`);let o=[];for(let u of(t.media||[]).slice(0,n.mediaAttachments)){let p=await A(u,(g)=>this.fetchImage(g));if(p)o.push(await this.uploadMedia(e,p.bytes,p.mimeType,u.altText))}let a={status:t.text,visibility:r.visibility??"public"};if(o.length)a.media_ids=o;if(t.reply?.parent?.uri)a.in_reply_to_id=t.reply.parent.uri;if(r.spoilerText?.trim())a.spoiler_text=r.spoilerText.trim();let c=r.language??t.langs?.[0];if(c)a.language=c;let d={authorization:`Bearer ${s}`,"content-type":"application/json"};if(r.idempotencyKey)d["idempotency-key"]=r.idempotencyKey;let l=await this.request(`${i}/api/v1/statuses`,{method:"POST",headers:d,body:JSON.stringify(a)});return{provider:this.provider,uri:l.id,cid:l.id,url:l.url||l.uri}}async timeline(e,t={}){return{items:[]}}async listAuthoredPosts(e,t={}){let r=this.instanceOf(e),{accountId:i}=await this.verifyCredentials(e),s=new URL(`${r}/api/v1/accounts/${encodeURIComponent(i)}/statuses`);if(s.searchParams.set("limit",String(Math.min(Math.max(t.limit||40,1),40))),s.searchParams.set("exclude_reblogs","true"),t.cursor)s.searchParams.set("max_id",t.cursor);let o=(await this.request(s.toString(),{headers:{authorization:`Bearer ${this.tokenOf(e)}`}})||[]).filter((a)=>a?.id).map((a)=>({uri:a.id,cid:a.id,text:a.content,postedAt:a.created_at,url:a.url}));return{cursor:o.length?o[o.length-1]?.uri:void 0,posts:o}}async deletePost(e,t){let r=String(t.cid||Oe(t.uri)||"").trim();if(!r)throw Error("A status id is required to delete a post.");await this.request(`${this.instanceOf(e)}/api/v1/statuses/${encodeURIComponent(r)}`,{method:"DELETE",headers:{authorization:`Bearer ${this.tokenOf(e)}`}})}async metrics(e,t){let r=this.instanceOf(e),i={authorization:`Bearer ${this.tokenOf(e)}`},s=new Map;for(let a of t){let c=String(Oe(a)||"").trim();if(c)s.set(c,a)}let n=[...s.keys()],o=[];for(let a=0;a<n.length;a+=40){let c=n.slice(a,a+40);try{o.push(...await this.request(`${r}/api/v1/statuses?${c.map((d)=>`id[]=${encodeURIComponent(d)}`).join("&")}`,{headers:i}))}catch(d){if(!Ee(d))throw d;for(let l of c)try{o.push(await this.request(`${r}/api/v1/statuses/${encodeURIComponent(l)}`,{headers:i}))}catch(u){if(!Ee(u))throw u}}}return o.flatMap((a)=>{let c=s.get(String(a.id));if(c===void 0)return[];return[{uri:c,likes:a.favourites_count??0,reposts:a.reblogs_count??0,replies:a.replies_count??0,...typeof a.quotes_count==="number"?{quotes:a.quotes_count}:{}}]})}async request(e,t){let r=await fetch(e,t),i=await r.text();if(!r.ok)throw new le(...m("Mastodon API",r,i));return i?JSON.parse(i):{}}}function Oe(e){return String(e||"").replace(/\/+$/,"").split("/").pop()||""}var $t=20,Et=1000,Le={views:"views",likes:"likes",replies:"replies",reposts:"reposts",quotes:"quotes",shares:"shares"},Ot=Object.keys(Le);class P extends y{constructor(e,t,r,i={}){super("threads",e,t,r,i);this.name="ThreadsApiError"}get isAuthError(){return this.status===401||this.status===403||this.status===190}}class ue{provider="threads";characterLimit=500;maxImages=$t;graphVersion;authBase;graphBase;constructor(e={}){this.graphVersion=e.graphVersion||"v1.0",this.authBase=e.authBase||"https://threads.net",this.graphBase=e.graphBase||"https://graph.threads.net"}getAuthUrl(e){let t=new URLSearchParams({client_id:e.clientId,redirect_uri:e.redirectUrl,scope:e.scopes.join(","),response_type:"code",state:e.state});return`${this.authBase}/oauth/authorize?${t.toString()}`}async exchangeCode(e){let t=await fetch(`${this.graphBase}/oauth/access_token`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:e.clientId,client_secret:e.clientSecret,grant_type:"authorization_code",redirect_uri:e.redirectUrl,code:e.code}).toString()}),r=await t.text(),i={};try{i=r?JSON.parse(r):{}}catch{i={}}if(!t.ok||i?.error||!i?.access_token)throw new P(...m("Threads token exchange",t,r));return{accessToken:i.access_token,userId:i.user_id!=null?String(i.user_id):void 0,expiresIn:i.expires_in}}async resolveAccount(e){let t=new URLSearchParams({fields:"id,username"}),r=await this.graph(`/me?${t.toString()}`,{method:"GET"},e);if(!r.id)throw new P("Could not resolve the Threads account for this token.",400,JSON.stringify(r));return{threadsUserId:r.id,username:r.username,accessToken:e}}async exchangeLongLivedToken(e,t){return this.tokenRequest("/access_token",new URLSearchParams({grant_type:"th_exchange_token",client_secret:e,access_token:t}))}async refreshLongLivedToken(e){return this.tokenRequest("/refresh_access_token",new URLSearchParams({grant_type:"th_refresh_token",access_token:e}))}async publish(e,t){if(!e.accessToken)throw Error("Threads access token is missing for this identity.");let r=e.did;if(!r)throw Error("Threads account id is required to publish.");if(S("threads",t.text,this.characterLimit))throw Error(`Threads posts must be ${this.characterLimit} characters or fewer.`);let i=(t.media??[]).slice(0,this.maxImages);if(i.some((p)=>!p.url))throw new P("Threads fetches images from a public address, and this image has none.",422,"");let s=e.accessToken,n=async(p)=>{let g=await this.graph(`/${r}/threads`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams(p).toString()},s);if(!g.id)throw new P("Threads did not return a media container id.",400,JSON.stringify(g));return g.id},o=t.reply?.parent?.uri,a={text:t.text,...o?{reply_to_id:o}:{}},c=(p)=>({media_type:"IMAGE",image_url:p.url,...p.altText?.trim()?{alt_text:p.altText.trim().slice(0,Et)}:{}}),d;if(i.length>1){let p=[];for(let g of i)p.push(await n({...c(g),is_carousel_item:"true"}));d=await n({media_type:"CAROUSEL",children:p.join(","),...a})}else if(i.length===1)d=await n({...c(i[0]),...a});else d=await n({media_type:"TEXT",...a});let l=await this.graph(`/${r}/threads_publish`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({creation_id:d}).toString()},s);if(!l.id)throw new P("Threads did not return a published post id.",400,JSON.stringify(l));let u=await this.graph(`/${l.id}?fields=permalink`,{method:"GET"},s).catch(()=>{return});return{provider:this.provider,uri:l.id,cid:l.id,url:u?.permalink}}async deletePost(e,t){if(!e.accessToken)throw Error("Threads access token is missing for this identity.");if(!/^\w+$/.test(t.uri))throw Error(`Threads post id "${t.uri}" is not an id.`);await this.graph(`/${t.uri}`,{method:"DELETE"},e.accessToken)}async timeline(e,t={}){return{items:[]}}async tokenRequest(e,t){let r=await fetch(`${this.graphBase}${e}`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:t.toString()}),i=await r.text(),s={};try{s=i?JSON.parse(i):{}}catch{s={}}if(!r.ok||s?.error||!s?.access_token)throw new P(...m("Threads token request",r,i));return{accessToken:s.access_token,expiresIn:s.expires_in}}async metrics(e,t){let r=e.accessToken;if(!r)throw Error("Threads access token is missing for this identity.");let i=[];for(let s of t){let n=String(s||"").trim();if(!n)continue;let o;try{o=await this.graph(`/${encodeURIComponent(n)}/insights?metric=${Ot.join(",")}`,{method:"GET"},r)}catch(c){if(c instanceof P&&V(c))continue;throw c}let a={uri:s};for(let c of o.data||[]){let d=Le[String(c.name)],l=Number(c.values?.[0]?.value);if(d&&Number.isFinite(l))a[d]=l}i.push(a)}return i}async graph(e,t,r){let i=new Headers(t.headers);if(r)i.set("authorization",`Bearer ${r}`);let s=await fetch(`${this.graphBase}/${this.graphVersion}${e}`,{...t,headers:i}),n=await s.text(),o={};try{o=n?JSON.parse(n):{}}catch{o={}}if(!s.ok||o?.error)throw new P(...m("Threads API",s,n));return o}}import{Buffer as Lt}from"buffer";import{fetcher as De}from"@stacksjs/api";import{config as K}from"@stacksjs/config";class pe extends w{baseUrl="https://twitter.com";apiUrl="https://api.twitter.com";_usesPKCE=!0;getConfig(){let e={clientId:this.clientId||(K.services.twitter?.clientId??""),clientSecret:this.clientSecret||(K.services.twitter?.clientSecret??""),redirectUrl:this.redirectUrl||(K.services.twitter?.redirectUrl??""),scopes:K.services.twitter?.scopes??["users.read","tweet.read"]};return this.setScopes(e.scopes),e}async getAuthUrl(){let e=this.resolveState(),{clientId:t,redirectUrl:r,scopes:i}=this.getConfig();return this.validateConfig(),`${this.baseUrl}/i/oauth2/authorize?${new URLSearchParams({client_id:t,redirect_uri:r,scope:i.join(" "),response_type:"code",...this.parameters,...await this.pkceFields(),state:e}).toString()}`}async getAccessToken(e){let{clientId:t,clientSecret:r,redirectUrl:i}=this.getConfig();this.validateConfig();let s=this.pkceTokenFields(),n=Lt.from(`${t}:${r}`).toString("base64"),o=await De.asForm().withHeaders({Authorization:`Basic ${n}`}).post(`${this.apiUrl}/2/oauth2/token`,{code:e,grant_type:"authorization_code",redirect_uri:i,...s});if(o.data.error)throw Error(`Twitter OAuth error: ${o.data.error_description}`);return o.data.access_token}async getUserByToken(e){let t=await De.withHeaders({Authorization:`Bearer ${e}`}).get(`${this.apiUrl}/2/users/me?user.fields=profile_image_url`);return{id:t.data.id,nickname:t.data.username,name:t.data.name,email:t.data.email??null,avatar:t.data.profile_image_url??null,token:e,raw:t.data}}validateConfig(){let{clientId:e,clientSecret:t,redirectUrl:r}=this.getConfig();if(!e)throw new h("Twitter client ID not provided");if(!t)throw new h("Twitter client secret not provided");if(!r)throw new h("Twitter redirect URL not provided")}getTokenUrl(){return`${this.apiUrl}/2/oauth2/token`}}class I extends y{constructor(e,t,r,i={}){super("twitter",e,t,r,i);this.name="TwitterApiError"}get isAuthError(){return this.status===401||this.status===403}}var Dt=4,Bt=1000;function Be(e){let t="";for(let r of e)t+=String.fromCharCode(r);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}class U{provider="twitter";characterLimit=280;maxImages=Dt;fetchImage=T;apiBase;authorizeBase;constructor(e={}){this.apiBase=e.apiBase||"https://api.twitter.com",this.authorizeBase=e.authorizeBase||"https://twitter.com"}async createAuthorization(e){let t=Be(crypto.getRandomValues(new Uint8Array(32))),r=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t)),i=Be(new Uint8Array(r)),s=new URLSearchParams({response_type:"code",client_id:e.clientId,redirect_uri:e.redirectUrl,scope:e.scopes.join(" "),state:e.state,code_challenge:i,code_challenge_method:"S256"});return{url:`${this.authorizeBase}/i/oauth2/authorize?${s.toString()}`,codeVerifier:t}}async exchangeCode(e){return this.tokenRequest(new URLSearchParams({grant_type:"authorization_code",code:e.code,redirect_uri:e.redirectUrl,code_verifier:e.codeVerifier,client_id:e.clientId}),e.clientId,e.clientSecret)}async refreshAccessToken(e){return this.tokenRequest(new URLSearchParams({grant_type:"refresh_token",refresh_token:e.refreshToken,client_id:e.clientId}),e.clientId,e.clientSecret)}async getProfile(e){let t=await this.request(`${this.apiBase}/2/users/me?user.fields=username,name`,{headers:{authorization:`Bearer ${e}`}});if(!t.data?.id||!t.data.username)throw new I("Twitter did not return the authenticated user.",400,JSON.stringify(t));return{id:t.data.id,username:t.data.username,name:t.data.name}}async uploadMedia(e,t,r){let i=new FormData;i.set("media",new Blob([new Uint8Array(t)],{type:r||"image/jpeg"})),i.set("media_category","tweet_image");let s=await this.request(`${this.apiBase}/2/media/upload`,{method:"POST",headers:{authorization:`Bearer ${e}`},body:i}),n=s.data?.id||s.media_id_string||s.id;if(!n)throw new I("Twitter did not return a media id.",400,JSON.stringify(s));return n}async describeMedia(e,t,r){try{return await this.request(`${this.apiBase}/2/media/metadata`,{method:"POST",headers:{authorization:`Bearer ${e}`,"content-type":"application/json"},body:JSON.stringify({id:t,metadata:{alt_text:{text:r.slice(0,Bt)}}})}),!0}catch{return!1}}async publish(e,t){if(!e.accessToken)throw Error("Twitter access token is missing for this identity.");if(S("twitter",t.text,this.characterLimit))throw Error(`Twitter posts must be ${this.characterLimit} characters or fewer.`);let r=[],i=[];for(let a of(t.media??[]).slice(0,this.maxImages)){let c=await A(a,(u)=>this.fetchImage(u));if(!c)continue;let d=await this.uploadMedia(e.accessToken,c.bytes,c.mimeType),l=a.altText?.trim();if(l&&!await this.describeMedia(e.accessToken,d,l))i.push(`X did not take the description for image ${r.length+1}.`);r.push(d)}let s={text:t.text};if(r.length)s.media={media_ids:r};if(t.reply?.parent?.uri)s.reply={in_reply_to_tweet_id:t.reply.parent.uri};let n=await this.request(`${this.apiBase}/2/tweets`,{method:"POST",headers:{authorization:`Bearer ${e.accessToken}`,"content-type":"application/json"},body:JSON.stringify(s)}),o=n.data?.id;if(!o)throw new I("Twitter did not return a tweet id.",400,JSON.stringify(n));return{provider:this.provider,uri:o,cid:o,url:e.handle?`https://x.com/${e.handle}/status/${o}`:`https://x.com/i/web/status/${o}`,...i.length?{warnings:i}:{}}}async timeline(e,t={}){return{items:[]}}async listAuthoredPosts(e,t={}){if(!e.accessToken)throw Error("Twitter access token is missing for this identity.");let r=e.did;if(!r)throw Error("Twitter user id is required to list posts.");let i=new URL(`${this.apiBase}/2/users/${encodeURIComponent(r)}/tweets`);if(i.searchParams.set("max_results",String(Math.min(Math.max(t.limit||100,5),100))),i.searchParams.set("tweet.fields","created_at"),t.cursor)i.searchParams.set("pagination_token",t.cursor);let s=await this.request(i.toString(),{headers:{authorization:`Bearer ${e.accessToken}`}});return{cursor:s.meta?.next_token,posts:(s.data||[]).filter((n)=>n?.id).map((n)=>({uri:n.id,cid:n.id,text:n.text,postedAt:n.created_at,url:`https://x.com/i/web/status/${n.id}`}))}}async metrics(e,t){let r=[...new Set(t.filter((n)=>/^[0-9]{1,19}$/.test(n)))];if(!r.length)return[];if(!e.accessToken)throw Error("Twitter access token is missing for this identity.");let i=[],s={authorization:`Bearer ${e.accessToken}`};for(let n=0;n<r.length;n+=100){let o=r.slice(n,n+100),a=new URLSearchParams({ids:o.join(","),"tweet.fields":"public_metrics"}),c=await this.request(`${this.apiBase}/2/tweets?${a}`,{headers:s}),d=new Set(o);for(let l of c.data??[]){let u=l.public_metrics;if(!u||!d.delete(l.id))continue;let p={likes:u.like_count,replies:u.reply_count,reposts:u.repost_count??u.retweet_count,quotes:u.quote_count,views:u.impression_count,saves:u.bookmark_count},g=Object.entries(p).filter(([,v])=>typeof v==="number"&&Number.isSafeInteger(v)&&v>=0);if(g.length)i.push({uri:l.id,...Object.fromEntries(g)})}}return i}async deletePost(e,t){if(!e.accessToken)throw Error("Twitter access token is missing for this identity.");let r=String(t.uri||"").trim();if(!r)throw Error("A tweet id is required to delete a post.");let i=await this.request(`${this.apiBase}/2/tweets/${encodeURIComponent(r)}`,{method:"DELETE",headers:{authorization:`Bearer ${e.accessToken}`}});if(i.data&&i.data.deleted===!1)throw new I(`X refused to delete tweet ${r}.`,400,JSON.stringify(i))}async tokenRequest(e,t,r){let i={"content-type":"application/x-www-form-urlencoded"};if(r)i.authorization=`Basic ${btoa(`${t}:${r}`)}`;let s=await this.request(`${this.apiBase}/2/oauth2/token`,{method:"POST",headers:i,body:e.toString()});if(!s.access_token)throw new I("Twitter did not return an access token.",400,JSON.stringify(s));return{accessToken:s.access_token,refreshToken:s.refresh_token,expiresIn:s.expires_in,scope:s.scope}}async request(e,t){let r=await fetch(e,t),i=await r.text();if(!r.ok)throw new I(...m("Twitter API",r,i));return i?JSON.parse(i):{}}}import{Buffer as Mt}from"buffer";class D extends Error{code;status;constructor(e,t){super(`Stacks issuer refused the request: ${e}`);this.code=e;this.status=t;this.name="StacksIssuerError"}}class Nt extends w{scopeSeparator=" ";settings;constructor(e){super(e);this.settings=e,this._scopes=e.scopes?.length?[...e.scopes]:[],this._usesPKCE=!0}endpoint(e){return(e==="authorize"?this.settings.authorizeUrl:e==="token"?this.settings.tokenUrl:this.settings.revokeUrl)||`${this.settings.issuer.replace(/\/+$/,"")}/${e}`}resources(){let e=this.settings.resource;return e==null?[]:Array.isArray(e)?e:[e]}validateConfig(){if(!this.settings.issuer)throw new h("Stacks issuer not provided");if(!this.clientId)throw new h("Stacks issuer client ID not provided");if(!this.clientSecret)throw new h("Stacks issuer client secret not provided");if(!this.redirectUrl)throw new h("Stacks issuer redirect URL not provided");if(!this.settings.userInfoUrl)throw new h("Stacks issuer userinfo URL not provided")}getTokenUrl(){return this.endpoint("token")}async getAuthUrl(){this.validateConfig();let e=new URLSearchParams({client_id:this.clientId,redirect_uri:this.redirectUrl,response_type:"code",scope:this.formatScopes(this.getScopes(),this.scopeSeparator),state:this.resolveState(),...await this.pkceFields()});for(let t of this.resources())e.append("resource",t);for(let[t,r]of Object.entries(this.parameters))e.set(t,String(r));return`${this.endpoint("authorize")}?${e.toString()}`}async post(e,t){let r=await fetch(e,{method:"POST",headers:{Authorization:`Basic ${Mt.from(`${encodeURIComponent(this.clientId)}:${encodeURIComponent(this.clientSecret)}`).toString("base64")}`,"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:t.toString()}),i=await r.json().catch(()=>({}));if(!r.ok)throw new D(typeof i.error==="string"?i.error:"server_error",r.status);return i}tokens(e){if(typeof e.access_token!=="string"||!e.access_token)throw new D("invalid_token_response",502);return{accessToken:e.access_token,refreshToken:typeof e.refresh_token==="string"?e.refresh_token:null,expiresIn:typeof e.expires_in==="number"?e.expires_in:null,scopes:typeof e.scope==="string"?e.scope.split(" ").filter(Boolean):[]}}async getTokens(e){this.validateConfig();let t=new URLSearchParams({grant_type:"authorization_code",code:e,redirect_uri:this.redirectUrl,...this.pkceTokenFields()});for(let r of this.resources())t.append("resource",r);return this.tokens(await this.post(this.endpoint("token"),t))}async getAccessToken(e){return(await this.getTokens(e)).accessToken}async refreshTokens(e){this.validateConfig();let t=new URLSearchParams({grant_type:"refresh_token",refresh_token:e});for(let r of this.resources())t.append("resource",r);return this.tokens(await this.post(this.endpoint("token"),t))}async revokeToken(e,t="refresh_token"){this.validateConfig(),await this.post(this.endpoint("revoke"),new URLSearchParams({token:e,token_type_hint:t}))}async getClaims(e){this.validateConfig();let t=await fetch(this.settings.userInfoUrl,{headers:{Authorization:`Bearer ${e}`,Accept:"application/json"}}),r=await t.json().catch(()=>({}));if(!t.ok)throw new D(typeof r.error==="string"?r.error:"invalid_token",t.status);if(typeof r.sub!=="string"||!r.sub)throw new D("invalid_userinfo",502);return r}async getUserByToken(e){let t=await this.getClaims(e),r=typeof t.email==="string"?t.email:null;return{id:String(t.sub),nickname:typeof t.preferred_username==="string"?t.preferred_username:null,name:typeof t.name==="string"&&t.name?t.name:r??"",email:r,emailVerified:typeof t.email_verified==="boolean"?t.email_verified:null,avatar:typeof t.picture==="string"?t.picture:null,token:e,raw:t}}}import{config as Ft}from"@stacksjs/config";var X=["clientId","clientSecret","redirectUrl"],B=Object.freeze({google:{name:"google",label:"Google",driver:oe,required:X,postCallback:!1,pkce:!1,nonce:!1},github:{name:"github",label:"GitHub",driver:ne,required:X,postCallback:!1,pkce:!1,nonce:!1},facebook:{name:"facebook",label:"Facebook",driver:ie,required:X,postCallback:!1,pkce:!1,nonce:!1},twitter:{name:"twitter",label:"X",driver:pe,required:X,postCallback:!1,pkce:!0,nonce:!1},apple:{name:"apple",label:"Apple",driver:te,required:["clientId","teamId","keyId","privateKey","redirectUrl"],postCallback:!0,pkce:!1,nonce:!0}});function Me(e){return Ft?.services?.[e]}function zt(e){return typeof e==="string"&&e in B}function Ne(e){if(!zt(e))return!1;let t=Me(e);if(!t)return!1;return B[e].required.every((r)=>Boolean(t[r]))}function Mi(){return Object.keys(B).filter(Ne).map((e)=>B[e])}function Ni(e){if(!Ne(e))return null;let t=B[e],r=Me(e)??{};return new t.driver({clientSecret:"",...r,clientId:String(r.clientId??""),redirectUrl:String(r.redirectUrl??"")})}class qt{accessToken;refreshToken;expiresIn;approvedScopes;constructor(e,t=null,r=null,i=[]){this.accessToken=e;this.refreshToken=t;this.expiresIn=r;this.approvedScopes=i}}function qi(e){return typeof e?.metrics==="function"}function Hi(e){return typeof e?.deletePost==="function"}function ji(e){return typeof e?.listAuthoredPosts==="function"}import{buildSessionHandoffCodeUrl as Ht,buildSessionHandoffUrl as jt}from"@stacksjs/composables";function he(e,t=[]){if(!e)return!1;if(e.startsWith("//"))return!1;if(e.startsWith("/"))return!0;try{let r=new URL(e);if(r.protocol!=="http:"&&r.protocol!=="https:")return!1;return t.includes(r.host)}catch{return!1}}function Ji(e,t={}){let r=t.redirectTo??"/";if(!he(r,t.allowedHosts??[]))throw Error(`[socials] refusing to hand a session to ${r}: relative paths are always allowed; an absolute URL needs its host in allowedHosts.`);return new Response(null,{status:302,headers:{Location:jt(r,e),"Cache-Control":"no-store","Referrer-Policy":"no-referrer"}})}function Ki(e,t={}){let r=t.redirectTo??"/";if(!he(r,t.allowedHosts??[]))throw Error(`[socials] refusing to hand a session to ${r}: relative paths are always allowed; an absolute URL needs its host in allowedHosts.`);return new Response(null,{status:302,headers:{Location:Ht(r,e),"Cache-Control":"no-store","Referrer-Policy":"no-referrer"}})}function Xi(e,t={}){let r=t.redirectTo??"/login";if(!he(r,t.allowedHosts??[]))throw Error(`[socials] refusing to redirect to ${r}`);let i=r.includes("?")?"&":"?",s=`${r}${i}social_error=${encodeURIComponent(e)}`;return new Response(null,{status:302,headers:{Location:s,"Cache-Control":"no-store","Referrer-Policy":"no-referrer"}})}import{Buffer as Fe}from"buffer";import{createHash as Vt,randomBytes as Gt,timingSafeEqual as Jt}from"crypto";function M(e){return Vt("sha256").update(e).digest("hex")}var Kt=/^[a-f0-9]{64}$/,Xt=/^[a-f0-9]{64}$/,Qt=/^[\w.:-]{1,64}$/,Wt=3600000,ze=null;function Zi(e){ze=e}function qe(){return ze??er()}function ge(e=32){return Gt(e).toString("hex")}function Yt(e,t){if(e.length!==t.length)return!1;return Jt(Fe.from(e,"utf8"),Fe.from(t,"utf8"))}function me(e){return`stacks_oauth_${M(e).slice(0,24)}`}async function Zt(){try{let{config:e}=await import("@stacksjs/config");return String(e.app?.url??"").startsWith("https:")}catch{return!1}}function He(e,t,r,i){return[`${e}=${t}`,`Path=${i.path}`,"HttpOnly",`SameSite=${i.sameSite}`,`Max-Age=${Math.max(0,Math.floor(r))}`,...i.secure?["Secure"]:[]].join("; ")}async function je(e={}){let t=e.sameSite??"Lax",r=t==="None"?!0:e.secure??await Zt();return{path:e.path??"/",sameSite:t,secure:r}}async function es(e){if(!Qt.test(e.purpose??""))throw TypeError("[socials] issueOAuthFlow needs a purpose of 1-64 word characters, dots, colons or dashes.");if(!Number.isFinite(e.ttlMs)||e.ttlMs<=0)throw TypeError("[socials] issueOAuthFlow needs a positive ttlMs.");if(e.challenge!==void 0&&!Xt.test(e.challenge))throw TypeError("[socials] issueOAuthFlow challenge must be the lowercase hex SHA-256 of the verifier.");if(e.userId!=null&&(!Number.isSafeInteger(e.userId)||e.userId<=0))throw TypeError("[socials] issueOAuthFlow userId must be a positive integer.");let t=Math.min(e.ttlMs,Wt),r=ge(),s=(e.challenge?!1:e.bindBrowser!==!1)?ge():null,n=e.nonce===!0?ge():typeof e.nonce==="string"&&e.nonce?e.nonce:void 0,o=new Date,a=new Date(o.getTime()+t),c=qe();try{await c.prune(o)}catch{}await c.insert({stateDigest:M(r),purpose:e.purpose,browserDigest:e.challenge??(s?M(s):null),userId:e.userId??null,nonce:n??null,data:e.data??null,expiresAt:a});let d=s?He(me(r),s,t/1000,await je(e.cookie)):null;return{state:r,cookie:d,secret:s,...n!==void 0&&{nonce:n},expiresAt:a}}async function ts(e,t){if(typeof e!=="string"||!Kt.test(e))return null;let r=qe(),i=M(e),s=await r.find(i);if(!s)return null;if(s.expiresAt.getTime()<=Date.now())return await r.take(i).catch(()=>!1),null;if(s.purpose!==t.purpose)return null;if(s.browserDigest!==null){let n=t.browserSecret;if(typeof n!=="string"||n.length===0||n.length>512)return null;if(!Yt(M(n),s.browserDigest))return null}if(!await r.take(i))return null;return{purpose:s.purpose,userId:s.userId,nonce:s.nonce,data:s.data,expiresAt:s.expiresAt}}function rs(e,t){if(!e||!t)return"";let r=me(t);for(let i of e.split(";")){let s=i.trim();if(s.startsWith(`${r}=`))return s.slice(r.length+1)}return""}async function is(e,t={}){return He(me(e),"",0,await je(t))}function ss(){let e=new Map;return{records:e,async insert(t){e.set(t.stateDigest,{...t})},async find(t){let r=e.get(t);return r?{...r}:void 0},async take(t){return e.delete(t)},async prune(t){for(let[r,i]of e)if(i.expiresAt.getTime()<=t.getTime())e.delete(r)}}}var Q="oauth_flows";function er(){let e=()=>import("@stacksjs/database/runtime");return{async insert(t){let{db:r,sqlDateTime:i}=await e();await r.insertInto(Q).values({state_digest:t.stateDigest,purpose:t.purpose,browser_digest:t.browserDigest,user_id:t.userId,nonce:t.nonce,data:t.data?JSON.stringify(t.data):null,expires_at:i(t.expiresAt),created_at:i(new Date)}).execute()},async find(t){let{db:r,parseSqlDateTime:i}=await e(),s=await r.primary.selectFrom(Q).where("state_digest","=",t).selectAll().executeTakeFirst();if(!s)return;let n=null;if(typeof s.data==="string"&&s.data)try{let o=JSON.parse(s.data);n=o&&typeof o==="object"?o:null}catch{n=null}return{stateDigest:String(s.state_digest),purpose:String(s.purpose),browserDigest:typeof s.browser_digest==="string"&&s.browser_digest?s.browser_digest:null,userId:s.user_id==null?null:Number(s.user_id),nonce:typeof s.nonce==="string"&&s.nonce?s.nonce:null,data:n,expiresAt:i(s.expires_at)??new Date(0)}},async take(t){let{db:r,mutationCount:i}=await e(),s=await r.deleteFrom(Q).where("state_digest","=",t).execute();return i(s)===1},async prune(t){let{db:r,sqlDateTime:i}=await e();await r.deleteFrom(Q).where("expires_at","<",i(t)).execute()}}}var tr={bluesky:["identifier","password","service"],twitter:["clientId","clientSecret","accessToken","refreshToken"],linkedin:["accessToken","memberUrn","clientId","clientSecret","apiVersion"],mastodon:["accessToken","instanceUrl"],instagram:["accessToken","accountId","clientId","clientSecret"],threads:["accessToken","userId","clientId","clientSecret"]},rr={bluesky:["identifier","password"],twitter:["clientId","clientSecret","accessToken"],linkedin:["accessToken","memberUrn"],mastodon:["accessToken","instanceUrl"],instagram:["accessToken","accountId"],threads:["accessToken","userId"]};function ir(e){return e.toUpperCase().replace(/[^A-Z0-9]/g,"")}function W(e,t,r){let i=r.replace(/[A-Z]/g,(s)=>`_${s}`).toUpperCase();return`SOCIALS_${ir(e)}_${t.toUpperCase()}_${i}`}class b extends Error{constructor(e){super(e);this.name="SocialIdentityError"}}async function Y(){let{config:e,overridesReady:t}=await import("@stacksjs/config");return await t,e.socials??{}}function Ve(e,t){let r=Object.keys(e.identities??{});if(t){if(!r.includes(t))throw new b(`Unknown social identity '${t}'. config/socials.ts declares: ${r.length?r.join(", "):"none"}.`);return t}if(e.default){if(!r.includes(e.default))throw new b(`config/socials.ts sets default: '${e.default}', which is not one of its identities: ${r.length?r.join(", "):"none"}.`);return e.default}if(r.length===1)return r[0];if(r.length===0)throw new b("config/socials.ts declares no identities, so there is no account to post as.");throw new b(`config/socials.ts declares ${r.length} identities (${r.join(", ")}) and no default, so a call has to name one.`)}function sr(e,t,r,i=process.env){let n=(e.identities?.[r]??{}).credentials?.[t]??{},o={};for(let a of tr[t]){let c=(n[a]??i[W(r,t,a)]??"").trim();if(c)o[a]=c}return o}function fe(e,t,r,i=process.env){let s=Ve(e,r),n=sr(e,t,s,i),o=rr[t].filter((a)=>!n[a]);if(o.length){let a=o.map((c)=>W(s,t,c)).join(", ");throw new b(`Identity '${s}' is not configured for ${t}: ${o.join(", ")} ${o.length===1?"is":"are"} missing. Set ${a}, or supply them inline in config/socials.ts.`)}return n}async function Ge(e){return Ve(await Y(),e)}async function E(e,t,r){return fe(await Y(),e,t,r)}function os(e,t){return E("bluesky",e,t)}function as(e,t){return E("twitter",e,t)}function cs(e,t){return E("linkedin",e,t)}function ls(e,t){return E("mastodon",e,t)}function ds(e,t){return E("instagram",e,t)}function us(e,t){return E("threads",e,t)}import{randomBytes as nr}from"crypto";function fs(e){return e==="twitter"}var or=["tweet.read","tweet.write","users.read","offline.access"],ar="127.0.0.1",Je="/callback";function ws(e){if(!Number.isInteger(e)||e<1||e>65535)throw new b(`${e} is not a port a redirect can listen on.`);return`http://${ar}:${e}${Je}`}function ys(){return nr(16).toString("hex")}function ks(e,t){let r;try{r=new URL(e)}catch{return{ok:!1,reason:"not-the-callback",message:`Not a URL: ${e}`}}if(r.pathname!==Je)return{ok:!1,reason:"not-the-callback",message:`Ignoring a request for ${r.pathname}.`};let i=r.searchParams.get("error");if(i){let o=r.searchParams.get("error_description");return{ok:!1,reason:"declined",message:o?`${i}: ${o}`:i}}let s=r.searchParams.get("state")??"";if(!t||s!==t)return{ok:!1,reason:"state-mismatch",message:"The redirect carried the wrong state, so it did not come from this run."};let n=r.searchParams.get("code")??"";if(!n)return{ok:!1,reason:"no-code",message:"The redirect carried no authorization code."};return{ok:!0,code:n}}function Ss(e,t,r){let i=[];for(let[s,n]of Object.entries(r)){if(!n)continue;i.push(`${W(e,t,s)}=${n}`)}return i}async function bs(e){let t=new U,r=await t.exchangeCode(e);if(!r.accessToken)throw new b("X returned no access token for that code.");let i=Boolean(r.refreshToken),s=await t.getProfile(r.accessToken);return{handle:s.username,accountId:s.id,accessToken:r.accessToken,refreshToken:r.refreshToken,expiresIn:r.expiresIn,scope:r.scope,renewable:i}}async function Ps(e){return new U().createAuthorization({clientId:e.clientId,redirectUrl:e.redirectUrl,scopes:[...or],state:e.state})}function vs(e,t){let r=(i)=>i.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;");return`<!doctype html><html lang="en"><head><meta charset="utf-8"><title>${r(e)}</title><style>body{font:16px/1.5 system-ui,sans-serif;margin:0;display:grid;place-items:center;min-height:100vh;color:#111}main{max-width:28rem;padding:2rem;text-align:center}h1{font-size:1.25rem;margin:0 0 .5rem}p{margin:0;color:#555}@media(prefers-color-scheme:dark){body{background:#111;color:#eee}p{color:#aaa}}</style></head><body><main><h1>${r(e)}</h1><p>${r(t)}</p></main></body></html>`}var cr={bluesky:null,twitter:null,linkedin:"memberUrn",mastodon:"instanceUrl",instagram:"accountId",threads:"userId"};function lr(e,t){if(e==="bluesky")return t.service?{service:t.service}:{};if(e==="linkedin")return t.apiVersion?{apiVersion:t.apiVersion}:{};return{}}function dr(e,t){if(e.service||!t.service)return e;return{...e,service:t.service}}function ur(e,t={}){switch(e){case"bluesky":return new H(t);case"linkedin":return new ce(t);case"twitter":return new U;case"mastodon":return new de;case"instagram":return new ae;case"threads":return new ue;default:throw new b(`No publishing driver for '${String(e)}'.`)}}function pr(e,t,r){let i=cr[e],s={handle:(t??"").trim()};if(r.accessToken)s.accessToken=r.accessToken;if(r.refreshToken)s.refreshToken=r.refreshToken;if(i&&r[i])s.did=r[i];return s}function hr(e,t,r){if(!r)return;if(r.includes(t))return;throw new b(`Identity '${e}' is not set up for ${t}. config/socials.ts lists: ${r.length?r.join(", "):"none"}.`)}async function gr(e,t,r){let i=await Y(),s=await Ge(t),n=i.identities?.[s]??{};hr(s,e,n.platforms);let o=fe(i,e,s,r),a=lr(e,o);if(e==="bluesky"){let c=await new H(a).createSession({identifier:o.identifier,password:o.password});return{name:s,platform:e,identity:{handle:c.handle,did:c.did,accessToken:c.accessJwt,refreshToken:c.refreshJwt},options:dr(a,c)}}return{name:s,platform:e,identity:pr(e,n.handle??"",o),options:a}}async function Ts(e,t,r,i){let s=await gr(e,r,i);return ur(s.platform,s.options).publish(s.identity,t)}export{ar as AUTHORIZE_HOST,Je as AUTHORIZE_PATH,w as AbstractProvider,te as AppleProvider,_e as BLUESKY_MAX_BLOB_BYTES,ut as BLUESKY_MAX_IMAGES,pt as BLUESKY_MAX_LANGS,O as BlueskyApiError,H as BlueskyPublishingDriver,h as ConfigException,cr as DRIVER_DID_FIELD,ie as FacebookProvider,ne as GitHubProvider,oe as GoogleProvider,yt as INSTAGRAM_MAX_ALT_TEXT,wt as INSTAGRAM_MAX_IMAGES,k as InstagramApiError,ae as InstagramPublishingDriver,Xe as InvalidStateException,$e as LINKEDIN_API_VERSION,It as LINKEDIN_MAX_ALT_TEXT,xt as LINKEDIN_MAX_IMAGES,_t as LINKEDIN_POSTING_ROLES,Cr as LINK_LENGTH,f as LinkedInApiError,ce as LinkedInPublishingDriver,R as MASTODON_DEFAULT_LIMITS,bt as MAX_POST_IMAGE_BYTES,j as META_GRAPH_VERSION,le as MastodonApiError,de as MastodonPublishingDriver,Ue as PostImageError,rr as REQUIRED_SOCIAL_CREDENTIALS,tr as SOCIAL_CREDENTIAL_FIELDS,B as SOCIAL_PROVIDERS,y as SocialApiError,b as SocialIdentityError,D as StacksIssuerError,Nt as StacksIssuerProvider,Et as THREADS_MAX_ALT_TEXT,$t as THREADS_MAX_IMAGES,or as TWITTER_PUBLISH_SCOPES,P as ThreadsApiError,ue as ThreadsPublishingDriver,qt as Token,I as TwitterApiError,pe as TwitterProvider,U as TwitterPublishingDriver,Bt as X_MAX_ALT_TEXT,Dt as X_MAX_IMAGES,m as apiFailure,hr as assertPlatformDeclared,Nr as blueskyRecordKey,dr as blueskyTargetOptions,vs as callbackPage,ws as callbackUri,q as classifySocialError,is as clearOAuthFlowCookie,bs as completeTwitterAuthorization,Mi as configuredSocialProviders,ts as consumeOAuthFlow,nt as countText,er as databaseOAuthFlowStore,gt as detectFacetCandidates,lr as driverOptions,Ss as envLines,W as envName,ir as envSegment,Tt as escapeLinkedInText,S as exceedsLimit,T as fetchPostImage,Pe as graphemes,fs as isAuthorizablePlatform,Mr as isBlueskySessionError,Ur as isExpiredSignIn,V as isMissingGraphObject,he as isSafeHandoffTarget,Ne as isSocialProviderConfigured,zt as isSocialProviderName,es as issueOAuthFlow,Pt as linkedInVersionSunset,ss as memoryOAuthFlowStore,z as networkReason,ys as newState,Ut as normalizeInstance,me as oauthFlowCookieName,M as oauthFlowDigest,lt as parseAtUri,fe as pickCredentials,Ve as pickIdentity,Ts as publishAs,ur as publishingDriver,ks as readCallback,sr as readCredentials,rs as readOAuthFlowCookie,os as resolveBlueskyCredentials,mt as resolveBlueskyService,Ge as resolveIdentityName,ds as resolveInstagramCredentials,cs as resolveLinkedInCredentials,vt as resolveLinkedInVersion,ls as resolveMastodonCredentials,A as resolvePostImage,E as resolveSocialCredentials,us as resolveThreadsCredentials,as as resolveTwitterCredentials,at as retryAfterMs,Re as sniffImageType,Ki as socialHandoffCodeRedirect,Xi as socialHandoffFailureRedirect,Ji as socialHandoffRedirect,Ni as socialProvider,gr as socialPublishTarget,Y as socialsConfig,Ps as startTwitterAuthorization,Hi as supportsDeletion,ji as supportsEnumeration,qi as supportsMetrics,pr as toDriverIdentity,Zi as useOAuthFlowStore};
2
+ var Ze=import.meta.require;import{Buffer as q}from"buffer";class w{clientId;clientSecret;redirectUrl;parameters={};_scopes=[];scopeSeparator=",";_stateless=!1;_usesPKCE=!1;_codeVerifier=null;_state=null;user=null;constructor(e){this.clientId=e.clientId,this.clientSecret=e.clientSecret,this.redirectUrl=e.redirectUrl}async getCodeFields(e=null){let t={client_id:this.clientId,redirect_uri:this.redirectUrl,scope:this.formatScopes(this.getScopes(),this.scopeSeparator),response_type:"code"};if(this.usesState())t.state=e;return{...t,...await this.pkceFields(),...this.parameters}}formatScopes(e,t){return e.join(t)}async userFromToken(e){return{...await this.getUserByToken(e),token:e}}scopes(e){let t=Array.isArray(e)?e:[e];return this._scopes=[...new Set([...this._scopes,...t])],this}setScopes(e){let t=Array.isArray(e)?e:[e];return this._scopes=[...new Set(t)],this}getScopes(){return this._scopes}setRedirectUrl(e){if(typeof e!=="string"||e.length===0)throw Error("[socials] setRedirectUrl requires a non-empty string");let t;try{t=new URL(e)}catch{throw Error(`[socials] setRedirectUrl: invalid URL: ${e}`)}if(t.protocol!=="https:"&&t.protocol!=="http:")throw Error(`[socials] setRedirectUrl protocol must be http(s)://, got ${t.protocol}`);return this.redirectUrl=e,this}withState(e){if(typeof e!=="string"||e.length===0)throw Error("[socials] withState requires a non-empty string");return this._state=e,this}resolveState(){return this._state??this.getState()}usesState(){return!this._stateless}validateState(e,t){if(typeof e!=="string"||typeof t!=="string")return!1;if(e.length===0||t.length===0)return!1;if(e.length!==t.length)return!1;try{let{timingSafeEqual:r}=Ze("crypto");return r(q.from(e,"utf8"),q.from(t,"utf8"))}catch{let r=0;for(let i=0;i<e.length;i++)r|=e.charCodeAt(i)^t.charCodeAt(i);return r===0}}isStateless(){return this._stateless}stateless(){return this._stateless=!0,this}getState(){let e=new Uint8Array(32);return crypto.getRandomValues(e),Array.from(e).map((t)=>t.toString(16).padStart(2,"0")).join("")}usesPKCE(){return this._usesPKCE}enablePKCE(){return this._usesPKCE=!0,this}getCodeVerifier(){if(this._codeVerifier===null){let e=new Uint8Array(32);crypto.getRandomValues(e),this._codeVerifier=q.from(e).toString("base64url")}return this._codeVerifier}getPkceVerifier(){return this._codeVerifier}withCodeVerifier(e){if(!e)throw Error("A PKCE code verifier must be a non-empty string");return this._usesPKCE=!0,this._codeVerifier=e,this}async pkceFields(){if(!this.usesPKCE())return{};return{code_challenge:await this.getCodeChallenge(),code_challenge_method:this.getCodeChallengeMethod()}}pkceTokenFields(){if(!this.usesPKCE())return{};if(this._codeVerifier===null)throw Error("PKCE is enabled but no code verifier is known for this exchange. Pass the one from getPkceVerifier() back with withCodeVerifier().");return{code_verifier:this._codeVerifier}}async getCodeChallenge(){let t=new TextEncoder().encode(this.getCodeVerifier()),r=await crypto.subtle.digest("SHA-256",t);return q.from(new Uint8Array(r)).toString("base64url")}getCodeChallengeMethod(){return"S256"}with(e){return this.parameters=e,this}async buildAuthUrlFromBase(e,t){let r=new URLSearchParams(await this.getCodeFields(t));return`${e}?${r.toString()}`}}import{Buffer as ve}from"buffer";import{createPrivateKey as st,sign as nt}from"crypto";import{config as _}from"@stacksjs/config";class et extends Error{constructor(e="Invalid state"){super(e);this.name="InvalidStateException"}}class h extends Error{constructor(e){super(e);this.name="ConfigException"}}import{Buffer as ie}from"buffer";var Pe=new Map,tt=600000,rt=60000;async function be(e,t){let r=await fetch(e);if(!r.ok)throw Error(`id_token verification failed: could not fetch signing keys from ${e} (HTTP ${r.status})`);let i=await r.json(),s=Array.isArray(i.keys)?i.keys:[];return Pe.set(e,{keys:s,fetchedAt:t}),s}async function it(e,t,r){let i=Pe.get(e),s=i!==void 0&&r-i.fetchedAt<tt,n=s?i.keys:await be(e,r),o=n.find((a)=>a.kid===t);if(!o&&s&&r-i.fetchedAt>=rt)n=await be(e,r),o=n.find((a)=>a.kid===t);if(!o)throw Error(`id_token verification failed: no signing key matches kid "${t}"`);if(o.kty!=="RSA")throw Error(`id_token verification failed: signing key "${t}" is ${o.kty}, expected RSA`);return o}function Se(e,t){try{return JSON.parse(ie.from(e,"base64url").toString("utf8"))}catch{throw Error(`id_token verification failed: ${t} is not valid JSON`)}}async function z(e,t){let r=e.split(".");if(r.length!==3)throw Error("id_token verification failed: malformed token");let[i,s,n]=r,o=Se(i,"header");if(o.alg!=="RS256")throw Error(`id_token verification failed: unsupported algorithm ${JSON.stringify(o.alg)}, expected RS256`);if(typeof o.kid!=="string"||o.kid==="")throw Error("id_token verification failed: header has no kid");let a=t.now??Date.now(),c=await it(t.jwksUrl,o.kid,a),u=await crypto.subtle.importKey("jwk",{kty:"RSA",n:c.n,e:c.e,alg:"RS256",ext:!0},{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!1,["verify"]);if(!await crypto.subtle.verify("RSASSA-PKCS1-v1_5",u,ie.from(n,"base64url"),ie.from(`${i}.${s}`)))throw Error("id_token verification failed: signature does not match the issuer's key");let l=Se(s,"payload"),p=(t.clockSkewSeconds??60)*1000,g=Array.isArray(t.issuer)?t.issuer:[t.issuer];if(!g.includes(l.iss))throw Error(`id_token verification failed: issuer is ${JSON.stringify(l.iss)}, expected ${g.map((re)=>JSON.stringify(re)).join(" or ")}`);let P=Array.isArray(t.audience)?t.audience:[t.audience];if(!(Array.isArray(l.aud)?l.aud:[l.aud]).some((re)=>P.includes(re)))throw Error("id_token verification failed: token is addressed to a different client");if(typeof l.exp!=="number"||l.exp*1000+p<=a)throw Error("id_token verification failed: token has expired");if(typeof l.iat==="number"&&l.iat*1000-p>a)throw Error("id_token verification failed: token was issued in the future");if(typeof l.nbf==="number"&&l.nbf*1000-p>a)throw Error("id_token verification failed: token is not valid yet");if(t.nonce!==void 0&&l.nonce!==t.nonce)throw Error("id_token verification failed: nonce does not match");if(typeof l.sub!=="string"||l.sub==="")throw Error("id_token verification failed: token has no subject");return l}class se extends w{baseUrl="https://appleid.apple.com";teamId="";keyId="";privateKey="";native=!1;constructor(e){super(e);this.teamId=e.teamId??"",this.keyId=e.keyId??"",this.privateKey=e.privateKey??"",this.native=e.native===!0}getConfig(){let e={clientId:this.clientId||(_.services.apple?.clientId??""),teamId:this.teamId||(_.services.apple?.teamId??""),keyId:this.keyId||(_.services.apple?.keyId??""),privateKey:(this.privateKey||(_.services.apple?.privateKey??"")).replace(/\\n/g,`
3
+ `),redirectUrl:this.native?"":this.redirectUrl||(_.services.apple?.redirectUrl??""),scopes:this._scopes.length>0?this._scopes:_.services.apple?.scopes??["name","email"]};return this.setScopes(e.scopes),e}async getAuthUrl(){if(this.native)throw new h("A native Apple provider redeems the app's codes; the web flow needs the Service ID");let e=this.resolveState(),{clientId:t,redirectUrl:r,scopes:i}=this.getConfig();this.validateConfig();let s={client_id:t,redirect_uri:r,scope:i.join(" "),state:e,response_type:"code",...this.parameters};if(i.length>0)s.response_mode="form_post";return`${this.baseUrl}/auth/authorize?${new URLSearchParams(s).toString()}`}async getAccessToken(e){let{clientId:t,redirectUrl:r}=this.getConfig();this.validateConfig();let i=await fetch(`${this.baseUrl}/auth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:e,...this.native?{}:{redirect_uri:r},client_id:t,client_secret:this.generateClientSecret()})}),s=await i.json();if(!i.ok||s.error)throw Error(`Apple OAuth error: ${s.error_description??s.error??`HTTP ${i.status}`}`);if(!s.id_token)throw Error("Apple OAuth error: token response contained no id_token");return s.id_token}async getUserByToken(e,t={}){let{clientId:r}=this.getConfig(),i;try{i=await z(e,{jwksUrl:`${this.baseUrl}/auth/keys`,issuer:this.baseUrl,audience:r,nonce:t.nonce})}catch(o){throw Error(`Apple OAuth error: ${o instanceof Error?o.message:String(o)}`)}let s=typeof i.email==="string"?i.email:null,n=null;if(i.email_verified===!0||i.email_verified==="true")n=!0;else if(i.email_verified===!1||i.email_verified==="false")n=!1;return{id:String(i.sub),nickname:null,name:"",email:s,emailVerified:n,avatar:null,token:e,raw:i}}generateClientSecret(){let{clientId:e,teamId:t,keyId:r,privateKey:i}=this.getConfig(),s=Math.floor(Date.now()/1000),n={alg:"ES256",kid:r,typ:"JWT"},o={iss:t,iat:s,exp:s+3600,aud:this.baseUrl,sub:e},a=`${this.base64urlJson(n)}.${this.base64urlJson(o)}`,c;try{c=st(i)}catch(d){throw new h(`Apple private key could not be parsed: ${d instanceof Error?d.message:String(d)}`)}let u=nt("sha256",ve.from(a),{key:c,dsaEncoding:"ieee-p1363"});return`${a}.${u.toString("base64url")}`}base64urlJson(e){return ve.from(JSON.stringify(e)).toString("base64url")}validateConfig(){let{clientId:e,teamId:t,keyId:r,privateKey:i,redirectUrl:s}=this.getConfig();if(!e)throw new h(this.native?"Apple client ID (the app's bundle ID) not provided":"Apple client ID (Service ID) not provided");if(!t)throw new h("Apple team ID not provided");if(!r)throw new h("Apple key ID not provided");if(!i)throw new h("Apple private key not provided");if(!s&&!this.native)throw new h("Apple redirect URL not provided")}getTokenUrl(){return`${this.baseUrl}/auth/token`}}import{fetchPublicUrl as ht}from"@stacksjs/security";var Br=23,ot=/\bhttps?:\/\/[^\s<>]+|(?<![@\w.-])(?:[a-z0-9-]+\.)+(?:com|org|net|io|dev|app|co|social|blog|ai|me|info|xyz|tv|fm|us|uk|de|fr|jp|ca|au|nl|ch|se|no|es|it)\b(?:\/[^\s<>]*)?/gi,at=/[.,;:!?)\]}'"]+$/,xe;function _e(){return xe??=new Intl.Segmenter(void 0,{granularity:"grapheme"}),xe}function F(e){let t=0;for(let r of _e().segment(e))t++;return t}function Ie(e){let t=[],r=0;for(let i of e.matchAll(ot)){let s=i[0].replace(at,"");if(!s)continue;let n=i.index;if(n>r)t.push({link:!1,value:e.slice(r,n)});t.push({link:!0,value:s}),r=n+s.length}if(r<e.length)t.push({link:!1,value:e.slice(r)});return t}function ct(e){return e<=4351||e>=8192&&e<=8205||e>=8208&&e<=8223||e>=8242&&e<=8247}function lt(e){let t=0;for(let{segment:r}of _e().segment(e.normalize("NFC"))){if(/\p{Extended_Pictographic}|\p{Regional_Indicator}/u.test(r)){t+=2;continue}for(let i of r)t+=ct(i.codePointAt(0))?1:2}return t}function dt(e,t,r={}){let i=String(t??"");switch(e){case"twitter":return Ie(i).reduce((s,n)=>s+(n.link?23:lt(n.value)),0);case"mastodon":{let s=r.linkLength??23;return Ie(i).reduce((n,o)=>{if(o.link)return n+s;return n+F(o.value.replace(/(^|[^\w/])(@[\w.-]+)@[\w.-]+\.[a-z]{2,}/gi,"$1$2"))},0)}case"bluesky":case"threads":return F(i);default:return i.length}}function b(e,t,r,i={}){return r>0&&dt(e,t,i)>r}function H(e){let t;try{t=typeof e==="string"?JSON.parse(e):e}catch{return""}if(!t||typeof t!=="object")return"";let r=Array.isArray(t.errors)?t.errors[0]:void 0,i=[t.detail,t.error?.error_user_msg,t.error?.message,t.message,t.error_description,t.error_message,r?.detail,r?.message,typeof t.error==="string"?t.error:void 0];for(let s of i){let n=typeof s==="string"?s.replace(/\s+/g," ").trim():"";if(n&&n.length<=200&&n.includes(" ")&&!/[{}<>]/.test(n))return n.replace(/[.!]+$/,"")}return""}function ut(e,t){let r=(i)=>i.test(t);if(e===429||r(/rate.?limit|too many requests|usage cap|throttl|request limit reached/i))return"rate-limited";if(r(/duplicate|already (?:posted|published|exists)|DUPLICATE_POST/i))return"duplicate";if(e===401||r(/invalid.?token|expired.?token|token (?:has )?(?:expired|been revoked)|session has (?:expired|been invalidated)|OAuthException.*(?:expired|invalid)|REVOKED_ACCESS_TOKEN/i))return"expired";if(e===413||r(/media|image|video|attachment|aspect ratio|file size|unsupported (?:format|type)|blob/i))return"media";if(e===403||r(/permission|scope|not (?:allowed|authorized|permitted)|forbidden|ACCESS_DENIED|insufficient/i))return"permission";if(e===408||e>=500)return"temporary";if(e===400||e===404||e===409||e===422)return"content";if(r(/fetch failed|network|ENOTFOUND|ECONNREFUSED|ECONNRESET|EAI_AGAIN|timed? ?out|socket|aborted/i))return"temporary";return"unknown"}function j(e){let t=e??{},r=Number(t.status)||0,i=String(t.message??e??""),s=H(t.body),n=typeof t.body==="string"?t.body.slice(0,2000):"";return{kind:ut(r,`${s} ${n} ${r?"":i}`),status:r,reason:s}}function Nr(e){return j(e).kind==="expired"}class y extends Error{network;status;body;retryAfterMs;constructor(e,t,r,i,s={}){super(t);this.network=e;this.status=r;this.body=i;if(this.name="SocialApiError",s.retryAfterMs!==void 0)this.retryAfterMs=s.retryAfterMs}get kind(){return j(this).kind}get reason(){return H(this.body)}}function Te(e,t){let r=e.trim();if(!r)return;if(/^\d+(?:\.\d+)?$/.test(r)){let s=Number(r);return s>1e9?Math.max(0,Math.round(s*1000-t)):Math.round(s*1000)}let i=Date.parse(r);return Number.isNaN(i)?void 0:Math.max(0,i-t)}function pt(e,t){let r=t.now??Date.now(),i=e.get("retry-after");if(i){let n=Te(i,r);if(n!==void 0)return n}if(!t.rateLimited)return;for(let n of["x-rate-limit-reset","ratelimit-reset","x-ratelimit-reset"]){let o=e.get(n),a=o?Te(o,r):void 0;if(a!==void 0)return a}let s=0;for(let n of["x-business-use-case-usage","x-app-usage"]){let o=e.get(n);if(!o)continue;try{let a=JSON.parse(o),c=Array.isArray(a)?a:Object.values(a??{}).flat();for(let u of[a,...c]){let d=Number(u?.estimated_time_to_regain_access);if(Number.isFinite(d)&&d>s)s=d}}catch{}}return s>0?s*60000:void 0}function m(e,t,r){let i=H(r)||t.statusText||"no reason given",s=pt(t.headers,{rateLimited:j({status:t.status,body:r}).kind==="rate-limited"});return[`${e} failed (${t.status}): ${i}`,t.status,r,s===void 0?{}:{retryAfterMs:s}]}var T="app.bsky.feed.post";function Ue(e){let t=/^at:\/\/([^/]+)\/([^/]+)\/([^/]+)$/.exec(String(e||"").trim());if(!t)throw Error(`"${e}" is not a Bluesky post URI.`);return{repo:t[1],collection:t[2],rkey:t[3]}}class L extends y{constructor(e,t,r,i={}){super("bluesky",e,t,r,i);this.name="BlueskyApiError"}get isAuthError(){if(this.status===401||this.status===403)return!0;if(this.status!==400)return!1;try{return gt.includes(String(JSON.parse(this.body)?.error))}catch{return!1}}}var gt=["ExpiredToken","InvalidToken"],Ae=1e6,mt=4,ft=3;function Gr(e){return e instanceof L&&e.isAuthError}var wt=new TextEncoder;function x(e){return wt.encode(e).length}function yt(e){let t=[],r=/https?:\/\/[^\s<>"']+/g;for(let o of e.matchAll(r)){let a=o[0].replace(/[),.;!?]+$/,"");t.push({byteStart:x(e.slice(0,o.index)),byteEnd:x(e.slice(0,o.index))+x(a),type:"link",value:a})}let i=(o,a)=>t.some((c)=>c.type==="link"&&o<c.byteEnd&&a>c.byteStart),s=/(^|\s)([#\uFF03])([^\s\u00AD\u2060\u200A-\u200D\u20E2]+)/gu;for(let o of e.matchAll(s)){let a=o[1],c=o[2],u=o[3];if(a===void 0||c===void 0||u===void 0)continue;let d=u.replace(/\p{P}+$/u,"");if(!d||!/[^\d\p{P}]/u.test(d)||[...d].length>64)continue;let l=(o.index??0)+a.length,p=x(e.slice(0,l)),g=p+x(c+d);if(i(p,g))continue;t.push({byteStart:p,byteEnd:g,type:"tag",value:d})}let n=/(^|\s)(@[a-z0-9][a-z0-9.-]*\.[a-z]{2,})/gi;for(let o of e.matchAll(n)){let a=o[1],c=o[2];if(a===void 0||c===void 0)continue;let u=(o.index??0)+a.length,d=x(e.slice(0,u)),l=d+x(c);if(i(d,l))continue;t.push({byteStart:d,byteEnd:l,type:"mention",value:c.slice(1).replace(/\.+$/,"")})}return t.sort((o,a)=>o.byteStart-a.byteStart)}async function kt(e,t={}){let r=(t.entryway??"https://bsky.social").replace(/\/+$/,""),i=(t.directory??"https://plc.directory").replace(/\/+$/,""),s=t.fetchJson??(async(n)=>{let a=n.startsWith(`${r}/`)||n.startsWith(`${i}/`)?await fetch(n,{redirect:"error"}):await ht(n,{},{maxRedirects:0,timeoutMs:1e4,maxBytes:262144});if(!a.ok)throw Error(`${a.status}`);return await a.json()});try{let n=e.trim(),o=n.startsWith("did:")?void 0:n.replace(/^@/,"").toLowerCase();if(o!==void 0){let p=await s(`${r}/xrpc/com.atproto.identity.resolveHandle?handle=${encodeURIComponent(o)}`);if(typeof p?.did!=="string")return;n=p.did}let a;if(/^did:plc:[a-z0-9]+$/i.test(n))a=`${i}/${n}`;else if(/^did:web:[a-z0-9.-]+$/i.test(n))a=`https://${n.slice(8)}/.well-known/did.json`;else return;let c=await s(a);if(c?.id!==n)return;let u=c.alsoKnownAs?.find((p)=>typeof p==="string"&&p.startsWith("at://"));if(o!==void 0&&u!==`at://${o}`)return;let d=(c.service??[]).find((p)=>(p?.id==="#atproto_pds"||p?.id===`${n}#atproto_pds`)&&p.type==="AtprotoPersonalDataServer");if(typeof d?.serviceEndpoint!=="string")return;let l=new URL(d.serviceEndpoint);if(l.protocol!=="https:"||l.username||l.password||l.search||l.hash)return;return l.href.replace(/\/+$/,"")}catch{return}}var V=/^did:[a-z]+:[A-Za-z0-9._:%-]+$/,bt=/^[A-Za-z0-9._:~-]{1,512}$/,Ce=/^[A-Za-z0-9]{1,256}$/;function Re(e){let t,r;if(e.startsWith("at://")){let i=Ue(e);if(i.collection===T)({repo:t,rkey:r}=i)}else{let i=URL.parse(e);if(i?.origin==="https://bsky.app"&&!i.username&&!i.password){let[,s,n]=/^\/profile\/([^/]+)\/post\/([^/]+)\/?$/.exec(i.pathname)??[];try{if(s&&n)t=decodeURIComponent(s),r=decodeURIComponent(n)}catch{}}}if(!t||!V.test(t)&&!/^(?:[A-Za-z0-9-]+\.)+[A-Za-z]+$/.test(t)||!r||!bt.test(r)||r==="."||r==="..")throw Error("Choose a valid Bluesky post link.");return{repo:t,rkey:r}}function St(e){if(!Array.isArray(e)||e.some((r)=>typeof r!=="string"||r.length>128||!/^!?[a-z]+(?:-[a-z]+)*$/.test(r)))throw Error("Bluesky content labels must be lowercase label names.");let t=[...new Set(e)].map((r)=>({val:r}));if(t.length>10)throw Error("Bluesky supports up to 10 self-labels per post.");return t}var Pt="234567abcdefghijklmnopqrstuvwxyz";function Jr(e=Date.now(),t=Math.floor(Math.random()*1024)){let r=BigInt(Math.floor(e))*1000n<<10n|BigInt(t&1023),i="";for(let s=0;s<13;s++)i=Pt[Number(r&31n)]+i,r>>=5n;return i}class G{provider="bluesky";characterLimit=300;service;configuredService;fetcher;constructor(e={}){this.service=e.service||"https://bsky.social",this.configuredService=Boolean(e.service),this.fetcher=e.fetcher}async createSession(e){let t=e.identifier.trim(),r=e.password.trim();if(!t)throw Error("Bluesky identifier is required.");if(!r)throw Error("Bluesky app password is required.");let i=await this.signIn(t,r),s=await this.getProfile({did:i.did,handle:i.handle,accessToken:i.accessJwt,refreshToken:i.refreshJwt}).catch(()=>{return});return{did:i.did,handle:i.handle,displayName:s?.displayName,accessJwt:i.accessJwt,refreshJwt:i.refreshJwt,service:this.service}}async signIn(e,t){let r=()=>this.post("/xrpc/com.atproto.server.createSession",{identifier:e,password:t});try{return await r()}catch(i){if(!(i instanceof L&&(i.status===400||i.status===401))||this.configuredService)throw i;let n=await kt(e,{entryway:this.service});if(!n||n===this.service)throw i;return this.service=n,await r()}}async refreshSession(e){if(!e)throw Error("Bluesky refresh token is required.");let t=await this.post("/xrpc/com.atproto.server.refreshSession",void 0,{authorization:`Bearer ${e}`});return{did:t.did,handle:t.handle,accessJwt:t.accessJwt,refreshJwt:t.refreshJwt}}async resolveQuote(e,t){if(!e.accessToken)throw Error("Bluesky access token is missing for this identity.");let{repo:r,rkey:i}=Re(t.trim()),s=V.test(r)?r:await this.resolveHandle(r);if(!s||!V.test(s))throw Error("Could not resolve the author of this Bluesky post.");let n=`at://${s}/${T}/${i}`,o=new URL(`${this.service}/xrpc/app.bsky.feed.getPosts`);o.searchParams.set("uris",n);let c=(await this.request(o,{headers:{authorization:`Bearer ${e.accessToken}`},redirect:"error",signal:AbortSignal.timeout(15000)})).posts?.find((u)=>u.uri===n);if(!c||typeof c.cid!=="string"||!Ce.test(c.cid))throw Error("Could not find the Bluesky post at this link.");if(c.viewer?.embeddingDisabled)throw Error("The author has disabled quoting this Bluesky post.");return{uri:n,cid:c.cid}}async publish(e,t,r={}){let i=e.did||e.handle;if(!e.accessToken)throw Error("Bluesky access token is missing for this identity.");if(!i)throw Error("Bluesky identity DID or handle is required.");if(b("bluesky",t.text,this.characterLimit))throw Error(`Bluesky posts must be ${this.characterLimit} characters or fewer.`);let s=r.quote;if(s){let l=Re(s.uri);if(s.uri!==`at://${l.repo}/${T}/${l.rkey}`||!V.test(l.repo)||typeof s.cid!=="string"||!Ce.test(s.cid))throw Error("Resolve the Bluesky post before quoting it.")}let n=r.selfLabels===void 0?[]:St(r.selfLabels),o={$type:"app.bsky.feed.post",text:t.text,createdAt:t.scheduledAt||new Date().toISOString()};if(t.langs?.length)o.langs=t.langs.slice(0,ft);if(t.reply)o.reply=t.reply;if(n.length)o.labels={$type:"com.atproto.label.defs#selfLabels",values:n};let a=t.facets??await this.buildFacets(t.text);if(a.length)o.facets=a;let c=[],u=(t.media||[]).filter((l)=>l.bytes?.length).slice(0,mt);if(u.length){let l=[];for(let p of u){let g=await this.uploadBlob(e,p.bytes,p.mimeType||"image/jpeg");l.push({image:g,alt:p.altText||""})}if(o.embed={$type:"app.bsky.embed.images",images:l},t.external)c.push("A Bluesky post holds one attachment, so the images went out and the link card did not. The link in the text still works.")}else if(t.external){let l={uri:t.external.uri,title:t.external.title,description:t.external.description||""},p=t.external.thumb;if(p?.bytes?.length)if(p.bytes.length>Ae)c.push("The link card's picture is larger than Bluesky takes, so the card went out without it.");else try{l.thumb=await this.uploadBlob(e,p.bytes,p.mimeType)}catch{c.push("Bluesky did not take the link card's picture, so the card went out without it.")}o.embed={$type:"app.bsky.embed.external",external:l}}if(s){let l={$type:"app.bsky.embed.record",record:{uri:s.uri,cid:s.cid}};o.embed=o.embed?{$type:"app.bsky.embed.recordWithMedia",record:l,media:o.embed}:l}let d=await this.createPostRecord(e,i,o,r.rkey);return{provider:this.provider,uri:d.uri,cid:d.cid,url:this.toPostUrl(e.handle,d.uri),...c.length?{warnings:c}:{}}}async metrics(e,t){if(!e.accessToken)throw Error("Bluesky access token is missing for this identity.");let r=[];for(let i=0;i<t.length;i+=25){let s=new URL(`${this.service}/xrpc/app.bsky.feed.getPosts`);for(let o of t.slice(i,i+25))s.searchParams.append("uris",o);let n=await this.request(s,{headers:{authorization:`Bearer ${e.accessToken}`}});for(let o of n.posts||[])r.push({uri:o.uri,likes:o.likeCount??0,reposts:o.repostCount??0,replies:o.replyCount??0,quotes:o.quoteCount??0})}return r}async postMetrics(e,t){if(!e.accessToken)throw Error("Bluesky access token is missing for this identity.");if(t.length===0)return[];let r=new URL(`${this.service}/xrpc/app.bsky.feed.getPosts`);for(let s of t.slice(0,25))r.searchParams.append("uris",s);return((await this.request(r,{headers:{authorization:`Bearer ${e.accessToken}`}})).posts||[]).map((s)=>({uri:s.uri,likeCount:s.likeCount||0,repostCount:s.repostCount||0,replyCount:s.replyCount||0}))}async timeline(e,t={}){if(!e.accessToken)throw Error("Bluesky access token is missing for this identity.");let r=new URL(`${this.service}/xrpc/app.bsky.feed.getTimeline`);if(r.searchParams.set("limit",String(Math.min(Math.max(t.limit||30,1),100))),t.cursor)r.searchParams.set("cursor",t.cursor);let i=await this.request(r,{headers:{authorization:`Bearer ${e.accessToken}`}});return{cursor:i.cursor,items:(i.feed||[]).flatMap((s)=>{let n=s.post;if(!n?.uri||!n.author?.handle)return[];return[{uri:n.uri,authorHandle:n.author.handle,authorName:n.author.displayName,authorAvatar:n.author.avatar,postUrl:this.toPostUrl(n.author.handle,n.uri),body:n.record?.text||"",postedAt:n.record?.createdAt||new Date().toISOString(),likeCount:n.likeCount||0,repostCount:n.repostCount||0,replyCount:n.replyCount||0}]})}}async getProfile(e){if(!e.accessToken)throw Error("Bluesky access token is missing for this identity.");let t=e.did||e.handle;if(!t)throw Error("Bluesky identity DID or handle is required.");let r=new URL(`${this.service}/xrpc/app.bsky.actor.getProfile`);return r.searchParams.set("actor",t),await this.request(r,{headers:{authorization:`Bearer ${e.accessToken}`}})}async buildFacets(e){let t=[];for(let r of yt(e)){let i=null;if(r.type==="link")i={$type:"app.bsky.richtext.facet#link",uri:r.value};else if(r.type==="tag")i={$type:"app.bsky.richtext.facet#tag",tag:r.value};else if(r.type==="mention"){let s=await this.resolveHandle(r.value);if(s)i={$type:"app.bsky.richtext.facet#mention",did:s}}if(i)t.push({index:{byteStart:r.byteStart,byteEnd:r.byteEnd},features:[i]})}return t}async resolveHandle(e){try{let t=new URL(`${this.service}/xrpc/com.atproto.identity.resolveHandle`);return t.searchParams.set("handle",e),(await this.request(t,{})).did||null}catch{return null}}async uploadBlob(e,t,r){if(!e.accessToken)throw Error("Bluesky access token is missing for this identity.");if(t.length>Ae)throw Error("Bluesky images must be 1MB or smaller.");return(await this.request(new URL(`${this.service}/xrpc/com.atproto.repo.uploadBlob`),{method:"POST",headers:{"content-type":r,authorization:`Bearer ${e.accessToken}`},body:new Uint8Array(t)})).blob}async listAuthoredPosts(e,t={}){let r=e.did||e.handle;if(!e.accessToken)throw Error("Bluesky access token is missing for this identity.");if(!r)throw Error("Bluesky identity DID or handle is required.");let i=new URL(`${this.service}/xrpc/com.atproto.repo.listRecords`);if(i.searchParams.set("repo",r),i.searchParams.set("collection",T),i.searchParams.set("limit",String(Math.min(Math.max(t.limit||100,1),100))),t.cursor)i.searchParams.set("cursor",t.cursor);let s=await this.request(i,{headers:{authorization:`Bearer ${e.accessToken}`}});return{cursor:s.cursor,posts:(s.records||[]).filter((n)=>n?.uri).map((n)=>({uri:n.uri,cid:n.cid,text:n.value?.text,postedAt:n.value?.createdAt,url:e.handle?this.toPostUrl(e.handle,n.uri):void 0}))}}async createPostRecord(e,t,r,i){let s=`Bearer ${e.accessToken}`;try{return await this.post("/xrpc/com.atproto.repo.createRecord",{repo:t,collection:T,...i?{rkey:i}:{},record:r},{authorization:s})}catch(n){if(!i||!(n instanceof L)||n.status>=500)throw n;let o=new URL(`${this.service}/xrpc/com.atproto.repo.getRecord`);o.searchParams.set("repo",t),o.searchParams.set("collection",T),o.searchParams.set("rkey",i);let a=await this.request(o,{headers:{authorization:s}}).catch(()=>{return});if(a?.uri&&a.cid&&a.value?.text===r.text)return{uri:a.uri,cid:a.cid};throw n}}async deletePost(e,t){if(!e.accessToken)throw Error("Bluesky access token is missing for this identity.");let{repo:r,collection:i,rkey:s}=Ue(t.uri);await this.post("/xrpc/com.atproto.repo.deleteRecord",{repo:r,collection:i,rkey:s},{authorization:`Bearer ${e.accessToken}`})}async post(e,t,r={}){return await this.request(new URL(`${this.service}${e}`),{method:"POST",headers:{...t===void 0?{}:{"content-type":"application/json"},...r},...t===void 0?{}:{body:JSON.stringify(t)}})}async request(e,t){let r=await(this.fetcher??fetch)(e,{...t,redirect:"error"}),i=await r.text();if(!r.ok)throw new L(...m("Bluesky API",r,i));return i?JSON.parse(i):{}}toPostUrl(e,t){let r=t.split("/").pop();return`https://bsky.app/profile/${e}/post/${r}`}}import{fetcher as Ee}from"@stacksjs/api";import{config as D}from"@stacksjs/config";var J="v24.0";function K(e){try{let t=JSON.parse(String(e?.body??""));return t.error?.code===100&&/does not exist/i.test(String(t.error.message))}catch{return!1}}class ne extends w{baseUrl="https://www.facebook.com";apiUrl="https://graph.facebook.com";get graphVersion(){return D.services.facebook?.graphVersion??J}getConfig(){let e={clientId:this.clientId||(D.services.facebook?.clientId??""),clientSecret:this.clientSecret||(D.services.facebook?.clientSecret??""),redirectUrl:this.redirectUrl||(D.services.facebook?.redirectUrl??""),scopes:D.services.facebook?.scopes??["email","public_profile"]};return this.setScopes(e.scopes),e}async getAuthUrl(){let e=this.resolveState(),{clientId:t,redirectUrl:r,scopes:i}=this.getConfig();return this.validateConfig(),`${this.baseUrl}/${this.graphVersion}/dialog/oauth?${new URLSearchParams({client_id:t,redirect_uri:r,scope:i.join(","),response_type:"code",...await this.pkceFields(),...this.parameters,state:e}).toString()}`}async getAccessToken(e){let{clientId:t,clientSecret:r,redirectUrl:i}=this.getConfig();this.validateConfig();let s=await Ee.get(`${this.apiUrl}/${this.graphVersion}/oauth/access_token?${new URLSearchParams({client_id:t,client_secret:r,redirect_uri:i,code:e,...this.pkceTokenFields()}).toString()}`);if(s.data.error)throw Error(`Facebook OAuth error: ${s.data.error.message}`);return s.data.access_token}async getUserByToken(e){let t=await Ee.withHeaders({Authorization:`Bearer ${e}`}).get(`${this.apiUrl}/${this.graphVersion}/me?${new URLSearchParams({fields:"id,name,email,picture"}).toString()}`);return{id:t.data.id,nickname:null,name:t.data.name,email:t.data.email??null,avatar:t.data.picture?.data.url??null,token:e,raw:t.data}}validateConfig(){let{clientId:e,clientSecret:t,redirectUrl:r}=this.getConfig();if(!e)throw new h("Facebook client ID not provided");if(!t)throw new h("Facebook client secret not provided");if(!r)throw new h("Facebook redirect URL not provided")}getTokenUrl(){return`${this.apiUrl}/${this.graphVersion}/oauth/access_token`}}import{fetcher as oe}from"@stacksjs/api";import{config as X}from"@stacksjs/config";class ae extends w{baseUrl="https://github.com";apiUrl="https://api.github.com";getConfig(){let e={clientId:this.clientId||(X.services.github?.clientId??""),clientSecret:this.clientSecret||(X.services.github?.clientSecret??""),redirectUrl:this.redirectUrl||(X.services.github?.redirectUrl??""),scopes:this._scopes.length>0?this._scopes:X.services.github?.scopes??["read:user","user:email"]};return this.setScopes(e.scopes),e}async getAuthUrl(){let e=this.resolveState(),{clientId:t,redirectUrl:r,scopes:i}=this.getConfig();return this.validateConfig(),`${this.baseUrl}/login/oauth/authorize?${new URLSearchParams({client_id:t,redirect_uri:r,scope:i.join(" "),state:e,response_type:"code",...await this.pkceFields(),...this.parameters}).toString()}`}async getAccessToken(e){let{clientId:t,clientSecret:r,redirectUrl:i}=this.getConfig();this.validateConfig();let s=await oe.post(`${this.baseUrl}/login/oauth/access_token`,{client_id:t,client_secret:r,code:e,redirect_uri:i,...this.pkceTokenFields()});if(s.data.error)throw Error(`GitHub OAuth error: ${s.data.error_description}`);return s.data.access_token}async getUserByToken(e){let[t,r]=await Promise.all([oe.withHeaders({Accept:"application/vnd.github.v3+json",Authorization:`token ${e}`}).get(`${this.apiUrl}/user`),oe.withHeaders({Accept:"application/vnd.github.v3+json",Authorization:`token ${e}`}).get(`${this.apiUrl}/user/emails`)]),i=this.pickEmail(r.data);return{id:t.data.id.toString(),nickname:t.data.login,name:t.data.name??t.data.login,email:i?.email??t.data.email??null,emailVerified:i?i.verified:null,avatar:t.data.avatar_url,token:e,raw:t.data}}pickEmail(e){if(!Array.isArray(e)||e.length===0)return null;let t=e.find((i)=>i.primary&&i.verified),r=e.find((i)=>i.verified);return t??r??e.find((i)=>i.primary)??e[0]??null}getEmail(e){return this.pickEmail(e)?.email??null}validateConfig(){let{clientId:e,clientSecret:t,redirectUrl:r}=this.getConfig();if(!e)throw new h("GitHub client ID not provided");if(!t)throw new h("GitHub client secret not provided");if(!r)throw new h("GitHub redirect URL not provided")}getTokenUrl(){return`${this.baseUrl}/login/oauth/access_token`}}import{fetcher as $e}from"@stacksjs/api";import{config as Q}from"@stacksjs/config";class ce extends w{baseUrl="https://accounts.google.com";apiUrl="https://www.googleapis.com";tokenUrl="https://oauth2.googleapis.com/token";tokenInfoUrl="https://oauth2.googleapis.com/tokeninfo";certsUrl="https://www.googleapis.com/oauth2/v3/certs";issuers=["https://accounts.google.com","accounts.google.com"];getConfig(){let e={clientId:this.clientId||(Q.services.google?.clientId??""),clientSecret:this.clientSecret||(Q.services.google?.clientSecret??""),redirectUrl:this.redirectUrl||(Q.services.google?.redirectUrl??""),scopes:this._scopes.length>0?this._scopes:Q.services.google?.scopes??["openid","email"]};return this.setScopes(e.scopes),e}async getAuthUrl(){let e=this.resolveState(),{clientId:t,redirectUrl:r,scopes:i}=this.getConfig();return this.validateConfig(),`${this.baseUrl}/o/oauth2/v2/auth?${new URLSearchParams({client_id:t,redirect_uri:r,scope:i.join(" "),state:e,response_type:"code",access_type:"offline",prompt:"consent",...await this.pkceFields(),...this.parameters}).toString()}`}async getAccessToken(e){let{clientId:t,clientSecret:r,redirectUrl:i}=this.getConfig();this.validateConfig();let s=await $e.post(this.tokenUrl,{client_id:t,client_secret:r,code:e,redirect_uri:i,grant_type:"authorization_code",...this.pkceTokenFields()});if(s.data.error)throw Error(`Google OAuth error: ${s.data.error_description}`);return s.data.access_token}async getUserByToken(e){await this.assertTokenWasIssuedToUs(e);let t=await $e.withHeaders({Authorization:`Bearer ${e}`}).get(`${this.apiUrl}/oauth2/v2/userinfo`);return{id:t.data.id,nickname:t.data.given_name,name:t.data.name,email:t.data.email,emailVerified:typeof t.data.verified_email==="boolean"?t.data.verified_email:null,avatar:t.data.picture,token:e,raw:t.data}}async getUserByIdToken(e,t={}){let{clientId:r}=this.getConfig(),i;try{i=await z(e,{jwksUrl:this.certsUrl,issuer:this.issuers,audience:r,nonce:t.nonce})}catch(n){throw Error(`Google OAuth error: ${n instanceof Error?n.message:String(n)}`)}let s=typeof i.email==="string"?i.email:"";return{id:String(i.sub),nickname:typeof i.given_name==="string"?i.given_name:null,name:typeof i.name==="string"?i.name:"",email:s,emailVerified:typeof i.email_verified==="boolean"?i.email_verified:i.email_verified==="true"?!0:i.email_verified==="false"?!1:null,avatar:typeof i.picture==="string"?i.picture:null,token:e,raw:i}}async assertTokenWasIssuedToUs(e){let{clientId:t}=this.getConfig(),r=await fetch(`${this.tokenInfoUrl}?access_token=${encodeURIComponent(e)}`);if(!r.ok)throw Error(`Google OAuth error: access token was not accepted by tokeninfo (HTTP ${r.status})`);let i=await r.json();if(i.error)throw Error(`Google OAuth error: ${i.error_description??i.error}`);let s=i.aud??i.audience;if(!s)throw Error("Google OAuth error: tokeninfo did not report an audience for the access token");if(s!==t)throw Error("Google OAuth error: access token was issued to a different client")}validateConfig(){let{clientId:e,clientSecret:t,redirectUrl:r}=this.getConfig();if(!e)throw new h("Google client ID not provided");if(!t)throw new h("Google client secret not provided");if(!r)throw new h("Google redirect URL not provided")}getTokenUrl(){return this.tokenUrl}}var vt=10,xt=1000,It=20,Oe={likes:"likes",comments:"replies",shares:"shares",saved:"saves",reach:"reach",views:"views"};class k extends y{constructor(e,t,r,i={}){super("instagram",e,t,r,i);this.name="InstagramApiError"}get isAuthError(){return this.status===401||this.status===403||this.status===190}}class le{provider="instagram";characterLimit=2200;maxImages=vt;containerTimeoutMs=300000;graphVersion;authBase;graphBase;constructor(e={}){this.graphVersion=e.graphVersion||J,this.authBase=e.authBase||"https://www.facebook.com",this.graphBase=e.graphBase||"https://graph.facebook.com"}getAuthUrl(e){let t=new URLSearchParams({client_id:e.clientId,redirect_uri:e.redirectUrl,scope:e.scopes.join(","),state:e.state,response_type:"code"});return`${this.authBase}/${this.graphVersion}/dialog/oauth?${t.toString()}`}async exchangeCode(e){let t=await this.graph("/oauth/access_token",{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:e.clientId,client_secret:e.clientSecret,redirect_uri:e.redirectUrl,code:e.code}).toString()});if(!t.access_token)throw new k("Facebook did not return an access token.",400,JSON.stringify(t));return{accessToken:t.access_token,expiresIn:t.expires_in}}async resolveAccount(e){for await(let t of this.pageAccounts(e))return{igUserId:t.igUserId,username:t.username,pageAccessToken:t.pageAccessToken};throw new k("No Instagram Business account is linked to your Facebook Pages.",400,"")}async listAccounts(e){let t=new Map;for await(let r of this.pageAccounts(e))if(r.pageId&&!t.has(r.pageId))t.set(r.pageId,{...r,pageId:r.pageId});return[...t.values()]}async*pageAccounts(e){let r=`/me/accounts?${new URLSearchParams({fields:"id,name,access_token,instagram_business_account{id,username}"}).toString()}`;for(let i=0;r&&i<It;i++){let s=await this.graph(r,{method:"GET"},e);for(let n of s.data??[]){let o=n.instagram_business_account;if(o?.id&&n.access_token)yield{pageId:n.id,pageName:n.name,igUserId:o.id,username:o.username,pageAccessToken:n.access_token}}r=s.paging?.next}}async exchangeLongLivedUserToken(e,t,r){let i=await this.graph("/oauth/access_token",{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"fb_exchange_token",client_id:e,client_secret:t,fb_exchange_token:r}).toString()});if(!i.access_token)throw new k("Facebook did not return a long-lived token.",400,JSON.stringify(i));return{accessToken:i.access_token,expiresIn:i.expires_in}}async publish(e,t){if(!e.accessToken)throw Error("Instagram access token is missing for this identity.");let r=e.did;if(!r)throw Error("Instagram account id is required to publish.");let i=(t.media??[]).slice(0,this.maxImages);if(!i.length)throw Error("Instagram requires an image to post.");if(i.some((d)=>!d.url))throw new k("Instagram fetches images from a public address, and this image has none.",422,"");if(i.some((d)=>d.mimeType&&!/^image\/jpe?g$/i.test(d.mimeType)))throw new k("Instagram only publishes JPEG images, and this image is not one.",422,"");if(b("instagram",t.text,this.characterLimit))throw Error(`Instagram captions must be ${this.characterLimit} characters or fewer.`);let s=e.accessToken,n=async(d)=>{let l=await this.graph(`/${r}/media`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams(d).toString()},s);if(!l.id)throw new k("Instagram did not return a media container id.",400,JSON.stringify(l));return l.id},o=(d)=>({image_url:d.url,...d.altText?.trim()?{alt_text:d.altText.trim().slice(0,xt)}:{}}),a;if(i.length>1){let d=[];for(let l of i)d.push(await n({...o(l),is_carousel_item:"true"}));a=await n({media_type:"CAROUSEL",children:d.join(","),caption:t.text})}else a=await n({...o(i[0]),caption:t.text});await this.waitForContainer(a,s);let c=await this.graph(`/${r}/media_publish`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({creation_id:a}).toString()},s);if(!c.id)throw new k("Instagram did not return a published post id.",400,JSON.stringify(c));let u=await this.graph(`/${c.id}?fields=permalink`,{method:"GET"},s).catch(()=>{return});return{provider:this.provider,uri:c.id,url:u?.permalink}}async waitForContainer(e,t){let r=0,i=1000;for(;;){let s=await this.graph(`/${e}?fields=status_code,status`,{method:"GET"},t),n=s.status_code;if(n==="FINISHED"||n==="PUBLISHED"||n===void 0)return;if(n==="ERROR"||n==="EXPIRED")throw new k(`Instagram could not prepare this post (${n}${s.status?`: ${s.status}`:""}).`,422,JSON.stringify(s));if(r>=this.containerTimeoutMs)throw new k(`Instagram was still processing this post after ${Math.round(r/1000)} seconds, so it was not published.`,504,JSON.stringify(s));let o=Math.min(i,60000,Math.max(this.containerTimeoutMs-r,0));await this.sleep(o),r+=o,i*=2}}sleep(e){return new Promise((t)=>setTimeout(t,e))}async timeline(e,t={}){return{items:[]}}async metrics(e,t){let r=e.accessToken;if(!r)throw Error("Instagram access token is missing for this identity.");let i=[];for(let s of t){let n=String(s||"").trim();if(!n)continue;let o;try{o=await this.graph(`/${encodeURIComponent(n)}/insights?metric=${Object.keys(Oe).join(",")}`,{method:"GET"},r)}catch(c){if(c instanceof k&&K(c))continue;throw c}let a={uri:s};for(let c of o.data||[]){let u=Oe[String(c.name)],d=Number(c.values?.[0]?.value);if(u&&Number.isFinite(d))a[u]=d}i.push(a)}return i}graphUrl(e){if(!/^https?:\/\//i.test(e))return`${this.graphBase}/${this.graphVersion}${e}`;let t=new URL(e);if(t.origin!==new URL(this.graphBase).origin||t.username||t.password)throw new k("Instagram returned a paging address on another host, so it was not followed.",502,"");return t.searchParams.delete("access_token"),t.href}async graph(e,t,r){let i=new Headers(t.headers);if(r)i.set("authorization",`Bearer ${r}`);let s=await fetch(this.graphUrl(e),{...t,headers:i}),n=await s.text(),o={};try{o=n?JSON.parse(n):{}}catch{o={}}if(!s.ok||o?.error)throw new k(...m("Instagram API",s,n));return o}}import{fetchPublicUrl as _t}from"@stacksjs/security";var Tt=10485760;function Le(e){if(e.length>=3&&e[0]===255&&e[1]===216&&e[2]===255)return"image/jpeg";if(e.length>=8&&e[0]===137&&e[1]===80&&e[2]===78&&e[3]===71)return"image/png";if(e.length>=6&&e[0]===71&&e[1]===73&&e[2]===70&&e[3]===56)return"image/gif";if(e.length>=12&&e[0]===82&&e[1]===73&&e[2]===70&&e[3]===70&&e[8]===87&&e[9]===69&&e[10]===66&&e[11]===80)return"image/webp";return null}async function A(e,t={}){try{let r=await _t(e,{},{allowHttp:!0,timeoutMs:15000,maxBytes:Tt,...t});if(!r.ok)return null;let i=new Uint8Array(await r.arrayBuffer()),s=Le(i);return s?{bytes:i,mimeType:s}:null}catch{return null}}class De extends Error{url;status=422;body="";constructor(e){super(`Could not read the image at ${e}.`);this.url=e;this.name="PostImageError"}}async function C(e,t){if(e.bytes?.length)return{bytes:e.bytes,mimeType:e.mimeType||Le(e.bytes)||"image/jpeg"};if(!e.url)return;let r=await t(e.url);if(!r)throw new De(e.url);return r}var Be="202611";function At(e){let t=Number(e.slice(0,4)),r=Number(e.slice(4,6));return new Date(Date.UTC(t+1,r-1,15))}function Ct(e,t=Date.now()){let r=String(e??"").trim();if(!/^\d{6}$/.test(r))return Be;return At(r).getTime()>t?r:Be}var Rt=20,Ut=4086,Et=["ADMINISTRATOR","DIRECT_SPONSORED_CONTENT_POSTER","CONTENT_ADMINISTRATOR","CONTENT_ADMIN"],R="2.0.0";class f extends y{constructor(e,t,r,i={}){super("linkedin",e,t,r,i);this.name="LinkedInApiError"}get isAuthError(){return this.status===401||this.status===403}}class de{provider="linkedin";characterLimit=3000;maxImages=Rt;fetchImage=A;organizationPageSize=100;apiVersion;authBase;apiBase;constructor(e={}){this.apiVersion=Ct(e.apiVersion),this.authBase=e.authBase||"https://www.linkedin.com",this.apiBase=e.apiBase||"https://api.linkedin.com"}getAuthUrl(e){let t=new URLSearchParams({response_type:"code",client_id:e.clientId,redirect_uri:e.redirectUrl,scope:e.scopes.join(" "),state:e.state});return`${this.authBase}/oauth/v2/authorization?${t.toString()}`}async exchangeCode(e){let t=new URLSearchParams({grant_type:"authorization_code",code:e.code,redirect_uri:e.redirectUrl,client_id:e.clientId,client_secret:e.clientSecret});return this.tokenRequest(t,"LinkedIn did not return an access token.")}async refreshAccessToken(e){return this.tokenRequest(new URLSearchParams({grant_type:"refresh_token",refresh_token:e.refreshToken,client_id:e.clientId,client_secret:e.clientSecret}),"LinkedIn did not return a refreshed access token.")}async tokenRequest(e,t){let r=await this.request(`${this.authBase}/oauth/v2/accessToken`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:e.toString()});if(!r.access_token)throw new f(t,400,JSON.stringify(r));return{accessToken:r.access_token,expiresIn:r.expires_in,scope:r.scope,refreshToken:r.refresh_token,refreshTokenExpiresIn:r.refresh_token_expires_in}}async getProfile(e){if(!e)throw Error("LinkedIn access token is required.");let t=await this.request(`${this.apiBase}/v2/userinfo`,{headers:{authorization:`Bearer ${e}`}});if(!t.sub)throw new f("LinkedIn profile is missing a subject id.",400,JSON.stringify(t));return{sub:t.sub,name:t.name,picture:t.picture}}async uploadImage(e,t,r,i){let s=await this.request(`${this.apiBase}/rest/images?action=initializeUpload`,{method:"POST",headers:{authorization:`Bearer ${e}`,"content-type":"application/json","linkedin-version":this.apiVersion,"x-restli-protocol-version":R},body:JSON.stringify({initializeUploadRequest:{owner:t}})}),n=s.value?.uploadUrl,o=s.value?.image;if(!n||!o)throw new f("LinkedIn did not return an image upload URL.",400,JSON.stringify(s));let a=await fetch(n,{method:"PUT",headers:{authorization:`Bearer ${e}`,"content-type":i||"image/jpeg"},body:new Uint8Array(r)});if(!a.ok){let c=await a.text().catch(()=>"");throw new f(...m("LinkedIn image upload",a,c))}return o}async publish(e,t){if(!e.accessToken)throw Error("LinkedIn access token is missing for this identity.");let r=e.did;if(!r)throw Error("LinkedIn author URN is required to publish.");if(b("linkedin",t.text,this.characterLimit))throw Error(`LinkedIn posts must be ${this.characterLimit} characters or fewer.`);let i=[];for(let c of(t.media??[]).slice(0,this.maxImages)){let u=await C(c,(p)=>this.fetchImage(p));if(!u)continue;let d=await this.uploadImage(e.accessToken,r,u.bytes,u.mimeType),l=c.altText?.trim();i.push({id:d,...l?{altText:l.slice(0,Ut)}:{}})}let s={author:r,commentary:$t(t.text),visibility:"PUBLIC",distribution:{feedDistribution:"MAIN_FEED",targetEntities:[],thirdPartyDistributionChannels:[]},lifecycleState:"PUBLISHED",isReshareDisabledByAuthor:!1};if(i.length===1)s.content={media:i[0]};else if(i.length>1)s.content={multiImage:{images:i}};else if(t.external)s.content={article:{source:t.external.uri,title:t.external.title,description:t.external.description||""}};let n=await fetch(`${this.apiBase}/rest/posts`,{method:"POST",headers:{authorization:`Bearer ${e.accessToken}`,"content-type":"application/json","linkedin-version":this.apiVersion,"x-restli-protocol-version":R},body:JSON.stringify(s)}),o=await n.text();if(!n.ok)throw new f(...m("LinkedIn API",n,o));let a=n.headers.get("x-restli-id")||n.headers.get("x-linkedin-id")||"";return{provider:this.provider,uri:a,url:a?`https://www.linkedin.com/feed/update/${a}`:void 0}}async timeline(e,t={}){return{items:[]}}async listAuthoredPosts(e,t={}){if(!e.accessToken)throw Error("LinkedIn access token is missing for this identity.");let r=e.did;if(!r)throw Error("LinkedIn author URN is required to list posts.");let i=r.startsWith("urn:li:organization:")?"r_organization_social":"r_member_social",s=Math.min(Math.max(t.limit||50,1),100),n=Number(t.cursor||0)||0,o=new URL(`${this.apiBase}/rest/posts`);o.searchParams.set("q","author"),o.searchParams.set("author",r),o.searchParams.set("count",String(s)),o.searchParams.set("start",String(n));let a;try{a=await this.request(o.toString(),{headers:{authorization:`Bearer ${e.accessToken}`,"linkedin-version":this.apiVersion,"x-restli-protocol-version":R}})}catch(u){if(u instanceof f&&(u.status===401||u.status===403))throw new f(`LinkedIn will not list this account's posts - the Posts author finder needs the ${i} permission, which this app does not hold.`,u.status,u.body);throw u}let c=(a.elements||[]).filter((u)=>u?.id).map((u)=>({uri:String(u.id),text:u.commentary,postedAt:u.createdAt?new Date(u.createdAt).toISOString():void 0,url:`https://www.linkedin.com/feed/update/${u.id}`}));return{cursor:c.length===s?String(n+s):void 0,posts:c}}async metrics(e,t){if(!e.accessToken)throw Error("LinkedIn access token is missing for this identity.");let r=String(e.did||"").startsWith("urn:li:organization:")?"r_organization_social_feed":"r_member_social_feed",i=[...new Set(t.map((n)=>String(n||"").trim()).filter(Boolean))],s=[];for(let n=0;n<i.length;n+=20){let o=i.slice(n,n+20),a=`${this.apiBase}/rest/socialMetadata?ids=List(${o.map((d)=>encodeURIComponent(d)).join(",")})`,c;try{c=await this.request(a,{headers:{authorization:`Bearer ${e.accessToken}`,"linkedin-version":this.apiVersion,"x-restli-protocol-version":R}})}catch(d){if(d instanceof f&&d.status===403)throw new f(`LinkedIn will not show this account's reactions and comments - that needs the ${r} permission, which this app does not hold.`,d.status,d.body,d.retryAfterMs===void 0?{}:{retryAfterMs:d.retryAfterMs});throw d}let u=c.results||{};for(let d of o){let l=u[d]??u[encodeURIComponent(d)];if(!l)continue;let p=Object.values(l.reactionSummaries||{}).reduce((g,P)=>g+(Number(P?.count)||0),0);s.push({uri:d,likes:p,...typeof l.commentSummary?.count==="number"?{replies:l.commentSummary.count}:{}})}}return s}async listOrganizations(e){if(!e)throw Error("LinkedIn access token is required to list organizations.");let t={authorization:`Bearer ${e}`,"linkedin-version":this.apiVersion,"x-restli-protocol-version":R},r=new Map,i=Math.max(1,this.organizationPageSize);for(let n=0,o=0;o<50;n+=i,o++){let a=new URL(`${this.apiBase}/rest/organizationAcls`);a.searchParams.set("q","roleAssignee"),a.searchParams.set("state","APPROVED"),a.searchParams.set("start",String(n)),a.searchParams.set("count",String(i));let c;try{c=await this.request(a.toString(),{headers:t})}catch(l){if(l instanceof f&&(l.status===401||l.status===403))throw new f("LinkedIn will not list this member's Pages - that needs the rw_organization_admin (or r_organization_admin) permission, which this token does not hold.",l.status,l.body);throw l}let u=c.elements||[];for(let l of u){let p=l.organizationTarget||l.organization,g=l.role||"";if(!p?.startsWith("urn:li:organization:")||!Et.includes(g)||r.has(p))continue;r.set(p,{urn:p,id:p.slice(20),role:g})}let d=c.paging?.total;if(u.length<i||typeof d==="number"&&n+i>=d)break}let s=[...r.values()];for(let n of s){let o=await this.request(`${this.apiBase}/rest/organizations/${encodeURIComponent(n.id)}`,{headers:t}).then((a)=>a.localizedName,()=>{return});if(o)n.name=o}return s}async deletePost(e,t){if(!e.accessToken)throw Error("LinkedIn access token is missing for this identity.");let r=String(t.uri||"").trim();if(!r)throw Error("A LinkedIn post URN is required to delete a post.");let i=await fetch(`${this.apiBase}/rest/posts/${encodeURIComponent(r)}`,{method:"DELETE",headers:{authorization:`Bearer ${e.accessToken}`,"linkedin-version":this.apiVersion,"x-restli-protocol-version":R}});if(!i.ok&&i.status!==404){let s=await i.text().catch(()=>"");throw new f(...m("LinkedIn API",i,s))}}async request(e,t){let r=await fetch(e,t),i=await r.text();if(!r.ok)throw new f(...m("LinkedIn API",r,i));return i?JSON.parse(i):{}}}function $t(e){return e.replace(/[\\|{}@[\]()<>#*_~]/g,(t,r)=>{if(t==="#"&&Ot(e,r))return t;return`\\${t}`})}function Ot(e,t){let r=t===0?"":e[t-1];if(r&&/[\p{L}\p{N}_#&/]/u.test(r))return!1;let i=/^[\p{L}\p{N}_]+/u.exec(e.slice(t+1))?.[0];return Boolean(i&&/\p{L}/u.test(i))}function Me(e){return e instanceof pe&&e.status===404}class pe extends y{constructor(e,t,r,i={}){super("mastodon",e,t,r,i);this.name="MastodonApiError"}get isAuthError(){return this.status===401||this.status===403}}var U={characters:500,charactersPerUrl:23,mediaAttachments:4},Lt=3600000,Dt=60000;function Bt(e){if(!e)return null;let t=Number(e.max_options),r=Number(e.max_characters_per_option),i=Number(e.min_expiration),s=Number(e.max_expiration);if(![t,r,i,s].every((n)=>Number.isSafeInteger(n)&&n>0)||t<2||s<i)return null;return{maxOptions:t,maxCharactersPerOption:r,minExpiration:i,maxExpiration:s}}function Mt(e,t){if(!t)throw Error("The Mastodon instance did not report its poll limits.");if(!Array.isArray(e.options)||e.options.some((i)=>typeof i!=="string"||!i.trim()))throw Error("Each poll option needs text.");let r=e.options.map((i)=>i.trim());if(r.length<2||r.length>t.maxOptions)throw Error(`This Mastodon instance allows between 2 and ${t.maxOptions} poll options.`);if(r.some((i)=>F(i)>t.maxCharactersPerOption))throw Error(`Each poll option can have up to ${t.maxCharactersPerOption} characters.`);if(new Set(r).size!==r.length)throw Error("Poll options must be distinct.");if(!Number.isSafeInteger(e.expiresIn)||e.expiresIn<t.minExpiration||e.expiresIn>t.maxExpiration)throw Error(`This Mastodon instance allows poll durations between ${t.minExpiration} and ${t.maxExpiration} seconds.`);return{options:r,expires_in:e.expiresIn,multiple:e.multiple===!0,hide_totals:e.hideTotals===!0}}function ue(e){let t=typeof e==="string"?URL.parse(e):null;if(!t||t.protocol!=="https:"||t.username||t.password)return null;return t.hash="",t.href}function Nt(e){let t=String(e||"").trim().replace(/\/+$/,"");if(!t)throw Error("Mastodon instance URL is required.");let r=/^https?:\/\//i.test(t)?t:`https://${t}`;try{let i=new URL(r);return`${i.protocol}//${i.host}`}catch{throw Error("Mastodon instance URL is invalid.")}}class he{provider="mastodon";characterLimit=U.characters;fetchImage=A;limits=new Map;async instanceLimits(e){let t=this.instanceOf(e),r=this.limits.get(t);if(r&&Date.now()<r.expires)return r.value;try{let i=await fetch(`${t}/api/v2/instance`,{signal:AbortSignal.timeout(5000)});if(!i.ok)throw Error(`HTTP ${i.status}`);let s=await i.json(),n=s.configuration?.statuses??{},o=(d,l)=>Number(d)>0?Math.floor(Number(d)):l,a=Bt(s.configuration?.polls),c=Number(s.api_versions?.mastodon)>=7,u={...a&&{poll:a},...c&&{quotePosts:!0},characters:o(n.max_characters,U.characters),charactersPerUrl:o(n.characters_reserved_per_url,U.charactersPerUrl),mediaAttachments:o(n.max_media_attachments,U.mediaAttachments)};return this.limits.set(t,{value:u,expires:Date.now()+Lt}),u}catch{return this.limits.set(t,{value:U,expires:Date.now()+Dt}),U}}instanceOf(e){return Nt(e.did||"")}tokenOf(e){if(!e.accessToken)throw Error("Mastodon access token is missing for this identity.");return e.accessToken}async verifyCredentials(e){let t=await this.request(`${this.instanceOf(e)}/api/v1/accounts/verify_credentials`,{headers:{authorization:`Bearer ${this.tokenOf(e)}`}});return{accountId:t.id,username:t.username,displayName:t.display_name||void 0,url:t.url}}async resolvePostId(e,t){let r=ue(t);if(!r)throw Error("Enter an HTTPS link to a Mastodon post.");let i=new URL("/api/v2/search",this.instanceOf(e));i.search=new URLSearchParams({q:r,type:"statuses",resolve:"true",limit:"1"}).toString();let n=(await this.request(i.href,{headers:{authorization:`Bearer ${this.tokenOf(e)}`},redirect:"error",signal:AbortSignal.timeout(15000)})).statuses?.find((o)=>ue(o.url)===r||ue(o.uri)===r);if(!n||!/^[0-9]{1,32}$/.test(n.id))throw Error("The Mastodon instance could not find the post at this link.");return n.id}async uploadMedia(e,t,r,i){let s=new FormData;if(s.set("file",new Blob([new Uint8Array(t)],{type:r||"image/jpeg"}),"upload"),i?.trim())s.set("description",i.trim().slice(0,1500));return(await this.request(`${this.instanceOf(e)}/api/v2/media`,{method:"POST",headers:{authorization:`Bearer ${this.tokenOf(e)}`},body:s})).id}async publish(e,t,r={}){let i=this.instanceOf(e),s=this.tokenOf(e),n=await this.instanceLimits(e);if(b("mastodon",t.text,n.characters,{linkLength:n.charactersPerUrl}))throw Error(`Mastodon posts on this instance must be ${n.characters} characters or fewer.`);if((r.poll||r.quotedStatusId!==void 0)&&t.media?.length)throw Error("Mastodon does not allow images with a poll or a quote.");if(r.poll&&r.quotedStatusId!==void 0)throw Error("Choose a poll or a quoted post on Mastodon.");if(r.quotedStatusId!==void 0){if(!n.quotePosts)throw Error("This Mastodon instance does not advertise quote posts.");if(!/^[0-9]{1,32}$/.test(r.quotedStatusId))throw Error("Choose a valid Mastodon status to quote.")}let o=r.poll?Mt(r.poll,n.poll):void 0,a=[];for(let p of(t.media||[]).slice(0,n.mediaAttachments)){let g=await C(p,(P)=>this.fetchImage(P));if(g)a.push(await this.uploadMedia(e,g.bytes,g.mimeType,p.altText))}let c={status:t.text,visibility:r.visibility??"public"};if(a.length)c.media_ids=a;if(o)c.poll=o;if(r.quotedStatusId!==void 0)c.quoted_status_id=r.quotedStatusId;if(t.reply?.parent?.uri)c.in_reply_to_id=t.reply.parent.uri;if(r.spoilerText?.trim())c.spoiler_text=r.spoilerText.trim();let u=r.language??t.langs?.[0];if(u)c.language=u;let d={authorization:`Bearer ${s}`,"content-type":"application/json"};if(r.idempotencyKey)d["idempotency-key"]=r.idempotencyKey;let l=await this.request(`${i}/api/v1/statuses`,{method:"POST",headers:d,body:JSON.stringify(c)});return{provider:this.provider,uri:l.id,cid:l.id,url:l.url||l.uri}}async timeline(e,t={}){return{items:[]}}async listAuthoredPosts(e,t={}){let r=this.instanceOf(e),{accountId:i}=await this.verifyCredentials(e),s=new URL(`${r}/api/v1/accounts/${encodeURIComponent(i)}/statuses`);if(s.searchParams.set("limit",String(Math.min(Math.max(t.limit||40,1),40))),s.searchParams.set("exclude_reblogs","true"),t.cursor)s.searchParams.set("max_id",t.cursor);let o=(await this.request(s.toString(),{headers:{authorization:`Bearer ${this.tokenOf(e)}`}})||[]).filter((a)=>a?.id).map((a)=>({uri:a.id,cid:a.id,text:a.content,postedAt:a.created_at,url:a.url}));return{cursor:o.length?o[o.length-1]?.uri:void 0,posts:o}}async deletePost(e,t){let r=String(t.cid||Ne(t.uri)||"").trim();if(!r)throw Error("A status id is required to delete a post.");await this.request(`${this.instanceOf(e)}/api/v1/statuses/${encodeURIComponent(r)}`,{method:"DELETE",headers:{authorization:`Bearer ${this.tokenOf(e)}`}})}async metrics(e,t){let r=this.instanceOf(e),i={authorization:`Bearer ${this.tokenOf(e)}`},s=new Map;for(let a of t){let c=String(Ne(a)||"").trim();if(c)s.set(c,a)}let n=[...s.keys()],o=[];for(let a=0;a<n.length;a+=40){let c=n.slice(a,a+40);try{o.push(...await this.request(`${r}/api/v1/statuses?${c.map((u)=>`id[]=${encodeURIComponent(u)}`).join("&")}`,{headers:i}))}catch(u){if(!Me(u))throw u;for(let d of c)try{o.push(await this.request(`${r}/api/v1/statuses/${encodeURIComponent(d)}`,{headers:i}))}catch(l){if(!Me(l))throw l}}}return o.flatMap((a)=>{let c=s.get(String(a.id));if(c===void 0)return[];return[{uri:c,likes:a.favourites_count??0,reposts:a.reblogs_count??0,replies:a.replies_count??0,...typeof a.quotes_count==="number"?{quotes:a.quotes_count}:{}}]})}async request(e,t){let r=await fetch(e,t),i=await r.text();if(!r.ok)throw new pe(...m("Mastodon API",r,i));return i?JSON.parse(i):{}}}function Ne(e){return String(e||"").replace(/\/+$/,"").split("/").pop()||""}var qt=20,zt=1000,qe={views:"views",likes:"likes",replies:"replies",reposts:"reposts",quotes:"quotes",shares:"shares"},Ft=Object.keys(qe);class v extends y{constructor(e,t,r,i={}){super("threads",e,t,r,i);this.name="ThreadsApiError"}get isAuthError(){return this.status===401||this.status===403||this.status===190}}class ge{provider="threads";characterLimit=500;maxImages=qt;graphVersion;authBase;graphBase;constructor(e={}){this.graphVersion=e.graphVersion||"v1.0",this.authBase=e.authBase||"https://threads.net",this.graphBase=e.graphBase||"https://graph.threads.net"}getAuthUrl(e){let t=new URLSearchParams({client_id:e.clientId,redirect_uri:e.redirectUrl,scope:e.scopes.join(","),response_type:"code",state:e.state});return`${this.authBase}/oauth/authorize?${t.toString()}`}async exchangeCode(e){let t=await fetch(`${this.graphBase}/oauth/access_token`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:e.clientId,client_secret:e.clientSecret,grant_type:"authorization_code",redirect_uri:e.redirectUrl,code:e.code}).toString()}),r=await t.text(),i={};try{i=r?JSON.parse(r):{}}catch{i={}}if(!t.ok||i?.error||!i?.access_token)throw new v(...m("Threads token exchange",t,r));return{accessToken:i.access_token,userId:i.user_id!=null?String(i.user_id):void 0,expiresIn:i.expires_in}}async resolveAccount(e){let t=new URLSearchParams({fields:"id,username"}),r=await this.graph(`/me?${t.toString()}`,{method:"GET"},e);if(!r.id)throw new v("Could not resolve the Threads account for this token.",400,JSON.stringify(r));return{threadsUserId:r.id,username:r.username,accessToken:e}}async exchangeLongLivedToken(e,t){return this.tokenRequest("/access_token",new URLSearchParams({grant_type:"th_exchange_token",client_secret:e,access_token:t}))}async refreshLongLivedToken(e){return this.tokenRequest("/refresh_access_token",new URLSearchParams({grant_type:"th_refresh_token",access_token:e}))}async publish(e,t){if(!e.accessToken)throw Error("Threads access token is missing for this identity.");let r=e.did;if(!r)throw Error("Threads account id is required to publish.");if(b("threads",t.text,this.characterLimit))throw Error(`Threads posts must be ${this.characterLimit} characters or fewer.`);let i=(t.media??[]).slice(0,this.maxImages);if(i.some((p)=>!p.url))throw new v("Threads fetches images from a public address, and this image has none.",422,"");let s=e.accessToken,n=async(p)=>{let g=await this.graph(`/${r}/threads`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams(p).toString()},s);if(!g.id)throw new v("Threads did not return a media container id.",400,JSON.stringify(g));return g.id},o=t.reply?.parent?.uri,a={text:t.text,...o?{reply_to_id:o}:{}},c=(p)=>({media_type:"IMAGE",image_url:p.url,...p.altText?.trim()?{alt_text:p.altText.trim().slice(0,zt)}:{}}),u;if(i.length>1){let p=[];for(let g of i)p.push(await n({...c(g),is_carousel_item:"true"}));u=await n({media_type:"CAROUSEL",children:p.join(","),...a})}else if(i.length===1)u=await n({...c(i[0]),...a});else u=await n({media_type:"TEXT",...a});let d=await this.graph(`/${r}/threads_publish`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({creation_id:u}).toString()},s);if(!d.id)throw new v("Threads did not return a published post id.",400,JSON.stringify(d));let l=await this.graph(`/${d.id}?fields=permalink`,{method:"GET"},s).catch(()=>{return});return{provider:this.provider,uri:d.id,cid:d.id,url:l?.permalink}}async deletePost(e,t){if(!e.accessToken)throw Error("Threads access token is missing for this identity.");if(!/^\w+$/.test(t.uri))throw Error(`Threads post id "${t.uri}" is not an id.`);await this.graph(`/${t.uri}`,{method:"DELETE"},e.accessToken)}async timeline(e,t={}){return{items:[]}}async tokenRequest(e,t){let r=await fetch(`${this.graphBase}${e}`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:t.toString()}),i=await r.text(),s={};try{s=i?JSON.parse(i):{}}catch{s={}}if(!r.ok||s?.error||!s?.access_token)throw new v(...m("Threads token request",r,i));return{accessToken:s.access_token,expiresIn:s.expires_in}}async metrics(e,t){let r=e.accessToken;if(!r)throw Error("Threads access token is missing for this identity.");let i=[];for(let s of t){let n=String(s||"").trim();if(!n)continue;let o;try{o=await this.graph(`/${encodeURIComponent(n)}/insights?metric=${Ft.join(",")}`,{method:"GET"},r)}catch(c){if(c instanceof v&&K(c))continue;throw c}let a={uri:s};for(let c of o.data||[]){let u=qe[String(c.name)],d=Number(c.values?.[0]?.value);if(u&&Number.isFinite(d))a[u]=d}i.push(a)}return i}async graph(e,t,r){let i=new Headers(t.headers);if(r)i.set("authorization",`Bearer ${r}`);let s=await fetch(`${this.graphBase}/${this.graphVersion}${e}`,{...t,headers:i}),n=await s.text(),o={};try{o=n?JSON.parse(n):{}}catch{o={}}if(!s.ok||o?.error)throw new v(...m("Threads API",s,n));return o}}import{Buffer as Ht}from"buffer";import{fetcher as ze}from"@stacksjs/api";import{config as W}from"@stacksjs/config";class me extends w{baseUrl="https://twitter.com";apiUrl="https://api.twitter.com";_usesPKCE=!0;getConfig(){let e={clientId:this.clientId||(W.services.twitter?.clientId??""),clientSecret:this.clientSecret||(W.services.twitter?.clientSecret??""),redirectUrl:this.redirectUrl||(W.services.twitter?.redirectUrl??""),scopes:W.services.twitter?.scopes??["users.read","tweet.read"]};return this.setScopes(e.scopes),e}async getAuthUrl(){let e=this.resolveState(),{clientId:t,redirectUrl:r,scopes:i}=this.getConfig();return this.validateConfig(),`${this.baseUrl}/i/oauth2/authorize?${new URLSearchParams({client_id:t,redirect_uri:r,scope:i.join(" "),response_type:"code",...this.parameters,...await this.pkceFields(),state:e}).toString()}`}async getAccessToken(e){let{clientId:t,clientSecret:r,redirectUrl:i}=this.getConfig();this.validateConfig();let s=this.pkceTokenFields(),n=Ht.from(`${t}:${r}`).toString("base64"),o=await ze.asForm().withHeaders({Authorization:`Basic ${n}`}).post(`${this.apiUrl}/2/oauth2/token`,{code:e,grant_type:"authorization_code",redirect_uri:i,...s});if(o.data.error)throw Error(`Twitter OAuth error: ${o.data.error_description}`);return o.data.access_token}async getUserByToken(e){let t=await ze.withHeaders({Authorization:`Bearer ${e}`}).get(`${this.apiUrl}/2/users/me?user.fields=profile_image_url`);return{id:t.data.id,nickname:t.data.username,name:t.data.name,email:t.data.email??null,avatar:t.data.profile_image_url??null,token:e,raw:t.data}}validateConfig(){let{clientId:e,clientSecret:t,redirectUrl:r}=this.getConfig();if(!e)throw new h("Twitter client ID not provided");if(!t)throw new h("Twitter client secret not provided");if(!r)throw new h("Twitter redirect URL not provided")}getTokenUrl(){return`${this.apiUrl}/2/oauth2/token`}}class I extends y{constructor(e,t,r,i={}){super("twitter",e,t,r,i);this.name="TwitterApiError"}get isAuthError(){return this.status===401||this.status===403}}var jt=4,Vt=1000;function Fe(e){let t="";for(let r of e)t+=String.fromCharCode(r);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}class E{provider="twitter";characterLimit=280;maxImages=jt;fetchImage=A;apiBase;authorizeBase;constructor(e={}){this.apiBase=e.apiBase||"https://api.twitter.com",this.authorizeBase=e.authorizeBase||"https://twitter.com"}async createAuthorization(e){let t=Fe(crypto.getRandomValues(new Uint8Array(32))),r=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t)),i=Fe(new Uint8Array(r)),s=new URLSearchParams({response_type:"code",client_id:e.clientId,redirect_uri:e.redirectUrl,scope:e.scopes.join(" "),state:e.state,code_challenge:i,code_challenge_method:"S256"});return{url:`${this.authorizeBase}/i/oauth2/authorize?${s.toString()}`,codeVerifier:t}}async exchangeCode(e){return this.tokenRequest(new URLSearchParams({grant_type:"authorization_code",code:e.code,redirect_uri:e.redirectUrl,code_verifier:e.codeVerifier,client_id:e.clientId}),e.clientId,e.clientSecret)}async refreshAccessToken(e){return this.tokenRequest(new URLSearchParams({grant_type:"refresh_token",refresh_token:e.refreshToken,client_id:e.clientId}),e.clientId,e.clientSecret)}async getProfile(e){let t=await this.request(`${this.apiBase}/2/users/me?user.fields=username,name`,{headers:{authorization:`Bearer ${e}`}});if(!t.data?.id||!t.data.username)throw new I("Twitter did not return the authenticated user.",400,JSON.stringify(t));return{id:t.data.id,username:t.data.username,name:t.data.name}}async uploadMedia(e,t,r){let i=new FormData;i.set("media",new Blob([new Uint8Array(t)],{type:r||"image/jpeg"})),i.set("media_category","tweet_image");let s=await this.request(`${this.apiBase}/2/media/upload`,{method:"POST",headers:{authorization:`Bearer ${e}`},body:i}),n=s.data?.id||s.media_id_string||s.id;if(!n)throw new I("Twitter did not return a media id.",400,JSON.stringify(s));return n}async describeMedia(e,t,r){try{return await this.request(`${this.apiBase}/2/media/metadata`,{method:"POST",headers:{authorization:`Bearer ${e}`,"content-type":"application/json"},body:JSON.stringify({id:t,metadata:{alt_text:{text:r.slice(0,Vt)}}})}),!0}catch{return!1}}async publish(e,t){if(!e.accessToken)throw Error("Twitter access token is missing for this identity.");if(b("twitter",t.text,this.characterLimit))throw Error(`Twitter posts must be ${this.characterLimit} characters or fewer.`);let r=[],i=[];for(let a of(t.media??[]).slice(0,this.maxImages)){let c=await C(a,(l)=>this.fetchImage(l));if(!c)continue;let u=await this.uploadMedia(e.accessToken,c.bytes,c.mimeType),d=a.altText?.trim();if(d&&!await this.describeMedia(e.accessToken,u,d))i.push(`X did not take the description for image ${r.length+1}.`);r.push(u)}let s={text:t.text};if(r.length)s.media={media_ids:r};if(t.reply?.parent?.uri)s.reply={in_reply_to_tweet_id:t.reply.parent.uri};let n=await this.request(`${this.apiBase}/2/tweets`,{method:"POST",headers:{authorization:`Bearer ${e.accessToken}`,"content-type":"application/json"},body:JSON.stringify(s)}),o=n.data?.id;if(!o)throw new I("Twitter did not return a tweet id.",400,JSON.stringify(n));return{provider:this.provider,uri:o,cid:o,url:e.handle?`https://x.com/${e.handle}/status/${o}`:`https://x.com/i/web/status/${o}`,...i.length?{warnings:i}:{}}}async timeline(e,t={}){return{items:[]}}async listAuthoredPosts(e,t={}){if(!e.accessToken)throw Error("Twitter access token is missing for this identity.");let r=e.did;if(!r)throw Error("Twitter user id is required to list posts.");let i=new URL(`${this.apiBase}/2/users/${encodeURIComponent(r)}/tweets`);if(i.searchParams.set("max_results",String(Math.min(Math.max(t.limit||100,5),100))),i.searchParams.set("tweet.fields","created_at"),t.cursor)i.searchParams.set("pagination_token",t.cursor);let s=await this.request(i.toString(),{headers:{authorization:`Bearer ${e.accessToken}`}});return{cursor:s.meta?.next_token,posts:(s.data||[]).filter((n)=>n?.id).map((n)=>({uri:n.id,cid:n.id,text:n.text,postedAt:n.created_at,url:`https://x.com/i/web/status/${n.id}`}))}}async metrics(e,t){let r=[...new Set(t.filter((n)=>/^[0-9]{1,19}$/.test(n)))];if(!r.length)return[];if(!e.accessToken)throw Error("Twitter access token is missing for this identity.");let i=[],s={authorization:`Bearer ${e.accessToken}`};for(let n=0;n<r.length;n+=100){let o=r.slice(n,n+100),a=new URLSearchParams({ids:o.join(","),"tweet.fields":"public_metrics"}),c=await this.request(`${this.apiBase}/2/tweets?${a}`,{headers:s}),u=new Set(o);for(let d of c.data??[]){let l=d.public_metrics;if(!l||!u.delete(d.id))continue;let p={likes:l.like_count,replies:l.reply_count,reposts:l.repost_count??l.retweet_count,quotes:l.quote_count,views:l.impression_count,saves:l.bookmark_count},g=Object.entries(p).filter(([,P])=>typeof P==="number"&&Number.isSafeInteger(P)&&P>=0);if(g.length)i.push({uri:d.id,...Object.fromEntries(g)})}}return i}async deletePost(e,t){if(!e.accessToken)throw Error("Twitter access token is missing for this identity.");let r=String(t.uri||"").trim();if(!r)throw Error("A tweet id is required to delete a post.");let i=await this.request(`${this.apiBase}/2/tweets/${encodeURIComponent(r)}`,{method:"DELETE",headers:{authorization:`Bearer ${e.accessToken}`}});if(i.data&&i.data.deleted===!1)throw new I(`X refused to delete tweet ${r}.`,400,JSON.stringify(i))}async tokenRequest(e,t,r){let i={"content-type":"application/x-www-form-urlencoded"};if(r)i.authorization=`Basic ${btoa(`${t}:${r}`)}`;let s=await this.request(`${this.apiBase}/2/oauth2/token`,{method:"POST",headers:i,body:e.toString()});if(!s.access_token)throw new I("Twitter did not return an access token.",400,JSON.stringify(s));return{accessToken:s.access_token,refreshToken:s.refresh_token,expiresIn:s.expires_in,scope:s.scope}}async request(e,t){let r=await fetch(e,t),i=await r.text();if(!r.ok)throw new I(...m("Twitter API",r,i));return i?JSON.parse(i):{}}}import{Buffer as Gt}from"buffer";class B extends Error{code;status;constructor(e,t){super(`Stacks issuer refused the request: ${e}`);this.code=e;this.status=t;this.name="StacksIssuerError"}}class Jt extends w{scopeSeparator=" ";settings;constructor(e){super(e);this.settings=e,this._scopes=e.scopes?.length?[...e.scopes]:[],this._usesPKCE=!0}endpoint(e){return(e==="authorize"?this.settings.authorizeUrl:e==="token"?this.settings.tokenUrl:this.settings.revokeUrl)||`${this.settings.issuer.replace(/\/+$/,"")}/${e}`}resources(){let e=this.settings.resource;return e==null?[]:Array.isArray(e)?e:[e]}validateConfig(){if(!this.settings.issuer)throw new h("Stacks issuer not provided");if(!this.clientId)throw new h("Stacks issuer client ID not provided");if(!this.clientSecret)throw new h("Stacks issuer client secret not provided");if(!this.redirectUrl)throw new h("Stacks issuer redirect URL not provided");if(!this.settings.userInfoUrl)throw new h("Stacks issuer userinfo URL not provided")}getTokenUrl(){return this.endpoint("token")}async getAuthUrl(){this.validateConfig();let e=new URLSearchParams({client_id:this.clientId,redirect_uri:this.redirectUrl,response_type:"code",scope:this.formatScopes(this.getScopes(),this.scopeSeparator),state:this.resolveState(),...await this.pkceFields()});for(let t of this.resources())e.append("resource",t);for(let[t,r]of Object.entries(this.parameters))e.set(t,String(r));return`${this.endpoint("authorize")}?${e.toString()}`}async post(e,t){let r=await fetch(e,{method:"POST",headers:{Authorization:`Basic ${Gt.from(`${encodeURIComponent(this.clientId)}:${encodeURIComponent(this.clientSecret)}`).toString("base64")}`,"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:t.toString()}),i=await r.json().catch(()=>({}));if(!r.ok)throw new B(typeof i.error==="string"?i.error:"server_error",r.status);return i}tokens(e){if(typeof e.access_token!=="string"||!e.access_token)throw new B("invalid_token_response",502);return{accessToken:e.access_token,refreshToken:typeof e.refresh_token==="string"?e.refresh_token:null,expiresIn:typeof e.expires_in==="number"?e.expires_in:null,scopes:typeof e.scope==="string"?e.scope.split(" ").filter(Boolean):[]}}async getTokens(e){this.validateConfig();let t=new URLSearchParams({grant_type:"authorization_code",code:e,redirect_uri:this.redirectUrl,...this.pkceTokenFields()});for(let r of this.resources())t.append("resource",r);return this.tokens(await this.post(this.endpoint("token"),t))}async getAccessToken(e){return(await this.getTokens(e)).accessToken}async refreshTokens(e){this.validateConfig();let t=new URLSearchParams({grant_type:"refresh_token",refresh_token:e});for(let r of this.resources())t.append("resource",r);return this.tokens(await this.post(this.endpoint("token"),t))}async revokeToken(e,t="refresh_token"){this.validateConfig(),await this.post(this.endpoint("revoke"),new URLSearchParams({token:e,token_type_hint:t}))}async getClaims(e){this.validateConfig();let t=await fetch(this.settings.userInfoUrl,{headers:{Authorization:`Bearer ${e}`,Accept:"application/json"}}),r=await t.json().catch(()=>({}));if(!t.ok)throw new B(typeof r.error==="string"?r.error:"invalid_token",t.status);if(typeof r.sub!=="string"||!r.sub)throw new B("invalid_userinfo",502);return r}async getUserByToken(e){let t=await this.getClaims(e),r=typeof t.email==="string"?t.email:null;return{id:String(t.sub),nickname:typeof t.preferred_username==="string"?t.preferred_username:null,name:typeof t.name==="string"&&t.name?t.name:r??"",email:r,emailVerified:typeof t.email_verified==="boolean"?t.email_verified:null,avatar:typeof t.picture==="string"?t.picture:null,token:e,raw:t}}}import{config as Kt}from"@stacksjs/config";var Y=["clientId","clientSecret","redirectUrl"],M=Object.freeze({google:{name:"google",label:"Google",driver:ce,required:Y,postCallback:!1,pkce:!1,nonce:!1},github:{name:"github",label:"GitHub",driver:ae,required:Y,postCallback:!1,pkce:!1,nonce:!1},facebook:{name:"facebook",label:"Facebook",driver:ne,required:Y,postCallback:!1,pkce:!1,nonce:!1},twitter:{name:"twitter",label:"X",driver:me,required:Y,postCallback:!1,pkce:!0,nonce:!1},apple:{name:"apple",label:"Apple",driver:se,required:["clientId","teamId","keyId","privateKey","redirectUrl"],postCallback:!0,pkce:!1,nonce:!0}});function He(e){return Kt?.services?.[e]}function Xt(e){return typeof e==="string"&&e in M}function je(e){if(!Xt(e))return!1;let t=He(e);if(!t)return!1;return M[e].required.every((r)=>Boolean(t[r]))}function Gi(){return Object.keys(M).filter(je).map((e)=>M[e])}function Ji(e){if(!je(e))return null;let t=M[e],r=He(e)??{};return new t.driver({clientSecret:"",...r,clientId:String(r.clientId??""),redirectUrl:String(r.redirectUrl??"")})}class Qt{accessToken;refreshToken;expiresIn;approvedScopes;constructor(e,t=null,r=null,i=[]){this.accessToken=e;this.refreshToken=t;this.expiresIn=r;this.approvedScopes=i}}function Qi(e){return typeof e?.metrics==="function"}function Wi(e){return typeof e?.deletePost==="function"}function Yi(e){return typeof e?.listAuthoredPosts==="function"}import{buildSessionHandoffCodeUrl as Wt,buildSessionHandoffUrl as Yt}from"@stacksjs/composables";function fe(e,t=[]){if(!e)return!1;if(e.startsWith("//"))return!1;if(e.startsWith("/"))return!0;try{let r=new URL(e);if(r.protocol!=="http:"&&r.protocol!=="https:")return!1;return t.includes(r.host)}catch{return!1}}function ts(e,t={}){let r=t.redirectTo??"/";if(!fe(r,t.allowedHosts??[]))throw Error(`[socials] refusing to hand a session to ${r}: relative paths are always allowed; an absolute URL needs its host in allowedHosts.`);return new Response(null,{status:302,headers:{Location:Yt(r,e),"Cache-Control":"no-store","Referrer-Policy":"no-referrer"}})}function rs(e,t={}){let r=t.redirectTo??"/";if(!fe(r,t.allowedHosts??[]))throw Error(`[socials] refusing to hand a session to ${r}: relative paths are always allowed; an absolute URL needs its host in allowedHosts.`);return new Response(null,{status:302,headers:{Location:Wt(r,e),"Cache-Control":"no-store","Referrer-Policy":"no-referrer"}})}function is(e,t={}){let r=t.redirectTo??"/login";if(!fe(r,t.allowedHosts??[]))throw Error(`[socials] refusing to redirect to ${r}`);let i=r.includes("?")?"&":"?",s=`${r}${i}social_error=${encodeURIComponent(e)}`;return new Response(null,{status:302,headers:{Location:s,"Cache-Control":"no-store","Referrer-Policy":"no-referrer"}})}import{Buffer as Ve}from"buffer";import{createHash as Zt,randomBytes as er,timingSafeEqual as tr}from"crypto";function N(e){return Zt("sha256").update(e).digest("hex")}var rr=/^[a-f0-9]{64}$/,ir=/^[a-f0-9]{64}$/,sr=/^[\w.:-]{1,64}$/,nr=3600000,Ge=null;function as(e){Ge=e}function Je(){return Ge??cr()}function we(e=32){return er(e).toString("hex")}function or(e,t){if(e.length!==t.length)return!1;return tr(Ve.from(e,"utf8"),Ve.from(t,"utf8"))}function ye(e){return`stacks_oauth_${N(e).slice(0,24)}`}async function ar(){try{let{config:e}=await import("@stacksjs/config");return String(e.app?.url??"").startsWith("https:")}catch{return!1}}function Ke(e,t,r,i){return[`${e}=${t}`,`Path=${i.path}`,"HttpOnly",`SameSite=${i.sameSite}`,`Max-Age=${Math.max(0,Math.floor(r))}`,...i.secure?["Secure"]:[]].join("; ")}async function Xe(e={}){let t=e.sameSite??"Lax",r=t==="None"?!0:e.secure??await ar();return{path:e.path??"/",sameSite:t,secure:r}}async function cs(e){if(!sr.test(e.purpose??""))throw TypeError("[socials] issueOAuthFlow needs a purpose of 1-64 word characters, dots, colons or dashes.");if(!Number.isFinite(e.ttlMs)||e.ttlMs<=0)throw TypeError("[socials] issueOAuthFlow needs a positive ttlMs.");if(e.challenge!==void 0&&!ir.test(e.challenge))throw TypeError("[socials] issueOAuthFlow challenge must be the lowercase hex SHA-256 of the verifier.");if(e.userId!=null&&(!Number.isSafeInteger(e.userId)||e.userId<=0))throw TypeError("[socials] issueOAuthFlow userId must be a positive integer.");let t=Math.min(e.ttlMs,nr),r=we(),s=(e.challenge?!1:e.bindBrowser!==!1)?we():null,n=e.nonce===!0?we():typeof e.nonce==="string"&&e.nonce?e.nonce:void 0,o=new Date,a=new Date(o.getTime()+t),c=Je();try{await c.prune(o)}catch{}await c.insert({stateDigest:N(r),purpose:e.purpose,browserDigest:e.challenge??(s?N(s):null),userId:e.userId??null,nonce:n??null,data:e.data??null,expiresAt:a});let u=s?Ke(ye(r),s,t/1000,await Xe(e.cookie)):null;return{state:r,cookie:u,secret:s,...n!==void 0&&{nonce:n},expiresAt:a}}async function ls(e,t){if(typeof e!=="string"||!rr.test(e))return null;let r=Je(),i=N(e),s=await r.find(i);if(!s)return null;if(s.expiresAt.getTime()<=Date.now())return await r.take(i).catch(()=>!1),null;if(s.purpose!==t.purpose)return null;if(s.browserDigest!==null){let n=t.browserSecret;if(typeof n!=="string"||n.length===0||n.length>512)return null;if(!or(N(n),s.browserDigest))return null}if(!await r.take(i))return null;return{purpose:s.purpose,userId:s.userId,nonce:s.nonce,data:s.data,expiresAt:s.expiresAt}}function ds(e,t){if(!e||!t)return"";let r=ye(t);for(let i of e.split(";")){let s=i.trim();if(s.startsWith(`${r}=`))return s.slice(r.length+1)}return""}async function us(e,t={}){return Ke(ye(e),"",0,await Xe(t))}function ps(){let e=new Map;return{records:e,async insert(t){e.set(t.stateDigest,{...t})},async find(t){let r=e.get(t);return r?{...r}:void 0},async take(t){return e.delete(t)},async prune(t){for(let[r,i]of e)if(i.expiresAt.getTime()<=t.getTime())e.delete(r)}}}var Z="oauth_flows";function cr(){let e=()=>import("@stacksjs/database/runtime");return{async insert(t){let{db:r,sqlDateTime:i}=await e();await r.insertInto(Z).values({state_digest:t.stateDigest,purpose:t.purpose,browser_digest:t.browserDigest,user_id:t.userId,nonce:t.nonce,data:t.data?JSON.stringify(t.data):null,expires_at:i(t.expiresAt),created_at:i(new Date)}).execute()},async find(t){let{db:r,parseSqlDateTime:i}=await e(),s=await r.primary.selectFrom(Z).where("state_digest","=",t).selectAll().executeTakeFirst();if(!s)return;let n=null;if(typeof s.data==="string"&&s.data)try{let o=JSON.parse(s.data);n=o&&typeof o==="object"?o:null}catch{n=null}return{stateDigest:String(s.state_digest),purpose:String(s.purpose),browserDigest:typeof s.browser_digest==="string"&&s.browser_digest?s.browser_digest:null,userId:s.user_id==null?null:Number(s.user_id),nonce:typeof s.nonce==="string"&&s.nonce?s.nonce:null,data:n,expiresAt:i(s.expires_at)??new Date(0)}},async take(t){let{db:r,mutationCount:i}=await e(),s=await r.deleteFrom(Z).where("state_digest","=",t).execute();return i(s)===1},async prune(t){let{db:r,sqlDateTime:i}=await e();await r.deleteFrom(Z).where("expires_at","<",i(t)).execute()}}}var lr={bluesky:["identifier","password","service"],twitter:["clientId","clientSecret","accessToken","refreshToken"],linkedin:["accessToken","memberUrn","clientId","clientSecret","apiVersion"],mastodon:["accessToken","instanceUrl"],instagram:["accessToken","accountId","clientId","clientSecret"],threads:["accessToken","userId","clientId","clientSecret"]},dr={bluesky:["identifier","password"],twitter:["clientId","clientSecret","accessToken"],linkedin:["accessToken","memberUrn"],mastodon:["accessToken","instanceUrl"],instagram:["accessToken","accountId"],threads:["accessToken","userId"]};function ur(e){return e.toUpperCase().replace(/[^A-Z0-9]/g,"")}function ee(e,t,r){let i=r.replace(/[A-Z]/g,(s)=>`_${s}`).toUpperCase();return`SOCIALS_${ur(e)}_${t.toUpperCase()}_${i}`}class S extends Error{constructor(e){super(e);this.name="SocialIdentityError"}}async function te(){let{config:e,overridesReady:t}=await import("@stacksjs/config");return await t,e.socials??{}}function Qe(e,t){let r=Object.keys(e.identities??{});if(t){if(!r.includes(t))throw new S(`Unknown social identity '${t}'. config/socials.ts declares: ${r.length?r.join(", "):"none"}.`);return t}if(e.default){if(!r.includes(e.default))throw new S(`config/socials.ts sets default: '${e.default}', which is not one of its identities: ${r.length?r.join(", "):"none"}.`);return e.default}if(r.length===1)return r[0];if(r.length===0)throw new S("config/socials.ts declares no identities, so there is no account to post as.");throw new S(`config/socials.ts declares ${r.length} identities (${r.join(", ")}) and no default, so a call has to name one.`)}function pr(e,t,r,i=process.env){let n=(e.identities?.[r]??{}).credentials?.[t]??{},o={};for(let a of lr[t]){let c=(n[a]??i[ee(r,t,a)]??"").trim();if(c)o[a]=c}return o}function ke(e,t,r,i=process.env){let s=Qe(e,r),n=pr(e,t,s,i),o=dr[t].filter((a)=>!n[a]);if(o.length){let a=o.map((c)=>ee(s,t,c)).join(", ");throw new S(`Identity '${s}' is not configured for ${t}: ${o.join(", ")} ${o.length===1?"is":"are"} missing. Set ${a}, or supply them inline in config/socials.ts.`)}return n}async function We(e){return Qe(await te(),e)}async function O(e,t,r){return ke(await te(),e,t,r)}function gs(e,t){return O("bluesky",e,t)}function ms(e,t){return O("twitter",e,t)}function fs(e,t){return O("linkedin",e,t)}function ws(e,t){return O("mastodon",e,t)}function ys(e,t){return O("instagram",e,t)}function ks(e,t){return O("threads",e,t)}import{randomBytes as hr}from"crypto";function xs(e){return e==="twitter"}var gr=["tweet.read","tweet.write","users.read","offline.access"],mr="127.0.0.1",Ye="/callback";function Is(e){if(!Number.isInteger(e)||e<1||e>65535)throw new S(`${e} is not a port a redirect can listen on.`);return`http://${mr}:${e}${Ye}`}function _s(){return hr(16).toString("hex")}function Ts(e,t){let r;try{r=new URL(e)}catch{return{ok:!1,reason:"not-the-callback",message:`Not a URL: ${e}`}}if(r.pathname!==Ye)return{ok:!1,reason:"not-the-callback",message:`Ignoring a request for ${r.pathname}.`};let i=r.searchParams.get("error");if(i){let o=r.searchParams.get("error_description");return{ok:!1,reason:"declined",message:o?`${i}: ${o}`:i}}let s=r.searchParams.get("state")??"";if(!t||s!==t)return{ok:!1,reason:"state-mismatch",message:"The redirect carried the wrong state, so it did not come from this run."};let n=r.searchParams.get("code")??"";if(!n)return{ok:!1,reason:"no-code",message:"The redirect carried no authorization code."};return{ok:!0,code:n}}function As(e,t,r){let i=[];for(let[s,n]of Object.entries(r)){if(!n)continue;i.push(`${ee(e,t,s)}=${n}`)}return i}async function Cs(e){let t=new E,r=await t.exchangeCode(e);if(!r.accessToken)throw new S("X returned no access token for that code.");let i=Boolean(r.refreshToken),s=await t.getProfile(r.accessToken);return{handle:s.username,accountId:s.id,accessToken:r.accessToken,refreshToken:r.refreshToken,expiresIn:r.expiresIn,scope:r.scope,renewable:i}}async function Rs(e){return new E().createAuthorization({clientId:e.clientId,redirectUrl:e.redirectUrl,scopes:[...gr],state:e.state})}function Us(e,t){let r=(i)=>i.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;");return`<!doctype html><html lang="en"><head><meta charset="utf-8"><title>${r(e)}</title><style>body{font:16px/1.5 system-ui,sans-serif;margin:0;display:grid;place-items:center;min-height:100vh;color:#111}main{max-width:28rem;padding:2rem;text-align:center}h1{font-size:1.25rem;margin:0 0 .5rem}p{margin:0;color:#555}@media(prefers-color-scheme:dark){body{background:#111;color:#eee}p{color:#aaa}}</style></head><body><main><h1>${r(e)}</h1><p>${r(t)}</p></main></body></html>`}var fr={bluesky:null,twitter:null,linkedin:"memberUrn",mastodon:"instanceUrl",instagram:"accountId",threads:"userId"};function wr(e,t){if(e==="bluesky")return t.service?{service:t.service}:{};if(e==="linkedin")return t.apiVersion?{apiVersion:t.apiVersion}:{};return{}}function yr(e,t){if(e.service||!t.service)return e;return{...e,service:t.service}}function kr(e,t={}){switch(e){case"bluesky":return new G(t);case"linkedin":return new de(t);case"twitter":return new E;case"mastodon":return new he;case"instagram":return new le;case"threads":return new ge;default:throw new S(`No publishing driver for '${String(e)}'.`)}}function br(e,t,r){let i=fr[e],s={handle:(t??"").trim()};if(r.accessToken)s.accessToken=r.accessToken;if(r.refreshToken)s.refreshToken=r.refreshToken;if(i&&r[i])s.did=r[i];return s}function Sr(e,t,r){if(!r)return;if(r.includes(t))return;throw new S(`Identity '${e}' is not set up for ${t}. config/socials.ts lists: ${r.length?r.join(", "):"none"}.`)}async function Pr(e,t,r){let i=await te(),s=await We(t),n=i.identities?.[s]??{};Sr(s,e,n.platforms);let o=ke(i,e,s,r),a=wr(e,o);if(e==="bluesky"){let c=await new G(a).createSession({identifier:o.identifier,password:o.password});return{name:s,platform:e,identity:{handle:c.handle,did:c.did,accessToken:c.accessJwt,refreshToken:c.refreshJwt},options:yr(a,c)}}return{name:s,platform:e,identity:br(e,n.handle??"",o),options:a}}async function Ls(e,t,r,i){let s=await Pr(e,r,i);return kr(s.platform,s.options).publish(s.identity,t)}export{mr as AUTHORIZE_HOST,Ye as AUTHORIZE_PATH,w as AbstractProvider,se as AppleProvider,Ae as BLUESKY_MAX_BLOB_BYTES,mt as BLUESKY_MAX_IMAGES,ft as BLUESKY_MAX_LANGS,L as BlueskyApiError,G as BlueskyPublishingDriver,h as ConfigException,fr as DRIVER_DID_FIELD,ne as FacebookProvider,ae as GitHubProvider,ce as GoogleProvider,xt as INSTAGRAM_MAX_ALT_TEXT,vt as INSTAGRAM_MAX_IMAGES,k as InstagramApiError,le as InstagramPublishingDriver,et as InvalidStateException,Be as LINKEDIN_API_VERSION,Ut as LINKEDIN_MAX_ALT_TEXT,Rt as LINKEDIN_MAX_IMAGES,Et as LINKEDIN_POSTING_ROLES,Br as LINK_LENGTH,f as LinkedInApiError,de as LinkedInPublishingDriver,U as MASTODON_DEFAULT_LIMITS,Tt as MAX_POST_IMAGE_BYTES,J as META_GRAPH_VERSION,pe as MastodonApiError,he as MastodonPublishingDriver,De as PostImageError,dr as REQUIRED_SOCIAL_CREDENTIALS,lr as SOCIAL_CREDENTIAL_FIELDS,M as SOCIAL_PROVIDERS,y as SocialApiError,S as SocialIdentityError,B as StacksIssuerError,Jt as StacksIssuerProvider,zt as THREADS_MAX_ALT_TEXT,qt as THREADS_MAX_IMAGES,gr as TWITTER_PUBLISH_SCOPES,v as ThreadsApiError,ge as ThreadsPublishingDriver,Qt as Token,I as TwitterApiError,me as TwitterProvider,E as TwitterPublishingDriver,Vt as X_MAX_ALT_TEXT,jt as X_MAX_IMAGES,m as apiFailure,Sr as assertPlatformDeclared,Jr as blueskyRecordKey,yr as blueskyTargetOptions,Us as callbackPage,Is as callbackUri,j as classifySocialError,us as clearOAuthFlowCookie,Cs as completeTwitterAuthorization,Gi as configuredSocialProviders,ls as consumeOAuthFlow,dt as countText,cr as databaseOAuthFlowStore,yt as detectFacetCandidates,wr as driverOptions,As as envLines,ee as envName,ur as envSegment,$t as escapeLinkedInText,b as exceedsLimit,A as fetchPostImage,F as graphemes,xs as isAuthorizablePlatform,Gr as isBlueskySessionError,Nr as isExpiredSignIn,K as isMissingGraphObject,fe as isSafeHandoffTarget,je as isSocialProviderConfigured,Xt as isSocialProviderName,cs as issueOAuthFlow,At as linkedInVersionSunset,ps as memoryOAuthFlowStore,H as networkReason,_s as newState,Nt as normalizeInstance,ye as oauthFlowCookieName,N as oauthFlowDigest,Ue as parseAtUri,ke as pickCredentials,Qe as pickIdentity,Ls as publishAs,kr as publishingDriver,Ts as readCallback,pr as readCredentials,ds as readOAuthFlowCookie,gs as resolveBlueskyCredentials,kt as resolveBlueskyService,We as resolveIdentityName,ys as resolveInstagramCredentials,fs as resolveLinkedInCredentials,Ct as resolveLinkedInVersion,ws as resolveMastodonCredentials,C as resolvePostImage,O as resolveSocialCredentials,ks as resolveThreadsCredentials,ms as resolveTwitterCredentials,pt as retryAfterMs,Le as sniffImageType,rs as socialHandoffCodeRedirect,is as socialHandoffFailureRedirect,ts as socialHandoffRedirect,Ji as socialProvider,Pr as socialPublishTarget,te as socialsConfig,Rs as startTwitterAuthorization,Wi as supportsDeletion,Yi as supportsEnumeration,Qi as supportsMetrics,br as toDriverIdentity,as as useOAuthFlowStore};
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@stacksjs/socials",
3
3
  "type": "module",
4
4
  "sideEffects": false,
5
- "version": "0.75.706",
5
+ "version": "0.75.707",
6
6
  "description": "A simple and elegant social authentication package for Stacks.",
7
7
  "author": "Chris Breuer",
8
8
  "contributors": [
@@ -57,15 +57,15 @@
57
57
  "prepublishOnly": "bun run build"
58
58
  },
59
59
  "dependencies": {
60
- "@stacksjs/api": "0.75.706",
61
- "@stacksjs/composables": "0.75.706",
62
- "@stacksjs/config": "0.75.706",
63
- "@stacksjs/database": "0.75.706",
64
- "@stacksjs/security": "0.75.706"
60
+ "@stacksjs/api": "0.75.707",
61
+ "@stacksjs/composables": "0.75.707",
62
+ "@stacksjs/config": "0.75.707",
63
+ "@stacksjs/database": "0.75.707",
64
+ "@stacksjs/security": "0.75.707"
65
65
  },
66
66
  "devDependencies": {
67
- "@stacksjs/error-handling": "0.75.706",
68
- "@stacksjs/router": "0.75.706",
67
+ "@stacksjs/error-handling": "0.75.707",
68
+ "@stacksjs/router": "0.75.707",
69
69
  "better-dx": "^0.2.39"
70
70
  }
71
71
  }