@wavebirdai/api 0.1.0-beta.15 → 0.1.0-beta.17

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/CHANGELOG.md ADDED
@@ -0,0 +1,34 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0-beta.17
4
+
5
+ - Optional `consentLocale` and `consentTheme` browser settings for the hosted consent dialog.
6
+ - Validate presentation settings before passing them to the renderer. Consent decisions, authorization and storage behavior are unchanged.
7
+ - Updated installation instructions and consent appearance reference.
8
+
9
+ ## 0.1.0-beta.16
10
+
11
+ - Fixed diagnostic categories for renderer and observed CSP failures, without signed URLs or credentials.
12
+ - Optional placement positioning within the server-authorized formats, timing and size limits.
13
+ - Contain synchronous and asynchronous diagnostic callback failures.
14
+ - Expanded guidance for CSP, existing apps, session limits and separate secret ENV downloads.
15
+
16
+ ## 0.1.0-beta.15
17
+
18
+ - Restore consent using the authoritative session revision after reload.
19
+
20
+ ## 0.1.0-beta.14
21
+
22
+ - Reject wildcard origins during server configuration.
23
+ - Clarify complete Server ENV, required dependencies and integration into existing apps.
24
+
25
+ ## 0.1.0-beta.13
26
+
27
+ - Shorter setup instructions with links to the API docs and Dashboard.
28
+ - Separate JavaScript, TypeScript and Python guides.
29
+ - Generation examples that preserve the app's request, response display and cancellation.
30
+ - Updated package description, documentation link and search keywords.
31
+
32
+ Runtime code, exports and generator templates are unchanged from `0.1.0-beta.12`. Dashboard-generated integrations remain on their selected version. The README installation command follows Dashboard's current `beta.12` selection.
33
+
34
+ The Python `0.1.0b9` source is included in the repository. Its released wheel is unchanged and is installed separately from npm.
package/README.md CHANGED
@@ -10,7 +10,7 @@ Integrate Banner, Native and Clip ads into your AI app. wavebird handles ad deli
10
10
  | --- | --- |
11
11
  | JavaScript | `@wavebirdai/api`, follow the steps below |
12
12
  | TypeScript | `@wavebirdai/api`, with included types and TypeScript examples |
