@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 +45 -0
- package/dist/index.d.mts +72 -5
- package/dist/index.d.ts +72 -5
- package/dist/index.js +515 -46
- package/dist/index.mjs +510 -46
- package/dist/opentui.js +1 -1
- package/dist/opentui.mjs +1 -1
- package/dist/{types-C20oXLJd.d.mts → types-DlHD2n-z.d.mts} +351 -5
- package/dist/{types-C20oXLJd.d.ts → types-DlHD2n-z.d.ts} +351 -5
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -39,7 +39,7 @@ var require_package = __commonJS({
|
|
|
39
39
|
"package.json"(exports2, module2) {
|
|
40
40
|
module2.exports = {
|
|
41
41
|
name: "@gravity-ai/api",
|
|
42
|
-
version: "1.
|
|
42
|
+
version: "1.6.0",
|
|
43
43
|
description: "Gravity JS SDK for retrieving targeted advertisements",
|
|
44
44
|
main: "dist/index.js",
|
|
45
45
|
module: "dist/index.mjs",
|
|
@@ -117,7 +117,10 @@ var require_package = __commonJS({
|
|
|
117
117
|
var index_exports = {};
|
|
118
118
|
__export(index_exports, {
|
|
119
119
|
Client: () => Client,
|
|
120
|
+
DEFAULT_INDEX_TIMEOUT_MS: () => DEFAULT_INDEX_TIMEOUT_MS,
|
|
121
|
+
DEFAULT_INDEX_URL: () => DEFAULT_INDEX_URL,
|
|
120
122
|
Gravity: () => Gravity,
|
|
123
|
+
GravityIndex: () => GravityIndex,
|
|
121
124
|
GravityPixel: () => GravityPixel,
|
|
122
125
|
detectCmpConsent: () => detectCmpConsent,
|
|
123
126
|
extractClientIp: () => extractClientIp,
|
|
@@ -126,6 +129,8 @@ __export(index_exports, {
|
|
|
126
129
|
gravityContextAsync: () => gravityContextAsync,
|
|
127
130
|
gravityPixel: () => gravityPixel,
|
|
128
131
|
hashPii: () => hashPii,
|
|
132
|
+
isConsumerSearchResponse: () => isConsumerSearchResponse,
|
|
133
|
+
isDeveloperSearchResponse: () => isDeveloperSearchResponse,
|
|
129
134
|
readCmpConsent: () => readCmpConsent,
|
|
130
135
|
toGravityMessages: () => toGravityMessages
|
|
131
136
|
});
|
|
@@ -141,6 +146,195 @@ var pkg = (() => {
|
|
|
141
146
|
})();
|
|
142
147
|
var SDK = { name: pkg.name, version: pkg.version };
|
|
143
148
|
|
|
149
|
+
// ../ui/src/psp.ts
|
|
150
|
+
var SPEC_LINK_PROTOCOLS = ["http:", "https:", "mailto:"];
|
|
151
|
+
var SHADCN_CHANNEL_DEFAULTS = {
|
|
152
|
+
background: "0 0% 100%",
|
|
153
|
+
foreground: "240 6% 10%",
|
|
154
|
+
card: "0 0% 100%",
|
|
155
|
+
"card-foreground": "240 6% 10%",
|
|
156
|
+
primary: "221 83% 53%",
|
|
157
|
+
"primary-foreground": "0 0% 100%",
|
|
158
|
+
muted: "240 5% 96%",
|
|
159
|
+
"muted-foreground": "240 5% 47%",
|
|
160
|
+
accent: "221 83% 53%",
|
|
161
|
+
"accent-foreground": "0 0% 100%",
|
|
162
|
+
border: "240 5% 90%"
|
|
163
|
+
};
|
|
164
|
+
var SHADCN_HOST_TOKENS = Object.keys(SHADCN_CHANNEL_DEFAULTS);
|
|
165
|
+
var PSP1_COLOR_TOKENS = [
|
|
166
|
+
"background",
|
|
167
|
+
"foreground",
|
|
168
|
+
"card",
|
|
169
|
+
"card-foreground",
|
|
170
|
+
"primary",
|
|
171
|
+
"primary-foreground",
|
|
172
|
+
"muted",
|
|
173
|
+
"muted-foreground",
|
|
174
|
+
"accent",
|
|
175
|
+
"accent-foreground",
|
|
176
|
+
"border"
|
|
177
|
+
];
|
|
178
|
+
var PSP1_MAX_FONT_SIZE_PX = 20;
|
|
179
|
+
var PSP1_MAX_SPACING_PX = 32;
|
|
180
|
+
var PSP1_MAX_IMAGE_PX = 64;
|
|
181
|
+
var ok = null;
|
|
182
|
+
function err(msg) {
|
|
183
|
+
return msg;
|
|
184
|
+
}
|
|
185
|
+
var PX_RE = /^\d+(\.\d+)?px$/;
|
|
186
|
+
var PX_LIST_RE = /^\d+(\.\d+)?px( \d+(\.\d+)?px){0,3}$/;
|
|
187
|
+
var EM_RE = /^-?\d+(\.\d+)?em$/;
|
|
188
|
+
var TOKEN_RE = new RegExp(
|
|
189
|
+
`^\\$(${PSP1_COLOR_TOKENS.join("|")})(/(100|[1-9]?[0-9]))?$`
|
|
190
|
+
);
|
|
191
|
+
function pxNumber(value) {
|
|
192
|
+
if (typeof value === "number") return value >= 0 ? value : null;
|
|
193
|
+
if (typeof value === "string" && PX_RE.test(value)) return parseFloat(value);
|
|
194
|
+
return null;
|
|
195
|
+
}
|
|
196
|
+
function ruleColor(value) {
|
|
197
|
+
if (typeof value !== "string") return err("color must be a string");
|
|
198
|
+
if (value === "transparent" || TOKEN_RE.test(value)) return ok;
|
|
199
|
+
return err(`color must be "transparent" or a $token, got "${value}"`);
|
|
200
|
+
}
|
|
201
|
+
function rulePx(cap) {
|
|
202
|
+
return (value) => {
|
|
203
|
+
const px2 = pxNumber(value);
|
|
204
|
+
if (px2 === null) return err(`must be a px value, got "${value}"`);
|
|
205
|
+
if (px2 > cap) return err(`exceeds ${cap}px cap (${px2}px)`);
|
|
206
|
+
return ok;
|
|
207
|
+
};
|
|
208
|
+
}
|
|
209
|
+
function rulePxList(cap) {
|
|
210
|
+
return (value) => {
|
|
211
|
+
if (typeof value === "number") {
|
|
212
|
+
if (value < 0) return err(`must not be negative (${value}px)`);
|
|
213
|
+
return value <= cap ? ok : err(`exceeds ${cap}px cap (${value}px)`);
|
|
214
|
+
}
|
|
215
|
+
if (typeof value !== "string" || !PX_LIST_RE.test(value)) {
|
|
216
|
+
return err(`must be 1-4 px values, got "${value}"`);
|
|
217
|
+
}
|
|
218
|
+
for (const part of value.split(" ")) {
|
|
219
|
+
if (parseFloat(part) > cap) {
|
|
220
|
+
return err(`exceeds ${cap}px cap ("${value}")`);
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
return ok;
|
|
224
|
+
};
|
|
225
|
+
}
|
|
226
|
+
function ruleEnum(...allowed) {
|
|
227
|
+
return (value) => allowed.includes(value) ? ok : err(`must be one of ${allowed.join("|")}, got "${value}"`);
|
|
228
|
+
}
|
|
229
|
+
var ruleDimension = (value, node) => {
|
|
230
|
+
if (value === "100%") return ok;
|
|
231
|
+
const px2 = pxNumber(value);
|
|
232
|
+
if (px2 === null) return err(`must be px or "100%", got "${value}"`);
|
|
233
|
+
if (node.type === "image" && px2 > PSP1_MAX_IMAGE_PX) {
|
|
234
|
+
return err(`image dimension exceeds ${PSP1_MAX_IMAGE_PX}px cap (${px2}px)`);
|
|
235
|
+
}
|
|
236
|
+
return ok;
|
|
237
|
+
};
|
|
238
|
+
var ruleRadius = (value) => {
|
|
239
|
+
if (value === "full" || value === "$radius") return ok;
|
|
240
|
+
const px2 = pxNumber(value);
|
|
241
|
+
if (px2 === null) {
|
|
242
|
+
return err(`must be px, "full", or "$radius", got "${value}"`);
|
|
243
|
+
}
|
|
244
|
+
return ok;
|
|
245
|
+
};
|
|
246
|
+
var ruleBorder = (value) => {
|
|
247
|
+
if (typeof value !== "string") return err("border must be a string");
|
|
248
|
+
const m = value.match(/^1px solid (\$\S+)$/);
|
|
249
|
+
if (!m || ruleColor(m[1]) !== null) {
|
|
250
|
+
return err(`must be "1px solid $token", got "${value}"`);
|
|
251
|
+
}
|
|
252
|
+
return ok;
|
|
253
|
+
};
|
|
254
|
+
var ruleLineHeight = (value) => {
|
|
255
|
+
if (typeof value === "boolean") return err("must be a number");
|
|
256
|
+
const n = typeof value === "number" ? value : parseFloat(value);
|
|
257
|
+
if (typeof value === "string" && !/^\d+(\.\d+)?$/.test(value)) {
|
|
258
|
+
return err(`must be a unitless multiplier, got "${value}"`);
|
|
259
|
+
}
|
|
260
|
+
if (Number.isNaN(n) || n < 1 || n > 2) {
|
|
261
|
+
return err(`must be a unitless multiplier in [1, 2], got "${value}"`);
|
|
262
|
+
}
|
|
263
|
+
return ok;
|
|
264
|
+
};
|
|
265
|
+
var ruleOpacity = (value) => {
|
|
266
|
+
if (typeof value === "boolean") return err("must be a number");
|
|
267
|
+
if (typeof value === "string" && !/^\d+(\.\d+)?$/.test(value)) {
|
|
268
|
+
return err(`must be a unitless number, got "${value}"`);
|
|
269
|
+
}
|
|
270
|
+
const n = typeof value === "number" ? value : parseFloat(value);
|
|
271
|
+
if (Number.isNaN(n) || n < 0 || n > 1) {
|
|
272
|
+
return err(`must be in [0, 1], got "${value}"`);
|
|
273
|
+
}
|
|
274
|
+
return ok;
|
|
275
|
+
};
|
|
276
|
+
var ruleMaxLines = (value) => {
|
|
277
|
+
if (typeof value === "boolean") return err("must be an integer");
|
|
278
|
+
if (typeof value === "string" && !/^\d+$/.test(value)) {
|
|
279
|
+
return err(`must be an integer, got "${value}"`);
|
|
280
|
+
}
|
|
281
|
+
const n = typeof value === "number" ? value : parseInt(value, 10);
|
|
282
|
+
if (!Number.isInteger(n) || n < 1 || n > 10) {
|
|
283
|
+
return err(`must be an integer in [1, 10], got "${value}"`);
|
|
284
|
+
}
|
|
285
|
+
return ok;
|
|
286
|
+
};
|
|
287
|
+
var ruleLetterSpacing = (value) => {
|
|
288
|
+
if (typeof value === "string" && EM_RE.test(value)) return ok;
|
|
289
|
+
return err(`must be an em value, got "${value}"`);
|
|
290
|
+
};
|
|
291
|
+
var ruleBool = (value) => value === true || value === false ? ok : err(`must be a boolean, got "${value}"`);
|
|
292
|
+
var PSP1_STYLE_RULES = {
|
|
293
|
+
// Layout
|
|
294
|
+
direction: ruleEnum("row", "column"),
|
|
295
|
+
gap: rulePx(PSP1_MAX_SPACING_PX),
|
|
296
|
+
align: ruleEnum("start", "center", "end", "baseline"),
|
|
297
|
+
justify: ruleEnum("start", "center", "end", "space-between"),
|
|
298
|
+
grow: ruleEnum(0, 1),
|
|
299
|
+
shrink: ruleEnum(0, 1),
|
|
300
|
+
spacerBefore: ruleBool,
|
|
301
|
+
// Box
|
|
302
|
+
padding: rulePxList(PSP1_MAX_SPACING_PX),
|
|
303
|
+
paddingTop: rulePx(PSP1_MAX_SPACING_PX),
|
|
304
|
+
paddingRight: rulePx(PSP1_MAX_SPACING_PX),
|
|
305
|
+
paddingBottom: rulePx(PSP1_MAX_SPACING_PX),
|
|
306
|
+
paddingLeft: rulePx(PSP1_MAX_SPACING_PX),
|
|
307
|
+
margin: rulePxList(PSP1_MAX_SPACING_PX),
|
|
308
|
+
marginTop: rulePx(PSP1_MAX_SPACING_PX),
|
|
309
|
+
marginRight: rulePx(PSP1_MAX_SPACING_PX),
|
|
310
|
+
marginBottom: rulePx(PSP1_MAX_SPACING_PX),
|
|
311
|
+
marginLeft: rulePx(PSP1_MAX_SPACING_PX),
|
|
312
|
+
width: ruleDimension,
|
|
313
|
+
height: ruleDimension,
|
|
314
|
+
maxWidth: rulePx(Infinity),
|
|
315
|
+
minWidth: (value) => value === 0 || value === "0" || pxNumber(value) !== null ? ok : err(`must be 0 or px, got "${value}"`),
|
|
316
|
+
// Surface
|
|
317
|
+
background: ruleColor,
|
|
318
|
+
border: ruleBorder,
|
|
319
|
+
borderRadius: ruleRadius,
|
|
320
|
+
elevation: ruleEnum("none", "sm", "md"),
|
|
321
|
+
opacity: ruleOpacity,
|
|
322
|
+
// Text
|
|
323
|
+
fontSize: rulePx(PSP1_MAX_FONT_SIZE_PX),
|
|
324
|
+
fontWeight: ruleEnum(400, 500, 600, 700, 800),
|
|
325
|
+
lineHeight: ruleLineHeight,
|
|
326
|
+
letterSpacing: ruleLetterSpacing,
|
|
327
|
+
color: ruleColor,
|
|
328
|
+
textTransform: ruleEnum("none", "uppercase"),
|
|
329
|
+
textDecoration: ruleEnum("none", "underline"),
|
|
330
|
+
textAlign: ruleEnum("left", "center", "right"),
|
|
331
|
+
maxLines: ruleMaxLines,
|
|
332
|
+
nowrap: ruleBool,
|
|
333
|
+
// Image
|
|
334
|
+
fit: ruleEnum("contain", "cover")
|
|
335
|
+
};
|
|
336
|
+
var ALLOWED_URL_PROTOCOLS = SPEC_LINK_PROTOCOLS.map((p) => p.slice(0, -1));
|
|
337
|
+
|
|
144
338
|
// ../ui/src/theme.ts
|
|
145
339
|
var GRAVITY_DARK_VARS = {
|
|
146
340
|
"--gravity-bg": "#1F1F23",
|
|
@@ -390,17 +584,263 @@ async function gravityAds(req, messages, placements, opts = {}) {
|
|
|
390
584
|
const data = await res.json();
|
|
391
585
|
const ads = Array.isArray(data) ? data : [data];
|
|
392
586
|
return { ads, status: res.status, elapsed, requestBody: body };
|
|
393
|
-
} catch (
|
|
587
|
+
} catch (err2) {
|
|
394
588
|
const elapsed = (performance.now() - start).toFixed(0);
|
|
395
|
-
const error =
|
|
589
|
+
const error = err2 instanceof Error ? err2.name === "TimeoutError" ? `Timeout (${timeoutMs}ms)` : err2.message : String(err2);
|
|
396
590
|
return { ads: [], status: 0, elapsed, error, requestBody: body };
|
|
397
591
|
}
|
|
398
592
|
}
|
|
399
593
|
|
|
594
|
+
// hash.ts
|
|
595
|
+
async function sha256Hex(value) {
|
|
596
|
+
const subtle = typeof globalThis !== "undefined" && globalThis.crypto?.subtle || void 0;
|
|
597
|
+
if (!subtle) return void 0;
|
|
598
|
+
try {
|
|
599
|
+
const bytes = new TextEncoder().encode(value);
|
|
600
|
+
const digest = await subtle.digest("SHA-256", bytes);
|
|
601
|
+
const hex2 = Array.from(new Uint8Array(digest)).map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
602
|
+
return hex2;
|
|
603
|
+
} catch {
|
|
604
|
+
return void 0;
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
function normalizeEmail(raw) {
|
|
608
|
+
if (typeof raw !== "string") return void 0;
|
|
609
|
+
const trimmed = raw.trim().toLowerCase();
|
|
610
|
+
return trimmed || void 0;
|
|
611
|
+
}
|
|
612
|
+
function normalizePhone(raw) {
|
|
613
|
+
if (typeof raw !== "string") return void 0;
|
|
614
|
+
const digits = raw.replace(/\D+/g, "");
|
|
615
|
+
return digits || void 0;
|
|
616
|
+
}
|
|
617
|
+
async function hashPii(values) {
|
|
618
|
+
const out = {};
|
|
619
|
+
const emailNorm = normalizeEmail(values.email ?? void 0);
|
|
620
|
+
const phoneNorm = normalizePhone(values.phone ?? void 0);
|
|
621
|
+
const [hashedEmail, hashedPhone] = await Promise.all([
|
|
622
|
+
emailNorm ? sha256Hex(emailNorm) : Promise.resolve(void 0),
|
|
623
|
+
phoneNorm ? sha256Hex(phoneNorm) : Promise.resolve(void 0)
|
|
624
|
+
]);
|
|
625
|
+
if (hashedEmail) out.hashed_email = hashedEmail;
|
|
626
|
+
if (hashedPhone) out.hashed_phone = hashedPhone;
|
|
627
|
+
return out;
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
// gravity-index.ts
|
|
631
|
+
var DEFAULT_INDEX_URL = "https://index.trygravity.com";
|
|
632
|
+
var DEFAULT_INDEX_TIMEOUT_MS = 3e4;
|
|
633
|
+
var MAX_USER_AGENT_LENGTH = 1024;
|
|
634
|
+
function readEnv(name) {
|
|
635
|
+
return typeof process !== "undefined" ? process.env?.[name] : void 0;
|
|
636
|
+
}
|
|
637
|
+
function stripTrailingSlashes(url) {
|
|
638
|
+
return url.replace(/\/+$/, "");
|
|
639
|
+
}
|
|
640
|
+
function parseRetryAfter(headers) {
|
|
641
|
+
const raw = headers?.get("retry-after");
|
|
642
|
+
if (!raw) return void 0;
|
|
643
|
+
const parsed = Number.parseInt(raw.trim(), 10);
|
|
644
|
+
return Number.isFinite(parsed) && parsed >= 0 ? parsed : void 0;
|
|
645
|
+
}
|
|
646
|
+
function extractErrorMessage(rawText, status) {
|
|
647
|
+
const trimmed = rawText.trim();
|
|
648
|
+
if (!trimmed) return `HTTP ${status}`;
|
|
649
|
+
try {
|
|
650
|
+
const parsed = JSON.parse(trimmed);
|
|
651
|
+
if (parsed && typeof parsed === "object") {
|
|
652
|
+
const record = parsed;
|
|
653
|
+
if (typeof record.detail === "string" && record.detail.trim()) {
|
|
654
|
+
return record.detail;
|
|
655
|
+
}
|
|
656
|
+
if (Array.isArray(record.detail) && record.detail.length > 0) {
|
|
657
|
+
const parts = record.detail.map((item) => {
|
|
658
|
+
if (item && typeof item === "object" && "msg" in item) {
|
|
659
|
+
return String(item.msg);
|
|
660
|
+
}
|
|
661
|
+
return typeof item === "string" ? item : JSON.stringify(item);
|
|
662
|
+
}).filter(Boolean);
|
|
663
|
+
if (parts.length > 0) return parts.join("; ");
|
|
664
|
+
}
|
|
665
|
+
if (typeof record.error === "string" && record.error.trim()) {
|
|
666
|
+
return record.error;
|
|
667
|
+
}
|
|
668
|
+
}
|
|
669
|
+
} catch {
|
|
670
|
+
}
|
|
671
|
+
return trimmed;
|
|
672
|
+
}
|
|
673
|
+
function buildSignal(timeoutMs, externalSignal) {
|
|
674
|
+
if (!externalSignal) {
|
|
675
|
+
return { signal: AbortSignal.timeout(timeoutMs), cleanup: () => {
|
|
676
|
+
} };
|
|
677
|
+
}
|
|
678
|
+
if (typeof AbortSignal.any === "function") {
|
|
679
|
+
return {
|
|
680
|
+
signal: AbortSignal.any([AbortSignal.timeout(timeoutMs), externalSignal]),
|
|
681
|
+
cleanup: () => {
|
|
682
|
+
}
|
|
683
|
+
};
|
|
684
|
+
}
|
|
685
|
+
const controller = new AbortController();
|
|
686
|
+
if (externalSignal.aborted) {
|
|
687
|
+
controller.abort(externalSignal.reason);
|
|
688
|
+
return { signal: controller.signal, cleanup: () => {
|
|
689
|
+
} };
|
|
690
|
+
}
|
|
691
|
+
const onExternalAbort = () => controller.abort(externalSignal.reason);
|
|
692
|
+
externalSignal.addEventListener("abort", onExternalAbort, { once: true });
|
|
693
|
+
const timer = setTimeout(() => {
|
|
694
|
+
const timeoutError = new Error(`Timeout (${timeoutMs}ms)`);
|
|
695
|
+
timeoutError.name = "TimeoutError";
|
|
696
|
+
controller.abort(timeoutError);
|
|
697
|
+
}, timeoutMs);
|
|
698
|
+
return {
|
|
699
|
+
signal: controller.signal,
|
|
700
|
+
cleanup: () => {
|
|
701
|
+
clearTimeout(timer);
|
|
702
|
+
externalSignal.removeEventListener("abort", onExternalAbort);
|
|
703
|
+
}
|
|
704
|
+
};
|
|
705
|
+
}
|
|
706
|
+
async function normalizeUserContext(params, options) {
|
|
707
|
+
const body = {};
|
|
708
|
+
for (const [key, value] of Object.entries(params)) {
|
|
709
|
+
if (value === void 0 || key === "email") continue;
|
|
710
|
+
if (key === "country" && !options.allowCountry) continue;
|
|
711
|
+
body[key] = value;
|
|
712
|
+
}
|
|
713
|
+
const explicitIp = typeof params.user_ip === "string" ? params.user_ip.trim() : "";
|
|
714
|
+
const envIp = readEnv("GRAVITY_INDEX_USER_IP")?.trim() || "";
|
|
715
|
+
body.user_ip = explicitIp || envIp || "caller";
|
|
716
|
+
if (typeof params.user_agent === "string") {
|
|
717
|
+
if (params.user_agent.length > 0) {
|
|
718
|
+
body.user_agent = params.user_agent.slice(0, MAX_USER_AGENT_LENGTH);
|
|
719
|
+
} else {
|
|
720
|
+
delete body.user_agent;
|
|
721
|
+
}
|
|
722
|
+
}
|
|
723
|
+
const explicitHashedEmail = typeof params.hashed_email === "string" ? params.hashed_email.trim() : "";
|
|
724
|
+
if (explicitHashedEmail) {
|
|
725
|
+
body.hashed_email = explicitHashedEmail;
|
|
726
|
+
} else {
|
|
727
|
+
delete body.hashed_email;
|
|
728
|
+
const rawEmail = typeof params.email === "string" ? params.email.trim() : "";
|
|
729
|
+
if (rawEmail) {
|
|
730
|
+
const hashed = await hashPii({ email: rawEmail });
|
|
731
|
+
if (hashed.hashed_email) {
|
|
732
|
+
body.hashed_email = hashed.hashed_email;
|
|
733
|
+
}
|
|
734
|
+
}
|
|
735
|
+
}
|
|
736
|
+
return body;
|
|
737
|
+
}
|
|
738
|
+
function isConsumerSearchResponse(response) {
|
|
739
|
+
return Boolean(response && response.vertical === "consumer");
|
|
740
|
+
}
|
|
741
|
+
function isDeveloperSearchResponse(response) {
|
|
742
|
+
return Boolean(response && response.vertical === "developer");
|
|
743
|
+
}
|
|
744
|
+
var GravityIndex = class {
|
|
745
|
+
constructor(opts = {}) {
|
|
746
|
+
this.opts = opts;
|
|
747
|
+
}
|
|
748
|
+
resolveApiKey(overrides) {
|
|
749
|
+
return (overrides?.apiKey || this.opts.apiKey || readEnv("GRAVITY_PUBLISHER_KEY") || readEnv("GRAVITY_API_KEY") || "").trim();
|
|
750
|
+
}
|
|
751
|
+
resolveIndexUrl() {
|
|
752
|
+
return stripTrailingSlashes(
|
|
753
|
+
this.opts.indexUrl || readEnv("GRAVITY_INDEX_URL") || DEFAULT_INDEX_URL
|
|
754
|
+
);
|
|
755
|
+
}
|
|
756
|
+
async post(path, body, overrides) {
|
|
757
|
+
const apiKey = this.resolveApiKey(overrides);
|
|
758
|
+
if (!apiKey) {
|
|
759
|
+
return {
|
|
760
|
+
ok: false,
|
|
761
|
+
data: null,
|
|
762
|
+
status: 0,
|
|
763
|
+
elapsed: "0",
|
|
764
|
+
error: "Missing Gravity API key (set GRAVITY_PUBLISHER_KEY or GRAVITY_API_KEY, or pass apiKey)"
|
|
765
|
+
};
|
|
766
|
+
}
|
|
767
|
+
const timeoutMs = overrides?.timeoutMs ?? this.opts.timeoutMs ?? DEFAULT_INDEX_TIMEOUT_MS;
|
|
768
|
+
const url = `${this.resolveIndexUrl()}${path}`;
|
|
769
|
+
const start = performance.now();
|
|
770
|
+
const { signal, cleanup } = buildSignal(timeoutMs, overrides?.signal);
|
|
771
|
+
try {
|
|
772
|
+
const res = await fetch(url, {
|
|
773
|
+
method: "POST",
|
|
774
|
+
headers: {
|
|
775
|
+
"Content-Type": "application/json",
|
|
776
|
+
"X-API-Key": apiKey
|
|
777
|
+
},
|
|
778
|
+
body: JSON.stringify(body),
|
|
779
|
+
signal
|
|
780
|
+
});
|
|
781
|
+
const elapsed = (performance.now() - start).toFixed(0);
|
|
782
|
+
const retryAfterSeconds = parseRetryAfter(res.headers);
|
|
783
|
+
if (!res.ok) {
|
|
784
|
+
const errText = await res.text().catch(() => "");
|
|
785
|
+
return {
|
|
786
|
+
ok: false,
|
|
787
|
+
data: null,
|
|
788
|
+
status: res.status,
|
|
789
|
+
elapsed,
|
|
790
|
+
error: extractErrorMessage(errText, res.status),
|
|
791
|
+
...retryAfterSeconds !== void 0 ? { retryAfterSeconds } : {}
|
|
792
|
+
};
|
|
793
|
+
}
|
|
794
|
+
const data = await res.json();
|
|
795
|
+
return {
|
|
796
|
+
ok: true,
|
|
797
|
+
data,
|
|
798
|
+
status: res.status,
|
|
799
|
+
elapsed,
|
|
800
|
+
...retryAfterSeconds !== void 0 ? { retryAfterSeconds } : {}
|
|
801
|
+
};
|
|
802
|
+
} catch (err2) {
|
|
803
|
+
const elapsed = (performance.now() - start).toFixed(0);
|
|
804
|
+
const reason = signal.aborted ? signal.reason : void 0;
|
|
805
|
+
const isTimeout = err2 instanceof Error && err2.name === "TimeoutError" || reason instanceof Error && reason.name === "TimeoutError";
|
|
806
|
+
const error = isTimeout ? `Timeout (${timeoutMs}ms)` : err2 instanceof Error ? err2.message : String(err2);
|
|
807
|
+
return { ok: false, data: null, status: 0, elapsed, error };
|
|
808
|
+
} finally {
|
|
809
|
+
cleanup();
|
|
810
|
+
}
|
|
811
|
+
}
|
|
812
|
+
/**
|
|
813
|
+
* Search the Gravity Index for the best developer service (or consumer
|
|
814
|
+
* products when `vertical: 'consumer'` or `filters` are provided).
|
|
815
|
+
*
|
|
816
|
+
* `POST /search`
|
|
817
|
+
*/
|
|
818
|
+
async search(params, overrides) {
|
|
819
|
+
const body = await normalizeUserContext(
|
|
820
|
+
params,
|
|
821
|
+
{ allowCountry: true }
|
|
822
|
+
);
|
|
823
|
+
return this.post("/search", body, overrides);
|
|
824
|
+
}
|
|
825
|
+
/**
|
|
826
|
+
* Search consumer products that a user can buy, with optional structured
|
|
827
|
+
* filters (brand, merchant, price range, sale status, etc.).
|
|
828
|
+
*
|
|
829
|
+
* `POST /shop/search`
|
|
830
|
+
*/
|
|
831
|
+
async shopSearch(params, overrides) {
|
|
832
|
+
const body = await normalizeUserContext(
|
|
833
|
+
params,
|
|
834
|
+
{ allowCountry: false }
|
|
835
|
+
);
|
|
836
|
+
return this.post("/shop/search", body, overrides);
|
|
837
|
+
}
|
|
838
|
+
};
|
|
839
|
+
|
|
400
840
|
// gravity.ts
|
|
401
841
|
var Gravity = class {
|
|
402
842
|
/**
|
|
403
|
-
* @param opts - Configuration applied to every `getAds()` call.
|
|
843
|
+
* @param opts - Configuration applied to every `getAds()` call and `gravity.index`.
|
|
404
844
|
*
|
|
405
845
|
* | Option | Type | Default | Description |
|
|
406
846
|
* |--------|------|---------|-------------|
|
|
@@ -411,10 +851,24 @@ var Gravity = class {
|
|
|
411
851
|
* | `timeoutMs` | `number` | `4000` | Request timeout in ms |
|
|
412
852
|
* | `excludedTopics` | `string[]` | — | Topics to exclude from ad matching |
|
|
413
853
|
* | `gravityApi` | `string` | production URL | Custom API endpoint |
|
|
854
|
+
* | `index` | `GravityIndexOptions` | — | Optional Gravity Index client overrides |
|
|
414
855
|
*/
|
|
415
856
|
constructor(opts = {}) {
|
|
416
857
|
this.opts = opts;
|
|
417
858
|
}
|
|
859
|
+
/**
|
|
860
|
+
* Gravity Index client sharing this instance's API key (plus any `opts.index`
|
|
861
|
+
* overrides).
|
|
862
|
+
*/
|
|
863
|
+
get index() {
|
|
864
|
+
if (!this.indexClient) {
|
|
865
|
+
this.indexClient = new GravityIndex({
|
|
866
|
+
apiKey: this.opts.apiKey,
|
|
867
|
+
...this.opts.index ?? {}
|
|
868
|
+
});
|
|
869
|
+
}
|
|
870
|
+
return this.indexClient;
|
|
871
|
+
}
|
|
418
872
|
/**
|
|
419
873
|
* Fetch ads from the Gravity API. **Never throws.**
|
|
420
874
|
*
|
|
@@ -429,8 +883,9 @@ var Gravity = class {
|
|
|
429
883
|
* @returns `{ ads, status, elapsed, requestBody, error? }` — always resolves
|
|
430
884
|
*/
|
|
431
885
|
async getAds(req, messages, placements, overrides = {}) {
|
|
886
|
+
const { index: _index, ...adOpts } = this.opts;
|
|
432
887
|
return gravityAds(req, messages, placements, {
|
|
433
|
-
...
|
|
888
|
+
...adOpts,
|
|
434
889
|
...overrides
|
|
435
890
|
});
|
|
436
891
|
}
|
|
@@ -454,7 +909,10 @@ function findCmpApi(name) {
|
|
|
454
909
|
}
|
|
455
910
|
var cachedTcf;
|
|
456
911
|
var cachedUsp;
|
|
912
|
+
var cachedGpp;
|
|
457
913
|
var tcfListening = false;
|
|
914
|
+
var tcfBroken = false;
|
|
915
|
+
var gppListening = false;
|
|
458
916
|
var cmpWaitExhausted = false;
|
|
459
917
|
function ensureListening() {
|
|
460
918
|
if (typeof window === "undefined") return;
|
|
@@ -474,6 +932,21 @@ function ensureListening() {
|
|
|
474
932
|
cachedTcf = { gdprApplies: false };
|
|
475
933
|
}
|
|
476
934
|
});
|
|
935
|
+
} catch {
|
|
936
|
+
tcfBroken = true;
|
|
937
|
+
}
|
|
938
|
+
}
|
|
939
|
+
const gpp = gppListening ? void 0 : findCmpApi("__gpp");
|
|
940
|
+
if (gpp) {
|
|
941
|
+
gppListening = true;
|
|
942
|
+
try {
|
|
943
|
+
gpp("addEventListener", (data, success) => {
|
|
944
|
+
if (!success || typeof data !== "object" || data === null) return;
|
|
945
|
+
cacheGppPing(data.pingData);
|
|
946
|
+
});
|
|
947
|
+
gpp("ping", (data, success) => {
|
|
948
|
+
if (success) cacheGppPing(data);
|
|
949
|
+
});
|
|
477
950
|
} catch {
|
|
478
951
|
}
|
|
479
952
|
}
|
|
@@ -489,13 +962,38 @@ function ensureListening() {
|
|
|
489
962
|
}
|
|
490
963
|
}
|
|
491
964
|
}
|
|
965
|
+
function cacheGppPing(ping) {
|
|
966
|
+
if (typeof ping !== "object" || ping === null) return;
|
|
967
|
+
const p = ping;
|
|
968
|
+
if (p.signalStatus !== "ready") return;
|
|
969
|
+
if (typeof p.gppString !== "string" || !p.gppString) return;
|
|
970
|
+
const raw = Array.isArray(p.applicableSections) ? p.applicableSections : [];
|
|
971
|
+
const readable = raw.every((id) => Number.isInteger(id));
|
|
972
|
+
const sections = readable ? raw.filter((id) => id !== -1) : [];
|
|
973
|
+
cachedGpp = sections.length ? { gpp: p.gppString, gppSid: sections } : { gpp: p.gppString };
|
|
974
|
+
}
|
|
975
|
+
function tcfPending() {
|
|
976
|
+
return !cachedTcf && !tcfBroken && Boolean(findCmpApi("__tcfapi"));
|
|
977
|
+
}
|
|
978
|
+
function cmpSettled() {
|
|
979
|
+
return !tcfPending() && (cachedGpp !== void 0 || !findCmpApi("__gpp"));
|
|
980
|
+
}
|
|
981
|
+
function detectGpc() {
|
|
982
|
+
return typeof navigator !== "undefined" && navigator.globalPrivacyControl === true;
|
|
983
|
+
}
|
|
492
984
|
function detectCmpConsent() {
|
|
493
985
|
ensureListening();
|
|
494
|
-
|
|
986
|
+
const gpc = detectGpc();
|
|
987
|
+
if (!cachedTcf && !cachedUsp && !cachedGpp && !gpc) return void 0;
|
|
495
988
|
const consent = {};
|
|
496
989
|
if (cachedTcf?.gdprApplies !== void 0) consent.gdprApplies = cachedTcf.gdprApplies;
|
|
497
990
|
if (cachedTcf?.tcfString) consent.tcfString = cachedTcf.tcfString;
|
|
498
991
|
if (cachedUsp) consent.usPrivacy = cachedUsp;
|
|
992
|
+
if (cachedGpp && !tcfPending()) {
|
|
993
|
+
consent.gpp = cachedGpp.gpp;
|
|
994
|
+
if (cachedGpp.gppSid) consent.gppSid = [...cachedGpp.gppSid];
|
|
995
|
+
}
|
|
996
|
+
if (gpc) consent.gpc = true;
|
|
499
997
|
if (Object.keys(consent).length === 0) return void 0;
|
|
500
998
|
return consent;
|
|
501
999
|
}
|
|
@@ -505,20 +1003,22 @@ if (typeof window !== "undefined") ensureListening();
|
|
|
505
1003
|
function readCmpConsent(timeoutMs = 500) {
|
|
506
1004
|
ensureListening();
|
|
507
1005
|
const immediate = detectCmpConsent();
|
|
508
|
-
if (immediate || cmpWaitExhausted || typeof window === "undefined") {
|
|
1006
|
+
if (immediate && cmpSettled() || cmpWaitExhausted || typeof window === "undefined") {
|
|
509
1007
|
return Promise.resolve(immediate);
|
|
510
1008
|
}
|
|
511
1009
|
return new Promise((resolve) => {
|
|
512
1010
|
const started = Date.now();
|
|
513
1011
|
const poll = () => {
|
|
514
1012
|
const consent = detectCmpConsent();
|
|
515
|
-
if (consent) return resolve(consent);
|
|
1013
|
+
if (consent && cmpSettled()) return resolve(consent);
|
|
516
1014
|
const elapsed = Date.now() - started;
|
|
517
|
-
const cmpPresent = Boolean(
|
|
1015
|
+
const cmpPresent = Boolean(
|
|
1016
|
+
findCmpApi("__tcfapi") || findCmpApi("__uspapi") || findCmpApi("__gpp")
|
|
1017
|
+
);
|
|
518
1018
|
if (cmpPresent) {
|
|
519
1019
|
if (elapsed >= timeoutMs) {
|
|
520
1020
|
cmpWaitExhausted = true;
|
|
521
|
-
return resolve(
|
|
1021
|
+
return resolve(consent);
|
|
522
1022
|
}
|
|
523
1023
|
} else if (elapsed >= timeoutMs || Date.now() - graceStartedAt >= NO_CMP_GRACE_MS) {
|
|
524
1024
|
return resolve(void 0);
|
|
@@ -822,42 +1322,6 @@ var Client = class {
|
|
|
822
1322
|
}
|
|
823
1323
|
};
|
|
824
1324
|
|
|
825
|
-
// hash.ts
|
|
826
|
-
async function sha256Hex(value) {
|
|
827
|
-
const subtle = typeof globalThis !== "undefined" && globalThis.crypto?.subtle || void 0;
|
|
828
|
-
if (!subtle) return void 0;
|
|
829
|
-
try {
|
|
830
|
-
const bytes = new TextEncoder().encode(value);
|
|
831
|
-
const digest = await subtle.digest("SHA-256", bytes);
|
|
832
|
-
const hex2 = Array.from(new Uint8Array(digest)).map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
833
|
-
return hex2;
|
|
834
|
-
} catch {
|
|
835
|
-
return void 0;
|
|
836
|
-
}
|
|
837
|
-
}
|
|
838
|
-
function normalizeEmail(raw) {
|
|
839
|
-
if (typeof raw !== "string") return void 0;
|
|
840
|
-
const trimmed = raw.trim().toLowerCase();
|
|
841
|
-
return trimmed || void 0;
|
|
842
|
-
}
|
|
843
|
-
function normalizePhone(raw) {
|
|
844
|
-
if (typeof raw !== "string") return void 0;
|
|
845
|
-
const digits = raw.replace(/\D+/g, "");
|
|
846
|
-
return digits || void 0;
|
|
847
|
-
}
|
|
848
|
-
async function hashPii(values) {
|
|
849
|
-
const out = {};
|
|
850
|
-
const emailNorm = normalizeEmail(values.email ?? void 0);
|
|
851
|
-
const phoneNorm = normalizePhone(values.phone ?? void 0);
|
|
852
|
-
const [hashedEmail, hashedPhone] = await Promise.all([
|
|
853
|
-
emailNorm ? sha256Hex(emailNorm) : Promise.resolve(void 0),
|
|
854
|
-
phoneNorm ? sha256Hex(phoneNorm) : Promise.resolve(void 0)
|
|
855
|
-
]);
|
|
856
|
-
if (hashedEmail) out.hashed_email = hashedEmail;
|
|
857
|
-
if (hashedPhone) out.hashed_phone = hashedPhone;
|
|
858
|
-
return out;
|
|
859
|
-
}
|
|
860
|
-
|
|
861
1325
|
// gravity-pixel.ts
|
|
862
1326
|
function uuid(prefix) {
|
|
863
1327
|
const hex2 = () => Math.random().toString(36).slice(2, 10);
|
|
@@ -1313,7 +1777,10 @@ function gravityPixel(opts) {
|
|
|
1313
1777
|
// Annotate the CommonJS export names for ESM import in node:
|
|
1314
1778
|
0 && (module.exports = {
|
|
1315
1779
|
Client,
|
|
1780
|
+
DEFAULT_INDEX_TIMEOUT_MS,
|
|
1781
|
+
DEFAULT_INDEX_URL,
|
|
1316
1782
|
Gravity,
|
|
1783
|
+
GravityIndex,
|
|
1317
1784
|
GravityPixel,
|
|
1318
1785
|
detectCmpConsent,
|
|
1319
1786
|
extractClientIp,
|
|
@@ -1322,6 +1789,8 @@ function gravityPixel(opts) {
|
|
|
1322
1789
|
gravityContextAsync,
|
|
1323
1790
|
gravityPixel,
|
|
1324
1791
|
hashPii,
|
|
1792
|
+
isConsumerSearchResponse,
|
|
1793
|
+
isDeveloperSearchResponse,
|
|
1325
1794
|
readCmpConsent,
|
|
1326
1795
|
toGravityMessages
|
|
1327
1796
|
});
|