switch to dedicated source maps
This commit is contained in:
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -1,89 +0,0 @@
|
||||
import * as TwitchAuth from "./TwitchAuth.ts";
|
||||
import { AccessTokenMaybeWithUserId, AuthProvider, AccessToken, AccessTokenWithUserId } from "@twurple/auth";
|
||||
|
||||
type Token = TwitchAuth.TwitchToken & AccessTokenMaybeWithUserId
|
||||
|
||||
function getTwurpleProxy(token: TwitchAuth.TwitchToken): Token {
|
||||
return new Proxy(token, {
|
||||
get(target, name, receiver) {
|
||||
return target[name.toString().replace(/[A-Z]/g, letter => `_${letter.toLowerCase()}`)]
|
||||
}
|
||||
}) as Token
|
||||
}
|
||||
|
||||
function hasScopes(token: Token, ...scopes: string[]) {
|
||||
if (!token) {
|
||||
return false
|
||||
}
|
||||
if (!scopes) {
|
||||
return true
|
||||
}
|
||||
for (const scope of scopes) {
|
||||
if (!token.scope.includes(scope)) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
export default class SugoiAuthProvider implements AuthProvider {
|
||||
|
||||
#token: Token
|
||||
clientId: string;
|
||||
|
||||
constructor(client_id: string) {
|
||||
this.clientId = client_id
|
||||
}
|
||||
|
||||
#setToken = (token: Token) => {
|
||||
this.#token = token
|
||||
return token
|
||||
}
|
||||
|
||||
async addUser(...scopes: string[]) {
|
||||
this.#token = await TwitchAuth.getUserToken(this.clientId, ...scopes).then(getTwurpleProxy).then(this.#setToken)
|
||||
return this.#token
|
||||
}
|
||||
|
||||
async addUserForToken(token: TwitchAuth.TwitchToken) {
|
||||
if (token.refresh_token) {
|
||||
this.#token = await TwitchAuth.refreshToken(this.clientId, token.refresh_token).then(getTwurpleProxy).then(this.#setToken)
|
||||
return this.#token
|
||||
}
|
||||
this.#token = await TwitchAuth.validateToken(token.access_token).then(getTwurpleProxy).then(this.#setToken)
|
||||
return this.#token
|
||||
}
|
||||
|
||||
removeUser() {
|
||||
this.#token = null
|
||||
}
|
||||
|
||||
async getAccessTokenForUser(user: string | number, ...scopeSets: string[][]) {
|
||||
if ((!scopeSets[0]) && (this.#token)) {
|
||||
return this.#token as AccessTokenWithUserId
|
||||
}
|
||||
for (const scopes of scopeSets) {
|
||||
if (hasScopes(this.#token, ...scopes)) {
|
||||
return this.#token as AccessTokenWithUserId
|
||||
}
|
||||
}
|
||||
this.#token = await TwitchAuth.getUserTokenPassive(this.clientId, ...(scopeSets[0] || [])).then(getTwurpleProxy).then(this.#setToken)
|
||||
return this.#token as AccessTokenWithUserId
|
||||
}
|
||||
|
||||
async getAnyAccessToken(user: string | number) {
|
||||
return this.#token || TwitchAuth.getAppToken(this.clientId).then(getTwurpleProxy)
|
||||
}
|
||||
|
||||
getCurrentScopesForUser(user: string | number) {
|
||||
if (!this.#token || this.#token instanceof Promise) {
|
||||
return []
|
||||
}
|
||||
return this.#token.scope
|
||||
}
|
||||
|
||||
async refreshAccessTokenForUser(user: string | number) {
|
||||
this.#token = await TwitchAuth.refreshToken(this.clientId, this.#token.refresh_token).then(this.#setToken)
|
||||
return this.#token as AccessTokenWithUserId
|
||||
}
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -1,210 +0,0 @@
|
||||
import fetch_retry from 'fetch-retry'
|
||||
const fetch = fetch_retry(globalThis.fetch, {
|
||||
retries: 10,
|
||||
retryDelay: attempts => attempts * 1000
|
||||
})
|
||||
|
||||
export interface TwitchToken {
|
||||
access_token: string
|
||||
expires_in: number
|
||||
obtainment_timestamp: number
|
||||
token_type: string
|
||||
user_id?: number
|
||||
scope?: Array<string>
|
||||
refresh_token?: string
|
||||
login?: string
|
||||
client_id?: string
|
||||
}
|
||||
|
||||
export interface AuthCode {
|
||||
code: string
|
||||
scope: string
|
||||
}
|
||||
|
||||
const redirect_uri = location.origin + location.pathname
|
||||
const proxy_uri = new URL('/oauth2/token', import.meta.url)
|
||||
|
||||
/**
|
||||
* Timestamp and return the token
|
||||
* @param {TwitchToken} token
|
||||
* @returns {TwitchToken}
|
||||
*/
|
||||
function stamp(token: TwitchToken): TwitchToken {
|
||||
token.obtainment_timestamp = Date.now()
|
||||
return token
|
||||
}
|
||||
|
||||
/**
|
||||
* https://dev.twitch.tv/docs/authentication/getting-tokens-oauth/#client-credentials-grant-flow
|
||||
* @param {string} client_id
|
||||
* @returns {Promise<TwitchToken>}
|
||||
*/
|
||||
export function getAppToken(client_id: string): Promise<TwitchToken> {
|
||||
const searchParams = new URLSearchParams({
|
||||
client_id: client_id,
|
||||
grant_type: 'client_credentials'
|
||||
})
|
||||
return fetch(proxy_uri, {
|
||||
method: 'POST',
|
||||
body: searchParams.toString(),
|
||||
headers: { 'content-type': 'application/x-www-form-urlencoded' }
|
||||
}).then(async function (response) {
|
||||
if (!response.ok) {
|
||||
throw new Error(await response.text())
|
||||
}
|
||||
const token = await response.json()
|
||||
return stamp(token)
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* https://dev.twitch.tv/docs/authentication/getting-tokens-oauth/#implicit-grant-flow
|
||||
* @param {string} client_id
|
||||
* @param {Array<string>|string} scopes
|
||||
* @returns {Promise<AuthCode>}
|
||||
*/
|
||||
export function requestAccessToken(client_id: string, ...scopes: Array<string>) {
|
||||
console.debug('requesting access token')
|
||||
const url = new URL('https://id.twitch.tv/oauth2/authorize')
|
||||
url.searchParams.append('response_type', 'token')
|
||||
url.searchParams.append('client_id', client_id)
|
||||
url.searchParams.append('scope', scopes.join(' '))
|
||||
location.assign(url + '&redirect_uri=' + redirect_uri)
|
||||
}
|
||||
|
||||
/**
|
||||
* https://dev.twitch.tv/docs/authentication/getting-tokens-oauth/#get-the-user-to-authorize-your-app
|
||||
* @param {string} client_id
|
||||
* @param {Array<string>|string} scopes
|
||||
* @returns {Promise<AuthCode>}
|
||||
*/
|
||||
export function requestAuthCode(client_id: string, ...scopes: Array<string>): Promise<any> {
|
||||
console.debug('requesting authorization code')
|
||||
const url = new URL('https://id.twitch.tv/oauth2/authorize')
|
||||
url.searchParams.append('response_type', 'code')
|
||||
url.searchParams.append('client_id', client_id)
|
||||
url.searchParams.append('scope', scopes.join(' ').trim())
|
||||
location.assign(url + '&redirect_uri=' + redirect_uri)
|
||||
return new Promise(()=>{})
|
||||
}
|
||||
|
||||
/**
|
||||
* https://dev.twitch.tv/docs/authentication/getting-tokens-oauth/#use-the-authorization-code-to-get-a-token
|
||||
* @param {string} client_id
|
||||
* @param {string} code
|
||||
* @returns {Promise<TwitchToken>}
|
||||
*/
|
||||
export function exchangeCode(client_id: string, code: string): Promise<TwitchToken> {
|
||||
console.debug('exchanging authorization code')
|
||||
const searchParams = new URLSearchParams({
|
||||
client_id: client_id,
|
||||
code: code,
|
||||
grant_type: 'authorization_code'
|
||||
})
|
||||
return fetch(proxy_uri, {
|
||||
method: 'POST',
|
||||
body: searchParams.toString() + '&redirect_uri=' + redirect_uri,
|
||||
headers: { 'content-type': 'application/x-www-form-urlencoded' }
|
||||
}).then(async function (response) {
|
||||
if (!response.ok) {
|
||||
throw new Error(await response.text())
|
||||
}
|
||||
const token = await response.json()
|
||||
return stamp(token)
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* https://dev.twitch.tv/docs/authentication/validate-tokens/#how-to-validate-a-token
|
||||
* @param {string} access_token
|
||||
* @returns {TwitchToken}
|
||||
*/
|
||||
export async function validateToken(access_token: string): Promise<TwitchToken> {
|
||||
console.debug('validating token')
|
||||
return fetch('https://id.twitch.tv/oauth2/validate', {
|
||||
headers: { authorization: 'OAuth ' + access_token }
|
||||
}).then(async response => {
|
||||
if (!response.ok) {
|
||||
throw new Error(await response.text())
|
||||
}
|
||||
/** @type {TwitchToken} */
|
||||
const token: any = await response.json()
|
||||
token.access_token = access_token
|
||||
token.scope = token.scopes
|
||||
delete token.scopes
|
||||
token.token_type = 'bearer'
|
||||
return stamp(token)
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* https://dev.twitch.tv/docs/authentication/refresh-tokens/#how-to-use-a-refresh-token
|
||||
* @param {string} client_id
|
||||
* @param {string} refresh_token
|
||||
* @returns {Promise<TwitchToken>}
|
||||
*/
|
||||
export function refreshToken(client_id: string, refresh_token: string): Promise<TwitchToken> {
|
||||
console.debug('refreshing token')
|
||||
const searchParams = new URLSearchParams({
|
||||
client_id: client_id,
|
||||
grant_type: 'refresh_token',
|
||||
refresh_token: refresh_token
|
||||
})
|
||||
return fetch(proxy_uri, {
|
||||
method: 'POST',
|
||||
body: searchParams.toString(),
|
||||
headers: { 'content-type': 'application/x-www-form-urlencoded' }
|
||||
}).then(async function (response) {
|
||||
if (!response.ok) {
|
||||
throw new Error(await response.text())
|
||||
}
|
||||
return await response.json()
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* This function checks the url search parameters and hash for an auth code,
|
||||
* refresh token, access token, or error message, in that order,
|
||||
* and if it finds none of those, starts the auth code grant flow.
|
||||
* https://dev.twitch.tv/docs/authentication/getting-tokens-oauth/#authorization-code-grant-flow
|
||||
* @param {string} client_id
|
||||
* @returns {TwitchToken}
|
||||
*/
|
||||
export async function getUserToken(client_id: string, ...scopes): Promise<TwitchToken> {
|
||||
const token=await getUserTokenPassive(client_id, ...scopes)
|
||||
if(!token){
|
||||
return requestAuthCode(client_id, ...scopes)
|
||||
}
|
||||
return token
|
||||
}
|
||||
|
||||
/**
|
||||
* This function checks the url search parameters and hash for an auth code,
|
||||
* refresh token, access token, or error message, in that order.
|
||||
* https://dev.twitch.tv/docs/authentication/getting-tokens-oauth/#authorization-code-grant-flow
|
||||
* @param {string} client_id
|
||||
* @returns {TwitchToken}
|
||||
*/
|
||||
export async function getUserTokenPassive(client_id: string, ...scopes): Promise<TwitchToken>{
|
||||
console.debug('scopes requested:',...scopes)
|
||||
const params = new URLSearchParams(location.search + '&' + location.hash.substring(1))
|
||||
if (params.has('code')) {
|
||||
const code = params.get('code')
|
||||
history.replaceState(null, '', redirect_uri)
|
||||
return exchangeCode(client_id, code)
|
||||
}
|
||||
if (params.has('refresh_token')) {
|
||||
return refreshToken(client_id, params.get('refresh_token'))
|
||||
}
|
||||
if (params.has('access_token')) {
|
||||
return validateToken(params.get('access_token'))
|
||||
}
|
||||
if (params.has('error')) {
|
||||
const error_message = params.get('error') + ': ' + params.get('error_description')
|
||||
history.replaceState(null, '', redirect_uri)
|
||||
throw new Error(error_message)
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
export default getUserToken
|
||||
@@ -1,3 +1,3 @@
|
||||
var d=i=>{throw TypeError(i)};var o=(i,t,h)=>t.has(i)||d("Cannot "+h);var n=(i,t,h)=>(o(i,t,"read from private field"),h?h.call(i):t.get(i)),c=(i,t,h)=>t.has(i)?d("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(i):t.set(i,h),u=(i,t,h,e)=>(o(i,t,"write to private field"),e?e.call(i,h):t.set(i,h),h);var l,r,a,s,w=class{constructor(t,h=(e,f)=>globalThis.fetch(e,f)){c(this,l,new URL(import.meta.url).origin);c(this,r,null);c(this,a,null);c(this,s,null);u(this,s,h),u(this,r,t),t.getAccessTokenForUser(void 0).then(e=>caches.open(e.userId+"/"+t.clientId)).then(e=>u(this,a,e))}async fetch(t,h={}){if(t=new URL(t,n(this,l)),t.origin==n(this,l)){let e=await n(this,r).getAccessTokenForUser(void 0);h.headers||(h.headers={}),h.headers.authorization="OAuth "+e.accessToken}if("method"in h)switch(h.method){case"PUT":case"POST":{let e=await n(this,s).call(this,t,h);if(!e.ok)return e;let f=await new Request(t,h).blob();return n(this,a).put(t,new Response(f)),e}case"DELETE":{let e=await n(this,s).call(this,t,h);return e.ok&&n(this,a).delete(t),e}}return n(this,s).call(this,t,h).then(async e=>{if(e.status>=500)throw new Error(e.statusText+`
|
||||
`+await e.text());return n(this,a).put(t,e.clone()),e}).catch(e=>(console.warn(e),n(this,a).match(t)))}};l=new WeakMap,r=new WeakMap,a=new WeakMap,s=new WeakMap;export{w as default};
|
||||
//# sourceMappingURL=data:application/json;base64,ewogICJ2ZXJzaW9uIjogMywKICAic291cmNlcyI6IFsiV2ViU3R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wcml2YXRlQWRkIiwgIl9fcHJpdmF0ZVNldCIsICJ0b2tlbiIsICJjYWNoZSIsICJfX3ByaXZhdGVHZXQiLCAicmVzcG9uc2UiLCAiYmxvYiIsICJlcnJvciJdCn0K
|
||||
//# sourceMappingURL=WebStorage.js.map
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"version": 3,
|
||||
"sources": ["WebStorage.ts"],
|
||||
"sourcesContent": ["/**\n * @callback fetch\n * @param {RequestInfo} resource\n * @param {RequestInit} options\n * @returns {Promise<Response>}\n */\n\nexport default class WebStorage {\n\n #origin = new URL(import.meta.url).origin\n #auth_provider: import('@twurple/auth').AuthProvider = null;\n #cache: Cache = null\n #fetch: typeof globalThis.fetch = null\n\n /**\n * Creates a fetch request wrapper that returns cached responses when the server can't be reached.\n * When only a path is provided, the origin defaults to the same origin this module was loaded from.\n * When the origin matches this script, authorization headers are added automatically.\n * You can also use this for GET requests to any orgigin, but other methods may have unknown behavior.\n * @param {import('@twurple/auth').AuthProvider} auth_provider used to add the authentication header to requests for web storage\n * @param {fetch} fetch defaults to `globalThis.fetch`, allows you to further customize fetch behavior via chaining, for example with `fetch-retry`\n */\n constructor(auth_provider: import('@twurple/auth').AuthProvider, fetch: typeof globalThis.fetch = (resource,options)=>{return globalThis.fetch(resource,options)}) {\n this.#fetch = fetch\n this.#auth_provider = auth_provider\n auth_provider.getAccessTokenForUser(undefined)\n .then(token => caches.open(token.userId + '/' + auth_provider.clientId))\n .then(cache => this.#cache = cache)\n }\n\n /**\n * \n * @param {String | URL} resource \n * @param {RequestInit} options \n */\n async fetch(resource: string | URL, options: RequestInit={}) {\n resource = new URL(resource, this.#origin)\n if (resource.origin == this.#origin) {\n const token = await this.#auth_provider.getAccessTokenForUser(undefined)\n if (!options.headers) {\n options.headers = {}\n }\n options.headers['authorization'] = 'OAuth ' + token.accessToken\n }\n if ('method' in options) {\n switch (options.method) {\n case 'PUT':\n case 'POST': {\n const response = await this.#fetch(resource, options)\n if (!response.ok) {\n return response\n }\n const blob = await new Request(resource, options).blob()\n this.#cache.put(resource, new Response(blob))\n return response\n }\n case 'DELETE': {\n const response = await this.#fetch(resource, options)\n if (!response.ok) {\n return response\n }\n this.#cache.delete(resource)\n return response\n }\n }\n }\n return this.#fetch(resource, options)\n .then(async response => {\n if (response.status >= 500) {\n throw new Error(response.statusText + '\\n' + await response.text())\n }\n this.#cache.put(resource, response.clone())\n return response\n }).catch(error => {\n console.warn(error)\n return this.#cache.match(resource)\n }\n )\n }\n}"],
|
||||
"mappings": "2UAAA,IAAAA,EAAAC,EAAAC,EAAAC,EAOqBC,EAArB,KAAgC,CAe5B,YAAYC,EAAqDC,EAAiC,CAACC,EAASC,IAAkB,WAAW,MAAMD,EAASC,CAAO,EAAI,CAbnKC,EAAA,KAAAT,EAAU,IAAI,IAAI,YAAY,GAAG,EAAE,QACnCS,EAAA,KAAAR,EAAuD,MACvDQ,EAAA,KAAAP,EAAgB,MAChBO,EAAA,KAAAN,EAAkC,MAW9BO,EAAA,KAAKP,EAASG,GACdI,EAAA,KAAKT,EAAiBI,GACtBA,EAAc,sBAAsB,MAAS,EACxC,KAAKM,GAAS,OAAO,KAAKA,EAAM,OAAS,IAAMN,EAAc,QAAQ,CAAC,EACtE,KAAKO,GAASF,EAAA,KAAKR,EAASU,EAAK,CAC1C,CAOA,MAAM,MAAML,EAAwBC,EAAqB,CAAC,EAAG,CAEzD,GADAD,EAAW,IAAI,IAAIA,EAAUM,EAAA,KAAKb,EAAO,EACrCO,EAAS,QAAUM,EAAA,KAAKb,GAAS,CACjC,IAAMW,EAAQ,MAAME,EAAA,KAAKZ,GAAe,sBAAsB,MAAS,EAClEO,EAAQ,UACTA,EAAQ,QAAU,CAAC,GAEvBA,EAAQ,QAAQ,cAAmB,SAAWG,EAAM,WACxD,CACA,GAAI,WAAYH,EACZ,OAAQA,EAAQ,OAAQ,CACpB,IAAK,MACL,IAAK,OAAQ,CACT,IAAMM,EAAW,MAAMD,EAAA,KAAKV,GAAL,UAAYI,EAAUC,GAC7C,GAAI,CAACM,EAAS,GACV,OAAOA,EAEX,IAAMC,EAAO,MAAM,IAAI,QAAQR,EAAUC,CAAO,EAAE,KAAK,EACvD,OAAAK,EAAA,KAAKX,GAAO,IAAIK,EAAU,IAAI,SAASQ,CAAI,CAAC,EACrCD,CACX,CACA,IAAK,SAAU,CACX,IAAMA,EAAW,MAAMD,EAAA,KAAKV,GAAL,UAAYI,EAAUC,GAC7C,OAAKM,EAAS,IAGdD,EAAA,KAAKX,GAAO,OAAOK,CAAQ,EACpBO,CACX,CACJ,CAEJ,OAAOD,EAAA,KAAKV,GAAL,UAAYI,EAAUC,GACxB,KAAK,MAAMM,GAAY,CACpB,GAAIA,EAAS,QAAU,IACnB,MAAM,IAAI,MAAMA,EAAS,WAAa;AAAA,EAAO,MAAMA,EAAS,KAAK,CAAC,EAEtE,OAAAD,EAAA,KAAKX,GAAO,IAAIK,EAAUO,EAAS,MAAM,CAAC,EACnCA,CACX,CAAC,EAAE,MAAME,IACL,QAAQ,KAAKA,CAAK,EACXH,EAAA,KAAKX,GAAO,MAAMK,CAAQ,EAEzC,CACJ,CACJ,EAtEIP,EAAA,YACAC,EAAA,YACAC,EAAA,YACAC,EAAA",
|
||||
"names": ["_origin", "_auth_provider", "_cache", "_fetch", "WebStorage", "auth_provider", "fetch", "resource", "options", "__privateAdd", "__privateSet", "token", "cache", "__privateGet", "response", "blob", "error"]
|
||||
}
|
||||
@@ -1,80 +0,0 @@
|
||||
/**
|
||||
* @callback fetch
|
||||
* @param {RequestInfo} resource
|
||||
* @param {RequestInit} options
|
||||
* @returns {Promise<Response>}
|
||||
*/
|
||||
|
||||
export default class WebStorage {
|
||||
|
||||
#origin = new URL(import.meta.url).origin
|
||||
#auth_provider: import('@twurple/auth').AuthProvider = null;
|
||||
#cache: Cache = null
|
||||
#fetch: typeof globalThis.fetch = null
|
||||
|
||||
/**
|
||||
* Creates a fetch request wrapper that returns cached responses when the server can't be reached.
|
||||
* When only a path is provided, the origin defaults to the same origin this module was loaded from.
|
||||
* When the origin matches this script, authorization headers are added automatically.
|
||||
* You can also use this for GET requests to any orgigin, but other methods may have unknown behavior.
|
||||
* @param {import('@twurple/auth').AuthProvider} auth_provider used to add the authentication header to requests for web storage
|
||||
* @param {fetch} fetch defaults to `globalThis.fetch`, allows you to further customize fetch behavior via chaining, for example with `fetch-retry`
|
||||
*/
|
||||
constructor(auth_provider: import('@twurple/auth').AuthProvider, fetch: typeof globalThis.fetch = (resource,options)=>{return globalThis.fetch(resource,options)}) {
|
||||
this.#fetch = fetch
|
||||
this.#auth_provider = auth_provider
|
||||
auth_provider.getAccessTokenForUser(undefined)
|
||||
.then(token => caches.open(token.userId + '/' + auth_provider.clientId))
|
||||
.then(cache => this.#cache = cache)
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {String | URL} resource
|
||||
* @param {RequestInit} options
|
||||
*/
|
||||
async fetch(resource: string | URL, options: RequestInit={}) {
|
||||
resource = new URL(resource, this.#origin)
|
||||
if (resource.origin == this.#origin) {
|
||||
const token = await this.#auth_provider.getAccessTokenForUser(undefined)
|
||||
if (!options.headers) {
|
||||
options.headers = {}
|
||||
}
|
||||
options.headers['authorization'] = 'OAuth ' + token.accessToken
|
||||
}
|
||||
if ('method' in options) {
|
||||
switch (options.method) {
|
||||
case 'PUT':
|
||||
case 'POST': {
|
||||
const response = await this.#fetch(resource, options)
|
||||
if (!response.ok) {
|
||||
return response
|
||||
}
|
||||
const blob = await new Request(resource, options).blob()
|
||||
this.#cache.put(resource, new Response(blob))
|
||||
return response
|
||||
}
|
||||
case 'DELETE': {
|
||||
const response = await this.#fetch(resource, options)
|
||||
if (!response.ok) {
|
||||
return response
|
||||
}
|
||||
this.#cache.delete(resource)
|
||||
return response
|
||||
}
|
||||
}
|
||||
}
|
||||
return this.#fetch(resource, options)
|
||||
.then(async response => {
|
||||
if (response.status >= 500) {
|
||||
throw new Error(response.statusText + '\n' + await response.text())
|
||||
}
|
||||
this.#cache.put(resource, response.clone())
|
||||
return response
|
||||
}).catch(error => {
|
||||
console.warn(error)
|
||||
return this.#cache.match(resource)
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
+1
-1
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -1,72 +0,0 @@
|
||||
import * as TwitchAuth from './TwitchAuth.ts'
|
||||
|
||||
interface AuthHeaders {
|
||||
'Authorization': string,
|
||||
'Client-ID': string
|
||||
}
|
||||
|
||||
interface Token extends TwitchAuth.TwitchToken {
|
||||
auth_headers: AuthHeaders
|
||||
}
|
||||
|
||||
let token: Token=null;
|
||||
|
||||
export function request_auth(client_id: string,scope: string,redirect_uri=location.origin+location.pathname){
|
||||
return TwitchAuth.requestAuthCode(client_id,...scope.split(' '))
|
||||
}
|
||||
|
||||
export function get_url_params(){
|
||||
return Object.fromEntries(new URLSearchParams(location.search))
|
||||
}
|
||||
|
||||
export async function fetch_tokens(client_id: string,code: string,redirect_uri=location.origin+location.pathname): Promise<Token>{
|
||||
client_id=client_id
|
||||
token=await TwitchAuth.exchangeCode(client_id,code) as Token
|
||||
token.client_id=client_id
|
||||
return token
|
||||
}
|
||||
|
||||
export function get_headers(tokens: Token): AuthHeaders{
|
||||
return {
|
||||
'Authorization':'Bearer '+tokens.access_token,
|
||||
'Client-ID':tokens.client_id
|
||||
}
|
||||
}
|
||||
|
||||
export async function validate_tokens(tokens: Token): Promise<Token>{
|
||||
const validation=await TwitchAuth.validateToken(tokens.access_token)
|
||||
Object.assign(tokens,validation)
|
||||
tokens.scope=validation.scope
|
||||
tokens.auth_headers=get_headers(tokens)
|
||||
token=tokens
|
||||
return token
|
||||
}
|
||||
|
||||
export function set_local_tokens(client_id: string,tokens: Token){
|
||||
token=tokens
|
||||
return token
|
||||
}
|
||||
|
||||
export function get_local_tokens(client_id: string){
|
||||
return token
|
||||
}
|
||||
|
||||
export async function refresh_tokens(client_id: string,refresh_token: string){
|
||||
token=await TwitchAuth.refreshToken(client_id,refresh_token) as Token
|
||||
return token
|
||||
}
|
||||
|
||||
export function set_refresh_timeout(client_id: string,tokens: Token){
|
||||
return setTimeout(()=>{
|
||||
TwitchAuth.refreshToken(client_id,tokens.refresh_token)
|
||||
.then(new_tokens=>Object.assign(tokens,new_tokens))
|
||||
},tokens.expires_in*999)
|
||||
}
|
||||
|
||||
export async function get_tokens(client_id: string,scope='',redirect_uri=location.origin+location.pathname,auth_return=false){
|
||||
token=await TwitchAuth.getUserToken(client_id,...scope.split(' ')).then(validate_tokens)
|
||||
set_refresh_timeout(client_id,token)
|
||||
return token
|
||||
}
|
||||
|
||||
export default get_tokens
|
||||
@@ -1,9 +0,0 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "es2020",
|
||||
"module": "es2020",
|
||||
"moduleResolution": "node",
|
||||
"allowImportingTsExtensions": true,
|
||||
"noEmit": true,
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user