@gravity-ai/api 1.4.0 → 1.6.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
@@ -302,6 +302,51 @@ if (ad) {
302
302
 
303
303
  ---
304
304
 
305
+ ## Gravity Index
306
+
307
+ Use `gravity.index` on an existing `Gravity` instance, or instantiate `GravityIndex` standalone to search developer services (`POST /search`) and consumer products (`POST /shop/search`).
308
+
309
+ ```ts
310
+ import { Gravity, GravityIndex, isDeveloperSearchResponse } from '@gravity-ai/api';
311
+
312
+ // Via existing Gravity client (shares apiKey):
313
+ const gravity = new Gravity({ production: true });
314
+ const res = await gravity.index.search({
315
+ query: 'serverless Postgres database with a free tier',
316
+ user_ip: '203.0.113.7', // real end-user IP for hosted servers (fallback: GRAVITY_INDEX_USER_IP || 'caller')
317
+ session_id: 'chat_8f3a',
318
+ email: 'alice@example.com', // SHA-256 hashed locally into hashed_email; never sent raw
319
+ user_agent: req.headers['user-agent'], // automatically capped at 1024 chars
320
+ country: 'US',
321
+ external_user_id_hash: 'sha256_user_id',
322
+ });
323
+
324
+ if (res.ok && isDeveloperSearchResponse(res.data)) {
325
+ console.log(res.data.recommendation?.name, res.data.click_url);
326
+ }
327
+
328
+ // Or standalone (reads GRAVITY_PUBLISHER_KEY || GRAVITY_API_KEY):
329
+ const index = new GravityIndex();
330
+ const products = await index.shopSearch({
331
+ query: 'running shoes for wide feet',
332
+ user_ip: '203.0.113.7',
333
+ session_id: 'chat_8f3a',
334
+ price_max: 150,
335
+ max_results: 3,
336
+ });
337
+ ```
338
+
339
+ Every method resolves to `IndexResult<T>` (`{ ok, data, status, elapsed, error?, retryAfterSeconds? }`) and never throws.
340
+
341
+ | Method | Endpoint | Purpose |
342
+ |--------|----------|---------|
343
+ | `search(params)` | `POST /search` | Recommend a developer service (or consumer products with `vertical: 'consumer'` / `filters`) |
344
+ | `shopSearch(params)` | `POST /shop/search` | Search consumer products with structured filters and facets |
345
+
346
+ **End-user context (CPM payouts & geo targeting):** Hosted servers should pass the end user's real `user_ip` (falls back to `GRAVITY_INDEX_USER_IP`, else `'caller'`), `session_id`, `user_agent` (capped at 1,024 chars), `hashed_email` (or raw `email`, which is trimmed, lowercased, and SHA-256 hashed locally and never transmitted raw), `external_user_id_hash`, and `country` (ISO 3166-1 alpha-2 on `search`).
347
+
348
+ ---
349
+
305
350
  ## License
306
351
 
307
352
  MIT
package/dist/index.d.mts CHANGED
@@ -1,5 +1,55 @@
1
- import { G as GravityAdsOptions, I as IncomingAdRequest, M as MessageObject, P as PlacementObject, a as GravityAdsResult, b as GravityContextOverrides, c as GravityContext, A as AdParams, d as Ad } from './types-C20oXLJd.mjs';
2
- export { e as AdAction, f as AdLayout, g as AdUnit, h as ApiErrorResponse, D as DeviceObject, F as FrameSize, i as Gender, H as HostTheme, L as LeadFormConfig, j as LeadFormField, k as LeadFormPrefill, l as McpConnect, m as McpConnectHandler, n as McpConnectRequest, o as McpConnectResult, p as ModelUsage, q as Placement, r as PromptAction, R as RenderEnvelope, s as Role, S as SlotSize, T as TextMetrics, U as UnitCapability, t as UnknownAdAction, u as UserObject } from './types-C20oXLJd.mjs';
1
+ import { G as GravityIndexOptions, I as IndexSearchParams, a as IndexRequestOptions, b as IndexResult, c as IndexSearchResponse, d as IndexShopSearchParams, e as IndexShopSearchResponse, f as IndexDeveloperSearchResponse, g as GravityOptions, h as IncomingAdRequest, M as MessageObject, P as PlacementObject, i as GravityAdsOptions, j as GravityAdsResult, k as GravityContextOverrides, l as GravityContext, A as AdParams, m as Ad } from './types-DlHD2n-z.mjs';
2
+ export { n as AdAction, o as AdLayout, p as AdUnit, q as ApiErrorResponse, D as DeviceObject, F as FrameSize, r as Gender, H as HostTheme, s as IndexAlternative, t as IndexContextMessage, u as IndexCredentialRequest, v as IndexGender, w as IndexInstallInstructions, x as IndexInstallStep, y as IndexMcpConnect, z as IndexMonetization, B as IndexMppCheckout, C as IndexPriceRange, E as IndexProduct, J as IndexRecommendation, K as IndexSearchContext, L as IndexSearchOption, N as IndexShopFacets, O as IndexShopFilters, Q as IndexUcpCheckout, R as IndexVertical, S as IndexWebResult, T as LeadFormConfig, U as LeadFormField, V as LeadFormPrefill, W as McpConnect, X as McpConnectHandler, Y as McpConnectRequest, Z as McpConnectResult, _ as ModelUsage, $ as Placement, a0 as PromptAction, a1 as RenderEnvelope, a2 as Role, a3 as SlotSize, a4 as TextMetrics, a5 as UnitCapability, a6 as UnknownAdAction, a7 as UserObject } from './types-DlHD2n-z.mjs';
3
+
4
+ declare const DEFAULT_INDEX_URL = "https://index.trygravity.com";
5
+ declare const DEFAULT_INDEX_TIMEOUT_MS = 30000;
6
+ /** Type guard: checks whether a `search()` payload is a consumer product response. */
7
+ declare function isConsumerSearchResponse(response: IndexSearchResponse | null | undefined): response is IndexShopSearchResponse;
8
+ /** Type guard: checks whether a `search()` payload is a developer service response. */
9
+ declare function isDeveloperSearchResponse(response: IndexSearchResponse | null | undefined): response is IndexDeveloperSearchResponse;
10
+ /**
11
+ * Client for the Gravity Index search APIs (`POST /search` and `POST /shop/search`).
12
+ *
13
+ * Every method resolves to `IndexResult<T>` and **never throws**.
14
+ *
15
+ * @example
16
+ * ```ts
17
+ * import { GravityIndex, isDeveloperSearchResponse } from '@gravity-ai/api';
18
+ *
19
+ * const index = new GravityIndex(); // reads GRAVITY_PUBLISHER_KEY or GRAVITY_API_KEY
20
+ *
21
+ * const res = await index.search({
22
+ * query: 'serverless Postgres database with a free tier',
23
+ * user_ip: '203.0.113.7',
24
+ * session_id: 'chat_8f3a',
25
+ * email: 'alice@example.com', // SHA-256 hashed locally; never sent raw
26
+ * });
27
+ * if (res.ok && isDeveloperSearchResponse(res.data)) {
28
+ * console.log(res.data.recommendation?.name, res.data.click_url);
29
+ * }
30
+ * ```
31
+ */
32
+ declare class GravityIndex {
33
+ private readonly opts;
34
+ constructor(opts?: GravityIndexOptions);
35
+ private resolveApiKey;
36
+ private resolveIndexUrl;
37
+ private post;
38
+ /**
39
+ * Search the Gravity Index for the best developer service (or consumer
40
+ * products when `vertical: 'consumer'` or `filters` are provided).
41
+ *
42
+ * `POST /search`
43
+ */
44
+ search(params: IndexSearchParams, overrides?: IndexRequestOptions): Promise<IndexResult<IndexSearchResponse>>;
45
+ /**
46
+ * Search consumer products that a user can buy, with optional structured
47
+ * filters (brand, merchant, price range, sale status, etc.).
48
+ *
49
+ * `POST /shop/search`
50
+ */
51
+ shopSearch(params: IndexShopSearchParams, overrides?: IndexRequestOptions): Promise<IndexResult<IndexShopSearchResponse>>;
52
+ }
3
53
 
4
54
  /**
5
55
  * Gravity ad client.
@@ -30,8 +80,9 @@ export { e as AdAction, f as AdLayout, g as AdUnit, h as ApiErrorResponse, D as
30
80
  */
31
81
  declare class Gravity {
32
82
  private opts;
83
+ private indexClient?;
33
84
  /**
34
- * @param opts - Configuration applied to every `getAds()` call.
85
+ * @param opts - Configuration applied to every `getAds()` call and `gravity.index`.
35
86
  *
36
87
  * | Option | Type | Default | Description |
37
88
  * |--------|------|---------|-------------|
@@ -42,8 +93,14 @@ declare class Gravity {
42
93
  * | `timeoutMs` | `number` | `4000` | Request timeout in ms |
43
94
  * | `excludedTopics` | `string[]` | — | Topics to exclude from ad matching |
44
95
  * | `gravityApi` | `string` | production URL | Custom API endpoint |
96
+ * | `index` | `GravityIndexOptions` | — | Optional Gravity Index client overrides |
45
97
  */
46
- constructor(opts?: GravityAdsOptions);
98
+ constructor(opts?: GravityOptions);
99
+ /**
100
+ * Gravity Index client sharing this instance's API key (plus any `opts.index`
101
+ * overrides).
102
+ */
103
+ get index(): GravityIndex;
47
104
  /**
48
105
  * Fetch ads from the Gravity API. **Never throws.**
49
106
  *
@@ -371,6 +428,10 @@ declare function hashPii(values: RawIdentity): Promise<HashedIdentity>;
371
428
  *
372
429
  * - TCF v2: `window.__tcfapi(command, version, callback)`
373
430
  * - US Privacy (CCPA): `window.__uspapi(command, version, callback)`
431
+ * - GPP v1.1: `window.__gpp(command, callback, parameter, version)`
432
+ *
433
+ * It also reads the browser's Global Privacy Control signal
434
+ * (`navigator.globalPrivacyControl`).
374
435
  *
375
436
  * This module reads those APIs (when present) and shapes the result into the
376
437
  * `consent` object the Gravity ad API accepts, so consent collected by the
@@ -385,6 +446,12 @@ interface ConsentSignal {
385
446
  tcfString?: string;
386
447
  /** IAB US Privacy (CCPA) string, e.g. `"1YNN"`. */
387
448
  usPrivacy?: string;
449
+ /** IAB Global Privacy Platform (GPP) string from the publisher's CMP. */
450
+ gpp?: string;
451
+ /** GPP section ids that apply to this request (`applicableSections`). */
452
+ gppSid?: number[];
453
+ /** Global Privacy Control. Only `true` is a signal; omit it otherwise. */
454
+ gpc?: boolean;
388
455
  }
389
456
  /**
390
457
  * Synchronously return the current CMP consent signal, or `undefined` when
@@ -506,5 +573,5 @@ declare class GravityPixel {
506
573
  */
507
574
  declare function gravityPixel(opts: GravityPixelConfig): GravityPixel;
508
575
 
509
- export { Ad, AdParams, Client, Gravity, GravityAdsOptions, GravityAdsResult, GravityContext, GravityContextOverrides, GravityPixel, IncomingAdRequest, MessageObject, PlacementObject, detectCmpConsent, extractClientIp, gravityAds, gravityContext, gravityContextAsync, gravityPixel, hashPii, readCmpConsent, toGravityMessages };
576
+ export { Ad, AdParams, Client, DEFAULT_INDEX_TIMEOUT_MS, DEFAULT_INDEX_URL, Gravity, GravityAdsOptions, GravityAdsResult, GravityContext, GravityContextOverrides, GravityIndex, GravityIndexOptions, GravityOptions, GravityPixel, IncomingAdRequest, IndexDeveloperSearchResponse, IndexRequestOptions, IndexResult, IndexSearchParams, IndexSearchResponse, IndexShopSearchParams, IndexShopSearchResponse, MessageObject, PlacementObject, detectCmpConsent, extractClientIp, gravityAds, gravityContext, gravityContextAsync, gravityPixel, hashPii, isConsumerSearchResponse, isDeveloperSearchResponse, readCmpConsent, toGravityMessages };
510
577
  export type { ClientParams, ConsentSignal, GravityPixelConfig, HashedIdentity, RawIdentity };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,55 @@
1
- import { G as GravityAdsOptions, I as IncomingAdRequest, M as MessageObject, P as PlacementObject, a as GravityAdsResult, b as GravityContextOverrides, c as GravityContext, A as AdParams, d as Ad } from './types-C20oXLJd.js';
2
- export { e as AdAction, f as AdLayout, g as AdUnit, h as ApiErrorResponse, D as DeviceObject, F as FrameSize, i as Gender, H as HostTheme, L as LeadFormConfig, j as LeadFormField, k as LeadFormPrefill, l as McpConnect, m as McpConnectHandler, n as McpConnectRequest, o as McpConnectResult, p as ModelUsage, q as Placement, r as PromptAction, R as RenderEnvelope, s as Role, S as SlotSize, T as TextMetrics, U as UnitCapability, t as UnknownAdAction, u as UserObject } from './types-C20oXLJd.js';
1
+ import { G as GravityIndexOptions, I as IndexSearchParams, a as IndexRequestOptions, b as IndexResult, c as IndexSearchResponse, d as IndexShopSearchParams, e as IndexShopSearchResponse, f as IndexDeveloperSearchResponse, g as GravityOptions, h as IncomingAdRequest, M as MessageObject, P as PlacementObject, i as GravityAdsOptions, j as GravityAdsResult, k as GravityContextOverrides, l as GravityContext, A as AdParams, m as Ad } from './types-DlHD2n-z.js';
2
+ export { n as AdAction, o as AdLayout, p as AdUnit, q as ApiErrorResponse, D as DeviceObject, F as FrameSize, r as Gender, H as HostTheme, s as IndexAlternative, t as IndexContextMessage, u as IndexCredentialRequest, v as IndexGender, w as IndexInstallInstructions, x as IndexInstallStep, y as IndexMcpConnect, z as IndexMonetization, B as IndexMppCheckout, C as IndexPriceRange, E as IndexProduct, J as IndexRecommendation, K as IndexSearchContext, L as IndexSearchOption, N as IndexShopFacets, O as IndexShopFilters, Q as IndexUcpCheckout, R as IndexVertical, S as IndexWebResult, T as LeadFormConfig, U as LeadFormField, V as LeadFormPrefill, W as McpConnect, X as McpConnectHandler, Y as McpConnectRequest, Z as McpConnectResult, _ as ModelUsage, $ as Placement, a0 as PromptAction, a1 as RenderEnvelope, a2 as Role, a3 as SlotSize, a4 as TextMetrics, a5 as UnitCapability, a6 as UnknownAdAction, a7 as UserObject } from './types-DlHD2n-z.js';
3
+
4
+ declare const DEFAULT_INDEX_URL = "https://index.trygravity.com";
5
+ declare const DEFAULT_INDEX_TIMEOUT_MS = 30000;
6
+ /** Type guard: checks whether a `search()` payload is a consumer product response. */
7
+ declare function isConsumerSearchResponse(response: IndexSearchResponse | null | undefined): response is IndexShopSearchResponse;
8
+ /** Type guard: checks whether a `search()` payload is a developer service response. */
9
+ declare function isDeveloperSearchResponse(response: IndexSearchResponse | null | undefined): response is IndexDeveloperSearchResponse;
10
+ /**
11
+ * Client for the Gravity Index search APIs (`POST /search` and `POST /shop/search`).
12
+ *
13
+ * Every method resolves to `IndexResult<T>` and **never throws**.
14
+ *
15
+ * @example
16
+ * ```ts
17
+ * import { GravityIndex, isDeveloperSearchResponse } from '@gravity-ai/api';
18
+ *
19
+ * const index = new GravityIndex(); // reads GRAVITY_PUBLISHER_KEY or GRAVITY_API_KEY
20
+ *
21
+ * const res = await index.search({
22
+ * query: 'serverless Postgres database with a free tier',
23
+ * user_ip: '203.0.113.7',
24
+ * session_id: 'chat_8f3a',
25
+ * email: 'alice@example.com', // SHA-256 hashed locally; never sent raw
26
+ * });
27
+ * if (res.ok && isDeveloperSearchResponse(res.data)) {
28
+ * console.log(res.data.recommendation?.name, res.data.click_url);
29
+ * }
30
+ * ```
31
+ */
32
+ declare class GravityIndex {
33
+ private readonly opts;
34
+ constructor(opts?: GravityIndexOptions);
35
+ private resolveApiKey;
36
+ private resolveIndexUrl;
37
+ private post;
38
+ /**
39
+ * Search the Gravity Index for the best developer service (or consumer
40
+ * products when `vertical: 'consumer'` or `filters` are provided).
41
+ *
42
+ * `POST /search`
43
+ */
44
+ search(params: IndexSearchParams, overrides?: IndexRequestOptions): Promise<IndexResult<IndexSearchResponse>>;
45
+ /**
46
+ * Search consumer products that a user can buy, with optional structured
47
+ * filters (brand, merchant, price range, sale status, etc.).
48
+ *
49
+ * `POST /shop/search`
50
+ */
51
+ shopSearch(params: IndexShopSearchParams, overrides?: IndexRequestOptions): Promise<IndexResult<IndexShopSearchResponse>>;
52
+ }
3
53
 
4
54
  /**
5
55
  * Gravity ad client.
@@ -30,8 +80,9 @@ export { e as AdAction, f as AdLayout, g as AdUnit, h as ApiErrorResponse, D as
30
80
  */
31
81
  declare class Gravity {
32
82
  private opts;
83
+ private indexClient?;
33
84
  /**
34
- * @param opts - Configuration applied to every `getAds()` call.
85
+ * @param opts - Configuration applied to every `getAds()` call and `gravity.index`.
35
86
  *
36
87
  * | Option | Type | Default | Description |
37
88
  * |--------|------|---------|-------------|
@@ -42,8 +93,14 @@ declare class Gravity {
42
93
  * | `timeoutMs` | `number` | `4000` | Request timeout in ms |
43
94
  * | `excludedTopics` | `string[]` | — | Topics to exclude from ad matching |
44
95
  * | `gravityApi` | `string` | production URL | Custom API endpoint |
96
+ * | `index` | `GravityIndexOptions` | — | Optional Gravity Index client overrides |
45
97
  */
46
- constructor(opts?: GravityAdsOptions);
98
+ constructor(opts?: GravityOptions);
99
+ /**
100
+ * Gravity Index client sharing this instance's API key (plus any `opts.index`
101
+ * overrides).
102
+ */
103
+ get index(): GravityIndex;
47
104
  /**
48
105
  * Fetch ads from the Gravity API. **Never throws.**
49
106
  *
@@ -371,6 +428,10 @@ declare function hashPii(values: RawIdentity): Promise<HashedIdentity>;
371
428
  *
372
429
  * - TCF v2: `window.__tcfapi(command, version, callback)`
373
430
  * - US Privacy (CCPA): `window.__uspapi(command, version, callback)`
431
+ * - GPP v1.1: `window.__gpp(command, callback, parameter, version)`
432
+ *
433
+ * It also reads the browser's Global Privacy Control signal
434
+ * (`navigator.globalPrivacyControl`).
374
435
  *
375
436
  * This module reads those APIs (when present) and shapes the result into the
376
437
  * `consent` object the Gravity ad API accepts, so consent collected by the
@@ -385,6 +446,12 @@ interface ConsentSignal {
385
446
  tcfString?: string;
386
447
  /** IAB US Privacy (CCPA) string, e.g. `"1YNN"`. */
387
448
  usPrivacy?: string;
449
+ /** IAB Global Privacy Platform (GPP) string from the publisher's CMP. */
450
+ gpp?: string;
451
+ /** GPP section ids that apply to this request (`applicableSections`). */
452
+ gppSid?: number[];
453
+ /** Global Privacy Control. Only `true` is a signal; omit it otherwise. */
454
+ gpc?: boolean;
388
455
  }
389
456
  /**
390
457
  * Synchronously return the current CMP consent signal, or `undefined` when
@@ -506,5 +573,5 @@ declare class GravityPixel {
506
573
  */
507
574
  declare function gravityPixel(opts: GravityPixelConfig): GravityPixel;
508
575
 
509
- export { Ad, AdParams, Client, Gravity, GravityAdsOptions, GravityAdsResult, GravityContext, GravityContextOverrides, GravityPixel, IncomingAdRequest, MessageObject, PlacementObject, detectCmpConsent, extractClientIp, gravityAds, gravityContext, gravityContextAsync, gravityPixel, hashPii, readCmpConsent, toGravityMessages };
576
+ export { Ad, AdParams, Client, DEFAULT_INDEX_TIMEOUT_MS, DEFAULT_INDEX_URL, Gravity, GravityAdsOptions, GravityAdsResult, GravityContext, GravityContextOverrides, GravityIndex, GravityIndexOptions, GravityOptions, GravityPixel, IncomingAdRequest, IndexDeveloperSearchResponse, IndexRequestOptions, IndexResult, IndexSearchParams, IndexSearchResponse, IndexShopSearchParams, IndexShopSearchResponse, MessageObject, PlacementObject, detectCmpConsent, extractClientIp, gravityAds, gravityContext, gravityContextAsync, gravityPixel, hashPii, isConsumerSearchResponse, isDeveloperSearchResponse, readCmpConsent, toGravityMessages };
510
577
  export type { ClientParams, ConsentSignal, GravityPixelConfig, HashedIdentity, RawIdentity };