{"version":3,"file":"remoteSavedGroups.mjs","names":["getPath","REMOTE_GROUP_IDS_ATTRIBUTE","remoteGroupsByPayload","WeakMap","NO_REMOTE_GROUPS","getRemoteSavedGroups","savedGroups","groups","get","Object","keys","reduce","remote","id","entry","Array","isArray","type","concat","attributeKey","valuesFrom","set","resolveRemoteGroupIds","attributes","resolver","length","used","value","redisResolver","redis","checks","all","group","source","find","g","toLookupValues","map","key","matchId","unique","c","members","Promise","k","sMembers","filter","indexOf","values","i","v","Number","isFinite","String","isMissingRemoteGroupIds","user","remoteGroupIds"],"sources":["../../src/remoteSavedGroups.ts"],"sourcesContent":["import type {\n  Attributes,\n  RemoteSavedGroup,\n  SavedGroupResolver,\n  SavedGroupsPayload,\n} from \"./types/growthbook\";\nimport { getPath } from \"./util\";\n\n/**\n * The attribute evaluation reads a user's remote saved groups from. Internal\n * attributes start with `__gb_`, matching GrowthBook's back end.\n */\nexport const REMOTE_GROUP_IDS_ATTRIBUTE = \"__gb_remoteGroupIds\";\n\n// Evaluation checks for remote groups often, so each payload is scanned once.\nconst remoteGroupsByPayload = new WeakMap<\n  SavedGroupsPayload,\n  RemoteSavedGroup[]\n>();\n\nconst NO_REMOTE_GROUPS: RemoteSavedGroup[] = [];\n\n/** Only v2 payloads include the remote group metadata this helper reads. */\nexport function getRemoteSavedGroups(\n  savedGroups?: SavedGroupsPayload,\n): RemoteSavedGroup[] {\n  // Most payloads have no saved groups; skip the allocation on the hot path\n  if (!savedGroups) return NO_REMOTE_GROUPS;\n  let groups = remoteGroupsByPayload.get(savedGroups);\n  if (!groups) {\n    groups = Object.keys(savedGroups).reduce<RemoteSavedGroup[]>(\n      (remote, id) => {\n        const entry = savedGroups[id];\n        return !Array.isArray(entry) && entry.type === \"remote\"\n          ? remote.concat({\n              id,\n              attributeKey: entry.attributeKey,\n              ...(entry.valuesFrom && { valuesFrom: entry.valuesFrom }),\n            })\n          : remote;\n      },\n      [],\n    );\n    remoteGroupsByPayload.set(savedGroups, groups);\n  }\n  return groups;\n}\n\n/**\n * Asks `resolver` which of the payload's remote groups the user is in. Only\n * the attributes those groups use are passed. Throws what the resolver\n * throws.\n *\n * Returns [] when the payload lists no remote groups. Don't set that as\n * `__gb_remoteGroupIds`: the payload may still check it directly, and [] makes\n * \"not in group\" rules match. Check `getRemoteSavedGroups` first.\n */\nexport async function resolveRemoteGroupIds(\n  attributes: Attributes,\n  savedGroups: SavedGroupsPayload | undefined,\n  resolver: SavedGroupResolver,\n): Promise<string[]> {\n  const groups = getRemoteSavedGroups(savedGroups);\n  if (!groups.length) return [];\n  return resolver({\n    // Keyed by `attributeKey`, which can be a dot-separated path.\n    attributes: groups.reduce<Attributes>((used, { attributeKey }) => {\n      const value = getPath(attributes, attributeKey);\n      return value === null ? used : { ...used, [attributeKey]: value };\n    }, {}),\n    groups,\n  });\n}\n\n/** A Redis client with the one command `redisResolver` needs. */\nexport type RedisSetClient = {\n  sMembers(key: string): Promise<string[]>;\n};\n\n/**\n * A resolver for remote groups loaded into Redis by GrowthBook's loader: one\n * `SMEMBERS gb:member:<attribute>:<value>` per attribute value. Works with a\n * node-redis v4 client; wrap others, e.g. `{ sMembers: (k) => redis.smembers(k) }`.\n *\n * A derived group checks its own attribute's value in its source group's\n * sets: `grp_vip:parent_id` looks up `gb:member:<grp_vip's attribute>:<parent_id>`\n * and matches when `grp_vip` comes back.\n */\nexport function redisResolver(redis: RedisSetClient): SavedGroupResolver {\n  return async ({ attributes, groups }) => {\n    // For each group and value: the Redis key, and the ID that means a match\n    const checks = groups.reduce<\n      { id: string; key: string; matchId: string }[]\n    >((all, group) => {\n      const source = group.valuesFrom\n        ? groups.find((g) => g.id === group.valuesFrom)\n        : group;\n      if (!source) return all;\n      return all.concat(\n        toLookupValues(attributes[group.attributeKey]).map((value) => ({\n          id: group.id,\n          key: `gb:member:${source.attributeKey}:${value}`,\n          matchId: source.id,\n        })),\n      );\n    }, []);\n    const keys = unique(checks.map((c) => c.key));\n    const members = await Promise.all(keys.map((k) => redis.sMembers(k)));\n    // Checking for the expected ID, not any ID in the set, also keeps keys\n    // that collide when attributes or values contain \":\" (`a:b` + `c` and\n    // `a` + `b:c`) from mixing up groups.\n    return unique(\n      checks\n        .filter((c) => members[keys.indexOf(c.key)].indexOf(c.matchId) !== -1)\n        .map((c) => c.id),\n    );\n  };\n}\n\nfunction unique(values: string[]): string[] {\n  return values.filter((value, i) => values.indexOf(value) === i);\n}\n\n// Each item of an array is looked up. Numbers use `String(value)`, the same\n// form the loader stores them in.\nfunction toLookupValues(value: unknown): string[] {\n  return (Array.isArray(value) ? value : [value])\n    .filter(\n      (v) =>\n        typeof v === \"string\" || (typeof v === \"number\" && Number.isFinite(v)),\n    )\n    .map(String);\n}\n\n/**\n * Whether the payload has remote groups but the user has no remote group IDs,\n * so every rule using them will fail.\n */\nexport function isMissingRemoteGroupIds(\n  user: { attributes?: Attributes; remoteGroupIds?: string[] },\n  savedGroups: SavedGroupsPayload | undefined,\n): boolean {\n  return (\n    !user.remoteGroupIds &&\n    !Array.isArray(user.attributes?.[REMOTE_GROUP_IDS_ATTRIBUTE]) &&\n    getRemoteSavedGroups(savedGroups).length > 0\n  );\n}\n"],"mappings":"AAMA,SAASA,OAAO,QAAQ,YAAQ;;AAEhC;AACA;AACA;AACA;AACA,OAAO,MAAMC,0BAA0B,GAAG,qBAAqB;;AAE/D;AACA,MAAMC,qBAAqB,GAAG,IAAIC,OAAO,CAGvC,CAAC;AAEH,MAAMC,gBAAoC,GAAG,EAAE;;AAE/C;AACA,OAAO,SAASC,oBAAoBA,CAClCC,WAAgC,EACZ;EACpB;EACA,IAAI,CAACA,WAAW,EAAE,OAAOF,gBAAgB;EACzC,IAAIG,MAAM,GAAGL,qBAAqB,CAACM,GAAG,CAACF,WAAW,CAAC;EACnD,IAAI,CAACC,MAAM,EAAE;IACXA,MAAM,GAAGE,MAAM,CAACC,IAAI,CAACJ,WAAW,CAAC,CAACK,MAAM,CACtC,CAACC,MAAM,EAAEC,EAAE,KAAK;MACd,MAAMC,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