@mastrojs/mastro 0.0.0-stage → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +60 -2
  3. package/dist/cli.d.ts +3 -0
  4. package/dist/cli.d.ts.map +1 -0
  5. package/dist/cli.js +92 -0
  6. package/dist/core/fs.d.ts +67 -0
  7. package/dist/core/fs.d.ts.map +1 -0
  8. package/dist/core/fs.js +114 -0
  9. package/dist/core/fsHelpers.d.ts +18 -0
  10. package/dist/core/fsHelpers.d.ts.map +1 -0
  11. package/dist/core/fsHelpers.js +17 -0
  12. package/dist/core/html.d.ts +67 -0
  13. package/dist/core/html.d.ts.map +1 -0
  14. package/dist/core/html.js +201 -0
  15. package/dist/core/responses.d.ts +98 -0
  16. package/dist/core/responses.d.ts.map +1 -0
  17. package/dist/core/responses.js +145 -0
  18. package/dist/core/routeHelpers.d.ts +12 -0
  19. package/dist/core/routeHelpers.d.ts.map +1 -0
  20. package/dist/core/routeHelpers.js +51 -0
  21. package/dist/generator.d.ts +16 -0
  22. package/dist/generator.d.ts.map +1 -0
  23. package/dist/generator.js +124 -0
  24. package/dist/index.d.ts +13 -0
  25. package/dist/index.d.ts.map +1 -0
  26. package/dist/index.js +10 -0
  27. package/dist/mastro.d.ts +58 -0
  28. package/dist/mastro.d.ts.map +1 -0
  29. package/dist/mastro.js +93 -0
  30. package/dist/middleware.d.ts +4 -0
  31. package/dist/middleware.d.ts.map +1 -0
  32. package/dist/middleware.js +21 -0
  33. package/dist/middlewares/fingerprintAssets.d.ts +3 -0
  34. package/dist/middlewares/fingerprintAssets.d.ts.map +1 -0
  35. package/dist/middlewares/fingerprintAssets.js +35 -0
  36. package/dist/middlewares/logger.d.ts +4 -0
  37. package/dist/middlewares/logger.d.ts.map +1 -0
  38. package/dist/middlewares/logger.js +41 -0
  39. package/dist/middlewares/staticFiles/mediaTypes.d.ts +6 -0
  40. package/dist/middlewares/staticFiles/mediaTypes.d.ts.map +1 -0
  41. package/dist/middlewares/staticFiles/mediaTypes.js +26 -0
  42. package/dist/middlewares/staticFiles/mediaTypes.json +910 -0
  43. package/dist/middlewares/staticFiles/staticFiles.d.ts +10 -0
  44. package/dist/middlewares/staticFiles/staticFiles.d.ts.map +1 -0
  45. package/dist/middlewares/staticFiles/staticFiles.js +119 -0
  46. package/dist/middlewares/tsToJs.d.ts +13 -0
  47. package/dist/middlewares/tsToJs.d.ts.map +1 -0
  48. package/dist/middlewares/tsToJs.js +49 -0
  49. package/dist/servers/fileRouter.d.ts +11 -0
  50. package/dist/servers/fileRouter.d.ts.map +1 -0
  51. package/dist/servers/fileRouter.js +74 -0
  52. package/dist/servers/fileRoutes.d.ts +2 -0
  53. package/dist/servers/fileRoutes.d.ts.map +1 -0
  54. package/dist/servers/fileRoutes.js +1 -0
  55. package/dist/servers/server.d.ts +22 -0
  56. package/dist/servers/server.d.ts.map +1 -0
  57. package/dist/servers/server.js +21 -0
  58. package/dist/types/mastro.d.ts +80 -0
  59. package/dist/types/middleware.d.ts +157 -0
  60. package/dist/types/standard-schema.d.ts +76 -0
  61. package/package.json +52 -3
  62. package/src/README.md +29 -0
  63. package/src/cli.ts +89 -0
  64. package/src/core/fs.ts +131 -0
  65. package/src/core/fsHelpers.ts +24 -0
  66. package/src/core/html.ts +226 -0
  67. package/src/core/responses.ts +175 -0
  68. package/src/core/routeHelpers.ts +60 -0
  69. package/src/generator.ts +139 -0
  70. package/src/index.ts +14 -0
  71. package/src/mastro.ts +116 -0
  72. package/src/middleware.ts +28 -0
  73. package/src/middlewares/fingerprintAssets.ts +37 -0
  74. package/src/middlewares/logger.ts +43 -0
  75. package/src/middlewares/staticFiles/mediaTypes.json +910 -0
  76. package/src/middlewares/staticFiles/mediaTypes.ts +28 -0
  77. package/src/middlewares/staticFiles/staticFiles.ts +136 -0
  78. package/src/middlewares/tsToJs.ts +43 -0
  79. package/src/servers/fileRouter.ts +83 -0
  80. package/src/servers/fileRoutes.ts +1 -0
  81. package/src/servers/server.ts +29 -0
  82. package/src/types/mastro.d.ts +80 -0
  83. package/src/types/middleware.d.ts +157 -0
  84. package/src/types/standard-schema.d.ts +76 -0
