Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
410 changes: 410 additions & 0 deletions bun.lock

Large diffs are not rendered by default.

Binary file modified bun.lockb
Binary file not shown.
211 changes: 211 additions & 0 deletions lib/admin/Table.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,211 @@
import React from "react"
import { timeAgo } from "./time-ago"

declare global {
interface Window {
timezone?: string
}
}

const pluralize = (resource: string) => {
if (resource.endsWith("s")) return resource
return resource.endsWith("y") ? `${resource.slice(0, -1)}ies` : `${resource}s`
}

const removeResourcePrefixes = (resource: string) => {
if (resource.startsWith("creator_")) return resource.slice(8)
if (resource.startsWith("owner_")) return resource.slice(6)
if (resource.startsWith("personal_")) return resource.slice(9)
return resource
}

// Adapt downloadable columns for generic use
const DOWNLOADABLE_COLUMNS = ["data", "metadata", "config"]

const Cell = ({
columnKey,
cellValue,
timezone,
}: {
columnKey: string
cellValue: any
timezone: string
}) => {
if (typeof cellValue === "boolean") return <>{String(cellValue)}</>
if (cellValue === null || cellValue === undefined) return <></>
if (React.isValidElement(cellValue)) return cellValue

// Handle arrays of IDs (e.g., thing_ids)
if (columnKey.endsWith("_ids") && Array.isArray(cellValue)) {
const resource = pluralize(columnKey.slice(0, -4))
return (
<div className="flex flex-col space-y-1">
{cellValue.map((id: string, index: number) => (
<a
key={index}
href={`/_fake/admin/${removeResourcePrefixes(resource)}/get?${removeResourcePrefixes(columnKey.slice(0, -1))}=${id}`}
className="text-blue-500 hover:underline"
>
{id?.split("-")?.[0]}...
</a>
))}
</div>
)
}

// Handle single IDs
if (columnKey.endsWith("_id") && typeof cellValue === "string") {
const resource = pluralize(columnKey.slice(0, -3))
return (
<a
href={`/_fake/admin/${removeResourcePrefixes(resource)}/get?${removeResourcePrefixes(columnKey)}=${cellValue}`}
className="text-blue-500 hover:underline"
>
{cellValue?.split("-")?.[0]}...
</a>
)
}

if (columnKey.endsWith("_at")) {
return <span className="tabular-nums">{timeAgo(cellValue, timezone)}</span>
}

if (DOWNLOADABLE_COLUMNS.includes(columnKey)) {
let b64: string
let filename: string
let contentType: string
if (typeof cellValue === "object") {
const jsonStr = JSON.stringify(cellValue, null, 2)
b64 = Buffer.from(jsonStr).toString("base64")
filename = `${columnKey}.json`
contentType = "application/json"
} else if (typeof cellValue === "string") {
b64 = Buffer.from(cellValue).toString("base64")
filename = `${columnKey}`
contentType = "application/octet-stream"
} else {
throw new Error(`Unknown cell value type: ${typeof cellValue}`)
}
return (
<div
// biome-ignore lint/security/noDangerouslySetInnerHtml: <explanation>
dangerouslySetInnerHTML={{
__html: `<button
class="bg-transparent hover:bg-transparent font-normal text-blue-500 hover:text-blue-700 py-1 px-2 rounded"
onclick="(function(){
const a = document.createElement('a');
const content = atob('${b64}');
const blob = new Blob([content], {type: '${contentType}'});
a.href = window.URL.createObjectURL(blob);
a.download = '${filename}';
a.click();
window.URL.revokeObjectURL(a.href);
})();return false;"
>
Download
</button>`,
}}
/>
)
}

if (typeof cellValue === "object") {
return (
<details>
<summary>{JSON.stringify(cellValue).slice(0, 40)}...</summary>
<pre>{JSON.stringify(cellValue, null, 2)}</pre>
</details>
)
}

return <>{String(cellValue)}</>
}

