sordo 0.4.0 → 1.0.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.
Files changed (152) hide show
  1. package/CHANGELOG.md +6 -116
  2. package/README.md +8 -175
  3. package/bin/sordo.ts +1 -4
  4. package/package.json +17 -41
  5. package/src/agents-md.ts +1 -0
  6. package/src/ai.ts +1 -0
  7. package/src/build.ts +1 -0
  8. package/src/client.ts +1 -0
  9. package/src/config.ts +1 -0
  10. package/src/dev.ts +1 -0
  11. package/src/index.ts +1 -55
  12. package/src/middleware.ts +1 -0
  13. package/src/plugin.ts +1 -0
  14. package/src/render.ts +1 -0
  15. package/src/router.ts +1 -0
  16. package/src/server.ts +1 -0
  17. package/CLAUDE.md +0 -124
  18. package/src/adapters/bun.ts +0 -59
  19. package/src/adapters/edge.ts +0 -75
  20. package/src/adapters/types.ts +0 -43
  21. package/src/agents-md/collect.ts +0 -113
  22. package/src/agents-md/generate.ts +0 -44
  23. package/src/agents-md/index.ts +0 -9
  24. package/src/agents-md/render.ts +0 -150
  25. package/src/agents-md/subprocess-entry.ts +0 -92
  26. package/src/agents-md/subprocess-runner.ts +0 -111
  27. package/src/agents-md/write.ts +0 -38
  28. package/src/agents-md/zod-to-json-schema.ts +0 -18
  29. package/src/ai/context.ts +0 -72
  30. package/src/ai/define.ts +0 -15
  31. package/src/ai/errors.ts +0 -51
  32. package/src/ai/index.ts +0 -36
  33. package/src/ai/middleware.ts +0 -21
  34. package/src/ai/registry.ts +0 -96
  35. package/src/ai/run.ts +0 -185
  36. package/src/ai/scan.ts +0 -42
  37. package/src/ai/stream.ts +0 -71
  38. package/src/ai/triggers.ts +0 -124
  39. package/src/ai/types.ts +0 -67
  40. package/src/ai/validate.ts +0 -82
  41. package/src/build/assets.ts +0 -48
  42. package/src/build/client-entry.ts +0 -43
  43. package/src/build/css.ts +0 -102
  44. package/src/build/embedded.ts +0 -66
  45. package/src/build/hash.ts +0 -21
  46. package/src/build/index.ts +0 -480
  47. package/src/build/macros/agents-hash.macro.ts +0 -9
  48. package/src/build/macros/agents.macro.ts +0 -21
  49. package/src/build/macros/env.macro.ts +0 -25
  50. package/src/build/macros/inline-assets.macro.ts +0 -28
  51. package/src/build/macros/manifest.macro.ts +0 -8
  52. package/src/build/macros/routes.macro.ts +0 -10
  53. package/src/build/page-entry.ts +0 -136
  54. package/src/build/scan-islands.ts +0 -39
  55. package/src/build/server-entry.ts +0 -256
  56. package/src/cli/ansi.ts +0 -41
  57. package/src/cli/build.ts +0 -195
  58. package/src/cli/commands/add/apply.ts +0 -31
  59. package/src/cli/commands/add/component-diff.ts +0 -116
  60. package/src/cli/commands/add/diff.ts +0 -153
  61. package/src/cli/commands/add/internal.ts +0 -41
  62. package/src/cli/commands/add/load-catalog.ts +0 -22
  63. package/src/cli/commands/add/peer-deps.ts +0 -115
  64. package/src/cli/commands/add/registry-fetch.ts +0 -122
  65. package/src/cli/commands/add/shadcn.ts +0 -285
  66. package/src/cli/commands/add/source.ts +0 -273
  67. package/src/cli/commands/add/stamper.ts +0 -73
  68. package/src/cli/commands/add/tokens.ts +0 -81
  69. package/src/cli/commands/add/ui-paths.ts +0 -113
  70. package/src/cli/commands/add.ts +0 -427
  71. package/src/cli/commands/deploy.ts +0 -143
  72. package/src/cli/commands/migrate.ts +0 -149
  73. package/src/cli/commands/secret.ts +0 -316
  74. package/src/cli/commands/ui/build.ts +0 -111
  75. package/src/cli/commands/ui/init.ts +0 -135
  76. package/src/cli/commands/ui/migrate/git-guard.ts +0 -19
  77. package/src/cli/commands/ui/migrate/radix.ts +0 -67
  78. package/src/cli/commands/ui/migrate/rtl.ts +0 -148
  79. package/src/cli/commands/ui/shadcn.ts +0 -82
  80. package/src/cli/commands/ui/view.ts +0 -63
  81. package/src/cli/commands/ui.ts +0 -86
  82. package/src/cli/commands/update.ts +0 -134
  83. package/src/cli/commands/upgrade.ts +0 -53
  84. package/src/cli/commands/view.ts +0 -34
  85. package/src/cli/dev.ts +0 -393
  86. package/src/cli/doctor/config-checks.ts +0 -63
  87. package/src/cli/doctor/deps.ts +0 -295
  88. package/src/cli/doctor/hydrate.ts +0 -65
  89. package/src/cli/doctor/monorepo.ts +0 -158
  90. package/src/cli/doctor/probes.ts +0 -16
  91. package/src/cli/doctor/report.ts +0 -72
  92. package/src/cli/doctor/toolchain.ts +0 -95
  93. package/src/cli/doctor/types.ts +0 -36
  94. package/src/cli/doctor.ts +0 -127
  95. package/src/cli/index.ts +0 -168
  96. package/src/cli/log.ts +0 -135
  97. package/src/cli/run/affected.ts +0 -79
  98. package/src/cli/run/cache-key.ts +0 -177
  99. package/src/cli/run/cache-store.ts +0 -0
  100. package/src/cli/run/files.ts +0 -96
  101. package/src/cli/run/git.ts +0 -13
  102. package/src/cli/run/runner.ts +0 -189
  103. package/src/cli/run/workspace.ts +0 -216
  104. package/src/cli/run.ts +0 -184
  105. package/src/cli/start.ts +0 -99
  106. package/src/cli/update-check.ts +0 -157
  107. package/src/client/index.ts +0 -65
  108. package/src/client/link.tsx +0 -61
  109. package/src/client/page.ts +0 -250
  110. package/src/config/define.ts +0 -5
  111. package/src/config/env.ts +0 -36
  112. package/src/config/load.ts +0 -152
  113. package/src/config/schema.ts +0 -135
  114. package/src/config/secrets.ts +0 -108
  115. package/src/dev/client.ts +0 -112
  116. package/src/dev/hot.ts +0 -24
  117. package/src/dev/index.ts +0 -4
  118. package/src/dev/tree.ts +0 -95
  119. package/src/dev/watcher.ts +0 -95
  120. package/src/internal/hmr-client.ts +0 -52
  121. package/src/internal/open-in-editor.ts +0 -23
  122. package/src/internal/runtime.ts +0 -30
  123. package/src/middleware/cookie-jar.ts +0 -135
  124. package/src/middleware/cookies.ts +0 -60
  125. package/src/middleware/index.ts +0 -127
  126. package/src/middleware/request-id.ts +0 -22
  127. package/src/middleware/response-helpers.ts +0 -25
  128. package/src/plugin/index.ts +0 -109
  129. package/src/render/bootstrap.ts +0 -44
  130. package/src/render/dev-error.tsx +0 -73
  131. package/src/render/index.tsx +0 -261
  132. package/src/render/island.tsx +0 -33
  133. package/src/render/meta.tsx +0 -48
  134. package/src/render/shell.tsx +0 -41
  135. package/src/router/conflict.ts +0 -20
  136. package/src/router/filesystem.ts +0 -37
  137. package/src/router/index.ts +0 -247
  138. package/src/router/match.ts +0 -91
  139. package/src/router/pattern.ts +0 -88
  140. package/src/server/index.ts +0 -250
  141. package/src/server/inline-assets.ts +0 -39
  142. package/src/types.ts +0 -53
  143. package/src/ui/schema.ts +0 -68
  144. package/src/ui/types.ts +0 -10
  145. package/templates/_internal/cn.ts +0 -6
  146. package/templates/_internal/slot.ts +0 -50
  147. package/templates/_internal/variants.ts +0 -1
  148. package/templates/themes/neutral/tokens.css +0 -46
  149. package/templates/themes/slate/tokens.css +0 -46
  150. package/templates/themes/stone/tokens.css +0 -46
  151. package/templates/themes/zinc/tokens.css +0 -46
  152. package/templates/tokens.css +0 -46