@@ -0,0 +1,201 @@
1
+ /**
2
+ * `@mastrojs/mastro/html` contains a selfcontained way to construct and properly escape
3
+ * HTML using JavaScript tagged template literals.
4
+ * All its exports are also exported by the default `@mastrojs/mastro` module,
5
+ * and usually you should just use those. However, it is also exported separately here
6
+ * for use in `@mastrojs/reactive` or other projects where you only want its functionality.
7
+ * @module
8
+ */
9
+ /**
10
+ * Tagged template literal to construct `Html` nodes.
11
+ * This makes sure things are properly escaped (unless `unsafeInnerHtml` is used).
12
+ *
13
+ * ```ts
14
+ * import { html, renderToString } from "@mastrojs/mastro";
15
+ *
16
+ * const myName = "World";
17
+ * const myClass = "hero";
18
+ *
19
+ * const str = await renderToString(
20
+ * html`<h1 class=${myClass}>Hello ${myName}</h1>`
21
+ * );
22
+ * ```
23
+ */
24
+ export const html = (templateParts, ...params) => {
25
+ let parts = cache.get(templateParts); // soon we can use cache.getOrInsertComputed
26
+ if (!parts)
27
+ cache.set(templateParts, parts = parseParts(templateParts));
28
+ const output = [];
29
+ for (let i = 0; i < parts.length; i++) {
30
+ const { html, quote } = parts[i];
31
+ output.push(html);
32
+ if (i < params.length) {
33
+ const p = params[i];
34
+ if (quote) {
35
+ output.push(unsafeInnerHtml('"'), p, unsafeInnerHtml('"'));
36
+ }
37
+ else if (Array.isArray(p)) {
38
+ output.push(...p);
39
+ }
40
+ else {
41
+ output.push(p);
42
+ }
43
+ }
44
+ }
45
+ return output;
46
+ };
47
+ /**
48
+ * Mark a string as already properly escaped HTML. Do not use this on an untrusted/user-supplied string!
49
+ *
50
+ * This is similar to the DOM's [innerHTML](https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML#replacing_the_contents_of_an_element)
51
+ * or React's `dangerouslySetInnerHTML`.
52
+ */
53
+ export const unsafeInnerHtml = (val) => Object.freeze(new String(val));
54
+ /**
55
+ * Returns true iff `val` is an async iterable
56
+ */
57
+ export const isAsyncIterable = (val) => val && typeof val[Symbol.asyncIterator] === "function";
58
+ /**
59
+ * Convert an `Html` node to a properly escaped `Promise<string>`.
60
+ *
61
+ * See `renderToStream` for a more efficient but less ergonomic alternative.
62
+ */
63
+ export const renderToString = async (node) => {
64
+ const s = renderToStream(node);
65
+ return typeof s === "string" ? s : (await Array.fromAsync(s)).join("");
66
+ };
67
+ /**
68
+ * Convert an `Html` node to a properly escaped `string` but
69
+ * throws if the input contains a Promise or AsyncIterable.
70
+ * You probably want to use `renderToString` or `renderToStream` instead.
71
+ */
72
+ export const renderToStringSync = (node) => {
73
+ const s = renderToStream(Array.isArray(node) ? node : [node]);
74
+ if (typeof s !== "string") {
75
+ throw Error("renderToStringSync received async value. Use renderToString instead.");
76
+ }
77
+ return s;
78
+ };
79
+ /**
80
+ * Convert an `Html` node to a properly escaped stream.
81
+ * Returns an `AsyncIterable<string>` if there are Promises or AsyncIterables in the input,
82
+ * otherwise returns a `string`.
83
+ *
84
+ * The string case is a lot more efficient – especially when then passed to
85
+ * Mastro's `htmlResponse`, to construct a `Response`.
86
+ */
87
+ export const renderToStream = (node) => {
88
+ let stack = [node];
89
+ if (Array.isArray(node)) {
90
+ stack = node.flat(Infinity);
91
+ if (!(stack.some((n) => n instanceof Promise || isAsyncIterable(n)))) {
92
+ // if there is nothing async, we can speed things up by an order of magnitude like this
93
+ let str = "";
94
+ for (let i = 0; i < stack.length; i++) {
95
+ // in my limited testing, this is faster than `stack.map(escape).join("")`
96
+ str += escape(stack[i]);
97
+ }
98
+ return str;
99
+ }
100
+ }
101
+ // reversing and using pop() is faster than using shift().
102
+ // However, we could investigate whether keeping a manual index would be better,
103
+ // but garbage collection would probably suffer.
104
+ stack.reverse();
105
+ // Set up buffer to reduce per-chunk overhead
106
+ let buffer = "";
107
+ let closed = false;
108
+ const flushBuffer = () => {
109
+ const value = buffer;
110
+ buffer = "";
111
+ return { value, done: false };
112
+ };
113
+ return {
114
+ [Symbol.asyncIterator]() {
115
+ return {
116
+ next: async () => {
117
+ while (stack.length > 0) {
118
+ const nextUp = stack[stack.length - 1];
119
+ if (buffer.length > 0 &&
120
+ (nextUp instanceof Promise || isAsyncIterable(nextUp) || isAsyncIterator(nextUp))) {
121
+ return flushBuffer();
122
+ }
123
+ if (isAsyncIterator(nextUp)) {
124
+ // If an iterator is on top of the stack, consume its next element:
125
+ const { value, done } = await nextUp.next();
126
+ if (closed)
127
+ break;
128
+ // But only pop the iterator itself from the stack when it's done:
129
+ done ? stack.pop() : stack.push(value);
130
+ }
131
+ else {
132
+ const current = await stack.pop();
133
+ if (closed)
134
+ break;
135
+ if (Array.isArray(current)) {
136
+ for (let i = current.length - 1; i >= 0; i--) {
137
+ stack.push(current[i]);
138
+ }
139
+ }
140
+ else if (isAsyncIterable(current)) {
141
+ // push iterator on stack for future consumption
142
+ stack.push(current[Symbol.asyncIterator]());
143
+ }
144
+ else {
145
+ buffer += escape(current);
146
+ }
147
+ }
148
+ }
149
+ // stack is emptied, only the buffer may be left
150
+ return buffer.length === 0 || closed
151
+ ? { value: undefined, done: true }
152
+ : flushBuffer();
153
+ },
154
+ return: async () => {
155
+ closed = true;
156
+ // Close sequentially from the inside out, continuing even if cleanup throws.
157
+ await stack.splice(0).filter(isAsyncIterator).reduceRight((cleanup, iterator) => cleanup.finally(() => iterator.return?.()), Promise.resolve());
158
+ return { value: undefined, done: true };
159
+ },
160
+ };
161
+ },
162
+ };
163
+ };
164
+ /**
165
+ * Parse HTML snippets to determine whether we should wrap the next part in quotes
166
+ * e.g. `<div class=${'myClass'}>`. We don't handle HTML comments, or single-quoted
167
+ * attributes, and track only whether we're in <script> contents (but not <style> etc).
168
+ */
169
+ const parseParts = (templateParts) => {
170
+ let inAttr = false, inScript = false;
171
+ let tagContents = ""; // empty string means we're outside a tag
172
+ return templateParts.map((str) => {
173
+ for (let i = 0; i < str.length; i++) {
174
+ const char = str[i];
175
+ if (inScript && str.startsWith("</script>", i))
176
+ inScript = false;
177
+ if (inScript)
178
+ continue;
179
+ if (!tagContents && char !== "<")
180
+ continue;
181
+ if (char === '"')
182
+ inAttr = !inAttr;
183
+ tagContents += char;
184
+ if (!inAttr && char === ">") {
185
+ inScript = /^<script(?:\s|>)/.test(tagContents);
186
+ tagContents = "";
187
+ }
188
+ }
189
+ return { html: unsafeInnerHtml(str), quote: !inAttr && /\s[\w:-]+=$/.test(tagContents) };
190
+ });
191
+ };
192
+ const escape = (n) => typeof n === "string"
193
+ ? escapeForAttribute(n)
194
+ : (n || typeof n === "number") ? n.toString() : "";
195
+ const escapeForAttribute = (str) => needsEscaping.test(str)
196
+ ? str.replace(/[&<>'"]/g, (char) => chars[char])
197
+ : str;
198
+ const needsEscaping = /[&<>'"]/;
199
+ const chars = { "&": "&amp;", "<": "&lt;", ">": "&gt;", "'": "&#39;", '"': "&quot;" };
200
+ const isAsyncIterator = (val) => val && typeof val.next === "function";
201
+ const cache = new Map();
@@ -0,0 +1,98 @@
1
+ import { type Html } from "./html.ts";
2
+ /**
3
+ * Create a standard Response object with `Content-Type: text/html` from a string
4
+ * or `AsyncIterable<string>` (in which case it will stream it).
5
+ */
6
+ export declare const htmlResponse: (body: string | AsyncIterable<string>, status?: number, headers?: Record<string, string>) => Response;
7
+ /**
8
+ * Create a standard Response object from an `Html` node.
9
+ */
10
+ export declare const htmlToResponse: (node: Html) => Response;
11
+ /**
12
+ * Create a standard Response object with `Content-Type: application/json`.
13
+ */
14
+ export declare const jsonResponse: (body: object, status?: number, headers?: Record<string, string>) => Response;
15
+ /**
16
+ * Create a standard Response object to stream an `AsyncIterable` of JSON data as
17
+ * [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events).
18
+ */
19
+ export declare const sseResponse: <T extends object>(stream: AsyncIterable<T>, headers?: Record<string, string>) => Response;
20
+ /**
21
+ * Returns the hashed path of a fingerprinted asset, as set by the fingerprintAssets middleware.
22
+ *
23
+ * - During static site generation, it reads from an in-memory map.
24
+ * - When running a production server, you need to run `mastro generate --only-pregenerate` in your
25
+ * CI, which will create a `generatedAssets.json` file, which this function will then read from.
26
+ * See the [Mastro Guide](https://mastrojs.github.io/guide/caching-service-workers-streaming/#fingerprinting-assets-with-hash-based-file-names).
27
+ * Don't forget to set your CDN's caching headers for `/_assets/*` to something like
28
+ * `Cache-Control: public, max-age=31556952, immutable` (1 year), otherwise hashing is little use.
29
+ *
30
+ * - Finally, when running the dev server, hashing all assets would be too slow. Thus if no
31
+ * `generatedAssets.json` file is present on server start, this function returns the unhashed
32
+ * input path prefixed with `/_assets/`. Therefore, be sure to delete `generatedAssets.json` after
33
+ * trying out `mastro generate --only-pregenerate` locally.
34
+ *
35
+ * Usage in your template, if you have e.g. a `routes/_assets/logo.webp` file:
36
+ *
37
+ * ```
38
+ * import { asset, html } from "@mastrojs/mastro";
39
+ *
40
+ * export const Header = () =>
41
+ * html`<header><img src=${asset("logo.webp")}></header>`;
42
+ * ```
43
+ */
44
+ export declare const asset: (path: string) => string;
45
+ /**
46
+ * [Identity tag literal](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/raw#building_an_identity_tag)
47
+ * which does no escaping: do not pass it untrusted input.
48
+ *
49
+ * ```ts
50
+ * export const styles = css`
51
+ * p {
52
+ * font-size: ${2 * 3}em;
53
+ * }
54
+ * `;
55
+ * ```
56
+ *
57
+ * For more usage examples, see
58
+ * [Component-scoped CSS without a build step](https://mastrojs.github.io/blog/2026-05-26-component-scoped-css-without-build-step/).
59
+ */
60
+ export declare const css: (strings: TemplateStringsArray, ...values: Array<string | number>) => string;
61
+ /**
62
+ * Returns the GitHub Pages base path (or an empty string).
63
+ *
64
+ * If you're hosting your website with GitHub Pages on a sub-directory
65
+ * (e.g. `https://my-name.github.io/my-repo` instead of `https://my-name.github.io`
66
+ * or instead of a custom domain), then you need to prefix all absolute links
67
+ * that start with a slash with your base path (`/my-repo` in this case),
68
+ * which is what this function returns when run on GitHub Actions.
69
+ *
70
+ * For example in your `Layout.ts` file:
71
+ *
72
+ * ```ts
73
+ * import { ghPagesBasePath, html } from "@mastrojs/mastro";
74
+ * export const basePath = ghPagesBasePath(); // export for use in other modules
75
+ * export const Layout = () =>
76
+ * html`
77
+ * <html>
78
+ * <head>
79
+ * <link href=${basePath + "/styles.css"}>
80
+ * `;
81
+ * ```
82
+ *
83
+ * btw. if you're not on GitHub Pages, but still hosting in a sub-directory, you can
84
+ * change the `generate` command in `package.json` to `BASEPATH='/my-path' mastro generate`,
85
+ * and use that like:
86
+ *
87
+ * ```ts
88
+ * export const basePath = process.env.BASEPATH || ""; // export for use in other modules
89
+ * export const Layout = () =>
90
+ * html`
91
+ * <html>
92
+ * <head>
93
+ * <link href=${basePath + "/styles.css"}>
94
+ * `;
95
+ * ```
96
+ */
97
+ export declare const ghPagesBasePath: () => string;
98
+ //# sourceMappingURL=responses.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"responses.d.ts","sourceRoot":"","sources":["../../src/core/responses.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,KAAK,IAAI,EAAmC,MAAM,WAAW,CAAC;AAEvE;;;GAGG;AACH,eAAO,MAAM,YAAY,SACjB,MAAM,GAAG,aAAa,CAAC,MAAM,CAAC,6BAE1B,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,KAC/B,QAIA,CAAC;AAEJ;;GAEG;AACH,eAAO,MAAM,cAAc,SAAU,IAAI,KAAG,QACR,CAAC;AAErC;;GAEG;AACH,eAAO,MAAM,YAAY,SACjB,MAAM,6BAEF,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,KAC/B,QAIC,CAAC;AAEL;;;GAGG;AACH,eAAO,MAAM,WAAW,GAAI,CAAC,SAAS,MAAM,UAClC,aAAa,CAAC,CAAC,CAAC,YACd,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,KAC/B,QAIA,CAAC;AAEJ;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,eAAO,MAAM,KAAK,SAAU,MAAM,KAAG,MAC4B,CAAC;AAElE;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,GAAG,YAAa,oBAAoB,aAAa,KAAK,CAAC,MAAM,GAAG,MAAM,CAAC,KAAG,MAC9C,CAAC;AA+B1C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AACH,eAAO,MAAM,eAAe,QAAO,MASlC,CAAC"}
@@ -0,0 +1,145 @@
1
+ import { readTextFile } from "./fs.js";
2
+ import { isAsyncIterable, renderToStream } from "./html.js";
3
+ /**
4
+ * Create a standard Response object with `Content-Type: text/html` from a string
5
+ * or `AsyncIterable<string>` (in which case it will stream it).
6
+ */
7
+ export const htmlResponse = (body, status = 200, headers) => new Response(isAsyncIterable(body) ? toReadableStream(body) : body, { status, headers: { "Content-Type": "text/html; charset=utf-8", ...headers } });
8
+ /**
9
+ * Create a standard Response object from an `Html` node.
10
+ */
11
+ export const htmlToResponse = (node) => htmlResponse(renderToStream(node));
12
+ /**
13
+ * Create a standard Response object with `Content-Type: application/json`.
14
+ */
15
+ export const jsonResponse = (body, status = 200, headers) => new Response(JSON.stringify(body), {
16
+ status,
17
+ headers: { "Content-Type": "application/json", ...headers },
18
+ });
19
+ /**
20
+ * Create a standard Response object to stream an `AsyncIterable` of JSON data as
21
+ * [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events).
22
+ */
23
+ export const sseResponse = (stream, headers) => new Response(toReadableStream(mapIterable(stream, (chunk) => `data: ${JSON.stringify(chunk)}\n\n`)), { headers: { "Content-Type": "text/event-stream", ...headers } });
24
+ /**
25
+ * Returns the hashed path of a fingerprinted asset, as set by the fingerprintAssets middleware.
26
+ *
27
+ * - During static site generation, it reads from an in-memory map.
28
+ * - When running a production server, you need to run `mastro generate --only-pregenerate` in your
29
+ * CI, which will create a `generatedAssets.json` file, which this function will then read from.
30
+ * See the [Mastro Guide](https://mastrojs.github.io/guide/caching-service-workers-streaming/#fingerprinting-assets-with-hash-based-file-names).
31
+ * Don't forget to set your CDN's caching headers for `/_assets/*` to something like
32
+ * `Cache-Control: public, max-age=31556952, immutable` (1 year), otherwise hashing is little use.
33
+ *
34
+ * - Finally, when running the dev server, hashing all assets would be too slow. Thus if no
35
+ * `generatedAssets.json` file is present on server start, this function returns the unhashed
36
+ * input path prefixed with `/_assets/`. Therefore, be sure to delete `generatedAssets.json` after
37
+ * trying out `mastro generate --only-pregenerate` locally.
38
+ *
39
+ * Usage in your template, if you have e.g. a `routes/_assets/logo.webp` file:
40
+ *
41
+ * ```
42
+ * import { asset, html } from "@mastrojs/mastro";
43
+ *
44
+ * export const Header = () =>
45
+ * html`<header><img src=${asset("logo.webp")}></header>`;
46
+ * ```
47
+ */
48
+ export const asset = (path) => globalThis._mastroAssets?.[path] || (/_assets/ + path);
49
+ /**
50
+ * [Identity tag literal](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/raw#building_an_identity_tag)
51
+ * which does no escaping: do not pass it untrusted input.
52
+ *
53
+ * ```ts
54
+ * export const styles = css`
55
+ * p {
56
+ * font-size: ${2 * 3}em;
57
+ * }
58
+ * `;
59
+ * ```
60
+ *
61
+ * For more usage examples, see
62
+ * [Component-scoped CSS without a build step](https://mastrojs.github.io/blog/2026-05-26-component-scoped-css-without-build-step/).
63
+ */
64
+ export const css = (strings, ...values) => String.raw({ raw: strings }, ...values);
65
+ const toReadableStream = (iterable) => {
66
+ // TODO: check back when and if something like the following works and is more performant:
67
+ // return ReadableStream.from(iterable.map(str => encoder.encode(str)));
68
+ const encoder = new TextEncoder();
69
+ const iterator = iterable[Symbol.asyncIterator]();
70
+ let canceled = false;
71
+ return new ReadableStream({
72
+ async pull(controller) {
73
+ try {
74
+ const { value, done } = await iterator.next();
75
+ if (done) {
76
+ controller.close();
77
+ }
78
+ else {
79
+ controller.enqueue(encoder.encode(value));
80
+ }
81
+ }
82
+ catch (e) {
83
+ if (canceled)
84
+ return;
85
+ console.error("Response failed mid-stream", e);
86
+ controller.error(e);
87
+ }
88
+ },
89
+ async cancel() {
90
+ canceled = true;
91
+ await iterator.return?.();
92
+ },
93
+ });
94
+ };
95
+ /**
96
+ * Returns the GitHub Pages base path (or an empty string).
97
+ *
98
+ * If you're hosting your website with GitHub Pages on a sub-directory
99
+ * (e.g. `https://my-name.github.io/my-repo` instead of `https://my-name.github.io`
100
+ * or instead of a custom domain), then you need to prefix all absolute links
101
+ * that start with a slash with your base path (`/my-repo` in this case),
102
+ * which is what this function returns when run on GitHub Actions.
103
+ *
104
+ * For example in your `Layout.ts` file:
105
+ *
106
+ * ```ts
107
+ * import { ghPagesBasePath, html } from "@mastrojs/mastro";
108
+ * export const basePath = ghPagesBasePath(); // export for use in other modules
109
+ * export const Layout = () =>
110
+ * html`
111
+ * <html>
112
+ * <head>
113
+ * <link href=${basePath + "/styles.css"}>
114
+ * `;
115
+ * ```
116
+ *
117
+ * btw. if you're not on GitHub Pages, but still hosting in a sub-directory, you can
118
+ * change the `generate` command in `package.json` to `BASEPATH='/my-path' mastro generate`,
119
+ * and use that like:
120
+ *
121
+ * ```ts
122
+ * export const basePath = process.env.BASEPATH || ""; // export for use in other modules
123
+ * export const Layout = () =>
124
+ * html`
125
+ * <html>
126
+ * <head>
127
+ * <link href=${basePath + "/styles.css"}>
128
+ * `;
129
+ * ```
130
+ */
131
+ export const ghPagesBasePath = () => {
132
+ if (typeof window === "undefined") {
133
+ // see https://docs.github.com/en/actions/reference/workflows-and-actions/variables
134
+ const repo = process.env.GITHUB_REPOSITORY?.split("/")[1];
135
+ if (repo && !repo.endsWith(".github.io")) {
136
+ return "/" + repo;
137
+ }
138
+ }
139
+ return "";
140
+ };
141
+ async function* mapIterable(iter, cb) {
142
+ for await (const val of iter) {
143
+ yield cb(val);
144
+ }
145
+ }
@@ -0,0 +1,12 @@
1
+ import type { Handler, Route } from "../types/mastro.d.ts";
2
+ import type { Context } from "../types/middleware.d.ts";
3
+ /**
4
+ * Attempts to determine whether we're running a development or production server.
5
+ *
6
+ * Currently this is done by checking whether the hostname is localhost, which is not perfect
7
+ * but allows you to test production behaviour by connecting to `127.0.0.1` and
8
+ * is easy to do without messing with environment variables.
9
+ */
10
+ export declare const isDevServer: (url: URL) => boolean;
11
+ export declare const routeHandler: <E>(rs: Route<Context<E>>[] | Promise<Route<Context<E>>[]>) => Handler<Context<E>>;
12
+ //# sourceMappingURL=routeHelpers.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"routeHelpers.d.ts","sourceRoot":"","sources":["../../src/core/routeHelpers.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,sBAAsB,CAAC;AAC3D,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,0BAA0B,CAAC;AAExD;;;;;;GAMG;AACH,eAAO,MAAM,WAAW,QAAS,GAAG,KAAG,OAAuC,CAAC;AAE/E,eAAO,MAAM,YAAY,GACtB,CAAC,MAAM,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,EAAE,GAAG,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,KAAG,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,CA6C9E,CAAC"}
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Attempts to determine whether we're running a development or production server.
3
+ *
4
+ * Currently this is done by checking whether the hostname is localhost, which is not perfect
5
+ * but allows you to test production behaviour by connecting to `127.0.0.1` and
6
+ * is easy to do without messing with environment variables.
7
+ */
8
+ export const isDevServer = (url) => url.hostname === "localhost";
9
+ export const routeHandler = (rs) => async (req, ctx) => {
10
+ const routes = await rs;
11
+ const method = req.method.toUpperCase();
12
+ const isDev = ctx.mode === "generator" || ctx.environment === "development";
13
+ let urlMatched;
14
+ let params = {};
15
+ const findRoute = (method) => routes.find((r) => {
16
+ const match = r.pattern.exec(req.url);
17
+ if (!match)
18
+ return false;
19
+ urlMatched = r.name;
20
+ if ((r.method === method || r.method === "all") && typeof r.handler === "function") {
21
+ params = match.pathname.groups;
22
+ return true;
23
+ }
24
+ });
25
+ const route = findRoute(method) ?? (method === "HEAD" ? findRoute("GET") : undefined);
26
+ if (route) {
27
+ if (route.pregenerate && !isDev && ctx.mode === "server") {
28
+ return new Response("404 Route was hit on non-localhost but has `pregenerate` set. " +
29
+ "Did you forget to run `mastro/generator --only-pregenerate` as a build step?", { status: 404 });
30
+ }
31
+ let res = await route.handler(req, { ...ctx, params });
32
+ if (!(res instanceof Response)) {
33
+ throw Error(`${method} handler in ${route.name} ${noResponseErr}`);
34
+ }
35
+ if (method === "HEAD") {
36
+ res.body?.cancel().catch(() => { });
37
+ res = new Response(null, res);
38
+ }
39
+ return isDev ? Object.assign(res, { routeName: route.name }) : res;
40
+ }
41
+ else if (urlMatched) {
42
+ const msg = `405 Method Not Allowed\n\nNo ${method} handler found`;
43
+ const m = isDev ? ` by ${urlMatched}\n\nsee https://mastrojs.github.io/docs/routing/` : "";
44
+ return new Response(msg + m, { status: 405 });
45
+ }
46
+ else {
47
+ const res = new Response("404 Not Found", { status: 404 });
48
+ return isDev ? Object.assign(res, { error: "No route match" }) : res;
49
+ }
50
+ };
51
+ const noResponseErr = "must return a Response object. Did you forget \`htmlToResponse\`?";
@@ -0,0 +1,16 @@
1
+ /**
2
+ * This module contains all functions related to static site generation.
3
+ * It is used both by the [vscode-extension](../../../vscode-extension/) and
4
+ * by the [static site generator on the CLI](https://mastrojs.github.io/docs/install-setup/#generate-a-static-site).
5
+ * @module
6
+ */
7
+ import type { Mastro } from "./mastro.ts";
8
+ import type { Simplify } from "./types/mastro.d.ts";
9
+ import type { Context, GeneratorCtxSimple } from "./types/middleware.d.ts";
10
+ /**
11
+ * Generate all pages for the static site and write them to disk.
12
+ *
13
+ * Can not be used in the VSCode extension.
14
+ */
15
+ export declare const generate: <E extends unknown[], L>(app: Mastro<E, L>, opts?: Simplify<Partial<GeneratorCtxSimple<Context<E>>>>) => Promise<boolean>;
16
+ //# sourceMappingURL=generator.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"generator.d.ts","sourceRoot":"","sources":["../src/generator.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAOH,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAG1C,OAAO,KAAK,EAAkB,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AACpE,OAAO,KAAK,EAAE,OAAO,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAE3E;;;;GAIG;AACH,eAAO,MAAM,QAAQ,GAAU,CAAC,SAAS,OAAO,EAAE,EAAE,CAAC,OAC9C,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,SACX,QAAQ,CAAC,OAAO,CAAC,kBAAkB,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,KACtD,OAAO,CAAC,OAAO,CAgDjB,CAAC"}
@@ -0,0 +1,124 @@
1
+ /**
2
+ * This module contains all functions related to static site generation.
3
+ * It is used both by the [vscode-extension](../../../vscode-extension/) and
4
+ * by the [static site generator on the CLI](https://mastrojs.github.io/docs/install-setup/#generate-a-static-site).
5
+ * @module
6
+ */
7
+ import fs from "node:fs/promises";
8
+ import { dirname, join, posix } from "node:path";
9
+ import { urlPathToFilePath } from "./core/fsHelpers.js";
10
+ import { routeHandler } from "./core/routeHelpers.js";
11
+ import { chainMiddlewares } from "./middleware.js";
12
+ import { middlewares } from "./servers/server.js";
13
+ /**
14
+ * Generate all pages for the static site and write them to disk.
15
+ *
16
+ * Can not be used in the VSCode extension.
17
+ */
18
+ export const generate = async (app, opts = {}) => {
19
+ const ctx = {
20
+ baseUrl: opts.baseUrl || "http://127.0.0.1",
21
+ extras: (opts.extras || []),
22
+ onlyPregenerate: !!opts.onlyPregenerate,
23
+ outFolder: opts.outFolder || "generated",
24
+ mode: "generator",
25
+ };
26
+ const { outFolder } = ctx;
27
+ const resetP = fs.rm(outFolder, { force: true, recursive: true }).then(() => fs.mkdir(outFolder));
28
+ const ms = app.getMiddlewares();
29
+ if (ms.every((m) => m.name !== "staticFiles")) {
30
+ // when we get passed an app for Cloudflare Workers or similar, we add staticFiles etc.
31
+ console.info("Did not find a staticFiles middleware, adding defaultMiddlewares.\n");
32
+ ms.unshift(...middlewares);
33
+ }
34
+ const routes = await app.getRoutes();
35
+ const handler = chainMiddlewares(ms, routeHandler(routes));
36
+ await resetP;
37
+ await Promise.all(ms.map((m) => ("beforeGenerate" in m ? m.beforeGenerate?.(ctx) : null)));
38
+ let completeSuccess = true;
39
+ for (const path of await getPaths(ctx, ...ms, routePaths(routes))) {
40
+ // TODO: parallelize without opening too many file handles at once
41
+ const url = new URL(path, ctx.baseUrl);
42
+ const context = { ...ctx, locals: {}, params: {} };
43
+ const { response, outFilePath } = await generatePage(handler, url, context);
44
+ if (response.ok) {
45
+ const outPath = join(outFolder, outFilePath);
46
+ await fs.mkdir(dirname(outPath), { recursive: true });
47
+ if (response.body) {
48
+ await fs.writeFile(outPath, response.body);
49
+ }
50
+ else {
51
+ console.warn(`\nWARNING: ${path} returned no body (HTTP ${response.status})\n.`);
52
+ }
53
+ }
54
+ else if (response.status !== 404) {
55
+ completeSuccess = false;
56
+ }
57
+ }
58
+ if (completeSuccess) {
59
+ await Promise.all(ms.map((m) => ("afterGenerate" in m ? m.afterGenerate?.(ctx) : null)));
60
+ console.info(`Generated static site and wrote to \`${outFolder}\` folder.`);
61
+ }
62
+ return completeSuccess;
63
+ };
64
+ /**
65
+ * call getStaticPaths of all middlewares and set things up for the fingerprintAssets middleware.
66
+ */
67
+ const getPaths = async (ctx, ...middlewares) => {
68
+ globalThis._mastroAssets = {};
69
+ const paths = middlewares.flatMap(async (m) => m.getStaticPaths ? validateStaticPaths(m.name, await m.getStaticPaths(ctx)) : []);
70
+ const assetPaths = [];
71
+ const otherPaths = [];
72
+ for (const p of (await Promise.all(paths)).flat()) {
73
+ (p.startsWith("/_assets/") ? assetPaths : otherPaths).push(p);
74
+ }
75
+ return assetPaths.concat(otherPaths);
76
+ };
77
+ const generatePage = async (handler, url, ctx) => {
78
+ const req = new Request(url);
79
+ const response = await handler(req, ctx);
80
+ const filename = parseContentDisposition(response.headers.get("Content-Disposition"));
81
+ const directory = url.pathname.slice(0, url.pathname.lastIndexOf("/") + 1);
82
+ const path = filename ? directory + filename : url.pathname;
83
+ const outFilePath = urlPathToFilePath(path.endsWith("/") ? `${path}index.html` : path);
84
+ return { response, outFilePath };
85
+ };
86
+ const parseContentDisposition = (val) => val?.match(/filename="?([^";]+)"?/i)?.[1];
87
+ const validateStaticPaths = (name, paths) => {
88
+ const prefix = `${name}"#getStaticPaths`;
89
+ const notStringMsg = " must return an array of strings";
90
+ if (!Array.isArray(paths))
91
+ throw Error(prefix + notStringMsg);
92
+ for (const path of paths) {
93
+ if (typeof path !== "string")
94
+ throw Error(prefix + notStringMsg);
95
+ if (path[0] !== "/")
96
+ throw Error(prefix + ": paths must start with a slash (/)");
97
+ if (path.includes("#") || path.includes("?") || path.includes("\\")) {
98
+ throw Error(`${prefix} must return encoded URL paths. Use encodeURIComponent.`);
99
+ }
100
+ if (!path.endsWith("/") && !posix.extname(path) && !path.startsWith("/.well-known/")) {
101
+ console.warn(`\nWARNING: ${name} has path ${path} without file extension.
102
+ Consider renaming route to e.g. ${name.replace(".server", ".html.server")}\n`);
103
+ }
104
+ }
105
+ return paths;
106
+ };
107
+ const routePaths = (routes) => ({
108
+ name: "router",
109
+ getStaticPaths: async (ctx) => {
110
+ const paths = (ctx.onlyPregenerate ? routes.filter((r) => r.pregenerate) : routes)
111
+ .filter((r) => r.method === "GET" || r.method === "all")
112
+ .map(async (r) => {
113
+ if (typeof r.getStaticPaths === "function")
114
+ return r.getStaticPaths();
115
+ if (hasRouteParams.test(r.pattern.pathname))
116
+ throw Error(r.name + staticPathErrMsg);
117
+ return r.pattern.pathname.replace(/\\(.)/g, "$1"); // unescape URLPattern syntax
118
+ });
119
+ return (await Promise.all(paths.reverse())).flat();
120
+ },
121
+ });
122
+ // URLPattern parameters, wildcards, and groups require concrete paths:
123
+ const hasRouteParams = /(?<!\\)[:*{(]/;
124
+ const staticPathErrMsg = " should provide a getStaticPaths function returning an array of strings.";