ghostcn 1.5.0 → 1.7.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 (88) 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/account-card.json +57 -0
  7. package/dist/registry/components/announcement-bar.json +79 -0
  8. package/dist/registry/components/archive-header.json +1 -1
  9. package/dist/registry/components/author-card.json +2 -2
  10. package/dist/registry/components/author-list.json +1 -1
  11. package/dist/registry/components/author-stack.json +63 -0
  12. package/dist/registry/components/avatar.json +62 -0
  13. package/dist/registry/components/back-to-top.json +72 -0
  14. package/dist/registry/components/breadcrumbs.json +59 -0
  15. package/dist/registry/components/button.json +1 -1
  16. package/dist/registry/components/callout.json +56 -0
  17. package/dist/registry/components/checkbox.json +82 -0
  18. package/dist/registry/components/code-copy.json +52 -0
  19. package/dist/registry/components/comments-section.json +56 -0
  20. package/dist/registry/components/dialog.json +83 -0
  21. package/dist/registry/components/dropdown.json +85 -0
  22. package/dist/registry/components/empty-state.json +65 -0
  23. package/dist/registry/components/error-card.json +74 -0
  24. package/dist/registry/components/faq-section.json +83 -0
  25. package/dist/registry/components/featured-posts.json +2 -2
  26. package/dist/registry/components/hero.json +89 -0
  27. package/dist/registry/components/image-lightbox.json +44 -0
  28. package/dist/registry/components/input.json +8 -2
  29. package/dist/registry/components/magazine-grid.json +62 -0
  30. package/dist/registry/components/member-cta.json +1 -1
  31. package/dist/registry/components/mobile-dock.json +69 -0
  32. package/dist/registry/components/newsletter-form.json +12 -3
  33. package/dist/registry/components/pagination.json +2 -2
  34. package/dist/registry/components/post-card.json +2 -2
  35. package/dist/registry/components/post-grid.json +2 -2
  36. package/dist/registry/components/post-header.json +2 -2
  37. package/dist/registry/components/post-list.json +62 -0
  38. package/dist/registry/components/pricing-table.json +24 -4
  39. package/dist/registry/components/pull-quote.json +70 -0
  40. package/dist/registry/components/radio-group.json +94 -0
  41. package/dist/registry/components/reader-controls.json +60 -0
  42. package/dist/registry/components/reading-meta.json +49 -0
  43. package/dist/registry/components/reading-progress.json +73 -0
  44. package/dist/registry/components/related-posts.json +7 -1
  45. package/dist/registry/components/search-trigger.json +68 -0
  46. package/dist/registry/components/select.json +94 -0
  47. package/dist/registry/components/separator.json +46 -0
  48. package/dist/registry/components/series-nav.json +62 -0
  49. package/dist/registry/components/share-buttons.json +76 -0
  50. package/dist/registry/components/site-footer.json +2 -2
  51. package/dist/registry/components/site-header.json +1 -1
  52. package/dist/registry/components/skeleton.json +48 -0
  53. package/dist/registry/components/skip-link.json +53 -0
  54. package/dist/registry/components/social-links.json +74 -0
  55. package/dist/registry/components/stat-strip.json +85 -0
  56. package/dist/registry/components/sticky-subscribe.json +82 -0
  57. package/dist/registry/components/subscribe-bar.json +61 -0
  58. package/dist/registry/components/switch.json +76 -0
  59. package/dist/registry/components/table-of-contents.json +12 -2
  60. package/dist/registry/components/tabs.json +81 -0
  61. package/dist/registry/components/tag-bar.json +63 -0
  62. package/dist/registry/components/tag-grid.json +1 -1
  63. package/dist/registry/components/tag-list.json +1 -1
  64. package/dist/registry/components/textarea.json +95 -0
  65. package/dist/registry/components/theme-toggle.json +65 -0
  66. package/dist/registry/components/tier-comparison.json +55 -0
  67. package/dist/registry/components/timeline.json +85 -0
  68. package/dist/registry/components/tooltip.json +65 -0
  69. package/dist/registry/components/visibility-badge.json +71 -0
  70. package/dist/registry/index.json +478 -4
  71. package/dist/templates/playground/index.html +2 -2
  72. package/dist/templates/playground/playground.css +8 -1
  73. package/dist/templates/playground/playground.js +39 -5
  74. package/dist/templates/playground/preview.css +1 -0
  75. package/dist/templates/theme-tools.mjs +62 -24
  76. package/dist/utils/component-diff.d.ts +1 -1
  77. package/dist/utils/component-diff.js +46 -17
  78. package/dist/utils/component-files.js +3 -2
  79. package/dist/utils/component-history.js +1 -1
  80. package/dist/utils/playground-server.js +40 -12
  81. package/dist/utils/preview-renderer.d.ts +77 -0
  82. package/dist/utils/preview-renderer.js +68 -8
  83. package/dist/utils/registry.js +15 -5
  84. package/dist/utils/theme-files.js +14 -7
  85. package/dist/utils/theme-project.js +6 -4
  86. package/dist/utils/theme-scaffold.js +22 -7
  87. package/dist/utils/theme.js +39 -32
  88. 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,19 +165,33 @@ 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', 'checked', 'showSubscribe', 'showImage', 'hideMeta', 'showLabel', 'alwaysVisible', 'hideShortcut', 'hideRss', 'hideAll', 'showCounts', 'hideSearch']);
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', 'subscribe-bar', 'tier-comparison'].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>';
189
+ if (name === 'code-copy')
190
+ html += '<article class="ghcn-article-content"><pre><code class="language-handlebars">{{&gt; &quot;components/callout&quot;\n variant=&quot;tip&quot;\n heading=&quot;Pro tip&quot;\n body=&quot;Click Copy to grab this snippet.&quot;\n}}</code></pre></article>';
191
+ if (name === 'image-lightbox')
192
+ html += `<article class="ghcn-article-content"><figure class="kg-card kg-image-card"><img src="${escape(preview_renderer_1.demoImage)}" alt="Folded paper editorial illustration" /><figcaption>Click the image to open the native lightbox viewer.</figcaption></figure></article>`;
193
+ if (name === 'reader-controls')
194
+ html += '<article class="ghcn-article-content"><p>Good stories deserve comfortable typography. Use the controls above to switch between compact, default, and large text sizes or toggle between Sans and Serif.</p></article>';
175
195
  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);
