@softure-ai/marketing-kit 0.1.7 → 0.1.8

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 (107) hide show
  1. package/README.md +79 -11
  2. package/dist/cli/main.js +84 -29
  3. package/dist/cli/main.js.map +1 -1
  4. package/dist/cli/og.d.ts +4 -1
  5. package/dist/cli/og.d.ts.map +1 -1
  6. package/dist/cli/og.js +15 -7
  7. package/dist/cli/og.js.map +1 -1
  8. package/dist/cli/options.d.ts +26 -2
  9. package/dist/cli/options.d.ts.map +1 -1
  10. package/dist/cli/options.js +97 -9
  11. package/dist/cli/options.js.map +1 -1
  12. package/dist/cli/voice.d.ts +14 -0
  13. package/dist/cli/voice.d.ts.map +1 -1
  14. package/dist/cli/voice.js +13 -0
  15. package/dist/cli/voice.js.map +1 -1
  16. package/dist/config/actions-schema.d.ts +14 -14
  17. package/dist/config/config.d.ts +2 -0
  18. package/dist/config/config.d.ts.map +1 -1
  19. package/dist/config/config.js +1 -1
  20. package/dist/config/config.js.map +1 -1
  21. package/dist/config/og-image-names.d.ts +7 -0
  22. package/dist/config/og-image-names.d.ts.map +1 -0
  23. package/dist/config/og-image-names.js +9 -0
  24. package/dist/config/og-image-names.js.map +1 -0
  25. package/dist/config/schema.d.ts +103 -15
  26. package/dist/config/schema.d.ts.map +1 -1
  27. package/dist/config/schema.js +64 -7
  28. package/dist/config/schema.js.map +1 -1
  29. package/dist/index.d.ts +5 -3
  30. package/dist/index.d.ts.map +1 -1
  31. package/dist/index.js +5 -3
  32. package/dist/index.js.map +1 -1
  33. package/dist/og/index.d.ts +3 -3
  34. package/dist/og/index.d.ts.map +1 -1
  35. package/dist/og/index.js +3 -2
  36. package/dist/og/index.js.map +1 -1
  37. package/dist/og/render.d.ts +13 -0
  38. package/dist/og/render.d.ts.map +1 -1
  39. package/dist/og/render.js +31 -6
  40. package/dist/og/render.js.map +1 -1
  41. package/dist/og/templates/big-number.d.ts +7 -0
  42. package/dist/og/templates/big-number.d.ts.map +1 -0
  43. package/dist/og/templates/big-number.js +41 -0
  44. package/dist/og/templates/big-number.js.map +1 -0
  45. package/dist/og/templates/carousel.d.ts +5 -0
  46. package/dist/og/templates/carousel.d.ts.map +1 -0
  47. package/dist/og/templates/carousel.js +26 -0
  48. package/dist/og/templates/carousel.js.map +1 -0
  49. package/dist/og/templates/context.d.ts +11 -3
  50. package/dist/og/templates/context.d.ts.map +1 -1
  51. package/dist/og/templates/context.js +6 -0
  52. package/dist/og/templates/context.js.map +1 -1
  53. package/dist/og/templates/frame.d.ts +2 -2
  54. package/dist/og/templates/frame.d.ts.map +1 -1
  55. package/dist/og/templates/frame.js +2 -2
  56. package/dist/og/templates/frame.js.map +1 -1
  57. package/dist/og/templates/index.d.ts +8 -3
  58. package/dist/og/templates/index.d.ts.map +1 -1
  59. package/dist/og/templates/index.js +18 -5
  60. package/dist/og/templates/index.js.map +1 -1
  61. package/dist/og/templates/portrait.d.ts +22 -0
  62. package/dist/og/templates/portrait.d.ts.map +1 -0
  63. package/dist/og/templates/portrait.js +75 -0
  64. package/dist/og/templates/portrait.js.map +1 -0
  65. package/dist/og/templates/schemas.d.ts +28 -0
  66. package/dist/og/templates/schemas.d.ts.map +1 -1
  67. package/dist/og/templates/schemas.js +26 -0
  68. package/dist/og/templates/schemas.js.map +1 -1
  69. package/dist/screenshot/gates.d.ts +6 -3
  70. package/dist/screenshot/gates.d.ts.map +1 -1
  71. package/dist/screenshot/gates.js +12 -3
  72. package/dist/screenshot/gates.js.map +1 -1
  73. package/dist/screenshot/screenshot.d.ts +17 -0
  74. package/dist/screenshot/screenshot.d.ts.map +1 -1
  75. package/dist/screenshot/screenshot.js +37 -6
  76. package/dist/screenshot/screenshot.js.map +1 -1
  77. package/dist/screenshot/storage-state.d.ts +9 -0
  78. package/dist/screenshot/storage-state.d.ts.map +1 -0
  79. package/dist/screenshot/storage-state.js +25 -0
  80. package/dist/screenshot/storage-state.js.map +1 -0
  81. package/dist/voice/placeholder.d.ts +35 -0
  82. package/dist/voice/placeholder.d.ts.map +1 -0
  83. package/dist/voice/placeholder.js +53 -0
  84. package/dist/voice/placeholder.js.map +1 -0
  85. package/package.json +1 -1
  86. package/schema/marketing.schema.json +343 -37
  87. package/src/cli/main.ts +80 -27
  88. package/src/cli/og.ts +14 -6
  89. package/src/cli/options.ts +109 -10
  90. package/src/cli/voice.ts +20 -0
  91. package/src/config/config.ts +3 -2
  92. package/src/config/og-image-names.ts +7 -0
  93. package/src/config/schema.ts +72 -8
  94. package/src/index.ts +7 -1
  95. package/src/og/index.ts +16 -2
  96. package/src/og/render.ts +36 -6
  97. package/src/og/templates/big-number.ts +44 -0
  98. package/src/og/templates/carousel.ts +27 -0
  99. package/src/og/templates/context.ts +16 -3
  100. package/src/og/templates/frame.ts +2 -2
  101. package/src/og/templates/index.ts +31 -9
  102. package/src/og/templates/portrait.ts +126 -0
  103. package/src/og/templates/schemas.ts +35 -0
  104. package/src/screenshot/gates.ts +13 -3
  105. package/src/screenshot/screenshot.ts +51 -11
  106. package/src/screenshot/storage-state.ts +24 -0
  107. package/src/voice/placeholder.ts +83 -0
