@cloudwerk/cli 0.0.6 → 0.1.1

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 (2) hide show
  1. package/dist/index.js +545 -77
  2. package/package.json +3 -2
package/dist/index.js CHANGED
@@ -4,8 +4,8 @@
4
4
  import { program } from "commander";
5
5
 
6
6
  // src/commands/dev.ts
7
- import * as path2 from "path";
8
- import * as fs2 from "fs";
7
+ import * as path6 from "path";
8
+ import * as fs5 from "fs";
9
9
  import * as os from "os";
10
10
  import { serve } from "@hono/node-server";
11
11
  import {
@@ -112,11 +112,11 @@ function printError(message, suggestion) {
112
112
  }
113
113
  console.log();
114
114
  }
115
- function logRequest(method, path3, status, duration) {
115
+ function logRequest(method, path7, status, duration) {
116
116
  const methodColor = getMethodColor(method);
117
117
  const statusColor = status >= 400 ? pc.red : status >= 300 ? pc.yellow : pc.green;
118
118
  console.log(
119
- pc.dim("[") + methodColor(method.padEnd(6)) + pc.dim("]") + " " + path3 + " " + statusColor(String(status)) + " " + pc.dim(`${duration}ms`)
119
+ pc.dim("[") + methodColor(method.padEnd(6)) + pc.dim("]") + " " + path7 + " " + statusColor(String(status)) + " " + pc.dim(`${duration}ms`)
120
120
  );
121
121
  }
122
122
 
@@ -237,26 +237,26 @@ var handleParsingNestedValues = (form, key, value) => {
237
237
  };
238
238
 
239
239
  // ../../node_modules/.pnpm/hono@4.11.5/node_modules/hono/dist/utils/url.js
240
- var splitPath = (path3) => {
241
- const paths = path3.split("/");
240
+ var splitPath = (path7) => {
241
+ const paths = path7.split("/");
242
242
  if (paths[0] === "") {
243
243
  paths.shift();
244
244
  }
245
245
  return paths;
246
246
  };
247
247
  var splitRoutingPath = (routePath) => {
248
- const { groups, path: path3 } = extractGroupsFromPath(routePath);
249
- const paths = splitPath(path3);
248
+ const { groups, path: path7 } = extractGroupsFromPath(routePath);
249
+ const paths = splitPath(path7);
250
250
  return replaceGroupMarks(paths, groups);
251
251
  };
252
- var extractGroupsFromPath = (path3) => {
252
+ var extractGroupsFromPath = (path7) => {
253
253
  const groups = [];
254
- path3 = path3.replace(/\{[^}]+\}/g, (match2, index) => {
254
+ path7 = path7.replace(/\{[^}]+\}/g, (match2, index) => {
255
255
  const mark = `@${index}`;
256
256
  groups.push([mark, match2]);
257
257
  return mark;
258
258
  });
259
- return { groups, path: path3 };
259
+ return { groups, path: path7 };
260
260
  };
261
261
  var replaceGroupMarks = (paths, groups) => {
262
262
  for (let i = groups.length - 1; i >= 0; i--) {
@@ -311,8 +311,8 @@ var getPath = (request) => {
311
311
  const charCode = url.charCodeAt(i);
312
312
  if (charCode === 37) {
313
313
  const queryIndex = url.indexOf("?", i);
314
- const path3 = url.slice(start, queryIndex === -1 ? void 0 : queryIndex);
315
- return tryDecodeURI(path3.includes("%25") ? path3.replace(/%25/g, "%2525") : path3);
314
+ const path7 = url.slice(start, queryIndex === -1 ? void 0 : queryIndex);
315
+ return tryDecodeURI(path7.includes("%25") ? path7.replace(/%25/g, "%2525") : path7);
316
316
  } else if (charCode === 63) {
317
317
  break;
318
318
  }
@@ -329,11 +329,11 @@ var mergePath = (base, sub, ...rest) => {
329
329
  }
330
330
  return `${base?.[0] === "/" ? "" : "/"}${base}${sub === "/" ? "" : `${base?.at(-1) === "/" ? "" : "/"}${sub?.[0] === "/" ? sub.slice(1) : sub}`}`;
331
331
  };
332
- var checkOptionalParameter = (path3) => {
333
- if (path3.charCodeAt(path3.length - 1) !== 63 || !path3.includes(":")) {
332
+ var checkOptionalParameter = (path7) => {
333
+ if (path7.charCodeAt(path7.length - 1) !== 63 || !path7.includes(":")) {
334
334
  return null;
335
335
  }
336
- const segments = path3.split("/");
336
+ const segments = path7.split("/");
337
337
  const results = [];
338
338
  let basePath = "";
339
339
  segments.forEach((segment) => {
@@ -474,9 +474,9 @@ var HonoRequest = class {
474
474
  */
475
475
  path;
476
476
  bodyCache = {};
477
- constructor(request, path3 = "/", matchResult = [[]]) {
477
+ constructor(request, path7 = "/", matchResult = [[]]) {
478
478
  this.raw = request;
479
- this.path = path3;
479
+ this.path = path7;
480
480
  this.#matchResult = matchResult;
481
481
  this.#validatedData = {};
482
482
  }
@@ -1212,8 +1212,8 @@ var Hono = class _Hono {
1212
1212
  return this;
1213
1213
  };
1214
1214
  });
1215
- this.on = (method, path3, ...handlers) => {
1216
- for (const p of [path3].flat()) {
1215
+ this.on = (method, path7, ...handlers) => {
1216
+ for (const p of [path7].flat()) {
1217
1217
  this.#path = p;
1218
1218
  for (const m of [method].flat()) {
1219
1219
  handlers.map((handler) => {
@@ -1270,8 +1270,8 @@ var Hono = class _Hono {
1270
1270
  * app.route("/api", app2) // GET /api/user
1271
1271
  * ```
1272
1272
  */
1273
- route(path3, app) {
1274
- const subApp = this.basePath(path3);
1273
+ route(path7, app) {
1274
+ const subApp = this.basePath(path7);
1275
1275
  app.routes.map((r) => {
1276
1276
  let handler;
1277
1277
  if (app.errorHandler === errorHandler) {
@@ -1297,9 +1297,9 @@ var Hono = class _Hono {
1297
1297
  * const api = new Hono().basePath('/api')
1298
1298
  * ```
1299
1299
  */
1300
- basePath(path3) {
1300
+ basePath(path7) {
1301
1301
  const subApp = this.#clone();
1302
- subApp._basePath = mergePath(this._basePath, path3);
1302
+ subApp._basePath = mergePath(this._basePath, path7);
1303
1303
  return subApp;
1304
1304
  }
1305
1305
  /**
@@ -1373,7 +1373,7 @@ var Hono = class _Hono {
1373
1373
  * })
1374
1374
  * ```
1375
1375
  */
1376
- mount(path3, applicationHandler, options) {
1376
+ mount(path7, applicationHandler, options) {
1377
1377
  let replaceRequest;
1378
1378
  let optionHandler;
1379
1379
  if (options) {
@@ -1400,7 +1400,7 @@ var Hono = class _Hono {
1400
1400
  return [c.env, executionContext];
1401
1401
  };
1402
1402
  replaceRequest ||= (() => {
1403
- const mergedPath = mergePath(this._basePath, path3);
1403
+ const mergedPath = mergePath(this._basePath, path7);
1404
1404
  const pathPrefixLength = mergedPath === "/" ? 0 : mergedPath.length;
1405
1405
  return (request) => {
1406
1406
  const url = new URL(request.url);
@@ -1415,14 +1415,14 @@ var Hono = class _Hono {
1415
1415
  }
1416
1416
  await next();
1417
1417
  };
1418
- this.#addRoute(METHOD_NAME_ALL, mergePath(path3, "*"), handler);
1418
+ this.#addRoute(METHOD_NAME_ALL, mergePath(path7, "*"), handler);
1419
1419
  return this;
1420
1420
  }
1421
- #addRoute(method, path3, handler) {
1421
+ #addRoute(method, path7, handler) {
1422
1422
  method = method.toUpperCase();
1423
- path3 = mergePath(this._basePath, path3);
1424
- const r = { basePath: this._basePath, path: path3, method, handler };
1425
- this.router.add(method, path3, [handler, r]);
1423
+ path7 = mergePath(this._basePath, path7);
1424
+ const r = { basePath: this._basePath, path: path7, method, handler };
1425
+ this.router.add(method, path7, [handler, r]);
1426
1426
  this.routes.push(r);
1427
1427
  }
1428
1428
  #handleError(err, c) {
@@ -1435,10 +1435,10 @@ var Hono = class _Hono {
1435
1435
  if (method === "HEAD") {
1436
1436
  return (async () => new Response(null, await this.#dispatch(request, executionCtx, env, "GET")))();
1437
1437
  }
1438
- const path3 = this.getPath(request, { env });
1439
- const matchResult = this.router.match(method, path3);
1438
+ const path7 = this.getPath(request, { env });
1439
+ const matchResult = this.router.match(method, path7);
1440
1440
  const c = new Context(request, {
1441
- path: path3,
1441
+ path: path7,
1442
1442
  matchResult,
1443
1443
  env,
1444
1444
  executionCtx,
@@ -1538,7 +1538,7 @@ var Hono = class _Hono {
1538
1538
 
1539
1539
  // ../../node_modules/.pnpm/hono@4.11.5/node_modules/hono/dist/router/reg-exp-router/matcher.js
1540
1540
  var emptyParam = [];
1541
- function match(method, path3) {
1541
+ function match(method, path7) {
1542
1542
  const matchers = this.buildAllMatchers();
1543
1543
  const match2 = ((method2, path22) => {
1544
1544
  const matcher = matchers[method2] || matchers[METHOD_NAME_ALL];
@@ -1554,7 +1554,7 @@ function match(method, path3) {
1554
1554
  return [matcher[1][index], match3];
1555
1555
  });
1556
1556
  this.match = match2;
1557
- return match2(method, path3);
1557
+ return match2(method, path7);
1558
1558
  }
1559
1559
 
1560
1560
  // ../../node_modules/.pnpm/hono@4.11.5/node_modules/hono/dist/router/reg-exp-router/node.js
@@ -1669,12 +1669,12 @@ var Node = class _Node {
1669
1669
  var Trie = class {
1670
1670
  #context = { varIndex: 0 };
1671
1671
  #root = new Node();
1672
- insert(path3, index, pathErrorCheckOnly) {
1672
+ insert(path7, index, pathErrorCheckOnly) {
1673
1673
  const paramAssoc = [];
1674
1674
  const groups = [];
1675
1675
  for (let i = 0; ; ) {
1676
1676
  let replaced = false;
1677
- path3 = path3.replace(/\{[^}]+\}/g, (m) => {
1677
+ path7 = path7.replace(/\{[^}]+\}/g, (m) => {
1678
1678
  const mark = `@\\${i}`;
1679
1679
  groups[i] = [mark, m];
1680
1680
  i++;
@@ -1685,7 +1685,7 @@ var Trie = class {
1685
1685
  break;
1686
1686
  }
1687
1687
  }
1688
- const tokens = path3.match(/(?::[^\/]+)|(?:\/\*$)|./g) || [];
1688
+ const tokens = path7.match(/(?::[^\/]+)|(?:\/\*$)|./g) || [];
1689
1689
  for (let i = groups.length - 1; i >= 0; i--) {
1690
1690
  const [mark] = groups[i];
1691
1691
  for (let j = tokens.length - 1; j >= 0; j--) {
@@ -1724,9 +1724,9 @@ var Trie = class {
1724
1724
  // ../../node_modules/.pnpm/hono@4.11.5/node_modules/hono/dist/router/reg-exp-router/router.js
1725
1725
  var nullMatcher = [/^$/, [], /* @__PURE__ */ Object.create(null)];
1726
1726
  var wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
1727
- function buildWildcardRegExp(path3) {
1728
- return wildcardRegExpCache[path3] ??= new RegExp(
1729
- path3 === "*" ? "" : `^${path3.replace(
1727
+ function buildWildcardRegExp(path7) {
1728
+ return wildcardRegExpCache[path7] ??= new RegExp(
1729
+ path7 === "*" ? "" : `^${path7.replace(
1730
1730
  /\/\*$|([.\\+*[^\]$()])/g,
1731
1731
  (_, metaChar) => metaChar ? `\\${metaChar}` : "(?:|/.*)"
1732
1732
  )}$`
@@ -1748,17 +1748,17 @@ function buildMatcherFromPreprocessedRoutes(routes) {
1748
1748
  );
1749
1749
  const staticMap = /* @__PURE__ */ Object.create(null);
1750
1750
  for (let i = 0, j = -1, len = routesWithStaticPathFlag.length; i < len; i++) {
1751
- const [pathErrorCheckOnly, path3, handlers] = routesWithStaticPathFlag[i];
1751
+ const [pathErrorCheckOnly, path7, handlers] = routesWithStaticPathFlag[i];
1752
1752
  if (pathErrorCheckOnly) {
1753
- staticMap[path3] = [handlers.map(([h]) => [h, /* @__PURE__ */ Object.create(null)]), emptyParam];
1753
+ staticMap[path7] = [handlers.map(([h]) => [h, /* @__PURE__ */ Object.create(null)]), emptyParam];
1754
1754
  } else {
1755
1755
  j++;
1756
1756
  }
1757
1757
  let paramAssoc;
1758
1758
  try {
1759
- paramAssoc = trie.insert(path3, j, pathErrorCheckOnly);
1759
+ paramAssoc = trie.insert(path7, j, pathErrorCheckOnly);
1760
1760
  } catch (e) {
1761
- throw e === PATH_ERROR ? new UnsupportedPathError(path3) : e;
1761
+ throw e === PATH_ERROR ? new UnsupportedPathError(path7) : e;
1762
1762
  }
1763
1763
  if (pathErrorCheckOnly) {
1764
1764
  continue;
@@ -1792,12 +1792,12 @@ function buildMatcherFromPreprocessedRoutes(routes) {
1792
1792
  }
1793
1793
  return [regexp, handlerMap, staticMap];
1794
1794
  }
1795
- function findMiddleware(middleware, path3) {
1795
+ function findMiddleware(middleware, path7) {
1796
1796
  if (!middleware) {
1797
1797
  return void 0;
1798
1798
  }
1799
1799
  for (const k of Object.keys(middleware).sort((a, b) => b.length - a.length)) {
1800
- if (buildWildcardRegExp(k).test(path3)) {
1800
+ if (buildWildcardRegExp(k).test(path7)) {
1801
1801
  return [...middleware[k]];
1802
1802
  }
1803
1803
  }
@@ -1811,7 +1811,7 @@ var RegExpRouter = class {
1811
1811
  this.#middleware = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
1812
1812
  this.#routes = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
1813
1813
  }
1814
- add(method, path3, handler) {
1814
+ add(method, path7, handler) {
1815
1815
  const middleware = this.#middleware;
1816
1816
  const routes = this.#routes;
1817
1817
  if (!middleware || !routes) {
@@ -1826,18 +1826,18 @@ var RegExpRouter = class {
1826
1826
  });
1827
1827
  });
1828
1828
  }
1829
- if (path3 === "/*") {
1830
- path3 = "*";
1829
+ if (path7 === "/*") {
1830
+ path7 = "*";
1831
1831
  }
1832
- const paramCount = (path3.match(/\/:/g) || []).length;
1833
- if (/\*$/.test(path3)) {
1834
- const re = buildWildcardRegExp(path3);
1832
+ const paramCount = (path7.match(/\/:/g) || []).length;
1833
+ if (/\*$/.test(path7)) {
1834
+ const re = buildWildcardRegExp(path7);
1835
1835
  if (method === METHOD_NAME_ALL) {
1836
1836
  Object.keys(middleware).forEach((m) => {
1837
- middleware[m][path3] ||= findMiddleware(middleware[m], path3) || findMiddleware(middleware[METHOD_NAME_ALL], path3) || [];
1837
+ middleware[m][path7] ||= findMiddleware(middleware[m], path7) || findMiddleware(middleware[METHOD_NAME_ALL], path7) || [];
1838
1838
  });
1839
1839
  } else {
1840
- middleware[method][path3] ||= findMiddleware(middleware[method], path3) || findMiddleware(middleware[METHOD_NAME_ALL], path3) || [];
1840
+ middleware[method][path7] ||= findMiddleware(middleware[method], path7) || findMiddleware(middleware[METHOD_NAME_ALL], path7) || [];
1841
1841
  }
1842
1842
  Object.keys(middleware).forEach((m) => {
1843
1843
  if (method === METHOD_NAME_ALL || method === m) {
@@ -1855,7 +1855,7 @@ var RegExpRouter = class {
1855
1855
  });
1856
1856
  return;
1857
1857
  }
1858
- const paths = checkOptionalParameter(path3) || [path3];
1858
+ const paths = checkOptionalParameter(path7) || [path7];
1859
1859
  for (let i = 0, len = paths.length; i < len; i++) {
1860
1860
  const path22 = paths[i];
1861
1861
  Object.keys(routes).forEach((m) => {
@@ -1882,13 +1882,13 @@ var RegExpRouter = class {
1882
1882
  const routes = [];
1883
1883
  let hasOwnRoute = method === METHOD_NAME_ALL;
1884
1884
  [this.#middleware, this.#routes].forEach((r) => {
1885
- const ownRoute = r[method] ? Object.keys(r[method]).map((path3) => [path3, r[method][path3]]) : [];
1885
+ const ownRoute = r[method] ? Object.keys(r[method]).map((path7) => [path7, r[method][path7]]) : [];
1886
1886
  if (ownRoute.length !== 0) {
1887
1887
  hasOwnRoute ||= true;
1888
1888
  routes.push(...ownRoute);
1889
1889
  } else if (method !== METHOD_NAME_ALL) {
1890
1890
  routes.push(
1891
- ...Object.keys(r[METHOD_NAME_ALL]).map((path3) => [path3, r[METHOD_NAME_ALL][path3]])
1891
+ ...Object.keys(r[METHOD_NAME_ALL]).map((path7) => [path7, r[METHOD_NAME_ALL][path7]])
1892
1892
  );
1893
1893
  }
1894
1894
  });
@@ -1908,13 +1908,13 @@ var SmartRouter = class {
1908
1908
  constructor(init) {
1909
1909
  this.#routers = init.routers;
1910
1910
  }
1911
- add(method, path3, handler) {
1911
+ add(method, path7, handler) {
1912
1912
  if (!this.#routes) {
1913
1913
  throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
1914
1914
  }
1915
- this.#routes.push([method, path3, handler]);
1915
+ this.#routes.push([method, path7, handler]);
1916
1916
  }
1917
- match(method, path3) {
1917
+ match(method, path7) {
1918
1918
  if (!this.#routes) {
1919
1919
  throw new Error("Fatal error");
1920
1920
  }
@@ -1929,7 +1929,7 @@ var SmartRouter = class {
1929
1929
  for (let i2 = 0, len2 = routes.length; i2 < len2; i2++) {
1930
1930
  router.add(...routes[i2]);
1931
1931
  }
1932
- res = router.match(method, path3);
1932
+ res = router.match(method, path7);
1933
1933
  } catch (e) {
1934
1934
  if (e instanceof UnsupportedPathError) {
1935
1935
  continue;
@@ -1973,10 +1973,10 @@ var Node2 = class _Node2 {
1973
1973
  }
1974
1974
  this.#patterns = [];
1975
1975
  }
1976
- insert(method, path3, handler) {
1976
+ insert(method, path7, handler) {
1977
1977
  this.#order = ++this.#order;
1978
1978
  let curNode = this;
1979
- const parts = splitRoutingPath(path3);
1979
+ const parts = splitRoutingPath(path7);
1980
1980
  const possibleKeys = [];
1981
1981
  for (let i = 0, len = parts.length; i < len; i++) {
1982
1982
  const p = parts[i];
@@ -2027,12 +2027,12 @@ var Node2 = class _Node2 {
2027
2027
  }
2028
2028
  return handlerSets;
2029
2029
  }
2030
- search(method, path3) {
2030
+ search(method, path7) {
2031
2031
  const handlerSets = [];
2032
2032
  this.#params = emptyParams;
2033
2033
  const curNode = this;
2034
2034
  let curNodes = [curNode];
2035
- const parts = splitPath(path3);
2035
+ const parts = splitPath(path7);
2036
2036
  const curNodesQueue = [];
2037
2037
  for (let i = 0, len = parts.length; i < len; i++) {
2038
2038
  const part = parts[i];
@@ -2120,18 +2120,18 @@ var TrieRouter = class {
2120
2120
  constructor() {
2121
2121
  this.#node = new Node2();
2122
2122
  }
2123
- add(method, path3, handler) {
2124
- const results = checkOptionalParameter(path3);
2123
+ add(method, path7, handler) {
2124
+ const results = checkOptionalParameter(path7);
2125
2125
  if (results) {
2126
2126
  for (let i = 0, len = results.length; i < len; i++) {
2127
2127
  this.#node.insert(method, results[i], handler);
2128
2128
  }
2129
2129
  return;
2130
2130
  }
2131
- this.#node.insert(method, path3, handler);
2131
+ this.#node.insert(method, path7, handler);
2132
2132
  }
2133
- match(method, path3) {
2134
- return this.#node.search(method, path3);
2133
+ match(method, path7) {
2134
+ return this.#node.search(method, path7);
2135
2135
  }
2136
2136
  };
2137
2137
 
@@ -2150,12 +2150,22 @@ var Hono2 = class extends Hono {
2150
2150
  }
2151
2151
  };
2152
2152
 
2153
+ // src/server/createApp.ts
2154
+ import { contextMiddleware } from "@cloudwerk/core";
2155
+ import { setActiveRenderer, getAvailableRenderers } from "@cloudwerk/ui";
2156
+
2157
+ // src/server/registerRoutes.ts
2158
+ import * as path5 from "path";
2159
+ import { createHandlerAdapter, setRouteConfig, NotFoundError, RedirectError } from "@cloudwerk/core";
2160
+ import { render } from "@cloudwerk/ui";
2161
+
2153
2162
  // src/server/loadHandler.ts
2154
2163
  import * as fs from "fs";
2155
2164
  import * as path from "path";
2156
2165
  import { builtinModules } from "module";
2157
2166
  import { build } from "esbuild";
2158
2167
  import { pathToFileURL } from "url";
2168
+ import { validateRouteConfig } from "@cloudwerk/core";
2159
2169
  var moduleCache = /* @__PURE__ */ new Map();
2160
2170
  async function loadRouteHandler(absolutePath, verbose = false) {
2161
2171
  try {
@@ -2193,7 +2203,15 @@ async function loadRouteHandler(absolutePath, verbose = false) {
2193
2203
  const tempFile = path.join(tempDir, `.cloudwerk-route-${cacheKey}.mjs`);
2194
2204
  fs.writeFileSync(tempFile, code);
2195
2205
  try {
2196
- const module = await import(pathToFileURL(tempFile).href);
2206
+ const rawModule = await import(pathToFileURL(tempFile).href);
2207
+ let validatedConfig = void 0;
2208
+ if ("config" in rawModule) {
2209
+ validatedConfig = validateRouteConfig(rawModule.config, absolutePath);
2210
+ }
2211
+ const module = {
2212
+ ...rawModule,
2213
+ config: validatedConfig
2214
+ };
2197
2215
  moduleCache.set(absolutePath, { module, mtime });
2198
2216
  return module;
2199
2217
  } finally {
@@ -2220,6 +2238,318 @@ function findSafeTempDir(filePath) {
2220
2238
  return dir;
2221
2239
  }
2222
2240
 
2241
+ // src/server/loadMiddleware.ts
2242
+ import * as fs2 from "fs";
2243
+ import * as path2 from "path";
2244
+ import { builtinModules as builtinModules2 } from "module";
2245
+ import { build as build2 } from "esbuild";
2246
+ import { pathToFileURL as pathToFileURL2 } from "url";
2247
+ import { createMiddlewareAdapter } from "@cloudwerk/core";
2248
+ var middlewareCache = /* @__PURE__ */ new Map();
2249
+ async function loadMiddlewareModule(absolutePath, verbose = false) {
2250
+ if (!fs2.existsSync(absolutePath)) {
2251
+ if (verbose) {
2252
+ console.warn(`Middleware not found: ${absolutePath}`);
2253
+ }
2254
+ return null;
2255
+ }
2256
+ try {
2257
+ const stat = fs2.statSync(absolutePath);
2258
+ const mtime = stat.mtimeMs;
2259
+ const cached = middlewareCache.get(absolutePath);
2260
+ if (cached && cached.mtime === mtime) {
2261
+ return extractMiddleware(cached.module, absolutePath, verbose);
2262
+ }
2263
+ const nodeVersion = process.versions.node.split(".")[0];
2264
+ const target = `node${nodeVersion}`;
2265
+ const result = await build2({
2266
+ entryPoints: [absolutePath],
2267
+ bundle: true,
2268
+ write: false,
2269
+ format: "esm",
2270
+ platform: "node",
2271
+ target,
2272
+ external: [
2273
+ "@cloudwerk/core",
2274
+ "hono",
2275
+ // Use builtinModules for comprehensive Node.js built-in coverage
2276
+ ...builtinModules2,
2277
+ ...builtinModules2.map((m) => `node:${m}`)
2278
+ ],
2279
+ logLevel: verbose ? "warning" : "silent",
2280
+ sourcemap: "inline"
2281
+ });
2282
+ if (!result.outputFiles || result.outputFiles.length === 0) {
2283
+ throw new Error("No output from esbuild");
2284
+ }
2285
+ const cacheKey = `${Date.now()}-${Math.random().toString(36).slice(2)}`;
2286
+ const tempDir = findSafeTempDir2(absolutePath);
2287
+ const tempFile = path2.join(tempDir, `.cloudwerk-middleware-${cacheKey}.mjs`);
2288
+ fs2.writeFileSync(tempFile, result.outputFiles[0].text);
2289
+ try {
2290
+ const module = await import(pathToFileURL2(tempFile).href);
2291
+ middlewareCache.set(absolutePath, { module, mtime });
2292
+ return extractMiddleware(module, absolutePath, verbose);
2293
+ } finally {
2294
+ try {
2295
+ fs2.unlinkSync(tempFile);
2296
+ } catch {
2297
+ }
2298
+ }
2299
+ } catch (error) {
2300
+ const message = error instanceof Error ? error.message : String(error);
2301
+ console.error(`Failed to compile middleware at ${absolutePath}: ${message}`);
2302
+ return null;
2303
+ }
2304
+ }
2305
+ function extractMiddleware(module, absolutePath, verbose) {
2306
+ const middleware = module.default ?? module.middleware;
2307
+ if (!middleware) {
2308
+ if (verbose) {
2309
+ console.warn(
2310
+ `Middleware at ${absolutePath} must export a default function or named 'middleware' export`
2311
+ );
2312
+ }
2313
+ return null;
2314
+ }
2315
+ if (typeof middleware !== "function") {
2316
+ console.warn(
2317
+ `Middleware in ${absolutePath} must export a function, got ${typeof middleware}`
2318
+ );
2319
+ return null;
2320
+ }
2321
+ return createMiddlewareAdapter(middleware);
2322
+ }
2323
+ function findSafeTempDir2(filePath) {
2324
+ let dir = path2.dirname(filePath);
2325
+ const hasSpecialChars = (p) => /\[|\]|\(|\)/.test(path2.basename(p));
2326
+ while (hasSpecialChars(dir)) {
2327
+ const parent = path2.dirname(dir);
2328
+ if (parent === dir) {
2329
+ break;
2330
+ }
2331
+ dir = parent;
2332
+ }
2333
+ return dir;
2334
+ }
2335
+
2336
+ // src/server/loadPage.ts
2337
+ import * as fs3 from "fs";
2338
+ import * as path3 from "path";
2339
+ import { builtinModules as builtinModules3 } from "module";
2340
+ import { build as build3 } from "esbuild";
2341
+ import { pathToFileURL as pathToFileURL3 } from "url";
2342
+ import { validateRouteConfig as validateRouteConfig2 } from "@cloudwerk/core";
2343
+ var pageModuleCache = /* @__PURE__ */ new Map();
2344
+ async function loadPageModule(absolutePath, verbose = false) {
2345
+ try {
2346
+ const stat = fs3.statSync(absolutePath);
2347
+ const mtime = stat.mtimeMs;
2348
+ const cached = pageModuleCache.get(absolutePath);
2349
+ if (cached && cached.mtime === mtime) {
2350
+ return cached.module;
2351
+ }
2352
+ const nodeVersion = process.versions.node.split(".")[0];
2353
+ const target = `node${nodeVersion}`;
2354
+ const result = await build3({
2355
+ entryPoints: [absolutePath],
2356
+ bundle: true,
2357
+ write: false,
2358
+ format: "esm",
2359
+ platform: "node",
2360
+ target,
2361
+ jsx: "automatic",
2362
+ jsxImportSource: "hono/jsx",
2363
+ external: [
2364
+ "@cloudwerk/core",
2365
+ "@cloudwerk/ui",
2366
+ "hono",
2367
+ "hono/jsx",
2368
+ "hono/jsx/dom",
2369
+ "hono/jsx/streaming",
2370
+ "hono/html",
2371
+ // Use builtinModules for comprehensive Node.js built-in coverage
2372
+ ...builtinModules3,
2373
+ ...builtinModules3.map((m) => `node:${m}`)
2374
+ ],
2375
+ logLevel: verbose ? "warning" : "silent",
2376
+ sourcemap: "inline"
2377
+ });
2378
+ if (!result.outputFiles || result.outputFiles.length === 0) {
2379
+ throw new Error("No output from esbuild");
2380
+ }
2381
+ const code = result.outputFiles[0].text;
2382
+ const cacheKey = `${Date.now()}-${Math.random().toString(36).slice(2)}`;
2383
+ const tempDir = findSafeTempDir3(absolutePath);
2384
+ const tempFile = path3.join(tempDir, `.cloudwerk-page-${cacheKey}.mjs`);
2385
+ fs3.writeFileSync(tempFile, code);
2386
+ try {
2387
+ const rawModule = await import(pathToFileURL3(tempFile).href);
2388
+ if (!rawModule.default) {
2389
+ throw new Error("Page must have a default export");
2390
+ }
2391
+ if (typeof rawModule.default !== "function") {
2392
+ throw new Error(
2393
+ `Page default export must be a function (component), got ${typeof rawModule.default}`
2394
+ );
2395
+ }
2396
+ let validatedConfig = void 0;
2397
+ if ("config" in rawModule && rawModule.config !== void 0) {
2398
+ validatedConfig = validateRouteConfig2(rawModule.config, absolutePath);
2399
+ }
2400
+ let validatedLoader = void 0;
2401
+ if ("loader" in rawModule && rawModule.loader !== void 0) {
2402
+ if (typeof rawModule.loader !== "function") {
2403
+ throw new Error(
2404
+ `Page loader export must be a function, got ${typeof rawModule.loader}`
2405
+ );
2406
+ }
2407
+ validatedLoader = rawModule.loader;
2408
+ }
2409
+ const module = {
2410
+ default: rawModule.default,
2411
+ config: validatedConfig,
2412
+ loader: validatedLoader
2413
+ };
2414
+ pageModuleCache.set(absolutePath, { module, mtime });
2415
+ return module;
2416
+ } finally {
2417
+ try {
2418
+ fs3.unlinkSync(tempFile);
2419
+ } catch {
2420
+ }
2421
+ }
2422
+ } catch (error) {
2423
+ const message = error instanceof Error ? error.message : String(error);
2424
+ throw new Error(`Failed to compile page at ${absolutePath}: ${message}`);
2425
+ }
2426
+ }
2427
+ function findSafeTempDir3(filePath) {
2428
+ let dir = path3.dirname(filePath);
2429
+ const hasSpecialChars = (p) => /\[|\]|\(|\)/.test(path3.basename(p));
2430
+ while (hasSpecialChars(dir)) {
2431
+ const parent = path3.dirname(dir);
2432
+ if (parent === dir) {
2433
+ break;
2434
+ }
2435
+ dir = parent;
2436
+ }
2437
+ return dir;
2438
+ }
2439
+
2440
+ // src/server/loadLayout.ts
2441
+ import * as fs4 from "fs";
2442
+ import * as path4 from "path";
2443
+ import { builtinModules as builtinModules4 } from "module";
2444
+ import { build as build4 } from "esbuild";
2445
+ import { pathToFileURL as pathToFileURL4 } from "url";
2446
+ var layoutModuleCache = /* @__PURE__ */ new Map();
2447
+ async function loadLayoutModule(absolutePath, verbose = false) {
2448
+ try {
2449
+ const stat = fs4.statSync(absolutePath);
2450
+ const mtime = stat.mtimeMs;
2451
+ const cached = layoutModuleCache.get(absolutePath);
2452
+ if (cached && cached.mtime === mtime) {
2453
+ return cached.module;
2454
+ }
2455
+ const nodeVersion = process.versions.node.split(".")[0];
2456
+ const target = `node${nodeVersion}`;
2457
+ const result = await build4({
2458
+ entryPoints: [absolutePath],
2459
+ bundle: true,
2460
+ write: false,
2461
+ format: "esm",
2462
+ platform: "node",
2463
+ target,
2464
+ jsx: "automatic",
2465
+ jsxImportSource: "hono/jsx",
2466
+ external: [
2467
+ "@cloudwerk/core",
2468
+ "@cloudwerk/ui",
2469
+ "hono",
2470
+ "hono/jsx",
2471
+ "hono/jsx/dom",
2472
+ "hono/jsx/streaming",
2473
+ "hono/html",
2474
+ // Use builtinModules for comprehensive Node.js built-in coverage
2475
+ ...builtinModules4,
2476
+ ...builtinModules4.map((m) => `node:${m}`)
2477
+ ],
2478
+ logLevel: verbose ? "warning" : "silent",
2479
+ sourcemap: "inline"
2480
+ });
2481
+ if (!result.outputFiles || result.outputFiles.length === 0) {
2482
+ throw new Error("No output from esbuild");
2483
+ }
2484
+ const code = result.outputFiles[0].text;
2485
+ const cacheKey = `${Date.now()}-${Math.random().toString(36).slice(2)}`;
2486
+ const tempDir = findSafeTempDir4(absolutePath);
2487
+ const tempFile = path4.join(tempDir, `.cloudwerk-layout-${cacheKey}.mjs`);
2488
+ fs4.writeFileSync(tempFile, code);
2489
+ try {
2490
+ const rawModule = await import(pathToFileURL4(tempFile).href);
2491
+ if (!rawModule.default) {
2492
+ throw new Error("Layout must have a default export");
2493
+ }
2494
+ if (typeof rawModule.default !== "function") {
2495
+ throw new Error(
2496
+ `Layout default export must be a function (component), got ${typeof rawModule.default}`
2497
+ );
2498
+ }
2499
+ let validatedLoader = void 0;
2500
+ if ("loader" in rawModule && rawModule.loader !== void 0) {
2501
+ if (typeof rawModule.loader !== "function") {
2502
+ throw new Error(
2503
+ `Layout loader export must be a function, got ${typeof rawModule.loader}`
2504
+ );
2505
+ }
2506
+ validatedLoader = rawModule.loader;
2507
+ }
2508
+ const module = {
2509
+ default: rawModule.default,
2510
+ loader: validatedLoader
2511
+ };
2512
+ layoutModuleCache.set(absolutePath, { module, mtime });
2513
+ return module;
2514
+ } finally {
2515
+ try {
2516
+ fs4.unlinkSync(tempFile);
2517
+ } catch {
2518
+ }
2519
+ }
2520
+ } catch (error) {
2521
+ const message = error instanceof Error ? error.message : String(error);
2522
+ throw new Error(`Failed to compile layout at ${absolutePath}: ${message}`);
2523
+ }
2524
+ }
2525
+ function findSafeTempDir4(filePath) {
2526
+ let dir = path4.dirname(filePath);
2527
+ const hasSpecialChars = (p) => /\[|\]|\(|\)/.test(path4.basename(p));
2528
+ while (hasSpecialChars(dir)) {
2529
+ const parent = path4.dirname(dir);
2530
+ if (parent === dir) {
2531
+ break;
2532
+ }
2533
+ dir = parent;
2534
+ }
2535
+ return dir;
2536
+ }
2537
+
2538
+ // src/server/parseSearchParams.ts
2539
+ function parseSearchParams(c) {
2540
+ const result = {};
2541
+ const url = new URL(c.req.url);
2542
+ for (const [key, value] of url.searchParams.entries()) {
2543
+ const existing = result[key];
2544
+ if (existing !== void 0) {
2545
+ result[key] = Array.isArray(existing) ? [...existing, value] : [existing, value];
2546
+ } else {
2547
+ result[key] = value;
2548
+ }
2549
+ }
2550
+ return result;
2551
+ }
2552
+
2223
2553
  // src/server/registerRoutes.ts
2224
2554
  var HTTP_METHODS = [
2225
2555
  "GET",
@@ -2230,16 +2560,140 @@ var HTTP_METHODS = [
2230
2560
  "OPTIONS",
2231
2561
  "HEAD"
2232
2562
  ];
2563
+ function isCloudwerkHandler(fn) {
2564
+ return typeof fn === "function" && fn.length === 2;
2565
+ }
2566
+ function createConfigMiddleware(config) {
2567
+ return async (c, next) => {
2568
+ setRouteConfig(config);
2569
+ await next();
2570
+ };
2571
+ }
2572
+ async function executeLoader(loader, args, c) {
2573
+ try {
2574
+ const data = await Promise.resolve(loader(args));
2575
+ return { data: data ?? {} };
2576
+ } catch (error) {
2577
+ if (error instanceof NotFoundError) {
2578
+ return { response: await Promise.resolve(c.notFound()) };
2579
+ }
2580
+ if (error instanceof RedirectError) {
2581
+ return { response: c.redirect(error.url, error.status) };
2582
+ }
2583
+ throw error;
2584
+ }
2585
+ }
2233
2586
  async function registerRoutes(app, manifest, logger, verbose = false) {
2234
2587
  const registeredRoutes = [];
2235
2588
  for (const route of manifest.routes) {
2589
+ if (route.fileType === "page") {
2590
+ try {
2591
+ logger.debug(`Loading page: ${route.filePath}`);
2592
+ const pageModule = await loadPageModule(route.absolutePath, verbose);
2593
+ const PageComponent = pageModule.default;
2594
+ const layoutModules = await Promise.all(
2595
+ route.layouts.map((layoutPath) => loadLayoutModule(layoutPath, verbose))
2596
+ );
2597
+ const layouts = layoutModules.map((m) => m.default);
2598
+ for (const middlewarePath of route.middleware) {
2599
+ const middlewareHandler = await loadMiddlewareModule(middlewarePath, verbose);
2600
+ if (middlewareHandler) {
2601
+ app.use(route.urlPattern, middlewareHandler);
2602
+ if (verbose) {
2603
+ logger.info(
2604
+ `Applied middleware: ${path5.basename(middlewarePath)} -> ${route.urlPattern}`
2605
+ );
2606
+ }
2607
+ }
2608
+ }
2609
+ if (pageModule.config) {
2610
+ app.use(route.urlPattern, createConfigMiddleware(pageModule.config));
2611
+ if (verbose) {
2612
+ logger.info(`Applied page config: ${route.filePath} -> ${route.urlPattern}`);
2613
+ }
2614
+ }
2615
+ app.get(route.urlPattern, async (c) => {
2616
+ try {
2617
+ const params = c.req.param();
2618
+ const searchParams = parseSearchParams(c);
2619
+ const request = c.req.raw;
2620
+ const loaderArgs = { params, request, context: c };
2621
+ const layoutLoaderData = [];
2622
+ for (let index = 0; index < layoutModules.length; index++) {
2623
+ const layoutModule = layoutModules[index];
2624
+ if (layoutModule.loader) {
2625
+ const result = await executeLoader(layoutModule.loader, loaderArgs, c);
2626
+ if (result.response) {
2627
+ return result.response;
2628
+ }
2629
+ layoutLoaderData[index] = result.data;
2630
+ } else {
2631
+ layoutLoaderData[index] = {};
2632
+ }
2633
+ }
2634
+ let pageLoaderData = {};
2635
+ if (pageModule.loader) {
2636
+ const result = await executeLoader(pageModule.loader, loaderArgs, c);
2637
+ if (result.response) {
2638
+ return result.response;
2639
+ }
2640
+ pageLoaderData = result.data;
2641
+ }
2642
+ const pageProps = { params, searchParams, ...pageLoaderData };
2643
+ let element = await Promise.resolve(PageComponent(pageProps));
2644
+ for (let i = layouts.length - 1; i >= 0; i--) {
2645
+ const Layout = layouts[i];
2646
+ const layoutProps = {
2647
+ children: element,
2648
+ params,
2649
+ ...layoutLoaderData[i]
2650
+ };
2651
+ element = await Promise.resolve(Layout(layoutProps));
2652
+ }
2653
+ return render(element);
2654
+ } catch (error) {
2655
+ const message = error instanceof Error ? error.message : String(error);
2656
+ logger.error(`Error rendering page ${route.filePath}: ${message}`);
2657
+ return c.html(
2658
+ `<!DOCTYPE html><html><body><h1>Internal Server Error</h1></body></html>`,
2659
+ 500
2660
+ );
2661
+ }
2662
+ });
2663
+ registeredRoutes.push({
2664
+ method: "GET",
2665
+ pattern: route.urlPattern,
2666
+ filePath: route.filePath
2667
+ });
2668
+ logger.debug(`Registered page ${route.urlPattern}`);
2669
+ } catch (error) {
2670
+ const message = error instanceof Error ? error.message : String(error);
2671
+ logger.error(`Failed to load page ${route.filePath}: ${message}`);
2672
+ }
2673
+ continue;
2674
+ }
2236
2675
  if (route.fileType !== "route") {
2237
2676
  logger.debug(`Skipping non-route file: ${route.filePath}`);
2238
2677
  continue;
2239
2678
  }
2240
2679
  try {
2680
+ for (const middlewarePath of route.middleware) {
2681
+ const middlewareHandler = await loadMiddlewareModule(middlewarePath, verbose);
2682
+ if (middlewareHandler) {
2683
+ app.use(route.urlPattern, middlewareHandler);
2684
+ if (verbose) {
2685
+ logger.info(`Applied middleware: ${path5.basename(middlewarePath)} -> ${route.urlPattern}`);
2686
+ }
2687
+ }
2688
+ }
2241
2689
  logger.debug(`Loading route handler: ${route.filePath}`);
2242
2690
  const module = await loadRouteHandler(route.absolutePath, verbose);
2691
+ if (module.config) {
2692
+ app.use(route.urlPattern, createConfigMiddleware(module.config));
2693
+ if (verbose) {
2694
+ logger.info(`Applied route config: ${route.filePath} -> ${route.urlPattern}`);
2695
+ }
2696
+ }
2243
2697
  for (const method of HTTP_METHODS) {
2244
2698
  const handler = module[method];
2245
2699
  if (handler && typeof handler === "function") {
@@ -2260,7 +2714,7 @@ async function registerRoutes(app, manifest, logger, verbose = false) {
2260
2714
  return registeredRoutes;
2261
2715
  }
2262
2716
  function registerMethod(app, method, pattern, handler) {
2263
- const h = handler;
2717
+ const h = isCloudwerkHandler(handler) ? createHandlerAdapter(handler) : handler;
2264
2718
  switch (method) {
2265
2719
  case "GET":
2266
2720
  app.get(pattern, h);
@@ -2297,9 +2751,23 @@ var HTTP_STATUS = {
2297
2751
 
2298
2752
  // src/server/createApp.ts
2299
2753
  async function createApp(manifest, config, logger, verbose = false) {
2754
+ const rendererName = config.ui?.renderer ?? "hono-jsx";
2755
+ try {
2756
+ setActiveRenderer(rendererName);
2757
+ if (verbose) {
2758
+ logger.info(`Using UI renderer: ${rendererName}`);
2759
+ }
2760
+ } catch (error) {
2761
+ const available = getAvailableRenderers().join(", ");
2762
+ throw new Error(
2763
+ `Failed to initialize UI renderer "${rendererName}". Available renderers: ${available}.`,
2764
+ { cause: error }
2765
+ );
2766
+ }
2300
2767
  const app = new Hono2({
2301
2768
  strict: false
2302
2769
  });
2770
+ app.use("*", contextMiddleware());
2303
2771
  if (verbose) {
2304
2772
  app.use("*", async (c, next) => {
2305
2773
  const start = Date.now();
@@ -2350,8 +2818,8 @@ async function dev(pathArg, options) {
2350
2818
  const verbose = options.verbose ?? false;
2351
2819
  const logger = createLogger(verbose);
2352
2820
  try {
2353
- const cwd = pathArg ? path2.resolve(process.cwd(), pathArg) : process.cwd();
2354
- if (!fs2.existsSync(cwd)) {
2821
+ const cwd = pathArg ? path6.resolve(process.cwd(), pathArg) : process.cwd();
2822
+ if (!fs5.existsSync(cwd)) {
2355
2823
  throw new CliError(
2356
2824
  `Directory does not exist: ${cwd}`,
2357
2825
  "ENOENT",
@@ -2364,7 +2832,7 @@ async function dev(pathArg, options) {
2364
2832
  logger.debug(`Config loaded: routesDir=${config.routesDir}, extensions=${config.extensions.join(", ")}`);
2365
2833
  const routesDir = resolveRoutesDir(config, cwd);
2366
2834
  logger.debug(`Routes directory: ${routesDir}`);
2367
- if (!fs2.existsSync(routesDir)) {
2835
+ if (!fs5.existsSync(routesDir)) {
2368
2836
  throw new CliError(
2369
2837
  `Routes directory does not exist: ${routesDir}`,
2370
2838
  "ENOENT",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cloudwerk/cli",
3
- "version": "0.0.6",
3
+ "version": "0.1.1",
4
4
  "description": "Dev server, build, deploy commands for Cloudwerk",
5
5
  "repository": {
6
6
  "type": "git",
@@ -25,7 +25,8 @@
25
25
  "commander": "^12.1.0",
26
26
  "esbuild": "^0.25.0",
27
27
  "picocolors": "^1.1.0",
28
- "@cloudwerk/core": "^0.0.6"
28
+ "@cloudwerk/core": "^0.1.1",
29
+ "@cloudwerk/ui": "^0.1.1"
29
30
  },
30
31
  "devDependencies": {
31
32
  "@types/node": "^20.0.0",