@prenta/cli 1.0.0 → 1.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.
@@ -1,4 +1,4 @@
1
1
 
2
- > @prenta/cli@1.0.0 build /home/runner/work/prenta/prenta/packages/cli
2
+ > @prenta/cli@1.1.0 build /home/runner/work/prenta/prenta/packages/cli
3
3
  > tsc
4
4
 
@@ -1,27 +1,44 @@
1
1
 
2
- > @prenta/cli@1.0.0 test /home/runner/work/prenta/prenta/packages/cli
2
+ > @prenta/cli@1.1.0 test /home/runner/work/prenta/prenta/packages/cli
3
3
  > vitest run "--no-file-parallelism"
4
4
 
5
5
 
6
6
   RUN  v4.1.8 /home/runner/work/prenta/prenta/packages/cli
7
7
 
8
- ✓ src/__tests__/db-restore.test.ts (34 tests) 3140ms
9
- ✓ src/__tests__/db-backup.test.ts (27 tests) 1205ms
10
- ✓ src/__tests__/deployment-diagnostics.test.ts (23 tests) 127ms
11
- ✓ src/__tests__/backup-blob-store.test.ts (18 tests) 486ms
12
- ✓ src/__tests__/backup-pg-tools.test.ts (26 tests) 333ms
13
- ✓ src/__tests__/db-sync.test.ts (13 tests) 961ms
8
+ ✓ src/__tests__/db-restore.test.ts (34 tests) 9820ms
9
+ ✓ requires --target and never defaults to the env database  416ms
10
+ ✓ rejects a --target whose path names no database (empty or "/") before any download  423ms
11
+ ✓ warns when --target carries a password on argv and recommends PGPASSWORD instead  588ms
12
+ ✓ OIDC mode (VERCEL_OIDC_TOKEN + BLOB_STORE_ID) lists and restores without passing a token  853ms
13
+ ✓ Prisma Postgres: a fresh database (different user, same host + db) restores with --yes  314ms
14
+ ✓ compares the typed name against the normalized database name and never accepts an empty answer  539ms
15
+ ✓ with the flag, still requires typing the database name — --yes does not skip it  436ms
16
+ ✓ verifies sha256, decrypts, runs pg_restore with the exact argv and prints counts  354ms
17
+ ✓ --list prints available backups newest first with stamps and sizes  323ms
18
+ ✓ "latest" selects the newest stamp under the prefix  435ms
19
+ ✓ honours --prefix for latest  335ms
20
+ ✓ says which interpretation won when <source> is both a local file and a Blob-looking pathname  353ms
21
+ ✓ registers db:restore with <source>, --target and the safety flag  353ms
22
+ ✓ src/__tests__/db-backup.test.ts (27 tests) 4535ms
23
+ ✓ writes the workflow YAML verbatim and exits 0 without touching the database  391ms
24
+ ✓ refuses localhost / 127.0.0.1 unless --allow-local  660ms
25
+ ✓ dumps with the exact argv, encrypts, and writes a verifiable manifest  311ms
26
+ ✓ src/__tests__/deployment-diagnostics.test.ts (23 tests) 438ms
27
+ ✓ src/__tests__/backup-blob-store.test.ts (18 tests) 1084ms
28
+ ✓ src/__tests__/backup-pg-tools.test.ts (26 tests) 449ms
29
+ ✓ src/__tests__/db-sync.test.ts (13 tests) 675ms
30
+ ✓ src/__tests__/chrome.test.ts (11 tests) 19838ms
14
31
  ↓ src/__tests__/integration/backup-roundtrip.int.test.ts (1 test | 1 skipped)
15
- ✓ src/__tests__/backup-manifest.test.ts (17 tests) 188ms
16
- ✓ src/__tests__/backup-crypto.test.ts (13 tests) 987ms
17
- ✓ src/__tests__/seed.test.ts (10 tests) 223ms
18
- ✓ src/__tests__/backup-common.test.ts (14 tests) 144ms
32
+ ✓ src/__tests__/backup-manifest.test.ts (17 tests) 109ms
33
+ ✓ src/__tests__/backup-crypto.test.ts (13 tests) 403ms
34
+ ✓ src/__tests__/seed.test.ts (10 tests) 142ms
35
+ ✓ src/__tests__/backup-common.test.ts (14 tests) 69ms
19
36
  - Reading canonical Prenta schema...
37
+ ✔ Prenta CMS models added to schema.
20
38
  stdout | src/__tests__/db-init.test.ts > db:init (WS-D D5 — canonical schema, no stale fragment) > command > injects canonical models with @@map and no duplicate datasource/generator
21
39
  ✔ Prisma client generated.
22
40
  ℹ Run `npx prisma migrate dev --name prenta-cms` to create the migration.
23
41
 
24
- ✔ Prenta CMS models added to schema.
25
42
  - Running prisma generate...
26
43
  - Reading canonical Prenta schema...
27
44
  ✖ Could not locate @prenta/core.
@@ -29,16 +46,15 @@
29
46
  ℹ Install it first: `npm install @prenta/core`.
30
47
 
31
48
  - Reading canonical Prenta schema...
32
- stdout | src/__tests__/db-init.test.ts > db:init (WS-D D5 — canonical schema, no stale fragment) > command > is idempotent without --force
33
49
  ✔ Prenta CMS models added to schema.
50
+ - Running prisma generate...
51
+ stdout | src/__tests__/db-init.test.ts > db:init (WS-D D5 — canonical schema, no stale fragment) > command > is idempotent without --force
34
52
  ✔ Prisma client generated.
35
53
  ℹ Run `npx prisma migrate dev --name prenta-cms` to create the migration.
36
- - Running prisma generate...
37
54
 
38
55
  - Reading canonical Prenta schema...
39
56
  ℹ Prenta CMS models already present in schema. Use --force to overwrite.
40
- ✓ src/__tests__/db-init.test.ts (4 tests) 530ms
41
- ✓ injects canonical models with @@map and no duplicate datasource/generator  346ms
57
+ ✓ src/__tests__/db-init.test.ts (4 tests) 184ms
42
58
  stdout | src/__tests__/mcp-init.test.ts > mcp:init > creates both editor configs with placeholder key and git-ignores them
43
59
  ✔ Created .cursor/mcp.json
44
60
 
@@ -167,13 +183,13 @@ Next steps
167
183
  3. Restart Cursor / VS Code so the MCP server is picked up
168
184
  Tip: pass --url https://your-site.com to target a deployed CMS instead.
169
185
 
170
- ✓ src/__tests__/mcp-init.test.ts (6 tests) 735ms
171
- ✓ src/__tests__/prisma-client-path.test.ts (8 tests) 140ms
172
- ✓ src/__tests__/form-seed.test.ts (10 tests) 122ms
173
- ✓ src/__tests__/vercel-env-matrix.test.ts (6 tests) 84ms
174
- ✓ src/__tests__/upgrade.test.ts (3 tests) 129ms
175
- ✓ src/__tests__/repo-root.test.ts (4 tests) 118ms
176
- ✓ src/__tests__/load-dotenv.test.ts (3 tests) 157ms
186
+ ✓ src/__tests__/mcp-init.test.ts (6 tests) 155ms
187
+ ✓ src/__tests__/prisma-client-path.test.ts (8 tests) 53ms
188
+ ✓ src/__tests__/form-seed.test.ts (10 tests) 33ms
189
+ ✓ src/__tests__/vercel-env-matrix.test.ts (6 tests) 11ms
190
+ ✓ src/__tests__/upgrade.test.ts (3 tests) 19ms
191
+ ✓ src/__tests__/repo-root.test.ts (4 tests) 27ms
192
+ ✓ src/__tests__/load-dotenv.test.ts (3 tests) 60ms
177
193
  - Reading canonical Prenta schema...
178
194
  ✔ Prenta CMS models added to schema.
179
195
  - Running prisma generate...
@@ -181,14 +197,13 @@ Next steps
181
197
  ✔ Prisma client generated.
182
198
  ℹ Run `npx prisma migrate dev --name prenta-cms` to create the migration.
183
199
 
