char-slop/stars.hackery.site
git clone https://git.t4t.associates/char-slop/stars.hackery.site
92004f9
main
1export async function readBytes ( 2chunks :AsyncIterable < Uint8Array > | Iterable < Uint8Array >, 3maxBytes :number , 4) :Promise < Uint8Array > { 5const parts :Uint8Array [] = []; 6let size = 0 ; 7for await ( const chunk of chunks ) { 8size += chunk . byteLength ; 9if ( size > maxBytes ) throw new Error ( "Body too large" ); 10parts . push ( chunk ); 11} 12const bytes = new Uint8Array ( size ); 13let offset = 0 ; 14for ( const part of parts ) { 15bytes . set ( part , offset ); 16offset += part . byteLength ; 17} 18return bytes ; 19} 20 21export const cookie = ( 22name :string , 23value :string , 24secure :boolean , 25maxAge :number , 26) => 27` ${ name } = ${ value } ; Path=/; HttpOnly; SameSite=Lax; Max-Age= ${ maxAge } ${ 28secure ? "; Secure" : "" 29} ` ; 30 31export const readCookie = ( req :Request , name :string ) => 32new RegExp ( `(?:^|;\\s*) ${ name } =([^;]*)` ) 33. exec ( req . headers . get ( "cookie" ) ?? "" )?.[ 1 ]; 34 35// An origin with nothing else: no credentials, path, query, or fragment. 36export const isBareOrigin = ( url :URL ) => 37[ "https:" , "http:" ]. includes ( url . protocol ) && ! url . username && 38! url . password && url . pathname === "/" && ! url . search && ! url . hash ; 39 40export class HttpError extends Error { 41constructor ( 42readonly status :number , 43message :string , 44readonly headers :HeadersInit = {}, 45) { 46super ( message ); 47} 48 49response () :Response { 50return new Response ( this . message , { 51status :this . status , 52headers :this . headers , 53}); 54} 55} 56 57export function fail ( status :number , message :string ) :never { 58throw new HttpError ( status , message ); 59} 60 61export const redirect = ( path :string , ...cookies :string []) :Response => { 62const res = new Response ( null , { status :303 , headers :{ location :path } }); 63for ( const value of cookies ) res . headers . append ( "set-cookie" , value ); 64return res ; 65};