@ezlogs/server 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2026 dezsirazvan
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,79 @@
1
- # Temporary Holding Version
1
+ # @ezlogs/server
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Makes what your app's server code does read as the work of the person whose click asked for it, in
4
+ [EZLogs](https://ezlogs.io): "Ana archived 3 tasks", not "App server updated 3 tasks".
5
+
6
+ For apps on Supabase (Lovable, Bolt, v0) with server code: TanStack Start server functions, or
7
+ Supabase Edge Functions. It works with [@ezlogs/browser](https://www.npmjs.com/package/@ezlogs/browser)
8
+ 0.4.0 or later and the EZLogs database install.
9
+
10
+ ## What it does
11
+
12
+ Per request to your server code:
13
+
14
+ - it reads the click's id that @ezlogs/browser put on the request (`x-correlation-id`, EZLogs' own
15
+ format only, at most an hour old), or starts one for the request;
16
+ - it adds that id to the calls your server makes to your Supabase project, through a client created
17
+ with `global: { fetch: ezlogsFetch() }`, so the rows that request writes join the click;
18
+ - it answers with `x-ezlogs: 1` and the id its work used (`x-ezlogs-correlation`), so the browser
19
+ module can say which click that work belongs to. An Edge Function is never sent a new header (its
20
+ CORS could refuse it): it starts its own id, and its answer carries it.
21
+
22
+ It sends nothing to EZLogs, reads no request body, keeps nothing, and never changes what your code
23
+ receives or returns, apart from those two response headers (exposed to the browser only when your
24
+ function already answers CORS). If anything in it fails, your code runs as without it. A timer or
25
+ queue started inside a request stops carrying its id 5 minutes after the request began.
26
+
27
+ ## Install
28
+
29
+ ```sh
30
+ npm install @ezlogs/server
31
+ ```
32
+
33
+ ### TanStack Start
34
+
35
+ ```ts
36
+ // src/start.ts
37
+ import { createStart } from "@tanstack/react-start";
38
+ import { ezlogsMiddleware } from "@ezlogs/server/tanstack";
39
+
40
+ export const startInstance = createStart(() => ({
41
+ requestMiddleware: [ezlogsMiddleware /* , ...your other request middleware */],
42
+ }));
43
+ ```
44
+
45
+ Then give every Supabase client created on the server the fetch:
46
+
47
+ ```ts
48
+ import { createClient } from "@supabase/supabase-js";
49
+ import { ezlogsFetch } from "@ezlogs/server";
50
+
51
+ export const supabaseAdmin = createClient(url, serviceRoleKey, {
52
+ global: { fetch: ezlogsFetch() }, // or ezlogsFetch(theFetchYouAlreadyPass)
53
+ });
54
+ ```
55
+
56
+ ### Supabase Edge Functions
57
+
58
+ ```ts
59
+ import { withEzlogs, ezlogsFetch } from "npm:@ezlogs/server@0.1";
60
+ import { createClient } from "npm:@supabase/supabase-js@2";
61
+
62
+ Deno.serve(withEzlogs(async (req) => {
63
+ const supabase = createClient(Deno.env.get("SUPABASE_URL")!, Deno.env.get("SUPABASE_SERVICE_ROLE_KEY")!, {
64
+ global: { fetch: ezlogsFetch() },
65
+ });
66
+ // ...your function, unchanged
67
+ }));
68
+ ```
69
+
70
+ Only calls that can change data are reported by the browser (POST, PUT, PATCH, DELETE): a server
71
+ function left on TanStack's default GET that writes keeps reading as "App server"; give a function
72
+ that changes data `createServerFn({ method: "POST" })`.
73
+
74
+ Runs on Node, Deno (Supabase Edge Functions) and Cloudflare Workers with Node compatibility (Lovable's
75
+ hosting), anywhere `node:async_hooks` AsyncLocalStorage exists. Never import it in browser code.
76
+
77
+ ## License
78
+
79
+ MIT. See [LICENSE](LICENSE).
@@ -0,0 +1,83 @@
1
+ import { AsyncLocalStorage } from 'async_hooks';
2
+
3
+ // src/index.ts
4
+ var HEADER = "x-correlation-id";
5
+ var CLICK = /^ezl_(\d{13})_[0-9a-f]{8}$/;
6
+ var MAX_AGE_MS = 60 * 60 * 1e3;
7
+ var MAX_AHEAD_MS = 5 * 60 * 1e3;
8
+ var STORE = /* @__PURE__ */ Symbol.for("ezlogs.server.store");
9
+ var REQUEST_MAX_MS = 5 * 60 * 1e3;
10
+ var g = globalThis;
11
+ var storage = g[STORE] ??= new AsyncLocalStorage();
12
+ function clickIdOf(headers, now = Date.now()) {
13
+ try {
14
+ const sent = headers?.get(HEADER)?.trim() ?? "";
15
+ const at = Number(CLICK.exec(sent)?.[1]);
16
+ if (at && at > now - MAX_AGE_MS && at < now + MAX_AHEAD_MS) return sent;
17
+ } catch {
18
+ }
19
+ return newClickId(now);
20
+ }
21
+ function currentClickId() {
22
+ const store = storage.getStore();
23
+ return store && Date.now() - store.started <= REQUEST_MAX_MS ? store.id : void 0;
24
+ }
25
+ function runWithClick(request, fn) {
26
+ let id;
27
+ try {
28
+ id = clickIdOf(request.headers);
29
+ } catch {
30
+ return fn();
31
+ }
32
+ return storage.run({ id, started: Date.now() }, fn);
33
+ }
34
+ function ezlogsFetch(base) {
35
+ return function ezlogsFetch2(input, init) {
36
+ const target = base ?? globalThis.fetch;
37
+ let args = [input, init];
38
+ try {
39
+ const id = currentClickId();
40
+ if (id) {
41
+ const headers = new Headers(init?.headers ?? (input instanceof Request ? input.headers : void 0));
42
+ if (!headers.has(HEADER)) {
43
+ headers.set(HEADER, id);
44
+ args = [input, { ...init, headers }];
45
+ }
46
+ }
47
+ } catch {
48
+ args = [input, init];
49
+ }
50
+ return target(...args);
51
+ };
52
+ }
53
+ function withEzlogs(handler) {
54
+ return async (request, ...rest) => {
55
+ let id;
56
+ const response = await runWithClick(request, () => {
57
+ id = currentClickId();
58
+ return handler(request, ...rest);
59
+ });
60
+ try {
61
+ return marked(response, id);
62
+ } catch {
63
+ return response;
64
+ }
65
+ };
66
+ }
67
+ function marked(response, id) {
68
+ const headers = new Headers(response.headers);
69
+ headers.set("x-ezlogs", "1");
70
+ if (id) headers.set("x-ezlogs-correlation", id);
71
+ const exposed = headers.get("access-control-expose-headers") ?? "";
72
+ if (headers.has("access-control-allow-origin") && !/(^|,)\s*x-ezlogs-correlation\s*(,|$)/i.test(exposed)) {
73
+ headers.set("access-control-expose-headers", exposed ? `${exposed}, x-ezlogs, x-ezlogs-correlation` : "x-ezlogs, x-ezlogs-correlation");
74
+ }
75
+ return new Response(response.body, { status: response.status, statusText: response.statusText, headers });
76
+ }
77
+ function newClickId(now) {
78
+ const bytes = new Uint8Array(4);
79
+ globalThis.crypto.getRandomValues(bytes);
80
+ return `ezl_${now}_${Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("")}`;
81
+ }
82
+
83
+ export { clickIdOf, currentClickId, ezlogsFetch, runWithClick, withEzlogs };
package/dist/index.cjs ADDED
@@ -0,0 +1,89 @@
1
+ 'use strict';
2
+
3
+ var async_hooks = require('async_hooks');
4
+
5
+ // src/index.ts
6
+ var HEADER = "x-correlation-id";
7
+ var CLICK = /^ezl_(\d{13})_[0-9a-f]{8}$/;
8
+ var MAX_AGE_MS = 60 * 60 * 1e3;
9
+ var MAX_AHEAD_MS = 5 * 60 * 1e3;
10
+ var STORE = /* @__PURE__ */ Symbol.for("ezlogs.server.store");
11
+ var REQUEST_MAX_MS = 5 * 60 * 1e3;
12
+ var g = globalThis;
13
+ var storage = g[STORE] ??= new async_hooks.AsyncLocalStorage();
14
+ function clickIdOf(headers, now = Date.now()) {
15
+ try {
16
+ const sent = headers?.get(HEADER)?.trim() ?? "";
17
+ const at = Number(CLICK.exec(sent)?.[1]);
18
+ if (at && at > now - MAX_AGE_MS && at < now + MAX_AHEAD_MS) return sent;
19
+ } catch {
20
+ }
21
+ return newClickId(now);
22
+ }
23
+ function currentClickId() {
24
+ const store = storage.getStore();
25
+ return store && Date.now() - store.started <= REQUEST_MAX_MS ? store.id : void 0;
26
+ }
27
+ function runWithClick(request, fn) {
28
+ let id;
29
+ try {
30
+ id = clickIdOf(request.headers);
31
+ } catch {
32
+ return fn();
33
+ }
34
+ return storage.run({ id, started: Date.now() }, fn);
35
+ }
36
+ function ezlogsFetch(base) {
37
+ return function ezlogsFetch2(input, init) {
38
+ const target = base ?? globalThis.fetch;
39
+ let args = [input, init];
40
+ try {
41
+ const id = currentClickId();
42
+ if (id) {
43
+ const headers = new Headers(init?.headers ?? (input instanceof Request ? input.headers : void 0));
44
+ if (!headers.has(HEADER)) {
45
+ headers.set(HEADER, id);
46
+ args = [input, { ...init, headers }];
47
+ }
48
+ }
49
+ } catch {
50
+ args = [input, init];
51
+ }
52
+ return target(...args);
53
+ };
54
+ }
55
+ function withEzlogs(handler) {
56
+ return async (request, ...rest) => {
57
+ let id;
58
+ const response = await runWithClick(request, () => {
59
+ id = currentClickId();
60
+ return handler(request, ...rest);
61
+ });
62
+ try {
63
+ return marked(response, id);
64
+ } catch {
65
+ return response;
66
+ }
67
+ };
68
+ }
69
+ function marked(response, id) {
70
+ const headers = new Headers(response.headers);
71
+ headers.set("x-ezlogs", "1");
72
+ if (id) headers.set("x-ezlogs-correlation", id);
73
+ const exposed = headers.get("access-control-expose-headers") ?? "";
74
+ if (headers.has("access-control-allow-origin") && !/(^|,)\s*x-ezlogs-correlation\s*(,|$)/i.test(exposed)) {
75
+ headers.set("access-control-expose-headers", exposed ? `${exposed}, x-ezlogs, x-ezlogs-correlation` : "x-ezlogs, x-ezlogs-correlation");
76
+ }
77
+ return new Response(response.body, { status: response.status, statusText: response.statusText, headers });
78
+ }
79
+ function newClickId(now) {
80
+ const bytes = new Uint8Array(4);
81
+ globalThis.crypto.getRandomValues(bytes);
82
+ return `ezl_${now}_${Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("")}`;
83
+ }
84
+
85
+ exports.clickIdOf = clickIdOf;
86
+ exports.currentClickId = currentClickId;
87
+ exports.ezlogsFetch = ezlogsFetch;
88
+ exports.runWithClick = runWithClick;
89
+ exports.withEzlogs = withEzlogs;
@@ -0,0 +1,22 @@
1
+ type Fetch = typeof fetch;
2
+ /** The click's id for a request: the browser's, when it is EZLogs' own and fresh; else a new one. */
3
+ declare function clickIdOf(headers: Headers | undefined, now?: number): string;
4
+ /** The current request's click id, if code runs inside one (and the request is recent). */
5
+ declare function currentClickId(): string | undefined;
6
+ /** Runs `fn` as part of the request's click: the Supabase calls it makes through ezlogsFetch carry it. */
7
+ declare function runWithClick<T>(request: Request, fn: () => T): T;
8
+ /**
9
+ * A fetch for your Supabase client: `createClient(url, key, { global: { fetch: ezlogsFetch() } })`.
10
+ * Pass the fetch the client used before, if it had one: `ezlogsFetch(createSupabaseFetch(key))`.
11
+ * Inside a request it adds the click's id (unless the call already has one); otherwise it is
12
+ * exactly that fetch.
13
+ */
14
+ declare function ezlogsFetch(base?: Fetch): Fetch;
15
+ /**
16
+ * For a Supabase Edge Function: `Deno.serve(withEzlogs(async (req) => { ... }))`. The handler runs
17
+ * with its own click id (the browser never sends an Edge Function a header its CORS might refuse);
18
+ * its answer carries `x-ezlogs: 1` and that id, which the browser module reports with the click.
19
+ */
20
+ declare function withEzlogs<A extends unknown[]>(handler: (request: Request, ...rest: A) => Response | Promise<Response>): (request: Request, ...rest: A) => Promise<Response>;
21
+
22
+ export { clickIdOf, currentClickId, ezlogsFetch, runWithClick, withEzlogs };
@@ -0,0 +1,22 @@
1
+ type Fetch = typeof fetch;
2
+ /** The click's id for a request: the browser's, when it is EZLogs' own and fresh; else a new one. */
3
+ declare function clickIdOf(headers: Headers | undefined, now?: number): string;
4
+ /** The current request's click id, if code runs inside one (and the request is recent). */
5
+ declare function currentClickId(): string | undefined;
6
+ /** Runs `fn` as part of the request's click: the Supabase calls it makes through ezlogsFetch carry it. */
7
+ declare function runWithClick<T>(request: Request, fn: () => T): T;
8
+ /**
9
+ * A fetch for your Supabase client: `createClient(url, key, { global: { fetch: ezlogsFetch() } })`.
10
+ * Pass the fetch the client used before, if it had one: `ezlogsFetch(createSupabaseFetch(key))`.
11
+ * Inside a request it adds the click's id (unless the call already has one); otherwise it is
12
+ * exactly that fetch.
13
+ */
14
+ declare function ezlogsFetch(base?: Fetch): Fetch;
15
+ /**
16
+ * For a Supabase Edge Function: `Deno.serve(withEzlogs(async (req) => { ... }))`. The handler runs
17
+ * with its own click id (the browser never sends an Edge Function a header its CORS might refuse);
18
+ * its answer carries `x-ezlogs: 1` and that id, which the browser module reports with the click.
19
+ */
20
+ declare function withEzlogs<A extends unknown[]>(handler: (request: Request, ...rest: A) => Response | Promise<Response>): (request: Request, ...rest: A) => Promise<Response>;
21
+
22
+ export { clickIdOf, currentClickId, ezlogsFetch, runWithClick, withEzlogs };
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ export { clickIdOf, currentClickId, ezlogsFetch, runWithClick, withEzlogs } from './chunk-CHHNBWTX.js';
@@ -0,0 +1,71 @@
1
+ 'use strict';
2
+
3
+ var reactStart = require('@tanstack/react-start');
4
+ var server = require('@tanstack/react-start/server');
5
+ var async_hooks = require('async_hooks');
6
+
7
+ // src/tanstack.ts
8
+ var HEADER = "x-correlation-id";
9
+ var CLICK = /^ezl_(\d{13})_[0-9a-f]{8}$/;
10
+ var MAX_AGE_MS = 60 * 60 * 1e3;
11
+ var MAX_AHEAD_MS = 5 * 60 * 1e3;
12
+ var STORE = /* @__PURE__ */ Symbol.for("ezlogs.server.store");
13
+ var REQUEST_MAX_MS = 5 * 60 * 1e3;
14
+ var g = globalThis;
15
+ var storage = g[STORE] ??= new async_hooks.AsyncLocalStorage();
16
+ function clickIdOf(headers, now = Date.now()) {
17
+ try {
18
+ const sent = headers?.get(HEADER)?.trim() ?? "";
19
+ const at = Number(CLICK.exec(sent)?.[1]);
20
+ if (at && at > now - MAX_AGE_MS && at < now + MAX_AHEAD_MS) return sent;
21
+ } catch {
22
+ }
23
+ return newClickId(now);
24
+ }
25
+ function currentClickId() {
26
+ const store = storage.getStore();
27
+ return store && Date.now() - store.started <= REQUEST_MAX_MS ? store.id : void 0;
28
+ }
29
+ function runWithClick(request, fn) {
30
+ let id;
31
+ try {
32
+ id = clickIdOf(request.headers);
33
+ } catch {
34
+ return fn();
35
+ }
36
+ return storage.run({ id, started: Date.now() }, fn);
37
+ }
38
+ function newClickId(now) {
39
+ const bytes = new Uint8Array(4);
40
+ globalThis.crypto.getRandomValues(bytes);
41
+ return `ezl_${now}_${Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("")}`;
42
+ }
43
+
44
+ // src/tanstack.ts
45
+ var SERVER_FUNCTION = /^\/_serverFn\//;
46
+ var ezlogsMiddleware = reactStart.createMiddleware().server(({ request, next }) => {
47
+ let serverFunction = false;
48
+ try {
49
+ serverFunction = SERVER_FUNCTION.test(new URL(request.url).pathname);
50
+ } catch {
51
+ serverFunction = false;
52
+ }
53
+ if (!serverFunction) return next();
54
+ return runWithClick(request, async () => {
55
+ const id = currentClickId();
56
+ try {
57
+ server.setResponseHeader("x-ezlogs", "1");
58
+ if (id) server.setResponseHeader("x-ezlogs-correlation", id);
59
+ } catch {
60
+ }
61
+ const result = await next();
62
+ try {
63
+ result?.response?.headers.set("x-ezlogs", "1");
64
+ if (id) result?.response?.headers.set("x-ezlogs-correlation", id);
65
+ } catch {
66
+ }
67
+ return result;
68
+ });
69
+ });
70
+
71
+ exports.ezlogsMiddleware = ezlogsMiddleware;
@@ -0,0 +1,3 @@
1
+ declare const ezlogsMiddleware: any;
2
+
3
+ export { ezlogsMiddleware };
@@ -0,0 +1,3 @@
1
+ declare const ezlogsMiddleware: any;
2
+
3
+ export { ezlogsMiddleware };
@@ -0,0 +1,31 @@
1
+ import { runWithClick, currentClickId } from './chunk-CHHNBWTX.js';
2
+ import { createMiddleware } from '@tanstack/react-start';
3
+ import { setResponseHeader } from '@tanstack/react-start/server';
4
+
5
+ var SERVER_FUNCTION = /^\/_serverFn\//;
6
+ var ezlogsMiddleware = createMiddleware().server(({ request, next }) => {
7
+ let serverFunction = false;
8
+ try {
9
+ serverFunction = SERVER_FUNCTION.test(new URL(request.url).pathname);
10
+ } catch {
11
+ serverFunction = false;
12
+ }
13
+ if (!serverFunction) return next();
14
+ return runWithClick(request, async () => {
15
+ const id = currentClickId();
16
+ try {
17
+ setResponseHeader("x-ezlogs", "1");
18
+ if (id) setResponseHeader("x-ezlogs-correlation", id);
19
+ } catch {
20
+ }
21
+ const result = await next();
22
+ try {
23
+ result?.response?.headers.set("x-ezlogs", "1");
24
+ if (id) result?.response?.headers.set("x-ezlogs-correlation", id);
25
+ } catch {
26
+ }
27
+ return result;
28
+ });
29
+ });
30
+
31
+ export { ezlogsMiddleware };
package/package.json CHANGED
@@ -1,6 +1,45 @@
1
1
  {
2
2
  "name": "@ezlogs/server",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Joins what your app's server code does to the click that asked for it, in EZLogs. Sends nothing, never changes your code's results.",
5
+ "type": "module",
6
+ "exports": {
7
+ ".": {
8
+ "import": { "types": "./dist/index.d.ts", "default": "./dist/index.js" },
9
+ "require": { "types": "./dist/index.d.cts", "default": "./dist/index.cjs" }
10
+ },
11
+ "./tanstack": {
12
+ "import": { "types": "./dist/tanstack.d.ts", "default": "./dist/tanstack.js" },
13
+ "require": { "types": "./dist/tanstack.d.cts", "default": "./dist/tanstack.cjs" }
14
+ }
15
+ },
16
+ "main": "./dist/index.cjs",
17
+ "module": "./dist/index.js",
18
+ "types": "./dist/index.d.ts",
19
+ "files": ["dist", "README.md", "LICENSE"],
20
+ "scripts": {
21
+ "build": "tsup",
22
+ "test": "vitest run",
23
+ "typecheck": "tsc --noEmit",
24
+ "pack:dry": "npm pack --dry-run",
25
+ "prepublishOnly": "npm run build && npm test"
26
+ },
27
+ "peerDependencies": {
28
+ "@tanstack/react-start": ">=1.169.0"
29
+ },
30
+ "peerDependenciesMeta": {
31
+ "@tanstack/react-start": { "optional": true }
32
+ },
33
+ "devDependencies": {
34
+ "@types/node": "20.19.40",
35
+ "tsup": "8.5.1",
36
+ "typescript": "5.9.3",
37
+ "vitest": "4.1.12"
38
+ },
39
+ "keywords": ["ezlogs", "supabase", "lovable", "tanstack-start", "edge-functions", "activity-log", "audit-log"],
40
+ "license": "MIT",
41
+ "repository": { "type": "git", "url": "https://github.com/dezsirazvan/ez_logs_server_js.git" },
42
+ "homepage": "https://ezlogs.io",
43
+ "sideEffects": false,
44
+ "publishConfig": { "access": "public" }
45
+ }