@gibeon/sdk 0.0.0-stage → 0.1.0

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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/errors.ts","../src/auth.ts","../src/browser.ts","../src/credentials.ts","../src/case.ts","../src/http.ts","../src/client.ts"],"sourcesContent":["export { GibeonApiError, GibeonAuthError } from './errors.js';\nexport type { GibeonAuthErrorCode } from './errors.js';\nexport { Gibeon } from './client.js';\nexport type {\n GibeonOptions,\n Screen,\n ScreenCreateOptions,\n ScreenPatch,\n Playlist,\n PlaylistItem,\n PlaylistItemInput,\n Asset,\n PublishOneResult,\n PublishAllResult,\n} from './types.js';\n","export type GibeonAuthErrorCode =\n | 'email_required'\n | 'claim_expired'\n | 'rate_limited'\n | 'token_expired'\n | 'sign_in_failed';\n\nexport class GibeonAuthError extends Error {\n readonly code: GibeonAuthErrorCode;\n\n constructor(code: GibeonAuthErrorCode, message: string) {\n super(message);\n this.name = 'GibeonAuthError';\n this.code = code;\n }\n}\n\nexport class GibeonApiError extends Error {\n readonly status: number;\n readonly code: string;\n readonly requestId: string | null;\n readonly ids?: string[];\n\n constructor(init: {\n status: number;\n code: string;\n message: string;\n requestId?: string | null;\n ids?: string[];\n }) {\n super(init.message);\n this.name = 'GibeonApiError';\n this.status = init.status;\n this.code = init.code;\n this.requestId = init.requestId ?? null;\n if (init.ids !== undefined) this.ids = init.ids;\n }\n}\n","import { createInterface } from 'node:readline';\nimport { openBrowser } from './browser.js';\nimport {\n type Credentials,\n credentialsPath,\n readCredentials,\n withLock,\n writeCredentials,\n} from './credentials.js';\nimport { GibeonAuthError } from './errors.js';\n\nexport const REGISTER_URL = 'https://cuztuwusnyvfuictgesw.supabase.co/auth/v1/oauth/clients/register';\nexport const TOKEN_URL = 'https://id.gibeon.io/auth/v1/oauth/token';\nexport const REDIRECT_URI = 'https://www.gibeon.io/agent/callback';\n\n/** A stored token with less than this left is refreshed before use. */\nexport const REFRESH_MARGIN_MS = 60_000;\n\n/**\n * Every request gives up after this long. A refresh holds the lock for one\n * request, so it ends long before another process may take the lock over\n * (LOCK_STALE_MS, 30 s).\n */\nexport const REQUEST_TIMEOUT_MS = 10_000;\n\n/**\n * Bounds on what the claim start may ask for. The server sends 600 s and 5 s;\n * an answer outside these bounds is clamped, so no answer can keep a script\n * waiting for hours or make it poll in a tight loop.\n */\nconst CLAIM_MAX_EXPIRES_S = 900;\nconst POLL_MIN_S = 1;\nconst POLL_MAX_S = 60;\n\nexport interface TokenSource {\n /** A bearer token valid for at least REFRESH_MARGIN_MS, signing in or refreshing first. */\n getToken(): Promise<string>;\n /** Called once after the API refused `used` with a 401: a newer token, or an error. */\n renew(used: string): Promise<string>;\n}\n\nexport interface AuthDeps {\n now(): number;\n sleep(ms: number): Promise<void>;\n stderr: { write(chunk: string): unknown };\n stdinIsTTY: boolean;\n stdoutIsTTY: boolean;\n prompt(question: string): Promise<string>;\n openBrowser(url: string): void;\n}\n\ntype Step = 'client registration' | 'claim start' | 'approval check';\n\ntype Tokens = Pick<Credentials, 'access_token' | 'refresh_token' | 'expires_at'>;\n\ninterface Claim {\n token: string;\n userCode: string;\n uri: string;\n expiresIn: number;\n interval: number;\n}\n\nconst EMAIL_PROMPT = 'Email address of your gibeon.io account: ';\nconst EMAIL_REQUIRED =\n 'gibeon.io sign-in needs the email address of your account: pass new Gibeon({ email }) or set GIBEON_EMAIL.';\nconst RATE_LIMITED =\n 'Too many sign-in attempts from this network: the limit is 20 per hour. Try again later.';\nconst CLAIM_EXPIRED =\n 'The sign-in link expired before it was approved. Run the script again for a new link.';\nconst TOKEN_EXPIRED =\n 'The access token from GIBEON_TOKEN or new Gibeon({ token }) was refused: it expired or was revoked. Generate a new one in the CMS (Settings, Connected apps), or leave it out to sign in.';\n\nconst REGISTRATION = {\n client_name: 'Gibeon SDK',\n redirect_uris: [REDIRECT_URI],\n token_endpoint_auth_method: 'none',\n grant_types: ['authorization_code', 'refresh_token'],\n response_types: ['code'],\n};\n\n/**\n * The token for every API call. With `token` (or GIBEON_TOKEN) that token is\n * used as is. Otherwise the token comes from the credentials file: refreshed\n * under the file's lock when it is about to expire, and after a sign-in with\n * one approval link when there is none. Sign-in is lazy: the first getToken.\n */\nexport function createTokenSource(\n opts: { email?: string; token?: string; baseUrl: string },\n deps: Partial<AuthDeps> = {},\n): TokenSource {\n const baseUrl = opts.baseUrl.replace(/\\/+$/, '');\n const claimUrl = `${baseUrl}/agent/claim`;\n const now = deps.now ?? Date.now;\n const sleep = deps.sleep ?? delay;\n const stderr = deps.stderr ?? process.stderr;\n const prompt = deps.prompt ?? promptOnTerminal;\n const open = deps.openBrowser ?? openBrowser;\n const onTerminal = (): boolean =>\n (deps.stdinIsTTY ?? process.stdin.isTTY === true) &&\n (deps.stdoutIsTTY ?? process.stdout.isTTY === true);\n\n // One sign-in or refresh at a time per source: parallel calls share it.\n let inflight: Promise<string> | null = null;\n\n function share(run: () => Promise<string>): Promise<string> {\n if (inflight !== null) return inflight;\n const pending = run().finally(() => {\n if (inflight === pending) inflight = null;\n });\n inflight = pending;\n return pending;\n }\n\n function fixedToken(): string | null {\n if (opts.token !== undefined && opts.token !== '') return opts.token;\n const fromEnv = process.env.GIBEON_TOKEN;\n return fromEnv !== undefined && fromEnv !== '' ? fromEnv : null;\n }\n\n /** The email the caller named, by option or else GIBEON_EMAIL. */\n function namedEmail(): string | null {\n for (const value of [opts.email, process.env.GIBEON_EMAIL]) {\n const email = value?.trim() ?? '';\n if (email !== '') return email;\n }\n return null;\n }\n\n function isFresh(c: Credentials): boolean {\n return c.expires_at - now() >= REFRESH_MARGIN_MS;\n }\n\n /** The stored credentials; those of another account than the one named count as absent. */\n async function readStored(path: string): Promise<Credentials | null> {\n const stored = await readCredentials(path);\n if (stored === null) return null;\n const named = namedEmail();\n if (named !== null && named.toLowerCase() !== stored.email.trim().toLowerCase()) return null;\n return stored;\n }\n\n /** `refused` is the token a 401 came back for, or null for a plain getToken. */\n async function obtain(refused: string | null): Promise<string> {\n const path = credentialsPath();\n const stored = await readStored(path);\n if (stored === null) return signIn(path, null);\n if (stored.access_token !== refused && isFresh(stored)) return stored.access_token;\n return refresh(path, stored, refused ?? stored.access_token);\n }\n\n async function refresh(path: string, stored: Credentials, replaced: string): Promise<string> {\n // A token another process stored meanwhile, with time left.\n const newer = (c: Credentials): boolean => c.access_token !== replaced && isFresh(c);\n\n let refreshed: string | null = null;\n try {\n refreshed = await withLock(path, async () => {\n const latest = await readStored(path);\n if (latest === null) return null;\n if (newer(latest)) return latest.access_token;\n const tokens = await requestRefresh(latest);\n if (tokens === null) return null;\n // The old refresh token is spent now: store the new one before anything else.\n await writeCredentials(path, { ...latest, ...tokens });\n return tokens.access_token;\n });\n } catch (err) {\n // ENOENT: the directory is gone (this machine was signed out), so there\n // is no lock to take and nothing to refresh. Sign in again below; the\n // sign-in recreates the directory and the file.\n if (errorCode(err) !== 'ENOENT') throw err;\n }\n if (refreshed !== null) return refreshed;\n\n const again = await readStored(path);\n if (again !== null && newer(again)) return again.access_token;\n return signIn(path, again ?? stored);\n }\n\n async function requestRefresh(c: Credentials): Promise<Tokens | null> {\n const body = new URLSearchParams({\n grant_type: 'refresh_token',\n client_id: c.client_id,\n refresh_token: c.refresh_token,\n }).toString();\n let res: Response;\n try {\n res = await fetch(TOKEN_URL, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body,\n // A redirect would carry the refresh token to another host.\n redirect: 'error',\n signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),\n });\n } catch {\n return null;\n }\n const answer = await readJson(res);\n return res.ok ? toTokens(answer) : null;\n }\n\n /** `known`: credentials whose client_id and email a new sign-in reuses. */\n async function signIn(path: string, known: Credentials | null): Promise<string> {\n const email = await resolveEmail(known);\n const clientId = known?.client_id ?? (await register());\n const claim = await startClaim(clientId, email);\n\n stderr.write(\n 'gibeon.io sign-in: open this link and enter the code to connect this script to your account.\\n',\n );\n stderr.write(` ${claim.uri}\\n`);\n stderr.write(` Code: ${claim.userCode}\\n`);\n stderr.write(\n `Waiting for approval (the link expires in ${Math.round(claim.expiresIn / 60)} minutes).\\n`,\n );\n open(claim.uri);\n\n const tokens = await awaitApproval(claim);\n await writeCredentials(path, { version: 1, client_id: clientId, email, ...tokens });\n stderr.write(`Signed in. The token is stored in ${path}.\\n`);\n return tokens.access_token;\n }\n\n async function resolveEmail(known: Credentials | null): Promise<string> {\n const named = namedEmail();\n if (named !== null) return named;\n if (known !== null) return known.email;\n if (onTerminal()) {\n const answer = (await prompt(EMAIL_PROMPT)).trim();\n if (answer !== '') return answer;\n }\n throw new GibeonAuthError('email_required', EMAIL_REQUIRED);\n }\n\n async function register(): Promise<string> {\n const step = 'client registration';\n const res = await postJson(REGISTER_URL, REGISTRATION);\n if (res === null) throw noAnswer(step);\n const answer = await readJson(res);\n if (!res.ok || !isRecord(answer) || !isText(answer.client_id)) {\n throw signInFailed(step, res.status);\n }\n return answer.client_id;\n }\n\n async function startClaim(clientId: string, email: string): Promise<Claim> {\n const step = 'claim start';\n const res = await postJson(claimUrl, { client_id: clientId, email });\n if (res === null) throw noAnswer(step);\n const answer = await readJson(res);\n // The limit is per network, so a retry only spends another attempt.\n if (res.status === 429) throw new GibeonAuthError('rate_limited', RATE_LIMITED);\n const claim = res.status === 200 ? toClaim(answer) : null;\n if (claim === null) throw signInFailed(step, res.status);\n return claim;\n }\n\n async function awaitApproval(claim: Claim): Promise<Tokens> {\n const deadline = now() + claim.expiresIn * 1000;\n const intervalMs = claim.interval * 1000;\n for (;;) {\n await sleep(intervalMs);\n if (now() >= deadline) throw new GibeonAuthError('claim_expired', CLAIM_EXPIRED);\n const res = await postJson(claimUrl, { claim_token: claim.token });\n // No answer or a server error: wait one interval and ask again.\n if (res === null) continue;\n const answer = await readJson(res);\n if (res.status === 202 || res.status >= 500) continue;\n if (res.status === 200) {\n const tokens = toTokens(answer);\n if (tokens === null) throw signInFailed('approval check', res.status);\n return tokens;\n }\n if (res.status === 400 && isRecord(answer) && answer.error === 'expired_token') {\n throw new GibeonAuthError('claim_expired', CLAIM_EXPIRED);\n }\n throw signInFailed('approval check', res.status);\n }\n }\n\n function toTokens(answer: unknown): Tokens | null {\n if (!isRecord(answer)) return null;\n const { access_token, refresh_token, expires_in } = answer;\n if (!isText(access_token) || !isText(refresh_token)) return null;\n if (typeof expires_in !== 'number' || !Number.isFinite(expires_in) || expires_in < 0) return null;\n return { access_token, refresh_token, expires_at: now() + expires_in * 1000 };\n }\n\n return {\n getToken(): Promise<string> {\n const fixed = fixedToken();\n if (fixed !== null) return Promise.resolve(fixed);\n return share(() => obtain(null));\n },\n\n async renew(used: string): Promise<string> {\n if (fixedToken() !== null) throw new GibeonAuthError('token_expired', TOKEN_EXPIRED);\n // A sign-in or refresh already under way may bring the new token.\n while (inflight !== null) {\n const token = await inflight;\n if (token !== used) return token;\n }\n return share(() => obtain(used));\n },\n };\n}\n\n/** A JSON POST with the request timeout; `null` when no answer came. */\nasync function postJson(url: string, body: unknown): Promise<Response | null> {\n try {\n return await fetch(url, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', Accept: 'application/json' },\n body: JSON.stringify(body),\n // A redirect would carry the email or the claim token to another host.\n redirect: 'error',\n signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),\n });\n } catch {\n return null;\n }\n}\n\nasync function readJson(res: Response): Promise<unknown> {\n try {\n return await res.json();\n } catch {\n return null;\n }\n}\n\nfunction toClaim(answer: unknown): Claim | null {\n if (!isRecord(answer) || !isText(answer.claim_token) || !isRecord(answer.claim_attempt)) {\n return null;\n }\n const { user_code, verification_uri, expires_in, interval } = answer.claim_attempt;\n // Both are printed to the terminal: no control characters. The server's code\n // is six digits (randomCode6 in the claim store), so anything else is refused.\n if (typeof user_code !== 'string' || !/^[0-9]{6}$/.test(user_code)) return null;\n if (!isPrintable(verification_uri)) return null;\n if (!isPositive(expires_in) || !isPositive(interval)) return null;\n return {\n token: answer.claim_token,\n userCode: user_code,\n uri: verification_uri,\n expiresIn: Math.min(expires_in, CLAIM_MAX_EXPIRES_S),\n interval: Math.min(Math.max(interval, POLL_MIN_S), POLL_MAX_S),\n };\n}\n\n/** A 2xx here carried a body the SDK cannot use; any other status is an error answer. */\nfunction signInFailed(step: Step, status: number): GibeonAuthError {\n const detail = status >= 200 && status < 300 ? `unexpected answer, HTTP ${status}` : `HTTP ${status}`;\n return new GibeonAuthError('sign_in_failed', `gibeon.io sign-in failed at ${step} (${detail}).`);\n}\n\nfunction noAnswer(step: Step): GibeonAuthError {\n return new GibeonAuthError(\n 'sign_in_failed',\n `gibeon.io sign-in failed at ${step} (no answer from the server).`,\n );\n}\n\n/** The terminal prompt, on stderr so stdout stays the script's own. */\nfunction promptOnTerminal(question: string): Promise<string> {\n return new Promise((resolve) => {\n const rl = createInterface({ input: process.stdin, output: process.stderr });\n // Ctrl-D ends the input without an answer: no email.\n rl.once('close', () => resolve(''));\n // Ctrl-C at the prompt stops the script, as it does anywhere else.\n rl.once('SIGINT', () => {\n rl.close();\n process.kill(process.pid, 'SIGINT');\n });\n rl.question(question, (answer) => {\n resolve(answer);\n rl.close();\n });\n });\n}\n\nfunction delay(ms: number): Promise<void> {\n return new Promise((resolve) => {\n setTimeout(resolve, ms);\n });\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction isText(value: unknown): value is string {\n return typeof value === 'string' && value !== '';\n}\n\n/**\n * No C0 or C1 control character and no bidi control (LRM, RLM, the embeddings\n * and overrides, the isolates): any of them could make the printed link read\n * differently in a terminal than it opens.\n */\nfunction isPrintable(value: unknown): value is string {\n return (\n typeof value === 'string' &&\n /^[^\\u0000-\\u001f\\u007f-\\u009f\\u200e\\u200f\\u202a-\\u202e\\u2066-\\u2069]+$/.test(value)\n );\n}\n\nfunction isPositive(value: unknown): value is number {\n return typeof value === 'number' && Number.isFinite(value) && value > 0;\n}\n\nfunction errorCode(err: unknown): unknown {\n return typeof err === 'object' && err !== null ? (err as { code?: unknown }).code : undefined;\n}\n","import { spawn } from 'node:child_process';\n\n/**\n * Only the approval link in the exact shape the server sends is ever handed to\n * a shell opener: `https://app.gibeon.io/oauth/agent?cat=<claim attempt token>`,\n * the token `cat_` plus base64url (`randomToken` in the claim store). Any other\n * URL is printed but never opened. The class also keeps out whitespace,\n * quotes, shell operators and `%` (cmd expands `%NAME%` before it parses).\n */\nconst OPENABLE_URL = /^https:\\/\\/app\\.gibeon\\.io\\/oauth\\/agent\\?cat=[A-Za-z0-9_-]+$/;\n\n/** A browser can open only with a terminal on stdout, outside CI, on a platform with a display. */\nexport function shouldOpenBrowser(i: {\n stdoutIsTTY: boolean;\n env: NodeJS.ProcessEnv;\n platform: NodeJS.Platform;\n}): boolean {\n if (!i.stdoutIsTTY) return false;\n if (isSet(i.env.CI)) return false;\n if (i.platform === 'darwin' || i.platform === 'win32') return true;\n if (i.platform === 'linux') return isSet(i.env.DISPLAY) || isSet(i.env.WAYLAND_DISPLAY);\n return false;\n}\n\nexport function browserCommand(\n platform: NodeJS.Platform,\n url: string,\n): { command: string; args: string[]; windowsVerbatimArguments?: boolean } | null {\n switch (platform) {\n case 'darwin':\n return { command: 'open', args: [url] };\n case 'win32':\n // `start` takes its first quoted argument as the window title, hence the empty \"\".\n return { command: 'cmd', args: ['/c', 'start', '\"\"', url], windowsVerbatimArguments: true };\n case 'linux':\n return { command: 'xdg-open', args: [url] };\n default:\n return null;\n }\n}\n\n/**\n * Opens `url` in the default browser when this machine can show one. Never\n * throws and never waits: the caller has printed the link already, so a\n * failed open changes nothing.\n */\nexport function openBrowser(url: string): void {\n if (!OPENABLE_URL.test(url)) return;\n const canOpen = shouldOpenBrowser({\n stdoutIsTTY: process.stdout.isTTY === true,\n env: process.env,\n platform: process.platform,\n });\n if (!canOpen) return;\n const cmd = browserCommand(process.platform, url);\n if (cmd === null) return;\n try {\n const child = spawn(cmd.command, cmd.args, {\n detached: true,\n stdio: 'ignore',\n // No console window flashes up for cmd on Windows; ignored elsewhere.\n windowsHide: true,\n ...(cmd.windowsVerbatimArguments === true ? { windowsVerbatimArguments: true } : {}),\n });\n // A missing opener arrives as an 'error' event; without a listener it would crash the process.\n child.on('error', () => undefined);\n child.unref();\n } catch {\n // A spawn that throws at once is ignored the same way.\n }\n}\n\nfunction isSet(value: string | undefined): boolean {\n return value !== undefined && value !== '';\n}\n","import { randomBytes } from 'node:crypto';\nimport {\n type FileHandle,\n chmod,\n link,\n lstat,\n mkdir,\n open,\n readFile,\n rename,\n stat,\n unlink,\n} from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { dirname, join, resolve } from 'node:path';\n\n/** The token file, `expires_at` in epoch milliseconds. */\nexport interface Credentials {\n version: 1;\n client_id: string;\n email: string;\n access_token: string;\n refresh_token: string;\n expires_at: number;\n}\n\n/** A lock whose mtime is older than this belongs to a process that died holding it. */\nexport const LOCK_STALE_MS = 30_000;\n\nconst DEFAULT_POLL_MS = 100;\n\nexport function credentialsPath(env: NodeJS.ProcessEnv = process.env): string {\n const fromEnv = env.GIBEON_CREDENTIALS_FILE;\n if (fromEnv !== undefined && fromEnv !== '') return fromEnv;\n return join(homedir(), '.gibeon', 'credentials.json');\n}\n\n/**\n * The stored credentials, or `null` when there are none we can use: no file,\n * a symlink, a file another user owns or that group or others may read or\n * write, a file that does not parse, another `version`, or a missing or\n * mistyped field. Any other read error (EACCES, EISDIR) is thrown. Without\n * `process.getuid` (Windows) there is no owner or mode to check.\n */\nexport async function readCredentials(path: string): Promise<Credentials | null> {\n try {\n // The SDK only ever writes a plain file here.\n if ((await lstat(path)).isSymbolicLink()) return null;\n } catch (err) {\n if (errorCode(err) === 'ENOENT') return null;\n throw err;\n }\n let handle: FileHandle;\n try {\n handle = await open(path, 'r');\n } catch (err) {\n if (errorCode(err) === 'ENOENT') return null;\n throw err;\n }\n let text: string;\n try {\n // Owner and mode of the file we opened, not of whatever the path names by now.\n const info = await handle.stat();\n if (info.isFile() && !isPrivate(info)) return null;\n text = await handle.readFile('utf8');\n } finally {\n await handle.close();\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n return null;\n }\n return toCredentials(parsed);\n}\n\n/**\n * Writes the file atomically: a temp file in the same directory (opened\n * exclusively with mode 0600, then chmod 0600 on its handle, which no umask\n * narrows), renamed over the target. A reader sees the old file or the new\n * one, never half of one. Nothing is chmodded by path after the rename: a\n * symlink put there meanwhile would carry the chmod to the file it points at.\n */\nexport async function writeCredentials(path: string, creds: Credentials): Promise<void> {\n const dir = dirname(path);\n await mkdir(dir, { recursive: true, mode: 0o700 });\n await narrowGibeonDir(dir);\n const tmp = `${path}.${process.pid}.${randomBytes(6).toString('hex')}.tmp`;\n const body = `${JSON.stringify(\n {\n version: 1,\n client_id: creds.client_id,\n email: creds.email,\n access_token: creds.access_token,\n refresh_token: creds.refresh_token,\n expires_at: creds.expires_at,\n },\n null,\n 2,\n )}\\n`;\n let created = false;\n try {\n const handle = await open(tmp, 'wx', 0o600);\n created = true;\n try {\n await handle.chmod(0o600);\n await handle.writeFile(body, 'utf8');\n } finally {\n await handle.close();\n }\n await rename(tmp, path);\n } catch (err) {\n // The write or rename failed: remove our temp file and report the cause.\n // A failure of that cleanup is not the error the caller needs to see.\n if (created) await unlink(tmp).catch(() => undefined);\n throw err;\n }\n}\n\n/**\n * `~/.gibeon` may exist from before with a wider mode (mkdir leaves an existing\n * directory as it is): narrow it to 0700, but only when it is a real directory\n * (lstat, so never through a symlink) that this user owns. Any other directory\n * (GIBEON_CREDENTIALS_FILE may point into a project folder) is left as it is.\n */\nasync function narrowGibeonDir(dir: string): Promise<void> {\n const uid = process.getuid?.();\n if (uid === undefined) return;\n if (resolve(dir) !== join(homedir(), '.gibeon')) return;\n const info = await lstat(dir);\n if (!info.isDirectory() || info.uid !== uid) return;\n if ((info.mode & 0o777) !== 0o700) await chmod(dir, 0o700);\n}\n\n/** Owned by this user, no group or other bit. Without process.getuid (Windows) nothing to check. */\nfunction isPrivate(info: { uid: number; mode: number }): boolean {\n const uid = process.getuid?.();\n if (uid === undefined) return true;\n return info.uid === uid && (info.mode & 0o077) === 0;\n}\n\n/**\n * Runs `fn` while holding `<path>.lock`, so two processes never refresh at\n * the same time. The lock is created exclusively and holds a random id; a\n * lock older than LOCK_STALE_MS is taken over, a younger one is waited on.\n *\n * Neither the takeover nor the release unlinks the shared lock name directly:\n * each first renames the lock to a name only this caller knows, then checks\n * what it moved. The takeover keeps it only when it is the same stale file it\n * saw (same inode and mtime); the release only when it still holds this\n * caller's id. A live lock moved by mistake is linked back, so a waiter that\n * acts late can never delete a lock another process has just made.\n */\nexport async function withLock<T>(\n path: string,\n fn: () => Promise<T>,\n opts?: { pollMs?: number },\n): Promise<T> {\n const lock = `${path}.lock`;\n const id = randomBytes(16).toString('hex');\n await acquire(lock, id, opts?.pollMs ?? DEFAULT_POLL_MS);\n try {\n return await fn();\n } finally {\n await release(lock, id);\n }\n}\n\nasync function acquire(lock: string, id: string, pollMs: number): Promise<void> {\n for (;;) {\n let handle: FileHandle;\n try {\n handle = await open(lock, 'wx');\n } catch (err) {\n if (errorCode(err) !== 'EEXIST') throw err;\n let seen: FileIdentity;\n try {\n const { ino, mtimeMs } = await stat(lock);\n seen = { ino, mtimeMs };\n } catch (statErr) {\n // Released between our open and our stat: try again at once.\n if (errorCode(statErr) === 'ENOENT') continue;\n throw statErr;\n }\n if (Date.now() - seen.mtimeMs > LOCK_STALE_MS && (await takeOver(lock, id, seen))) {\n continue;\n }\n await delay(pollMs);\n continue;\n }\n try {\n try {\n await handle.writeFile(id, 'utf8');\n } finally {\n await handle.close();\n }\n } catch (err) {\n // We created this file, so it is ours to remove; leaving it behind would\n // make every other process wait LOCK_STALE_MS. A failed cleanup is not\n // the error the caller needs to see.\n await unlink(lock).catch(() => undefined);\n throw err;\n }\n return;\n }\n}\n\ninterface FileIdentity {\n ino: number;\n mtimeMs: number;\n}\n\n/**\n * Removes the stale lock `seen` described. Returns true when the lock is gone\n * (removed by us or already by someone else), false when what sat at the lock\n * name was a live lock another waiter made after our stat; that one is put back.\n */\nasync function takeOver(lock: string, id: string, seen: FileIdentity): Promise<boolean> {\n const aside = await moveAside(lock, id);\n if (aside === null) return true;\n const moved = await stat(aside);\n // The inode alone is not enough: a file system may hand the inode of the\n // removed stale lock to the fresh one; a fresh lock has a new mtime.\n if (moved.ino === seen.ino && moved.mtimeMs === seen.mtimeMs) {\n await unlinkIfPresent(aside);\n return true;\n }\n await putBack(aside, lock);\n return false;\n}\n\nasync function release(lock: string, id: string): Promise<void> {\n // A lock that is not ours (taken over after we passed LOCK_STALE_MS) is left\n // alone without being touched.\n if ((await readLockId(lock)) !== id) return;\n // It was ours a moment ago. Move it aside and check again, so the removal can\n // never hit a lock another process made in between.\n const aside = await moveAside(lock, id);\n if (aside === null) return;\n if ((await readFile(aside, 'utf8')) === id) {\n await unlinkIfPresent(aside);\n } else {\n await putBack(aside, lock);\n }\n}\n\n/** Renames the lock to a name only this caller knows; null when there was none. */\nasync function moveAside(lock: string, id: string): Promise<string | null> {\n const aside = `${lock}.${id}.stale`;\n try {\n await rename(lock, aside);\n } catch (err) {\n if (errorCode(err) === 'ENOENT') return null;\n throw err;\n }\n return aside;\n}\n\n/**\n * Puts a lock we moved aside by mistake back under the lock name, unless a\n * process has made a new lock there since (EEXIST): that one wins.\n */\nasync function putBack(aside: string, lock: string): Promise<void> {\n try {\n await link(aside, lock);\n } catch (err) {\n if (errorCode(err) !== 'EEXIST') throw err;\n } finally {\n await unlinkIfPresent(aside);\n }\n}\n\nasync function readLockId(lock: string): Promise<string | null> {\n try {\n return await readFile(lock, 'utf8');\n } catch (err) {\n if (errorCode(err) === 'ENOENT') return null;\n throw err;\n }\n}\n\nasync function unlinkIfPresent(path: string): Promise<void> {\n try {\n await unlink(path);\n } catch (err) {\n if (errorCode(err) !== 'ENOENT') throw err;\n }\n}\n\nfunction delay(ms: number): Promise<void> {\n return new Promise((resolve) => {\n setTimeout(resolve, ms);\n });\n}\n\nfunction toCredentials(value: unknown): Credentials | null {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return null;\n const v = value as Record<string, unknown>;\n if (v.version !== 1) return null;\n const { client_id, email, access_token, refresh_token, expires_at } = v;\n if (!isText(client_id) || !isText(email) || !isText(access_token) || !isText(refresh_token)) {\n return null;\n }\n if (typeof expires_at !== 'number' || !Number.isFinite(expires_at)) return null;\n return { version: 1, client_id, email, access_token, refresh_token, expires_at };\n}\n\nfunction isText(value: unknown): value is string {\n return typeof value === 'string' && value !== '';\n}\n\nfunction errorCode(err: unknown): unknown {\n return typeof err === 'object' && err !== null ? (err as { code?: unknown }).code : undefined;\n}\n","function camel(key: string): string {\n return key.replace(/_([a-z0-9])/g, (_, c: string) => c.toUpperCase());\n}\n\n/** Keys of plain objects from snake_case to camelCase, through arrays and nested objects. Values stay as they are. */\nexport function toCamel<T>(value: unknown): T {\n if (Array.isArray(value)) return value.map((v) => toCamel(v)) as T;\n if (value !== null && typeof value === 'object' && Object.getPrototypeOf(value) === Object.prototype) {\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(value as Record<string, unknown>)) out[camel(k)] = toCamel(v);\n return out as T;\n }\n return value as T;\n}\n","import type { TokenSource } from './auth.js';\nimport { GibeonApiError } from './errors.js';\n\n/** A JSON request (and the read of its answer) gives up after this long. */\nexport const API_TIMEOUT_MS = 60_000;\n\n/** An asset upload gives up after this long: the bytes may take a while. */\nexport const UPLOAD_TIMEOUT_MS = 300_000;\n\ntype Body = string | Uint8Array | ArrayBuffer | undefined;\n\nexport class Http {\n private readonly baseUrl: string;\n private readonly tokens: TokenSource;\n\n constructor(o: { baseUrl: string; tokens: TokenSource }) {\n this.baseUrl = o.baseUrl.replace(/\\/+$/, '');\n this.tokens = o.tokens;\n }\n\n async json<T>(method: string, path: string, body?: unknown): Promise<T> {\n const headers: Record<string, string> = { Accept: 'application/json' };\n let payload: string | undefined;\n if (body !== undefined) {\n headers['Content-Type'] = 'application/json';\n payload = JSON.stringify(body);\n }\n return (await this.send(method, path, headers, payload, API_TIMEOUT_MS)) as T;\n }\n\n async put(path: string, data: Uint8Array | ArrayBuffer, contentType: string): Promise<void> {\n await this.send(\n 'PUT',\n path,\n { Accept: 'application/json', 'Content-Type': contentType },\n data,\n UPLOAD_TIMEOUT_MS,\n );\n }\n\n /** One request; a 401 renews the token once and retries once. Each try gets `timeoutMs`. */\n private async send(\n method: string,\n path: string,\n extra: Record<string, string>,\n body: Body,\n timeoutMs: number,\n ): Promise<unknown> {\n const used = await this.tokens.getToken();\n let res = await this.once(method, path, used, extra, body, timeoutMs);\n if (res.status === 401) {\n const fresh = await this.tokens.renew(used);\n res = await this.once(method, path, fresh, extra, body, timeoutMs);\n }\n if (!res.ok) throw await toApiError(res);\n if (res.status === 204) return undefined;\n let text: string;\n try {\n // The timeout covers the body too: it ends a read that stops halfway.\n text = await res.text();\n } catch (err) {\n throw isTimeout(err) ? timedOut(timeoutMs) : err;\n }\n if (text === '') return undefined;\n try {\n return JSON.parse(text);\n } catch {\n throw new GibeonApiError({\n status: res.status,\n code: 'invalid_json',\n message: 'The API sent an answer that is not JSON.',\n });\n }\n }\n\n private async once(\n method: string,\n path: string,\n token: string,\n extra: Record<string, string>,\n body: Body,\n timeoutMs: number,\n ): Promise<Response> {\n const init: RequestInit = {\n method,\n headers: { Authorization: `Bearer ${token}`, ...extra },\n // A redirect would carry the bearer token to another host.\n redirect: 'error',\n signal: AbortSignal.timeout(timeoutMs),\n };\n if (body !== undefined) init.body = body as NonNullable<RequestInit['body']>;\n try {\n return await fetch(`${this.baseUrl}${path}`, init);\n } catch (err) {\n throw isTimeout(err) ? timedOut(timeoutMs) : err;\n }\n }\n}\n\n/** AbortSignal.timeout rejects the fetch, or errors its body, with a TimeoutError. */\nfunction isTimeout(err: unknown): boolean {\n return typeof err === 'object' && err !== null && (err as { name?: unknown }).name === 'TimeoutError';\n}\n\nfunction timedOut(timeoutMs: number): GibeonApiError {\n return new GibeonApiError({\n status: 0,\n code: 'timeout',\n message: `The API did not answer within ${timeoutMs / 1000} seconds.`,\n });\n}\n\nasync function toApiError(res: Response): Promise<GibeonApiError> {\n const header = res.headers.get('X-Request-Id');\n try {\n const parsed = JSON.parse(await res.text()) as { error?: { code?: unknown; message?: unknown; request_id?: unknown } };\n const e = parsed.error;\n if (e && typeof e.code === 'string' && typeof e.message === 'string') {\n return new GibeonApiError({\n status: res.status,\n code: e.code,\n message: e.message,\n requestId: typeof e.request_id === 'string' ? e.request_id : header,\n });\n }\n } catch {\n // not the API's error body\n }\n return new GibeonApiError({\n status: res.status,\n code: 'http_error',\n message: `HTTP ${res.status}`,\n requestId: header,\n });\n}\n","import { createTokenSource } from './auth.js';\nimport { toCamel } from './case.js';\nimport { GibeonApiError } from './errors.js';\nimport { Http } from './http.js';\nimport type {\n Asset,\n GibeonOptions,\n Playlist,\n PlaylistItem,\n PlaylistItemInput,\n PublishAllResult,\n PublishOneResult,\n Screen,\n ScreenCreateOptions,\n ScreenPatch,\n} from './types.js';\n\nconst DEFAULT_BASE_URL = 'https://api.gibeon.io';\n\nconst BASE_URL_SCHEME = 'new Gibeon({ baseUrl }) needs an https URL, or http on localhost or 127.0.0.1.';\nconst BASE_URL_STORE =\n 'A baseUrl other than api.gibeon.io needs GIBEON_CREDENTIALS_FILE or a token, so its sign-in never replaces the tokens of api.gibeon.io: set GIBEON_CREDENTIALS_FILE to a file of its own, or pass new Gibeon({ token }) or set GIBEON_TOKEN.';\n\ninterface Wrapped<T> {\n data: T;\n}\n\nconst enc = encodeURIComponent;\n\n/**\n * The bearer token goes to `baseUrl`, so only https, or plain http to this\n * machine for a local worker. Another host than the default signs in for its\n * own tokens, which must not land in the default credentials file: it needs a\n * file of its own (GIBEON_CREDENTIALS_FILE) or a token that is never stored.\n */\nfunction checkBaseUrl(baseUrl: string, token: string | undefined): void {\n let url: URL;\n try {\n url = new URL(baseUrl);\n } catch {\n throw new TypeError(BASE_URL_SCHEME);\n }\n const local = url.hostname === 'localhost' || url.hostname === '127.0.0.1';\n if (url.protocol !== 'https:' && !(url.protocol === 'http:' && local)) {\n throw new TypeError(BASE_URL_SCHEME);\n }\n if (baseUrl === DEFAULT_BASE_URL) return;\n const env = process.env;\n if (isSet(token) || isSet(env.GIBEON_TOKEN) || isSet(env.GIBEON_CREDENTIALS_FILE)) return;\n throw new TypeError(BASE_URL_STORE);\n}\n\nfunction isSet(value: string | undefined): boolean {\n return value !== undefined && value !== '';\n}\n\nfunction assetTypeOf(mimeType: string): 'image' | 'pdf' | 'html' {\n if (mimeType.startsWith('image/')) return 'image';\n if (mimeType === 'application/pdf') return 'pdf';\n if (mimeType === 'text/html') return 'html';\n throw new TypeError(\n `assets.upload takes an image, a PDF or an HTML file, not \"${mimeType}\" (mimeType image/*, application/pdf or text/html)`,\n );\n}\n\nexport class Gibeon {\n private readonly http: Http;\n\n readonly screens: {\n list(): Promise<Screen[]>;\n get(id: string): Promise<Screen>;\n create(name: string, opts: ScreenCreateOptions): Promise<Screen>;\n update(id: string, patch: ScreenPatch): Promise<Screen & { publishRequired: boolean }>;\n publish(id: string): Promise<PublishOneResult>;\n publish(): Promise<PublishAllResult>;\n };\n\n readonly playlists: {\n list(): Promise<Playlist[]>;\n get(id: string): Promise<Playlist>;\n create(input: { name: string }): Promise<Playlist>;\n addItem(playlistId: string, item: PlaylistItemInput): Promise<PlaylistItem>;\n };\n\n readonly assets: {\n upload(input: { name: string; data: Uint8Array | ArrayBuffer; mimeType: string }): Promise<Asset>;\n };\n\n constructor(options: GibeonOptions = {}) {\n const baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/+$/, '');\n checkBaseUrl(baseUrl, options.token);\n const tokens = createTokenSource({ email: options.email, token: options.token, baseUrl });\n const http = new Http({ baseUrl, tokens });\n this.http = http;\n\n const getScreen = async (id: string): Promise<Screen> => {\n // GET /v1/players/ would answer the list, which would read back as one screen.\n if (id === '') throw new TypeError('screens.get needs a screen id');\n return toCamel<Screen>((await http.json<Wrapped<unknown>>('GET', `/v1/players/${enc(id)}`)).data);\n };\n\n const publishOne = async (id: string): Promise<PublishOneResult> =>\n toCamel<PublishOneResult>(\n (await http.json<Wrapped<unknown>>('POST', `/v1/players/${enc(id)}/publish`)).data,\n );\n\n const publishAll = async (): Promise<PublishAllResult> =>\n toCamel<PublishAllResult>((await http.json<Wrapped<unknown>>('POST', '/v1/players/publish')).data);\n\n function publish(id: string): Promise<PublishOneResult>;\n function publish(): Promise<PublishAllResult>;\n function publish(id?: string): Promise<PublishOneResult | PublishAllResult> {\n return id === undefined ? publishAll() : publishOne(id);\n }\n\n this.screens = {\n list: async () =>\n toCamel<Screen[]>((await http.json<Wrapped<unknown[]>>('GET', '/v1/players')).data),\n get: getScreen,\n create: async (name, opts) => {\n const wanted = name.trim();\n if (wanted === '') throw new TypeError('screens.create needs a name that is not blank');\n const content: Array<[string, string | undefined]> = [\n ['playlist_id', opts.playlistId],\n ['sequence_id', opts.sequenceId],\n ['planning_id', opts.planningId],\n ];\n const given = content.filter(([, v]) => v !== undefined);\n if (given.length !== 1) {\n throw new TypeError('screens.create needs exactly one of playlistId, sequenceId, planningId');\n }\n const [field, id] = given[0] as [string, string];\n\n const all = (await http.json<Wrapped<Array<{ id: string; name: string; play_url: string | null }>>>(\n 'GET',\n '/v1/players',\n )).data;\n const matches = all.filter((p) => p.play_url !== null && p.name === wanted);\n\n if (matches.length >= 2) {\n const ids = matches.map((m) => m.id);\n throw new GibeonApiError({\n status: 409,\n code: 'ambiguous_name',\n message: `${matches.length} screens are named \"${wanted}\": ${ids.join(', ')}. Rename all but one, or call screens.update(id, ...) with the id you mean.`,\n ids,\n });\n }\n\n if (matches.length === 1) {\n const target = matches[0].id;\n const patch: Record<string, unknown> = {};\n for (const [key] of content) patch[key] = key === field ? id : null;\n if (opts.location !== undefined) patch.location = opts.location;\n const patched = await http.json<{ data: unknown; publish_required?: boolean }>(\n 'PATCH',\n `/v1/players/${enc(target)}`,\n patch,\n );\n // The API says true when a content field changed. Pointed at what it already\n // plays, the screen is not republished: a republish restarts what it shows.\n if (patched.publish_required === true) await publishOne(target);\n return toCamel<Screen>(patched.data);\n }\n\n const body: Record<string, unknown> = { name: wanted, [field]: id };\n if (opts.orientation !== undefined) body.orientation = opts.orientation;\n if (opts.location !== undefined) body.location = opts.location;\n return toCamel<Screen>((await http.json<Wrapped<unknown>>('POST', '/v1/players', body)).data);\n },\n update: async (id, patch) => {\n const map: Array<[keyof ScreenPatch, string]> = [\n ['name', 'name'],\n ['location', 'location'],\n ['playlistId', 'playlist_id'],\n ['sequenceId', 'sequence_id'],\n ['planningId', 'planning_id'],\n ['groupId', 'group_id'],\n ['volume', 'volume'],\n ['isActive', 'is_active'],\n ['hideWatermark', 'hide_watermark'],\n ];\n const body: Record<string, unknown> = {};\n for (const [from, to] of map) if (patch[from] !== undefined) body[to] = patch[from];\n const res = await http.json<{ data: unknown; publish_required: boolean }>(\n 'PATCH',\n `/v1/players/${enc(id)}`,\n body,\n );\n return { ...toCamel<Screen>(res.data), publishRequired: res.publish_required };\n },\n publish,\n };\n\n this.playlists = {\n list: async () =>\n toCamel<Playlist[]>((await http.json<Wrapped<unknown[]>>('GET', '/v1/playlists')).data),\n get: async (id) =>\n toCamel<Playlist>((await http.json<Wrapped<unknown>>('GET', `/v1/playlists/${enc(id)}`)).data),\n create: async (input) =>\n toCamel<Playlist>((await http.json<Wrapped<unknown>>('POST', '/v1/playlists', input)).data),\n addItem: async (playlistId, item) =>\n toCamel<PlaylistItem>(\n (await http.json<Wrapped<unknown>>('POST', `/v1/playlists/${enc(playlistId)}/items`, item)).data,\n ),\n };\n\n this.assets = {\n upload: async ({ name, data, mimeType }) => {\n const assetType = assetTypeOf(mimeType);\n const created = await http.json<Wrapped<{ id: string }>>('POST', '/v1/assets', {\n name,\n asset_type: assetType,\n mime_type: mimeType,\n file_size: data.byteLength,\n });\n const id = created.data.id;\n // The answer's upload.url is ignored: the bytes go to our own base URL, so the bearer token stays there.\n await http.put(`/v1/assets/${enc(id)}/upload`, data, mimeType);\n return toCamel<Asset>((await http.json<Wrapped<unknown>>('GET', `/v1/assets/${enc(id)}`)).data);\n },\n };\n }\n\n async request<T = unknown>(method: string, path: string, body?: unknown): Promise<T> {\n if (!path.startsWith('/')) throw new TypeError('request path must start with \"/\"');\n return this.http.json<T>(method, path, body);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACOO,IAAM,kBAAN,cAA8B,MAAM;AAAA,EAChC;AAAA,EAET,YAAY,MAA2B,SAAiB;AACtD,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,OAAO;AAAA,EACd;AACF;AAEO,IAAM,iBAAN,cAA6B,MAAM;AAAA,EAC/B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAET,YAAY,MAMT;AACD,UAAM,KAAK,OAAO;AAClB,SAAK,OAAO;AACZ,SAAK,SAAS,KAAK;AACnB,SAAK,OAAO,KAAK;AACjB,SAAK,YAAY,KAAK,aAAa;AACnC,QAAI,KAAK,QAAQ,OAAW,MAAK,MAAM,KAAK;AAAA,EAC9C;AACF;;;ACrCA,2BAAgC;;;ACAhC,gCAAsB;AAStB,IAAM,eAAe;AAGd,SAAS,kBAAkB,GAItB;AACV,MAAI,CAAC,EAAE,YAAa,QAAO;AAC3B,MAAI,MAAM,EAAE,IAAI,EAAE,EAAG,QAAO;AAC5B,MAAI,EAAE,aAAa,YAAY,EAAE,aAAa,QAAS,QAAO;AAC9D,MAAI,EAAE,aAAa,QAAS,QAAO,MAAM,EAAE,IAAI,OAAO,KAAK,MAAM,EAAE,IAAI,eAAe;AACtF,SAAO;AACT;AAEO,SAAS,eACd,UACA,KACgF;AAChF,UAAQ,UAAU;AAAA,IAChB,KAAK;AACH,aAAO,EAAE,SAAS,QAAQ,MAAM,CAAC,GAAG,EAAE;AAAA,IACxC,KAAK;AAEH,aAAO,EAAE,SAAS,OAAO,MAAM,CAAC,MAAM,SAAS,MAAM,GAAG,GAAG,0B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YAAY,YAAY,QAAQ;AACtC,cAAM,UAAU,MAAM,KAAK,KAA8B,QAAQ,cAAc;AAAA,UAC7E;AAAA,UACA,YAAY;AAAA,UACZ,WAAW;AAAA,UACX,WAAW,KAAK;AAAA,QAClB,CAAC;AACD,cAAM,KAAK,QAAQ,KAAK;AAExB,cAAM,KAAK,IAAI,cAAc,IAAI,EAAE,CAAC,WAAW,MAAM,QAAQ;AAC7D,eAAO,SAAgB,MAAM,KAAK,KAAuB,OAAO,cAAc,IAAI,EAAE,CAAC,EAAE,GAAG,IAAI;AAAA,MAChG;AAAA,IACF;AAAA,EACF;AAAA,EAEA,MAAM,QAAqB,QAAgB,MAAc,MAA4B;AACnF,QAAI,CAAC,KAAK,WAAW,GAAG,EAAG,OAAM,IAAI,UAAU,kCAAkC;AACjF,WAAO,KAAK,KAAK,KAAQ,QAAQ,MAAM,IAAI;AAAA,EAC7C;AACF;","names":["resolve","delay","open","errorCode","isText","resolve","isSet"]}
@@ -0,0 +1,179 @@
1
+ type GibeonAuthErrorCode = 'email_required' | 'claim_expired' | 'rate_limited' | 'token_expired' | 'sign_in_failed';
2
+ declare class GibeonAuthError extends Error {
3
+ readonly code: GibeonAuthErrorCode;
4
+ constructor(code: GibeonAuthErrorCode, message: string);
5
+ }
6
+ declare class GibeonApiError extends Error {
7
+ readonly status: number;
8
+ readonly code: string;
9
+ readonly requestId: string | null;
10
+ readonly ids?: string[];
11
+ constructor(init: {
12
+ status: number;
13
+ code: string;
14
+ message: string;
15
+ requestId?: string | null;
16
+ ids?: string[];
17
+ });
18
+ }
19
+
20
+ interface Screen {
21
+ id: string;
22
+ name: string;
23
+ location: string | null;
24
+ status: 'online' | 'offline';
25
+ lastSeen: string | null;
26
+ playlistId: string | null;
27
+ sequenceId: string | null;
28
+ planningId: string | null;
29
+ groupId: string | null;
30
+ volume: number;
31
+ isActive: boolean;
32
+ hideWatermark: boolean;
33
+ playUrl: string | null;
34
+ createdAt: string;
35
+ updatedAt: string;
36
+ }
37
+ interface Playlist {
38
+ id: string;
39
+ name: string;
40
+ defaultInterval: number;
41
+ imageUri: string | null;
42
+ createdAt: string;
43
+ updatedAt: string;
44
+ }
45
+ interface PlaylistItem {
46
+ id: string;
47
+ playlistId: string;
48
+ type: string;
49
+ name: string | null;
50
+ assetId: string | null;
51
+ externalUrl: string | null;
52
+ durationSeconds: number;
53
+ sortOrder: number;
54
+ isSelected: boolean;
55
+ scheduleStart: string | null;
56
+ scheduleEnd: string | null;
57
+ config: Record<string, unknown>;
58
+ createdAt: string;
59
+ }
60
+ interface Asset {
61
+ id: string;
62
+ name: string;
63
+ assetType: string;
64
+ mimeType: string | null;
65
+ fileSize: number | null;
66
+ width: number | null;
67
+ height: number | null;
68
+ duration: number | null;
69
+ folderId: string | null;
70
+ url: string | null;
71
+ status: string;
72
+ createdAt: string;
73
+ updatedAt: string;
74
+ }
75
+ interface PublishOneResult {
76
+ playerId: string;
77
+ snapshotBuiltAt: string;
78
+ snapshotSizeBytes: number;
79
+ }
80
+ interface PublishAllResult {
81
+ published: number;
82
+ failed: number;
83
+ players: Array<{
84
+ id: string;
85
+ status: 'published' | 'skipped' | 'failed';
86
+ snapshotBuiltAt?: string;
87
+ reason?: string;
88
+ }>;
89
+ }
90
+ type ScreenContent = {
91
+ playlistId: string;
92
+ sequenceId?: never;
93
+ planningId?: never;
94
+ } | {
95
+ sequenceId: string;
96
+ playlistId?: never;
97
+ planningId?: never;
98
+ } | {
99
+ planningId: string;
100
+ playlistId?: never;
101
+ sequenceId?: never;
102
+ };
103
+ type ScreenCreateOptions = ScreenContent & {
104
+ orientation?: 'landscape' | 'portrait';
105
+ location?: string | null;
106
+ };
107
+ interface ScreenPatch {
108
+ name?: string;
109
+ location?: string | null;
110
+ playlistId?: string | null;
111
+ sequenceId?: string | null;
112
+ planningId?: string | null;
113
+ groupId?: string | null;
114
+ volume?: number;
115
+ isActive?: boolean;
116
+ hideWatermark?: boolean;
117
+ }
118
+ /** The API body of POST /v1/playlists/{id}/items, in the API's snake_case. */
119
+ type PlaylistItemInput = {
120
+ name?: string | null;
121
+ duration_seconds?: number;
122
+ is_selected?: boolean;
123
+ schedule_start?: string | null;
124
+ schedule_end?: string | null;
125
+ } & ({
126
+ type: 'image' | 'video';
127
+ asset_id: string;
128
+ } | {
129
+ type: 'youtube';
130
+ external_url: string;
131
+ } | {
132
+ type: 'image_slideshow';
133
+ config: {
134
+ asset_ids: string[];
135
+ image_duration?: number;
136
+ transition_speed?: number;
137
+ fit?: 'contain' | 'cover';
138
+ bg_color?: string;
139
+ randomize?: boolean;
140
+ };
141
+ });
142
+ interface GibeonOptions {
143
+ email?: string;
144
+ token?: string;
145
+ baseUrl?: string;
146
+ }
147
+
148
+ declare class Gibeon {
149
+ private readonly http;
150
+ readonly screens: {
151
+ list(): Promise<Screen[]>;
152
+ get(id: string): Promise<Screen>;
153
+ create(name: string, opts: ScreenCreateOptions): Promise<Screen>;
154
+ update(id: string, patch: ScreenPatch): Promise<Screen & {
155
+ publishRequired: boolean;
156
+ }>;
157
+ publish(id: string): Promise<PublishOneResult>;
158
+ publish(): Promise<PublishAllResult>;
159
+ };
160
+ readonly playlists: {
161
+ list(): Promise<Playlist[]>;
162
+ get(id: string): Promise<Playlist>;
163
+ create(input: {
164
+ name: string;
165
+ }): Promise<Playlist>;
166
+ addItem(playlistId: string, item: PlaylistItemInput): Promise<PlaylistItem>;
167
+ };
168
+ readonly assets: {
169
+ upload(input: {
170
+ name: string;
171
+ data: Uint8Array | ArrayBuffer;
172
+ mimeType: string;
173
+ }): Promise<Asset>;
174
+ };
175
+ constructor(options?: GibeonOptions);
176
+ request<T = unknown>(method: string, path: string, body?: unknown): Promise<T>;
177
+ }
178
+
179
+ export { type Asset, Gibeon, GibeonApiError, GibeonAuthError, type GibeonAuthErrorCode, type GibeonOptions, type Playlist, type PlaylistItem, type PlaylistItemInput, type PublishAllResult, type PublishOneResult, type Screen, type ScreenCreateOptions, type ScreenPatch };
@@ -0,0 +1,179 @@
1
+ type GibeonAuthErrorCode = 'email_required' | 'claim_expired' | 'rate_limited' | 'token_expired' | 'sign_in_failed';
2
+ declare class GibeonAuthError extends Error {
3
+ readonly code: GibeonAuthErrorCode;
4
+ constructor(code: GibeonAuthErrorCode, message: string);
5
+ }
6
+ declare class GibeonApiError extends Error {
7
+ readonly status: number;
8
+ readonly code: string;
9
+ readonly requestId: string | null;
10
+ readonly ids?: string[];
11
+ constructor(init: {
12
+ status: number;
13
+ code: string;
14
+ message: string;
15
+ requestId?: string | null;
16
+ ids?: string[];
17
+ });
18
+ }
19
+
20
+ interface Screen {
21
+ id: string;
22
+ name: string;
23
+ location: string | null;
24
+ status: 'online' | 'offline';
25
+ lastSeen: string | null;
26
+ playlistId: string | null;
27
+ sequenceId: string | null;
28
+ planningId: string | null;
29
+ groupId: string | null;
30
+ volume: number;
31
+ isActive: boolean;
32
+ hideWatermark: boolean;
33
+ playUrl: string | null;
34
+ createdAt: string;
35
+ updatedAt: string;
36
+ }
37
+ interface Playlist {
38
+ id: string;
39
+ name: string;
40
+ defaultInterval: number;
41
+ imageUri: string | null;
42
+ createdAt: string;
43
+ updatedAt: string;
44
+ }
45
+ interface PlaylistItem {
46
+ id: string;
47
+ playlistId: string;
48
+ type: string;
49
+ name: string | null;
50
+ assetId: string | null;
51
+ externalUrl: string | null;
52
+ durationSeconds: number;
53
+ sortOrder: number;
54
+ isSelected: boolean;
55
+ scheduleStart: string | null;
56
+ scheduleEnd: string | null;
57
+ config: Record<string, unknown>;
58
+ createdAt: string;
59
+ }
60
+ interface Asset {
61
+ id: string;
62
+ name: string;
63
+ assetType: string;
64
+ mimeType: string | null;
65
+ fileSize: number | null;
66
+ width: number | null;
67
+ height: number | null;
68
+ duration: number | null;
69
+ folderId: string | null;
70
+ url: string | null;
71
+ status: string;
72
+ createdAt: string;
73
+ updatedAt: string;
74
+ }
75
+ interface PublishOneResult {
76
+ playerId: string;
77
+ snapshotBuiltAt: string;
78
+ snapshotSizeBytes: number;
79
+ }
80
+ interface PublishAllResult {
81
+ published: number;
82
+ failed: number;
83
+ players: Array<{
84
+ id: string;
85
+ status: 'published' | 'skipped' | 'failed';
86
+ snapshotBuiltAt?: string;
87
+ reason?: string;
88
+ }>;
89
+ }
90
+ type ScreenContent = {
91
+ playlistId: string;
92
+ sequenceId?: never;
93
+ planningId?: never;
94
+ } | {
95
+ sequenceId: string;
96
+ playlistId?: never;
97
+ planningId?: never;
98
+ } | {
99
+ planningId: string;
100
+ playlistId?: never;
101
+ sequenceId?: never;
102
+ };
103
+ type ScreenCreateOptions = ScreenContent & {
104
+ orientation?: 'landscape' | 'portrait';
105
+ location?: string | null;
106
+ };
107
+ interface ScreenPatch {
108
+ name?: string;
109
+ location?: string | null;
110
+ playlistId?: string | null;
111
+ sequenceId?: string | null;
112
+ planningId?: string | null;
113
+ groupId?: string | null;
114
+ volume?: number;
115
+ isActive?: boolean;
116
+ hideWatermark?: boolean;
117
+ }
118
+ /** The API body of POST /v1/playlists/{id}/items, in the API's snake_case. */
119
+ type PlaylistItemInput = {
120
+ name?: string | null;
121
+ duration_seconds?: number;
122
+ is_selected?: boolean;
123
+ schedule_start?: string | null;
124
+ schedule_end?: string | null;
125
+ } & ({
126
+ type: 'image' | 'video';
127
+ asset_id: string;
128
+ } | {
129
+ type: 'youtube';
130
+ external_url: string;
131
+ } | {
132
+ type: 'image_slideshow';
133
+ config: {
134
+ asset_ids: string[];
135
+ image_duration?: number;
136
+ transition_speed?: number;
137
+ fit?: 'contain' | 'cover';
138
+ bg_color?: string;
139
+ randomize?: boolean;
140
+ };
141
+ });
142
+ interface GibeonOptions {
143
+ email?: string;
144
+ token?: string;
145
+ baseUrl?: string;
146
+ }
147
+
148
+ declare class Gibeon {
149
+ private readonly http;
150
+ readonly screens: {
151
+ list(): Promise<Screen[]>;
152
+ get(id: string): Promise<Screen>;
153
+ create(name: string, opts: ScreenCreateOptions): Promise<Screen>;
154
+ update(id: string, patch: ScreenPatch): Promise<Screen & {
155
+ publishRequired: boolean;
156
+ }>;
157
+ publish(id: string): Promise<PublishOneResult>;
158
+ publish(): Promise<PublishAllResult>;
159
+ };
160
+ readonly playlists: {
161
+ list(): Promise<Playlist[]>;
162
+ get(id: string): Promise<Playlist>;
163
+ create(input: {
164
+ name: string;
165
+ }): Promise<Playlist>;
166
+ addItem(playlistId: string, item: PlaylistItemInput): Promise<PlaylistItem>;
167
+ };
168
+ readonly assets: {
169
+ upload(input: {
170
+ name: string;
171
+ data: Uint8Array | ArrayBuffer;
172
+ mimeType: string;
173
+ }): Promise<Asset>;
174
+ };
175
+ constructor(options?: GibeonOptions);
176
+ request<T = unknown>(method: string, path: string, body?: unknown): Promise<T>;
177
+ }
178
+
179
+ export { type Asset, Gibeon, GibeonApiError, GibeonAuthError, type GibeonAuthErrorCode, type GibeonOptions, type Playlist, type PlaylistItem, type PlaylistItemInput, type PublishAllResult, type PublishOneResult, type Screen, type ScreenCreateOptions, type ScreenPatch };