@jayfarei/lazyanalytics 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +27 -0
- package/LICENSE +21 -0
- package/README.md +210 -0
- package/cli/dist/commands/base.d.ts +2 -0
- package/cli/dist/commands/base.js +129 -0
- package/cli/dist/commands/config.d.ts +2 -0
- package/cli/dist/commands/config.js +45 -0
- package/cli/dist/commands/setup.d.ts +2 -0
- package/cli/dist/commands/setup.js +155 -0
- package/cli/dist/commands/sites.d.ts +2 -0
- package/cli/dist/commands/sites.js +127 -0
- package/cli/dist/commands/skill.d.ts +2 -0
- package/cli/dist/commands/skill.js +28 -0
- package/cli/dist/commands/snippet.d.ts +2 -0
- package/cli/dist/commands/snippet.js +48 -0
- package/cli/dist/commands/usage.d.ts +2 -0
- package/cli/dist/commands/usage.js +156 -0
- package/cli/dist/index.d.ts +2 -0
- package/cli/dist/index.js +31 -0
- package/cli/dist/lib/api.d.ts +9 -0
- package/cli/dist/lib/api.js +27 -0
- package/cli/dist/lib/env.d.ts +15 -0
- package/cli/dist/lib/env.js +81 -0
- package/cli/dist/lib/paths.d.ts +16 -0
- package/cli/dist/lib/paths.js +54 -0
- package/cli/dist/lib/prompt.d.ts +8 -0
- package/cli/dist/lib/prompt.js +42 -0
- package/cli/dist/lib/scaffold.d.ts +5 -0
- package/cli/dist/lib/scaffold.js +21 -0
- package/cli/dist/lib/wrangler.d.ts +17 -0
- package/cli/dist/lib/wrangler.js +65 -0
- package/dist/worker.js +3221 -0
- package/package.json +58 -0
- package/skill/SKILL.md +111 -0
- package/templates/wrangler.toml +14 -0
package/dist/worker.js
ADDED
|
@@ -0,0 +1,3221 @@
|
|
|
1
|
+
// worker/node_modules/hono/dist/compose.js
|
|
2
|
+
var compose = (middleware, onError, onNotFound) => {
|
|
3
|
+
return (context, next) => {
|
|
4
|
+
let index = -1;
|
|
5
|
+
return dispatch(0);
|
|
6
|
+
async function dispatch(i) {
|
|
7
|
+
if (i <= index) {
|
|
8
|
+
throw new Error("next() called multiple times");
|
|
9
|
+
}
|
|
10
|
+
index = i;
|
|
11
|
+
let res;
|
|
12
|
+
let isError = false;
|
|
13
|
+
let handler;
|
|
14
|
+
if (middleware[i]) {
|
|
15
|
+
handler = middleware[i][0][0];
|
|
16
|
+
context.req.routeIndex = i;
|
|
17
|
+
} else {
|
|
18
|
+
handler = i === middleware.length && next || void 0;
|
|
19
|
+
}
|
|
20
|
+
if (handler) {
|
|
21
|
+
try {
|
|
22
|
+
res = await handler(context, () => dispatch(i + 1));
|
|
23
|
+
} catch (err) {
|
|
24
|
+
if (err instanceof Error && onError) {
|
|
25
|
+
context.error = err;
|
|
26
|
+
res = await onError(err, context);
|
|
27
|
+
isError = true;
|
|
28
|
+
} else {
|
|
29
|
+
throw err;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
} else {
|
|
33
|
+
if (context.finalized === false && onNotFound) {
|
|
34
|
+
res = await onNotFound(context);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
if (res && (context.finalized === false || isError)) {
|
|
38
|
+
context.res = res;
|
|
39
|
+
}
|
|
40
|
+
return context;
|
|
41
|
+
}
|
|
42
|
+
};
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
// worker/node_modules/hono/dist/request/constants.js
|
|
46
|
+
var GET_MATCH_RESULT = /* @__PURE__ */ Symbol();
|
|
47
|
+
|
|
48
|
+
// worker/node_modules/hono/dist/utils/body.js
|
|
49
|
+
var parseBody = async (request, options = /* @__PURE__ */ Object.create(null)) => {
|
|
50
|
+
const { all = false, dot = false } = options;
|
|
51
|
+
const headers = request instanceof HonoRequest ? request.raw.headers : request.headers;
|
|
52
|
+
const contentType = headers.get("Content-Type");
|
|
53
|
+
if (contentType?.startsWith("multipart/form-data") || contentType?.startsWith("application/x-www-form-urlencoded")) {
|
|
54
|
+
return parseFormData(request, { all, dot });
|
|
55
|
+
}
|
|
56
|
+
return {};
|
|
57
|
+
};
|
|
58
|
+
async function parseFormData(request, options) {
|
|
59
|
+
const formData = await request.formData();
|
|
60
|
+
if (formData) {
|
|
61
|
+
return convertFormDataToBodyData(formData, options);
|
|
62
|
+
}
|
|
63
|
+
return {};
|
|
64
|
+
}
|
|
65
|
+
function convertFormDataToBodyData(formData, options) {
|
|
66
|
+
const form = /* @__PURE__ */ Object.create(null);
|
|
67
|
+
formData.forEach((value, key) => {
|
|
68
|
+
const shouldParseAllValues = options.all || key.endsWith("[]");
|
|
69
|
+
if (!shouldParseAllValues) {
|
|
70
|
+
form[key] = value;
|
|
71
|
+
} else {
|
|
72
|
+
handleParsingAllValues(form, key, value);
|
|
73
|
+
}
|
|
74
|
+
});
|
|
75
|
+
if (options.dot) {
|
|
76
|
+
Object.entries(form).forEach(([key, value]) => {
|
|
77
|
+
const shouldParseDotValues = key.includes(".");
|
|
78
|
+
if (shouldParseDotValues) {
|
|
79
|
+
handleParsingNestedValues(form, key, value);
|
|
80
|
+
delete form[key];
|
|
81
|
+
}
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
return form;
|
|
85
|
+
}
|
|
86
|
+
var handleParsingAllValues = (form, key, value) => {
|
|
87
|
+
if (form[key] !== void 0) {
|
|
88
|
+
if (Array.isArray(form[key])) {
|
|
89
|
+
;
|
|
90
|
+
form[key].push(value);
|
|
91
|
+
} else {
|
|
92
|
+
form[key] = [form[key], value];
|
|
93
|
+
}
|
|
94
|
+
} else {
|
|
95
|
+
if (!key.endsWith("[]")) {
|
|
96
|
+
form[key] = value;
|
|
97
|
+
} else {
|
|
98
|
+
form[key] = [value];
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
};
|
|
102
|
+
var handleParsingNestedValues = (form, key, value) => {
|
|
103
|
+
if (/(?:^|\.)__proto__\./.test(key)) {
|
|
104
|
+
return;
|
|
105
|
+
}
|
|
106
|
+
let nestedForm = form;
|
|
107
|
+
const keys = key.split(".");
|
|
108
|
+
keys.forEach((key2, index) => {
|
|
109
|
+
if (index === keys.length - 1) {
|
|
110
|
+
nestedForm[key2] = value;
|
|
111
|
+
} else {
|
|
112
|
+
if (!nestedForm[key2] || typeof nestedForm[key2] !== "object" || Array.isArray(nestedForm[key2]) || nestedForm[key2] instanceof File) {
|
|
113
|
+
nestedForm[key2] = /* @__PURE__ */ Object.create(null);
|
|
114
|
+
}
|
|
115
|
+
nestedForm = nestedForm[key2];
|
|
116
|
+
}
|
|
117
|
+
});
|
|
118
|
+
};
|
|
119
|
+
|
|
120
|
+
// worker/node_modules/hono/dist/utils/url.js
|
|
121
|
+
var splitPath = (path) => {
|
|
122
|
+
const paths = path.split("/");
|
|
123
|
+
if (paths[0] === "") {
|
|
124
|
+
paths.shift();
|
|
125
|
+
}
|
|
126
|
+
return paths;
|
|
127
|
+
};
|
|
128
|
+
var splitRoutingPath = (routePath) => {
|
|
129
|
+
const { groups, path } = extractGroupsFromPath(routePath);
|
|
130
|
+
const paths = splitPath(path);
|
|
131
|
+
return replaceGroupMarks(paths, groups);
|
|
132
|
+
};
|
|
133
|
+
var extractGroupsFromPath = (path) => {
|
|
134
|
+
const groups = [];
|
|
135
|
+
path = path.replace(/\{[^}]+\}/g, (match2, index) => {
|
|
136
|
+
const mark = `@${index}`;
|
|
137
|
+
groups.push([mark, match2]);
|
|
138
|
+
return mark;
|
|
139
|
+
});
|
|
140
|
+
return { groups, path };
|
|
141
|
+
};
|
|
142
|
+
var replaceGroupMarks = (paths, groups) => {
|
|
143
|
+
for (let i = groups.length - 1; i >= 0; i--) {
|
|
144
|
+
const [mark] = groups[i];
|
|
145
|
+
for (let j = paths.length - 1; j >= 0; j--) {
|
|
146
|
+
if (paths[j].includes(mark)) {
|
|
147
|
+
paths[j] = paths[j].replace(mark, groups[i][1]);
|
|
148
|
+
break;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
return paths;
|
|
153
|
+
};
|
|
154
|
+
var patternCache = {};
|
|
155
|
+
var getPattern = (label, next) => {
|
|
156
|
+
if (label === "*") {
|
|
157
|
+
return "*";
|
|
158
|
+
}
|
|
159
|
+
const match2 = label.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
|
|
160
|
+
if (match2) {
|
|
161
|
+
const cacheKey = `${label}#${next}`;
|
|
162
|
+
if (!patternCache[cacheKey]) {
|
|
163
|
+
if (match2[2]) {
|
|
164
|
+
patternCache[cacheKey] = next && next[0] !== ":" && next[0] !== "*" ? [cacheKey, match2[1], new RegExp(`^${match2[2]}(?=/${next})`)] : [label, match2[1], new RegExp(`^${match2[2]}$`)];
|
|
165
|
+
} else {
|
|
166
|
+
patternCache[cacheKey] = [label, match2[1], true];
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
return patternCache[cacheKey];
|
|
170
|
+
}
|
|
171
|
+
return null;
|
|
172
|
+
};
|
|
173
|
+
var tryDecode = (str, decoder) => {
|
|
174
|
+
try {
|
|
175
|
+
return decoder(str);
|
|
176
|
+
} catch {
|
|
177
|
+
return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match2) => {
|
|
178
|
+
try {
|
|
179
|
+
return decoder(match2);
|
|
180
|
+
} catch {
|
|
181
|
+
return match2;
|
|
182
|
+
}
|
|
183
|
+
});
|
|
184
|
+
}
|
|
185
|
+
};
|
|
186
|
+
var tryDecodeURI = (str) => tryDecode(str, decodeURI);
|
|
187
|
+
var getPath = (request) => {
|
|
188
|
+
const url = request.url;
|
|
189
|
+
const start = url.indexOf("/", url.indexOf(":") + 4);
|
|
190
|
+
let i = start;
|
|
191
|
+
for (; i < url.length; i++) {
|
|
192
|
+
const charCode = url.charCodeAt(i);
|
|
193
|
+
if (charCode === 37) {
|
|
194
|
+
const queryIndex = url.indexOf("?", i);
|
|
195
|
+
const hashIndex = url.indexOf("#", i);
|
|
196
|
+
const end = queryIndex === -1 ? hashIndex === -1 ? void 0 : hashIndex : hashIndex === -1 ? queryIndex : Math.min(queryIndex, hashIndex);
|
|
197
|
+
const path = url.slice(start, end);
|
|
198
|
+
return tryDecodeURI(path.includes("%25") ? path.replace(/%25/g, "%2525") : path);
|
|
199
|
+
} else if (charCode === 63 || charCode === 35) {
|
|
200
|
+
break;
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
return url.slice(start, i);
|
|
204
|
+
};
|
|
205
|
+
var getPathNoStrict = (request) => {
|
|
206
|
+
const result = getPath(request);
|
|
207
|
+
return result.length > 1 && result.at(-1) === "/" ? result.slice(0, -1) : result;
|
|
208
|
+
};
|
|
209
|
+
var mergePath = (base, sub, ...rest) => {
|
|
210
|
+
if (rest.length) {
|
|
211
|
+
sub = mergePath(sub, ...rest);
|
|
212
|
+
}
|
|
213
|
+
return `${base?.[0] === "/" ? "" : "/"}${base}${sub === "/" ? "" : `${base?.at(-1) === "/" ? "" : "/"}${sub?.[0] === "/" ? sub.slice(1) : sub}`}`;
|
|
214
|
+
};
|
|
215
|
+
var checkOptionalParameter = (path) => {
|
|
216
|
+
if (path.charCodeAt(path.length - 1) !== 63 || !path.includes(":")) {
|
|
217
|
+
return null;
|
|
218
|
+
}
|
|
219
|
+
const segments = path.split("/");
|
|
220
|
+
const results = [];
|
|
221
|
+
let basePath = "";
|
|
222
|
+
segments.forEach((segment) => {
|
|
223
|
+
if (segment !== "" && !/\:/.test(segment)) {
|
|
224
|
+
basePath += "/" + segment;
|
|
225
|
+
} else if (/\:/.test(segment)) {
|
|
226
|
+
if (/\?/.test(segment)) {
|
|
227
|
+
if (results.length === 0 && basePath === "") {
|
|
228
|
+
results.push("/");
|
|
229
|
+
} else {
|
|
230
|
+
results.push(basePath);
|
|
231
|
+
}
|
|
232
|
+
const optionalSegment = segment.replace("?", "");
|
|
233
|
+
basePath += "/" + optionalSegment;
|
|
234
|
+
results.push(basePath);
|
|
235
|
+
} else {
|
|
236
|
+
basePath += "/" + segment;
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
});
|
|
240
|
+
return results.filter((v, i, a) => a.indexOf(v) === i);
|
|
241
|
+
};
|
|
242
|
+
var _decodeURI = (value) => {
|
|
243
|
+
if (!/[%+]/.test(value)) {
|
|
244
|
+
return value;
|
|
245
|
+
}
|
|
246
|
+
if (value.indexOf("+") !== -1) {
|
|
247
|
+
value = value.replace(/\+/g, " ");
|
|
248
|
+
}
|
|
249
|
+
return value.indexOf("%") !== -1 ? tryDecode(value, decodeURIComponent_) : value;
|
|
250
|
+
};
|
|
251
|
+
var _getQueryParam = (url, key, multiple) => {
|
|
252
|
+
let encoded;
|
|
253
|
+
if (!multiple && key && !/[%+]/.test(key)) {
|
|
254
|
+
let keyIndex2 = url.indexOf("?", 8);
|
|
255
|
+
if (keyIndex2 === -1) {
|
|
256
|
+
return void 0;
|
|
257
|
+
}
|
|
258
|
+
if (!url.startsWith(key, keyIndex2 + 1)) {
|
|
259
|
+
keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
|
|
260
|
+
}
|
|
261
|
+
while (keyIndex2 !== -1) {
|
|
262
|
+
const trailingKeyCode = url.charCodeAt(keyIndex2 + key.length + 1);
|
|
263
|
+
if (trailingKeyCode === 61) {
|
|
264
|
+
const valueIndex = keyIndex2 + key.length + 2;
|
|
265
|
+
const endIndex = url.indexOf("&", valueIndex);
|
|
266
|
+
return _decodeURI(url.slice(valueIndex, endIndex === -1 ? void 0 : endIndex));
|
|
267
|
+
} else if (trailingKeyCode == 38 || isNaN(trailingKeyCode)) {
|
|
268
|
+
return "";
|
|
269
|
+
}
|
|
270
|
+
keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
|
|
271
|
+
}
|
|
272
|
+
encoded = /[%+]/.test(url);
|
|
273
|
+
if (!encoded) {
|
|
274
|
+
return void 0;
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
const results = {};
|
|
278
|
+
encoded ??= /[%+]/.test(url);
|
|
279
|
+
let keyIndex = url.indexOf("?", 8);
|
|
280
|
+
while (keyIndex !== -1) {
|
|
281
|
+
const nextKeyIndex = url.indexOf("&", keyIndex + 1);
|
|
282
|
+
let valueIndex = url.indexOf("=", keyIndex);
|
|
283
|
+
if (valueIndex > nextKeyIndex && nextKeyIndex !== -1) {
|
|
284
|
+
valueIndex = -1;
|
|
285
|
+
}
|
|
286
|
+
let name = url.slice(
|
|
287
|
+
keyIndex + 1,
|
|
288
|
+
valueIndex === -1 ? nextKeyIndex === -1 ? void 0 : nextKeyIndex : valueIndex
|
|
289
|
+
);
|
|
290
|
+
if (encoded) {
|
|
291
|
+
name = _decodeURI(name);
|
|
292
|
+
}
|
|
293
|
+
keyIndex = nextKeyIndex;
|
|
294
|
+
if (name === "") {
|
|
295
|
+
continue;
|
|
296
|
+
}
|
|
297
|
+
let value;
|
|
298
|
+
if (valueIndex === -1) {
|
|
299
|
+
value = "";
|
|
300
|
+
} else {
|
|
301
|
+
value = url.slice(valueIndex + 1, nextKeyIndex === -1 ? void 0 : nextKeyIndex);
|
|
302
|
+
if (encoded) {
|
|
303
|
+
value = _decodeURI(value);
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
if (multiple) {
|
|
307
|
+
if (!(results[name] && Array.isArray(results[name]))) {
|
|
308
|
+
results[name] = [];
|
|
309
|
+
}
|
|
310
|
+
;
|
|
311
|
+
results[name].push(value);
|
|
312
|
+
} else {
|
|
313
|
+
results[name] ??= value;
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
return key ? results[key] : results;
|
|
317
|
+
};
|
|
318
|
+
var getQueryParam = _getQueryParam;
|
|
319
|
+
var getQueryParams = (url, key) => {
|
|
320
|
+
return _getQueryParam(url, key, true);
|
|
321
|
+
};
|
|
322
|
+
var decodeURIComponent_ = decodeURIComponent;
|
|
323
|
+
|
|
324
|
+
// worker/node_modules/hono/dist/request.js
|
|
325
|
+
var tryDecodeURIComponent = (str) => tryDecode(str, decodeURIComponent_);
|
|
326
|
+
var HonoRequest = class {
|
|
327
|
+
/**
|
|
328
|
+
* `.raw` can get the raw Request object.
|
|
329
|
+
*
|
|
330
|
+
* @see {@link https://hono.dev/docs/api/request#raw}
|
|
331
|
+
*
|
|
332
|
+
* @example
|
|
333
|
+
* ```ts
|
|
334
|
+
* // For Cloudflare Workers
|
|
335
|
+
* app.post('/', async (c) => {
|
|
336
|
+
* const metadata = c.req.raw.cf?.hostMetadata?
|
|
337
|
+
* ...
|
|
338
|
+
* })
|
|
339
|
+
* ```
|
|
340
|
+
*/
|
|
341
|
+
raw;
|
|
342
|
+
#validatedData;
|
|
343
|
+
// Short name of validatedData
|
|
344
|
+
#matchResult;
|
|
345
|
+
routeIndex = 0;
|
|
346
|
+
/**
|
|
347
|
+
* `.path` can get the pathname of the request.
|
|
348
|
+
*
|
|
349
|
+
* @see {@link https://hono.dev/docs/api/request#path}
|
|
350
|
+
*
|
|
351
|
+
* @example
|
|
352
|
+
* ```ts
|
|
353
|
+
* app.get('/about/me', (c) => {
|
|
354
|
+
* const pathname = c.req.path // `/about/me`
|
|
355
|
+
* })
|
|
356
|
+
* ```
|
|
357
|
+
*/
|
|
358
|
+
path;
|
|
359
|
+
bodyCache = {};
|
|
360
|
+
constructor(request, path = "/", matchResult = [[]]) {
|
|
361
|
+
this.raw = request;
|
|
362
|
+
this.path = path;
|
|
363
|
+
this.#matchResult = matchResult;
|
|
364
|
+
this.#validatedData = {};
|
|
365
|
+
}
|
|
366
|
+
param(key) {
|
|
367
|
+
return key ? this.#getDecodedParam(key) : this.#getAllDecodedParams();
|
|
368
|
+
}
|
|
369
|
+
#getDecodedParam(key) {
|
|
370
|
+
const paramKey = this.#matchResult[0][this.routeIndex][1][key];
|
|
371
|
+
const param = this.#getParamValue(paramKey);
|
|
372
|
+
return param && /\%/.test(param) ? tryDecodeURIComponent(param) : param;
|
|
373
|
+
}
|
|
374
|
+
#getAllDecodedParams() {
|
|
375
|
+
const decoded = {};
|
|
376
|
+
const keys = Object.keys(this.#matchResult[0][this.routeIndex][1]);
|
|
377
|
+
for (const key of keys) {
|
|
378
|
+
const value = this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key]);
|
|
379
|
+
if (value !== void 0) {
|
|
380
|
+
decoded[key] = /\%/.test(value) ? tryDecodeURIComponent(value) : value;
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
return decoded;
|
|
384
|
+
}
|
|
385
|
+
#getParamValue(paramKey) {
|
|
386
|
+
return this.#matchResult[1] ? this.#matchResult[1][paramKey] : paramKey;
|
|
387
|
+
}
|
|
388
|
+
query(key) {
|
|
389
|
+
return getQueryParam(this.url, key);
|
|
390
|
+
}
|
|
391
|
+
queries(key) {
|
|
392
|
+
return getQueryParams(this.url, key);
|
|
393
|
+
}
|
|
394
|
+
header(name) {
|
|
395
|
+
if (name) {
|
|
396
|
+
return this.raw.headers.get(name) ?? void 0;
|
|
397
|
+
}
|
|
398
|
+
const headerData = {};
|
|
399
|
+
this.raw.headers.forEach((value, key) => {
|
|
400
|
+
headerData[key] = value;
|
|
401
|
+
});
|
|
402
|
+
return headerData;
|
|
403
|
+
}
|
|
404
|
+
async parseBody(options) {
|
|
405
|
+
return parseBody(this, options);
|
|
406
|
+
}
|
|
407
|
+
#cachedBody = (key) => {
|
|
408
|
+
const { bodyCache, raw: raw2 } = this;
|
|
409
|
+
const cachedBody = bodyCache[key];
|
|
410
|
+
if (cachedBody) {
|
|
411
|
+
return cachedBody;
|
|
412
|
+
}
|
|
413
|
+
const anyCachedKey = Object.keys(bodyCache)[0];
|
|
414
|
+
if (anyCachedKey) {
|
|
415
|
+
return bodyCache[anyCachedKey].then((body) => {
|
|
416
|
+
if (anyCachedKey === "json") {
|
|
417
|
+
body = JSON.stringify(body);
|
|
418
|
+
}
|
|
419
|
+
return new Response(body)[key]();
|
|
420
|
+
});
|
|
421
|
+
}
|
|
422
|
+
return bodyCache[key] = raw2[key]();
|
|
423
|
+
};
|
|
424
|
+
/**
|
|
425
|
+
* `.json()` can parse Request body of type `application/json`
|
|
426
|
+
*
|
|
427
|
+
* @see {@link https://hono.dev/docs/api/request#json}
|
|
428
|
+
*
|
|
429
|
+
* @example
|
|
430
|
+
* ```ts
|
|
431
|
+
* app.post('/entry', async (c) => {
|
|
432
|
+
* const body = await c.req.json()
|
|
433
|
+
* })
|
|
434
|
+
* ```
|
|
435
|
+
*/
|
|
436
|
+
json() {
|
|
437
|
+
return this.#cachedBody("text").then((text) => JSON.parse(text));
|
|
438
|
+
}
|
|
439
|
+
/**
|
|
440
|
+
* `.text()` can parse Request body of type `text/plain`
|
|
441
|
+
*
|
|
442
|
+
* @see {@link https://hono.dev/docs/api/request#text}
|
|
443
|
+
*
|
|
444
|
+
* @example
|
|
445
|
+
* ```ts
|
|
446
|
+
* app.post('/entry', async (c) => {
|
|
447
|
+
* const body = await c.req.text()
|
|
448
|
+
* })
|
|
449
|
+
* ```
|
|
450
|
+
*/
|
|
451
|
+
text() {
|
|
452
|
+
return this.#cachedBody("text");
|
|
453
|
+
}
|
|
454
|
+
/**
|
|
455
|
+
* `.arrayBuffer()` parse Request body as an `ArrayBuffer`
|
|
456
|
+
*
|
|
457
|
+
* @see {@link https://hono.dev/docs/api/request#arraybuffer}
|
|
458
|
+
*
|
|
459
|
+
* @example
|
|
460
|
+
* ```ts
|
|
461
|
+
* app.post('/entry', async (c) => {
|
|
462
|
+
* const body = await c.req.arrayBuffer()
|
|
463
|
+
* })
|
|
464
|
+
* ```
|
|
465
|
+
*/
|
|
466
|
+
arrayBuffer() {
|
|
467
|
+
return this.#cachedBody("arrayBuffer");
|
|
468
|
+
}
|
|
469
|
+
/**
|
|
470
|
+
* Parses the request body as a `Blob`.
|
|
471
|
+
* @example
|
|
472
|
+
* ```ts
|
|
473
|
+
* app.post('/entry', async (c) => {
|
|
474
|
+
* const body = await c.req.blob();
|
|
475
|
+
* });
|
|
476
|
+
* ```
|
|
477
|
+
* @see https://hono.dev/docs/api/request#blob
|
|
478
|
+
*/
|
|
479
|
+
blob() {
|
|
480
|
+
return this.#cachedBody("blob");
|
|
481
|
+
}
|
|
482
|
+
/**
|
|
483
|
+
* Parses the request body as `FormData`.
|
|
484
|
+
* @example
|
|
485
|
+
* ```ts
|
|
486
|
+
* app.post('/entry', async (c) => {
|
|
487
|
+
* const body = await c.req.formData();
|
|
488
|
+
* });
|
|
489
|
+
* ```
|
|
490
|
+
* @see https://hono.dev/docs/api/request#formdata
|
|
491
|
+
*/
|
|
492
|
+
formData() {
|
|
493
|
+
return this.#cachedBody("formData");
|
|
494
|
+
}
|
|
495
|
+
/**
|
|
496
|
+
* Adds validated data to the request.
|
|
497
|
+
*
|
|
498
|
+
* @param target - The target of the validation.
|
|
499
|
+
* @param data - The validated data to add.
|
|
500
|
+
*/
|
|
501
|
+
addValidatedData(target, data) {
|
|
502
|
+
this.#validatedData[target] = data;
|
|
503
|
+
}
|
|
504
|
+
valid(target) {
|
|
505
|
+
return this.#validatedData[target];
|
|
506
|
+
}
|
|
507
|
+
/**
|
|
508
|
+
* `.url()` can get the request url strings.
|
|
509
|
+
*
|
|
510
|
+
* @see {@link https://hono.dev/docs/api/request#url}
|
|
511
|
+
*
|
|
512
|
+
* @example
|
|
513
|
+
* ```ts
|
|
514
|
+
* app.get('/about/me', (c) => {
|
|
515
|
+
* const url = c.req.url // `http://localhost:8787/about/me`
|
|
516
|
+
* ...
|
|
517
|
+
* })
|
|
518
|
+
* ```
|
|
519
|
+
*/
|
|
520
|
+
get url() {
|
|
521
|
+
return this.raw.url;
|
|
522
|
+
}
|
|
523
|
+
/**
|
|
524
|
+
* `.method()` can get the method name of the request.
|
|
525
|
+
*
|
|
526
|
+
* @see {@link https://hono.dev/docs/api/request#method}
|
|
527
|
+
*
|
|
528
|
+
* @example
|
|
529
|
+
* ```ts
|
|
530
|
+
* app.get('/about/me', (c) => {
|
|
531
|
+
* const method = c.req.method // `GET`
|
|
532
|
+
* })
|
|
533
|
+
* ```
|
|
534
|
+
*/
|
|
535
|
+
get method() {
|
|
536
|
+
return this.raw.method;
|
|
537
|
+
}
|
|
538
|
+
get [GET_MATCH_RESULT]() {
|
|
539
|
+
return this.#matchResult;
|
|
540
|
+
}
|
|
541
|
+
/**
|
|
542
|
+
* `.matchedRoutes()` can return a matched route in the handler
|
|
543
|
+
*
|
|
544
|
+
* @deprecated
|
|
545
|
+
*
|
|
546
|
+
* Use matchedRoutes helper defined in "hono/route" instead.
|
|
547
|
+
*
|
|
548
|
+
* @see {@link https://hono.dev/docs/api/request#matchedroutes}
|
|
549
|
+
*
|
|
550
|
+
* @example
|
|
551
|
+
* ```ts
|
|
552
|
+
* app.use('*', async function logger(c, next) {
|
|
553
|
+
* await next()
|
|
554
|
+
* c.req.matchedRoutes.forEach(({ handler, method, path }, i) => {
|
|
555
|
+
* const name = handler.name || (handler.length < 2 ? '[handler]' : '[middleware]')
|
|
556
|
+
* console.log(
|
|
557
|
+
* method,
|
|
558
|
+
* ' ',
|
|
559
|
+
* path,
|
|
560
|
+
* ' '.repeat(Math.max(10 - path.length, 0)),
|
|
561
|
+
* name,
|
|
562
|
+
* i === c.req.routeIndex ? '<- respond from here' : ''
|
|
563
|
+
* )
|
|
564
|
+
* })
|
|
565
|
+
* })
|
|
566
|
+
* ```
|
|
567
|
+
*/
|
|
568
|
+
get matchedRoutes() {
|
|
569
|
+
return this.#matchResult[0].map(([[, route]]) => route);
|
|
570
|
+
}
|
|
571
|
+
/**
|
|
572
|
+
* `routePath()` can retrieve the path registered within the handler
|
|
573
|
+
*
|
|
574
|
+
* @deprecated
|
|
575
|
+
*
|
|
576
|
+
* Use routePath helper defined in "hono/route" instead.
|
|
577
|
+
*
|
|
578
|
+
* @see {@link https://hono.dev/docs/api/request#routepath}
|
|
579
|
+
*
|
|
580
|
+
* @example
|
|
581
|
+
* ```ts
|
|
582
|
+
* app.get('/posts/:id', (c) => {
|
|
583
|
+
* return c.json({ path: c.req.routePath })
|
|
584
|
+
* })
|
|
585
|
+
* ```
|
|
586
|
+
*/
|
|
587
|
+
get routePath() {
|
|
588
|
+
return this.#matchResult[0].map(([[, route]]) => route)[this.routeIndex].path;
|
|
589
|
+
}
|
|
590
|
+
};
|
|
591
|
+
|
|
592
|
+
// worker/node_modules/hono/dist/utils/html.js
|
|
593
|
+
var HtmlEscapedCallbackPhase = {
|
|
594
|
+
Stringify: 1,
|
|
595
|
+
BeforeStream: 2,
|
|
596
|
+
Stream: 3
|
|
597
|
+
};
|
|
598
|
+
var raw = (value, callbacks) => {
|
|
599
|
+
const escapedString = new String(value);
|
|
600
|
+
escapedString.isEscaped = true;
|
|
601
|
+
escapedString.callbacks = callbacks;
|
|
602
|
+
return escapedString;
|
|
603
|
+
};
|
|
604
|
+
var resolveCallback = async (str, phase, preserveCallbacks, context, buffer) => {
|
|
605
|
+
if (typeof str === "object" && !(str instanceof String)) {
|
|
606
|
+
if (!(str instanceof Promise)) {
|
|
607
|
+
str = str.toString();
|
|
608
|
+
}
|
|
609
|
+
if (str instanceof Promise) {
|
|
610
|
+
str = await str;
|
|
611
|
+
}
|
|
612
|
+
}
|
|
613
|
+
const callbacks = str.callbacks;
|
|
614
|
+
if (!callbacks?.length) {
|
|
615
|
+
return Promise.resolve(str);
|
|
616
|
+
}
|
|
617
|
+
if (buffer) {
|
|
618
|
+
buffer[0] += str;
|
|
619
|
+
} else {
|
|
620
|
+
buffer = [str];
|
|
621
|
+
}
|
|
622
|
+
const resStr = Promise.all(callbacks.map((c) => c({ phase, buffer, context }))).then(
|
|
623
|
+
(res) => Promise.all(
|
|
624
|
+
res.filter(Boolean).map((str2) => resolveCallback(str2, phase, false, context, buffer))
|
|
625
|
+
).then(() => buffer[0])
|
|
626
|
+
);
|
|
627
|
+
if (preserveCallbacks) {
|
|
628
|
+
return raw(await resStr, callbacks);
|
|
629
|
+
} else {
|
|
630
|
+
return resStr;
|
|
631
|
+
}
|
|
632
|
+
};
|
|
633
|
+
|
|
634
|
+
// worker/node_modules/hono/dist/context.js
|
|
635
|
+
var TEXT_PLAIN = "text/plain; charset=UTF-8";
|
|
636
|
+
var setDefaultContentType = (contentType, headers) => {
|
|
637
|
+
return {
|
|
638
|
+
"Content-Type": contentType,
|
|
639
|
+
...headers
|
|
640
|
+
};
|
|
641
|
+
};
|
|
642
|
+
var createResponseInstance = (body, init) => new Response(body, init);
|
|
643
|
+
var Context = class {
|
|
644
|
+
#rawRequest;
|
|
645
|
+
#req;
|
|
646
|
+
/**
|
|
647
|
+
* `.env` can get bindings (environment variables, secrets, KV namespaces, D1 database, R2 bucket etc.) in Cloudflare Workers.
|
|
648
|
+
*
|
|
649
|
+
* @see {@link https://hono.dev/docs/api/context#env}
|
|
650
|
+
*
|
|
651
|
+
* @example
|
|
652
|
+
* ```ts
|
|
653
|
+
* // Environment object for Cloudflare Workers
|
|
654
|
+
* app.get('*', async c => {
|
|
655
|
+
* const counter = c.env.COUNTER
|
|
656
|
+
* })
|
|
657
|
+
* ```
|
|
658
|
+
*/
|
|
659
|
+
env = {};
|
|
660
|
+
#var;
|
|
661
|
+
finalized = false;
|
|
662
|
+
/**
|
|
663
|
+
* `.error` can get the error object from the middleware if the Handler throws an error.
|
|
664
|
+
*
|
|
665
|
+
* @see {@link https://hono.dev/docs/api/context#error}
|
|
666
|
+
*
|
|
667
|
+
* @example
|
|
668
|
+
* ```ts
|
|
669
|
+
* app.use('*', async (c, next) => {
|
|
670
|
+
* await next()
|
|
671
|
+
* if (c.error) {
|
|
672
|
+
* // do something...
|
|
673
|
+
* }
|
|
674
|
+
* })
|
|
675
|
+
* ```
|
|
676
|
+
*/
|
|
677
|
+
error;
|
|
678
|
+
#status;
|
|
679
|
+
#executionCtx;
|
|
680
|
+
#res;
|
|
681
|
+
#layout;
|
|
682
|
+
#renderer;
|
|
683
|
+
#notFoundHandler;
|
|
684
|
+
#preparedHeaders;
|
|
685
|
+
#matchResult;
|
|
686
|
+
#path;
|
|
687
|
+
/**
|
|
688
|
+
* Creates an instance of the Context class.
|
|
689
|
+
*
|
|
690
|
+
* @param req - The Request object.
|
|
691
|
+
* @param options - Optional configuration options for the context.
|
|
692
|
+
*/
|
|
693
|
+
constructor(req, options) {
|
|
694
|
+
this.#rawRequest = req;
|
|
695
|
+
if (options) {
|
|
696
|
+
this.#executionCtx = options.executionCtx;
|
|
697
|
+
this.env = options.env;
|
|
698
|
+
this.#notFoundHandler = options.notFoundHandler;
|
|
699
|
+
this.#path = options.path;
|
|
700
|
+
this.#matchResult = options.matchResult;
|
|
701
|
+
}
|
|
702
|
+
}
|
|
703
|
+
/**
|
|
704
|
+
* `.req` is the instance of {@link HonoRequest}.
|
|
705
|
+
*/
|
|
706
|
+
get req() {
|
|
707
|
+
this.#req ??= new HonoRequest(this.#rawRequest, this.#path, this.#matchResult);
|
|
708
|
+
return this.#req;
|
|
709
|
+
}
|
|
710
|
+
/**
|
|
711
|
+
* @see {@link https://hono.dev/docs/api/context#event}
|
|
712
|
+
* The FetchEvent associated with the current request.
|
|
713
|
+
*
|
|
714
|
+
* @throws Will throw an error if the context does not have a FetchEvent.
|
|
715
|
+
*/
|
|
716
|
+
get event() {
|
|
717
|
+
if (this.#executionCtx && "respondWith" in this.#executionCtx) {
|
|
718
|
+
return this.#executionCtx;
|
|
719
|
+
} else {
|
|
720
|
+
throw Error("This context has no FetchEvent");
|
|
721
|
+
}
|
|
722
|
+
}
|
|
723
|
+
/**
|
|
724
|
+
* @see {@link https://hono.dev/docs/api/context#executionctx}
|
|
725
|
+
* The ExecutionContext associated with the current request.
|
|
726
|
+
*
|
|
727
|
+
* @throws Will throw an error if the context does not have an ExecutionContext.
|
|
728
|
+
*/
|
|
729
|
+
get executionCtx() {
|
|
730
|
+
if (this.#executionCtx) {
|
|
731
|
+
return this.#executionCtx;
|
|
732
|
+
} else {
|
|
733
|
+
throw Error("This context has no ExecutionContext");
|
|
734
|
+
}
|
|
735
|
+
}
|
|
736
|
+
/**
|
|
737
|
+
* @see {@link https://hono.dev/docs/api/context#res}
|
|
738
|
+
* The Response object for the current request.
|
|
739
|
+
*/
|
|
740
|
+
get res() {
|
|
741
|
+
return this.#res ||= createResponseInstance(null, {
|
|
742
|
+
headers: this.#preparedHeaders ??= new Headers()
|
|
743
|
+
});
|
|
744
|
+
}
|
|
745
|
+
/**
|
|
746
|
+
* Sets the Response object for the current request.
|
|
747
|
+
*
|
|
748
|
+
* @param _res - The Response object to set.
|
|
749
|
+
*/
|
|
750
|
+
set res(_res) {
|
|
751
|
+
if (this.#res && _res) {
|
|
752
|
+
_res = createResponseInstance(_res.body, _res);
|
|
753
|
+
for (const [k, v] of this.#res.headers.entries()) {
|
|
754
|
+
if (k === "content-type") {
|
|
755
|
+
continue;
|
|
756
|
+
}
|
|
757
|
+
if (k === "set-cookie") {
|
|
758
|
+
const cookies = this.#res.headers.getSetCookie();
|
|
759
|
+
_res.headers.delete("set-cookie");
|
|
760
|
+
for (const cookie of cookies) {
|
|
761
|
+
_res.headers.append("set-cookie", cookie);
|
|
762
|
+
}
|
|
763
|
+
} else {
|
|
764
|
+
_res.headers.set(k, v);
|
|
765
|
+
}
|
|
766
|
+
}
|
|
767
|
+
}
|
|
768
|
+
this.#res = _res;
|
|
769
|
+
this.finalized = true;
|
|
770
|
+
}
|
|
771
|
+
/**
|
|
772
|
+
* `.render()` can create a response within a layout.
|
|
773
|
+
*
|
|
774
|
+
* @see {@link https://hono.dev/docs/api/context#render-setrenderer}
|
|
775
|
+
*
|
|
776
|
+
* @example
|
|
777
|
+
* ```ts
|
|
778
|
+
* app.get('/', (c) => {
|
|
779
|
+
* return c.render('Hello!')
|
|
780
|
+
* })
|
|
781
|
+
* ```
|
|
782
|
+
*/
|
|
783
|
+
render = (...args) => {
|
|
784
|
+
this.#renderer ??= (content) => this.html(content);
|
|
785
|
+
return this.#renderer(...args);
|
|
786
|
+
};
|
|
787
|
+
/**
|
|
788
|
+
* Sets the layout for the response.
|
|
789
|
+
*
|
|
790
|
+
* @param layout - The layout to set.
|
|
791
|
+
* @returns The layout function.
|
|
792
|
+
*/
|
|
793
|
+
setLayout = (layout) => this.#layout = layout;
|
|
794
|
+
/**
|
|
795
|
+
* Gets the current layout for the response.
|
|
796
|
+
*
|
|
797
|
+
* @returns The current layout function.
|
|
798
|
+
*/
|
|
799
|
+
getLayout = () => this.#layout;
|
|
800
|
+
/**
|
|
801
|
+
* `.setRenderer()` can set the layout in the custom middleware.
|
|
802
|
+
*
|
|
803
|
+
* @see {@link https://hono.dev/docs/api/context#render-setrenderer}
|
|
804
|
+
*
|
|
805
|
+
* @example
|
|
806
|
+
* ```tsx
|
|
807
|
+
* app.use('*', async (c, next) => {
|
|
808
|
+
* c.setRenderer((content) => {
|
|
809
|
+
* return c.html(
|
|
810
|
+
* <html>
|
|
811
|
+
* <body>
|
|
812
|
+
* <p>{content}</p>
|
|
813
|
+
* </body>
|
|
814
|
+
* </html>
|
|
815
|
+
* )
|
|
816
|
+
* })
|
|
817
|
+
* await next()
|
|
818
|
+
* })
|
|
819
|
+
* ```
|
|
820
|
+
*/
|
|
821
|
+
setRenderer = (renderer) => {
|
|
822
|
+
this.#renderer = renderer;
|
|
823
|
+
};
|
|
824
|
+
/**
|
|
825
|
+
* `.header()` can set headers.
|
|
826
|
+
*
|
|
827
|
+
* @see {@link https://hono.dev/docs/api/context#header}
|
|
828
|
+
*
|
|
829
|
+
* @example
|
|
830
|
+
* ```ts
|
|
831
|
+
* app.get('/welcome', (c) => {
|
|
832
|
+
* // Set headers
|
|
833
|
+
* c.header('X-Message', 'Hello!')
|
|
834
|
+
* c.header('Content-Type', 'text/plain')
|
|
835
|
+
*
|
|
836
|
+
* return c.body('Thank you for coming')
|
|
837
|
+
* })
|
|
838
|
+
* ```
|
|
839
|
+
*/
|
|
840
|
+
header = (name, value, options) => {
|
|
841
|
+
if (this.finalized) {
|
|
842
|
+
this.#res = createResponseInstance(this.#res.body, this.#res);
|
|
843
|
+
}
|
|
844
|
+
const headers = this.#res ? this.#res.headers : this.#preparedHeaders ??= new Headers();
|
|
845
|
+
if (value === void 0) {
|
|
846
|
+
headers.delete(name);
|
|
847
|
+
} else if (options?.append) {
|
|
848
|
+
headers.append(name, value);
|
|
849
|
+
} else {
|
|
850
|
+
headers.set(name, value);
|
|
851
|
+
}
|
|
852
|
+
};
|
|
853
|
+
status = (status) => {
|
|
854
|
+
this.#status = status;
|
|
855
|
+
};
|
|
856
|
+
/**
|
|
857
|
+
* `.set()` can set the value specified by the key.
|
|
858
|
+
*
|
|
859
|
+
* @see {@link https://hono.dev/docs/api/context#set-get}
|
|
860
|
+
*
|
|
861
|
+
* @example
|
|
862
|
+
* ```ts
|
|
863
|
+
* app.use('*', async (c, next) => {
|
|
864
|
+
* c.set('message', 'Hono is hot!!')
|
|
865
|
+
* await next()
|
|
866
|
+
* })
|
|
867
|
+
* ```
|
|
868
|
+
*/
|
|
869
|
+
set = (key, value) => {
|
|
870
|
+
this.#var ??= /* @__PURE__ */ new Map();
|
|
871
|
+
this.#var.set(key, value);
|
|
872
|
+
};
|
|
873
|
+
/**
|
|
874
|
+
* `.get()` can use the value specified by the key.
|
|
875
|
+
*
|
|
876
|
+
* @see {@link https://hono.dev/docs/api/context#set-get}
|
|
877
|
+
*
|
|
878
|
+
* @example
|
|
879
|
+
* ```ts
|
|
880
|
+
* app.get('/', (c) => {
|
|
881
|
+
* const message = c.get('message')
|
|
882
|
+
* return c.text(`The message is "${message}"`)
|
|
883
|
+
* })
|
|
884
|
+
* ```
|
|
885
|
+
*/
|
|
886
|
+
get = (key) => {
|
|
887
|
+
return this.#var ? this.#var.get(key) : void 0;
|
|
888
|
+
};
|
|
889
|
+
/**
|
|
890
|
+
* `.var` can access the value of a variable.
|
|
891
|
+
*
|
|
892
|
+
* @see {@link https://hono.dev/docs/api/context#var}
|
|
893
|
+
*
|
|
894
|
+
* @example
|
|
895
|
+
* ```ts
|
|
896
|
+
* const result = c.var.client.oneMethod()
|
|
897
|
+
* ```
|
|
898
|
+
*/
|
|
899
|
+
// c.var.propName is a read-only
|
|
900
|
+
get var() {
|
|
901
|
+
if (!this.#var) {
|
|
902
|
+
return {};
|
|
903
|
+
}
|
|
904
|
+
return Object.fromEntries(this.#var);
|
|
905
|
+
}
|
|
906
|
+
#newResponse(data, arg, headers) {
|
|
907
|
+
const responseHeaders = this.#res ? new Headers(this.#res.headers) : this.#preparedHeaders ?? new Headers();
|
|
908
|
+
if (typeof arg === "object" && "headers" in arg) {
|
|
909
|
+
const argHeaders = arg.headers instanceof Headers ? arg.headers : new Headers(arg.headers);
|
|
910
|
+
for (const [key, value] of argHeaders) {
|
|
911
|
+
if (key.toLowerCase() === "set-cookie") {
|
|
912
|
+
responseHeaders.append(key, value);
|
|
913
|
+
} else {
|
|
914
|
+
responseHeaders.set(key, value);
|
|
915
|
+
}
|
|
916
|
+
}
|
|
917
|
+
}
|
|
918
|
+
if (headers) {
|
|
919
|
+
for (const [k, v] of Object.entries(headers)) {
|
|
920
|
+
if (typeof v === "string") {
|
|
921
|
+
responseHeaders.set(k, v);
|
|
922
|
+
} else {
|
|
923
|
+
responseHeaders.delete(k);
|
|
924
|
+
for (const v2 of v) {
|
|
925
|
+
responseHeaders.append(k, v2);
|
|
926
|
+
}
|
|
927
|
+
}
|
|
928
|
+
}
|
|
929
|
+
}
|
|
930
|
+
const status = typeof arg === "number" ? arg : arg?.status ?? this.#status;
|
|
931
|
+
return createResponseInstance(data, { status, headers: responseHeaders });
|
|
932
|
+
}
|
|
933
|
+
newResponse = (...args) => this.#newResponse(...args);
|
|
934
|
+
/**
|
|
935
|
+
* `.body()` can return the HTTP response.
|
|
936
|
+
* You can set headers with `.header()` and set HTTP status code with `.status`.
|
|
937
|
+
* This can also be set in `.text()`, `.json()` and so on.
|
|
938
|
+
*
|
|
939
|
+
* @see {@link https://hono.dev/docs/api/context#body}
|
|
940
|
+
*
|
|
941
|
+
* @example
|
|
942
|
+
* ```ts
|
|
943
|
+
* app.get('/welcome', (c) => {
|
|
944
|
+
* // Set headers
|
|
945
|
+
* c.header('X-Message', 'Hello!')
|
|
946
|
+
* c.header('Content-Type', 'text/plain')
|
|
947
|
+
* // Set HTTP status code
|
|
948
|
+
* c.status(201)
|
|
949
|
+
*
|
|
950
|
+
* // Return the response body
|
|
951
|
+
* return c.body('Thank you for coming')
|
|
952
|
+
* })
|
|
953
|
+
* ```
|
|
954
|
+
*/
|
|
955
|
+
body = (data, arg, headers) => this.#newResponse(data, arg, headers);
|
|
956
|
+
/**
|
|
957
|
+
* `.text()` can render text as `Content-Type:text/plain`.
|
|
958
|
+
*
|
|
959
|
+
* @see {@link https://hono.dev/docs/api/context#text}
|
|
960
|
+
*
|
|
961
|
+
* @example
|
|
962
|
+
* ```ts
|
|
963
|
+
* app.get('/say', (c) => {
|
|
964
|
+
* return c.text('Hello!')
|
|
965
|
+
* })
|
|
966
|
+
* ```
|
|
967
|
+
*/
|
|
968
|
+
text = (text, arg, headers) => {
|
|
969
|
+
return !this.#preparedHeaders && !this.#status && !arg && !headers && !this.finalized ? new Response(text) : this.#newResponse(
|
|
970
|
+
text,
|
|
971
|
+
arg,
|
|
972
|
+
setDefaultContentType(TEXT_PLAIN, headers)
|
|
973
|
+
);
|
|
974
|
+
};
|
|
975
|
+
/**
|
|
976
|
+
* `.json()` can render JSON as `Content-Type:application/json`.
|
|
977
|
+
*
|
|
978
|
+
* @see {@link https://hono.dev/docs/api/context#json}
|
|
979
|
+
*
|
|
980
|
+
* @example
|
|
981
|
+
* ```ts
|
|
982
|
+
* app.get('/api', (c) => {
|
|
983
|
+
* return c.json({ message: 'Hello!' })
|
|
984
|
+
* })
|
|
985
|
+
* ```
|
|
986
|
+
*/
|
|
987
|
+
json = (object, arg, headers) => {
|
|
988
|
+
return this.#newResponse(
|
|
989
|
+
JSON.stringify(object),
|
|
990
|
+
arg,
|
|
991
|
+
setDefaultContentType("application/json", headers)
|
|
992
|
+
);
|
|
993
|
+
};
|
|
994
|
+
html = (html, arg, headers) => {
|
|
995
|
+
const res = (html2) => this.#newResponse(html2, arg, setDefaultContentType("text/html; charset=UTF-8", headers));
|
|
996
|
+
return typeof html === "object" ? resolveCallback(html, HtmlEscapedCallbackPhase.Stringify, false, {}).then(res) : res(html);
|
|
997
|
+
};
|
|
998
|
+
/**
|
|
999
|
+
* `.redirect()` can Redirect, default status code is 302.
|
|
1000
|
+
*
|
|
1001
|
+
* @see {@link https://hono.dev/docs/api/context#redirect}
|
|
1002
|
+
*
|
|
1003
|
+
* @example
|
|
1004
|
+
* ```ts
|
|
1005
|
+
* app.get('/redirect', (c) => {
|
|
1006
|
+
* return c.redirect('/')
|
|
1007
|
+
* })
|
|
1008
|
+
* app.get('/redirect-permanently', (c) => {
|
|
1009
|
+
* return c.redirect('/', 301)
|
|
1010
|
+
* })
|
|
1011
|
+
* ```
|
|
1012
|
+
*/
|
|
1013
|
+
redirect = (location, status) => {
|
|
1014
|
+
const locationString = String(location);
|
|
1015
|
+
this.header(
|
|
1016
|
+
"Location",
|
|
1017
|
+
// Multibyes should be encoded
|
|
1018
|
+
// eslint-disable-next-line no-control-regex
|
|
1019
|
+
!/[^\x00-\xFF]/.test(locationString) ? locationString : encodeURI(locationString)
|
|
1020
|
+
);
|
|
1021
|
+
return this.newResponse(null, status ?? 302);
|
|
1022
|
+
};
|
|
1023
|
+
/**
|
|
1024
|
+
* `.notFound()` can return the Not Found Response.
|
|
1025
|
+
*
|
|
1026
|
+
* @see {@link https://hono.dev/docs/api/context#notfound}
|
|
1027
|
+
*
|
|
1028
|
+
* @example
|
|
1029
|
+
* ```ts
|
|
1030
|
+
* app.get('/notfound', (c) => {
|
|
1031
|
+
* return c.notFound()
|
|
1032
|
+
* })
|
|
1033
|
+
* ```
|
|
1034
|
+
*/
|
|
1035
|
+
notFound = () => {
|
|
1036
|
+
this.#notFoundHandler ??= () => createResponseInstance();
|
|
1037
|
+
return this.#notFoundHandler(this);
|
|
1038
|
+
};
|
|
1039
|
+
};
|
|
1040
|
+
|
|
1041
|
+
// worker/node_modules/hono/dist/router.js
|
|
1042
|
+
var METHOD_NAME_ALL = "ALL";
|
|
1043
|
+
var METHOD_NAME_ALL_LOWERCASE = "all";
|
|
1044
|
+
var METHODS = ["get", "post", "put", "delete", "options", "patch"];
|
|
1045
|
+
var MESSAGE_MATCHER_IS_ALREADY_BUILT = "Can not add a route since the matcher is already built.";
|
|
1046
|
+
var UnsupportedPathError = class extends Error {
|
|
1047
|
+
};
|
|
1048
|
+
|
|
1049
|
+
// worker/node_modules/hono/dist/utils/constants.js
|
|
1050
|
+
var COMPOSED_HANDLER = "__COMPOSED_HANDLER";
|
|
1051
|
+
|
|
1052
|
+
// worker/node_modules/hono/dist/hono-base.js
|
|
1053
|
+
var notFoundHandler = (c) => {
|
|
1054
|
+
return c.text("404 Not Found", 404);
|
|
1055
|
+
};
|
|
1056
|
+
var errorHandler = (err, c) => {
|
|
1057
|
+
if ("getResponse" in err) {
|
|
1058
|
+
const res = err.getResponse();
|
|
1059
|
+
return c.newResponse(res.body, res);
|
|
1060
|
+
}
|
|
1061
|
+
console.error(err);
|
|
1062
|
+
return c.text("Internal Server Error", 500);
|
|
1063
|
+
};
|
|
1064
|
+
var Hono = class _Hono {
|
|
1065
|
+
get;
|
|
1066
|
+
post;
|
|
1067
|
+
put;
|
|
1068
|
+
delete;
|
|
1069
|
+
options;
|
|
1070
|
+
patch;
|
|
1071
|
+
all;
|
|
1072
|
+
on;
|
|
1073
|
+
use;
|
|
1074
|
+
/*
|
|
1075
|
+
This class is like an abstract class and does not have a router.
|
|
1076
|
+
To use it, inherit the class and implement router in the constructor.
|
|
1077
|
+
*/
|
|
1078
|
+
router;
|
|
1079
|
+
getPath;
|
|
1080
|
+
// Cannot use `#` because it requires visibility at JavaScript runtime.
|
|
1081
|
+
_basePath = "/";
|
|
1082
|
+
#path = "/";
|
|
1083
|
+
routes = [];
|
|
1084
|
+
constructor(options = {}) {
|
|
1085
|
+
const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE];
|
|
1086
|
+
allMethods.forEach((method) => {
|
|
1087
|
+
this[method] = (args1, ...args) => {
|
|
1088
|
+
if (typeof args1 === "string") {
|
|
1089
|
+
this.#path = args1;
|
|
1090
|
+
} else {
|
|
1091
|
+
this.#addRoute(method, this.#path, args1);
|
|
1092
|
+
}
|
|
1093
|
+
args.forEach((handler) => {
|
|
1094
|
+
this.#addRoute(method, this.#path, handler);
|
|
1095
|
+
});
|
|
1096
|
+
return this;
|
|
1097
|
+
};
|
|
1098
|
+
});
|
|
1099
|
+
this.on = (method, path, ...handlers) => {
|
|
1100
|
+
for (const p of [path].flat()) {
|
|
1101
|
+
this.#path = p;
|
|
1102
|
+
for (const m of [method].flat()) {
|
|
1103
|
+
handlers.map((handler) => {
|
|
1104
|
+
this.#addRoute(m.toUpperCase(), this.#path, handler);
|
|
1105
|
+
});
|
|
1106
|
+
}
|
|
1107
|
+
}
|
|
1108
|
+
return this;
|
|
1109
|
+
};
|
|
1110
|
+
this.use = (arg1, ...handlers) => {
|
|
1111
|
+
if (typeof arg1 === "string") {
|
|
1112
|
+
this.#path = arg1;
|
|
1113
|
+
} else {
|
|
1114
|
+
this.#path = "*";
|
|
1115
|
+
handlers.unshift(arg1);
|
|
1116
|
+
}
|
|
1117
|
+
handlers.forEach((handler) => {
|
|
1118
|
+
this.#addRoute(METHOD_NAME_ALL, this.#path, handler);
|
|
1119
|
+
});
|
|
1120
|
+
return this;
|
|
1121
|
+
};
|
|
1122
|
+
const { strict, ...optionsWithoutStrict } = options;
|
|
1123
|
+
Object.assign(this, optionsWithoutStrict);
|
|
1124
|
+
this.getPath = strict ?? true ? options.getPath ?? getPath : getPathNoStrict;
|
|
1125
|
+
}
|
|
1126
|
+
#clone() {
|
|
1127
|
+
const clone = new _Hono({
|
|
1128
|
+
router: this.router,
|
|
1129
|
+
getPath: this.getPath
|
|
1130
|
+
});
|
|
1131
|
+
clone.errorHandler = this.errorHandler;
|
|
1132
|
+
clone.#notFoundHandler = this.#notFoundHandler;
|
|
1133
|
+
clone.routes = this.routes;
|
|
1134
|
+
return clone;
|
|
1135
|
+
}
|
|
1136
|
+
#notFoundHandler = notFoundHandler;
|
|
1137
|
+
// Cannot use `#` because it requires visibility at JavaScript runtime.
|
|
1138
|
+
errorHandler = errorHandler;
|
|
1139
|
+
/**
|
|
1140
|
+
* `.route()` allows grouping other Hono instance in routes.
|
|
1141
|
+
*
|
|
1142
|
+
* @see {@link https://hono.dev/docs/api/routing#grouping}
|
|
1143
|
+
*
|
|
1144
|
+
* @param {string} path - base Path
|
|
1145
|
+
* @param {Hono} app - other Hono instance
|
|
1146
|
+
* @returns {Hono} routed Hono instance
|
|
1147
|
+
*
|
|
1148
|
+
* @example
|
|
1149
|
+
* ```ts
|
|
1150
|
+
* const app = new Hono()
|
|
1151
|
+
* const app2 = new Hono()
|
|
1152
|
+
*
|
|
1153
|
+
* app2.get("/user", (c) => c.text("user"))
|
|
1154
|
+
* app.route("/api", app2) // GET /api/user
|
|
1155
|
+
* ```
|
|
1156
|
+
*/
|
|
1157
|
+
route(path, app2) {
|
|
1158
|
+
const subApp = this.basePath(path);
|
|
1159
|
+
app2.routes.map((r) => {
|
|
1160
|
+
let handler;
|
|
1161
|
+
if (app2.errorHandler === errorHandler) {
|
|
1162
|
+
handler = r.handler;
|
|
1163
|
+
} else {
|
|
1164
|
+
handler = async (c, next) => (await compose([], app2.errorHandler)(c, () => r.handler(c, next))).res;
|
|
1165
|
+
handler[COMPOSED_HANDLER] = r.handler;
|
|
1166
|
+
}
|
|
1167
|
+
subApp.#addRoute(r.method, r.path, handler);
|
|
1168
|
+
});
|
|
1169
|
+
return this;
|
|
1170
|
+
}
|
|
1171
|
+
/**
|
|
1172
|
+
* `.basePath()` allows base paths to be specified.
|
|
1173
|
+
*
|
|
1174
|
+
* @see {@link https://hono.dev/docs/api/routing#base-path}
|
|
1175
|
+
*
|
|
1176
|
+
* @param {string} path - base Path
|
|
1177
|
+
* @returns {Hono} changed Hono instance
|
|
1178
|
+
*
|
|
1179
|
+
* @example
|
|
1180
|
+
* ```ts
|
|
1181
|
+
* const api = new Hono().basePath('/api')
|
|
1182
|
+
* ```
|
|
1183
|
+
*/
|
|
1184
|
+
basePath(path) {
|
|
1185
|
+
const subApp = this.#clone();
|
|
1186
|
+
subApp._basePath = mergePath(this._basePath, path);
|
|
1187
|
+
return subApp;
|
|
1188
|
+
}
|
|
1189
|
+
/**
|
|
1190
|
+
* `.onError()` handles an error and returns a customized Response.
|
|
1191
|
+
*
|
|
1192
|
+
* @see {@link https://hono.dev/docs/api/hono#error-handling}
|
|
1193
|
+
*
|
|
1194
|
+
* @param {ErrorHandler} handler - request Handler for error
|
|
1195
|
+
* @returns {Hono} changed Hono instance
|
|
1196
|
+
*
|
|
1197
|
+
* @example
|
|
1198
|
+
* ```ts
|
|
1199
|
+
* app.onError((err, c) => {
|
|
1200
|
+
* console.error(`${err}`)
|
|
1201
|
+
* return c.text('Custom Error Message', 500)
|
|
1202
|
+
* })
|
|
1203
|
+
* ```
|
|
1204
|
+
*/
|
|
1205
|
+
onError = (handler) => {
|
|
1206
|
+
this.errorHandler = handler;
|
|
1207
|
+
return this;
|
|
1208
|
+
};
|
|
1209
|
+
/**
|
|
1210
|
+
* `.notFound()` allows you to customize a Not Found Response.
|
|
1211
|
+
*
|
|
1212
|
+
* @see {@link https://hono.dev/docs/api/hono#not-found}
|
|
1213
|
+
*
|
|
1214
|
+
* @param {NotFoundHandler} handler - request handler for not-found
|
|
1215
|
+
* @returns {Hono} changed Hono instance
|
|
1216
|
+
*
|
|
1217
|
+
* @example
|
|
1218
|
+
* ```ts
|
|
1219
|
+
* app.notFound((c) => {
|
|
1220
|
+
* return c.text('Custom 404 Message', 404)
|
|
1221
|
+
* })
|
|
1222
|
+
* ```
|
|
1223
|
+
*/
|
|
1224
|
+
notFound = (handler) => {
|
|
1225
|
+
this.#notFoundHandler = handler;
|
|
1226
|
+
return this;
|
|
1227
|
+
};
|
|
1228
|
+
/**
|
|
1229
|
+
* `.mount()` allows you to mount applications built with other frameworks into your Hono application.
|
|
1230
|
+
*
|
|
1231
|
+
* @see {@link https://hono.dev/docs/api/hono#mount}
|
|
1232
|
+
*
|
|
1233
|
+
* @param {string} path - base Path
|
|
1234
|
+
* @param {Function} applicationHandler - other Request Handler
|
|
1235
|
+
* @param {MountOptions} [options] - options of `.mount()`
|
|
1236
|
+
* @returns {Hono} mounted Hono instance
|
|
1237
|
+
*
|
|
1238
|
+
* @example
|
|
1239
|
+
* ```ts
|
|
1240
|
+
* import { Router as IttyRouter } from 'itty-router'
|
|
1241
|
+
* import { Hono } from 'hono'
|
|
1242
|
+
* // Create itty-router application
|
|
1243
|
+
* const ittyRouter = IttyRouter()
|
|
1244
|
+
* // GET /itty-router/hello
|
|
1245
|
+
* ittyRouter.get('/hello', () => new Response('Hello from itty-router'))
|
|
1246
|
+
*
|
|
1247
|
+
* const app = new Hono()
|
|
1248
|
+
* app.mount('/itty-router', ittyRouter.handle)
|
|
1249
|
+
* ```
|
|
1250
|
+
*
|
|
1251
|
+
* @example
|
|
1252
|
+
* ```ts
|
|
1253
|
+
* const app = new Hono()
|
|
1254
|
+
* // Send the request to another application without modification.
|
|
1255
|
+
* app.mount('/app', anotherApp, {
|
|
1256
|
+
* replaceRequest: (req) => req,
|
|
1257
|
+
* })
|
|
1258
|
+
* ```
|
|
1259
|
+
*/
|
|
1260
|
+
mount(path, applicationHandler, options) {
|
|
1261
|
+
let replaceRequest;
|
|
1262
|
+
let optionHandler;
|
|
1263
|
+
if (options) {
|
|
1264
|
+
if (typeof options === "function") {
|
|
1265
|
+
optionHandler = options;
|
|
1266
|
+
} else {
|
|
1267
|
+
optionHandler = options.optionHandler;
|
|
1268
|
+
if (options.replaceRequest === false) {
|
|
1269
|
+
replaceRequest = (request) => request;
|
|
1270
|
+
} else {
|
|
1271
|
+
replaceRequest = options.replaceRequest;
|
|
1272
|
+
}
|
|
1273
|
+
}
|
|
1274
|
+
}
|
|
1275
|
+
const getOptions = optionHandler ? (c) => {
|
|
1276
|
+
const options2 = optionHandler(c);
|
|
1277
|
+
return Array.isArray(options2) ? options2 : [options2];
|
|
1278
|
+
} : (c) => {
|
|
1279
|
+
let executionContext = void 0;
|
|
1280
|
+
try {
|
|
1281
|
+
executionContext = c.executionCtx;
|
|
1282
|
+
} catch {
|
|
1283
|
+
}
|
|
1284
|
+
return [c.env, executionContext];
|
|
1285
|
+
};
|
|
1286
|
+
replaceRequest ||= (() => {
|
|
1287
|
+
const mergedPath = mergePath(this._basePath, path);
|
|
1288
|
+
const pathPrefixLength = mergedPath === "/" ? 0 : mergedPath.length;
|
|
1289
|
+
return (request) => {
|
|
1290
|
+
const url = new URL(request.url);
|
|
1291
|
+
url.pathname = url.pathname.slice(pathPrefixLength) || "/";
|
|
1292
|
+
return new Request(url, request);
|
|
1293
|
+
};
|
|
1294
|
+
})();
|
|
1295
|
+
const handler = async (c, next) => {
|
|
1296
|
+
const res = await applicationHandler(replaceRequest(c.req.raw), ...getOptions(c));
|
|
1297
|
+
if (res) {
|
|
1298
|
+
return res;
|
|
1299
|
+
}
|
|
1300
|
+
await next();
|
|
1301
|
+
};
|
|
1302
|
+
this.#addRoute(METHOD_NAME_ALL, mergePath(path, "*"), handler);
|
|
1303
|
+
return this;
|
|
1304
|
+
}
|
|
1305
|
+
#addRoute(method, path, handler) {
|
|
1306
|
+
method = method.toUpperCase();
|
|
1307
|
+
path = mergePath(this._basePath, path);
|
|
1308
|
+
const r = { basePath: this._basePath, path, method, handler };
|
|
1309
|
+
this.router.add(method, path, [handler, r]);
|
|
1310
|
+
this.routes.push(r);
|
|
1311
|
+
}
|
|
1312
|
+
#handleError(err, c) {
|
|
1313
|
+
if (err instanceof Error) {
|
|
1314
|
+
return this.errorHandler(err, c);
|
|
1315
|
+
}
|
|
1316
|
+
throw err;
|
|
1317
|
+
}
|
|
1318
|
+
#dispatch(request, executionCtx, env, method) {
|
|
1319
|
+
if (method === "HEAD") {
|
|
1320
|
+
return (async () => new Response(null, await this.#dispatch(request, executionCtx, env, "GET")))();
|
|
1321
|
+
}
|
|
1322
|
+
const path = this.getPath(request, { env });
|
|
1323
|
+
const matchResult = this.router.match(method, path);
|
|
1324
|
+
const c = new Context(request, {
|
|
1325
|
+
path,
|
|
1326
|
+
matchResult,
|
|
1327
|
+
env,
|
|
1328
|
+
executionCtx,
|
|
1329
|
+
notFoundHandler: this.#notFoundHandler
|
|
1330
|
+
});
|
|
1331
|
+
if (matchResult[0].length === 1) {
|
|
1332
|
+
let res;
|
|
1333
|
+
try {
|
|
1334
|
+
res = matchResult[0][0][0][0](c, async () => {
|
|
1335
|
+
c.res = await this.#notFoundHandler(c);
|
|
1336
|
+
});
|
|
1337
|
+
} catch (err) {
|
|
1338
|
+
return this.#handleError(err, c);
|
|
1339
|
+
}
|
|
1340
|
+
return res instanceof Promise ? res.then(
|
|
1341
|
+
(resolved) => resolved || (c.finalized ? c.res : this.#notFoundHandler(c))
|
|
1342
|
+
).catch((err) => this.#handleError(err, c)) : res ?? this.#notFoundHandler(c);
|
|
1343
|
+
}
|
|
1344
|
+
const composed = compose(matchResult[0], this.errorHandler, this.#notFoundHandler);
|
|
1345
|
+
return (async () => {
|
|
1346
|
+
try {
|
|
1347
|
+
const context = await composed(c);
|
|
1348
|
+
if (!context.finalized) {
|
|
1349
|
+
throw new Error(
|
|
1350
|
+
"Context is not finalized. Did you forget to return a Response object or `await next()`?"
|
|
1351
|
+
);
|
|
1352
|
+
}
|
|
1353
|
+
return context.res;
|
|
1354
|
+
} catch (err) {
|
|
1355
|
+
return this.#handleError(err, c);
|
|
1356
|
+
}
|
|
1357
|
+
})();
|
|
1358
|
+
}
|
|
1359
|
+
/**
|
|
1360
|
+
* `.fetch()` will be entry point of your app.
|
|
1361
|
+
*
|
|
1362
|
+
* @see {@link https://hono.dev/docs/api/hono#fetch}
|
|
1363
|
+
*
|
|
1364
|
+
* @param {Request} request - request Object of request
|
|
1365
|
+
* @param {Env} Env - env Object
|
|
1366
|
+
* @param {ExecutionContext} - context of execution
|
|
1367
|
+
* @returns {Response | Promise<Response>} response of request
|
|
1368
|
+
*
|
|
1369
|
+
*/
|
|
1370
|
+
fetch = (request, ...rest) => {
|
|
1371
|
+
return this.#dispatch(request, rest[1], rest[0], request.method);
|
|
1372
|
+
};
|
|
1373
|
+
/**
|
|
1374
|
+
* `.request()` is a useful method for testing.
|
|
1375
|
+
* You can pass a URL or pathname to send a GET request.
|
|
1376
|
+
* app will return a Response object.
|
|
1377
|
+
* ```ts
|
|
1378
|
+
* test('GET /hello is ok', async () => {
|
|
1379
|
+
* const res = await app.request('/hello')
|
|
1380
|
+
* expect(res.status).toBe(200)
|
|
1381
|
+
* })
|
|
1382
|
+
* ```
|
|
1383
|
+
* @see https://hono.dev/docs/api/hono#request
|
|
1384
|
+
*/
|
|
1385
|
+
request = (input, requestInit, Env, executionCtx) => {
|
|
1386
|
+
if (input instanceof Request) {
|
|
1387
|
+
return this.fetch(requestInit ? new Request(input, requestInit) : input, Env, executionCtx);
|
|
1388
|
+
}
|
|
1389
|
+
input = input.toString();
|
|
1390
|
+
return this.fetch(
|
|
1391
|
+
new Request(
|
|
1392
|
+
/^https?:\/\//.test(input) ? input : `http://localhost${mergePath("/", input)}`,
|
|
1393
|
+
requestInit
|
|
1394
|
+
),
|
|
1395
|
+
Env,
|
|
1396
|
+
executionCtx
|
|
1397
|
+
);
|
|
1398
|
+
};
|
|
1399
|
+
/**
|
|
1400
|
+
* `.fire()` automatically adds a global fetch event listener.
|
|
1401
|
+
* This can be useful for environments that adhere to the Service Worker API, such as non-ES module Cloudflare Workers.
|
|
1402
|
+
* @deprecated
|
|
1403
|
+
* Use `fire` from `hono/service-worker` instead.
|
|
1404
|
+
* ```ts
|
|
1405
|
+
* import { Hono } from 'hono'
|
|
1406
|
+
* import { fire } from 'hono/service-worker'
|
|
1407
|
+
*
|
|
1408
|
+
* const app = new Hono()
|
|
1409
|
+
* // ...
|
|
1410
|
+
* fire(app)
|
|
1411
|
+
* ```
|
|
1412
|
+
* @see https://hono.dev/docs/api/hono#fire
|
|
1413
|
+
* @see https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API
|
|
1414
|
+
* @see https://developers.cloudflare.com/workers/reference/migrate-to-module-workers/
|
|
1415
|
+
*/
|
|
1416
|
+
fire = () => {
|
|
1417
|
+
addEventListener("fetch", (event) => {
|
|
1418
|
+
event.respondWith(this.#dispatch(event.request, event, void 0, event.request.method));
|
|
1419
|
+
});
|
|
1420
|
+
};
|
|
1421
|
+
};
|
|
1422
|
+
|
|
1423
|
+
// worker/node_modules/hono/dist/router/reg-exp-router/matcher.js
|
|
1424
|
+
var emptyParam = [];
|
|
1425
|
+
function match(method, path) {
|
|
1426
|
+
const matchers = this.buildAllMatchers();
|
|
1427
|
+
const match2 = ((method2, path2) => {
|
|
1428
|
+
const matcher = matchers[method2] || matchers[METHOD_NAME_ALL];
|
|
1429
|
+
const staticMatch = matcher[2][path2];
|
|
1430
|
+
if (staticMatch) {
|
|
1431
|
+
return staticMatch;
|
|
1432
|
+
}
|
|
1433
|
+
const match3 = path2.match(matcher[0]);
|
|
1434
|
+
if (!match3) {
|
|
1435
|
+
return [[], emptyParam];
|
|
1436
|
+
}
|
|
1437
|
+
const index = match3.indexOf("", 1);
|
|
1438
|
+
return [matcher[1][index], match3];
|
|
1439
|
+
});
|
|
1440
|
+
this.match = match2;
|
|
1441
|
+
return match2(method, path);
|
|
1442
|
+
}
|
|
1443
|
+
|
|
1444
|
+
// worker/node_modules/hono/dist/router/reg-exp-router/node.js
|
|
1445
|
+
var LABEL_REG_EXP_STR = "[^/]+";
|
|
1446
|
+
var ONLY_WILDCARD_REG_EXP_STR = ".*";
|
|
1447
|
+
var TAIL_WILDCARD_REG_EXP_STR = "(?:|/.*)";
|
|
1448
|
+
var PATH_ERROR = /* @__PURE__ */ Symbol();
|
|
1449
|
+
var regExpMetaChars = new Set(".\\+*[^]$()");
|
|
1450
|
+
function compareKey(a, b) {
|
|
1451
|
+
if (a.length === 1) {
|
|
1452
|
+
return b.length === 1 ? a < b ? -1 : 1 : -1;
|
|
1453
|
+
}
|
|
1454
|
+
if (b.length === 1) {
|
|
1455
|
+
return 1;
|
|
1456
|
+
}
|
|
1457
|
+
if (a === ONLY_WILDCARD_REG_EXP_STR || a === TAIL_WILDCARD_REG_EXP_STR) {
|
|
1458
|
+
return 1;
|
|
1459
|
+
} else if (b === ONLY_WILDCARD_REG_EXP_STR || b === TAIL_WILDCARD_REG_EXP_STR) {
|
|
1460
|
+
return -1;
|
|
1461
|
+
}
|
|
1462
|
+
if (a === LABEL_REG_EXP_STR) {
|
|
1463
|
+
return 1;
|
|
1464
|
+
} else if (b === LABEL_REG_EXP_STR) {
|
|
1465
|
+
return -1;
|
|
1466
|
+
}
|
|
1467
|
+
return a.length === b.length ? a < b ? -1 : 1 : b.length - a.length;
|
|
1468
|
+
}
|
|
1469
|
+
var Node = class _Node {
|
|
1470
|
+
#index;
|
|
1471
|
+
#varIndex;
|
|
1472
|
+
#children = /* @__PURE__ */ Object.create(null);
|
|
1473
|
+
insert(tokens, index, paramMap, context, pathErrorCheckOnly) {
|
|
1474
|
+
if (tokens.length === 0) {
|
|
1475
|
+
if (this.#index !== void 0) {
|
|
1476
|
+
throw PATH_ERROR;
|
|
1477
|
+
}
|
|
1478
|
+
if (pathErrorCheckOnly) {
|
|
1479
|
+
return;
|
|
1480
|
+
}
|
|
1481
|
+
this.#index = index;
|
|
1482
|
+
return;
|
|
1483
|
+
}
|
|
1484
|
+
const [token, ...restTokens] = tokens;
|
|
1485
|
+
const pattern = token === "*" ? restTokens.length === 0 ? ["", "", ONLY_WILDCARD_REG_EXP_STR] : ["", "", LABEL_REG_EXP_STR] : token === "/*" ? ["", "", TAIL_WILDCARD_REG_EXP_STR] : token.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
|
|
1486
|
+
let node;
|
|
1487
|
+
if (pattern) {
|
|
1488
|
+
const name = pattern[1];
|
|
1489
|
+
let regexpStr = pattern[2] || LABEL_REG_EXP_STR;
|
|
1490
|
+
if (name && pattern[2]) {
|
|
1491
|
+
if (regexpStr === ".*") {
|
|
1492
|
+
throw PATH_ERROR;
|
|
1493
|
+
}
|
|
1494
|
+
regexpStr = regexpStr.replace(/^\((?!\?:)(?=[^)]+\)$)/, "(?:");
|
|
1495
|
+
if (/\((?!\?:)/.test(regexpStr)) {
|
|
1496
|
+
throw PATH_ERROR;
|
|
1497
|
+
}
|
|
1498
|
+
}
|
|
1499
|
+
node = this.#children[regexpStr];
|
|
1500
|
+
if (!node) {
|
|
1501
|
+
if (Object.keys(this.#children).some(
|
|
1502
|
+
(k) => k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR
|
|
1503
|
+
)) {
|
|
1504
|
+
throw PATH_ERROR;
|
|
1505
|
+
}
|
|
1506
|
+
if (pathErrorCheckOnly) {
|
|
1507
|
+
return;
|
|
1508
|
+
}
|
|
1509
|
+
node = this.#children[regexpStr] = new _Node();
|
|
1510
|
+
if (name !== "") {
|
|
1511
|
+
node.#varIndex = context.varIndex++;
|
|
1512
|
+
}
|
|
1513
|
+
}
|
|
1514
|
+
if (!pathErrorCheckOnly && name !== "") {
|
|
1515
|
+
paramMap.push([name, node.#varIndex]);
|
|
1516
|
+
}
|
|
1517
|
+
} else {
|
|
1518
|
+
node = this.#children[token];
|
|
1519
|
+
if (!node) {
|
|
1520
|
+
if (Object.keys(this.#children).some(
|
|
1521
|
+
(k) => k.length > 1 && k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR
|
|
1522
|
+
)) {
|
|
1523
|
+
throw PATH_ERROR;
|
|
1524
|
+
}
|
|
1525
|
+
if (pathErrorCheckOnly) {
|
|
1526
|
+
return;
|
|
1527
|
+
}
|
|
1528
|
+
node = this.#children[token] = new _Node();
|
|
1529
|
+
}
|
|
1530
|
+
}
|
|
1531
|
+
node.insert(restTokens, index, paramMap, context, pathErrorCheckOnly);
|
|
1532
|
+
}
|
|
1533
|
+
buildRegExpStr() {
|
|
1534
|
+
const childKeys = Object.keys(this.#children).sort(compareKey);
|
|
1535
|
+
const strList = childKeys.map((k) => {
|
|
1536
|
+
const c = this.#children[k];
|
|
1537
|
+
return (typeof c.#varIndex === "number" ? `(${k})@${c.#varIndex}` : regExpMetaChars.has(k) ? `\\${k}` : k) + c.buildRegExpStr();
|
|
1538
|
+
});
|
|
1539
|
+
if (typeof this.#index === "number") {
|
|
1540
|
+
strList.unshift(`#${this.#index}`);
|
|
1541
|
+
}
|
|
1542
|
+
if (strList.length === 0) {
|
|
1543
|
+
return "";
|
|
1544
|
+
}
|
|
1545
|
+
if (strList.length === 1) {
|
|
1546
|
+
return strList[0];
|
|
1547
|
+
}
|
|
1548
|
+
return "(?:" + strList.join("|") + ")";
|
|
1549
|
+
}
|
|
1550
|
+
};
|
|
1551
|
+
|
|
1552
|
+
// worker/node_modules/hono/dist/router/reg-exp-router/trie.js
|
|
1553
|
+
var Trie = class {
|
|
1554
|
+
#context = { varIndex: 0 };
|
|
1555
|
+
#root = new Node();
|
|
1556
|
+
insert(path, index, pathErrorCheckOnly) {
|
|
1557
|
+
const paramAssoc = [];
|
|
1558
|
+
const groups = [];
|
|
1559
|
+
for (let i = 0; ; ) {
|
|
1560
|
+
let replaced = false;
|
|
1561
|
+
path = path.replace(/\{[^}]+\}/g, (m) => {
|
|
1562
|
+
const mark = `@\\${i}`;
|
|
1563
|
+
groups[i] = [mark, m];
|
|
1564
|
+
i++;
|
|
1565
|
+
replaced = true;
|
|
1566
|
+
return mark;
|
|
1567
|
+
});
|
|
1568
|
+
if (!replaced) {
|
|
1569
|
+
break;
|
|
1570
|
+
}
|
|
1571
|
+
}
|
|
1572
|
+
const tokens = path.match(/(?::[^\/]+)|(?:\/\*$)|./g) || [];
|
|
1573
|
+
for (let i = groups.length - 1; i >= 0; i--) {
|
|
1574
|
+
const [mark] = groups[i];
|
|
1575
|
+
for (let j = tokens.length - 1; j >= 0; j--) {
|
|
1576
|
+
if (tokens[j].indexOf(mark) !== -1) {
|
|
1577
|
+
tokens[j] = tokens[j].replace(mark, groups[i][1]);
|
|
1578
|
+
break;
|
|
1579
|
+
}
|
|
1580
|
+
}
|
|
1581
|
+
}
|
|
1582
|
+
this.#root.insert(tokens, index, paramAssoc, this.#context, pathErrorCheckOnly);
|
|
1583
|
+
return paramAssoc;
|
|
1584
|
+
}
|
|
1585
|
+
buildRegExp() {
|
|
1586
|
+
let regexp = this.#root.buildRegExpStr();
|
|
1587
|
+
if (regexp === "") {
|
|
1588
|
+
return [/^$/, [], []];
|
|
1589
|
+
}
|
|
1590
|
+
let captureIndex = 0;
|
|
1591
|
+
const indexReplacementMap = [];
|
|
1592
|
+
const paramReplacementMap = [];
|
|
1593
|
+
regexp = regexp.replace(/#(\d+)|@(\d+)|\.\*\$/g, (_, handlerIndex, paramIndex) => {
|
|
1594
|
+
if (handlerIndex !== void 0) {
|
|
1595
|
+
indexReplacementMap[++captureIndex] = Number(handlerIndex);
|
|
1596
|
+
return "$()";
|
|
1597
|
+
}
|
|
1598
|
+
if (paramIndex !== void 0) {
|
|
1599
|
+
paramReplacementMap[Number(paramIndex)] = ++captureIndex;
|
|
1600
|
+
return "";
|
|
1601
|
+
}
|
|
1602
|
+
return "";
|
|
1603
|
+
});
|
|
1604
|
+
return [new RegExp(`^${regexp}`), indexReplacementMap, paramReplacementMap];
|
|
1605
|
+
}
|
|
1606
|
+
};
|
|
1607
|
+
|
|
1608
|
+
// worker/node_modules/hono/dist/router/reg-exp-router/router.js
|
|
1609
|
+
var nullMatcher = [/^$/, [], /* @__PURE__ */ Object.create(null)];
|
|
1610
|
+
var wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
|
|
1611
|
+
function buildWildcardRegExp(path) {
|
|
1612
|
+
return wildcardRegExpCache[path] ??= new RegExp(
|
|
1613
|
+
path === "*" ? "" : `^${path.replace(
|
|
1614
|
+
/\/\*$|([.\\+*[^\]$()])/g,
|
|
1615
|
+
(_, metaChar) => metaChar ? `\\${metaChar}` : "(?:|/.*)"
|
|
1616
|
+
)}$`
|
|
1617
|
+
);
|
|
1618
|
+
}
|
|
1619
|
+
function clearWildcardRegExpCache() {
|
|
1620
|
+
wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
|
|
1621
|
+
}
|
|
1622
|
+
function buildMatcherFromPreprocessedRoutes(routes) {
|
|
1623
|
+
const trie = new Trie();
|
|
1624
|
+
const handlerData = [];
|
|
1625
|
+
if (routes.length === 0) {
|
|
1626
|
+
return nullMatcher;
|
|
1627
|
+
}
|
|
1628
|
+
const routesWithStaticPathFlag = routes.map(
|
|
1629
|
+
(route) => [!/\*|\/:/.test(route[0]), ...route]
|
|
1630
|
+
).sort(
|
|
1631
|
+
([isStaticA, pathA], [isStaticB, pathB]) => isStaticA ? 1 : isStaticB ? -1 : pathA.length - pathB.length
|
|
1632
|
+
);
|
|
1633
|
+
const staticMap = /* @__PURE__ */ Object.create(null);
|
|
1634
|
+
for (let i = 0, j = -1, len = routesWithStaticPathFlag.length; i < len; i++) {
|
|
1635
|
+
const [pathErrorCheckOnly, path, handlers] = routesWithStaticPathFlag[i];
|
|
1636
|
+
if (pathErrorCheckOnly) {
|
|
1637
|
+
staticMap[path] = [handlers.map(([h]) => [h, /* @__PURE__ */ Object.create(null)]), emptyParam];
|
|
1638
|
+
} else {
|
|
1639
|
+
j++;
|
|
1640
|
+
}
|
|
1641
|
+
let paramAssoc;
|
|
1642
|
+
try {
|
|
1643
|
+
paramAssoc = trie.insert(path, j, pathErrorCheckOnly);
|
|
1644
|
+
} catch (e) {
|
|
1645
|
+
throw e === PATH_ERROR ? new UnsupportedPathError(path) : e;
|
|
1646
|
+
}
|
|
1647
|
+
if (pathErrorCheckOnly) {
|
|
1648
|
+
continue;
|
|
1649
|
+
}
|
|
1650
|
+
handlerData[j] = handlers.map(([h, paramCount]) => {
|
|
1651
|
+
const paramIndexMap = /* @__PURE__ */ Object.create(null);
|
|
1652
|
+
paramCount -= 1;
|
|
1653
|
+
for (; paramCount >= 0; paramCount--) {
|
|
1654
|
+
const [key, value] = paramAssoc[paramCount];
|
|
1655
|
+
paramIndexMap[key] = value;
|
|
1656
|
+
}
|
|
1657
|
+
return [h, paramIndexMap];
|
|
1658
|
+
});
|
|
1659
|
+
}
|
|
1660
|
+
const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp();
|
|
1661
|
+
for (let i = 0, len = handlerData.length; i < len; i++) {
|
|
1662
|
+
for (let j = 0, len2 = handlerData[i].length; j < len2; j++) {
|
|
1663
|
+
const map = handlerData[i][j]?.[1];
|
|
1664
|
+
if (!map) {
|
|
1665
|
+
continue;
|
|
1666
|
+
}
|
|
1667
|
+
const keys = Object.keys(map);
|
|
1668
|
+
for (let k = 0, len3 = keys.length; k < len3; k++) {
|
|
1669
|
+
map[keys[k]] = paramReplacementMap[map[keys[k]]];
|
|
1670
|
+
}
|
|
1671
|
+
}
|
|
1672
|
+
}
|
|
1673
|
+
const handlerMap = [];
|
|
1674
|
+
for (const i in indexReplacementMap) {
|
|
1675
|
+
handlerMap[i] = handlerData[indexReplacementMap[i]];
|
|
1676
|
+
}
|
|
1677
|
+
return [regexp, handlerMap, staticMap];
|
|
1678
|
+
}
|
|
1679
|
+
function findMiddleware(middleware, path) {
|
|
1680
|
+
if (!middleware) {
|
|
1681
|
+
return void 0;
|
|
1682
|
+
}
|
|
1683
|
+
for (const k of Object.keys(middleware).sort((a, b) => b.length - a.length)) {
|
|
1684
|
+
if (buildWildcardRegExp(k).test(path)) {
|
|
1685
|
+
return [...middleware[k]];
|
|
1686
|
+
}
|
|
1687
|
+
}
|
|
1688
|
+
return void 0;
|
|
1689
|
+
}
|
|
1690
|
+
var RegExpRouter = class {
|
|
1691
|
+
name = "RegExpRouter";
|
|
1692
|
+
#middleware;
|
|
1693
|
+
#routes;
|
|
1694
|
+
constructor() {
|
|
1695
|
+
this.#middleware = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
|
|
1696
|
+
this.#routes = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
|
|
1697
|
+
}
|
|
1698
|
+
add(method, path, handler) {
|
|
1699
|
+
const middleware = this.#middleware;
|
|
1700
|
+
const routes = this.#routes;
|
|
1701
|
+
if (!middleware || !routes) {
|
|
1702
|
+
throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
|
|
1703
|
+
}
|
|
1704
|
+
if (!middleware[method]) {
|
|
1705
|
+
;
|
|
1706
|
+
[middleware, routes].forEach((handlerMap) => {
|
|
1707
|
+
handlerMap[method] = /* @__PURE__ */ Object.create(null);
|
|
1708
|
+
Object.keys(handlerMap[METHOD_NAME_ALL]).forEach((p) => {
|
|
1709
|
+
handlerMap[method][p] = [...handlerMap[METHOD_NAME_ALL][p]];
|
|
1710
|
+
});
|
|
1711
|
+
});
|
|
1712
|
+
}
|
|
1713
|
+
if (path === "/*") {
|
|
1714
|
+
path = "*";
|
|
1715
|
+
}
|
|
1716
|
+
const paramCount = (path.match(/\/:/g) || []).length;
|
|
1717
|
+
if (/\*$/.test(path)) {
|
|
1718
|
+
const re = buildWildcardRegExp(path);
|
|
1719
|
+
if (method === METHOD_NAME_ALL) {
|
|
1720
|
+
Object.keys(middleware).forEach((m) => {
|
|
1721
|
+
middleware[m][path] ||= findMiddleware(middleware[m], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];
|
|
1722
|
+
});
|
|
1723
|
+
} else {
|
|
1724
|
+
middleware[method][path] ||= findMiddleware(middleware[method], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];
|
|
1725
|
+
}
|
|
1726
|
+
Object.keys(middleware).forEach((m) => {
|
|
1727
|
+
if (method === METHOD_NAME_ALL || method === m) {
|
|
1728
|
+
Object.keys(middleware[m]).forEach((p) => {
|
|
1729
|
+
re.test(p) && middleware[m][p].push([handler, paramCount]);
|
|
1730
|
+
});
|
|
1731
|
+
}
|
|
1732
|
+
});
|
|
1733
|
+
Object.keys(routes).forEach((m) => {
|
|
1734
|
+
if (method === METHOD_NAME_ALL || method === m) {
|
|
1735
|
+
Object.keys(routes[m]).forEach(
|
|
1736
|
+
(p) => re.test(p) && routes[m][p].push([handler, paramCount])
|
|
1737
|
+
);
|
|
1738
|
+
}
|
|
1739
|
+
});
|
|
1740
|
+
return;
|
|
1741
|
+
}
|
|
1742
|
+
const paths = checkOptionalParameter(path) || [path];
|
|
1743
|
+
for (let i = 0, len = paths.length; i < len; i++) {
|
|
1744
|
+
const path2 = paths[i];
|
|
1745
|
+
Object.keys(routes).forEach((m) => {
|
|
1746
|
+
if (method === METHOD_NAME_ALL || method === m) {
|
|
1747
|
+
routes[m][path2] ||= [
|
|
1748
|
+
...findMiddleware(middleware[m], path2) || findMiddleware(middleware[METHOD_NAME_ALL], path2) || []
|
|
1749
|
+
];
|
|
1750
|
+
routes[m][path2].push([handler, paramCount - len + i + 1]);
|
|
1751
|
+
}
|
|
1752
|
+
});
|
|
1753
|
+
}
|
|
1754
|
+
}
|
|
1755
|
+
match = match;
|
|
1756
|
+
buildAllMatchers() {
|
|
1757
|
+
const matchers = /* @__PURE__ */ Object.create(null);
|
|
1758
|
+
Object.keys(this.#routes).concat(Object.keys(this.#middleware)).forEach((method) => {
|
|
1759
|
+
matchers[method] ||= this.#buildMatcher(method);
|
|
1760
|
+
});
|
|
1761
|
+
this.#middleware = this.#routes = void 0;
|
|
1762
|
+
clearWildcardRegExpCache();
|
|
1763
|
+
return matchers;
|
|
1764
|
+
}
|
|
1765
|
+
#buildMatcher(method) {
|
|
1766
|
+
const routes = [];
|
|
1767
|
+
let hasOwnRoute = method === METHOD_NAME_ALL;
|
|
1768
|
+
[this.#middleware, this.#routes].forEach((r) => {
|
|
1769
|
+
const ownRoute = r[method] ? Object.keys(r[method]).map((path) => [path, r[method][path]]) : [];
|
|
1770
|
+
if (ownRoute.length !== 0) {
|
|
1771
|
+
hasOwnRoute ||= true;
|
|
1772
|
+
routes.push(...ownRoute);
|
|
1773
|
+
} else if (method !== METHOD_NAME_ALL) {
|
|
1774
|
+
routes.push(
|
|
1775
|
+
...Object.keys(r[METHOD_NAME_ALL]).map((path) => [path, r[METHOD_NAME_ALL][path]])
|
|
1776
|
+
);
|
|
1777
|
+
}
|
|
1778
|
+
});
|
|
1779
|
+
if (!hasOwnRoute) {
|
|
1780
|
+
return null;
|
|
1781
|
+
} else {
|
|
1782
|
+
return buildMatcherFromPreprocessedRoutes(routes);
|
|
1783
|
+
}
|
|
1784
|
+
}
|
|
1785
|
+
};
|
|
1786
|
+
|
|
1787
|
+
// worker/node_modules/hono/dist/router/smart-router/router.js
|
|
1788
|
+
var SmartRouter = class {
|
|
1789
|
+
name = "SmartRouter";
|
|
1790
|
+
#routers = [];
|
|
1791
|
+
#routes = [];
|
|
1792
|
+
constructor(init) {
|
|
1793
|
+
this.#routers = init.routers;
|
|
1794
|
+
}
|
|
1795
|
+
add(method, path, handler) {
|
|
1796
|
+
if (!this.#routes) {
|
|
1797
|
+
throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
|
|
1798
|
+
}
|
|
1799
|
+
this.#routes.push([method, path, handler]);
|
|
1800
|
+
}
|
|
1801
|
+
match(method, path) {
|
|
1802
|
+
if (!this.#routes) {
|
|
1803
|
+
throw new Error("Fatal error");
|
|
1804
|
+
}
|
|
1805
|
+
const routers = this.#routers;
|
|
1806
|
+
const routes = this.#routes;
|
|
1807
|
+
const len = routers.length;
|
|
1808
|
+
let i = 0;
|
|
1809
|
+
let res;
|
|
1810
|
+
for (; i < len; i++) {
|
|
1811
|
+
const router = routers[i];
|
|
1812
|
+
try {
|
|
1813
|
+
for (let i2 = 0, len2 = routes.length; i2 < len2; i2++) {
|
|
1814
|
+
router.add(...routes[i2]);
|
|
1815
|
+
}
|
|
1816
|
+
res = router.match(method, path);
|
|
1817
|
+
} catch (e) {
|
|
1818
|
+
if (e instanceof UnsupportedPathError) {
|
|
1819
|
+
continue;
|
|
1820
|
+
}
|
|
1821
|
+
throw e;
|
|
1822
|
+
}
|
|
1823
|
+
this.match = router.match.bind(router);
|
|
1824
|
+
this.#routers = [router];
|
|
1825
|
+
this.#routes = void 0;
|
|
1826
|
+
break;
|
|
1827
|
+
}
|
|
1828
|
+
if (i === len) {
|
|
1829
|
+
throw new Error("Fatal error");
|
|
1830
|
+
}
|
|
1831
|
+
this.name = `SmartRouter + ${this.activeRouter.name}`;
|
|
1832
|
+
return res;
|
|
1833
|
+
}
|
|
1834
|
+
get activeRouter() {
|
|
1835
|
+
if (this.#routes || this.#routers.length !== 1) {
|
|
1836
|
+
throw new Error("No active router has been determined yet.");
|
|
1837
|
+
}
|
|
1838
|
+
return this.#routers[0];
|
|
1839
|
+
}
|
|
1840
|
+
};
|
|
1841
|
+
|
|
1842
|
+
// worker/node_modules/hono/dist/router/trie-router/node.js
|
|
1843
|
+
var emptyParams = /* @__PURE__ */ Object.create(null);
|
|
1844
|
+
var hasChildren = (children) => {
|
|
1845
|
+
for (const _ in children) {
|
|
1846
|
+
return true;
|
|
1847
|
+
}
|
|
1848
|
+
return false;
|
|
1849
|
+
};
|
|
1850
|
+
var Node2 = class _Node2 {
|
|
1851
|
+
#methods;
|
|
1852
|
+
#children;
|
|
1853
|
+
#patterns;
|
|
1854
|
+
#order = 0;
|
|
1855
|
+
#params = emptyParams;
|
|
1856
|
+
constructor(method, handler, children) {
|
|
1857
|
+
this.#children = children || /* @__PURE__ */ Object.create(null);
|
|
1858
|
+
this.#methods = [];
|
|
1859
|
+
if (method && handler) {
|
|
1860
|
+
const m = /* @__PURE__ */ Object.create(null);
|
|
1861
|
+
m[method] = { handler, possibleKeys: [], score: 0 };
|
|
1862
|
+
this.#methods = [m];
|
|
1863
|
+
}
|
|
1864
|
+
this.#patterns = [];
|
|
1865
|
+
}
|
|
1866
|
+
insert(method, path, handler) {
|
|
1867
|
+
this.#order = ++this.#order;
|
|
1868
|
+
let curNode = this;
|
|
1869
|
+
const parts = splitRoutingPath(path);
|
|
1870
|
+
const possibleKeys = [];
|
|
1871
|
+
for (let i = 0, len = parts.length; i < len; i++) {
|
|
1872
|
+
const p = parts[i];
|
|
1873
|
+
const nextP = parts[i + 1];
|
|
1874
|
+
const pattern = getPattern(p, nextP);
|
|
1875
|
+
const key = Array.isArray(pattern) ? pattern[0] : p;
|
|
1876
|
+
if (key in curNode.#children) {
|
|
1877
|
+
curNode = curNode.#children[key];
|
|
1878
|
+
if (pattern) {
|
|
1879
|
+
possibleKeys.push(pattern[1]);
|
|
1880
|
+
}
|
|
1881
|
+
continue;
|
|
1882
|
+
}
|
|
1883
|
+
curNode.#children[key] = new _Node2();
|
|
1884
|
+
if (pattern) {
|
|
1885
|
+
curNode.#patterns.push(pattern);
|
|
1886
|
+
possibleKeys.push(pattern[1]);
|
|
1887
|
+
}
|
|
1888
|
+
curNode = curNode.#children[key];
|
|
1889
|
+
}
|
|
1890
|
+
curNode.#methods.push({
|
|
1891
|
+
[method]: {
|
|
1892
|
+
handler,
|
|
1893
|
+
possibleKeys: possibleKeys.filter((v, i, a) => a.indexOf(v) === i),
|
|
1894
|
+
score: this.#order
|
|
1895
|
+
}
|
|
1896
|
+
});
|
|
1897
|
+
return curNode;
|
|
1898
|
+
}
|
|
1899
|
+
#pushHandlerSets(handlerSets, node, method, nodeParams, params) {
|
|
1900
|
+
for (let i = 0, len = node.#methods.length; i < len; i++) {
|
|
1901
|
+
const m = node.#methods[i];
|
|
1902
|
+
const handlerSet = m[method] || m[METHOD_NAME_ALL];
|
|
1903
|
+
const processedSet = {};
|
|
1904
|
+
if (handlerSet !== void 0) {
|
|
1905
|
+
handlerSet.params = /* @__PURE__ */ Object.create(null);
|
|
1906
|
+
handlerSets.push(handlerSet);
|
|
1907
|
+
if (nodeParams !== emptyParams || params && params !== emptyParams) {
|
|
1908
|
+
for (let i2 = 0, len2 = handlerSet.possibleKeys.length; i2 < len2; i2++) {
|
|
1909
|
+
const key = handlerSet.possibleKeys[i2];
|
|
1910
|
+
const processed = processedSet[handlerSet.score];
|
|
1911
|
+
handlerSet.params[key] = params?.[key] && !processed ? params[key] : nodeParams[key] ?? params?.[key];
|
|
1912
|
+
processedSet[handlerSet.score] = true;
|
|
1913
|
+
}
|
|
1914
|
+
}
|
|
1915
|
+
}
|
|
1916
|
+
}
|
|
1917
|
+
}
|
|
1918
|
+
search(method, path) {
|
|
1919
|
+
const handlerSets = [];
|
|
1920
|
+
this.#params = emptyParams;
|
|
1921
|
+
const curNode = this;
|
|
1922
|
+
let curNodes = [curNode];
|
|
1923
|
+
const parts = splitPath(path);
|
|
1924
|
+
const curNodesQueue = [];
|
|
1925
|
+
const len = parts.length;
|
|
1926
|
+
let partOffsets = null;
|
|
1927
|
+
for (let i = 0; i < len; i++) {
|
|
1928
|
+
const part = parts[i];
|
|
1929
|
+
const isLast = i === len - 1;
|
|
1930
|
+
const tempNodes = [];
|
|
1931
|
+
for (let j = 0, len2 = curNodes.length; j < len2; j++) {
|
|
1932
|
+
const node = curNodes[j];
|
|
1933
|
+
const nextNode = node.#children[part];
|
|
1934
|
+
if (nextNode) {
|
|
1935
|
+
nextNode.#params = node.#params;
|
|
1936
|
+
if (isLast) {
|
|
1937
|
+
if (nextNode.#children["*"]) {
|
|
1938
|
+
this.#pushHandlerSets(handlerSets, nextNode.#children["*"], method, node.#params);
|
|
1939
|
+
}
|
|
1940
|
+
this.#pushHandlerSets(handlerSets, nextNode, method, node.#params);
|
|
1941
|
+
} else {
|
|
1942
|
+
tempNodes.push(nextNode);
|
|
1943
|
+
}
|
|
1944
|
+
}
|
|
1945
|
+
for (let k = 0, len3 = node.#patterns.length; k < len3; k++) {
|
|
1946
|
+
const pattern = node.#patterns[k];
|
|
1947
|
+
const params = node.#params === emptyParams ? {} : { ...node.#params };
|
|
1948
|
+
if (pattern === "*") {
|
|
1949
|
+
const astNode = node.#children["*"];
|
|
1950
|
+
if (astNode) {
|
|
1951
|
+
this.#pushHandlerSets(handlerSets, astNode, method, node.#params);
|
|
1952
|
+
astNode.#params = params;
|
|
1953
|
+
tempNodes.push(astNode);
|
|
1954
|
+
}
|
|
1955
|
+
continue;
|
|
1956
|
+
}
|
|
1957
|
+
const [key, name, matcher] = pattern;
|
|
1958
|
+
if (!part && !(matcher instanceof RegExp)) {
|
|
1959
|
+
continue;
|
|
1960
|
+
}
|
|
1961
|
+
const child = node.#children[key];
|
|
1962
|
+
if (matcher instanceof RegExp) {
|
|
1963
|
+
if (partOffsets === null) {
|
|
1964
|
+
partOffsets = new Array(len);
|
|
1965
|
+
let offset = path[0] === "/" ? 1 : 0;
|
|
1966
|
+
for (let p = 0; p < len; p++) {
|
|
1967
|
+
partOffsets[p] = offset;
|
|
1968
|
+
offset += parts[p].length + 1;
|
|
1969
|
+
}
|
|
1970
|
+
}
|
|
1971
|
+
const restPathString = path.substring(partOffsets[i]);
|
|
1972
|
+
const m = matcher.exec(restPathString);
|
|
1973
|
+
if (m) {
|
|
1974
|
+
params[name] = m[0];
|
|
1975
|
+
this.#pushHandlerSets(handlerSets, child, method, node.#params, params);
|
|
1976
|
+
if (hasChildren(child.#children)) {
|
|
1977
|
+
child.#params = params;
|
|
1978
|
+
const componentCount = m[0].match(/\//)?.length ?? 0;
|
|
1979
|
+
const targetCurNodes = curNodesQueue[componentCount] ||= [];
|
|
1980
|
+
targetCurNodes.push(child);
|
|
1981
|
+
}
|
|
1982
|
+
continue;
|
|
1983
|
+
}
|
|
1984
|
+
}
|
|
1985
|
+
if (matcher === true || matcher.test(part)) {
|
|
1986
|
+
params[name] = part;
|
|
1987
|
+
if (isLast) {
|
|
1988
|
+
this.#pushHandlerSets(handlerSets, child, method, params, node.#params);
|
|
1989
|
+
if (child.#children["*"]) {
|
|
1990
|
+
this.#pushHandlerSets(
|
|
1991
|
+
handlerSets,
|
|
1992
|
+
child.#children["*"],
|
|
1993
|
+
method,
|
|
1994
|
+
params,
|
|
1995
|
+
node.#params
|
|
1996
|
+
);
|
|
1997
|
+
}
|
|
1998
|
+
} else {
|
|
1999
|
+
child.#params = params;
|
|
2000
|
+
tempNodes.push(child);
|
|
2001
|
+
}
|
|
2002
|
+
}
|
|
2003
|
+
}
|
|
2004
|
+
}
|
|
2005
|
+
const shifted = curNodesQueue.shift();
|
|
2006
|
+
curNodes = shifted ? tempNodes.concat(shifted) : tempNodes;
|
|
2007
|
+
}
|
|
2008
|
+
if (handlerSets.length > 1) {
|
|
2009
|
+
handlerSets.sort((a, b) => {
|
|
2010
|
+
return a.score - b.score;
|
|
2011
|
+
});
|
|
2012
|
+
}
|
|
2013
|
+
return [handlerSets.map(({ handler, params }) => [handler, params])];
|
|
2014
|
+
}
|
|
2015
|
+
};
|
|
2016
|
+
|
|
2017
|
+
// worker/node_modules/hono/dist/router/trie-router/router.js
|
|
2018
|
+
var TrieRouter = class {
|
|
2019
|
+
name = "TrieRouter";
|
|
2020
|
+
#node;
|
|
2021
|
+
constructor() {
|
|
2022
|
+
this.#node = new Node2();
|
|
2023
|
+
}
|
|
2024
|
+
add(method, path, handler) {
|
|
2025
|
+
const results = checkOptionalParameter(path);
|
|
2026
|
+
if (results) {
|
|
2027
|
+
for (let i = 0, len = results.length; i < len; i++) {
|
|
2028
|
+
this.#node.insert(method, results[i], handler);
|
|
2029
|
+
}
|
|
2030
|
+
return;
|
|
2031
|
+
}
|
|
2032
|
+
this.#node.insert(method, path, handler);
|
|
2033
|
+
}
|
|
2034
|
+
match(method, path) {
|
|
2035
|
+
return this.#node.search(method, path);
|
|
2036
|
+
}
|
|
2037
|
+
};
|
|
2038
|
+
|
|
2039
|
+
// worker/node_modules/hono/dist/hono.js
|
|
2040
|
+
var Hono2 = class extends Hono {
|
|
2041
|
+
/**
|
|
2042
|
+
* Creates an instance of the Hono class.
|
|
2043
|
+
*
|
|
2044
|
+
* @param options - Optional configuration options for the Hono instance.
|
|
2045
|
+
*/
|
|
2046
|
+
constructor(options = {}) {
|
|
2047
|
+
super(options);
|
|
2048
|
+
this.router = options.router ?? new SmartRouter({
|
|
2049
|
+
routers: [new RegExpRouter(), new TrieRouter()]
|
|
2050
|
+
});
|
|
2051
|
+
}
|
|
2052
|
+
};
|
|
2053
|
+
|
|
2054
|
+
// worker/node_modules/hono/dist/middleware/cors/index.js
|
|
2055
|
+
var cors = (options) => {
|
|
2056
|
+
const defaults = {
|
|
2057
|
+
origin: "*",
|
|
2058
|
+
allowMethods: ["GET", "HEAD", "PUT", "POST", "DELETE", "PATCH"],
|
|
2059
|
+
allowHeaders: [],
|
|
2060
|
+
exposeHeaders: []
|
|
2061
|
+
};
|
|
2062
|
+
const opts = {
|
|
2063
|
+
...defaults,
|
|
2064
|
+
...options
|
|
2065
|
+
};
|
|
2066
|
+
const findAllowOrigin = ((optsOrigin) => {
|
|
2067
|
+
if (typeof optsOrigin === "string") {
|
|
2068
|
+
if (optsOrigin === "*") {
|
|
2069
|
+
if (opts.credentials) {
|
|
2070
|
+
return (origin) => origin || null;
|
|
2071
|
+
}
|
|
2072
|
+
return () => optsOrigin;
|
|
2073
|
+
} else {
|
|
2074
|
+
return (origin) => optsOrigin === origin ? origin : null;
|
|
2075
|
+
}
|
|
2076
|
+
} else if (typeof optsOrigin === "function") {
|
|
2077
|
+
return optsOrigin;
|
|
2078
|
+
} else {
|
|
2079
|
+
return (origin) => optsOrigin.includes(origin) ? origin : null;
|
|
2080
|
+
}
|
|
2081
|
+
})(opts.origin);
|
|
2082
|
+
const findAllowMethods = ((optsAllowMethods) => {
|
|
2083
|
+
if (typeof optsAllowMethods === "function") {
|
|
2084
|
+
return optsAllowMethods;
|
|
2085
|
+
} else if (Array.isArray(optsAllowMethods)) {
|
|
2086
|
+
return () => optsAllowMethods;
|
|
2087
|
+
} else {
|
|
2088
|
+
return () => [];
|
|
2089
|
+
}
|
|
2090
|
+
})(opts.allowMethods);
|
|
2091
|
+
return async function cors2(c, next) {
|
|
2092
|
+
function set(key, value) {
|
|
2093
|
+
c.res.headers.set(key, value);
|
|
2094
|
+
}
|
|
2095
|
+
const allowOrigin = await findAllowOrigin(c.req.header("origin") || "", c);
|
|
2096
|
+
if (allowOrigin) {
|
|
2097
|
+
set("Access-Control-Allow-Origin", allowOrigin);
|
|
2098
|
+
}
|
|
2099
|
+
if (opts.credentials) {
|
|
2100
|
+
set("Access-Control-Allow-Credentials", "true");
|
|
2101
|
+
}
|
|
2102
|
+
if (opts.exposeHeaders?.length) {
|
|
2103
|
+
set("Access-Control-Expose-Headers", opts.exposeHeaders.join(","));
|
|
2104
|
+
}
|
|
2105
|
+
if (c.req.method === "OPTIONS") {
|
|
2106
|
+
if (opts.origin !== "*" || opts.credentials) {
|
|
2107
|
+
set("Vary", "Origin");
|
|
2108
|
+
}
|
|
2109
|
+
if (opts.maxAge != null) {
|
|
2110
|
+
set("Access-Control-Max-Age", opts.maxAge.toString());
|
|
2111
|
+
}
|
|
2112
|
+
const allowMethods = await findAllowMethods(c.req.header("origin") || "", c);
|
|
2113
|
+
if (allowMethods.length) {
|
|
2114
|
+
set("Access-Control-Allow-Methods", allowMethods.join(","));
|
|
2115
|
+
}
|
|
2116
|
+
let headers = opts.allowHeaders;
|
|
2117
|
+
if (!headers?.length) {
|
|
2118
|
+
const requestHeaders = c.req.header("Access-Control-Request-Headers");
|
|
2119
|
+
if (requestHeaders) {
|
|
2120
|
+
headers = requestHeaders.split(/\s*,\s*/);
|
|
2121
|
+
}
|
|
2122
|
+
}
|
|
2123
|
+
if (headers?.length) {
|
|
2124
|
+
set("Access-Control-Allow-Headers", headers.join(","));
|
|
2125
|
+
c.res.headers.append("Vary", "Access-Control-Request-Headers");
|
|
2126
|
+
}
|
|
2127
|
+
c.res.headers.delete("Content-Length");
|
|
2128
|
+
c.res.headers.delete("Content-Type");
|
|
2129
|
+
return new Response(null, {
|
|
2130
|
+
headers: c.res.headers,
|
|
2131
|
+
status: 204,
|
|
2132
|
+
statusText: "No Content"
|
|
2133
|
+
});
|
|
2134
|
+
}
|
|
2135
|
+
await next();
|
|
2136
|
+
if (opts.origin !== "*" || opts.credentials) {
|
|
2137
|
+
c.header("Vary", "Origin", { append: true });
|
|
2138
|
+
}
|
|
2139
|
+
};
|
|
2140
|
+
};
|
|
2141
|
+
|
|
2142
|
+
// worker/src/lib/parse-ua.ts
|
|
2143
|
+
function parseUA(ua) {
|
|
2144
|
+
return {
|
|
2145
|
+
browser: parseBrowser(ua),
|
|
2146
|
+
os: parseOS(ua),
|
|
2147
|
+
device: parseDevice(ua)
|
|
2148
|
+
};
|
|
2149
|
+
}
|
|
2150
|
+
function parseBrowser(ua) {
|
|
2151
|
+
if (/Edg\//i.test(ua)) return "Edge";
|
|
2152
|
+
if (/OPR\//i.test(ua) || /Opera/i.test(ua)) return "Opera";
|
|
2153
|
+
if (/Firefox\//i.test(ua)) return "Firefox";
|
|
2154
|
+
if (/SamsungBrowser\//i.test(ua)) return "Samsung Browser";
|
|
2155
|
+
if (/Chrome\//i.test(ua) && !/Chromium/i.test(ua)) return "Chrome";
|
|
2156
|
+
if (/Safari\//i.test(ua) && !/Chrome/i.test(ua)) return "Safari";
|
|
2157
|
+
if (/MSIE|Trident/i.test(ua)) return "IE";
|
|
2158
|
+
return "Other";
|
|
2159
|
+
}
|
|
2160
|
+
function parseOS(ua) {
|
|
2161
|
+
if (/Windows/i.test(ua)) return "Windows";
|
|
2162
|
+
if (/iPhone|iPad|iPod/i.test(ua)) return "iOS";
|
|
2163
|
+
if (/Mac OS X|macOS/i.test(ua)) return "macOS";
|
|
2164
|
+
if (/Android/i.test(ua)) return "Android";
|
|
2165
|
+
if (/Linux/i.test(ua)) return "Linux";
|
|
2166
|
+
if (/CrOS/i.test(ua)) return "ChromeOS";
|
|
2167
|
+
return "Other";
|
|
2168
|
+
}
|
|
2169
|
+
function parseDevice(ua) {
|
|
2170
|
+
if (/iPad|tablet/i.test(ua)) return "tablet";
|
|
2171
|
+
if (/Mobile|iPhone|iPod|Android.*Mobile|Opera Mini|IEMobile/i.test(ua)) return "mobile";
|
|
2172
|
+
return "desktop";
|
|
2173
|
+
}
|
|
2174
|
+
|
|
2175
|
+
// worker/src/lib/visitor.ts
|
|
2176
|
+
async function hashVisitor(site, ip, ua, date, salt) {
|
|
2177
|
+
const data = new TextEncoder().encode(`${site}|${ip}|${ua}|${date}|${salt}`);
|
|
2178
|
+
const hashBuffer = await crypto.subtle.digest("SHA-256", data);
|
|
2179
|
+
const hashArray = new Uint8Array(hashBuffer);
|
|
2180
|
+
return Array.from(hashArray.slice(0, 16)).map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
2181
|
+
}
|
|
2182
|
+
function todayUTC() {
|
|
2183
|
+
return (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
|
|
2184
|
+
}
|
|
2185
|
+
|
|
2186
|
+
// worker/src/lib/bot.ts
|
|
2187
|
+
var BOT_PATTERNS = [
|
|
2188
|
+
/bot/i,
|
|
2189
|
+
/crawl/i,
|
|
2190
|
+
/spider/i,
|
|
2191
|
+
/slurp/i,
|
|
2192
|
+
/mediapartners/i,
|
|
2193
|
+
/googlebot/i,
|
|
2194
|
+
/bingbot/i,
|
|
2195
|
+
/yandex/i,
|
|
2196
|
+
/baidu/i,
|
|
2197
|
+
/duckduckbot/i,
|
|
2198
|
+
/facebookexternalhit/i,
|
|
2199
|
+
/twitterbot/i,
|
|
2200
|
+
/linkedinbot/i,
|
|
2201
|
+
/whatsapp/i,
|
|
2202
|
+
/telegrambot/i,
|
|
2203
|
+
/discordbot/i,
|
|
2204
|
+
/slackbot/i,
|
|
2205
|
+
/pingdom/i,
|
|
2206
|
+
/uptimerobot/i,
|
|
2207
|
+
/headlesschrome/i,
|
|
2208
|
+
/phantomjs/i,
|
|
2209
|
+
/selenium/i,
|
|
2210
|
+
/puppeteer/i,
|
|
2211
|
+
/lighthouse/i,
|
|
2212
|
+
/pagespeed/i,
|
|
2213
|
+
/gptbot/i,
|
|
2214
|
+
/claudebot/i,
|
|
2215
|
+
/anthropic/i,
|
|
2216
|
+
/chatgpt/i,
|
|
2217
|
+
/prerender/i,
|
|
2218
|
+
/preview/i,
|
|
2219
|
+
/wget/i,
|
|
2220
|
+
/curl/i,
|
|
2221
|
+
/httpie/i,
|
|
2222
|
+
/python-requests/i,
|
|
2223
|
+
/axios/i,
|
|
2224
|
+
/node-fetch/i,
|
|
2225
|
+
/go-http-client/i
|
|
2226
|
+
];
|
|
2227
|
+
function isBot(ua) {
|
|
2228
|
+
if (!ua || ua.length < 10) return true;
|
|
2229
|
+
return BOT_PATTERNS.some((pattern) => pattern.test(ua));
|
|
2230
|
+
}
|
|
2231
|
+
|
|
2232
|
+
// worker/src/collect.ts
|
|
2233
|
+
async function collect(c) {
|
|
2234
|
+
if (c.req.method !== "POST") {
|
|
2235
|
+
return c.text("Method not allowed", 405);
|
|
2236
|
+
}
|
|
2237
|
+
const ua = c.req.header("User-Agent") || "";
|
|
2238
|
+
if (isBot(ua)) {
|
|
2239
|
+
return c.newResponse(null, 204);
|
|
2240
|
+
}
|
|
2241
|
+
let payload;
|
|
2242
|
+
try {
|
|
2243
|
+
payload = await c.req.json();
|
|
2244
|
+
} catch {
|
|
2245
|
+
return c.json({ error: "Invalid JSON payload" }, 400);
|
|
2246
|
+
}
|
|
2247
|
+
if (!payload.sid || !payload.url) {
|
|
2248
|
+
return c.json({ error: "Missing required fields: sid, url" }, 400);
|
|
2249
|
+
}
|
|
2250
|
+
const allowedSites = (c.env.ALLOWED_SITES || "").split(",").map((s) => s.trim()).filter(Boolean);
|
|
2251
|
+
if (allowedSites.length === 0) {
|
|
2252
|
+
return c.newResponse(null, 204);
|
|
2253
|
+
}
|
|
2254
|
+
if (!allowedSites.includes(payload.sid)) {
|
|
2255
|
+
return c.json({ error: "Unknown site" }, 400);
|
|
2256
|
+
}
|
|
2257
|
+
if (!c.env.HASH_SALT) {
|
|
2258
|
+
return c.newResponse(null, 204);
|
|
2259
|
+
}
|
|
2260
|
+
let pagePath;
|
|
2261
|
+
try {
|
|
2262
|
+
const parsed2 = new URL(payload.url);
|
|
2263
|
+
pagePath = parsed2.pathname;
|
|
2264
|
+
} catch {
|
|
2265
|
+
pagePath = payload.url.split("?")[0].split("#")[0];
|
|
2266
|
+
}
|
|
2267
|
+
let referrerDomain = "";
|
|
2268
|
+
if (payload.ref) {
|
|
2269
|
+
try {
|
|
2270
|
+
const host = new URL(payload.ref.includes("://") ? payload.ref : `https://${payload.ref}`).hostname;
|
|
2271
|
+
const isOwnSite = allowedSites.some((s) => host === s || host.endsWith(`.${s}`));
|
|
2272
|
+
if (!isOwnSite && host.includes(".")) {
|
|
2273
|
+
referrerDomain = host;
|
|
2274
|
+
}
|
|
2275
|
+
} catch {
|
|
2276
|
+
}
|
|
2277
|
+
}
|
|
2278
|
+
const ip = c.req.header("CF-Connecting-IP") || c.req.header("X-Forwarded-For") || "unknown";
|
|
2279
|
+
const country = c.req.header("CF-IPCountry") || "XX";
|
|
2280
|
+
const parsed = parseUA(ua);
|
|
2281
|
+
const visitorHash = await hashVisitor(payload.sid, ip, ua, todayUTC(), c.env.HASH_SALT);
|
|
2282
|
+
c.env.ANALYTICS.writeDataPoint({
|
|
2283
|
+
indexes: [visitorHash],
|
|
2284
|
+
blobs: [
|
|
2285
|
+
payload.sid,
|
|
2286
|
+
// blob1: site_id
|
|
2287
|
+
pagePath,
|
|
2288
|
+
// blob2: page path (no query string)
|
|
2289
|
+
referrerDomain,
|
|
2290
|
+
// blob3: referrer domain
|
|
2291
|
+
country,
|
|
2292
|
+
// blob4: country
|
|
2293
|
+
parsed.browser,
|
|
2294
|
+
// blob5: browser
|
|
2295
|
+
parsed.os,
|
|
2296
|
+
// blob6: OS
|
|
2297
|
+
parsed.device,
|
|
2298
|
+
// blob7: device type
|
|
2299
|
+
payload.us || "",
|
|
2300
|
+
// blob8: utm_source
|
|
2301
|
+
payload.um || ""
|
|
2302
|
+
// blob9: utm_medium
|
|
2303
|
+
],
|
|
2304
|
+
doubles: [
|
|
2305
|
+
1,
|
|
2306
|
+
// double1: count
|
|
2307
|
+
payload.sw || 0
|
|
2308
|
+
// double2: screen width
|
|
2309
|
+
]
|
|
2310
|
+
});
|
|
2311
|
+
return c.newResponse(null, 204);
|
|
2312
|
+
}
|
|
2313
|
+
|
|
2314
|
+
// worker/src/tracker.ts
|
|
2315
|
+
var TRACKER_SCRIPT = `(function(){
|
|
2316
|
+
"use strict";
|
|
2317
|
+
var d=document,w=window,l=d.currentScript;
|
|
2318
|
+
if(!l)return;
|
|
2319
|
+
var sid=l.getAttribute("data-site-id");
|
|
2320
|
+
if(!sid)return;
|
|
2321
|
+
var endpoint=l.src.replace("/tracker.js","/collect");
|
|
2322
|
+
|
|
2323
|
+
function send(data){
|
|
2324
|
+
try{
|
|
2325
|
+
var body=JSON.stringify(data);
|
|
2326
|
+
if(navigator.sendBeacon){
|
|
2327
|
+
navigator.sendBeacon(endpoint,body);
|
|
2328
|
+
}else{
|
|
2329
|
+
var xhr=new XMLHttpRequest();
|
|
2330
|
+
xhr.open("POST",endpoint,true);
|
|
2331
|
+
xhr.setRequestHeader("Content-Type","application/json");
|
|
2332
|
+
xhr.send(body);
|
|
2333
|
+
}
|
|
2334
|
+
}catch(e){}
|
|
2335
|
+
}
|
|
2336
|
+
|
|
2337
|
+
function getUTM(k){
|
|
2338
|
+
try{
|
|
2339
|
+
return new URLSearchParams(w.location.search).get(k)||"";
|
|
2340
|
+
}catch(e){return "";}
|
|
2341
|
+
}
|
|
2342
|
+
|
|
2343
|
+
function stripUrl(u){
|
|
2344
|
+
try{var p=new URL(u);return p.origin+p.pathname;}catch(e){return u.split("?")[0].split("#")[0];}
|
|
2345
|
+
}
|
|
2346
|
+
|
|
2347
|
+
function stripRef(r){
|
|
2348
|
+
try{var h=new URL(r).hostname;return h===w.location.hostname?"":h;}catch(e){return "";}
|
|
2349
|
+
}
|
|
2350
|
+
|
|
2351
|
+
function track(){
|
|
2352
|
+
send({
|
|
2353
|
+
sid:sid,
|
|
2354
|
+
url:stripUrl(w.location.href),
|
|
2355
|
+
ref:stripRef(d.referrer),
|
|
2356
|
+
sw:w.screen?w.screen.width:0,
|
|
2357
|
+
us:getUTM("utm_source"),
|
|
2358
|
+
um:getUTM("utm_medium")
|
|
2359
|
+
});
|
|
2360
|
+
}
|
|
2361
|
+
|
|
2362
|
+
// Track on page load
|
|
2363
|
+
if(d.readyState==="complete"){
|
|
2364
|
+
track();
|
|
2365
|
+
}else{
|
|
2366
|
+
w.addEventListener("load",track,{once:true});
|
|
2367
|
+
}
|
|
2368
|
+
|
|
2369
|
+
// Track SPA navigation via History API
|
|
2370
|
+
var pushState=history.pushState;
|
|
2371
|
+
history.pushState=function(){
|
|
2372
|
+
pushState.apply(this,arguments);
|
|
2373
|
+
setTimeout(track,10);
|
|
2374
|
+
};
|
|
2375
|
+
w.addEventListener("popstate",function(){setTimeout(track,10);});
|
|
2376
|
+
})();`;
|
|
2377
|
+
function serveTracker(c) {
|
|
2378
|
+
return c.newResponse(TRACKER_SCRIPT, 200, {
|
|
2379
|
+
"Content-Type": "application/javascript",
|
|
2380
|
+
"Cache-Control": "public, max-age=86400",
|
|
2381
|
+
"Access-Control-Allow-Origin": "*"
|
|
2382
|
+
});
|
|
2383
|
+
}
|
|
2384
|
+
|
|
2385
|
+
// worker/src/dashboard.ts
|
|
2386
|
+
var DASHBOARD_HTML = `<!doctype html>
|
|
2387
|
+
<html lang="en">
|
|
2388
|
+
<head>
|
|
2389
|
+
<meta charset="utf-8">
|
|
2390
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
2391
|
+
<title>Analytics</title>
|
|
2392
|
+
<style>
|
|
2393
|
+
:root {
|
|
2394
|
+
--bg: #0b0e14;
|
|
2395
|
+
--panel: #121723;
|
|
2396
|
+
--panel-2: #161c2b;
|
|
2397
|
+
--border: #1f2738;
|
|
2398
|
+
--text: #e6ebf4;
|
|
2399
|
+
--muted: #8b94a7;
|
|
2400
|
+
--accent: #5eead4;
|
|
2401
|
+
--accent-dim: rgba(94, 234, 212, 0.12);
|
|
2402
|
+
--bar: rgba(94, 234, 212, 0.14);
|
|
2403
|
+
}
|
|
2404
|
+
* { box-sizing: border-box; margin: 0; padding: 0; }
|
|
2405
|
+
body {
|
|
2406
|
+
background: var(--bg);
|
|
2407
|
+
color: var(--text);
|
|
2408
|
+
font: 14px/1.5 -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
|
|
2409
|
+
-webkit-font-smoothing: antialiased;
|
|
2410
|
+
}
|
|
2411
|
+
.wrap { max-width: 1080px; margin: 0 auto; padding: 28px 20px 60px; }
|
|
2412
|
+
|
|
2413
|
+
header { display: flex; align-items: center; gap: 14px; flex-wrap: wrap; margin-bottom: 24px; }
|
|
2414
|
+
header h1 { font-size: 17px; font-weight: 600; letter-spacing: -0.01em; }
|
|
2415
|
+
header h1 .dot { color: var(--accent); }
|
|
2416
|
+
.spacer { flex: 1; }
|
|
2417
|
+
.periods { display: flex; gap: 4px; background: var(--panel); border: 1px solid var(--border); border-radius: 8px; padding: 3px; }
|
|
2418
|
+
.periods button {
|
|
2419
|
+
border: 0; background: transparent; color: var(--muted); font: inherit; font-size: 13px;
|
|
2420
|
+
padding: 4px 10px; border-radius: 6px; cursor: pointer;
|
|
2421
|
+
}
|
|
2422
|
+
.periods button.active { background: var(--panel-2); color: var(--text); }
|
|
2423
|
+
.periods button:hover { color: var(--text); }
|
|
2424
|
+
.logout { border: 0; background: transparent; color: var(--muted); font: inherit; font-size: 12px; cursor: pointer; }
|
|
2425
|
+
.logout:hover { color: var(--text); }
|
|
2426
|
+
|
|
2427
|
+
.properties { display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 12px; margin-bottom: 28px; }
|
|
2428
|
+
.prop {
|
|
2429
|
+
background: var(--panel); border: 1px solid var(--border); border-radius: 12px;
|
|
2430
|
+
padding: 14px 16px; cursor: pointer; text-align: left; font: inherit; color: inherit;
|
|
2431
|
+
transition: border-color 0.15s;
|
|
2432
|
+
}
|
|
2433
|
+
.prop:hover { border-color: #2c3850; }
|
|
2434
|
+
.prop.active { border-color: var(--accent); background: var(--panel-2); }
|
|
2435
|
+
.prop .name { font-size: 13px; color: var(--muted); margin-bottom: 6px; }
|
|
2436
|
+
.prop.active .name { color: var(--accent); }
|
|
2437
|
+
.prop .nums { display: flex; align-items: baseline; gap: 10px; }
|
|
2438
|
+
.prop .views { font-size: 22px; font-weight: 650; letter-spacing: -0.02em; font-variant-numeric: tabular-nums; }
|
|
2439
|
+
.prop .visitors { font-size: 12px; color: var(--muted); }
|
|
2440
|
+
.prop svg { display: block; width: 100%; height: 28px; margin-top: 10px; }
|
|
2441
|
+
|
|
2442
|
+
.panel { background: var(--panel); border: 1px solid var(--border); border-radius: 12px; padding: 18px; }
|
|
2443
|
+
.panel h2 { font-size: 12px; font-weight: 600; text-transform: uppercase; letter-spacing: 0.06em; color: var(--muted); margin-bottom: 14px; }
|
|
2444
|
+
|
|
2445
|
+
.chart-panel { margin-bottom: 16px; }
|
|
2446
|
+
.chart-head { display: flex; align-items: baseline; gap: 24px; margin-bottom: 8px; }
|
|
2447
|
+
.bignum .v { font-size: 26px; font-weight: 650; letter-spacing: -0.02em; font-variant-numeric: tabular-nums; }
|
|
2448
|
+
.bignum .l { font-size: 12px; color: var(--muted); }
|
|
2449
|
+
#chart { width: 100%; height: 220px; display: block; }
|
|
2450
|
+
.xlabels { display: flex; justify-content: space-between; font-size: 11px; color: var(--muted); margin-top: 4px; }
|
|
2451
|
+
|
|
2452
|
+
.grid { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; }
|
|
2453
|
+
@media (max-width: 760px) { .grid { grid-template-columns: 1fr; } }
|
|
2454
|
+
|
|
2455
|
+
.tabs { display: flex; gap: 12px; margin-bottom: 14px; }
|
|
2456
|
+
.tabs button { border: 0; background: transparent; color: var(--muted); font: inherit; font-size: 12px; font-weight: 600; text-transform: uppercase; letter-spacing: 0.06em; cursor: pointer; padding: 0; }
|
|
2457
|
+
.tabs button.active { color: var(--text); border-bottom: 2px solid var(--accent); padding-bottom: 2px; }
|
|
2458
|
+
|
|
2459
|
+
.rows { display: flex; flex-direction: column; gap: 4px; }
|
|
2460
|
+
.row { position: relative; display: flex; justify-content: space-between; gap: 12px; padding: 5px 8px; border-radius: 6px; overflow: hidden; }
|
|
2461
|
+
.row .fill { position: absolute; inset: 0; background: var(--bar); border-radius: 6px; transform-origin: left; }
|
|
2462
|
+
.row .label, .row .val { position: relative; }
|
|
2463
|
+
.row .label { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
|
2464
|
+
.row .val { font-variant-numeric: tabular-nums; color: var(--muted); flex-shrink: 0; }
|
|
2465
|
+
.empty { color: var(--muted); font-size: 13px; padding: 8px 0; }
|
|
2466
|
+
|
|
2467
|
+
.loading { opacity: 0.45; pointer-events: none; }
|
|
2468
|
+
.foot { margin-top: 24px; font-size: 12px; color: var(--muted); }
|
|
2469
|
+
.err { background: rgba(248, 113, 113, 0.1); border: 1px solid rgba(248, 113, 113, 0.35); color: #fca5a5; border-radius: 8px; padding: 10px 14px; margin-bottom: 16px; display: none; }
|
|
2470
|
+
|
|
2471
|
+
/* Token gate */
|
|
2472
|
+
#gate { max-width: 360px; margin: 18vh auto 0; padding: 0 20px; }
|
|
2473
|
+
#gate .panel { padding: 26px; }
|
|
2474
|
+
#gate h1 { font-size: 16px; margin-bottom: 6px; }
|
|
2475
|
+
#gate p { color: var(--muted); font-size: 13px; margin-bottom: 16px; }
|
|
2476
|
+
#gate input {
|
|
2477
|
+
width: 100%; background: var(--bg); border: 1px solid var(--border); border-radius: 8px;
|
|
2478
|
+
color: var(--text); font: inherit; padding: 9px 12px; margin-bottom: 12px;
|
|
2479
|
+
}
|
|
2480
|
+
#gate input:focus { outline: none; border-color: var(--accent); }
|
|
2481
|
+
#gate button {
|
|
2482
|
+
width: 100%; border: 0; border-radius: 8px; background: var(--accent); color: #06241f;
|
|
2483
|
+
font: inherit; font-weight: 600; padding: 9px 12px; cursor: pointer;
|
|
2484
|
+
}
|
|
2485
|
+
#gate .gate-err { color: #fca5a5; font-size: 13px; margin-top: 10px; display: none; }
|
|
2486
|
+
</style>
|
|
2487
|
+
</head>
|
|
2488
|
+
<body>
|
|
2489
|
+
|
|
2490
|
+
<div id="gate" style="display:none">
|
|
2491
|
+
<div class="panel">
|
|
2492
|
+
<h1>Analytics<span style="color:var(--accent)">.</span></h1>
|
|
2493
|
+
<p>Enter your API token to view the dashboard.</p>
|
|
2494
|
+
<input id="gate-input" type="password" placeholder="API token" autocomplete="off">
|
|
2495
|
+
<button id="gate-btn">Unlock</button>
|
|
2496
|
+
<div class="gate-err" id="gate-err">Invalid token. Try again.</div>
|
|
2497
|
+
</div>
|
|
2498
|
+
</div>
|
|
2499
|
+
|
|
2500
|
+
<div class="wrap" id="app" style="display:none">
|
|
2501
|
+
<header>
|
|
2502
|
+
<h1>Analytics<span class="dot">.</span></h1>
|
|
2503
|
+
<div class="spacer"></div>
|
|
2504
|
+
<div class="periods" id="periods"></div>
|
|
2505
|
+
<button class="logout" id="logout" title="Forget token">Sign out</button>
|
|
2506
|
+
</header>
|
|
2507
|
+
|
|
2508
|
+
<div class="err" id="err"></div>
|
|
2509
|
+
|
|
2510
|
+
<div class="properties" id="properties"></div>
|
|
2511
|
+
|
|
2512
|
+
<div class="panel chart-panel" id="chart-wrap">
|
|
2513
|
+
<div class="chart-head">
|
|
2514
|
+
<div class="bignum"><div class="v" id="stat-views">–</div><div class="l">Pageviews</div></div>
|
|
2515
|
+
<div class="bignum"><div class="v" id="stat-visitors">–</div><div class="l">Visitors (approx)</div></div>
|
|
2516
|
+
</div>
|
|
2517
|
+
<svg id="chart" preserveAspectRatio="none"></svg>
|
|
2518
|
+
<div class="xlabels" id="xlabels"></div>
|
|
2519
|
+
</div>
|
|
2520
|
+
|
|
2521
|
+
<div class="grid">
|
|
2522
|
+
<div class="panel" id="p-pages"><h2>Top pages</h2><div class="rows"></div></div>
|
|
2523
|
+
<div class="panel" id="p-referrers"><h2>Referrers</h2><div class="rows"></div></div>
|
|
2524
|
+
<div class="panel" id="p-geo"><h2>Countries</h2><div class="rows"></div></div>
|
|
2525
|
+
<div class="panel" id="p-devices">
|
|
2526
|
+
<div class="tabs" id="device-tabs">
|
|
2527
|
+
<button data-type="browser" class="active">Browsers</button>
|
|
2528
|
+
<button data-type="os">OS</button>
|
|
2529
|
+
<button data-type="device">Devices</button>
|
|
2530
|
+
</div>
|
|
2531
|
+
<div class="rows"></div>
|
|
2532
|
+
</div>
|
|
2533
|
+
</div>
|
|
2534
|
+
|
|
2535
|
+
<div class="foot">Counts are sampling-adjusted (Cloudflare Analytics Engine). Data retained for 90 days.</div>
|
|
2536
|
+
</div>
|
|
2537
|
+
|
|
2538
|
+
<script>
|
|
2539
|
+
(function () {
|
|
2540
|
+
'use strict';
|
|
2541
|
+
var SITES = [];
|
|
2542
|
+
var PERIODS = [
|
|
2543
|
+
{ key: '1d', label: '24h', unit: 'hour' },
|
|
2544
|
+
{ key: '7d', label: '7d', unit: 'day' },
|
|
2545
|
+
{ key: '30d', label: '30d', unit: 'day' },
|
|
2546
|
+
{ key: '90d', label: '90d', unit: 'day' }
|
|
2547
|
+
];
|
|
2548
|
+
|
|
2549
|
+
var token = sessionStorage.getItem('aa_token') || '';
|
|
2550
|
+
var site = localStorage.getItem('aa_site');
|
|
2551
|
+
var period = localStorage.getItem('aa_period') || '7d';
|
|
2552
|
+
if (!PERIODS.some(function (p) { return p.key === period; })) period = '7d';
|
|
2553
|
+
var deviceType = 'browser';
|
|
2554
|
+
var loadSeq = 0;
|
|
2555
|
+
|
|
2556
|
+
var $ = function (sel) { return document.querySelector(sel); };
|
|
2557
|
+
|
|
2558
|
+
function api(endpoint, params) {
|
|
2559
|
+
var qs = new URLSearchParams(params).toString();
|
|
2560
|
+
return fetch('/api/' + endpoint + '?' + qs, {
|
|
2561
|
+
headers: { Authorization: 'Bearer ' + token }
|
|
2562
|
+
}).then(function (r) {
|
|
2563
|
+
if (r.status === 401) { showGate(true); throw new Error('unauthorized'); }
|
|
2564
|
+
if (!r.ok) {
|
|
2565
|
+
return r.json().catch(function () { return {}; }).then(function (b) {
|
|
2566
|
+
throw new Error(b.error || ('HTTP ' + r.status));
|
|
2567
|
+
});
|
|
2568
|
+
}
|
|
2569
|
+
return r.json();
|
|
2570
|
+
});
|
|
2571
|
+
}
|
|
2572
|
+
|
|
2573
|
+
function fmt(n) {
|
|
2574
|
+
n = Number(n) || 0;
|
|
2575
|
+
if (n >= 1e6) return (n / 1e6).toFixed(1).replace(/\\.0$/, '') + 'M';
|
|
2576
|
+
if (n >= 1e4) return (n / 1e3).toFixed(1).replace(/\\.0$/, '') + 'k';
|
|
2577
|
+
return Math.round(n).toLocaleString();
|
|
2578
|
+
}
|
|
2579
|
+
|
|
2580
|
+
var regionNames;
|
|
2581
|
+
try { regionNames = new Intl.DisplayNames(['en'], { type: 'region' }); } catch (e) { regionNames = null; }
|
|
2582
|
+
function countryLabel(code) {
|
|
2583
|
+
if (!code || code.length !== 2) return code || 'Unknown';
|
|
2584
|
+
var flag = String.fromCodePoint(127397 + code.charCodeAt(0), 127397 + code.charCodeAt(1));
|
|
2585
|
+
var name = code;
|
|
2586
|
+
if (regionNames) { try { name = regionNames.of(code) || code; } catch (e) {} }
|
|
2587
|
+
return flag + ' ' + name;
|
|
2588
|
+
}
|
|
2589
|
+
|
|
2590
|
+
// --- Token gate ---
|
|
2591
|
+
function showGate(invalid) {
|
|
2592
|
+
$('#app').style.display = 'none';
|
|
2593
|
+
$('#gate').style.display = 'block';
|
|
2594
|
+
$('#gate-err').style.display = invalid ? 'block' : 'none';
|
|
2595
|
+
$('#gate-input').focus();
|
|
2596
|
+
}
|
|
2597
|
+
// Fetch the configured site list (also validates the token: 401 shows the gate).
|
|
2598
|
+
function fetchSites() {
|
|
2599
|
+
return api('sites', {}).then(function (res) {
|
|
2600
|
+
SITES = res.data.map(function (r) { return r.site; });
|
|
2601
|
+
});
|
|
2602
|
+
}
|
|
2603
|
+
function enterApp() {
|
|
2604
|
+
if (SITES.indexOf(site) === -1) site = SITES[0];
|
|
2605
|
+
$('#gate').style.display = 'none';
|
|
2606
|
+
$('#app').style.display = 'block';
|
|
2607
|
+
if (!SITES.length) {
|
|
2608
|
+
showErr(new Error('No sites configured. Add sites to ALLOWED_SITES and redeploy.'));
|
|
2609
|
+
return;
|
|
2610
|
+
}
|
|
2611
|
+
loadAll();
|
|
2612
|
+
}
|
|
2613
|
+
function submitToken() {
|
|
2614
|
+
var v = $('#gate-input').value.trim();
|
|
2615
|
+
if (!v) return;
|
|
2616
|
+
token = v;
|
|
2617
|
+
fetchSites().then(function () {
|
|
2618
|
+
sessionStorage.setItem('aa_token', token);
|
|
2619
|
+
enterApp();
|
|
2620
|
+
}).catch(function (e) {
|
|
2621
|
+
if (e.message !== 'unauthorized') {
|
|
2622
|
+
$('#gate-err').textContent = e.message;
|
|
2623
|
+
$('#gate-err').style.display = 'block';
|
|
2624
|
+
}
|
|
2625
|
+
});
|
|
2626
|
+
}
|
|
2627
|
+
$('#gate-btn').addEventListener('click', submitToken);
|
|
2628
|
+
$('#gate-input').addEventListener('keydown', function (e) { if (e.key === 'Enter') submitToken(); });
|
|
2629
|
+
$('#logout').addEventListener('click', function () {
|
|
2630
|
+
sessionStorage.removeItem('aa_token');
|
|
2631
|
+
token = '';
|
|
2632
|
+
$('#gate-input').value = '';
|
|
2633
|
+
showGate(false);
|
|
2634
|
+
});
|
|
2635
|
+
|
|
2636
|
+
// --- Header controls ---
|
|
2637
|
+
function renderPeriods() {
|
|
2638
|
+
var el = $('#periods');
|
|
2639
|
+
el.innerHTML = '';
|
|
2640
|
+
PERIODS.forEach(function (p) {
|
|
2641
|
+
var b = document.createElement('button');
|
|
2642
|
+
b.textContent = p.label;
|
|
2643
|
+
if (p.key === period) b.className = 'active';
|
|
2644
|
+
b.addEventListener('click', function () {
|
|
2645
|
+
period = p.key;
|
|
2646
|
+
localStorage.setItem('aa_period', period);
|
|
2647
|
+
renderPeriods();
|
|
2648
|
+
loadAll();
|
|
2649
|
+
});
|
|
2650
|
+
el.appendChild(b);
|
|
2651
|
+
});
|
|
2652
|
+
}
|
|
2653
|
+
|
|
2654
|
+
// --- Property cards ---
|
|
2655
|
+
function sparkline(points) {
|
|
2656
|
+
if (!points || points.length < 2) return '';
|
|
2657
|
+
var max = Math.max.apply(null, points.map(function (p) { return p.v; })) || 1;
|
|
2658
|
+
var w = 100, h = 28;
|
|
2659
|
+
var step = w / (points.length - 1);
|
|
2660
|
+
var coords = points.map(function (p, i) {
|
|
2661
|
+
return (i * step).toFixed(1) + ',' + (h - 2 - (p.v / max) * (h - 4)).toFixed(1);
|
|
2662
|
+
});
|
|
2663
|
+
return '<svg viewBox="0 0 100 28" preserveAspectRatio="none">' +
|
|
2664
|
+
'<polyline fill="none" stroke="var(--accent)" stroke-width="1.5" points="' + coords.join(' ') + '"/></svg>';
|
|
2665
|
+
}
|
|
2666
|
+
|
|
2667
|
+
function renderProperties(results) {
|
|
2668
|
+
var el = $('#properties');
|
|
2669
|
+
el.innerHTML = '';
|
|
2670
|
+
SITES.forEach(function (s, i) {
|
|
2671
|
+
var r = results[i];
|
|
2672
|
+
var b = document.createElement('button');
|
|
2673
|
+
b.className = 'prop' + (s === site ? ' active' : '');
|
|
2674
|
+
b.innerHTML =
|
|
2675
|
+
'<div class="name"></div>' +
|
|
2676
|
+
'<div class="nums"><span class="views">' + (r ? fmt(r.views) : '–') + '</span>' +
|
|
2677
|
+
'<span class="visitors">' + (r ? fmt(r.visitors) + ' visitors' : '') + '</span></div>' +
|
|
2678
|
+
(r ? sparkline(r.series) : '');
|
|
2679
|
+
b.querySelector('.name').textContent = s;
|
|
2680
|
+
b.addEventListener('click', function () {
|
|
2681
|
+
if (s === site) return;
|
|
2682
|
+
site = s;
|
|
2683
|
+
localStorage.setItem('aa_site', site);
|
|
2684
|
+
el.querySelectorAll('.prop').forEach(function (n) { n.classList.remove('active'); });
|
|
2685
|
+
b.classList.add('active');
|
|
2686
|
+
loadDetail();
|
|
2687
|
+
});
|
|
2688
|
+
el.appendChild(b);
|
|
2689
|
+
});
|
|
2690
|
+
}
|
|
2691
|
+
|
|
2692
|
+
// --- Main chart ---
|
|
2693
|
+
function renderChart(series, unit) {
|
|
2694
|
+
var svg = $('#chart');
|
|
2695
|
+
var xl = $('#xlabels');
|
|
2696
|
+
svg.innerHTML = '';
|
|
2697
|
+
xl.innerHTML = '';
|
|
2698
|
+
if (!series.length) return;
|
|
2699
|
+
|
|
2700
|
+
var W = 1000, H = 220, PAD = 6;
|
|
2701
|
+
svg.setAttribute('viewBox', '0 0 ' + W + ' ' + H);
|
|
2702
|
+
var max = Math.max.apply(null, series.map(function (p) { return p.v; })) || 1;
|
|
2703
|
+
var step = series.length > 1 ? (W - PAD * 2) / (series.length - 1) : 0;
|
|
2704
|
+
var pts = series.map(function (p, i) {
|
|
2705
|
+
var x = PAD + i * step;
|
|
2706
|
+
var y = H - 24 - (p.v / max) * (H - 44);
|
|
2707
|
+
return [x, y];
|
|
2708
|
+
});
|
|
2709
|
+
var line = pts.map(function (p) { return p[0].toFixed(1) + ',' + p[1].toFixed(1); }).join(' ');
|
|
2710
|
+
var area = 'M' + PAD + ',' + (H - 24) + ' L' + line.replace(/ /g, ' L') + ' L' + (PAD + (series.length - 1) * step).toFixed(1) + ',' + (H - 24) + ' Z';
|
|
2711
|
+
|
|
2712
|
+
svg.innerHTML =
|
|
2713
|
+
'<defs><linearGradient id="g" x1="0" y1="0" x2="0" y2="1">' +
|
|
2714
|
+
'<stop offset="0%" stop-color="rgba(94,234,212,0.28)"/><stop offset="100%" stop-color="rgba(94,234,212,0)"/>' +
|
|
2715
|
+
'</linearGradient></defs>' +
|
|
2716
|
+
'<path d="' + area + '" fill="url(#g)"/>' +
|
|
2717
|
+
'<polyline fill="none" stroke="#5eead4" stroke-width="2" stroke-linejoin="round" points="' + line + '"/>' +
|
|
2718
|
+
pts.map(function (p, i) {
|
|
2719
|
+
return '<circle cx="' + p[0].toFixed(1) + '" cy="' + p[1].toFixed(1) + '" r="6" fill="transparent">' +
|
|
2720
|
+
'<title>' + series[i].label + ': ' + fmt(series[i].v) + ' views</title></circle>';
|
|
2721
|
+
}).join('');
|
|
2722
|
+
|
|
2723
|
+
var labels = [series[0], series[Math.floor(series.length / 2)], series[series.length - 1]];
|
|
2724
|
+
labels.forEach(function (p) {
|
|
2725
|
+
var d = document.createElement('span');
|
|
2726
|
+
d.textContent = p.label;
|
|
2727
|
+
xl.appendChild(d);
|
|
2728
|
+
});
|
|
2729
|
+
}
|
|
2730
|
+
|
|
2731
|
+
function tsLabel(iso, unit) {
|
|
2732
|
+
var d = new Date(iso);
|
|
2733
|
+
if (unit === 'hour') return d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
|
|
2734
|
+
return d.toLocaleDateString([], { month: 'short', day: 'numeric' });
|
|
2735
|
+
}
|
|
2736
|
+
|
|
2737
|
+
// --- Bar lists ---
|
|
2738
|
+
function renderRows(panelSel, data, labelFn) {
|
|
2739
|
+
var el = document.querySelector(panelSel + ' .rows');
|
|
2740
|
+
el.innerHTML = '';
|
|
2741
|
+
if (!data.length) {
|
|
2742
|
+
el.innerHTML = '<div class="empty">No data for this period.</div>';
|
|
2743
|
+
return;
|
|
2744
|
+
}
|
|
2745
|
+
var max = Math.max.apply(null, data.map(function (r) { return Number(r.views) || 0; })) || 1;
|
|
2746
|
+
data.forEach(function (r) {
|
|
2747
|
+
var row = document.createElement('div');
|
|
2748
|
+
row.className = 'row';
|
|
2749
|
+
var pct = ((Number(r.views) || 0) / max * 100).toFixed(1);
|
|
2750
|
+
var fill = document.createElement('div');
|
|
2751
|
+
fill.className = 'fill';
|
|
2752
|
+
fill.style.width = pct + '%';
|
|
2753
|
+
var label = document.createElement('span');
|
|
2754
|
+
label.className = 'label';
|
|
2755
|
+
label.textContent = labelFn(r);
|
|
2756
|
+
var val = document.createElement('span');
|
|
2757
|
+
val.className = 'val';
|
|
2758
|
+
val.textContent = fmt(r.views);
|
|
2759
|
+
row.appendChild(fill); row.appendChild(label); row.appendChild(val);
|
|
2760
|
+
el.appendChild(row);
|
|
2761
|
+
});
|
|
2762
|
+
}
|
|
2763
|
+
|
|
2764
|
+
// --- Device tabs ---
|
|
2765
|
+
$('#device-tabs').addEventListener('click', function (e) {
|
|
2766
|
+
var btn = e.target.closest('button');
|
|
2767
|
+
if (!btn || btn.dataset.type === deviceType) return;
|
|
2768
|
+
deviceType = btn.dataset.type;
|
|
2769
|
+
this.querySelectorAll('button').forEach(function (b) { b.classList.remove('active'); });
|
|
2770
|
+
btn.classList.add('active');
|
|
2771
|
+
loadDevices();
|
|
2772
|
+
});
|
|
2773
|
+
|
|
2774
|
+
function loadDevices() {
|
|
2775
|
+
var seq = loadSeq;
|
|
2776
|
+
var panel = $('#p-devices');
|
|
2777
|
+
panel.classList.add('loading');
|
|
2778
|
+
api('browsers', { site: site, period: period, limit: 10, type: deviceType }).then(function (res) {
|
|
2779
|
+
if (seq !== loadSeq) return;
|
|
2780
|
+
renderRows('#p-devices', res.data, function (r) { return r.name || 'Unknown'; });
|
|
2781
|
+
}).catch(showErr).finally(function () { panel.classList.remove('loading'); });
|
|
2782
|
+
}
|
|
2783
|
+
|
|
2784
|
+
// --- Loaders ---
|
|
2785
|
+
function showErr(e) {
|
|
2786
|
+
if (e.message === 'unauthorized') return;
|
|
2787
|
+
var el = $('#err');
|
|
2788
|
+
el.textContent = e.message;
|
|
2789
|
+
el.style.display = 'block';
|
|
2790
|
+
}
|
|
2791
|
+
|
|
2792
|
+
function unitFor(p) {
|
|
2793
|
+
return PERIODS.filter(function (x) { return x.key === p; })[0].unit;
|
|
2794
|
+
}
|
|
2795
|
+
|
|
2796
|
+
function loadDetail() {
|
|
2797
|
+
var seq = ++loadSeq;
|
|
2798
|
+
$('#err').style.display = 'none';
|
|
2799
|
+
var unit = unitFor(period);
|
|
2800
|
+
['#chart-wrap', '#p-pages', '#p-referrers', '#p-geo', '#p-devices'].forEach(function (s) {
|
|
2801
|
+
$(s).classList.add('loading');
|
|
2802
|
+
});
|
|
2803
|
+
|
|
2804
|
+
api('stats', { site: site, period: period }).then(function (res) {
|
|
2805
|
+
if (seq !== loadSeq) return;
|
|
2806
|
+
$('#stat-views').textContent = fmt(res.data.pageviews);
|
|
2807
|
+
$('#stat-visitors').textContent = fmt(res.data.approx_daily_visitors);
|
|
2808
|
+
}).catch(showErr);
|
|
2809
|
+
|
|
2810
|
+
api('timeseries', { site: site, period: period, unit: unit }).then(function (res) {
|
|
2811
|
+
if (seq !== loadSeq) return;
|
|
2812
|
+
var series = res.data.map(function (r) {
|
|
2813
|
+
return { v: Number(r.views) || 0, label: tsLabel(r.timestamp, unit) };
|
|
2814
|
+
});
|
|
2815
|
+
renderChart(series, unit);
|
|
2816
|
+
$('#chart-wrap').classList.remove('loading');
|
|
2817
|
+
}).catch(showErr);
|
|
2818
|
+
|
|
2819
|
+
api('pages', { site: site, period: period, limit: 10 }).then(function (res) {
|
|
2820
|
+
if (seq !== loadSeq) return;
|
|
2821
|
+
renderRows('#p-pages', res.data, function (r) { return r.page; });
|
|
2822
|
+
$('#p-pages').classList.remove('loading');
|
|
2823
|
+
}).catch(showErr);
|
|
2824
|
+
|
|
2825
|
+
api('referrers', { site: site, period: period, limit: 10 }).then(function (res) {
|
|
2826
|
+
if (seq !== loadSeq) return;
|
|
2827
|
+
renderRows('#p-referrers', res.data, function (r) { return r.referrer; });
|
|
2828
|
+
$('#p-referrers').classList.remove('loading');
|
|
2829
|
+
}).catch(showErr);
|
|
2830
|
+
|
|
2831
|
+
api('geo', { site: site, period: period, limit: 10 }).then(function (res) {
|
|
2832
|
+
if (seq !== loadSeq) return;
|
|
2833
|
+
renderRows('#p-geo', res.data, function (r) { return countryLabel(r.country); });
|
|
2834
|
+
$('#p-geo').classList.remove('loading');
|
|
2835
|
+
}).catch(showErr);
|
|
2836
|
+
|
|
2837
|
+
loadDevices();
|
|
2838
|
+
}
|
|
2839
|
+
|
|
2840
|
+
function loadAll() {
|
|
2841
|
+
renderPeriods();
|
|
2842
|
+
// Overview cards: stats + sparkline per property
|
|
2843
|
+
Promise.all(SITES.map(function (s) {
|
|
2844
|
+
return Promise.all([
|
|
2845
|
+
api('stats', { site: s, period: period }),
|
|
2846
|
+
api('timeseries', { site: s, period: period, unit: unitFor(period) })
|
|
2847
|
+
]).then(function (res) {
|
|
2848
|
+
return {
|
|
2849
|
+
views: res[0].data.pageviews,
|
|
2850
|
+
visitors: res[0].data.approx_daily_visitors,
|
|
2851
|
+
series: res[1].data.map(function (r) { return { v: Number(r.views) || 0 }; })
|
|
2852
|
+
};
|
|
2853
|
+
}).catch(function () { return null; });
|
|
2854
|
+
})).then(renderProperties);
|
|
2855
|
+
|
|
2856
|
+
loadDetail();
|
|
2857
|
+
}
|
|
2858
|
+
|
|
2859
|
+
// --- Boot ---
|
|
2860
|
+
// Accept token via URL fragment (#token=...) so it can be handed off without
|
|
2861
|
+
// typing. The fragment never reaches the server; strip it immediately.
|
|
2862
|
+
var hashMatch = location.hash.match(/^#token=(.+)$/);
|
|
2863
|
+
if (hashMatch) {
|
|
2864
|
+
token = decodeURIComponent(hashMatch[1]);
|
|
2865
|
+
sessionStorage.setItem('aa_token', token);
|
|
2866
|
+
history.replaceState(null, '', location.pathname);
|
|
2867
|
+
}
|
|
2868
|
+
if (!token) {
|
|
2869
|
+
showGate(false);
|
|
2870
|
+
} else {
|
|
2871
|
+
fetchSites().then(enterApp).catch(function (e) {
|
|
2872
|
+
// 401 already shows the gate via api(); surface anything else.
|
|
2873
|
+
if (e.message !== 'unauthorized') {
|
|
2874
|
+
showGate(false);
|
|
2875
|
+
$('#gate-err').textContent = e.message;
|
|
2876
|
+
$('#gate-err').style.display = 'block';
|
|
2877
|
+
}
|
|
2878
|
+
});
|
|
2879
|
+
}
|
|
2880
|
+
})();
|
|
2881
|
+
<\/script>
|
|
2882
|
+
</body>
|
|
2883
|
+
</html>`;
|
|
2884
|
+
function serveDashboard(c) {
|
|
2885
|
+
return c.html(DASHBOARD_HTML, 200, {
|
|
2886
|
+
"Cache-Control": "no-store"
|
|
2887
|
+
});
|
|
2888
|
+
}
|
|
2889
|
+
|
|
2890
|
+
// worker/src/lib/auth.ts
|
|
2891
|
+
function timingSafeEqual(a, b) {
|
|
2892
|
+
if (a.length !== b.length) return false;
|
|
2893
|
+
const encoder = new TextEncoder();
|
|
2894
|
+
const bufA = encoder.encode(a);
|
|
2895
|
+
const bufB = encoder.encode(b);
|
|
2896
|
+
let result = 0;
|
|
2897
|
+
for (let i = 0; i < bufA.length; i++) {
|
|
2898
|
+
result |= bufA[i] ^ bufB[i];
|
|
2899
|
+
}
|
|
2900
|
+
return result === 0;
|
|
2901
|
+
}
|
|
2902
|
+
async function authMiddleware(c, next) {
|
|
2903
|
+
if (!c.env.API_SECRET) {
|
|
2904
|
+
return c.json({ error: "Server not configured: API_SECRET secret is not set. Run: lazyanalytics setup" }, 500);
|
|
2905
|
+
}
|
|
2906
|
+
const authHeader = c.req.header("Authorization");
|
|
2907
|
+
if (!authHeader) {
|
|
2908
|
+
return c.json({ error: "Missing Authorization header" }, 401);
|
|
2909
|
+
}
|
|
2910
|
+
const parts = authHeader.split(" ");
|
|
2911
|
+
if (parts.length !== 2 || parts[0] !== "Bearer") {
|
|
2912
|
+
return c.json({ error: "Invalid Authorization header format. Expected: Bearer <token>" }, 401);
|
|
2913
|
+
}
|
|
2914
|
+
const token = parts[1];
|
|
2915
|
+
if (!timingSafeEqual(token, c.env.API_SECRET)) {
|
|
2916
|
+
return c.json({ error: "Invalid API token" }, 401);
|
|
2917
|
+
}
|
|
2918
|
+
await next();
|
|
2919
|
+
}
|
|
2920
|
+
|
|
2921
|
+
// worker/src/lib/query.ts
|
|
2922
|
+
var DATASET = "agent_analytics";
|
|
2923
|
+
function parsePeriod(period) {
|
|
2924
|
+
const match2 = period.match(/^(\d+)d$/);
|
|
2925
|
+
if (!match2) {
|
|
2926
|
+
throw new Error(`Invalid period format: "${period}". Expected format: Nd (e.g., 7d, 30d, 90d)`);
|
|
2927
|
+
}
|
|
2928
|
+
const days = parseInt(match2[1], 10);
|
|
2929
|
+
if (days < 1 || days > 90) {
|
|
2930
|
+
throw new Error(`Period must be between 1d and 90d. Got: ${days}d`);
|
|
2931
|
+
}
|
|
2932
|
+
const endAt = /* @__PURE__ */ new Date();
|
|
2933
|
+
const startAt = new Date(endAt.getTime() - days * 24 * 60 * 60 * 1e3);
|
|
2934
|
+
return { startAt, endAt };
|
|
2935
|
+
}
|
|
2936
|
+
function parseAllowedSites(allowedSites) {
|
|
2937
|
+
return (allowedSites || "").split(",").map((s) => s.trim()).filter(Boolean);
|
|
2938
|
+
}
|
|
2939
|
+
function validateSite(site, allowedSites) {
|
|
2940
|
+
return parseAllowedSites(allowedSites).includes(site);
|
|
2941
|
+
}
|
|
2942
|
+
async function queryAE(env, sql) {
|
|
2943
|
+
if (!env.CF_ACCOUNT_ID || !env.CF_API_TOKEN) {
|
|
2944
|
+
throw new Error(
|
|
2945
|
+
"Server not configured: CF_ACCOUNT_ID and CF_API_TOKEN secrets are not set on the worker, so it cannot run queries"
|
|
2946
|
+
);
|
|
2947
|
+
}
|
|
2948
|
+
const url = `https://api.cloudflare.com/client/v4/accounts/${env.CF_ACCOUNT_ID}/analytics_engine/sql`;
|
|
2949
|
+
const response = await fetch(url, {
|
|
2950
|
+
method: "POST",
|
|
2951
|
+
headers: {
|
|
2952
|
+
Authorization: `Bearer ${env.CF_API_TOKEN}`,
|
|
2953
|
+
"Content-Type": "text/plain"
|
|
2954
|
+
},
|
|
2955
|
+
body: sql
|
|
2956
|
+
});
|
|
2957
|
+
if (!response.ok) {
|
|
2958
|
+
const text = await response.text();
|
|
2959
|
+
throw new Error(`Analytics Engine query failed (${response.status}): ${text}`);
|
|
2960
|
+
}
|
|
2961
|
+
const result = await response.json();
|
|
2962
|
+
return {
|
|
2963
|
+
data: result.data || [],
|
|
2964
|
+
meta: (result.meta || []).map((m) => m.name),
|
|
2965
|
+
rows: result.rows || 0
|
|
2966
|
+
};
|
|
2967
|
+
}
|
|
2968
|
+
function formatTimestamp(d) {
|
|
2969
|
+
return d.toISOString().replace("T", " ").replace(/\.\d{3}Z$/, "");
|
|
2970
|
+
}
|
|
2971
|
+
function buildWhereClause(opts) {
|
|
2972
|
+
const site = opts.site.replace(/'/g, "''");
|
|
2973
|
+
const start = formatTimestamp(opts.startAt);
|
|
2974
|
+
const end = formatTimestamp(opts.endAt);
|
|
2975
|
+
return `WHERE blob1 = '${site}' AND timestamp >= toDateTime('${start}') AND timestamp <= toDateTime('${end}')`;
|
|
2976
|
+
}
|
|
2977
|
+
function envelope(data, site, period, sampled) {
|
|
2978
|
+
return { data, meta: { site, period, sampled } };
|
|
2979
|
+
}
|
|
2980
|
+
function extractSampled(rows) {
|
|
2981
|
+
let sampled = false;
|
|
2982
|
+
const cleaned = rows.map((row) => {
|
|
2983
|
+
const { max_interval, ...rest } = row;
|
|
2984
|
+
if (Number(max_interval) > 1) sampled = true;
|
|
2985
|
+
return rest;
|
|
2986
|
+
});
|
|
2987
|
+
return { rows: cleaned, sampled };
|
|
2988
|
+
}
|
|
2989
|
+
function extractParams(c, env) {
|
|
2990
|
+
const site = c.req.query("site");
|
|
2991
|
+
const period = c.req.query("period") || "7d";
|
|
2992
|
+
const limitStr = c.req.query("limit");
|
|
2993
|
+
const limit = limitStr ? Math.min(Math.max(parseInt(limitStr, 10) || 10, 1), 100) : 10;
|
|
2994
|
+
if (!site) throw new Error("Missing required parameter: site");
|
|
2995
|
+
if (!validateSite(site, env.ALLOWED_SITES)) throw new Error(`Unknown site: ${site}`);
|
|
2996
|
+
const { startAt, endAt } = parsePeriod(period);
|
|
2997
|
+
return { site, period, limit, opts: { site, startAt, endAt } };
|
|
2998
|
+
}
|
|
2999
|
+
|
|
3000
|
+
// worker/src/api/stats.ts
|
|
3001
|
+
async function statsHandler(c) {
|
|
3002
|
+
try {
|
|
3003
|
+
const { site, period, opts } = extractParams(c, c.env);
|
|
3004
|
+
const where = buildWhereClause(opts);
|
|
3005
|
+
const sql = `
|
|
3006
|
+
SELECT
|
|
3007
|
+
SUM(_sample_interval) as pageviews,
|
|
3008
|
+
COUNT(DISTINCT index1) as approx_daily_visitors,
|
|
3009
|
+
SUM(_sample_interval * double2) / (SUM(_sample_interval) + 0.0001) as avg_screen_width,
|
|
3010
|
+
MAX(_sample_interval) as max_interval
|
|
3011
|
+
FROM ${DATASET}
|
|
3012
|
+
${where}
|
|
3013
|
+
`;
|
|
3014
|
+
const result = await queryAE(c.env, sql);
|
|
3015
|
+
const { rows, sampled } = extractSampled(result.data);
|
|
3016
|
+
const row = rows[0] || { pageviews: 0, approx_daily_visitors: 0, avg_screen_width: 0 };
|
|
3017
|
+
return c.json(envelope(row, site, period, sampled));
|
|
3018
|
+
} catch (e) {
|
|
3019
|
+
const msg = e instanceof Error && !e.message.includes("Analytics Engine") ? e.message : "Internal query error";
|
|
3020
|
+
return c.json({ error: msg }, 400);
|
|
3021
|
+
}
|
|
3022
|
+
}
|
|
3023
|
+
|
|
3024
|
+
// worker/src/api/pages.ts
|
|
3025
|
+
async function pagesHandler(c) {
|
|
3026
|
+
try {
|
|
3027
|
+
const { site, period, limit, opts } = extractParams(c, c.env);
|
|
3028
|
+
const where = buildWhereClause(opts);
|
|
3029
|
+
const sql = `
|
|
3030
|
+
SELECT
|
|
3031
|
+
blob2 as page,
|
|
3032
|
+
SUM(_sample_interval) as views,
|
|
3033
|
+
COUNT(DISTINCT index1) as approx_visitors,
|
|
3034
|
+
MAX(_sample_interval) as max_interval
|
|
3035
|
+
FROM ${DATASET}
|
|
3036
|
+
${where}
|
|
3037
|
+
AND blob2 != ''
|
|
3038
|
+
GROUP BY blob2
|
|
3039
|
+
ORDER BY views DESC
|
|
3040
|
+
LIMIT ${limit}
|
|
3041
|
+
`;
|
|
3042
|
+
const result = await queryAE(c.env, sql);
|
|
3043
|
+
const { rows, sampled } = extractSampled(result.data);
|
|
3044
|
+
return c.json(envelope(rows, site, period, sampled));
|
|
3045
|
+
} catch (e) {
|
|
3046
|
+
const msg = e instanceof Error && !e.message.includes("Analytics Engine") ? e.message : "Internal query error";
|
|
3047
|
+
return c.json({ error: msg }, 400);
|
|
3048
|
+
}
|
|
3049
|
+
}
|
|
3050
|
+
|
|
3051
|
+
// worker/src/api/referrers.ts
|
|
3052
|
+
async function referrersHandler(c) {
|
|
3053
|
+
try {
|
|
3054
|
+
const { site, period, limit, opts } = extractParams(c, c.env);
|
|
3055
|
+
const where = buildWhereClause(opts);
|
|
3056
|
+
const sql = `
|
|
3057
|
+
SELECT
|
|
3058
|
+
blob3 as referrer,
|
|
3059
|
+
SUM(_sample_interval) as views,
|
|
3060
|
+
COUNT(DISTINCT index1) as approx_visitors,
|
|
3061
|
+
MAX(_sample_interval) as max_interval
|
|
3062
|
+
FROM ${DATASET}
|
|
3063
|
+
${where}
|
|
3064
|
+
AND blob3 != ''
|
|
3065
|
+
GROUP BY blob3
|
|
3066
|
+
ORDER BY views DESC
|
|
3067
|
+
LIMIT ${limit}
|
|
3068
|
+
`;
|
|
3069
|
+
const result = await queryAE(c.env, sql);
|
|
3070
|
+
const { rows, sampled } = extractSampled(result.data);
|
|
3071
|
+
return c.json(envelope(rows, site, period, sampled));
|
|
3072
|
+
} catch (e) {
|
|
3073
|
+
const msg = e instanceof Error && !e.message.includes("Analytics Engine") ? e.message : "Internal query error";
|
|
3074
|
+
return c.json({ error: msg }, 400);
|
|
3075
|
+
}
|
|
3076
|
+
}
|
|
3077
|
+
|
|
3078
|
+
// worker/src/api/geo.ts
|
|
3079
|
+
async function geoHandler(c) {
|
|
3080
|
+
try {
|
|
3081
|
+
const { site, period, limit, opts } = extractParams(c, c.env);
|
|
3082
|
+
const where = buildWhereClause(opts);
|
|
3083
|
+
const sql = `
|
|
3084
|
+
SELECT
|
|
3085
|
+
blob4 as country,
|
|
3086
|
+
SUM(_sample_interval) as views,
|
|
3087
|
+
COUNT(DISTINCT index1) as approx_visitors,
|
|
3088
|
+
MAX(_sample_interval) as max_interval
|
|
3089
|
+
FROM ${DATASET}
|
|
3090
|
+
${where}
|
|
3091
|
+
AND blob4 != '' AND blob4 != 'XX'
|
|
3092
|
+
GROUP BY blob4
|
|
3093
|
+
ORDER BY views DESC
|
|
3094
|
+
LIMIT ${limit}
|
|
3095
|
+
`;
|
|
3096
|
+
const result = await queryAE(c.env, sql);
|
|
3097
|
+
const { rows, sampled } = extractSampled(result.data);
|
|
3098
|
+
return c.json(envelope(rows, site, period, sampled));
|
|
3099
|
+
} catch (e) {
|
|
3100
|
+
const msg = e instanceof Error && !e.message.includes("Analytics Engine") ? e.message : "Internal query error";
|
|
3101
|
+
return c.json({ error: msg }, 400);
|
|
3102
|
+
}
|
|
3103
|
+
}
|
|
3104
|
+
|
|
3105
|
+
// worker/src/api/browsers.ts
|
|
3106
|
+
async function browsersHandler(c) {
|
|
3107
|
+
try {
|
|
3108
|
+
const { site, period, limit, opts } = extractParams(c, c.env);
|
|
3109
|
+
const where = buildWhereClause(opts);
|
|
3110
|
+
const type = c.req.query("type") || "browser";
|
|
3111
|
+
let groupCol;
|
|
3112
|
+
switch (type) {
|
|
3113
|
+
case "os":
|
|
3114
|
+
groupCol = "blob6";
|
|
3115
|
+
break;
|
|
3116
|
+
case "device":
|
|
3117
|
+
groupCol = "blob7";
|
|
3118
|
+
break;
|
|
3119
|
+
default:
|
|
3120
|
+
groupCol = "blob5";
|
|
3121
|
+
}
|
|
3122
|
+
const sql = `
|
|
3123
|
+
SELECT
|
|
3124
|
+
${groupCol} as name,
|
|
3125
|
+
SUM(_sample_interval) as views,
|
|
3126
|
+
COUNT(DISTINCT index1) as approx_visitors,
|
|
3127
|
+
MAX(_sample_interval) as max_interval
|
|
3128
|
+
FROM ${DATASET}
|
|
3129
|
+
${where}
|
|
3130
|
+
AND ${groupCol} != ''
|
|
3131
|
+
GROUP BY ${groupCol}
|
|
3132
|
+
ORDER BY views DESC
|
|
3133
|
+
LIMIT ${limit}
|
|
3134
|
+
`;
|
|
3135
|
+
const result = await queryAE(c.env, sql);
|
|
3136
|
+
const { rows, sampled } = extractSampled(result.data);
|
|
3137
|
+
return c.json(envelope(rows, site, period, sampled));
|
|
3138
|
+
} catch (e) {
|
|
3139
|
+
const msg = e instanceof Error && !e.message.includes("Analytics Engine") ? e.message : "Internal query error";
|
|
3140
|
+
return c.json({ error: msg }, 400);
|
|
3141
|
+
}
|
|
3142
|
+
}
|
|
3143
|
+
|
|
3144
|
+
// worker/src/api/timeseries.ts
|
|
3145
|
+
async function timeseriesHandler(c) {
|
|
3146
|
+
try {
|
|
3147
|
+
const { site, period, opts } = extractParams(c, c.env);
|
|
3148
|
+
const unit = c.req.query("unit") || "day";
|
|
3149
|
+
const where = buildWhereClause(opts);
|
|
3150
|
+
let bucketSeconds;
|
|
3151
|
+
switch (unit) {
|
|
3152
|
+
case "hour":
|
|
3153
|
+
bucketSeconds = 3600;
|
|
3154
|
+
break;
|
|
3155
|
+
case "day":
|
|
3156
|
+
bucketSeconds = 86400;
|
|
3157
|
+
break;
|
|
3158
|
+
default:
|
|
3159
|
+
return c.json({ error: "Invalid unit. Supported: hour, day" }, 400);
|
|
3160
|
+
}
|
|
3161
|
+
const sql = `
|
|
3162
|
+
SELECT
|
|
3163
|
+
intDiv(toUInt32(timestamp), ${bucketSeconds}) * ${bucketSeconds} as t,
|
|
3164
|
+
SUM(_sample_interval) as views,
|
|
3165
|
+
COUNT(DISTINCT index1) as approx_visitors,
|
|
3166
|
+
MAX(_sample_interval) as max_interval
|
|
3167
|
+
FROM ${DATASET}
|
|
3168
|
+
${where}
|
|
3169
|
+
GROUP BY t
|
|
3170
|
+
ORDER BY t ASC
|
|
3171
|
+
`;
|
|
3172
|
+
const result = await queryAE(c.env, sql);
|
|
3173
|
+
const { rows, sampled } = extractSampled(result.data);
|
|
3174
|
+
const data = rows.map((row) => ({
|
|
3175
|
+
timestamp: new Date(row.t * 1e3).toISOString(),
|
|
3176
|
+
views: row.views,
|
|
3177
|
+
approx_visitors: row.approx_visitors
|
|
3178
|
+
}));
|
|
3179
|
+
return c.json(envelope(data, site, period, sampled));
|
|
3180
|
+
} catch (e) {
|
|
3181
|
+
const msg = e instanceof Error && !e.message.includes("Analytics Engine") ? e.message : "Internal query error";
|
|
3182
|
+
return c.json({ error: msg }, 400);
|
|
3183
|
+
}
|
|
3184
|
+
}
|
|
3185
|
+
|
|
3186
|
+
// worker/src/api/sites.ts
|
|
3187
|
+
async function sitesHandler(c) {
|
|
3188
|
+
const sites = parseAllowedSites(c.env.ALLOWED_SITES);
|
|
3189
|
+
const meta = { count: sites.length };
|
|
3190
|
+
if (sites.length === 0) {
|
|
3191
|
+
meta.hint = "No sites configured. Run: lazyanalytics sites add <domain> (or set ALLOWED_SITES in wrangler.toml and redeploy).";
|
|
3192
|
+
}
|
|
3193
|
+
return c.json({
|
|
3194
|
+
data: sites.map((site) => ({ site })),
|
|
3195
|
+
meta
|
|
3196
|
+
});
|
|
3197
|
+
}
|
|
3198
|
+
|
|
3199
|
+
// worker/src/version.ts
|
|
3200
|
+
var VERSION = true ? "0.1.0" : "0.1.0";
|
|
3201
|
+
|
|
3202
|
+
// worker/src/index.ts
|
|
3203
|
+
var app = new Hono2();
|
|
3204
|
+
app.use("/api/*", cors());
|
|
3205
|
+
app.use("/collect", cors());
|
|
3206
|
+
app.get("/tracker.js", serveTracker);
|
|
3207
|
+
app.post("/collect", collect);
|
|
3208
|
+
app.get("/dashboard", serveDashboard);
|
|
3209
|
+
app.use("/api/*", authMiddleware);
|
|
3210
|
+
app.get("/api/stats", statsHandler);
|
|
3211
|
+
app.get("/api/pages", pagesHandler);
|
|
3212
|
+
app.get("/api/referrers", referrersHandler);
|
|
3213
|
+
app.get("/api/geo", geoHandler);
|
|
3214
|
+
app.get("/api/browsers", browsersHandler);
|
|
3215
|
+
app.get("/api/timeseries", timeseriesHandler);
|
|
3216
|
+
app.get("/api/sites", sitesHandler);
|
|
3217
|
+
app.get("/health", (c) => c.json({ status: "ok", version: VERSION, timestamp: (/* @__PURE__ */ new Date()).toISOString() }));
|
|
3218
|
+
var index_default = app;
|
|
3219
|
+
export {
|
|
3220
|
+
index_default as default
|
|
3221
|
+
};
|