13
- | Python | `wavebird-publisher-server`, follow the [Python guide](python/README.md) |
13
+ | Python | `wavebird-publisher-server`, follow the [Python guide](https://github.com/wavebird-ai/api/blob/main/python/README.md) |
14
14
 
15
15
  Native iOS and Android packages are not currently available. See [integration paths](https://wavebird.ai/api/integration-paths) for supported environments.
16
16
 
@@ -22,22 +22,26 @@ Use Node.js 20 or later on your server.
22
22
  2. **Install the package.** Run this in your app's terminal, in the folder containing `package.json`:
23
23
 
24
24
  ```sh
25
- npm install @wavebirdai/api@0.1.0-beta.15
25
+ npm install @wavebirdai/api@0.1.0-beta.17
26
26
  ```
27
27
 
28
28
  3. **Save the Server ENV from Overview, Integration step 2.** The key-only download is not the full configuration. Keep `WAVEBIRD_SECRET_KEY` and the stable, project-specific `WAVEBIRD_PREFERENCE_SECRET` out of browser code and Git. Include the saved `WAVEBIRD_PUBLIC_ORIGINS`.
29
- 4. **Connect the backend and frontend code.** Follow Dashboard's generated files to connect your app session, durable turn storage, model stream and ad slot. Keep the saved formats, sizes and timing.
29
+ 4. **Connect the backend and frontend code.** Follow Dashboard's generated files to connect your app session, durable turn storage, model stream and ad slot. The source ZIP contains code only; download secret Server ENV separately. Keep the saved formats, sizes and timing. For apps with a Content Security Policy, follow the [exact renderer rules](https://github.com/wavebird-ai/api/blob/main/docs/web/nextjs.md#generate-files).
30
30
  5. **Run your first Test ad.** Confirm that the ad appears and the request is recorded in Test Logs. Check that generation still works with declined consent, no available ad and Stop.
31
31
 
32
32
  Test ads are nonpayable. Complete the [Live prerequisites](https://wavebird.ai/api/guides/going-live) before requesting Live activation.
33
33
 
34
- For Next.js, you can use the [generator](docs/web/nextjs.md) instead of copying Dashboard's route files.
34
+ For Next.js, you can use the [generator](https://github.com/wavebird-ai/api/blob/main/docs/web/nextjs.md) instead of copying Dashboard's route files.
35
35
 
36
36
  ## Connect your model output
37
37
 
38
38
  Use `@wavebirdai/api/server` on the server and `@wavebirdai/api/browser` for the ad slot. Your response consumer must display the model output and finish only after the result is visible.
39
39
 
40
- [JavaScript and TypeScript examples](docs/web/generation.md) | [Server and browser reference](docs/web/reference.md)
40
+ [JavaScript and TypeScript examples](https://github.com/wavebird-ai/api/blob/main/docs/web/generation.md) | [Server and browser reference](https://github.com/wavebird-ai/api/blob/main/docs/web/reference.md)
41
+
42
+ ## Consent appearance
43
+
44
+ The wavebird dialog follows the browser language, with English as the fallback. Optional language and theme settings let it match your app while preserving consent choices and behavior. See [consent appearance](https://github.com/wavebird-ai/api/blob/main/docs/web/reference.md#consent-appearance) for supported languages and options.
41
45
 
42
46
  ## Update an existing integration
43
47
 
@@ -46,7 +46,7 @@ export async function plan(argv) {
46
46
  ];
47
47
  for (const [source, dest] of files) {
48
48
  await access(source, constants.R_OK);
49
- try { await access(dest); throw new Error(`Refusing to overwrite ${dest}`); }
49
+ try { await access(dest); throw new Error(`Refusing to overwrite ${dest}. Keep the existing file. Copy the matching connection hooks from Dashboard Overview into your app. See https://wavebird.ai/api/quickstart#backend`); }
50
50
  catch (error) { if (error.code !== "ENOENT") throw error; }
51
51
  }
52
52
  return { lang, projectRoot, appDir, files };
package/dist/browser.d.ts CHANGED
@@ -17,6 +17,18 @@ export type PublisherAds<Bound extends boolean = boolean> = {
17
17
  deny(): Promise<unknown>;
18
18
  withdraw(): Promise<unknown>;
19
19
  };
20
+ export type PublisherConsentTheme = {
21
+ /** Six-digit hex colors. Insufficient contrast falls back to readable colors. */
22
+ accentColor?: string;
23
+ backgroundColor?: string;
24
+ textColor?: string;
25
+ /** Font family names only, without CSS rules or URLs. No font is downloaded. */
26
+ fontFamily?: string;
27
+ /** Corner radius in pixels, 0–20. */
28
+ radius?: number;
29
+ /** Card padding in pixels, 12–32. */
30
+ spacing?: number;
31
+ };
20
32
  type PublisherAdsOptionsBase = {
21
33
  target: HTMLElement;
22
34
  clientId: string;
@@ -26,10 +38,16 @@ type PublisherAdsOptionsBase = {
26
38
  conversationId: string;
27
39
  timing?: "before" | "during" | "after";
28
40
  consentMode?: "wavebird_consent" | "own_cmp";
41
+ /** Defaults to browser language preferences, then English. Optional BCP 47 language tag or "auto". */
42
+ consentLocale?: string;
43
+ /** Presentation only. Does not change consent choices or storage. */
44
+ consentTheme?: PublisherConsentTheme;
29
45
  /** Optional official renderer URL. Only https://api.wavebird.ai/v1/render.js is supported. */
30
46
  rendererUrl?: string;
31
47
  privacySettingsTarget?: string;
32
48
  getFormat?: () => "banner" | "native" | "clip" | "auto";
49
+ /** Fixed diagnostic codes only. Exceptions in this callback never interrupt the model. */
50
+ onDiagnostic?: (event: { code: "renderer_csp_blocked" | "renderer_unavailable" | "renderer_frame_unavailable" }) => void;
33
51
  placementEndpoint?: string;
34
52
  consentEndpoint?: string;
35
53
  };
package/dist/browser.js CHANGED
@@ -52,6 +52,25 @@ export function createPublisherAds(options) {
52
52
  if (rendererUrl !== "https://api.wavebird.ai/v1/render.js") throw new Error("publisher_renderer_url_invalid");
53
53
  if (options.getFormat !== undefined && typeof options.getFormat !== "function")
54
54
  throw new Error("publisher_format_hook_invalid");
55
+ if (options.onDiagnostic !== undefined && typeof options.onDiagnostic !== "function")
56
+ throw new Error("publisher_diagnostic_hook_invalid");
57
+ if (options.consentLocale !== undefined && (typeof options.consentLocale !== "string" ||
58
+ !/^(?:auto|[a-z]{2,3}(?:-[a-z0-9]{2,8})*)$/i.test(options.consentLocale)))
59
+ throw new Error("publisher_consent_locale_invalid");
60
+ const consentTheme = options.consentTheme === undefined ? undefined : options.consentTheme;
61
+ if (consentTheme !== undefined) {
62
+ const validators = {
63
+ accentColor: value => typeof value === "string" && /^#[\da-f]{6}$/i.test(value),
64
+ backgroundColor: value => typeof value === "string" && /^#[\da-f]{6}$/i.test(value),
65
+ textColor: value => typeof value === "string" && /^#[\da-f]{6}$/i.test(value),
66
+ fontFamily: value => typeof value === "string" && /^[a-z0-9 ,"'\-]{1,160}$/i.test(value),
67
+ radius: value => typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= 20,
68
+ spacing: value => typeof value === "number" && Number.isFinite(value) && value >= 12 && value <= 32,
69
+ };
70
+ if (!consentTheme || typeof consentTheme !== "object" || Array.isArray(consentTheme) ||
71
+ Object.entries(consentTheme).some(([key, value]) => !Object.hasOwn(validators, key) || !validators[key](value)))
72
+ throw new Error("publisher_consent_theme_invalid");
73
+ }
55
74
  let privacyTarget = null;
56
75
  if (consentMode === "wavebird_consent" && options.privacySettingsTarget !== undefined) {
57
76
  if (typeof options.privacySettingsTarget !== "string" || !options.privacySettingsTarget.trim())
@@ -62,7 +81,21 @@ export function createPublisherAds(options) {
62
81
  let binding = { userId: options.userId, conversationId: options.conversationId,
63
82
  sessionId: turnBinding ? options.sessionId : crypto.randomUUID() };
64
83
  let sponsor = null, disposed = false, context = 0, active = null;
84
+ const diagnostic = code => {
85
+ if (!disposed) { try { Promise.resolve(options.onDiagnostic?.({ code })).catch(() => {}); } catch {} }
86
+ };
87
+ const onPolicyViolation = event => {
88
+ if (event.disposition !== "enforce" ||
89
+ !["script-src", "script-src-elem", "frame-src", "connect-src"].includes(event.effectiveDirective)) return;
90
+ try {
91
+ if (new URL(event.blockedURI).origin === "https://api.wavebird.ai") diagnostic("renderer_csp_blocked");
92
+ } catch {}
93
+ };
94
+ document.addEventListener?.("securitypolicyviolation", onPolicyViolation);
65
95
  const slot = document.createElement("section");
96
+ const onRenderFailure = () => diagnostic("renderer_frame_unavailable");
97
+ // Renderer failures originate in a child mount and do not bubble.
98
+ slot.addEventListener?.("ad:render_failed", onRenderFailure, true);
66
99
  slot.setAttribute("aria-label", "Sponsored placement");
67
100
  slot.style.cssText = "width:100%;height:100%;overflow:hidden;margin:0 auto";
68
101
  target.append(slot);
@@ -121,8 +154,10 @@ export function createPublisherAds(options) {
121
154
  if (active) event(active, "abort");
122
155
  disposed = true; context++; active = null;
123
156
  sponsor?.dispose(); sponsor = null; slot.remove();
157
+ slot.removeEventListener?.("ad:render_failed", onRenderFailure, true);
124
158
  privacyTarget?.removeEventListener("click", openPrivacySettings);
125
159
  window.removeEventListener("pagehide", dispose);
160
+ document.removeEventListener?.("securitypolicyviolation", onPolicyViolation);
126
161
  }
127
162
  window.addEventListener("pagehide", dispose);
128
163
  const ready = loadRenderer(rendererUrl).then(() => {
@@ -130,6 +165,8 @@ export function createPublisherAds(options) {
130
165
  sponsor = window.wavebird.createChatSponsor({ target: slot, ...binding,
131
166
  clientId: options.clientId, surfaceId: options.surfaceId, jobType: options.jobType, timing, consentMode,
132
167
  cleanupAfterClip: true,
168
+ ...(options.consentLocale === undefined ? {} : { consentLocale: options.consentLocale }),
169
+ ...(consentTheme === undefined ? {} : { consentTheme: { ...consentTheme } }),
133
170
  ...(turnBinding ? { turnBinding: true } : {}),
134
171
  ...(options.getFormat === undefined ? {} : { getFormat: options.getFormat }),
135
172
  ...(options.placementEndpoint === undefined ? {} : { placementEndpoint: options.placementEndpoint }),
@@ -143,7 +180,7 @@ export function createPublisherAds(options) {
143
180
  notify("onStarted", active.id); notify("onDone", active.id);
144
181
  }
145
182
  }
146
- }).catch(() => {});
183
+ }).catch(() => { diagnostic("renderer_unavailable"); });
147
184
 
148
185
  async function connectGeneration({ request, consume, signal }) {
149
186
  const job = { id: crypto.randomUUID(), sessionId: binding.sessionId, context, state: "pending", cancelled: false,
package/dist/server.d.ts CHANGED
@@ -47,7 +47,8 @@ type PublisherServerBaseOptions = {
47
47
  gdprApplies?: boolean;
48
48
  publisher: { app_name: string; app_domain: string; categories: string[] };
49
49
  allowedFormats: Array<"banner" | "native" | "clip">;
50
- positionHint: "above" | "below" | "sidebar" | "between";
50
+ /** Omit to inherit the project's saved position. Must match your physical layout when supplied. */
51
+ positionHint?: "above" | "below" | "sidebar" | "between";
51
52
  /** Optional advanced caps; saved allowedSizes determine the normal envelope. */
52
53
  maxWidth?: number;
53
54
  maxHeight?: number;
package/dist/server.js CHANGED
@@ -44,7 +44,7 @@ function normalizeOptions(options) {
44
44
  if (!["wavebird_consent", "own_cmp"].includes(options.consentMode)) throw new Error("publisher_consent_mode_invalid");
45
45
  if (options.gdprApplies !== undefined && typeof options.gdprApplies !== "boolean") throw new Error("publisher_gdpr_invalid");
46
46
  if (!Array.isArray(options.allowedFormats) || options.allowedFormats.length === 0 || options.allowedFormats.some(value => !["banner", "native", "clip"].includes(value))) throw new Error("publisher_formats_invalid");
47
- if (!["above", "below", "sidebar", "between"].includes(options.positionHint)) throw new Error("publisher_position_invalid");
47
+ if (options.positionHint !== undefined && !["above", "below", "sidebar", "between"].includes(options.positionHint)) throw new Error("publisher_position_invalid");
48
48
  if (!Array.isArray(options.allowedSizes) || options.allowedSizes.length === 0 || options.allowedSizes.length > MAX_ALLOWED_SIZES || options.allowedSizes.some(size => !size || typeof size !== "object" || Object.keys(size).some(key => !["width", "height", "formats"].includes(key)) || !Number.isSafeInteger(size.width) || !Number.isSafeInteger(size.height) || size.width < 1 || size.height < 1 || size.width > MAX_SIZE_EDGE || size.height > MAX_SIZE_EDGE ||
49
49
  (size.formats !== undefined && (!Array.isArray(size.formats) || size.formats.length === 0 || size.formats.some(format => !options.allowedFormats.includes(format)))))) throw new Error("publisher_sizes_invalid");
50
50
  if (new Set(options.allowedSizes.map(size => `${size.width}x${size.height}`)).size !== options.allowedSizes.length)
@@ -256,7 +256,7 @@ export function createPublisherServer(inputOptions) {
256
256
  const placementFetch = boundedFetcher();
257
257
  const consentFetch = boundedFetcher();
258
258
  const generationReportFetch = boundedGenerationReporter();
259
- const diagnostic = code => { try { options.onDiagnostic?.(code); } catch {} };
259
+ const diagnostic = code => { try { Promise.resolve(options.onDiagnostic?.(code)).catch(() => {}); } catch {} };
260
260
  if (typeof options.turnJournal?.reconcilePending === "function") {
261
261
  void Promise.resolve().then(() => options.turnJournal.reconcilePending(options.clientId, options.surfaceId))
262
262
  .catch(() => diagnostic("turn_journal_unavailable"));
@@ -22,7 +22,7 @@ export function createPublisherTurnJournal({ storage, reportGeneration, keySecre
22
22
  const tasks = new Set();
23
23
  let activeReports = 0;
24
24
  const reportWaiters = [];
25
- const diagnostic = code => { try { onDiagnostic?.(code); } catch {} };
25
+ const diagnostic = code => { try { Promise.resolve(onDiagnostic?.(code)).catch(() => {}); } catch {} };
26
26
  const verifiedScopes = new Set();
27
27
  const versionKey = createHash("sha256").update("wavebird/turn-journal-version-row/v1").digest("hex");
28
28
  const keyFingerprint = createHmac("sha256", keySecret).update("wavebird/turn-journal-key-version/v1").digest("hex");
@@ -1,6 +1,6 @@
1
1
  # Connect generation to the displayed result
2
2
 
3
- These are connection helpers, not complete apps. Use the same installed `@wavebirdai/api@0.1.0-beta.15` as your server routes.
3
+ These are connection helpers, not complete apps. Use the same installed `@wavebirdai/api@0.1.0-beta.17` as your server routes.
4
4
 
5
5
  - `ads` is the instance for this surface, returned by `createPublisherAds` or the generated component's `onReady` callback.
6
6
  - `sendExistingRequest` sends your existing authenticated model request. Merge the provided headers into its headers and preserve its body and abort signal. Call the route wrapped by `withGeneration`.
@@ -4,10 +4,14 @@ Use this path instead of copying Dashboard's route files. It supports an existin
4
4
 
5
5
  ## Generate files
6
6
 
7
+ The generator never overwrites existing files. If it reports a conflict, keep your app's file and merge the authentication, storage and generation hooks from [Dashboard Overview](https://dashboard.wavebird.ai/wavebird/overview). Do not delete your model implementation to make the generator run.
8
+
9
+ If your app sets Content Security Policy, allow `https://api.wavebird.ai` in its script, frame and connection rules. Update `script-src-elem` too if your policy uses it. Preserve existing nonces and protections. Do not use wildcards or disable CSP. The optional browser `onDiagnostic` callback reports `renderer_csp_blocked` only for an observed enforced violation, `renderer_unavailable` if loading fails, or `renderer_frame_unavailable` if the ad frame fails. Without a CSP event, the cause remains unknown. Diagnostics never include blocked URLs or credentials.
10
+
7
11
  From the folder containing `package.json`:
8
12
 
9
13
  ```sh
10
- npm install @wavebirdai/api@0.1.0-beta.15 server-only
14
+ npm install @wavebirdai/api@0.1.0-beta.17 server-only
11
15
  ./node_modules/.bin/wavebird-next init --lang ts --root . --app-dir src/app
12
16
  ```
13
17
 
@@ -1,6 +1,6 @@
1
1
  # Web integration reference
2
2
 
3
- Applies to `@wavebirdai/api@0.1.0-beta.15`. [Start with the integration steps](../../README.md#set-up-javascript-or-typescript).
3
+ Applies to `@wavebirdai/api@0.1.0-beta.17`. [Start with the integration steps](../../README.md#set-up-javascript-or-typescript).
4
4
 
5
5
 
6
6
  `@wavebirdai/api/server` exports `createPublisherServer`. Configure it with server-only Project ID, Server Test or production Key, preference signing secret, the publisher's real request authorization function, exact `publicOrigins`, and the saved project/placement values shown in the dashboard. The origin list is required. The package compares the browser Origin with a configured public origin whose host matches the route Host, even when Next.js or a proxy gives the route an internal URL. `localhost` and `127.0.0.1` are separate origins, and each port and scheme must match exactly; HTTP loopback is available only with a Server Test Key. A production key also requires its separately approved project and wavebird server authority. Omit `bidfloor` and `bidfloorCurrency` to inherit saved pricing. An explicit override supplies both a nonnegative amount, including zero, and a three-letter currency; the API validates it against the saved project. It returns authenticated `placementPOST`, `consentGET`, `consentPOST`, and `withGeneration` handlers, plus the server-only `reportGeneration(jobId, event)` method. The helper constructs the existing `/v1/placements`, `/v1/consent`, and `/v1/jobs/{id}/generation/{event}` requests; it does not introduce a new wavebird protocol. The wavebird API remains authoritative for saved scope, creative formats, duration, fallback, and financial classification.
@@ -20,6 +20,28 @@ Call `reportGeneration` only from trusted server code with a job ID returned by
20
20
  For `after`, resolve the generation consumer only after your app presents the result. The browser helper waits for both the transport finish and that consumer before starting the placement. If presentation fails, reject the consumer so the placement does not start.
21
21
 
22
22
 
23
+ ## Placement and diagnosis
24
+
25
+ Place the component where the ad belongs in your layout. Set `positionHint` to `above`, `below`, `sidebar` or `between` to describe that physical position. Omit it to use the project's saved position. The server still enforces formats, timing, maximum sizes, project ownership and consent.
26
+
27
+ Allow the creative, disclosure and controls to determine the slot height. A fixed creative-only height can crop the ad. In a fixed-height chat, keep the composer separate and allow the ad area to scroll if its expanded information exceeds the available space. Empty or cleared slots should collapse.
28
+
29
+ For renderer failures, the browser's optional `onDiagnostic` receives only a fixed `code`. `renderer_csp_blocked` requires an observed enforced policy violation. `renderer_unavailable` and `renderer_frame_unavailable` do not identify the cause. See the [CSP setup](nextjs.md#generate-files). Callback errors never interrupt model output.
30
+
31
+ Use the existing `generationId` in the server `onLifecycle` observer to correlate generation events. It is not a credential. Retain only that ID, event category and relative timing, never session identities, request headers or response contents. A renderer error without an exact turn or slot link must stay uncorrelated.
32
+
33
+ ## Consent appearance
34
+
35
+ The wavebird dialog follows the browser's preferred supported language: English, German, Spanish, French, Portuguese or Japanese, with English as the fallback. Add `consentLocale: "de-DE"` to `createPublisherAds` only to override that preference. Omit it or use `"auto"` for browser detection.
36
+
37
+ The optional `consentTheme` accepts `accentColor`, `backgroundColor` and `textColor` as six-digit hex colors, `fontFamily` as existing font names, `radius` from 0 to 20, and `spacing` from 12 to 32 pixels. Low-contrast colors fall back to readable colors. No fonts are downloaded. For example:
38
+
39
+ ```js
40
+ consentTheme: { accentColor: "#243c5a", radius: 4, fontFamily: "Arial, sans-serif" }
41
+ ```
42
+
43
+ This is a configuration fragment, not a complete integration. Appearance does not change choices, storage, consent requirements or the `own_cmp` integration. Do not hide, rename or disable consent actions with app styles.
44
+
23
45
  ## Troubleshooting
24
46
 
25
47
  With the trusted-session integration, consent restoration reads the current server revision before synchronizing the saved choice. Reloading does not reset consent revisions. An unavailable revision keeps ads disabled until consent can be synchronized; it does not block the model response.
@@ -28,6 +50,7 @@ With the trusted-session integration, consent restoration reads the current serv
28
50
  - **Origin rejected:** compare scheme, hostname and port with the saved project and server allowlist. `www.example.com` and `example.com` are separate origins.
29
51
  - **No-Fill or `no_fit`:** keep the model result usable. Check saved formats and the measured slot size. Do not stretch a creative to force it to fit.
30
52
  - **Empty frame:** record only the fixed error category and relative timing. HTTP 200 alone does not prove visible rendering. Never share signed URLs, headers, tokens or a HAR containing credentials.
53
+ - **Frequency limit:** limits apply to the supplied session. `frequency_cap_exceeded` is an actual cap denial. Test decision metadata identifies its policy and limit; an unknown reset time remains `null`. `frequency_session_required` means session data is missing. `frequency_service_unavailable`, `frequency_context_unavailable` and `frequency_configuration_invalid` are technical failures, not proof of repeated ad exposure.
31
54
  - **After ad arrives too early:** resolve the result consumer after the UI has presented the result, not merely after the last network byte.
32
55
 
33
56
  See [troubleshooting](https://wavebird.ai/api/troubleshooting) and [format behavior](https://wavebird.ai/api/concepts/ad-formats).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wavebirdai/api",
3
- "version": "0.1.0-beta.15",
3
+ "version": "0.1.0-beta.17",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "JavaScript and TypeScript integration for wavebird Banner, Native and Clip ads, with consent and generation lifecycle handling.",
@@ -20,6 +20,7 @@
20
20
  "bin",
21
21
  "templates",
22
22
  "README.md",
23
+ "CHANGELOG.md",
23
24
  "LICENSE",
24
25
  "docs/web",
25
26
  "python/README.md",
package/src/browser.d.ts CHANGED
@@ -17,6 +17,18 @@ export type PublisherAds<Bound extends boolean = boolean> = {
17
17
  deny(): Promise<unknown>;
18
18
  withdraw(): Promise<unknown>;
19
19
  };
20
+ export type PublisherConsentTheme = {
21
+ /** Six-digit hex colors. Insufficient contrast falls back to readable colors. */
22
+ accentColor?: string;
23
+ backgroundColor?: string;
24
+ textColor?: string;
25
+ /** Font family names only, without CSS rules or URLs. No font is downloaded. */
26
+ fontFamily?: string;
27
+ /** Corner radius in pixels, 0–20. */
28
+ radius?: number;
29
+ /** Card padding in pixels, 12–32. */
30
+ spacing?: number;
31
+ };
20
32
  type PublisherAdsOptionsBase = {
21
33
  target: HTMLElement;
22
34
  clientId: string;
@@ -26,10 +38,16 @@ type PublisherAdsOptionsBase = {
26
38
  conversationId: string;
27
39
  timing?: "before" | "during" | "after";
28
40
  consentMode?: "wavebird_consent" | "own_cmp";
41
+ /** Defaults to browser language preferences, then English. Optional BCP 47 language tag or "auto". */
42
+ consentLocale?: string;
43
+ /** Presentation only. Does not change consent choices or storage. */
44
+ consentTheme?: PublisherConsentTheme;
29
45
  /** Optional official renderer URL. Only https://api.wavebird.ai/v1/render.js is supported. */
30
46
  rendererUrl?: string;
31
47
  privacySettingsTarget?: string;
32
48
  getFormat?: () => "banner" | "native" | "clip" | "auto";
49
+ /** Fixed diagnostic codes only. Exceptions in this callback never interrupt the model. */
50
+ onDiagnostic?: (event: { code: "renderer_csp_blocked" | "renderer_unavailable" | "renderer_frame_unavailable" }) => void;
33
51
  placementEndpoint?: string;
34
52
  consentEndpoint?: string;
35
53
  };
package/src/browser.js CHANGED
@@ -52,6 +52,25 @@ export function createPublisherAds(options) {
52
52
  if (rendererUrl !== "https://api.wavebird.ai/v1/render.js") throw new Error("publisher_renderer_url_invalid");
53
53
  if (options.getFormat !== undefined && typeof options.getFormat !== "function")
54
54
  throw new Error("publisher_format_hook_invalid");
55
+ if (options.onDiagnostic !== undefined && typeof options.onDiagnostic !== "function")
56
+ throw new Error("publisher_diagnostic_hook_invalid");
57
+ if (options.consentLocale !== undefined && (typeof options.consentLocale !== "string" ||
58
+ !/^(?:auto|[a-z]{2,3}(?:-[a-z0-9]{2,8})*)$/i.test(options.consentLocale)))
59
+ throw new Error("publisher_consent_locale_invalid");
60
+ const consentTheme = options.consentTheme === undefined ? undefined : options.consentTheme;
61
+ if (consentTheme !== undefined) {
62
+ const validators = {
63
+ accentColor: value => typeof value === "string" && /^#[\da-f]{6}$/i.test(value),
64
+ backgroundColor: value => typeof value === "string" && /^#[\da-f]{6}$/i.test(value),
65
+ textColor: value => typeof value === "string" && /^#[\da-f]{6}$/i.test(value),
66
+ fontFamily: value => typeof value === "string" && /^[a-z0-9 ,"'\-]{1,160}$/i.test(value),
67
+ radius: value => typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= 20,
68
+ spacing: value => typeof value === "number" && Number.isFinite(value) && value >= 12 && value <= 32,
69
+ };
70
+ if (!consentTheme || typeof consentTheme !== "object" || Array.isArray(consentTheme) ||
71
+ Object.entries(consentTheme).some(([key, value]) => !Object.hasOwn(validators, key) || !validators[key](value)))
72
+ throw new Error("publisher_consent_theme_invalid");
73
+ }
55
74
  let privacyTarget = null;
56
75
  if (consentMode === "wavebird_consent" && options.privacySettingsTarget !== undefined) {
57
76
  if (typeof options.privacySettingsTarget !== "string" || !options.privacySettingsTarget.trim())
@@ -62,7 +81,21 @@ export function createPublisherAds(options) {
62
81
  let binding = { userId: options.userId, conversationId: options.conversationId,
63
82
  sessionId: turnBinding ? options.sessionId : crypto.randomUUID() };
64
83
  let sponsor = null, disposed = false, context = 0, active = null;
84
+ const diagnostic = code => {
85
+ if (!disposed) { try { Promise.resolve(options.onDiagnostic?.({ code })).catch(() => {}); } catch {} }
86
+ };
87
+ const onPolicyViolation = event => {
88
+ if (event.disposition !== "enforce" ||
89
+ !["script-src", "script-src-elem", "frame-src", "connect-src"].includes(event.effectiveDirective)) return;
90
+ try {
91
+ if (new URL(event.blockedURI).origin === "https://api.wavebird.ai") diagnostic("renderer_csp_blocked");
92
+ } catch {}
93
+ };
94
+ document.addEventListener?.("securitypolicyviolation", onPolicyViolation);
65
95
  const slot = document.createElement("section");
96
+ const onRenderFailure = () => diagnostic("renderer_frame_unavailable");
97
+ // Renderer failures originate in a child mount and do not bubble.
98
+ slot.addEventListener?.("ad:render_failed", onRenderFailure, true);
66
99
  slot.setAttribute("aria-label", "Sponsored placement");
67
100
  slot.style.cssText = "width:100%;height:100%;overflow:hidden;margin:0 auto";
68
101
  target.append(slot);
@@ -121,8 +154,10 @@ export function createPublisherAds(options) {
121
154
  if (active) event(active, "abort");
122
155
  disposed = true; context++; active = null;
123
156
  sponsor?.dispose(); sponsor = null; slot.remove();
157
+ slot.removeEventListener?.("ad:render_failed", onRenderFailure, true);
124
158
  privacyTarget?.removeEventListener("click", openPrivacySettings);
125
159
  window.removeEventListener("pagehide", dispose);
160
+ document.removeEventListener?.("securitypolicyviolation", onPolicyViolation);
126
161
  }
127
162
  window.addEventListener("pagehide", dispose);
128
163
  const ready = loadRenderer(rendererUrl).then(() => {
@@ -130,6 +165,8 @@ export function createPublisherAds(options) {
130
165
  sponsor = window.wavebird.createChatSponsor({ target: slot, ...binding,
131
166
  clientId: options.clientId, surfaceId: options.surfaceId, jobType: options.jobType, timing, consentMode,
132
167
  cleanupAfterClip: true,
168
+ ...(options.consentLocale === undefined ? {} : { consentLocale: options.consentLocale }),
169
+ ...(consentTheme === undefined ? {} : { consentTheme: { ...consentTheme } }),
133
170
  ...(turnBinding ? { turnBinding: true } : {}),
134
171
  ...(options.getFormat === undefined ? {} : { getFormat: options.getFormat }),
135
172
  ...(options.placementEndpoint === undefined ? {} : { placementEndpoint: options.placementEndpoint }),
@@ -143,7 +180,7 @@ export function createPublisherAds(options) {
143
180
  notify("onStarted", active.id); notify("onDone", active.id);
144
181
  }
145
182
  }
146
- }).catch(() => {});
183
+ }).catch(() => { diagnostic("renderer_unavailable"); });
147
184
 
148
185
  async function connectGeneration({ request, consume, signal }) {
149
186
  const job = { id: crypto.randomUUID(), sessionId: binding.sessionId, context, state: "pending", cancelled: false,
package/src/server.d.ts CHANGED
@@ -47,7 +47,8 @@ type PublisherServerBaseOptions = {
47
47
  gdprApplies?: boolean;
48
48
  publisher: { app_name: string; app_domain: string; categories: string[] };
49
49
  allowedFormats: Array<"banner" | "native" | "clip">;
50
- positionHint: "above" | "below" | "sidebar" | "between";
50
+ /** Omit to inherit the project's saved position. Must match your physical layout when supplied. */
51
+ positionHint?: "above" | "below" | "sidebar" | "between";
51
52
  /** Optional advanced caps; saved allowedSizes determine the normal envelope. */
52
53
  maxWidth?: number;
53
54
  maxHeight?: number;
package/src/server.js CHANGED
@@ -44,7 +44,7 @@ function normalizeOptions(options) {
44
44
  if (!["wavebird_consent", "own_cmp"].includes(options.consentMode)) throw new Error("publisher_consent_mode_invalid");
45
45
  if (options.gdprApplies !== undefined && typeof options.gdprApplies !== "boolean") throw new Error("publisher_gdpr_invalid");
46
46
  if (!Array.isArray(options.allowedFormats) || options.allowedFormats.length === 0 || options.allowedFormats.some(value => !["banner", "native", "clip"].includes(value))) throw new Error("publisher_formats_invalid");
47
- if (!["above", "below", "sidebar", "between"].includes(options.positionHint)) throw new Error("publisher_position_invalid");
47
+ if (options.positionHint !== undefined && !["above", "below", "sidebar", "between"].includes(options.positionHint)) throw new Error("publisher_position_invalid");
48
48
  if (!Array.isArray(options.allowedSizes) || options.allowedSizes.length === 0 || options.allowedSizes.length > MAX_ALLOWED_SIZES || options.allowedSizes.some(size => !size || typeof size !== "object" || Object.keys(size).some(key => !["width", "height", "formats"].includes(key)) || !Number.isSafeInteger(size.width) || !Number.isSafeInteger(size.height) || size.width < 1 || size.height < 1 || size.width > MAX_SIZE_EDGE || size.height > MAX_SIZE_EDGE ||
49
49
  (size.formats !== undefined && (!Array.isArray(size.formats) || size.formats.length === 0 || size.formats.some(format => !options.allowedFormats.includes(format)))))) throw new Error("publisher_sizes_invalid");
50
50
  if (new Set(options.allowedSizes.map(size => `${size.width}x${size.height}`)).size !== options.allowedSizes.length)
@@ -256,7 +256,7 @@ export function createPublisherServer(inputOptions) {
256
256
  const placementFetch = boundedFetcher();
257
257
  const consentFetch = boundedFetcher();
258
258
  const generationReportFetch = boundedGenerationReporter();
259
- const diagnostic = code => { try { options.onDiagnostic?.(code); } catch {} };
259
+ const diagnostic = code => { try { Promise.resolve(options.onDiagnostic?.(code)).catch(() => {}); } catch {} };
260
260
  if (typeof options.turnJournal?.reconcilePending === "function") {
261
261
  void Promise.resolve().then(() => options.turnJournal.reconcilePending(options.clientId, options.surfaceId))
262
262
  .catch(() => diagnostic("turn_journal_unavailable"));
@@ -22,7 +22,7 @@ export function createPublisherTurnJournal({ storage, reportGeneration, keySecre
22
22
  const tasks = new Set();
23
23
  let activeReports = 0;
24
24
  const reportWaiters = [];
25
- const diagnostic = code => { try { onDiagnostic?.(code); } catch {} };
25
+ const diagnostic = code => { try { Promise.resolve(onDiagnostic?.(code)).catch(() => {}); } catch {} };
26
26
  const verifiedScopes = new Set();
27
27
  const versionKey = createHash("sha256").update("wavebird/turn-journal-version-row/v1").digest("hex");
28
28
  const keyFingerprint = createHmac("sha256", keySecret).update("wavebird/turn-journal-key-version/v1").digest("hex");
@@ -1,10 +1,12 @@
1
1
  # Connect wavebird to this Next.js app
2
2
 
3
+ If your app sets Content Security Policy, merge `https://api.wavebird.ai` into `script-src`, `frame-src` and `connect-src`. Preserve nonces and existing protections. Do not disable CSP or allow wildcard origins. Keep secret Server ENV outside source downloads, Git and browser bundles.
4
+
3
5
  The generator installed `lib/publisher`, `lib/auth`, `lib/turn-store` and `lib/model`; `app/api/generate`, `app/api/sponsor-slot`, `app/api/sponsor-consent` and `app/api/sponsor-session`; and `components/WavebirdPlacement` (under `src/` when `src/app` was selected). No existing page was replaced.
4
6
 
5
7
  Install `server-only` in your app (`npm install server-only`). Install `pg` too if you use the PostgreSQL adapter. Use the full Server ENV from Dashboard's Integration step 2, including the saved preference secret and origins. A key-only ENV download is not the full configuration. Keep the preference secret unchanged across restarts.
6
8
 
7
- 1. Copy the complete Server ENV from the Dashboard: `WAVEBIRD_CLIENT_ID`, `WAVEBIRD_SECRET_KEY`, `WAVEBIRD_PREFERENCE_SECRET`, and `WAVEBIRD_PUBLIC_ORIGINS`. Keep the saved preference secret stable. The origins value is a comma-separated list of the exact scheme, host, and port where your app is opened. Keep the Dashboard project domain at your real HTTPS host. For local Server Test-key testing, include the exact loopback origin in `WAVEBIRD_PUBLIC_ORIGINS` without changing that project domain; Browser Test Keys instead use their separate Allowed origins field in API Keys. `localhost` and `127.0.0.1` are distinct. Do not use wildcards. The package rejects an absent or malformed list. Never expose server secrets through `NEXT_PUBLIC_` or client props. `clientId` is the public project ID.
9
+ 1. Copy the complete Server ENV from the Dashboard: `WAVEBIRD_API_BASE_URL`, `WAVEBIRD_CLIENT_ID`, `WAVEBIRD_SECRET_KEY`, `WAVEBIRD_PREFERENCE_SECRET`, and `WAVEBIRD_PUBLIC_ORIGINS`. Keep the saved preference secret stable. The origins value is a comma-separated list of the exact scheme, host, and port where your app is opened. Keep the Dashboard project domain at your real HTTPS host. For local Server Test-key testing, include the exact loopback origin in `WAVEBIRD_PUBLIC_ORIGINS` without changing that project domain; Browser Test Keys instead use their separate Allowed origins field in API Keys. `localhost` and `127.0.0.1` are distinct. Do not use wildcards. The package rejects an absent or malformed list. Never expose server secrets through `NEXT_PUBLIC_` or client props. `clientId` is the public project ID.
8
10
  2. Replace `lib/publisher`'s example surface, placement, allowed sizes, formats, locale, consent mode, and publisher identity with the **saved Dashboard values**. The responsive example lists 728×90 and 320×50 Banner sizes only to show the size-selection shape. The saved sizes define the normal envelope; optional `maxWidth` and `maxHeight` are advanced caps that only narrow it. Keep `responsiveSizeSelection: true` only when the selected project and placement approve every configured size. Remove any size absent from the saved project before Test traffic. The API enforces its own authority; example values do not create a valid placement.
9
11
  3. Connect `lib/auth` to the app's real session authorization. Its supplied path check fails closed when `PUBLISHER_AUTH_CHECK_PATH` is absent. The path must be a publisher-owned same-origin route that returns 204 only for an authorized user and supplies an `x-publisher-session-id` header containing a stable non-credential correlation ID for that authenticated session. Never return a cookie, bearer token or raw credential as that ID. The route must not be any wavebird route. The example sends the session cookie to that check only when the request origin exactly matches `WAVEBIRD_PUBLIC_ORIGINS`; a missing or different origin fails closed. The package checks that the browser's session ID matches this server-validated value before placement or generation.
10
12
  4. Replace `lib/turn-store`'s fail-closed stub with `createPostgresTurnStorage(yourExistingPgPool)` or another persistent store implementing the package's atomic interface. For PostgreSQL, run the adapter's `install()` once in your normal database migration step; use a pool shared by the publisher's workers. Keep `WAVEBIRD_PREFERENCE_SECRET` stable across workers and restarts; the package derives a separate journal key from it and rejects a changed key for an active project. Coordinate secret rotation after active turns are drained; never clear the journal guard to restore ad service while turns remain. The package owns turn claims, ordered reports, retry and bounded reconciliation. An unavailable store suppresses ad placement while the authenticated model route remains available.