@anker-in/analysis 0.1.0 → 0.2.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.
Files changed (104) hide show
  1. package/dist/index.cjs +699 -0
  2. package/dist/index.cjs.map +1 -0
  3. package/dist/index.d.mts +387 -0
  4. package/dist/index.d.ts +372 -21
  5. package/dist/index.js +648 -33
  6. package/dist/index.js.map +1 -0
  7. package/package.json +23 -36
  8. package/dist/autoTrack/click.d.ts +0 -2
  9. package/dist/autoTrack/click.d.ts.map +0 -1
  10. package/dist/autoTrack/click.js +0 -80
  11. package/dist/autoTrack/index.d.ts +0 -2
  12. package/dist/autoTrack/index.d.ts.map +0 -1
  13. package/dist/autoTrack/index.js +0 -47
  14. package/dist/autoTrack/pv.d.ts +0 -2
  15. package/dist/autoTrack/pv.d.ts.map +0 -1
  16. package/dist/autoTrack/pv.js +0 -57
  17. package/dist/autoTrack/trackByTags.d.ts +0 -17
  18. package/dist/autoTrack/trackByTags.d.ts.map +0 -1
  19. package/dist/autoTrack/trackByTags.js +0 -141
  20. package/dist/constants/index.d.ts +0 -2
  21. package/dist/constants/index.d.ts.map +0 -1
  22. package/dist/constants/index.js +0 -1
  23. package/dist/constants/tagsMap.d.ts +0 -9
  24. package/dist/constants/tagsMap.d.ts.map +0 -1
  25. package/dist/constants/tagsMap.js +0 -8
  26. package/dist/core/adapters/gtag.d.ts +0 -37
  27. package/dist/core/adapters/gtag.d.ts.map +0 -1
  28. package/dist/core/adapters/gtag.js +0 -55
  29. package/dist/core/adapters/index.d.ts +0 -6
  30. package/dist/core/adapters/index.d.ts.map +0 -1
  31. package/dist/core/adapters/index.js +0 -5
  32. package/dist/core/adapters/meta.d.ts +0 -20
  33. package/dist/core/adapters/meta.d.ts.map +0 -1
  34. package/dist/core/adapters/meta.js +0 -41
  35. package/dist/core/helpers/function-utils.d.ts +0 -17
  36. package/dist/core/helpers/function-utils.d.ts.map +0 -1
  37. package/dist/core/helpers/function-utils.js +0 -43
  38. package/dist/core/helpers/index.d.ts +0 -8
  39. package/dist/core/helpers/index.d.ts.map +0 -1
  40. package/dist/core/helpers/index.js +0 -7
  41. package/dist/core/helpers/logger.d.ts +0 -20
  42. package/dist/core/helpers/logger.d.ts.map +0 -1
  43. package/dist/core/helpers/logger.js +0 -32
  44. package/dist/core/helpers/platform-detector.d.ts +0 -14
  45. package/dist/core/helpers/platform-detector.d.ts.map +0 -1
  46. package/dist/core/helpers/platform-detector.js +0 -28
  47. package/dist/core/helpers/script-loader.d.ts +0 -39
  48. package/dist/core/helpers/script-loader.d.ts.map +0 -1
  49. package/dist/core/helpers/script-loader.js +0 -107
  50. package/dist/core/index.d.ts +0 -7
  51. package/dist/core/index.d.ts.map +0 -1
  52. package/dist/core/index.js +0 -9
  53. package/dist/core/track/gtagTrack.d.ts +0 -2
  54. package/dist/core/track/gtagTrack.d.ts.map +0 -1
  55. package/dist/core/track/gtagTrack.js +0 -12
  56. package/dist/core/track/index.d.ts +0 -4
  57. package/dist/core/track/index.d.ts.map +0 -1
  58. package/dist/core/track/index.js +0 -3
  59. package/dist/core/track/metaTrack.d.ts +0 -2
  60. package/dist/core/track/metaTrack.d.ts.map +0 -1
  61. package/dist/core/track/metaTrack.js +0 -18
  62. package/dist/core/track/track.d.ts +0 -6
  63. package/dist/core/track/track.d.ts.map +0 -1
  64. package/dist/core/track/track.js +0 -128
  65. package/dist/core/tracking/dispatcher.d.ts +0 -10
  66. package/dist/core/tracking/dispatcher.d.ts.map +0 -1
  67. package/dist/core/tracking/dispatcher.js +0 -67
  68. package/dist/core/tracking/index.d.ts +0 -6
  69. package/dist/core/tracking/index.d.ts.map +0 -1
  70. package/dist/core/tracking/index.js +0 -5
  71. package/dist/core/tracking/with-tracking.d.ts +0 -33
  72. package/dist/core/tracking/with-tracking.d.ts.map +0 -1
  73. package/dist/core/tracking/with-tracking.js +0 -137
  74. package/dist/core/utils.d.ts +0 -64
  75. package/dist/core/utils.d.ts.map +0 -1
  76. package/dist/core/utils.js +0 -182
  77. package/dist/index.d.ts.map +0 -1
  78. package/dist/pixels/GtagPixel.d.ts +0 -7
  79. package/dist/pixels/GtagPixel.d.ts.map +0 -1
  80. package/dist/pixels/GtagPixel.js +0 -73
  81. package/dist/pixels/MetaPixel.d.ts +0 -7
  82. package/dist/pixels/MetaPixel.d.ts.map +0 -1
  83. package/dist/pixels/MetaPixel.js +0 -61
  84. package/dist/pixels/PixelsManager.d.ts +0 -5
  85. package/dist/pixels/PixelsManager.d.ts.map +0 -1
  86. package/dist/pixels/PixelsManager.js +0 -17
  87. package/dist/pixels/index.d.ts +0 -4
  88. package/dist/pixels/index.d.ts.map +0 -1
  89. package/dist/pixels/index.js +0 -3
  90. package/dist/types/common.d.ts +0 -66
  91. package/dist/types/common.d.ts.map +0 -1
  92. package/dist/types/common.js +0 -1
  93. package/dist/types/gtag.d.ts +0 -34
  94. package/dist/types/gtag.d.ts.map +0 -1
  95. package/dist/types/gtag.js +0 -1
  96. package/dist/types/index.d.ts +0 -91
  97. package/dist/types/index.d.ts.map +0 -1
  98. package/dist/types/index.js +0 -1
  99. package/dist/types/meta.d.ts +0 -8
  100. package/dist/types/meta.d.ts.map +0 -1
  101. package/dist/types/meta.js +0 -4
  102. package/dist/types/trackByTags.d.ts +0 -26
  103. package/dist/types/trackByTags.d.ts.map +0 -1
  104. package/dist/types/trackByTags.js +0 -4