184
- ✓ src/__tests__/schema-fragment.test.ts (1 test) 267ms
185
- ✓ src/__tests__/db-sync-resolver.test.ts (4 tests) 30ms
186
- ✓ src/__tests__/import-typescript.test.ts (3 tests) 428ms
187
- ✓ loads a TypeScript file that imports a sibling without appending ?namespace=  400ms
188
- ✓ src/__tests__/init.test.ts (2 tests) 41ms
200
+ ✓ src/__tests__/schema-fragment.test.ts (1 test) 53ms
201
+ ✓ src/__tests__/db-sync-resolver.test.ts (4 tests) 15ms
202
+ ✓ src/__tests__/import-typescript.test.ts (3 tests) 228ms
203
+ ✓ src/__tests__/init.test.ts (2 tests) 20ms
189
204
 
190
-  Test Files  22 passed | 1 skipped (23)
191
-  Tests  249 passed | 1 skipped (250)
192
-  Start at  14:44:32
193
-  Duration  57.32s (transform 4.85s, setup 0ms, import 12.45s, tests 10.57s, environment 23ms)
205
+  Test Files  23 passed | 1 skipped (24)
206
+  Tests  260 passed | 1 skipped (261)
207
+  Start at  13:36:18
208
+  Duration  83.89s (transform 23.34s, setup 0ms, import 14.95s, tests 38.42s, environment 15ms)
194
209
 
package/CHANGELOG.md CHANGED
@@ -1,5 +1,27 @@
1
1
  # @actuate-media/cli
2
2
 
3
+ ## 1.1.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 69b9667: Porcelain, Linen, and Graphite replace the purple admin palette. Accent presets are Cobalt, Teal, Actuate coral, Rust, and Slate, each tuned to 4.5:1. Shared page header, count chip, tabs, and unsaved bar are new exports. Legacy accent names still resolve.
8
+
9
+ Jobs can be cancelled. A queued job stops immediately; a running job stops after the current slice. Review decisions, batch estimates, and the admin-only automatic apply rule are enforced in cms-core.
10
+
11
+ Menus keep a location on one menu and stop new indents at depth 2. Chrome is a code-first schema with `defineRegion` and `prenta pull chrome`. Form settings cover attribution windows, spam terms, closed forms, and retention.
12
+
13
+ - 69b9667: Sites declare what editors can change in their header and footer with `defineRegion(name, { component, variants, fields })` and `field.brand`, `menu`, `link`, `text`, `textarea`, `select`, `boolean` and `social`, from `@prenta/core/config`. Saved values are typed per region: `RegionValues<typeof header>` for what the CMS stores, `ChromeFieldsOf<typeof header>` for what the site receives. The earlier array-of-fields `defineRegion` and `DEFAULT_CHROME_SCHEMA` are gone, and the `@prenta/core/chrome/schema` entry with them.
14
+
15
+ `prenta push chrome` sends the regions `prenta.config.ts` exports to the CMS, with the repo, branch and commit; run it on every deploy, with an admin API key. The CMS stores each region's schema and fits the saved values to it. A value whose field was removed is kept as an orphan for 30 days, or until someone removes it. A field with `renamedFrom` keeps the old key's value. `prenta pull chrome` writes the CMS's schema to `.prenta/chrome.json`, and `prenta types` generates `ChromeFields` from it.
16
+
17
+ Migration 0027 adds the `prenta_chrome_regions` table. It ships a `down.sql` for manual rollback.
18
+
19
+ ## 1.0.1
20
+
21
+ ### Patch Changes
22
+
23
+ - 17cf190: Cap `@prenta/core` peer ranges at `>=8.0.0 <9.0.0` so an 8.x package does not advertise compatibility with 9.x.
24
+
3
25
  ## 1.0.0
4
26
 
5
27
  ### Patch Changes
