import {JSONValue} from '../system'; export type Id = string; export type IdMap = { [key: string]: Id; }; export interface AreaAccess { id: Id; name: string; owner: Id; permissions: number; } export interface Layer { id: Id; name: string; owner: Id; } export interface AccessTokens { access: AreaAccess; tokens: { space: Layer; token: string; }[]; } export interface Obj { [_: string]: JSONValue; id: Id; name: string; created: number; user: Id; } export function newId(): Id { let id: Id = ''; for (let i = 0; i < 16; i++) { let idp = Math.floor(Math.random() * 256).toString(16); while (idp.length < 2) { idp = '0' + idp; } id += idp; } return id; } export type RequestBody = ArrayBuffer | string; export interface RequestOptions { request: 'json' | 'raw'; response: 'json' | 'raw'; } export interface Request { method: 'GET' | 'POST' | 'PUT' | 'DELETE'; url: string; headers?: { [_: string]: string }; body?: RequestBody; } export interface Response { status: number; body?: ArrayBuffer; headers: { [_: string]: string }; } export async function request(r: Request): Promise { const fetchHeaders = new Headers(); for (const key of Object.keys(r.headers ?? {})) { fetchHeaders.set(key, r.headers![key]); } const init = { headers: fetchHeaders, method: r.method, body: undefined as undefined | RequestBody, }; if (r.body) { init['body'] = r.body; } const resp = await fetch(r.url, init); const headers: { [_: string]: string } = {}; for (const e of resp.headers.entries()) { headers[e[0]] = e[1]; } return { status: resp.status, body: await resp.arrayBuffer(), headers, }; } export function isId(id: string): boolean { return /^[0-9A-Fa-f]{32}$/i.test(id); }