@marko/run 0.1.2 → 0.1.3

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.
@@ -1,4 +1,4 @@
1
- declare type ValuesOf<T> = T[keyof T];
1
+ type ValuesOf<T> = T[keyof T];
2
2
  export declare const markoRunFilePrefix = "__marko-run__";
3
3
  export declare const virtualFilePrefix = "virtual:marko-run";
4
4
  export declare const virtualRoutesPrefix: string;
@@ -15,6 +15,6 @@ export declare const RoutableFileTypes: {
15
15
  readonly NotFound: "404";
16
16
  readonly Error: "500";
17
17
  };
18
- export declare type RoutableFileType = ValuesOf<typeof RoutableFileTypes>;
19
- export declare type HttpVerb = typeof httpVerbs[number];
18
+ export type RoutableFileType = ValuesOf<typeof RoutableFileTypes>;
19
+ export type HttpVerb = typeof httpVerbs[number];
20
20
  export {};
@@ -26,7 +26,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
26
26
  // src/vite/index.ts
27
27
  var vite_exports = {};
28
28
  __export(vite_exports, {
29
- default: () => markoServe,
29
+ default: () => markoRun,
30
30
  getAvailablePort: () => getAvailablePort,
31
31
  isPortInUse: () => isPortInUse,
32
32
  loadEnv: () => loadEnv,
@@ -663,7 +663,7 @@ function renderRouter(routes, options = {
663
663
  writer.writeLines(`// @marko/run/router`);
664
664
  const imports = writer.branch("imports");
665
665
  imports.writeLines(
666
- `import { NotHandled, NotMatched, createInput } from 'virtual:marko-run/internal';`
666
+ `import { NotHandled, NotMatched, createContext } from 'virtual:marko-run/internal';`
667
667
  );
668
668
  for (const route of routes.list) {
669
669
  const verbs = getVerbs(route);
@@ -680,7 +680,17 @@ function renderRouter(routes, options = {
680
680
  `import page${key} from '${virtualFilePrefix}/${markoRunFilePrefix}special__${key}.marko${serverEntryQuery}';`
681
681
  );
682
682
  }
683
- writer.writeLines(``).writeBlockStart(`export function match(method, pathname) {`).writeLines(
683
+ writer.writeLines(
684
+ `
685
+ const page404ResponseInit = {
686
+ status: 404,
687
+ headers: { "content-type": "text/html;charset=UTF-8" },
688
+ };
689
+ const page500ResponseInit = {
690
+ status: 404,
691
+ headers: { "content-type": "text/html;charset=UTF-8" },
692
+ };`
693
+ ).writeBlockStart(`export function match(method, pathname) {`).writeLines(
684
694
  `if (!pathname) {
685
695
  pathname = '/';
686
696
  } else if (pathname.charAt(0) !== '/') {
@@ -698,17 +708,10 @@ function renderRouter(routes, options = {
698
708
  }
699
709
  writer.writeBlockEnd("}").writeLines("return null;").writeBlockEnd("}");
700
710
  writer.write(`
701
- export async function invoke(route, request, platform, url = new URL(request.url)) {
702
- const context = {
703
- url,
704
- request,
705
- platform
706
- };
707
- const buildInput = createInput(context);
711
+ export async function invoke(route, request, platform, url) {
712
+ const [context, buildInput] = createContext(route, request, platform, url);
708
713
  try {
709
714
  if (route) {
710
- context.params = route.params;
711
- context.meta = route.meta;
712
715
  try {
713
716
  const response = await route.handler(context, buildInput);
714
717
  if (response) return response;
@@ -723,14 +726,9 @@ export async function invoke(route, request, platform, url = new URL(request.url
723
726
  if (routes.special[RoutableFileTypes.NotFound]) {
724
727
  writer.write(
725
728
  ` } else {
726
- context.params = {};
727
- context.meta = {};
728
729
  }
729
730
  if (context.request.headers.get('Accept')?.includes('text/html')) {
730
- return new Response(page404.stream(buildInput()), {
731
- status: 404,
732
- headers: { "content-type": "text/html;charset=UTF-8" },
733
- });
731
+ return new Response(page404.stream(buildInput()), page404ResponseInit);
734
732
  }
735
733
  `
736
734
  );
@@ -742,13 +740,8 @@ export async function invoke(route, request, platform, url = new URL(request.url
742
740
  if (routes.special[RoutableFileTypes.Error]) {
743
741
  writer.writeBlockStart(
744
742
  `if (context.request.headers.get('Accept')?.includes('text/html')) {`
745
- ).writeBlock(
746
- `return new Response(page500.stream(buildInput({ error })), {`,
747
- [
748
- `status: 500,`,
749
- `headers: { "content-type": "text/html;charset=UTF-8" },`
750
- ],
751
- `});`
743
+ ).writeLines(
744
+ `return new Response(page500.stream(buildInput({ error })), page500ResponseInit);`
752
745
  ).writeBlockEnd("}");
753
746
  }
754
747
  writer.writeLines(`throw error;`).writeBlockEnd("}").writeBlockEnd("}").write(`
@@ -984,8 +977,8 @@ function stripTsExtension(path3) {
984
977
  }
985
978
  return path3;
986
979
  }
987
- function renderRouteTypeInfo(routes, pathPrefix = ".", adapterTypes = "") {
988
- var _a, _b;
980
+ async function renderRouteTypeInfo(routes, pathPrefix = ".", adapter) {
981
+ var _a, _b, _c, _d;
989
982
  const writer = createStringWriter();
990
983
  writer.writeLines(
991
984
  `/*
@@ -993,28 +986,25 @@ function renderRouteTypeInfo(routes, pathPrefix = ".", adapterTypes = "") {
993
986
  Do NOT manually edit this file or your changes will be lost.
994
987
  */
995
988
  `,
996
- `import type { HandlerLike, Route as AnyRoute, Context as AnyContext, ValidatePath, ValidateHref } from "@marko/run";`,
997
- adapterTypes,
998
- `
999
-
1000
- declare global {
1001
- namespace MarkoRun {`
989
+ `import type { HandlerLike, Route as AnyRoute, Context as AnyContext, ParamsObject, ValidatePath, ValidateHref } from "@marko/run";`
1002
990
  );
1003
- const pathsWriter = writer.branch("paths");
1004
- writer.write(`
1005
- type GetablePath<T extends string> = ValidatePath<GetPaths, T>;
1006
- type GetableHref<T extends string> = ValidateHref<GetPaths, T>;
1007
- type PostablePath<T extends string> = ValidatePath<PostPaths, T>;
1008
- type PostableHref<T extends string> = ValidateHref<PostPaths, T>;
991
+ let platformType = "unknown";
992
+ if (adapter && adapter.typeInfo) {
993
+ platformType = await adapter.typeInfo((data) => writer.write(data));
994
+ writer.writeLines("");
1009
995
  }
1010
- }
996
+ writer.writeLines(`
997
+ interface NoParams extends ParamsObject {}
998
+ interface NoMeta {}
1011
999
  `);
1000
+ const pathsWriter = writer.branch("paths");
1012
1001
  const routesWriter = writer.branch("types");
1013
1002
  const serverWriter = writer.branch("server");
1014
1003
  const middlewareRouteTypes = /* @__PURE__ */ new Map();
1015
1004
  const layoutRouteTypes = /* @__PURE__ */ new Map();
1016
1005
  const getPaths = /* @__PURE__ */ new Set();
1017
1006
  const postPaths = /* @__PURE__ */ new Set();
1007
+ writeModuleDeclaration(serverWriter, void 0, void 0, platformType);
1018
1008
  for (const route of routes.list) {
1019
1009
  const { meta, handler, params, middleware, page, layouts } = route;
1020
1010
  const routeType = `Route${route.index}`;
@@ -1022,8 +1012,8 @@ declare global {
1022
1012
  /\/\$(\$?)([^\/]*)/,
1023
1013
  (_, catchAll, name) => catchAll ? `/:${name || "rest"}*` : `/:${name}`
1024
1014
  )}\``;
1025
- const paramsType = params ? renderParamsInfoType(params) : "{}";
1026
- let metaType = "undefined";
1015
+ const paramsType = (params == null ? void 0 : params.length) ? renderParamsInfoType(params) : "NoParams";
1016
+ let metaType = "NoMeta";
1027
1017
  if (page || handler) {
1028
1018
  const isGet = page || ((_a = handler == null ? void 0 : handler.verbs) == null ? void 0 : _a.includes("get"));
1029
1019
  const isPost = (_b = handler == null ? void 0 : handler.verbs) == null ? void 0 : _b.includes("post");
@@ -1043,31 +1033,31 @@ declare global {
1043
1033
  }
1044
1034
  }
1045
1035
  if (meta) {
1046
- metaType = `typeof import('${pathPrefix}/${stripTsExtension(
1047
- meta.relativePath
1048
- )}')`;
1036
+ const path3 = stripTsExtension(`${pathPrefix}/${meta.relativePath}`);
1037
+ metaType = `typeof import('${path3}')`;
1049
1038
  if (/\.(ts|js|mjs)$/.test(meta.relativePath)) {
1050
1039
  metaType += `['default']`;
1051
1040
  }
1052
1041
  }
1053
1042
  if (handler) {
1054
- writeRouteTypeModule(
1043
+ writeModuleDeclaration(
1055
1044
  serverWriter,
1056
- pathPrefix,
1057
- handler.relativePath,
1058
- routeType
1045
+ `${pathPrefix}/${handler.relativePath}`,
1046
+ routeType,
1047
+ platformType
1059
1048
  );
1060
1049
  }
1061
1050
  if (page) {
1062
- writer.writeLines(`
1063
- declare module '${pathPrefix}/${page.relativePath}' {
1064
- export interface Input {}
1065
-
1066
- namespace MarkoRun {
1067
- type Route = ${routeType};
1068
- type Context = AnyContext<AnyContext['platform'], Route>;
1069
- }
1070
- }`);
1051
+ writeModuleDeclaration(
1052
+ writer,
1053
+ `${pathPrefix}/${page.relativePath}`,
1054
+ routeType,
1055
+ platformType,
1056
+ `
1057
+ export interface Input {
1058
+ renderBody: Marko.Body;
1059
+ }`
1060
+ );
1071
1061
  }
1072
1062
  if (middleware) {
1073
1063
  let i = 0;
@@ -1097,74 +1087,106 @@ declare module '${pathPrefix}/${page.relativePath}' {
1097
1087
  }
1098
1088
  }
1099
1089
  routesWriter.writeLines(
1100
- `interface ${routeType} extends AnyRoute<${paramsType}, ${metaType}, ${pathType}> {}`
1090
+ `type ${routeType} = AnyRoute<${paramsType}, ${metaType}, ${pathType}>;`
1101
1091
  );
1102
1092
  }
1103
- pathsWriter.write(" type GetPaths =");
1104
- for (const path3 of getPaths) {
1105
- pathsWriter.write(`
1106
- | '${path3}'`);
1093
+ pathsWriter.write(`type Get =`);
1094
+ if (getPaths.size) {
1095
+ for (const path3 of getPaths) {
1096
+ pathsWriter.write(`
1097
+ | '${path3}'`);
1098
+ }
1099
+ } else {
1100
+ pathsWriter.write(" never");
1107
1101
  }
1108
1102
  pathsWriter.writeLines(";", "");
1109
- pathsWriter.write(" type PostPaths =");
1110
- for (const path3 of postPaths) {
1111
- pathsWriter.write(`
1112
- | '${path3}'`);
1103
+ pathsWriter.write("type Post =");
1104
+ if (postPaths.size) {
1105
+ for (const path3 of postPaths) {
1106
+ pathsWriter.write(`
1107
+ | '${path3}'`);
1108
+ }
1109
+ } else {
1110
+ pathsWriter.write(" never");
1113
1111
  }
1114
- pathsWriter.writeLines(";");
1112
+ pathsWriter.writeLines(";", "");
1115
1113
  pathsWriter.join();
1116
1114
  for (const [file, { routeTypes }] of middlewareRouteTypes) {
1117
- writeRouteTypeModule(
1115
+ writeModuleDeclaration(
1118
1116
  serverWriter,
1119
- pathPrefix,
1120
- file.relativePath,
1121
- routeTypes.join(" | ")
1117
+ `${pathPrefix}/${file.relativePath}`,
1118
+ routeTypes.join(" | "),
1119
+ platformType
1122
1120
  );
1123
1121
  }
1124
1122
  for (const [file, { routeTypes }] of layoutRouteTypes) {
1125
- writer.writeLines(`
1126
- declare module '${pathPrefix}/${file.relativePath}' {
1123
+ writeModuleDeclaration(
1124
+ writer,
1125
+ `${pathPrefix}/${file.relativePath}`,
1126
+ routeTypes.join(" | "),
1127
+ platformType,
1128
+ `
1127
1129
  export interface Input {
1128
1130
  renderBody: Marko.Body;
1131
+ }`
1132
+ );
1129
1133
  }
1130
-
1131
- namespace MarkoRun {
1132
- type Route = ${routeTypes.join(" | ")};
1133
- type Context = AnyContext<AnyContext['platform'], Route>;
1134
- }
1135
- }`);
1134
+ if ((_c = routes.special["404"]) == null ? void 0 : _c.page) {
1135
+ writeModuleDeclaration(
1136
+ writer,
1137
+ `${pathPrefix}/${routes.special["404"].page.relativePath}`,
1138
+ void 0,
1139
+ platformType,
1140
+ `
1141
+ export interface Input {}`
1142
+ );
1136
1143
  }
1137
- for (const route of [routes.special["404"], routes.special["500"]]) {
1138
- if (route && route.page) {
1139
- writer.write(`
1140
- declare module '${pathPrefix}/${route.page.relativePath}' {
1141
- export interface Input {`);
1142
- if (route.page.type === RoutableFileTypes.Error) {
1143
- writer.write(`
1144
+ if ((_d = routes.special["500"]) == null ? void 0 : _d.page) {
1145
+ writeModuleDeclaration(
1146
+ writer,
1147
+ `${pathPrefix}/${routes.special["500"].page.relativePath}`,
1148
+ void 0,
1149
+ platformType,
1150
+ `
1151
+ export interface Input {
1144
1152
  error: unknown;
1145
- `);
1146
- }
1147
- writer.writeLines(`}
1148
-
1149
- namespace MarkoRun {
1150
- type Route = AnyRoute;
1151
- type Context = AnyContext<AnyContext['platform'], Route>;
1152
- }
1153
- }`);
1154
- }
1153
+ }`
1154
+ );
1155
1155
  }
1156
1156
  serverWriter.join();
1157
1157
  return writer.end();
1158
1158
  }
1159
- function writeRouteTypeModule(writer, pathPrefix, path3, routeType) {
1160
- writer.writeLines(`
1161
- declare module '${pathPrefix}/${stripTsExtension(path3)}' {
1159
+ function writeModuleDeclaration(writer, path3 = "global", routeType = "AnyRoute", platformType = "unknown", moduleTypes) {
1160
+ writer.writeLines("");
1161
+ if (path3 === "global") {
1162
+ writer.write("declare global {");
1163
+ } else {
1164
+ writer.write(`declare module '${stripTsExtension(path3)}' {`);
1165
+ }
1166
+ if (moduleTypes) {
1167
+ writer.writeLines(moduleTypes);
1168
+ }
1169
+ const isMarko = path3.endsWith(".marko");
1170
+ writer.write(`
1162
1171
  namespace MarkoRun {
1172
+ type GetPaths = Get;
1173
+ type PostPaths = Post;
1174
+ type GetablePath<T extends string> = ValidatePath<Get, T>;
1175
+ type GetableHref<T extends string> = ValidateHref<Get, T>;
1176
+ type PostablePath<T extends string> = ValidatePath<Post, T>;
1177
+ type PostableHref<T extends string> = ValidateHref<Post, T>;
1178
+ type Platform = ${platformType};`);
1179
+ if (path3 !== "global") {
1180
+ writer.write(`
1163
1181
  type Route = ${routeType};
1164
- type Context = AnyContext<AnyContext['platform'], Route>;
1182
+ type Context = AnyContext<Platform, Route>${isMarko ? " & Marko.Global" : ""};
1165
1183
  type Handler<_Params = Route['params'], _Meta = Route['meta']> = HandlerLike<Route>;
1166
1184
  function route(handler: Handler): typeof handler;
1167
1185
  function route<_Params = Route['params'], _Meta = Route['meta']>(handler: Handler): typeof handler;
1186
+ const NotHandled: unique symbol;
1187
+ const NotMatched: unique symbol;`);
1188
+ }
1189
+ writer.writeLines(`
1168
1190
  }
1169
1191
  }`);
1170
1192
  }
@@ -1363,8 +1385,9 @@ var normalizePath = import_path2.default.sep === WINDOWS_SEP ? (id) => id.replac
1363
1385
  function isMarkoFile(id) {
1364
1386
  return id.endsWith(markoExt);
1365
1387
  }
1366
- function markoServe(opts = {}) {
1367
- const { routesDir = "src/routes", adapter, ...markoOptions } = opts;
1388
+ function markoRun(opts = {}) {
1389
+ let { routesDir = "src/routes", adapter, ...markoOptions } = opts;
1390
+ let compiler;
1368
1391
  let store;
1369
1392
  let root;
1370
1393
  let resolvedRoutesDir;
@@ -1395,8 +1418,11 @@ function markoServe(opts = {}) {
1395
1418
  "{.tsconfig*,tsconfig*.json}"
1396
1419
  ))) {
1397
1420
  const filepath = import_path2.default.join(typesDir, "routes.d.ts");
1398
- const adapterTypeInfo = (adapter == null ? void 0 : adapter.writeTypeInfo) && await (adapter == null ? void 0 : adapter.writeTypeInfo());
1399
- const data = renderRouteTypeInfo(routes, import_path2.default.relative(typesDir, routesDir), adapterTypeInfo);
1421
+ const data = await renderRouteTypeInfo(
1422
+ routes,
1423
+ import_path2.default.relative(typesDir, routesDir),
1424
+ adapter
1425
+ );
1400
1426
  if (data !== typesFile || !import_fs2.default.existsSync(filepath)) {
1401
1427
  await ensureDir(typesDir);
1402
1428
  await import_fs2.default.promises.writeFile(filepath, typesFile = data);
@@ -1409,13 +1435,16 @@ function markoServe(opts = {}) {
1409
1435
  route.handler.verbs = await extractVerbs(route.handler.filePath);
1410
1436
  if (!route.handler.verbs.length) {
1411
1437
  console.warn(
1412
- `Did not find any valid exports in middleware entry file:'${route.handler.filePath}' - expected to find any of 'get', 'post', 'put' or 'del'`
1438
+ `Did not find any valid exports in middleware entry file:'${route.handler.filePath}' - expected to find any of 'GET', 'POST', 'PUT' or 'DELETE'`
1413
1439
  );
1414
1440
  }
1415
1441
  }
1416
1442
  if (route.page) {
1417
1443
  virtualFiles.set(
1418
- import_path2.default.posix.join(root, `${markoRunFilePrefix}route__${route.key}.marko`),
1444
+ import_path2.default.posix.join(
1445
+ root,
1446
+ `${markoRunFilePrefix}route__${route.key}.marko`
1447
+ ),
1419
1448
  render ? renderRouteTemplate(route) : ""
1420
1449
  );
1421
1450
  }
@@ -1426,7 +1455,10 @@ function markoServe(opts = {}) {
1426
1455
  }
1427
1456
  for (const route of Object.values(routes.special)) {
1428
1457
  virtualFiles.set(
1429
- import_path2.default.posix.join(root, `${markoRunFilePrefix}special__${route.key}.marko`),
1458
+ import_path2.default.posix.join(
1459
+ root,
1460
+ `${markoRunFilePrefix}special__${route.key}.marko`
1461
+ ),
1430
1462
  render ? renderRouteTemplate(route) : ""
1431
1463
  );
1432
1464
  }
@@ -1466,22 +1498,32 @@ function markoServe(opts = {}) {
1466
1498
  if (externalPluginOptions) {
1467
1499
  opts = (0, import_vite.mergeConfig)(opts, externalPluginOptions);
1468
1500
  }
1501
+ root = normalizePath(config2.root || process.cwd());
1502
+ isBuild = env.command === "build";
1503
+ isSSRBuild = isBuild && Boolean((_a = config2.build) == null ? void 0 : _a.ssr);
1504
+ adapter = await resolveAdapter(root, opts, config2.logLevel !== "silent" && !isBuild || isSSRBuild);
1469
1505
  if (adapter) {
1470
1506
  const externalAdapterConfig = getExternalAdapterOptions(config2);
1471
1507
  if (externalAdapterConfig && adapter.configure) {
1472
1508
  adapter.configure(externalAdapterConfig);
1473
1509
  }
1474
- const adapterOptions = await ((_a = adapter.pluginOptions) == null ? void 0 : _a.call(adapter, opts));
1510
+ const adapterOptions = await ((_b = adapter.pluginOptions) == null ? void 0 : _b.call(adapter, opts));
1475
1511
  if (adapterOptions) {
1476
1512
  opts = (0, import_vite.mergeConfig)(opts, adapterOptions);
1477
1513
  }
1478
1514
  }
1479
- root = normalizePath(config2.root || process.cwd());
1515
+ compiler ?? (compiler = await import(opts.compiler || "@marko/compiler"));
1516
+ compiler.taglib.register("@marko/run", {
1517
+ "<*>": {
1518
+ template: import_path2.default.resolve(
1519
+ __dirname,
1520
+ "../components/src-attributes-transformer.cjs"
1521
+ )
1522
+ }
1523
+ });
1480
1524
  store = opts.store || new import_vite2.FileStore(
1481
1525
  `marko-serve-vite-${import_crypto.default.createHash("SHA1").update(root).digest("hex")}`
1482
1526
  );
1483
- isBuild = env.command === "build";
1484
- isSSRBuild = isBuild && Boolean((_b = config2.build) == null ? void 0 : _b.ssr);
1485
1527
  resolvedRoutesDir = import_path2.default.resolve(root, routesDir);
1486
1528
  typesDir = import_path2.default.join(root, ".marko-run");
1487
1529
  devEntryFile = import_path2.default.join(root, "index.html");
@@ -1723,6 +1765,31 @@ async function ensureDir(dir) {
1723
1765
  await import_fs2.default.promises.mkdir(dir, { recursive: true });
1724
1766
  }
1725
1767
  }
1768
+ async function resolveAdapter(root, options, log) {
1769
+ const { adapter } = options;
1770
+ if (adapter !== void 0) {
1771
+ return adapter;
1772
+ }
1773
+ const pkg = (0, import_vite.resolvePackageData)(".", root);
1774
+ if (pkg) {
1775
+ const dependecies = { ...pkg.data.dependecies, ...pkg.data.devDependencies };
1776
+ for (const name of Object.keys(dependecies)) {
1777
+ if (name.startsWith("@marko/run-adapter") || name.indexOf("marko-run-adapter") !== -1) {
1778
+ try {
1779
+ const module3 = await import(name);
1780
+ log && console.log(`Using adapter ${name} listed in your package.json dependecies`);
1781
+ return module3.default();
1782
+ } catch (err) {
1783
+ log && console.warn(`Attempt to use package '${name}' failed`, err);
1784
+ }
1785
+ }
1786
+ }
1787
+ }
1788
+ const defaultAdapter = "@marko/run/adapter";
1789
+ const module2 = await import(defaultAdapter);
1790
+ log && console.log("Using default adapter");
1791
+ return module2.default();
1792
+ }
1726
1793
 
1727
1794
  // src/vite/utils/server.ts
1728
1795
  var import_net = __toESM(require("net"), 1);