@cloudwerk/cli 0.1.1 → 0.2.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 +520 -90
  2. package/package.json +2 -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 path6 from "path";
8
- import * as fs5 from "fs";
7
+ import * as path8 from "path";
8
+ import * as fs7 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, path7, status, duration) {
115
+ function logRequest(method, path9, 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("]") + " " + path7 + " " + statusColor(String(status)) + " " + pc.dim(`${duration}ms`)
119
+ pc.dim("[") + methodColor(method.padEnd(6)) + pc.dim("]") + " " + path9 + " " + 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 = (path7) => {
241
- const paths = path7.split("/");
240
+ var splitPath = (path9) => {
241
+ const paths = path9.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: path7 } = extractGroupsFromPath(routePath);
249
- const paths = splitPath(path7);
248
+ const { groups, path: path9 } = extractGroupsFromPath(routePath);
249
+ const paths = splitPath(path9);
250
250
  return replaceGroupMarks(paths, groups);
251
251
  };
252
- var extractGroupsFromPath = (path7) => {
252
+ var extractGroupsFromPath = (path9) => {
253
253
  const groups = [];
254
- path7 = path7.replace(/\{[^}]+\}/g, (match2, index) => {
254
+ path9 = path9.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: path7 };
259
+ return { groups, path: path9 };
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 path7 = url.slice(start, queryIndex === -1 ? void 0 : queryIndex);
315
- return tryDecodeURI(path7.includes("%25") ? path7.replace(/%25/g, "%2525") : path7);
314
+ const path9 = url.slice(start, queryIndex === -1 ? void 0 : queryIndex);
315
+ return tryDecodeURI(path9.includes("%25") ? path9.replace(/%25/g, "%2525") : path9);
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 = (path7) => {
333
- if (path7.charCodeAt(path7.length - 1) !== 63 || !path7.includes(":")) {
332
+ var checkOptionalParameter = (path9) => {
333
+ if (path9.charCodeAt(path9.length - 1) !== 63 || !path9.includes(":")) {
334
334
  return null;
335
335
  }
336
- const segments = path7.split("/");
336
+ const segments = path9.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, path7 = "/", matchResult = [[]]) {
477
+ constructor(request, path9 = "/", matchResult = [[]]) {
478
478
  this.raw = request;
479
- this.path = path7;
479
+ this.path = path9;
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, path7, ...handlers) => {
1216
- for (const p of [path7].flat()) {
1215
+ this.on = (method, path9, ...handlers) => {
1216
+ for (const p of [path9].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(path7, app) {
1274
- const subApp = this.basePath(path7);
1273
+ route(path9, app) {
1274
+ const subApp = this.basePath(path9);
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(path7) {
1300
+ basePath(path9) {
1301
1301
  const subApp = this.#clone();
1302
- subApp._basePath = mergePath(this._basePath, path7);
1302
+ subApp._basePath = mergePath(this._basePath, path9);
1303
1303
  return subApp;
1304
1304
  }
1305
1305
  /**
@@ -1373,7 +1373,7 @@ var Hono = class _Hono {
1373
1373
  * })
1374
1374
  * ```
1375
1375
  */
1376
- mount(path7, applicationHandler, options) {
1376
+ mount(path9, 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, path7);
1403
+ const mergedPath = mergePath(this._basePath, path9);
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(path7, "*"), handler);
1418
+ this.#addRoute(METHOD_NAME_ALL, mergePath(path9, "*"), handler);
1419
1419
  return this;
1420
1420
  }
1421
- #addRoute(method, path7, handler) {
1421
+ #addRoute(method, path9, handler) {
1422
1422
  method = method.toUpperCase();
1423
- path7 = mergePath(this._basePath, path7);
1424
- const r = { basePath: this._basePath, path: path7, method, handler };
1425
- this.router.add(method, path7, [handler, r]);
1423
+ path9 = mergePath(this._basePath, path9);
1424
+ const r = { basePath: this._basePath, path: path9, method, handler };
1425
+ this.router.add(method, path9, [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 path7 = this.getPath(request, { env });
1439
- const matchResult = this.router.match(method, path7);
1438
+ const path9 = this.getPath(request, { env });
1439
+ const matchResult = this.router.match(method, path9);
1440
1440
  const c = new Context(request, {
1441
- path: path7,
1441
+ path: path9,
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, path7) {
1541
+ function match(method, path9) {
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, path7) {
1554
1554
  return [matcher[1][index], match3];
1555
1555
  });
1556
1556
  this.match = match2;
1557
- return match2(method, path7);
1557
+ return match2(method, path9);
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(path7, index, pathErrorCheckOnly) {
1672
+ insert(path9, index, pathErrorCheckOnly) {
1673
1673
  const paramAssoc = [];
1674
1674
  const groups = [];
1675
1675
  for (let i = 0; ; ) {
1676
1676
  let replaced = false;
1677
- path7 = path7.replace(/\{[^}]+\}/g, (m) => {
1677
+ path9 = path9.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 = path7.match(/(?::[^\/]+)|(?:\/\*$)|./g) || [];
1688
+ const tokens = path9.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(path7) {
1728
- return wildcardRegExpCache[path7] ??= new RegExp(
1729
- path7 === "*" ? "" : `^${path7.replace(
1727
+ function buildWildcardRegExp(path9) {
1728
+ return wildcardRegExpCache[path9] ??= new RegExp(
1729
+ path9 === "*" ? "" : `^${path9.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, path7, handlers] = routesWithStaticPathFlag[i];
1751
+ const [pathErrorCheckOnly, path9, handlers] = routesWithStaticPathFlag[i];
1752
1752
  if (pathErrorCheckOnly) {
1753
- staticMap[path7] = [handlers.map(([h]) => [h, /* @__PURE__ */ Object.create(null)]), emptyParam];
1753
+ staticMap[path9] = [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(path7, j, pathErrorCheckOnly);
1759
+ paramAssoc = trie.insert(path9, j, pathErrorCheckOnly);
1760
1760
  } catch (e) {
1761
- throw e === PATH_ERROR ? new UnsupportedPathError(path7) : e;
1761
+ throw e === PATH_ERROR ? new UnsupportedPathError(path9) : 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, path7) {
1795
+ function findMiddleware(middleware, path9) {
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(path7)) {
1800
+ if (buildWildcardRegExp(k).test(path9)) {
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, path7, handler) {
1814
+ add(method, path9, 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 (path7 === "/*") {
1830
- path7 = "*";
1829
+ if (path9 === "/*") {
1830
+ path9 = "*";
1831
1831
  }
1832
- const paramCount = (path7.match(/\/:/g) || []).length;
1833
- if (/\*$/.test(path7)) {
1834
- const re = buildWildcardRegExp(path7);
1832
+ const paramCount = (path9.match(/\/:/g) || []).length;
1833
+ if (/\*$/.test(path9)) {
1834
+ const re = buildWildcardRegExp(path9);
1835
1835
  if (method === METHOD_NAME_ALL) {
1836
1836
  Object.keys(middleware).forEach((m) => {
1837
- middleware[m][path7] ||= findMiddleware(middleware[m], path7) || findMiddleware(middleware[METHOD_NAME_ALL], path7) || [];
1837
+ middleware[m][path9] ||= findMiddleware(middleware[m], path9) || findMiddleware(middleware[METHOD_NAME_ALL], path9) || [];
1838
1838
  });
1839
1839
  } else {
1840
- middleware[method][path7] ||= findMiddleware(middleware[method], path7) || findMiddleware(middleware[METHOD_NAME_ALL], path7) || [];
1840
+ middleware[method][path9] ||= findMiddleware(middleware[method], path9) || findMiddleware(middleware[METHOD_NAME_ALL], path9) || [];
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(path7) || [path7];
1858
+ const paths = checkOptionalParameter(path9) || [path9];
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((path7) => [path7, r[method][path7]]) : [];
1885
+ const ownRoute = r[method] ? Object.keys(r[method]).map((path9) => [path9, r[method][path9]]) : [];
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((path7) => [path7, r[METHOD_NAME_ALL][path7]])
1891
+ ...Object.keys(r[METHOD_NAME_ALL]).map((path9) => [path9, r[METHOD_NAME_ALL][path9]])
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, path7, handler) {
1911
+ add(method, path9, handler) {
1912
1912
  if (!this.#routes) {
1913
1913
  throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
1914
1914
  }
1915
- this.#routes.push([method, path7, handler]);
1915
+ this.#routes.push([method, path9, handler]);
1916
1916
  }
1917
- match(method, path7) {
1917
+ match(method, path9) {
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, path7);
1932
+ res = router.match(method, path9);
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, path7, handler) {
1976
+ insert(method, path9, handler) {
1977
1977
  this.#order = ++this.#order;
1978
1978
  let curNode = this;
1979
- const parts = splitRoutingPath(path7);
1979
+ const parts = splitRoutingPath(path9);
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, path7) {
2030
+ search(method, path9) {
2031
2031
  const handlerSets = [];
2032
2032
  this.#params = emptyParams;
2033
2033
  const curNode = this;
2034
2034
  let curNodes = [curNode];
2035
- const parts = splitPath(path7);
2035
+ const parts = splitPath(path9);
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, path7, handler) {
2124
- const results = checkOptionalParameter(path7);
2123
+ add(method, path9, handler) {
2124
+ const results = checkOptionalParameter(path9);
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, path7, handler);
2131
+ this.#node.insert(method, path9, handler);
2132
2132
  }
2133
- match(method, path7) {
2134
- return this.#node.search(method, path7);
2133
+ match(method, path9) {
2134
+ return this.#node.search(method, path9);
2135
2135
  }
2136
2136
  };
2137
2137
 
@@ -2155,8 +2155,15 @@ import { contextMiddleware } from "@cloudwerk/core";
2155
2155
  import { setActiveRenderer, getAvailableRenderers } from "@cloudwerk/ui";
2156
2156
 
2157
2157
  // src/server/registerRoutes.ts
2158
- import * as path5 from "path";
2159
- import { createHandlerAdapter, setRouteConfig, NotFoundError, RedirectError } from "@cloudwerk/core";
2158
+ import * as path7 from "path";
2159
+ import {
2160
+ createHandlerAdapter,
2161
+ setRouteConfig,
2162
+ NotFoundError,
2163
+ RedirectError,
2164
+ resolveErrorBoundary,
2165
+ resolveNotFoundBoundary
2166
+ } from "@cloudwerk/core";
2160
2167
  import { render } from "@cloudwerk/ui";
2161
2168
 
2162
2169
  // src/server/loadHandler.ts
@@ -2406,10 +2413,33 @@ async function loadPageModule(absolutePath, verbose = false) {
2406
2413
  }
2407
2414
  validatedLoader = rawModule.loader;
2408
2415
  }
2416
+ let validatedAction = void 0;
2417
+ if ("action" in rawModule && rawModule.action !== void 0) {
2418
+ if (typeof rawModule.action !== "function") {
2419
+ throw new Error(
2420
+ `Page action export must be a function, got ${typeof rawModule.action}`
2421
+ );
2422
+ }
2423
+ validatedAction = rawModule.action;
2424
+ }
2425
+ const actionMethods = ["POST", "PUT", "PATCH", "DELETE"];
2426
+ const validatedMethods = {};
2427
+ for (const method of actionMethods) {
2428
+ if (method in rawModule && rawModule[method] !== void 0) {
2429
+ if (typeof rawModule[method] !== "function") {
2430
+ throw new Error(
2431
+ `Page ${method} export must be a function, got ${typeof rawModule[method]}`
2432
+ );
2433
+ }
2434
+ validatedMethods[method] = rawModule[method];
2435
+ }
2436
+ }
2409
2437
  const module = {
2410
2438
  default: rawModule.default,
2411
2439
  config: validatedConfig,
2412
- loader: validatedLoader
2440
+ loader: validatedLoader,
2441
+ action: validatedAction,
2442
+ ...validatedMethods
2413
2443
  };
2414
2444
  pageModuleCache.set(absolutePath, { module, mtime });
2415
2445
  return module;
@@ -2535,6 +2565,202 @@ function findSafeTempDir4(filePath) {
2535
2565
  return dir;
2536
2566
  }
2537
2567
 
2568
+ // src/server/loadErrorBoundary.ts
2569
+ import * as fs5 from "fs";
2570
+ import * as path5 from "path";
2571
+ import { builtinModules as builtinModules5 } from "module";
2572
+ import { build as build5 } from "esbuild";
2573
+ import { pathToFileURL as pathToFileURL5 } from "url";
2574
+ var errorBoundaryModuleCache = /* @__PURE__ */ new Map();
2575
+ async function loadErrorBoundaryModule(absolutePath, verbose = false) {
2576
+ try {
2577
+ const stat = fs5.statSync(absolutePath);
2578
+ const mtime = stat.mtimeMs;
2579
+ const cached = errorBoundaryModuleCache.get(absolutePath);
2580
+ if (cached && cached.mtime === mtime) {
2581
+ return cached.module;
2582
+ }
2583
+ const nodeVersion = process.versions.node.split(".")[0];
2584
+ const target = `node${nodeVersion}`;
2585
+ const result = await build5({
2586
+ entryPoints: [absolutePath],
2587
+ bundle: true,
2588
+ write: false,
2589
+ format: "esm",
2590
+ platform: "node",
2591
+ target,
2592
+ jsx: "automatic",
2593
+ jsxImportSource: "hono/jsx",
2594
+ external: [
2595
+ "@cloudwerk/core",
2596
+ "@cloudwerk/ui",
2597
+ "hono",
2598
+ "hono/jsx",
2599
+ "hono/jsx/dom",
2600
+ "hono/jsx/streaming",
2601
+ "hono/html",
2602
+ // Use builtinModules for comprehensive Node.js built-in coverage
2603
+ ...builtinModules5,
2604
+ ...builtinModules5.map((m) => `node:${m}`)
2605
+ ],
2606
+ logLevel: verbose ? "warning" : "silent",
2607
+ sourcemap: "inline"
2608
+ });
2609
+ if (!result.outputFiles || result.outputFiles.length === 0) {
2610
+ throw new Error("No output from esbuild");
2611
+ }
2612
+ const code = result.outputFiles[0].text;
2613
+ const cacheKey = `${Date.now()}-${Math.random().toString(36).slice(2)}`;
2614
+ const tempDir = findSafeTempDir5(absolutePath);
2615
+ const tempFile = path5.join(tempDir, `.cloudwerk-error-${cacheKey}.mjs`);
2616
+ fs5.writeFileSync(tempFile, code);
2617
+ try {
2618
+ const rawModule = await import(pathToFileURL5(tempFile).href);
2619
+ if (!rawModule.default) {
2620
+ throw new Error("Error boundary must have a default export");
2621
+ }
2622
+ if (typeof rawModule.default !== "function") {
2623
+ throw new Error(
2624
+ `Error boundary default export must be a function (component), got ${typeof rawModule.default}`
2625
+ );
2626
+ }
2627
+ let validatedLoader = void 0;
2628
+ if ("loader" in rawModule && rawModule.loader !== void 0) {
2629
+ if (typeof rawModule.loader !== "function") {
2630
+ throw new Error(
2631
+ `Error boundary loader export must be a function, got ${typeof rawModule.loader}`
2632
+ );
2633
+ }
2634
+ validatedLoader = rawModule.loader;
2635
+ }
2636
+ const module = {
2637
+ default: rawModule.default,
2638
+ loader: validatedLoader
2639
+ };
2640
+ errorBoundaryModuleCache.set(absolutePath, { module, mtime });
2641
+ return module;
2642
+ } finally {
2643
+ try {
2644
+ fs5.unlinkSync(tempFile);
2645
+ } catch {
2646
+ }
2647
+ }
2648
+ } catch (error) {
2649
+ const message = error instanceof Error ? error.message : String(error);
2650
+ throw new Error(`Failed to compile error boundary at ${absolutePath}: ${message}`);
2651
+ }
2652
+ }
2653
+ function findSafeTempDir5(filePath) {
2654
+ let dir = path5.dirname(filePath);
2655
+ const hasSpecialChars = (p) => /\[|\]|\(|\)/.test(path5.basename(p));
2656
+ while (hasSpecialChars(dir)) {
2657
+ const parent = path5.dirname(dir);
2658
+ if (parent === dir) {
2659
+ break;
2660
+ }
2661
+ dir = parent;
2662
+ }
2663
+ return dir;
2664
+ }
2665
+
2666
+ // src/server/loadNotFound.ts
2667
+ import * as fs6 from "fs";
2668
+ import * as path6 from "path";
2669
+ import { builtinModules as builtinModules6 } from "module";
2670
+ import { build as build6 } from "esbuild";
2671
+ import { pathToFileURL as pathToFileURL6 } from "url";
2672
+ var notFoundModuleCache = /* @__PURE__ */ new Map();
2673
+ async function loadNotFoundModule(absolutePath, verbose = false) {
2674
+ try {
2675
+ const stat = fs6.statSync(absolutePath);
2676
+ const mtime = stat.mtimeMs;
2677
+ const cached = notFoundModuleCache.get(absolutePath);
2678
+ if (cached && cached.mtime === mtime) {
2679
+ return cached.module;
2680
+ }
2681
+ const nodeVersion = process.versions.node.split(".")[0];
2682
+ const target = `node${nodeVersion}`;
2683
+ const result = await build6({
2684
+ entryPoints: [absolutePath],
2685
+ bundle: true,
2686
+ write: false,
2687
+ format: "esm",
2688
+ platform: "node",
2689
+ target,
2690
+ jsx: "automatic",
2691
+ jsxImportSource: "hono/jsx",
2692
+ external: [
2693
+ "@cloudwerk/core",
2694
+ "@cloudwerk/ui",
2695
+ "hono",
2696
+ "hono/jsx",
2697
+ "hono/jsx/dom",
2698
+ "hono/jsx/streaming",
2699
+ "hono/html",
2700
+ // Use builtinModules for comprehensive Node.js built-in coverage
2701
+ ...builtinModules6,
2702
+ ...builtinModules6.map((m) => `node:${m}`)
2703
+ ],
2704
+ logLevel: verbose ? "warning" : "silent",
2705
+ sourcemap: "inline"
2706
+ });
2707
+ if (!result.outputFiles || result.outputFiles.length === 0) {
2708
+ throw new Error("No output from esbuild");
2709
+ }
2710
+ const code = result.outputFiles[0].text;
2711
+ const cacheKey = `${Date.now()}-${Math.random().toString(36).slice(2)}`;
2712
+ const tempDir = findSafeTempDir6(absolutePath);
2713
+ const tempFile = path6.join(tempDir, `.cloudwerk-not-found-${cacheKey}.mjs`);
2714
+ fs6.writeFileSync(tempFile, code);
2715
+ try {
2716
+ const rawModule = await import(pathToFileURL6(tempFile).href);
2717
+ if (!rawModule.default) {
2718
+ throw new Error("Not-found boundary must have a default export");
2719
+ }
2720
+ if (typeof rawModule.default !== "function") {
2721
+ throw new Error(
2722
+ `Not-found boundary default export must be a function (component), got ${typeof rawModule.default}`
2723
+ );
2724
+ }
2725
+ let validatedLoader = void 0;
2726
+ if ("loader" in rawModule && rawModule.loader !== void 0) {
2727
+ if (typeof rawModule.loader !== "function") {
2728
+ throw new Error(
2729
+ `Not-found boundary loader export must be a function, got ${typeof rawModule.loader}`
2730
+ );
2731
+ }
2732
+ validatedLoader = rawModule.loader;
2733
+ }
2734
+ const module = {
2735
+ default: rawModule.default,
2736
+ loader: validatedLoader
2737
+ };
2738
+ notFoundModuleCache.set(absolutePath, { module, mtime });
2739
+ return module;
2740
+ } finally {
2741
+ try {
2742
+ fs6.unlinkSync(tempFile);
2743
+ } catch {
2744
+ }
2745
+ }
2746
+ } catch (error) {
2747
+ const message = error instanceof Error ? error.message : String(error);
2748
+ throw new Error(`Failed to compile not-found boundary at ${absolutePath}: ${message}`);
2749
+ }
2750
+ }
2751
+ function findSafeTempDir6(filePath) {
2752
+ let dir = path6.dirname(filePath);
2753
+ const hasSpecialChars = (p) => /\[|\]|\(|\)/.test(path6.basename(p));
2754
+ while (hasSpecialChars(dir)) {
2755
+ const parent = path6.dirname(dir);
2756
+ if (parent === dir) {
2757
+ break;
2758
+ }
2759
+ dir = parent;
2760
+ }
2761
+ return dir;
2762
+ }
2763
+
2538
2764
  // src/server/parseSearchParams.ts
2539
2765
  function parseSearchParams(c) {
2540
2766
  const result = {};
@@ -2574,16 +2800,27 @@ async function executeLoader(loader, args, c) {
2574
2800
  const data = await Promise.resolve(loader(args));
2575
2801
  return { data: data ?? {} };
2576
2802
  } catch (error) {
2577
- if (error instanceof NotFoundError) {
2578
- return { response: await Promise.resolve(c.notFound()) };
2803
+ if (error instanceof RedirectError) {
2804
+ return { response: c.redirect(error.url, error.status) };
2579
2805
  }
2806
+ throw error;
2807
+ }
2808
+ }
2809
+ async function executeAction(action, args, c) {
2810
+ try {
2811
+ const result = await Promise.resolve(action(args));
2812
+ if (result instanceof Response) {
2813
+ return { response: result };
2814
+ }
2815
+ return { data: result ?? {} };
2816
+ } catch (error) {
2580
2817
  if (error instanceof RedirectError) {
2581
2818
  return { response: c.redirect(error.url, error.status) };
2582
2819
  }
2583
2820
  throw error;
2584
2821
  }
2585
2822
  }
2586
- async function registerRoutes(app, manifest, logger, verbose = false) {
2823
+ async function registerRoutes(app, manifest, scanResult, logger, verbose = false) {
2587
2824
  const registeredRoutes = [];
2588
2825
  for (const route of manifest.routes) {
2589
2826
  if (route.fileType === "page") {
@@ -2601,7 +2838,7 @@ async function registerRoutes(app, manifest, logger, verbose = false) {
2601
2838
  app.use(route.urlPattern, middlewareHandler);
2602
2839
  if (verbose) {
2603
2840
  logger.info(
2604
- `Applied middleware: ${path5.basename(middlewarePath)} -> ${route.urlPattern}`
2841
+ `Applied middleware: ${path7.basename(middlewarePath)} -> ${route.urlPattern}`
2605
2842
  );
2606
2843
  }
2607
2844
  }
@@ -2613,12 +2850,12 @@ async function registerRoutes(app, manifest, logger, verbose = false) {
2613
2850
  }
2614
2851
  }
2615
2852
  app.get(route.urlPattern, async (c) => {
2853
+ const params = c.req.param();
2854
+ const searchParams = parseSearchParams(c);
2855
+ const request = c.req.raw;
2856
+ const layoutLoaderData = [];
2616
2857
  try {
2617
- const params = c.req.param();
2618
- const searchParams = parseSearchParams(c);
2619
- const request = c.req.raw;
2620
2858
  const loaderArgs = { params, request, context: c };
2621
- const layoutLoaderData = [];
2622
2859
  for (let index = 0; index < layoutModules.length; index++) {
2623
2860
  const layoutModule = layoutModules[index];
2624
2861
  if (layoutModule.loader) {
@@ -2652,6 +2889,67 @@ async function registerRoutes(app, manifest, logger, verbose = false) {
2652
2889
  }
2653
2890
  return render(element);
2654
2891
  } catch (error) {
2892
+ if (error instanceof NotFoundError) {
2893
+ const notFoundPath = resolveNotFoundBoundary(route.filePath, scanResult.notFound);
2894
+ if (notFoundPath) {
2895
+ try {
2896
+ const notFoundModule = await loadNotFoundModule(notFoundPath, verbose);
2897
+ const NotFoundComponent = notFoundModule.default;
2898
+ const notFoundProps = { params, searchParams };
2899
+ let notFoundElement = await Promise.resolve(NotFoundComponent(notFoundProps));
2900
+ for (let i = layouts.length - 1; i >= 0; i--) {
2901
+ const Layout = layouts[i];
2902
+ const layoutProps = {
2903
+ children: notFoundElement,
2904
+ params,
2905
+ ...layoutLoaderData[i]
2906
+ };
2907
+ notFoundElement = await Promise.resolve(Layout(layoutProps));
2908
+ }
2909
+ return render(notFoundElement, { status: 404 });
2910
+ } catch (boundaryError) {
2911
+ const boundaryMessage = boundaryError instanceof Error ? boundaryError.message : String(boundaryError);
2912
+ logger.error(`Not-found boundary failed: ${boundaryMessage}`);
2913
+ }
2914
+ }
2915
+ return c.notFound();
2916
+ }
2917
+ const errorPath = resolveErrorBoundary(route.filePath, scanResult.errors);
2918
+ if (errorPath) {
2919
+ try {
2920
+ const errorModule = await loadErrorBoundaryModule(errorPath, verbose);
2921
+ const ErrorComponent = errorModule.default;
2922
+ const digest = crypto.randomUUID().slice(0, 8);
2923
+ const originalMessage = error instanceof Error ? error.message : String(error);
2924
+ logger.error(`Error [${digest}] in ${route.filePath}: ${originalMessage}`);
2925
+ const sanitizedError = process.env.NODE_ENV === "production" ? Object.assign(new Error("An error occurred"), { digest }) : Object.assign(
2926
+ error instanceof Error ? error : new Error(String(error)),
2927
+ { digest }
2928
+ );
2929
+ const errorProps = {
2930
+ error: sanitizedError,
2931
+ errorType: "loader",
2932
+ reset: () => {
2933
+ },
2934
+ params,
2935
+ searchParams
2936
+ };
2937
+ let errorElement = await Promise.resolve(ErrorComponent(errorProps));
2938
+ for (let i = layouts.length - 1; i >= 0; i--) {
2939
+ const Layout = layouts[i];
2940
+ const layoutProps = {
2941
+ children: errorElement,
2942
+ params,
2943
+ ...layoutLoaderData[i]
2944
+ };
2945
+ errorElement = await Promise.resolve(Layout(layoutProps));
2946
+ }
2947
+ return render(errorElement, { status: 500 });
2948
+ } catch (boundaryError) {
2949
+ const boundaryMessage = boundaryError instanceof Error ? boundaryError.message : String(boundaryError);
2950
+ logger.error(`Error boundary failed: ${boundaryMessage}`);
2951
+ }
2952
+ }
2655
2953
  const message = error instanceof Error ? error.message : String(error);
2656
2954
  logger.error(`Error rendering page ${route.filePath}: ${message}`);
2657
2955
  return c.html(
@@ -2666,6 +2964,138 @@ async function registerRoutes(app, manifest, logger, verbose = false) {
2666
2964
  filePath: route.filePath
2667
2965
  });
2668
2966
  logger.debug(`Registered page ${route.urlPattern}`);
2967
+ const actionMethods = ["POST", "PUT", "PATCH", "DELETE"];
2968
+ for (const method of actionMethods) {
2969
+ const action = pageModule[method] ?? pageModule.action;
2970
+ if (action && typeof action === "function") {
2971
+ const actionFn = action;
2972
+ registerMethod(app, method, route.urlPattern, async (c) => {
2973
+ const params = c.req.param();
2974
+ const searchParams = parseSearchParams(c);
2975
+ const request = c.req.raw;
2976
+ const layoutLoaderData = [];
2977
+ try {
2978
+ const actionArgs = { params, request, context: c };
2979
+ const actionResult = await executeAction(actionFn, actionArgs, c);
2980
+ if (actionResult.response) {
2981
+ return actionResult.response;
2982
+ }
2983
+ const loaderArgs = { params, request, context: c };
2984
+ for (let index = 0; index < layoutModules.length; index++) {
2985
+ const layoutModule = layoutModules[index];
2986
+ if (layoutModule.loader) {
2987
+ const result = await executeLoader(layoutModule.loader, loaderArgs, c);
2988
+ if (result.response) {
2989
+ return result.response;
2990
+ }
2991
+ layoutLoaderData[index] = result.data;
2992
+ } else {
2993
+ layoutLoaderData[index] = {};
2994
+ }
2995
+ }
2996
+ let pageLoaderData = {};
2997
+ if (pageModule.loader) {
2998
+ const result = await executeLoader(pageModule.loader, loaderArgs, c);
2999
+ if (result.response) {
3000
+ return result.response;
3001
+ }
3002
+ pageLoaderData = result.data;
3003
+ }
3004
+ const pageProps = {
3005
+ params,
3006
+ searchParams,
3007
+ actionData: actionResult.data,
3008
+ ...pageLoaderData
3009
+ };
3010
+ let element = await Promise.resolve(PageComponent(pageProps));
3011
+ for (let i = layouts.length - 1; i >= 0; i--) {
3012
+ const Layout = layouts[i];
3013
+ const layoutProps = {
3014
+ children: element,
3015
+ params,
3016
+ ...layoutLoaderData[i]
3017
+ };
3018
+ element = await Promise.resolve(Layout(layoutProps));
3019
+ }
3020
+ return render(element);
3021
+ } catch (error) {
3022
+ if (error instanceof NotFoundError) {
3023
+ const notFoundPath = resolveNotFoundBoundary(route.filePath, scanResult.notFound);
3024
+ if (notFoundPath) {
3025
+ try {
3026
+ const notFoundModule = await loadNotFoundModule(notFoundPath, verbose);
3027
+ const NotFoundComponent = notFoundModule.default;
3028
+ const notFoundProps = { params, searchParams };
3029
+ let notFoundElement = await Promise.resolve(NotFoundComponent(notFoundProps));
3030
+ for (let i = layouts.length - 1; i >= 0; i--) {
3031
+ const Layout = layouts[i];
3032
+ const layoutProps = {
3033
+ children: notFoundElement,
3034
+ params,
3035
+ ...layoutLoaderData[i]
3036
+ };
3037
+ notFoundElement = await Promise.resolve(Layout(layoutProps));
3038
+ }
3039
+ return render(notFoundElement, { status: 404 });
3040
+ } catch (boundaryError) {
3041
+ const boundaryMessage = boundaryError instanceof Error ? boundaryError.message : String(boundaryError);
3042
+ logger.error(`Not-found boundary failed: ${boundaryMessage}`);
3043
+ }
3044
+ }
3045
+ return c.notFound();
3046
+ }
3047
+ const errorPath = resolveErrorBoundary(route.filePath, scanResult.errors);
3048
+ if (errorPath) {
3049
+ try {
3050
+ const errorModule = await loadErrorBoundaryModule(errorPath, verbose);
3051
+ const ErrorComponent = errorModule.default;
3052
+ const digest = crypto.randomUUID().slice(0, 8);
3053
+ const originalMessage = error instanceof Error ? error.message : String(error);
3054
+ logger.error(`Error [${digest}] in ${route.filePath} action: ${originalMessage}`);
3055
+ const sanitizedError = process.env.NODE_ENV === "production" ? Object.assign(new Error("An error occurred"), { digest }) : Object.assign(
3056
+ error instanceof Error ? error : new Error(String(error)),
3057
+ { digest }
3058
+ );
3059
+ const errorProps = {
3060
+ error: sanitizedError,
3061
+ errorType: "action",
3062
+ reset: () => {
3063
+ },
3064
+ params,
3065
+ searchParams
3066
+ };
3067
+ let errorElement = await Promise.resolve(ErrorComponent(errorProps));
3068
+ for (let i = layouts.length - 1; i >= 0; i--) {
3069
+ const Layout = layouts[i];
3070
+ const layoutProps = {
3071
+ children: errorElement,
3072
+ params,
3073
+ ...layoutLoaderData[i]
3074
+ };
3075
+ errorElement = await Promise.resolve(Layout(layoutProps));
3076
+ }
3077
+ return render(errorElement, { status: 500 });
3078
+ } catch (boundaryError) {
3079
+ const boundaryMessage = boundaryError instanceof Error ? boundaryError.message : String(boundaryError);
3080
+ logger.error(`Error boundary failed: ${boundaryMessage}`);
3081
+ }
3082
+ }
3083
+ const message = error instanceof Error ? error.message : String(error);
3084
+ logger.error(`Error executing action ${route.filePath}: ${message}`);
3085
+ return c.html(
3086
+ `<!DOCTYPE html><html><body><h1>Internal Server Error</h1></body></html>`,
3087
+ 500
3088
+ );
3089
+ }
3090
+ });
3091
+ registeredRoutes.push({
3092
+ method,
3093
+ pattern: route.urlPattern,
3094
+ filePath: route.filePath
3095
+ });
3096
+ logger.debug(`Registered ${method} action ${route.urlPattern}`);
3097
+ }
3098
+ }
2669
3099
  } catch (error) {
2670
3100
  const message = error instanceof Error ? error.message : String(error);
2671
3101
  logger.error(`Failed to load page ${route.filePath}: ${message}`);
@@ -2682,7 +3112,7 @@ async function registerRoutes(app, manifest, logger, verbose = false) {
2682
3112
  if (middlewareHandler) {
2683
3113
  app.use(route.urlPattern, middlewareHandler);
2684
3114
  if (verbose) {
2685
- logger.info(`Applied middleware: ${path5.basename(middlewarePath)} -> ${route.urlPattern}`);
3115
+ logger.info(`Applied middleware: ${path7.basename(middlewarePath)} -> ${route.urlPattern}`);
2686
3116
  }
2687
3117
  }
2688
3118
  }
@@ -2750,7 +3180,7 @@ var HTTP_STATUS = {
2750
3180
  };
2751
3181
 
2752
3182
  // src/server/createApp.ts
2753
- async function createApp(manifest, config, logger, verbose = false) {
3183
+ async function createApp(manifest, scanResult, config, logger, verbose = false) {
2754
3184
  const rendererName = config.ui?.renderer ?? "hono-jsx";
2755
3185
  try {
2756
3186
  setActiveRenderer(rendererName);
@@ -2781,7 +3211,7 @@ async function createApp(manifest, config, logger, verbose = false) {
2781
3211
  app.use("*", middleware);
2782
3212
  }
2783
3213
  }
2784
- const routes = await registerRoutes(app, manifest, logger, verbose);
3214
+ const routes = await registerRoutes(app, manifest, scanResult, logger, verbose);
2785
3215
  app.notFound((c) => {
2786
3216
  return c.json(
2787
3217
  {
@@ -2818,8 +3248,8 @@ async function dev(pathArg, options) {
2818
3248
  const verbose = options.verbose ?? false;
2819
3249
  const logger = createLogger(verbose);
2820
3250
  try {
2821
- const cwd = pathArg ? path6.resolve(process.cwd(), pathArg) : process.cwd();
2822
- if (!fs5.existsSync(cwd)) {
3251
+ const cwd = pathArg ? path8.resolve(process.cwd(), pathArg) : process.cwd();
3252
+ if (!fs7.existsSync(cwd)) {
2823
3253
  throw new CliError(
2824
3254
  `Directory does not exist: ${cwd}`,
2825
3255
  "ENOENT",
@@ -2832,7 +3262,7 @@ async function dev(pathArg, options) {
2832
3262
  logger.debug(`Config loaded: routesDir=${config.routesDir}, extensions=${config.extensions.join(", ")}`);
2833
3263
  const routesDir = resolveRoutesDir(config, cwd);
2834
3264
  logger.debug(`Routes directory: ${routesDir}`);
2835
- if (!fs5.existsSync(routesDir)) {
3265
+ if (!fs7.existsSync(routesDir)) {
2836
3266
  throw new CliError(
2837
3267
  `Routes directory does not exist: ${routesDir}`,
2838
3268
  "ENOENT",
@@ -2867,7 +3297,7 @@ async function dev(pathArg, options) {
2867
3297
  logger.warn(`Create a route.ts file to get started.`);
2868
3298
  }
2869
3299
  logger.debug(`Creating Hono app...`);
2870
- const { app, routes } = await createApp(manifest, config, logger, verbose);
3300
+ const { app, routes } = await createApp(manifest, scanResult, config, logger, verbose);
2871
3301
  const port = parseInt(options.port, 10);
2872
3302
  if (isNaN(port) || port < 1 || port > 65535) {
2873
3303
  throw new CliError(
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cloudwerk/cli",
3
- "version": "0.1.1",
3
+ "version": "0.2.1",
4
4
  "description": "Dev server, build, deploy commands for Cloudwerk",
5
5
  "repository": {
6
6
  "type": "git",
@@ -25,7 +25,7 @@
25
25
  "commander": "^12.1.0",
26
26
  "esbuild": "^0.25.0",
27
27
  "picocolors": "^1.1.0",
28
- "@cloudwerk/core": "^0.1.1",
28
+ "@cloudwerk/core": "^0.2.1",
29
29
  "@cloudwerk/ui": "^0.1.1"
30
30
  },
31
31
  "devDependencies": {