@rawdash/connector-posthog 0.0.1 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,26 +1,78 @@
1
+ <!-- This file is generated from connector metadata by scripts/generate-connector-docs.ts. Do not edit by hand. -->
2
+
1
3
  # @rawdash/connector-posthog
2
4
 
3
- Rawdash connector for [PostHog](https://posthog.com) — syncs event volume, active users (DAU/WAU/MAU), feature flags, feature-flag usage, and declared funnels into the six-shape storage model. Built for the product-analytics vertical: engineering and product teams that already run PostHog can chart adoption, rollout exposure, and conversion alongside the rest of their dashboards.
5
+ [![npm version](https://img.shields.io/npm/v/@rawdash/connector-posthog)](https://www.npmjs.com/package/@rawdash/connector-posthog)
6
+ [![license](https://img.shields.io/npm/l/@rawdash/connector-posthog)](https://github.com/rawdash/rawdash/blob/main/LICENSE)
7
+
8
+ Sync feature flags, per-day event volume, feature flag usage, active users, and funnel conversion from a PostHog project.
4
9
 
5
- ## Auth setup
10
+ ## Install
6
11
 
7
- The connector authenticates with a **personal API key** (read access to the project).
12
+ ```sh
13
+ npm install @rawdash/connector-posthog
14
+ ```
8
15
 
9
- 1. In PostHog, open **Settings → Personal API keys** (under your account menu).
10
- 2. Click **Create personal API key**, give it a name (e.g. `rawdash`).
11
- 3. Scope it to **read** access for the project's analytics and feature-flag resources (`query:read`, `feature_flag:read`). A personal API key is required — project keys and organization keys are not supported.
12
- 4. Copy the key (starts with `phx_`) — it's shown only once.
16
+ ## Authentication
13
17
 
14
- You also need your **Project ID** (a number), found in **Settings Project Project ID**, and your instance **host**:
18
+ A PostHog personal API key with read access to the project is required, along with the numeric project ID and the instance host.
15
19
 
16
- - PostHog Cloud US: `https://us.posthog.com`
17
- - PostHog Cloud EU: `https://eu.posthog.com`
18
- - Self-hosted: your own origin, e.g. `https://posthog.internal.example.com`
20
+ 1. Open PostHog Settings → Personal API keys and create a key with read access to the project (it starts with `phx_`).
21
+ 2. Find your numeric project ID in PostHog Settings → Project → Project ID.
22
+ 3. Set `host` to your instance base URL - `https://us.posthog.com` or `https://eu.posthog.com` for PostHog Cloud, or your self-hosted origin (no trailing slash).
23
+ 4. Store the key as a secret and reference it from config as `apiKey: secret("POSTHOG_API_KEY")`.
19
24
 
20
25
  ## Configuration
21
26
 
27
+ | Field | Type | Required | Description |
28
+ | -------------- | ------ | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
29
+ | `apiKey` | secret | Yes | PostHog personal API key with read access to the project. Create one at PostHog → Settings → Personal API keys (starts with `phx_`). |
30
+ | `projectId` | string | Yes | Numeric ID of your PostHog project. Find it in PostHog → Settings → Project → Project ID. |
31
+ | `host` | string | No | PostHog instance base URL. Use https://us.posthog.com or https://eu.posthog.com for PostHog Cloud, or your self-hosted origin. No trailing slash. |
32
+ | `events` | array | No | Event names to roll up in the `events_per_day` resource. Omit to roll up every event in the project. |
33
+ | `funnels` | array | No | Funnel definitions to evaluate. Each funnel is an object with name, steps (an ordered list of event names), and an optional windowDays. Conversion is measured over the sync window. |
34
+ | `lookbackDays` | number | No | How many calendar days of history to roll up on a full sync. Defaults to 30. |
35
+ | `resources` | array | No | Which PostHog resources to sync. Omit to sync all of them. |
36
+
37
+ ## Resources
38
+
39
+ - **`posthog_feature_flag`** _(entity)_ - Feature flags in the project, keyed by flag id, with key, name, active state, rollout percentage, and a JSON snapshot of the flag filters.
40
+ - Endpoint: `GET /api/projects/{projectId}/feature_flags/`
41
+ - Feature flags upsert by id on every run.
42
+ - **`posthog_events_per_day`** _(metric)_ - Daily event volume rolled up by event name via HogQL. One sample per (day, event) over the lookback window. Restricted to the configured `events` list when provided, otherwise every event.
43
+ - Endpoint: `POST /api/projects/{projectId}/query (HogQLQuery)`
44
+ - Unit: events
45
+ - Granularity: Daily (UTC)
46
+ - Dimensions: `event`, `count`, `distinctUsers`
47
+ - Rollup metrics are stamped at UTC midnight of the day they cover.
48
+ - **`posthog_feature_flag_usage`** _(metric)_ - Daily `$feature_flag_called` volume rolled up by flag key via HogQL. One sample per (day, flag) over the lookback window.
49
+ - Endpoint: `POST /api/projects/{projectId}/query (HogQLQuery)`
50
+ - Unit: calls
51
+ - Granularity: Daily (UTC)
52
+ - Dimensions: `flagKey`, `callCount`, `uniqueUsers`
53
+ - Rollup metrics are stamped at UTC midnight of the day they cover.
54
+ - **`posthog_active_users`** _(metric)_ - Daily active-user counts from a TrendsQuery, with one sample per day per rolling window (daily, weekly, and monthly active users).
55
+ - Endpoint: `POST /api/projects/{projectId}/query (TrendsQuery)`
56
+ - Unit: users
57
+ - Granularity: Daily (UTC)
58
+ - Dimensions: `window`
59
+ - Rollup metrics are stamped at UTC midnight of the day they cover.
60
+ - **`posthog_funnel`** _(metric)_ - Funnel conversion snapshot. One sample per declared funnel step, stamped at the start of the current UTC day, carrying the step user count and conversion rate relative to the first step. Only written when `funnels` are configured.
61
+ - Endpoint: `POST /api/projects/{projectId}/query (FunnelsQuery)`
62
+ - Unit: users
63
+ - Granularity: Snapshot per sync (start of UTC day)
64
+ - Dimensions: `funnel`, `step`, `stepName`, `users`, `conversionRate`
65
+ - A single conversion snapshot measured over the lookback window, stamped at the start of the current UTC day, not a per-day time series.
66
+
67
+ ## Example
68
+
22
69
  ```ts
23
- import { secret } from '@rawdash/core';
70
+ import {
71
+ defineConfig,
72
+ defineDashboard,
73
+ defineMetric,
74
+ secret,
75
+ } from '@rawdash/core';
24
76
 
25
77
  const posthog = {
26
78
  name: 'posthog',
@@ -28,100 +80,25 @@ const posthog = {
28
80
  config: {
29
81
  apiKey: secret('POSTHOG_API_KEY'),
30
82
  projectId: '12345',
31
- host: 'https://us.posthog.com', // defaults to https://us.posthog.com
32
- // events: ['$pageview', 'signed_up'], // optional, defaults to all events
33
- // funnels: [{ name: 'Signup', steps: ['$pageview', 'signed_up'] }],
34
- // resources: ['events_per_day', 'feature_flags'], // optional, defaults to all
83
+ host: 'https://us.posthog.com',
84
+ events: ['pageview', 'signup'],
35
85
  },
36
86
  };
37
- ```
38
-
39
- Register the connector class when mounting the engine:
40
-
41
- ```ts
42
- import { PostHogConnector } from '@rawdash/connector-posthog';
43
- import { mountEngine } from '@rawdash/hono';
44
-
45
- mountEngine(config, { connectorRegistry: { posthog: PostHogConnector } });
46
- ```
47
-
48
- ### Choosing resources
49
-
50
- By default the connector syncs every supported resource. Pass `resources` to sync only a subset:
51
-
52
- `feature_flags`, `events_per_day`, `feature_flag_usage`, `active_users`, `funnels`
53
-
54
- ### Configuration reference
55
-
56
- | Field | Required | Description |
57
- | -------------- | -------- | -------------------------------------------------------------------------------------------------- |
58
- | `apiKey` | yes | Personal API key (secret). Bearer-authenticated. |
59
- | `projectId` | yes | Numeric PostHog project ID. |
60
- | `host` | no | Instance base URL. Defaults to `https://us.posthog.com`. No trailing slash. |
61
- | `events` | no | Event names to roll up in `events_per_day`. Omit to roll up every event. |
62
- | `funnels` | no | Funnel definitions: `{ name, steps: [event, …], windowDays? }`. `steps` needs at least two events. |
63
- | `lookbackDays` | no | Days of history to roll up on a full sync. Defaults to 30. |
64
- | `resources` | no | Subset of resources to sync. Omit for all. |
65
-
66
- ### Example dashboard
67
-
68
- ```ts
69
- import { defineConfig, defineDashboard, defineMetric } from '@rawdash/core';
70
87
 
71
88
  export default defineConfig({
72
89
  connectors: [posthog],
73
90
  dashboards: {
74
91
  product: defineDashboard({
75
92
  widgets: {
76
- active_flags: {
77
- kind: 'stat',
78
- title: 'Active feature flags',
79
- metric: defineMetric({
80
- connector: posthog,
81
- shape: 'entity',
82
- entityType: 'posthog_feature_flag',
83
- fn: 'count',
84
- filter: [{ field: 'active', op: 'eq', value: true }],
85
- }),
86
- },
87
- dau: {
93
+ daily_events: {
88
94
  kind: 'timeseries',
89
- title: 'Daily active users',
95
+ title: 'Events per day',
90
96
  window: '30d',
91
- metric: defineMetric({
92
- connector: posthog,
93
- shape: 'metric',
94
- name: 'posthog_active_users',
95
- field: 'value',
96
- fn: 'latest',
97
- window: '30d',
98
- filter: [{ field: 'window', op: 'eq', value: 'dau' }],
99
- groupBy: { field: 'ts', granularity: 'day' },
100
- }),
101
- },
102
- events_by_name: {
103
- kind: 'distribution',
104
- title: 'Events by name (30d)',
105
97
  metric: defineMetric({
106
98
  connector: posthog,
107
99
  shape: 'metric',
108
100
  name: 'posthog_events_per_day',
109
- field: 'count',
110
101
  fn: 'sum',
111
- groupBy: { field: 'event' },
112
- }),
113
- },
114
- checkout_funnel: {
115
- kind: 'funnel',
116
- title: 'Checkout conversion',
117
- metric: defineMetric({
118
- connector: posthog,
119
- shape: 'metric',
120
- name: 'posthog_funnel',
121
- field: 'conversionRate',
122
- fn: 'latest',
123
- filter: [{ field: 'funnel', op: 'eq', value: 'Checkout' }],
124
- groupBy: { field: 'step' },
125
102
  }),
126
103
  },
127
104
  },
@@ -130,42 +107,20 @@ export default defineConfig({
130
107
  });
131
108
  ```
132
109
 
133
- ## Data model
134
-
135
- Timestamps stored in attributes are Unix milliseconds. Rollup metrics are stamped at UTC midnight of the day they cover.
136
-
137
- | Storage shape | Type | Key attributes |
138
- | ------------- | ---------------------------- | ----------------------------------------------------- |
139
- | entity | `posthog_feature_flag` | key, name, active, rolloutPercentage, filters (JSON) |
140
- | metric | `posthog_events_per_day` | event, count, distinctUsers (value = count) |
141
- | metric | `posthog_feature_flag_usage` | flagKey, callCount, uniqueUsers (value = callCount) |
142
- | metric | `posthog_active_users` | window (`dau` / `wau` / `mau`) (value = active users) |
143
- | metric | `posthog_funnel` | funnel, step, stepName, users, conversionRate |
144
-
145
- - **`posthog_events_per_day`** is a HogQL rollup grouped by `(day, event)`. Restrict it to specific events with the `events` config field.
146
- - **`posthog_active_users`** runs one Trends query with `dau` / `weekly_active` / `monthly_active` series; each series is written under the matching `window` attribute so a single metric drives all three.
147
- - **`posthog_feature_flag_usage`** counts `$feature_flag_called` events grouped by `(day, flag key)`.
148
- - **`posthog_funnel`** evaluates each declared funnel over the sync window and writes one sample per step; `conversionRate` is the step's users relative to the first step.
149
-
150
- ## Schemas
151
-
152
- `PostHogConnector.schemas` declares the Zod schema for each resource's raw API payload — the feature-flag record array, the positional HogQL result rows, the Trends series, and the funnel step results. Used by the cloud shape-drift pipeline to populate `connector_baselines`, and by the package's property tests.
153
-
154
- ## Sync behaviour
110
+ ## Rate limits
155
111
 
156
- - **Backfill** (`mode: 'full'`): rolls up the last `lookbackDays` (default 30) of analytics and rewrites every metric scope; feature flags are enumerated in full.
157
- - **Incremental** (`mode: 'latest'`): the rollup window starts at `options.since` (capped to `lookbackDays`), so analytics queries scan only the changed window. Feature flags upsert by id on every run.
158
- - **Resumable**: `feature_flags` yields an offset cursor and `funnels` yields a per-funnel index cursor, so an interrupted sync resumes from the same page. The single-shot query phases re-run from scratch (their scope is cleared first, so the rewrite is idempotent).
159
- - **Rate limits**: PostHog enforces ~1200 requests/min per personal key and returns `429` when exceeded. The shared HTTP client retries automatically with exponential back-off and honours `Retry-After`.
112
+ PostHog allows roughly 1200 requests/min per personal API key; Retry-After is honored.
160
113
 
161
- ## Aggregates
114
+ ## Limitations
162
115
 
163
- No aggregates yet. PostHog's `query` endpoint could serve `count(...)` widgets server-side (a HogQL `count()` over the events table), which would let stat widgets skip a rollup backfill; the hook is left for a follow-up once the count-filter translation surface is defined.
116
+ - Session recordings/replays and cohorts are not synced.
164
117
 
165
- ## Property tests
118
+ ## Links
166
119
 
167
- `feature_flags`, `events_per_day`, `feature_flag_usage`, and `active_users` have fast-check property tests under `src/property.test.ts` that generate synthetic API payloads from each resource's Zod schema, run them through `connector.sync()` against an `InMemoryStorage`, and assert universal invariants (non-empty ids, finite timestamps, no `undefined` in storage, no thrown errors). Funnels and the HogQL/Trends mapping details are covered by example-driven unit tests in `src/posthog.test.ts`.
120
+ - [Rawdash docs](https://rawdash.dev/docs/connectors/)
121
+ - [PostHog API docs](https://posthog.com/docs/api)
122
+ - [GitHub](https://github.com/rawdash/rawdash)
168
123
 
169
- ## Out of scope
124
+ ## License
170
125
 
171
- Session recordings / replays and cohorts are intentionally not synced — they aren't dashboard-shaped. Open an issue if you need them.
126
+ Apache-2.0
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { BaseConnector, ConnectorContext, SyncOptions, StorageHandle, SyncResult } from '@rawdash/core';
1
+ import { BaseConnector, ConnectorContext, SyncOptions, StorageHandle, SyncResult, ConnectorDoc } from '@rawdash/core';
2
2
  import { z } from 'zod';
3
3
 
4
4
  declare const configFields: z.ZodObject<{
@@ -22,6 +22,7 @@ declare const configFields: z.ZodObject<{
22
22
  active_users: "active_users";
23
23
  }>>>;
24
24
  }, z.core.$strip>;
25
+ declare const doc: ConnectorDoc;
25
26
  interface PostHogFunnel {
26
27
  name: string;
27
28
  steps: readonly string[];
@@ -45,8 +46,245 @@ type PostHogCredentials = typeof posthogCredentials;
45
46
  declare const PHASE_ORDER: readonly ["feature_flags", "events_per_day", "feature_flag_usage", "active_users", "funnels"];
46
47
  type PostHogPhase = (typeof PHASE_ORDER)[number];
47
48
  type PostHogResource = PostHogPhase;
49
+ declare const posthogResources: {
50
+ readonly posthog_feature_flag: {
51
+ readonly shape: "entity";
52
+ readonly description: "Feature flags in the project, keyed by flag id, with key, name, active state, rollout percentage, and a JSON snapshot of the flag filters.";
53
+ readonly endpoint: "GET /api/projects/{projectId}/feature_flags/";
54
+ readonly notes: "Feature flags upsert by id on every run.";
55
+ readonly responses: {
56
+ readonly feature_flags: z.ZodArray<z.ZodObject<{
57
+ id: z.ZodNumber;
58
+ key: z.ZodString;
59
+ name: z.ZodOptional<z.ZodNullable<z.ZodString>>;
60
+ active: z.ZodBoolean;
61
+ rollout_percentage: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
62
+ created_at: z.ZodOptional<z.ZodNullable<z.ZodString>>;
63
+ }, z.core.$strip>>;
64
+ };
65
+ };
66
+ readonly posthog_events_per_day: {
67
+ readonly shape: "metric";
68
+ readonly description: "Daily event volume rolled up by event name via HogQL. One sample per (day, event) over the lookback window. Restricted to the configured `events` list when provided, otherwise every event.";
69
+ readonly endpoint: "POST /api/projects/{projectId}/query (HogQLQuery)";
70
+ readonly unit: "events";
71
+ readonly granularity: "Daily (UTC)";
72
+ readonly notes: "Rollup metrics are stamped at UTC midnight of the day they cover.";
73
+ readonly dimensions: [{
74
+ readonly name: "event";
75
+ readonly description: "The PostHog event name.";
76
+ }, {
77
+ readonly name: "count";
78
+ readonly description: "Total event occurrences that day.";
79
+ }, {
80
+ readonly name: "distinctUsers";
81
+ readonly description: "Distinct persons who fired the event that day.";
82
+ }];
83
+ readonly responses: {
84
+ readonly events_per_day: z.ZodObject<{
85
+ results: z.ZodArray<z.ZodTuple<[z.ZodString, z.ZodNullable<z.ZodString>, z.ZodNumber, z.ZodNumber], null>>;
86
+ }, z.core.$strip>;
87
+ };
88
+ };
89
+ readonly posthog_feature_flag_usage: {
90
+ readonly shape: "metric";
91
+ readonly description: "Daily `$feature_flag_called` volume rolled up by flag key via HogQL. One sample per (day, flag) over the lookback window.";
92
+ readonly endpoint: "POST /api/projects/{projectId}/query (HogQLQuery)";
93
+ readonly unit: "calls";
94
+ readonly granularity: "Daily (UTC)";
95
+ readonly notes: "Rollup metrics are stamped at UTC midnight of the day they cover.";
96
+ readonly dimensions: [{
97
+ readonly name: "flagKey";
98
+ readonly description: "The feature flag key that was evaluated.";
99
+ }, {
100
+ readonly name: "callCount";
101
+ readonly description: "Number of flag evaluations that day.";
102
+ }, {
103
+ readonly name: "uniqueUsers";
104
+ readonly description: "Distinct persons who evaluated the flag that day.";
105
+ }];
106
+ readonly responses: {
107
+ readonly feature_flag_usage: z.ZodObject<{
108
+ results: z.ZodArray<z.ZodTuple<[z.ZodString, z.ZodNullable<z.ZodString>, z.ZodNumber, z.ZodNumber], null>>;
109
+ }, z.core.$strip>;
110
+ };
111
+ };
112
+ readonly posthog_active_users: {
113
+ readonly shape: "metric";
114
+ readonly description: "Daily active-user counts from a TrendsQuery, with one sample per day per rolling window (daily, weekly, and monthly active users).";
115
+ readonly endpoint: "POST /api/projects/{projectId}/query (TrendsQuery)";
116
+ readonly unit: "users";
117
+ readonly granularity: "Daily (UTC)";
118
+ readonly notes: "Rollup metrics are stamped at UTC midnight of the day they cover.";
119
+ readonly dimensions: [{
120
+ readonly name: "window";
121
+ readonly description: "The active-user window the sample belongs to: `dau`, `wau`, or `mau`.";
122
+ }];
123
+ readonly responses: {
124
+ readonly active_users: z.ZodObject<{
125
+ results: z.ZodArray<z.ZodObject<{
126
+ data: z.ZodArray<z.ZodNumber>;
127
+ days: z.ZodArray<z.ZodString>;
128
+ label: z.ZodOptional<z.ZodNullable<z.ZodString>>;
129
+ }, z.core.$strip>>;
130
+ }, z.core.$strip>;
131
+ };
132
+ };
133
+ readonly posthog_funnel: {
134
+ readonly shape: "metric";
135
+ readonly description: "Funnel conversion snapshot. One sample per declared funnel step, stamped at the start of the current UTC day, carrying the step user count and conversion rate relative to the first step. Only written when `funnels` are configured.";
136
+ readonly endpoint: "POST /api/projects/{projectId}/query (FunnelsQuery)";
137
+ readonly unit: "users";
138
+ readonly granularity: "Snapshot per sync (start of UTC day)";
139
+ readonly notes: "A single conversion snapshot measured over the lookback window, stamped at the start of the current UTC day, not a per-day time series.";
140
+ readonly dimensions: [{
141
+ readonly name: "funnel";
142
+ readonly description: "The configured funnel name.";
143
+ }, {
144
+ readonly name: "step";
145
+ readonly description: "Zero-based step order within the funnel.";
146
+ }, {
147
+ readonly name: "stepName";
148
+ readonly description: "The event name for the step, if returned.";
149
+ }, {
150
+ readonly name: "users";
151
+ readonly description: "Users who reached this step.";
152
+ }, {
153
+ readonly name: "conversionRate";
154
+ readonly description: "Step users divided by first-step users (0 when no base).";
155
+ }];
156
+ readonly responses: {
157
+ readonly funnels: z.ZodObject<{
158
+ results: z.ZodArray<z.ZodObject<{
159
+ count: z.ZodNumber;
160
+ name: z.ZodOptional<z.ZodNullable<z.ZodString>>;
161
+ order: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
162
+ }, z.core.$strip>>;
163
+ }, z.core.$strip>;
164
+ };
165
+ };
166
+ };
167
+ declare const id = "posthog";
48
168
  declare class PostHogConnector extends BaseConnector<PostHogSettings, PostHogCredentials> {
49
169
  static readonly id = "posthog";
170
+ static readonly resources: {
171
+ readonly posthog_feature_flag: {
172
+ readonly shape: "entity";
173
+ readonly description: "Feature flags in the project, keyed by flag id, with key, name, active state, rollout percentage, and a JSON snapshot of the flag filters.";
174
+ readonly endpoint: "GET /api/projects/{projectId}/feature_flags/";
175
+ readonly notes: "Feature flags upsert by id on every run.";
176
+ readonly responses: {
177
+ readonly feature_flags: z.ZodArray<z.ZodObject<{
178
+ id: z.ZodNumber;
179
+ key: z.ZodString;
180
+ name: z.ZodOptional<z.ZodNullable<z.ZodString>>;
181
+ active: z.ZodBoolean;
182
+ rollout_percentage: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
183
+ created_at: z.ZodOptional<z.ZodNullable<z.ZodString>>;
184
+ }, z.core.$strip>>;
185
+ };
186
+ };
187
+ readonly posthog_events_per_day: {
188
+ readonly shape: "metric";
189
+ readonly description: "Daily event volume rolled up by event name via HogQL. One sample per (day, event) over the lookback window. Restricted to the configured `events` list when provided, otherwise every event.";
190
+ readonly endpoint: "POST /api/projects/{projectId}/query (HogQLQuery)";
191
+ readonly unit: "events";
192
+ readonly granularity: "Daily (UTC)";
193
+ readonly notes: "Rollup metrics are stamped at UTC midnight of the day they cover.";
194
+ readonly dimensions: [{
195
+ readonly name: "event";
196
+ readonly description: "The PostHog event name.";
197
+ }, {
198
+ readonly name: "count";
199
+ readonly description: "Total event occurrences that day.";
200
+ }, {
201
+ readonly name: "distinctUsers";
202
+ readonly description: "Distinct persons who fired the event that day.";
203
+ }];
204
+ readonly responses: {
205
+ readonly events_per_day: z.ZodObject<{
206
+ results: z.ZodArray<z.ZodTuple<[z.ZodString, z.ZodNullable<z.ZodString>, z.ZodNumber, z.ZodNumber], null>>;
207
+ }, z.core.$strip>;
208
+ };
209
+ };
210
+ readonly posthog_feature_flag_usage: {
211
+ readonly shape: "metric";
212
+ readonly description: "Daily `$feature_flag_called` volume rolled up by flag key via HogQL. One sample per (day, flag) over the lookback window.";
213
+ readonly endpoint: "POST /api/projects/{projectId}/query (HogQLQuery)";
214
+ readonly unit: "calls";
215
+ readonly granularity: "Daily (UTC)";
216
+ readonly notes: "Rollup metrics are stamped at UTC midnight of the day they cover.";
217
+ readonly dimensions: [{
218
+ readonly name: "flagKey";
219
+ readonly description: "The feature flag key that was evaluated.";
220
+ }, {
221
+ readonly name: "callCount";
222
+ readonly description: "Number of flag evaluations that day.";
223
+ }, {
224
+ readonly name: "uniqueUsers";
225
+ readonly description: "Distinct persons who evaluated the flag that day.";
226
+ }];
227
+ readonly responses: {
228
+ readonly feature_flag_usage: z.ZodObject<{
229
+ results: z.ZodArray<z.ZodTuple<[z.ZodString, z.ZodNullable<z.ZodString>, z.ZodNumber, z.ZodNumber], null>>;
230
+ }, z.core.$strip>;
231
+ };
232
+ };
233
+ readonly posthog_active_users: {
234
+ readonly shape: "metric";
235
+ readonly description: "Daily active-user counts from a TrendsQuery, with one sample per day per rolling window (daily, weekly, and monthly active users).";
236
+ readonly endpoint: "POST /api/projects/{projectId}/query (TrendsQuery)";
237
+ readonly unit: "users";
238
+ readonly granularity: "Daily (UTC)";
239
+ readonly notes: "Rollup metrics are stamped at UTC midnight of the day they cover.";
240
+ readonly dimensions: [{
241
+ readonly name: "window";
242
+ readonly description: "The active-user window the sample belongs to: `dau`, `wau`, or `mau`.";
243
+ }];
244
+ readonly responses: {
245
+ readonly active_users: z.ZodObject<{
246
+ results: z.ZodArray<z.ZodObject<{
247
+ data: z.ZodArray<z.ZodNumber>;
248
+ days: z.ZodArray<z.ZodString>;
249
+ label: z.ZodOptional<z.ZodNullable<z.ZodString>>;
250
+ }, z.core.$strip>>;
251
+ }, z.core.$strip>;
252
+ };
253
+ };
254
+ readonly posthog_funnel: {
255
+ readonly shape: "metric";
256
+ readonly description: "Funnel conversion snapshot. One sample per declared funnel step, stamped at the start of the current UTC day, carrying the step user count and conversion rate relative to the first step. Only written when `funnels` are configured.";
257
+ readonly endpoint: "POST /api/projects/{projectId}/query (FunnelsQuery)";
258
+ readonly unit: "users";
259
+ readonly granularity: "Snapshot per sync (start of UTC day)";
260
+ readonly notes: "A single conversion snapshot measured over the lookback window, stamped at the start of the current UTC day, not a per-day time series.";
261
+ readonly dimensions: [{
262
+ readonly name: "funnel";
263
+ readonly description: "The configured funnel name.";
264
+ }, {
265
+ readonly name: "step";
266
+ readonly description: "Zero-based step order within the funnel.";
267
+ }, {
268
+ readonly name: "stepName";
269
+ readonly description: "The event name for the step, if returned.";
270
+ }, {
271
+ readonly name: "users";
272
+ readonly description: "Users who reached this step.";
273
+ }, {
274
+ readonly name: "conversionRate";
275
+ readonly description: "Step users divided by first-step users (0 when no base).";
276
+ }];
277
+ readonly responses: {
278
+ readonly funnels: z.ZodObject<{
279
+ results: z.ZodArray<z.ZodObject<{
280
+ count: z.ZodNumber;
281
+ name: z.ZodOptional<z.ZodNullable<z.ZodString>>;
282
+ order: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
283
+ }, z.core.$strip>>;
284
+ }, z.core.$strip>;
285
+ };
286
+ };
287
+ };
50
288
  static readonly schemas: {
51
289
  readonly feature_flags: z.ZodArray<z.ZodObject<{
52
290
  id: z.ZodNumber;
@@ -56,12 +294,15 @@ declare class PostHogConnector extends BaseConnector<PostHogSettings, PostHogCre
56
294
  rollout_percentage: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
57
295
  created_at: z.ZodOptional<z.ZodNullable<z.ZodString>>;
58
296
  }, z.core.$strip>>;
297
+ } & {
59
298
  readonly events_per_day: z.ZodObject<{
60
299
  results: z.ZodArray<z.ZodTuple<[z.ZodString, z.ZodNullable<z.ZodString>, z.ZodNumber, z.ZodNumber], null>>;
61
300
  }, z.core.$strip>;
301
+ } & {
62
302
  readonly feature_flag_usage: z.ZodObject<{
63
303
  results: z.ZodArray<z.ZodTuple<[z.ZodString, z.ZodNullable<z.ZodString>, z.ZodNumber, z.ZodNumber], null>>;
64
304
  }, z.core.$strip>;
305
+ } & {
65
306
  readonly active_users: z.ZodObject<{
66
307
  results: z.ZodArray<z.ZodObject<{
67
308
  data: z.ZodArray<z.ZodNumber>;
@@ -69,6 +310,7 @@ declare class PostHogConnector extends BaseConnector<PostHogSettings, PostHogCre
69
310
  label: z.ZodOptional<z.ZodNullable<z.ZodString>>;
70
311
  }, z.core.$strip>>;
71
312
  }, z.core.$strip>;
313
+ } & {
72
314
  readonly funnels: z.ZodObject<{
73
315
  results: z.ZodArray<z.ZodObject<{
74
316
  count: z.ZodNumber;
@@ -76,7 +318,7 @@ declare class PostHogConnector extends BaseConnector<PostHogSettings, PostHogCre
76
318
  order: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
77
319
  }, z.core.$strip>>;
78
320
  }, z.core.$strip>;
79
- };
321
+ } & Readonly<Record<string, z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>>>;
80
322
  static create(input: unknown, ctx?: ConnectorContext): PostHogConnector;
81
323
  readonly id = "posthog";
82
324
  readonly credentials: {
@@ -104,4 +346,4 @@ declare class PostHogConnector extends BaseConnector<PostHogSettings, PostHogCre
104
346
  sync(options: SyncOptions, storage: StorageHandle, signal?: AbortSignal): Promise<SyncResult>;
105
347
  }
106
348
 
107
- export { PostHogConnector, type PostHogFunnel, type PostHogResource, type PostHogSettings, configFields, PostHogConnector as default };
349
+ export { PostHogConnector, type PostHogFunnel, type PostHogResource, type PostHogSettings, configFields, PostHogConnector as default, doc, id, posthogResources as resources };
package/dist/index.js CHANGED
@@ -30,8 +30,11 @@ function parseEpoch(value, unit) {
30
30
  import {
31
31
  BaseConnector,
32
32
  defineConfigFields,
33
+ defineConnectorDoc,
34
+ defineResources,
33
35
  makeChunkedCursorGuard,
34
36
  paginateChunked,
37
+ schemasFromResources,
35
38
  selectActivePhases
36
39
  } from "@rawdash/core";
37
40
  import { z } from "zod";
@@ -67,7 +70,7 @@ var configFields = defineConfigFields(
67
70
  }),
68
71
  funnels: z.array(funnelDefinition).nonempty().optional().meta({
69
72
  label: "Funnels",
70
- description: "Funnel definitions to evaluate. Each funnel is { name, steps: [event, \u2026], windowDays? }. Conversion is measured over the sync window."
73
+ description: "Funnel definitions to evaluate. Each funnel is an object with name, steps (an ordered list of event names), and an optional windowDays. Conversion is measured over the sync window."
71
74
  }),
72
75
  lookbackDays: z.number().int().positive().optional().meta({
73
76
  label: "Lookback days (full sync)",
@@ -88,6 +91,28 @@ var configFields = defineConfigFields(
88
91
  })
89
92
  })
90
93
  );
94
+ var doc = defineConnectorDoc({
95
+ displayName: "PostHog",
96
+ category: "product",
97
+ brandColor: "#000000",
98
+ tagline: "Sync feature flags, per-day event volume, feature flag usage, active users, and funnel conversion from a PostHog project.",
99
+ vendor: {
100
+ name: "PostHog",
101
+ apiDocs: "https://posthog.com/docs/api",
102
+ website: "https://posthog.com"
103
+ },
104
+ auth: {
105
+ summary: "A PostHog personal API key with read access to the project is required, along with the numeric project ID and the instance host.",
106
+ setup: [
107
+ "Open PostHog \u2192 Settings \u2192 Personal API keys and create a key with read access to the project (it starts with `phx_`).",
108
+ "Find your numeric project ID in PostHog \u2192 Settings \u2192 Project \u2192 Project ID.",
109
+ "Set `host` to your instance base URL - `https://us.posthog.com` or `https://eu.posthog.com` for PostHog Cloud, or your self-hosted origin (no trailing slash).",
110
+ 'Store the key as a secret and reference it from config as `apiKey: secret("POSTHOG_API_KEY")`.'
111
+ ]
112
+ },
113
+ rateLimit: "PostHog allows roughly 1200 requests/min per personal API key; Retry-After is honored.",
114
+ limitations: ["Session recordings/replays and cohorts are not synced."]
115
+ });
91
116
  var posthogCredentials = {
92
117
  apiKey: {
93
118
  description: "PostHog personal API key",
@@ -196,15 +221,100 @@ var funnelSchema = z.object({
196
221
  })
197
222
  )
198
223
  });
224
+ var posthogResources = defineResources({
225
+ posthog_feature_flag: {
226
+ shape: "entity",
227
+ description: "Feature flags in the project, keyed by flag id, with key, name, active state, rollout percentage, and a JSON snapshot of the flag filters.",
228
+ endpoint: "GET /api/projects/{projectId}/feature_flags/",
229
+ notes: "Feature flags upsert by id on every run.",
230
+ responses: { feature_flags: z.array(featureFlagSchema) }
231
+ },
232
+ posthog_events_per_day: {
233
+ shape: "metric",
234
+ description: "Daily event volume rolled up by event name via HogQL. One sample per (day, event) over the lookback window. Restricted to the configured `events` list when provided, otherwise every event.",
235
+ endpoint: "POST /api/projects/{projectId}/query (HogQLQuery)",
236
+ unit: "events",
237
+ granularity: "Daily (UTC)",
238
+ notes: "Rollup metrics are stamped at UTC midnight of the day they cover.",
239
+ dimensions: [
240
+ { name: "event", description: "The PostHog event name." },
241
+ { name: "count", description: "Total event occurrences that day." },
242
+ {
243
+ name: "distinctUsers",
244
+ description: "Distinct persons who fired the event that day."
245
+ }
246
+ ],
247
+ responses: { events_per_day: hogqlSchema }
248
+ },
249
+ posthog_feature_flag_usage: {
250
+ shape: "metric",
251
+ description: "Daily `$feature_flag_called` volume rolled up by flag key via HogQL. One sample per (day, flag) over the lookback window.",
252
+ endpoint: "POST /api/projects/{projectId}/query (HogQLQuery)",
253
+ unit: "calls",
254
+ granularity: "Daily (UTC)",
255
+ notes: "Rollup metrics are stamped at UTC midnight of the day they cover.",
256
+ dimensions: [
257
+ {
258
+ name: "flagKey",
259
+ description: "The feature flag key that was evaluated."
260
+ },
261
+ {
262
+ name: "callCount",
263
+ description: "Number of flag evaluations that day."
264
+ },
265
+ {
266
+ name: "uniqueUsers",
267
+ description: "Distinct persons who evaluated the flag that day."
268
+ }
269
+ ],
270
+ responses: { feature_flag_usage: hogqlSchema }
271
+ },
272
+ posthog_active_users: {
273
+ shape: "metric",
274
+ description: "Daily active-user counts from a TrendsQuery, with one sample per day per rolling window (daily, weekly, and monthly active users).",
275
+ endpoint: "POST /api/projects/{projectId}/query (TrendsQuery)",
276
+ unit: "users",
277
+ granularity: "Daily (UTC)",
278
+ notes: "Rollup metrics are stamped at UTC midnight of the day they cover.",
279
+ dimensions: [
280
+ {
281
+ name: "window",
282
+ description: "The active-user window the sample belongs to: `dau`, `wau`, or `mau`."
283
+ }
284
+ ],
285
+ responses: { active_users: trendsSchema }
286
+ },
287
+ posthog_funnel: {
288
+ shape: "metric",
289
+ description: "Funnel conversion snapshot. One sample per declared funnel step, stamped at the start of the current UTC day, carrying the step user count and conversion rate relative to the first step. Only written when `funnels` are configured.",
290
+ endpoint: "POST /api/projects/{projectId}/query (FunnelsQuery)",
291
+ unit: "users",
292
+ granularity: "Snapshot per sync (start of UTC day)",
293
+ notes: "A single conversion snapshot measured over the lookback window, stamped at the start of the current UTC day, not a per-day time series.",
294
+ dimensions: [
295
+ { name: "funnel", description: "The configured funnel name." },
296
+ {
297
+ name: "step",
298
+ description: "Zero-based step order within the funnel."
299
+ },
300
+ {
301
+ name: "stepName",
302
+ description: "The event name for the step, if returned."
303
+ },
304
+ { name: "users", description: "Users who reached this step." },
305
+ {
306
+ name: "conversionRate",
307
+ description: "Step users divided by first-step users (0 when no base)."
308
+ }
309
+ ],
310
+ responses: { funnels: funnelSchema }
311
+ }
312
+ });
313
+ var id = "posthog";
199
314
  var PostHogConnector = class _PostHogConnector extends BaseConnector {
200
- static id = "posthog";
201
- static schemas = {
202
- feature_flags: z.array(featureFlagSchema),
203
- events_per_day: hogqlSchema,
204
- feature_flag_usage: hogqlSchema,
205
- active_users: trendsSchema,
206
- funnels: funnelSchema
207
- };
315
+ static id = id;
316
+ static resources = posthogResources;
317
+ static schemas = schemasFromResources(posthogResources);
208
318
  static create(input, ctx) {
209
319
  const parsed = configFields.parse(input);
210
320
  return new _PostHogConnector(
@@ -220,7 +330,7 @@ var PostHogConnector = class _PostHogConnector extends BaseConnector {
220
330
  ctx
221
331
  );
222
332
  }
223
- id = "posthog";
333
+ id = id;
224
334
  credentials = posthogCredentials;
225
335
  get baseUrl() {
226
336
  return this.settings.host.replace(/\/+$/, "");
@@ -551,6 +661,9 @@ var index_default = PostHogConnector;
551
661
  export {
552
662
  PostHogConnector,
553
663
  configFields,
554
- index_default as default
664
+ index_default as default,
665
+ doc,
666
+ id,
667
+ posthogResources as resources
555
668
  };
556
669
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../connector-shared/src/errors.ts","../../../connector-shared/src/retry.ts","../../../connector-shared/src/version.ts","../../../connector-shared/src/request.ts","../../../connector-shared/src/rate-limit.ts","../../../connector-shared/src/sanitize.ts","../../../connector-shared/src/epoch.ts","../../../connector-shared/src/pagination.ts","../../../connector-shared/src/logger.ts","../src/posthog.ts","../src/index.ts"],"sourcesContent":["import type { HttpResponse } from './types';\n\nexport type HttpErrorKind =\n | 'transient'\n | 'rate_limit'\n | 'auth'\n | 'upstream_bug'\n | 'client_bug';\n\nexport abstract class HttpClientError extends Error {\n abstract readonly kind: HttpErrorKind;\n readonly response?: HttpResponse;\n\n constructor(message: string, response?: HttpResponse) {\n super(message);\n this.name = new.target.name;\n this.response = response;\n }\n}\n\nexport class TransientError extends HttpClientError {\n readonly kind = 'transient' as const;\n}\n\nexport class RateLimitError extends HttpClientError {\n readonly kind = 'rate_limit' as const;\n readonly retryAfter?: Date;\n\n constructor(message: string, response?: HttpResponse, retryAfter?: Date) {\n super(message, response);\n this.retryAfter = retryAfter;\n }\n}\n\nexport class AuthError extends HttpClientError {\n readonly kind = 'auth' as const;\n}\n\nexport class UpstreamBugError extends HttpClientError {\n readonly kind = 'upstream_bug' as const;\n}\n\nexport class ClientBugError extends HttpClientError {\n readonly kind = 'client_bug' as const;\n}\n\nexport function classifyStatus(status: number): HttpErrorKind {\n if (status === 429) {\n return 'rate_limit';\n }\n if (status === 401 || status === 403) {\n return 'auth';\n }\n if (status === 408) {\n return 'transient';\n }\n if (status >= 500) {\n return 'upstream_bug';\n }\n if (status >= 400) {\n return 'client_bug';\n }\n return 'client_bug';\n}\n\nexport function errorForStatus(\n message: string,\n response: HttpResponse,\n retryAfter?: Date,\n): HttpClientError {\n const kind = classifyStatus(response.status);\n switch (kind) {\n case 'rate_limit':\n return new RateLimitError(message, response, retryAfter);\n case 'auth':\n return new AuthError(message, response);\n case 'transient':\n return new TransientError(message, response);\n case 'upstream_bug':\n return new UpstreamBugError(message, response);\n case 'client_bug':\n return new ClientBugError(message, response);\n }\n}\n","import { HttpClientError, RateLimitError, TransientError } from './errors';\n\nexport interface RetryPolicy {\n maxAttempts?: number;\n initialDelayMs?: number;\n maxDelayMs?: number;\n retryOn?: (status: number | null, err?: Error) => boolean;\n}\n\nexport const defaultRetryOn = (status: number | null, err?: Error): boolean => {\n if (err instanceof RateLimitError) {\n return true;\n }\n if (err instanceof TransientError) {\n return true;\n }\n if (status === null) {\n return err instanceof Error && !(err instanceof HttpClientError);\n }\n if (status === 408 || status === 429) {\n return true;\n }\n if (status >= 500) {\n return true;\n }\n return false;\n};\n\nexport function backoffDelayMs(\n attempt: number,\n policy: Required<Pick<RetryPolicy, 'initialDelayMs' | 'maxDelayMs'>>,\n): number {\n const base = policy.initialDelayMs * 2 ** attempt;\n const jitter = base * 0.25 * Math.random();\n return Math.min(base + jitter, policy.maxDelayMs);\n}\n\nexport function parseRetryAfter(\n headerValue: string | null,\n now: Date = new Date(),\n): Date | undefined {\n if (!headerValue) {\n return undefined;\n }\n const trimmed = headerValue.trim();\n if (/^\\d+$/.test(trimmed)) {\n return new Date(now.getTime() + Number(trimmed) * 1000);\n }\n const parsed = Date.parse(trimmed);\n if (Number.isNaN(parsed)) {\n return undefined;\n }\n return new Date(parsed);\n}\n\nexport function sleep(ms: number, signal?: AbortSignal): Promise<void> {\n if (signal?.aborted) {\n return Promise.reject(signal.reason ?? new Error('Aborted'));\n }\n return new Promise<void>((resolve, reject) => {\n const onAbort = () => {\n clearTimeout(timer);\n reject(signal!.reason ?? new Error('Aborted'));\n };\n const timer = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n}\n","export const HTTP_CLIENT_VERSION = '0.0.0';\n\nexport const DEFAULT_USER_AGENT = `rawdash-connector/${HTTP_CLIENT_VERSION} (+https://rawdash.dev)`;\n\nexport function connectorUserAgent(connectorId: string): string {\n return `rawdash-connector-${connectorId}/${HTTP_CLIENT_VERSION} (+https://rawdash.dev)`;\n}\n","import {\n AuthError,\n ClientBugError,\n HttpClientError,\n RateLimitError,\n TransientError,\n UpstreamBugError,\n errorForStatus,\n} from './errors';\nimport { defaultRetryOn, parseRetryAfter, sleep } from './retry';\nimport type { FetchLike, HttpMethod, HttpRequest, HttpResponse } from './types';\nimport { DEFAULT_USER_AGENT } from './version';\n\nconst DEFAULT_TIMEOUT_MS = 10_000;\nconst DEFAULT_MAX_ATTEMPTS = 3;\nconst DEFAULT_INITIAL_DELAY_MS = 1000;\nconst DEFAULT_MAX_DELAY_MS = 60_000;\nconst OBSERVER_TIMEOUT_MS = 250;\n\nexport interface RequestObservation {\n url: string;\n method: HttpMethod;\n status: number;\n resource: string;\n requestId: string;\n body: unknown;\n}\n\nexport type RequestObserver = (\n event: RequestObservation,\n) => void | Promise<void>;\n\nexport interface RequestOptions {\n fetch?: FetchLike;\n observer?: RequestObserver;\n resource: string;\n requestId?: string;\n}\n\nasync function notifyObserver(\n observer: RequestObserver,\n event: RequestObservation,\n): Promise<void> {\n let result: void | Promise<void>;\n try {\n result = observer(event);\n } catch (err) {\n console.warn('[connector-shared] request observer threw:', err);\n return;\n }\n if (!(result instanceof Promise)) {\n return;\n }\n const guarded = result.catch((err) => {\n console.warn('[connector-shared] request observer rejected:', err);\n });\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timeout = new Promise<void>((resolve) => {\n timer = setTimeout(resolve, OBSERVER_TIMEOUT_MS);\n });\n try {\n await Promise.race([guarded, timeout]);\n } finally {\n if (timer) {\n clearTimeout(timer);\n }\n }\n}\n\nfunction newRequestId(): string {\n const c = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto;\n if (c?.randomUUID) {\n return c.randomUUID();\n }\n return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;\n}\n\nfunction mergeHeaders(\n defaults: Record<string, string>,\n overrides: Record<string, string> | undefined,\n): Record<string, string> {\n const merged: Record<string, string> = {};\n for (const [k, v] of Object.entries(defaults)) {\n merged[k.toLowerCase()] = v;\n }\n if (overrides) {\n for (const [k, v] of Object.entries(overrides)) {\n merged[k.toLowerCase()] = v;\n }\n }\n return merged;\n}\n\nfunction linkTimeoutSignal(\n parent: AbortSignal | undefined,\n timeoutMs: number,\n): { signal: AbortSignal; cancel: () => void } {\n const controller = new AbortController();\n const onParentAbort = () => {\n controller.abort(parent?.reason);\n };\n if (parent) {\n if (parent.aborted) {\n controller.abort(parent.reason);\n } else {\n parent.addEventListener('abort', onParentAbort, { once: true });\n }\n }\n const timer = setTimeout(() => {\n controller.abort(new Error(`Request timed out after ${timeoutMs}ms`));\n }, timeoutMs);\n return {\n signal: controller.signal,\n cancel: () => {\n clearTimeout(timer);\n if (parent) {\n parent.removeEventListener('abort', onParentAbort);\n }\n },\n };\n}\n\nasync function readBody(res: Response, parseJson: boolean): Promise<unknown> {\n if (res.status === 204 || res.status === 205) {\n return null;\n }\n const contentType = res.headers.get('content-type') ?? '';\n if (parseJson && contentType.includes('application/json')) {\n const text = await res.text();\n if (text.length === 0) {\n return null;\n }\n return JSON.parse(text);\n }\n return res.text();\n}\n\nexport async function request<T = unknown>(\n req: HttpRequest,\n options: RequestOptions,\n): Promise<HttpResponse<T>> {\n const fetchImpl: FetchLike = options.fetch ?? (globalThis.fetch as FetchLike);\n const retry = req.retry ?? {};\n const maxAttempts = retry.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;\n const initialDelayMs = retry.initialDelayMs ?? DEFAULT_INITIAL_DELAY_MS;\n const maxDelayMs = retry.maxDelayMs ?? DEFAULT_MAX_DELAY_MS;\n const retryOn = retry.retryOn ?? defaultRetryOn;\n const timeoutMs = req.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const parseJson = req.parseJson ?? true;\n\n const headers = mergeHeaders(\n {\n 'User-Agent': DEFAULT_USER_AGENT,\n Accept: 'application/json',\n },\n req.headers,\n );\n\n let lastErr: Error | undefined;\n\n for (let attempt = 0; attempt < maxAttempts; attempt++) {\n req.signal?.throwIfAborted();\n\n const { signal, cancel } = linkTimeoutSignal(req.signal, timeoutMs);\n let res: Response;\n try {\n res = await fetchImpl(req.url, {\n method: req.method ?? 'GET',\n headers,\n body: req.body as RequestInit['body'],\n signal,\n });\n } catch (err) {\n cancel();\n if (req.signal?.aborted) {\n throw req.signal.reason ?? err;\n }\n const error = err instanceof Error ? err : new Error(String(err));\n lastErr = error;\n if (attempt < maxAttempts - 1 && retryOn(null, error)) {\n const delay = computeDelay(attempt, initialDelayMs, maxDelayMs);\n await sleep(delay, req.signal);\n continue;\n }\n throw new TransientError(error.message);\n }\n cancel();\n\n const body = await readBody(res, parseJson);\n const httpResponse: HttpResponse<T> = {\n status: res.status,\n headers: res.headers,\n body: body as T,\n };\n if (req.rateLimit) {\n const state = req.rateLimit.parse(res.headers);\n if (state) {\n httpResponse.rateLimitState = state;\n }\n }\n\n if (options.observer) {\n await notifyObserver(options.observer, {\n url: req.url,\n method: req.method ?? 'GET',\n status: res.status,\n resource: options.resource,\n requestId: options.requestId ?? newRequestId(),\n body,\n });\n }\n\n if (res.ok) {\n return httpResponse;\n }\n\n const retryAfter = parseRetryAfter(res.headers.get('retry-after'));\n const message = `HTTP ${res.status} ${res.statusText} for ${req.method ?? 'GET'} ${req.url}`;\n const err = errorForStatus(message, httpResponse, retryAfter);\n\n if (\n attempt < maxAttempts - 1 &&\n retryOn(res.status, err) &&\n !(err instanceof AuthError) &&\n !(err instanceof ClientBugError)\n ) {\n lastErr = err;\n let delay = computeDelay(attempt, initialDelayMs, maxDelayMs);\n if (err instanceof RateLimitError && retryAfter) {\n const wait = retryAfter.getTime() - Date.now();\n if (wait > 0) {\n delay = Math.min(wait, maxDelayMs);\n }\n }\n await sleep(delay, req.signal);\n continue;\n }\n\n throw err;\n }\n\n throw lastErr ?? new UpstreamBugError('Exhausted retry attempts');\n}\n\nfunction computeDelay(\n attempt: number,\n initialDelayMs: number,\n maxDelayMs: number,\n): number {\n const base = initialDelayMs * 2 ** attempt;\n const jitter = base * 0.25 * Math.random();\n return Math.min(base + jitter, maxDelayMs);\n}\n\nexport { HttpClientError };\n","export interface RateLimitState {\n remaining: number;\n resetAt: Date;\n}\n\nexport interface RateLimitPolicy {\n parse(headers: Headers): RateLimitState | null;\n}\n\nexport interface StandardRateLimitPolicyConfig {\n remainingHeader: string;\n resetHeader: string;\n resetUnit: 's' | 'ms';\n resetFallbackMs?: number;\n}\n\nexport function standardRateLimitPolicy(\n config: StandardRateLimitPolicyConfig,\n): RateLimitPolicy {\n const { remainingHeader, resetHeader, resetUnit, resetFallbackMs } = config;\n const multiplier = resetUnit === 's' ? 1000 : 1;\n return {\n parse(h) {\n const remainingRaw = h.get(remainingHeader);\n if (remainingRaw === null || remainingRaw.trim() === '') {\n return null;\n }\n const remaining = Number(remainingRaw);\n if (!Number.isFinite(remaining)) {\n return null;\n }\n const resetRaw = h.get(resetHeader);\n if (resetRaw === null) {\n if (resetFallbackMs === undefined) {\n return null;\n }\n return {\n remaining,\n resetAt: new Date(Date.now() + resetFallbackMs),\n };\n }\n if (resetRaw.trim() === '') {\n return null;\n }\n const reset = Number(resetRaw);\n if (!Number.isFinite(reset) || reset < 0) {\n return null;\n }\n const resetMs = reset * multiplier;\n if (!Number.isFinite(resetMs)) {\n return null;\n }\n return { remaining, resetAt: new Date(resetMs) };\n },\n };\n}\n","export interface SanitizeAllowedUrlOptions {\n url: string | null;\n host: string;\n pathname: string;\n protocol?: 'https:' | 'http:';\n}\n\nexport function sanitizeAllowedUrl(\n options: SanitizeAllowedUrlOptions,\n): string | null {\n const { url, host, pathname, protocol = 'https:' } = options;\n if (url === null) {\n return null;\n }\n try {\n const u = new URL(url);\n if (u.protocol !== protocol || u.host !== host || u.pathname !== pathname) {\n return null;\n }\n return u.toString();\n } catch {\n return null;\n }\n}\n","export type EpochUnit = 'ms' | 's' | 'iso';\n\nexport function parseEpoch(\n value: number | string | null | undefined,\n unit: EpochUnit,\n): number | null {\n if (value === null || value === undefined) {\n return null;\n }\n if (unit === 'iso') {\n if (typeof value !== 'string') {\n return null;\n }\n const ms = new Date(value).getTime();\n return Number.isFinite(ms) ? ms : null;\n }\n if (typeof value === 'string' && value.trim() === '') {\n return null;\n }\n const n = typeof value === 'number' ? value : Number(value);\n if (!Number.isFinite(n)) {\n return null;\n }\n const result = unit === 's' ? n * 1000 : n;\n return Number.isFinite(result) ? result : null;\n}\n","import { request } from './request';\nimport type { HttpRequest } from './types';\n\nexport function parseLinkHeader(header: string | null): Record<string, string> {\n if (!header) {\n return {};\n }\n const result: Record<string, string> = {};\n for (const part of header.split(',')) {\n const match = part.match(/<([^>]+)>\\s*;\\s*rel=\"([^\"]+)\"/);\n if (match) {\n result[match[2]!] = match[1]!;\n }\n }\n return result;\n}\n\nexport async function* paginateLink<T>(\n initial: HttpRequest,\n parse: (body: unknown) => T[],\n options: { resource: string },\n): AsyncIterable<T> {\n let next: string | null = initial.url;\n while (next) {\n const res: Awaited<ReturnType<typeof request>> = await request(\n {\n ...initial,\n url: next,\n },\n { resource: options.resource },\n );\n for (const item of parse(res.body)) {\n yield item;\n }\n const links = parseLinkHeader(res.headers.get('link'));\n next = links['next'] ?? null;\n }\n}\n\nexport async function* paginateCursor<T>(\n initial: HttpRequest,\n parse: (body: unknown) => { items: T[]; nextCursor: string | null },\n buildNext: (req: HttpRequest, cursor: string) => HttpRequest,\n options: { resource: string },\n): AsyncIterable<T> {\n let req: HttpRequest = initial;\n while (true) {\n const res = await request(req, { resource: options.resource });\n const { items, nextCursor } = parse(res.body);\n for (const item of items) {\n yield item;\n }\n if (!nextCursor) {\n return;\n }\n req = buildNext(req, nextCursor);\n }\n}\n\nexport async function* paginatePage<T>(\n initial: HttpRequest,\n parse: (body: unknown) => { items: T[]; hasMore: boolean },\n buildPage: (req: HttpRequest, page: number) => HttpRequest,\n options: { resource: string },\n): AsyncIterable<T> {\n let page = 1;\n while (true) {\n const req = page === 1 ? initial : buildPage(initial, page);\n const res = await request(req, { resource: options.resource });\n const { items, hasMore } = parse(res.body);\n for (const item of items) {\n yield item;\n }\n if (!hasMore || items.length === 0) {\n return;\n }\n page++;\n }\n}\n","export type LogFields = Record<string, unknown>;\n\nexport interface ConnectorLogger {\n info(event: string, fields?: LogFields): void;\n warn(event: string, fields?: LogFields): void;\n}\n\nexport interface ConnectorLoggerOptions {\n scope: string;\n}\n\nconst MAX_VALUE_LEN = 120;\n\nfunction truncate(s: string, max = MAX_VALUE_LEN): string {\n if (s.length <= max) {\n return s;\n }\n return `${s.slice(0, max - 1)}…`;\n}\n\nfunction formatValue(value: unknown): string {\n if (value === null) {\n return 'null';\n }\n if (value === undefined) {\n return '';\n }\n if (typeof value === 'number' || typeof value === 'boolean') {\n return String(value);\n }\n if (typeof value === 'string') {\n const t = truncate(value);\n if (/[\\s\"=]/.test(t)) {\n return JSON.stringify(t);\n }\n return t;\n }\n if (typeof value === 'bigint') {\n return value.toString();\n }\n let json: string | undefined;\n try {\n json = JSON.stringify(value);\n } catch {\n json = undefined;\n }\n return truncate(json ?? String(value));\n}\n\nexport function formatLogFields(fields?: LogFields): string {\n if (!fields) {\n return '';\n }\n const parts: string[] = [];\n for (const [k, v] of Object.entries(fields)) {\n if (v === undefined) {\n continue;\n }\n parts.push(`${k}=${formatValue(v)}`);\n }\n return parts.length > 0 ? ` ${parts.join(' ')}` : '';\n}\n\nexport function formatLogLine(\n scope: string,\n event: string,\n fields?: LogFields,\n): string {\n return `[${scope}] ${event}${formatLogFields(fields)}`;\n}\n\nexport function createDefaultConnectorLogger(\n opts: ConnectorLoggerOptions,\n): ConnectorLogger {\n return {\n info(event, fields) {\n console.info(formatLogLine(opts.scope, event, fields));\n },\n warn(event, fields) {\n console.warn(formatLogLine(opts.scope, event, fields));\n },\n };\n}\n\nconst NOOP_LOGGER: ConnectorLogger = {\n info() {},\n warn() {},\n};\n\nexport function noopConnectorLogger(): ConnectorLogger {\n return NOOP_LOGGER;\n}\n","import { connectorUserAgent, parseEpoch } from '@rawdash/connector-shared';\nimport {\n BaseConnector,\n type ConnectorContext,\n type CredentialsSchema,\n type StorageHandle,\n type SyncOptions,\n type SyncResult,\n defineConfigFields,\n makeChunkedCursorGuard,\n paginateChunked,\n selectActivePhases,\n} from '@rawdash/core';\nimport { z } from 'zod';\n\n// ---------------------------------------------------------------------------\n// configFields\n// ---------------------------------------------------------------------------\n\nconst funnelDefinition = z.object({\n name: z.string().min(1),\n steps: z.array(z.string().min(1)).min(2),\n windowDays: z.number().int().positive().optional(),\n});\n\nexport const configFields = defineConfigFields(\n z.object({\n apiKey: z.object({ $secret: z.string() }).meta({\n label: 'Personal API key',\n description:\n 'PostHog personal API key with read access to the project. Create one at PostHog → Settings → Personal API keys (starts with `phx_`).',\n placeholder: 'phx_...',\n secret: true,\n }),\n projectId: z\n .string()\n .trim()\n .regex(/^\\d+$/, 'PostHog project ID must be digits only')\n .meta({\n label: 'Project ID',\n description:\n 'Numeric ID of your PostHog project. Find it in PostHog → Settings → Project → Project ID.',\n placeholder: '12345',\n }),\n host: z\n .string()\n .trim()\n .regex(\n /^https?:\\/\\/[^\\s/]+$/,\n 'Use a base URL with protocol and no trailing slash, e.g. https://us.posthog.com',\n )\n .default('https://us.posthog.com')\n .meta({\n label: 'Host',\n description:\n 'PostHog instance base URL. Use https://us.posthog.com or https://eu.posthog.com for PostHog Cloud, or your self-hosted origin. No trailing slash.',\n placeholder: 'https://us.posthog.com',\n }),\n events: z.array(z.string().min(1)).nonempty().optional().meta({\n label: 'Tracked events',\n description:\n 'Event names to roll up in the `events_per_day` resource. Omit to roll up every event in the project.',\n }),\n funnels: z.array(funnelDefinition).nonempty().optional().meta({\n label: 'Funnels',\n description:\n 'Funnel definitions to evaluate. Each funnel is { name, steps: [event, …], windowDays? }. Conversion is measured over the sync window.',\n }),\n lookbackDays: z.number().int().positive().optional().meta({\n label: 'Lookback days (full sync)',\n description:\n 'How many calendar days of history to roll up on a full sync. Defaults to 30.',\n placeholder: '30',\n }),\n resources: z\n .array(\n z.enum([\n 'feature_flags',\n 'events_per_day',\n 'feature_flag_usage',\n 'active_users',\n 'funnels',\n ]),\n )\n .nonempty()\n .optional()\n .meta({\n label: 'Resources',\n description:\n 'Which PostHog resources to sync. Omit to sync all of them.',\n }),\n }),\n);\n\n// ---------------------------------------------------------------------------\n// Settings / credentials\n// ---------------------------------------------------------------------------\n\nexport interface PostHogFunnel {\n name: string;\n steps: readonly string[];\n windowDays?: number;\n}\n\nexport interface PostHogSettings {\n projectId: string;\n host: string;\n events?: readonly string[];\n funnels?: readonly PostHogFunnel[];\n lookbackDays?: number;\n resources?: readonly PostHogResource[];\n}\n\nconst posthogCredentials = {\n apiKey: {\n description: 'PostHog personal API key',\n auth: 'required' as const,\n },\n} satisfies CredentialsSchema;\n\ntype PostHogCredentials = typeof posthogCredentials;\n\n// ---------------------------------------------------------------------------\n// Sync phases + cursor\n// ---------------------------------------------------------------------------\n\nconst PHASE_ORDER = [\n 'feature_flags',\n 'events_per_day',\n 'feature_flag_usage',\n 'active_users',\n 'funnels',\n] as const;\n\ntype PostHogPhase = (typeof PHASE_ORDER)[number];\n\nexport type PostHogResource = PostHogPhase;\n\nconst isPostHogSyncCursor = makeChunkedCursorGuard(PHASE_ORDER);\n\nconst FLAGS_PAGE_SIZE = 100;\nconst QUERY_PAGE_SIZE = 10_000;\nconst DEFAULT_LOOKBACK_DAYS = 30;\nconst DEFAULT_FUNNEL_WINDOW_DAYS = 14;\nconst MS_PER_DAY = 24 * 60 * 60 * 1000;\n\nconst FEATURE_FLAG_ENTITY = 'posthog_feature_flag';\nconst EVENTS_PER_DAY_METRIC = 'posthog_events_per_day';\nconst FLAG_USAGE_METRIC = 'posthog_feature_flag_usage';\nconst ACTIVE_USERS_METRIC = 'posthog_active_users';\nconst FUNNEL_METRIC = 'posthog_funnel';\n\n// Series order requested in the active-users TrendsQuery; the response keeps\n// this order so the index maps back to the active-user window.\nconst ACTIVE_USER_WINDOWS = ['dau', 'wau', 'mau'] as const;\nconst ACTIVE_USER_MATH = ['dau', 'weekly_active', 'monthly_active'] as const;\n\n// ---------------------------------------------------------------------------\n// PostHog API types\n// ---------------------------------------------------------------------------\n\ninterface FeatureFlagRecord {\n id: number;\n key: string;\n name?: string | null;\n active: boolean;\n rollout_percentage?: number | null;\n created_at?: string | null;\n filters?: unknown;\n}\n\ninterface FeatureFlagListResponse {\n count?: number;\n next?: string | null;\n results: FeatureFlagRecord[];\n}\n\ninterface HogQLResponse {\n results: Array<Array<string | number | boolean | null>>;\n}\n\ninterface TrendsResponse {\n results: Array<{\n data: number[];\n days: string[];\n label?: string | null;\n }>;\n}\n\ninterface FunnelStepResult {\n count: number;\n name?: string | null;\n order?: number | null;\n}\n\ninterface FunnelResponse {\n results: FunnelStepResult[];\n}\n\n// ---------------------------------------------------------------------------\n// Value helpers\n// ---------------------------------------------------------------------------\n\nfunction finiteNumber(value: unknown, fallback = 0): number {\n const n = typeof value === 'number' ? value : Number(value);\n return Number.isFinite(n) ? n : fallback;\n}\n\nfunction finiteNumberOrNull(value: unknown): number | null {\n if (value === null || value === undefined || value === '') {\n return null;\n }\n const n = typeof value === 'number' ? value : Number(value);\n return Number.isFinite(n) ? n : null;\n}\n\nfunction stringOrNull(value: unknown): string | null {\n return typeof value === 'string' ? value : null;\n}\n\n// PostHog dates from HogQL come back as 'YYYY-MM-DD' (or full timestamps).\n// Treat them as UTC midnight so re-syncing the same day is idempotent.\nfunction dateStringToMs(value: unknown): number | null {\n if (typeof value !== 'string') {\n return null;\n }\n const trimmed = value.trim();\n if (trimmed === '') {\n return null;\n }\n const isoLike = /^\\d{4}-\\d{2}-\\d{2}$/.test(trimmed)\n ? `${trimmed}T00:00:00.000Z`\n : trimmed;\n return parseEpoch(isoLike, 'iso');\n}\n\n// Filters are an opaque, deeply-nested PostHog payload. Persist a JSON snapshot\n// rather than the raw object so no `undefined` (or non-serializable value)\n// leaks into entity attributes.\nfunction stringifyFilters(value: unknown): string | null {\n if (value === undefined || value === null) {\n return null;\n }\n try {\n const json = JSON.stringify(value);\n return json === undefined ? null : json;\n } catch {\n return null;\n }\n}\n\nfunction startOfUtcDay(ms: number): number {\n return Math.floor(ms / MS_PER_DAY) * MS_PER_DAY;\n}\n\nfunction safeOffset(page: string | null): number {\n if (page === null) {\n return 0;\n }\n const n = Number(page);\n return Number.isFinite(n) && n >= 0 ? Math.floor(n) : 0;\n}\n\nfunction quoteHogQLString(value: string): string {\n return `'${value.replace(/\\\\/g, '\\\\\\\\').replace(/'/g, \"\\\\'\")}'`;\n}\n\n// ---------------------------------------------------------------------------\n// Schemas — describe the per-resource API response shape consumed by request()\n// ---------------------------------------------------------------------------\n\nconst featureFlagSchema = z.object({\n id: z.number(),\n key: z.string().min(1),\n name: z.string().nullish(),\n active: z.boolean(),\n rollout_percentage: z.number().nullish(),\n created_at: z.string().nullish(),\n});\n\n// HogQL grouped rollups return positional rows: [day, key, count, distinct].\nconst dailyCountRow = z.tuple([\n z.string(),\n z.string().nullable(),\n z.number(),\n z.number(),\n]);\n\nconst hogqlSchema = z.object({ results: z.array(dailyCountRow) });\n\nconst trendsSchema = z.object({\n results: z.array(\n z.object({\n data: z.array(z.number()),\n days: z.array(z.string()),\n label: z.string().nullish(),\n }),\n ),\n});\n\nconst funnelSchema = z.object({\n results: z.array(\n z.object({\n count: z.number(),\n name: z.string().nullish(),\n order: z.number().nullish(),\n }),\n ),\n});\n\n// ---------------------------------------------------------------------------\n// PostHogConnector\n// ---------------------------------------------------------------------------\n\nexport class PostHogConnector extends BaseConnector<\n PostHogSettings,\n PostHogCredentials\n> {\n static readonly id = 'posthog';\n\n static readonly schemas = {\n feature_flags: z.array(featureFlagSchema),\n events_per_day: hogqlSchema,\n feature_flag_usage: hogqlSchema,\n active_users: trendsSchema,\n funnels: funnelSchema,\n } as const;\n\n static create(input: unknown, ctx?: ConnectorContext): PostHogConnector {\n const parsed = configFields.parse(input);\n return new PostHogConnector(\n {\n projectId: parsed.projectId,\n host: parsed.host,\n events: parsed.events,\n funnels: parsed.funnels,\n lookbackDays: parsed.lookbackDays,\n resources: parsed.resources,\n },\n { apiKey: parsed.apiKey },\n ctx,\n );\n }\n\n readonly id = 'posthog';\n override readonly credentials = posthogCredentials;\n\n private get baseUrl(): string {\n return this.settings.host.replace(/\\/+$/, '');\n }\n\n private buildHeaders(): Record<string, string> {\n return {\n Authorization: `Bearer ${this.creds.apiKey}`,\n 'Content-Type': 'application/json',\n 'User-Agent': connectorUserAgent('posthog'),\n };\n }\n\n // ISO date (YYYY-MM-DD) that bounds the rollup window. Metric phases use\n // clear-and-rewrite, so the window must always cover the full lookback or\n // an incremental tick would wipe history and only rewrite a narrower slice.\n // A `since` earlier than the lookback extends the window; a later `since`\n // is ignored.\n private windowStartDate(options: SyncOptions): string {\n const lookbackDays = this.settings.lookbackDays ?? DEFAULT_LOOKBACK_DAYS;\n const now = Date.now();\n let startMs = now - (lookbackDays - 1) * MS_PER_DAY;\n if (options.since) {\n const sinceMs = new Date(options.since).getTime();\n if (Number.isFinite(sinceMs) && sinceMs < startMs) {\n startMs = sinceMs;\n }\n }\n return new Date(startMs).toISOString().slice(0, 10);\n }\n\n private runQuery<T>(\n query: Record<string, unknown>,\n resource: PostHogPhase,\n signal?: AbortSignal,\n ): Promise<T> {\n return this.post<T>(\n `${this.baseUrl}/api/projects/${this.settings.projectId}/query`,\n {\n resource,\n headers: this.buildHeaders(),\n body: JSON.stringify({ query }),\n signal,\n },\n ).then((res) => res.body);\n }\n\n // -------------------------------------------------------------------------\n // feature_flags — paginated REST list (entities)\n // -------------------------------------------------------------------------\n\n private async fetchFeatureFlagsPage(\n page: string | null,\n signal?: AbortSignal,\n ): Promise<{ items: unknown[]; next: string | null }> {\n const offset = safeOffset(page);\n const url = new URL(\n `${this.baseUrl}/api/projects/${this.settings.projectId}/feature_flags/`,\n );\n url.searchParams.set('limit', String(FLAGS_PAGE_SIZE));\n url.searchParams.set('offset', String(offset));\n const res = await this.get<FeatureFlagListResponse>(url.toString(), {\n resource: 'feature_flags',\n headers: this.buildHeaders(),\n signal,\n });\n const results = res.body.results;\n // Build the next offset ourselves rather than echoing the API's absolute\n // `next` URL back into fetch(), avoiding any SSRF surface from a tampered\n // cursor while still stopping once a short page comes back.\n const next =\n res.body.next && results.length === FLAGS_PAGE_SIZE\n ? String(offset + FLAGS_PAGE_SIZE)\n : null;\n return { items: results, next };\n }\n\n private async writeFeatureFlags(\n storage: StorageHandle,\n items: FeatureFlagRecord[],\n ): Promise<void> {\n for (const flag of items) {\n await storage.entity({\n type: FEATURE_FLAG_ENTITY,\n id: String(flag.id),\n attributes: {\n key: flag.key,\n name: flag.name ?? null,\n active: flag.active,\n rolloutPercentage: finiteNumberOrNull(flag.rollout_percentage),\n filters: stringifyFilters(flag.filters),\n },\n updated_at: parseEpoch(flag.created_at ?? null, 'iso') ?? 0,\n });\n }\n }\n\n // -------------------------------------------------------------------------\n // events_per_day — HogQL grouped by (day, event)\n // -------------------------------------------------------------------------\n\n private async fetchEventsPerDay(\n startDate: string,\n page: string | null,\n signal?: AbortSignal,\n ): Promise<{ items: unknown[]; next: string | null }> {\n const offset = safeOffset(page);\n const clauses = [`timestamp >= toDateTime(${quoteHogQLString(startDate)})`];\n const events = this.settings.events;\n if (events && events.length > 0) {\n const list = events.map(quoteHogQLString).join(', ');\n clauses.push(`event IN (${list})`);\n }\n const sql =\n `SELECT toString(toDate(timestamp)) AS day, event AS event, ` +\n `count() AS total, count(DISTINCT person_id) AS users ` +\n `FROM events WHERE ${clauses.join(' AND ')} ` +\n `GROUP BY day, event ORDER BY day, event ` +\n `LIMIT ${QUERY_PAGE_SIZE} OFFSET ${offset}`;\n const body = await this.runQuery<HogQLResponse>(\n { kind: 'HogQLQuery', query: sql },\n 'events_per_day',\n signal,\n );\n const next =\n body.results.length === QUERY_PAGE_SIZE\n ? String(offset + QUERY_PAGE_SIZE)\n : null;\n return { items: body.results, next };\n }\n\n private async writeEventsPerDay(\n storage: StorageHandle,\n rows: HogQLResponse['results'],\n ): Promise<void> {\n for (const row of rows) {\n const ts = dateStringToMs(row[0]);\n if (ts === null) {\n continue;\n }\n const count = finiteNumber(row[2]);\n await storage.metric({\n name: EVENTS_PER_DAY_METRIC,\n ts,\n value: count,\n attributes: {\n event: stringOrNull(row[1]),\n count,\n distinctUsers: finiteNumber(row[3]),\n },\n });\n }\n }\n\n // -------------------------------------------------------------------------\n // feature_flag_usage — HogQL over $feature_flag_called events\n // -------------------------------------------------------------------------\n\n private async fetchFlagUsage(\n startDate: string,\n page: string | null,\n signal?: AbortSignal,\n ): Promise<{ items: unknown[]; next: string | null }> {\n const offset = safeOffset(page);\n const sql =\n `SELECT toString(toDate(timestamp)) AS day, ` +\n `properties.$feature_flag AS flag, count() AS calls, ` +\n `count(DISTINCT person_id) AS users FROM events ` +\n `WHERE event = '$feature_flag_called' AND ` +\n `timestamp >= toDateTime(${quoteHogQLString(startDate)}) ` +\n `GROUP BY day, flag ORDER BY day, flag ` +\n `LIMIT ${QUERY_PAGE_SIZE} OFFSET ${offset}`;\n const body = await this.runQuery<HogQLResponse>(\n { kind: 'HogQLQuery', query: sql },\n 'feature_flag_usage',\n signal,\n );\n const next =\n body.results.length === QUERY_PAGE_SIZE\n ? String(offset + QUERY_PAGE_SIZE)\n : null;\n return { items: body.results, next };\n }\n\n private async writeFlagUsage(\n storage: StorageHandle,\n rows: HogQLResponse['results'],\n ): Promise<void> {\n for (const row of rows) {\n const ts = dateStringToMs(row[0]);\n if (ts === null) {\n continue;\n }\n const callCount = finiteNumber(row[2]);\n await storage.metric({\n name: FLAG_USAGE_METRIC,\n ts,\n value: callCount,\n attributes: {\n flagKey: stringOrNull(row[1]),\n callCount,\n uniqueUsers: finiteNumber(row[3]),\n },\n });\n }\n }\n\n // -------------------------------------------------------------------------\n // active_users — TrendsQuery (dau / wau / mau)\n // -------------------------------------------------------------------------\n\n private async fetchActiveUsers(\n startDate: string,\n signal?: AbortSignal,\n ): Promise<{ items: unknown[]; next: null }> {\n const body = await this.runQuery<TrendsResponse>(\n {\n kind: 'TrendsQuery',\n dateRange: { date_from: startDate },\n interval: 'day',\n series: ACTIVE_USER_MATH.map((math) => ({\n kind: 'EventsNode',\n event: null,\n math,\n })),\n },\n 'active_users',\n signal,\n );\n return { items: body.results, next: null };\n }\n\n private async writeActiveUsers(\n storage: StorageHandle,\n series: TrendsResponse['results'],\n ): Promise<void> {\n for (let i = 0; i < series.length; i++) {\n const entry = series[i]!;\n const window = ACTIVE_USER_WINDOWS[i] ?? `series_${i}`;\n const data = entry.data ?? [];\n const days = entry.days ?? [];\n const n = Math.min(data.length, days.length);\n for (let j = 0; j < n; j++) {\n const ts = dateStringToMs(days[j]);\n if (ts === null) {\n continue;\n }\n await storage.metric({\n name: ACTIVE_USERS_METRIC,\n ts,\n value: finiteNumber(data[j]),\n attributes: { window },\n });\n }\n }\n }\n\n // -------------------------------------------------------------------------\n // funnels — one FunnelsQuery per declared funnel (index-paged)\n // -------------------------------------------------------------------------\n\n private async fetchFunnelPage(\n page: string | null,\n startDate: string,\n signal?: AbortSignal,\n ): Promise<{ items: unknown[]; next: string | null }> {\n const funnels = this.settings.funnels ?? [];\n const index = safeOffset(page);\n if (index >= funnels.length) {\n return { items: [], next: null };\n }\n const funnel = funnels[index]!;\n const body = await this.runQuery<FunnelResponse>(\n {\n kind: 'FunnelsQuery',\n dateRange: { date_from: startDate },\n series: funnel.steps.map((event) => ({ kind: 'EventsNode', event })),\n funnelWindowInterval: funnel.windowDays ?? DEFAULT_FUNNEL_WINDOW_DAYS,\n funnelWindowIntervalUnit: 'day',\n },\n 'funnels',\n signal,\n );\n // Tag each step row with its funnel so writeBatch stays stateless.\n const items = body.results.map((step) => ({ funnel, step }));\n const next = index + 1 < funnels.length ? String(index + 1) : null;\n return { items, next };\n }\n\n private async writeFunnelSteps(\n storage: StorageHandle,\n items: Array<{ funnel: PostHogFunnel; step: FunnelStepResult }>,\n ): Promise<void> {\n // Snapshot timestamp: funnel conversion is measured over the whole window,\n // so stamp every step at the start of the current UTC day.\n const ts = startOfUtcDay(Date.now());\n for (const { funnel, step } of items) {\n const users = finiteNumber(step.count);\n const base = items.find(\n (it) => it.funnel === funnel && (it.step.order ?? 0) === 0,\n )?.step.count;\n const baseUsers = finiteNumber(base);\n const conversionRate = baseUsers > 0 ? users / baseUsers : 0;\n await storage.metric({\n name: FUNNEL_METRIC,\n ts,\n value: users,\n attributes: {\n funnel: funnel.name,\n step: finiteNumber(step.order),\n stepName: stringOrNull(step.name),\n users,\n conversionRate,\n },\n });\n }\n }\n\n // -------------------------------------------------------------------------\n // Scope clearing (idempotency)\n // -------------------------------------------------------------------------\n\n private async clearScopeOnFirstPage(\n storage: StorageHandle,\n phase: PostHogPhase,\n isFull: boolean,\n ): Promise<void> {\n switch (phase) {\n case 'feature_flags':\n // Entities upsert by id; only a full backfill drops stale rows.\n if (isFull) {\n await storage.entities([], { types: [FEATURE_FLAG_ENTITY] });\n }\n return;\n case 'events_per_day':\n await storage.metrics([], { names: [EVENTS_PER_DAY_METRIC] });\n return;\n case 'feature_flag_usage':\n await storage.metrics([], { names: [FLAG_USAGE_METRIC] });\n return;\n case 'active_users':\n await storage.metrics([], { names: [ACTIVE_USERS_METRIC] });\n return;\n case 'funnels':\n await storage.metrics([], { names: [FUNNEL_METRIC] });\n return;\n }\n }\n\n private async writePhase(\n storage: StorageHandle,\n phase: PostHogPhase,\n items: unknown[],\n ): Promise<void> {\n switch (phase) {\n case 'feature_flags':\n await this.writeFeatureFlags(storage, items as FeatureFlagRecord[]);\n return;\n case 'events_per_day':\n await this.writeEventsPerDay(\n storage,\n items as HogQLResponse['results'],\n );\n return;\n case 'feature_flag_usage':\n await this.writeFlagUsage(storage, items as HogQLResponse['results']);\n return;\n case 'active_users':\n await this.writeActiveUsers(\n storage,\n items as TrendsResponse['results'],\n );\n return;\n case 'funnels':\n await this.writeFunnelSteps(\n storage,\n items as Array<{ funnel: PostHogFunnel; step: FunnelStepResult }>,\n );\n return;\n }\n }\n\n async sync(\n options: SyncOptions,\n storage: StorageHandle,\n signal?: AbortSignal,\n ): Promise<SyncResult> {\n const cursor = isPostHogSyncCursor(options.cursor)\n ? options.cursor\n : undefined;\n const isFull = options.mode === 'full';\n const startDate = this.windowStartDate(options);\n\n const phases = selectActivePhases<PostHogResource, PostHogPhase>(\n (r) => r,\n PHASE_ORDER,\n this.settings.resources,\n );\n\n return paginateChunked<PostHogPhase, string>({\n phases,\n cursor,\n signal,\n logger: this.logger,\n fetchPage: async (phase, page, sig) => {\n switch (phase) {\n case 'feature_flags':\n return this.fetchFeatureFlagsPage(page, sig);\n case 'events_per_day':\n return this.fetchEventsPerDay(startDate, page, sig);\n case 'feature_flag_usage':\n return this.fetchFlagUsage(startDate, page, sig);\n case 'active_users':\n return this.fetchActiveUsers(startDate, sig);\n case 'funnels':\n return this.fetchFunnelPage(page, startDate, sig);\n }\n },\n writeBatch: async (phase, items, page) => {\n if (page === null) {\n await this.clearScopeOnFirstPage(storage, phase, isFull);\n }\n await this.writePhase(storage, phase, items);\n },\n });\n }\n}\n","import { PostHogConnector } from './posthog';\n\nexport { configFields, PostHogConnector } from './posthog';\nexport type {\n PostHogSettings,\n PostHogResource,\n PostHogFunnel,\n} from './posthog';\nexport default PostHogConnector;\n"],"mappings":";AEAO,IAAM,sBAAsB;AAE5B,IAAM,qBAAqB,qBAAqB,mBAAmB;AAEnE,SAAS,mBAAmB,aAA6B;AAC9D,SAAO,qBAAqB,WAAW,IAAI,mBAAmB;AAChE;AIJO,SAAS,WACd,OACA,MACe;AACf,MAAI,UAAU,QAAQ,UAAU,QAAW;AACzC,WAAO;EACT;AACA,MAAI,SAAS,OAAO;AAClB,QAAI,OAAO,UAAU,UAAU;AAC7B,aAAO;IACT;AACA,UAAM,KAAK,IAAI,KAAK,KAAK,EA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EACF;AAAA,EAEA,MAAM,KACJ,SACA,SACA,QACqB;AACrB,UAAM,SAAS,oBAAoB,QAAQ,MAAM,IAC7C,QAAQ,SACR;AACJ,UAAM,SAAS,QAAQ,SAAS;AAChC,UAAM,YAAY,KAAK,gBAAgB,OAAO;AAE9C,UAAM,SAAS;AAAA,MACb,CAAC,MAAM;AAAA,MACP;AAAA,MACA,KAAK,SAAS;AAAA,IAChB;AAEA,WAAO,gBAAsC;AAAA,MAC3C;AAAA,MACA;AAAA,MACA;AAAA,MACA,QAAQ,KAAK;AAAA,MACb,WAAW,OAAO,OAAO,MAAM,QAAQ;AACrC,gBAAQ,OAAO;AAAA,UACb,KAAK;AACH,mBAAO,KAAK,sBAAsB,MAAM,GAAG;AAAA,UAC7C,KAAK;AACH,mBAAO,KAAK,kBAAkB,WAAW,MAAM,GAAG;AAAA,UACpD,KAAK;AACH,mBAAO,KAAK,eAAe,WAAW,MAAM,GAAG;AAAA,UACjD,KAAK;AACH,mBAAO,KAAK,iBAAiB,WAAW,GAAG;AAAA,UAC7C,KAAK;AACH,mBAAO,KAAK,gBAAgB,MAAM,WAAW,GAAG;AAAA,QACpD;AAAA,MACF;AAAA,MACA,YAAY,OAAO,OAAO,OAAO,SAAS;AACxC,YAAI,SAAS,MAAM;AACjB,gBAAM,KAAK,sBAAsB,SAAS,OAAO,MAAM;AAAA,QACzD;AACA,cAAM,KAAK,WAAW,SAAS,OAAO,KAAK;AAAA,MAC7C;AAAA,IACF,CAAC;AAAA,EACH;AACF;;;AC5vBA,IAAO,gBAAQ;","names":[]}
1
+ {"version":3,"sources":["../../../connector-shared/src/errors.ts","../../../connector-shared/src/retry.ts","../../../connector-shared/src/version.ts","../../../connector-shared/src/request.ts","../../../connector-shared/src/rate-limit.ts","../../../connector-shared/src/sanitize.ts","../../../connector-shared/src/epoch.ts","../../../connector-shared/src/pagination.ts","../../../connector-shared/src/logger.ts","../src/posthog.ts","../src/index.ts"],"sourcesContent":["import type { HttpResponse } from './types';\n\nexport type HttpErrorKind =\n | 'transient'\n | 'rate_limit'\n | 'auth'\n | 'upstream_bug'\n | 'client_bug';\n\nexport abstract class HttpClientError extends Error {\n abstract readonly kind: HttpErrorKind;\n readonly response?: HttpResponse;\n\n constructor(message: string, response?: HttpResponse) {\n super(message);\n this.name = new.target.name;\n this.response = response;\n }\n}\n\nexport class TransientError extends HttpClientError {\n readonly kind = 'transient' as const;\n}\n\nexport class RateLimitError extends HttpClientError {\n readonly kind = 'rate_limit' as const;\n readonly retryAfter?: Date;\n\n constructor(message: string, response?: HttpResponse, retryAfter?: Date) {\n super(message, response);\n this.retryAfter = retryAfter;\n }\n}\n\nexport class AuthError extends HttpClientError {\n readonly kind = 'auth' as const;\n}\n\nexport class UpstreamBugError extends HttpClientError {\n readonly kind = 'upstream_bug' as const;\n}\n\nexport class ClientBugError extends HttpClientError {\n readonly kind = 'client_bug' as const;\n}\n\nexport function classifyStatus(status: number): HttpErrorKind {\n if (status === 429) {\n return 'rate_limit';\n }\n if (status === 401 || status === 403) {\n return 'auth';\n }\n if (status === 408) {\n return 'transient';\n }\n if (status >= 500) {\n return 'upstream_bug';\n }\n if (status >= 400) {\n return 'client_bug';\n }\n return 'client_bug';\n}\n\nexport function errorForStatus(\n message: string,\n response: HttpResponse,\n retryAfter?: Date,\n): HttpClientError {\n const kind = classifyStatus(response.status);\n switch (kind) {\n case 'rate_limit':\n return new RateLimitError(message, response, retryAfter);\n case 'auth':\n return new AuthError(message, response);\n case 'transient':\n return new TransientError(message, response);\n case 'upstream_bug':\n return new UpstreamBugError(message, response);\n case 'client_bug':\n return new ClientBugError(message, response);\n }\n}\n","import { HttpClientError, RateLimitError, TransientError } from './errors';\n\nexport interface RetryPolicy {\n maxAttempts?: number;\n initialDelayMs?: number;\n maxDelayMs?: number;\n retryOn?: (status: number | null, err?: Error) => boolean;\n}\n\nexport const defaultRetryOn = (status: number | null, err?: Error): boolean => {\n if (err instanceof RateLimitError) {\n return true;\n }\n if (err instanceof TransientError) {\n return true;\n }\n if (status === null) {\n return err instanceof Error && !(err instanceof HttpClientError);\n }\n if (status === 408 || status === 429) {\n return true;\n }\n if (status >= 500) {\n return true;\n }\n return false;\n};\n\nexport function backoffDelayMs(\n attempt: number,\n policy: Required<Pick<RetryPolicy, 'initialDelayMs' | 'maxDelayMs'>>,\n): number {\n const base = policy.initialDelayMs * 2 ** attempt;\n const jitter = base * 0.25 * Math.random();\n return Math.min(base + jitter, policy.maxDelayMs);\n}\n\nexport function parseRetryAfter(\n headerValue: string | null,\n now: Date = new Date(),\n): Date | undefined {\n if (!headerValue) {\n return undefined;\n }\n const trimmed = headerValue.trim();\n if (/^\\d+$/.test(trimmed)) {\n return new Date(now.getTime() + Number(trimmed) * 1000);\n }\n const parsed = Date.parse(trimmed);\n if (Number.isNaN(parsed)) {\n return undefined;\n }\n return new Date(parsed);\n}\n\nexport function sleep(ms: number, signal?: AbortSignal): Promise<void> {\n if (signal?.aborted) {\n return Promise.reject(signal.reason ?? new Error('Aborted'));\n }\n return new Promise<void>((resolve, reject) => {\n const onAbort = () => {\n clearTimeout(timer);\n reject(signal!.reason ?? new Error('Aborted'));\n };\n const timer = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n}\n","export const HTTP_CLIENT_VERSION = '0.0.0';\n\nexport const DEFAULT_USER_AGENT = `rawdash-connector/${HTTP_CLIENT_VERSION} (+https://rawdash.dev)`;\n\nexport function connectorUserAgent(connectorId: string): string {\n return `rawdash-connector-${connectorId}/${HTTP_CLIENT_VERSION} (+https://rawdash.dev)`;\n}\n","import {\n AuthError,\n ClientBugError,\n HttpClientError,\n RateLimitError,\n TransientError,\n UpstreamBugError,\n errorForStatus,\n} from './errors';\nimport { defaultRetryOn, parseRetryAfter, sleep } from './retry';\nimport type { FetchLike, HttpMethod, HttpRequest, HttpResponse } from './types';\nimport { DEFAULT_USER_AGENT } from './version';\n\nconst DEFAULT_TIMEOUT_MS = 10_000;\nconst DEFAULT_MAX_ATTEMPTS = 3;\nconst DEFAULT_INITIAL_DELAY_MS = 1000;\nconst DEFAULT_MAX_DELAY_MS = 60_000;\nconst OBSERVER_TIMEOUT_MS = 250;\n\nexport interface RequestObservation {\n url: string;\n method: HttpMethod;\n status: number;\n resource: string;\n requestId: string;\n body: unknown;\n}\n\nexport type RequestObserver = (\n event: RequestObservation,\n) => void | Promise<void>;\n\nexport interface RequestOptions {\n fetch?: FetchLike;\n observer?: RequestObserver;\n resource: string;\n requestId?: string;\n}\n\nasync function notifyObserver(\n observer: RequestObserver,\n event: RequestObservation,\n): Promise<void> {\n let result: void | Promise<void>;\n try {\n result = observer(event);\n } catch (err) {\n console.warn('[connector-shared] request observer threw:', err);\n return;\n }\n if (!(result instanceof Promise)) {\n return;\n }\n const guarded = result.catch((err) => {\n console.warn('[connector-shared] request observer rejected:', err);\n });\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timeout = new Promise<void>((resolve) => {\n timer = setTimeout(resolve, OBSERVER_TIMEOUT_MS);\n });\n try {\n await Promise.race([guarded, timeout]);\n } finally {\n if (timer) {\n clearTimeout(timer);\n }\n }\n}\n\nfunction newRequestId(): string {\n const c = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto;\n if (c?.randomUUID) {\n return c.randomUUID();\n }\n return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;\n}\n\nfunction mergeHeaders(\n defaults: Record<string, string>,\n overrides: Record<string, string> | undefined,\n): Record<string, string> {\n const merged: Record<string, string> = {};\n for (const [k, v] of Object.entries(defaults)) {\n merged[k.toLowerCase()] = v;\n }\n if (overrides) {\n for (const [k, v] of Object.entries(overrides)) {\n merged[k.toLowerCase()] = v;\n }\n }\n return merged;\n}\n\nfunction linkTimeoutSignal(\n parent: AbortSignal | undefined,\n timeoutMs: number,\n): { signal: AbortSignal; cancel: () => void } {\n const controller = new AbortController();\n const onParentAbort = () => {\n controller.abort(parent?.reason);\n };\n if (parent) {\n if (parent.aborted) {\n controller.abort(parent.reason);\n } else {\n parent.addEventListener('abort', onParentAbort, { once: true });\n }\n }\n const timer = setTimeout(() => {\n controller.abort(new Error(`Request timed out after ${timeoutMs}ms`));\n }, timeoutMs);\n return {\n signal: controller.signal,\n cancel: () => {\n clearTimeout(timer);\n if (parent) {\n parent.removeEventListener('abort', onParentAbort);\n }\n },\n };\n}\n\nasync function readBody(res: Response, parseJson: boolean): Promise<unknown> {\n if (res.status === 204 || res.status === 205) {\n return null;\n }\n const contentType = res.headers.get('content-type') ?? '';\n if (parseJson && contentType.includes('application/json')) {\n const text = await res.text();\n if (text.length === 0) {\n return null;\n }\n return JSON.parse(text);\n }\n return res.text();\n}\n\nexport async function request<T = unknown>(\n req: HttpRequest,\n options: RequestOptions,\n): Promise<HttpResponse<T>> {\n const fetchImpl: FetchLike = options.fetch ?? (globalThis.fetch as FetchLike);\n const retry = req.retry ?? {};\n const maxAttempts = retry.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;\n const initialDelayMs = retry.initialDelayMs ?? DEFAULT_INITIAL_DELAY_MS;\n const maxDelayMs = retry.maxDelayMs ?? DEFAULT_MAX_DELAY_MS;\n const retryOn = retry.retryOn ?? defaultRetryOn;\n const timeoutMs = req.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const parseJson = req.parseJson ?? true;\n\n const headers = mergeHeaders(\n {\n 'User-Agent': DEFAULT_USER_AGENT,\n Accept: 'application/json',\n },\n req.headers,\n );\n\n let lastErr: Error | undefined;\n\n for (let attempt = 0; attempt < maxAttempts; attempt++) {\n req.signal?.throwIfAborted();\n\n const { signal, cancel } = linkTimeoutSignal(req.signal, timeoutMs);\n let res: Response;\n try {\n res = await fetchImpl(req.url, {\n method: req.method ?? 'GET',\n headers,\n body: req.body as RequestInit['body'],\n signal,\n });\n } catch (err) {\n cancel();\n if (req.signal?.aborted) {\n throw req.signal.reason ?? err;\n }\n const error = err instanceof Error ? err : new Error(String(err));\n lastErr = error;\n if (attempt < maxAttempts - 1 && retryOn(null, error)) {\n const delay = computeDelay(attempt, initialDelayMs, maxDelayMs);\n await sleep(delay, req.signal);\n continue;\n }\n throw new TransientError(error.message);\n }\n cancel();\n\n const body = await readBody(res, parseJson);\n const httpResponse: HttpResponse<T> = {\n status: res.status,\n headers: res.headers,\n body: body as T,\n };\n if (req.rateLimit) {\n const state = req.rateLimit.parse(res.headers);\n if (state) {\n httpResponse.rateLimitState = state;\n }\n }\n\n if (options.observer) {\n await notifyObserver(options.observer, {\n url: req.url,\n method: req.method ?? 'GET',\n status: res.status,\n resource: options.resource,\n requestId: options.requestId ?? newRequestId(),\n body,\n });\n }\n\n if (res.ok) {\n return httpResponse;\n }\n\n const retryAfter = parseRetryAfter(res.headers.get('retry-after'));\n const message = `HTTP ${res.status} ${res.statusText} for ${req.method ?? 'GET'} ${req.url}`;\n const err = errorForStatus(message, httpResponse, retryAfter);\n\n if (\n attempt < maxAttempts - 1 &&\n retryOn(res.status, err) &&\n !(err instanceof AuthError) &&\n !(err instanceof ClientBugError)\n ) {\n lastErr = err;\n let delay = computeDelay(attempt, initialDelayMs, maxDelayMs);\n if (err instanceof RateLimitError && retryAfter) {\n const wait = retryAfter.getTime() - Date.now();\n if (wait > 0) {\n delay = Math.min(wait, maxDelayMs);\n }\n }\n await sleep(delay, req.signal);\n continue;\n }\n\n throw err;\n }\n\n throw lastErr ?? new UpstreamBugError('Exhausted retry attempts');\n}\n\nfunction computeDelay(\n attempt: number,\n initialDelayMs: number,\n maxDelayMs: number,\n): number {\n const base = initialDelayMs * 2 ** attempt;\n const jitter = base * 0.25 * Math.random();\n return Math.min(base + jitter, maxDelayMs);\n}\n\nexport { HttpClientError };\n","export interface RateLimitState {\n remaining: number;\n resetAt: Date;\n}\n\nexport interface RateLimitPolicy {\n parse(headers: Headers): RateLimitState | null;\n}\n\nexport interface StandardRateLimitPolicyConfig {\n remainingHeader: string;\n resetHeader: string;\n resetUnit: 's' | 'ms';\n resetFallbackMs?: number;\n}\n\nexport function standardRateLimitPolicy(\n config: StandardRateLimitPolicyConfig,\n): RateLimitPolicy {\n const { remainingHeader, resetHeader, resetUnit, resetFallbackMs } = config;\n const multiplier = resetUnit === 's' ? 1000 : 1;\n return {\n parse(h) {\n const remainingRaw = h.get(remainingHeader);\n if (remainingRaw === null || remainingRaw.trim() === '') {\n return null;\n }\n const remaining = Number(remainingRaw);\n if (!Number.isFinite(remaining)) {\n return null;\n }\n const resetRaw = h.get(resetHeader);\n if (resetRaw === null) {\n if (resetFallbackMs === undefined) {\n return null;\n }\n return {\n remaining,\n resetAt: new Date(Date.now() + resetFallbackMs),\n };\n }\n if (resetRaw.trim() === '') {\n return null;\n }\n const reset = Number(resetRaw);\n if (!Number.isFinite(reset) || reset < 0) {\n return null;\n }\n const resetMs = reset * multiplier;\n if (!Number.isFinite(resetMs)) {\n return null;\n }\n return { remaining, resetAt: new Date(resetMs) };\n },\n };\n}\n","export interface SanitizeAllowedUrlOptions {\n url: string | null;\n host: string;\n pathname: string;\n protocol?: 'https:' | 'http:';\n}\n\nexport function sanitizeAllowedUrl(\n options: SanitizeAllowedUrlOptions,\n): string | null {\n const { url, host, pathname, protocol = 'https:' } = options;\n if (url === null) {\n return null;\n }\n try {\n const u = new URL(url);\n if (u.protocol !== protocol || u.host !== host || u.pathname !== pathname) {\n return null;\n }\n return u.toString();\n } catch {\n return null;\n }\n}\n","export type EpochUnit = 'ms' | 's' | 'iso';\n\nexport function parseEpoch(\n value: number | string | null | undefined,\n unit: EpochUnit,\n): number | null {\n if (value === null || value === undefined) {\n return null;\n }\n if (unit === 'iso') {\n if (typeof value !== 'string') {\n return null;\n }\n const ms = new Date(value).getTime();\n return Number.isFinite(ms) ? ms : null;\n }\n if (typeof value === 'string' && value.trim() === '') {\n return null;\n }\n const n = typeof value === 'number' ? value : Number(value);\n if (!Number.isFinite(n)) {\n return null;\n }\n const result = unit === 's' ? n * 1000 : n;\n return Number.isFinite(result) ? result : null;\n}\n","import { request } from './request';\nimport type { HttpRequest } from './types';\n\nexport function parseLinkHeader(header: string | null): Record<string, string> {\n if (!header) {\n return {};\n }\n const result: Record<string, string> = {};\n for (const part of header.split(',')) {\n const match = part.match(/<([^>]+)>\\s*;\\s*rel=\"([^\"]+)\"/);\n if (match) {\n result[match[2]!] = match[1]!;\n }\n }\n return result;\n}\n\nexport async function* paginateLink<T>(\n initial: HttpRequest,\n parse: (body: unknown) => T[],\n options: { resource: string },\n): AsyncIterable<T> {\n let next: string | null = initial.url;\n while (next) {\n const res: Awaited<ReturnType<typeof request>> = await request(\n {\n ...initial,\n url: next,\n },\n { resource: options.resource },\n );\n for (const item of parse(res.body)) {\n yield item;\n }\n const links = parseLinkHeader(res.headers.get('link'));\n next = links['next'] ?? null;\n }\n}\n\nexport async function* paginateCursor<T>(\n initial: HttpRequest,\n parse: (body: unknown) => { items: T[]; nextCursor: string | null },\n buildNext: (req: HttpRequest, cursor: string) => HttpRequest,\n options: { resource: string },\n): AsyncIterable<T> {\n let req: HttpRequest = initial;\n while (true) {\n const res = await request(req, { resource: options.resource });\n const { items, nextCursor } = parse(res.body);\n for (const item of items) {\n yield item;\n }\n if (!nextCursor) {\n return;\n }\n req = buildNext(req, nextCursor);\n }\n}\n\nexport async function* paginatePage<T>(\n initial: HttpRequest,\n parse: (body: unknown) => { items: T[]; hasMore: boolean },\n buildPage: (req: HttpRequest, page: number) => HttpRequest,\n options: { resource: string },\n): AsyncIterable<T> {\n let page = 1;\n while (true) {\n const req = page === 1 ? initial : buildPage(initial, page);\n const res = await request(req, { resource: options.resource });\n const { items, hasMore } = parse(res.body);\n for (const item of items) {\n yield item;\n }\n if (!hasMore || items.length === 0) {\n return;\n }\n page++;\n }\n}\n","export type LogFields = Record<string, unknown>;\n\nexport interface ConnectorLogger {\n info(event: string, fields?: LogFields): void;\n warn(event: string, fields?: LogFields): void;\n}\n\nexport interface ConnectorLoggerOptions {\n scope: string;\n}\n\nconst MAX_VALUE_LEN = 120;\n\nfunction truncate(s: string, max = MAX_VALUE_LEN): string {\n if (s.length <= max) {\n return s;\n }\n return `${s.slice(0, max - 1)}…`;\n}\n\nfunction formatValue(value: unknown): string {\n if (value === null) {\n return 'null';\n }\n if (value === undefined) {\n return '';\n }\n if (typeof value === 'number' || typeof value === 'boolean') {\n return String(value);\n }\n if (typeof value === 'string') {\n const t = truncate(value);\n if (/[\\s\"=]/.test(t)) {\n return JSON.stringify(t);\n }\n return t;\n }\n if (typeof value === 'bigint') {\n return value.toString();\n }\n let json: string | undefined;\n try {\n json = JSON.stringify(value);\n } catch {\n json = undefined;\n }\n return truncate(json ?? String(value));\n}\n\nexport function formatLogFields(fields?: LogFields): string {\n if (!fields) {\n return '';\n }\n const parts: string[] = [];\n for (const [k, v] of Object.entries(fields)) {\n if (v === undefined) {\n continue;\n }\n parts.push(`${k}=${formatValue(v)}`);\n }\n return parts.length > 0 ? ` ${parts.join(' ')}` : '';\n}\n\nexport function formatLogLine(\n scope: string,\n event: string,\n fields?: LogFields,\n): string {\n return `[${scope}] ${event}${formatLogFields(fields)}`;\n}\n\nexport function createDefaultConnectorLogger(\n opts: ConnectorLoggerOptions,\n): ConnectorLogger {\n return {\n info(event, fields) {\n console.info(formatLogLine(opts.scope, event, fields));\n },\n warn(event, fields) {\n console.warn(formatLogLine(opts.scope, event, fields));\n },\n };\n}\n\nconst NOOP_LOGGER: ConnectorLogger = {\n info() {},\n warn() {},\n};\n\nexport function noopConnectorLogger(): ConnectorLogger {\n return NOOP_LOGGER;\n}\n","import { connectorUserAgent, parseEpoch } from '@rawdash/connector-shared';\nimport {\n BaseConnector,\n type ConnectorContext,\n type ConnectorDoc,\n type CredentialsSchema,\n type StorageHandle,\n type SyncOptions,\n type SyncResult,\n defineConfigFields,\n defineConnectorDoc,\n defineResources,\n makeChunkedCursorGuard,\n paginateChunked,\n schemasFromResources,\n selectActivePhases,\n} from '@rawdash/core';\nimport { z } from 'zod';\n\n// ---------------------------------------------------------------------------\n// configFields\n// ---------------------------------------------------------------------------\n\nconst funnelDefinition = z.object({\n name: z.string().min(1),\n steps: z.array(z.string().min(1)).min(2),\n windowDays: z.number().int().positive().optional(),\n});\n\nexport const configFields = defineConfigFields(\n z.object({\n apiKey: z.object({ $secret: z.string() }).meta({\n label: 'Personal API key',\n description:\n 'PostHog personal API key with read access to the project. Create one at PostHog → Settings → Personal API keys (starts with `phx_`).',\n placeholder: 'phx_...',\n secret: true,\n }),\n projectId: z\n .string()\n .trim()\n .regex(/^\\d+$/, 'PostHog project ID must be digits only')\n .meta({\n label: 'Project ID',\n description:\n 'Numeric ID of your PostHog project. Find it in PostHog → Settings → Project → Project ID.',\n placeholder: '12345',\n }),\n host: z\n .string()\n .trim()\n .regex(\n /^https?:\\/\\/[^\\s/]+$/,\n 'Use a base URL with protocol and no trailing slash, e.g. https://us.posthog.com',\n )\n .default('https://us.posthog.com')\n .meta({\n label: 'Host',\n description:\n 'PostHog instance base URL. Use https://us.posthog.com or https://eu.posthog.com for PostHog Cloud, or your self-hosted origin. No trailing slash.',\n placeholder: 'https://us.posthog.com',\n }),\n events: z.array(z.string().min(1)).nonempty().optional().meta({\n label: 'Tracked events',\n description:\n 'Event names to roll up in the `events_per_day` resource. Omit to roll up every event in the project.',\n }),\n funnels: z.array(funnelDefinition).nonempty().optional().meta({\n label: 'Funnels',\n description:\n 'Funnel definitions to evaluate. Each funnel is an object with name, steps (an ordered list of event names), and an optional windowDays. Conversion is measured over the sync window.',\n }),\n lookbackDays: z.number().int().positive().optional().meta({\n label: 'Lookback days (full sync)',\n description:\n 'How many calendar days of history to roll up on a full sync. Defaults to 30.',\n placeholder: '30',\n }),\n resources: z\n .array(\n z.enum([\n 'feature_flags',\n 'events_per_day',\n 'feature_flag_usage',\n 'active_users',\n 'funnels',\n ]),\n )\n .nonempty()\n .optional()\n .meta({\n label: 'Resources',\n description:\n 'Which PostHog resources to sync. Omit to sync all of them.',\n }),\n }),\n);\n\nexport const doc: ConnectorDoc = defineConnectorDoc({\n displayName: 'PostHog',\n category: 'product',\n brandColor: '#000000',\n tagline:\n 'Sync feature flags, per-day event volume, feature flag usage, active users, and funnel conversion from a PostHog project.',\n vendor: {\n name: 'PostHog',\n apiDocs: 'https://posthog.com/docs/api',\n website: 'https://posthog.com',\n },\n auth: {\n summary:\n 'A PostHog personal API key with read access to the project is required, along with the numeric project ID and the instance host.',\n setup: [\n 'Open PostHog → Settings → Personal API keys and create a key with read access to the project (it starts with `phx_`).',\n 'Find your numeric project ID in PostHog → Settings → Project → Project ID.',\n 'Set `host` to your instance base URL - `https://us.posthog.com` or `https://eu.posthog.com` for PostHog Cloud, or your self-hosted origin (no trailing slash).',\n 'Store the key as a secret and reference it from config as `apiKey: secret(\"POSTHOG_API_KEY\")`.',\n ],\n },\n rateLimit:\n 'PostHog allows roughly 1200 requests/min per personal API key; Retry-After is honored.',\n limitations: ['Session recordings/replays and cohorts are not synced.'],\n});\n\n// ---------------------------------------------------------------------------\n// Settings / credentials\n// ---------------------------------------------------------------------------\n\nexport interface PostHogFunnel {\n name: string;\n steps: readonly string[];\n windowDays?: number;\n}\n\nexport interface PostHogSettings {\n projectId: string;\n host: string;\n events?: readonly string[];\n funnels?: readonly PostHogFunnel[];\n lookbackDays?: number;\n resources?: readonly PostHogResource[];\n}\n\nconst posthogCredentials = {\n apiKey: {\n description: 'PostHog personal API key',\n auth: 'required' as const,\n },\n} satisfies CredentialsSchema;\n\ntype PostHogCredentials = typeof posthogCredentials;\n\n// ---------------------------------------------------------------------------\n// Sync phases + cursor\n// ---------------------------------------------------------------------------\n\nconst PHASE_ORDER = [\n 'feature_flags',\n 'events_per_day',\n 'feature_flag_usage',\n 'active_users',\n 'funnels',\n] as const;\n\ntype PostHogPhase = (typeof PHASE_ORDER)[number];\n\nexport type PostHogResource = PostHogPhase;\n\nconst isPostHogSyncCursor = makeChunkedCursorGuard(PHASE_ORDER);\n\nconst FLAGS_PAGE_SIZE = 100;\nconst QUERY_PAGE_SIZE = 10_000;\nconst DEFAULT_LOOKBACK_DAYS = 30;\nconst DEFAULT_FUNNEL_WINDOW_DAYS = 14;\nconst MS_PER_DAY = 24 * 60 * 60 * 1000;\n\nconst FEATURE_FLAG_ENTITY = 'posthog_feature_flag';\nconst EVENTS_PER_DAY_METRIC = 'posthog_events_per_day';\nconst FLAG_USAGE_METRIC = 'posthog_feature_flag_usage';\nconst ACTIVE_USERS_METRIC = 'posthog_active_users';\nconst FUNNEL_METRIC = 'posthog_funnel';\n\n// Series order requested in the active-users TrendsQuery; the response keeps\n// this order so the index maps back to the active-user window.\nconst ACTIVE_USER_WINDOWS = ['dau', 'wau', 'mau'] as const;\nconst ACTIVE_USER_MATH = ['dau', 'weekly_active', 'monthly_active'] as const;\n\n// ---------------------------------------------------------------------------\n// PostHog API types\n// ---------------------------------------------------------------------------\n\ninterface FeatureFlagRecord {\n id: number;\n key: string;\n name?: string | null;\n active: boolean;\n rollout_percentage?: number | null;\n created_at?: string | null;\n filters?: unknown;\n}\n\ninterface FeatureFlagListResponse {\n count?: number;\n next?: string | null;\n results: FeatureFlagRecord[];\n}\n\ninterface HogQLResponse {\n results: Array<Array<string | number | boolean | null>>;\n}\n\ninterface TrendsResponse {\n results: Array<{\n data: number[];\n days: string[];\n label?: string | null;\n }>;\n}\n\ninterface FunnelStepResult {\n count: number;\n name?: string | null;\n order?: number | null;\n}\n\ninterface FunnelResponse {\n results: FunnelStepResult[];\n}\n\n// ---------------------------------------------------------------------------\n// Value helpers\n// ---------------------------------------------------------------------------\n\nfunction finiteNumber(value: unknown, fallback = 0): number {\n const n = typeof value === 'number' ? value : Number(value);\n return Number.isFinite(n) ? n : fallback;\n}\n\nfunction finiteNumberOrNull(value: unknown): number | null {\n if (value === null || value === undefined || value === '') {\n return null;\n }\n const n = typeof value === 'number' ? value : Number(value);\n return Number.isFinite(n) ? n : null;\n}\n\nfunction stringOrNull(value: unknown): string | null {\n return typeof value === 'string' ? value : null;\n}\n\n// PostHog dates from HogQL come back as 'YYYY-MM-DD' (or full timestamps).\n// Treat them as UTC midnight so re-syncing the same day is idempotent.\nfunction dateStringToMs(value: unknown): number | null {\n if (typeof value !== 'string') {\n return null;\n }\n const trimmed = value.trim();\n if (trimmed === '') {\n return null;\n }\n const isoLike = /^\\d{4}-\\d{2}-\\d{2}$/.test(trimmed)\n ? `${trimmed}T00:00:00.000Z`\n : trimmed;\n return parseEpoch(isoLike, 'iso');\n}\n\n// Filters are an opaque, deeply-nested PostHog payload. Persist a JSON snapshot\n// rather than the raw object so no `undefined` (or non-serializable value)\n// leaks into entity attributes.\nfunction stringifyFilters(value: unknown): string | null {\n if (value === undefined || value === null) {\n return null;\n }\n try {\n const json = JSON.stringify(value);\n return json === undefined ? null : json;\n } catch {\n return null;\n }\n}\n\nfunction startOfUtcDay(ms: number): number {\n return Math.floor(ms / MS_PER_DAY) * MS_PER_DAY;\n}\n\nfunction safeOffset(page: string | null): number {\n if (page === null) {\n return 0;\n }\n const n = Number(page);\n return Number.isFinite(n) && n >= 0 ? Math.floor(n) : 0;\n}\n\nfunction quoteHogQLString(value: string): string {\n return `'${value.replace(/\\\\/g, '\\\\\\\\').replace(/'/g, \"\\\\'\")}'`;\n}\n\n// ---------------------------------------------------------------------------\n// Schemas — describe the per-resource API response shape consumed by request()\n// ---------------------------------------------------------------------------\n\nconst featureFlagSchema = z.object({\n id: z.number(),\n key: z.string().min(1),\n name: z.string().nullish(),\n active: z.boolean(),\n rollout_percentage: z.number().nullish(),\n created_at: z.string().nullish(),\n});\n\n// HogQL grouped rollups return positional rows: [day, key, count, distinct].\nconst dailyCountRow = z.tuple([\n z.string(),\n z.string().nullable(),\n z.number(),\n z.number(),\n]);\n\nconst hogqlSchema = z.object({ results: z.array(dailyCountRow) });\n\nconst trendsSchema = z.object({\n results: z.array(\n z.object({\n data: z.array(z.number()),\n days: z.array(z.string()),\n label: z.string().nullish(),\n }),\n ),\n});\n\nconst funnelSchema = z.object({\n results: z.array(\n z.object({\n count: z.number(),\n name: z.string().nullish(),\n order: z.number().nullish(),\n }),\n ),\n});\n\n// ---------------------------------------------------------------------------\n// Resources\n// ---------------------------------------------------------------------------\n\nexport const posthogResources = defineResources({\n posthog_feature_flag: {\n shape: 'entity',\n description:\n 'Feature flags in the project, keyed by flag id, with key, name, active state, rollout percentage, and a JSON snapshot of the flag filters.',\n endpoint: 'GET /api/projects/{projectId}/feature_flags/',\n notes: 'Feature flags upsert by id on every run.',\n responses: { feature_flags: z.array(featureFlagSchema) },\n },\n posthog_events_per_day: {\n shape: 'metric',\n description:\n 'Daily event volume rolled up by event name via HogQL. One sample per (day, event) over the lookback window. Restricted to the configured `events` list when provided, otherwise every event.',\n endpoint: 'POST /api/projects/{projectId}/query (HogQLQuery)',\n unit: 'events',\n granularity: 'Daily (UTC)',\n notes: 'Rollup metrics are stamped at UTC midnight of the day they cover.',\n dimensions: [\n { name: 'event', description: 'The PostHog event name.' },\n { name: 'count', description: 'Total event occurrences that day.' },\n {\n name: 'distinctUsers',\n description: 'Distinct persons who fired the event that day.',\n },\n ],\n responses: { events_per_day: hogqlSchema },\n },\n posthog_feature_flag_usage: {\n shape: 'metric',\n description:\n 'Daily `$feature_flag_called` volume rolled up by flag key via HogQL. One sample per (day, flag) over the lookback window.',\n endpoint: 'POST /api/projects/{projectId}/query (HogQLQuery)',\n unit: 'calls',\n granularity: 'Daily (UTC)',\n notes: 'Rollup metrics are stamped at UTC midnight of the day they cover.',\n dimensions: [\n {\n name: 'flagKey',\n description: 'The feature flag key that was evaluated.',\n },\n {\n name: 'callCount',\n description: 'Number of flag evaluations that day.',\n },\n {\n name: 'uniqueUsers',\n description: 'Distinct persons who evaluated the flag that day.',\n },\n ],\n responses: { feature_flag_usage: hogqlSchema },\n },\n posthog_active_users: {\n shape: 'metric',\n description:\n 'Daily active-user counts from a TrendsQuery, with one sample per day per rolling window (daily, weekly, and monthly active users).',\n endpoint: 'POST /api/projects/{projectId}/query (TrendsQuery)',\n unit: 'users',\n granularity: 'Daily (UTC)',\n notes: 'Rollup metrics are stamped at UTC midnight of the day they cover.',\n dimensions: [\n {\n name: 'window',\n description:\n 'The active-user window the sample belongs to: `dau`, `wau`, or `mau`.',\n },\n ],\n responses: { active_users: trendsSchema },\n },\n posthog_funnel: {\n shape: 'metric',\n description:\n 'Funnel conversion snapshot. One sample per declared funnel step, stamped at the start of the current UTC day, carrying the step user count and conversion rate relative to the first step. Only written when `funnels` are configured.',\n endpoint: 'POST /api/projects/{projectId}/query (FunnelsQuery)',\n unit: 'users',\n granularity: 'Snapshot per sync (start of UTC day)',\n notes:\n 'A single conversion snapshot measured over the lookback window, stamped at the start of the current UTC day, not a per-day time series.',\n dimensions: [\n { name: 'funnel', description: 'The configured funnel name.' },\n {\n name: 'step',\n description: 'Zero-based step order within the funnel.',\n },\n {\n name: 'stepName',\n description: 'The event name for the step, if returned.',\n },\n { name: 'users', description: 'Users who reached this step.' },\n {\n name: 'conversionRate',\n description: 'Step users divided by first-step users (0 when no base).',\n },\n ],\n responses: { funnels: funnelSchema },\n },\n});\n\n// ---------------------------------------------------------------------------\n// PostHogConnector\n// ---------------------------------------------------------------------------\n\nexport const id = 'posthog';\n\nexport class PostHogConnector extends BaseConnector<\n PostHogSettings,\n PostHogCredentials\n> {\n static readonly id = id;\n\n static readonly resources = posthogResources;\n\n static readonly schemas = schemasFromResources(posthogResources);\n\n static create(input: unknown, ctx?: ConnectorContext): PostHogConnector {\n const parsed = configFields.parse(input);\n return new PostHogConnector(\n {\n projectId: parsed.projectId,\n host: parsed.host,\n events: parsed.events,\n funnels: parsed.funnels,\n lookbackDays: parsed.lookbackDays,\n resources: parsed.resources,\n },\n { apiKey: parsed.apiKey },\n ctx,\n );\n }\n\n readonly id = id;\n override readonly credentials = posthogCredentials;\n\n private get baseUrl(): string {\n return this.settings.host.replace(/\\/+$/, '');\n }\n\n private buildHeaders(): Record<string, string> {\n return {\n Authorization: `Bearer ${this.creds.apiKey}`,\n 'Content-Type': 'application/json',\n 'User-Agent': connectorUserAgent('posthog'),\n };\n }\n\n // ISO date (YYYY-MM-DD) that bounds the rollup window. Metric phases use\n // clear-and-rewrite, so the window must always cover the full lookback or\n // an incremental tick would wipe history and only rewrite a narrower slice.\n // A `since` earlier than the lookback extends the window; a later `since`\n // is ignored.\n private windowStartDate(options: SyncOptions): string {\n const lookbackDays = this.settings.lookbackDays ?? DEFAULT_LOOKBACK_DAYS;\n const now = Date.now();\n let startMs = now - (lookbackDays - 1) * MS_PER_DAY;\n if (options.since) {\n const sinceMs = new Date(options.since).getTime();\n if (Number.isFinite(sinceMs) && sinceMs < startMs) {\n startMs = sinceMs;\n }\n }\n return new Date(startMs).toISOString().slice(0, 10);\n }\n\n private runQuery<T>(\n query: Record<string, unknown>,\n resource: PostHogPhase,\n signal?: AbortSignal,\n ): Promise<T> {\n return this.post<T>(\n `${this.baseUrl}/api/projects/${this.settings.projectId}/query`,\n {\n resource,\n headers: this.buildHeaders(),\n body: JSON.stringify({ query }),\n signal,\n },\n ).then((res) => res.body);\n }\n\n // -------------------------------------------------------------------------\n // feature_flags — paginated REST list (entities)\n // -------------------------------------------------------------------------\n\n private async fetchFeatureFlagsPage(\n page: string | null,\n signal?: AbortSignal,\n ): Promise<{ items: unknown[]; next: string | null }> {\n const offset = safeOffset(page);\n const url = new URL(\n `${this.baseUrl}/api/projects/${this.settings.projectId}/feature_flags/`,\n );\n url.searchParams.set('limit', String(FLAGS_PAGE_SIZE));\n url.searchParams.set('offset', String(offset));\n const res = await this.get<FeatureFlagListResponse>(url.toString(), {\n resource: 'feature_flags',\n headers: this.buildHeaders(),\n signal,\n });\n const results = res.body.results;\n // Build the next offset ourselves rather than echoing the API's absolute\n // `next` URL back into fetch(), avoiding any SSRF surface from a tampered\n // cursor while still stopping once a short page comes back.\n const next =\n res.body.next && results.length === FLAGS_PAGE_SIZE\n ? String(offset + FLAGS_PAGE_SIZE)\n : null;\n return { items: results, next };\n }\n\n private async writeFeatureFlags(\n storage: StorageHandle,\n items: FeatureFlagRecord[],\n ): Promise<void> {\n for (const flag of items) {\n await storage.entity({\n type: FEATURE_FLAG_ENTITY,\n id: String(flag.id),\n attributes: {\n key: flag.key,\n name: flag.name ?? null,\n active: flag.active,\n rolloutPercentage: finiteNumberOrNull(flag.rollout_percentage),\n filters: stringifyFilters(flag.filters),\n },\n updated_at: parseEpoch(flag.created_at ?? null, 'iso') ?? 0,\n });\n }\n }\n\n // -------------------------------------------------------------------------\n // events_per_day — HogQL grouped by (day, event)\n // -------------------------------------------------------------------------\n\n private async fetchEventsPerDay(\n startDate: string,\n page: string | null,\n signal?: AbortSignal,\n ): Promise<{ items: unknown[]; next: string | null }> {\n const offset = safeOffset(page);\n const clauses = [`timestamp >= toDateTime(${quoteHogQLString(startDate)})`];\n const events = this.settings.events;\n if (events && events.length > 0) {\n const list = events.map(quoteHogQLString).join(', ');\n clauses.push(`event IN (${list})`);\n }\n const sql =\n `SELECT toString(toDate(timestamp)) AS day, event AS event, ` +\n `count() AS total, count(DISTINCT person_id) AS users ` +\n `FROM events WHERE ${clauses.join(' AND ')} ` +\n `GROUP BY day, event ORDER BY day, event ` +\n `LIMIT ${QUERY_PAGE_SIZE} OFFSET ${offset}`;\n const body = await this.runQuery<HogQLResponse>(\n { kind: 'HogQLQuery', query: sql },\n 'events_per_day',\n signal,\n );\n const next =\n body.results.length === QUERY_PAGE_SIZE\n ? String(offset + QUERY_PAGE_SIZE)\n : null;\n return { items: body.results, next };\n }\n\n private async writeEventsPerDay(\n storage: StorageHandle,\n rows: HogQLResponse['results'],\n ): Promise<void> {\n for (const row of rows) {\n const ts = dateStringToMs(row[0]);\n if (ts === null) {\n continue;\n }\n const count = finiteNumber(row[2]);\n await storage.metric({\n name: EVENTS_PER_DAY_METRIC,\n ts,\n value: count,\n attributes: {\n event: stringOrNull(row[1]),\n count,\n distinctUsers: finiteNumber(row[3]),\n },\n });\n }\n }\n\n // -------------------------------------------------------------------------\n // feature_flag_usage — HogQL over $feature_flag_called events\n // -------------------------------------------------------------------------\n\n private async fetchFlagUsage(\n startDate: string,\n page: string | null,\n signal?: AbortSignal,\n ): Promise<{ items: unknown[]; next: string | null }> {\n const offset = safeOffset(page);\n const sql =\n `SELECT toString(toDate(timestamp)) AS day, ` +\n `properties.$feature_flag AS flag, count() AS calls, ` +\n `count(DISTINCT person_id) AS users FROM events ` +\n `WHERE event = '$feature_flag_called' AND ` +\n `timestamp >= toDateTime(${quoteHogQLString(startDate)}) ` +\n `GROUP BY day, flag ORDER BY day, flag ` +\n `LIMIT ${QUERY_PAGE_SIZE} OFFSET ${offset}`;\n const body = await this.runQuery<HogQLResponse>(\n { kind: 'HogQLQuery', query: sql },\n 'feature_flag_usage',\n signal,\n );\n const next =\n body.results.length === QUERY_PAGE_SIZE\n ? String(offset + QUERY_PAGE_SIZE)\n : null;\n return { items: body.results, next };\n }\n\n private async writeFlagUsage(\n storage: StorageHandle,\n rows: HogQLResponse['results'],\n ): Promise<void> {\n for (const row of rows) {\n const ts = dateStringToMs(row[0]);\n if (ts === null) {\n continue;\n }\n const callCount = finiteNumber(row[2]);\n await storage.metric({\n name: FLAG_USAGE_METRIC,\n ts,\n value: callCount,\n attributes: {\n flagKey: stringOrNull(row[1]),\n callCount,\n uniqueUsers: finiteNumber(row[3]),\n },\n });\n }\n }\n\n // -------------------------------------------------------------------------\n // active_users — TrendsQuery (dau / wau / mau)\n // -------------------------------------------------------------------------\n\n private async fetchActiveUsers(\n startDate: string,\n signal?: AbortSignal,\n ): Promise<{ items: unknown[]; next: null }> {\n const body = await this.runQuery<TrendsResponse>(\n {\n kind: 'TrendsQuery',\n dateRange: { date_from: startDate },\n interval: 'day',\n series: ACTIVE_USER_MATH.map((math) => ({\n kind: 'EventsNode',\n event: null,\n math,\n })),\n },\n 'active_users',\n signal,\n );\n return { items: body.results, next: null };\n }\n\n private async writeActiveUsers(\n storage: StorageHandle,\n series: TrendsResponse['results'],\n ): Promise<void> {\n for (let i = 0; i < series.length; i++) {\n const entry = series[i]!;\n const window = ACTIVE_USER_WINDOWS[i] ?? `series_${i}`;\n const data = entry.data ?? [];\n const days = entry.days ?? [];\n const n = Math.min(data.length, days.length);\n for (let j = 0; j < n; j++) {\n const ts = dateStringToMs(days[j]);\n if (ts === null) {\n continue;\n }\n await storage.metric({\n name: ACTIVE_USERS_METRIC,\n ts,\n value: finiteNumber(data[j]),\n attributes: { window },\n });\n }\n }\n }\n\n // -------------------------------------------------------------------------\n // funnels — one FunnelsQuery per declared funnel (index-paged)\n // -------------------------------------------------------------------------\n\n private async fetchFunnelPage(\n page: string | null,\n startDate: string,\n signal?: AbortSignal,\n ): Promise<{ items: unknown[]; next: string | null }> {\n const funnels = this.settings.funnels ?? [];\n const index = safeOffset(page);\n if (index >= funnels.length) {\n return { items: [], next: null };\n }\n const funnel = funnels[index]!;\n const body = await this.runQuery<FunnelResponse>(\n {\n kind: 'FunnelsQuery',\n dateRange: { date_from: startDate },\n series: funnel.steps.map((event) => ({ kind: 'EventsNode', event })),\n funnelWindowInterval: funnel.windowDays ?? DEFAULT_FUNNEL_WINDOW_DAYS,\n funnelWindowIntervalUnit: 'day',\n },\n 'funnels',\n signal,\n );\n // Tag each step row with its funnel so writeBatch stays stateless.\n const items = body.results.map((step) => ({ funnel, step }));\n const next = index + 1 < funnels.length ? String(index + 1) : null;\n return { items, next };\n }\n\n private async writeFunnelSteps(\n storage: StorageHandle,\n items: Array<{ funnel: PostHogFunnel; step: FunnelStepResult }>,\n ): Promise<void> {\n // Snapshot timestamp: funnel conversion is measured over the whole window,\n // so stamp every step at the start of the current UTC day.\n const ts = startOfUtcDay(Date.now());\n for (const { funnel, step } of items) {\n const users = finiteNumber(step.count);\n const base = items.find(\n (it) => it.funnel === funnel && (it.step.order ?? 0) === 0,\n )?.step.count;\n const baseUsers = finiteNumber(base);\n const conversionRate = baseUsers > 0 ? users / baseUsers : 0;\n await storage.metric({\n name: FUNNEL_METRIC,\n ts,\n value: users,\n attributes: {\n funnel: funnel.name,\n step: finiteNumber(step.order),\n stepName: stringOrNull(step.name),\n users,\n conversionRate,\n },\n });\n }\n }\n\n // -------------------------------------------------------------------------\n // Scope clearing (idempotency)\n // -------------------------------------------------------------------------\n\n private async clearScopeOnFirstPage(\n storage: StorageHandle,\n phase: PostHogPhase,\n isFull: boolean,\n ): Promise<void> {\n switch (phase) {\n case 'feature_flags':\n // Entities upsert by id; only a full backfill drops stale rows.\n if (isFull) {\n await storage.entities([], { types: [FEATURE_FLAG_ENTITY] });\n }\n return;\n case 'events_per_day':\n await storage.metrics([], { names: [EVENTS_PER_DAY_METRIC] });\n return;\n case 'feature_flag_usage':\n await storage.metrics([], { names: [FLAG_USAGE_METRIC] });\n return;\n case 'active_users':\n await storage.metrics([], { names: [ACTIVE_USERS_METRIC] });\n return;\n case 'funnels':\n await storage.metrics([], { names: [FUNNEL_METRIC] });\n return;\n }\n }\n\n private async writePhase(\n storage: StorageHandle,\n phase: PostHogPhase,\n items: unknown[],\n ): Promise<void> {\n switch (phase) {\n case 'feature_flags':\n await this.writeFeatureFlags(storage, items as FeatureFlagRecord[]);\n return;\n case 'events_per_day':\n await this.writeEventsPerDay(\n storage,\n items as HogQLResponse['results'],\n );\n return;\n case 'feature_flag_usage':\n await this.writeFlagUsage(storage, items as HogQLResponse['results']);\n return;\n case 'active_users':\n await this.writeActiveUsers(\n storage,\n items as TrendsResponse['results'],\n );\n return;\n case 'funnels':\n await this.writeFunnelSteps(\n storage,\n items as Array<{ funnel: PostHogFunnel; step: FunnelStepResult }>,\n );\n return;\n }\n }\n\n async sync(\n options: SyncOptions,\n storage: StorageHandle,\n signal?: AbortSignal,\n ): Promise<SyncResult> {\n const cursor = isPostHogSyncCursor(options.cursor)\n ? options.cursor\n : undefined;\n const isFull = options.mode === 'full';\n const startDate = this.windowStartDate(options);\n\n const phases = selectActivePhases<PostHogResource, PostHogPhase>(\n (r) => r,\n PHASE_ORDER,\n this.settings.resources,\n );\n\n return paginateChunked<PostHogPhase, string>({\n phases,\n cursor,\n signal,\n logger: this.logger,\n fetchPage: async (phase, page, sig) => {\n switch (phase) {\n case 'feature_flags':\n return this.fetchFeatureFlagsPage(page, sig);\n case 'events_per_day':\n return this.fetchEventsPerDay(startDate, page, sig);\n case 'feature_flag_usage':\n return this.fetchFlagUsage(startDate, page, sig);\n case 'active_users':\n return this.fetchActiveUsers(startDate, sig);\n case 'funnels':\n return this.fetchFunnelPage(page, startDate, sig);\n }\n },\n writeBatch: async (phase, items, page) => {\n if (page === null) {\n await this.clearScopeOnFirstPage(storage, phase, isFull);\n }\n await this.writePhase(storage, phase, items);\n },\n });\n }\n}\n","import { PostHogConnector } from './posthog';\n\nexport {\n configFields,\n doc,\n PostHogConnector,\n posthogResources as resources,\n id,\n} from './posthog';\nexport type {\n PostHogSettings,\n PostHogResource,\n PostHogFunnel,\n} from './posthog';\nexport default PostHogConnector;\n"],"mappings":";AEAO,IAAM,sBAAsB;AAE5B,IAAM,qBAAqB,qBAAqB,mBAAmB;AAEnE,SAAS,mBAAmB,aAA6B;AAC9D,SAAO,qBAAqB,WAAW,IAAI,mBAAmB;AAChE;AIJO,SAAS,WACd,OACA,MACe;AACf,MAAI,UAAU,QAAQ,UAAU,QAAW;AACzC,WAAO;EACT;AACA,MAAI,SAAS,OAAO;AAClB,QAAI,OAAO,UAAU,UAAU;AAC7B,aAAO;IACT;AACA,UAAM,KAAK,IAAI,KAAK,KAAK,EAAE,QAAQ;AACnC,WAAO,OAAO,SAAS,EAAE,IAAI,KAAK;EACpC;AACA,MAAI,OAAO,UAAU,YAAY,MAAM,KAAK,MAAM,IAAI;AACpD,WAAO;EACT;AACA,QAAM,IAAI,OAAO,UAAU,WAAW,QAAQ,OAAO,KAAK;AAC1D,MAAI,CAAC,OAAO,SAAS,CAAC,GAAG;AACvB,WAAO;EACT;AACA,QAAM,SAAS,SAAS,MAAM,IAAI,MAAO;AACzC,SAAO,OAAO,SAAS,MAAM,IAAI,SAAS;AAC5C;;;AGxBA;AAAA,EACE;AAAA,EAOA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,SAAS;AAMlB,IAAM,mBAAmB,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": "@rawdash/connector-posthog",
3
- "version": "0.0.1",
3
+ "version": "0.17.0",
4
4
  "description": "Rawdash connector for PostHog — event volume, active users, feature flags, flag usage, and funnels",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
7
+ "sideEffects": false,
7
8
  "repository": {
8
9
  "type": "git",
9
10
  "url": "https://github.com/rawdash/rawdash.git",
@@ -21,22 +22,22 @@
21
22
  "import": "./dist/index.js"
22
23
  }
23
24
  },
24
- "scripts": {
25
- "build": "tsup",
26
- "typecheck": "tsc --noEmit",
27
- "lint": "eslint src",
28
- "test": "vitest run"
29
- },
30
25
  "dependencies": {
31
- "@rawdash/core": "workspace:*",
32
- "zod": "^4.4.3"
26
+ "zod": "^4.4.3",
27
+ "@rawdash/core": "0.17.0"
33
28
  },
34
29
  "devDependencies": {
35
- "@rawdash/connector-shared": "workspace:*",
36
- "@rawdash/connector-test-utils": "workspace:*",
37
30
  "fast-check": "^4.8.0",
38
31
  "tsup": "^8.0.0",
39
32
  "typescript": "^5.7.2",
40
- "vitest": "^4.1.4"
33
+ "vitest": "^4.1.4",
34
+ "@rawdash/connector-shared": "0.3.0",
35
+ "@rawdash/connector-test-utils": "0.0.4"
36
+ },
37
+ "scripts": {
38
+ "build": "tsup",
39
+ "typecheck": "tsc --noEmit",
40
+ "lint": "eslint src",
41
+ "test": "vitest run"
41
42
  }
42
- }
43
+ }