Merge branch 'main' of https://github.com/probablycorey/the-rabbit-hole
This commit is contained in:
commit
6950f43ead
|
|
@ -0,0 +1,111 @@
|
|||
---
|
||||
description: Use Bun instead of Node.js, npm, pnpm, or vite.
|
||||
globs: "*.ts, *.tsx, *.html, *.css, *.js, *.jsx, package.json"
|
||||
alwaysApply: false
|
||||
---
|
||||
|
||||
Default to using Bun instead of Node.js.
|
||||
|
||||
- Use `bun <file>` instead of `node <file>` or `ts-node <file>`
|
||||
- Use `bun test` instead of `jest` or `vitest`
|
||||
- Use `bun build <file.html|file.ts|file.css>` instead of `webpack` or `esbuild`
|
||||
- Use `bun install` instead of `npm install` or `yarn install` or `pnpm install`
|
||||
- Use `bun run <script>` instead of `npm run <script>` or `yarn run <script>` or `pnpm run <script>`
|
||||
- Bun automatically loads .env, so don't use dotenv.
|
||||
|
||||
## APIs
|
||||
|
||||
- `Bun.serve()` supports WebSockets, HTTPS, and routes. Don't use `express`.
|
||||
- `bun:sqlite` for SQLite. Don't use `better-sqlite3`.
|
||||
- `Bun.redis` for Redis. Don't use `ioredis`.
|
||||
- `Bun.sql` for Postgres. Don't use `pg` or `postgres.js`.
|
||||
- `WebSocket` is built-in. Don't use `ws`.
|
||||
- Prefer `Bun.file` over `node:fs`'s readFile/writeFile
|
||||
- Bun.$`ls` instead of execa.
|
||||
|
||||
## Testing
|
||||
|
||||
Use `bun test` to run tests.
|
||||
|
||||
```ts#index.test.ts
|
||||
import { test, expect } from "bun:test";
|
||||
|
||||
test("hello world", () => {
|
||||
expect(1).toBe(1);
|
||||
});
|
||||
```
|
||||
|
||||
## Frontend
|
||||
|
||||
Use HTML imports with `Bun.serve()`. Don't use `vite`. HTML imports fully support React, CSS, Tailwind.
|
||||
|
||||
Server:
|
||||
|
||||
```ts#index.ts
|
||||
import index from "./index.html"
|
||||
|
||||
Bun.serve({
|
||||
routes: {
|
||||
"/": index,
|
||||
"/api/users/:id": {
|
||||
GET: (req) => {
|
||||
return new Response(JSON.stringify({ id: req.params.id }));
|
||||
},
|
||||
},
|
||||
},
|
||||
// optional websocket support
|
||||
websocket: {
|
||||
open: (ws) => {
|
||||
ws.send("Hello, world!");
|
||||
},
|
||||
message: (ws, message) => {
|
||||
ws.send(message);
|
||||
},
|
||||
close: (ws) => {
|
||||
// handle close
|
||||
}
|
||||
},
|
||||
development: {
|
||||
hmr: true,
|
||||
console: true,
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
HTML files can import .tsx, .jsx or .js files directly and Bun's bundler will transpile & bundle automatically. `<link>` tags can point to stylesheets and Bun's CSS bundler will bundle.
|
||||
|
||||
```html#index.html
|
||||
<html>
|
||||
<body>
|
||||
<h1>Hello, world!</h1>
|
||||
<script type="module" src="./frontend.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
With the following `frontend.tsx`:
|
||||
|
||||
```tsx#frontend.tsx
|
||||
import React from "react";
|
||||
|
||||
// import .css files directly and it works
|
||||
import './index.css';
|
||||
|
||||
import { createRoot } from "react-dom/client";
|
||||
|
||||
const root = createRoot(document.body);
|
||||
|
||||
export default function Frontend() {
|
||||
return <h1>Hello, world!</h1>;
|
||||
}
|
||||
|
||||
root.render(<Frontend />);
|
||||
```
|
||||
|
||||
Then, run index.ts
|
||||
|
||||
```sh
|
||||
bun --hot ./index.ts
|
||||
```
|
||||
|
||||
For more information, read the Bun API docs in `node_modules/bun-types/docs/**.md`.
|
||||
23
packages/cubby/.cursor/rules/workshop.mdc
Normal file
23
packages/cubby/.cursor/rules/workshop.mdc
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
---
|
||||
description: The Workshop's JS/TS style.
|
||||
alwaysApply: false
|
||||
globs: "*.ts, *.tsx, *.html, *.css, *.js, *.jsx"
|
||||
---
|
||||
|
||||
- No semicolons — ever.
|
||||
- No comments — ever.
|
||||
- 2‑space indentation.
|
||||
- Double quotes for strings.
|
||||
- Trailing commas where ES5 allows (objects, arrays, imports).
|
||||
- Keep lines <= 100 characters.
|
||||
- End every file with a single newline.
|
||||
|
||||
- This project runs on Bun.
|
||||
- Assume `strict` mode is on (no implicit `any`).
|
||||
- Prefer `const`; use `let` only when reassignment is required.
|
||||
- Avoid the `any` type unless unavoidable.
|
||||
- Use `import type { … }` when importing only types.
|
||||
- In TypeScript files put npm imports first, then std imports, then library imports.
|
||||
|
||||
- Respond in a concise, direct tone.
|
||||
- Do not ask follow‑up questions unless clarification is essential.
|
||||
35
packages/cubby/.gitignore
vendored
Normal file
35
packages/cubby/.gitignore
vendored
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
# dependencies (bun install)
|
||||
node_modules
|
||||
cubby/
|
||||
|
||||
# output
|
||||
out
|
||||
dist
|
||||
*.tgz
|
||||
|
||||
# code coverage
|
||||
coverage
|
||||
*.lcov
|
||||
|
||||
# logs
|
||||
logs
|
||||
_.log
|
||||
report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json
|
||||
|
||||
# dotenv environment variable files
|
||||
.env
|
||||
.env.development.local
|
||||
.env.test.local
|
||||
.env.production.local
|
||||
.env.local
|
||||
|
||||
# caches
|
||||
.eslintcache
|
||||
.cache
|
||||
*.tsbuildinfo
|
||||
|
||||
# IntelliJ based IDEs
|
||||
.idea
|
||||
|
||||
# Finder (MacOS) folder config
|
||||
.DS_Store
|
||||
15
packages/cubby/README.md
Normal file
15
packages/cubby/README.md
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
# cubby
|
||||
|
||||
To install dependencies:
|
||||
|
||||
```bash
|
||||
bun install
|
||||
```
|
||||
|
||||
To run:
|
||||
|
||||
```bash
|
||||
bun run index.ts
|
||||
```
|
||||
|
||||
This project was created using `bun init` in bun v1.2.18. [Bun](https://bun.sh) is a fast all-in-one JavaScript runtime.
|
||||
0
packages/cubby/main
Normal file
0
packages/cubby/main
Normal file
23
packages/cubby/package.json
Normal file
23
packages/cubby/package.json
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
{
|
||||
"name": "cubby",
|
||||
"module": "src/server.tsx",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "bun subdomain:dev",
|
||||
"subdomain:start": "bun run src/server.tsx",
|
||||
"subdomain:dev": "bun run --hot src/server.tsx"
|
||||
},
|
||||
"dependencies": {
|
||||
"hono": "catalog:",
|
||||
"marked": "^16.1.1",
|
||||
"preact": "^10.26.9",
|
||||
"preact-render-to-string": "^6.5.13"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/bun": "latest"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"typescript": "^5"
|
||||
}
|
||||
}
|
||||
104
packages/cubby/public/css/main.css
Normal file
104
packages/cubby/public/css/main.css
Normal file
|
|
@ -0,0 +1,104 @@
|
|||
.content-wrapper {
|
||||
display: flex;
|
||||
gap: 2rem;
|
||||
}
|
||||
|
||||
.main-content {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.side-content {
|
||||
width: 30%;
|
||||
min-width: 250px;
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.content-wrapper {
|
||||
flex-direction: column;
|
||||
}
|
||||
.side-content {
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
main ul.file-list {
|
||||
list-style: none;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
main ul.file-list li {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
main ul.file-list li .delete-button {
|
||||
display: none;
|
||||
padding: 0 4px;
|
||||
margin: 0;
|
||||
background: none;
|
||||
border: none;
|
||||
font-weight: bold;
|
||||
color: #ff4444;
|
||||
transition: transform 0.2s;
|
||||
cursor: pointer;
|
||||
font-size: 1.2em;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
main ul.file-list li:hover .delete-button {
|
||||
display: block;
|
||||
}
|
||||
|
||||
main ul.file-list li .delete-button:hover {
|
||||
transform: scale(1.2);
|
||||
}
|
||||
|
||||
.upload-container {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.file-input {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.upload-button {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.progress-container {
|
||||
position: fixed;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
padding: 10px;
|
||||
background: rgba(0, 0, 0, 0.1);
|
||||
display: none;
|
||||
}
|
||||
|
||||
.progress-bar {
|
||||
width: 0%;
|
||||
height: 20px;
|
||||
background: #4CAF50;
|
||||
}
|
||||
|
||||
.drag-overlay {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
background: rgba(0, 0, 0, 0.7);
|
||||
z-index: 1000;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
display: none;
|
||||
}
|
||||
|
||||
.drag-text {
|
||||
color: white;
|
||||
font-size: 2em;
|
||||
}
|
||||
4
packages/cubby/public/css/pico.fuchsia.css
Normal file
4
packages/cubby/public/css/pico.fuchsia.css
Normal file
File diff suppressed because one or more lines are too long
4
packages/cubby/public/css/pico.min.css
vendored
Normal file
4
packages/cubby/public/css/pico.min.css
vendored
Normal file
File diff suppressed because one or more lines are too long
114
packages/cubby/public/js/project.js
Normal file
114
packages/cubby/public/js/project.js
Normal file
|
|
@ -0,0 +1,114 @@
|
|||
const fileInput = document.getElementById("file-input")
|
||||
const uploadButton = document.getElementById("upload-button")
|
||||
const progressContainer = document.getElementById("progress-container")
|
||||
const progressBar = document.getElementById("progress-bar")
|
||||
const progressText = document.getElementById("progress-text")
|
||||
const dragOverlay = document.getElementById("drag-overlay")
|
||||
const deleteButtons = document.querySelectorAll(".delete-button")
|
||||
let dragCounter = 0
|
||||
|
||||
fileInput.addEventListener("change", () => {
|
||||
uploadButton.style.display = fileInput.files.length > 0 ? "block" : "none"
|
||||
})
|
||||
|
||||
deleteButtons.forEach(button => {
|
||||
button.addEventListener("click", async () => {
|
||||
const file = button.dataset.file
|
||||
if (!confirm("Are you sure you want to delete " + file + "?")) return
|
||||
|
||||
try {
|
||||
const response = await fetch(window.location.pathname + "/delete/" + file, {
|
||||
method: "DELETE"
|
||||
})
|
||||
|
||||
if (response.ok) {
|
||||
window.location.reload()
|
||||
} else {
|
||||
alert("Delete failed")
|
||||
}
|
||||
} catch (err) {
|
||||
alert("Delete failed")
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
function uploadFile(file) {
|
||||
const xhr = new XMLHttpRequest()
|
||||
const formData = new FormData()
|
||||
formData.append("file", file)
|
||||
|
||||
progressContainer.style.display = "block"
|
||||
uploadButton.disabled = true
|
||||
fileInput.disabled = true
|
||||
|
||||
xhr.upload.addEventListener("progress", (e) => {
|
||||
if (e.lengthComputable) {
|
||||
const percent = Math.round((e.loaded / e.total) * 100)
|
||||
progressBar.style.width = percent + "%"
|
||||
progressText.textContent = percent + "%"
|
||||
}
|
||||
})
|
||||
|
||||
xhr.addEventListener("load", () => {
|
||||
if (xhr.status === 200) {
|
||||
window.location.reload()
|
||||
} else {
|
||||
alert("Upload failed")
|
||||
progressContainer.style.display = "none"
|
||||
uploadButton.disabled = false
|
||||
fileInput.disabled = false
|
||||
}
|
||||
})
|
||||
|
||||
xhr.addEventListener("error", () => {
|
||||
alert("Upload failed")
|
||||
progressContainer.style.display = "none"
|
||||
uploadButton.disabled = false
|
||||
fileInput.disabled = false
|
||||
})
|
||||
|
||||
xhr.open("POST", window.location.pathname + "/upload")
|
||||
xhr.send(formData)
|
||||
}
|
||||
|
||||
uploadButton.addEventListener("click", () => {
|
||||
const file = fileInput.files[0]
|
||||
if (!file) return
|
||||
uploadFile(file)
|
||||
})
|
||||
|
||||
document.addEventListener("dragenter", (e) => {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
dragCounter++
|
||||
dragOverlay.style.display = "flex"
|
||||
})
|
||||
|
||||
document.addEventListener("dragleave", (e) => {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
dragCounter--
|
||||
if (dragCounter === 0) {
|
||||
dragOverlay.style.display = "none"
|
||||
}
|
||||
})
|
||||
|
||||
document.addEventListener("dragover", (e) => {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
})
|
||||
|
||||
document.addEventListener("drop", async (e) => {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
dragCounter = 0
|
||||
dragOverlay.style.display = "none"
|
||||
|
||||
const files = [...e.dataTransfer.files]
|
||||
if (files.length === 0) return
|
||||
|
||||
for (const file of files) {
|
||||
uploadFile(file)
|
||||
break
|
||||
}
|
||||
})
|
||||
24
packages/cubby/src/components/Layout.tsx
Normal file
24
packages/cubby/src/components/Layout.tsx
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
interface LayoutProps {
|
||||
children: any
|
||||
title?: string
|
||||
}
|
||||
|
||||
export function Layout({ children, title }: LayoutProps) {
|
||||
return (
|
||||
<html lang="en">
|
||||
<head>
|
||||
<title>{title ? title : "Cubby"}</title>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<meta name="color-scheme" content="light dark" />
|
||||
<meta charset="utf-8" />
|
||||
<link rel="stylesheet" href="/css/pico.fuchsia.css" />
|
||||
<link rel="stylesheet" href="/css/main.css" />
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
{children}
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
)
|
||||
}
|
||||
52
packages/cubby/src/components/Project.tsx
Normal file
52
packages/cubby/src/components/Project.tsx
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
import { marked } from "marked"
|
||||
|
||||
interface ProjectProps {
|
||||
name: string
|
||||
readme: string
|
||||
files: string[]
|
||||
}
|
||||
|
||||
export function Project({ name, readme, files }: ProjectProps) {
|
||||
return (
|
||||
<>
|
||||
<p><a href="/">« Back</a></p>
|
||||
<div class="content-wrapper">
|
||||
<div class="main-content">
|
||||
<p dangerouslySetInnerHTML={{ __html: marked.parse(readme) }} />
|
||||
</div>
|
||||
<div class="side-content">
|
||||
{files.length > 0 && (
|
||||
<>
|
||||
<h2>Files</h2>
|
||||
<ul class="file-list">
|
||||
{files.sort().map(file => (
|
||||
<li key={file}>
|
||||
<a href={`/${name}/${file}`}>{file}</a>
|
||||
<button
|
||||
type="button"
|
||||
class="delete-button"
|
||||
data-file={file}
|
||||
>×</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</>
|
||||
)}
|
||||
<h2>Upload File</h2>
|
||||
<div id="upload-container" class="upload-container">
|
||||
<input type="file" id="file-input" class="file-input" />
|
||||
<button type="button" id="upload-button" class="upload-button" style="display: none">Upload</button>
|
||||
<div id="progress-container" class="progress-container">
|
||||
<div id="progress-bar" class="progress-bar"></div>
|
||||
<div id="progress-text">0%</div>
|
||||
</div>
|
||||
</div>
|
||||
<div id="drag-overlay" class="drag-overlay">
|
||||
<div class="drag-text">DROP FILE HERE</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<script src="/js/project.js"></script>
|
||||
</>
|
||||
)
|
||||
}
|
||||
119
packages/cubby/src/server.tsx
Normal file
119
packages/cubby/src/server.tsx
Normal file
|
|
@ -0,0 +1,119 @@
|
|||
import { Hono } from "hono"
|
||||
import { serveStatic } from "hono/bun"
|
||||
import { render } from "preact-render-to-string"
|
||||
import { marked } from "marked"
|
||||
import { readdirSync } from "fs"
|
||||
import { mkdir, readdir } from 'node:fs/promises'
|
||||
import { basename, join } from 'path'
|
||||
import { Layout } from "./components/Layout"
|
||||
import { Project } from "./components/Project"
|
||||
|
||||
const PROJECTS_DIR = ".."
|
||||
const WORKSHOP_REPO = "https://github.com/probablycorey/the-rabbit-hole"
|
||||
const CUBBY_DIR = "./cubby"
|
||||
|
||||
const app = new Hono()
|
||||
app.use('/css/*', serveStatic({ root: './public' }))
|
||||
app.use('/js/*', serveStatic({ root: './public' }))
|
||||
|
||||
async function projects(): Promise<string[]> {
|
||||
const subdirs = readdirSync(PROJECTS_DIR, { withFileTypes: true })
|
||||
.filter((entry: any) => entry.isDirectory())
|
||||
.map((entry: any) => entry.name).sort()
|
||||
|
||||
return subdirs
|
||||
}
|
||||
|
||||
function tsx(node: any) {
|
||||
return "<!DOCTYPE html>" + render(<Layout>{node}</Layout>)
|
||||
}
|
||||
|
||||
app.get("/", async (c) => {
|
||||
const names = await projects()
|
||||
return c.html(tsx(
|
||||
<div>
|
||||
<h1>Projects</h1>
|
||||
<ul>
|
||||
{names.map(name => <li key={name}><a href={`/${name}`}>{name}</a></li>)}
|
||||
</ul>
|
||||
</div>
|
||||
))
|
||||
})
|
||||
|
||||
app.get("/:name", async (c) => {
|
||||
const name = c.req.param("name").replace("..", "")
|
||||
const readme = await Bun.file(`${PROJECTS_DIR}/${name}/README.md`).text()
|
||||
const cubbyPath = join(CUBBY_DIR, `project_${name}`)
|
||||
let files: string[] = []
|
||||
|
||||
try {
|
||||
files = await readdir(cubbyPath)
|
||||
} catch (err: any) {
|
||||
if (err.code !== "ENOENT") {
|
||||
console.error("Error reading cubby:", err)
|
||||
}
|
||||
}
|
||||
|
||||
return c.html(tsx(<Project name={name} readme={readme} files={files} />))
|
||||
})
|
||||
|
||||
app.get('/:id/:filename', async c => {
|
||||
const { id, filename } = c.req.param()
|
||||
const path = join(CUBBY_DIR, `project_${id}`, filename)
|
||||
const file = Bun.file(path)
|
||||
if (!(await file.exists())) return c.json({ error: 'Not found' }, 404)
|
||||
|
||||
return new Response(file, {
|
||||
headers: {
|
||||
'Content-Type': file.type || 'application/octet-stream',
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
app.post('/:id/upload', async c => {
|
||||
const id = c.req.param('id')
|
||||
|
||||
if (id !== basename(id))
|
||||
return c.json({ error: 'Invalid project id' }, 400)
|
||||
|
||||
const folder = join(CUBBY_DIR, `project_${id}`)
|
||||
try {
|
||||
await mkdir(folder, { recursive: true })
|
||||
|
||||
const form = await c.req.formData()
|
||||
const file = form.get('file')
|
||||
if (!(file instanceof File))
|
||||
return c.json({ error: 'Invalid file' }, 400)
|
||||
|
||||
const filename = basename(file.name)
|
||||
const filepath = join(folder, filename)
|
||||
await Bun.write(filepath, await file.arrayBuffer())
|
||||
|
||||
return c.redirect(`/${id}`)
|
||||
} catch (err) {
|
||||
console.error('Upload error:', err)
|
||||
return c.json({ error: 'Upload failed' }, 500)
|
||||
}
|
||||
})
|
||||
|
||||
app.delete('/:id/delete/:filename', async c => {
|
||||
const { id, filename } = c.req.param()
|
||||
|
||||
if (id !== basename(id) || filename !== basename(filename))
|
||||
return c.json({ error: 'Invalid project id or filename' }, 400)
|
||||
|
||||
const filepath = join(CUBBY_DIR, `project_${id}`, filename)
|
||||
try {
|
||||
await Bun.file(filepath).delete()
|
||||
return c.json({ success: true })
|
||||
} catch (err) {
|
||||
console.error('Delete error:', err)
|
||||
return c.json({ error: 'Delete failed' }, 500)
|
||||
}
|
||||
})
|
||||
|
||||
export default {
|
||||
port: process.env.PORT || 3000,
|
||||
fetch: app.fetch,
|
||||
maxRequestBodySize: 1024 * 1024 * 1024, // 1GB
|
||||
}
|
||||
31
packages/cubby/tsconfig.json
Normal file
31
packages/cubby/tsconfig.json
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
{
|
||||
"compilerOptions": {
|
||||
// Environment setup & latest features
|
||||
"lib": ["ESNext"],
|
||||
"target": "ESNext",
|
||||
"module": "Preserve",
|
||||
"moduleDetection": "force",
|
||||
"jsx": "react-jsx",
|
||||
"allowJs": true,
|
||||
"jsxImportSource": "preact",
|
||||
"types": ["preact", "bun"],
|
||||
|
||||
// Bundler mode
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"noEmit": true,
|
||||
|
||||
// Best practices
|
||||
"strict": true,
|
||||
"skipLibCheck": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"noUncheckedIndexedAccess": true,
|
||||
"noImplicitOverride": true,
|
||||
|
||||
// Some stricter flags (disabled by default)
|
||||
"noUnusedLocals": false,
|
||||
"noUnusedParameters": false,
|
||||
"noPropertyAccessFromIndexSignature": false
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,117 @@
|
|||
---
|
||||
description: Use Bun instead of Node.js, npm, pnpm, or vite.
|
||||
globs: "*.ts, *.tsx, *.html, *.css, *.js, *.jsx, package.json"
|
||||
alwaysApply: false
|
||||
---
|
||||
|
||||
Default to using Bun instead of Node.js.
|
||||
|
||||
- Use `bun <file>` instead of `node <file>` or `ts-node <file>`
|
||||
- Use `bun test` instead of `jest` or `vitest`
|
||||
- Use `bun build <file.html|file.ts|file.css>` instead of `webpack` or `esbuild`
|
||||
- Use `bun install` instead of `npm install` or `yarn install` or `pnpm install`
|
||||
- Use `bun run <script>` instead of `npm run <script>` or `yarn run <script>` or `pnpm run <script>`
|
||||
- Bun automatically loads .env, so don't use dotenv.
|
||||
|
||||
## APIs
|
||||
|
||||
- `Bun.serve()` supports WebSockets, HTTPS, and routes. Don't use `express`.
|
||||
- `bun:sqlite` for SQLite. Don't use `better-sqlite3`.
|
||||
- `Bun.redis` for Redis. Don't use `ioredis`.
|
||||
- `Bun.sql` for Postgres. Don't use `pg` or `postgres.js`.
|
||||
- `WebSocket` is built-in. Don't use `ws`.
|
||||
- Prefer `Bun.file` over `node:fs`'s readFile/writeFile
|
||||
- Bun.$`ls` instead of execa.
|
||||
|
||||
## Testing
|
||||
|
||||
Use `bun test` to run tests.
|
||||
|
||||
Tests should use the toplevel `test()` and the `assert` library.
|
||||
|
||||
Test files should always live in `test/` off the project root and be named `THING.test.ts`
|
||||
|
||||
```ts#index.test.ts
|
||||
import { test } from "bun:test"
|
||||
import assert from 'assert'
|
||||
|
||||
test("1 + 2 = 3", () => {
|
||||
assert.equal(1 + 2, 3)
|
||||
assert.ok(true)
|
||||
})
|
||||
```
|
||||
|
||||
## Frontend
|
||||
|
||||
Use HTML imports with `Bun.serve()`. Don't use `vite`. HTML imports fully support React, CSS, Tailwind.
|
||||
|
||||
Server:
|
||||
|
||||
```ts#index.ts
|
||||
import index from "./index.html"
|
||||
|
||||
Bun.serve({
|
||||
routes: {
|
||||
"/": index,
|
||||
"/api/users/:id": {
|
||||
GET: (req) => {
|
||||
return new Response(JSON.stringify({ id: req.params.id }));
|
||||
},
|
||||
},
|
||||
},
|
||||
// optional websocket support
|
||||
websocket: {
|
||||
open: (ws) => {
|
||||
ws.send("Hello, world!");
|
||||
},
|
||||
message: (ws, message) => {
|
||||
ws.send(message);
|
||||
},
|
||||
close: (ws) => {
|
||||
// handle close
|
||||
}
|
||||
},
|
||||
development: {
|
||||
hmr: true,
|
||||
console: true,
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
HTML files can import .tsx, .jsx or .js files directly and Bun's bundler will transpile & bundle automatically. `<link>` tags can point to stylesheets and Bun's CSS bundler will bundle.
|
||||
|
||||
```html#index.html
|
||||
<html>
|
||||
<body>
|
||||
<h1>Hello, world!</h1>
|
||||
<script type="module" src="./frontend.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
With the following `frontend.tsx`:
|
||||
|
||||
```tsx#frontend.tsx
|
||||
import React from "react";
|
||||
|
||||
// import .css files directly and it works
|
||||
import './index.css';
|
||||
|
||||
import { createRoot } from "react-dom/client";
|
||||
|
||||
const root = createRoot(document.body);
|
||||
|
||||
export default function Frontend() {
|
||||
return <h1>Hello, world!</h1>;
|
||||
}
|
||||
|
||||
root.render(<Frontend />);
|
||||
```
|
||||
|
||||
Then, run index.ts
|
||||
|
||||
```sh
|
||||
bun --hot ./index.ts
|
||||
```
|
||||
|
||||
For more information, read the Bun API docs in `node_modules/bun-types/docs/**.md`.
|
||||
23
packages/glyph/.cursor/rules/workshop.mdc
Normal file
23
packages/glyph/.cursor/rules/workshop.mdc
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
---
|
||||
description: The Workshop's JS/TS style.
|
||||
alwaysApply: false
|
||||
globs: "*.ts, *.tsx, *.html, *.css, *.js, *.jsx"
|
||||
---
|
||||
|
||||
- No semicolons — ever.
|
||||
- No comments — ever.
|
||||
- 2‑space indentation.
|
||||
- Double quotes for strings.
|
||||
- Trailing commas where ES5 allows (objects, arrays, imports).
|
||||
- Keep lines <= 100 characters.
|
||||
- End every file with a single newline.
|
||||
|
||||
- This project runs on Bun.
|
||||
- Assume `strict` mode is on (no implicit `any`).
|
||||
- Prefer `const`; use `let` only when reassignment is required.
|
||||
- Avoid the `any` type unless unavoidable.
|
||||
- Use `import type { … }` when importing only types.
|
||||
- In TypeScript files put npm imports first, then std imports, then library imports.
|
||||
|
||||
- Respond in a concise, direct tone.
|
||||
- Do not ask follow‑up questions unless clarification is essential.
|
||||
34
packages/glyph/.gitignore
vendored
Normal file
34
packages/glyph/.gitignore
vendored
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
# dependencies (bun install)
|
||||
node_modules
|
||||
|
||||
# output
|
||||
out
|
||||
dist
|
||||
*.tgz
|
||||
|
||||
# code coverage
|
||||
coverage
|
||||
*.lcov
|
||||
|
||||
# logs
|
||||
logs
|
||||
_.log
|
||||
report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json
|
||||
|
||||
# dotenv environment variable files
|
||||
.env
|
||||
.env.development.local
|
||||
.env.test.local
|
||||
.env.production.local
|
||||
.env.local
|
||||
|
||||
# caches
|
||||
.eslintcache
|
||||
.cache
|
||||
*.tsbuildinfo
|
||||
|
||||
# IntelliJ based IDEs
|
||||
.idea
|
||||
|
||||
# Finder (MacOS) folder config
|
||||
.DS_Store
|
||||
15
packages/glyph/README.md
Normal file
15
packages/glyph/README.md
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
# @workshop/glyph
|
||||
|
||||
To install dependencies:
|
||||
|
||||
```bash
|
||||
bun install
|
||||
```
|
||||
|
||||
To run:
|
||||
|
||||
```bash
|
||||
bun run index.ts
|
||||
```
|
||||
|
||||
This project was created using `bun init` in bun v1.2.18. [Bun](https://bun.sh) is a fast all-in-one JavaScript runtime.
|
||||
26
packages/glyph/example.tsx
Normal file
26
packages/glyph/example.tsx
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
<tags>
|
||||
card: VStack max-w-2xl mx-auto p-6 bg-white rounded-lg shadow-md
|
||||
name: h3 text-2xl font-bold mb-4 text-gray-800
|
||||
description: p text-gray-600 mb-6 leading-relaxed
|
||||
socials: div inline-flex items-center text-blue-600 hover:text-blue-800 transition-colors duration-200
|
||||
</tags>
|
||||
|
||||
<card>
|
||||
<name>Bobby Tables</name>
|
||||
<description>
|
||||
Bobby is a software engineer and the creator of the popular web development framework, Treeact. He is a true master of all things front-end, and his work has been praised by developers and non-developers alike.
|
||||
</description>
|
||||
<socials>
|
||||
<Link to="https://www.github.com/bobbytables2000" text="GitHub" />
|
||||
</socials>
|
||||
</card>
|
||||
|
||||
<card id="roger">
|
||||
<name class="this-still-works">Roger Tables</name>
|
||||
<description>
|
||||
Roger is a software engineer and the creator of no popular web development frameworks. He is a true lover of all things front-end, but his work has not been praised by developers and non-developers alike.
|
||||
</description>
|
||||
<socials>
|
||||
<Link to="https://www.github.com/rogertables3000" text="GitHub" />
|
||||
</socials>
|
||||
</card>
|
||||
162
packages/glyph/index.ts
Normal file
162
packages/glyph/index.ts
Normal file
|
|
@ -0,0 +1,162 @@
|
|||
import { parseFragment as parse, serialize } from "parse5"
|
||||
|
||||
type TagDefinitions = Record<string, [string, string[]]>
|
||||
|
||||
type Node = {
|
||||
nodeName: string
|
||||
tagName: string
|
||||
parentNode: Node | null
|
||||
childNodes: Node[]
|
||||
value: string
|
||||
attrs: { name: string, value: string }[]
|
||||
}
|
||||
|
||||
// search for <tags> node
|
||||
function findTagsNode(node: Node): Node | null {
|
||||
if (node.nodeName === "tags" && node.childNodes) {
|
||||
return node
|
||||
}
|
||||
|
||||
if (node.childNodes) {
|
||||
for (const child of node.childNodes) {
|
||||
const result = findTagsNode(child)
|
||||
if (result) return result
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
// pull out <tags>'s inner text
|
||||
function tagsNodeText(node: Node): string | null {
|
||||
if (node && node.childNodes) {
|
||||
const textNode = node.childNodes.find((n: Node) => n.nodeName === "#text")
|
||||
if (textNode)
|
||||
return textNode.value
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
// turn what's inside <tags> into a map of tag definitions
|
||||
// ignores //comment lines
|
||||
// format is `tag: parent class1 class2`
|
||||
function parseTagDefinitions(text: string): TagDefinitions {
|
||||
const tags: TagDefinitions = {}
|
||||
text.split("\n")
|
||||
.forEach(line => {
|
||||
line = line.trim()
|
||||
if (line === "") return
|
||||
if (line.startsWith("//")) return
|
||||
|
||||
const [name, definition] = line.split(/:(.+)/)
|
||||
if (!name || !definition) {
|
||||
console.error(`Invalid tag definition: ${line}`)
|
||||
return
|
||||
}
|
||||
|
||||
const [parent, ...classes] = definition.trim().split(" ")
|
||||
if (!parent) {
|
||||
console.error(`Invalid tag definition: ${line}`)
|
||||
return
|
||||
}
|
||||
|
||||
tags[name.trim()] = [parent.trim(), classes]
|
||||
})
|
||||
|
||||
return tags
|
||||
}
|
||||
|
||||
// using our tag definitions, replace the tags in the AST with the real tags w/ classes
|
||||
function replaceTags(ast: Node, tagDefinitions: TagDefinitions): string {
|
||||
const tags = Object.keys(tagDefinitions)
|
||||
|
||||
for (const tag of tags) {
|
||||
const [parent, classes] = tagDefinitions[tag] as [string, string[]]
|
||||
const parentNodes = findTagsByName(ast, tag)
|
||||
for (const parentNode of parentNodes) {
|
||||
if (parentNode) {
|
||||
parentNode.tagName = parent
|
||||
parentNode.nodeName = parent
|
||||
if (parentNode.attrs.length === 0) {
|
||||
parentNode.attrs = [{ name: "class", value: classes.join(" ") }]
|
||||
} else {
|
||||
const classAttr = parentNode.attrs.find((a: any) => a.name === "class")
|
||||
if (classAttr) {
|
||||
classAttr.value += " " + classes.join(" ")
|
||||
} else {
|
||||
parentNode.attrs.push({ name: "class", value: classes.join(" ") })
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// delete <tags> node
|
||||
const tagsIndex = ast.childNodes.findIndex((n: Node) => n.nodeName === "tags")
|
||||
if (tagsIndex !== -1) {
|
||||
ast.childNodes.splice(tagsIndex, 1)
|
||||
}
|
||||
|
||||
return serialize(ast as any)
|
||||
}
|
||||
|
||||
// find tag by name in the AST
|
||||
function findTagByName(ast: Node, tag: string): Node | null {
|
||||
if (ast.nodeName === tag) {
|
||||
return ast
|
||||
}
|
||||
|
||||
if (ast.childNodes) {
|
||||
for (const child of ast.childNodes) {
|
||||
const result = findTagByName(child, tag)
|
||||
if (result) return result
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
// find tags by name in the AST
|
||||
function findTagsByName(ast: Node, tag: string): Node[] {
|
||||
const tags: Node[] = []
|
||||
if (ast.nodeName === tag) {
|
||||
tags.push(ast)
|
||||
}
|
||||
if (ast.childNodes) {
|
||||
for (const child of ast.childNodes) {
|
||||
tags.push(...findTagsByName(child, tag))
|
||||
}
|
||||
}
|
||||
return tags
|
||||
}
|
||||
|
||||
// transform string HTML w/ <tags> into new HTML w/ <tags> + friends replaced by new HTML
|
||||
function transform(content: string): string {
|
||||
const ast = parse(content) as Node
|
||||
|
||||
const tagsNode = findTagsNode(ast)
|
||||
if (!tagsNode) {
|
||||
console.error("No <tags> element found")
|
||||
return content
|
||||
}
|
||||
|
||||
const tagsText = tagsNodeText(tagsNode)
|
||||
if (!tagsText) {
|
||||
console.error("No <tags> text found")
|
||||
return content
|
||||
}
|
||||
|
||||
const tagDefinitions = parseTagDefinitions(tagsText)
|
||||
|
||||
return replaceTags(ast, tagDefinitions)
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const content = await Bun.file("example.tsx").text()
|
||||
const transformed = transform(content)
|
||||
console.log(transformed.trim())
|
||||
}
|
||||
|
||||
if (import.meta.main) {
|
||||
main()
|
||||
}
|
||||
14
packages/glyph/package.json
Normal file
14
packages/glyph/package.json
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
{
|
||||
"name": "@workshop/glyph",
|
||||
"module": "index.ts",
|
||||
"type": "module",
|
||||
"devDependencies": {
|
||||
"@types/bun": "latest"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"typescript": "^5"
|
||||
},
|
||||
"dependencies": {
|
||||
"parse5": "^8.0.0"
|
||||
}
|
||||
}
|
||||
29
packages/glyph/tsconfig.json
Normal file
29
packages/glyph/tsconfig.json
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
{
|
||||
"compilerOptions": {
|
||||
// Environment setup & latest features
|
||||
"lib": ["ESNext"],
|
||||
"target": "ESNext",
|
||||
"module": "Preserve",
|
||||
"moduleDetection": "force",
|
||||
"jsx": "react-jsx",
|
||||
"allowJs": true,
|
||||
|
||||
// Bundler mode
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"noEmit": true,
|
||||
|
||||
// Best practices
|
||||
"strict": true,
|
||||
"skipLibCheck": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"noUncheckedIndexedAccess": true,
|
||||
"noImplicitOverride": true,
|
||||
|
||||
// Some stricter flags (disabled by default)
|
||||
"noUnusedLocals": false,
|
||||
"noUnusedParameters": false,
|
||||
"noPropertyAccessFromIndexSignature": false
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user