@@ -0,0 +1,74 @@
1
+ import { Command } from 'commander';
2
+ import type { ChromeSchemaReadResult, ChromeSyncStatus, RegionDefinition, RegionSchema } from '@prenta/core';
3
+ export interface CmsConnection {
4
+ url?: string;
5
+ key?: string;
6
+ fetch?: typeof fetch;
7
+ }
8
+ /** What `prenta pull chrome` writes and `prenta types` reads. */
9
+ export interface PulledChrome {
10
+ pulledAt: string;
11
+ cms: string;
12
+ sync: ChromeSyncStatus;
13
+ regions: RegionSchema[];
14
+ }
15
+ /** The CMS API base for `--url` / `PRENTA_CMS_URL`, with or without `/api/cms` on the end. */
16
+ export declare function cmsApiBase(url: string): string;
17
+ /** Fetch the schema the CMS holds and write it to `.prenta/chrome.json`. */
18
+ export declare function pullChrome(options?: CmsConnection & {
19
+ out?: string;
20
+ cwd?: string;
21
+ }): Promise<{
22
+ file: string;
23
+ pulled: PulledChrome;
24
+ }>;
25
+ /** Generate `ChromeFields` from `.prenta/chrome.json`. With `out: '-'` the source is returned, not written. */
26
+ export declare function writeChromeTypes(options?: {
27
+ in?: string;
28
+ out?: string;
29
+ cwd?: string;
30
+ }): Promise<{
31
+ file: string | null;
32
+ source: string;
33
+ }>;
34
+ /** Every `defineRegion` a config module exports, named or default. */
35
+ export declare function collectRegions(mod: unknown): Promise<RegionDefinition[]>;
36
+ export interface SchemaSource {
37
+ repo: string;
38
+ branch: string;
39
+ commit: string;
40
+ }
41
+ type Run = (file: string, args: string[], options: {
42
+ cwd: string;
43
+ }) => string;
44
+ /**
45
+ * `git@github.com:owner/repo.git` or `https://github.com/owner/repo` → `owner/repo`.
46
+ * Credentials in the remote (`https://oauth2:TOKEN@host/site.git`) are
47
+ * dropped: the CMS stores the source and shows it to everyone who signs in.
48
+ */
49
+ export declare function repoFromRemote(remote: string): string;
50
+ /** Where the schema comes from: CI variables first (Vercel, GitHub Actions), then git. */
51
+ export declare function detectSource(env?: NodeJS.ProcessEnv, cwd?: string, run?: Run): SchemaSource;
52
+ export interface PushChromeOptions extends CmsConnection {
53
+ config?: string;
54
+ cwd?: string;
55
+ dryRun?: boolean;
56
+ source?: Partial<SchemaSource>;
57
+ /** Loads the config module. Tests pass their own. */
58
+ load?: (file: string) => Promise<unknown>;
59
+ }
60
+ /**
61
+ * The deploy hook: send the regions a config defines to `PUT /chrome/schema`.
62
+ * Needs an admin-scoped API key. A region the config no longer defines loses
63
+ * its schema, and its values are kept as orphans for 30 days.
64
+ */
65
+ export declare function pushChrome(options?: PushChromeOptions): Promise<{
66
+ payload: {
67
+ regions: unknown[];
68
+ source: SchemaSource;
69
+ };
70
+ result: ChromeSchemaReadResult | null;
71
+ }>;
72
+ export declare function registerChromeCommand(program: Command): void;
73
+ export {};
74
+ //# sourceMappingURL=chrome.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"chrome.d.ts","sourceRoot":"","sources":["../../src/commands/chrome.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAA;AACnC,OAAO,KAAK,EACV,sBAAsB,EACtB,gBAAgB,EAChB,gBAAgB,EAChB,YAAY,EACb,MAAM,cAAc,CAAA;AAiBrB,MAAM,WAAW,aAAa;IAC5B,GAAG,CAAC,EAAE,MAAM,CAAA;IACZ,GAAG,CAAC,EAAE,MAAM,CAAA;IACZ,KAAK,CAAC,EAAE,OAAO,KAAK,CAAA;CACrB;AAED,iEAAiE;AACjE,MAAM,WAAW,YAAY;IAC3B,QAAQ,EAAE,MAAM,CAAA;IAChB,GAAG,EAAE,MAAM,CAAA;IACX,IAAI,EAAE,gBAAgB,CAAA;IACtB,OAAO,EAAE,YAAY,EAAE,CAAA;CACxB;AAED,8FAA8F;AAC9F,wBAAgB,UAAU,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAG9C;AA4CD,4EAA4E;AAC5E,wBAAsB,UAAU,CAC9B,OAAO,GAAE,aAAa,GAAG;IAAE,GAAG,CAAC,EAAE,MAAM,CAAC;IAAC,GAAG,CAAC,EAAE,MAAM,CAAA;CAAO,GAC3D,OAAO,CAAC;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,YAAY,CAAA;CAAE,CAAC,CAiBjD;AAID,+GAA+G;AAC/G,wBAAsB,gBAAgB,CACpC,OAAO,GAAE;IAAE,EAAE,CAAC,EAAE,MAAM,CAAC;IAAC,GAAG,CAAC,EAAE,MAAM,CAAC;IAAC,GAAG,CAAC,EAAE,MAAM,CAAA;CAAO,GACxD,OAAO,CAAC;IAAE,IAAI,EAAE,MAAM,GAAG,I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AE,OAAO,GAAG,IAAI,CAgF5D"}
@@ -0,0 +1,274 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { mkdir, readFile, writeFile } from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { importProjectTypescript } from '../utils/import-typescript.js';
5
+ import { logger } from '../utils/logger.js';
6
+ const DEFAULT_SCHEMA_FILE = '.prenta/chrome.json';
7
+ const DEFAULT_TYPES_FILE = '.prenta/chrome.d.ts';
8
+ const REQUEST_TIMEOUT_MS = 20_000;
9
+ /** Load core only for the chrome commands, so the rest of the CLI doesn't pay for it. */
10
+ async function chromeCore() {
11
+ const core = await import('@prenta/core');
12
+ if (typeof core.chromeTypesSource !== 'function' || typeof core.serializeRegion !== 'function') {
13
+ throw new Error('The chrome commands need a newer @prenta/core. Update it, then try again.');
14
+ }
15
+ return core;
16
+ }
17
+ /** The CMS API base for `--url` / `PRENTA_CMS_URL`, with or without `/api/cms` on the end. */
18
+ export function cmsApiBase(url) {
19
+ const origin = url.trim().replace(/\/+$/, '');
20
+ return /\/api\/cms(\/v1)?$/.test(origin) ? origin : `${origin}/api/cms`;
21
+ }
22
+ function connection(options) {
23
+ const url = options.url ?? process.env.PRENTA_CMS_URL;
24
+ const key = options.key ?? process.env.PRENTA_API_KEY;
25
+ if (!url)
26
+ throw new Error('Set the CMS URL with --url or PRENTA_CMS_URL.');
27
+ if (!key)
28
+ throw new Error('Set an API key with --key or PRENTA_API_KEY.');
29
+ return { base: cmsApiBase(url), key, fetch: options.fetch ?? fetch };
30
+ }
31
+ async function cmsRequest(conn, method, route, body) {
32
+ const response = await conn.fetch(`${conn.base}${route}`, {
33
+ method,
34
+ headers: {
35
+ authorization: `Bearer ${conn.key}`,
36
+ accept: 'application/json',
37
+ ...(body !== undefined ? { 'content-type': 'application/json' } : {}),
38
+ },
39
+ ...(body !== undefined ? { body: JSON.stringify(body) } : {}),
40
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
41
+ });
42
+ const text = await response.text();
43
+ let parsed = null;
44
+ try {
45
+ parsed = text ? JSON.parse(text) : null;
46
+ }
47
+ catch {
48
+ // Not JSON: report the status below.
49
+ }
50
+ if (!response.ok) {
51
+ throw new Error(`${method} ${route} failed (${response.status}): ${parsed?.error ?? text.slice(0, 200)}`);
52
+ }
53
+ if (!parsed || parsed.data === undefined)
54
+ throw new Error(`${method} ${route} returned no data`);
55
+ return parsed.data;
56
+ }
57
+ // ─── pull ───────────────────────────────────────────────────────────────
58
+ /** Fetch the schema the CMS holds and write it to `.prenta/chrome.json`. */
59
+ export async function pullChrome(options = {}) {
60
+ const conn = connection(options);
61
+ const view = await cmsRequest(conn, 'GET', '/chrome/schema');
62
+ const pulled = {
63
+ pulledAt: new Date().toISOString(),
64
+ cms: conn.base,
65
+ sync: view.sync,
66
+ regions: view.regions,
67
+ };
68
+ const file = path.resolve(options.cwd ?? process.cwd(), options.out ?? DEFAULT_SCHEMA_FILE);
69
+ await mkdir(path.dirname(file), { recursive: true });
70
+ await writeFile(file, `${JSON.stringify(pulled, null, 2)}\n`);
71
+ return { file, pulled };
72
+ }
73
+ // ─── types ──────────────────────────────────────────────────────────────
74
+ /** Generate `ChromeFields` from `.prenta/chrome.json`. With `out: '-'` the source is returned, not written. */
75
+ export async function writeChromeTypes(options = {}) {
76
+ const cwd = options.cwd ?? process.cwd();
77
+ const input = path.resolve(cwd, options.in ?? DEFAULT_SCHEMA_FILE);
78
+ let pulled;
79
+ try {
80
+ pulled = JSON.parse(await readFile(input, 'utf8'));
81
+ }
82
+ catch (err) {
83
+ const code = err.code;
84
+ throw new Error(code === 'ENOENT'
85
+ ? `${path.relative(cwd, input) || input} doesn't exist yet. Run \`prenta pull chrome\` first.`
86
+ : `Couldn't read ${input}: ${err instanceof Error ? err.message : String(err)}`);
87
+ }
88
+ if (!Array.isArray(pulled.regions))
89
+ throw new Error(`${input} has no regions`);
90
+ const source = (await chromeCore()).chromeTypesSource(pulled.regions);
91
+ if (options.out === '-')
92
+ return { file: null, source };
93
+ const file = path.resolve(cwd, options.out ?? DEFAULT_TYPES_FILE);
94
+ await mkdir(path.dirname(file), { recursive: true });
95
+ await writeFile(file, source);
96
+ return { file, source };
97
+ }
98
+ // ─── push ───────────────────────────────────────────────────────────────
99
+ /** Every `defineRegion` a config module exports, named or default. */
100
+ export async function collectRegions(mod) {
101
+ if (typeof mod !== 'object' || mod === null)
102
+ return [];
103
+ const { isRegionDefinition } = await chromeCore();
104
+ const found = new Map();
105
+ for (const value of Object.values(mod)) {
106
+ if (isRegionDefinition(value)) {
107
+ if (found.has(value.region)) {
108
+ throw new Error(`The config defines the ${value.region} region twice.`);
109
+ }
110
+ found.set(value.region, value);
111
+ }
112
+ }
113
+ return [...found.values()];
114
+ }
115
+ const runGit = (file, args, options) => execFileSync(file, args, {
116
+ cwd: options.cwd,
117
+ encoding: 'utf8',
118
+ stdio: ['ignore', 'pipe', 'ignore'],
119
+ });
120
+ /**
121
+ * `git@github.com:owner/repo.git` or `https://github.com/owner/repo` → `owner/repo`.
122
+ * Credentials in the remote (`https://oauth2:TOKEN@host/site.git`) are
123
+ * dropped: the CMS stores the source and shows it to everyone who signs in.
124
+ */
125
+ export function repoFromRemote(remote) {
126
+ const trimmed = remote.trim();
127
+ let path;
128
+ if (/^[a-z][a-z0-9+.-]*:\/\//i.test(trimmed)) {
129
+ try {
130
+ path = new URL(trimmed).pathname;
131
+ }
132
+ catch {
133
+ path = trimmed.replace(/^[a-z][a-z0-9+.-]*:\/\/[^/]*/i, '');
134
+ }
135
+ }
136
+ else {
137
+ // scp-like `[user[:password]@]host:owner/repo`.
138
+ path = trimmed.replace(/^[^@/]*@/, '').replace(/^[^:/]+:/, '/');
139
+ }
140
+ const segments = path
141
+ .replace(/\.git\/?$/, '')
142
+ .split('/')
143
+ .filter(Boolean);
144
+ return segments.slice(-2).join('/');
145
+ }
146
+ /** Where the schema comes from: CI variables first (Vercel, GitHub Actions), then git. */
147
+ export function detectSource(env = process.env, cwd = process.cwd(), run = runGit) {
148
+ const git = (args) => {
149
+ try {
150
+ return run('git', args, { cwd }).trim();
151
+ }
152
+ catch {
153
+ return '';
154
+ }
155
+ };
156
+ const vercelRepo = env.VERCEL_GIT_REPO_OWNER && env.VERCEL_GIT_REPO_SLUG
157
+ ? `${env.VERCEL_GIT_REPO_OWNER}/${env.VERCEL_GIT_REPO_SLUG}`
158
+ : '';
159
+ const repo = vercelRepo || env.GITHUB_REPOSITORY || repoFromRemote(git(['remote', 'get-url', 'origin']));
160
+ const branch = env.VERCEL_GIT_COMMIT_REF || env.GITHUB_REF_NAME || git(['rev-parse', '--abbrev-ref', 'HEAD']);
161
+ const commit = env.VERCEL_GIT_COMMIT_SHA || env.GITHUB_SHA || git(['rev-parse', 'HEAD']);
162
+ return { repo, branch, commit };
163
+ }
164
+ /**
165
+ * The deploy hook: send the regions a config defines to `PUT /chrome/schema`.
166
+ * Needs an admin-scoped API key. A region the config no longer defines loses
167
+ * its schema, and its values are kept as orphans for 30 days.
168
+ */
169
+ export async function pushChrome(options = {}) {
170
+ const cwd = options.cwd ?? process.cwd();
171
+ const configPath = path.resolve(cwd, options.config ?? 'prenta.config.ts');
172
+ const mod = await (options.load ?? importProjectTypescript)(configPath);
173
+ const regions = await collectRegions(mod);
174
+ if (regions.length === 0) {
175
+ throw new Error(`${path.relative(cwd, configPath) || configPath} exports no regions. Export each one: export const header = defineRegion('header', { … }).`);
176
+ }
177
+ const source = { ...detectSource(process.env, cwd), ...options.source };
178
+ const { serializeRegion } = await chromeCore();
179
+ const payload = { regions: regions.map((region) => serializeRegion(region)), source };
180
+ if (options.dryRun)
181
+ return { payload, result: null };
182
+ const result = await cmsRequest(connection(options), 'PUT', '/chrome/schema', payload);
183
+ return { payload, result };
184
+ }
185
+ function describeRead(result) {
186
+ return result.regions.map((region) => {
187
+ const parts = [];
188
+ if (region.orphaned.length > 0) {
189
+ parts.push(`kept ${region.orphaned.join(', ')} as orphans for 30 days`);
190
+ }
191
+ for (const { from, to } of region.renamed)
192
+ parts.push(`moved ${from} to ${to}`);
193
+ if (region.restored.length > 0)
194
+ parts.push(`restored ${region.restored.join(', ')}`);
195
+ const what = parts.length > 0 ? parts.join('; ') : region.changed ? 'updated' : 'unchanged';
196
+ return `${region.region}: ${what}`;
197
+ });
198
+ }
199
+ // ─── commands ───────────────────────────────────────────────────────────
200
+ function fail(err) {
201
+ logger.error(err instanceof Error ? err.message : String(err));
202
+ process.exitCode = 1;
203
+ }
204
+ export function registerChromeCommand(program) {
205
+ const pull = program.command('pull').description('Read what the CMS holds into .prenta/');
206
+ pull
207
+ .command('chrome')
208
+ .description('Write the header and footer schema the CMS holds to .prenta/chrome.json')
209
+ .option('--url <url>', 'CMS origin (default: PRENTA_CMS_URL)')
210
+ .option('--key <key>', 'API key with the chrome scope (default: PRENTA_API_KEY)')
211
+ .option('--out <file>', 'Where to write it', DEFAULT_SCHEMA_FILE)
212
+ .action(async (options) => {
213
+ try {
214
+ const { file, pulled } = await pullChrome(options);
215
+ const regions = pulled.regions.map((region) => region.region).join(', ') || 'no regions yet';
216
+ logger.success(`Wrote ${path.relative(process.cwd(), file)} (${regions})`);
217
+ }
218
+ catch (err) {
219
+ fail(err);
220
+ }
221
+ });
222
+ const push = program.command('push').description('Send what the site defines to the CMS');
223
+ push
224
+ .command('chrome')
225
+ .description('Send the defineRegion schemas in prenta.config.ts to the CMS. Run it on every deploy.')
226
+ .option('--config <path>', 'Config that exports the regions', 'prenta.config.ts')
227
+ .option('--url <url>', 'CMS origin (default: PRENTA_CMS_URL)')
228
+ .option('--key <key>', 'Admin API key (default: PRENTA_API_KEY)')
229
+ .option('--repo <repo>', 'Repository shown as the source (default: from CI or git)')
230
+ .option('--branch <branch>', 'Branch shown as the source (default: from CI or git)')
231
+ .option('--commit <sha>', 'Commit shown as the source (default: from CI or git)')
232
+ .option('--dry-run', 'Print what would be sent, and send nothing')
233
+ .action(async (options) => {
234
+ try {
235
+ const source = {};
236
+ if (options.repo)
237
+ source.repo = options.repo;
238
+ if (options.branch)
239
+ source.branch = options.branch;
240
+ if (options.commit)
241
+ source.commit = options.commit;
242
+ const { payload, result } = await pushChrome({ ...options, source });
243
+ if (!result) {
244
+ process.stdout.write(`${JSON.stringify(payload, null, 2)}\n`);
245
+ return;
246
+ }
247
+ logger.success(`Schema read at ${payload.source.repo || 'unknown repo'}@${payload.source.commit || 'unknown'}`);
248
+ for (const line of describeRead(result))
249
+ logger.info(line);
250
+ }
251
+ catch (err) {
252
+ fail(err);
253
+ }
254
+ });
255
+ program
256
+ .command('types')
257
+ .description('Generate ChromeFields types from .prenta/chrome.json (run prenta pull chrome first)')
258
+ .option('--in <file>', 'Pulled schema', DEFAULT_SCHEMA_FILE)
259
+ .option('--out <file>', 'Where to write the types ("-" prints them)', DEFAULT_TYPES_FILE)
260
+ .action(async (options) => {
261
+ try {
262
+ const { file, source } = await writeChromeTypes(options);
263
+ if (!file) {
264
+ process.stdout.write(source);
265
+ return;
266
+ }
267
+ logger.success(`Wrote ${path.relative(process.cwd(), file)}`);
268
+ }
269
+ catch (err) {
270
+ fail(err);
271
+ }
272
+ });
273
+ }
274
+ //# sourceMappingURL=chrome.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"chrome.js","sourceRoot":"","sources":["../../src/commands/chrome.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAA;AACjD,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAA;AAC7D,OAAO,IAAI,MAAM,WAAW,CAAA;AAQ5B,OAAO,EAAE,uBAAuB,EAAE,MAAM,+BAA+B,CAAA;AACvE,OAAO,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAA;AAE3C,MAAM,mBAAmB,GAAG,qBAAqB,CAAA;AACjD,MAAM,kBAAkB,GAAG,qBAAqB,CAAA;AAChD,MAAM,kBAAkB,GAAG,MAAM,CAAA;AAEjC,yFAAyF;AACzF,KAAK,UAAU,UAAU;IACvB,MAAM,IAAI,GAA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O;SACJ,OAAO,CAAC,OAAO,CAAC;SAChB,WAAW,CACV,qFAAqF,CACtF;SACA,MAAM,CAAC,aAAa,EAAE,eAAe,EAAE,mBAAmB,CAAC;SAC3D,MAAM,CAAC,cAAc,EAAE,4CAA4C,EAAE,kBAAkB,CAAC;SACxF,MAAM,CAAC,KAAK,EAAE,OAAsC,EAAE,EAAE;QACvD,IAAI,CAAC;YACH,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,GAAG,MAAM,gBAAgB,CAAC,OAAO,CAAC,CAAA;YACxD,IAAI,CAAC,IAAI,EAAE,CAAC;gBACV,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,CAAA;gBAC5B,OAAM;YACR,CAAC;YACD,MAAM,CAAC,OAAO,CAAC,SAAS,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,IAAI,CAAC,EAAE,CAAC,CAAA;QAC/D,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,IAAI,CAAC,GAAG,CAAC,CAAA;QACX,CAAC;IACH,CAAC,CAAC,CAAA;AACN,CAAC"}
package/dist/index.js CHANGED
@@ -22,6 +22,7 @@ import { registerInitCommand } from './commands/init.js';
22
22
  import { registerDeployCheckCommand, registerDoctorCommand, registerVerifyCommand, } from './commands/doctor.js';
