@adviverse/desktop 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,95 @@
1
- # Temporary Holding Version
1
+ # @adviverse/desktop
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Adviverse ads for **native desktop apps that host a webview** — Electron, Tauri,
4
+ CEF, WKWebView, WebView2. It runs the same loop as the terminal/mobile SDKs:
5
+ **fetch → cache → render → viewability → impression → click**, with the ad
6
+ rendered right in your app's UI. On no-fill it renders nothing.
7
+
8
+ For a **pure-native** app (Qt/Cocoa/WinUI, no webview), use the native-render
9
+ core instead: [`@adviverse/desktop-native`](../desktop-native) (C ABI).
10
+
11
+ ## Install
12
+
13
+ ```sh
14
+ npm install @adviverse/desktop
15
+ ```
16
+
17
+ | You use | Package | Repo |
18
+ |---|---|---|
19
+ | Any webview, no framework (Tauri, CEF, WKWebView, WebView2, Electron renderer) | `@adviverse/desktop` | [desktop-sdk](https://github.com/Adviverse/desktop-sdk) |
20
+ | React renderer | `@adviverse/desktop-react` | [desktop-react-sdk](https://github.com/Adviverse/desktop-react-sdk) |
21
+ | Electron main process (click → system browser) | `@adviverse/electron` | [electron-sdk](https://github.com/Adviverse/electron-sdk) |
22
+
23
+ Get a **serve token** (`ts_…`) from your Adviverse dashboard (Publisher →
24
+ Placements → terminal/SDK token). `ak_…` API keys and publisher placement tags
25
+ also work.
26
+
27
+ ## Renderer — no framework
28
+
29
+ ```ts
30
+ import { mountAd } from '@adviverse/desktop';
31
+
32
+ const dispose = mountAd(document.getElementById('ad')!, {
33
+ token: 'ts_yourtoken',
34
+ refreshMs: 60000,
35
+ });
36
+ // later: dispose();
37
+ ```
38
+
39
+ Or drive it yourself:
40
+
41
+ ```ts
42
+ import { fetchAd, openClick, observeViewability } from '@adviverse/desktop';
43
+
44
+ const ad = await fetchAd({ token: 'ts_yourtoken' });
45
+ if (ad) {
46
+ const el = renderYourCard(ad); // your DOM
47
+ observeViewability(el, ad); // fires the impression when truly visible
48
+ el.onclick = () => openClick(ad); // opens the landing page in the default browser
49
+ }
50
+ ```
51
+
52
+ ## Opening clicks in the system browser
53
+
54
+ A display-ad click must open the **default browser**, not navigate your app
55
+ window. `openClick()` auto-detects the host:
56
+
57
+ - **Tauri** — uses the shell-open plugin (add `@tauri-apps/plugin-shell` and
58
+ allow `shell:open`).
59
+ - **Electron** — expose a bridge from the main process (below).
60
+ - **Fallback** — `window.open(url, '_blank')`.
61
+
62
+ ### Electron bridge
63
+
64
+ Electron apps install [`@adviverse/electron`](https://github.com/Adviverse/electron-sdk)
65
+ in the main process (one call + a ready-made preload).
66
+
67
+ ## What "done right" means (built in)
68
+
69
+ - **Viewability** — the impression fires only when the ad is ≥50% on-screen
70
+ **and** the window is visible **and** focused, continuously for ~1s (MRC-style).
71
+ Backgrounded/minimized windows don't count.
72
+ - **Consent** — pass `consent: { gdpr, usPrivacy }` (TCF string / US-Privacy);
73
+ they're forwarded to serving.
74
+ - **Integrity** — a stable per-install `uid` is generated + persisted; ships
75
+ your serve token. For signed placements use an `ak_` key server-side.
76
+ - **Frequency/caching** — the ad is cached ~60s per token, so a re-render or a
77
+ tight `refreshMs` never hammers the network.
78
+
79
+ ## Config
80
+
81
+ | field | default | notes |
82
+ |-------|---------|-------|
83
+ | `token` | — | `ts_` serve token \| `ak_` API key \| publisher tag (required) |
84
+ | `uid` | auto | stable per-install id (persisted in localStorage) |
85
+ | `consent` | — | `{ gdpr, usPrivacy }` privacy signals |
86
+ | `emailSha256` | — | SHA-256 of a lowercased email (opt-in identity) |
87
+ | `client` | `"desktop"` | reporting/integrity label |
88
+ | `base` | `https://serve.adviverse.com` | serve host override |
89
+ | `timeoutMs` | `2500` | fetch timeout (UI never blocks regardless) |
90
+
91
+ ## Store policies
92
+
93
+ Mac App Store / Microsoft Store require ads to be **disclosed** and non-deceptive
94
+ — the built-in card shows an `ad` label; keep it if you swap in custom markup.
95
+ Steam / self-distributed apps are more permissive.
package/dist/core.d.ts ADDED
@@ -0,0 +1,67 @@
1
+ /**
2
+ * @adviverse/desktop — core ad loop for native desktop apps that host a webview
3
+ * (Electron, Tauri, CEF, WKWebView, WebView2). Framework-agnostic: fetch → cache
4
+ * → render → viewability → impression → click. The React and vanilla surfaces
5
+ * are thin wrappers over this.
6
+ *
7
+ * Serving mirrors the terminal/IDE SDKs: an `ADVIVERSE_TAG` routes by prefix —
8
+ * `ts_` (public serve token) and `ak_` (secret API key) go to the self-network
9
+ * serve endpoint; anything else is treated as a publisher placement tag.
10
+ */
11
+ export interface Ad {
12
+ /** Headline — the line shown. */
13
+ text: string;
14
+ /** Optional secondary text. */
15
+ body?: string;
16
+ /** Call to action, e.g. "Try free". */
17
+ cta?: string;
18
+ brand?: string;
19
+ /** Tracked /click redirect — open this in the default browser on click. */
20
+ url?: string;
21
+ /** Compact /c/<code> link (fallback). */
22
+ short_url?: string;
23
+ /** GET this once when the ad is actually displayed (viewability). */
24
+ impression_url?: string;
25
+ /** Disclosure marker, e.g. "ad". */
26
+ label: string;
27
+ /** Seconds the ad may be cached/shown. */
28
+ ttl: number;
29
+ }
30
+ export interface AdviverseConfig {
31
+ /** ts_ serve token | ak_ API key | publisher placement tag. Required. */
32
+ token: string;
33
+ /** Stable per-install id. Auto-generated + persisted (localStorage) if omitted. */
34
+ uid?: string;
35
+ /** Privacy signals passed through to serving (GDPR TCF string / US Privacy). */
36
+ consent?: {
37
+ gdpr?: string;
38
+ usPrivacy?: string;
39
+ };
40
+ /** SHA-256 of a lowercased email, for cross-surface identity (opt-in). */
41
+ emailSha256?: string;
42
+ /** Override the serve base (default https://serve.adviverse.com). */
43
+ base?: string;
44
+ /** Fetch timeout (default 2500ms). Never blocks the UI regardless. */
45
+ timeoutMs?: number;
46
+ /** App/client label for reporting + integrity (default "desktop"). */
47
+ client?: string;
48
+ }
49
+ /**
50
+ * Fetch an ad (cached ~60s per token so the network is hit at most once/minute).
51
+ * Resolves to null on no-fill / offline / error — callers render nothing then.
52
+ */
53
+ export declare function fetchAd(cfg: AdviverseConfig): Promise<Ad | null>;
54
+ /** Open the ad's landing page in the user's DEFAULT browser (never in-app). */
55
+ export declare function openClick(ad: Ad): void;
56
+ /** Fire the impression beacon exactly once (idempotent per Ad object). */
57
+ export declare function fireImpression(ad: Ad & {
58
+ __imp?: boolean;
59
+ }): void;
60
+ /**
61
+ * Watch an element and fire the impression once it is genuinely VIEWABLE: at
62
+ * least 50% on-screen AND the window/tab visible AND focused, continuously for
63
+ * `dwellMs` (MRC-style). Returns a disposer. Pure DOM — works in any webview.
64
+ */
65
+ export declare function observeViewability(el: Element, ad: Ad, opts?: {
66
+ dwellMs?: number;
67
+ }): () => void;
package/dist/core.js ADDED
@@ -0,0 +1,155 @@
1
+ /**
2
+ * @adviverse/desktop — core ad loop for native desktop apps that host a webview
3
+ * (Electron, Tauri, CEF, WKWebView, WebView2). Framework-agnostic: fetch → cache
4
+ * → render → viewability → impression → click. The React and vanilla surfaces
5
+ * are thin wrappers over this.
6
+ *
7
+ * Serving mirrors the terminal/IDE SDKs: an `ADVIVERSE_TAG` routes by prefix —
8
+ * `ts_` (public serve token) and `ak_` (secret API key) go to the self-network
9
+ * serve endpoint; anything else is treated as a publisher placement tag.
10
+ */
11
+ const DEFAULT_BASE = 'https://serve.adviverse.com';
12
+ const TTL_MS = 60000; // network back-off; the widget re-renders from cache freely
13
+ const UID_KEY = 'adviverse_uid';
14
+ const w = globalThis;
15
+ function persistedUid() {
16
+ try {
17
+ const cur = w.localStorage?.getItem(UID_KEY);
18
+ if (cur)
19
+ return cur;
20
+ }
21
+ catch { /* no storage */ }
22
+ const id = 'ins_' + Math.random().toString(36).slice(2, 10) + Date.now().toString(36);
23
+ try {
24
+ w.localStorage?.setItem(UID_KEY, id);
25
+ }
26
+ catch { /* ignore */ }
27
+ return id;
28
+ }
29
+ const memCache = new Map();
30
+ function serveUrl(cfg) {
31
+ const base = cfg.base || DEFAULT_BASE;
32
+ const q = new URLSearchParams({
33
+ uid: cfg.uid || persistedUid(),
34
+ client: cfg.client || 'desktop',
35
+ });
36
+ if (cfg.emailSha256)
37
+ q.set('em', cfg.emailSha256);
38
+ if (cfg.consent?.gdpr)
39
+ q.set('gdpr_consent', cfg.consent.gdpr);
40
+ if (cfg.consent?.usPrivacy)
41
+ q.set('us_privacy', cfg.consent.usPrivacy);
42
+ const headers = {};
43
+ if (/^ts_/.test(cfg.token)) {
44
+ q.set('token', cfg.token);
45
+ return { url: `${base}/terminal/serve?${q}`, headers };
46
+ }
47
+ if (/^ak_/.test(cfg.token)) {
48
+ headers['x-api-key'] = cfg.token;
49
+ return { url: `${base}/terminal/serve?${q}`, headers };
50
+ }
51
+ q.set('tag', cfg.token);
52
+ return { url: `${base}/terminal?${q}`, headers };
53
+ }
54
+ /**
55
+ * Fetch an ad (cached ~60s per token so the network is hit at most once/minute).
56
+ * Resolves to null on no-fill / offline / error — callers render nothing then.
57
+ */
58
+ export async function fetchAd(cfg) {
59
+ const key = cfg.token;
60
+ const hit = memCache.get(key);
61
+ if (hit && Date.now() - hit.at < TTL_MS)
62
+ return hit.ad;
63
+ let ad = null;
64
+ try {
65
+ const { url, headers } = serveUrl(cfg);
66
+ const ctrl = new AbortController();
67
+ const timer = setTimeout(() => ctrl.abort(), cfg.timeoutMs ?? 2500);
68
+ const res = await fetch(url, { headers, signal: ctrl.signal, credentials: 'omit' });
69
+ clearTimeout(timer);
70
+ const body = (await res.json());
71
+ if (body && body.text)
72
+ ad = body;
73
+ }
74
+ catch {
75
+ ad = null; // offline / timeout / no-fill — cache the miss to back off for TTL
76
+ }
77
+ memCache.set(key, { at: Date.now(), ad });
78
+ return ad;
79
+ }
80
+ /** Open the ad's landing page in the user's DEFAULT browser (never in-app). */
81
+ export function openClick(ad) {
82
+ const url = ad.url || ad.short_url;
83
+ if (!url)
84
+ return;
85
+ // Electron: the app's preload should expose window.adviverse.openExternal →
86
+ // shell.openExternal (see electron.ts). Tauri: the shell-open plugin. Else the
87
+ // webview's window.open, which most hosts route to the system browser.
88
+ try {
89
+ if (typeof w.adviverse?.openExternal === 'function') {
90
+ w.adviverse.openExternal(url);
91
+ return;
92
+ }
93
+ const tauriOpen = w.__TAURI__?.shell?.open;
94
+ if (typeof tauriOpen === 'function') {
95
+ tauriOpen(url);
96
+ return;
97
+ }
98
+ if (w.__TAURI_INTERNALS__ && typeof w.__TAURI_INVOKE__ !== 'undefined') {
99
+ // Tauri v2 with the shell plugin registered.
100
+ w.__TAURI__?.core?.invoke?.('plugin:shell|open', { path: url });
101
+ return;
102
+ }
103
+ w.open?.(url, '_blank', 'noopener,noreferrer');
104
+ }
105
+ catch { /* best-effort */ }
106
+ }
107
+ /** Fire the impression beacon exactly once (idempotent per Ad object). */
108
+ export function fireImpression(ad) {
109
+ if (ad.__imp || !ad.impression_url)
110
+ return;
111
+ ad.__imp = true;
112
+ try {
113
+ fetch(ad.impression_url, { credentials: 'omit', keepalive: true }).catch(() => { });
114
+ }
115
+ catch { /* ignore */ }
116
+ }
117
+ /**
118
+ * Watch an element and fire the impression once it is genuinely VIEWABLE: at
119
+ * least 50% on-screen AND the window/tab visible AND focused, continuously for
120
+ * `dwellMs` (MRC-style). Returns a disposer. Pure DOM — works in any webview.
121
+ */
122
+ export function observeViewability(el, ad, opts = {}) {
123
+ const dwell = opts.dwellMs ?? 1000;
124
+ let timer = null;
125
+ let done = false;
126
+ const visible = () => (typeof document === 'undefined' || document.visibilityState === 'visible') &&
127
+ (typeof document === 'undefined' || typeof document.hasFocus !== 'function' || document.hasFocus());
128
+ const stop = () => { if (timer) {
129
+ clearTimeout(timer);
130
+ timer = null;
131
+ } };
132
+ const arm = () => {
133
+ if (done || timer)
134
+ return;
135
+ timer = setTimeout(() => {
136
+ if (!done && visible()) {
137
+ done = true;
138
+ fireImpression(ad);
139
+ io.disconnect();
140
+ window.removeEventListener('blur', stop);
141
+ }
142
+ }, dwell);
143
+ };
144
+ const io = new IntersectionObserver((entries) => {
145
+ for (const e of entries) {
146
+ if (e.isIntersecting && e.intersectionRatio >= 0.5 && visible())
147
+ arm();
148
+ else
149
+ stop();
150
+ }
151
+ }, { threshold: [0, 0.5, 1] });
152
+ io.observe(el);
153
+ window.addEventListener('blur', stop);
154
+ return () => { done = true; stop(); io.disconnect(); window.removeEventListener('blur', stop); };
155
+ }
@@ -0,0 +1,13 @@
1
+ /**
2
+ * @adviverse/desktop — ads for native desktop apps that host a webview
3
+ * (Electron, Tauri, CEF, WKWebView, WebView2).
4
+ *
5
+ * Renderer entry (no React): core loop + a framework-free mount.
6
+ * import { mountAd, fetchAd } from '@adviverse/desktop';
7
+ * React: @adviverse/desktop-react (<AdviverseAd/>)
8
+ * Electron: @adviverse/electron (main-process + preload bridge)
9
+ */
10
+ export type { Ad, AdviverseConfig } from './core';
11
+ export { fetchAd, openClick, fireImpression, observeViewability } from './core';
12
+ export { mountAd } from './vanilla';
13
+ export type { MountOptions } from './vanilla';
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export { fetchAd, openClick, fireImpression, observeViewability } from './core';
2
+ export { mountAd } from './vanilla';
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Framework-free ad mount for any webview renderer (no React).
3
+ *
4
+ * import { mountAd } from '@adviverse/desktop';
5
+ * const dispose = mountAd(document.getElementById('ad'), { token: 'ts_...' });
6
+ *
7
+ * Builds a disclosed ad card in `el`, fires the impression on viewability, and
8
+ * opens clicks in the default browser. Returns a disposer. Renders nothing on
9
+ * no-fill. Re-render with `refreshMs` for rotation (min 30s; paused while hidden).
10
+ */
11
+ import { AdviverseConfig } from './core';
12
+ export interface MountOptions extends AdviverseConfig {
13
+ refreshMs?: number;
14
+ }
15
+ export declare function mountAd(el: Element, opts: MountOptions): () => void;
@@ -0,0 +1,72 @@
1
+ /**
2
+ * Framework-free ad mount for any webview renderer (no React).
3
+ *
4
+ * import { mountAd } from '@adviverse/desktop';
5
+ * const dispose = mountAd(document.getElementById('ad'), { token: 'ts_...' });
6
+ *
7
+ * Builds a disclosed ad card in `el`, fires the impression on viewability, and
8
+ * opens clicks in the default browser. Returns a disposer. Renders nothing on
9
+ * no-fill. Re-render with `refreshMs` for rotation (min 30s; paused while hidden).
10
+ */
11
+ import { fetchAd, observeViewability, openClick } from './core';
12
+ function card(ad) {
13
+ const root = document.createElement('div');
14
+ root.setAttribute('role', 'link');
15
+ root.tabIndex = 0;
16
+ Object.assign(root.style, {
17
+ display: 'flex', alignItems: 'center', gap: '10px', cursor: 'pointer',
18
+ padding: '10px 12px', borderRadius: '10px', fontSize: '13px', lineHeight: '1.35',
19
+ border: '1px solid rgba(127,127,127,0.22)', background: 'rgba(127,127,127,0.06)',
20
+ boxSizing: 'border-box', maxWidth: '100%',
21
+ });
22
+ const label = document.createElement('span');
23
+ label.textContent = ad.label || 'ad';
24
+ Object.assign(label.style, { fontSize: '10px', textTransform: 'uppercase', letterSpacing: '0.06em', opacity: '0.6', flex: 'none' });
25
+ const body = document.createElement('span');
26
+ Object.assign(body.style, { flex: '1', minWidth: '0', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' });
27
+ body.textContent = (ad.brand ? ad.brand + ' — ' : '') + ad.text + (ad.body ? ' ' + ad.body : '');
28
+ root.append(label, body);
29
+ if (ad.cta) {
30
+ const cta = document.createElement('span');
31
+ cta.textContent = ad.cta + ' →';
32
+ Object.assign(cta.style, { flex: 'none', fontWeight: '600', color: '#1b50e0', whiteSpace: 'nowrap' });
33
+ root.append(cta);
34
+ }
35
+ return root;
36
+ }
37
+ export function mountAd(el, opts) {
38
+ let disposeView = null;
39
+ let alive = true;
40
+ const render = (ad) => {
41
+ if (!alive)
42
+ return;
43
+ if (disposeView) {
44
+ disposeView();
45
+ disposeView = null;
46
+ }
47
+ el.innerHTML = '';
48
+ if (!ad)
49
+ return;
50
+ const node = card(ad);
51
+ const onClick = () => openClick(ad);
52
+ node.addEventListener('click', onClick);
53
+ node.addEventListener('keydown', (e) => { const k = e.key; if (k === 'Enter' || k === ' ')
54
+ onClick(); });
55
+ el.append(node);
56
+ disposeView = observeViewability(node, ad);
57
+ };
58
+ const load = () => fetchAd(opts).then(render);
59
+ load();
60
+ // Rotation floor 30s (faster refreshes are voided as repeat views anyway); skip while the window is hidden.
61
+ const refresh = () => { if (typeof document === 'undefined' || document.visibilityState === 'visible')
62
+ load(); };
63
+ const id = opts.refreshMs ? setInterval(refresh, Math.max(30000, opts.refreshMs)) : undefined;
64
+ return () => {
65
+ alive = false;
66
+ if (id)
67
+ clearInterval(id);
68
+ if (disposeView)
69
+ disposeView();
70
+ el.innerHTML = '';
71
+ };
72
+ }
package/package.json CHANGED
@@ -1,6 +1,34 @@
1
1
  {
2
2
  "name": "@adviverse/desktop",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "Adviverse ads for desktop apps that host a webview (Electron, Tauri, CEF, WKWebView, WebView2) \u2014 core loop + framework-free mount. React: @adviverse/desktop-react. Electron bridge: @adviverse/electron.",
5
+ "license": "UNLICENSED",
6
+ "type": "module",
7
+ "main": "dist/index.js",
8
+ "types": "dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/index.js"
13
+ }
14
+ },
15
+ "files": [
16
+ "dist",
17
+ "README.md"
18
+ ],
19
+ "scripts": {
20
+ "build": "tsc -p tsconfig.json",
21
+ "typecheck": "tsc -p tsconfig.json --noEmit"
22
+ },
23
+ "devDependencies": {
24
+ "typescript": "^5.6.2"
25
+ },
26
+ "keywords": [
27
+ "adviverse",
28
+ "ads",
29
+ "desktop",
30
+ "tauri",
31
+ "webview",
32
+ "electron"
33
+ ]
34
+ }