previewer-agency 0.3.0 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,13 +1,38 @@
1
1
  # previewer
2
2
 
3
3
  Upload HTML5 banners, images and videos to [Previewer](https://previewer.agency) from any folder,
4
- whatever tool built them, and check on approvals. Needs Node 20 or newer; nothing else to install.
4
+ whatever tool built them, and check on approvals.
5
5
 
6
6
  ```bash
7
7
  npx previewer-agency login
8
8
  npx previewer-agency push ./dist --client "Acme" --campaign "Spring sale"
9
9
  ```
10
10
 
11
+ ## Install
12
+
13
+ Needs [Node.js](https://nodejs.org) 20.11 or newer; check with `node --version`.
14
+
15
+ **Without installing**, put `npx previewer-agency` in front of each command, as in the examples on this
16
+ page. npx fetches the latest version the first time.
17
+
18
+ **On your computer**, for the shorter `previewer` command (run it again later to update):
19
+
20
+ ```bash
21
+ npm install -g previewer-agency
22
+ previewer --version
23
+ ```
24
+
25
+ Every example then works with `previewer` instead of `npx previewer-agency`, for example
26
+ `previewer push ./dist`.
27
+
28
+ **In a project**, so everyone on it uses the same version:
29
+
30
+ ```bash
31
+ npm install --save-dev previewer-agency
32
+ ```
33
+
34
+ Then add a script to `package.json`, `"preview": "previewer push dist"`, and run `npm run preview`.
35
+
11
36
  ## Sign in
12
37
 
13
38
  ```bash
@@ -54,7 +79,11 @@ npx previewer-agency push ./dist
54
79
  ```
55
80
 
56
81
  When it's done it prints the preview link and copies it to your clipboard. `--open` opens it.
57
- `--dry-run` shows what would go up without uploading.
82
+ `--dry-run` shows what would go up, and to which client and campaign, without uploading.
83
+
84
+ A `--client` you name has to own the campaign. In a folder linked to one client's campaign,
85
+ `push --client "Another client"` stops before anything is uploaded; add `--campaign` to say which
86
+ campaign of that client you mean.
58
87
 
59
88
  ## Check on it
60
89
 
package/bin/previewer.mjs CHANGED
@@ -9,6 +9,7 @@ import path from 'node:path';
9
9
  import { createInterface } from 'node:readline/promises';
10
10
  import { parseArgs } from 'node:util';
11
11
  import { PreviewerClient, PreviewerError, isApprovalPath, newCliToken } from '../lib/api.mjs';
12
+ import { clientMismatch } from '../lib/destination.mjs';
12
13
  import { collectUploads } from '../lib/files.mjs';
13
14
  import { createMcpServer, runStdio } from '../lib/mcp.mjs';
14
15
  import { selectMenu } from '../lib/menu.mjs';
@@ -167,7 +168,7 @@ const clientFor = async (options, project) => {
167
168
  const auth = await resolveAuth({ site: options.site, project });
168
169
  if (!auth.token && auth.envTokenWithheld) {
169
170
  fail(
170
- `PREVIEWER_TOKEN was not sent to ${auth.site}, which comes from ${PROJECT_FILE}.`,
171
+ `PREVIEWER_TOKEN was not sent to ${auth.site}, which comes from ${auth.siteFrom === 'project' ? PROJECT_FILE : 'your saved sign-in'}.`,
171
172
  `The token only goes to the site set with --site or PREVIEWER_URL (default ${DEFAULT_SITE}). If you trust ${auth.site}, set PREVIEWER_URL to it.`,
172
173
  );
173
174
  }
@@ -209,17 +210,24 @@ async function login(options) {
209
210
  const deadline = Date.parse(started.expiresAt);
210
211
  while (Date.now() < deadline) {
211
212
  await new Promise((resolve) => setTimeout(resolve, 2000));
212
- const status = await api.loginStatus(started.requestId, token);
213
+ // A dropped connection while waiting isn't the end of the sign-in: keep asking until it expires.
214
+ let status;
215
+ try {
216
+ status = await api.loginStatus(started.requestId, token);
217
+ } catch (error) {
218
+ if (error instanceof PreviewerError && error.code === 'network') continue;
219
+ throw error;
220
+ }
213
221
  if (status === 'approved') {
214
222
  const me = await new PreviewerClient({ baseUrl: site, token }).me();
215
223
  await saveSiteLogin(site, { token, account: me.account }, { makeDefault: Boolean(options.site) });
216
224
  say(`${green('✔')} Signed in to ${bold(me.account?.name ?? site)} (${me.token.permission}).`);
217
225
  return;
218
226
  }
219
- if (status === 'denied') fail('The login was denied.');
227
+ if (status === 'denied') fail('The sign-in was denied.');
220
228
  if (status === 'expired') break;
221
229
  }
222
- fail('The login expired before it was approved.', `Run ${CMD} login again.`);
230
+ fail('The sign-in expired before it was approved.', `Run ${CMD} login again.`);
223
231
  }
224
232
 
225
233
  async function logout(options) {
@@ -258,8 +266,23 @@ const resolveClient = async (api, wanted) => {
258
266
  );
259
267
  };
260
268
 
261
- /** The campaign to work on, from flags, the folder's link, or (in a terminal) a picker. */
262
- const resolveCampaign = async (api, options, project, { allowCreate = false } = {}) => {
269
+ const MISMATCH_HINT = `Leave out --client, or name the campaign with --campaign (this folder's ${PROJECT_FILE} or the id points at another client's).`;
270
+
271
+ /**
272
+ * The campaign to work on, from flags, the folder's link, or (in a terminal) a picker. A client named
273
+ * with --client has to own it, however the campaign was found (the folder's link and a campaign id
274
+ * say nothing about the client).
275
+ */
276
+ const resolveCampaign = async (api, options, project, settings = {}) => {
277
+ const found = await findCampaign(api, options, project, settings);
278
+ if (options.client) {
279
+ const mismatch = clientMismatch(found.campaign, await resolveClient(api, options.client));
280
+ if (mismatch) fail(mismatch, MISMATCH_HINT);
281
+ }
282
+ return found;
283
+ };
284
+
285
+ const findCampaign = async (api, options, project, { allowCreate = false } = {}) => {
263
286
  if (options.campaign && /^\d+$/.test(options.campaign)) return { campaign: await api.campaign(Number(options.campaign)), fromFlags: true };
264
287
  if (options.campaign) {
265
288
  const clientId = options.client ? (await resolveClient(api, options.client)).id : project?.clientId;
@@ -324,7 +347,9 @@ async function listCampaigns(options) {
324
347
  if (options.json) return say(JSON.stringify(campaigns, null, 2));
325
348
  if (campaigns.length === 0) return say('No campaigns.');
326
349
  for (const campaign of campaigns) {
327
- const approvals = campaign.approvedCount === null ? '' : ` · ${campaign.approvedCount}/${campaign.bannerCount} approved`;
350
+ // Out of what the client can approve (not links or banners hidden from the preview); an older
351
+ // server without that count falls back to all banners.
352
+ const approvals = campaign.approvedCount === null ? '' : ` · ${campaign.approvedCount}/${campaign.reviewableCount ?? campaign.bannerCount} approved`;
328
353
  say(`${dim(String(campaign.id).padStart(5))} ${bold(campaign.name)} ${dim(`— ${campaign.client.name}`)}`, ` ${campaign.bannerCount} banners${approvals} · ${campaign.previewUrl}`);
329
354
  }
330
355
  }
@@ -352,6 +377,32 @@ async function push(options, folder = '.') {
352
377
  if (options['dry-run']) {
353
378
  say(`${bold('Would upload')} ${summary} (${kb(total)}):`);
354
379
  for (const item of items) say(` ${dim(item.type.padEnd(6))} ${item.source}${item.source !== item.name ? dim(` → ${item.name}`) : ''} ${dim(kb(item.size))}`);
380
+ // Uploads nothing, but does say where the real push would go and what it would stop on: a client
381
+ // that isn't there, or a campaign that isn't the named client's.
382
+ const linked = await findProject(process.cwd());
383
+ const auth = await resolveAuth({ site: options.site, project: linked });
384
+ if (!auth.token) return say('', dim(`Not signed in to ${auth.site}, so the client and campaign weren't checked.`));
385
+ const dry = new PreviewerClient({ baseUrl: auth.site, token: auth.token, userAgent: `previewer-cli/${VERSION}` });
386
+ let client = null;
387
+ if (options.client) {
388
+ const clients = await dry.clients();
389
+ const known = /^\d+$/.test(String(options.client)) ? clients.some((item) => item.id === Number(options.client)) : matchName(clients, options.client).length > 0;
390
+ if (!known) return say('', `${yellow('!')} No client "${options.client}" yet. Create it in the Previewer admin first; the campaign is created for you.`);
391
+ client = await resolveClient(dry, options.client);
392
+ }
393
+ let campaign = null;
394
+ if (options.campaign && /^\d+$/.test(options.campaign)) campaign = await dry.campaign(Number(options.campaign));
395
+ else if (options.campaign) {
396
+ const clientId = client?.id ?? linked?.clientId;
397
+ const matches = matchName(await dry.campaigns(clientId ? { clientId } : {}), options.campaign);
398
+ if (matches.length > 1) return say('', `${yellow('!')} Several campaigns are called "${options.campaign}". Add --client, or use the campaign id.`);
399
+ if (matches.length === 0) return say('', `Campaign "${options.campaign}" doesn't exist yet${client ? ` for ${client.name}` : ''}: the push would ${options.create ? 'create it' : 'ask to create it (or add --create)'}.`);
400
+ campaign = matches[0];
401
+ } else if (linked?.campaignId) campaign = await dry.campaign(linked.campaignId);
402
+ else return say('', dim(`No campaign chosen yet: add --campaign <name|id>${client ? '' : ' (and --client <name>)'}.`));
403
+ const mismatch = clientMismatch(campaign, client);
404
+ if (mismatch) fail(mismatch, MISMATCH_HINT);
405
+ say('', `Would go to ${bold(`${campaign.client.name} → ${campaign.name}`)}.`);
355
406
  return;
356
407
  }
357
408
 
@@ -384,7 +435,8 @@ async function status(options) {
384
435
  const { campaign } = await resolveCampaign(api, options, project);
385
436
  if (options.json) return say(JSON.stringify(campaign, null, 2));
386
437
 
387
- const reviewable = campaign.banners.filter((banner) => banner.kind !== 'external');
438
+ // What the client can approve: no links, nothing hidden from the preview.
439
+ const reviewable = campaign.banners.filter((banner) => banner.kind !== 'external' && !banner.hidden);
388
440
  const approved = reviewable.filter((banner) => banner.status === 'approved').length;
389
441
  say(
390
442
  `${bold(`${campaign.client.name} → ${campaign.name}`)}`,
@@ -399,7 +451,11 @@ async function status(options) {
399
451
  const width = Math.max(10, ...campaign.banners.map((banner) => banner.label.length));
400
452
  for (const banner of campaign.banners) {
401
453
  const approvedNow = banner.status === 'approved';
402
- const state = !campaign.approvalsRequired ? ''.padEnd(9) : (approvedNow ? green : yellow)((approvedNow ? 'approved' : 'in review').padEnd(9));
454
+ const state = banner.hidden
455
+ ? dim('hidden'.padEnd(9))
456
+ : !campaign.approvalsRequired
457
+ ? ''.padEnd(9)
458
+ : (approvedNow ? green : yellow)((approvedNow ? 'approved' : 'in review').padEnd(9));
403
459
  const backup = banner.kind !== 'html' ? ''.padEnd(9) : banner.hasBackup ? dim('backup ✓'.padEnd(9)) : yellow('no backup');
404
460
  say(` ${banner.label.padEnd(width)} ${dim(`${banner.width}×${banner.height}`.padEnd(9))} ${state} ${backup} ${dim(ago(banner.updatedAt) ?? '')}`);
405
461
  }
package/lib/config.mjs CHANGED
@@ -60,6 +60,8 @@ export const saveConfig = async (config) => {
60
60
  export const resolveAuth = async ({ site: siteFlag, project } = {}) => {
61
61
  const config = await loadConfig();
62
62
  const site = normalizeSite(siteFlag || process.env.PREVIEWER_URL || project?.site || config.defaultSite || DEFAULT_SITE);
63
+ // Where that site came from, for messages that have to say so.
64
+ const siteFrom = siteFlag ? 'flag' : process.env.PREVIEWER_URL ? 'env' : project?.site ? 'project' : config.defaultSite ? 'saved' : 'default';
63
65
  const problem = siteProblem(site);
64
66
  if (problem) throw new Error(problem);
65
67
  const envToken = String(process.env.PREVIEWER_TOKEN || '').trim();
@@ -68,6 +70,7 @@ export const resolveAuth = async ({ site: siteFlag, project } = {}) => {
68
70
  const saved = config.sites?.[site];
69
71
  return {
70
72
  site,
73
+ siteFrom,
71
74
  token: (useEnvToken ? envToken : '') || saved?.token || '',
72
75
  fromEnv: useEnvToken,
73
76
  envTokenWithheld: Boolean(envToken) && !useEnvToken,
@@ -0,0 +1,14 @@
1
+ // Where an upload is about to go, checked against what the caller said.
2
+ //
3
+ // A folder can be linked to a campaign (.previewer.json), and a campaign can be named by its id. When
4
+ // the caller also names a client, the campaign has to be that client's: otherwise "push for client B"
5
+ // in a folder linked to client A's campaign would put B's banners on A's preview link. Shared by the
6
+ // command line and the MCP server, so the two can't drift apart.
7
+
8
+ /** The reason this campaign is not the named client's, or null when it is (or no client was named). */
9
+ export const clientMismatch = (campaign, client) => {
10
+ if (!client || !campaign) return null;
11
+ if (campaign.client?.id === client.id) return null;
12
+ const owner = campaign.client?.name ? `${campaign.client.name}'s` : "another client's";
13
+ return `Campaign "${campaign.name}" (${campaign.id}) is ${owner}, not ${client.name}'s.`;
14
+ };
package/lib/files.mjs CHANGED
@@ -244,6 +244,12 @@ export const collectUploads = async (dir) => {
244
244
  skipped.push({ name: image.name, reason: 'backup images must be JPG, PNG or WebP' });
245
245
  continue;
246
246
  }
247
+ // Its banner has no size in the file name (the size is only in the ad.size tag), so there is no
248
+ // id to hang the backup on, and the server would refuse the whole backup batch over it.
249
+ if (pair && !pair.id && !sizeFromName(image.name)) {
250
+ skipped.push({ name: image.name, reason: `backup for ${baseName(image.name)}.zip, which has no size in its name: rename both, e.g. ${baseName(image.name)}-300x250` });
251
+ continue;
252
+ }
247
253
  // Named after its banner's id when known, so it lands on exactly that banner.
248
254
  const name = pair?.id ? `${pair.id}${ext}` : image.name;
249
255
  items.push({ type: 'backup', name, size: info.size, path: image.full, mimeType: MIME[ext], source: path.relative(dir, image.full) });
package/lib/mcp.mjs CHANGED
@@ -7,6 +7,7 @@
7
7
  import os from 'node:os';
8
8
  import path from 'node:path';
9
9
  import { createInterface } from 'node:readline';
10
+ import { clientMismatch } from './destination.mjs';
10
11
  import { PreviewerClient, PreviewerError, isApprovalPath, newCliToken } from './api.mjs';
11
12
  import { collectUploads } from './files.mjs';
12
13
  import { PROJECT_FILE, findProject, resolveAuth, saveProject, saveSiteLogin } from './config.mjs';
@@ -56,6 +57,7 @@ const campaignSummary = (campaign) => ({
56
57
  client: campaign.client,
57
58
  previewUrl: campaign.previewUrl,
58
59
  bannerCount: campaign.bannerCount,
60
+ reviewableCount: campaign.reviewableCount ?? null,
59
61
  approvedCount: campaign.approvedCount,
60
62
  });
61
63
 
@@ -86,10 +88,17 @@ export const createMcpServer = ({ version = '0.0.0', cwd = process.cwd(), deps =
86
88
  const auth = await d.resolveAuth({ project });
87
89
  if (!auth.token && auth.envTokenWithheld) {
88
90
  throw new ToolError(
89
- `PREVIEWER_TOKEN is not sent to ${auth.site}, which comes from ${PROJECT_FILE}: it only goes to PREVIEWER_URL (default https://previewer.agency). Ask the user whether to trust that site.`,
91
+ `PREVIEWER_TOKEN is not sent to ${auth.site}, which comes from ${auth.siteFrom === 'project' ? PROJECT_FILE : 'the saved sign-in'}: it only goes to PREVIEWER_URL (default https://previewer.agency). Ask the user whether to trust that site.`,
90
92
  );
91
93
  }
92
94
  if (!auth.token) {
95
+ // sign_in only ever signs in to the site the person set up, so for a folder that points
96
+ // somewhere else it would never help: the person has to sign in there themselves.
97
+ if (auth.siteFrom === 'project') {
98
+ throw new ToolError(
99
+ `Not signed in to ${auth.site}, the site this folder's ${PROJECT_FILE} names. sign_in can't sign in there. Ask the user whether they trust that site, and if so to run: previewer login --site ${auth.site}`,
100
+ );
101
+ }
93
102
  const waiting = login?.status === 'pending' ? ` A sign-in is waiting for approval: code ${login.code} at ${login.url}.` : ' Call sign_in.';
94
103
  throw new ToolError(`Not signed in to ${auth.site}.${waiting}`);
95
104
  }
@@ -103,7 +112,19 @@ export const createMcpServer = ({ version = '0.0.0', cwd = process.cwd(), deps =
103
112
  return client;
104
113
  };
105
114
 
106
- const resolveCampaign = async (api, project, args, { create = false } = {}) => {
115
+ // A client passed along has to own the campaign, however it was found: the folder's link and a
116
+ // campaign id say nothing about the client, and an upload to the wrong one lands on another
117
+ // client's preview link.
118
+ const resolveCampaign = async (api, project, args, settings = {}) => {
119
+ const found = await findCampaign(api, project, args, settings);
120
+ if (args.client !== undefined && args.client !== null && String(args.client).trim()) {
121
+ const mismatch = clientMismatch(found.campaign, await resolveClient(api, args.client));
122
+ if (mismatch) throw Object.assign(new ToolError(`${mismatch} Leave out client, or pass the campaign that is that client's.`), { mismatch: true });
123
+ }
124
+ return found;
125
+ };
126
+
127
+ const findCampaign = async (api, project, args, { create = false } = {}) => {
107
128
  const wanted = args.campaign === undefined || args.campaign === null ? '' : String(args.campaign).trim();
108
129
  if (!wanted) {
109
130
  if (project?.campaignId) return { campaign: await api.campaign(project.campaignId) };
@@ -279,7 +300,7 @@ export const createMcpServer = ({ version = '0.0.0', cwd = process.cwd(), deps =
279
300
  name: 'upload_folder',
280
301
  title: 'Upload banners',
281
302
  description:
282
- 'Upload a folder to a campaign: HTML5 banner ZIPs, banner folders with an index.html (zipped for you), images and videos, and backup images (300x250.jpg next to 300x250.zip, or anything in backups/). A file named like a banner already in the campaign replaces it as a new version. Returns the preview link to give the user. Use dry_run to see what would go up.',
303
+ 'Upload a folder to a campaign: HTML5 banner ZIPs, banner folders with an index.html (zipped for you), images and videos, and backup images (300x250.jpg next to 300x250.zip, or anything in backups/). A file named like a banner already in the campaign replaces it as a new version. Returns the preview link to give the user. Use dry_run to see what would go up and where. A client you pass has to own the campaign.',
283
304
  inputSchema: object(
284
305
  {
285
306
  folder: { ...FOLDER, description: `The folder to upload, e.g. "dist". ${FOLDER.description}` },
@@ -297,7 +318,21 @@ export const createMcpServer = ({ version = '0.0.0', cwd = process.cwd(), deps =
297
318
  throw new ToolError(error.code === 'ENOENT' ? `No folder ${dir}.` : `Could not read ${dir}: ${error.message}`);
298
319
  });
299
320
  const files = items.map((item) => ({ type: item.type, file: item.source ?? item.name, as: item.name, bytes: item.size }));
300
- if (args.dry_run) return { dryRun: true, folder: dir, files, skipped };
321
+ if (args.dry_run) {
322
+ // Nothing is sent, but the destination is the real one: where this upload would go, or why
323
+ // that isn't known yet. A campaign that isn't the named client's stops here too.
324
+ let destination = null;
325
+ let destinationNote = null;
326
+ try {
327
+ const { api, project } = await connect(args.folder);
328
+ const { campaign } = await resolveCampaign(api, project, args);
329
+ destination = campaignSummary(campaign);
330
+ } catch (error) {
331
+ if (!(error instanceof ToolError) || error.mismatch) throw error;
332
+ destinationNote = error.message;
333
+ }
334
+ return { dryRun: true, folder: dir, files, skipped, destination, destinationNote };
335
+ }
301
336
  if (items.length === 0) throw new ToolError(`Nothing to upload in ${dir}: expected ZIPs, banner folders with an index.html, images or videos.`);
302
337
 
303
338
  const { api, auth, project } = await connect(args.folder);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "previewer-agency",
3
- "version": "0.3.0",
3
+ "version": "0.3.2",
4
4
  "description": "Upload HTML5 banners, images and videos to Previewer from any folder, CI job or AI agent (MCP), and check approvals.",
5
5
  "type": "module",
6
6
  "bin": {