23
23
  import { registerVercelBlobLinkCommand } from './commands/vercel-blob-link.js';
24
24
  import { registerMcpCommand } from './commands/mcp.js';
25
+ import { registerChromeCommand } from './commands/chrome.js';
25
26
  const program = new Command();
26
27
  program
27
28
  .name('prenta')
@@ -51,5 +52,6 @@ registerDeployCheckCommand(program);
51
52
  registerVerifyCommand(program);
52
53
  registerVercelBlobLinkCommand(program);
53
54
  registerMcpCommand(program);
55
+ registerChromeCommand(program);
54
56
  program.parse();
55
57
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings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K,EAAE,CAAA"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@prenta/cli",
3
- "version": "1.0.0",
3
+ "version": "1.1.0",
4
4
  "license": "MIT",
5
5
  "description": "CLI for Prenta CMS — migrations, codegen, imports, exports, and upgrades",
6
6
  "repository": {
@@ -24,7 +24,7 @@
24
24
  "tsx": "^4.23.0"
25
25
  },
26
26
  "peerDependencies": {
27
- "@prenta/core": ">=8.0.0",
27
+ "@prenta/core": ">=8.10.0 <9.0.0",
28
28
  "@vercel/blob": ">=2.0.0"
29
29
  },
30
30
  "peerDependenciesMeta": {
@@ -36,7 +36,7 @@
36
36
  "@vercel/blob": "^2.3.1",
37
37
  "typescript": "^5.7.0",
38
38
  "vitest": "^4.1.0",
39
- "@prenta/core": "8.0.0"
39
+ "@prenta/core": "8.10.0"
40
40
  },
