react-native-avo-inspector
Version:
[](https://badge.fury.io/js/react-native-avo-inspector)
291 lines (290 loc) • 13.8 kB
JavaScript
"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;
return g = { next: verb(0), "throw": verb(1), "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 };
}
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AvoEventSpecFetcher = void 0;
/**
* EventSpecFetcher handles fetching event specifications from the Avo API.
*
* Endpoint: GET /trackingPlan/eventSpec
* Base URL: https://api.avo.app
*
* Adapted for React Native: uses global fetch instead of XMLHttpRequest.
*/
var AvoEventSpecFetcher = /** @class */ (function () {
function AvoEventSpecFetcher(timeout, shouldLog, env, baseUrl) {
if (timeout === void 0) { timeout = 2000; }
if (shouldLog === void 0) { shouldLog = false; }
if (baseUrl === void 0) { baseUrl = "https://api.avo.app"; }
this.baseUrl = baseUrl;
this.timeout = timeout;
this.shouldLog = shouldLog;
this.env = env;
this.inFlightRequests = new Map();
}
/** Generates a unique key for tracking in-flight requests. */
AvoEventSpecFetcher.prototype.generateRequestKey = function (params) {
return "".concat(params.apiKey, ":").concat(params.streamId, ":").concat(params.eventName);
};
/**
* Fetches an event specification from the API.
*
* Returns null if:
* - The network request fails
* - The response has an invalid status code (non-200)
* - The response is invalid or malformed
* - The request times out
*
* This method gracefully degrades - failures do not throw errors.
* When null is returned, validation is skipped for that event.
*
* In-flight de-duplication: concurrent requests for the same key
* share a single fetch promise. On failure, all waiters receive null.
*/
AvoEventSpecFetcher.prototype.fetch = function (params) {
return __awaiter(this, void 0, void 0, function () {
var requestKey, existingRequest, requestPromise, result;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
requestKey = this.generateRequestKey(params);
existingRequest = this.inFlightRequests.get(requestKey);
if (existingRequest) {
return [2 /*return*/, existingRequest];
}
requestPromise = this.fetchInternal(params);
this.inFlightRequests.set(requestKey, requestPromise);
_a.label = 1;
case 1:
_a.trys.push([1, , 3, 4]);
return [4 /*yield*/, requestPromise];
case 2:
result = _a.sent();
return [2 /*return*/, result];
case 3:
// Clean up the in-flight request tracking
this.inFlightRequests.delete(requestKey);
return [7 /*endfinally*/];
case 4: return [2 /*return*/];
}
});
});
};
/** Internal fetch implementation. */
AvoEventSpecFetcher.prototype.fetchInternal = function (params) {
return __awaiter(this, void 0, void 0, function () {
var url, wireResponse, response, error_1;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
// Defensive: AvoEventSpecFetcher is only constructed for dev/staging in AvoInspector,
// so this guard should never be reached in practice.
if (!(this.env === "dev" || this.env === "staging")) {
return [2 /*return*/, null];
}
url = this.buildUrl(params);
_a.label = 1;
case 1:
_a.trys.push([1, 3, , 4]);
return [4 /*yield*/, this.makeRequest(url)];
case 2:
wireResponse = _a.sent();
if (!wireResponse) {
if (this.shouldLog) {
console.warn("[Avo Inspector] Failed to fetch event spec for: ".concat(params.eventName));
}
return [2 /*return*/, null];
}
// Basic structure check for wire format
if (!this.hasExpectedShape(wireResponse)) {
if (this.shouldLog) {
console.warn("[Avo Inspector] Invalid event spec response for: ".concat(params.eventName));
}
return [2 /*return*/, null];
}
response = AvoEventSpecFetcher.parseEventSpecResponse(wireResponse);
return [2 /*return*/, response];
case 3:
error_1 = _a.sent();
if (this.shouldLog) {
console.error("[Avo Inspector] Error fetching event spec for: ".concat(params.eventName), error_1);
}
return [2 /*return*/, null];
case 4: return [2 /*return*/];
}
});
});
};
/** Builds the complete URL with query parameters. */
AvoEventSpecFetcher.prototype.buildUrl = function (params) {
var queryParams = new URLSearchParams({
apiKey: params.apiKey,
streamId: params.streamId,
eventName: params.eventName,
});
return "".concat(this.baseUrl, "/trackingPlan/eventSpec?").concat(queryParams.toString());
};
/**
* Makes an HTTP GET request using global fetch (available in React Native).
* Returns the parsed JSON response or null on failure.
*/
AvoEventSpecFetcher.prototype.makeRequest = function (url) {
return __awaiter(this, void 0, void 0, function () {
var controller, timeoutId, response, json, parseError_1, error_2;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
controller = new AbortController();
timeoutId = setTimeout(function () { return controller.abort(); }, this.timeout);
_a.label = 1;
case 1:
_a.trys.push([1, 7, , 8]);
return [4 /*yield*/, fetch(url, {
method: "GET",
signal: controller.signal,
})];
case 2:
response = _a.sent();
clearTimeout(timeoutId);
if (response.status !== 200) {
if (this.shouldLog) {
console.warn("[Avo Inspector] Request failed with status: ".concat(response.status));
}
return [2 /*return*/, null];
}
_a.label = 3;
case 3:
_a.trys.push([3, 5, , 6]);
return [4 /*yield*/, response.json()];
case 4:
json = _a.sent();
return [2 /*return*/, json];
case 5:
parseError_1 = _a.sent();
if (this.shouldLog) {
console.error("[Avo Inspector] Failed to parse response:", parseError_1);
}
return [2 /*return*/, null];
case 6: return [3 /*break*/, 8];
case 7:
error_2 = _a.sent();
clearTimeout(timeoutId);
if (error_2 && error_2.name === "AbortError") {
if (this.shouldLog) {
console.error("[Avo Inspector] Request timed out after ".concat(this.timeout, "ms"));
}
}
else {
if (this.shouldLog) {
console.error("[Avo Inspector] Network error occurred");
}
}
return [2 /*return*/, null];
case 8: return [2 /*return*/];
}
});
});
};
/**
* Basic shape check for wire format - ensures response has the minimum expected structure.
* Uses short field names from wire format.
*/
AvoEventSpecFetcher.prototype.hasExpectedShape = function (response) {
return (response &&
typeof response === "object" &&
Array.isArray(response.events) &&
response.metadata &&
typeof response.metadata === "object" &&
typeof response.metadata.schemaId === "string" &&
typeof response.metadata.branchId === "string" &&
typeof response.metadata.latestActionId === "string");
};
/** Parses the wire format response into internal format with meaningful field names. */
AvoEventSpecFetcher.parseEventSpecResponse = function (wire) {
return {
events: wire.events.map(AvoEventSpecFetcher.parseEventSpecEntry),
metadata: wire.metadata,
};
};
/** Parses a single event spec entry from wire format. */
AvoEventSpecFetcher.parseEventSpecEntry = function (wire) {
var props = {};
var wireProps = wire.p || {};
for (var _i = 0, _a = Object.entries(wireProps); _i < _a.length; _i++) {
var entry = _a[_i];
var propName = entry[0];
var propWire = entry[1];
props[propName] = AvoEventSpecFetcher.parsePropertyConstraints(propWire);
}
return {
branchId: wire.b,
baseEventId: wire.id,
variantIds: wire.vids,
props: props,
};
};
/** Parses property constraints from wire format. */
AvoEventSpecFetcher.parsePropertyConstraints = function (wire) {
var result = { type: wire.t, required: wire.r };
if (wire.l) {
result.isList = wire.l;
}
if (wire.p) {
result.pinnedValues = wire.p;
}
if (wire.v) {
result.allowedValues = wire.v;
}
if (wire.rx) {
result.regexPatterns = wire.rx;
}
if (wire.minmax) {
result.minMaxRanges = wire.minmax;
}
if (wire.children) {
result.children = {};
for (var _i = 0, _a = Object.entries(wire.children); _i < _a.length; _i++) {
var _b = _a[_i], propName = _b[0], childWire = _b[1];
result.children[propName] =
AvoEventSpecFetcher.parsePropertyConstraints(childWire);
}
}
return result;
};
return AvoEventSpecFetcher;
}());
exports.AvoEventSpecFetcher = AvoEventSpecFetcher;