package/src/dev/client.ts DELETED
@@ -1,112 +0,0 @@
1
- import type { CssOption } from "../build/css.ts";
2
- import { build, type ClientManifest } from "../build/index.ts";
3
- import type { HydrateDefault } from "../build/page-entry.ts";
4
- import { loadConfig } from "../config/load.ts";
5
- import type { BunRoutes } from "../types.ts";
6
-
7
- export interface SetupDevClientOptions {
8
- appDir: string;
9
- /** Where to emit the dev client bundle. Defaults to `<appDir>/.sordo`. */
10
- outDir?: string;
11
- /** Whole-tree hydration default. Defaults to `render.hydrate` from config. */
12
- hydrate?: HydrateDefault;
13
- /** Stylesheet entry. Defaults to `css` from config; `null` disables it. */
14
- css?: CssOption | null;
15
- }
16
-
17
- export interface DevClient {
18
- manifest: ClientManifest;
19
- routes: BunRoutes;
20
- /** Re-runs the island bundle and mutates `manifest` in place. */
21
- rebuild(): Promise<void>;
22
- }
23
-
24
- const PUBLIC_PREFIX = "/_sordo/client/";
25
-
26
- // Bundles islands in development (no minify) and serves the chunks under
27
- // `/_sordo/client/*`. The returned `manifest` is what `createRenderer`
28
- // needs to emit a `<script>` tag that hydrates the islands in the browser —
29
- // without it, dev pages SSR fine but never wake up client-side.
30
- export async function setupDevClient(
31
- options: SetupDevClientOptions,
32
- ): Promise<DevClient> {
33
- const appDir = options.appDir.replace(/\/+$/, "");
34
- const outDir = (options.outDir ?? `${appDir}/.sordo`).replace(/\/+$/, "");
35
- const clientOutDir = `${outDir}/client`;
36
-
37
- const manifest: ClientManifest = { entry: null, islands: {}, pages: {} };
38
- const configured =
39
- options.hydrate === undefined || options.css === undefined
40
- ? await configuredDefaults()
41
- : undefined;
42
- const hydrate = options.hydrate ?? configured?.hydrate ?? "off";
43
- const css =
44
- options.css === undefined ? configured?.css : (options.css ?? undefined);
45
-
46
- const rebuild = async (): Promise<void> => {
47
- const result = await build({
48
- appDir,
49
- outDir,
50
- mode: "development",
51
- hydrate,
52
- css,
53
- });
54
- manifest.entry = result.clientManifest.entry;
55
- if (result.clientManifest.css) manifest.css = result.clientManifest.css;
56
- else delete manifest.css;
57
- // Replace keys so removed islands/pages disappear from the manifest.
58
- replaceRecord(manifest.islands, result.clientManifest.islands);
59
- replaceRecord(manifest.pages, result.clientManifest.pages);
60
- };
61
-
62
- await rebuild();
63
-
64
- const serveFile = async (req: Request): Promise<Response> => {
65
- const url = new URL(req.url);
66
- const rel = url.pathname.slice(PUBLIC_PREFIX.length).replace(/^\/+/, "");
67
- if (!rel || rel.includes("..")) {
68
- return new Response("not found", { status: 404 });
69
- }
70
- const file = Bun.file(`${clientOutDir}/${rel}`);
71
- if (!(await file.exists())) {
72
- return new Response("not found", { status: 404 });
73
- }
74
- const ctype =
75
- rel.endsWith(".js") || rel.endsWith(".mjs")
76
- ? "application/javascript; charset=utf-8"
77
- : rel.endsWith(".css")
78
- ? "text/css; charset=utf-8"
79
- : rel.endsWith(".map")
80
- ? "application/json; charset=utf-8"
81
- : "application/octet-stream";
82
- return new Response(file, { headers: { "Content-Type": ctype } });
83
- };
84
-
85
- const routes: BunRoutes = {
86
- [`${PUBLIC_PREFIX}*`]: serveFile as unknown as BunRoutes[string],
87
- };
88
-
89
- return { manifest, routes, rebuild };
90
- }
91
-
92
- function replaceRecord(
93
- target: Record<string, string>,
94
- next: Record<string, string>,
95
- ): void {
96
- for (const k of Object.keys(target)) delete target[k];
97
- Object.assign(target, next);
98
- }
99
-
100
- // `sordo dev` runs from the project root, so the config there is the app's.
101
- // A missing or invalid config falls back to defaults — the dev client must boot.
102
- async function configuredDefaults(): Promise<{
103
- hydrate: HydrateDefault;
104
- css?: CssOption;
105
- }> {
106
- try {
107
- const { config } = await loadConfig(process.cwd());
108
- return { hydrate: config.render.hydrate, css: config.css };
109
- } catch {
110
- return { hydrate: "off" };
111
- }
112
- }
package/src/dev/hot.ts DELETED
@@ -1,24 +0,0 @@
1
- // `bun --hot` re-evaluates every module on change but keeps `globalThis`, so
2
- // anything that must survive a reload — or count reloads — lives there.
3
-
4
- export interface HotState {
5
- /** Evaluations of the dev bootstrap in this process; >1 means a hot reload. */
6
- generation: number;
7
- /** Per-process id; lets the HMR client tell a restart from a hot reload. */
8
- serverId: string;
9
- }
10
-
11
- const KEY = Symbol.for("sordo.dev.hot");
12
-
13
- export function hotState(): HotState {
14
- const g = globalThis as unknown as Record<symbol, HotState | undefined>;
15
- let state = g[KEY];
16
- if (!state) {
17
- state = {
18
- generation: 0,
19
- serverId: `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`,
20
- };
21
- g[KEY] = state;
22
- }
23
- return state;
24
- }
package/src/dev/index.ts DELETED
@@ -1,4 +0,0 @@
1
- export type { DevClient, SetupDevClientOptions } from "./client.ts";
2
- export { setupDevClient } from "./client.ts";
3
- export type { DevOptions, DevServer, WebSocketHandler } from "./watcher.ts";
4
- export { createDevServer } from "./watcher.ts";
package/src/dev/tree.ts DELETED
@@ -1,95 +0,0 @@
1
- import { type FSWatcher, watch } from "node:fs";
2
-
3
- // `bun --hot` / `--watch` only see files already in the module graph, so a
4
- // newly added route (or a deleted one) never triggers a reload and the route
5
- // table built at startup goes stale. `sordo dev` watches the app tree for
6
- // files appearing or disappearing and restarts the dev process — the one
7
- // place runtime re-scanning is allowed (.claude/rules/build-time-discovery.md).
8
- //
9
- // Content edits are deliberately ignored: they belong to `bun --hot`. The
10
- // comparison is on the set of files, so editors that save atomically
11
- // (write a temp file, rename it over the original) don't cause restarts.
12
-
13
- const SOURCE_GLOB = "**/*.{ts,tsx,js,jsx,mts,mjs,cts,cjs}";
14
- const DEBOUNCE_MS = 75;
15
- // FSEvents can drop an event when it coalesces with a burst of writes (the
16
- // dev build rewriting .sordo/ right as a route is added), leaving the new
17
- // route unserved until some unrelated later event. A cheap periodic rescan
18
- // bounds that to one interval; events stay the fast path.
19
- const POLL_MS = 1000;
20
- // Written by every dev build (src/build/index.ts); tracking it would restart
21
- // the server right after its own first build.
22
- const GENERATED_DIR = "sordo-gen";
23
-
24
- function ignored(rel: string): boolean {
25
- return (
26
- rel.startsWith(".") ||
27
- rel === GENERATED_DIR ||
28
- rel.startsWith(`${GENERATED_DIR}/`) ||
29
- rel.startsWith("node_modules/") ||
30
- rel.includes("/node_modules/")
31
- );
32
- }
33
-
34
- export interface AppTreeWatcher {
35
- close(): void;
36
- }
37
-
38
- export function snapshotAppTree(appDir: string): Set<string> {
39
- const files = new Set<string>();
40
- const glob = new Bun.Glob(SOURCE_GLOB);
41
- try {
42
- // `dot: false` (the default) keeps the `.sordo` build output out.
43
- for (const rel of glob.scanSync({ cwd: appDir, onlyFiles: true })) {
44
- if (!ignored(rel)) files.add(rel);
45
- }
46
- } catch {
47
- // Missing app dir: an empty tree; a later `mkdir app` shows up as a change.
48
- }
49
- return files;
50
- }
51
-
52
- function sameSet(a: Set<string>, b: Set<string>): boolean {
53
- if (a.size !== b.size) return false;
54
- for (const v of a) if (!b.has(v)) return false;
55
- return true;
56
- }
57
-
58
- export function watchAppTree(
59
- appDir: string,
60
- onStructureChange: () => void,
61
- { pollMs = POLL_MS }: { pollMs?: number } = {},
62
- ): AppTreeWatcher {
63
- let known = snapshotAppTree(appDir);
64
- let timer: ReturnType<typeof setTimeout> | null = null;
65
-
66
- const check = (): void => {
67
- timer = null;
68
- const next = snapshotAppTree(appDir);
69
- if (sameSet(known, next)) return;
70
- known = next;
71
- onStructureChange();
72
- };
73
-
74
- let watcher: FSWatcher | null = null;
75
- try {
76
- watcher = watch(appDir, { recursive: true }, (_event, filename) => {
77
- if (filename && ignored(String(filename))) return;
78
- if (timer) clearTimeout(timer);
79
- timer = setTimeout(check, DEBOUNCE_MS);
80
- });
81
- } catch {
82
- // No app dir to watch yet; the poll below still notices one appearing.
83
- }
84
- const poll = setInterval(() => {
85
- if (!timer) check();
86
- }, pollMs);
87
-
88
- return {
89
- close() {
90
- if (timer) clearTimeout(timer);
91
- clearInterval(poll);
92
- watcher?.close();
93
- },
94
- };
95
- }
@@ -1,95 +0,0 @@
1
- // Dev / HMR server module (spec 05).
2
- //
3
- // The dev runtime is `bun --hot` (or `bun --watch` via `sordo dev --cold`).
4
- // This module owns the WebSocket endpoint at `/__sordo_hmr` and the
5
- // publish channel that tells connected browsers to reload or re-hydrate.
6
- //
7
- // We rely on Bun's native primitives:
8
- // - WebSocket pub/sub topics manage the subscriber set; we never hold a
9
- // `Set<ServerWebSocket>` ourselves and dead sockets are pruned on close.
10
- // - `bun --hot` keeps `Bun.serve` (and these WebSockets) alive across
11
- // module reloads, so reconnect logic on the client is only exercised
12
- // under `--cold` or when `sordo dev` restarts for an added/removed file.
13
-
14
- import { hotState } from "./hot.ts";
15
-
16
- type AnyServer = {
17
- publish: (topic: string, data: string) => number;
18
- };
19
-
20
- type AnyWS = {
21
- subscribe: (topic: string) => void;
22
- send: (data: string) => void;
23
- };
24
-
25
- export interface WebSocketHandler {
26
- open?: (ws: AnyWS) => void;
27
- message?: (ws: AnyWS, data: string | ArrayBufferLike) => void;
28
- close?: (ws: AnyWS, code: number, reason: string) => void;
29
- }
30
-
31
- export interface DevServer {
32
- /** Fallback HTTP response when a non-WS request hits the HMR endpoint. */
33
- fetch: (req: Request) => Response | Promise<Response>;
34
- /** Bun.serve `websocket` handler. */
35
- websocket: WebSocketHandler;
36
- /** Publish an update for the given filesystem path. */
37
- notifyChange(path: string): void;
38
- /** Called by `startServer` once `Bun.serve` returns the live server. */
39
- attachServer(server: AnyServer): void;
40
- }
41
-
42
- export interface DevOptions {
43
- /** Absolute path to the user's `app/` directory; used to classify changes. */
44
- appDir: string;
45
- }
46
-
47
- const HMR_TOPIC = "hmr";
48
- const RELOAD_MSG = JSON.stringify({ type: "reload" });
49
-
50
- export function createDevServer(options: DevOptions): DevServer {
51
- let server: AnyServer | null = null;
52
- // Per-process id so reconnecting clients can tell "same server, transient
53
- // disconnect" (no reload) from "server restarted, reload". Kept on
54
- // `globalThis` so it survives `bun --hot` module reloads (same process);
55
- // changes on `--cold` / full restart.
56
- const helloMsg = JSON.stringify({
57
- type: "hello",
58
- serverId: hotState().serverId,
59
- });
60
- const islandsDir = `${options.appDir.replace(/\/+$/, "")}/islands/`;
61
-
62
- const publish = (msg: string): void => {
63
- if (!server) return;
64
- server.publish(HMR_TOPIC, msg);
65
- };
66
-
67
- const notifyChange = (path: string): void => {
68
- if (path.startsWith(islandsDir)) {
69
- const rel = path.slice(islandsDir.length);
70
- const name = rel.replace(/\.[tj]sx?$/, "").replace(/\//g, "-");
71
- publish(JSON.stringify({ type: "update", island: name }));
72
- return;
73
- }
74
- publish(RELOAD_MSG);
75
- };
76
-
77
- const websocket: WebSocketHandler = {
78
- open(ws) {
79
- ws.subscribe(HMR_TOPIC);
80
- ws.send(helloMsg);
81
- },
82
- };
83
-
84
- const fetch = (_req: Request): Response =>
85
- new Response("Expected WebSocket upgrade", { status: 426 });
86
-
87
- return {
88
- fetch,
89
- websocket,
90
- notifyChange,
91
- attachServer(s) {
92
- server = s;
93
- },
94
- };
95
- }
@@ -1,52 +0,0 @@
1
- // Inline HMR client snippet, framework-controlled string (no user input).
2
- // Injected into dev-mode HTML responses by src/render/index.tsx.
3
- export const HMR_CLIENT_SCRIPT = `
4
- (function () {
5
- var url = (location.protocol === "https:" ? "wss:" : "ws:") + "//" + location.host + "/__sordo_hmr";
6
- var backoff = 250;
7
- var failures = 0;
8
- function connect() {
9
- var ws;
10
- try { ws = new WebSocket(url); } catch (e) { schedule(); return; }
11
- ws.addEventListener("open", function () {
12
- backoff = 250;
13
- failures = 0;
14
- });
15
- ws.addEventListener("message", function (ev) {
16
- var msg;
17
- try { msg = JSON.parse(ev.data); } catch (e) { return; }
18
- if (!msg || typeof msg !== "object") return;
19
- if (msg.type === "hello" && typeof msg.serverId === "string") {
20
- // Reload only if the server id changed from a prior session — i.e. the
21
- // server actually restarted. First-ever connect and same-server
22
- // reconnects are no-ops.
23
- var key = "sordo:devServerId";
24
- var prev = null;
25
- try { prev = sessionStorage.getItem(key); } catch (e) {}
26
- if (prev && prev !== msg.serverId) {
27
- try { sessionStorage.setItem(key, msg.serverId); } catch (e) {}
28
- location.reload();
29
- return;
30
- }
31
- try { sessionStorage.setItem(key, msg.serverId); } catch (e) {}
32
- return;
33
- }
34
- if (msg.type === "reload") { location.reload(); return; }
35
- if (msg.type === "update" && msg.island) {
36
- try {
37
- window.dispatchEvent(new CustomEvent("sordo:island-update", { detail: { island: msg.island } }));
38
- } catch (e) {}
39
- }
40
- });
41
- ws.addEventListener("close", function () { schedule(); });
42
- ws.addEventListener("error", function () { try { ws.close(); } catch (e) {} });
43
- }
44
- function schedule() {
45
- failures++;
46
- if (failures === 5) { try { console.warn("[sordo] dev server unreachable, still retrying…"); } catch (e) {} }
47
- setTimeout(connect, backoff);
48
- backoff = Math.min(backoff * 2, 5000);
49
- }
50
- connect();
51
- })();
52
- `.trim();
@@ -1,23 +0,0 @@
1
- // GET /__sordo_open?file=<abs>&line=<n> → opens the file in the user's editor
2
- // via Bun.openInEditor(), returns 204.
3
- export async function handleOpenInEditor(req: Request): Promise<Response> {
4
- const url = new URL(req.url);
5
- const file = url.searchParams.get("file");
6
- const lineRaw = url.searchParams.get("line");
7
- if (!file) return new Response("missing ?file", { status: 400 });
8
- const line = lineRaw ? Number(lineRaw) : undefined;
9
-
10
- try {
11
- const opener = (
12
- Bun as unknown as {
13
- openInEditor?: (f: string, opts?: { line?: number }) => void;
14
- }
15
- ).openInEditor;
16
- if (typeof opener === "function") {
17
- opener(file, line ? { line } : undefined);
18
- }
19
- return new Response(null, { status: 204 });
20
- } catch (err) {
21
- return new Response((err as Error).message, { status: 500 });
22
- }
23
- }
@@ -1,30 +0,0 @@
1
- // Runtime-global lookups that survive the `edge` target. workerd has neither
2
- // `Bun` nor (without `nodejs_compat`) `process`, and a bare reference to either
3
- // is a ReferenceError — so read them off `globalThis` instead.
4
-
5
- type Env = Record<string, string | undefined>;
6
-
7
- export function bunGlobal(): Partial<typeof Bun> | undefined {
8
- return (globalThis as { Bun?: Partial<typeof Bun> }).Bun;
9
- }
10
-
11
- function processGlobal(): { env?: Env; cwd?: () => string } | undefined {
12
- return (globalThis as { process?: { env?: Env; cwd?: () => string } })
13
- .process;
14
- }
15
-
16
- // Bun.env on Bun, process.env on Node / nodejs_compat, else undefined (workerd
17
- // without nodejs_compat has no ambient env at all).
18
- export function findRuntimeEnv(): Env | undefined {
19
- return (bunGlobal()?.env as Env | undefined) ?? processGlobal()?.env;
20
- }
21
-
22
- export function runtimeEnv(): Env {
23
- return findRuntimeEnv() ?? {};
24
- }
25
-
26
- // process.cwd() where it exists; "/" on runtimes without a filesystem.
27
- export function runtimeCwd(): string {
28
- const cwd = processGlobal()?.cwd;
29
- return typeof cwd === "function" ? cwd() : "/";
30
- }
@@ -1,135 +0,0 @@
1
- // Minimal stand-in for Bun.CookieMap on runtimes that lack it (the `edge`
2
- // target). Covers the surface middleware relies on: read the inbound Cookie
3
- // header, set/delete, and flush changes as Set-Cookie values.
4
-
5
- export interface CookieOptions {
6
- domain?: string;
7
- path?: string;
8
- expires?: Date | number | string;
9
- maxAge?: number;
10
- secure?: boolean;
11
- httpOnly?: boolean;
12
- sameSite?: "strict" | "lax" | "none" | "Strict" | "Lax" | "None";
13
- partitioned?: boolean;
14
- }
15
-
16
- export interface CookieInit extends CookieOptions {
17
- name: string;
18
- value: string;
19
- }
20
-
21
- function decode(v: string): string {
22
- try {
23
- return decodeURIComponent(v);
24
- } catch {
25
- return v;
26
- }
27
- }
28
-
29
- // RFC 6265 cookie-name token; attribute values must not smuggle `;` or CTLs.
30
- const TOKEN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
31
- function isUnsafeAttr(v: string): boolean {
32
- for (let i = 0; i < v.length; i++) {
33
- const c = v.charCodeAt(i);
34
- if (c === 0x3b || c < 0x20 || c === 0x7f) return true;
35
- }
36
- return false;
37
- }
38
-
39
- function assertSafe(c: CookieInit): void {
40
- if (!TOKEN.test(c.name)) {
41
- throw new TypeError(`Invalid cookie name: ${JSON.stringify(c.name)}`);
42
- }
43
- for (const key of ["domain", "path"] as const) {
44
- const v = c[key];
45
- if (v !== undefined && isUnsafeAttr(v)) {
46
- throw new TypeError(`Invalid cookie ${key}: ${JSON.stringify(v)}`);
47
- }
48
- }
49
- }
50
-
51
- function serialize(c: CookieInit): string {
52
- const parts = [`${c.name}=${encodeURIComponent(c.value)}`];
53
- if (c.domain) parts.push(`Domain=${c.domain}`);
54
- parts.push(`Path=${c.path ?? "/"}`);
55
- if (c.expires !== undefined) {
56
- parts.push(`Expires=${new Date(c.expires).toUTCString()}`);
57
- }
58
- if (c.maxAge !== undefined) parts.push(`Max-Age=${Math.floor(c.maxAge)}`);
59
- if (c.secure) parts.push("Secure");
60
- if (c.httpOnly) parts.push("HttpOnly");
61
- if (c.sameSite) {
62
- const s = c.sameSite.toLowerCase();
63
- parts.push(`SameSite=${s[0]?.toUpperCase()}${s.slice(1)}`);
64
- }
65
- if (c.partitioned) parts.push("Partitioned");
66
- return parts.join("; ");
67
- }
68
-
69
- export class CookieJar {
70
- readonly #values = new Map<string, string>();
71
- readonly #changes = new Map<string, CookieInit>();
72
-
73
- constructor(header = "") {
74
- for (const pair of header.split(";")) {
75
- const eq = pair.indexOf("=");
76
- if (eq <= 0) continue;
77
- const name = pair.slice(0, eq).trim();
78
- if (name && !this.#values.has(name)) {
79
- this.#values.set(name, decode(pair.slice(eq + 1).trim()));
80
- }
81
- }
82
- }
83
-
84
- get size(): number {
85
- return this.#values.size;
86
- }
87
-
88
- get(name: string): string | null {
89
- return this.#values.get(name) ?? null;
90
- }
91
-
92
- has(name: string): boolean {
93
- return this.#values.has(name);
94
- }
95
-
96
- set(
97
- nameOrInit: string | CookieInit,
98
- value?: string,
99
- options: CookieOptions = {},
100
- ): void {
101
- const init: CookieInit =
102
- typeof nameOrInit === "string"
103
- ? { ...options, name: nameOrInit, value: value ?? "" }
104
- : nameOrInit;
105
- assertSafe(init);
106
- this.#values.set(init.name, init.value);
107
- this.#changes.set(init.name, init);
108
- }
109
-
110
- delete(
111
- nameOrOptions:
112
- | string
113
- | (Pick<CookieOptions, "domain" | "path"> & { name: string }),
114
- ): void {
115
- const opts =
116
- typeof nameOrOptions === "string"
117
- ? { name: nameOrOptions }
118
- : nameOrOptions;
119
- assertSafe({ ...opts, value: "" });
120
- this.#values.delete(opts.name);
121
- this.#changes.set(opts.name, { ...opts, value: "", expires: 0, maxAge: 0 });
122
- }
123
-
124
- entries(): IterableIterator<[string, string]> {
125
- return this.#values.entries();
126
- }
127
-
128
- [Symbol.iterator](): IterableIterator<[string, string]> {
129
- return this.entries();
130
- }
131
-
132
- toSetCookieHeaders(): string[] {
133
- return [...this.#changes.values()].map(serialize);
134
- }
135
- }
@@ -1,60 +0,0 @@
1
- import { bunGlobal, findRuntimeEnv } from "../internal/runtime.ts";
2
- import type { SordoContext } from "./index.ts";
3
-
4
- // Collect Set-Cookie header values from a mutated Bun.CookieMap.
5
- // Bun.CookieMap exposes toSetCookieHeaders() (per the bun-cookies RFC).
6
- // We probe at runtime and return [] if the shape differs.
7
- export function collectSetCookieHeaders(cookies: unknown): string[] {
8
- if (!cookies || typeof cookies !== "object") return [];
9
- const anyCookies = cookies as { toSetCookieHeaders?: () => string[] };
10
- if (typeof anyCookies.toSetCookieHeaders === "function") {
11
- return anyCookies.toSetCookieHeaders();
12
- }
13
- return [];
14
- }
15
-
16
- // Wall-clock millisecond reading. Prefer Bun.nanoseconds() on Bun; fall back to
17
- // performance.now() on non-Bun targets. Both yield double-precision ms.
18
- export function now(): number {
19
- const bun = bunGlobal();
20
- if (typeof bun?.nanoseconds === "function") {
21
- return Number(bun.nanoseconds()) / 1e6;
22
- }
23
- return performance.now();
24
- }
25
-
26
- // A runtime with no ambient env (edge) can't say it's dev, so it fails closed
27
- // and gets no dev-only headers.
28
- function isProduction(): boolean {
29
- const env = findRuntimeEnv();
30
- return env === undefined || env.NODE_ENV === "production";
31
- }
32
-
33
- // The response finalizer: flushes Set-Cookie headers, echoes the request id as
34
- // X-Request-Id, and (in dev only) emits Server-Timing. Handler-set X-Request-Id
35
- // and Server-Timing headers are never overwritten.
36
- export function finalizeResponse(
37
- res: Response,
38
- ctx: SordoContext,
39
- opts: { startMs: number },
40
- ): Response {
41
- const cookieValues = collectSetCookieHeaders(ctx.cookies);
42
- const headers = new Headers(res.headers);
43
-
44
- for (const v of cookieValues) headers.append("Set-Cookie", v);
45
-
46
- if (!headers.has("X-Request-Id")) {
47
- headers.set("X-Request-Id", ctx.requestId);
48
- }
49
-
50
- if (!isProduction() && !headers.has("Server-Timing")) {
51
- const ms = now() - opts.startMs;
52
- headers.set("Server-Timing", `total;dur=${ms.toFixed(1)}`);
53
- }
54
-
55
- return new Response(res.body, {
56
- status: res.status,
57
- statusText: res.statusText,
58
- headers,
59
- });
60
- }