176
196
  const styles = themeStyles(themeRoot, config).map(asset => `<link rel="stylesheet" href="/theme-assets/${escape(asset)}">`).join('');
177
197
  const scriptTags = scripts.map(file => `<script defer src="/theme-assets/${escape(file.relative.replace(/^assets\//, ''))}"></script>`).join('');
@@ -185,5 +205,13 @@ async function startPlayground(options) {
185
205
  }
186
206
  });
187
207
  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())) };
208
+ return {
209
+ server,
210
+ url: `http://127.0.0.1:${actualPort}`,
211
+ close: () => new Promise((resolve, reject) => {
212
+ server.close(error => error ? reject(error) : resolve());
213
+ if (typeof server.closeAllConnections === 'function')
214
+ server.closeAllConnections();
215
+ })
216
+ };
189
217
  }
@@ -24,19 +24,38 @@ export declare const demoPost: {
24
24
  posts: number;
25
25
  };
26
26
  };
27
+ authors: {
28
+ name: string;
29
+ url: string;
30
+ bio: string;
31
+ location: string;
32
+ count: {
33
+ posts: number;
34
+ };
35
+ }[];
27
36
  primary_tag: {
28
37
  name: string;
38
+ slug: string;
29
39
  description: string;
30
40
  url: string;
31
41
  visibility: string;
42
+ count: {
43
+ posts: number;
44
+ };
32
45
  };
33
46
  tags: {
34
47
  name: string;
48
+ slug: string;
35
49
  description: string;
36
50
  url: string;
37
51
  visibility: string;
52
+ count: {
53
+ posts: number;
54
+ };
38
55
  }[];
39
56
  access: boolean;
57
+ visibility: string;
58
+ comments: boolean;
40
59
  };
41
60
  export declare const demoPosts: {
42
61
  title: string;
@@ -54,19 +73,38 @@ export declare const demoPosts: {
54
73
  posts: number;
55
74
  };
56
75
  };
76
+ authors: {
77
+ name: string;
78
+ url: string;
79
+ bio: string;
80
+ location: string;
81
+ count: {
82
+ posts: number;
83
+ };
84
+ }[];
57
85
  primary_tag: {
58
86
  name: string;
87
+ slug: string;
59
88
  description: string;
60
89
  url: string;
61
90
  visibility: string;
91
+ count: {
92
+ posts: number;
93
+ };
62
94
  };
63
95
  tags: {
64
96
  name: string;
97
+ slug: string;
65
98
  description: string;
66
99
  url: string;
67
100
  visibility: string;
101
+ count: {
102
+ posts: number;
103
+ };
68
104
  }[];
69
105
  access: boolean;
106
+ visibility: string;
107
+ comments: boolean;
70
108
  }[];
71
109
  export declare const previewStates: string[];
72
110
  export declare const previewDemoContext: {
@@ -86,19 +124,38 @@ export declare const previewDemoContext: {
86
124
  posts: number;
87
125
  };
88
126
  };
127
+ authors: {
128
+ name: string;
129
+ url: string;
130
+ bio: string;
131
+ location: string;
132
+ count: {
133
+ posts: number;
134
+ };
135
+ }[];
89
136
  primary_tag: {
90
137
  name: string;
138
+ slug: string;
91
139
  description: string;
92
140
  url: string;
93
141
  visibility: string;
142
+ count: {
143
+ posts: number;
144
+ };
94
145
  };
95
146
  tags: {
96
147
  name: string;
148
+ slug: string;
97
149
  description: string;
98
150
  url: string;
99
151
  visibility: string;
152
+ count: {
153
+ posts: number;
154
+ };
100
155
  }[];
101
156
  access: boolean;
157
+ visibility: string;
158
+ comments: boolean;
102
159
  }[];
103
160
  pagination: {
104
161
  page: number;
@@ -121,23 +178,43 @@ export declare const previewDemoContext: {
121
178
  posts: number;
122
179
  };
123
180
  };
181
+ authors: {
182
+ name: string;
183
+ url: string;
184
+ bio: string;
185
+ location: string;
186
+ count: {
187
+ posts: number;
188
+ };
189
+ }[];
124
190
  primary_tag: {
125
191
  name: string;
192
+ slug: string;
126
193
  description: string;
127
194
  url: string;
128
195
  visibility: string;
196
+ count: {
197
+ posts: number;
198
+ };
129
199
  };
130
200
  tags: {
131
201
  name: string;
202
+ slug: string;
132
203
  description: string;
133
204
  url: string;
134
205
  visibility: string;
206
+ count: {
207
+ posts: number;
208
+ };
135
209
  }[];
136
210
  access: boolean;
211
+ visibility: string;
212
+ comments: boolean;
137
213
  };
138
214
  export declare const demoParameters: Record<string, Record<string, string>>;
139
215
  export declare function renderPreviewTemplate(partials: Record<string, string>, template: string, options?: {
140
216
  state?: string;
141
217
  context?: Record<string, unknown>;
218
+ access?: boolean;
142
219
  }): string;
143
220
  export declare function previewInvocation(partialName: string, parameters: Record<string, unknown>): string;