@lemonadecms/create 0.0.0-stage → 0.1.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.
- package/CHANGELOG.md +13 -0
- package/LICENSE +21 -0
- package/README.md +26 -2
- package/bin/create-lemonade.mjs +122 -0
- package/dist/catalog.json +604 -0
- package/dist/templates/angular/angular.json +54 -0
- package/dist/templates/angular/locks/npm-lock.json.template +7079 -0
- package/dist/templates/angular/locks/pnpm-lock.yaml.template +4234 -0
- package/dist/templates/angular/package.json +61 -0
- package/dist/templates/angular/src/app/app.config.server.ts +23 -0
- package/dist/templates/angular/src/app/app.config.ts +34 -0
- package/dist/templates/angular/src/app/app.ts +9 -0
- package/dist/templates/angular/src/app/blog.service.ts +74 -0
- package/dist/templates/angular/src/app/journal.html +71 -0
- package/dist/templates/angular/src/app/journal.ts +47 -0
- package/dist/templates/angular/src/index.html +14 -0
- package/dist/templates/angular/src/main.server.ts +5 -0
- package/dist/templates/angular/src/main.ts +6 -0
- package/dist/templates/angular/src/server.ts +79 -0
- package/dist/templates/angular/tsconfig.app.json +8 -0
- package/dist/templates/angular/tsconfig.json +21 -0
- package/dist/templates/astro/astro.config.mjs +7 -0
- package/dist/templates/astro/locks/npm-lock.json.template +5478 -0
- package/dist/templates/astro/locks/pnpm-lock.yaml.template +3530 -0
- package/dist/templates/astro/package.json +42 -0
- package/dist/templates/astro/src/components/BlogView.astro +92 -0
- package/dist/templates/astro/src/layouts/Site.astro +23 -0
- package/dist/templates/astro/src/pages/articles/[id].astro +13 -0
- package/dist/templates/astro/src/pages/index.astro +13 -0
- package/dist/templates/astro/src/pages/lemonade/preview/[...path].ts +4 -0
- package/dist/templates/astro/src/pages/lemonade/preview.ts +4 -0
- package/dist/templates/astro/tsconfig.json +9 -0
- package/dist/templates/next/app/articles/[id]/page.tsx +29 -0
- package/dist/templates/next/app/data.ts +12 -0
- package/dist/templates/next/app/error.tsx +15 -0
- package/dist/templates/next/app/layout.tsx +13 -0
- package/dist/templates/next/app/lemonade/preview/[[...path]]/route.ts +7 -0
- package/dist/templates/next/app/loading.tsx +7 -0
- package/dist/templates/next/app/not-found.tsx +8 -0
- package/dist/templates/next/app/page.tsx +17 -0
- package/dist/templates/next/app/view.tsx +111 -0
- package/dist/templates/next/locks/npm-lock.json.template +1158 -0
- package/dist/templates/next/locks/pnpm-lock.yaml.template +715 -0
- package/dist/templates/next/next-env.d.ts +2 -0
- package/dist/templates/next/next.config.mjs +8 -0
- package/dist/templates/next/package.json +44 -0
- package/dist/templates/next/proxy.ts +19 -0
- package/dist/templates/next/tsconfig.json +25 -0
- package/dist/templates/nuxt/app/app.vue +1 -0
- package/dist/templates/nuxt/app/components/JournalView.vue +75 -0
- package/dist/templates/nuxt/app/pages/articles/[id].vue +8 -0
- package/dist/templates/nuxt/app/pages/index.vue +8 -0
- package/dist/templates/nuxt/locks/npm-lock.json.template +9113 -0
- package/dist/templates/nuxt/locks/pnpm-lock.yaml.template +6466 -0
- package/dist/templates/nuxt/nuxt.config.ts +27 -0
- package/dist/templates/nuxt/package.json +54 -0
- package/dist/templates/nuxt/server/api/blog/[id].get.ts +10 -0
- package/dist/templates/nuxt/server/api/blog.get.ts +9 -0
- package/dist/templates/nuxt/server/middleware/preview.ts +9 -0
- package/dist/templates/nuxt/server/utils/cms-environment.ts +15 -0
- package/dist/templates/nuxt/tsconfig.json +7 -0
- package/dist/templates/shared/GETTING_STARTED.md +29 -0
- package/dist/templates/shared/README.md +8 -0
- package/dist/templates/shared/env.example.template +11 -0
- package/dist/templates/shared/gitignore.template +13 -0
- package/dist/templates/shared/model-template.json +75 -0
- package/dist/templates/shared/public/blog.css +255 -0
- package/dist/templates/shared/public/lemonade.svg +5 -0
- package/dist/templates/shared/schema-contract.json +37 -0
- package/dist/templates/shared/scripts/cms-tools.mjs +171 -0
- package/dist/templates/shared/scripts/environment.mjs +68 -0
- package/dist/templates/shared/scripts/run.mjs +122 -0
- package/dist/templates/shared/server/blog.d.mts +35 -0
- package/dist/templates/shared/server/blog.mjs +159 -0
- package/dist/templates/shared/server/config.d.mts +11 -0
- package/dist/templates/shared/server/config.mjs +42 -0
- package/dist/templates/shared/server/preview.d.mts +4 -0
- package/dist/templates/shared/server/preview.mjs +276 -0
- package/dist/templates/shared/src/types/cms-models.ts +37 -0
- package/package.json +24 -4
- package/src/arguments.mjs +55 -0
- package/src/catalog.mjs +134 -0
- package/src/errors.mjs +10 -0
- package/src/generation.mjs +103 -0
- package/src/paths.mjs +90 -0
- package/src/prompts.mjs +65 -0
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
// Saved-preview grants and sessions are separate from the public SDK reader.
|
|
2
|
+
// This helper never uses an environment secret to read arbitrary draft content.
|
|
3
|
+
import { createHash } from 'node:crypto';
|
|
4
|
+
import { post } from './blog.mjs';
|
|
5
|
+
const base = '/lemonade/preview',
|
|
6
|
+
session = /^ps_[A-Za-z0-9_-]{43}$/,
|
|
7
|
+
uuid = /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i;
|
|
8
|
+
const esc = (v) =>
|
|
9
|
+
String(v ?? '').replace(
|
|
10
|
+
/[&<>"']/g,
|
|
11
|
+
(c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c],
|
|
12
|
+
);
|
|
13
|
+
export function previewConfig(env = process.env) {
|
|
14
|
+
if (env.CMS_PREVIEW_ENABLED !== 'true') return null;
|
|
15
|
+
try {
|
|
16
|
+
const audience = new URL(env.CMS_PREVIEW_URL),
|
|
17
|
+
studio = new URL(env.CMS_STUDIO_ORIGIN || 'https://app.lemonadecms.com');
|
|
18
|
+
const safe = (u) =>
|
|
19
|
+
!u.username &&
|
|
20
|
+
!u.password &&
|
|
21
|
+
!u.search &&
|
|
22
|
+
!u.hash &&
|
|
23
|
+
(u.protocol === 'https:' ||
|
|
24
|
+
(u.protocol === 'http:' &&
|
|
25
|
+
['localhost', '127.0.0.1', '[::1]'].includes(u.hostname)));
|
|
26
|
+
if (
|
|
27
|
+
!safe(audience) ||
|
|
28
|
+
audience.pathname !== base ||
|
|
29
|
+
!safe(studio) ||
|
|
30
|
+
studio.pathname !== '/' ||
|
|
31
|
+
!uuid.test(env.CMS_PROJECT_ID || '') ||
|
|
32
|
+
!(
|
|
33
|
+
/^[a-z][a-z0-9_-]{0,31}$/.test(env.CMS_ENVIRONMENT || '') ||
|
|
34
|
+
uuid.test(env.CMS_ENVIRONMENT || '')
|
|
35
|
+
) ||
|
|
36
|
+
!/^[a-z]{2,3}(?:-[A-Z][a-z]{3})?(?:-(?:[A-Z]{2}|[0-9]{3}))?$/.test(
|
|
37
|
+
env.CMS_LOCALE || '',
|
|
38
|
+
) ||
|
|
39
|
+
!/^((sk_[A-Za-z0-9_-]{43})|(lmd_sk_[0-9a-f-]{36}\.[A-Za-z0-9_-]{43}))$/.test(
|
|
40
|
+
env.CMS_SECRET_KEY || '',
|
|
41
|
+
)
|
|
42
|
+
)
|
|
43
|
+
return null;
|
|
44
|
+
return {
|
|
45
|
+
audience: audience.href,
|
|
46
|
+
origin: audience.origin,
|
|
47
|
+
studio: studio.origin,
|
|
48
|
+
project: env.CMS_PROJECT_ID.toLowerCase(),
|
|
49
|
+
locale: env.CMS_LOCALE,
|
|
50
|
+
environment: uuid.test(env.CMS_ENVIRONMENT)
|
|
51
|
+
? env.CMS_ENVIRONMENT.toLowerCase()
|
|
52
|
+
: env.CMS_ENVIRONMENT,
|
|
53
|
+
secret: env.CMS_SECRET_KEY,
|
|
54
|
+
cookie:
|
|
55
|
+
'lemonade_preview_' +
|
|
56
|
+
createHash('sha256').update(audience.href).digest('hex').slice(0, 12),
|
|
57
|
+
secure: audience.protocol === 'https:',
|
|
58
|
+
};
|
|
59
|
+
} catch {
|
|
60
|
+
return null;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
export function privateHeaders(config, extra = {}) {
|
|
64
|
+
return {
|
|
65
|
+
'Cache-Control': 'private, no-store',
|
|
66
|
+
'Vary': 'Cookie',
|
|
67
|
+
'X-Content-Type-Options': 'nosniff',
|
|
68
|
+
'Referrer-Policy': 'no-referrer',
|
|
69
|
+
'X-Robots-Tag': 'noindex, nofollow, noarchive',
|
|
70
|
+
'Content-Security-Policy': `default-src 'self'; img-src 'self' https:; style-src 'self'; script-src 'self'; frame-ancestors ${config.studio}`,
|
|
71
|
+
...extra,
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
async function bytes(response, max) {
|
|
75
|
+
if (!response.body) throw new Error('Empty response');
|
|
76
|
+
const reader = response.body.getReader();
|
|
77
|
+
let count = 0;
|
|
78
|
+
const parts = [];
|
|
79
|
+
let timer;
|
|
80
|
+
const deadline = new Promise((_, reject) => {
|
|
81
|
+
timer = setTimeout(() => reject(new Error('Body deadline exceeded')), 5000);
|
|
82
|
+
});
|
|
83
|
+
try {
|
|
84
|
+
while (true) {
|
|
85
|
+
const { done, value } = await Promise.race([reader.read(), deadline]);
|
|
86
|
+
if (done) break;
|
|
87
|
+
count += value.length;
|
|
88
|
+
if (count > max) throw new Error('Response too large');
|
|
89
|
+
parts.push(value);
|
|
90
|
+
}
|
|
91
|
+
return Buffer.concat(parts);
|
|
92
|
+
} finally {
|
|
93
|
+
clearTimeout(timer);
|
|
94
|
+
// An adversarial stream can also stall its cancel hook. Do not retain the
|
|
95
|
+
// request while awaiting that hook; the read deadline already ended it.
|
|
96
|
+
void reader.cancel().catch(() => {});
|
|
97
|
+
reader.releaseLock();
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
const json = async (response, max = 2097152) =>
|
|
101
|
+
JSON.parse((await bytes(response, max)).toString('utf8'));
|
|
102
|
+
const token = (request, c) => {
|
|
103
|
+
const values = (request.headers.get('cookie') || '')
|
|
104
|
+
.split(';')
|
|
105
|
+
.map((v) => v.trim().split('='))
|
|
106
|
+
.filter((v) => v[0] === c.cookie);
|
|
107
|
+
return values.length === 1 && session.test(values[0][1]) ? values[0][1] : null;
|
|
108
|
+
};
|
|
109
|
+
const cookie = (c, value, age) =>
|
|
110
|
+
`${c.cookie}=${value}; Path=${base}; Max-Age=${age}; HttpOnly; SameSite=Lax${c.secure ? '; Secure' : ''}`;
|
|
111
|
+
function page(c, title, body, status = 200) {
|
|
112
|
+
return new Response(
|
|
113
|
+
`<!doctype html><html lang="${esc(c.locale)}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${esc(title)}</title><link rel="stylesheet" href="/blog.css"></head><body>${body}</body></html>`,
|
|
114
|
+
{
|
|
115
|
+
status,
|
|
116
|
+
headers: privateHeaders(c, { 'Content-Type': 'text/html; charset=utf-8' }),
|
|
117
|
+
},
|
|
118
|
+
);
|
|
119
|
+
}
|
|
120
|
+
function unavailable(c, status = 401) {
|
|
121
|
+
return page(
|
|
122
|
+
c,
|
|
123
|
+
'Preview unavailable',
|
|
124
|
+
`<main class="notice"><h1>Preview unavailable</h1><p>The session expired, access changed, or the CMS is unavailable. Open a new saved draft preview from Studio.</p><a href="${esc(c.studio)}/studio" target="_top">Return to Studio</a></main>`,
|
|
125
|
+
status,
|
|
126
|
+
);
|
|
127
|
+
}
|
|
128
|
+
function matchesContext(data, c) {
|
|
129
|
+
const context = data.context,
|
|
130
|
+
entry = data.entry;
|
|
131
|
+
return (
|
|
132
|
+
context?.project_id === c.project &&
|
|
133
|
+
context.studio_origin === c.studio &&
|
|
134
|
+
context.model === 'article' &&
|
|
135
|
+
context.locale === c.locale &&
|
|
136
|
+
uuid.test(context.channel || '') &&
|
|
137
|
+
uuid.test(context.environment_id || '') &&
|
|
138
|
+
entry?.project_id === c.project &&
|
|
139
|
+
entry.locale === c.locale &&
|
|
140
|
+
entry.fields &&
|
|
141
|
+
entry.environment?.id === context.environment_id &&
|
|
142
|
+
(entry.environment.id === c.environment || entry.environment.key === c.environment)
|
|
143
|
+
);
|
|
144
|
+
}
|
|
145
|
+
export const runtime = String.raw`const root=document.querySelector('[data-preview]');const base='/lemonade/preview';if(root){const code=new URLSearchParams(location.hash.slice(1)).get('lemonade-preview');if(code){history.replaceState(null,'',location.pathname);fetch(base,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({code}),credentials:'same-origin',redirect:'error',cache:'no-store',signal:AbortSignal.timeout(10000)}).then(r=>{if(!r.ok)throw Error();location.replace(base+'/content')}).catch(()=>{document.querySelector('#preview-status').textContent='Preview could not start. Open a new preview from Studio, or try opening it in a new tab if embedded cookies are blocked.'});}const studio=root.dataset.studio,channel=root.dataset.channel;if(channel){const send=(type,request)=>window.parent!==window&&window.parent.postMessage({type,channel,...(request?{request}:{})},studio);window.addEventListener('message',e=>{if(e.origin!==studio||e.source!==window.parent||e.data?.channel!==channel)return;if(e.data.type==='lemonade:preview-connect'&&typeof e.data.request==='string'&&e.data.request.length<=64)send('lemonade:preview-ready',e.data.request);if(e.data.type==='lemonade:preview-refresh')location.reload()});send('lemonade:preview-ready');}root.querySelector('form')?.addEventListener('submit',async e=>{e.preventDefault();const b=e.target.querySelector('button');b.disabled=true;try{const r=await fetch(base+'/exit',{method:'POST',headers:{'Content-Type':'application/json'},body:'{}',credentials:'same-origin',redirect:'error',cache:'no-store'});if(!r.ok)throw Error();location.replace('/')}catch{b.disabled=false;b.textContent='Try exiting again'}});}`;
|
|
146
|
+
export async function handlePreview(
|
|
147
|
+
request,
|
|
148
|
+
{ env = process.env, fetcher = globalThis.fetch } = {},
|
|
149
|
+
) {
|
|
150
|
+
const url = new URL(request.url);
|
|
151
|
+
if (url.pathname !== base && !url.pathname.startsWith(base + '/')) return null;
|
|
152
|
+
const c = previewConfig(env);
|
|
153
|
+
if (!c)
|
|
154
|
+
return new Response('Saved preview is not configured. See GETTING_STARTED.md.', {
|
|
155
|
+
status: 503,
|
|
156
|
+
headers: { 'Cache-Control': 'private, no-store', 'X-Robots-Tag': 'noindex' },
|
|
157
|
+
});
|
|
158
|
+
// Astro can deliberately replace an untrusted Request origin with localhost.
|
|
159
|
+
// Validate the exact configured Host instead; never derive a destination from
|
|
160
|
+
// forwarding headers. POSTs independently require the configured HTTPS Origin.
|
|
161
|
+
const host = request.headers.get('host');
|
|
162
|
+
if (
|
|
163
|
+
(host ? host !== new URL(c.audience).host : url.origin !== c.origin) ||
|
|
164
|
+
(url.search && !url.pathname.startsWith(base + '/assets/'))
|
|
165
|
+
)
|
|
166
|
+
return unavailable(c, 400);
|
|
167
|
+
const call = (suffix, key, options = {}) =>
|
|
168
|
+
fetcher('https://api.lemonadecms.com/api/v1/site-preview' + suffix, {
|
|
169
|
+
...options,
|
|
170
|
+
headers: { Authorization: 'Bearer ' + key, ...options.headers },
|
|
171
|
+
credentials: 'omit',
|
|
172
|
+
redirect: 'error',
|
|
173
|
+
cache: 'no-store',
|
|
174
|
+
signal: AbortSignal.timeout(5000),
|
|
175
|
+
});
|
|
176
|
+
if (request.method === 'GET' && url.pathname === base + '/runtime.js')
|
|
177
|
+
return new Response(runtime, {
|
|
178
|
+
headers: privateHeaders(c, { 'Content-Type': 'text/javascript; charset=utf-8' }),
|
|
179
|
+
});
|
|
180
|
+
if (request.method === 'GET' && url.pathname === base)
|
|
181
|
+
return page(
|
|
182
|
+
c,
|
|
183
|
+
'Opening saved draft',
|
|
184
|
+
`<main data-preview data-studio="${esc(c.studio)}"><h1>Opening your saved draft</h1><p id="preview-status" role="status">Open this page from Studio to start a private session.</p></main><script src="${base}/runtime.js" defer></script>`,
|
|
185
|
+
);
|
|
186
|
+
if (request.method === 'POST' && [base, base + '/exit'].includes(url.pathname)) {
|
|
187
|
+
if (request.headers.get('origin') !== c.origin) return unavailable(c, 403);
|
|
188
|
+
if (url.pathname.endsWith('/exit')) {
|
|
189
|
+
const value = token(request, c);
|
|
190
|
+
if (value) {
|
|
191
|
+
try {
|
|
192
|
+
await call('/revoke', value, { method: 'POST' });
|
|
193
|
+
} catch {}
|
|
194
|
+
}
|
|
195
|
+
return new Response(null, {
|
|
196
|
+
status: 204,
|
|
197
|
+
headers: privateHeaders(c, { 'Set-Cookie': cookie(c, '', 0) }),
|
|
198
|
+
});
|
|
199
|
+
}
|
|
200
|
+
if (!request.headers.get('content-type')?.startsWith('application/json'))
|
|
201
|
+
return unavailable(c, 415);
|
|
202
|
+
try {
|
|
203
|
+
const body = await json(request, 4096);
|
|
204
|
+
if (!/^pc_[A-Za-z0-9_-]{43}$/.test(body.code || '')) return unavailable(c);
|
|
205
|
+
const r = await call('/exchange', c.secret, {
|
|
206
|
+
method: 'POST',
|
|
207
|
+
headers: { 'Content-Type': 'application/json' },
|
|
208
|
+
body: JSON.stringify({ code: body.code, audience: c.audience }),
|
|
209
|
+
});
|
|
210
|
+
if (!r.ok) return unavailable(c);
|
|
211
|
+
const data = await json(r, 4096);
|
|
212
|
+
const age = Math.min(
|
|
213
|
+
600,
|
|
214
|
+
Math.floor((Date.parse(data.expires_at) - Date.now()) / 1000),
|
|
215
|
+
);
|
|
216
|
+
if (!session.test(data.token) || !(age > 0) || data.kind === 'website-impact')
|
|
217
|
+
return unavailable(c);
|
|
218
|
+
return Response.json(
|
|
219
|
+
{ ok: true },
|
|
220
|
+
{ headers: privateHeaders(c, { 'Set-Cookie': cookie(c, data.token, age) }) },
|
|
221
|
+
);
|
|
222
|
+
} catch {
|
|
223
|
+
return unavailable(c);
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
if (request.method !== 'GET') return unavailable(c, 405);
|
|
227
|
+
const value = token(request, c);
|
|
228
|
+
if (!value) return unavailable(c);
|
|
229
|
+
if (url.pathname === base + '/content') {
|
|
230
|
+
try {
|
|
231
|
+
const r = await call('', value);
|
|
232
|
+
if (!r.ok) return unavailable(c);
|
|
233
|
+
const data = await json(r);
|
|
234
|
+
const context = data.context;
|
|
235
|
+
if (!matchesContext(data, c)) return unavailable(c);
|
|
236
|
+
const article = post(data.entry, { preview: true });
|
|
237
|
+
return page(
|
|
238
|
+
c,
|
|
239
|
+
article.title,
|
|
240
|
+
`<div data-preview data-studio="${esc(c.studio)}" data-channel="${esc(context.channel)}"><aside class="preview-banner"><div><strong>Saved draft preview</strong><p>Private session. Unsaved editor changes are excluded.</p></div><form action="${base}/exit" method="post"><button class="button">Exit preview</button></form></aside><main class="article"><h1>${esc(article.title)}</h1>${article.image ? `<img class="post-image" src="${esc(article.image)}" alt="${esc(article.imageAlt)}">` : ''}<div class="body">${article.bodyHtml}</div></main></div><script src="${base}/runtime.js" defer></script>`,
|
|
241
|
+
);
|
|
242
|
+
} catch {
|
|
243
|
+
return unavailable(c);
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
if (url.pathname.startsWith(base + '/assets/')) {
|
|
247
|
+
const id = url.pathname.slice((base + '/assets/').length);
|
|
248
|
+
if (
|
|
249
|
+
!uuid.test(id) ||
|
|
250
|
+
[...url.searchParams.keys()].some((k) => !['v', 'rendition'].includes(k))
|
|
251
|
+
)
|
|
252
|
+
return unavailable(c, 400);
|
|
253
|
+
try {
|
|
254
|
+
// A retained session can outlive a deployment's selected environment.
|
|
255
|
+
// Check its fresh authorized context before proxying any private bytes.
|
|
256
|
+
const current = await call('', value);
|
|
257
|
+
if (!current.ok || !matchesContext(await json(current), c)) return unavailable(c);
|
|
258
|
+
const r = await call(
|
|
259
|
+
'/assets/' + id + (url.search ? '?' + url.searchParams.toString() : ''),
|
|
260
|
+
value,
|
|
261
|
+
);
|
|
262
|
+
if (!r.ok) return unavailable(c);
|
|
263
|
+
const type = r.headers.get('content-type') || '';
|
|
264
|
+
if (!type.startsWith('image/')) return unavailable(c, 415);
|
|
265
|
+
return new Response(await bytes(r, 16777216), {
|
|
266
|
+
headers: privateHeaders(c, {
|
|
267
|
+
'Content-Type': type,
|
|
268
|
+
'Content-Security-Policy': "default-src 'none'; sandbox",
|
|
269
|
+
}),
|
|
270
|
+
});
|
|
271
|
+
} catch {
|
|
272
|
+
return unavailable(c);
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
return unavailable(c, 404);
|
|
276
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
// Generated by @lemonadecms/client codegen. Do not edit.
|
|
2
|
+
// Every field allows historical absence/null; previews may be incomplete.
|
|
3
|
+
export interface ContentReference<Fields> { id: string; fields?: Fields; published_at?: string | null; content_type?: { id: string; key: string; name: string }; project_id?: string; environment?: { id: string; key: string }; locale?: string }
|
|
4
|
+
export interface ContentRendition { key: string; preset: "hero" | "card" | "social"; width: number; height: number; content_type: string; url: string }
|
|
5
|
+
export interface ContentAsset { id: string; url: string; content_type: string; byte_size: number; metadata: { title?: string; alt?: string; description?: string; focal_point?: { x: number; y: number } }; renditions?: ContentRendition[] }
|
|
6
|
+
export type RichTextMark = { type: 'bold' | 'italic' | 'underline' | 'strike' | 'code' } | { type: 'link'; attrs: { href: string } };
|
|
7
|
+
export type RichTextInline = { type: 'text'; text: string; marks?: RichTextMark[] } | { type: 'hardBreak' };
|
|
8
|
+
export type RichTextEntry<Target extends keyof Models> = { [K in Target]: { type: 'entry'; attrs: { id: string; target: K }; resource?: ContentReference<Models[K]> | null } }[Target];
|
|
9
|
+
export type RichTextBlock<Target extends keyof Models = keyof Models> = { type: 'paragraph'; content?: RichTextInline[] } | { type: 'heading'; attrs: { level: 2 | 3 | 4 }; content?: RichTextInline[] } | { type: 'bulletList' | 'orderedList'; attrs?: { start: 1 }; content: { type: 'listItem'; content: RichTextBlock<Target>[] }[] } | { type: 'image'; attrs: { id: string; alt: string }; resource?: ContentAsset | null } | RichTextEntry<Target>;
|
|
10
|
+
export interface ContentRichText<Target extends keyof Models = keyof Models> { version: 1; document: { type: 'doc'; content?: RichTextBlock<Target>[] } }
|
|
11
|
+
export interface Models {
|
|
12
|
+
"article": {
|
|
13
|
+
"title"?: string | null;
|
|
14
|
+
"slug"?: string | null;
|
|
15
|
+
"body"?: string | null;
|
|
16
|
+
"author"?: ContentReference<Models["author"]> | null;
|
|
17
|
+
"cover"?: ContentAsset | null;
|
|
18
|
+
"date"?: string | null;
|
|
19
|
+
};
|
|
20
|
+
"author": {
|
|
21
|
+
"name"?: string | null;
|
|
22
|
+
"bio"?: string | null;
|
|
23
|
+
"portrait"?: ContentAsset | null;
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
// Opt-in read-only reverse collections: parent model -> relation -> source model.
|
|
28
|
+
export interface Relationships {
|
|
29
|
+
"article": {};
|
|
30
|
+
"author": {};
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// Presentation roles, refreshed by codegen after schema changes.
|
|
34
|
+
export const seoModels = {
|
|
35
|
+
"article": {},
|
|
36
|
+
"author": {}
|
|
37
|
+
} as const;
|
package/package.json
CHANGED
|
@@ -1,6 +1,26 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lemonadecms/create",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"description": "
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"description": "Create a standalone Lemonade CMS application with Astro, Nuxt, Next.js or Angular",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"homepage": "https://lemonadecms.com/guides",
|
|
8
|
+
"engines": {
|
|
9
|
+
"node": "^22.23.5 || ^24.22.3"
|
|
10
|
+
},
|
|
11
|
+
"bin": {
|
|
12
|
+
"create-lemonade": "bin/create-lemonade.mjs"
|
|
13
|
+
},
|
|
14
|
+
"files": [
|
|
15
|
+
"bin/",
|
|
16
|
+
"src/",
|
|
17
|
+
"dist/",
|
|
18
|
+
"README.md",
|
|
19
|
+
"CHANGELOG.md",
|
|
20
|
+
"LICENSE"
|
|
21
|
+
],
|
|
22
|
+
"publishConfig": {
|
|
23
|
+
"access": "public",
|
|
24
|
+
"registry": "https://registry.npmjs.org/"
|
|
25
|
+
}
|
|
26
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { CreateError } from './errors.mjs';
|
|
2
|
+
export const frameworks = ['astro', 'nuxt', 'next', 'angular'];
|
|
3
|
+
export const HELP = `Create a Lemonade CMS blog
|
|
4
|
+
|
|
5
|
+
create-lemonade <new-directory> --framework astro|nuxt|next|angular
|
|
6
|
+
--template blog Versioned blog template (default blog)
|
|
7
|
+
--package-manager npm|pnpm Select the frozen lockfile (default npm)
|
|
8
|
+
--json Noninteractive, machine-readable result
|
|
9
|
+
--help, --version
|
|
10
|
+
|
|
11
|
+
Generation is offline. No dependencies, Git operations or CMS changes are run.
|
|
12
|
+
Existing destinations are never overwritten. Connect through the included guide.
|
|
13
|
+
`;
|
|
14
|
+
export function supportedRuntime(value = process.versions.node) {
|
|
15
|
+
if (!/^\d+\.\d+\.\d+$/.test(value)) return false;
|
|
16
|
+
const [major, minor, patch] = value.split('.').map(Number);
|
|
17
|
+
return (
|
|
18
|
+
(major === 22 && (minor > 23 || (minor === 23 && patch >= 5))) ||
|
|
19
|
+
(major === 24 && (minor > 22 || (minor === 22 && patch >= 3)))
|
|
20
|
+
);
|
|
21
|
+
}
|
|
22
|
+
export function parseArguments(args) {
|
|
23
|
+
const result = { template: 'blog', packageManager: 'npm', json: false };
|
|
24
|
+
const seen = new Set();
|
|
25
|
+
const flags = {
|
|
26
|
+
'--framework': 'framework',
|
|
27
|
+
'--template': 'template',
|
|
28
|
+
'--package-manager': 'packageManager',
|
|
29
|
+
};
|
|
30
|
+
for (let i = 0; i < args.length; i++) {
|
|
31
|
+
const item = args[i];
|
|
32
|
+
if (['--help', '--version', '--json'].includes(item)) {
|
|
33
|
+
if (seen.has(item)) throw new CreateError(2, 'An option was repeated.');
|
|
34
|
+
seen.add(item);
|
|
35
|
+
result[item.slice(2)] = true;
|
|
36
|
+
continue;
|
|
37
|
+
}
|
|
38
|
+
if (flags[item]) {
|
|
39
|
+
if (seen.has(item) || !args[i + 1] || args[i + 1].startsWith('-'))
|
|
40
|
+
throw new CreateError(2, 'An option is missing a value or was repeated.');
|
|
41
|
+
seen.add(item);
|
|
42
|
+
result[flags[item]] = args[++i];
|
|
43
|
+
if (item === '--package-manager') result.managerProvided = true;
|
|
44
|
+
continue;
|
|
45
|
+
}
|
|
46
|
+
if (item.startsWith('-') || result.directory)
|
|
47
|
+
throw new CreateError(2, 'Unknown option or extra directory. Use --help.');
|
|
48
|
+
result.directory = item;
|
|
49
|
+
}
|
|
50
|
+
if (result.framework && !frameworks.includes(result.framework))
|
|
51
|
+
throw new CreateError(2, 'Choose astro, nuxt, next or angular.');
|
|
52
|
+
if (result.template !== 'blog' || !['npm', 'pnpm'].includes(result.packageManager))
|
|
53
|
+
throw new CreateError(2, 'Choose the blog template and npm or pnpm.');
|
|
54
|
+
return result;
|
|
55
|
+
}
|
package/src/catalog.mjs
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
import { open, lstat } from 'node:fs/promises';
|
|
2
|
+
import { resolve, relative, isAbsolute } from 'node:path';
|
|
3
|
+
import { createHash } from 'node:crypto';
|
|
4
|
+
import { safeRelative } from './paths.mjs';
|
|
5
|
+
import { invariant } from './errors.mjs';
|
|
6
|
+
export const hash = (bytes) => createHash('sha256').update(bytes).digest('hex');
|
|
7
|
+
async function bundledDirectory(path) {
|
|
8
|
+
const stat = await lstat(path);
|
|
9
|
+
invariant(
|
|
10
|
+
stat.isDirectory() && !stat.isSymbolicLink(),
|
|
11
|
+
'Bundled asset directories cannot be links.',
|
|
12
|
+
);
|
|
13
|
+
}
|
|
14
|
+
export async function boundedFile(path, limit = 8 * 1024 * 1024) {
|
|
15
|
+
const stat = await lstat(path);
|
|
16
|
+
invariant(
|
|
17
|
+
stat.isFile() && !stat.isSymbolicLink() && stat.size <= limit,
|
|
18
|
+
'Invalid or oversized bundled file.',
|
|
19
|
+
);
|
|
20
|
+
const handle = await open(path, 'r');
|
|
21
|
+
try {
|
|
22
|
+
const actual = await handle.stat();
|
|
23
|
+
invariant(
|
|
24
|
+
actual.ino === stat.ino && actual.dev === stat.dev && actual.size <= limit,
|
|
25
|
+
'Bundled file changed.',
|
|
26
|
+
);
|
|
27
|
+
const bytes = Buffer.alloc(actual.size + 1);
|
|
28
|
+
let count = 0;
|
|
29
|
+
while (count < bytes.length) {
|
|
30
|
+
const { bytesRead } = await handle.read(
|
|
31
|
+
bytes,
|
|
32
|
+
count,
|
|
33
|
+
bytes.length - count,
|
|
34
|
+
count,
|
|
35
|
+
);
|
|
36
|
+
if (!bytesRead) break;
|
|
37
|
+
count += bytesRead;
|
|
38
|
+
}
|
|
39
|
+
const after = await handle.stat();
|
|
40
|
+
invariant(
|
|
41
|
+
count === actual.size &&
|
|
42
|
+
after.size === actual.size &&
|
|
43
|
+
after.mtimeMs === actual.mtimeMs,
|
|
44
|
+
'Bundled file changed.',
|
|
45
|
+
);
|
|
46
|
+
return bytes.subarray(0, count);
|
|
47
|
+
} finally {
|
|
48
|
+
await handle.close();
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
export async function loadCatalog(root) {
|
|
52
|
+
await bundledDirectory(resolve(root, 'dist'));
|
|
53
|
+
const bytes = await boundedFile(resolve(root, 'dist/catalog.json'), 512 * 1024);
|
|
54
|
+
const value = JSON.parse(bytes.toString('utf8'));
|
|
55
|
+
invariant(
|
|
56
|
+
value.version === 1 &&
|
|
57
|
+
typeof value.revision === 'string' &&
|
|
58
|
+
Array.isArray(value.files) &&
|
|
59
|
+
value.files.length <= 2000,
|
|
60
|
+
'Invalid starter catalog.',
|
|
61
|
+
);
|
|
62
|
+
const keys = new Set();
|
|
63
|
+
let total = 0;
|
|
64
|
+
for (const file of value.files) {
|
|
65
|
+
safeRelative(file.source);
|
|
66
|
+
safeRelative(file.target);
|
|
67
|
+
invariant(
|
|
68
|
+
file.target !== 'lemonade.starter.json',
|
|
69
|
+
'The provenance path is reserved.',
|
|
70
|
+
);
|
|
71
|
+
invariant(
|
|
72
|
+
['shared', 'astro', 'nuxt', 'next', 'angular'].includes(file.framework) &&
|
|
73
|
+
/^(both|npm|pnpm)$/.test(file.manager),
|
|
74
|
+
'Invalid catalog scope.',
|
|
75
|
+
);
|
|
76
|
+
invariant(
|
|
77
|
+
/^[a-f0-9]{64}$/.test(file.sha256) &&
|
|
78
|
+
Number.isSafeInteger(file.bytes) &&
|
|
79
|
+
file.bytes >= 0 &&
|
|
80
|
+
file.bytes <= 8 * 1024 * 1024,
|
|
81
|
+
'Invalid catalog file identity.',
|
|
82
|
+
);
|
|
83
|
+
const key = `${file.framework}:${file.manager}:${file.target.normalize('NFC').toLowerCase()}`;
|
|
84
|
+
invariant(!keys.has(key), 'Duplicate catalog output.');
|
|
85
|
+
keys.add(key);
|
|
86
|
+
total += file.bytes;
|
|
87
|
+
const path = resolve(root, 'dist/templates', file.source);
|
|
88
|
+
const rel = relative(resolve(root, 'dist/templates'), path);
|
|
89
|
+
invariant(!rel.startsWith('..') && !isAbsolute(rel), 'Unsafe asset source.');
|
|
90
|
+
}
|
|
91
|
+
invariant(total <= 64 * 1024 * 1024, 'Starter payload exceeds its bound.');
|
|
92
|
+
return value;
|
|
93
|
+
}
|
|
94
|
+
export async function selectedFiles(root, catalog, framework, manager, name) {
|
|
95
|
+
await bundledDirectory(resolve(root, 'dist'));
|
|
96
|
+
await bundledDirectory(resolve(root, 'dist/templates'));
|
|
97
|
+
const result = [];
|
|
98
|
+
const seen = new Set();
|
|
99
|
+
for (const item of catalog.files.filter(
|
|
100
|
+
(f) =>
|
|
101
|
+
['shared', framework].includes(f.framework) &&
|
|
102
|
+
['both', manager].includes(f.manager),
|
|
103
|
+
)) {
|
|
104
|
+
const key = item.target.normalize('NFC').toLowerCase();
|
|
105
|
+
invariant(!seen.has(key), 'Conflicting starter files.');
|
|
106
|
+
seen.add(key);
|
|
107
|
+
let parent = resolve(root, 'dist/templates');
|
|
108
|
+
for (const part of item.source.split('/').slice(0, -1)) {
|
|
109
|
+
parent = resolve(parent, part);
|
|
110
|
+
await bundledDirectory(parent);
|
|
111
|
+
}
|
|
112
|
+
let body = await boundedFile(resolve(root, 'dist/templates', item.source));
|
|
113
|
+
invariant(
|
|
114
|
+
body.length === item.bytes && hash(body) === item.sha256,
|
|
115
|
+
'Starter assets failed their integrity check.',
|
|
116
|
+
);
|
|
117
|
+
if (['package.json', 'package-lock.json'].includes(item.target)) {
|
|
118
|
+
const json = JSON.parse(body.toString('utf8'));
|
|
119
|
+
json.name = name;
|
|
120
|
+
if (item.target === 'package.json')
|
|
121
|
+
json.packageManager = `${manager}@${manager === 'npm' ? '11.6.2' : '10.34.5'}`;
|
|
122
|
+
if (json.packages?.['']) json.packages[''].name = name;
|
|
123
|
+
body = Buffer.from(JSON.stringify(json, null, 2) + '\n');
|
|
124
|
+
}
|
|
125
|
+
result.push({ path: item.target, body });
|
|
126
|
+
}
|
|
127
|
+
invariant(
|
|
128
|
+
result.some((f) => f.path === 'package.json') &&
|
|
129
|
+
result.some((f) => f.path === '.gitignore') &&
|
|
130
|
+
result.some((f) => f.path === '.env.example'),
|
|
131
|
+
'Starter is incomplete.',
|
|
132
|
+
);
|
|
133
|
+
return result;
|
|
134
|
+
}
|
package/src/errors.mjs
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export class CreateError extends Error {
|
|
2
|
+
constructor(code, message) {
|
|
3
|
+
super(message);
|
|
4
|
+
this.name = 'CreateError';
|
|
5
|
+
this.code = code;
|
|
6
|
+
}
|
|
7
|
+
}
|
|
8
|
+
export function invariant(condition, message, code = 5) {
|
|
9
|
+
if (!condition) throw new CreateError(code, message);
|
|
10
|
+
}
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import { mkdir, open, lstat, unlink, rmdir } from 'node:fs/promises';
|
|
2
|
+
import { resolve, dirname, relative } from 'node:path';
|
|
3
|
+
import { hash, boundedFile } from './catalog.mjs';
|
|
4
|
+
import { CreateError, invariant } from './errors.mjs';
|
|
5
|
+
export async function generate(target, files, provenance, { signal, onWrite } = {}) {
|
|
6
|
+
const owned = [],
|
|
7
|
+
directories = [],
|
|
8
|
+
paths = new Set();
|
|
9
|
+
let claimed = false;
|
|
10
|
+
const check = () => {
|
|
11
|
+
if (signal?.aborted) throw new CreateError(130, 'Creation cancelled.');
|
|
12
|
+
};
|
|
13
|
+
async function directory(path) {
|
|
14
|
+
if (path === target || paths.has(path)) return;
|
|
15
|
+
await directory(dirname(path));
|
|
16
|
+
await mkdir(path);
|
|
17
|
+
const stat = await lstat(path);
|
|
18
|
+
directories.push({ path, ino: stat.ino, dev: stat.dev });
|
|
19
|
+
paths.add(path);
|
|
20
|
+
}
|
|
21
|
+
try {
|
|
22
|
+
check();
|
|
23
|
+
await mkdir(target);
|
|
24
|
+
claimed = true;
|
|
25
|
+
const stat = await lstat(target);
|
|
26
|
+
directories.push({ path: target, ino: stat.ino, dev: stat.dev });
|
|
27
|
+
paths.add(target);
|
|
28
|
+
for (const item of [
|
|
29
|
+
...files,
|
|
30
|
+
{
|
|
31
|
+
path: 'lemonade.starter.json',
|
|
32
|
+
body: Buffer.from(JSON.stringify(provenance, null, 2) + '\n'),
|
|
33
|
+
},
|
|
34
|
+
]) {
|
|
35
|
+
check();
|
|
36
|
+
const path = resolve(target, item.path);
|
|
37
|
+
invariant(
|
|
38
|
+
relative(target, path) && !relative(target, path).startsWith('..'),
|
|
39
|
+
'Unsafe output.',
|
|
40
|
+
);
|
|
41
|
+
await directory(dirname(path));
|
|
42
|
+
check();
|
|
43
|
+
const handle = await open(path, 'wx', 0o644);
|
|
44
|
+
let row;
|
|
45
|
+
try {
|
|
46
|
+
const stat = await handle.stat();
|
|
47
|
+
row = { path, ino: stat.ino, dev: stat.dev, digest: hash(item.body) };
|
|
48
|
+
owned.push(row);
|
|
49
|
+
await handle.writeFile(item.body);
|
|
50
|
+
} finally {
|
|
51
|
+
await handle.close();
|
|
52
|
+
}
|
|
53
|
+
await onWrite?.(item.path);
|
|
54
|
+
check();
|
|
55
|
+
}
|
|
56
|
+
return { files: owned.length };
|
|
57
|
+
} catch (error) {
|
|
58
|
+
let retained = false;
|
|
59
|
+
if (claimed) {
|
|
60
|
+
for (const file of owned.reverse()) {
|
|
61
|
+
try {
|
|
62
|
+
const stat = await lstat(file.path);
|
|
63
|
+
if (
|
|
64
|
+
stat.isFile() &&
|
|
65
|
+
!stat.isSymbolicLink() &&
|
|
66
|
+
stat.ino === file.ino &&
|
|
67
|
+
stat.dev === file.dev &&
|
|
68
|
+
hash(await boundedFile(file.path)) === file.digest
|
|
69
|
+
)
|
|
70
|
+
await unlink(file.path);
|
|
71
|
+
else retained = true;
|
|
72
|
+
} catch (e) {
|
|
73
|
+
if (e.code !== 'ENOENT') retained = true;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
for (const row of directories.reverse()) {
|
|
77
|
+
try {
|
|
78
|
+
const stat = await lstat(row.path);
|
|
79
|
+
if (
|
|
80
|
+
stat.isDirectory() &&
|
|
81
|
+
!stat.isSymbolicLink() &&
|
|
82
|
+
stat.ino === row.ino &&
|
|
83
|
+
stat.dev === row.dev
|
|
84
|
+
)
|
|
85
|
+
await rmdir(row.path);
|
|
86
|
+
else retained = true;
|
|
87
|
+
} catch (e) {
|
|
88
|
+
if (e.code !== 'ENOENT') retained = true;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
if (retained)
|
|
93
|
+
throw new CreateError(
|
|
94
|
+
error.code === 130 ? 130 : 6,
|
|
95
|
+
'Creation stopped. Changed or incomplete files were retained; inspect the destination before removing it.',
|
|
96
|
+
);
|
|
97
|
+
if (error instanceof CreateError) throw error;
|
|
98
|
+
throw new CreateError(
|
|
99
|
+
6,
|
|
100
|
+
'Could not create the project. Choose an available new directory.',
|
|
101
|
+
);
|
|
102
|
+
}
|
|
103
|
+
}
|