@arivie/source-mixpanel 0.1.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 +204 -0
- package/README.md +55 -0
- package/dist/index.cjs +344 -0
- package/dist/index.d.cts +91 -0
- package/dist/index.d.ts +91 -0
- package/dist/index.js +325 -0
- package/package.json +41 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
Copyright 2026 Arivie Contributors
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
Apache License
|
|
5
|
+
Version 2.0, January 2004
|
|
6
|
+
http://www.apache.org/licenses/
|
|
7
|
+
|
|
8
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
9
|
+
|
|
10
|
+
1. Definitions.
|
|
11
|
+
|
|
12
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
13
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
14
|
+
|
|
15
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
16
|
+
the copyright owner that is granting the License.
|
|
17
|
+
|
|
18
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
19
|
+
other entities that control, are controlled by, or are under common
|
|
20
|
+
control with that entity. For the purposes of this definition,
|
|
21
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
22
|
+
direction or management of such entity, whether by contract or
|
|
23
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
24
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
25
|
+
|
|
26
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
27
|
+
exercising permissions granted by this License.
|
|
28
|
+
|
|
29
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
30
|
+
including but not limited to software source code, documentation
|
|
31
|
+
source, and configuration files.
|
|
32
|
+
|
|
33
|
+
"Object" form shall mean any form resulting from mechanical
|
|
34
|
+
transformation or translation of a Source form, including but
|
|
35
|
+
not limited to compiled object code, generated documentation,
|
|
36
|
+
and conversions to other media types.
|
|
37
|
+
|
|
38
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
39
|
+
Object form, made available under the License, as indicated by a
|
|
40
|
+
copyright notice that is included in or attached to the work
|
|
41
|
+
(an example is provided in the Appendix below).
|
|
42
|
+
|
|
43
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
44
|
+
form, that is based on (or derived from) the Work and for which the
|
|
45
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
46
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
47
|
+
of this License, Derivative Works shall not include works that remain
|
|
48
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
49
|
+
the Work and Derivative Works thereof.
|
|
50
|
+
|
|
51
|
+
"Contribution" shall mean any work of authorship, including
|
|
52
|
+
the original version of the Work and any modifications or additions
|
|
53
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
54
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
55
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
56
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
57
|
+
means any form of electronic, verbal, or written communication sent
|
|
58
|
+
to the Licensor or its representatives, including but not limited to
|
|
59
|
+
communication on electronic mailing lists, source code control systems,
|
|
60
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
61
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
62
|
+
excluding communication that is conspicuously marked or otherwise
|
|
63
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
64
|
+
|
|
65
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
66
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
67
|
+
subsequently incorporated within the Work.
|
|
68
|
+
|
|
69
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
70
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
71
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
72
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
73
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
74
|
+
Work and such Derivative Works in Source or Object form.
|
|
75
|
+
|
|
76
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
77
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
78
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
79
|
+
(except as stated in this section) patent license to make, have made,
|
|
80
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
81
|
+
where such license applies only to those patent claims licensable
|
|
82
|
+
by such Contributor that are necessarily infringed by their
|
|
83
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
84
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
85
|
+
institute patent litigation against any entity (including a
|
|
86
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
87
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
88
|
+
or contributory patent infringement, then any patent licenses
|
|
89
|
+
granted to You under this License for that Work shall terminate
|
|
90
|
+
as of the date such litigation is filed.
|
|
91
|
+
|
|
92
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
93
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
94
|
+
modifications, and in Source or Object form, provided that You
|
|
95
|
+
meet the following conditions:
|
|
96
|
+
|
|
97
|
+
(a) You must give any other recipients of the Work or
|
|
98
|
+
Derivative Works a copy of this License; and
|
|
99
|
+
|
|
100
|
+
(b) You must cause any modified files to carry prominent notices
|
|
101
|
+
stating that You changed the files; and
|
|
102
|
+
|
|
103
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
104
|
+
that You distribute, all copyright, patent, trademark, and
|
|
105
|
+
attribution notices from the Source form of the Work,
|
|
106
|
+
excluding those notices that do not pertain to any part of
|
|
107
|
+
the Derivative Works; and
|
|
108
|
+
|
|
109
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
110
|
+
distribution, then any Derivative Works that You distribute must
|
|
111
|
+
include a readable copy of the attribution notices contained
|
|
112
|
+
within such NOTICE file, excluding those notices that do not
|
|
113
|
+
pertain to any part of the Derivative Works, in at least one
|
|
114
|
+
of the following places: within a NOTICE text file distributed
|
|
115
|
+
as part of the Derivative Works; within the Source form or
|
|
116
|
+
documentation, if provided along with the Derivative Works; or,
|
|
117
|
+
within a display generated by the Derivative Works, if and
|
|
118
|
+
wherever such third-party notices normally appear. The contents
|
|
119
|
+
of the NOTICE file are for informational purposes only and
|
|
120
|
+
do not modify the License. You may add Your own attribution
|
|
121
|
+
notices within Derivative Works that You distribute, alongside
|
|
122
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
123
|
+
that such additional attribution notices cannot be construed
|
|
124
|
+
as modifying the License.
|
|
125
|
+
|
|
126
|
+
You may add Your own copyright statement to Your modifications and
|
|
127
|
+
may provide additional or different license terms and conditions
|
|
128
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
129
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
130
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
131
|
+
the conditions stated in this License.
|
|
132
|
+
|
|
133
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
134
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
135
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
136
|
+
this License, without any additional terms or conditions.
|
|
137
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
138
|
+
the terms of any separate license agreement you may have executed
|
|
139
|
+
with Licensor regarding such Contributions.
|
|
140
|
+
|
|
141
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
142
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
143
|
+
except as required for reasonable and customary use in describing the
|
|
144
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
145
|
+
|
|
146
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
147
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
148
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
149
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
150
|
+
implied, including, without limitation, any warranties or conditions
|
|
151
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
152
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
153
|
+
appropriateness of using or redistributing the Work and assume any
|
|
154
|
+
risks associated with Your exercise of permissions under this License.
|
|
155
|
+
|
|
156
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
157
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
158
|
+
unless required by applicable law (such as deliberate and grossly
|
|
159
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
160
|
+
liable to You for damages, including any direct, indirect, special,
|
|
161
|
+
incidental, or consequential damages of any character arising as a
|
|
162
|
+
result of this License or out of the use or inability to use the
|
|
163
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
164
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
165
|
+
other commercial damages or losses), even if such Contributor
|
|
166
|
+
has been advised of the possibility of such damages.
|
|
167
|
+
|
|
168
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
169
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
170
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
171
|
+
or other liability obligations and/or rights consistent with this
|
|
172
|
+
License. However, in accepting such obligations, You may act only
|
|
173
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
174
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
175
|
+
defend, and hold each Contributor harmless for any liability
|
|
176
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
177
|
+
of your accepting any such warranty or additional liability.
|
|
178
|
+
|
|
179
|
+
END OF TERMS AND CONDITIONS
|
|
180
|
+
|
|
181
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
182
|
+
|
|
183
|
+
To apply the Apache License to your work, attach the following
|
|
184
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
185
|
+
replaced with your own identifying information. (Don't include
|
|
186
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
187
|
+
comment syntax for the file format. We also recommend that a
|
|
188
|
+
file or class name and description of purpose be included on the
|
|
189
|
+
same "printed page" as the copyright notice for easier
|
|
190
|
+
identification within third-party archives.
|
|
191
|
+
|
|
192
|
+
Copyright [yyyy] [name of copyright owner]
|
|
193
|
+
|
|
194
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
195
|
+
you may not use this file except in compliance with the License.
|
|
196
|
+
You may obtain a copy of the License at
|
|
197
|
+
|
|
198
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
199
|
+
|
|
200
|
+
Unless required by applicable law or agreed to in writing, software
|
|
201
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
202
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
203
|
+
See the License for the specific language governing permissions and
|
|
204
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
# @arivie/source-mixpanel
|
|
2
|
+
|
|
3
|
+
Mixpanel Query API `SourceAdapter` for Arivie (RFC-003 v2 REQ-41).
|
|
4
|
+
|
|
5
|
+
## Usage
|
|
6
|
+
|
|
7
|
+
```ts
|
|
8
|
+
import { mixpanelAdapter } from "@arivie/source-mixpanel";
|
|
9
|
+
|
|
10
|
+
const mixpanel = mixpanelAdapter({
|
|
11
|
+
projectToken: process.env.MIXPANEL_TOKEN!,
|
|
12
|
+
projectId: process.env.MIXPANEL_PROJECT_ID!,
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
// Wire into defineArivie sources (C45):
|
|
16
|
+
// sources: { mixpanel }
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
## Authentication
|
|
20
|
+
|
|
21
|
+
Query API requests use HTTP Basic Auth: the project API secret (or service-account
|
|
22
|
+
credential) as the username with an empty password. See
|
|
23
|
+
[Mixpanel Project Secret](https://developer.mixpanel.com/reference/project-secret).
|
|
24
|
+
|
|
25
|
+
## Read-only tokens
|
|
26
|
+
|
|
27
|
+
On the first `execute()` call, the adapter probes the Import API. If the
|
|
28
|
+
credential can successfully import events, construction fails with a clear error.
|
|
29
|
+
Mixpanel does not expose a dedicated read-only scope endpoint — configure
|
|
30
|
+
query-only tokens in your Mixpanel project settings.
|
|
31
|
+
|
|
32
|
+
## Live tests (HS-5)
|
|
33
|
+
|
|
34
|
+
```bash
|
|
35
|
+
MIXPANEL_TOKEN=... MIXPANEL_PROJECT_ID=... pnpm --filter @arivie/source-mixpanel test
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
When credentials are absent, `test/live.test.ts` is skipped and logs
|
|
39
|
+
`[HS-5] Mixpanel creds missing — running mock-only`. Mock fixtures in
|
|
40
|
+
`test/fixtures/mock-mixpanel-responses.ts` exercise deterministic query paths.
|
|
41
|
+
|
|
42
|
+
## Query shape
|
|
43
|
+
|
|
44
|
+
```ts
|
|
45
|
+
interface MixpanelQuery {
|
|
46
|
+
event?: string;
|
|
47
|
+
aggregate?: "count" | "sum" | "average";
|
|
48
|
+
from_date: string; // yyyy-mm-dd
|
|
49
|
+
to_date: string;
|
|
50
|
+
where?: string;
|
|
51
|
+
on?: string;
|
|
52
|
+
}
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
`compileMetric` is defined for REQ-43; the agent dispatcher lands in Sprint 3 C61.
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,344 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var crypto = require('crypto');
|
|
4
|
+
|
|
5
|
+
// src/adapter.ts
|
|
6
|
+
|
|
7
|
+
// src/compile-metric.ts
|
|
8
|
+
function defaultDateRange() {
|
|
9
|
+
const to = /* @__PURE__ */ new Date();
|
|
10
|
+
const from = new Date(to);
|
|
11
|
+
from.setUTCDate(from.getUTCDate() - 30);
|
|
12
|
+
return {
|
|
13
|
+
from_date: formatDate(from),
|
|
14
|
+
to_date: formatDate(to)
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
function formatDate(d) {
|
|
18
|
+
return d.toISOString().slice(0, 10);
|
|
19
|
+
}
|
|
20
|
+
function compileMetricForMixpanel(opts) {
|
|
21
|
+
const { entity, metric } = opts;
|
|
22
|
+
const measure = entity.measures?.find((m) => m.name === metric);
|
|
23
|
+
if (measure == null) {
|
|
24
|
+
throw new Error(
|
|
25
|
+
`compileMetricForMixpanel: metric '${metric}' not found on entity '${entity.name}'`
|
|
26
|
+
);
|
|
27
|
+
}
|
|
28
|
+
const range = defaultDateRange();
|
|
29
|
+
const sql = measure.sql.toLowerCase();
|
|
30
|
+
let aggregate = "count";
|
|
31
|
+
if (sql.includes("sum(")) {
|
|
32
|
+
aggregate = "sum";
|
|
33
|
+
} else if (sql.includes("avg(") || sql.includes("average")) {
|
|
34
|
+
aggregate = "average";
|
|
35
|
+
}
|
|
36
|
+
const eventDim = entity.dimensions?.find((d) => d.name === "event_name");
|
|
37
|
+
const event = typeof opts.filters?.event_name === "string" ? opts.filters.event_name : typeof opts.filters?.event === "string" ? opts.filters.event : eventDim != null ? void 0 : entity.name;
|
|
38
|
+
const query = {
|
|
39
|
+
...range,
|
|
40
|
+
aggregate,
|
|
41
|
+
...event != null ? { event } : {}
|
|
42
|
+
};
|
|
43
|
+
if (aggregate === "sum") {
|
|
44
|
+
const onDim = entity.dimensions?.find((d) => d.name !== "event_name");
|
|
45
|
+
query.on = onDim?.sql ?? 'properties["$amount"]';
|
|
46
|
+
}
|
|
47
|
+
return { query };
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// src/query.ts
|
|
51
|
+
var READ_ONLY_REQUIRED_MSG = "MixpanelAdapter: read-only API token required; got token with write scope";
|
|
52
|
+
function aggregateToSegmentationType(aggregate) {
|
|
53
|
+
switch (aggregate) {
|
|
54
|
+
case "average":
|
|
55
|
+
return "average";
|
|
56
|
+
case "sum":
|
|
57
|
+
return "general";
|
|
58
|
+
case "count":
|
|
59
|
+
default:
|
|
60
|
+
return "general";
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
function requiresSumEndpoint(query) {
|
|
64
|
+
return query.aggregate === "sum" && query.on != null && query.on !== "";
|
|
65
|
+
}
|
|
66
|
+
function buildSegmentationSearchParams(query, projectId) {
|
|
67
|
+
const params = new URLSearchParams();
|
|
68
|
+
params.set("project_id", projectId);
|
|
69
|
+
if (query.event) {
|
|
70
|
+
params.set("event", query.event);
|
|
71
|
+
}
|
|
72
|
+
params.set("from_date", query.from_date);
|
|
73
|
+
params.set("to_date", query.to_date);
|
|
74
|
+
if (query.where) {
|
|
75
|
+
params.set("where", query.where);
|
|
76
|
+
}
|
|
77
|
+
if (query.on && !requiresSumEndpoint(query)) {
|
|
78
|
+
params.set("on", query.on);
|
|
79
|
+
}
|
|
80
|
+
params.set("type", aggregateToSegmentationType(query.aggregate));
|
|
81
|
+
return params;
|
|
82
|
+
}
|
|
83
|
+
function buildSumSearchParams(query, projectId) {
|
|
84
|
+
const params = new URLSearchParams();
|
|
85
|
+
params.set("project_id", projectId);
|
|
86
|
+
if (query.event) {
|
|
87
|
+
params.set("event", query.event);
|
|
88
|
+
}
|
|
89
|
+
params.set("fromDate", query.from_date);
|
|
90
|
+
params.set("toDate", query.to_date);
|
|
91
|
+
if (query.on) {
|
|
92
|
+
params.set("on", query.on);
|
|
93
|
+
}
|
|
94
|
+
if (query.where) {
|
|
95
|
+
params.set("where", query.where);
|
|
96
|
+
}
|
|
97
|
+
return params;
|
|
98
|
+
}
|
|
99
|
+
function parseSegmentationData(data, eventName) {
|
|
100
|
+
if (data == null || typeof data !== "object") {
|
|
101
|
+
return [];
|
|
102
|
+
}
|
|
103
|
+
const root = data;
|
|
104
|
+
if (root.results && typeof root.results === "object") {
|
|
105
|
+
return Object.entries(root.results).map(([date, value]) => {
|
|
106
|
+
const row = {
|
|
107
|
+
date,
|
|
108
|
+
value: Number(value)
|
|
109
|
+
};
|
|
110
|
+
if (eventName != null) {
|
|
111
|
+
row.event = eventName;
|
|
112
|
+
}
|
|
113
|
+
return row;
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
const series = root.data?.series ?? [];
|
|
117
|
+
const values = root.data?.values ?? {};
|
|
118
|
+
const rows = [];
|
|
119
|
+
for (const [segment, byDate] of Object.entries(values)) {
|
|
120
|
+
for (const date of series) {
|
|
121
|
+
const raw = byDate[date];
|
|
122
|
+
if (raw == null) {
|
|
123
|
+
continue;
|
|
124
|
+
}
|
|
125
|
+
rows.push({
|
|
126
|
+
date,
|
|
127
|
+
value: Number(raw),
|
|
128
|
+
event: eventName ?? segment,
|
|
129
|
+
segment
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
if (rows.length === 0 && eventName != null) {
|
|
134
|
+
const direct = values[eventName];
|
|
135
|
+
if (direct) {
|
|
136
|
+
for (const [date, raw] of Object.entries(direct)) {
|
|
137
|
+
rows.push({ date, value: Number(raw), event: eventName });
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
return rows;
|
|
142
|
+
}
|
|
143
|
+
function sumRowValues(rows) {
|
|
144
|
+
return rows.reduce((acc, r) => acc + r.value, 0);
|
|
145
|
+
}
|
|
146
|
+
function compileMetricQuery(opts) {
|
|
147
|
+
return compileMetricForMixpanel(opts).query;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// src/execute.ts
|
|
151
|
+
function queryApiBaseUrl(region = "mixpanel") {
|
|
152
|
+
return `https://${region}.com/api/query`;
|
|
153
|
+
}
|
|
154
|
+
function importApiBaseUrl(region = "mixpanel") {
|
|
155
|
+
const host = region === "mixpanel" ? "api.mixpanel.com" : `api.${region}.com`;
|
|
156
|
+
return `https://${host}`;
|
|
157
|
+
}
|
|
158
|
+
function basicAuthHeader(projectToken) {
|
|
159
|
+
const encoded = Buffer.from(`${projectToken}:`).toString("base64");
|
|
160
|
+
return `Basic ${encoded}`;
|
|
161
|
+
}
|
|
162
|
+
async function mixpanelGet(config, path, params, signal) {
|
|
163
|
+
const url = `${config.queryBaseUrl}${path}?${params.toString()}`;
|
|
164
|
+
const init = {
|
|
165
|
+
method: "GET",
|
|
166
|
+
headers: {
|
|
167
|
+
Authorization: basicAuthHeader(config.projectToken),
|
|
168
|
+
Accept: "application/json"
|
|
169
|
+
}
|
|
170
|
+
};
|
|
171
|
+
if (signal != null) {
|
|
172
|
+
init.signal = signal;
|
|
173
|
+
}
|
|
174
|
+
const res = await config.fetch(url, init);
|
|
175
|
+
const text = await res.text();
|
|
176
|
+
let body = null;
|
|
177
|
+
if (text.length > 0) {
|
|
178
|
+
try {
|
|
179
|
+
body = JSON.parse(text);
|
|
180
|
+
} catch {
|
|
181
|
+
body = { raw: text };
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
if (!res.ok) {
|
|
185
|
+
const detail = body && typeof body === "object" && "error" in body ? String(body.error) : text.slice(0, 200);
|
|
186
|
+
throw new Error(
|
|
187
|
+
`Mixpanel Query API ${path} failed (${res.status}): ${detail}`
|
|
188
|
+
);
|
|
189
|
+
}
|
|
190
|
+
return body;
|
|
191
|
+
}
|
|
192
|
+
async function probeWriteScope(config) {
|
|
193
|
+
const url = `${config.importBaseUrl}/import?strict=1&project_id=${encodeURIComponent(config.projectId)}`;
|
|
194
|
+
const probeBody = JSON.stringify([
|
|
195
|
+
{
|
|
196
|
+
event: "__arivie_readonly_probe__",
|
|
197
|
+
properties: {
|
|
198
|
+
distinct_id: "__arivie_probe__",
|
|
199
|
+
time: Math.floor(Date.now() / 1e3),
|
|
200
|
+
$insert_id: `arivie-probe-${Date.now()}`
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
]);
|
|
204
|
+
const res = await config.fetch(url, {
|
|
205
|
+
method: "POST",
|
|
206
|
+
headers: {
|
|
207
|
+
Authorization: basicAuthHeader(config.projectToken),
|
|
208
|
+
"Content-Type": "application/json"
|
|
209
|
+
},
|
|
210
|
+
body: probeBody
|
|
211
|
+
});
|
|
212
|
+
if (res.status === 401 || res.status === 403) {
|
|
213
|
+
return false;
|
|
214
|
+
}
|
|
215
|
+
const text = await res.text();
|
|
216
|
+
if (!res.ok) {
|
|
217
|
+
return false;
|
|
218
|
+
}
|
|
219
|
+
try {
|
|
220
|
+
const parsed = JSON.parse(text);
|
|
221
|
+
if (parsed.status === "ok" || parsed.code === 200) {
|
|
222
|
+
return true;
|
|
223
|
+
}
|
|
224
|
+
} catch {
|
|
225
|
+
if (res.ok) {
|
|
226
|
+
return true;
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
return false;
|
|
230
|
+
}
|
|
231
|
+
async function fetchSegmentation(config, query, signal) {
|
|
232
|
+
if (requiresSumEndpoint(query)) {
|
|
233
|
+
const params2 = buildSumSearchParams(query, config.projectId);
|
|
234
|
+
return mixpanelGet(config, "/segmentation/sum", params2, signal);
|
|
235
|
+
}
|
|
236
|
+
const params = buildSegmentationSearchParams(query, config.projectId);
|
|
237
|
+
return mixpanelGet(config, "/segmentation", params, signal);
|
|
238
|
+
}
|
|
239
|
+
async function fetchEventNames(config) {
|
|
240
|
+
const params = new URLSearchParams();
|
|
241
|
+
params.set("project_id", config.projectId);
|
|
242
|
+
params.set("type", "general");
|
|
243
|
+
const body = await mixpanelGet(config, "/events/names", params);
|
|
244
|
+
if (Array.isArray(body)) {
|
|
245
|
+
return body.filter((x) => typeof x === "string");
|
|
246
|
+
}
|
|
247
|
+
return [];
|
|
248
|
+
}
|
|
249
|
+
async function executeMixpanelQuery(config, opts) {
|
|
250
|
+
const startedAt = Date.now();
|
|
251
|
+
const controller = new AbortController();
|
|
252
|
+
const timeout = setTimeout(() => controller.abort(), opts.timeoutMs);
|
|
253
|
+
try {
|
|
254
|
+
const raw = await fetchSegmentation(config, opts.query, controller.signal);
|
|
255
|
+
const parsed = parseSegmentationData(raw, opts.query.event);
|
|
256
|
+
const rows = parsed.map((r) => ({
|
|
257
|
+
date: r.date,
|
|
258
|
+
value: r.value,
|
|
259
|
+
event: r.event ?? opts.query.event,
|
|
260
|
+
segment: r.segment
|
|
261
|
+
}));
|
|
262
|
+
const truncated = rows.length > opts.rowLimit;
|
|
263
|
+
const limited = rows.slice(0, opts.rowLimit);
|
|
264
|
+
return {
|
|
265
|
+
rows: limited,
|
|
266
|
+
rowCount: limited.length,
|
|
267
|
+
durationMs: Date.now() - startedAt,
|
|
268
|
+
truncated
|
|
269
|
+
};
|
|
270
|
+
} finally {
|
|
271
|
+
clearTimeout(timeout);
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
// src/adapter.ts
|
|
276
|
+
function deriveMixpanelAdapterId(projectId, projectToken) {
|
|
277
|
+
const hash = crypto.createHash("sha256").update(projectToken).digest("hex").slice(0, 12);
|
|
278
|
+
return `mixpanel:${projectId}:${hash}`;
|
|
279
|
+
}
|
|
280
|
+
function hashProjectToken(projectToken) {
|
|
281
|
+
return crypto.createHash("sha256").update(projectToken).digest("hex").slice(0, 12);
|
|
282
|
+
}
|
|
283
|
+
function mixpanelAdapter(opts) {
|
|
284
|
+
const region = opts.region ?? "mixpanel";
|
|
285
|
+
const projectId = String(opts.projectId);
|
|
286
|
+
const clientConfig = {
|
|
287
|
+
projectToken: opts.projectToken,
|
|
288
|
+
projectId,
|
|
289
|
+
queryBaseUrl: queryApiBaseUrl(region),
|
|
290
|
+
importBaseUrl: importApiBaseUrl(region),
|
|
291
|
+
fetch: opts.fetch ?? globalThis.fetch
|
|
292
|
+
};
|
|
293
|
+
let introspectCache = null;
|
|
294
|
+
let readOnlyVerified = opts.skipReadOnlyProbe === true;
|
|
295
|
+
async function ensureReadOnly() {
|
|
296
|
+
if (readOnlyVerified) {
|
|
297
|
+
return;
|
|
298
|
+
}
|
|
299
|
+
const writable = await probeWriteScope(clientConfig);
|
|
300
|
+
readOnlyVerified = true;
|
|
301
|
+
if (writable) {
|
|
302
|
+
throw new Error(READ_ONLY_REQUIRED_MSG);
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
return {
|
|
306
|
+
kind: "mixpanel",
|
|
307
|
+
id: deriveMixpanelAdapterId(projectId, opts.projectToken),
|
|
308
|
+
async execute(executeOpts) {
|
|
309
|
+
await ensureReadOnly();
|
|
310
|
+
return executeMixpanelQuery(clientConfig, executeOpts);
|
|
311
|
+
},
|
|
312
|
+
async introspect() {
|
|
313
|
+
if (introspectCache != null) {
|
|
314
|
+
return introspectCache;
|
|
315
|
+
}
|
|
316
|
+
await ensureReadOnly();
|
|
317
|
+
const names = await fetchEventNames(clientConfig);
|
|
318
|
+
introspectCache = names.map((name) => ({ name }));
|
|
319
|
+
return introspectCache;
|
|
320
|
+
},
|
|
321
|
+
async verifyOwnerIdentity() {
|
|
322
|
+
},
|
|
323
|
+
compileMetric: compileMetricForMixpanel
|
|
324
|
+
};
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
exports.READ_ONLY_REQUIRED_MSG = READ_ONLY_REQUIRED_MSG;
|
|
328
|
+
exports.aggregateToSegmentationType = aggregateToSegmentationType;
|
|
329
|
+
exports.basicAuthHeader = basicAuthHeader;
|
|
330
|
+
exports.buildSegmentationSearchParams = buildSegmentationSearchParams;
|
|
331
|
+
exports.buildSumSearchParams = buildSumSearchParams;
|
|
332
|
+
exports.compileMetricForMixpanel = compileMetricForMixpanel;
|
|
333
|
+
exports.compileMetricQuery = compileMetricQuery;
|
|
334
|
+
exports.deriveMixpanelAdapterId = deriveMixpanelAdapterId;
|
|
335
|
+
exports.executeMixpanelQuery = executeMixpanelQuery;
|
|
336
|
+
exports.fetchEventNames = fetchEventNames;
|
|
337
|
+
exports.fetchSegmentation = fetchSegmentation;
|
|
338
|
+
exports.hashProjectToken = hashProjectToken;
|
|
339
|
+
exports.importApiBaseUrl = importApiBaseUrl;
|
|
340
|
+
exports.mixpanelAdapter = mixpanelAdapter;
|
|
341
|
+
exports.parseSegmentationData = parseSegmentationData;
|
|
342
|
+
exports.probeWriteScope = probeWriteScope;
|
|
343
|
+
exports.queryApiBaseUrl = queryApiBaseUrl;
|
|
344
|
+
exports.sumRowValues = sumRowValues;
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { SourceAdapter, SourceAdapterCompileMetricOpts, SourceAdapterExecuteOpts, SourceAdapterExecuteResult } from '@arivie/core/types';
|
|
2
|
+
|
|
3
|
+
/** Segmentation query routed to the Mixpanel Query API. */
|
|
4
|
+
interface MixpanelQuery {
|
|
5
|
+
event?: string;
|
|
6
|
+
aggregate?: "count" | "sum" | "average";
|
|
7
|
+
from_date: string;
|
|
8
|
+
to_date: string;
|
|
9
|
+
where?: string;
|
|
10
|
+
on?: string;
|
|
11
|
+
}
|
|
12
|
+
interface MixpanelAdapterOptions {
|
|
13
|
+
/** Project API secret or service-account credential (HTTP Basic username). */
|
|
14
|
+
projectToken: string;
|
|
15
|
+
projectId: number | string;
|
|
16
|
+
name?: string;
|
|
17
|
+
/** Query API host prefix, e.g. `mixpanel` (US) or `eu.mixpanel`. */
|
|
18
|
+
region?: "mixpanel" | "eu.mixpanel" | "in.mixpanel";
|
|
19
|
+
/** Override for tests — custom fetch implementation. */
|
|
20
|
+
fetch?: typeof globalThis.fetch;
|
|
21
|
+
/** When true, skip the read-only import probe (tests only). */
|
|
22
|
+
skipReadOnlyProbe?: boolean;
|
|
23
|
+
}
|
|
24
|
+
type MixpanelAdapter = SourceAdapter<MixpanelQuery>;
|
|
25
|
+
interface MixpanelEventInfo {
|
|
26
|
+
name: string;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Credential-safe adapter id (RFC-003 v2 §4.7). */
|
|
30
|
+
declare function deriveMixpanelAdapterId(projectId: string | number, projectToken: string): string;
|
|
31
|
+
declare function hashProjectToken(projectToken: string): string;
|
|
32
|
+
/**
|
|
33
|
+
* Mixpanel Query API adapter (RFC-003 v2 REQ-41).
|
|
34
|
+
*
|
|
35
|
+
* Authenticates with HTTP Basic Auth: project token/secret as username, empty
|
|
36
|
+
* password (see Mixpanel Project Secret / Project Token docs).
|
|
37
|
+
*
|
|
38
|
+
* Read-only enforcement probes the Import API on first `execute()` (Mixpanel
|
|
39
|
+
* does not expose a dedicated read-only scope endpoint).
|
|
40
|
+
*/
|
|
41
|
+
declare function mixpanelAdapter(opts: MixpanelAdapterOptions): MixpanelAdapter;
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Compiles a semantic-layer measure on a Mixpanel-bound entity to a Query API payload.
|
|
45
|
+
*/
|
|
46
|
+
declare function compileMetricForMixpanel(opts: SourceAdapterCompileMetricOpts): {
|
|
47
|
+
query: MixpanelQuery;
|
|
48
|
+
params?: unknown[];
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
interface MixpanelClientConfig {
|
|
52
|
+
projectToken: string;
|
|
53
|
+
projectId: string;
|
|
54
|
+
queryBaseUrl: string;
|
|
55
|
+
importBaseUrl: string;
|
|
56
|
+
fetch: typeof globalThis.fetch;
|
|
57
|
+
}
|
|
58
|
+
declare function queryApiBaseUrl(region?: "mixpanel" | "eu.mixpanel" | "in.mixpanel"): string;
|
|
59
|
+
declare function importApiBaseUrl(region?: "mixpanel" | "eu.mixpanel" | "in.mixpanel"): string;
|
|
60
|
+
declare function basicAuthHeader(projectToken: string): string;
|
|
61
|
+
/**
|
|
62
|
+
* Probes the Import API to detect write-capable credentials.
|
|
63
|
+
*
|
|
64
|
+
* Mixpanel does not expose a dedicated "read-only" scope flag on tokens.
|
|
65
|
+
* When import accepts data (HTTP 200 with success), the credential can write.
|
|
66
|
+
* Documented limitation: enforcement depends on the token permissions the
|
|
67
|
+
* consumer configured in Mixpanel project settings.
|
|
68
|
+
*/
|
|
69
|
+
declare function probeWriteScope(config: MixpanelClientConfig): Promise<boolean>;
|
|
70
|
+
declare function fetchSegmentation(config: MixpanelClientConfig, query: MixpanelQuery, signal?: AbortSignal): Promise<unknown>;
|
|
71
|
+
declare function fetchEventNames(config: MixpanelClientConfig): Promise<string[]>;
|
|
72
|
+
declare function executeMixpanelQuery(config: MixpanelClientConfig, opts: SourceAdapterExecuteOpts<MixpanelQuery>): Promise<SourceAdapterExecuteResult<Record<string, unknown>>>;
|
|
73
|
+
|
|
74
|
+
declare const READ_ONLY_REQUIRED_MSG = "MixpanelAdapter: read-only API token required; got token with write scope";
|
|
75
|
+
/** Maps adapter aggregate to Mixpanel segmentation `type`. */
|
|
76
|
+
declare function aggregateToSegmentationType(aggregate: MixpanelQuery["aggregate"] | undefined): "general" | "unique" | "average";
|
|
77
|
+
declare function buildSegmentationSearchParams(query: MixpanelQuery, projectId: string): URLSearchParams;
|
|
78
|
+
declare function buildSumSearchParams(query: MixpanelQuery, projectId: string): URLSearchParams;
|
|
79
|
+
interface SegmentationSeriesRow {
|
|
80
|
+
date: string;
|
|
81
|
+
value: number;
|
|
82
|
+
event?: string;
|
|
83
|
+
segment?: string;
|
|
84
|
+
}
|
|
85
|
+
/** Flattens Mixpanel segmentation JSON into tabular rows. */
|
|
86
|
+
declare function parseSegmentationData(data: unknown, eventName?: string): SegmentationSeriesRow[];
|
|
87
|
+
declare function sumRowValues(rows: SegmentationSeriesRow[]): number;
|
|
88
|
+
/** @deprecated Use {@link compileMetricForMixpanel} from `./compile-metric.js`. */
|
|
89
|
+
declare function compileMetricQuery(opts: Parameters<typeof compileMetricForMixpanel>[0]): MixpanelQuery;
|
|
90
|
+
|
|
91
|
+
export { type MixpanelAdapter, type MixpanelAdapterOptions, type MixpanelClientConfig, type MixpanelEventInfo, type MixpanelQuery, READ_ONLY_REQUIRED_MSG, type SegmentationSeriesRow, aggregateToSegmentationType, basicAuthHeader, buildSegmentationSearchParams, buildSumSearchParams, compileMetricForMixpanel, compileMetricQuery, deriveMixpanelAdapterId, executeMixpanelQuery, fetchEventNames, fetchSegmentation, hashProjectToken, importApiBaseUrl, mixpanelAdapter, parseSegmentationData, probeWriteScope, queryApiBaseUrl, sumRowValues };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { SourceAdapter, SourceAdapterCompileMetricOpts, SourceAdapterExecuteOpts, SourceAdapterExecuteResult } from '@arivie/core/types';
|
|
2
|
+
|
|
3
|
+
/** Segmentation query routed to the Mixpanel Query API. */
|
|
4
|
+
interface MixpanelQuery {
|
|
5
|
+
event?: string;
|
|
6
|
+
aggregate?: "count" | "sum" | "average";
|
|
7
|
+
from_date: string;
|
|
8
|
+
to_date: string;
|
|
9
|
+
where?: string;
|
|
10
|
+
on?: string;
|
|
11
|
+
}
|
|
12
|
+
interface MixpanelAdapterOptions {
|
|
13
|
+
/** Project API secret or service-account credential (HTTP Basic username). */
|
|
14
|
+
projectToken: string;
|
|
15
|
+
projectId: number | string;
|
|
16
|
+
name?: string;
|
|
17
|
+
/** Query API host prefix, e.g. `mixpanel` (US) or `eu.mixpanel`. */
|
|
18
|
+
region?: "mixpanel" | "eu.mixpanel" | "in.mixpanel";
|
|
19
|
+
/** Override for tests — custom fetch implementation. */
|
|
20
|
+
fetch?: typeof globalThis.fetch;
|
|
21
|
+
/** When true, skip the read-only import probe (tests only). */
|
|
22
|
+
skipReadOnlyProbe?: boolean;
|
|
23
|
+
}
|
|
24
|
+
type MixpanelAdapter = SourceAdapter<MixpanelQuery>;
|
|
25
|
+
interface MixpanelEventInfo {
|
|
26
|
+
name: string;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Credential-safe adapter id (RFC-003 v2 §4.7). */
|
|
30
|
+
declare function deriveMixpanelAdapterId(projectId: string | number, projectToken: string): string;
|
|
31
|
+
declare function hashProjectToken(projectToken: string): string;
|
|
32
|
+
/**
|
|
33
|
+
* Mixpanel Query API adapter (RFC-003 v2 REQ-41).
|
|
34
|
+
*
|
|
35
|
+
* Authenticates with HTTP Basic Auth: project token/secret as username, empty
|
|
36
|
+
* password (see Mixpanel Project Secret / Project Token docs).
|
|
37
|
+
*
|
|
38
|
+
* Read-only enforcement probes the Import API on first `execute()` (Mixpanel
|
|
39
|
+
* does not expose a dedicated read-only scope endpoint).
|
|
40
|
+
*/
|
|
41
|
+
declare function mixpanelAdapter(opts: MixpanelAdapterOptions): MixpanelAdapter;
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Compiles a semantic-layer measure on a Mixpanel-bound entity to a Query API payload.
|
|
45
|
+
*/
|
|
46
|
+
declare function compileMetricForMixpanel(opts: SourceAdapterCompileMetricOpts): {
|
|
47
|
+
query: MixpanelQuery;
|
|
48
|
+
params?: unknown[];
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
interface MixpanelClientConfig {
|
|
52
|
+
projectToken: string;
|
|
53
|
+
projectId: string;
|
|
54
|
+
queryBaseUrl: string;
|
|
55
|
+
importBaseUrl: string;
|
|
56
|
+
fetch: typeof globalThis.fetch;
|
|
57
|
+
}
|
|
58
|
+
declare function queryApiBaseUrl(region?: "mixpanel" | "eu.mixpanel" | "in.mixpanel"): string;
|
|
59
|
+
declare function importApiBaseUrl(region?: "mixpanel" | "eu.mixpanel" | "in.mixpanel"): string;
|
|
60
|
+
declare function basicAuthHeader(projectToken: string): string;
|
|
61
|
+
/**
|
|
62
|
+
* Probes the Import API to detect write-capable credentials.
|
|
63
|
+
*
|
|
64
|
+
* Mixpanel does not expose a dedicated "read-only" scope flag on tokens.
|
|
65
|
+
* When import accepts data (HTTP 200 with success), the credential can write.
|
|
66
|
+
* Documented limitation: enforcement depends on the token permissions the
|
|
67
|
+
* consumer configured in Mixpanel project settings.
|
|
68
|
+
*/
|
|
69
|
+
declare function probeWriteScope(config: MixpanelClientConfig): Promise<boolean>;
|
|
70
|
+
declare function fetchSegmentation(config: MixpanelClientConfig, query: MixpanelQuery, signal?: AbortSignal): Promise<unknown>;
|
|
71
|
+
declare function fetchEventNames(config: MixpanelClientConfig): Promise<string[]>;
|
|
72
|
+
declare function executeMixpanelQuery(config: MixpanelClientConfig, opts: SourceAdapterExecuteOpts<MixpanelQuery>): Promise<SourceAdapterExecuteResult<Record<string, unknown>>>;
|
|
73
|
+
|
|
74
|
+
declare const READ_ONLY_REQUIRED_MSG = "MixpanelAdapter: read-only API token required; got token with write scope";
|
|
75
|
+
/** Maps adapter aggregate to Mixpanel segmentation `type`. */
|
|
76
|
+
declare function aggregateToSegmentationType(aggregate: MixpanelQuery["aggregate"] | undefined): "general" | "unique" | "average";
|
|
77
|
+
declare function buildSegmentationSearchParams(query: MixpanelQuery, projectId: string): URLSearchParams;
|
|
78
|
+
declare function buildSumSearchParams(query: MixpanelQuery, projectId: string): URLSearchParams;
|
|
79
|
+
interface SegmentationSeriesRow {
|
|
80
|
+
date: string;
|
|
81
|
+
value: number;
|
|
82
|
+
event?: string;
|
|
83
|
+
segment?: string;
|
|
84
|
+
}
|
|
85
|
+
/** Flattens Mixpanel segmentation JSON into tabular rows. */
|
|
86
|
+
declare function parseSegmentationData(data: unknown, eventName?: string): SegmentationSeriesRow[];
|
|
87
|
+
declare function sumRowValues(rows: SegmentationSeriesRow[]): number;
|
|
88
|
+
/** @deprecated Use {@link compileMetricForMixpanel} from `./compile-metric.js`. */
|
|
89
|
+
declare function compileMetricQuery(opts: Parameters<typeof compileMetricForMixpanel>[0]): MixpanelQuery;
|
|
90
|
+
|
|
91
|
+
export { type MixpanelAdapter, type MixpanelAdapterOptions, type MixpanelClientConfig, type MixpanelEventInfo, type MixpanelQuery, READ_ONLY_REQUIRED_MSG, type SegmentationSeriesRow, aggregateToSegmentationType, basicAuthHeader, buildSegmentationSearchParams, buildSumSearchParams, compileMetricForMixpanel, compileMetricQuery, deriveMixpanelAdapterId, executeMixpanelQuery, fetchEventNames, fetchSegmentation, hashProjectToken, importApiBaseUrl, mixpanelAdapter, parseSegmentationData, probeWriteScope, queryApiBaseUrl, sumRowValues };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,325 @@
|
|
|
1
|
+
import { createHash } from 'crypto';
|
|
2
|
+
|
|
3
|
+
// src/adapter.ts
|
|
4
|
+
|
|
5
|
+
// src/compile-metric.ts
|
|
6
|
+
function defaultDateRange() {
|
|
7
|
+
const to = /* @__PURE__ */ new Date();
|
|
8
|
+
const from = new Date(to);
|
|
9
|
+
from.setUTCDate(from.getUTCDate() - 30);
|
|
10
|
+
return {
|
|
11
|
+
from_date: formatDate(from),
|
|
12
|
+
to_date: formatDate(to)
|
|
13
|
+
};
|
|
14
|
+
}
|
|
15
|
+
function formatDate(d) {
|
|
16
|
+
return d.toISOString().slice(0, 10);
|
|
17
|
+
}
|
|
18
|
+
function compileMetricForMixpanel(opts) {
|
|
19
|
+
const { entity, metric } = opts;
|
|
20
|
+
const measure = entity.measures?.find((m) => m.name === metric);
|
|
21
|
+
if (measure == null) {
|
|
22
|
+
throw new Error(
|
|
23
|
+
`compileMetricForMixpanel: metric '${metric}' not found on entity '${entity.name}'`
|
|
24
|
+
);
|
|
25
|
+
}
|
|
26
|
+
const range = defaultDateRange();
|
|
27
|
+
const sql = measure.sql.toLowerCase();
|
|
28
|
+
let aggregate = "count";
|
|
29
|
+
if (sql.includes("sum(")) {
|
|
30
|
+
aggregate = "sum";
|
|
31
|
+
} else if (sql.includes("avg(") || sql.includes("average")) {
|
|
32
|
+
aggregate = "average";
|
|
33
|
+
}
|
|
34
|
+
const eventDim = entity.dimensions?.find((d) => d.name === "event_name");
|
|
35
|
+
const event = typeof opts.filters?.event_name === "string" ? opts.filters.event_name : typeof opts.filters?.event === "string" ? opts.filters.event : eventDim != null ? void 0 : entity.name;
|
|
36
|
+
const query = {
|
|
37
|
+
...range,
|
|
38
|
+
aggregate,
|
|
39
|
+
...event != null ? { event } : {}
|
|
40
|
+
};
|
|
41
|
+
if (aggregate === "sum") {
|
|
42
|
+
const onDim = entity.dimensions?.find((d) => d.name !== "event_name");
|
|
43
|
+
query.on = onDim?.sql ?? 'properties["$amount"]';
|
|
44
|
+
}
|
|
45
|
+
return { query };
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// src/query.ts
|
|
49
|
+
var READ_ONLY_REQUIRED_MSG = "MixpanelAdapter: read-only API token required; got token with write scope";
|
|
50
|
+
function aggregateToSegmentationType(aggregate) {
|
|
51
|
+
switch (aggregate) {
|
|
52
|
+
case "average":
|
|
53
|
+
return "average";
|
|
54
|
+
case "sum":
|
|
55
|
+
return "general";
|
|
56
|
+
case "count":
|
|
57
|
+
default:
|
|
58
|
+
return "general";
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
function requiresSumEndpoint(query) {
|
|
62
|
+
return query.aggregate === "sum" && query.on != null && query.on !== "";
|
|
63
|
+
}
|
|
64
|
+
function buildSegmentationSearchParams(query, projectId) {
|
|
65
|
+
const params = new URLSearchParams();
|
|
66
|
+
params.set("project_id", projectId);
|
|
67
|
+
if (query.event) {
|
|
68
|
+
params.set("event", query.event);
|
|
69
|
+
}
|
|
70
|
+
params.set("from_date", query.from_date);
|
|
71
|
+
params.set("to_date", query.to_date);
|
|
72
|
+
if (query.where) {
|
|
73
|
+
params.set("where", query.where);
|
|
74
|
+
}
|
|
75
|
+
if (query.on && !requiresSumEndpoint(query)) {
|
|
76
|
+
params.set("on", query.on);
|
|
77
|
+
}
|
|
78
|
+
params.set("type", aggregateToSegmentationType(query.aggregate));
|
|
79
|
+
return params;
|
|
80
|
+
}
|
|
81
|
+
function buildSumSearchParams(query, projectId) {
|
|
82
|
+
const params = new URLSearchParams();
|
|
83
|
+
params.set("project_id", projectId);
|
|
84
|
+
if (query.event) {
|
|
85
|
+
params.set("event", query.event);
|
|
86
|
+
}
|
|
87
|
+
params.set("fromDate", query.from_date);
|
|
88
|
+
params.set("toDate", query.to_date);
|
|
89
|
+
if (query.on) {
|
|
90
|
+
params.set("on", query.on);
|
|
91
|
+
}
|
|
92
|
+
if (query.where) {
|
|
93
|
+
params.set("where", query.where);
|
|
94
|
+
}
|
|
95
|
+
return params;
|
|
96
|
+
}
|
|
97
|
+
function parseSegmentationData(data, eventName) {
|
|
98
|
+
if (data == null || typeof data !== "object") {
|
|
99
|
+
return [];
|
|
100
|
+
}
|
|
101
|
+
const root = data;
|
|
102
|
+
if (root.results && typeof root.results === "object") {
|
|
103
|
+
return Object.entries(root.results).map(([date, value]) => {
|
|
104
|
+
const row = {
|
|
105
|
+
date,
|
|
106
|
+
value: Number(value)
|
|
107
|
+
};
|
|
108
|
+
if (eventName != null) {
|
|
109
|
+
row.event = eventName;
|
|
110
|
+
}
|
|
111
|
+
return row;
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
const series = root.data?.series ?? [];
|
|
115
|
+
const values = root.data?.values ?? {};
|
|
116
|
+
const rows = [];
|
|
117
|
+
for (const [segment, byDate] of Object.entries(values)) {
|
|
118
|
+
for (const date of series) {
|
|
119
|
+
const raw = byDate[date];
|
|
120
|
+
if (raw == null) {
|
|
121
|
+
continue;
|
|
122
|
+
}
|
|
123
|
+
rows.push({
|
|
124
|
+
date,
|
|
125
|
+
value: Number(raw),
|
|
126
|
+
event: eventName ?? segment,
|
|
127
|
+
segment
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
if (rows.length === 0 && eventName != null) {
|
|
132
|
+
const direct = values[eventName];
|
|
133
|
+
if (direct) {
|
|
134
|
+
for (const [date, raw] of Object.entries(direct)) {
|
|
135
|
+
rows.push({ date, value: Number(raw), event: eventName });
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
return rows;
|
|
140
|
+
}
|
|
141
|
+
function sumRowValues(rows) {
|
|
142
|
+
return rows.reduce((acc, r) => acc + r.value, 0);
|
|
143
|
+
}
|
|
144
|
+
function compileMetricQuery(opts) {
|
|
145
|
+
return compileMetricForMixpanel(opts).query;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// src/execute.ts
|
|
149
|
+
function queryApiBaseUrl(region = "mixpanel") {
|
|
150
|
+
return `https://${region}.com/api/query`;
|
|
151
|
+
}
|
|
152
|
+
function importApiBaseUrl(region = "mixpanel") {
|
|
153
|
+
const host = region === "mixpanel" ? "api.mixpanel.com" : `api.${region}.com`;
|
|
154
|
+
return `https://${host}`;
|
|
155
|
+
}
|
|
156
|
+
function basicAuthHeader(projectToken) {
|
|
157
|
+
const encoded = Buffer.from(`${projectToken}:`).toString("base64");
|
|
158
|
+
return `Basic ${encoded}`;
|
|
159
|
+
}
|
|
160
|
+
async function mixpanelGet(config, path, params, signal) {
|
|
161
|
+
const url = `${config.queryBaseUrl}${path}?${params.toString()}`;
|
|
162
|
+
const init = {
|
|
163
|
+
method: "GET",
|
|
164
|
+
headers: {
|
|
165
|
+
Authorization: basicAuthHeader(config.projectToken),
|
|
166
|
+
Accept: "application/json"
|
|
167
|
+
}
|
|
168
|
+
};
|
|
169
|
+
if (signal != null) {
|
|
170
|
+
init.signal = signal;
|
|
171
|
+
}
|
|
172
|
+
const res = await config.fetch(url, init);
|
|
173
|
+
const text = await res.text();
|
|
174
|
+
let body = null;
|
|
175
|
+
if (text.length > 0) {
|
|
176
|
+
try {
|
|
177
|
+
body = JSON.parse(text);
|
|
178
|
+
} catch {
|
|
179
|
+
body = { raw: text };
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
if (!res.ok) {
|
|
183
|
+
const detail = body && typeof body === "object" && "error" in body ? String(body.error) : text.slice(0, 200);
|
|
184
|
+
throw new Error(
|
|
185
|
+
`Mixpanel Query API ${path} failed (${res.status}): ${detail}`
|
|
186
|
+
);
|
|
187
|
+
}
|
|
188
|
+
return body;
|
|
189
|
+
}
|
|
190
|
+
async function probeWriteScope(config) {
|
|
191
|
+
const url = `${config.importBaseUrl}/import?strict=1&project_id=${encodeURIComponent(config.projectId)}`;
|
|
192
|
+
const probeBody = JSON.stringify([
|
|
193
|
+
{
|
|
194
|
+
event: "__arivie_readonly_probe__",
|
|
195
|
+
properties: {
|
|
196
|
+
distinct_id: "__arivie_probe__",
|
|
197
|
+
time: Math.floor(Date.now() / 1e3),
|
|
198
|
+
$insert_id: `arivie-probe-${Date.now()}`
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
]);
|
|
202
|
+
const res = await config.fetch(url, {
|
|
203
|
+
method: "POST",
|
|
204
|
+
headers: {
|
|
205
|
+
Authorization: basicAuthHeader(config.projectToken),
|
|
206
|
+
"Content-Type": "application/json"
|
|
207
|
+
},
|
|
208
|
+
body: probeBody
|
|
209
|
+
});
|
|
210
|
+
if (res.status === 401 || res.status === 403) {
|
|
211
|
+
return false;
|
|
212
|
+
}
|
|
213
|
+
const text = await res.text();
|
|
214
|
+
if (!res.ok) {
|
|
215
|
+
return false;
|
|
216
|
+
}
|
|
217
|
+
try {
|
|
218
|
+
const parsed = JSON.parse(text);
|
|
219
|
+
if (parsed.status === "ok" || parsed.code === 200) {
|
|
220
|
+
return true;
|
|
221
|
+
}
|
|
222
|
+
} catch {
|
|
223
|
+
if (res.ok) {
|
|
224
|
+
return true;
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
return false;
|
|
228
|
+
}
|
|
229
|
+
async function fetchSegmentation(config, query, signal) {
|
|
230
|
+
if (requiresSumEndpoint(query)) {
|
|
231
|
+
const params2 = buildSumSearchParams(query, config.projectId);
|
|
232
|
+
return mixpanelGet(config, "/segmentation/sum", params2, signal);
|
|
233
|
+
}
|
|
234
|
+
const params = buildSegmentationSearchParams(query, config.projectId);
|
|
235
|
+
return mixpanelGet(config, "/segmentation", params, signal);
|
|
236
|
+
}
|
|
237
|
+
async function fetchEventNames(config) {
|
|
238
|
+
const params = new URLSearchParams();
|
|
239
|
+
params.set("project_id", config.projectId);
|
|
240
|
+
params.set("type", "general");
|
|
241
|
+
const body = await mixpanelGet(config, "/events/names", params);
|
|
242
|
+
if (Array.isArray(body)) {
|
|
243
|
+
return body.filter((x) => typeof x === "string");
|
|
244
|
+
}
|
|
245
|
+
return [];
|
|
246
|
+
}
|
|
247
|
+
async function executeMixpanelQuery(config, opts) {
|
|
248
|
+
const startedAt = Date.now();
|
|
249
|
+
const controller = new AbortController();
|
|
250
|
+
const timeout = setTimeout(() => controller.abort(), opts.timeoutMs);
|
|
251
|
+
try {
|
|
252
|
+
const raw = await fetchSegmentation(config, opts.query, controller.signal);
|
|
253
|
+
const parsed = parseSegmentationData(raw, opts.query.event);
|
|
254
|
+
const rows = parsed.map((r) => ({
|
|
255
|
+
date: r.date,
|
|
256
|
+
value: r.value,
|
|
257
|
+
event: r.event ?? opts.query.event,
|
|
258
|
+
segment: r.segment
|
|
259
|
+
}));
|
|
260
|
+
const truncated = rows.length > opts.rowLimit;
|
|
261
|
+
const limited = rows.slice(0, opts.rowLimit);
|
|
262
|
+
return {
|
|
263
|
+
rows: limited,
|
|
264
|
+
rowCount: limited.length,
|
|
265
|
+
durationMs: Date.now() - startedAt,
|
|
266
|
+
truncated
|
|
267
|
+
};
|
|
268
|
+
} finally {
|
|
269
|
+
clearTimeout(timeout);
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
// src/adapter.ts
|
|
274
|
+
function deriveMixpanelAdapterId(projectId, projectToken) {
|
|
275
|
+
const hash = createHash("sha256").update(projectToken).digest("hex").slice(0, 12);
|
|
276
|
+
return `mixpanel:${projectId}:${hash}`;
|
|
277
|
+
}
|
|
278
|
+
function hashProjectToken(projectToken) {
|
|
279
|
+
return createHash("sha256").update(projectToken).digest("hex").slice(0, 12);
|
|
280
|
+
}
|
|
281
|
+
function mixpanelAdapter(opts) {
|
|
282
|
+
const region = opts.region ?? "mixpanel";
|
|
283
|
+
const projectId = String(opts.projectId);
|
|
284
|
+
const clientConfig = {
|
|
285
|
+
projectToken: opts.projectToken,
|
|
286
|
+
projectId,
|
|
287
|
+
queryBaseUrl: queryApiBaseUrl(region),
|
|
288
|
+
importBaseUrl: importApiBaseUrl(region),
|
|
289
|
+
fetch: opts.fetch ?? globalThis.fetch
|
|
290
|
+
};
|
|
291
|
+
let introspectCache = null;
|
|
292
|
+
let readOnlyVerified = opts.skipReadOnlyProbe === true;
|
|
293
|
+
async function ensureReadOnly() {
|
|
294
|
+
if (readOnlyVerified) {
|
|
295
|
+
return;
|
|
296
|
+
}
|
|
297
|
+
const writable = await probeWriteScope(clientConfig);
|
|
298
|
+
readOnlyVerified = true;
|
|
299
|
+
if (writable) {
|
|
300
|
+
throw new Error(READ_ONLY_REQUIRED_MSG);
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
return {
|
|
304
|
+
kind: "mixpanel",
|
|
305
|
+
id: deriveMixpanelAdapterId(projectId, opts.projectToken),
|
|
306
|
+
async execute(executeOpts) {
|
|
307
|
+
await ensureReadOnly();
|
|
308
|
+
return executeMixpanelQuery(clientConfig, executeOpts);
|
|
309
|
+
},
|
|
310
|
+
async introspect() {
|
|
311
|
+
if (introspectCache != null) {
|
|
312
|
+
return introspectCache;
|
|
313
|
+
}
|
|
314
|
+
await ensureReadOnly();
|
|
315
|
+
const names = await fetchEventNames(clientConfig);
|
|
316
|
+
introspectCache = names.map((name) => ({ name }));
|
|
317
|
+
return introspectCache;
|
|
318
|
+
},
|
|
319
|
+
async verifyOwnerIdentity() {
|
|
320
|
+
},
|
|
321
|
+
compileMetric: compileMetricForMixpanel
|
|
322
|
+
};
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
export { READ_ONLY_REQUIRED_MSG, aggregateToSegmentationType, basicAuthHeader, buildSegmentationSearchParams, buildSumSearchParams, compileMetricForMixpanel, compileMetricQuery, deriveMixpanelAdapterId, executeMixpanelQuery, fetchEventNames, fetchSegmentation, hashProjectToken, importApiBaseUrl, mixpanelAdapter, parseSegmentationData, probeWriteScope, queryApiBaseUrl, sumRowValues };
|
package/package.json
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@arivie/source-mixpanel",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Arivie Mixpanel source adapter — Query API segmentation with read-only token enforcement.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "Apache-2.0",
|
|
7
|
+
"main": "./dist/index.cjs",
|
|
8
|
+
"module": "./dist/index.js",
|
|
9
|
+
"types": "./dist/index.d.ts",
|
|
10
|
+
"exports": {
|
|
11
|
+
".": {
|
|
12
|
+
"types": "./dist/index.d.ts",
|
|
13
|
+
"import": "./dist/index.js",
|
|
14
|
+
"require": "./dist/index.cjs"
|
|
15
|
+
}
|
|
16
|
+
},
|
|
17
|
+
"files": [
|
|
18
|
+
"dist",
|
|
19
|
+
"README.md"
|
|
20
|
+
],
|
|
21
|
+
"dependencies": {
|
|
22
|
+
"@arivie/core": "0.1.0",
|
|
23
|
+
"@arivie/semantic": "0.1.0"
|
|
24
|
+
},
|
|
25
|
+
"devDependencies": {
|
|
26
|
+
"@types/node": "^22.0.0",
|
|
27
|
+
"tsup": "^8.5.1",
|
|
28
|
+
"typescript": "^6.0.0",
|
|
29
|
+
"vitest": "^4.1.0"
|
|
30
|
+
},
|
|
31
|
+
"publishConfig": {
|
|
32
|
+
"access": "public",
|
|
33
|
+
"registry": "https://registry.npmjs.org/"
|
|
34
|
+
},
|
|
35
|
+
"scripts": {
|
|
36
|
+
"build": "tsup",
|
|
37
|
+
"test": "vitest run",
|
|
38
|
+
"typecheck": "tsc --noEmit",
|
|
39
|
+
"lint": "echo no-lint-yet"
|
|
40
|
+
}
|
|
41
|
+
}
|