cubby
This commit is contained in:
parent
7a08efb568
commit
9b790366ab
|
|
@ -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.
|
||||
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"
|
||||
}
|
||||
}
|
||||
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
405
packages/cubby/src/server.tsx
Normal file
405
packages/cubby/src/server.tsx
Normal file
|
|
@ -0,0 +1,405 @@
|
|||
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'
|
||||
|
||||
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' }))
|
||||
|
||||
// all the workshop projects!
|
||||
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
|
||||
}
|
||||
|
||||
// magic
|
||||
function tsx(node: any) {
|
||||
return "<!DOCTYPE html>" + render(<Layout>{node}</Layout>)
|
||||
}
|
||||
|
||||
// more magic
|
||||
function js(code: TemplateStringsArray, ...args: any[]): string {
|
||||
return code.join("") + args.map(arg => arg.toString()).join("")
|
||||
}
|
||||
|
||||
// can you believe it?
|
||||
function css(code: TemplateStringsArray, ...args: any[]): string {
|
||||
return code.join("") + args.map(arg => arg.toString()).join("")
|
||||
}
|
||||
|
||||
// layout
|
||||
function Layout({ children, title }: { children: any, title?: string }) {
|
||||
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" />
|
||||
<style dangerouslySetInnerHTML={{
|
||||
__html: css`
|
||||
.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;
|
||||
}
|
||||
`}} />
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
{children}
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
)
|
||||
}
|
||||
|
||||
// list all workshop projects
|
||||
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>
|
||||
))
|
||||
})
|
||||
|
||||
// show a project's README and uploaded cubby files
|
||||
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((
|
||||
<>
|
||||
{/* <p><a href={`${WORKSHOP_REPO}/tree/main/packages/${name}`}>View on GitHub</a></p> */}
|
||||
<p><a href="/">« Back</a></p>
|
||||
<div class="content-wrapper">
|
||||
<div class="main-content">
|
||||
<p dangerouslySetInnerHTML={{ __html: await marked(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 dangerouslySetInnerHTML={{
|
||||
__html: js`
|
||||
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
|
||||
}
|
||||
})
|
||||
`
|
||||
}} />
|
||||
</>
|
||||
)))
|
||||
})
|
||||
|
||||
// download a file from a project's cubby
|
||||
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',
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
// upload a file to a project's cubby
|
||||
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)
|
||||
|
||||
// strip any directory parts from the uploaded filename
|
||||
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)
|
||||
}
|
||||
})
|
||||
|
||||
// delete a file from a project's cubby
|
||||
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: 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
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user