@riebeckite/analytics-cloudflare 0.0.3
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 +201 -0
- package/README.md +69 -0
- package/README_ja.md +16 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +289 -0
- package/dist/src/domain/analytics/storage.d.ts +3 -0
- package/dist/src/infrastructure/d1/d1_analytics_storage.d.ts +17 -0
- package/dist/src/infrastructure/d1/d1_types.d.ts +11 -0
- package/dist/src/infrastructure/kv/kv_analytics_storage.d.ts +20 -0
- package/dist/src/presentation/worker/create_worker.d.ts +17 -0
- package/migrations/0001_analytics_page_views.sql +8 -0
- package/package.json +54 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright Rerurate_514
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
# @riebeckite/analytics-cloudflare
|
|
2
|
+
|
|
3
|
+
Independent Cloudflare Worker runtime for `@riebeckite/plugin-analytics`. The
|
|
4
|
+
generic plugin contains only browser configuration and analytics contracts; this
|
|
5
|
+
package owns Worker bindings and storage.
|
|
6
|
+
|
|
7
|
+
## Architecture
|
|
8
|
+
|
|
9
|
+
`createWorker` is the presentation boundary for a dedicated Worker runtime. It
|
|
10
|
+
validates HTTP input, calls the generic `AnalyticsProvider` contract through the
|
|
11
|
+
runtime-owned `AnalyticsStorage` boundary, and maps unsupported reads to HTTP
|
|
12
|
+
errors. D1 and KV live in infrastructure and are never imported by
|
|
13
|
+
`@riebeckite/plugin-analytics`. The site's only public setting remains the
|
|
14
|
+
generic plugin's `collectorUrl`; bindings and storage selection stay in this
|
|
15
|
+
Worker.
|
|
16
|
+
|
|
17
|
+
## Choose exactly one storage adapter
|
|
18
|
+
|
|
19
|
+
- **`D1AnalyticsStorage`**: atomic SQLite upserts into UTC daily aggregate
|
|
20
|
+
buckets. It supports capture, content page-view totals, popular-content
|
|
21
|
+
ranking, and date-bucket time ranges. It stores no raw event log. A range is
|
|
22
|
+
bucket-based: bounds select entire UTC days, not exact sub-day event windows.
|
|
23
|
+
- **`KvAnalyticsStorage`**: minimal best-effort total capture only. KV lacks
|
|
24
|
+
atomic increment and aggregate listing, so concurrent writes can be lost and
|
|
25
|
+
`content_page_views` / `popular_content` deliberately throw
|
|
26
|
+
`UnsupportedAnalyticsQueryError` (the Worker returns `501`). Do not use it
|
|
27
|
+
for reporting.
|
|
28
|
+
|
|
29
|
+
There is no default adapter. Bind and construct exactly one in the Worker.
|
|
30
|
+
|
|
31
|
+
```ts
|
|
32
|
+
import { createWorker, D1AnalyticsStorage } from "@riebeckite/analytics-cloudflare";
|
|
33
|
+
|
|
34
|
+
export interface Env { ANALYTICS_DB: D1Database; }
|
|
35
|
+
export default { fetch: (request: Request, env: Env) =>
|
|
36
|
+
createWorker({ storage: new D1AnalyticsStorage(env.ANALYTICS_DB), cors: { allowedOrigins: ["https://www.example.com"] } }).fetch(request),
|
|
37
|
+
};
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
The Worker binding is constructed per request because `env` exists only in
|
|
41
|
+
`fetch`.
|
|
42
|
+
|
|
43
|
+
## Endpoints and validation
|
|
44
|
+
|
|
45
|
+
- `POST /events` accepts only JSON `page_view` payloads with an ISO timestamp,
|
|
46
|
+
a 1–160 character safe content ID (`[A-Za-z0-9._:-]` after the first
|
|
47
|
+
alphanumeric character), optional bounded path and language, and no unknown
|
|
48
|
+
fields. Bodies are limited to 8 KiB.
|
|
49
|
+
- `GET /content/:contentId/page-views?from=&to=` and `GET /popular?limit=&from=&to=`
|
|
50
|
+
are available only when storage advertises the corresponding capability.
|
|
51
|
+
|
|
52
|
+
Origin access is deny-by-default. Set explicit `allowedOrigins`; use `"any"`
|
|
53
|
+
only for a consciously public collector. No request IP, cookies, user-agent,
|
|
54
|
+
or fingerprinting data is read or stored. The accepted `path` and `lang` are
|
|
55
|
+
contextual metadata and D1 does not persist them.
|
|
56
|
+
|
|
57
|
+
## D1 schema and deployment
|
|
58
|
+
|
|
59
|
+
Workers must not migrate D1 during a request. Apply the included schema before
|
|
60
|
+
deploying:
|
|
61
|
+
|
|
62
|
+
```sh
|
|
63
|
+
pnpm exec wrangler d1 execute ANALYTICS_DB --file node_modules/@riebeckite/analytics-cloudflare/migrations/0001_analytics_page_views.sql
|
|
64
|
+
pnpm exec wrangler deploy
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
Copy either `templates/analytics-cloudflare/d1` or `kv` into a separate Worker
|
|
68
|
+
repository/directory. It has its own `main` and must not replace a static
|
|
69
|
+
Riebeckite site's `wrangler.jsonc` or main entry.
|
package/README_ja.md
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
# @riebeckite/analytics-cloudflare
|
|
2
|
+
|
|
3
|
+
`@riebeckite/plugin-analytics` のための独立した Cloudflare Worker 実行環境です。汎用プラグインには Cloudflare 固有コードを含めません。
|
|
4
|
+
|
|
5
|
+
## ストレージは必ず一つ選ぶ
|
|
6
|
+
|
|
7
|
+
- **D1**: UTC 日単位で集計し、原子的な upsert、コンテンツ別 PV、人気記事、日バケット単位の期間指定に対応します。生イベントは保存しません。時刻境界は日単位であり、サブ日精度ではありません。
|
|
8
|
+
- **KV**: 最小のベストエフォート集計のみです。原子的な加算や集計検索がないため、同時書き込みで欠損し得ます。読み取り API は対応能力として宣言せず、`UnsupportedAnalyticsQueryError` / HTTP 501 を返します。レポーティング用途には D1 を使ってください。
|
|
9
|
+
|
|
10
|
+
既定アダプターはありません。テンプレートの D1 または KV を一つだけ選び、静的サイト用の `wrangler.jsonc` や main は変更しません。
|
|
11
|
+
|
|
12
|
+
## プライバシーと検証
|
|
13
|
+
|
|
14
|
+
`POST /events` は 8 KiB 以下の JSON `page_view` だけを受け入れ、安全な content ID、ISO 時刻、長さを制限した `path` / `lang` を検証します。IP、Cookie、User-Agent、フィンガープリントは読まず保存しません。Origin は既定で拒否されるため、許可するサイト Origin を明示してください。
|
|
15
|
+
|
|
16
|
+
D1 スキーマはリクエスト中に実行せず、デプロイ前に `migrations/0001_analytics_page_views.sql` を `wrangler d1 execute` で明示適用してください。詳しい設定は各テンプレートの README を参照してください。
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export type { AnalyticsStorage } from "./src/domain/analytics/storage.js";
|
|
2
|
+
export { D1AnalyticsStorage, d1Storage, } from "./src/infrastructure/d1/d1_analytics_storage.js";
|
|
3
|
+
export type { D1Database } from "./src/infrastructure/d1/d1_types.js";
|
|
4
|
+
export type { KvNamespace } from "./src/infrastructure/kv/kv_analytics_storage.js";
|
|
5
|
+
export { KvAnalyticsStorage, kvStorage, } from "./src/infrastructure/kv/kv_analytics_storage.js";
|
|
6
|
+
export type { AnalyticsCorsOptions, AnalyticsWorker, AnalyticsWorkerOptions, } from "./src/presentation/worker/create_worker.js";
|
|
7
|
+
export { createWorker } from "./src/presentation/worker/create_worker.js";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,289 @@
|
|
|
1
|
+
// src/infrastructure/d1/d1_analytics_storage.ts
|
|
2
|
+
import { assertAnalyticsQuerySupported } from "@riebeckite/plugin-analytics";
|
|
3
|
+
var D1AnalyticsStorage = class {
|
|
4
|
+
constructor(database) {
|
|
5
|
+
this.database = database;
|
|
6
|
+
}
|
|
7
|
+
database;
|
|
8
|
+
capabilities = /* @__PURE__ */ new Set([
|
|
9
|
+
"capture",
|
|
10
|
+
"content_page_views",
|
|
11
|
+
"popular_content"
|
|
12
|
+
]);
|
|
13
|
+
async capture(event) {
|
|
14
|
+
if (!isPageView(event)) return;
|
|
15
|
+
const bucketStart = event.occurredAt.slice(0, 10);
|
|
16
|
+
await this.database.prepare(
|
|
17
|
+
`INSERT INTO analytics_page_views (content_id, bucket_start, page_views)
|
|
18
|
+
VALUES (?, ?, 1)
|
|
19
|
+
ON CONFLICT(content_id, bucket_start)
|
|
20
|
+
DO UPDATE SET page_views = page_views + 1`
|
|
21
|
+
).bind(event.contentId, bucketStart).run();
|
|
22
|
+
}
|
|
23
|
+
async query(query) {
|
|
24
|
+
assertAnalyticsQuerySupported(this, query);
|
|
25
|
+
const range = bucketRange(query.timeRange);
|
|
26
|
+
if (query.type === "content_page_views") {
|
|
27
|
+
const result2 = await this.database.prepare(
|
|
28
|
+
`SELECT COALESCE(SUM(page_views), 0) AS page_views
|
|
29
|
+
FROM analytics_page_views
|
|
30
|
+
WHERE content_id = ?${range.clause}`
|
|
31
|
+
).bind(query.contentId, ...range.values).all();
|
|
32
|
+
return {
|
|
33
|
+
type: query.type,
|
|
34
|
+
contentId: query.contentId,
|
|
35
|
+
pageViews: numberValue(result2.results?.[0]?.page_views)
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
const limit = Math.min(Math.max(query.limit ?? 10, 1), 100);
|
|
39
|
+
const result = await this.database.prepare(
|
|
40
|
+
`SELECT content_id, SUM(page_views) AS page_views
|
|
41
|
+
FROM analytics_page_views${range.where}
|
|
42
|
+
GROUP BY content_id
|
|
43
|
+
ORDER BY page_views DESC, content_id ASC
|
|
44
|
+
LIMIT ?`
|
|
45
|
+
).bind(...range.values, limit).all();
|
|
46
|
+
return {
|
|
47
|
+
type: query.type,
|
|
48
|
+
items: (result.results ?? []).map(
|
|
49
|
+
(row) => ({
|
|
50
|
+
contentId: row.content_id,
|
|
51
|
+
pageViews: numberValue(row.page_views)
|
|
52
|
+
})
|
|
53
|
+
)
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
};
|
|
57
|
+
function d1Storage(database) {
|
|
58
|
+
return new D1AnalyticsStorage(database);
|
|
59
|
+
}
|
|
60
|
+
function isPageView(event) {
|
|
61
|
+
return event.type === "page_view";
|
|
62
|
+
}
|
|
63
|
+
function bucketRange(timeRange) {
|
|
64
|
+
const values = [];
|
|
65
|
+
if (timeRange?.from) values.push(timeRange.from.slice(0, 10));
|
|
66
|
+
if (timeRange?.to) values.push(timeRange.to.slice(0, 10));
|
|
67
|
+
const conditions = [
|
|
68
|
+
timeRange?.from ? "bucket_start >= ?" : void 0,
|
|
69
|
+
timeRange?.to ? "bucket_start <= ?" : void 0
|
|
70
|
+
].filter((condition) => condition !== void 0);
|
|
71
|
+
const clause = conditions.length ? ` AND ${conditions.join(" AND ")}` : "";
|
|
72
|
+
return {
|
|
73
|
+
clause,
|
|
74
|
+
where: conditions.length ? ` WHERE ${conditions.join(" AND ")}` : "",
|
|
75
|
+
values
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
function numberValue(value) {
|
|
79
|
+
return typeof value === "number" ? value : Number(value ?? 0);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// src/infrastructure/kv/kv_analytics_storage.ts
|
|
83
|
+
import { UnsupportedAnalyticsQueryError } from "@riebeckite/plugin-analytics";
|
|
84
|
+
var KvAnalyticsStorage = class {
|
|
85
|
+
constructor(namespace) {
|
|
86
|
+
this.namespace = namespace;
|
|
87
|
+
}
|
|
88
|
+
namespace;
|
|
89
|
+
capabilities = /* @__PURE__ */ new Set(["capture"]);
|
|
90
|
+
async capture(event) {
|
|
91
|
+
if (!isPageView2(event)) return;
|
|
92
|
+
const key = `analytics:page-view:${event.contentId}`;
|
|
93
|
+
const existing = await this.namespace.get(key);
|
|
94
|
+
const pageViews = Math.max(0, Number.parseInt(existing ?? "0", 10) || 0) + 1;
|
|
95
|
+
await this.namespace.put(key, String(pageViews));
|
|
96
|
+
}
|
|
97
|
+
async query(query) {
|
|
98
|
+
throw new UnsupportedAnalyticsQueryError(query, query.type);
|
|
99
|
+
}
|
|
100
|
+
};
|
|
101
|
+
function kvStorage(namespace) {
|
|
102
|
+
return new KvAnalyticsStorage(namespace);
|
|
103
|
+
}
|
|
104
|
+
function isPageView2(event) {
|
|
105
|
+
return event.type === "page_view";
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// src/presentation/worker/create_worker.ts
|
|
109
|
+
var MAX_BODY_BYTES = 8192;
|
|
110
|
+
var MAX_CONTENT_ID_LENGTH = 160;
|
|
111
|
+
var MAX_PATH_LENGTH = 512;
|
|
112
|
+
var MAX_LANG_LENGTH = 35;
|
|
113
|
+
function createWorker(options) {
|
|
114
|
+
return {
|
|
115
|
+
async fetch(request) {
|
|
116
|
+
const originResponse = corsResponse(request, options.cors);
|
|
117
|
+
if (originResponse) return originResponse;
|
|
118
|
+
const corsHeaders = responseCorsHeaders(request, options.cors);
|
|
119
|
+
if (request.method === "OPTIONS") {
|
|
120
|
+
return new Response(null, { status: 204, headers: corsHeaders });
|
|
121
|
+
}
|
|
122
|
+
const url = new URL(request.url);
|
|
123
|
+
if (request.method === "POST" && url.pathname === "/events") {
|
|
124
|
+
return captureEvent(request, options.storage, corsHeaders);
|
|
125
|
+
}
|
|
126
|
+
if (request.method === "GET" && url.pathname === "/popular") {
|
|
127
|
+
return queryPopular(url, options.storage, corsHeaders);
|
|
128
|
+
}
|
|
129
|
+
const contentMatch = /^\/content\/([^/]+)\/page-views$/.exec(
|
|
130
|
+
url.pathname
|
|
131
|
+
);
|
|
132
|
+
if (request.method === "GET" && contentMatch) {
|
|
133
|
+
return queryContent(contentMatch[1], url, options.storage, corsHeaders);
|
|
134
|
+
}
|
|
135
|
+
return json({ error: "not_found" }, 404, corsHeaders);
|
|
136
|
+
}
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
async function captureEvent(request, storage, headers) {
|
|
140
|
+
if (!request.headers.get("content-type")?.includes("application/json")) {
|
|
141
|
+
return json({ error: "unsupported_media_type" }, 415, headers);
|
|
142
|
+
}
|
|
143
|
+
const length = Number(request.headers.get("content-length"));
|
|
144
|
+
if (Number.isFinite(length) && length > MAX_BODY_BYTES) {
|
|
145
|
+
return json({ error: "payload_too_large" }, 413, headers);
|
|
146
|
+
}
|
|
147
|
+
const text = await request.text();
|
|
148
|
+
if (new TextEncoder().encode(text).byteLength > MAX_BODY_BYTES) {
|
|
149
|
+
return json({ error: "payload_too_large" }, 413, headers);
|
|
150
|
+
}
|
|
151
|
+
let value;
|
|
152
|
+
try {
|
|
153
|
+
value = JSON.parse(text);
|
|
154
|
+
} catch {
|
|
155
|
+
return json({ error: "invalid_json" }, 400, headers);
|
|
156
|
+
}
|
|
157
|
+
const event = validateEvent(value);
|
|
158
|
+
if (!event) return json({ error: "invalid_event" }, 400, headers);
|
|
159
|
+
await storage.capture(event);
|
|
160
|
+
return new Response(null, { status: 204, headers });
|
|
161
|
+
}
|
|
162
|
+
async function queryContent(contentId, url, storage, headers) {
|
|
163
|
+
if (!isContentId(contentId))
|
|
164
|
+
return json({ error: "invalid_content_id" }, 400, headers);
|
|
165
|
+
const timeRange = parseTimeRange(url);
|
|
166
|
+
if (timeRange === null)
|
|
167
|
+
return json({ error: "invalid_time_range" }, 400, headers);
|
|
168
|
+
try {
|
|
169
|
+
return json(
|
|
170
|
+
await storage.query({
|
|
171
|
+
type: "content_page_views",
|
|
172
|
+
contentId,
|
|
173
|
+
timeRange: timeRange ?? void 0
|
|
174
|
+
}),
|
|
175
|
+
200,
|
|
176
|
+
headers
|
|
177
|
+
);
|
|
178
|
+
} catch (error) {
|
|
179
|
+
return queryError(error, headers);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
async function queryPopular(url, storage, headers) {
|
|
183
|
+
const timeRange = parseTimeRange(url);
|
|
184
|
+
const rawLimit = url.searchParams.get("limit");
|
|
185
|
+
const limit = rawLimit === null ? void 0 : Number(rawLimit);
|
|
186
|
+
if (timeRange === null || limit !== void 0 && (!Number.isInteger(limit) || limit < 1 || limit > 100)) {
|
|
187
|
+
return json({ error: "invalid_query" }, 400, headers);
|
|
188
|
+
}
|
|
189
|
+
try {
|
|
190
|
+
return json(
|
|
191
|
+
await storage.query({
|
|
192
|
+
type: "popular_content",
|
|
193
|
+
limit,
|
|
194
|
+
timeRange: timeRange ?? void 0
|
|
195
|
+
}),
|
|
196
|
+
200,
|
|
197
|
+
headers
|
|
198
|
+
);
|
|
199
|
+
} catch (error) {
|
|
200
|
+
return queryError(error, headers);
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
function validateEvent(value) {
|
|
204
|
+
if (!isRecord(value) || value.type !== "page_view") return void 0;
|
|
205
|
+
if (!isContentId(value.contentId) || !isIsoDate(value.occurredAt))
|
|
206
|
+
return void 0;
|
|
207
|
+
if (value.path !== void 0 && (!isSafeString(value.path, MAX_PATH_LENGTH) || !value.path.startsWith("/")))
|
|
208
|
+
return void 0;
|
|
209
|
+
if (value.lang !== void 0 && !isSafeString(value.lang, MAX_LANG_LENGTH))
|
|
210
|
+
return void 0;
|
|
211
|
+
if (Object.keys(value).some(
|
|
212
|
+
(key) => !["type", "contentId", "occurredAt", "path", "lang"].includes(key)
|
|
213
|
+
))
|
|
214
|
+
return void 0;
|
|
215
|
+
return {
|
|
216
|
+
type: "page_view",
|
|
217
|
+
contentId: value.contentId,
|
|
218
|
+
occurredAt: value.occurredAt,
|
|
219
|
+
...value.path === void 0 ? {} : { path: value.path },
|
|
220
|
+
...value.lang === void 0 ? {} : { lang: value.lang }
|
|
221
|
+
};
|
|
222
|
+
}
|
|
223
|
+
function parseTimeRange(url) {
|
|
224
|
+
const from = url.searchParams.get("from") ?? void 0;
|
|
225
|
+
const to = url.searchParams.get("to") ?? void 0;
|
|
226
|
+
if (from && !isIsoDate(from) || to && !isIsoDate(to) || from && to && from > to)
|
|
227
|
+
return null;
|
|
228
|
+
return from || to ? { from, to } : void 0;
|
|
229
|
+
}
|
|
230
|
+
function corsResponse(request, cors) {
|
|
231
|
+
const origin = request.headers.get("origin");
|
|
232
|
+
const allowed = cors?.allowedOrigins;
|
|
233
|
+
const originAllowed = origin !== null && (allowed === "any" || Array.isArray(allowed) && allowed.includes(origin));
|
|
234
|
+
if (origin !== null && !originAllowed)
|
|
235
|
+
return json({ error: "origin_not_allowed" }, 403);
|
|
236
|
+
if (origin === null && !cors?.allowMissingOrigin)
|
|
237
|
+
return json({ error: "origin_required" }, 403);
|
|
238
|
+
return void 0;
|
|
239
|
+
}
|
|
240
|
+
function responseCorsHeaders(request, cors) {
|
|
241
|
+
const headers = new Headers({ Vary: "Origin" });
|
|
242
|
+
const origin = request.headers.get("origin");
|
|
243
|
+
if (origin && (cors?.allowedOrigins === "any" || cors?.allowedOrigins?.includes(origin))) {
|
|
244
|
+
headers.set(
|
|
245
|
+
"Access-Control-Allow-Origin",
|
|
246
|
+
cors.allowedOrigins === "any" ? "*" : origin
|
|
247
|
+
);
|
|
248
|
+
headers.set("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
|
|
249
|
+
headers.set("Access-Control-Allow-Headers", "Content-Type");
|
|
250
|
+
}
|
|
251
|
+
return headers;
|
|
252
|
+
}
|
|
253
|
+
function queryError(error, headers) {
|
|
254
|
+
if (error instanceof Error && error.name === "UnsupportedAnalyticsQueryError") {
|
|
255
|
+
return json(
|
|
256
|
+
{ error: "unsupported_query", message: error.message },
|
|
257
|
+
501,
|
|
258
|
+
headers
|
|
259
|
+
);
|
|
260
|
+
}
|
|
261
|
+
return json({ error: "storage_unavailable" }, 503, headers);
|
|
262
|
+
}
|
|
263
|
+
function json(value, status, headers = new Headers()) {
|
|
264
|
+
const output = new Headers(headers);
|
|
265
|
+
output.set("Content-Type", "application/json; charset=utf-8");
|
|
266
|
+
return new Response(JSON.stringify(value), { status, headers: output });
|
|
267
|
+
}
|
|
268
|
+
function isRecord(value) {
|
|
269
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
270
|
+
}
|
|
271
|
+
function isSafeString(value, length) {
|
|
272
|
+
return typeof value === "string" && value.length > 0 && value.length <= length && [...value].every((character) => {
|
|
273
|
+
const code = character.codePointAt(0) ?? 0;
|
|
274
|
+
return code > 31 && code !== 127;
|
|
275
|
+
});
|
|
276
|
+
}
|
|
277
|
+
function isContentId(value) {
|
|
278
|
+
return isSafeString(value, MAX_CONTENT_ID_LENGTH) && value.trim() === value;
|
|
279
|
+
}
|
|
280
|
+
function isIsoDate(value) {
|
|
281
|
+
return typeof value === "string" && value.length <= 40 && !Number.isNaN(Date.parse(value));
|
|
282
|
+
}
|
|
283
|
+
export {
|
|
284
|
+
D1AnalyticsStorage,
|
|
285
|
+
KvAnalyticsStorage,
|
|
286
|
+
createWorker,
|
|
287
|
+
d1Storage,
|
|
288
|
+
kvStorage
|
|
289
|
+
};
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { AnalyticsEvent, AnalyticsQuery, AnalyticsResult } from "@riebeckite/plugin-analytics";
|
|
2
|
+
import type { AnalyticsStorage } from "../../domain/analytics/storage.js";
|
|
3
|
+
import type { D1Database } from "./d1_types.js";
|
|
4
|
+
/**
|
|
5
|
+
* D1 storage aggregates page views by UTC day. It never writes individual event
|
|
6
|
+
* records. Ranges select whole matching UTC buckets, so sub-day bounds are not
|
|
7
|
+
* exact and should be avoided by callers that need event-level precision.
|
|
8
|
+
*/
|
|
9
|
+
export declare class D1AnalyticsStorage implements AnalyticsStorage {
|
|
10
|
+
private readonly database;
|
|
11
|
+
readonly capabilities: Set<"capture" | "content_page_views" | "popular_content">;
|
|
12
|
+
constructor(database: D1Database);
|
|
13
|
+
capture(event: AnalyticsEvent): Promise<void>;
|
|
14
|
+
query(query: AnalyticsQuery): Promise<AnalyticsResult>;
|
|
15
|
+
}
|
|
16
|
+
/** Creates a D1-backed analytics storage adapter from a Worker binding. */
|
|
17
|
+
export declare function d1Storage(database: D1Database): AnalyticsStorage;
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export interface D1Result<T = unknown> {
|
|
2
|
+
results?: T[];
|
|
3
|
+
}
|
|
4
|
+
export interface D1PreparedStatement {
|
|
5
|
+
bind(...values: unknown[]): D1PreparedStatement;
|
|
6
|
+
run(): Promise<unknown>;
|
|
7
|
+
all<T = unknown>(): Promise<D1Result<T>>;
|
|
8
|
+
}
|
|
9
|
+
export interface D1Database {
|
|
10
|
+
prepare(query: string): D1PreparedStatement;
|
|
11
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { AnalyticsEvent, AnalyticsQuery, AnalyticsResult } from "@riebeckite/plugin-analytics";
|
|
2
|
+
import type { AnalyticsStorage } from "../../domain/analytics/storage.js";
|
|
3
|
+
export interface KvNamespace {
|
|
4
|
+
get(key: string): Promise<string | null>;
|
|
5
|
+
put(key: string, value: string): Promise<void>;
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* Minimal KV capture storage. KV has no atomic increment or aggregate query;
|
|
9
|
+
* its best-effort totals may lose concurrent writes and it intentionally does
|
|
10
|
+
* not advertise read capabilities.
|
|
11
|
+
*/
|
|
12
|
+
export declare class KvAnalyticsStorage implements AnalyticsStorage {
|
|
13
|
+
private readonly namespace;
|
|
14
|
+
readonly capabilities: Set<"capture">;
|
|
15
|
+
constructor(namespace: KvNamespace);
|
|
16
|
+
capture(event: AnalyticsEvent): Promise<void>;
|
|
17
|
+
query(query: AnalyticsQuery): Promise<AnalyticsResult>;
|
|
18
|
+
}
|
|
19
|
+
/** Creates a KV-backed, capture-only analytics storage adapter from a binding. */
|
|
20
|
+
export declare function kvStorage(namespace: KvNamespace): AnalyticsStorage;
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { AnalyticsStorage } from "../../domain/analytics/storage.js";
|
|
2
|
+
export type AnalyticsCorsOptions = Readonly<{
|
|
3
|
+
/** Explicit browser origins, or "any" for a deliberately public collector. */
|
|
4
|
+
allowedOrigins?: readonly string[] | "any";
|
|
5
|
+
/** Allows non-browser clients that do not send Origin. Defaults to false. */
|
|
6
|
+
allowMissingOrigin?: boolean;
|
|
7
|
+
}>;
|
|
8
|
+
export type AnalyticsWorkerOptions = Readonly<{
|
|
9
|
+
/** One explicitly selected runtime storage adapter. No default is provided. */
|
|
10
|
+
storage: AnalyticsStorage;
|
|
11
|
+
cors?: AnalyticsCorsOptions;
|
|
12
|
+
}>;
|
|
13
|
+
export type AnalyticsWorker = Readonly<{
|
|
14
|
+
fetch(request: Request): Promise<Response>;
|
|
15
|
+
}>;
|
|
16
|
+
/** Creates a standalone analytics Worker; it does not serve static site assets. */
|
|
17
|
+
export declare function createWorker(options: AnalyticsWorkerOptions): AnalyticsWorker;
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
-- Apply explicitly with: wrangler d1 execute <DATABASE_NAME> --file migrations/0001_analytics_page_views.sql
|
|
2
|
+
-- D1 Workers cannot safely run schema migration during request handling.
|
|
3
|
+
CREATE TABLE IF NOT EXISTS analytics_page_views (
|
|
4
|
+
content_id TEXT NOT NULL,
|
|
5
|
+
bucket_start TEXT NOT NULL,
|
|
6
|
+
page_views INTEGER NOT NULL DEFAULT 0 CHECK (page_views >= 0),
|
|
7
|
+
PRIMARY KEY (content_id, bucket_start)
|
|
8
|
+
);
|
package/package.json
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@riebeckite/analytics-cloudflare",
|
|
3
|
+
"version": "0.0.3",
|
|
4
|
+
"license": "Apache-2.0",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./dist/index.js",
|
|
7
|
+
"types": "./dist/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
11
|
+
"import": "./dist/index.js",
|
|
12
|
+
"source": "./index.ts",
|
|
13
|
+
"default": "./dist/index.js"
|
|
14
|
+
}
|
|
15
|
+
},
|
|
16
|
+
"dependencies": {
|
|
17
|
+
"@riebeckite/plugin-analytics": "0.0.3"
|
|
18
|
+
},
|
|
19
|
+
"publishConfig": {
|
|
20
|
+
"access": "public"
|
|
21
|
+
},
|
|
22
|
+
"files": [
|
|
23
|
+
"LICENSE",
|
|
24
|
+
"README.md",
|
|
25
|
+
"README_ja.md",
|
|
26
|
+
"migrations",
|
|
27
|
+
"dist"
|
|
28
|
+
],
|
|
29
|
+
"repository": {
|
|
30
|
+
"type": "git",
|
|
31
|
+
"url": "https://github.com/Rerurate514/riebeckite.git",
|
|
32
|
+
"directory": "packages/integrations/analytics-cloudflare"
|
|
33
|
+
},
|
|
34
|
+
"homepage": "https://github.com/Rerurate514/riebeckite#readme",
|
|
35
|
+
"bugs": {
|
|
36
|
+
"url": "https://github.com/Rerurate514/riebeckite/issues"
|
|
37
|
+
},
|
|
38
|
+
"description": "Cloudflare Workers, D1, and KV runtime for Riebeckite analytics.",
|
|
39
|
+
"keywords": [
|
|
40
|
+
"riebeckite",
|
|
41
|
+
"analytics",
|
|
42
|
+
"cloudflare",
|
|
43
|
+
"workers",
|
|
44
|
+
"d1"
|
|
45
|
+
],
|
|
46
|
+
"engines": {
|
|
47
|
+
"node": "^20.19.0 || >=22.12.0"
|
|
48
|
+
},
|
|
49
|
+
"sideEffects": false,
|
|
50
|
+
"scripts": {
|
|
51
|
+
"build": "node ../../../scripts/build_package.mjs",
|
|
52
|
+
"test": "pnpm exec tsx --test \"test/*.test.ts\""
|
|
53
|
+
}
|
|
54
|
+
}
|