@every-app/sdk 0.1.13 → 0.2.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/dist/internal/identity.d.ts +73 -0
- package/dist/internal/identity.d.ts.map +1 -0
- package/dist/internal/identity.js +192 -0
- package/dist/internal/index.d.ts +3 -0
- package/dist/internal/index.d.ts.map +1 -0
- package/dist/internal/index.js +2 -0
- package/dist/internal/protocol.d.ts +111 -0
- package/dist/internal/protocol.d.ts.map +1 -0
- package/dist/internal/protocol.js +139 -0
- package/dist/server/everyApp.d.ts +55 -0
- package/dist/server/everyApp.d.ts.map +1 -0
- package/dist/server/everyApp.js +121 -0
- package/dist/server/gatewayFetch.d.ts +21 -0
- package/dist/server/gatewayFetch.d.ts.map +1 -0
- package/dist/server/gatewayFetch.js +70 -0
- package/dist/server/index.d.ts +9 -0
- package/dist/server/index.d.ts.map +1 -0
- package/dist/server/index.js +8 -0
- package/dist/server/mcp.d.ts +66 -0
- package/dist/server/mcp.d.ts.map +1 -0
- package/dist/server/mcp.js +147 -0
- package/package.json +21 -44
- package/dist/cloudflare/getLocalD1Url.d.ts +0 -2
- package/dist/cloudflare/getLocalD1Url.d.ts.map +0 -1
- package/dist/cloudflare/getLocalD1Url.js +0 -40
- package/dist/cloudflare/index.d.ts +0 -2
- package/dist/cloudflare/index.d.ts.map +0 -1
- package/dist/cloudflare/index.js +0 -1
- package/dist/cloudflare/lazyInit.d.ts +0 -22
- package/dist/cloudflare/lazyInit.d.ts.map +0 -1
- package/dist/cloudflare/lazyInit.js +0 -65
- package/dist/cloudflare/server/gateway.d.ts +0 -29
- package/dist/cloudflare/server/gateway.d.ts.map +0 -1
- package/dist/cloudflare/server/gateway.js +0 -69
- package/dist/cloudflare/server/index.d.ts +0 -3
- package/dist/cloudflare/server/index.d.ts.map +0 -1
- package/dist/cloudflare/server/index.js +0 -2
- package/dist/core/authenticatedFetch.d.ts +0 -9
- package/dist/core/authenticatedFetch.d.ts.map +0 -1
- package/dist/core/authenticatedFetch.js +0 -31
- package/dist/core/index.d.ts +0 -4
- package/dist/core/index.d.ts.map +0 -1
- package/dist/core/index.js +0 -2
- package/dist/core/sessionManager.d.ts +0 -58
- package/dist/core/sessionManager.d.ts.map +0 -1
- package/dist/core/sessionManager.js +0 -357
- package/dist/shared/bypassGatewayLocalOnly.d.ts +0 -14
- package/dist/shared/bypassGatewayLocalOnly.d.ts.map +0 -1
- package/dist/shared/bypassGatewayLocalOnly.js +0 -41
- package/dist/shared/parseMessagePayload.d.ts +0 -3
- package/dist/shared/parseMessagePayload.d.ts.map +0 -1
- package/dist/shared/parseMessagePayload.js +0 -18
- package/dist/tanstack/EmbeddedAppProvider.d.ts +0 -30
- package/dist/tanstack/EmbeddedAppProvider.d.ts.map +0 -1
- package/dist/tanstack/EmbeddedAppProvider.js +0 -57
- package/dist/tanstack/GatewayRequiredError.d.ts +0 -20
- package/dist/tanstack/GatewayRequiredError.d.ts.map +0 -1
- package/dist/tanstack/GatewayRequiredError.js +0 -91
- package/dist/tanstack/_internal/useEveryAppSession.d.ts +0 -18
- package/dist/tanstack/_internal/useEveryAppSession.d.ts.map +0 -1
- package/dist/tanstack/_internal/useEveryAppSession.js +0 -47
- package/dist/tanstack/index.d.ts +0 -4
- package/dist/tanstack/index.d.ts.map +0 -1
- package/dist/tanstack/index.js +0 -3
- package/dist/tanstack/server/authConfig.d.ts +0 -3
- package/dist/tanstack/server/authConfig.d.ts.map +0 -1
- package/dist/tanstack/server/authConfig.js +0 -13
- package/dist/tanstack/server/authenticateRequest.d.ts +0 -29
- package/dist/tanstack/server/authenticateRequest.d.ts.map +0 -1
- package/dist/tanstack/server/authenticateRequest.js +0 -82
- package/dist/tanstack/server/index.d.ts +0 -4
- package/dist/tanstack/server/index.d.ts.map +0 -1
- package/dist/tanstack/server/index.js +0 -2
- package/dist/tanstack/server/types.d.ts +0 -5
- package/dist/tanstack/server/types.d.ts.map +0 -1
- package/dist/tanstack/server/types.js +0 -1
- package/dist/tanstack/useEveryAppRouter.d.ts +0 -7
- package/dist/tanstack/useEveryAppRouter.d.ts.map +0 -1
- package/dist/tanstack/useEveryAppRouter.js +0 -66
- package/dist/tanstack/useSessionTokenClientMiddleware.d.ts +0 -2
- package/dist/tanstack/useSessionTokenClientMiddleware.d.ts.map +0 -1
- package/dist/tanstack/useSessionTokenClientMiddleware.js +0 -29
- package/src/cloudflare/getLocalD1Url.ts +0 -64
- package/src/cloudflare/index.ts +0 -1
- package/src/cloudflare/lazyInit.ts +0 -67
- package/src/cloudflare/server/gateway.test.ts +0 -262
- package/src/cloudflare/server/gateway.ts +0 -114
- package/src/cloudflare/server/index.ts +0 -2
- package/src/core/authenticatedFetch.ts +0 -54
- package/src/core/index.ts +0 -12
- package/src/core/sessionManager.test.ts +0 -939
- package/src/core/sessionManager.ts +0 -492
- package/src/env.d.ts +0 -13
- package/src/shared/bypassGatewayLocalOnly.ts +0 -55
- package/src/shared/parseMessagePayload.ts +0 -22
- package/src/tanstack/EmbeddedAppProvider.tsx +0 -96
- package/src/tanstack/GatewayRequiredError.tsx +0 -150
- package/src/tanstack/_internal/useEveryAppSession.test.ts +0 -40
- package/src/tanstack/_internal/useEveryAppSession.tsx +0 -74
- package/src/tanstack/index.ts +0 -3
- package/src/tanstack/server/authConfig.ts +0 -19
- package/src/tanstack/server/authenticateRequest.test.ts +0 -482
- package/src/tanstack/server/authenticateRequest.ts +0 -143
- package/src/tanstack/server/index.ts +0 -3
- package/src/tanstack/server/types.ts +0 -4
- package/src/tanstack/useEveryAppRouter.tsx +0 -83
- package/src/tanstack/useSessionTokenClientMiddleware.ts +0 -43
|
@@ -1,64 +0,0 @@
|
|
|
1
|
-
import fs from "fs";
|
|
2
|
-
import path from "path";
|
|
3
|
-
import { execSync } from "child_process";
|
|
4
|
-
import { parse } from "jsonc-parser";
|
|
5
|
-
|
|
6
|
-
function findSqliteFile(basePath: string): string | undefined {
|
|
7
|
-
return fs
|
|
8
|
-
.readdirSync(basePath, { encoding: "utf-8", recursive: true })
|
|
9
|
-
.find((f) => f.endsWith(".sqlite"));
|
|
10
|
-
}
|
|
11
|
-
|
|
12
|
-
export function getLocalD1Url() {
|
|
13
|
-
const basePath = path.resolve(".wrangler");
|
|
14
|
-
|
|
15
|
-
// Check if .wrangler directory exists
|
|
16
|
-
if (!fs.existsSync(basePath)) {
|
|
17
|
-
console.error(
|
|
18
|
-
"================================================================================",
|
|
19
|
-
);
|
|
20
|
-
console.error("WARNING: .wrangler directory not found");
|
|
21
|
-
console.error("This is expected in CI/non-development environments.");
|
|
22
|
-
console.error(
|
|
23
|
-
"The local D1 database is only available after running 'wrangler dev' which you can trigger by running 'npm run dev'.",
|
|
24
|
-
);
|
|
25
|
-
console.error(
|
|
26
|
-
"================================================================================",
|
|
27
|
-
);
|
|
28
|
-
return null;
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
let dbFile = findSqliteFile(basePath);
|
|
32
|
-
|
|
33
|
-
if (!dbFile) {
|
|
34
|
-
// Read wrangler.jsonc to get the database name
|
|
35
|
-
const wranglerConfigPath = path.resolve("wrangler.jsonc");
|
|
36
|
-
const wranglerConfig = parse(fs.readFileSync(wranglerConfigPath, "utf-8"));
|
|
37
|
-
|
|
38
|
-
const databaseName = wranglerConfig.d1_databases?.[0]?.database_name;
|
|
39
|
-
|
|
40
|
-
if (!databaseName) {
|
|
41
|
-
throw new Error(
|
|
42
|
-
"Could not find database_name in wrangler.jsonc d1_databases configuration",
|
|
43
|
-
);
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
// Execute the command to initialize the local database
|
|
47
|
-
console.log(`Initializing local D1 database: ${databaseName}...`);
|
|
48
|
-
execSync(
|
|
49
|
-
`npx wrangler d1 execute ${databaseName} --local --command "SELECT 1;"`,
|
|
50
|
-
{ stdio: "pipe" },
|
|
51
|
-
);
|
|
52
|
-
|
|
53
|
-
// Try to find the db file again after initialization
|
|
54
|
-
dbFile = findSqliteFile(basePath);
|
|
55
|
-
|
|
56
|
-
if (!dbFile) {
|
|
57
|
-
throw new Error(
|
|
58
|
-
`Failed to initialize local D1 database. The sqlite file was not created.`,
|
|
59
|
-
);
|
|
60
|
-
}
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
return path.resolve(basePath, dbFile);
|
|
64
|
-
}
|
package/src/cloudflare/index.ts
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export { lazyInitForWorkers } from "./lazyInit.js";
|
|
@@ -1,67 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Wraps a factory function in a Proxy to defer initialization until first access.
|
|
3
|
-
* This prevents async operations (Like creating Tanstack DB Collections) from running in Cloudflare Workers' global scope.
|
|
4
|
-
*
|
|
5
|
-
* @param factory - A function that creates and returns the resource.
|
|
6
|
-
* Must be a callback to defer execution; passing the value directly
|
|
7
|
-
* would evaluate it at module load time, triggering the Cloudflare error.
|
|
8
|
-
* @returns A Proxy that lazily initializes the resource on first property access
|
|
9
|
-
*
|
|
10
|
-
* @example
|
|
11
|
-
* ```ts
|
|
12
|
-
* export const myCollection = lazyInitForWorkers(() =>
|
|
13
|
-
* createCollection(queryCollectionOptions({
|
|
14
|
-
* queryKey: ["myData"],
|
|
15
|
-
* queryFn: async () => fetchData(),
|
|
16
|
-
* // ... other options
|
|
17
|
-
* }))
|
|
18
|
-
* );
|
|
19
|
-
* ```
|
|
20
|
-
*/
|
|
21
|
-
export function lazyInitForWorkers<T extends object>(factory: () => T): T {
|
|
22
|
-
// Closure: This variable is captured by getInstance() and the Proxy traps below.
|
|
23
|
-
// It remains in memory as long as the returned Proxy is referenced, enabling singleton behavior.
|
|
24
|
-
let instance: T | null = null;
|
|
25
|
-
|
|
26
|
-
function getInstance() {
|
|
27
|
-
if (!instance) {
|
|
28
|
-
instance = factory();
|
|
29
|
-
}
|
|
30
|
-
return instance;
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
return new Proxy({} as T, {
|
|
34
|
-
get(_, prop) {
|
|
35
|
-
const inst = getInstance();
|
|
36
|
-
const value = inst[prop as keyof T];
|
|
37
|
-
// Bind methods to the instance to preserve `this` context
|
|
38
|
-
return typeof value === "function" ? value.bind(inst) : value;
|
|
39
|
-
},
|
|
40
|
-
set(_, prop, value) {
|
|
41
|
-
const inst = getInstance();
|
|
42
|
-
(inst as any)[prop] = value;
|
|
43
|
-
return true;
|
|
44
|
-
},
|
|
45
|
-
deleteProperty(_, prop) {
|
|
46
|
-
const inst = getInstance();
|
|
47
|
-
delete (inst as any)[prop];
|
|
48
|
-
return true;
|
|
49
|
-
},
|
|
50
|
-
has(_, prop) {
|
|
51
|
-
const inst = getInstance();
|
|
52
|
-
return prop in inst;
|
|
53
|
-
},
|
|
54
|
-
ownKeys(_) {
|
|
55
|
-
const inst = getInstance();
|
|
56
|
-
return Reflect.ownKeys(inst);
|
|
57
|
-
},
|
|
58
|
-
getOwnPropertyDescriptor(_, prop) {
|
|
59
|
-
const inst = getInstance();
|
|
60
|
-
return Reflect.getOwnPropertyDescriptor(inst, prop);
|
|
61
|
-
},
|
|
62
|
-
getPrototypeOf(_) {
|
|
63
|
-
const inst = getInstance();
|
|
64
|
-
return Reflect.getPrototypeOf(inst);
|
|
65
|
-
},
|
|
66
|
-
});
|
|
67
|
-
}
|
|
@@ -1,262 +0,0 @@
|
|
|
1
|
-
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
|
2
|
-
import { fetchGateway, getGatewayUrl } from "./gateway";
|
|
3
|
-
|
|
4
|
-
type TestFetcher = {
|
|
5
|
-
fetch: ReturnType<typeof vi.fn>;
|
|
6
|
-
};
|
|
7
|
-
|
|
8
|
-
type TestEnv = {
|
|
9
|
-
GATEWAY_URL?: string;
|
|
10
|
-
EVERY_APP_GATEWAY?: TestFetcher;
|
|
11
|
-
GATEWAY_APP_API_TOKEN?: string;
|
|
12
|
-
APP_TOKEN?: string;
|
|
13
|
-
};
|
|
14
|
-
|
|
15
|
-
describe("gateway server helpers", () => {
|
|
16
|
-
beforeEach(() => {
|
|
17
|
-
vi.restoreAllMocks();
|
|
18
|
-
});
|
|
19
|
-
|
|
20
|
-
afterEach(() => {
|
|
21
|
-
vi.restoreAllMocks();
|
|
22
|
-
});
|
|
23
|
-
|
|
24
|
-
it("returns gateway URL and throws when missing", () => {
|
|
25
|
-
expect(getGatewayUrl({ GATEWAY_URL: "https://gateway.example.com" })).toBe(
|
|
26
|
-
"https://gateway.example.com",
|
|
27
|
-
);
|
|
28
|
-
|
|
29
|
-
expect(() => getGatewayUrl({} as TestEnv)).toThrow(
|
|
30
|
-
"GATEWAY_URL is required",
|
|
31
|
-
);
|
|
32
|
-
});
|
|
33
|
-
|
|
34
|
-
it("fetches via HTTP when service binding is unavailable", async () => {
|
|
35
|
-
const fetchMock = vi
|
|
36
|
-
.spyOn(globalThis, "fetch")
|
|
37
|
-
.mockResolvedValue(new Response("ok", { status: 200 }));
|
|
38
|
-
|
|
39
|
-
const env: TestEnv = {
|
|
40
|
-
GATEWAY_URL: "https://gateway.example.com",
|
|
41
|
-
GATEWAY_APP_API_TOKEN: "eat_test_token",
|
|
42
|
-
};
|
|
43
|
-
|
|
44
|
-
await fetchGateway({
|
|
45
|
-
env,
|
|
46
|
-
url: "/api/ai/openai/v1/responses?stream=true",
|
|
47
|
-
init: { method: "POST" },
|
|
48
|
-
});
|
|
49
|
-
|
|
50
|
-
expect(fetchMock).toHaveBeenCalledTimes(1);
|
|
51
|
-
const [requestArg] = fetchMock.mock.calls[0];
|
|
52
|
-
const request = requestArg as Request;
|
|
53
|
-
|
|
54
|
-
expect(request.url).toBe(
|
|
55
|
-
"https://gateway.example.com/api/ai/openai/v1/responses?stream=true",
|
|
56
|
-
);
|
|
57
|
-
});
|
|
58
|
-
|
|
59
|
-
it("throws when absolute URL points to non-gateway origin", async () => {
|
|
60
|
-
const fetchMock = vi
|
|
61
|
-
.spyOn(globalThis, "fetch")
|
|
62
|
-
.mockResolvedValue(new Response("ok", { status: 200 }));
|
|
63
|
-
|
|
64
|
-
const env: TestEnv = {
|
|
65
|
-
GATEWAY_URL: "https://gateway.example.com",
|
|
66
|
-
GATEWAY_APP_API_TOKEN: "eat_test_token",
|
|
67
|
-
};
|
|
68
|
-
|
|
69
|
-
await expect(
|
|
70
|
-
fetchGateway({
|
|
71
|
-
env,
|
|
72
|
-
url: "https://evil.example.com/api/ai/openai/v1/responses",
|
|
73
|
-
init: { method: "POST" },
|
|
74
|
-
}),
|
|
75
|
-
).rejects.toThrow(
|
|
76
|
-
"Refusing to send gateway token to non-gateway origin: https://evil.example.com",
|
|
77
|
-
);
|
|
78
|
-
|
|
79
|
-
expect(fetchMock).not.toHaveBeenCalled();
|
|
80
|
-
});
|
|
81
|
-
|
|
82
|
-
it("allows absolute URL when it matches gateway origin", async () => {
|
|
83
|
-
const fetchMock = vi
|
|
84
|
-
.spyOn(globalThis, "fetch")
|
|
85
|
-
.mockResolvedValue(new Response("ok", { status: 200 }));
|
|
86
|
-
|
|
87
|
-
const env: TestEnv = {
|
|
88
|
-
GATEWAY_URL: "https://gateway.example.com",
|
|
89
|
-
GATEWAY_APP_API_TOKEN: "eat_test_token",
|
|
90
|
-
};
|
|
91
|
-
|
|
92
|
-
await fetchGateway({
|
|
93
|
-
env,
|
|
94
|
-
url: "https://gateway.example.com/api/ai/openai/v1/responses",
|
|
95
|
-
init: { method: "POST" },
|
|
96
|
-
});
|
|
97
|
-
|
|
98
|
-
expect(fetchMock).toHaveBeenCalledTimes(1);
|
|
99
|
-
const [requestArg] = fetchMock.mock.calls[0];
|
|
100
|
-
const request = requestArg as Request;
|
|
101
|
-
expect(request.url).toBe(
|
|
102
|
-
"https://gateway.example.com/api/ai/openai/v1/responses",
|
|
103
|
-
);
|
|
104
|
-
});
|
|
105
|
-
|
|
106
|
-
it("fetches via service binding when available in production", async () => {
|
|
107
|
-
// Service binding is only used when import.meta.env.PROD is true
|
|
108
|
-
const originalProd = import.meta.env.PROD;
|
|
109
|
-
import.meta.env.PROD = true;
|
|
110
|
-
|
|
111
|
-
try {
|
|
112
|
-
const bindingFetch = vi
|
|
113
|
-
.fn()
|
|
114
|
-
.mockResolvedValue(new Response("ok", { status: 200 }));
|
|
115
|
-
|
|
116
|
-
const env: TestEnv = {
|
|
117
|
-
GATEWAY_URL: "https://gateway.example.com",
|
|
118
|
-
EVERY_APP_GATEWAY: { fetch: bindingFetch },
|
|
119
|
-
GATEWAY_APP_API_TOKEN: "eat_test_token",
|
|
120
|
-
};
|
|
121
|
-
|
|
122
|
-
await fetchGateway({
|
|
123
|
-
env,
|
|
124
|
-
url: "/api/ai/openai/v1/chat/completions",
|
|
125
|
-
init: { method: "POST" },
|
|
126
|
-
});
|
|
127
|
-
|
|
128
|
-
expect(bindingFetch).toHaveBeenCalledTimes(1);
|
|
129
|
-
const [requestArg] = bindingFetch.mock.calls[0];
|
|
130
|
-
const request = requestArg as Request;
|
|
131
|
-
expect(request.url).toBe(
|
|
132
|
-
"http://localhost/api/ai/openai/v1/chat/completions",
|
|
133
|
-
);
|
|
134
|
-
} finally {
|
|
135
|
-
import.meta.env.PROD = originalProd;
|
|
136
|
-
}
|
|
137
|
-
});
|
|
138
|
-
|
|
139
|
-
it("skips service binding in development and uses HTTP fetch", async () => {
|
|
140
|
-
const fetchMock = vi
|
|
141
|
-
.spyOn(globalThis, "fetch")
|
|
142
|
-
.mockResolvedValue(new Response("ok", { status: 200 }));
|
|
143
|
-
|
|
144
|
-
const bindingFetch = vi.fn();
|
|
145
|
-
|
|
146
|
-
const env: TestEnv = {
|
|
147
|
-
GATEWAY_URL: "https://gateway.example.com",
|
|
148
|
-
EVERY_APP_GATEWAY: { fetch: bindingFetch },
|
|
149
|
-
GATEWAY_APP_API_TOKEN: "eat_test_token",
|
|
150
|
-
};
|
|
151
|
-
|
|
152
|
-
await fetchGateway({
|
|
153
|
-
env,
|
|
154
|
-
url: "/api/ai/openai/v1/chat/completions",
|
|
155
|
-
init: { method: "POST" },
|
|
156
|
-
});
|
|
157
|
-
|
|
158
|
-
// In dev, should use HTTP fetch, not service binding
|
|
159
|
-
expect(bindingFetch).not.toHaveBeenCalled();
|
|
160
|
-
expect(fetchMock).toHaveBeenCalledTimes(1);
|
|
161
|
-
});
|
|
162
|
-
|
|
163
|
-
it("always injects app token and strips Authorization header", async () => {
|
|
164
|
-
const fetchMock = vi
|
|
165
|
-
.spyOn(globalThis, "fetch")
|
|
166
|
-
.mockResolvedValue(new Response("ok", { status: 200 }));
|
|
167
|
-
|
|
168
|
-
const env: TestEnv = {
|
|
169
|
-
GATEWAY_URL: "https://gateway.example.com",
|
|
170
|
-
GATEWAY_APP_API_TOKEN: "eat_my_token",
|
|
171
|
-
};
|
|
172
|
-
|
|
173
|
-
await fetchGateway({
|
|
174
|
-
env,
|
|
175
|
-
url: "/api/ai/openai/v1/responses",
|
|
176
|
-
init: {
|
|
177
|
-
method: "POST",
|
|
178
|
-
headers: {
|
|
179
|
-
authorization: "Bearer some-sdk-dummy-value",
|
|
180
|
-
},
|
|
181
|
-
},
|
|
182
|
-
});
|
|
183
|
-
|
|
184
|
-
expect(fetchMock).toHaveBeenCalledTimes(1);
|
|
185
|
-
const [requestArg] = fetchMock.mock.calls[0];
|
|
186
|
-
const request = requestArg as Request;
|
|
187
|
-
|
|
188
|
-
expect(request.headers.get("x-every-app-token")).toBe("eat_my_token");
|
|
189
|
-
expect(request.headers.get("authorization")).toBeNull();
|
|
190
|
-
});
|
|
191
|
-
|
|
192
|
-
it("throws when app token is missing", async () => {
|
|
193
|
-
const env: TestEnv = {
|
|
194
|
-
GATEWAY_URL: "https://gateway.example.com",
|
|
195
|
-
};
|
|
196
|
-
|
|
197
|
-
await expect(
|
|
198
|
-
fetchGateway({
|
|
199
|
-
env,
|
|
200
|
-
url: "/api/ai/openai/v1/responses",
|
|
201
|
-
}),
|
|
202
|
-
).rejects.toThrow("GATEWAY_APP_API_TOKEN is required");
|
|
203
|
-
});
|
|
204
|
-
|
|
205
|
-
it("supports legacy APP_TOKEN env variable", async () => {
|
|
206
|
-
const fetchMock = vi
|
|
207
|
-
.spyOn(globalThis, "fetch")
|
|
208
|
-
.mockResolvedValue(new Response("ok", { status: 200 }));
|
|
209
|
-
|
|
210
|
-
const env: TestEnv = {
|
|
211
|
-
GATEWAY_URL: "https://gateway.example.com",
|
|
212
|
-
APP_TOKEN: "eat_legacy_token",
|
|
213
|
-
};
|
|
214
|
-
|
|
215
|
-
await fetchGateway({
|
|
216
|
-
env,
|
|
217
|
-
url: "/api/ai/openai/v1/responses",
|
|
218
|
-
init: { method: "POST" },
|
|
219
|
-
});
|
|
220
|
-
|
|
221
|
-
expect(fetchMock).toHaveBeenCalledTimes(1);
|
|
222
|
-
const [requestArg] = fetchMock.mock.calls[0];
|
|
223
|
-
const request = requestArg as Request;
|
|
224
|
-
|
|
225
|
-
expect(request.headers.get("x-every-app-token")).toBe("eat_legacy_token");
|
|
226
|
-
expect(request.headers.get("authorization")).toBeNull();
|
|
227
|
-
});
|
|
228
|
-
|
|
229
|
-
it("supports Request input and preserves method/body", async () => {
|
|
230
|
-
const fetchMock = vi
|
|
231
|
-
.spyOn(globalThis, "fetch")
|
|
232
|
-
.mockResolvedValue(new Response("ok", { status: 200 }));
|
|
233
|
-
|
|
234
|
-
const env: TestEnv = {
|
|
235
|
-
GATEWAY_URL: "https://gateway.example.com",
|
|
236
|
-
GATEWAY_APP_API_TOKEN: "eat_test_token",
|
|
237
|
-
};
|
|
238
|
-
|
|
239
|
-
const sourceRequest = new Request(
|
|
240
|
-
"https://gateway.example.com/api/ai/openai/v1/responses",
|
|
241
|
-
{
|
|
242
|
-
method: "POST",
|
|
243
|
-
body: JSON.stringify({ model: "gpt-5.2" }),
|
|
244
|
-
headers: { "content-type": "application/json" },
|
|
245
|
-
},
|
|
246
|
-
);
|
|
247
|
-
|
|
248
|
-
await fetchGateway({
|
|
249
|
-
env,
|
|
250
|
-
url: sourceRequest,
|
|
251
|
-
});
|
|
252
|
-
|
|
253
|
-
expect(fetchMock).toHaveBeenCalledTimes(1);
|
|
254
|
-
const [requestArg] = fetchMock.mock.calls[0];
|
|
255
|
-
const request = requestArg as Request;
|
|
256
|
-
expect(request.url).toBe(
|
|
257
|
-
"https://gateway.example.com/api/ai/openai/v1/responses",
|
|
258
|
-
);
|
|
259
|
-
expect(request.method).toBe("POST");
|
|
260
|
-
expect(request.headers.get("content-type")).toBe("application/json");
|
|
261
|
-
});
|
|
262
|
-
});
|
|
@@ -1,114 +0,0 @@
|
|
|
1
|
-
const SERVICE_BINDING_ORIGIN = "http://localhost";
|
|
2
|
-
const APP_TOKEN_HEADER = "x-every-app-token";
|
|
3
|
-
|
|
4
|
-
interface GatewayFetcher {
|
|
5
|
-
fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response>;
|
|
6
|
-
}
|
|
7
|
-
|
|
8
|
-
interface GatewayEnv {
|
|
9
|
-
GATEWAY_URL?: string;
|
|
10
|
-
EVERY_APP_GATEWAY?: GatewayFetcher;
|
|
11
|
-
GATEWAY_APP_API_TOKEN?: string;
|
|
12
|
-
APP_TOKEN?: string;
|
|
13
|
-
}
|
|
14
|
-
|
|
15
|
-
interface FetchGatewayOptions {
|
|
16
|
-
env: GatewayEnv;
|
|
17
|
-
/** The URL, path, or Request to send to the gateway. Typically the full URL
|
|
18
|
-
* passed by a provider SDK's custom `fetch` override. */
|
|
19
|
-
url: string | URL | Request;
|
|
20
|
-
/** Standard `RequestInit` (method, headers, body, etc.) from the provider SDK. */
|
|
21
|
-
init?: RequestInit;
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
export function getGatewayUrl(env: GatewayEnv): string {
|
|
25
|
-
const gatewayUrl = env.GATEWAY_URL?.trim();
|
|
26
|
-
if (!gatewayUrl) {
|
|
27
|
-
throw new Error("GATEWAY_URL is required");
|
|
28
|
-
}
|
|
29
|
-
return gatewayUrl;
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
/**
|
|
33
|
-
* Fetch from the gateway proxy, authenticating with the app token.
|
|
34
|
-
*
|
|
35
|
-
* - Strips any existing `Authorization` header (the gateway only accepts
|
|
36
|
-
* app token auth via `x-every-app-token`).
|
|
37
|
-
* - Requires `GATEWAY_APP_API_TOKEN` (or legacy `APP_TOKEN`) in the env.
|
|
38
|
-
* - Routes via service binding in production, falls back to HTTP in dev.
|
|
39
|
-
*/
|
|
40
|
-
export async function fetchGateway({
|
|
41
|
-
env,
|
|
42
|
-
url,
|
|
43
|
-
init,
|
|
44
|
-
}: FetchGatewayOptions): Promise<Response> {
|
|
45
|
-
const gatewayBaseUrl = getGatewayUrl(env);
|
|
46
|
-
const resolvedRequest = toRequest(url, init, gatewayBaseUrl);
|
|
47
|
-
const authenticatedRequest = applyAppTokenAuth(resolvedRequest, env);
|
|
48
|
-
|
|
49
|
-
// Use service binding in production for zero-latency internal routing.
|
|
50
|
-
// In local dev wrangler still exposes the binding object, but the target
|
|
51
|
-
// service usually isn't running locally, so we skip it and use HTTP fetch.
|
|
52
|
-
if (import.meta.env.PROD && env.EVERY_APP_GATEWAY) {
|
|
53
|
-
const url = new URL(authenticatedRequest.url);
|
|
54
|
-
const bindingUrl = `${SERVICE_BINDING_ORIGIN}${url.pathname}${url.search}`;
|
|
55
|
-
const bindingRequest = new Request(bindingUrl, authenticatedRequest);
|
|
56
|
-
return env.EVERY_APP_GATEWAY.fetch(bindingRequest);
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
// HTTP fetch – used in local dev, or as a fallback when no binding exists
|
|
60
|
-
return fetch(authenticatedRequest);
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
function applyAppTokenAuth(request: Request, env: GatewayEnv): Request {
|
|
64
|
-
const gatewayOrigin = new URL(getGatewayUrl(env)).origin;
|
|
65
|
-
const requestOrigin = new URL(request.url).origin;
|
|
66
|
-
if (requestOrigin !== gatewayOrigin) {
|
|
67
|
-
throw new Error(
|
|
68
|
-
`Refusing to send gateway token to non-gateway origin: ${requestOrigin}`,
|
|
69
|
-
);
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
const appToken = getGatewayAppApiToken(env);
|
|
73
|
-
if (!appToken) {
|
|
74
|
-
throw new Error(
|
|
75
|
-
"GATEWAY_APP_API_TOKEN is required. Run `npx everyapp app deploy` to provision one.",
|
|
76
|
-
);
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
const headers = new Headers(request.headers);
|
|
80
|
-
headers.delete("authorization");
|
|
81
|
-
headers.set(APP_TOKEN_HEADER, appToken);
|
|
82
|
-
return new Request(request, { headers });
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
function getGatewayAppApiToken(env: GatewayEnv): string | null {
|
|
86
|
-
const configuredToken = env.GATEWAY_APP_API_TOKEN?.trim();
|
|
87
|
-
if (configuredToken) {
|
|
88
|
-
return configuredToken;
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
const legacyToken = env.APP_TOKEN?.trim();
|
|
92
|
-
return legacyToken || null;
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
function toRequest(
|
|
96
|
-
input: RequestInfo | URL,
|
|
97
|
-
init?: RequestInit,
|
|
98
|
-
baseUrl?: string,
|
|
99
|
-
): Request {
|
|
100
|
-
if (input instanceof Request) {
|
|
101
|
-
return init ? new Request(input, init) : input;
|
|
102
|
-
}
|
|
103
|
-
|
|
104
|
-
if (input instanceof URL) {
|
|
105
|
-
return new Request(input.toString(), init);
|
|
106
|
-
}
|
|
107
|
-
|
|
108
|
-
if (typeof input === "string" && baseUrl && !/^https?:\/\//i.test(input)) {
|
|
109
|
-
const normalizedPath = input.startsWith("/") ? input : `/${input}`;
|
|
110
|
-
return new Request(new URL(normalizedPath, baseUrl).toString(), init);
|
|
111
|
-
}
|
|
112
|
-
|
|
113
|
-
return new Request(input, init);
|
|
114
|
-
}
|
|
@@ -1,54 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
BYPASS_GATEWAY_LOCAL_ONLY_TOKEN,
|
|
3
|
-
isBypassGatewayLocalOnlyClient,
|
|
4
|
-
} from "../shared/bypassGatewayLocalOnly.js";
|
|
5
|
-
|
|
6
|
-
interface SessionManager {
|
|
7
|
-
getToken(): Promise<string>;
|
|
8
|
-
}
|
|
9
|
-
|
|
10
|
-
interface WindowWithSessionManager extends Window {
|
|
11
|
-
__embeddedSessionManager?: SessionManager;
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
/**
|
|
15
|
-
* Gets the current session token from the embedded session manager
|
|
16
|
-
*/
|
|
17
|
-
export async function getSessionToken(): Promise<string> {
|
|
18
|
-
if (isBypassGatewayLocalOnlyClient()) {
|
|
19
|
-
return BYPASS_GATEWAY_LOCAL_ONLY_TOKEN;
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
const windowWithSession = window as WindowWithSessionManager;
|
|
23
|
-
const sessionManager = windowWithSession.__embeddedSessionManager;
|
|
24
|
-
|
|
25
|
-
if (!sessionManager) {
|
|
26
|
-
throw new Error("Session manager not available");
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
const token = await sessionManager.getToken();
|
|
30
|
-
|
|
31
|
-
if (!token) {
|
|
32
|
-
throw new Error("No token available");
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
return token;
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
/**
|
|
39
|
-
* Performs a fetch request with the authorization header automatically added
|
|
40
|
-
*/
|
|
41
|
-
export async function authenticatedFetch(
|
|
42
|
-
input: RequestInfo | URL,
|
|
43
|
-
init?: RequestInit,
|
|
44
|
-
): Promise<Response> {
|
|
45
|
-
const token = await getSessionToken();
|
|
46
|
-
|
|
47
|
-
const headers = new Headers(init?.headers);
|
|
48
|
-
headers.set("Authorization", `Bearer ${token}`);
|
|
49
|
-
|
|
50
|
-
return fetch(input, {
|
|
51
|
-
...init,
|
|
52
|
-
headers,
|
|
53
|
-
});
|
|
54
|
-
}
|
package/src/core/index.ts
DELETED
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
export {
|
|
2
|
-
SessionManager,
|
|
3
|
-
isRunningInIframe,
|
|
4
|
-
isRunningInReactNativeWebView,
|
|
5
|
-
detectEnvironment,
|
|
6
|
-
} from "./sessionManager.js";
|
|
7
|
-
export type {
|
|
8
|
-
SessionManagerConfig,
|
|
9
|
-
EmbeddedEnvironment,
|
|
10
|
-
} from "./sessionManager.js";
|
|
11
|
-
|
|
12
|
-
export { authenticatedFetch, getSessionToken } from "./authenticatedFetch.js";
|