sordo 0.5.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 -126
  2. package/README.md +8 -178
  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 -151
  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 -128
  44. package/src/build/embedded.ts +0 -66
  45. package/src/build/hash.ts +0 -21
  46. package/src/build/index.ts +0 -505
  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 -34
  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 -135
  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 -269
  138. package/src/router/match.ts +0 -91
  139. package/src/router/pattern.ts +0 -104
  140. package/src/server/index.ts +0 -250
  141. package/src/server/inline-assets.ts +0 -57
  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
@@ -1,136 +0,0 @@
1
- import type { BunPlugin } from "bun";
2
- import type { RouteEntry } from "../types.ts";
3
-
4
- export type HydrateDefault = "off" | "pages";
5
-
6
- export interface HydratedPage {
7
- entry: RouteEntry;
8
- // Stable per-build id; also the generated entry's file stem.
9
- id: string;
10
- hasDeserialize: boolean;
11
- }
12
-
13
- // Server-only page exports. Removed from the client bundle so their imports
14
- // (databases, secrets, `bun:*` modules) never reach the browser.
15
- const SERVER_ONLY_EXPORTS = ["loader", "serialize"];
16
-
17
- const HYDRATE_LITERAL_RE =
18
- /export\s+const\s+hydrate\s*(?::\s*boolean\s*)?=\s*(true|false)\b/;
19
- const BARE_IMPORT_RE = /^\s*import\s*["']([^"']+)["'];?\s*$/gm;
20
-
21
- function loaderFor(path: string): "tsx" | "ts" | "jsx" | "js" {
22
- if (path.endsWith(".tsx")) return "tsx";
23
- if (path.endsWith(".ts")) return "ts";
24
- if (path.endsWith(".jsx")) return "jsx";
25
- return "js";
26
- }
27
-
28
- // Decide statically (no module evaluation) whether a page route hydrates. A
29
- // non-literal `hydrate` export is rejected: the build can't know its value
30
- // without running user code.
31
- export function readHydrateFlag(
32
- source: string,
33
- filePath: string,
34
- defaultMode: HydrateDefault,
35
- ): { hydrate: boolean; exports: string[] } {
36
- const exports = new Bun.Transpiler({ loader: loaderFor(filePath) }).scan(
37
- source,
38
- ).exports;
39
- if (!exports.includes("hydrate")) {
40
- return { hydrate: defaultMode === "pages", exports };
41
- }
42
- const m = source.match(HYDRATE_LITERAL_RE);
43
- if (!m) {
44
- throw new Error(
45
- `sordo build: ${filePath} exports \`hydrate\` but not as a literal boolean. Use \`export const hydrate = true\` (or false).`,
46
- );
47
- }
48
- return { hydrate: m[1] === "true", exports };
49
- }
50
-
51
- export async function scanHydratedPages(
52
- entries: RouteEntry[],
53
- defaultMode: HydrateDefault,
54
- ): Promise<HydratedPage[]> {
55
- const out: HydratedPage[] = [];
56
- for (const entry of entries) {
57
- if (entry.kind !== "page") continue;
58
- const source = await Bun.file(entry.filePath).text();
59
- const { hydrate, exports } = readHydrateFlag(
60
- source,
61
- entry.filePath,
62
- defaultMode,
63
- );
64
- if (!hydrate) continue;
65
- out.push({
66
- entry,
67
- id: `page-${out.length}-${slug(entry.bunPattern)}`,
68
- hasDeserialize: exports.includes("deserialize"),
69
- });
70
- }
71
- return out;
72
- }
73
-
74
- function slug(pattern: string): string {
75
- const s = pattern
76
- .replace(/[^A-Za-z0-9]+/g, "-")
77
- .replace(/^-+|-+$/g, "")
78
- .toLowerCase();
79
- return s || "index";
80
- }
81
-
82
- export function generatePageEntry(
83
- page: HydratedPage,
84
- options: { frameworkRoot: string },
85
- ): string {
86
- const runtime = JSON.stringify(`${options.frameworkRoot}/client/page.ts`);
87
- const pagePath = JSON.stringify(page.entry.filePath);
88
- const named = page.hasDeserialize ? ", { deserialize }" : "";
89
- const exportsObj = page.hasDeserialize ? "{ Page, deserialize }" : "{ Page }";
90
- return `import { bootPage } from ${runtime}
91
- import Page${named} from ${pagePath}
92
-
93
- bootPage(${JSON.stringify(page.entry.bunPattern)}, ${exportsObj})
94
- `;
95
- }
96
-
97
- // Strip server-only exports from hydrated page modules before Bun.build sees
98
- // them. `Bun.Transpiler` eliminates the exports and trims the imports only
99
- // they used; trimmed imports survive as bare `import "x"` side-effect lines,
100
- // which are dropped unless the author wrote them that way.
101
- export function stripServerExportsPlugin(pagePaths: string[]): BunPlugin {
102
- const targets = new Set(pagePaths);
103
- return {
104
- name: "sordo:strip-server-exports",
105
- setup(builder) {
106
- builder.onLoad({ filter: /\.[jt]sx?$/ }, async (args) => {
107
- if (!targets.has(args.path)) return undefined;
108
- const source = await Bun.file(args.path).text();
109
- return {
110
- contents: stripServerExports(source, args.path),
111
- loader: "js",
112
- };
113
- });
114
- },
115
- };
116
- }
117
-
118
- export function stripServerExports(source: string, filePath: string): string {
119
- const authoredBare = new Set<string>();
120
- for (const m of source.matchAll(BARE_IMPORT_RE)) {
121
- if (m[1]) authoredBare.add(m[1]);
122
- }
123
- const transpiler = new Bun.Transpiler({
124
- loader: loaderFor(filePath),
125
- exports: { eliminate: SERVER_ONLY_EXPORTS },
126
- trimUnusedImports: true,
127
- autoImportJSX: true,
128
- // `react/jsx-runtime` exists in React's dev and prod builds alike, unlike
129
- // `jsxDEV`, so the stripped module works whichever one Bun.build resolves.
130
- define: { "process.env.NODE_ENV": '"production"' },
131
- });
132
- const out = transpiler.transformSync(source);
133
- return out.replace(BARE_IMPORT_RE, (line, spec: string) =>
134
- authoredBare.has(spec) ? line : "",
135
- );
136
- }
@@ -1,39 +0,0 @@
1
- export interface IslandEntry {
2
- name: string;
3
- filePath: string;
4
- relPath: string;
5
- }
6
-
7
- const TEST_FILE_RE = /\.test\.tsx$/;
8
-
9
- export async function scanIslands(appDir: string): Promise<IslandEntry[]> {
10
- const islandsDir = `${appDir.replace(/\/+$/, "")}/islands`;
11
- // Islands are React components — `.tsx` only. Plain `.ts` helpers next to
12
- // islands are not auto-registered. See spec 04 §"Client bundle".
13
- const glob = new Bun.Glob("**/*.tsx");
14
- const entries: IslandEntry[] = [];
15
-
16
- try {
17
- for await (const rel of glob.scan({ cwd: islandsDir, onlyFiles: true })) {
18
- const base = rel.split("/").pop() ?? rel;
19
- if (base.startsWith("_")) continue;
20
- if (TEST_FILE_RE.test(base)) continue;
21
- entries.push({
22
- name: islandNameFromRel(rel),
23
- filePath: `${islandsDir}/${rel}`,
24
- relPath: rel,
25
- });
26
- }
27
- } catch (err) {
28
- const msg = (err as Error)?.message ?? "";
29
- if (/ENOENT|no such file/i.test(msg)) return [];
30
- throw err;
31
- }
32
-
33
- entries.sort((a, b) => a.name.localeCompare(b.name));
34
- return entries;
35
- }
36
-
37
- function islandNameFromRel(rel: string): string {
38
- return rel.replace(/\.[tj]sx?$/, "").replace(/\//g, "-");
39
- }
@@ -1,256 +0,0 @@
1
- import type { ScannedModule } from "../ai/scan.ts";
2
- import type { RouteEntry } from "../types.ts";
3
-
4
- export interface ServerEntryInput {
5
- appDir: string;
6
- entries: RouteEntry[];
7
- agents?: ScannedModule[];
8
- tools?: ScannedModule[];
9
- jobs?: ScannedModule[];
10
- hasUserMiddleware: boolean;
11
- frameworkRoot: string; // absolute path to the framework src/ root
12
- routesMacroPath: string; // absolute path to routes.macro.ts
13
- envMacroPath: string; // absolute path to env.macro.ts
14
- manifestMacroPath: string; // absolute path to manifest.macro.ts
15
- agentsHashMacroPath: string; // absolute path to agents-hash.macro.ts
16
- agentsMacroPath?: string; // absolute path to agents.macro.ts
17
- manifestPath: string; // absolute path to the on-disk manifest.json
18
- // Client outputs (island/page chunks, the CSS sheet and its assets) inlined
19
- // via macro and served from memory. Absent in compile mode and when the
20
- // build produced no client files.
21
- inlineAssets?: { macroPath: string; listPath: string };
22
- target: "bun" | "edge";
23
- port?: number;
24
- /** Emit Bun.embeddedFiles static-map wiring (bun + --compile only). */
25
- compile?: boolean;
26
- }
27
-
28
- // Generate the source for the synthetic server entry written into outDir/.gen/.
29
- // Build-time data (route table, public env, client manifest, AGENTS.md hash) is
30
- // pulled in via Bun's `with { type: "macro" }` import attribute so the
31
- // production bundle never performs a filesystem scan — the guarantee is
32
- // compiler-enforced, not author-disciplined. See spec 04 §"Macro policy".
33
- export function generateServerEntry(input: ServerEntryInput): string {
34
- const {
35
- appDir,
36
- entries,
37
- hasUserMiddleware,
38
- frameworkRoot,
39
- routesMacroPath,
40
- envMacroPath,
41
- manifestMacroPath,
42
- agentsHashMacroPath,
43
- manifestPath,
44
- target,
45
- port,
46
- } = input;
47
-
48
- const agents = input.agents ?? [];
49
- const tools = input.tools ?? [];
50
- const jobs = input.jobs ?? [];
51
-
52
- // Compile mode embeds app/public assets + client chunks into the binary and
53
- // serves them from Bun.embeddedFiles. Bun-only; edge never compiles.
54
- const emitEmbedded = target === "bun" && input.compile === true;
55
- const embeddedImport = emitEmbedded
56
- ? `import { EMBEDDED_ASSET_PATHS } from "./embedded-manifest.ts"`
57
- : "";
58
- const staticMapSetup = emitEmbedded
59
- ? `const __filesByName = new Map()
60
- for (const f of Bun.embeddedFiles) {
61
- __filesByName.set(f.name, f)
62
- const __base = String(f.name).split("/").pop()
63
- if (__base && !__filesByName.has(__base)) __filesByName.set(__base, f)
64
- }
65
- const __staticMap = {}
66
- for (const [route, id] of Object.entries(EMBEDDED_ASSET_PATHS)) {
67
- const f = __filesByName.get(id) ?? __filesByName.get(String(id).split("/").pop())
68
- if (f) __staticMap[route] = new Response(f, { headers: { "content-type": f.type || "application/octet-stream" } })
69
- }`
70
- : "";
71
-
72
- const fwImport = (sub: string) => JSON.stringify(`${frameworkRoot}/${sub}`);
73
-
74
- const inline = input.inlineAssets;
75
- const inlineImports = inline
76
- ? `import { INLINE_ASSETS } from ${JSON.stringify(inline.macroPath)} with { type: "macro" }
77
- import { inlineAssetRoutes, matchInlineAsset } from ${fwImport("server/inline-assets.ts")}
78
- const INLINE_ASSET_DATA = await INLINE_ASSETS(${JSON.stringify(inline.listPath)})`
79
- : "";
80
- // Compile mode embeds client/ in the binary, so the build only passes
81
- // `inlineAssets` for non-compiled servers.
82
- const staticRoutesExpr = emitEmbedded
83
- ? "__staticMap"
84
- : inline
85
- ? "inlineAssetRoutes(INLINE_ASSET_DATA)"
86
- : null;
87
-
88
- // Workaround: Bun.build can fail to resolve a `.tsx` import when a sibling
89
- // `.ts` import with a shared path prefix is encountered first. Emit the
90
- // import statements with `.tsx` files first; ROUTE_TABLE keeps the canonical
91
- // routing order separately.
92
- const importOrder = entries
93
- .map((e, idx) => ({ e, idx }))
94
- .sort((a, b) => {
95
- const ax = a.e.filePath.endsWith(".tsx") ? 0 : 1;
96
- const bx = b.e.filePath.endsWith(".tsx") ? 0 : 1;
97
- return ax - bx;
98
- });
99
- const routeImports = importOrder
100
- .map(
101
- ({ e, idx }) => `import * as R${idx} from ${JSON.stringify(e.filePath)}`,
102
- )
103
- .join("\n");
104
-
105
- const moduleMapEntries = entries
106
- .map((e, idx) => ` [${JSON.stringify(e.filePath)}]: R${idx}`)
107
- .join(",\n");
108
-
109
- const middlewareImport = hasUserMiddleware
110
- ? `import userMiddleware from ${JSON.stringify(`${appDir}/middleware.ts`)}`
111
- : `const userMiddleware = undefined`;
112
-
113
- const appDirLiteral = JSON.stringify(appDir);
114
- const manifestPathLiteral = JSON.stringify(manifestPath);
115
-
116
- const agentImports = agents
117
- .map((a, i) => `import AGENT_MOD_${i} from ${JSON.stringify(a.filePath)}`)
118
- .join("\n");
119
- const toolImports = tools
120
- .map((t, i) => `import TOOL_MOD_${i} from ${JSON.stringify(t.filePath)}`)
121
- .join("\n");
122
- const jobImports = jobs
123
- .map((j, i) => `import JOB_MOD_${i} from ${JSON.stringify(j.filePath)}`)
124
- .join("\n");
125
-
126
- const aiImports =
127
- agents.length || tools.length || jobs.length
128
- ? `import { registerAgent, registerTool, registerJob, hasAny as __hasAnyAi } from ${fwImport("ai/index.ts")}
129
- import { createAiContextMiddleware } from ${fwImport("ai/middleware.ts")}
130
- import { registerAgentTriggers } from ${fwImport("ai/triggers.ts")}
131
- import { createAiContext as __createAiContext } from ${fwImport("ai/context.ts")}
132
- import { validateNamedModules, validateAgentToolReferences, validateJobs } from ${fwImport("ai/validate.ts")}`
133
- : "";
134
-
135
- const aiRegistration =
136
- agents.length || tools.length || jobs.length
137
- ? `
138
- const __agentMods = [
139
- ${agents.map((a, i) => ` { expectedName: ${JSON.stringify(a.name)}, filePath: ${JSON.stringify(a.filePath)}, config: AGENT_MOD_${i} }`).join(",\n")}
140
- ]
141
- const __toolMods = [
142
- ${tools.map((t, i) => ` { expectedName: ${JSON.stringify(t.name)}, filePath: ${JSON.stringify(t.filePath)}, config: TOOL_MOD_${i} }`).join(",\n")}
143
- ]
144
- const __jobMods = [
145
- ${jobs.map((j, i) => ` { expectedName: ${JSON.stringify(j.name)}, filePath: ${JSON.stringify(j.filePath)}, config: JOB_MOD_${i} }`).join(",\n")}
146
- ]
147
- validateNamedModules("agent", __agentMods)
148
- validateNamedModules("tool", __toolMods)
149
- validateNamedModules("job", __jobMods)
150
- validateAgentToolReferences(__agentMods, __toolMods)
151
- validateJobs(__jobMods)
152
- for (const t of __toolMods) registerTool(t.config, t.filePath)
153
- for (const a of __agentMods) registerAgent(a.config, a.filePath)
154
- for (const j of __jobMods) registerJob(j.config, j.filePath)
155
- `
156
- : "";
157
-
158
- const aiMiddlewareInject =
159
- agents.length || tools.length
160
- ? `const __aiMiddleware = __hasAnyAi() ? createAiContextMiddleware() : undefined
161
- const __composedMiddleware = __aiMiddleware
162
- ? (userMiddleware
163
- ? async (req, ctx, next) => __aiMiddleware(req, ctx, () => userMiddleware(req, ctx, next))
164
- : __aiMiddleware)
165
- : userMiddleware`
166
- : `const __composedMiddleware = userMiddleware`;
167
-
168
- const triggerWire = agents.length
169
- ? `registerAgentTriggers(router.routes, ROUTE_TABLE)`
170
- : "";
171
-
172
- const cronWire =
173
- jobs.length && target === "bun"
174
- ? `
175
- if (typeof (Bun).cron === "function") {
176
- for (const j of __jobMods) {
177
- try {
178
- (Bun).cron(j.config.schedule, () => {
179
- const __ctx = __createAiContext({ requestId: crypto.randomUUID() })
180
- return j.config.handler(__ctx)
181
- })
182
- } catch (err) {
183
- console.error("[sordo] failed to register cron job " + j.config.name + ":", err)
184
- }
185
- }
186
- }
187
- `
188
- : "";
189
-
190
- const bootForBun = `
191
- ${triggerWire}
192
- ${cronWire}
193
- ${staticMapSetup}
194
- const server = startServer({
195
- port: Number(Bun.env.PORT) || ${port ?? 3000},
196
- routes: router.routes,
197
- fallback: router.fallback,${staticRoutesExpr ? `\n staticRoutes: ${staticRoutesExpr},` : ""}
198
- })
199
- export { server }
200
- `.trim();
201
-
202
- const bootForEdge = `
203
- ${triggerWire}
204
- const __compiled = compilePatterns(router.routes)
205
- export default {
206
- async fetch(req: Request, env: Record<string, unknown>, execCtx: { waitUntil(p: Promise<unknown>): void }) {${inline ? "\n const asset = matchInlineAsset(INLINE_ASSET_DATA, req)\n if (asset) return asset" : ""}
207
- const hit = await dispatch(router.routes, req, { env, execCtx }, __compiled)
208
- if (hit) return hit
209
- return router.fallback(Object.assign(req, { env, execCtx }))
210
- }
211
- }
212
- `.trim();
213
-
214
- const boot = target === "edge" ? bootForEdge : bootForBun;
215
-
216
- return `${routeImports}
217
- ${agentImports}
218
- ${toolImports}
219
- ${jobImports}
220
- ${middlewareImport}
221
- ${aiImports}
222
- import { ROUTES } from ${JSON.stringify(routesMacroPath)} with { type: "macro" }
223
- import { PUBLIC_ENV } from ${JSON.stringify(envMacroPath)} with { type: "macro" }
224
- import { MANIFEST } from ${JSON.stringify(manifestMacroPath)} with { type: "macro" }
225
- import { AGENTS_HASH } from ${JSON.stringify(agentsHashMacroPath)} with { type: "macro" }
226
- import { createCompiledRouter } from ${fwImport("router/index.ts")}
227
- import { createRenderer } from ${fwImport("render/index.tsx")}
228
- import { startServer } from ${fwImport("server/index.ts")}
229
- import { compilePatterns, dispatch } from ${fwImport("router/match.ts")}
230
- ${embeddedImport}
231
- ${inlineImports}
232
-
233
- const ROUTE_TABLE = await ROUTES(${appDirLiteral})
234
- const PUBLIC_ENV_VALUES = PUBLIC_ENV()
235
- const MANIFEST_DATA = await MANIFEST(${manifestPathLiteral})
236
- const AGENTS_MD_HASH = await AGENTS_HASH(${appDirLiteral})
237
- void PUBLIC_ENV_VALUES
238
- void AGENTS_MD_HASH
239
- void ${appDirLiteral}
240
- const MODULES = {
241
- ${moduleMapEntries}
242
- }
243
- ${aiRegistration}
244
- ${aiMiddlewareInject}
245
-
246
- const renderer = createRenderer({ manifest: MANIFEST_DATA, modules: MODULES, dev: false })
247
- const router = await createCompiledRouter({
248
- renderer,
249
- middleware: __composedMiddleware,
250
- entries: ROUTE_TABLE,
251
- modules: MODULES,
252
- })
253
-
254
- ${boot}
255
- `;
256
- }
package/src/cli/ansi.ts DELETED
@@ -1,41 +0,0 @@
1
- // Width-aware terminal output helpers, built on Bun builtins so the CLI never
2
- // pulls the chalk-ecosystem trio (`string-width` / `strip-ansi` / `wrap-ansi`).
3
- // See framework/24 §24.2 and rfc-bun-cli-ansi. Color *emission* stays inline in
4
- // log.ts; this module is measurement + layout only.
5
-
6
- /** Pad `s` on the right to `width` display columns. Never truncates. */
7
- export function padEnd(s: string, width: number): string {
8
- const w = Bun.stringWidth(s);
9
- return w >= width ? s : s + " ".repeat(width - w);
10
- }
11
-
12
- /** Strip ANSI escapes — used before emitting to a non-TTY / `--json`. */
13
- export function strip(s: string): string {
14
- return Bun.stripANSI(s);
15
- }
16
-
17
- /** Current terminal width, defaulting to 80 when not attached to a TTY. */
18
- export function terminalColumns(): number {
19
- const cols = process.stdout.columns;
20
- return typeof cols === "number" && cols > 0 ? cols : 80;
21
- }
22
-
23
- /**
24
- * Hard-wrap `text` to `cols` (preserving inline ANSI styling), then prefix the
25
- * first line with `firstPrefix` and every continuation line with `contPrefix`.
26
- * Prefixes are applied *after* wrapping because `Bun.wrapAnsi` trims leading
27
- * whitespace per line, so a leading indent baked into `text` would be lost.
28
- */
29
- export function wrapWithPrefix(
30
- text: string,
31
- cols: number,
32
- firstPrefix: string,
33
- contPrefix: string,
34
- ): string {
35
- const width = Math.max(1, cols - Bun.stringWidth(firstPrefix));
36
- const wrapped = Bun.wrapAnsi(text, width, { hard: true });
37
- return wrapped
38
- .split("\n")
39
- .map((line, i) => (i === 0 ? firstPrefix : contPrefix) + line)
40
- .join("\n");
41
- }
package/src/cli/build.ts DELETED
@@ -1,195 +0,0 @@
1
- import { resolve } from "node:path";
2
- import pkg from "../../package.json" with { type: "json" };
3
- import { generateAgentsMd } from "../agents-md/generate.ts";
4
- import { writeManifestToFile } from "../agents-md/write.ts";
5
- import { build } from "../build/index.ts";
6
- import { loadConfig } from "../config/load.ts";
7
- import { assertPluginCompat, type Plugin } from "../plugin/index.ts";
8
- import type { CliContext } from "./index.ts";
9
- import { EXIT, formatError, log } from "./log.ts";
10
-
11
- // 80% of the 3 MB gzipped free-plan Worker script limit.
12
- const WORKER_WARN_BYTES = 0.8 * 3 * 1024 * 1024;
13
-
14
- const FRAMEWORK_VERSION = (pkg as { version: string }).version;
15
-
16
- export interface BuildArgs {
17
- target?: "bun" | "edge";
18
- outDir?: string;
19
- appDir?: string;
20
- compile?: boolean;
21
- mode: "development" | "production";
22
- }
23
-
24
- export async function runBuild(
25
- argv: string[],
26
- ctx: CliContext = { cwd: process.cwd(), verbose: false },
27
- ): Promise<number> {
28
- const args = parseArgs(argv, ctx.cwd);
29
-
30
- let loaded: Awaited<ReturnType<typeof loadConfig>>;
31
- try {
32
- loaded = await loadConfig({
33
- cwd: ctx.cwd,
34
- configPath: ctx.configPath,
35
- overrides: args.target ? { target: args.target } : undefined,
36
- });
37
- } catch (err) {
38
- const msg = (err as Error)?.message ?? String(err);
39
- log.error(msg);
40
- return EXIT.ERROR;
41
- }
42
- const { config } = loaded;
43
-
44
- const target = config.target;
45
- const appDir = args.appDir ?? config.appDir;
46
- const outDir = args.outDir ?? config.outDir;
47
- const compile = args.compile ?? config.adapter.bun.compile;
48
-
49
- if (compile && target === "edge") {
50
- log.error(
51
- 'sordo build: adapter.bun.compile is only supported with target "bun" (got target "edge"). Remove --compile or set target: "bun".',
52
- );
53
- return EXIT.ERROR;
54
- }
55
-
56
- const plugins = (config.plugins ?? []) as Plugin[];
57
- for (const p of plugins) assertPluginCompat(FRAMEWORK_VERSION, p);
58
-
59
- const t0 = performance.now();
60
- let result: Awaited<ReturnType<typeof build>> | undefined;
61
- let failure: Error | undefined;
62
- try {
63
- result = await build({
64
- appDir,
65
- outDir,
66
- target,
67
- mode: args.mode,
68
- compile,
69
- plugins,
70
- hydrate: config.render.hydrate,
71
- css: config.css,
72
- edgeAssets: config.adapter.edge.assets,
73
- });
74
- } catch (err) {
75
- failure = err as Error;
76
- }
77
- const elapsedMs = performance.now() - t0;
78
-
79
- if (failure || !result) {
80
- printError(failure ?? new Error("build failed"));
81
- return EXIT.ERROR;
82
- }
83
-
84
- await printSummary(result, { target, outDir, elapsedMs });
85
-
86
- try {
87
- const md = await generateAgentsMd(appDir, {
88
- appDir,
89
- env: { required: config.env.required, optional: config.env.public },
90
- plugins,
91
- });
92
- const targets = agentsMdTargets(config.agentsMd.path);
93
- for (const t of targets) {
94
- await writeManifestToFile(`${ctx.cwd}/${t}`, md);
95
- log.success(`${t}: manifest section updated`);
96
- }
97
- } catch (err) {
98
- log.warn(
99
- `agent manifest generation failed: ${(err as Error)?.message ?? String(err)}`,
100
- );
101
- }
102
- return EXIT.OK;
103
- }
104
-
105
- function agentsMdTargets(path: string | string[]): string[] {
106
- const list = Array.isArray(path) ? path : [path];
107
- return list.map((p) => p.replace(/^\/+/, ""));
108
- }
109
-
110
- function printError(err: Error): void {
111
- process.stderr.write(
112
- `${formatError({ title: "Build failed", reason: err.message })}\n`,
113
- );
114
- }
115
-
116
- interface SummaryCtx {
117
- target: "bun" | "edge";
118
- outDir: string;
119
- elapsedMs: number;
120
- }
121
-
122
- async function printSummary(
123
- result: Awaited<ReturnType<typeof build>>,
124
- ctx: SummaryCtx,
125
- ): Promise<void> {
126
- log.success(
127
- `built ${ctx.target} target (${(ctx.elapsedMs / 1000).toFixed(2)}s)`,
128
- );
129
- log.dim(` out: ${ctx.outDir}`);
130
- const serverSize = await gzippedSize(result.serverEntry);
131
- log.dim(
132
- ` serverEntry: ${result.serverEntry} (${formatBytes(serverSize)} gz)`,
133
- );
134
- if (ctx.target === "edge") {
135
- if (serverSize >= WORKER_WARN_BYTES) {
136
- log.warn(
137
- `worker.js is ${formatBytes(serverSize)} gz — Cloudflare caps a Worker at 3 MB gz (free) / 10 MB gz (paid). Set adapter.edge.assets: "external" to move client assets out of the script.`,
138
- );
139
- }
140
- }
141
- if (result.assets.length > 0) {
142
- log.dim(` assets:`);
143
- for (const a of result.assets) {
144
- const size = await gzippedSize(a.dest);
145
- log.dim(` ${a.publicPath} ${formatBytes(size)} gz`);
146
- }
147
- }
148
- log.dim(
149
- ` counts: routes=${result.counts.routes} islands=${result.counts.islands} hydrated=${result.counts.hydratedPages} agents=${result.counts.agents} tools=${result.counts.tools} jobs=${result.counts.jobs}`,
150
- );
151
- const hydrated = Object.entries(result.clientBytes);
152
- if (hydrated.length > 0) {
153
- // Raw bytes a cold visit downloads per hydrated route (entry + imports).
154
- log.dim(` hydrated pages (client JS):`);
155
- for (const [route, bytes] of hydrated) {
156
- log.dim(` ${route} ${formatBytes(bytes)}`);
157
- }
158
- }
159
- if (result.artifacts.length > 0) {
160
- log.dim(` artifacts: ${result.artifacts.join(", ")}`);
161
- }
162
- }
163
-
164
- async function gzippedSize(path: string): Promise<number> {
165
- try {
166
- const bytes = await Bun.file(path).bytes();
167
- return Bun.gzipSync(bytes).byteLength;
168
- } catch {
169
- return 0;
170
- }
171
- }
172
-
173
- function formatBytes(n: number): string {
174
- if (n < 1024) return `${n} B`;
175
- if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;
176
- return `${(n / 1024 / 1024).toFixed(2)} MB`;
177
- }
178
-
179
- function parseArgs(argv: string[], cwd: string): BuildArgs {
180
- const out: BuildArgs = { mode: "production" };
181
- for (let i = 0; i < argv.length; i++) {
182
- const a = argv[i];
183
- if (a === undefined) continue;
184
- if (a === "--target") out.target = String(argv[++i]) as "bun" | "edge";
185
- else if (a.startsWith("--target="))
186
- out.target = a.slice(9) as "bun" | "edge";
187
- else if (a === "--out") out.outDir = resolve(cwd, String(argv[++i]));
188
- else if (a.startsWith("--out=")) out.outDir = resolve(cwd, a.slice(6));
189
- else if (a === "--app") out.appDir = resolve(cwd, String(argv[++i]));
190
- else if (a.startsWith("--app=")) out.appDir = resolve(cwd, a.slice(6));
191
- else if (a === "--compile") out.compile = true;
192
- else if (a === "--dev") out.mode = "development";
193
- }
194
- return out;
195
- }
@@ -1,31 +0,0 @@
1
- import type { ComponentEntry } from "../../../ui/types.ts";
2
- import { stampInternals } from "./internal.ts";
3
- import { applyDeps, planDeps } from "./peer-deps.ts";
4
- import { applyStamp, planStamp } from "./stamper.ts";
5
- import { mergeTokens } from "./tokens.ts";
6
- import type { UiPaths } from "./ui-paths.ts";
7
-
8
- // Stamp a component's files, helpers, tokens, and peer deps. `force` overwrites
9
- // existing files / re-merges the token block (used by `update`). Shared by
10
- // `sordo add` and `sordo update`.
11
- export async function applyComponent(
12
- entry: ComponentEntry,
13
- cwd: string,
14
- uiPaths: UiPaths,
15
- templatesDir: string,
16
- opts: { force: boolean; themeName?: string },
17
- ): Promise<void> {
18
- const plan = await planStamp(entry, uiPaths, templatesDir);
19
- const depPlan = await planDeps(entry.peerDeps, cwd);
20
- await stampInternals(entry.internalHelpers, uiPaths, templatesDir, {
21
- dryRun: false,
22
- force: opts.force,
23
- });
24
- await applyStamp(plan, { force: opts.force });
25
- await applyDeps(depPlan, cwd);
26
- await mergeTokens(entry.tokens ?? [], uiPaths, templatesDir, {
27
- dryRun: false,
28
- force: opts.force,
29
- themeName: opts.themeName,
30
- });
31
- }