@@ -6,7 +6,7 @@ import type { OgPalette } from "../palette.js";
6
6
  export interface OgTemplateContext {
7
7
  width: number;
8
8
  height: number;
9
- /** `width / 1200`: template sizes are written for a 1200-pixel-wide card and multiplied by this. */
9
+ /** Template sizes are written for the layout's base card and multiplied by this (see `getLayoutScale`). */
10
10
  scale: number;
11
11
  palette: OgPalette;
12
12
  fonts: { heading: OgFontFamily; body: OgFontFamily };
@@ -14,9 +14,22 @@ export interface OgTemplateContext {
14
14
  }
15
15
 
16
16
  export interface OgTemplate<Data> {
17
- /** Draws the card; `data` has passed the template's schema. */
18
- build(data: Data, context: OgTemplateContext): OgNode;
17
+ /** Draws the card; `data` has passed the template's schema. `slide` is 1-based; single cards have only slide 1. */
18
+ build(data: Data, context: OgTemplateContext, slide: number): OgNode;
19
19
  }
20
20
 
21
21
  export const BASE_WIDTH = 1200;
22
22
 
23
+ /**
24
+ * The card a template is written for. `landscape` templates (the 1200×630 share cards) scale by width alone, as
25
+ * they always did; `portrait` templates are written for a 1080×1350 post and scale by the limiting side, so a
26
+ * square or a story never overflows what the portrait fits.
27
+ */
28
+ export type OgLayout = "landscape" | "portrait";
29
+
30
+ export const PORTRAIT_BASE: readonly [number, number] = [1080, 1350];
31
+
32
+ export function getLayoutScale(layout: OgLayout, width: number, height: number): number {
33
+ if (layout === "landscape") return width / BASE_WIDTH;
34
+ return Math.min(width / PORTRAIT_BASE[0], height / PORTRAIT_BASE[1]);
35
+ }
@@ -2,12 +2,12 @@ import { pickWeight, toFontFamilyCss, type OgFontFamily, type OgFontWeight } fro
2
2
  import { h, type OgChild, type OgNode, type OgStyle } from "../element.js";
3
3
  import type { OgTemplateContext } from "./context.js";
4
4
 
5
- /** Text in a family (and its subset families) at a size written for the 1200-pixel card, in the loaded weight nearest `wish`. */
5
+ /** Text in a family (and its subset families) at a size written for the layout's base card, in the loaded weight nearest `wish`. */
6
6
  export function text(context: OgTemplateContext, family: OgFontFamily, size: number, wish: OgFontWeight): OgStyle {
7
7
  return { fontFamily: toFontFamilyCss(family), fontSize: Math.round(size * context.scale), fontWeight: pickWeight(family.weights, wish) };
8
8
  }
9
9
 
10
- /** A length written for the 1200-pixel card. */
10
+ /** A length written for the layout's base card. */
11
11
  export function px(context: OgTemplateContext, value: number): number {
12
12
  return Math.round(value * context.scale);
13
13
  }
@@ -1,25 +1,47 @@
1
1
  import type { z } from "zod";
2
2
 
3
3
  import type { OgNode } from "../element.js";
4
- import type { OgTemplateContext } from "./context.js";
4
+ import { bigNumberTemplate } from "./big-number.js";
5
+ import { carouselTemplate } from "./carousel.js";
6
+ import type { OgLayout, OgTemplateContext } from "./context.js";
5
7
  import { headlineChartTemplate } from "./headline-chart.js";
6
8
  import { headlineCtaTemplate } from "./headline-cta.js";
7
- import { headlineChartDataSchema, headlineCtaDataSchema } from "./schemas.js";
9
+ import { bigNumberDataSchema, carouselDataSchema, headlineChartDataSchema, headlineCtaDataSchema } from "./schemas.js";
8
10
 
9
- /** A template with its data schema; `build` takes data that passed it. */
11
+ /** A template with its data schema; `build` and `countSlides` take data that passed it. */
10
12
  interface RegisteredTemplate {
11
13
  schema: z.ZodType;
12
- build(data: unknown, context: OgTemplateContext): OgNode;
14
+ layout: OgLayout;
15
+ /** How many images the data makes; 1 for a single card. */
16
+ countSlides(data: unknown): number;
17
+ build(data: unknown, context: OgTemplateContext, slide: number): OgNode;
13
18
  }
14
19
 
15
- function register<Schema extends z.ZodType>(schema: Schema, template: { build(data: z.output<Schema>, context: OgTemplateContext): OgNode }): RegisteredTemplate {
16
- // `data` reaches `build` only after `schema` parsed it (see `buildOgTree`).
17
- return { schema, build: (data, context) => template.build(data as z.output<Schema>, context) };
20
+ interface TemplateDefinition<Data> {
21
+ layout: OgLayout;
22
+ build(data: Data, context: OgTemplateContext, slide: number): OgNode;
23
+ countSlides?(data: Data): number;
24
+ }
25
+
26
+ function register<Schema extends z.ZodType>(schema: Schema, template: TemplateDefinition<z.output<Schema>>): RegisteredTemplate {
27
+ // `data` reaches `build` and `countSlides` only after `schema` parsed it (see `buildOgTree`).
28
+ return {
29
+ schema,
30
+ layout: template.layout,
31
+ countSlides: (data) => template.countSlides?.(data as z.output<Schema>) ?? 1,
32
+ build: (data, context, slide) => template.build(data as z.output<Schema>, context, slide),
33
+ };
18
34
  }
19
35
 
20
36
  export const OG_TEMPLATES = {
21
- "headline-cta": register(headlineCtaDataSchema, headlineCtaTemplate),
22
- "headline-chart": register(headlineChartDataSchema, headlineChartTemplate),
37
+ "headline-cta": register(headlineCtaDataSchema, { layout: "landscape", build: (data, context, slide) => headlineCtaTemplate.build(data, context, slide) }),
38
+ "headline-chart": register(headlineChartDataSchema, { layout: "landscape", build: (data, context, slide) => headlineChartTemplate.build(data, context, slide) }),
39
+ "big-number": register(bigNumberDataSchema, { layout: "portrait", build: (data, context, slide) => bigNumberTemplate.build(data, context, slide) }),
40
+ carousel: register(carouselDataSchema, {
41
+ layout: "portrait",
42
+ build: (data, context, slide) => carouselTemplate.build(data, context, slide),
43
+ countSlides: (data) => data.slides.length,
44
+ }),
23
45
  } as const satisfies Record<string, RegisteredTemplate>;
24
46
 
25
47
  export type OgTemplateId = keyof typeof OG_TEMPLATES;
@@ -0,0 +1,126 @@
1
+ import { h, type OgChild, type OgNode } from "../element.js";
2
+ import type { OgTemplateContext } from "./context.js";
3
+ import { px, text, type Tile } from "./frame.js";
4
+
5
+ /** Sizes in this file are written for the 1080×1350 post (`PORTRAIT_BASE`). */
6
+
7
+ const PADDING = 80;
8
+
9
+ export interface PortraitFrame {
10
+ /** "2/6" in the top corner, or null. */
11
+ counter: string | null;
12
+ content: (OgChild | null)[];
13
+ cta: string | undefined;
14
+ source: string | undefined;
15
+ }
16
+
17
+ /**
18
+ * The portrait post: the logo and name on top (the counter opposite), the content filling the middle, and the call
19
+ * to action and source line pinned to the bottom, so a tall frame spreads the post instead of adding empty bands.
20
+ */
21
+ export function portraitFrame(context: OgTemplateContext, frame: PortraitFrame): OgNode {
22
+ const { palette } = context;
23
+ const logoSize = px(context, 64);
24
+ const hasFooter = frame.cta !== undefined || frame.source !== undefined;
25
+ return h(
26
+ "div",
27
+ {
28
+ style: {
29
+ display: "flex",
30
+ flexDirection: "column",
31
+ width: "100%",
32
+ height: "100%",
33
+ padding: px(context, PADDING),
34
+ backgroundColor: palette.background,
35
+ color: palette.foreground,
36
+ },
37
+ },
38
+ h(
39
+ "div",
40
+ { style: { display: "flex", alignItems: "center", justifyContent: "space-between" } },
41
+ h(
42
+ "div",
43
+ { style: { display: "flex", alignItems: "center", gap: px(context, 20) } },
44
+ context.brand.logo === null ? null : h("img", { src: context.brand.logo, width: logoSize, height: logoSize, style: { width: logoSize, height: logoSize } }),
45
+ h("div", { style: { ...text(context, context.fonts.body, 32, 600), wordBreak: "break-word", color: palette.muted } }, context.brand.name),
46
+ ),
47
+ frame.counter === null ? null : h("div", { style: { ...text(context, context.fonts.body, 32, 600), wordBreak: "break-word", color: palette.muted } }, frame.counter),
48
+ ),
49
+ h(
50
+ "div",
51
+ { style: { display: "flex", flexDirection: "column", flexGrow: 1, justifyContent: "center", marginTop: px(context, 32), marginBottom: px(context, 32) } },
52
+ ...frame.content,
53
+ ),
54
+ hasFooter
55
+ ? h(
56
+ "div",
57
+ { style: { display: "flex", flexDirection: "column", alignItems: "flex-start", gap: px(context, 28) } },
58
+ frame.cta === undefined
59
+ ? null
60
+ : h(
61
+ "div",
62
+ {
63
+ style: {
64
+ ...text(context, context.fonts.body, 34, 600),
65
+ wordBreak: "break-word",
66
+ maxWidth: "100%",
67
+ padding: `${px(context, 18)}px ${px(context, 36)}px`,
68
+ borderRadius: px(context, 999),
69
+ backgroundColor: palette.cta,
70
+ color: palette.onCta,
71
+ },
72
+ },
73
+ frame.cta,
74
+ ),
75
+ frame.source === undefined ? null : h("div", { style: { ...text(context, context.fonts.body, 24, 400), wordBreak: "break-word", lineHeight: 1.3, color: palette.muted } }, frame.source),
76
+ )
77
+ : null,
78
+ );
79
+ }
80
+
81
+ export function portraitEyebrow(context: OgTemplateContext, value: string | undefined): OgNode | null {
82
+ if (value === undefined) return null;
83
+ return h("div", { style: { ...text(context, context.fonts.body, 34, 600), wordBreak: "break-word", color: context.palette.accent, marginBottom: px(context, 24) } }, value);
84
+ }
85
+
86
+ /** The portrait headline size: shorter headlines get bigger type. */
87
+ export function portraitHeadlineSize(headline: string): number {
88
+ if (headline.length <= 30) return 84;
89
+ if (headline.length <= 60) return 70;
90
+ return 60;
91
+ }
92
+
93
+ export function portraitHeadline(context: OgTemplateContext, value: string): OgNode {
94
+ return h("div", { style: { ...text(context, context.fonts.heading, portraitHeadlineSize(value), 700), wordBreak: "break-word", lineHeight: 1.12, color: context.palette.foreground } }, value);
95
+ }
96
+
97
+ /** Up to two figures in boxes side by side: the value large, the label under it. */
98
+ export function portraitTiles(context: OgTemplateContext, entries: readonly Tile[]): OgNode | null {
99
+ if (entries.length === 0) return null;
100
+ const { palette } = context;
101
+ const gap = px(context, 20);
102
+ // Two per row: half of the content width (the frame's padding off both sides) minus half the gap.
103
+ const tileWidth = Math.floor((context.width - 2 * px(context, PADDING) - gap) / 2);
104
+ return h(
105
+ "div",
106
+ { style: { display: "flex", flexWrap: "wrap", gap, marginTop: px(context, 40) } },
107
+ ...entries.map((tile) =>
108
+ h(
109
+ "div",
110
+ {
111
+ style: {
112
+ display: "flex",
113
+ flexDirection: "column",
114
+ width: tileWidth,
115
+ padding: `${px(context, 22)}px ${px(context, 28)}px`,
116
+ borderRadius: px(context, 24),
117
+ border: `${px(context, 2)}px solid ${palette.border}`,
118
+ backgroundColor: palette.surface,
119
+ },
120
+ },
121
+ h("div", { style: { ...text(context, context.fonts.heading, 44, 700), wordBreak: "break-word", color: palette.foreground } }, tile.value),
122
+ h("div", { style: { ...text(context, context.fonts.body, 28, 400), wordBreak: "break-word", color: palette.muted, marginTop: px(context, 6) } }, tile.label),
123
+ ),
124
+ ),
125
+ );
126
+ }
@@ -63,3 +63,38 @@ export const headlineChartDataSchema = z.strictObject({
63
63
 
64
64
  export type HeadlineCtaData = z.output<typeof headlineCtaDataSchema>;
65
65
  export type HeadlineChartData = z.output<typeof headlineChartDataSchema>;
66
+
67
+ /*
68
+ * The portrait templates are written for a 1080×1350 post and scale by the limiting side, so their limits hold at
69
+ * every size: copy at the limits stays inside the frame (tests/og/portrait-fit.test.ts renders it and checks).
70
+ */
71
+
72
+ const source = line(80).optional().describe('Where the figures come from, drawn small at the bottom, e.g. "Source: ZUS, 2026"; at most 80 characters.');
73
+ const portraitCta = line(32).optional().describe("A call to action, drawn as a pill in the cta colours at the bottom; at most 32 characters.");
74
+
75
+ export const bigNumberDataSchema = z.strictObject({
76
+ eyebrow,
77
+ number: line(12).describe('The figure that fills the post, unit included, e.g. "898 PLN"; at most 12 characters. Shorter numbers get bigger type.'),
78
+ caption: line(90).describe("The sentence that says what the number is, under it; at most 90 characters."),
79
+ tiles: z.array(tileSchema).max(2, "at most two tiles fit").default([]).describe("Up to two label and value tiles under the caption, e.g. a second figure."),
80
+ cta: portraitCta,
81
+ source,
82
+ });
83
+
84
+ const slideSchema = z.strictObject({
85
+ eyebrow,
86
+ headline: line(90).describe("The slide's headline, at most 90 characters."),
87
+ body: line(200).optional().describe("A paragraph under the headline, at most 200 characters."),
88
+ tiles: z.array(tileSchema).max(2, "at most two tiles fit").default([]).describe("Up to two label and value tiles side by side."),
89
+ cta: portraitCta,
90
+ source,
91
+ });
92
+
93
+ export const carouselDataSchema = z.strictObject({
94
+ slides: z.array(slideSchema).min(2, "a carousel needs at least two slides").max(10, "at most ten slides").describe("The slides in order, two to ten; each renders to its own file <id>-<n>.png."),
95
+ counter: z.boolean().default(true).describe('Draws "n/N" in the top corner of every slide.'),
96
+ });
97
+
98
+ export type BigNumberData = z.output<typeof bigNumberDataSchema>;
99
+ export type CarouselData = z.output<typeof carouselDataSchema>;
100
+ export type CarouselSlide = CarouselData["slides"][number];
@@ -1,10 +1,11 @@
1
1
  /**
2
2
  * The quality gates a screenshot passes before it is kept (FIRE's screenshot script): the page
3
- * answered below HTTP 400, it shows the expected phrase, and the file is not suspiciously small. A
4
- * blank page, an error page or a half-loaded one fails at least one of them.
3
+ * answered below HTTP 400, it reached the requested scroll offset, it shows the expected phrase, and
4
+ * the file is not suspiciously small. A blank page, an error page, a half-loaded one or a frame of
5
+ * the wrong place fails at least one of them.
5
6
  */
6
7
 
7
- export const SCREENSHOT_GATES = ["load", "status", "phrase", "size"] as const;
8
+ export const SCREENSHOT_GATES = ["load", "status", "scroll", "phrase", "size"] as const;
8
9
 
9
10
  export type ScreenshotGate = (typeof SCREENSHOT_GATES)[number];
10
11
 
@@ -18,6 +19,15 @@ export function findStatusFailure(status: number | null, url: string): string |
18
19
  return null;
19
20
  }
20
21
 
22
+ /** Browsers report fractional offsets on scaled screens; half a pixel short still counts as there. */
23
+ const SCROLL_TOLERANCE_PX = 1;
24
+
25
+ /** Null when the page scrolled to the offset; otherwise why the frame would show another place. */
26
+ export function findScrollFailure(reached: number, wanted: number): string | null {
27
+ if (reached >= wanted - SCROLL_TOLERANCE_PX) return null;
28
+ return `the page scrolls only to ${Math.round(reached)} px, short of scrollTo ${wanted}`;
29
+ }
30
+
21
31
  /** Null when the file is large enough; otherwise why it is refused. */
22
32
  export function findSizeFailure(bytes: number, minBytes: number): string | null {
23
33
  if (bytes >= minBytes) return null;
@@ -1,13 +1,13 @@
1
1
  import { mkdirSync, rmSync, statSync } from "node:fs";
2
- import { join } from "node:path";
2
+ import { basename, dirname, extname, join } from "node:path";
3
3
 
4
4
  import { chromium, errors, type Browser, type Page } from "playwright";
5
5
 
6
6
  import type { ColorTheme } from "../config/colors.js";
7
7
  import type { MarketingJson } from "../config/schema.js";
8
- import { getScreenshotNames, getScreenshotShots, type ScreenshotShot } from "../config/screenshot-names.js";
8
+ import { getScreenshotNames, getScreenshotShots } from "../config/screenshot-names.js";
9
9
  import { containsPhrase } from "../film.js";
10
- import { findSizeFailure, findStatusFailure, type ScreenshotGate } from "./gates.js";
10
+ import { findScrollFailure, findSizeFailure, findStatusFailure, type ScreenshotGate } from "./gates.js";
11
11
 
12
12
  /**
13
13
  * `softure-marketing shots`: the `screenshots` entries of `marketing.json`. Each shot of an entry
@@ -121,6 +121,15 @@ async function captureLoadedPage(page: Page, target: ShotTarget): Promise<Screen
121
121
  const { entry, name, url, file } = target;
122
122
  await page.evaluate(() => document.fonts.ready);
123
123
  if (entry.full) await scrollThroughPage(page);
124
+ if (entry.scrollTo !== undefined) {
125
+ const reached = await page.evaluate((top) => {
126
+ window.scrollTo(0, top);
127
+ return window.scrollY;
128
+ }, entry.scrollTo);
129
+ const scrollFailure = findScrollFailure(reached, entry.scrollTo);
130
+ if (scrollFailure !== null) return { ok: false, id: entry.id, name, gate: "scroll", message: scrollFailure };
131
+ }
132
+ if (entry.waitMs > 0) await page.waitForTimeout(entry.waitMs);
124
133
  if (!(await waitForPhrase(page, entry.expect))) {
125
134
  return { ok: false, id: entry.id, name, gate: "phrase", message: `${url} does not show "${entry.expect}"` };
126
135
  }
@@ -142,21 +151,22 @@ function removeEntryFiles(outDir: string, entry: ScreenshotEntry): void {
142
151
  interface TakeShotOptions {
143
152
  browser: Browser;
144
153
  settings: ScreenshotBrowser;
145
- entry: ScreenshotEntry;
146
- shot: ScreenshotShot;
147
- baseUrl: string;
148
- outDir: string;
154
+ target: ShotTarget;
155
+ scheme: ColorTheme;
149
156
  }
150
157
 
151
158
  async function takeShot(options: TakeShotOptions): Promise<ScreenshotResult> {
152
- const { browser, settings, entry, shot } = options;
159
+ const { browser, settings, target, scheme } = options;
160
+ const { entry } = target;
153
161
  const context = await browser.newContext({
154
162
  viewport: { width: entry.width, height: entry.height },
155
163
  deviceScaleFactor: entry.scale,
156
- colorScheme: shot.scheme,
164
+ colorScheme: scheme,
157
165
  locale: settings.locale,
158
166
  timezoneId: settings.timezone,
159
167
  reducedMotion: entry.motion,
168
+ // Resolved to an absolute path by the caller (the CLI resolves it against the folder of marketing.json).
169
+ ...(entry.storageState === undefined ? {} : { storageState: entry.storageState }),
160
170
  });
161
171
  try {
162
172
  const page = await context.newPage();
@@ -173,7 +183,6 @@ async function takeShot(options: TakeShotOptions): Promise<ScreenshotResult> {
173
183
  }
174
184
  });
175
185
  }, css);
176
- const target = { entry, name: shot.name, url: new URL(entry.path, options.baseUrl).href, file: getScreenshotFile(options.outDir, shot.name) };
177
186
  return await takeOne(page, target);
178
187
  } finally {
179
188
  await context.close();
@@ -190,7 +199,8 @@ export async function takeScreenshots(options: TakeScreenshotsOptions): Promise<
190
199
  for (const entry of entries) {
191
200
  removeEntryFiles(outDir, entry);
192
201
  for (const shot of getScreenshotShots(entry, settings.colorScheme)) {
193
- results.push(await takeShot({ browser, settings, entry, shot, baseUrl, outDir }));
202
+ const target = { entry, name: shot.name, url: new URL(entry.path, baseUrl).href, file: getScreenshotFile(outDir, shot.name) };
203
+ results.push(await takeShot({ browser, settings, target, scheme: shot.scheme }));
194
204
  }
195
205
  }
196
206
  } finally {
@@ -198,3 +208,33 @@ export async function takeScreenshots(options: TakeScreenshotsOptions): Promise<
198
208
  }
199
209
  return results;
200
210
  }
211
+
212
+ export interface TakePageScreenshotOptions {
213
+ /** The shot's settings; its `path` is ignored, `url` is the page. */
214
+ entry: ScreenshotEntry;
215
+ /** The page to capture, any http(s) address. */
216
+ url: string;
217
+ /** The PNG to write; removed first, so a refused shot leaves no older file behind. */
218
+ file: string;
219
+ /** The scheme the browser prefers; `browser.colorScheme` when absent. */
220
+ scheme?: ColorTheme;
221
+ browser: ScreenshotBrowser;
222
+ executablePath?: string;
223
+ }
224
+
225
+ /**
226
+ * One page anywhere (`shots --page`): a competitor's page, production, a page of another app. The same browser
227
+ * settings and gates as an entry, one file at the given path, and no app is started.
228
+ */
229
+ export async function takePageScreenshot(options: TakePageScreenshotOptions): Promise<ScreenshotResult> {
230
+ const { entry, url, file, browser: settings } = options;
231
+ rmSync(file, { force: true });
232
+ mkdirSync(dirname(file), { recursive: true });
233
+ const browser = await chromium.launch(options.executablePath === undefined ? {} : { executablePath: options.executablePath });
234
+ try {
235
+ const target = { entry, name: basename(file, extname(file)), url, file };
236
+ return await takeShot({ browser, settings, target, scheme: options.scheme ?? settings.colorScheme });
237
+ } finally {
238
+ await browser.close();
239
+ }
240
+ }
@@ -0,0 +1,24 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+
3
+ /**
4
+ * A Playwright storage state (`{ cookies, origins }`) restores a signed-in session for a screenshot. Checked before
5
+ * the browser starts, so a missing or broken file is reported by name instead of as a browser error halfway through
6
+ * the run. The file holds session cookies: its contents are never printed.
7
+ */
8
+
9
+ export const STORAGE_STATE_HINT = "create it with your app's login script (context.storageState({ path })) or npx playwright codegen --save-storage=<file> <url>";
10
+
11
+ /** Null when the file looks like a storage state; otherwise what is wrong with it, without its contents. */
12
+ export function findStorageStateProblem(path: string): string | null {
13
+ if (!existsSync(path)) return `the storage state ${path} does not exist; ${STORAGE_STATE_HINT}`;
14
+ let data: unknown;
15
+ try {
16
+ data = JSON.parse(readFileSync(path, "utf8"));
17
+ } catch {
18
+ // The parse error would quote the file, which holds a session; the path is enough to find it.
19
+ return `the storage state ${path} is not JSON; ${STORAGE_STATE_HINT}`;
20
+ }
21
+ const isStorageState = typeof data === "object" && data !== null && Array.isArray((data as { cookies?: unknown }).cookies);
22
+ if (!isStorageState) return `the storage state ${path} has no "cookies" list, so it is not a Playwright storage state; ${STORAGE_STATE_HINT}`;
23
+ return null;
24
+ }
@@ -0,0 +1,83 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { mkdirSync, writeFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+
5
+ import type { Voiceover } from "./cache.js";
6
+ import type { TimedWord } from "./voiceover.js";
7
+
8
+ /**
9
+ * A free stand-in for the paid voiceover, so a film can be recorded and rendered end to end before anyone pays
10
+ * (`all`/`record`/`render --placeholder`): every word at a fixed pace, a pause between sentences, and a quiet tone as
11
+ * the audio. It lives in the film's build folder under its own key, never in `voice.cacheDir`: a placeholder in the
12
+ * cache would be a cache hit for the real key, so the paid recording would never be made.
13
+ */
14
+
15
+ export interface PlaceholderPace {
16
+ /** Words spoken per second (`voice.placeholder.wordsPerSecond`). */
17
+ wordsPerSecond: number;
18
+ /** Silence after every sentence but the last (`voice.placeholder.sentencePauseSeconds`). */
19
+ sentencePauseSeconds: number;
20
+ }
21
+
22
+ /** The key a recording made on the placeholder carries in its log, so it never renders with the real voiceover. */
23
+ export const PLACEHOLDER_KEY_PREFIX = "placeholder-";
24
+
25
+ /** Silence before the first word and after the last, so the tone does not start or end on a word. */
26
+ const LEAD_SECONDS = 0.1;
27
+ const TAIL_SECONDS = 0.5;
28
+ /** A word ends a little before the next starts, as in a real recording's timings. */
29
+ const WORD_GAP_SECONDS = 0.05;
30
+ const TONE_HZ = 220;
31
+ const TONE_VOLUME = 0.05;
32
+
33
+ const round = (value: number): number => Math.round(value * 1000) / 1000;
34
+
35
+ export function getPlaceholderKey(voiceoverKey: string): string {
36
+ return `${PLACEHOLDER_KEY_PREFIX}${voiceoverKey}`;
37
+ }
38
+
39
+ export function isPlaceholderKey(key: string | undefined): boolean {
40
+ return key?.startsWith(PLACEHOLDER_KEY_PREFIX) ?? false;
41
+ }
42
+
43
+ /** The words of the script, evenly paced, with a pause after every sentence; the shape the provider returns. */
44
+ export function makePlaceholderWords(sentences: { text: string }[], pace: PlaceholderPace): TimedWord[] {
45
+ const wordSeconds = 1 / pace.wordsPerSecond;
46
+ const words: TimedWord[] = [];
47
+ let time = LEAD_SECONDS;
48
+ sentences.forEach((sentence, index) => {
49
+ for (const text of sentence.text.trim().split(/\s+/).filter((word) => word.length > 0)) {
50
+ words.push({ text, start: round(time), end: round(time + wordSeconds - WORD_GAP_SECONDS) });
51
+ time += wordSeconds;
52
+ }
53
+ if (index < sentences.length - 1) time += pace.sentencePauseSeconds;
54
+ });
55
+ return words;
56
+ }
57
+
58
+ /** How long the placeholder's audio lasts: past the last word by the tail. */
59
+ export function getPlaceholderSeconds(words: TimedWord[]): number {
60
+ return round((words.at(-1)?.end ?? 0) + TAIL_SECONDS);
61
+ }
62
+
63
+ export interface WritePlaceholderOptions {
64
+ /** The folder of the placeholder's files: `<output.buildDir>/<video>/placeholder/`. */
65
+ dir: string;
66
+ sentences: { text: string }[];
67
+ pace: PlaceholderPace;
68
+ }
69
+
70
+ /** Writes `voiceover.json` (the words) and `voiceover.mp3` (a quiet tone as long as them); needs ffmpeg in PATH. */
71
+ export function writePlaceholderVoiceover(options: WritePlaceholderOptions): Voiceover {
72
+ const words = makePlaceholderWords(options.sentences, options.pace);
73
+ mkdirSync(options.dir, { recursive: true });
74
+ const audio = join(options.dir, "voiceover.mp3");
75
+ const seconds = getPlaceholderSeconds(words);
76
+ const tone = ["-v", "error", "-y", "-f", "lavfi", "-i", `sine=frequency=${TONE_HZ}:duration=${seconds}`, "-filter:a", `volume=${TONE_VOLUME}`];
77
+ const result = spawnSync("ffmpeg", [...tone, "-c:a", "libmp3lame", "-q:a", "6", audio], { encoding: "utf8" });
78
+ if (result.status !== 0) {
79
+ throw new Error(`ffmpeg could not write the placeholder voiceover ${audio}: ${result.error?.message ?? result.stderr.trim()}`);
80
+ }
81
+ writeFileSync(join(options.dir, "voiceover.json"), `${JSON.stringify(words, null, 1)}\n`);
82
+ return { audio, words };
83
+ }