export const Table = ({
rows,
obj,
timezone,
}: {
rows?: Record<string, any>[]
obj?: Record<string, any>
timezone?: string
}) => {
if (!timezone) {
timezone =
(typeof window !== "undefined" ? window.timezone : undefined) ?? "UTC"
}

if (obj) {
const entries = Object.entries(obj)
return (
<table className="min-w-full divide-y divide-gray-200 bg-white shadow-sm rounded-lg overflow-hidden">
<thead>
<tr>
<th className="px-4 py-3 bg-gray-50 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Key
</th>
<th className="px-4 py-3 bg-gray-50 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Value
</th>
</tr>
</thead>
<tbody>
{entries.map(([key, value], index) => (
<tr key={index} className="hover:bg-gray-50">
<td className="px-4 py-2 whitespace-nowrap text-sm text-gray-900 border-b border-gray-100">
{key}
</td>
<td className="px-4 py-2 whitespace-normal text-sm text-gray-600 border-b border-gray-100">
<Cell columnKey={key} cellValue={value} timezone={timezone!} />
</td>
</tr>
))}
</tbody>
</table>
)
}

if (!rows || rows.length === 0)
return (
<div className="text-center py-8 bg-gray-50 rounded-lg border border-gray-200 text-gray-500">
Empty Table
</div>
)

const keys = Object.keys(rows[0]!)

return (
<table className="min-w-full divide-y divide-gray-200 bg-white shadow-sm rounded-lg overflow-hidden">
<thead>
<tr>
{keys.map((key) => (
<th
key={key}
className="px-4 py-3 bg-gray-50 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"
>
{key}
</th>
))}
</tr>
</thead>
<tbody>
{rows.map((row, rowIndex) => (
<tr key={rowIndex}>
{keys.map((key) => (
<td
key={key}
className="px-4 py-2 whitespace-normal text-sm text-gray-600 border-b border-gray-100"
>
<Cell
columnKey={key}
cellValue={row[key]}
timezone={timezone!}
/>
</td>
))}
</tr>
))}
</tbody>
</table>
)
}
29 changes: 29 additions & 0 deletions lib/admin/time-ago.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
export function timeAgo(date: Date, timezone: string = "UTC"): string {
const now = new Date()
const formatter = new Intl.DateTimeFormat("en-US", {
timeZone: timezone,
hour: "numeric",
minute: "numeric",
hour12: true,
})

const formattedTime = formatter.format(date)
const seconds = Math.floor((now.getTime() - date.getTime()) / 1000)

if (seconds < 60) {
return `${seconds}s ago (${formattedTime})`
}

const minutes = Math.floor(seconds / 60)
if (minutes < 60) {
return `${minutes}m ago (${formattedTime})`
}

const hours = Math.floor(minutes / 60)
if (hours < 24) {
return `${hours}h ago (${formattedTime})`
}

const days = Math.floor(hours / 24)
return `${days}d ago (${formattedTime})`
}
99 changes: 99 additions & 0 deletions lib/middleware/with-ctx-react.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
import { renderToString } from "react-dom/server"
import type { Middleware } from "winterspec"
import React from "react"
import type { ReactNode } from "react"
import { timeAgo } from "lib/admin/time-ago"

export const withCtxReact: Middleware<
{},
{ react: (component: ReactNode) => Response }
> = async (req, ctx, next) => {
ctx.react = (component: ReactNode) => {
const pathComponents = new URL(req.url).pathname.split("/").filter(Boolean)
const timezone = req.headers.get("X-Timezone") || "UTC"
return new Response(
renderToString(
<html lang="en">
<script src="https://cdn.tailwindcss.com" />
<style
type="text/tailwindcss"
// biome-ignore lint/security/noDangerouslySetInnerHtml: <explanation>
dangerouslySetInnerHTML={{
__html: `
.btn {
@apply text-white visited:text-white m-1 bg-blue-500 hover:bg-blue-700 font-bold py-2 px-4 rounded
}
a {
@apply underline text-blue-600 hover:text-blue-800 visited:text-purple-800 m-1
}
h2 {
@apply text-xl font-bold my-2
}
input, select {
@apply border border-gray-300 rounded p-1 ml-0.5
}
form {
@apply inline-flex flex-col gap-2 border border-gray-300 rounded p-2 m-2 text-xs
}
button {
@apply bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded
}
`,
}}
/>
<body>
<div>
<div className="border-b border-gray-300 py-1 flex justify-between items-center">
<div>
<span className="px-1 pr-2">admin panel</span>
{pathComponents.map((component, index) => {
return (
<span key={index}>
<span className="px-0.5 text-gray-500">/</span>
<a
href={`/${pathComponents.slice(0, index + 1).join("/")}`}
>
{component}
</a>
</span>
)
})}
</div>
<div className="mr-2 flex items-center">
<div className="text-xs text-gray-500 mr-1">
{timeAgo(new Date(), timezone)}
</div>
<div
// biome-ignore lint/security/noDangerouslySetInnerHtml: <explanation>
dangerouslySetInnerHTML={{
__html: `
<select
id="timezone-select"
class="text-xs"
value="${timezone}"
onchange="document.cookie = 'timezone=' + this.value + ';path=/'; location.reload();"
>
<option ${timezone === "UTC" ? "selected" : ""} value="UTC">UTC</option>
<option ${timezone === "America/Los_Angeles" ? "selected" : ""} value="America/Los_Angeles">Pacific</option>
<option ${timezone === "Asia/Kolkata" ? "selected" : ""} value="Asia/Kolkata">IST</option>
</select>
`,
}}
/>
</div>
</div>
<div className="flex flex-col text-xs p-1">{component}</div>
</div>
</body>
</html>,
),
{
headers: {
"Content-Type": "text/html",
},
},
)
}

return await next(req, ctx)
}
10 changes: 9 additions & 1 deletion lib/middleware/with-db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,22 @@ import type { DbClient } from "lib/db/db-client"
import { createDatabase } from "lib/db/db-client"
import type { Middleware } from "winterspec/middleware"

// Create a singleton instance of the database
let dbInstance: DbClient | null = null

export const withDb: Middleware<
{},
{
db: DbClient
}
> = async (req, ctx, next) => {
// Only set db if not already provided by another middleware
if (!ctx.db) {
ctx.db = createDatabase()
if (!dbInstance) {
dbInstance = createDatabase()
}
ctx.db = dbInstance
}

return next(req, ctx)
}
3 changes: 2 additions & 1 deletion lib/middleware/with-winter-spec.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import { createWithWinterSpec } from "winterspec"
import { withDb } from "./with-db"
import { withCtxReact } from "./with-ctx-react"

export const withRouteSpec = createWithWinterSpec({
apiName: "tscircuit Debug API",
productionServerUrl: "https://debug-api.tscircuit.com",
beforeAuthMiddleware: [],
authMiddleware: {},
afterAuthMiddleware: [withDb],
afterAuthMiddleware: [withDb, withCtxReact],
})
Loading