ghostcn 1.5.0 → 1.6.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 (50) hide show
  1. package/dist/commands/create.js +10 -3
  2. package/dist/commands/diff.js +47 -5
  3. package/dist/commands/init.js +17 -8
  4. package/dist/commands/list.js +22 -4
  5. package/dist/registry/components/accordion.json +66 -0
  6. package/dist/registry/components/announcement-bar.json +79 -0
  7. package/dist/registry/components/archive-header.json +1 -1
  8. package/dist/registry/components/author-card.json +2 -2
  9. package/dist/registry/components/author-list.json +1 -1
  10. package/dist/registry/components/avatar.json +62 -0
  11. package/dist/registry/components/breadcrumbs.json +59 -0
  12. package/dist/registry/components/button.json +1 -1
  13. package/dist/registry/components/featured-posts.json +2 -2
  14. package/dist/registry/components/input.json +8 -2
  15. package/dist/registry/components/member-cta.json +1 -1
  16. package/dist/registry/components/newsletter-form.json +12 -3
  17. package/dist/registry/components/pagination.json +2 -2
  18. package/dist/registry/components/post-card.json +2 -2
  19. package/dist/registry/components/post-grid.json +1 -1
  20. package/dist/registry/components/post-header.json +2 -2
  21. package/dist/registry/components/pricing-table.json +24 -4
  22. package/dist/registry/components/reading-progress.json +73 -0
  23. package/dist/registry/components/related-posts.json +6 -0
  24. package/dist/registry/components/share-buttons.json +76 -0
  25. package/dist/registry/components/site-footer.json +2 -2
  26. package/dist/registry/components/site-header.json +1 -1
  27. package/dist/registry/components/table-of-contents.json +12 -2
  28. package/dist/registry/components/tag-grid.json +1 -1
  29. package/dist/registry/components/tag-list.json +1 -1
  30. package/dist/registry/components/theme-toggle.json +65 -0
  31. package/dist/registry/components/visibility-badge.json +71 -0
  32. package/dist/registry/index.json +89 -4
  33. package/dist/templates/playground/index.html +2 -2
  34. package/dist/templates/playground/playground.css +8 -1
  35. package/dist/templates/playground/playground.js +39 -5
  36. package/dist/templates/playground/preview.css +1 -0
  37. package/dist/templates/theme-tools.mjs +62 -24
  38. package/dist/utils/component-diff.d.ts +1 -1
  39. package/dist/utils/component-diff.js +46 -17
  40. package/dist/utils/component-files.js +3 -2
  41. package/dist/utils/component-history.js +1 -1
  42. package/dist/utils/playground-server.js +34 -12
  43. package/dist/utils/preview-renderer.d.ts +5 -0
  44. package/dist/utils/preview-renderer.js +20 -6
  45. package/dist/utils/registry.js +15 -5
  46. package/dist/utils/theme-files.js +14 -7
  47. package/dist/utils/theme-project.js +6 -4
  48. package/dist/utils/theme-scaffold.js +22 -7
  49. package/dist/utils/theme.js +39 -32
  50. package/package.json +1 -1
@@ -1,19 +1,22 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
+ import zlib from 'node:zlib';
3
4
  import { fileURLToPath } from 'node:url';
4
5
 
5
6
  function inside(root, relative) {
6
7
  const target = path.resolve(root, relative);
7
8
  if (target === root || !target.startsWith(root + path.sep)) throw new Error(`Path escapes theme: ${relative}`);
8
- // Never follow links when inspecting or packaging a theme.
9
+ // Never follow links (including dangling symlinks) when inspecting or packaging a theme.
9
10
  let current = root;
10
11
  for (const part of path.relative(root, target).split(path.sep)) {
11
12
  current = path.join(current, part);
12
- if (fs.existsSync(current) && fs.lstatSync(current).isSymbolicLink()) throw new Error(`Symlink is not supported: ${relative}`);
13
+ if (fs.lstatSync(current, { throwIfNoEntry: false })?.isSymbolicLink()) throw new Error(`Symlink is not supported: ${relative}`);
13
14
  }
14
15
  return target;
15
16
  }
16
17
 
