UNPKG

posthog-js

Version:

Posthog-js allows you to automatically capture usage and send events to PostHog.

307 lines • 14.4 kB
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype); return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (g && (g = 0, op[0] && (_ = 0)), _) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; var __values = (this && this.__values) || function(o) { var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); if (o && typeof o.length === "number") return { next: function () { if (o && i >= o.length) o = void 0; return { value: o && o[i++], done: !o }; } }; throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.BrowserClientAdapter = void 0; var browser_common_1 = require("@posthog/browser-common"); var extension_runtime_1 = require("@posthog/browser-common/extension-runtime"); var logger_1 = require("@posthog/browser-common/utils/logger"); var core_1 = require("@posthog/core"); var config_1 = __importDefault(require("../config")); var constants_1 = require("../constants"); var request_1 = require("../request"); var BrowserClientKeyValueStore = /** @class */ (function () { function BrowserClientKeyValueStore(_instance) { this._instance = _instance; } BrowserClientKeyValueStore.prototype.initialize = function () { }; BrowserClientKeyValueStore.prototype.get = function (keyOrKeys) { var e_1, _a; var persistence = this._instance.persistence; if (typeof keyOrKeys === 'string') { return persistence === null || persistence === void 0 ? void 0 : persistence.get_property(keyOrKeys); } var values = {}; try { for (var keyOrKeys_1 = __values(keyOrKeys), keyOrKeys_1_1 = keyOrKeys_1.next(); !keyOrKeys_1_1.done; keyOrKeys_1_1 = keyOrKeys_1.next()) { var key = keyOrKeys_1_1.value; var value = persistence === null || persistence === void 0 ? void 0 : persistence.get_property(key); if (!(0, core_1.isUndefined)(value)) { values[key] = value; } } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (keyOrKeys_1_1 && !keyOrKeys_1_1.done && (_a = keyOrKeys_1.return)) _a.call(keyOrKeys_1); } finally { if (e_1) throw e_1.error; } } return values; }; BrowserClientKeyValueStore.prototype.set = function (properties, value) { var _a; var _b; (_b = this._instance.persistence) === null || _b === void 0 ? void 0 : _b.register((typeof properties === 'string' ? (_a = {}, _a[properties] = value, _a) : properties)); }; BrowserClientKeyValueStore.prototype.remove = function (keyOrKeys) { var _a; (_a = this._instance.persistence) === null || _a === void 0 ? void 0 : _a.unregister(keyOrKeys); }; return BrowserClientKeyValueStore; }()); var REMOTE_CONFIG_EVENT = 'extensionsRemoteConfig'; /** One shared extension client and lifecycle host per browser-v1 PostHog instance. */ var BrowserClientAdapter = /** @class */ (function () { function BrowserClientAdapter(instance) { var _this = this; this.instance = instance; this._disposed = false; this._logger = logger_1.logger; this._latestRemoteConfigResult = instance._lastRemoteConfig; this.kv = new BrowserClientKeyValueStore(instance); this.onEvent = function (handler) { var unsubscribe = _this.instance.on('eventCaptured', function (event) { try { handler({ event: event.event, properties: event.properties, }); } catch (error) { _this._logger.error('Browser extension event listener failed', error); } }); return (0, browser_common_1.createDisposable)(unsubscribe); }; this.onRemoteConfig = function (handler) { if (_this._disposed) { return (0, browser_common_1.createDisposable)(function () { }); } var invoke = function (result) { try { handler(result); } catch (error) { _this._logger.error('Browser extension remote config listener failed', error); } }; var unsubscribe = _this.instance._internalEventEmitter.on(REMOTE_CONFIG_EVENT, invoke); if (_this._latestRemoteConfigResult) { invoke(_this._latestRemoteConfigResult); } return (0, browser_common_1.createDisposable)(unsubscribe); }; this._runtime = new extension_runtime_1.ExtensionRuntime(logger_1.logger.createLogger('[BrowserExtensions]'), this); } Object.defineProperty(BrowserClientAdapter.prototype, "logger", { get: function () { return this._logger; }, enumerable: false, configurable: true }); Object.defineProperty(BrowserClientAdapter.prototype, "distinctId", { get: function () { return this.instance.get_distinct_id(); }, enumerable: false, configurable: true }); Object.defineProperty(BrowserClientAdapter.prototype, "anonymousId", { get: function () { var _a; return (_a = this.instance.get_property(constants_1.DEVICE_ID)) !== null && _a !== void 0 ? _a : this.distinctId; }, enumerable: false, configurable: true }); Object.defineProperty(BrowserClientAdapter.prototype, "deviceId", { get: function () { var value = this.instance.get_property(constants_1.DEVICE_ID); return typeof value === 'string' ? value : undefined; }, enumerable: false, configurable: true }); Object.defineProperty(BrowserClientAdapter.prototype, "library", { get: function () { return { name: config_1.default.LIB_NAME, version: config_1.default.LIB_VERSION }; }, enumerable: false, configurable: true }); Object.defineProperty(BrowserClientAdapter.prototype, "initialPersonProperties", { get: function () { var _a, _b; return ((_b = (_a = this.instance.persistence) === null || _a === void 0 ? void 0 : _a.get_initial_props()) !== null && _b !== void 0 ? _b : {}); }, enumerable: false, configurable: true }); Object.defineProperty(BrowserClientAdapter.prototype, "groups", { get: function () { return this.instance.getGroups(); }, enumerable: false, configurable: true }); Object.defineProperty(BrowserClientAdapter.prototype, "session", { get: function () { var _a, _b, _c, _d; try { var current = (_a = this.instance.sessionManager) === null || _a === void 0 ? void 0 : _a.checkAndGetSessionAndWindowId(true); return { sessionId: (_b = current === null || current === void 0 ? void 0 : current.sessionId) !== null && _b !== void 0 ? _b : '', windowId: (_c = current === null || current === void 0 ? void 0 : current.windowId) !== null && _c !== void 0 ? _c : '', sessionStartTimestamp: (_d = current === null || current === void 0 ? void 0 : current.sessionStartTimestamp) !== null && _d !== void 0 ? _d : 0, }; } catch (_e) { return { sessionId: '', windowId: '', sessionStartTimestamp: 0 }; } }, enumerable: false, configurable: true }); Object.defineProperty(BrowserClientAdapter.prototype, "canCapture", { get: function () { return this.instance.is_capturing(); }, enumerable: false, configurable: true }); Object.defineProperty(BrowserClientAdapter.prototype, "projectToken", { get: function () { return this.instance.config.token; }, enumerable: false, configurable: true }); BrowserClientAdapter.prototype.add = function (extension) { return this._runtime.add(extension); }; BrowserClientAdapter.prototype.getExtension = function (name) { return this._runtime.getExtension(name); }; BrowserClientAdapter.prototype.capture = function (event, properties, options) { return __awaiter(this, void 0, void 0, function () { var captureOptions; return __generator(this, function (_a) { if (!options) { this.instance.capture(event, properties); return [2 /*return*/]; } captureOptions = { timestamp: options.timestamp, uuid: options.uuid, $set: options.set, $set_once: options.setOnce, }; this.instance.capture(event, properties, captureOptions); return [2 /*return*/]; }); }); }; BrowserClientAdapter.prototype.registerDynamicEventProperties = function (producer) { return (0, browser_common_1.createDisposable)(this.instance._registerExtensionEventProperties(producer)); }; BrowserClientAdapter.prototype.handleRemoteConfig = function (result) { if (this._disposed) { return; } this._latestRemoteConfigResult = result; this.instance._internalEventEmitter.emit(REMOTE_CONFIG_EVENT, result); }; BrowserClientAdapter.prototype.sendRequest = function (path_1) { return __awaiter(this, arguments, void 0, function (path, init) { var endpoint, requestOptions; var _this = this; var _a; if (init === void 0) { init = {}; } return __generator(this, function (_b) { endpoint = this.instance.requestRouter.endpointFor((_a = init.target) !== null && _a !== void 0 ? _a : 'api', path); requestOptions = { method: init.method, url: init.query ? (0, request_1.extendURLParams)(endpoint, init.query) : endpoint, data: init.body, headers: init.headers, timeout: init.timeoutMs, fireCallbackOnDrop: true, transport: init.transport, compression: init.compression, compressionFallback: init.target === 'flags' && init.compression === 'best-available' ? core_1.Compression.Base64 : undefined, timestampMode: init.sentAt, }; if (init.transport === 'sendBeacon') { this.instance._send_request(requestOptions); return [2 /*return*/, { statusCode: 202 }]; } // eslint-disable-next-line compat/compat -- The shared Client transport is intentionally awaitable. return [2 /*return*/, new Promise(function (resolve) { requestOptions.callback = resolve; _this.instance._send_request(requestOptions); })]; }); }); }; BrowserClientAdapter.prototype.dispose = function () { if (this._disposed) { return; } this._disposed = true; this._runtime.dispose(); }; return BrowserClientAdapter; }()); exports.BrowserClientAdapter = BrowserClientAdapter; //# sourceMappingURL=browser-client.js.map