@octanejs/email-cli 0.0.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Dominic Gannaway
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,28 @@
1
+ # @octanejs/email-cli
2
+
3
+ Develop and compile Octane `.tsrx` email templates.
4
+
5
+ ## Installation
6
+
7
+ ```sh
8
+ npm install --save-dev @octanejs/email-cli
9
+ pnpm add --save-dev @octanejs/email-cli
10
+ ```
11
+
12
+ ```sh
13
+ octane-email dev --dir ./emails
14
+ ```
15
+
16
+ The development server lists nested templates at `http://127.0.0.1:3000`, renders a
17
+ selected template through `@octanejs/email`, serves `emails/static`, and reloads the
18
+ page when templates or assets change. Compilation and rendering errors appear in the
19
+ preview while the server stays running. Use `--host` and `--port` to change its address.
20
+
21
+ ```sh
22
+ octane-email export --dir ./emails --outDir ./out
23
+ ```
24
+
25
+ Each template must default-export an Octane component. The export command retains nested
26
+ paths, renders through `@octanejs/email`, and copies `emails/static` to `out/static`.
27
+
28
+ Options include `--pretty` and `--extension <suffix>`.
package/package.json ADDED
@@ -0,0 +1,47 @@
1
+ {
2
+ "name": "@octanejs/email-cli",
3
+ "version": "0.0.1",
4
+ "license": "MIT",
5
+ "type": "module",
6
+ "engines": {
7
+ "node": ">=22.22.2"
8
+ },
9
+ "description": "Compile, preview, and export Octane email templates.",
10
+ "publishConfig": {
11
+ "access": "public"
12
+ },
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "git+https://github.com/octanejs/octane.git",
16
+ "directory": "packages/email-cli"
17
+ },
18
+ "bin": {
19
+ "octane-email": "./src/cli.js"
20
+ },
21
+ "exports": {
22
+ ".": "./src/index.js",
23
+ "./preview": "./src/preview/server.js"
24
+ },
25
+ "files": [
26
+ "src",
27
+ "README.md"
28
+ ],
29
+ "dependencies": {
30
+ "vite": "^8.1.5",
31
+ "@octanejs/email": "0.0.1"
32
+ },
33
+ "peerDependencies": {
34
+ "octane": "0.1.50"
35
+ },
36
+ "devDependencies": {
37
+ "@types/node": "^24.13.3",
38
+ "typescript": "^5.9.3",
39
+ "vitest": "^4.1.10",
40
+ "octane": "0.1.50"
41
+ },
42
+ "scripts": {
43
+ "test": "vitest run --config vitest.config.ts",
44
+ "typecheck": "tsc --noEmit",
45
+ "dev": "node ./src/cli.js dev"
46
+ }
47
+ }
package/src/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/src/cli.js ADDED
@@ -0,0 +1,57 @@
1
+ #!/usr/bin/env node
2
+ import { parseArgs } from 'node:util';
3
+ import { exportTemplates } from './export.js';
4
+ import { startPreviewServer } from './preview/server.js';
5
+
6
+ const { positionals, values } = parseArgs({
7
+ allowPositionals: true,
8
+ options: {
9
+ dir: { type: 'string', short: 'd', default: './emails' },
10
+ outDir: { type: 'string', default: './out' },
11
+ extension: { type: 'string', short: 'e' },
12
+ pretty: { type: 'boolean', short: 'p', default: false },
13
+ port: { type: 'string', default: '3000' },
14
+ host: { type: 'string', default: '127.0.0.1' },
15
+ help: { type: 'boolean', short: 'h', default: false },
16
+ },
17
+ });
18
+
19
+ const command = positionals[0];
20
+
21
+ if (values.help || (command !== 'export' && command !== 'dev')) {
22
+ console.log(`Usage: octane-email <dev|export> [options]
23
+
24
+ Options:
25
+ -d, --dir <path> email templates directory (default: ./emails)
26
+ --host <host> preview host (default: 127.0.0.1)
27
+ --port <port> preview port (default: 3000)
28
+ --outDir <path> rendered output directory (default: ./out)
29
+ -e, --extension <suffix> rendered file extension (default: html)
30
+ -p, --pretty format rendered markup`);
31
+ process.exitCode = values.help ? 0 : 1;
32
+ } else if (command === 'export') {
33
+ try {
34
+ const result = await exportTemplates(values.outDir, values.dir, {
35
+ extension: values.extension,
36
+ pretty: values.pretty,
37
+ });
38
+ console.log(
39
+ `Exported ${result.templates.length} email${result.templates.length === 1 ? '' : 's'} to ${result.outputDirectory}`,
40
+ );
41
+ } catch (error) {
42
+ console.error(error instanceof Error ? error.message : error);
43
+ process.exitCode = 1;
44
+ }
45
+ } else {
46
+ try {
47
+ const port = Number(values.port);
48
+ if (!Number.isInteger(port) || port < 0 || port > 65_535) {
49
+ throw new Error(`Invalid port: ${values.port}`);
50
+ }
51
+ const server = await startPreviewServer({ directory: values.dir, host: values.host, port });
52
+ console.log(`Octane email preview available at ${server.url}`);
53
+ } catch (error) {
54
+ console.error(error instanceof Error ? error.message : error);
55
+ process.exitCode = 1;
56
+ }
57
+ }
@@ -0,0 +1,19 @@
1
+ export type ExportedTemplate = {
2
+ sourcePath: string;
3
+ relativePath: string;
4
+ };
5
+
6
+ export type ExportTemplatesOptions = {
7
+ pretty?: boolean;
8
+ extension?: string;
9
+ };
10
+
11
+ /**
12
+ * Compile and export every default-exported `.tsrx` email beneath `emailsDirectoryPath`.
13
+ * Nested paths are retained and `static/` is copied without entering the compiler graph.
14
+ */
15
+ export function exportTemplates(
16
+ outputDirectoryPath: string,
17
+ emailsDirectoryPath: string,
18
+ options?: ExportTemplatesOptions,
19
+ ): Promise<{ templates: ExportedTemplate[]; outputDirectory: string }>;
package/src/export.js ADDED
@@ -0,0 +1,114 @@
1
+ import { cp, mkdir, rm, writeFile } from 'node:fs/promises';
2
+ import { dirname, extname, isAbsolute, join, relative, resolve, sep } from 'node:path';
3
+ import { octane } from 'octane/compiler/vite';
4
+ import { createServer } from 'vite';
5
+ import { discoverTemplatePaths, isDirectory } from './templates.js';
6
+
7
+ /** @typedef {{ sourcePath: string, relativePath: string }} ExportedTemplate */
8
+ /** @typedef {{ pretty?: boolean, extension?: string }} ExportTemplatesOptions */
9
+
10
+ /**
11
+ * Compile and export every default-exported `.tsrx` email beneath `emailsDirectoryPath`.
12
+ * Nested paths are retained and `static/` is copied without entering the compiler graph.
13
+ *
14
+ * @param {string} outputDirectoryPath
15
+ * @param {string} emailsDirectoryPath
16
+ * @param {ExportTemplatesOptions} [options]
17
+ * @returns {Promise<{ templates: ExportedTemplate[], outputDirectory: string }>}
18
+ */
19
+ export async function exportTemplates(outputDirectoryPath, emailsDirectoryPath, options = {}) {
20
+ const sourceDirectory = resolve(emailsDirectoryPath);
21
+ const outputDirectory = resolve(outputDirectoryPath);
22
+ await assertDirectory(sourceDirectory);
23
+ assertSeparateDirectories(sourceDirectory, outputDirectory);
24
+ const extension = normalizeExtension(options.extension ?? '.html');
25
+
26
+ const templatePaths = (await discoverTemplatePaths(sourceDirectory)).sort((left, right) =>
27
+ left.localeCompare(right),
28
+ );
29
+ await rm(outputDirectory, { recursive: true, force: true });
30
+ await mkdir(outputDirectory, { recursive: true });
31
+
32
+ const server = await createServer({
33
+ root: sourceDirectory,
34
+ configFile: false,
35
+ appType: 'custom',
36
+ logLevel: 'silent',
37
+ plugins: [octane({ hmr: false, ssr: true })],
38
+ server: { middlewareMode: true },
39
+ });
40
+
41
+ /** @type {ExportedTemplate[]} */
42
+ const templates = [];
43
+ try {
44
+ const emailLibrary = await server.ssrLoadModule('@octanejs/email');
45
+ if (typeof emailLibrary.render !== 'function') {
46
+ throw new Error('@octanejs/email does not export render()');
47
+ }
48
+
49
+ for (const sourcePath of templatePaths) {
50
+ const emailModule = await server.ssrLoadModule(sourcePath);
51
+ if (typeof emailModule.default !== 'function') {
52
+ throw new TypeError(
53
+ `${relative(sourceDirectory, sourcePath)} must default-export an email component`,
54
+ );
55
+ }
56
+
57
+ const sourceRelativePath = relative(sourceDirectory, sourcePath);
58
+ const relativePath = replaceExtension(sourceRelativePath, extension);
59
+ const destination = join(outputDirectory, relativePath);
60
+ await mkdir(dirname(destination), { recursive: true });
61
+ const html = await emailLibrary.render(emailModule.default, undefined, {
62
+ pretty: options.pretty,
63
+ });
64
+ await writeFile(destination, html);
65
+ templates.push({ sourcePath, relativePath });
66
+ }
67
+ } finally {
68
+ await server.close();
69
+ }
70
+
71
+ const staticDirectory = join(sourceDirectory, 'static');
72
+ if (await isDirectory(staticDirectory)) {
73
+ await cp(staticDirectory, join(outputDirectory, 'static'), { recursive: true });
74
+ }
75
+
76
+ return { templates, outputDirectory };
77
+ }
78
+
79
+ /** @param {string} path */
80
+ async function assertDirectory(path) {
81
+ if (!(await isDirectory(path))) throw new Error(`Email directory does not exist: ${path}`);
82
+ }
83
+
84
+ /** @param {string} sourceDirectory @param {string} outputDirectory */
85
+ function assertSeparateDirectories(sourceDirectory, outputDirectory) {
86
+ if (
87
+ containsPath(sourceDirectory, outputDirectory) ||
88
+ containsPath(outputDirectory, sourceDirectory)
89
+ ) {
90
+ throw new Error('Output and email source directories cannot contain each other');
91
+ }
92
+ }
93
+
94
+ /** @param {string} parent @param {string} child */
95
+ function containsPath(parent, child) {
96
+ const childPath = relative(parent, child);
97
+ return (
98
+ childPath === '' ||
99
+ (!childPath.startsWith(`..${sep}`) && childPath !== '..' && !isAbsolute(childPath))
100
+ );
101
+ }
102
+
103
+ /** @param {string} extension */
104
+ function normalizeExtension(extension) {
105
+ if (!/^\.?[A-Za-z0-9]+$/.test(extension)) {
106
+ throw new Error(`Invalid output extension: ${extension}`);
107
+ }
108
+ return extension.startsWith('.') ? extension : `.${extension}`;
109
+ }
110
+
111
+ /** @param {string} path @param {string} extension */
112
+ function replaceExtension(path, extension) {
113
+ return path.slice(0, -extname(path).length) + extension;
114
+ }
package/src/index.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ export { exportTemplates } from './export.js';
2
+ export { startPreviewServer } from './preview/server.js';
package/src/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export { exportTemplates } from './export.js';
2
+ export { startPreviewServer } from './preview/server.js';
@@ -0,0 +1,12 @@
1
+ export type PreviewServerOptions = {
2
+ directory?: string;
3
+ host?: string;
4
+ port?: number;
5
+ logLevel?: 'error' | 'warn' | 'info' | 'silent';
6
+ };
7
+
8
+ /** Start an Octane-native development server for `.tsrx` email templates. */
9
+ export function startPreviewServer(options?: PreviewServerOptions): Promise<{
10
+ url: string;
11
+ close(): Promise<void>;
12
+ }>;
@@ -0,0 +1,182 @@
1
+ import { createServer as createHttpServer } from 'node:http';
2
+ import { extname, join, relative, resolve, sep } from 'node:path';
3
+ import { octane } from 'octane/compiler/vite';
4
+ import { createServer as createViteServer } from 'vite';
5
+ import { discoverTemplatePaths, isDirectory } from '../templates.js';
6
+
7
+ /** @typedef {{ directory?: string, host?: string, port?: number, logLevel?: 'error' | 'warn' | 'info' | 'silent' }} PreviewServerOptions */
8
+
9
+ /**
10
+ * Start an Octane-native development server for `.tsrx` email templates.
11
+ *
12
+ * @param {PreviewServerOptions} [options]
13
+ */
14
+ export async function startPreviewServer(options = {}) {
15
+ const sourceDirectory = resolve(options.directory ?? './emails');
16
+ if (!(await isDirectory(sourceDirectory))) {
17
+ throw new Error(`Email directory does not exist: ${sourceDirectory}`);
18
+ }
19
+
20
+ const httpServer = createHttpServer();
21
+ const vite = await createViteServer({
22
+ root: sourceDirectory,
23
+ configFile: false,
24
+ appType: 'custom',
25
+ logLevel: options.logLevel ?? 'info',
26
+ plugins: [octane({ ssr: true })],
27
+ server: {
28
+ hmr: { server: httpServer },
29
+ middlewareMode: true,
30
+ },
31
+ });
32
+ /** @param {string} path */
33
+ const reloadPreview = (path) => {
34
+ if (!isPreviewFile(sourceDirectory, path)) return;
35
+ vite.moduleGraph.invalidateAll();
36
+ vite.ws.send({ type: 'full-reload' });
37
+ };
38
+ vite.watcher.on('add', reloadPreview);
39
+ vite.watcher.on('change', reloadPreview);
40
+ vite.watcher.on('unlink', reloadPreview);
41
+
42
+ vite.middlewares.use(async (request, response, next) => {
43
+ if (request.method !== 'GET' && request.method !== 'HEAD') return next();
44
+
45
+ try {
46
+ const url = new URL(request.url ?? '/', 'http://preview.local');
47
+ if (url.pathname === '/') {
48
+ const templates = await discoverTemplates(sourceDirectory);
49
+ return sendHtml(response, 200, renderIndex(templates));
50
+ }
51
+
52
+ if (url.pathname.startsWith('/preview/')) {
53
+ const requestedName = decodeURIComponent(url.pathname.slice('/preview/'.length));
54
+ const templates = await discoverTemplates(sourceDirectory);
55
+ const template = templates.find((entry) => entry.name === requestedName);
56
+ if (!template) return sendHtml(response, 404, renderError('Template not found'));
57
+
58
+ const emailModule = await vite.ssrLoadModule(template.sourcePath);
59
+ if (typeof emailModule.default !== 'function') {
60
+ throw new TypeError(`${template.relativePath} must default-export an email component`);
61
+ }
62
+ const emailLibrary = await vite.ssrLoadModule('@octanejs/email');
63
+ if (typeof emailLibrary.render !== 'function') {
64
+ throw new Error('@octanejs/email does not export render()');
65
+ }
66
+ const markup = await emailLibrary.render(emailModule.default);
67
+ return sendHtml(response, 200, enableLiveReload(markup));
68
+ }
69
+ } catch (error) {
70
+ vite.ssrFixStacktrace(/** @type {Error} */ (error));
71
+ return sendHtml(response, 500, renderError(formatError(error)));
72
+ }
73
+
74
+ return next();
75
+ });
76
+
77
+ httpServer.on('request', (request, response) => {
78
+ try {
79
+ new URL(request.url ?? '/', 'http://preview.local');
80
+ } catch (error) {
81
+ return sendHtml(response, 500, renderError(formatError(error)));
82
+ }
83
+ vite.middlewares(request, response);
84
+ });
85
+ try {
86
+ await new Promise((resolvePromise, reject) => {
87
+ httpServer.once('error', reject);
88
+ httpServer.listen(options.port ?? 3000, options.host ?? '127.0.0.1', () => {
89
+ httpServer.off('error', reject);
90
+ resolvePromise(undefined);
91
+ });
92
+ });
93
+ } catch (error) {
94
+ await vite.close();
95
+ throw error;
96
+ }
97
+
98
+ const address = httpServer.address();
99
+ if (!address || typeof address === 'string')
100
+ throw new Error('Preview server did not bind to TCP');
101
+ const advertisedHost = address.address === '::' ? 'localhost' : address.address;
102
+ const url = `http://${advertisedHost.includes(':') ? `[${advertisedHost}]` : advertisedHost}:${address.port}/`;
103
+ let closed = false;
104
+
105
+ return {
106
+ url,
107
+ async close() {
108
+ if (closed) return;
109
+ closed = true;
110
+ await vite.close();
111
+ if (httpServer.listening) {
112
+ await new Promise((resolvePromise, reject) =>
113
+ httpServer.close((error) => (error ? reject(error) : resolvePromise(undefined))),
114
+ );
115
+ }
116
+ },
117
+ };
118
+ }
119
+
120
+ /** @param {string} directory */
121
+ async function discoverTemplates(directory, rootDirectory = directory) {
122
+ return (await discoverTemplatePaths(directory))
123
+ .map((sourcePath) => {
124
+ const relativePath = relative(resolve(rootDirectory), sourcePath).split(sep).join('/');
125
+ return { sourcePath, relativePath, name: relativePath.slice(0, -'.tsrx'.length) };
126
+ })
127
+ .sort((left, right) => left.name.localeCompare(right.name));
128
+ }
129
+
130
+ /** @param {import('node:http').ServerResponse} response @param {number} status @param {string} html */
131
+ function sendHtml(response, status, html) {
132
+ response.statusCode = status;
133
+ response.setHeader('Content-Type', 'text/html; charset=utf-8');
134
+ response.end(html);
135
+ }
136
+
137
+ /** @param {{ name: string }[]} templates */
138
+ function renderIndex(templates) {
139
+ const items = templates.length
140
+ ? templates
141
+ .map(
142
+ (template) =>
143
+ `<li><a href="/preview/${encodeURI(template.name)}">${escapeHtml(template.name)}</a></li>`,
144
+ )
145
+ .join('')
146
+ : '<li>No .tsrx email templates found.</li>';
147
+ return `<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>Octane Email Preview</title><style>body{font:16px system-ui;max-width:52rem;margin:3rem auto;padding:0 1.5rem;color:#18181b}a{color:#2563eb}li{margin:.75rem 0}</style></head><body><h1>Octane Email Preview</h1><ul>${items}</ul><script type="module" src="/@vite/client"></script></body></html>`;
148
+ }
149
+
150
+ /** @param {string} markup */
151
+ function enableLiveReload(markup) {
152
+ const client = '<script type="module" src="/@vite/client"></script>';
153
+ return markup.includes('</body>')
154
+ ? markup.replace('</body>', `${client}</body>`)
155
+ : `${markup}${client}`;
156
+ }
157
+
158
+ /** @param {string} message */
159
+ function renderError(message) {
160
+ return `<!doctype html><html><head><meta charset="utf-8"><title>Preview error</title></head><body><h1>Unable to render email</h1><pre style="white-space:pre-wrap">${escapeHtml(message)}</pre><script type="module" src="/@vite/client"></script></body></html>`;
161
+ }
162
+
163
+ /** @param {unknown} error */
164
+ function formatError(error) {
165
+ return error instanceof Error ? error.stack || error.message : String(error);
166
+ }
167
+
168
+ /** @param {string} value */
169
+ function escapeHtml(value) {
170
+ return value
171
+ .replaceAll('&', '&amp;')
172
+ .replaceAll('<', '&lt;')
173
+ .replaceAll('>', '&gt;')
174
+ .replaceAll('"', '&quot;');
175
+ }
176
+
177
+ /** @param {string} sourceDirectory @param {string} path */
178
+ function isPreviewFile(sourceDirectory, path) {
179
+ const sourceRelativePath = relative(sourceDirectory, path);
180
+ if (sourceRelativePath === '' || sourceRelativePath.startsWith(`..${sep}`)) return false;
181
+ return extname(path) === '.tsrx' || sourceRelativePath.split(sep)[0] === 'static';
182
+ }
@@ -0,0 +1,2 @@
1
+ export function discoverTemplatePaths(directory: string): Promise<string[]>;
2
+ export function isDirectory(path: string): Promise<boolean>;
@@ -0,0 +1,26 @@
1
+ import { readdir, stat } from 'node:fs/promises';
2
+ import { extname, join } from 'node:path';
3
+
4
+ /** @param {string} directory */
5
+ export async function discoverTemplatePaths(directory) {
6
+ /** @type {string[]} */
7
+ const templates = [];
8
+ for (const entry of await readdir(directory, { withFileTypes: true })) {
9
+ if (entry.name === 'static' || entry.name === 'node_modules' || entry.name.startsWith('.'))
10
+ continue;
11
+ const path = join(directory, entry.name);
12
+ if (entry.isDirectory()) templates.push(...(await discoverTemplatePaths(path)));
13
+ else if (entry.isFile() && extname(entry.name) === '.tsrx') templates.push(path);
14
+ }
15
+ return templates;
16
+ }
17
+
18
+ /** @param {string} path */
19
+ export async function isDirectory(path) {
20
+ try {
21
+ return (await stat(path)).isDirectory();
22
+ } catch (error) {
23
+ if (/** @type {NodeJS.ErrnoException} */ (error).code === 'ENOENT') return false;
24
+ throw error;
25
+ }
26
+ }