@stacksjs/socials 0.70.161 → 0.70.162
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/drivers/bluesky.d.ts +16 -0
- package/dist/index.js +2 -2
- package/dist/types.d.ts +8 -1
- package/package.json +3 -3
|
@@ -1,7 +1,19 @@
|
|
|
1
1
|
import type { BlueskySession, BlueskySessionCredentials, PublishedPost, PublishPostInput, SocialIdentityCredentials, SocialPublishingDriver, TimelineQuery, TimelineResult } from '../types';
|
|
2
|
+
/**
|
|
3
|
+
* Find link/hashtag/mention spans in post text with UTF-8 byte offsets
|
|
4
|
+
* (ATProto facet ranges are byte-indexed, not character-indexed).
|
|
5
|
+
* Mentions still need their DID resolved before they become facets.
|
|
6
|
+
*/
|
|
7
|
+
export declare function detectFacetCandidates(text: string): FacetCandidate[];
|
|
2
8
|
export declare interface BlueskyDriverOptions {
|
|
3
9
|
service?: string
|
|
4
10
|
}
|
|
11
|
+
declare interface FacetCandidate {
|
|
12
|
+
byteStart: number
|
|
13
|
+
byteEnd: number
|
|
14
|
+
type: 'link' | 'tag' | 'mention'
|
|
15
|
+
value: string
|
|
16
|
+
}
|
|
5
17
|
export declare class BlueskyApiError extends Error {
|
|
6
18
|
public status: number;
|
|
7
19
|
public body: string;
|
|
@@ -16,8 +28,12 @@ export declare class BlueskyPublishingDriver implements SocialPublishingDriver {
|
|
|
16
28
|
createSession(credentials: BlueskySessionCredentials): Promise<BlueskySession>;
|
|
17
29
|
refreshSession(refreshToken: string): Promise<BlueskySession>;
|
|
18
30
|
publish(identity: SocialIdentityCredentials, post: PublishPostInput): Promise<PublishedPost>;
|
|
31
|
+
postMetrics(identity: SocialIdentityCredentials, uris: string[]): Promise<Array<{ uri: string, likeCount: number, repostCount: number, replyCount: number }>>;
|
|
19
32
|
timeline(identity: SocialIdentityCredentials, query?: TimelineQuery): Promise<TimelineResult>;
|
|
20
33
|
getProfile(identity: SocialIdentityCredentials): Promise<{ did: string, handle: string, displayName?: string }>;
|
|
34
|
+
protected buildFacets(text: string): Promise<Array<Record<string, unknown>>>;
|
|
35
|
+
protected resolveHandle(handle: string): Promise<string | null>;
|
|
36
|
+
uploadBlob(identity: SocialIdentityCredentials, bytes: Uint8Array, mimeType: string): Promise<unknown>;
|
|
21
37
|
protected post<T>(path: string, body?: unknown, headers?: Record<string, string>): Promise<T>;
|
|
22
38
|
protected request<T>(url: URL, init: RequestInit): Promise<T>;
|
|
23
39
|
protected toPostUrl(handle: string, uri: string): string;
|
package/dist/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var
|
|
3
|
-
`),redirectUrl:this.redirectUrl||(R.services.apple?.redirectUrl??""),scopes:this._scopes.length>0?this._scopes:R.services.apple?.scopes??["name","email"]};return this.setScopes(w.scopes),w}async getAuthUrl(){let w=this.resolveState(),{clientId:h,redirectUrl:P,scopes:S}=this.getConfig();this.validateConfig();let $={client_id:h,redirect_uri:P,scope:S.join(" "),state:w,response_type:"code",...this.parameters};if(S.length>0)$.response_mode="form_post";return`${this.baseUrl}/auth/authorize?${new URLSearchParams($).toString()}`}async getAccessToken(w){let{clientId:h,redirectUrl:P}=this.getConfig();this.validateConfig();let S=await fetch(`${this.baseUrl}/auth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:w,redirect_uri:P,client_id:h,client_secret:this.generateClientSecret()})}),$=await S.json();if(!S.ok||$.error)throw Error(`Apple OAuth error: ${$.error_description??$.error??`HTTP ${S.status}`}`);if(!$.id_token)throw Error("Apple OAuth error: token response contained no id_token");return $.id_token}async getUserByToken(w){let{clientId:h}=this.getConfig(),P=this.decodeIdToken(w),S=P.iss===this.baseUrl,$=Array.isArray(P.aud)?P.aud.includes(h):P.aud===h,J=typeof P.exp==="number"&&P.exp*1000>Date.now();if(!S||!$||!J)throw Error("Apple OAuth error: id_token claims failed validation (iss/aud/exp)");if(!P.sub)throw Error("Apple OAuth error: id_token has no subject");let D=typeof P.email==="string"?P.email:null,u=null;if(P.email_verified===!0||P.email_verified==="true")u=!0;else if(P.email_verified===!1||P.email_verified==="false")u=!1;return{id:String(P.sub),nickname:null,name:"",email:D,emailVerified:u,avatar:null,token:w,raw:P}}generateClientSecret(){let{clientId:w,teamId:h,keyId:P,privateKey:S}=this.getConfig(),$=Math.floor(Date.now()/1000),J={alg:"ES256",kid:P,typ:"JWT"},D={iss:h,iat:$,exp:$+3600,aud:this.baseUrl,sub:w},u=`${this.base64urlJson(J)}.${this.base64urlJson(D)}`,Z;try{Z=V(S)}catch(H){throw new B(`Apple private key could not be parsed: ${H instanceof Error?H.message:String(H)}`)}let L=v("sha256",X.from(u),{key:Z,dsaEncoding:"ieee-p1363"});return`${u}.${L.toString("base64url")}`}decodeIdToken(w){let h=w.split(".");if(h.length!==3)throw Error("Apple OAuth error: malformed id_token");return JSON.parse(X.from(h[1],"base64url").toString("utf8"))}base64urlJson(w){return X.from(JSON.stringify(w)).toString("base64url")}validateConfig(){let{clientId:w,teamId:h,keyId:P,privateKey:S,redirectUrl:$}=this.getConfig();if(!w)throw new B("Apple client ID (Service ID) not provided");if(!h)throw new B("Apple team ID not provided");if(!P)throw new B("Apple key ID not provided");if(!S)throw new B("Apple private key not provided");if(!$)throw new B("Apple redirect URL not provided")}getTokenUrl(){return`${this.baseUrl}/auth/token`}}class T extends Error{status;body;constructor(w,h,P){super(w);this.status=h;this.body=P;this.name="BlueskyApiError"}get isAuthError(){return this.status===400||this.status===401||this.status===403}}class U{provider="bluesky";characterLimit=300;service;constructor(w={}){this.service=w.service||"https://bsky.social"}async createSession(w){let h=w.identifier.trim(),P=w.password.trim();if(!h)throw Error("Bluesky identifier is required.");if(!P)throw Error("Bluesky app password is required.");let S=await this.post("/xrpc/com.atproto.server.createSession",{identifier:h,password:P}),$=await this.getProfile({did:S.did,handle:S.handle,accessToken:S.accessJwt,refreshToken:S.refreshJwt}).catch(()=>{return});return{did:S.did,handle:S.handle,displayName:$?.displayName,accessJwt:S.accessJwt,refreshJwt:S.refreshJwt}}async refreshSession(w){if(!w)throw Error("Bluesky refresh token is required.");let h=await this.post("/xrpc/com.atproto.server.refreshSession",void 0,{authorization:`Bearer ${w}`});return{did:h.did,handle:h.handle,accessJwt:h.accessJwt,refreshJwt:h.refreshJwt}}async publish(w,h){let P=w.did||w.handle;if(!w.accessToken)throw Error("Bluesky access token is missing for this identity.");if(!P)throw Error("Bluesky identity DID or handle is required.");if(h.text.length>this.characterLimit)throw Error(`Bluesky posts must be ${this.characterLimit} characters or fewer.`);let S={$type:"app.bsky.feed.post",text:h.text,createdAt:h.scheduledAt||new Date().toISOString()};if(h.langs?.length)S.langs=h.langs;if(h.external)S.embed={$type:"app.bsky.embed.external",external:{uri:h.external.uri,title:h.external.title,description:h.external.description||""}};let $=await this.post("/xrpc/com.atproto.repo.createRecord",{repo:P,collection:"app.bsky.feed.post",record:S},{authorization:`Bearer ${w.accessToken}`});return{provider:this.provider,uri:$.uri,cid:$.cid,url:this.toPostUrl(w.handle,$.uri)}}async timeline(w,h={}){if(!w.accessToken)throw Error("Bluesky access token is missing for this identity.");let P=new URL(`${this.service}/xrpc/app.bsky.feed.getTimeline`);if(P.searchParams.set("limit",String(Math.min(Math.max(h.limit||30,1),100))),h.cursor)P.searchParams.set("cursor",h.cursor);let S=await this.request(P,{headers:{authorization:`Bearer ${w.accessToken}`}});return{cursor:S.cursor,items:(S.feed||[]).flatMap(($)=>{let J=$.post;if(!J?.uri||!J.author?.handle)return[];return[{uri:J.uri,authorHandle:J.author.handle,authorName:J.author.displayName,authorAvatar:J.author.avatar,postUrl:this.toPostUrl(J.author.handle,J.uri),body:J.record?.text||"",postedAt:J.record?.createdAt||new Date().toISOString(),likeCount:J.likeCount||0,repostCount:J.repostCount||0,replyCount:J.replyCount||0}]})}}async getProfile(w){if(!w.accessToken)throw Error("Bluesky access token is missing for this identity.");let h=w.did||w.handle;if(!h)throw Error("Bluesky identity DID or handle is required.");let P=new URL(`${this.service}/xrpc/app.bsky.actor.getProfile`);return P.searchParams.set("actor",h),await this.request(P,{headers:{authorization:`Bearer ${w.accessToken}`}})}async post(w,h,P={}){return await this.request(new URL(`${this.service}${w}`),{method:"POST",headers:{...h===void 0?{}:{"content-type":"application/json"},...P},...h===void 0?{}:{body:JSON.stringify(h)}})}async request(w,h){let P=await fetch(w,h),S=await P.text();if(!P.ok)throw new T(`Bluesky API failed (${P.status}): ${S||P.statusText}`,P.status,S);return S?JSON.parse(S):{}}toPostUrl(w,h){let P=h.split("/").pop();return`https://bsky.app/profile/${w}/post/${P}`}}import{fetcher as W}from"@stacksjs/api";import{config as Q}from"@stacksjs/config";class C extends N{baseUrl="https://www.facebook.com";apiUrl="https://graph.facebook.com";getConfig(){let w={clientId:Q.services.facebook?.clientId??"",clientSecret:Q.services.facebook?.clientSecret??"",redirectUrl:Q.services.facebook?.redirectUrl??"",scopes:Q.services.facebook?.scopes??["email","public_profile"]};return this.setScopes(w.scopes),w}async getAuthUrl(){let w=this.getState(),{clientId:h,redirectUrl:P,scopes:S}=this.getConfig();return this.validateConfig(),`${this.baseUrl}/v18.0/dialog/oauth?${new URLSearchParams({client_id:h,redirect_uri:P,scope:S.join(","),state:w,response_type:"code"}).toString()}`}async getAccessToken(w){let{clientId:h,clientSecret:P,redirectUrl:S}=this.getConfig();this.validateConfig();let $=await W.get(`${this.apiUrl}/v18.0/oauth/access_token?${new URLSearchParams({client_id:h,client_secret:P,redirect_uri:S,code:w}).toString()}`);if($.data.error)throw Error(`Facebook OAuth error: ${$.data.error.message}`);return $.data.access_token}async getUserByToken(w){let h=await W.get(`${this.apiUrl}/v18.0/me?${new URLSearchParams({access_token:w,fields:"id,name,email,picture"}).toString()}`);return{id:h.data.id,nickname:null,name:h.data.name,email:h.data.email??null,avatar:h.data.picture?.data.url??null,token:w,raw:h.data}}validateConfig(){let{clientId:w,clientSecret:h,redirectUrl:P}=this.getConfig();if(!w)throw new B("Facebook client ID not provided");if(!h)throw new B("Facebook client secret not provided");if(!P)throw new B("Facebook redirect URL not provided")}getTokenUrl(){return`${this.apiUrl}/v18.0/oauth/access_token`}}import{fetcher as Y}from"@stacksjs/api";import{config as q}from"@stacksjs/config";class x extends N{baseUrl="https://github.com";apiUrl="https://api.github.com";getConfig(){let w={clientId:this.clientId||(q.services.github?.clientId??""),clientSecret:this.clientSecret||(q.services.github?.clientSecret??""),redirectUrl:this.redirectUrl||(q.services.github?.redirectUrl??""),scopes:this._scopes.length>0?this._scopes:q.services.github?.scopes??["read:user","user:email"]};return this.setScopes(w.scopes),w}async getAuthUrl(){let w=this.resolveState(),{clientId:h,redirectUrl:P,scopes:S}=this.getConfig();return this.validateConfig(),`${this.baseUrl}/login/oauth/authorize?${new URLSearchParams({client_id:h,redirect_uri:P,scope:S.join(" "),state:w,response_type:"code",...this.parameters}).toString()}`}async getAccessToken(w){let{clientId:h,clientSecret:P,redirectUrl:S}=this.getConfig();this.validateConfig();let $=await Y.post(`${this.baseUrl}/login/oauth/access_token`,{client_id:h,client_secret:P,code:w,redirect_uri:S});if($.data.error)throw Error(`GitHub OAuth error: ${$.data.error_description}`);return $.data.access_token}async getUserByToken(w){let[h,P]=await Promise.all([Y.withHeaders({Accept:"application/vnd.github.v3+json",Authorization:`token ${w}`}).get(`${this.apiUrl}/user`),Y.withHeaders({Accept:"application/vnd.github.v3+json",Authorization:`token ${w}`}).get(`${this.apiUrl}/user/emails`)]),S=this.pickEmail(P.data);return{id:h.data.id.toString(),nickname:h.data.login,name:h.data.name??h.data.login,email:S?.email??h.data.email??null,emailVerified:S?S.verified:null,avatar:h.data.avatar_url,token:w,raw:h.data}}pickEmail(w){if(!Array.isArray(w)||w.length===0)return null;let h=w.find((S)=>S.primary&&S.verified),P=w.find((S)=>S.verified);return h??P??w.find((S)=>S.primary)??w[0]??null}getEmail(w){return this.pickEmail(w)?.email??null}validateConfig(){let{clientId:w,clientSecret:h,redirectUrl:P}=this.getConfig();if(!w)throw new B("GitHub client ID not provided");if(!h)throw new B("GitHub client secret not provided");if(!P)throw new B("GitHub redirect URL not provided")}getTokenUrl(){return`${this.baseUrl}/login/oauth/access_token`}}import{fetcher as b}from"@stacksjs/api";import{config as F}from"@stacksjs/config";class k extends N{baseUrl="https://accounts.google.com";apiUrl="https://www.googleapis.com";getConfig(){let w={clientId:this.clientId||(F.services.google?.clientId??""),clientSecret:this.clientSecret||(F.services.google?.clientSecret??""),redirectUrl:this.redirectUrl||(F.services.google?.redirectUrl??""),scopes:this._scopes.length>0?this._scopes:F.services.google?.scopes??["openid","email"]};return this.setScopes(w.scopes),w}async getAuthUrl(){let w=this.resolveState(),{clientId:h,redirectUrl:P,scopes:S}=this.getConfig();return this.validateConfig(),`${this.baseUrl}/o/oauth2/v2/auth?${new URLSearchParams({client_id:h,redirect_uri:P,scope:S.join(" "),state:w,response_type:"code",access_type:"offline",prompt:"consent",...this.parameters}).toString()}`}async getAccessToken(w){let{clientId:h,clientSecret:P,redirectUrl:S}=this.getConfig();this.validateConfig();let $=await b.post(`${this.baseUrl}/oauth2/v4/token`,{client_id:h,client_secret:P,code:w,redirect_uri:S,grant_type:"authorization_code"});if($.data.error)throw Error(`Google OAuth error: ${$.data.error_description}`);return $.data.access_token}async getUserByToken(w){let h=await b.withHeaders({Authorization:`Bearer ${w}`}).get(`${this.apiUrl}/oauth2/v2/userinfo`);return{id:h.data.id,nickname:h.data.given_name,name:h.data.name,email:h.data.email,emailVerified:typeof h.data.verified_email==="boolean"?h.data.verified_email:null,avatar:h.data.picture,token:w,raw:h.data}}validateConfig(){let{clientId:w,clientSecret:h,redirectUrl:P}=this.getConfig();if(!w)throw new B("Google client ID not provided");if(!h)throw new B("Google client secret not provided");if(!P)throw new B("Google redirect URL not provided")}getTokenUrl(){return`${this.baseUrl}/oauth2/v4/token`}}class O extends Error{status;body;constructor(w,h,P){super(w);this.status=h;this.body=P;this.name="InstagramApiError"}get isAuthError(){return this.status===401||this.status===403||this.status===190}}class A{provider="instagram";characterLimit=2200;graphVersion;authBase;graphBase;constructor(w={}){this.graphVersion=w.graphVersion||"v21.0",this.authBase=w.authBase||"https://www.facebook.com",this.graphBase=w.graphBase||"https://graph.facebook.com"}getAuthUrl(w){let h=new URLSearchParams({client_id:w.clientId,redirect_uri:w.redirectUrl,scope:w.scopes.join(","),state:w.state,response_type:"code"});return`${this.authBase}/${this.graphVersion}/dialog/oauth?${h.toString()}`}async exchangeCode(w){let h=new URLSearchParams({client_id:w.clientId,client_secret:w.clientSecret,redirect_uri:w.redirectUrl,code:w.code}),P=await this.graph(`/oauth/access_token?${h.toString()}`,{method:"GET"});if(!P.access_token)throw new O("Facebook did not return an access token.",400,JSON.stringify(P));return{accessToken:P.access_token,expiresIn:P.expires_in}}async resolveAccount(w){let h=new URLSearchParams({fields:"name,access_token,instagram_business_account{id,username}",access_token:w}),P=await this.graph(`/me/accounts?${h.toString()}`,{method:"GET"}),S=(P.data||[]).find((J)=>J.instagram_business_account?.id),$=S?.instagram_business_account;if(!$?.id||!S?.access_token)throw new O("No Instagram Business account is linked to your Facebook Pages.",400,JSON.stringify(P));return{igUserId:$.id,username:$.username,pageAccessToken:S.access_token}}async publish(w,h){if(!w.accessToken)throw Error("Instagram access token is missing for this identity.");let P=w.did;if(!P)throw Error("Instagram account id is required to publish.");let S=h.media?.[0];if(!S?.url)throw Error("Instagram requires an image to post.");if(h.text.length>this.characterLimit)throw Error(`Instagram captions must be ${this.characterLimit} characters or fewer.`);let $=await this.graph(`/${P}/media`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({image_url:S.url,caption:h.text,access_token:w.accessToken}).toString()});if(!$.id)throw new O("Instagram did not return a media container id.",400,JSON.stringify($));let J=await this.graph(`/${P}/media_publish`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({creation_id:$.id,access_token:w.accessToken}).toString()}),D=await this.graph(`/${J.id}?fields=permalink&access_token=${encodeURIComponent(w.accessToken)}`,{method:"GET"}).catch(()=>{return});return{provider:this.provider,uri:J.id,url:D?.permalink}}async timeline(w,h={}){return{items:[]}}async graph(w,h){let P=await fetch(`${this.graphBase}/${this.graphVersion}${w}`,h),S=await P.text(),$={};try{$=S?JSON.parse(S):{}}catch{$={}}if(!P.ok||$?.error){let J=$?.error?.message||S||P.statusText;throw new O(`Instagram API failed (${P.status}): ${J}`,P.status,S)}return $}}class M extends Error{status;body;constructor(w,h,P){super(w);this.status=h;this.body=P;this.name="LinkedInApiError"}get isAuthError(){return this.status===401||this.status===403}}class E{provider="linkedin";characterLimit=3000;apiVersion;authBase;apiBase;constructor(w={}){this.apiVersion=w.apiVersion||"202405",this.authBase=w.authBase||"https://www.linkedin.com",this.apiBase=w.apiBase||"https://api.linkedin.com"}getAuthUrl(w){let h=new URLSearchParams({response_type:"code",client_id:w.clientId,redirect_uri:w.redirectUrl,scope:w.scopes.join(" "),state:w.state});return`${this.authBase}/oauth/v2/authorization?${h.toString()}`}async exchangeCode(w){let h=new URLSearchParams({grant_type:"authorization_code",code:w.code,redirect_uri:w.redirectUrl,client_id:w.clientId,client_secret:w.clientSecret}),P=await this.request(`${this.authBase}/oauth/v2/accessToken`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:h.toString()});if(!P.access_token)throw new M("LinkedIn did not return an access token.",400,JSON.stringify(P));return{accessToken:P.access_token,expiresIn:P.expires_in,scope:P.scope}}async getProfile(w){if(!w)throw Error("LinkedIn access token is required.");let h=await this.request(`${this.apiBase}/v2/userinfo`,{headers:{authorization:`Bearer ${w}`}});if(!h.sub)throw new M("LinkedIn profile is missing a subject id.",400,JSON.stringify(h));return{sub:h.sub,name:h.name,picture:h.picture}}async publish(w,h){if(!w.accessToken)throw Error("LinkedIn access token is missing for this identity.");let P=w.did;if(!P)throw Error("LinkedIn member URN is required to publish.");if(h.text.length>this.characterLimit)throw Error(`LinkedIn posts must be ${this.characterLimit} characters or fewer.`);let S={author:P,commentary:j(h.text),visibility:"PUBLIC",distribution:{feedDistribution:"MAIN_FEED",targetEntities:[],thirdPartyDistributionChannels:[]},lifecycleState:"PUBLISHED",isReshareDisabledByAuthor:!1};if(h.external)S.content={article:{source:h.external.uri,title:h.external.title,description:h.external.description||""}};let $=await fetch(`${this.apiBase}/rest/posts`,{method:"POST",headers:{authorization:`Bearer ${w.accessToken}`,"content-type":"application/json","linkedin-version":this.apiVersion,"x-restli-protocol-version":"2.0.0"},body:JSON.stringify(S)}),J=await $.text();if(!$.ok)throw new M(`LinkedIn API failed (${$.status}): ${J||$.statusText}`,$.status,J);let D=$.headers.get("x-restli-id")||$.headers.get("x-linkedin-id")||"";return{provider:this.provider,uri:D,url:D?`https://www.linkedin.com/feed/update/${D}`:void 0}}async timeline(w,h={}){return{items:[]}}async request(w,h){let P=await fetch(w,h),S=await P.text();if(!P.ok)throw new M(`LinkedIn API failed (${P.status}): ${S||P.statusText}`,P.status,S);return S?JSON.parse(S):{}}}function j(w){return w.replace(/[\\|{}@[\]()<>#*_~]/g,"\\$&")}class z extends Error{status;body;constructor(w,h,P){super(w);this.status=h;this.body=P;this.name="ThreadsApiError"}get isAuthError(){return this.status===401||this.status===403||this.status===190}}class y{provider="threads";characterLimit=500;graphVersion;authBase;graphBase;constructor(w={}){this.graphVersion=w.graphVersion||"v1.0",this.authBase=w.authBase||"https://threads.net",this.graphBase=w.graphBase||"https://graph.threads.net"}getAuthUrl(w){let h=new URLSearchParams({client_id:w.clientId,redirect_uri:w.redirectUrl,scope:w.scopes.join(","),response_type:"code",state:w.state});return`${this.authBase}/oauth/authorize?${h.toString()}`}async exchangeCode(w){let h=await fetch(`${this.graphBase}/oauth/access_token`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:w.clientId,client_secret:w.clientSecret,grant_type:"authorization_code",redirect_uri:w.redirectUrl,code:w.code}).toString()}),P=await h.text(),S={};try{S=P?JSON.parse(P):{}}catch{S={}}if(!h.ok||S?.error||!S?.access_token){let $=S?.error_message||S?.error?.message||P||h.statusText;throw new z(`Threads token exchange failed (${h.status}): ${$}`,h.status,P)}return{accessToken:S.access_token,userId:S.user_id!=null?String(S.user_id):void 0,expiresIn:S.expires_in}}async resolveAccount(w){let h=new URLSearchParams({fields:"id,username",access_token:w}),P=await this.graph(`/me?${h.toString()}`,{method:"GET"});if(!P.id)throw new z("Could not resolve the Threads account for this token.",400,JSON.stringify(P));return{threadsUserId:P.id,username:P.username,accessToken:w}}async publish(w,h){if(!w.accessToken)throw Error("Threads access token is missing for this identity.");let P=w.did;if(!P)throw Error("Threads account id is required to publish.");if(h.text.length>this.characterLimit)throw Error(`Threads posts must be ${this.characterLimit} characters or fewer.`);let S=h.media?.[0],$=new URLSearchParams({text:h.text,access_token:w.accessToken});if(S?.url)$.set("media_type","IMAGE"),$.set("image_url",S.url);else $.set("media_type","TEXT");let J=await this.graph(`/${P}/threads`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:$.toString()});if(!J.id)throw new z("Threads did not return a media container id.",400,JSON.stringify(J));let D=await this.graph(`/${P}/threads_publish`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({creation_id:J.id,access_token:w.accessToken}).toString()});if(!D.id)throw new z("Threads did not return a published post id.",400,JSON.stringify(D));let u=await this.graph(`/${D.id}?fields=permalink&access_token=${encodeURIComponent(w.accessToken)}`,{method:"GET"}).catch(()=>{return});return{provider:this.provider,uri:D.id,url:u?.permalink}}async timeline(w,h={}){return{items:[]}}async graph(w,h){let P=await fetch(`${this.graphBase}/${this.graphVersion}${w}`,h),S=await P.text(),$={};try{$=S?JSON.parse(S):{}}catch{$={}}if(!P.ok||$?.error){let J=$?.error?.message||S||P.statusText;throw new z(`Threads API failed (${P.status}): ${J}`,P.status,S)}return $}}import{Buffer as I}from"buffer";import{createHash as g,randomBytes as r}from"crypto";import{fetcher as K}from"@stacksjs/api";import{config as G}from"@stacksjs/config";class f extends N{baseUrl="https://twitter.com";apiUrl="https://api.twitter.com";codeVerifier=null;getConfig(){let w={clientId:G.services.twitter?.clientId??"",clientSecret:G.services.twitter?.clientSecret??"",redirectUrl:G.services.twitter?.redirectUrl??"",scopes:G.services.twitter?.scopes??["users.read","tweet.read"]};return this.setScopes(w.scopes),w}generateCodeVerifier(){return r(32).toString("base64").replace(/[^a-z0-9]/gi,"").substring(0,128)}generateCodeChallenge(w){return g("sha256").update(w).digest("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}async getAuthUrl(){let w=this.getState(),{clientId:h,redirectUrl:P,scopes:S}=this.getConfig();this.validateConfig(),this.codeVerifier=this.generateCodeVerifier();let $=this.generateCodeChallenge(this.codeVerifier);return`${this.baseUrl}/i/oauth2/authorize?${new URLSearchParams({client_id:h,redirect_uri:P,scope:S.join(" "),state:w,response_type:"code",code_challenge:$,code_challenge_method:"S256"}).toString()}`}async getAccessToken(w){let{clientId:h,clientSecret:P,redirectUrl:S}=this.getConfig();if(this.validateConfig(),!this.codeVerifier)throw Error("Code verifier not found. Please ensure getAuthUrl() is called first.");let $=I.from(`${h}:${P}`).toString("base64"),J=await K.withHeaders({Authorization:`Basic ${$}`,"Content-Type":"application/x-www-form-urlencoded"}).post(`${this.apiUrl}/2/oauth2/token`,{code:w,grant_type:"authorization_code",redirect_uri:S,code_verifier:this.codeVerifier});if(J.data.error)throw Error(`Twitter OAuth error: ${J.data.error_description}`);return J.data.access_token}async getUserByToken(w){let h=await K.withHeaders({Authorization:`Bearer ${w}`}).get(`${this.apiUrl}/2/users/me?user.fields=profile_image_url`);return{id:h.data.id,nickname:h.data.username,name:h.data.name,email:h.data.email??null,avatar:h.data.profile_image_url??null,token:w,raw:h.data}}validateConfig(){let{clientId:w,clientSecret:h,redirectUrl:P}=this.getConfig();if(!w)throw new B("Twitter client ID not provided");if(!h)throw new B("Twitter client secret not provided");if(!P)throw new B("Twitter redirect URL not provided")}getTokenUrl(){return`${this.apiUrl}/2/oauth2/token`}}class a{accessToken;refreshToken;expiresIn;approvedScopes;constructor(w,h=null,P=null,S=[]){this.accessToken=w;this.refreshToken=h;this.expiresIn=P;this.approvedScopes=S}}export{j as escapeLinkedInText,f as TwitterProvider,a as Token,y as ThreadsPublishingDriver,z as ThreadsApiError,E as LinkedInPublishingDriver,M as LinkedInApiError,m as InvalidStateException,A as InstagramPublishingDriver,O as InstagramApiError,k as GoogleProvider,x as GitHubProvider,C as FacebookProvider,B as ConfigException,U as BlueskyPublishingDriver,T as BlueskyApiError,l as AppleProvider,N as AbstractProvider};
|
|
2
|
+
var U=import.meta.require;class F{clientId;clientSecret;redirectUrl;parameters={};_scopes=[];scopeSeparator=",";_stateless=!1;_usesPKCE=!1;_state=null;user=null;constructor(z){this.clientId=z.clientId,this.clientSecret=z.clientSecret,this.redirectUrl=z.redirectUrl}getCodeFields(z=null){let D={client_id:this.clientId,redirect_uri:this.redirectUrl,scope:this.formatScopes(this.getScopes(),this.scopeSeparator),response_type:"code"};if(this.usesState())D.state=z;if(this.usesPKCE())D.code_challenge=this.getCodeChallenge(),D.code_challenge_method=this.getCodeChallengeMethod();return{...D,...this.parameters}}formatScopes(z,D){return z.join(D)}async userFromToken(z){return{...await this.getUserByToken(z),token:z}}scopes(z){let D=Array.isArray(z)?z:[z];return this._scopes=[...new Set([...this._scopes,...D])],this}setScopes(z){let D=Array.isArray(z)?z:[z];return this._scopes=[...new Set(D)],this}getScopes(){return this._scopes}setRedirectUrl(z){if(typeof z!=="string"||z.length===0)throw Error("[socials] setRedirectUrl requires a non-empty string");let D;try{D=new URL(z)}catch{throw Error(`[socials] setRedirectUrl: invalid URL: ${z}`)}if(D.protocol!=="https:"&&D.protocol!=="http:")throw Error(`[socials] setRedirectUrl protocol must be http(s)://, got ${D.protocol}`);return this.redirectUrl=z,this}withState(z){if(typeof z!=="string"||z.length===0)throw Error("[socials] withState requires a non-empty string");return this._state=z,this}resolveState(){return this._state??this.getState()}usesState(){return!this._stateless}validateState(z,D){if(typeof z!=="string"||typeof D!=="string")return!1;if(z.length===0||D.length===0)return!1;if(z.length!==D.length)return!1;try{let{timingSafeEqual:G}=U("crypto");return G(Buffer.from(z,"utf8"),Buffer.from(D,"utf8"))}catch{let G=0;for(let J=0;J<z.length;J++)G|=z.charCodeAt(J)^D.charCodeAt(J);return G===0}}isStateless(){return this._stateless}stateless(){return this._stateless=!0,this}getState(){let z=new Uint8Array(32);return crypto.getRandomValues(z),Array.from(z).map((D)=>D.toString(16).padStart(2,"0")).join("")}usesPKCE(){return this._usesPKCE}enablePKCE(){return this._usesPKCE=!0,this}getCodeVerifier(){let z=new Uint8Array(48);return crypto.getRandomValues(z),Array.from(z).map((D)=>D.toString(16).padStart(2,"0")).join("")}async getCodeChallenge(){let D=new TextEncoder().encode(this.getCodeVerifier()),G=await crypto.subtle.digest("SHA-256",D),{Buffer:J}=await import("buffer");return J.from(new Uint8Array(G)).toString("base64url")}getCodeChallengeMethod(){return"S256"}with(z){return this.parameters=z,this}buildAuthUrlFromBase(z,D){let G=new URLSearchParams(this.getCodeFields(D));return`${z}?${G.toString()}`}}import{Buffer as S}from"buffer";import{createPrivateKey as I,sign as E}from"crypto";import{config as M}from"@stacksjs/config";class C extends Error{constructor(z="Invalid state"){super(z);this.name="InvalidStateException"}}class Z extends Error{constructor(z){super(z);this.name="ConfigException"}}class b extends F{baseUrl="https://appleid.apple.com";teamId="";keyId="";privateKey="";constructor(z){super(z);this.teamId=z.teamId??"",this.keyId=z.keyId??"",this.privateKey=z.privateKey??""}getConfig(){let z={clientId:this.clientId||(M.services.apple?.clientId??""),teamId:this.teamId||(M.services.apple?.teamId??""),keyId:this.keyId||(M.services.apple?.keyId??""),privateKey:(this.privateKey||(M.services.apple?.privateKey??"")).replace(/\\n/g,`
|
|
3
|
+
`),redirectUrl:this.redirectUrl||(M.services.apple?.redirectUrl??""),scopes:this._scopes.length>0?this._scopes:M.services.apple?.scopes??["name","email"]};return this.setScopes(z.scopes),z}async getAuthUrl(){let z=this.resolveState(),{clientId:D,redirectUrl:G,scopes:J}=this.getConfig();this.validateConfig();let N={client_id:D,redirect_uri:G,scope:J.join(" "),state:z,response_type:"code",...this.parameters};if(J.length>0)N.response_mode="form_post";return`${this.baseUrl}/auth/authorize?${new URLSearchParams(N).toString()}`}async getAccessToken(z){let{clientId:D,redirectUrl:G}=this.getConfig();this.validateConfig();let J=await fetch(`${this.baseUrl}/auth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:z,redirect_uri:G,client_id:D,client_secret:this.generateClientSecret()})}),N=await J.json();if(!J.ok||N.error)throw Error(`Apple OAuth error: ${N.error_description??N.error??`HTTP ${J.status}`}`);if(!N.id_token)throw Error("Apple OAuth error: token response contained no id_token");return N.id_token}async getUserByToken(z){let{clientId:D}=this.getConfig(),G=this.decodeIdToken(z),J=G.iss===this.baseUrl,N=Array.isArray(G.aud)?G.aud.includes(D):G.aud===D,Q=typeof G.exp==="number"&&G.exp*1000>Date.now();if(!J||!N||!Q)throw Error("Apple OAuth error: id_token claims failed validation (iss/aud/exp)");if(!G.sub)throw Error("Apple OAuth error: id_token has no subject");let X=typeof G.email==="string"?G.email:null,Y=null;if(G.email_verified===!0||G.email_verified==="true")Y=!0;else if(G.email_verified===!1||G.email_verified==="false")Y=!1;return{id:String(G.sub),nickname:null,name:"",email:X,emailVerified:Y,avatar:null,token:z,raw:G}}generateClientSecret(){let{clientId:z,teamId:D,keyId:G,privateKey:J}=this.getConfig(),N=Math.floor(Date.now()/1000),Q={alg:"ES256",kid:G,typ:"JWT"},X={iss:D,iat:N,exp:N+3600,aud:this.baseUrl,sub:z},Y=`${this.base64urlJson(Q)}.${this.base64urlJson(X)}`,_;try{_=I(J)}catch($){throw new Z(`Apple private key could not be parsed: ${$ instanceof Error?$.message:String($)}`)}let H=E("sha256",S.from(Y),{key:_,dsaEncoding:"ieee-p1363"});return`${Y}.${H.toString("base64url")}`}decodeIdToken(z){let D=z.split(".");if(D.length!==3)throw Error("Apple OAuth error: malformed id_token");return JSON.parse(S.from(D[1],"base64url").toString("utf8"))}base64urlJson(z){return S.from(JSON.stringify(z)).toString("base64url")}validateConfig(){let{clientId:z,teamId:D,keyId:G,privateKey:J,redirectUrl:N}=this.getConfig();if(!z)throw new Z("Apple client ID (Service ID) not provided");if(!D)throw new Z("Apple team ID not provided");if(!G)throw new Z("Apple key ID not provided");if(!J)throw new Z("Apple private key not provided");if(!N)throw new Z("Apple redirect URL not provided")}getTokenUrl(){return`${this.baseUrl}/auth/token`}}class T extends Error{status;body;constructor(z,D,G){super(z);this.status=D;this.body=G;this.name="BlueskyApiError"}get isAuthError(){return this.status===400||this.status===401||this.status===403}}var x=new TextEncoder;function W(z){return x.encode(z).length}function k(z){let D=[],G=/https?:\/\/[^\s<>"']+/g;for(let X of z.matchAll(G)){let Y=X[0].replace(/[),.;!?]+$/,"");D.push({byteStart:W(z.slice(0,X.index)),byteEnd:W(z.slice(0,X.index))+W(Y),type:"link",value:Y})}let J=(X,Y)=>D.some((_)=>_.type==="link"&&X<_.byteEnd&&Y>_.byteStart),N=/(^|\s)(#[A-Za-z0-9_]+)/g;for(let X of z.matchAll(N)){let Y=X[1],_=X[2];if(Y===void 0||_===void 0)continue;if(/^#\d+$/.test(_))continue;let H=(X.index??0)+Y.length,$=W(z.slice(0,H)),O=$+W(_);if(J($,O))continue;D.push({byteStart:$,byteEnd:O,type:"tag",value:_.slice(1)})}let Q=/(^|\s)(@[a-z0-9][a-z0-9.-]*\.[a-z]{2,})/gi;for(let X of z.matchAll(Q)){let Y=X[1],_=X[2];if(Y===void 0||_===void 0)continue;let H=(X.index??0)+Y.length,$=W(z.slice(0,H)),O=$+W(_);if(J($,O))continue;D.push({byteStart:$,byteEnd:O,type:"mention",value:_.slice(1).replace(/\.+$/,"")})}return D.sort((X,Y)=>X.byteStart-Y.byteStart)}class h{provider="bluesky";characterLimit=300;service;constructor(z={}){this.service=z.service||"https://bsky.social"}async createSession(z){let D=z.identifier.trim(),G=z.password.trim();if(!D)throw Error("Bluesky identifier is required.");if(!G)throw Error("Bluesky app password is required.");let J=await this.post("/xrpc/com.atproto.server.createSession",{identifier:D,password:G}),N=await this.getProfile({did:J.did,handle:J.handle,accessToken:J.accessJwt,refreshToken:J.refreshJwt}).catch(()=>{return});return{did:J.did,handle:J.handle,displayName:N?.displayName,accessJwt:J.accessJwt,refreshJwt:J.refreshJwt}}async refreshSession(z){if(!z)throw Error("Bluesky refresh token is required.");let D=await this.post("/xrpc/com.atproto.server.refreshSession",void 0,{authorization:`Bearer ${z}`});return{did:D.did,handle:D.handle,accessJwt:D.accessJwt,refreshJwt:D.refreshJwt}}async publish(z,D){let G=z.did||z.handle;if(!z.accessToken)throw Error("Bluesky access token is missing for this identity.");if(!G)throw Error("Bluesky identity DID or handle is required.");if(D.text.length>this.characterLimit)throw Error(`Bluesky posts must be ${this.characterLimit} characters or fewer.`);let J={$type:"app.bsky.feed.post",text:D.text,createdAt:D.scheduledAt||new Date().toISOString()};if(D.langs?.length)J.langs=D.langs;if(D.reply)J.reply=D.reply;let N=D.facets??await this.buildFacets(D.text);if(N.length)J.facets=N;if(D.external)J.embed={$type:"app.bsky.embed.external",external:{uri:D.external.uri,title:D.external.title,description:D.external.description||""}};let Q=(D.media||[]).filter((Y)=>Y.bytes?.length).slice(0,4);if(Q.length){let Y=[];for(let _ of Q){let H=await this.uploadBlob(z,_.bytes,_.mimeType||"image/jpeg");Y.push({image:H,alt:_.altText||""})}J.embed={$type:"app.bsky.embed.images",images:Y}}let X=await this.post("/xrpc/com.atproto.repo.createRecord",{repo:G,collection:"app.bsky.feed.post",record:J},{authorization:`Bearer ${z.accessToken}`});return{provider:this.provider,uri:X.uri,cid:X.cid,url:this.toPostUrl(z.handle,X.uri)}}async postMetrics(z,D){if(!z.accessToken)throw Error("Bluesky access token is missing for this identity.");if(D.length===0)return[];let G=new URL(`${this.service}/xrpc/app.bsky.feed.getPosts`);for(let N of D.slice(0,25))G.searchParams.append("uris",N);return((await this.request(G,{headers:{authorization:`Bearer ${z.accessToken}`}})).posts||[]).map((N)=>({uri:N.uri,likeCount:N.likeCount||0,repostCount:N.repostCount||0,replyCount:N.replyCount||0}))}async timeline(z,D={}){if(!z.accessToken)throw Error("Bluesky access token is missing for this identity.");let G=new URL(`${this.service}/xrpc/app.bsky.feed.getTimeline`);if(G.searchParams.set("limit",String(Math.min(Math.max(D.limit||30,1),100))),D.cursor)G.searchParams.set("cursor",D.cursor);let J=await this.request(G,{headers:{authorization:`Bearer ${z.accessToken}`}});return{cursor:J.cursor,items:(J.feed||[]).flatMap((N)=>{let Q=N.post;if(!Q?.uri||!Q.author?.handle)return[];return[{uri:Q.uri,authorHandle:Q.author.handle,authorName:Q.author.displayName,authorAvatar:Q.author.avatar,postUrl:this.toPostUrl(Q.author.handle,Q.uri),body:Q.record?.text||"",postedAt:Q.record?.createdAt||new Date().toISOString(),likeCount:Q.likeCount||0,repostCount:Q.repostCount||0,replyCount:Q.replyCount||0}]})}}async getProfile(z){if(!z.accessToken)throw Error("Bluesky access token is missing for this identity.");let D=z.did||z.handle;if(!D)throw Error("Bluesky identity DID or handle is required.");let G=new URL(`${this.service}/xrpc/app.bsky.actor.getProfile`);return G.searchParams.set("actor",D),await this.request(G,{headers:{authorization:`Bearer ${z.accessToken}`}})}async buildFacets(z){let D=[];for(let G of k(z)){let J=null;if(G.type==="link")J={$type:"app.bsky.richtext.facet#link",uri:G.value};else if(G.type==="tag")J={$type:"app.bsky.richtext.facet#tag",tag:G.value};else if(G.type==="mention"){let N=await this.resolveHandle(G.value);if(N)J={$type:"app.bsky.richtext.facet#mention",did:N}}if(J)D.push({index:{byteStart:G.byteStart,byteEnd:G.byteEnd},features:[J]})}return D}async resolveHandle(z){try{let D=new URL(`${this.service}/xrpc/com.atproto.identity.resolveHandle`);return D.searchParams.set("handle",z),(await this.request(D,{})).did||null}catch{return null}}async uploadBlob(z,D,G){if(!z.accessToken)throw Error("Bluesky access token is missing for this identity.");if(D.length>1e6)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":G,authorization:`Bearer ${z.accessToken}`},body:new Uint8Array(D)})).blob}async post(z,D,G={}){return await this.request(new URL(`${this.service}${z}`),{method:"POST",headers:{...D===void 0?{}:{"content-type":"application/json"},...G},...D===void 0?{}:{body:JSON.stringify(D)}})}async request(z,D){let G=await fetch(z,D),J=await G.text();if(!G.ok)throw new T(`Bluesky API failed (${G.status}): ${J||G.statusText}`,G.status,J);return J?JSON.parse(J):{}}toPostUrl(z,D){let G=D.split("/").pop();return`https://bsky.app/profile/${z}/post/${G}`}}import{fetcher as j}from"@stacksjs/api";import{config as P}from"@stacksjs/config";class m extends F{baseUrl="https://www.facebook.com";apiUrl="https://graph.facebook.com";getConfig(){let z={clientId:P.services.facebook?.clientId??"",clientSecret:P.services.facebook?.clientSecret??"",redirectUrl:P.services.facebook?.redirectUrl??"",scopes:P.services.facebook?.scopes??["email","public_profile"]};return this.setScopes(z.scopes),z}async getAuthUrl(){let z=this.getState(),{clientId:D,redirectUrl:G,scopes:J}=this.getConfig();return this.validateConfig(),`${this.baseUrl}/v18.0/dialog/oauth?${new URLSearchParams({client_id:D,redirect_uri:G,scope:J.join(","),state:z,response_type:"code"}).toString()}`}async getAccessToken(z){let{clientId:D,clientSecret:G,redirectUrl:J}=this.getConfig();this.validateConfig();let N=await j.get(`${this.apiUrl}/v18.0/oauth/access_token?${new URLSearchParams({client_id:D,client_secret:G,redirect_uri:J,code:z}).toString()}`);if(N.data.error)throw Error(`Facebook OAuth error: ${N.data.error.message}`);return N.data.access_token}async getUserByToken(z){let D=await j.get(`${this.apiUrl}/v18.0/me?${new URLSearchParams({access_token:z,fields:"id,name,email,picture"}).toString()}`);return{id:D.data.id,nickname:null,name:D.data.name,email:D.data.email??null,avatar:D.data.picture?.data.url??null,token:z,raw:D.data}}validateConfig(){let{clientId:z,clientSecret:D,redirectUrl:G}=this.getConfig();if(!z)throw new Z("Facebook client ID not provided");if(!D)throw new Z("Facebook client secret not provided");if(!G)throw new Z("Facebook redirect URL not provided")}getTokenUrl(){return`${this.apiUrl}/v18.0/oauth/access_token`}}import{fetcher as L}from"@stacksjs/api";import{config as V}from"@stacksjs/config";class g extends F{baseUrl="https://github.com";apiUrl="https://api.github.com";getConfig(){let z={clientId:this.clientId||(V.services.github?.clientId??""),clientSecret:this.clientSecret||(V.services.github?.clientSecret??""),redirectUrl:this.redirectUrl||(V.services.github?.redirectUrl??""),scopes:this._scopes.length>0?this._scopes:V.services.github?.scopes??["read:user","user:email"]};return this.setScopes(z.scopes),z}async getAuthUrl(){let z=this.resolveState(),{clientId:D,redirectUrl:G,scopes:J}=this.getConfig();return this.validateConfig(),`${this.baseUrl}/login/oauth/authorize?${new URLSearchParams({client_id:D,redirect_uri:G,scope:J.join(" "),state:z,response_type:"code",...this.parameters}).toString()}`}async getAccessToken(z){let{clientId:D,clientSecret:G,redirectUrl:J}=this.getConfig();this.validateConfig();let N=await L.post(`${this.baseUrl}/login/oauth/access_token`,{client_id:D,client_secret:G,code:z,redirect_uri:J});if(N.data.error)throw Error(`GitHub OAuth error: ${N.data.error_description}`);return N.data.access_token}async getUserByToken(z){let[D,G]=await Promise.all([L.withHeaders({Accept:"application/vnd.github.v3+json",Authorization:`token ${z}`}).get(`${this.apiUrl}/user`),L.withHeaders({Accept:"application/vnd.github.v3+json",Authorization:`token ${z}`}).get(`${this.apiUrl}/user/emails`)]),J=this.pickEmail(G.data);return{id:D.data.id.toString(),nickname:D.data.login,name:D.data.name??D.data.login,email:J?.email??D.data.email??null,emailVerified:J?J.verified:null,avatar:D.data.avatar_url,token:z,raw:D.data}}pickEmail(z){if(!Array.isArray(z)||z.length===0)return null;let D=z.find((J)=>J.primary&&J.verified),G=z.find((J)=>J.verified);return D??G??z.find((J)=>J.primary)??z[0]??null}getEmail(z){return this.pickEmail(z)?.email??null}validateConfig(){let{clientId:z,clientSecret:D,redirectUrl:G}=this.getConfig();if(!z)throw new Z("GitHub client ID not provided");if(!D)throw new Z("GitHub client secret not provided");if(!G)throw new Z("GitHub redirect URL not provided")}getTokenUrl(){return`${this.baseUrl}/login/oauth/access_token`}}import{fetcher as v}from"@stacksjs/api";import{config as q}from"@stacksjs/config";class f extends F{baseUrl="https://accounts.google.com";apiUrl="https://www.googleapis.com";getConfig(){let z={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(z.scopes),z}async getAuthUrl(){let z=this.resolveState(),{clientId:D,redirectUrl:G,scopes:J}=this.getConfig();return this.validateConfig(),`${this.baseUrl}/o/oauth2/v2/auth?${new URLSearchParams({client_id:D,redirect_uri:G,scope:J.join(" "),state:z,response_type:"code",access_type:"offline",prompt:"consent",...this.parameters}).toString()}`}async getAccessToken(z){let{clientId:D,clientSecret:G,redirectUrl:J}=this.getConfig();this.validateConfig();let N=await v.post(`${this.baseUrl}/oauth2/v4/token`,{client_id:D,client_secret:G,code:z,redirect_uri:J,grant_type:"authorization_code"});if(N.data.error)throw Error(`Google OAuth error: ${N.data.error_description}`);return N.data.access_token}async getUserByToken(z){let D=await v.withHeaders({Authorization:`Bearer ${z}`}).get(`${this.apiUrl}/oauth2/v2/userinfo`);return{id:D.data.id,nickname:D.data.given_name,name:D.data.name,email:D.data.email,emailVerified:typeof D.data.verified_email==="boolean"?D.data.verified_email:null,avatar:D.data.picture,token:z,raw:D.data}}validateConfig(){let{clientId:z,clientSecret:D,redirectUrl:G}=this.getConfig();if(!z)throw new Z("Google client ID not provided");if(!D)throw new Z("Google client secret not provided");if(!G)throw new Z("Google redirect URL not provided")}getTokenUrl(){return`${this.baseUrl}/oauth2/v4/token`}}class w extends Error{status;body;constructor(z,D,G){super(z);this.status=D;this.body=G;this.name="InstagramApiError"}get isAuthError(){return this.status===401||this.status===403||this.status===190}}class u{provider="instagram";characterLimit=2200;graphVersion;authBase;graphBase;constructor(z={}){this.graphVersion=z.graphVersion||"v21.0",this.authBase=z.authBase||"https://www.facebook.com",this.graphBase=z.graphBase||"https://graph.facebook.com"}getAuthUrl(z){let D=new URLSearchParams({client_id:z.clientId,redirect_uri:z.redirectUrl,scope:z.scopes.join(","),state:z.state,response_type:"code"});return`${this.authBase}/${this.graphVersion}/dialog/oauth?${D.toString()}`}async exchangeCode(z){let D=new URLSearchParams({client_id:z.clientId,client_secret:z.clientSecret,redirect_uri:z.redirectUrl,code:z.code}),G=await this.graph(`/oauth/access_token?${D.toString()}`,{method:"GET"});if(!G.access_token)throw new w("Facebook did not return an access token.",400,JSON.stringify(G));return{accessToken:G.access_token,expiresIn:G.expires_in}}async resolveAccount(z){let D=new URLSearchParams({fields:"name,access_token,instagram_business_account{id,username}",access_token:z}),G=await this.graph(`/me/accounts?${D.toString()}`,{method:"GET"}),J=(G.data||[]).find((Q)=>Q.instagram_business_account?.id),N=J?.instagram_business_account;if(!N?.id||!J?.access_token)throw new w("No Instagram Business account is linked to your Facebook Pages.",400,JSON.stringify(G));return{igUserId:N.id,username:N.username,pageAccessToken:J.access_token}}async publish(z,D){if(!z.accessToken)throw Error("Instagram access token is missing for this identity.");let G=z.did;if(!G)throw Error("Instagram account id is required to publish.");let J=D.media?.[0];if(!J?.url)throw Error("Instagram requires an image to post.");if(D.text.length>this.characterLimit)throw Error(`Instagram captions must be ${this.characterLimit} characters or fewer.`);let N=await this.graph(`/${G}/media`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({image_url:J.url,caption:D.text,access_token:z.accessToken}).toString()});if(!N.id)throw new w("Instagram did not return a media container id.",400,JSON.stringify(N));let Q=await this.graph(`/${G}/media_publish`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({creation_id:N.id,access_token:z.accessToken}).toString()}),X=await this.graph(`/${Q.id}?fields=permalink&access_token=${encodeURIComponent(z.accessToken)}`,{method:"GET"}).catch(()=>{return});return{provider:this.provider,uri:Q.id,url:X?.permalink}}async timeline(z,D={}){return{items:[]}}async graph(z,D){let G=await fetch(`${this.graphBase}/${this.graphVersion}${z}`,D),J=await G.text(),N={};try{N=J?JSON.parse(J):{}}catch{N={}}if(!G.ok||N?.error){let Q=N?.error?.message||J||G.statusText;throw new w(`Instagram API failed (${G.status}): ${Q}`,G.status,J)}return N}}class R extends Error{status;body;constructor(z,D,G){super(z);this.status=D;this.body=G;this.name="LinkedInApiError"}get isAuthError(){return this.status===401||this.status===403}}class y{provider="linkedin";characterLimit=3000;apiVersion;authBase;apiBase;constructor(z={}){this.apiVersion=z.apiVersion||"202405",this.authBase=z.authBase||"https://www.linkedin.com",this.apiBase=z.apiBase||"https://api.linkedin.com"}getAuthUrl(z){let D=new URLSearchParams({response_type:"code",client_id:z.clientId,redirect_uri:z.redirectUrl,scope:z.scopes.join(" "),state:z.state});return`${this.authBase}/oauth/v2/authorization?${D.toString()}`}async exchangeCode(z){let D=new URLSearchParams({grant_type:"authorization_code",code:z.code,redirect_uri:z.redirectUrl,client_id:z.clientId,client_secret:z.clientSecret}),G=await this.request(`${this.authBase}/oauth/v2/accessToken`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:D.toString()});if(!G.access_token)throw new R("LinkedIn did not return an access token.",400,JSON.stringify(G));return{accessToken:G.access_token,expiresIn:G.expires_in,scope:G.scope}}async getProfile(z){if(!z)throw Error("LinkedIn access token is required.");let D=await this.request(`${this.apiBase}/v2/userinfo`,{headers:{authorization:`Bearer ${z}`}});if(!D.sub)throw new R("LinkedIn profile is missing a subject id.",400,JSON.stringify(D));return{sub:D.sub,name:D.name,picture:D.picture}}async publish(z,D){if(!z.accessToken)throw Error("LinkedIn access token is missing for this identity.");let G=z.did;if(!G)throw Error("LinkedIn member URN is required to publish.");if(D.text.length>this.characterLimit)throw Error(`LinkedIn posts must be ${this.characterLimit} characters or fewer.`);let J={author:G,commentary:l(D.text),visibility:"PUBLIC",distribution:{feedDistribution:"MAIN_FEED",targetEntities:[],thirdPartyDistributionChannels:[]},lifecycleState:"PUBLISHED",isReshareDisabledByAuthor:!1};if(D.external)J.content={article:{source:D.external.uri,title:D.external.title,description:D.external.description||""}};let N=await fetch(`${this.apiBase}/rest/posts`,{method:"POST",headers:{authorization:`Bearer ${z.accessToken}`,"content-type":"application/json","linkedin-version":this.apiVersion,"x-restli-protocol-version":"2.0.0"},body:JSON.stringify(J)}),Q=await N.text();if(!N.ok)throw new R(`LinkedIn API failed (${N.status}): ${Q||N.statusText}`,N.status,Q);let X=N.headers.get("x-restli-id")||N.headers.get("x-linkedin-id")||"";return{provider:this.provider,uri:X,url:X?`https://www.linkedin.com/feed/update/${X}`:void 0}}async timeline(z,D={}){return{items:[]}}async request(z,D){let G=await fetch(z,D),J=await G.text();if(!G.ok)throw new R(`LinkedIn API failed (${G.status}): ${J||G.statusText}`,G.status,J);return J?JSON.parse(J):{}}}function l(z){return z.replace(/[\\|{}@[\]()<>#*_~]/g,"\\$&")}class K extends Error{status;body;constructor(z,D,G){super(z);this.status=D;this.body=G;this.name="ThreadsApiError"}get isAuthError(){return this.status===401||this.status===403||this.status===190}}class c{provider="threads";characterLimit=500;graphVersion;authBase;graphBase;constructor(z={}){this.graphVersion=z.graphVersion||"v1.0",this.authBase=z.authBase||"https://threads.net",this.graphBase=z.graphBase||"https://graph.threads.net"}getAuthUrl(z){let D=new URLSearchParams({client_id:z.clientId,redirect_uri:z.redirectUrl,scope:z.scopes.join(","),response_type:"code",state:z.state});return`${this.authBase}/oauth/authorize?${D.toString()}`}async exchangeCode(z){let D=await fetch(`${this.graphBase}/oauth/access_token`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:z.clientId,client_secret:z.clientSecret,grant_type:"authorization_code",redirect_uri:z.redirectUrl,code:z.code}).toString()}),G=await D.text(),J={};try{J=G?JSON.parse(G):{}}catch{J={}}if(!D.ok||J?.error||!J?.access_token){let N=J?.error_message||J?.error?.message||G||D.statusText;throw new K(`Threads token exchange failed (${D.status}): ${N}`,D.status,G)}return{accessToken:J.access_token,userId:J.user_id!=null?String(J.user_id):void 0,expiresIn:J.expires_in}}async resolveAccount(z){let D=new URLSearchParams({fields:"id,username",access_token:z}),G=await this.graph(`/me?${D.toString()}`,{method:"GET"});if(!G.id)throw new K("Could not resolve the Threads account for this token.",400,JSON.stringify(G));return{threadsUserId:G.id,username:G.username,accessToken:z}}async publish(z,D){if(!z.accessToken)throw Error("Threads access token is missing for this identity.");let G=z.did;if(!G)throw Error("Threads account id is required to publish.");if(D.text.length>this.characterLimit)throw Error(`Threads posts must be ${this.characterLimit} characters or fewer.`);let J=D.media?.[0],N=new URLSearchParams({text:D.text,access_token:z.accessToken});if(J?.url)N.set("media_type","IMAGE"),N.set("image_url",J.url);else N.set("media_type","TEXT");let Q=await this.graph(`/${G}/threads`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:N.toString()});if(!Q.id)throw new K("Threads did not return a media container id.",400,JSON.stringify(Q));let X=await this.graph(`/${G}/threads_publish`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({creation_id:Q.id,access_token:z.accessToken}).toString()});if(!X.id)throw new K("Threads did not return a published post id.",400,JSON.stringify(X));let Y=await this.graph(`/${X.id}?fields=permalink&access_token=${encodeURIComponent(z.accessToken)}`,{method:"GET"}).catch(()=>{return});return{provider:this.provider,uri:X.id,url:Y?.permalink}}async timeline(z,D={}){return{items:[]}}async graph(z,D){let G=await fetch(`${this.graphBase}/${this.graphVersion}${z}`,D),J=await G.text(),N={};try{N=J?JSON.parse(J):{}}catch{N={}}if(!G.ok||N?.error){let Q=N?.error?.message||J||G.statusText;throw new K(`Threads API failed (${G.status}): ${Q}`,G.status,J)}return N}}import{Buffer as d}from"buffer";import{createHash as p,randomBytes as a}from"crypto";import{fetcher as A}from"@stacksjs/api";import{config as B}from"@stacksjs/config";class r extends F{baseUrl="https://twitter.com";apiUrl="https://api.twitter.com";codeVerifier=null;getConfig(){let z={clientId:B.services.twitter?.clientId??"",clientSecret:B.services.twitter?.clientSecret??"",redirectUrl:B.services.twitter?.redirectUrl??"",scopes:B.services.twitter?.scopes??["users.read","tweet.read"]};return this.setScopes(z.scopes),z}generateCodeVerifier(){return a(32).toString("base64").replace(/[^a-z0-9]/gi,"").substring(0,128)}generateCodeChallenge(z){return p("sha256").update(z).digest("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}async getAuthUrl(){let z=this.getState(),{clientId:D,redirectUrl:G,scopes:J}=this.getConfig();this.validateConfig(),this.codeVerifier=this.generateCodeVerifier();let N=this.generateCodeChallenge(this.codeVerifier);return`${this.baseUrl}/i/oauth2/authorize?${new URLSearchParams({client_id:D,redirect_uri:G,scope:J.join(" "),state:z,response_type:"code",code_challenge:N,code_challenge_method:"S256"}).toString()}`}async getAccessToken(z){let{clientId:D,clientSecret:G,redirectUrl:J}=this.getConfig();if(this.validateConfig(),!this.codeVerifier)throw Error("Code verifier not found. Please ensure getAuthUrl() is called first.");let N=d.from(`${D}:${G}`).toString("base64"),Q=await A.withHeaders({Authorization:`Basic ${N}`,"Content-Type":"application/x-www-form-urlencoded"}).post(`${this.apiUrl}/2/oauth2/token`,{code:z,grant_type:"authorization_code",redirect_uri:J,code_verifier:this.codeVerifier});if(Q.data.error)throw Error(`Twitter OAuth error: ${Q.data.error_description}`);return Q.data.access_token}async getUserByToken(z){let D=await A.withHeaders({Authorization:`Bearer ${z}`}).get(`${this.apiUrl}/2/users/me?user.fields=profile_image_url`);return{id:D.data.id,nickname:D.data.username,name:D.data.name,email:D.data.email??null,avatar:D.data.profile_image_url??null,token:z,raw:D.data}}validateConfig(){let{clientId:z,clientSecret:D,redirectUrl:G}=this.getConfig();if(!z)throw new Z("Twitter client ID not provided");if(!D)throw new Z("Twitter client secret not provided");if(!G)throw new Z("Twitter redirect URL not provided")}getTokenUrl(){return`${this.apiUrl}/2/oauth2/token`}}class o{accessToken;refreshToken;expiresIn;approvedScopes;constructor(z,D=null,G=null,J=[]){this.accessToken=z;this.refreshToken=D;this.expiresIn=G;this.approvedScopes=J}}export{l as escapeLinkedInText,k as detectFacetCandidates,r as TwitterProvider,o as Token,c as ThreadsPublishingDriver,K as ThreadsApiError,y as LinkedInPublishingDriver,R as LinkedInApiError,C as InvalidStateException,u as InstagramPublishingDriver,w as InstagramApiError,f as GoogleProvider,g as GitHubProvider,m as FacebookProvider,Z as ConfigException,h as BlueskyPublishingDriver,T as BlueskyApiError,b as AppleProvider,F as AbstractProvider};
|
package/dist/types.d.ts
CHANGED
|
@@ -113,10 +113,17 @@ export declare interface PublishPostInput {
|
|
|
113
113
|
title: string
|
|
114
114
|
description?: string
|
|
115
115
|
}
|
|
116
|
+
reply?: {
|
|
117
|
+
root: { uri: string, cid: string }
|
|
118
|
+
parent: { uri: string, cid: string }
|
|
119
|
+
}
|
|
116
120
|
media?: Array<{
|
|
117
|
-
url
|
|
121
|
+
url?: string
|
|
122
|
+
bytes?: Uint8Array
|
|
123
|
+
mimeType?: string
|
|
118
124
|
altText?: string
|
|
119
125
|
}>
|
|
126
|
+
facets?: unknown[]
|
|
120
127
|
}
|
|
121
128
|
export declare interface PublishedPost {
|
|
122
129
|
provider: SocialPublishingProvider
|
package/package.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"name": "@stacksjs/socials",
|
|
3
3
|
"type": "module",
|
|
4
4
|
"sideEffects": false,
|
|
5
|
-
"version": "0.70.
|
|
5
|
+
"version": "0.70.162",
|
|
6
6
|
"description": "A simple and elegant social authentication package for Stacks.",
|
|
7
7
|
"author": "Chris Breuer",
|
|
8
8
|
"contributors": [
|
|
@@ -53,7 +53,7 @@
|
|
|
53
53
|
},
|
|
54
54
|
"devDependencies": {
|
|
55
55
|
"better-dx": "^0.2.17",
|
|
56
|
-
"@stacksjs/error-handling": "0.70.
|
|
57
|
-
"@stacksjs/router": "0.70.
|
|
56
|
+
"@stacksjs/error-handling": "0.70.162",
|
|
57
|
+
"@stacksjs/router": "0.70.162"
|
|
58
58
|
}
|
|
59
59
|
}
|