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