@mrrocket/sdk 0.23.0 → 0.24.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/CHANGELOG.md +27 -10
- package/dist/api-client.d.ts +7 -0
- package/dist/api-client.js +2 -0
- package/dist/api-client.js.map +1 -1
- package/dist/browser/mrrocket-flows.js +3 -3
- package/dist/browser/mrrocket-messenger.js +3 -3
- package/dist/browser/mrrocket-replay.js +3 -3
- package/dist/browser/mrrocket.js +2 -1
- package/dist/client.js +93 -45
- package/dist/client.js.map +1 -1
- package/dist/context.d.ts +5 -0
- package/dist/context.js.map +1 -1
- package/dist/core.d.ts +84 -13
- package/dist/core.js +95 -14
- package/dist/core.js.map +1 -1
- package/dist/flows.d.ts +12 -1
- package/dist/flows.js +12 -1
- package/dist/flows.js.map +1 -1
- package/dist/messenger-ui.d.ts +1 -1
- package/dist/messenger-ui.js +43 -9
- package/dist/messenger-ui.js.map +1 -1
- package/dist/paywall.d.ts +6 -3
- package/dist/paywall.js +5 -5
- package/dist/paywall.js.map +1 -1
- package/dist/proxy.d.ts +3 -2
- package/dist/proxy.js +1 -1
- package/dist/proxy.js.map +1 -1
- package/dist/react-native/index.d.cts +31 -2
- package/dist/react-native/index.d.ts +31 -2
- package/dist/react-native/index.js +114 -32
- package/dist/react-native/index.js.map +1 -1
- package/dist/server.d.ts +29 -7
- package/dist/server.js +43 -9
- package/dist/server.js.map +1 -1
- package/dist/user-hash.d.ts +1 -0
- package/dist/user-hash.js +1 -0
- package/dist/user-hash.js.map +1 -1
- package/dist/web-state.d.ts +2 -1
- package/dist/web-state.js +3 -0
- package/dist/web-state.js.map +1 -1
- package/package.json +1 -1
package/dist/server.d.ts
CHANGED
|
@@ -9,6 +9,10 @@ interface CookieReader {
|
|
|
9
9
|
value: string;
|
|
10
10
|
} | undefined;
|
|
11
11
|
}
|
|
12
|
+
/** What Next's `headers()` (and a `Request`'s `headers`) offer. */
|
|
13
|
+
interface HeaderReader {
|
|
14
|
+
get(name: string): string | null;
|
|
15
|
+
}
|
|
12
16
|
/**
|
|
13
17
|
* The experiments for a public key. `null` when MRRocket cannot be reached, answers with an error or is slower than
|
|
14
18
|
* `timeoutMs`: everyone then sees control and the page still renders. Runs on Node, the Edge runtime and Cloudflare
|
|
@@ -16,19 +20,31 @@ interface CookieReader {
|
|
|
16
20
|
*
|
|
17
21
|
* `apiKey` and `host` default to `NEXT_PUBLIC_MRROCKET_KEY` and `NEXT_PUBLIC_MRROCKET_HOST`. `locale` (0.21.0): the
|
|
18
22
|
* visitor's language when your server knows it, so the SDK's words come along; without it the browser reads them itself.
|
|
23
|
+
*
|
|
24
|
+
* `headers` (0.24.0): the visitor's request headers (`await headers()` from `next/headers`). With them and the server key
|
|
25
|
+
* (`serverKey` or `MRROCKET_SERVER_KEY`) MRRocket hands over the visitor's `unit`, its daily visitor hash, made from the
|
|
26
|
+
* visitor's address and browser as your server saw them; the address is used for that hash only and never stored.
|
|
27
|
+
* Running tests then render the visitor's version on the first paint in the default cookieless mode, the same all day
|
|
28
|
+
* and the same the browser keeps. Without them the config comes without a unit: running tests render control on the
|
|
29
|
+
* server and the browser asks for the unit itself (a cookie or `distinctId` still decides as before).
|
|
19
30
|
*/
|
|
20
|
-
export declare const getCockpitConfig: ({ apiKey, host, timeoutMs, locale }?: {
|
|
31
|
+
export declare const getCockpitConfig: ({ apiKey, host, timeoutMs, locale, headers, serverKey, }?: {
|
|
21
32
|
apiKey?: string;
|
|
22
33
|
host?: string;
|
|
23
34
|
timeoutMs?: number;
|
|
24
35
|
locale?: string;
|
|
36
|
+
headers?: HeaderReader;
|
|
37
|
+
serverKey?: string;
|
|
25
38
|
}) => Promise<CockpitConfig | null>;
|
|
26
39
|
/** Forced variants and the embed flag from a page's search params, for previews in Cockpit. */
|
|
27
40
|
export declare const previewFrom: (searchParams: SearchParams | undefined) => {
|
|
28
41
|
preview: Record<string, string>;
|
|
29
42
|
embedded: boolean;
|
|
30
43
|
};
|
|
31
|
-
/**
|
|
44
|
+
/**
|
|
45
|
+
* The visitor's id from the `ck_id` cookie, if the browser has one yet (only in consent "cookies" mode); "anonymous"
|
|
46
|
+
* without one. The helpers below no longer assign tests by "anonymous" (0.24.0): see `assignIdFor`.
|
|
47
|
+
*/
|
|
32
48
|
export declare const distinctIdFrom: (cookies: CookieReader | undefined) => string;
|
|
33
49
|
/**
|
|
34
50
|
* Who the visitor is for this request. Pass `distinctId` (your signed-in user id, the same you give
|
|
@@ -40,22 +56,28 @@ interface RequestInfo {
|
|
|
40
56
|
cookies?: CookieReader;
|
|
41
57
|
distinctId?: string;
|
|
42
58
|
}
|
|
43
|
-
/**
|
|
44
|
-
|
|
59
|
+
/**
|
|
60
|
+
* The id this request's tests and flags assign by (0.24.0): `distinctId`, else the `ck_id` cookie, else the config's
|
|
61
|
+
* `unit` (from `getCockpitConfig({ headers })`), the same the browser then uses. Null when none is known: running
|
|
62
|
+
* tests render control on the server and the browser decides, instead of putting every such visitor in one version.
|
|
63
|
+
*/
|
|
64
|
+
export declare const assignIdFor: ({ config, cookies, distinctId }: RequestInfo) => string | null;
|
|
65
|
+
/** The variant of one experiment for this request (control for a running test while the visitor is unknown). */
|
|
66
|
+
export declare const getVariant: (key: string, info: RequestInfo) => VariantId;
|
|
45
67
|
/**
|
|
46
68
|
* A feature flag for this request: true while it is on for the visitor, false while it is off or unknown (or MRRocket
|
|
47
69
|
* could not be reached). `person` takes the properties the flag's audience reads ("Email", "Plan" …), as you pass them
|
|
48
70
|
* to identify(). For a multivariate flag use `getFlagVariant`.
|
|
49
71
|
*/
|
|
50
|
-
export declare const getFlag: (key: string,
|
|
72
|
+
export declare const getFlag: (key: string, info: RequestInfo & {
|
|
51
73
|
person?: FlagPerson;
|
|
52
74
|
}) => boolean;
|
|
53
75
|
/** The variant of a multivariate flag for this request, or null while it is off. */
|
|
54
|
-
export declare const getFlagVariant: (key: string,
|
|
76
|
+
export declare const getFlagVariant: (key: string, info: RequestInfo & {
|
|
55
77
|
person?: FlagPerson;
|
|
56
78
|
}) => string | null;
|
|
57
79
|
/** Every text change for this request, to render `<Text>` defaults server-side. */
|
|
58
|
-
export declare const getTexts: (
|
|
80
|
+
export declare const getTexts: (info: RequestInfo) => Record<string, string>;
|
|
59
81
|
export * from "./core.js";
|
|
60
82
|
/** Identity verification (0.16.0): sign a user id for `identify(id, props, { hash })` with the product's server key. */
|
|
61
83
|
export { type UserHashOptions, userHash } from "./user-hash.js";
|
package/dist/server.js
CHANGED
|
@@ -1,23 +1,55 @@
|
|
|
1
1
|
// src/server.ts
|
|
2
|
-
import {
|
|
2
|
+
import {
|
|
3
|
+
EMBED_PARAM,
|
|
4
|
+
ID_COOKIE,
|
|
5
|
+
PREVIEW_PARAM,
|
|
6
|
+
VISITOR_IP_HEADER,
|
|
7
|
+
VISITOR_UA_HEADER,
|
|
8
|
+
envKey,
|
|
9
|
+
flagFor,
|
|
10
|
+
parsePreview,
|
|
11
|
+
resolveHost,
|
|
12
|
+
resolveVariant,
|
|
13
|
+
textChanges
|
|
14
|
+
} from "./core.js";
|
|
15
|
+
import { envServerKey } from "./user-hash.js";
|
|
3
16
|
export * from "./core.js";
|
|
4
17
|
import { userHash } from "./user-hash.js";
|
|
5
18
|
import { attackIn, ipOf, reportAuthDenied, reportFailedLogin, reportSuspiciousRequest, watchRequest } from "./security.js";
|
|
6
19
|
import { REFERRAL_COOKIE, readReferralCookie, referralForCheckout, referralLink } from "./referral.js";
|
|
7
20
|
var CONFIG_TIMEOUT_MS = 2500;
|
|
8
|
-
var
|
|
21
|
+
var warnedNoKey = false;
|
|
22
|
+
var visitorIpOf = (h) => (h.get("cf-connecting-ip") ?? h.get("x-forwarded-for")?.split(",")[0] ?? h.get("x-real-ip") ?? "").trim() || void 0;
|
|
23
|
+
var getCockpitConfig = async ({
|
|
24
|
+
apiKey,
|
|
25
|
+
host,
|
|
26
|
+
timeoutMs = CONFIG_TIMEOUT_MS,
|
|
27
|
+
locale,
|
|
28
|
+
headers,
|
|
29
|
+
serverKey
|
|
30
|
+
} = {}) => {
|
|
9
31
|
const key = apiKey ?? envKey();
|
|
10
32
|
if (!key) return null;
|
|
33
|
+
const secret = (serverKey ?? envServerKey() ?? "").trim();
|
|
34
|
+
const ip = headers ? visitorIpOf(headers) : void 0;
|
|
35
|
+
const forward = !!(secret && ip);
|
|
36
|
+
if (headers && !secret && !warnedNoKey) {
|
|
37
|
+
warnedNoKey = true;
|
|
38
|
+
console.warn("[MRRocket] getCockpitConfig({ headers }) needs the server key (MRROCKET_SERVER_KEY or serverKey) to render a cookieless visitor's test version on the server; until then running tests render control there and the browser picks.");
|
|
39
|
+
}
|
|
11
40
|
const ctl = new AbortController();
|
|
12
41
|
const timer = setTimeout(() => ctl.abort(), timeoutMs);
|
|
13
42
|
try {
|
|
14
43
|
const res = await fetch(`${resolveHost(host)}/api/sdk/config?key=${encodeURIComponent(key)}${locale ? `&lang=${encodeURIComponent(locale)}` : ""}`, {
|
|
15
44
|
signal: ctl.signal,
|
|
16
|
-
next: { revalidate: 0 }
|
|
45
|
+
next: { revalidate: 0 },
|
|
46
|
+
...forward && ip ? { headers: { authorization: `Bearer ${secret}`, [VISITOR_IP_HEADER]: ip, [VISITOR_UA_HEADER]: headers?.get("user-agent") ?? "" } } : {}
|
|
17
47
|
});
|
|
18
48
|
if (!res.ok) return null;
|
|
19
49
|
const config = await res.json();
|
|
20
|
-
|
|
50
|
+
if (!config || !Array.isArray(config.experiments)) return null;
|
|
51
|
+
if (!forward) delete config.unit;
|
|
52
|
+
return config;
|
|
21
53
|
} catch {
|
|
22
54
|
return null;
|
|
23
55
|
} finally {
|
|
@@ -29,15 +61,17 @@ var previewFrom = (searchParams) => {
|
|
|
29
61
|
return { preview: parsePreview(searchParams?.[PREVIEW_PARAM]), embedded: (Array.isArray(embed) ? embed[0] : embed) === "1" };
|
|
30
62
|
};
|
|
31
63
|
var distinctIdFrom = (cookies) => cookies?.get(ID_COOKIE)?.value ?? "anonymous";
|
|
32
|
-
var
|
|
33
|
-
var
|
|
34
|
-
var
|
|
35
|
-
|
|
64
|
+
var assignIdFor = ({ config, cookies, distinctId }) => distinctId ?? cookies?.get(ID_COOKIE)?.value ?? config?.unit ?? null;
|
|
65
|
+
var getVariant = (key, info) => resolveVariant(key, info.config, assignIdFor(info), previewFrom(info.searchParams).preview);
|
|
66
|
+
var getFlag = (key, info) => flagFor(key, info.config, assignIdFor(info) ?? "anonymous", info.person) !== false;
|
|
67
|
+
var getFlagVariant = (key, info) => {
|
|
68
|
+
const v = flagFor(key, info.config, assignIdFor(info) ?? "anonymous", info.person);
|
|
36
69
|
return typeof v === "string" ? v : null;
|
|
37
70
|
};
|
|
38
|
-
var getTexts = (
|
|
71
|
+
var getTexts = (info) => textChanges(info.config, assignIdFor(info), previewFrom(info.searchParams).preview);
|
|
39
72
|
export {
|
|
40
73
|
REFERRAL_COOKIE,
|
|
74
|
+
assignIdFor,
|
|
41
75
|
attackIn,
|
|
42
76
|
distinctIdFrom,
|
|
43
77
|
getCockpitConfig,
|
package/dist/server.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/server.ts"],"sourcesContent":["import { type CockpitConfig, EMBED_PARAM, type FlagPerson, ID_COOKIE, PREVIEW_PARAM, type VariantId, envKey, flagFor, parsePreview, resolveHost, resolveVariant, textChanges } from \"./core\";\n\n/**\n * Server helpers for the App Router: load the experiments once per request, then render the right variant on the\n * first paint (no flicker) and hand the same config to `<CockpitProvider config>` so the browser agrees.\n */\n\ntype SearchParams = Record<string, string | string[] | undefined>;\ninterface CookieReader {\n get(name: string): { value: string } | undefined;\n}\n\n/** How long the server waits for MRRocket before it renders with control. */\nconst CONFIG_TIMEOUT_MS = 2500;\n\n/**\n * The experiments for a public key. `null` when MRRocket cannot be reached, answers with an error or is slower than\n * `timeoutMs`: everyone then sees control and the page still renders. Runs on Node, the Edge runtime and Cloudflare\n * Workers (only `fetch` and `AbortController`).\n *\n * `apiKey` and `host` default to `NEXT_PUBLIC_MRROCKET_KEY` and `NEXT_PUBLIC_MRROCKET_HOST`. `locale` (0.21.0): the\n * visitor's language when your server knows it, so the SDK's words come along; without it the browser reads them itself.\n */\nexport const getCockpitConfig = async ({ apiKey, host, timeoutMs = CONFIG_TIMEOUT_MS, locale }: { apiKey?: string; host?: string; timeoutMs?: number; locale?: string } = {}): Promise<CockpitConfig | null> => {\n const key = apiKey ?? envKey();\n if (!key) return null;\n const ctl = new AbortController();\n const timer = setTimeout(() => ctl.abort(), timeoutMs);\n try {\n // `next.revalidate: 0` keeps this request uncached in Next.js. Not `cache: \"no-store\"`: Cloudflare Workers\n // throws on the `cache` field of a fetch unless a compatibility flag is on, and every config would be null.\n const res = await fetch(`${resolveHost(host)}/api/sdk/config?key=${encodeURIComponent(key)}${locale ? `&lang=${encodeURIComponent(locale)}` : \"\"}`, {\n signal: ctl.signal,\n next: { revalidate: 0 },\n } as RequestInit);\n if (!res.ok) return null;\n const config = (await res.json()) as CockpitConfig | null;\n return config && Array.isArray(config.experiments) ? config : null;\n } catch {\n return null;\n } finally {\n clearTimeout(timer);\n }\n};\n\n/** Forced variants and the embed flag from a page's search params, for previews in Cockpit. */\nexport const previewFrom = (searchParams: SearchParams | undefined) => {\n const embed = searchParams?.[EMBED_PARAM];\n return { preview: parsePreview(searchParams?.[PREVIEW_PARAM]), embedded: (Array.isArray(embed) ? embed[0] : embed) === \"1\" };\n};\n\n/** The visitor's id from the `ck_id` cookie, if the browser has one yet (only in consent \"cookies\" mode). */\nexport const distinctIdFrom = (cookies: CookieReader | undefined) => cookies?.get(ID_COOKIE)?.value ?? \"anonymous\";\n\n/**\n * Who the visitor is for this request. Pass `distinctId` (your signed-in user id, the same you give\n * `<CockpitProvider distinctId>`) when there is no `ck_id` cookie, as in the default cookieless mode.\n */\ninterface RequestInfo {\n config: CockpitConfig | null;\n searchParams?: SearchParams;\n cookies?: CookieReader;\n distinctId?: string;\n}\n\n/** The variant of one experiment for this request. */\nexport const getVariant = (key: string, { config, searchParams, cookies, distinctId }: RequestInfo): VariantId =>\n resolveVariant(key, config, distinctId ?? distinctIdFrom(cookies), previewFrom(searchParams).preview);\n\n/**\n * A feature flag for this request: true while it is on for the visitor, false while it is off or unknown (or MRRocket\n * could not be reached). `person` takes the properties the flag's audience reads (\"Email\", \"Plan\" …), as you pass them\n * to identify(). For a multivariate flag use `getFlagVariant`.\n */\nexport const getFlag = (key: string, { config, cookies, distinctId, person }: RequestInfo & { person?: FlagPerson }): boolean =>\n flagFor(key, config, distinctId ?? distinctIdFrom(cookies), person) !== false;\n\n/** The variant of a multivariate flag for this request, or null while it is off. */\nexport const getFlagVariant = (key: string, { config, cookies, distinctId, person }: RequestInfo & { person?: FlagPerson }): string | null => {\n const v = flagFor(key, config, distinctId ?? distinctIdFrom(cookies), person);\n return typeof v === \"string\" ? v : null;\n};\n\n/** Every text change for this request, to render `<Text>` defaults server-side. */\nexport const getTexts = ({ config, searchParams, cookies, distinctId }: RequestInfo) =>\n textChanges(config, distinctId ?? distinctIdFrom(cookies), previewFrom(searchParams).preview);\n\nexport * from \"./core\";\n/** Identity verification (0.16.0): sign a user id for `identify(id, props, { hash })` with the product's server key. */\nexport { type UserHashOptions, userHash } from \"./user-hash\";\nexport { type AttackKind, type SecurityOptions, attackIn, ipOf, reportAuthDenied, reportFailedLogin, reportSuspiciousRequest, watchRequest } from \"./security\";\n/** Affiliate referrals on the server: read the `mrr_ref` cookie in the route that creates a Stripe Checkout Session. */\nexport { type CheckoutReferral, type Referral, REFERRAL_COOKIE, readReferralCookie, referralForCheckout, referralLink } from \"./referral\";\n"],"mappings":";AAAA,SAA6B,aAA8B,WAAW,eAA+B,QAAQ,SAAS,cAAc,aAAa,gBAAgB,mBAAmB;AAuFpL,cAAc;AAEd,SAA+B,gBAAgB;AAC/C,SAAgD,UAAU,MAAM,kBAAkB,mBAAmB,yBAAyB,oBAAoB;AAElJ,SAA+C,iBAAiB,oBAAoB,qBAAqB,oBAAoB;AA/E7H,IAAM,oBAAoB;AAUnB,IAAM,m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S,YAAY,OAAO,MAA4D;AAC1I,QAAM,IAAI,QAAQ,KAAK,QAAQ,cAAc,eAAe,OAAO,GAAG,MAAM;AAC5E,SAAO,OAAO,MAAM,WAAW,IAAI;AACvC;AAGO,IAAM,WAAW,CAAC,EAAE,QAAQ,cAAc,SAAS,WAAW,MACjE,YAAY,QAAQ,cAAc,eAAe,OAAO,GAAG,YAAY,YAAY,EAAE,OAAO;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/server.ts"],"sourcesContent":["import {\n type CockpitConfig,\n EMBED_PARAM,\n type FlagPerson,\n ID_COOKIE,\n PREVIEW_PARAM,\n VISITOR_IP_HEADER,\n VISITOR_UA_HEADER,\n type VariantId,\n envKey,\n flagFor,\n parsePreview,\n resolveHost,\n resolveVariant,\n textChanges,\n} from \"./core\";\nimport { envServerKey } from \"./user-hash\";\n\n/**\n * Server helpers for the App Router: load the experiments once per request, then render the right variant on the\n * first paint (no flicker) and hand the same config to `<CockpitProvider config>` so the browser agrees.\n */\n\ntype SearchParams = Record<string, string | string[] | undefined>;\ninterface CookieReader {\n get(name: string): { value: string } | undefined;\n}\n/** What Next's `headers()` (and a `Request`'s `headers`) offer. */\ninterface HeaderReader {\n get(name: string): string | null;\n}\n\n/** How long the server waits for MRRocket before it renders with control. */\nconst CONFIG_TIMEOUT_MS = 2500;\n\nlet warnedNoKey = false;\n\n/** The visitor's address in the order MRRocket's event ingest reads it, so both make the same daily hash. */\nconst visitorIpOf = (h: HeaderReader) => (h.get(\"cf-connecting-ip\") ?? h.get(\"x-forwarded-for\")?.split(\",\")[0] ?? h.get(\"x-real-ip\") ?? \"\").trim() || undefined;\n\n/**\n * The experiments for a public key. `null` when MRRocket cannot be reached, answers with an error or is slower than\n * `timeoutMs`: everyone then sees control and the page still renders. Runs on Node, the Edge runtime and Cloudflare\n * Workers (only `fetch` and `AbortController`).\n *\n * `apiKey` and `host` default to `NEXT_PUBLIC_MRROCKET_KEY` and `NEXT_PUBLIC_MRROCKET_HOST`. `locale` (0.21.0): the\n * visitor's language when your server knows it, so the SDK's words come along; without it the browser reads them itself.\n *\n * `headers` (0.24.0): the visitor's request headers (`await headers()` from `next/headers`). With them and the server key\n * (`serverKey` or `MRROCKET_SERVER_KEY`) MRRocket hands over the visitor's `unit`, its daily visitor hash, made from the\n * visitor's address and browser as your server saw them; the address is used for that hash only and never stored.\n * Running tests then render the visitor's version on the first paint in the default cookieless mode, the same all day\n * and the same the browser keeps. Without them the config comes without a unit: running tests render control on the\n * server and the browser asks for the unit itself (a cookie or `distinctId` still decides as before).\n */\nexport const getCockpitConfig = async ({\n apiKey,\n host,\n timeoutMs = CONFIG_TIMEOUT_MS,\n locale,\n headers,\n serverKey,\n}: { apiKey?: string; host?: string; timeoutMs?: number; locale?: string; headers?: HeaderReader; serverKey?: string } = {}): Promise<CockpitConfig | null> => {\n const key = apiKey ?? envKey();\n if (!key) return null;\n // The visitor, as this server saw them, signed by the server key: otherwise MRRocket would hash this server's address.\n const secret = (serverKey ?? envServerKey() ?? \"\").trim();\n const ip = headers ? visitorIpOf(headers) : undefined;\n const forward = !!(secret && ip);\n if (headers && !secret && !warnedNoKey) {\n warnedNoKey = true;\n console.warn(\"[MRRocket] getCockpitConfig({ headers }) needs the server key (MRROCKET_SERVER_KEY or serverKey) to render a cookieless visitor's test version on the server; until then running tests render control there and the browser picks.\");\n }\n const ctl = new AbortController();\n const timer = setTimeout(() => ctl.abort(), timeoutMs);\n try {\n // `next.revalidate: 0` keeps this request uncached in Next.js. Not `cache: \"no-store\"`: Cloudflare Workers\n // throws on the `cache` field of a fetch unless a compatibility flag is on, and every config would be null.\n const res = await fetch(`${resolveHost(host)}/api/sdk/config?key=${encodeURIComponent(key)}${locale ? `&lang=${encodeURIComponent(locale)}` : \"\"}`, {\n signal: ctl.signal,\n next: { revalidate: 0 },\n ...(forward && ip\n ? { headers: { authorization: `Bearer ${secret}`, [VISITOR_IP_HEADER]: ip, [VISITOR_UA_HEADER]: headers?.get(\"user-agent\") ?? \"\" } }\n : {}),\n } as RequestInit);\n if (!res.ok) return null;\n const config = (await res.json()) as CockpitConfig | null;\n if (!config || !Array.isArray(config.experiments)) return null;\n // A unit made without the visitor's headers is this server's own: it would put every visitor in one version.\n if (!forward) delete config.unit;\n return config;\n } catch {\n return null;\n } finally {\n clearTimeout(timer);\n }\n};\n\n/** Forced variants and the embed flag from a page's search params, for previews in Cockpit. */\nexport const previewFrom = (searchParams: SearchParams | undefined) => {\n const embed = searchParams?.[EMBED_PARAM];\n return { preview: parsePreview(searchParams?.[PREVIEW_PARAM]), embedded: (Array.isArray(embed) ? embed[0] : embed) === \"1\" };\n};\n\n/**\n * The visitor's id from the `ck_id` cookie, if the browser has one yet (only in consent \"cookies\" mode); \"anonymous\"\n * without one. The helpers below no longer assign tests by \"anonymous\" (0.24.0): see `assignIdFor`.\n */\nexport const distinctIdFrom = (cookies: CookieReader | undefined) => cookies?.get(ID_COOKIE)?.value ?? \"anonymous\";\n\n/**\n * Who the visitor is for this request. Pass `distinctId` (your signed-in user id, the same you give\n * `<CockpitProvider distinctId>`) when there is no `ck_id` cookie, as in the default cookieless mode.\n */\ninterface RequestInfo {\n config: CockpitConfig | null;\n searchParams?: SearchParams;\n cookies?: CookieReader;\n distinctId?: string;\n}\n\n/**\n * The id this request's tests and flags assign by (0.24.0): `distinctId`, else the `ck_id` cookie, else the config's\n * `unit` (from `getCockpitConfig({ headers })`), the same the browser then uses. Null when none is known: running\n * tests render control on the server and the browser decides, instead of putting every such visitor in one version.\n */\nexport const assignIdFor = ({ config, cookies, distinctId }: RequestInfo): string | null => distinctId ?? cookies?.get(ID_COOKIE)?.value ?? config?.unit ?? null;\n\n/** The variant of one experiment for this request (control for a running test while the visitor is unknown). */\nexport const getVariant = (key: string, info: RequestInfo): VariantId => resolveVariant(key, info.config, assignIdFor(info), previewFrom(info.searchParams).preview);\n\n/**\n * A feature flag for this request: true while it is on for the visitor, false while it is off or unknown (or MRRocket\n * could not be reached). `person` takes the properties the flag's audience reads (\"Email\", \"Plan\" …), as you pass them\n * to identify(). For a multivariate flag use `getFlagVariant`.\n */\nexport const getFlag = (key: string, info: RequestInfo & { person?: FlagPerson }): boolean => flagFor(key, info.config, assignIdFor(info) ?? \"anonymous\", info.person) !== false;\n\n/** The variant of a multivariate flag for this request, or null while it is off. */\nexport const getFlagVariant = (key: string, info: RequestInfo & { person?: FlagPerson }): string | null => {\n const v = flagFor(key, info.config, assignIdFor(info) ?? \"anonymous\", info.person);\n return typeof v === \"string\" ? v : null;\n};\n\n/** Every text change for this request, to render `<Text>` defaults server-side. */\nexport const getTexts = (info: RequestInfo) => textChanges(info.config, assignIdFor(info), previewFrom(info.searchParams).preview);\n\nexport * from \"./core\";\n/** Identity verification (0.16.0): sign a user id for `identify(id, props, { hash })` with the product's server key. */\nexport { type UserHashOptions, userHash } from \"./user-hash\";\nexport { type AttackKind, type SecurityOptions, attackIn, ipOf, reportAuthDenied, reportFailedLogin, reportSuspiciousRequest, watchRequest } from \"./security\";\n/** Affiliate referrals on the server: read the `mrr_ref` cookie in the route that creates a Stripe Checkout Session. */\nexport { type CheckoutReferral, type Referral, REFERRAL_COOKIE, readReferralCookie, referralForCheckout, referralLink } from \"./referral\";\n"],"mappings":";AAAA;AAAA,EAEI;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACG;AACP,SAAS,oBAAoB;AAmI7B,cAAc;AAEd,SAA+B,gBAAgB;AAC/C,SAAgD,UAAU,MAAM,kBAAkB,mBAAmB,yBAAyB,oBAAoB;AAElJ,SAA+C,iBAAiB,oBAAoB,qBAAqB,oBAAoB;AAvH7H,IAAM,oBAAoB;AAE1B,IAAI,cAAc;AAGlB,IAAM,cAAc,CAAC,OAAqB,EAAE,IAAI,kBAAkB,KAAK,EAAE,IAAI,iBAAiB,GAAG,MAAM,GAAG,EAAE,CAAC,KAAK,EAAE,IAAI,WAAW,KAA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,QAAM,QAAQ,eAAe,WAAW;AACxC,SAAO,EAAE,SAAS,aAAa,eAAe,aAAa,CAAC,GAAG,WAAW,MAAM,QAAQ,KAAK,IAAI,MAAM,CAAC,IAAI,WAAW,IAAI;AAC/H;AAMO,IAAM,iBAAiB,CAAC,YAAsC,SAAS,IAAI,SAAS,GAAG,SAAS;AAkBhG,IAAM,cAAc,CAAC,EAAE,QAAQ,SAAS,WAAW,MAAkC,cAAc,SAAS,IAAI,SAAS,GAAG,SAAS,QAAQ,QAAQ;AAGrJ,IAAM,aAAa,CAAC,KAAa,SAAiC,eAAe,KAAK,KAAK,QAAQ,YAAY,IAAI,GAAG,YAAY,KAAK,YAAY,EAAE,OAAO;AAO5J,IAAM,UAAU,CAAC,KAAa,SAAyD,QAAQ,KAAK,KAAK,QAAQ,YAAY,IAAI,KAAK,aAAa,KAAK,MAAM,MAAM;AAGpK,IAAM,iBAAiB,CAAC,KAAa,SAA+D;AACvG,QAAM,IAAI,QAAQ,KAAK,KAAK,QAAQ,YAAY,IAAI,KAAK,aAAa,KAAK,MAAM;AACjF,SAAO,OAAO,MAAM,WAAW,IAAI;AACvC;AAGO,IAAM,WAAW,CAAC,SAAsB,YAAY,KAAK,QAAQ,YAAY,IAAI,GAAG,YAAY,KAAK,YAAY,EAAE,OAAO;","names":[]}
|
package/dist/user-hash.d.ts
CHANGED
|
@@ -19,6 +19,7 @@ export interface UserHashOptions {
|
|
|
19
19
|
/** The product's server key (`mrr_sk_…`). Defaults to `MRROCKET_SERVER_KEY`. */
|
|
20
20
|
serverKey?: string;
|
|
21
21
|
}
|
|
22
|
+
export declare const envServerKey: () => string | undefined;
|
|
22
23
|
/**
|
|
23
24
|
* The hash of `userId` for `identify(id, props, { hash })` (64 lowercase hex characters). Throws when there is no
|
|
24
25
|
* server key (pass `serverKey` or set `MRROCKET_SERVER_KEY`) or no WebCrypto, so a missing setting shows at once on
|
package/dist/user-hash.js
CHANGED
package/dist/user-hash.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/user-hash.ts"],"sourcesContent":["/**\n * Identity verification (0.16.0), the server side: signs a user id so MRRocket can tell that requests for it come from\n * that user's own session, not from someone who only knows the id. Like Intercom's identity verification.\n *\n * // app/layout.tsx (a server component)\n * const hash = user ? await userHash(user.id) : undefined;\n * <CockpitProvider distinctId={user?.id} userHash={hash}> // or identify(user.id, props, { hash }) in the browser\n *\n * The formula, for a backend in another language (the server key is `mrr_sk_…`, MRRocket › Settings › Products ›\n * Sign-in; MRRocket keeps only its SHA-256, which is why that is the HMAC key):\n *\n * userHash = lowercase hex( HMAC-SHA256( key = SHA-256(server key) as its 32 raw bytes, message = user id as UTF-8 ) )\n *\n * Only on your server: the server key must never reach a browser or an app bundle. WebCrypto only (`crypto.subtle`), so\n * it runs on Node 18+ (Next.js provides `crypto` there; plain Node 18 needs `globalThis.crypto ??=\n * require(\"node:crypto\").webcrypto`), the Edge runtime, Cloudflare Workers, Deno and Bun.\n */\n\nexport interface UserHashOptions {\n /** The product's server key (`mrr_sk_…`). Defaults to `MRROCKET_SERVER_KEY`. */\n serverKey?: string;\n}\n\
|
|
1
|
+
{"version":3,"sources":["../src/user-hash.ts"],"sourcesContent":["/**\n * Identity verification (0.16.0), the server side: signs a user id so MRRocket can tell that requests for it come from\n * that user's own session, not from someone who only knows the id. Like Intercom's identity verification.\n *\n * // app/layout.tsx (a server component)\n * const hash = user ? await userHash(user.id) : undefined;\n * <CockpitProvider distinctId={user?.id} userHash={hash}> // or identify(user.id, props, { hash }) in the browser\n *\n * The formula, for a backend in another language (the server key is `mrr_sk_…`, MRRocket › Settings › Products ›\n * Sign-in; MRRocket keeps only its SHA-256, which is why that is the HMAC key):\n *\n * userHash = lowercase hex( HMAC-SHA256( key = SHA-256(server key) as its 32 raw bytes, message = user id as UTF-8 ) )\n *\n * Only on your server: the server key must never reach a browser or an app bundle. WebCrypto only (`crypto.subtle`), so\n * it runs on Node 18+ (Next.js provides `crypto` there; plain Node 18 needs `globalThis.crypto ??=\n * require(\"node:crypto\").webcrypto`), the Edge runtime, Cloudflare Workers, Deno and Bun.\n */\n\nexport interface UserHashOptions {\n /** The product's server key (`mrr_sk_…`). Defaults to `MRROCKET_SERVER_KEY`. */\n serverKey?: string;\n}\n\nexport const envServerKey = () => {\n try {\n return typeof process !== \"undefined\" ? process.env.MRROCKET_SERVER_KEY : undefined;\n } catch {\n return undefined;\n }\n};\n\nconst hex = (buf: ArrayBuffer) => Array.from(new Uint8Array(buf), (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n\n/**\n * The hash of `userId` for `identify(id, props, { hash })` (64 lowercase hex characters). Throws when there is no\n * server key (pass `serverKey` or set `MRROCKET_SERVER_KEY`) or no WebCrypto, so a missing setting shows at once on\n * your server instead of as refused requests in the browser.\n */\nexport const userHash = async (userId: string, { serverKey }: UserHashOptions = {}): Promise<string> => {\n if (typeof userId !== \"string\" || !userId) throw new Error(\"userHash: the user id must be a non-empty string (the same id you pass to identify).\");\n const key = (serverKey ?? envServerKey() ?? \"\").trim();\n if (!key) throw new Error(\"userHash: no server key. Set MRROCKET_SERVER_KEY (MRRocket › Settings › Products › your product › Sign-in) or pass { serverKey }.\");\n const subtle = (globalThis as { crypto?: Crypto }).crypto?.subtle;\n if (!subtle) throw new Error('userHash needs WebCrypto (crypto.subtle). On plain Node 18 add: globalThis.crypto ??= require(\"node:crypto\").webcrypto');\n const utf8 = new TextEncoder();\n const signingKey = await subtle.digest(\"SHA-256\", utf8.encode(key));\n const hmac = await subtle.importKey(\"raw\", signingKey, { name: \"HMAC\", hash: \"SHA-256\" }, false, [\"sign\"]);\n return hex(await subtle.sign(\"HMAC\", hmac, utf8.encode(userId)));\n};\n"],"mappings":";AAuBO,IAAM,eAAe,MAAM;AAC9B,MAAI;AACA,WAAO,OAAO,YAAY,cAAc,QAAQ,IAAI,sBAAsB;AAAA,EAC9E,QAAQ;AACJ,WAAO;AAAA,EACX;AACJ;AAEA,IAAM,MAAM,CAAC,QAAqB,MAAM,KAAK,IAAI,WAAW,GAAG,GAAG,CAAC,MAAM,EAAE,SAAS,EAAE,EAAE,SAAS,GAAG,GAAG,CAAC,EAAE,KAAK,EAAE;AAO1G,IAAM,WAAW,OAAO,QAAgB,EAAE,UAAU,IAAqB,CAAC,MAAuB;AACpG,MAAI,OAAO,WAAW,YAAY,CAAC,OAAQ,OAAM,IAAI,MAAM,sFAAsF;AACjJ,QAAM,OAAO,aAAa,aAAa,KAAK,IAAI,KAAK;AACrD,MAAI,CAAC,IAAK,OAAM,IAAI,MAAM,uJAAmI;AAC7J,QAAM,SAAU,WAAmC,QAAQ;AAC3D,MAAI,CAAC,OAAQ,OAAM,IAAI,MAAM,wHAAwH;AACrJ,QAAM,OAAO,IAAI,YAAY;AAC7B,QAAM,aAAa,MAAM,OAAO,OAAO,WAAW,KAAK,OAAO,GAAG,CAAC;AAClE,QAAM,OAAO,MAAM,OAAO,UAAU,OAAO,YAAY,EAAE,MAAM,QAAQ,MAAM,UAAU,GAAG,OAAO,CAAC,MAAM,CAAC;AACzG,SAAO,IAAI,MAAM,OAAO,KAAK,QAAQ,MAAM,KAAK,OAAO,MAAM,CAAC,CAAC;AACnE;","names":[]}
|
package/dist/web-state.d.ts
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
* the visitor and session cookies, the in-memory id of this page load, the current page's URL, referrer and campaign,
|
|
4
4
|
* and the browser's privacy signal. Plain functions, no React; only called in the browser (effects, event handlers).
|
|
5
5
|
*/
|
|
6
|
-
import { type ConsentMode, type UtmKey } from "./core.js";
|
|
6
|
+
import { type ConsentMode, type KeptVariants, type UtmKey } from "./core.js";
|
|
7
7
|
export declare const YEAR_S: number;
|
|
8
8
|
export declare const readCookie: (name: string) => string | undefined;
|
|
9
9
|
export declare const writeCookie: (name: string, value: string, maxAge: number) => void;
|
|
@@ -23,6 +23,7 @@ export declare const page: {
|
|
|
23
23
|
utm: Partial<Record<UtmKey, string>>;
|
|
24
24
|
};
|
|
25
25
|
export declare const memoryId: () => string;
|
|
26
|
+
export declare const kept: () => KeptVariants | undefined;
|
|
26
27
|
/**
|
|
27
28
|
* The visitor id for experiments, surveys and feedback. Only "cookies" reads or writes `ck_id`; the other modes keep a
|
|
28
29
|
* random id in memory for this page load. The page id follows the cookie, so leaving "cookies" keeps the same variants.
|
package/dist/web-state.js
CHANGED
|
@@ -20,6 +20,8 @@ var deleteCookie = (name) => {
|
|
|
20
20
|
};
|
|
21
21
|
var page = { utm: {} };
|
|
22
22
|
var memoryId = () => page.id ??= newDistinctId();
|
|
23
|
+
var keptVariants = /* @__PURE__ */ new Map();
|
|
24
|
+
var kept = () => typeof window === "undefined" ? void 0 : keptVariants;
|
|
23
25
|
var visitorId = (mode, write) => {
|
|
24
26
|
if (mode !== "cookies") return memoryId();
|
|
25
27
|
const stored = readCookie(ID_COOKIE);
|
|
@@ -53,6 +55,7 @@ export {
|
|
|
53
55
|
YEAR_S,
|
|
54
56
|
deleteCookie,
|
|
55
57
|
enterPage,
|
|
58
|
+
kept,
|
|
56
59
|
memoryId,
|
|
57
60
|
page,
|
|
58
61
|
privacySignal,
|
package/dist/web-state.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/web-state.ts"],"sourcesContent":["/**\n * The browser state both web runtimes share, the Next.js provider (client.tsx) and the script tag (script/index.ts):\n * the visitor and session cookies, the in-memory id of this page load, the current page's URL, referrer and campaign,\n * and the browser's privacy signal. Plain functions, no React; only called in the browser (effects, event handlers).\n */\nimport { type ConsentMode, ID_COOKIE, SESSION_COOKIE, SESSION_TIMEOUT_MS, type UtmKey, newDistinctId, readUtm } from \"./core\";\n\nexport const YEAR_S = 60 * 60 * 24 * 365;\n\nexport const readCookie = (name: string) => {\n if (typeof document === \"undefined\") return undefined;\n const raw = document.cookie\n .split(\"; \")\n .find((c) => c.startsWith(`${name}=`))\n ?.slice(name.length + 1);\n if (!raw) return undefined;\n try {\n return decodeURIComponent(raw);\n } catch {\n return raw;\n }\n};\n\nexport const writeCookie = (name: string, value: string, maxAge: number) => {\n const secure = window.location.protocol === \"https:\" ? \"; secure\" : \"\";\n document.cookie = `${name}=${encodeURIComponent(value)}; path=/; max-age=${maxAge}; samesite=lax${secure}`;\n};\n\nexport const deleteCookie = (name: string) => {\n document.cookie = `${name}=; path=/; max-age=0; samesite=lax`;\n};\n\n/**\n * What lives for one page load, outside React so it survives a provider that remounts on navigation: the in-memory\n * visitor id, the session, the current page's URL and referrer, and the campaign (UTM) parameters.\n */\nexport const page: {\n id?: string;\n session?: { id: string; last: number };\n url?: string;\n referrer?: string;\n utm: Partial<Record<UtmKey, string>>;\n} = { utm: {} };\n\nexport const memoryId = () => (page.id ??= newDistinctId());\n\n/**\n * The visitor id for experiments, surveys and feedback. Only \"cookies\" reads or writes `ck_id`; the other modes keep a\n * random id in memory for this page load. The page id follows the cookie, so leaving \"cookies\" keeps the same variants.\n */\nexport const visitorId = (mode: ConsentMode, write: boolean) => {\n if (mode !== \"cookies\") return memoryId();\n const stored = readCookie(ID_COOKIE);\n if (stored) return (page.id = stored);\n const id = memoryId();\n if (write) writeCookie(ID_COOKIE, id, YEAR_S);\n return id;\n};\n\n/** The session id for an event. Every event renews it; after 30 minutes without one a new session starts. */\nexport const touchSession = (persist: boolean) => {\n const now = Date.now();\n const s = page.session;\n // In \"cookies\" mode the cookie wins, so tabs share a session.\n const id = (persist ? readCookie(SESSION_COOKIE) : undefined) ?? (s && now - s.last < SESSION_TIMEOUT_MS ? s.id : newDistinctId());\n page.session = { id, last: now };\n if (persist) writeCookie(SESSION_COOKIE, id, SESSION_TIMEOUT_MS / 1000);\n return id;\n};\n\n/** On every route change: the previous in-app URL becomes the referrer, and a URL with UTM parameters replaces the old ones. */\nexport const enterPage = () => {\n const href = window.location.href;\n if (page.url === href) return;\n page.referrer = page.url ?? (document.referrer || undefined);\n page.url = href;\n const utm = readUtm(window.location.search);\n if (Object.keys(utm).length) page.utm = utm;\n};\n\n/** Do Not Track or Global Privacy Control. */\nexport const privacySignal = () => {\n const nav = navigator as Navigator & { doNotTrack?: string | null; globalPrivacyControl?: boolean };\n const win = window as unknown as { doNotTrack?: string | null };\n return nav.doNotTrack === \"1\" || win.doNotTrack === \"1\" || nav.globalPrivacyControl === true;\n};\n"],"mappings":";AAKA,SAA2B,
|
|
1
|
+
{"version":3,"sources":["../src/web-state.ts"],"sourcesContent":["/**\n * The browser state both web runtimes share, the Next.js provider (client.tsx) and the script tag (script/index.ts):\n * the visitor and session cookies, the in-memory id of this page load, the current page's URL, referrer and campaign,\n * and the browser's privacy signal. Plain functions, no React; only called in the browser (effects, event handlers).\n */\nimport { type ConsentMode, ID_COOKIE, type KeptVariants, SESSION_COOKIE, SESSION_TIMEOUT_MS, type UtmKey, newDistinctId, readUtm } from \"./core\";\n\nexport const YEAR_S = 60 * 60 * 24 * 365;\n\nexport const readCookie = (name: string) => {\n if (typeof document === \"undefined\") return undefined;\n const raw = document.cookie\n .split(\"; \")\n .find((c) => c.startsWith(`${name}=`))\n ?.slice(name.length + 1);\n if (!raw) return undefined;\n try {\n return decodeURIComponent(raw);\n } catch {\n return raw;\n }\n};\n\nexport const writeCookie = (name: string, value: string, maxAge: number) => {\n const secure = window.location.protocol === \"https:\" ? \"; secure\" : \"\";\n document.cookie = `${name}=${encodeURIComponent(value)}; path=/; max-age=${maxAge}; samesite=lax${secure}`;\n};\n\nexport const deleteCookie = (name: string) => {\n document.cookie = `${name}=; path=/; max-age=0; samesite=lax`;\n};\n\n/**\n * What lives for one page load, outside React so it survives a provider that remounts on navigation: the in-memory\n * visitor id, the session, the current page's URL and referrer, and the campaign (UTM) parameters.\n */\nexport const page: {\n id?: string;\n session?: { id: string; last: number };\n url?: string;\n referrer?: string;\n utm: Partial<Record<UtmKey, string>>;\n} = { utm: {} };\n\nexport const memoryId = () => (page.id ??= newDistinctId());\n\n/**\n * 0.24.0: the first version each running test gave an id on this page load (`assignKept`), in memory only. Undefined on\n * a server, where this module is shared by every request.\n */\nconst keptVariants: KeptVariants = new Map();\nexport const kept = (): KeptVariants | undefined => (typeof window === \"undefined\" ? undefined : keptVariants);\n\n/**\n * The visitor id for experiments, surveys and feedback. Only \"cookies\" reads or writes `ck_id`; the other modes keep a\n * random id in memory for this page load. The page id follows the cookie, so leaving \"cookies\" keeps the same variants.\n */\nexport const visitorId = (mode: ConsentMode, write: boolean) => {\n if (mode !== \"cookies\") return memoryId();\n const stored = readCookie(ID_COOKIE);\n if (stored) return (page.id = stored);\n const id = memoryId();\n if (write) writeCookie(ID_COOKIE, id, YEAR_S);\n return id;\n};\n\n/** The session id for an event. Every event renews it; after 30 minutes without one a new session starts. */\nexport const touchSession = (persist: boolean) => {\n const now = Date.now();\n const s = page.session;\n // In \"cookies\" mode the cookie wins, so tabs share a session.\n const id = (persist ? readCookie(SESSION_COOKIE) : undefined) ?? (s && now - s.last < SESSION_TIMEOUT_MS ? s.id : newDistinctId());\n page.session = { id, last: now };\n if (persist) writeCookie(SESSION_COOKIE, id, SESSION_TIMEOUT_MS / 1000);\n return id;\n};\n\n/** On every route change: the previous in-app URL becomes the referrer, and a URL with UTM parameters replaces the old ones. */\nexport const enterPage = () => {\n const href = window.location.href;\n if (page.url === href) return;\n page.referrer = page.url ?? (document.referrer || undefined);\n page.url = href;\n const utm = readUtm(window.location.search);\n if (Object.keys(utm).length) page.utm = utm;\n};\n\n/** Do Not Track or Global Privacy Control. */\nexport const privacySignal = () => {\n const nav = navigator as Navigator & { doNotTrack?: string | null; globalPrivacyControl?: boolean };\n const win = window as unknown as { doNotTrack?: string | null };\n return nav.doNotTrack === \"1\" || win.doNotTrack === \"1\" || nav.globalPrivacyControl === true;\n};\n"],"mappings":";AAKA,SAA2B,WAA8B,gBAAgB,oBAAiC,eAAe,eAAe;AAEjI,IAAM,SAAS,KAAK,KAAK,KAAK;AAE9B,IAAM,aAAa,CAAC,SAAiB;AACxC,MAAI,OAAO,aAAa,YAAa,QAAO;AAC5C,QAAM,MAAM,SAAS,OAChB,MAAM,IAAI,EACV,KAA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AM;AACvB,OAAK,WAAW,KAAK,QAAQ,SAAS,YAAY;AAClD,OAAK,MAAM;AACX,QAAM,MAAM,QAAQ,OAAO,SAAS,MAAM;AAC1C,MAAI,OAAO,KAAK,GAAG,EAAE,OAAQ,MAAK,MAAM;AAC5C;AAGO,IAAM,gBAAgB,MAAM;AAC/B,QAAM,MAAM;AACZ,QAAM,MAAM;AACZ,SAAO,IAAI,eAAe,OAAO,IAAI,eAAe,OAAO,IAAI,yBAAyB;AAC5F;","names":[]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mrrocket/sdk",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.24.0",
|
|
4
4
|
"description": "MRRocket SDK: page views, events, heatmap clicks, session recordings, A/B tests, feature flags, error tracking, feedback board, surveys, a chat messenger, a cancel flow, onboarding tours and checklists, in-app messages, push notifications and redirect tests that your MRRocket agents can run and read. Next.js (@mrrocket/sdk/next), React Native and Expo (@mrrocket/sdk/react-native), and a script tag for any website.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"nextjs",
|