package/dist/index.js CHANGED
@@ -1,34 +1,649 @@
1
- /**
2
- * Analysis SDK - 埋点 SDK 主入口
3
- *
4
- * 提供统一的埋点接口,支持多平台埋点上报
5
- */
6
- // ============= 核心功能 =============
7
- export { track } from "./core/tracking";
8
- export { gtagTrack } from "./core/adapters";
9
- export { metaTrack } from "./core/adapters";
10
- // ============= 高阶函数 - 无侵入式埋点 =============
11
- export { withTracking, useTracking } from "./core/tracking";
12
- // ============= TrackByTags 功能 =============
13
- export { trackByTags } from "./autoTrack/trackByTags";
14
- // ============= 工具函数 =============
15
- export { logger, isPlatformAvailable, updateScriptType, updateScriptsType, } from "./core/helpers";
16
- // ============= Pixels 组件 =============
17
- export { GtagPixel, MetaPixel, PixelsManager } from "./pixels";
18
- // ============= 常量 =============
19
- export { TrackTagsVersionMap } from "./constants";
20
- // ============= 默认导出 =============
21
- import { track } from "./core/tracking";
22
- import { trackByTags } from "./autoTrack/trackByTags";
23
- import { logger, isPlatformAvailable, updateScriptType, updateScriptsType, } from "./core/helpers";
24
- import { withTracking, useTracking } from "./core/tracking";
25
- export default {
26
- track,
27
- trackByTags,
28
- withTracking,
29
- useTracking,
30
- logger,
31
- isPlatformAvailable,
32
- updateScriptType,
33
- updateScriptsType,
1
+ var __defProp = Object.defineProperty;
2
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
3
+
4
+ // src/core/helpers/logger.ts
5
+ function createLogger(initialEnabled = false) {
6
+ let enabled = initialEnabled;
7
+ return {
8
+ setEnabled(value) {
9
+ enabled = value;
10
+ },
11
+ log(...args) {
12
+ if (enabled) {
13
+ console.log("[Analysis SDK]", ...args);
14
+ }
15
+ },
16
+ warn(...args) {
17
+ if (enabled) {
18
+ console.warn("[Analysis SDK]", ...args);
19
+ }
20
+ },
21
+ error(...args) {
22
+ if (enabled) {
23
+ console.error("[Analysis SDK]", ...args);
24
+ }
25
+ }
26
+ };
27
+ }
28
+ __name(createLogger, "createLogger");
29
+ var logger = createLogger();
30
+
31
+ // src/core/helpers/script-loader.ts
32
+ function updateScriptType(options) {
33
+ const { id, enabled, executeOnEnable = true, onError } = options;
34
+ if (typeof window === "undefined") {
35
+ return false;
36
+ }
37
+ const scriptElement = document.getElementById(id);
38
+ if (!scriptElement) {
39
+ logger.warn(`Script element with id "${id}" not found`);
40
+ return false;
41
+ }
42
+ const newType = enabled ? "text/javascript" : "text/plain";
43
+ const currentType = scriptElement.getAttribute("type");
44
+ if (executeOnEnable && currentType === "text/plain" && newType === "text/javascript") {
45
+ scriptElement.setAttribute("type", newType);
46
+ const scriptContent = scriptElement.innerHTML;
47
+ if (scriptContent && typeof window.eval === "function") {
48
+ try {
49
+ window.eval(scriptContent);
50
+ logger.log(`Script "${id}" executed successfully`);
51
+ } catch (e) {
52
+ const error = e instanceof Error ? e : new Error(String(e));
53
+ logger.error(`Script "${id}" execution error:`, error);
54
+ if (onError) {
55
+ onError(error);
56
+ }
57
+ }
58
+ }
59
+ } else {
60
+ scriptElement.setAttribute("type", newType);
61
+ }
62
+ return true;
63
+ }
64
+ __name(updateScriptType, "updateScriptType");
65
+ function updateScriptsType(scriptIds, enabled, executeOnEnable = true) {
66
+ if (typeof window === "undefined") {
67
+ return 0;
68
+ }
69
+ let successCount = 0;
70
+ const ids = Array.isArray(scriptIds) ? scriptIds : Array.from({ length: 100 }, (_, i) => scriptIds(i)).filter(
71
+ (id) => document.getElementById(id)
72
+ );
73
+ ids.forEach((id) => {
74
+ const success = updateScriptType({
75
+ id,
76
+ enabled,
77
+ executeOnEnable
78
+ });
79
+ if (success) {
80
+ successCount++;
81
+ }
82
+ });
83
+ logger.log(`Updated ${successCount}/${ids.length} scripts`);
84
+ return successCount;
85
+ }
86
+ __name(updateScriptsType, "updateScriptsType");
87
+
88
+ // src/core/helpers/function-utils.ts
89
+ function debounce(fn, delay) {
90
+ let timer = null;
91
+ return function(...args) {
92
+ if (timer) clearTimeout(timer);
93
+ timer = setTimeout(() => {
94
+ fn.apply(this, args);
95
+ }, delay);
96
+ };
97
+ }
98
+ __name(debounce, "debounce");
99
+ function throttle(fn, delay) {
100
+ let lastTime = 0;
101
+ return function(...args) {
102
+ const now = Date.now();
103
+ if (now - lastTime >= delay) {
104
+ lastTime = now;
105
+ fn.apply(this, args);
106
+ }
107
+ };
108
+ }
109
+ __name(throttle, "throttle");
110
+
111
+ // src/core/helpers/platform-detector.ts
112
+ var isPlatformAvailable = /* @__PURE__ */ __name((platform) => {
113
+ if (typeof window === "undefined") {
114
+ return false;
115
+ }
116
+ switch (platform) {
117
+ case "gtag":
118
+ return typeof window.gtag !== "undefined" || typeof window.dataLayer !== "undefined";
119
+ case "meta":
120
+ return typeof window.fbq !== "undefined";
121
+ default:
122
+ return false;
123
+ }
124
+ }, "isPlatformAvailable");
125
+
126
+ // src/core/adapters/gtag.ts
127
+ var gtagTrack = /* @__PURE__ */ __name((command, targetOrEventName, params) => {
128
+ if (typeof window === "undefined") {
129
+ return;
130
+ }
131
+ if (typeof window.gtag !== "function") {
132
+ console.warn("gtag is not available. Please load gtag.js first.");
133
+ return;
134
+ }
135
+ try {
136
+ window.gtag(command, targetOrEventName, params);
137
+ } catch (error) {
138
+ console.error("gtagTrack error:", error);
139
+ }
140
+ }, "gtagTrack");
141
+ var gtagEvent = /* @__PURE__ */ __name((eventName, eventParams) => {
142
+ gtagTrack("event", eventName, eventParams);
143
+ }, "gtagEvent");
144
+ var gtagConfig = /* @__PURE__ */ __name((measurementId, configParams) => {
145
+ gtagTrack("config", measurementId, configParams);
146
+ }, "gtagConfig");
147
+
148
+ // src/core/adapters/meta.ts
149
+ var metaTrack = /* @__PURE__ */ __name((event, data) => {
150
+ if (typeof window === "undefined") {
151
+ return;
152
+ }
153
+ if (typeof window.fbq !== "undefined") {
154
+ try {
155
+ if (data) {
156
+ window.fbq("track", event, data);
157
+ } else {
158
+ window.fbq("track", event);
159
+ }
160
+ } catch (error) {
161
+ console.log("fbqTrack error", error);
162
+ }
163
+ }
164
+ }, "metaTrack");
165
+
166
+ // src/core/tracking/dispatcher.ts
167
+ function track(config) {
168
+ const { platform, ...params } = config;
169
+ if (!isPlatformAvailable(platform)) {
170
+ logger.warn(`Platform ${platform} is not available`);
171
+ return;
172
+ }
173
+ try {
174
+ switch (platform) {
175
+ case "gtag": {
176
+ const gtagParams = params;
177
+ handleGtagTrack(gtagParams);
178
+ break;
179
+ }
180
+ case "meta": {
181
+ const metaParams = params;
182
+ handleMetaTrack(metaParams);
183
+ break;
184
+ }
185
+ default:
186
+ logger.warn(`Unsupported platform: ${platform}`);
187
+ }
188
+ } catch (error) {
189
+ logger.error(`Failed to track on platform ${platform}:`, error);
190
+ }
191
+ }
192
+ __name(track, "track");
193
+ function handleGtagTrack(params) {
194
+ const { eventName, measurementId, ...restParams } = params;
195
+ if (measurementId) {
196
+ gtagConfig(measurementId, {});
197
+ }
198
+ const eventParams = { ...restParams };
199
+ if (eventParams.transactionId && !eventParams.transaction_id) {
200
+ eventParams.transaction_id = eventParams.transactionId;
201
+ delete eventParams.transactionId;
202
+ }
203
+ gtagEvent(eventName, eventParams);
204
+ logger.log(`Gtag conversion tracked: ${eventName}`, eventParams);
205
+ }
206
+ __name(handleGtagTrack, "handleGtagTrack");
207
+ function handleMetaTrack(params) {
208
+ const { event, data } = params;
209
+ if (!event) {
210
+ logger.warn("Meta Pixel event name is required");
211
+ return;
212
+ }
213
+ metaTrack(event, data);
214
+ logger.log(`Meta Pixel event tracked: ${event}`, data);
215
+ }
216
+ __name(handleMetaTrack, "handleMetaTrack");
217
+
218
+ // src/constants/tagsMap.ts
219
+ var TrackTagsVersionMap = {
220
+ "fbq:act": "fbq:atc",
221
+ "gtag:conversion": "gtag:atc"
34
222
  };
223
+
224
+ // src/autoTrack/trackByTags.ts
225
+ function parseTag(tag) {
226
+ const parts = tag.split(":");
227
+ if (parts.length < 2) {
228
+ return null;
229
+ }
230
+ return {
231
+ media: parts[0]?.toLowerCase() || "",
232
+ event: parts[1]?.toLowerCase() || "",
233
+ target: parts[2] || null
234
+ };
235
+ }
236
+ __name(parseTag, "parseTag");
237
+ function adaptEventName(tags) {
238
+ for (let i = 0; i < tags.length; i++) {
239
+ if (!tags[i]) {
240
+ continue;
241
+ }
242
+ for (const [oldEvent, newEvent] of Object.entries(TrackTagsVersionMap)) {
243
+ if (tags[i]?.includes(oldEvent)) {
244
+ tags[i] = tags[i]?.replace(oldEvent, newEvent) ?? "";
245
+ break;
246
+ }
247
+ }
248
+ }
249
+ }
250
+ __name(adaptEventName, "adaptEventName");
251
+ function filterTagsByEvent(tags, eventSymbol) {
252
+ return tags.filter((tag) => {
253
+ const parsed = parseTag(tag);
254
+ return parsed?.event === eventSymbol.toLowerCase();
255
+ });
256
+ }
257
+ __name(filterTagsByEvent, "filterTagsByEvent");
258
+ function handleTagTracking(parsedTag, eventData) {
259
+ const { media, event, target } = parsedTag;
260
+ if (!target) {
261
+ logger.warn(`Tag missing target: ${media}:${event}`);
262
+ return;
263
+ }
264
+ try {
265
+ switch (media) {
266
+ case "fbq":
267
+ case "meta": {
268
+ const config = {
269
+ platform: "meta",
270
+ event: target,
271
+ // target 作为事件名
272
+ data: eventData
273
+ };
274
+ track(config);
275
+ break;
276
+ }
277
+ case "gtag": {
278
+ const config = {
279
+ platform: "gtag",
280
+ eventName: "conversion",
281
+ send_to: target,
282
+ // target 作为转化目标ID
283
+ value: eventData?.value ?? 1,
284
+ currency: eventData?.currency,
285
+ transactionId: eventData?.transactionId
286
+ };
287
+ track(config);
288
+ break;
289
+ }
290
+ default:
291
+ logger.warn(`Unsupported media platform: ${media}`);
292
+ }
293
+ } catch (error) {
294
+ logger.error(`Failed to track tag ${media}:${event}:${target}:`, error);
295
+ }
296
+ }
297
+ __name(handleTagTracking, "handleTagTracking");
298
+ function trackByTags({ tags, data }) {
299
+ if (!tags || tags.length === 0) {
300
+ logger.warn("trackByTags: tags array is empty");
301
+ return;
302
+ }
303
+ if (!data || data.length === 0) {
304
+ logger.warn("trackByTags: data array is empty");
305
+ return;
306
+ }
307
+ const adaptedTags = [...tags];
308
+ adaptEventName(adaptedTags);
309
+ data.forEach((trackData) => {
310
+ const eventSymbol = trackData.event?.toLowerCase();
311
+ if (!eventSymbol) {
312
+ logger.warn("trackByTags: event symbol is missing in trackData");
313
+ return;
314
+ }
315
+ const matchedTags = filterTagsByEvent(adaptedTags, eventSymbol);
316
+ if (matchedTags.length === 0) {
317
+ logger.log(`trackByTags: No tags found for event: ${eventSymbol}`);
318
+ return;
319
+ }
320
+ const { event, ...eventData } = trackData;
321
+ matchedTags.forEach((tag) => {
322
+ const parsed = parseTag(tag);
323
+ if (!parsed) {
324
+ logger.warn(`trackByTags: Invalid tag format: ${tag}`);
325
+ return;
326
+ }
327
+ handleTagTracking(parsed, eventData);
328
+ });
329
+ });
330
+ }
331
+ __name(trackByTags, "trackByTags");
332
+
333
+ // src/core/tracking/with-tracking.ts
334
+ function executeTracking(trackPoint, trackConfig) {
335
+ const configs = Array.isArray(trackConfig) ? trackConfig : [trackConfig ?? {}];
336
+ configs.forEach((config) => {
337
+ try {
338
+ track(config);
339
+ } catch (error) {
340
+ logger.error("withTracking: \u57CB\u70B9\u6267\u884C\u5931\u8D25", error);
341
+ }
342
+ });
343
+ if (typeof window !== "undefined" && !!trackPoint && window.__FUN_TRACK_TAGS__?.[trackPoint ?? ""]?.length > 0) {
344
+ trackByTags({
345
+ tags: window.__FUN_TRACK_TAGS__?.[trackPoint ?? ""] ?? [],
346
+ data: [{ event: "custom" }]
347
+ });
348
+ }
349
+ }
350
+ __name(executeTracking, "executeTracking");
351
+ function withTracking(fn, config) {
352
+ const {
353
+ trackConfig,
354
+ timing = "after",
355
+ condition,
356
+ trackOnError = false,
357
+ errorTrackConfig,
358
+ debounce: debounceTime,
359
+ throttle: throttleTime,
360
+ trackPoint
361
+ } = config;
362
+ function wrappedFunction(...args) {
363
+ if (condition && !condition(args)) {
364
+ return fn(...args);
365
+ }
366
+ const getTrackConfig = /* @__PURE__ */ __name((result) => {
367
+ return typeof trackConfig === "function" ? trackConfig(args, result) : trackConfig;
368
+ }, "getTrackConfig");
369
+ if (timing === "before" || timing === "both") {
370
+ const config2 = getTrackConfig();
371
+ executeTracking(trackPoint, config2);
372
+ }
373
+ try {
374
+ const result = fn(...args);
375
+ if (result instanceof Promise) {
376
+ return result.then((resolvedResult) => {
377
+ if (timing === "after" || timing === "both") {
378
+ const config2 = getTrackConfig(resolvedResult);
379
+ executeTracking(trackPoint, config2);
380
+ }
381
+ return resolvedResult;
382
+ }).catch((error) => {
383
+ if (trackOnError && errorTrackConfig) {
384
+ executeTracking(trackPoint, errorTrackConfig(error, args));
385
+ }
386
+ throw error;
387
+ });
388
+ }
389
+ if (timing === "after" || timing === "both") {
390
+ const config2 = getTrackConfig(result);
391
+ executeTracking(trackPoint, config2);
392
+ }
393
+ return result;
394
+ } catch (error) {
395
+ if (trackOnError && errorTrackConfig) {
396
+ executeTracking(trackPoint, errorTrackConfig(error, args));
397
+ }
398
+ throw error;
399
+ }
400
+ }
401
+ __name(wrappedFunction, "wrappedFunction");
402
+ if (typeof window !== "undefined" && !!trackPoint) {
403
+ const urlParams = new URLSearchParams(window.location.search);
404
+ if (urlParams.has("TRACK_DEV")) {
405
+ return ((...args) => {
406
+ window.open(
407
+ `http://localhost:3002/tracking?trackPoint=${trackPoint}`,
408
+ "_blank"
409
+ );
410
+ });
411
+ }
412
+ }
413
+ if (debounceTime) {
414
+ return debounce(wrappedFunction, debounceTime);
415
+ }
416
+ if (throttleTime) {
417
+ return throttle(wrappedFunction, throttleTime);
418
+ }
419
+ return wrappedFunction;
420
+ }
421
+ __name(withTracking, "withTracking");
422
+ function useTracking(config) {
423
+ return (fn) => {
424
+ return withTracking(fn, config);
425
+ };
426
+ }
427
+ __name(useTracking, "useTracking");
428
+
429
+ // src/pixels/GtagPixel.tsx
430
+ import { useEffect, useRef, useMemo } from "react";
431
+ import Script from "next/script";
432
+ import { Fragment, jsx } from "react/jsx-runtime";
433
+ var GtagPixel = /* @__PURE__ */ __name((props) => {
434
+ const {
435
+ cookieConsentEnabled,
436
+ pixelIds,
437
+ strategy,
438
+ onPixelLoaded,
439
+ ...scriptProps
440
+ } = props;
441
+ const pixelIdsKey = useMemo(() => JSON.stringify(pixelIds), [pixelIds]);
442
+ const pixelIdsArray = useMemo(
443
+ () => Array.isArray(pixelIds) ? pixelIds : [pixelIds],
444
+ [pixelIdsKey]
445
+ );
446
+ const onLoadRef = useRef(onPixelLoaded);
447
+ useEffect(() => {
448
+ onLoadRef.current = onPixelLoaded;
449
+ }, [onPixelLoaded]);
450
+ const initializeGtag = /* @__PURE__ */ __name((pixelId) => {
451
+ try {
452
+ window.dataLayer = window.dataLayer || [];
453
+ if (typeof window.gtag !== "function") {
454
+ window.gtag = /* @__PURE__ */ __name(function gtag() {
455
+ window.dataLayer.push(arguments);
456
+ }, "gtag");
457
+ }
458
+ window.gtag("js", /* @__PURE__ */ new Date());
459
+ window.gtag("config", pixelId, {
460
+ allow_enhanced_conversions: true
461
+ });
462
+ console.log(`\u2705 GtagPixel ${pixelId} initialized`);
463
+ } catch (error) {
464
+ console.error(`Failed to initialize GtagPixel ${pixelId}:`, error);
465
+ }
466
+ }, "initializeGtag");
467
+ useEffect(() => {
468
+ if (!cookieConsentEnabled || typeof window === "undefined") return;
469
+ if (typeof window.gtag !== "undefined" || typeof window.dataLayer !== "undefined") {
470
+ console.log("\u2705 Gtag already available");
471
+ pixelIdsArray.forEach((pixelId) => initializeGtag(pixelId));
472
+ onLoadRef.current?.();
473
+ return;
474
+ }
475
+ const checkScriptLoaded = setInterval(() => {
476
+ if (typeof window.gtag !== "undefined" || typeof window.dataLayer !== "undefined") {
477
+ console.log("\u2705 Gtag became available!");
478
+ clearInterval(checkScriptLoaded);
479
+ pixelIdsArray.forEach((pixelId) => initializeGtag(pixelId));
480
+ onLoadRef.current?.();
481
+ }
482
+ }, 100);
483
+ const timeout = setTimeout(() => {
484
+ clearInterval(checkScriptLoaded);
485
+ console.warn("\u26A0\uFE0F Timeout waiting for gtag");
486
+ }, 5e3);
487
+ return () => {
488
+ clearInterval(checkScriptLoaded);
489
+ clearTimeout(timeout);
490
+ };
491
+ }, [cookieConsentEnabled, pixelIdsArray]);
492
+ return /* @__PURE__ */ jsx(Fragment, { children: pixelIdsArray.length > 0 && pixelIdsArray.map((pixelId, index) => /* @__PURE__ */ jsx(
493
+ Script,
494
+ {
495
+ id: `GtagPixel_${pixelId}_${index}`,
496
+ type: cookieConsentEnabled ? "text/plain" : "text/javascript",
497
+ "data-category": "targeting",
498
+ strategy,
499
+ src: `https://www.googletagmanager.com/gtag/js?id=${pixelId}`,
500
+ onLoad: () => {
501
+ console.log(`\u2705 GtagPixel ${pixelId} loaded from network`);
502
+ initializeGtag(pixelId);
503
+ },
504
+ onError: () => {
505
+ console.error(`\u274C GtagPixel ${pixelId} script load error`);
506
+ },
507
+ ...scriptProps
508
+ },
509
+ pixelId
510
+ )) });
511
+ }, "GtagPixel");
512
+ var GtagPixel_default = GtagPixel;
513
+
514
+ // src/pixels/MetaPixel.tsx
515
+ import { useEffect as useEffect2, useRef as useRef2, useMemo as useMemo2 } from "react";
516
+ import Script2 from "next/script";
517
+ import { Fragment as Fragment2, jsx as jsx2, jsxs } from "react/jsx-runtime";
518
+ var MetaPixel = /* @__PURE__ */ __name((props) => {
519
+ const {
520
+ cookieConsentEnabled,
521
+ pixelIds,
522
+ strategy,
523
+ onPixelLoaded,
524
+ ...scriptProps
525
+ } = props;
526
+ const pixelIdsKey = useMemo2(() => JSON.stringify(pixelIds), [pixelIds]);
527
+ const pixelIdsArray = useMemo2(
528
+ () => Array.isArray(pixelIds) ? pixelIds : [pixelIds],
529
+ [pixelIdsKey]
530
+ );
531
+ const onLoadRef = useRef2(onPixelLoaded);
532
+ useEffect2(() => {
533
+ onLoadRef.current = onPixelLoaded;
534
+ }, [onPixelLoaded]);
535
+ useEffect2(() => {
536
+ if (!cookieConsentEnabled || typeof window === "undefined") return;
537
+ if (typeof window.fbq !== "undefined") {
538
+ console.log("\u2705 window.fbq already available");
539
+ onLoadRef.current?.();
540
+ return;
541
+ }
542
+ const checkScriptLoaded = setInterval(() => {
543
+ if (typeof window.fbq !== "undefined") {
544
+ console.log("\u2705 window.fbq became available!");
545
+ clearInterval(checkScriptLoaded);
546
+ onLoadRef.current?.();
547
+ }
548
+ }, 100);
549
+ const timeout = setTimeout(() => {
550
+ clearInterval(checkScriptLoaded);
551
+ console.warn("\u26A0\uFE0F Timeout waiting for window.fbq");
552
+ }, 5e3);
553
+ return () => {
554
+ clearInterval(checkScriptLoaded);
555
+ clearTimeout(timeout);
556
+ };
557
+ }, [cookieConsentEnabled]);
558
+ return /* @__PURE__ */ jsx2(Fragment2, { children: pixelIdsArray?.length > 0 && // 添加 cookieConsentEnabled 条件
559
+ /* @__PURE__ */ jsxs(Fragment2, { children: [
560
+ /* @__PURE__ */ jsx2(
561
+ Script2,
562
+ {
563
+ id: "MetaPixel",
564
+ strategy,
565
+ type: cookieConsentEnabled ? "text/plain" : "text/javascript",
566
+ "data-category": "targeting",
567
+ src: `https://connect.facebook.net/en_US/fbevents.js`,
568
+ onLoad: () => {
569
+ console.log("\u2705 MetaPixel main script loaded from network");
570
+ },
571
+ onError: () => {
572
+ console.error("\u274C MetaPixel main script load error");
573
+ }
574
+ },
575
+ "MetaPixel"
576
+ ),
577
+ pixelIdsArray.map((pixelId, index) => /* @__PURE__ */ jsx2(
578
+ Script2,
579
+ {
580
+ id: `MetaPixel_${pixelId}_${index}`,
581
+ strategy,
582
+ type: "text/javascript",
583
+ dangerouslySetInnerHTML: {
584
+ __html: `
585
+ !function(f,b,n)
586
+ {if(f.fbq)return;n=f.fbq=function(){n.callMethod?
587
+ n.callMethod.apply(n,arguments):n.queue.push(arguments)};
588
+ if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
589
+ n.queue=[];}(window, document);
590
+ fbq('init', '${pixelId}');
591
+ fbq('track', 'PageView');
592
+ `
593
+ },
594
+ onError: () => {
595
+ console.error(`\u274C MetaPixel ${pixelId} script error`);
596
+ },
597
+ ...scriptProps
598
+ },
599
+ pixelId
600
+ ))
601
+ ] }) });
602
+ }, "MetaPixel");
603
+ var MetaPixel_default = MetaPixel;
604
+
605
+ // src/pixels/PixelsManager.tsx
606
+ import { jsx as jsx3 } from "react/jsx-runtime";
607
+ var PIXEL_COMPONENTS = {
608
+ gtag: GtagPixel_default,
609
+ meta: MetaPixel_default
610
+ };
611
+ var PixelsManager = /* @__PURE__ */ __name((config) => {
612
+ const { type, ...pixelProps } = config;
613
+ const PixelComponent = PIXEL_COMPONENTS[type];
614
+ if (!PixelComponent) {
615
+ return null;
616
+ }
617
+ return /* @__PURE__ */ jsx3(PixelComponent, { ...pixelProps });
618
+ }, "PixelsManager");
619
+ var PixelsManager_default = PixelsManager;
620
+
621
+ // src/index.ts
622
+ var index_default = {
623
+ track,
624
+ trackByTags,
625
+ withTracking,
626
+ useTracking,
627
+ logger,
628
+ isPlatformAvailable,
629
+ updateScriptType,
630
+ updateScriptsType
631
+ };
632
+ export {
633
+ GtagPixel_default as GtagPixel,
634
+ MetaPixel_default as MetaPixel,
635
+ PixelsManager_default as PixelsManager,
636
+ TrackTagsVersionMap,
637
+ index_default as default,
638
+ gtagTrack,
639
+ isPlatformAvailable,
640
+ logger,
641
+ metaTrack,
642
+ track,
643
+ trackByTags,
644
+ updateScriptType,
645
+ updateScriptsType,
646
+ useTracking,
647
+ withTracking
648
+ };
649
+ //# sourceMappingURL=index.js.map