create-clarity 0.1.3 → 0.2.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.
@@ -96,7 +96,7 @@ async function main() {
96
96
  // ── clarity-js dependency source ───────────────────────────────────────────
97
97
  const clarityDep = argv.flags.local
98
98
  ? `file:${path.resolve(process.cwd(), argv.flags.local)}`
99
- : `^0.6.3`;
99
+ : `^0.12.0`;
100
100
 
101
101
  const options = {
102
102
  projectName,
package/lib/templates.js CHANGED
@@ -34,8 +34,12 @@ function buildFiles(opts) {
34
34
  preview: 'vite preview',
35
35
  };
36
36
  if (opts.ssr) {
37
- scripts['build:server'] = `vite build --ssr src/entry-server.${ext}`;
38
- scripts.serve = `node server.${ext === 'ts' ? 'js' : 'js'}`;
37
+ // Vite's SSR setup: one server.js for dev (Vite middleware, renders on each request)
38
+ // and production (serves dist/client, renders with dist/server).
39
+ scripts.dev = 'node server.js';
40
+ scripts.build = `vite build --outDir dist/client && vite build --ssr src/entry-server.${ext} --outDir dist/server`;
41
+ scripts.serve = 'node server.js --prod';
42
+ delete scripts.preview;
39
43
  }
40
44
  if (opts.testing) scripts.test = 'node --test test/';
41
45
  if (opts.typescript) scripts.typecheck = 'tsc --noEmit';
@@ -72,7 +76,7 @@ export default defineConfig({
72
76
  <link rel="stylesheet" href="/src/styles.css" />
73
77
  </head>
74
78
  <body>
75
- <div id="app"></div>
79
+ <div id="app">${opts.ssr ? '<!--app-html-->' : ''}</div>
76
80
  <script type="module" src="/src/main.${ext}"></script>
77
81
  </body>
78
82
  </html>
@@ -91,8 +95,17 @@ nav a { margin-right: 1rem; }
91
95
  if (opts.router) {
92
96
  // File-based routing: the Vite plugin (scanPages) generates the route table
93
97
  // from pages/ and exposes a ready-to-mount Routes component.
94
- files[`src/main.${ext}`] =
95
- `import { mount } from '@ozsarman/clarityjs';
98
+ files[`src/main.${ext}`] = opts.ssr
99
+ ? `import { hydrateRoot } from '@ozsarman/clarityjs/hydrate';
100
+ import { Routes } from 'virtual:clarity-pages';
101
+ ${opts.i18n ? "import './i18n.js';\n" : ''}
102
+ // Load this URL's page first so the client renders the same page the server sent,
103
+ // then take over the server HTML.
104
+ Routes.preload(location.pathname).then(() => {
105
+ hydrateRoot(document.getElementById('app'), Routes);
106
+ });
107
+ `
108
+ : `import { mount } from '@ozsarman/clarityjs';
96
109
  import { Routes } from 'virtual:clarity-pages';
97
110
  ${opts.i18n ? "import './i18n.js';\n" : ''}
98
111
  const container = document.getElementById('app');
@@ -103,8 +116,14 @@ mount(Routes, container);
103
116
  files['pages/[slug].clarity'] = dynamicPage(opts);
104
117
  files['pages/not-found.clarity'] = notFoundPage(opts);
105
118
  } else {
106
- files[`src/main.${ext}`] =
107
- `import { mount } from '@ozsarman/clarityjs';
119
+ files[`src/main.${ext}`] = opts.ssr
120
+ ? `import { hydrateRoot } from '@ozsarman/clarityjs/hydrate';
121
+ import { App } from './App.clarity';
122
+ ${opts.i18n ? "import './i18n.js';\n" : ''}
123
+ // Take over the HTML the server rendered.
124
+ hydrateRoot(document.getElementById('app'), App);
125
+ `
126
+ : `import { mount } from '@ozsarman/clarityjs';
108
127
  import { App } from './App.clarity';
109
128
  ${opts.i18n ? "import './i18n.js';\n" : ''}
110
129
  const container = document.getElementById('app');
@@ -115,30 +134,97 @@ mount(App, container);
115
134
 
116
135
  // ── SSR extras ───────────────────────────────────────────────────────────--
117
136
  if (opts.ssr) {
118
- files[`src/entry-server.${ext}`] =
119
- `import { renderToString } from '@ozsarman/clarityjs/ssr';
137
+ files[`src/entry-server.${ext}`] = opts.router
138
+ ? `import { renderToString } from '@ozsarman/clarityjs/ssr';
139
+ import { setServerPath } from '@ozsarman/clarityjs/router';
140
+ import { Routes } from 'virtual:clarity-pages';
141
+
142
+ // Called by server.js for every page request.
143
+ export async function render(url${opts.typescript ? ': string' : ''}) {
144
+ setServerPath(url); // the router renders the page for this URL
145
+ await Routes.preload(url); // load the page module before rendering
146
+ return renderToString(Routes); // { html, state }
147
+ }
148
+ `
149
+ : `import { renderToString } from '@ozsarman/clarityjs/ssr';
120
150
  import { App } from './App.clarity';
121
151
 
122
- // Called by the server (server.js) to produce HTML for each request.
123
- export function render() {
124
- return renderToString(App());
152
+ // Called by server.js for every page request.
153
+ export async function render(_url${opts.typescript ? ': string' : ''}) {
154
+ return renderToString(App); // { html, state }
125
155
  }
126
156
  `;
127
157
  files['server.js'] =
128
- `import { createServer } from 'node:http';
129
- import { render } from './src/entry-server.${ext === 'ts' ? 'js' : 'js'}';
130
-
131
- // Minimal SSR server. In production, build with \`npm run build:server\`
132
- // and serve the compiled output. This dev server renders on each request.
133
- const PORT = process.env.PORT || 5173;
134
-
135
- createServer((req, res) => {
136
- const appHtml = render();
137
- res.setHeader('content-type', 'text/html');
138
- res.end(\`<!DOCTYPE html>
139
- <html><head><meta charset="utf-8"><title>${opts.projectName}</title></head>
140
- <body><div id="app">\${appHtml}</div></body></html>\`);
141
- }).listen(PORT, () => console.log('SSR server on http://localhost:' + PORT));
158
+ `// SSR server.
159
+ // npm run dev → Vite in middleware mode, renders each request from source
160
+ // npm run build → dist/client (browser) + dist/server (render function)
161
+ // npm run serve → serves dist/client and renders with dist/server
162
+ import fs from 'node:fs/promises';
163
+ import http from 'node:http';
164
+ import path from 'node:path';
165
+ import { fileURLToPath } from 'node:url';
166
+ import { safeJSONForScript } from '@ozsarman/clarityjs/ssr';
167
+
168
+ const root = path.dirname(fileURLToPath(import.meta.url));
169
+ const prod = process.argv.includes('--prod') || process.env.NODE_ENV === 'production';
170
+ const PORT = Number(process.env.PORT) || 5173;
171
+ const TYPES = { '.js': 'text/javascript', '.css': 'text/css', '.svg': 'image/svg+xml', '.png': 'image/png',
172
+ '.jpg': 'image/jpeg', '.webp': 'image/webp', '.ico': 'image/x-icon', '.json': 'application/json', '.woff2': 'font/woff2' };
173
+
174
+ let vite = null;
175
+ let prodTemplate = '';
176
+ let prodRender = null;
177
+ if (prod) {
178
+ prodTemplate = await fs.readFile(path.join(root, 'dist/client/index.html'), 'utf8');
179
+ prodRender = (await import('./dist/server/entry-server.js')).render;
180
+ } else {
181
+ const { createServer } = await import('vite');
182
+ vite = await createServer({ root, server: { middlewareMode: true }, appType: 'custom' });
183
+ }
184
+
185
+ async function serveStatic(url, res) {
186
+ const clean = decodeURIComponent(url.split('?')[0]);
187
+ if (clean === '/' || clean.endsWith('.html')) return false;
188
+ const file = path.join(root, 'dist/client', path.normalize(clean));
189
+ if (!file.startsWith(path.join(root, 'dist/client'))) return false;
190
+ try {
191
+ const body = await fs.readFile(file);
192
+ res.setHeader('content-type', TYPES[path.extname(file)] ?? 'application/octet-stream');
193
+ if (clean.startsWith('/assets/')) res.setHeader('cache-control', 'public, max-age=31536000, immutable');
194
+ res.end(body);
195
+ return true;
196
+ } catch { return false; }
197
+ }
198
+
199
+ const server = http.createServer(async (req, res) => {
200
+ const url = req.url ?? '/';
201
+ try {
202
+ if (vite) {
203
+ await new Promise((next) => vite.middlewares(req, res, next));
204
+ if (res.writableEnded) return;
205
+ } else if (await serveStatic(url, res)) return;
206
+
207
+ let template = prodTemplate;
208
+ let render = prodRender;
209
+ if (vite) {
210
+ template = await vite.transformIndexHtml(url, await fs.readFile(path.join(root, 'index.html'), 'utf8'));
211
+ render = (await vite.ssrLoadModule('/src/entry-server.${ext}')).render;
212
+ }
213
+ const { html, state } = await render(url);
214
+ const page = template
215
+ .replace('<!--app-html-->', html)
216
+ .replace('</head>', \`<script>window.__CLARITY_DATA__=\${safeJSONForScript(state)};</script></head>\`);
217
+ res.statusCode = 200;
218
+ res.setHeader('content-type', 'text/html; charset=utf-8');
219
+ res.end(page);
220
+ } catch (e) {
221
+ vite?.ssrFixStacktrace(e);
222
+ console.error(e);
223
+ res.statusCode = 500;
224
+ res.end(prod ? 'Internal Server Error' : String(e.stack));
225
+ }
226
+ });
227
+ server.listen(PORT, () => console.log(\`\${prod ? 'Production' : 'Dev'} SSR server on http://localhost:\${server.address().port}\`));
142
228
  `;
143
229
  }
144
230
 
@@ -347,11 +433,13 @@ npm install
347
433
  npm run dev
348
434
  \`\`\`
349
435
 
350
- ${opts.ssr ? '## SSR\n\n```bash\nnpm run build:server\nnpm run serve\n```\n\n' : ''}## Scripts
436
+ ${opts.ssr ? '## SSR\n\nPages are rendered on the server and hydrated in the browser (`src/entry-server`, `src/main`, `server.js`).\n\n```bash\nnpm run build\nnpm run serve\n```\n\n' : ''}## Scripts
351
437
 
352
- - \`npm run dev\` — start the Vite dev server
353
- - \`npm run build\` — production build
354
- - \`npm run preview\` — preview the production build
438
+ ${opts.ssr ? `- \\\`npm run dev\\\` — dev server with server-side rendering (Vite middleware)
439
+ - \\\`npm run build\\\` — client bundle (dist/client) and server render function (dist/server)
440
+ - \\\`npm run serve\\\` — serve the production build` : `- \\\`npm run dev\\\` — start the Vite dev server
441
+ - \\\`npm run build\\\` — production build
442
+ - \\\`npm run preview\\\` — preview the production build`}
355
443
  ${opts.testing ? '- `npm test` — run the test suite\n' : ''}${opts.typescript ? '- `npm run typecheck` — type-check with tsc\n' : ''}
356
444
  ${opts.router ? `## Routing
357
445
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-clarity",
3
- "version": "0.1.3",
3
+ "version": "0.2.0",
4
4
  "description": "Scaffold a new Clarity.js app — npm create clarity@latest",
5
5
  "type": "commonjs",
6
6
  "bin": {