18
+ const stripHbsComments = source => source.replace(/\{\{!--[\s\S]*?--\}\}/g, '').replace(/\{\{![\s\S]*?\}\}/g, '');
19
+
17
20
  export function inspectTheme(themeRoot) {
18
21
  const root = path.resolve(themeRoot);
19
22
  const errors = [], warnings = [];
@@ -26,8 +29,11 @@ export function inspectTheme(themeRoot) {
26
29
  }
27
30
  if (exists('package.json')) {
28
31
  pkg = JSON.parse(read('package.json'));
29
- if (!pkg.engines?.ghost) errors.push('package.json needs engines.ghost');
30
- if (!pkg.author?.email) errors.push('package.json needs author.email');
32
+ if (!pkg.engines?.ghost && !pkg.engines?.['ghost-api']) errors.push('package.json needs engines.ghost');
33
+ const hasAuthorEmail = typeof pkg.author === 'string'
34
+ ? /<[^>\s]+@[^>\s]+>/.test(pkg.author)
35
+ : Boolean(pkg.author?.email);
36
+ if (!hasAuthorEmail) errors.push('package.json needs author.email');
31
37
  }
32
38
  if (exists('components.json')) {
33
39
  config = JSON.parse(read('components.json'));
@@ -51,35 +57,51 @@ export function inspectTheme(themeRoot) {
51
57
  };
52
58
  const templates = fs.readdirSync(root).filter(name => name.endsWith('.hbs'));
53
59
  if (exists('partials')) scan('partials', file => { if (file.endsWith('.hbs')) templates.push(file); });
60
+ if (exists('members')) scan('members', file => { if (file.endsWith('.hbs')) templates.push(file); });
54
61
  for (const file of templates) {
55
- const source = read(file).replace(/\{\{!--[\s\S]*?--\}\}/g, '');
62
+ const source = stripHbsComments(read(file));
56
63
  for (const match of source.matchAll(/\{\{asset\s+["']([^"']+)["']/g)) {
57
64
  if (!exists(`assets/${match[1]}`)) errors.push(`${file}: missing asset ${match[1]} (run your build)`);
58
65
  }
59
- for (const match of source.matchAll(/\{\{(?:#>|>)\s*["']([^"']+)["']/g)) {
60
- if (!exists(`partials/${match[1]}.hbs`)) errors.push(`${file}: missing partial ${match[1]}`);
66
+ for (const match of source.matchAll(/\{\{(?:#>|>)\s*(?:["']([^"']+)["']|([a-zA-Z0-9_/-]+))/g)) {
67
+ const partial = match[1] || match[2];
68
+ if (!partial || partial.startsWith('@')) continue;
69
+ if (!exists(`partials/${partial}.hbs`)) errors.push(`${file}: missing partial ${partial}`);
61
70
  }
62
71
  }
63
72
  if (exists('default.hbs')) {
64
73
  const layout = read('default.hbs');
74
+ const stripped = stripHbsComments(layout);
65
75
  const linked = new Set();
66
- for (const tag of layout.replace(/\{\{!--[\s\S]*?--\}\}/g, '').matchAll(/<link\b[^>]*>/gi)) {
76
+ for (const tag of stripped.matchAll(/<link\b[^>]*>/gi)) {
67
77
  if (!/\brel\s*=\s*["']stylesheet["']/i.test(tag[0])) continue;
68
78
  const asset = tag[0].match(/\{\{asset\s+["']([^"']+)["']/);
69
79
  if (asset) linked.add(asset[1]);
70
80
  }
81
+ const linkedScripts = new Set();
82
+ for (const tag of stripped.matchAll(/<script\b[^>]*>/gi)) {
83
+ const asset = tag[0].match(/\{\{asset\s+["']([^"']+)["']/);
84
+ if (asset) linkedScripts.add(asset[1]);
85
+ }
71
86
  for (const helper of ['ghost_head', 'ghost_foot']) {
72
- if (!new RegExp(`\\{\\{\\s*${helper}\\s*\\}\\}`).test(layout)) errors.push(`default.hbs needs {{${helper}}}`);
87
+ if (!new RegExp(`\\{\\{\\s*${helper}\\s*\\}\\}`).test(stripped)) errors.push(`default.hbs needs {{${helper}}}`);
73
88
  }
74
89
  if (config && !linked.has(path.relative(path.join(root, 'assets'), inside(root, config.cssFile)).replaceAll('\\', '/'))) {
75
90
  errors.push('default.hbs does not link the configured ghostcn stylesheet');
76
91
  }
77
92
  if (config?.aliases?.styles && exists(config.aliases.styles)) {
78
- for (const name of fs.readdirSync(inside(root, config.aliases.styles)).filter(name => name.endsWith('.css'))) {
93
+ for (const name of fs.readdirSync(inside(root, config.aliases.styles)).filter(name => name.toLowerCase().endsWith('.css'))) {
79
94
  const asset = path.relative(path.join(root, 'assets'), inside(root, path.join(config.aliases.styles, name))).replaceAll('\\', '/');
80
95
  if (!linked.has(asset)) errors.push(`default.hbs does not link component stylesheet ${asset}`);
81
96
  }
82
97
  }
98
+ const jsDir = config?.aliases?.js || 'assets/js/components';
99
+ if (config && exists(jsDir)) {
100
+ for (const name of fs.readdirSync(inside(root, jsDir)).filter(name => name.toLowerCase().endsWith('.js'))) {
101
+ const asset = path.relative(path.join(root, 'assets'), inside(root, path.join(jsDir, name))).replaceAll('\\', '/');
102
+ if (!linkedScripts.has(asset)) errors.push(`default.hbs does not link component script ${asset}`);
103
+ }
104
+ }
83
105
  }
84
106
  } catch (error) { errors.push(error.message); }
85
107
  return { errors: [...new Set(errors)], warnings: [...new Set(warnings)] };
@@ -98,25 +120,25 @@ export function packageTheme(themeRoot) {
98
120
  const root = path.resolve(themeRoot);
99
121
  const result = inspectTheme(root);
100
122
  if (result.errors.length) throw new Error(result.errors.join('\n'));
101
- const pkg = JSON.parse(fs.readFileSync(inside(root, 'package.json'), 'utf8'));
123
+ const pkg = JSON.parse(fs.readFileSync(inside(root, 'package.json'), 'utf8').replace(/^\uFEFF/, ''));
102
124
  if (!/^[a-z0-9][a-z0-9-]*$/.test(pkg.name) || !/^\d+\.\d+\.\d+(?:-[a-zA-Z0-9.-]+)?$/.test(pkg.version)) {
103
125
  throw new Error('Packaging needs a safe lowercase theme name and a semantic version in package.json');
104
126
  }
105
- const files = fs.readdirSync(root).filter(name => name.endsWith('.hbs') || ['package.json', 'LICENSE', 'LICENSE.md'].includes(name));
127
+ const files = fs.readdirSync(root).filter(name => name.endsWith('.hbs') || ['package.json', 'LICENSE', 'LICENSE.md', 'routes.yaml'].includes(name));
106
128
  // Keep a source stylesheet if an existing theme actually links it at runtime.
107
129
  const sourceStyles = new Set(['assets/css/source.css', 'assets/css/ghostcn-tailwind.css']);
108
130
  const linkedStyles = new Set();
109
- const findLinks = dir => {
131
+ const findLinks = (dir, insideTemplateDir = false) => {
110
132
  for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
111
133
  if (entry.name.startsWith('.') || entry.name === 'node_modules' || entry.name === 'dist' || entry.name === 'assets') continue;
112
134
  const target = path.join(dir, entry.name);
113
- if (entry.isDirectory() && entry.name === 'partials') {
135
+ if (entry.isDirectory() && (insideTemplateDir || entry.name === 'partials' || entry.name === 'members')) {
114
136
  inside(root, path.relative(root, target));
115
- findLinks(target);
137
+ findLinks(target, true);
116
138
  }
117
139
  else if (entry.isFile() && entry.name.endsWith('.hbs')) {
118
140
  inside(root, path.relative(root, target));
119
- for (const match of fs.readFileSync(target, 'utf8').matchAll(/\{\{asset\s+["']([^"']+)["']/g)) linkedStyles.add(`assets/${match[1]}`);
141
+ for (const match of stripHbsComments(fs.readFileSync(target, 'utf8')).matchAll(/\{\{asset\s+["']([^"']+)["']/g)) linkedStyles.add(`assets/${match[1]}`);
120
142
  }
121
143
  }
122
144
  };
@@ -130,24 +152,28 @@ export function packageTheme(themeRoot) {
130
152
  else if (entry.isFile() && !relative.endsWith('.map') && (!sourceStyles.has(relative) || linkedStyles.has(relative))) files.push(relative);
131
153
  }
132
154
  };
133
- for (const dir of ['partials', 'assets']) if (fs.existsSync(inside(root, dir))) collect(dir);
155
+ for (const dir of ['partials', 'assets', 'locales', 'members']) if (existsSafe(root, dir)) collect(dir);
134
156
  const chunks = [], directory = [];
135
157
  let offset = 0;
136
158
  for (const file of files.sort()) {
137
159
  const name = Buffer.from(file.replaceAll('\\', '/'));
138
160
  const data = fs.readFileSync(inside(root, file));
161
+ const deflated = zlib.deflateRawSync(data);
162
+ const useDeflate = deflated.length < data.length;
163
+ const payload = useDeflate ? deflated : data;
164
+ const method = useDeflate ? 8 : 0;
139
165
  const crc = crc32(data);
140
166
  const local = Buffer.alloc(30);
141
- local.writeUInt32LE(0x04034b50); local.writeUInt16LE(20, 4); local.writeUInt16LE(0x800, 6);
167
+ local.writeUInt32LE(0x04034b50); local.writeUInt16LE(20, 4); local.writeUInt16LE(0x800, 6); local.writeUInt16LE(method, 8);
142
168
  local.writeUInt16LE(33, 12); // 1980-01-01: deterministic archive timestamps
143
- local.writeUInt32LE(crc, 14); local.writeUInt32LE(data.length, 18); local.writeUInt32LE(data.length, 22); local.writeUInt16LE(name.length, 26);
144
- chunks.push(local, name, data);
169
+ local.writeUInt32LE(crc, 14); local.writeUInt32LE(payload.length, 18); local.writeUInt32LE(data.length, 22); local.writeUInt16LE(name.length, 26);
170
+ chunks.push(local, name, payload);
145
171
  const central = Buffer.alloc(46);
146
- central.writeUInt32LE(0x02014b50); central.writeUInt16LE(20, 4); central.writeUInt16LE(20, 6); central.writeUInt16LE(0x800, 8);
147
- central.writeUInt16LE(33, 14); central.writeUInt32LE(crc, 16); central.writeUInt32LE(data.length, 20); central.writeUInt32LE(data.length, 24);
172
+ central.writeUInt32LE(0x02014b50); central.writeUInt16LE(20, 4); central.writeUInt16LE(20, 6); central.writeUInt16LE(0x800, 8); central.writeUInt16LE(method, 10);
173
+ central.writeUInt16LE(33, 14); central.writeUInt32LE(crc, 16); central.writeUInt32LE(payload.length, 20); central.writeUInt32LE(data.length, 24);
148
174
  central.writeUInt16LE(name.length, 28); central.writeUInt32LE(offset, 42);
149
175
  directory.push(central, name);
150
- offset += local.length + name.length + data.length;
176
+ offset += local.length + name.length + payload.length;
151
177
  }
152
178
  if (files.length > 65535 || offset > 0xffffffff) throw new Error('Theme exceeds ZIP32 limits');
153
179
  const central = Buffer.concat(directory), end = Buffer.alloc(22);
@@ -160,6 +186,11 @@ export function packageTheme(themeRoot) {
160
186
  return { output, files };
161
187
  }
162
188
 
189
+ function existsSafe(root, dir) {
190
+ const target = inside(root, dir);
191
+ return fs.existsSync(target) && fs.statSync(target).isDirectory();
192
+ }
193
+
163
194
  export function reportTheme(themeRoot) {
164
195
  const result = inspectTheme(themeRoot);
165
196
  for (const warning of result.warnings) console.warn(`WARN: ${warning}`);
@@ -169,7 +200,14 @@ export function reportTheme(themeRoot) {
169
200
  return true;
170
201
  }
171
202
 
172
- if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
203
+ const isEntrypoint = (argvPath, metaUrl) => {
204
+ if (!argvPath) return false;
205
+ const left = path.resolve(argvPath);
206
+ const right = fileURLToPath(metaUrl);
207
+ return process.platform === 'win32' ? left.toLowerCase() === right.toLowerCase() : left === right;
208
+ };
209
+
210
+ if (isEntrypoint(process.argv[1], import.meta.url)) {
173
211
  const root = path.resolve(process.argv[3] || process.cwd());
174
212
  try {
175
213
  if (process.argv[2] === 'pack') console.log(`Created ${packageTheme(root).output}`);
@@ -15,4 +15,4 @@ export declare function compareComponent(themeRoot: string, config: GhostcnConfi
15
15
  incomingRevision: string;
16
16
  files: FileComparison[];
17
17
  };
18
- export declare function unifiedDiff(before: string | undefined, after: string | undefined, label: string): string;
18
+ export declare function unifiedDiff(before: string | undefined, after: string | undefined, label: string, contextLines?: number): string;
@@ -28,6 +28,7 @@ async function comparisonManifest(name, latest) {
28
28
  throw new Error('Registry returned an invalid component manifest.');
29
29
  return manifest;
30
30
  }
31
+ const normalizeEol = (value) => value?.replace(/\r\n/g, '\n');
31
32
  function compareComponent(themeRoot, config, manifest) {
32
33
  const files = (0, component_files_1.componentFiles)(themeRoot, config, manifest);
33
34
  const saved = (0, component_history_1.readHistory)(themeRoot).components[manifest.name];
@@ -38,18 +39,21 @@ function compareComponent(themeRoot, config, manifest) {
38
39
  const baseline = saved?.files[relative];
39
40
  const local = fs_1.default.existsSync(target) ? fs_1.default.readFileSync(target, 'utf8') : undefined;
40
41
  const next = incoming[relative];
42
+ const normBaseline = normalizeEol(baseline);
43
+ const normLocal = normalizeEol(local);
44
+ const normNext = normalizeEol(next);
41
45
  let status;
42
46
  if (next === undefined)
43
47
  status = 'removed-upstream';
44
48
  else if (local === undefined)
45
49
  status = 'missing';
46
- else if (local === next)
50
+ else if (normLocal === normNext)
47
51
  status = 'unchanged';
48
52
  else if (baseline === undefined)
49
53
  status = 'untracked';
50
- else if (baseline === next)
54
+ else if (normBaseline === normNext)
51
55
  status = 'locally-modified';
52
- else if (baseline === local)
56
+ else if (normBaseline === normLocal)
53
57
  status = 'upstream-changed';
54
58
  else
55
59
  status = 'conflict';
@@ -57,37 +61,62 @@ function compareComponent(themeRoot, config, manifest) {
57
61
  });
58
62
  return { name: manifest.name, installedRevision: saved?.revision, incomingRevision: (0, component_history_1.revision)(incoming), files: comparisons };
59
63
  }
60
- // Complete line diff with bounded memory. Large files remain reviewable as replacement hunks.
61
- function unifiedDiff(before, after, label) {
62
- if (before === after)
64
+ // Contextual line diff (3-line hunks) with bounded memory. Large files remain reviewable as replacement hunks.
65
+ function unifiedDiff(before, after, label, contextLines = 3) {
66
+ if (normalizeEol(before) === normalizeEol(after))
63
67
  return '';
64
- const split = (value) => value?.replace(/\r\n/g, '\n').match(/[^\n]*\n|[^\n]+$/g) || [];
68
+ const split = (value) => normalizeEol(value)?.match(/[^\n]*\n|[^\n]+$/g) || [];
65
69
  const a = split(before);
66
70
  const b = split(after);
67
- const lines = [`--- ${label} (local)`, `+++ ${label} (registry)`, `@@ -${a.length ? 1 : 0},${a.length} +${b.length ? 1 : 0},${b.length} @@`];
68
- const emit = (prefix, value) => {
69
- lines.push(prefix + (value.endsWith('\n') ? value.slice(0, -1) : value));
71
+ const header = [`--- ${label} (local)`, `+++ ${label} (registry)`];
72
+ const formatLine = (prefix, value) => {
73
+ const out = [prefix + (value.endsWith('\n') ? value.slice(0, -1) : value)];
70
74
  if (!value.endsWith('\n'))
71
- lines.push('\');
75
+ out.push('\');
76
+ return out;
72
77
  };
73
78
  if (a.length * b.length > 1_000_000) {
74
- a.forEach(value => emit('-', value));
75
- b.forEach(value => emit('+', value));
76
- return lines.join('\n');
79
+ const out = [...header, `@@ -${a.length ? 1 : 0},${a.length} +${b.length ? 1 : 0},${b.length} @@`];
80
+ a.forEach(value => out.push(...formatLine('-', value)));
81
+ b.forEach(value => out.push(...formatLine('+', value)));
82
+ return out.join('\n');
77
83
  }
78
84
  const width = b.length + 1;
79
85
  const matrix = new Uint32Array((a.length + 1) * width);
80
86
  for (let i = a.length - 1; i >= 0; i--)
81
87
  for (let j = b.length - 1; j >= 0; j--)
82
88
  matrix[i * width + j] = a[i] === b[j] ? 1 + matrix[(i + 1) * width + j + 1] : Math.max(matrix[(i + 1) * width + j], matrix[i * width + j + 1]);
89
+ const ops = [];
83
90
  let i = 0, j = 0;
84
91
  while (i < a.length || j < b.length) {
85
92
  if (i < a.length && j < b.length && a[i] === b[j])
86
- emit(' ', a[i++]), j++;
93
+ ops.push({ kind: ' ', value: a[i], oldLine: i + 1, newLine: j + 1 }), i++, j++;
87
94
  else if (i < a.length && (j === b.length || matrix[(i + 1) * width + j] >= matrix[i * width + j + 1]))
88
- emit('-', a[i++]);
95
+ ops.push({ kind: '-', value: a[i], oldLine: i + 1, newLine: j + 1 }), i++;
89
96
  else
90
- emit('+', b[j++]);
97
+ ops.push({ kind: '+', value: b[j], oldLine: i + 1, newLine: j + 1 }), j++;
98
+ }
99
+ const ranges = [];
100
+ ops.forEach((op, idx) => {
101
+ if (op.kind === ' ')
102
+ return;
103
+ const start = Math.max(0, idx - contextLines);
104
+ const end = Math.min(ops.length - 1, idx + contextLines);
105
+ if (ranges.length && start <= ranges[ranges.length - 1][1] + 1)
106
+ ranges[ranges.length - 1][1] = end;
107
+ else
108
+ ranges.push([start, end]);
109
+ });
110
+ const lines = [...header];
111
+ for (const [start, end] of ranges) {
112
+ const slice = ops.slice(start, end + 1);
113
+ const oldCount = slice.filter(op => op.kind !== '+').length;
114
+ const newCount = slice.filter(op => op.kind !== '-').length;
115
+ const oldStart = oldCount ? slice.find(op => op.kind !== '+').oldLine : Math.max(0, slice[0].oldLine - 1);
116
+ const newStart = newCount ? slice.find(op => op.kind !== '-').newLine : Math.max(0, slice[0].newLine - 1);
117
+ lines.push(`@@ -${oldStart},${oldCount} +${newStart},${newCount} @@`);
118
+ for (const op of slice)
119
+ lines.push(...formatLine(op.kind, op.value));
91
120
  }
92
121
  return lines.join('\n');
93
122
  }
@@ -40,9 +40,10 @@ function componentFiles(themeRoot, config, manifest) {
40
40
  throw new Error('Component target must be a file, not a directory.');
41
41
  if (file.type === 'style' || file.type === 'js')
42
42
  (0, theme_files_1.toGhostAssetPath)(relative);
43
- if (targets.has(target))
43
+ const key = process.platform === 'win32' ? target.toLowerCase() : target;
44
+ if (targets.has(key))
44
45
  throw new Error('Duplicate component target.');
45
- targets.add(target);
46
+ targets.add(key);
46
47
  return { relative: path_1.default.relative(path_1.default.resolve(themeRoot), target).replace(/\\/g, '/'), target, content: file.type === 'style' ? (0, styles_1.componentCss)(file.content, config.style) : file.type === 'partial' ? aliasedPartial(file.content, config) : file.content };
47
48
  });
48
49
  }
@@ -18,7 +18,7 @@ function readHistory(themeRoot) {
18
18
  const target = (0, component_files_1.safeThemePath)(themeRoot, '.ghostcn/installed.json');
19
19
  if (!fs_1.default.existsSync(target))
20
20
  return { schema: 1, components: {} };
21
- const state = JSON.parse(fs_1.default.readFileSync(target, 'utf8'));
21
+ const state = JSON.parse(fs_1.default.readFileSync(target, 'utf8').replace(/^\uFEFF/, ''));
22
22
  if (state.schema !== 1 || !state.components || Array.isArray(state.components) || typeof state.components !== 'object')
23
23
  throw new Error('Invalid .ghostcn/installed.json; preserve it and repair before continuing.');
24
24
  for (const [name, entry] of Object.entries(state.components)) {
@@ -39,19 +39,22 @@ function collectThemeFiles(themeRoot, directory, extension) {
39
39
  }
40
40
  function themeStyles(themeRoot, config) {
41
41
  const layout = (0, theme_files_1.safeThemePath)(themeRoot, 'default.hbs');
42
- const source = fs_1.default.existsSync(layout) ? fs_1.default.readFileSync(layout, 'utf8') : '';
42
+ const raw = fs_1.default.existsSync(layout) ? fs_1.default.readFileSync(layout, 'utf8') : '';
43
+ const source = raw.replace(/\{\{!--[\s\S]*?--\}\}/g, '').replace(/\{\{![\s\S]*?\}\}/g, '');
43
44
  const links = [];
44
- for (const link of source.match(/<link\b[^>]*>/g) || []) {
45
- if (!/rel=["']stylesheet["']/.test(link))
45
+ for (const link of source.match(/<link\b[^>]*>/gi) || []) {
46
+ if (!/\brel\s*=\s*["']stylesheet["']/i.test(link))
46
47
  continue;
47
48
  const asset = link.match(/\{\{asset\s+["']([^"']+\.css)["']\s*\}\}/)?.[1] || link.match(/href=["']\/assets\/([^"']+\.css)["']/)?.[1];
48
49
  if (asset && !links.includes(asset)) {
49
- (0, theme_files_1.safeThemePath)(themeRoot, `assets/${asset}`);
50
- links.push(asset);
50
+ const target = (0, theme_files_1.safeThemePath)(themeRoot, `assets/${asset}`);
51
+ if (fs_1.default.existsSync(target) && fs_1.default.statSync(target).isFile())
52
+ links.push(asset);
51
53
  }
52
54
  }
53
55
  if (!links.length) {
54
- const fallback = [config.cssFile, ...collectThemeFiles(themeRoot, config.aliases.styles, '.css').map(file => path_1.default.relative(themeRoot, file).replace(/\\/g, '/')), 'assets/built/screen.css'];
56
+ const styleFiles = config.aliases?.styles ? collectThemeFiles(themeRoot, config.aliases.styles, '.css').map(file => path_1.default.relative(themeRoot, file).replace(/\\/g, '/')) : [];
57
+ const fallback = [config.cssFile, ...styleFiles, 'assets/built/screen.css'].filter(Boolean);
55
58
  for (const relative of fallback)
56
59
  if (fs_1.default.existsSync((0, theme_files_1.safeThemePath)(themeRoot, relative)))
57
60
  links.push(relative.replace(/^assets\//, ''));
@@ -60,7 +63,10 @@ function themeStyles(themeRoot, config) {
60
63
  }
61
64
  async function startPlayground(options) {
62
65
  const themeRoot = fs_1.default.realpathSync(options.themeRoot);
63
- const config = JSON.parse(fs_1.default.readFileSync((0, theme_files_1.safeThemePath)(themeRoot, 'components.json'), 'utf8').replace(/^\uFEFF/, ''));
66
+ const configPath = (0, theme_files_1.safeThemePath)(themeRoot, 'components.json');
67
+ if (!fs_1.default.existsSync(configPath))
68
+ throw new Error('components.json was not found. Run "npx ghostcn init" from your Ghost theme root first.');
69
+ const config = JSON.parse(fs_1.default.readFileSync(configPath, 'utf8').replace(/^\uFEFF/, ''));
64
70
  if (!['css', 'tailwind'].includes(config.style) || !config.aliases)
65
71
  throw new Error('Invalid components.json. Run ghostcn doctor.');
66
72
  (0, component_files_1.componentPartialName)(config, 'button');
@@ -159,17 +165,25 @@ async function startPlayground(options) {
159
165
  partials[path_1.default.relative(path_1.default.join(themeRoot, 'partials'), file).replace(/\\/g, '/').replace(/\.hbs$/, '')] = fs_1.default.readFileSync(file, 'utf8');
160
166
  const parameters = { ...(preview_renderer_1.demoParameters[name] || {}) };
161
167
  const keys = new Set([...Object.keys(manifest.parameters || {}), ...Object.keys(manifest.styleSlots || {})]);
168
+ const boolKeys = new Set(['disabled', 'required', 'invalid', 'urgent', 'decorative', 'open', 'hideDismiss', 'showPublic']);
162
169
  for (const key of keys)
163
170
  if (url.searchParams.has(key))
164
- parameters[key] = ['disabled', 'required', 'invalid', 'urgent'].includes(key) ? url.searchParams.get(key) === 'true' : url.searchParams.get(key);
165
- const state = preview_renderer_1.previewStates.includes(url.searchParams.get('state') || '') ? url.searchParams.get('state') : 'visitor';
171
+ parameters[key] = boolKeys.has(key) ? url.searchParams.get(key) === 'true' : url.searchParams.get(key);
172
+ const allowedStates = [...preview_renderer_1.previewStates, 'free-only'];
173
+ const state = allowedStates.includes(url.searchParams.get('state') || '') ? url.searchParams.get('state') : 'visitor';
174
+ const access = url.searchParams.get('access') === 'false' ? false : true;
166
175
  const scheme = url.searchParams.get('scheme');
167
176
  const nameInTheme = name === 'pagination' ? 'pagination' : (0, component_files_1.componentPartialName)(config, name);
168
- const context = { ...(name === 'author-card' ? preview_renderer_1.demoAuthor : preview_renderer_1.previewDemoContext), ...parameters };
177
+ const baseContext = ['pricing-table', 'newsletter-form'].includes(name)
178
+ ? {}
179
+ : name === 'author-card'
180
+ ? preview_renderer_1.demoAuthor
181
+ : { ...preview_renderer_1.previewDemoContext, access };
182
+ const context = { ...baseContext, ...parameters };
169
183
  let source = (0, preview_renderer_1.previewInvocation)(nameInTheme, parameters);
170
184
  if (name === 'pagination')
171
185
  source = `{{> "pagination" pagination ${Object.keys(parameters).map(key => `${key}=${key}`).join(' ')}}}`;
172
- let html = (0, preview_renderer_1.renderPreviewTemplate)(partials, source, { state, context });
186
+ let html = (0, preview_renderer_1.renderPreviewTemplate)(partials, source, { state, context, access });
173
187
  if (name === 'table-of-contents')
174
188
  html += '<article class="ghcn-article-content"><h2>Start with your story</h2><p>Demo article.</p><h3>Make room for readers</h3><p>A subsection.</p><h2>Keep it yours</h2><p>Your theme, your style.</p></article>';
175
189
  const scripts = manifest.files.filter(file => file.type === 'js').map(file => (0, component_files_1.componentFiles)(themeRoot, config, manifest).find(target => target.relative.endsWith(`/${file.name}`))).filter(Boolean);
@@ -185,5 +199,13 @@ async function startPlayground(options) {
185
199
  }
186
200
  });
187
201
  await new Promise((resolve, reject) => { server.once('error', reject); server.listen(port, '127.0.0.1', () => { server.removeListener('error', reject); actualPort = server.address().port; resolve(); }); });
188
- return { server, url: `http://127.0.0.1:${actualPort}`, close: () => new Promise((resolve, reject) => server.close(error => error ? reject(error) : resolve())) };
202
+ return {
203
+ server,
204
+ url: `http://127.0.0.1:${actualPort}`,
205
+ close: () => new Promise((resolve, reject) => {
206
+ server.close(error => error ? reject(error) : resolve());
207
+ if (typeof server.closeAllConnections === 'function')
208
+ server.closeAllConnections();
209
+ })
210
+ };
189
211
  }
@@ -37,6 +37,7 @@ export declare const demoPost: {
37
37
  visibility: string;
38
38
  }[];
39
39
  access: boolean;
40
+ visibility: string;
40
41
  };
41
42
  export declare const demoPosts: {
42
43
  title: string;
@@ -67,6 +68,7 @@ export declare const demoPosts: {
67
68
  visibility: string;
68
69
  }[];
69
70
  access: boolean;
71
+ visibility: string;
70
72
  }[];
71
73
  export declare const previewStates: string[];
72
74
  export declare const previewDemoContext: {
@@ -99,6 +101,7 @@ export declare const previewDemoContext: {
99
101
  visibility: string;
100
102
  }[];
101
103
  access: boolean;
104
+ visibility: string;
102
105
  }[];
103
106
  pagination: {
104
107
  page: number;
@@ -134,10 +137,12 @@ export declare const previewDemoContext: {
134
137
  visibility: string;
135
138
  }[];
136
139
  access: boolean;
140
+ visibility: string;
137
141
  };
138
142
  export declare const demoParameters: Record<string, Record<string, string>>;
139
143
  export declare function renderPreviewTemplate(partials: Record<string, string>, template: string, options?: {
140
144
  state?: string;
141
145
  context?: Record<string, unknown>;
146
+ access?: boolean;
142
147
  }): string;
143
148
  export declare function previewInvocation(partialName: string, parameters: Record<string, unknown>): string;
@@ -16,7 +16,7 @@ const secondImage = editorialImage('#cbd1c5', '#374738', '<circle cx="600" cy="3
16
16
  const thirdImage = editorialImage('#dbc7bb', '#6a483e', '<path d="M334 454l140-235 127 208 126-208 140 235z"/><path d="M312 485h576v40H312z" fill="#9c6956"/><circle cx="603" cy="166" r="44" fill="#f5e4cd"/>');
17
17
  exports.demoAuthor = { name: 'Alex Reader', url: '/author/alex/', bio: 'Writing about independent publishing, thoughtful design, and building a home for your readers.', location: 'Everywhere', count: { posts: 12 } };
18
18
  const tags = [{ name: 'Publishing', description: 'Stories about independent publishing.', url: '/tag/publishing/', visibility: 'public' }, { name: 'Design', description: 'The details that make it yours.', url: '/tag/design/', visibility: 'public' }];
19
- exports.demoPost = { title: 'A home for independent ideas', url: '/a-home-for-independent-ideas/', excerpt: 'Good stories deserve a place of their own. Build a publication around your ideas, your community, and your voice.', custom_excerpt: 'Good stories deserve a place of their own.', feature_image: exports.demoImage, feature_image_alt: 'An abstract illustration of folded paper', primary_author: exports.demoAuthor, primary_tag: tags[0], tags, access: true };
19
+ exports.demoPost = { title: 'A home for independent ideas', url: '/a-home-for-independent-ideas/', excerpt: 'Good stories deserve a place of their own. Build a publication around your ideas, your community, and your voice.', custom_excerpt: 'Good stories deserve a place of their own.', feature_image: exports.demoImage, feature_image_alt: 'An abstract illustration of folded paper', primary_author: exports.demoAuthor, primary_tag: tags[0], tags, access: true, visibility: 'members' };
20
20
  exports.demoPosts = [
21
21
  exports.demoPost,
22
22
  { ...exports.demoPost, title: 'Make room for your readers', url: '/make-room-for-your-readers/', feature_image: secondImage, feature_image_alt: 'An abstract illustration of intersecting circles', excerpt: 'A thoughtful reading experience starts with space for the story and a clear path to what comes next.' },
@@ -32,10 +32,19 @@ exports.demoParameters = {
32
32
  input: { label: 'Email address', type: 'email', name: 'email', placeholder: 'you@example.com', hint: 'We will keep your email private.', hintId: 'demo-email-hint' },
33
33
  alert: { heading: 'You are all set', description: 'Your theme is ready to customize.' },
34
34
  'post-grid': { heading: 'Latest stories' }, 'author-list': { heading: 'Meet the authors' }, 'tag-grid': { heading: 'Explore topics' },
35
- 'archive-header': { heading: 'Publishing', description: 'Ideas for a publication of your own.', eyebrow: 'Topic', archiveImage: exports.demoImage, imageAlt: 'Demo archive image' }
35
+ 'archive-header': { heading: 'Publishing', description: 'Ideas for a publication of your own.', eyebrow: 'Topic', archiveImage: exports.demoImage, imageAlt: 'Demo archive image' },
36
+ avatar: { name: 'Alex Reader' },
37
+ accordion: { heading: 'How does membership work?', body: 'Choose a free or paid tier in Ghost Portal to unlock member-only essays and newsletters.' },
38
+ 'theme-toggle': { ariaLabel: 'Color theme' },
39
+ 'announcement-bar': { text: 'Issue 14 is live — read our spring editorial report.', linkText: 'Read issue', href: '/archive/' },
40
+ 'reading-progress': { initialValue: '42' },
41
+ 'share-buttons': { heading: 'Share' },
42
+ breadcrumbs: { homeLabel: 'Home' },
43
+ 'visibility-badge': { membersLabel: 'Members only' }
36
44
  };
37
45
  function renderPreviewTemplate(partials, template, options = {}) {
38
46
  const state = options.state || 'visitor';
47
+ const postContext = options.access === undefined ? exports.demoPost : { ...exports.demoPost, access: options.access };
39
48
  const hbs = handlebars_1.default.create();
40
49
  hbs.registerPartial(partials);
41
50
  hbs.registerHelper('foreach', (items, opts) => {
@@ -49,10 +58,14 @@ function renderPreviewTemplate(partials, template, options = {}) {
49
58
  hbs.registerHelper('get', (resource, opts) => opts.fn(resource === 'tiers' ? { tiers } : resource === 'authors' ? { authors: [exports.demoAuthor] } : resource === 'tags' ? { tags } : { posts: exports.demoPosts }, { data: opts.data }));
50
59
  hbs.registerHelper('match', function (value, expected, opts) { return value === expected ? opts.fn(this) : opts.inverse(this); });
51
60
  hbs.registerHelper('has', function (opts) { return String(opts.data?.index) === opts.hash.index ? opts.fn(this) : opts.inverse(this); });
52
- hbs.registerHelper('post', opts => opts.fn(exports.demoPost, { data: opts.data }));
61
+ hbs.registerHelper('post', opts => opts.fn(postContext, { data: opts.data }));
53
62
  hbs.registerHelper('primary_author', function (opts) { return opts.fn(this.primary_author, { data: opts.data }); });
54
63
  hbs.registerHelper('img_url', value => value);
55
- hbs.registerHelper('url', function () { return this.url; });
64
+ hbs.registerHelper('url', function (opts) {
65
+ const pathUrl = this.url || '/a-home-for-independent-ideas/';
66
+ return opts?.hash?.absolute ? `https://example.com${pathUrl}` : pathUrl;
67
+ });
68
+ hbs.registerHelper('encode', value => encodeURIComponent(String(value ?? '')));
56
69
  hbs.registerHelper('excerpt', function () { return this.excerpt; });
57
70
  hbs.registerHelper('asset', value => `/theme-assets/${value}`);
58
71
  hbs.registerHelper('reading_time', () => '4 min read');
@@ -63,9 +76,10 @@ function renderPreviewTemplate(partials, template, options = {}) {
63
76
  hbs.registerHelper('navigation', () => new hbs.SafeString('<ul class="nav"><li class="nav-current"><a href="/">Home</a></li><li><a href="/about/">About</a></li><li><a href="/archive/">Archive</a></li></ul>'));
64
77
  hbs.registerHelper('search', () => new hbs.SafeString('<button type="button" class="ghcn-icon-button ghcn-button--ghost" aria-label="Search"><svg width="20" height="20" viewBox="0 0 24 24" aria-hidden="true"><circle cx="10" cy="10" r="6" fill="none" stroke="currentColor" stroke-width="2"/><path d="m15 15 6 6" stroke="currentColor" stroke-width="2"/></svg></button>'));
65
78
  hbs.registerHelper('price', (amount, opts) => new Intl.NumberFormat('en', { style: 'currency', currency: opts.hash.currency }).format(amount / 100));
66
- const site = { title: 'Ghostcn Journal', url: '/', description: 'Independent ideas, shared with your readers.', locale: 'en', members_enabled: state !== 'disabled', paid_members_enabled: state !== 'disabled', members_invite_only: state === 'invite', allow_self_signup: !['disabled', 'invite', 'restricted'].includes(state) };
79
+ const site = { title: 'Ghostcn Journal', url: '/', description: 'Independent ideas, shared with your readers.', locale: 'en', members_enabled: state !== 'disabled', paid_members_enabled: state !== 'disabled' && state !== 'free-only', members_invite_only: state === 'invite', allow_self_signup: !['disabled', 'invite', 'restricted'].includes(state) };
67
80
  const data = { site, member: ['free', 'paid'].includes(state) ? { paid: state === 'paid' } : undefined };
68
- return hbs.compile(template)(options.context || exports.previewDemoContext, { data });
81
+ const context = options.context || (options.access === undefined ? exports.previewDemoContext : { ...exports.previewDemoContext, access: options.access });
82
+ return hbs.compile(template)(context, { data });
69
83
  }
70
84
  function previewInvocation(partialName, parameters) {
71
85
  // Values are bound as data, never interpolated into executable Handlebars source.
@@ -35,22 +35,32 @@ async function fetchRegistryJson(url, timeoutMs = 5000) {
35
35
  controller.abort();
36
36
  }
37
37
  }
38
+ function safeRegistryBase(raw) {
39
+ const url = new URL(raw.trim().replace(/\/+$/, ''));
40
+ if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password) {
41
+ throw new Error('Invalid GHOST_UI_REGISTRY_URL.');
42
+ }
43
+ return url.href.replace(/\/+$/, '');
44
+ }
45
+ function isValidRegistryDir(dir) {
46
+ return fs_1.default.existsSync(path_1.default.join(dir, 'index.json')) && fs_1.default.statSync(path_1.default.join(dir, 'index.json')).isFile();
47
+ }
38
48
  function findLocalRegistryDir() {
39
49
  const bundledCandidates = [
40
50
  path_1.default.join(__dirname, 'registry'),
41
51
  path_1.default.join(__dirname, '..', 'registry')
42
52
  ];
43
53
  for (const cand of bundledCandidates) {
44
- if (fs_1.default.existsSync(cand) && fs_1.default.statSync(cand).isDirectory()) {
54
+ if (isValidRegistryDir(cand)) {
45
55
  return cand;
46
56
  }
47
57
  }
48
- const searchStarts = [process.cwd(), __dirname];
58
+ const searchStarts = [__dirname, process.cwd()];
49
59
  for (const start of searchStarts) {
50
60
  let currentDir = start;
51
61
  while (currentDir !== path_1.default.parse(currentDir).root) {
52
62
  const potentialPath = path_1.default.join(currentDir, 'registry');
53
- if (fs_1.default.existsSync(potentialPath) && fs_1.default.statSync(potentialPath).isDirectory()) {
63
+ if (isValidRegistryDir(potentialPath)) {
54
64
  return potentialPath;
55
65
  }
56
66
  currentDir = path_1.default.dirname(currentDir);
@@ -92,7 +102,7 @@ async function getRegistryIndex() {
92
102
  // If custom registry URL explicitly configured, try remote first
93
103
  if (process.env.GHOST_UI_REGISTRY_URL) {
94
104
  try {
95
- return await fetchRegistryJson(`${process.env.GHOST_UI_REGISTRY_URL}/index.json`);
105
+ return await fetchRegistryJson(`${safeRegistryBase(process.env.GHOST_UI_REGISTRY_URL)}/index.json`);
96
106
  }
97
107
  catch {
98
108
  // Fallback to local
@@ -117,7 +127,7 @@ async function getComponent(componentName) {
117
127
  // If custom registry URL explicitly configured, try remote first
118
128
  if (process.env.GHOST_UI_REGISTRY_URL) {
119
129
  try {
120
- return await fetchRegistryJson(`${process.env.GHOST_UI_REGISTRY_URL}/components/${sanitized}.json`);
130
+ return await fetchRegistryJson(`${safeRegistryBase(process.env.GHOST_UI_REGISTRY_URL)}/components/${sanitized}.json`);
121
131
  }
122
132
  catch {
123
133
  // Fallback to local