@lark-apaas/observable-web 1.0.0-alpha.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/LICENSE ADDED
@@ -0,0 +1,13 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Lark Technologies Pte. Ltd. and/or its affiliates
4
+
5
+ Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted,provided that the above copyright notice and this permission notice appear in all copies.
6
+
7
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
8
+ IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE
9
+ INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
10
+ EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR
11
+ CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
12
+ DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
13
+ ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
package/README.md ADDED
@@ -0,0 +1 @@
1
+ # @lark-apaas/miaoda-inspector-jsx-runtime
@@ -0,0 +1,33 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __export = (target, all) => {
6
+ for (var name in all)
7
+ __defProp(target, name, { get: all[name], enumerable: true });
8
+ };
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
18
+ var const_exports = {};
19
+ __export(const_exports, {
20
+ AppEnv: () => AppEnv,
21
+ defaultResourceAttr: () => defaultResourceAttr
22
+ });
23
+ module.exports = __toCommonJS(const_exports);
24
+ const defaultResourceAttr = {
25
+ sdk_version: "1.0.1-alpha.18",
26
+ sdk_lang: "web",
27
+ sdk_type: "client-web"
28
+ };
29
+ var AppEnv = /* @__PURE__ */ ((AppEnv2) => {
30
+ AppEnv2["Dev"] = "preview";
31
+ AppEnv2["Prod"] = "runtime";
32
+ return AppEnv2;
33
+ })(AppEnv || {});
@@ -0,0 +1,70 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
20
+ var PvInstrumentation_exports = {};
21
+ __export(PvInstrumentation_exports, {
22
+ PvInstrumentation: () => PvInstrumentation
23
+ });
24
+ module.exports = __toCommonJS(PvInstrumentation_exports);
25
+ var import_getDeviceID = require("../../utils/getDeviceID");
26
+ class PvInstrumentation {
27
+ constructor(meter) {
28
+ __publicField(this, "meter");
29
+ __publicField(this, "lastUrl");
30
+ this.meter = meter;
31
+ }
32
+ /**
33
+ * 开启自动采集
34
+ */
35
+ enable() {
36
+ const pvCounter = this.meter.createCounter("page_view", {
37
+ description: "Count of page views"
38
+ });
39
+ const reportPv = () => {
40
+ const currentUrl = window.location.href;
41
+ if (this.lastUrl === currentUrl) return;
42
+ this.lastUrl = currentUrl;
43
+ pvCounter.add(1, {
44
+ "page_url": window.location.href,
45
+ "page_path": window.location.pathname,
46
+ "page_title": document.title,
47
+ "page_referrer": document.referrer,
48
+ "device_id": (0, import_getDeviceID.getDeviceId)(),
49
+ "user_id": window.userId || "",
50
+ "tenant_id": window.tenantID || "",
51
+ "app_id": window.appId || ""
52
+ });
53
+ };
54
+ window.addEventListener("load", reportPv);
55
+ window.addEventListener("popstate", reportPv);
56
+ this.patchHistory("pushState", reportPv);
57
+ this.patchHistory("replaceState", reportPv);
58
+ }
59
+ /**
60
+ * Monkey Patch 历史记录 API
61
+ */
62
+ patchHistory(type, callback) {
63
+ const original = history[type];
64
+ history[type] = function(...args) {
65
+ const result = original.apply(this, args);
66
+ callback();
67
+ return result;
68
+ };
69
+ }
70
+ }
@@ -0,0 +1,136 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
7
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
8
+ var __spreadValues = (a, b) => {
9
+ for (var prop in b || (b = {}))
10
+ if (__hasOwnProp.call(b, prop))
11
+ __defNormalProp(a, prop, b[prop]);
12
+ if (__getOwnPropSymbols)
13
+ for (var prop of __getOwnPropSymbols(b)) {
14
+ if (__propIsEnum.call(b, prop))
15
+ __defNormalProp(a, prop, b[prop]);
16
+ }
17
+ return a;
18
+ };
19
+ var __export = (target, all) => {
20
+ for (var name in all)
21
+ __defProp(target, name, { get: all[name], enumerable: true });
22
+ };
23
+ var __copyProps = (to, from, except, desc) => {
24
+ if (from && typeof from === "object" || typeof from === "function") {
25
+ for (let key of __getOwnPropNames(from))
26
+ if (!__hasOwnProp.call(to, key) && key !== except)
27
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
28
+ }
29
+ return to;
30
+ };
31
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
32
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
33
+ var __async = (__this, __arguments, generator) => {
34
+ return new Promise((resolve, reject) => {
35
+ var fulfilled = (value) => {
36
+ try {
37
+ step(generator.next(value));
38
+ } catch (e) {
39
+ reject(e);
40
+ }
41
+ };
42
+ var rejected = (value) => {
43
+ try {
44
+ step(generator.throw(value));
45
+ } catch (e) {
46
+ reject(e);
47
+ }
48
+ };
49
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
50
+ step((generator = generator.apply(__this, __arguments)).next());
51
+ });
52
+ };
53
+ var log_exporter_exports = {};
54
+ __export(log_exporter_exports, {
55
+ CustomWebLogExporter: () => CustomWebLogExporter
56
+ });
57
+ module.exports = __toCommonJS(log_exporter_exports);
58
+ var import_core = require("@opentelemetry/core");
59
+ var import_convertAllAttrIntoString = require("../utils/convertAllAttrIntoString");
60
+ var import_hrTimeToNanoNumber = require("../utils/hrTimeToNanoNumber");
61
+ var import_generateUUID = require("../utils/generateUUID");
62
+ var import_const = require("../const");
63
+ class CustomWebLogExporter {
64
+ constructor(config) {
65
+ __publicField(this, "url");
66
+ __publicField(this, "headers");
67
+ __publicField(this, "appEnv");
68
+ this.url = config.url;
69
+ this.appEnv = config.env;
70
+ this.headers = config.headers || {};
71
+ }
72
+ export(logs, resultCallback) {
73
+ const defaultAttributes = {
74
+ uuid: (0, import_generateUUID.generateUUID)(),
75
+ app_env: this.appEnv
76
+ };
77
+ const resourceAttributes = logs.length > 0 ? logs[0].resource.attributes : {};
78
+ const otlpLikePayload = {
79
+ resource: {
80
+ attributes: __spreadValues(__spreadValues({}, resourceAttributes), import_const.defaultResourceAttr)
81
+ },
82
+ logRecords: logs.map((log) => {
83
+ var _a, _b, _c;
84
+ return {
85
+ timeUnixNano: (0, import_hrTimeToNanoNumber.hrTimeToNanosNumber)(log.hrTime),
86
+ observedTimeUnixNano: (0, import_hrTimeToNanoNumber.hrTimeToNanosNumber)(log.hrTimeObserved),
87
+ severityNumber: log.severityNumber,
88
+ severityText: log.severityText,
89
+ body: log.body,
90
+ attributes: (0, import_convertAllAttrIntoString.convertAttributesToString)(__spreadValues(__spreadValues({}, defaultAttributes), (_a = log.attributes) != null ? _a : {})),
91
+ traceID: (_b = log.spanContext) == null ? void 0 : _b.traceId,
92
+ spanID: (_c = log.spanContext) == null ? void 0 : _c.spanId
93
+ };
94
+ })
95
+ };
96
+ this.sendWithFetch({
97
+ logsData: otlpLikePayload
98
+ }, resultCallback);
99
+ }
100
+ /**
101
+ * 封装 Fetch 逻辑
102
+ */
103
+ sendWithFetch(data, callback) {
104
+ const body = JSON.stringify(data);
105
+ fetch(this.url, {
106
+ method: "POST",
107
+ headers: __spreadValues({
108
+ "Content-Type": "application/json"
109
+ }, this.headers),
110
+ body,
111
+ // 关键: keepalive 允许请求在页面关闭后继续发送 (替代 sendBeacon, 避免存在 header 需传递但是 sendBeacon 不支持)
112
+ keepalive: true
113
+ }).then((response) => {
114
+ if (response.ok) {
115
+ callback({ code: import_core.ExportResultCode.SUCCESS });
116
+ } else {
117
+ console.error(`Log export failed: ${response.status} ${response.statusText}`);
118
+ callback({
119
+ code: import_core.ExportResultCode.FAILED,
120
+ error: new Error(`HTTP Status ${response.status}`)
121
+ });
122
+ }
123
+ }).catch((error) => {
124
+ console.error("Log export network error:", error);
125
+ callback({
126
+ code: import_core.ExportResultCode.FAILED,
127
+ error
128
+ });
129
+ });
130
+ }
131
+ shutdown() {
132
+ return __async(this, null, function* () {
133
+ return Promise.resolve();
134
+ });
135
+ }
136
+ }
@@ -0,0 +1,218 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
7
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
8
+ var __spreadValues = (a, b) => {
9
+ for (var prop in b || (b = {}))
10
+ if (__hasOwnProp.call(b, prop))
11
+ __defNormalProp(a, prop, b[prop]);
12
+ if (__getOwnPropSymbols)
13
+ for (var prop of __getOwnPropSymbols(b)) {
14
+ if (__propIsEnum.call(b, prop))
15
+ __defNormalProp(a, prop, b[prop]);
16
+ }
17
+ return a;
18
+ };
19
+ var __export = (target, all) => {
20
+ for (var name in all)
21
+ __defProp(target, name, { get: all[name], enumerable: true });
22
+ };
23
+ var __copyProps = (to, from, except, desc) => {
24
+ if (from && typeof from === "object" || typeof from === "function") {
25
+ for (let key of __getOwnPropNames(from))
26
+ if (!__hasOwnProp.call(to, key) && key !== except)
27
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
28
+ }
29
+ return to;
30
+ };
31
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
32
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
33
+ var __async = (__this, __arguments, generator) => {
34
+ return new Promise((resolve, reject) => {
35
+ var fulfilled = (value) => {
36
+ try {
37
+ step(generator.next(value));
38
+ } catch (e) {
39
+ reject(e);
40
+ }
41
+ };
42
+ var rejected = (value) => {
43
+ try {
44
+ step(generator.throw(value));
45
+ } catch (e) {
46
+ reject(e);
47
+ }
48
+ };
49
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
50
+ step((generator = generator.apply(__this, __arguments)).next());
51
+ });
52
+ };
53
+ var metric_exporter_exports = {};
54
+ __export(metric_exporter_exports, {
55
+ CustomWebMetricExporter: () => CustomWebMetricExporter
56
+ });
57
+ module.exports = __toCommonJS(metric_exporter_exports);
58
+ var import_sdk_metrics = require("@opentelemetry/sdk-metrics");
59
+ var import_core = require("@opentelemetry/core");
60
+ var import_types = require("../types");
61
+ var import_convertAllAttrIntoString = require("../utils/convertAllAttrIntoString");
62
+ var import_hrTimeToNanoNumber = require("../utils/hrTimeToNanoNumber");
63
+ class CustomWebMetricExporter {
64
+ constructor(config) {
65
+ __publicField(this, "url");
66
+ __publicField(this, "headers");
67
+ __publicField(this, "_shutdown", false);
68
+ this.url = config.url;
69
+ this.headers = config.headers || {};
70
+ }
71
+ export(metrics, resultCallback) {
72
+ if (this._shutdown) {
73
+ resultCallback({ code: import_core.ExportResultCode.FAILED, error: new Error("Exporter is shutdown") });
74
+ return;
75
+ }
76
+ try {
77
+ const payload = this.transform(metrics);
78
+ if (!payload.metrics || payload.metrics.length === 0) {
79
+ resultCallback({ code: import_core.ExportResultCode.SUCCESS });
80
+ return;
81
+ }
82
+ this.send(payload, resultCallback);
83
+ } catch (err) {
84
+ console.error("Transform metrics failed:", err);
85
+ resultCallback({ code: import_core.ExportResultCode.FAILED, error: err });
86
+ }
87
+ }
88
+ /**
89
+ * 将 OTel ResourceMetrics 转换为目标 MetricsData
90
+ */
91
+ transform(resourceMetrics) {
92
+ var _a;
93
+ const targetMetrics = [];
94
+ for (const scopeMetrics of resourceMetrics.scopeMetrics) {
95
+ const scopeName = scopeMetrics.scope.name;
96
+ for (const metric of scopeMetrics.metrics) {
97
+ const targetMetric = {
98
+ name: metric.descriptor.name,
99
+ description: metric.descriptor.description,
100
+ unit: metric.descriptor.unit,
101
+ scopeName
102
+ };
103
+ switch (metric.dataPointType) {
104
+ case import_sdk_metrics.DataPointType.SUM:
105
+ targetMetric.sum = {
106
+ aggregationTemporality: this.mapTemporality(metric.aggregationTemporality),
107
+ isMonotonic: (_a = metric.isMonotonic) != null ? _a : true,
108
+ dataPoints: this.transformNumberDataPoints(metric.dataPoints)
109
+ };
110
+ break;
111
+ case import_sdk_metrics.DataPointType.GAUGE:
112
+ targetMetric.gauge = {
113
+ dataPoints: this.transformNumberDataPoints(metric.dataPoints)
114
+ };
115
+ break;
116
+ case import_sdk_metrics.DataPointType.HISTOGRAM:
117
+ targetMetric.histogram = {
118
+ aggregationTemporality: this.mapTemporality(metric.aggregationTemporality),
119
+ dataPoints: this.transformHistogramDataPoints(metric.dataPoints)
120
+ };
121
+ break;
122
+ }
123
+ targetMetrics.push(targetMetric);
124
+ }
125
+ }
126
+ return {
127
+ resource: {
128
+ attributes: (0, import_convertAllAttrIntoString.convertAttributesToString)(resourceMetrics.resource.attributes)
129
+ },
130
+ metrics: targetMetrics
131
+ };
132
+ }
133
+ /**
134
+ * 转换数值型数据点 (Sum / Gauge)
135
+ */
136
+ transformNumberDataPoints(dataPoints) {
137
+ return dataPoints.map((dp) => ({
138
+ attributes: (0, import_convertAllAttrIntoString.convertAttributesToString)(dp.attributes),
139
+ startTimeUnixNano: (0, import_hrTimeToNanoNumber.hrTimeToNanosNumber)(dp.startTime),
140
+ timeUnixNano: (0, import_hrTimeToNanoNumber.hrTimeToNanosNumber)(dp.endTime),
141
+ // JS 中所有数字都是双精度浮点数,默认映射到 asDouble
142
+ // 如果需要 asInt,需要自行判断 Number.isInteger(dp.value)
143
+ asDouble: dp.value
144
+ }));
145
+ }
146
+ /**
147
+ * 转换直方图数据点
148
+ */
149
+ transformHistogramDataPoints(dataPoints) {
150
+ return dataPoints.map((dp) => {
151
+ return {
152
+ attributes: (0, import_convertAllAttrIntoString.convertAttributesToString)(dp.attributes),
153
+ startTimeUnixNano: (0, import_hrTimeToNanoNumber.hrTimeToNanosNumber)(dp.startTime),
154
+ timeUnixNano: (0, import_hrTimeToNanoNumber.hrTimeToNanosNumber)(dp.endTime),
155
+ count: dp.value.count,
156
+ sum: dp.value.sum,
157
+ min: dp.value.min,
158
+ max: dp.value.max,
159
+ bucketCounts: dp.value.buckets.counts,
160
+ explicitBounds: dp.value.buckets.boundaries
161
+ };
162
+ });
163
+ }
164
+ /**
165
+ * 映射聚合时间枚举
166
+ */
167
+ mapTemporality(temp) {
168
+ switch (temp) {
169
+ case import_sdk_metrics.AggregationTemporality.DELTA:
170
+ return import_types.AggregationTemporality.AGGREGATION_TEMPORALITY_DELTA;
171
+ case import_sdk_metrics.AggregationTemporality.CUMULATIVE:
172
+ return import_types.AggregationTemporality.AGGREGATION_TEMPORALITY_CUMULATIVE;
173
+ default:
174
+ return import_types.AggregationTemporality.AGGREGATION_TEMPORALITY_UNSPECIFIED;
175
+ }
176
+ }
177
+ /**
178
+ * 强制使用 Cumulative 模式 (Web 端通常推荐)
179
+ */
180
+ forceFlush() {
181
+ return Promise.resolve();
182
+ }
183
+ selectAggregationTemporality(_instrumentType) {
184
+ return import_sdk_metrics.AggregationTemporality.CUMULATIVE;
185
+ }
186
+ shutdown() {
187
+ return __async(this, null, function* () {
188
+ this._shutdown = true;
189
+ return Promise.resolve();
190
+ });
191
+ }
192
+ /**
193
+ * 发送逻辑
194
+ */
195
+ send(data, callback) {
196
+ const body = JSON.stringify({ metricsData: data });
197
+ fetch(this.url, {
198
+ method: "POST",
199
+ headers: __spreadValues({
200
+ "Content-Type": "application/json"
201
+ }, this.headers),
202
+ body,
203
+ keepalive: true
204
+ // 关键:防止页面跳转丢失数据
205
+ }).then((res) => {
206
+ if (res.ok) {
207
+ callback({ code: import_core.ExportResultCode.SUCCESS });
208
+ } else {
209
+ callback({
210
+ code: import_core.ExportResultCode.FAILED,
211
+ error: new Error(`HTTP ${res.status} ${res.statusText}`)
212
+ });
213
+ }
214
+ }).catch((err) => {
215
+ callback({ code: import_core.ExportResultCode.FAILED, error: err });
216
+ });
217
+ }
218
+ }
@@ -0,0 +1,60 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
7
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
8
+ var __spreadValues = (a, b) => {
9
+ for (var prop in b || (b = {}))
10
+ if (__hasOwnProp.call(b, prop))
11
+ __defNormalProp(a, prop, b[prop]);
12
+ if (__getOwnPropSymbols)
13
+ for (var prop of __getOwnPropSymbols(b)) {
14
+ if (__propIsEnum.call(b, prop))
15
+ __defNormalProp(a, prop, b[prop]);
16
+ }
17
+ return a;
18
+ };
19
+ var __export = (target, all) => {
20
+ for (var name in all)
21
+ __defProp(target, name, { get: all[name], enumerable: true });
22
+ };
23
+ var __copyProps = (to, from, except, desc) => {
24
+ if (from && typeof from === "object" || typeof from === "function") {
25
+ for (let key of __getOwnPropNames(from))
26
+ if (!__hasOwnProp.call(to, key) && key !== except)
27
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
28
+ }
29
+ return to;
30
+ };
31
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
32
+ var resource_detector_exports = {};
33
+ __export(resource_detector_exports, {
34
+ CustomWebDetector: () => CustomWebDetector
35
+ });
36
+ module.exports = __toCommonJS(resource_detector_exports);
37
+ class CustomWebDetector {
38
+ /**
39
+ * 核心探测方法
40
+ * @param config 探测配置(通常用不到,但接口要求)
41
+ */
42
+ detect(config) {
43
+ const browserAttributes = {
44
+ "browser_language": navigator.language,
45
+ "page_url": window.location.href,
46
+ "page_referrer": document.referrer
47
+ };
48
+ const appId = window.appId || "";
49
+ const tenantId = window.tenantID || "";
50
+ const userId = window.userId || "";
51
+ const appAttributes = {
52
+ app_id: appId,
53
+ tenant_id: tenantId,
54
+ user_id: userId
55
+ };
56
+ return {
57
+ attributes: __spreadValues(__spreadValues({}, browserAttributes), appAttributes)
58
+ };
59
+ }
60
+ }
@@ -0,0 +1,157 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
20
+ var __async = (__this, __arguments, generator) => {
21
+ return new Promise((resolve, reject) => {
22
+ var fulfilled = (value) => {
23
+ try {
24
+ step(generator.next(value));
25
+ } catch (e) {
26
+ reject(e);
27
+ }
28
+ };
29
+ var rejected = (value) => {
30
+ try {
31
+ step(generator.throw(value));
32
+ } catch (e) {
33
+ reject(e);
34
+ }
35
+ };
36
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
37
+ step((generator = generator.apply(__this, __arguments)).next());
38
+ });
39
+ };
40
+ var sdk_exports = {};
41
+ __export(sdk_exports, {
42
+ WebObservableSdk: () => WebObservableSdk,
43
+ observable: () => observable
44
+ });
45
+ module.exports = __toCommonJS(sdk_exports);
46
+ var import_resources = require("@opentelemetry/resources");
47
+ var import_sdk_logs = require("@opentelemetry/sdk-logs");
48
+ var import_exporter_logs_otlp_http = require("@opentelemetry/exporter-logs-otlp-http");
49
+ var import_sdk_metrics = require("@opentelemetry/sdk-metrics");
50
+ var import_resource_detector = require("./resource-detector");
51
+ var import_metric_exporter = require("./metric-exporter");
52
+ var import_PvInstrumentation = require("./instrumentation/PvInstrumentation");
53
+ const _WebObservableSdk = class _WebObservableSdk {
54
+ constructor() {
55
+ __publicField(this, "loggerProvider");
56
+ __publicField(this, "meterProvider");
57
+ __publicField(this, "logger");
58
+ __publicField(this, "meter");
59
+ __publicField(this, "resource");
60
+ __publicField(this, "config");
61
+ __publicField(this, "isStarted", false);
62
+ }
63
+ static get instance() {
64
+ if (!this._instance) {
65
+ this._instance = new _WebObservableSdk();
66
+ }
67
+ return this._instance;
68
+ }
69
+ start(config) {
70
+ if (this.isStarted) return;
71
+ this.config = config;
72
+ try {
73
+ this.resource = (0, import_resources.detectResources)({
74
+ detectors: [new import_resource_detector.CustomWebDetector()]
75
+ });
76
+ this.initLogs();
77
+ this.initMetrics();
78
+ this.initAutoPv();
79
+ this.isStarted = true;
80
+ } catch (error) {
81
+ console.error("Failed to start WebObservableSdk:", error);
82
+ }
83
+ }
84
+ // --- 初始化日志模块 ---
85
+ initLogs() {
86
+ var _a;
87
+ if (!((_a = this.config) == null ? void 0 : _a.collectorUrl.log)) return;
88
+ const exporter = new import_exporter_logs_otlp_http.OTLPLogExporter({
89
+ url: this.config.collectorUrl.log
90
+ });
91
+ this.loggerProvider = new import_sdk_logs.LoggerProvider({
92
+ resource: this.resource,
93
+ processors: [
94
+ new import_sdk_logs.BatchLogRecordProcessor(exporter, {
95
+ scheduledDelayMillis: 5e3,
96
+ maxExportBatchSize: 5
97
+ })
98
+ ].filter(Boolean)
99
+ });
100
+ this.logger = this.loggerProvider.getLogger("web-logger");
101
+ }
102
+ // --- 初始化指标模块 ---
103
+ initMetrics() {
104
+ var _a, _b;
105
+ if (!((_a = this.config) == null ? void 0 : _a.collectorUrl.metric)) return;
106
+ const exporter = new import_metric_exporter.CustomWebMetricExporter({
107
+ url: (_b = this.config) == null ? void 0 : _b.collectorUrl.metric
108
+ });
109
+ this.meterProvider = new import_sdk_metrics.MeterProvider({
110
+ resource: this.resource,
111
+ readers: [
112
+ // 定期读取并上报
113
+ new import_sdk_metrics.PeriodicExportingMetricReader({
114
+ exporter,
115
+ exportIntervalMillis: 1e4
116
+ // 10秒一次
117
+ })
118
+ ]
119
+ });
120
+ this.meter = this.meterProvider.getMeter("web-meter");
121
+ }
122
+ initAutoPv() {
123
+ var _a;
124
+ const meter = (_a = this.meterProvider) == null ? void 0 : _a.getMeter("web-sdk-pv-instrumentation");
125
+ if (!meter) return;
126
+ const pvTracker = new import_PvInstrumentation.PvInstrumentation(meter);
127
+ pvTracker.enable();
128
+ }
129
+ // --- 公开 API: 日志(Log) ---
130
+ log(level, message, attributes = {}) {
131
+ this.logger.emit({
132
+ severityText: level,
133
+ body: message,
134
+ attributes,
135
+ timestamp: /* @__PURE__ */ new Date()
136
+ });
137
+ }
138
+ // --- 公开 API: 计数器 (Metric) ---
139
+ addCount(name, value = 1, attributes = {}) {
140
+ const counter = this.meter.createCounter(name);
141
+ counter.add(value, attributes);
142
+ }
143
+ // --- 关键: 页面关闭时的清理 ---
144
+ // 必须处理 visibilitychange 或 beforeunload 事件手动 flush
145
+ shutdown() {
146
+ return __async(this, null, function* () {
147
+ var _a, _b;
148
+ yield Promise.all([
149
+ (_a = this.loggerProvider) == null ? void 0 : _a.shutdown(),
150
+ (_b = this.meterProvider) == null ? void 0 : _b.shutdown()
151
+ ]);
152
+ });
153
+ }
154
+ };
155
+ __publicField(_WebObservableSdk, "_instance");
156
+ let WebObservableSdk = _WebObservableSdk;
157
+ const observable = WebObservableSdk.instance;
@@ -0,0 +1,25 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __export = (target, all) => {
6
+ for (var name in all)
7
+ __defProp(target, name, { get: all[name], enumerable: true });
8
+ };
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
18
+ var index_exports = {};
19
+ __export(index_exports, {
20
+ AppEnv: () => import_const.AppEnv,
21
+ observable: () => import_sdk.observable
22
+ });
23
+ module.exports = __toCommonJS(index_exports);
24
+ var import_sdk = require("./core/sdk");
25
+ var import_const = require("./const");
@@ -0,0 +1,28 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __export = (target, all) => {
6
+ for (var name in all)
7
+ __defProp(target, name, { get: all[name], enumerable: true });
8
+ };
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
18
+ var types_exports = {};
19
+ __export(types_exports, {
20
+ AggregationTemporality: () => AggregationTemporality
21
+ });
22
+ module.exports = __toCommonJS(types_exports);
23
+ var AggregationTemporality = /* @__PURE__ */ ((AggregationTemporality2) => {
24
+ AggregationTemporality2[AggregationTemporality2["AGGREGATION_TEMPORALITY_UNSPECIFIED"] = 0] = "AGGREGATION_TEMPORALITY_UNSPECIFIED";
25
+ AggregationTemporality2[AggregationTemporality2["AGGREGATION_TEMPORALITY_DELTA"] = 1] = "AGGREGATION_TEMPORALITY_DELTA";
26
+ AggregationTemporality2[AggregationTemporality2["AGGREGATION_TEMPORALITY_CUMULATIVE"] = 2] = "AGGREGATION_TEMPORALITY_CUMULATIVE";
27
+ return AggregationTemporality2;
28
+ })(AggregationTemporality || {});
@@ -0,0 +1,36 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __export = (target, all) => {
6
+ for (var name in all)
7
+ __defProp(target, name, { get: all[name], enumerable: true });
8
+ };
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
18
+ var convertAllAttrIntoString_exports = {};
19
+ __export(convertAllAttrIntoString_exports, {
20
+ convertAttributesToString: () => convertAttributesToString
21
+ });
22
+ module.exports = __toCommonJS(convertAllAttrIntoString_exports);
23
+ const safeStringify = (obj) => {
24
+ try {
25
+ return JSON.stringify(obj);
26
+ } catch (error) {
27
+ return "\u3010Observable SDK\u3011Stringify Error";
28
+ }
29
+ };
30
+ function convertAttributesToString(attributes) {
31
+ const result = {};
32
+ for (const [key, value] of Object.entries(attributes)) {
33
+ result[key] = value !== void 0 && value !== null ? typeof value === "object" ? safeStringify(value) : String(value) : "";
34
+ }
35
+ return result;
36
+ }
@@ -0,0 +1,34 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __export = (target, all) => {
6
+ for (var name in all)
7
+ __defProp(target, name, { get: all[name], enumerable: true });
8
+ };
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
18
+ var generateUUID_exports = {};
19
+ __export(generateUUID_exports, {
20
+ generateUUID: () => generateUUID
21
+ });
22
+ module.exports = __toCommonJS(generateUUID_exports);
23
+ const generateUUID = () => {
24
+ if (typeof crypto !== "undefined" && crypto.getRandomValues) {
25
+ const bytes = new Uint8Array(8);
26
+ crypto.getRandomValues(bytes);
27
+ return Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("");
28
+ }
29
+ let result = "";
30
+ for (let i = 0; i < 16; i++) {
31
+ result += Math.floor(Math.random() * 16).toString(16);
32
+ }
33
+ return result;
34
+ };
@@ -0,0 +1,32 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __export = (target, all) => {
6
+ for (var name in all)
7
+ __defProp(target, name, { get: all[name], enumerable: true });
8
+ };
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
18
+ var getDeviceID_exports = {};
19
+ __export(getDeviceID_exports, {
20
+ getDeviceId: () => getDeviceId
21
+ });
22
+ module.exports = __toCommonJS(getDeviceID_exports);
23
+ var import_generateUUID = require("./generateUUID");
24
+ const STORAGE_KEY = "x_sdk_device_id";
25
+ const getDeviceId = () => {
26
+ let id = localStorage.getItem(STORAGE_KEY);
27
+ if (!id) {
28
+ id = (0, import_generateUUID.generateUUID)();
29
+ localStorage.setItem(STORAGE_KEY, id);
30
+ }
31
+ return id;
32
+ };
@@ -0,0 +1,28 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __export = (target, all) => {
6
+ for (var name in all)
7
+ __defProp(target, name, { get: all[name], enumerable: true });
8
+ };
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
18
+ var hrTimeToNanoNumber_exports = {};
19
+ __export(hrTimeToNanoNumber_exports, {
20
+ hrTimeToNanosNumber: () => hrTimeToNanosNumber
21
+ });
22
+ module.exports = __toCommonJS(hrTimeToNanoNumber_exports);
23
+ function hrTimeToNanosNumber(hrTime) {
24
+ const seconds = Number(hrTime[0]);
25
+ const nanos = Number(hrTime[1]);
26
+ const totalNanos = seconds * 1e9 + nanos;
27
+ return totalNanos;
28
+ }
package/package.json ADDED
@@ -0,0 +1,40 @@
1
+ {
2
+ "name": "@lark-apaas/observable-web",
3
+ "version": "1.0.0-alpha.0",
4
+ "description": "Observable SDK For Web",
5
+ "main": "./dist/lib/index.js",
6
+ "files": [
7
+ "dist"
8
+ ],
9
+ "publishConfig": {
10
+ "access": "public"
11
+ },
12
+ "scripts": {
13
+ "build": "tsup",
14
+ "lint": "eslint . --quiet",
15
+ "test": "vitest",
16
+ "test:cov": "vitest run --coverage",
17
+ "test:update": "vitest run -u",
18
+ "prepublishOnly": "npm run build"
19
+ },
20
+ "dependencies": {
21
+ "@opentelemetry/api": "^1.9.0",
22
+ "@opentelemetry/exporter-logs-otlp-http": "^0.208.0",
23
+ "@opentelemetry/exporter-metrics-otlp-http": "^0.208.0",
24
+ "@opentelemetry/resources": "^2.2.0",
25
+ "@opentelemetry/sdk-logs": "^0.208.0",
26
+ "@opentelemetry/sdk-metrics": "^2.2.0"
27
+ },
28
+ "devDependencies": {
29
+ "@testing-library/react": "^12",
30
+ "@testing-library/react-hooks": "^8",
31
+ "@types/node": "^18.17.18",
32
+ "@types/react": "^17",
33
+ "eslint": "^8",
34
+ "react": "^18"
35
+ },
36
+ "peerDependencies": {
37
+ "react": ">=16.14.0",
38
+ "react-dom": ">=16.14.0"
39
+ }
40
+ }