41
41
  "scripts": {
42
42
  "build": "tsc",
@@ -0,0 +1,258 @@
1
+ import { mkdtemp, readFile, rm, writeFile, mkdir } from 'node:fs/promises'
2
+ import { tmpdir } from 'node:os'
3
+ import path from 'node:path'
4
+ import { defineRegion, field } from '@prenta/core/config'
5
+ import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
6
+
7
+ import {
8
+ cmsApiBase,
9
+ collectRegions,
10
+ detectSource,
11
+ pullChrome,
12
+ pushChrome,
13
+ repoFromRemote,
14
+ writeChromeTypes,
15
+ } from '../commands/chrome.js'
16
+
17
+ const header = defineRegion('header', {
18
+ component: './src/components/site/Header.astro',
19
+ variants: { default: 'Logo left, menu right', minimal: 'Logo + CTA' },
20
+ fields: {
21
+ logo: field.brand('logo'),
22
+ menu: field.menu({ default: 'main' }),
23
+ cta: field.link({ optional: true }),
24
+ },
25
+ })
26
+ const footer = defineRegion('footer', {
27
+ component: './src/components/site/Footer.astro',
28
+ variants: { columns: 'Columns' },
29
+ fields: { tone: field.select(['dark', 'light'], { default: 'dark' }) },
30
+ })
31
+
32
+ const schemaView = {
33
+ regions: [
34
+ {
35
+ region: 'header',
36
+ component: './src/components/site/Header.astro',
37
+ variants: { default: 'Logo left, menu right', minimal: 'Logo + CTA' },
38
+ fields: { logo: { type: 'brand', key: 'logo' }, cta: { type: 'link', optional: true } },
39
+ source: {
40
+ repo: 'actuate/website',
41
+ branch: 'main',
42
+ commit: 'a41f9c2',
43
+ readAt: '2026-10-20T10:00:00.000Z',
44
+ },
45
+ },
46
+ ],
47
+ sync: { status: 'synced', source: null, regions: ['header'], fieldCount: 2 },
48
+ }
49
+
50
+ function mockFetch(respond: (url: string, init: RequestInit) => Response) {
51
+ return vi.fn(async (input: string | URL | Request, init?: RequestInit) =>
52
+ respond(String(input), init ?? {}),
53
+ ) as unknown as typeof fetch
54
+ }
55
+
56
+ let dir: string
57
+
58
+ // The commands load the core barrel on first use, which takes a few seconds cold.
59
+ beforeAll(async () => {
60
+ await import('@prenta/core')
61
+ }, 60_000)
62
+
63
+ beforeEach(async () => {
64
+ dir = await mkdtemp(path.join(tmpdir(), 'prenta-chrome-'))
65
+ })
66
+
67
+ afterEach(async () => {
68
+ await rm(dir, { recursive: true, force: true })
69
+ })
70
+
71
+ describe('prenta pull chrome', () => {
72
+ it('writes the CMS schema to .prenta/chrome.json', async () => {
73
+ const fetchImpl = mockFetch((url, init) => {
74
+ expect(url).toBe('https://cms.example.com/api/cms/chrome/schema')
75
+ expect(new Headers(init.headers).get('authorization')).toBe('Bearer act_sk_test')
76
+ return new Response(JSON.stringify({ data: schemaView }), { status: 200 })
77
+ })
78
+ const { file } = await pullChrome({
79
+ url: 'https://cms.example.com/',
80
+ key: 'act_sk_test',
81
+ fetch: fetchImpl,
82
+ cwd: dir,
83
+ })
84
+ expect(file).toBe(path.join(dir, '.prenta', 'chrome.json'))
85
+ const written = JSON.parse(await readFile(file, 'utf8'))
86
+ expect(written.regions).toEqual(schemaView.regions)
87
+ expect(written.sync).toEqual(schemaView.sync)
88
+ expect(written.cms).toBe('https://cms.example.com/api/cms')
89
+ })
90
+
91
+ it('reports the CMS error and needs a URL and key', async () => {
92
+ const fetchImpl = mockFetch(
93
+ () =>
94
+ new Response(JSON.stringify({ error: 'API key does not have the chrome scope' }), {
95
+ status: 403,
96
+ }),
97
+ )
98
+ await expect(
99
+ pullChrome({ url: 'https://cms.example.com', key: 'k', fetch: fetchImpl, cwd: dir }),
100
+ ).rejects.toThrow(/403.*chrome scope/)
101
+ await expect(pullChrome({ url: undefined, key: 'k', cwd: dir })).rejects.toThrow(
102
+ /PRENTA_CMS_URL/,
103
+ )
104
+ })
105
+ })
106
+
107
+ describe('prenta types', () => {
108
+ it('emits ChromeFields from the pulled schema', async () => {
109
+ await mkdir(path.join(dir, '.prenta'))
110
+ await writeFile(path.join(dir, '.prenta', 'chrome.json'), JSON.stringify(schemaView))
111
+ const { file, source } = await writeChromeTypes({ cwd: dir })
112
+ expect(file).toBe(path.join(dir, '.prenta', 'chrome.d.ts'))
113
+ expect(await readFile(file!, 'utf8')).toBe(source)
114
+ expect(source).toContain('export interface ChromeFields {')
115
+ expect(source).toContain(' cta: ChromeLink | null\n')
116
+ expect(source).toContain('export interface ChromeVariants {')
117
+ })
118
+
119
+ it('prints with --out - and says to pull first when nothing was pulled', async () => {
120
+ await expect(writeChromeTypes({ cwd: dir })).rejects.toThrow(/prenta pull chrome/)
121
+ await mkdir(path.join(dir, '.prenta'))
122
+ await writeFile(path.join(dir, '.prenta', 'chrome.json'), JSON.stringify(schemaView))
123
+ expect((await writeChromeTypes({ cwd: dir, out: '-' })).file).toBeNull()
124
+ })
125
+ })
126
+
127
+ describe('prenta push chrome', () => {
128
+ it('sends every exported region with its source, and reports what the CMS changed', async () => {
129
+ let body: {
130
+ regions: Array<{ region: string; fields: Record<string, unknown> }>
131
+ source: unknown
132
+ } | null = null
133
+ const fetchImpl = mockFetch((url, init) => {
134
+ expect(url).toBe('https://cms.example.com/api/cms/chrome/schema')
135
+ expect(init.method).toBe('PUT')
136
+ body = JSON.parse(String(init.body))
137
+ return new Response(
138
+ JSON.stringify({
139
+ data: {
140
+ regions: [
141
+ { region: 'header', orphaned: ['tagline'], renamed: [], restored: [], changed: true },
142
+ ],
143
+ source: { repo: 'actuate/website', branch: 'main', commit: 'a41f9c2', readAt: 'x' },
144
+ },
145
+ }),
146
+ { status: 200 },
147
+ )
148
+ })
149
+ const { result } = await pushChrome({
150
+ url: 'https://cms.example.com',
151
+ key: 'act_sk_admin',
152
+ fetch: fetchImpl,
153
+ cwd: dir,
154
+ load: async () => ({ header, footer, default: { collections: {} }, helper: 1 }),
155
+ source: { repo: 'actuate/website', branch: 'main', commit: 'a41f9c2' },
156
+ })
157
+ expect(body!.regions.map((region) => region.region)).toEqual(['header', 'footer'])
158
+ expect(body!.regions[0]!.fields.cta).toEqual({ type: 'link', optional: true })
159
+ expect(body!.source).toEqual({ repo: 'actuate/website', branch: 'main', commit: 'a41f9c2' })
160
+ expect(result?.regions[0]?.orphaned).toEqual(['tagline'])
161
+ })
162
+
163
+ it('refuses a config with no regions, and sends nothing on --dry-run', async () => {
164
+ await expect(pushChrome({ cwd: dir, load: async () => ({ default: {} }) })).rejects.toThrow(
165
+ /exports no regions/,
166
+ )
167
+ const fetchImpl = vi.fn() as unknown as typeof fetch
168
+ const { payload, result } = await pushChrome({
169
+ cwd: dir,
170
+ dryRun: true,
171
+ fetch: fetchImpl,
172
+ load: async () => ({ header }),
173
+ source: { commit: 'abc' },
174
+ })
175
+ expect(result).toBeNull()
176
+ expect(payload.regions).toHaveLength(1)
177
+ expect(fetchImpl).not.toHaveBeenCalled()
178
+ })
179
+
180
+ it('refuses a region defined twice', async () => {
181
+ await expect(collectRegions({ a: header, b: header })).rejects.toThrow(/header region twice/)
182
+ })
183
+ })
184
+
185
+ describe('source detection', () => {
186
+ it('prefers Vercel, then GitHub Actions, then git', () => {
187
+ const neverGit = () => {
188
+ throw new Error('no git')
189
+ }
190
+ expect(
191
+ detectSource(
192
+ {
193
+ VERCEL_GIT_REPO_OWNER: 'actuate',
194
+ VERCEL_GIT_REPO_SLUG: 'website',
195
+ VERCEL_GIT_COMMIT_REF: 'main',
196
+ VERCEL_GIT_COMMIT_SHA: 'a41f9c2',
197
+ GITHUB_SHA: 'ignored',
198
+ },
199
+ dir,
200
+ neverGit,
201
+ ),
202
+ ).toEqual({ repo: 'actuate/website', branch: 'main', commit: 'a41f9c2' })
203
+ expect(
204
+ detectSource(
205
+ { GITHUB_REPOSITORY: 'actuate/website', GITHUB_REF_NAME: 'release', GITHUB_SHA: 'b1' },
206
+ dir,
207
+ neverGit,
208
+ ),
209
+ ).toEqual({ repo: 'actuate/website', branch: 'release', commit: 'b1' })
210
+ const git = (_file: string, args: string[]) =>
211
+ args[0] === 'remote'
212
+ ? 'git@github.com:actuate/website.git\n'
213
+ : args.includes('--abbrev-ref')
214
+ ? 'main\n'
215
+ : 'c0ffee\n'
216
+ expect(detectSource({}, dir, git)).toEqual({
217
+ repo: 'actuate/website',
218
+ branch: 'main',
219
+ commit: 'c0ffee',
220
+ })
221
+ expect(detectSource({}, dir, neverGit)).toEqual({ repo: '', branch: '', commit: '' })
222
+ })
223
+
224
+ it('reads owner/repo from a remote URL', () => {
225
+ expect(repoFromRemote('https://github.com/actuate/website.git')).toBe('actuate/website')
226
+ expect(repoFromRemote('git@github.com:actuate/website')).toBe('actuate/website')
227
+ })
228
+
229
+ it('never keeps credentials from the remote (review)', () => {
230
+ const secret = 'SECRET'
231
+ for (const remote of [
232
+ `https://oauth2:${secret}@git.example.com/site.git`,
233
+ `https://${secret}@github.com/actuate/website.git`,
234
+ `https://user:${secret}@gitlab.example.com/group/sub/site`,
235
+ `user:${secret}@git.example.com:actuate/website.git`,
236
+ ]) {
237
+ expect(repoFromRemote(remote)).not.toContain(secret)
238
+ expect(repoFromRemote(remote)).not.toContain('@')
239
+ }
240
+ expect(repoFromRemote(`https://oauth2:${secret}@git.example.com/site.git`)).toBe('site')
241
+ expect(repoFromRemote(`https://${secret}@github.com/actuate/website.git`)).toBe(
242
+ 'actuate/website',
243
+ )
244
+ expect(repoFromRemote(`user:${secret}@git.example.com:actuate/website.git`)).toBe(
245
+ 'actuate/website',
246
+ )
247
+ const git = () => `https://x-access-token:${secret}@github.com/actuate/website.git\n`
248
+ expect(detectSource({}, dir, git).repo).toBe('actuate/website')
249
+ })
250
+
251
+ it('takes a CMS URL with or without /api/cms', () => {
252
+ expect(cmsApiBase('https://cms.example.com/')).toBe('https://cms.example.com/api/cms')
253
+ expect(cmsApiBase('https://cms.example.com/api/cms')).toBe('https://cms.example.com/api/cms')
254
+ expect(cmsApiBase('https://cms.example.com/api/cms/v1')).toBe(
255
+ 'https://cms.example.com/api/cms/v1',
256
+ )
257
+ })
258
+ })
@@ -0,0 +1,362 @@
1
+ import { execFileSync } from 'node:child_process'
2
+ import { mkdir, readFile, writeFile } from 'node:fs/promises'
3
+ import path from 'node:path'
4
+ import { Command } from 'commander'
5
+ import type {
6
+ ChromeSchemaReadResult,
7
+ ChromeSyncStatus,
8
+ RegionDefinition,
9
+ RegionSchema,
10
+ } from '@prenta/core'
11
+ import { importProjectTypescript } from '../utils/import-typescript.js'
12
+ import { logger } from '../utils/logger.js'
13
+
14
+ const DEFAULT_SCHEMA_FILE = '.prenta/chrome.json'
15
+ const DEFAULT_TYPES_FILE = '.prenta/chrome.d.ts'
16
+ const REQUEST_TIMEOUT_MS = 20_000
17
+
18
+ /** Load core only for the chrome commands, so the rest of the CLI doesn't pay for it. */
19
+ async function chromeCore() {
20
+ const core = await import('@prenta/core')
21
+ if (typeof core.chromeTypesSource !== 'function' || typeof core.serializeRegion !== 'function') {
22
+ throw new Error('The chrome commands need a newer @prenta/core. Update it, then try again.')
23
+ }
24
+ return core
25
+ }
26
+
27
+ export interface CmsConnection {
28
+ url?: string
29
+ key?: string
30
+ fetch?: typeof fetch
31
+ }
32
+
33
+ /** What `prenta pull chrome` writes and `prenta types` reads. */
34
+ export interface PulledChrome {
35
+ pulledAt: string
36
+ cms: string
37
+ sync: ChromeSyncStatus
38
+ regions: RegionSchema[]
39
+ }
40
+
41
+ /** The CMS API base for `--url` / `PRENTA_CMS_URL`, with or without `/api/cms` on the end. */
42
+ export function cmsApiBase(url: string): string {
43
+ const origin = url.trim().replace(/\/+$/, '')
44
+ return /\/api\/cms(\/v1)?$/.test(origin) ? origin : `${origin}/api/cms`
45
+ }
46
+
47
+ function connection(options: CmsConnection): { base: string; key: string; fetch: typeof fetch } {
48
+ const url = options.url ?? process.env.PRENTA_CMS_URL
49
+ const key = options.key ?? process.env.PRENTA_API_KEY
50
+ if (!url) throw new Error('Set the CMS URL with --url or PRENTA_CMS_URL.')
51
+ if (!key) throw new Error('Set an API key with --key or PRENTA_API_KEY.')
52
+ return { base: cmsApiBase(url), key, fetch: options.fetch ?? fetch }
53
+ }
54
+
55
+ async function cmsRequest<T>(
56
+ conn: { base: string; key: string; fetch: typeof fetch },
57
+ method: 'GET' | 'PUT',
58
+ route: string,
59
+ body?: unknown,
60
+ ): Promise<T> {
61
+ const response = await conn.fetch(`${conn.base}${route}`, {
62
+ method,
63
+ headers: {
64
+ authorization: `Bearer ${conn.key}`,
65
+ accept: 'application/json',
66
+ ...(body !== undefined ? { 'content-type': 'application/json' } : {}),
67
+ },
68
+ ...(body !== undefined ? { body: JSON.stringify(body) } : {}),
69
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
70
+ })
71
+ const text = await response.text()
72
+ let parsed: { data?: T; error?: string } | null = null
73
+ try {
74
+ parsed = text ? (JSON.parse(text) as { data?: T; error?: string }) : null
75
+ } catch {
76
+ // Not JSON: report the status below.
77
+ }
78
+ if (!response.ok) {
79
+ throw new Error(
80
+ `${method} ${route} failed (${response.status}): ${parsed?.error ?? text.slice(0, 200)}`,
81
+ )
82
+ }
83
+ if (!parsed || parsed.data === undefined) throw new Error(`${method} ${route} returned no data`)
84
+ return parsed.data
85
+ }
86
+
87
+ // ─── pull ───────────────────────────────────────────────────────────────
88
+
89
+ /** Fetch the schema the CMS holds and write it to `.prenta/chrome.json`. */
90
+ export async function pullChrome(
91
+ options: CmsConnection & { out?: string; cwd?: string } = {},
92
+ ): Promise<{ file: string; pulled: PulledChrome }> {
93
+ const conn = connection(options)
94
+ const view = await cmsRequest<{ regions: RegionSchema[]; sync: ChromeSyncStatus }>(
95
+ conn,
96
+ 'GET',
97
+ '/chrome/schema',
98
+ )
99
+ const pulled: PulledChrome = {
100
+ pulledAt: new Date().toISOString(),
101
+ cms: conn.base,
102
+ sync: view.sync,
103
+ regions: view.regions,
104
+ }
105
+ const file = path.resolve(options.cwd ?? process.cwd(), options.out ?? DEFAULT_SCHEMA_FILE)
106
+ await mkdir(path.dirname(file), { recursive: true })
107
+ await writeFile(file, `${JSON.stringify(pulled, null, 2)}\n`)
108
+ return { file, pulled }
109
+ }
110
+
111
+ // ─── types ──────────────────────────────────────────────────────────────
112
+
113
+ /** Generate `ChromeFields` from `.prenta/chrome.json`. With `out: '-'` the source is returned, not written. */
114
+ export async function writeChromeTypes(
115
+ options: { in?: string; out?: string; cwd?: string } = {},
116
+ ): Promise<{ file: string | null; source: string }> {
117
+ const cwd = options.cwd ?? process.cwd()
118
+ const input = path.resolve(cwd, options.in ?? DEFAULT_SCHEMA_FILE)
119
+ let pulled: PulledChrome
120
+ try {
121
+ pulled = JSON.parse(await readFile(input, 'utf8')) as PulledChrome
122
+ } catch (err) {
123
+ const code = (err as NodeJS.ErrnoException).code
124
+ throw new Error(
125
+ code === 'ENOENT'
126
+ ? `${path.relative(cwd, input) || input} doesn't exist yet. Run \`prenta pull chrome\` first.`
127
+ : `Couldn't read ${input}: ${err instanceof Error ? err.message : String(err)}`,
128
+ )
129
+ }
130
+ if (!Array.isArray(pulled.regions)) throw new Error(`${input} has no regions`)
131
+ const source = (await chromeCore()).chromeTypesSource(pulled.regions)
132
+ if (options.out === '-') return { file: null, source }
133
+ const file = path.resolve(cwd, options.out ?? DEFAULT_TYPES_FILE)
134
+ await mkdir(path.dirname(file), { recursive: true })
135
+ await writeFile(file, source)
136
+ return { file, source }
137
+ }
138
+
139
+ // ─── push ───────────────────────────────────────────────────────────────
140
+
141
+ /** Every `defineRegion` a config module exports, named or default. */
142
+ export async function collectRegions(mod: unknown): Promise<RegionDefinition[]> {
143
+ if (typeof mod !== 'object' || mod === null) return []
144
+ const { isRegionDefinition } = await chromeCore()
145
+ const found = new Map<string, RegionDefinition>()
146
+ for (const value of Object.values(mod as Record<string, unknown>)) {
147
+ if (isRegionDefinition(value)) {
148
+ if (found.has(value.region)) {
149
+ throw new Error(`The config defines the ${value.region} region twice.`)
150
+ }
151
+ found.set(value.region, value)
152
+ }
153
+ }
154
+ return [...found.values()]
155
+ }
156
+
157
+ export interface SchemaSource {
158
+ repo: string
159
+ branch: string
160
+ commit: string
161
+ }
162
+
163
+ type Run = (file: string, args: string[], options: { cwd: string }) => string
164
+
165
+ const runGit: Run = (file, args, options) =>
166
+ execFileSync(file, args, {
167
+ cwd: options.cwd,
168
+ encoding: 'utf8',
169
+ stdio: ['ignore', 'pipe', 'ignore'],
170
+ })
171
+
172
+ /**
173
+ * `git@github.com:owner/repo.git` or `https://github.com/owner/repo` → `owner/repo`.
174
+ * Credentials in the remote (`https://oauth2:TOKEN@host/site.git`) are
175
+ * dropped: the CMS stores the source and shows it to everyone who signs in.
176
+ */
177
+ export function repoFromRemote(remote: string): string {
178
+ const trimmed = remote.trim()
179
+ let path: string
180
+ if (/^[a-z][a-z0-9+.-]*:\/\//i.test(trimmed)) {
181
+ try {
182
+ path = new URL(trimmed).pathname
183
+ } catch {
184
+ path = trimmed.replace(/^[a-z][a-z0-9+.-]*:\/\/[^/]*/i, '')
185
+ }
186
+ } else {
187
+ // scp-like `[user[:password]@]host:owner/repo`.
188
+ path = trimmed.replace(/^[^@/]*@/, '').replace(/^[^:/]+:/, '/')
189
+ }
190
+ const segments = path
191
+ .replace(/\.git\/?$/, '')
192
+ .split('/')
193
+ .filter(Boolean)
194
+ return segments.slice(-2).join('/')
195
+ }
196
+
197
+ /** Where the schema comes from: CI variables first (Vercel, GitHub Actions), then git. */
198
+ export function detectSource(
199
+ env: NodeJS.ProcessEnv = process.env,
200
+ cwd = process.cwd(),
201
+ run: Run = runGit,
202
+ ): SchemaSource {
203
+ const git = (args: string[]) => {
204
+ try {
205
+ return run('git', args, { cwd }).trim()
206
+ } catch {
207
+ return ''
208
+ }
209
+ }
210
+ const vercelRepo =
211
+ env.VERCEL_GIT_REPO_OWNER && env.VERCEL_GIT_REPO_SLUG
212
+ ? `${env.VERCEL_GIT_REPO_OWNER}/${env.VERCEL_GIT_REPO_SLUG}`
213
+ : ''
214
+ const repo =
215
+ vercelRepo || env.GITHUB_REPOSITORY || repoFromRemote(git(['remote', 'get-url', 'origin']))
216
+ const branch =
217
+ env.VERCEL_GIT_COMMIT_REF || env.GITHUB_REF_NAME || git(['rev-parse', '--abbrev-ref', 'HEAD'])
218
+ const commit = env.VERCEL_GIT_COMMIT_SHA || env.GITHUB_SHA || git(['rev-parse', 'HEAD'])
219
+ return { repo, branch, commit }
220
+ }
221
+
222
+ export interface PushChromeOptions extends CmsConnection {
223
+ config?: string
224
+ cwd?: string
225
+ dryRun?: boolean
226
+ source?: Partial<SchemaSource>
227
+ /** Loads the config module. Tests pass their own. */
228
+ load?: (file: string) => Promise<unknown>
229
+ }
230
+
231
+ /**
232
+ * The deploy hook: send the regions a config defines to `PUT /chrome/schema`.
233
+ * Needs an admin-scoped API key. A region the config no longer defines loses
234
+ * its schema, and its values are kept as orphans for 30 days.
235
+ */
236
+ export async function pushChrome(options: PushChromeOptions = {}): Promise<{
237
+ payload: { regions: unknown[]; source: SchemaSource }
238
+ result: ChromeSchemaReadResult | null
239
+ }> {
240
+ const cwd = options.cwd ?? process.cwd()
241
+ const configPath = path.resolve(cwd, options.config ?? 'prenta.config.ts')
242
+ const mod = await (options.load ?? importProjectTypescript)(configPath)
243
+ const regions = await collectRegions(mod)
244
+ if (regions.length === 0) {
245
+ throw new Error(
246
+ `${path.relative(cwd, configPath) || configPath} exports no regions. Export each one: export const header = defineRegion('header', { … }).`,
247
+ )
248
+ }
249
+ const source = { ...detectSource(process.env, cwd), ...options.source }
250
+ const { serializeRegion } = await chromeCore()
251
+ const payload = { regions: regions.map((region) => serializeRegion(region)), source }
252
+ if (options.dryRun) return { payload, result: null }
253
+ const result = await cmsRequest<ChromeSchemaReadResult>(
254
+ connection(options),
255
+ 'PUT',
256
+ '/chrome/schema',
257
+ payload,
258
+ )
259
+ return { payload, result }
260
+ }
261
+
262
+ function describeRead(result: ChromeSchemaReadResult): string[] {
263
+ return result.regions.map((region) => {
264
+ const parts: string[] = []
265
+ if (region.orphaned.length > 0) {
266
+ parts.push(`kept ${region.orphaned.join(', ')} as orphans for 30 days`)
267
+ }
268
+ for (const { from, to } of region.renamed) parts.push(`moved ${from} to ${to}`)
269
+ if (region.restored.length > 0) parts.push(`restored ${region.restored.join(', ')}`)
270
+ const what = parts.length > 0 ? parts.join('; ') : region.changed ? 'updated' : 'unchanged'
271
+ return `${region.region}: ${what}`
272
+ })
273
+ }
274
+
275
+ // ─── commands ───────────────────────────────────────────────────────────
276
+
277
+ function fail(err: unknown): void {
278
+ logger.error(err instanceof Error ? err.message : String(err))
279
+ process.exitCode = 1
280
+ }
281
+
282
+ export function registerChromeCommand(program: Command): void {
283
+ const pull = program.command('pull').description('Read what the CMS holds into .prenta/')
284
+ pull
285
+ .command('chrome')
286
+ .description('Write the header and footer schema the CMS holds to .prenta/chrome.json')
287
+ .option('--url <url>', 'CMS origin (default: PRENTA_CMS_URL)')
288
+ .option('--key <key>', 'API key with the chrome scope (default: PRENTA_API_KEY)')
289
+ .option('--out <file>', 'Where to write it', DEFAULT_SCHEMA_FILE)
290
+ .action(async (options: { url?: string; key?: string; out?: string }) => {
291
+ try {
292
+ const { file, pulled } = await pullChrome(options)
293
+ const regions = pulled.regions.map((region) => region.region).join(', ') || 'no regions yet'
294
+ logger.success(`Wrote ${path.relative(process.cwd(), file)} (${regions})`)
295
+ } catch (err) {
296
+ fail(err)
297
+ }
298
+ })
299
+
300
+ const push = program.command('push').description('Send what the site defines to the CMS')
301
+ push
302
+ .command('chrome')
303
+ .description(
304
+ 'Send the defineRegion schemas in prenta.config.ts to the CMS. Run it on every deploy.',
305
+ )
306
+ .option('--config <path>', 'Config that exports the regions', 'prenta.config.ts')
307
+ .option('--url <url>', 'CMS origin (default: PRENTA_CMS_URL)')
308
+ .option('--key <key>', 'Admin API key (default: PRENTA_API_KEY)')
309
+ .option('--repo <repo>', 'Repository shown as the source (default: from CI or git)')
310
+ .option('--branch <branch>', 'Branch shown as the source (default: from CI or git)')
311
+ .option('--commit <sha>', 'Commit shown as the source (default: from CI or git)')
312
+ .option('--dry-run', 'Print what would be sent, and send nothing')
313
+ .action(
314
+ async (options: {
315
+ config?: string
316
+ url?: string
317
+ key?: string
318
+ repo?: string
319
+ branch?: string
320
+ commit?: string
321
+ dryRun?: boolean
322
+ }) => {
323
+ try {
324
+ const source: Partial<SchemaSource> = {}
325
+ if (options.repo) source.repo = options.repo
326
+ if (options.branch) source.branch = options.branch
327
+ if (options.commit) source.commit = options.commit
328
+ const { payload, result } = await pushChrome({ ...options, source })
329
+ if (!result) {
330
+ process.stdout.write(`${JSON.stringify(payload, null, 2)}\n`)
331
+ return
332
+ }
333
+ logger.success(
334
+ `Schema read at ${payload.source.repo || 'unknown repo'}@${payload.source.commit || 'unknown'}`,
335
+ )
336
+ for (const line of describeRead(result)) logger.info(line)
337
+ } catch (err) {
338
+ fail(err)
339
+ }
340
+ },
341
+ )
342
+
343
+ program
344
+ .command('types')
345
+ .description(
346
+ 'Generate ChromeFields types from .prenta/chrome.json (run prenta pull chrome first)',
347
+ )
348
+ .option('--in <file>', 'Pulled schema', DEFAULT_SCHEMA_FILE)
349
+ .option('--out <file>', 'Where to write the types ("-" prints them)', DEFAULT_TYPES_FILE)
350
+ .action(async (options: { in?: string; out?: string }) => {
351
+ try {
352
+ const { file, source } = await writeChromeTypes(options)
353
+ if (!file) {
354
+ process.stdout.write(source)
355
+ return
356
+ }
357
+ logger.success(`Wrote ${path.relative(process.cwd(), file)}`)
358
+ } catch (err) {
359
+ fail(err)
360
+ }
361
+ })
362
+ }
package/src/index.ts CHANGED
@@ -26,6 +26,7 @@ import {
26
26
  } from './commands/doctor.js'
27
27
  import { registerVercelBlobLinkCommand } from './commands/vercel-blob-link.js'
28
28
  import { registerMcpCommand } from './commands/mcp.js'
29
+ import { registerChromeCommand } from './commands/chrome.js'
29
30
 
30
31
  const program = new Command()
31
32
 
@@ -58,5 +59,6 @@ registerDeployCheckCommand(program)
58
59
  registerVerifyCommand(program)
59
60
  registerVercelBlobLinkCommand(program)
60
61
  registerMcpCommand(program)
62
+ registerChromeCommand(program)
61
63
 
62
64
  program.parse()