diff --git a/.gitignore b/.gitignore index e8b8fb0..5dc46a0 100644 --- a/.gitignore +++ b/.gitignore @@ -414,4 +414,8 @@ examples/**/**/package-lock.json # playwright test result test-results -**/public \ No newline at end of file +**/public + +# application insights package +src/feature-management-applicationinsights-browser/package-lock.json +src/feature-management-applicationinsights-node/package-lock.json diff --git a/src/feature-management-applicationinsights-browser/package.json b/src/feature-management-applicationinsights-browser/package.json index 00f792e..8ecbaf8 100644 --- a/src/feature-management-applicationinsights-browser/package.json +++ b/src/feature-management-applicationinsights-browser/package.json @@ -46,7 +46,8 @@ }, "dependencies": { "@microsoft/applicationinsights-web": "^3.3.2", - "@microsoft/feature-management": "2.1.0" + "@microsoft/feature-management": "2.1.0", + "@nevware21/ts-utils": ">= 0.12.5 < 2.x" } } \ No newline at end of file diff --git a/src/feature-management-applicationinsights-browser/src/targeting.ts b/src/feature-management-applicationinsights-browser/src/targeting.ts new file mode 100644 index 0000000..7d7a395 --- /dev/null +++ b/src/feature-management-applicationinsights-browser/src/targeting.ts @@ -0,0 +1,52 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { getDocument } from "@nevware21/ts-utils"; +import { ITargetingContext, ITargetingContextAccessor } from "@microsoft/feature-management"; + +const APPLICATION_INSIGHTS_USER_COOKIE = "ai_user"; + +/** + * A default implementation of ITargetingContextAccessor that retrieves targeting context from the document's cookie. + */ +export class DefaultHttpTargetingContextAccessor implements ITargetingContextAccessor { + #document: Document; + #cookieValue: string; + #cookieCache: { [key: string]: string } = {}; + + constructor() { + this.#document = getDocument(); + this.#cookieValue = this.#document.cookie || ""; + } + + getTargetingContext(): ITargetingContext { + return { + userId: this.#getCookieValue(APPLICATION_INSIGHTS_USER_COOKIE) + }; + } + + #getCookieValue(name: string): string { + const cookie = this.#document.cookie || ""; + if (this.#cookieValue !== cookie) { + this.#parseCookie(cookie); + this.#cookieValue = cookie; + } + return this.#cookieCache[name] || ""; + } + + #parseCookie(cookie: string): void { + this.#cookieCache = {}; + const cookies = cookie.split(";").map(c => c.trim()); + for (const c of cookies) { + if (!c) { + continue; + } + const eqIdx = c.indexOf("="); + if (eqIdx > -1) { + const name = c.substring(0, eqIdx).trim(); + const value = c.substring(eqIdx + 1).trim(); + this.#cookieCache[name] = value; + } + } + } +}